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