@eventuras/fides-auth-next 0.3.0 → 0.6.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.
Files changed (61) hide show
  1. package/LICENSE +21 -674
  2. package/README.md +6 -1
  3. package/dist/cookie-store.d.ts +10 -0
  4. package/dist/cookie-store.d.ts.map +1 -0
  5. package/dist/cookie-store.js +25 -0
  6. package/dist/cookie-store.js.map +1 -0
  7. package/dist/cookies.d.ts +18 -41
  8. package/dist/cookies.d.ts.map +1 -1
  9. package/dist/cookies.js +31 -29
  10. package/dist/cookies.js.map +1 -1
  11. package/dist/heartbeat-handler.d.ts +1 -1
  12. package/dist/heartbeat-handler.d.ts.map +1 -1
  13. package/dist/heartbeat-handler.js +12 -36
  14. package/dist/heartbeat-handler.js.map +1 -1
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +6 -11
  18. package/dist/oidc-callback.d.ts +5 -5
  19. package/dist/oidc-callback.d.ts.map +1 -1
  20. package/dist/oidc-callback.js +16 -39
  21. package/dist/oidc-callback.js.map +1 -1
  22. package/dist/oidc-login.d.ts.map +1 -1
  23. package/dist/oidc-login.js +12 -24
  24. package/dist/oidc-login.js.map +1 -1
  25. package/dist/oidc-logout.d.ts +44 -0
  26. package/dist/oidc-logout.d.ts.map +1 -0
  27. package/dist/oidc-logout.js +44 -0
  28. package/dist/oidc-logout.js.map +1 -0
  29. package/dist/request.js.map +1 -1
  30. package/dist/session.d.ts +24 -62
  31. package/dist/session.d.ts.map +1 -1
  32. package/dist/session.js +30 -132
  33. package/dist/session.js.map +1 -1
  34. package/dist/store/index.d.ts +2 -7
  35. package/dist/store/index.d.ts.map +1 -1
  36. package/dist/store/index.js +2 -6
  37. package/package.json +24 -25
  38. package/dist/store/configure-logger.d.ts +0 -15
  39. package/dist/store/configure-logger.d.ts.map +0 -1
  40. package/dist/store/configure-logger.js +0 -25
  41. package/dist/store/configure-logger.js.map +0 -1
  42. package/dist/store/hooks.d.ts +0 -64
  43. package/dist/store/hooks.d.ts.map +0 -1
  44. package/dist/store/hooks.js +0 -78
  45. package/dist/store/hooks.js.map +0 -1
  46. package/dist/store/session-monitor.d.ts +0 -51
  47. package/dist/store/session-monitor.d.ts.map +0 -1
  48. package/dist/store/session-monitor.js +0 -92
  49. package/dist/store/session-monitor.js.map +0 -1
  50. package/dist/store/store.d.ts +0 -81
  51. package/dist/store/store.d.ts.map +0 -1
  52. package/dist/store/store.js +0 -218
  53. package/dist/store/store.js.map +0 -1
  54. package/dist/store/use-heartbeat.d.ts +0 -98
  55. package/dist/store/use-heartbeat.d.ts.map +0 -1
  56. package/dist/store/use-heartbeat.js +0 -205
  57. package/dist/store/use-heartbeat.js.map +0 -1
  58. package/dist/store/use-session-monitor.d.ts +0 -28
  59. package/dist/store/use-session-monitor.d.ts.map +0 -1
  60. package/dist/store/use-session-monitor.js +0 -40
  61. package/dist/store/use-session-monitor.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"oidc-login.js","names":[],"sources":["../src/oidc-login.ts"],"sourcesContent":["/**\n * Generic OIDC login initiation handler for Next.js route handlers.\n *\n * Builds PKCE parameters, persists them in cookies, and redirects\n * to the OIDC provider's authorization endpoint.\n */\n\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport {\n buildPKCEOptions,\n discoverAndBuildAuthorizationUrl,\n} from '@eventuras/fides-auth/oauth';\nimport { Logger } from '@eventuras/logger';\nimport { cookies } from 'next/headers';\n\nimport { defaultOAuthCookieOptions } from './cookies';\nimport { globalGETRateLimit } from './request';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:oidc-login' });\n\nexport interface OidcLoginConfig {\n /** OAuth/OIDC configuration */\n oauthConfig: OAuthConfig;\n\n /**\n * Validates and sanitizes the returnTo parameter.\n * Should return a safe path or null to use the default.\n * @default Only allows relative paths starting with /\n */\n validateReturnTo?: (rawReturnTo: string) => string | null;\n}\n\nconst defaultValidateReturnTo = (raw: string): string | null =>\n /^\\/(?!\\/)/.test(raw) ? raw : null;\n\n/**\n * Handles OIDC login initiation in a Next.js route handler.\n *\n * @example\n * ```ts\n * // In app/api/auth/login/route.ts\n * import { handleOidcLogin } from '@eventuras/fides-auth-next/oidc-login';\n *\n * export async function GET(request: Request) {\n * return handleOidcLogin(request, { oauthConfig });\n * }\n * ```\n */\nexport async function handleOidcLogin(\n request: Request,\n config: OidcLoginConfig,\n): Promise<Response> {\n const { oauthConfig, validateReturnTo = defaultValidateReturnTo } = config;\n\n if (!(await globalGETRateLimit())) {\n logger.warn('Rate limit exceeded');\n return new Response('Too many requests', { status: 429 });\n }\n\n // Validate returnTo parameter\n const url = new URL(request.url);\n const rawReturnTo = url.searchParams.get('returnTo');\n const returnTo = rawReturnTo ? validateReturnTo(rawReturnTo) : null;\n\n // Build PKCE & authorization URL\n const pkce = await buildPKCEOptions(oauthConfig);\n const authorizationUrl = await discoverAndBuildAuthorizationUrl(oauthConfig, pkce);\n\n logger.info('Redirecting to OIDC provider for login');\n\n // Persist PKCE state in cookies using Next.js cookies API\n const cookieStore = await cookies();\n const cookieOpts = defaultOAuthCookieOptions;\n\n cookieStore.set('oauth_state', pkce.state, cookieOpts);\n cookieStore.set('oauth_code_verifier', pkce.code_verifier, cookieOpts);\n\n if (returnTo) {\n cookieStore.set('returnTo', returnTo, cookieOpts);\n }\n\n return new Response(null, {\n status: 302,\n headers: { Location: authorizationUrl.toString() },\n });\n}\n"],"mappings":";;;;;;AAkBA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,6BAA6B,CAAC;AAcxE,IAAM,2BAA2B,QAC/B,YAAY,KAAK,GAAG,IAAI,MAAM;;;;;;;;;;;;;;AAehC,eAAsB,gBACpB,SACA,QACmB;CACnB,MAAM,EAAE,aAAa,mBAAmB,4BAA4B;CAEpE,IAAI,CAAE,MAAM,mBAAmB,GAAI;EACjC,OAAO,KAAK,qBAAqB;EACjC,OAAO,IAAI,SAAS,qBAAqB,EAAE,QAAQ,IAAI,CAAC;CAC1D;CAIA,MAAM,cAAc,IADJ,IAAI,QAAQ,GACR,EAAI,aAAa,IAAI,UAAU;CACnD,MAAM,WAAW,cAAc,iBAAiB,WAAW,IAAI;CAG/D,MAAM,OAAO,MAAM,iBAAiB,WAAW;CAC/C,MAAM,mBAAmB,MAAM,iCAAiC,aAAa,IAAI;CAEjF,OAAO,KAAK,wCAAwC;CAGpD,MAAM,cAAc,MAAM,QAAQ;CAClC,MAAM,aAAa;CAEnB,YAAY,IAAI,eAAe,KAAK,OAAO,UAAU;CACrD,YAAY,IAAI,uBAAuB,KAAK,eAAe,UAAU;CAErE,IAAI,UACF,YAAY,IAAI,YAAY,UAAU,UAAU;CAGlD,OAAO,IAAI,SAAS,MAAM;EACxB,QAAQ;EACR,SAAS,EAAE,UAAU,iBAAiB,SAAS,EAAE;CACnD,CAAC;AACH"}
1
+ {"version":3,"file":"oidc-login.js","names":[],"sources":["../src/oidc-login.ts"],"sourcesContent":["/**\n * OIDC login initiation for Next.js route handlers — a thin wrapper over the\n * framework-agnostic handler in `@eventuras/fides-auth/server`, wiring it to the\n * Next cookie store and the global GET rate limiter.\n */\n\nimport { handleOidcLogin as coreHandleOidcLogin } from '@eventuras/fides-auth/server';\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\n\nimport { nextCookieStore } from './cookie-store';\nimport { globalGETRateLimit } from './request';\n\nexport interface OidcLoginConfig {\n /** OAuth/OIDC configuration */\n oauthConfig: OAuthConfig;\n\n /**\n * Validates and sanitizes the returnTo parameter.\n * Should return a safe path or null to use the default.\n * @default Only allows relative paths starting with /\n */\n validateReturnTo?: (rawReturnTo: string) => string | null;\n}\n\n/**\n * Handles OIDC login initiation in a Next.js route handler.\n *\n * @example\n * ```ts\n * // In app/api/auth/login/route.ts\n * import { handleOidcLogin } from '@eventuras/fides-auth-next/oidc-login';\n *\n * export async function GET(request: Request) {\n * return handleOidcLogin(request, { oauthConfig });\n * }\n * ```\n */\nexport async function handleOidcLogin(\n request: Request,\n config: OidcLoginConfig,\n): Promise<Response> {\n return coreHandleOidcLogin(request, {\n oauthConfig: config.oauthConfig,\n validateReturnTo: config.validateReturnTo,\n cookies: await nextCookieStore(),\n rateLimit: globalGETRateLimit,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqCA,eAAsB,gBACpB,SACA,QACmB;CACnB,OAAO,kBAAoB,SAAS;EAClC,aAAa,OAAO;EACpB,kBAAkB,OAAO;EACzB,SAAS,MAAM,gBAAgB;EAC/B,WAAW;CACb,CAAC;AACH"}
@@ -0,0 +1,44 @@
1
+ import { OAuthConfig } from '@eventuras/fides-auth/oauth';
2
+ export interface OidcLogoutConfig {
3
+ /** OAuth/OIDC configuration */
4
+ oauthConfig: OAuthConfig;
5
+ /**
6
+ * URI the provider redirects back to after logout. Must be registered with the
7
+ * provider as a post-logout redirect URI.
8
+ */
9
+ postLogoutRedirectUri: string;
10
+ /** Opaque value echoed back on the post-logout redirect. */
11
+ state?: string;
12
+ /** `logout_hint`, when the provider documents one. */
13
+ logoutHint?: string;
14
+ /** Whether to send `client_id`. Default true. */
15
+ includeClientId?: boolean;
16
+ /** Request methods that may trigger a logout. @default ['POST'] */
17
+ allowedMethods?: string[];
18
+ /** Public application URL, used to check the `Origin` header behind a proxy. */
19
+ applicationUrl?: string;
20
+ /**
21
+ * Where to send the user when the provider advertises no end_session_endpoint.
22
+ * @default postLogoutRedirectUri
23
+ */
24
+ fallbackRedirectUri?: string;
25
+ }
26
+ /**
27
+ * Handles logout in a Next.js route handler: clears the session cookies and
28
+ * redirects to the provider's end-session endpoint with `id_token_hint`.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * // In app/api/auth/logout/route.ts
33
+ * import { handleOidcLogout } from '@eventuras/fides-auth-next/oidc-logout';
34
+ *
35
+ * export async function POST(request: Request) {
36
+ * return handleOidcLogout(request, {
37
+ * oauthConfig,
38
+ * postLogoutRedirectUri: 'https://example.com/',
39
+ * });
40
+ * }
41
+ * ```
42
+ */
43
+ export declare function handleOidcLogout(request: Request, config: OidcLogoutConfig): Promise<Response>;
44
+ //# sourceMappingURL=oidc-logout.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc-logout.d.ts","sourceRoot":"","sources":["../src/oidc-logout.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAK/D,MAAM,WAAW,gBAAgB;IAC/B,+BAA+B;IAC/B,WAAW,EAAE,WAAW,CAAC;IAEzB;;;OAGG;IACH,qBAAqB,EAAE,MAAM,CAAC;IAE9B,4DAA4D;IAC5D,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,sDAAsD;IACtD,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB,iDAAiD;IACjD,eAAe,CAAC,EAAE,OAAO,CAAC;IAE1B,mEAAmE;IACnE,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAE1B,gFAAgF;IAChF,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,gBAAgB,GACvB,OAAO,CAAC,QAAQ,CAAC,CAanB"}
@@ -0,0 +1,44 @@
1
+ import { globalPOSTRateLimit } from "./request.js";
2
+ import { nextCookieStore } from "./cookie-store.js";
3
+ import { handleOidcLogout as handleOidcLogout$1 } from "@eventuras/fides-auth/server";
4
+ //#region src/oidc-logout.ts
5
+ /**
6
+ * RP-initiated logout for Next.js route handlers — a thin wrapper over the
7
+ * framework-agnostic handler in `@eventuras/fides-auth/server`, wiring it to the
8
+ * Next cookie store and the global POST rate limiter.
9
+ */
10
+ /**
11
+ * Handles logout in a Next.js route handler: clears the session cookies and
12
+ * redirects to the provider's end-session endpoint with `id_token_hint`.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * // In app/api/auth/logout/route.ts
17
+ * import { handleOidcLogout } from '@eventuras/fides-auth-next/oidc-logout';
18
+ *
19
+ * export async function POST(request: Request) {
20
+ * return handleOidcLogout(request, {
21
+ * oauthConfig,
22
+ * postLogoutRedirectUri: 'https://example.com/',
23
+ * });
24
+ * }
25
+ * ```
26
+ */
27
+ async function handleOidcLogout(request, config) {
28
+ return handleOidcLogout$1(request, {
29
+ oauthConfig: config.oauthConfig,
30
+ postLogoutRedirectUri: config.postLogoutRedirectUri,
31
+ state: config.state,
32
+ logoutHint: config.logoutHint,
33
+ includeClientId: config.includeClientId,
34
+ fallbackRedirectUri: config.fallbackRedirectUri,
35
+ allowedMethods: config.allowedMethods,
36
+ applicationUrl: config.applicationUrl,
37
+ cookies: await nextCookieStore(),
38
+ rateLimit: globalPOSTRateLimit
39
+ });
40
+ }
41
+ //#endregion
42
+ export { handleOidcLogout };
43
+
44
+ //# sourceMappingURL=oidc-logout.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc-logout.js","names":[],"sources":["../src/oidc-logout.ts"],"sourcesContent":["/**\n * RP-initiated logout for Next.js route handlers — a thin wrapper over the\n * framework-agnostic handler in `@eventuras/fides-auth/server`, wiring it to the\n * Next cookie store and the global POST rate limiter.\n */\n\nimport { handleOidcLogout as coreHandleOidcLogout } from '@eventuras/fides-auth/server';\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\n\nimport { nextCookieStore } from './cookie-store';\nimport { globalPOSTRateLimit } from './request';\n\nexport interface OidcLogoutConfig {\n /** OAuth/OIDC configuration */\n oauthConfig: OAuthConfig;\n\n /**\n * URI the provider redirects back to after logout. Must be registered with the\n * provider as a post-logout redirect URI.\n */\n postLogoutRedirectUri: string;\n\n /** Opaque value echoed back on the post-logout redirect. */\n state?: string;\n\n /** `logout_hint`, when the provider documents one. */\n logoutHint?: string;\n\n /** Whether to send `client_id`. Default true. */\n includeClientId?: boolean;\n\n /** Request methods that may trigger a logout. @default ['POST'] */\n allowedMethods?: string[];\n\n /** Public application URL, used to check the `Origin` header behind a proxy. */\n applicationUrl?: string;\n\n /**\n * Where to send the user when the provider advertises no end_session_endpoint.\n * @default postLogoutRedirectUri\n */\n fallbackRedirectUri?: string;\n}\n\n/**\n * Handles logout in a Next.js route handler: clears the session cookies and\n * redirects to the provider's end-session endpoint with `id_token_hint`.\n *\n * @example\n * ```ts\n * // In app/api/auth/logout/route.ts\n * import { handleOidcLogout } from '@eventuras/fides-auth-next/oidc-logout';\n *\n * export async function POST(request: Request) {\n * return handleOidcLogout(request, {\n * oauthConfig,\n * postLogoutRedirectUri: 'https://example.com/',\n * });\n * }\n * ```\n */\nexport async function handleOidcLogout(\n request: Request,\n config: OidcLogoutConfig,\n): Promise<Response> {\n return coreHandleOidcLogout(request, {\n oauthConfig: config.oauthConfig,\n postLogoutRedirectUri: config.postLogoutRedirectUri,\n state: config.state,\n logoutHint: config.logoutHint,\n includeClientId: config.includeClientId,\n fallbackRedirectUri: config.fallbackRedirectUri,\n allowedMethods: config.allowedMethods,\n applicationUrl: config.applicationUrl,\n cookies: await nextCookieStore(),\n rateLimit: globalPOSTRateLimit,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,eAAsB,iBACpB,SACA,QACmB;CACnB,OAAO,mBAAqB,SAAS;EACnC,aAAa,OAAO;EACpB,uBAAuB,OAAO;EAC9B,OAAO,OAAO;EACd,YAAY,OAAO;EACnB,iBAAiB,OAAO;EACxB,qBAAqB,OAAO;EAC5B,gBAAgB,OAAO;EACvB,gBAAgB,OAAO;EACvB,SAAS,MAAM,gBAAgB;EAC/B,WAAW;CACb,CAAC;AACH"}
@@ -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,GACL,IAAI,iBAAiB;EAClD,IAAI,aAAa,MACf,OAAO;EAET,OAAO,UAAU,EAAE,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,GACL,IAAI,iBAAiB;EAClD,IAAI,aAAa,MACf,OAAO;EAET,OAAO,UAAU,EAAE,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 { 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"}
package/dist/session.d.ts CHANGED
@@ -3,57 +3,35 @@ import { OAuthConfig } from '@eventuras/fides-auth/oauth';
3
3
  /**
4
4
  * Creates an encrypted JWT containing session data.
5
5
  *
6
+ * Pre-split API: this serializes the whole session, raw tokens included, into one
7
+ * value. Prefer {@link createAndPersistSession}, which splits the large JWTs across
8
+ * cookies instead of spending one cookie's byte budget on all of them.
9
+ *
6
10
  * @param session - Session data (tokens, user, etc.)
7
11
  * @param options - Configuration options (e.g., sessionDurationDays)
8
12
  * @returns Encrypted JWT string
9
- *
10
- * @example
11
- * ```ts
12
- * const jwt = await createSession({
13
- * tokens: {
14
- * accessToken: 'token',
15
- * refreshToken: 'refresh',
16
- * },
17
- * user: {
18
- * name: 'John Doe',
19
- * email: 'john@example.com',
20
- * }
21
- * });
22
- * ```
23
13
  */
24
14
  export declare function createSession<TData = Record<string, unknown>>(session: Session<TData>, options?: CreateSessionOptions): Promise<string>;
25
15
  /**
26
- * Retrieves the current session from the "session" cookie, if any.
27
- * Uses React server components' cache for performance.
16
+ * Retrieves the current session from cookies, if any. Wraps the framework-
17
+ * agnostic {@link readSession} with React's `cache` so repeated calls within one
18
+ * server render share a single read.
28
19
  *
29
- * This function:
30
- * 1. Gets the session cookie
31
- * 2. Validates the JWT
32
- * 3. Returns the session if valid, null otherwise
20
+ * The session may carry an expired access token — check `accessTokenExpires`
21
+ * before using it, or refresh via `refreshCurrentSession`.
33
22
  *
34
- * @param config - Optional OAuth config (currently unused, kept for compatibility)
35
- * @returns Session object or null if no valid session exists
23
+ * @param _config - Unused; kept for backwards compatibility.
24
+ * @returns Session object or null if no session exists.
36
25
  *
37
26
  * @example
38
27
  * ```ts
39
- * // In a server component or server action
40
28
  * const session = await getCurrentSession();
41
- * if (session) {
42
- * console.log('User:', session.user);
43
- * } else {
44
- * // User not logged in
45
- * }
29
+ * if (session) console.log('User:', session.user);
46
30
  * ```
47
31
  */
48
- export declare const getCurrentSession: (config?: OAuthConfig) => Promise<Session<any> | null>;
32
+ export declare const getCurrentSession: (_config?: OAuthConfig) => Promise<Session<any> | null>;
49
33
  /**
50
- * Refreshes the current session using the refresh token.
51
- *
52
- * This function:
53
- * 1. Gets the current session
54
- * 2. Uses the refresh token to get new access tokens
55
- * 3. Updates the session cookie with new tokens
56
- * 4. Returns the updated session
34
+ * Refreshes the current session using its refresh token and updates the cookies.
57
35
  *
58
36
  * @param config - OAuth configuration
59
37
  * @param options - Session creation options
@@ -61,45 +39,29 @@ export declare const getCurrentSession: (config?: OAuthConfig) => Promise<Sessio
61
39
  *
62
40
  * @example
63
41
  * ```ts
64
- * const updatedSession = await refreshCurrentSession(oauthConfig);
65
- * if (updatedSession) {
66
- * // Session refreshed successfully
67
- * } else {
68
- * // Refresh failed, user needs to log in again
69
- * redirect('/login');
70
- * }
42
+ * const updated = await refreshCurrentSession(oauthConfig);
43
+ * if (!updated) redirect('/login');
71
44
  * ```
72
45
  */
73
46
  export declare function refreshCurrentSession(config: OAuthConfig, options?: CreateSessionOptions): Promise<Session | null>;
74
47
  /**
75
- * Creates and persists a new session.
76
- *
77
- * This is a convenience function that combines createSession and setSessionCookie.
78
- * Use this after successful authentication to establish a user session.
48
+ * Creates and persists a new session across the session/session_at cookies.
79
49
  *
80
50
  * @param session - Session data
81
- * @param options - Session creation options
82
- * @returns The encrypted JWT that was stored in the cookie
51
+ * @param _options - Session creation options (reserved; not currently applied)
52
+ * @returns The encrypted JWT stored in the main "session" cookie.
83
53
  *
84
54
  * @example
85
55
  * ```ts
86
- * // After successful OAuth callback
87
56
  * await createAndPersistSession({
88
- * tokens: {
89
- * accessToken: tokens.access_token,
90
- * refreshToken: tokens.refresh_token,
91
- * },
92
- * user: {
93
- * name: 'John Doe',
94
- * email: 'john@example.com',
95
- * }
96
- * }, { sessionDurationDays: 30 });
57
+ * tokens: { accessToken: tokens.access_token, refreshToken: tokens.refresh_token },
58
+ * user: { name: 'John Doe', email: 'john@example.com' },
59
+ * });
97
60
  * ```
98
61
  */
99
- export declare function createAndPersistSession(session: Session, options?: CreateSessionOptions): Promise<string>;
62
+ export declare function createAndPersistSession(session: Session, _options?: CreateSessionOptions): Promise<string>;
100
63
  /**
101
- * Clears the current session by deleting the session cookie.
102
- * Use this when logging out or when session validation fails.
64
+ * Clears the current session by deleting the session cookies.
103
65
  *
104
66
  * @example
105
67
  * ```ts
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACjF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAO/D;;;;;;;;;;;;;;;;;;;;GAoBG;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,CAejB;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,iBAAiB,YAAyB,WAAW,KAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAkC9F,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,WAAW,EACnB,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CA+CzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,MAAM,CAAC,CAajB;AAED;;;;;;;;;GASG;AACH,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC,CAUzD"}
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;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,iBAAiB,aACX,WAAW,KAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAG3D,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,uBAAuB,CAC3C,OAAO,EAAE,OAAO,EAChB,QAAQ,GAAE,oBAAyB,GAClC,OAAO,CAAC,MAAM,CAAC,CAEjB;AAED;;;;;;;;GAQG;AACH,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC,CAEzD"}
package/dist/session.js CHANGED
@@ -1,34 +1,22 @@
1
- import { deleteSessionCookie, getSessionCookie, setSessionCookie } from "./cookies.js";
1
+ import { nextCookieStore } from "./cookie-store.js";
2
2
  import { Logger } from "@eventuras/logger";
3
3
  import { createEncryptedJWT, getSessionSecret } from "@eventuras/fides-auth/utils";
4
- import { validateSessionJwt } from "@eventuras/fides-auth/session-validation";
5
- import { refreshSession } from "@eventuras/fides-auth/session-refresh";
4
+ import { clearSession, persistSession, readSession, refreshSessionInStore } from "@eventuras/fides-auth/server";
6
5
  import { cache } from "react";
7
6
  //#region src/session.ts
8
7
  var logger = Logger.create({ namespace: "fides-auth-next:session" });
9
8
  /**
10
9
  * Creates an encrypted JWT containing session data.
11
10
  *
11
+ * Pre-split API: this serializes the whole session, raw tokens included, into one
12
+ * value. Prefer {@link createAndPersistSession}, which splits the large JWTs across
13
+ * cookies instead of spending one cookie's byte budget on all of them.
14
+ *
12
15
  * @param session - Session data (tokens, user, etc.)
13
16
  * @param options - Configuration options (e.g., sessionDurationDays)
14
17
  * @returns Encrypted JWT string
15
- *
16
- * @example
17
- * ```ts
18
- * const jwt = await createSession({
19
- * tokens: {
20
- * accessToken: 'token',
21
- * refreshToken: 'refresh',
22
- * },
23
- * user: {
24
- * name: 'John Doe',
25
- * email: 'john@example.com',
26
- * }
27
- * });
28
- * ```
29
18
  */
30
19
  async function createSession(session, options = {}) {
31
- logger.debug("Creating new session");
32
20
  const { sessionDurationDays = 7 } = options;
33
21
  try {
34
22
  const jwt = await createEncryptedJWT({ ...session }, getSessionSecret());
@@ -40,61 +28,27 @@ async function createSession(session, options = {}) {
40
28
  }
41
29
  }
42
30
  /**
43
- * Retrieves the current session from the "session" cookie, if any.
44
- * Uses React server components' cache for performance.
31
+ * Retrieves the current session from cookies, if any. Wraps the framework-
32
+ * agnostic {@link readSession} with React's `cache` so repeated calls within one
33
+ * server render share a single read.
45
34
  *
46
- * This function:
47
- * 1. Gets the session cookie
48
- * 2. Validates the JWT
49
- * 3. Returns the session if valid, null otherwise
35
+ * The session may carry an expired access token — check `accessTokenExpires`
36
+ * before using it, or refresh via `refreshCurrentSession`.
50
37
  *
51
- * @param config - Optional OAuth config (currently unused, kept for compatibility)
52
- * @returns Session object or null if no valid session exists
38
+ * @param _config - Unused; kept for backwards compatibility.
39
+ * @returns Session object or null if no session exists.
53
40
  *
54
41
  * @example
55
42
  * ```ts
56
- * // In a server component or server action
57
43
  * const session = await getCurrentSession();
58
- * if (session) {
59
- * console.log('User:', session.user);
60
- * } else {
61
- * // User not logged in
62
- * }
44
+ * if (session) console.log('User:', session.user);
63
45
  * ```
64
46
  */
65
- var getCurrentSession = cache(async (config) => {
66
- logger.debug("Retrieving current session");
67
- try {
68
- const sessionCookie = await getSessionCookie();
69
- if (!sessionCookie) {
70
- logger.debug("No session cookie found");
71
- return null;
72
- }
73
- const { status, session } = await validateSessionJwt(sessionCookie, getSessionSecret());
74
- if (status !== "VALID") {
75
- logger.warn({ status }, "Session validation failed");
76
- return null;
77
- }
78
- if (!session) {
79
- logger.warn("Session validation succeeded but no session object returned");
80
- return null;
81
- }
82
- logger.debug("Current session retrieved successfully");
83
- return session;
84
- } catch (error) {
85
- if (error instanceof Error && error.message.includes("worker")) logger.error({ error }, "Worker thread error in getCurrentSession");
86
- else logger.error({ error }, "Unexpected error in getCurrentSession");
87
- return null;
88
- }
47
+ var getCurrentSession = cache(async (_config) => {
48
+ return readSession(await nextCookieStore(), getSessionSecret());
89
49
  });
90
50
  /**
91
- * Refreshes the current session using the refresh token.
92
- *
93
- * This function:
94
- * 1. Gets the current session
95
- * 2. Uses the refresh token to get new access tokens
96
- * 3. Updates the session cookie with new tokens
97
- * 4. Returns the updated session
51
+ * Refreshes the current session using its refresh token and updates the cookies.
98
52
  *
99
53
  * @param config - OAuth configuration
100
54
  * @param options - Session creation options
@@ -102,82 +56,33 @@ var getCurrentSession = cache(async (config) => {
102
56
  *
103
57
  * @example
104
58
  * ```ts
105
- * const updatedSession = await refreshCurrentSession(oauthConfig);
106
- * if (updatedSession) {
107
- * // Session refreshed successfully
108
- * } else {
109
- * // Refresh failed, user needs to log in again
110
- * redirect('/login');
111
- * }
59
+ * const updated = await refreshCurrentSession(oauthConfig);
60
+ * if (!updated) redirect('/login');
112
61
  * ```
113
62
  */
114
63
  async function refreshCurrentSession(config, options = {}) {
115
- logger.info("Starting session refresh");
116
- try {
117
- const currentSession = await getCurrentSession();
118
- if (!currentSession) {
119
- logger.warn("No current session to refresh");
120
- return null;
121
- }
122
- if (!currentSession.tokens?.refreshToken) {
123
- logger.error("Current session has no refresh token");
124
- return null;
125
- }
126
- const updatedSession = await refreshSession(currentSession, config, options);
127
- if (!updatedSession) {
128
- logger.error("Session refresh returned null");
129
- return null;
130
- }
131
- await setSessionCookie(await createSession(updatedSession, options));
132
- logger.info("Session refreshed and cookie updated successfully");
133
- return updatedSession;
134
- } catch (error) {
135
- const err = error;
136
- if (err?.code === "OAUTH_RESPONSE_BODY_ERROR" && err?.error === "invalid_grant") logger.info("Session refresh failed - refresh token expired or invalid");
137
- else logger.error({ error }, "Failed to refresh current session");
138
- return null;
139
- }
64
+ return refreshSessionInStore(await nextCookieStore(), config, getSessionSecret(), options);
140
65
  }
141
66
  /**
142
- * Creates and persists a new session.
143
- *
144
- * This is a convenience function that combines createSession and setSessionCookie.
145
- * Use this after successful authentication to establish a user session.
67
+ * Creates and persists a new session across the session/session_at cookies.
146
68
  *
147
69
  * @param session - Session data
148
- * @param options - Session creation options
149
- * @returns The encrypted JWT that was stored in the cookie
70
+ * @param _options - Session creation options (reserved; not currently applied)
71
+ * @returns The encrypted JWT stored in the main "session" cookie.
150
72
  *
151
73
  * @example
152
74
  * ```ts
153
- * // After successful OAuth callback
154
75
  * await createAndPersistSession({
155
- * tokens: {
156
- * accessToken: tokens.access_token,
157
- * refreshToken: tokens.refresh_token,
158
- * },
159
- * user: {
160
- * name: 'John Doe',
161
- * email: 'john@example.com',
162
- * }
163
- * }, { sessionDurationDays: 30 });
76
+ * tokens: { accessToken: tokens.access_token, refreshToken: tokens.refresh_token },
77
+ * user: { name: 'John Doe', email: 'john@example.com' },
78
+ * });
164
79
  * ```
165
80
  */
166
- async function createAndPersistSession(session, options = {}) {
167
- logger.info("Creating and persisting new session");
168
- try {
169
- const jwt = await createSession(session, options);
170
- await setSessionCookie(jwt);
171
- logger.info("Session created and persisted successfully");
172
- return jwt;
173
- } catch (error) {
174
- logger.error({ error }, "Failed to create and persist session");
175
- throw error;
176
- }
81
+ async function createAndPersistSession(session, _options = {}) {
82
+ return persistSession(await nextCookieStore(), session, getSessionSecret());
177
83
  }
178
84
  /**
179
- * Clears the current session by deleting the session cookie.
180
- * Use this when logging out or when session validation fails.
85
+ * Clears the current session by deleting the session cookies.
181
86
  *
182
87
  * @example
183
88
  * ```ts
@@ -186,14 +91,7 @@ async function createAndPersistSession(session, options = {}) {
186
91
  * ```
187
92
  */
188
93
  async function clearCurrentSession() {
189
- logger.info("Clearing current session");
190
- try {
191
- await deleteSessionCookie();
192
- logger.info("Session cleared successfully");
193
- } catch (error) {
194
- logger.error({ error }, "Failed to clear session");
195
- throw error;
196
- }
94
+ await clearSession(await nextCookieStore());
197
95
  }
198
96
  //#endregion
199
97
  export { clearCurrentSession, createAndPersistSession, createSession, getCurrentSession, refreshCurrentSession };
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { createEncryptedJWT, getSessionSecret } from '@eventuras/fides-auth/utils';\nimport { validateSessionJwt } from '@eventuras/fides-auth/session-validation';\nimport { refreshSession as refreshSessionCore } from '@eventuras/fides-auth/session-refresh';\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';\nimport { getSessionCookie, setSessionCookie, deleteSessionCookie } from './cookies';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:session' });\n\n/**\n * Creates an encrypted JWT containing session data.\n *\n * @param session - Session data (tokens, user, etc.)\n * @param options - Configuration options (e.g., sessionDurationDays)\n * @returns Encrypted JWT string\n *\n * @example\n * ```ts\n * const jwt = await createSession({\n * tokens: {\n * accessToken: 'token',\n * refreshToken: 'refresh',\n * },\n * user: {\n * name: 'John Doe',\n * email: 'john@example.com',\n * }\n * });\n * ```\n */\nexport async function createSession<TData = Record<string, unknown>>(\n session: Session<TData>,\n options: CreateSessionOptions = {}\n): Promise<string> {\n logger.debug('Creating new session');\n\n const { sessionDurationDays = 7 } = options;\n\n try {\n // Build the JWT payload and encrypt\n const jwt = await createEncryptedJWT({ ...session }, getSessionSecret());\n\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 the \"session\" cookie, if any.\n * Uses React server components' cache for performance.\n *\n * This function:\n * 1. Gets the session cookie\n * 2. Validates the JWT\n * 3. Returns the session if valid, null otherwise\n *\n * @param config - Optional OAuth config (currently unused, kept for compatibility)\n * @returns Session object or null if no valid session exists\n *\n * @example\n * ```ts\n * // In a server component or server action\n * const session = await getCurrentSession();\n * if (session) {\n * console.log('User:', session.user);\n * } else {\n * // User not logged in\n * }\n * ```\n */\nexport const getCurrentSession = cache(async (config?: OAuthConfig): Promise<Session<any> | null> => {\n logger.debug('Retrieving current session');\n\n try {\n const sessionCookie = await getSessionCookie();\n\n if (!sessionCookie) {\n logger.debug('No session cookie found');\n return null;\n }\n\n const { status, session } = await validateSessionJwt(sessionCookie, getSessionSecret());\n\n if (status !== 'VALID') {\n logger.warn({ status }, 'Session validation failed');\n return null;\n }\n\n if (!session) {\n logger.warn('Session validation succeeded but no session object returned');\n return null;\n }\n\n logger.debug('Current session retrieved successfully');\n return session;\n } catch (error) {\n // Worker thread errors should not crash the application\n if (error instanceof Error && error.message.includes('worker')) {\n logger.error({ error }, 'Worker thread error in getCurrentSession');\n } else {\n logger.error({ error }, 'Unexpected error in getCurrentSession');\n }\n return null;\n }\n});\n\n/**\n * Refreshes the current session using the refresh token.\n *\n * This function:\n * 1. Gets the current session\n * 2. Uses the refresh token to get new access tokens\n * 3. Updates the session cookie with new tokens\n * 4. Returns the updated session\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 updatedSession = await refreshCurrentSession(oauthConfig);\n * if (updatedSession) {\n * // Session refreshed successfully\n * } else {\n * // Refresh failed, user needs to log in again\n * redirect('/login');\n * }\n * ```\n */\nexport async function refreshCurrentSession(\n config: OAuthConfig,\n options: CreateSessionOptions = {}\n): Promise<Session | null> {\n logger.info('Starting session refresh');\n\n try {\n const currentSession = await getCurrentSession();\n\n if (!currentSession) {\n logger.warn('No current session to refresh');\n return null;\n }\n\n if (!currentSession.tokens?.refreshToken) {\n logger.error('Current session has no refresh token');\n return null;\n }\n\n // Use the core refresh function\n const updatedSession = await refreshSessionCore(currentSession, config, options);\n\n if (!updatedSession) {\n logger.error('Session refresh returned null');\n return null;\n }\n\n // Create new encrypted JWT\n const jwt = await createSession(updatedSession, options);\n\n // Update the session cookie\n await setSessionCookie(jwt);\n\n logger.info('Session refreshed and cookie updated successfully');\n return updatedSession;\n } catch (error) {\n // Check if this is an expected invalid_grant error\n const err = error as { code?: string; error?: string; };\n const isInvalidGrant = err?.code === 'OAUTH_RESPONSE_BODY_ERROR' && err?.error === 'invalid_grant';\n\n if (isInvalidGrant) {\n // Expected during logout/session expiry - log at info level\n logger.info('Session refresh failed - refresh token expired or invalid');\n } else {\n // Unexpected error - log at error level\n logger.error({ error }, 'Failed to refresh current session');\n }\n\n return null;\n }\n}\n\n/**\n * Creates and persists a new session.\n *\n * This is a convenience function that combines createSession and setSessionCookie.\n * Use this after successful authentication to establish a user session.\n *\n * @param session - Session data\n * @param options - Session creation options\n * @returns The encrypted JWT that was stored in the cookie\n *\n * @example\n * ```ts\n * // After successful OAuth callback\n * await createAndPersistSession({\n * tokens: {\n * accessToken: tokens.access_token,\n * refreshToken: tokens.refresh_token,\n * },\n * user: {\n * name: 'John Doe',\n * email: 'john@example.com',\n * }\n * }, { sessionDurationDays: 30 });\n * ```\n */\nexport async function createAndPersistSession(\n session: Session,\n options: CreateSessionOptions = {}\n): Promise<string> {\n logger.info('Creating and persisting new session');\n\n try {\n const jwt = await createSession(session, options);\n await setSessionCookie(jwt);\n\n logger.info('Session created and persisted successfully');\n return jwt;\n } catch (error) {\n logger.error({ error }, 'Failed to create and persist session');\n throw error;\n }\n}\n\n/**\n * Clears the current session by deleting the session cookie.\n * Use this when logging out or when session validation fails.\n *\n * @example\n * ```ts\n * await clearCurrentSession();\n * redirect('/');\n * ```\n */\nexport async function clearCurrentSession(): Promise<void> {\n logger.info('Clearing current session');\n\n try {\n await deleteSessionCookie();\n logger.info('Session cleared successfully');\n } catch (error) {\n logger.error({ error }, 'Failed to clear session');\n throw error;\n }\n}\n"],"mappings":";;;;;;;AASA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,0BAA0B,CAAC;;;;;;;;;;;;;;;;;;;;;;AAuBrE,eAAsB,cACpB,SACA,UAAgC,CAAC,GAChB;CACjB,OAAO,MAAM,sBAAsB;CAEnC,MAAM,EAAE,sBAAsB,MAAM;CAEpC,IAAI;EAEF,MAAM,MAAM,MAAM,mBAAmB,EAAE,GAAG,QAAQ,GAAG,iBAAiB,CAAC;EAEvE,OAAO,KAAK,EAAE,oBAAoB,GAAG,8BAA8B;EACnE,OAAO;CACT,SAAS,OAAO;EACd,OAAO,MAAM,EAAE,MAAM,GAAG,0BAA0B;EAClD,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,oBAAoB,MAAM,OAAO,WAAuD;CACnG,OAAO,MAAM,4BAA4B;CAEzC,IAAI;EACF,MAAM,gBAAgB,MAAM,iBAAiB;EAE7C,IAAI,CAAC,eAAe;GAClB,OAAO,MAAM,yBAAyB;GACtC,OAAO;EACT;EAEA,MAAM,EAAE,QAAQ,YAAY,MAAM,mBAAmB,eAAe,iBAAiB,CAAC;EAEtF,IAAI,WAAW,SAAS;GACtB,OAAO,KAAK,EAAE,OAAO,GAAG,2BAA2B;GACnD,OAAO;EACT;EAEA,IAAI,CAAC,SAAS;GACZ,OAAO,KAAK,6DAA6D;GACzE,OAAO;EACT;EAEA,OAAO,MAAM,wCAAwC;EACrD,OAAO;CACT,SAAS,OAAO;EAEd,IAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,QAAQ,GAC3D,OAAO,MAAM,EAAE,MAAM,GAAG,0CAA0C;OAElE,OAAO,MAAM,EAAE,MAAM,GAAG,uCAAuC;EAEjE,OAAO;CACT;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;AA0BD,eAAsB,sBACpB,QACA,UAAgC,CAAC,GACR;CACzB,OAAO,KAAK,0BAA0B;CAEtC,IAAI;EACF,MAAM,iBAAiB,MAAM,kBAAkB;EAE/C,IAAI,CAAC,gBAAgB;GACnB,OAAO,KAAK,+BAA+B;GAC3C,OAAO;EACT;EAEA,IAAI,CAAC,eAAe,QAAQ,cAAc;GACxC,OAAO,MAAM,sCAAsC;GACnD,OAAO;EACT;EAGA,MAAM,iBAAiB,MAAM,eAAmB,gBAAgB,QAAQ,OAAO;EAE/E,IAAI,CAAC,gBAAgB;GACnB,OAAO,MAAM,+BAA+B;GAC5C,OAAO;EACT;EAMA,MAAM,iBAAiB,MAHL,cAAc,gBAAgB,OAAO,CAG7B;EAE1B,OAAO,KAAK,mDAAmD;EAC/D,OAAO;CACT,SAAS,OAAO;EAEd,MAAM,MAAM;EAGZ,IAFuB,KAAK,SAAS,+BAA+B,KAAK,UAAU,iBAIjF,OAAO,KAAK,2DAA2D;OAGvE,OAAO,MAAM,EAAE,MAAM,GAAG,mCAAmC;EAG7D,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,eAAsB,wBACpB,SACA,UAAgC,CAAC,GAChB;CACjB,OAAO,KAAK,qCAAqC;CAEjD,IAAI;EACF,MAAM,MAAM,MAAM,cAAc,SAAS,OAAO;EAChD,MAAM,iBAAiB,GAAG;EAE1B,OAAO,KAAK,4CAA4C;EACxD,OAAO;CACT,SAAS,OAAO;EACd,OAAO,MAAM,EAAE,MAAM,GAAG,sCAAsC;EAC9D,MAAM;CACR;AACF;;;;;;;;;;;AAYA,eAAsB,sBAAqC;CACzD,OAAO,KAAK,0BAA0B;CAEtC,IAAI;EACF,MAAM,oBAAoB;EAC1B,OAAO,KAAK,8BAA8B;CAC5C,SAAS,OAAO;EACd,OAAO,MAAM,EAAE,MAAM,GAAG,yBAAyB;EACjD,MAAM;CACR;AACF"}
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"}
@@ -98,11 +98,6 @@
98
98
  * });
99
99
  * ```
100
100
  */
101
- export { createAuthStore, initializeAuth, checkAuth, type AuthStoreContext, type AuthStoreConfig, } from './store';
102
- export { createAuthStoreHooks, type AuthStoreSelector, type AuthStoreActions, } from './hooks';
103
- export { startSessionMonitor, type SessionMonitorConfig, } from './session-monitor';
104
- export { useSessionMonitor } from './use-session-monitor';
105
- export { useHeartbeat, type HeartbeatConfig } from './use-heartbeat';
106
- export { configureAuthLogger } from './configure-logger';
107
- export type { SessionUser, AuthStatus } from './types';
101
+ export { createAuthStore, initializeAuth, checkAuth, startSessionMonitor, configureAuthLogger, type AuthStoreContext, type AuthStoreConfig, type SessionMonitorConfig, type SessionUser, type AuthStatus, } from '@eventuras/fides-auth-store';
102
+ export { createAuthStoreHooks, useSessionMonitor, useHeartbeat, type AuthStoreSelector, type AuthStoreActions, type HeartbeatConfig, } from '@eventuras/fides-auth-react';
108
103
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmGG;AAGH,OAAO,EACL,eAAe,EACf,cAAc,EACd,SAAS,EACT,KAAK,gBAAgB,EACrB,KAAK,eAAe,GACrB,MAAM,SAAS,CAAC;AAEjB,OAAO,EACL,oBAAoB,EACpB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,GACtB,MAAM,SAAS,CAAC;AAEjB,OAAO,EACL,mBAAmB,EACnB,KAAK,oBAAoB,GAC1B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D,OAAO,EAAE,YAAY,EAAE,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAErE,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAGzD,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmGG;AAIH,OAAO,EACL,eAAe,EACf,cAAc,EACd,SAAS,EACT,mBAAmB,EACnB,mBAAmB,EACnB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,oBAAoB,EACzB,KAAK,WAAW,EAChB,KAAK,UAAU,GAChB,MAAM,6BAA6B,CAAC;AAIrC,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EACjB,YAAY,EACZ,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,KAAK,eAAe,GACrB,MAAM,6BAA6B,CAAC"}
@@ -1,7 +1,3 @@
1
- import { checkAuth, createAuthStore, initializeAuth } from "./store.js";
2
- import { createAuthStoreHooks } from "./hooks.js";
3
- import { startSessionMonitor } from "./session-monitor.js";
4
- import { useSessionMonitor } from "./use-session-monitor.js";
5
- import { useHeartbeat } from "./use-heartbeat.js";
6
- import { configureAuthLogger } from "./configure-logger.js";
1
+ import { checkAuth, configureAuthLogger, createAuthStore, initializeAuth, startSessionMonitor } from "@eventuras/fides-auth-store";
2
+ import { createAuthStoreHooks, useHeartbeat, useSessionMonitor } from "@eventuras/fides-auth-react";
7
3
  export { checkAuth, configureAuthLogger, createAuthStore, createAuthStoreHooks, initializeAuth, startSessionMonitor, useHeartbeat, useSessionMonitor };