@every-app/sdk 0.0.5 → 0.0.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.
Files changed (40) hide show
  1. package/dist/client/EmbeddedAppProvider.d.ts +33 -0
  2. package/dist/client/EmbeddedAppProvider.d.ts.map +1 -0
  3. package/dist/client/EmbeddedAppProvider.js +55 -0
  4. package/dist/client/_internal/useEveryAppRouter.d.ts +9 -0
  5. package/dist/client/_internal/useEveryAppRouter.d.ts.map +1 -0
  6. package/dist/client/_internal/useEveryAppRouter.js +60 -0
  7. package/dist/client/_internal/useEveryAppSession.d.ts +15 -0
  8. package/dist/client/_internal/useEveryAppSession.d.ts.map +1 -0
  9. package/dist/client/_internal/useEveryAppSession.js +31 -0
  10. package/dist/client/authenticatedFetch.d.ts +12 -0
  11. package/dist/client/authenticatedFetch.d.ts.map +1 -0
  12. package/dist/client/authenticatedFetch.js +27 -0
  13. package/dist/client/index.d.ts +7 -0
  14. package/dist/client/index.d.ts.map +1 -0
  15. package/dist/client/index.js +5 -0
  16. package/dist/client/lazyInitForWorkers.d.ts +24 -0
  17. package/dist/client/lazyInitForWorkers.d.ts.map +1 -0
  18. package/dist/client/lazyInitForWorkers.js +68 -0
  19. package/dist/client/session-manager.d.ts +27 -0
  20. package/dist/client/session-manager.d.ts.map +1 -0
  21. package/dist/client/session-manager.js +141 -0
  22. package/dist/client/useSessionTokenClientMiddleware.d.ts +8 -0
  23. package/dist/client/useSessionTokenClientMiddleware.d.ts.map +1 -0
  24. package/dist/client/useSessionTokenClientMiddleware.js +24 -0
  25. package/dist/server/auth-config.d.ts +3 -0
  26. package/dist/server/auth-config.d.ts.map +1 -0
  27. package/dist/server/auth-config.js +7 -0
  28. package/dist/server/authenticateRequest.d.ts +26 -0
  29. package/dist/server/authenticateRequest.d.ts.map +1 -0
  30. package/dist/server/authenticateRequest.js +71 -0
  31. package/dist/server/getLocalD1Url.d.ts +2 -0
  32. package/dist/server/getLocalD1Url.d.ts.map +1 -0
  33. package/dist/server/getLocalD1Url.js +53 -0
  34. package/dist/server/index.d.ts +4 -0
  35. package/dist/server/index.d.ts.map +1 -0
  36. package/dist/server/index.js +2 -0
  37. package/dist/server/types.d.ts +5 -0
  38. package/dist/server/types.d.ts.map +1 -0
  39. package/dist/server/types.js +1 -0
  40. package/package.json +17 -5
@@ -0,0 +1,33 @@
1
+ import React from "react";
2
+ import { SessionManagerConfig } from "./session-manager";
3
+ interface EmbeddedProviderConfig extends SessionManagerConfig {
4
+ children: React.ReactNode;
5
+ }
6
+ export declare function EmbeddedAppProvider({
7
+ children,
8
+ ...config
9
+ }: EmbeddedProviderConfig): import("react/jsx-runtime").JSX.Element | null;
10
+ /**
11
+ * Hook to get the current authenticated user.
12
+ * Returns the user's ID and email extracted from the JWT token,
13
+ * or null if not authenticated.
14
+ *
15
+ * @example
16
+ * ```tsx
17
+ * function MyComponent() {
18
+ * const user = useCurrentUser();
19
+ *
20
+ * if (!user) {
21
+ * return <div>Not authenticated</div>;
22
+ * }
23
+ *
24
+ * return <div>Welcome, {user.email}</div>;
25
+ * }
26
+ * ```
27
+ */
28
+ export declare function useCurrentUser(): {
29
+ userId: string;
30
+ email: string;
31
+ } | null;
32
+ export {};
33
+ //# sourceMappingURL=EmbeddedAppProvider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EmbeddedAppProvider.d.ts","sourceRoot":"","sources":["../../src/client/EmbeddedAppProvider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAA6C,MAAM,OAAO,CAAC;AAClE,OAAO,EAAkB,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAIzE,UAAU,sBAAuB,SAAQ,oBAAoB;IAC3D,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;CAC3B;AAUD,wBAAgB,mBAAmB,CAAC,EAClC,QAAQ,EACR,GAAG,MAAM,EACV,EAAE,sBAAsB,kDAmBxB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,cAAc,IAAI;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAmBzE"}
@@ -0,0 +1,55 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext, useMemo } from "react";
3
+ import { useEveryAppSession } from "./_internal/useEveryAppSession";
4
+ import { useEveryAppRouter } from "./_internal/useEveryAppRouter";
5
+ const EmbeddedAppContext = createContext(null);
6
+ export function EmbeddedAppProvider({ children, ...config }) {
7
+ const { sessionManager, sessionTokenState } = useEveryAppSession({
8
+ sessionManagerConfig: config,
9
+ });
10
+ useEveryAppRouter({ sessionManager });
11
+ if (!sessionManager) return null;
12
+ const value = {
13
+ sessionManager,
14
+ isAuthenticated: sessionTokenState.status === "VALID",
15
+ sessionTokenState,
16
+ };
17
+ return _jsx(EmbeddedAppContext.Provider, {
18
+ value: value,
19
+ children: children,
20
+ });
21
+ }
22
+ /**
23
+ * Hook to get the current authenticated user.
24
+ * Returns the user's ID and email extracted from the JWT token,
25
+ * or null if not authenticated.
26
+ *
27
+ * @example
28
+ * ```tsx
29
+ * function MyComponent() {
30
+ * const user = useCurrentUser();
31
+ *
32
+ * if (!user) {
33
+ * return <div>Not authenticated</div>;
34
+ * }
35
+ *
36
+ * return <div>Welcome, {user.email}</div>;
37
+ * }
38
+ * ```
39
+ */
40
+ export function useCurrentUser() {
41
+ const context = useContext(EmbeddedAppContext);
42
+ if (!context) {
43
+ throw new Error(
44
+ "useCurrentUser must be used within an EmbeddedAppProvider",
45
+ );
46
+ }
47
+ const { sessionManager, sessionTokenState } = context;
48
+ return useMemo(() => {
49
+ // Only return user if we have a valid token
50
+ if (sessionTokenState.status !== "VALID") {
51
+ return null;
52
+ }
53
+ return sessionManager.getUser();
54
+ }, [sessionManager, sessionTokenState]);
55
+ }
@@ -0,0 +1,9 @@
1
+ import { SessionManager } from "../session-manager";
2
+ interface UseEveryAppRouterParams {
3
+ sessionManager: SessionManager | null;
4
+ }
5
+ export declare function useEveryAppRouter({
6
+ sessionManager,
7
+ }: UseEveryAppRouterParams): void;
8
+ export {};
9
+ //# sourceMappingURL=useEveryAppRouter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useEveryAppRouter.d.ts","sourceRoot":"","sources":["../../../src/client/_internal/useEveryAppRouter.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGpD,UAAU,uBAAuB;IAC/B,cAAc,EAAE,cAAc,GAAG,IAAI,CAAC;CACvC;AACD,wBAAgB,iBAAiB,CAAC,EAAE,cAAc,EAAE,EAAE,uBAAuB,QAmE5E"}
@@ -0,0 +1,60 @@
1
+ import { useEffect } from "react";
2
+ import { useRouter } from "@tanstack/react-router";
3
+ export function useEveryAppRouter({ sessionManager }) {
4
+ const router = useRouter();
5
+ // Route synchronization effect
6
+ useEffect(() => {
7
+ if (!sessionManager) return;
8
+ // Listen for route sync messages from parent
9
+ const handleMessage = (event) => {
10
+ if (event.origin !== sessionManager.parentOrigin) return;
11
+ if (
12
+ event.data.type === "ROUTE_CHANGE" &&
13
+ event.data.direction === "parent-to-child"
14
+ ) {
15
+ const targetRoute = event.data.route;
16
+ const currentRoute = window.location.pathname;
17
+ // Only navigate if the route is different from current location
18
+ if (targetRoute && targetRoute !== currentRoute) {
19
+ router.navigate({ to: targetRoute });
20
+ }
21
+ }
22
+ };
23
+ window.addEventListener("message", handleMessage);
24
+ // Simplified route change detection with 2 reliable methods
25
+ let lastReportedPath = window.location.pathname;
26
+ const handleRouteChange = () => {
27
+ const currentPath = window.location.pathname;
28
+ // Only report if the path actually changed
29
+ if (currentPath === lastReportedPath) {
30
+ return;
31
+ }
32
+ lastReportedPath = currentPath;
33
+ if (window.parent !== window) {
34
+ window.parent.postMessage(
35
+ {
36
+ type: "ROUTE_CHANGE",
37
+ route: currentPath,
38
+ appId: sessionManager.appId,
39
+ direction: "child-to-parent",
40
+ },
41
+ sessionManager.parentOrigin,
42
+ );
43
+ }
44
+ };
45
+ // Listen to popstate for browser back/forward
46
+ window.addEventListener("popstate", handleRouteChange);
47
+ // Polling to detect route changes (catches router navigation)
48
+ const pollInterval = setInterval(() => {
49
+ const currentPath = window.location.pathname;
50
+ if (currentPath !== lastReportedPath) {
51
+ handleRouteChange();
52
+ }
53
+ }, 100);
54
+ return () => {
55
+ window.removeEventListener("message", handleMessage);
56
+ window.removeEventListener("popstate", handleRouteChange);
57
+ clearInterval(pollInterval);
58
+ };
59
+ }, [sessionManager]);
60
+ }
@@ -0,0 +1,15 @@
1
+ import { SessionManager, SessionManagerConfig } from "../session-manager";
2
+ interface UseEveryAppSessionParams {
3
+ sessionManagerConfig: SessionManagerConfig;
4
+ }
5
+ export declare function useEveryAppSession({
6
+ sessionManagerConfig,
7
+ }: UseEveryAppSessionParams): {
8
+ sessionManager: SessionManager | null;
9
+ sessionTokenState: {
10
+ status: "NO_TOKEN" | "VALID" | "EXPIRED" | "REFRESHING";
11
+ token: string | null;
12
+ };
13
+ };
14
+ export {};
15
+ //# sourceMappingURL=useEveryAppSession.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useEveryAppSession.d.ts","sourceRoot":"","sources":["../../../src/client/_internal/useEveryAppSession.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE1E,UAAU,wBAAwB;IAChC,oBAAoB,EAAE,oBAAoB,CAAC;CAC5C;AAED,wBAAgB,kBAAkB,CAAC,EACjC,oBAAoB,GACrB,EAAE,wBAAwB;;;;;;EAsC1B"}
@@ -0,0 +1,31 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { SessionManager } from "../session-manager";
3
+ export function useEveryAppSession({ sessionManagerConfig }) {
4
+ const sessionManagerRef = useRef(null);
5
+ const [sessionTokenState, setSessionTokenState] = useState({
6
+ status: "NO_TOKEN",
7
+ token: null,
8
+ });
9
+ if (!sessionManagerRef.current && typeof document !== "undefined") {
10
+ sessionManagerRef.current = new SessionManager(sessionManagerConfig);
11
+ }
12
+ const sessionManager = sessionManagerRef.current;
13
+ useEffect(() => {
14
+ if (!sessionManager) return;
15
+ const interval = setInterval(() => {
16
+ setSessionTokenState(sessionManager.getTokenState());
17
+ }, 5000);
18
+ sessionManager.getToken().catch((err) => {
19
+ console.error("[EmbeddedProvider] Initial token request failed:", err);
20
+ });
21
+ return () => {
22
+ clearInterval(interval);
23
+ };
24
+ }, [sessionManager]);
25
+ useEffect(() => {
26
+ if (!sessionManager) return;
27
+ // Make sessionManager globally accessible for middleware
28
+ window.__embeddedSessionManager = sessionManager;
29
+ }, [sessionManager]);
30
+ return { sessionManager, sessionTokenState };
31
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Gets the current session token from the embedded session manager
3
+ */
4
+ export declare function getSessionToken(): Promise<string>;
5
+ /**
6
+ * Performs a fetch request with the authorization header automatically added
7
+ */
8
+ export declare function authenticatedFetch(
9
+ input: RequestInfo | URL,
10
+ init?: RequestInit,
11
+ ): Promise<Response>;
12
+ //# sourceMappingURL=authenticatedFetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authenticatedFetch.d.ts","sourceRoot":"","sources":["../../src/client/authenticatedFetch.ts"],"names":[],"mappings":"AAQA;;GAEG;AACH,wBAAsB,eAAe,IAAI,OAAO,CAAC,MAAM,CAAC,CAevD;AAED;;GAEG;AACH,wBAAsB,kBAAkB,CACtC,KAAK,EAAE,WAAW,GAAG,GAAG,EACxB,IAAI,CAAC,EAAE,WAAW,GACjB,OAAO,CAAC,QAAQ,CAAC,CAUnB"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Gets the current session token from the embedded session manager
3
+ */
4
+ export async function getSessionToken() {
5
+ const windowWithSession = window;
6
+ const sessionManager = windowWithSession.__embeddedSessionManager;
7
+ if (!sessionManager) {
8
+ throw new Error("Session manager not available");
9
+ }
10
+ const token = await sessionManager.getToken();
11
+ if (!token) {
12
+ throw new Error("No token available");
13
+ }
14
+ return token;
15
+ }
16
+ /**
17
+ * Performs a fetch request with the authorization header automatically added
18
+ */
19
+ export async function authenticatedFetch(input, init) {
20
+ const token = await getSessionToken();
21
+ const headers = new Headers(init?.headers);
22
+ headers.set("Authorization", `Bearer ${token}`);
23
+ return fetch(input, {
24
+ ...init,
25
+ headers,
26
+ });
27
+ }
@@ -0,0 +1,7 @@
1
+ export { SessionManager } from "./session-manager";
2
+ export type { SessionManagerConfig } from "./session-manager";
3
+ export { useSessionTokenClientMiddleware } from "./useSessionTokenClientMiddleware";
4
+ export { EmbeddedAppProvider, useCurrentUser } from "./EmbeddedAppProvider";
5
+ export { lazyInitForWorkers } from "./lazyInitForWorkers";
6
+ export { authenticatedFetch, getSessionToken } from "./authenticatedFetch";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,YAAY,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AAEpF,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { SessionManager } from "./session-manager";
2
+ export { useSessionTokenClientMiddleware } from "./useSessionTokenClientMiddleware";
3
+ export { EmbeddedAppProvider, useCurrentUser } from "./EmbeddedAppProvider";
4
+ export { lazyInitForWorkers } from "./lazyInitForWorkers";
5
+ export { authenticatedFetch, getSessionToken } from "./authenticatedFetch";
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Wraps a factory function in a Proxy to defer initialization until first access.
3
+ * This prevents async operations (Like creating Tanstack DB Collections) from running in Cloudflare Workers' global scope.
4
+ *
5
+ * @param factory - A function that creates and returns the resource.
6
+ * Must be a callback to defer execution; passing the value directly
7
+ * would evaluate it at module load time, triggering the Cloudflare error.
8
+ * @returns A Proxy that lazily initializes the resource on first property access
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * export const myCollection = lazyInitForWorkers(() =>
13
+ * createCollection(queryCollectionOptions({
14
+ * queryKey: ["myData"],
15
+ * queryFn: async () => fetchData(),
16
+ * // ... other options
17
+ * }))
18
+ * );
19
+ * ```
20
+ */
21
+ export declare function lazyInitForWorkers<T extends object>(
22
+ factory: () => T,
23
+ ): T;
24
+ //# sourceMappingURL=lazyInitForWorkers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lazyInitForWorkers.d.ts","sourceRoot":"","sources":["../../src/client/lazyInitForWorkers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,CA8CxE"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Wraps a factory function in a Proxy to defer initialization until first access.
3
+ * This prevents async operations (Like creating Tanstack DB Collections) from running in Cloudflare Workers' global scope.
4
+ *
5
+ * @param factory - A function that creates and returns the resource.
6
+ * Must be a callback to defer execution; passing the value directly
7
+ * would evaluate it at module load time, triggering the Cloudflare error.
8
+ * @returns A Proxy that lazily initializes the resource on first property access
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * export const myCollection = lazyInitForWorkers(() =>
13
+ * createCollection(queryCollectionOptions({
14
+ * queryKey: ["myData"],
15
+ * queryFn: async () => fetchData(),
16
+ * // ... other options
17
+ * }))
18
+ * );
19
+ * ```
20
+ */
21
+ export function lazyInitForWorkers(factory) {
22
+ // Closure: This variable is captured by getInstance() and the Proxy traps below.
23
+ // It remains in memory as long as the returned Proxy is referenced, enabling singleton behavior.
24
+ let instance = null;
25
+ function getInstance() {
26
+ if (!instance) {
27
+ instance = factory();
28
+ }
29
+ return instance;
30
+ }
31
+ return new Proxy(
32
+ {},
33
+ {
34
+ get(_, prop) {
35
+ const inst = getInstance();
36
+ const value = inst[prop];
37
+ // Bind methods to the instance to preserve `this` context
38
+ return typeof value === "function" ? value.bind(inst) : value;
39
+ },
40
+ set(_, prop, value) {
41
+ const inst = getInstance();
42
+ inst[prop] = value;
43
+ return true;
44
+ },
45
+ deleteProperty(_, prop) {
46
+ const inst = getInstance();
47
+ delete inst[prop];
48
+ return true;
49
+ },
50
+ has(_, prop) {
51
+ const inst = getInstance();
52
+ return prop in inst;
53
+ },
54
+ ownKeys(_) {
55
+ const inst = getInstance();
56
+ return Reflect.ownKeys(inst);
57
+ },
58
+ getOwnPropertyDescriptor(_, prop) {
59
+ const inst = getInstance();
60
+ return Reflect.getOwnPropertyDescriptor(inst, prop);
61
+ },
62
+ getPrototypeOf(_) {
63
+ const inst = getInstance();
64
+ return Reflect.getPrototypeOf(inst);
65
+ },
66
+ },
67
+ );
68
+ }
@@ -0,0 +1,27 @@
1
+ export interface SessionManagerConfig {
2
+ appId: string;
3
+ }
4
+ export declare class SessionManager {
5
+ readonly parentOrigin: string;
6
+ readonly appId: string;
7
+ private token;
8
+ private refreshPromise;
9
+ constructor(config: SessionManagerConfig);
10
+ private isTokenExpiringSoon;
11
+ private postMessageWithResponse;
12
+ requestNewToken(): Promise<string>;
13
+ getToken(): Promise<string>;
14
+ getTokenState(): {
15
+ status: "NO_TOKEN" | "VALID" | "EXPIRED" | "REFRESHING";
16
+ token: string | null;
17
+ };
18
+ /**
19
+ * Extracts user information from the current JWT token.
20
+ * Returns null if no valid token is available.
21
+ */
22
+ getUser(): {
23
+ userId: string;
24
+ email: string;
25
+ } | null;
26
+ }
27
+ //# sourceMappingURL=session-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-manager.d.ts","sourceRoot":"","sources":["../../src/client/session-manager.ts"],"names":[],"mappings":"AAWA,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,MAAM,CAAC;CACf;AAMD,qBAAa,cAAc;IACzB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAEvB,OAAO,CAAC,KAAK,CAA6B;IAC1C,OAAO,CAAC,cAAc,CAAgC;gBAE1C,MAAM,EAAE,oBAAoB;IAoBxC,OAAO,CAAC,mBAAmB;IAO3B,OAAO,CAAC,uBAAuB;IAuCzB,eAAe,IAAI,OAAO,CAAC,MAAM,CAAC;IA8ClC,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC;IAOjC,aAAa,IAAI;QACf,MAAM,EAAE,UAAU,GAAG,OAAO,GAAG,SAAS,GAAG,YAAY,CAAC;QACxD,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;KACtB;IAgBD;;;OAGG;IACH,OAAO,IAAI;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI;CAwBpD"}
@@ -0,0 +1,141 @@
1
+ const MESSAGE_TIMEOUT_MS = 5000;
2
+ const TOKEN_EXPIRY_BUFFER_MS = 10000;
3
+ const DEFAULT_TOKEN_LIFETIME_MS = 60000;
4
+ export class SessionManager {
5
+ parentOrigin;
6
+ appId;
7
+ token = null;
8
+ refreshPromise = null;
9
+ constructor(config) {
10
+ if (!config.appId) {
11
+ throw new Error("[SessionManager] appId is required.");
12
+ }
13
+ const gatewayUrl = import.meta.env.VITE_GATEWAY_URL;
14
+ if (!gatewayUrl) {
15
+ throw new Error("[SessionManager] VITE_GATEWAY_URL env var is required.");
16
+ }
17
+ try {
18
+ new URL(gatewayUrl);
19
+ } catch {
20
+ throw new Error(`[SessionManager] Invalid gateway URL: ${gatewayUrl}`);
21
+ }
22
+ this.appId = config.appId;
23
+ this.parentOrigin = gatewayUrl;
24
+ }
25
+ isTokenExpiringSoon(bufferMs = TOKEN_EXPIRY_BUFFER_MS) {
26
+ if (!this.token) return true;
27
+ return Date.now() >= this.token.expiresAt - bufferMs;
28
+ }
29
+ postMessageWithResponse(request, responseType, requestId) {
30
+ return new Promise((resolve, reject) => {
31
+ const cleanup = () => {
32
+ clearTimeout(timeout);
33
+ window.removeEventListener("message", handler);
34
+ };
35
+ const handler = (event) => {
36
+ // Security: reject messages from wrong origin (including null from sandboxed iframes)
37
+ if (event.origin !== this.parentOrigin) return;
38
+ // Safety: ignore malformed messages that could crash the handler
39
+ if (!event.data || typeof event.data !== "object") return;
40
+ if (
41
+ event.data.type === responseType &&
42
+ event.data.requestId === requestId
43
+ ) {
44
+ cleanup();
45
+ if (event.data.error) {
46
+ reject(new Error(event.data.error));
47
+ } else {
48
+ resolve(event.data);
49
+ }
50
+ }
51
+ };
52
+ const timeout = setTimeout(() => {
53
+ cleanup();
54
+ reject(new Error("Token request timeout - parent did not respond"));
55
+ }, MESSAGE_TIMEOUT_MS);
56
+ window.addEventListener("message", handler);
57
+ window.parent.postMessage(request, this.parentOrigin);
58
+ });
59
+ }
60
+ async requestNewToken() {
61
+ if (this.refreshPromise) {
62
+ return this.refreshPromise;
63
+ }
64
+ this.refreshPromise = (async () => {
65
+ const requestId = crypto.randomUUID();
66
+ const response = await this.postMessageWithResponse(
67
+ {
68
+ type: "SESSION_TOKEN_REQUEST",
69
+ requestId,
70
+ appId: this.appId,
71
+ },
72
+ "SESSION_TOKEN_RESPONSE",
73
+ requestId,
74
+ );
75
+ if (!response.token) {
76
+ throw new Error("No token in response");
77
+ }
78
+ // Parse expiresAt, falling back to default lifetime if invalid
79
+ let expiresAt = Date.now() + DEFAULT_TOKEN_LIFETIME_MS;
80
+ if (response.expiresAt) {
81
+ const parsed = new Date(response.expiresAt).getTime();
82
+ if (!Number.isNaN(parsed)) {
83
+ expiresAt = parsed;
84
+ }
85
+ }
86
+ this.token = {
87
+ token: response.token,
88
+ expiresAt,
89
+ };
90
+ return this.token.token;
91
+ })();
92
+ try {
93
+ return await this.refreshPromise;
94
+ } finally {
95
+ this.refreshPromise = null;
96
+ }
97
+ }
98
+ async getToken() {
99
+ if (this.isTokenExpiringSoon()) {
100
+ return this.requestNewToken();
101
+ }
102
+ return this.token.token;
103
+ }
104
+ getTokenState() {
105
+ if (this.refreshPromise) {
106
+ return { status: "REFRESHING", token: null };
107
+ }
108
+ if (!this.token) {
109
+ return { status: "NO_TOKEN", token: null };
110
+ }
111
+ if (this.isTokenExpiringSoon(0)) {
112
+ return { status: "EXPIRED", token: this.token.token };
113
+ }
114
+ return { status: "VALID", token: this.token.token };
115
+ }
116
+ /**
117
+ * Extracts user information from the current JWT token.
118
+ * Returns null if no valid token is available.
119
+ */
120
+ getUser() {
121
+ if (!this.token) {
122
+ return null;
123
+ }
124
+ try {
125
+ const parts = this.token.token.split(".");
126
+ if (parts.length !== 3) {
127
+ return null;
128
+ }
129
+ const payload = JSON.parse(atob(parts[1]));
130
+ if (!payload.sub) {
131
+ return null;
132
+ }
133
+ return {
134
+ userId: payload.sub,
135
+ email: payload.email ?? "",
136
+ };
137
+ } catch {
138
+ return null;
139
+ }
140
+ }
141
+ }
@@ -0,0 +1,8 @@
1
+ export declare const useSessionTokenClientMiddleware: import("@tanstack/react-start").FunctionMiddlewareAfterClient<
2
+ {},
3
+ unknown,
4
+ undefined,
5
+ undefined,
6
+ undefined
7
+ >;
8
+ //# sourceMappingURL=useSessionTokenClientMiddleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useSessionTokenClientMiddleware.d.ts","sourceRoot":"","sources":["../../src/client/useSessionTokenClientMiddleware.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,+BAA+B,6GA2B1C,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { createMiddleware } from "@tanstack/react-start";
2
+ export const useSessionTokenClientMiddleware = createMiddleware({
3
+ type: "function",
4
+ }).client(async ({ next }) => {
5
+ // Get the global sessionManager - this MUST be available for embedded apps
6
+ const sessionManager = window.__embeddedSessionManager;
7
+ if (!sessionManager) {
8
+ throw new Error(
9
+ "[AuthMiddleware] SessionManager not available - embedded provider not initialized",
10
+ );
11
+ }
12
+ // INVARIANT: This is just an extra check and should never be the case if the sessionManager exists.
13
+ if (typeof sessionManager.getToken !== "function") {
14
+ throw new Error(
15
+ "[AuthMiddleware] SessionManager.getToken is not a function",
16
+ );
17
+ }
18
+ const token = await sessionManager.getToken();
19
+ return next({
20
+ headers: {
21
+ Authorization: `Bearer ${token}`,
22
+ },
23
+ });
24
+ });
@@ -0,0 +1,3 @@
1
+ import type { AuthConfig } from "./types";
2
+ export declare function getAuthConfig(): AuthConfig;
3
+ //# sourceMappingURL=auth-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-config.d.ts","sourceRoot":"","sources":["../../src/server/auth-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAG1C,wBAAgB,aAAa,IAAI,UAAU,CAK1C"}
@@ -0,0 +1,7 @@
1
+ import { env } from "cloudflare:workers";
2
+ export function getAuthConfig() {
3
+ return {
4
+ issuer: env.GATEWAY_URL,
5
+ audience: import.meta.env.VITE_APP_ID,
6
+ };
7
+ }
@@ -0,0 +1,26 @@
1
+ import type { AuthConfig } from "./types";
2
+ interface SessionTokenPayload {
3
+ sub: string;
4
+ iss: string;
5
+ aud: string;
6
+ exp: number;
7
+ iat: number;
8
+ appId?: string;
9
+ permissions?: string[];
10
+ email?: string;
11
+ }
12
+ export declare function authenticateRequest(
13
+ authConfig: AuthConfig,
14
+ providedRequest?: Request,
15
+ ): Promise<SessionTokenPayload | null>;
16
+ /**
17
+ * Extracts the bearer token from an Authorization header.
18
+ *
19
+ * @param authHeader - The Authorization header value (e.g., "Bearer eyJ...")
20
+ * @returns The token string if valid, null otherwise
21
+ */
22
+ export declare function extractBearerToken(
23
+ authHeader: string | null,
24
+ ): string | null;
25
+ export {};
26
+ //# sourceMappingURL=authenticateRequest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authenticateRequest.d.ts","sourceRoot":"","sources":["../../src/server/authenticateRequest.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAG1C,UAAU,mBAAmB;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,wBAAsB,mBAAmB,CACvC,UAAU,EAAE,UAAU,EACtB,eAAe,CAAC,EAAE,OAAO,GACxB,OAAO,CAAC,mBAAmB,GAAG,IAAI,CAAC,CA+BrC;AAyCD;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CAK3E"}
@@ -0,0 +1,71 @@
1
+ import { getRequest } from "@tanstack/react-start/server";
2
+ import { createLocalJWKSet, jwtVerify } from "jose";
3
+ import { env } from "cloudflare:workers";
4
+ export async function authenticateRequest(authConfig, providedRequest) {
5
+ const request = providedRequest || getRequest();
6
+ const authHeader = request.headers.get("authorization");
7
+ if (!authHeader) {
8
+ console.log("No auth header found");
9
+ return null;
10
+ }
11
+ const token = extractBearerToken(authHeader);
12
+ if (!token) {
13
+ return null;
14
+ }
15
+ try {
16
+ const session = await verifySessionToken(token, authConfig);
17
+ return session;
18
+ } catch (error) {
19
+ console.error(
20
+ JSON.stringify({
21
+ message: "Error verifying session token",
22
+ error: error instanceof Error ? error.message : String(error),
23
+ stack: error instanceof Error ? error.stack : undefined,
24
+ errorType: error instanceof Error ? error.constructor.name : "Unknown",
25
+ issuer: authConfig.issuer,
26
+ audience: authConfig.audience,
27
+ }),
28
+ );
29
+ return null;
30
+ }
31
+ }
32
+ async function verifySessionToken(token, config) {
33
+ const { issuer, audience } = config;
34
+ if (!issuer) {
35
+ throw new Error("Issuer must be provided for token verification");
36
+ }
37
+ if (!audience) {
38
+ throw new Error("Audience must be provided for token verification");
39
+ }
40
+ // Fetch JWKS - use service binding in production, direct fetch in development
41
+ const jwksResponse =
42
+ import.meta.env.PROD && env.EVERY_APP_GATEWAY
43
+ ? await env.EVERY_APP_GATEWAY.fetch("http://localhost/api/embedded/jwks")
44
+ : await fetch(`${env.GATEWAY_URL}/api/embedded/jwks`);
45
+ if (!jwksResponse.ok) {
46
+ throw new Error(
47
+ `Failed to fetch JWKS: ${jwksResponse.status} ${jwksResponse.statusText}`,
48
+ );
49
+ }
50
+ const jwks = await jwksResponse.json();
51
+ const localJWKS = createLocalJWKSet(jwks);
52
+ const options = {
53
+ issuer,
54
+ audience,
55
+ algorithms: ["RS256"],
56
+ };
57
+ const { payload } = await jwtVerify(token, localJWKS, options);
58
+ return payload;
59
+ }
60
+ /**
61
+ * Extracts the bearer token from an Authorization header.
62
+ *
63
+ * @param authHeader - The Authorization header value (e.g., "Bearer eyJ...")
64
+ * @returns The token string if valid, null otherwise
65
+ */
66
+ export function extractBearerToken(authHeader) {
67
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
68
+ return null;
69
+ }
70
+ return authHeader.substring(7);
71
+ }
@@ -0,0 +1,2 @@
1
+ export declare function getLocalD1Url(): string | null;
2
+ //# sourceMappingURL=getLocalD1Url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getLocalD1Url.d.ts","sourceRoot":"","sources":["../../src/server/getLocalD1Url.ts"],"names":[],"mappings":"AAWA,wBAAgB,aAAa,kBAoD5B"}
@@ -0,0 +1,53 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { execSync } from "child_process";
4
+ import { parse } from "jsonc-parser";
5
+ function findSqliteFile(basePath) {
6
+ return fs
7
+ .readdirSync(basePath, { encoding: "utf-8", recursive: true })
8
+ .find((f) => f.endsWith(".sqlite"));
9
+ }
10
+ export function getLocalD1Url() {
11
+ const basePath = path.resolve(".wrangler");
12
+ // Check if .wrangler directory exists
13
+ if (!fs.existsSync(basePath)) {
14
+ console.error(
15
+ "================================================================================",
16
+ );
17
+ console.error("WARNING: .wrangler directory not found");
18
+ console.error("This is expected in CI/non-development environments.");
19
+ console.error(
20
+ "The local D1 database is only available after running 'wrangler dev' which you can trigger by running 'npm run dev'.",
21
+ );
22
+ console.error(
23
+ "================================================================================",
24
+ );
25
+ return null;
26
+ }
27
+ let dbFile = findSqliteFile(basePath);
28
+ if (!dbFile) {
29
+ // Read wrangler.jsonc to get the database name
30
+ const wranglerConfigPath = path.resolve("wrangler.jsonc");
31
+ const wranglerConfig = parse(fs.readFileSync(wranglerConfigPath, "utf-8"));
32
+ const databaseName = wranglerConfig.d1_databases?.[0]?.database_name;
33
+ if (!databaseName) {
34
+ throw new Error(
35
+ "Could not find database_name in wrangler.jsonc d1_databases configuration",
36
+ );
37
+ }
38
+ // Execute the command to initialize the local database
39
+ console.log(`Initializing local D1 database: ${databaseName}...`);
40
+ execSync(
41
+ `npx wrangler d1 execute ${databaseName} --local --command "SELECT 1;"`,
42
+ { stdio: "pipe" },
43
+ );
44
+ // Try to find the db file again after initialization
45
+ dbFile = findSqliteFile(basePath);
46
+ if (!dbFile) {
47
+ throw new Error(
48
+ `Failed to initialize local D1 database. The sqlite file was not created.`,
49
+ );
50
+ }
51
+ }
52
+ return path.resolve(basePath, dbFile);
53
+ }
@@ -0,0 +1,4 @@
1
+ export { authenticateRequest } from "./authenticateRequest";
2
+ export type { AuthConfig } from "./types";
3
+ export { getAuthConfig } from "./auth-config";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,YAAY,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { authenticateRequest } from "./authenticateRequest";
2
+ export { getAuthConfig } from "./auth-config";
@@ -0,0 +1,5 @@
1
+ export interface AuthConfig {
2
+ issuer: string;
3
+ audience: string;
4
+ }
5
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/server/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;CAClB"}
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,17 +1,29 @@
1
1
  {
2
2
  "name": "@every-app/sdk",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "type": "module",
5
- "main": "./src/client/index.ts",
5
+ "main": "./dist/client/index.js",
6
+ "types": "./dist/client/index.d.ts",
6
7
  "exports": {
7
- "./client": "./src/client/index.ts",
8
- "./server": "./src/server/index.ts",
9
- "./server/getLocalD1Url": "./src/server/getLocalD1Url.ts"
8
+ "./client": {
9
+ "types": "./dist/client/index.d.ts",
10
+ "default": "./dist/client/index.js"
11
+ },
12
+ "./server": {
13
+ "types": "./dist/server/index.d.ts",
14
+ "default": "./dist/server/index.js"
15
+ },
16
+ "./server/getLocalD1Url": {
17
+ "types": "./dist/server/getLocalD1Url.d.ts",
18
+ "default": "./dist/server/getLocalD1Url.js"
19
+ }
10
20
  },
11
21
  "files": [
22
+ "dist",
12
23
  "src"
13
24
  ],
14
25
  "scripts": {
26
+ "build": "tsc -p tsconfig.build.json",
15
27
  "types:check": "tsc --noEmit",
16
28
  "format:check": "prettier --check .",
17
29
  "format:write": "prettier . --write",