@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
@@ -1,5 +1,9 @@
1
+ import { signMessage } from '@oxyhq/protocol';
1
2
  import { KeyManager } from '../crypto/keyManager.js';
2
3
  import { SignatureService } from '../crypto/signatureService.js';
4
+ import { RecoveryPhraseService } from '../crypto/recoveryPhrase.js';
5
+ import { isWeb } from '../utils/platform.js';
6
+ import { logger } from '../logger/index.js';
3
7
  import { CACHE_TIMES } from './mixinHelpers.js';
4
8
  /**
5
9
  * Registrable apex the Oxy DID method is anchored on. A user's DID is
@@ -137,6 +141,168 @@ export function OxyServicesIdentityMixin(Base) {
137
141
  throw this.handleError(error);
138
142
  }
139
143
  }
144
+ /**
145
+ * Rotate the account's identity key: derive a brand-new keypair, prove
146
+ * control of the CURRENT key, and have the server ATOMICALLY replace the old
147
+ * key with the new one.
148
+ *
149
+ * The rotation is an atomic REPLACE on the server (never remove-then-add), so
150
+ * it never passes through a zero-auth-method state and is independent of the
151
+ * unlink guards. Because control of the current key is PROVEN (from
152
+ * SecureStore in `'device'` mode, or a recovery-phrase re-derivation in
153
+ * `'phrase'` mode), even the LAST remaining credential can be replaced.
154
+ *
155
+ * Ordering (safety-critical): the new key is persisted on-device ONLY AFTER
156
+ * the server confirms the swap. Persisting earlier would clobber the local
157
+ * key while the server still trusts the old one, locking the device out.
158
+ *
159
+ * Ambiguous-network-failure guard: if the `complete` response is lost
160
+ * (request sent, no reply), the swap may already have applied server-side.
161
+ * Before surfacing the error we reconcile against the derived DID document —
162
+ * if it already advertises the new key, the rotation is treated as done.
163
+ *
164
+ * NOTE: the UI is responsible for showing `newPhrase` to the user. For a
165
+ * "show-phrase-first" flow, derive the identity up front via
166
+ * {@link RecoveryPhraseService.derivePendingIdentity}, display it, then pass
167
+ * it back as `options.pendingIdentity` so the SAME identity is committed.
168
+ *
169
+ * @throws when no user is authenticated, when `proof: 'phrase'` is given
170
+ * without a `phrase`, when `proof: 'device'` runs with no on-device key,
171
+ * or when the rotation does not complete.
172
+ */
173
+ async rotateKey(options) {
174
+ try {
175
+ const userId = this.getCurrentUserId();
176
+ if (!userId) {
177
+ throw new Error('No authenticated user — sign in before rotating your key.');
178
+ }
179
+ // 1. The NEW identity (in memory only). The UI may pre-derive + pre-show
180
+ // it and pass it back here so the phrase shown === the phrase committed.
181
+ const pending = options.pendingIdentity ?? (await RecoveryPhraseService.derivePendingIdentity());
182
+ const newPublicKey = pending.publicKey;
183
+ // 2. Resolve the OLD signing capability from the chosen proof mode.
184
+ let oldPublicKey;
185
+ let signWithOldKey;
186
+ if (options.proof === 'phrase') {
187
+ const phrase = options.phrase?.trim();
188
+ if (!phrase) {
189
+ throw new Error('A recovery phrase is required for phrase-proof rotation.');
190
+ }
191
+ const oldPrivateKey = await RecoveryPhraseService.derivePrivateKeyFromPhrase(phrase);
192
+ oldPublicKey = KeyManager.derivePublicKey(oldPrivateKey);
193
+ signWithOldKey = (message) => signMessage(message, oldPrivateKey);
194
+ }
195
+ else {
196
+ const currentPublicKey = await KeyManager.getPublicKey();
197
+ if (!currentPublicKey) {
198
+ throw new Error('No on-device identity found. Use the recovery-phrase option to rotate your key.');
199
+ }
200
+ oldPublicKey = currentPublicKey;
201
+ signWithOldKey = (message) => SignatureService.sign(message);
202
+ }
203
+ // 3. Request a single-use rotate_key challenge (bearer).
204
+ const { challenge } = await this.makeRequest('POST', '/auth/rotate/challenge', undefined, { cache: false });
205
+ // 4. Sign the rotation proofs. The OLD key proves control of the key being
206
+ // replaced; the NEW key proves possession of the key being rotated in
207
+ // (so the server never accepts a re-encoding of a key the caller does
208
+ // not control). Both signed byte strings MUST match the server's
209
+ // reconstruction exactly (this key order). The old key is canonicalized
210
+ // so legacy compressed encodings in Mongo still verify.
211
+ const timestamp = Date.now();
212
+ const canonicalOldPublicKey = KeyManager.canonicalPublicKey(oldPublicKey);
213
+ const message = JSON.stringify({
214
+ action: 'rotate_key',
215
+ userId,
216
+ oldPublicKey: canonicalOldPublicKey,
217
+ newPublicKey,
218
+ challenge,
219
+ timestamp,
220
+ });
221
+ const signature = await signWithOldKey(message);
222
+ const newKeyMessage = JSON.stringify({
223
+ action: 'rotate_key_new',
224
+ userId,
225
+ newPublicKey,
226
+ challenge,
227
+ timestamp,
228
+ });
229
+ const newKeyProof = await signMessage(newKeyMessage, pending.privateKey);
230
+ // 5. Complete the rotation. On an AMBIGUOUS failure, reconcile against the
231
+ // DID before deciding the rotation failed.
232
+ let applied = false;
233
+ try {
234
+ const result = await this.makeRequest('POST', '/auth/rotate/complete', {
235
+ newPublicKey,
236
+ challenge,
237
+ signature,
238
+ newKeyProof,
239
+ timestamp,
240
+ ...(options.signOutEverywhere ? { signOutEverywhere: true } : {}),
241
+ }, { cache: false });
242
+ applied = result.success && result.publicKey.toLowerCase() === newPublicKey.toLowerCase();
243
+ }
244
+ catch (error) {
245
+ const reconciled = await this._rotationAlreadyApplied(userId, newPublicKey);
246
+ if (!reconciled) {
247
+ throw error;
248
+ }
249
+ applied = true;
250
+ }
251
+ if (!applied) {
252
+ throw new Error('Key rotation did not complete — your previous key is unchanged.');
253
+ }
254
+ // 6. ONLY after the server confirms the swap, persist the new key locally,
255
+ // overwriting the old one. `importKeyPair({ overwrite: true })` uses the
256
+ // atomic persist path (backs the previous key up first). Native-only —
257
+ // on web the key never lived in SecureStore, so there is nothing to
258
+ // persist locally.
259
+ //
260
+ // If this local write fails the server key is ALREADY the new one, so
261
+ // we must NOT throw and swallow the phrase — the caller needs it to
262
+ // re-import the now-live key. Surface the result with
263
+ // `localPersistFailed: true` (mirrors the pendingIdentity
264
+ // show-phrase-first path, where the caller already holds the phrase).
265
+ let localPersistFailed = false;
266
+ if (!isWeb()) {
267
+ try {
268
+ await KeyManager.importKeyPair(pending.privateKey, { overwrite: true });
269
+ }
270
+ catch (persistError) {
271
+ localPersistFailed = true;
272
+ 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);
273
+ }
274
+ }
275
+ this._invalidateIdentityCaches(userId);
276
+ return localPersistFailed
277
+ ? { newPublicKey, newPhrase: pending.phrase, words: pending.words, localPersistFailed: true }
278
+ : { newPublicKey, newPhrase: pending.phrase, words: pending.words };
279
+ }
280
+ catch (error) {
281
+ throw this.handleError(error);
282
+ }
283
+ }
284
+ /**
285
+ * Reconciliation probe for the rotation ambiguous-failure guard: fetch the
286
+ * account's derived DID document (uncached) and report whether it already
287
+ * advertises `newPublicKey` as a verification method — i.e. whether the swap
288
+ * already landed server-side. A failed probe returns `false` (unconfirmed),
289
+ * so the caller surfaces the original network error.
290
+ *
291
+ * Uses the DID document rather than `GET /auth/methods` because the latter
292
+ * intentionally does NOT expose raw public keys, whereas the DID's
293
+ * `verificationMethod[].publicKeyHex` is derived live from the account's
294
+ * current key — so it reflects a completed rotation immediately.
295
+ *
296
+ * Internal helper (leading underscore); public rather than `private` for the
297
+ * same TS4094 reason as {@link _invalidateIdentityCaches}.
298
+ */
299
+ async _rotationAlreadyApplied(userId, newPublicKey) {
300
+ return this.makeRequest('GET', `/u/${encodeURIComponent(userId)}/did.json`, undefined, { cache: false })
301
+ .then((doc) => doc.verificationMethod.some((vm) => 'publicKeyHex' in vm &&
302
+ typeof vm.publicKeyHex === 'string' &&
303
+ vm.publicKeyHex.toLowerCase() === newPublicKey.toLowerCase()))
304
+ .catch(() => false);
305
+ }
140
306
  /**
141
307
  * Sign a record with the on-device identity key, WITHOUT publishing it.
142
308
  * The subject is the current user's DID. NATIVE-ONLY (requires a stored
@@ -0,0 +1,158 @@
1
+ import { KeyManager, IdentityAlreadyExistsError } from '../crypto/keyManager.js';
2
+ import { RecoveryPhraseService, BACKUP_KDF_ENCRYPTION_INFO } from '../crypto/recoveryPhrase.js';
3
+ import { encryptAead, decryptAead } from '../crypto/aead.js';
4
+ /** Envelope/KDF version — bump only on a breaking scheme change. */
5
+ const BACKUP_ENVELOPE_VERSION = 1;
6
+ /** The AEAD the backup is sealed with. Pinned so a mismatched decryptor fails loudly. */
7
+ const BACKUP_ALGORITHM = 'xchacha20poly1305';
8
+ /**
9
+ * Length (hex chars) of the public-key HINT stored/echoed with a backup — enough
10
+ * to let the owner recognise WHICH identity a backup belongs to, but only a
11
+ * prefix (the full key is public anyway; a prefix keeps the record minimal).
12
+ */
13
+ const PUBLIC_KEY_HINT_LENGTH = 16;
14
+ /** Encode bytes as lowercase hex (cross-platform, no Buffer dependency). */
15
+ function toHex(bytes) {
16
+ let out = '';
17
+ for (let i = 0; i < bytes.length; i += 1) {
18
+ out += bytes[i].toString(16).padStart(2, '0');
19
+ }
20
+ return out;
21
+ }
22
+ /** Decode a lowercase/uppercase hex string to bytes. Throws on malformed input. */
23
+ function fromHex(hex) {
24
+ if (hex.length % 2 !== 0 || /[^0-9a-fA-F]/.test(hex)) {
25
+ throw new Error('Malformed hex in encrypted backup envelope.');
26
+ }
27
+ const out = new Uint8Array(hex.length / 2);
28
+ for (let i = 0; i < out.length; i += 1) {
29
+ out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
30
+ }
31
+ return out;
32
+ }
33
+ /**
34
+ * The AEAD associated data binds the ciphertext to its `{version, publicKeyHint}`
35
+ * context: the exact bytes must be reproduced at decrypt time, so a mismatched
36
+ * version or hint (e.g. an envelope re-stamped by a tamperer) fails the
37
+ * Poly1305 check. Deterministic: both sides build the SAME object literal, so
38
+ * `JSON.stringify` yields identical bytes.
39
+ */
40
+ function buildBackupAad(version, publicKeyHint) {
41
+ return new TextEncoder().encode(JSON.stringify({ version, publicKeyHint }));
42
+ }
43
+ export function OxyServicesIdentityBackupMixin(Base) {
44
+ return class extends Base {
45
+ constructor(...args) {
46
+ super(...args);
47
+ }
48
+ /**
49
+ * Derive the backup key material from the recovery phrase, encrypt the
50
+ * identity's `{privateKey, publicKey, createdAt}` with it, and upload the
51
+ * ciphertext + raw `lookupId` (`POST /identity/backup`, bearer). The server
52
+ * stores only `sha256(lookupId)` + the ciphertext. Idempotent per user: a
53
+ * re-upload REPLACES the prior backup (upsert by user id).
54
+ *
55
+ * The identity is derived from the PHRASE (not read from SecureStore), so
56
+ * this works cross-platform and does not require an on-device key.
57
+ *
58
+ * @param phrase - The identity's BIP-39 recovery phrase.
59
+ * @returns The post-write backup status (`{ exists: true, publicKeyHint, createdAt }`).
60
+ */
61
+ async createEncryptedBackup(phrase) {
62
+ try {
63
+ const { backupKey, lookupId } = await RecoveryPhraseService.deriveBackupMaterial(phrase);
64
+ const privateKey = await RecoveryPhraseService.derivePrivateKeyFromPhrase(phrase);
65
+ const publicKey = KeyManager.derivePublicKey(privateKey);
66
+ const createdAt = new Date().toISOString();
67
+ const publicKeyHint = publicKey.slice(0, PUBLIC_KEY_HINT_LENGTH);
68
+ const payload = { privateKey, publicKey, createdAt };
69
+ const plaintext = new TextEncoder().encode(JSON.stringify(payload));
70
+ const aad = buildBackupAad(BACKUP_ENVELOPE_VERSION, publicKeyHint);
71
+ const { nonce, ciphertext } = encryptAead(backupKey, plaintext, aad);
72
+ const body = {
73
+ version: BACKUP_ENVELOPE_VERSION,
74
+ algorithm: BACKUP_ALGORITHM,
75
+ kdfInfo: BACKUP_KDF_ENCRYPTION_INFO,
76
+ nonce: toHex(nonce),
77
+ ciphertext: toHex(ciphertext),
78
+ publicKeyHint,
79
+ createdAt,
80
+ lookupId,
81
+ };
82
+ return await this.makeRequest('POST', '/identity/backup', body, { cache: false });
83
+ }
84
+ catch (error) {
85
+ throw this.handleError(error);
86
+ }
87
+ }
88
+ /**
89
+ * Whether the authenticated user has a stored encrypted backup, plus the
90
+ * non-sensitive hint + timestamp when one exists (`GET /identity/backup/status`,
91
+ * bearer). Returns no ciphertext and no locator.
92
+ */
93
+ async getBackupStatus() {
94
+ try {
95
+ return await this.makeRequest('GET', '/identity/backup/status', undefined, { cache: false });
96
+ }
97
+ catch (error) {
98
+ throw this.handleError(error);
99
+ }
100
+ }
101
+ /**
102
+ * Delete the authenticated user's stored backup (`DELETE /identity/backup`,
103
+ * bearer). Idempotent — deleting a non-existent backup still succeeds.
104
+ */
105
+ async deleteBackup() {
106
+ try {
107
+ return await this.makeRequest('DELETE', '/identity/backup', undefined, { cache: false });
108
+ }
109
+ catch (error) {
110
+ throw this.handleError(error);
111
+ }
112
+ }
113
+ /**
114
+ * Restore an identity from its encrypted off-device backup using ONLY the
115
+ * recovery phrase: re-derive `{backupKey, lookupId}`, fetch the envelope by
116
+ * `lookupId` (`GET /identity/backup/:lookupId`, PUBLIC — the 256-bit locator
117
+ * is the protection), decrypt + authenticate locally, then persist the key.
118
+ *
119
+ * NATIVE-ONLY persistence: `KeyManager.importKeyPair` throws on web. It also
120
+ * refuses to clobber a DIFFERENT existing on-device identity unless
121
+ * `overwrite: true` — the {@link import('../crypto/keyManager').IdentityAlreadyExistsError}
122
+ * propagates to the caller (never swallowed) so the UI can confirm before
123
+ * overwriting.
124
+ *
125
+ * @param phrase - The identity's BIP-39 recovery phrase.
126
+ * @param options.overwrite - Replace a different existing on-device identity.
127
+ * @returns The restored identity's public key.
128
+ * @throws if the phrase is invalid, no backup exists (404), the ciphertext
129
+ * fails authentication (tamper), or an existing identity blocks the import.
130
+ */
131
+ async restoreFromEncryptedBackup(phrase, options) {
132
+ try {
133
+ const { backupKey, lookupId } = await RecoveryPhraseService.deriveBackupMaterial(phrase);
134
+ const envelope = await this.makeRequest('GET', `/identity/backup/${encodeURIComponent(lookupId)}`, undefined, { cache: false });
135
+ if (envelope.algorithm !== BACKUP_ALGORITHM) {
136
+ throw new Error(`Unsupported backup algorithm: ${envelope.algorithm}`);
137
+ }
138
+ const aad = buildBackupAad(envelope.version, envelope.publicKeyHint);
139
+ const plaintext = decryptAead(backupKey, fromHex(envelope.nonce), fromHex(envelope.ciphertext), aad);
140
+ const payload = JSON.parse(new TextDecoder().decode(plaintext));
141
+ // Persist the recovered key. Native-only; refuses to clobber a different
142
+ // identity unless overwrite — the IdentityAlreadyExistsError propagates.
143
+ return await KeyManager.importKeyPair(payload.privateKey, {
144
+ overwrite: options?.overwrite === true,
145
+ });
146
+ }
147
+ catch (error) {
148
+ // Preserve the typed "an identity already exists" signal so the caller
149
+ // can prompt for overwrite. `handleError` would flatten it to a generic
150
+ // Error and lose that discrimination.
151
+ if (error instanceof IdentityAlreadyExistsError) {
152
+ throw error;
153
+ }
154
+ throw this.handleError(error);
155
+ }
156
+ }
157
+ };
158
+ }
@@ -10,6 +10,12 @@ import { extractErrorStatus } from '../utils/errorUtils.js';
10
10
  * server-side batch cap; larger inputs are split into multiple chunked calls.
11
11
  */
12
12
  const USERS_BY_IDS_CHUNK_SIZE = 100;
13
+ /**
14
+ * Maximum number of ids sent per `POST /users/follow-status/bulk` request.
15
+ * Matches the server-side `MAX_BULK_FOLLOW` cap; larger inputs are split into
16
+ * multiple chunked calls whose result maps are merged.
17
+ */
18
+ const FOLLOW_STATUS_CHUNK_SIZE = 200;
13
19
  export function OxyServicesUserMixin(Base) {
14
20
  return class extends Base {
15
21
  constructor(...args) {
@@ -601,6 +607,43 @@ export function OxyServicesUserMixin(Base) {
601
607
  throw this.handleError(error);
602
608
  }
603
609
  }
610
+ /**
611
+ * Resolve the viewer's follow status for MANY users in one round-trip per
612
+ * chunk. Built for list UIs (a page of `FollowButton`s) that would otherwise
613
+ * fire one `getFollowStatus` per button (the classic N+1).
614
+ *
615
+ * Ids are deduplicated and validated (empty/blank ids dropped), split into
616
+ * chunks of {@link FOLLOW_STATUS_CHUNK_SIZE} (the server's bulk cap), and
617
+ * POSTed to `/users/follow-status/bulk` as `{ userIds }`. The per-chunk
618
+ * `{ statuses }` maps are merged into one `Record<string, boolean>` covering
619
+ * every requested id — ids the viewer does not follow come back `false`.
620
+ *
621
+ * Uncached (`{ cache: false }`): the UI store owns follow-status freshness
622
+ * and writes optimistically on every mutation, so an SDK cache here would
623
+ * serve a stale status right after a follow/unfollow. An empty/whitespace-
624
+ * only input resolves immediately with `{}` and performs no network call.
625
+ */
626
+ async getFollowStatuses(userIds) {
627
+ const uniqueIds = Array.from(new Set(userIds.filter((id) => typeof id === 'string' && id.trim().length > 0)));
628
+ if (uniqueIds.length === 0) {
629
+ return {};
630
+ }
631
+ const chunks = [];
632
+ for (let i = 0; i < uniqueIds.length; i += FOLLOW_STATUS_CHUNK_SIZE) {
633
+ chunks.push(uniqueIds.slice(i, i + FOLLOW_STATUS_CHUNK_SIZE));
634
+ }
635
+ try {
636
+ const responses = await Promise.all(chunks.map((chunk) => this.makeRequest('POST', '/users/follow-status/bulk', { userIds: chunk }, { cache: false })));
637
+ const merged = {};
638
+ for (const response of responses) {
639
+ Object.assign(merged, response?.statuses ?? {});
640
+ }
641
+ return merged;
642
+ }
643
+ catch (error) {
644
+ throw this.handleError(error);
645
+ }
646
+ }
604
647
  /**
605
648
  * Get user followers
606
649
  */
@@ -8,6 +8,7 @@ import { OxyServicesBase } from '../OxyServices.base.js';
8
8
  import { OxyServicesAuthMixin } from './OxyServices.auth.js';
9
9
  import { OxyServicesUserMixin } from './OxyServices.user.js';
10
10
  import { OxyServicesIdentityMixin } from './OxyServices.identity.js';
11
+ import { OxyServicesIdentityBackupMixin } from './OxyServices.identityBackup.js';
11
12
  import { OxyServicesPrivacyMixin } from './OxyServices.privacy.js';
12
13
  import { OxyServicesLanguageMixin } from './OxyServices.language.js';
13
14
  import { OxyServicesPaymentMixin } from './OxyServices.payment.js';
@@ -46,6 +47,9 @@ const MIXIN_PIPELINE = [
46
47
  OxyServicesUserMixin,
47
48
  // Self-sovereign identity (DID, signed records, auth-method ↔ VM mapping)
48
49
  OxyServicesIdentityMixin,
50
+ // Encrypted off-device identity backup (b3 Feature 1): store/restore an
51
+ // encrypted copy of the self-custody key, keyed off the recovery phrase.
52
+ OxyServicesIdentityBackupMixin,
49
53
  OxyServicesPrivacyMixin,
50
54
  // Feature mixins
51
55
  OxyServicesLanguageMixin,