@mysten/enoki 0.0.2 → 0.0.4

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/src/EnokiFlow.ts DELETED
@@ -1,308 +0,0 @@
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
- }
@@ -1,98 +0,0 @@
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
- }
package/src/encryption.ts DELETED
@@ -1,105 +0,0 @@
1
- // Copyright (c) Mysten Labs, Inc.
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import { fromB64, toB64 } from '@mysten/sui.js/utils';
5
-
6
- /**
7
- * An interface
8
- */
9
- export interface Encryption {
10
- encrypt(password: string, data: string): Promise<string>;
11
- decrypt(password: string, data: string): Promise<string>;
12
- }
13
-
14
- /**
15
- * Create the default encryption interface, which uses the browsers built-in crypto primitives.
16
- */
17
- export function createDefaultEncryption(): Encryption {
18
- type EncryptedJSON = {
19
- payload: string;
20
- iv: string;
21
- salt: string;
22
- };
23
-
24
- async function keyFromPassword(password: string, salt: Uint8Array) {
25
- const key = await crypto.subtle.importKey(
26
- 'raw',
27
- new TextEncoder().encode(password),
28
- { name: 'PBKDF2' },
29
- false,
30
- ['deriveBits', 'deriveKey'],
31
- );
32
-
33
- const derivedKey = await crypto.subtle.deriveKey(
34
- {
35
- name: 'PBKDF2',
36
- salt,
37
- iterations: 900_000,
38
- hash: 'SHA-256',
39
- },
40
- key,
41
- { name: 'AES-GCM', length: 256 },
42
- false,
43
- ['encrypt', 'decrypt'],
44
- );
45
-
46
- return { key, derivedKey };
47
- }
48
-
49
- return {
50
- async encrypt(password, data) {
51
- const salt = crypto.getRandomValues(new Uint8Array(16));
52
- const iv = crypto.getRandomValues(new Uint8Array(12));
53
-
54
- const { derivedKey } = await keyFromPassword(password, salt);
55
-
56
- const payload = await crypto.subtle.encrypt(
57
- {
58
- name: 'AES-GCM',
59
- iv,
60
- },
61
- derivedKey,
62
- new TextEncoder().encode(data),
63
- );
64
-
65
- return JSON.stringify({
66
- payload: toB64(new Uint8Array(payload)),
67
- iv: toB64(iv),
68
- salt: toB64(salt),
69
- } satisfies EncryptedJSON);
70
- },
71
- async decrypt(password, data) {
72
- const parsed = JSON.parse(data) as EncryptedJSON;
73
- if (!parsed.payload || !parsed.iv || !parsed.salt) {
74
- throw new Error('Invalid encrypted data');
75
- }
76
-
77
- const { derivedKey } = await keyFromPassword(password, fromB64(parsed.salt));
78
-
79
- const decryptedContent = await crypto.subtle.decrypt(
80
- {
81
- name: 'AES-GCM',
82
- iv: fromB64(parsed.iv),
83
- },
84
- derivedKey,
85
- fromB64(parsed.payload),
86
- );
87
-
88
- return new TextDecoder().decode(decryptedContent);
89
- },
90
- };
91
- }
92
-
93
- /**
94
- * Create a passthrough encryption interface, which does not encrypt or decrypt data.
95
- */
96
- export function createPassthroughEncryption(): Encryption {
97
- return {
98
- async encrypt(_password, data) {
99
- return data;
100
- },
101
- async decrypt(_password, data) {
102
- return data;
103
- },
104
- };
105
- }
package/src/index.ts DELETED
@@ -1,13 +0,0 @@
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';
package/src/react.tsx DELETED
@@ -1,33 +0,0 @@
1
- // Copyright (c) Mysten Labs, Inc.
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import { useStore } from '@nanostores/react';
5
- import type { ReactNode } from 'react';
6
- import { createContext, useContext, useState } from 'react';
7
-
8
- import type { EnokiFlowConfig } from './EnokiFlow.js';
9
- import { EnokiFlow } from './EnokiFlow.js';
10
-
11
- const EnokiFlowContext = createContext<EnokiFlow | null>(null);
12
-
13
- export interface EnokiFlowProviderProps extends EnokiFlowConfig {
14
- children: ReactNode;
15
- }
16
-
17
- export function EnokiFlowProvider({ children, ...config }: EnokiFlowProviderProps) {
18
- const [enokiFlow] = useState(() => new EnokiFlow(config));
19
- return <EnokiFlowContext.Provider value={enokiFlow}>{children}</EnokiFlowContext.Provider>;
20
- }
21
-
22
- export function useEnokiFlow() {
23
- const context = useContext(EnokiFlowContext);
24
- if (!context) {
25
- throw new Error('Missing `EnokiFlowContext` provider');
26
- }
27
- return context;
28
- }
29
-
30
- export function useZkLogin() {
31
- const flow = useEnokiFlow();
32
- return useStore(flow.$zkLoginState);
33
- }
package/src/stores.ts DELETED
@@ -1,68 +0,0 @@
1
- // Copyright (c) Mysten Labs, Inc.
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- /**
5
- * An sync key-value store.
6
- */
7
- export interface SyncStore {
8
- get(key: string): string | null;
9
- set(key: string, value: string): void;
10
- delete(key: string): void;
11
- }
12
-
13
- function createWebStorage(storage: Storage): SyncStore {
14
- return {
15
- get(key: string) {
16
- return storage.getItem(key);
17
- },
18
- set(key: string, value: string) {
19
- storage.setItem(key, value);
20
- },
21
- delete(key: string) {
22
- storage.removeItem(key);
23
- },
24
- };
25
- }
26
-
27
- /**
28
- * Create a storage interface backed by memory.
29
- * This is generally useful for server-side rendering, and test environments.
30
- */
31
- export function createInMemoryStorage(): SyncStore {
32
- const store = new Map<string, string>();
33
- return {
34
- get(key) {
35
- return store.get(key) ?? null;
36
- },
37
- set(key, value) {
38
- store.set(key, value);
39
- },
40
- delete(key) {
41
- store.delete(key);
42
- },
43
- };
44
- }
45
-
46
- /**
47
- * Create a store backed by `localStorage`.
48
- */
49
- export function createLocalStorage(): SyncStore {
50
- if (typeof window === 'undefined') {
51
- console.warn('`window.localStorage` is not available, falling back to in-memory storage');
52
- return createInMemoryStorage();
53
- }
54
-
55
- return createWebStorage(window.localStorage);
56
- }
57
-
58
- /**
59
- * Create a store backed by `sessionStorage`.
60
- */
61
- export function createSessionStorage(): SyncStore {
62
- if (typeof window === 'undefined') {
63
- console.warn('`window.sessionStorage` is not available, falling back to in-memory storage');
64
- return createInMemoryStorage();
65
- }
66
-
67
- return createWebStorage(window.sessionStorage);
68
- }