@eventuras/fides-auth-next 0.6.0 → 0.7.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/cookies.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { cookies } from "next/headers";
2
- import { Logger } from "@eventuras/logger";
2
+ import { createLogger } from "@eventuras/fides-auth/logger";
3
3
  import { ACCESS_TOKEN_COOKIE_NAME, ACCESS_TOKEN_COOKIE_NAME as ACCESS_TOKEN_COOKIE_NAME$1, COOKIE_INFO_BYTES, COOKIE_INFO_BYTES as COOKIE_INFO_BYTES$1, COOKIE_MAX_BYTES, CookieTooLargeError, ID_TOKEN_COOKIE_NAME, assertCookieWithinLimit, assertCookieWithinLimit as assertCookieWithinLimit$1, cookieByteSize, defaultOAuthCookieOptions, defaultSessionCookieOptions, defaultSessionCookieOptions as defaultSessionCookieOptions$1 } from "@eventuras/fides-auth/cookies";
4
4
  //#region src/cookies.ts
5
5
  /**
@@ -15,7 +15,7 @@ import { ACCESS_TOKEN_COOKIE_NAME, ACCESS_TOKEN_COOKIE_NAME as ACCESS_TOKEN_COOK
15
15
  * - Middleware (use NextResponse.cookies instead)
16
16
  * - Edge Runtime without proper configuration
17
17
  */
18
- var logger = Logger.create({ namespace: "fides-auth-next:cookies" });
18
+ var logger = createLogger({ namespace: "fides-auth-next:cookies" });
19
19
  /**
20
20
  * Sets a cookie with the given name and value.
21
21
  *
@@ -1 +1 @@
1
- {"version":3,"file":"cookies.js","names":[],"sources":["../src/cookies.ts"],"sourcesContent":["/**\n * Cookie helpers for Next.js authentication flows.\n *\n * IMPORTANT: These functions can ONLY be used in:\n * - Server Actions (functions marked with 'use server')\n * - Route Handlers (files in app/api directory)\n * - Server Components (async React components)\n *\n * They CANNOT be used in:\n * - Client Components (marked with 'use client')\n * - Middleware (use NextResponse.cookies instead)\n * - Edge Runtime without proper configuration\n */\n\nimport {\n ACCESS_TOKEN_COOKIE_NAME,\n COOKIE_INFO_BYTES,\n assertCookieWithinLimit,\n defaultSessionCookieOptions,\n} from '@eventuras/fides-auth/cookies';\nimport type { CookieOptions } from '@eventuras/fides-auth/cookies';\nimport { Logger } from '@eventuras/logger';\nimport { cookies } from 'next/headers';\n\n// Re-export the framework-agnostic cookie attributes, limits, and size guard from\n// the core package so existing import sites keep working. This Next adapter only\n// owns the actual cookie I/O (via next/headers); the values and the size check\n// itself live in @eventuras/fides-auth/cookies.\nexport {\n COOKIE_INFO_BYTES,\n COOKIE_MAX_BYTES,\n CookieTooLargeError,\n ACCESS_TOKEN_COOKIE_NAME,\n ID_TOKEN_COOKIE_NAME,\n defaultSessionCookieOptions,\n defaultOAuthCookieOptions,\n cookieByteSize,\n assertCookieWithinLimit,\n} from '@eventuras/fides-auth/cookies';\nexport type { CookieOptions } from '@eventuras/fides-auth/cookies';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:cookies' });\n\n/**\n * Sets a cookie with the given name and value.\n *\n * @param name - Cookie name\n * @param value - Cookie value\n * @param options - Cookie options (defaults to session cookie options)\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await setAuthCookie('session', encryptedJwt);\n *\n * // With custom options\n * await setAuthCookie('oauth_state', state, {\n * maxAge: 60 * 10, // 10 minutes\n * });\n * ```\n */\nexport async function setAuthCookie(\n name: string,\n value: string,\n options: CookieOptions = defaultSessionCookieOptions\n): Promise<void> {\n try {\n const cookieStore = await cookies();\n const cookieOptions = { ...defaultSessionCookieOptions, ...options };\n\n // Fail loudly above the browser per-cookie limit (the browser would otherwise\n // drop the cookie silently). The size check lives in the core package.\n const size = assertCookieWithinLimit(name, value);\n if (size >= COOKIE_INFO_BYTES) {\n logger.info({ cookieName: name, size }, 'Cookie approaching browser size limit');\n }\n\n cookieStore.set(name, value, cookieOptions);\n\n logger.debug({\n cookieName: name,\n maxAge: cookieOptions.maxAge,\n secure: cookieOptions.secure\n }, 'Cookie set successfully');\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to set cookie');\n throw error;\n }\n}\n\n/**\n * Gets a cookie value by name.\n *\n * @param name - Cookie name\n * @returns Cookie value or null if not found\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * const sessionCookie = await getAuthCookie('session');\n * if (sessionCookie) {\n * // Validate and use session\n * }\n * ```\n */\nexport async function getAuthCookie(name: string): Promise<string | null> {\n try {\n const cookieStore = await cookies();\n const cookie = cookieStore.get(name);\n\n if (!cookie?.value) {\n logger.debug({ cookieName: name }, 'Cookie not found');\n return null;\n }\n\n logger.debug({ cookieName: name }, 'Cookie retrieved');\n return cookie.value;\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to get cookie');\n return null;\n }\n}\n\n/**\n * Deletes a cookie by name.\n *\n * @param name - Cookie name to delete\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await deleteAuthCookie('session');\n * ```\n */\nexport async function deleteAuthCookie(name: string): Promise<void> {\n try {\n const cookieStore = await cookies();\n cookieStore.delete(name);\n\n logger.debug({ cookieName: name }, 'Cookie deleted successfully');\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to delete cookie');\n throw error;\n }\n}\n\n/**\n * Deletes multiple cookies at once.\n * Useful for cleaning up OAuth flow cookies.\n *\n * @param names - Array of cookie names to delete\n *\n * @example\n * ```ts\n * // Clean up OAuth cookies after callback\n * await deleteAuthCookies(['oauth_state', 'oauth_code_verifier', 'returnTo']);\n * ```\n */\nexport async function deleteAuthCookies(names: string[]): Promise<void> {\n try {\n const cookieStore = await cookies();\n\n for (const name of names) {\n cookieStore.delete(name);\n }\n\n logger.debug({ cookieNames: names }, 'Multiple cookies deleted successfully');\n } catch (error) {\n logger.error({ error, cookieNames: names }, 'Failed to delete cookies');\n throw error;\n }\n}\n\n/**\n * Sets the session cookie with proper security settings.\n * This is a convenience wrapper around setAuthCookie.\n *\n * @param encryptedJwt - The encrypted JWT session token\n * @param options - Optional cookie options (merged with defaults)\n *\n * @example\n * ```ts\n * const jwt = await createSession({ ... });\n * await setSessionCookie(jwt);\n * ```\n */\nexport async function setSessionCookie(\n encryptedJwt: string,\n options: Partial<CookieOptions> = {}\n): Promise<void> {\n await setAuthCookie('session', encryptedJwt, {\n ...defaultSessionCookieOptions,\n ...options,\n });\n\n logger.info('Session cookie set');\n}\n\n/**\n * Sets the access-token cookie (\"session_at\") with session cookie settings.\n *\n * @param encryptedJwt - The encrypted JWT wrapping the access token\n * @param options - Optional cookie options (merged with session defaults)\n */\nexport async function setAccessTokenCookie(\n encryptedJwt: string,\n options: Partial<CookieOptions> = {}\n): Promise<void> {\n await setAuthCookie(ACCESS_TOKEN_COOKIE_NAME, encryptedJwt, {\n ...defaultSessionCookieOptions,\n ...options,\n });\n}\n\n/**\n * Gets the access-token cookie (\"session_at\") value, or null if absent.\n */\nexport async function getAccessTokenCookie(): Promise<string | null> {\n return await getAuthCookie(ACCESS_TOKEN_COOKIE_NAME);\n}\n\n/**\n * Deletes the access-token cookie (\"session_at\").\n */\nexport async function deleteAccessTokenCookie(): Promise<void> {\n await deleteAuthCookie(ACCESS_TOKEN_COOKIE_NAME);\n}\n\n/**\n * Gets the current session cookie value.\n * Returns null if no session cookie exists.\n *\n * @returns Encrypted JWT session token or null\n *\n * @example\n * ```ts\n * const sessionToken = await getSessionCookie();\n * if (sessionToken) {\n * const { status, session } = await validateSessionJwt(sessionToken);\n * // ...\n * }\n * ```\n */\nexport async function getSessionCookie(): Promise<string | null> {\n return await getAuthCookie('session');\n}\n\n/**\n * Deletes the session cookie.\n * Use this when logging out or when session validation fails.\n *\n * @example\n * ```ts\n * await deleteSessionCookie();\n * redirect('/');\n * ```\n */\nexport async function deleteSessionCookie(): Promise<void> {\n await deleteAuthCookie('session');\n logger.info('Session cookie deleted');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyCA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,0BAA0B,CAAC;;;;;;;;;;;;;;;;;;;AAoBrE,eAAsB,cACpB,MACA,OACA,UAAyB,6BACV;CACf,IAAI;EACF,MAAM,c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,OAAO;EACd,OAAO,MAAM;GAAE;GAAO,aAAa;EAAM,GAAG,0BAA0B;EACtE,MAAM;CACR;AACF;;;;;;;;;;;;;;AAeA,eAAsB,iBACpB,cACA,UAAkC,CAAC,GACpB;CACf,MAAM,cAAc,WAAW,cAAc;EAC3C,GAAG;EACH,GAAG;CACL,CAAC;CAED,OAAO,KAAK,oBAAoB;AAClC;;;;;;;AAQA,eAAsB,qBACpB,cACA,UAAkC,CAAC,GACpB;CACf,MAAM,cAAc,0BAA0B,cAAc;EAC1D,GAAG;EACH,GAAG;CACL,CAAC;AACH;;;;AAKA,eAAsB,uBAA+C;CACnE,OAAO,MAAM,cAAc,wBAAwB;AACrD;;;;AAKA,eAAsB,0BAAyC;CAC7D,MAAM,iBAAiB,wBAAwB;AACjD;;;;;;;;;;;;;;;;AAiBA,eAAsB,mBAA2C;CAC/D,OAAO,MAAM,cAAc,SAAS;AACtC;;;;;;;;;;;AAYA,eAAsB,sBAAqC;CACzD,MAAM,iBAAiB,SAAS;CAChC,OAAO,KAAK,wBAAwB;AACtC"}
1
+ {"version":3,"file":"cookies.js","names":[],"sources":["../src/cookies.ts"],"sourcesContent":["/**\n * Cookie helpers for Next.js authentication flows.\n *\n * IMPORTANT: These functions can ONLY be used in:\n * - Server Actions (functions marked with 'use server')\n * - Route Handlers (files in app/api directory)\n * - Server Components (async React components)\n *\n * They CANNOT be used in:\n * - Client Components (marked with 'use client')\n * - Middleware (use NextResponse.cookies instead)\n * - Edge Runtime without proper configuration\n */\n\nimport {\n ACCESS_TOKEN_COOKIE_NAME,\n COOKIE_INFO_BYTES,\n assertCookieWithinLimit,\n defaultSessionCookieOptions,\n} from '@eventuras/fides-auth/cookies';\nimport type { CookieOptions } from '@eventuras/fides-auth/cookies';\nimport { createLogger } from '@eventuras/fides-auth/logger';\nimport { cookies } from 'next/headers';\n\n// Re-export the framework-agnostic cookie attributes, limits, and size guard from\n// the core package so existing import sites keep working. This Next adapter only\n// owns the actual cookie I/O (via next/headers); the values and the size check\n// itself live in @eventuras/fides-auth/cookies.\nexport {\n COOKIE_INFO_BYTES,\n COOKIE_MAX_BYTES,\n CookieTooLargeError,\n ACCESS_TOKEN_COOKIE_NAME,\n ID_TOKEN_COOKIE_NAME,\n defaultSessionCookieOptions,\n defaultOAuthCookieOptions,\n cookieByteSize,\n assertCookieWithinLimit,\n} from '@eventuras/fides-auth/cookies';\nexport type { CookieOptions } from '@eventuras/fides-auth/cookies';\n\nconst logger = createLogger({ namespace: 'fides-auth-next:cookies' });\n\n/**\n * Sets a cookie with the given name and value.\n *\n * @param name - Cookie name\n * @param value - Cookie value\n * @param options - Cookie options (defaults to session cookie options)\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await setAuthCookie('session', encryptedJwt);\n *\n * // With custom options\n * await setAuthCookie('oauth_state', state, {\n * maxAge: 60 * 10, // 10 minutes\n * });\n * ```\n */\nexport async function setAuthCookie(\n name: string,\n value: string,\n options: CookieOptions = defaultSessionCookieOptions\n): Promise<void> {\n try {\n const cookieStore = await cookies();\n const cookieOptions = { ...defaultSessionCookieOptions, ...options };\n\n // Fail loudly above the browser per-cookie limit (the browser would otherwise\n // drop the cookie silently). The size check lives in the core package.\n const size = assertCookieWithinLimit(name, value);\n if (size >= COOKIE_INFO_BYTES) {\n logger.info({ cookieName: name, size }, 'Cookie approaching browser size limit');\n }\n\n cookieStore.set(name, value, cookieOptions);\n\n logger.debug({\n cookieName: name,\n maxAge: cookieOptions.maxAge,\n secure: cookieOptions.secure\n }, 'Cookie set successfully');\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to set cookie');\n throw error;\n }\n}\n\n/**\n * Gets a cookie value by name.\n *\n * @param name - Cookie name\n * @returns Cookie value or null if not found\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * const sessionCookie = await getAuthCookie('session');\n * if (sessionCookie) {\n * // Validate and use session\n * }\n * ```\n */\nexport async function getAuthCookie(name: string): Promise<string | null> {\n try {\n const cookieStore = await cookies();\n const cookie = cookieStore.get(name);\n\n if (!cookie?.value) {\n logger.debug({ cookieName: name }, 'Cookie not found');\n return null;\n }\n\n logger.debug({ cookieName: name }, 'Cookie retrieved');\n return cookie.value;\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to get cookie');\n return null;\n }\n}\n\n/**\n * Deletes a cookie by name.\n *\n * @param name - Cookie name to delete\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await deleteAuthCookie('session');\n * ```\n */\nexport async function deleteAuthCookie(name: string): Promise<void> {\n try {\n const cookieStore = await cookies();\n cookieStore.delete(name);\n\n logger.debug({ cookieName: name }, 'Cookie deleted successfully');\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to delete cookie');\n throw error;\n }\n}\n\n/**\n * Deletes multiple cookies at once.\n * Useful for cleaning up OAuth flow cookies.\n *\n * @param names - Array of cookie names to delete\n *\n * @example\n * ```ts\n * // Clean up OAuth cookies after callback\n * await deleteAuthCookies(['oauth_state', 'oauth_code_verifier', 'returnTo']);\n * ```\n */\nexport async function deleteAuthCookies(names: string[]): Promise<void> {\n try {\n const cookieStore = await cookies();\n\n for (const name of names) {\n cookieStore.delete(name);\n }\n\n logger.debug({ cookieNames: names }, 'Multiple cookies deleted successfully');\n } catch (error) {\n logger.error({ error, cookieNames: names }, 'Failed to delete cookies');\n throw error;\n }\n}\n\n/**\n * Sets the session cookie with proper security settings.\n * This is a convenience wrapper around setAuthCookie.\n *\n * @param encryptedJwt - The encrypted JWT session token\n * @param options - Optional cookie options (merged with defaults)\n *\n * @example\n * ```ts\n * const jwt = await createSession({ ... });\n * await setSessionCookie(jwt);\n * ```\n */\nexport async function setSessionCookie(\n encryptedJwt: string,\n options: Partial<CookieOptions> = {}\n): Promise<void> {\n await setAuthCookie('session', encryptedJwt, {\n ...defaultSessionCookieOptions,\n ...options,\n });\n\n logger.info('Session cookie set');\n}\n\n/**\n * Sets the access-token cookie (\"session_at\") with session cookie settings.\n *\n * @param encryptedJwt - The encrypted JWT wrapping the access token\n * @param options - Optional cookie options (merged with session defaults)\n */\nexport async function setAccessTokenCookie(\n encryptedJwt: string,\n options: Partial<CookieOptions> = {}\n): Promise<void> {\n await setAuthCookie(ACCESS_TOKEN_COOKIE_NAME, encryptedJwt, {\n ...defaultSessionCookieOptions,\n ...options,\n });\n}\n\n/**\n * Gets the access-token cookie (\"session_at\") value, or null if absent.\n */\nexport async function getAccessTokenCookie(): Promise<string | null> {\n return await getAuthCookie(ACCESS_TOKEN_COOKIE_NAME);\n}\n\n/**\n * Deletes the access-token cookie (\"session_at\").\n */\nexport async function deleteAccessTokenCookie(): Promise<void> {\n await deleteAuthCookie(ACCESS_TOKEN_COOKIE_NAME);\n}\n\n/**\n * Gets the current session cookie value.\n * Returns null if no session cookie exists.\n *\n * @returns Encrypted JWT session token or null\n *\n * @example\n * ```ts\n * const sessionToken = await getSessionCookie();\n * if (sessionToken) {\n * const { status, session } = await validateSessionJwt(sessionToken);\n * // ...\n * }\n * ```\n */\nexport async function getSessionCookie(): Promise<string | null> {\n return await getAuthCookie('session');\n}\n\n/**\n * Deletes the session cookie.\n * Use this when logging out or when session validation fails.\n *\n * @example\n * ```ts\n * await deleteSessionCookie();\n * redirect('/');\n * ```\n */\nexport async function deleteSessionCookie(): Promise<void> {\n await deleteAuthCookie('session');\n logger.info('Session cookie deleted');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyCA,IAAM,SAAS,aAAa,EAAE,WAAW,0BAA0B,CAAC;;;;;;;;;;;;;;;;;;;AAoBpE,eAAsB,cACpB,MACA,OACA,UAAyB,6BACV;CACf,IAAI;EACF,MAAM,cAAc,MAAM,QAAQ;EAClC,MAAM,gBAAgB;GAAE,GAAG;GAA6B,GAAG;EAAQ;EAInE,MAAM,OAAO,wBAAwB,MAAM,KAAK;EAChD,IAAI,QAAQ,mBACV,OAAO,KAAK;GAAE,YAAY;GAAM;EAAK,GAAG,uCAAuC;EAGjF,YAAY,IAAI,MAAM,OAAO,aAAa;EAE1C,OAAO,MAAM;GACX,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AAQA,eAAsB,qBACpB,cACA,UAAkC,CAAC,GACpB;CACf,MAAM,cAAc,0BAA0B,cAAc;EAC1D,GAAG;EACH,GAAG;CACL,CAAC;AACH;;;;AAKA,eAAsB,uBAA+C;CACnE,OAAO,MAAM,cAAc,wBAAwB;AACrD;;;;AAKA,eAAsB,0BAAyC;CAC7D,MAAM,iBAAiB,wBAAwB;AACjD;;;;;;;;;;;;;;;;AAiBA,eAAsB,mBAA2C;CAC/D,OAAO,MAAM,cAAc,SAAS;AACtC;;;;;;;;;;;AAYA,eAAsB,sBAAqC;CACzD,MAAM,iBAAiB,SAAS;CAChC,OAAO,KAAK,wBAAwB;AACtC"}
@@ -1,5 +1,5 @@
1
- import { globalPOSTRateLimit } from "./request.js";
2
1
  import { nextCookieStore } from "./cookie-store.js";
2
+ import { globalPOSTRateLimit } from "./request.js";
3
3
  import { handleHeartbeat as handleHeartbeat$1 } from "@eventuras/fides-auth/server";
4
4
  //#region src/heartbeat-handler.ts
5
5
  /**
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from './cookie-store';
1
2
  export * from './request';
2
3
  export * from './session';
3
4
  export * from './cookies';
@@ -8,6 +9,8 @@ export * from './heartbeat-handler';
8
9
  export * from './store';
9
10
  export * from '@eventuras/fides-auth/oauth';
10
11
  export type { OAuthConfig } from '@eventuras/fides-auth/oauth';
12
+ export * from '@eventuras/fides-auth/logger';
13
+ export * from '@eventuras/fides-auth/session-events';
11
14
  export * from '@eventuras/fides-auth/session-refresh';
12
15
  export * from '@eventuras/fides-auth/session-validation';
13
16
  export * from '@eventuras/fides-auth/silent-login';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC;AAGpC,cAAc,SAAS,CAAC;AAGxB,cAAc,6BAA6B,CAAC;AAC5C,YAAY,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC/D,cAAc,uCAAuC,CAAC;AACtD,cAAc,0CAA0C,CAAC;AACzD,cAAc,oCAAoC,CAAC;AACnD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,6BAA6B,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC;AAGpC,cAAc,SAAS,CAAC;AAGxB,cAAc,6BAA6B,CAAC;AAC5C,YAAY,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC/D,cAAc,8BAA8B,CAAC;AAC7C,cAAc,sCAAsC,CAAC;AACrD,cAAc,uCAAuC,CAAC;AACtD,cAAc,0CAA0C,CAAC;AACzD,cAAc,oCAAoC,CAAC;AACnD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,6BAA6B,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC"}
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
+ import { nextCookieStore } from "./cookie-store.js";
1
2
  import { globalGETRateLimit, globalPOSTRateLimit } from "./request.js";
2
- import { clearCurrentSession, createAndPersistSession, createSession, getCurrentSession, refreshCurrentSession } from "./session.js";
3
+ import { clearCurrentSession, createAndPersistSession, createSession, getCurrentSession, refreshCurrentSession, tryGetCurrentSession, tryRefreshCurrentSession } from "./session.js";
3
4
  import { ACCESS_TOKEN_COOKIE_NAME, COOKIE_INFO_BYTES, COOKIE_MAX_BYTES, CookieTooLargeError, ID_TOKEN_COOKIE_NAME, assertCookieWithinLimit, cookieByteSize, defaultOAuthCookieOptions, defaultSessionCookieOptions, deleteAccessTokenCookie, deleteAuthCookie, deleteAuthCookies, deleteSessionCookie, getAccessTokenCookie, getAuthCookie, getSessionCookie, setAccessTokenCookie, setAuthCookie, setSessionCookie } from "./cookies.js";
4
5
  import { handleOidcCallback } from "./oidc-callback.js";
5
6
  import { handleOidcLogin } from "./oidc-login.js";
@@ -7,10 +8,12 @@ import { handleOidcLogout } from "./oidc-logout.js";
7
8
  import { handleHeartbeat } from "./heartbeat-handler.js";
8
9
  import { checkAuth, configureAuthLogger, createAuthStore, createAuthStoreHooks, initializeAuth, startSessionMonitor, useHeartbeat, useSessionMonitor } from "./store/index.js";
9
10
  import { TokenBucket } from "@eventuras/fides-auth/rate-limit";
11
+ export * from "@eventuras/fides-auth/logger";
10
12
  export * from "@eventuras/fides-auth/utils";
11
13
  export * from "@eventuras/fides-auth/oauth";
14
+ export * from "@eventuras/fides-auth/session-events";
12
15
  export * from "@eventuras/fides-auth/session-refresh";
13
16
  export * from "@eventuras/fides-auth/session-validation";
14
17
  export * from "@eventuras/fides-auth/silent-login";
15
18
  export * from "@eventuras/fides-auth/types";
16
- export { ACCESS_TOKEN_COOKIE_NAME, COOKIE_INFO_BYTES, COOKIE_MAX_BYTES, CookieTooLargeError, ID_TOKEN_COOKIE_NAME, TokenBucket, assertCookieWithinLimit, checkAuth, clearCurrentSession, configureAuthLogger, cookieByteSize, createAndPersistSession, createAuthStore, createAuthStoreHooks, createSession, defaultOAuthCookieOptions, defaultSessionCookieOptions, deleteAccessTokenCookie, deleteAuthCookie, deleteAuthCookies, deleteSessionCookie, getAccessTokenCookie, getAuthCookie, getCurrentSession, getSessionCookie, globalGETRateLimit, globalPOSTRateLimit, handleHeartbeat, handleOidcCallback, handleOidcLogin, handleOidcLogout, initializeAuth, refreshCurrentSession, setAccessTokenCookie, setAuthCookie, setSessionCookie, startSessionMonitor, useHeartbeat, useSessionMonitor };
19
+ export { ACCESS_TOKEN_COOKIE_NAME, COOKIE_INFO_BYTES, COOKIE_MAX_BYTES, CookieTooLargeError, ID_TOKEN_COOKIE_NAME, TokenBucket, assertCookieWithinLimit, checkAuth, clearCurrentSession, configureAuthLogger, cookieByteSize, createAndPersistSession, createAuthStore, createAuthStoreHooks, createSession, defaultOAuthCookieOptions, defaultSessionCookieOptions, deleteAccessTokenCookie, deleteAuthCookie, deleteAuthCookies, deleteSessionCookie, getAccessTokenCookie, getAuthCookie, getCurrentSession, getSessionCookie, globalGETRateLimit, globalPOSTRateLimit, handleHeartbeat, handleOidcCallback, handleOidcLogin, handleOidcLogout, initializeAuth, nextCookieStore, refreshCurrentSession, setAccessTokenCookie, setAuthCookie, setSessionCookie, startSessionMonitor, tryGetCurrentSession, tryRefreshCurrentSession, useHeartbeat, useSessionMonitor };
@@ -1,5 +1,5 @@
1
- import { globalGETRateLimit } from "./request.js";
2
1
  import { nextCookieStore } from "./cookie-store.js";
2
+ import { globalGETRateLimit } from "./request.js";
3
3
  import { handleOidcCallback as handleOidcCallback$1 } from "@eventuras/fides-auth/server";
4
4
  //#region src/oidc-callback.ts
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { globalGETRateLimit } from "./request.js";
2
1
  import { nextCookieStore } from "./cookie-store.js";
2
+ import { globalGETRateLimit } from "./request.js";
3
3
  import { handleOidcLogin as handleOidcLogin$1 } from "@eventuras/fides-auth/server";
4
4
  //#region src/oidc-login.ts
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { globalPOSTRateLimit } from "./request.js";
2
1
  import { nextCookieStore } from "./cookie-store.js";
2
+ import { globalPOSTRateLimit } from "./request.js";
3
3
  import { handleOidcLogout as handleOidcLogout$1 } from "@eventuras/fides-auth/server";
4
4
  //#region src/oidc-logout.ts
5
5
  /**
package/dist/request.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { headers } from "next/headers";
2
2
  import { TokenBucket } from "@eventuras/fides-auth/rate-limit";
3
- import { Logger } from "@eventuras/logger";
3
+ import { createLogger } from "@eventuras/fides-auth/logger";
4
4
  //#region src/request.ts
5
- var logger = Logger.create({ namespace: "fides-auth-next:request" });
5
+ var logger = createLogger({ namespace: "fides-auth-next:request" });
6
6
  var globalBucket = null;
7
7
  function getBucket() {
8
8
  if (!globalBucket) globalBucket = new TokenBucket(100, 1);
@@ -1 +1 @@
1
- {"version":3,"file":"request.js","names":[],"sources":["../src/request.ts"],"sourcesContent":["import { headers } from 'next/headers';\nimport {TokenBucket} from '@eventuras/fides-auth/rate-limit';\nimport { Logger } from '@eventuras/logger';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:request' });\n\n// Initialize bucket lazily to avoid worker thread issues\nlet globalBucket: TokenBucket<string> | null = null;\n\nfunction getBucket(): TokenBucket<string> {\n if (!globalBucket) {\n globalBucket = new TokenBucket<string>(100, 1);\n }\n return globalBucket;\n}\n\nexport async function globalGETRateLimit(): Promise<boolean> {\n try {\n const headerStore = await headers();\n const clientIP = headerStore.get('X-Forwarded-For');\n if (clientIP === null) {\n return true;\n }\n return getBucket().consume(clientIP, 1);\n } catch (error) {\n // If worker thread crashes, allow the request through\n if (error instanceof Error && error.message.includes('worker')) {\n logger.error({ error }, 'Worker thread error in globalGETRateLimit');\n } else {\n logger.error({ error }, 'Unexpected error in globalGETRateLimit');\n }\n return true;\n }\n}\n\nexport async function globalPOSTRateLimit(): Promise<boolean> {\n try {\n const headerStore = await headers();\n const clientIP = headerStore.get('X-Forwarded-For');\n if (clientIP === null) {\n return true;\n }\n return getBucket().consume(clientIP, 3);\n } catch (error) {\n // If worker thread crashes, allow the request through\n if (error instanceof Error && error.message.includes('worker')) {\n logger.error({ error }, 'Worker thread error in globalPOSTRateLimit');\n } else {\n logger.error({ error }, 'Unexpected error in globalPOSTRateLimit');\n }\n return true;\n }\n}\n"],"mappings":";;;;AAIA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,0BAA0B,CAAC;AAGrE,IAAI,eAA2C;AAE/C,SAAS,YAAiC;CACxC,IAAI,CAAC,cACH,eAAe,IAAI,YAAoB,KAAK,CAAC;CAE/C,OAAO;AACT;AAEA,eAAsB,qBAAuC;CAC3D,IAAI;EAEF,MAAM,YAAW,MADS,QAAQ,EAAA,CACL,IAAI,iBAAiB;EAClD,IAAI,aAAa,MACf,OAAO;EAET,OAAO,UAAU,CAAC,CAAC,QAAQ,UAAU,CAAC;CACxC,SAAS,OAAO;EAEd,IAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,QAAQ,GAC3D,OAAO,MAAM,EAAE,MAAM,GAAG,2CAA2C;OAEnE,OAAO,MAAM,EAAE,MAAM,GAAG,wCAAwC;EAElE,OAAO;CACT;AACF;AAEA,eAAsB,sBAAwC;CAC5D,IAAI;EAEF,MAAM,YAAW,MADS,QAAQ,EAAA,CACL,IAAI,iBAAiB;EAClD,IAAI,aAAa,MACf,OAAO;EAET,OAAO,UAAU,CAAC,CAAC,QAAQ,UAAU,CAAC;CACxC,SAAS,OAAO;EAEd,IAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,QAAQ,GAC3D,OAAO,MAAM,EAAE,MAAM,GAAG,4CAA4C;OAEpE,OAAO,MAAM,EAAE,MAAM,GAAG,yCAAyC;EAEnE,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"request.js","names":[],"sources":["../src/request.ts"],"sourcesContent":["import { headers } from 'next/headers';\nimport {TokenBucket} from '@eventuras/fides-auth/rate-limit';\nimport { createLogger } from '@eventuras/fides-auth/logger';\n\nconst logger = createLogger({ namespace: 'fides-auth-next:request' });\n\n// Initialize bucket lazily to avoid worker thread issues\nlet globalBucket: TokenBucket<string> | null = null;\n\nfunction getBucket(): TokenBucket<string> {\n if (!globalBucket) {\n globalBucket = new TokenBucket<string>(100, 1);\n }\n return globalBucket;\n}\n\nexport async function globalGETRateLimit(): Promise<boolean> {\n try {\n const headerStore = await headers();\n const clientIP = headerStore.get('X-Forwarded-For');\n if (clientIP === null) {\n return true;\n }\n return getBucket().consume(clientIP, 1);\n } catch (error) {\n // If worker thread crashes, allow the request through\n if (error instanceof Error && error.message.includes('worker')) {\n logger.error({ error }, 'Worker thread error in globalGETRateLimit');\n } else {\n logger.error({ error }, 'Unexpected error in globalGETRateLimit');\n }\n return true;\n }\n}\n\nexport async function globalPOSTRateLimit(): Promise<boolean> {\n try {\n const headerStore = await headers();\n const clientIP = headerStore.get('X-Forwarded-For');\n if (clientIP === null) {\n return true;\n }\n return getBucket().consume(clientIP, 3);\n } catch (error) {\n // If worker thread crashes, allow the request through\n if (error instanceof Error && error.message.includes('worker')) {\n logger.error({ error }, 'Worker thread error in globalPOSTRateLimit');\n } else {\n logger.error({ error }, 'Unexpected error in globalPOSTRateLimit');\n }\n return true;\n }\n}\n"],"mappings":";;;;AAIA,IAAM,SAAS,aAAa,EAAE,WAAW,0BAA0B,CAAC;AAGpE,IAAI,eAA2C;AAE/C,SAAS,YAAiC;CACxC,IAAI,CAAC,cACH,eAAe,IAAI,YAAoB,KAAK,CAAC;CAE/C,OAAO;AACT;AAEA,eAAsB,qBAAuC;CAC3D,IAAI;EAEF,MAAM,YAAW,MADS,QAAQ,EAAA,CACL,IAAI,iBAAiB;EAClD,IAAI,aAAa,MACf,OAAO;EAET,OAAO,UAAU,CAAC,CAAC,QAAQ,UAAU,CAAC;CACxC,SAAS,OAAO;EAEd,IAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,QAAQ,GAC3D,OAAO,MAAM,EAAE,MAAM,GAAG,2CAA2C;OAEnE,OAAO,MAAM,EAAE,MAAM,GAAG,wCAAwC;EAElE,OAAO;CACT;AACF;AAEA,eAAsB,sBAAwC;CAC5D,IAAI;EAEF,MAAM,YAAW,MADS,QAAQ,EAAA,CACL,IAAI,iBAAiB;EAClD,IAAI,aAAa,MACf,OAAO;EAET,OAAO,UAAU,CAAC,CAAC,QAAQ,UAAU,CAAC;CACxC,SAAS,OAAO;EAEd,IAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,QAAQ,GAC3D,OAAO,MAAM,EAAE,MAAM,GAAG,4CAA4C;OAEpE,OAAO,MAAM,EAAE,MAAM,GAAG,yCAAyC;EAEnE,OAAO;CACT;AACF"}
package/dist/session.d.ts CHANGED
@@ -1,5 +1,7 @@
1
+ import { ClearSessionOptions, ReadSessionResult, RefreshSessionResult } from '@eventuras/fides-auth/server';
1
2
  import { Session, CreateSessionOptions } from '@eventuras/fides-auth/types';
2
3
  import { OAuthConfig } from '@eventuras/fides-auth/oauth';
4
+ export type { ClearSessionOptions, ReadSessionResult, RefreshSessionResult };
3
5
  /**
4
6
  * Creates an encrypted JWT containing session data.
5
7
  *
@@ -30,6 +32,35 @@ export declare function createSession<TData = Record<string, unknown>>(session:
30
32
  * ```
31
33
  */
32
34
  export declare const getCurrentSession: (_config?: OAuthConfig) => Promise<Session<any> | null>;
35
+ /**
36
+ * Reads the current session and, when there isn't one, says why.
37
+ *
38
+ * The reason comes from the package-wide vocabulary, so a proxy or a status
39
+ * route logs the same word for the same situation that the heartbeat endpoint
40
+ * logs — which is the point of having a vocabulary at all. Cached per render
41
+ * like {@link getCurrentSession}, and shared with it, so asking for the reason
42
+ * costs no extra decrypt.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * import {
47
+ * SESSION_EVENT,
48
+ * createLogger,
49
+ * logSessionEvent,
50
+ * tryGetCurrentSession,
51
+ * } from '@eventuras/fides-auth-next';
52
+ * import { redirect } from 'next/navigation';
53
+ *
54
+ * const logger = createLogger({ namespace: 'my-app:proxy' });
55
+ *
56
+ * const { session, reason } = await tryGetCurrentSession();
57
+ * if (!session) {
58
+ * logSessionEvent(logger, { event: SESSION_EVENT.REJECTED, reason, source: 'proxy' });
59
+ * redirect('/login');
60
+ * }
61
+ * ```
62
+ */
63
+ export declare const tryGetCurrentSession: () => Promise<ReadSessionResult>;
33
64
  /**
34
65
  * Refreshes the current session using its refresh token and updates the cookies.
35
66
  *
@@ -44,6 +75,22 @@ export declare const getCurrentSession: (_config?: OAuthConfig) => Promise<Sessi
44
75
  * ```
45
76
  */
46
77
  export declare function refreshCurrentSession(config: OAuthConfig, options?: CreateSessionOptions): Promise<Session | null>;
78
+ /**
79
+ * Refreshes the current session and, on failure, says why.
80
+ *
81
+ * Prefer this over {@link refreshCurrentSession} anywhere the answer decides
82
+ * whether the user stays logged in: a bare null cannot tell "the provider says
83
+ * this refresh token is dead" apart from "we could not reach the provider", and
84
+ * ending a session on the second is how a provider blip becomes a logout.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * const result = await tryRefreshCurrentSession(oauthConfig);
89
+ * if (!result.ok && result.cause === 'invalid_grant') redirect('/login');
90
+ * // transport / idp_error: keep the session and retry.
91
+ * ```
92
+ */
93
+ export declare function tryRefreshCurrentSession(config: OAuthConfig, options?: CreateSessionOptions): Promise<RefreshSessionResult>;
47
94
  /**
48
95
  * Creates and persists a new session across the session/session_at cookies.
49
96
  *
@@ -69,5 +116,5 @@ export declare function createAndPersistSession(session: Session, _options?: Cre
69
116
  * redirect('/');
70
117
  * ```
71
118
  */
72
- export declare function clearCurrentSession(): Promise<void>;
119
+ export declare function clearCurrentSession(options?: ClearSessionOptions): Promise<void>;
73
120
  //# sourceMappingURL=session.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACjF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAQ/D;;;;;;;;;;GAUG;AACH,wBAAsB,aAAa,CAAC,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjE,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,EACvB,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,MAAM,CAAC,CAUjB;AAED;;;;;;;;;;;;;;;;G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M,oBAAoB,QACrB,OAAO,CAAC,iBAAiB,CAGpC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,WAAW,EACnB,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAEzB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,WAAW,EACnB,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,oBAAoB,CAAC,CAE/B;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,OAAO,EAChB,QAAQ,GAAE,oBAAyB,GAClC,OAAO,CAAC,MAAM,CAAC,CAEjB;AAED;;;;;;;;GAQG;AACH,wBAAsB,mBAAmB,CACvC,OAAO,GAAE,mBAAwB,GAChC,OAAO,CAAC,IAAI,CAAC,CASf"}
package/dist/session.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { nextCookieStore } from "./cookie-store.js";
2
- import { Logger } from "@eventuras/logger";
2
+ import { createLogger } from "@eventuras/fides-auth/logger";
3
3
  import { createEncryptedJWT, getSessionSecret } from "@eventuras/fides-auth/utils";
4
- import { clearSession, persistSession, readSession, refreshSessionInStore } from "@eventuras/fides-auth/server";
4
+ import { clearSession, persistSession, refreshSessionInStore, tryReadSession, tryRefreshSessionInStore } from "@eventuras/fides-auth/server";
5
5
  import { cache } from "react";
6
6
  //#region src/session.ts
7
- var logger = Logger.create({ namespace: "fides-auth-next:session" });
7
+ var logger = createLogger({ namespace: "fides-auth-next:session" });
8
8
  /**
9
9
  * Creates an encrypted JWT containing session data.
10
10
  *
@@ -45,7 +45,38 @@ async function createSession(session, options = {}) {
45
45
  * ```
46
46
  */
47
47
  var getCurrentSession = cache(async (_config) => {
48
- return readSession(await nextCookieStore(), getSessionSecret());
48
+ return (await tryGetCurrentSession()).session;
49
+ });
50
+ /**
51
+ * Reads the current session and, when there isn't one, says why.
52
+ *
53
+ * The reason comes from the package-wide vocabulary, so a proxy or a status
54
+ * route logs the same word for the same situation that the heartbeat endpoint
55
+ * logs — which is the point of having a vocabulary at all. Cached per render
56
+ * like {@link getCurrentSession}, and shared with it, so asking for the reason
57
+ * costs no extra decrypt.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * import {
62
+ * SESSION_EVENT,
63
+ * createLogger,
64
+ * logSessionEvent,
65
+ * tryGetCurrentSession,
66
+ * } from '@eventuras/fides-auth-next';
67
+ * import { redirect } from 'next/navigation';
68
+ *
69
+ * const logger = createLogger({ namespace: 'my-app:proxy' });
70
+ *
71
+ * const { session, reason } = await tryGetCurrentSession();
72
+ * if (!session) {
73
+ * logSessionEvent(logger, { event: SESSION_EVENT.REJECTED, reason, source: 'proxy' });
74
+ * redirect('/login');
75
+ * }
76
+ * ```
77
+ */
78
+ var tryGetCurrentSession = cache(async () => {
79
+ return tryReadSession(await nextCookieStore(), getSessionSecret());
49
80
  });
50
81
  /**
51
82
  * Refreshes the current session using its refresh token and updates the cookies.
@@ -64,6 +95,24 @@ async function refreshCurrentSession(config, options = {}) {
64
95
  return refreshSessionInStore(await nextCookieStore(), config, getSessionSecret(), options);
65
96
  }
66
97
  /**
98
+ * Refreshes the current session and, on failure, says why.
99
+ *
100
+ * Prefer this over {@link refreshCurrentSession} anywhere the answer decides
101
+ * whether the user stays logged in: a bare null cannot tell "the provider says
102
+ * this refresh token is dead" apart from "we could not reach the provider", and
103
+ * ending a session on the second is how a provider blip becomes a logout.
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * const result = await tryRefreshCurrentSession(oauthConfig);
108
+ * if (!result.ok && result.cause === 'invalid_grant') redirect('/login');
109
+ * // transport / idp_error: keep the session and retry.
110
+ * ```
111
+ */
112
+ async function tryRefreshCurrentSession(config, options = {}) {
113
+ return tryRefreshSessionInStore(await nextCookieStore(), config, getSessionSecret(), options);
114
+ }
115
+ /**
67
116
  * Creates and persists a new session across the session/session_at cookies.
68
117
  *
69
118
  * @param session - Session data
@@ -90,10 +139,14 @@ async function createAndPersistSession(session, _options = {}) {
90
139
  * redirect('/');
91
140
  * ```
92
141
  */
93
- async function clearCurrentSession() {
94
- await clearSession(await nextCookieStore());
142
+ async function clearCurrentSession(options = {}) {
143
+ const sid = options.sid ?? (await tryGetCurrentSession()).session?.sid;
144
+ await clearSession(await nextCookieStore(), {
145
+ trigger: options.trigger ?? "logout",
146
+ sid
147
+ });
95
148
  }
96
149
  //#endregion
97
- export { clearCurrentSession, createAndPersistSession, createSession, getCurrentSession, refreshCurrentSession };
150
+ export { clearCurrentSession, createAndPersistSession, createSession, getCurrentSession, refreshCurrentSession, tryGetCurrentSession, tryRefreshCurrentSession };
98
151
 
99
152
  //# sourceMappingURL=session.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { createEncryptedJWT, getSessionSecret } from '@eventuras/fides-auth/utils';\nimport {\n persistSession,\n readSession,\n refreshSessionInStore,\n clearSession,\n} from '@eventuras/fides-auth/server';\nimport type { Session, CreateSessionOptions } from '@eventuras/fides-auth/types';\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport { Logger } from '@eventuras/logger';\nimport { cache } from 'react';\n\nimport { nextCookieStore } from './cookie-store';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:session' });\n\n/**\n * Creates an encrypted JWT containing session data.\n *\n * Pre-split API: this serializes the whole session, raw tokens included, into one\n * value. Prefer {@link createAndPersistSession}, which splits the large JWTs across\n * cookies instead of spending one cookie's byte budget on all of them.\n *\n * @param session - Session data (tokens, user, etc.)\n * @param options - Configuration options (e.g., sessionDurationDays)\n * @returns Encrypted JWT string\n */\nexport async function createSession<TData = Record<string, unknown>>(\n session: Session<TData>,\n options: CreateSessionOptions = {}\n): Promise<string> {\n const { sessionDurationDays = 7 } = options;\n try {\n const jwt = await createEncryptedJWT({ ...session }, getSessionSecret());\n logger.info({ sessionDurationDays }, 'Session created successfully');\n return jwt;\n } catch (error) {\n logger.error({ error }, 'Failed to create session');\n throw error;\n }\n}\n\n/**\n * Retrieves the current session from cookies, if any. Wraps the framework-\n * agnostic {@link readSession} with React's `cache` so repeated calls within one\n * server render share a single read.\n *\n * The session may carry an expired access token — check `accessTokenExpires`\n * before using it, or refresh via `refreshCurrentSession`.\n *\n * @param _config - Unused; kept for backwards compatibility.\n * @returns Session object or null if no session exists.\n *\n * @example\n * ```ts\n * const session = await getCurrentSession();\n * if (session) console.log('User:', session.user);\n * ```\n */\nexport const getCurrentSession = cache(\n async (_config?: OAuthConfig): Promise<Session<any> | null> => {\n return readSession(await nextCookieStore(), getSessionSecret());\n },\n);\n\n/**\n * Refreshes the current session using its refresh token and updates the cookies.\n *\n * @param config - OAuth configuration\n * @param options - Session creation options\n * @returns Updated session or null if refresh failed\n *\n * @example\n * ```ts\n * const updated = await refreshCurrentSession(oauthConfig);\n * if (!updated) redirect('/login');\n * ```\n */\nexport async function refreshCurrentSession(\n config: OAuthConfig,\n options: CreateSessionOptions = {}\n): Promise<Session | null> {\n return refreshSessionInStore(await nextCookieStore(), config, getSessionSecret(), options);\n}\n\n/**\n * Creates and persists a new session across the session/session_at cookies.\n *\n * @param session - Session data\n * @param _options - Session creation options (reserved; not currently applied)\n * @returns The encrypted JWT stored in the main \"session\" cookie.\n *\n * @example\n * ```ts\n * await createAndPersistSession({\n * tokens: { accessToken: tokens.access_token, refreshToken: tokens.refresh_token },\n * user: { name: 'John Doe', email: 'john@example.com' },\n * });\n * ```\n */\nexport async function createAndPersistSession(\n session: Session,\n _options: CreateSessionOptions = {}\n): Promise<string> {\n return persistSession(await nextCookieStore(), session, getSessionSecret());\n}\n\n/**\n * Clears the current session by deleting the session cookies.\n *\n * @example\n * ```ts\n * await clearCurrentSession();\n * redirect('/');\n * ```\n */\nexport async function clearCurrentSession(): Promise<void> {\n await clearSession(await nextCookieStore());\n}\n"],"mappings":";;;;;;AAcA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,0BAA0B,CAAC;;;;;;;;;;;;AAarE,eAAsB,cACpB,SACA,UAAgC,CAAC,GAChB;CACjB,MAAM,EAAE,sBAAsB,MAAM;CACpC,IAAI;EACF,MAAM,MAAM,MAAM,mBAAmB,EAAE,GAAG,QAAQ,GAAG,iBAAiB,CAAC;EACvE,OAAO,KAAK,EAAE,oBAAoB,GAAG,8BAA8B;EACnE,OAAO;CACT,SAAS,OAAO;EACd,OAAO,MAAM,EAAE,MAAM,GAAG,0BAA0B;EAClD,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;;AAmBA,IAAa,oBAAoB,MAC/B,OAAO,YAAwD;CAC7D,OAAO,YAAY,MAAM,gBAAgB,GAAG,iBAAiB,CAAC;AAChE,CACF;;;;;;;;;;;;;;AAeA,eAAsB,sBACpB,QACA,UAAgC,CAAC,GACR;CACzB,OAAO,sBAAsB,MAAM,gBAAgB,GAAG,QAAQ,iBAAiB,GAAG,OAAO;AAC3F;;;;;;;;;;;;;;;;AAiBA,eAAsB,wBACpB,SACA,WAAiC,CAAC,GACjB;CACjB,OAAO,eAAe,MAAM,gBAAgB,GAAG,SAAS,iBAAiB,CAAC;AAC5E;;;;;;;;;;AAWA,eAAsB,sBAAqC;CACzD,MAAM,aAAa,MAAM,gBAAgB,CAAC;AAC5C"}
1
+ {"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { createEncryptedJWT, getSessionSecret } from '@eventuras/fides-auth/utils';\nimport {\n persistSession,\n readSession,\n tryReadSession,\n refreshSessionInStore,\n tryRefreshSessionInStore,\n clearSession,\n type ClearSessionOptions,\n type ReadSessionResult,\n type RefreshSessionResult,\n} from '@eventuras/fides-auth/server';\nimport type { Session, CreateSessionOptions } from '@eventuras/fides-auth/types';\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport { createLogger } from '@eventuras/fides-auth/logger';\nimport { cache } from 'react';\n\nimport { nextCookieStore } from './cookie-store';\n\nconst logger = createLogger({ namespace: 'fides-auth-next:session' });\n\n// The result shapes the try* helpers below return, so consumers can name them\n// without reaching past this package.\nexport type { ClearSessionOptions, ReadSessionResult, RefreshSessionResult };\n\n/**\n * Creates an encrypted JWT containing session data.\n *\n * Pre-split API: this serializes the whole session, raw tokens included, into one\n * value. Prefer {@link createAndPersistSession}, which splits the large JWTs across\n * cookies instead of spending one cookie's byte budget on all of them.\n *\n * @param session - Session data (tokens, user, etc.)\n * @param options - Configuration options (e.g., sessionDurationDays)\n * @returns Encrypted JWT string\n */\nexport async function createSession<TData = Record<string, unknown>>(\n session: Session<TData>,\n options: CreateSessionOptions = {}\n): Promise<string> {\n const { sessionDurationDays = 7 } = options;\n try {\n const jwt = await createEncryptedJWT({ ...session }, getSessionSecret());\n logger.info({ sessionDurationDays }, 'Session created successfully');\n return jwt;\n } catch (error) {\n logger.error({ error }, 'Failed to create session');\n throw error;\n }\n}\n\n/**\n * Retrieves the current session from cookies, if any. Wraps the framework-\n * agnostic {@link readSession} with React's `cache` so repeated calls within one\n * server render share a single read.\n *\n * The session may carry an expired access token — check `accessTokenExpires`\n * before using it, or refresh via `refreshCurrentSession`.\n *\n * @param _config - Unused; kept for backwards compatibility.\n * @returns Session object or null if no session exists.\n *\n * @example\n * ```ts\n * const session = await getCurrentSession();\n * if (session) console.log('User:', session.user);\n * ```\n */\nexport const getCurrentSession = cache(\n async (_config?: OAuthConfig): Promise<Session<any> | null> => {\n return (await tryGetCurrentSession()).session;\n },\n);\n\n/**\n * Reads the current session and, when there isn't one, says why.\n *\n * The reason comes from the package-wide vocabulary, so a proxy or a status\n * route logs the same word for the same situation that the heartbeat endpoint\n * logs — which is the point of having a vocabulary at all. Cached per render\n * like {@link getCurrentSession}, and shared with it, so asking for the reason\n * costs no extra decrypt.\n *\n * @example\n * ```ts\n * import {\n * SESSION_EVENT,\n * createLogger,\n * logSessionEvent,\n * tryGetCurrentSession,\n * } from '@eventuras/fides-auth-next';\n * import { redirect } from 'next/navigation';\n *\n * const logger = createLogger({ namespace: 'my-app:proxy' });\n *\n * const { session, reason } = await tryGetCurrentSession();\n * if (!session) {\n * logSessionEvent(logger, { event: SESSION_EVENT.REJECTED, reason, source: 'proxy' });\n * redirect('/login');\n * }\n * ```\n */\nexport const tryGetCurrentSession = cache(\n async (): Promise<ReadSessionResult> => {\n return tryReadSession(await nextCookieStore(), getSessionSecret());\n },\n);\n\n/**\n * Refreshes the current session using its refresh token and updates the cookies.\n *\n * @param config - OAuth configuration\n * @param options - Session creation options\n * @returns Updated session or null if refresh failed\n *\n * @example\n * ```ts\n * const updated = await refreshCurrentSession(oauthConfig);\n * if (!updated) redirect('/login');\n * ```\n */\nexport async function refreshCurrentSession(\n config: OAuthConfig,\n options: CreateSessionOptions = {}\n): Promise<Session | null> {\n return refreshSessionInStore(await nextCookieStore(), config, getSessionSecret(), options);\n}\n\n/**\n * Refreshes the current session and, on failure, says why.\n *\n * Prefer this over {@link refreshCurrentSession} anywhere the answer decides\n * whether the user stays logged in: a bare null cannot tell \"the provider says\n * this refresh token is dead\" apart from \"we could not reach the provider\", and\n * ending a session on the second is how a provider blip becomes a logout.\n *\n * @example\n * ```ts\n * const result = await tryRefreshCurrentSession(oauthConfig);\n * if (!result.ok && result.cause === 'invalid_grant') redirect('/login');\n * // transport / idp_error: keep the session and retry.\n * ```\n */\nexport async function tryRefreshCurrentSession(\n config: OAuthConfig,\n options: CreateSessionOptions = {}\n): Promise<RefreshSessionResult> {\n return tryRefreshSessionInStore(await nextCookieStore(), config, getSessionSecret(), options);\n}\n\n/**\n * Creates and persists a new session across the session/session_at cookies.\n *\n * @param session - Session data\n * @param _options - Session creation options (reserved; not currently applied)\n * @returns The encrypted JWT stored in the main \"session\" cookie.\n *\n * @example\n * ```ts\n * await createAndPersistSession({\n * tokens: { accessToken: tokens.access_token, refreshToken: tokens.refresh_token },\n * user: { name: 'John Doe', email: 'john@example.com' },\n * });\n * ```\n */\nexport async function createAndPersistSession(\n session: Session,\n _options: CreateSessionOptions = {}\n): Promise<string> {\n return persistSession(await nextCookieStore(), session, getSessionSecret());\n}\n\n/**\n * Clears the current session by deleting the session cookies.\n *\n * @example\n * ```ts\n * await clearCurrentSession();\n * redirect('/');\n * ```\n */\nexport async function clearCurrentSession(\n options: ClearSessionOptions = {},\n): Promise<void> {\n // Defaults to `logout` because that is what this function is for; pass a\n // trigger explicitly when clearing for some other reason. The sid comes from\n // the per-render cache, so correlating the logout costs nothing extra.\n const sid = options.sid ?? (await tryGetCurrentSession()).session?.sid;\n await clearSession(await nextCookieStore(), {\n trigger: options.trigger ?? 'logout',\n sid,\n });\n}\n"],"mappings":";;;;;;AAmBA,IAAM,SAAS,aAAa,EAAE,WAAW,0BAA0B,CAAC;;;;;;;;;;;;AAiBpE,eAAsB,cACpB,SACA,UAAgC,CAAC,GAChB;CACjB,MAAM,EAAE,sBAAsB,MAAM;CACpC,IAAI;EACF,MAAM,MAAM,MAAM,mBAAmB,EAAE,GAAG,QAAQ,GAAG,iBAAiB,CAAC;EACvE,OAAO,KAAK,EAAE,oBAAoB,GAAG,8BAA8B;EACnE,OAAO;CACT,SAAS,OAAO;EACd,OAAO,MAAM,EAAE,MAAM,GAAG,0BAA0B;EAClD,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;;AAmBA,IAAa,oBAAoB,MAC/B,OAAO,YAAwD;CAC7D,QAAQ,MAAM,qBAAqB,EAAA,CAAG;AACxC,CACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,IAAa,uBAAuB,MAClC,YAAwC;CACtC,OAAO,eAAe,MAAM,gBAAgB,GAAG,iBAAiB,CAAC;AACnE,CACF;;;;;;;;;;;;;;AAeA,eAAsB,sBACpB,QACA,UAAgC,CAAC,GACR;CACzB,OAAO,sBAAsB,MAAM,gBAAgB,GAAG,QAAQ,iBAAiB,GAAG,OAAO;AAC3F;;;;;;;;;;;;;;;;AAiBA,eAAsB,yBACpB,QACA,UAAgC,CAAC,GACF;CAC/B,OAAO,yBAAyB,MAAM,gBAAgB,GAAG,QAAQ,iBAAiB,GAAG,OAAO;AAC9F;;;;;;;;;;;;;;;;AAiBA,eAAsB,wBACpB,SACA,WAAiC,CAAC,GACjB;CACjB,OAAO,eAAe,MAAM,gBAAgB,GAAG,SAAS,iBAAiB,CAAC;AAC5E;;;;;;;;;;AAWA,eAAsB,oBACpB,UAA+B,CAAC,GACjB;CAIf,MAAM,MAAM,QAAQ,QAAQ,MAAM,qBAAqB,EAAA,CAAG,SAAS;CACnE,MAAM,aAAa,MAAM,gBAAgB,GAAG;EAC1C,SAAS,QAAQ,WAAW;EAC5B;CACF,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eventuras/fides-auth-next",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Next.js bindings for @eventuras/fides-auth",
5
5
  "homepage": "https://github.com/losol/fides-auth/tree/main/packages/fides-auth-next#readme",
6
6
  "bugs": {
@@ -22,6 +22,10 @@
22
22
  "types": "./dist/session.d.ts",
23
23
  "import": "./dist/session.js"
24
24
  },
25
+ "./cookie-store": {
26
+ "types": "./dist/cookie-store.d.ts",
27
+ "import": "./dist/cookie-store.js"
28
+ },
25
29
  "./request": {
26
30
  "types": "./dist/request.d.ts",
27
31
  "import": "./dist/request.js"
@@ -54,20 +58,20 @@
54
58
  "LICENSE"
55
59
  ],
56
60
  "dependencies": {
57
- "@eventuras/logger": "^0.8.1",
58
- "@eventuras/fides-auth": "0.12.0",
59
- "@eventuras/fides-auth-react": "0.1.3",
60
- "@eventuras/fides-auth-store": "0.1.3"
61
+ "@eventuras/fides-auth": "0.13.0",
62
+ "@eventuras/fides-auth-store": "0.2.1",
63
+ "@eventuras/fides-auth-react": "0.1.5"
61
64
  },
62
65
  "devDependencies": {
63
66
  "@testing-library/jest-dom": "6.9.1",
64
67
  "@types/react": "^19.2.18",
65
68
  "jsdom": "29.1.1",
66
69
  "react": "^19.2.8",
70
+ "typescript": "^6.0.2",
67
71
  "vite": "^8.2.0",
68
72
  "vitest": "^4.1.10",
69
- "@eventuras/vite-config": "0.2.2",
70
- "@eventuras/typescript-config": "1.0.0"
73
+ "@eventuras/typescript-config": "1.0.0",
74
+ "@eventuras/vite-config": "0.2.2"
71
75
  },
72
76
  "peerDependencies": {
73
77
  "next": "^16.0.0",
@@ -75,6 +79,7 @@
75
79
  },
76
80
  "scripts": {
77
81
  "build": "vite build",
82
+ "typecheck": "tsc --noEmit",
78
83
  "dev": "vite build --watch",
79
84
  "test": "vitest run",
80
85
  "test:watch": "vitest"