@phantom/embedded-provider-core 0.1.1 → 0.1.2
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/dist/index.d.mts +21 -8
- package/dist/index.d.ts +21 -8
- package/dist/index.js +62 -37
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +64 -39
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -5
package/dist/index.d.mts
CHANGED
|
@@ -1,14 +1,22 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { StamperWithKeyManagement } from '@phantom/sdk-types';
|
|
2
|
+
import { AddressType } from '@phantom/client';
|
|
3
|
+
import { NetworkId } from '@phantom/constants';
|
|
4
|
+
import { ParsedSignatureResult, ParsedTransactionResult } from '@phantom/parsers';
|
|
2
5
|
|
|
3
6
|
interface Keypair {
|
|
4
7
|
publicKey: string;
|
|
5
8
|
secretKey: string;
|
|
6
9
|
}
|
|
10
|
+
interface StamperInfo {
|
|
11
|
+
keyId: string;
|
|
12
|
+
publicKey: string;
|
|
13
|
+
}
|
|
7
14
|
interface Session {
|
|
8
15
|
sessionId: string;
|
|
9
16
|
walletId: string;
|
|
10
17
|
organizationId: string;
|
|
11
|
-
|
|
18
|
+
stamperInfo: StamperInfo;
|
|
19
|
+
keypair?: Keypair;
|
|
12
20
|
authProvider?: string;
|
|
13
21
|
userInfo?: Record<string, any>;
|
|
14
22
|
status: "pending" | "completed" | "failed";
|
|
@@ -67,9 +75,11 @@ interface AuthProvider {
|
|
|
67
75
|
}
|
|
68
76
|
|
|
69
77
|
interface PlatformAdapter {
|
|
78
|
+
name: string;
|
|
70
79
|
storage: EmbeddedStorage;
|
|
71
80
|
authProvider: AuthProvider;
|
|
72
81
|
urlParamsAccessor: URLParamsAccessor;
|
|
82
|
+
stamper: StamperWithKeyManagement;
|
|
73
83
|
}
|
|
74
84
|
interface DebugLogger {
|
|
75
85
|
info(category: string, message: string, data?: any): void;
|
|
@@ -91,12 +101,13 @@ interface SignMessageParams {
|
|
|
91
101
|
message: string;
|
|
92
102
|
networkId: NetworkId;
|
|
93
103
|
}
|
|
104
|
+
interface SignMessageResult extends ParsedSignatureResult {
|
|
105
|
+
}
|
|
94
106
|
interface SignAndSendTransactionParams {
|
|
95
107
|
transaction: any;
|
|
96
108
|
networkId: NetworkId;
|
|
97
109
|
}
|
|
98
|
-
interface SignedTransaction {
|
|
99
|
-
rawTransaction: string;
|
|
110
|
+
interface SignedTransaction extends ParsedTransactionResult {
|
|
100
111
|
}
|
|
101
112
|
interface AuthOptions {
|
|
102
113
|
provider?: "google" | "apple" | "jwt";
|
|
@@ -117,9 +128,11 @@ interface EmbeddedProviderConfig {
|
|
|
117
128
|
|
|
118
129
|
declare class EmbeddedProvider {
|
|
119
130
|
private config;
|
|
131
|
+
private platform;
|
|
120
132
|
private storage;
|
|
121
133
|
private authProvider;
|
|
122
134
|
private urlParamsAccessor;
|
|
135
|
+
private stamper;
|
|
123
136
|
private logger;
|
|
124
137
|
private client;
|
|
125
138
|
private walletId;
|
|
@@ -129,11 +142,11 @@ declare class EmbeddedProvider {
|
|
|
129
142
|
private getAndFilterWalletAddresses;
|
|
130
143
|
private validateAndCleanSession;
|
|
131
144
|
private validateAuthOptions;
|
|
132
|
-
private
|
|
145
|
+
private createOrganizationAndStamper;
|
|
133
146
|
connect(authOptions?: AuthOptions): Promise<ConnectResult>;
|
|
134
147
|
disconnect(): Promise<void>;
|
|
135
|
-
signMessage(params: SignMessageParams): Promise<
|
|
136
|
-
signAndSendTransaction(params: SignAndSendTransactionParams): Promise<
|
|
148
|
+
signMessage(params: SignMessageParams): Promise<ParsedSignatureResult>;
|
|
149
|
+
signAndSendTransaction(params: SignAndSendTransactionParams): Promise<ParsedTransactionResult>;
|
|
137
150
|
getAddresses(): WalletAddress[];
|
|
138
151
|
isConnected(): boolean;
|
|
139
152
|
private handleAuthFlow;
|
|
@@ -151,4 +164,4 @@ declare function generateSessionId(): string;
|
|
|
151
164
|
|
|
152
165
|
declare function retryWithBackoff<T>(operation: () => Promise<T>, operationName: string, logger: DebugLogger, maxRetries?: number, baseDelay?: number): Promise<T>;
|
|
153
166
|
|
|
154
|
-
export { AuthOptions, AuthProvider, AuthResult, ConnectResult, DebugLogger, EmbeddedProvider, EmbeddedProviderConfig, EmbeddedStorage, JWTAuth, JWTAuthOptions, Keypair, PhantomConnectOptions, PlatformAdapter, Session, SignAndSendTransactionParams, SignMessageParams, SignedTransaction, URLParamsAccessor, WalletAddress, generateSessionId, retryWithBackoff };
|
|
167
|
+
export { AuthOptions, AuthProvider, AuthResult, ConnectResult, DebugLogger, EmbeddedProvider, EmbeddedProviderConfig, EmbeddedStorage, JWTAuth, JWTAuthOptions, Keypair, PhantomConnectOptions, PlatformAdapter, Session, SignAndSendTransactionParams, SignMessageParams, SignMessageResult, SignedTransaction, StamperInfo, URLParamsAccessor, WalletAddress, generateSessionId, retryWithBackoff };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,14 +1,22 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { StamperWithKeyManagement } from '@phantom/sdk-types';
|
|
2
|
+
import { AddressType } from '@phantom/client';
|
|
3
|
+
import { NetworkId } from '@phantom/constants';
|
|
4
|
+
import { ParsedSignatureResult, ParsedTransactionResult } from '@phantom/parsers';
|
|
2
5
|
|
|
3
6
|
interface Keypair {
|
|
4
7
|
publicKey: string;
|
|
5
8
|
secretKey: string;
|
|
6
9
|
}
|
|
10
|
+
interface StamperInfo {
|
|
11
|
+
keyId: string;
|
|
12
|
+
publicKey: string;
|
|
13
|
+
}
|
|
7
14
|
interface Session {
|
|
8
15
|
sessionId: string;
|
|
9
16
|
walletId: string;
|
|
10
17
|
organizationId: string;
|
|
11
|
-
|
|
18
|
+
stamperInfo: StamperInfo;
|
|
19
|
+
keypair?: Keypair;
|
|
12
20
|
authProvider?: string;
|
|
13
21
|
userInfo?: Record<string, any>;
|
|
14
22
|
status: "pending" | "completed" | "failed";
|
|
@@ -67,9 +75,11 @@ interface AuthProvider {
|
|
|
67
75
|
}
|
|
68
76
|
|
|
69
77
|
interface PlatformAdapter {
|
|
78
|
+
name: string;
|
|
70
79
|
storage: EmbeddedStorage;
|
|
71
80
|
authProvider: AuthProvider;
|
|
72
81
|
urlParamsAccessor: URLParamsAccessor;
|
|
82
|
+
stamper: StamperWithKeyManagement;
|
|
73
83
|
}
|
|
74
84
|
interface DebugLogger {
|
|
75
85
|
info(category: string, message: string, data?: any): void;
|
|
@@ -91,12 +101,13 @@ interface SignMessageParams {
|
|
|
91
101
|
message: string;
|
|
92
102
|
networkId: NetworkId;
|
|
93
103
|
}
|
|
104
|
+
interface SignMessageResult extends ParsedSignatureResult {
|
|
105
|
+
}
|
|
94
106
|
interface SignAndSendTransactionParams {
|
|
95
107
|
transaction: any;
|
|
96
108
|
networkId: NetworkId;
|
|
97
109
|
}
|
|
98
|
-
interface SignedTransaction {
|
|
99
|
-
rawTransaction: string;
|
|
110
|
+
interface SignedTransaction extends ParsedTransactionResult {
|
|
100
111
|
}
|
|
101
112
|
interface AuthOptions {
|
|
102
113
|
provider?: "google" | "apple" | "jwt";
|
|
@@ -117,9 +128,11 @@ interface EmbeddedProviderConfig {
|
|
|
117
128
|
|
|
118
129
|
declare class EmbeddedProvider {
|
|
119
130
|
private config;
|
|
131
|
+
private platform;
|
|
120
132
|
private storage;
|
|
121
133
|
private authProvider;
|
|
122
134
|
private urlParamsAccessor;
|
|
135
|
+
private stamper;
|
|
123
136
|
private logger;
|
|
124
137
|
private client;
|
|
125
138
|
private walletId;
|
|
@@ -129,11 +142,11 @@ declare class EmbeddedProvider {
|
|
|
129
142
|
private getAndFilterWalletAddresses;
|
|
130
143
|
private validateAndCleanSession;
|
|
131
144
|
private validateAuthOptions;
|
|
132
|
-
private
|
|
145
|
+
private createOrganizationAndStamper;
|
|
133
146
|
connect(authOptions?: AuthOptions): Promise<ConnectResult>;
|
|
134
147
|
disconnect(): Promise<void>;
|
|
135
|
-
signMessage(params: SignMessageParams): Promise<
|
|
136
|
-
signAndSendTransaction(params: SignAndSendTransactionParams): Promise<
|
|
148
|
+
signMessage(params: SignMessageParams): Promise<ParsedSignatureResult>;
|
|
149
|
+
signAndSendTransaction(params: SignAndSendTransactionParams): Promise<ParsedTransactionResult>;
|
|
137
150
|
getAddresses(): WalletAddress[];
|
|
138
151
|
isConnected(): boolean;
|
|
139
152
|
private handleAuthFlow;
|
|
@@ -151,4 +164,4 @@ declare function generateSessionId(): string;
|
|
|
151
164
|
|
|
152
165
|
declare function retryWithBackoff<T>(operation: () => Promise<T>, operationName: string, logger: DebugLogger, maxRetries?: number, baseDelay?: number): Promise<T>;
|
|
153
166
|
|
|
154
|
-
export { AuthOptions, AuthProvider, AuthResult, ConnectResult, DebugLogger, EmbeddedProvider, EmbeddedProviderConfig, EmbeddedStorage, JWTAuth, JWTAuthOptions, Keypair, PhantomConnectOptions, PlatformAdapter, Session, SignAndSendTransactionParams, SignMessageParams, SignedTransaction, URLParamsAccessor, WalletAddress, generateSessionId, retryWithBackoff };
|
|
167
|
+
export { AuthOptions, AuthProvider, AuthResult, ConnectResult, DebugLogger, EmbeddedProvider, EmbeddedProviderConfig, EmbeddedStorage, JWTAuth, JWTAuthOptions, Keypair, PhantomConnectOptions, PlatformAdapter, Session, SignAndSendTransactionParams, SignMessageParams, SignMessageResult, SignedTransaction, StamperInfo, URLParamsAccessor, WalletAddress, generateSessionId, retryWithBackoff };
|
package/dist/index.js
CHANGED
|
@@ -29,7 +29,6 @@ module.exports = __toCommonJS(src_exports);
|
|
|
29
29
|
|
|
30
30
|
// src/embedded-provider.ts
|
|
31
31
|
var import_client = require("@phantom/client");
|
|
32
|
-
var import_api_key_stamper = require("@phantom/api-key-stamper");
|
|
33
32
|
var import_parsers = require("@phantom/parsers");
|
|
34
33
|
|
|
35
34
|
// src/auth/jwt-auth.ts
|
|
@@ -157,9 +156,11 @@ var EmbeddedProvider = class {
|
|
|
157
156
|
this.logger = logger;
|
|
158
157
|
this.logger.log("EMBEDDED_PROVIDER", "Initializing EmbeddedProvider", { config });
|
|
159
158
|
this.config = config;
|
|
159
|
+
this.platform = platform;
|
|
160
160
|
this.storage = platform.storage;
|
|
161
161
|
this.authProvider = platform.authProvider;
|
|
162
162
|
this.urlParamsAccessor = platform.urlParamsAccessor;
|
|
163
|
+
this.stamper = platform.stamper;
|
|
163
164
|
this.jwtAuth = new JWTAuth();
|
|
164
165
|
config.solanaProvider;
|
|
165
166
|
this.logger.info("EMBEDDED_PROVIDER", "EmbeddedProvider initialized");
|
|
@@ -233,29 +234,33 @@ var EmbeddedProvider = class {
|
|
|
233
234
|
}
|
|
234
235
|
}
|
|
235
236
|
/*
|
|
236
|
-
* We use this method to
|
|
237
|
+
* We use this method to initialize the stamper and create an organization for new sessions.
|
|
237
238
|
* This is the first step when no existing session is found and we need to set up a new wallet.
|
|
238
239
|
*/
|
|
239
|
-
async
|
|
240
|
-
this.logger.log("EMBEDDED_PROVIDER", "
|
|
241
|
-
const
|
|
242
|
-
this.logger.log("EMBEDDED_PROVIDER", "
|
|
240
|
+
async createOrganizationAndStamper() {
|
|
241
|
+
this.logger.log("EMBEDDED_PROVIDER", "Initializing stamper");
|
|
242
|
+
const stamperInfo = await this.stamper.init();
|
|
243
|
+
this.logger.log("EMBEDDED_PROVIDER", "Stamper initialized", { publicKey: stamperInfo.publicKey, keyId: stamperInfo.keyId, algorithm: this.stamper.algorithm });
|
|
243
244
|
this.logger.log("EMBEDDED_PROVIDER", "Creating temporary PhantomClient");
|
|
244
|
-
const stamper = new import_api_key_stamper.ApiKeyStamper({
|
|
245
|
-
apiSecretKey: keypair.secretKey
|
|
246
|
-
});
|
|
247
245
|
const tempClient = new import_client.PhantomClient(
|
|
248
246
|
{
|
|
249
247
|
apiBaseUrl: this.config.apiBaseUrl
|
|
250
248
|
},
|
|
251
|
-
stamper
|
|
249
|
+
this.stamper
|
|
252
250
|
);
|
|
253
251
|
const uid = Date.now();
|
|
254
252
|
const organizationName = `${this.config.organizationId}-${uid}`;
|
|
255
|
-
this.
|
|
256
|
-
const
|
|
257
|
-
|
|
258
|
-
|
|
253
|
+
const platformName = this.platform.name || "unknown";
|
|
254
|
+
const shortPubKey = stamperInfo.publicKey.slice(0, 8);
|
|
255
|
+
const authenticatorName = `${platformName}-${shortPubKey}-${uid}`;
|
|
256
|
+
this.logger.log("EMBEDDED_PROVIDER", "Creating organization", {
|
|
257
|
+
organizationName,
|
|
258
|
+
authenticatorName,
|
|
259
|
+
platform: platformName
|
|
260
|
+
});
|
|
261
|
+
const { organizationId } = await tempClient.createOrganization(organizationName, stamperInfo.publicKey, authenticatorName);
|
|
262
|
+
this.logger.info("EMBEDDED_PROVIDER", "Organization created", { organizationId, authenticatorName });
|
|
263
|
+
return { organizationId, stamperInfo };
|
|
259
264
|
}
|
|
260
265
|
async connect(authOptions) {
|
|
261
266
|
try {
|
|
@@ -282,8 +287,8 @@ var EmbeddedProvider = class {
|
|
|
282
287
|
this.validateAuthOptions(authOptions);
|
|
283
288
|
if (!session) {
|
|
284
289
|
this.logger.info("EMBEDDED_PROVIDER", "No existing session, creating new one");
|
|
285
|
-
const { organizationId,
|
|
286
|
-
session = await this.handleAuthFlow(organizationId,
|
|
290
|
+
const { organizationId, stamperInfo } = await this.createOrganizationAndStamper();
|
|
291
|
+
session = await this.handleAuthFlow(organizationId, stamperInfo, authOptions);
|
|
287
292
|
}
|
|
288
293
|
if (!session) {
|
|
289
294
|
return {
|
|
@@ -345,22 +350,24 @@ var EmbeddedProvider = class {
|
|
|
345
350
|
throw new Error("Not connected");
|
|
346
351
|
}
|
|
347
352
|
const parsedMessage = (0, import_parsers.parseMessage)(params.message);
|
|
348
|
-
|
|
353
|
+
const rawResponse = await this.client.signMessage({
|
|
349
354
|
walletId: this.walletId,
|
|
350
355
|
message: parsedMessage.base64url,
|
|
351
356
|
networkId: params.networkId
|
|
352
357
|
});
|
|
358
|
+
return (0, import_parsers.parseSignMessageResponse)(rawResponse, params.networkId);
|
|
353
359
|
}
|
|
354
360
|
async signAndSendTransaction(params) {
|
|
355
361
|
if (!this.client || !this.walletId) {
|
|
356
362
|
throw new Error("Not connected");
|
|
357
363
|
}
|
|
358
364
|
const parsedTransaction = await (0, import_parsers.parseTransaction)(params.transaction, params.networkId);
|
|
359
|
-
|
|
365
|
+
const rawResponse = await this.client.signAndSendTransaction({
|
|
360
366
|
walletId: this.walletId,
|
|
361
367
|
transaction: parsedTransaction.base64url,
|
|
362
368
|
networkId: params.networkId
|
|
363
369
|
});
|
|
370
|
+
return await (0, import_parsers.parseTransactionResponse)(rawResponse.rawTransaction, params.networkId, rawResponse.hash);
|
|
364
371
|
}
|
|
365
372
|
getAddresses() {
|
|
366
373
|
return this.addresses;
|
|
@@ -373,23 +380,28 @@ var EmbeddedProvider = class {
|
|
|
373
380
|
* It handles app-wallet creation directly or routes to JWT/redirect authentication for user-wallets.
|
|
374
381
|
* Returns null for redirect flows since they don't complete synchronously.
|
|
375
382
|
*/
|
|
376
|
-
async handleAuthFlow(organizationId,
|
|
383
|
+
async handleAuthFlow(organizationId, stamperInfo, authOptions) {
|
|
377
384
|
if (this.config.embeddedWalletType === "user-wallet") {
|
|
378
385
|
this.logger.info("EMBEDDED_PROVIDER", "Creating user-wallet, routing authentication", {
|
|
379
386
|
authProvider: authOptions?.provider || "phantom-connect"
|
|
380
387
|
});
|
|
381
388
|
if (authOptions?.provider === "jwt") {
|
|
382
|
-
return await this.handleJWTAuth(organizationId,
|
|
389
|
+
return await this.handleJWTAuth(organizationId, stamperInfo, authOptions);
|
|
383
390
|
} else {
|
|
384
|
-
|
|
385
|
-
|
|
391
|
+
this.logger.info("EMBEDDED_PROVIDER", "Starting redirect-based authentication flow", {
|
|
392
|
+
organizationId,
|
|
393
|
+
parentOrganizationId: this.config.organizationId,
|
|
394
|
+
provider: authOptions?.provider
|
|
395
|
+
});
|
|
396
|
+
return await this.handleRedirectAuth(organizationId, stamperInfo, authOptions);
|
|
386
397
|
}
|
|
387
398
|
} else {
|
|
388
399
|
const tempClient = new import_client.PhantomClient(
|
|
389
400
|
{
|
|
390
|
-
apiBaseUrl: this.config.apiBaseUrl
|
|
401
|
+
apiBaseUrl: this.config.apiBaseUrl,
|
|
402
|
+
organizationId
|
|
391
403
|
},
|
|
392
|
-
|
|
404
|
+
this.stamper
|
|
393
405
|
);
|
|
394
406
|
const wallet = await tempClient.createWallet(`Wallet ${Date.now()}`);
|
|
395
407
|
const walletId = wallet.walletId;
|
|
@@ -397,8 +409,8 @@ var EmbeddedProvider = class {
|
|
|
397
409
|
const session = {
|
|
398
410
|
sessionId: generateSessionId(),
|
|
399
411
|
walletId,
|
|
400
|
-
organizationId
|
|
401
|
-
|
|
412
|
+
organizationId,
|
|
413
|
+
stamperInfo,
|
|
402
414
|
authProvider: "app-wallet",
|
|
403
415
|
userInfo: { embeddedWalletType: this.config.embeddedWalletType },
|
|
404
416
|
status: "completed",
|
|
@@ -413,7 +425,7 @@ var EmbeddedProvider = class {
|
|
|
413
425
|
* We use this method to handle JWT-based authentication for user-wallets.
|
|
414
426
|
* It authenticates using the provided JWT token and creates a completed session.
|
|
415
427
|
*/
|
|
416
|
-
async handleJWTAuth(organizationId,
|
|
428
|
+
async handleJWTAuth(organizationId, stamperInfo, authOptions) {
|
|
417
429
|
this.logger.info("EMBEDDED_PROVIDER", "Using JWT authentication flow");
|
|
418
430
|
if (!authOptions.jwtToken) {
|
|
419
431
|
this.logger.error("EMBEDDED_PROVIDER", "JWT token missing for JWT authentication");
|
|
@@ -432,8 +444,8 @@ var EmbeddedProvider = class {
|
|
|
432
444
|
const session = {
|
|
433
445
|
sessionId: generateSessionId(),
|
|
434
446
|
walletId,
|
|
435
|
-
organizationId
|
|
436
|
-
|
|
447
|
+
organizationId,
|
|
448
|
+
stamperInfo,
|
|
437
449
|
authProvider: authResult.provider,
|
|
438
450
|
userInfo: authResult.userInfo,
|
|
439
451
|
status: "completed",
|
|
@@ -449,7 +461,7 @@ var EmbeddedProvider = class {
|
|
|
449
461
|
* It saves a temporary session before redirecting to prevent losing state during the redirect flow.
|
|
450
462
|
* Session timestamp is updated before redirect to prevent race conditions.
|
|
451
463
|
*/
|
|
452
|
-
async handleRedirectAuth(organizationId,
|
|
464
|
+
async handleRedirectAuth(organizationId, stamperInfo, authOptions) {
|
|
453
465
|
this.logger.info("EMBEDDED_PROVIDER", "Using Phantom Connect authentication flow (redirect-based)", {
|
|
454
466
|
provider: authOptions?.provider,
|
|
455
467
|
hasRedirectUrl: !!this.config.authOptions?.redirectUrl,
|
|
@@ -462,7 +474,7 @@ var EmbeddedProvider = class {
|
|
|
462
474
|
walletId: `temp-${now}`,
|
|
463
475
|
// Temporary ID, will be updated after redirect
|
|
464
476
|
organizationId,
|
|
465
|
-
|
|
477
|
+
stamperInfo,
|
|
466
478
|
authProvider: "phantom-connect",
|
|
467
479
|
userInfo: { provider: authOptions?.provider },
|
|
468
480
|
status: "pending",
|
|
@@ -481,7 +493,7 @@ var EmbeddedProvider = class {
|
|
|
481
493
|
provider: authOptions?.provider,
|
|
482
494
|
authUrl: this.config.authOptions?.authUrl
|
|
483
495
|
});
|
|
484
|
-
await this.authProvider.authenticate({
|
|
496
|
+
const authResult = await this.authProvider.authenticate({
|
|
485
497
|
organizationId,
|
|
486
498
|
parentOrganizationId: this.config.organizationId,
|
|
487
499
|
provider: authOptions?.provider,
|
|
@@ -490,6 +502,20 @@ var EmbeddedProvider = class {
|
|
|
490
502
|
authUrl: this.config.authOptions?.authUrl,
|
|
491
503
|
sessionId
|
|
492
504
|
});
|
|
505
|
+
if (authResult && "walletId" in authResult) {
|
|
506
|
+
this.logger.info("EMBEDDED_PROVIDER", "Authentication completed after redirect", {
|
|
507
|
+
walletId: authResult.walletId,
|
|
508
|
+
provider: authResult.provider
|
|
509
|
+
});
|
|
510
|
+
tempSession.walletId = authResult.walletId;
|
|
511
|
+
tempSession.authProvider = authResult.provider || tempSession.authProvider;
|
|
512
|
+
tempSession.status = "completed";
|
|
513
|
+
tempSession.lastUsed = Date.now();
|
|
514
|
+
await this.storage.saveSession(tempSession);
|
|
515
|
+
return tempSession;
|
|
516
|
+
}
|
|
517
|
+
this.logger.info("EMBEDDED_PROVIDER", "Redirect authentication initiated, waiting for redirect completion");
|
|
518
|
+
return null;
|
|
493
519
|
}
|
|
494
520
|
async completeAuthConnection(authResult) {
|
|
495
521
|
const session = await this.storage.getSession();
|
|
@@ -498,7 +524,6 @@ var EmbeddedProvider = class {
|
|
|
498
524
|
}
|
|
499
525
|
session.walletId = authResult.walletId;
|
|
500
526
|
session.authProvider = authResult.provider || session.authProvider;
|
|
501
|
-
session.userInfo = { ...session.userInfo, ...authResult.userInfo };
|
|
502
527
|
session.status = "completed";
|
|
503
528
|
session.lastUsed = Date.now();
|
|
504
529
|
await this.storage.saveSession(session);
|
|
@@ -518,15 +543,15 @@ var EmbeddedProvider = class {
|
|
|
518
543
|
organizationId: session.organizationId,
|
|
519
544
|
walletId: session.walletId
|
|
520
545
|
});
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
}
|
|
546
|
+
if (!this.stamper.getKeyInfo()) {
|
|
547
|
+
await this.stamper.init();
|
|
548
|
+
}
|
|
524
549
|
this.client = new import_client.PhantomClient(
|
|
525
550
|
{
|
|
526
551
|
apiBaseUrl: this.config.apiBaseUrl,
|
|
527
552
|
organizationId: session.organizationId
|
|
528
553
|
},
|
|
529
|
-
stamper
|
|
554
|
+
this.stamper
|
|
530
555
|
);
|
|
531
556
|
this.walletId = session.walletId;
|
|
532
557
|
this.addresses = await this.getAndFilterWalletAddresses(session.walletId);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/embedded-provider.ts","../src/auth/jwt-auth.ts","../src/utils/session.ts","../src/utils/retry.ts"],"sourcesContent":["export * from \"./interfaces\";\nexport * from \"./types\";\nexport * from \"./embedded-provider\";\nexport * from \"./auth/jwt-auth\";\nexport * from \"./utils/session\";\nexport * from \"./utils/retry\";\n","import { PhantomClient, generateKeyPair } from \"@phantom/client\";\nimport type { AddressType } from \"@phantom/client\";\nimport { ApiKeyStamper } from \"@phantom/api-key-stamper\";\nimport { parseMessage, parseTransaction } from \"@phantom/parsers\";\n\nimport type {\n PlatformAdapter,\n Session,\n AuthResult,\n DebugLogger,\n EmbeddedStorage,\n AuthProvider,\n URLParamsAccessor,\n} from \"./interfaces\";\nimport type {\n EmbeddedProviderConfig,\n ConnectResult,\n SignMessageParams,\n SignAndSendTransactionParams,\n SignedTransaction,\n WalletAddress,\n AuthOptions,\n} from \"./types\";\nimport { JWTAuth } from \"./auth/jwt-auth\";\nimport { generateSessionId } from \"./utils/session\";\nimport { retryWithBackoff } from \"./utils/retry\";\n\nexport class EmbeddedProvider {\n private config: EmbeddedProviderConfig;\n private storage: EmbeddedStorage;\n private authProvider: AuthProvider;\n private urlParamsAccessor: URLParamsAccessor;\n private logger: DebugLogger;\n private client: PhantomClient | null = null;\n private walletId: string | null = null;\n private addresses: WalletAddress[] = [];\n private jwtAuth: JWTAuth;\n\n constructor(config: EmbeddedProviderConfig, platform: PlatformAdapter, logger: DebugLogger) {\n this.logger = logger;\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Initializing EmbeddedProvider\", { config });\n\n this.config = config;\n this.storage = platform.storage;\n this.authProvider = platform.authProvider;\n this.urlParamsAccessor = platform.urlParamsAccessor;\n this.jwtAuth = new JWTAuth();\n\n // Store solana provider config (unused for now)\n config.solanaProvider;\n this.logger.info(\"EMBEDDED_PROVIDER\", \"EmbeddedProvider initialized\");\n }\n\n private async getAndFilterWalletAddresses(walletId: string): Promise<WalletAddress[]> {\n // Get wallet addresses with retry and auto-disconnect on failure\n const addresses = await retryWithBackoff(\n () => this.client!.getWalletAddresses(walletId),\n \"getWalletAddresses\",\n this.logger,\n ).catch(async error => {\n this.logger.error(\"EMBEDDED_PROVIDER\", \"getWalletAddresses failed after retries, disconnecting\", {\n walletId,\n error: error.message,\n });\n // Clear the session if getWalletAddresses fails after retries\n await this.storage.clearSession();\n this.client = null;\n this.walletId = null;\n this.addresses = [];\n throw error;\n });\n\n // Filter by enabled address types and return formatted addresses\n return addresses\n .filter(addr => this.config.addressTypes.some(type => type === addr.addressType))\n .map(addr => ({\n addressType: addr.addressType as AddressType,\n address: addr.address,\n }));\n }\n\n /*\n * We use this method to make sure the session is not invalid, or there's a different session id in the url.\n * If there's a different one, we delete the current session and start from scratch.\n * This prevents issues where users have stale sessions or URL mismatches after redirects.\n */\n private async validateAndCleanSession(session: Session | null): Promise<Session | null> {\n if (!session) return null;\n\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Found existing session, validating\", {\n sessionId: session.sessionId,\n status: session.status,\n walletId: session.walletId,\n });\n\n // If session is not completed, check if we're in the right context\n if (session.status !== \"completed\") {\n const urlSessionId = this.urlParamsAccessor.getParam(\"session_id\");\n\n // If we have a pending session but no sessionId in URL, this is a mismatch\n if (session.status === \"pending\" && !urlSessionId) {\n this.logger.warn(\"EMBEDDED_PROVIDER\", \"Session mismatch detected - pending session without redirect context\", {\n sessionId: session.sessionId,\n status: session.status,\n });\n // Clear the invalid session and start fresh\n await this.storage.clearSession();\n return null;\n }\n // If sessionId in URL doesn't match stored session, clear invalid session\n else if (urlSessionId && urlSessionId !== session.sessionId) {\n this.logger.warn(\"EMBEDDED_PROVIDER\", \"Session ID mismatch detected\", {\n storedSessionId: session.sessionId,\n urlSessionId: urlSessionId,\n });\n await this.storage.clearSession();\n return null;\n }\n }\n\n return session;\n }\n\n /*\n * We use this method to validate authentication options before processing them.\n * This ensures only supported auth providers are used and required tokens are present.\n */\n private validateAuthOptions(authOptions?: AuthOptions): void {\n if (!authOptions) return;\n\n if (authOptions.provider && ![\"google\", \"apple\", \"jwt\"].includes(authOptions.provider)) {\n throw new Error(`Invalid auth provider: ${authOptions.provider}. Must be \"google\", \"apple\", or \"jwt\"`);\n }\n\n if (authOptions.provider === \"jwt\" && !authOptions.jwtToken) {\n throw new Error(\"JWT token is required when using JWT authentication\");\n }\n }\n\n /*\n * We use this method to generate a new keypair and create an organization for new sessions.\n * This is the first step when no existing session is found and we need to set up a new wallet.\n */\n private async createOrganizationAndKeypair(): Promise<{ organizationId: string; keypair: any }> {\n // Generate keypair using PhantomClient\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Generating keypair\");\n const keypair = generateKeyPair();\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Keypair generated\", { publicKey: keypair.publicKey });\n\n // Create a temporary client with the keypair\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Creating temporary PhantomClient\");\n const stamper = new ApiKeyStamper({\n apiSecretKey: keypair.secretKey,\n });\n\n const tempClient = new PhantomClient(\n {\n apiBaseUrl: this.config.apiBaseUrl,\n },\n stamper,\n );\n\n // Create an organization\n // organization name is a combination of this organizationId and this userId, which will be a unique identifier\n const uid = Date.now(); // for now\n const organizationName = `${this.config.organizationId}-${uid}`;\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Creating organization\", { organizationName });\n const { organizationId } = await tempClient.createOrganization(organizationName, keypair);\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Organization created\", { organizationId });\n\n return { organizationId, keypair };\n }\n\n async connect(authOptions?: AuthOptions): Promise<ConnectResult> {\n try {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Starting embedded provider connect\", {\n authOptions: authOptions\n ? {\n provider: authOptions.provider,\n hasJwtToken: !!authOptions.jwtToken,\n }\n : undefined,\n });\n\n // Get and validate existing session\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Getting existing session\");\n let session = await this.storage.getSession();\n session = await this.validateAndCleanSession(session);\n\n // First, check if we're resuming from a redirect\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Checking for redirect resume\");\n if (this.authProvider.resumeAuthFromRedirect) {\n const authResult = this.authProvider.resumeAuthFromRedirect();\n if (authResult) {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Resuming from redirect\", {\n walletId: authResult.walletId,\n provider: authResult.provider,\n });\n return this.completeAuthConnection(authResult);\n }\n }\n\n // Validate auth options\n this.validateAuthOptions(authOptions);\n\n // If no session exists, create new one\n if (!session) {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"No existing session, creating new one\");\n const { organizationId, keypair } = await this.createOrganizationAndKeypair();\n session = await this.handleAuthFlow(organizationId, keypair, authOptions);\n }\n\n // If session is null here, it means we're doing a redirect\n if (!session) {\n // This should not return anything as redirect is happening\n return {\n addresses: [],\n status: \"pending\",\n } as ConnectResult;\n }\n\n // Update session last used timestamp (only for non-redirect flows)\n // For redirect flows, timestamp is updated before redirect to prevent race condition\n if (!authOptions || authOptions.provider === \"jwt\" || this.config.embeddedWalletType === \"app-wallet\") {\n session.lastUsed = Date.now();\n await this.storage.saveSession(session);\n }\n\n // Initialize client and get addresses\n await this.initializeClientFromSession(session);\n\n return {\n walletId: this.walletId!,\n addresses: this.addresses,\n status: \"completed\",\n };\n } catch (error) {\n // Log the full error details for debugging\n this.logger.error(\"EMBEDDED_PROVIDER\", \"Connect failed with error\", {\n error:\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : error,\n });\n\n // Enhanced error handling with specific error types\n if (error instanceof Error) {\n // Check for specific error types and provide better error messages\n if (error.message.includes(\"IndexedDB\") || error.message.includes(\"storage\")) {\n throw new Error(\n \"Storage error: Unable to access browser storage. Please ensure storage is available and try again.\",\n );\n }\n\n if (error.message.includes(\"network\") || error.message.includes(\"fetch\")) {\n throw new Error(\n \"Network error: Unable to connect to authentication server. Please check your internet connection and try again.\",\n );\n }\n\n if (error.message.includes(\"JWT\") || error.message.includes(\"jwt\")) {\n throw new Error(`JWT Authentication error: ${error.message}`);\n }\n\n if (error.message.includes(\"Authentication\") || error.message.includes(\"auth\")) {\n throw new Error(`Authentication error: ${error.message}`);\n }\n\n if (error.message.includes(\"organization\") || error.message.includes(\"wallet\")) {\n throw new Error(`Wallet creation error: ${error.message}`);\n }\n\n // Re-throw the original error if it's already well-formatted\n throw error;\n }\n\n // Handle unknown error types\n throw new Error(`Embedded wallet connection failed: ${String(error)}`);\n }\n }\n\n async disconnect(): Promise<void> {\n await this.storage.clearSession();\n this.client = null;\n this.walletId = null;\n this.addresses = [];\n }\n\n async signMessage(params: SignMessageParams): Promise<string> {\n if (!this.client || !this.walletId) {\n throw new Error(\"Not connected\");\n }\n\n // Parse message to base64url format for client\n const parsedMessage = parseMessage(params.message);\n\n return await this.client.signMessage({\n walletId: this.walletId,\n message: parsedMessage.base64url,\n networkId: params.networkId,\n });\n }\n\n async signAndSendTransaction(params: SignAndSendTransactionParams): Promise<SignedTransaction> {\n if (!this.client || !this.walletId) {\n throw new Error(\"Not connected\");\n }\n\n // Parse transaction to base64url format for client based on network\n const parsedTransaction = await parseTransaction(params.transaction, params.networkId);\n\n return await this.client.signAndSendTransaction({\n walletId: this.walletId,\n transaction: parsedTransaction.base64url,\n networkId: params.networkId,\n });\n }\n\n getAddresses(): WalletAddress[] {\n return this.addresses;\n }\n\n isConnected(): boolean {\n return this.client !== null && this.walletId !== null;\n }\n\n /*\n * We use this method to route between different authentication flows based on wallet type and auth options.\n * It handles app-wallet creation directly or routes to JWT/redirect authentication for user-wallets.\n * Returns null for redirect flows since they don't complete synchronously.\n */\n private async handleAuthFlow(\n organizationId: string,\n keypair: any,\n authOptions?: AuthOptions,\n ): Promise<Session | null> {\n if (this.config.embeddedWalletType === \"user-wallet\") {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Creating user-wallet, routing authentication\", {\n authProvider: authOptions?.provider || \"phantom-connect\",\n });\n\n // Route to appropriate authentication flow based on authOptions\n if (authOptions?.provider === \"jwt\") {\n return await this.handleJWTAuth(organizationId, keypair, authOptions);\n } else {\n // This will redirect, so we don't return a session\n await this.handleRedirectAuth(organizationId, keypair, authOptions);\n return null;\n }\n } else {\n // Create app-wallet directly\n const tempClient = new PhantomClient(\n {\n apiBaseUrl: this.config.apiBaseUrl,\n },\n new ApiKeyStamper({ apiSecretKey: keypair.secretKey }),\n );\n\n const wallet = await tempClient.createWallet(`Wallet ${Date.now()}`);\n const walletId = wallet.walletId;\n\n // Save session with app-wallet info\n const now = Date.now();\n const session = {\n sessionId: generateSessionId(),\n walletId: walletId,\n organizationId: this.config.organizationId,\n keypair,\n authProvider: \"app-wallet\",\n userInfo: { embeddedWalletType: this.config.embeddedWalletType },\n status: \"completed\" as const,\n createdAt: now,\n lastUsed: now,\n };\n await this.storage.saveSession(session);\n return session;\n }\n }\n\n /*\n * We use this method to handle JWT-based authentication for user-wallets.\n * It authenticates using the provided JWT token and creates a completed session.\n */\n private async handleJWTAuth(organizationId: string, keypair: any, authOptions: AuthOptions): Promise<Session> {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Using JWT authentication flow\");\n\n // Use JWT authentication flow\n if (!authOptions.jwtToken) {\n this.logger.error(\"EMBEDDED_PROVIDER\", \"JWT token missing for JWT authentication\");\n throw new Error(\"JWT token is required for JWT authentication\");\n }\n\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Starting JWT authentication\");\n const authResult = await this.jwtAuth.authenticate({\n organizationId: organizationId,\n parentOrganizationId: this.config.organizationId,\n jwtToken: authOptions.jwtToken,\n customAuthData: authOptions.customAuthData,\n });\n const walletId = authResult.walletId;\n this.logger.info(\"EMBEDDED_PROVIDER\", \"JWT authentication completed\", { walletId });\n\n // Save session with auth info\n const now = Date.now();\n const session = {\n sessionId: generateSessionId(),\n walletId: walletId,\n organizationId: this.config.organizationId,\n keypair,\n authProvider: authResult.provider,\n userInfo: authResult.userInfo,\n status: \"completed\" as const,\n createdAt: now,\n lastUsed: now,\n };\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Saving JWT session\");\n await this.storage.saveSession(session);\n return session;\n }\n\n /*\n * We use this method to handle redirect-based authentication (Google/Apple OAuth).\n * It saves a temporary session before redirecting to prevent losing state during the redirect flow.\n * Session timestamp is updated before redirect to prevent race conditions.\n */\n private async handleRedirectAuth(organizationId: string, keypair: any, authOptions?: AuthOptions): Promise<void> {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Using Phantom Connect authentication flow (redirect-based)\", {\n provider: authOptions?.provider,\n hasRedirectUrl: !!this.config.authOptions?.redirectUrl,\n authUrl: this.config.authOptions?.authUrl,\n });\n\n // Use Phantom Connect authentication flow (redirect-based)\n // Store session before redirect so we can restore it after redirect\n const now = Date.now();\n const sessionId = generateSessionId();\n const tempSession = {\n sessionId: sessionId,\n walletId: `temp-${now}`, // Temporary ID, will be updated after redirect\n organizationId: organizationId,\n keypair,\n authProvider: \"phantom-connect\",\n userInfo: { provider: authOptions?.provider },\n status: \"pending\" as const,\n createdAt: now,\n lastUsed: now,\n };\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Saving temporary session before redirect\", {\n sessionId: tempSession.sessionId,\n tempWalletId: tempSession.walletId,\n });\n\n // Update session timestamp before redirect (prevents race condition)\n tempSession.lastUsed = Date.now();\n await this.storage.saveSession(tempSession);\n\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Starting Phantom Connect redirect\", {\n organizationId,\n parentOrganizationId: this.config.organizationId,\n provider: authOptions?.provider,\n authUrl: this.config.authOptions?.authUrl,\n });\n\n // Start the authentication flow (this will redirect the user)\n await this.authProvider.authenticate({\n organizationId: organizationId,\n parentOrganizationId: this.config.organizationId,\n provider: authOptions?.provider as \"google\" | \"apple\" | undefined,\n redirectUrl: this.config.authOptions?.redirectUrl,\n customAuthData: authOptions?.customAuthData,\n authUrl: this.config.authOptions?.authUrl,\n sessionId: sessionId,\n });\n }\n\n private async completeAuthConnection(authResult: AuthResult): Promise<ConnectResult> {\n // Check if we have an existing session\n const session = await this.storage.getSession();\n\n if (!session) {\n throw new Error(\"No session found after redirect - session may have expired\");\n }\n\n // Update session with actual wallet ID and auth info from redirect\n session.walletId = authResult.walletId;\n session.authProvider = authResult.provider || session.authProvider;\n session.userInfo = { ...session.userInfo, ...authResult.userInfo };\n session.status = \"completed\";\n session.lastUsed = Date.now();\n await this.storage.saveSession(session);\n\n await this.initializeClientFromSession(session);\n\n return {\n walletId: this.walletId!,\n addresses: this.addresses,\n status: \"completed\",\n };\n }\n\n /*\n * We use this method to initialize the PhantomClient and fetch wallet addresses from a completed session.\n * This is the final step that sets up the provider's client state and retrieves available addresses.\n */\n private async initializeClientFromSession(session: Session): Promise<void> {\n // Create client from session\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Initializing PhantomClient from session\", {\n organizationId: session.organizationId,\n walletId: session.walletId,\n });\n\n const stamper = new ApiKeyStamper({\n apiSecretKey: session.keypair.secretKey,\n });\n\n this.client = new PhantomClient(\n {\n apiBaseUrl: this.config.apiBaseUrl,\n organizationId: session.organizationId,\n },\n stamper,\n );\n\n this.walletId = session.walletId;\n\n // Get wallet addresses and filter by enabled address types with retry\n this.addresses = await this.getAndFilterWalletAddresses(session.walletId);\n }\n}\n","import type { AuthResult, JWTAuthOptions } from \"../interfaces\";\n\nexport class JWTAuth {\n async authenticate(options: JWTAuthOptions): Promise<AuthResult> {\n // Validate JWT token format\n if (!options.jwtToken || typeof options.jwtToken !== \"string\") {\n throw new Error(\"Invalid JWT token: token must be a non-empty string\");\n }\n\n // Basic JWT format validation (3 parts separated by dots)\n const jwtParts = options.jwtToken.split(\".\");\n if (jwtParts.length !== 3) {\n throw new Error(\"Invalid JWT token format: token must have 3 parts separated by dots\");\n }\n\n // JWT authentication flow - direct API call to create wallet with JWT\n try {\n // This would typically make an API call to your backend\n // which would validate the JWT and create/retrieve the wallet\n const response = await fetch(\"/api/auth/jwt\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${options.jwtToken}`,\n },\n body: JSON.stringify({\n organizationId: options.organizationId,\n parentOrganizationId: options.parentOrganizationId,\n customAuthData: options.customAuthData,\n }),\n });\n\n if (!response.ok) {\n let errorMessage = `HTTP ${response.status}`;\n try {\n const errorData = await response.json();\n errorMessage = errorData.message || errorData.error || errorMessage;\n } catch {\n errorMessage = response.statusText || errorMessage;\n }\n\n switch (response.status) {\n case 400:\n throw new Error(`Invalid JWT authentication request: ${errorMessage}`);\n case 401:\n throw new Error(`JWT token is invalid or expired: ${errorMessage}`);\n case 403:\n throw new Error(`JWT authentication forbidden: ${errorMessage}`);\n case 404:\n throw new Error(`JWT authentication endpoint not found: ${errorMessage}`);\n case 429:\n throw new Error(`Too many JWT authentication requests: ${errorMessage}`);\n case 500:\n case 502:\n case 503:\n case 504:\n throw new Error(`JWT authentication server error: ${errorMessage}`);\n default:\n throw new Error(`JWT authentication failed: ${errorMessage}`);\n }\n }\n\n let result;\n try {\n result = await response.json();\n } catch (parseError) {\n throw new Error(\"Invalid response from JWT authentication server: response is not valid JSON\");\n }\n\n if (!result.walletId) {\n throw new Error(\"Invalid JWT authentication response: missing walletId\");\n }\n\n return {\n walletId: result.walletId,\n provider: \"jwt\",\n userInfo: result.userInfo || {},\n };\n } catch (error) {\n if (error instanceof TypeError && error.message.includes(\"fetch\")) {\n throw new Error(\"JWT authentication failed: network error or invalid endpoint\");\n }\n\n if (error instanceof Error) {\n throw error; // Re-throw known errors\n }\n\n throw new Error(`JWT authentication error: ${String(error)}`);\n }\n }\n}\n","export function generateSessionId(): string {\n return (\n \"session_\" +\n Math.random().toString(36).substring(2, 15) +\n Math.random().toString(36).substring(2, 15) +\n \"_\" +\n Date.now()\n );\n}\n","import type { DebugLogger } from \"../interfaces\";\n\nexport async function retryWithBackoff<T>(\n operation: () => Promise<T>,\n operationName: string,\n logger: DebugLogger,\n maxRetries: number = 3,\n baseDelay: number = 1000,\n): Promise<T> {\n let lastError: Error;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n logger.log(\"EMBEDDED_PROVIDER\", `Attempting ${operationName}`, {\n attempt,\n maxRetries,\n });\n return await operation();\n } catch (error) {\n lastError = error as Error;\n logger.warn(\"EMBEDDED_PROVIDER\", `${operationName} failed`, {\n attempt,\n maxRetries,\n error: error instanceof Error ? error.message : String(error),\n });\n\n if (attempt === maxRetries) {\n logger.error(\"EMBEDDED_PROVIDER\", `${operationName} failed after ${maxRetries} attempts`, {\n finalError: error instanceof Error ? error.message : String(error),\n });\n break;\n }\n\n // Exponential backoff: 1s, 2s, 4s\n const delay = baseDelay * Math.pow(2, attempt - 1);\n logger.log(\"EMBEDDED_PROVIDER\", `Retrying ${operationName} in ${delay}ms`, {\n attempt: attempt + 1,\n delay,\n });\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n }\n\n throw lastError!;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAA+C;AAE/C,6BAA8B;AAC9B,qBAA+C;;;ACDxC,IAAM,UAAN,MAAc;AAAA,EACnB,MAAM,aAAa,SAA8C;AAE/D,QAAI,CAAC,QAAQ,YAAY,OAAO,QAAQ,aAAa,UAAU;AAC7D,YAAM,IAAI,MAAM,qDAAqD;AAAA,IACvE;AAGA,UAAM,WAAW,QAAQ,SAAS,MAAM,GAAG;AAC3C,QAAI,SAAS,WAAW,GAAG;AACzB,YAAM,IAAI,MAAM,qEAAqE;AAAA,IACvF;AAGA,QAAI;AAGF,YAAM,WAAW,MAAM,MAAM,iBAAiB;AAAA,QAC5C,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,UAChB,eAAe,UAAU,QAAQ,QAAQ;AAAA,QAC3C;AAAA,QACA,MAAM,KAAK,UAAU;AAAA,UACnB,gBAAgB,QAAQ;AAAA,UACxB,sBAAsB,QAAQ;AAAA,UAC9B,gBAAgB,QAAQ;AAAA,QAC1B,CAAC;AAAA,MACH,CAAC;AAED,UAAI,CAAC,SAAS,IAAI;AAChB,YAAI,eAAe,QAAQ,SAAS,MAAM;AAC1C,YAAI;AACF,gBAAM,YAAY,MAAM,SAAS,KAAK;AACtC,yBAAe,UAAU,WAAW,UAAU,SAAS;AAAA,QACzD,QAAQ;AACN,yBAAe,SAAS,cAAc;AAAA,QACxC;AAEA,gBAAQ,SAAS,QAAQ;AAAA,UACvB,KAAK;AACH,kBAAM,IAAI,MAAM,uCAAuC,YAAY,EAAE;AAAA,U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AACjE,YAAQ,SAAS;AACjB,YAAQ,WAAW,KAAK,IAAI;AAC5B,UAAM,KAAK,QAAQ,YAAY,OAAO;AAEtC,UAAM,KAAK,4BAA4B,OAAO;AAE9C,WAAO;AAAA,MACL,UAAU,KAAK;AAAA,MACf,WAAW,KAAK;AAAA,MAChB,QAAQ;AAAA,IACV;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,4BAA4B,SAAiC;AAEzE,SAAK,OAAO,IAAI,qBAAqB,2CAA2C;AAAA,MAC9E,gBAAgB,QAAQ;AAAA,MACxB,UAAU,QAAQ;AAAA,IACpB,CAAC;AAED,UAAM,UAAU,IAAI,qCAAc;AAAA,MAChC,cAAc,QAAQ,QAAQ;AAAA,IAChC,CAAC;AAED,SAAK,SAAS,IAAI;AAAA,MAChB;AAAA,QACE,YAAY,KAAK,OAAO;AAAA,QACxB,gBAAgB,QAAQ;AAAA,MAC1B;AAAA,MACA;AAAA,IACF;AAEA,SAAK,WAAW,QAAQ;AAGxB,SAAK,YAAY,MAAM,KAAK,4BAA4B,QAAQ,QAAQ;AAAA,EAC1E;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/embedded-provider.ts","../src/auth/jwt-auth.ts","../src/utils/session.ts","../src/utils/retry.ts"],"sourcesContent":["export * from \"./interfaces\";\nexport * from \"./types\";\nexport * from \"./embedded-provider\";\nexport * from \"./auth/jwt-auth\";\nexport * from \"./utils/session\";\nexport * from \"./utils/retry\";\n","import { PhantomClient } from \"@phantom/client\";\nimport type { AddressType } from \"@phantom/client\";\nimport { parseMessage, parseTransaction, parseSignMessageResponse, parseTransactionResponse,type ParsedTransactionResult, type ParsedSignatureResult } from \"@phantom/parsers\";\n\nimport type {\n PlatformAdapter,\n Session,\n AuthResult,\n DebugLogger,\n EmbeddedStorage,\n AuthProvider,\n URLParamsAccessor,\n StamperInfo,\n} from \"./interfaces\";\nimport type {\n EmbeddedProviderConfig,\n ConnectResult,\n SignMessageParams,\n SignAndSendTransactionParams,\n WalletAddress,\n AuthOptions,\n} from \"./types\";\nimport { JWTAuth } from \"./auth/jwt-auth\";\nimport { generateSessionId } from \"./utils/session\";\nimport { retryWithBackoff } from \"./utils/retry\";\nimport type { StamperWithKeyManagement } from \"@phantom/sdk-types\";\nexport class EmbeddedProvider {\n private config: EmbeddedProviderConfig;\n private platform: PlatformAdapter;\n private storage: EmbeddedStorage;\n private authProvider: AuthProvider;\n private urlParamsAccessor: URLParamsAccessor;\n private stamper: StamperWithKeyManagement;\n private logger: DebugLogger;\n private client: PhantomClient | null = null;\n private walletId: string | null = null;\n private addresses: WalletAddress[] = [];\n private jwtAuth: JWTAuth;\n\n constructor(config: EmbeddedProviderConfig, platform: PlatformAdapter, logger: DebugLogger) {\n this.logger = logger;\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Initializing EmbeddedProvider\", { config });\n\n this.config = config;\n this.platform = platform;\n this.storage = platform.storage;\n this.authProvider = platform.authProvider;\n this.urlParamsAccessor = platform.urlParamsAccessor;\n this.stamper = platform.stamper;\n this.jwtAuth = new JWTAuth();\n\n // Store solana provider config (unused for now)\n config.solanaProvider;\n this.logger.info(\"EMBEDDED_PROVIDER\", \"EmbeddedProvider initialized\");\n }\n\n private async getAndFilterWalletAddresses(walletId: string): Promise<WalletAddress[]> {\n // Get wallet addresses with retry and auto-disconnect on failure\n const addresses = await retryWithBackoff(\n () => this.client!.getWalletAddresses(walletId),\n \"getWalletAddresses\",\n this.logger,\n ).catch(async error => {\n this.logger.error(\"EMBEDDED_PROVIDER\", \"getWalletAddresses failed after retries, disconnecting\", {\n walletId,\n error: error.message,\n });\n // Clear the session if getWalletAddresses fails after retries\n await this.storage.clearSession();\n this.client = null;\n this.walletId = null;\n this.addresses = [];\n throw error;\n });\n\n // Filter by enabled address types and return formatted addresses\n return addresses\n .filter(addr => this.config.addressTypes.some(type => type === addr.addressType))\n .map(addr => ({\n addressType: addr.addressType as AddressType,\n address: addr.address,\n }));\n }\n\n /*\n * We use this method to make sure the session is not invalid, or there's a different session id in the url.\n * If there's a different one, we delete the current session and start from scratch.\n * This prevents issues where users have stale sessions or URL mismatches after redirects.\n */\n private async validateAndCleanSession(session: Session | null): Promise<Session | null> {\n if (!session) return null;\n\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Found existing session, validating\", {\n sessionId: session.sessionId,\n status: session.status,\n walletId: session.walletId,\n });\n\n // If session is not completed, check if we're in the right context\n if (session.status !== \"completed\") {\n const urlSessionId = this.urlParamsAccessor.getParam(\"session_id\");\n\n // If we have a pending session but no sessionId in URL, this is a mismatch\n if (session.status === \"pending\" && !urlSessionId) {\n this.logger.warn(\"EMBEDDED_PROVIDER\", \"Session mismatch detected - pending session without redirect context\", {\n sessionId: session.sessionId,\n status: session.status,\n });\n // Clear the invalid session and start fresh\n await this.storage.clearSession();\n return null;\n }\n // If sessionId in URL doesn't match stored session, clear invalid session\n else if (urlSessionId && urlSessionId !== session.sessionId) {\n this.logger.warn(\"EMBEDDED_PROVIDER\", \"Session ID mismatch detected\", {\n storedSessionId: session.sessionId,\n urlSessionId: urlSessionId,\n });\n await this.storage.clearSession();\n return null;\n }\n }\n\n return session;\n }\n\n /*\n * We use this method to validate authentication options before processing them.\n * This ensures only supported auth providers are used and required tokens are present.\n */\n private validateAuthOptions(authOptions?: AuthOptions): void {\n if (!authOptions) return;\n\n if (authOptions.provider && ![\"google\", \"apple\", \"jwt\"].includes(authOptions.provider)) {\n throw new Error(`Invalid auth provider: ${authOptions.provider}. Must be \"google\", \"apple\", or \"jwt\"`);\n }\n\n if (authOptions.provider === \"jwt\" && !authOptions.jwtToken) {\n throw new Error(\"JWT token is required when using JWT authentication\");\n }\n }\n\n /*\n * We use this method to initialize the stamper and create an organization for new sessions.\n * This is the first step when no existing session is found and we need to set up a new wallet.\n */\n private async createOrganizationAndStamper(): Promise<{ organizationId: string; stamperInfo: StamperInfo }> {\n // Initialize stamper (generates keypair in IndexedDB)\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Initializing stamper\");\n const stamperInfo = await this.stamper.init();\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Stamper initialized\", { publicKey: stamperInfo.publicKey, keyId: stamperInfo.keyId, algorithm: this.stamper.algorithm });\n\n // Create a temporary client with the stamper\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Creating temporary PhantomClient\");\n const tempClient = new PhantomClient(\n {\n apiBaseUrl: this.config.apiBaseUrl,\n },\n this.stamper,\n );\n\n // Create an organization\n // organization name is a combination of this organizationId and this userId, which will be a unique identifier\n const uid = Date.now(); // for now\n const organizationName = `${this.config.organizationId}-${uid}`;\n \n // Create authenticator name with platform info and public key for identification\n const platformName = this.platform.name || \"unknown\";\n const shortPubKey = stamperInfo.publicKey.slice(0, 8); // First 8 chars of public key\n const authenticatorName = `${platformName}-${shortPubKey}-${uid}`;\n \n this.logger.log(\"EMBEDDED_PROVIDER\", \"Creating organization\", { \n organizationName, \n authenticatorName, \n platform: platformName \n });\n \n const { organizationId } = await tempClient.createOrganization(organizationName, stamperInfo.publicKey, authenticatorName);\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Organization created\", { organizationId, authenticatorName });\n\n return { organizationId, stamperInfo };\n }\n\n async connect(authOptions?: AuthOptions): Promise<ConnectResult> {\n try {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Starting embedded provider connect\", {\n authOptions: authOptions\n ? {\n provider: authOptions.provider,\n hasJwtToken: !!authOptions.jwtToken,\n }\n : undefined,\n });\n\n // Get and validate existing session\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Getting existing session\");\n let session = await this.storage.getSession();\n session = await this.validateAndCleanSession(session);\n\n // First, check if we're resuming from a redirect\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Checking for redirect resume\");\n if (this.authProvider.resumeAuthFromRedirect) {\n const authResult = this.authProvider.resumeAuthFromRedirect();\n if (authResult) {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Resuming from redirect\", {\n walletId: authResult.walletId,\n provider: authResult.provider,\n });\n return this.completeAuthConnection(authResult);\n }\n }\n\n // Validate auth options\n this.validateAuthOptions(authOptions);\n\n // If no session exists, create new one\n if (!session) {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"No existing session, creating new one\");\n const { organizationId, stamperInfo } = await this.createOrganizationAndStamper();\n session = await this.handleAuthFlow(organizationId, stamperInfo, authOptions);\n }\n\n // If session is null here, it means we're doing a redirect\n if (!session) {\n // This should not return anything as redirect is happening\n return {\n addresses: [],\n status: \"pending\",\n } as ConnectResult;\n }\n\n // Update session last used timestamp (only for non-redirect flows)\n // For redirect flows, timestamp is updated before redirect to prevent race condition\n if (!authOptions || authOptions.provider === \"jwt\" || this.config.embeddedWalletType === \"app-wallet\") {\n session.lastUsed = Date.now();\n await this.storage.saveSession(session);\n }\n\n // Initialize client and get addresses\n await this.initializeClientFromSession(session);\n\n return {\n walletId: this.walletId!,\n addresses: this.addresses,\n status: \"completed\",\n };\n } catch (error) {\n // Log the full error details for debugging\n this.logger.error(\"EMBEDDED_PROVIDER\", \"Connect failed with error\", {\n error:\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : error,\n });\n\n // Enhanced error handling with specific error types\n if (error instanceof Error) {\n // Check for specific error types and provide better error messages\n if (error.message.includes(\"IndexedDB\") || error.message.includes(\"storage\")) {\n throw new Error(\n \"Storage error: Unable to access browser storage. Please ensure storage is available and try again.\",\n );\n }\n\n if (error.message.includes(\"network\") || error.message.includes(\"fetch\")) {\n throw new Error(\n \"Network error: Unable to connect to authentication server. Please check your internet connection and try again.\",\n );\n }\n\n if (error.message.includes(\"JWT\") || error.message.includes(\"jwt\")) {\n throw new Error(`JWT Authentication error: ${error.message}`);\n }\n\n if (error.message.includes(\"Authentication\") || error.message.includes(\"auth\")) {\n throw new Error(`Authentication error: ${error.message}`);\n }\n\n if (error.message.includes(\"organization\") || error.message.includes(\"wallet\")) {\n throw new Error(`Wallet creation error: ${error.message}`);\n }\n\n // Re-throw the original error if it's already well-formatted\n throw error;\n }\n\n // Handle unknown error types\n throw new Error(`Embedded wallet connection failed: ${String(error)}`);\n }\n }\n\n async disconnect(): Promise<void> {\n await this.storage.clearSession();\n this.client = null;\n this.walletId = null;\n this.addresses = [];\n }\n\n async signMessage(params: SignMessageParams): Promise<ParsedSignatureResult> {\n if (!this.client || !this.walletId) {\n throw new Error(\"Not connected\");\n }\n\n // Parse message to base64url format for client\n const parsedMessage = parseMessage(params.message);\n\n // Get raw response from client\n const rawResponse = await this.client.signMessage({\n walletId: this.walletId,\n message: parsedMessage.base64url,\n networkId: params.networkId,\n });\n\n // Parse the response to get human-readable signature and explorer URL\n return parseSignMessageResponse(rawResponse, params.networkId);\n }\n\n async signAndSendTransaction(params: SignAndSendTransactionParams): Promise<ParsedTransactionResult> {\n if (!this.client || !this.walletId) {\n throw new Error(\"Not connected\");\n }\n\n // Parse transaction to base64url format for client based on network\n const parsedTransaction = await parseTransaction(params.transaction, params.networkId);\n\n // Get raw response from client\n const rawResponse = await this.client.signAndSendTransaction({\n walletId: this.walletId,\n transaction: parsedTransaction.base64url,\n networkId: params.networkId,\n });\n\n // Parse the response to get transaction hash and explorer URL\n return await parseTransactionResponse(rawResponse.rawTransaction, params.networkId, rawResponse.hash);\n }\n\n getAddresses(): WalletAddress[] {\n return this.addresses;\n }\n\n isConnected(): boolean {\n return this.client !== null && this.walletId !== null;\n }\n\n /*\n * We use this method to route between different authentication flows based on wallet type and auth options.\n * It handles app-wallet creation directly or routes to JWT/redirect authentication for user-wallets.\n * Returns null for redirect flows since they don't complete synchronously.\n */\n private async handleAuthFlow(\n organizationId: string,\n stamperInfo: StamperInfo,\n authOptions?: AuthOptions,\n ): Promise<Session | null> {\n if (this.config.embeddedWalletType === \"user-wallet\") {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Creating user-wallet, routing authentication\", {\n authProvider: authOptions?.provider || \"phantom-connect\",\n });\n\n // Route to appropriate authentication flow based on authOptions\n if (authOptions?.provider === \"jwt\") {\n return await this.handleJWTAuth(organizationId, stamperInfo, authOptions);\n } else {\n // This will redirect in browser, so we don't return a session\n // In react-native this will return an auth result\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Starting redirect-based authentication flow\", {\n organizationId,\n parentOrganizationId: this.config.organizationId,\n provider: authOptions?.provider,\n });\n return await this.handleRedirectAuth(organizationId, stamperInfo, authOptions);\n \n }\n } else {\n // Create app-wallet directly\n const tempClient = new PhantomClient(\n {\n apiBaseUrl: this.config.apiBaseUrl,\n organizationId: organizationId,\n },\n this.stamper,\n );\n\n const wallet = await tempClient.createWallet(`Wallet ${Date.now()}`);\n const walletId = wallet.walletId;\n\n // Save session with app-wallet info\n const now = Date.now();\n const session = {\n sessionId: generateSessionId(),\n walletId: walletId,\n organizationId: organizationId,\n stamperInfo,\n authProvider: \"app-wallet\",\n userInfo: { embeddedWalletType: this.config.embeddedWalletType },\n status: \"completed\" as const,\n createdAt: now,\n lastUsed: now,\n };\n await this.storage.saveSession(session);\n return session;\n }\n }\n\n /*\n * We use this method to handle JWT-based authentication for user-wallets.\n * It authenticates using the provided JWT token and creates a completed session.\n */\n private async handleJWTAuth(organizationId: string, stamperInfo: StamperInfo, authOptions: AuthOptions): Promise<Session> {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Using JWT authentication flow\");\n\n // Use JWT authentication flow\n if (!authOptions.jwtToken) {\n this.logger.error(\"EMBEDDED_PROVIDER\", \"JWT token missing for JWT authentication\");\n throw new Error(\"JWT token is required for JWT authentication\");\n }\n\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Starting JWT authentication\");\n const authResult = await this.jwtAuth.authenticate({\n organizationId: organizationId,\n parentOrganizationId: this.config.organizationId,\n jwtToken: authOptions.jwtToken,\n customAuthData: authOptions.customAuthData,\n });\n const walletId = authResult.walletId;\n this.logger.info(\"EMBEDDED_PROVIDER\", \"JWT authentication completed\", { walletId });\n\n // Save session with auth info\n const now = Date.now();\n const session = {\n sessionId: generateSessionId(),\n walletId: walletId,\n organizationId: organizationId,\n stamperInfo,\n authProvider: authResult.provider,\n userInfo: authResult.userInfo,\n status: \"completed\" as const,\n createdAt: now,\n lastUsed: now,\n };\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Saving JWT session\");\n await this.storage.saveSession(session);\n return session;\n }\n\n /*\n * We use this method to handle redirect-based authentication (Google/Apple OAuth).\n * It saves a temporary session before redirecting to prevent losing state during the redirect flow.\n * Session timestamp is updated before redirect to prevent race conditions.\n */\n private async handleRedirectAuth(organizationId: string, stamperInfo: StamperInfo, authOptions?: AuthOptions): Promise<Session | null> {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Using Phantom Connect authentication flow (redirect-based)\", {\n provider: authOptions?.provider,\n hasRedirectUrl: !!this.config.authOptions?.redirectUrl,\n authUrl: this.config.authOptions?.authUrl,\n });\n\n // Use Phantom Connect authentication flow (redirect-based)\n // Store session before redirect so we can restore it after redirect\n const now = Date.now();\n const sessionId = generateSessionId();\n const tempSession: Session = {\n sessionId: sessionId,\n walletId: `temp-${now}`, // Temporary ID, will be updated after redirect\n organizationId: organizationId,\n stamperInfo,\n authProvider: \"phantom-connect\",\n userInfo: { provider: authOptions?.provider },\n status: \"pending\" as const,\n createdAt: now,\n lastUsed: now,\n };\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Saving temporary session before redirect\", {\n sessionId: tempSession.sessionId,\n tempWalletId: tempSession.walletId,\n });\n\n // Update session timestamp before redirect (prevents race condition)\n tempSession.lastUsed = Date.now();\n await this.storage.saveSession(tempSession);\n\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Starting Phantom Connect redirect\", {\n organizationId,\n parentOrganizationId: this.config.organizationId,\n provider: authOptions?.provider,\n authUrl: this.config.authOptions?.authUrl,\n });\n\n // Start the authentication flow (this will redirect the user in the browser, or handle it in React Native)\n const authResult = await this.authProvider.authenticate({\n organizationId: organizationId,\n parentOrganizationId: this.config.organizationId,\n provider: authOptions?.provider as \"google\" | \"apple\" | undefined,\n redirectUrl: this.config.authOptions?.redirectUrl,\n customAuthData: authOptions?.customAuthData,\n authUrl: this.config.authOptions?.authUrl,\n sessionId: sessionId,\n });\n\n if (authResult && \"walletId\" in authResult) {\n // If we got an auth result, we need to update the session with actual wallet ID\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Authentication completed after redirect\", {\n walletId: authResult.walletId,\n provider: authResult.provider,\n });\n\n // Update the temporary session with actual wallet ID and auth info\n tempSession.walletId = authResult.walletId;\n tempSession.authProvider = authResult.provider || tempSession.authProvider;\n tempSession.status = \"completed\";\n tempSession.lastUsed = Date.now();\n await this.storage.saveSession(tempSession);\n\n return tempSession; // Return the auth result for further processing\n }\n // If we don't have an auth result, it means we're in a redirect flow\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Redirect authentication initiated, waiting for redirect completion\");\n // In this case, we don't return anything as the redirect will handle the rest\n return null;\n }\n\n private async completeAuthConnection(authResult: AuthResult): Promise<ConnectResult> {\n // Check if we have an existing session\n const session = await this.storage.getSession();\n\n if (!session) {\n throw new Error(\"No session found after redirect - session may have expired\");\n }\n\n // Update session with actual wallet ID and auth info from redirect\n session.walletId = authResult.walletId;\n session.authProvider = authResult.provider || session.authProvider;\n session.status = \"completed\";\n session.lastUsed = Date.now();\n await this.storage.saveSession(session);\n\n await this.initializeClientFromSession(session);\n\n return {\n walletId: this.walletId!,\n addresses: this.addresses,\n status: \"completed\",\n };\n }\n\n /*\n * We use this method to initialize the PhantomClient and fetch wallet addresses from a completed session.\n * This is the final step that sets up the provider's client state and retrieves available addresses.\n */\n private async initializeClientFromSession(session: Session): Promise<void> {\n // Create client from session\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Initializing PhantomClient from session\", {\n organizationId: session.organizationId,\n walletId: session.walletId,\n });\n\n // Ensure stamper is initialized with existing keys\n if (!this.stamper.getKeyInfo()) {\n await this.stamper.init();\n }\n\n this.client = new PhantomClient(\n {\n apiBaseUrl: this.config.apiBaseUrl,\n organizationId: session.organizationId,\n },\n this.stamper,\n );\n\n this.walletId = session.walletId;\n\n // Get wallet addresses and filter by enabled address types with retry\n this.addresses = await this.getAndFilterWalletAddresses(session.walletId);\n }\n}\n","import type { AuthResult, JWTAuthOptions } from \"../interfaces\";\n\nexport class JWTAuth {\n async authenticate(options: JWTAuthOptions): Promise<AuthResult> {\n // Validate JWT token format\n if (!options.jwtToken || typeof options.jwtToken !== \"string\") {\n throw new Error(\"Invalid JWT token: token must be a non-empty string\");\n }\n\n // Basic JWT format validation (3 parts separated by dots)\n const jwtParts = options.jwtToken.split(\".\");\n if (jwtParts.length !== 3) {\n throw new Error(\"Invalid JWT token format: token must have 3 parts separated by dots\");\n }\n\n // JWT authentication flow - direct API call to create wallet with JWT\n try {\n // This would typically make an API call to your backend\n // which would validate the JWT and create/retrieve the wallet\n const response = await fetch(\"/api/auth/jwt\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${options.jwtToken}`,\n },\n body: JSON.stringify({\n organizationId: options.organizationId,\n parentOrganizationId: options.parentOrganizationId,\n customAuthData: options.customAuthData,\n }),\n });\n\n if (!response.ok) {\n let errorMessage = `HTTP ${response.status}`;\n try {\n const errorData = await response.json();\n errorMessage = errorData.message || errorData.error || errorMessage;\n } catch {\n errorMessage = response.statusText || errorMessage;\n }\n\n switch (response.status) {\n case 400:\n throw new Error(`Invalid JWT authentication request: ${errorMessage}`);\n case 401:\n throw new Error(`JWT token is invalid or expired: ${errorMessage}`);\n case 403:\n throw new Error(`JWT authentication forbidden: ${errorMessage}`);\n case 404:\n throw new Error(`JWT authentication endpoint not found: ${errorMessage}`);\n case 429:\n throw new Error(`Too many JWT authentication requests: ${errorMessage}`);\n case 500:\n case 502:\n case 503:\n case 504:\n throw new Error(`JWT authentication server error: ${errorMessage}`);\n default:\n throw new Error(`JWT authentication failed: ${errorMessage}`);\n }\n }\n\n let result;\n try {\n result = await response.json();\n } catch (parseError) {\n throw new Error(\"Invalid response from JWT authentication server: response is not valid JSON\");\n }\n\n if (!result.walletId) {\n throw new Error(\"Invalid JWT authentication response: missing walletId\");\n }\n\n return {\n walletId: result.walletId,\n provider: \"jwt\",\n userInfo: result.userInfo || {},\n };\n } catch (error) {\n if (error instanceof TypeError && error.message.includes(\"fetch\")) {\n throw new Error(\"JWT authentication failed: network error or invalid endpoint\");\n }\n\n if (error instanceof Error) {\n throw error; // Re-throw known errors\n }\n\n throw new Error(`JWT authentication error: ${String(error)}`);\n }\n }\n}\n","export function generateSessionId(): string {\n return (\n \"session_\" +\n Math.random().toString(36).substring(2, 15) +\n Math.random().toString(36).substring(2, 15) +\n \"_\" +\n Date.now()\n );\n}\n","import type { DebugLogger } from \"../interfaces\";\n\nexport async function retryWithBackoff<T>(\n operation: () => Promise<T>,\n operationName: string,\n logger: DebugLogger,\n maxRetries: number = 3,\n baseDelay: number = 1000,\n): Promise<T> {\n let lastError: Error;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n logger.log(\"EMBEDDED_PROVIDER\", `Attempting ${operationName}`, {\n attempt,\n maxRetries,\n });\n return await operation();\n } catch (error) {\n lastError = error as Error;\n logger.warn(\"EMBEDDED_PROVIDER\", `${operationName} failed`, {\n attempt,\n maxRetries,\n error: error instanceof Error ? error.message : String(error),\n });\n\n if (attempt === maxRetries) {\n logger.error(\"EMBEDDED_PROVIDER\", `${operationName} failed after ${maxRetries} attempts`, {\n finalError: error instanceof Error ? error.message : String(error),\n });\n break;\n }\n\n // Exponential backoff: 1s, 2s, 4s\n const delay = baseDelay * Math.pow(2, attempt - 1);\n logger.log(\"EMBEDDED_PROVIDER\", `Retrying ${operationName} in ${delay}ms`, {\n attempt: attempt + 1,\n delay,\n });\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n }\n\n throw lastError!;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAA8B;AAE9B,qBAA4J;;;ACArJ,IAAM,UAAN,MAAc;AAAA,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ers";
|
|
2
|
+
import { PhantomClient } from "@phantom/client";
|
|
3
|
+
import { parseMessage, parseTransaction, parseSignMessageResponse, parseTransactionResponse } from "@phantom/parsers";
|
|
5
4
|
|
|
6
5
|
// src/auth/jwt-auth.ts
|
|
7
6
|
var JWTAuth = class {
|
|
@@ -128,9 +127,11 @@ var EmbeddedProvider = class {
|
|
|
128
127
|
this.logger = logger;
|
|
129
128
|
this.logger.log("EMBEDDED_PROVIDER", "Initializing EmbeddedProvider", { config });
|
|
130
129
|
this.config = config;
|
|
130
|
+
this.platform = platform;
|
|
131
131
|
this.storage = platform.storage;
|
|
132
132
|
this.authProvider = platform.authProvider;
|
|
133
133
|
this.urlParamsAccessor = platform.urlParamsAccessor;
|
|
134
|
+
this.stamper = platform.stamper;
|
|
134
135
|
this.jwtAuth = new JWTAuth();
|
|
135
136
|
config.solanaProvider;
|
|
136
137
|
this.logger.info("EMBEDDED_PROVIDER", "EmbeddedProvider initialized");
|
|
@@ -204,29 +205,33 @@ var EmbeddedProvider = class {
|
|
|
204
205
|
}
|
|
205
206
|
}
|
|
206
207
|
/*
|
|
207
|
-
* We use this method to
|
|
208
|
+
* We use this method to initialize the stamper and create an organization for new sessions.
|
|
208
209
|
* This is the first step when no existing session is found and we need to set up a new wallet.
|
|
209
210
|
*/
|
|
210
|
-
async
|
|
211
|
-
this.logger.log("EMBEDDED_PROVIDER", "
|
|
212
|
-
const
|
|
213
|
-
this.logger.log("EMBEDDED_PROVIDER", "
|
|
211
|
+
async createOrganizationAndStamper() {
|
|
212
|
+
this.logger.log("EMBEDDED_PROVIDER", "Initializing stamper");
|
|
213
|
+
const stamperInfo = await this.stamper.init();
|
|
214
|
+
this.logger.log("EMBEDDED_PROVIDER", "Stamper initialized", { publicKey: stamperInfo.publicKey, keyId: stamperInfo.keyId, algorithm: this.stamper.algorithm });
|
|
214
215
|
this.logger.log("EMBEDDED_PROVIDER", "Creating temporary PhantomClient");
|
|
215
|
-
const stamper = new ApiKeyStamper({
|
|
216
|
-
apiSecretKey: keypair.secretKey
|
|
217
|
-
});
|
|
218
216
|
const tempClient = new PhantomClient(
|
|
219
217
|
{
|
|
220
218
|
apiBaseUrl: this.config.apiBaseUrl
|
|
221
219
|
},
|
|
222
|
-
stamper
|
|
220
|
+
this.stamper
|
|
223
221
|
);
|
|
224
222
|
const uid = Date.now();
|
|
225
223
|
const organizationName = `${this.config.organizationId}-${uid}`;
|
|
226
|
-
this.
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
|
|
224
|
+
const platformName = this.platform.name || "unknown";
|
|
225
|
+
const shortPubKey = stamperInfo.publicKey.slice(0, 8);
|
|
226
|
+
const authenticatorName = `${platformName}-${shortPubKey}-${uid}`;
|
|
227
|
+
this.logger.log("EMBEDDED_PROVIDER", "Creating organization", {
|
|
228
|
+
organizationName,
|
|
229
|
+
authenticatorName,
|
|
230
|
+
platform: platformName
|
|
231
|
+
});
|
|
232
|
+
const { organizationId } = await tempClient.createOrganization(organizationName, stamperInfo.publicKey, authenticatorName);
|
|
233
|
+
this.logger.info("EMBEDDED_PROVIDER", "Organization created", { organizationId, authenticatorName });
|
|
234
|
+
return { organizationId, stamperInfo };
|
|
230
235
|
}
|
|
231
236
|
async connect(authOptions) {
|
|
232
237
|
try {
|
|
@@ -253,8 +258,8 @@ var EmbeddedProvider = class {
|
|
|
253
258
|
this.validateAuthOptions(authOptions);
|
|
254
259
|
if (!session) {
|
|
255
260
|
this.logger.info("EMBEDDED_PROVIDER", "No existing session, creating new one");
|
|
256
|
-
const { organizationId,
|
|
257
|
-
session = await this.handleAuthFlow(organizationId,
|
|
261
|
+
const { organizationId, stamperInfo } = await this.createOrganizationAndStamper();
|
|
262
|
+
session = await this.handleAuthFlow(organizationId, stamperInfo, authOptions);
|
|
258
263
|
}
|
|
259
264
|
if (!session) {
|
|
260
265
|
return {
|
|
@@ -316,22 +321,24 @@ var EmbeddedProvider = class {
|
|
|
316
321
|
throw new Error("Not connected");
|
|
317
322
|
}
|
|
318
323
|
const parsedMessage = parseMessage(params.message);
|
|
319
|
-
|
|
324
|
+
const rawResponse = await this.client.signMessage({
|
|
320
325
|
walletId: this.walletId,
|
|
321
326
|
message: parsedMessage.base64url,
|
|
322
327
|
networkId: params.networkId
|
|
323
328
|
});
|
|
329
|
+
return parseSignMessageResponse(rawResponse, params.networkId);
|
|
324
330
|
}
|
|
325
331
|
async signAndSendTransaction(params) {
|
|
326
332
|
if (!this.client || !this.walletId) {
|
|
327
333
|
throw new Error("Not connected");
|
|
328
334
|
}
|
|
329
335
|
const parsedTransaction = await parseTransaction(params.transaction, params.networkId);
|
|
330
|
-
|
|
336
|
+
const rawResponse = await this.client.signAndSendTransaction({
|
|
331
337
|
walletId: this.walletId,
|
|
332
338
|
transaction: parsedTransaction.base64url,
|
|
333
339
|
networkId: params.networkId
|
|
334
340
|
});
|
|
341
|
+
return await parseTransactionResponse(rawResponse.rawTransaction, params.networkId, rawResponse.hash);
|
|
335
342
|
}
|
|
336
343
|
getAddresses() {
|
|
337
344
|
return this.addresses;
|
|
@@ -344,23 +351,28 @@ var EmbeddedProvider = class {
|
|
|
344
351
|
* It handles app-wallet creation directly or routes to JWT/redirect authentication for user-wallets.
|
|
345
352
|
* Returns null for redirect flows since they don't complete synchronously.
|
|
346
353
|
*/
|
|
347
|
-
async handleAuthFlow(organizationId,
|
|
354
|
+
async handleAuthFlow(organizationId, stamperInfo, authOptions) {
|
|
348
355
|
if (this.config.embeddedWalletType === "user-wallet") {
|
|
349
356
|
this.logger.info("EMBEDDED_PROVIDER", "Creating user-wallet, routing authentication", {
|
|
350
357
|
authProvider: authOptions?.provider || "phantom-connect"
|
|
351
358
|
});
|
|
352
359
|
if (authOptions?.provider === "jwt") {
|
|
353
|
-
return await this.handleJWTAuth(organizationId,
|
|
360
|
+
return await this.handleJWTAuth(organizationId, stamperInfo, authOptions);
|
|
354
361
|
} else {
|
|
355
|
-
|
|
356
|
-
|
|
362
|
+
this.logger.info("EMBEDDED_PROVIDER", "Starting redirect-based authentication flow", {
|
|
363
|
+
organizationId,
|
|
364
|
+
parentOrganizationId: this.config.organizationId,
|
|
365
|
+
provider: authOptions?.provider
|
|
366
|
+
});
|
|
367
|
+
return await this.handleRedirectAuth(organizationId, stamperInfo, authOptions);
|
|
357
368
|
}
|
|
358
369
|
} else {
|
|
359
370
|
const tempClient = new PhantomClient(
|
|
360
371
|
{
|
|
361
|
-
apiBaseUrl: this.config.apiBaseUrl
|
|
372
|
+
apiBaseUrl: this.config.apiBaseUrl,
|
|
373
|
+
organizationId
|
|
362
374
|
},
|
|
363
|
-
|
|
375
|
+
this.stamper
|
|
364
376
|
);
|
|
365
377
|
const wallet = await tempClient.createWallet(`Wallet ${Date.now()}`);
|
|
366
378
|
const walletId = wallet.walletId;
|
|
@@ -368,8 +380,8 @@ var EmbeddedProvider = class {
|
|
|
368
380
|
const session = {
|
|
369
381
|
sessionId: generateSessionId(),
|
|
370
382
|
walletId,
|
|
371
|
-
organizationId
|
|
372
|
-
|
|
383
|
+
organizationId,
|
|
384
|
+
stamperInfo,
|
|
373
385
|
authProvider: "app-wallet",
|
|
374
386
|
userInfo: { embeddedWalletType: this.config.embeddedWalletType },
|
|
375
387
|
status: "completed",
|
|
@@ -384,7 +396,7 @@ var EmbeddedProvider = class {
|
|
|
384
396
|
* We use this method to handle JWT-based authentication for user-wallets.
|
|
385
397
|
* It authenticates using the provided JWT token and creates a completed session.
|
|
386
398
|
*/
|
|
387
|
-
async handleJWTAuth(organizationId,
|
|
399
|
+
async handleJWTAuth(organizationId, stamperInfo, authOptions) {
|
|
388
400
|
this.logger.info("EMBEDDED_PROVIDER", "Using JWT authentication flow");
|
|
389
401
|
if (!authOptions.jwtToken) {
|
|
390
402
|
this.logger.error("EMBEDDED_PROVIDER", "JWT token missing for JWT authentication");
|
|
@@ -403,8 +415,8 @@ var EmbeddedProvider = class {
|
|
|
403
415
|
const session = {
|
|
404
416
|
sessionId: generateSessionId(),
|
|
405
417
|
walletId,
|
|
406
|
-
organizationId
|
|
407
|
-
|
|
418
|
+
organizationId,
|
|
419
|
+
stamperInfo,
|
|
408
420
|
authProvider: authResult.provider,
|
|
409
421
|
userInfo: authResult.userInfo,
|
|
410
422
|
status: "completed",
|
|
@@ -420,7 +432,7 @@ var EmbeddedProvider = class {
|
|
|
420
432
|
* It saves a temporary session before redirecting to prevent losing state during the redirect flow.
|
|
421
433
|
* Session timestamp is updated before redirect to prevent race conditions.
|
|
422
434
|
*/
|
|
423
|
-
async handleRedirectAuth(organizationId,
|
|
435
|
+
async handleRedirectAuth(organizationId, stamperInfo, authOptions) {
|
|
424
436
|
this.logger.info("EMBEDDED_PROVIDER", "Using Phantom Connect authentication flow (redirect-based)", {
|
|
425
437
|
provider: authOptions?.provider,
|
|
426
438
|
hasRedirectUrl: !!this.config.authOptions?.redirectUrl,
|
|
@@ -433,7 +445,7 @@ var EmbeddedProvider = class {
|
|
|
433
445
|
walletId: `temp-${now}`,
|
|
434
446
|
// Temporary ID, will be updated after redirect
|
|
435
447
|
organizationId,
|
|
436
|
-
|
|
448
|
+
stamperInfo,
|
|
437
449
|
authProvider: "phantom-connect",
|
|
438
450
|
userInfo: { provider: authOptions?.provider },
|
|
439
451
|
status: "pending",
|
|
@@ -452,7 +464,7 @@ var EmbeddedProvider = class {
|
|
|
452
464
|
provider: authOptions?.provider,
|
|
453
465
|
authUrl: this.config.authOptions?.authUrl
|
|
454
466
|
});
|
|
455
|
-
await this.authProvider.authenticate({
|
|
467
|
+
const authResult = await this.authProvider.authenticate({
|
|
456
468
|
organizationId,
|
|
457
469
|
parentOrganizationId: this.config.organizationId,
|
|
458
470
|
provider: authOptions?.provider,
|
|
@@ -461,6 +473,20 @@ var EmbeddedProvider = class {
|
|
|
461
473
|
authUrl: this.config.authOptions?.authUrl,
|
|
462
474
|
sessionId
|
|
463
475
|
});
|
|
476
|
+
if (authResult && "walletId" in authResult) {
|
|
477
|
+
this.logger.info("EMBEDDED_PROVIDER", "Authentication completed after redirect", {
|
|
478
|
+
walletId: authResult.walletId,
|
|
479
|
+
provider: authResult.provider
|
|
480
|
+
});
|
|
481
|
+
tempSession.walletId = authResult.walletId;
|
|
482
|
+
tempSession.authProvider = authResult.provider || tempSession.authProvider;
|
|
483
|
+
tempSession.status = "completed";
|
|
484
|
+
tempSession.lastUsed = Date.now();
|
|
485
|
+
await this.storage.saveSession(tempSession);
|
|
486
|
+
return tempSession;
|
|
487
|
+
}
|
|
488
|
+
this.logger.info("EMBEDDED_PROVIDER", "Redirect authentication initiated, waiting for redirect completion");
|
|
489
|
+
return null;
|
|
464
490
|
}
|
|
465
491
|
async completeAuthConnection(authResult) {
|
|
466
492
|
const session = await this.storage.getSession();
|
|
@@ -469,7 +495,6 @@ var EmbeddedProvider = class {
|
|
|
469
495
|
}
|
|
470
496
|
session.walletId = authResult.walletId;
|
|
471
497
|
session.authProvider = authResult.provider || session.authProvider;
|
|
472
|
-
session.userInfo = { ...session.userInfo, ...authResult.userInfo };
|
|
473
498
|
session.status = "completed";
|
|
474
499
|
session.lastUsed = Date.now();
|
|
475
500
|
await this.storage.saveSession(session);
|
|
@@ -489,15 +514,15 @@ var EmbeddedProvider = class {
|
|
|
489
514
|
organizationId: session.organizationId,
|
|
490
515
|
walletId: session.walletId
|
|
491
516
|
});
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
}
|
|
517
|
+
if (!this.stamper.getKeyInfo()) {
|
|
518
|
+
await this.stamper.init();
|
|
519
|
+
}
|
|
495
520
|
this.client = new PhantomClient(
|
|
496
521
|
{
|
|
497
522
|
apiBaseUrl: this.config.apiBaseUrl,
|
|
498
523
|
organizationId: session.organizationId
|
|
499
524
|
},
|
|
500
|
-
stamper
|
|
525
|
+
this.stamper
|
|
501
526
|
);
|
|
502
527
|
this.walletId = session.walletId;
|
|
503
528
|
this.addresses = await this.getAndFilterWalletAddresses(session.walletId);
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embedded-provider.ts","../src/auth/jwt-auth.ts","../src/utils/session.ts","../src/utils/retry.ts"],"sourcesContent":["import { PhantomClient, generateKeyPair } from \"@phantom/client\";\nimport type { AddressType } from \"@phantom/client\";\nimport { ApiKeyStamper } from \"@phantom/api-key-stamper\";\nimport { parseMessage, parseTransaction } from \"@phantom/parsers\";\n\nimport type {\n PlatformAdapter,\n Session,\n AuthResult,\n DebugLogger,\n EmbeddedStorage,\n AuthProvider,\n URLParamsAccessor,\n} from \"./interfaces\";\nimport type {\n EmbeddedProviderConfig,\n ConnectResult,\n SignMessageParams,\n SignAndSendTransactionParams,\n SignedTransaction,\n WalletAddress,\n AuthOptions,\n} from \"./types\";\nimport { JWTAuth } from \"./auth/jwt-auth\";\nimport { generateSessionId } from \"./utils/session\";\nimport { retryWithBackoff } from \"./utils/retry\";\n\nexport class EmbeddedProvider {\n private config: EmbeddedProviderConfig;\n private storage: EmbeddedStorage;\n private authProvider: AuthProvider;\n private urlParamsAccessor: URLParamsAccessor;\n private logger: DebugLogger;\n private client: PhantomClient | null = null;\n private walletId: string | null = null;\n private addresses: WalletAddress[] = [];\n private jwtAuth: JWTAuth;\n\n constructor(config: EmbeddedProviderConfig, platform: PlatformAdapter, logger: DebugLogger) {\n this.logger = logger;\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Initializing EmbeddedProvider\", { config });\n\n this.config = config;\n this.storage = platform.storage;\n this.authProvider = platform.authProvider;\n this.urlParamsAccessor = platform.urlParamsAccessor;\n this.jwtAuth = new JWTAuth();\n\n // Store solana provider config (unused for now)\n config.solanaProvider;\n this.logger.info(\"EMBEDDED_PROVIDER\", \"EmbeddedProvider initialized\");\n }\n\n private async getAndFilterWalletAddresses(walletId: string): Promise<WalletAddress[]> {\n // Get wallet addresses with retry and auto-disconnect on failure\n const addresses = await retryWithBackoff(\n () => this.client!.getWalletAddresses(walletId),\n \"getWalletAddresses\",\n this.logger,\n ).catch(async error => {\n this.logger.error(\"EMBEDDED_PROVIDER\", \"getWalletAddresses failed after retries, disconnecting\", {\n walletId,\n error: error.message,\n });\n // Clear the session if getWalletAddresses fails after retries\n await this.storage.clearSession();\n this.client = null;\n this.walletId = null;\n this.addresses = [];\n throw error;\n });\n\n // Filter by enabled address types and return formatted addresses\n return addresses\n .filter(addr => this.config.addressTypes.some(type => type === addr.addressType))\n .map(addr => ({\n addressType: addr.addressType as AddressType,\n address: addr.address,\n }));\n }\n\n /*\n * We use this method to make sure the session is not invalid, or there's a different session id in the url.\n * If there's a different one, we delete the current session and start from scratch.\n * This prevents issues where users have stale sessions or URL mismatches after redirects.\n */\n private async validateAndCleanSession(session: Session | null): Promise<Session | null> {\n if (!session) return null;\n\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Found existing session, validating\", {\n sessionId: session.sessionId,\n status: session.status,\n walletId: session.walletId,\n });\n\n // If session is not completed, check if we're in the right context\n if (session.status !== \"completed\") {\n const urlSessionId = this.urlParamsAccessor.getParam(\"session_id\");\n\n // If we have a pending session but no sessionId in URL, this is a mismatch\n if (session.status === \"pending\" && !urlSessionId) {\n this.logger.warn(\"EMBEDDED_PROVIDER\", \"Session mismatch detected - pending session without redirect context\", {\n sessionId: session.sessionId,\n status: session.status,\n });\n // Clear the invalid session and start fresh\n await this.storage.clearSession();\n return null;\n }\n // If sessionId in URL doesn't match stored session, clear invalid session\n else if (urlSessionId && urlSessionId !== session.sessionId) {\n this.logger.warn(\"EMBEDDED_PROVIDER\", \"Session ID mismatch detected\", {\n storedSessionId: session.sessionId,\n urlSessionId: urlSessionId,\n });\n await this.storage.clearSession();\n return null;\n }\n }\n\n return session;\n }\n\n /*\n * We use this method to validate authentication options before processing them.\n * This ensures only supported auth providers are used and required tokens are present.\n */\n private validateAuthOptions(authOptions?: AuthOptions): void {\n if (!authOptions) return;\n\n if (authOptions.provider && ![\"google\", \"apple\", \"jwt\"].includes(authOptions.provider)) {\n throw new Error(`Invalid auth provider: ${authOptions.provider}. Must be \"google\", \"apple\", or \"jwt\"`);\n }\n\n if (authOptions.provider === \"jwt\" && !authOptions.jwtToken) {\n throw new Error(\"JWT token is required when using JWT authentication\");\n }\n }\n\n /*\n * We use this method to generate a new keypair and create an organization for new sessions.\n * This is the first step when no existing session is found and we need to set up a new wallet.\n */\n private async createOrganizationAndKeypair(): Promise<{ organizationId: string; keypair: any }> {\n // Generate keypair using PhantomClient\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Generating keypair\");\n const keypair = generateKeyPair();\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Keypair generated\", { publicKey: keypair.publicKey });\n\n // Create a temporary client with the keypair\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Creating temporary PhantomClient\");\n const stamper = new ApiKeyStamper({\n apiSecretKey: keypair.secretKey,\n });\n\n const tempClient = new PhantomClient(\n {\n apiBaseUrl: this.config.apiBaseUrl,\n },\n stamper,\n );\n\n // Create an organization\n // organization name is a combination of this organizationId and this userId, which will be a unique identifier\n const uid = Date.now(); // for now\n const organizationName = `${this.config.organizationId}-${uid}`;\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Creating organization\", { organizationName });\n const { organizationId } = await tempClient.createOrganization(organizationName, keypair);\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Organization created\", { organizationId });\n\n return { organizationId, keypair };\n }\n\n async connect(authOptions?: AuthOptions): Promise<ConnectResult> {\n try {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Starting embedded provider connect\", {\n authOptions: authOptions\n ? {\n provider: authOptions.provider,\n hasJwtToken: !!authOptions.jwtToken,\n }\n : undefined,\n });\n\n // Get and validate existing session\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Getting existing session\");\n let session = await this.storage.getSession();\n session = await this.validateAndCleanSession(session);\n\n // First, check if we're resuming from a redirect\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Checking for redirect resume\");\n if (this.authProvider.resumeAuthFromRedirect) {\n const authResult = this.authProvider.resumeAuthFromRedirect();\n if (authResult) {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Resuming from redirect\", {\n walletId: authResult.walletId,\n provider: authResult.provider,\n });\n return this.completeAuthConnection(authResult);\n }\n }\n\n // Validate auth options\n this.validateAuthOptions(authOptions);\n\n // If no session exists, create new one\n if (!session) {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"No existing session, creating new one\");\n const { organizationId, keypair } = await this.createOrganizationAndKeypair();\n session = await this.handleAuthFlow(organizationId, keypair, authOptions);\n }\n\n // If session is null here, it means we're doing a redirect\n if (!session) {\n // This should not return anything as redirect is happening\n return {\n addresses: [],\n status: \"pending\",\n } as ConnectResult;\n }\n\n // Update session last used timestamp (only for non-redirect flows)\n // For redirect flows, timestamp is updated before redirect to prevent race condition\n if (!authOptions || authOptions.provider === \"jwt\" || this.config.embeddedWalletType === \"app-wallet\") {\n session.lastUsed = Date.now();\n await this.storage.saveSession(session);\n }\n\n // Initialize client and get addresses\n await this.initializeClientFromSession(session);\n\n return {\n walletId: this.walletId!,\n addresses: this.addresses,\n status: \"completed\",\n };\n } catch (error) {\n // Log the full error details for debugging\n this.logger.error(\"EMBEDDED_PROVIDER\", \"Connect failed with error\", {\n error:\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : error,\n });\n\n // Enhanced error handling with specific error types\n if (error instanceof Error) {\n // Check for specific error types and provide better error messages\n if (error.message.includes(\"IndexedDB\") || error.message.includes(\"storage\")) {\n throw new Error(\n \"Storage error: Unable to access browser storage. Please ensure storage is available and try again.\",\n );\n }\n\n if (error.message.includes(\"network\") || error.message.includes(\"fetch\")) {\n throw new Error(\n \"Network error: Unable to connect to authentication server. Please check your internet connection and try again.\",\n );\n }\n\n if (error.message.includes(\"JWT\") || error.message.includes(\"jwt\")) {\n throw new Error(`JWT Authentication error: ${error.message}`);\n }\n\n if (error.message.includes(\"Authentication\") || error.message.includes(\"auth\")) {\n throw new Error(`Authentication error: ${error.message}`);\n }\n\n if (error.message.includes(\"organization\") || error.message.includes(\"wallet\")) {\n throw new Error(`Wallet creation error: ${error.message}`);\n }\n\n // Re-throw the original error if it's already well-formatted\n throw error;\n }\n\n // Handle unknown error types\n throw new Error(`Embedded wallet connection failed: ${String(error)}`);\n }\n }\n\n async disconnect(): Promise<void> {\n await this.storage.clearSession();\n this.client = null;\n this.walletId = null;\n this.addresses = [];\n }\n\n async signMessage(params: SignMessageParams): Promise<string> {\n if (!this.client || !this.walletId) {\n throw new Error(\"Not connected\");\n }\n\n // Parse message to base64url format for client\n const parsedMessage = parseMessage(params.message);\n\n return await this.client.signMessage({\n walletId: this.walletId,\n message: parsedMessage.base64url,\n networkId: params.networkId,\n });\n }\n\n async signAndSendTransaction(params: SignAndSendTransactionParams): Promise<SignedTransaction> {\n if (!this.client || !this.walletId) {\n throw new Error(\"Not connected\");\n }\n\n // Parse transaction to base64url format for client based on network\n const parsedTransaction = await parseTransaction(params.transaction, params.networkId);\n\n return await this.client.signAndSendTransaction({\n walletId: this.walletId,\n transaction: parsedTransaction.base64url,\n networkId: params.networkId,\n });\n }\n\n getAddresses(): WalletAddress[] {\n return this.addresses;\n }\n\n isConnected(): boolean {\n return this.client !== null && this.walletId !== null;\n }\n\n /*\n * We use this method to route between different authentication flows based on wallet type and auth options.\n * It handles app-wallet creation directly or routes to JWT/redirect authentication for user-wallets.\n * Returns null for redirect flows since they don't complete synchronously.\n */\n private async handleAuthFlow(\n organizationId: string,\n keypair: any,\n authOptions?: AuthOptions,\n ): Promise<Session | null> {\n if (this.config.embeddedWalletType === \"user-wallet\") {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Creating user-wallet, routing authentication\", {\n authProvider: authOptions?.provider || \"phantom-connect\",\n });\n\n // Route to appropriate authentication flow based on authOptions\n if (authOptions?.provider === \"jwt\") {\n return await this.handleJWTAuth(organizationId, keypair, authOptions);\n } else {\n // This will redirect, so we don't return a session\n await this.handleRedirectAuth(organizationId, keypair, authOptions);\n return null;\n }\n } else {\n // Create app-wallet directly\n const tempClient = new PhantomClient(\n {\n apiBaseUrl: this.config.apiBaseUrl,\n },\n new ApiKeyStamper({ apiSecretKey: keypair.secretKey }),\n );\n\n const wallet = await tempClient.createWallet(`Wallet ${Date.now()}`);\n const walletId = wallet.walletId;\n\n // Save session with app-wallet info\n const now = Date.now();\n const session = {\n sessionId: generateSessionId(),\n walletId: walletId,\n organizationId: this.config.organizationId,\n keypair,\n authProvider: \"app-wallet\",\n userInfo: { embeddedWalletType: this.config.embeddedWalletType },\n status: \"completed\" as const,\n createdAt: now,\n lastUsed: now,\n };\n await this.storage.saveSession(session);\n return session;\n }\n }\n\n /*\n * We use this method to handle JWT-based authentication for user-wallets.\n * It authenticates using the provided JWT token and creates a completed session.\n */\n private async handleJWTAuth(organizationId: string, keypair: any, authOptions: AuthOptions): Promise<Session> {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Using JWT authentication flow\");\n\n // Use JWT authentication flow\n if (!authOptions.jwtToken) {\n this.logger.error(\"EMBEDDED_PROVIDER\", \"JWT token missing for JWT authentication\");\n throw new Error(\"JWT token is required for JWT authentication\");\n }\n\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Starting JWT authentication\");\n const authResult = await this.jwtAuth.authenticate({\n organizationId: organizationId,\n parentOrganizationId: this.config.organizationId,\n jwtToken: authOptions.jwtToken,\n customAuthData: authOptions.customAuthData,\n });\n const walletId = authResult.walletId;\n this.logger.info(\"EMBEDDED_PROVIDER\", \"JWT authentication completed\", { walletId });\n\n // Save session with auth info\n const now = Date.now();\n const session = {\n sessionId: generateSessionId(),\n walletId: walletId,\n organizationId: this.config.organizationId,\n keypair,\n authProvider: authResult.provider,\n userInfo: authResult.userInfo,\n status: \"completed\" as const,\n createdAt: now,\n lastUsed: now,\n };\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Saving JWT session\");\n await this.storage.saveSession(session);\n return session;\n }\n\n /*\n * We use this method to handle redirect-based authentication (Google/Apple OAuth).\n * It saves a temporary session before redirecting to prevent losing state during the redirect flow.\n * Session timestamp is updated before redirect to prevent race conditions.\n */\n private async handleRedirectAuth(organizationId: string, keypair: any, authOptions?: AuthOptions): Promise<void> {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Using Phantom Connect authentication flow (redirect-based)\", {\n provider: authOptions?.provider,\n hasRedirectUrl: !!this.config.authOptions?.redirectUrl,\n authUrl: this.config.authOptions?.authUrl,\n });\n\n // Use Phantom Connect authentication flow (redirect-based)\n // Store session before redirect so we can restore it after redirect\n const now = Date.now();\n const sessionId = generateSessionId();\n const tempSession = {\n sessionId: sessionId,\n walletId: `temp-${now}`, // Temporary ID, will be updated after redirect\n organizationId: organizationId,\n keypair,\n authProvider: \"phantom-connect\",\n userInfo: { provider: authOptions?.provider },\n status: \"pending\" as const,\n createdAt: now,\n lastUsed: now,\n };\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Saving temporary session before redirect\", {\n sessionId: tempSession.sessionId,\n tempWalletId: tempSession.walletId,\n });\n\n // Update session timestamp before redirect (prevents race condition)\n tempSession.lastUsed = Date.now();\n await this.storage.saveSession(tempSession);\n\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Starting Phantom Connect redirect\", {\n organizationId,\n parentOrganizationId: this.config.organizationId,\n provider: authOptions?.provider,\n authUrl: this.config.authOptions?.authUrl,\n });\n\n // Start the authentication flow (this will redirect the user)\n await this.authProvider.authenticate({\n organizationId: organizationId,\n parentOrganizationId: this.config.organizationId,\n provider: authOptions?.provider as \"google\" | \"apple\" | undefined,\n redirectUrl: this.config.authOptions?.redirectUrl,\n customAuthData: authOptions?.customAuthData,\n authUrl: this.config.authOptions?.authUrl,\n sessionId: sessionId,\n });\n }\n\n private async completeAuthConnection(authResult: AuthResult): Promise<ConnectResult> {\n // Check if we have an existing session\n const session = await this.storage.getSession();\n\n if (!session) {\n throw new Error(\"No session found after redirect - session may have expired\");\n }\n\n // Update session with actual wallet ID and auth info from redirect\n session.walletId = authResult.walletId;\n session.authProvider = authResult.provider || session.authProvider;\n session.userInfo = { ...session.userInfo, ...authResult.userInfo };\n session.status = \"completed\";\n session.lastUsed = Date.now();\n await this.storage.saveSession(session);\n\n await this.initializeClientFromSession(session);\n\n return {\n walletId: this.walletId!,\n addresses: this.addresses,\n status: \"completed\",\n };\n }\n\n /*\n * We use this method to initialize the PhantomClient and fetch wallet addresses from a completed session.\n * This is the final step that sets up the provider's client state and retrieves available addresses.\n */\n private async initializeClientFromSession(session: Session): Promise<void> {\n // Create client from session\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Initializing PhantomClient from session\", {\n organizationId: session.organizationId,\n walletId: session.walletId,\n });\n\n const stamper = new ApiKeyStamper({\n apiSecretKey: session.keypair.secretKey,\n });\n\n this.client = new PhantomClient(\n {\n apiBaseUrl: this.config.apiBaseUrl,\n organizationId: session.organizationId,\n },\n stamper,\n );\n\n this.walletId = session.walletId;\n\n // Get wallet addresses and filter by enabled address types with retry\n this.addresses = await this.getAndFilterWalletAddresses(session.walletId);\n }\n}\n","import type { AuthResult, JWTAuthOptions } from \"../interfaces\";\n\nexport class JWTAuth {\n async authenticate(options: JWTAuthOptions): Promise<AuthResult> {\n // Validate JWT token format\n if (!options.jwtToken || typeof options.jwtToken !== \"string\") {\n throw new Error(\"Invalid JWT token: token must be a non-empty string\");\n }\n\n // Basic JWT format validation (3 parts separated by dots)\n const jwtParts = options.jwtToken.split(\".\");\n if (jwtParts.length !== 3) {\n throw new Error(\"Invalid JWT token format: token must have 3 parts separated by dots\");\n }\n\n // JWT authentication flow - direct API call to create wallet with JWT\n try {\n // This would typically make an API call to your backend\n // which would validate the JWT and create/retrieve the wallet\n const response = await fetch(\"/api/auth/jwt\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${options.jwtToken}`,\n },\n body: JSON.stringify({\n organizationId: options.organizationId,\n parentOrganizationId: options.parentOrganizationId,\n customAuthData: options.customAuthData,\n }),\n });\n\n if (!response.ok) {\n let errorMessage = `HTTP ${response.status}`;\n try {\n const errorData = await response.json();\n errorMessage = errorData.message || errorData.error || errorMessage;\n } catch {\n errorMessage = response.statusText || errorMessage;\n }\n\n switch (response.status) {\n case 400:\n throw new Error(`Invalid JWT authentication request: ${errorMessage}`);\n case 401:\n throw new Error(`JWT token is invalid or expired: ${errorMessage}`);\n case 403:\n throw new Error(`JWT authentication forbidden: ${errorMessage}`);\n case 404:\n throw new Error(`JWT authentication endpoint not found: ${errorMessage}`);\n case 429:\n throw new Error(`Too many JWT authentication requests: ${errorMessage}`);\n case 500:\n case 502:\n case 503:\n case 504:\n throw new Error(`JWT authentication server error: ${errorMessage}`);\n default:\n throw new Error(`JWT authentication failed: ${errorMessage}`);\n }\n }\n\n let result;\n try {\n result = await response.json();\n } catch (parseError) {\n throw new Error(\"Invalid response from JWT authentication server: response is not valid JSON\");\n }\n\n if (!result.walletId) {\n throw new Error(\"Invalid JWT authentication response: missing walletId\");\n }\n\n return {\n walletId: result.walletId,\n provider: \"jwt\",\n userInfo: result.userInfo || {},\n };\n } catch (error) {\n if (error instanceof TypeError && error.message.includes(\"fetch\")) {\n throw new Error(\"JWT authentication failed: network error or invalid endpoint\");\n }\n\n if (error instanceof Error) {\n throw error; // Re-throw known errors\n }\n\n throw new Error(`JWT authentication error: ${String(error)}`);\n }\n }\n}\n","export function generateSessionId(): string {\n return (\n \"session_\" +\n Math.random().toString(36).substring(2, 15) +\n Math.random().toString(36).substring(2, 15) +\n \"_\" +\n Date.now()\n );\n}\n","import type { DebugLogger } from \"../interfaces\";\n\nexport async function retryWithBackoff<T>(\n operation: () => Promise<T>,\n operationName: string,\n logger: DebugLogger,\n maxRetries: number = 3,\n baseDelay: number = 1000,\n): Promise<T> {\n let lastError: Error;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n logger.log(\"EMBEDDED_PROVIDER\", `Attempting ${operationName}`, {\n attempt,\n maxRetries,\n });\n return await operation();\n } catch (error) {\n lastError = error as Error;\n logger.warn(\"EMBEDDED_PROVIDER\", `${operationName} failed`, {\n attempt,\n maxRetries,\n error: error instanceof Error ? error.message : String(error),\n });\n\n if (attempt === maxRetries) {\n logger.error(\"EMBEDDED_PROVIDER\", `${operationName} failed after ${maxRetries} attempts`, {\n finalError: error instanceof Error ? error.message : String(error),\n });\n break;\n }\n\n // Exponential backoff: 1s, 2s, 4s\n const delay = baseDelay * Math.pow(2, attempt - 1);\n logger.log(\"EMBEDDED_PROVIDER\", `Retrying ${operationName} in ${delay}ms`, {\n attempt: attempt + 1,\n delay,\n });\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n }\n\n throw lastError!;\n}\n"],"mappings":";AAAA,SAAS,eAAe,uBAAuB;AAE/C,SAAS,qBAAqB;AAC9B,SAAS,cAAc,wBAAwB;;;ACDxC,IAAM,UAAN,MAAc;AAAA,EACnB,MAAM,aAAa,SAA8C;AAE/D,QAAI,CAAC,QAAQ,YAAY,OAAO,QAAQ,aAAa,UAAU;AAC7D,YAAM,IAAI,MAAM,qDAAqD;AAAA,IACvE;AAGA,UAAM,WAAW,QAAQ,SAAS,MAAM,GAAG;AAC3C,QAAI,SAAS,WAAW,GAAG;AACzB,YAAM,IAAI,MAAM,qEAAqE;AAAA,IACvF;AAGA,QAAI;AAGF,YAAM,WAAW,MAAM,MAAM,iBAAiB;AAAA,QAC5C,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,UAChB,eAAe,UAAU,QAAQ,QAAQ;AAAA,QAC3C;AAAA,QACA,MAAM,KAAK,UAAU;AAAA,UACnB,gBAAgB,QAAQ;AAAA,UACxB,sBAAsB,QAAQ;AAAA,UAC9B,gBAAgB,QAAQ;AAAA,QAC1B,CAAC;AAAA,MACH,CAAC;AAED,UAAI,CAAC,SAAS,IAAI;AAChB,YAAI,eAAe,QAAQ,SAAS,MAAM;AAC1C,YAAI;AACF,gBAAM,YAAY,MAAM,SAAS,KAAK;AACtC,yBAAe,UAAU,WAAW,UAAU,SAAS;AAAA,QACzD,QAAQ;AACN,yBAAe,SAAS,cAAc;AAAA,QACxC;AAEA,gBAAQ,SAAS,QAAQ;AAAA,UACvB,KAAK;AACH,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EAAE,GAAG,QAAQ,UAAU,GAAG,WAAW,SAAS;AACjE,YAAQ,SAAS;AACjB,YAAQ,WAAW,KAAK,IAAI;AAC5B,UAAM,KAAK,QAAQ,YAAY,OAAO;AAEtC,UAAM,KAAK,4BAA4B,OAAO;AAE9C,WAAO;AAAA,MACL,UAAU,KAAK;AAAA,MACf,WAAW,KAAK;AAAA,MAChB,QAAQ;AAAA,IACV;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,4BAA4B,SAAiC;AAEzE,SAAK,OAAO,IAAI,qBAAqB,2CAA2C;AAAA,MAC9E,gBAAgB,QAAQ;AAAA,MACxB,UAAU,QAAQ;AAAA,IACpB,CAAC;AAED,UAAM,UAAU,IAAI,cAAc;AAAA,MAChC,cAAc,QAAQ,QAAQ;AAAA,IAChC,CAAC;AAED,SAAK,SAAS,IAAI;AAAA,MAChB;AAAA,QACE,YAAY,KAAK,OAAO;AAAA,QACxB,gBAAgB,QAAQ;AAAA,MAC1B;AAAA,MACA;AAAA,IACF;AAEA,SAAK,WAAW,QAAQ;AAGxB,SAAK,YAAY,MAAM,KAAK,4BAA4B,QAAQ,QAAQ;AAAA,EAC1E;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/embedded-provider.ts","../src/auth/jwt-auth.ts","../src/utils/session.ts","../src/utils/retry.ts"],"sourcesContent":["import { PhantomClient } from \"@phantom/client\";\nimport type { AddressType } from \"@phantom/client\";\nimport { parseMessage, parseTransaction, parseSignMessageResponse, parseTransactionResponse,type ParsedTransactionResult, type ParsedSignatureResult } from \"@phantom/parsers\";\n\nimport type {\n PlatformAdapter,\n Session,\n AuthResult,\n DebugLogger,\n EmbeddedStorage,\n AuthProvider,\n URLParamsAccessor,\n StamperInfo,\n} from \"./interfaces\";\nimport type {\n EmbeddedProviderConfig,\n ConnectResult,\n SignMessageParams,\n SignAndSendTransactionParams,\n WalletAddress,\n AuthOptions,\n} from \"./types\";\nimport { JWTAuth } from \"./auth/jwt-auth\";\nimport { generateSessionId } from \"./utils/session\";\nimport { retryWithBackoff } from \"./utils/retry\";\nimport type { StamperWithKeyManagement } from \"@phantom/sdk-types\";\nexport class EmbeddedProvider {\n private config: EmbeddedProviderConfig;\n private platform: PlatformAdapter;\n private storage: EmbeddedStorage;\n private authProvider: AuthProvider;\n private urlParamsAccessor: URLParamsAccessor;\n private stamper: StamperWithKeyManagement;\n private logger: DebugLogger;\n private client: PhantomClient | null = null;\n private walletId: string | null = null;\n private addresses: WalletAddress[] = [];\n private jwtAuth: JWTAuth;\n\n constructor(config: EmbeddedProviderConfig, platform: PlatformAdapter, logger: DebugLogger) {\n this.logger = logger;\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Initializing EmbeddedProvider\", { config });\n\n this.config = config;\n this.platform = platform;\n this.storage = platform.storage;\n this.authProvider = platform.authProvider;\n this.urlParamsAccessor = platform.urlParamsAccessor;\n this.stamper = platform.stamper;\n this.jwtAuth = new JWTAuth();\n\n // Store solana provider config (unused for now)\n config.solanaProvider;\n this.logger.info(\"EMBEDDED_PROVIDER\", \"EmbeddedProvider initialized\");\n }\n\n private async getAndFilterWalletAddresses(walletId: string): Promise<WalletAddress[]> {\n // Get wallet addresses with retry and auto-disconnect on failure\n const addresses = await retryWithBackoff(\n () => this.client!.getWalletAddresses(walletId),\n \"getWalletAddresses\",\n this.logger,\n ).catch(async error => {\n this.logger.error(\"EMBEDDED_PROVIDER\", \"getWalletAddresses failed after retries, disconnecting\", {\n walletId,\n error: error.message,\n });\n // Clear the session if getWalletAddresses fails after retries\n await this.storage.clearSession();\n this.client = null;\n this.walletId = null;\n this.addresses = [];\n throw error;\n });\n\n // Filter by enabled address types and return formatted addresses\n return addresses\n .filter(addr => this.config.addressTypes.some(type => type === addr.addressType))\n .map(addr => ({\n addressType: addr.addressType as AddressType,\n address: addr.address,\n }));\n }\n\n /*\n * We use this method to make sure the session is not invalid, or there's a different session id in the url.\n * If there's a different one, we delete the current session and start from scratch.\n * This prevents issues where users have stale sessions or URL mismatches after redirects.\n */\n private async validateAndCleanSession(session: Session | null): Promise<Session | null> {\n if (!session) return null;\n\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Found existing session, validating\", {\n sessionId: session.sessionId,\n status: session.status,\n walletId: session.walletId,\n });\n\n // If session is not completed, check if we're in the right context\n if (session.status !== \"completed\") {\n const urlSessionId = this.urlParamsAccessor.getParam(\"session_id\");\n\n // If we have a pending session but no sessionId in URL, this is a mismatch\n if (session.status === \"pending\" && !urlSessionId) {\n this.logger.warn(\"EMBEDDED_PROVIDER\", \"Session mismatch detected - pending session without redirect context\", {\n sessionId: session.sessionId,\n status: session.status,\n });\n // Clear the invalid session and start fresh\n await this.storage.clearSession();\n return null;\n }\n // If sessionId in URL doesn't match stored session, clear invalid session\n else if (urlSessionId && urlSessionId !== session.sessionId) {\n this.logger.warn(\"EMBEDDED_PROVIDER\", \"Session ID mismatch detected\", {\n storedSessionId: session.sessionId,\n urlSessionId: urlSessionId,\n });\n await this.storage.clearSession();\n return null;\n }\n }\n\n return session;\n }\n\n /*\n * We use this method to validate authentication options before processing them.\n * This ensures only supported auth providers are used and required tokens are present.\n */\n private validateAuthOptions(authOptions?: AuthOptions): void {\n if (!authOptions) return;\n\n if (authOptions.provider && ![\"google\", \"apple\", \"jwt\"].includes(authOptions.provider)) {\n throw new Error(`Invalid auth provider: ${authOptions.provider}. Must be \"google\", \"apple\", or \"jwt\"`);\n }\n\n if (authOptions.provider === \"jwt\" && !authOptions.jwtToken) {\n throw new Error(\"JWT token is required when using JWT authentication\");\n }\n }\n\n /*\n * We use this method to initialize the stamper and create an organization for new sessions.\n * This is the first step when no existing session is found and we need to set up a new wallet.\n */\n private async createOrganizationAndStamper(): Promise<{ organizationId: string; stamperInfo: StamperInfo }> {\n // Initialize stamper (generates keypair in IndexedDB)\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Initializing stamper\");\n const stamperInfo = await this.stamper.init();\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Stamper initialized\", { publicKey: stamperInfo.publicKey, keyId: stamperInfo.keyId, algorithm: this.stamper.algorithm });\n\n // Create a temporary client with the stamper\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Creating temporary PhantomClient\");\n const tempClient = new PhantomClient(\n {\n apiBaseUrl: this.config.apiBaseUrl,\n },\n this.stamper,\n );\n\n // Create an organization\n // organization name is a combination of this organizationId and this userId, which will be a unique identifier\n const uid = Date.now(); // for now\n const organizationName = `${this.config.organizationId}-${uid}`;\n \n // Create authenticator name with platform info and public key for identification\n const platformName = this.platform.name || \"unknown\";\n const shortPubKey = stamperInfo.publicKey.slice(0, 8); // First 8 chars of public key\n const authenticatorName = `${platformName}-${shortPubKey}-${uid}`;\n \n this.logger.log(\"EMBEDDED_PROVIDER\", \"Creating organization\", { \n organizationName, \n authenticatorName, \n platform: platformName \n });\n \n const { organizationId } = await tempClient.createOrganization(organizationName, stamperInfo.publicKey, authenticatorName);\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Organization created\", { organizationId, authenticatorName });\n\n return { organizationId, stamperInfo };\n }\n\n async connect(authOptions?: AuthOptions): Promise<ConnectResult> {\n try {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Starting embedded provider connect\", {\n authOptions: authOptions\n ? {\n provider: authOptions.provider,\n hasJwtToken: !!authOptions.jwtToken,\n }\n : undefined,\n });\n\n // Get and validate existing session\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Getting existing session\");\n let session = await this.storage.getSession();\n session = await this.validateAndCleanSession(session);\n\n // First, check if we're resuming from a redirect\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Checking for redirect resume\");\n if (this.authProvider.resumeAuthFromRedirect) {\n const authResult = this.authProvider.resumeAuthFromRedirect();\n if (authResult) {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Resuming from redirect\", {\n walletId: authResult.walletId,\n provider: authResult.provider,\n });\n return this.completeAuthConnection(authResult);\n }\n }\n\n // Validate auth options\n this.validateAuthOptions(authOptions);\n\n // If no session exists, create new one\n if (!session) {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"No existing session, creating new one\");\n const { organizationId, stamperInfo } = await this.createOrganizationAndStamper();\n session = await this.handleAuthFlow(organizationId, stamperInfo, authOptions);\n }\n\n // If session is null here, it means we're doing a redirect\n if (!session) {\n // This should not return anything as redirect is happening\n return {\n addresses: [],\n status: \"pending\",\n } as ConnectResult;\n }\n\n // Update session last used timestamp (only for non-redirect flows)\n // For redirect flows, timestamp is updated before redirect to prevent race condition\n if (!authOptions || authOptions.provider === \"jwt\" || this.config.embeddedWalletType === \"app-wallet\") {\n session.lastUsed = Date.now();\n await this.storage.saveSession(session);\n }\n\n // Initialize client and get addresses\n await this.initializeClientFromSession(session);\n\n return {\n walletId: this.walletId!,\n addresses: this.addresses,\n status: \"completed\",\n };\n } catch (error) {\n // Log the full error details for debugging\n this.logger.error(\"EMBEDDED_PROVIDER\", \"Connect failed with error\", {\n error:\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : error,\n });\n\n // Enhanced error handling with specific error types\n if (error instanceof Error) {\n // Check for specific error types and provide better error messages\n if (error.message.includes(\"IndexedDB\") || error.message.includes(\"storage\")) {\n throw new Error(\n \"Storage error: Unable to access browser storage. Please ensure storage is available and try again.\",\n );\n }\n\n if (error.message.includes(\"network\") || error.message.includes(\"fetch\")) {\n throw new Error(\n \"Network error: Unable to connect to authentication server. Please check your internet connection and try again.\",\n );\n }\n\n if (error.message.includes(\"JWT\") || error.message.includes(\"jwt\")) {\n throw new Error(`JWT Authentication error: ${error.message}`);\n }\n\n if (error.message.includes(\"Authentication\") || error.message.includes(\"auth\")) {\n throw new Error(`Authentication error: ${error.message}`);\n }\n\n if (error.message.includes(\"organization\") || error.message.includes(\"wallet\")) {\n throw new Error(`Wallet creation error: ${error.message}`);\n }\n\n // Re-throw the original error if it's already well-formatted\n throw error;\n }\n\n // Handle unknown error types\n throw new Error(`Embedded wallet connection failed: ${String(error)}`);\n }\n }\n\n async disconnect(): Promise<void> {\n await this.storage.clearSession();\n this.client = null;\n this.walletId = null;\n this.addresses = [];\n }\n\n async signMessage(params: SignMessageParams): Promise<ParsedSignatureResult> {\n if (!this.client || !this.walletId) {\n throw new Error(\"Not connected\");\n }\n\n // Parse message to base64url format for client\n const parsedMessage = parseMessage(params.message);\n\n // Get raw response from client\n const rawResponse = await this.client.signMessage({\n walletId: this.walletId,\n message: parsedMessage.base64url,\n networkId: params.networkId,\n });\n\n // Parse the response to get human-readable signature and explorer URL\n return parseSignMessageResponse(rawResponse, params.networkId);\n }\n\n async signAndSendTransaction(params: SignAndSendTransactionParams): Promise<ParsedTransactionResult> {\n if (!this.client || !this.walletId) {\n throw new Error(\"Not connected\");\n }\n\n // Parse transaction to base64url format for client based on network\n const parsedTransaction = await parseTransaction(params.transaction, params.networkId);\n\n // Get raw response from client\n const rawResponse = await this.client.signAndSendTransaction({\n walletId: this.walletId,\n transaction: parsedTransaction.base64url,\n networkId: params.networkId,\n });\n\n // Parse the response to get transaction hash and explorer URL\n return await parseTransactionResponse(rawResponse.rawTransaction, params.networkId, rawResponse.hash);\n }\n\n getAddresses(): WalletAddress[] {\n return this.addresses;\n }\n\n isConnected(): boolean {\n return this.client !== null && this.walletId !== null;\n }\n\n /*\n * We use this method to route between different authentication flows based on wallet type and auth options.\n * It handles app-wallet creation directly or routes to JWT/redirect authentication for user-wallets.\n * Returns null for redirect flows since they don't complete synchronously.\n */\n private async handleAuthFlow(\n organizationId: string,\n stamperInfo: StamperInfo,\n authOptions?: AuthOptions,\n ): Promise<Session | null> {\n if (this.config.embeddedWalletType === \"user-wallet\") {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Creating user-wallet, routing authentication\", {\n authProvider: authOptions?.provider || \"phantom-connect\",\n });\n\n // Route to appropriate authentication flow based on authOptions\n if (authOptions?.provider === \"jwt\") {\n return await this.handleJWTAuth(organizationId, stamperInfo, authOptions);\n } else {\n // This will redirect in browser, so we don't return a session\n // In react-native this will return an auth result\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Starting redirect-based authentication flow\", {\n organizationId,\n parentOrganizationId: this.config.organizationId,\n provider: authOptions?.provider,\n });\n return await this.handleRedirectAuth(organizationId, stamperInfo, authOptions);\n \n }\n } else {\n // Create app-wallet directly\n const tempClient = new PhantomClient(\n {\n apiBaseUrl: this.config.apiBaseUrl,\n organizationId: organizationId,\n },\n this.stamper,\n );\n\n const wallet = await tempClient.createWallet(`Wallet ${Date.now()}`);\n const walletId = wallet.walletId;\n\n // Save session with app-wallet info\n const now = Date.now();\n const session = {\n sessionId: generateSessionId(),\n walletId: walletId,\n organizationId: organizationId,\n stamperInfo,\n authProvider: \"app-wallet\",\n userInfo: { embeddedWalletType: this.config.embeddedWalletType },\n status: \"completed\" as const,\n createdAt: now,\n lastUsed: now,\n };\n await this.storage.saveSession(session);\n return session;\n }\n }\n\n /*\n * We use this method to handle JWT-based authentication for user-wallets.\n * It authenticates using the provided JWT token and creates a completed session.\n */\n private async handleJWTAuth(organizationId: string, stamperInfo: StamperInfo, authOptions: AuthOptions): Promise<Session> {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Using JWT authentication flow\");\n\n // Use JWT authentication flow\n if (!authOptions.jwtToken) {\n this.logger.error(\"EMBEDDED_PROVIDER\", \"JWT token missing for JWT authentication\");\n throw new Error(\"JWT token is required for JWT authentication\");\n }\n\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Starting JWT authentication\");\n const authResult = await this.jwtAuth.authenticate({\n organizationId: organizationId,\n parentOrganizationId: this.config.organizationId,\n jwtToken: authOptions.jwtToken,\n customAuthData: authOptions.customAuthData,\n });\n const walletId = authResult.walletId;\n this.logger.info(\"EMBEDDED_PROVIDER\", \"JWT authentication completed\", { walletId });\n\n // Save session with auth info\n const now = Date.now();\n const session = {\n sessionId: generateSessionId(),\n walletId: walletId,\n organizationId: organizationId,\n stamperInfo,\n authProvider: authResult.provider,\n userInfo: authResult.userInfo,\n status: \"completed\" as const,\n createdAt: now,\n lastUsed: now,\n };\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Saving JWT session\");\n await this.storage.saveSession(session);\n return session;\n }\n\n /*\n * We use this method to handle redirect-based authentication (Google/Apple OAuth).\n * It saves a temporary session before redirecting to prevent losing state during the redirect flow.\n * Session timestamp is updated before redirect to prevent race conditions.\n */\n private async handleRedirectAuth(organizationId: string, stamperInfo: StamperInfo, authOptions?: AuthOptions): Promise<Session | null> {\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Using Phantom Connect authentication flow (redirect-based)\", {\n provider: authOptions?.provider,\n hasRedirectUrl: !!this.config.authOptions?.redirectUrl,\n authUrl: this.config.authOptions?.authUrl,\n });\n\n // Use Phantom Connect authentication flow (redirect-based)\n // Store session before redirect so we can restore it after redirect\n const now = Date.now();\n const sessionId = generateSessionId();\n const tempSession: Session = {\n sessionId: sessionId,\n walletId: `temp-${now}`, // Temporary ID, will be updated after redirect\n organizationId: organizationId,\n stamperInfo,\n authProvider: \"phantom-connect\",\n userInfo: { provider: authOptions?.provider },\n status: \"pending\" as const,\n createdAt: now,\n lastUsed: now,\n };\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Saving temporary session before redirect\", {\n sessionId: tempSession.sessionId,\n tempWalletId: tempSession.walletId,\n });\n\n // Update session timestamp before redirect (prevents race condition)\n tempSession.lastUsed = Date.now();\n await this.storage.saveSession(tempSession);\n\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Starting Phantom Connect redirect\", {\n organizationId,\n parentOrganizationId: this.config.organizationId,\n provider: authOptions?.provider,\n authUrl: this.config.authOptions?.authUrl,\n });\n\n // Start the authentication flow (this will redirect the user in the browser, or handle it in React Native)\n const authResult = await this.authProvider.authenticate({\n organizationId: organizationId,\n parentOrganizationId: this.config.organizationId,\n provider: authOptions?.provider as \"google\" | \"apple\" | undefined,\n redirectUrl: this.config.authOptions?.redirectUrl,\n customAuthData: authOptions?.customAuthData,\n authUrl: this.config.authOptions?.authUrl,\n sessionId: sessionId,\n });\n\n if (authResult && \"walletId\" in authResult) {\n // If we got an auth result, we need to update the session with actual wallet ID\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Authentication completed after redirect\", {\n walletId: authResult.walletId,\n provider: authResult.provider,\n });\n\n // Update the temporary session with actual wallet ID and auth info\n tempSession.walletId = authResult.walletId;\n tempSession.authProvider = authResult.provider || tempSession.authProvider;\n tempSession.status = \"completed\";\n tempSession.lastUsed = Date.now();\n await this.storage.saveSession(tempSession);\n\n return tempSession; // Return the auth result for further processing\n }\n // If we don't have an auth result, it means we're in a redirect flow\n this.logger.info(\"EMBEDDED_PROVIDER\", \"Redirect authentication initiated, waiting for redirect completion\");\n // In this case, we don't return anything as the redirect will handle the rest\n return null;\n }\n\n private async completeAuthConnection(authResult: AuthResult): Promise<ConnectResult> {\n // Check if we have an existing session\n const session = await this.storage.getSession();\n\n if (!session) {\n throw new Error(\"No session found after redirect - session may have expired\");\n }\n\n // Update session with actual wallet ID and auth info from redirect\n session.walletId = authResult.walletId;\n session.authProvider = authResult.provider || session.authProvider;\n session.status = \"completed\";\n session.lastUsed = Date.now();\n await this.storage.saveSession(session);\n\n await this.initializeClientFromSession(session);\n\n return {\n walletId: this.walletId!,\n addresses: this.addresses,\n status: \"completed\",\n };\n }\n\n /*\n * We use this method to initialize the PhantomClient and fetch wallet addresses from a completed session.\n * This is the final step that sets up the provider's client state and retrieves available addresses.\n */\n private async initializeClientFromSession(session: Session): Promise<void> {\n // Create client from session\n this.logger.log(\"EMBEDDED_PROVIDER\", \"Initializing PhantomClient from session\", {\n organizationId: session.organizationId,\n walletId: session.walletId,\n });\n\n // Ensure stamper is initialized with existing keys\n if (!this.stamper.getKeyInfo()) {\n await this.stamper.init();\n }\n\n this.client = new PhantomClient(\n {\n apiBaseUrl: this.config.apiBaseUrl,\n organizationId: session.organizationId,\n },\n this.stamper,\n );\n\n this.walletId = session.walletId;\n\n // Get wallet addresses and filter by enabled address types with retry\n this.addresses = await this.getAndFilterWalletAddresses(session.walletId);\n }\n}\n","import type { AuthResult, JWTAuthOptions } from \"../interfaces\";\n\nexport class JWTAuth {\n async authenticate(options: JWTAuthOptions): Promise<AuthResult> {\n // Validate JWT token format\n if (!options.jwtToken || typeof options.jwtToken !== \"string\") {\n throw new Error(\"Invalid JWT token: token must be a non-empty string\");\n }\n\n // Basic JWT format validation (3 parts separated by dots)\n const jwtParts = options.jwtToken.split(\".\");\n if (jwtParts.length !== 3) {\n throw new Error(\"Invalid JWT token format: token must have 3 parts separated by dots\");\n }\n\n // JWT authentication flow - direct API call to create wallet with JWT\n try {\n // This would typically make an API call to your backend\n // which would validate the JWT and create/retrieve the wallet\n const response = await fetch(\"/api/auth/jwt\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${options.jwtToken}`,\n },\n body: JSON.stringify({\n organizationId: options.organizationId,\n parentOrganizationId: options.parentOrganizationId,\n customAuthData: options.customAuthData,\n }),\n });\n\n if (!response.ok) {\n let errorMessage = `HTTP ${response.status}`;\n try {\n const errorData = await response.json();\n errorMessage = errorData.message || errorData.error || errorMessage;\n } catch {\n errorMessage = response.statusText || errorMessage;\n }\n\n switch (response.status) {\n case 400:\n throw new Error(`Invalid JWT authentication request: ${errorMessage}`);\n case 401:\n throw new Error(`JWT token is invalid or expired: ${errorMessage}`);\n case 403:\n throw new Error(`JWT authentication forbidden: ${errorMessage}`);\n case 404:\n throw new Error(`JWT authentication endpoint not found: ${errorMessage}`);\n case 429:\n throw new Error(`Too many JWT authentication requests: ${errorMessage}`);\n case 500:\n case 502:\n case 503:\n case 504:\n throw new Error(`JWT authentication server error: ${errorMessage}`);\n default:\n throw new Error(`JWT authentication failed: ${errorMessage}`);\n }\n }\n\n let result;\n try {\n result = await response.json();\n } catch (parseError) {\n throw new Error(\"Invalid response from JWT authentication server: response is not valid JSON\");\n }\n\n if (!result.walletId) {\n throw new Error(\"Invalid JWT authentication response: missing walletId\");\n }\n\n return {\n walletId: result.walletId,\n provider: \"jwt\",\n userInfo: result.userInfo || {},\n };\n } catch (error) {\n if (error instanceof TypeError && error.message.includes(\"fetch\")) {\n throw new Error(\"JWT authentication failed: network error or invalid endpoint\");\n }\n\n if (error instanceof Error) {\n throw error; // Re-throw known errors\n }\n\n throw new Error(`JWT authentication error: ${String(error)}`);\n }\n }\n}\n","export function generateSessionId(): string {\n return (\n \"session_\" +\n Math.random().toString(36).substring(2, 15) +\n Math.random().toString(36).substring(2, 15) +\n \"_\" +\n Date.now()\n );\n}\n","import type { DebugLogger } from \"../interfaces\";\n\nexport async function retryWithBackoff<T>(\n operation: () => Promise<T>,\n operationName: string,\n logger: DebugLogger,\n maxRetries: number = 3,\n baseDelay: number = 1000,\n): Promise<T> {\n let lastError: Error;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n logger.log(\"EMBEDDED_PROVIDER\", `Attempting ${operationName}`, {\n attempt,\n maxRetries,\n });\n return await operation();\n } catch (error) {\n lastError = error as Error;\n logger.warn(\"EMBEDDED_PROVIDER\", `${operationName} failed`, {\n attempt,\n maxRetries,\n error: error instanceof Error ? error.message : String(error),\n });\n\n if (attempt === maxRetries) {\n logger.error(\"EMBEDDED_PROVIDER\", `${operationName} failed after ${maxRetries} attempts`, {\n finalError: error instanceof Error ? error.message : String(error),\n });\n break;\n }\n\n // Exponential backoff: 1s, 2s, 4s\n const delay = baseDelay * Math.pow(2, attempt - 1);\n logger.log(\"EMBEDDED_PROVIDER\", `Retrying ${operationName} in ${delay}ms`, {\n attempt: attempt + 1,\n delay,\n });\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n }\n\n throw lastError!;\n}\n"],"mappings":";AAAA,SAAS,qBAAqB;AAE9B,SAAS,cAAc,kBAAkB,0BAA0B,gCAAyF;;;ACArJ,IAAM,UAAN,MAAc;AAAA,EACnB,MAAM,aAAa,SAA8C;AAE/D,QAAI,CAAC,QAAQ,YAAY,OAAO,QAAQ,aAAa,UAAU;AAC7D,YAAM,IAAI,MAAM,qDAAqD;AAA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G,WAAO;AAAA,EACT;AAAA,EAEA,MAAc,uBAAuB,YAAgD;AAEnF,UAAM,UAAU,MAAM,KAAK,QAAQ,WAAW;AAE9C,QAAI,CAAC,SAAS;AACZ,YAAM,IAAI,MAAM,4DAA4D;AAAA,IAC9E;AAGA,YAAQ,WAAW,WAAW;AAC9B,YAAQ,eAAe,WAAW,YAAY,QAAQ;AACtD,YAAQ,SAAS;AACjB,YAAQ,WAAW,KAAK,IAAI;AAC5B,UAAM,KAAK,QAAQ,YAAY,OAAO;AAEtC,UAAM,KAAK,4BAA4B,OAAO;AAE9C,WAAO;AAAA,MACL,UAAU,KAAK;AAAA,MACf,WAAW,KAAK;AAAA,MAChB,QAAQ;AAAA,IACV;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,4BAA4B,SAAiC;AAEzE,SAAK,OAAO,IAAI,qBAAqB,2CAA2C;AAAA,MAC9E,gBAAgB,QAAQ;AAAA,MACxB,UAAU,QAAQ;AAAA,IACpB,CAAC;AAGD,QAAI,CAAC,KAAK,QAAQ,WAAW,GAAG;AAC9B,YAAM,KAAK,QAAQ,KAAK;AAAA,IAC1B;AAEA,SAAK,SAAS,IAAI;AAAA,MAChB;AAAA,QACE,YAAY,KAAK,OAAO;AAAA,QACxB,gBAAgB,QAAQ;AAAA,MAC1B;AAAA,MACA,KAAK;AAAA,IACP;AAEA,SAAK,WAAW,QAAQ;AAGxB,SAAK,YAAY,MAAM,KAAK,4BAA4B,QAAQ,QAAQ;AAAA,EAC1E;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@phantom/embedded-provider-core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Platform-agnostic embedded provider core logic for Phantom Wallet SDK",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"test": "jest",
|
|
25
25
|
"test:watch": "jest --watch",
|
|
26
26
|
"lint": "tsc --noEmit && eslint --cache . --ext .ts,.tsx",
|
|
27
|
-
"
|
|
27
|
+
"check-types": "tsc --noEmit",
|
|
28
28
|
"prettier": "prettier --write \"src/**/*.{ts,tsx}\""
|
|
29
29
|
},
|
|
30
30
|
"keywords": [
|
|
@@ -39,9 +39,11 @@
|
|
|
39
39
|
"author": "Phantom",
|
|
40
40
|
"license": "MIT",
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@phantom/api-key-stamper": "0.1.
|
|
43
|
-
"@phantom/client": "0.1.
|
|
44
|
-
"@phantom/
|
|
42
|
+
"@phantom/api-key-stamper": "^0.1.2",
|
|
43
|
+
"@phantom/client": "^0.1.5",
|
|
44
|
+
"@phantom/constants": "^0.0.2",
|
|
45
|
+
"@phantom/parsers": "^0.0.5",
|
|
46
|
+
"@phantom/sdk-types": "^0.1.1"
|
|
45
47
|
},
|
|
46
48
|
"devDependencies": {
|
|
47
49
|
"@types/jest": "^29.5.5",
|