@block-auth.io/core 0.11.0 → 0.12.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/dist/index.cjs +357 -42
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +74 -5
- package/dist/index.d.ts +74 -5
- package/dist/index.js +355 -43
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -16,13 +16,11 @@ var __export = (target, all) => {
|
|
|
16
16
|
};
|
|
17
17
|
|
|
18
18
|
// src/utils/apiBridge.ts
|
|
19
|
-
var DEFAULT_API_URL = "https://api.block-auth.io";
|
|
20
19
|
function buildApiUrl(path, apiUrl) {
|
|
21
|
-
|
|
22
|
-
return `${base}${path}`;
|
|
20
|
+
return `${apiUrl.replace(/\/+$/, "")}${path}`;
|
|
23
21
|
}
|
|
24
22
|
async function bridgeSessionCookie(token, apiUrl) {
|
|
25
|
-
if (!token || typeof fetch === "undefined") return false;
|
|
23
|
+
if (!apiUrl || !token || typeof fetch === "undefined") return false;
|
|
26
24
|
try {
|
|
27
25
|
const response = await fetch(buildApiUrl("/auth/session", apiUrl), {
|
|
28
26
|
method: "POST",
|
|
@@ -37,7 +35,7 @@ async function bridgeSessionCookie(token, apiUrl) {
|
|
|
37
35
|
}
|
|
38
36
|
}
|
|
39
37
|
async function clearSessionCookie(apiUrl) {
|
|
40
|
-
if (typeof fetch === "undefined") return false;
|
|
38
|
+
if (!apiUrl || typeof fetch === "undefined") return false;
|
|
41
39
|
try {
|
|
42
40
|
const response = await fetch(buildApiUrl("/auth/logout", apiUrl), {
|
|
43
41
|
method: "POST",
|
|
@@ -50,7 +48,9 @@ async function clearSessionCookie(apiUrl) {
|
|
|
50
48
|
}
|
|
51
49
|
}
|
|
52
50
|
async function requestWsTicket(apiUrl) {
|
|
53
|
-
if (typeof fetch === "undefined")
|
|
51
|
+
if (!apiUrl || typeof fetch === "undefined") {
|
|
52
|
+
return { ticket: null, refused: false };
|
|
53
|
+
}
|
|
54
54
|
try {
|
|
55
55
|
const response = await fetch(buildApiUrl("/auth/ws-ticket", apiUrl), {
|
|
56
56
|
method: "GET",
|
|
@@ -81,14 +81,11 @@ function buildWsServerApiUrl(path, wsUrl) {
|
|
|
81
81
|
async function fetchBrowserToken(apiKey, wsUrl) {
|
|
82
82
|
if (!apiKey || typeof fetch === "undefined") return null;
|
|
83
83
|
try {
|
|
84
|
-
const response = await fetch(
|
|
85
|
-
|
|
86
|
-
{
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
body: JSON.stringify({ apiKey })
|
|
90
|
-
}
|
|
91
|
-
);
|
|
84
|
+
const response = await fetch(buildWsServerApiUrl("/browser-token", wsUrl), {
|
|
85
|
+
method: "POST",
|
|
86
|
+
headers: { "Content-Type": "application/json" },
|
|
87
|
+
body: JSON.stringify({ apiKey })
|
|
88
|
+
});
|
|
92
89
|
const payload = await response.json();
|
|
93
90
|
if (!response.ok || !payload?.success) return null;
|
|
94
91
|
return payload.message?.accessToken || null;
|
|
@@ -119,6 +116,7 @@ var WsClient = class {
|
|
|
119
116
|
this._roles = [];
|
|
120
117
|
this._logs = [];
|
|
121
118
|
this._kycIssuerByAddress = {};
|
|
119
|
+
this._connecting = null;
|
|
122
120
|
this._wsUrl = url || "wss://wss.block-auth.io/";
|
|
123
121
|
this._apiUrl = apiUrl;
|
|
124
122
|
this._wsConfig = {
|
|
@@ -150,6 +148,14 @@ var WsClient = class {
|
|
|
150
148
|
* @returns Promise<void>
|
|
151
149
|
*/
|
|
152
150
|
async connect(url = "", waitMs = 5e3, retries = 3) {
|
|
151
|
+
if (this.isConnected()) return;
|
|
152
|
+
if (this._connecting) return this._connecting;
|
|
153
|
+
this._connecting = this._doConnect(url, waitMs, retries).finally(() => {
|
|
154
|
+
this._connecting = null;
|
|
155
|
+
});
|
|
156
|
+
return this._connecting;
|
|
157
|
+
}
|
|
158
|
+
async _doConnect(url, waitMs, retries) {
|
|
153
159
|
const _url = url || this._wsUrl;
|
|
154
160
|
this._wsConfig.auth = (done) => {
|
|
155
161
|
fetchWsTicket(this._apiUrl).then((ticket) => done(ticket ? { ticket } : {})).catch(() => done({}));
|
|
@@ -995,6 +1001,7 @@ var initial2 = {
|
|
|
995
1001
|
isSigned: false,
|
|
996
1002
|
isSigningLoader: false,
|
|
997
1003
|
isAcceptingTxn: false,
|
|
1004
|
+
isRejectingTxn: false,
|
|
998
1005
|
acceptTxnError: null,
|
|
999
1006
|
waitingForSuccessLogInSince: 0,
|
|
1000
1007
|
isOtpRequired: false,
|
|
@@ -1014,6 +1021,7 @@ var setIsSigning = (v) => $ui.setKey("isSigning", v);
|
|
|
1014
1021
|
var setIsSigned = (v) => $ui.setKey("isSigned", v);
|
|
1015
1022
|
var setIsSigningLoader = (v) => $ui.setKey("isSigningLoader", v);
|
|
1016
1023
|
var setIsAcceptingTxn = (v) => $ui.setKey("isAcceptingTxn", v);
|
|
1024
|
+
var setIsRejectingTxn = (v) => $ui.setKey("isRejectingTxn", v);
|
|
1017
1025
|
var setAcceptTxnError = (v) => $ui.setKey("acceptTxnError", v);
|
|
1018
1026
|
var setWaitingForSuccessLogInSince = (v) => $ui.setKey("waitingForSuccessLogInSince", v);
|
|
1019
1027
|
var setIsOtpRequired = (v) => $ui.setKey("isOtpRequired", v);
|
|
@@ -1095,6 +1103,7 @@ var setExtensionIsUser = (v) => $extension.setKey("isUser", v);
|
|
|
1095
1103
|
var setExtensionIsUserActive = (v) => $extension.setKey("isUserActive", v);
|
|
1096
1104
|
var resetExtension = () => $extension.set({ ...initial5 });
|
|
1097
1105
|
var isShowSignin = (state = $extension.get()) => Boolean(state.installed && state.isUser && state.isUserActive && !state.isLocked);
|
|
1106
|
+
var needsExtensionUnlock = (serviceName, did, isLocked) => serviceName === "blockauth" && (isLocked || !did);
|
|
1098
1107
|
var initial6 = { backendMessage: null, signature: null, signedBy: null };
|
|
1099
1108
|
var $web3 = map({ ...initial6 });
|
|
1100
1109
|
var setBackendMessage = (v) => $web3.setKey("backendMessage", v);
|
|
@@ -2079,21 +2088,147 @@ function connectBlockAuth(apiUrl) {
|
|
|
2079
2088
|
requestExtensionStateSync();
|
|
2080
2089
|
}
|
|
2081
2090
|
|
|
2082
|
-
// src/auth/
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2091
|
+
// src/auth/popupSize.ts
|
|
2092
|
+
var LOGIN_POPUP_WIDTH = 380;
|
|
2093
|
+
var LOGIN_POPUP_HEIGHT = 640;
|
|
2094
|
+
|
|
2095
|
+
// src/auth/loginWithPopup.ts
|
|
2096
|
+
var AUTH_CODE_MESSAGE = "blockauth:auth-code";
|
|
2097
|
+
var POPUP_CLOSED_POLL_MS = 500;
|
|
2098
|
+
var LOGIN_TIMEOUT_MS = 15 * 60 * 1e3;
|
|
2099
|
+
function base64url(bytes) {
|
|
2100
|
+
let binary = "";
|
|
2101
|
+
for (const b of bytes) binary += String.fromCharCode(b);
|
|
2102
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
2103
|
+
}
|
|
2104
|
+
function randomString(byteLength) {
|
|
2105
|
+
return base64url(crypto.getRandomValues(new Uint8Array(byteLength)));
|
|
2106
|
+
}
|
|
2107
|
+
async function sha256Base64url(value) {
|
|
2108
|
+
const digest = await crypto.subtle.digest(
|
|
2109
|
+
"SHA-256",
|
|
2110
|
+
new TextEncoder().encode(value)
|
|
2111
|
+
);
|
|
2112
|
+
return base64url(new Uint8Array(digest));
|
|
2113
|
+
}
|
|
2114
|
+
async function postWsServer(path, body, wsUrl) {
|
|
2115
|
+
const response = await fetch(buildWsServerApiUrl(path, wsUrl), {
|
|
2116
|
+
method: "POST",
|
|
2117
|
+
headers: { "Content-Type": "application/json" },
|
|
2118
|
+
body: JSON.stringify(body)
|
|
2119
|
+
});
|
|
2120
|
+
const payload = await response.json();
|
|
2121
|
+
if (!response.ok || !payload?.success) {
|
|
2122
|
+
const reason = typeof payload?.message === "string" ? payload.message : "Login failed";
|
|
2123
|
+
throw new Error(reason);
|
|
2124
|
+
}
|
|
2125
|
+
return payload.message;
|
|
2126
|
+
}
|
|
2127
|
+
function waitForCode(popup, authOrigin, state) {
|
|
2128
|
+
return new Promise((resolve, reject) => {
|
|
2086
2129
|
let done = false;
|
|
2087
|
-
const finish = () => {
|
|
2088
|
-
if (
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2130
|
+
const finish = (error, code) => {
|
|
2131
|
+
if (done) return;
|
|
2132
|
+
done = true;
|
|
2133
|
+
window.removeEventListener("message", onMessage);
|
|
2134
|
+
clearInterval(closedPoll);
|
|
2135
|
+
clearTimeout(timeout);
|
|
2136
|
+
if (error) reject(error);
|
|
2137
|
+
else resolve(code);
|
|
2138
|
+
};
|
|
2139
|
+
const onMessage = (event) => {
|
|
2140
|
+
if (event.origin !== authOrigin || event.source !== popup) return;
|
|
2141
|
+
const data = event.data;
|
|
2142
|
+
if (data?.type !== AUTH_CODE_MESSAGE || data.state !== state) return;
|
|
2143
|
+
if (data.code) finish(null, data.code);
|
|
2092
2144
|
};
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2145
|
+
window.addEventListener("message", onMessage);
|
|
2146
|
+
const closedPoll = setInterval(() => {
|
|
2147
|
+
if (!popup.closed) return;
|
|
2148
|
+
setTimeout(
|
|
2149
|
+
() => finish(new Error("Login window closed")),
|
|
2150
|
+
POPUP_CLOSED_POLL_MS
|
|
2151
|
+
);
|
|
2152
|
+
}, POPUP_CLOSED_POLL_MS);
|
|
2153
|
+
const timeout = setTimeout(
|
|
2154
|
+
() => finish(new Error("Login timed out")),
|
|
2155
|
+
LOGIN_TIMEOUT_MS
|
|
2156
|
+
);
|
|
2096
2157
|
});
|
|
2158
|
+
}
|
|
2159
|
+
function popupFeatures() {
|
|
2160
|
+
const left = Math.max(
|
|
2161
|
+
0,
|
|
2162
|
+
Math.round(window.screenX + (window.outerWidth - LOGIN_POPUP_WIDTH) / 2)
|
|
2163
|
+
);
|
|
2164
|
+
const top = Math.max(
|
|
2165
|
+
0,
|
|
2166
|
+
Math.round(window.screenY + (window.outerHeight - LOGIN_POPUP_HEIGHT) / 2)
|
|
2167
|
+
);
|
|
2168
|
+
return `popup,width=${LOGIN_POPUP_WIDTH},height=${LOGIN_POPUP_HEIGHT},left=${left},top=${top}`;
|
|
2169
|
+
}
|
|
2170
|
+
async function runAuthorize(options) {
|
|
2171
|
+
const popup = window.open("about:blank", "blockauth-login", popupFeatures());
|
|
2172
|
+
if (!popup) throw new Error("Login popup blocked");
|
|
2173
|
+
const redirectUri = `${window.location.origin}/`;
|
|
2174
|
+
try {
|
|
2175
|
+
const codeVerifier = randomString(32);
|
|
2176
|
+
const state = randomString(16);
|
|
2177
|
+
const codeChallenge = await sha256Base64url(codeVerifier);
|
|
2178
|
+
const { url } = await postWsServer(
|
|
2179
|
+
"/auth/authorize",
|
|
2180
|
+
{ apiKey: options.apiKey, redirectUri, state, codeChallenge },
|
|
2181
|
+
options.wsUrl
|
|
2182
|
+
);
|
|
2183
|
+
popup.location.href = url;
|
|
2184
|
+
const code = await waitForCode(popup, new URL(url).origin, state);
|
|
2185
|
+
return { code, codeVerifier, redirectUri };
|
|
2186
|
+
} catch (error) {
|
|
2187
|
+
popup.close();
|
|
2188
|
+
throw error;
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
var inFlight = null;
|
|
2192
|
+
var loginInFlight = null;
|
|
2193
|
+
function authorizeWithPopup(options) {
|
|
2194
|
+
inFlight ?? (inFlight = runAuthorize(options).finally(() => {
|
|
2195
|
+
inFlight = null;
|
|
2196
|
+
}));
|
|
2197
|
+
return inFlight;
|
|
2198
|
+
}
|
|
2199
|
+
function loginWithPopup(options) {
|
|
2200
|
+
loginInFlight ?? (loginInFlight = authorizeWithPopup(options).then(
|
|
2201
|
+
({ code, codeVerifier, redirectUri }) => postWsServer(
|
|
2202
|
+
"/auth/token",
|
|
2203
|
+
{ apiKey: options.apiKey, code, redirectUri, codeVerifier },
|
|
2204
|
+
options.wsUrl
|
|
2205
|
+
)
|
|
2206
|
+
).finally(() => {
|
|
2207
|
+
loginInFlight = null;
|
|
2208
|
+
}));
|
|
2209
|
+
return loginInFlight;
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
// src/auth/logout.ts
|
|
2213
|
+
async function performLogout(args) {
|
|
2214
|
+
const { wsc, token, apiKey, sessionId, apiUrl } = args;
|
|
2215
|
+
if (apiUrl) {
|
|
2216
|
+
await new Promise((resolve) => {
|
|
2217
|
+
let done = false;
|
|
2218
|
+
const finish = () => {
|
|
2219
|
+
if (!done) {
|
|
2220
|
+
done = true;
|
|
2221
|
+
resolve();
|
|
2222
|
+
}
|
|
2223
|
+
};
|
|
2224
|
+
wsc.ws?.once?.("signout", finish);
|
|
2225
|
+
wsc.emit("signout", { token, apiKey, sessionId });
|
|
2226
|
+
setTimeout(finish, 1500);
|
|
2227
|
+
});
|
|
2228
|
+
} else {
|
|
2229
|
+
resetUser();
|
|
2230
|
+
browserBase.reset("session");
|
|
2231
|
+
}
|
|
2097
2232
|
if (typeof localStorage !== "undefined") {
|
|
2098
2233
|
localStorage.setItem("blockauth-logged-out", "true");
|
|
2099
2234
|
}
|
|
@@ -2328,6 +2463,19 @@ async function signInWithMicrosoft(overrides = {}) {
|
|
|
2328
2463
|
setServiceIcon(imgUrlByService("microsoft"));
|
|
2329
2464
|
return { accessToken: response.accessToken, response };
|
|
2330
2465
|
}
|
|
2466
|
+
function rememberHostedLogin(result) {
|
|
2467
|
+
const did = result.did ?? result.address;
|
|
2468
|
+
browserBase.setSession({ did, serviceName: "blockauth" });
|
|
2469
|
+
setUser({
|
|
2470
|
+
address: result.address,
|
|
2471
|
+
did,
|
|
2472
|
+
roles: result.roles ?? []
|
|
2473
|
+
});
|
|
2474
|
+
setServiceName("blockauth");
|
|
2475
|
+
setIsServiceConnected(true);
|
|
2476
|
+
setIsSigned(true);
|
|
2477
|
+
setIsSignedFirstCheck(true);
|
|
2478
|
+
}
|
|
2331
2479
|
function createBlockAuthClient(config3) {
|
|
2332
2480
|
if (config3.locale) setLocale(config3.locale);
|
|
2333
2481
|
const provider = new BlockAuthProvider(
|
|
@@ -2372,13 +2520,15 @@ function createBlockAuthClient(config3) {
|
|
|
2372
2520
|
const ext = browserBase.getExternalService();
|
|
2373
2521
|
return ext.service !== "blockauth" ? ext.token ?? "" : s.token ?? "";
|
|
2374
2522
|
}
|
|
2523
|
+
let runtimeBridge = null;
|
|
2375
2524
|
return {
|
|
2376
2525
|
state: {
|
|
2377
2526
|
$ws,
|
|
2378
2527
|
$ui,
|
|
2379
2528
|
$wallet,
|
|
2380
2529
|
$openModals,
|
|
2381
|
-
$user
|
|
2530
|
+
$user,
|
|
2531
|
+
$extension
|
|
2382
2532
|
},
|
|
2383
2533
|
/** App apiKey from client config (also seeded into $ws). */
|
|
2384
2534
|
apiKey: config3.apiKey,
|
|
@@ -2405,6 +2555,23 @@ function createBlockAuthClient(config3) {
|
|
|
2405
2555
|
// BlockAuth extension connect (sets blockauth as the active service);
|
|
2406
2556
|
// the txn-signing flow is driven by the caller via requestSignin.
|
|
2407
2557
|
connectBlockAuth: () => connectBlockAuth(config3.apiUrl),
|
|
2558
|
+
// Login for an app without a backend: hosted login in a popup, PKCE
|
|
2559
|
+
// instead of the apiSecret (see auth/loginWithPopup.ts). Call it from a
|
|
2560
|
+
// click handler.
|
|
2561
|
+
loginWithPopup: async () => {
|
|
2562
|
+
const result = await loginWithPopup({
|
|
2563
|
+
apiKey: config3.apiKey,
|
|
2564
|
+
wsUrl: config3.wsUrl
|
|
2565
|
+
});
|
|
2566
|
+
rememberHostedLogin(result);
|
|
2567
|
+
return result;
|
|
2568
|
+
},
|
|
2569
|
+
// Same popup, but the code goes to the app's backend, which redeems it
|
|
2570
|
+
// with its apiSecret (see PopupAuthCode). Call it from a click handler.
|
|
2571
|
+
authorizeWithPopup: () => authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl }),
|
|
2572
|
+
// After the backend redeemed the code: shows the user in the page's UI
|
|
2573
|
+
// (profile dropdown, roles). The backend's answer is the source of truth.
|
|
2574
|
+
rememberHostedLogin: (user) => rememberHostedLogin(user),
|
|
2408
2575
|
// oauth
|
|
2409
2576
|
oauth: {
|
|
2410
2577
|
...oauth_exports,
|
|
@@ -2445,10 +2612,13 @@ function createBlockAuthClient(config3) {
|
|
|
2445
2612
|
}),
|
|
2446
2613
|
// transaction accept/reject
|
|
2447
2614
|
txns: {
|
|
2448
|
-
reject: () =>
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2615
|
+
reject: () => {
|
|
2616
|
+
setIsRejectingTxn(true);
|
|
2617
|
+
rejectTxn({
|
|
2618
|
+
wsc: provider.wsc,
|
|
2619
|
+
token: userToken()
|
|
2620
|
+
});
|
|
2621
|
+
},
|
|
2452
2622
|
accept: (opts) => acceptTxn({
|
|
2453
2623
|
wsc: provider.wsc,
|
|
2454
2624
|
token: userToken(),
|
|
@@ -2488,6 +2658,10 @@ function createBlockAuthClient(config3) {
|
|
|
2488
2658
|
openModal,
|
|
2489
2659
|
closeModal,
|
|
2490
2660
|
closeAllModals,
|
|
2661
|
+
registerRuntime: (bridge) => {
|
|
2662
|
+
runtimeBridge = bridge;
|
|
2663
|
+
},
|
|
2664
|
+
switchAccount: () => runtimeBridge?.switchAccount() ?? Promise.resolve(),
|
|
2491
2665
|
// opciones del connect inicial del WS (las consume createAuthRuntime)
|
|
2492
2666
|
wsConnectTimeout: config3.wsConnectTimeout ?? 300,
|
|
2493
2667
|
wsConnectRetries: config3.wsConnectRetries ?? 3,
|
|
@@ -2862,6 +3036,87 @@ var undoSolicitedValue = (form, item) => ({
|
|
|
2862
3036
|
shared: (item.value ?? "").trim() ? form.shared : omitKey(form.shared, item.slug)
|
|
2863
3037
|
});
|
|
2864
3038
|
|
|
3039
|
+
// src/auth/redirectPopup.ts
|
|
3040
|
+
var AUTH_CODE_MESSAGE2 = "blockauth:auth-code";
|
|
3041
|
+
function centeredPopupFeatures(width, height) {
|
|
3042
|
+
const base = `popup,width=${width},height=${height}`;
|
|
3043
|
+
if (typeof window === "undefined") return base;
|
|
3044
|
+
const screenLeft = window.screenLeft ?? window.screenX ?? 0;
|
|
3045
|
+
const screenTop = window.screenTop ?? window.screenY ?? 0;
|
|
3046
|
+
const viewportWidth = window.innerWidth || document.documentElement?.clientWidth || window.screen?.width || width;
|
|
3047
|
+
const viewportHeight = window.innerHeight || document.documentElement?.clientHeight || window.screen?.height || height;
|
|
3048
|
+
const left = Math.max(
|
|
3049
|
+
0,
|
|
3050
|
+
Math.round(screenLeft + (viewportWidth - width) / 2)
|
|
3051
|
+
);
|
|
3052
|
+
const top = Math.max(
|
|
3053
|
+
0,
|
|
3054
|
+
Math.round(screenTop + (viewportHeight - height) / 2)
|
|
3055
|
+
);
|
|
3056
|
+
return `${base},left=${left},top=${top}`;
|
|
3057
|
+
}
|
|
3058
|
+
function openLoginPopup({
|
|
3059
|
+
url,
|
|
3060
|
+
expectedOrigin,
|
|
3061
|
+
timeoutMs = 3e5,
|
|
3062
|
+
windowName = "blockauth-login",
|
|
3063
|
+
windowFeatures,
|
|
3064
|
+
width = LOGIN_POPUP_WIDTH,
|
|
3065
|
+
height = LOGIN_POPUP_HEIGHT
|
|
3066
|
+
}) {
|
|
3067
|
+
return new Promise((resolve, reject) => {
|
|
3068
|
+
if (typeof window === "undefined" || typeof window.open !== "function") {
|
|
3069
|
+
reject(new Error("Popup login is only available in a browser"));
|
|
3070
|
+
return;
|
|
3071
|
+
}
|
|
3072
|
+
const features = windowFeatures ?? centeredPopupFeatures(width, height);
|
|
3073
|
+
const popup = window.open(url, windowName, features);
|
|
3074
|
+
if (!popup) {
|
|
3075
|
+
reject(new Error("Popup blocked"));
|
|
3076
|
+
return;
|
|
3077
|
+
}
|
|
3078
|
+
let settled = false;
|
|
3079
|
+
let closedTimer = null;
|
|
3080
|
+
let timeoutTimer = null;
|
|
3081
|
+
const cleanup = () => {
|
|
3082
|
+
window.removeEventListener("message", onMessage);
|
|
3083
|
+
if (closedTimer !== null) clearInterval(closedTimer);
|
|
3084
|
+
if (timeoutTimer !== null) clearTimeout(timeoutTimer);
|
|
3085
|
+
};
|
|
3086
|
+
const finish = (action) => {
|
|
3087
|
+
if (settled) return;
|
|
3088
|
+
settled = true;
|
|
3089
|
+
cleanup();
|
|
3090
|
+
action();
|
|
3091
|
+
};
|
|
3092
|
+
const onMessage = (event) => {
|
|
3093
|
+
if (event.origin !== expectedOrigin) return;
|
|
3094
|
+
if (event.source !== popup) return;
|
|
3095
|
+
const data = event.data;
|
|
3096
|
+
if (!data || data.type !== AUTH_CODE_MESSAGE2) return;
|
|
3097
|
+
if (typeof data.code !== "string" || typeof data.state !== "string") {
|
|
3098
|
+
finish(() => reject(new Error("Malformed auth code message")));
|
|
3099
|
+
return;
|
|
3100
|
+
}
|
|
3101
|
+
finish(
|
|
3102
|
+
() => resolve({ code: data.code, state: data.state })
|
|
3103
|
+
);
|
|
3104
|
+
};
|
|
3105
|
+
window.addEventListener("message", onMessage);
|
|
3106
|
+
closedTimer = setInterval(() => {
|
|
3107
|
+
if (popup.closed) {
|
|
3108
|
+
finish(() => reject(new Error("Login popup closed")));
|
|
3109
|
+
}
|
|
3110
|
+
}, 500);
|
|
3111
|
+
timeoutTimer = setTimeout(() => {
|
|
3112
|
+
finish(() => {
|
|
3113
|
+
if (!popup.closed) popup.close();
|
|
3114
|
+
reject(new Error("Login popup timed out"));
|
|
3115
|
+
});
|
|
3116
|
+
}, timeoutMs);
|
|
3117
|
+
});
|
|
3118
|
+
}
|
|
3119
|
+
|
|
2865
3120
|
// src/session/sessionExpired.ts
|
|
2866
3121
|
var USER_SESSION_REQUIRED = "USER_SESSION_REQUIRED";
|
|
2867
3122
|
var SESSION_EXPIRED_MARK = "blockauth-session-expired";
|
|
@@ -2908,8 +3163,8 @@ function createAuthRuntime(client, callbacks = {}) {
|
|
|
2908
3163
|
let unsignTimeout = null;
|
|
2909
3164
|
let signinTimeout = null;
|
|
2910
3165
|
const wsc = () => provider.wsc;
|
|
2911
|
-
const emitSdkSign = (token, address) => {
|
|
2912
|
-
wsc().emit("sdk:sign", { token, address });
|
|
3166
|
+
const emitSdkSign = (token, address, afterSign = false) => {
|
|
3167
|
+
wsc().emit("sdk:sign", { token, address, afterSign });
|
|
2913
3168
|
};
|
|
2914
3169
|
const ownTxnItems = (items) => {
|
|
2915
3170
|
const apiKey = client.apiKey;
|
|
@@ -2944,6 +3199,8 @@ function createAuthRuntime(client, callbacks = {}) {
|
|
|
2944
3199
|
});
|
|
2945
3200
|
const onLogout = callbacks.onLogout ?? (async () => {
|
|
2946
3201
|
});
|
|
3202
|
+
const onCancel = callbacks.onCancel ?? (async () => {
|
|
3203
|
+
});
|
|
2947
3204
|
const _onSuccess = async (address) => {
|
|
2948
3205
|
deletion.resetHandlingState();
|
|
2949
3206
|
await onSuccess(address);
|
|
@@ -3281,7 +3538,10 @@ function createAuthRuntime(client, callbacks = {}) {
|
|
|
3281
3538
|
hookState.pendingSignin = null;
|
|
3282
3539
|
hookState.pendingTxnId = null;
|
|
3283
3540
|
hookState.settledAttemptId = hookState.signinAttemptId;
|
|
3284
|
-
if (!hookState.isSigned)
|
|
3541
|
+
if (!hookState.isSigned) {
|
|
3542
|
+
closeAllModals();
|
|
3543
|
+
void onCancel();
|
|
3544
|
+
}
|
|
3285
3545
|
return;
|
|
3286
3546
|
}
|
|
3287
3547
|
if (hookState.settledAttemptId === hookState.signinAttemptId) {
|
|
@@ -3292,18 +3552,24 @@ function createAuthRuntime(client, callbacks = {}) {
|
|
|
3292
3552
|
hookState.pendingSignin = null;
|
|
3293
3553
|
const willVerifySign = outcome === "resolved" && !hookState.isSigned && !!pendingSignin;
|
|
3294
3554
|
if (willVerifySign) {
|
|
3295
|
-
emitSdkSign(pendingSignin.accessToken, pendingSignin.did);
|
|
3555
|
+
emitSdkSign(pendingSignin.accessToken, pendingSignin.did, true);
|
|
3296
3556
|
} else if (!hookState.isSigned) {
|
|
3297
3557
|
closeAllModals();
|
|
3298
3558
|
}
|
|
3299
3559
|
};
|
|
3560
|
+
const consumePendingReject = () => {
|
|
3561
|
+
if (!$ui.get().isRejectingTxn) return false;
|
|
3562
|
+
setIsRejectingTxn(false);
|
|
3563
|
+
settleSigningAttempt("cancelled");
|
|
3564
|
+
return true;
|
|
3565
|
+
};
|
|
3300
3566
|
const onUserTxns = async (data) => {
|
|
3301
3567
|
const { success, message } = data;
|
|
3302
3568
|
if (!success) return;
|
|
3303
3569
|
const items = ownTxnItems(message.items ?? []);
|
|
3304
3570
|
captureOwnTxnId(items);
|
|
3305
3571
|
const hasInitialTxns = items.some((item) => item.state === "initial");
|
|
3306
|
-
if (!hasInitialTxns) {
|
|
3572
|
+
if (!hasInitialTxns && !consumePendingReject()) {
|
|
3307
3573
|
settleSigningAttempt("resolved");
|
|
3308
3574
|
}
|
|
3309
3575
|
setRequests(items);
|
|
@@ -3314,7 +3580,7 @@ function createAuthRuntime(client, callbacks = {}) {
|
|
|
3314
3580
|
const items = ownTxnItems(message.items ?? []);
|
|
3315
3581
|
captureOwnTxnId(items);
|
|
3316
3582
|
const hasInitialTxns = items.some((item) => item.state === "initial");
|
|
3317
|
-
if (!hasInitialTxns) {
|
|
3583
|
+
if (!hasInitialTxns && !consumePendingReject()) {
|
|
3318
3584
|
const txnId = hookState.pendingTxnId;
|
|
3319
3585
|
const wasCancelled = txnId != null && !items.some((item) => item.id === txnId);
|
|
3320
3586
|
settleSigningAttempt(
|
|
@@ -3326,6 +3592,7 @@ function createAuthRuntime(client, callbacks = {}) {
|
|
|
3326
3592
|
const onUserTxnsCreate = async (data) => {
|
|
3327
3593
|
const { success, message } = data;
|
|
3328
3594
|
if (success) {
|
|
3595
|
+
setIsRejectingTxn(false);
|
|
3329
3596
|
setIsSigning(true);
|
|
3330
3597
|
hookState.isSigning = true;
|
|
3331
3598
|
const attemptId = ++hookState.signinAttemptId;
|
|
@@ -3374,6 +3641,7 @@ function createAuthRuntime(client, callbacks = {}) {
|
|
|
3374
3641
|
setToken(_token);
|
|
3375
3642
|
setIsSigned(success);
|
|
3376
3643
|
hookState.isSigned = success;
|
|
3644
|
+
if (success) setIsAcceptingTxn(false);
|
|
3377
3645
|
if (success) clearSessionExpiredMark();
|
|
3378
3646
|
if (success && hookState.isUnsignTimeoutSet && message?.signedExpiredAt) {
|
|
3379
3647
|
rearmUnsignTimeout(message.signedExpiredAt, _did);
|
|
@@ -3542,10 +3810,10 @@ function createAuthRuntime(client, callbacks = {}) {
|
|
|
3542
3810
|
_token = externalService.token;
|
|
3543
3811
|
_did = externalService.did;
|
|
3544
3812
|
}
|
|
3545
|
-
setDid(_did);
|
|
3546
|
-
setToken(_token);
|
|
3547
|
-
setApiKey(client.apiKey ?? $ws.get().apiKey);
|
|
3548
3813
|
const isLoggedOut = typeof localStorage !== "undefined" && localStorage.getItem("blockauth-logged-out") === "true";
|
|
3814
|
+
setDid(isLoggedOut ? null : _did);
|
|
3815
|
+
setToken(isLoggedOut ? "" : _token);
|
|
3816
|
+
setApiKey(client.apiKey ?? $ws.get().apiKey);
|
|
3549
3817
|
setIsServiceConnected(isLoggedOut ? false : externalService.connected);
|
|
3550
3818
|
setServiceName(externalService.service);
|
|
3551
3819
|
setServiceIcon(imgUrlByService(externalService.service));
|
|
@@ -3659,7 +3927,46 @@ function createAuthRuntime(client, callbacks = {}) {
|
|
|
3659
3927
|
const logout = async () => {
|
|
3660
3928
|
await _onLogout();
|
|
3661
3929
|
};
|
|
3662
|
-
|
|
3930
|
+
const switchAccount = async () => {
|
|
3931
|
+
if (hookState.isLoggingOut) return;
|
|
3932
|
+
if (unsignTimeout) {
|
|
3933
|
+
clearTimeout(unsignTimeout);
|
|
3934
|
+
unsignTimeout = null;
|
|
3935
|
+
}
|
|
3936
|
+
if (signinTimeout) {
|
|
3937
|
+
clearTimeout(signinTimeout);
|
|
3938
|
+
signinTimeout = null;
|
|
3939
|
+
}
|
|
3940
|
+
if (getUserTxnsInterval) {
|
|
3941
|
+
clearInterval(getUserTxnsInterval);
|
|
3942
|
+
getUserTxnsInterval = null;
|
|
3943
|
+
}
|
|
3944
|
+
hookState.isUnsignTimeoutSet = false;
|
|
3945
|
+
hookState.isSigning = false;
|
|
3946
|
+
hookState.pendingSignin = null;
|
|
3947
|
+
hookState.pendingTxnId = null;
|
|
3948
|
+
hookState.settledAttemptId = hookState.signinAttemptId;
|
|
3949
|
+
setIsSigning(false);
|
|
3950
|
+
setIsSigningLoader(false);
|
|
3951
|
+
setIsAcceptingTxn(false);
|
|
3952
|
+
setIsOtpRequired(false);
|
|
3953
|
+
setWaitingForSuccessLogInSince(0);
|
|
3954
|
+
closeAllModals();
|
|
3955
|
+
openModal("signup");
|
|
3956
|
+
const s = browserBase.getSession();
|
|
3957
|
+
const ext = browserBase.getExternalService();
|
|
3958
|
+
const token = ext.service !== "blockauth" ? ext.token : s.token;
|
|
3959
|
+
const apiKey = $ws.get().apiKey ?? client.apiKey;
|
|
3960
|
+
const sessionId = browserBase.getDeviceSessionId();
|
|
3961
|
+
await performLogout({
|
|
3962
|
+
wsc: wsc(),
|
|
3963
|
+
token: token ?? "",
|
|
3964
|
+
apiKey,
|
|
3965
|
+
sessionId,
|
|
3966
|
+
apiUrl: client.apiUrl
|
|
3967
|
+
});
|
|
3968
|
+
};
|
|
3969
|
+
return { start, stop, logout, switchAccount };
|
|
3663
3970
|
}
|
|
3664
3971
|
function deepLinkFor(service, domain) {
|
|
3665
3972
|
switch (service) {
|
|
@@ -3734,6 +4041,7 @@ var TEXTS = {
|
|
|
3734
4041
|
solicitedData: { es: "Datos solicitados", en: "Solicited data" },
|
|
3735
4042
|
reject: { es: "RECHAZAR", en: "REJECT" },
|
|
3736
4043
|
accept: { es: "ACEPTAR", en: "ACCEPT" },
|
|
4044
|
+
useAnotherAccount: { es: "Usar otra cuenta", en: "Use another account" },
|
|
3737
4045
|
iAuthorizeThe: { es: "Autorizo la", en: "I authorize the" },
|
|
3738
4046
|
privacyPolicy: { es: "Pol\xEDtica de Privacidad", en: "Privacy Policy" },
|
|
3739
4047
|
andThe: { es: "y los", en: "and the" },
|
|
@@ -3777,6 +4085,7 @@ var TEXTS = {
|
|
|
3777
4085
|
},
|
|
3778
4086
|
clearField: { es: "Limpiar campo", en: "Clear field" },
|
|
3779
4087
|
acceptData: { es: "Aceptar", en: "Accept" },
|
|
4088
|
+
cancelData: { es: "Cancelar", en: "Cancel" },
|
|
3780
4089
|
noTransactionsFound: {
|
|
3781
4090
|
es: "No se encontraron transacciones",
|
|
3782
4091
|
en: "No transactions found"
|
|
@@ -3837,7 +4146,10 @@ var TEXTS = {
|
|
|
3837
4146
|
en: "Enter a valid phone number"
|
|
3838
4147
|
},
|
|
3839
4148
|
phoneCountry: { es: "Pa\xEDs", en: "Country" },
|
|
3840
|
-
searchPhoneCountry: {
|
|
4149
|
+
searchPhoneCountry: {
|
|
4150
|
+
es: "Buscar pa\xEDs o prefijo",
|
|
4151
|
+
en: "Search country or code"
|
|
4152
|
+
},
|
|
3841
4153
|
noPhoneCountryResults: {
|
|
3842
4154
|
es: "No hay pa\xEDses que coincidan",
|
|
3843
4155
|
en: "No matching countries"
|
|
@@ -3862,6 +4174,6 @@ function t(key, locale = "en") {
|
|
|
3862
4174
|
return entry?.[locale] ?? entry?.en ?? key;
|
|
3863
4175
|
}
|
|
3864
4176
|
|
|
3865
|
-
export { $extension, $locale, $openModals, $ui, $user, $wallet, $web3, $ws, BlockAuthProvider, DEFAULT_PHONE_COUNTRY, DISCOVERY_TIMEOUT_MS, EMPTY_SOLICITED_DATA_FORM, PARAM_DISPLAY_FORMATTERS, PARAM_DISPLAY_ORDER, PARAM_ERROR_KEYS, PARAM_INPUT_TYPE, PARAM_LABEL_KEYS, PARAM_NORMALIZERS, PARAM_VALIDATORS, RpcClient, SDK_PAGE_MARKER, SYNC_TIMEOUT_MS, TEXTS, WsClient, appearsExtensionInstalled, buildPhoneE164, buildPhoneValue, clearExtensionDomMarkers, clearRemainingAuthData, clearSdkPresence, closeAllModals, closeModal, confirmExtensionPresence, createAuthRuntime, createBlockAuthClient, createDeletionService, createEvmWallet, createSolanaWallet, deepLinkFor, discoverExtensionOnce, fetchUserProfile, finalizeAfterRestorationExpired, formatParamValue, formatPhoneForDisplay, getDefaultPhoneCountry, getExtensionStoreUrl, getPhoneCountries, getPhoneCountryFlag, getPhoneDialCode, getSolicitedAcceptParams, getSolicitedFields, getSolicitedHintKey, getSolicitedParams, getUserRoleNames, getUserRoleSlugs, getUserRoles, handleRestorationExpired, handleRestoreFailure, hasAnyRole, hasAnyRoleBySlug, hasRole, hasRoleBySlug, isExtensionPresent, isExtensionStateComplete, isFirefox, isModalOpen, isPhoneCountry, isRestorationExpiredMessage, isSdkPage, isShowSignin, isSolicitedDataComplete, isSolicitedHintSuccess, isValidParamValue, isValidPhoneValue, loadUserProfile, makeQrDataUrl, markSdkPresence, normalizeParamValue, oauth_exports as oauth, onExtensionRemoved, onExtensionStatePublished, openExtensionOnTxn, openModal, parsePhoneValue, probeExtensionPresence, reconcileExtensionState, requestExtensionRefresh, requestExtensionStateSync, requestSdkRestore, resetExtension, resetExtensionAbsentState, resetExtensionSyncModuleState, resetUi, resetUser, resetWallet, resetWeb3, resetWs, resolvePhoneDraft, saveSolicitedValue, searchPhoneCountries, setAcceptTxnError, setApiKey, setBackendMessage, setDeletionAddress, setDid, setExtensionInstalled, setExtensionIsLocked, setExtensionIsUser, setExtensionIsUserActive, setIsAcceptingTxn, setIsAppActive, setIsCheckingAppActive, setIsLoadingUser, setIsOnDeletion, setIsOtpRequired, setIsSdkSignedIn, setIsServiceConnected, setIsSigned, setIsSignedFirstCheck, setIsSigning, setIsSigningLoader, setLocale, setReady, setRequests, setServiceIcon, setServiceName, setSignature, setSignedBy, setSolicitedShared, setSolicitedValue, setToken, setUiConfig, setUser, setWaitingForSuccessLogInSince, startExtensionSync, syncExtensionStateFromStorage, t, toPhoneE164, undoSolicitedValue, updatePhoneDraft, utils_exports as utils };
|
|
4177
|
+
export { $extension, $locale, $openModals, $ui, $user, $wallet, $web3, $ws, BlockAuthProvider, DEFAULT_PHONE_COUNTRY, DISCOVERY_TIMEOUT_MS, EMPTY_SOLICITED_DATA_FORM, PARAM_DISPLAY_FORMATTERS, PARAM_DISPLAY_ORDER, PARAM_ERROR_KEYS, PARAM_INPUT_TYPE, PARAM_LABEL_KEYS, PARAM_NORMALIZERS, PARAM_VALIDATORS, RpcClient, SDK_PAGE_MARKER, SYNC_TIMEOUT_MS, TEXTS, WsClient, appearsExtensionInstalled, buildPhoneE164, buildPhoneValue, clearExtensionDomMarkers, clearRemainingAuthData, clearSdkPresence, closeAllModals, closeModal, confirmExtensionPresence, createAuthRuntime, createBlockAuthClient, createDeletionService, createEvmWallet, createSolanaWallet, deepLinkFor, discoverExtensionOnce, fetchUserProfile, finalizeAfterRestorationExpired, formatParamValue, formatPhoneForDisplay, getDefaultPhoneCountry, getExtensionStoreUrl, getPhoneCountries, getPhoneCountryFlag, getPhoneDialCode, getSolicitedAcceptParams, getSolicitedFields, getSolicitedHintKey, getSolicitedParams, getUserRoleNames, getUserRoleSlugs, getUserRoles, handleRestorationExpired, handleRestoreFailure, hasAnyRole, hasAnyRoleBySlug, hasRole, hasRoleBySlug, isExtensionPresent, isExtensionStateComplete, isFirefox, isModalOpen, isPhoneCountry, isRestorationExpiredMessage, isSdkPage, isShowSignin, isSolicitedDataComplete, isSolicitedHintSuccess, isValidParamValue, isValidPhoneValue, loadUserProfile, makeQrDataUrl, markSdkPresence, needsExtensionUnlock, normalizeParamValue, oauth_exports as oauth, onExtensionRemoved, onExtensionStatePublished, openExtensionOnTxn, openLoginPopup, openModal, parsePhoneValue, probeExtensionPresence, reconcileExtensionState, requestExtensionRefresh, requestExtensionStateSync, requestSdkRestore, resetExtension, resetExtensionAbsentState, resetExtensionSyncModuleState, resetUi, resetUser, resetWallet, resetWeb3, resetWs, resolvePhoneDraft, saveSolicitedValue, searchPhoneCountries, setAcceptTxnError, setApiKey, setBackendMessage, setDeletionAddress, setDid, setExtensionInstalled, setExtensionIsLocked, setExtensionIsUser, setExtensionIsUserActive, setIsAcceptingTxn, setIsAppActive, setIsCheckingAppActive, setIsLoadingUser, setIsOnDeletion, setIsOtpRequired, setIsRejectingTxn, setIsSdkSignedIn, setIsServiceConnected, setIsSigned, setIsSignedFirstCheck, setIsSigning, setIsSigningLoader, setLocale, setReady, setRequests, setServiceIcon, setServiceName, setSignature, setSignedBy, setSolicitedShared, setSolicitedValue, setToken, setUiConfig, setUser, setWaitingForSuccessLogInSince, startExtensionSync, syncExtensionStateFromStorage, t, toPhoneE164, undoSolicitedValue, updatePhoneDraft, utils_exports as utils };
|
|
3866
4178
|
//# sourceMappingURL=index.js.map
|
|
3867
4179
|
//# sourceMappingURL=index.js.map
|