@oxy.so/core 7.24.0 → 7.25.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.
- package/dist/cjs/crypto/identitySigner.js +16 -0
- package/dist/cjs/crypto/index.js +14 -1
- package/dist/cjs/crypto/keyManager.js +48 -4
- package/dist/cjs/crypto/organizationKeys.js +349 -0
- package/dist/esm/crypto/identitySigner.js +14 -1
- package/dist/esm/crypto/index.js +2 -0
- package/dist/esm/crypto/keyManager.js +48 -4
- package/dist/esm/crypto/organizationKeys.js +336 -0
- package/dist/types/crypto/identitySigner.d.ts +18 -0
- package/dist/types/crypto/index.d.ts +2 -0
- package/dist/types/crypto/keyManager.d.ts +23 -5
- package/dist/types/crypto/organizationKeys.d.ts +90 -0
- package/package.json +2 -2
- package/src/crypto/identitySigner.ts +28 -0
- package/src/crypto/index.ts +19 -0
- package/src/crypto/keyManager.ts +55 -4
- package/src/crypto/organizationKeys.ts +399 -0
package/src/crypto/keyManager.ts
CHANGED
|
@@ -30,7 +30,8 @@ import {
|
|
|
30
30
|
} from '@oxy.so/protocol/secp256k1';
|
|
31
31
|
import { isDev, logger } from '../logger';
|
|
32
32
|
import { deriveScopedSeedFromKey, signSocialReceiveDigest } from './identityDerivations';
|
|
33
|
-
import type
|
|
33
|
+
import { type IdentitySignerStore, registerIdentitySignerStore } from './identitySigner';
|
|
34
|
+
import { getOrganizationPrivateKey, isOrganizationAccountId } from './organizationKeys';
|
|
34
35
|
import {
|
|
35
36
|
type IdentityMarker,
|
|
36
37
|
clearIdentityMarker,
|
|
@@ -457,6 +458,7 @@ export class KeyManager {
|
|
|
457
458
|
*/
|
|
458
459
|
static setIdentitySignerStore(store: IdentitySignerStore | null): void {
|
|
459
460
|
KeyManager.identitySignerStore = store;
|
|
461
|
+
registerIdentitySignerStore(store);
|
|
460
462
|
KeyManager.invalidateSharedCache();
|
|
461
463
|
}
|
|
462
464
|
|
|
@@ -3237,14 +3239,26 @@ export class KeyManager {
|
|
|
3237
3239
|
* Both reproduce from the user's Oxy recovery phrase, so the seed is
|
|
3238
3240
|
* recoverable, and the IPC answer is byte-identical to the local one.
|
|
3239
3241
|
*
|
|
3242
|
+
* With `opts.accountId` the seed is derived from that ORGANIZATION's key
|
|
3243
|
+
* instead (ADR 0061 D6), from the same places: Commons' own copy, the iOS
|
|
3244
|
+
* keychain group, or Commons' identity host. It never falls back to the
|
|
3245
|
+
* personal key.
|
|
3246
|
+
*
|
|
3240
3247
|
* @param info Context/domain-binding label (distinct labels → independent seeds).
|
|
3248
|
+
* @param opts.accountId An organization's account id, for its key.
|
|
3241
3249
|
* @returns 32 bytes of derived keying material, or `null` on web / when no
|
|
3242
3250
|
* identity key is available to this app.
|
|
3243
3251
|
*/
|
|
3244
|
-
static async deriveScopedSeed(
|
|
3252
|
+
static async deriveScopedSeed(
|
|
3253
|
+
info: string,
|
|
3254
|
+
opts?: { accountId?: string },
|
|
3255
|
+
): Promise<Uint8Array | null> {
|
|
3245
3256
|
if (isWebPlatform()) {
|
|
3246
3257
|
return null;
|
|
3247
3258
|
}
|
|
3259
|
+
if (opts?.accountId !== undefined) {
|
|
3260
|
+
return KeyManager._deriveOrganizationScopedSeed(info, opts.accountId);
|
|
3261
|
+
}
|
|
3248
3262
|
if (isAndroid()) {
|
|
3249
3263
|
if (KeyManager.identitySignerStore) {
|
|
3250
3264
|
// Commons: its own key.
|
|
@@ -3263,6 +3277,28 @@ export class KeyManager {
|
|
|
3263
3277
|
return deriveScopedSeedFromKey(privateKey, info);
|
|
3264
3278
|
}
|
|
3265
3279
|
|
|
3280
|
+
/**
|
|
3281
|
+
* {@link deriveScopedSeed} over an ORGANIZATION key (ADR 0061 D6): Commons'
|
|
3282
|
+
* own copy inside Commons and on iOS the keychain group, everywhere else on
|
|
3283
|
+
* Android Commons' identity host. Never falls back to the personal key: an
|
|
3284
|
+
* organization this device cannot reach is `null`.
|
|
3285
|
+
*/
|
|
3286
|
+
private static async _deriveOrganizationScopedSeed(
|
|
3287
|
+
info: string,
|
|
3288
|
+
accountId: string,
|
|
3289
|
+
): Promise<Uint8Array | null> {
|
|
3290
|
+
if (!isOrganizationAccountId(accountId)) {
|
|
3291
|
+
return null;
|
|
3292
|
+
}
|
|
3293
|
+
if (isAndroid() && !KeyManager.identitySignerStore) {
|
|
3294
|
+
const bridge = await loadCommonsIdentityBridge();
|
|
3295
|
+
const seed = (await bridge?.deriveScopedSeed(info, accountId)) ?? null;
|
|
3296
|
+
return seed ? hexToBytes(seed) : null;
|
|
3297
|
+
}
|
|
3298
|
+
const privateKey = await getOrganizationPrivateKey(accountId);
|
|
3299
|
+
return privateKey ? deriveScopedSeedFromKey(privateKey, info) : null;
|
|
3300
|
+
}
|
|
3301
|
+
|
|
3266
3302
|
/**
|
|
3267
3303
|
* Sign a 32-byte digest (a transaction sighash, lowercase hex) with the
|
|
3268
3304
|
* identity's social-receive child key `index`: the non-hardened BIP32 child
|
|
@@ -3270,8 +3306,9 @@ export class KeyManager {
|
|
|
3270
3306
|
* signature is RFC 6979, low-S, DER hex; `publicKey` is the child's
|
|
3271
3307
|
* compressed public key for the scriptSig.
|
|
3272
3308
|
*
|
|
3273
|
-
* Key source: as {@link deriveScopedSeed}
|
|
3274
|
-
*
|
|
3309
|
+
* Key source: as {@link deriveScopedSeed}, including `opts.accountId` for an
|
|
3310
|
+
* organization's key (ADR 0061 D6). On Android outside Commons the signature
|
|
3311
|
+
* comes from Commons, which allows it for the wallet app only.
|
|
3275
3312
|
*
|
|
3276
3313
|
* @returns the signature, or `null` on web / when no identity key is
|
|
3277
3314
|
* available to this app.
|
|
@@ -3279,10 +3316,24 @@ export class KeyManager {
|
|
|
3279
3316
|
static async signSocialReceive(
|
|
3280
3317
|
index: number,
|
|
3281
3318
|
digest: string,
|
|
3319
|
+
opts?: { accountId?: string },
|
|
3282
3320
|
): Promise<CommonsSocialReceiveSignature | null> {
|
|
3283
3321
|
if (isWebPlatform()) {
|
|
3284
3322
|
return null;
|
|
3285
3323
|
}
|
|
3324
|
+
const accountId = opts?.accountId;
|
|
3325
|
+
if (accountId !== undefined) {
|
|
3326
|
+
// An organization key (ADR 0061 D6); never the personal one in its place.
|
|
3327
|
+
if (!isOrganizationAccountId(accountId)) {
|
|
3328
|
+
return null;
|
|
3329
|
+
}
|
|
3330
|
+
if (isAndroid() && !KeyManager.identitySignerStore) {
|
|
3331
|
+
const bridge = await loadCommonsIdentityBridge();
|
|
3332
|
+
return (await bridge?.signSocialReceive(index, digest, accountId)) ?? null;
|
|
3333
|
+
}
|
|
3334
|
+
const organizationKey = await getOrganizationPrivateKey(accountId);
|
|
3335
|
+
return organizationKey ? signSocialReceiveDigest(organizationKey, index, digest) : null;
|
|
3336
|
+
}
|
|
3286
3337
|
if (isAndroid() && !KeyManager.identitySignerStore) {
|
|
3287
3338
|
// Every app but Commons: Commons signs.
|
|
3288
3339
|
const bridge = await loadCommonsIdentityBridge();
|
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Organization keys on the device (ADR 0061 D6).
|
|
3
|
+
*
|
|
4
|
+
* An organization's identity key is created in Commons by one of its owners or
|
|
5
|
+
* admins, from a fresh 24-word phrase (`seed[0:32]`, the personal-root
|
|
6
|
+
* derivation), and is published as the organization's DID `#key-1`. Commons
|
|
7
|
+
* holds it beside the person's own root, under the organization's account id;
|
|
8
|
+
* other Oxy apps reach it the way they reach the personal identity, by
|
|
9
|
+
* derivation and never by the key:
|
|
10
|
+
*
|
|
11
|
+
* - iOS: the keychain access group `group.so.oxy.shared`, like the personal
|
|
12
|
+
* shared slot. Only Commons writes it.
|
|
13
|
+
* - Android: Commons' own expo-secure-store slot, mirrored into the identity
|
|
14
|
+
* signer store (`./identitySigner`) that Commons' identity host answers
|
|
15
|
+
* `accountId` requests from. Every other app asks Commons over IPC
|
|
16
|
+
* (`loadCommonsIdentityBridge`), and never gets the key.
|
|
17
|
+
*
|
|
18
|
+
* The phrase is kept only in Commons, on the device that created or imported
|
|
19
|
+
* it, so an owner can show it to another owner (ADR 0061 D5); it never reaches
|
|
20
|
+
* the keychain group, an IPC answer or a log.
|
|
21
|
+
*
|
|
22
|
+
* This module imports nothing from `./keyManager` (which imports it): the
|
|
23
|
+
* signer store comes from `./identitySigner`'s registry.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { generateMnemonic, mnemonicToSeed, validateMnemonic } from '@scure/bip39';
|
|
27
|
+
import { wordlist } from '@scure/bip39/wordlists/english.js';
|
|
28
|
+
import {
|
|
29
|
+
type ExpoSecureStoreLike,
|
|
30
|
+
loadCommonsIdentityBridge,
|
|
31
|
+
loadSecureStore,
|
|
32
|
+
} from '@oxy.so/protocol';
|
|
33
|
+
import {
|
|
34
|
+
deriveSecp256k1PublicKey,
|
|
35
|
+
isValidSecp256k1PrivateKey,
|
|
36
|
+
isValidSecp256k1PublicKey,
|
|
37
|
+
normalizeSecp256k1PrivateKey,
|
|
38
|
+
normalizeSecp256k1PublicKey,
|
|
39
|
+
} from '@oxy.so/protocol/secp256k1';
|
|
40
|
+
import { logger } from '../logger';
|
|
41
|
+
import { isAndroid, isIOS, isWeb } from '../utils/platform';
|
|
42
|
+
import { registeredIdentitySignerStore } from './identitySigner';
|
|
43
|
+
|
|
44
|
+
/** A secp256k1 pair: private key 64 hex, public key lowercase uncompressed (`04…`, 130 hex). */
|
|
45
|
+
export interface OrganizationKeyPair {
|
|
46
|
+
privateKey: string;
|
|
47
|
+
publicKey: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A new organization key and the 24-word phrase it derives from. */
|
|
51
|
+
export interface GeneratedOrganizationKey extends OrganizationKeyPair {
|
|
52
|
+
mnemonic: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** What {@link storeOrganizationKey} keeps: the pair, and the phrase when the device has it. */
|
|
56
|
+
export interface StoredOrganizationKey extends OrganizationKeyPair {
|
|
57
|
+
mnemonic?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Same set the server's account ids come from: a legacy 24-hex id or a lowercase uuid. */
|
|
61
|
+
const ACCOUNT_ID =
|
|
62
|
+
/^(?:[0-9a-f]{24}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
|
|
63
|
+
|
|
64
|
+
const IOS_KEYCHAIN_GROUP = 'group.so.oxy.shared';
|
|
65
|
+
/** Android, Commons-local: its own Keystore key, shared with no personal slot. */
|
|
66
|
+
const ANDROID_KEYCHAIN_SERVICE = 'oxy_org_identity';
|
|
67
|
+
const MNEMONIC_KEYCHAIN_SERVICE = 'oxy_org_identity_mnemonic';
|
|
68
|
+
const INDEX_KEYCHAIN_SERVICE = 'oxy_org_identity_index';
|
|
69
|
+
const INDEX_STORAGE_KEY = 'oxy_org_identity_index_v1';
|
|
70
|
+
const ORGANIZATION_PHRASE_WORDS = 24;
|
|
71
|
+
|
|
72
|
+
interface SecureStoreOptions {
|
|
73
|
+
keychainService?: string;
|
|
74
|
+
keychainAccessible?: number;
|
|
75
|
+
keychainAccessGroup?: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Whether `value` is an account id an organization key can be stored under. */
|
|
79
|
+
export function isOrganizationAccountId(value: string): boolean {
|
|
80
|
+
return ACCOUNT_ID.test(value);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function assertAccountId(accountId: string): void {
|
|
84
|
+
if (!isOrganizationAccountId(accountId)) {
|
|
85
|
+
throw new Error('organization key: accountId must be a 24-hex or uuid account id');
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const privateKeyName = (accountId: string) => `oxy_org_identity_private_key.${accountId}`;
|
|
90
|
+
const publicKeyName = (accountId: string) => `oxy_org_identity_public_key.${accountId}`;
|
|
91
|
+
const mnemonicName = (accountId: string) => `oxy_org_identity_mnemonic.${accountId}`;
|
|
92
|
+
|
|
93
|
+
function toHex(bytes: Uint8Array): string {
|
|
94
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Lowercase uncompressed public key of `privateKey`. */
|
|
98
|
+
function publicKeyOf(privateKey: string): string {
|
|
99
|
+
return deriveSecp256k1PublicKey(normalizeSecp256k1PrivateKey(privateKey));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** True only when both halves are well-formed AND the public key derives from the private one. */
|
|
103
|
+
export function isHealthyOrganizationKeyPair(
|
|
104
|
+
privateKey: string | null | undefined,
|
|
105
|
+
publicKey: string | null | undefined,
|
|
106
|
+
): boolean {
|
|
107
|
+
if (!privateKey || !publicKey) return false;
|
|
108
|
+
if (!isValidSecp256k1PrivateKey(privateKey) || !isValidSecp256k1PublicKey(publicKey)) {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
return publicKeyOf(privateKey) === normalizeSecp256k1PublicKey(publicKey);
|
|
113
|
+
} catch {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function normalizePhrase(phrase: string): string {
|
|
119
|
+
return phrase.trim().toLowerCase().split(/\s+/).join(' ');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function pairFromPhrase(phrase: string): Promise<OrganizationKeyPair> {
|
|
123
|
+
const normalized = normalizePhrase(phrase);
|
|
124
|
+
if (
|
|
125
|
+
normalized.split(' ').length !== ORGANIZATION_PHRASE_WORDS ||
|
|
126
|
+
!validateMnemonic(normalized, wordlist)
|
|
127
|
+
) {
|
|
128
|
+
throw new Error('organization key: not a valid 24-word recovery phrase');
|
|
129
|
+
}
|
|
130
|
+
const seed = await mnemonicToSeed(normalized);
|
|
131
|
+
const privateKey = toHex(seed.subarray(0, 32));
|
|
132
|
+
return { privateKey, publicKey: publicKeyOf(privateKey) };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* A fresh organization key: a 24-word phrase and the pair derived from it
|
|
137
|
+
* exactly as a personal root is (`seed[0:32]`). Stores NOTHING: the caller shows
|
|
138
|
+
* the phrase, links the key (`oxy.accounts.identityKey`), and only then calls
|
|
139
|
+
* {@link storeOrganizationKey}.
|
|
140
|
+
*/
|
|
141
|
+
export async function generateOrganizationKey(): Promise<GeneratedOrganizationKey> {
|
|
142
|
+
const mnemonic = generateMnemonic(wordlist, 256);
|
|
143
|
+
return { mnemonic, ...(await pairFromPhrase(mnemonic)) };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* The pair a 24-word organization phrase derives. Stores nothing; the caller
|
|
148
|
+
* checks the public key against the organization's DID `#key-1` before keeping
|
|
149
|
+
* it (ADR 0061 D5).
|
|
150
|
+
*/
|
|
151
|
+
export async function organizationKeyFromPhrase(phrase: string): Promise<OrganizationKeyPair> {
|
|
152
|
+
return pairFromPhrase(phrase);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function secureStore(): Promise<ExpoSecureStoreLike> {
|
|
156
|
+
return loadSecureStore();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function readIndex(store: ExpoSecureStoreLike): Promise<string[]> {
|
|
160
|
+
const raw = await store.getItemAsync(INDEX_STORAGE_KEY, {
|
|
161
|
+
keychainService: INDEX_KEYCHAIN_SERVICE,
|
|
162
|
+
} satisfies SecureStoreOptions);
|
|
163
|
+
if (!raw) return [];
|
|
164
|
+
try {
|
|
165
|
+
const parsed: unknown = JSON.parse(raw);
|
|
166
|
+
return Array.isArray(parsed)
|
|
167
|
+
? parsed.filter((id): id is string => typeof id === 'string' && isOrganizationAccountId(id))
|
|
168
|
+
: [];
|
|
169
|
+
} catch (error) {
|
|
170
|
+
logger.warn('Organization key index unreadable; treating as empty', {
|
|
171
|
+
component: 'OrganizationKeys',
|
|
172
|
+
error: error instanceof Error ? error.name : 'unknown',
|
|
173
|
+
});
|
|
174
|
+
return [];
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async function writeIndex(store: ExpoSecureStoreLike, ids: string[]): Promise<void> {
|
|
179
|
+
await store.setItemAsync(INDEX_STORAGE_KEY, JSON.stringify([...new Set(ids)].sort()), {
|
|
180
|
+
keychainService: INDEX_KEYCHAIN_SERVICE,
|
|
181
|
+
} satisfies SecureStoreOptions);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Where this platform keeps the pair: the iOS keychain group, or Commons' own Android slot. */
|
|
185
|
+
function pairOptions(store: ExpoSecureStoreLike, forPrivateWrite: boolean): SecureStoreOptions {
|
|
186
|
+
if (isIOS()) {
|
|
187
|
+
return forPrivateWrite
|
|
188
|
+
? {
|
|
189
|
+
keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
|
|
190
|
+
keychainAccessGroup: IOS_KEYCHAIN_GROUP,
|
|
191
|
+
}
|
|
192
|
+
: { keychainAccessGroup: IOS_KEYCHAIN_GROUP };
|
|
193
|
+
}
|
|
194
|
+
return forPrivateWrite
|
|
195
|
+
? {
|
|
196
|
+
keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
|
|
197
|
+
keychainService: ANDROID_KEYCHAIN_SERVICE,
|
|
198
|
+
}
|
|
199
|
+
: { keychainService: ANDROID_KEYCHAIN_SERVICE };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The pair from this app's own storage (iOS group; Android Commons slot, then signer store). */
|
|
203
|
+
async function readLocalPair(accountId: string): Promise<OrganizationKeyPair | null> {
|
|
204
|
+
if (isWeb()) return null;
|
|
205
|
+
if (isAndroid()) {
|
|
206
|
+
const signer = registeredIdentitySignerStore();
|
|
207
|
+
if (!signer) return null; // Only Commons holds organization keys on Android.
|
|
208
|
+
const store = await secureStore();
|
|
209
|
+
const options = pairOptions(store, false);
|
|
210
|
+
const privateKey = await store.getItemAsync(privateKeyName(accountId), options);
|
|
211
|
+
const publicKey = await store.getItemAsync(publicKeyName(accountId), options);
|
|
212
|
+
if (privateKey && publicKey && isHealthyOrganizationKeyPair(privateKey, publicKey)) {
|
|
213
|
+
return {
|
|
214
|
+
privateKey: normalizeSecp256k1PrivateKey(privateKey),
|
|
215
|
+
publicKey: normalizeSecp256k1PublicKey(publicKey),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
// The signer store is a rung: a wiped expo-secure-store slot still has it.
|
|
219
|
+
const mirrored = (await signer.readOrganization?.(accountId)) ?? null;
|
|
220
|
+
return mirrored && isHealthyOrganizationKeyPair(mirrored.privateKey, mirrored.publicKey)
|
|
221
|
+
? mirrored
|
|
222
|
+
: null;
|
|
223
|
+
}
|
|
224
|
+
if (!isIOS()) return null;
|
|
225
|
+
const store = await secureStore();
|
|
226
|
+
const options = pairOptions(store, false);
|
|
227
|
+
const privateKey = await store.getItemAsync(privateKeyName(accountId), options);
|
|
228
|
+
const publicKey = await store.getItemAsync(publicKeyName(accountId), options);
|
|
229
|
+
return privateKey && publicKey && isHealthyOrganizationKeyPair(privateKey, publicKey)
|
|
230
|
+
? {
|
|
231
|
+
privateKey: normalizeSecp256k1PrivateKey(privateKey),
|
|
232
|
+
publicKey: normalizeSecp256k1PublicKey(publicKey),
|
|
233
|
+
}
|
|
234
|
+
: null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Keep an organization key on this device. Commons only: on Android it needs
|
|
239
|
+
* the identity signer store Commons registers, so the identity host can serve
|
|
240
|
+
* it; on iOS only Commons calls it (the keychain group is shared).
|
|
241
|
+
*
|
|
242
|
+
* Refuses a pair whose public key does not derive from its private key, and a
|
|
243
|
+
* phrase that does not derive the pair. Overwrites whatever this device held for
|
|
244
|
+
* the organization (a replaced key is the caller's decision, ADR 0061 D7).
|
|
245
|
+
*/
|
|
246
|
+
export async function storeOrganizationKey(
|
|
247
|
+
accountId: string,
|
|
248
|
+
key: StoredOrganizationKey,
|
|
249
|
+
): Promise<void> {
|
|
250
|
+
assertAccountId(accountId);
|
|
251
|
+
if (isWeb()) throw new Error('organization key: only a native device holds one');
|
|
252
|
+
if (!isHealthyOrganizationKeyPair(key.privateKey, key.publicKey)) {
|
|
253
|
+
throw new Error('organization key: the public key does not derive from the private key');
|
|
254
|
+
}
|
|
255
|
+
const privateKey = normalizeSecp256k1PrivateKey(key.privateKey);
|
|
256
|
+
const publicKey = normalizeSecp256k1PublicKey(key.publicKey);
|
|
257
|
+
if (key.mnemonic !== undefined) {
|
|
258
|
+
const fromPhrase = await pairFromPhrase(key.mnemonic);
|
|
259
|
+
if (fromPhrase.publicKey !== publicKey) {
|
|
260
|
+
throw new Error('organization key: the phrase derives a different key');
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const signer = isAndroid() ? registeredIdentitySignerStore() : null;
|
|
265
|
+
if (isAndroid() && !signer?.writeOrganization) {
|
|
266
|
+
throw new Error(
|
|
267
|
+
'On Android only Commons holds organization keys; this app has no identity signer store for them.',
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
const store = await secureStore();
|
|
271
|
+
await store.setItemAsync(privateKeyName(accountId), privateKey, pairOptions(store, true));
|
|
272
|
+
await store.setItemAsync(publicKeyName(accountId), publicKey, pairOptions(store, false));
|
|
273
|
+
if (
|
|
274
|
+
signer?.writeOrganization &&
|
|
275
|
+
!(await signer.writeOrganization(accountId, privateKey, publicKey))
|
|
276
|
+
) {
|
|
277
|
+
throw new Error(
|
|
278
|
+
`The identity signer store (${signer.name}) did not confirm the organization key.`,
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
if (key.mnemonic !== undefined) {
|
|
282
|
+
await store.setItemAsync(mnemonicName(accountId), normalizePhrase(key.mnemonic), {
|
|
283
|
+
keychainService: MNEMONIC_KEYCHAIN_SERVICE,
|
|
284
|
+
keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
|
|
285
|
+
} satisfies SecureStoreOptions);
|
|
286
|
+
} else {
|
|
287
|
+
await store.deleteItemAsync(mnemonicName(accountId), {
|
|
288
|
+
keychainService: MNEMONIC_KEYCHAIN_SERVICE,
|
|
289
|
+
} satisfies SecureStoreOptions);
|
|
290
|
+
}
|
|
291
|
+
await writeIndex(store, [...(await readIndex(store)), accountId]);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* The organization's public key as THIS device can reach it, or `null`.
|
|
296
|
+
* iOS: the keychain group. Android: Commons' own slot inside Commons, and
|
|
297
|
+
* Commons' identity host (`describe` with `accountId`) everywhere else. Compare
|
|
298
|
+
* it with the organization's DID `#key-1` before receiving (Peable ADR 0002).
|
|
299
|
+
*/
|
|
300
|
+
export async function getOrganizationPublicKey(accountId: string): Promise<string | null> {
|
|
301
|
+
if (!isOrganizationAccountId(accountId) || isWeb()) return null;
|
|
302
|
+
try {
|
|
303
|
+
if (isAndroid() && !registeredIdentitySignerStore()) {
|
|
304
|
+
const bridge = await loadCommonsIdentityBridge();
|
|
305
|
+
const description = (await bridge?.describe(accountId)) ?? null;
|
|
306
|
+
return description?.accountId === accountId ? description.publicKey : null;
|
|
307
|
+
}
|
|
308
|
+
return (await readLocalPair(accountId))?.publicKey ?? null;
|
|
309
|
+
} catch (error) {
|
|
310
|
+
logger.warn('Failed to read an organization public key', {
|
|
311
|
+
component: 'OrganizationKeys',
|
|
312
|
+
error: error instanceof Error ? error.name : 'unknown',
|
|
313
|
+
});
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* The organization's private key, where this app may hold it: Commons (both
|
|
320
|
+
* platforms) and, on iOS, the keychain group. `null` on Android outside
|
|
321
|
+
* Commons. Use it to sign within the app only; never transmit it.
|
|
322
|
+
*/
|
|
323
|
+
export async function getOrganizationPrivateKey(accountId: string): Promise<string | null> {
|
|
324
|
+
if (!isOrganizationAccountId(accountId)) return null;
|
|
325
|
+
try {
|
|
326
|
+
return (await readLocalPair(accountId))?.privateKey ?? null;
|
|
327
|
+
} catch (error) {
|
|
328
|
+
logger.warn('Failed to read an organization private key', {
|
|
329
|
+
component: 'OrganizationKeys',
|
|
330
|
+
error: error instanceof Error ? error.name : 'unknown',
|
|
331
|
+
});
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** The organization's phrase, if this device created or imported it with one. Commons only. */
|
|
337
|
+
export async function getOrganizationRecoveryPhrase(accountId: string): Promise<string | null> {
|
|
338
|
+
if (!isOrganizationAccountId(accountId) || isWeb()) return null;
|
|
339
|
+
const store = await secureStore();
|
|
340
|
+
return store.getItemAsync(mnemonicName(accountId), {
|
|
341
|
+
keychainService: MNEMONIC_KEYCHAIN_SERVICE,
|
|
342
|
+
} satisfies SecureStoreOptions);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** The organizations this device keeps a key for (Commons' own index). */
|
|
346
|
+
export async function listOrganizationKeys(): Promise<string[]> {
|
|
347
|
+
if (isWeb()) return [];
|
|
348
|
+
return readIndex(await secureStore());
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Forget an organization key on this device: its pair, its phrase, its signer copy and its index entry. */
|
|
352
|
+
export async function deleteOrganizationKey(accountId: string): Promise<void> {
|
|
353
|
+
assertAccountId(accountId);
|
|
354
|
+
if (isWeb()) return;
|
|
355
|
+
const store = await secureStore();
|
|
356
|
+
const options = pairOptions(store, false);
|
|
357
|
+
await store.deleteItemAsync(privateKeyName(accountId), options);
|
|
358
|
+
await store.deleteItemAsync(publicKeyName(accountId), options);
|
|
359
|
+
await store.deleteItemAsync(mnemonicName(accountId), {
|
|
360
|
+
keychainService: MNEMONIC_KEYCHAIN_SERVICE,
|
|
361
|
+
} satisfies SecureStoreOptions);
|
|
362
|
+
const signer = isAndroid() ? registeredIdentitySignerStore() : null;
|
|
363
|
+
await signer?.clearOrganization?.(accountId);
|
|
364
|
+
await writeIndex(
|
|
365
|
+
store,
|
|
366
|
+
(await readIndex(store)).filter((id) => id !== accountId),
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Commons on Android: copy every held organization key into the identity
|
|
372
|
+
* signer store again, so the identity host answers for it after that file was
|
|
373
|
+
* rebuilt (its self-heal leaves it empty). Call on every boot, beside
|
|
374
|
+
* `KeyManager.syncSharedIdentity`. Resolves how many it mirrored. Elsewhere 0.
|
|
375
|
+
*/
|
|
376
|
+
export async function syncOrganizationKeys(): Promise<number> {
|
|
377
|
+
const signer = isAndroid() ? registeredIdentitySignerStore() : null;
|
|
378
|
+
if (!signer?.writeOrganization || !signer.readOrganization) return 0;
|
|
379
|
+
const store = await secureStore();
|
|
380
|
+
let mirrored = 0;
|
|
381
|
+
for (const accountId of await readIndex(store)) {
|
|
382
|
+
const options = pairOptions(store, false);
|
|
383
|
+
const privateKey = await store.getItemAsync(privateKeyName(accountId), options);
|
|
384
|
+
const publicKey = await store.getItemAsync(publicKeyName(accountId), options);
|
|
385
|
+
if (!privateKey || !publicKey || !isHealthyOrganizationKeyPair(privateKey, publicKey)) continue;
|
|
386
|
+
const current = await signer.readOrganization(accountId);
|
|
387
|
+
if (current?.publicKey.toLowerCase() === publicKey.toLowerCase()) continue;
|
|
388
|
+
if (
|
|
389
|
+
await signer.writeOrganization(
|
|
390
|
+
accountId,
|
|
391
|
+
normalizeSecp256k1PrivateKey(privateKey),
|
|
392
|
+
publicKey.toLowerCase(),
|
|
393
|
+
)
|
|
394
|
+
) {
|
|
395
|
+
mirrored += 1;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
return mirrored;
|
|
399
|
+
}
|