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