@monocloud/auth-nextjs 0.1.7 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.mts +4 -3
- package/dist/client/index.mjs +1 -1
- package/dist/components/client/index.cjs +1 -1
- package/dist/components/client/index.cjs.map +1 -1
- package/dist/components/client/index.d.mts +2 -2
- package/dist/components/client/index.mjs +1 -1
- package/dist/components/client/index.mjs.map +1 -1
- package/dist/components/index.d.mts +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +5 -5
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{protect-client-page-BFlGkK8F.mjs → protect-client-page-BFVskb3X.mjs} +4 -3
- package/dist/protect-client-page-BFVskb3X.mjs.map +1 -0
- package/dist/{protect-client-page-B1fOU4Zl.cjs → protect-client-page-BdsnH8gs.cjs} +4 -3
- package/dist/protect-client-page-BdsnH8gs.cjs.map +1 -0
- package/dist/{types-xS_Me3Qg.d.mts → types-ClljFIvK.d.mts} +49 -69
- package/package.json +3 -3
- package/dist/protect-client-page-B1fOU4Zl.cjs.map +0 -1
- package/dist/protect-client-page-BFlGkK8F.mjs.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["NextResponse","cookie","NextRequest","NextResponse","MonoCloudValidationError","MonoCloudCoreClient","NextResponse","MonoCloudValidationError"],"sources":["../src/requests/monocloud-app-router-request.ts","../src/requests/monocloud-page-router-request.ts","../src/responses/monocloud-app-router-response.ts","../src/responses/monocloud-page-router-response.ts","../src/responses/monocloud-cookie-response.ts","../src/requests/monocloud-cookie-request.ts","../src/utils.ts","../src/monocloud-next-client.ts","../src/initialize.ts"],"sourcesContent":["import type { MonoCloudRequest } from '@monocloud/auth-node-core';\n// eslint-disable-next-line import/extensions\nimport type { NextRequest } from 'next/server.js';\n\nexport default class MonoCloudAppRouterRequest implements MonoCloudRequest {\n constructor(public readonly req: NextRequest) {}\n\n getQuery(parameter: string): string | string[] | undefined {\n const url = new URL(this.req.url);\n return url.searchParams.get(parameter) ?? undefined;\n }\n\n getCookie(name: string): Promise<string | undefined> {\n return Promise.resolve(this.req.cookies.get(name)?.value);\n }\n\n async getRawRequest(): Promise<{\n method: string;\n url: string;\n body: Record<string, string> | string;\n }> {\n return {\n method: this.req.method,\n url: this.req.url,\n body: await this.req.text(),\n };\n }\n\n getAllCookies(): Promise<Map<string, string>> {\n const values = new Map<string, string>();\n this.req.cookies.getAll().forEach(x => {\n values.set(x.name, x.value);\n });\n return Promise.resolve(values);\n }\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\nimport type { MonoCloudRequest } from '@monocloud/auth-node-core';\nimport type { NextApiRequest } from 'next';\n\nexport default class MonoCloudPageRouterRequest implements MonoCloudRequest {\n constructor(public readonly req: NextApiRequest) {}\n\n /* v8 ignore next */\n getQuery(parameter: string): string | string[] | undefined {\n return this.req.query[parameter];\n }\n\n /* v8 ignore next */\n getCookie(name: string): Promise<string | undefined> {\n return Promise.resolve(this.req.cookies[name]);\n }\n\n /* v8 ignore next */\n getRawRequest(): Promise<{\n method: string;\n url: string;\n body: Record<string, string> | string;\n }> {\n return Promise.resolve({\n method: this.req.method!,\n url: this.req.url!,\n body: this.req.body,\n });\n }\n\n getAllCookies(): Promise<Map<string, string>> {\n const values = new Map<string, string>();\n const { cookies } = this.req;\n Object.keys(cookies).forEach(x => {\n const val = cookies[x];\n /* v8 ignore else -- @preserve */\n if (typeof x === 'string' && typeof val === 'string') {\n values.set(x, val);\n }\n });\n return Promise.resolve(values);\n }\n}\n","import type {\n CookieOptions,\n MonoCloudResponse,\n} from '@monocloud/auth-node-core';\n// eslint-disable-next-line import/extensions\nimport { NextResponse } from 'next/server.js';\n\nexport default class MonoCloudAppRouterResponse implements MonoCloudResponse {\n constructor(public res: NextResponse) {}\n\n setCookie(\n cookieName: string,\n value: string,\n options: CookieOptions\n ): Promise<void> {\n this.res.cookies.set(cookieName, value, options);\n return Promise.resolve();\n }\n\n redirect(url: string, statusCode: number | undefined = 302): void {\n const { headers } = this.res;\n this.res = NextResponse.redirect(url, { status: statusCode, headers });\n }\n\n sendJson(data: any, statusCode?: number): void {\n const { headers } = this.res;\n this.res = NextResponse.json(data, { status: statusCode, headers });\n }\n\n /* v8 ignore next */\n notFound(): void {\n const { headers } = this.res;\n this.res = new NextResponse(null, { status: 404, headers });\n }\n\n internalServerError(): void {\n const { headers } = this.res;\n this.res = new NextResponse(null, { status: 500, headers });\n }\n\n noContent(): void {\n const { headers } = this.res;\n this.res = new NextResponse(null, { status: 204, headers });\n }\n\n methodNotAllowed(): void {\n const { headers } = this.res;\n this.res = new NextResponse(null, { status: 405, headers });\n }\n\n setNoCache(): void {\n this.res.headers.set('Cache-Control', 'no-cache no-store');\n this.res.headers.set('Pragma', 'no-cache');\n }\n\n done(): any {\n return this.res;\n }\n}\n","import type {\n CookieOptions,\n MonoCloudResponse,\n} from '@monocloud/auth-node-core';\nimport type { NextApiResponse } from 'next';\nimport { serialize } from 'cookie';\n\nexport default class MonoCloudPageRouterResponse implements MonoCloudResponse {\n constructor(public readonly res: NextApiResponse) {}\n\n setCookie(\n cookieName: string,\n value: string,\n options: CookieOptions\n ): Promise<void> {\n let cookies = this.res.getHeader('Set-Cookie') ?? [];\n\n /* v8 ignore if -- @preserve */\n if (!Array.isArray(cookies)) {\n cookies = [cookies as string];\n }\n\n this.res.setHeader('Set-Cookie', [\n ...cookies.filter(cookie => !cookie.startsWith(`${cookieName}=`)),\n serialize(cookieName, value, options),\n ]);\n\n return Promise.resolve();\n }\n\n /* v8 ignore next */\n redirect(url: string, statusCode?: number): void {\n this.res.redirect(statusCode ?? 302, url);\n }\n\n /* v8 ignore next */\n sendJson(data: any, statusCode?: number): void {\n this.res.status(statusCode ?? 200);\n this.res.json(data);\n }\n\n /* v8 ignore next */\n notFound(): void {\n this.res.status(404);\n }\n\n /* v8 ignore next */\n internalServerError(): void {\n this.res.status(500);\n }\n\n /* v8 ignore next */\n noContent(): void {\n this.res.status(204);\n }\n\n /* v8 ignore next */\n methodNotAllowed(): void {\n this.res.status(405);\n }\n\n /* v8 ignore next */\n setNoCache(): void {\n this.res.setHeader('Cache-Control', 'no-cache no-store');\n this.res.setHeader('Pragma', 'no-cache');\n }\n\n /* v8 ignore next */\n done(): any {\n this.res.end();\n }\n}\n","/* eslint-disable no-console */\nimport type {\n CookieOptions,\n IMonoCloudCookieResponse,\n} from '@monocloud/auth-node-core';\n\nlet isWarned = false;\n\nexport default class MonoCloudCookieResponse implements IMonoCloudCookieResponse {\n async setCookie(\n cookieName: string,\n value: string,\n options: CookieOptions\n ): Promise<void> {\n try {\n // @ts-expect-error Cannot find module 'next/headers'\n const { cookies } = await import('next/headers');\n\n (await cookies()).set(cookieName, value, options);\n } catch (e: any) {\n if (!isWarned) {\n console.warn(e.message);\n isWarned = true;\n }\n }\n }\n}\n","import type { IMonoCloudCookieRequest } from '@monocloud/auth-node-core';\n\nexport default class MonoCloudCookieRequest implements IMonoCloudCookieRequest {\n /* v8 ignore next */\n async getCookie(name: string): Promise<string | undefined> {\n // @ts-expect-error Cannot find module 'next/headers'\n const { cookies } = await import('next/headers');\n\n return (await cookies()).get(name)?.value;\n }\n\n async getAllCookies(): Promise<Map<string, string>> {\n const values = new Map<string, string>();\n // @ts-expect-error Cannot find module 'next/headers'\n const { cookies } = await import('next/headers');\n\n (await cookies()).getAll().forEach((x: any) => {\n values.set(x.name, x.value);\n });\n return values;\n }\n}\n","// eslint-disable-next-line import/extensions\nimport { NextRequest, NextResponse } from 'next/server.js';\nimport type { NextApiRequest, NextApiResponse } from 'next/types';\nimport {\n MonoCloudValidationError,\n type IMonoCloudCookieRequest,\n type IMonoCloudCookieResponse,\n} from '@monocloud/auth-node-core';\nimport { AppRouterContext } from './types';\nimport MonoCloudAppRouterRequest from './requests/monocloud-app-router-request';\nimport MonoCloudPageRouterRequest from './requests/monocloud-page-router-request';\nimport MonoCloudAppRouterResponse from './responses/monocloud-app-router-response';\nimport MonoCloudPageRouterResponse from './responses/monocloud-page-router-response';\nimport MonoCloudCookieResponse from './responses/monocloud-cookie-response';\nimport MonoCloudCookieRequest from './requests/monocloud-cookie-request';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { isPresent } from '@monocloud/auth-node-core/internal';\n\nexport const isMonoCloudRequest = (\n req: unknown\n): req is IMonoCloudCookieRequest =>\n req instanceof MonoCloudAppRouterRequest ||\n req instanceof MonoCloudPageRouterRequest ||\n req instanceof MonoCloudCookieRequest;\n\nexport const isMonoCloudResponse = (\n res: unknown\n): res is IMonoCloudCookieResponse =>\n res instanceof MonoCloudAppRouterResponse ||\n res instanceof MonoCloudPageRouterResponse ||\n res instanceof MonoCloudCookieResponse;\n\nexport const isAppRouter = (req: unknown): boolean =>\n req instanceof Request ||\n (req as Request).headers instanceof Headers ||\n typeof (req as Request).bodyUsed === 'boolean';\n\nexport const isNodeRequest = (req: any): req is IncomingMessage => {\n return !!(\n req &&\n typeof req === 'object' &&\n 'headers' in req &&\n !('bodyUsed' in req) &&\n typeof req.on === 'function'\n );\n};\n\nexport const isNodeResponse = (res: any): res is ServerResponse => {\n return !!(\n res &&\n typeof res === 'object' &&\n 'setHeader' in res &&\n typeof res.setHeader === 'function' &&\n 'end' in res &&\n typeof res.end === 'function'\n );\n};\n\nexport const getNextRequest = (req: Request | NextRequest): NextRequest => {\n if (req instanceof NextRequest) {\n return req;\n }\n\n return new NextRequest(req.url, {\n method: req.method,\n headers: req.headers,\n body: req.body,\n /* v8 ignore next -- @preserve */\n duplex: (req as any).duplex ?? 'half',\n });\n};\n\nexport const getNextResponse = (\n res: Response | NextResponse | AppRouterContext\n): NextResponse => {\n if (res instanceof NextResponse) {\n return res;\n }\n\n if (res instanceof Response) {\n const nextResponse = new NextResponse(res.body, {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n url: res.url,\n });\n\n try {\n /* v8 ignore else -- @preserve */\n if (!isPresent(nextResponse.url)) {\n (nextResponse as any).url = res.url;\n }\n } catch {\n // ignore\n }\n\n return nextResponse;\n }\n\n return new NextResponse();\n};\n\nexport const getMonoCloudCookieReqRes = (\n req: unknown,\n resOrCtx: unknown\n): {\n request: IMonoCloudCookieRequest;\n response: IMonoCloudCookieResponse;\n} => {\n let request: IMonoCloudCookieRequest;\n let response: IMonoCloudCookieResponse;\n\n if (isAppRouter(req)) {\n request = new MonoCloudAppRouterRequest(getNextRequest(req as Request));\n\n response =\n resOrCtx instanceof Response\n ? new MonoCloudAppRouterResponse(getNextResponse(resOrCtx))\n : new MonoCloudCookieResponse();\n } else {\n if (!isNodeRequest(req) || !isNodeResponse(resOrCtx)) {\n throw new MonoCloudValidationError(\n 'Invalid pages router request and response'\n );\n }\n request = new MonoCloudPageRouterRequest(req as NextApiRequest);\n response = new MonoCloudPageRouterResponse(resOrCtx as NextApiResponse);\n }\n\n return { request, response };\n};\n\nexport const mergeResponse = (responses: NextResponse[]): NextResponse => {\n const resp = responses.pop();\n\n if (!resp) {\n return new NextResponse();\n }\n\n responses.forEach(response => {\n response.headers.forEach((v, k) => {\n if ((k === 'location' && !resp.headers.has(k)) || k !== 'location') {\n resp.headers.set(k, v);\n }\n });\n\n response.cookies.getAll().forEach(c => {\n const { name, value, ...cookieOpt } = c;\n resp.cookies.set(name, value, cookieOpt);\n });\n });\n\n return resp;\n};\n","/* 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 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 * @returns Returns the resolved session, or `undefined` if none exists.\n */\n public getSession(): 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 * @returns Returns the resolved session, or `undefined` if none exists.\n */\n public getSession(\n req: NextRequest | Request,\n res?: NextResponse | Response\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 * @returns Returns the resolved session, or `undefined` if none exists.\n */\n public getSession(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>\n ): Promise<MonoCloudSession | undefined>;\n\n async getSession(...args: any[]): Promise<MonoCloudSession | undefined> {\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 getSession()'\n );\n }\n\n return await this.coreClient.getSession(request, response);\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 (Array.isArray(options?.scopes)) {\n signInRoute.searchParams.set('scope', options.scopes.join(' '));\n }\n\n if (Array.isArray(options?.resource)) {\n signInRoute.searchParams.set('resource', options.resource.join(' '));\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","import type { ParsedUrlQuery } from 'node:querystring';\nimport { MonoCloudNextClient } from './monocloud-next-client';\nimport type {\n AppRouterApiHandlerFn,\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 type {\n NextMiddleware,\n NextProxy,\n NextRequest,\n NextFetchEvent,\n NextResponse,\n} from 'next/server';\nimport type { MonoCloudSession } from '@monocloud/auth-core';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { NextApiHandler, NextApiRequest, NextApiResponse } from 'next';\nimport type {\n GetTokensOptions,\n MonoCloudTokens,\n} from '@monocloud/auth-node-core';\n\nlet instance: MonoCloudNextClient | undefined;\n\n/**\n * Retrieves the singleton instance of the MonoCloudNextClient.\n * Initializes it lazily on the first call.\n */\nconst getInstance = (): MonoCloudNextClient => {\n instance ??= new MonoCloudNextClient();\n return instance;\n};\n\n/**\n * Creates a Next.js catch-all auth route handler (Pages Router and App Router) for the built-in routes (`/signin`, `/callback`, `/userinfo`, `/signout`).\n *\n * Mount this handler on a catch-all route (e.g. `/api/auth/[...monocloud]`).\n *\n * > If you already use `authMiddleware()`, you typically don’t need this handler. Use `monoCloudAuth()` when middleware cannot be used or when auth routes need customization.\n *\n * @example App Router\n * ```tsx:src/app/api/auth/[...monocloud]/route.ts tab=\"App Router\" tab-group=\"monoCloudAuth\"\n * import { monoCloudAuth } from \"@monocloud/auth-nextjs\";\n *\n * export const GET = monoCloudAuth();\n *```\n *\n * @example App Router (Response)\n * ```tsx:src/app/api/auth/[...monocloud]/route.ts tab=\"App Router (Response)\" tab-group=\"monoCloudAuth\"\n * import { monoCloudAuth } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = (req: NextRequest) => {\n * const authHandler = monoCloudAuth();\n *\n * const res = new NextResponse();\n *\n * res.cookies.set(\"last_auth_requested\", `${Date.now()}`);\n *\n * return authHandler(req, res);\n * };\n * ```\n *\n * @example Pages Router\n * ```tsx:src/pages/api/auth/[...monocloud].ts tab=\"Pages Router\" tab-group=\"monoCloudAuth\"\n * import { monoCloudAuth } from \"@monocloud/auth-nextjs\";\n *\n * export default monoCloudAuth();\n *```\n *\n * @example Pages Router (Response)\n * ```tsx:src/pages/api/auth/[...monocloud].ts tab=\"Pages Router (Response)\" tab-group=\"monoCloudAuth\"\n * import { monoCloudAuth } from \"@monocloud/auth-nextjs\";\n * import { NextApiRequest, NextApiResponse } from \"next\";\n *\n * export default function handler(req: NextApiRequest, res: NextApiResponse) {\n * const authHandler = monoCloudAuth();\n *\n * res.setHeader(\"last_auth_requested\", `${Date.now()}`);\n *\n * return authHandler(req, res);\n * }\n * ```\n *\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 * @category Functions\n */\nexport function monoCloudAuth(\n options?: MonoCloudAuthOptions\n): MonoCloudAuthHandler {\n return getInstance().monoCloudAuth(options);\n}\n\n/**\n * Creates a Next.js authentication middleware that protects routes.\n *\n * By default, all routes matched by `config.matcher` are protected unless configured otherwise.\n *\n * @example Protect All Routes\n * ```tsx:src/proxy.ts tab=\"Protect All Routes\" tab-group=\"auth-middleware\"\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 * @example Protect Selected Routes\n * ```tsx:src/proxy.ts tab=\"Protect Selected Routes\" tab-group=\"auth-middleware\"\n * import { authMiddleware } from \"@monocloud/auth-nextjs\";\n *\n * export default authMiddleware({\n * protectedRoutes: [\"/api/admin\", \"^/api/protected(/.*)?$\"],\n * });\n *\n * export const config = {\n * matcher: [\n * \"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)\",\n * ],\n * };\n *```\n *\n * @example No Protected Routes\n * ```tsx:src/proxy.ts tab=\"No Protected Routes\" tab-group=\"auth-middleware\"\n * import { authMiddleware } from \"@monocloud/auth-nextjs\";\n *\n * export default authMiddleware({\n * protectedRoutes: [],\n * });\n *\n * export const config = {\n * matcher: [\n * \"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)\",\n * ],\n * };\n * ```\n *\n * @example Dynamic\n * ```tsx:src/proxy.ts tab=\"Dynamic\" tab-group=\"auth-middleware\"\n * import { authMiddleware } from \"@monocloud/auth-nextjs\";\n *\n * export default authMiddleware({\n * protectedRoutes: (req) => {\n * return req.nextUrl.pathname.startsWith(\"/api/protected\");\n * },\n * });\n *\n * export const config = {\n * matcher: [\n * \"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)\",\n * ],\n * };\n * ```\n *\n * @example Group Protection\n * ```tsx:src/proxy.ts tab=\"Group Protection\" tab-group=\"auth-middleware\"\n * import { authMiddleware } from \"@monocloud/auth-nextjs\";\n *\n * export default authMiddleware({\n * protectedRoutes: [\n * {\n * groups: [\"admin\", \"editor\", \"537e7c3d-a442-4b5b-b308-30837aa045a4\"],\n * routes: [\"/internal\", \"/api/internal(.*)\"],\n * },\n * ],\n * });\n *\n * export const config = {\n * matcher: [\n * \"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)\",\n * ],\n * };\n * ```\n *\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, such as a NextResponse, redirect, or undefined to continue processing.\n *\n * @category Functions\n */\nexport function authMiddleware(\n options?: MonoCloudMiddlewareOptions\n): NextMiddleware | NextProxy;\n\n/**\n * Executes the authentication middleware manually.\n *\n * Intended for advanced scenarios where the middleware is composed within custom logic.\n *\n * @example Composing with custom middleware\n *\n * ```tsx:src/proxy.ts title=\"Composing with custom middleware\"\n * import { authMiddleware } from \"@monocloud/auth-nextjs\";\n * import { NextFetchEvent, NextRequest, NextResponse } from \"next/server\";\n *\n * export default function customMiddleware(req: NextRequest, evt: NextFetchEvent) {\n * if (req.nextUrl.pathname.startsWith(\"/api/protected\")) {\n * return authMiddleware(req, evt);\n * }\n *\n * return NextResponse.next();\n * }\n *\n * export const config = {\n * matcher: [\n * \"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)\",\n * ],\n * };\n * ```\n *\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 * @category Functions\n */\nexport function authMiddleware(\n request: NextRequest,\n event: NextFetchEvent\n): Promise<NextMiddlewareResult> | NextMiddlewareResult;\n\nexport function authMiddleware(\n ...args: any[]\n):\n | NextMiddleware\n | NextProxy\n | Promise<NextMiddlewareResult>\n | NextMiddlewareResult {\n return getInstance().authMiddleware(...args);\n}\n\n/**\n * Retrieves the current user's session using the active server request context.\n *\n * Intended for Server Components, Server Actions, Route Handlers, and Middleware where the request is implicitly available.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"session-ssr\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n *\n * export default async function Home() {\n * const session = await getSession();\n *\n * return <div>{session?.user.name}</div>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"session-ssr\"\n * \"use server\";\n *\n * import { getSession } from \"@monocloud/auth-nextjs\";\n *\n * export async function getUserAction() {\n * const session = await getSession();\n *\n * return { name: session?.user.name };\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/user/route.ts tab=\"API Handler\" tab-group=\"session-ssr\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const session = await getSession();\n *\n * return NextResponse.json({ name: session?.user.name });\n * };\n * ```\n *\n * @example Middleware\n * ```tsx:src/proxy.ts tab=\"Middleware\" tab-group=\"session-ssr\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export default async function proxy() {\n * const session = await getSession();\n *\n * if (!session) {\n * return new NextResponse(\"User not signed in\", { status: 401 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @returns Returns the resolved session, or `undefined` if none exists.\n *\n * @category Functions\n */\nexport function getSession(): Promise<MonoCloudSession | undefined>;\n\n/**\n * Retrieves the current user's session using an explicit Web or Next.js request.\n *\n * Use this overload when you already have access to a `Request` or `NextRequest` (for example in Middleware or Route Handlers).\n *\n * @example Middleware (Request)\n * ```tsx:src/proxy.ts tab=\"Middleware (Request)\" tab-group=\"session-route-handler\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const session = await getSession(req);\n *\n * if (!session) {\n * return new NextResponse(\"User not signed in\", { status: 401 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @example Middleware (Response)\n * ```tsx:src/proxy.ts tab=\"Middleware (Response)\" tab-group=\"session-route-handler\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const res = NextResponse.next();\n *\n * const session = await getSession(req, res);\n *\n * if (!session) {\n * return new NextResponse(\"User not signed in\", { status: 401 });\n * }\n *\n * res.headers.set(\"x-auth-status\", \"active\");\n *\n * return res;\n * }\n * ```\n *\n * @example API Handler (Request)\n * ```tsx:src/app/api/user/route.ts tab=\"API Handler (Request)\" tab-group=\"session-route-handler\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const session = await getSession(req);\n *\n * return NextResponse.json({ name: session?.user.name });\n * };\n * ```\n *\n * @example API Handler (Response)\n * ```tsx:src/app/api/user/route.ts tab=\"API Handler (Response)\" tab-group=\"session-route-handler\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const res = new NextResponse(\"YOUR CUSTOM RESPONSE\");\n *\n * const session = await getSession(req, res);\n *\n * if (session?.user) {\n * res.cookies.set(\"something\", \"important\");\n * }\n *\n * return res;\n * };\n * ```\n *\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 * @returns Returns the resolved session, or `undefined` if none exists.\n *\n * @category Functions\n */\nexport function getSession(\n req: NextRequest | Request,\n res?: NextResponse | Response\n): Promise<MonoCloudSession | undefined>;\n\n/**\n * Retrieves the current user's session in the Pages Router or Node.js runtime.\n *\n * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.\n *\n * @example Pages Router (Pages)\n * ```tsx:src/pages/index.tsx tab=\"Pages Router (Pages)\" tab-group=\"session-pages\"\n * import { getSession, MonoCloudSession } from \"@monocloud/auth-nextjs\";\n * import { GetServerSideProps } from \"next\";\n *\n * type Props = {\n * session?: MonoCloudSession;\n * };\n *\n * export default function Home({ session }: Props) {\n * return <pre>Session: {JSON.stringify(session, null, 2)}</pre>;\n * }\n *\n * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {\n * const session = await getSession(ctx.req, ctx.res);\n *\n * return {\n * props: {\n * session\n * }\n * };\n * };\n * ```\n * @example Pages Router (API)\n * ```tsx:src/pages/api/user.ts tab=\"Pages Router (API)\" tab-group=\"session-pages\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextApiRequest, NextApiResponse } from \"next\";\n *\n * export default async function handler(\n * req: NextApiRequest,\n * res: NextApiResponse\n * ) {\n * const session = await getSession(req, res);\n *\n * res.status(200).json({ name: session?.user.name });\n * }\n * ```\n *\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 * @returns Returns the resolved session, or `undefined` if none exists.\n *\n * @category Functions\n */\nexport function getSession(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>\n): Promise<MonoCloudSession | undefined>;\n\nexport function getSession(\n ...args: any[]\n): Promise<MonoCloudSession | undefined> {\n return (getInstance().getSession as any)(...args);\n}\n\n/**\n * Retrieves the current user's tokens using the active server request context.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"tokens-ssr\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n *\n * export default async function Home() {\n * const tokens = await getTokens();\n *\n * return <div>Expired: {tokens.isExpired.toString()}</div>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"tokens-ssr\"\n * \"use server\";\n *\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n *\n * export async function getExpiredAction() {\n * const tokens = await getTokens();\n *\n * return { expired: tokens.isExpired };\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/tokens/route.ts tab=\"API Handler\" tab-group=\"tokens-ssr\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const tokens = await getTokens();\n *\n * return NextResponse.json({ expired: tokens.isExpired });\n * };\n * ```\n *\n * @example Middleware\n * ```tsx:src/proxy.ts tab=\"Middleware\" tab-group=\"tokens-ssr\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export default async function proxy() {\n * const tokens = await getTokens();\n *\n * if (tokens.isExpired) {\n * return new NextResponse(\"Tokens expired\", { status: 401 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @example Refresh the default token\n *\n * The **default token** is the access token associated with your default authorization parameters:\n * - Scopes: `MONOCLOUD_AUTH_SCOPES` or `options.defaultAuthParams.scopes`\n * - Resource: `MONOCLOUD_AUTH_RESOURCE` or `options.defaultAuthParams.resource`\n *\n * Calling `getTokens()` returns the current token set and **refreshes the default token automatically when needed** (for example, if it has expired). To force a refresh even when it isn’t expired, use `forceRefresh: true`.\n *\n * ```tsx:src/app/page.tsx title=\"Refresh default token\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * // Forces a refresh of the default token\n * const tokens = await getTokens({ forceRefresh: true });\n *\n * return NextResponse.json({ accessToken: tokens?.accessToken });\n * };\n * ```\n *\n * @example Request an access token for resource(s)\n *\n * Use `resource` and `scopes` to request an access token for one or more resources.\n *\n * > The requested resource and scopes must be included in the initial authorization flow (so the user has consented / the session is eligible to mint that token).\n *\n * ```tsx:src/app/page.tsx title=\"Request a new access token for resource(s)\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const tokens = await getTokens({\n * resource: \"https://first.example.com https://second.example.com\",\n * scopes: \"read:first read:second shared\",\n * });\n *\n * return NextResponse.json({ accessToken: tokens?.accessToken });\n * };\n * ```\n *\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 * @category Functions\n */\nexport function getTokens(options?: GetTokensOptions): Promise<MonoCloudTokens>;\n\n/**\n * Retrieves the current user's tokens using an explicit Web or Next.js request.\n *\n * Use this overload when you already have access to a `Request` or `NextRequest` (for example, in Middleware or Route Handlers).\n *\n * @example Middleware (Request)\n * ```tsx:src/proxy.ts tab=\"Middleware (Request)\" tab-group=\"tokens-route-handler-request\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const tokens = await getTokens(req);\n *\n * if (tokens.isExpired) {\n * return new NextResponse(\"Tokens expired\", { status: 401 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @example API Handler (Request)\n * ```tsx:src/app/api/tokens/route.ts tab=\"API Handler (Request)\" tab-group=\"tokens-route-handler-request\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const tokens = await getTokens(req);\n *\n * return NextResponse.json({ expired: tokens?.isExpired });\n * };\n * ```\n *\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 * @category Functions\n */\nexport function getTokens(\n req: NextRequest | Request,\n options?: GetTokensOptions\n): Promise<MonoCloudTokens>;\n\n/**\n * Retrieves the current user's tokens using an explicit request and response.\n *\n * Use this overload when you have already created a response and want refreshed authentication cookies or headers applied to it.\n *\n * @example Middleware (Response)\n *```tsx:src/proxy.ts tab=\"Middleware (Response)\" tab-group=\"tokens-route-handler-response\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const res = NextResponse.next();\n *\n * const tokens = await getTokens(req, res);\n *\n * res.headers.set(\"x-tokens-expired\", tokens.isExpired.toString());\n *\n * return res;\n * }\n * ```\n *\n * @example API Handler (Response)\n * ```tsx:src/app/api/tokens/route.ts tab=\"API Handler (Response)\" tab-group=\"tokens-route-handler-response\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const res = new NextResponse(\"Custom Body\");\n *\n * const tokens = await getTokens(req, res);\n *\n * if (!tokens.isExpired) {\n * res.headers.set(\"x-auth-status\", \"active\");\n * }\n *\n * return res;\n * };\n * ```\n *\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 * @category Functions\n */\nexport function getTokens(\n req: NextRequest | Request,\n res: NextResponse | Response,\n options?: GetTokensOptions\n): Promise<MonoCloudTokens>;\n\n/**\n * Retrieves the current user's tokens in the Pages Router or Node.js runtime.\n *\n * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.\n *\n * @example Pages Router (Pages)\n * ```tsx:src/pages/index.tsx tab=\"Pages Router (Pages)\" tab-group=\"tokens-pages\"\n * import { getTokens, MonoCloudTokens } from \"@monocloud/auth-nextjs\";\n * import { GetServerSideProps } from \"next\";\n *\n * type Props = {\n * tokens: MonoCloudTokens;\n * };\n *\n * export default function Home({ tokens }: Props) {\n * return <pre>Tokens: {JSON.stringify(tokens, null, 2)}</pre>;\n * }\n *\n * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {\n * const tokens = await getTokens(ctx.req, ctx.res);\n *\n * return {\n * props: {\n * tokens: tokens\n * }\n * };\n * };\n * ```\n *\n * @example Pages Router (API)\n * ```tsx:src/pages/api/tokens.ts tab=\"Pages Router (API)\" tab-group=\"tokens-pages\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextApiRequest, NextApiResponse } from \"next\";\n *\n * export default async function handler(\n * req: NextApiRequest,\n * res: NextApiResponse\n * ) {\n * const tokens = await getTokens(req, res);\n *\n * res.status(200).json({ accessToken: tokens?.accessToken });\n * }\n * ```\n *\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 * @category Functions\n */\nexport function getTokens(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>,\n options?: GetTokensOptions\n): Promise<MonoCloudTokens>;\n\nexport function getTokens(...args: any[]): Promise<MonoCloudTokens> {\n return getInstance().getTokens(...args);\n}\n\n/**\n * Checks whether the current user is authenticated using the active server request context.\n *\n * Intended for Server Components, Server Actions, Route Handlers, and Middleware where the request is implicitly available.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"is-authenticated-ssr\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n *\n * export default async function Home() {\n * const authenticated = await isAuthenticated();\n *\n * return <div>Authenticated: {authenticated.toString()}</div>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"is-authenticated-ssr\"\n * \"use server\";\n *\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n *\n * export async function checkAuthAction() {\n * const authenticated = await isAuthenticated();\n *\n * return { authenticated };\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/authenticated/route.ts tab=\"API Handler\" tab-group=\"is-authenticated-ssr\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const authenticated = await isAuthenticated();\n *\n * return NextResponse.json({ authenticated });\n * };\n * ```\n *\n * @example Middleware\n * ```tsx:src/proxy.ts tab=\"Middleware\" tab-group=\"is-authenticated-ssr\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export default async function proxy() {\n * const authenticated = await isAuthenticated();\n *\n * if (!authenticated) {\n * return new NextResponse(\"User not signed in\", { status: 401 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @returns Returns `true` if a valid session exists; otherwise `false`.\n *\n * @category Functions\n */\nexport function isAuthenticated(): Promise<boolean>;\n\n/**\n * Checks whether the current user is authenticated using an explicit Web or Next.js request.\n *\n * Use this overload when you already have access to a `Request` or `NextRequest` (for example, in Middleware or Route Handlers).\n *\n * @example Middleware (Request)\n * ```tsx:src/proxy.ts tab=\"Middleware (Request)\" tab-group=\"is-authenticated-route-handler\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const authenticated = await isAuthenticated(req);\n *\n * if (!authenticated) {\n * return new NextResponse(\"User not signed in\", { status: 401 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @example Middleware (Response)\n * ```tsx:src/proxy.ts tab=\"Middleware (Response)\" tab-group=\"is-authenticated-route-handler\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const res = NextResponse.next();\n *\n * const authenticated = await isAuthenticated(req, res);\n *\n * if (!authenticated) {\n * return new NextResponse(\"User not signed in\", { status: 401 });\n * }\n *\n * res.headers.set(\"x-authenticated\", \"true\");\n *\n * return res;\n * }\n * ```\n *\n * @example API Handler (Request)\n * ```tsx:src/app/api/authenticated/route.ts tab=\"API Handler (Request)\" tab-group=\"is-authenticated-route-handler\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const authenticated = await isAuthenticated(req);\n *\n * return NextResponse.json({ authenticated });\n * };\n * ```\n *\n * @example API Handler (Response)\n * ```tsx:src/app/api/authenticated/route.ts tab=\"API Handler (Response)\" tab-group=\"is-authenticated-route-handler\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const res = new NextResponse(\"YOUR CUSTOM RESPONSE\");\n *\n * const authenticated = await isAuthenticated(req, res);\n *\n * if (authenticated) {\n * res.cookies.set(\"something\", \"important\");\n * }\n *\n * return res;\n * };\n * ```\n *\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 * @category Functions\n */\nexport function isAuthenticated(\n req: NextRequest | Request,\n res?: NextResponse | Response\n): Promise<boolean>;\n\n/**\n * Checks whether the current user is authenticated in the Pages Router or Node.js runtime.\n *\n * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.\n *\n * @example Pages Router (Pages)\n * ```tsx:src/pages/index.tsx tab=\"Pages Router (Pages)\" tab-group=\"is-authenticated-pages\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { GetServerSideProps } from \"next\";\n *\n * type Props = {\n * authenticated: boolean;\n * };\n *\n * export default function Home({ authenticated }: Props) {\n * return <pre>User is {authenticated ? \"logged in\" : \"guest\"}</pre>;\n * }\n *\n * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {\n * const authenticated = await isAuthenticated(ctx.req, ctx.res);\n *\n * return {\n * props: {\n * authenticated\n * }\n * };\n * };\n * ```\n *\n * @example Pages Router (API)\n * ```tsx:src/pages/api/authenticated.ts tab=\"Pages Router (API)\" tab-group=\"is-authenticated-pages\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextApiRequest, NextApiResponse } from \"next\";\n *\n * export default async function handler(\n * req: NextApiRequest,\n * res: NextApiResponse\n * ) {\n * const authenticated = await isAuthenticated(req, res);\n *\n * res.status(200).json({ authenticated });\n * }\n * ```\n *\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 * @category Functions\n */\nexport function isAuthenticated(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>\n): Promise<boolean>;\n\nexport function isAuthenticated(...args: any[]): Promise<boolean> {\n return (getInstance().isAuthenticated as any)(...args);\n}\n\n/**\n * Ensures the current user is authenticated. If not, redirects to the sign-in flow.\n *\n * > **App Router only.** Intended for Server Components, Route Handlers, and Server Actions.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"protect\"\n * import { protect } from \"@monocloud/auth-nextjs\";\n *\n * export default async function Home() {\n * await protect();\n *\n * return <>You are signed in.</>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"protect\"\n * \"use server\";\n *\n * import { protect } from \"@monocloud/auth-nextjs\";\n *\n * export async function getMessage() {\n * await protect();\n *\n * return { secret: \"sssshhhhh!!!\" };\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/protected/route.ts tab=\"API Handler\" tab-group=\"protect\"\n * import { protect } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * await protect();\n *\n * return NextResponse.json({ secret: \"ssshhhh!!!\" });\n * };\n * ```\n *\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 * @category Functions\n */\nexport function protect(options?: ProtectOptions): Promise<void> {\n return getInstance().protect(options);\n}\n\n/**\n * Wraps an App Router API route handler and ensures that only authenticated (and optionally authorized) requests can access the route.\n *\n * Intended for Next.js App Router Route Handlers.\n *\n * @example\n * ```tsx:src/app/api/protected/route.ts\n * import { protectApi } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = protectApi(async () => {\n * return NextResponse.json({\n * message: \"You accessed a protected endpoint\",\n * });\n * });\n * ```\n *\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 * @category Functions\n */\nexport function protectApi(\n handler: AppRouterApiHandlerFn,\n options?: ProtectApiAppOptions\n): AppRouterApiHandlerFn;\n\n/**\n * Wraps a Pages Router API route handler and ensures that only authenticated (and optionally authorized) requests can access the route.\n *\n * Intended for Next.js Pages Router API routes.\n *\n * @example\n * ```tsx:src/pages/api/protected.ts\n * import { protectApi } from \"@monocloud/auth-nextjs\";\n * import { NextApiRequest, NextApiResponse } from \"next\";\n *\n * export default protectApi(\n * async (req: NextApiRequest, res: NextApiResponse) => {\n * return res.json({\n * message: \"You accessed a protected endpoint\",\n * });\n * }\n * );\n * ```\n *\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 * @category Functions\n */\nexport function protectApi(\n handler: NextApiHandler,\n options?: ProtectApiPageOptions\n): NextApiHandler;\n\nexport function protectApi(\n handler: AppRouterApiHandlerFn | NextApiHandler,\n options?: ProtectApiAppOptions | ProtectApiPageOptions\n): AppRouterApiHandlerFn | NextApiHandler {\n return (getInstance().protectApi as any)(handler, options);\n}\n\n/**\n * Restricts access to App Router server-rendered pages.\n *\n * **Access control**\n * - If the user is not authenticated, `onAccessDenied` is invoked (or default behavior applies).\n * - If the user is authenticated but fails group checks, `onGroupAccessDenied` is invoked (or the default \"Access Denied\" view is rendered).\n *\n * Both behaviors can be customized via options.\n *\n * @example Basic Usage\n * ```tsx:src/app/page.tsx tab=\"Basic Usage\" tab-group=\"protectPage-app\"\n * import { protectPage } from \"@monocloud/auth-nextjs\";\n *\n * export default protectPage(async function Home({ user }) {\n * return <>Hi {user.email}. You accessed a protected page.</>;\n * });\n * ```\n *\n * @example With Options\n * ```tsx:src/app/page.tsx tab=\"With Options\" tab-group=\"protectPage-app\"\n * import { protectPage } from \"@monocloud/auth-nextjs\";\n *\n * export default protectPage(\n * async function Home({ user }) {\n * return <>Hi {user.email}. You accessed a protected page.</>;\n * },\n * {\n * returnUrl: \"/dashboard\",\n * groups: [\"admin\"],\n * }\n * );\n * ```\n *\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 * @category Functions\n */\nexport function protectPage(\n component: ProtectedAppServerComponent,\n options?: ProtectAppPageOptions\n): AppRouterPageHandler;\n\n/**\n * Restricts access to Pages Router server-rendered pages using `getServerSideProps`.\n *\n * **Access control**\n * - If the user is not authenticated, `onAccessDenied` is invoked (or default behavior applies).\n * - If the user is authenticated but fails group checks, the page can still render and `groupAccessDenied` is provided in props. Use `onGroupAccessDenied` to customize the props or behavior.\n *\n * Both behaviors can be customized via options.\n *\n * @example Basic Usage\n * ```tsx:src/pages/index.tsx tab=\"Basic Usage\" tab-group=\"protectPage-page\"\n * import { protectPage, MonoCloudUser } from \"@monocloud/auth-nextjs\";\n *\n * type Props = {\n * user: MonoCloudUser;\n * };\n *\n * export default function Home({ user }: Props) {\n * return <>Hi {user.email}. You accessed a protected page.</>;\n * }\n *\n * export const getServerSideProps = protectPage();\n * ```\n *\n * @example With Options\n * ```tsx:src/pages/index.tsx tab=\"With Options\" tab-group=\"protectPage-page\"\n * import { protectPage, MonoCloudUser } from \"@monocloud/auth-nextjs\";\n * import { GetServerSidePropsContext } from \"next\";\n *\n * type Props = {\n * user: MonoCloudUser;\n * url: string;\n * };\n *\n * export default function Home({ user, url }: Props) {\n * console.log(url);\n * return <div>Hi {user?.email}. You accessed a protected page.</div>;\n * }\n *\n * export const getServerSideProps = protectPage({\n * returnUrl: \"/dashboard\",\n * groups: [\"admin\"],\n * getServerSideProps: async (context: GetServerSidePropsContext) => ({\n * props: { url: context.resolvedUrl }\n * })\n * });\n * ```\n *\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 * @category Functions\n */\nexport function protectPage<\n P extends Record<string, any> = Record<string, any>,\n Q extends ParsedUrlQuery = ParsedUrlQuery,\n>(options?: ProtectPagePageOptions<P, Q>): ProtectPagePageReturnType<P, Q>;\n\nexport function protectPage(...args: any[]): any {\n return getInstance().protectPage(...args);\n}\n\n/**\n * Checks whether the currently authenticated user is a member of **any** of the specified groups.\n *\n * The `groups` parameter accepts group identifiers (IDs or names).\n *\n * The authenticated user's session may contain groups represented as:\n * - Group IDs\n * - Group names\n * - `Group` objects (for example, `{ id: string; name: string }`)\n *\n * Matching is always performed against the group's **ID** and **name**, regardless of how the group is represented in the session.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"is-user-in-group-rsc\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n *\n * export default async function AdminPanel() {\n * const isAdmin = await isUserInGroup([\"admin\"]);\n *\n * if (!isAdmin) {\n * return <div>Access Denied</div>;\n * }\n *\n * return <div>Admin Control Panel</div>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"is-user-in-group-rsc\"\n * \"use server\";\n *\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n *\n * export async function deletePostAction() {\n * const canDelete = await isUserInGroup([\"admin\", \"editor\"]);\n *\n * if (!canDelete) {\n * return { success: false };\n * }\n *\n * return { success: true };\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/group-check/route.ts tab=\"API Handler\" tab-group=\"is-user-in-group-rsc\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const allowed = await isUserInGroup([\"admin\", \"editor\"]);\n *\n * if (!allowed) {\n * return new NextResponse(\"Forbidden\", { status: 403 });\n * }\n *\n * return NextResponse.json({ status: \"success\" });\n * };\n * ```\n *\n * @example Middleware\n * ```tsx:src/proxy.ts tab=\"Middleware\" tab-group=\"is-user-in-group-rsc\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export default async function proxy() {\n * const isAdmin = await isUserInGroup([\"admin\"]);\n *\n * if (!isAdmin) {\n * return new NextResponse(\"User is not admin\", { status: 403 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\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 * @category Functions\n */\nexport function isUserInGroup(\n groups: string[],\n options?: IsUserInGroupOptions\n): Promise<boolean>;\n\n/**\n * Checks group membership using an explicit Web or Next.js request.\n *\n * Use this overload when you already have access to a `Request` or `NextRequest` (for example, in Middleware or Route Handlers).\n *\n * @example Middleware (Request)\n * ```tsx:src/proxy.ts tab=\"Middleware (Request)\" tab-group=\"is-user-in-group-request\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const isAdmin = await isUserInGroup(req, [\"admin\"]);\n *\n * if (!isAdmin) {\n * return new NextResponse(\"User is not admin\", { status: 403 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @example API Handler (Request)\n * ```tsx:src/app/api/group-check/route.ts tab=\"API Handler (Request)\" tab-group=\"is-user-in-group-request\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const isMember = await isUserInGroup(req, [\"admin\", \"editor\"]);\n *\n * return NextResponse.json({ isMember });\n * };\n * ```\n *\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 * @category Functions\n */\nexport function isUserInGroup(\n req: NextRequest | Request,\n groups: string[],\n options?: IsUserInGroupOptions\n): Promise<boolean>;\n\n/**\n * Checks group membership using an explicit request and response.\n *\n * Use this overload when you have already created a response and want refreshed authentication cookies or headers applied to it.\n *\n * @example Middleware (Response)\n * ```tsx:src/proxy.ts tab=\"Middleware (Response)\" tab-group=\"is-user-in-group-response\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const res = NextResponse.next();\n *\n * const isAdmin = await isUserInGroup(req, res, [\"admin\"]);\n *\n * if (!isAdmin) {\n * return new NextResponse(\"User is not admin\", { status: 403 });\n * }\n *\n * res.headers.set(\"x-user\", \"admin\");\n *\n * return res;\n * }\n * ```\n *\n * @example API Handler (Response)\n * ```tsx:src/app/api/group-check/route.ts tab=\"API Handler (Response)\" tab-group=\"is-user-in-group-response\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const res = new NextResponse(\"Restricted Content\");\n *\n * const allowed = await isUserInGroup(req, res, [\"admin\"]);\n *\n * if (!allowed) {\n * return new NextResponse(\"Not Allowed\", res);\n * }\n *\n * return res;\n * };\n * ```\n *\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 * @category Functions\n */\nexport function isUserInGroup(\n req: NextRequest | Request,\n res: NextResponse | Response,\n groups: string[],\n options?: IsUserInGroupOptions\n): Promise<boolean>;\n\n/**\n * Checks group membership in the Pages Router or Node.js runtime.\n *\n * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.\n *\n * @example Pages Router (Pages)\n * ```tsx:src/pages/index.tsx tab=\"Pages Router (Pages)\" tab-group=\"is-user-in-group-pages\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { GetServerSideProps } from \"next\";\n *\n * type Props = {\n * isAdmin: boolean;\n * };\n *\n * export default function Home({ isAdmin }: Props) {\n * return <div>User is admin: {isAdmin.toString()}</div>;\n * }\n *\n * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {\n * const isAdmin = await isUserInGroup(ctx.req, ctx.res, [\"admin\"]);\n *\n * return {\n * props: {\n * isAdmin\n * }\n * };\n * };\n * ```\n *\n * @example Pages Router (API)\n * ```tsx:src/pages/api/group-check.ts tab=\"Pages Router (API)\" tab-group=\"is-user-in-group-pages\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextApiRequest, NextApiResponse } from \"next\";\n *\n * export default async function handler(\n * req: NextApiRequest,\n * res: NextApiResponse\n * ) {\n * const isAdmin = await isUserInGroup(req, res, [\"admin\"]);\n *\n * if (!isAdmin) {\n * return res.status(403).json({ error: \"Forbidden\" });\n * }\n *\n * res.status(200).json({ message: \"Welcome Admin\" });\n * }\n * ```\n *\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 * @category Functions\n */\nexport function isUserInGroup(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>,\n groups: string[],\n options?: IsUserInGroupOptions\n): Promise<boolean>;\n\nexport function isUserInGroup(...args: any[]): Promise<boolean> {\n return (getInstance().isUserInGroup as any)(...args);\n}\n\n/**\n * Redirects the user to the sign-in flow.\n *\n * > **App Router only**. Intended for use in Server Components, Route Handlers, and Server Actions.\n *\n * This helper performs a server-side redirect to the configured sign-in route. Execution does not continue after the redirect is triggered.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"redirect-to-sign-in\"\n * import { isUserInGroup, redirectToSignIn } from \"@monocloud/auth-nextjs\";\n *\n * export default async function Home() {\n * const allowed = await isUserInGroup([\"admin\"]);\n *\n * if (!allowed) {\n * await redirectToSignIn({ returnUrl: \"/home\" });\n * }\n *\n * return <>You are signed in.</>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"redirect-to-sign-in\"\n * \"use server\";\n *\n * import { getSession, redirectToSignIn } from \"@monocloud/auth-nextjs\";\n *\n * export async function protectedAction() {\n * const session = await getSession();\n *\n * if (!session) {\n * await redirectToSignIn();\n * }\n *\n * return { data: \"Sensitive Data\" };\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/protected/route.ts tab=\"API Handler\" tab-group=\"redirect-to-sign-in\"\n * import { getSession, redirectToSignIn } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const session = await getSession();\n *\n * if (!session) {\n * await redirectToSignIn({\n * returnUrl: \"/dashboard\",\n * });\n * }\n *\n * return NextResponse.json({ data: \"Protected content\" });\n * };\n * ```\n *\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 * @category Functions\n */\nexport function redirectToSignIn(\n options?: RedirectToSignInOptions\n): Promise<void> {\n return getInstance().redirectToSignIn(options);\n}\n\n/**\n * Redirects the user to the sign-out flow.\n *\n * > **App Router only**. Intended for use in Server Components, Route Handlers, and Server Actions.\n *\n * This helper performs a server-side redirect to the configured sign-out route. Execution does not continue after the redirect is triggered.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"redirect-to-sign-out\"\n * import { getSession, redirectToSignOut } from \"@monocloud/auth-nextjs\";\n *\n * export default async function Page() {\n * const session = await getSession();\n *\n * // Example: Force sign-out if a specific condition is met (e.g., account suspended)\n * if (session?.user.isSuspended) {\n * await redirectToSignOut();\n * }\n *\n * return <>Welcome User</>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"redirect-to-sign-out\"\n * \"use server\";\n *\n * import { getSession, redirectToSignOut } from \"@monocloud/auth-nextjs\";\n *\n * export async function signOutAction() {\n * const session = await getSession();\n *\n * if (session) {\n * await redirectToSignOut();\n * }\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/signout/route.ts tab=\"API Handler\" tab-group=\"redirect-to-sign-out\"\n * import { getSession, redirectToSignOut } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const session = await getSession();\n *\n * if (session) {\n * await redirectToSignOut({\n * postLogoutRedirectUri: \"/goodbye\",\n * });\n * }\n *\n * return NextResponse.json({ status: \"already_signed_out\" });\n * };\n * ```\n *\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 * @category Functions\n */\nexport function redirectToSignOut(\n options?: RedirectToSignOutOptions\n): Promise<void> {\n return getInstance().redirectToSignOut(options);\n}\n"],"mappings":";;;;;;;;;AAIA,IAAqB,4BAArB,MAA2E;CACzE,YAAY,AAAgB,KAAkB;EAAlB;;CAE5B,SAAS,WAAkD;AAEzD,SADY,IAAI,IAAI,KAAK,IAAI,IAAI,CACtB,aAAa,IAAI,UAAU,IAAI;;CAG5C,UAAU,MAA2C;;AACnD,SAAO,QAAQ,iCAAQ,KAAK,IAAI,QAAQ,IAAI,KAAK,gFAAE,MAAM;;CAG3D,MAAM,gBAIH;AACD,SAAO;GACL,QAAQ,KAAK,IAAI;GACjB,KAAK,KAAK,IAAI;GACd,MAAM,MAAM,KAAK,IAAI,MAAM;GAC5B;;CAGH,gBAA8C;EAC5C,MAAM,yBAAS,IAAI,KAAqB;AACxC,OAAK,IAAI,QAAQ,QAAQ,CAAC,SAAQ,MAAK;AACrC,UAAO,IAAI,EAAE,MAAM,EAAE,MAAM;IAC3B;AACF,SAAO,QAAQ,QAAQ,OAAO;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AAO,aAAa,CAAC,cAAc,QAAQ;;AAsI7C,SAAgB,eACd,GAAG,MAKoB;AACvB,QAAO,aAAa,CAAC,eAAe,GAAG,KAAK;;AA0M9C,SAAgB,WACd,GAAG,MACoC;AACvC,QAAQ,aAAa,CAAC,WAAmB,GAAG,KAAK;;AAsQnD,SAAgB,UAAU,GAAG,MAAuC;AAClE,QAAO,aAAa,CAAC,UAAU,GAAG,KAAK;;AA2MzC,SAAgB,gBAAgB,GAAG,MAA+B;AAChE,QAAQ,aAAa,CAAC,gBAAwB,GAAG,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDxD,SAAgB,QAAQ,SAAyC;AAC/D,QAAO,aAAa,CAAC,QAAQ,QAAQ;;AA6DvC,SAAgB,WACd,SACA,SACwC;AACxC,QAAQ,aAAa,CAAC,WAAmB,SAAS,QAAQ;;AA2G5D,SAAgB,YAAY,GAAG,MAAkB;AAC/C,QAAO,aAAa,CAAC,YAAY,GAAG,KAAK;;AAiQ3C,SAAgB,cAAc,GAAG,MAA+B;AAC9D,QAAQ,aAAa,CAAC,cAAsB,GAAG,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEtD,SAAgB,iBACd,SACe;AACf,QAAO,aAAa,CAAC,iBAAiB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEhD,SAAgB,kBACd,SACe;AACf,QAAO,aAAa,CAAC,kBAAkB,QAAQ"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["NextResponse","cookie","NextRequest","NextResponse","MonoCloudValidationError","MonoCloudCoreClient","NextResponse","MonoCloudValidationError"],"sources":["../src/requests/monocloud-app-router-request.ts","../src/requests/monocloud-page-router-request.ts","../src/responses/monocloud-app-router-response.ts","../src/responses/monocloud-page-router-response.ts","../src/responses/monocloud-cookie-response.ts","../src/requests/monocloud-cookie-request.ts","../src/utils.ts","../src/monocloud-next-client.ts","../src/initialize.ts"],"sourcesContent":["import type { MonoCloudRequest } from '@monocloud/auth-node-core';\n// eslint-disable-next-line import/extensions\nimport type { NextRequest } from 'next/server.js';\n\nexport default class MonoCloudAppRouterRequest implements MonoCloudRequest {\n constructor(public readonly req: NextRequest) {}\n\n getQuery(parameter: string): string | string[] | undefined {\n const url = new URL(this.req.url);\n return url.searchParams.get(parameter) ?? undefined;\n }\n\n getCookie(name: string): Promise<string | undefined> {\n return Promise.resolve(this.req.cookies.get(name)?.value);\n }\n\n async getRawRequest(): Promise<{\n method: string;\n url: string;\n body: Record<string, string> | string;\n }> {\n return {\n method: this.req.method,\n url: this.req.url,\n body: await this.req.text(),\n };\n }\n\n getAllCookies(): Promise<Map<string, string>> {\n const values = new Map<string, string>();\n this.req.cookies.getAll().forEach(x => {\n values.set(x.name, x.value);\n });\n return Promise.resolve(values);\n }\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\nimport type { MonoCloudRequest } from '@monocloud/auth-node-core';\nimport type { NextApiRequest } from 'next';\n\nexport default class MonoCloudPageRouterRequest implements MonoCloudRequest {\n constructor(public readonly req: NextApiRequest) {}\n\n /* v8 ignore next */\n getQuery(parameter: string): string | string[] | undefined {\n return this.req.query[parameter];\n }\n\n /* v8 ignore next */\n getCookie(name: string): Promise<string | undefined> {\n return Promise.resolve(this.req.cookies[name]);\n }\n\n /* v8 ignore next */\n getRawRequest(): Promise<{\n method: string;\n url: string;\n body: Record<string, string> | string;\n }> {\n return Promise.resolve({\n method: this.req.method!,\n url: this.req.url!,\n body: this.req.body,\n });\n }\n\n getAllCookies(): Promise<Map<string, string>> {\n const values = new Map<string, string>();\n const { cookies } = this.req;\n Object.keys(cookies).forEach(x => {\n const val = cookies[x];\n /* v8 ignore else -- @preserve */\n if (typeof x === 'string' && typeof val === 'string') {\n values.set(x, val);\n }\n });\n return Promise.resolve(values);\n }\n}\n","import type {\n CookieOptions,\n MonoCloudResponse,\n} from '@monocloud/auth-node-core';\n// eslint-disable-next-line import/extensions\nimport { NextResponse } from 'next/server.js';\n\nexport default class MonoCloudAppRouterResponse implements MonoCloudResponse {\n constructor(public res: NextResponse) {}\n\n setCookie(\n cookieName: string,\n value: string,\n options: CookieOptions\n ): Promise<void> {\n this.res.cookies.set(cookieName, value, options);\n return Promise.resolve();\n }\n\n redirect(url: string, statusCode: number | undefined = 302): void {\n const { headers } = this.res;\n this.res = NextResponse.redirect(url, { status: statusCode, headers });\n }\n\n sendJson(data: any, statusCode?: number): void {\n const { headers } = this.res;\n this.res = NextResponse.json(data, { status: statusCode, headers });\n }\n\n /* v8 ignore next */\n notFound(): void {\n const { headers } = this.res;\n this.res = new NextResponse(null, { status: 404, headers });\n }\n\n internalServerError(): void {\n const { headers } = this.res;\n this.res = new NextResponse(null, { status: 500, headers });\n }\n\n noContent(): void {\n const { headers } = this.res;\n this.res = new NextResponse(null, { status: 204, headers });\n }\n\n methodNotAllowed(): void {\n const { headers } = this.res;\n this.res = new NextResponse(null, { status: 405, headers });\n }\n\n setNoCache(): void {\n this.res.headers.set('Cache-Control', 'no-cache no-store');\n this.res.headers.set('Pragma', 'no-cache');\n }\n\n done(): any {\n return this.res;\n }\n}\n","import type {\n CookieOptions,\n MonoCloudResponse,\n} from '@monocloud/auth-node-core';\nimport type { NextApiResponse } from 'next';\nimport { serialize } from 'cookie';\n\nexport default class MonoCloudPageRouterResponse implements MonoCloudResponse {\n constructor(public readonly res: NextApiResponse) {}\n\n setCookie(\n cookieName: string,\n value: string,\n options: CookieOptions\n ): Promise<void> {\n let cookies = this.res.getHeader('Set-Cookie') ?? [];\n\n /* v8 ignore if -- @preserve */\n if (!Array.isArray(cookies)) {\n cookies = [cookies as string];\n }\n\n this.res.setHeader('Set-Cookie', [\n ...cookies.filter(cookie => !cookie.startsWith(`${cookieName}=`)),\n serialize(cookieName, value, options),\n ]);\n\n return Promise.resolve();\n }\n\n /* v8 ignore next */\n redirect(url: string, statusCode?: number): void {\n this.res.redirect(statusCode ?? 302, url);\n }\n\n /* v8 ignore next */\n sendJson(data: any, statusCode?: number): void {\n this.res.status(statusCode ?? 200);\n this.res.json(data);\n }\n\n /* v8 ignore next */\n notFound(): void {\n this.res.status(404);\n }\n\n /* v8 ignore next */\n internalServerError(): void {\n this.res.status(500);\n }\n\n /* v8 ignore next */\n noContent(): void {\n this.res.status(204);\n }\n\n /* v8 ignore next */\n methodNotAllowed(): void {\n this.res.status(405);\n }\n\n /* v8 ignore next */\n setNoCache(): void {\n this.res.setHeader('Cache-Control', 'no-cache no-store');\n this.res.setHeader('Pragma', 'no-cache');\n }\n\n /* v8 ignore next */\n done(): any {\n this.res.end();\n }\n}\n","/* eslint-disable no-console */\nimport type {\n CookieOptions,\n IMonoCloudCookieResponse,\n} from '@monocloud/auth-node-core';\n\nlet isWarned = false;\n\nexport default class MonoCloudCookieResponse implements IMonoCloudCookieResponse {\n async setCookie(\n cookieName: string,\n value: string,\n options: CookieOptions\n ): Promise<void> {\n try {\n // @ts-expect-error Cannot find module 'next/headers'\n const { cookies } = await import('next/headers');\n\n (await cookies()).set(cookieName, value, options);\n } catch (e: any) {\n if (!isWarned) {\n console.warn(e.message);\n isWarned = true;\n }\n }\n }\n}\n","import type { IMonoCloudCookieRequest } from '@monocloud/auth-node-core';\n\nexport default class MonoCloudCookieRequest implements IMonoCloudCookieRequest {\n /* v8 ignore next */\n async getCookie(name: string): Promise<string | undefined> {\n // @ts-expect-error Cannot find module 'next/headers'\n const { cookies } = await import('next/headers');\n\n return (await cookies()).get(name)?.value;\n }\n\n async getAllCookies(): Promise<Map<string, string>> {\n const values = new Map<string, string>();\n // @ts-expect-error Cannot find module 'next/headers'\n const { cookies } = await import('next/headers');\n\n (await cookies()).getAll().forEach((x: any) => {\n values.set(x.name, x.value);\n });\n return values;\n }\n}\n","// eslint-disable-next-line import/extensions\nimport { NextRequest, NextResponse } from 'next/server.js';\nimport type { NextApiRequest, NextApiResponse } from 'next/types';\nimport {\n MonoCloudValidationError,\n type IMonoCloudCookieRequest,\n type IMonoCloudCookieResponse,\n} from '@monocloud/auth-node-core';\nimport { AppRouterContext } from './types';\nimport MonoCloudAppRouterRequest from './requests/monocloud-app-router-request';\nimport MonoCloudPageRouterRequest from './requests/monocloud-page-router-request';\nimport MonoCloudAppRouterResponse from './responses/monocloud-app-router-response';\nimport MonoCloudPageRouterResponse from './responses/monocloud-page-router-response';\nimport MonoCloudCookieResponse from './responses/monocloud-cookie-response';\nimport MonoCloudCookieRequest from './requests/monocloud-cookie-request';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { isPresent } from '@monocloud/auth-node-core/internal';\n\nexport const isMonoCloudRequest = (\n req: unknown\n): req is IMonoCloudCookieRequest =>\n req instanceof MonoCloudAppRouterRequest ||\n req instanceof MonoCloudPageRouterRequest ||\n req instanceof MonoCloudCookieRequest;\n\nexport const isMonoCloudResponse = (\n res: unknown\n): res is IMonoCloudCookieResponse =>\n res instanceof MonoCloudAppRouterResponse ||\n res instanceof MonoCloudPageRouterResponse ||\n res instanceof MonoCloudCookieResponse;\n\nexport const isAppRouter = (req: unknown): boolean =>\n req instanceof Request ||\n (req as Request).headers instanceof Headers ||\n typeof (req as Request).bodyUsed === 'boolean';\n\nexport const isNodeRequest = (req: any): req is IncomingMessage => {\n return !!(\n req &&\n typeof req === 'object' &&\n 'headers' in req &&\n !('bodyUsed' in req) &&\n typeof req.on === 'function'\n );\n};\n\nexport const isNodeResponse = (res: any): res is ServerResponse => {\n return !!(\n res &&\n typeof res === 'object' &&\n 'setHeader' in res &&\n typeof res.setHeader === 'function' &&\n 'end' in res &&\n typeof res.end === 'function'\n );\n};\n\nexport const getNextRequest = (req: Request | NextRequest): NextRequest => {\n if (req instanceof NextRequest) {\n return req;\n }\n\n return new NextRequest(req.url, {\n method: req.method,\n headers: req.headers,\n body: req.body,\n /* v8 ignore next -- @preserve */\n duplex: (req as any).duplex ?? 'half',\n });\n};\n\nexport const getNextResponse = (\n res: Response | NextResponse | AppRouterContext\n): NextResponse => {\n if (res instanceof NextResponse) {\n return res;\n }\n\n if (res instanceof Response) {\n const nextResponse = new NextResponse(res.body, {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n url: res.url,\n });\n\n try {\n /* v8 ignore else -- @preserve */\n if (!isPresent(nextResponse.url)) {\n (nextResponse as any).url = res.url;\n }\n } catch {\n // ignore\n }\n\n return nextResponse;\n }\n\n return new NextResponse();\n};\n\nexport const getMonoCloudCookieReqRes = (\n req: unknown,\n resOrCtx: unknown\n): {\n request: IMonoCloudCookieRequest;\n response: IMonoCloudCookieResponse;\n} => {\n let request: IMonoCloudCookieRequest;\n let response: IMonoCloudCookieResponse;\n\n if (isAppRouter(req)) {\n request = new MonoCloudAppRouterRequest(getNextRequest(req as Request));\n\n response =\n resOrCtx instanceof Response\n ? new MonoCloudAppRouterResponse(getNextResponse(resOrCtx))\n : new MonoCloudCookieResponse();\n } else {\n if (!isNodeRequest(req) || !isNodeResponse(resOrCtx)) {\n throw new MonoCloudValidationError(\n 'Invalid pages router request and response'\n );\n }\n request = new MonoCloudPageRouterRequest(req as NextApiRequest);\n response = new MonoCloudPageRouterResponse(resOrCtx as NextApiResponse);\n }\n\n return { request, response };\n};\n\nexport const mergeResponse = (responses: NextResponse[]): NextResponse => {\n const resp = responses.pop();\n\n if (!resp) {\n return new NextResponse();\n }\n\n responses.forEach(response => {\n response.headers.forEach((v, k) => {\n if ((k === 'location' && !resp.headers.has(k)) || k !== 'location') {\n resp.headers.set(k, v);\n }\n });\n\n response.cookies.getAll().forEach(c => {\n const { name, value, ...cookieOpt } = c;\n resp.cookies.set(name, value, cookieOpt);\n });\n });\n\n return resp;\n};\n","/* 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 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 * @returns Returns the resolved session, or `undefined` if none exists.\n */\n public getSession(): 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 * @returns Returns the resolved session, or `undefined` if none exists.\n */\n public getSession(\n req: NextRequest | Request,\n res?: NextResponse | Response\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 * @returns Returns the resolved session, or `undefined` if none exists.\n */\n public getSession(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>\n ): Promise<MonoCloudSession | undefined>;\n\n async getSession(...args: any[]): Promise<MonoCloudSession | undefined> {\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 getSession()'\n );\n }\n\n return await this.coreClient.getSession(request, response);\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","import type { ParsedUrlQuery } from 'node:querystring';\nimport { MonoCloudNextClient } from './monocloud-next-client';\nimport type {\n AppRouterApiHandlerFn,\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 type {\n NextMiddleware,\n NextProxy,\n NextRequest,\n NextFetchEvent,\n NextResponse,\n} from 'next/server';\nimport type { MonoCloudSession } from '@monocloud/auth-core';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { NextApiHandler, NextApiRequest, NextApiResponse } from 'next';\nimport type {\n GetTokensOptions,\n MonoCloudTokens,\n} from '@monocloud/auth-node-core';\n\nlet instance: MonoCloudNextClient | undefined;\n\n/**\n * Retrieves the singleton instance of the MonoCloudNextClient.\n * Initializes it lazily on the first call.\n */\nconst getInstance = (): MonoCloudNextClient => {\n instance ??= new MonoCloudNextClient();\n return instance;\n};\n\n/**\n * Creates a Next.js catch-all auth route handler (Pages Router and App Router) for the built-in routes (`/signin`, `/callback`, `/userinfo`, `/signout`).\n *\n * Mount this handler on a catch-all route (e.g. `/api/auth/[...monocloud]`).\n *\n * > If you already use `authMiddleware()`, you typically don’t need this handler. Use `monoCloudAuth()` when middleware cannot be used or when auth routes need customization.\n *\n * @example App Router\n * ```tsx:src/app/api/auth/[...monocloud]/route.ts tab=\"App Router\" tab-group=\"monoCloudAuth\"\n * import { monoCloudAuth } from \"@monocloud/auth-nextjs\";\n *\n * export const GET = monoCloudAuth();\n *```\n *\n * @example App Router (Response)\n * ```tsx:src/app/api/auth/[...monocloud]/route.ts tab=\"App Router (Response)\" tab-group=\"monoCloudAuth\"\n * import { monoCloudAuth } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = (req: NextRequest) => {\n * const authHandler = monoCloudAuth();\n *\n * const res = new NextResponse();\n *\n * res.cookies.set(\"last_auth_requested\", `${Date.now()}`);\n *\n * return authHandler(req, res);\n * };\n * ```\n *\n * @example Pages Router\n * ```tsx:src/pages/api/auth/[...monocloud].ts tab=\"Pages Router\" tab-group=\"monoCloudAuth\"\n * import { monoCloudAuth } from \"@monocloud/auth-nextjs\";\n *\n * export default monoCloudAuth();\n *```\n *\n * @example Pages Router (Response)\n * ```tsx:src/pages/api/auth/[...monocloud].ts tab=\"Pages Router (Response)\" tab-group=\"monoCloudAuth\"\n * import { monoCloudAuth } from \"@monocloud/auth-nextjs\";\n * import { NextApiRequest, NextApiResponse } from \"next\";\n *\n * export default function handler(req: NextApiRequest, res: NextApiResponse) {\n * const authHandler = monoCloudAuth();\n *\n * res.setHeader(\"last_auth_requested\", `${Date.now()}`);\n *\n * return authHandler(req, res);\n * }\n * ```\n *\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 * @category Functions\n */\nexport function monoCloudAuth(\n options?: MonoCloudAuthOptions\n): MonoCloudAuthHandler {\n return getInstance().monoCloudAuth(options);\n}\n\n/**\n * Creates a Next.js authentication middleware that protects routes.\n *\n * By default, all routes matched by `config.matcher` are protected unless configured otherwise.\n *\n * @example Protect All Routes\n * ```tsx:src/proxy.ts tab=\"Protect All Routes\" tab-group=\"auth-middleware\"\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 * @example Protect Selected Routes\n * ```tsx:src/proxy.ts tab=\"Protect Selected Routes\" tab-group=\"auth-middleware\"\n * import { authMiddleware } from \"@monocloud/auth-nextjs\";\n *\n * export default authMiddleware({\n * protectedRoutes: [\"/api/admin\", \"^/api/protected(/.*)?$\"],\n * });\n *\n * export const config = {\n * matcher: [\n * \"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)\",\n * ],\n * };\n *```\n *\n * @example No Protected Routes\n * ```tsx:src/proxy.ts tab=\"No Protected Routes\" tab-group=\"auth-middleware\"\n * import { authMiddleware } from \"@monocloud/auth-nextjs\";\n *\n * export default authMiddleware({\n * protectedRoutes: [],\n * });\n *\n * export const config = {\n * matcher: [\n * \"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)\",\n * ],\n * };\n * ```\n *\n * @example Dynamic\n * ```tsx:src/proxy.ts tab=\"Dynamic\" tab-group=\"auth-middleware\"\n * import { authMiddleware } from \"@monocloud/auth-nextjs\";\n *\n * export default authMiddleware({\n * protectedRoutes: (req) => {\n * return req.nextUrl.pathname.startsWith(\"/api/protected\");\n * },\n * });\n *\n * export const config = {\n * matcher: [\n * \"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)\",\n * ],\n * };\n * ```\n *\n * @example Group Protection\n * ```tsx:src/proxy.ts tab=\"Group Protection\" tab-group=\"auth-middleware\"\n * import { authMiddleware } from \"@monocloud/auth-nextjs\";\n *\n * export default authMiddleware({\n * protectedRoutes: [\n * {\n * groups: [\"admin\", \"editor\", \"537e7c3d-a442-4b5b-b308-30837aa045a4\"],\n * routes: [\"/internal\", \"/api/internal(.*)\"],\n * },\n * ],\n * });\n *\n * export const config = {\n * matcher: [\n * \"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)\",\n * ],\n * };\n * ```\n *\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, such as a `NextResponse`, `redirect`, or `undefined` to continue processing.\n *\n * @category Functions\n */\nexport function authMiddleware(\n options?: MonoCloudMiddlewareOptions\n): NextMiddleware | NextProxy;\n\n/**\n * Executes the authentication middleware manually.\n *\n * Intended for advanced scenarios where the middleware is composed within custom logic.\n *\n * @example Composing with custom middleware\n *\n * ```tsx:src/proxy.ts title=\"Composing with custom middleware\"\n * import { authMiddleware } from \"@monocloud/auth-nextjs\";\n * import { NextFetchEvent, NextRequest, NextResponse } from \"next/server\";\n *\n * export default function customMiddleware(req: NextRequest, evt: NextFetchEvent) {\n * if (req.nextUrl.pathname.startsWith(\"/api/protected\")) {\n * return authMiddleware(req, evt);\n * }\n *\n * return NextResponse.next();\n * }\n *\n * export const config = {\n * matcher: [\n * \"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)\",\n * ],\n * };\n * ```\n *\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 * @category Functions\n */\nexport function authMiddleware(\n request: NextRequest,\n event: NextFetchEvent\n): Promise<NextMiddlewareResult> | NextMiddlewareResult;\n\nexport function authMiddleware(\n ...args: any[]\n):\n | NextMiddleware\n | NextProxy\n | Promise<NextMiddlewareResult>\n | NextMiddlewareResult {\n return getInstance().authMiddleware(...args);\n}\n\n/**\n * Retrieves the current user's session using the active server request context.\n *\n * Intended for Server Components, Server Actions, Route Handlers, and Middleware where the request is implicitly available.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"session-ssr\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n *\n * export default async function Home() {\n * const session = await getSession();\n *\n * return <div>{session?.user.name}</div>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"session-ssr\"\n * \"use server\";\n *\n * import { getSession } from \"@monocloud/auth-nextjs\";\n *\n * export async function getUserAction() {\n * const session = await getSession();\n *\n * return { name: session?.user.name };\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/user/route.ts tab=\"API Handler\" tab-group=\"session-ssr\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const session = await getSession();\n *\n * return NextResponse.json({ name: session?.user.name });\n * };\n * ```\n *\n * @example Middleware\n * ```tsx:src/proxy.ts tab=\"Middleware\" tab-group=\"session-ssr\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export default async function proxy() {\n * const session = await getSession();\n *\n * if (!session) {\n * return new NextResponse(\"User not signed in\", { status: 401 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @returns Returns the resolved session, or `undefined` if none exists.\n *\n * @category Functions\n */\nexport function getSession(): Promise<MonoCloudSession | undefined>;\n\n/**\n * Retrieves the current user's session using an explicit Web or Next.js request.\n *\n * Use this overload when you already have access to a `Request` or `NextRequest` (for example in Middleware or Route Handlers).\n *\n * @example Middleware (Request)\n * ```tsx:src/proxy.ts tab=\"Middleware (Request)\" tab-group=\"session-route-handler\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const session = await getSession(req);\n *\n * if (!session) {\n * return new NextResponse(\"User not signed in\", { status: 401 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @example Middleware (Response)\n * ```tsx:src/proxy.ts tab=\"Middleware (Response)\" tab-group=\"session-route-handler\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const res = NextResponse.next();\n *\n * const session = await getSession(req, res);\n *\n * if (!session) {\n * return new NextResponse(\"User not signed in\", { status: 401 });\n * }\n *\n * res.headers.set(\"x-auth-status\", \"active\");\n *\n * return res;\n * }\n * ```\n *\n * @example API Handler (Request)\n * ```tsx:src/app/api/user/route.ts tab=\"API Handler (Request)\" tab-group=\"session-route-handler\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const session = await getSession(req);\n *\n * return NextResponse.json({ name: session?.user.name });\n * };\n * ```\n *\n * @example API Handler (Response)\n * ```tsx:src/app/api/user/route.ts tab=\"API Handler (Response)\" tab-group=\"session-route-handler\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const res = new NextResponse(\"YOUR CUSTOM RESPONSE\");\n *\n * const session = await getSession(req, res);\n *\n * if (session?.user) {\n * res.cookies.set(\"something\", \"important\");\n * }\n *\n * return res;\n * };\n * ```\n *\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 * @returns Returns the resolved session, or `undefined` if none exists.\n *\n * @category Functions\n */\nexport function getSession(\n req: NextRequest | Request,\n res?: NextResponse | Response\n): Promise<MonoCloudSession | undefined>;\n\n/**\n * Retrieves the current user's session in the Pages Router or Node.js runtime.\n *\n * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.\n *\n * @example Pages Router (Pages)\n * ```tsx:src/pages/index.tsx tab=\"Pages Router (Pages)\" tab-group=\"session-pages\"\n * import { getSession, MonoCloudSession } from \"@monocloud/auth-nextjs\";\n * import { GetServerSideProps } from \"next\";\n *\n * type Props = {\n * session?: MonoCloudSession;\n * };\n *\n * export default function Home({ session }: Props) {\n * return <pre>Session: {JSON.stringify(session, null, 2)}</pre>;\n * }\n *\n * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {\n * const session = await getSession(ctx.req, ctx.res);\n *\n * return {\n * props: {\n * session\n * }\n * };\n * };\n * ```\n * @example Pages Router (API)\n * ```tsx:src/pages/api/user.ts tab=\"Pages Router (API)\" tab-group=\"session-pages\"\n * import { getSession } from \"@monocloud/auth-nextjs\";\n * import { NextApiRequest, NextApiResponse } from \"next\";\n *\n * export default async function handler(\n * req: NextApiRequest,\n * res: NextApiResponse\n * ) {\n * const session = await getSession(req, res);\n *\n * res.status(200).json({ name: session?.user.name });\n * }\n * ```\n *\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 * @returns Returns the resolved session, or `undefined` if none exists.\n *\n * @category Functions\n */\nexport function getSession(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>\n): Promise<MonoCloudSession | undefined>;\n\nexport function getSession(\n ...args: any[]\n): Promise<MonoCloudSession | undefined> {\n return (getInstance().getSession as any)(...args);\n}\n\n/**\n * Retrieves the current user's tokens using the active server request context.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"tokens-ssr\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n *\n * export default async function Home() {\n * const tokens = await getTokens();\n *\n * return <div>Expired: {tokens.isExpired.toString()}</div>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"tokens-ssr\"\n * \"use server\";\n *\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n *\n * export async function getExpiredAction() {\n * const tokens = await getTokens();\n *\n * return { expired: tokens.isExpired };\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/tokens/route.ts tab=\"API Handler\" tab-group=\"tokens-ssr\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const tokens = await getTokens();\n *\n * return NextResponse.json({ expired: tokens.isExpired });\n * };\n * ```\n *\n * @example Middleware\n * ```tsx:src/proxy.ts tab=\"Middleware\" tab-group=\"tokens-ssr\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export default async function proxy() {\n * const tokens = await getTokens();\n *\n * if (tokens.isExpired) {\n * return new NextResponse(\"Tokens expired\", { status: 401 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @example Refresh the default token\n *\n * The **default token** is the access token associated with your default authorization parameters:\n * - Scopes: `MONOCLOUD_AUTH_SCOPES` or `options.defaultAuthParams.scopes`\n * - Resource: `MONOCLOUD_AUTH_RESOURCE` or `options.defaultAuthParams.resource`\n *\n * Calling `getTokens()` returns the current token set and **refreshes the default token automatically when needed** (for example, if it has expired). To force a refresh even when it isn’t expired, use `forceRefresh: true`.\n *\n * ```tsx:src/app/page.tsx title=\"Refresh default token\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * // Forces a refresh of the default token\n * const tokens = await getTokens({ forceRefresh: true });\n *\n * return NextResponse.json({ accessToken: tokens?.accessToken });\n * };\n * ```\n *\n * @example Request an access token for resource(s)\n *\n * Use `resource` and `scopes` to request an access token for one or more resources.\n *\n * > The requested resource and scopes must be included in the initial authorization flow (so the user has consented / the session is eligible to mint that token).\n *\n * ```tsx:src/app/page.tsx title=\"Request a new access token for resource(s)\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const tokens = await getTokens({\n * resource: \"https://first.example.com https://second.example.com\",\n * scopes: \"read:first read:second shared\",\n * });\n *\n * return NextResponse.json({ accessToken: tokens?.accessToken });\n * };\n * ```\n *\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 * @category Functions\n */\nexport function getTokens(options?: GetTokensOptions): Promise<MonoCloudTokens>;\n\n/**\n * Retrieves the current user's tokens using an explicit Web or Next.js request.\n *\n * Use this overload when you already have access to a `Request` or `NextRequest` (for example, in Middleware or Route Handlers).\n *\n * @example Middleware (Request)\n * ```tsx:src/proxy.ts tab=\"Middleware (Request)\" tab-group=\"tokens-route-handler-request\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const tokens = await getTokens(req);\n *\n * if (tokens.isExpired) {\n * return new NextResponse(\"Tokens expired\", { status: 401 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @example API Handler (Request)\n * ```tsx:src/app/api/tokens/route.ts tab=\"API Handler (Request)\" tab-group=\"tokens-route-handler-request\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const tokens = await getTokens(req);\n *\n * return NextResponse.json({ expired: tokens?.isExpired });\n * };\n * ```\n *\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 * @category Functions\n */\nexport function getTokens(\n req: NextRequest | Request,\n options?: GetTokensOptions\n): Promise<MonoCloudTokens>;\n\n/**\n * Retrieves the current user's tokens using an explicit request and response.\n *\n * Use this overload when you have already created a response and want refreshed authentication cookies or headers applied to it.\n *\n * @example Middleware (Response)\n *```tsx:src/proxy.ts tab=\"Middleware (Response)\" tab-group=\"tokens-route-handler-response\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const res = NextResponse.next();\n *\n * const tokens = await getTokens(req, res);\n *\n * res.headers.set(\"x-tokens-expired\", tokens.isExpired.toString());\n *\n * return res;\n * }\n * ```\n *\n * @example API Handler (Response)\n * ```tsx:src/app/api/tokens/route.ts tab=\"API Handler (Response)\" tab-group=\"tokens-route-handler-response\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const res = new NextResponse(\"Custom Body\");\n *\n * const tokens = await getTokens(req, res);\n *\n * if (!tokens.isExpired) {\n * res.headers.set(\"x-auth-status\", \"active\");\n * }\n *\n * return res;\n * };\n * ```\n *\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 * @category Functions\n */\nexport function getTokens(\n req: NextRequest | Request,\n res: NextResponse | Response,\n options?: GetTokensOptions\n): Promise<MonoCloudTokens>;\n\n/**\n * Retrieves the current user's tokens in the Pages Router or Node.js runtime.\n *\n * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.\n *\n * @example Pages Router (Pages)\n * ```tsx:src/pages/index.tsx tab=\"Pages Router (Pages)\" tab-group=\"tokens-pages\"\n * import { getTokens, MonoCloudTokens } from \"@monocloud/auth-nextjs\";\n * import { GetServerSideProps } from \"next\";\n *\n * type Props = {\n * tokens: MonoCloudTokens;\n * };\n *\n * export default function Home({ tokens }: Props) {\n * return <pre>Tokens: {JSON.stringify(tokens, null, 2)}</pre>;\n * }\n *\n * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {\n * const tokens = await getTokens(ctx.req, ctx.res);\n *\n * return {\n * props: {\n * tokens: tokens\n * }\n * };\n * };\n * ```\n *\n * @example Pages Router (API)\n * ```tsx:src/pages/api/tokens.ts tab=\"Pages Router (API)\" tab-group=\"tokens-pages\"\n * import { getTokens } from \"@monocloud/auth-nextjs\";\n * import { NextApiRequest, NextApiResponse } from \"next\";\n *\n * export default async function handler(\n * req: NextApiRequest,\n * res: NextApiResponse\n * ) {\n * const tokens = await getTokens(req, res);\n *\n * res.status(200).json({ accessToken: tokens?.accessToken });\n * }\n * ```\n *\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 * @category Functions\n */\nexport function getTokens(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>,\n options?: GetTokensOptions\n): Promise<MonoCloudTokens>;\n\nexport function getTokens(...args: any[]): Promise<MonoCloudTokens> {\n return getInstance().getTokens(...args);\n}\n\n/**\n * Checks whether the current user is authenticated using the active server request context.\n *\n * Intended for Server Components, Server Actions, Route Handlers, and Middleware where the request is implicitly available.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"is-authenticated-ssr\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n *\n * export default async function Home() {\n * const authenticated = await isAuthenticated();\n *\n * return <div>Authenticated: {authenticated.toString()}</div>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"is-authenticated-ssr\"\n * \"use server\";\n *\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n *\n * export async function checkAuthAction() {\n * const authenticated = await isAuthenticated();\n *\n * return { authenticated };\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/authenticated/route.ts tab=\"API Handler\" tab-group=\"is-authenticated-ssr\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const authenticated = await isAuthenticated();\n *\n * return NextResponse.json({ authenticated });\n * };\n * ```\n *\n * @example Middleware\n * ```tsx:src/proxy.ts tab=\"Middleware\" tab-group=\"is-authenticated-ssr\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export default async function proxy() {\n * const authenticated = await isAuthenticated();\n *\n * if (!authenticated) {\n * return new NextResponse(\"User not signed in\", { status: 401 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @returns Returns `true` if a valid session exists; otherwise `false`.\n *\n * @category Functions\n */\nexport function isAuthenticated(): Promise<boolean>;\n\n/**\n * Checks whether the current user is authenticated using an explicit Web or Next.js request.\n *\n * Use this overload when you already have access to a `Request` or `NextRequest` (for example, in Middleware or Route Handlers).\n *\n * @example Middleware (Request)\n * ```tsx:src/proxy.ts tab=\"Middleware (Request)\" tab-group=\"is-authenticated-route-handler\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const authenticated = await isAuthenticated(req);\n *\n * if (!authenticated) {\n * return new NextResponse(\"User not signed in\", { status: 401 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @example Middleware (Response)\n * ```tsx:src/proxy.ts tab=\"Middleware (Response)\" tab-group=\"is-authenticated-route-handler\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const res = NextResponse.next();\n *\n * const authenticated = await isAuthenticated(req, res);\n *\n * if (!authenticated) {\n * return new NextResponse(\"User not signed in\", { status: 401 });\n * }\n *\n * res.headers.set(\"x-authenticated\", \"true\");\n *\n * return res;\n * }\n * ```\n *\n * @example API Handler (Request)\n * ```tsx:src/app/api/authenticated/route.ts tab=\"API Handler (Request)\" tab-group=\"is-authenticated-route-handler\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const authenticated = await isAuthenticated(req);\n *\n * return NextResponse.json({ authenticated });\n * };\n * ```\n *\n * @example API Handler (Response)\n * ```tsx:src/app/api/authenticated/route.ts tab=\"API Handler (Response)\" tab-group=\"is-authenticated-route-handler\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const res = new NextResponse(\"YOUR CUSTOM RESPONSE\");\n *\n * const authenticated = await isAuthenticated(req, res);\n *\n * if (authenticated) {\n * res.cookies.set(\"something\", \"important\");\n * }\n *\n * return res;\n * };\n * ```\n *\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 * @category Functions\n */\nexport function isAuthenticated(\n req: NextRequest | Request,\n res?: NextResponse | Response\n): Promise<boolean>;\n\n/**\n * Checks whether the current user is authenticated in the Pages Router or Node.js runtime.\n *\n * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.\n *\n * @example Pages Router (Pages)\n * ```tsx:src/pages/index.tsx tab=\"Pages Router (Pages)\" tab-group=\"is-authenticated-pages\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { GetServerSideProps } from \"next\";\n *\n * type Props = {\n * authenticated: boolean;\n * };\n *\n * export default function Home({ authenticated }: Props) {\n * return <pre>User is {authenticated ? \"logged in\" : \"guest\"}</pre>;\n * }\n *\n * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {\n * const authenticated = await isAuthenticated(ctx.req, ctx.res);\n *\n * return {\n * props: {\n * authenticated\n * }\n * };\n * };\n * ```\n *\n * @example Pages Router (API)\n * ```tsx:src/pages/api/authenticated.ts tab=\"Pages Router (API)\" tab-group=\"is-authenticated-pages\"\n * import { isAuthenticated } from \"@monocloud/auth-nextjs\";\n * import { NextApiRequest, NextApiResponse } from \"next\";\n *\n * export default async function handler(\n * req: NextApiRequest,\n * res: NextApiResponse\n * ) {\n * const authenticated = await isAuthenticated(req, res);\n *\n * res.status(200).json({ authenticated });\n * }\n * ```\n *\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 * @category Functions\n */\nexport function isAuthenticated(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>\n): Promise<boolean>;\n\nexport function isAuthenticated(...args: any[]): Promise<boolean> {\n return (getInstance().isAuthenticated as any)(...args);\n}\n\n/**\n * Ensures the current user is authenticated. If not, redirects to the sign-in flow.\n *\n * > **App Router only.** Intended for Server Components, Route Handlers, and Server Actions.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"protect\"\n * import { protect } from \"@monocloud/auth-nextjs\";\n *\n * export default async function Home() {\n * await protect();\n *\n * return <>You are signed in.</>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"protect\"\n * \"use server\";\n *\n * import { protect } from \"@monocloud/auth-nextjs\";\n *\n * export async function getMessage() {\n * await protect();\n *\n * return { secret: \"sssshhhhh!!!\" };\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/protected/route.ts tab=\"API Handler\" tab-group=\"protect\"\n * import { protect } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * await protect();\n *\n * return NextResponse.json({ secret: \"ssshhhh!!!\" });\n * };\n * ```\n *\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 * @category Functions\n */\nexport function protect(options?: ProtectOptions): Promise<void> {\n return getInstance().protect(options);\n}\n\n/**\n * Wraps an App Router API route handler and ensures that only authenticated (and optionally authorized) requests can access the route.\n *\n * Intended for Next.js App Router Route Handlers.\n *\n * @example\n * ```tsx:src/app/api/protected/route.ts\n * import { protectApi } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = protectApi(async () => {\n * return NextResponse.json({\n * message: \"You accessed a protected endpoint\",\n * });\n * });\n * ```\n *\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 * @category Functions\n */\nexport function protectApi(\n handler: AppRouterApiHandlerFn,\n options?: ProtectApiAppOptions\n): AppRouterApiHandlerFn;\n\n/**\n * Wraps a Pages Router API route handler and ensures that only authenticated (and optionally authorized) requests can access the route.\n *\n * Intended for Next.js Pages Router API routes.\n *\n * @example\n * ```tsx:src/pages/api/protected.ts\n * import { protectApi } from \"@monocloud/auth-nextjs\";\n * import { NextApiRequest, NextApiResponse } from \"next\";\n *\n * export default protectApi(\n * async (req: NextApiRequest, res: NextApiResponse) => {\n * return res.json({\n * message: \"You accessed a protected endpoint\",\n * });\n * }\n * );\n * ```\n *\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 * @category Functions\n */\nexport function protectApi(\n handler: NextApiHandler,\n options?: ProtectApiPageOptions\n): NextApiHandler;\n\nexport function protectApi(\n handler: AppRouterApiHandlerFn | NextApiHandler,\n options?: ProtectApiAppOptions | ProtectApiPageOptions\n): AppRouterApiHandlerFn | NextApiHandler {\n return (getInstance().protectApi as any)(handler, options);\n}\n\n/**\n * Restricts access to App Router server-rendered pages.\n *\n * **Access control**\n * - If the user is not authenticated, `onAccessDenied` is invoked (or default behavior applies).\n * - If the user is authenticated but fails group checks, `onGroupAccessDenied` is invoked (or the default \"Access Denied\" view is rendered).\n *\n * Both behaviors can be customized via options.\n *\n * @example Basic Usage\n * ```tsx:src/app/page.tsx tab=\"Basic Usage\" tab-group=\"protectPage-app\"\n * import { protectPage } from \"@monocloud/auth-nextjs\";\n *\n * export default protectPage(async function Home({ user }) {\n * return <>Hi {user.email}. You accessed a protected page.</>;\n * });\n * ```\n *\n * @example With Options\n * ```tsx:src/app/page.tsx tab=\"With Options\" tab-group=\"protectPage-app\"\n * import { protectPage } from \"@monocloud/auth-nextjs\";\n *\n * export default protectPage(\n * async function Home({ user }) {\n * return <>Hi {user.email}. You accessed a protected page.</>;\n * },\n * {\n * returnUrl: \"/dashboard\",\n * groups: [\"admin\"],\n * }\n * );\n * ```\n *\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 * @category Functions\n */\nexport function protectPage(\n component: ProtectedAppServerComponent,\n options?: ProtectAppPageOptions\n): AppRouterPageHandler;\n\n/**\n * Restricts access to Pages Router server-rendered pages using `getServerSideProps`.\n *\n * **Access control**\n * - If the user is not authenticated, `onAccessDenied` is invoked (or default behavior applies).\n * - If the user is authenticated but fails group checks, the page can still render and `groupAccessDenied` is provided in props. Use `onGroupAccessDenied` to customize the props or behavior.\n *\n * Both behaviors can be customized via options.\n *\n * @example Basic Usage\n * ```tsx:src/pages/index.tsx tab=\"Basic Usage\" tab-group=\"protectPage-page\"\n * import { protectPage, MonoCloudUser } from \"@monocloud/auth-nextjs\";\n *\n * type Props = {\n * user: MonoCloudUser;\n * };\n *\n * export default function Home({ user }: Props) {\n * return <>Hi {user.email}. You accessed a protected page.</>;\n * }\n *\n * export const getServerSideProps = protectPage();\n * ```\n *\n * @example With Options\n * ```tsx:src/pages/index.tsx tab=\"With Options\" tab-group=\"protectPage-page\"\n * import { protectPage, MonoCloudUser } from \"@monocloud/auth-nextjs\";\n * import { GetServerSidePropsContext } from \"next\";\n *\n * type Props = {\n * user: MonoCloudUser;\n * url: string;\n * };\n *\n * export default function Home({ user, url }: Props) {\n * console.log(url);\n * return <div>Hi {user?.email}. You accessed a protected page.</div>;\n * }\n *\n * export const getServerSideProps = protectPage({\n * returnUrl: \"/dashboard\",\n * groups: [\"admin\"],\n * getServerSideProps: async (context: GetServerSidePropsContext) => ({\n * props: { url: context.resolvedUrl }\n * })\n * });\n * ```\n *\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 * @category Functions\n */\nexport function protectPage<\n P extends Record<string, any> = Record<string, any>,\n Q extends ParsedUrlQuery = ParsedUrlQuery,\n>(options?: ProtectPagePageOptions<P, Q>): ProtectPagePageReturnType<P, Q>;\n\nexport function protectPage(...args: any[]): any {\n return getInstance().protectPage(...args);\n}\n\n/**\n * Checks whether the currently authenticated user is a member of **any** of the specified groups.\n *\n * The `groups` parameter accepts group identifiers (IDs or names).\n *\n * The authenticated user's session may contain groups represented as:\n * - Group IDs\n * - Group names\n * - `Group` objects (for example, `{ id: string; name: string }`)\n *\n * Matching is always performed against the group's **ID** and **name**, regardless of how the group is represented in the session.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"is-user-in-group-rsc\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n *\n * export default async function AdminPanel() {\n * const isAdmin = await isUserInGroup([\"admin\"]);\n *\n * if (!isAdmin) {\n * return <div>Access Denied</div>;\n * }\n *\n * return <div>Admin Control Panel</div>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"is-user-in-group-rsc\"\n * \"use server\";\n *\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n *\n * export async function deletePostAction() {\n * const canDelete = await isUserInGroup([\"admin\", \"editor\"]);\n *\n * if (!canDelete) {\n * return { success: false };\n * }\n *\n * return { success: true };\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/group-check/route.ts tab=\"API Handler\" tab-group=\"is-user-in-group-rsc\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const allowed = await isUserInGroup([\"admin\", \"editor\"]);\n *\n * if (!allowed) {\n * return new NextResponse(\"Forbidden\", { status: 403 });\n * }\n *\n * return NextResponse.json({ status: \"success\" });\n * };\n * ```\n *\n * @example Middleware\n * ```tsx:src/proxy.ts tab=\"Middleware\" tab-group=\"is-user-in-group-rsc\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export default async function proxy() {\n * const isAdmin = await isUserInGroup([\"admin\"]);\n *\n * if (!isAdmin) {\n * return new NextResponse(\"User is not admin\", { status: 403 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\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 * @category Functions\n */\nexport function isUserInGroup(\n groups: string[],\n options?: IsUserInGroupOptions\n): Promise<boolean>;\n\n/**\n * Checks group membership using an explicit Web or Next.js request.\n *\n * Use this overload when you already have access to a `Request` or `NextRequest` (for example, in Middleware or Route Handlers).\n *\n * @example Middleware (Request)\n * ```tsx:src/proxy.ts tab=\"Middleware (Request)\" tab-group=\"is-user-in-group-request\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const isAdmin = await isUserInGroup(req, [\"admin\"]);\n *\n * if (!isAdmin) {\n * return new NextResponse(\"User is not admin\", { status: 403 });\n * }\n *\n * return NextResponse.next();\n * }\n * ```\n *\n * @example API Handler (Request)\n * ```tsx:src/app/api/group-check/route.ts tab=\"API Handler (Request)\" tab-group=\"is-user-in-group-request\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const isMember = await isUserInGroup(req, [\"admin\", \"editor\"]);\n *\n * return NextResponse.json({ isMember });\n * };\n * ```\n *\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 * @category Functions\n */\nexport function isUserInGroup(\n req: NextRequest | Request,\n groups: string[],\n options?: IsUserInGroupOptions\n): Promise<boolean>;\n\n/**\n * Checks group membership using an explicit request and response.\n *\n * Use this overload when you have already created a response and want refreshed authentication cookies or headers applied to it.\n *\n * @example Middleware (Response)\n * ```tsx:src/proxy.ts tab=\"Middleware (Response)\" tab-group=\"is-user-in-group-response\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export default async function proxy(req: NextRequest) {\n * const res = NextResponse.next();\n *\n * const isAdmin = await isUserInGroup(req, res, [\"admin\"]);\n *\n * if (!isAdmin) {\n * return new NextResponse(\"User is not admin\", { status: 403 });\n * }\n *\n * res.headers.set(\"x-user\", \"admin\");\n *\n * return res;\n * }\n * ```\n *\n * @example API Handler (Response)\n * ```tsx:src/app/api/group-check/route.ts tab=\"API Handler (Response)\" tab-group=\"is-user-in-group-response\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextRequest, NextResponse } from \"next/server\";\n *\n * export const GET = async (req: NextRequest) => {\n * const res = new NextResponse(\"Restricted Content\");\n *\n * const allowed = await isUserInGroup(req, res, [\"admin\"]);\n *\n * if (!allowed) {\n * return new NextResponse(\"Not Allowed\", res);\n * }\n *\n * return res;\n * };\n * ```\n *\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 * @category Functions\n */\nexport function isUserInGroup(\n req: NextRequest | Request,\n res: NextResponse | Response,\n groups: string[],\n options?: IsUserInGroupOptions\n): Promise<boolean>;\n\n/**\n * Checks group membership in the Pages Router or Node.js runtime.\n *\n * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.\n *\n * @example Pages Router (Pages)\n * ```tsx:src/pages/index.tsx tab=\"Pages Router (Pages)\" tab-group=\"is-user-in-group-pages\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { GetServerSideProps } from \"next\";\n *\n * type Props = {\n * isAdmin: boolean;\n * };\n *\n * export default function Home({ isAdmin }: Props) {\n * return <div>User is admin: {isAdmin.toString()}</div>;\n * }\n *\n * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {\n * const isAdmin = await isUserInGroup(ctx.req, ctx.res, [\"admin\"]);\n *\n * return {\n * props: {\n * isAdmin\n * }\n * };\n * };\n * ```\n *\n * @example Pages Router (API)\n * ```tsx:src/pages/api/group-check.ts tab=\"Pages Router (API)\" tab-group=\"is-user-in-group-pages\"\n * import { isUserInGroup } from \"@monocloud/auth-nextjs\";\n * import { NextApiRequest, NextApiResponse } from \"next\";\n *\n * export default async function handler(\n * req: NextApiRequest,\n * res: NextApiResponse\n * ) {\n * const isAdmin = await isUserInGroup(req, res, [\"admin\"]);\n *\n * if (!isAdmin) {\n * return res.status(403).json({ error: \"Forbidden\" });\n * }\n *\n * res.status(200).json({ message: \"Welcome Admin\" });\n * }\n * ```\n *\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 * @category Functions\n */\nexport function isUserInGroup(\n req: NextApiRequest | IncomingMessage,\n res: NextApiResponse | ServerResponse<IncomingMessage>,\n groups: string[],\n options?: IsUserInGroupOptions\n): Promise<boolean>;\n\nexport function isUserInGroup(...args: any[]): Promise<boolean> {\n return (getInstance().isUserInGroup as any)(...args);\n}\n\n/**\n * Redirects the user to the sign-in flow.\n *\n * > **App Router only**. Intended for use in Server Components, Route Handlers, and Server Actions.\n *\n * This helper performs a server-side redirect to the configured sign-in route. Execution does not continue after the redirect is triggered.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"redirect-to-sign-in\"\n * import { isUserInGroup, redirectToSignIn } from \"@monocloud/auth-nextjs\";\n *\n * export default async function Home() {\n * const allowed = await isUserInGroup([\"admin\"]);\n *\n * if (!allowed) {\n * await redirectToSignIn({ returnUrl: \"/home\" });\n * }\n *\n * return <>You are signed in.</>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"redirect-to-sign-in\"\n * \"use server\";\n *\n * import { getSession, redirectToSignIn } from \"@monocloud/auth-nextjs\";\n *\n * export async function protectedAction() {\n * const session = await getSession();\n *\n * if (!session) {\n * await redirectToSignIn();\n * }\n *\n * return { data: \"Sensitive Data\" };\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/protected/route.ts tab=\"API Handler\" tab-group=\"redirect-to-sign-in\"\n * import { getSession, redirectToSignIn } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const session = await getSession();\n *\n * if (!session) {\n * await redirectToSignIn({\n * returnUrl: \"/dashboard\",\n * });\n * }\n *\n * return NextResponse.json({ data: \"Protected content\" });\n * };\n * ```\n *\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 * @category Functions\n */\nexport function redirectToSignIn(\n options?: RedirectToSignInOptions\n): Promise<void> {\n return getInstance().redirectToSignIn(options);\n}\n\n/**\n * Redirects the user to the sign-out flow.\n *\n * > **App Router only**. Intended for use in Server Components, Route Handlers, and Server Actions.\n *\n * This helper performs a server-side redirect to the configured sign-out route. Execution does not continue after the redirect is triggered.\n *\n * @example Server Component\n * ```tsx:src/app/page.tsx tab=\"Server Component\" tab-group=\"redirect-to-sign-out\"\n * import { getSession, redirectToSignOut } from \"@monocloud/auth-nextjs\";\n *\n * export default async function Page() {\n * const session = await getSession();\n *\n * // Example: Force sign-out if a specific condition is met (e.g., account suspended)\n * if (session?.user.isSuspended) {\n * await redirectToSignOut();\n * }\n *\n * return <>Welcome User</>;\n * }\n * ```\n *\n * @example Server Action\n * ```tsx:src/action.ts tab=\"Server Action\" tab-group=\"redirect-to-sign-out\"\n * \"use server\";\n *\n * import { getSession, redirectToSignOut } from \"@monocloud/auth-nextjs\";\n *\n * export async function signOutAction() {\n * const session = await getSession();\n *\n * if (session) {\n * await redirectToSignOut();\n * }\n * }\n * ```\n *\n * @example API Handler\n * ```tsx:src/app/api/signout/route.ts tab=\"API Handler\" tab-group=\"redirect-to-sign-out\"\n * import { getSession, redirectToSignOut } from \"@monocloud/auth-nextjs\";\n * import { NextResponse } from \"next/server\";\n *\n * export const GET = async () => {\n * const session = await getSession();\n *\n * if (session) {\n * await redirectToSignOut({\n * postLogoutRedirectUri: \"/goodbye\",\n * });\n * }\n *\n * return NextResponse.json({ status: \"already_signed_out\" });\n * };\n * ```\n *\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 * @category Functions\n */\nexport function redirectToSignOut(\n options?: RedirectToSignOutOptions\n): Promise<void> {\n return getInstance().redirectToSignOut(options);\n}\n"],"mappings":";;;;;;;;;AAIA,IAAqB,4BAArB,MAA2E;CACzE,YAAY,AAAgB,KAAkB;EAAlB;;CAE5B,SAAS,WAAkD;AAEzD,SADY,IAAI,IAAI,KAAK,IAAI,IAAI,CACtB,aAAa,IAAI,UAAU,IAAI;;CAG5C,UAAU,MAA2C;;AACnD,SAAO,QAAQ,iCAAQ,KAAK,IAAI,QAAQ,IAAI,KAAK,gFAAE,MAAM;;CAG3D,MAAM,gBAIH;AACD,SAAO;GACL,QAAQ,KAAK,IAAI;GACjB,KAAK,KAAK,IAAI;GACd,MAAM,MAAM,KAAK,IAAI,MAAM;GAC5B;;CAGH,gBAA8C;EAC5C,MAAM,yBAAS,IAAI,KAAqB;AAC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