@monocloud/auth-nextjs 0.1.9 → 0.1.11

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 (97) hide show
  1. package/README.md +1 -1
  2. package/dist/{chunk-C0xms8kb.cjs → _virtual/_rolldown/runtime.cjs} +1 -6
  3. package/dist/client/index.cjs +3 -2
  4. package/dist/client/index.d.mts +3 -203
  5. package/dist/client/index.mjs +2 -1
  6. package/dist/{protect-client-page-BdsnH8gs.cjs → client/protect-client-page.cjs} +9 -112
  7. package/dist/client/protect-client-page.cjs.map +1 -0
  8. package/dist/client/protect-client-page.d.mts +123 -0
  9. package/dist/{protect-client-page-BFVskb3X.mjs → client/protect-client-page.mjs} +5 -91
  10. package/dist/client/protect-client-page.mjs.map +1 -0
  11. package/dist/client/use-auth.cjs +96 -0
  12. package/dist/client/use-auth.cjs.map +1 -0
  13. package/dist/client/use-auth.d.mts +84 -0
  14. package/dist/client/use-auth.mjs +94 -0
  15. package/dist/client/use-auth.mjs.map +1 -0
  16. package/dist/components/client/index.cjs +4 -156
  17. package/dist/components/client/index.d.mts +3 -189
  18. package/dist/components/client/index.mjs +3 -153
  19. package/dist/components/client/protected.cjs +89 -0
  20. package/dist/components/client/protected.cjs.map +1 -0
  21. package/dist/components/client/protected.d.mts +114 -0
  22. package/dist/components/client/protected.mjs +87 -0
  23. package/dist/components/client/protected.mjs.map +1 -0
  24. package/dist/components/client/redirect-to-signin.cjs +77 -0
  25. package/dist/components/client/redirect-to-signin.cjs.map +1 -0
  26. package/dist/components/client/redirect-to-signin.d.mts +78 -0
  27. package/dist/components/client/redirect-to-signin.mjs +76 -0
  28. package/dist/components/client/redirect-to-signin.mjs.map +1 -0
  29. package/dist/components/index.cjs +6 -168
  30. package/dist/components/index.d.mts +4 -188
  31. package/dist/components/index.mjs +4 -164
  32. package/dist/components/signin.cjs +63 -0
  33. package/dist/components/signin.cjs.map +1 -0
  34. package/dist/components/signin.d.mts +72 -0
  35. package/dist/components/signin.mjs +61 -0
  36. package/dist/components/signin.mjs.map +1 -0
  37. package/dist/components/signout.cjs +49 -0
  38. package/dist/components/signout.cjs.map +1 -0
  39. package/dist/components/signout.d.mts +55 -0
  40. package/dist/components/signout.mjs +47 -0
  41. package/dist/components/signout.mjs.map +1 -0
  42. package/dist/components/signup.cjs +67 -0
  43. package/dist/components/signup.cjs.map +1 -0
  44. package/dist/components/signup.d.mts +70 -0
  45. package/dist/components/signup.mjs +65 -0
  46. package/dist/components/signup.mjs.map +1 -0
  47. package/dist/index.cjs +15 -1136
  48. package/dist/index.d.mts +5 -1681
  49. package/dist/index.mjs +4 -1125
  50. package/dist/initialize.cjs +284 -0
  51. package/dist/initialize.cjs.map +1 -0
  52. package/dist/initialize.d.mts +1383 -0
  53. package/dist/initialize.mjs +274 -0
  54. package/dist/initialize.mjs.map +1 -0
  55. package/dist/monocloud-next-client.cjs +600 -0
  56. package/dist/monocloud-next-client.cjs.map +1 -0
  57. package/dist/monocloud-next-client.d.mts +330 -0
  58. package/dist/monocloud-next-client.mjs +599 -0
  59. package/dist/monocloud-next-client.mjs.map +1 -0
  60. package/dist/requests/monocloud-app-router-request.cjs +32 -0
  61. package/dist/requests/monocloud-app-router-request.cjs.map +1 -0
  62. package/dist/requests/monocloud-app-router-request.mjs +31 -0
  63. package/dist/requests/monocloud-app-router-request.mjs.map +1 -0
  64. package/dist/requests/monocloud-cookie-request.cjs +22 -0
  65. package/dist/requests/monocloud-cookie-request.cjs.map +1 -0
  66. package/dist/requests/monocloud-cookie-request.mjs +21 -0
  67. package/dist/requests/monocloud-cookie-request.mjs.map +1 -0
  68. package/dist/requests/monocloud-page-router-request.cjs +37 -0
  69. package/dist/requests/monocloud-page-router-request.cjs.map +1 -0
  70. package/dist/requests/monocloud-page-router-request.mjs +36 -0
  71. package/dist/requests/monocloud-page-router-request.mjs.map +1 -0
  72. package/dist/responses/monocloud-app-router-response.cjs +67 -0
  73. package/dist/responses/monocloud-app-router-response.cjs.map +1 -0
  74. package/dist/responses/monocloud-app-router-response.mjs +66 -0
  75. package/dist/responses/monocloud-app-router-response.mjs.map +1 -0
  76. package/dist/responses/monocloud-cookie-response.cjs +20 -0
  77. package/dist/responses/monocloud-cookie-response.cjs.map +1 -0
  78. package/dist/responses/monocloud-cookie-response.mjs +19 -0
  79. package/dist/responses/monocloud-cookie-response.mjs.map +1 -0
  80. package/dist/responses/monocloud-page-router-response.cjs +54 -0
  81. package/dist/responses/monocloud-page-router-response.cjs.map +1 -0
  82. package/dist/responses/monocloud-page-router-response.mjs +53 -0
  83. package/dist/responses/monocloud-page-router-response.mjs.map +1 -0
  84. package/dist/{types-ClljFIvK.d.mts → types.d.mts} +2 -2
  85. package/dist/utils.cjs +89 -0
  86. package/dist/utils.cjs.map +1 -0
  87. package/dist/utils.mjs +80 -0
  88. package/dist/utils.mjs.map +1 -0
  89. package/package.json +3 -3
  90. package/dist/components/client/index.cjs.map +0 -1
  91. package/dist/components/client/index.mjs.map +0 -1
  92. package/dist/components/index.cjs.map +0 -1
  93. package/dist/components/index.mjs.map +0 -1
  94. package/dist/index.cjs.map +0 -1
  95. package/dist/index.mjs.map +0 -1
  96. package/dist/protect-client-page-BFVskb3X.mjs.map +0 -1
  97. package/dist/protect-client-page-BdsnH8gs.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"monocloud-next-client.cjs","names":["MonoCloudCoreClient","isAppRouter","MonoCloudAppRouterRequest","getNextRequest","MonoCloudAppRouterResponse","getNextResponse","MonoCloudPageRouterRequest","MonoCloudPageRouterResponse","NextResponse","mergeResponse","MonoCloudCookieRequest","MonoCloudCookieResponse","getMonoCloudCookieReqRes","isNodeRequest","isNodeResponse","isMonoCloudRequest","isMonoCloudResponse","MonoCloudValidationError"],"sources":["../src/monocloud-next-client.ts"],"sourcesContent":["/* eslint-disable import/extensions */\n/* eslint-disable @typescript-eslint/no-non-null-assertion */\nimport type {\n monoCloudAuth,\n protect,\n protectPage,\n authMiddleware,\n getSession,\n getTokens,\n isAuthenticated,\n isUserInGroup,\n redirectToSignIn,\n redirectToSignOut,\n} from './initialize';\nimport {\n NextFetchEvent,\n NextRequest,\n NextResponse,\n NextMiddleware,\n NextProxy,\n} from 'next/server.js';\nimport type {\n NextApiHandler,\n NextApiRequest,\n NextApiResponse,\n} from 'next/types';\nimport {\n ensureLeadingSlash,\n isAbsoluteUrl,\n} from '@monocloud/auth-node-core/internal';\nimport { isUserInGroup as isUserInGroupCore } from '@monocloud/auth-node-core/utils';\nimport type {\n GetSessionOptions,\n GetTokensOptions,\n IMonoCloudCookieRequest,\n IMonoCloudCookieResponse,\n MonoCloudOptions,\n MonoCloudRequest,\n MonoCloudResponse,\n MonoCloudTokens,\n MonoCloudSession,\n OnError,\n} from '@monocloud/auth-node-core';\nimport { MonoCloudOidcClient } from '@monocloud/auth-core';\nimport {\n MonoCloudCoreClient,\n MonoCloudValidationError,\n} from '@monocloud/auth-node-core';\nimport {\n AppRouterApiHandlerFn,\n AppRouterContext,\n AppRouterPageHandler,\n IsUserInGroupOptions,\n MonoCloudAuthHandler,\n MonoCloudAuthOptions,\n MonoCloudMiddlewareOptions,\n NextMiddlewareResult,\n ProtectApiAppOptions,\n ProtectApiPageOptions,\n ProtectAppPageOptions,\n ProtectedAppServerComponent,\n ProtectOptions,\n ProtectPagePageOptions,\n ProtectPagePageReturnType,\n RedirectToSignInOptions,\n RedirectToSignOutOptions,\n} from './types';\nimport {\n getMonoCloudCookieReqRes,\n getNextRequest,\n getNextResponse,\n isAppRouter,\n isMonoCloudRequest,\n isMonoCloudResponse,\n mergeResponse,\n isNodeRequest,\n isNodeResponse,\n} from './utils';\nimport MonoCloudCookieRequest from './requests/monocloud-cookie-request';\nimport MonoCloudCookieResponse from './responses/monocloud-cookie-response';\nimport MonoCloudAppRouterRequest from './requests/monocloud-app-router-request';\nimport MonoCloudAppRouterResponse from './responses/monocloud-app-router-response';\nimport type { JSX } from 'react';\nimport type { ParsedUrlQuery } from 'node:querystring';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport MonoCloudPageRouterRequest from './requests/monocloud-page-router-request';\nimport MonoCloudPageRouterResponse from './responses/monocloud-page-router-response';\n\n/**\n * `MonoCloudNextClient` is the core SDK entry point for integrating MonoCloud authentication into a Next.js application.\n *\n * It provides:\n * - Authentication middleware\n * - Route protection helpers\n * - Session and token access\n * - Redirect utilities\n * - Server-side enforcement helpers\n *\n * ## 1. Add environment variables\n *\n * ```bash:.env.local\n * MONOCLOUD_AUTH_TENANT_DOMAIN=<tenant-domain>\n * MONOCLOUD_AUTH_CLIENT_ID=<client-id>\n * MONOCLOUD_AUTH_CLIENT_SECRET=<client-secret>\n * MONOCLOUD_AUTH_SCOPES=openid profile email\n * MONOCLOUD_AUTH_APP_URL=http://localhost:3000\n * MONOCLOUD_AUTH_COOKIE_SECRET=<cookie-secret>\n * ```\n *\n * ## 2. Register middleware\n *\n * ```typescript:src/proxy.ts\n * import { authMiddleware } from \"@monocloud/auth-nextjs\";\n *\n * export default authMiddleware();\n *\n * export const config = {\n * matcher: [\n * \"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)\",\n * ],\n * };\n * ```\n *\n * ## Advanced usage\n *\n * ### Create a shared client instance\n *\n * By default, the SDK exposes function exports (for example, `authMiddleware()`, `getSession()`, `getTokens()`) that internally use a shared singleton `MonoCloudNextClient`.\n *\n * Create your own `MonoCloudNextClient` instance when you need multiple configurations, dependency injection, or explicit control over initialization.\n *\n * ```ts:src/monocloud.ts\n * import { MonoCloudNextClient } from \"@monocloud/auth-nextjs\";\n *\n * export const monoCloud = new MonoCloudNextClient();\n * ```\n *\n * ### Using instance methods\n *\n * Once you create a client instance, call methods directly on it instead of using the default function exports.\n *\n * ```ts:src/app/page.tsx\n * import { monoCloud } from \"@/monocloud\";\n *\n * export default async function Page() {\n * const session = await monoCloud.getSession();\n *\n * if (!session) {\n * return <>Not signed in</>;\n * }\n *\n * return <>Hello {session.user.name}</>;\n * }\n * ```\n *\n * #### Using constructor options\n *\n * When configuration is provided through both constructor options and environment variables, the values passed to the constructor take precedence. Environment variables are used only for options that are not explicitly supplied.\n *\n * ```ts:src/monocloud.ts\n * import { MonoCloudNextClient } from \"@monocloud/auth-nextjs\";\n *\n * export const monoCloud = new MonoCloudNextClient({\n * tenantDomain: \"<tenant-domain>\",\n * clientId: \"<client-id>\",\n * clientSecret: \"<client-secret>\",\n * appUrl: \"http://localhost:3000\",\n * cookieSecret: \"<cookie-secret>\",\n * defaultAuthParams: {\n * scopes: \"openid profile email\",\n * },\n * });\n * ```\n *\n * ### Modifying default routes\n *\n * If you customize any of the default auth route paths:\n *\n * - Also set the corresponding `NEXT_PUBLIC_` environment variables so client-side helpers\n * (for example `<SignIn />`, `<SignOut />`, and `useAuth()`) can discover the correct URLs.\n * - Update the **Application URLs** in your MonoCloud Dashboard to match the new paths.\n *\n * Example:\n *\n * ```bash:.env.local\n * MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback\n * NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback\n * ```\n *\n * When routes are overridden, the Redirect URI configured in the dashboard\n * must reflect the new path. For example, during local development:\n *\n * `http://localhost:3000/api/custom_callback`\n *\n * @category Classes\n */\nexport class MonoCloudNextClient {\n private readonly _coreClient: MonoCloudCoreClient;\n\n /**\n * This exposes the framework-agnostic MonoCloud client used internally by the Next.js SDK.\n * Use it if you need access to lower-level functionality not directly exposed by MonoCloudNextClient.\n *\n * @returns Returns the underlying **Node client** instance.\n */\n public get coreClient(): MonoCloudCoreClient {\n return this._coreClient;\n }\n\n /**\n * This is intended for advanced scenarios requiring direct control over the authorization or token flow.\n *\n * @returns Returns the underlying **OIDC client** used for OpenID Connect operations.\n */\n public get oidcClient(): MonoCloudOidcClient {\n return this.coreClient.oidcClient;\n }\n\n /**\n * Creates a new client instance.\n *\n * @param options Optional configuration for initializing the MonoCloud client. If not provided, settings are automatically resolved from environment variables.\n */\n constructor(options?: MonoCloudOptions) {\n const opt = {\n ...(options ?? {}),\n userAgent: options?.userAgent ?? `${SDK_NAME}@${SDK_VERSION}`,\n debugger: options?.debugger ?? SDK_DEBUGGER_NAME,\n };\n\n this.registerPublicEnvVariables();\n this._coreClient = new MonoCloudCoreClient(opt);\n }\n\n /**\n * @see {@link monoCloudAuth} for full docs and examples.\n * @param options Optional configuration for the auth handler.\n * @returns Returns a Next.js-compatible handler for App Router route handlers or Pages Router API routes.\n */\n public monoCloudAuth(options?: MonoCloudAuthOptions): MonoCloudAuthHandler {\n return (req, resOrCtx) => {\n const { routes, appUrl } = this.getOptions();\n\n let { url = '' } = req;\n\n if (!isAbsoluteUrl(url)) {\n url = new URL(url, appUrl).toString();\n }\n\n const route = new URL(url);\n\n let onError;\n if (typeof options?.onError === 'function') {\n onError = (\n error: Error\n ): void | NextResponse | Promise<void | NextResponse<unknown>> =>\n options.onError!(req as any, resOrCtx as any, error);\n }\n\n let request: MonoCloudRequest;\n let response: MonoCloudResponse;\n\n if (isAppRouter(req)) {\n request = new MonoCloudAppRouterRequest(getNextRequest(req as Request));\n response = new MonoCloudAppRouterResponse(\n getNextResponse(resOrCtx as Response)\n );\n } else {\n request = new MonoCloudPageRouterRequest(req as NextApiRequest);\n response = new MonoCloudPageRouterResponse(resOrCtx as NextApiResponse);\n }\n\n return this.handleAuthRoutes(\n request,\n response,\n route.pathname,\n routes,\n onError\n );\n };\n }\n\n /**\n * @see {@link protectPage} for full docs and examples.\n * @param component The App Router server component to protect.\n * @param options Optional configuration for authentication, authorization, and custom access handling (`onAccessDenied`, `onGroupAccessDenied`).\n * @returns A wrapped page component that enforces authentication before rendering.\n */\n protectPage(\n component: ProtectedAppServerComponent,\n options?: ProtectAppPageOptions\n ): AppRouterPageHandler;\n\n /**\n * @see {@link protectPage} for full docs and examples.\n * @param options Optional configuration for authentication, authorization, and custom access handling (`onAccessDenied`, `onGroupAccessDenied`).\n * @typeParam P - Props returned from `getServerSideProps`.\n * @typeParam Q - Query parameters parsed from the URL.\n * @returns A getServerSideProps wrapper that enforces authentication before executing the page logic.\n */\n protectPage<\n P extends Record<string, any> = Record<string, any>,\n Q extends ParsedUrlQuery = ParsedUrlQuery,\n >(options?: ProtectPagePageOptions<P, Q>): ProtectPagePageReturnType<P, Q>;\n\n public protectPage(...args: unknown[]): any {\n if (typeof args[0] === 'function') {\n return this.protectAppPage(\n args[0] as AppRouterPageHandler,\n args[1] as ProtectAppPageOptions\n ) as any;\n }\n\n return this.protectPagePage(\n args[0] as ProtectPagePageOptions\n ) as ProtectPagePageReturnType<any, any>;\n }\n\n private protectAppPage(\n component: ProtectedAppServerComponent,\n options?: ProtectAppPageOptions\n ): AppRouterPageHandler {\n return async params => {\n const session = await this.getSession();\n\n if (!session) {\n if (options?.onAccessDenied) {\n return options.onAccessDenied({ ...params });\n }\n\n const { routes, appUrl } = this.getOptions();\n\n // @ts-expect-error Cannot find module 'next/headers'\n const { headers } = await import('next/headers');\n\n const path = (await headers()).get('x-monocloud-path');\n\n const signInRoute = new URL(\n `${appUrl}${ensureLeadingSlash(routes!.signIn)}`\n );\n\n signInRoute.searchParams.set(\n 'return_url',\n options?.returnUrl ?? path ?? '/'\n );\n\n if (options?.authParams?.scopes) {\n signInRoute.searchParams.set('scope', options.authParams.scopes);\n }\n if (options?.authParams?.resource) {\n signInRoute.searchParams.set('resource', options.authParams.resource);\n }\n\n if (options?.authParams?.acrValues) {\n signInRoute.searchParams.set(\n 'acr_values',\n options.authParams.acrValues.join(' ')\n );\n }\n\n if (options?.authParams?.display) {\n signInRoute.searchParams.set('display', options.authParams.display);\n }\n\n if (options?.authParams?.prompt) {\n signInRoute.searchParams.set('prompt', options.authParams.prompt);\n }\n\n if (options?.authParams?.authenticatorHint) {\n signInRoute.searchParams.set(\n 'authenticator_hint',\n options.authParams.authenticatorHint\n );\n }\n\n if (options?.authParams?.uiLocales) {\n signInRoute.searchParams.set(\n 'ui_locales',\n options.authParams.uiLocales\n );\n }\n\n if (options?.authParams?.maxAge) {\n signInRoute.searchParams.set(\n 'max_age',\n options.authParams.maxAge.toString()\n );\n }\n\n if (options?.authParams?.loginHint) {\n signInRoute.searchParams.set(\n 'login_hint',\n options.authParams.loginHint\n );\n }\n\n // @ts-expect-error Cannot find module 'next/navigation'\n const { redirect } = await import('next/navigation');\n\n return redirect(signInRoute.toString());\n }\n\n if (\n options?.groups &&\n !isUserInGroupCore(\n session.user,\n options.groups,\n options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM,\n options.matchAll\n )\n ) {\n if (options.onGroupAccessDenied) {\n return options.onGroupAccessDenied({\n ...params,\n user: session.user,\n });\n }\n\n return 'Access Denied' as unknown as JSX.Element;\n }\n\n return component({ ...params, user: session.user });\n };\n }\n\n private protectPagePage<\n P extends Record<string, any> = Record<string, any>,\n Q extends ParsedUrlQuery = ParsedUrlQuery,\n >(options?: ProtectPagePageOptions<P, Q>): ProtectPagePageReturnType<P, Q> {\n return async context => {\n const session = await this.getSession(\n context.req as any,\n context.res as any\n );\n\n if (!session) {\n if (options?.onAccessDenied) {\n const customProps: any = await options.onAccessDenied({\n ...context,\n });\n\n const props = {\n ...(customProps ?? {}),\n props: { ...(customProps?.props ?? {}) },\n };\n\n return props;\n }\n\n const { routes, appUrl } = this.getOptions();\n\n const signInRoute = new URL(\n `${appUrl}${ensureLeadingSlash(routes!.signIn)}`\n );\n\n signInRoute.searchParams.set(\n 'return_url',\n options?.returnUrl ?? context.resolvedUrl\n );\n\n if (options?.authParams?.scopes) {\n signInRoute.searchParams.set('scope', options.authParams.scopes);\n }\n if (options?.authParams?.resource) {\n signInRoute.searchParams.set('resource', options.authParams.resource);\n }\n\n if (options?.authParams?.acrValues) {\n signInRoute.searchParams.set(\n 'acr_values',\n options.authParams.acrValues.join(' ')\n );\n }\n\n if (options?.authParams?.display) {\n signInRoute.searchParams.set('display', options.authParams.display);\n }\n\n if (options?.authParams?.prompt) {\n signInRoute.searchParams.set('prompt', options.authParams.prompt);\n }\n\n if (options?.authParams?.authenticatorHint) {\n signInRoute.searchParams.set(\n 'authenticator_hint',\n options.authParams.authenticatorHint\n );\n }\n\n if (options?.authParams?.uiLocales) {\n signInRoute.searchParams.set(\n 'ui_locales',\n options.authParams.uiLocales\n );\n }\n\n if (options?.authParams?.maxAge) {\n signInRoute.searchParams.set(\n 'max_age',\n options.authParams.maxAge.toString()\n );\n }\n\n if (options?.authParams?.loginHint) {\n signInRoute.searchParams.set(\n 'login_hint',\n options.authParams.loginHint\n );\n }\n\n return {\n redirect: {\n destination: signInRoute.toString(),\n permanent: false,\n },\n };\n }\n\n if (\n options?.groups &&\n !isUserInGroupCore(\n session.user,\n options.groups,\n options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM,\n options.matchAll\n )\n ) {\n const customProps: any = (await options.onGroupAccessDenied?.({\n ...context,\n user: session.user,\n })) ?? { props: { groupAccessDenied: true } };\n\n const props = {\n ...customProps,\n props: { ...(customProps.props ?? {}) },\n };\n\n return props;\n }\n\n const customProps: any = options?.getServerSideProps\n ? await options.getServerSideProps(context)\n : {};\n\n const promiseProp = customProps.props;\n\n if (promiseProp instanceof Promise) {\n return {\n ...customProps,\n props: promiseProp.then((props: any) => ({\n user: session.user,\n ...props,\n })),\n };\n }\n\n return {\n ...customProps,\n props: { user: session.user, ...customProps.props },\n };\n };\n }\n\n /**\n * @see {@link protectApi} for full docs and examples.\n * @param handler The route handler to protect.\n * @param options Optional configuration controlling authentication and authorization behavior.\n * @returns Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.\n */\n protectApi(\n handler: AppRouterApiHandlerFn,\n options?: ProtectApiAppOptions\n ): AppRouterApiHandlerFn;\n\n /**\n * @see {@link protectApi} for full docs and examples.\n * @param handler - The route handler to protect.\n * @param options Optional configuration controlling authentication and authorization behavior.\n * @returns Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.\n */\n protectApi(\n handler: NextApiHandler,\n options?: ProtectApiPageOptions\n ): NextApiHandler;\n\n public protectApi(\n handler: AppRouterApiHandlerFn | NextApiHandler,\n options?: ProtectApiAppOptions | ProtectApiPageOptions\n ): AppRouterApiHandlerFn | NextApiHandler {\n return (\n req: NextRequest | NextApiRequest,\n resOrCtx: AppRouterContext | NextApiResponse\n ) => {\n if (isAppRouter(req)) {\n return this.protectAppApi(\n req as NextRequest,\n resOrCtx as AppRouterContext,\n handler as AppRouterApiHandlerFn,\n options as ProtectApiAppOptions\n );\n }\n return this.protectPageApi(\n req as NextApiRequest,\n resOrCtx as NextApiResponse,\n handler as NextApiHandler,\n options as ProtectApiPageOptions\n );\n };\n }\n\n private async protectAppApi(\n req: NextRequest,\n ctx: AppRouterContext,\n handler: AppRouterApiHandlerFn,\n options?: ProtectApiAppOptions\n ): Promise<NextResponse> {\n const res = new NextResponse();\n\n const session = await this.getSession(req, res);\n\n if (!session) {\n if (options?.onAccessDenied) {\n const result = await options.onAccessDenied(req, ctx);\n\n if (result instanceof NextResponse) {\n return mergeResponse([res, result]);\n }\n\n return mergeResponse([res, new NextResponse(result.body, result)]);\n }\n\n return mergeResponse([\n res,\n NextResponse.json({ message: 'unauthorized' }, { status: 401 }),\n ]);\n }\n\n if (\n options?.groups &&\n !isUserInGroupCore(\n session.user,\n options.groups,\n options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM,\n options.matchAll\n )\n ) {\n if (options.onGroupAccessDenied) {\n const result = await options.onGroupAccessDenied(\n req,\n ctx,\n session.user\n );\n\n if (result instanceof NextResponse) {\n return mergeResponse([res, result]);\n }\n\n return mergeResponse([res, new NextResponse(result.body, result)]);\n }\n\n return mergeResponse([\n res,\n NextResponse.json({ message: 'forbidden' }, { status: 403 }),\n ]);\n }\n\n const resp = await handler(req, ctx);\n\n if (resp instanceof NextResponse) {\n return mergeResponse([res, resp]);\n }\n\n return mergeResponse([res, new NextResponse(resp.body, resp)]);\n }\n\n private async protectPageApi(\n req: NextApiRequest,\n res: NextApiResponse,\n handler: NextApiHandler,\n options?: ProtectApiPageOptions\n ): Promise<unknown> {\n const session = await this.getSession(req, res);\n\n if (!session) {\n if (options?.onAccessDenied) {\n return options.onAccessDenied(req, res);\n }\n\n return res.status(401).json({\n message: 'unauthorized',\n });\n }\n\n if (\n options?.groups &&\n !isUserInGroupCore(\n session.user,\n options.groups,\n options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM,\n options.matchAll\n )\n ) {\n if (options.onGroupAccessDenied) {\n return options.onGroupAccessDenied(req, res, session.user);\n }\n\n return res.status(403).json({\n message: 'forbidden',\n });\n }\n\n return handler(req, res);\n }\n\n /**\n * @see {@link authMiddleware} for full docs and examples.\n * @param options Optional configuration that controls how authentication is enforced (for example, redirect behavior, route matching, or custom handling of unauthenticated requests).\n * @returns Returns a Next.js middleware result (`NextResponse`, redirect, or `undefined` to continue processing).\n */\n authMiddleware(\n options?: MonoCloudMiddlewareOptions\n ): NextMiddleware | NextProxy;\n\n /**\n * @see {@link authMiddleware} for full docs and examples.\n * @param request Incoming Next.js middleware request used to resolve authentication state.\n * @param event Next.js middleware event providing lifecycle hooks such as `waitUntil`.\n * @returns Returns a Next.js middleware result (`NextResponse`, redirect, or `undefined` to continue processing).\n */\n authMiddleware(\n request: NextRequest,\n event: NextFetchEvent\n ): Promise<NextMiddlewareResult> | NextMiddlewareResult;\n\n public authMiddleware(\n ...args: any[]\n ):\n | NextMiddleware\n | NextProxy\n | Promise<NextMiddlewareResult>\n | NextMiddlewareResult {\n let req: NextRequest | undefined;\n let evt: NextFetchEvent | undefined;\n let options: MonoCloudMiddlewareOptions | undefined;\n\n /* v8 ignore else -- @preserve */\n if (Array.isArray(args)) {\n if (args.length === 2) {\n /* v8 ignore else -- @preserve */\n if (isAppRouter(args[0])) {\n req = args[0] as NextRequest;\n evt = args[1] as NextFetchEvent;\n }\n }\n\n if (args.length === 1) {\n options = args[0] as MonoCloudMiddlewareOptions;\n }\n }\n\n if (req && evt) {\n return this.authMiddlewareHandler(req, evt, options) as any;\n }\n\n return (request: NextRequest, nxtEvt: NextFetchEvent) => {\n return this.authMiddlewareHandler(request, nxtEvt, options);\n };\n }\n\n private async authMiddlewareHandler(\n req: NextRequest,\n evt: NextFetchEvent,\n options?: MonoCloudMiddlewareOptions\n ): Promise<NextMiddlewareResult> {\n // eslint-disable-next-line no-param-reassign\n req = getNextRequest(req);\n\n if (req.headers.has('x-middleware-subrequest')) {\n return NextResponse.json({ message: 'forbidden' }, { status: 403 });\n }\n\n const { routes, appUrl } = this.getOptions();\n\n if (\n Object.values(routes!)\n .map(x => ensureLeadingSlash(x))\n .includes(req.nextUrl.pathname)\n ) {\n let onError;\n if (typeof options?.onError === 'function') {\n onError = (\n error: Error\n ):\n | Promise<void | NextResponse<unknown>>\n | void\n | NextResponse<unknown> => options.onError!(req, evt, error);\n }\n\n const request = new MonoCloudAppRouterRequest(req);\n const response = new MonoCloudAppRouterResponse(new NextResponse());\n\n return this.handleAuthRoutes(\n request,\n response,\n req.nextUrl.pathname,\n routes,\n onError\n );\n }\n\n const nxtResp = new NextResponse();\n\n nxtResp.headers.set(\n 'x-monocloud-path',\n req.nextUrl.pathname + req.nextUrl.search\n );\n\n let isRouteProtected = true;\n let allowedGroups: string[] | undefined;\n\n if (typeof options?.protectedRoutes === 'function') {\n isRouteProtected = await options.protectedRoutes(req);\n } else if (\n typeof options?.protectedRoutes !== 'undefined' &&\n Array.isArray(options.protectedRoutes)\n ) {\n isRouteProtected = options.protectedRoutes.some(route => {\n if (typeof route === 'string' || route instanceof RegExp) {\n return new RegExp(route).test(req.nextUrl.pathname);\n }\n\n return route.routes.some(groupRoute => {\n const result = new RegExp(groupRoute).test(req.nextUrl.pathname);\n\n if (result) {\n allowedGroups = route.groups;\n }\n\n return result;\n });\n });\n }\n\n if (!isRouteProtected) {\n return NextResponse.next({\n headers: {\n 'x-monocloud-path': req.nextUrl.pathname + req.nextUrl.search,\n },\n });\n }\n\n const session = await this.getSession(req, nxtResp);\n\n if (!session) {\n if (options?.onAccessDenied) {\n const result = await options.onAccessDenied(req, evt);\n\n if (result instanceof NextResponse) {\n return mergeResponse([nxtResp, result]);\n }\n\n if (result) {\n return mergeResponse([\n nxtResp,\n new NextResponse(result.body, result),\n ]);\n }\n\n return NextResponse.next(nxtResp);\n }\n\n if (req.nextUrl.pathname.startsWith('/api')) {\n return mergeResponse([\n nxtResp,\n NextResponse.json({ message: 'unauthorized' }, { status: 401 }),\n ]);\n }\n\n const signInRoute = new URL(\n `${appUrl}${ensureLeadingSlash(routes!.signIn)}`\n );\n\n signInRoute.searchParams.set(\n 'return_url',\n req.nextUrl.pathname + req.nextUrl.search\n );\n\n return mergeResponse([nxtResp, NextResponse.redirect(signInRoute)]);\n }\n\n const groupsClaim =\n options?.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM;\n\n if (\n allowedGroups &&\n !isUserInGroupCore(session.user, allowedGroups, groupsClaim)\n ) {\n if (options?.onGroupAccessDenied) {\n const result = await options.onGroupAccessDenied(\n req,\n evt,\n session.user\n );\n\n if (result instanceof NextResponse) {\n return mergeResponse([nxtResp, result]);\n }\n\n if (result) {\n return mergeResponse([\n nxtResp,\n new NextResponse(result.body, result),\n ]);\n }\n\n return NextResponse.next(nxtResp);\n }\n\n if (req.nextUrl.pathname.startsWith('/api')) {\n return mergeResponse([\n nxtResp,\n NextResponse.json({ message: 'forbidden' }, { status: 403 }),\n ]);\n }\n\n return new NextResponse(`forbidden`, {\n status: 403,\n });\n }\n\n return NextResponse.next(nxtResp);\n }\n\n private handleAuthRoutes(\n request: MonoCloudRequest,\n response: MonoCloudResponse,\n path: string,\n routes: MonoCloudOptions['routes'],\n onError?: OnError\n ): Promise<any> {\n switch (path) {\n case ensureLeadingSlash(routes!.signIn):\n return this.coreClient.signIn(request, response, {\n onError,\n });\n\n case ensureLeadingSlash(routes!.callback):\n return this.coreClient.callback(request, response, {\n onError,\n });\n\n case ensureLeadingSlash(routes!.userInfo):\n return this.coreClient.userInfo(request, response, {\n onError,\n });\n\n case ensureLeadingSlash(routes!.signOut):\n return this.coreClient.signOut(request, response, {\n onError,\n });\n\n default:\n response.notFound();\n return response.done();\n }\n }\n\n /**\n * @see {@link getSession} for full docs and examples.\n * @param options Optional configuration controlling session retrieval behavior.\n * @returns Returns the resolved session, or `undefined` if none exists.\n */\n public getSession(\n options?: GetSessionOptions\n ): Promise<MonoCloudSession | undefined>;\n\n /**\n * @see {@link getSession} for full docs and examples.\n * @param req Incoming request used to read authentication cookies and headers to resolve the current user's session.\n * @param options Optional configuration controlling session retrieval behavior.\n * @returns Returns the resolved session, or `undefined` if none exists.\n */\n public getSession(\n req: NextRequest | Request,\n options?: GetSessionOptions\n ): Promise<MonoCloudSession | undefined>;\n\n /**\n * @see {@link getSession} for full docs and examples.\n * @param req Incoming request used to read authentication cookies and headers to resolve the current user's session.\n * @param res Optional response to update if session resolution requires refreshed authentication cookies or headers.\n * @param options Optional configuration controlling session retrieval behavior.\n * @returns Returns the resolved session, or `undefined` if none exists.\n */\n public getSession(\n req: NextRequest | Request,\n res: NextResponse | Response,\n options?: GetSessionOptions\n ): Promise<MonoCloudSession | undefined>;\n\n /**\n * @see {@link getSession} for full docs and examples.\n * @param req Incoming Node.js request used to read authentication cookies and resolve the current user's session.\n * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.\n * @param options Optional configuration controlling session retrieval behavior.\n * @returns Returns the resolved session, or `undefined` if none exists.\n */\n public getSession(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>,\n options?: GetSessionOptions\n ): Promise<MonoCloudSession | undefined>;\n\n async getSession(...args: any[]): Promise<MonoCloudSession | undefined> {\n let request: IMonoCloudCookieRequest;\n let response: IMonoCloudCookieResponse;\n let options: GetSessionOptions | undefined;\n\n if (args.length === 0) {\n request = new MonoCloudCookieRequest();\n response = new MonoCloudCookieResponse();\n } else if (args.length === 1) {\n if (args[0] instanceof Request) {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], undefined));\n } else {\n request = new MonoCloudCookieRequest();\n response = new MonoCloudCookieResponse();\n options = args[0];\n }\n } else if (args.length === 2 && args[0] instanceof Request) {\n if (args[1] instanceof Response) {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], args[1]));\n } else {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], undefined));\n\n options = args[1] as GetSessionOptions;\n }\n } else if (\n args.length === 2 &&\n isNodeRequest(args[0]) &&\n isNodeResponse(args[1])\n ) {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], args[1]));\n } else {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], args[1]));\n\n options = args[2] as GetSessionOptions;\n }\n\n if (\n !isMonoCloudRequest(request) ||\n !isMonoCloudResponse(response) ||\n (options && typeof options !== 'object')\n ) {\n throw new MonoCloudValidationError(\n 'Invalid parameters passed to getSession()'\n );\n }\n\n return await this.coreClient.getSession(request, response, options);\n }\n\n /**\n * @see {@link getTokens} for full docs and examples.\n * @param options Optional configuration controlling refresh behavior and resource/scope selection.\n * @returns The current user's tokens, refreshed if necessary.\n * @throws {@link MonoCloudValidationError} If no valid session exists.\n */\n public getTokens(options?: GetTokensOptions): Promise<MonoCloudTokens>;\n\n /**\n * @see {@link getTokens} for full docs and examples.\n * @param req Incoming request used to resolve authentication from cookies and headers.\n * @param options Optional configuration controlling refresh behavior and resource/scope selection.\n * @returns The current user's tokens, refreshed if necessary.\n * @throws {@link MonoCloudValidationError} If no valid session exists.\n */\n public getTokens(\n req: NextRequest | Request,\n options?: GetTokensOptions\n ): Promise<MonoCloudTokens>;\n\n /**\n * @see {@link getTokens} for full docs and examples.\n * @param req Incoming request used to resolve authentication from cookies and headers.\n * @param res Existing response to update with refreshed authentication cookies or headers.\n * @param options Optional configuration controlling refresh behavior and resource/scope selection.\n * @returns The current user's tokens, refreshed if necessary.\n * @throws {@link MonoCloudValidationError} If no valid session exists.\n */\n public getTokens(\n req: NextRequest | Request,\n res: NextResponse | Response,\n options?: GetTokensOptions\n ): Promise<MonoCloudTokens>;\n\n /**\n * @see {@link getTokens} for full docs and examples.\n * @param req Incoming Node.js request used to resolve authentication from cookies.\n * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.\n * @param options Optional configuration controlling refresh behavior and resource/scope selection.\n * @returns The current user's tokens, refreshed if necessary.\n * @throws {@link MonoCloudValidationError} If no valid session exists.\n */\n public getTokens(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>,\n options?: GetTokensOptions\n ): Promise<MonoCloudTokens>;\n\n async getTokens(...args: any[]): Promise<MonoCloudTokens> {\n let request: IMonoCloudCookieRequest;\n let response: IMonoCloudCookieResponse;\n let options: GetTokensOptions | undefined;\n\n if (args.length === 0) {\n request = new MonoCloudCookieRequest();\n response = new MonoCloudCookieResponse();\n } else if (args.length === 1) {\n if (args[0] instanceof Request) {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], undefined));\n } else {\n request = new MonoCloudCookieRequest();\n response = new MonoCloudCookieResponse();\n options = args[0];\n }\n } else if (args.length === 2 && args[0] instanceof Request) {\n if (args[1] instanceof Response) {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], args[1]));\n } else {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], undefined));\n\n options = args[1] as GetTokensOptions;\n }\n } else if (\n args.length === 2 &&\n isNodeRequest(args[0]) &&\n isNodeResponse(args[1])\n ) {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], args[1]));\n } else {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], args[1]));\n\n options = args[2] as GetTokensOptions;\n }\n\n if (\n !isMonoCloudRequest(request) ||\n !isMonoCloudResponse(response) ||\n (options && typeof options !== 'object')\n ) {\n throw new MonoCloudValidationError(\n 'Invalid parameters passed to getTokens()'\n );\n }\n\n return await this.coreClient.getTokens(request, response, options);\n }\n\n /**\n * @see {@link isAuthenticated} for full docs and examples.\n * @returns Returns `true` if a valid session exists; otherwise `false`.\n */\n public isAuthenticated(): Promise<boolean>;\n\n /**\n * @see {@link isAuthenticated} for full docs and examples.\n * @param req Incoming request used to resolve authentication from cookies and headers.\n * @param res Optional response to update if refreshed authentication cookies or headers are required.\n * @returns Returns `true` if a valid session exists; otherwise `false`.\n */\n public isAuthenticated(\n req: NextRequest | Request,\n res?: NextResponse | Response\n ): Promise<boolean>;\n\n /**\n * @see {@link isAuthenticated} for full docs and examples.\n * @param req Incoming Node.js request used to resolve authentication from cookies.\n * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.\n * @returns Returns `true` if a valid session exists; otherwise `false`.\n */\n public isAuthenticated(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>\n ): Promise<boolean>;\n\n async isAuthenticated(...args: any[]): Promise<boolean> {\n let request: IMonoCloudCookieRequest;\n let response: IMonoCloudCookieResponse;\n\n if (args.length === 0) {\n request = new MonoCloudCookieRequest();\n response = new MonoCloudCookieResponse();\n } else {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], args[1]));\n }\n\n /* v8 ignore next -- @preserve */\n if (!isMonoCloudRequest(request) || !isMonoCloudResponse(response)) {\n throw new MonoCloudValidationError(\n 'Invalid parameters passed to isAuthenticated()'\n );\n }\n\n return await this.coreClient.isAuthenticated(request, response);\n }\n\n /**\n * @see {@link protect} for full docs and examples.\n * @param options Optional configuration for redirect behavior (for example, return URL or sign-in parameters).\n * @returns Resolves if the user is authenticated; otherwise triggers a redirect.\n */\n public async protect(options?: ProtectOptions): Promise<void> {\n const { routes, appUrl } = this.coreClient.getOptions();\n let path: string;\n try {\n const session = await this.getSession();\n\n if (session && !options?.groups) {\n return;\n }\n\n if (\n session &&\n options?.groups &&\n isUserInGroupCore(\n session.user,\n options.groups,\n options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM,\n options.matchAll\n )\n ) {\n return;\n }\n\n // @ts-expect-error Cannot find module 'next/headers'\n const { headers } = await import('next/headers');\n\n path = (await headers()).get('x-monocloud-path') ?? '/';\n } catch {\n throw new Error(\n 'protect() can only be used in App Router server environments (RSC, route handlers, or server actions)'\n );\n }\n\n const signInRoute = new URL(`${appUrl}${routes.signIn}`);\n\n signInRoute.searchParams.set('return_url', options?.returnUrl ?? path);\n\n if (options?.authParams?.maxAge) {\n signInRoute.searchParams.set(\n 'max_age',\n options.authParams.maxAge.toString()\n );\n }\n\n if (options?.authParams?.authenticatorHint) {\n signInRoute.searchParams.set(\n 'authenticator_hint',\n options.authParams.authenticatorHint\n );\n }\n\n if (options?.authParams?.scopes) {\n signInRoute.searchParams.set('scope', options.authParams.scopes);\n }\n\n if (options?.authParams?.resource) {\n signInRoute.searchParams.set('resource', options.authParams.resource);\n }\n\n if (options?.authParams?.display) {\n signInRoute.searchParams.set('display', options.authParams.display);\n }\n\n if (options?.authParams?.uiLocales) {\n signInRoute.searchParams.set('ui_locales', options.authParams.uiLocales);\n }\n\n if (Array.isArray(options?.authParams?.acrValues)) {\n signInRoute.searchParams.set(\n 'acr_values',\n options.authParams.acrValues.join(' ')\n );\n }\n\n if (options?.authParams?.loginHint) {\n signInRoute.searchParams.set('login_hint', options.authParams.loginHint);\n }\n\n if (options?.authParams?.prompt) {\n signInRoute.searchParams.set('prompt', options.authParams.prompt);\n }\n\n // @ts-expect-error Cannot find module 'next/navigation'\n const { redirect } = await import('next/navigation');\n\n redirect(signInRoute.toString());\n }\n\n /**\n * @see {@link isUserInGroup} for full docs and examples.\n * @param groups Group IDs or names to check against the user's group memberships.\n * @param options Optional configuration controlling how group membership is evaluated.\n * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.\n */\n isUserInGroup(\n groups: string[],\n options?: IsUserInGroupOptions\n ): Promise<boolean>;\n\n /**\n * @see {@link isUserInGroup} for full docs and examples.\n * @param req Incoming request used to resolve authentication from cookies and headers.\n * @param groups Group IDs or names to check against the user's group memberships.\n * @param options Optional configuration controlling how group membership is evaluated.\n * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.\n */\n isUserInGroup(\n req: NextRequest | Request,\n groups: string[],\n options?: IsUserInGroupOptions\n ): Promise<boolean>;\n\n /**\n * @see {@link isUserInGroup} for full docs and examples.\n * @param req Incoming request used to resolve authentication from cookies and headers.\n * @param res Existing response to update with refreshed authentication cookies or headers when required.\n * @param groups Group IDs or names to check against the user's group memberships.\n * @param options Optional configuration controlling how group membership is evaluated.\n * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.\n */\n isUserInGroup(\n req: NextRequest | Request,\n res: NextResponse | Response,\n groups: string[],\n options?: IsUserInGroupOptions\n ): Promise<boolean>;\n\n /**\n * @see {@link isUserInGroup} for full docs and examples.\n * @param req Incoming Node.js request used to resolve authentication from cookies.\n * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.\n * @param groups Group IDs or names to check against the user's group memberships.\n * @param options Optional configuration controlling how group membership is evaluated.\n * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.\n */\n isUserInGroup(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>,\n groups: string[],\n options?: IsUserInGroupOptions\n ): Promise<boolean>;\n\n public async isUserInGroup(...args: any[]): Promise<boolean> {\n let request: IMonoCloudCookieRequest | undefined;\n let response: IMonoCloudCookieResponse | undefined;\n let groups: string[] | undefined;\n let options: IsUserInGroupOptions | undefined;\n\n if (args.length === 4) {\n groups = args[2];\n options = args[3];\n\n ({ request, response } = getMonoCloudCookieReqRes(args[0], args[1]));\n }\n\n if (args.length === 3) {\n if (args[0] instanceof Request) {\n if (args[1] instanceof Response) {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], args[1]));\n groups = args[2];\n } else {\n ({ request, response } = getMonoCloudCookieReqRes(\n args[0],\n undefined\n ));\n groups = args[1];\n options = args[2];\n }\n }\n\n if (isNodeRequest(args[0]) && isNodeResponse(args[1])) {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], args[1]));\n groups = args[2];\n }\n }\n\n if (args.length === 2) {\n if (args[0] instanceof Request) {\n ({ request, response } = getMonoCloudCookieReqRes(args[0], undefined));\n groups = args[1];\n }\n\n if (Array.isArray(args[0])) {\n request = new MonoCloudCookieRequest();\n response = new MonoCloudCookieResponse();\n\n groups = args[0];\n options = args[1];\n }\n }\n\n if (args.length === 1) {\n request = new MonoCloudCookieRequest();\n response = new MonoCloudCookieResponse();\n\n groups = args[0];\n }\n\n if (\n !Array.isArray(groups) ||\n !isMonoCloudRequest(request) ||\n !isMonoCloudResponse(response) ||\n (options && typeof options !== 'object')\n ) {\n throw new MonoCloudValidationError(\n 'Invalid parameters passed to isUserInGroup()'\n );\n }\n\n const result = await this.coreClient.isUserInGroup(\n request,\n response,\n groups,\n options?.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM,\n options?.matchAll\n );\n\n return result;\n }\n\n /**\n * @see {@link redirectToSignIn} for full docs and examples.\n * @param options Optional configuration for the redirect, such as `returnUrl` or additional sign-in parameters.\n * @returns Never resolves. Triggers a redirect to the sign-in flow.\n */\n public async redirectToSignIn(\n options?: RedirectToSignInOptions\n ): Promise<void> {\n const { routes, appUrl } = this.coreClient.getOptions();\n\n try {\n // @ts-expect-error Cannot find module 'next/headers'\n const { headers } = await import('next/headers');\n\n await headers();\n } catch {\n throw new Error(\n 'redirectToSignIn() can only be used in App Router server environments (RSC, route handlers, or server actions)'\n );\n }\n\n const signInRoute = new URL(`${appUrl}${routes.signIn}`);\n\n if (options?.returnUrl) {\n signInRoute.searchParams.set('return_url', options.returnUrl);\n }\n\n if (options?.maxAge) {\n signInRoute.searchParams.set('max_age', options.maxAge.toString());\n }\n\n if (options?.authenticatorHint) {\n signInRoute.searchParams.set(\n 'authenticator_hint',\n options.authenticatorHint\n );\n }\n\n if (options?.scopes) {\n signInRoute.searchParams.set('scope', options.scopes);\n }\n\n if (options?.resource) {\n signInRoute.searchParams.set('resource', options.resource);\n }\n\n if (options?.display) {\n signInRoute.searchParams.set('display', options.display);\n }\n\n if (options?.uiLocales) {\n signInRoute.searchParams.set('ui_locales', options.uiLocales);\n }\n\n if (Array.isArray(options?.acrValues)) {\n signInRoute.searchParams.set('acr_values', options.acrValues.join(' '));\n }\n\n if (options?.loginHint) {\n signInRoute.searchParams.set('login_hint', options.loginHint);\n }\n\n if (options?.prompt) {\n signInRoute.searchParams.set('prompt', options.prompt);\n }\n\n // @ts-expect-error Cannot find module 'next/navigation'\n const { redirect } = await import('next/navigation');\n\n redirect(signInRoute.toString());\n }\n\n /**\n * @see {@link redirectToSignOut} for full docs and examples.\n * @param options Optional configuration for the redirect, such as `postLogoutRedirectUri` or additional sign-out parameters.\n * @returns Never resolves. Triggers a redirect to the sign-out flow.\n */\n public async redirectToSignOut(\n options?: RedirectToSignOutOptions\n ): Promise<void> {\n const { routes, appUrl } = this.coreClient.getOptions();\n\n try {\n // @ts-expect-error Cannot find module 'next/headers'\n const { headers } = await import('next/headers');\n\n await headers();\n } catch {\n throw new Error(\n 'redirectToSignOut() can only be used in App Router server environments (RSC, route handlers, or server actions)'\n );\n }\n\n const signOutRoute = new URL(`${appUrl}${routes.signOut}`);\n\n if (options?.postLogoutRedirectUri?.trim().length) {\n signOutRoute.searchParams.set(\n 'post_logout_url',\n options.postLogoutRedirectUri\n );\n }\n\n if (typeof options?.federated === 'boolean') {\n signOutRoute.searchParams.set('federated', options.federated.toString());\n }\n\n // @ts-expect-error Cannot find module 'next/navigation'\n const { redirect } = await import('next/navigation');\n\n redirect(signOutRoute.toString());\n }\n\n private getOptions(): MonoCloudOptions {\n return this.coreClient.getOptions();\n }\n\n private registerPublicEnvVariables(): void {\n Object.keys(process.env)\n .filter(key => key.startsWith('NEXT_PUBLIC_MONOCLOUD_AUTH'))\n .forEach(publicKey => {\n const [, privateKey] = publicKey.split('NEXT_PUBLIC_');\n process.env[privateKey] = process.env[publicKey];\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoMA,I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AACrC,SAAO,KAAK,WAAW,YAAY;;CAGrC,AAAQ,6BAAmC;AACzC,SAAO,KAAK,QAAQ,IAAI,CACrB,QAAO,QAAO,IAAI,WAAW,6BAA6B,CAAC,CAC3D,SAAQ,cAAa;GACpB,MAAM,GAAG,cAAc,UAAU,MAAM,eAAe;AACtD,WAAQ,IAAI,cAAc,QAAQ,IAAI;IACtC"}
@@ -0,0 +1,330 @@
1
+ import { AppRouterApiHandlerFn, AppRouterPageHandler, IsUserInGroupOptions, MonoCloudAuthHandler, MonoCloudAuthOptions, MonoCloudMiddlewareOptions, NextMiddlewareResult, ProtectApiAppOptions, ProtectApiPageOptions, ProtectAppPageOptions, ProtectOptions, ProtectPagePageOptions, ProtectPagePageReturnType, ProtectedAppServerComponent, RedirectToSignInOptions, RedirectToSignOutOptions } from "./types.mjs";
2
+ import { GetSessionOptions, GetTokensOptions, MonoCloudCoreClient, MonoCloudOptions, MonoCloudSession, MonoCloudTokens } from "@monocloud/auth-node-core";
3
+ import { NextFetchEvent, NextMiddleware, NextProxy, NextRequest, NextResponse } from "next/server.js";
4
+ import { NextApiHandler, NextApiRequest, NextApiResponse } from "next/types";
5
+ import { ParsedUrlQuery } from "node:querystring";
6
+ import { MonoCloudOidcClient } from "@monocloud/auth-core";
7
+ import { IncomingMessage, ServerResponse } from "node:http";
8
+
9
+ //#region src/monocloud-next-client.d.ts
10
+ /**
11
+ * `MonoCloudNextClient` is the core SDK entry point for integrating MonoCloud authentication into a Next.js application.
12
+ *
13
+ * It provides:
14
+ * - Authentication middleware
15
+ * - Route protection helpers
16
+ * - Session and token access
17
+ * - Redirect utilities
18
+ * - Server-side enforcement helpers
19
+ *
20
+ * ## 1. Add environment variables
21
+ *
22
+ * ```bash:.env.local
23
+ * MONOCLOUD_AUTH_TENANT_DOMAIN=<tenant-domain>
24
+ * MONOCLOUD_AUTH_CLIENT_ID=<client-id>
25
+ * MONOCLOUD_AUTH_CLIENT_SECRET=<client-secret>
26
+ * MONOCLOUD_AUTH_SCOPES=openid profile email
27
+ * MONOCLOUD_AUTH_APP_URL=http://localhost:3000
28
+ * MONOCLOUD_AUTH_COOKIE_SECRET=<cookie-secret>
29
+ * ```
30
+ *
31
+ * ## 2. Register middleware
32
+ *
33
+ * ```typescript:src/proxy.ts
34
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
35
+ *
36
+ * export default authMiddleware();
37
+ *
38
+ * export const config = {
39
+ * matcher: [
40
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
41
+ * ],
42
+ * };
43
+ * ```
44
+ *
45
+ * ## Advanced usage
46
+ *
47
+ * ### Create a shared client instance
48
+ *
49
+ * By default, the SDK exposes function exports (for example, `authMiddleware()`, `getSession()`, `getTokens()`) that internally use a shared singleton `MonoCloudNextClient`.
50
+ *
51
+ * Create your own `MonoCloudNextClient` instance when you need multiple configurations, dependency injection, or explicit control over initialization.
52
+ *
53
+ * ```ts:src/monocloud.ts
54
+ * import { MonoCloudNextClient } from "@monocloud/auth-nextjs";
55
+ *
56
+ * export const monoCloud = new MonoCloudNextClient();
57
+ * ```
58
+ *
59
+ * ### Using instance methods
60
+ *
61
+ * Once you create a client instance, call methods directly on it instead of using the default function exports.
62
+ *
63
+ * ```ts:src/app/page.tsx
64
+ * import { monoCloud } from "@/monocloud";
65
+ *
66
+ * export default async function Page() {
67
+ * const session = await monoCloud.getSession();
68
+ *
69
+ * if (!session) {
70
+ * return <>Not signed in</>;
71
+ * }
72
+ *
73
+ * return <>Hello {session.user.name}</>;
74
+ * }
75
+ * ```
76
+ *
77
+ * #### Using constructor options
78
+ *
79
+ * When configuration is provided through both constructor options and environment variables, the values passed to the constructor take precedence. Environment variables are used only for options that are not explicitly supplied.
80
+ *
81
+ * ```ts:src/monocloud.ts
82
+ * import { MonoCloudNextClient } from "@monocloud/auth-nextjs";
83
+ *
84
+ * export const monoCloud = new MonoCloudNextClient({
85
+ * tenantDomain: "<tenant-domain>",
86
+ * clientId: "<client-id>",
87
+ * clientSecret: "<client-secret>",
88
+ * appUrl: "http://localhost:3000",
89
+ * cookieSecret: "<cookie-secret>",
90
+ * defaultAuthParams: {
91
+ * scopes: "openid profile email",
92
+ * },
93
+ * });
94
+ * ```
95
+ *
96
+ * ### Modifying default routes
97
+ *
98
+ * If you customize any of the default auth route paths:
99
+ *
100
+ * - Also set the corresponding `NEXT_PUBLIC_` environment variables so client-side helpers
101
+ * (for example `<SignIn />`, `<SignOut />`, and `useAuth()`) can discover the correct URLs.
102
+ * - Update the **Application URLs** in your MonoCloud Dashboard to match the new paths.
103
+ *
104
+ * Example:
105
+ *
106
+ * ```bash:.env.local
107
+ * MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
108
+ * NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
109
+ * ```
110
+ *
111
+ * When routes are overridden, the Redirect URI configured in the dashboard
112
+ * must reflect the new path. For example, during local development:
113
+ *
114
+ * `http://localhost:3000/api/custom_callback`
115
+ *
116
+ * @category Classes
117
+ */
118
+ declare class MonoCloudNextClient {
119
+ private readonly _coreClient;
120
+ /**
121
+ * This exposes the framework-agnostic MonoCloud client used internally by the Next.js SDK.
122
+ * Use it if you need access to lower-level functionality not directly exposed by MonoCloudNextClient.
123
+ *
124
+ * @returns Returns the underlying **Node client** instance.
125
+ */
126
+ get coreClient(): MonoCloudCoreClient;
127
+ /**
128
+ * This is intended for advanced scenarios requiring direct control over the authorization or token flow.
129
+ *
130
+ * @returns Returns the underlying **OIDC client** used for OpenID Connect operations.
131
+ */
132
+ get oidcClient(): MonoCloudOidcClient;
133
+ /**
134
+ * Creates a new client instance.
135
+ *
136
+ * @param options Optional configuration for initializing the MonoCloud client. If not provided, settings are automatically resolved from environment variables.
137
+ */
138
+ constructor(options?: MonoCloudOptions);
139
+ /**
140
+ * @see {@link monoCloudAuth} for full docs and examples.
141
+ * @param options Optional configuration for the auth handler.
142
+ * @returns Returns a Next.js-compatible handler for App Router route handlers or Pages Router API routes.
143
+ */
144
+ monoCloudAuth(options?: MonoCloudAuthOptions): MonoCloudAuthHandler;
145
+ /**
146
+ * @see {@link protectPage} for full docs and examples.
147
+ * @param component The App Router server component to protect.
148
+ * @param options Optional configuration for authentication, authorization, and custom access handling (`onAccessDenied`, `onGroupAccessDenied`).
149
+ * @returns A wrapped page component that enforces authentication before rendering.
150
+ */
151
+ protectPage(component: ProtectedAppServerComponent, options?: ProtectAppPageOptions): AppRouterPageHandler;
152
+ /**
153
+ * @see {@link protectPage} for full docs and examples.
154
+ * @param options Optional configuration for authentication, authorization, and custom access handling (`onAccessDenied`, `onGroupAccessDenied`).
155
+ * @typeParam P - Props returned from `getServerSideProps`.
156
+ * @typeParam Q - Query parameters parsed from the URL.
157
+ * @returns A getServerSideProps wrapper that enforces authentication before executing the page logic.
158
+ */
159
+ protectPage<P extends Record<string, any> = Record<string, any>, Q extends ParsedUrlQuery = ParsedUrlQuery>(options?: ProtectPagePageOptions<P, Q>): ProtectPagePageReturnType<P, Q>;
160
+ private protectAppPage;
161
+ private protectPagePage;
162
+ /**
163
+ * @see {@link protectApi} for full docs and examples.
164
+ * @param handler The route handler to protect.
165
+ * @param options Optional configuration controlling authentication and authorization behavior.
166
+ * @returns Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.
167
+ */
168
+ protectApi(handler: AppRouterApiHandlerFn, options?: ProtectApiAppOptions): AppRouterApiHandlerFn;
169
+ /**
170
+ * @see {@link protectApi} for full docs and examples.
171
+ * @param handler - The route handler to protect.
172
+ * @param options Optional configuration controlling authentication and authorization behavior.
173
+ * @returns Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.
174
+ */
175
+ protectApi(handler: NextApiHandler, options?: ProtectApiPageOptions): NextApiHandler;
176
+ private protectAppApi;
177
+ private protectPageApi;
178
+ /**
179
+ * @see {@link authMiddleware} for full docs and examples.
180
+ * @param options Optional configuration that controls how authentication is enforced (for example, redirect behavior, route matching, or custom handling of unauthenticated requests).
181
+ * @returns Returns a Next.js middleware result (`NextResponse`, redirect, or `undefined` to continue processing).
182
+ */
183
+ authMiddleware(options?: MonoCloudMiddlewareOptions): NextMiddleware | NextProxy;
184
+ /**
185
+ * @see {@link authMiddleware} for full docs and examples.
186
+ * @param request Incoming Next.js middleware request used to resolve authentication state.
187
+ * @param event Next.js middleware event providing lifecycle hooks such as `waitUntil`.
188
+ * @returns Returns a Next.js middleware result (`NextResponse`, redirect, or `undefined` to continue processing).
189
+ */
190
+ authMiddleware(request: NextRequest, event: NextFetchEvent): Promise<NextMiddlewareResult> | NextMiddlewareResult;
191
+ private authMiddlewareHandler;
192
+ private handleAuthRoutes;
193
+ /**
194
+ * @see {@link getSession} for full docs and examples.
195
+ * @param options Optional configuration controlling session retrieval behavior.
196
+ * @returns Returns the resolved session, or `undefined` if none exists.
197
+ */
198
+ getSession(options?: GetSessionOptions): Promise<MonoCloudSession | undefined>;
199
+ /**
200
+ * @see {@link getSession} for full docs and examples.
201
+ * @param req Incoming request used to read authentication cookies and headers to resolve the current user's session.
202
+ * @param options Optional configuration controlling session retrieval behavior.
203
+ * @returns Returns the resolved session, or `undefined` if none exists.
204
+ */
205
+ getSession(req: NextRequest | Request, options?: GetSessionOptions): Promise<MonoCloudSession | undefined>;
206
+ /**
207
+ * @see {@link getSession} for full docs and examples.
208
+ * @param req Incoming request used to read authentication cookies and headers to resolve the current user's session.
209
+ * @param res Optional response to update if session resolution requires refreshed authentication cookies or headers.
210
+ * @param options Optional configuration controlling session retrieval behavior.
211
+ * @returns Returns the resolved session, or `undefined` if none exists.
212
+ */
213
+ getSession(req: NextRequest | Request, res: NextResponse | Response, options?: GetSessionOptions): Promise<MonoCloudSession | undefined>;
214
+ /**
215
+ * @see {@link getSession} for full docs and examples.
216
+ * @param req Incoming Node.js request used to read authentication cookies and resolve the current user's session.
217
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
218
+ * @param options Optional configuration controlling session retrieval behavior.
219
+ * @returns Returns the resolved session, or `undefined` if none exists.
220
+ */
221
+ getSession(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>, options?: GetSessionOptions): Promise<MonoCloudSession | undefined>;
222
+ /**
223
+ * @see {@link getTokens} for full docs and examples.
224
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
225
+ * @returns The current user's tokens, refreshed if necessary.
226
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
227
+ */
228
+ getTokens(options?: GetTokensOptions): Promise<MonoCloudTokens>;
229
+ /**
230
+ * @see {@link getTokens} for full docs and examples.
231
+ * @param req Incoming request used to resolve authentication from cookies and headers.
232
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
233
+ * @returns The current user's tokens, refreshed if necessary.
234
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
235
+ */
236
+ getTokens(req: NextRequest | Request, options?: GetTokensOptions): Promise<MonoCloudTokens>;
237
+ /**
238
+ * @see {@link getTokens} for full docs and examples.
239
+ * @param req Incoming request used to resolve authentication from cookies and headers.
240
+ * @param res Existing response to update with refreshed authentication cookies or headers.
241
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
242
+ * @returns The current user's tokens, refreshed if necessary.
243
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
244
+ */
245
+ getTokens(req: NextRequest | Request, res: NextResponse | Response, options?: GetTokensOptions): Promise<MonoCloudTokens>;
246
+ /**
247
+ * @see {@link getTokens} for full docs and examples.
248
+ * @param req Incoming Node.js request used to resolve authentication from cookies.
249
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
250
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
251
+ * @returns The current user's tokens, refreshed if necessary.
252
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
253
+ */
254
+ getTokens(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>, options?: GetTokensOptions): Promise<MonoCloudTokens>;
255
+ /**
256
+ * @see {@link isAuthenticated} for full docs and examples.
257
+ * @returns Returns `true` if a valid session exists; otherwise `false`.
258
+ */
259
+ isAuthenticated(): Promise<boolean>;
260
+ /**
261
+ * @see {@link isAuthenticated} for full docs and examples.
262
+ * @param req Incoming request used to resolve authentication from cookies and headers.
263
+ * @param res Optional response to update if refreshed authentication cookies or headers are required.
264
+ * @returns Returns `true` if a valid session exists; otherwise `false`.
265
+ */
266
+ isAuthenticated(req: NextRequest | Request, res?: NextResponse | Response): Promise<boolean>;
267
+ /**
268
+ * @see {@link isAuthenticated} for full docs and examples.
269
+ * @param req Incoming Node.js request used to resolve authentication from cookies.
270
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
271
+ * @returns Returns `true` if a valid session exists; otherwise `false`.
272
+ */
273
+ isAuthenticated(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>): Promise<boolean>;
274
+ /**
275
+ * @see {@link protect} for full docs and examples.
276
+ * @param options Optional configuration for redirect behavior (for example, return URL or sign-in parameters).
277
+ * @returns Resolves if the user is authenticated; otherwise triggers a redirect.
278
+ */
279
+ protect(options?: ProtectOptions): Promise<void>;
280
+ /**
281
+ * @see {@link isUserInGroup} for full docs and examples.
282
+ * @param groups Group IDs or names to check against the user's group memberships.
283
+ * @param options Optional configuration controlling how group membership is evaluated.
284
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
285
+ */
286
+ isUserInGroup(groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
287
+ /**
288
+ * @see {@link isUserInGroup} for full docs and examples.
289
+ * @param req Incoming request used to resolve authentication from cookies and headers.
290
+ * @param groups Group IDs or names to check against the user's group memberships.
291
+ * @param options Optional configuration controlling how group membership is evaluated.
292
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
293
+ */
294
+ isUserInGroup(req: NextRequest | Request, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
295
+ /**
296
+ * @see {@link isUserInGroup} for full docs and examples.
297
+ * @param req Incoming request used to resolve authentication from cookies and headers.
298
+ * @param res Existing response to update with refreshed authentication cookies or headers when required.
299
+ * @param groups Group IDs or names to check against the user's group memberships.
300
+ * @param options Optional configuration controlling how group membership is evaluated.
301
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
302
+ */
303
+ isUserInGroup(req: NextRequest | Request, res: NextResponse | Response, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
304
+ /**
305
+ * @see {@link isUserInGroup} for full docs and examples.
306
+ * @param req Incoming Node.js request used to resolve authentication from cookies.
307
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
308
+ * @param groups Group IDs or names to check against the user's group memberships.
309
+ * @param options Optional configuration controlling how group membership is evaluated.
310
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
311
+ */
312
+ isUserInGroup(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
313
+ /**
314
+ * @see {@link redirectToSignIn} for full docs and examples.
315
+ * @param options Optional configuration for the redirect, such as `returnUrl` or additional sign-in parameters.
316
+ * @returns Never resolves. Triggers a redirect to the sign-in flow.
317
+ */
318
+ redirectToSignIn(options?: RedirectToSignInOptions): Promise<void>;
319
+ /**
320
+ * @see {@link redirectToSignOut} for full docs and examples.
321
+ * @param options Optional configuration for the redirect, such as `postLogoutRedirectUri` or additional sign-out parameters.
322
+ * @returns Never resolves. Triggers a redirect to the sign-out flow.
323
+ */
324
+ redirectToSignOut(options?: RedirectToSignOutOptions): Promise<void>;
325
+ private getOptions;
326
+ private registerPublicEnvVariables;
327
+ }
328
+ //#endregion
329
+ export { MonoCloudNextClient };
330
+ //# sourceMappingURL=monocloud-next-client.d.mts.map