@mysten/enoki 0.4.3 → 0.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/cjs/EnokiFlow.js +5 -5
- package/dist/cjs/EnokiFlow.js.map +2 -2
- package/dist/cjs/encryption.js +6 -6
- package/dist/cjs/encryption.js.map +2 -2
- package/dist/esm/EnokiFlow.js +6 -6
- package/dist/esm/EnokiFlow.js.map +2 -2
- package/dist/esm/encryption.js +7 -7
- package/dist/esm/encryption.js.map +2 -2
- package/dist/tsconfig.esm.tsbuildinfo +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @mysten/enoki
|
|
2
2
|
|
|
3
|
+
## 0.4.5
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [5436a90]
|
|
8
|
+
- Updated dependencies [5436a90]
|
|
9
|
+
- @mysten/sui@1.12.0
|
|
10
|
+
- @mysten/zklogin@0.7.22
|
|
11
|
+
|
|
12
|
+
## 0.4.4
|
|
13
|
+
|
|
14
|
+
### Patch Changes
|
|
15
|
+
|
|
16
|
+
- Updated dependencies [489f421]
|
|
17
|
+
- Updated dependencies [489f421]
|
|
18
|
+
- @mysten/sui@1.11.0
|
|
19
|
+
- @mysten/zklogin@0.7.21
|
|
20
|
+
|
|
3
21
|
## 0.4.3
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/dist/cjs/EnokiFlow.js
CHANGED
|
@@ -121,7 +121,7 @@ class EnokiFlow {
|
|
|
121
121
|
expiresAt: estimatedExpiration,
|
|
122
122
|
maxEpoch,
|
|
123
123
|
randomness,
|
|
124
|
-
ephemeralKeyPair: (0, import_utils.
|
|
124
|
+
ephemeralKeyPair: (0, import_utils.toBase64)((0, import_cryptography.decodeSuiPrivateKey)(ephemeralKeyPair.getSecretKey()).secretKey)
|
|
125
125
|
});
|
|
126
126
|
return oauthUrl;
|
|
127
127
|
}
|
|
@@ -192,7 +192,7 @@ class EnokiFlow {
|
|
|
192
192
|
if (!salt || !zkp || !zkp.jwt) {
|
|
193
193
|
throw new Error("Missing required parameters for proof generation");
|
|
194
194
|
}
|
|
195
|
-
const ephemeralKeyPair = import_ed25519.Ed25519Keypair.fromSecretKey((0, import_utils.
|
|
195
|
+
const ephemeralKeyPair = import_ed25519.Ed25519Keypair.fromSecretKey((0, import_utils.fromBase64)(zkp.ephemeralKeyPair));
|
|
196
196
|
const proof = await __privateGet(this, _enokiClient).createZkLoginZkp({
|
|
197
197
|
network,
|
|
198
198
|
jwt: zkp.jwt,
|
|
@@ -220,7 +220,7 @@ class EnokiFlow {
|
|
|
220
220
|
address,
|
|
221
221
|
maxEpoch: zkp.maxEpoch,
|
|
222
222
|
proof: zkp.proof,
|
|
223
|
-
ephemeralKeypair: import_ed25519.Ed25519Keypair.fromSecretKey((0, import_utils.
|
|
223
|
+
ephemeralKeypair: import_ed25519.Ed25519Keypair.fromSecretKey((0, import_utils.fromBase64)(zkp.ephemeralKeyPair))
|
|
224
224
|
});
|
|
225
225
|
}
|
|
226
226
|
async sponsorTransaction({
|
|
@@ -239,7 +239,7 @@ class EnokiFlow {
|
|
|
239
239
|
return await __privateGet(this, _enokiClient).createSponsoredTransaction({
|
|
240
240
|
jwt: session.jwt,
|
|
241
241
|
network,
|
|
242
|
-
transactionKindBytes: (0, import_utils.
|
|
242
|
+
transactionKindBytes: (0, import_utils.toBase64)(transactionKindBytes)
|
|
243
243
|
});
|
|
244
244
|
}
|
|
245
245
|
async executeTransaction({
|
|
@@ -249,7 +249,7 @@ class EnokiFlow {
|
|
|
249
249
|
client
|
|
250
250
|
}) {
|
|
251
251
|
const keypair = await this.getKeypair({ network });
|
|
252
|
-
const userSignature = await keypair.signTransaction((0, import_utils.
|
|
252
|
+
const userSignature = await keypair.signTransaction((0, import_utils.fromBase64)(bytes));
|
|
253
253
|
await __privateGet(this, _enokiClient).executeSponsoredTransaction({
|
|
254
254
|
digest,
|
|
255
255
|
signature: userSignature.signature
|
|
@@ -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 { SuiClient } from '@mysten/sui/client';\nimport { decodeSuiPrivateKey } from '@mysten/sui/cryptography';\nimport { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport type { Transaction } from '@mysten/sui/transactions';\nimport { fromB64, toB64 } from '@mysten/sui/utils';\nimport type { ZkLoginSignatureInputs } from '@mysten/sui/zklogin';\nimport { decodeJwt } from 'jose';\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 { EnokiKeypair } from './EnokiKeypair.js';\nimport type { SyncStore } from './stores.js';\nimport { createSessionStorage } from './stores.js';\n\nexport interface EnokiFlowConfig extends EnokiClientConfig {\n\t/**\n\t * The storage interface to persist Enoki data locally.\n\t * If not provided, it will use a sessionStorage-backed store.\n\t */\n\tstore?: SyncStore;\n\t/**\n\t * The encryption interface that will be used to encrypt data before storing it locally.\n\t * If not provided, it will use a default encryption interface.\n\t */\n\tencryption?: Encryption;\n}\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}\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\nexport type AuthProvider = 'google' | 'facebook' | 'twitch';\n\nconst createStorageKeys = (apiKey: string) => ({\n\tSTATE: `@enoki/flow/state/${apiKey}`,\n\tSESSION: `@enoki/flow/session/${apiKey}`,\n});\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\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\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 = new Ed25519Keypair();\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\tawait this.#setSession({\n\t\t\texpiresAt: estimatedExpiration,\n\t\t\tmaxEpoch,\n\t\t\trandomness,\n\t\t\tephemeralKeyPair: toB64(decodeSuiPrivateKey(ephemeralKeyPair.getSecretKey()).secretKey),\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\tconst decodedJwt = decodeJwt(jwt);\n\t\tif (!decodedJwt.sub || !decodedJwt.aud || typeof decodedJwt.aud !== 'string') {\n\t\t\tthrow new Error('Missing JWT data');\n\t\t}\n\n\t\tconst { address, salt } = 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});\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 this.#setSession(null);\n\t}\n\n\t// TODO: Should this return the proof if it already exists?\n\tasync getProof({ network }: { network?: 'mainnet' | 'testnet' } = {}) {\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 ephemeralKeyPair = Ed25519Keypair.fromSecretKey(fromB64(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?: 'mainnet' | 'testnet' } = {}) {\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\treturn new EnokiKeypair({\n\t\t\taddress,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\tproof: zkp.proof,\n\t\t\tephemeralKeypair: Ed25519Keypair.fromSecretKey(fromB64(zkp.ephemeralKeyPair)),\n\t\t});\n\t}\n\n\tasync sponsorTransaction({\n\t\tnetwork,\n\t\ttransaction,\n\t\tclient,\n\t}: {\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\ttransaction: Transaction;\n\t\tclient: SuiClient;\n\t}) {\n\t\tconst session = await this.getSession();\n\n\t\tif (!session || !session.jwt) {\n\t\t\tthrow new Error('Missing required data for sponsorship.');\n\t\t}\n\n\t\tconst transactionKindBytes = await transaction.build({\n\t\t\tonlyTransactionKind: true,\n\t\t\tclient,\n\t\t});\n\n\t\treturn await this.#enokiClient.createSponsoredTransaction({\n\t\t\tjwt: session.jwt,\n\t\t\tnetwork,\n\t\t\ttransactionKindBytes: toB64(transactionKindBytes),\n\t\t});\n\t}\n\n\tasync executeTransaction({\n\t\tnetwork,\n\t\tbytes,\n\t\tdigest,\n\t\tclient,\n\t}: {\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\tbytes: string;\n\t\tdigest: string;\n\t\tclient: SuiClient;\n\t}) {\n\t\tconst keypair = await this.getKeypair({ network });\n\t\tconst userSignature = await keypair.signTransaction(fromB64(bytes));\n\n\t\tawait this.#enokiClient.executeSponsoredTransaction({\n\t\t\tdigest,\n\t\t\tsignature: userSignature.signature,\n\t\t});\n\n\t\t// TODO: Should the parent just do this?\n\t\tawait client.waitForTransaction({ digest });\n\n\t\treturn { digest };\n\t}\n\n\tasync sponsorAndExecuteTransaction({\n\t\tnetwork,\n\t\ttransaction,\n\t\tclient,\n\t}: {\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\ttransaction: Transaction;\n\t\tclient: SuiClient;\n\t}) {\n\t\tconst { bytes, digest } = await this.sponsorTransaction({\n\t\t\tnetwork,\n\t\t\ttransaction,\n\t\t\tclient,\n\t\t});\n\t\treturn await this.executeTransaction({ network, bytes, digest, client });\n\t}\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,0BAAoC;AACpC,qBAA+B;AAE/B,
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { SuiClient } from '@mysten/sui/client';\nimport { decodeSuiPrivateKey } from '@mysten/sui/cryptography';\nimport { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport type { Transaction } from '@mysten/sui/transactions';\nimport { fromBase64, toBase64 } from '@mysten/sui/utils';\nimport type { ZkLoginSignatureInputs } from '@mysten/sui/zklogin';\nimport { decodeJwt } from 'jose';\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 { EnokiKeypair } from './EnokiKeypair.js';\nimport type { SyncStore } from './stores.js';\nimport { createSessionStorage } from './stores.js';\n\nexport interface EnokiFlowConfig extends EnokiClientConfig {\n\t/**\n\t * The storage interface to persist Enoki data locally.\n\t * If not provided, it will use a sessionStorage-backed store.\n\t */\n\tstore?: SyncStore;\n\t/**\n\t * The encryption interface that will be used to encrypt data before storing it locally.\n\t * If not provided, it will use a default encryption interface.\n\t */\n\tencryption?: Encryption;\n}\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}\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\nexport type AuthProvider = 'google' | 'facebook' | 'twitch';\n\nconst createStorageKeys = (apiKey: string) => ({\n\tSTATE: `@enoki/flow/state/${apiKey}`,\n\tSESSION: `@enoki/flow/session/${apiKey}`,\n});\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\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\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 = new Ed25519Keypair();\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\tawait this.#setSession({\n\t\t\texpiresAt: estimatedExpiration,\n\t\t\tmaxEpoch,\n\t\t\trandomness,\n\t\t\tephemeralKeyPair: toBase64(decodeSuiPrivateKey(ephemeralKeyPair.getSecretKey()).secretKey),\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\tconst decodedJwt = decodeJwt(jwt);\n\t\tif (!decodedJwt.sub || !decodedJwt.aud || typeof decodedJwt.aud !== 'string') {\n\t\t\tthrow new Error('Missing JWT data');\n\t\t}\n\n\t\tconst { address, salt } = 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});\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 this.#setSession(null);\n\t}\n\n\t// TODO: Should this return the proof if it already exists?\n\tasync getProof({ network }: { network?: 'mainnet' | 'testnet' } = {}) {\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 ephemeralKeyPair = 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?: 'mainnet' | 'testnet' } = {}) {\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\treturn new EnokiKeypair({\n\t\t\taddress,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\tproof: zkp.proof,\n\t\t\tephemeralKeypair: Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair)),\n\t\t});\n\t}\n\n\tasync sponsorTransaction({\n\t\tnetwork,\n\t\ttransaction,\n\t\tclient,\n\t}: {\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\ttransaction: Transaction;\n\t\tclient: SuiClient;\n\t}) {\n\t\tconst session = await this.getSession();\n\n\t\tif (!session || !session.jwt) {\n\t\t\tthrow new Error('Missing required data for sponsorship.');\n\t\t}\n\n\t\tconst transactionKindBytes = await transaction.build({\n\t\t\tonlyTransactionKind: true,\n\t\t\tclient,\n\t\t});\n\n\t\treturn await this.#enokiClient.createSponsoredTransaction({\n\t\t\tjwt: session.jwt,\n\t\t\tnetwork,\n\t\t\ttransactionKindBytes: toBase64(transactionKindBytes),\n\t\t});\n\t}\n\n\tasync executeTransaction({\n\t\tnetwork,\n\t\tbytes,\n\t\tdigest,\n\t\tclient,\n\t}: {\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\tbytes: string;\n\t\tdigest: string;\n\t\tclient: SuiClient;\n\t}) {\n\t\tconst keypair = await this.getKeypair({ network });\n\t\tconst userSignature = await keypair.signTransaction(fromBase64(bytes));\n\n\t\tawait this.#enokiClient.executeSponsoredTransaction({\n\t\t\tdigest,\n\t\t\tsignature: userSignature.signature,\n\t\t});\n\n\t\t// TODO: Should the parent just do this?\n\t\tawait client.waitForTransaction({ digest });\n\n\t\treturn { digest };\n\t}\n\n\tasync sponsorAndExecuteTransaction({\n\t\tnetwork,\n\t\ttransaction,\n\t\tclient,\n\t}: {\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\ttransaction: Transaction;\n\t\tclient: SuiClient;\n\t}) {\n\t\tconst { bytes, digest } = await this.sponsorTransaction({\n\t\t\tnetwork,\n\t\t\ttransaction,\n\t\t\tclient,\n\t\t});\n\t\treturn await this.executeTransaction({ network, bytes, digest, client });\n\t}\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,0BAAoC;AACpC,qBAA+B;AAE/B,mBAAqC;AAErC,kBAA0B;AAE1B,wBAAqC;AAGrC,wBAAwC;AAExC,yBAA4B;AAC5B,0BAA6B;AAE7B,oBAAqC;AAnBrC;AAsDA,MAAM,oBAAoB,CAAC,YAAoB;AAAA,EAC9C,OAAO,qBAAqB,MAAM;AAAA,EAClC,SAAS,uBAAuB,MAAM;AACvC;AAEO,MAAM,UAAU;AAAA,EAUtB,YAAY,QAAyB;AAV/B;AACN;AACA;AACA;AACA;AACA;AAMC,uBAAK,cAAe,IAAI,+BAAY;AAAA,MACnC,QAAQ,OAAO;AAAA,MACf,QAAQ,OAAO;AAAA,IAChB,CAAC;AACD,uBAAK,gBAAiB,OAAO;AAC7B,uBAAK,aAAc,OAAO,kBAAc,2CAAwB;AAChE,uBAAK,QAA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js/encryption.js
CHANGED
|
@@ -60,9 +60,9 @@ function createDefaultEncryption() {
|
|
|
60
60
|
new TextEncoder().encode(data)
|
|
61
61
|
);
|
|
62
62
|
return JSON.stringify({
|
|
63
|
-
payload: (0, import_utils.
|
|
64
|
-
iv: (0, import_utils.
|
|
65
|
-
salt: (0, import_utils.
|
|
63
|
+
payload: (0, import_utils.toBase64)(new Uint8Array(payload)),
|
|
64
|
+
iv: (0, import_utils.toBase64)(iv),
|
|
65
|
+
salt: (0, import_utils.toBase64)(salt)
|
|
66
66
|
});
|
|
67
67
|
},
|
|
68
68
|
async decrypt(password, data) {
|
|
@@ -70,14 +70,14 @@ function createDefaultEncryption() {
|
|
|
70
70
|
if (!parsed.payload || !parsed.iv || !parsed.salt) {
|
|
71
71
|
throw new Error("Invalid encrypted data");
|
|
72
72
|
}
|
|
73
|
-
const { derivedKey } = await keyFromPassword(password, (0, import_utils.
|
|
73
|
+
const { derivedKey } = await keyFromPassword(password, (0, import_utils.fromBase64)(parsed.salt));
|
|
74
74
|
const decryptedContent = await crypto.subtle.decrypt(
|
|
75
75
|
{
|
|
76
76
|
name: "AES-GCM",
|
|
77
|
-
iv: (0, import_utils.
|
|
77
|
+
iv: (0, import_utils.fromBase64)(parsed.iv)
|
|
78
78
|
},
|
|
79
79
|
derivedKey,
|
|
80
|
-
(0, import_utils.
|
|
80
|
+
(0, import_utils.fromBase64)(parsed.payload)
|
|
81
81
|
);
|
|
82
82
|
return new TextDecoder().decode(decryptedContent);
|
|
83
83
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/encryption.ts"],
|
|
4
|
-
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromBase64, toBase64 } from '@mysten/sui/utils';\n\n/**\n * An interface\n */\nexport interface Encryption {\n\tencrypt(password: string, data: string): Promise<string>;\n\tdecrypt(password: string, data: string): Promise<string>;\n}\n\n/**\n * Create the default encryption interface, which uses the browsers built-in crypto primitives.\n */\nexport function createDefaultEncryption(): Encryption {\n\ttype EncryptedJSON = {\n\t\tpayload: string;\n\t\tiv: string;\n\t\tsalt: string;\n\t};\n\n\tasync function keyFromPassword(password: string, salt: Uint8Array) {\n\t\tconst key = await crypto.subtle.importKey(\n\t\t\t'raw',\n\t\t\tnew TextEncoder().encode(password),\n\t\t\t{ name: 'PBKDF2' },\n\t\t\tfalse,\n\t\t\t['deriveBits', 'deriveKey'],\n\t\t);\n\n\t\tconst derivedKey = await crypto.subtle.deriveKey(\n\t\t\t{\n\t\t\t\tname: 'PBKDF2',\n\t\t\t\tsalt,\n\t\t\t\titerations: 900_000,\n\t\t\t\thash: 'SHA-256',\n\t\t\t},\n\t\t\tkey,\n\t\t\t{ name: 'AES-GCM', length: 256 },\n\t\t\tfalse,\n\t\t\t['encrypt', 'decrypt'],\n\t\t);\n\n\t\treturn { key, derivedKey };\n\t}\n\n\treturn {\n\t\tasync encrypt(password, data) {\n\t\t\tconst salt = crypto.getRandomValues(new Uint8Array(16));\n\t\t\tconst iv = crypto.getRandomValues(new Uint8Array(12));\n\n\t\t\tconst { derivedKey } = await keyFromPassword(password, salt);\n\n\t\t\tconst payload = await crypto.subtle.encrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv,\n\t\t\t\t},\n\t\t\t\tderivedKey,\n\t\t\t\tnew TextEncoder().encode(data),\n\t\t\t);\n\n\t\t\treturn JSON.stringify({\n\t\t\t\tpayload: toBase64(new Uint8Array(payload)),\n\t\t\t\tiv: toBase64(iv),\n\t\t\t\tsalt: toBase64(salt),\n\t\t\t} satisfies EncryptedJSON);\n\t\t},\n\t\tasync decrypt(password, data) {\n\t\t\tconst parsed = JSON.parse(data) as EncryptedJSON;\n\t\t\tif (!parsed.payload || !parsed.iv || !parsed.salt) {\n\t\t\t\tthrow new Error('Invalid encrypted data');\n\t\t\t}\n\n\t\t\tconst { derivedKey } = await keyFromPassword(password, fromBase64(parsed.salt));\n\n\t\t\tconst decryptedContent = await crypto.subtle.decrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv: fromBase64(parsed.iv),\n\t\t\t\t},\n\t\t\t\tderivedKey,\n\t\t\t\tfromBase64(parsed.payload),\n\t\t\t);\n\n\t\t\treturn new TextDecoder().decode(decryptedContent);\n\t\t},\n\t};\n}\n\n/**\n * Create a passthrough encryption interface, which does not encrypt or decrypt data.\n */\nexport function createPassthroughEncryption(): Encryption {\n\treturn {\n\t\tasync encrypt(_password, data) {\n\t\t\treturn data;\n\t\t},\n\t\tasync decrypt(_password, data) {\n\t\t\treturn data;\n\t\t},\n\t};\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAqC;AAa9B,SAAS,0BAAsC;AAOrD,iBAAe,gBAAgB,UAAkB,MAAkB;AAClE,UAAM,MAAM,MAAM,OAAO,OAAO;AAAA,MAC/B;AAAA,MACA,IAAI,YAAY,EAAE,OAAO,QAAQ;AAAA,MACjC,EAAE,MAAM,SAAS;AAAA,MACjB;AAAA,MACA,CAAC,cAAc,WAAW;AAAA,IAC3B;AAEA,UAAM,aAAa,MAAM,OAAO,OAAO;AAAA,MACtC;AAAA,QACC,MAAM;AAAA,QACN;AAAA,QACA,YAAY;AAAA,QACZ,MAAM;AAAA,MACP;AAAA,MACA;AAAA,MACA,EAAE,MAAM,WAAW,QAAQ,IAAI;AAAA,MAC/B;AAAA,MACA,CAAC,WAAW,SAAS;AAAA,IACtB;AAEA,WAAO,EAAE,KAAK,WAAW;AAAA,E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|
"names": []
|
|
7
7
|
}
|
package/dist/esm/EnokiFlow.js
CHANGED
|
@@ -9,7 +9,7 @@ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "acce
|
|
|
9
9
|
var _storageKeys, _enokiClient, _encryption, _encryptionKey, _store, _EnokiFlow_instances, setSession_fn;
|
|
10
10
|
import { decodeSuiPrivateKey } from "@mysten/sui/cryptography";
|
|
11
11
|
import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
|
|
12
|
-
import {
|
|
12
|
+
import { fromBase64, toBase64 } from "@mysten/sui/utils";
|
|
13
13
|
import { decodeJwt } from "jose";
|
|
14
14
|
import { atom, onMount, onSet } from "nanostores";
|
|
15
15
|
import { createDefaultEncryption } from "./encryption.js";
|
|
@@ -98,7 +98,7 @@ class EnokiFlow {
|
|
|
98
98
|
expiresAt: estimatedExpiration,
|
|
99
99
|
maxEpoch,
|
|
100
100
|
randomness,
|
|
101
|
-
ephemeralKeyPair:
|
|
101
|
+
ephemeralKeyPair: toBase64(decodeSuiPrivateKey(ephemeralKeyPair.getSecretKey()).secretKey)
|
|
102
102
|
});
|
|
103
103
|
return oauthUrl;
|
|
104
104
|
}
|
|
@@ -169,7 +169,7 @@ class EnokiFlow {
|
|
|
169
169
|
if (!salt || !zkp || !zkp.jwt) {
|
|
170
170
|
throw new Error("Missing required parameters for proof generation");
|
|
171
171
|
}
|
|
172
|
-
const ephemeralKeyPair = Ed25519Keypair.fromSecretKey(
|
|
172
|
+
const ephemeralKeyPair = Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair));
|
|
173
173
|
const proof = await __privateGet(this, _enokiClient).createZkLoginZkp({
|
|
174
174
|
network,
|
|
175
175
|
jwt: zkp.jwt,
|
|
@@ -197,7 +197,7 @@ class EnokiFlow {
|
|
|
197
197
|
address,
|
|
198
198
|
maxEpoch: zkp.maxEpoch,
|
|
199
199
|
proof: zkp.proof,
|
|
200
|
-
ephemeralKeypair: Ed25519Keypair.fromSecretKey(
|
|
200
|
+
ephemeralKeypair: Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair))
|
|
201
201
|
});
|
|
202
202
|
}
|
|
203
203
|
async sponsorTransaction({
|
|
@@ -216,7 +216,7 @@ class EnokiFlow {
|
|
|
216
216
|
return await __privateGet(this, _enokiClient).createSponsoredTransaction({
|
|
217
217
|
jwt: session.jwt,
|
|
218
218
|
network,
|
|
219
|
-
transactionKindBytes:
|
|
219
|
+
transactionKindBytes: toBase64(transactionKindBytes)
|
|
220
220
|
});
|
|
221
221
|
}
|
|
222
222
|
async executeTransaction({
|
|
@@ -226,7 +226,7 @@ class EnokiFlow {
|
|
|
226
226
|
client
|
|
227
227
|
}) {
|
|
228
228
|
const keypair = await this.getKeypair({ network });
|
|
229
|
-
const userSignature = await keypair.signTransaction(
|
|
229
|
+
const userSignature = await keypair.signTransaction(fromBase64(bytes));
|
|
230
230
|
await __privateGet(this, _enokiClient).executeSponsoredTransaction({
|
|
231
231
|
digest,
|
|
232
232
|
signature: userSignature.signature
|
|
@@ -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 { SuiClient } from '@mysten/sui/client';\nimport { decodeSuiPrivateKey } from '@mysten/sui/cryptography';\nimport { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport type { Transaction } from '@mysten/sui/transactions';\nimport { fromB64, toB64 } from '@mysten/sui/utils';\nimport type { ZkLoginSignatureInputs } from '@mysten/sui/zklogin';\nimport { decodeJwt } from 'jose';\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 { EnokiKeypair } from './EnokiKeypair.js';\nimport type { SyncStore } from './stores.js';\nimport { createSessionStorage } from './stores.js';\n\nexport interface EnokiFlowConfig extends EnokiClientConfig {\n\t/**\n\t * The storage interface to persist Enoki data locally.\n\t * If not provided, it will use a sessionStorage-backed store.\n\t */\n\tstore?: SyncStore;\n\t/**\n\t * The encryption interface that will be used to encrypt data before storing it locally.\n\t * If not provided, it will use a default encryption interface.\n\t */\n\tencryption?: Encryption;\n}\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}\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\nexport type AuthProvider = 'google' | 'facebook' | 'twitch';\n\nconst createStorageKeys = (apiKey: string) => ({\n\tSTATE: `@enoki/flow/state/${apiKey}`,\n\tSESSION: `@enoki/flow/session/${apiKey}`,\n});\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\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\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 = new Ed25519Keypair();\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\tawait this.#setSession({\n\t\t\texpiresAt: estimatedExpiration,\n\t\t\tmaxEpoch,\n\t\t\trandomness,\n\t\t\tephemeralKeyPair: toB64(decodeSuiPrivateKey(ephemeralKeyPair.getSecretKey()).secretKey),\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\tconst decodedJwt = decodeJwt(jwt);\n\t\tif (!decodedJwt.sub || !decodedJwt.aud || typeof decodedJwt.aud !== 'string') {\n\t\t\tthrow new Error('Missing JWT data');\n\t\t}\n\n\t\tconst { address, salt } = 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});\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 this.#setSession(null);\n\t}\n\n\t// TODO: Should this return the proof if it already exists?\n\tasync getProof({ network }: { network?: 'mainnet' | 'testnet' } = {}) {\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 ephemeralKeyPair = Ed25519Keypair.fromSecretKey(fromB64(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?: 'mainnet' | 'testnet' } = {}) {\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\treturn new EnokiKeypair({\n\t\t\taddress,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\tproof: zkp.proof,\n\t\t\tephemeralKeypair: Ed25519Keypair.fromSecretKey(fromB64(zkp.ephemeralKeyPair)),\n\t\t});\n\t}\n\n\tasync sponsorTransaction({\n\t\tnetwork,\n\t\ttransaction,\n\t\tclient,\n\t}: {\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\ttransaction: Transaction;\n\t\tclient: SuiClient;\n\t}) {\n\t\tconst session = await this.getSession();\n\n\t\tif (!session || !session.jwt) {\n\t\t\tthrow new Error('Missing required data for sponsorship.');\n\t\t}\n\n\t\tconst transactionKindBytes = await transaction.build({\n\t\t\tonlyTransactionKind: true,\n\t\t\tclient,\n\t\t});\n\n\t\treturn await this.#enokiClient.createSponsoredTransaction({\n\t\t\tjwt: session.jwt,\n\t\t\tnetwork,\n\t\t\ttransactionKindBytes: toB64(transactionKindBytes),\n\t\t});\n\t}\n\n\tasync executeTransaction({\n\t\tnetwork,\n\t\tbytes,\n\t\tdigest,\n\t\tclient,\n\t}: {\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\tbytes: string;\n\t\tdigest: string;\n\t\tclient: SuiClient;\n\t}) {\n\t\tconst keypair = await this.getKeypair({ network });\n\t\tconst userSignature = await keypair.signTransaction(fromB64(bytes));\n\n\t\tawait this.#enokiClient.executeSponsoredTransaction({\n\t\t\tdigest,\n\t\t\tsignature: userSignature.signature,\n\t\t});\n\n\t\t// TODO: Should the parent just do this?\n\t\tawait client.waitForTransaction({ digest });\n\n\t\treturn { digest };\n\t}\n\n\tasync sponsorAndExecuteTransaction({\n\t\tnetwork,\n\t\ttransaction,\n\t\tclient,\n\t}: {\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\ttransaction: Transaction;\n\t\tclient: SuiClient;\n\t}) {\n\t\tconst { bytes, digest } = await this.sponsorTransaction({\n\t\t\tnetwork,\n\t\t\ttransaction,\n\t\t\tclient,\n\t\t});\n\t\treturn await this.executeTransaction({ network, bytes, digest, client });\n\t}\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;AAAA;AAIA,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;AAE/B,SAAS,
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { SuiClient } from '@mysten/sui/client';\nimport { decodeSuiPrivateKey } from '@mysten/sui/cryptography';\nimport { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport type { Transaction } from '@mysten/sui/transactions';\nimport { fromBase64, toBase64 } from '@mysten/sui/utils';\nimport type { ZkLoginSignatureInputs } from '@mysten/sui/zklogin';\nimport { decodeJwt } from 'jose';\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 { EnokiKeypair } from './EnokiKeypair.js';\nimport type { SyncStore } from './stores.js';\nimport { createSessionStorage } from './stores.js';\n\nexport interface EnokiFlowConfig extends EnokiClientConfig {\n\t/**\n\t * The storage interface to persist Enoki data locally.\n\t * If not provided, it will use a sessionStorage-backed store.\n\t */\n\tstore?: SyncStore;\n\t/**\n\t * The encryption interface that will be used to encrypt data before storing it locally.\n\t * If not provided, it will use a default encryption interface.\n\t */\n\tencryption?: Encryption;\n}\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}\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\nexport type AuthProvider = 'google' | 'facebook' | 'twitch';\n\nconst createStorageKeys = (apiKey: string) => ({\n\tSTATE: `@enoki/flow/state/${apiKey}`,\n\tSESSION: `@enoki/flow/session/${apiKey}`,\n});\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\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\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 = new Ed25519Keypair();\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\tawait this.#setSession({\n\t\t\texpiresAt: estimatedExpiration,\n\t\t\tmaxEpoch,\n\t\t\trandomness,\n\t\t\tephemeralKeyPair: toBase64(decodeSuiPrivateKey(ephemeralKeyPair.getSecretKey()).secretKey),\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\tconst decodedJwt = decodeJwt(jwt);\n\t\tif (!decodedJwt.sub || !decodedJwt.aud || typeof decodedJwt.aud !== 'string') {\n\t\t\tthrow new Error('Missing JWT data');\n\t\t}\n\n\t\tconst { address, salt } = 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});\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 this.#setSession(null);\n\t}\n\n\t// TODO: Should this return the proof if it already exists?\n\tasync getProof({ network }: { network?: 'mainnet' | 'testnet' } = {}) {\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 ephemeralKeyPair = 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?: 'mainnet' | 'testnet' } = {}) {\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\treturn new EnokiKeypair({\n\t\t\taddress,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\tproof: zkp.proof,\n\t\t\tephemeralKeypair: Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair)),\n\t\t});\n\t}\n\n\tasync sponsorTransaction({\n\t\tnetwork,\n\t\ttransaction,\n\t\tclient,\n\t}: {\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\ttransaction: Transaction;\n\t\tclient: SuiClient;\n\t}) {\n\t\tconst session = await this.getSession();\n\n\t\tif (!session || !session.jwt) {\n\t\t\tthrow new Error('Missing required data for sponsorship.');\n\t\t}\n\n\t\tconst transactionKindBytes = await transaction.build({\n\t\t\tonlyTransactionKind: true,\n\t\t\tclient,\n\t\t});\n\n\t\treturn await this.#enokiClient.createSponsoredTransaction({\n\t\t\tjwt: session.jwt,\n\t\t\tnetwork,\n\t\t\ttransactionKindBytes: toBase64(transactionKindBytes),\n\t\t});\n\t}\n\n\tasync executeTransaction({\n\t\tnetwork,\n\t\tbytes,\n\t\tdigest,\n\t\tclient,\n\t}: {\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\tbytes: string;\n\t\tdigest: string;\n\t\tclient: SuiClient;\n\t}) {\n\t\tconst keypair = await this.getKeypair({ network });\n\t\tconst userSignature = await keypair.signTransaction(fromBase64(bytes));\n\n\t\tawait this.#enokiClient.executeSponsoredTransaction({\n\t\t\tdigest,\n\t\t\tsignature: userSignature.signature,\n\t\t});\n\n\t\t// TODO: Should the parent just do this?\n\t\tawait client.waitForTransaction({ digest });\n\n\t\treturn { digest };\n\t}\n\n\tasync sponsorAndExecuteTransaction({\n\t\tnetwork,\n\t\ttransaction,\n\t\tclient,\n\t}: {\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\ttransaction: Transaction;\n\t\tclient: SuiClient;\n\t}) {\n\t\tconst { bytes, digest } = await this.sponsorTransaction({\n\t\t\tnetwork,\n\t\t\ttransaction,\n\t\t\tclient,\n\t\t});\n\t\treturn await this.executeTransaction({ network, bytes, digest, client });\n\t}\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;AAAA;AAIA,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;A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,IACD,CAAC;AACD,WAAO,MAAM,KAAK,mBAAmB,EAAE,SAAS,OAAO,QAAQ,OAAO,CAAC;AAAA,EACxE;AACD;AArUC;AACA;AACA;AACA;AACA;AALM;AAsJA,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;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/esm/encryption.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { fromBase64, toBase64 } from "@mysten/sui/utils";
|
|
2
2
|
function createDefaultEncryption() {
|
|
3
3
|
async function keyFromPassword(password, salt) {
|
|
4
4
|
const key = await crypto.subtle.importKey(
|
|
@@ -36,9 +36,9 @@ function createDefaultEncryption() {
|
|
|
36
36
|
new TextEncoder().encode(data)
|
|
37
37
|
);
|
|
38
38
|
return JSON.stringify({
|
|
39
|
-
payload:
|
|
40
|
-
iv:
|
|
41
|
-
salt:
|
|
39
|
+
payload: toBase64(new Uint8Array(payload)),
|
|
40
|
+
iv: toBase64(iv),
|
|
41
|
+
salt: toBase64(salt)
|
|
42
42
|
});
|
|
43
43
|
},
|
|
44
44
|
async decrypt(password, data) {
|
|
@@ -46,14 +46,14 @@ function createDefaultEncryption() {
|
|
|
46
46
|
if (!parsed.payload || !parsed.iv || !parsed.salt) {
|
|
47
47
|
throw new Error("Invalid encrypted data");
|
|
48
48
|
}
|
|
49
|
-
const { derivedKey } = await keyFromPassword(password,
|
|
49
|
+
const { derivedKey } = await keyFromPassword(password, fromBase64(parsed.salt));
|
|
50
50
|
const decryptedContent = await crypto.subtle.decrypt(
|
|
51
51
|
{
|
|
52
52
|
name: "AES-GCM",
|
|
53
|
-
iv:
|
|
53
|
+
iv: fromBase64(parsed.iv)
|
|
54
54
|
},
|
|
55
55
|
derivedKey,
|
|
56
|
-
|
|
56
|
+
fromBase64(parsed.payload)
|
|
57
57
|
);
|
|
58
58
|
return new TextDecoder().decode(decryptedContent);
|
|
59
59
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/encryption.ts"],
|
|
4
|
-
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {
|
|
5
|
-
"mappings": "AAGA,SAAS,
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromBase64, toBase64 } from '@mysten/sui/utils';\n\n/**\n * An interface\n */\nexport interface Encryption {\n\tencrypt(password: string, data: string): Promise<string>;\n\tdecrypt(password: string, data: string): Promise<string>;\n}\n\n/**\n * Create the default encryption interface, which uses the browsers built-in crypto primitives.\n */\nexport function createDefaultEncryption(): Encryption {\n\ttype EncryptedJSON = {\n\t\tpayload: string;\n\t\tiv: string;\n\t\tsalt: string;\n\t};\n\n\tasync function keyFromPassword(password: string, salt: Uint8Array) {\n\t\tconst key = await crypto.subtle.importKey(\n\t\t\t'raw',\n\t\t\tnew TextEncoder().encode(password),\n\t\t\t{ name: 'PBKDF2' },\n\t\t\tfalse,\n\t\t\t['deriveBits', 'deriveKey'],\n\t\t);\n\n\t\tconst derivedKey = await crypto.subtle.deriveKey(\n\t\t\t{\n\t\t\t\tname: 'PBKDF2',\n\t\t\t\tsalt,\n\t\t\t\titerations: 900_000,\n\t\t\t\thash: 'SHA-256',\n\t\t\t},\n\t\t\tkey,\n\t\t\t{ name: 'AES-GCM', length: 256 },\n\t\t\tfalse,\n\t\t\t['encrypt', 'decrypt'],\n\t\t);\n\n\t\treturn { key, derivedKey };\n\t}\n\n\treturn {\n\t\tasync encrypt(password, data) {\n\t\t\tconst salt = crypto.getRandomValues(new Uint8Array(16));\n\t\t\tconst iv = crypto.getRandomValues(new Uint8Array(12));\n\n\t\t\tconst { derivedKey } = await keyFromPassword(password, salt);\n\n\t\t\tconst payload = await crypto.subtle.encrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv,\n\t\t\t\t},\n\t\t\t\tderivedKey,\n\t\t\t\tnew TextEncoder().encode(data),\n\t\t\t);\n\n\t\t\treturn JSON.stringify({\n\t\t\t\tpayload: toBase64(new Uint8Array(payload)),\n\t\t\t\tiv: toBase64(iv),\n\t\t\t\tsalt: toBase64(salt),\n\t\t\t} satisfies EncryptedJSON);\n\t\t},\n\t\tasync decrypt(password, data) {\n\t\t\tconst parsed = JSON.parse(data) as EncryptedJSON;\n\t\t\tif (!parsed.payload || !parsed.iv || !parsed.salt) {\n\t\t\t\tthrow new Error('Invalid encrypted data');\n\t\t\t}\n\n\t\t\tconst { derivedKey } = await keyFromPassword(password, fromBase64(parsed.salt));\n\n\t\t\tconst decryptedContent = await crypto.subtle.decrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv: fromBase64(parsed.iv),\n\t\t\t\t},\n\t\t\t\tderivedKey,\n\t\t\t\tfromBase64(parsed.payload),\n\t\t\t);\n\n\t\t\treturn new TextDecoder().decode(decryptedContent);\n\t\t},\n\t};\n}\n\n/**\n * Create a passthrough encryption interface, which does not encrypt or decrypt data.\n */\nexport function createPassthroughEncryption(): Encryption {\n\treturn {\n\t\tasync encrypt(_password, data) {\n\t\t\treturn data;\n\t\t},\n\t\tasync decrypt(_password, data) {\n\t\t\treturn data;\n\t\t},\n\t};\n}\n"],
|
|
5
|
+
"mappings": "AAGA,SAAS,YAAY,gBAAgB;AAa9B,SAAS,0BAAsC;AAOrD,iBA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