w3pk 0.9.2 → 0.10.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/README.md CHANGED
@@ -52,6 +52,7 @@ const endpoints = await w3pk.getEndpoints(1)
52
52
  - EIP-1193 provider for ethers, viem, wagmi, RainbowKit (`getEIP1193Provider`)
53
53
  - ERC-5564 stealth addresses (opt-in)
54
54
  - ZK primitives (zero-knowledge proof generation and verification)
55
+ - Post-quantum encryption (ML-KEM-1024/Kyber NIST FIPS 203)
55
56
  - Chainlist support (2390+ networks)
56
57
  - EIP-7702 network detection (329+ networks)
57
58
  - External wallet integration (delegate MetaMask/Ledger to w3pk via EIP-7702)
@@ -337,6 +338,15 @@ if (result.isForUser) {
337
338
  const myPayments = await w3pk.stealth?.scanAnnouncements(announcements)
338
339
  ```
339
340
 
341
+ ### ML-KEM encryption
342
+
343
+ ```typescript
344
+ // Encrypt with post-quantum security (NIST FIPS 203)
345
+ const pubKey = await w3pk.deriveMLKemPublicKey()
346
+ const encrypted = await w3pk.mlkemEncrypt('secret', [pubKey])
347
+ const plaintext = await w3pk.mlkemDecrypt(encrypted)
348
+ ```
349
+
340
350
  ### Backup & Recovery
341
351
 
342
352
  ```typescript
@@ -355,8 +365,13 @@ console.log('Security Score:', status.securityScore.total) // 0-100
355
365
  // Create encrypted backup file
356
366
  const { blob, filename } = await w3pk.createBackupFile('password', password)
357
367
 
358
- // Setup social recovery (M-of-N guardians)
359
- await w3pk.setupSocialRecovery(
368
+ // Setup social recovery (M-of-N guardians) - guardians store backup file fragments
369
+ import { SocialRecoveryManager } from 'w3pk'
370
+ const backupFileJson = await blob.text()
371
+ const socialRecovery = new SocialRecoveryManager()
372
+ const guardians = await socialRecovery.setupSocialRecovery(
373
+ backupFileJson,
374
+ w3pk.user.ethereumAddress,
360
375
  [
361
376
  { name: 'Alice', email: 'alice@example.com' },
362
377
  { name: 'Bob', phone: '+1234567890' },
@@ -366,10 +381,11 @@ await w3pk.setupSocialRecovery(
366
381
  )
367
382
 
368
383
  // Generate guardian invite
369
- const invite = await w3pk.generateGuardianInvite(guardianShare)
384
+ const invite = await socialRecovery.generateGuardianInvite(guardians[0])
370
385
 
371
- // Recover from guardian shares
372
- const { mnemonic } = await w3pk.recoverFromGuardians([share1, share2])
386
+ // Recover from guardian shares - reconstructs encrypted backup file
387
+ const { backupFileJson } = await socialRecovery.recoverFromGuardians([share1, share2])
388
+ await w3pk.registerWithBackupFile(backupFileJson, password, 'username')
373
389
 
374
390
  // Restore from backup file
375
391
  await w3pk.restoreFromBackupFile(encryptedData, password)
package/dist/index.d.mts CHANGED
@@ -1016,6 +1016,111 @@ declare class Web3Passkey {
1016
1016
  * @param hours - Duration in hours
1017
1017
  */
1018
1018
  setSessionDuration(hours: number): void;
1019
+ /**
1020
+ * Derive ML-KEM-1024 public key from the current wallet
1021
+ *
1022
+ * Returns the public key that can be shared with others for encryption.
1023
+ * The keypair is derived deterministically from the wallet's private key.
1024
+ *
1025
+ * @param options - Optional configuration
1026
+ * @param options.context - Context string for domain separation (default: 'mlkem-v1')
1027
+ * @param options.mode - Security mode (default: 'YOLO' to access private key)
1028
+ * @param options.tag - Tag for address derivation (default: 'MAIN')
1029
+ * @param options.origin - Origin for derivation (default: current origin)
1030
+ * @param options.requireAuth - Force WebAuthn re-authentication
1031
+ * @returns Base64-encoded ML-KEM public key (1568 bytes)
1032
+ *
1033
+ * @example
1034
+ * ```typescript
1035
+ * const w3pk = createWeb3Passkey();
1036
+ * await w3pk.login();
1037
+ *
1038
+ * const publicKey = await w3pk.deriveMLKemPublicKey();
1039
+ * // Share publicKey with others so they can encrypt data for you
1040
+ * ```
1041
+ */
1042
+ deriveMLKemPublicKey(options?: {
1043
+ context?: string;
1044
+ mode?: SecurityMode;
1045
+ tag?: string;
1046
+ origin?: string;
1047
+ requireAuth?: boolean;
1048
+ }): Promise<string>;
1049
+ /**
1050
+ * Encrypt data using ML-KEM-1024 for self + additional recipients
1051
+ *
1052
+ * Encrypts data such that you (the sender) and specified recipients can decrypt.
1053
+ * Your ML-KEM keypair is derived from your wallet, so you can always decrypt later.
1054
+ *
1055
+ * @param plaintext - The data to encrypt
1056
+ * @param recipientPublicKeys - Array of recipient ML-KEM public keys (base64 strings or Uint8Arrays)
1057
+ * @param options - Optional configuration
1058
+ * @param options.context - Context string for key derivation (default: 'mlkem-v1')
1059
+ * @param options.mode - Security mode (default: 'YOLO' to access private key)
1060
+ * @param options.tag - Tag for address derivation (default: 'MAIN')
1061
+ * @param options.origin - Origin for derivation (default: current origin)
1062
+ * @param options.requireAuth - Force WebAuthn re-authentication
1063
+ * @returns Encrypted payload that can be decrypted by sender or recipients
1064
+ *
1065
+ * @example
1066
+ * ```typescript
1067
+ * const w3pk = createWeb3Passkey();
1068
+ * await w3pk.login();
1069
+ *
1070
+ * // Get server's public key
1071
+ * const serverPubKey = await fetch('/api/mlkem-public-key').then(r => r.text());
1072
+ *
1073
+ * // Encrypt for yourself + server
1074
+ * const encrypted = await w3pk.mlkemEncrypt(
1075
+ * 'my secret data',
1076
+ * [serverPubKey]
1077
+ * );
1078
+ *
1079
+ * // Later: decrypt with the same wallet
1080
+ * const decrypted = await w3pk.mlkemDecrypt(encrypted);
1081
+ * ```
1082
+ */
1083
+ mlkemEncrypt(plaintext: string, recipientPublicKeys: Array<string | Uint8Array>, options?: {
1084
+ context?: string;
1085
+ mode?: SecurityMode;
1086
+ tag?: string;
1087
+ origin?: string;
1088
+ requireAuth?: boolean;
1089
+ }): Promise<any>;
1090
+ /**
1091
+ * Decrypt ML-KEM encrypted data using current wallet
1092
+ *
1093
+ * Decrypts data that was encrypted for this wallet.
1094
+ * The ML-KEM keypair is derived from your wallet's private key.
1095
+ *
1096
+ * @param payload - The encrypted payload (from mlkemEncrypt)
1097
+ * @param options - Optional configuration
1098
+ * @param options.context - Context string for key derivation (default: 'mlkem-v1', must match encryption)
1099
+ * @param options.mode - Security mode (default: 'YOLO' to access private key)
1100
+ * @param options.tag - Tag for address derivation (default: 'MAIN')
1101
+ * @param options.origin - Origin for derivation (default: current origin)
1102
+ * @param options.requireAuth - Force WebAuthn re-authentication
1103
+ * @returns Decrypted plaintext
1104
+ *
1105
+ * @example
1106
+ * ```typescript
1107
+ * const w3pk = createWeb3Passkey();
1108
+ * await w3pk.login();
1109
+ *
1110
+ * // Retrieve encrypted data
1111
+ * const encrypted = await fetch('/api/my-data').then(r => r.json());
1112
+ *
1113
+ * // Decrypt locally (server never sees plaintext!)
1114
+ * const plaintext = await w3pk.mlkemDecrypt(encrypted);
1115
+ * ```
1116
+ */
1117
+ mlkemDecrypt(payload: any, options?: {
1118
+ context?: string;
1119
+ mode?: SecurityMode;
1120
+ tag?: string;
1121
+ origin?: string;
1122
+ requireAuth?: boolean;
1123
+ }): Promise<string>;
1019
1124
  }
1020
1125
 
1021
1126
  /**
@@ -1209,6 +1314,14 @@ interface AuthenticationCredential {
1209
1314
  signature: ArrayBuffer;
1210
1315
  userHandle?: ArrayBuffer;
1211
1316
  };
1317
+ getClientExtensionResults(): {
1318
+ prf?: {
1319
+ results?: {
1320
+ first?: ArrayBuffer;
1321
+ second?: ArrayBuffer;
1322
+ };
1323
+ };
1324
+ };
1212
1325
  }
1213
1326
 
1214
1327
  /**
@@ -1753,6 +1866,93 @@ interface RecoveryProgress {
1753
1866
  canRecover: boolean;
1754
1867
  }
1755
1868
 
1869
+ /**
1870
+ * Social Recovery Manager
1871
+ * Manages guardian-based wallet recovery using Shamir Secret Sharing
1872
+ */
1873
+
1874
+ declare class SocialRecoveryManager {
1875
+ private storageKey;
1876
+ /**
1877
+ * Get storage (localStorage or in-memory fallback)
1878
+ */
1879
+ private getItem;
1880
+ /**
1881
+ * Set storage (localStorage or in-memory fallback)
1882
+ */
1883
+ private setItem;
1884
+ /**
1885
+ * Set up social recovery
1886
+ * Splits encrypted backup file into M-of-N shares and distributes to guardians
1887
+ *
1888
+ * @param backupFileJson - The complete backup file JSON string (password-encrypted)
1889
+ * @param ethereumAddress - The Ethereum address for verification
1890
+ * @param guardians - Array of guardian information
1891
+ * @param threshold - Minimum number of guardians needed for recovery
1892
+ */
1893
+ setupSocialRecovery(backupFileJson: string, ethereumAddress: string, guardians: {
1894
+ name: string;
1895
+ email?: string;
1896
+ phone?: string;
1897
+ }[], threshold: number): Promise<Guardian[]>;
1898
+ /**
1899
+ * Get current social recovery configuration
1900
+ */
1901
+ getSocialRecoveryConfig(): SocialRecoveryConfig | null;
1902
+ /**
1903
+ * Generate guardian invitation
1904
+ * Creates QR code and educational materials for guardian
1905
+ */
1906
+ generateGuardianInvite(guardian: Guardian): Promise<GuardianInvite>;
1907
+ /**
1908
+ * Generate QR code from share data
1909
+ * Uses 'qrcode' library if available, falls back to canvas text
1910
+ */
1911
+ private generateQRCode;
1912
+ /**
1913
+ * Create fallback QR representation
1914
+ */
1915
+ private createPlaceholderQR;
1916
+ /**
1917
+ * Wrap text for display
1918
+ */
1919
+ private wrapText;
1920
+ /**
1921
+ * Get guardian explainer text
1922
+ */
1923
+ private getGuardianExplainer;
1924
+ /**
1925
+ * Recover backup file from guardian shares
1926
+ * Returns the reconstructed backup file JSON that can be used with restoreFromBackupFile()
1927
+ */
1928
+ recoverFromGuardians(shareData: string[]): Promise<{
1929
+ backupFileJson: string;
1930
+ ethereumAddress: string;
1931
+ }>;
1932
+ /**
1933
+ * Get recovery progress
1934
+ */
1935
+ getRecoveryProgress(collectedShares: string[]): RecoveryProgress;
1936
+ /**
1937
+ * Mark guardian as verified
1938
+ * Note: This updates guardian status but does NOT automatically refresh security score.
1939
+ * The security score will be updated on the next call to BackupManager.getBackupStatus()
1940
+ */
1941
+ markGuardianVerified(guardianId: string): void;
1942
+ /**
1943
+ * Revoke a guardian
1944
+ */
1945
+ revokeGuardian(guardianId: string): void;
1946
+ /**
1947
+ * Add new guardian (requires re-sharing with new backup file)
1948
+ */
1949
+ addGuardian(backupFileJson: string, newGuardian: {
1950
+ name: string;
1951
+ email?: string;
1952
+ phone?: string;
1953
+ }): Promise<Guardian>;
1954
+ }
1955
+
1756
1956
  /**
1757
1957
  * Cross-Device Sync Type Definitions
1758
1958
  */
@@ -1980,6 +2180,105 @@ declare function inspect(options?: BrowserInspectOptions): Promise<BrowserInspec
1980
2180
  */
1981
2181
  declare function inspectNow(options?: BrowserInspectOptions): Promise<void>;
1982
2182
 
2183
+ interface MLKemKeypair {
2184
+ publicKey: Uint8Array;
2185
+ privateKey: Uint8Array;
2186
+ }
2187
+ interface EncryptedPayload {
2188
+ recipients: Array<{
2189
+ publicKey: string;
2190
+ ciphertext: string;
2191
+ }>;
2192
+ encryptedData: string;
2193
+ iv: string;
2194
+ authTag: string;
2195
+ }
2196
+ /**
2197
+ * Derive deterministic ML-KEM-1024 keypair from any private key material
2198
+ *
2199
+ * Uses HKDF-SHA256 to derive a 64-byte seed from the input key material,
2200
+ * then generates a reproducible ML-KEM-1024 keypair.
2201
+ *
2202
+ * @param privateKey - Private key material (hex string with optional 0x prefix, or Uint8Array)
2203
+ * @param context - Context string for domain separation (default: 'mlkem-v1')
2204
+ * @returns ML-KEM-1024 keypair (publicKey: 1568 bytes, privateKey: 3168 bytes)
2205
+ *
2206
+ * @example
2207
+ * ```typescript
2208
+ * // Derive from Ethereum private key
2209
+ * const ethPrivateKey = '0x1234...';
2210
+ * const keypair = await deriveMLKemKeypair(ethPrivateKey, 'my-app');
2211
+ *
2212
+ * // Derive from any 32-byte key
2213
+ * const randomKey = crypto.getRandomValues(new Uint8Array(32));
2214
+ * const keypair2 = await deriveMLKemKeypair(randomKey);
2215
+ * ```
2216
+ */
2217
+ declare function deriveMLKemKeypair(privateKey: string | Uint8Array, context?: string): Promise<MLKemKeypair>;
2218
+ /**
2219
+ * Encrypt data using ML-KEM-1024 + AES-256-GCM for multiple recipients
2220
+ *
2221
+ * @param plaintext - The data to encrypt
2222
+ * @param publicKeys - Array of ML-KEM-1024 public keys (base64 strings or Uint8Arrays, 1568 bytes each)
2223
+ * @returns Encrypted payload with per-recipient ciphertexts and shared encrypted data
2224
+ */
2225
+ declare function mlkemEncrypt(plaintext: string, publicKeys: (string | Uint8Array) | Array<string | Uint8Array>): Promise<EncryptedPayload>;
2226
+ /**
2227
+ * Decrypt data encrypted with mlkemEncrypt()
2228
+ *
2229
+ * @param payload - The encrypted payload
2230
+ * @param privateKey - ML-KEM-1024 private key (base64 string or Uint8Array, 3168 bytes)
2231
+ * @param publicKey - Optional: Your public key to find the correct recipient entry (base64 string or Uint8Array, 1568 bytes)
2232
+ * @returns Decrypted plaintext
2233
+ */
2234
+ declare function mlkemDecrypt(payload: EncryptedPayload, privateKey: string | Uint8Array, publicKey?: string | Uint8Array): Promise<string>;
2235
+ /**
2236
+ * Encrypt data with ML-KEM using derived keypairs from private keys
2237
+ *
2238
+ * This is a convenience function that derives ML-KEM keypairs from private key material,
2239
+ * then encrypts the data for all recipients. The sender's keypair is derived and used
2240
+ * as one of the recipients.
2241
+ *
2242
+ * @param plaintext - The data to encrypt
2243
+ * @param senderPrivateKey - Sender's private key (hex string or Uint8Array)
2244
+ * @param recipientPublicKeys - Array of recipient ML-KEM public keys (from deriveMLKemKeypair)
2245
+ * @param senderContext - Context for sender's key derivation (default: 'mlkem-v1')
2246
+ * @returns Encrypted payload with sender + recipients
2247
+ *
2248
+ * @example
2249
+ * ```typescript
2250
+ * // Encrypt for yourself + server
2251
+ * const serverKeypair = await deriveMLKemKeypair(serverPrivateKey, 'server');
2252
+ * const encrypted = await mlkemEncryptWithKey(
2253
+ * 'secret data',
2254
+ * myEthPrivateKey,
2255
+ * [serverKeypair.publicKey]
2256
+ * );
2257
+ * ```
2258
+ */
2259
+ declare function mlkemEncryptWithKey(plaintext: string, senderPrivateKey: string | Uint8Array, recipientPublicKeys: Array<string | Uint8Array>, senderContext?: string): Promise<EncryptedPayload>;
2260
+ /**
2261
+ * Decrypt data with ML-KEM using a derived keypair from private key
2262
+ *
2263
+ * This is a convenience function that derives an ML-KEM keypair from private key material,
2264
+ * then decrypts the payload.
2265
+ *
2266
+ * @param payload - The encrypted payload
2267
+ * @param privateKey - Private key material (hex string or Uint8Array)
2268
+ * @param context - Context for key derivation (default: 'mlkem-v1')
2269
+ * @returns Decrypted plaintext
2270
+ *
2271
+ * @example
2272
+ * ```typescript
2273
+ * // Decrypt with your Ethereum private key
2274
+ * const plaintext = await mlkemDecryptWithKey(
2275
+ * encryptedPayload,
2276
+ * myEthPrivateKey
2277
+ * );
2278
+ * ```
2279
+ */
2280
+ declare function mlkemDecryptWithKey(payload: EncryptedPayload, privateKey: string | Uint8Array, context?: string): Promise<string>;
2281
+
1983
2282
  declare function createWeb3Passkey(config?: Web3PasskeyConfig): Web3Passkey;
1984
2283
 
1985
- export { ApiError, AuthenticationError, type BackupStatus, type BrowserInspectOptions, type BrowserInspectResult, CryptoError, DEFAULT_MODE, DEFAULT_TAG, type DeviceInfo, type EIP1193Provider, type EIP7702Authorization, type EncryptedBackupInfo, type Guardian, type GuardianInvite, type PasskeySelectionResult, type QRBackupOptions, type RecoveryProgress, type RecoveryScenario, type RecoveryShare, RecoverySimulator, RegistrationError, type SecurityScore, type SignAuthorizationParams, type SimulationResult, type SiweMessage, type SocialRecoveryConfig, type StealthAddressConfig, StealthAddressModule, type StealthAddressResult, type StealthKeys, StorageError, type SyncCapabilities, type SyncStatus, type SyncVault, type UserInfo, WalletError, type WalletInfo, Web3Passkey, type Web3PasskeyConfig, Web3PasskeyError, arrayBufferToBase64Url, assertEthereumAddress, assertMnemonic, assertUsername, authenticateWithPasskey, base64ToArrayBuffer, base64UrlDecode, base64UrlToArrayBuffer, canControlStealthAddress, checkStealthAddress, clearCache, computeStealthPrivateKey, createSiweMessage, createWalletFromMnemonic, createWeb3Passkey, createWeb3Passkey as default, deriveAddressFromP256PublicKey, deriveIndexFromOriginModeAndTag, deriveStealthKeys, deriveWalletFromMnemonic, detectWalletProvider, encodeEIP7702AuthorizationMessage, extractRS, generateBIP39Wallet, generateSiweNonce, generateStealthAddress, getAllChains, getAllTopics, getChainById, getCurrentBuildHash, getCurrentOrigin, getDefaultProvider, getEndpoints, getExplainer, getOriginSpecificAddress, getPackageVersion, getW3pkBuildHash, hashEIP7702AuthorizationMessage, inspect, inspectNow, isStrongPassword, normalizeOrigin, parseSiweMessage, promptPasskeySelection, requestExternalWalletAuthorization, safeAtob, safeBtoa, searchExplainers, supportsEIP7702Authorization, validateEthereumAddress, validateMnemonic, validateSiweMessage, validateUsername, verifyBuildHash, verifyEIP7702Authorization, verifySiweSignature };
2284
+ export { ApiError, AuthenticationError, type BackupStatus, type BrowserInspectOptions, type BrowserInspectResult, CryptoError, DEFAULT_MODE, DEFAULT_TAG, type DeviceInfo, type EIP1193Provider, type EIP7702Authorization, type EncryptedBackupInfo, type EncryptedPayload, type Guardian, type GuardianInvite, type MLKemKeypair, type PasskeySelectionResult, type QRBackupOptions, type RecoveryProgress, type RecoveryScenario, type RecoveryShare, RecoverySimulator, RegistrationError, type SecurityScore, type SignAuthorizationParams, type SimulationResult, type SiweMessage, type SocialRecoveryConfig, SocialRecoveryManager, type StealthAddressConfig, StealthAddressModule, type StealthAddressResult, type StealthKeys, StorageError, type SyncCapabilities, type SyncStatus, type SyncVault, type UserInfo, WalletError, type WalletInfo, Web3Passkey, type Web3PasskeyConfig, Web3PasskeyError, arrayBufferToBase64Url, assertEthereumAddress, assertMnemonic, assertUsername, authenticateWithPasskey, base64ToArrayBuffer, base64UrlDecode, base64UrlToArrayBuffer, canControlStealthAddress, checkStealthAddress, clearCache, computeStealthPrivateKey, createSiweMessage, createWalletFromMnemonic, createWeb3Passkey, createWeb3Passkey as default, deriveAddressFromP256PublicKey, deriveIndexFromOriginModeAndTag, deriveMLKemKeypair, deriveStealthKeys, deriveWalletFromMnemonic, detectWalletProvider, encodeEIP7702AuthorizationMessage, extractRS, generateBIP39Wallet, generateSiweNonce, generateStealthAddress, getAllChains, getAllTopics, getChainById, getCurrentBuildHash, getCurrentOrigin, getDefaultProvider, getEndpoints, getExplainer, getOriginSpecificAddress, getPackageVersion, getW3pkBuildHash, hashEIP7702AuthorizationMessage, inspect, inspectNow, isStrongPassword, mlkemDecrypt, mlkemDecryptWithKey, mlkemEncrypt, mlkemEncryptWithKey, normalizeOrigin, parseSiweMessage, promptPasskeySelection, requestExternalWalletAuthorization, safeAtob, safeBtoa, searchExplainers, supportsEIP7702Authorization, validateEthereumAddress, validateMnemonic, validateSiweMessage, validateUsername, verifyBuildHash, verifyEIP7702Authorization, verifySiweSignature };