-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathcontroller.ts
More file actions
849 lines (729 loc) · 23.5 KB
/
controller.ts
File metadata and controls
849 lines (729 loc) · 23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
import { AsyncMethodReturns } from "@cartridge/penpal";
import { Policy } from "@cartridge/presets";
import { StarknetInjectedWallet } from "@starknet-io/get-starknet-wallet-standard";
import type { WalletWithStarknetFeatures } from "@starknet-io/get-starknet-wallet-standard/features";
import {
AddInvokeTransactionResult,
AddStarknetChainParameters,
ChainId,
} from "@starknet-io/types-js";
import { constants, shortString, WalletAccount } from "starknet";
import { version } from "../package.json";
import ControllerAccount from "./account";
import { KEYCHAIN_URL } from "./constants";
import { HeadlessAuthenticationError, NotReadyToConnect } from "./errors";
import { KeychainIFrame } from "./iframe";
import BaseProvider from "./provider";
import { lookupUsername as lookupUsernameApi } from "./lookup";
import {
AuthOptions,
Chain,
ConnectError,
ConnectReply,
ConnectOptions,
ControllerOptions,
IFrames,
Keychain,
ProbeReply,
ProfileContextTypeVariant,
ResponseCodes,
OpenOptions,
HeadlessUsernameLookupResult,
StarterpackOptions,
} from "./types";
import { validateRedirectUrl } from "./url-validator";
import { parseChainId } from "./utils";
export default class ControllerProvider extends BaseProvider {
private keychain?: AsyncMethodReturns<Keychain>;
private options: ControllerOptions;
private iframes?: IFrames;
private selectedChain: ChainId;
private chains: Map<ChainId, Chain>;
private referral: { ref?: string; refGroup?: string };
private encryptedBlob?: string;
isReady(): boolean {
return !!this.keychain;
}
constructor(options: ControllerOptions = {}) {
super();
// Default Cartridge chains that are always available
const cartridgeChains: Chain[] = [
{ rpcUrl: "https://api.cartridge.gg/x/starknet/sepolia/rpc/v0_9" },
{ rpcUrl: "https://api.cartridge.gg/x/starknet/mainnet/rpc/v0_9" },
];
// Merge user chains with default chains
// User chains take precedence if they specify the same network
const chains = [...cartridgeChains, ...(options.chains || [])];
const defaultChainId =
options.defaultChainId || constants.StarknetChainId.SN_MAIN;
this.selectedChain = defaultChainId;
this.chains = new Map<ChainId, Chain>();
// Auto-extract referral parameters from URL
// This allows games to pass referrals via their own URL: game.com/?ref=alice&ref_group=campaign1
const urlParams =
typeof window !== "undefined"
? new URLSearchParams(window.location.search)
: null;
this.referral = {
ref: urlParams?.get("ref") ?? undefined,
refGroup: urlParams?.get("ref_group") ?? undefined,
};
this.options = { ...options, chains, defaultChainId };
// Auto-detect and set lastUsedConnector from URL parameter
// This is set by the keychain after redirect flow completion
if (typeof window !== "undefined" && typeof localStorage !== "undefined") {
// Check our dedicated parameter to detect return from standalone auth flow
const standaloneParam = urlParams?.get("controller_standalone");
if (standaloneParam === "1") {
// Store a flag in sessionStorage so lazy-loaded iframes can detect this
// Use sessionStorage instead of localStorage to avoid cross-tab issues
sessionStorage.setItem("controller_standalone", "1");
}
// Also handle lastUsedConnector for backwards compatibility
const lastUsedConnector = urlParams?.get("lastUsedConnector");
if (lastUsedConnector) {
localStorage.setItem("lastUsedConnector", lastUsedConnector);
}
// Extract encrypted blob from URL fragment (#kc=...)
// This contains the encrypted localStorage snapshot from keychain
if (window.location.hash) {
const hashParams = new URLSearchParams(window.location.hash.slice(1));
const encryptedBlob = hashParams.get("kc");
if (encryptedBlob) {
// Store encrypted blob as class variable to pass to iframe
this.encryptedBlob = encryptedBlob;
}
}
// Clean up the URL by removing controller flow parameters
if (urlParams && window.history?.replaceState) {
let needsCleanup = false;
if (standaloneParam) {
urlParams.delete("controller_standalone");
needsCleanup = true;
}
if (lastUsedConnector) {
urlParams.delete("lastUsedConnector");
needsCleanup = true;
}
// Also clean up the fragment if it contains our encrypted blob
let cleanHash = window.location.hash;
if (cleanHash) {
const hashParams = new URLSearchParams(cleanHash.slice(1));
if (hashParams.has("kc")) {
hashParams.delete("kc");
cleanHash = hashParams.toString()
? `#${hashParams.toString()}`
: "";
needsCleanup = true;
}
}
if (needsCleanup) {
const newUrl =
window.location.pathname +
(urlParams.toString() ? "?" + urlParams.toString() : "") +
cleanHash;
window.history.replaceState({}, "", newUrl);
}
}
}
this.initializeChains(chains);
this.iframes = {
keychain: options.lazyload ? undefined : this.createKeychainIframe(),
};
if (typeof window !== "undefined") {
(window as any).starknet_controller = this;
}
}
async logout() {
if (!this.keychain) {
console.error(new NotReadyToConnect().message);
return;
}
try {
// Disconnect the controller/keychain first
await this.disconnect();
// Close all controller iframes
const iframes = document.querySelectorAll('iframe[id^="controller-"]');
iframes.forEach((iframe) => {
const container = iframe.parentElement;
if (container) {
// Start fade-out transition
container.style.opacity = "0";
// Set display: none after transition completes
setTimeout(() => {
container.style.display = "none";
}, 200);
}
});
// Reset body overflow
if (document.body) {
document.body.style.overflow = "auto";
}
// Reload the page to complete logout
window.location.reload();
} catch (err) {
console.error("Logout failed:", err);
throw err;
}
}
async probe(): Promise<WalletAccount | undefined> {
if (!this.iframes) {
return;
}
try {
// Ensure iframe is created if using lazy loading
if (!this.iframes.keychain) {
this.iframes.keychain = this.createKeychainIframe();
}
await this.waitForKeychain();
if (!this.keychain) {
console.error(new NotReadyToConnect().message);
return;
}
const response = (await this.keychain.probe(this.rpcUrl())) as ProbeReply;
// For backwards compat with controller <=0.6.0
let rpcUrl = response?.rpcUrl || this.rpcUrl();
this.account = new ControllerAccount(
this,
rpcUrl,
response.address,
this.keychain,
this.options,
this.iframes.keychain,
);
} catch (e) {
console.error(e);
return;
}
return this.account;
}
async connect(
options?: AuthOptions | ConnectOptions,
): Promise<WalletAccount | undefined> {
const connectOptions = Array.isArray(options) ? undefined : options;
const headless =
connectOptions?.username && connectOptions?.signer
? {
username: connectOptions.username,
signer: connectOptions.signer,
password: connectOptions.password,
}
: undefined;
if (!this.iframes) {
return;
}
if (this.account) {
return this.account;
}
// Ensure iframe is created if using lazy loading
if (!this.iframes.keychain) {
this.iframes.keychain = this.createKeychainIframe();
}
// Always wait for the keychain connection to be established
await this.waitForKeychain();
if (!this.keychain || !this.iframes.keychain) {
console.error(new NotReadyToConnect().message);
return;
}
try {
if (headless) {
// Headless auth should not open the UI until the keychain determines
// user interaction is required (e.g. session approval).
const response = await this.keychain.connect({
username: headless.username,
signer: headless.signer,
password: headless.password,
});
if (response.code !== ResponseCodes.SUCCESS) {
throw new HeadlessAuthenticationError(
"message" in response && response.message
? response.message
: "Headless authentication failed",
);
}
// Keychain will call onSessionCreated (awaitable) during headless connect,
// which probes and updates this.account. Keep a fallback for older keychains.
if (this.account) {
return this.account;
}
const address =
"address" in response && response.address ? response.address : null;
if (!address) {
throw new HeadlessAuthenticationError(
"Headless authentication failed",
);
}
this.account = new ControllerAccount(
this,
this.rpcUrl(),
address,
this.keychain,
this.options,
this.iframes.keychain,
);
this.emitAccountsChanged([address]);
return this.account;
}
// Only open modal if NOT headless
this.iframes.keychain.open();
// Use connect() parameter if provided, otherwise fall back to constructor options
const effectiveOptions = Array.isArray(options)
? options
: (connectOptions?.signupOptions ?? this.options.signupOptions);
// Pass options to keychain
let response = await this.keychain.connect({
signupOptions: effectiveOptions,
});
if (response.code !== ResponseCodes.SUCCESS) {
throw new Error(response.message);
}
response = response as ConnectReply;
this.account = new ControllerAccount(
this,
this.rpcUrl(),
response.address,
this.keychain,
this.options,
this.iframes.keychain,
);
return this.account;
} catch (e) {
if (headless) {
if (e instanceof HeadlessAuthenticationError) {
throw e;
}
const message =
e instanceof Error
? e.message
: typeof e === "object" && e && "message" in e
? String((e as any).message)
: "Headless authentication failed";
throw new HeadlessAuthenticationError(message);
}
console.log(e);
} finally {
// Only close modal if it was opened (not headless)
if (!headless) {
this.iframes.keychain.close();
}
}
}
async switchStarknetChain(chainId: string): Promise<boolean> {
if (!this.iframes) {
return false;
}
if (!this.keychain || !this.iframes.keychain) {
console.error(new NotReadyToConnect().message);
return false;
}
const currentChain = this.selectedChain;
try {
this.selectedChain = chainId;
await this.keychain.switchChain(this.rpcUrl());
} catch (e) {
console.error(e);
this.selectedChain = currentChain;
return false;
}
this.emitNetworkChanged(chainId);
return true;
}
addStarknetChain(_chain: AddStarknetChainParameters): Promise<boolean> {
return Promise.resolve(true);
}
async disconnect() {
this.account = undefined;
this.emitAccountsChanged([]);
try {
if (typeof localStorage !== "undefined") {
localStorage.removeItem("lastUsedConnector");
for (let i = localStorage.length - 1; i >= 0; i--) {
const key = localStorage.key(i);
if (key?.startsWith("@cartridge/")) {
localStorage.removeItem(key);
}
}
}
} catch {
// Ignore environments where localStorage is unavailable.
}
if (!this.keychain) {
console.error(new NotReadyToConnect().message);
return;
}
return this.keychain.disconnect();
}
async openProfile(tab: ProfileContextTypeVariant = "inventory") {
if (!this.iframes) {
return;
}
// Profile functionality is now integrated into keychain
// Navigate keychain iframe to profile page
if (!this.keychain || !this.iframes.keychain) {
console.error(new NotReadyToConnect().message);
return;
}
if (!this.account) {
console.error("Account is not ready");
return;
}
const username = await this.keychain.username();
// Navigate first, then open to avoid flash
const options = [];
if (this.options.slot) {
options.push(`ps=${this.options.slot}`);
}
await this.keychain.navigate(
`/account/${username}/${tab}?${options.join("&")}`,
);
this.iframes.keychain.open();
}
async openProfileTo(to: string) {
if (!this.iframes) {
return;
}
// Profile functionality is now integrated into keychain
if (!this.keychain || !this.iframes.keychain) {
console.error(new NotReadyToConnect().message);
return;
}
if (!this.account) {
console.error("Account is not ready");
return;
}
const username = await this.keychain.username();
const options = [];
if (this.options.slot) {
options.push(`ps=${this.options.slot}`);
}
await this.keychain.navigate(
`/account/${username}/${to}?${options.join("&")}`,
);
this.iframes.keychain.open();
}
async openProfileAt(at: string) {
if (!this.iframes) {
return;
}
// Profile functionality is now integrated into keychain
if (!this.keychain || !this.iframes.keychain) {
console.error(new NotReadyToConnect().message);
return;
}
if (!this.account) {
console.error("Account is not ready");
return;
}
await this.keychain.navigate(at);
this.iframes.keychain.open();
}
openSettings() {
if (!this.iframes) {
return;
}
if (!this.keychain || !this.iframes.keychain) {
console.error(new NotReadyToConnect().message);
return;
}
this.iframes.keychain.open();
this.keychain.openSettings();
}
async close() {
if (!this.iframes || !this.iframes.keychain) {
return;
}
this.iframes.keychain.close();
}
revoke(origin: string, _policy: Policy[]) {
if (!this.keychain) {
console.error(new NotReadyToConnect().message);
return null;
}
return this.keychain.revoke(origin);
}
rpcUrl(): string {
const chain = this.chains.get(this.selectedChain);
if (!chain) {
const availableChains = Array.from(this.chains.keys()).map((chain) =>
shortString.decodeShortString(chain),
);
throw new Error(
`Chain not found: ${shortString.decodeShortString(this.selectedChain)}. Available chains: ${availableChains.join(", ")}`,
);
}
return chain.rpcUrl;
}
username() {
if (!this.keychain) {
console.error(new NotReadyToConnect().message);
return;
}
return this.keychain.username();
}
async lookupUsername(
username: string,
): Promise<HeadlessUsernameLookupResult> {
const trimmed = username.trim();
if (!trimmed) {
throw new Error("Username is required");
}
return lookupUsernameApi(trimmed, this.selectedChain);
}
openPurchaseCredits() {
if (!this.iframes) {
return;
}
if (!this.keychain || !this.iframes.keychain) {
console.error(new NotReadyToConnect().message);
return;
}
this.keychain.navigate("/purchase/credits").then(() => {
this.iframes!.keychain?.open();
});
}
async openStarterPack(
id: string | number,
options?: StarterpackOptions,
): Promise<void> {
if (!this.iframes) {
return;
}
if (!this.keychain || !this.iframes.keychain) {
console.error(new NotReadyToConnect().message);
return;
}
const { onPurchaseComplete, ...starterpackOptions } = options ?? {};
this.iframes.keychain.setOnStarterpackPlay(onPurchaseComplete);
const sanitizedOptions =
Object.keys(starterpackOptions).length > 0
? (starterpackOptions as Omit<StarterpackOptions, "onPurchaseComplete">)
: undefined;
await this.keychain.openStarterPack(id, sanitizedOptions);
this.iframes.keychain?.open();
}
async openExecute(calls: any, chainId?: string) {
if (!this.iframes) {
return;
}
if (!this.keychain || !this.iframes.keychain) {
console.error(new NotReadyToConnect().message);
return;
}
// Switch to the chain if provided
let currentChainId = this.selectedChain;
if (chainId) {
this.switchStarknetChain(chainId);
}
// Open keychain
this.iframes.keychain.open();
// Invoke execute
const res = await this.keychain.execute(calls, undefined, undefined, true);
// Close keychain
this.iframes.keychain.close();
// Switch back to the original chain
if (chainId) {
this.switchStarknetChain(currentChainId);
}
const status = !(
res &&
((res as ConnectError).code === ResponseCodes.NOT_CONNECTED ||
(res as ConnectError).code === ResponseCodes.CANCELED)
);
return {
status,
transactionHash: (res as AddInvokeTransactionResult)?.transaction_hash,
};
}
async delegateAccount() {
if (!this.keychain) {
console.error(new NotReadyToConnect().message);
return null;
}
return await this.keychain.delegateAccount();
}
/**
* Returns a wallet standard interface for the controller.
* This allows using the controller with libraries that expect the wallet standard interface.
*/
asWalletStandard(): WalletWithStarknetFeatures {
if (typeof window !== "undefined") {
console.warn(
`Casting Controller to WalletWithStarknetFeatures is an experimental feature. ` +
`Please report any issues at https://github.com/cartridge-gg/controller/issues`,
);
}
const controller = this;
const inner = new StarknetInjectedWallet(controller);
// Override disconnect to also disconnect controller
const disconnect = {
"standard:disconnect": {
version: "1.0.0" as const,
disconnect: async () => {
await inner.features["standard:disconnect"].disconnect();
await controller.disconnect();
},
},
};
return {
get version() {
return inner.version;
},
get name() {
return inner.name;
},
get icon() {
return inner.icon;
},
get chains() {
return inner.chains;
},
get accounts() {
return inner.accounts;
},
get features() {
return { ...inner.features, ...disconnect };
},
};
}
/**
* Opens the keychain in standalone mode (first-party context) for authentication.
* This establishes first-party storage, enabling seamless iframe access across all games.
* @param options - Configuration for redirect after authentication
*/
open(options: OpenOptions = {}) {
if (typeof window === "undefined") {
console.error("open can only be called in browser context");
return;
}
const keychainUrl = new URL(this.options.url || KEYCHAIN_URL);
// Add redirect target (defaults to current page)
const redirectUrl = options.redirectUrl || window.location.href;
// Validate redirect URL to prevent XSS and open redirect attacks
const validation = validateRedirectUrl(redirectUrl);
if (!validation.isValid) {
console.error(
`Invalid redirect URL: ${validation.error}`,
`URL: ${redirectUrl}`,
);
return;
}
keychainUrl.searchParams.set("redirect_url", redirectUrl);
// Add preset if provided
if (this.options.preset) {
keychainUrl.searchParams.set("preset", this.options.preset);
}
// Add controller configuration parameters
if (this.options.slot) {
keychainUrl.searchParams.set("ps", this.options.slot);
}
if (this.options.namespace) {
keychainUrl.searchParams.set("ns", this.options.namespace);
}
if (this.options.tokens?.erc20) {
keychainUrl.searchParams.set(
"erc20",
this.options.tokens.erc20.toString(),
);
}
if (this.rpcUrl()) {
keychainUrl.searchParams.set("rpc_url", this.rpcUrl());
}
// Navigate to standalone keychain
window.location.href = keychainUrl.toString();
}
private initializeChains(chains: Chain[]) {
for (const chain of chains) {
try {
const url = new URL(chain.rpcUrl);
const chainId = parseChainId(url);
this.chains.set(chainId, chain);
} catch (error) {
console.error(`Failed to parse chainId for ${chain.rpcUrl}:`, error);
throw error; // Re-throw to ensure invalid chains fail fast
}
}
if (!this.chains.has(this.selectedChain)) {
console.warn(
`Selected chain ${this.selectedChain} not found in configured chains. ` +
`Available chains: ${Array.from(this.chains.keys()).join(", ")}`,
);
}
}
private createKeychainIframe(): KeychainIFrame {
// Check if we're returning from standalone auth flow
const isReturningFromRedirect =
typeof window !== "undefined" &&
typeof sessionStorage !== "undefined" &&
sessionStorage.getItem("controller_standalone") === "1";
// Extract username from URL if present (passed from keychain after auth)
const urlParams =
typeof window !== "undefined"
? new URLSearchParams(window.location.search)
: undefined;
const username = urlParams?.get("username") ?? undefined;
// Extract encrypted blob from class variable (stored during URL parsing)
const encryptedBlob = this.encryptedBlob;
// Clear the flag after detecting it
if (isReturningFromRedirect) {
sessionStorage.removeItem("controller_standalone");
}
// Clear encrypted blob after using it
if (encryptedBlob) {
this.encryptedBlob = undefined;
}
const iframe = new KeychainIFrame({
...this.options,
rpcUrl: this.rpcUrl(),
onClose: () => {
this.keychain?.reset?.();
},
onConnect: (keychain) => {
this.keychain = keychain;
},
version: version,
ref: this.referral.ref,
refGroup: this.referral.refGroup,
needsSessionCreation: isReturningFromRedirect,
encryptedBlob: encryptedBlob ?? undefined,
username: username,
onSessionCreated: async () => {
const previousAddress = this.account?.address;
const account = await this.probe();
if (account?.address && account.address !== previousAddress) {
this.emitAccountsChanged([account.address]);
}
},
});
// If we're returning from redirect, open the modal immediately to show session creation prompt
if (isReturningFromRedirect) {
// Open after a short delay to ensure iframe is ready
setTimeout(() => {
iframe.open();
}, 100);
}
return iframe;
}
private waitForKeychain({
timeout = 50000,
interval = 100,
}:
| {
timeout?: number;
interval?: number;
}
| undefined = {}) {
return new Promise<void>((resolve, reject) => {
const startTime = Date.now();
const id = setInterval(() => {
if (Date.now() - startTime > timeout) {
clearInterval(id);
reject(new Error("Timeout waiting for keychain"));
return;
}
if (!this.keychain) return;
clearInterval(id);
resolve();
}, interval);
});
}
}