@block-auth.io/core 0.13.0 → 0.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.
package/dist/index.cjs CHANGED
@@ -2233,6 +2233,83 @@ function loginWithPopup(options) {
2233
2233
  return loginInFlight;
2234
2234
  }
2235
2235
 
2236
+ // src/auth/authEndpoint.ts
2237
+ var AccountLinkError = class extends Error {
2238
+ constructor(reason, status) {
2239
+ super(`authEndpoint /link failed (${status})`);
2240
+ this.reason = reason;
2241
+ this.status = status;
2242
+ this.name = "AccountLinkError";
2243
+ }
2244
+ };
2245
+ function toUser(payload) {
2246
+ const { address, did, roles } = payload ?? {};
2247
+ if (typeof address !== "string" || !address) {
2248
+ throw new Error("Invalid user from authEndpoint");
2249
+ }
2250
+ const user = {
2251
+ address,
2252
+ roles: Array.isArray(roles) ? roles : []
2253
+ };
2254
+ if (typeof did === "string" && did) user.did = did;
2255
+ return user;
2256
+ }
2257
+ function createAuthEndpoint(baseUrl) {
2258
+ const base = baseUrl.replace(/\/+$/, "");
2259
+ const request = (path, init) => fetch(`${base}${path}`, {
2260
+ ...init,
2261
+ credentials: "include",
2262
+ cache: "no-store",
2263
+ redirect: "error"
2264
+ });
2265
+ const postJson = (path, body) => request(path, {
2266
+ method: "POST",
2267
+ headers: { "Content-Type": "application/json" },
2268
+ body: JSON.stringify(body)
2269
+ });
2270
+ const fail = (path, response) => {
2271
+ throw new Error(`authEndpoint ${path} failed (${response.status})`);
2272
+ };
2273
+ return {
2274
+ redeem: async ({ code, codeVerifier, redirectUri }) => {
2275
+ const response = await postJson("/code", {
2276
+ code,
2277
+ codeVerifier,
2278
+ redirectUri
2279
+ });
2280
+ if (!response.ok) fail("/code", response);
2281
+ return toUser(await response.json());
2282
+ },
2283
+ me: async () => {
2284
+ const response = await request("/me", { method: "GET" });
2285
+ if (response.status === 401) return null;
2286
+ if (!response.ok) fail("/me", response);
2287
+ return toUser(await response.json());
2288
+ },
2289
+ logout: async () => {
2290
+ const response = await postJson("/logout", {});
2291
+ if (!response.ok) fail("/logout", response);
2292
+ },
2293
+ linkStatus: async () => {
2294
+ const response = await request("/link", { method: "GET" });
2295
+ if (response.status === 401) return null;
2296
+ if (!response.ok) fail("/link", response);
2297
+ const { linked } = await response.json();
2298
+ return linked === true;
2299
+ },
2300
+ link: async ({ code, codeVerifier, redirectUri }) => {
2301
+ const response = await postJson("/link", {
2302
+ code,
2303
+ codeVerifier,
2304
+ redirectUri
2305
+ });
2306
+ if (response.ok) return;
2307
+ const reason = response.status === 409 ? "already_linked" : response.status === 401 ? "not_signed_in" : "failed";
2308
+ throw new AccountLinkError(reason, response.status);
2309
+ }
2310
+ };
2311
+ }
2312
+
2236
2313
  // src/auth/logout.ts
2237
2314
  async function performLogout(args) {
2238
2315
  const { wsc, token, apiKey, sessionId, apiUrl } = args;
@@ -2487,9 +2564,9 @@ async function signInWithMicrosoft(overrides = {}) {
2487
2564
  setServiceIcon(imgUrlByService("microsoft"));
2488
2565
  return { accessToken: response.accessToken, response };
2489
2566
  }
2490
- function rememberHostedLogin(result) {
2567
+ function showHostedUser(result) {
2491
2568
  const did = result.did ?? result.address;
2492
- browserBase.setSession({ did, serviceName: "blockauth" });
2569
+ setDid(did);
2493
2570
  setUser({
2494
2571
  address: result.address,
2495
2572
  did,
@@ -2499,9 +2576,22 @@ function rememberHostedLogin(result) {
2499
2576
  setIsServiceConnected(true);
2500
2577
  setIsSigned(true);
2501
2578
  setIsSignedFirstCheck(true);
2579
+ return did;
2580
+ }
2581
+ function rememberHostedLogin(result) {
2582
+ const did = showHostedUser(result);
2583
+ browserBase.setSession({ did, serviceName: "blockauth" });
2584
+ }
2585
+ function forgetHostedUser() {
2586
+ resetUser();
2587
+ setDid(null);
2588
+ setIsServiceConnected(false);
2589
+ setIsSigned(false);
2590
+ setIsSignedFirstCheck(true);
2502
2591
  }
2503
2592
  function createBlockAuthClient(config3) {
2504
2593
  if (config3.locale) setLocale(config3.locale);
2594
+ const authEndpoint = config3.authEndpoint ? createAuthEndpoint(config3.authEndpoint) : null;
2505
2595
  const provider = new BlockAuthProvider(
2506
2596
  config3.apiKey,
2507
2597
  config3.apiSecret,
@@ -2595,7 +2685,36 @@ function createBlockAuthClient(config3) {
2595
2685
  authorizeWithPopup: () => authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl }),
2596
2686
  // After the backend redeemed the code: shows the user in the page's UI
2597
2687
  // (profile dropdown, roles). The backend's answer is the source of truth.
2598
- rememberHostedLogin: (user) => rememberHostedLogin(user),
2688
+ rememberHostedLogin: (user) => {
2689
+ showHostedUser(user);
2690
+ },
2691
+ forgetHostedLogin: () => forgetHostedUser(),
2692
+ hasAuthEndpoint: Boolean(authEndpoint),
2693
+ loginWithAuthEndpoint: async () => {
2694
+ if (!authEndpoint) throw new Error("authEndpoint not configured");
2695
+ const user = await authEndpoint.redeem(
2696
+ await authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl })
2697
+ );
2698
+ showHostedUser(user);
2699
+ return user;
2700
+ },
2701
+ getAccountLinkStatus: async () => {
2702
+ if (!authEndpoint) return null;
2703
+ return authEndpoint.linkStatus();
2704
+ },
2705
+ linkWithAuthEndpoint: async () => {
2706
+ if (!authEndpoint) throw new Error("authEndpoint not configured");
2707
+ await authEndpoint.link(
2708
+ await authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl })
2709
+ );
2710
+ },
2711
+ restoreHostedLogin: async () => {
2712
+ if (!authEndpoint) return null;
2713
+ const user = await authEndpoint.me();
2714
+ if (user) showHostedUser(user);
2715
+ else forgetHostedUser();
2716
+ return user;
2717
+ },
2599
2718
  // oauth
2600
2719
  oauth: {
2601
2720
  ...oauth_exports,
@@ -2672,13 +2791,16 @@ function createBlockAuthClient(config3) {
2672
2791
  // full deletion-state teardown after the user confirms the
2673
2792
  // restoration-expired modal.
2674
2793
  finalizeRestorationExpired: () => finalizeAfterRestorationExpired(),
2675
- logout: () => performLogout({
2676
- wsc: provider.wsc,
2677
- token: userToken(),
2678
- apiKey: config3.apiKey,
2679
- sessionId: browserBase.getDeviceSessionId(),
2680
- apiUrl: config3.apiUrl
2681
- }),
2794
+ logout: async () => {
2795
+ if (authEndpoint && !config3.apiUrl) await authEndpoint.logout();
2796
+ await performLogout({
2797
+ wsc: provider.wsc,
2798
+ token: userToken(),
2799
+ apiKey: config3.apiKey,
2800
+ sessionId: browserBase.getDeviceSessionId(),
2801
+ apiUrl: config3.apiUrl
2802
+ });
2803
+ },
2682
2804
  // modals (stack — supports overlaying signin on top of signup)
2683
2805
  openModal,
2684
2806
  closeModal,
@@ -3811,6 +3933,13 @@ function createAuthRuntime(client, callbacks = {}) {
3811
3933
  );
3812
3934
  });
3813
3935
  };
3936
+ const onSocketReconnect = () => {
3937
+ if (stopped || hookState.isLoggingOut || !hookState.isSigned) return;
3938
+ const externalService = browserBase.getExternalService();
3939
+ const did = externalService.service && externalService.service !== "blockauth" ? externalService.did : browserBase.getSession().did;
3940
+ if (!did) return;
3941
+ emitSdkSign(wsc().accessToken, did);
3942
+ };
3814
3943
  const onSdkUserRolesChanged = async (data) => {
3815
3944
  const { success, message } = data || {};
3816
3945
  if (!success || !message?.address) return;
@@ -3920,6 +4049,7 @@ function createAuthRuntime(client, callbacks = {}) {
3920
4049
  wsc().on("sdk:user:roles:changed", onSdkUserRolesChanged);
3921
4050
  wsc().on("sdk:restore", onSdkRestore);
3922
4051
  wsc().ws?.onAny(onAnyServerEvent);
4052
+ wsc().ws?.on("connect", onSocketReconnect);
3923
4053
  if (typeof window !== "undefined") {
3924
4054
  window.addEventListener("storage", onStorageLogout);
3925
4055
  }
@@ -3969,6 +4099,7 @@ function createAuthRuntime(client, callbacks = {}) {
3969
4099
  w.off("sdk:user:roles:changed", onSdkUserRolesChanged);
3970
4100
  w.off("sdk:restore", onSdkRestore);
3971
4101
  w.ws?.offAny(onAnyServerEvent);
4102
+ w.ws?.off("connect", onSocketReconnect);
3972
4103
  }
3973
4104
  if (typeof window !== "undefined") {
3974
4105
  window.removeEventListener("storage", onStorageLogout);
@@ -4248,6 +4379,7 @@ exports.$user = $user;
4248
4379
  exports.$wallet = $wallet;
4249
4380
  exports.$web3 = $web3;
4250
4381
  exports.$ws = $ws;
4382
+ exports.AccountLinkError = AccountLinkError;
4251
4383
  exports.BlockAuthProvider = BlockAuthProvider;
4252
4384
  exports.DEFAULT_PHONE_COUNTRY = DEFAULT_PHONE_COUNTRY;
4253
4385
  exports.DISCOVERY_TIMEOUT_MS = DISCOVERY_TIMEOUT_MS;