@sugarcasino/passkey-wallet 0.0.0 → 0.1.0-beta.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 @@
1
+ {"version":3,"file":"initializer.d.mts","names":[],"sources":["../../src/wallet/initializer.ts"],"mappings":";;;;;;wBAWgB,yBAAyB,SAAS,KAAK;;EAMlD,aAAA,UAAA;IACF,UAAU,cAAc,eAAe;IACvC,YAAY,UAAU,eAAe,YAAY"}
@@ -0,0 +1,21 @@
1
+ import { registerPasskeyWallet } from "./register.mjs";
2
+ // src/wallet/initializer.ts
3
+ /**
4
+ * Registers the passkey wallet from dApp Kit's `walletInitializers`, with one client per dApp Kit
5
+ * network.
6
+ */
7
+ function passkeyWalletInitializer(options) {
8
+ return {
9
+ id: "passkey-wallet-initializer",
10
+ initialize({ networks, getClient }) {
11
+ const { unregister } = registerPasskeyWallet({
12
+ ...options,
13
+ clients: networks.map((network) => getClient(network))
14
+ });
15
+ return { unregister };
16
+ }
17
+ };
18
+ }
19
+ export { passkeyWalletInitializer };
20
+
21
+ //# sourceMappingURL=initializer.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initializer.mjs","names":[],"sources":["../../src/wallet/initializer.ts"],"sourcesContent":["// Copyright (c) Sugar\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { ClientWithCoreApi, SuiClientTypes } from '@mysten/sui/client';\nimport { registerPasskeyWallet } from './register.js';\nimport type { PasskeyWalletOptions } from './types.js';\n\n/**\n * Registers the passkey wallet from dApp Kit's `walletInitializers`, with one client per dApp Kit\n * network.\n */\nexport function passkeyWalletInitializer(options: Omit<PasskeyWalletOptions, 'clients'>) {\n\treturn {\n\t\tid: 'passkey-wallet-initializer',\n\t\tinitialize({\n\t\t\tnetworks,\n\t\t\tgetClient,\n\t\t}: {\n\t\t\tnetworks: ReadonlyArray<SuiClientTypes.Network>;\n\t\t\tgetClient: (network?: SuiClientTypes.Network) => ClientWithCoreApi;\n\t\t}) {\n\t\t\tconst { unregister } = registerPasskeyWallet({\n\t\t\t\t...options,\n\t\t\t\tclients: networks.map((network) => getClient(network)),\n\t\t\t});\n\n\t\t\treturn { unregister };\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;AAWA,SAAgB,yBAAyB,SAAgD;CACxF,OAAO;EACN,IAAI;EACJ,WAAW,EACV,UACA,aAIE;GACF,MAAM,EAAE,eAAe,sBAAsB;IAC5C,GAAG;IACH,SAAS,SAAS,KAAK,YAAY,UAAU,OAAO,CAAC;GACtD,CAAC;GAED,OAAO,EAAE,WAAW;EACrB;CACD;AACD"}
@@ -0,0 +1,8 @@
1
+ import { PasskeyWalletOptions } from "./types.mjs";
2
+ import { PasskeyWallet } from "./wallet.mjs";
3
+ /** Registers a passkey wallet with the Wallet Standard, so dApp Kit lists it with the other wallets. */
4
+ export declare function registerPasskeyWallet(options: PasskeyWalletOptions): {
5
+ wallet: PasskeyWallet;
6
+ unregister: () => void;
7
+ };
8
+ //# sourceMappingURL=register.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"register.d.mts","names":[],"sources":["../../src/wallet/register.ts"],"mappings":";;;wBAQgB,sBAAsB,SAAS"}
@@ -0,0 +1,19 @@
1
+ import { getWallets } from "@mysten/wallet-standard";
2
+ import { PasskeyWallet } from "./wallet.mjs";
3
+ // src/wallet/register.ts
4
+ /** Registers a passkey wallet with the Wallet Standard, so dApp Kit lists it with the other wallets. */
5
+ function registerPasskeyWallet(options) {
6
+ const wallet = new PasskeyWallet(options);
7
+ const unregisterWallet = getWallets().register(wallet);
8
+ const unregister = () => {
9
+ unregisterWallet();
10
+ wallet.dispose();
11
+ };
12
+ return {
13
+ wallet,
14
+ unregister
15
+ };
16
+ }
17
+ export { registerPasskeyWallet };
18
+
19
+ //# sourceMappingURL=register.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"register.mjs","names":[],"sources":["../../src/wallet/register.ts"],"sourcesContent":["// Copyright (c) Sugar\n// SPDX-License-Identifier: Apache-2.0\n\nimport { getWallets } from '@mysten/wallet-standard';\nimport type { PasskeyWalletOptions } from './types.js';\nimport { PasskeyWallet } from './wallet.js';\n\n/** Registers a passkey wallet with the Wallet Standard, so dApp Kit lists it with the other wallets. */\nexport function registerPasskeyWallet(options: PasskeyWalletOptions) {\n\tconst wallet = new PasskeyWallet(options);\n\tconst unregisterWallet = getWallets().register(wallet);\n\tconst unregister = () => {\n\t\tunregisterWallet();\n\t\twallet.dispose();\n\t};\n\treturn { wallet, unregister };\n}\n"],"mappings":";;;;AAQA,SAAgB,sBAAsB,SAA+B;CACpE,MAAM,SAAS,IAAI,cAAc,OAAO;CACxC,MAAM,mBAAmB,WAAW,CAAC,CAAC,SAAS,MAAM;CACrD,MAAM,mBAAmB;EACxB,iBAAiB;EACjB,OAAO,QAAQ;CAChB;CACA,OAAO;EAAE;EAAQ;CAAW;AAC7B"}
@@ -0,0 +1,45 @@
1
+ import { ClientWithCoreApi } from "@mysten/sui/client";
2
+ import "@mysten/sui/keypairs/secp256r1";
3
+ import { WalletIcon } from "@mysten/wallet-standard";
4
+ import "@mysten/webcrypto-signer";
5
+ export type PasskeyWalletOptions = {
6
+ /** One client per supported network, used to build and execute transactions. */
7
+ clients: Array<ClientWithCoreApi>;
8
+ /**
9
+ * How long a session lasts once the passkey unlocks the wallet: signatures and page reloads need
10
+ * no prompt until it ends. The key is kept in IndexedDB for this time. `0` keeps it in memory
11
+ * only, so the session ends at the next reload.
12
+ *
13
+ * @default 7 days
14
+ */
15
+ sessionDurationMs?: number;
16
+ /** Relying party and prompts of the passkeys. */
17
+ webauthn: {
18
+ /** Name shown in the passkey prompts, such as `My App`. */
19
+ rpName: string;
20
+ /**
21
+ * Domain the passkeys are bound to. Defaults to the current hostname. A passkey only works on
22
+ * its domain, so fix this value before users hold funds.
23
+ */
24
+ rpId?: string;
25
+ /**
26
+ * How long a passkey prompt waits for the user before it fails with `PasskeyCancelledError`.
27
+ * Browsers may clamp it.
28
+ *
29
+ * @default 60 seconds
30
+ */
31
+ promptTimeoutMs?: number;
32
+ };
33
+ /** How the wallet appears in wallet lists, such as the dApp Kit connect modal. */
34
+ wallet?: {
35
+ /**
36
+ * Wallet name. dApp Kit reconnects a wallet by its name, so keep it stable.
37
+ *
38
+ * @default 'Passkey'
39
+ */
40
+ name?: string;
41
+ /** Data URL of an SVG, PNG, WebP or GIF image. Defaults to a person with a key. */
42
+ icon?: WalletIcon;
43
+ };
44
+ };
45
+ //# sourceMappingURL=types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../../src/wallet/types.ts"],"mappings":";;;;YAgCY;;EAEX,SAAS,MAAM;;;;;;;;EAQf;;EAEA;;IAEC;;;;;IAKA;;;;;;;IAOA;;;EAGD;;;;;;IAMC;;IAEA,OAAO"}
@@ -0,0 +1,13 @@
1
+ import { Wallet } from "@mysten/wallet-standard";
2
+ import { UiWallet } from "@wallet-standard/ui";
3
+ import { CreatePasskeyWalletOptions } from "./features.mjs";
4
+ import { PasskeyWallet } from "./wallet.mjs";
5
+ /** Whether a wallet, such as one from dApp Kit's `useWallets()`, is a passkey wallet. */
6
+ export declare function isPasskeyWallet(wallet: UiWallet): boolean;
7
+ export declare function isPasskeyWallet(wallet: Wallet): wallet is PasskeyWallet;
8
+ /**
9
+ * Creates a new passkey, which gives a new address, and connects its wallet. Then call dApp Kit's
10
+ * `connectWallet()` so it marks the wallet as connected.
11
+ */
12
+ export declare function createPasskeyWallet(wallet: Wallet | UiWallet, options?: CreatePasskeyWalletOptions): Promise<import("@mysten/wallet-standard").StandardConnectOutput>;
13
+ //# sourceMappingURL=utils.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.mts","names":[],"sources":["../../src/wallet/utils.ts"],"mappings":";;;;;wBAgBgB,gBAAgB,QAAQ;wBACxB,gBAAgB,QAAQ,SAAS,UAAU;;;;;wBAWrC,oBACrB,QAAQ,SAAS,UACjB,UAAU,6BAA0B,0CAAA"}
@@ -0,0 +1,25 @@
1
+ import { getWalletFeature } from "@wallet-standard/ui";
2
+ import { PasskeyWalletCreate } from "./features.mjs";
3
+ // src/wallet/utils.ts
4
+ function isPasskeyWallet(wallet) {
5
+ return isWalletHandle(wallet) ? wallet.features.includes(PasskeyWalletCreate) : PasskeyWalletCreate in wallet.features;
6
+ }
7
+ /**
8
+ * Creates a new passkey, which gives a new address, and connects its wallet. Then call dApp Kit's
9
+ * `connectWallet()` so it marks the wallet as connected.
10
+ */
11
+ async function createPasskeyWallet(wallet, options) {
12
+ return getFeature(wallet, PasskeyWalletCreate).create(options);
13
+ }
14
+ function getFeature(wallet, name) {
15
+ if (!isWalletHandle(wallet)) {
16
+ if (isPasskeyWallet(wallet)) return wallet.features[name];
17
+ } else if (isPasskeyWallet(wallet)) return getWalletFeature(wallet, name);
18
+ throw new Error(`${wallet.name} is not a passkey wallet.`);
19
+ }
20
+ function isWalletHandle(wallet) {
21
+ return Array.isArray(wallet.features);
22
+ }
23
+ export { createPasskeyWallet, isPasskeyWallet };
24
+
25
+ //# sourceMappingURL=utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.mjs","names":[],"sources":["../../src/wallet/utils.ts"],"sourcesContent":["// Copyright (c) Sugar\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Wallet } from '@mysten/wallet-standard';\nimport { getWalletFeature, type UiWallet } from '@wallet-standard/ui';\nimport {\n\ttype CreatePasskeyWalletOptions,\n\tPasskeyWalletCreate,\n\ttype PasskeyWalletCreateFeature,\n} from './features.js';\nimport type { PasskeyWallet } from './wallet.js';\n\n/** Features the passkey wallet adds to the Wallet Standard. */\ntype PasskeyWalletFeatures = PasskeyWalletCreateFeature;\n\n/** Whether a wallet, such as one from dApp Kit's `useWallets()`, is a passkey wallet. */\nexport function isPasskeyWallet(wallet: UiWallet): boolean;\nexport function isPasskeyWallet(wallet: Wallet): wallet is PasskeyWallet;\nexport function isPasskeyWallet(wallet: Wallet | UiWallet) {\n\treturn isWalletHandle(wallet)\n\t\t? wallet.features.includes(PasskeyWalletCreate)\n\t\t: PasskeyWalletCreate in wallet.features;\n}\n\n/**\n * Creates a new passkey, which gives a new address, and connects its wallet. Then call dApp Kit's\n * `connectWallet()` so it marks the wallet as connected.\n */\nexport async function createPasskeyWallet(\n\twallet: Wallet | UiWallet,\n\toptions?: CreatePasskeyWalletOptions,\n) {\n\treturn getFeature(wallet, PasskeyWalletCreate).create(options);\n}\n\nfunction getFeature<TName extends keyof PasskeyWalletFeatures>(\n\twallet: Wallet | UiWallet,\n\tname: TName,\n): PasskeyWalletFeatures[TName] {\n\tif (!isWalletHandle(wallet)) {\n\t\tif (isPasskeyWallet(wallet)) {\n\t\t\treturn wallet.features[name];\n\t\t}\n\t} else if (isPasskeyWallet(wallet)) {\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- getWalletFeature returns unknown; isPasskeyWallet checked the wallet.\n\t\treturn getWalletFeature(wallet, name) as PasskeyWalletFeatures[TName];\n\t}\n\n\tthrow new Error(`${wallet.name} is not a passkey wallet.`);\n}\n\nfunction isWalletHandle(wallet: Wallet | UiWallet): wallet is UiWallet {\n\t// TypeScript does not narrow readonly arrays with Array.isArray:\n\t// https://github.com/microsoft/TypeScript/issues/17002\n\treturn Array.isArray(wallet.features);\n}\n"],"mappings":";;;AAkBA,SAAgB,gBAAgB,QAA2B;CAC1D,OAAO,eAAe,MAAM,IACzB,OAAO,SAAS,SAAS,mBAAmB,IAC5C,uBAAuB,OAAO;AAClC;;;;;AAMA,eAAsB,oBACrB,QACA,SACC;CACD,OAAO,WAAW,QAAQ,mBAAmB,CAAC,CAAC,OAAO,OAAO;AAC9D;AAEA,SAAS,WACR,QACA,MAC+B;CAC/B,IAAI,CAAC,eAAe,MAAM,GACrB;MAAA,gBAAgB,MAAM,GACzB,OAAO,OAAO,SAAS;CAAA,OAElB,IAAI,gBAAgB,MAAM,GAEhC,OAAO,iBAAiB,QAAQ,IAAI;CAGrC,MAAM,IAAI,MAAM,GAAG,OAAO,KAAK,0BAA0B;AAC1D;AAEA,SAAS,eAAe,QAA+C;CAGtE,OAAO,MAAM,QAAQ,OAAO,QAAQ;AACrC"}
@@ -0,0 +1,25 @@
1
+ import { StandardConnectFeature, StandardDisconnectFeature, StandardEventsFeature, SuiSignAndExecuteTransactionFeature, SuiSignPersonalMessageFeature, SuiSignTransactionFeature, Wallet, WalletAccount } from "@mysten/wallet-standard";
2
+ import { PasskeyWalletCreateFeature } from "./features.mjs";
3
+ import { PasskeyWalletOptions } from "./types.mjs";
4
+ /**
5
+ * Wallet Standard wallet unlocked by a passkey.
6
+ *
7
+ * The wallet key is a secp256r1 key derived from the passkey with the WebAuthn PRF extension, so a
8
+ * synced passkey opens the same wallet on every device. Once unlocked, the key is a non-extractable
9
+ * WebCrypto key kept in IndexedDB for `sessionDurationMs`, so signatures and reloads need no
10
+ * prompt. `localStorage` holds only the public key and credential ID. Disconnecting deletes both.
11
+ * Browser only.
12
+ */
13
+ export declare class PasskeyWallet implements Wallet {
14
+ #private;
15
+ constructor({ clients, sessionDurationMs, webauthn: { rpName, rpId, promptTimeoutMs }, wallet: { name, icon } }: PasskeyWalletOptions);
16
+ get version(): '1.0.0';
17
+ get name(): string;
18
+ get icon(): `data:image/gif;base64,${string}` | `data:image/png;base64,${string}` | `data:image/svg+xml;base64,${string}` | `data:image/webp;base64,${string}`;
19
+ get chains(): `sui:${string & {}}`[];
20
+ get accounts(): ReadonlyArray<WalletAccount>;
21
+ get features(): StandardConnectFeature & StandardDisconnectFeature & StandardEventsFeature & SuiSignTransactionFeature & SuiSignAndExecuteTransactionFeature & SuiSignPersonalMessageFeature & PasskeyWalletCreateFeature;
22
+ /** Stops following other tabs. `registerPasskeyWallet()` calls it on unregister. */
23
+ dispose(): void;
24
+ }
25
+ //# sourceMappingURL=wallet.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wallet.d.mts","names":[],"sources":["../../src/wallet/wallet.ts"],"mappings":";;;;;;;;;;;;qBAgFa,yBAAyB;;EAcrC,cACC,SACA,mBACA,YAAY,QAAQ,MAA0B,mBAC9C,UAAU,MAAkB,UAC1B;MAwCC;MAIA;MAIA;MAIA;MAIA,YAAY,cAAc;MAK1B,YAAY,yBACf,4BACA,wBACA,4BACA,sCACA,gCACA;;EAmBD"}
@@ -0,0 +1,323 @@
1
+ import { Secp256r1PublicKey } from "@mysten/sui/keypairs/secp256r1";
2
+ import { Transaction } from "@mysten/sui/transactions";
3
+ import { fromBase64, toBase64 } from "@mysten/sui/utils";
4
+ import { mitt } from "@mysten/utils";
5
+ import { ReadonlyWalletAccount, StandardConnect, StandardDisconnect, StandardEvents, SuiSignAndExecuteTransaction, SuiSignPersonalMessage, SuiSignTransaction } from "@mysten/wallet-standard";
6
+ import { WebCryptoSigner } from "@mysten/webcrypto-signer";
7
+ import { utf8ToBytes } from "@noble/hashes/utils.js";
8
+ import { createStore, del, get, set } from "idb-keyval";
9
+ import { NAMESPACE } from "../constants.mjs";
10
+ import { PasskeyWalletMismatchError } from "../errors.mjs";
11
+ import { deriveSigner } from "../key.mjs";
12
+ import { createPasskey, getPasskeySecret } from "../provider.mjs";
13
+ import { PasskeyWalletCreate } from "./features.mjs";
14
+ // src/wallet/wallet.ts
15
+ const STORAGE_KEY_PREFIX = `${NAMESPACE}:v1:`;
16
+ const DEFAULT_SESSION_DURATION_MS = 6048e5;
17
+ const DEFAULT_PROMPT_TIMEOUT_MS = 6e4;
18
+ const ICON = `data:image/svg+xml;base64,${toBase64(utf8ToBytes("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"6 6 180 180\"><defs><linearGradient id=\"g\" x2=\"0\" y2=\"1\"><stop offset=\"0\" stop-color=\"#afbdce\"/><stop offset=\"1\" stop-color=\"#7d88a1\"/></linearGradient><g id=\"k\"><path fill-rule=\"evenodd\" d=\"M116.5 91a19.5 19.5 0 1 0 39 0 19.5 19.5 0 1 0-39 0zm13.5-6a6.5 6.5 0 1 0 13 0 6.5 6.5 0 1 0-13 0z\"/><path d=\"M130.5 104h11.5v8l8 10-8 8v3l5 5.5v1.5l-4 4-6.5 7h-.5l-5.5-6.5z\"/></g><mask id=\"m\"><rect x=\"6\" y=\"6\" width=\"180\" height=\"180\" fill=\"#fff\"/><use href=\"#k\" stroke=\"#000\" stroke-width=\"22\" stroke-linejoin=\"round\"/></mask></defs><rect x=\"6\" y=\"6\" width=\"180\" height=\"180\" rx=\"40\" fill=\"url(#g)\"/><g fill=\"#fff\" stroke=\"#fff\"><circle cx=\"82.5\" cy=\"66.5\" r=\"23.5\" stroke=\"none\"/><path mask=\"url(#m)\" stroke=\"none\" d=\"M35 137c0-21 21-36 47.5-36S130 116 130 137v2a4 4 0 0 1-4 4H39a4 4 0 0 1-4-4z\"/><use href=\"#k\" stroke-width=\"1.5\" stroke-linejoin=\"round\"/></g></svg>"))}`;
19
+ /**
20
+ * Wallet Standard wallet unlocked by a passkey.
21
+ *
22
+ * The wallet key is a secp256r1 key derived from the passkey with the WebAuthn PRF extension, so a
23
+ * synced passkey opens the same wallet on every device. Once unlocked, the key is a non-extractable
24
+ * WebCrypto key kept in IndexedDB for `sessionDurationMs`, so signatures and reloads need no
25
+ * prompt. `localStorage` holds only the public key and credential ID. Disconnecting deletes both.
26
+ * Browser only.
27
+ */
28
+ var PasskeyWallet = class {
29
+ #events = mitt();
30
+ #clients;
31
+ #webauthn;
32
+ #name;
33
+ #icon;
34
+ #storageKey;
35
+ #sessionDurationMs;
36
+ #keyStore;
37
+ #state = null;
38
+ #session = null;
39
+ #accounts = [];
40
+ #removeStorageListener = null;
41
+ constructor({ clients, sessionDurationMs = DEFAULT_SESSION_DURATION_MS, webauthn: { rpName, rpId = location.hostname, promptTimeoutMs = DEFAULT_PROMPT_TIMEOUT_MS }, wallet: { name = "Passkey", icon = ICON } = {} }) {
42
+ if (clients.length === 0) throw new Error("At least one Sui client is required.");
43
+ if (!Number.isFinite(sessionDurationMs) || sessionDurationMs < 0) throw new Error("sessionDurationMs must be a finite number of milliseconds, 0 or more.");
44
+ if (!Number.isFinite(promptTimeoutMs) || promptTimeoutMs <= 0) throw new Error("promptTimeoutMs must be a finite number of milliseconds, more than 0.");
45
+ this.#clients = clients;
46
+ this.#webauthn = {
47
+ rpId,
48
+ rpName,
49
+ timeoutMs: promptTimeoutMs
50
+ };
51
+ this.#name = name;
52
+ this.#icon = icon;
53
+ this.#storageKey = `${STORAGE_KEY_PREFIX}${rpId}`;
54
+ this.#sessionDurationMs = sessionDurationMs;
55
+ this.#keyStore = sessionDurationMs > 0 ? createStore(NAMESPACE, "keys") : null;
56
+ this.#accounts = this.#loadState();
57
+ if (typeof window !== "undefined") {
58
+ const onStorage = (event) => {
59
+ if (event.key === this.#storageKey || event.key === null) {
60
+ const address = this.#state?.address;
61
+ this.#setAccounts(this.#loadState());
62
+ if (this.#state?.address !== address) this.#session = null;
63
+ }
64
+ };
65
+ window.addEventListener("storage", onStorage);
66
+ this.#removeStorageListener = () => {
67
+ window.removeEventListener("storage", onStorage);
68
+ };
69
+ }
70
+ }
71
+ get version() {
72
+ return "1.0.0";
73
+ }
74
+ get name() {
75
+ return this.#name;
76
+ }
77
+ get icon() {
78
+ return this.#icon;
79
+ }
80
+ get chains() {
81
+ return this.#clients.map((client) => `sui:${client.network}`);
82
+ }
83
+ get accounts() {
84
+ return this.#accounts;
85
+ }
86
+ get features() {
87
+ return {
88
+ [StandardConnect]: {
89
+ version: "1.0.0",
90
+ connect: this.#connect
91
+ },
92
+ [StandardDisconnect]: {
93
+ version: "1.0.0",
94
+ disconnect: this.#disconnect
95
+ },
96
+ [StandardEvents]: {
97
+ version: "1.0.0",
98
+ on: this.#on
99
+ },
100
+ [SuiSignTransaction]: {
101
+ version: "2.0.0",
102
+ signTransaction: this.#signTransaction
103
+ },
104
+ [SuiSignAndExecuteTransaction]: {
105
+ version: "2.0.0",
106
+ signAndExecuteTransaction: this.#signAndExecuteTransaction
107
+ },
108
+ [SuiSignPersonalMessage]: {
109
+ version: "1.1.0",
110
+ signPersonalMessage: this.#signPersonalMessage
111
+ },
112
+ [PasskeyWalletCreate]: {
113
+ version: "1.0.0",
114
+ create: this.#create
115
+ }
116
+ };
117
+ }
118
+ /** Stops following other tabs. `registerPasskeyWallet()` calls it on unregister. */
119
+ dispose() {
120
+ this.#removeStorageListener?.();
121
+ this.#removeStorageListener = null;
122
+ }
123
+ /** Creates a new passkey, which gives a new address, and connects it unlocked. */
124
+ #create = async ({ label } = {}) => {
125
+ await this.#connectSecret(await createPasskey(this.#webauthn, label));
126
+ return { accounts: this.accounts };
127
+ };
128
+ #connect = async (input) => {
129
+ if (input?.silent !== true && this.#state == null) await this.#connectSecret(await getPasskeySecret(this.#webauthn));
130
+ return { accounts: this.accounts };
131
+ };
132
+ #disconnect = async () => {
133
+ this.#session = null;
134
+ this.#state = null;
135
+ try {
136
+ localStorage.removeItem(this.#storageKey);
137
+ } catch {}
138
+ this.#setAccounts([]);
139
+ await this.#deleteStoredSession();
140
+ };
141
+ #on = (event, listener) => {
142
+ this.#events.on(event, listener);
143
+ return () => {
144
+ this.#events.off(event, listener);
145
+ };
146
+ };
147
+ #signTransaction = async ({ transaction, account, chain, signal }) => {
148
+ signal?.throwIfAborted();
149
+ this.#assertConnected(account.address);
150
+ const { bytes } = await this.#buildTransaction(transaction, account.address, this.#getClient(chain));
151
+ return (await this.#getSigner(account.address)).signTransaction(bytes);
152
+ };
153
+ #signAndExecuteTransaction = async ({ transaction, account, chain, signal }) => {
154
+ signal?.throwIfAborted();
155
+ this.#assertConnected(account.address);
156
+ const client = this.#getClient(chain);
157
+ const { parsedTransaction, bytes } = await this.#buildTransaction(transaction, account.address, client);
158
+ const result = await (await this.#getSigner(account.address)).signAndExecuteTransaction({
159
+ transaction: parsedTransaction,
160
+ client
161
+ });
162
+ const executed = result.Transaction ?? result.FailedTransaction;
163
+ const [signature] = executed.signatures;
164
+ if (signature == null || executed.effects.bcs == null) throw new Error(`Transaction ${executed.digest} was executed but returned no signature or effects.`);
165
+ return {
166
+ bytes: toBase64(bytes),
167
+ signature,
168
+ digest: executed.digest,
169
+ effects: toBase64(executed.effects.bcs)
170
+ };
171
+ };
172
+ #signPersonalMessage = async ({ message, account }) => {
173
+ return (await this.#getSigner(account.address)).signPersonalMessage(message);
174
+ };
175
+ async #buildTransaction(transaction, sender, client) {
176
+ const parsedTransaction = Transaction.from(await transaction.toJSON());
177
+ parsedTransaction.setSenderIfNotSet(sender);
178
+ return {
179
+ parsedTransaction,
180
+ bytes: await parsedTransaction.build({ client })
181
+ };
182
+ }
183
+ #getClient(chain) {
184
+ const client = this.#clients.find(({ network }) => `sui:${network}` === chain);
185
+ if (client == null) throw new Error(`Unsupported chain ${chain}. Use one of: ${this.chains.join(", ")}.`);
186
+ return client;
187
+ }
188
+ #assertConnected(address) {
189
+ if (this.#state?.address !== address) throw new Error(`Account ${address} is not connected to the passkey wallet.`);
190
+ return this.#state;
191
+ }
192
+ async #getSigner(address) {
193
+ return this.#getSessionSigner(this.#assertConnected(address));
194
+ }
195
+ /** Returns the session key from memory or IndexedDB, or asks for the passkey once. */
196
+ async #getSessionSigner(state) {
197
+ const fresh = this.#session == null;
198
+ const session = this.#session ??= this.#readStoredSession(state).then((stored) => stored ?? this.#createSession(state));
199
+ let result;
200
+ try {
201
+ result = await session;
202
+ } catch (error) {
203
+ if (this.#session === session) this.#session = null;
204
+ throw error;
205
+ }
206
+ if (fresh || result.expiresAt > Date.now()) return result.signer;
207
+ if (this.#session === session) this.#session = null;
208
+ return this.#getSessionSigner(state);
209
+ }
210
+ /** Asks for the passkey and starts a new session for the connected wallet. */
211
+ async #createSession(state) {
212
+ const secret = await getPasskeySecret(this.#webauthn, state.credentialId);
213
+ const signer = await deriveSigner(secret.prfOutput);
214
+ if (signer.toSuiAddress() !== state.address) throw new PasskeyWalletMismatchError("This passkey opens a different wallet than the connected one.");
215
+ return this.#storeSession(signer);
216
+ }
217
+ async #connectSecret({ credentialId, prfOutput }) {
218
+ const signer = await deriveSigner(prfOutput);
219
+ const publicKey = signer.getPublicKey();
220
+ this.#session = Promise.resolve(await this.#storeSession(signer));
221
+ this.#setState({
222
+ address: publicKey.toSuiAddress(),
223
+ publicKey,
224
+ credentialId
225
+ });
226
+ }
227
+ async #readStoredSession(state) {
228
+ if (this.#keyStore == null) return null;
229
+ try {
230
+ const stored = await get(this.#storageKey, this.#keyStore);
231
+ if (stored == null) return null;
232
+ const signer = WebCryptoSigner.import(stored);
233
+ if (stored.expiresAt > Date.now() && signer.toSuiAddress() === state.address) return {
234
+ signer,
235
+ expiresAt: stored.expiresAt
236
+ };
237
+ } catch {
238
+ return null;
239
+ }
240
+ await this.#deleteStoredSession();
241
+ return null;
242
+ }
243
+ /**
244
+ * Saves the key in IndexedDB and returns it with its expiry. A memory-only key lasts until
245
+ * reload.
246
+ */
247
+ async #storeSession(signer) {
248
+ if (this.#keyStore == null) return {
249
+ signer,
250
+ expiresAt: 1e400
251
+ };
252
+ const expiresAt = Date.now() + this.#sessionDurationMs;
253
+ try {
254
+ await set(this.#storageKey, {
255
+ ...signer.export(),
256
+ expiresAt
257
+ }, this.#keyStore);
258
+ } catch {}
259
+ return {
260
+ signer,
261
+ expiresAt
262
+ };
263
+ }
264
+ async #deleteStoredSession() {
265
+ if (this.#keyStore == null) return;
266
+ try {
267
+ await del(this.#storageKey, this.#keyStore);
268
+ } catch {}
269
+ }
270
+ #setState(state) {
271
+ this.#state = state;
272
+ this.#writeStoredState(state);
273
+ this.#setAccounts([this.#createAccount(state)]);
274
+ }
275
+ #setAccounts(accounts) {
276
+ this.#accounts = accounts;
277
+ this.#events.emit("change", { accounts: this.accounts });
278
+ }
279
+ #createAccount({ address, publicKey }) {
280
+ return new ReadonlyWalletAccount({
281
+ address,
282
+ chains: this.chains,
283
+ icon: this.icon,
284
+ features: [
285
+ SuiSignPersonalMessage,
286
+ SuiSignTransaction,
287
+ SuiSignAndExecuteTransaction
288
+ ],
289
+ publicKey: publicKey.toRawBytes()
290
+ });
291
+ }
292
+ /** Loads the connected wallet from storage and returns its accounts. */
293
+ #loadState() {
294
+ this.#state = this.#readStoredState();
295
+ return this.#state == null ? [] : [this.#createAccount(this.#state)];
296
+ }
297
+ #readStoredState() {
298
+ try {
299
+ const stored = JSON.parse(localStorage.getItem(this.#storageKey) ?? "null");
300
+ if (typeof stored !== "object" || stored == null || !("publicKey" in stored) || !("credentialId" in stored) || typeof stored.publicKey !== "string" || typeof stored.credentialId !== "string") return null;
301
+ const publicKey = new Secp256r1PublicKey(fromBase64(stored.publicKey));
302
+ return {
303
+ address: publicKey.toSuiAddress(),
304
+ publicKey,
305
+ credentialId: fromBase64(stored.credentialId)
306
+ };
307
+ } catch {
308
+ return null;
309
+ }
310
+ }
311
+ #writeStoredState({ publicKey, credentialId }) {
312
+ const stored = {
313
+ publicKey: publicKey.toBase64(),
314
+ credentialId: toBase64(credentialId)
315
+ };
316
+ try {
317
+ localStorage.setItem(this.#storageKey, JSON.stringify(stored));
318
+ } catch {}
319
+ }
320
+ };
321
+ export { PasskeyWallet };
322
+
323
+ //# sourceMappingURL=wallet.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wallet.mjs","names":[],"sources":["../../src/wallet/wallet.ts"],"sourcesContent":["// Copyright (c) Sugar\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { ClientWithCoreApi } from '@mysten/sui/client';\nimport { Secp256r1PublicKey } from '@mysten/sui/keypairs/secp256r1';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { fromBase64, toBase64 } from '@mysten/sui/utils';\nimport { type Emitter, mitt } from '@mysten/utils';\nimport {\n\ttype IdentifierString,\n\tReadonlyWalletAccount,\n\tStandardConnect,\n\ttype StandardConnectFeature,\n\ttype StandardConnectMethod,\n\tStandardDisconnect,\n\ttype StandardDisconnectFeature,\n\ttype StandardDisconnectMethod,\n\tStandardEvents,\n\ttype StandardEventsFeature,\n\ttype StandardEventsOnMethod,\n\tSuiSignAndExecuteTransaction,\n\ttype SuiSignAndExecuteTransactionFeature,\n\ttype SuiSignAndExecuteTransactionMethod,\n\tSuiSignPersonalMessage,\n\ttype SuiSignPersonalMessageFeature,\n\ttype SuiSignPersonalMessageMethod,\n\tSuiSignTransaction,\n\ttype SuiSignTransactionFeature,\n\ttype SuiSignTransactionInput,\n\ttype SuiSignTransactionMethod,\n\ttype Wallet,\n\ttype WalletAccount,\n\ttype WalletIcon,\n} from '@mysten/wallet-standard';\nimport { WebCryptoSigner } from '@mysten/webcrypto-signer';\nimport { utf8ToBytes } from '@noble/hashes/utils.js';\nimport { createStore, del, get, set, type UseStore } from 'idb-keyval';\nimport { NAMESPACE } from '../constants.js';\nimport { PasskeyWalletMismatchError } from '../errors.js';\nimport { deriveSigner } from '../key.js';\nimport {\n\tcreatePasskey,\n\tgetPasskeySecret,\n\ttype PasskeySecret,\n\ttype WebAuthnOptions,\n} from '../provider.js';\nimport {\n\tPasskeyWalletCreate,\n\ttype PasskeyWalletCreateFeature,\n\ttype PasskeyWalletCreateMethod,\n} from './features.js';\nimport type {\n\tPasskeyWalletOptions,\n\tSession,\n\tStoredSession,\n\tStoredState,\n\tWalletEventsMap,\n\tWalletState,\n} from './types.js';\n\nconst STORAGE_KEY_PREFIX = `${NAMESPACE}:v1:`;\n\nconst DEFAULT_SESSION_DURATION_MS = 7 * 24 * 60 * 60 * 1000;\n\nconst DEFAULT_PROMPT_TIMEOUT_MS = 60_000;\n\nconst ICON_SVG =\n\t'<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"6 6 180 180\"><defs><linearGradient id=\"g\" x2=\"0\" y2=\"1\"><stop offset=\"0\" stop-color=\"#afbdce\"/><stop offset=\"1\" stop-color=\"#7d88a1\"/></linearGradient><g id=\"k\"><path fill-rule=\"evenodd\" d=\"M116.5 91a19.5 19.5 0 1 0 39 0 19.5 19.5 0 1 0-39 0zm13.5-6a6.5 6.5 0 1 0 13 0 6.5 6.5 0 1 0-13 0z\"/><path d=\"M130.5 104h11.5v8l8 10-8 8v3l5 5.5v1.5l-4 4-6.5 7h-.5l-5.5-6.5z\"/></g><mask id=\"m\"><rect x=\"6\" y=\"6\" width=\"180\" height=\"180\" fill=\"#fff\"/><use href=\"#k\" stroke=\"#000\" stroke-width=\"22\" stroke-linejoin=\"round\"/></mask></defs><rect x=\"6\" y=\"6\" width=\"180\" height=\"180\" rx=\"40\" fill=\"url(#g)\"/><g fill=\"#fff\" stroke=\"#fff\"><circle cx=\"82.5\" cy=\"66.5\" r=\"23.5\" stroke=\"none\"/><path mask=\"url(#m)\" stroke=\"none\" d=\"M35 137c0-21 21-36 47.5-36S130 116 130 137v2a4 4 0 0 1-4 4H39a4 4 0 0 1-4-4z\"/><use href=\"#k\" stroke-width=\"1.5\" stroke-linejoin=\"round\"/></g></svg>';\n\nconst ICON: WalletIcon = `data:image/svg+xml;base64,${toBase64(utf8ToBytes(ICON_SVG))}`;\n\n/**\n * Wallet Standard wallet unlocked by a passkey.\n *\n * The wallet key is a secp256r1 key derived from the passkey with the WebAuthn PRF extension, so a\n * synced passkey opens the same wallet on every device. Once unlocked, the key is a non-extractable\n * WebCrypto key kept in IndexedDB for `sessionDurationMs`, so signatures and reloads need no\n * prompt. `localStorage` holds only the public key and credential ID. Disconnecting deletes both.\n * Browser only.\n */\nexport class PasskeyWallet implements Wallet {\n\treadonly #events: Emitter<WalletEventsMap> = mitt();\n\treadonly #clients: Array<ClientWithCoreApi>;\n\treadonly #webauthn: WebAuthnOptions;\n\treadonly #name: string;\n\treadonly #icon: WalletIcon;\n\treadonly #storageKey: string;\n\treadonly #sessionDurationMs: number;\n\treadonly #keyStore: UseStore | null;\n\t#state: WalletState | null = null;\n\t#session: Promise<Session> | null = null;\n\t#accounts: Array<ReadonlyWalletAccount> = [];\n\t#removeStorageListener: (() => void) | null = null;\n\n\tconstructor({\n\t\tclients,\n\t\tsessionDurationMs = DEFAULT_SESSION_DURATION_MS,\n\t\twebauthn: { rpName, rpId = location.hostname, promptTimeoutMs = DEFAULT_PROMPT_TIMEOUT_MS },\n\t\twallet: { name = 'Passkey', icon = ICON } = {},\n\t}: PasskeyWalletOptions) {\n\t\tif (clients.length === 0) {\n\t\t\tthrow new Error('At least one Sui client is required.');\n\t\t}\n\n\t\tif (!Number.isFinite(sessionDurationMs) || sessionDurationMs < 0) {\n\t\t\tthrow new Error('sessionDurationMs must be a finite number of milliseconds, 0 or more.');\n\t\t}\n\n\t\tif (!Number.isFinite(promptTimeoutMs) || promptTimeoutMs <= 0) {\n\t\t\tthrow new Error('promptTimeoutMs must be a finite number of milliseconds, more than 0.');\n\t\t}\n\n\t\tthis.#clients = clients;\n\t\tthis.#webauthn = { rpId, rpName, timeoutMs: promptTimeoutMs };\n\t\tthis.#name = name;\n\t\tthis.#icon = icon;\n\t\tthis.#storageKey = `${STORAGE_KEY_PREFIX}${rpId}`;\n\t\tthis.#sessionDurationMs = sessionDurationMs;\n\t\tthis.#keyStore = sessionDurationMs > 0 ? createStore(NAMESPACE, 'keys') : null;\n\t\tthis.#accounts = this.#loadState();\n\n\t\tif (typeof window !== 'undefined') {\n\t\t\t// Follow connections and disconnections made in other tabs.\n\t\t\tconst onStorage = (event: StorageEvent) => {\n\t\t\t\tif (event.key === this.#storageKey || event.key === null) {\n\t\t\t\t\tconst address = this.#state?.address;\n\t\t\t\t\tthis.#setAccounts(this.#loadState());\n\t\t\t\t\tif (this.#state?.address !== address) {\n\t\t\t\t\t\tthis.#session = null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\twindow.addEventListener('storage', onStorage);\n\t\t\tthis.#removeStorageListener = () => {\n\t\t\t\twindow.removeEventListener('storage', onStorage);\n\t\t\t};\n\t\t}\n\t}\n\n\tget version() {\n\t\treturn '1.0.0' as const;\n\t}\n\n\tget name() {\n\t\treturn this.#name;\n\t}\n\n\tget icon() {\n\t\treturn this.#icon;\n\t}\n\n\tget chains() {\n\t\treturn this.#clients.map((client) => `sui:${client.network}` as const);\n\t}\n\n\tget accounts(): ReadonlyArray<WalletAccount> {\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Same shape: only `label?: string` differs under exactOptionalPropertyTypes.\n\t\treturn this.#accounts as ReadonlyArray<WalletAccount>;\n\t}\n\n\tget features(): StandardConnectFeature &\n\t\tStandardDisconnectFeature &\n\t\tStandardEventsFeature &\n\t\tSuiSignTransactionFeature &\n\t\tSuiSignAndExecuteTransactionFeature &\n\t\tSuiSignPersonalMessageFeature &\n\t\tPasskeyWalletCreateFeature {\n\t\treturn {\n\t\t\t[StandardConnect]: { version: '1.0.0', connect: this.#connect },\n\t\t\t[StandardDisconnect]: { version: '1.0.0', disconnect: this.#disconnect },\n\t\t\t[StandardEvents]: { version: '1.0.0', on: this.#on },\n\t\t\t[SuiSignTransaction]: { version: '2.0.0', signTransaction: this.#signTransaction },\n\t\t\t[SuiSignAndExecuteTransaction]: {\n\t\t\t\tversion: '2.0.0',\n\t\t\t\tsignAndExecuteTransaction: this.#signAndExecuteTransaction,\n\t\t\t},\n\t\t\t[SuiSignPersonalMessage]: {\n\t\t\t\tversion: '1.1.0',\n\t\t\t\tsignPersonalMessage: this.#signPersonalMessage,\n\t\t\t},\n\t\t\t[PasskeyWalletCreate]: { version: '1.0.0', create: this.#create },\n\t\t};\n\t}\n\n\t/** Stops following other tabs. `registerPasskeyWallet()` calls it on unregister. */\n\tdispose() {\n\t\tthis.#removeStorageListener?.();\n\t\tthis.#removeStorageListener = null;\n\t}\n\n\t/** Creates a new passkey, which gives a new address, and connects it unlocked. */\n\t#create: PasskeyWalletCreateMethod = async ({ label } = {}) => {\n\t\tawait this.#connectSecret(await createPasskey(this.#webauthn, label));\n\t\treturn { accounts: this.accounts };\n\t};\n\n\t#connect: StandardConnectMethod = async (input) => {\n\t\t// Opens the wallet of any passkey of the relying party, such as one synced from another\n\t\t// device. Never create one implicitly: an unexpected new address would look like lost funds.\n\t\tif (input?.silent !== true && this.#state == null) {\n\t\t\tawait this.#connectSecret(await getPasskeySecret(this.#webauthn));\n\t\t}\n\n\t\treturn { accounts: this.accounts };\n\t};\n\n\t// Forgets the wallet on this browser, so the next user of a shared browser cannot see\n\t// which address was used.\n\t#disconnect: StandardDisconnectMethod = async () => {\n\t\tthis.#session = null;\n\t\tthis.#state = null;\n\t\ttry {\n\t\t\tlocalStorage.removeItem(this.#storageKey);\n\t\t} catch {\n\t\t\t// Storage is blocked: nothing was saved.\n\t\t}\n\n\t\tthis.#setAccounts([]);\n\t\tawait this.#deleteStoredSession();\n\t};\n\n\t#on: StandardEventsOnMethod = (event, listener) => {\n\t\tthis.#events.on(event, listener);\n\t\treturn () => {\n\t\t\tthis.#events.off(event, listener);\n\t\t};\n\t};\n\n\t#signTransaction: SuiSignTransactionMethod = async ({ transaction, account, chain, signal }) => {\n\t\tsignal?.throwIfAborted();\n\t\tthis.#assertConnected(account.address);\n\t\tconst { bytes } = await this.#buildTransaction(\n\t\t\ttransaction,\n\t\t\taccount.address,\n\t\t\tthis.#getClient(chain),\n\t\t);\n\t\tconst signer = await this.#getSigner(account.address);\n\t\treturn signer.signTransaction(bytes);\n\t};\n\n\t#signAndExecuteTransaction: SuiSignAndExecuteTransactionMethod = async ({\n\t\ttransaction,\n\t\taccount,\n\t\tchain,\n\t\tsignal,\n\t}) => {\n\t\tsignal?.throwIfAborted();\n\t\tthis.#assertConnected(account.address);\n\t\tconst client = this.#getClient(chain);\n\t\tconst { parsedTransaction, bytes } = await this.#buildTransaction(\n\t\t\ttransaction,\n\t\t\taccount.address,\n\t\t\tclient,\n\t\t);\n\t\tconst signer = await this.#getSigner(account.address);\n\t\tconst result = await signer.signAndExecuteTransaction({\n\t\t\ttransaction: parsedTransaction,\n\t\t\tclient,\n\t\t});\n\t\tconst executed = result.Transaction ?? result.FailedTransaction;\n\t\tconst [signature] = executed.signatures;\n\n\t\tif (signature == null || executed.effects.bcs == null) {\n\t\t\tthrow new Error(\n\t\t\t\t`Transaction ${executed.digest} was executed but returned no signature or effects.`,\n\t\t\t);\n\t\t}\n\n\t\treturn {\n\t\t\tbytes: toBase64(bytes),\n\t\t\tsignature,\n\t\t\tdigest: executed.digest,\n\t\t\teffects: toBase64(executed.effects.bcs),\n\t\t};\n\t};\n\n\t#signPersonalMessage: SuiSignPersonalMessageMethod = async ({ message, account }) => {\n\t\tconst signer = await this.#getSigner(account.address);\n\t\treturn signer.signPersonalMessage(message);\n\t};\n\n\tasync #buildTransaction(\n\t\ttransaction: SuiSignTransactionInput['transaction'],\n\t\tsender: string,\n\t\tclient: ClientWithCoreApi,\n\t) {\n\t\tconst parsedTransaction = Transaction.from(await transaction.toJSON());\n\t\tparsedTransaction.setSenderIfNotSet(sender);\n\t\treturn { parsedTransaction, bytes: await parsedTransaction.build({ client }) };\n\t}\n\n\t#getClient(chain: IdentifierString) {\n\t\tconst client = this.#clients.find(({ network }) => `sui:${network}` === chain);\n\t\tif (client == null) {\n\t\t\tthrow new Error(`Unsupported chain ${chain}. Use one of: ${this.chains.join(', ')}.`);\n\t\t}\n\n\t\treturn client;\n\t}\n\n\t#assertConnected(address: string) {\n\t\tif (this.#state?.address !== address) {\n\t\t\tthrow new Error(`Account ${address} is not connected to the passkey wallet.`);\n\t\t}\n\n\t\treturn this.#state;\n\t}\n\n\tasync #getSigner(address: string) {\n\t\treturn this.#getSessionSigner(this.#assertConnected(address));\n\t}\n\n\t/** Returns the session key from memory or IndexedDB, or asks for the passkey once. */\n\tasync #getSessionSigner(state: WalletState): Promise<WebCryptoSigner> {\n\t\tconst fresh = this.#session == null;\n\t\t// Concurrent signatures share one passkey prompt.\n\t\tconst session = (this.#session ??= this.#readStoredSession(state).then(\n\t\t\t(stored) => stored ?? this.#createSession(state),\n\t\t));\n\t\tlet result: Session;\n\t\ttry {\n\t\t\tresult = await session;\n\t\t} catch (error) {\n\t\t\tif (this.#session === session) {\n\t\t\t\tthis.#session = null;\n\t\t\t}\n\n\t\t\tthrow error;\n\t\t}\n\n\t\t// A key just unlocked always signs once, even with a tiny sessionDurationMs.\n\t\tif (fresh || result.expiresAt > Date.now()) {\n\t\t\treturn result.signer;\n\t\t}\n\n\t\t// Expired while the page stayed open: ask for the passkey again.\n\t\tif (this.#session === session) {\n\t\t\tthis.#session = null;\n\t\t}\n\n\t\treturn this.#getSessionSigner(state);\n\t}\n\n\t/** Asks for the passkey and starts a new session for the connected wallet. */\n\tasync #createSession(state: WalletState): Promise<Session> {\n\t\tconst secret = await getPasskeySecret(this.#webauthn, state.credentialId);\n\t\tconst signer = await deriveSigner(secret.prfOutput);\n\t\tif (signer.toSuiAddress() !== state.address) {\n\t\t\tthrow new PasskeyWalletMismatchError(\n\t\t\t\t'This passkey opens a different wallet than the connected one.',\n\t\t\t);\n\t\t}\n\n\t\treturn this.#storeSession(signer);\n\t}\n\n\tasync #connectSecret({ credentialId, prfOutput }: PasskeySecret) {\n\t\tconst signer = await deriveSigner(prfOutput);\n\t\tconst publicKey = signer.getPublicKey();\n\t\tthis.#session = Promise.resolve(await this.#storeSession(signer));\n\t\tthis.#setState({ address: publicKey.toSuiAddress(), publicKey, credentialId });\n\t}\n\n\tasync #readStoredSession(state: WalletState): Promise<Session | null> {\n\t\tif (this.#keyStore == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stored = await get<StoredSession>(this.#storageKey, this.#keyStore);\n\t\t\tif (stored == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst signer = WebCryptoSigner.import(stored);\n\t\t\tif (stored.expiresAt > Date.now() && signer.toSuiAddress() === state.address) {\n\t\t\t\treturn { signer, expiresAt: stored.expiresAt };\n\t\t\t}\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\n\t\tawait this.#deleteStoredSession();\n\t\treturn null;\n\t}\n\n\t/**\n\t * Saves the key in IndexedDB and returns it with its expiry. A memory-only key lasts until\n\t * reload.\n\t */\n\tasync #storeSession(signer: WebCryptoSigner): Promise<Session> {\n\t\tif (this.#keyStore == null) {\n\t\t\treturn { signer, expiresAt: Infinity };\n\t\t}\n\n\t\tconst expiresAt = Date.now() + this.#sessionDurationMs;\n\t\ttry {\n\t\t\tawait set(\n\t\t\t\tthis.#storageKey,\n\t\t\t\t{ ...signer.export(), expiresAt } satisfies StoredSession,\n\t\t\t\tthis.#keyStore,\n\t\t\t);\n\t\t} catch {\n\t\t\t// IndexedDB is blocked: the key stays in memory until it expires or the page reloads.\n\t\t}\n\n\t\treturn { signer, expiresAt };\n\t}\n\n\tasync #deleteStoredSession() {\n\t\tif (this.#keyStore == null) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tawait del(this.#storageKey, this.#keyStore);\n\t\t} catch {\n\t\t\t// Nothing to delete when IndexedDB is blocked.\n\t\t}\n\t}\n\n\t#setState(state: WalletState) {\n\t\tthis.#state = state;\n\t\tthis.#writeStoredState(state);\n\t\tthis.#setAccounts([this.#createAccount(state)]);\n\t}\n\n\t#setAccounts(accounts: Array<ReadonlyWalletAccount>) {\n\t\tthis.#accounts = accounts;\n\t\tthis.#events.emit('change', { accounts: this.accounts });\n\t}\n\n\t#createAccount({ address, publicKey }: WalletState) {\n\t\treturn new ReadonlyWalletAccount({\n\t\t\taddress,\n\t\t\tchains: this.chains,\n\t\t\ticon: this.icon,\n\t\t\tfeatures: [SuiSignPersonalMessage, SuiSignTransaction, SuiSignAndExecuteTransaction],\n\t\t\tpublicKey: publicKey.toRawBytes(),\n\t\t});\n\t}\n\n\t/** Loads the connected wallet from storage and returns its accounts. */\n\t#loadState() {\n\t\tthis.#state = this.#readStoredState();\n\t\treturn this.#state == null ? [] : [this.#createAccount(this.#state)];\n\t}\n\n\t#readStoredState(): WalletState | null {\n\t\ttry {\n\t\t\tconst stored: unknown = JSON.parse(localStorage.getItem(this.#storageKey) ?? 'null');\n\t\t\tif (\n\t\t\t\ttypeof stored !== 'object' ||\n\t\t\t\tstored == null ||\n\t\t\t\t!('publicKey' in stored) ||\n\t\t\t\t!('credentialId' in stored) ||\n\t\t\t\ttypeof stored.publicKey !== 'string' ||\n\t\t\t\ttypeof stored.credentialId !== 'string'\n\t\t\t) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Rejects malformed public keys before they are shown as an address.\n\t\t\tconst publicKey = new Secp256r1PublicKey(fromBase64(stored.publicKey));\n\t\t\treturn {\n\t\t\t\taddress: publicKey.toSuiAddress(),\n\t\t\t\tpublicKey,\n\t\t\t\tcredentialId: fromBase64(stored.credentialId),\n\t\t\t};\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t#writeStoredState({ publicKey, credentialId }: WalletState) {\n\t\tconst stored: StoredState = {\n\t\t\tpublicKey: publicKey.toBase64(),\n\t\t\tcredentialId: toBase64(credentialId),\n\t\t};\n\n\t\ttry {\n\t\t\tlocalStorage.setItem(this.#storageKey, JSON.stringify(stored));\n\t\t} catch {\n\t\t\t// Storage is blocked or full: the wallet stays connected in memory until the page reloads.\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA4DA,MAAM,qBAAqB,GAAG,UAAU;AAExC,MAAM,8BAA8B;AAEpC,MAAM,4BAA4B;AAKlC,MAAM,OAAmB,6BAA6B,SAAS,YAAY,g+BAAQ,CAAC;;;;;;;;;;AAWpF,IAAa,gBAAb,MAA6C;CACnC,UAAoC,KAAK;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACT,SAA6B;CAC7B,WAAoC;CACpC,YAA0C,CAAC;CAC3C,yBAA8C;CAE9C,YAAY,EACX,SACA,oBAAoB,6BACpB,UAAU,EAAE,QAAQ,OAAO,SAAS,UAAU,kBAAkB,6BAChE,QAAQ,EAAE,OAAO,WAAW,OAAO,SAAS,CAAC,KACrB;EACxB,IAAI,QAAQ,WAAW,GACtB,MAAM,IAAI,MAAM,sCAAsC;EAGvD,IAAI,CAAC,OAAO,SAAS,iBAAiB,KAAK,oBAAoB,GAC9D,MAAM,IAAI,MAAM,uEAAuE;EAGxF,IAAI,CAAC,OAAO,SAAS,eAAe,KAAK,mBAAmB,GAC3D,MAAM,IAAI,MAAM,uEAAuE;EAGxF,KAAK,WAAW;EAChB,KAAK,YAAY;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