@talismn/keyring 1.0.12 → 2.0.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/index.mjs CHANGED
@@ -1,477 +1,390 @@
1
- // src/keyring/Keyring.ts
2
- import {
3
- addressEncodingFromCurve,
4
- addressFromPublicKey,
5
- base58,
6
- blake3,
7
- deriveKeypair,
8
- entropyToMnemonic,
9
- entropyToSeed,
10
- getPublicKeyFromSecret,
11
- isAddressEqual,
12
- isValidMnemonic,
13
- mnemonicToEntropy,
14
- normalizeAddress,
15
- utf8
16
- } from "@talismn/crypto";
17
-
18
- // src/types/utils.ts
19
- import {
20
- detectAddressEncoding,
21
- getAccountPlatformFromAddress,
22
- getAccountPlatformFromCurve,
23
- isBitcoinAddress,
24
- isEthereumAddress,
25
- isSolanaAddress
26
- } from "@talismn/crypto";
27
- var isAccountOfType = (account, type) => {
28
- return account?.type === type;
1
+ import { addressEncodingFromCurve, addressFromPublicKey, base58, blake3, deriveKeypair, detectAddressEncoding, entropyToMnemonic, entropyToSeed, getAccountPlatformFromAddress, getAccountPlatformFromCurve, getPublicKeyFromSecret, isAddressEqual, isBitcoinAddress, isEthereumAddress, isSolanaAddress, isValidMnemonic, mnemonicToEntropy, normalizeAddress, pbkdf2, utf8 } from "@talismn/crypto";
2
+ //#region src/types/utils.ts
3
+ const isAccountOfType = (account, type) => {
4
+ return account?.type === type;
29
5
  };
30
- var isAccountInTypes = (account, types) => {
31
- return !!account && types.includes(account.type);
6
+ const isAccountInTypes = (account, types) => {
7
+ return !!account && types.includes(account.type);
32
8
  };
33
- var ACCOUNT_TYPES_OWNED = [
34
- "keypair",
35
- "ledger-ethereum",
36
- "ledger-polkadot",
37
- "ledger-solana",
38
- "polkadot-vault"
9
+ const ACCOUNT_TYPES_OWNED = [
10
+ "keypair",
11
+ "ledger-ethereum",
12
+ "ledger-polkadot",
13
+ "ledger-solana",
14
+ "polkadot-vault"
39
15
  ];
40
- var ACCOUNT_TYPES_EXTERNAL = [
41
- "contact",
42
- "watch-only",
43
- "ledger-ethereum",
44
- "ledger-polkadot",
45
- "ledger-solana",
46
- "polkadot-vault",
47
- "signet"
16
+ const ACCOUNT_TYPES_EXTERNAL = [
17
+ "contact",
18
+ "watch-only",
19
+ "ledger-ethereum",
20
+ "ledger-polkadot",
21
+ "ledger-solana",
22
+ "polkadot-vault",
23
+ "signet"
48
24
  ];
49
- var isAccountExternal = (account) => {
50
- return isAccountInTypes(account, ACCOUNT_TYPES_EXTERNAL);
51
- };
52
- var isAccountOwned = (account) => {
53
- return isAccountInTypes(account, ACCOUNT_TYPES_OWNED);
25
+ const isAccountExternal = (account) => {
26
+ return isAccountInTypes(account, ACCOUNT_TYPES_EXTERNAL);
54
27
  };
55
- var isAccountPortfolio = (account) => {
56
- return isAccountOwned(account) || isAccountOfType(account, "watch-only") && account.isPortfolio;
28
+ const isAccountOwned = (account) => {
29
+ return isAccountInTypes(account, ACCOUNT_TYPES_OWNED);
57
30
  };
58
- var isAccountNotContact = (acc) => acc.type !== "contact";
59
- var isAccountAddressEthereum = (account) => {
60
- return !!account && isEthereumAddress(account.address);
31
+ const isAccountPortfolio = (account) => {
32
+ return isAccountOwned(account) || isAccountOfType(account, "watch-only") && account.isPortfolio;
61
33
  };
62
- var isAccountPlatformEthereum = (account) => {
63
- return !!account && account.type !== "ledger-polkadot" && isEthereumAddress(account.address);
34
+ const isAccountNotContact = (acc) => acc.type !== "contact";
35
+ const isAccountAddressEthereum = (account) => {
36
+ return !!account && isEthereumAddress(account.address);
64
37
  };
65
- var isAccountPlatformSolana = (account) => {
66
- return !!account && isSolanaAddress(account.address);
38
+ const isAccountPlatformEthereum = (account) => {
39
+ return !!account && account.type !== "ledger-polkadot" && isEthereumAddress(account.address);
67
40
  };
68
- var isAccountPlatformPolkadot = (account) => {
69
- return !!account && account.type !== "ledger-ethereum" && (isAccountAddressEthereum(account) || isAccountAddressSs58(account));
41
+ const isAccountPlatformSolana = (account) => {
42
+ return !!account && isSolanaAddress(account.address);
70
43
  };
71
- var isAccountAddressSs58 = (account) => {
72
- return !!account && detectAddressEncoding(account.address) === "ss58";
44
+ const isAccountPlatformPolkadot = (account) => {
45
+ return !!account && account.type !== "ledger-ethereum" && (isAccountAddressEthereum(account) || isAccountAddressSs58(account));
73
46
  };
74
- var isAccountLedgerPolkadot = (account) => {
75
- return isAccountOfType(account, "ledger-polkadot");
47
+ const isAccountAddressSs58 = (account) => {
48
+ return !!account && detectAddressEncoding(account.address) === "ss58";
76
49
  };
77
- var isAccountLedgerPolkadotGeneric = (account) => {
78
- return isAccountOfType(account, "ledger-polkadot") && !account.genesisHash;
50
+ const isAccountLedgerPolkadot = (account) => {
51
+ return isAccountOfType(account, "ledger-polkadot");
79
52
  };
80
- var isAccountLedgerPolkadotLegacy = (account) => {
81
- return isAccountOfType(account, "ledger-polkadot") && !!account.genesisHash;
53
+ const isAccountLedgerPolkadotGeneric = (account) => {
54
+ return isAccountOfType(account, "ledger-polkadot") && !account.genesisHash;
82
55
  };
83
- var isAccountBitcoin = (account) => {
84
- return !!account && isBitcoinAddress(account.address);
56
+ const isAccountLedgerPolkadotLegacy = (account) => {
57
+ return isAccountOfType(account, "ledger-polkadot") && !!account.genesisHash;
85
58
  };
86
- var getAccountGenesisHash = (account) => {
87
- if (!account) return void 0;
88
- return "genesisHash" in account ? account.genesisHash || void 0 : void 0;
59
+ const isAccountBitcoin = (account) => {
60
+ return !!account && isBitcoinAddress(account.address);
89
61
  };
90
- var getAccountSignetUrl = (account) => {
91
- return isAccountOfType(account, "signet") ? account.url : void 0;
62
+ const getAccountGenesisHash = (account) => {
63
+ if (!account) return void 0;
64
+ return "genesisHash" in account ? account.genesisHash || void 0 : void 0;
92
65
  };
93
- var getAccountPlatform = (account) => {
94
- if (!account) return void 0;
95
- return "curve" in account ? getAccountPlatformFromCurve(account.curve) : getAccountPlatformFromAddress(account.address);
66
+ const getAccountSignetUrl = (account) => {
67
+ return isAccountOfType(account, "signet") ? account.url : void 0;
96
68
  };
97
-
98
- // src/keyring/encryption.ts
99
- import { pbkdf2 } from "@talismn/crypto";
100
- var deriveKey = async (password, salt) => (
101
- // Deriving 32-byte key using PBKDF2 with 100,000 iterations and SHA-256
102
- await crypto.subtle.importKey(
103
- "raw",
104
- await pbkdf2(
105
- "SHA-256",
106
- new TextEncoder().encode(password),
107
- salt,
108
- 1e5,
109
- // 100,000 iterations
110
- 32
111
- // 32 bytes (32 * 8 == 256 bits)
112
- ),
113
- { name: "AES-GCM", length: 256 },
114
- false,
115
- ["encrypt", "decrypt"]
116
- )
117
- );
118
- var encryptData = async (data, password) => {
119
- try {
120
- const salt = crypto.getRandomValues(new Uint8Array(16));
121
- const iv = crypto.getRandomValues(new Uint8Array(12));
122
- const key = await deriveKey(password, salt);
123
- const encryptedSeed = await crypto.subtle.encrypt(
124
- { name: "AES-GCM", iv },
125
- key,
126
- data
127
- );
128
- const combined = new Uint8Array(salt.length + iv.length + encryptedSeed.byteLength);
129
- combined.set(salt, 0);
130
- combined.set(iv, salt.length);
131
- combined.set(new Uint8Array(encryptedSeed), salt.length + iv.length);
132
- return btoa(String.fromCharCode(...combined));
133
- } catch (cause) {
134
- throw new Error("Failed to encrypt data", { cause });
135
- }
69
+ const getAccountPlatform = (account) => {
70
+ if (!account) return void 0;
71
+ return "curve" in account ? getAccountPlatformFromCurve(account.curve) : getAccountPlatformFromAddress(account.address);
136
72
  };
137
- var decryptData = async (encryptedData, password) => {
138
- try {
139
- const combined = Uint8Array.from(atob(encryptedData), (c) => c.charCodeAt(0));
140
- const salt = combined.slice(0, 16);
141
- const iv = combined.slice(16, 28);
142
- const encryptedSeed = combined.slice(28);
143
- const key = await deriveKey(password, salt);
144
- const decryptedSeed = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, encryptedSeed);
145
- return new Uint8Array(decryptedSeed);
146
- } catch (cause) {
147
- throw new Error("Failed to decrypt data", { cause });
148
- }
73
+ //#endregion
74
+ //#region src/keyring/encryption.ts
75
+ const deriveKey = async (password, salt) => await crypto.subtle.importKey("raw", await pbkdf2("SHA-256", new TextEncoder().encode(password), salt, 1e5, 32), {
76
+ name: "AES-GCM",
77
+ length: 256
78
+ }, false, ["encrypt", "decrypt"]);
79
+ const encryptData = async (data, password) => {
80
+ try {
81
+ const salt = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
82
+ const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
83
+ const key = await deriveKey(password, salt);
84
+ const encryptedSeed = await crypto.subtle.encrypt({
85
+ name: "AES-GCM",
86
+ iv
87
+ }, key, data);
88
+ const combined = new Uint8Array(salt.length + iv.length + encryptedSeed.byteLength);
89
+ combined.set(salt, 0);
90
+ combined.set(iv, salt.length);
91
+ combined.set(new Uint8Array(encryptedSeed), salt.length + iv.length);
92
+ return btoa(String.fromCharCode(...combined));
93
+ } catch (cause) {
94
+ throw new Error("Failed to encrypt data", { cause });
95
+ }
149
96
  };
150
- var changeEncryptedDataPassword = async (encryptedData, oldPassword, newPassword) => {
151
- try {
152
- const decrypted = await decryptData(encryptedData, oldPassword);
153
- return await encryptData(decrypted, newPassword);
154
- } catch (cause) {
155
- throw new Error("Failed to change password on encrypted data", { cause });
156
- }
97
+ const decryptData = async (encryptedData, password) => {
98
+ try {
99
+ const combined = Uint8Array.from(atob(encryptedData), (c) => c.charCodeAt(0));
100
+ const salt = combined.slice(0, 16);
101
+ const iv = combined.slice(16, 28);
102
+ const encryptedSeed = combined.slice(28);
103
+ const key = await deriveKey(password, salt);
104
+ const decryptedSeed = await crypto.subtle.decrypt({
105
+ name: "AES-GCM",
106
+ iv
107
+ }, key, encryptedSeed);
108
+ return new Uint8Array(decryptedSeed);
109
+ } catch (cause) {
110
+ throw new Error("Failed to decrypt data", { cause });
111
+ }
157
112
  };
158
-
159
- // src/keyring/utils.ts
160
- var REGEX_HEX_STRING = /^0x[0-9a-fA-F]*$/;
161
- var isHexString = (value) => {
162
- return typeof value === "string" && REGEX_HEX_STRING.test(value);
113
+ const changeEncryptedDataPassword = async (encryptedData, oldPassword, newPassword) => {
114
+ try {
115
+ const decrypted = await decryptData(encryptedData, oldPassword);
116
+ return await encryptData(decrypted, newPassword);
117
+ } catch (cause) {
118
+ throw new Error("Failed to change password on encrypted data", { cause });
119
+ }
163
120
  };
164
-
165
- // src/keyring/Keyring.ts
166
- var Keyring = class _Keyring {
167
- #data;
168
- constructor(data) {
169
- this.#data = structuredClone(data);
170
- }
171
- static create() {
172
- return new _Keyring({
173
- passwordCheck: null,
174
- // well-known data encrypted using the password, used to ensure all secrets of the keyring are encrypted with the same password
175
- mnemonics: [],
176
- accounts: []
177
- });
178
- }
179
- static load(data) {
180
- if (!data.accounts || !data.mnemonics) throw new Error("Invalid data");
181
- for (const account of data.accounts) {
182
- if (account.type === "ledger-polkadot" && !account.curve) account.curve = "ed25519";
183
- }
184
- return new _Keyring(data);
185
- }
186
- async checkPassword(password, reset = false) {
187
- if (typeof password !== "string" || !password) throw new Error("password is required");
188
- const passwordHash = oneWayHash(password);
189
- const PASSWORD_CHECK_PHRASE = "PASSWORD_CHECK_PHRASE";
190
- if (!this.#data.passwordCheck || reset) {
191
- const bytes = utf8.decode(PASSWORD_CHECK_PHRASE);
192
- this.#data.passwordCheck = await encryptData(bytes, passwordHash);
193
- } else {
194
- try {
195
- const bytes = await decryptData(this.#data.passwordCheck, passwordHash);
196
- const text = utf8.encode(bytes);
197
- if (text !== PASSWORD_CHECK_PHRASE) throw new Error("Invalid password");
198
- } catch {
199
- throw new Error("Invalid password");
200
- }
201
- }
202
- }
203
- /** Returns true if a password has been set on this keyring. */
204
- hasPassword() {
205
- return this.#data.passwordCheck !== null;
206
- }
207
- /**
208
- * Verify a password against the keyring's passwordCheck blob.
209
- * Returns true on success, false on wrong password.
210
- * Throws if no password has been set (caller should check hasPassword() first).
211
- */
212
- async verifyPassword(password) {
213
- if (!this.#data.passwordCheck) {
214
- throw new Error("No password set \u2014 call hasPassword() before verifyPassword()");
215
- }
216
- try {
217
- await this.checkPassword(password);
218
- return true;
219
- } catch {
220
- return false;
221
- }
222
- }
223
- /**
224
- * Initialize the password on a fresh keyring that has no password set.
225
- * Throws if a password is already set (use changePassword flow instead).
226
- */
227
- async initializePassword(password) {
228
- if (this.#data.passwordCheck !== null) {
229
- throw new Error("Password already set \u2014 cannot re-initialize");
230
- }
231
- await this.checkPassword(password, true);
232
- }
233
- toJson() {
234
- return structuredClone(this.#data);
235
- }
236
- async export(password, jsonPassword) {
237
- const keyring = new _Keyring(structuredClone(this.#data));
238
- for (const mnemonic of keyring.#data.mnemonics)
239
- mnemonic.entropy = await changeEncryptedDataPassword(mnemonic.entropy, password, jsonPassword);
240
- for (const account of keyring.#data.accounts)
241
- if (account.type === "keypair")
242
- account.secretKey = await changeEncryptedDataPassword(
243
- account.secretKey,
244
- password,
245
- jsonPassword
246
- );
247
- await keyring.checkPassword(jsonPassword, true);
248
- return keyring.toJson();
249
- }
250
- getMnemonics() {
251
- return this.#data.mnemonics.map(mnemonicFromStorage);
252
- }
253
- async addMnemonic({ name, mnemonic, confirmed }, password) {
254
- if (typeof name !== "string" || !name) throw new Error("name is required");
255
- if (typeof mnemonic !== "string") throw new Error("mnemonic is required");
256
- if (typeof confirmed !== "boolean") throw new Error("confirmed is required");
257
- if (!isValidMnemonic(mnemonic)) throw new Error("Invalid mnemonic");
258
- await this.checkPassword(password);
259
- const entropy = mnemonicToEntropy(mnemonic);
260
- const id = oneWayHash(entropy);
261
- if (this.#data.mnemonics.find((s) => s.id === id)) throw new Error("Mnemonic already exists");
262
- const storage = {
263
- id,
264
- name,
265
- entropy: await encryptData(entropy, password),
266
- confirmed,
267
- createdAt: Date.now()
268
- };
269
- this.#data.mnemonics.push(storage);
270
- return mnemonicFromStorage(storage);
271
- }
272
- getMnemonic(id) {
273
- const mnemonic = this.#data.mnemonics.find((s) => s.id === id);
274
- return mnemonic ? mnemonicFromStorage(mnemonic) : null;
275
- }
276
- updateMnemonic(id, { name, confirmed }) {
277
- const mnemonic = this.#data.mnemonics.find((s) => s.id === id);
278
- if (!mnemonic) throw new Error("Mnemonic not found");
279
- if (name !== void 0) {
280
- if (typeof name !== "string" || !name) throw new Error("name must be a string");
281
- mnemonic.name = name;
282
- }
283
- if (confirmed !== void 0) {
284
- if (typeof confirmed !== "boolean") throw new Error("confirmed must be a boolean");
285
- mnemonic.confirmed = confirmed;
286
- }
287
- return mnemonicFromStorage(mnemonic);
288
- }
289
- removeMnemonic(id) {
290
- const index = this.#data.mnemonics.findIndex((mnemonic) => mnemonic.id === id);
291
- if (index === -1) throw new Error("Mnemonic not found");
292
- this.#data.mnemonics.splice(index, 1);
293
- }
294
- async getMnemonicText(id, password) {
295
- const mnemonic = this.#data.mnemonics.find((s) => s.id === id);
296
- if (!mnemonic) throw new Error("Mnemonic not found");
297
- const entropy = await decryptData(mnemonic.entropy, password);
298
- return entropyToMnemonic(entropy);
299
- }
300
- getExistingMnemonicId(mnemonic) {
301
- const entropy = mnemonicToEntropy(mnemonic);
302
- const mnemonicId = oneWayHash(entropy);
303
- return this.#data.mnemonics.some((s) => s.id === mnemonicId) ? mnemonicId : null;
304
- }
305
- getAccounts() {
306
- return this.#data.accounts.map(accountFromStorage);
307
- }
308
- getAccount(address) {
309
- const account = this.#data.accounts.find((s) => isAddressEqual(s.address, address));
310
- return account ? accountFromStorage(account) : null;
311
- }
312
- updateAccount(address, { name, isPortfolio, genesisHash }) {
313
- const account = this.#data.accounts.find((s) => s.address === address);
314
- if (!account) throw new Error("Account not found");
315
- if (name) {
316
- if (typeof name !== "string" || !name) throw new Error("name is required");
317
- account.name = name;
318
- }
319
- if (account.type === "watch-only" && isPortfolio !== void 0) {
320
- if (typeof isPortfolio !== "boolean") throw new Error("isPortfolio must be a boolean");
321
- account.isPortfolio = isPortfolio;
322
- }
323
- if (account.type === "contact") {
324
- if (genesisHash) {
325
- if (!isHexString(genesisHash)) throw new Error("genesisHash must be a hex string");
326
- account.genesisHash = genesisHash;
327
- } else delete account.genesisHash;
328
- }
329
- return accountFromStorage(account);
330
- }
331
- removeAccount(address) {
332
- const index = this.#data.accounts.findIndex((s) => isAddressEqual(s.address, address));
333
- if (index === -1) throw new Error("Account not found");
334
- this.#data.accounts.splice(index, 1);
335
- }
336
- addAccountExternal(options) {
337
- const address = normalizeAddress(options.address);
338
- if (this.getAccount(address)) throw new Error("Account already exists");
339
- const account = {
340
- ...options,
341
- address,
342
- createdAt: Date.now()
343
- };
344
- if (!isAccountExternal(account)) throw new Error("Invalid account type");
345
- this.#data.accounts.push(account);
346
- return accountFromStorage(account);
347
- }
348
- /**
349
- * Needs to be called before deriving an account from a mnemonic.
350
- *
351
- * This will ensure that it is present (or add it if possible) in the keyring before actually creating the account.
352
- *
353
- * @param options
354
- * @param password
355
- * @returns the id of the mnemonic
356
- */
357
- async ensureMnemonic(options, password) {
358
- await this.checkPassword(password);
359
- switch (options.type) {
360
- case "new-mnemonic": {
361
- const { mnemonic, mnemonicName: name, confirmed } = options;
362
- if (typeof name !== "string" || !name) throw new Error("mnemonicName is required");
363
- if (typeof confirmed !== "boolean") throw new Error("confirmed is required");
364
- const mnemonicId = this.getExistingMnemonicId(mnemonic);
365
- if (mnemonicId) return mnemonicId;
366
- const { id } = await this.addMnemonic(
367
- {
368
- name,
369
- mnemonic,
370
- confirmed
371
- },
372
- password
373
- );
374
- return id;
375
- }
376
- case "existing-mnemonic": {
377
- if (typeof options.mnemonicId !== "string" || !options.mnemonicId)
378
- throw new Error("mnemonicId must be a string");
379
- return options.mnemonicId;
380
- }
381
- }
382
- }
383
- async addAccountDerive(options, password) {
384
- await this.checkPassword(password);
385
- const { curve, derivationPath, name } = options;
386
- const mnemonicId = await this.ensureMnemonic(options, password);
387
- const mnemonic = this.#data.mnemonics.find((s) => s.id === mnemonicId);
388
- if (!mnemonic) throw new Error("Mnemonic not found");
389
- const entropy = await decryptData(mnemonic.entropy, password);
390
- const seed = await entropyToSeed(entropy, curve);
391
- const pair = deriveKeypair(seed, derivationPath, curve);
392
- if (this.getAccount(pair.address)) throw new Error("Account already exists");
393
- const account = {
394
- type: "keypair",
395
- curve,
396
- name,
397
- address: normalizeAddress(pair.address),
398
- secretKey: await encryptData(pair.secretKey, password),
399
- mnemonicId,
400
- derivationPath,
401
- createdAt: Date.now()
402
- };
403
- this.#data.accounts.push(account);
404
- return accountFromStorage(account);
405
- }
406
- async addAccountKeypair({ curve, name, secretKey }, password) {
407
- await this.checkPassword(password);
408
- const publicKey = getPublicKeyFromSecret(secretKey, curve);
409
- const encoding = addressEncodingFromCurve(curve);
410
- const address = addressFromPublicKey(publicKey, encoding);
411
- if (this.getAccount(address)) throw new Error("Account already exists");
412
- const account = {
413
- type: "keypair",
414
- curve,
415
- name,
416
- address: normalizeAddress(address),
417
- secretKey: await encryptData(secretKey, password),
418
- createdAt: Date.now()
419
- };
420
- this.#data.accounts.push(account);
421
- return accountFromStorage(account);
422
- }
423
- getAccountSecretKey(address, password) {
424
- if (typeof address !== "string" || !address) throw new Error("address is required");
425
- if (typeof password !== "string" || !password) throw new Error("password is required");
426
- const account = this.#data.accounts.find((a) => a.address === normalizeAddress(address));
427
- if (!account) throw new Error("Account not found");
428
- if (account.type !== "keypair") throw new Error("Secret key unavailable");
429
- return decryptData(account.secretKey, password);
430
- }
431
- async getDerivedAddress(mnemonicId, derivationPath, curve, password) {
432
- if (typeof mnemonicId !== "string" || !mnemonicId) throw new Error("mnemonicId is required");
433
- if (typeof password !== "string" || !password) throw new Error("password is required");
434
- const mnemonic = this.#data.mnemonics.find((s) => s.id === mnemonicId);
435
- if (!mnemonic) throw new Error("Mnemonic not found");
436
- const entropy = await decryptData(mnemonic.entropy, password);
437
- const seed = await entropyToSeed(entropy, curve);
438
- const pair = deriveKeypair(seed, derivationPath, curve);
439
- return pair.address;
440
- }
121
+ //#endregion
122
+ //#region src/keyring/utils.ts
123
+ const REGEX_HEX_STRING = /^0x[0-9a-fA-F]*$/;
124
+ const isHexString = (value) => {
125
+ return typeof value === "string" && REGEX_HEX_STRING.test(value);
441
126
  };
442
- var oneWayHash = (bytes) => {
443
- if (typeof bytes === "string") bytes = utf8.decode(bytes);
444
- return base58.encode(blake3(bytes));
127
+ //#endregion
128
+ //#region src/keyring/Keyring.ts
129
+ var Keyring = class Keyring {
130
+ #data;
131
+ constructor(data) {
132
+ this.#data = structuredClone(data);
133
+ }
134
+ static create() {
135
+ return new Keyring({
136
+ passwordCheck: null,
137
+ mnemonics: [],
138
+ accounts: []
139
+ });
140
+ }
141
+ static load(data) {
142
+ if (!data.accounts || !data.mnemonics) throw new Error("Invalid data");
143
+ for (const account of data.accounts) if (account.type === "ledger-polkadot" && !account.curve) account.curve = "ed25519";
144
+ return new Keyring(data);
145
+ }
146
+ async checkPassword(password, reset = false) {
147
+ if (typeof password !== "string" || !password) throw new Error("password is required");
148
+ const passwordHash = oneWayHash(password);
149
+ const PASSWORD_CHECK_PHRASE = "PASSWORD_CHECK_PHRASE";
150
+ if (!this.#data.passwordCheck || reset) {
151
+ const bytes = utf8.decode(PASSWORD_CHECK_PHRASE);
152
+ this.#data.passwordCheck = await encryptData(bytes, passwordHash);
153
+ } else try {
154
+ const bytes = await decryptData(this.#data.passwordCheck, passwordHash);
155
+ if (utf8.encode(bytes) !== PASSWORD_CHECK_PHRASE) throw new Error("Invalid password");
156
+ } catch {
157
+ throw new Error("Invalid password");
158
+ }
159
+ }
160
+ /** Returns true if a password has been set on this keyring. */
161
+ hasPassword() {
162
+ return this.#data.passwordCheck !== null;
163
+ }
164
+ /**
165
+ * Verify a password against the keyring's passwordCheck blob.
166
+ * Returns true on success, false on wrong password.
167
+ * Throws if no password has been set (caller should check hasPassword() first).
168
+ */
169
+ async verifyPassword(password) {
170
+ if (!this.#data.passwordCheck) throw new Error("No password set — call hasPassword() before verifyPassword()");
171
+ try {
172
+ await this.checkPassword(password);
173
+ return true;
174
+ } catch {
175
+ return false;
176
+ }
177
+ }
178
+ /**
179
+ * Initialize the password on a fresh keyring that has no password set.
180
+ * Throws if a password is already set (use changePassword flow instead).
181
+ */
182
+ async initializePassword(password) {
183
+ if (this.#data.passwordCheck !== null) throw new Error("Password already set — cannot re-initialize");
184
+ await this.checkPassword(password, true);
185
+ }
186
+ toJson() {
187
+ return structuredClone(this.#data);
188
+ }
189
+ async export(password, jsonPassword) {
190
+ const keyring = new Keyring(structuredClone(this.#data));
191
+ for (const mnemonic of keyring.#data.mnemonics) mnemonic.entropy = await changeEncryptedDataPassword(mnemonic.entropy, password, jsonPassword);
192
+ for (const account of keyring.#data.accounts) if (account.type === "keypair") account.secretKey = await changeEncryptedDataPassword(account.secretKey, password, jsonPassword);
193
+ await keyring.checkPassword(jsonPassword, true);
194
+ return keyring.toJson();
195
+ }
196
+ getMnemonics() {
197
+ return this.#data.mnemonics.map(mnemonicFromStorage);
198
+ }
199
+ async addMnemonic({ name, mnemonic, confirmed }, password) {
200
+ if (typeof name !== "string" || !name) throw new Error("name is required");
201
+ if (typeof mnemonic !== "string") throw new Error("mnemonic is required");
202
+ if (typeof confirmed !== "boolean") throw new Error("confirmed is required");
203
+ if (!isValidMnemonic(mnemonic)) throw new Error("Invalid mnemonic");
204
+ await this.checkPassword(password);
205
+ const entropy = mnemonicToEntropy(mnemonic);
206
+ const id = oneWayHash(entropy);
207
+ if (this.#data.mnemonics.find((s) => s.id === id)) throw new Error("Mnemonic already exists");
208
+ const storage = {
209
+ id,
210
+ name,
211
+ entropy: await encryptData(entropy, password),
212
+ confirmed,
213
+ createdAt: Date.now()
214
+ };
215
+ this.#data.mnemonics.push(storage);
216
+ return mnemonicFromStorage(storage);
217
+ }
218
+ getMnemonic(id) {
219
+ const mnemonic = this.#data.mnemonics.find((s) => s.id === id);
220
+ return mnemonic ? mnemonicFromStorage(mnemonic) : null;
221
+ }
222
+ updateMnemonic(id, { name, confirmed }) {
223
+ const mnemonic = this.#data.mnemonics.find((s) => s.id === id);
224
+ if (!mnemonic) throw new Error("Mnemonic not found");
225
+ if (name !== void 0) {
226
+ if (typeof name !== "string" || !name) throw new Error("name must be a string");
227
+ mnemonic.name = name;
228
+ }
229
+ if (confirmed !== void 0) {
230
+ if (typeof confirmed !== "boolean") throw new Error("confirmed must be a boolean");
231
+ mnemonic.confirmed = confirmed;
232
+ }
233
+ return mnemonicFromStorage(mnemonic);
234
+ }
235
+ removeMnemonic(id) {
236
+ const index = this.#data.mnemonics.findIndex((mnemonic) => mnemonic.id === id);
237
+ if (index === -1) throw new Error("Mnemonic not found");
238
+ this.#data.mnemonics.splice(index, 1);
239
+ }
240
+ async getMnemonicText(id, password) {
241
+ const mnemonic = this.#data.mnemonics.find((s) => s.id === id);
242
+ if (!mnemonic) throw new Error("Mnemonic not found");
243
+ return entropyToMnemonic(await decryptData(mnemonic.entropy, password));
244
+ }
245
+ getExistingMnemonicId(mnemonic) {
246
+ const entropy = mnemonicToEntropy(mnemonic);
247
+ const mnemonicId = oneWayHash(entropy);
248
+ return this.#data.mnemonics.some((s) => s.id === mnemonicId) ? mnemonicId : null;
249
+ }
250
+ getAccounts() {
251
+ return this.#data.accounts.map(accountFromStorage);
252
+ }
253
+ getAccount(address) {
254
+ const account = this.#data.accounts.find((s) => isAddressEqual(s.address, address));
255
+ return account ? accountFromStorage(account) : null;
256
+ }
257
+ updateAccount(address, { name, isPortfolio, genesisHash }) {
258
+ const account = this.#data.accounts.find((s) => s.address === address);
259
+ if (!account) throw new Error("Account not found");
260
+ if (name) {
261
+ if (typeof name !== "string" || !name) throw new Error("name is required");
262
+ account.name = name;
263
+ }
264
+ if (account.type === "watch-only" && isPortfolio !== void 0) {
265
+ if (typeof isPortfolio !== "boolean") throw new Error("isPortfolio must be a boolean");
266
+ account.isPortfolio = isPortfolio;
267
+ }
268
+ if (account.type === "contact") if (genesisHash) {
269
+ if (!isHexString(genesisHash)) throw new Error("genesisHash must be a hex string");
270
+ account.genesisHash = genesisHash;
271
+ } else delete account.genesisHash;
272
+ return accountFromStorage(account);
273
+ }
274
+ removeAccount(address) {
275
+ const index = this.#data.accounts.findIndex((s) => isAddressEqual(s.address, address));
276
+ if (index === -1) throw new Error("Account not found");
277
+ this.#data.accounts.splice(index, 1);
278
+ }
279
+ addAccountExternal(options) {
280
+ const address = normalizeAddress(options.address);
281
+ if (this.getAccount(address)) throw new Error("Account already exists");
282
+ const account = {
283
+ ...options,
284
+ address,
285
+ createdAt: Date.now()
286
+ };
287
+ if (!isAccountExternal(account)) throw new Error("Invalid account type");
288
+ this.#data.accounts.push(account);
289
+ return accountFromStorage(account);
290
+ }
291
+ /**
292
+ * Needs to be called before deriving an account from a mnemonic.
293
+ *
294
+ * This will ensure that it is present (or add it if possible) in the keyring before actually creating the account.
295
+ *
296
+ * @param options
297
+ * @param password
298
+ * @returns the id of the mnemonic
299
+ */
300
+ async ensureMnemonic(options, password) {
301
+ await this.checkPassword(password);
302
+ switch (options.type) {
303
+ case "new-mnemonic": {
304
+ const { mnemonic, mnemonicName: name, confirmed } = options;
305
+ if (typeof name !== "string" || !name) throw new Error("mnemonicName is required");
306
+ if (typeof confirmed !== "boolean") throw new Error("confirmed is required");
307
+ const mnemonicId = this.getExistingMnemonicId(mnemonic);
308
+ if (mnemonicId) return mnemonicId;
309
+ const { id } = await this.addMnemonic({
310
+ name,
311
+ mnemonic,
312
+ confirmed
313
+ }, password);
314
+ return id;
315
+ }
316
+ case "existing-mnemonic":
317
+ if (typeof options.mnemonicId !== "string" || !options.mnemonicId) throw new Error("mnemonicId must be a string");
318
+ return options.mnemonicId;
319
+ }
320
+ }
321
+ async addAccountDerive(options, password) {
322
+ await this.checkPassword(password);
323
+ const { curve, derivationPath, name } = options;
324
+ const mnemonicId = await this.ensureMnemonic(options, password);
325
+ const mnemonic = this.#data.mnemonics.find((s) => s.id === mnemonicId);
326
+ if (!mnemonic) throw new Error("Mnemonic not found");
327
+ const pair = deriveKeypair(await entropyToSeed(await decryptData(mnemonic.entropy, password), curve), derivationPath, curve);
328
+ if (this.getAccount(pair.address)) throw new Error("Account already exists");
329
+ const account = {
330
+ type: "keypair",
331
+ curve,
332
+ name,
333
+ address: normalizeAddress(pair.address),
334
+ secretKey: await encryptData(pair.secretKey, password),
335
+ mnemonicId,
336
+ derivationPath,
337
+ createdAt: Date.now()
338
+ };
339
+ this.#data.accounts.push(account);
340
+ return accountFromStorage(account);
341
+ }
342
+ async addAccountKeypair({ curve, name, secretKey }, password) {
343
+ await this.checkPassword(password);
344
+ const address = addressFromPublicKey(getPublicKeyFromSecret(secretKey, curve), addressEncodingFromCurve(curve));
345
+ if (this.getAccount(address)) throw new Error("Account already exists");
346
+ const account = {
347
+ type: "keypair",
348
+ curve,
349
+ name,
350
+ address: normalizeAddress(address),
351
+ secretKey: await encryptData(secretKey, password),
352
+ createdAt: Date.now()
353
+ };
354
+ this.#data.accounts.push(account);
355
+ return accountFromStorage(account);
356
+ }
357
+ getAccountSecretKey(address, password) {
358
+ if (typeof address !== "string" || !address) throw new Error("address is required");
359
+ if (typeof password !== "string" || !password) throw new Error("password is required");
360
+ const account = this.#data.accounts.find((a) => a.address === normalizeAddress(address));
361
+ if (!account) throw new Error("Account not found");
362
+ if (account.type !== "keypair") throw new Error("Secret key unavailable");
363
+ return decryptData(account.secretKey, password);
364
+ }
365
+ async getDerivedAddress(mnemonicId, derivationPath, curve, password) {
366
+ if (typeof mnemonicId !== "string" || !mnemonicId) throw new Error("mnemonicId is required");
367
+ if (typeof password !== "string" || !password) throw new Error("password is required");
368
+ const mnemonic = this.#data.mnemonics.find((s) => s.id === mnemonicId);
369
+ if (!mnemonic) throw new Error("Mnemonic not found");
370
+ return deriveKeypair(await entropyToSeed(await decryptData(mnemonic.entropy, password), curve), derivationPath, curve).address;
371
+ }
445
372
  };
446
- var mnemonicFromStorage = (data) => {
447
- const copy = structuredClone(data);
448
- if ("entropy" in copy) delete copy.entropy;
449
- return Object.freeze(copy);
373
+ const oneWayHash = (bytes) => {
374
+ if (typeof bytes === "string") bytes = utf8.decode(bytes);
375
+ return base58.encode(blake3(bytes));
450
376
  };
451
- var accountFromStorage = (data) => {
452
- const copy = structuredClone(data);
453
- if ("secretKey" in copy) delete copy.secretKey;
454
- return Object.freeze(copy);
377
+ const mnemonicFromStorage = (data) => {
378
+ const copy = structuredClone(data);
379
+ if ("entropy" in copy) delete copy.entropy;
380
+ return Object.freeze(copy);
455
381
  };
456
- export {
457
- Keyring,
458
- getAccountGenesisHash,
459
- getAccountPlatform,
460
- getAccountSignetUrl,
461
- isAccountAddressEthereum,
462
- isAccountAddressSs58,
463
- isAccountBitcoin,
464
- isAccountExternal,
465
- isAccountInTypes,
466
- isAccountLedgerPolkadot,
467
- isAccountLedgerPolkadotGeneric,
468
- isAccountLedgerPolkadotLegacy,
469
- isAccountNotContact,
470
- isAccountOfType,
471
- isAccountOwned,
472
- isAccountPlatformEthereum,
473
- isAccountPlatformPolkadot,
474
- isAccountPlatformSolana,
475
- isAccountPortfolio
382
+ const accountFromStorage = (data) => {
383
+ const copy = structuredClone(data);
384
+ if ("secretKey" in copy) delete copy.secretKey;
385
+ return Object.freeze(copy);
476
386
  };
387
+ //#endregion
388
+ export { Keyring, getAccountGenesisHash, getAccountPlatform, getAccountSignetUrl, isAccountAddressEthereum, isAccountAddressSs58, isAccountBitcoin, isAccountExternal, isAccountInTypes, isAccountLedgerPolkadot, isAccountLedgerPolkadotGeneric, isAccountLedgerPolkadotLegacy, isAccountNotContact, isAccountOfType, isAccountOwned, isAccountPlatformEthereum, isAccountPlatformPolkadot, isAccountPlatformSolana, isAccountPortfolio };
389
+
477
390
  //# sourceMappingURL=index.mjs.map