@beaconmcu/auth 0.0.0-stage → 0.1.0

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/README.md CHANGED
@@ -1,3 +1,113 @@
1
- # Temporary Holding Version
1
+ # @beaconmcu/auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Add "Sign in with Google" to your Stellar dApp. Your users get a wallet instantly: no extension, no seed phrase.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @beaconmcu/auth
9
+ ```
10
+
11
+ Create an app in the [Beacon dashboard](https://dashboard.beaconmcu.space), add your site's URL as an allowed origin, and copy the Client ID.
12
+
13
+ ## Quick start
14
+
15
+ ```ts
16
+ import { BeaconAuth } from "@beaconmcu/auth";
17
+
18
+ const beacon = new BeaconAuth({ clientId: "bcn_app_xxxxxxxxxxxxxxxxxxxxxxxx" });
19
+
20
+ const { address } = await beacon.login(); // opens the wallet, user signs in with Google
21
+ console.log("Stellar address:", address); // G...
22
+
23
+ beacon.on("accountChanged", (address) => console.log(address));
24
+ await beacon.logout();
25
+ ```
26
+
27
+ `beacon.getAddress()` returns the address or `null`. `beacon.getNetwork()` returns the active network.
28
+
29
+ ## Send XLM (one call)
30
+
31
+ ```ts
32
+ const { hash } = await beacon.sendPayment({ to: "G...", amount: "10" });
33
+ ```
34
+
35
+ The wallet builds the payment, shows it to the user, signs it and submits it, then returns the transaction hash. `memo` is optional (text, up to 28 bytes). Sending to an account that does not exist yet creates it, which needs at least 1 XLM.
36
+
37
+ ## Sign (the user always approves in the wallet)
38
+
39
+ ```ts
40
+ // Sign a message (SEP-53). The signature is base64.
41
+ const { signedMessage } = await beacon.signMessage("Hello Stellar");
42
+
43
+ // For anything beyond a plain XLM payment, build the transaction with the Stellar SDK,
44
+ // sign it with Beacon, then submit it yourself.
45
+ import { TransactionBuilder, Operation, Asset, Horizon } from "@stellar/stellar-sdk";
46
+
47
+ const server = new Horizon.Server(beacon.getNetwork().horizonUrl);
48
+ const account = await server.loadAccount(address);
49
+ const tx = new TransactionBuilder(account, { fee: "100", networkPassphrase: beacon.getNetwork().passphrase })
50
+ .addOperation(Operation.payment({ destination: "G...", asset: Asset.native(), amount: "10" }))
51
+ .setTimeout(180)
52
+ .build();
53
+
54
+ const { signedTxXdr } = await beacon.signTransaction(tx.toXDR());
55
+ await server.submitTransaction(TransactionBuilder.fromXDR(signedTxXdr, beacon.getNetwork().passphrase));
56
+ ```
57
+
58
+ Every signature opens a confirmation screen in the wallet that shows the requesting site, the network and what the transaction does (payments, account changes, contract calls). Soroban authorization entries are supported with `signAuthEntry`.
59
+
60
+ ## Silent signing (optional)
61
+
62
+ By default every signature opens a confirmation screen. An app can turn the screen off, like Privy's `showWalletUIs`:
63
+
64
+ ```ts
65
+ const beacon = new BeaconAuth({ clientId: "bcn_app_...", showWalletUI: false });
66
+ ```
67
+
68
+ Only low-risk requests are then signed silently: text messages and transactions made **only** of plain XLM payments (payment or create-account) from the user's own account. These always still ask, even with `showWalletUI: false`: smart contract calls, authorization entries, account settings changes (signers, thresholds), account merges, trust changes, fee bumps, and anything that acts for another account.
69
+
70
+ Turn the screen off only if you are comfortable with your app moving the user's XLM without a prompt.
71
+
72
+ ## Choose the network (in code)
73
+
74
+ ```ts
75
+ const beacon = new BeaconAuth({
76
+ clientId: "bcn_app_...",
77
+ defaultNetwork: "testnet", // used on login
78
+ supportedNetworks: ["testnet", "mainnet"], // the app may switch between these
79
+ });
80
+
81
+ await beacon.switchNetwork("mainnet");
82
+ beacon.on("networkChanged", (network) => console.log(network));
83
+ ```
84
+
85
+ - `"testnet"` has free test XLM (Friendbot). `"mainnet"` is real money.
86
+ - Without `defaultNetwork`, the app's network from the Beacon dashboard is used (testnet if none).
87
+ - A network outside `supportedNetworks` is rejected with error code `-6`.
88
+ - Every approval screen in the wallet shows the network, and marks mainnet as "real funds".
89
+ - A Stellar account exists only after it receives at least 1 XLM. On testnet, fund it with Friendbot.
90
+
91
+ ## Use it with wallet libraries (SEP-43)
92
+
93
+ `beacon.getWalletInterface()` returns the standard Stellar wallet shape (`getAddress`, `getNetwork`, `signTransaction`, `signMessage`, `signAuthEntry`), so libraries such as Stellar Wallets Kit can use Beacon.
94
+
95
+ ## Options
96
+
97
+ | Option | Default | Notes |
98
+ |---------------------|----------------------------------|--------------------------------------------|
99
+ | `clientId` | required | From the dashboard |
100
+ | `defaultNetwork` | the dashboard's network | `"testnet"` or `"mainnet"` |
101
+ | `supportedNetworks` | just the default | Networks `switchNetwork` may use |
102
+ | `showWalletUI` | `true` | `false` = sign low-risk requests silently |
103
+ | `walletUrl` | `https://wallet.beaconmcu.space` | Override for local development |
104
+
105
+ Errors are `BeaconError` with a `code` from the Stellar wallet standard: `-1` internal, `-2` external service, `-3` invalid request, `-4` user rejected, plus `-5` not connected, `-6` unsupported and `-7` busy.
106
+
107
+ ## Security model
108
+
109
+ - **The private key never leaves the wallet iframe.** It is created, decrypted and used only on `wallet.beaconmcu.space`. This package contains no keys and no crypto.
110
+ - **Your site and the wallet talk only through `postMessage`**, and both sides check the sender's origin and window.
111
+ - **Only origins you allow can open the wallet.** The wallet checks your page against the app's allowed origins, and the server adds a `frame-ancestors` header.
112
+ - **The server stores only an encrypted copy** of the key (AES-256-GCM). The decrypted key lives in the wallet's memory only. The 1-hour sign-in session is kept in the wallet's own tab storage so a page refresh keeps the user signed in; it is cleared on logout and when the tab closes. Nothing goes to cookies or long-term storage.
113
+ - **Nothing is signed silently.** Every signature needs an explicit Approve click showing the requesting site, network and details.
package/dist/index.cjs ADDED
@@ -0,0 +1,442 @@
1
+ 'use strict';
2
+
3
+ // src/shared/networks.ts
4
+ var NETWORKS = {
5
+ testnet: {
6
+ id: "testnet",
7
+ name: "Stellar Testnet",
8
+ passphrase: "Test SDF Network ; September 2015",
9
+ horizonUrl: "https://horizon-testnet.stellar.org",
10
+ explorerUrl: "https://stellar.expert/explorer/testnet",
11
+ friendbotUrl: "https://friendbot.stellar.org"
12
+ },
13
+ mainnet: {
14
+ id: "mainnet",
15
+ name: "Stellar Mainnet",
16
+ passphrase: "Public Global Stellar Network ; September 2015",
17
+ horizonUrl: "https://horizon.stellar.org",
18
+ explorerUrl: "https://stellar.expert/explorer/public"
19
+ }
20
+ };
21
+ var isNetworkId = (value) => value === "testnet" || value === "mainnet";
22
+
23
+ // src/shared/messages.ts
24
+ var ErrorCode = {
25
+ INTERNAL: -1,
26
+ // an outside service (Horizon, network) failed
27
+ INVALID_REQUEST: -3,
28
+ // log in first
29
+ UNSUPPORTED: -6};
30
+ var isObject = (v) => typeof v === "object" && v !== null;
31
+ function isWalletMessage(data) {
32
+ if (!isObject(data) || typeof data.type !== "string") return false;
33
+ switch (data.type) {
34
+ case "beacon:ready":
35
+ case "beacon:disconnected":
36
+ case "beacon:show":
37
+ case "beacon:hide":
38
+ return true;
39
+ case "beacon:networkChanged":
40
+ return isNetworkId(data.network);
41
+ case "beacon:resize":
42
+ return typeof data.height === "number" && Number.isFinite(data.height) && data.height > 0;
43
+ case "beacon:connected":
44
+ return typeof data.address === "string" && isNetworkId(data.network);
45
+ case "beacon:response":
46
+ return typeof data.id === "string" && ("result" in data || isObject(data.error) && typeof data.error.code === "number" && typeof data.error.message === "string");
47
+ default:
48
+ return false;
49
+ }
50
+ }
51
+
52
+ // src/errors.ts
53
+ var BeaconError = class extends Error {
54
+ constructor(code, message) {
55
+ super(message);
56
+ this.name = "BeaconError";
57
+ this.code = code;
58
+ }
59
+ };
60
+ var internalError = (message) => new BeaconError(ErrorCode.INTERNAL, message);
61
+
62
+ // src/connection.ts
63
+ var READY_TIMEOUT_MS = 15e3;
64
+ var INTERACTIVE_METHODS = /* @__PURE__ */ new Set([
65
+ "beacon_login",
66
+ "stellar_sendPayment",
67
+ "stellar_signTransaction",
68
+ "stellar_signMessage",
69
+ "stellar_signAuthEntry"
70
+ ]);
71
+ var WalletConnection = class {
72
+ constructor(walletUrl, clientId, networks, showWalletUI, handlers) {
73
+ this.clientId = clientId;
74
+ this.networks = networks;
75
+ this.showWalletUI = showWalletUI;
76
+ this.handlers = handlers;
77
+ this.overlay = null;
78
+ this.iframe = null;
79
+ this.openedEarly = false;
80
+ // the frame was opened before the wallet asked for it (it was still loading)
81
+ this.pending = /* @__PURE__ */ new Map();
82
+ this.isReady = false;
83
+ this.readyWaiters = [];
84
+ // ---- incoming messages ----
85
+ this.onMessage = (event) => {
86
+ if (event.origin !== this.walletOrigin) return;
87
+ if (!this.iframe || event.source !== this.iframe.contentWindow) return;
88
+ if (!isWalletMessage(event.data)) return;
89
+ const message = event.data;
90
+ switch (message.type) {
91
+ case "beacon:ready":
92
+ this.isReady = true;
93
+ this.readyWaiters.splice(0).forEach((resolve) => resolve());
94
+ break;
95
+ case "beacon:show":
96
+ this.setVisible(true);
97
+ break;
98
+ case "beacon:hide":
99
+ this.setVisible(false);
100
+ break;
101
+ case "beacon:resize":
102
+ if (this.iframe) this.iframe.style.height = `${Math.ceil(message.height)}px`;
103
+ break;
104
+ case "beacon:networkChanged":
105
+ this.handlers.onNetworkChanged(message.network);
106
+ break;
107
+ case "beacon:connected":
108
+ this.handlers.onConnected(message.address, message.network);
109
+ break;
110
+ case "beacon:disconnected":
111
+ this.handlers.onDisconnected();
112
+ break;
113
+ case "beacon:response":
114
+ this.settle(message);
115
+ break;
116
+ }
117
+ };
118
+ let url;
119
+ try {
120
+ url = new URL(walletUrl);
121
+ } catch {
122
+ throw new BeaconError(ErrorCode.INTERNAL, `Invalid walletUrl: ${walletUrl}`);
123
+ }
124
+ this.walletOrigin = url.origin;
125
+ url.pathname = "/";
126
+ url.search = "";
127
+ url.hash = "";
128
+ url.searchParams.set("client_id", clientId);
129
+ this.src = url.toString();
130
+ if (typeof window !== "undefined") {
131
+ window.addEventListener("message", this.onMessage);
132
+ this.mount();
133
+ }
134
+ }
135
+ // ---- iframe + modal ----
136
+ mount() {
137
+ const attach = () => {
138
+ const overlay = document.createElement("div");
139
+ Object.assign(overlay.style, {
140
+ display: "none",
141
+ position: "fixed",
142
+ inset: "0",
143
+ zIndex: "2147483647",
144
+ alignItems: "center",
145
+ justifyContent: "center",
146
+ background: "rgba(0, 0, 0, 0.6)"
147
+ });
148
+ const iframe = document.createElement("iframe");
149
+ iframe.title = "Beacon wallet";
150
+ iframe.allow = "clipboard-write";
151
+ iframe.src = this.src;
152
+ Object.assign(iframe.style, {
153
+ width: "min(380px, calc(100vw - 32px))",
154
+ height: "160px",
155
+ // the wallet's loading screen; replaced by its real content height (beacon:resize)
156
+ maxHeight: "calc(100vh - 32px)",
157
+ transition: "height 120ms ease",
158
+ border: "0",
159
+ borderRadius: "20px",
160
+ // the wallet is one white card; the iframe clips it to rounded corners
161
+ background: "#ffffff",
162
+ overflow: "hidden"
163
+ });
164
+ iframe.addEventListener("load", () => {
165
+ const init = {
166
+ type: "beacon:init",
167
+ ...this.networks && { networks: this.networks },
168
+ ...!this.showWalletUI && { showWalletUI: false }
169
+ };
170
+ iframe.contentWindow?.postMessage(init, this.walletOrigin);
171
+ });
172
+ overlay.appendChild(iframe);
173
+ document.body.appendChild(overlay);
174
+ this.overlay = overlay;
175
+ this.iframe = iframe;
176
+ };
177
+ if (document.body) attach();
178
+ else document.addEventListener("DOMContentLoaded", attach, { once: true });
179
+ }
180
+ setVisible(visible) {
181
+ if (!this.overlay || !this.iframe) return;
182
+ this.openedEarly = false;
183
+ this.overlay.style.display = visible ? "flex" : "none";
184
+ if (visible) this.iframe.focus();
185
+ }
186
+ // The user acted before the wallet finished loading: open the frame now. The wallet's own
187
+ // loading screen is what they see, and it takes over from there.
188
+ openEarly() {
189
+ if (!this.overlay || this.openedEarly || this.overlay.style.display !== "none") return;
190
+ this.openedEarly = true;
191
+ this.overlay.style.display = "flex";
192
+ }
193
+ // Opened early, but the wallet never asked to be shown (or failed): close it again.
194
+ closeEarly() {
195
+ if (!this.openedEarly) return;
196
+ this.openedEarly = false;
197
+ if (this.overlay) this.overlay.style.display = "none";
198
+ }
199
+ settle(message) {
200
+ const entry = this.pending.get(message.id);
201
+ if (!entry) return;
202
+ this.closeEarly();
203
+ this.pending.delete(message.id);
204
+ clearTimeout(entry.timer);
205
+ if ("error" in message) entry.reject(new BeaconError(message.error.code, message.error.message));
206
+ else entry.resolve(message.result);
207
+ }
208
+ // ---- outgoing requests ----
209
+ whenReady() {
210
+ if (this.isReady) return Promise.resolve();
211
+ return new Promise((resolve, reject) => {
212
+ const timer = setTimeout(() => {
213
+ this.readyWaiters = this.readyWaiters.filter((w) => w !== onReady);
214
+ this.closeEarly();
215
+ reject(
216
+ internalError(
217
+ `The Beacon wallet did not load. Check that this site (${window.location.origin}) is an allowed origin for Client ID ${this.clientId}, and that the wallet URL (${this.walletOrigin}) is correct.`
218
+ )
219
+ );
220
+ }, READY_TIMEOUT_MS);
221
+ const onReady = () => {
222
+ clearTimeout(timer);
223
+ resolve();
224
+ };
225
+ this.readyWaiters.push(onReady);
226
+ });
227
+ }
228
+ async request(method, params, timeoutMs) {
229
+ if (typeof window === "undefined") throw internalError("Beacon can only be used in a browser");
230
+ if (!this.isReady && INTERACTIVE_METHODS.has(method)) this.openEarly();
231
+ await this.whenReady();
232
+ const target = this.iframe?.contentWindow;
233
+ if (!target) throw internalError("The Beacon wallet is not available");
234
+ const id = newId();
235
+ return new Promise((resolve, reject) => {
236
+ const timer = setTimeout(() => {
237
+ this.pending.delete(id);
238
+ this.cancel(id);
239
+ reject(internalError(`Wallet request timed out (${method})`));
240
+ }, timeoutMs);
241
+ this.pending.set(id, { resolve, reject, timer });
242
+ const request = { type: "beacon:request", id, method, params };
243
+ target.postMessage(request, this.walletOrigin);
244
+ });
245
+ }
246
+ cancel(requestId) {
247
+ const request = { type: "beacon:request", id: newId(), method: "beacon_cancel", params: [requestId] };
248
+ this.iframe?.contentWindow?.postMessage(request, this.walletOrigin);
249
+ }
250
+ destroy() {
251
+ if (typeof window === "undefined") return;
252
+ window.removeEventListener("message", this.onMessage);
253
+ this.pending.forEach((entry) => {
254
+ clearTimeout(entry.timer);
255
+ entry.reject(internalError("Beacon was destroyed"));
256
+ });
257
+ this.pending.clear();
258
+ this.overlay?.remove();
259
+ this.overlay = this.iframe = null;
260
+ }
261
+ };
262
+ function newId() {
263
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
264
+ return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
265
+ }
266
+
267
+ // src/emitter.ts
268
+ var Emitter = class {
269
+ constructor() {
270
+ this.listeners = /* @__PURE__ */ new Map();
271
+ }
272
+ on(event, listener) {
273
+ let set = this.listeners.get(event);
274
+ if (!set) this.listeners.set(event, set = /* @__PURE__ */ new Set());
275
+ set.add(listener);
276
+ return () => this.off(event, listener);
277
+ }
278
+ off(event, listener) {
279
+ this.listeners.get(event)?.delete(listener);
280
+ }
281
+ emit(event, ...args) {
282
+ for (const listener of [...this.listeners.get(event) ?? []]) {
283
+ try {
284
+ listener(...args);
285
+ } catch {
286
+ }
287
+ }
288
+ }
289
+ };
290
+
291
+ // src/stellar.ts
292
+ async function wrap(run) {
293
+ try {
294
+ return await run();
295
+ } catch (error) {
296
+ if (error instanceof BeaconError) return { error: { code: error.code, message: error.message } };
297
+ return { error: { code: -1, message: "Something went wrong" } };
298
+ }
299
+ }
300
+ function createWalletInterface(beacon) {
301
+ return {
302
+ // getAddress logs the user in if needed, like Freighter's "connect".
303
+ getAddress: () => wrap(() => beacon.login()),
304
+ getNetwork: () => wrap(async () => {
305
+ const { id, passphrase } = beacon.getNetwork();
306
+ return { network: id === "mainnet" ? "PUBLIC" : "TESTNET", networkPassphrase: passphrase };
307
+ }),
308
+ signTransaction: (xdr, opts) => wrap(() => beacon.signTransaction(xdr, opts)),
309
+ signMessage: (message, opts) => wrap(() => beacon.signMessage(message, opts)),
310
+ signAuthEntry: (authEntry, opts) => wrap(() => beacon.signAuthEntry(authEntry, opts))
311
+ };
312
+ }
313
+
314
+ // src/BeaconAuth.ts
315
+ var DEFAULT_WALLET_URL = "https://wallet.beaconmcu.space";
316
+ var LOGIN_TIMEOUT_MS = 5 * 6e4;
317
+ var SIGNING_TIMEOUT_MS = 6e4;
318
+ var SEND_TIMEOUT_MS = 9e4;
319
+ var DEFAULT_TIMEOUT_MS = 15e3;
320
+ function checkNetwork(network) {
321
+ if (!isNetworkId(network)) {
322
+ throw new BeaconError(ErrorCode.UNSUPPORTED, `Unknown network "${String(network)}". Use "testnet" or "mainnet".`);
323
+ }
324
+ return network;
325
+ }
326
+ var BeaconAuth = class {
327
+ constructor(options) {
328
+ this.address = null;
329
+ // replaced by the wallet's active network once it connects
330
+ this.events = new Emitter();
331
+ if (!options || typeof options.clientId !== "string" || !options.clientId) {
332
+ throw new BeaconError(ErrorCode.INVALID_REQUEST, "BeaconAuth: clientId is required");
333
+ }
334
+ const defaultNetwork = options.defaultNetwork ? checkNetwork(options.defaultNetwork) : void 0;
335
+ const supported = options.supportedNetworks?.map(checkNetwork);
336
+ this.network = defaultNetwork ?? "testnet";
337
+ const networks = defaultNetwork || supported ? { default: defaultNetwork, supported } : void 0;
338
+ this.connection = new WalletConnection(options.walletUrl ?? DEFAULT_WALLET_URL, options.clientId, networks, options.showWalletUI !== false, {
339
+ onConnected: (address, network) => this.handleConnected(address, network),
340
+ onDisconnected: () => this.handleDisconnected(),
341
+ onNetworkChanged: (network) => this.handleNetworkChanged(network)
342
+ });
343
+ }
344
+ /** Opens the wallet and signs the user in with Google. Resolves with the Stellar address (G...). */
345
+ async login() {
346
+ if (this.address) return { address: this.address };
347
+ const result = await this.connection.request("beacon_login", [], LOGIN_TIMEOUT_MS);
348
+ return { address: result.address };
349
+ }
350
+ async logout() {
351
+ try {
352
+ await this.connection.request("beacon_logout", [], DEFAULT_TIMEOUT_MS);
353
+ } catch {
354
+ }
355
+ this.handleDisconnected();
356
+ }
357
+ /** Switches to another of the app's supportedNetworks. Rejects with code -6 for any other network. */
358
+ async switchNetwork(network) {
359
+ await this.connection.request("stellar_switchNetwork", [checkNetwork(network)], DEFAULT_TIMEOUT_MS);
360
+ }
361
+ // ---- sending and signing (the user approves in the wallet) ----
362
+ /**
363
+ * Sends XLM in one call. The wallet builds the payment, asks the user to approve it, signs it and
364
+ * submits it. Resolves with the transaction hash. (To create a new account, send at least 1 XLM.)
365
+ */
366
+ async sendPayment(payment) {
367
+ return await this.connection.request("stellar_sendPayment", [payment], SEND_TIMEOUT_MS);
368
+ }
369
+ // ---- signing (the user always approves inside the wallet) ----
370
+ /** Signs a transaction (base64 XDR). Returns the signed XDR; submit it yourself, e.g. through Horizon. */
371
+ async signTransaction(xdr, options = {}) {
372
+ return await this.connection.request(
373
+ "stellar_signTransaction",
374
+ [xdr, options],
375
+ SIGNING_TIMEOUT_MS
376
+ );
377
+ }
378
+ /** Signs a text message (SEP-53). The signature is base64. */
379
+ async signMessage(message, options = {}) {
380
+ return await this.connection.request("stellar_signMessage", [message, options], SIGNING_TIMEOUT_MS);
381
+ }
382
+ /** Signs a Soroban authorization entry preimage (base64 XDR). Returns a base64 signature. */
383
+ async signAuthEntry(preimage, options = {}) {
384
+ return await this.connection.request(
385
+ "stellar_signAuthEntry",
386
+ [preimage, options],
387
+ SIGNING_TIMEOUT_MS
388
+ );
389
+ }
390
+ // ---- state ----
391
+ getAddress() {
392
+ return this.address;
393
+ }
394
+ /** The active network (the default one until the wallet reports otherwise). */
395
+ getNetwork() {
396
+ return NETWORKS[this.network];
397
+ }
398
+ /**
399
+ * The same functions in the standard Stellar wallet shape (SEP-43), for libraries such as
400
+ * Stellar Wallets Kit: getAddress, signTransaction, signMessage, signAuthEntry, getNetwork.
401
+ */
402
+ getWalletInterface() {
403
+ return createWalletInterface(this);
404
+ }
405
+ on(event, callback) {
406
+ return this.events.on(event, callback);
407
+ }
408
+ off(event, callback) {
409
+ this.events.off(event, callback);
410
+ }
411
+ /** Removes the wallet iframe and listeners. */
412
+ destroy() {
413
+ this.connection.destroy();
414
+ }
415
+ // ---- wallet events ----
416
+ handleNetworkChanged(network) {
417
+ if (network === this.network) return;
418
+ this.network = network;
419
+ this.events.emit("networkChanged", network);
420
+ }
421
+ handleConnected(address, network) {
422
+ const accountChanged = this.address !== address;
423
+ const networkChanged = this.network !== network;
424
+ this.address = address;
425
+ this.network = network;
426
+ this.events.emit("connect", { address, network });
427
+ if (networkChanged) this.events.emit("networkChanged", network);
428
+ if (accountChanged) this.events.emit("accountChanged", address);
429
+ }
430
+ handleDisconnected() {
431
+ if (!this.address) return;
432
+ this.address = null;
433
+ this.events.emit("disconnect");
434
+ this.events.emit("accountChanged", null);
435
+ }
436
+ };
437
+
438
+ exports.BeaconAuth = BeaconAuth;
439
+ exports.BeaconError = BeaconError;
440
+ exports.NETWORKS = NETWORKS;
441
+ //# sourceMappingURL=index.cjs.map
442
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shared/networks.ts","../src/shared/messages.ts","../src/errors.ts","../src/connection.ts","../src/emitter.ts","../src/stellar.ts","../src/BeaconAuth.ts"],"names":[],"mappings":";;;AAeO,IAAM,QAAA,GAA2C;AAAA,EACtD,OAAA,EAAS;AAAA,IACP,EAAA,EAAI,SAAA;AAAA,IACJ,IAAA,EAAM,iBAAA;AAAA,IACN,UAAA,EAAY,mCAAA;AAAA,IACZ,UAAA,EAAY,qCAAA;AAAA,IACZ,WAAA,EAAa,yCAAA;AAAA,IACb,YAAA,EAAc;AAAA,GAChB;AAAA,EACA,OAAA,EAAS;AAAA,IACP,EAAA,EAAI,SAAA;AAAA,IACJ,IAAA,EAAM,iBAAA;AAAA,IACN,UAAA,EAAY,gDAAA;AAAA,IACZ,UAAA,EAAY,6BAAA;AAAA,IACZ,WAAA,EAAa;AAAA;AAEjB;AAEO,IAAM,WAAA,GAAc,CAAC,KAAA,KAAuC,KAAA,KAAU,aAAa,KAAA,KAAU,SAAA;;;AC1B7F,IAAM,SAAA,GAAY;AAAA,EACvB,QAAA,EAAU,EAAA;AAAA,EACA;AAAA,EACV,eAAA,EAAiB,EAAA;AAAA,EAEF;AAAA,EACf,WAAA,EAAa,EAEf,C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AACxC,IAAA,MAAM,cAAA,GAAiB,KAAK,OAAA,KAAY,OAAA;AACxC,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAEf,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,SAAA,EAAW,EAAE,OAAA,EAAS,SAAS,CAAA;AAChD,IAAA,IAAI,cAAA,EAAgB,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,kBAAkB,OAAO,CAAA;AAC9D,IAAA,IAAI,cAAA,EAAgB,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,kBAAkB,OAAO,CAAA;AAAA,EAChE;AAAA,EAEQ,kBAAA,GAA2B;AACjC,IAAA,IAAI,CAAC,KAAK,OAAA,EAAS;AACnB,IAAA,IAAA,CAAK,OAAA,GAAU,IAAA;AACf,IAAA,IAAA,CAAK,MAAA,CAAO,KAAK,YAAY,CAAA;AAC7B,IAAA,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,gBAAA,EAAkB,IAAI,CAAA;AAAA,EACzC;AACF","file":"index.cjs","sourcesContent":["// Stellar network data with NO imports, so the SDK bundle stays tiny.\n// The wallet keeps its own copy (wallet/src/shared/networks.ts): keep them in sync.\n// Source: https://developers.stellar.org/docs/networks\n\nexport type NetworkId = \"testnet\" | \"mainnet\";\n\nexport type NetworkInfo = {\n id: NetworkId;\n name: string;\n passphrase: string; // identifies the network inside every signed transaction\n horizonUrl: string;\n explorerUrl: string;\n friendbotUrl?: string; // free test funds: testnet only\n};\n\nexport const NETWORKS: Record<NetworkId, NetworkInfo> = {\n testnet: {\n id: \"testnet\",\n name: \"Stellar Testnet\",\n passphrase: \"Test SDF Network ; September 2015\",\n horizonUrl: \"https://horizon-testnet.stellar.org\",\n explorerUrl: \"https://stellar.expert/explorer/testnet\",\n friendbotUrl: \"https://friendbot.stellar.org\",\n },\n mainnet: {\n id: \"mainnet\",\n name: \"Stellar Mainnet\",\n passphrase: \"Public Global Stellar Network ; September 2015\",\n horizonUrl: \"https://horizon.stellar.org\",\n explorerUrl: \"https://stellar.expert/explorer/public\",\n },\n};\n\nexport const isNetworkId = (value: unknown): value is NetworkId => value === \"testnet\" || value === \"mainnet\";\n","// postMessage protocol between the SDK (parent page) and the wallet iframe.\n// Used by both sides. Contains no secrets and no crypto.\n// The wallet keeps its own copy (wallet/src/shared/messages.ts): keep them in sync.\n\nimport { isNetworkId, type NetworkId } from \"./networks\";\n\n// ---- error codes: the ones from SEP-43 (Stellar wallet interface), plus a few of ours ----\nexport const ErrorCode = {\n INTERNAL: -1, // internal wallet error\n EXTERNAL: -2, // an outside service (Horizon, network) failed\n INVALID_REQUEST: -3, // bad parameters, malformed XDR, wrong network\n USER_REJECTED: -4, // the user said no: do not retry\n NOT_CONNECTED: -5, // log in first\n UNSUPPORTED: -6, // method or network not supported\n BUSY: -7, // another request is already waiting for the user\n} as const;\n\nexport type RpcError = { code: number; message: string };\n\n// ---- SDK -> wallet ----\n\n// Must be the FIRST message the SDK sends. The wallet checks event.origin against the app's allowed origins.\n// Optionally carries the networks the app configured in code (defaultNetwork / supportedNetworks).\nexport type BeaconInit = {\n type: \"beacon:init\";\n networks?: { default?: NetworkId; supported?: NetworkId[] };\n // false = sign LOW-RISK requests (messages, plain payments) without a confirmation screen. Default: true.\n showWalletUI?: boolean;\n};\n\nexport type BeaconRequest = {\n type: \"beacon:request\";\n id: string;\n method: string;\n params?: unknown[];\n};\n\n// Methods the wallet handles.\nexport const WALLET_METHODS = [\n \"beacon_login\",\n \"beacon_logout\",\n \"beacon_cancel\", // params: [requestId]. The SDK gave up on a request (timeout): the wallet drops it.\n \"stellar_getAddress\",\n \"stellar_getNetwork\",\n \"stellar_switchNetwork\", // params: [networkId], only between the app's supported networks\n \"stellar_sendPayment\", // params: [{ to, amount, memo? }]. The wallet builds, signs and submits an XLM payment.\n \"stellar_signTransaction\", // params: [xdr, { networkPassphrase?, address? }?]\n \"stellar_signMessage\", // params: [message, { address? }?] (SEP-53)\n \"stellar_signAuthEntry\", // params: [base64 preimage, { networkPassphrase?, address? }?]\n] as const;\n\n// ---- wallet -> SDK ----\n\nexport type BeaconResponse =\n | { type: \"beacon:response\"; id: string; result: unknown }\n | { type: \"beacon:response\"; id: string; error: RpcError };\n\nexport type WalletEvent =\n | { type: \"beacon:ready\" }\n | { type: \"beacon:connected\"; address: string; network: NetworkId }\n | { type: \"beacon:disconnected\" }\n | { type: \"beacon:show\" }\n | { type: \"beacon:hide\" }\n | { type: \"beacon:resize\"; height: number } // content height in px, so the SDK can fit the iframe\n | { type: \"beacon:networkChanged\"; network: NetworkId };\n\nexport type WalletMessage = BeaconResponse | WalletEvent;\n\n// ---- type guards (message data is untrusted) ----\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nexport function isBeaconInit(data: unknown): data is BeaconInit {\n return isObject(data) && data.type === \"beacon:init\";\n}\n\n// The networks an app asked for in its init message (untrusted input): known ids only.\nexport function readInitNetworks(init: BeaconInit): { default?: NetworkId; supported: NetworkId[] } {\n const raw = init.networks;\n const supported = Array.isArray(raw?.supported) ? raw.supported.filter(isNetworkId).slice(0, 2) : [];\n return { default: isNetworkId(raw?.default) ? raw.default : undefined, supported };\n}\n\n// Did the app turn confirmation screens off? (untrusted input: only an explicit false counts)\nexport function readInitShowWalletUI(init: BeaconInit): boolean {\n return init.showWalletUI !== false;\n}\n\nexport function isBeaconRequest(data: unknown): data is BeaconRequest {\n return (\n isObject(data) &&\n data.type === \"beacon:request\" &&\n typeof data.id === \"string\" &&\n typeof data.method === \"string\" &&\n (data.params === undefined || Array.isArray(data.params))\n );\n}\n\nexport function isWalletMessage(data: unknown): data is WalletMessage {\n if (!isObject(data) || typeof data.type !== \"string\") return false;\n switch (data.type) {\n case \"beacon:ready\":\n case \"beacon:disconnected\":\n case \"beacon:show\":\n case \"beacon:hide\":\n return true;\n case \"beacon:networkChanged\":\n return isNetworkId(data.network);\n case \"beacon:resize\":\n return typeof data.height === \"number\" && Number.isFinite(data.height) && data.height > 0;\n case \"beacon:connected\":\n return typeof data.address === \"string\" && isNetworkId(data.network);\n case \"beacon:response\":\n return (\n typeof data.id === \"string\" &&\n (\"result\" in data ||\n (isObject(data.error) && typeof data.error.code === \"number\" && typeof data.error.message === \"string\"))\n );\n default:\n return false;\n }\n}\n","import { ErrorCode } from \"./shared/messages\";\n\n// Error with a numeric `code` from the Stellar wallet standard (SEP-43): -4 means the user rejected it.\nexport class BeaconError extends Error {\n code: number;\n\n constructor(code: number, message: string) {\n super(message);\n this.name = \"BeaconError\";\n this.code = code;\n }\n}\n\nexport const internalError = (message: string) => new BeaconError(ErrorCode.INTERNAL, message);\n","import {\n isWalletMessage,\n ErrorCode,\n type BeaconInit,\n type BeaconRequest,\n type BeaconResponse,\n} from \"./shared/messages\";\nimport { BeaconError, internalError } from \"./errors\";\nimport type { NetworkId } from \"./shared/networks\";\n\nconst READY_TIMEOUT_MS = 15_000;\n\n// Requests that open the wallet window. If the wallet is still loading, the frame opens at once and\n// the wallet shows its own loading screen (the SDK draws nothing itself).\nconst INTERACTIVE_METHODS = new Set([\n \"beacon_login\",\n \"stellar_sendPayment\",\n \"stellar_signTransaction\",\n \"stellar_signMessage\",\n \"stellar_signAuthEntry\",\n]);\n\ntype Pending = {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\ntype Handlers = {\n onNetworkChanged: (network: NetworkId) => void;\n onConnected: (address: string, network: NetworkId) => void;\n onDisconnected: () => void;\n};\n\n// Owns the wallet iframe and the postMessage channel to it.\n// Only messages from the wallet's origin AND from this iframe's window are accepted.\nexport class WalletConnection {\n private readonly walletOrigin: string;\n private readonly src: string;\n private overlay: HTMLDivElement | null = null;\n private iframe: HTMLIFrameElement | null = null;\n private openedEarly = false; // the frame was opened before the wallet asked for it (it was still loading)\n private pending = new Map<string, Pending>();\n private isReady = false;\n private readyWaiters: Array<() => void> = [];\n\n constructor(\n walletUrl: string,\n private clientId: string,\n private networks: { default?: NetworkId; supported?: NetworkId[] } | undefined,\n private showWalletUI: boolean,\n private handlers: Handlers,\n ) {\n let url: URL;\n try {\n url = new URL(walletUrl);\n } catch {\n throw new BeaconError(ErrorCode.INTERNAL, `Invalid walletUrl: ${walletUrl}`);\n }\n this.walletOrigin = url.origin;\n url.pathname = \"/\";\n url.search = \"\";\n url.hash = \"\";\n url.searchParams.set(\"client_id\", clientId);\n this.src = url.toString();\n\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"message\", this.onMessage);\n this.mount();\n }\n }\n\n // ---- iframe + modal ----\n\n private mount(): void {\n const attach = () => {\n const overlay = document.createElement(\"div\");\n Object.assign(overlay.style, {\n display: \"none\",\n position: \"fixed\",\n inset: \"0\",\n zIndex: \"2147483647\",\n alignItems: \"center\",\n justifyContent: \"center\",\n background: \"rgba(0, 0, 0, 0.6)\",\n });\n\n const iframe = document.createElement(\"iframe\");\n iframe.title = \"Beacon wallet\";\n // clipboard-write: lets the wallet copy the address.\n iframe.allow = \"clipboard-write\";\n iframe.src = this.src;\n Object.assign(iframe.style, {\n width: \"min(380px, calc(100vw - 32px))\",\n height: \"160px\", // the wallet's loading screen; replaced by its real content height (beacon:resize)\n maxHeight: \"calc(100vh - 32px)\",\n transition: \"height 120ms ease\",\n border: \"0\",\n borderRadius: \"20px\", // the wallet is one white card; the iframe clips it to rounded corners\n background: \"#ffffff\",\n overflow: \"hidden\",\n });\n\n // The first message to the wallet. It checks our origin against the app's allowed origins.\n iframe.addEventListener(\"load\", () => {\n const init: BeaconInit = { type: \"beacon:init\", ...(this.networks && { networks: this.networks }),\n ...(!this.showWalletUI && { showWalletUI: false }) };\n iframe.contentWindow?.postMessage(init, this.walletOrigin);\n });\n\n overlay.appendChild(iframe);\n document.body.appendChild(overlay);\n this.overlay = overlay;\n this.iframe = iframe;\n };\n\n if (document.body) attach();\n else document.addEventListener(\"DOMContentLoaded\", attach, { once: true });\n }\n\n private setVisible(visible: boolean): void {\n if (!this.overlay || !this.iframe) return;\n this.openedEarly = false;\n this.overlay.style.display = visible ? \"flex\" : \"none\";\n if (visible) this.iframe.focus();\n }\n\n // The user acted before the wallet finished loading: open the frame now. The wallet's own\n // loading screen is what they see, and it takes over from there.\n private openEarly(): void {\n if (!this.overlay || this.openedEarly || this.overlay.style.display !== \"none\") return;\n this.openedEarly = true;\n this.overlay.style.display = \"flex\";\n }\n\n // Opened early, but the wallet never asked to be shown (or failed): close it again.\n private closeEarly(): void {\n if (!this.openedEarly) return;\n this.openedEarly = false;\n if (this.overlay) this.overlay.style.display = \"none\";\n }\n\n // ---- incoming messages ----\n\n private onMessage = (event: MessageEvent): void => {\n if (event.origin !== this.walletOrigin) return;\n if (!this.iframe || event.source !== this.iframe.contentWindow) return;\n if (!isWalletMessage(event.data)) return;\n\n const message = event.data;\n switch (message.type) {\n case \"beacon:ready\":\n this.isReady = true;\n this.readyWaiters.splice(0).forEach((resolve) => resolve());\n break;\n case \"beacon:show\":\n this.setVisible(true);\n break;\n case \"beacon:hide\":\n this.setVisible(false);\n break;\n case \"beacon:resize\":\n // Fit the modal to the wallet's content (max-height keeps it inside the viewport).\n if (this.iframe) this.iframe.style.height = `${Math.ceil(message.height)}px`;\n break;\n case \"beacon:networkChanged\":\n this.handlers.onNetworkChanged(message.network);\n break;\n case \"beacon:connected\":\n this.handlers.onConnected(message.address, message.network);\n break;\n case \"beacon:disconnected\":\n this.handlers.onDisconnected();\n break;\n case \"beacon:response\":\n this.settle(message);\n break;\n }\n };\n\n private settle(message: BeaconResponse): void {\n const entry = this.pending.get(message.id);\n if (!entry) return; // unknown or already timed out\n this.closeEarly(); // answered without ever showing the wallet (e.g. already connected)\n this.pending.delete(message.id);\n clearTimeout(entry.timer);\n\n if (\"error\" in message) entry.reject(new BeaconError(message.error.code, message.error.message));\n else entry.resolve(message.result);\n }\n\n // ---- outgoing requests ----\n\n private whenReady(): Promise<void> {\n if (this.isReady) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this.readyWaiters = this.readyWaiters.filter((w) => w !== onReady);\n this.closeEarly();\n reject(\n internalError(\n `The Beacon wallet did not load. Check that this site (${window.location.origin}) is an allowed origin ` +\n `for Client ID ${this.clientId}, and that the wallet URL (${this.walletOrigin}) is correct.`,\n ),\n );\n }, READY_TIMEOUT_MS);\n const onReady = () => {\n clearTimeout(timer);\n resolve();\n };\n this.readyWaiters.push(onReady);\n });\n }\n\n async request(method: string, params: unknown[], timeoutMs: number): Promise<unknown> {\n if (typeof window === \"undefined\") throw internalError(\"Beacon can only be used in a browser\");\n // Still loading? Open the frame now instead of waiting invisibly.\n if (!this.isReady && INTERACTIVE_METHODS.has(method)) this.openEarly();\n await this.whenReady();\n\n const target = this.iframe?.contentWindow;\n if (!target) throw internalError(\"The Beacon wallet is not available\");\n\n const id = newId();\n return new Promise<unknown>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pending.delete(id);\n this.cancel(id); // tell the wallet to drop it, so a late approval can't go unnoticed\n reject(internalError(`Wallet request timed out (${method})`));\n }, timeoutMs);\n\n this.pending.set(id, { resolve, reject, timer });\n const request: BeaconRequest = { type: \"beacon:request\", id, method, params };\n target.postMessage(request, this.walletOrigin);\n });\n }\n\n private cancel(requestId: string): void {\n const request: BeaconRequest = { type: \"beacon:request\", id: newId(), method: \"beacon_cancel\", params: [requestId] };\n this.iframe?.contentWindow?.postMessage(request, this.walletOrigin);\n }\n\n destroy(): void {\n if (typeof window === \"undefined\") return;\n window.removeEventListener(\"message\", this.onMessage);\n this.pending.forEach((entry) => {\n clearTimeout(entry.timer);\n entry.reject(internalError(\"Beacon was destroyed\"));\n });\n this.pending.clear();\n this.overlay?.remove();\n this.overlay = this.iframe = null;\n }\n}\n\nfunction newId(): string {\n if (typeof crypto !== \"undefined\" && \"randomUUID\" in crypto) return crypto.randomUUID();\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Listener = (...args: any[]) => void;\n\nexport class Emitter {\n private listeners = new Map<string, Set<Listener>>();\n\n on(event: string, listener: Listener): () => void {\n let set = this.listeners.get(event);\n if (!set) this.listeners.set(event, (set = new Set()));\n set.add(listener);\n return () => this.off(event, listener);\n }\n\n off(event: string, listener: Listener): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n emit(event: string, ...args: unknown[]): void {\n for (const listener of [...(this.listeners.get(event) ?? [])]) {\n try {\n listener(...args);\n } catch {\n // A faulty listener in the dApp must not break the SDK.\n }\n }\n }\n}\n","import type { BeaconAuth } from \"./BeaconAuth\";\nimport { BeaconError } from \"./errors\";\n\n// The standard Stellar wallet interface (SEP-43), so Beacon can plug into libraries like Stellar\n// Wallets Kit. Each function returns the result, or { error: { code, message } } instead of throwing.\n// Error codes: -1 internal, -2 external service, -3 invalid request, -4 user rejected.\n\ntype WalletError = { error: { code: number; message: string } };\n\nexport interface StellarWalletInterface {\n getAddress(): Promise<{ address: string } | WalletError>;\n getNetwork(): Promise<{ network: string; networkPassphrase: string } | WalletError>;\n signTransaction(\n xdr: string,\n opts?: { networkPassphrase?: string; address?: string },\n ): Promise<{ signedTxXdr: string; signerAddress: string } | WalletError>;\n signMessage(\n message: string,\n opts?: { address?: string },\n ): Promise<{ signedMessage: string; signerAddress: string } | WalletError>;\n signAuthEntry(\n authEntry: string,\n opts?: { networkPassphrase?: string; address?: string },\n ): Promise<{ signedAuthEntry: string; signerAddress: string } | WalletError>;\n}\n\nasync function wrap<T>(run: () => Promise<T>): Promise<T | WalletError> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof BeaconError) return { error: { code: error.code, message: error.message } };\n return { error: { code: -1, message: \"Something went wrong\" } };\n }\n}\n\nexport function createWalletInterface(beacon: BeaconAuth): StellarWalletInterface {\n return {\n // getAddress logs the user in if needed, like Freighter's \"connect\".\n getAddress: () => wrap(() => beacon.login()),\n getNetwork: () =>\n wrap(async () => {\n const { id, passphrase } = beacon.getNetwork();\n return { network: id === \"mainnet\" ? \"PUBLIC\" : \"TESTNET\", networkPassphrase: passphrase };\n }),\n signTransaction: (xdr, opts) => wrap(() => beacon.signTransaction(xdr, opts)),\n signMessage: (message, opts) => wrap(() => beacon.signMessage(message, opts)),\n signAuthEntry: (authEntry, opts) => wrap(() => beacon.signAuthEntry(authEntry, opts)),\n };\n}\n","import { WalletConnection } from \"./connection\";\nimport { Emitter } from \"./emitter\";\nimport { BeaconError } from \"./errors\";\nimport { ErrorCode } from \"./shared/messages\";\nimport { isNetworkId, NETWORKS, type NetworkId, type NetworkInfo } from \"./shared/networks\";\nimport { createWalletInterface, type StellarWalletInterface } from \"./stellar\";\n\nexport type BeaconOptions = {\n /** Public Client ID from the Beacon dashboard (bcn_app_...). */\n clientId: string;\n /** Network used on login. Defaults to the app's network from the dashboard (testnet if none). */\n defaultNetwork?: NetworkId;\n /** Networks the app can switch between with switchNetwork(). Defaults to just the default network. */\n supportedNetworks?: NetworkId[];\n /** Defaults to https://wallet.beaconmcu.space */\n walletUrl?: string;\n /**\n * Show the wallet's confirmation screen before signing. Default true.\n * Set false to sign low-risk requests silently (messages and plain XLM payments from the user's own\n * account). Anything risky (contract calls, account changes, other accounts) is always confirmed.\n */\n showWalletUI?: boolean;\n};\n\nexport type BeaconEventMap = {\n connect: (info: { address: string; network: NetworkId }) => void;\n disconnect: () => void;\n accountChanged: (address: string | null) => void;\n networkChanged: (network: NetworkId) => void;\n};\n\nconst DEFAULT_WALLET_URL = \"https://wallet.beaconmcu.space\";\n\n// Waiting for a person: sign-in includes a Google popup, so it gets longer than other calls.\nconst LOGIN_TIMEOUT_MS = 5 * 60_000;\nconst SIGNING_TIMEOUT_MS = 60_000;\nconst SEND_TIMEOUT_MS = 90_000; // approval plus building and submitting on the network\nconst DEFAULT_TIMEOUT_MS = 15_000;\n\nfunction checkNetwork(network: unknown): NetworkId {\n if (!isNetworkId(network)) {\n throw new BeaconError(ErrorCode.UNSUPPORTED, `Unknown network \"${String(network)}\". Use \"testnet\" or \"mainnet\".`);\n }\n return network;\n}\n\nexport class BeaconAuth {\n private address: string | null = null;\n private network: NetworkId; // replaced by the wallet's active network once it connects\n private events = new Emitter();\n private connection: WalletConnection;\n\n constructor(options: BeaconOptions) {\n if (!options || typeof options.clientId !== \"string\" || !options.clientId) {\n throw new BeaconError(ErrorCode.INVALID_REQUEST, \"BeaconAuth: clientId is required\");\n }\n\n const defaultNetwork = options.defaultNetwork ? checkNetwork(options.defaultNetwork) : undefined;\n const supported = options.supportedNetworks?.map(checkNetwork);\n this.network = defaultNetwork ?? \"testnet\";\n const networks = defaultNetwork || supported ? { default: defaultNetwork, supported } : undefined;\n\n this.connection = new WalletConnection(options.walletUrl ?? DEFAULT_WALLET_URL, options.clientId, networks, options.showWalletUI !== false, {\n onConnected: (address, network) => this.handleConnected(address, network),\n onDisconnected: () => this.handleDisconnected(),\n onNetworkChanged: (network) => this.handleNetworkChanged(network),\n });\n }\n\n /** Opens the wallet and signs the user in with Google. Resolves with the Stellar address (G...). */\n async login(): Promise<{ address: string }> {\n if (this.address) return { address: this.address };\n const result = (await this.connection.request(\"beacon_login\", [], LOGIN_TIMEOUT_MS)) as { address: string };\n return { address: result.address };\n }\n\n async logout(): Promise<void> {\n try {\n await this.connection.request(\"beacon_logout\", [], DEFAULT_TIMEOUT_MS);\n } catch {\n // The wallet is unreachable: still forget the session locally.\n }\n this.handleDisconnected();\n }\n\n /** Switches to another of the app's supportedNetworks. Rejects with code -6 for any other network. */\n async switchNetwork(network: NetworkId): Promise<void> {\n await this.connection.request(\"stellar_switchNetwork\", [checkNetwork(network)], DEFAULT_TIMEOUT_MS);\n }\n\n // ---- sending and signing (the user approves in the wallet) ----\n\n /**\n * Sends XLM in one call. The wallet builds the payment, asks the user to approve it, signs it and\n * submits it. Resolves with the transaction hash. (To create a new account, send at least 1 XLM.)\n */\n async sendPayment(payment: { to: string; amount: string; memo?: string }): Promise<{ hash: string }> {\n return (await this.connection.request(\"stellar_sendPayment\", [payment], SEND_TIMEOUT_MS)) as { hash: string };\n }\n\n // ---- signing (the user always approves inside the wallet) ----\n\n /** Signs a transaction (base64 XDR). Returns the signed XDR; submit it yourself, e.g. through Horizon. */\n async signTransaction(\n xdr: string,\n options: { networkPassphrase?: string; address?: string } = {},\n ): Promise<{ signedTxXdr: string; signerAddress: string }> {\n return (await this.connection.request(\n \"stellar_signTransaction\",\n [xdr, options],\n SIGNING_TIMEOUT_MS,\n )) as { signedTxXdr: string; signerAddress: string };\n }\n\n /** Signs a text message (SEP-53). The signature is base64. */\n async signMessage(\n message: string,\n options: { address?: string } = {},\n ): Promise<{ signedMessage: string; signerAddress: string }> {\n return (await this.connection.request(\"stellar_signMessage\", [message, options], SIGNING_TIMEOUT_MS)) as {\n signedMessage: string;\n signerAddress: string;\n };\n }\n\n /** Signs a Soroban authorization entry preimage (base64 XDR). Returns a base64 signature. */\n async signAuthEntry(\n preimage: string,\n options: { networkPassphrase?: string; address?: string } = {},\n ): Promise<{ signedAuthEntry: string; signerAddress: string }> {\n return (await this.connection.request(\n \"stellar_signAuthEntry\",\n [preimage, options],\n SIGNING_TIMEOUT_MS,\n )) as { signedAuthEntry: string; signerAddress: string };\n }\n\n // ---- state ----\n\n getAddress(): string | null {\n return this.address;\n }\n\n /** The active network (the default one until the wallet reports otherwise). */\n getNetwork(): NetworkInfo {\n return NETWORKS[this.network];\n }\n\n /**\n * The same functions in the standard Stellar wallet shape (SEP-43), for libraries such as\n * Stellar Wallets Kit: getAddress, signTransaction, signMessage, signAuthEntry, getNetwork.\n */\n getWalletInterface(): StellarWalletInterface {\n return createWalletInterface(this);\n }\n\n on<E extends keyof BeaconEventMap>(event: E, callback: BeaconEventMap[E]): () => void {\n return this.events.on(event, callback);\n }\n\n off<E extends keyof BeaconEventMap>(event: E, callback: BeaconEventMap[E]): void {\n this.events.off(event, callback);\n }\n\n /** Removes the wallet iframe and listeners. */\n destroy(): void {\n this.connection.destroy();\n }\n\n // ---- wallet events ----\n\n private handleNetworkChanged(network: NetworkId): void {\n if (network === this.network) return;\n this.network = network;\n this.events.emit(\"networkChanged\", network);\n }\n\n private handleConnected(address: string, network: NetworkId): void {\n const accountChanged = this.address !== address;\n const networkChanged = this.network !== network;\n this.address = address;\n this.network = network;\n\n this.events.emit(\"connect\", { address, network });\n if (networkChanged) this.events.emit(\"networkChanged\", network);\n if (accountChanged) this.events.emit(\"accountChanged\", address);\n }\n\n private handleDisconnected(): void {\n if (!this.address) return;\n this.address = null;\n this.events.emit(\"disconnect\");\n this.events.emit(\"accountChanged\", null);\n }\n}\n"]}