@beaconmcu/auth 0.1.4 → 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;
@@ -143,7 +151,8 @@ var WalletConnection = class {
143
151
  zIndex: "2147483647",
144
152
  alignItems: "center",
145
153
  justifyContent: "center",
146
- background: "rgba(0, 0, 0, 0.6)"
154
+ background: "transparent"
155
+ // no dark backdrop: only a soft shadow around the wallet (on the iframe below)
147
156
  });
148
157
  const iframe = document.createElement("iframe");
149
158
  iframe.title = "Beacon wallet";
@@ -151,13 +160,15 @@ var WalletConnection = class {
151
160
  iframe.src = this.src;
152
161
  Object.assign(iframe.style, {
153
162
  width: "min(380px, calc(100vw - 32px))",
154
- height: "520px",
155
- // the wallet's fixed height; the wallet confirms it with beacon:resize
163
+ height: "380px",
164
+ // the wallet's fixed height (a square: same as the width); the wallet confirms it with beacon:resize
156
165
  maxHeight: "calc(100vh - 32px)",
157
166
  transition: "height 120ms ease",
158
167
  border: "0",
159
168
  borderRadius: "20px",
160
169
  // the wallet is one white card; the iframe clips it to rounded corners
170
+ 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)",
171
+ // feathered glow
161
172
  background: "#ffffff",
162
173
  overflow: "hidden"
163
174
  });
@@ -225,6 +236,11 @@ var WalletConnection = class {
225
236
  this.readyWaiters.push(onReady);
226
237
  });
227
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
+ }
228
244
  async request(method, params, timeoutMs) {
229
245
  if (typeof window === "undefined") throw internalError("Beacon can only be used in a browser");
230
246
  if (!this.isReady && INTERACTIVE_METHODS.has(method)) this.openEarly();
@@ -311,6 +327,222 @@ function createWalletInterface(beacon) {
311
327
  };
312
328
  }
313
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
+
314
546
  // src/BeaconAuth.ts
315
547
  var DEFAULT_WALLET_URL = "https://wallet.beaconmcu.space";
316
548
  var LOGIN_TIMEOUT_MS = 5 * 6e4;
@@ -328,26 +560,54 @@ var BeaconAuth = class {
328
560
  this.address = null;
329
561
  // replaced by the wallet's active network once it connects
330
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;
331
567
  if (!options || typeof options.clientId !== "string" || !options.clientId) {
332
568
  throw new BeaconError(ErrorCode.INVALID_REQUEST, "BeaconAuth: clientId is required");
333
569
  }
334
570
  const defaultNetwork = options.defaultNetwork ? checkNetwork(options.defaultNetwork) : void 0;
335
571
  const supported = options.supportedNetworks?.map(checkNetwork);
336
572
  this.network = defaultNetwork ?? "testnet";
573
+ this.supported = [.../* @__PURE__ */ new Set([this.network, ...supported ?? []])];
337
574
  const networks = defaultNetwork || supported ? { default: defaultNetwork, supported } : void 0;
338
575
  this.connection = new WalletConnection(options.walletUrl ?? DEFAULT_WALLET_URL, options.clientId, networks, options.showWalletUI !== false, {
339
576
  onConnected: (address, network) => this.handleConnected(address, network),
340
- onDisconnected: () => this.handleDisconnected(),
577
+ onDisconnected: () => !this.external.connected && this.handleDisconnected(),
578
+ // the Beacon wallet's events do not end an external wallet's session
341
579
  onNetworkChanged: (network) => this.handleNetworkChanged(network)
342
580
  });
343
581
  }
344
- /** 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
+ */
345
586
  async login() {
346
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
+ }
347
602
  const result = await this.connection.request("beacon_login", [], LOGIN_TIMEOUT_MS);
348
603
  return { address: result.address };
349
604
  }
350
605
  async logout() {
606
+ if (this.external.connected) {
607
+ this.external.disconnect();
608
+ this.handleDisconnected();
609
+ return;
610
+ }
351
611
  try {
352
612
  await this.connection.request("beacon_logout", [], DEFAULT_TIMEOUT_MS);
353
613
  } catch {
@@ -356,6 +616,13 @@ var BeaconAuth = class {
356
616
  }
357
617
  /** Switches to another of the app's supportedNetworks. Rejects with code -6 for any other network. */
358
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
+ }
359
626
  await this.connection.request("stellar_switchNetwork", [checkNetwork(network)], DEFAULT_TIMEOUT_MS);
360
627
  }
361
628
  // ---- sending and signing (the user approves in the wallet) ----
@@ -364,11 +631,23 @@ var BeaconAuth = class {
364
631
  * submits it. Resolves with the transaction hash. (To create a new account, send at least 1 XLM.)
365
632
  */
366
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
+ }
367
640
  return await this.connection.request("stellar_sendPayment", [payment], SEND_TIMEOUT_MS);
368
641
  }
369
642
  // ---- signing (the user always approves inside the wallet) ----
370
643
  /** Signs a transaction (base64 XDR). Returns the signed XDR; submit it yourself, e.g. through Horizon. */
371
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
+ }
372
651
  return await this.connection.request(
373
652
  "stellar_signTransaction",
374
653
  [xdr, options],
@@ -377,10 +656,19 @@ var BeaconAuth = class {
377
656
  }
378
657
  /** Signs a text message (SEP-53). The signature is base64. */
379
658
  async signMessage(message, options = {}) {
659
+ if (this.external.connected) {
660
+ return this.external.signMessage(message, { address: options.address ?? this.address ?? void 0 });
661
+ }
380
662
  return await this.connection.request("stellar_signMessage", [message, options], SIGNING_TIMEOUT_MS);
381
663
  }
382
664
  /** Signs a Soroban authorization entry preimage (base64 XDR). Returns a base64 signature. */
383
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
+ }
384
672
  return await this.connection.request(
385
673
  "stellar_signAuthEntry",
386
674
  [preimage, options],