@lydianpay/sdk-web 3.13.0 → 3.14.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.
@@ -0,0 +1,314 @@
1
+ var f = Object.defineProperty;
2
+ var S = (e, t, n) => t in e ? f(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var h = (e, t, n) => S(e, typeof t != "symbol" ? t + "" : t, n);
4
+ import { d as s } from "./index-B2KlqxZz.js";
5
+ import { v as w } from "./connect-multichain-W5NFpeTb.js";
6
+ import { a as l } from "./mountEngine-0u7my-Xz.js";
7
+ function m(e) {
8
+ var t, n;
9
+ return typeof ((n = (t = e == null ? void 0 : e.prototype) == null ? void 0 : t.constructor) == null ? void 0 : n.name) == "string";
10
+ }
11
+ function p(e, t) {
12
+ return m(e) ? new e({
13
+ message: t
14
+ }) : e({
15
+ message: t
16
+ });
17
+ }
18
+ class _ extends Error {
19
+ constructor(t) {
20
+ super(t.message), this.code = "ERR_ASSERTION";
21
+ }
22
+ }
23
+ function u(e, t = "Assertion failed.", n = _) {
24
+ if (!e)
25
+ throw t instanceof Error ? t : p(n, t);
26
+ }
27
+ function T(e) {
28
+ return e instanceof Uint8Array;
29
+ }
30
+ function C(e) {
31
+ u(T(e), "Value must be a Uint8Array.");
32
+ }
33
+ function x(e) {
34
+ return C(e), l.encode(e);
35
+ }
36
+ function E(e) {
37
+ return u(typeof e == "string", "Value must be a string."), l.decode(e);
38
+ }
39
+ var y = class {
40
+ constructor(e) {
41
+ h(this, "context");
42
+ this.context = e;
43
+ }
44
+ /**
45
+ * Executes the complete trusted connection flow.
46
+ * This method is fully self-contained and handles the connection process.
47
+ */
48
+ async execute(e, t) {
49
+ await this.context.transport.connect(), await this.context.transport.subscribe(t.channel);
50
+ const n = await this._waitForHandshakeOffer(t.expiresAt), i = this._createFinalSession(e, n);
51
+ this.context.session = i, await this._finalizeConnection(i, t);
52
+ }
53
+ /**
54
+ * Waits for a `handshake-offer` message from the wallet.
55
+ *
56
+ * This method uses a dual-timeout strategy. The total wait time is the sum of the
57
+ * `SessionRequest` TTL (the time the user has to scan the QR code) and the
58
+ * `HANDSHAKE_TIMEOUT` (a grace period for the dApp to resume from suspension
59
+ * and process the historical message from the relay).
60
+ *
61
+ * @param requestExpiry - The timestamp when the session request expires.
62
+ * @returns A promise that resolves with the `HandshakeOfferPayload`.
63
+ * @throws {SessionError} If the offer is not received before the combined timeout expires.
64
+ */
65
+ _waitForHandshakeOffer(e) {
66
+ return new Promise((t, n) => {
67
+ if (e < Date.now())
68
+ return n(new s.SessionError(s.ErrorCode.REQUEST_EXPIRED, "Session request expired before wallet could connect"));
69
+ const i = e + N - Date.now(), o = setTimeout(() => {
70
+ this.context.off("handshake_offer_received", r), n(new s.SessionError(s.ErrorCode.REQUEST_EXPIRED, "Did not receive handshake offer from wallet in time."));
71
+ }, i), r = (a) => {
72
+ clearTimeout(o), t(a);
73
+ };
74
+ this.context.once("handshake_offer_received", r);
75
+ });
76
+ }
77
+ /**
78
+ * Creates the final session object with details from the wallet's offer.
79
+ *
80
+ * @param session - The pending session object (with temporary values)
81
+ * @param offer - The handshake offer payload from the wallet
82
+ * @returns The complete session object ready for use
83
+ */
84
+ _createFinalSession(e, t) {
85
+ const n = E(t.publicKeyB64);
86
+ return this.context.keymanager.validatePeerKey(n), {
87
+ ...e,
88
+ channel: `session:${t.channelId}`,
89
+ theirPublicKey: n
90
+ };
91
+ }
92
+ /**
93
+ * Completes the connection by persisting the session, cleaning up the
94
+ * temporary handshake channel, and transitioning to the `CONNECTED` state.
95
+ *
96
+ * @param session - The finalized session object
97
+ * @param request - The session request object
98
+ */
99
+ async _finalizeConnection(e, t) {
100
+ if (!this.context.session) throw new s.SessionError(s.ErrorCode.SESSION_INVALID_STATE);
101
+ await this.context.sessionstore.set(this.context.session), await this.context.transport.subscribe(e.channel), await this.context.transport.clear(t.channel), this.context.state = s.ClientState.CONNECTED, this.context.emit("connected");
102
+ }
103
+ }, I = class {
104
+ constructor(e) {
105
+ h(this, "context");
106
+ h(this, "otpAttempts", 3);
107
+ h(this, "timeoutId", null);
108
+ this.context = e;
109
+ }
110
+ /**
111
+ * Executes the complete untrusted connection flow.
112
+ * This method is fully self-contained and handles the entire OTP-based connection process.
113
+ */
114
+ async execute(e, t) {
115
+ await this.context.transport.connect(), await this.context.transport.subscribe(t.channel);
116
+ const n = await this._waitForHandshakeOffer(t.expiresAt);
117
+ await this._handleOtpInput(n);
118
+ const i = this._createFinalSession(e, n);
119
+ this.context.session = i, await this._acknowledgeHandshake(i), await this._finalizeConnection(t.channel);
120
+ }
121
+ /**
122
+ * Waits for a `handshake-offer` message from the wallet on the handshake channel.
123
+ *
124
+ * @param requestExpiry - The timestamp when the session request expires
125
+ * @returns A promise that resolves with the `HandshakeOfferPayload`
126
+ * @throws {SessionError} If the offer is not received before the request expires
127
+ */
128
+ _waitForHandshakeOffer(e) {
129
+ return new Promise((t, n) => {
130
+ const i = e - Date.now();
131
+ if (i <= 0)
132
+ return n(new s.SessionError(s.ErrorCode.REQUEST_EXPIRED, "Session request expired before wallet could connect."));
133
+ this.timeoutId = setTimeout(() => {
134
+ this.context.off("handshake_offer_received", o), n(new s.SessionError(s.ErrorCode.REQUEST_EXPIRED, "Did not receive handshake offer from wallet in time."));
135
+ }, i);
136
+ const o = (r) => {
137
+ this.timeoutId && clearTimeout(this.timeoutId), this.timeoutId = null, t(r);
138
+ };
139
+ this.context.once("handshake_offer_received", o);
140
+ });
141
+ }
142
+ /**
143
+ * Manages the OTP verification step by emitting the `otp_required` event and
144
+ * waiting for the user to submit the correct OTP.
145
+ *
146
+ * @param offer - The handshake offer from the wallet containing the OTP
147
+ * @throws {SessionError} If the OTP is incorrect after max attempts, the OTP expires,
148
+ * or the user cancels
149
+ */
150
+ _handleOtpInput(e) {
151
+ return new Promise((t, n) => {
152
+ if (!e.deadline || !e.otp)
153
+ return n(new s.SessionError(s.ErrorCode.UNKNOWN, "Handshake offer is missing OTP details for untrusted connection."));
154
+ if (Date.now() > e.deadline)
155
+ return n(new s.SessionError(s.ErrorCode.OTP_ENTRY_TIMEOUT, "The OTP has already expired."));
156
+ const i = e.otp;
157
+ let o = 0;
158
+ const r = async (d) => {
159
+ if (!s.timingSafeEqual(d, i)) {
160
+ if (o++, o >= this.otpAttempts)
161
+ n(new s.SessionError(s.ErrorCode.OTP_MAX_ATTEMPTS_REACHED, "Maximum OTP attempts reached."));
162
+ else
163
+ throw new s.SessionError(s.ErrorCode.OTP_INCORRECT, `Incorrect OTP. ${this.otpAttempts - o} attempts remaining.`);
164
+ return;
165
+ }
166
+ t();
167
+ }, a = () => n(new Error("User cancelled OTP entry."));
168
+ this.context.emit("otp_required", { submit: r, cancel: a, deadline: e.deadline });
169
+ });
170
+ }
171
+ /**
172
+ * Creates the final session object with details from the wallet's offer.
173
+ *
174
+ * @param session - The pending session object (with temporary values)
175
+ * @param offer - The handshake offer payload from the wallet
176
+ * @returns The complete session object ready for use
177
+ */
178
+ _createFinalSession(e, t) {
179
+ const n = E(t.publicKeyB64);
180
+ return this.context.keymanager.validatePeerKey(n), {
181
+ ...e,
182
+ channel: `session:${t.channelId}`,
183
+ theirPublicKey: n
184
+ };
185
+ }
186
+ /**
187
+ * Subscribes to the secure session channel and sends handshake acknowledgment.
188
+ *
189
+ * @param session - The finalized session object
190
+ */
191
+ async _acknowledgeHandshake(e) {
192
+ await this.context.transport.subscribe(e.channel), await this.context.sendMessage(e.channel, { type: "handshake-ack" });
193
+ }
194
+ /**
195
+ * Completes the connection by persisting the session, cleaning up the
196
+ * temporary handshake channel, and transitioning to the `CONNECTED` state.
197
+ *
198
+ * @param handshakeChannel - The temporary channel used for the initial handshake
199
+ */
200
+ async _finalizeConnection(e) {
201
+ if (!this.context.session) throw new s.SessionError(s.ErrorCode.SESSION_INVALID_STATE);
202
+ await this.context.sessionstore.set(this.context.session), await this.context.transport.clear(e), this.context.state = s.ClientState.CONNECTED, this.context.emit("connected");
203
+ }
204
+ }, O = 60 * 1e3, N = 60 * 1e3, k = class extends s.BaseClient {
205
+ // biome-ignore lint/suspicious/noExplicitAny: used for event emitter
206
+ on(e, t) {
207
+ return super.on(e, t);
208
+ }
209
+ constructor(e) {
210
+ super(e.transport, e.keymanager, e.sessionstore);
211
+ }
212
+ /**
213
+ * Initiates a new session with a wallet. The process differs based on the connection mode:
214
+ *
215
+ * **Trusted Mode** (same-device/trusted context):
216
+ * 1. Emits a `session_request` event
217
+ * 2. Waits for wallet handshake offer
218
+ * 3. Automatically finalizes secure session
219
+ *
220
+ * **Untrusted Mode** (high-security):
221
+ * 1. Emits a `session_request` event
222
+ * 2. Waits for wallet handshake offer with OTP
223
+ * 3. Emits `otp_required` event for user verification
224
+ * 4. Finalizes secure, encrypted session after OTP validation
225
+ *
226
+ * @param options - Connection options including the desired mode
227
+ * @returns A promise that resolves when the session is successfully established
228
+ * @throws {SessionError} If the client is not in a `DISCONNECTED` state or if the
229
+ * connection process fails
230
+ */
231
+ async connect(e = {}) {
232
+ if (this.state !== s.ClientState.DISCONNECTED) throw new s.SessionError(s.ErrorCode.SESSION_INVALID_STATE, `Cannot connect when state is ${this.state}`);
233
+ const { mode: t = "untrusted", initialPayload: n } = e;
234
+ if (!s.isValidConnectionMode(t)) throw new s.SessionError(s.ErrorCode.SESSION_INVALID_STATE, `Invalid connection mode: "${String(t)}"`);
235
+ this.state = s.ClientState.CONNECTING;
236
+ const { pendingSession: i, request: o } = this._createPendingSessionAndRequest(t, n);
237
+ this.session = i, this.emit("session_request", o);
238
+ const r = this, a = {
239
+ transport: this.transport,
240
+ sessionstore: this.sessionstore,
241
+ keymanager: this.keymanager,
242
+ get session() {
243
+ return r.session;
244
+ },
245
+ set session(c) {
246
+ r.session = c;
247
+ },
248
+ get state() {
249
+ return r.state;
250
+ },
251
+ set state(c) {
252
+ r.state = c;
253
+ },
254
+ emit: this.emit.bind(this),
255
+ once: this.once.bind(this),
256
+ off: this.off.bind(this),
257
+ sendMessage: this.sendMessage.bind(this)
258
+ }, d = t === "trusted" ? new y(a) : new I(a);
259
+ try {
260
+ await d.execute(i, o);
261
+ } catch (c) {
262
+ throw this.emit("error", c), await this.disconnect(), c;
263
+ }
264
+ }
265
+ /**
266
+ * Sends a request payload to the connected wallet.
267
+ *
268
+ * @param payload - The request payload to send to the wallet
269
+ * @throws {SessionError} If the client is not in a `CONNECTED` state
270
+ */
271
+ async sendRequest(e) {
272
+ if (this.state !== s.ClientState.CONNECTED || !this.session) throw new s.SessionError(s.ErrorCode.SESSION_INVALID_STATE, "Cannot send request: not connected.");
273
+ await this.sendMessage(this.session.channel, { type: "message", payload: e });
274
+ }
275
+ /**
276
+ * Routes incoming messages based on the client's connection state.
277
+ * During connection, it handles handshake messages. Once connected, it
278
+ * handles standard application messages.
279
+ *
280
+ * @param message - The incoming message to handle
281
+ */
282
+ handleMessage(e) {
283
+ this.state === s.ClientState.CONNECTING && e.type === "handshake-offer" ? this.emit("handshake_offer_received", e.payload) : this.state === s.ClientState.CONNECTED && e.type === "message" && this.emit("message", e.payload);
284
+ }
285
+ /**
286
+ * Creates a temporary session object and the corresponding `SessionRequest`
287
+ * payload to be shared with the wallet.
288
+ *
289
+ * @param mode - The connection mode to use for this session
290
+ * @returns An object containing the pending session and session request
291
+ */
292
+ _createPendingSessionAndRequest(e, t) {
293
+ const n = w(), i = this.keymanager.generateKeyPair(), o = {
294
+ id: n,
295
+ channel: "",
296
+ // To be determined by the wallet's handshake offer
297
+ keyPair: i,
298
+ theirPublicKey: new Uint8Array(0),
299
+ // Placeholder, will be updated
300
+ expiresAt: Date.now() + s.DEFAULT_SESSION_TTL
301
+ }, r = t ? { type: "message", payload: t } : void 0, a = {
302
+ id: n,
303
+ mode: e,
304
+ channel: `handshake:${n}`,
305
+ publicKeyB64: x(i.publicKey),
306
+ expiresAt: Date.now() + O,
307
+ initialMessage: r
308
+ };
309
+ return { pendingSession: o, request: a };
310
+ }
311
+ };
312
+ export {
313
+ k as DappClient
314
+ };