@beaconmcu/auth 0.1.5 → 0.1.6

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,222 @@ 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, and which of them are installed in this browser. */
362
+ async list() {
363
+ const modules = await this.load();
364
+ return Promise.all(
365
+ modules.map(async (m) => ({
366
+ id: m.productId,
367
+ name: m.productName,
368
+ icon: m.productIcon,
369
+ url: m.productUrl,
370
+ installed: await Promise.race([
371
+ m.isAvailable().catch(() => false),
372
+ new Promise((resolve) => setTimeout(() => resolve(false), AVAILABLE_TIMEOUT_MS))
373
+ ])
374
+ }))
375
+ );
376
+ }
377
+ /** Asks the wallet to share its address (the wallet shows its own approval). */
378
+ async connect(id) {
379
+ const wallet = (await this.load()).find((m) => m.productId === id);
380
+ if (!wallet) throw new BeaconError(ErrorCode.INVALID_REQUEST, `Unknown wallet "${id}".`);
381
+ try {
382
+ const { address } = await wallet.getAddress();
383
+ if (!address) throw new Error("The wallet did not return an address.");
384
+ this.active = wallet;
385
+ return address;
386
+ } catch (e) {
387
+ throw toBeaconError(e, "Could not connect to the wallet.");
388
+ }
389
+ }
390
+ get connected() {
391
+ return this.active !== null;
392
+ }
393
+ disconnect() {
394
+ this.active = null;
395
+ }
396
+ wallet() {
397
+ if (!this.active) throw new BeaconError(ErrorCode.NOT_CONNECTED, "No wallet is connected.");
398
+ return this.active;
399
+ }
400
+ async signTransaction(xdr, opts) {
401
+ try {
402
+ const r = await this.wallet().signTransaction(xdr, opts);
403
+ return { signedTxXdr: r.signedTxXdr, signerAddress: r.signerAddress ?? opts.address ?? "" };
404
+ } catch (e) {
405
+ throw toBeaconError(e, "The wallet could not sign the transaction.");
406
+ }
407
+ }
408
+ async signMessage(message, opts) {
409
+ const w = this.wallet();
410
+ if (!w.signMessage) throw new BeaconError(ErrorCode.UNSUPPORTED, `${w.productName} cannot sign messages.`);
411
+ try {
412
+ const r = await w.signMessage(message, opts);
413
+ return { signedMessage: r.signedMessage, signerAddress: r.signerAddress ?? opts.address ?? "" };
414
+ } catch (e) {
415
+ throw toBeaconError(e, "The wallet could not sign the message.");
416
+ }
417
+ }
418
+ async signAuthEntry(entry, opts) {
419
+ const w = this.wallet();
420
+ if (!w.signAuthEntry) throw new BeaconError(ErrorCode.UNSUPPORTED, `${w.productName} cannot sign authorization entries.`);
421
+ try {
422
+ const r = await w.signAuthEntry(entry, opts);
423
+ return { signedAuthEntry: r.signedAuthEntry, signerAddress: r.signerAddress ?? opts.address ?? "" };
424
+ } catch (e) {
425
+ throw toBeaconError(e, "The wallet could not sign the authorization entry.");
426
+ }
427
+ }
428
+ };
429
+
430
+ // src/wallets/picker.ts
431
+ var FONT = 'Inter, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif';
432
+ function el(tag, style = {}, text) {
433
+ const node = document.createElement(tag);
434
+ Object.assign(node.style, style);
435
+ if (text !== void 0) node.textContent = text;
436
+ return node;
437
+ }
438
+ 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>';
439
+ var rowStyle = {
440
+ display: "flex",
441
+ alignItems: "center",
442
+ gap: "12px",
443
+ width: "100%",
444
+ boxSizing: "border-box",
445
+ padding: "10px 12px",
446
+ border: "1px solid #e5e7eb",
447
+ borderRadius: "12px",
448
+ background: "#fff",
449
+ color: "#111827",
450
+ font: `500 15px ${FONT}`,
451
+ textAlign: "left",
452
+ cursor: "pointer"
453
+ };
454
+ function pickSignIn(loadWallets) {
455
+ return new Promise((resolve) => {
456
+ const overlay = el("div", {
457
+ position: "fixed",
458
+ inset: "0",
459
+ zIndex: "2147483647",
460
+ display: "flex",
461
+ alignItems: "center",
462
+ justifyContent: "center",
463
+ background: "transparent"
464
+ });
465
+ const card = el("div", {
466
+ width: "min(380px, calc(100vw - 32px))",
467
+ maxHeight: "calc(100vh - 32px)",
468
+ boxSizing: "border-box",
469
+ overflowY: "auto",
470
+ padding: "20px",
471
+ borderRadius: "20px",
472
+ background: "#fff",
473
+ color: "#111827",
474
+ fontFamily: FONT,
475
+ 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)"
476
+ });
477
+ card.setAttribute("role", "dialog");
478
+ card.setAttribute("aria-modal", "true");
479
+ card.setAttribute("aria-label", "Sign in");
480
+ const onKey = (e) => {
481
+ if (e.key === "Escape") done(null);
482
+ };
483
+ const done = (result) => {
484
+ document.removeEventListener("keydown", onKey);
485
+ overlay.remove();
486
+ resolve(result);
487
+ };
488
+ document.addEventListener("keydown", onKey);
489
+ overlay.addEventListener("mousedown", (e) => {
490
+ if (e.target === overlay) done(null);
491
+ });
492
+ const header = el("div", { display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "16px" });
493
+ header.appendChild(el("p", { margin: "0", font: `600 18px ${FONT}` }, "Sign in"));
494
+ const close = el(
495
+ "button",
496
+ { border: "0", background: "transparent", cursor: "pointer", padding: "4px", color: "#6b7280", font: `400 22px ${FONT}`, lineHeight: "1" },
497
+ "\xD7"
498
+ );
499
+ close.type = "button";
500
+ close.setAttribute("aria-label", "Close");
501
+ close.addEventListener("click", () => done(null));
502
+ header.appendChild(close);
503
+ card.appendChild(header);
504
+ const google = el("button", { ...rowStyle, justifyContent: "center" });
505
+ google.type = "button";
506
+ google.innerHTML = GOOGLE_G;
507
+ google.appendChild(el("span", {}, "Continue with Google"));
508
+ google.addEventListener("click", () => done({ kind: "google" }));
509
+ card.appendChild(google);
510
+ card.appendChild(el("p", { margin: "16px 0 10px", font: `500 13px ${FONT}`, color: "#6b7280" }, "Or connect a Stellar wallet"));
511
+ const list = el("div", { display: "flex", flexDirection: "column", gap: "8px" });
512
+ const loading = el("p", { margin: "0", font: `400 14px ${FONT}`, color: "#6b7280" }, "Loading wallets\u2026");
513
+ list.appendChild(loading);
514
+ card.appendChild(list);
515
+ overlay.appendChild(card);
516
+ document.body.appendChild(overlay);
517
+ google.focus();
518
+ loadWallets().then((wallets) => {
519
+ list.replaceChildren();
520
+ [...wallets].sort((a, b) => Number(b.installed) - Number(a.installed)).forEach((w) => list.appendChild(walletRow(w, done)));
521
+ }).catch(() => {
522
+ loading.textContent = "Wallets could not be loaded. Use Google instead.";
523
+ });
524
+ });
525
+ }
526
+ function walletRow(wallet, done) {
527
+ const row = el("button", rowStyle);
528
+ row.type = "button";
529
+ const icon = el("img", { width: "28px", height: "28px", borderRadius: "8px", objectFit: "cover", flexShrink: "0" });
530
+ icon.alt = "";
531
+ icon.src = wallet.icon;
532
+ icon.addEventListener("error", () => icon.style.visibility = "hidden");
533
+ row.appendChild(icon);
534
+ row.appendChild(el("span", { flex: "1" }, wallet.name));
535
+ if (wallet.installed) {
536
+ row.addEventListener("click", () => done({ kind: "wallet", id: wallet.id }));
537
+ } else {
538
+ row.appendChild(
539
+ el("span", { font: `500 12px ${FONT}`, color: "#4b5563", border: "1px solid #d1d5db", borderRadius: "8px", padding: "3px 8px" }, "Install \u2197")
540
+ );
541
+ row.addEventListener("click", () => window.open(wallet.url, "_blank", "noopener,noreferrer"));
542
+ }
543
+ return row;
544
+ }
545
+
317
546
  // src/BeaconAuth.ts
318
547
  var DEFAULT_WALLET_URL = "https://wallet.beaconmcu.space";
319
548
  var LOGIN_TIMEOUT_MS = 5 * 6e4;
@@ -331,26 +560,54 @@ var BeaconAuth = class {
331
560
  this.address = null;
332
561
  // replaced by the wallet's active network once it connects
333
562
  this.events = new Emitter();
563
+ this.external = new ExternalWallets();
564
+ // an external Stellar wallet (Freighter, xBull, ...), when the app allows them
565
+ this.supported = [];
566
+ this.loginInFlight = null;
334
567
  if (!options || typeof options.clientId !== "string" || !options.clientId) {
335
568
  throw new BeaconError(ErrorCode.INVALID_REQUEST, "BeaconAuth: clientId is required");
336
569
  }
337
570
  const defaultNetwork = options.defaultNetwork ? checkNetwork(options.defaultNetwork) : void 0;
338
571
  const supported = options.supportedNetworks?.map(checkNetwork);
339
572
  this.network = defaultNetwork ?? "testnet";
573
+ this.supported = [.../* @__PURE__ */ new Set([this.network, ...supported ?? []])];
340
574
  const networks = defaultNetwork || supported ? { default: defaultNetwork, supported } : void 0;
341
575
  this.connection = new WalletConnection(options.walletUrl ?? DEFAULT_WALLET_URL, options.clientId, networks, options.showWalletUI !== false, {
342
576
  onConnected: (address, network) => this.handleConnected(address, network),
343
- onDisconnected: () => this.handleDisconnected(),
577
+ onDisconnected: () => !this.external.connected && this.handleDisconnected(),
578
+ // the Beacon wallet's events do not end an external wallet's session
344
579
  onNetworkChanged: (network) => this.handleNetworkChanged(network)
345
580
  });
346
581
  }
347
- /** Opens the wallet and signs the user in with Google. Resolves with the Stellar address (G...). */
582
+ /**
583
+ * Signs the user in and resolves with the Stellar address (G...). With Google only, it opens the Beacon wallet.
584
+ * When the app turned on External wallets in the dashboard, the person first picks Google or a wallet.
585
+ */
348
586
  async login() {
349
587
  if (this.address) return { address: this.address };
588
+ this.loginInFlight ?? (this.loginInFlight = this.startLogin().finally(() => this.loginInFlight = null));
589
+ return this.loginInFlight;
590
+ }
591
+ async startLogin() {
592
+ const methods = await this.connection.signInMethods();
593
+ if (methods.includes("wallets")) {
594
+ const choice = await pickSignIn(() => this.external.list());
595
+ if (!choice) throw new BeaconError(ErrorCode.USER_REJECTED, "Sign-in was closed.");
596
+ if (choice.kind === "wallet") {
597
+ const address = await this.external.connect(choice.id);
598
+ this.handleConnected(address, this.network);
599
+ return { address };
600
+ }
601
+ }
350
602
  const result = await this.connection.request("beacon_login", [], LOGIN_TIMEOUT_MS);
351
603
  return { address: result.address };
352
604
  }
353
605
  async logout() {
606
+ if (this.external.connected) {
607
+ this.external.disconnect();
608
+ this.handleDisconnected();
609
+ return;
610
+ }
354
611
  try {
355
612
  await this.connection.request("beacon_logout", [], DEFAULT_TIMEOUT_MS);
356
613
  } catch {
@@ -359,6 +616,13 @@ var BeaconAuth = class {
359
616
  }
360
617
  /** Switches to another of the app's supportedNetworks. Rejects with code -6 for any other network. */
361
618
  async switchNetwork(network) {
619
+ if (this.external.connected) {
620
+ if (!this.supported.includes(checkNetwork(network))) {
621
+ throw new BeaconError(ErrorCode.UNSUPPORTED, `Network "${network}" is not one of this app's supportedNetworks.`);
622
+ }
623
+ this.handleNetworkChanged(network);
624
+ return;
625
+ }
362
626
  await this.connection.request("stellar_switchNetwork", [checkNetwork(network)], DEFAULT_TIMEOUT_MS);
363
627
  }
364
628
  // ---- sending and signing (the user approves in the wallet) ----
@@ -367,11 +631,23 @@ var BeaconAuth = class {
367
631
  * submits it. Resolves with the transaction hash. (To create a new account, send at least 1 XLM.)
368
632
  */
369
633
  async sendPayment(payment) {
634
+ if (this.external.connected) {
635
+ throw new BeaconError(
636
+ ErrorCode.UNSUPPORTED,
637
+ "sendPayment is only available with a Beacon (Google) wallet. With an external wallet, build the transaction and use signTransaction."
638
+ );
639
+ }
370
640
  return await this.connection.request("stellar_sendPayment", [payment], SEND_TIMEOUT_MS);
371
641
  }
372
642
  // ---- signing (the user always approves inside the wallet) ----
373
643
  /** Signs a transaction (base64 XDR). Returns the signed XDR; submit it yourself, e.g. through Horizon. */
374
644
  async signTransaction(xdr, options = {}) {
645
+ if (this.external.connected) {
646
+ return this.external.signTransaction(xdr, {
647
+ networkPassphrase: options.networkPassphrase ?? NETWORKS[this.network].passphrase,
648
+ address: options.address ?? this.address ?? void 0
649
+ });
650
+ }
375
651
  return await this.connection.request(
376
652
  "stellar_signTransaction",
377
653
  [xdr, options],
@@ -380,10 +656,19 @@ var BeaconAuth = class {
380
656
  }
381
657
  /** Signs a text message (SEP-53). The signature is base64. */
382
658
  async signMessage(message, options = {}) {
659
+ if (this.external.connected) {
660
+ return this.external.signMessage(message, { address: options.address ?? this.address ?? void 0 });
661
+ }
383
662
  return await this.connection.request("stellar_signMessage", [message, options], SIGNING_TIMEOUT_MS);
384
663
  }
385
664
  /** Signs a Soroban authorization entry preimage (base64 XDR). Returns a base64 signature. */
386
665
  async signAuthEntry(preimage, options = {}) {
666
+ if (this.external.connected) {
667
+ return this.external.signAuthEntry(preimage, {
668
+ networkPassphrase: options.networkPassphrase ?? NETWORKS[this.network].passphrase,
669
+ address: options.address ?? this.address ?? void 0
670
+ });
671
+ }
387
672
  return await this.connection.request(
388
673
  "stellar_signAuthEntry",
389
674
  [preimage, options],