@beaconmcu/auth 0.1.5 → 0.1.7

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.cjs CHANGED
@@ -23,8 +23,14 @@ var isNetworkId = (value) => value === "testnet" || value === "mainnet";
23
23
  // src/shared/messages.ts
24
24
  var ErrorCode = {
25
25
  INTERNAL: -1,
26
+ // internal wallet error
27
+ EXTERNAL: -2,
26
28
  // an outside service (Horizon, network) failed
27
29
  INVALID_REQUEST: -3,
30
+ // bad parameters, malformed XDR, wrong network
31
+ USER_REJECTED: -4,
32
+ // the user said no: do not retry
33
+ NOT_CONNECTED: -5,
28
34
  // log in first
29
35
  UNSUPPORTED: -6};
30
36
  var isObject = (v) => typeof v === "object" && v !== null;
@@ -80,6 +86,7 @@ var WalletConnection = class {
80
86
  // the frame was opened before the wallet asked for it (it was still loading)
81
87
  this.pending = /* @__PURE__ */ new Map();
82
88
  this.isReady = false;
89
+ this.authMethods = [];
83
90
  this.readyWaiters = [];
84
91
  // ---- incoming messages ----
85
92
  this.onMessage = (event) => {
@@ -89,6 +96,7 @@ var WalletConnection = class {
89
96
  const message = event.data;
90
97
  switch (message.type) {
91
98
  case "beacon:ready":
99
+ this.authMethods = Array.isArray(message.authMethods) ? message.authMethods.filter((m) => typeof m === "string") : [];
92
100
  this.isReady = true;
93
101
  this.readyWaiters.splice(0).forEach((resolve) => resolve());
94
102
  break;
@@ -228,6 +236,11 @@ var WalletConnection = class {
228
236
  this.readyWaiters.push(onReady);
229
237
  });
230
238
  }
239
+ /** The sign-in methods the app turned on in the dashboard (waits for the wallet to load). */
240
+ async signInMethods() {
241
+ await this.whenReady();
242
+ return this.authMethods;
243
+ }
231
244
  async request(method, params, timeoutMs) {
232
245
  if (typeof window === "undefined") throw internalError("Beacon can only be used in a browser");
233
246
  if (!this.isReady && INTERACTIVE_METHODS.has(method)) this.openEarly();
@@ -314,6 +327,245 @@ function createWalletInterface(beacon) {
314
327
  };
315
328
  }
316
329
 
330
+ // src/wallets/registry.ts
331
+ var WALLET_LOADERS = [
332
+ async () => new (await import('@creit.tech/stellar-wallets-kit/modules/xbull')).xBullModule(),
333
+ async () => new (await import('@creit.tech/stellar-wallets-kit/modules/varial')).VarialModule(),
334
+ // Freighter, now called Varial
335
+ async () => new (await import('@creit.tech/stellar-wallets-kit/modules/lobstr')).LobstrModule(),
336
+ async () => new (await import('@creit.tech/stellar-wallets-kit/modules/hana')).HanaModule(),
337
+ async () => new (await import('@creit.tech/stellar-wallets-kit/modules/albedo')).AlbedoModule(),
338
+ async () => new (await import('@creit.tech/stellar-wallets-kit/modules/rabet')).RabetModule()
339
+ ];
340
+
341
+ // src/wallets/external.ts
342
+ var AVAILABLE_TIMEOUT_MS = 1500;
343
+ function toBeaconError(error, fallback) {
344
+ if (error instanceof BeaconError) return error;
345
+ const e = error;
346
+ const code = typeof e?.code === "number" ? e.code : typeof e?.error?.code === "number" ? e.error.code : void 0;
347
+ const raw = typeof e?.message === "string" ? e.message : typeof e?.error?.message === "string" ? e.error.message : "";
348
+ const rejected = code === ErrorCode.USER_REJECTED || /reject|denied|declin|cancel/i.test(raw);
349
+ if (rejected) return new BeaconError(ErrorCode.USER_REJECTED, "The request was cancelled in the wallet.");
350
+ return new BeaconError(ErrorCode.EXTERNAL, raw || fallback);
351
+ }
352
+ var ExternalWallets = class {
353
+ constructor() {
354
+ this.modules = null;
355
+ this.active = null;
356
+ }
357
+ load() {
358
+ this.modules ?? (this.modules = Promise.all(WALLET_LOADERS.map((load) => load())));
359
+ return this.modules;
360
+ }
361
+ /** The wallets to show (name, icon, link). Quick: it does not check what is installed. */
362
+ async list() {
363
+ return (await this.load()).map((m) => ({ id: m.productId, name: m.productName, icon: m.productIcon, url: m.productUrl }));
364
+ }
365
+ /** Is this wallet installed in this browser? Checked one wallet at a time, so slow ones do not hold up the rest. */
366
+ async installed(id) {
367
+ const wallet = (await this.load()).find((m) => m.productId === id);
368
+ if (!wallet) return false;
369
+ return Promise.race([
370
+ wallet.isAvailable().catch(() => false),
371
+ new Promise((resolve) => setTimeout(() => resolve(false), AVAILABLE_TIMEOUT_MS))
372
+ ]);
373
+ }
374
+ /** Loads the wallet code and icons ahead of time, so the sign-in window opens with its list ready. */
375
+ async preload() {
376
+ const wallets = await this.list();
377
+ if (typeof Image === "undefined") return;
378
+ wallets.forEach((w) => new Image().src = w.icon);
379
+ }
380
+ /** Asks the wallet to share its address (the wallet shows its own approval). */
381
+ async connect(id) {
382
+ const wallet = (await this.load()).find((m) => m.productId === id);
383
+ if (!wallet) throw new BeaconError(ErrorCode.INVALID_REQUEST, `Unknown wallet "${id}".`);
384
+ try {
385
+ const { address } = await wallet.getAddress();
386
+ if (!address) throw new Error("The wallet did not return an address.");
387
+ this.active = wallet;
388
+ return address;
389
+ } catch (e) {
390
+ throw toBeaconError(e, "Could not connect to the wallet.");
391
+ }
392
+ }
393
+ get connected() {
394
+ return this.active !== null;
395
+ }
396
+ disconnect() {
397
+ this.active = null;
398
+ }
399
+ wallet() {
400
+ if (!this.active) throw new BeaconError(ErrorCode.NOT_CONNECTED, "No wallet is connected.");
401
+ return this.active;
402
+ }
403
+ async signTransaction(xdr, opts) {
404
+ try {
405
+ const r = await this.wallet().signTransaction(xdr, opts);
406
+ return { signedTxXdr: r.signedTxXdr, signerAddress: r.signerAddress ?? opts.address ?? "" };
407
+ } catch (e) {
408
+ throw toBeaconError(e, "The wallet could not sign the transaction.");
409
+ }
410
+ }
411
+ async signMessage(message, opts) {
412
+ const w = this.wallet();
413
+ if (!w.signMessage) throw new BeaconError(ErrorCode.UNSUPPORTED, `${w.productName} cannot sign messages.`);
414
+ try {
415
+ const r = await w.signMessage(message, opts);
416
+ return { signedMessage: r.signedMessage, signerAddress: r.signerAddress ?? opts.address ?? "" };
417
+ } catch (e) {
418
+ throw toBeaconError(e, "The wallet could not sign the message.");
419
+ }
420
+ }
421
+ async signAuthEntry(entry, opts) {
422
+ const w = this.wallet();
423
+ if (!w.signAuthEntry) throw new BeaconError(ErrorCode.UNSUPPORTED, `${w.productName} cannot sign authorization entries.`);
424
+ try {
425
+ const r = await w.signAuthEntry(entry, opts);
426
+ return { signedAuthEntry: r.signedAuthEntry, signerAddress: r.signerAddress ?? opts.address ?? "" };
427
+ } catch (e) {
428
+ throw toBeaconError(e, "The wallet could not sign the authorization entry.");
429
+ }
430
+ }
431
+ };
432
+
433
+ // src/wallets/picker.ts
434
+ var FONT = 'Inter, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif';
435
+ var SKELETON_ROWS = 5;
436
+ function el(tag, style = {}, text) {
437
+ const node = document.createElement(tag);
438
+ Object.assign(node.style, style);
439
+ if (text !== void 0) node.textContent = text;
440
+ return node;
441
+ }
442
+ var GOOGLE_G = '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path fill="#4285F4" d="M23.5 12.3c0-.8-.1-1.6-.2-2.3H12v4.5h6.5a5.6 5.6 0 0 1-2.4 3.7v3h3.9c2.3-2.1 3.5-5.2 3.5-8.9z"/><path fill="#34A853" d="M12 24c3.2 0 6-1.1 7.9-2.9l-3.9-3c-1.1.7-2.5 1.2-4 1.2-3.1 0-5.7-2.1-6.6-4.9H1.4v3.1A12 12 0 0 0 12 24z"/><path fill="#FBBC05" d="M5.4 14.4a7.2 7.2 0 0 1 0-4.8V6.5H1.4a12 12 0 0 0 0 11z"/><path fill="#EA4335" d="M12 4.8c1.8 0 3.3.6 4.6 1.8l3.4-3.4A12 12 0 0 0 1.4 6.5l4 3.1C6.3 6.9 8.9 4.8 12 4.8z"/></svg>';
443
+ var rowStyle = {
444
+ display: "flex",
445
+ alignItems: "center",
446
+ gap: "12px",
447
+ width: "100%",
448
+ height: "48px",
449
+ flexShrink: "0",
450
+ boxSizing: "border-box",
451
+ padding: "0 12px",
452
+ border: "1px solid #e5e7eb",
453
+ borderRadius: "12px",
454
+ background: "#fff",
455
+ color: "#111827",
456
+ font: `500 15px ${FONT}`,
457
+ textAlign: "left",
458
+ cursor: "pointer"
459
+ };
460
+ function skeletonRow() {
461
+ const row = el("div", { ...rowStyle, cursor: "default", borderColor: "#f3f4f6" });
462
+ row.appendChild(el("div", { width: "28px", height: "28px", borderRadius: "8px", background: "#f3f4f6", flexShrink: "0" }));
463
+ row.appendChild(el("div", { width: "90px", height: "12px", borderRadius: "6px", background: "#f3f4f6" }));
464
+ row.animate?.([{ opacity: 0.45 }, { opacity: 1 }], { duration: 800, iterations: Infinity, direction: "alternate", easing: "ease-in-out" });
465
+ return row;
466
+ }
467
+ function pickSignIn(wallets) {
468
+ return new Promise((resolve) => {
469
+ const overlay = el("div", {
470
+ position: "fixed",
471
+ inset: "0",
472
+ zIndex: "2147483647",
473
+ display: "flex",
474
+ alignItems: "center",
475
+ justifyContent: "center",
476
+ background: "transparent"
477
+ });
478
+ const card = el("div", {
479
+ display: "flex",
480
+ flexDirection: "column",
481
+ width: "min(340px, calc(100vw - 32px))",
482
+ height: "min(380px, calc(100vh - 32px))",
483
+ boxSizing: "border-box",
484
+ padding: "20px 20px 14px",
485
+ borderRadius: "20px",
486
+ background: "#fff",
487
+ color: "#111827",
488
+ fontFamily: FONT,
489
+ boxShadow: "0 0 0 1px rgba(0,0,0,0.04), 0 8px 40px rgba(0,0,0,0.28), 0 0 90px 24px rgba(0,0,0,0.18)"
490
+ });
491
+ card.setAttribute("role", "dialog");
492
+ card.setAttribute("aria-modal", "true");
493
+ card.setAttribute("aria-label", "Sign in");
494
+ const onKey = (e) => {
495
+ if (e.key === "Escape") done(null);
496
+ };
497
+ const done = (result) => {
498
+ document.removeEventListener("keydown", onKey);
499
+ overlay.remove();
500
+ resolve(result);
501
+ };
502
+ document.addEventListener("keydown", onKey);
503
+ overlay.addEventListener("mousedown", (e) => {
504
+ if (e.target === overlay) done(null);
505
+ });
506
+ const header = el("div", { display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "14px", flexShrink: "0" });
507
+ header.appendChild(el("p", { margin: "0", font: `600 18px ${FONT}` }, "Sign in"));
508
+ const close = el(
509
+ "button",
510
+ { border: "0", background: "transparent", cursor: "pointer", padding: "4px", color: "#6b7280", font: `400 22px ${FONT}`, lineHeight: "1" },
511
+ "\xD7"
512
+ );
513
+ close.type = "button";
514
+ close.setAttribute("aria-label", "Close");
515
+ close.addEventListener("click", () => done(null));
516
+ header.appendChild(close);
517
+ card.appendChild(header);
518
+ const google = el("button", { ...rowStyle, justifyContent: "center" });
519
+ google.type = "button";
520
+ google.innerHTML = GOOGLE_G;
521
+ google.appendChild(el("span", {}, "Continue with Google"));
522
+ google.addEventListener("click", () => done({ kind: "google" }));
523
+ card.appendChild(google);
524
+ card.appendChild(
525
+ el("p", { margin: "14px 0 8px", flexShrink: "0", font: `500 13px ${FONT}`, color: "#6b7280" }, "Or connect a Stellar wallet")
526
+ );
527
+ const list = el("div", { display: "flex", flexDirection: "column", gap: "8px", flex: "1", minHeight: "0", overflowY: "auto", paddingBottom: "2px" });
528
+ for (let i = 0; i < SKELETON_ROWS; i++) list.appendChild(skeletonRow());
529
+ card.appendChild(list);
530
+ card.appendChild(
531
+ el("p", { margin: "10px 0 0", paddingTop: "10px", flexShrink: "0", borderTop: "1px solid #f3f4f6", textAlign: "center", font: `400 12px ${FONT}`, color: "#9ca3af" }, "Powered by Beacon")
532
+ );
533
+ overlay.appendChild(card);
534
+ document.body.appendChild(overlay);
535
+ google.focus();
536
+ wallets.list().then((all) => {
537
+ list.replaceChildren();
538
+ all.forEach((w) => list.appendChild(walletRow(w, wallets, done)));
539
+ }).catch(() => {
540
+ list.replaceChildren(el("p", { margin: "0", font: `400 14px ${FONT}`, color: "#6b7280" }, "Wallets could not be loaded. Use Google instead."));
541
+ });
542
+ });
543
+ }
544
+ function walletRow(wallet, wallets, done) {
545
+ const row = el("button", rowStyle);
546
+ row.type = "button";
547
+ const icon = el("img", { width: "28px", height: "28px", borderRadius: "8px", objectFit: "cover", flexShrink: "0" });
548
+ icon.alt = "";
549
+ icon.src = wallet.icon;
550
+ icon.addEventListener("error", () => icon.style.visibility = "hidden");
551
+ row.appendChild(icon);
552
+ row.appendChild(el("span", { flex: "1" }, wallet.name));
553
+ const installed = wallets.installed(wallet.id);
554
+ void installed.then((yes) => {
555
+ if (yes) return;
556
+ row.appendChild(
557
+ el("span", { font: `500 12px ${FONT}`, color: "#4b5563", border: "1px solid #d1d5db", borderRadius: "8px", padding: "3px 8px" }, "Install \u2197")
558
+ );
559
+ });
560
+ row.addEventListener("click", () => {
561
+ void installed.then((yes) => {
562
+ if (yes) done({ kind: "wallet", id: wallet.id });
563
+ else window.open(wallet.url, "_blank", "noopener,noreferrer");
564
+ });
565
+ });
566
+ return row;
567
+ }
568
+
317
569
  // src/BeaconAuth.ts
318
570
  var DEFAULT_WALLET_URL = "https://wallet.beaconmcu.space";
319
571
  var LOGIN_TIMEOUT_MS = 5 * 6e4;
@@ -331,26 +583,57 @@ var BeaconAuth = class {
331
583
  this.address = null;
332
584
  // replaced by the wallet's active network once it connects
333
585
  this.events = new Emitter();
586
+ this.external = new ExternalWallets();
587
+ // an external Stellar wallet (Freighter, xBull, ...), when the app allows them
588
+ this.supported = [];
589
+ this.loginInFlight = null;
334
590
  if (!options || typeof options.clientId !== "string" || !options.clientId) {
335
591
  throw new BeaconError(ErrorCode.INVALID_REQUEST, "BeaconAuth: clientId is required");
336
592
  }
337
593
  const defaultNetwork = options.defaultNetwork ? checkNetwork(options.defaultNetwork) : void 0;
338
594
  const supported = options.supportedNetworks?.map(checkNetwork);
339
595
  this.network = defaultNetwork ?? "testnet";
596
+ this.supported = [.../* @__PURE__ */ new Set([this.network, ...supported ?? []])];
340
597
  const networks = defaultNetwork || supported ? { default: defaultNetwork, supported } : void 0;
341
598
  this.connection = new WalletConnection(options.walletUrl ?? DEFAULT_WALLET_URL, options.clientId, networks, options.showWalletUI !== false, {
342
599
  onConnected: (address, network) => this.handleConnected(address, network),
343
- onDisconnected: () => this.handleDisconnected(),
600
+ onDisconnected: () => !this.external.connected && this.handleDisconnected(),
601
+ // the Beacon wallet's events do not end an external wallet's session
344
602
  onNetworkChanged: (network) => this.handleNetworkChanged(network)
345
603
  });
604
+ if (typeof window !== "undefined") {
605
+ this.connection.signInMethods().then((methods) => methods.includes("wallets") ? this.external.preload() : void 0).catch(() => void 0);
606
+ }
346
607
  }
347
- /** Opens the wallet and signs the user in with Google. Resolves with the Stellar address (G...). */
608
+ /**
609
+ * Signs the user in and resolves with the Stellar address (G...). With Google only, it opens the Beacon wallet.
610
+ * When the app turned on External wallets in the dashboard, the person first picks Google or a wallet.
611
+ */
348
612
  async login() {
349
613
  if (this.address) return { address: this.address };
614
+ this.loginInFlight ?? (this.loginInFlight = this.startLogin().finally(() => this.loginInFlight = null));
615
+ return this.loginInFlight;
616
+ }
617
+ async startLogin() {
618
+ const methods = await this.connection.signInMethods();
619
+ if (methods.includes("wallets")) {
620
+ const choice = await pickSignIn(this.external);
621
+ if (!choice) throw new BeaconError(ErrorCode.USER_REJECTED, "Sign-in was closed.");
622
+ if (choice.kind === "wallet") {
623
+ const address = await this.external.connect(choice.id);
624
+ this.handleConnected(address, this.network);
625
+ return { address };
626
+ }
627
+ }
350
628
  const result = await this.connection.request("beacon_login", [], LOGIN_TIMEOUT_MS);
351
629
  return { address: result.address };
352
630
  }
353
631
  async logout() {
632
+ if (this.external.connected) {
633
+ this.external.disconnect();
634
+ this.handleDisconnected();
635
+ return;
636
+ }
354
637
  try {
355
638
  await this.connection.request("beacon_logout", [], DEFAULT_TIMEOUT_MS);
356
639
  } catch {
@@ -359,6 +642,13 @@ var BeaconAuth = class {
359
642
  }
360
643
  /** Switches to another of the app's supportedNetworks. Rejects with code -6 for any other network. */
361
644
  async switchNetwork(network) {
645
+ if (this.external.connected) {
646
+ if (!this.supported.includes(checkNetwork(network))) {
647
+ throw new BeaconError(ErrorCode.UNSUPPORTED, `Network "${network}" is not one of this app's supportedNetworks.`);
648
+ }
649
+ this.handleNetworkChanged(network);
650
+ return;
651
+ }
362
652
  await this.connection.request("stellar_switchNetwork", [checkNetwork(network)], DEFAULT_TIMEOUT_MS);
363
653
  }
364
654
  // ---- sending and signing (the user approves in the wallet) ----
@@ -367,11 +657,23 @@ var BeaconAuth = class {
367
657
  * submits it. Resolves with the transaction hash. (To create a new account, send at least 1 XLM.)
368
658
  */
369
659
  async sendPayment(payment) {
660
+ if (this.external.connected) {
661
+ throw new BeaconError(
662
+ ErrorCode.UNSUPPORTED,
663
+ "sendPayment is only available with a Beacon (Google) wallet. With an external wallet, build the transaction and use signTransaction."
664
+ );
665
+ }
370
666
  return await this.connection.request("stellar_sendPayment", [payment], SEND_TIMEOUT_MS);
371
667
  }
372
668
  // ---- signing (the user always approves inside the wallet) ----
373
669
  /** Signs a transaction (base64 XDR). Returns the signed XDR; submit it yourself, e.g. through Horizon. */
374
670
  async signTransaction(xdr, options = {}) {
671
+ if (this.external.connected) {
672
+ return this.external.signTransaction(xdr, {
673
+ networkPassphrase: options.networkPassphrase ?? NETWORKS[this.network].passphrase,
674
+ address: options.address ?? this.address ?? void 0
675
+ });
676
+ }
375
677
  return await this.connection.request(
376
678
  "stellar_signTransaction",
377
679
  [xdr, options],
@@ -380,10 +682,19 @@ var BeaconAuth = class {
380
682
  }
381
683
  /** Signs a text message (SEP-53). The signature is base64. */
382
684
  async signMessage(message, options = {}) {
685
+ if (this.external.connected) {
686
+ return this.external.signMessage(message, { address: options.address ?? this.address ?? void 0 });
687
+ }
383
688
  return await this.connection.request("stellar_signMessage", [message, options], SIGNING_TIMEOUT_MS);
384
689
  }
385
690
  /** Signs a Soroban authorization entry preimage (base64 XDR). Returns a base64 signature. */
386
691
  async signAuthEntry(preimage, options = {}) {
692
+ if (this.external.connected) {
693
+ return this.external.signAuthEntry(preimage, {
694
+ networkPassphrase: options.networkPassphrase ?? NETWORKS[this.network].passphrase,
695
+ address: options.address ?? this.address ?? void 0
696
+ });
697
+ }
387
698
  return await this.connection.request(
388
699
  "stellar_signAuthEntry",
389
700
  [preimage, options],