@erikey/react 0.1.6 → 0.2.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.mjs CHANGED
@@ -1613,284 +1613,151 @@ function createDashboardClient(config) {
1613
1613
  });
1614
1614
  }
1615
1615
 
1616
- // ../js/dist/index.js
1617
- var DEFAULT_BASE_URL = "https://auth.erikey.com";
1616
+ // src/lib/cross-origin-auth.ts
1617
+ function shouldUseBearerAuth(authApiUrl) {
1618
+ if (typeof window === "undefined") {
1619
+ return false;
1620
+ }
1621
+ try {
1622
+ const currentOrigin = window.location.origin;
1623
+ const authOrigin = new URL(authApiUrl).origin;
1624
+ return currentOrigin !== authOrigin;
1625
+ } catch {
1626
+ return false;
1627
+ }
1628
+ }
1629
+ function getStorageKey(projectId) {
1630
+ return `erikey.session.${projectId}`;
1631
+ }
1632
+ function storeToken(projectId, session) {
1633
+ if (typeof window === "undefined") return;
1634
+ const key = getStorageKey(projectId);
1635
+ localStorage.setItem(key, JSON.stringify(session));
1636
+ }
1637
+ function getStoredToken(projectId) {
1638
+ if (typeof window === "undefined") return null;
1639
+ const key = getStorageKey(projectId);
1640
+ const stored = localStorage.getItem(key);
1641
+ if (!stored) return null;
1642
+ try {
1643
+ const session = JSON.parse(stored);
1644
+ if (new Date(session.expiresAt) < /* @__PURE__ */ new Date()) {
1645
+ localStorage.removeItem(key);
1646
+ return null;
1647
+ }
1648
+ return session.token;
1649
+ } catch {
1650
+ localStorage.removeItem(key);
1651
+ return null;
1652
+ }
1653
+ }
1654
+ function clearToken(projectId) {
1655
+ if (typeof window === "undefined") return;
1656
+ const key = getStorageKey(projectId);
1657
+ localStorage.removeItem(key);
1658
+ }
1659
+
1660
+ // src/auth-client.ts
1618
1661
  function createAuthClient2(config) {
1619
- const { projectId, baseUrl = DEFAULT_BASE_URL } = config;
1620
- const fetchWithAuth = async (endpoint, options) => {
1621
- const headers = {
1622
- "Content-Type": "application/json",
1623
- "X-Project-Id": projectId,
1624
- ...options?.headers || {}
1625
- };
1626
- const response = await fetch(`${baseUrl}/api/auth${endpoint}`, {
1627
- ...options,
1628
- credentials: "include",
1629
- // Send cookies
1630
- headers
1631
- });
1632
- const data = await response.json();
1633
- if (!response.ok) {
1634
- return {
1635
- success: false,
1636
- error: data?.error?.message || data?.message || "Request failed"
1637
- };
1662
+ const { projectId, baseUrl = "https://auth.erikey.com" } = config;
1663
+ const useBearerAuth = shouldUseBearerAuth(baseUrl);
1664
+ const fetchOptions = {
1665
+ // Always send project ID header for multi-tenant routing
1666
+ headers: {
1667
+ "X-Project-Id": projectId
1668
+ },
1669
+ // For cross-origin contexts, use Bearer token auth
1670
+ ...useBearerAuth && {
1671
+ auth: {
1672
+ type: "Bearer",
1673
+ token: () => getStoredToken(projectId) || ""
1674
+ }
1638
1675
  }
1639
- return {
1640
- success: true,
1641
- data
1642
- };
1643
1676
  };
1677
+ const client = createAuthClient({
1678
+ baseURL: baseUrl,
1679
+ fetchOptions,
1680
+ // For same-origin, include cookies
1681
+ ...!useBearerAuth && { credentials: "include" }
1682
+ });
1683
+ if (!useBearerAuth) {
1684
+ return client;
1685
+ }
1644
1686
  return {
1645
- /**
1646
- * Sign up a new user
1647
- */
1648
- signUp: async (data) => {
1649
- return fetchWithAuth("/sign-up/email", {
1650
- method: "POST",
1651
- body: JSON.stringify(data)
1652
- });
1653
- },
1654
- /**
1655
- * Sign in an existing user
1656
- */
1657
- signIn: async (data) => {
1658
- return fetchWithAuth("/sign-in/email", {
1659
- method: "POST",
1660
- body: JSON.stringify(data)
1661
- });
1662
- },
1663
- /**
1664
- * Sign out the current user
1665
- */
1666
- signOut: async () => {
1667
- return fetchWithAuth("/sign-out", {
1668
- method: "POST"
1669
- });
1670
- },
1671
- /**
1672
- * Get the current authenticated user
1673
- */
1674
- getUser: async () => {
1675
- return fetchWithAuth("/get-session", {
1676
- method: "GET"
1677
- });
1678
- },
1679
- /**
1680
- * Request a password reset email
1681
- */
1682
- forgotPassword: async (email) => {
1683
- const result = await fetchWithAuth("/forget-password", {
1684
- method: "POST",
1685
- body: JSON.stringify({ email })
1686
- });
1687
- if (!result.success) {
1688
- return { success: false, message: result.error || "Failed to request password reset" };
1689
- }
1690
- return {
1691
- success: true,
1692
- message: result.data?.message || "Password reset email sent"
1693
- };
1694
- },
1695
- /**
1696
- * Reset password with a token from the reset email
1697
- */
1698
- resetPassword: async (token, newPassword) => {
1699
- const result = await fetchWithAuth("/reset-password", {
1700
- method: "POST",
1701
- body: JSON.stringify({ token, newPassword })
1702
- });
1703
- if (!result.success) {
1704
- return { success: false, message: result.error || "Failed to reset password" };
1705
- }
1706
- return {
1707
- success: true,
1708
- message: result.data?.message || "Password reset successful"
1709
- };
1710
- },
1711
- /**
1712
- * Set a single key-value pair
1713
- */
1714
- setValue: async (key, value) => {
1715
- return fetchWithAuth(`/key-value/${encodeURIComponent(key)}`, {
1716
- method: "PUT",
1717
- body: JSON.stringify({ value })
1718
- });
1719
- },
1720
- /**
1721
- * Get a single key-value pair
1722
- */
1723
- getValue: async (key) => {
1724
- const result = await fetchWithAuth(
1725
- `/key-value/${encodeURIComponent(key)}`,
1726
- { method: "GET" }
1727
- );
1728
- if (!result.success) {
1729
- return { success: false, error: result.error };
1730
- }
1731
- return {
1732
- success: true,
1733
- data: {
1734
- key: result.data.key,
1735
- value: result.data.value,
1736
- createdAt: result.data.createdAt,
1737
- updatedAt: result.data.updatedAt
1687
+ ...client,
1688
+ signIn: {
1689
+ ...client.signIn,
1690
+ email: async (...args) => {
1691
+ const result = await client.signIn.email(...args);
1692
+ const token = result.data?.token;
1693
+ const sessionId = result.data?.session?.id || "session";
1694
+ if (token) {
1695
+ const session = {
1696
+ id: sessionId,
1697
+ token,
1698
+ expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString()
1699
+ };
1700
+ storeToken(projectId, session);
1738
1701
  }
1739
- };
1702
+ return result;
1703
+ },
1704
+ // Social OAuth works as-is (redirect-based, no token in response)
1705
+ social: client.signIn.social
1740
1706
  },
1741
- /**
1742
- * Get all key-value pairs for the authenticated user
1743
- */
1744
- getValues: async () => {
1745
- const result = await fetchWithAuth(
1746
- "/key-value",
1747
- { method: "GET" }
1748
- );
1749
- if (!result.success) {
1750
- return { success: false, error: result.error };
1751
- }
1752
- return {
1753
- success: true,
1754
- data: {
1755
- kvPairs: result.data.kvPairs,
1756
- total: result.data.total
1707
+ signUp: {
1708
+ ...client.signUp,
1709
+ email: async (...args) => {
1710
+ const result = await client.signUp.email(...args);
1711
+ const token = result.data?.token;
1712
+ const sessionId = result.data?.session?.id || "session";
1713
+ if (token) {
1714
+ const session = {
1715
+ id: sessionId,
1716
+ token,
1717
+ expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString()
1718
+ };
1719
+ storeToken(projectId, session);
1757
1720
  }
1758
- };
1759
- },
1760
- /**
1761
- * Delete a single key-value pair
1762
- */
1763
- deleteValue: async (key) => {
1764
- const result = await fetchWithAuth(
1765
- `/key-value/${encodeURIComponent(key)}`,
1766
- { method: "DELETE" }
1767
- );
1768
- if (!result.success) {
1769
- return { success: false, error: result.error };
1721
+ return result;
1770
1722
  }
1771
- return {
1772
- success: true,
1773
- data: {
1774
- message: result.data.message || "KV pair deleted"
1775
- }
1776
- };
1777
1723
  },
1778
- /**
1779
- * Delete multiple key-value pairs
1780
- * Note: Makes sequential DELETE requests since no bulk delete endpoint exists
1781
- */
1782
- deleteValues: async (keys) => {
1783
- if (keys.length === 0) {
1784
- return {
1785
- success: true,
1786
- data: {
1787
- deleted: [],
1788
- failed: []
1789
- }
1790
- };
1791
- }
1792
- const results = await Promise.allSettled(
1793
- keys.map(
1794
- (key) => fetchWithAuth(
1795
- `/key-value/${encodeURIComponent(key)}`,
1796
- { method: "DELETE" }
1797
- ).then((result) => ({ key, result }))
1798
- )
1799
- );
1800
- const deleted = [];
1801
- const failed = [];
1802
- results.forEach((result, index) => {
1803
- if (result.status === "fulfilled") {
1804
- const { key, result: deleteResult } = result.value;
1805
- if (deleteResult.success) {
1806
- deleted.push(key);
1807
- } else {
1808
- failed.push({
1809
- key,
1810
- error: deleteResult.error || "Delete failed"
1811
- });
1812
- }
1813
- } else {
1814
- failed.push({
1815
- key: keys[index],
1816
- error: result.reason?.message || "Request failed"
1817
- });
1818
- }
1819
- });
1820
- return {
1821
- success: failed.length === 0,
1822
- data: {
1823
- deleted,
1824
- failed
1825
- }
1826
- };
1724
+ signOut: async (...args) => {
1725
+ clearToken(projectId);
1726
+ return client.signOut(...args);
1827
1727
  },
1828
- /**
1829
- * Set multiple key-value pairs in bulk (max 100 pairs)
1830
- */
1831
- setValues: async (kvPairs) => {
1832
- const result = await fetchWithAuth(
1833
- "/key-value/bulk",
1834
- {
1835
- method: "POST",
1836
- body: JSON.stringify({ kvPairs })
1837
- }
1838
- );
1839
- if (!result.success) {
1840
- return { success: false, error: result.error };
1841
- }
1842
- return {
1843
- success: true,
1844
- data: {
1845
- results: result.data.results,
1846
- total: result.data.total
1847
- }
1848
- };
1849
- }
1728
+ // useSession works as-is - it uses the Bearer token from fetchOptions
1729
+ useSession: client.useSession,
1730
+ // Pass through other methods
1731
+ getSession: client.getSession
1850
1732
  };
1851
1733
  }
1852
1734
 
1853
1735
  // ../../sandpack-auth/dist/client/index.js
1854
- function isSandpackEnvironment() {
1736
+ function shouldUseBearerAuth2(authApiUrl) {
1855
1737
  if (typeof window === "undefined") {
1856
1738
  return false;
1857
1739
  }
1858
- if (process.env.NODE_ENV === "production") {
1859
- console.warn(
1860
- "[SANDPACK-AUTH] Sandpack detection called in production environment. This should only run in development/preview. Returning false."
1861
- );
1862
- return false;
1863
- }
1864
1740
  try {
1865
- const inIframe = window.self !== window.top;
1866
- return inIframe;
1867
- } catch {
1868
- return true;
1741
+ const currentOrigin = window.location.origin;
1742
+ const authOrigin = new URL(authApiUrl).origin;
1743
+ const isCrossOrigin = currentOrigin !== authOrigin;
1744
+ if (isCrossOrigin) {
1745
+ console.log("[Sandpack Auth] Cross-origin detected:", {
1746
+ current: currentOrigin,
1747
+ auth: authOrigin
1748
+ });
1749
+ }
1750
+ return isCrossOrigin;
1751
+ } catch (error) {
1752
+ console.error("[Sandpack Auth] Failed to check origin:", error);
1753
+ return false;
1869
1754
  }
1870
1755
  }
1871
- function getStorageKey(projectId) {
1756
+ function getStorageKey2(projectId) {
1872
1757
  return `erikey.session.${projectId}`;
1873
1758
  }
1874
- function storeToken(projectId, session) {
1875
- const key = getStorageKey(projectId);
1876
- const stored = {
1877
- token: session.token,
1878
- expiresAt: session.expiresAt
1879
- };
1880
- console.log("[Sandpack Auth] Storing token:", {
1881
- key,
1882
- tokenPreview: session.token.substring(0, 20) + "..."
1883
- });
1884
- localStorage.setItem(key, JSON.stringify(stored));
1885
- const check = localStorage.getItem(key);
1886
- if (!check) {
1887
- console.error("[Sandpack Auth] Failed to store token in localStorage");
1888
- } else {
1889
- console.log("[Sandpack Auth] Token stored successfully");
1890
- }
1891
- }
1892
- function getStoredToken(projectId) {
1893
- const key = getStorageKey(projectId);
1759
+ function getStoredToken2(projectId) {
1760
+ const key = getStorageKey2(projectId);
1894
1761
  const stored = localStorage.getItem(key);
1895
1762
  if (!stored) {
1896
1763
  return null;
@@ -1909,33 +1776,26 @@ function getStoredToken(projectId) {
1909
1776
  return null;
1910
1777
  }
1911
1778
  }
1912
- function clearToken(projectId) {
1913
- const key = getStorageKey(projectId);
1914
- console.log("[Sandpack Auth] Clearing token from localStorage");
1915
- localStorage.removeItem(key);
1916
- }
1917
1779
 
1918
- // src/auth-client.ts
1919
- function createAuthClient3(config) {
1920
- const { projectId } = config;
1921
- const baseUrl = config.baseUrl || "https://auth.erikey.com";
1922
- const client = createAuthClient2(config);
1923
- const inSandpack = isSandpackEnvironment();
1924
- if (!inSandpack) {
1925
- return client;
1926
- }
1927
- const fetchWithBearer = async (endpoint, options) => {
1928
- const token = getStoredToken(projectId);
1780
+ // src/kv-client.ts
1781
+ function createKvClient(config) {
1782
+ const { projectId, baseUrl = "https://auth.erikey.com" } = config;
1783
+ const useBearerAuth = shouldUseBearerAuth2(baseUrl);
1784
+ const fetchWithAuth = async (endpoint, options) => {
1929
1785
  const headers = {
1930
1786
  "Content-Type": "application/json",
1931
1787
  "X-Project-Id": projectId,
1932
1788
  ...options?.headers || {}
1933
1789
  };
1934
- if (token) {
1935
- headers["Authorization"] = `Bearer ${token}`;
1790
+ if (useBearerAuth) {
1791
+ const token = getStoredToken2(projectId);
1792
+ if (token) {
1793
+ headers["Authorization"] = `Bearer ${token}`;
1794
+ }
1936
1795
  }
1937
1796
  const response = await fetch(`${baseUrl}/api/auth${endpoint}`, {
1938
1797
  ...options,
1798
+ credentials: useBearerAuth ? "omit" : "include",
1939
1799
  headers
1940
1800
  });
1941
1801
  const data = await response.json();
@@ -1951,72 +1811,20 @@ function createAuthClient3(config) {
1951
1811
  };
1952
1812
  };
1953
1813
  return {
1954
- signUp: async (data) => {
1955
- const result = await client.signUp(data);
1956
- const token = result.data?.token || result.data?.session?.token;
1957
- if (result.success && token) {
1958
- console.log("[Sandpack Auth] Storing token after sign-up");
1959
- storeToken(projectId, {
1960
- token,
1961
- expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString()
1962
- // 7 days
1963
- });
1964
- }
1965
- return result;
1966
- },
1967
- signIn: async (data) => {
1968
- const result = await client.signIn(data);
1969
- const token = result.data?.token || result.data?.session?.token;
1970
- if (result.success && token) {
1971
- console.log("[Sandpack Auth] Storing token after sign-in");
1972
- storeToken(projectId, {
1973
- token,
1974
- expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString()
1975
- // 7 days
1976
- });
1977
- }
1978
- return result;
1979
- },
1980
- signOut: async () => {
1981
- const result = await client.signOut();
1982
- clearToken(projectId);
1983
- return result;
1984
- },
1985
- getUser: async () => {
1986
- const result = await client.getUser();
1987
- const hasUser = result.success && result.data && ("email" in result.data || // Direct User object
1988
- "user" in result.data && result.data.user);
1989
- if (hasUser) {
1990
- return result;
1991
- }
1992
- const token = getStoredToken(projectId);
1993
- if (token) {
1994
- console.log("[Sandpack Auth] Cookie auth returned no user, trying Bearer token");
1995
- const response = await fetch(`${baseUrl}/api/auth/get-session`, {
1996
- headers: {
1997
- "Authorization": `Bearer ${token}`,
1998
- "X-Project-Id": projectId
1999
- }
2000
- });
2001
- const data = await response.json();
2002
- if (response.ok && (data?.user || data?.email)) {
2003
- console.log("[Sandpack Auth] Bearer token auth successful");
2004
- return { success: true, data };
2005
- }
2006
- }
2007
- return result;
2008
- },
2009
- forgotPassword: client.forgotPassword,
2010
- resetPassword: client.resetPassword,
2011
- // KV methods - wrapped with Bearer token support for Sandpack
1814
+ /**
1815
+ * Set a single key-value pair
1816
+ */
2012
1817
  setValue: async (key, value) => {
2013
- return fetchWithBearer(`/key-value/${encodeURIComponent(key)}`, {
1818
+ return fetchWithAuth(`/key-value/${encodeURIComponent(key)}`, {
2014
1819
  method: "PUT",
2015
1820
  body: JSON.stringify({ value })
2016
1821
  });
2017
1822
  },
1823
+ /**
1824
+ * Get a single key-value pair
1825
+ */
2018
1826
  getValue: async (key) => {
2019
- const result = await fetchWithBearer(
1827
+ const result = await fetchWithAuth(
2020
1828
  `/key-value/${encodeURIComponent(key)}`,
2021
1829
  { method: "GET" }
2022
1830
  );
@@ -2033,8 +1841,11 @@ function createAuthClient3(config) {
2033
1841
  }
2034
1842
  };
2035
1843
  },
1844
+ /**
1845
+ * Get all key-value pairs for the authenticated user
1846
+ */
2036
1847
  getValues: async () => {
2037
- const result = await fetchWithBearer(
1848
+ const result = await fetchWithAuth(
2038
1849
  "/key-value",
2039
1850
  { method: "GET" }
2040
1851
  );
@@ -2049,8 +1860,11 @@ function createAuthClient3(config) {
2049
1860
  }
2050
1861
  };
2051
1862
  },
1863
+ /**
1864
+ * Delete a single key-value pair
1865
+ */
2052
1866
  deleteValue: async (key) => {
2053
- const result = await fetchWithBearer(
1867
+ const result = await fetchWithAuth(
2054
1868
  `/key-value/${encodeURIComponent(key)}`,
2055
1869
  { method: "DELETE" }
2056
1870
  );
@@ -2064,6 +1878,9 @@ function createAuthClient3(config) {
2064
1878
  }
2065
1879
  };
2066
1880
  },
1881
+ /**
1882
+ * Delete multiple key-value pairs
1883
+ */
2067
1884
  deleteValues: async (keys) => {
2068
1885
  if (keys.length === 0) {
2069
1886
  return {
@@ -2076,7 +1893,7 @@ function createAuthClient3(config) {
2076
1893
  }
2077
1894
  const results = await Promise.allSettled(
2078
1895
  keys.map(
2079
- (key) => fetchWithBearer(
1896
+ (key) => fetchWithAuth(
2080
1897
  `/key-value/${encodeURIComponent(key)}`,
2081
1898
  { method: "DELETE" }
2082
1899
  ).then((result) => ({ key, result }))
@@ -2110,8 +1927,11 @@ function createAuthClient3(config) {
2110
1927
  }
2111
1928
  };
2112
1929
  },
1930
+ /**
1931
+ * Set multiple key-value pairs in bulk (max 100 pairs)
1932
+ */
2113
1933
  setValues: async (kvPairs) => {
2114
- const result = await fetchWithBearer(
1934
+ const result = await fetchWithAuth(
2115
1935
  "/key-value/bulk",
2116
1936
  {
2117
1937
  method: "POST",
@@ -2132,7 +1952,8 @@ function createAuthClient3(config) {
2132
1952
  };
2133
1953
  }
2134
1954
  export {
2135
- createAuthClient3 as createAuthClient,
2136
- createDashboardClient
1955
+ createAuthClient2 as createAuthClient,
1956
+ createDashboardClient,
1957
+ createKvClient
2137
1958
  };
2138
1959
  //# sourceMappingURL=index.mjs.map