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