@mysten/enoki 0.0.0-experimental-20231117210618

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 (65) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +201 -0
  3. package/README.md +1 -0
  4. package/dist/cjs/EnokiClient/index.d.ts +18 -0
  5. package/dist/cjs/EnokiClient/index.js +114 -0
  6. package/dist/cjs/EnokiClient/index.js.map +7 -0
  7. package/dist/cjs/EnokiClient/type.d.ts +36 -0
  8. package/dist/cjs/EnokiClient/type.js +17 -0
  9. package/dist/cjs/EnokiClient/type.js.map +7 -0
  10. package/dist/cjs/EnokiFlow.d.ts +50 -0
  11. package/dist/cjs/EnokiFlow.js +256 -0
  12. package/dist/cjs/EnokiFlow.js.map +7 -0
  13. package/dist/cjs/EnokiKeypair.d.ts +31 -0
  14. package/dist/cjs/EnokiKeypair.js +119 -0
  15. package/dist/cjs/EnokiKeypair.js.map +7 -0
  16. package/dist/cjs/encryption.d.ts +15 -0
  17. package/dist/cjs/encryption.js +47 -0
  18. package/dist/cjs/encryption.js.map +7 -0
  19. package/dist/cjs/index.d.ts +5 -0
  20. package/dist/cjs/index.js +36 -0
  21. package/dist/cjs/index.js.map +7 -0
  22. package/dist/cjs/package.json +4 -0
  23. package/dist/cjs/react.d.ts +9 -0
  24. package/dist/cjs/react.js +46 -0
  25. package/dist/cjs/react.js.map +7 -0
  26. package/dist/cjs/stores.d.ts +21 -0
  27. package/dist/cjs/stores.js +67 -0
  28. package/dist/cjs/stores.js.map +7 -0
  29. package/dist/esm/EnokiClient/index.d.ts +18 -0
  30. package/dist/esm/EnokiClient/index.js +94 -0
  31. package/dist/esm/EnokiClient/index.js.map +7 -0
  32. package/dist/esm/EnokiClient/type.d.ts +36 -0
  33. package/dist/esm/EnokiClient/type.js +1 -0
  34. package/dist/esm/EnokiClient/type.js.map +7 -0
  35. package/dist/esm/EnokiFlow.d.ts +50 -0
  36. package/dist/esm/EnokiFlow.js +236 -0
  37. package/dist/esm/EnokiFlow.js.map +7 -0
  38. package/dist/esm/EnokiKeypair.d.ts +31 -0
  39. package/dist/esm/EnokiKeypair.js +99 -0
  40. package/dist/esm/EnokiKeypair.js.map +7 -0
  41. package/dist/esm/encryption.d.ts +15 -0
  42. package/dist/esm/encryption.js +30 -0
  43. package/dist/esm/encryption.js.map +7 -0
  44. package/dist/esm/index.d.ts +5 -0
  45. package/dist/esm/index.js +20 -0
  46. package/dist/esm/index.js.map +7 -0
  47. package/dist/esm/package.json +4 -0
  48. package/dist/esm/react.d.ts +9 -0
  49. package/dist/esm/react.js +26 -0
  50. package/dist/esm/react.js.map +7 -0
  51. package/dist/esm/stores.d.ts +21 -0
  52. package/dist/esm/stores.js +47 -0
  53. package/dist/esm/stores.js.map +7 -0
  54. package/dist/tsconfig.esm.tsbuildinfo +1 -0
  55. package/dist/tsconfig.tsbuildinfo +1 -0
  56. package/package.json +73 -0
  57. package/react/package.json +5 -0
  58. package/src/EnokiClient/index.ts +97 -0
  59. package/src/EnokiClient/type.ts +42 -0
  60. package/src/EnokiFlow.ts +308 -0
  61. package/src/EnokiKeypair.ts +98 -0
  62. package/src/encryption.ts +44 -0
  63. package/src/index.ts +13 -0
  64. package/src/react.tsx +33 -0
  65. package/src/stores.ts +68 -0
package/package.json ADDED
@@ -0,0 +1,73 @@
1
+ {
2
+ "name": "@mysten/enoki",
3
+ "version": "0.0.0-experimental-20231117210618",
4
+ "description": "TODO: Description",
5
+ "license": "Apache-2.0",
6
+ "author": "Mysten Labs <build@mystenlabs.com>",
7
+ "type": "commonjs",
8
+ "main": "./dist/cjs/index.js",
9
+ "module": "./dist/esm/index.js",
10
+ "types": "./dist/cjs/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "import": "./dist/esm/index.js",
14
+ "require": "./dist/cjs/index.js"
15
+ },
16
+ "./react": {
17
+ "import": "./dist/esm/react.js",
18
+ "require": "./dist/cjs/react.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "CHANGELOG.md",
23
+ "dist",
24
+ "react",
25
+ "src"
26
+ ],
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/mystenlabs/sui.git"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/mystenlabs/sui/issues"
33
+ },
34
+ "homepage": "https://github.com/mystenlabs/sui#readme",
35
+ "devDependencies": {
36
+ "@types/node": "^20.4.2",
37
+ "@types/react": "^18.2.15",
38
+ "react": "^18.2.0",
39
+ "tsx": "^3.12.7",
40
+ "typescript": "^5.1.6",
41
+ "@mysten/build-scripts": "0.0.0"
42
+ },
43
+ "dependencies": {
44
+ "@metamask/browser-passworder": "^4.1.0",
45
+ "@nanostores/react": "^0.7.1",
46
+ "jose": "^4.14.4",
47
+ "nanostores": "^0.9.3",
48
+ "@mysten/sui.js": "0.0.0-experimental-20231117210618",
49
+ "@mysten/zklogin": "0.0.0-experimental-20231117210618"
50
+ },
51
+ "peerDependencies": {
52
+ "@types/react": ">=17.0.0",
53
+ "react": ">=17.0.0"
54
+ },
55
+ "peerDependenciesMeta": {
56
+ "react": {
57
+ "optional": true
58
+ },
59
+ "@types/react": {
60
+ "optional": true
61
+ }
62
+ },
63
+ "scripts": {
64
+ "clean": "rm -rf tsconfig.tsbuildinfo ./dist",
65
+ "build": "build-package",
66
+ "prettier:check": "prettier -c --ignore-unknown .",
67
+ "prettier:fix": "prettier -w --ignore-unknown .",
68
+ "eslint:check": "eslint --max-warnings=0 .",
69
+ "eslint:fix": "pnpm run eslint:check --fix",
70
+ "lint": "pnpm run eslint:check && pnpm run prettier:check",
71
+ "lint:fix": "pnpm run eslint:fix && pnpm run prettier:fix"
72
+ }
73
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "private": true,
3
+ "import": "../dist/esm/react.js",
4
+ "main": "../dist/cjs/react.js"
5
+ }
@@ -0,0 +1,97 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type {
5
+ CreateZkLoginNonceApiInput,
6
+ CreateZkLoginNonceApiResponse,
7
+ CreateZkLoginZkpApiInput,
8
+ CreateZkLoginZkpApiResponse,
9
+ GetAppApiInput,
10
+ GetAppApiResponse,
11
+ GetZkLoginApiInput,
12
+ GetZkLoginApiResponse,
13
+ } from './type.js';
14
+
15
+ const DEFAULT_API_URL = 'https://api.enoki.mystenlabs.com';
16
+ const ZKLOGIN_HEADER = 'zklogin-jwt';
17
+
18
+ export interface EnokiClientConfig {
19
+ /** The API key for the Enoki app, available in the Enoki Portal. */
20
+ apiKey: string;
21
+
22
+ /** The API URL for Enoki. In most cases, this should not be set. */
23
+ apiUrl?: string;
24
+ }
25
+
26
+ /**
27
+ * A low-level client for interacting with the Enoki API.
28
+ */
29
+ export class EnokiClient {
30
+ #version: string;
31
+ #apiUrl: string;
32
+ #apiKey: string;
33
+
34
+ constructor(config: EnokiClientConfig) {
35
+ this.#version = 'v1';
36
+ this.#apiUrl = config.apiUrl ?? DEFAULT_API_URL;
37
+ this.#apiKey = config.apiKey;
38
+ }
39
+
40
+ getApp(_input?: GetAppApiInput) {
41
+ return this.#fetch<GetAppApiResponse>('app', {
42
+ method: 'GET',
43
+ });
44
+ }
45
+
46
+ getZkLogin(input: GetZkLoginApiInput) {
47
+ return this.#fetch<GetZkLoginApiResponse>('zklogin', {
48
+ method: 'GET',
49
+ headers: {
50
+ [ZKLOGIN_HEADER]: input.jwt,
51
+ },
52
+ });
53
+ }
54
+
55
+ createZkLoginNonce(input: CreateZkLoginNonceApiInput) {
56
+ return this.#fetch<CreateZkLoginNonceApiResponse>('zklogin/nonce', {
57
+ method: 'POST',
58
+ body: JSON.stringify({
59
+ ephemeralPublicKey: input.ephemeralPublicKey.toSuiPublicKey(),
60
+ }),
61
+ });
62
+ }
63
+
64
+ createZkLoginZkp(input: CreateZkLoginZkpApiInput) {
65
+ return this.#fetch<CreateZkLoginZkpApiResponse>('zklogin/kzp', {
66
+ method: 'POST',
67
+ headers: {
68
+ [ZKLOGIN_HEADER]: input.jwt,
69
+ },
70
+ body: JSON.stringify({
71
+ ephemeralPublicKey: input.ephemeralPublicKey.toSuiPublicKey(),
72
+ maxEpoch: input.maxEpoch,
73
+ randomness: input.randomness,
74
+ }),
75
+ });
76
+ }
77
+
78
+ async #fetch<T = unknown>(path: string, init: RequestInit): Promise<T> {
79
+ const res = await fetch(`${this.#apiUrl}/${this.#version}/${path}`, {
80
+ ...init,
81
+ headers: {
82
+ ...init.headers,
83
+ Authorization: `Bearer ${this.#apiKey}`,
84
+ 'Content-Type': 'application/json',
85
+ 'Request-Id': crypto.randomUUID(),
86
+ },
87
+ });
88
+
89
+ if (!res.ok) {
90
+ throw new Error('Failed to fetch');
91
+ }
92
+
93
+ const { data } = await res.json();
94
+
95
+ return data as T;
96
+ }
97
+ }
@@ -0,0 +1,42 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { PublicKey } from '@mysten/sui.js/cryptography';
5
+ import type { ZkLoginSignatureInputs } from '@mysten/sui.js/zklogin';
6
+
7
+ import type { AuthProvider } from '../EnokiFlow.js';
8
+
9
+ export interface GetAppApiInput {}
10
+ export interface GetAppApiResponse {
11
+ authenticationProviders: {
12
+ providerType: AuthProvider;
13
+ clientId: string;
14
+ }[];
15
+ }
16
+
17
+ export interface GetZkLoginApiInput {
18
+ jwt: string;
19
+ }
20
+ export interface GetZkLoginApiResponse {
21
+ address: string;
22
+ salt: string;
23
+ }
24
+
25
+ export interface CreateZkLoginNonceApiInput {
26
+ ephemeralPublicKey: PublicKey;
27
+ }
28
+ export interface CreateZkLoginNonceApiResponse {
29
+ nonce: string;
30
+ randomness: string;
31
+ epoch: number;
32
+ maxEpoch: number;
33
+ estimatedExpiration: number;
34
+ }
35
+
36
+ export interface CreateZkLoginZkpApiInput {
37
+ jwt: string;
38
+ ephemeralPublicKey: PublicKey;
39
+ randomness: string;
40
+ maxEpoch: number;
41
+ }
42
+ export interface CreateZkLoginZkpApiResponse extends ZkLoginSignatureInputs {}
@@ -0,0 +1,308 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { Ed25519Keypair } from '@mysten/sui.js/keypairs/ed25519';
5
+ import { fromB64 } from '@mysten/sui.js/utils';
6
+ import type { ZkLoginSignatureInputs } from '@mysten/sui.js/zklogin';
7
+ import { decodeJwt } from 'jose';
8
+ import type { WritableAtom } from 'nanostores';
9
+ import { atom, onSet } from 'nanostores';
10
+
11
+ import type { Encryption } from './encryption.js';
12
+ import { createDefaultEncryption } from './encryption.js';
13
+ import type { EnokiClientConfig } from './EnokiClient/index.js';
14
+ import { EnokiClient } from './EnokiClient/index.js';
15
+ import { EnokiKeypair } from './EnokiKeypair.js';
16
+ import type { SyncStore } from './stores.js';
17
+ import { createSessionStorage } from './stores.js';
18
+
19
+ export interface EnokiFlowConfig extends EnokiClientConfig {
20
+ /**
21
+ * The storage interface to persist Enoki data locally.
22
+ * If not provided, it will use a sessionStorage-backed store.
23
+ */
24
+ store?: SyncStore;
25
+ /**
26
+ * The encryption interface that will be used to encrypt data before storing it locally.
27
+ * If not provided, it will use a default encryption interface.
28
+ */
29
+ encryption?: Encryption;
30
+ }
31
+
32
+ // State that is not bound to a session, and is encrypted.
33
+ export interface ZkLoginState {
34
+ provider?: AuthProvider;
35
+ address?: string;
36
+ salt?: string;
37
+ }
38
+
39
+ // State that session-bound, and is encrypted in storage.
40
+ export interface ZkLoginSession {
41
+ ephemeralKeyPair: string;
42
+ maxEpoch: number;
43
+ randomness: string;
44
+ expiresAt: number;
45
+
46
+ jwt?: string;
47
+ proof?: ZkLoginSignatureInputs;
48
+ }
49
+
50
+ export type AuthProvider = 'google' | 'facebook' | 'twitch';
51
+
52
+ const STORAGE_KEYS = {
53
+ STATE: '@enoki/flow/state',
54
+ SESSION: '@enoki/flow/session',
55
+ };
56
+
57
+ export class EnokiFlow {
58
+ #enokiClient: EnokiClient;
59
+ #encryption: Encryption;
60
+ #encryptionKey: string;
61
+ #store: SyncStore;
62
+
63
+ #zkLoginSessionInitialized: boolean;
64
+ #zkLoginSession: ZkLoginSession | null;
65
+
66
+ $zkLoginState: WritableAtom<ZkLoginState>;
67
+
68
+ constructor(config: EnokiFlowConfig) {
69
+ this.#enokiClient = new EnokiClient({
70
+ apiKey: config.apiKey,
71
+ apiUrl: config.apiUrl,
72
+ });
73
+ this.#encryptionKey = config.apiKey;
74
+ this.#encryption = config.encryption ?? createDefaultEncryption();
75
+ this.#store = config.store ?? createSessionStorage();
76
+
77
+ let storedState = null;
78
+ try {
79
+ const rawStoredValue = this.#store.get(STORAGE_KEYS.STATE);
80
+ if (rawStoredValue) {
81
+ storedState = JSON.parse(rawStoredValue);
82
+ }
83
+ } catch {
84
+ // Ignore errors
85
+ }
86
+
87
+ this.$zkLoginState = atom(storedState || {});
88
+
89
+ this.#zkLoginSessionInitialized = false;
90
+ this.#zkLoginSession = null;
91
+
92
+ onSet(this.$zkLoginState, ({ newValue }) => {
93
+ this.#store.set(STORAGE_KEYS.STATE, JSON.stringify(newValue));
94
+ });
95
+ }
96
+
97
+ get enokiClient() {
98
+ return this.#enokiClient;
99
+ }
100
+
101
+ async createAuthorizationURL(input: {
102
+ provider: AuthProvider;
103
+ clientId: string;
104
+ redirectUrl: string;
105
+ extraParams?: Record<string, unknown>;
106
+ }) {
107
+ const ephemeralKeyPair = new Ed25519Keypair();
108
+ const { nonce, randomness, maxEpoch, estimatedExpiration } =
109
+ await this.#enokiClient.createZkLoginNonce({
110
+ ephemeralPublicKey: ephemeralKeyPair.getPublicKey(),
111
+ });
112
+
113
+ const params = new URLSearchParams({
114
+ ...input.extraParams,
115
+ nonce,
116
+ client_id: input.clientId,
117
+ redirect_uri: input.redirectUrl,
118
+ response_type: 'id_token',
119
+ // TODO: Eventually fetch the scopes for this client ID from the Enoki service:
120
+ scope: [
121
+ 'openid',
122
+ // Merge the requested scopes in with the required openid scopes:
123
+ ...(input.extraParams && 'scope' in input.extraParams
124
+ ? (input.extraParams.scope as string[])
125
+ : []),
126
+ ]
127
+ .filter(Boolean)
128
+ .join(' '),
129
+ });
130
+
131
+ let oauthUrl: string;
132
+ switch (input.provider) {
133
+ case 'google': {
134
+ oauthUrl = `https://accounts.google.com/o/oauth2/v2/auth?${params}`;
135
+ break;
136
+ }
137
+
138
+ case 'facebook': {
139
+ oauthUrl = `https://www.facebook.com/v17.0/dialog/oauth?${params}`;
140
+ break;
141
+ }
142
+
143
+ case 'twitch': {
144
+ params.set('force_verify', 'true');
145
+ oauthUrl = `https://id.twitch.tv/oauth2/authorize?${params}`;
146
+ break;
147
+ }
148
+
149
+ default:
150
+ throw new Error(`Invalid provider: ${input.provider}`);
151
+ }
152
+
153
+ this.$zkLoginState.set({ provider: input.provider });
154
+ await this.#setSession({
155
+ expiresAt: estimatedExpiration,
156
+ maxEpoch,
157
+ randomness,
158
+ ephemeralKeyPair: ephemeralKeyPair.export().privateKey,
159
+ });
160
+
161
+ return oauthUrl;
162
+ }
163
+
164
+ // TODO: Should our SDK manage this automatically in addition to exposing a method?
165
+ async handleAuthCallback(hash: string = window.location.hash) {
166
+ const params = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash);
167
+
168
+ // Before we handle the auth redirect and get the state, we need to restore it:
169
+ const zkp = await this.getSession();
170
+
171
+ if (!zkp || !zkp.ephemeralKeyPair || !zkp.maxEpoch || !zkp.randomness) {
172
+ throw new Error(
173
+ 'Start of sign-in flow could not be found. Ensure you have started the sign-in flow before calling this.',
174
+ );
175
+ }
176
+
177
+ const jwt = params.get('id_token');
178
+ if (!jwt) {
179
+ throw new Error('Missing ID Token');
180
+ }
181
+
182
+ const decodedJwt = decodeJwt(jwt);
183
+ if (!decodedJwt.sub || !decodedJwt.aud || typeof decodedJwt.aud !== 'string') {
184
+ throw new Error('Missing JWT data');
185
+ }
186
+
187
+ const { address, salt } = await this.#enokiClient.getZkLogin({ jwt });
188
+
189
+ this.$zkLoginState.set({
190
+ ...this.$zkLoginState.get(),
191
+ salt,
192
+ address,
193
+ });
194
+ await this.#setSession({
195
+ ...zkp,
196
+ jwt,
197
+ });
198
+
199
+ return params.get('state');
200
+ }
201
+
202
+ async #setSession(newValue: ZkLoginSession | null) {
203
+ if (newValue) {
204
+ const storedValue = await this.#encryption.encrypt(
205
+ this.#encryptionKey,
206
+ JSON.stringify(newValue),
207
+ );
208
+
209
+ this.#store.set(STORAGE_KEYS.SESSION, storedValue);
210
+ } else {
211
+ this.#store.delete(STORAGE_KEYS.SESSION);
212
+ }
213
+
214
+ this.#zkLoginSession = newValue;
215
+ }
216
+
217
+ async getSession() {
218
+ if (this.#zkLoginSessionInitialized) {
219
+ return this.#zkLoginSession;
220
+ }
221
+
222
+ try {
223
+ const storedValue = this.#store.get(STORAGE_KEYS.SESSION);
224
+ if (!storedValue) return null;
225
+
226
+ const state: ZkLoginSession = JSON.parse(
227
+ await this.#encryption.decrypt(this.#encryptionKey, storedValue),
228
+ );
229
+
230
+ // TODO: Rather than having expiration act as a logout, we should keep the state that still is relevant,
231
+ // and just clear out the expired session, but keep the other zkLogin state.
232
+ if (state?.expiresAt && Date.now() > state.expiresAt) {
233
+ await this.logout();
234
+ } else {
235
+ this.#zkLoginSession = state;
236
+ }
237
+
238
+ return this.#zkLoginSession;
239
+ } finally {
240
+ this.#zkLoginSessionInitialized = true;
241
+ }
242
+ }
243
+
244
+ async logout() {
245
+ this.$zkLoginState.set({});
246
+ this.#store.delete(STORAGE_KEYS.STATE);
247
+
248
+ await this.#setSession(null);
249
+ }
250
+
251
+ // TODO: Should this return the proof if it already exists?
252
+ async getProof() {
253
+ const zkp = await this.getSession();
254
+ const { salt } = this.$zkLoginState.get();
255
+
256
+ if (zkp?.proof) {
257
+ if (zkp.expiresAt && Date.now() > zkp.expiresAt) {
258
+ throw new Error('Stored proof is expired.');
259
+ }
260
+
261
+ return zkp.proof;
262
+ }
263
+
264
+ if (!salt || !zkp || !zkp.jwt) {
265
+ throw new Error('Missing required parameters for proof generation');
266
+ }
267
+
268
+ const ephemeralKeyPair = Ed25519Keypair.fromSecretKey(fromB64(zkp.ephemeralKeyPair));
269
+
270
+ const proof = await this.#enokiClient.createZkLoginZkp({
271
+ jwt: zkp.jwt!,
272
+ maxEpoch: zkp.maxEpoch!,
273
+ randomness: zkp.randomness!,
274
+ ephemeralPublicKey: ephemeralKeyPair.getPublicKey(),
275
+ });
276
+
277
+ await this.#setSession({
278
+ ...zkp,
279
+ proof,
280
+ });
281
+
282
+ return proof;
283
+ }
284
+
285
+ async getKeypair() {
286
+ const zkp = await this.getSession();
287
+
288
+ // Get the proof, so that we ensure it exists in state:
289
+ await this.getProof();
290
+
291
+ // Check to see if we have the essentials for a keypair:
292
+ const { address } = this.$zkLoginState.get();
293
+ if (!address || !zkp || !zkp.proof) {
294
+ throw new Error('Missing required data for keypair generation.');
295
+ }
296
+
297
+ if (Date.now() > zkp.expiresAt) {
298
+ throw new Error('Stored proof is expired.');
299
+ }
300
+
301
+ return new EnokiKeypair({
302
+ address,
303
+ maxEpoch: zkp.maxEpoch,
304
+ proof: zkp.proof,
305
+ ephemeralKeypair: Ed25519Keypair.fromSecretKey(fromB64(zkp.ephemeralKeyPair)),
306
+ });
307
+ }
308
+ }
@@ -0,0 +1,98 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { SignatureWithBytes } from '@mysten/sui.js/cryptography';
5
+ import { Keypair, PublicKey, SIGNATURE_SCHEME_TO_FLAG } from '@mysten/sui.js/cryptography';
6
+ import type { Ed25519Keypair, Ed25519PublicKey } from '@mysten/sui.js/keypairs/ed25519';
7
+ import type { ZkLoginSignatureInputs } from '@mysten/sui.js/zklogin';
8
+ import { getZkLoginSignature } from '@mysten/zklogin';
9
+
10
+ export class EnokiPublicKey extends PublicKey {
11
+ #address: string;
12
+ #ephemeralPublicKey: Ed25519PublicKey;
13
+
14
+ constructor(input: { address: string; ephemeralPublicKey: Ed25519PublicKey }) {
15
+ super();
16
+ this.#address = input.address;
17
+ this.#ephemeralPublicKey = input.ephemeralPublicKey;
18
+ }
19
+
20
+ flag(): number {
21
+ return SIGNATURE_SCHEME_TO_FLAG['ZkLogin'];
22
+ }
23
+
24
+ toSuiAddress(): string {
25
+ return this.#address;
26
+ }
27
+
28
+ verify(): never {
29
+ throw new Error('Verification for EnokiPublicKey is not supported');
30
+ }
31
+
32
+ toRawBytes(): Uint8Array {
33
+ return this.#ephemeralPublicKey.toRawBytes();
34
+ }
35
+ }
36
+
37
+ export class EnokiKeypair extends Keypair {
38
+ #proof: ZkLoginSignatureInputs;
39
+ #maxEpoch: number;
40
+ #ephemeralKeypair: Ed25519Keypair;
41
+ #publicKey: EnokiPublicKey;
42
+
43
+ constructor(input: {
44
+ address: string;
45
+ maxEpoch: number;
46
+ proof: ZkLoginSignatureInputs;
47
+ ephemeralKeypair: Ed25519Keypair;
48
+ }) {
49
+ super();
50
+ this.#proof = input.proof;
51
+ this.#maxEpoch = input.maxEpoch;
52
+ this.#ephemeralKeypair = input.ephemeralKeypair;
53
+ this.#publicKey = new EnokiPublicKey({
54
+ address: input.address,
55
+ ephemeralPublicKey: input.ephemeralKeypair.getPublicKey(),
56
+ });
57
+ }
58
+
59
+ signData(data: Uint8Array) {
60
+ return this.#ephemeralKeypair.signData(data);
61
+ }
62
+
63
+ async sign(data: Uint8Array) {
64
+ return this.#ephemeralKeypair.sign(data);
65
+ }
66
+
67
+ signPersonalMessage(): never {
68
+ throw new Error('Signing personal messages is not supported');
69
+ }
70
+
71
+ async signTransactionBlock(bytes: Uint8Array): Promise<SignatureWithBytes> {
72
+ const { bytes: signedBytes, signature: userSignature } =
73
+ await this.#ephemeralKeypair.signTransactionBlock(bytes);
74
+
75
+ const zkSignature = getZkLoginSignature({
76
+ inputs: this.#proof,
77
+ maxEpoch: this.#maxEpoch,
78
+ userSignature,
79
+ });
80
+
81
+ return {
82
+ bytes: signedBytes,
83
+ signature: zkSignature,
84
+ };
85
+ }
86
+
87
+ getKeyScheme() {
88
+ return this.#ephemeralKeypair.getKeyScheme();
89
+ }
90
+
91
+ getPublicKey() {
92
+ return this.#publicKey;
93
+ }
94
+
95
+ export(): never {
96
+ throw new Error('EnokiKeypair does not support exporting');
97
+ }
98
+ }
@@ -0,0 +1,44 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import {
5
+ decrypt as metamaskDecrypt,
6
+ encrypt as metamaskEncrypt,
7
+ } from '@metamask/browser-passworder';
8
+
9
+ /**
10
+ * An interface
11
+ */
12
+ export interface Encryption {
13
+ encrypt(password: string, data: string): Promise<string>;
14
+ decrypt(password: string, data: string): Promise<string>;
15
+ }
16
+
17
+ /**
18
+ * Create the default encryption interface, which uses the browsers built-in crypto primitives.
19
+ */
20
+ export function createDefaultEncryption(): Encryption {
21
+ return {
22
+ async encrypt(password, data) {
23
+ return metamaskEncrypt(password, data);
24
+ },
25
+ async decrypt(password, data) {
26
+ const decrypted = await metamaskDecrypt(password, data);
27
+ return decrypted as string;
28
+ },
29
+ };
30
+ }
31
+
32
+ /**
33
+ * Create a passthrough encryption interface, which does not encrypt or decrypt data.
34
+ */
35
+ export function createPassthroughEncryption(): Encryption {
36
+ return {
37
+ async encrypt(_password, data) {
38
+ return data;
39
+ },
40
+ async decrypt(_password, data) {
41
+ return data;
42
+ },
43
+ };
44
+ }
package/src/index.ts ADDED
@@ -0,0 +1,13 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export { EnokiClient, type EnokiClientConfig } from './EnokiClient/index.js';
5
+ export { EnokiFlow, type AuthProvider, type EnokiFlowConfig } from './EnokiFlow.js';
6
+ export {
7
+ createLocalStorage,
8
+ createSessionStorage,
9
+ createInMemoryStorage,
10
+ type SyncStore,
11
+ } from './stores.js';
12
+ export { createDefaultEncryption, type Encryption } from './encryption.js';
13
+ export { EnokiKeypair, EnokiPublicKey } from './EnokiKeypair.js';