@cryptforge/core 0.1.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,772 @@
1
+ interface KeyData {
2
+ mnemonic: string;
3
+ seed: Uint8Array;
4
+ privateKey: Uint8Array;
5
+ privateKeyHex: string;
6
+ publicKey: Uint8Array;
7
+ publicKeyHex: string;
8
+ address: string;
9
+ path: string;
10
+ }
11
+ interface ChainData {
12
+ name: string;
13
+ symbol: string;
14
+ chainId: number;
15
+ tokenStandard?: string;
16
+ decimals: number;
17
+ cmc_id: number;
18
+ }
19
+ interface Chain {
20
+ id: string;
21
+ name: string;
22
+ symbol: string;
23
+ }
24
+ interface Identity {
25
+ id: string;
26
+ publicKey: string;
27
+ fingerprint: string;
28
+ label?: string;
29
+ metadata: Record<string, any>;
30
+ createdAt: Date;
31
+ lastAccess?: Date;
32
+ }
33
+ interface StoredIdentity {
34
+ id: string;
35
+ fingerprint: string;
36
+ publicKey: string;
37
+ label?: string;
38
+ metadata: Record<string, any>;
39
+ keystore: string;
40
+ createdAt: string;
41
+ lastAccess?: string;
42
+ }
43
+ interface Keys {
44
+ privateKey: Uint8Array;
45
+ privateKeyHex: string;
46
+ publicKey: Uint8Array;
47
+ publicKeyHex: string;
48
+ address: string;
49
+ derivationPath: string;
50
+ chain: Chain;
51
+ expiresAt: Date;
52
+ expiresIn: number;
53
+ identity: Identity;
54
+ }
55
+ interface AuthState {
56
+ identity: Identity | null;
57
+ keys: Keys | null;
58
+ currentChain: Chain | null;
59
+ isLocked: boolean;
60
+ }
61
+ interface CreateIdentityOptions {
62
+ mnemonic: string;
63
+ password: string;
64
+ metadata?: Record<string, any>;
65
+ label?: string;
66
+ }
67
+ interface GenerateMnemonicOptions {
68
+ wordCount?: 12 | 24;
69
+ language?: string;
70
+ }
71
+ interface RestoreIdentityOptions {
72
+ mnemonic: string;
73
+ password: string;
74
+ metadata?: Record<string, any>;
75
+ label?: string;
76
+ }
77
+ interface UnlockOptions {
78
+ password: string;
79
+ identityId?: string;
80
+ chainId?: string;
81
+ derivationPath?: string;
82
+ duration?: number;
83
+ }
84
+ interface SignMessageOptions {
85
+ message: string | Uint8Array;
86
+ derivationPath?: string;
87
+ }
88
+ interface SignTransactionOptions {
89
+ transaction: any;
90
+ derivationPath?: string;
91
+ }
92
+ interface DeriveKeyOptions {
93
+ path: string;
94
+ hardened?: boolean;
95
+ }
96
+ interface DeriveDataKeyOptions {
97
+ purpose: string;
98
+ version?: number;
99
+ algorithm?: "AES-GCM" | "AES-CBC";
100
+ length?: 128 | 192 | 256;
101
+ extractable?: boolean;
102
+ }
103
+ type AuthEvent = "IDENTITY_CREATED" | "IDENTITY_IMPORTED" | "IDENTITY_SWITCHED" | "IDENTITY_DELETED" | "PASSWORD_CHANGED" | "UNLOCKED" | "LOCKED" | "KEYS_ROTATED" | "IDENTITY_UPDATED" | "KEY_DERIVED" | "KEYS_EXPIRED" | "CHAIN_SWITCHED";
104
+ type AuthChangeCallback = (event: AuthEvent, keys: Keys | null) => void;
105
+ interface AuthAdapter {
106
+ registerAdapter: (chainId: string, adapter: any) => void;
107
+ getRegisteredChains: () => string[];
108
+ generateMnemonic: (options?: GenerateMnemonicOptions) => string;
109
+ createIdentity: (options: CreateIdentityOptions & {
110
+ chainId?: string;
111
+ }) => Promise<{
112
+ identity: Identity;
113
+ keys: Keys;
114
+ }>;
115
+ listIdentities: () => Promise<Array<Identity>>;
116
+ switchIdentity: (identityId: string) => Promise<{
117
+ identity: Identity;
118
+ }>;
119
+ updateIdentity: (identityId: string, updates: {
120
+ label?: string;
121
+ metadata?: Record<string, any>;
122
+ }) => Promise<{
123
+ identity: Identity;
124
+ }>;
125
+ deleteIdentity: (identityId: string, password: string) => Promise<void>;
126
+ changePassword: (identityId: string, oldPassword: string, newPassword: string) => Promise<void>;
127
+ exportMnemonic: (identityId: string, password: string) => Promise<string>;
128
+ exportKeystore: (identityId: string) => Promise<string>;
129
+ exportIdentity: (identityId: string) => Promise<StoredIdentity>;
130
+ importMnemonic: (mnemonic: string, password: string, label?: string) => Promise<{
131
+ identity: Identity;
132
+ }>;
133
+ importKeystore: (keystoreJson: string, password: string, label?: string) => Promise<{
134
+ identity: Identity;
135
+ }>;
136
+ importIdentity: (storedIdentity: StoredIdentity) => Promise<{
137
+ identity: Identity;
138
+ }>;
139
+ unlock: (options: UnlockOptions) => Promise<{
140
+ keys: Keys;
141
+ }>;
142
+ lock: () => Promise<void>;
143
+ verifyPassword: (password: string) => Promise<boolean>;
144
+ switchChain: (chainId: string, password?: string) => Promise<{
145
+ keys: Keys;
146
+ }>;
147
+ rotateKeys: (newDerivationPath?: string) => Promise<{
148
+ keys: Keys;
149
+ }>;
150
+ deriveKey: (options: DeriveKeyOptions) => Promise<{
151
+ privateKey: string;
152
+ publicKey: string;
153
+ address: string;
154
+ path: string;
155
+ }>;
156
+ deriveBIP44DocumentID: (options: {
157
+ appId: number;
158
+ account?: number;
159
+ purpose?: number;
160
+ index?: number;
161
+ }) => Promise<string>;
162
+ deriveDataEncryptionKey: (options: DeriveDataKeyOptions) => Promise<CryptoKey>;
163
+ getAddressForChain: (chainId: string, index?: number) => Promise<{
164
+ address: string;
165
+ publicKey: string;
166
+ derivationPath: string;
167
+ }>;
168
+ getAddresses: (chainId: string, start?: number, count?: number) => Promise<Array<{
169
+ address: string;
170
+ path: string;
171
+ index: number;
172
+ }>>;
173
+ findUsedAddresses: (chainId: string, checkBalance: (address: string) => Promise<boolean>) => Promise<Array<{
174
+ address: string;
175
+ path: string;
176
+ index: number;
177
+ }>>;
178
+ signMessage: (options: SignMessageOptions) => Promise<{
179
+ signature: string;
180
+ address: string;
181
+ publicKey: string;
182
+ }>;
183
+ signTransaction: (options: SignTransactionOptions) => Promise<{
184
+ signedTransaction: any;
185
+ signature: string;
186
+ }>;
187
+ verifySignature: (message: string | Uint8Array, signature: string, publicKey: string) => Promise<boolean>;
188
+ onAuthStateChange: (callback: AuthChangeCallback) => () => void;
189
+ readonly currentIdentity: Identity | null;
190
+ readonly currentKeys: Keys | null;
191
+ readonly currentChain: Chain | null;
192
+ readonly currentAddress: string | null;
193
+ readonly currentPublicKey: string | null;
194
+ readonly currentExpiresAt: Date | null;
195
+ readonly currentExpiresIn: number | null;
196
+ readonly isLocked: boolean;
197
+ readonly isUnlocked: boolean;
198
+ readonly hasIdentity: boolean;
199
+ readonly masterPublicKey: string | null;
200
+ }
201
+
202
+ type BlockchainType = "Bitcoin" | "Ethereum" | "Sonic" | "Kaspa";
203
+ interface TransactionReceipt {
204
+ /** Transaction hash - can be used to track on explorer */
205
+ hash: string;
206
+ /** Sender address */
207
+ from: string;
208
+ /** Recipient address (or contract address for token transfers) */
209
+ to: string;
210
+ /** Value transferred in wei (for native) or "0" (for token transfers) */
211
+ value: string;
212
+ /** Chain ID */
213
+ chainId: number;
214
+ /** Initial status - will be "pending" on return */
215
+ status: "pending";
216
+ /** Nonce used */
217
+ nonce: number;
218
+ }
219
+ interface TransactionStatusUpdate {
220
+ /** Transaction hash */
221
+ hash: string;
222
+ /** Current status */
223
+ status: "pending" | "confirmed" | "failed";
224
+ /** Block number if confirmed */
225
+ blockNumber?: number;
226
+ /** Number of confirmations if confirmed */
227
+ confirmations?: number;
228
+ /** Error message if failed */
229
+ error?: string;
230
+ /** Gas used (if confirmed) */
231
+ gasUsed?: string;
232
+ }
233
+ interface TokenBalance {
234
+ /** Token contract address */
235
+ contractAddress: string;
236
+ /** Balance in smallest unit (e.g., wei for 18 decimals) */
237
+ balance: string;
238
+ /** Human-readable balance (balance / 10^decimals) */
239
+ balanceFormatted: string;
240
+ /** Token symbol (e.g., "USDC") */
241
+ symbol: string;
242
+ /** Token name (e.g., "USD Coin") */
243
+ name: string;
244
+ /** Token decimals */
245
+ decimals: number;
246
+ /** Token logo URL (optional) */
247
+ logo?: string;
248
+ /**
249
+ * Whether this is an NFT (ERC-721/ERC-1155)
250
+ * Currently false for all ERC-20 tokens. Will be populated when dedicated NFT methods are implemented.
251
+ */
252
+ isNFT: boolean;
253
+ }
254
+ interface Transaction {
255
+ /** Transaction hash */
256
+ hash: string;
257
+ /** Sender address */
258
+ from: string;
259
+ /** Recipient address */
260
+ to: string;
261
+ /** Value transferred in wei */
262
+ value: string;
263
+ /** Unix timestamp */
264
+ timestamp: number;
265
+ /** Block number */
266
+ blockNumber: number;
267
+ /** Gas used */
268
+ gasUsed: string;
269
+ /** Gas price in wei */
270
+ gasPrice: string;
271
+ /** Transaction status */
272
+ status: "success" | "failed" | "pending";
273
+ /** Whether transaction failed */
274
+ isError: boolean;
275
+ }
276
+ interface TokenTransfer {
277
+ /** Transaction hash */
278
+ hash: string;
279
+ /** Sender address */
280
+ from: string;
281
+ /** Recipient address */
282
+ to: string;
283
+ /** Amount transferred in smallest unit */
284
+ value: string;
285
+ /** Unix timestamp */
286
+ timestamp: number;
287
+ /** Block number */
288
+ blockNumber: number;
289
+ /** Token contract address */
290
+ tokenAddress: string;
291
+ /** Token symbol */
292
+ tokenSymbol: string;
293
+ /** Token name */
294
+ tokenName: string;
295
+ /** Token decimals */
296
+ tokenDecimal: string;
297
+ }
298
+ interface TransactionOptions {
299
+ /** Starting block number (default: 0) */
300
+ startBlock?: number;
301
+ /** Ending block number (default: latest) */
302
+ endBlock?: number;
303
+ /** Page number for pagination (default: 1) */
304
+ page?: number;
305
+ /** Number of results per page (default: 100) */
306
+ offset?: number;
307
+ /** Sort order (default: 'desc') */
308
+ sort?: "asc" | "desc";
309
+ }
310
+ interface BlockchainAdapter {
311
+ readonly chainData: ChainData;
312
+ deriveKeys: (mnemonic: string) => Promise<KeyData>;
313
+ /**
314
+ * Derive keys at a specific address index
315
+ * @param mnemonic - BIP39 mnemonic phrase
316
+ * @param addressIndex - Address index in the BIP44 path
317
+ * @returns KeyData with derived keys
318
+ */
319
+ deriveKeysAtIndex: (mnemonic: string, addressIndex: number) => Promise<KeyData>;
320
+ /**
321
+ * Derive keys at a custom derivation path
322
+ * @param mnemonic - BIP39 mnemonic phrase
323
+ * @param path - Full BIP44 derivation path
324
+ * @returns KeyData with derived keys
325
+ */
326
+ deriveKeysAtPath: (mnemonic: string, path: string) => Promise<KeyData>;
327
+ /**
328
+ * Get address at a specific index (read-only, no private key)
329
+ * @param mnemonic - BIP39 mnemonic phrase
330
+ * @param index - Address index
331
+ * @returns Address and public key information
332
+ */
333
+ getAddressAtIndex: (mnemonic: string, index: number) => Promise<{
334
+ address: string;
335
+ publicKey: string;
336
+ path: string;
337
+ }>;
338
+ /**
339
+ * Get multiple addresses starting from an index
340
+ * @param mnemonic - BIP39 mnemonic phrase
341
+ * @param startIndex - Starting address index
342
+ * @param count - Number of addresses to generate
343
+ * @returns Array of addresses with metadata
344
+ */
345
+ getAddresses: (mnemonic: string, startIndex: number, count: number) => Promise<Array<{
346
+ address: string;
347
+ path: string;
348
+ index: number;
349
+ }>>;
350
+ /**
351
+ * Sign a message with a private key
352
+ * @param privateKey - Private key as Uint8Array
353
+ * @param message - Message to sign (string or Uint8Array)
354
+ * @returns Signature
355
+ */
356
+ signMessage: (privateKey: Uint8Array, message: string | Uint8Array) => Promise<{
357
+ signature: string;
358
+ }>;
359
+ /**
360
+ * Sign a transaction with a private key
361
+ * @param privateKey - Private key as Uint8Array
362
+ * @param transaction - Chain-specific transaction object
363
+ * @returns Signed transaction and signature
364
+ */
365
+ signTransaction: (privateKey: Uint8Array, transaction: any) => Promise<{
366
+ signedTransaction: any;
367
+ signature: string;
368
+ }>;
369
+ /**
370
+ * Verify a signature against a public key
371
+ * @param message - Original message
372
+ * @param signature - Signature to verify
373
+ * @param publicKey - Public key (hex string)
374
+ * @returns True if signature is valid
375
+ */
376
+ verifySignature: (message: string | Uint8Array, signature: string, publicKey: string) => Promise<boolean>;
377
+ /**
378
+ * Get native token balance (ETH, BTC, etc.) with metadata
379
+ * @param address - Wallet address
380
+ * @returns TokenBalance object with balance and metadata
381
+ */
382
+ getNativeBalance: (address: string) => Promise<TokenBalance>;
383
+ /**
384
+ * Get all ERC-20/token balances with metadata
385
+ * @param address - Wallet address
386
+ * @returns Array of token balances
387
+ */
388
+ getTokenBalances: (address: string) => Promise<TokenBalance[]>;
389
+ /**
390
+ * Get balance for a specific token contract
391
+ * @param address - Wallet address
392
+ * @param tokenAddress - Token contract address
393
+ * @returns Balance in smallest unit as string
394
+ */
395
+ getTokenBalance: (address: string, tokenAddress: string) => Promise<string>;
396
+ /**
397
+ * Get all native token transactions (send/receive)
398
+ * @param address - Wallet address
399
+ * @param options - Optional filtering and pagination
400
+ * @returns Array of transactions
401
+ */
402
+ getTransactions: (address: string, options?: TransactionOptions) => Promise<Transaction[]>;
403
+ /**
404
+ * Get all token transfer events
405
+ * @param address - Wallet address
406
+ * @param options - Optional filtering and pagination
407
+ * @returns Array of token transfers
408
+ */
409
+ getTokenTransfers: (address: string, options?: TransactionOptions) => Promise<TokenTransfer[]>;
410
+ /**
411
+ * Send native tokens (ETH, BTC, etc.)
412
+ * Private key must be obtained from AuthClient after password verification
413
+ * @param params - Transaction parameters including private key
414
+ * @returns Transaction receipt with pending status
415
+ */
416
+ sendNativeToken: (params: {
417
+ privateKey: Uint8Array;
418
+ to: string;
419
+ amount: string;
420
+ }) => Promise<TransactionReceipt>;
421
+ /**
422
+ * Send tokens (ERC-20, etc.)
423
+ * Private key must be obtained from AuthClient after password verification
424
+ * @param params - Transaction parameters including private key and token address
425
+ * @returns Transaction receipt with pending status
426
+ */
427
+ sendToken: (params: {
428
+ privateKey: Uint8Array;
429
+ to: string;
430
+ tokenAddress: string;
431
+ amount: string;
432
+ }) => Promise<TransactionReceipt>;
433
+ /**
434
+ * Get transaction status by hash
435
+ * @param hash - Transaction hash
436
+ * @returns Current transaction status with confirmations
437
+ */
438
+ getTransactionStatus: (hash: string) => Promise<TransactionStatusUpdate>;
439
+ }
440
+
441
+ /**
442
+ * Base document type that developers work with.
443
+ * Includes managed metadata fields (id, createdAt, updatedAt) that are automatically set by the library.
444
+ * Users should extend this interface to define their document types.
445
+ *
446
+ * @example
447
+ * ```typescript
448
+ * interface UserDocument extends BaseDocument {
449
+ * type: 'user'
450
+ * name: string
451
+ * email: string
452
+ * // id, createdAt, updatedAt are automatically available
453
+ * }
454
+ * ```
455
+ */
456
+ interface BaseDocument {
457
+ /** The document type identifier (e.g., 'note', 'task', 'user') */
458
+ type: string;
459
+ /** The Automerge document URL - automatically set by the library */
460
+ id: string;
461
+ /** Timestamp when the document was created - automatically set by the library */
462
+ createdAt: number;
463
+ /** Timestamp of the last update - automatically set by the library */
464
+ updatedAt: number;
465
+ /** Additional fields can be added as needed */
466
+ [key: string]: any;
467
+ }
468
+ /**
469
+ * Helper type to ensure user's document type doesn't include managed fields.
470
+ * This prevents conflicts and ensures the library controls these fields.
471
+ * Users cannot pass id, createdAt, or updatedAt when creating documents.
472
+ */
473
+ type ExternalDocument<T extends BaseDocument> = Omit<T, "id" | "createdAt" | "updatedAt">;
474
+ /**
475
+ * Internal encrypted document wrapper.
476
+ * This structure is what's actually stored in Automerge.
477
+ * The encryption/decryption is handled transparently by the store.
478
+ *
479
+ * @template T - The type of the decrypted document content (used for type safety, not stored in interface)
480
+ */
481
+ interface EncryptedDocument<_T> extends BaseDocument {
482
+ /** Always 'encrypted' to identify this as an encrypted wrapper */
483
+ type: "encrypted";
484
+ /** Base64-encoded encrypted data containing the actual document */
485
+ encryptedData: string;
486
+ /**
487
+ * Optional owner identifier (e.g., master public key from auth).
488
+ * Stored unencrypted for server-side ownership verification without decryption.
489
+ */
490
+ owner?: string;
491
+ /** Metadata about the encrypted document */
492
+ metadata: {
493
+ /** The original document type before encryption */
494
+ contentType: string;
495
+ /** Timestamp when the document was last encrypted */
496
+ encryptedAt: number;
497
+ /** User ID who encrypted the document */
498
+ encryptedBy: string;
499
+ };
500
+ }
501
+ /**
502
+ * Configuration for subscribing to document changes.
503
+ *
504
+ * @template T - The type of document being subscribed to
505
+ */
506
+ interface SubscribeConfig<T extends BaseDocument> {
507
+ /** The Automerge document URL/ID to subscribe to */
508
+ id: string;
509
+ /**
510
+ * Unique context identifier for this subscription.
511
+ * Allows multiple subscriptions to the same document (e.g., 'sidebar', 'main-view').
512
+ */
513
+ context: string;
514
+ /**
515
+ * Callback invoked with the decrypted document whenever it changes.
516
+ * Receives null if the document doesn't exist or was deleted.
517
+ * The document includes id, createdAt, and updatedAt fields automatically.
518
+ */
519
+ onUpdate: (doc: T | null) => void;
520
+ /**
521
+ * Optional error handler for subscription failures.
522
+ * Called when decryption fails or other errors occur.
523
+ */
524
+ onError?: (error: Error) => void;
525
+ }
526
+ /**
527
+ * Configuration for unsubscribing from document changes.
528
+ */
529
+ interface UnsubscribeConfig {
530
+ /** The document ID to unsubscribe from */
531
+ id: string;
532
+ /** The context identifier of the subscription to remove */
533
+ context: string;
534
+ }
535
+ /**
536
+ * Generic interface for cryptographic operations.
537
+ *
538
+ * @template TKey - The encryption key type (CryptoKey for browser, Buffer for Node.js)
539
+ */
540
+ interface CryptoOperations<TKey = unknown> {
541
+ /**
542
+ * Encryption key for all document operations.
543
+ * All documents are encrypted at rest using this key.
544
+ * Browser implementations use CryptoKey, Node.js implementations use Buffer.
545
+ */
546
+ setEncryptionKey?: (key: TKey) => void;
547
+ /**
548
+ * Creates an encryption function that encrypts string data using AES-GCM encryption.
549
+ * Returns a curried function that uses the instance's encryption key from `getEncryptionKey`.
550
+ *
551
+ * The returned function signature:
552
+ * - `data`: The plaintext string to encrypt
553
+ * - Returns: A promise resolving to the encrypted data as a string
554
+ */
555
+ encrypt: () => (data: string) => Promise<string>;
556
+ /**
557
+ * Creates a decryption function that decrypts encrypted string data using AES-GCM decryption.
558
+ * Returns a curried function that uses the instance's encryption key from `getEncryptionKey`.
559
+ *
560
+ * The returned function signature:
561
+ * - `encryptedData`: The encrypted string data to decrypt
562
+ * - Returns: A promise resolving to the decrypted plaintext string
563
+ */
564
+ decrypt: () => (encryptedData: string) => Promise<string>;
565
+ }
566
+ /**
567
+ * Interface for document store adapters.
568
+ * Provides a standard interface for document storage, retrieval, modification, and subscription operations.
569
+ *
570
+ * @template TKey - The encryption key type (CryptoKey for browser, Buffer for Node.js)
571
+ */
572
+ interface StoreAdapter {
573
+ /**
574
+ * Optional: Gets the network adapter for stores that support network synchronization.
575
+ * Returns null if no network adapter is configured.
576
+ * This property is only available on stores that implement network synchronization.
577
+ * The type is `any` to avoid coupling core types to Automerge-specific types.
578
+ */
579
+ readonly networkAdapter?: any | null;
580
+ /**
581
+ * Sets the encryption key for the store. Store operations aren't possible until the encryption key is set.
582
+ *
583
+ * @template TKey - The encryption key type (CryptoKey for browser, Buffer for Node.js)
584
+ * @param key - The encryption key to set
585
+ */
586
+ setEncryptionKey<TKey = unknown>(key: TKey): void;
587
+ /**
588
+ * Sets the owner identifier for document ownership (e.g., auth.masterPublicKey).
589
+ * Stored unencrypted in EncryptedDocument for server-side verification.
590
+ * Should be chain-independent for multi-blockchain applications.
591
+ *
592
+ * @param publicKey - The owner's public key
593
+ */
594
+ setOwnerPublicKey(publicKey: string): void;
595
+ /**
596
+ * Creates a new document with automatic encryption.
597
+ *
598
+ * The document is encrypted before being stored.
599
+ * Returns the document URL which can be used to retrieve or subscribe to the document.
600
+ *
601
+ * @template T - The document type (must extend BaseDocument)
602
+ * @param doc - The document to create (must include a 'type' field)
603
+ * @param url - Optional Automerge URL for deterministic document IDs
604
+ * @returns Promise resolving to the document URL
605
+ * @throws {Error} If document is missing 'type' field or encryption fails
606
+ */
607
+ create<T extends BaseDocument>(doc: ExternalDocument<T>, url?: string): Promise<string>;
608
+ /**
609
+ * Retrieves and decrypts a document by ID.
610
+ *
611
+ * @template T - The expected document type
612
+ * @param id - The document URL/ID
613
+ * @returns Promise resolving to the decrypted document, or null if not found
614
+ * @throws {Error} If document ID is invalid or decryption fails
615
+ */
616
+ get<T extends BaseDocument>(id: string): Promise<T | null>;
617
+ /**
618
+ * Modifies a document with automatic re-encryption.
619
+ *
620
+ * The document is decrypted, modified via the callback, then re-encrypted.
621
+ * Changes are applied atomically.
622
+ * The document includes id, createdAt, and updatedAt fields automatically.
623
+ *
624
+ * **Protected Fields**: The fields `id`, `createdAt`, and `updatedAt` are managed
625
+ * by the library and cannot be modified. Any attempts to change these fields in
626
+ * the callback will be ignored and restored to their original values. The library
627
+ * automatically updates `updatedAt` when changes are made.
628
+ *
629
+ * @template T - The document type
630
+ * @param id - The document ID to modify
631
+ * @param callback - Function that receives the decrypted document to modify
632
+ * @returns Promise that resolves when the change is applied
633
+ * @throws {Error} If document not found or encryption fails
634
+ */
635
+ change<T extends BaseDocument>(id: string, callback: (doc: T) => void): Promise<void>;
636
+ /**
637
+ * Deletes a document and cleans up all associated subscriptions.
638
+ *
639
+ * This removes the document from storage and automatically
640
+ * unsubscribes all active listeners to prevent memory leaks.
641
+ *
642
+ * @param id - The document ID to delete
643
+ * @returns Promise that resolves when deletion is complete
644
+ */
645
+ delete(id: string): Promise<void>;
646
+ /**
647
+ * Subscribes to document changes with automatic decryption.
648
+ *
649
+ * The callback receives the decrypted document whenever it changes.
650
+ * Multiple subscriptions to the same document are supported via different contexts.
651
+ *
652
+ * @template T - The document type
653
+ * @param config - Subscription configuration
654
+ * @returns Unsubscribe function to stop receiving updates
655
+ */
656
+ subscribe<T extends BaseDocument>(config: SubscribeConfig<T>): () => void;
657
+ /**
658
+ * Unsubscribes from document changes using document ID and context.
659
+ *
660
+ * Alternative to calling the unsubscribe function returned by subscribe().
661
+ *
662
+ * @param config - Object containing document ID and context
663
+ * @returns true if subscription was found and removed, false otherwise
664
+ */
665
+ unsubscribe(config: UnsubscribeConfig): boolean;
666
+ /**
667
+ * Gets all active subscription contexts for a document.
668
+ * Useful for debugging subscription state.
669
+ *
670
+ * @param id - The document ID
671
+ * @returns Array of context identifiers currently subscribed to this document
672
+ */
673
+ getActiveSubscriptions(id: string): string[];
674
+ /**
675
+ * Gets all active subscriptions across all documents.
676
+ * Useful for debugging memory leaks or subscription issues.
677
+ *
678
+ * @returns Object mapping document IDs to arrays of context identifiers
679
+ */
680
+ getAllActiveSubscriptions(): Record<string, string[]>;
681
+ }
682
+
683
+ type ActionType = "primary" | "secondary";
684
+ interface SlideAction {
685
+ type: ActionType;
686
+ title: string;
687
+ action: () => void;
688
+ }
689
+ interface WalkthroughStep {
690
+ image?: string;
691
+ title: string;
692
+ description: string;
693
+ actions?: SlideAction[];
694
+ }
695
+ interface AppInfo {
696
+ appId: number;
697
+ icon: string;
698
+ name: string;
699
+ secret: string;
700
+ description: string;
701
+ steps: WalkthroughStep[];
702
+ }
703
+
704
+ interface KeyTransportAdapter {
705
+ enableBroadcast: () => Promise<string>;
706
+ connect: (topic: string, name: string, app: string) => Promise<void>;
707
+ onClientConnection: (callback: (response: Record<string, any>) => void) => Promise<void> | Promise<() => void>;
708
+ requestKeystore: (pin: string) => Promise<void>;
709
+ onKeystoreRequestInvalidPIN: (callback: (response: Record<string, any>) => void) => Promise<void> | Promise<() => void>;
710
+ onKeystoreRequestValidPIN: (callback: (response: Record<string, any>) => void) => Promise<void> | Promise<() => void>;
711
+ onKeystoreRequest: (callback: (response: Record<string, any>) => void) => Promise<void> | Promise<() => void>;
712
+ approveRequest: (data: {
713
+ identity: StoredIdentity;
714
+ appId: number;
715
+ }) => Promise<void>;
716
+ onClientApproval: (callback: (response: Record<string, any>) => void) => Promise<void> | Promise<() => void>;
717
+ denyRequest: () => Promise<void>;
718
+ onClientDenial: (callback: (response: Record<string, any>) => void) => Promise<void> | Promise<() => void>;
719
+ onCompletion: (callback: (response: Record<string, any>) => void) => Promise<void> | Promise<() => void>;
720
+ disableBroadcast: () => Promise<void>;
721
+ onBroadcastDisable: (callback: (response: Record<string, any>) => void) => Promise<void> | Promise<() => void>;
722
+ getDeviceInfo: () => Promise<Record<string, any>>;
723
+ getHostname: () => Promise<string>;
724
+ connectPresence: (topic: string) => Promise<void>;
725
+ broadcastClientState: (id: string, state: ClientConnectionState) => Promise<void>;
726
+ onClientStateRequest: (callback: () => void) => Promise<void> | Promise<() => void>;
727
+ onClientStateUpdate: (callback: (response: {
728
+ id: string;
729
+ state: ClientConnectionState;
730
+ }) => void) => Promise<void> | Promise<() => void>;
731
+ getPeerState: (id: string) => ClientConnectionState | undefined;
732
+ getAllPeers: () => ReadonlyMap<string, ClientConnectionState>;
733
+ }
734
+ type OnSetupEventCallback = (options: {
735
+ route: string;
736
+ data: Record<string, any>;
737
+ }) => void;
738
+
739
+ interface PresenceAdapter {
740
+ connectPresence: (topic: string) => Promise<void>;
741
+ broadcastClientState: (id: string, state: ClientConnectionState) => Promise<void>;
742
+ onClientStateRequest: (callback: () => void) => Promise<void> | Promise<() => void>;
743
+ onClientStateUpdate: (callback: (response: {
744
+ id: string;
745
+ state: ClientConnectionState;
746
+ }) => void) => Promise<void> | Promise<() => void>;
747
+ getPeerState: (id: string) => ClientConnectionState | undefined;
748
+ getAllPeers: () => ReadonlyMap<string, ClientConnectionState>;
749
+ }
750
+
751
+ interface CryptForgeClientOptions {
752
+ secrets: KeyTransportAdapter;
753
+ presence: PresenceAdapter;
754
+ data: StoreAdapter;
755
+ appInfo: AppInfo;
756
+ blockchain: BlockchainAdapter;
757
+ auth: AuthAdapter;
758
+ }
759
+ interface CryptForgeClient {
760
+ secrets: KeyTransportAdapter;
761
+ presence: PresenceAdapter;
762
+ data: StoreAdapter;
763
+ appInfo: AppInfo;
764
+ blockchain: BlockchainAdapter;
765
+ auth: AuthAdapter;
766
+ }
767
+ declare function createCryptForgeClient(options: CryptForgeClientOptions): CryptForgeClient;
768
+ type ClientConnectionState = "unknown" | "connecting" | "connected" | "idle" | "disconnected";
769
+
770
+ declare const version = "0.1.0";
771
+
772
+ export { type ActionType, type AppInfo, type AuthAdapter, type AuthChangeCallback, type AuthEvent, type AuthState, type BaseDocument, type BlockchainAdapter, type BlockchainType, type Chain, type ChainData, type ClientConnectionState, type CreateIdentityOptions, type CryptForgeClient, type CryptForgeClientOptions, type CryptoOperations, type DeriveDataKeyOptions, type DeriveKeyOptions, type EncryptedDocument, type ExternalDocument, type GenerateMnemonicOptions, type Identity, type KeyData, type KeyTransportAdapter, type Keys, type OnSetupEventCallback, type PresenceAdapter, type RestoreIdentityOptions, type SignMessageOptions, type SignTransactionOptions, type SlideAction, type StoreAdapter, type StoredIdentity, type SubscribeConfig, type TokenBalance, type TokenTransfer, type Transaction, type TransactionOptions, type TransactionReceipt, type TransactionStatusUpdate, type UnlockOptions, type UnsubscribeConfig, type WalkthroughStep, createCryptForgeClient, version };