@insforge/sdk 1.0.1-refresh.4 → 1.0.1-refresh.6

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.mjs CHANGED
@@ -228,7 +228,7 @@ var SecureSessionStorage = class {
228
228
  if (this.accessToken) return false;
229
229
  return this.hasAuthFlag();
230
230
  }
231
- // --- Private: Auth Flag Cookie Detection (read-only) ---
231
+ // --- Private: Auth Flag Cookie Detection (SDK-managed on frontend domain) ---
232
232
  hasAuthFlag() {
233
233
  if (typeof document === "undefined") return false;
234
234
  return document.cookie.split(";").some(
@@ -492,27 +492,41 @@ var Auth = class {
492
492
  this.detectAuthCallback();
493
493
  }
494
494
  /**
495
- * Check if the isAuthenticated cookie flag exists
495
+ * Set the isAuthenticated cookie flag on the frontend domain
496
+ * This is managed by SDK, not backend, to work in cross-origin scenarios
496
497
  */
497
- hasAuthenticatedCookie() {
498
- if (typeof document === "undefined") return false;
499
- return document.cookie.split(";").some(
500
- (c) => c.trim().startsWith(`${AUTH_FLAG_COOKIE}=`)
501
- );
498
+ setAuthenticatedCookie() {
499
+ if (typeof document === "undefined") return;
500
+ const maxAge = 7 * 24 * 60 * 60;
501
+ document.cookie = `${AUTH_FLAG_COOKIE}=true; path=/; max-age=${maxAge}; SameSite=Lax`;
502
+ }
503
+ /**
504
+ * Clear the isAuthenticated cookie flag from the frontend domain
505
+ */
506
+ clearAuthenticatedCookie() {
507
+ if (typeof document === "undefined") return;
508
+ document.cookie = `${AUTH_FLAG_COOKIE}=; path=/; max-age=0; SameSite=Lax`;
502
509
  }
503
510
  /**
504
511
  * Switch to SecureSessionStorage (cookie-based auth)
505
- * Called when we detect backend supports secure cookie mode
512
+ * Called when backend returns sessionMode: 'secure'
506
513
  * @internal
507
514
  */
508
515
  _switchToSecureStorage() {
509
- if (this.tokenManager.getStrategyId() === "secure") return;
516
+ console.log("[InsForge:Auth] _switchToSecureStorage() called, current strategy:", this.tokenManager.getStrategyId());
517
+ if (this.tokenManager.getStrategyId() === "secure") {
518
+ console.log("[InsForge:Auth] _switchToSecureStorage() - already in secure mode, skipping");
519
+ return;
520
+ }
510
521
  const currentSession = this.tokenManager.getSession();
511
522
  this.tokenManager.setStrategy(new SecureSessionStorage());
512
523
  if (typeof localStorage !== "undefined") {
524
+ console.log("[InsForge:Auth] _switchToSecureStorage() - clearing localStorage");
513
525
  localStorage.removeItem(TOKEN_KEY);
514
526
  localStorage.removeItem(USER_KEY);
515
527
  }
528
+ console.log("[InsForge:Auth] _switchToSecureStorage() - setting isAuthenticated cookie");
529
+ this.setAuthenticatedCookie();
516
530
  if (currentSession) {
517
531
  this.tokenManager.saveSession(currentSession);
518
532
  }
@@ -526,17 +540,19 @@ var Auth = class {
526
540
  if (this.tokenManager.getStrategyId() === "local") return;
527
541
  const currentSession = this.tokenManager.getSession();
528
542
  this.tokenManager.setStrategy(new LocalSessionStorage());
543
+ this.clearAuthenticatedCookie();
529
544
  if (currentSession) {
530
545
  this.tokenManager.saveSession(currentSession);
531
546
  }
532
547
  }
533
548
  /**
534
- * Detect storage strategy after successful auth
535
- * Checks for isAuthenticated cookie to determine backend mode
549
+ * Detect storage strategy based on backend response
550
+ * @param sessionMode - The sessionMode returned by backend ('secure' or undefined)
536
551
  * @internal
537
552
  */
538
- _detectStorageAfterAuth() {
539
- if (this.hasAuthenticatedCookie()) {
553
+ _detectStorageFromResponse(sessionMode) {
554
+ console.log("[InsForge:Auth] _detectStorageFromResponse() - sessionMode:", sessionMode);
555
+ if (sessionMode === "secure") {
540
556
  this._switchToSecureStorage();
541
557
  }
542
558
  }
@@ -553,8 +569,9 @@ var Auth = class {
553
569
  const userId = params.get("user_id");
554
570
  const email = params.get("email");
555
571
  const name = params.get("name");
572
+ const sessionMode = params.get("session_mode");
556
573
  if (accessToken && userId && email) {
557
- this._detectStorageAfterAuth();
574
+ this._detectStorageFromResponse(sessionMode || void 0);
558
575
  const session = {
559
576
  accessToken,
560
577
  user: {
@@ -575,6 +592,7 @@ var Auth = class {
575
592
  url.searchParams.delete("user_id");
576
593
  url.searchParams.delete("email");
577
594
  url.searchParams.delete("name");
595
+ url.searchParams.delete("session_mode");
578
596
  if (params.has("error")) {
579
597
  url.searchParams.delete("error");
580
598
  }
@@ -590,6 +608,8 @@ var Auth = class {
590
608
  async signUp(request) {
591
609
  try {
592
610
  const response = await this.http.post("/api/auth/users", request);
611
+ const sessionMode = response.sessionMode;
612
+ this._detectStorageFromResponse(sessionMode);
593
613
  if (response.accessToken && response.user) {
594
614
  const session = {
595
615
  accessToken: response.accessToken,
@@ -599,7 +619,6 @@ var Auth = class {
599
619
  this.tokenManager.saveSession(session);
600
620
  }
601
621
  this.http.setAuthToken(response.accessToken);
602
- this._detectStorageAfterAuth();
603
622
  }
604
623
  return {
605
624
  data: response,
@@ -625,6 +644,8 @@ var Auth = class {
625
644
  async signInWithPassword(request) {
626
645
  try {
627
646
  const response = await this.http.post("/api/auth/sessions", request);
647
+ const sessionMode = response.sessionMode;
648
+ this._detectStorageFromResponse(sessionMode);
628
649
  const session = {
629
650
  accessToken: response.accessToken || "",
630
651
  user: response.user || {
@@ -640,7 +661,6 @@ var Auth = class {
640
661
  this.tokenManager.saveSession(session);
641
662
  }
642
663
  this.http.setAuthToken(response.accessToken || "");
643
- this._detectStorageAfterAuth();
644
664
  return {
645
665
  data: response,
646
666
  error: null
@@ -698,17 +718,25 @@ var Auth = class {
698
718
  * In modern mode, also calls backend to clear the refresh token cookie
699
719
  */
700
720
  async signOut() {
721
+ console.log("[InsForge:Auth] signOut() called");
722
+ console.log("[InsForge:Auth] signOut() stack trace:", new Error().stack);
701
723
  try {
702
724
  if (this.tokenManager.getStrategyId() === "secure") {
725
+ console.log("[InsForge:Auth] signOut() - calling backend /api/auth/logout");
703
726
  try {
704
727
  await this.http.post("/api/auth/logout");
705
- } catch {
728
+ console.log("[InsForge:Auth] signOut() - backend logout successful");
729
+ } catch (e) {
730
+ console.log("[InsForge:Auth] signOut() - backend logout failed (ignored):", e);
706
731
  }
707
732
  }
708
733
  this.tokenManager.clearSession();
709
734
  this.http.setAuthToken(null);
735
+ this.clearAuthenticatedCookie();
736
+ console.log("[InsForge:Auth] signOut() - completed");
710
737
  return { error: null };
711
738
  } catch (error) {
739
+ console.error("[InsForge:Auth] signOut() - error:", error);
712
740
  return {
713
741
  error: new InsForgeError(
714
742
  "Failed to sign out",
@@ -725,16 +753,20 @@ var Auth = class {
725
753
  * @returns New access token or throws an error
726
754
  */
727
755
  async refreshToken() {
756
+ console.log("[InsForge:Auth] refreshToken() called");
728
757
  try {
729
758
  const response = await this.http.post(
730
759
  "/api/auth/refresh"
731
760
  );
761
+ console.log("[InsForge:Auth] refreshToken() - response received, hasAccessToken:", !!response.accessToken);
732
762
  if (response.accessToken) {
763
+ this._detectStorageFromResponse(response.sessionMode);
733
764
  this.tokenManager.setAccessToken(response.accessToken);
734
765
  this.http.setAuthToken(response.accessToken);
735
766
  if (response.user) {
736
767
  this.tokenManager.setUser(response.user);
737
768
  }
769
+ console.log("[InsForge:Auth] refreshToken() - success");
738
770
  return response.accessToken;
739
771
  }
740
772
  throw new InsForgeError(
@@ -743,10 +775,13 @@ var Auth = class {
743
775
  "REFRESH_FAILED"
744
776
  );
745
777
  } catch (error) {
778
+ console.error("[InsForge:Auth] refreshToken() - error:", error);
746
779
  if (error instanceof InsForgeError) {
747
780
  if (error.statusCode === 401 || error.statusCode === 403) {
781
+ console.log("[InsForge:Auth] refreshToken() - clearing session due to 401/403");
748
782
  this.tokenManager.clearSession();
749
783
  this.http.setAuthToken(null);
784
+ this.clearAuthenticatedCookie();
750
785
  }
751
786
  throw error;
752
787
  }
@@ -802,12 +837,17 @@ var Auth = class {
802
837
  * to refresh the session if no access token is available (e.g., after page reload).
803
838
  */
804
839
  async getCurrentUser() {
840
+ console.log("[InsForge:Auth] getCurrentUser() called");
805
841
  try {
806
842
  let accessToken = this.tokenManager.getAccessToken();
807
- if (!accessToken && this.tokenManager.shouldAttemptRefresh()) {
843
+ const shouldRefresh = this.tokenManager.shouldAttemptRefresh();
844
+ console.log("[InsForge:Auth] getCurrentUser() - hasAccessToken:", !!accessToken, "shouldAttemptRefresh:", shouldRefresh);
845
+ if (!accessToken && shouldRefresh) {
846
+ console.log("[InsForge:Auth] getCurrentUser() - attempting refresh");
808
847
  try {
809
848
  accessToken = await this.refreshToken();
810
849
  } catch (error) {
850
+ console.log("[InsForge:Auth] getCurrentUser() - refresh failed:", error);
811
851
  if (error instanceof InsForgeError && (error.statusCode === 401 || error.statusCode === 403)) {
812
852
  return { data: null, error };
813
853
  }
@@ -815,14 +855,17 @@ var Auth = class {
815
855
  }
816
856
  }
817
857
  if (!accessToken) {
858
+ console.log("[InsForge:Auth] getCurrentUser() - no access token, returning null");
818
859
  return { data: null, error: null };
819
860
  }
820
861
  this.http.setAuthToken(accessToken);
862
+ console.log("[InsForge:Auth] getCurrentUser() - fetching user from API");
821
863
  const authResponse = await this.http.get("/api/auth/sessions/current");
822
864
  const { data: profile, error: profileError } = await this.database.from("users").select("*").eq("id", authResponse.user.id).single();
823
865
  if (profileError && profileError.code !== "PGRST116") {
824
866
  return { data: null, error: profileError };
825
867
  }
868
+ console.log("[InsForge:Auth] getCurrentUser() - success");
826
869
  return {
827
870
  data: {
828
871
  user: authResponse.user,
@@ -831,8 +874,12 @@ var Auth = class {
831
874
  error: null
832
875
  };
833
876
  } catch (error) {
877
+ console.error("[InsForge:Auth] getCurrentUser() - catch error:", error);
834
878
  if (error instanceof InsForgeError && error.statusCode === 401) {
835
- await this.signOut();
879
+ console.log("[InsForge:Auth] getCurrentUser() - 401 error, clearing local session only (NOT calling signOut)");
880
+ this.tokenManager.clearSession();
881
+ this.http.setAuthToken(null);
882
+ this.clearAuthenticatedCookie();
836
883
  return { data: null, error: null };
837
884
  }
838
885
  if (error instanceof InsForgeError) {
@@ -1080,6 +1127,8 @@ var Auth = class {
1080
1127
  "/api/auth/email/verify",
1081
1128
  request
1082
1129
  );
1130
+ const sessionMode = response.sessionMode;
1131
+ this._detectStorageFromResponse(sessionMode);
1083
1132
  if (response.accessToken) {
1084
1133
  const session = {
1085
1134
  accessToken: response.accessToken,
@@ -1638,9 +1687,14 @@ function hasAuthenticatedCookie() {
1638
1687
  }
1639
1688
  var InsForgeClient = class {
1640
1689
  constructor(config = {}) {
1690
+ console.log("[InsForge:Client] Initializing SDK");
1641
1691
  this.http = new HttpClient(config);
1642
1692
  this.tokenManager = new TokenManager(config.storage);
1643
- if (hasAuthenticatedCookie()) {
1693
+ const hasAuthCookie = hasAuthenticatedCookie();
1694
+ console.log("[InsForge:Client] hasAuthenticatedCookie:", hasAuthCookie);
1695
+ console.log("[InsForge:Client] document.cookie:", typeof document !== "undefined" ? document.cookie : "N/A (SSR)");
1696
+ if (hasAuthCookie) {
1697
+ console.log("[InsForge:Client] Switching to SecureSessionStorage");
1644
1698
  this.tokenManager.setStrategy(new SecureSessionStorage());
1645
1699
  }
1646
1700
  if (config.edgeFunctionToken) {
@@ -1652,25 +1706,31 @@ var InsForgeClient = class {
1652
1706
  });
1653
1707
  }
1654
1708
  this.http.setRefreshCallback(async () => {
1709
+ console.log("[InsForge:Client] HTTP 401 refresh callback triggered");
1655
1710
  try {
1656
1711
  return await this.auth.refreshToken();
1657
- } catch {
1712
+ } catch (e) {
1713
+ console.log("[InsForge:Client] Refresh callback failed:", e);
1658
1714
  if (this.tokenManager.getStrategyId() === "secure") {
1715
+ console.log("[InsForge:Client] Falling back to LocalSessionStorage");
1659
1716
  this.auth._switchToLocalStorage();
1660
1717
  }
1661
1718
  return null;
1662
1719
  }
1663
1720
  });
1664
1721
  const existingSession = this.tokenManager.getSession();
1722
+ console.log("[InsForge:Client] existingSession:", !!existingSession, "strategyId:", this.tokenManager.getStrategyId());
1665
1723
  if (existingSession?.accessToken) {
1666
1724
  this.http.setAuthToken(existingSession.accessToken);
1667
1725
  } else if (this.tokenManager.getStrategyId() === "secure") {
1726
+ console.log("[InsForge:Client] Secure mode, no session in memory - will refresh on first API call");
1668
1727
  }
1669
1728
  this.auth = new Auth(this.http, this.tokenManager);
1670
1729
  this.database = new Database(this.http, this.tokenManager);
1671
1730
  this.storage = new Storage(this.http);
1672
1731
  this.ai = new AI(this.http);
1673
1732
  this.functions = new Functions(this.http);
1733
+ console.log("[InsForge:Client] SDK initialized");
1674
1734
  }
1675
1735
  /**
1676
1736
  * Get the underlying HTTP client for custom requests