@cryptforge/auth 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,372 @@
1
+ import { AuthAdapter, BlockchainAdapter, GenerateMnemonicOptions, CreateIdentityOptions, Identity, Keys, UnlockOptions, DeriveKeyOptions, DeriveDataKeyOptions, SignMessageOptions, SignTransactionOptions, AuthChangeCallback, Chain } from '@cryptforge/core';
2
+ export { AuthAdapter, AuthChangeCallback, AuthEvent, AuthState, Chain, CreateIdentityOptions, DeriveDataKeyOptions, DeriveKeyOptions, GenerateMnemonicOptions, Identity, Keys, RestoreIdentityOptions, SignMessageOptions, SignTransactionOptions, StoredIdentity, UnlockOptions } from '@cryptforge/core';
3
+
4
+ declare class AuthClient implements AuthAdapter {
5
+ private state;
6
+ private listeners;
7
+ private lockTimer?;
8
+ private decryptedMnemonic;
9
+ private adapters;
10
+ private currentAdapter;
11
+ /**
12
+ * Register a blockchain adapter for a specific chain
13
+ * @param chainId - Unique chain identifier (e.g., 'ethereum', 'bitcoin')
14
+ * @param adapter - BlockchainAdapter implementation
15
+ */
16
+ registerAdapter: (chainId: string, adapter: BlockchainAdapter) => void;
17
+ /**
18
+ * Get the adapter for a specific chain
19
+ * @param chainId - Chain identifier
20
+ * @returns BlockchainAdapter instance
21
+ * @throws Error if no adapter is registered for the chain
22
+ */
23
+ private getAdapter;
24
+ /**
25
+ * Get all registered chain IDs
26
+ * @returns Array of registered chain IDs
27
+ */
28
+ getRegisteredChains: () => string[];
29
+ /**
30
+ * Generates a BIP39 mnemonic phrase (12 or 24 words).
31
+ * @param options - Optional configuration for word count
32
+ * @returns BIP39 mnemonic phrase
33
+ */
34
+ generateMnemonic: (options?: GenerateMnemonicOptions) => string;
35
+ /**
36
+ * Creates a new identity from a mnemonic and encrypts it with a password.
37
+ * Optionally unlocks with a specific blockchain.
38
+ * @param options - Identity creation options including mnemonic, password, and optional chainId
39
+ * @returns Promise resolving to the created identity and keys
40
+ * @throws {Error} If mnemonic is invalid
41
+ */
42
+ createIdentity: (options: CreateIdentityOptions & {
43
+ chainId?: string;
44
+ }) => Promise<{
45
+ identity: Identity;
46
+ keys: Keys;
47
+ }>;
48
+ /**
49
+ * Unlocks the wallet by decrypting the keystore and deriving keys for a blockchain.
50
+ * @param options - Unlock options including password, chainId, and optional duration
51
+ * @returns Promise resolving to the derived keys
52
+ * @throws {Error} If password is incorrect or no identity is selected
53
+ */
54
+ unlock: (options: UnlockOptions) => Promise<{
55
+ keys: Keys;
56
+ }>;
57
+ /**
58
+ * Locks the wallet and clears all keys from memory.
59
+ * The encrypted keystore remains in IndexedDB.
60
+ * @returns Promise that resolves when wallet is locked
61
+ */
62
+ lock: () => Promise<void>;
63
+ /**
64
+ * Switches to a different blockchain while preserving the same identity.
65
+ * @param chainId - Target blockchain identifier
66
+ * @param password - Optional password if wallet is locked
67
+ * @returns Promise resolving to keys for the new chain
68
+ * @throws {Error} If locked without password or adapter not registered
69
+ */
70
+ switchChain: (chainId: string, password?: string) => Promise<{
71
+ keys: Keys;
72
+ }>;
73
+ /**
74
+ * Rotates to a new set of keys at the next address index or custom path.
75
+ * Preserves key expiration times from current session.
76
+ * @param newDerivationPath - Optional custom BIP44 path (defaults to next index)
77
+ * @returns Promise resolving to the new keys
78
+ * @throws {Error} If wallet is locked
79
+ */
80
+ rotateKeys: (newDerivationPath?: string) => Promise<{
81
+ keys: Keys;
82
+ }>;
83
+ /**
84
+ * Derives a one-time key at a custom BIP44 path without storing it in the session.
85
+ * Useful for signing with different addresses or accounts.
86
+ * @param options - Derivation options with custom path
87
+ * @returns Promise resolving to the derived key data
88
+ * @throws {Error} If wallet is locked
89
+ */
90
+ deriveKey: (options: DeriveKeyOptions) => Promise<{
91
+ privateKey: string;
92
+ publicKey: string;
93
+ address: string;
94
+ path: string;
95
+ }>;
96
+ /**
97
+ * Derives a deterministic document ID using BIP44-style hierarchical derivation.
98
+ * Returns a hex-encoded ID (32 bytes / 64 hex characters).
99
+ * Path: m/44'/[appId]'/[account]'/[purpose]/[index]
100
+ * @param options - BIP44 derivation parameters (appId required, others default to 0)
101
+ * @returns Promise resolving to hex-encoded document ID (64 characters)
102
+ * @throws {Error} If wallet is locked or parameters are out of range
103
+ */
104
+ deriveBIP44DocumentID: (options: {
105
+ appId: number;
106
+ account?: number;
107
+ purpose?: number;
108
+ index?: number;
109
+ }) => Promise<string>;
110
+ /**
111
+ * Derives a data encryption key using HKDF for encrypting/decrypting data.
112
+ * This key is deterministic (derived from mnemonic) and chain-independent.
113
+ * Perfect for document encryption, file storage, etc.
114
+ *
115
+ * @param options - Derivation options including purpose, version, algorithm
116
+ * @returns CryptoKey ready for use with Web Crypto API
117
+ *
118
+ * @example
119
+ * ```typescript
120
+ * const key = await auth.deriveDataEncryptionKey({
121
+ * purpose: 'automerge-documents',
122
+ * version: 1,
123
+ * });
124
+ *
125
+ * // Use with Web Crypto API
126
+ * const encrypted = await crypto.subtle.encrypt(
127
+ * { name: 'AES-GCM', iv },
128
+ * key,
129
+ * data
130
+ * );
131
+ * ```
132
+ */
133
+ deriveDataEncryptionKey: (options: DeriveDataKeyOptions) => Promise<CryptoKey>;
134
+ /**
135
+ * Gets the address for a specific blockchain at a given index.
136
+ * @param chainId - Blockchain identifier
137
+ * @param index - Address index (default: 0)
138
+ * @returns Promise resolving to address, public key, and derivation path
139
+ * @throws {Error} If wallet is locked or adapter not registered
140
+ */
141
+ getAddressForChain: (chainId: string, index?: number) => Promise<{
142
+ address: string;
143
+ publicKey: string;
144
+ derivationPath: string;
145
+ }>;
146
+ /**
147
+ * Verify password without unlocking wallet
148
+ * Useful for transaction confirmation
149
+ * @param password - Password to verify
150
+ * @returns Promise resolving to true if password is correct
151
+ */
152
+ verifyPassword: (password: string) => Promise<boolean>;
153
+ /**
154
+ * Signs a message using the current or specified private key.
155
+ * Performs soft expiration check (warns but doesn't block).
156
+ * @param options - Message and optional derivation path
157
+ * @returns Promise resolving to signature, address, and public key
158
+ * @throws {Error} If wallet is locked
159
+ */
160
+ signMessage: (options: SignMessageOptions) => Promise<{
161
+ signature: string;
162
+ address: string;
163
+ publicKey: string;
164
+ }>;
165
+ /**
166
+ * Signs a blockchain transaction using the current or specified private key.
167
+ * Performs soft expiration check (warns but doesn't block).
168
+ * @param options - Transaction object and optional derivation path
169
+ * @returns Promise resolving to signed transaction and signature
170
+ * @throws {Error} If wallet is locked
171
+ */
172
+ signTransaction: (options: SignTransactionOptions) => Promise<{
173
+ signedTransaction: any;
174
+ signature: string;
175
+ }>;
176
+ /**
177
+ * Verifies a signature against a message and public key using the current adapter.
178
+ * @param message - Message that was signed (string or bytes)
179
+ * @param signature - Signature to verify
180
+ * @param publicKey - Public key to verify against
181
+ * @returns Promise resolving to true if signature is valid
182
+ * @throws {Error} If no adapter is selected
183
+ */
184
+ verifySignature: (message: string | Uint8Array, signature: string, publicKey: string) => Promise<boolean>;
185
+ /**
186
+ * Lists all identities stored in IndexedDB.
187
+ * @returns Promise resolving to array of all identities
188
+ */
189
+ listIdentities: () => Promise<Array<Identity>>;
190
+ /**
191
+ * Switches to a different identity. Locks the current wallet first.
192
+ * @param identityId - ID of the identity to switch to
193
+ * @returns Promise resolving to the selected identity
194
+ * @throws {Error} If identity not found
195
+ */
196
+ switchIdentity: (identityId: string) => Promise<{
197
+ identity: Identity;
198
+ }>;
199
+ /**
200
+ * Updates the label or metadata for an identity.
201
+ * @param identityId - ID of the identity to update
202
+ * @param updates - Label and/or metadata to update
203
+ * @returns Promise resolving to the updated identity
204
+ * @throws {Error} If identity not found
205
+ */
206
+ updateIdentity: (identityId: string, updates: {
207
+ label?: string;
208
+ metadata?: Record<string, any>;
209
+ }) => Promise<{
210
+ identity: Identity;
211
+ }>;
212
+ /**
213
+ * Permanently deletes an identity from IndexedDB. Requires password verification.
214
+ * Locks wallet if deleting current identity.
215
+ * @param identityId - ID of the identity to delete
216
+ * @param password - Password to verify ownership
217
+ * @returns Promise that resolves when deleted
218
+ * @throws {Error} If identity not found or password incorrect
219
+ */
220
+ deleteIdentity: (identityId: string, password: string) => Promise<void>;
221
+ /**
222
+ * Changes the password for an identity's encrypted keystore.
223
+ * Re-encrypts the mnemonic with the new password.
224
+ * @param identityId - ID of the identity
225
+ * @param oldPassword - Current password
226
+ * @param newPassword - New password
227
+ * @returns Promise that resolves when password is changed
228
+ * @throws {Error} If identity not found or old password incorrect
229
+ */
230
+ changePassword: (identityId: string, oldPassword: string, newPassword: string) => Promise<void>;
231
+ /**
232
+ * Exports the mnemonic phrase for an identity.
233
+ * Requires password verification to decrypt the keystore.
234
+ * ⚠️ Security: Only export mnemonics to secure locations (password managers, paper backup).
235
+ * @param identityId - ID of the identity to export
236
+ * @param password - Password to decrypt the keystore
237
+ * @returns Promise resolving to the mnemonic phrase
238
+ * @throws {Error} If identity not found or password incorrect
239
+ */
240
+ exportMnemonic: (identityId: string, password: string) => Promise<string>;
241
+ /**
242
+ * Exports the encrypted keystore JSON for an identity.
243
+ * No password required - keystore is already encrypted.
244
+ * Perfect for encrypted backup files.
245
+ * @param identityId - ID of the identity to export
246
+ * @returns Promise resolving to encrypted keystore JSON string
247
+ * @throws {Error} If identity not found
248
+ */
249
+ exportKeystore: (identityId: string) => Promise<string>;
250
+ /**
251
+ * Exports the complete StoredIdentity object including metadata.
252
+ * No password required - keystore within is already encrypted.
253
+ * Perfect for migrating identities between devices/browsers with all metadata intact.
254
+ * @param identityId - ID of the identity to export
255
+ * @returns Promise resolving to complete StoredIdentity object
256
+ * @throws {Error} If identity not found
257
+ */
258
+ exportIdentity: (identityId: string) => Promise<StoredIdentity>;
259
+ /**
260
+ * Imports an identity from a mnemonic phrase.
261
+ * Creates and encrypts a new identity in IndexedDB with the provided password.
262
+ * @param mnemonic - BIP39 mnemonic phrase (12 or 24 words)
263
+ * @param password - Password to encrypt the new identity
264
+ * @param label - Optional label for the wallet (default: "Imported Wallet")
265
+ * @returns Promise resolving to the created identity
266
+ * @throws {Error} If mnemonic is invalid
267
+ */
268
+ importMnemonic: (mnemonic: string, password: string, label?: string) => Promise<{
269
+ identity: Identity;
270
+ }>;
271
+ /**
272
+ * Imports an identity from an encrypted keystore JSON.
273
+ * Decrypts the keystore and creates a new identity in IndexedDB.
274
+ * @param keystoreJson - Encrypted keystore JSON string
275
+ * @param password - Password to decrypt the keystore
276
+ * @param label - Optional label for the wallet (default: "Imported Wallet")
277
+ * @returns Promise resolving to the created identity
278
+ * @throws {Error} If keystore is invalid or password incorrect
279
+ */
280
+ importKeystore: (keystoreJson: string, password: string, label?: string) => Promise<{
281
+ identity: Identity;
282
+ }>;
283
+ /**
284
+ * Imports a complete StoredIdentity object.
285
+ * No password required - keystore is already encrypted.
286
+ * Perfect for migrating identities between devices/browsers with all metadata intact.
287
+ * Note: This will overwrite any existing identity with the same ID.
288
+ * @param storedIdentity - Complete StoredIdentity object to import
289
+ * @returns Promise resolving to the imported identity
290
+ * @throws {Error} If stored identity data is invalid
291
+ */
292
+ importIdentity: (storedIdentity: StoredIdentity) => Promise<{
293
+ identity: Identity;
294
+ }>;
295
+ /**
296
+ * Gets multiple addresses for a blockchain starting from a specific index.
297
+ * @param chainId - Blockchain identifier
298
+ * @param start - Starting index (default: 0)
299
+ * @param count - Number of addresses to generate (default: 20)
300
+ * @returns Promise resolving to array of addresses with paths
301
+ * @throws {Error} If wallet is locked or adapter not registered
302
+ */
303
+ getAddresses: (chainId: string, start?: number, count?: number) => Promise<Array<{
304
+ address: string;
305
+ path: string;
306
+ index: number;
307
+ }>>;
308
+ /**
309
+ * Finds all used addresses by checking balances with BIP44 gap limit of 20.
310
+ * Useful for account discovery when restoring wallets.
311
+ * @param chainId - Blockchain identifier
312
+ * @param checkBalance - Function that returns true if address has balance
313
+ * @returns Promise resolving to array of used addresses
314
+ * @throws {Error} If wallet is locked or adapter not registered
315
+ */
316
+ findUsedAddresses: (chainId: string, checkBalance: (address: string) => Promise<boolean>) => Promise<Array<{
317
+ address: string;
318
+ path: string;
319
+ index: number;
320
+ }>>;
321
+ /**
322
+ * Subscribes to authentication state changes.
323
+ * @param callback - Function called on each auth event with event type and keys
324
+ * @returns Unsubscribe function
325
+ */
326
+ onAuthStateChange: (callback: AuthChangeCallback) => (() => void);
327
+ /** Gets the current active identity, or null if none selected. */
328
+ get currentIdentity(): Identity | null;
329
+ /** Gets the current derived keys, or null if wallet is locked. */
330
+ get currentKeys(): Keys | null;
331
+ /** Gets the current blockchain, or null if none selected. */
332
+ get currentChain(): Chain | null;
333
+ /** Gets the current blockchain address, or null if locked. */
334
+ get currentAddress(): string | null;
335
+ /** Gets the current public key as hex string, or null if locked. */
336
+ get currentPublicKey(): string | null;
337
+ /** Gets the key expiration date, or null if no expiration set. */
338
+ get currentExpiresAt(): Date | null;
339
+ /** Gets the remaining seconds until key expiration, or null if no expiration set. */
340
+ get currentExpiresIn(): number | null;
341
+ /** Returns true if wallet is locked (keys cleared from memory). */
342
+ get isLocked(): boolean;
343
+ /** Returns true if wallet is unlocked with active keys. */
344
+ get isUnlocked(): boolean;
345
+ /** Returns true if an identity has been created or selected. */
346
+ get hasIdentity(): boolean;
347
+ /**
348
+ * Gets the chain-independent master public key (33 bytes, compressed secp256k1).
349
+ * Safe to expose publicly - does NOT include chaincode.
350
+ * Perfect for document ownership and cross-chain identity verification.
351
+ * @returns Hex-encoded master public key, or null if locked
352
+ */
353
+ get masterPublicKey(): string | null;
354
+ private isKeysExpired;
355
+ private checkKeysExpiration;
356
+ private deriveKeysWithAdapter;
357
+ private notifyListeners;
358
+ private setAutoLockTimer;
359
+ }
360
+ declare const createAuthClient: () => AuthClient;
361
+ interface StoredIdentity {
362
+ id: string;
363
+ fingerprint: string;
364
+ publicKey: string;
365
+ label?: string;
366
+ metadata: Record<string, any>;
367
+ keystore: string;
368
+ createdAt: string;
369
+ lastAccess?: string;
370
+ }
371
+
372
+ export { AuthClient, createAuthClient };