@block-auth.io/core 0.13.1 → 0.15.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,189 @@ function loginWithPopup(options) {
2233
2233
  return loginInFlight;
2234
2234
  }
2235
2235
 
2236
+ // src/auth/authEndpoint.ts
2237
+ var DEFAULT_AUTH_ENDPOINT = "/auth/blockauth";
2238
+ var BACKEND_ROUTES_GUIDE = "https://docs.block-auth.io/sdk-integration-spa-backend/#backend-routes";
2239
+ var AccountLinkError = class extends Error {
2240
+ constructor(reason, status) {
2241
+ super(`authEndpoint /link failed (${status})`);
2242
+ this.reason = reason;
2243
+ this.status = status;
2244
+ this.name = "AccountLinkError";
2245
+ }
2246
+ };
2247
+ function toUser(payload) {
2248
+ const { address, did, roles } = payload ?? {};
2249
+ if (typeof address !== "string" || !address) {
2250
+ throw new Error("Invalid user from authEndpoint");
2251
+ }
2252
+ const user = {
2253
+ address,
2254
+ roles: Array.isArray(roles) ? roles : []
2255
+ };
2256
+ if (typeof did === "string" && did) user.did = did;
2257
+ return user;
2258
+ }
2259
+ function createAuthEndpoint(baseUrl) {
2260
+ const base = baseUrl.replace(/\/+$/, "");
2261
+ const hinted = /* @__PURE__ */ new Set();
2262
+ const hint = (key, message) => {
2263
+ if (hinted.has(key)) return;
2264
+ hinted.add(key);
2265
+ console.error(
2266
+ `[Block-Auth] ${message} authEndpoint is "${base}". Guide: ${BACKEND_ROUTES_GUIDE}`
2267
+ );
2268
+ };
2269
+ const request = async (path, init) => {
2270
+ try {
2271
+ return await fetch(`${base}${path}`, {
2272
+ ...init,
2273
+ credentials: "include",
2274
+ cache: "no-store",
2275
+ redirect: "error"
2276
+ });
2277
+ } catch (error) {
2278
+ if (error instanceof TypeError) {
2279
+ hint(
2280
+ `network ${path}`,
2281
+ `${init.method} ${base}${path} did not reach your backend. If it runs on another origin, allow this origin in its CORS with credentials, or serve it under this origin. It must answer without redirects.`
2282
+ );
2283
+ }
2284
+ throw error;
2285
+ }
2286
+ };
2287
+ const readJson = async (path, response) => {
2288
+ try {
2289
+ return await response.json();
2290
+ } catch (error) {
2291
+ hint(
2292
+ `json ${path}`,
2293
+ `${base}${path} answered ${response.status} without JSON. The request is probably served by your frontend (a SPA fallback or a dev server without a proxy to your backend).`
2294
+ );
2295
+ throw error;
2296
+ }
2297
+ };
2298
+ const postJson = (path, body) => request(path, {
2299
+ method: "POST",
2300
+ headers: { "Content-Type": "application/json" },
2301
+ body: JSON.stringify(body)
2302
+ });
2303
+ const readUser = async (path, response) => {
2304
+ const payload = await readJson(path, response);
2305
+ try {
2306
+ return toUser(payload);
2307
+ } catch (error) {
2308
+ hint(
2309
+ `user ${path}`,
2310
+ `${base}${path} must answer { address, did, roles } from the user Block-Auth returned.`
2311
+ );
2312
+ throw error;
2313
+ }
2314
+ };
2315
+ const fail = (path, response) => {
2316
+ if (response.status === 404 || response.status === 405) {
2317
+ hint(
2318
+ `missing ${path}`,
2319
+ `${base}${path} answered ${response.status}: add the ${path} route to your backend.`
2320
+ );
2321
+ } else if (path === "/code" && response.status >= 500) {
2322
+ hint(
2323
+ `redeem ${response.status}`,
2324
+ `${base}/code answered ${response.status}: your backend could not redeem the code. Check its logs and the apiKey, apiSecret hash and redirectUri it sends to /api/auth/token.`
2325
+ );
2326
+ }
2327
+ throw new Error(`authEndpoint ${path} failed (${response.status})`);
2328
+ };
2329
+ return {
2330
+ redeem: async ({ code, codeVerifier, redirectUri }) => {
2331
+ const response = await postJson("/code", {
2332
+ code,
2333
+ codeVerifier,
2334
+ redirectUri
2335
+ });
2336
+ if (!response.ok) fail("/code", response);
2337
+ return readUser("/code", response);
2338
+ },
2339
+ me: async () => {
2340
+ const response = await request("/me", { method: "GET" });
2341
+ if (response.status === 401) return null;
2342
+ if (!response.ok) fail("/me", response);
2343
+ return readUser("/me", response);
2344
+ },
2345
+ logout: async () => {
2346
+ const response = await postJson("/logout", {});
2347
+ if (!response.ok) fail("/logout", response);
2348
+ },
2349
+ linkStatus: async () => {
2350
+ const response = await request("/link", { method: "GET" });
2351
+ if (response.status === 401) return null;
2352
+ if (!response.ok) fail("/link", response);
2353
+ const { linked } = await readJson("/link", response);
2354
+ return linked === true;
2355
+ },
2356
+ link: async ({ code, codeVerifier, redirectUri }) => {
2357
+ const response = await postJson("/link", {
2358
+ code,
2359
+ codeVerifier,
2360
+ redirectUri
2361
+ });
2362
+ if (response.ok) return;
2363
+ const reason = response.status === 409 ? "already_linked" : response.status === 401 ? "not_signed_in" : "failed";
2364
+ throw new AccountLinkError(reason, response.status);
2365
+ }
2366
+ };
2367
+ }
2368
+
2369
+ // src/session/sessionWatch.ts
2370
+ var MAX_TIMER_MS = 2147483647;
2371
+ function createSessionWatch({
2372
+ check,
2373
+ onEnded,
2374
+ intervalMs,
2375
+ minGapMs = 5e3
2376
+ }) {
2377
+ let active = false;
2378
+ let timer = null;
2379
+ let running = false;
2380
+ let lastRun = 0;
2381
+ const run = async () => {
2382
+ if (!active || running || Date.now() - lastRun < minGapMs) return;
2383
+ running = true;
2384
+ lastRun = Date.now();
2385
+ try {
2386
+ const alive = await check();
2387
+ if (active && alive === false) {
2388
+ stop();
2389
+ onEnded();
2390
+ }
2391
+ } finally {
2392
+ running = false;
2393
+ }
2394
+ };
2395
+ const onVisible = () => {
2396
+ if (document.visibilityState === "visible") void run();
2397
+ };
2398
+ const onFocus = () => void run();
2399
+ function start() {
2400
+ if (active || !Number.isFinite(intervalMs) || intervalMs <= 0 || typeof window === "undefined")
2401
+ return;
2402
+ active = true;
2403
+ lastRun = Date.now();
2404
+ timer = setInterval(() => void run(), Math.min(intervalMs, MAX_TIMER_MS));
2405
+ document.addEventListener("visibilitychange", onVisible);
2406
+ window.addEventListener("focus", onFocus);
2407
+ }
2408
+ function stop() {
2409
+ if (!active) return;
2410
+ active = false;
2411
+ if (timer !== null) clearInterval(timer);
2412
+ timer = null;
2413
+ document.removeEventListener("visibilitychange", onVisible);
2414
+ window.removeEventListener("focus", onFocus);
2415
+ }
2416
+ return { start, stop };
2417
+ }
2418
+
2236
2419
  // src/auth/logout.ts
2237
2420
  async function performLogout(args) {
2238
2421
  const { wsc, token, apiKey, sessionId, apiUrl } = args;
@@ -2487,9 +2670,9 @@ async function signInWithMicrosoft(overrides = {}) {
2487
2670
  setServiceIcon(imgUrlByService("microsoft"));
2488
2671
  return { accessToken: response.accessToken, response };
2489
2672
  }
2490
- function rememberHostedLogin(result) {
2673
+ function showHostedUser(result) {
2491
2674
  const did = result.did ?? result.address;
2492
- browserBase.setSession({ did, serviceName: "blockauth" });
2675
+ setDid(did);
2493
2676
  setUser({
2494
2677
  address: result.address,
2495
2678
  did,
@@ -2499,9 +2682,34 @@ function rememberHostedLogin(result) {
2499
2682
  setIsServiceConnected(true);
2500
2683
  setIsSigned(true);
2501
2684
  setIsSignedFirstCheck(true);
2685
+ return did;
2686
+ }
2687
+ function rememberHostedLogin(result) {
2688
+ const did = showHostedUser(result);
2689
+ browserBase.setSession({ did, serviceName: "blockauth" });
2690
+ }
2691
+ function forgetHostedUser() {
2692
+ resetUser();
2693
+ setDid(null);
2694
+ setIsServiceConnected(false);
2695
+ setIsSigned(false);
2696
+ setIsSignedFirstCheck(true);
2502
2697
  }
2503
2698
  function createBlockAuthClient(config3) {
2504
2699
  if (config3.locale) setLocale(config3.locale);
2700
+ const authEndpointUrl = config3.authEndpoint === false ? null : config3.authEndpoint || (config3.apiUrl ? null : DEFAULT_AUTH_ENDPOINT);
2701
+ const authEndpoint = authEndpointUrl ? createAuthEndpoint(authEndpointUrl) : null;
2702
+ const isDefaultAuthEndpoint = Boolean(authEndpoint) && !config3.authEndpoint;
2703
+ const usesAuthEndpoint = (ownsAuthCode = false) => Boolean(authEndpoint) && !(ownsAuthCode && isDefaultAuthEndpoint);
2704
+ let sessionOnAuthEndpoint = Boolean(authEndpoint);
2705
+ const sessionWatch = authEndpoint ? createSessionWatch({
2706
+ check: () => authEndpoint.me().then((user) => user !== null).catch(() => null),
2707
+ onEnded: () => {
2708
+ forgetHostedUser();
2709
+ config3.onSessionEnded?.();
2710
+ },
2711
+ intervalMs: (config3.sessionCheckSeconds ?? 60) * 1e3
2712
+ }) : null;
2505
2713
  const provider = new BlockAuthProvider(
2506
2714
  config3.apiKey,
2507
2715
  config3.apiSecret,
@@ -2595,7 +2803,50 @@ function createBlockAuthClient(config3) {
2595
2803
  authorizeWithPopup: () => authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl }),
2596
2804
  // After the backend redeemed the code: shows the user in the page's UI
2597
2805
  // (profile dropdown, roles). The backend's answer is the source of truth.
2598
- rememberHostedLogin: (user) => rememberHostedLogin(user),
2806
+ rememberHostedLogin: (user, options = {}) => {
2807
+ showHostedUser(user);
2808
+ sessionOnAuthEndpoint = usesAuthEndpoint(options.ownsAuthCode);
2809
+ if (sessionOnAuthEndpoint) sessionWatch?.start();
2810
+ },
2811
+ forgetHostedLogin: () => {
2812
+ sessionWatch?.stop();
2813
+ forgetHostedUser();
2814
+ },
2815
+ hasAuthEndpoint: Boolean(authEndpoint),
2816
+ usesAuthEndpoint,
2817
+ loginWithAuthEndpoint: async () => {
2818
+ if (!authEndpoint) throw new Error("authEndpoint not configured");
2819
+ const user = await authEndpoint.redeem(
2820
+ await authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl })
2821
+ );
2822
+ showHostedUser(user);
2823
+ sessionOnAuthEndpoint = true;
2824
+ sessionWatch?.start();
2825
+ return user;
2826
+ },
2827
+ getAccountLinkStatus: async () => {
2828
+ if (!authEndpoint) return null;
2829
+ return authEndpoint.linkStatus();
2830
+ },
2831
+ linkWithAuthEndpoint: async () => {
2832
+ if (!authEndpoint) throw new Error("authEndpoint not configured");
2833
+ await authEndpoint.link(
2834
+ await authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl })
2835
+ );
2836
+ },
2837
+ restoreHostedLogin: async () => {
2838
+ if (!authEndpoint) return null;
2839
+ const user = await authEndpoint.me();
2840
+ if (user) {
2841
+ showHostedUser(user);
2842
+ sessionOnAuthEndpoint = true;
2843
+ sessionWatch?.start();
2844
+ } else {
2845
+ sessionWatch?.stop();
2846
+ forgetHostedUser();
2847
+ }
2848
+ return user;
2849
+ },
2599
2850
  // oauth
2600
2851
  oauth: {
2601
2852
  ...oauth_exports,
@@ -2672,13 +2923,18 @@ function createBlockAuthClient(config3) {
2672
2923
  // full deletion-state teardown after the user confirms the
2673
2924
  // restoration-expired modal.
2674
2925
  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
- }),
2926
+ logout: async () => {
2927
+ if (authEndpoint && !config3.apiUrl && sessionOnAuthEndpoint)
2928
+ await authEndpoint.logout();
2929
+ sessionWatch?.stop();
2930
+ await performLogout({
2931
+ wsc: provider.wsc,
2932
+ token: userToken(),
2933
+ apiKey: config3.apiKey,
2934
+ sessionId: browserBase.getDeviceSessionId(),
2935
+ apiUrl: config3.apiUrl
2936
+ });
2937
+ },
2682
2938
  // modals (stack — supports overlaying signin on top of signup)
2683
2939
  openModal,
2684
2940
  closeModal,
@@ -2806,7 +3062,7 @@ function getDefaultPhoneCountry(languages) {
2806
3062
  }
2807
3063
  return DEFAULT_PHONE_COUNTRY;
2808
3064
  }
2809
- function parsePhoneValue(value, fallbackCountry = getDefaultPhoneCountry()) {
3065
+ function parsePhoneValue(value, fallbackCountry = DEFAULT_PHONE_COUNTRY) {
2810
3066
  const raw = (value ?? "").trim();
2811
3067
  if (!raw) return { country: fallbackCountry, nationalNumber: "" };
2812
3068
  const legacy = raw.match(LEGACY_PHONE_PATTERN);
@@ -2870,7 +3126,7 @@ function updatePhoneDraft(country, nationalNumber) {
2870
3126
  function resolvePhoneDraft(value, draft, fallbackCountry) {
2871
3127
  const current = value ?? "";
2872
3128
  if (draft && draft.value === current) return draft;
2873
- const country = draft?.country ?? fallbackCountry ?? getDefaultPhoneCountry();
3129
+ const country = draft?.country ?? fallbackCountry ?? DEFAULT_PHONE_COUNTRY;
2874
3130
  const parsed = parsePhoneValue(current, country);
2875
3131
  const keepCountry = !!draft && min.getCountryCallingCode(draft.country) === min.getCountryCallingCode(parsed.country);
2876
3132
  return {
@@ -4257,6 +4513,7 @@ exports.$user = $user;
4257
4513
  exports.$wallet = $wallet;
4258
4514
  exports.$web3 = $web3;
4259
4515
  exports.$ws = $ws;
4516
+ exports.AccountLinkError = AccountLinkError;
4260
4517
  exports.BlockAuthProvider = BlockAuthProvider;
4261
4518
  exports.DEFAULT_PHONE_COUNTRY = DEFAULT_PHONE_COUNTRY;
4262
4519
  exports.DISCOVERY_TIMEOUT_MS = DISCOVERY_TIMEOUT_MS;