@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.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,193 @@ function createDashboardClient(config) {
1638
1639
  });
1639
1640
  }
1640
1641
 
1641
- // ../js/dist/index.js
1642
- var DEFAULT_BASE_URL = "https://auth.erikey.com";
1643
- 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
- };
1642
+ // src/auth-client.ts
1643
+ var import_react3 = require("react");
1644
+
1645
+ // src/lib/cross-origin-auth.ts
1646
+ function shouldUseBearerAuth(authApiUrl) {
1647
+ if (typeof window === "undefined") {
1648
+ return false;
1649
+ }
1650
+ try {
1651
+ const currentOrigin = window.location.origin;
1652
+ const authOrigin = new URL(authApiUrl).origin;
1653
+ return currentOrigin !== authOrigin;
1654
+ } catch {
1655
+ return false;
1656
+ }
1657
+ }
1658
+ function getStorageKey(projectId) {
1659
+ return `erikey.session.${projectId}`;
1660
+ }
1661
+ function storeToken(projectId, session) {
1662
+ if (typeof window === "undefined") return;
1663
+ const key = getStorageKey(projectId);
1664
+ localStorage.setItem(key, JSON.stringify(session));
1665
+ }
1666
+ function getStoredToken(projectId) {
1667
+ if (typeof window === "undefined") return null;
1668
+ const key = getStorageKey(projectId);
1669
+ const stored = localStorage.getItem(key);
1670
+ if (!stored) return null;
1671
+ try {
1672
+ const session = JSON.parse(stored);
1673
+ if (new Date(session.expiresAt) < /* @__PURE__ */ new Date()) {
1674
+ localStorage.removeItem(key);
1675
+ return null;
1663
1676
  }
1664
- return {
1665
- success: true,
1666
- data
1667
- };
1668
- };
1669
- 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
- });
1677
+ return session.token;
1678
+ } catch {
1679
+ localStorage.removeItem(key);
1680
+ return null;
1681
+ }
1682
+ }
1683
+ function clearToken(projectId) {
1684
+ if (typeof window === "undefined") return;
1685
+ const key = getStorageKey(projectId);
1686
+ localStorage.removeItem(key);
1687
+ }
1688
+
1689
+ // src/auth-client.ts
1690
+ function createAuthClient2(config) {
1691
+ const { projectId, baseUrl = "https://auth.erikey.com" } = config;
1692
+ const useBearerAuth = shouldUseBearerAuth(baseUrl);
1693
+ const fetchOptions = {
1694
+ // Always send project ID header for multi-tenant routing
1695
+ headers: {
1696
+ "X-Project-Id": projectId
1744
1697
  },
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 };
1698
+ // For cross-origin contexts, use Bearer token auth
1699
+ ...useBearerAuth && {
1700
+ auth: {
1701
+ type: "Bearer",
1702
+ token: () => getStoredToken(projectId) || ""
1755
1703
  }
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
1763
- }
1764
- };
1765
- },
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 };
1704
+ }
1705
+ };
1706
+ const client = createAuthClient({
1707
+ baseURL: baseUrl,
1708
+ fetchOptions,
1709
+ // For same-origin, include cookies
1710
+ ...!useBearerAuth && { credentials: "include" }
1711
+ });
1712
+ if (!useBearerAuth) {
1713
+ return client;
1714
+ }
1715
+ return new Proxy({}, {
1716
+ get(_target, prop) {
1717
+ if (typeof prop === "symbol") {
1718
+ return client[prop];
1776
1719
  }
1777
- return {
1778
- success: true,
1779
- data: {
1780
- kvPairs: result.data.kvPairs,
1781
- total: result.data.total
1782
- }
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 };
1720
+ if (prop === "signIn") {
1721
+ return new Proxy(client.signIn, {
1722
+ get(_signInTarget, signInProp) {
1723
+ if (signInProp === "email") {
1724
+ return async (...args) => {
1725
+ const result = await client.signIn.email(...args);
1726
+ const token = result.data?.token;
1727
+ if (token) {
1728
+ const session = {
1729
+ id: result.data?.session?.id || "session",
1730
+ token,
1731
+ expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString()
1732
+ };
1733
+ storeToken(projectId, session);
1734
+ }
1735
+ return result;
1736
+ };
1737
+ }
1738
+ return client.signIn[signInProp];
1739
+ }
1740
+ });
1795
1741
  }
1796
- return {
1797
- success: true,
1798
- data: {
1799
- message: result.data.message || "KV pair deleted"
1800
- }
1801
- };
1802
- },
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: []
1742
+ if (prop === "signUp") {
1743
+ return new Proxy(client.signUp, {
1744
+ get(_signUpTarget, signUpProp) {
1745
+ if (signUpProp === "email") {
1746
+ return async (...args) => {
1747
+ const result = await client.signUp.email(...args);
1748
+ const token = result.data?.token;
1749
+ if (token) {
1750
+ const session = {
1751
+ id: result.data?.session?.id || "session",
1752
+ token,
1753
+ expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString()
1754
+ };
1755
+ storeToken(projectId, session);
1756
+ }
1757
+ return result;
1758
+ };
1759
+ }
1760
+ return client.signUp[signUpProp];
1814
1761
  }
1762
+ });
1763
+ }
1764
+ if (prop === "signOut") {
1765
+ return async (...args) => {
1766
+ clearToken(projectId);
1767
+ return client.signOut(...args);
1815
1768
  };
1816
1769
  }
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
- };
1852
- },
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 };
1770
+ if (prop === "useSession") {
1771
+ return function useSession() {
1772
+ const [data, setData] = (0, import_react3.useState)(null);
1773
+ const [isPending, setIsPending] = (0, import_react3.useState)(true);
1774
+ const [error, setError] = (0, import_react3.useState)(null);
1775
+ const refetch = (0, import_react3.useCallback)(async () => {
1776
+ setIsPending(true);
1777
+ try {
1778
+ const result = await client.getSession();
1779
+ if (result.error) {
1780
+ setError(result.error);
1781
+ setData(null);
1782
+ } else {
1783
+ setData(result.data);
1784
+ setError(null);
1785
+ }
1786
+ } catch (e) {
1787
+ setError(e);
1788
+ setData(null);
1789
+ }
1790
+ setIsPending(false);
1791
+ }, []);
1792
+ (0, import_react3.useEffect)(() => {
1793
+ refetch();
1794
+ }, [refetch]);
1795
+ return { data, isPending, error, refetch };
1796
+ };
1866
1797
  }
1867
- return {
1868
- success: true,
1869
- data: {
1870
- results: result.data.results,
1871
- total: result.data.total
1872
- }
1873
- };
1798
+ return client[prop];
1874
1799
  }
1875
- };
1800
+ });
1876
1801
  }
1877
1802
 
1878
1803
  // ../../sandpack-auth/dist/client/index.js
1879
- function isSandpackEnvironment() {
1804
+ function shouldUseBearerAuth2(authApiUrl) {
1880
1805
  if (typeof window === "undefined") {
1881
1806
  return false;
1882
1807
  }
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
1808
  try {
1890
- const inIframe = window.self !== window.top;
1891
- return inIframe;
1892
- } catch {
1893
- return true;
1809
+ const currentOrigin = window.location.origin;
1810
+ const authOrigin = new URL(authApiUrl).origin;
1811
+ const isCrossOrigin = currentOrigin !== authOrigin;
1812
+ if (isCrossOrigin) {
1813
+ console.log("[Sandpack Auth] Cross-origin detected:", {
1814
+ current: currentOrigin,
1815
+ auth: authOrigin
1816
+ });
1817
+ }
1818
+ return isCrossOrigin;
1819
+ } catch (error) {
1820
+ console.error("[Sandpack Auth] Failed to check origin:", error);
1821
+ return false;
1894
1822
  }
1895
1823
  }
1896
- function getStorageKey(projectId) {
1824
+ function getStorageKey2(projectId) {
1897
1825
  return `erikey.session.${projectId}`;
1898
1826
  }
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);
1827
+ function getStoredToken2(projectId) {
1828
+ const key = getStorageKey2(projectId);
1919
1829
  const stored = localStorage.getItem(key);
1920
1830
  if (!stored) {
1921
1831
  return null;
@@ -1934,33 +1844,26 @@ function getStoredToken(projectId) {
1934
1844
  return null;
1935
1845
  }
1936
1846
  }
1937
- function clearToken(projectId) {
1938
- const key = getStorageKey(projectId);
1939
- console.log("[Sandpack Auth] Clearing token from localStorage");
1940
- localStorage.removeItem(key);
1941
- }
1942
1847
 
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);
1848
+ // src/kv-client.ts
1849
+ function createKvClient(config) {
1850
+ const { projectId, baseUrl = "https://auth.erikey.com" } = config;
1851
+ const useBearerAuth = shouldUseBearerAuth2(baseUrl);
1852
+ const fetchWithAuth = async (endpoint, options) => {
1954
1853
  const headers = {
1955
1854
  "Content-Type": "application/json",
1956
1855
  "X-Project-Id": projectId,
1957
1856
  ...options?.headers || {}
1958
1857
  };
1959
- if (token) {
1960
- headers["Authorization"] = `Bearer ${token}`;
1858
+ if (useBearerAuth) {
1859
+ const token = getStoredToken2(projectId);
1860
+ if (token) {
1861
+ headers["Authorization"] = `Bearer ${token}`;
1862
+ }
1961
1863
  }
1962
1864
  const response = await fetch(`${baseUrl}/api/auth${endpoint}`, {
1963
1865
  ...options,
1866
+ credentials: useBearerAuth ? "omit" : "include",
1964
1867
  headers
1965
1868
  });
1966
1869
  const data = await response.json();
@@ -1976,66 +1879,20 @@ function createAuthClient3(config) {
1976
1879
  };
1977
1880
  };
1978
1881
  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 token = getStoredToken(projectId);
2012
- if (token) {
2013
- const response = await fetch(`${baseUrl}/api/auth/get-session`, {
2014
- headers: {
2015
- "Authorization": `Bearer ${token}`,
2016
- "X-Project-Id": projectId
2017
- }
2018
- });
2019
- const data = await response.json();
2020
- if (response.ok && (data?.user || data?.email)) {
2021
- return { success: true, data };
2022
- }
2023
- console.log("[Sandpack Auth] Bearer token invalid, clearing");
2024
- clearToken(projectId);
2025
- }
2026
- return { success: true, data: void 0 };
2027
- },
2028
- forgotPassword: client.forgotPassword,
2029
- resetPassword: client.resetPassword,
2030
- // KV methods - wrapped with Bearer token support for Sandpack
1882
+ /**
1883
+ * Set a single key-value pair
1884
+ */
2031
1885
  setValue: async (key, value) => {
2032
- return fetchWithBearer(`/key-value/${encodeURIComponent(key)}`, {
1886
+ return fetchWithAuth(`/key-value/${encodeURIComponent(key)}`, {
2033
1887
  method: "PUT",
2034
1888
  body: JSON.stringify({ value })
2035
1889
  });
2036
1890
  },
1891
+ /**
1892
+ * Get a single key-value pair
1893
+ */
2037
1894
  getValue: async (key) => {
2038
- const result = await fetchWithBearer(
1895
+ const result = await fetchWithAuth(
2039
1896
  `/key-value/${encodeURIComponent(key)}`,
2040
1897
  { method: "GET" }
2041
1898
  );
@@ -2052,8 +1909,11 @@ function createAuthClient3(config) {
2052
1909
  }
2053
1910
  };
2054
1911
  },
1912
+ /**
1913
+ * Get all key-value pairs for the authenticated user
1914
+ */
2055
1915
  getValues: async () => {
2056
- const result = await fetchWithBearer(
1916
+ const result = await fetchWithAuth(
2057
1917
  "/key-value",
2058
1918
  { method: "GET" }
2059
1919
  );
@@ -2068,8 +1928,11 @@ function createAuthClient3(config) {
2068
1928
  }
2069
1929
  };
2070
1930
  },
1931
+ /**
1932
+ * Delete a single key-value pair
1933
+ */
2071
1934
  deleteValue: async (key) => {
2072
- const result = await fetchWithBearer(
1935
+ const result = await fetchWithAuth(
2073
1936
  `/key-value/${encodeURIComponent(key)}`,
2074
1937
  { method: "DELETE" }
2075
1938
  );
@@ -2083,6 +1946,9 @@ function createAuthClient3(config) {
2083
1946
  }
2084
1947
  };
2085
1948
  },
1949
+ /**
1950
+ * Delete multiple key-value pairs
1951
+ */
2086
1952
  deleteValues: async (keys) => {
2087
1953
  if (keys.length === 0) {
2088
1954
  return {
@@ -2095,7 +1961,7 @@ function createAuthClient3(config) {
2095
1961
  }
2096
1962
  const results = await Promise.allSettled(
2097
1963
  keys.map(
2098
- (key) => fetchWithBearer(
1964
+ (key) => fetchWithAuth(
2099
1965
  `/key-value/${encodeURIComponent(key)}`,
2100
1966
  { method: "DELETE" }
2101
1967
  ).then((result) => ({ key, result }))
@@ -2129,8 +1995,11 @@ function createAuthClient3(config) {
2129
1995
  }
2130
1996
  };
2131
1997
  },
1998
+ /**
1999
+ * Set multiple key-value pairs in bulk (max 100 pairs)
2000
+ */
2132
2001
  setValues: async (kvPairs) => {
2133
- const result = await fetchWithBearer(
2002
+ const result = await fetchWithAuth(
2134
2003
  "/key-value/bulk",
2135
2004
  {
2136
2005
  method: "POST",
@@ -2153,6 +2022,7 @@ function createAuthClient3(config) {
2153
2022
  // Annotate the CommonJS export names for ESM import in node:
2154
2023
  0 && (module.exports = {
2155
2024
  createAuthClient,
2156
- createDashboardClient
2025
+ createDashboardClient,
2026
+ createKvClient
2157
2027
  });
2158
2028
  //# sourceMappingURL=index.js.map