@mysten/enoki 0.6.20 → 0.7.1

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/cjs/EnokiFlow.js +1 -1
  3. package/dist/cjs/EnokiFlow.js.map +2 -2
  4. package/dist/cjs/index.d.ts +2 -1
  5. package/dist/cjs/index.js +8 -3
  6. package/dist/cjs/index.js.map +3 -3
  7. package/dist/cjs/wallet/feature.d.ts +31 -0
  8. package/dist/cjs/wallet/feature.js +25 -0
  9. package/dist/cjs/wallet/feature.js.map +7 -0
  10. package/dist/cjs/wallet/index.d.ts +2 -2
  11. package/dist/cjs/wallet/index.js +24 -12
  12. package/dist/cjs/wallet/index.js.map +2 -2
  13. package/dist/cjs/wallet/state.d.ts +1 -1
  14. package/dist/cjs/wallet/state.js +2 -2
  15. package/dist/cjs/wallet/state.js.map +2 -2
  16. package/dist/cjs/wallet/utils.d.ts +9 -0
  17. package/dist/cjs/wallet/utils.js +65 -0
  18. package/dist/cjs/wallet/utils.js.map +7 -0
  19. package/dist/esm/EnokiFlow.js +1 -1
  20. package/dist/esm/EnokiFlow.js.map +2 -2
  21. package/dist/esm/index.d.ts +2 -1
  22. package/dist/esm/index.js +12 -1
  23. package/dist/esm/index.js.map +2 -2
  24. package/dist/esm/wallet/feature.d.ts +31 -0
  25. package/dist/esm/wallet/feature.js +5 -0
  26. package/dist/esm/wallet/feature.js.map +7 -0
  27. package/dist/esm/wallet/index.d.ts +2 -2
  28. package/dist/esm/wallet/index.js +34 -13
  29. package/dist/esm/wallet/index.js.map +2 -2
  30. package/dist/esm/wallet/state.d.ts +1 -1
  31. package/dist/esm/wallet/state.js +2 -2
  32. package/dist/esm/wallet/state.js.map +2 -2
  33. package/dist/esm/wallet/utils.d.ts +9 -0
  34. package/dist/esm/wallet/utils.js +45 -0
  35. package/dist/esm/wallet/utils.js.map +7 -0
  36. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  37. package/dist/tsconfig.tsbuildinfo +1 -1
  38. package/package.json +6 -5
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var utils_exports = {};
20
+ __export(utils_exports, {
21
+ getWalletMetadata: () => getWalletMetadata,
22
+ isEnokiWallet: () => isEnokiWallet,
23
+ isFacebookWallet: () => isFacebookWallet,
24
+ isGoogleWallet: () => isGoogleWallet,
25
+ isTwitchWallet: () => isTwitchWallet
26
+ });
27
+ module.exports = __toCommonJS(utils_exports);
28
+ var import_ui = require("@wallet-standard/ui");
29
+ var import_feature = require("./feature.js");
30
+ function isEnokiWallet(wallet) {
31
+ if (isWalletHandle(wallet)) {
32
+ return wallet.features.includes(import_feature.EnokiGetMetadata);
33
+ }
34
+ return import_feature.EnokiGetMetadata in wallet.features;
35
+ }
36
+ function getWalletMetadata(wallet) {
37
+ if (isWalletHandle(wallet)) {
38
+ try {
39
+ const { getMetadata } = (0, import_ui.getWalletFeature)(
40
+ wallet,
41
+ import_feature.EnokiGetMetadata
42
+ );
43
+ return getMetadata();
44
+ } catch (error) {
45
+ return null;
46
+ }
47
+ } else if (import_feature.EnokiGetMetadata in wallet.features) {
48
+ const walletWithFeature = wallet;
49
+ return walletWithFeature.features[import_feature.EnokiGetMetadata].getMetadata();
50
+ }
51
+ return null;
52
+ }
53
+ function isGoogleWallet(wallet) {
54
+ return getWalletMetadata(wallet)?.provider === "google";
55
+ }
56
+ function isTwitchWallet(wallet) {
57
+ return getWalletMetadata(wallet)?.provider === "twitch";
58
+ }
59
+ function isFacebookWallet(wallet) {
60
+ return getWalletMetadata(wallet)?.provider === "facebook";
61
+ }
62
+ function isWalletHandle(wallet) {
63
+ return Array.isArray(wallet.features);
64
+ }
65
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/wallet/utils.ts"],
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Wallet, WalletWithFeatures } from '@mysten/wallet-standard';\nimport type { UiWallet } from '@wallet-standard/ui';\nimport { getWalletFeature } from '@wallet-standard/ui';\nimport type { EnokiWallet } from './index.js';\nimport type { EnokiGetMetadataFeature } from './feature.js';\nimport { EnokiGetMetadata } from './feature.js';\n\nexport function isEnokiWallet(wallet: UiWallet): boolean;\nexport function isEnokiWallet(wallet: Wallet): wallet is EnokiWallet;\nexport function isEnokiWallet(wallet: Wallet | UiWallet) {\n\tif (isWalletHandle(wallet)) {\n\t\treturn wallet.features.includes(EnokiGetMetadata);\n\t}\n\treturn EnokiGetMetadata in wallet.features;\n}\n\nexport function getWalletMetadata(wallet: Wallet | UiWallet) {\n\tif (isWalletHandle(wallet)) {\n\t\ttry {\n\t\t\tconst { getMetadata } = getWalletFeature(\n\t\t\t\twallet,\n\t\t\t\tEnokiGetMetadata,\n\t\t\t) as EnokiGetMetadataFeature[typeof EnokiGetMetadata];\n\n\t\t\treturn getMetadata();\n\t\t} catch (error) {\n\t\t\treturn null;\n\t\t}\n\t} else if (EnokiGetMetadata in wallet.features) {\n\t\tconst walletWithFeature = wallet as WalletWithFeatures<EnokiGetMetadataFeature>;\n\t\treturn walletWithFeature.features[EnokiGetMetadata].getMetadata();\n\t}\n\treturn null;\n}\n\nexport function isGoogleWallet(wallet: Wallet | UiWallet) {\n\treturn getWalletMetadata(wallet)?.provider === 'google';\n}\n\nexport function isTwitchWallet(wallet: Wallet | UiWallet) {\n\treturn getWalletMetadata(wallet)?.provider === 'twitch';\n}\n\nexport function isFacebookWallet(wallet: Wallet | UiWallet) {\n\treturn getWalletMetadata(wallet)?.provider === 'facebook';\n}\n\nfunction isWalletHandle(wallet: UiWallet | Wallet): wallet is UiWallet {\n\t// TypeScript doesn't properly narrow readonly arrays:\n\t// https://github.com/microsoft/TypeScript/issues/1700\n\treturn Array.isArray(wallet.features);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,gBAAiC;AAGjC,qBAAiC;AAI1B,SAAS,cAAc,QAA2B;AACxD,MAAI,eAAe,MAAM,GAAG;AAC3B,WAAO,OAAO,SAAS,SAAS,+BAAgB;AAAA,EACjD;AACA,SAAO,mCAAoB,OAAO;AACnC;AAEO,SAAS,kBAAkB,QAA2B;AAC5D,MAAI,eAAe,MAAM,GAAG;AAC3B,QAAI;AACH,YAAM,EAAE,YAAY,QAAI;AAAA,QACvB;AAAA,QACA;AAAA,MACD;AAEA,aAAO,YAAY;AAAA,IACpB,SAAS,OAAO;AACf,aAAO;AAAA,IACR;AAAA,EACD,WAAW,mCAAoB,OAAO,UAAU;AAC/C,UAAM,oBAAoB;AAC1B,WAAO,kBAAkB,SAAS,+BAAgB,EAAE,YAAY;AAAA,EACjE;AACA,SAAO;AACR;AAEO,SAAS,eAAe,QAA2B;AACzD,SAAO,kBAAkB,MAAM,GAAG,aAAa;AAChD;AAEO,SAAS,eAAe,QAA2B;AACzD,SAAO,kBAAkB,MAAM,GAAG,aAAa;AAChD;AAEO,SAAS,iBAAiB,QAA2B;AAC3D,SAAO,kBAAkB,MAAM,GAAG,aAAa;AAChD;AAEA,SAAS,eAAe,QAA+C;AAGtE,SAAO,MAAM,QAAQ,OAAO,QAAQ;AACrC;",
6
+ "names": []
7
+ }
@@ -39,7 +39,7 @@ class EnokiFlow {
39
39
  __privateSet(this, _encryptionKey, config.apiKey);
40
40
  if (config.experimental_nativeCryptoSigner) {
41
41
  __privateSet(this, _useNativeCryptoSigner, true);
42
- __privateSet(this, _idbStore, createStore("enoki", config.apiKey));
42
+ __privateSet(this, _idbStore, createStore(config.apiKey, "enoki"));
43
43
  } else {
44
44
  __privateSet(this, _useNativeCryptoSigner, false);
45
45
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/EnokiFlow.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { ExportedWebCryptoKeypair } from '@mysten/signers/webcrypto';\nimport { WebCryptoSigner } from '@mysten/signers/webcrypto';\nimport { decodeSuiPrivateKey } from '@mysten/sui/cryptography';\nimport { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport { fromBase64, toBase64 } from '@mysten/sui/utils';\nimport { decodeJwt } from '@mysten/sui/zklogin';\nimport type { ZkLoginSignatureInputs } from '@mysten/sui/zklogin';\nimport type { UseStore } from 'idb-keyval';\nimport { clear, createStore, get, set } from 'idb-keyval';\nimport type { WritableAtom } from 'nanostores';\nimport { atom, onMount, onSet } from 'nanostores';\n\nimport type { Encryption } from './encryption.js';\nimport { createDefaultEncryption } from './encryption.js';\nimport type { EnokiClientConfig } from './EnokiClient/index.js';\nimport { EnokiClient } from './EnokiClient/index.js';\nimport type { AuthProvider, EnokiNetwork } from './EnokiClient/type.js';\nimport { EnokiKeypair } from './EnokiKeypair.js';\nimport type { SyncStore } from './stores.js';\nimport { createSessionStorage } from './stores.js';\n\n/**\n * @deprecated Use `RegisterEnokiWalletsOptions` instead\n */\nexport type EnokiFlowConfig = EnokiClientConfig &\n\t(\n\t\t| {\n\t\t\t\texperimental_nativeCryptoSigner?: unknown;\n\t\t\t\t/**\n\t\t\t\t * The storage interface to persist Enoki data locally.\n\t\t\t\t * If not provided, it will use a sessionStorage-backed store.\n\t\t\t\t */\n\t\t\t\tstore?: SyncStore;\n\t\t\t\t/**\n\t\t\t\t * The encryption interface that will be used to encrypt data before storing it locally.\n\t\t\t\t * If not provided, it will use a default encryption interface.\n\t\t\t\t */\n\t\t\t\tencryption?: Encryption;\n\t\t }\n\t\t| {\n\t\t\t\tstore?: never;\n\t\t\t\tencryption?: never;\n\t\t\t\t/**\n\t\t\t\t * Enables the new native crypto signer for the EnokiFlow, which is more secure.\n\t\t\t\t */\n\t\t\t\texperimental_nativeCryptoSigner: true;\n\t\t }\n\t);\n\n// State that is not bound to a session, and is encrypted.\nexport interface ZkLoginState {\n\tprovider?: AuthProvider;\n\taddress?: string;\n\tsalt?: string;\n\tpublicKey?: string;\n}\n\n// State that session-bound, and is encrypted in storage.\nexport interface ZkLoginSession {\n\tephemeralKeyPair: string;\n\tmaxEpoch: number;\n\trandomness: string;\n\texpiresAt: number;\n\n\tjwt?: string;\n\tproof?: ZkLoginSignatureInputs;\n}\n\nconst createStorageKeys = (apiKey: string) => ({\n\tSTATE: `@enoki/flow/state/${apiKey}`,\n\tSESSION: `@enoki/flow/session/${apiKey}`,\n});\n\n/**\n * @deprecated Use `registerEnokiWallets` instead\n */\nexport class EnokiFlow {\n\t#storageKeys: { STATE: string; SESSION: string };\n\t#enokiClient: EnokiClient;\n\t#encryption: Encryption;\n\t#encryptionKey: string;\n\t#store: SyncStore;\n\t#useNativeCryptoSigner: boolean;\n\t#idbStore?: UseStore;\n\n\t$zkLoginSession: WritableAtom<{ initialized: boolean; value: ZkLoginSession | null }>;\n\t$zkLoginState: WritableAtom<ZkLoginState>;\n\n\tconstructor(config: EnokiFlowConfig) {\n\t\tthis.#enokiClient = new EnokiClient({\n\t\t\tapiKey: config.apiKey,\n\t\t\tapiUrl: config.apiUrl,\n\t\t});\n\t\tthis.#encryptionKey = config.apiKey;\n\n\t\tif (config.experimental_nativeCryptoSigner) {\n\t\t\tthis.#useNativeCryptoSigner = true;\n\t\t\tthis.#idbStore = createStore('enoki', config.apiKey);\n\t\t} else {\n\t\t\tthis.#useNativeCryptoSigner = false;\n\t\t}\n\n\t\tthis.#encryption = config.encryption ?? createDefaultEncryption();\n\t\tthis.#store = config.store ?? createSessionStorage();\n\t\tthis.#storageKeys = createStorageKeys(config.apiKey);\n\n\t\tlet storedState = null;\n\t\ttry {\n\t\t\tconst rawStoredValue = this.#store.get(this.#storageKeys.STATE);\n\t\t\tif (rawStoredValue) {\n\t\t\t\tstoredState = JSON.parse(rawStoredValue);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore errors\n\t\t}\n\n\t\tthis.$zkLoginState = atom(storedState || {});\n\t\tthis.$zkLoginSession = atom({ initialized: false, value: null });\n\n\t\t// Hydrate the session on mount:\n\t\tonMount(this.$zkLoginSession, () => {\n\t\t\tthis.getSession();\n\t\t});\n\n\t\tonSet(this.$zkLoginState, ({ newValue }) => {\n\t\t\tthis.#store.set(this.#storageKeys.STATE, JSON.stringify(newValue));\n\t\t});\n\t}\n\n\tget enokiClient() {\n\t\treturn this.#enokiClient;\n\t}\n\n\tasync createAuthorizationURL(input: {\n\t\tprovider: AuthProvider;\n\t\tclientId: string;\n\t\tredirectUrl: string;\n\t\tnetwork?: 'mainnet' | 'testnet' | 'devnet';\n\t\textraParams?: Record<string, unknown>;\n\t}) {\n\t\tconst ephemeralKeyPair = this.#useNativeCryptoSigner\n\t\t\t? await WebCryptoSigner.generate()\n\t\t\t: new Ed25519Keypair();\n\n\t\tconst { nonce, randomness, maxEpoch, estimatedExpiration } =\n\t\t\tawait this.#enokiClient.createZkLoginNonce({\n\t\t\t\tnetwork: input.network,\n\t\t\t\tephemeralPublicKey: ephemeralKeyPair.getPublicKey(),\n\t\t\t});\n\n\t\tconst params = new URLSearchParams({\n\t\t\t...input.extraParams,\n\t\t\tnonce,\n\t\t\tclient_id: input.clientId,\n\t\t\tredirect_uri: input.redirectUrl,\n\t\t\tresponse_type: 'id_token',\n\t\t\t// TODO: Eventually fetch the scopes for this client ID from the Enoki service:\n\t\t\tscope: [\n\t\t\t\t'openid',\n\t\t\t\t// Merge the requested scopes in with the required openid scopes:\n\t\t\t\t...(input.extraParams && 'scope' in input.extraParams\n\t\t\t\t\t? (input.extraParams.scope as string[])\n\t\t\t\t\t: []),\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(' '),\n\t\t});\n\n\t\tlet oauthUrl: string;\n\t\tswitch (input.provider) {\n\t\t\tcase 'google': {\n\t\t\t\toauthUrl = `https://accounts.google.com/o/oauth2/v2/auth?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'facebook': {\n\t\t\t\toauthUrl = `https://www.facebook.com/v17.0/dialog/oauth?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'twitch': {\n\t\t\t\tparams.set('force_verify', 'true');\n\t\t\t\toauthUrl = `https://id.twitch.tv/oauth2/authorize?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Invalid provider: ${input.provider}`);\n\t\t}\n\n\t\tthis.$zkLoginState.set({ provider: input.provider });\n\t\tif (this.#useNativeCryptoSigner) {\n\t\t\tawait set('ephemeralKeyPair', (ephemeralKeyPair as WebCryptoSigner).export(), this.#idbStore);\n\t\t}\n\n\t\tawait this.#setSession({\n\t\t\texpiresAt: estimatedExpiration,\n\t\t\tmaxEpoch,\n\t\t\trandomness,\n\t\t\tephemeralKeyPair: this.#useNativeCryptoSigner\n\t\t\t\t? '@@native'\n\t\t\t\t: toBase64(\n\t\t\t\t\t\tdecodeSuiPrivateKey((ephemeralKeyPair as Ed25519Keypair).getSecretKey()).secretKey,\n\t\t\t\t\t),\n\t\t});\n\n\t\treturn oauthUrl;\n\t}\n\n\t// TODO: Should our SDK manage this automatically in addition to exposing a method?\n\tasync handleAuthCallback(hash: string = window.location.hash) {\n\t\tconst params = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash);\n\n\t\t// Before we handle the auth redirect and get the state, we need to restore it:\n\t\tconst zkp = await this.getSession();\n\n\t\tif (!zkp || !zkp.ephemeralKeyPair || !zkp.maxEpoch || !zkp.randomness) {\n\t\t\tthrow new Error(\n\t\t\t\t'Start of sign-in flow could not be found. Ensure you have started the sign-in flow before calling this.',\n\t\t\t);\n\t\t}\n\n\t\tconst jwt = params.get('id_token');\n\t\tif (!jwt) {\n\t\t\tthrow new Error('Missing ID Token');\n\t\t}\n\n\t\tdecodeJwt(jwt);\n\n\t\tconst { address, salt, publicKey } = await this.#enokiClient.getZkLogin({ jwt });\n\n\t\tthis.$zkLoginState.set({\n\t\t\t...this.$zkLoginState.get(),\n\t\t\tsalt,\n\t\t\taddress,\n\t\t\tpublicKey,\n\t\t});\n\t\tawait this.#setSession({\n\t\t\t...zkp,\n\t\t\tjwt,\n\t\t});\n\n\t\treturn params.get('state');\n\t}\n\n\tasync #setSession(newValue: ZkLoginSession | null) {\n\t\tif (newValue) {\n\t\t\tconst storedValue = await this.#encryption.encrypt(\n\t\t\t\tthis.#encryptionKey,\n\t\t\t\tJSON.stringify(newValue),\n\t\t\t);\n\n\t\t\tthis.#store.set(this.#storageKeys.SESSION, storedValue);\n\t\t} else {\n\t\t\tthis.#store.delete(this.#storageKeys.SESSION);\n\t\t}\n\n\t\tthis.$zkLoginSession.set({ initialized: true, value: newValue });\n\t}\n\n\tasync getSession() {\n\t\tif (this.$zkLoginSession.get().initialized) {\n\t\t\treturn this.$zkLoginSession.get().value;\n\t\t}\n\n\t\ttry {\n\t\t\tconst storedValue = this.#store.get(this.#storageKeys.SESSION);\n\t\t\tif (!storedValue) return null;\n\n\t\t\tconst state: ZkLoginSession = JSON.parse(\n\t\t\t\tawait this.#encryption.decrypt(this.#encryptionKey, storedValue),\n\t\t\t);\n\n\t\t\t// TODO: Rather than having expiration act as a logout, we should keep the state that still is relevant,\n\t\t\t// and just clear out the expired session, but keep the other zkLogin state.\n\t\t\tif (state?.expiresAt && Date.now() > state.expiresAt) {\n\t\t\t\tawait this.logout();\n\t\t\t} else {\n\t\t\t\tthis.$zkLoginSession.set({ initialized: true, value: state });\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.$zkLoginSession.set({ initialized: true, value: null });\n\t\t}\n\n\t\treturn this.$zkLoginSession.get().value;\n\t}\n\n\tasync logout() {\n\t\tthis.$zkLoginState.set({});\n\t\tthis.#store.delete(this.#storageKeys.STATE);\n\n\t\tif (this.#useNativeCryptoSigner) {\n\t\t\tawait clear(this.#idbStore);\n\t\t}\n\t\tawait this.#setSession(null);\n\t}\n\n\t// TODO: Should this return the proof if it already exists?\n\tasync getProof({ network }: { network?: EnokiNetwork } = {}) {\n\t\tconst zkp = await this.getSession();\n\t\tconst { salt } = this.$zkLoginState.get();\n\n\t\tif (zkp?.proof) {\n\t\t\tif (zkp.expiresAt && Date.now() > zkp.expiresAt) {\n\t\t\t\tthrow new Error('Stored proof is expired.');\n\t\t\t}\n\n\t\t\treturn zkp.proof;\n\t\t}\n\n\t\tif (!salt || !zkp || !zkp.jwt) {\n\t\t\tthrow new Error('Missing required parameters for proof generation');\n\t\t}\n\n\t\tlet storedNativeSigner: ExportedWebCryptoKeypair | undefined = undefined;\n\t\tif (this.#useNativeCryptoSigner && zkp.ephemeralKeyPair === '@@native') {\n\t\t\tstoredNativeSigner = await get('ephemeralKeyPair', this.#idbStore);\n\t\t\tif (!storedNativeSigner) {\n\t\t\t\tthrow new Error('Native signer not found in store.');\n\t\t\t}\n\t\t}\n\n\t\tconst ephemeralKeyPair =\n\t\t\tzkp.ephemeralKeyPair === '@@native'\n\t\t\t\t? WebCryptoSigner.import(storedNativeSigner!)\n\t\t\t\t: Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair));\n\n\t\tconst proof = await this.#enokiClient.createZkLoginZkp({\n\t\t\tnetwork,\n\t\t\tjwt: zkp.jwt,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\trandomness: zkp.randomness,\n\t\t\tephemeralPublicKey: ephemeralKeyPair.getPublicKey(),\n\t\t});\n\n\t\tawait this.#setSession({\n\t\t\t...zkp,\n\t\t\tproof,\n\t\t});\n\n\t\treturn proof;\n\t}\n\n\tasync getKeypair({ network }: { network?: EnokiNetwork } = {}) {\n\t\t// Get the proof, so that we ensure it exists in state:\n\t\tawait this.getProof({ network });\n\n\t\tconst zkp = await this.getSession();\n\n\t\t// Check to see if we have the essentials for a keypair:\n\t\tconst { address } = this.$zkLoginState.get();\n\t\tif (!address || !zkp || !zkp.proof) {\n\t\t\tthrow new Error('Missing required data for keypair generation.');\n\t\t}\n\n\t\tif (Date.now() > zkp.expiresAt) {\n\t\t\tthrow new Error('Stored proof is expired.');\n\t\t}\n\n\t\tlet storedNativeSigner: ExportedWebCryptoKeypair | undefined = undefined;\n\t\tif (this.#useNativeCryptoSigner && zkp.ephemeralKeyPair === '@@native') {\n\t\t\tstoredNativeSigner = await get('ephemeralKeyPair', this.#idbStore);\n\t\t\tif (!storedNativeSigner) {\n\t\t\t\tthrow new Error('Native signer not found in store.');\n\t\t\t}\n\t\t}\n\n\t\tconst ephemeralKeypair =\n\t\t\tzkp.ephemeralKeyPair === '@@native'\n\t\t\t\t? WebCryptoSigner.import(storedNativeSigner!)\n\t\t\t\t: Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair));\n\n\t\treturn new EnokiKeypair({\n\t\t\taddress,\n\t\t\tephemeralKeypair,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\tproof: zkp.proof,\n\t\t});\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;AAAA;AAIA,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;AAC/B,SAAS,YAAY,gBAAgB;AACrC,SAAS,iBAAiB;AAG1B,SAAS,OAAO,aAAa,KAAK,WAAW;AAE7C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Aa,SAAS,WAAW;AAAA,EACvD,OAAO;AACN,uBAAK,QAAO,OAAO,mBAAK,cAAa,OAAO;AAAA,EAC7C;AAEA,OAAK,gBAAgB,IAAI,EAAE,aAAa,MAAM,OAAO,SAAS,CAAC;AAChE;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { ExportedWebCryptoKeypair } from '@mysten/signers/webcrypto';\nimport { WebCryptoSigner } from '@mysten/signers/webcrypto';\nimport { decodeSuiPrivateKey } from '@mysten/sui/cryptography';\nimport { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport { fromBase64, toBase64 } from '@mysten/sui/utils';\nimport { decodeJwt } from '@mysten/sui/zklogin';\nimport type { ZkLoginSignatureInputs } from '@mysten/sui/zklogin';\nimport type { UseStore } from 'idb-keyval';\nimport { clear, createStore, get, set } from 'idb-keyval';\nimport type { WritableAtom } from 'nanostores';\nimport { atom, onMount, onSet } from 'nanostores';\n\nimport type { Encryption } from './encryption.js';\nimport { createDefaultEncryption } from './encryption.js';\nimport type { EnokiClientConfig } from './EnokiClient/index.js';\nimport { EnokiClient } from './EnokiClient/index.js';\nimport type { AuthProvider, EnokiNetwork } from './EnokiClient/type.js';\nimport { EnokiKeypair } from './EnokiKeypair.js';\nimport type { SyncStore } from './stores.js';\nimport { createSessionStorage } from './stores.js';\n\n/**\n * @deprecated Use `RegisterEnokiWalletsOptions` instead\n */\nexport type EnokiFlowConfig = EnokiClientConfig &\n\t(\n\t\t| {\n\t\t\t\texperimental_nativeCryptoSigner?: unknown;\n\t\t\t\t/**\n\t\t\t\t * The storage interface to persist Enoki data locally.\n\t\t\t\t * If not provided, it will use a sessionStorage-backed store.\n\t\t\t\t */\n\t\t\t\tstore?: SyncStore;\n\t\t\t\t/**\n\t\t\t\t * The encryption interface that will be used to encrypt data before storing it locally.\n\t\t\t\t * If not provided, it will use a default encryption interface.\n\t\t\t\t */\n\t\t\t\tencryption?: Encryption;\n\t\t }\n\t\t| {\n\t\t\t\tstore?: never;\n\t\t\t\tencryption?: never;\n\t\t\t\t/**\n\t\t\t\t * Enables the new native crypto signer for the EnokiFlow, which is more secure.\n\t\t\t\t */\n\t\t\t\texperimental_nativeCryptoSigner: true;\n\t\t }\n\t);\n\n// State that is not bound to a session, and is encrypted.\nexport interface ZkLoginState {\n\tprovider?: AuthProvider;\n\taddress?: string;\n\tsalt?: string;\n\tpublicKey?: string;\n}\n\n// State that session-bound, and is encrypted in storage.\nexport interface ZkLoginSession {\n\tephemeralKeyPair: string;\n\tmaxEpoch: number;\n\trandomness: string;\n\texpiresAt: number;\n\n\tjwt?: string;\n\tproof?: ZkLoginSignatureInputs;\n}\n\nconst createStorageKeys = (apiKey: string) => ({\n\tSTATE: `@enoki/flow/state/${apiKey}`,\n\tSESSION: `@enoki/flow/session/${apiKey}`,\n});\n\n/**\n * @deprecated Use `registerEnokiWallets` instead\n */\nexport class EnokiFlow {\n\t#storageKeys: { STATE: string; SESSION: string };\n\t#enokiClient: EnokiClient;\n\t#encryption: Encryption;\n\t#encryptionKey: string;\n\t#store: SyncStore;\n\t#useNativeCryptoSigner: boolean;\n\t#idbStore?: UseStore;\n\n\t$zkLoginSession: WritableAtom<{ initialized: boolean; value: ZkLoginSession | null }>;\n\t$zkLoginState: WritableAtom<ZkLoginState>;\n\n\tconstructor(config: EnokiFlowConfig) {\n\t\tthis.#enokiClient = new EnokiClient({\n\t\t\tapiKey: config.apiKey,\n\t\t\tapiUrl: config.apiUrl,\n\t\t});\n\t\tthis.#encryptionKey = config.apiKey;\n\n\t\tif (config.experimental_nativeCryptoSigner) {\n\t\t\tthis.#useNativeCryptoSigner = true;\n\t\t\tthis.#idbStore = createStore(config.apiKey, 'enoki');\n\t\t} else {\n\t\t\tthis.#useNativeCryptoSigner = false;\n\t\t}\n\n\t\tthis.#encryption = config.encryption ?? createDefaultEncryption();\n\t\tthis.#store = config.store ?? createSessionStorage();\n\t\tthis.#storageKeys = createStorageKeys(config.apiKey);\n\n\t\tlet storedState = null;\n\t\ttry {\n\t\t\tconst rawStoredValue = this.#store.get(this.#storageKeys.STATE);\n\t\t\tif (rawStoredValue) {\n\t\t\t\tstoredState = JSON.parse(rawStoredValue);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore errors\n\t\t}\n\n\t\tthis.$zkLoginState = atom(storedState || {});\n\t\tthis.$zkLoginSession = atom({ initialized: false, value: null });\n\n\t\t// Hydrate the session on mount:\n\t\tonMount(this.$zkLoginSession, () => {\n\t\t\tthis.getSession();\n\t\t});\n\n\t\tonSet(this.$zkLoginState, ({ newValue }) => {\n\t\t\tthis.#store.set(this.#storageKeys.STATE, JSON.stringify(newValue));\n\t\t});\n\t}\n\n\tget enokiClient() {\n\t\treturn this.#enokiClient;\n\t}\n\n\tasync createAuthorizationURL(input: {\n\t\tprovider: AuthProvider;\n\t\tclientId: string;\n\t\tredirectUrl: string;\n\t\tnetwork?: 'mainnet' | 'testnet' | 'devnet';\n\t\textraParams?: Record<string, unknown>;\n\t}) {\n\t\tconst ephemeralKeyPair = this.#useNativeCryptoSigner\n\t\t\t? await WebCryptoSigner.generate()\n\t\t\t: new Ed25519Keypair();\n\n\t\tconst { nonce, randomness, maxEpoch, estimatedExpiration } =\n\t\t\tawait this.#enokiClient.createZkLoginNonce({\n\t\t\t\tnetwork: input.network,\n\t\t\t\tephemeralPublicKey: ephemeralKeyPair.getPublicKey(),\n\t\t\t});\n\n\t\tconst params = new URLSearchParams({\n\t\t\t...input.extraParams,\n\t\t\tnonce,\n\t\t\tclient_id: input.clientId,\n\t\t\tredirect_uri: input.redirectUrl,\n\t\t\tresponse_type: 'id_token',\n\t\t\t// TODO: Eventually fetch the scopes for this client ID from the Enoki service:\n\t\t\tscope: [\n\t\t\t\t'openid',\n\t\t\t\t// Merge the requested scopes in with the required openid scopes:\n\t\t\t\t...(input.extraParams && 'scope' in input.extraParams\n\t\t\t\t\t? (input.extraParams.scope as string[])\n\t\t\t\t\t: []),\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(' '),\n\t\t});\n\n\t\tlet oauthUrl: string;\n\t\tswitch (input.provider) {\n\t\t\tcase 'google': {\n\t\t\t\toauthUrl = `https://accounts.google.com/o/oauth2/v2/auth?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'facebook': {\n\t\t\t\toauthUrl = `https://www.facebook.com/v17.0/dialog/oauth?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'twitch': {\n\t\t\t\tparams.set('force_verify', 'true');\n\t\t\t\toauthUrl = `https://id.twitch.tv/oauth2/authorize?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Invalid provider: ${input.provider}`);\n\t\t}\n\n\t\tthis.$zkLoginState.set({ provider: input.provider });\n\t\tif (this.#useNativeCryptoSigner) {\n\t\t\tawait set('ephemeralKeyPair', (ephemeralKeyPair as WebCryptoSigner).export(), this.#idbStore);\n\t\t}\n\n\t\tawait this.#setSession({\n\t\t\texpiresAt: estimatedExpiration,\n\t\t\tmaxEpoch,\n\t\t\trandomness,\n\t\t\tephemeralKeyPair: this.#useNativeCryptoSigner\n\t\t\t\t? '@@native'\n\t\t\t\t: toBase64(\n\t\t\t\t\t\tdecodeSuiPrivateKey((ephemeralKeyPair as Ed25519Keypair).getSecretKey()).secretKey,\n\t\t\t\t\t),\n\t\t});\n\n\t\treturn oauthUrl;\n\t}\n\n\t// TODO: Should our SDK manage this automatically in addition to exposing a method?\n\tasync handleAuthCallback(hash: string = window.location.hash) {\n\t\tconst params = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash);\n\n\t\t// Before we handle the auth redirect and get the state, we need to restore it:\n\t\tconst zkp = await this.getSession();\n\n\t\tif (!zkp || !zkp.ephemeralKeyPair || !zkp.maxEpoch || !zkp.randomness) {\n\t\t\tthrow new Error(\n\t\t\t\t'Start of sign-in flow could not be found. Ensure you have started the sign-in flow before calling this.',\n\t\t\t);\n\t\t}\n\n\t\tconst jwt = params.get('id_token');\n\t\tif (!jwt) {\n\t\t\tthrow new Error('Missing ID Token');\n\t\t}\n\n\t\tdecodeJwt(jwt);\n\n\t\tconst { address, salt, publicKey } = await this.#enokiClient.getZkLogin({ jwt });\n\n\t\tthis.$zkLoginState.set({\n\t\t\t...this.$zkLoginState.get(),\n\t\t\tsalt,\n\t\t\taddress,\n\t\t\tpublicKey,\n\t\t});\n\t\tawait this.#setSession({\n\t\t\t...zkp,\n\t\t\tjwt,\n\t\t});\n\n\t\treturn params.get('state');\n\t}\n\n\tasync #setSession(newValue: ZkLoginSession | null) {\n\t\tif (newValue) {\n\t\t\tconst storedValue = await this.#encryption.encrypt(\n\t\t\t\tthis.#encryptionKey,\n\t\t\t\tJSON.stringify(newValue),\n\t\t\t);\n\n\t\t\tthis.#store.set(this.#storageKeys.SESSION, storedValue);\n\t\t} else {\n\t\t\tthis.#store.delete(this.#storageKeys.SESSION);\n\t\t}\n\n\t\tthis.$zkLoginSession.set({ initialized: true, value: newValue });\n\t}\n\n\tasync getSession() {\n\t\tif (this.$zkLoginSession.get().initialized) {\n\t\t\treturn this.$zkLoginSession.get().value;\n\t\t}\n\n\t\ttry {\n\t\t\tconst storedValue = this.#store.get(this.#storageKeys.SESSION);\n\t\t\tif (!storedValue) return null;\n\n\t\t\tconst state: ZkLoginSession = JSON.parse(\n\t\t\t\tawait this.#encryption.decrypt(this.#encryptionKey, storedValue),\n\t\t\t);\n\n\t\t\t// TODO: Rather than having expiration act as a logout, we should keep the state that still is relevant,\n\t\t\t// and just clear out the expired session, but keep the other zkLogin state.\n\t\t\tif (state?.expiresAt && Date.now() > state.expiresAt) {\n\t\t\t\tawait this.logout();\n\t\t\t} else {\n\t\t\t\tthis.$zkLoginSession.set({ initialized: true, value: state });\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.$zkLoginSession.set({ initialized: true, value: null });\n\t\t}\n\n\t\treturn this.$zkLoginSession.get().value;\n\t}\n\n\tasync logout() {\n\t\tthis.$zkLoginState.set({});\n\t\tthis.#store.delete(this.#storageKeys.STATE);\n\n\t\tif (this.#useNativeCryptoSigner) {\n\t\t\tawait clear(this.#idbStore);\n\t\t}\n\t\tawait this.#setSession(null);\n\t}\n\n\t// TODO: Should this return the proof if it already exists?\n\tasync getProof({ network }: { network?: EnokiNetwork } = {}) {\n\t\tconst zkp = await this.getSession();\n\t\tconst { salt } = this.$zkLoginState.get();\n\n\t\tif (zkp?.proof) {\n\t\t\tif (zkp.expiresAt && Date.now() > zkp.expiresAt) {\n\t\t\t\tthrow new Error('Stored proof is expired.');\n\t\t\t}\n\n\t\t\treturn zkp.proof;\n\t\t}\n\n\t\tif (!salt || !zkp || !zkp.jwt) {\n\t\t\tthrow new Error('Missing required parameters for proof generation');\n\t\t}\n\n\t\tlet storedNativeSigner: ExportedWebCryptoKeypair | undefined = undefined;\n\t\tif (this.#useNativeCryptoSigner && zkp.ephemeralKeyPair === '@@native') {\n\t\t\tstoredNativeSigner = await get('ephemeralKeyPair', this.#idbStore);\n\t\t\tif (!storedNativeSigner) {\n\t\t\t\tthrow new Error('Native signer not found in store.');\n\t\t\t}\n\t\t}\n\n\t\tconst ephemeralKeyPair =\n\t\t\tzkp.ephemeralKeyPair === '@@native'\n\t\t\t\t? WebCryptoSigner.import(storedNativeSigner!)\n\t\t\t\t: Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair));\n\n\t\tconst proof = await this.#enokiClient.createZkLoginZkp({\n\t\t\tnetwork,\n\t\t\tjwt: zkp.jwt,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\trandomness: zkp.randomness,\n\t\t\tephemeralPublicKey: ephemeralKeyPair.getPublicKey(),\n\t\t});\n\n\t\tawait this.#setSession({\n\t\t\t...zkp,\n\t\t\tproof,\n\t\t});\n\n\t\treturn proof;\n\t}\n\n\tasync getKeypair({ network }: { network?: EnokiNetwork } = {}) {\n\t\t// Get the proof, so that we ensure it exists in state:\n\t\tawait this.getProof({ network });\n\n\t\tconst zkp = await this.getSession();\n\n\t\t// Check to see if we have the essentials for a keypair:\n\t\tconst { address } = this.$zkLoginState.get();\n\t\tif (!address || !zkp || !zkp.proof) {\n\t\t\tthrow new Error('Missing required data for keypair generation.');\n\t\t}\n\n\t\tif (Date.now() > zkp.expiresAt) {\n\t\t\tthrow new Error('Stored proof is expired.');\n\t\t}\n\n\t\tlet storedNativeSigner: ExportedWebCryptoKeypair | undefined = undefined;\n\t\tif (this.#useNativeCryptoSigner && zkp.ephemeralKeyPair === '@@native') {\n\t\t\tstoredNativeSigner = await get('ephemeralKeyPair', this.#idbStore);\n\t\t\tif (!storedNativeSigner) {\n\t\t\t\tthrow new Error('Native signer not found in store.');\n\t\t\t}\n\t\t}\n\n\t\tconst ephemeralKeypair =\n\t\t\tzkp.ephemeralKeyPair === '@@native'\n\t\t\t\t? WebCryptoSigner.import(storedNativeSigner!)\n\t\t\t\t: Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair));\n\n\t\treturn new EnokiKeypair({\n\t\t\taddress,\n\t\t\tephemeralKeypair,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\tproof: zkp.proof,\n\t\t});\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;AAAA;AAIA,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;AAC/B,SAAS,YAAY,gBAAgB;AACrC,SAAS,iBAAiB;AAG1B,SAAS,OAAO,aAAa,KAAK,WAAW;AAE7C,SAAS,MAAM,SAAS,aAAa;AAGrC,SAAS,+BAA+B;AAExC,SAAS,mBAAmB;AAE5B,SAAS,oBAAoB;AAE7B,SAAS,4BAA4B;AAiDrC,MAAM,oBAAoB,CAAC,YAAoB;AAAA,EAC9C,OAAO,qBAAqB,MAAM;AAAA,EAClC,SAAS,uBAAuB,MAAM;AACvC;AAKO,MAAM,UAAU;AAAA,EAYtB,YAAY,QAAyB;AAZ/B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, createInMemoryStorage, type SyncStore, } from './stores.js';
5
5
  export { createDefaultEncryption, type Encryption } from './encryption.js';
6
6
  export { EnokiKeypair, EnokiPublicKey } from './EnokiKeypair.js';
7
- export { isEnokiWallet, registerEnokiWallets, type EnokiWallet } from './wallet/index.js';
7
+ export { registerEnokiWallets, type EnokiWallet } from './wallet/index.js';
8
+ export { isEnokiWallet, isGoogleWallet, isTwitchWallet, isFacebookWallet, getWalletMetadata, } from './wallet/utils.js';
8
9
  export { type RegisterEnokiWalletsOptions } from './wallet/types.js';
9
10
  export { isEnokiNetwork } from './utils.js';
package/dist/esm/index.js CHANGED
@@ -7,7 +7,14 @@ import {
7
7
  } from "./stores.js";
8
8
  import { createDefaultEncryption } from "./encryption.js";
9
9
  import { EnokiKeypair, EnokiPublicKey } from "./EnokiKeypair.js";
10
- import { isEnokiWallet, registerEnokiWallets } from "./wallet/index.js";
10
+ import { registerEnokiWallets } from "./wallet/index.js";
11
+ import {
12
+ isEnokiWallet,
13
+ isGoogleWallet,
14
+ isTwitchWallet,
15
+ isFacebookWallet,
16
+ getWalletMetadata
17
+ } from "./wallet/utils.js";
11
18
  import { isEnokiNetwork } from "./utils.js";
12
19
  export {
13
20
  EnokiClient,
@@ -19,8 +26,12 @@ export {
19
26
  createInMemoryStorage,
20
27
  createLocalStorage,
21
28
  createSessionStorage,
29
+ getWalletMetadata,
22
30
  isEnokiNetwork,
23
31
  isEnokiWallet,
32
+ isFacebookWallet,
33
+ isGoogleWallet,
34
+ isTwitchWallet,
24
35
  registerEnokiWallets
25
36
  };
26
37
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/index.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nexport { EnokiClient, type EnokiClientConfig, EnokiClientError } from './EnokiClient/index.js';\nexport type { EnokiNetwork, AuthProvider } from './EnokiClient/type.js';\nexport { EnokiFlow, type EnokiFlowConfig } from './EnokiFlow.js';\nexport {\n\tcreateLocalStorage,\n\tcreateSessionStorage,\n\tcreateInMemoryStorage,\n\ttype SyncStore,\n} from './stores.js';\nexport { createDefaultEncryption, type Encryption } from './encryption.js';\nexport { EnokiKeypair, EnokiPublicKey } from './EnokiKeypair.js';\n\nexport { isEnokiWallet, registerEnokiWallets, type EnokiWallet } from './wallet/index.js';\nexport { type RegisterEnokiWalletsOptions } from './wallet/types.js';\n\nexport { isEnokiNetwork } from './utils.js';\n"],
5
- "mappings": "AAGA,SAAS,aAAqC,wBAAwB;AAEtE,SAAS,iBAAuC;AAChD;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,OAEM;AACP,SAAS,+BAAgD;AACzD,SAAS,cAAc,sBAAsB;AAE7C,SAAS,eAAe,4BAA8C;AAGtE,SAAS,sBAAsB;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nexport { EnokiClient, type EnokiClientConfig, EnokiClientError } from './EnokiClient/index.js';\nexport type { EnokiNetwork, AuthProvider } from './EnokiClient/type.js';\nexport { EnokiFlow, type EnokiFlowConfig } from './EnokiFlow.js';\nexport {\n\tcreateLocalStorage,\n\tcreateSessionStorage,\n\tcreateInMemoryStorage,\n\ttype SyncStore,\n} from './stores.js';\nexport { createDefaultEncryption, type Encryption } from './encryption.js';\nexport { EnokiKeypair, EnokiPublicKey } from './EnokiKeypair.js';\n\nexport { registerEnokiWallets, type EnokiWallet } from './wallet/index.js';\nexport {\n\tisEnokiWallet,\n\tisGoogleWallet,\n\tisTwitchWallet,\n\tisFacebookWallet,\n\tgetWalletMetadata,\n} from './wallet/utils.js';\nexport { type RegisterEnokiWalletsOptions } from './wallet/types.js';\n\nexport { isEnokiNetwork } from './utils.js';\n"],
5
+ "mappings": "AAGA,SAAS,aAAqC,wBAAwB;AAEtE,SAAS,iBAAuC;AAChD;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,OAEM;AACP,SAAS,+BAAgD;AACzD,SAAS,cAAc,sBAAsB;AAE7C,SAAS,4BAA8C;AACvD;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AAGP,SAAS,sBAAsB;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,31 @@
1
+ import type { decodeJwt } from '@mysten/sui/zklogin';
2
+ import type { AuthProvider } from '../EnokiClient/type.js';
3
+ /** Name of the feature. */
4
+ export declare const EnokiGetMetadata = "enoki:getMetadata";
5
+ /** The latest API version of the getEnokiMetadata API. */
6
+ export type EnokiGetMetadataVersion = '1.0.0';
7
+ /**
8
+ * A Wallet Standard feature for retreiving Enoki-specific metadata about the wallet.
9
+ */
10
+ export type EnokiGetMetadataFeature = {
11
+ /** Namespace for the feature. */
12
+ [EnokiGetMetadata]: {
13
+ /** Version of the feature API. */
14
+ version: '1.0.0';
15
+ getMetadata: EnokiGetMetadataMethod;
16
+ };
17
+ };
18
+ export type EnokiGetMetadataMethod = (input?: EnokiGetMetadataInput) => EnokiGetMetadataOutput;
19
+ /** Input for retrieving metadata about the wallet. */
20
+ export interface EnokiGetMetadataInput {
21
+ }
22
+ /** Output of retrieving metadata about the wallet. */
23
+ export interface EnokiGetMetadataOutput {
24
+ /** The social provider for the wallet. */
25
+ provider: AuthProvider;
26
+ /** Metadata pertaining to the active session. */
27
+ activeSession?: {
28
+ /** The decoded JWT for the session. */
29
+ decodedJwt: ReturnType<typeof decodeJwt>;
30
+ };
31
+ }
@@ -0,0 +1,5 @@
1
+ const EnokiGetMetadata = "enoki:getMetadata";
2
+ export {
3
+ EnokiGetMetadata
4
+ };
5
+ //# sourceMappingURL=feature.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/wallet/feature.ts"],
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { decodeJwt } from '@mysten/sui/zklogin';\nimport type { AuthProvider } from '../EnokiClient/type.js';\n\n/** Name of the feature. */\nexport const EnokiGetMetadata = 'enoki:getMetadata';\n\n/** The latest API version of the getEnokiMetadata API. */\nexport type EnokiGetMetadataVersion = '1.0.0';\n\n/**\n * A Wallet Standard feature for retreiving Enoki-specific metadata about the wallet.\n */\nexport type EnokiGetMetadataFeature = {\n\t/** Namespace for the feature. */\n\t[EnokiGetMetadata]: {\n\t\t/** Version of the feature API. */\n\t\tversion: '1.0.0';\n\t\tgetMetadata: EnokiGetMetadataMethod;\n\t};\n};\n\nexport type EnokiGetMetadataMethod = (input?: EnokiGetMetadataInput) => EnokiGetMetadataOutput;\n\n/** Input for retrieving metadata about the wallet. */\nexport interface EnokiGetMetadataInput {}\n\n/** Output of retrieving metadata about the wallet. */\nexport interface EnokiGetMetadataOutput {\n\t/** The social provider for the wallet. */\n\tprovider: AuthProvider;\n\n\t/** Metadata pertaining to the active session. */\n\tactiveSession?: {\n\t\t/** The decoded JWT for the session. */\n\t\tdecodedJwt: ReturnType<typeof decodeJwt>;\n\t};\n}\n"],
5
+ "mappings": "AAOO,MAAM,mBAAmB;",
6
+ "names": []
7
+ }
@@ -4,6 +4,7 @@ import { ReadonlyWalletAccount } from '@mysten/wallet-standard';
4
4
  import type { AuthProvider } from '../EnokiClient/type.js';
5
5
  import { INTERNAL_ONLY_EnokiFlow } from './state.js';
6
6
  import type { RegisterEnokiWalletsOptions } from './types.js';
7
+ import type { EnokiGetMetadataFeature } from './feature.js';
7
8
  export declare class EnokiWallet implements Wallet {
8
9
  #private;
9
10
  get id(): string;
@@ -13,7 +14,7 @@ export declare class EnokiWallet implements Wallet {
13
14
  get version(): "1.0.0";
14
15
  get chains(): readonly ["sui:mainnet" | "sui:testnet" | "sui:devnet"];
15
16
  get accounts(): ReadonlyWalletAccount[];
16
- get features(): StandardConnectFeature & StandardDisconnectFeature & StandardEventsFeature & SuiSignTransactionFeature & SuiSignAndExecuteTransactionFeature & SuiSignPersonalMessageFeature;
17
+ get features(): StandardConnectFeature & StandardDisconnectFeature & StandardEventsFeature & SuiSignTransactionFeature & SuiSignAndExecuteTransactionFeature & SuiSignPersonalMessageFeature & EnokiGetMetadataFeature;
17
18
  constructor({ name, icon, flow, provider, clientId, redirectUrl, extraParams, client, windowFeatures, }: {
18
19
  icon: Wallet['icon'];
19
20
  name: string;
@@ -30,5 +31,4 @@ export declare function registerEnokiWallets({ providers, client, network, windo
30
31
  wallets: Partial<Record<AuthProvider, EnokiWallet>>;
31
32
  unregister: () => void;
32
33
  };
33
- export declare function isEnokiWallet(wallet: Wallet): wallet is EnokiWallet;
34
34
  export declare function defaultWindowFeatures(): string;
@@ -6,13 +6,24 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
6
6
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
7
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
8
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
- var _events, _accounts, _name, _id, _icon, _flow, _provider, _clientId, _redirectUrl, _extraParams, _client, _windowFeatures, _signTransaction, _signAndExecuteTransaction, _signPersonalMessage, _on, _EnokiWallet_instances, setAccount_fn, _connect, _disconnect, validateChain_fn;
9
+ var _events, _accounts, _name, _id, _icon, _flow, _provider, _clientId, _redirectUrl, _extraParams, _client, _windowFeatures, _signTransaction, _signAndExecuteTransaction, _signPersonalMessage, _on, _EnokiWallet_instances, setAccount_fn, _connect, _getMetadata, _disconnect, validateChain_fn;
10
10
  import { Transaction } from "@mysten/sui/transactions";
11
11
  import { fromBase64, toBase64 } from "@mysten/sui/utils";
12
- import { getWallets, ReadonlyWalletAccount } from "@mysten/wallet-standard";
12
+ import {
13
+ getWallets,
14
+ ReadonlyWalletAccount,
15
+ StandardConnect,
16
+ StandardDisconnect,
17
+ StandardEvents,
18
+ SuiSignAndExecuteTransaction,
19
+ SuiSignPersonalMessage,
20
+ SuiSignTransaction
21
+ } from "@mysten/wallet-standard";
13
22
  import mitt from "mitt";
14
23
  import { ENOKI_PROVIDER_WALLETS_INFO } from "./providers.js";
15
24
  import { INTERNAL_ONLY_EnokiFlow } from "./state.js";
25
+ import { EnokiGetMetadata } from "./feature.js";
26
+ import { decodeJwt } from "@mysten/sui/zklogin";
16
27
  class EnokiWallet {
17
28
  constructor({
18
29
  name,
@@ -131,6 +142,14 @@ class EnokiWallet {
131
142
  __privateMethod(this, _EnokiWallet_instances, setAccount_fn).call(this);
132
143
  return { accounts: this.accounts };
133
144
  });
145
+ __privateAdd(this, _getMetadata, () => {
146
+ const session = __privateGet(this, _flow).$zkLoginSession.get();
147
+ const decodedJwt = session.value?.jwt ? decodeJwt(session.value.jwt) : void 0;
148
+ return {
149
+ provider: __privateGet(this, _provider),
150
+ activeSession: decodedJwt ? { decodedJwt } : void 0
151
+ };
152
+ });
134
153
  __privateAdd(this, _disconnect, async () => {
135
154
  await __privateGet(this, _flow).logout();
136
155
  __privateMethod(this, _EnokiWallet_instances, setAccount_fn).call(this);
@@ -172,29 +191,33 @@ class EnokiWallet {
172
191
  }
173
192
  get features() {
174
193
  return {
175
- "standard:connect": {
194
+ [StandardConnect]: {
176
195
  version: "1.0.0",
177
196
  connect: __privateGet(this, _connect)
178
197
  },
179
- "standard:disconnect": {
198
+ [StandardDisconnect]: {
180
199
  version: "1.0.0",
181
200
  disconnect: __privateGet(this, _disconnect)
182
201
  },
183
- "standard:events": {
202
+ [StandardEvents]: {
184
203
  version: "1.0.0",
185
204
  on: __privateGet(this, _on)
186
205
  },
187
- "sui:signTransaction": {
206
+ [SuiSignTransaction]: {
188
207
  version: "2.0.0",
189
208
  signTransaction: __privateGet(this, _signTransaction)
190
209
  },
191
- "sui:signAndExecuteTransaction": {
210
+ [SuiSignAndExecuteTransaction]: {
192
211
  version: "2.0.0",
193
212
  signAndExecuteTransaction: __privateGet(this, _signAndExecuteTransaction)
194
213
  },
195
- "sui:signPersonalMessage": {
214
+ [SuiSignPersonalMessage]: {
196
215
  version: "1.1.0",
197
216
  signPersonalMessage: __privateGet(this, _signPersonalMessage)
217
+ },
218
+ [EnokiGetMetadata]: {
219
+ version: "1.0.0",
220
+ getMetadata: __privateGet(this, _getMetadata)
198
221
  }
199
222
  };
200
223
  }
@@ -223,7 +246,8 @@ setAccount_fn = function() {
223
246
  new ReadonlyWalletAccount({
224
247
  address: state.address,
225
248
  chains: this.chains,
226
- features: Object.keys(this.features),
249
+ icon: this.icon,
250
+ features: [SuiSignPersonalMessage, SuiSignTransaction, SuiSignAndExecuteTransaction],
227
251
  publicKey: fromBase64(state.publicKey)
228
252
  })
229
253
  ]);
@@ -233,6 +257,7 @@ setAccount_fn = function() {
233
257
  __privateGet(this, _events).emit("change", { accounts: this.accounts });
234
258
  };
235
259
  _connect = new WeakMap();
260
+ _getMetadata = new WeakMap();
236
261
  _disconnect = new WeakMap();
237
262
  validateChain_fn = function(chain) {
238
263
  if (!chain || !this.chains.includes(chain)) {
@@ -281,9 +306,6 @@ function registerEnokiWallets({
281
306
  }
282
307
  };
283
308
  }
284
- function isEnokiWallet(wallet) {
285
- return !!wallet.id?.startsWith("enoki:");
286
- }
287
309
  function defaultWindowFeatures() {
288
310
  const width = 500;
289
311
  const height = 800;
@@ -294,7 +316,6 @@ function defaultWindowFeatures() {
294
316
  export {
295
317
  EnokiWallet,
296
318
  defaultWindowFeatures,
297
- isEnokiWallet,
298
319
  registerEnokiWallets
299
320
  };
300
321
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/wallet/index.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { fromBase64, toBase64 } from '@mysten/sui/utils';\nimport type {\n\tIdentifierArray,\n\tIdentifierString,\n\tStandardConnectFeature,\n\tStandardConnectMethod,\n\tStandardDisconnectFeature,\n\tStandardDisconnectMethod,\n\tStandardEventsFeature,\n\tStandardEventsOnMethod,\n\tSuiSignAndExecuteTransactionFeature,\n\tSuiSignAndExecuteTransactionMethod,\n\tSuiSignPersonalMessageFeature,\n\tSuiSignPersonalMessageMethod,\n\tSuiSignTransactionFeature,\n\tSuiSignTransactionMethod,\n\tWallet,\n} from '@mysten/wallet-standard';\nimport { getWallets, ReadonlyWalletAccount } from '@mysten/wallet-standard';\nimport type { Emitter } from 'mitt';\nimport mitt from 'mitt';\n\nimport type { AuthProvider } from '../EnokiClient/type.js';\nimport { ENOKI_PROVIDER_WALLETS_INFO } from './providers.js';\nimport { INTERNAL_ONLY_EnokiFlow } from './state.js';\nimport type { RegisterEnokiWalletsOptions, WalletEventsMap } from './types.js';\n\nexport class EnokiWallet implements Wallet {\n\t#events: Emitter<WalletEventsMap>;\n\t#accounts: ReadonlyWalletAccount[];\n\t#name: string;\n\t#id: string;\n\t#icon: Wallet['icon'];\n\t#flow: INTERNAL_ONLY_EnokiFlow;\n\t#provider: AuthProvider;\n\t#clientId: string;\n\t#redirectUrl: string | undefined;\n\t#extraParams: Record<string, string> | undefined;\n\t#client;\n\t#windowFeatures?: string | (() => string);\n\n\tget id() {\n\t\treturn this.#id;\n\t}\n\n\tget name() {\n\t\treturn this.#name;\n\t}\n\n\tget provider() {\n\t\treturn this.#provider;\n\t}\n\n\tget icon() {\n\t\treturn this.#icon;\n\t}\n\n\tget version() {\n\t\treturn '1.0.0' as const;\n\t}\n\n\tget chains() {\n\t\treturn [`sui:${this.#flow.network}`] as const;\n\t}\n\n\tget accounts() {\n\t\treturn this.#accounts;\n\t}\n\n\tget features(): StandardConnectFeature &\n\t\tStandardDisconnectFeature &\n\t\tStandardEventsFeature &\n\t\tSuiSignTransactionFeature &\n\t\tSuiSignAndExecuteTransactionFeature &\n\t\tSuiSignPersonalMessageFeature {\n\t\treturn {\n\t\t\t'standard:connect': {\n\t\t\t\tversion: '1.0.0',\n\t\t\t\tconnect: this.#connect,\n\t\t\t},\n\t\t\t'standard:disconnect': {\n\t\t\t\tversion: '1.0.0',\n\t\t\t\tdisconnect: this.#disconnect,\n\t\t\t},\n\t\t\t'standard:events': {\n\t\t\t\tversion: '1.0.0',\n\t\t\t\ton: this.#on,\n\t\t\t},\n\t\t\t'sui:signTransaction': {\n\t\t\t\tversion: '2.0.0',\n\t\t\t\tsignTransaction: this.#signTransaction,\n\t\t\t},\n\t\t\t'sui:signAndExecuteTransaction': {\n\t\t\t\tversion: '2.0.0',\n\t\t\t\tsignAndExecuteTransaction: this.#signAndExecuteTransaction,\n\t\t\t},\n\t\t\t'sui:signPersonalMessage': {\n\t\t\t\tversion: '1.1.0',\n\t\t\t\tsignPersonalMessage: this.#signPersonalMessage,\n\t\t\t},\n\t\t};\n\t}\n\n\tconstructor({\n\t\tname,\n\t\ticon,\n\t\tflow,\n\t\tprovider,\n\t\tclientId,\n\t\tredirectUrl,\n\t\textraParams,\n\t\tclient,\n\t\twindowFeatures,\n\t}: {\n\t\ticon: Wallet['icon'];\n\t\tname: string;\n\t\tflow: INTERNAL_ONLY_EnokiFlow;\n\t\tprovider: AuthProvider;\n\t\tclientId: string;\n\t\tredirectUrl?: string;\n\t\textraParams?: Record<string, string>;\n\t\tclient: SuiClient;\n\t\twindowFeatures?: string | (() => string);\n\t}) {\n\t\tthis.#accounts = [];\n\t\tthis.#events = mitt();\n\n\t\tthis.#client = client;\n\t\tthis.#name = name;\n\t\tthis.#id = `enoki:${provider}:${flow.network}:${clientId}`;\n\t\tthis.#icon = icon;\n\t\tthis.#flow = flow;\n\t\tthis.#provider = provider;\n\t\tthis.#clientId = clientId;\n\t\tthis.#redirectUrl = redirectUrl;\n\t\tthis.#extraParams = extraParams;\n\t\tthis.#windowFeatures = windowFeatures;\n\n\t\tthis.#setAccount();\n\t}\n\n\t#signTransaction: SuiSignTransactionMethod = async ({ transaction, chain, account }) => {\n\t\tthis.#validateChain(chain);\n\n\t\tconst parsedTransaction = Transaction.from(await transaction.toJSON());\n\t\tconst keypair = await this.#flow.getKeypair();\n\t\tconst suiAddress = keypair.toSuiAddress();\n\n\t\tif (suiAddress !== account.address) {\n\t\t\tthrow new Error(\n\t\t\t\t`The specified account ${account.address} does not match the currently connected Enoki address ${suiAddress}.`,\n\t\t\t);\n\t\t}\n\n\t\tparsedTransaction.setSenderIfNotSet(suiAddress);\n\t\treturn keypair.signTransaction(await parsedTransaction.build({ client: this.#client }));\n\t};\n\n\t#signAndExecuteTransaction: SuiSignAndExecuteTransactionMethod = async ({\n\t\ttransaction,\n\t\tchain,\n\t\taccount,\n\t}) => {\n\t\tconst { signature, bytes } = await this.#signTransaction({ transaction, account, chain });\n\t\tconst { digest, rawEffects } = await this.#client.executeTransactionBlock({\n\t\t\ttransactionBlock: bytes,\n\t\t\tsignature,\n\t\t\toptions: {\n\t\t\t\tshowRawEffects: true,\n\t\t\t},\n\t\t});\n\n\t\treturn {\n\t\t\tdigest,\n\t\t\tsignature,\n\t\t\tbytes,\n\t\t\teffects: toBase64(Uint8Array.from(rawEffects!)),\n\t\t};\n\t};\n\n\t#signPersonalMessage: SuiSignPersonalMessageMethod = async ({ message, account, chain }) => {\n\t\tthis.#validateChain(chain);\n\n\t\tconst keypair = await this.#flow.getKeypair();\n\t\tconst suiAddress = keypair.toSuiAddress();\n\n\t\tif (suiAddress !== account.address) {\n\t\t\tthrow new Error(\n\t\t\t\t`The specified account ${account.address} does not match the currently connected Enoki address ${suiAddress}.`,\n\t\t\t);\n\t\t}\n\n\t\treturn keypair.signPersonalMessage(message);\n\t};\n\n\t#on: StandardEventsOnMethod = (event, listener) => {\n\t\tthis.#events.on(event, listener);\n\t\treturn () => this.#events.off(event, listener);\n\t};\n\n\t#setAccount() {\n\t\tconst state = this.#flow.$zkLoginState.get();\n\t\tif (state.address && state.publicKey) {\n\t\t\tthis.#accounts = [\n\t\t\t\tnew ReadonlyWalletAccount({\n\t\t\t\t\taddress: state.address,\n\t\t\t\t\tchains: this.chains,\n\t\t\t\t\tfeatures: Object.keys(this.features) as IdentifierArray,\n\t\t\t\t\tpublicKey: fromBase64(state.publicKey),\n\t\t\t\t}),\n\t\t\t];\n\t\t} else {\n\t\t\tthis.#accounts = [];\n\t\t}\n\n\t\tthis.#events.emit('change', { accounts: this.accounts });\n\t}\n\n\t#connect: StandardConnectMethod = async (input) => {\n\t\tthis.#setAccount();\n\n\t\tif (this.accounts.length || input?.silent) {\n\t\t\treturn { accounts: this.accounts };\n\t\t}\n\n\t\tconst popup = window.open(\n\t\t\tundefined,\n\t\t\t'_blank',\n\t\t\ttypeof this.#windowFeatures === 'function' ? this.#windowFeatures() : this.#windowFeatures,\n\t\t);\n\t\tif (!popup) {\n\t\t\tthrow new Error('Failed to open popup');\n\t\t}\n\n\t\tconst url = await this.#flow.createAuthorizationURL({\n\t\t\tprovider: this.#provider,\n\t\t\tclientId: this.#clientId,\n\t\t\tredirectUrl: this.#redirectUrl ?? window.location.href.split('#')[0],\n\t\t\textraParams: this.#extraParams,\n\t\t});\n\n\t\tpopup.location = url;\n\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tconst interval = setInterval(() => {\n\t\t\t\ttry {\n\t\t\t\t\tif (popup.closed) {\n\t\t\t\t\t\tclearInterval(interval);\n\t\t\t\t\t\treject(new Error('Popup closed'));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!popup.location.hash) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tclearInterval(interval);\n\n\t\t\t\tthis.#flow.handleAuthCallback(popup.location.hash).then(() => resolve(), reject);\n\n\t\t\t\ttry {\n\t\t\t\t\tpopup.close();\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t}, 16);\n\t\t});\n\n\t\tthis.#setAccount();\n\n\t\treturn { accounts: this.accounts };\n\t};\n\n\t#disconnect: StandardDisconnectMethod = async () => {\n\t\tawait this.#flow.logout();\n\n\t\tthis.#setAccount();\n\t};\n\n\t#validateChain(chain?: IdentifierString): asserts chain is (typeof this.chains)[number] {\n\t\tif (!chain || !this.chains.includes(chain as (typeof this.chains)[number])) {\n\t\t\tthrow new Error(\n\t\t\t\t`A valid Sui chain identifier was not provided in the request. Please report this issue to the dApp developer. Examples of valid Sui chain identifiers are 'sui:testnet' and 'sui:mainnet'. Consider using the '@mysten/dapp-kit' package, which provides this value automatically.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nexport function registerEnokiWallets({\n\tproviders,\n\tclient,\n\tnetwork = 'mainnet',\n\twindowFeatures = defaultWindowFeatures,\n\t...config\n}: RegisterEnokiWalletsOptions) {\n\tconst walletsApi = getWallets();\n\tconst flow = new INTERNAL_ONLY_EnokiFlow({ ...config, network });\n\n\tconst unregisterCallbacks: (() => void)[] = [];\n\tconst wallets: Partial<Record<AuthProvider, EnokiWallet>> = {};\n\n\tfor (const { name, icon, provider } of ENOKI_PROVIDER_WALLETS_INFO) {\n\t\tconst providerOptions = providers[provider];\n\t\tif (providerOptions) {\n\t\t\tconst { clientId, redirectUrl, extraParams } = providerOptions;\n\t\t\tconst wallet = new EnokiWallet({\n\t\t\t\tname,\n\t\t\t\ticon,\n\t\t\t\tflow,\n\t\t\t\tprovider,\n\t\t\t\tclientId,\n\t\t\t\tclient,\n\t\t\t\tredirectUrl,\n\t\t\t\textraParams,\n\t\t\t\twindowFeatures,\n\t\t\t});\n\n\t\t\tconst unregister = walletsApi.register(wallet);\n\t\t\tunregisterCallbacks.push(unregister);\n\n\t\t\twallets[provider] = wallet;\n\t\t}\n\t}\n\n\treturn {\n\t\twallets,\n\t\tunregister: () => {\n\t\t\tfor (const unregister of unregisterCallbacks) {\n\t\t\t\tunregister();\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport function isEnokiWallet(wallet: Wallet): wallet is EnokiWallet {\n\treturn !!wallet.id?.startsWith('enoki:');\n}\n\nexport function defaultWindowFeatures() {\n\tconst width = 500;\n\tconst height = 800;\n\tconst left = (screen.width - width) / 2;\n\tconst top = (screen.height - height) / 4;\n\n\treturn `popup=1;toolbar=0;status=0;resizable=1,width=${width},height=${height},top=${top},left=${left}`;\n}\n"],
5
- "mappings": ";;;;;;;;AAAA;AAIA,SAAS,mBAAmB;AAC5B,SAAS,YAAY,gBAAgB;AAkBrC,SAAS,YAAY,6BAA6B;AAElD,OAAO,UAAU;AAGjB,SAAS,mCAAmC;AAC5C,SAAS,+BAA+B;AAGjC,MAAM,YAA8B;AAAA,EA4E1C,YAAY;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD,GAUG;AAhGG;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAsGA,yCAA6C,OAAO,EAAE,aAAa,OAAO,QAAQ,MAAM;AACvF,4BAAK,0CAAL,WAAoB;AAEpB,YAAM,oBAAoB,YAAY,KAAK,MAAM,YAAY,OAAO,CAAC;AACrE,YAAM,UAAU,MAAM,mBAAK,OAAM,WAAW;AAC5C,YAAM,aAAa,QAAQ,aAAa;AAExC,UAAI,eAAe,QAAQ,SAAS;AACnC,cAAM,IAAI;AAAA,UACT,yBAAyB,QAAQ,OAAO,yDAAyD,UAAU;AAAA,QAC5G;AAAA,MACD;AAEA,wBAAkB,kBAAkB,UAAU;AAC9C,aAAO,QAAQ,gBAAgB,MAAM,kBAAkB,MAAM,EAAE,QAAQ,mBAAK,SAAQ,CAAC,CAAC;AAAA,IACvF;AAEA,mDAAiE,OAAO;AAAA,MACvE;AAAA,MACA;AAAA,MACA;AAAA,IACD,MAAM;AACL,YAAM,EAAE,WAAW,MAAM,IAAI,MAAM,mBAAK,kBAAL,WAAsB,EAAE,aAAa,SAAS,MAAM;AACvF,YAAM,EAAE,Q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tG;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { fromBase64, toBase64 } from '@mysten/sui/utils';\nimport type {\n\tIdentifierString,\n\tStandardConnectFeature,\n\tStandardConnectMethod,\n\tStandardDisconnectFeature,\n\tStandardDisconnectMethod,\n\tStandardEventsFeature,\n\tStandardEventsOnMethod,\n\tSuiSignAndExecuteTransactionFeature,\n\tSuiSignAndExecuteTransactionMethod,\n\tSuiSignPersonalMessageFeature,\n\tSuiSignPersonalMessageMethod,\n\tSuiSignTransactionFeature,\n\tSuiSignTransactionMethod,\n\tWallet,\n} from '@mysten/wallet-standard';\nimport {\n\tgetWallets,\n\tReadonlyWalletAccount,\n\tStandardConnect,\n\tStandardDisconnect,\n\tStandardEvents,\n\tSuiSignAndExecuteTransaction,\n\tSuiSignPersonalMessage,\n\tSuiSignTransaction,\n} from '@mysten/wallet-standard';\nimport type { Emitter } from 'mitt';\nimport mitt from 'mitt';\n\nimport type { AuthProvider } from '../EnokiClient/type.js';\nimport { ENOKI_PROVIDER_WALLETS_INFO } from './providers.js';\nimport { INTERNAL_ONLY_EnokiFlow } from './state.js';\nimport type { RegisterEnokiWalletsOptions, WalletEventsMap } from './types.js';\nimport type { EnokiGetMetadataFeature, EnokiGetMetadataMethod } from './feature.js';\nimport { EnokiGetMetadata } from './feature.js';\nimport { decodeJwt } from '@mysten/sui/zklogin';\n\nexport class EnokiWallet implements Wallet {\n\t#events: Emitter<WalletEventsMap>;\n\t#accounts: ReadonlyWalletAccount[];\n\t#name: string;\n\t#id: string;\n\t#icon: Wallet['icon'];\n\t#flow: INTERNAL_ONLY_EnokiFlow;\n\t#provider: AuthProvider;\n\t#clientId: string;\n\t#redirectUrl: string | undefined;\n\t#extraParams: Record<string, string> | undefined;\n\t#client;\n\t#windowFeatures?: string | (() => string);\n\n\tget id() {\n\t\treturn this.#id;\n\t}\n\n\tget name() {\n\t\treturn this.#name;\n\t}\n\n\tget provider() {\n\t\treturn this.#provider;\n\t}\n\n\tget icon() {\n\t\treturn this.#icon;\n\t}\n\n\tget version() {\n\t\treturn '1.0.0' as const;\n\t}\n\n\tget chains() {\n\t\treturn [`sui:${this.#flow.network}`] as const;\n\t}\n\n\tget accounts() {\n\t\treturn this.#accounts;\n\t}\n\n\tget features(): StandardConnectFeature &\n\t\tStandardDisconnectFeature &\n\t\tStandardEventsFeature &\n\t\tSuiSignTransactionFeature &\n\t\tSuiSignAndExecuteTransactionFeature &\n\t\tSuiSignPersonalMessageFeature &\n\t\tEnokiGetMetadataFeature {\n\t\treturn {\n\t\t\t[StandardConnect]: {\n\t\t\t\tversion: '1.0.0',\n\t\t\t\tconnect: this.#connect,\n\t\t\t},\n\t\t\t[StandardDisconnect]: {\n\t\t\t\tversion: '1.0.0',\n\t\t\t\tdisconnect: this.#disconnect,\n\t\t\t},\n\t\t\t[StandardEvents]: {\n\t\t\t\tversion: '1.0.0',\n\t\t\t\ton: this.#on,\n\t\t\t},\n\t\t\t[SuiSignTransaction]: {\n\t\t\t\tversion: '2.0.0',\n\t\t\t\tsignTransaction: this.#signTransaction,\n\t\t\t},\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[EnokiGetMetadata]: {\n\t\t\t\tversion: '1.0.0',\n\t\t\t\tgetMetadata: this.#getMetadata,\n\t\t\t},\n\t\t};\n\t}\n\n\tconstructor({\n\t\tname,\n\t\ticon,\n\t\tflow,\n\t\tprovider,\n\t\tclientId,\n\t\tredirectUrl,\n\t\textraParams,\n\t\tclient,\n\t\twindowFeatures,\n\t}: {\n\t\ticon: Wallet['icon'];\n\t\tname: string;\n\t\tflow: INTERNAL_ONLY_EnokiFlow;\n\t\tprovider: AuthProvider;\n\t\tclientId: string;\n\t\tredirectUrl?: string;\n\t\textraParams?: Record<string, string>;\n\t\tclient: SuiClient;\n\t\twindowFeatures?: string | (() => string);\n\t}) {\n\t\tthis.#accounts = [];\n\t\tthis.#events = mitt();\n\n\t\tthis.#client = client;\n\t\tthis.#name = name;\n\t\tthis.#id = `enoki:${provider}:${flow.network}:${clientId}`;\n\t\tthis.#icon = icon;\n\t\tthis.#flow = flow;\n\t\tthis.#provider = provider;\n\t\tthis.#clientId = clientId;\n\t\tthis.#redirectUrl = redirectUrl;\n\t\tthis.#extraParams = extraParams;\n\t\tthis.#windowFeatures = windowFeatures;\n\n\t\tthis.#setAccount();\n\t}\n\n\t#signTransaction: SuiSignTransactionMethod = async ({ transaction, chain, account }) => {\n\t\tthis.#validateChain(chain);\n\n\t\tconst parsedTransaction = Transaction.from(await transaction.toJSON());\n\t\tconst keypair = await this.#flow.getKeypair();\n\t\tconst suiAddress = keypair.toSuiAddress();\n\n\t\tif (suiAddress !== account.address) {\n\t\t\tthrow new Error(\n\t\t\t\t`The specified account ${account.address} does not match the currently connected Enoki address ${suiAddress}.`,\n\t\t\t);\n\t\t}\n\n\t\tparsedTransaction.setSenderIfNotSet(suiAddress);\n\t\treturn keypair.signTransaction(await parsedTransaction.build({ client: this.#client }));\n\t};\n\n\t#signAndExecuteTransaction: SuiSignAndExecuteTransactionMethod = async ({\n\t\ttransaction,\n\t\tchain,\n\t\taccount,\n\t}) => {\n\t\tconst { signature, bytes } = await this.#signTransaction({ transaction, account, chain });\n\t\tconst { digest, rawEffects } = await this.#client.executeTransactionBlock({\n\t\t\ttransactionBlock: bytes,\n\t\t\tsignature,\n\t\t\toptions: {\n\t\t\t\tshowRawEffects: true,\n\t\t\t},\n\t\t});\n\n\t\treturn {\n\t\t\tdigest,\n\t\t\tsignature,\n\t\t\tbytes,\n\t\t\teffects: toBase64(Uint8Array.from(rawEffects!)),\n\t\t};\n\t};\n\n\t#signPersonalMessage: SuiSignPersonalMessageMethod = async ({ message, account, chain }) => {\n\t\tthis.#validateChain(chain);\n\n\t\tconst keypair = await this.#flow.getKeypair();\n\t\tconst suiAddress = keypair.toSuiAddress();\n\n\t\tif (suiAddress !== account.address) {\n\t\t\tthrow new Error(\n\t\t\t\t`The specified account ${account.address} does not match the currently connected Enoki address ${suiAddress}.`,\n\t\t\t);\n\t\t}\n\n\t\treturn keypair.signPersonalMessage(message);\n\t};\n\n\t#on: StandardEventsOnMethod = (event, listener) => {\n\t\tthis.#events.on(event, listener);\n\t\treturn () => this.#events.off(event, listener);\n\t};\n\n\t#setAccount() {\n\t\tconst state = this.#flow.$zkLoginState.get();\n\t\tif (state.address && state.publicKey) {\n\t\t\tthis.#accounts = [\n\t\t\t\tnew ReadonlyWalletAccount({\n\t\t\t\t\taddress: state.address,\n\t\t\t\t\tchains: this.chains,\n\t\t\t\t\ticon: this.icon,\n\t\t\t\t\tfeatures: [SuiSignPersonalMessage, SuiSignTransaction, SuiSignAndExecuteTransaction],\n\t\t\t\t\tpublicKey: fromBase64(state.publicKey),\n\t\t\t\t}),\n\t\t\t];\n\t\t} else {\n\t\t\tthis.#accounts = [];\n\t\t}\n\n\t\tthis.#events.emit('change', { accounts: this.accounts });\n\t}\n\n\t#connect: StandardConnectMethod = async (input) => {\n\t\tthis.#setAccount();\n\n\t\tif (this.accounts.length || input?.silent) {\n\t\t\treturn { accounts: this.accounts };\n\t\t}\n\n\t\tconst popup = window.open(\n\t\t\tundefined,\n\t\t\t'_blank',\n\t\t\ttypeof this.#windowFeatures === 'function' ? this.#windowFeatures() : this.#windowFeatures,\n\t\t);\n\t\tif (!popup) {\n\t\t\tthrow new Error('Failed to open popup');\n\t\t}\n\n\t\tconst url = await this.#flow.createAuthorizationURL({\n\t\t\tprovider: this.#provider,\n\t\t\tclientId: this.#clientId,\n\t\t\tredirectUrl: this.#redirectUrl ?? window.location.href.split('#')[0],\n\t\t\textraParams: this.#extraParams,\n\t\t});\n\n\t\tpopup.location = url;\n\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tconst interval = setInterval(() => {\n\t\t\t\ttry {\n\t\t\t\t\tif (popup.closed) {\n\t\t\t\t\t\tclearInterval(interval);\n\t\t\t\t\t\treject(new Error('Popup closed'));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!popup.location.hash) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tclearInterval(interval);\n\n\t\t\t\tthis.#flow.handleAuthCallback(popup.location.hash).then(() => resolve(), reject);\n\n\t\t\t\ttry {\n\t\t\t\t\tpopup.close();\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t}, 16);\n\t\t});\n\n\t\tthis.#setAccount();\n\n\t\treturn { accounts: this.accounts };\n\t};\n\n\t#getMetadata: EnokiGetMetadataMethod = () => {\n\t\tconst session = this.#flow.$zkLoginSession.get();\n\t\tconst decodedJwt = session.value?.jwt ? decodeJwt(session.value.jwt) : undefined;\n\n\t\treturn {\n\t\t\tprovider: this.#provider,\n\t\t\tactiveSession: decodedJwt ? { decodedJwt } : undefined,\n\t\t};\n\t};\n\n\t#disconnect: StandardDisconnectMethod = async () => {\n\t\tawait this.#flow.logout();\n\n\t\tthis.#setAccount();\n\t};\n\n\t#validateChain(chain?: IdentifierString): asserts chain is (typeof this.chains)[number] {\n\t\tif (!chain || !this.chains.includes(chain as (typeof this.chains)[number])) {\n\t\t\tthrow new Error(\n\t\t\t\t`A valid Sui chain identifier was not provided in the request. Please report this issue to the dApp developer. Examples of valid Sui chain identifiers are 'sui:testnet' and 'sui:mainnet'. Consider using the '@mysten/dapp-kit' package, which provides this value automatically.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nexport function registerEnokiWallets({\n\tproviders,\n\tclient,\n\tnetwork = 'mainnet',\n\twindowFeatures = defaultWindowFeatures,\n\t...config\n}: RegisterEnokiWalletsOptions) {\n\tconst walletsApi = getWallets();\n\tconst flow = new INTERNAL_ONLY_EnokiFlow({ ...config, network });\n\n\tconst unregisterCallbacks: (() => void)[] = [];\n\tconst wallets: Partial<Record<AuthProvider, EnokiWallet>> = {};\n\n\tfor (const { name, icon, provider } of ENOKI_PROVIDER_WALLETS_INFO) {\n\t\tconst providerOptions = providers[provider];\n\t\tif (providerOptions) {\n\t\t\tconst { clientId, redirectUrl, extraParams } = providerOptions;\n\t\t\tconst wallet = new EnokiWallet({\n\t\t\t\tname,\n\t\t\t\ticon,\n\t\t\t\tflow,\n\t\t\t\tprovider,\n\t\t\t\tclientId,\n\t\t\t\tclient,\n\t\t\t\tredirectUrl,\n\t\t\t\textraParams,\n\t\t\t\twindowFeatures,\n\t\t\t});\n\n\t\t\tconst unregister = walletsApi.register(wallet);\n\t\t\tunregisterCallbacks.push(unregister);\n\n\t\t\twallets[provider] = wallet;\n\t\t}\n\t}\n\n\treturn {\n\t\twallets,\n\t\tunregister: () => {\n\t\t\tfor (const unregister of unregisterCallbacks) {\n\t\t\t\tunregister();\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport function defaultWindowFeatures() {\n\tconst width = 500;\n\tconst height = 800;\n\tconst left = (screen.width - width) / 2;\n\tconst top = (screen.height - height) / 4;\n\n\treturn `popup=1;toolbar=0;status=0;resizable=1,width=${width},height=${height},top=${top},left=${left}`;\n}\n"],
5
+ "mappings": ";;;;;;;;AAAA;AAIA,SAAS,mBAAmB;AAC5B,SAAS,YAAY,gBAAgB;AAiBrC;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AAEP,OAAO,UAAU;AAGjB,SAAS,mCAAmC;AAC5C,SAAS,+BAA+B;AAGxC,SAAS,wBAAwB;AACjC,SAAS,iBAAiB;AAEnB,MAAM,YAA8B;AAAA,EAiF1C,Y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_EnokiFlow {
32
32
  provider: AuthProvider;
33
33
  clientId: string;
34
34
  redirectUrl: string;
35
- extraParams?: Record<string, unknown>;
35
+ extraParams?: Record<string, string>;
36
36
  }): Promise<string>;
37
37
  handleAuthCallback(hash?: string): Promise<string | null>;
38
38
  getSession(): Promise<ZkLoginSession | null>;
@@ -38,7 +38,7 @@ class INTERNAL_ONLY_EnokiFlow {
38
38
  __privateSet(this, _encryption, createDefaultEncryption());
39
39
  __privateSet(this, _store, createSessionStorage());
40
40
  __privateSet(this, _storageKeys, createStorageKeys(config.apiKey, __privateGet(this, _network)));
41
- __privateSet(this, _idbStore, createStore("enoki", `${config.apiKey}_${__privateGet(this, _network)}`));
41
+ __privateSet(this, _idbStore, createStore(`${config.apiKey}_${__privateGet(this, _network)}`, "enoki"));
42
42
  let storedState = null;
43
43
  try {
44
44
  const rawStoredValue = __privateGet(this, _store).get(__privateGet(this, _storageKeys).STATE);
@@ -75,7 +75,7 @@ class INTERNAL_ONLY_EnokiFlow {
75
75
  scope: [
76
76
  "openid",
77
77
  // Merge the requested scopes in with the required openid scopes:
78
- ...input.extraParams && "scope" in input.extraParams ? input.extraParams.scope : []
78
+ ...input.extraParams?.scope ? input.extraParams.scope.split(" ") : []
79
79
  ].filter(Boolean).join(" ")
80
80
  });
81
81
  let oauthUrl;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/wallet/state.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { ExportedWebCryptoKeypair } from '@mysten/signers/webcrypto';\nimport { WebCryptoSigner } from '@mysten/signers/webcrypto';\nimport { decodeJwt } from '@mysten/sui/zklogin';\nimport type { ZkLoginSignatureInputs } from '@mysten/sui/zklogin';\nimport type { UseStore } from 'idb-keyval';\nimport { clear, createStore, get, set } from 'idb-keyval';\nimport type { WritableAtom } from 'nanostores';\nimport { atom, onMount, onSet } from 'nanostores';\n\nimport type { Encryption } from '../encryption.js';\nimport { createDefaultEncryption } from '../encryption.js';\nimport type { EnokiClientConfig } from '../EnokiClient/index.js';\nimport { EnokiClient } from '../EnokiClient/index.js';\nimport type { AuthProvider, EnokiNetwork } from '../EnokiClient/type.js';\nimport { EnokiKeypair } from '../EnokiKeypair.js';\nimport type { SyncStore } from '../stores.js';\nimport { createSessionStorage } from '../stores.js';\n\ntype EnokiFlowConfig = EnokiClientConfig & { network: EnokiNetwork };\n\n// State that is not bound to a session, and is encrypted.\ninterface ZkLoginState {\n\tprovider?: AuthProvider;\n\taddress?: string;\n\tsalt?: string;\n\tpublicKey?: string;\n}\n\n// State that session-bound, and is encrypted in storage.\ninterface ZkLoginSession {\n\tmaxEpoch: number;\n\trandomness: string;\n\texpiresAt: number;\n\n\tjwt?: string;\n\tproof?: ZkLoginSignatureInputs;\n}\n\nconst createStorageKeys = (apiKey: string, network: EnokiNetwork) => ({\n\tSTATE: `@enoki/flow/state/${apiKey}/${network}`,\n\tSESSION: `@enoki/flow/session/${apiKey}/${network}`,\n});\n\nexport class INTERNAL_ONLY_EnokiFlow {\n\t#storageKeys: { STATE: string; SESSION: string };\n\t#enokiClient: EnokiClient;\n\t#network: EnokiNetwork;\n\t#encryption: Encryption;\n\t#encryptionKey: string;\n\t#store: SyncStore;\n\t#idbStore: UseStore;\n\n\t$zkLoginSession: WritableAtom<{ initialized: boolean; value: ZkLoginSession | null }>;\n\t$zkLoginState: WritableAtom<ZkLoginState>;\n\n\tconstructor(config: EnokiFlowConfig) {\n\t\tthis.#enokiClient = new EnokiClient({\n\t\t\tapiKey: config.apiKey,\n\t\t\tapiUrl: config.apiUrl,\n\t\t});\n\t\tthis.#network = config.network;\n\t\tthis.#encryptionKey = config.apiKey;\n\t\tthis.#encryption = createDefaultEncryption();\n\t\tthis.#store = createSessionStorage();\n\t\tthis.#storageKeys = createStorageKeys(config.apiKey, this.#network);\n\t\tthis.#idbStore = createStore('enoki', `${config.apiKey}_${this.#network}`);\n\n\t\tlet storedState = null;\n\t\ttry {\n\t\t\tconst rawStoredValue = this.#store.get(this.#storageKeys.STATE);\n\t\t\tif (rawStoredValue) {\n\t\t\t\tstoredState = JSON.parse(rawStoredValue);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore errors\n\t\t}\n\n\t\tthis.$zkLoginState = atom(storedState || {});\n\t\tthis.$zkLoginSession = atom({ initialized: false, value: null });\n\n\t\t// Hydrate the session on mount:\n\t\tonMount(this.$zkLoginSession, () => {\n\t\t\tthis.getSession();\n\t\t});\n\n\t\tonSet(this.$zkLoginState, ({ newValue }) => {\n\t\t\tthis.#store.set(this.#storageKeys.STATE, JSON.stringify(newValue));\n\t\t});\n\t}\n\n\tget network() {\n\t\treturn this.#network;\n\t}\n\n\tasync createAuthorizationURL(input: {\n\t\tprovider: AuthProvider;\n\t\tclientId: string;\n\t\tredirectUrl: string;\n\t\textraParams?: Record<string, unknown>;\n\t}) {\n\t\tconst ephemeralKeyPair = await WebCryptoSigner.generate();\n\t\tconst { nonce, randomness, maxEpoch, estimatedExpiration } =\n\t\t\tawait this.#enokiClient.createZkLoginNonce({\n\t\t\t\tnetwork: this.#network,\n\t\t\t\tephemeralPublicKey: ephemeralKeyPair.getPublicKey(),\n\t\t\t});\n\n\t\tconst params = new URLSearchParams({\n\t\t\t...input.extraParams,\n\t\t\tnonce,\n\t\t\tclient_id: input.clientId,\n\t\t\tredirect_uri: input.redirectUrl,\n\t\t\tresponse_type: 'id_token',\n\t\t\t// TODO: Eventually fetch the scopes for this client ID from the Enoki service:\n\t\t\tscope: [\n\t\t\t\t'openid',\n\t\t\t\t// Merge the requested scopes in with the required openid scopes:\n\t\t\t\t...(input.extraParams && 'scope' in input.extraParams\n\t\t\t\t\t? (input.extraParams.scope as string[])\n\t\t\t\t\t: []),\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(' '),\n\t\t});\n\n\t\tlet oauthUrl: string;\n\t\tswitch (input.provider) {\n\t\t\tcase 'google': {\n\t\t\t\toauthUrl = `https://accounts.google.com/o/oauth2/v2/auth?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'facebook': {\n\t\t\t\toauthUrl = `https://www.facebook.com/v17.0/dialog/oauth?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'twitch': {\n\t\t\t\tparams.set('force_verify', 'true');\n\t\t\t\toauthUrl = `https://id.twitch.tv/oauth2/authorize?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Invalid provider: ${input.provider}`);\n\t\t}\n\n\t\tthis.$zkLoginState.set({ provider: input.provider });\n\n\t\tawait set('ephemeralKeyPair', ephemeralKeyPair.export(), this.#idbStore);\n\t\tawait this.#setSession({\n\t\t\texpiresAt: estimatedExpiration,\n\t\t\tmaxEpoch,\n\t\t\trandomness,\n\t\t});\n\n\t\treturn oauthUrl;\n\t}\n\n\tasync handleAuthCallback(hash: string = window.location.hash) {\n\t\tconst params = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash);\n\n\t\t// Before we handle the auth redirect and get the state, we need to restore it:\n\t\tconst zkp = await this.getSession();\n\n\t\tif (!zkp || !zkp.maxEpoch || !zkp.randomness) {\n\t\t\tthrow new Error(\n\t\t\t\t'Start of sign-in flow could not be found. Ensure you have started the sign-in flow before calling this.',\n\t\t\t);\n\t\t}\n\n\t\tconst jwt = params.get('id_token');\n\t\tif (!jwt) {\n\t\t\tthrow new Error('Missing ID Token');\n\t\t}\n\n\t\tdecodeJwt(jwt);\n\n\t\tconst { address, salt, publicKey } = await this.#enokiClient.getZkLogin({ jwt });\n\n\t\tthis.$zkLoginState.set({\n\t\t\t...this.$zkLoginState.get(),\n\t\t\tsalt,\n\t\t\taddress,\n\t\t\tpublicKey,\n\t\t});\n\t\tawait this.#setSession({\n\t\t\t...zkp,\n\t\t\tjwt,\n\t\t});\n\n\t\treturn params.get('state');\n\t}\n\n\tasync #setSession(newValue: ZkLoginSession | null) {\n\t\tif (newValue) {\n\t\t\tconst storedValue = await this.#encryption.encrypt(\n\t\t\t\tthis.#encryptionKey,\n\t\t\t\tJSON.stringify(newValue),\n\t\t\t);\n\n\t\t\tthis.#store.set(this.#storageKeys.SESSION, storedValue);\n\t\t} else {\n\t\t\tthis.#store.delete(this.#storageKeys.SESSION);\n\t\t}\n\n\t\tthis.$zkLoginSession.set({ initialized: true, value: newValue });\n\t}\n\n\tasync getSession() {\n\t\tif (this.$zkLoginSession.get().initialized) {\n\t\t\treturn this.$zkLoginSession.get().value;\n\t\t}\n\n\t\ttry {\n\t\t\tconst storedValue = this.#store.get(this.#storageKeys.SESSION);\n\t\t\tif (!storedValue) return null;\n\n\t\t\tconst state: ZkLoginSession = JSON.parse(\n\t\t\t\tawait this.#encryption.decrypt(this.#encryptionKey, storedValue),\n\t\t\t);\n\n\t\t\t// TODO: Rather than having expiration act as a logout, we should keep the state that still is relevant,\n\t\t\t// and just clear out the expired session, but keep the other zkLogin state.\n\t\t\tif (state?.expiresAt && Date.now() > state.expiresAt) {\n\t\t\t\tawait this.logout();\n\t\t\t} else {\n\t\t\t\tthis.$zkLoginSession.set({ initialized: true, value: state });\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.$zkLoginSession.set({ initialized: true, value: null });\n\t\t}\n\n\t\treturn this.$zkLoginSession.get().value;\n\t}\n\n\tasync logout() {\n\t\tthis.$zkLoginState.set({});\n\t\tthis.#store.delete(this.#storageKeys.STATE);\n\n\t\tawait clear(this.#idbStore);\n\t\tawait this.#setSession(null);\n\t}\n\n\t// TODO: Should this return the proof if it already exists?\n\tasync getProof() {\n\t\tconst zkp = await this.getSession();\n\t\tconst { salt } = this.$zkLoginState.get();\n\n\t\tif (zkp?.proof) {\n\t\t\tif (zkp.expiresAt && Date.now() > zkp.expiresAt) {\n\t\t\t\tthrow new Error('Stored proof is expired.');\n\t\t\t}\n\n\t\t\treturn zkp.proof;\n\t\t}\n\n\t\tif (!salt || !zkp || !zkp.jwt) {\n\t\t\tthrow new Error('Missing required parameters for proof generation');\n\t\t}\n\n\t\tconst storedNativeSigner = await get<ExportedWebCryptoKeypair>(\n\t\t\t'ephemeralKeyPair',\n\t\t\tthis.#idbStore,\n\t\t);\n\t\tif (!storedNativeSigner) {\n\t\t\tthrow new Error('Native signer not found in store.');\n\t\t}\n\n\t\tconst ephemeralKeyPair = WebCryptoSigner.import(storedNativeSigner);\n\n\t\tconst proof = await this.#enokiClient.createZkLoginZkp({\n\t\t\tnetwork: this.#network,\n\t\t\tjwt: zkp.jwt,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\trandomness: zkp.randomness,\n\t\t\tephemeralPublicKey: ephemeralKeyPair.getPublicKey(),\n\t\t});\n\n\t\tawait this.#setSession({\n\t\t\t...zkp,\n\t\t\tproof,\n\t\t});\n\n\t\treturn proof;\n\t}\n\n\tasync getKeypair() {\n\t\t// Get the proof, so that we ensure it exists in state:\n\t\tawait this.getProof();\n\n\t\tconst zkp = await this.getSession();\n\n\t\t// Check to see if we have the essentials for a keypair:\n\t\tconst { address } = this.$zkLoginState.get();\n\t\tif (!address || !zkp || !zkp.proof) {\n\t\t\tthrow new Error('Missing required data for keypair generation.');\n\t\t}\n\n\t\tif (Date.now() > zkp.expiresAt) {\n\t\t\tthrow new Error('Stored proof is expired.');\n\t\t}\n\n\t\tconst storedNativeSigner = await get<ExportedWebCryptoKeypair>(\n\t\t\t'ephemeralKeyPair',\n\t\t\tthis.#idbStore,\n\t\t);\n\n\t\tif (!storedNativeSigner) {\n\t\t\tthrow new Error('Native signer not found in store.');\n\t\t}\n\n\t\tconst ephemeralKeypair = WebCryptoSigner.import(storedNativeSigner);\n\n\t\treturn new EnokiKeypair({\n\t\t\taddress,\n\t\t\tephemeralKeypair,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\tproof: zkp.proof,\n\t\t});\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;AAAA;AAIA,SAAS,uBAAuB;AAChC,SAAS,iBA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,CAAC,OAAO,CAAC,IAAI,OAAO;AACnC,YAAM,IAAI,MAAM,+CAA+C;AAAA,IAChE;AAEA,QAAI,KAAK,IAAI,IAAI,IAAI,WAAW;AAC/B,YAAM,IAAI,MAAM,0BAA0B;AAAA,IAC3C;AAEA,UAAM,qBAAqB,MAAM;AAAA,MAChC;AAAA,MACA,mBAAK;AAAA,IACN;AAEA,QAAI,CAAC,oBAAoB;AACxB,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACpD;AAEA,UAAM,mBAAmB,gBAAgB,OAAO,kBAAkB;AAElE,WAAO,IAAI,aAAa;AAAA,MACvB;AAAA,MACA;AAAA,MACA,UAAU,IAAI;AAAA,MACd,OAAO,IAAI;AAAA,IACZ,CAAC;AAAA,EACF;AACD;AAlRC;AACA;AACA;AACA;AACA;AACA;AACA;AAPM;AAoJA,gBAAW,eAAC,UAAiC;AAClD,MAAI,UAAU;AACb,UAAM,cAAc,MAAM,mBAAK,aAAY;AAAA,MAC1C,mBAAK;AAAA,MACL,KAAK,UAAU,QAAQ;AAAA,IACxB;AAEA,uBAAK,QAAO,IAAI,mBAAK,cAAa,SAAS,WAAW;AAAA,EACvD,OAAO;AACN,uBAAK,QAAO,OAAO,mBAAK,cAAa,OAAO;AAAA,EAC7C;AAEA,OAAK,gBAAgB,IAAI,EAAE,aAAa,MAAM,OAAO,SAAS,CAAC;AAChE;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { ExportedWebCryptoKeypair } from '@mysten/signers/webcrypto';\nimport { WebCryptoSigner } from '@mysten/signers/webcrypto';\nimport { decodeJwt } from '@mysten/sui/zklogin';\nimport type { ZkLoginSignatureInputs } from '@mysten/sui/zklogin';\nimport type { UseStore } from 'idb-keyval';\nimport { clear, createStore, get, set } from 'idb-keyval';\nimport type { WritableAtom } from 'nanostores';\nimport { atom, onMount, onSet } from 'nanostores';\n\nimport type { Encryption } from '../encryption.js';\nimport { createDefaultEncryption } from '../encryption.js';\nimport type { EnokiClientConfig } from '../EnokiClient/index.js';\nimport { EnokiClient } from '../EnokiClient/index.js';\nimport type { AuthProvider, EnokiNetwork } from '../EnokiClient/type.js';\nimport { EnokiKeypair } from '../EnokiKeypair.js';\nimport type { SyncStore } from '../stores.js';\nimport { createSessionStorage } from '../stores.js';\n\ntype EnokiFlowConfig = EnokiClientConfig & { network: EnokiNetwork };\n\n// State that is not bound to a session, and is encrypted.\ninterface ZkLoginState {\n\tprovider?: AuthProvider;\n\taddress?: string;\n\tsalt?: string;\n\tpublicKey?: string;\n}\n\n// State that session-bound, and is encrypted in storage.\ninterface ZkLoginSession {\n\tmaxEpoch: number;\n\trandomness: string;\n\texpiresAt: number;\n\n\tjwt?: string;\n\tproof?: ZkLoginSignatureInputs;\n}\n\nconst createStorageKeys = (apiKey: string, network: EnokiNetwork) => ({\n\tSTATE: `@enoki/flow/state/${apiKey}/${network}`,\n\tSESSION: `@enoki/flow/session/${apiKey}/${network}`,\n});\n\nexport class INTERNAL_ONLY_EnokiFlow {\n\t#storageKeys: { STATE: string; SESSION: string };\n\t#enokiClient: EnokiClient;\n\t#network: EnokiNetwork;\n\t#encryption: Encryption;\n\t#encryptionKey: string;\n\t#store: SyncStore;\n\t#idbStore: UseStore;\n\n\t$zkLoginSession: WritableAtom<{ initialized: boolean; value: ZkLoginSession | null }>;\n\t$zkLoginState: WritableAtom<ZkLoginState>;\n\n\tconstructor(config: EnokiFlowConfig) {\n\t\tthis.#enokiClient = new EnokiClient({\n\t\t\tapiKey: config.apiKey,\n\t\t\tapiUrl: config.apiUrl,\n\t\t});\n\t\tthis.#network = config.network;\n\t\tthis.#encryptionKey = config.apiKey;\n\t\tthis.#encryption = createDefaultEncryption();\n\t\tthis.#store = createSessionStorage();\n\t\tthis.#storageKeys = createStorageKeys(config.apiKey, this.#network);\n\t\tthis.#idbStore = createStore(`${config.apiKey}_${this.#network}`, 'enoki');\n\n\t\tlet storedState = null;\n\t\ttry {\n\t\t\tconst rawStoredValue = this.#store.get(this.#storageKeys.STATE);\n\t\t\tif (rawStoredValue) {\n\t\t\t\tstoredState = JSON.parse(rawStoredValue);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore errors\n\t\t}\n\n\t\tthis.$zkLoginState = atom(storedState || {});\n\t\tthis.$zkLoginSession = atom({ initialized: false, value: null });\n\n\t\t// Hydrate the session on mount:\n\t\tonMount(this.$zkLoginSession, () => {\n\t\t\tthis.getSession();\n\t\t});\n\n\t\tonSet(this.$zkLoginState, ({ newValue }) => {\n\t\t\tthis.#store.set(this.#storageKeys.STATE, JSON.stringify(newValue));\n\t\t});\n\t}\n\n\tget network() {\n\t\treturn this.#network;\n\t}\n\n\tasync createAuthorizationURL(input: {\n\t\tprovider: AuthProvider;\n\t\tclientId: string;\n\t\tredirectUrl: string;\n\t\textraParams?: Record<string, string>;\n\t}) {\n\t\tconst ephemeralKeyPair = await WebCryptoSigner.generate();\n\t\tconst { nonce, randomness, maxEpoch, estimatedExpiration } =\n\t\t\tawait this.#enokiClient.createZkLoginNonce({\n\t\t\t\tnetwork: this.#network,\n\t\t\t\tephemeralPublicKey: ephemeralKeyPair.getPublicKey(),\n\t\t\t});\n\n\t\tconst params = new URLSearchParams({\n\t\t\t...input.extraParams,\n\t\t\tnonce,\n\t\t\tclient_id: input.clientId,\n\t\t\tredirect_uri: input.redirectUrl,\n\t\t\tresponse_type: 'id_token',\n\t\t\t// TODO: Eventually fetch the scopes for this client ID from the Enoki service:\n\t\t\tscope: [\n\t\t\t\t'openid',\n\t\t\t\t// Merge the requested scopes in with the required openid scopes:\n\t\t\t\t...(input.extraParams?.scope ? input.extraParams.scope.split(' ') : []),\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(' '),\n\t\t});\n\n\t\tlet oauthUrl: string;\n\t\tswitch (input.provider) {\n\t\t\tcase 'google': {\n\t\t\t\toauthUrl = `https://accounts.google.com/o/oauth2/v2/auth?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'facebook': {\n\t\t\t\toauthUrl = `https://www.facebook.com/v17.0/dialog/oauth?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'twitch': {\n\t\t\t\tparams.set('force_verify', 'true');\n\t\t\t\toauthUrl = `https://id.twitch.tv/oauth2/authorize?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Invalid provider: ${input.provider}`);\n\t\t}\n\n\t\tthis.$zkLoginState.set({ provider: input.provider });\n\n\t\tawait set('ephemeralKeyPair', ephemeralKeyPair.export(), this.#idbStore);\n\t\tawait this.#setSession({\n\t\t\texpiresAt: estimatedExpiration,\n\t\t\tmaxEpoch,\n\t\t\trandomness,\n\t\t});\n\n\t\treturn oauthUrl;\n\t}\n\n\tasync handleAuthCallback(hash: string = window.location.hash) {\n\t\tconst params = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash);\n\n\t\t// Before we handle the auth redirect and get the state, we need to restore it:\n\t\tconst zkp = await this.getSession();\n\n\t\tif (!zkp || !zkp.maxEpoch || !zkp.randomness) {\n\t\t\tthrow new Error(\n\t\t\t\t'Start of sign-in flow could not be found. Ensure you have started the sign-in flow before calling this.',\n\t\t\t);\n\t\t}\n\n\t\tconst jwt = params.get('id_token');\n\t\tif (!jwt) {\n\t\t\tthrow new Error('Missing ID Token');\n\t\t}\n\n\t\tdecodeJwt(jwt);\n\n\t\tconst { address, salt, publicKey } = await this.#enokiClient.getZkLogin({ jwt });\n\n\t\tthis.$zkLoginState.set({\n\t\t\t...this.$zkLoginState.get(),\n\t\t\tsalt,\n\t\t\taddress,\n\t\t\tpublicKey,\n\t\t});\n\t\tawait this.#setSession({\n\t\t\t...zkp,\n\t\t\tjwt,\n\t\t});\n\n\t\treturn params.get('state');\n\t}\n\n\tasync #setSession(newValue: ZkLoginSession | null) {\n\t\tif (newValue) {\n\t\t\tconst storedValue = await this.#encryption.encrypt(\n\t\t\t\tthis.#encryptionKey,\n\t\t\t\tJSON.stringify(newValue),\n\t\t\t);\n\n\t\t\tthis.#store.set(this.#storageKeys.SESSION, storedValue);\n\t\t} else {\n\t\t\tthis.#store.delete(this.#storageKeys.SESSION);\n\t\t}\n\n\t\tthis.$zkLoginSession.set({ initialized: true, value: newValue });\n\t}\n\n\tasync getSession() {\n\t\tif (this.$zkLoginSession.get().initialized) {\n\t\t\treturn this.$zkLoginSession.get().value;\n\t\t}\n\n\t\ttry {\n\t\t\tconst storedValue = this.#store.get(this.#storageKeys.SESSION);\n\t\t\tif (!storedValue) return null;\n\n\t\t\tconst state: ZkLoginSession = JSON.parse(\n\t\t\t\tawait this.#encryption.decrypt(this.#encryptionKey, storedValue),\n\t\t\t);\n\n\t\t\t// TODO: Rather than having expiration act as a logout, we should keep the state that still is relevant,\n\t\t\t// and just clear out the expired session, but keep the other zkLogin state.\n\t\t\tif (state?.expiresAt && Date.now() > state.expiresAt) {\n\t\t\t\tawait this.logout();\n\t\t\t} else {\n\t\t\t\tthis.$zkLoginSession.set({ initialized: true, value: state });\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.$zkLoginSession.set({ initialized: true, value: null });\n\t\t}\n\n\t\treturn this.$zkLoginSession.get().value;\n\t}\n\n\tasync logout() {\n\t\tthis.$zkLoginState.set({});\n\t\tthis.#store.delete(this.#storageKeys.STATE);\n\n\t\tawait clear(this.#idbStore);\n\t\tawait this.#setSession(null);\n\t}\n\n\t// TODO: Should this return the proof if it already exists?\n\tasync getProof() {\n\t\tconst zkp = await this.getSession();\n\t\tconst { salt } = this.$zkLoginState.get();\n\n\t\tif (zkp?.proof) {\n\t\t\tif (zkp.expiresAt && Date.now() > zkp.expiresAt) {\n\t\t\t\tthrow new Error('Stored proof is expired.');\n\t\t\t}\n\n\t\t\treturn zkp.proof;\n\t\t}\n\n\t\tif (!salt || !zkp || !zkp.jwt) {\n\t\t\tthrow new Error('Missing required parameters for proof generation');\n\t\t}\n\n\t\tconst storedNativeSigner = await get<ExportedWebCryptoKeypair>(\n\t\t\t'ephemeralKeyPair',\n\t\t\tthis.#idbStore,\n\t\t);\n\t\tif (!storedNativeSigner) {\n\t\t\tthrow new Error('Native signer not found in store.');\n\t\t}\n\n\t\tconst ephemeralKeyPair = WebCryptoSigner.import(storedNativeSigner);\n\n\t\tconst proof = await this.#enokiClient.createZkLoginZkp({\n\t\t\tnetwork: this.#network,\n\t\t\tjwt: zkp.jwt,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\trandomness: zkp.randomness,\n\t\t\tephemeralPublicKey: ephemeralKeyPair.getPublicKey(),\n\t\t});\n\n\t\tawait this.#setSession({\n\t\t\t...zkp,\n\t\t\tproof,\n\t\t});\n\n\t\treturn proof;\n\t}\n\n\tasync getKeypair() {\n\t\t// Get the proof, so that we ensure it exists in state:\n\t\tawait this.getProof();\n\n\t\tconst zkp = await this.getSession();\n\n\t\t// Check to see if we have the essentials for a keypair:\n\t\tconst { address } = this.$zkLoginState.get();\n\t\tif (!address || !zkp || !zkp.proof) {\n\t\t\tthrow new Error('Missing required data for keypair generation.');\n\t\t}\n\n\t\tif (Date.now() > zkp.expiresAt) {\n\t\t\tthrow new Error('Stored proof is expired.');\n\t\t}\n\n\t\tconst storedNativeSigner = await get<ExportedWebCryptoKeypair>(\n\t\t\t'ephemeralKeyPair',\n\t\t\tthis.#idbStore,\n\t\t);\n\n\t\tif (!storedNativeSigner) {\n\t\t\tthrow new Error('Native signer not found in store.');\n\t\t}\n\n\t\tconst ephemeralKeypair = WebCryptoSigner.import(storedNativeSigner);\n\n\t\treturn new EnokiKeypair({\n\t\t\taddress,\n\t\t\tephemeralKeypair,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\tproof: zkp.proof,\n\t\t});\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;AAAA;AAIA,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAG1B,SAAS,OAAO,aAAa,KAAK,WAAW;AAE7C,SAAS,MAAM,SAAS,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