@oxy.so/core 7.28.0 → 7.30.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 (44) hide show
  1. package/dist/cjs/api/identity.js +40 -1
  2. package/dist/cjs/crypto/index.js +28 -1
  3. package/dist/cjs/crypto/keyManager.js +175 -107
  4. package/dist/cjs/crypto/keychainGroupMigration.js +353 -0
  5. package/dist/cjs/crypto/keychainItems.js +70 -0
  6. package/dist/cjs/crypto/organizationKeys.js +80 -72
  7. package/dist/cjs/crypto/retiredKeys.js +371 -0
  8. package/dist/cjs/crypto/secureStoreOptions.js +2 -0
  9. package/dist/cjs/session/index.js +11 -1
  10. package/dist/cjs/utils/keychainAccessGroups.js +248 -0
  11. package/dist/esm/api/identity.js +40 -1
  12. package/dist/esm/crypto/index.js +6 -0
  13. package/dist/esm/crypto/keyManager.js +132 -64
  14. package/dist/esm/crypto/keychainGroupMigration.js +348 -0
  15. package/dist/esm/crypto/keychainItems.js +61 -0
  16. package/dist/esm/crypto/organizationKeys.js +54 -46
  17. package/dist/esm/crypto/retiredKeys.js +361 -0
  18. package/dist/esm/crypto/secureStoreOptions.js +1 -0
  19. package/dist/esm/session/index.js +3 -0
  20. package/dist/esm/utils/keychainAccessGroups.js +231 -0
  21. package/dist/types/api/identity.d.ts +10 -0
  22. package/dist/types/crypto/identitySigner.d.ts +23 -0
  23. package/dist/types/crypto/index.d.ts +6 -0
  24. package/dist/types/crypto/keyManager.d.ts +32 -2
  25. package/dist/types/crypto/keychainGroupMigration.d.ts +27 -0
  26. package/dist/types/crypto/keychainItems.d.ts +41 -0
  27. package/dist/types/crypto/organizationKeys.d.ts +11 -9
  28. package/dist/types/crypto/retiredKeys.d.ts +116 -0
  29. package/dist/types/crypto/secureStoreOptions.d.ts +15 -0
  30. package/dist/types/session/index.d.ts +2 -0
  31. package/dist/types/utils/keychainAccessGroups.d.ts +104 -0
  32. package/package.json +3 -3
  33. package/src/api/identity.ts +46 -3
  34. package/src/crypto/identitySigner.ts +23 -0
  35. package/src/crypto/index.ts +40 -0
  36. package/src/crypto/keyManager.ts +165 -102
  37. package/src/crypto/keychainGroupMigration.ts +440 -0
  38. package/src/crypto/keychainItems.ts +73 -0
  39. package/src/crypto/organizationKeys.ts +72 -57
  40. package/src/crypto/retiredKeys.ts +453 -0
  41. package/src/crypto/secureStoreOptions.ts +32 -0
  42. package/src/session/index.ts +11 -0
  43. package/src/utils/keychainAccessGroups.ts +308 -0
  44. package/src/types/expo-secure-store.d.ts +0 -21
@@ -0,0 +1,361 @@
1
+ /**
2
+ * Retired identity keys: the keys an account HAD, kept on the device for
3
+ * spending only (oxy ADR 0061 D7 as amended 2026-11-06, Peable ADR 0002).
4
+ *
5
+ * The Peable wallet derives from the account's identity key (`deriveScopedSeed`
6
+ * for its HD wallet, `signSocialReceive` for its social-receive addresses), and
7
+ * coins keep arriving under a key after it is replaced: payments already
8
+ * broadcast settle against the key they were reserved under, and late payers
9
+ * and `@username` senders hold old addresses. So a personal rotation
10
+ * (`oxy.identity.rotateKey`) and an organization replacement keep the replaced
11
+ * private key here, in a ring per account — `personal`, and one per
12
+ * organization account id — instead of deleting it.
13
+ *
14
+ * A retired key is NEVER a way to sign in, publish, receive a new reservation or
15
+ * rotate: nothing here signs a challenge, and the identity host refuses
16
+ * `proveIdentity` / `describe` for one. It is reached exactly as the current key
17
+ * is, by derivation and never by export, through the `publicKey` selector of
18
+ * `KeyManager.deriveScopedSeed` / `signSocialReceive`:
19
+ *
20
+ * - iOS: the private key in the wallet keychain group (ADR 0062's
21
+ * `spending-key`: Commons and the Peable wallet only), beside the current
22
+ * private keys; the ring's index (public keys and dates only) in the same
23
+ * group, so the wallet can list it. Only Commons writes either.
24
+ * - Android: Commons' own expo-secure-store slot, mirrored into the identity
25
+ * signer store (`./identitySigner`) that Commons' identity host answers
26
+ * `keyPublicKey` requests from (wallet only). Every other app asks over IPC
27
+ * (`loadCommonsIdentityBridge`) and never gets the key.
28
+ *
29
+ * A retired phrase is not kept: the person wrote it down, and a phrase is a
30
+ * second copy of the key that buys the wallet nothing.
31
+ *
32
+ * A key enters the ring only from Commons: the key being replaced (rotation,
33
+ * organization replacement), or a previous recovery phrase the person adds,
34
+ * which Commons accepts only when Oxy's key history names it as one of the
35
+ * account's retired keys. Never into the current slot.
36
+ *
37
+ * Security: a retired key that was compromised is also the attacker's. The
38
+ * ring makes the coins under it spendable from Peable again; it cannot make
39
+ * them safe. A rotation forced by a compromise must be followed at once by the
40
+ * wallet's "move to your current key" sweep, which races the attacker.
41
+ *
42
+ * This module imports nothing from `./keyManager` (which imports it).
43
+ */
44
+ import { mnemonicToSeed, validateMnemonic } from '@scure/bip39';
45
+ import { wordlist } from '@scure/bip39/wordlists/english.js';
46
+ import { loadCommonsIdentityBridge, loadSecureStore, } from '@oxy.so/protocol';
47
+ import { deriveSecp256k1PublicKey, isValidSecp256k1PrivateKey, isValidSecp256k1PublicKey, normalizeSecp256k1PrivateKey, normalizeSecp256k1PublicKey, } from '@oxy.so/protocol/secp256k1';
48
+ import { logger } from '../logger/index.js';
49
+ import { groupedKeychainStore, resolveKeychainAccess } from '../utils/keychainAccessGroups.js';
50
+ import { isAndroid, isIOS, isWeb } from '../utils/platform.js';
51
+ import { registeredIdentitySignerStore } from './identitySigner.js';
52
+ import { ensureKeychainGroupsMigrated } from './keychainGroupMigration.js';
53
+ import { isOrganizationAccountId } from './organizationKeys.js';
54
+ const PERSONAL_SCOPE = 'personal';
55
+ /** Android, Commons-local: its own Keystore-backed slot, shared with no other key. */
56
+ const ANDROID_KEYCHAIN_SERVICE = 'oxy_retired_identity';
57
+ const INDEX_KEYCHAIN_SERVICE = 'oxy_retired_identity_index';
58
+ const INDEX_STORAGE_KEY = 'oxy_retired_identity_index_v1';
59
+ const PUBLIC_KEY = /^04[0-9a-f]{128}$/;
60
+ /**
61
+ * The secure store for the ring. On iOS every item is a `spending-key`
62
+ * (ADR 0062): the private keys AND the index live in the wallet group, which
63
+ * only Commons and the Peable wallet can read, never the shared one. In
64
+ * Commons every access first awaits the access-group migration. On Android
65
+ * the grouping is a no-op and Commons' own services below apply.
66
+ */
67
+ async function ringStore() {
68
+ const raw = await loadSecureStore();
69
+ const access = await resolveKeychainAccess();
70
+ if (access.mode === 'grouped' && access.role === 'holder') {
71
+ await ensureKeychainGroupsMigrated();
72
+ }
73
+ return groupedKeychainStore(raw, access, 'spending-key');
74
+ }
75
+ /** The ring a selector names: `personal`, or the organization's account id. */
76
+ export function retiredKeyScope(selector) {
77
+ const accountId = selector?.accountId;
78
+ if (accountId === undefined)
79
+ return PERSONAL_SCOPE;
80
+ return isOrganizationAccountId(accountId) ? accountId : null;
81
+ }
82
+ function canonicalPublicKey(publicKey) {
83
+ try {
84
+ const normalized = normalizeSecp256k1PublicKey(publicKey.trim());
85
+ return PUBLIC_KEY.test(normalized) ? normalized : null;
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ }
91
+ function publicKeyOf(privateKey) {
92
+ return deriveSecp256k1PublicKey(normalizeSecp256k1PrivateKey(privateKey));
93
+ }
94
+ function isHealthyPair(privateKey, publicKey) {
95
+ if (!isValidSecp256k1PrivateKey(privateKey) || !isValidSecp256k1PublicKey(publicKey)) {
96
+ return false;
97
+ }
98
+ try {
99
+ return publicKeyOf(privateKey) === normalizeSecp256k1PublicKey(publicKey);
100
+ }
101
+ catch {
102
+ return false;
103
+ }
104
+ }
105
+ const privateKeyName = (scope, publicKey) => `oxy_retired_identity_private_key.${scope}.${publicKey}`;
106
+ /** The options of a private half: on iOS none but accessibility (the group comes from {@link ringStore}). */
107
+ function privateOptions(store, forWrite) {
108
+ if (isIOS()) {
109
+ return forWrite ? { keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY } : {};
110
+ }
111
+ return forWrite
112
+ ? {
113
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
114
+ keychainService: ANDROID_KEYCHAIN_SERVICE,
115
+ }
116
+ : { keychainService: ANDROID_KEYCHAIN_SERVICE };
117
+ }
118
+ /** The index: public keys and dates, beside the private halves. */
119
+ function indexOptions() {
120
+ return isIOS() ? {} : { keychainService: INDEX_KEYCHAIN_SERVICE };
121
+ }
122
+ function isIndexEntry(value) {
123
+ if (typeof value !== 'object' || value === null)
124
+ return false;
125
+ const entry = value;
126
+ return (typeof entry.scope === 'string' &&
127
+ (entry.scope === PERSONAL_SCOPE || isOrganizationAccountId(entry.scope)) &&
128
+ typeof entry.publicKey === 'string' &&
129
+ PUBLIC_KEY.test(entry.publicKey) &&
130
+ typeof entry.retiredAt === 'number' &&
131
+ Number.isFinite(entry.retiredAt));
132
+ }
133
+ async function readIndex(store) {
134
+ const raw = await store.getItemAsync(INDEX_STORAGE_KEY, indexOptions());
135
+ if (!raw)
136
+ return [];
137
+ try {
138
+ const parsed = JSON.parse(raw);
139
+ return Array.isArray(parsed) ? parsed.filter(isIndexEntry) : [];
140
+ }
141
+ catch (error) {
142
+ logger.warn('Retired key index unreadable; treating as empty', {
143
+ component: 'RetiredKeys',
144
+ error: error instanceof Error ? error.name : 'unknown',
145
+ });
146
+ return [];
147
+ }
148
+ }
149
+ async function writeIndex(store, entries) {
150
+ const unique = new Map();
151
+ for (const entry of entries) {
152
+ const id = `${entry.scope}.${entry.publicKey}`;
153
+ if (!unique.has(id))
154
+ unique.set(id, entry);
155
+ }
156
+ const sorted = [...unique.values()].sort((a, b) => a.retiredAt - b.retiredAt || a.publicKey.localeCompare(b.publicKey));
157
+ await store.setItemAsync(INDEX_STORAGE_KEY, JSON.stringify(sorted), indexOptions());
158
+ }
159
+ function toListed(entry) {
160
+ return entry.scope === PERSONAL_SCOPE
161
+ ? { publicKey: entry.publicKey, retiredAt: entry.retiredAt }
162
+ : { publicKey: entry.publicKey, accountId: entry.scope, retiredAt: entry.retiredAt };
163
+ }
164
+ /** Whether this app writes the ring: Commons (Android: the signer store it registers; iOS: native). */
165
+ function assertMayWrite() {
166
+ if (isWeb())
167
+ throw new Error('retired key: only a native device holds one');
168
+ if (isAndroid() && !registeredIdentitySignerStore()?.writeRetired) {
169
+ throw new Error('On Android only Commons holds retired keys; this app has no identity signer store for them.');
170
+ }
171
+ }
172
+ /**
173
+ * Keep `key` in the ring of `selector`'s account. Commons only. Idempotent: a
174
+ * key already kept stays, with its first date. Refuses a pair whose public key
175
+ * does not derive from its private key. Resolves once every copy confirmed it
176
+ * (Android: the signer store's read-back too), and throws otherwise, so a
177
+ * caller about to replace the key can stop before anything is lost.
178
+ */
179
+ export async function retireIdentityKey(key, selector) {
180
+ const scope = retiredKeyScope(selector);
181
+ if (!scope)
182
+ throw new Error('retired key: accountId must be a 24-hex or uuid account id');
183
+ assertMayWrite();
184
+ if (!isHealthyPair(key.privateKey, key.publicKey)) {
185
+ throw new Error('retired key: the public key does not derive from the private key');
186
+ }
187
+ const privateKey = normalizeSecp256k1PrivateKey(key.privateKey);
188
+ const publicKey = normalizeSecp256k1PublicKey(key.publicKey);
189
+ const store = await ringStore();
190
+ await store.setItemAsync(privateKeyName(scope, publicKey), privateKey, privateOptions(store, true));
191
+ const readBack = await store.getItemAsync(privateKeyName(scope, publicKey), privateOptions(store, false));
192
+ if (readBack !== privateKey) {
193
+ throw new Error('retired key: the keychain did not confirm the key');
194
+ }
195
+ const signer = isAndroid() ? registeredIdentitySignerStore() : null;
196
+ if (signer?.writeRetired && !(await signer.writeRetired(scope, privateKey, publicKey))) {
197
+ throw new Error(`The identity signer store (${signer.name}) did not confirm the retired key.`);
198
+ }
199
+ const index = await readIndex(store);
200
+ if (!index.some((entry) => entry.scope === scope && entry.publicKey === publicKey)) {
201
+ await writeIndex(store, [...index, { scope, publicKey, retiredAt: Date.now() }]);
202
+ }
203
+ }
204
+ /**
205
+ * The retired keys of `selector`'s account this app can reach, oldest first.
206
+ * iOS and Commons: the ring's index. Android elsewhere: Commons' identity host
207
+ * (the wallet only), which leaves out the scope's current key. After an
208
+ * interrupted rotation the local list can include the current key: compare
209
+ * with the DID's `#key-1` before treating an entry as retired.
210
+ */
211
+ export async function listRetiredIdentityKeys(selector) {
212
+ const scope = retiredKeyScope(selector);
213
+ if (!scope || isWeb())
214
+ return [];
215
+ try {
216
+ if (isAndroid() && !registeredIdentitySignerStore()) {
217
+ const bridge = await loadCommonsIdentityBridge();
218
+ const keys = (await bridge?.listRetiredKeys?.(selector?.accountId)) ?? null;
219
+ return (keys ?? []).map((publicKey) => scope === PERSONAL_SCOPE
220
+ ? { publicKey, retiredAt: 0 }
221
+ : { publicKey, accountId: scope, retiredAt: 0 });
222
+ }
223
+ if (!isIOS() && !isAndroid())
224
+ return [];
225
+ const store = await ringStore();
226
+ return (await readIndex(store)).filter((entry) => entry.scope === scope).map(toListed);
227
+ }
228
+ catch (error) {
229
+ logger.warn('Failed to list retired keys', {
230
+ component: 'RetiredKeys',
231
+ error: error instanceof Error ? error.name : 'unknown',
232
+ });
233
+ return [];
234
+ }
235
+ }
236
+ /**
237
+ * The private half of a retired key, where this app may hold it: Commons (both
238
+ * platforms) and, on iOS, the keychain group. `null` on Android outside Commons
239
+ * (ask the identity host instead) and for a key not in the ring. Sign within
240
+ * the app only; never transmit it. @internal — `KeyManager` reads it for the
241
+ * `publicKey` selector.
242
+ */
243
+ export async function getRetiredPrivateKey(publicKey, selector) {
244
+ const scope = retiredKeyScope(selector);
245
+ const canonical = canonicalPublicKey(publicKey);
246
+ if (!scope || !canonical || isWeb())
247
+ return null;
248
+ try {
249
+ if (isAndroid()) {
250
+ const signer = registeredIdentitySignerStore();
251
+ if (!signer)
252
+ return null;
253
+ const store = await ringStore();
254
+ const local = await store.getItemAsync(privateKeyName(scope, canonical), privateOptions(store, false));
255
+ if (local && isHealthyPair(local, canonical))
256
+ return normalizeSecp256k1PrivateKey(local);
257
+ // The signer store is a rung: a wiped expo-secure-store slot still has it.
258
+ const mirrored = (await signer.readRetired?.(scope, canonical)) ?? null;
259
+ return mirrored && isHealthyPair(mirrored.privateKey, canonical)
260
+ ? normalizeSecp256k1PrivateKey(mirrored.privateKey)
261
+ : null;
262
+ }
263
+ if (!isIOS())
264
+ return null;
265
+ const store = await ringStore();
266
+ const value = await store.getItemAsync(privateKeyName(scope, canonical), privateOptions(store, false));
267
+ return value && isHealthyPair(value, canonical) ? normalizeSecp256k1PrivateKey(value) : null;
268
+ }
269
+ catch (error) {
270
+ logger.warn('Failed to read a retired key', {
271
+ component: 'RetiredKeys',
272
+ error: error instanceof Error ? error.name : 'unknown',
273
+ });
274
+ return null;
275
+ }
276
+ }
277
+ /**
278
+ * Forget a retired key on this device: its private half, its signer copy and
279
+ * its index entry. Commons only, and only on the person's explicit request
280
+ * (their coins under it are then spendable only with its phrase again).
281
+ */
282
+ export async function forgetRetiredIdentityKey(publicKey, selector) {
283
+ const scope = retiredKeyScope(selector);
284
+ const canonical = canonicalPublicKey(publicKey);
285
+ if (!scope || !canonical)
286
+ throw new Error('retired key: invalid selector or public key');
287
+ assertMayWrite();
288
+ const store = await ringStore();
289
+ await store.deleteItemAsync(privateKeyName(scope, canonical), privateOptions(store, false));
290
+ const signer = isAndroid() ? registeredIdentitySignerStore() : null;
291
+ await signer?.clearRetired?.(scope, canonical);
292
+ await writeIndex(store, (await readIndex(store)).filter((entry) => !(entry.scope === scope && entry.publicKey === canonical)));
293
+ }
294
+ /**
295
+ * Forget every retired key of one ring (the person's, or an organization's):
296
+ * called when the identity itself is deleted from this device, so a phone
297
+ * handed on keeps none of the person's old keys. Commons only. Resolves how
298
+ * many it removed.
299
+ */
300
+ export async function forgetRetiredIdentityKeys(selector) {
301
+ const scope = retiredKeyScope(selector);
302
+ if (!scope || isWeb())
303
+ return 0;
304
+ if (isAndroid() && !registeredIdentitySignerStore())
305
+ return 0;
306
+ const store = await ringStore();
307
+ const index = await readIndex(store);
308
+ const signer = isAndroid() ? registeredIdentitySignerStore() : null;
309
+ let removed = 0;
310
+ for (const entry of index) {
311
+ if (entry.scope !== scope)
312
+ continue;
313
+ await store.deleteItemAsync(privateKeyName(scope, entry.publicKey), privateOptions(store, false));
314
+ await signer?.clearRetired?.(scope, entry.publicKey);
315
+ removed += 1;
316
+ }
317
+ await writeIndex(store, index.filter((entry) => entry.scope !== scope));
318
+ return removed;
319
+ }
320
+ /**
321
+ * Commons on Android: copy every retired key into the identity signer store
322
+ * again, so the identity host answers for it after that file was rebuilt (its
323
+ * self-heal leaves it empty). Call on every boot, beside `syncOrganizationKeys`.
324
+ * Resolves how many it mirrored. Elsewhere 0.
325
+ */
326
+ export async function syncRetiredKeys() {
327
+ const signer = isAndroid() ? registeredIdentitySignerStore() : null;
328
+ if (!signer?.writeRetired || !signer.readRetired)
329
+ return 0;
330
+ const store = await ringStore();
331
+ let mirrored = 0;
332
+ for (const entry of await readIndex(store)) {
333
+ const privateKey = await store.getItemAsync(privateKeyName(entry.scope, entry.publicKey), privateOptions(store, false));
334
+ if (!privateKey || !isHealthyPair(privateKey, entry.publicKey))
335
+ continue;
336
+ const current = await signer.readRetired(entry.scope, entry.publicKey);
337
+ if (current?.publicKey.toLowerCase() === entry.publicKey)
338
+ continue;
339
+ if (await signer.writeRetired(entry.scope, normalizeSecp256k1PrivateKey(privateKey), entry.publicKey)) {
340
+ mirrored += 1;
341
+ }
342
+ }
343
+ return mirrored;
344
+ }
345
+ /**
346
+ * The pair a previous recovery phrase derives (`seed[0:32]`, the personal-root
347
+ * and organization-key derivation; 12–24 words). Stores nothing: the caller
348
+ * checks the public key against the account's key history (personal:
349
+ * `oxy.identity.keyHistory()`; organization: `oxy.accounts.identityKey.get`)
350
+ * and only then calls {@link retireIdentityKey}.
351
+ */
352
+ export async function retiredKeyFromPhrase(phrase) {
353
+ const normalized = phrase.trim().toLowerCase().split(/\s+/).join(' ');
354
+ const words = normalized.split(' ').length;
355
+ if (words < 12 || words > 24 || words % 3 !== 0 || !validateMnemonic(normalized, wordlist)) {
356
+ throw new Error('retired key: not a valid recovery phrase');
357
+ }
358
+ const seed = await mnemonicToSeed(normalized);
359
+ const privateKey = Array.from(seed.subarray(0, 32), (b) => b.toString(16).padStart(2, '0')).join('');
360
+ return { privateKey, publicKey: publicKeyOf(privateKey) };
361
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -72,6 +72,9 @@ export { createWebAuthStateStore, createNativeAuthStateStore, createMemoryAuthSt
72
72
  // Commons private identity key: an app that only needs a session must never be
73
73
  // handed the key that signs identity approvals.
74
74
  export { createSharedMirroringAuthStateStore, decideSharedDeviceJoin, decideSharedDevicePublish, normalizeSharedDeviceSessionRead, publishProvenDeviceCredential, readLocalDeviceCredential, } from './sharedDeviceCredential.js';
75
+ // Where the shared device credential (and an app's own items) live on iOS:
76
+ // docs/identity/ios-keychain-access-groups.md, ADR 0062.
77
+ export { KeychainAccessUnavailableError, keychainAccessGroupValue, ownKeychainItemPlan, readThroughPlan, deleteThroughPlan, resolveKeychainAccess, } from '../utils/keychainAccessGroups.js';
75
78
  // Identity-bound sessions (the identity vault). The pin is the durable
76
79
  // `{publicKey, accountId}` binding between this device's PRIMARY identity key
77
80
  // and the account it authenticates as; it is what keeps such a client from
@@ -0,0 +1,231 @@
1
+ /**
2
+ * iOS keychain access groups: which group each Oxy keychain item lives in, and
3
+ * which apps may read it (docs/identity/ios-keychain-access-groups.md, ADR 0062).
4
+ *
5
+ * | Group | Held by | Item class |
6
+ * |-------------------------------|------------------------------|-------------------|
7
+ * | `<TEAM>.so.oxy.identity` | Commons only (listed FIRST) | `identity-secret` |
8
+ * | `<TEAM>.so.oxy.wallet` | Commons, the Peable wallet | `spending-key` |
9
+ * | `<TEAM>.group.so.oxy.shared` | every Oxy app | `shared` |
10
+ *
11
+ * - `identity-secret`: the personal root (primary and backup slots), the
12
+ * personal and organization recovery phrases, the organization index. Only
13
+ * Commons may read or write them.
14
+ * - `spending-key`: private keys an app other than Commons signs or derives
15
+ * with in process — the personal key's shared slot and organization pairs
16
+ * (`deriveScopedSeed`, `signSocialReceive`). Commons writes them; the Peable
17
+ * wallet reads them.
18
+ * - `shared`: what every Oxy app may read: the shared public key and the
19
+ * device-session credential.
20
+ *
21
+ * The ROLE of this binary comes from the keychain itself: an item written
22
+ * without a group lands in the app's default group, the first entry of its
23
+ * `keychain-access-groups` entitlement, and `@oxy.so/app-preset` lets only
24
+ * Commons put the identity group first and only the Peable wallet the wallet
25
+ * group. The same probe gives the team prefix, which `kSecAttrAccessGroup`
26
+ * needs and JavaScript cannot otherwise see.
27
+ *
28
+ * Android and web have no access groups: there every helper here answers the
29
+ * single-store behaviour (`ungrouped`), and Android's narrowing is Commons'
30
+ * identity host. An iOS build whose native module predates the probe is also
31
+ * `ungrouped` — exactly what that build's entitlements (one shared group) do.
32
+ *
33
+ * This module never imports the identity stack: services' device-session store
34
+ * and Peable's wallet storage use it too.
35
+ */
36
+ import { loadKeychainDefaultAccessGroup } from '@oxy.so/protocol';
37
+ import { isIOS } from './platform.js';
38
+ /** The group names after the team prefix, exactly as the entitlements list them. */
39
+ export const KEYCHAIN_ACCESS_GROUPS = {
40
+ identity: 'so.oxy.identity',
41
+ wallet: 'so.oxy.wallet',
42
+ shared: 'group.so.oxy.shared',
43
+ };
44
+ /** Thrown while the probe cannot answer (before first unlock). Transient. */
45
+ export class KeychainAccessUnavailableError extends Error {
46
+ constructor(cause) {
47
+ super('The keychain cannot say which access groups this app holds right now.');
48
+ this.cause = cause;
49
+ this.name = 'KeychainAccessUnavailableError';
50
+ }
51
+ }
52
+ /**
53
+ * The single place each item class is assigned a group. A new kind of item
54
+ * (F1's retained keys, for one) picks its class and reuses everything below.
55
+ */
56
+ export function keychainGroupFor(item) {
57
+ switch (item) {
58
+ case 'identity-secret':
59
+ return 'identity';
60
+ case 'spending-key':
61
+ return 'wallet';
62
+ case 'shared':
63
+ return 'shared';
64
+ }
65
+ }
66
+ /** Whether `role` holds the group `item` lives in. */
67
+ export function mayHoldKeychainItem(role, item) {
68
+ switch (role) {
69
+ case 'holder':
70
+ return true;
71
+ case 'wallet':
72
+ return item !== 'identity-secret';
73
+ case 'member':
74
+ return item === 'shared';
75
+ }
76
+ }
77
+ /** Parse the default access group the probe reported. Exported for tests. */
78
+ export function keychainAccessFromDefaultGroup(defaultGroup) {
79
+ const dot = defaultGroup.indexOf('.');
80
+ if (dot <= 0 || dot === defaultGroup.length - 1) {
81
+ // Not `<prefix>.<group>`: an unsigned simulator build. Nothing to split.
82
+ return { mode: 'ungrouped' };
83
+ }
84
+ const prefix = defaultGroup.slice(0, dot + 1);
85
+ const group = defaultGroup.slice(dot + 1);
86
+ const role = group === KEYCHAIN_ACCESS_GROUPS.identity
87
+ ? 'holder'
88
+ : group === KEYCHAIN_ACCESS_GROUPS.wallet
89
+ ? 'wallet'
90
+ : 'member';
91
+ return { mode: 'grouped', prefix, defaultGroup, role };
92
+ }
93
+ let resolvedAccess = null;
94
+ /**
95
+ * This binary's keychain access, memoized once known. THROWS
96
+ * {@link KeychainAccessUnavailableError} while the probe cannot answer, which
97
+ * every caller already treats as "storage unavailable, retry".
98
+ */
99
+ export async function resolveKeychainAccess() {
100
+ if (resolvedAccess) {
101
+ return resolvedAccess;
102
+ }
103
+ if (!isIOS()) {
104
+ // Not memoized: until `@oxy.so/services` registers the platform, a phone
105
+ // reads as "not iOS", and caching that would keep the whole process on the
106
+ // pre-split behaviour.
107
+ return { mode: 'ungrouped' };
108
+ }
109
+ let probe;
110
+ try {
111
+ probe = await loadKeychainDefaultAccessGroup();
112
+ }
113
+ catch (cause) {
114
+ throw new KeychainAccessUnavailableError(cause);
115
+ }
116
+ if (probe.state === 'unavailable') {
117
+ throw new KeychainAccessUnavailableError(probe.cause);
118
+ }
119
+ resolvedAccess =
120
+ probe.state === 'resolved'
121
+ ? keychainAccessFromDefaultGroup(probe.accessGroup)
122
+ : { mode: 'ungrouped' };
123
+ return resolvedAccess;
124
+ }
125
+ /** Forget the memoized access. Tests only. @internal */
126
+ export function resetKeychainAccessForTests() {
127
+ resolvedAccess = null;
128
+ }
129
+ /** The full `kSecAttrAccessGroup` value of `group`, or `undefined` when ungrouped. */
130
+ export function keychainAccessGroupValue(access, group) {
131
+ return access.mode === 'grouped' ? `${access.prefix}${KEYCHAIN_ACCESS_GROUPS[group]}` : undefined;
132
+ }
133
+ function option(value) {
134
+ return value === undefined ? {} : { accessGroup: value };
135
+ }
136
+ /**
137
+ * The option bags a READ of `item` tries, in order: its own group, then the
138
+ * shared group, where every item lived before the split (release 4 of the doc
139
+ * drops that fallback). Empty when this app may not hold the item: the caller
140
+ * answers `null` without touching the keychain.
141
+ */
142
+ export function keychainReadPlan(access, item) {
143
+ if (access.mode === 'ungrouped') {
144
+ return [{}];
145
+ }
146
+ if (!mayHoldKeychainItem(access.role, item)) {
147
+ return [];
148
+ }
149
+ const own = keychainGroupFor(item);
150
+ const plan = [option(keychainAccessGroupValue(access, own))];
151
+ if (own !== 'shared') {
152
+ plan.push(option(keychainAccessGroupValue(access, 'shared')));
153
+ }
154
+ return plan;
155
+ }
156
+ /**
157
+ * Every place a DELETE of `item` must reach: the read plan, so a delete never
158
+ * leaves a pre-split copy behind in the shared group.
159
+ */
160
+ export function keychainDeletePlan(access, item) {
161
+ return keychainReadPlan(access, item);
162
+ }
163
+ /**
164
+ * The option a WRITE of `item` carries. THROWS when this app may not hold the
165
+ * item: an identity secret written by any app but Commons would land in that
166
+ * app's default group, a second holder nobody knows about.
167
+ */
168
+ export function keychainWriteOption(access, item) {
169
+ if (access.mode === 'ungrouped') {
170
+ return {};
171
+ }
172
+ if (!mayHoldKeychainItem(access.role, item)) {
173
+ throw new Error(`This app (keychain role "${access.role}") may not hold a ${item} keychain item; only Commons writes the identity.`);
174
+ }
175
+ return option(keychainAccessGroupValue(access, keychainGroupFor(item)));
176
+ }
177
+ /**
178
+ * The plan for an app's OWN items (its session credential, its settings, an
179
+ * imported wallet's phrase) in Commons and the Peable wallet, whose default
180
+ * group the split changed: written to the default group explicitly — where a
181
+ * write without a group goes anyway — and read from it FIRST, then from every
182
+ * group (`{}`), where all of them were written before. Without the explicit
183
+ * order a read could return whichever of two copies the keychain met first.
184
+ * Deletes reach every group, as they always did.
185
+ *
186
+ * Every other app (`member`) and Android/web keep the calls they always made.
187
+ */
188
+ export function ownKeychainItemPlan(access) {
189
+ if (access.mode === 'ungrouped' || access.role === 'member') {
190
+ return { read: [{}], write: {}, delete: [{}] };
191
+ }
192
+ return {
193
+ read: [option(access.defaultGroup), {}],
194
+ write: option(access.defaultGroup),
195
+ delete: [{}],
196
+ };
197
+ }
198
+ /** Read `key` through `plan`: the first non-null answer. A thrown read propagates. */
199
+ export async function readThroughPlan(store, key, options, plan) {
200
+ for (const group of plan) {
201
+ const value = await store.getItemAsync(key, { ...options, ...group });
202
+ if (value !== null && value !== undefined) {
203
+ return value;
204
+ }
205
+ }
206
+ return null;
207
+ }
208
+ /** Delete `key` from every location in `plan`. A thrown delete propagates. */
209
+ export async function deleteThroughPlan(store, key, options, plan) {
210
+ for (const group of plan) {
211
+ await store.deleteItemAsync(key, { ...options, ...group });
212
+ }
213
+ }
214
+ /**
215
+ * `store` with every call routed to `item`'s groups for this app: reads walk
216
+ * the read plan, writes carry the write option (throwing for a role that may
217
+ * not hold the item), deletes reach every location. The constants of the
218
+ * wrapped store are kept, so `store.WHEN_UNLOCKED_THIS_DEVICE_ONLY` still reads.
219
+ */
220
+ export function groupedKeychainStore(store, access, item) {
221
+ const plan = keychainReadPlan(access, item);
222
+ const wrapped = {
223
+ getItemAsync: (key, options) => readThroughPlan(store, key, options ?? {}, plan),
224
+ setItemAsync: async (key, value, options) => {
225
+ const group = keychainWriteOption(access, item);
226
+ await store.setItemAsync(key, value, { ...(options ?? {}), ...group });
227
+ },
228
+ deleteItemAsync: (key, options) => deleteThroughPlan(store, key, options ?? {}, plan),
229
+ };
230
+ return Object.assign(Object.create(store), wrapped);
231
+ }
@@ -1,3 +1,4 @@
1
+ import { type IdentityKeyHistory } from '@oxy.so/contracts/client';
1
2
  import type { AuthMethodsResponse, BackupStatusResponse, DidDocument, DomainVerificationInstructions, ExportBundle, IdentityLinkCreateResponse, IdentityLinkState, IdentityRootStatus, OxySignedRecordType, ReauthProof, SignedRecordEnvelope, VerifiedDomain } from '@oxy.so/contracts';
2
3
  import type { OxyContext } from '../client/context';
3
4
  import type { PendingIdentityResult } from '../crypto/recoveryPhrase';
@@ -176,6 +177,15 @@ export declare class IdentityApi {
176
177
  * user's derived DID document (which embeds auth methods + verified domains).
177
178
  */
178
179
  private invalidate;
180
+ /**
181
+ * The signed-in personal account's current root (`null` without one) and
182
+ * every root a rotation replaced, oldest first, all canonical (uncompressed,
183
+ * lowercase). Commons reads it to accept a previous recovery phrase only when
184
+ * it derives a key that WAS this account's root. A retired root is never any
185
+ * account's again. First-party only; a non-personal account is refused
186
+ * (`IDENTITY_NOT_PERSONAL_ACCOUNT`).
187
+ */
188
+ keyHistory(): Promise<IdentityKeyHistory>;
179
189
  }
180
190
  /** `oxy.identity.links` — joining Commons' root to an account (ADR 0029 D3). */
181
191
  export declare class IdentityLinksApi {
@@ -40,6 +40,29 @@ export interface IdentitySignerStore {
40
40
  writeOrganization?(accountId: string, privateKey: string, publicKey: string): Promise<boolean>;
41
41
  /** Drop that organization's pair. */
42
42
  clearOrganization?(accountId: string): Promise<void>;
43
+ /**
44
+ * The RETIRED key ring: keys a scope rotated away from (a personal rotation,
45
+ * or an organization key replacement, ADR 0061 D7), kept so the identity host
46
+ * can still derive and sign with them for the wallet when a request names
47
+ * their public key. Spending only: the host never signs anyone in with one.
48
+ *
49
+ * `scope` is `'personal'` or an organization's account id (24-hex or uuid);
50
+ * `publicKey` is the retired key's lowercase uncompressed SEC1 hex (130),
51
+ * which names its entry. The native side refuses anything else. Clearing the
52
+ * personal pair ({@link clear}) or an organization's never drops a ring.
53
+ * Optional so a store built before retired keys still type-checks; Commons
54
+ * offers all four or none.
55
+ */
56
+ readRetired?(scope: string, publicKey: string): Promise<{
57
+ privateKey: string;
58
+ publicKey: string;
59
+ } | null>;
60
+ /** Keep a retired pair in `scope`'s ring. Resolves whether a read-back confirmed it. */
61
+ writeRetired?(scope: string, privateKey: string, publicKey: string): Promise<boolean>;
62
+ /** The public keys in `scope`'s ring (healthy entries only, sorted); `[]` when none. */
63
+ listRetired?(scope: string): Promise<string[]>;
64
+ /** Drop one retired key from `scope`'s ring. */
65
+ clearRetired?(scope: string, publicKey: string): Promise<void>;
43
66
  }
44
67
  /** @internal */
45
68
  export declare function registerIdentitySignerStore(store: IdentitySignerStore | null): void;
@@ -19,6 +19,12 @@ export type { IdentityDeviceBackupStore } from './deviceBackup';
19
19
  export type { IdentitySignerStore } from './identitySigner';
20
20
  export { generateOrganizationKey, organizationKeyFromPhrase, storeOrganizationKey, getOrganizationPublicKey, getOrganizationPrivateKey, getOrganizationRecoveryPhrase, listOrganizationKeys, deleteOrganizationKey, syncOrganizationKeys, isOrganizationAccountId, isHealthyOrganizationKeyPair, } from './organizationKeys';
21
21
  export type { OrganizationKeyPair, GeneratedOrganizationKey, StoredOrganizationKey, } from './organizationKeys';
22
+ export { KEYCHAIN_ACCESS_GROUPS, KeychainAccessUnavailableError, keychainGroupFor, mayHoldKeychainItem, resolveKeychainAccess, keychainAccessGroupValue, keychainReadPlan, keychainDeletePlan, keychainWriteOption, ownKeychainItemPlan, readThroughPlan, deleteThroughPlan, groupedKeychainStore, } from '../utils/keychainAccessGroups';
23
+ export type { KeychainAccess, KeychainAccessGroupName, KeychainGroupOption, KeychainItemClass, KeychainRole, KeychainStoreLike, } from '../utils/keychainAccessGroups';
24
+ export { ensureKeychainGroupsMigrated } from './keychainGroupMigration';
25
+ export type { KeychainGroupMigrationReport, KeychainItemMigrationOutcome, } from './keychainGroupMigration';
26
+ export { retireIdentityKey, listRetiredIdentityKeys, forgetRetiredIdentityKey, forgetRetiredIdentityKeys, syncRetiredKeys, retiredKeyFromPhrase, } from './retiredKeys';
27
+ export type { RetiredIdentityKey, RetiredKeyPair, RetiredKeySelector } from './retiredKeys';
22
28
  export { SignatureService } from './signatureService';
23
29
  export type { SignedMessage, AuthChallenge } from './signatureService';
24
30
  export { RecoveryPhraseService, BACKUP_KDF_ENCRYPTION_INFO } from './recoveryPhrase';