@oxy.so/core 7.24.0 → 7.26.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.
@@ -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
+ }
package/src/index.ts CHANGED
@@ -319,8 +319,8 @@ export {
319
319
  getNormalizedUserHandle,
320
320
  } from './utils/userHandle';
321
321
  export type { CanonicalUserHandleInput, UserHandleInput } from './utils/userHandle';
322
- export { normalizeProfileLinks } from './utils/profileLinks';
323
- export type { ProfileLink, ProfileLinkMetadata } from './utils/profileLinks';
322
+ export { normalizeProfileLinks, supportProviderOf } from './utils/profileLinks';
323
+ export type { ProfileLink, ProfileLinkMetadata, SupportProvider } from './utils/profileLinks';
324
324
 
325
325
  // ---------------------------------------------------------------------------
326
326
  // Auth helpers (token refresh, error normalisation, retry policies)
@@ -13,6 +13,8 @@ export interface ProfileLink {
13
13
  url: string;
14
14
  description?: string;
15
15
  image?: string;
16
+ /** Clarity's favicon for the link's host, when Clarity has one. */
17
+ faviconUrl?: string;
16
18
  }
17
19
 
18
20
  /** Source shape of a single `User.linksMetadata` entry. */
@@ -22,6 +24,7 @@ export interface ProfileLinkMetadata {
22
24
  description?: string;
23
25
  image?: string;
24
26
  id?: string;
27
+ faviconUrl?: string;
25
28
  }
26
29
 
27
30
  function cleanUrl(value: unknown): string | null {
@@ -63,12 +66,14 @@ export function normalizeProfileLinks(
63
66
  const title = typeof entry?.title === 'string' ? entry.title : undefined;
64
67
  const description = typeof entry?.description === 'string' ? entry.description : undefined;
65
68
  const image = typeof entry?.image === 'string' ? entry.image : undefined;
69
+ const faviconUrl = typeof entry?.faviconUrl === 'string' ? entry.faviconUrl : undefined;
66
70
  result.push({
67
71
  id,
68
72
  url,
69
73
  ...(title !== undefined ? { title } : {}),
70
74
  ...(description !== undefined ? { description } : {}),
71
75
  ...(image !== undefined ? { image } : {}),
76
+ ...(faviconUrl !== undefined ? { faviconUrl } : {}),
72
77
  });
73
78
  });
74
79
  return result;
@@ -86,3 +91,42 @@ export function normalizeProfileLinks(
86
91
 
87
92
  return [];
88
93
  }
94
+
95
+ /** A platform a profile can point supporters to, recognised by the link's host. */
96
+ export interface SupportProvider {
97
+ id: 'patreon' | 'kofi' | 'buymeacoffee' | 'github-sponsors' | 'liberapay';
98
+ name: string;
99
+ }
100
+
101
+ const SUPPORT_PROVIDERS: readonly { provider: SupportProvider; hosts: readonly string[] }[] = [
102
+ { provider: { id: 'patreon', name: 'Patreon' }, hosts: ['patreon.com'] },
103
+ { provider: { id: 'kofi', name: 'Ko-fi' }, hosts: ['ko-fi.com'] },
104
+ { provider: { id: 'buymeacoffee', name: 'Buy Me a Coffee' }, hosts: ['buymeacoffee.com'] },
105
+ { provider: { id: 'github-sponsors', name: 'GitHub Sponsors' }, hosts: ['github.com'] },
106
+ { provider: { id: 'liberapay', name: 'Liberapay' }, hosts: ['liberapay.com'] },
107
+ ];
108
+
109
+ /**
110
+ * The support platform a link points at, or `null`. GitHub Sponsors is the one
111
+ * host shared with ordinary GitHub pages, so only its `/sponsors/` path counts.
112
+ */
113
+ export function supportProviderOf(url: string): SupportProvider | null {
114
+ let parsed: URL;
115
+ try {
116
+ parsed = new URL(url);
117
+ } catch {
118
+ return null;
119
+ }
120
+ const host = parsed.hostname.toLowerCase().replace(/^www\./, '');
121
+ for (const { provider, hosts } of SUPPORT_PROVIDERS) {
122
+ if (!hosts.some((known) => host === known || host.endsWith(`.${known}`))) continue;
123
+ if (
124
+ provider.id === 'github-sponsors' &&
125
+ !parsed.pathname.toLowerCase().startsWith('/sponsors/')
126
+ ) {
127
+ continue;
128
+ }
129
+ return provider;
130
+ }
131
+ return null;
132
+ }