@beaconmcu/auth 0.0.0-stage → 0.1.1
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 +142 -2
- package/dist/index.cjs +442 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +142 -0
- package/dist/index.d.ts +142 -0
- package/dist/index.js +438 -0
- package/dist/index.js.map +1 -0
- package/package.json +44 -4
package/README.md
CHANGED
|
@@ -1,3 +1,143 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @beaconmcu/auth
|
|
2
2
|
|
|
3
|
-
|
|
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) and copy its Client ID. Local development (`localhost`) works with nothing else to set up; add your live site's address under **Domains** before you launch.
|
|
12
|
+
|
|
13
|
+
**Requirements:** a modern browser. The package has no dependencies, includes TypeScript types, and works as ESM or CommonJS. Full docs: https://dashboard.beaconmcu.space/docs
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { BeaconAuth } from "@beaconmcu/auth";
|
|
19
|
+
|
|
20
|
+
const beacon = new BeaconAuth({ clientId: "bcn_app_xxxxxxxxxxxxxxxxxxxxxxxx" });
|
|
21
|
+
|
|
22
|
+
const { address } = await beacon.login(); // opens the wallet, user signs in with Google
|
|
23
|
+
console.log("Stellar address:", address); // G...
|
|
24
|
+
|
|
25
|
+
beacon.on("accountChanged", (address) => console.log(address));
|
|
26
|
+
await beacon.logout();
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`beacon.getAddress()` returns the address or `null`. `beacon.getNetwork()` returns the active network.
|
|
30
|
+
|
|
31
|
+
## React and Next.js
|
|
32
|
+
|
|
33
|
+
Create one `BeaconAuth` for the whole app, in its own file, and read it from your components:
|
|
34
|
+
|
|
35
|
+
```tsx
|
|
36
|
+
// beacon.ts
|
|
37
|
+
import { BeaconAuth } from "@beaconmcu/auth";
|
|
38
|
+
export const beacon = new BeaconAuth({ clientId: "bcn_app_...", defaultNetwork: "testnet" });
|
|
39
|
+
|
|
40
|
+
// LoginButton.tsx (in Next.js, add "use client" at the top)
|
|
41
|
+
import { useEffect, useState } from "react";
|
|
42
|
+
import { beacon } from "./beacon";
|
|
43
|
+
|
|
44
|
+
export function LoginButton() {
|
|
45
|
+
const [address, setAddress] = useState(beacon.getAddress());
|
|
46
|
+
|
|
47
|
+
useEffect(() => beacon.on("accountChanged", setAddress), []); // returns the function that unsubscribes
|
|
48
|
+
|
|
49
|
+
return address ? (
|
|
50
|
+
<button onClick={() => beacon.logout()}>Log out ({address.slice(0, 6)}…)</button>
|
|
51
|
+
) : (
|
|
52
|
+
<button onClick={() => beacon.login()}>Log in</button>
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
It is safe to import on the server (it only touches the page in the browser). Use it from client-side code.
|
|
58
|
+
|
|
59
|
+
## Send XLM (one call)
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
const { hash } = await beacon.sendPayment({ to: "G...", amount: "10" });
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
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.
|
|
66
|
+
|
|
67
|
+
## Sign (the user always approves in the wallet)
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
// Sign a message (SEP-53). The signature is base64.
|
|
71
|
+
const { signedMessage } = await beacon.signMessage("Hello Stellar");
|
|
72
|
+
|
|
73
|
+
// For anything beyond a plain XLM payment, build the transaction with the Stellar SDK,
|
|
74
|
+
// sign it with Beacon, then submit it yourself.
|
|
75
|
+
import { TransactionBuilder, Operation, Asset, Horizon } from "@stellar/stellar-sdk";
|
|
76
|
+
|
|
77
|
+
const server = new Horizon.Server(beacon.getNetwork().horizonUrl);
|
|
78
|
+
const account = await server.loadAccount(address);
|
|
79
|
+
const tx = new TransactionBuilder(account, { fee: "100", networkPassphrase: beacon.getNetwork().passphrase })
|
|
80
|
+
.addOperation(Operation.payment({ destination: "G...", asset: Asset.native(), amount: "10" }))
|
|
81
|
+
.setTimeout(180)
|
|
82
|
+
.build();
|
|
83
|
+
|
|
84
|
+
const { signedTxXdr } = await beacon.signTransaction(tx.toXDR());
|
|
85
|
+
await server.submitTransaction(TransactionBuilder.fromXDR(signedTxXdr, beacon.getNetwork().passphrase));
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
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`.
|
|
89
|
+
|
|
90
|
+
## Silent signing (optional)
|
|
91
|
+
|
|
92
|
+
By default every signature opens a confirmation screen. An app can turn the screen off, like Privy's `showWalletUIs`:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
const beacon = new BeaconAuth({ clientId: "bcn_app_...", showWalletUI: false });
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
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.
|
|
99
|
+
|
|
100
|
+
Turn the screen off only if you are comfortable with your app moving the user's XLM without a prompt.
|
|
101
|
+
|
|
102
|
+
## Choose the network (in code)
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
const beacon = new BeaconAuth({
|
|
106
|
+
clientId: "bcn_app_...",
|
|
107
|
+
defaultNetwork: "testnet", // used on login
|
|
108
|
+
supportedNetworks: ["testnet", "mainnet"], // the app may switch between these
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
await beacon.switchNetwork("mainnet");
|
|
112
|
+
beacon.on("networkChanged", (network) => console.log(network));
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
- `"testnet"` has free test XLM (Friendbot). `"mainnet"` is real money.
|
|
116
|
+
- Without `defaultNetwork`, the app's network from the Beacon dashboard is used (testnet if none).
|
|
117
|
+
- A network outside `supportedNetworks` is rejected with error code `-6`.
|
|
118
|
+
- Every approval screen in the wallet shows the network, and marks mainnet as "real funds".
|
|
119
|
+
- A Stellar account exists only after it receives at least 1 XLM. On testnet, fund it with Friendbot.
|
|
120
|
+
|
|
121
|
+
## Use it with wallet libraries (SEP-43)
|
|
122
|
+
|
|
123
|
+
`beacon.getWalletInterface()` returns the standard Stellar wallet shape (`getAddress`, `getNetwork`, `signTransaction`, `signMessage`, `signAuthEntry`), so libraries such as Stellar Wallets Kit can use Beacon.
|
|
124
|
+
|
|
125
|
+
## Options
|
|
126
|
+
|
|
127
|
+
| Option | Default | Notes |
|
|
128
|
+
|---------------------|----------------------------------|--------------------------------------------|
|
|
129
|
+
| `clientId` | required | From the dashboard |
|
|
130
|
+
| `defaultNetwork` | the dashboard's network | `"testnet"` or `"mainnet"` |
|
|
131
|
+
| `supportedNetworks` | just the default | Networks `switchNetwork` may use |
|
|
132
|
+
| `showWalletUI` | `true` | `false` = sign low-risk requests silently |
|
|
133
|
+
| `walletUrl` | `https://wallet.beaconmcu.space` | Override for local development |
|
|
134
|
+
|
|
135
|
+
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.
|
|
136
|
+
|
|
137
|
+
## Security model
|
|
138
|
+
|
|
139
|
+
- **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.
|
|
140
|
+
- **Your site and the wallet talk only through `postMessage`**, and both sides check the sender's origin and window.
|
|
141
|
+
- **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.
|
|
142
|
+
- **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.
|
|
143
|
+
- **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
|