@erikey/react 0.1.7 → 0.2.1

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,193 @@ function createDashboardClient(config) {
1613
1613
  });
1614
1614
  }
1615
1615
 
1616
- // ../js/dist/index.js
1617
- var DEFAULT_BASE_URL = "https://auth.erikey.com";
1618
- 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
- };
1616
+ // src/auth-client.ts
1617
+ import { useState, useEffect, useCallback as useCallback2 } from "react";
1618
+
1619
+ // src/lib/cross-origin-auth.ts
1620
+ function shouldUseBearerAuth(authApiUrl) {
1621
+ if (typeof window === "undefined") {
1622
+ return false;
1623
+ }
1624
+ try {
1625
+ const currentOrigin = window.location.origin;
1626
+ const authOrigin = new URL(authApiUrl).origin;
1627
+ return currentOrigin !== authOrigin;
1628
+ } catch {
1629
+ return false;
1630
+ }
1631
+ }
1632
+ function getStorageKey(projectId) {
1633
+ return `erikey.session.${projectId}`;
1634
+ }
1635
+ function storeToken(projectId, session) {
1636
+ if (typeof window === "undefined") return;
1637
+ const key = getStorageKey(projectId);
1638
+ localStorage.setItem(key, JSON.stringify(session));
1639
+ }
1640
+ function getStoredToken(projectId) {
1641
+ if (typeof window === "undefined") return null;
1642
+ const key = getStorageKey(projectId);
1643
+ const stored = localStorage.getItem(key);
1644
+ if (!stored) return null;
1645
+ try {
1646
+ const session = JSON.parse(stored);
1647
+ if (new Date(session.expiresAt) < /* @__PURE__ */ new Date()) {
1648
+ localStorage.removeItem(key);
1649
+ return null;
1638
1650
  }
1639
- return {
1640
- success: true,
1641
- data
1642
- };
1643
- };
1644
- 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
- });
1651
+ return session.token;
1652
+ } catch {
1653
+ localStorage.removeItem(key);
1654
+ return null;
1655
+ }
1656
+ }
1657
+ function clearToken(projectId) {
1658
+ if (typeof window === "undefined") return;
1659
+ const key = getStorageKey(projectId);
1660
+ localStorage.removeItem(key);
1661
+ }
1662
+
1663
+ // src/auth-client.ts
1664
+ function createAuthClient2(config) {
1665
+ const { projectId, baseUrl = "https://auth.erikey.com" } = config;
1666
+ const useBearerAuth = shouldUseBearerAuth(baseUrl);
1667
+ const fetchOptions = {
1668
+ // Always send project ID header for multi-tenant routing
1669
+ headers: {
1670
+ "X-Project-Id": projectId
1719
1671
  },
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 };
1672
+ // For cross-origin contexts, use Bearer token auth
1673
+ ...useBearerAuth && {
1674
+ auth: {
1675
+ type: "Bearer",
1676
+ token: () => getStoredToken(projectId) || ""
1730
1677
  }
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
1738
- }
1739
- };
1740
- },
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 };
1678
+ }
1679
+ };
1680
+ const client = createAuthClient({
1681
+ baseURL: baseUrl,
1682
+ fetchOptions,
1683
+ // For same-origin, include cookies
1684
+ ...!useBearerAuth && { credentials: "include" }
1685
+ });
1686
+ if (!useBearerAuth) {
1687
+ return client;
1688
+ }
1689
+ return new Proxy({}, {
1690
+ get(_target, prop) {
1691
+ if (typeof prop === "symbol") {
1692
+ return client[prop];
1751
1693
  }
1752
- return {
1753
- success: true,
1754
- data: {
1755
- kvPairs: result.data.kvPairs,
1756
- total: result.data.total
1757
- }
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 };
1694
+ if (prop === "signIn") {
1695
+ return new Proxy(client.signIn, {
1696
+ get(_signInTarget, signInProp) {
1697
+ if (signInProp === "email") {
1698
+ return async (...args) => {
1699
+ const result = await client.signIn.email(...args);
1700
+ const token = result.data?.token;
1701
+ if (token) {
1702
+ const session = {
1703
+ id: result.data?.session?.id || "session",
1704
+ token,
1705
+ expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString()
1706
+ };
1707
+ storeToken(projectId, session);
1708
+ }
1709
+ return result;
1710
+ };
1711
+ }
1712
+ return client.signIn[signInProp];
1713
+ }
1714
+ });
1770
1715
  }
1771
- return {
1772
- success: true,
1773
- data: {
1774
- message: result.data.message || "KV pair deleted"
1775
- }
1776
- };
1777
- },
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: []
1716
+ if (prop === "signUp") {
1717
+ return new Proxy(client.signUp, {
1718
+ get(_signUpTarget, signUpProp) {
1719
+ if (signUpProp === "email") {
1720
+ return async (...args) => {
1721
+ const result = await client.signUp.email(...args);
1722
+ const token = result.data?.token;
1723
+ if (token) {
1724
+ const session = {
1725
+ id: result.data?.session?.id || "session",
1726
+ token,
1727
+ expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString()
1728
+ };
1729
+ storeToken(projectId, session);
1730
+ }
1731
+ return result;
1732
+ };
1733
+ }
1734
+ return client.signUp[signUpProp];
1789
1735
  }
1736
+ });
1737
+ }
1738
+ if (prop === "signOut") {
1739
+ return async (...args) => {
1740
+ clearToken(projectId);
1741
+ return client.signOut(...args);
1790
1742
  };
1791
1743
  }
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
- };
1827
- },
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 };
1744
+ if (prop === "useSession") {
1745
+ return function useSession() {
1746
+ const [data, setData] = useState(null);
1747
+ const [isPending, setIsPending] = useState(true);
1748
+ const [error, setError] = useState(null);
1749
+ const refetch = useCallback2(async () => {
1750
+ setIsPending(true);
1751
+ try {
1752
+ const result = await client.getSession();
1753
+ if (result.error) {
1754
+ setError(result.error);
1755
+ setData(null);
1756
+ } else {
1757
+ setData(result.data);
1758
+ setError(null);
1759
+ }
1760
+ } catch (e) {
1761
+ setError(e);
1762
+ setData(null);
1763
+ }
1764
+ setIsPending(false);
1765
+ }, []);
1766
+ useEffect(() => {
1767
+ refetch();
1768
+ }, [refetch]);
1769
+ return { data, isPending, error, refetch };
1770
+ };
1841
1771
  }
1842
- return {
1843
- success: true,
1844
- data: {
1845
- results: result.data.results,
1846
- total: result.data.total
1847
- }
1848
- };
1772
+ return client[prop];
1849
1773
  }
1850
- };
1774
+ });
1851
1775
  }
1852
1776
 
1853
1777
  // ../../sandpack-auth/dist/client/index.js
1854
- function isSandpackEnvironment() {
1778
+ function shouldUseBearerAuth2(authApiUrl) {
1855
1779
  if (typeof window === "undefined") {
1856
1780
  return false;
1857
1781
  }
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
1782
  try {
1865
- const inIframe = window.self !== window.top;
1866
- return inIframe;
1867
- } catch {
1868
- return true;
1783
+ const currentOrigin = window.location.origin;
1784
+ const authOrigin = new URL(authApiUrl).origin;
1785
+ const isCrossOrigin = currentOrigin !== authOrigin;
1786
+ if (isCrossOrigin) {
1787
+ console.log("[Sandpack Auth] Cross-origin detected:", {
1788
+ current: currentOrigin,
1789
+ auth: authOrigin
1790
+ });
1791
+ }
1792
+ return isCrossOrigin;
1793
+ } catch (error) {
1794
+ console.error("[Sandpack Auth] Failed to check origin:", error);
1795
+ return false;
1869
1796
  }
1870
1797
  }
1871
- function getStorageKey(projectId) {
1798
+ function getStorageKey2(projectId) {
1872
1799
  return `erikey.session.${projectId}`;
1873
1800
  }
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);
1801
+ function getStoredToken2(projectId) {
1802
+ const key = getStorageKey2(projectId);
1894
1803
  const stored = localStorage.getItem(key);
1895
1804
  if (!stored) {
1896
1805
  return null;
@@ -1909,33 +1818,26 @@ function getStoredToken(projectId) {
1909
1818
  return null;
1910
1819
  }
1911
1820
  }
1912
- function clearToken(projectId) {
1913
- const key = getStorageKey(projectId);
1914
- console.log("[Sandpack Auth] Clearing token from localStorage");
1915
- localStorage.removeItem(key);
1916
- }
1917
1821
 
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);
1822
+ // src/kv-client.ts
1823
+ function createKvClient(config) {
1824
+ const { projectId, baseUrl = "https://auth.erikey.com" } = config;
1825
+ const useBearerAuth = shouldUseBearerAuth2(baseUrl);
1826
+ const fetchWithAuth = async (endpoint, options) => {
1929
1827
  const headers = {
1930
1828
  "Content-Type": "application/json",
1931
1829
  "X-Project-Id": projectId,
1932
1830
  ...options?.headers || {}
1933
1831
  };
1934
- if (token) {
1935
- headers["Authorization"] = `Bearer ${token}`;
1832
+ if (useBearerAuth) {
1833
+ const token = getStoredToken2(projectId);
1834
+ if (token) {
1835
+ headers["Authorization"] = `Bearer ${token}`;
1836
+ }
1936
1837
  }
1937
1838
  const response = await fetch(`${baseUrl}/api/auth${endpoint}`, {
1938
1839
  ...options,
1840
+ credentials: useBearerAuth ? "omit" : "include",
1939
1841
  headers
1940
1842
  });
1941
1843
  const data = await response.json();
@@ -1951,66 +1853,20 @@ function createAuthClient3(config) {
1951
1853
  };
1952
1854
  };
1953
1855
  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 token = getStoredToken(projectId);
1987
- if (token) {
1988
- const response = await fetch(`${baseUrl}/api/auth/get-session`, {
1989
- headers: {
1990
- "Authorization": `Bearer ${token}`,
1991
- "X-Project-Id": projectId
1992
- }
1993
- });
1994
- const data = await response.json();
1995
- if (response.ok && (data?.user || data?.email)) {
1996
- return { success: true, data };
1997
- }
1998
- console.log("[Sandpack Auth] Bearer token invalid, clearing");
1999
- clearToken(projectId);
2000
- }
2001
- return { success: true, data: void 0 };
2002
- },
2003
- forgotPassword: client.forgotPassword,
2004
- resetPassword: client.resetPassword,
2005
- // KV methods - wrapped with Bearer token support for Sandpack
1856
+ /**
1857
+ * Set a single key-value pair
1858
+ */
2006
1859
  setValue: async (key, value) => {
2007
- return fetchWithBearer(`/key-value/${encodeURIComponent(key)}`, {
1860
+ return fetchWithAuth(`/key-value/${encodeURIComponent(key)}`, {
2008
1861
  method: "PUT",
2009
1862
  body: JSON.stringify({ value })
2010
1863
  });
2011
1864
  },
1865
+ /**
1866
+ * Get a single key-value pair
1867
+ */
2012
1868
  getValue: async (key) => {
2013
- const result = await fetchWithBearer(
1869
+ const result = await fetchWithAuth(
2014
1870
  `/key-value/${encodeURIComponent(key)}`,
2015
1871
  { method: "GET" }
2016
1872
  );
@@ -2027,8 +1883,11 @@ function createAuthClient3(config) {
2027
1883
  }
2028
1884
  };
2029
1885
  },
1886
+ /**
1887
+ * Get all key-value pairs for the authenticated user
1888
+ */
2030
1889
  getValues: async () => {
2031
- const result = await fetchWithBearer(
1890
+ const result = await fetchWithAuth(
2032
1891
  "/key-value",
2033
1892
  { method: "GET" }
2034
1893
  );
@@ -2043,8 +1902,11 @@ function createAuthClient3(config) {
2043
1902
  }
2044
1903
  };
2045
1904
  },
1905
+ /**
1906
+ * Delete a single key-value pair
1907
+ */
2046
1908
  deleteValue: async (key) => {
2047
- const result = await fetchWithBearer(
1909
+ const result = await fetchWithAuth(
2048
1910
  `/key-value/${encodeURIComponent(key)}`,
2049
1911
  { method: "DELETE" }
2050
1912
  );
@@ -2058,6 +1920,9 @@ function createAuthClient3(config) {
2058
1920
  }
2059
1921
  };
2060
1922
  },
1923
+ /**
1924
+ * Delete multiple key-value pairs
1925
+ */
2061
1926
  deleteValues: async (keys) => {
2062
1927
  if (keys.length === 0) {
2063
1928
  return {
@@ -2070,7 +1935,7 @@ function createAuthClient3(config) {
2070
1935
  }
2071
1936
  const results = await Promise.allSettled(
2072
1937
  keys.map(
2073
- (key) => fetchWithBearer(
1938
+ (key) => fetchWithAuth(
2074
1939
  `/key-value/${encodeURIComponent(key)}`,
2075
1940
  { method: "DELETE" }
2076
1941
  ).then((result) => ({ key, result }))
@@ -2104,8 +1969,11 @@ function createAuthClient3(config) {
2104
1969
  }
2105
1970
  };
2106
1971
  },
1972
+ /**
1973
+ * Set multiple key-value pairs in bulk (max 100 pairs)
1974
+ */
2107
1975
  setValues: async (kvPairs) => {
2108
- const result = await fetchWithBearer(
1976
+ const result = await fetchWithAuth(
2109
1977
  "/key-value/bulk",
2110
1978
  {
2111
1979
  method: "POST",
@@ -2126,7 +1994,8 @@ function createAuthClient3(config) {
2126
1994
  };
2127
1995
  }
2128
1996
  export {
2129
- createAuthClient3 as createAuthClient,
2130
- createDashboardClient
1997
+ createAuthClient2 as createAuthClient,
1998
+ createDashboardClient,
1999
+ createKvClient
2131
2000
  };
2132
2001
  //# sourceMappingURL=index.mjs.map