@monocloud/auth-nextjs 0.1.5 → 0.1.7

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/index.d.mts CHANGED
@@ -1,42 +1,41 @@
1
- import { _ as ProtectPagePageOptions, a as GroupOptions, b as RedirectToSignInOptions, c as MonoCloudAuthOptions, d as PageRouterApiOnAccessDeniedHandler, f as ProtectApiAppOptions, g as ProtectPagePageOnAccessDeniedType, h as ProtectOptions, i as ExtraAuthParams, l as MonoCloudMiddlewareOptions, m as ProtectAppPageOptions, n as AppRouterApiOnAccessDeniedHandler, o as IsUserInGroupOptions, p as ProtectApiPageOptions, r as AppRouterPageHandler, s as MonoCloudAuthHandler, t as AppRouterApiHandlerFn, u as NextMiddlewareResult, v as ProtectPagePageReturnType, x as RedirectToSignOutOptions, y as ProtectedAppServerComponent } from "./types-CsBjAJce.mjs";
2
- import { AccessToken, GetTokensOptions, GetTokensOptions as GetTokensOptions$1, MonoCloudAuthBaseError, MonoCloudCoreClient, MonoCloudHttpError, MonoCloudOPError, MonoCloudOidcClient, MonoCloudOptions, MonoCloudOptions as MonoCloudOptions$1, MonoCloudSession, MonoCloudSession as MonoCloudSession$1, MonoCloudTokenError, MonoCloudTokens, MonoCloudTokens as MonoCloudTokens$1, MonoCloudUser, MonoCloudValidationError } from "@monocloud/auth-node-core";
1
+ import { A as ProtectedRouteMatcher, C as ProtectAppPageOptions, D as ProtectPagePageOptions, E as ProtectPagePageOnGroupAccessDeniedType, M as RedirectToSignInOptions, N as RedirectToSignOutOptions, O as ProtectPagePageReturnType, S as ProtectApiPageOptions, T as ProtectPagePageOnAccessDeniedType, _ as OnError, a as AppRouterContext, b as PageRouterApiOnGroupAccessDeniedHandler, c as ExtraAuthParams, d as MonoCloudAuthHandler, f as MonoCloudAuthOptions, g as NextMiddlewareResult, h as NextMiddlewareOnGroupAccessDenied, i as AppRouterApiOnGroupAccessDeniedHandler, j as ProtectedRoutes, k as ProtectedAppServerComponent, l as GroupOptions, m as NextMiddlewareOnAccessDenied, n as AppRouterApiHandlerFn, o as AppRouterPageHandler, p as MonoCloudMiddlewareOptions, r as AppRouterApiOnAccessDeniedHandler, s as CustomProtectedRouteMatcher, t as AppOnError, u as IsUserInGroupOptions, v as PageOnError, w as ProtectOptions, x as ProtectApiAppOptions, y as PageRouterApiOnAccessDeniedHandler } from "./types-xS_Me3Qg.mjs";
2
+ import { AccessToken, Address, ApplicationState, Authenticators, AuthorizationParams, CodeChallengeMethod, DisplayOptions, GetTokensOptions, GetTokensOptions as GetTokensOptions$1, Group, IdTokenClaims, Indicator, Jwk, MonoCloudAuthBaseError, MonoCloudCookieOptions, MonoCloudCoreClient, MonoCloudHttpError, MonoCloudOPError, MonoCloudOptions, MonoCloudOptions as MonoCloudOptions$1, MonoCloudRequest, MonoCloudRoutes, MonoCloudSession, MonoCloudSession as MonoCloudSession$1, MonoCloudSessionOptions, MonoCloudSessionOptionsBase, MonoCloudSessionStore, MonoCloudStateOptions, MonoCloudStatePartialOptions, MonoCloudTokenError, MonoCloudTokens, MonoCloudTokens as MonoCloudTokens$1, MonoCloudUser, MonoCloudValidationError, OnBackChannelLogout, OnSessionCreating, OnSetApplicationState, Prompt, ResponseModes, ResponseTypes, SameSiteValues, SecurityAlgorithms, SessionLifetime, UserinfoResponse } from "@monocloud/auth-node-core";
3
3
  import { NextFetchEvent, NextMiddleware, NextProxy, NextRequest, NextResponse } from "next/server.js";
4
- import { IncomingMessage, ServerResponse } from "node:http";
4
+ import { NextFetchEvent as NextFetchEvent$1, NextMiddleware as NextMiddleware$1, NextProxy as NextProxy$1, NextRequest as NextRequest$1, NextResponse as NextResponse$1 } from "next/server";
5
5
  import { NextApiHandler, NextApiRequest, NextApiResponse } from "next/types";
6
6
  import { ParsedUrlQuery } from "node:querystring";
7
+ import { MonoCloudOidcClient, MonoCloudSession as MonoCloudSession$2 } from "@monocloud/auth-core";
8
+ import { IncomingMessage, ServerResponse } from "node:http";
9
+ import { NextApiHandler as NextApiHandler$1, NextApiRequest as NextApiRequest$1, NextApiResponse as NextApiResponse$1 } from "next";
7
10
 
8
11
  //#region src/monocloud-next-client.d.ts
9
-
10
12
  /**
11
- * The MonoCloud Next.js Client.
13
+ * `MonoCloudNextClient` is the core SDK entry point for integrating MonoCloud authentication into a Next.js application.
12
14
  *
13
- * @example Using Environment Variables (Recommended)
15
+ * It provides:
16
+ * - Authentication middleware
17
+ * - Route protection helpers
18
+ * - Session and token access
19
+ * - Redirect utilities
20
+ * - Server-side enforcement helpers
14
21
  *
15
- * 1. Add following variables to your `.env`.
22
+ * ## 1. Add environment variables
16
23
  *
17
- * ```bash
24
+ * ```bash:.env.local
18
25
  * MONOCLOUD_AUTH_TENANT_DOMAIN=<tenant-domain>
19
26
  * MONOCLOUD_AUTH_CLIENT_ID=<client-id>
20
27
  * MONOCLOUD_AUTH_CLIENT_SECRET=<client-secret>
21
- * MONOCLOUD_AUTH_SCOPES=openid profile email # Default
28
+ * MONOCLOUD_AUTH_SCOPES=openid profile email
22
29
  * MONOCLOUD_AUTH_APP_URL=http://localhost:3000
23
30
  * MONOCLOUD_AUTH_COOKIE_SECRET=<cookie-secret>
24
31
  * ```
25
32
  *
26
- * 2. Instantiate the client in a shared file (e.g., lib/monocloud.ts)
27
- *
28
- * ```typescript
29
- * import { MonoCloudNextClient } from '@monocloud/auth-nextjs';
30
- *
31
- * export const monoCloud = new MonoCloudNextClient();
32
- * ```
33
- *
34
- * 3. Add MonoCloud middleware/proxy
33
+ * ## 2. Register middleware
35
34
  *
36
- * ```typescript
37
- * import { monoCloud } from "@/lib/monocloud";
35
+ * ```typescript:src/proxy.ts
36
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
38
37
  *
39
- * export default monoCloud.authMiddleware();
38
+ * export default authMiddleware();
40
39
  *
41
40
  * export const config = {
42
41
  * matcher: [
@@ -45,1926 +44,1638 @@ import { ParsedUrlQuery } from "node:querystring";
45
44
  * };
46
45
  * ```
47
46
  *
48
- * @example Using Constructor Options
47
+ * ## Advanced usage
48
+ *
49
+ * ### Create a shared client instance
50
+ *
51
+ * By default, the SDK exposes function exports (for example, `authMiddleware()`, `getSession()`, `getTokens()`) that internally use a shared singleton `MonoCloudNextClient`.
52
+ *
53
+ * Create your own `MonoCloudNextClient` instance when you need multiple configurations, dependency injection, or explicit control over initialization.
54
+ *
55
+ * ```ts:src/monocloud.ts
56
+ * import { MonoCloudNextClient } from "@monocloud/auth-nextjs";
57
+ *
58
+ * export const monoCloud = new MonoCloudNextClient();
59
+ * ```
60
+ *
61
+ * ### Using instance methods
49
62
  *
50
- * ⚠️ Security Note: Never commit your credentials to version control. Load them from environment variables.
63
+ * Once you create a client instance, call methods directly on it instead of using the default function exports.
51
64
  *
52
- * 1. Instantiate the client in a shared file (e.g., lib/monocloud.ts)
65
+ * ```ts:src/app/page.tsx
66
+ * import { monoCloud } from "@/monocloud";
53
67
  *
54
- * ```typescript
55
- * import { MonoCloudNextClient } from '@monocloud/auth-nextjs';
68
+ * export default async function Page() {
69
+ * const session = await monoCloud.getSession();
70
+ *
71
+ * if (!session) {
72
+ * return <>Not signed in</>;
73
+ * }
74
+ *
75
+ * return <>Hello {session.user.name}</>;
76
+ * }
77
+ * ```
78
+ *
79
+ * #### Using constructor options
80
+ *
81
+ * 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.
82
+ *
83
+ * ```ts:src/monocloud.ts
84
+ * import { MonoCloudNextClient } from "@monocloud/auth-nextjs";
56
85
  *
57
86
  * export const monoCloud = new MonoCloudNextClient({
58
- * tenantDomain: '<tenant-domain>',
59
- * clientId: '<client-id>',
60
- * clientSecret: '<client-secret>',
61
- * scopes: 'openid profile email', // Default
62
- * appUrl: 'http://localhost:3000',
63
- * cookieSecret: '<cookie-secret>'
87
+ * tenantDomain: "<tenant-domain>",
88
+ * clientId: "<client-id>",
89
+ * clientSecret: "<client-secret>",
90
+ * appUrl: "http://localhost:3000",
91
+ * cookieSecret: "<cookie-secret>",
92
+ * defaultAuthParams: {
93
+ * scopes: "openid profile email",
94
+ * },
64
95
  * });
65
96
  * ```
66
- * 2. Add MonoCloud middleware/proxy
67
97
  *
68
- * ```typescript
69
- * import { monoCloud } from "@/lib/monocloud";
98
+ * ### Modifying default routes
70
99
  *
71
- * export default monoCloud.authMiddleware();
100
+ * If you customize any of the default auth route paths:
72
101
  *
73
- * export const config = {
74
- * matcher: [
75
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
76
- * ],
77
- * };
102
+ * - Also set the corresponding `NEXT_PUBLIC_` environment variables so client-side helpers
103
+ * (for example `<SignIn />`, `<SignOut />`, and `useAuth()`) can discover the correct URLs.
104
+ * - Update the **Application URLs** in your MonoCloud Dashboard to match the new paths.
105
+ *
106
+ * Example:
107
+ *
108
+ * ```bash:.env.local
109
+ * MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
110
+ * NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
78
111
  * ```
79
112
  *
80
- * <details>
81
- * <summary>All Environment Variables</summary>
82
- * <h4>Core Configuration (Required)</h4>
83
- *
84
- * <ul>
85
- * <li><strong>MONOCLOUD_AUTH_CLIENT_ID : </strong>Unique identifier for your application/client.</li>
86
- * <li><strong>MONOCLOUD_AUTH_CLIENT_SECRET : </strong>Application/client secret.</li>
87
- * <li><strong>MONOCLOUD_AUTH_TENANT_DOMAIN : </strong>The domain of your MonoCloud tenant (e.g., https://your-tenant.us.monocloud.com).</li>
88
- * <li><strong>MONOCLOUD_AUTH_APP_URL : </strong>The base URL where your application is hosted.</li>
89
- * <li><strong>MONOCLOUD_AUTH_COOKIE_SECRET : </strong>A long, random string used to encrypt and sign session cookies.</li>
90
- * </ul>
91
- *
92
- * <h4>Authentication &amp; Security</h4>
93
- *
94
- * <ul>
95
- * <li><strong>MONOCLOUD_AUTH_SCOPES : </strong>A space-separated list of OIDC scopes to request (e.g., openid profile email).</li>
96
- * <li><strong>MONOCLOUD_AUTH_RESOURCE : </strong>The default resource/audience identifier for access tokens.</li>
97
- * <li><strong>MONOCLOUD_AUTH_USE_PAR : </strong>Enables Pushed Authorization Requests.</li>
98
- * <li><strong>MONOCLOUD_AUTH_CLOCK_SKEW : </strong>The allowed clock drift in seconds when validating token timestamps.</li>
99
- * <li><strong>MONOCLOUD_AUTH_FEDERATED_SIGNOUT : </strong>If true, signs the user out of MonoCloud (SSO sign-out) when they sign out of the app.</li>
100
- * <li><strong>MONOCLOUD_AUTH_RESPONSE_TIMEOUT : </strong>The maximum time in milliseconds to wait for a response.</li>
101
- * <li><strong>MONOCLOUD_AUTH_ALLOW_QUERY_PARAM_OVERRIDES : </strong>Allows dynamic overrides of auth parameters via URL query strings.</li>
102
- * <li><strong>MONOCLOUD_AUTH_POST_LOGOUT_REDIRECT_URI : </strong>The URL users are sent to after a successful logout.</li>
103
- * <li><strong>MONOCLOUD_AUTH_USER_INFO : </strong>Determines if user profile data from the UserInfo endpoint should be fetched after authorization code exchange.</li>
104
- * <li><strong>MONOCLOUD_AUTH_REFETCH_USER_INFO : </strong>If true, re-fetches user information on every request to userinfo endpoint or when calling getTokens()</li>
105
- * <li><strong>MONOCLOUD_AUTH_ID_TOKEN_SIGNING_ALG : </strong>The expected algorithm for signing ID tokens (e.g., RS256).</li>
106
- * <li><strong>MONOCLOUD_AUTH_FILTERED_ID_TOKEN_CLAIMS : </strong>A space-separated list of claims to exclude from the session object.</li>
107
- * </ul>
108
- *
109
- * <h4>Routes</h4>
110
- *
111
- * <aside>
112
- * <strong>⚠️ Important: Modifying Default Routes</strong>
113
- * <p>If you choose to customize any of the default route paths, you must adhere to the following requirements:</p>
114
- * <ul>
115
- * <li>
116
- * <strong>Client-Side Synchronization:</strong> You must also define a corresponding <code>NEXT_PUBLIC_</code> version of the environment variable (e.g., <code>NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL</code>). This ensures that client-side components like <code>&lt;SignIn /&gt;</code>, <code>&lt;SignOut /&gt;</code>, and the <code>useAuth()</code> hook can correctly identify your custom endpoints.
117
- * </li>
118
- * <li>
119
- * <strong>Dashboard Configuration:</strong> Changing these URLs will alter the endpoints required by MonoCloud. You must update the <strong>Application URLs</strong> section in your MonoCloud Dashboard to match these new paths.
120
- * </li>
121
- * </ul>
122
- * <p><em>Example:</em></p>
123
- * <code>
124
- * MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback<br />
125
- * NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
126
- * </code>
127
- * <p>In this case, the Redirect URI in your dashboard should be set to: <code>http://localhost:3000/api/custom_callback</code> (assuming local development).</p>
128
- * </aside>
129
- *
130
- * <ul>
131
- * <li><strong>MONOCLOUD_AUTH_CALLBACK_URL : </strong>The application path where MonoCloud sends the user after authentication.</li>
132
- * <li><strong>MONOCLOUD_AUTH_SIGNIN_URL : </strong>The internal route path to trigger the sign-in.</li>
133
- * <li><strong>MONOCLOUD_AUTH_SIGNOUT_URL : </strong>The internal route path to trigger the sign-out.</li>
134
- * <li><strong>MONOCLOUD_AUTH_USER_INFO_URL : </strong>The route that exposes the current user's profile from userinfo endpoint.</li>
135
- * </ul>
136
- *
137
- * <h4>Session Cookie Settings</h4>
138
- *
139
- * <ul>
140
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_NAME : </strong>The name of the cookie used to store the user session.</li>
141
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_PATH : </strong>The scope path for the session cookie.</li>
142
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_DOMAIN : </strong>The domain scope for the session cookie.</li>
143
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_HTTP_ONLY : </strong>Prevents client-side scripts from accessing the session cookie.</li>
144
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_SECURE : </strong>Ensures the session cookie is only sent over HTTPS.</li>
145
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_SAME_SITE : </strong>The SameSite policy for the session cookie (Lax, Strict, or None).</li>
146
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_PERSISTENT : </strong>If true, the session survives browser restarts.</li>
147
- * <li><strong>MONOCLOUD_AUTH_SESSION_SLIDING : </strong>If true, the session will be a sliding session instead of absolute.</li>
148
- * <li><strong>MONOCLOUD_AUTH_SESSION_DURATION : </strong>The session lifetime in seconds.</li>
149
- * <li><strong>MONOCLOUD_AUTH_SESSION_MAX_DURATION : </strong>The absolute maximum lifetime of a session in seconds.</li>
150
- * </ul>
151
- *
152
- * <h4>State Cookie Settings</h4>
153
- *
154
- * <ul>
155
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_NAME : </strong>The name of the cookie used to store OpenID state/nonce.</li>
156
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_PATH : </strong>The scope path for the state cookie.</li>
157
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_DOMAIN : </strong>The domain scope for the state cookie.</li>
158
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_SECURE : </strong>Ensures the state cookie is only sent over HTTPS</li>
159
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_SAME_SITE : </strong>The SameSite policy for the state cookie.</li>
160
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_PERSISTENT : </strong>Whether the state cookie is persistent.</li>
161
- * </ul>
162
- *
163
- * <h4>Caching</h4>
164
- *
165
- * <ul>
166
- * <li><strong>MONOCLOUD_AUTH_JWKS_CACHE_DURATION : </strong>Duration in seconds to cache the JSON Web Key Set.</li>
167
- * <li><strong>MONOCLOUD_AUTH_METADATA_CACHE_DURATION : </strong>Duration in seconds to cache the OpenID discovery metadata.</li>
168
- * </ul>
169
- * </details>
113
+ * When routes are overridden, the Redirect URI configured in the dashboard
114
+ * must reflect the new path. For example, during local development:
170
115
  *
116
+ * `http://localhost:3000/api/custom_callback`
171
117
  *
118
+ * @category Classes
172
119
  */
173
120
  declare class MonoCloudNextClient {
121
+ private readonly _coreClient;
174
122
  /**
175
- * The underlying MonoCloud Node Core Client instance.
176
- *
177
- * This property exposes the framework-agnostic node core client used by the Next.js client.
178
- * You can access this to use low-level methods not directly exposed by the Next.js wrapper.
123
+ * This exposes the framework-agnostic MonoCloud client used internally by the Next.js SDK.
124
+ * Use it if you need access to lower-level functionality not directly exposed by MonoCloudNextClient.
179
125
  *
180
- * @example Manually destroy session
181
- * ```typescript
182
- * // req and res must implement IMonoCloudCookieRequest/Response
183
- * await monoCloud.coreClient.destroySession(request, response);
184
- * ```
126
+ * @returns Returns the underlying **Node client** instance.
185
127
  */
186
- readonly coreClient: MonoCloudCoreClient;
128
+ get coreClient(): MonoCloudCoreClient;
187
129
  /**
188
- * The underlying OIDC client instance used for low-level OpenID Connect operations.
130
+ * This is intended for advanced scenarios requiring direct control over the authorization or token flow.
189
131
  *
190
- * @example
191
- * // Manually revoke an access token
192
- * await client.oidcClient.revokeToken(accessToken, 'access_token');
132
+ * @returns Returns the underlying **OIDC client** used for OpenID Connect operations.
193
133
  */
194
134
  get oidcClient(): MonoCloudOidcClient;
195
135
  /**
196
- * @param options Configuration options including domain, client ID, and secret.
136
+ * Creates a new client instance.
137
+ *
138
+ * @param options Optional configuration for initializing the MonoCloud client. If not provided, settings are automatically resolved from environment variables.
197
139
  */
198
140
  constructor(options?: MonoCloudOptions$1);
199
141
  /**
200
- * Creates a **Next.js API route handler** (for both Pages Router and App Router)
201
- * that processes all MonoCloud authentication endpoints
202
- * (`/signin`, `/callback`, `/userinfo`, `/signout`).
203
- *
204
- * @param options Authentication configuration routes.
205
- *
206
- * **Note:** If you are already using `authMiddleware()`, you typically do **not**
207
- * need this API route handler. This function is intended for applications where
208
- * middleware cannot be used—such as statically generated (SSG) deployments that still
209
- * require server-side authentication flows.
210
- *
211
- * @example App Router
212
- *
213
- * ```typescript
214
- * // app/api/auth/[...monocloud]/route.ts
215
- *
216
- * import { monoCloud } from "@/lib/monocloud";
217
- *
218
- * export const GET = monoCloud.monoCloudAuth();
219
- *```
220
- *
221
- * @example App Router with Response
222
- *
223
- * ```typescript
224
- * import { monoCloud } from "@/lib/monocloud";
225
- * import { NextRequest, NextResponse } from "next/server";
226
- *
227
- * export const GET = (req: NextRequest) => {
228
- * const authHandler = monoCloud.monoCloudAuth();
229
- *
230
- * const res = new NextResponse();
231
- *
232
- * res.cookies.set("last_auth_requested", `${Date.now()}`);
233
- *
234
- * return authHandler(req, res);
235
- * };
236
- * ```
237
- *
238
- * @example Pages Router
239
- *
240
- * ```typescript
241
- * // pages/api/auth/[...monocloud].ts
242
- *
243
- * import { monoCloud } from "@/lib/monocloud";
244
- *
245
- * export default monoCloud.monoCloudAuth();
246
- *```
247
- *
248
- * @example Page Router with Response
249
- *
250
- * ```typescript
251
- * import { monoCloud } from "@/lib/monocloud";
252
- * import { NextApiRequest, NextApiResponse } from "next";
253
- *
254
- * export default function handler(req: NextApiRequest, res: NextApiResponse) {
255
- * const authHandler = monoCloud.monoCloudAuth();
256
- *
257
- * res.setHeader("last_auth_requested", `${Date.now()}`);
258
- *
259
- * return authHandler(req, res);
260
- * }
261
- * ```
262
- *
142
+ * @see {@link monoCloudAuth} for full docs and examples.
143
+ * @param options Optional configuration for the auth handler.
144
+ * @returns Returns a Next.js-compatible handler for App Router route handlers or Pages Router API routes.
263
145
  */
264
146
  monoCloudAuth(options?: MonoCloudAuthOptions): MonoCloudAuthHandler;
265
147
  /**
266
- *
267
- * ## App Router
268
- *
269
- * Restricts access to server-rendered pages in your Next.js App Router application, ensures that only authenticated (and optionally authorized) users can view the page.
270
- *
271
- * **Note⚠️ - When using groups to protect a page, 'Access Denied' is rendered by default when the user does not belong to the groups.
272
- * To display a custom component, pass the `onGroupAccessDenied` parameter.**
273
- *
274
- * @param component The App Router server component that protectPage wraps and secures
275
- * @param options App Router `protectPage()` configuration options
276
- *
277
- * @returns A protected page handler.
278
- *
279
- * @example
280
- *
281
- * ```typescript
282
- * import { monoCloud } from "@/lib/monocloud";
283
- *
284
- * export default monoCloud.protectPage(async function Home({ user }) {
285
- * return <>Hi {user.email}. You accessed a protected page.</>;
286
- * });
287
- * ```
288
- *
289
- * @example App Router with options
290
- *
291
- * ```typescript
292
- * import { monoCloud } from "@/lib/monocloud";
293
- *
294
- * export default monoCloud.protectPage(
295
- * async function Home({ user }) {
296
- * return <>Hi {user.email}. You accessed a protected page.</>;
297
- * },
298
- * {
299
- * returnUrl: "/dashboard",
300
- * groups: ["admin"],
301
- * }
302
- * );
303
- * ```
148
+ * @see {@link protectPage} for full docs and examples.
149
+ * @param component The App Router server component to protect.
150
+ * @param options Optional configuration for authentication, authorization, and custom access handling (`onAccessDenied`, `onGroupAccessDenied`).
151
+ * @returns A wrapped page component that enforces authentication before rendering.
304
152
  */
305
153
  protectPage(component: ProtectedAppServerComponent, options?: ProtectAppPageOptions): AppRouterPageHandler;
306
154
  /**
307
- * ## Pages Router
308
- *
309
- * Restricts access to server-rendered pages in your Next.js Pages Router application, ensures that only authenticated (and optionally authorized) users can view the page.
310
- *
311
- * **Note⚠️ - When using groups to protect a page, the page will be rendered even if the user does not belong to the groups.
312
- * You should check the props for `groupAccessDenied` boolean value to determine whether the user is
313
- * allowed to access the page. Alternatively, you can pass `onGroupAccessDenied` parameter to return custom props.**
314
- *
315
- * @param options Pages Router `protectPage()` configuration options
316
- *
317
- * @typeParam P - The type of parameters accepted by the page handler.
318
- * @typeParam Q - The type of query parameters parsed from the URL.
319
- *
320
- * @returns A protected page handler.
321
- *
322
- * @example
323
- *
324
- * ```typescript
325
- * import { monoCloud } from "@/lib/monocloud";
326
- * import { InferGetServerSidePropsType } from "next";
327
- *
328
- * export default function Home({
329
- * user,
330
- * }: InferGetServerSidePropsType<typeof getServerSideProps>) {
331
- * return <>Hi {user.email}. You accessed a protected page.</>;
332
- * }
333
- *
334
- * export const getServerSideProps = monoCloud.protectPage();
335
- * ```
336
- *
337
- * @example Pages Router with options
338
- *
339
- * ```typescript
340
- * import { monoCloud } from "@/lib/monocloud";
341
- * import { GetServerSidePropsContext, InferGetServerSidePropsType } from "next";
342
- *
343
- * export default function Home({
344
- * user,
345
- * url,
346
- * }: InferGetServerSidePropsType<typeof getServerSideProps>) {
347
- * console.log(url);
348
- * return <div>Hi {user?.email}. You accessed a protected page.</div>;
349
- * }
350
- *
351
- * export const getServerSideProps = monoCloud.protectPage({
352
- * returnUrl: "/dashboard",
353
- * groups: ["admin"],
354
- * getServerSideProps: async (context: GetServerSidePropsContext) => ({
355
- * props: { url: context.resolvedUrl },
356
- * }),
357
- * });
358
- * ```
155
+ * @see {@link protectPage} for full docs and examples.
156
+ * @param options Optional configuration for authentication, authorization, and custom access handling (`onAccessDenied`, `onGroupAccessDenied`).
157
+ * @typeParam P - Props returned from getServerSideProps.
158
+ * @typeParam Q - Query parameters parsed from the URL.
159
+ * @returns A getServerSideProps wrapper that enforces authentication before executing the page logic.
359
160
  */
360
161
  protectPage<P extends Record<string, any> = Record<string, any>, Q extends ParsedUrlQuery = ParsedUrlQuery>(options?: ProtectPagePageOptions<P, Q>): ProtectPagePageReturnType<P, Q>;
361
162
  private protectAppPage;
362
163
  private protectPagePage;
363
164
  /**
364
- * ## App Router
365
- *
366
- * Secures Next.js App Router APIs. It ensures only authenticated (and optionally authorized) requests can access the route.
367
- *
368
- * @param handler The api route handler function to protect
369
- * @param options App Router `protectApi()` configuration options
370
- *
371
- * @returns Protected route handler
372
- *
373
- * @example
374
- *
375
- * ```typescript
376
- * import { monoCloud } from "@/lib/monocloud";
377
- * import { NextResponse } from "next/server";
378
- *
379
- * export const GET = monoCloud.protectApi(async () => {
380
- * return NextResponse.json({
381
- * message: "You accessed a protected endpoint",
382
- * });
383
- * });
384
- * ```
165
+ * @see {@link protectApi} for full docs and examples.
166
+ * @param handler The route handler to protect.
167
+ * @param options Optional configuration controlling authentication and authorization behavior.
168
+ * @returns Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.
385
169
  */
386
170
  protectApi(handler: AppRouterApiHandlerFn, options?: ProtectApiAppOptions): AppRouterApiHandlerFn;
387
171
  /**
388
- * ## Pages Router
389
- *
390
- * Secures Next.js Pages Router APIs. It ensures only authenticated (and optionally authorized) requests can access the route.
391
- *
392
- * @param handler The api route handler function to protect
393
- * @param options Pages Router `protectApi()` configuration options
394
- *
395
- * @returns Protected route handler
396
- *
397
- * @example
398
- *
399
- * ```typescript
400
- * import { monoCloud } from "@/lib/monocloud";
401
- * import type { NextApiRequest, NextApiResponse } from "next";
402
- *
403
- * export default monoCloud.protectApi(
404
- * async (req: NextApiRequest, res: NextApiResponse) => {
405
- * return res.json({
406
- * message: "You accessed a protected endpoint",
407
- * });
408
- * }
409
- * );
410
- * ```
172
+ * @see {@link protectApi} for full docs and examples.
173
+ * @param handler - The route handler to protect.
174
+ * @param options Optional configuration controlling authentication and authorization behavior.
175
+ * @returns Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.
411
176
  */
412
177
  protectApi(handler: NextApiHandler, options?: ProtectApiPageOptions): NextApiHandler;
413
178
  private protectAppApi;
414
179
  private protectPageApi;
415
180
  /**
416
- * A middleware/proxy that protects pages and APIs and handles authentication.
417
- *
418
- * @param options Middleware configuration options
419
- *
420
- * @returns A Next.js middleware/proxy function.
421
- *
422
- * @example Protect All Routes
423
- *
424
- * - Default behavior: protect all routes matched by `config.matcher`
425
- *
426
- * ```typescript
427
- * import { monoCloud } from "@/lib/monocloud";
428
- *
429
- * export default monoCloud.authMiddleware();
430
- *
431
- * export const config = {
432
- * matcher: [
433
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
434
- * ],
435
- * };
436
- * ```
437
- *
438
- * @example Protect Selected Routes
439
- *
440
- * - Protect only the routes listed in `protectedRoutes`
441
- *
442
- * ```typescript
443
- * import { monoCloud } from "@/lib/monocloud";
444
- *
445
- * export default monoCloud.authMiddleware({
446
- * protectedRoutes: ["/api/admin", "^/api/protected(/.*)?$"],
447
- * });
448
- *
449
- * export const config = {
450
- * matcher: [
451
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
452
- * ],
453
- * };
454
- *```
455
- *
456
- * @example Make All Routes Public
457
- *
458
- * - Do not protect any routes; MonoCloud still handles auth endpoints
459
- *
460
- * ```typescript
461
- * import { monoCloud } from "@/lib/monocloud";
462
- *
463
- * export default monoCloud.authMiddleware({
464
- * protectedRoutes: [],
465
- * });
466
- *
467
- * export const config = {
468
- * matcher: [
469
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
470
- * ],
471
- * };
472
- * ```
473
- *
474
- * @example Protect Routes Dynamically
475
- *
476
- * - Decide at runtime which routes to protect
477
- *
478
- * ```typescript
479
- * import { monoCloud } from "@/lib/monocloud";
480
- *
481
- * export default monoCloud.authMiddleware({
482
- * protectedRoutes: (req) => {
483
- * return req.nextUrl.pathname.startsWith("/api/protected");
484
- * },
485
- * });
486
- *
487
- * export const config = {
488
- * matcher: [
489
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
490
- * ],
491
- * };
492
- * ```
493
- *
494
- * @example Protect routes based on groups
495
- *
496
- * ```typescript
497
- * import { monoCloud } from "@/lib/monocloud";
498
- *
499
- * export default monoCloud.authMiddleware({
500
- * // group names or IDs
501
- * protectedRoutes: [
502
- * {
503
- * groups: ["admin", "editor", "537e7c3d-a442-4b5b-b308-30837aa045a4"],
504
- * routes: ["/internal", "/api/internal(.*)"],
505
- * },
506
- * ],
507
- * });
508
- *
509
- * export const config = {
510
- * matcher: [
511
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
512
- * ],
513
- * };
514
- * ```
515
- *
181
+ * @see {@link authMiddleware} for full docs and examples.
182
+ * @param options Optional configuration that controls how authentication is enforced (for example, redirect behavior, route matching, or custom handling of unauthenticated requests).
183
+ * @returns Returns a Next.js middleware result (`NextResponse`, redirect, or `undefined` to continue processing).
516
184
  */
517
185
  authMiddleware(options?: MonoCloudMiddlewareOptions): NextMiddleware | NextProxy;
518
186
  /**
519
- * A middleware that protects pages and APIs and handles authentication.
520
- *
521
- * @param request The Next.js fetch event object.
522
- * @param event The associated fetch event [Docs](https://nextjs.org/docs/app/api-reference/file-conventions/proxy#waituntil-and-nextfetchevent).
523
- *
524
- * @returns A promise resolving to a Next.js middleware result or a Next.js middleware result.
525
- *
526
- * @example Nest Custom Middleware
527
- *
528
- * - Use your own middleware wrapper and call MonoCloud only for specific routes
529
- *
530
- * ```typescript
531
- * import { monoCloud } from "@/lib/monocloud";
532
- * import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
533
- *
534
- * export default function customMiddleware(req: NextRequest, evt: NextFetchEvent) {
535
- * if (req.nextUrl.pathname.startsWith("/api/protected")) {
536
- * return monoCloud.authMiddleware(req, evt);
537
- * }
538
- *
539
- * return NextResponse.next();
540
- * }
541
- *
542
- * export const config = {
543
- * matcher: [
544
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
545
- * ],
546
- * };
547
- * ```
548
- *
187
+ * @see {@link authMiddleware} for full docs and examples.
188
+ * @param request Incoming Next.js middleware request used to resolve authentication state.
189
+ * @param event Next.js middleware event providing lifecycle hooks such as `waitUntil`.
190
+ * @returns Returns a Next.js middleware result (`NextResponse`, redirect, or `undefined` to continue processing).
549
191
  */
550
192
  authMiddleware(request: NextRequest, event: NextFetchEvent): Promise<NextMiddlewareResult> | NextMiddlewareResult;
551
193
  private authMiddlewareHandler;
552
194
  private handleAuthRoutes;
553
195
  /**
554
- * ## SSR Components, Actions, Middleware or API Handlers
555
- *
556
- * Retrieves the session object for the currently authenticated user on the server.
557
- *
558
- * **Use Case:**
559
- * - App Router Server Components (RSC).
560
- * - Server Actions
561
- * - Route Handlers (App Router only).
562
- * - Middleware (App Router and Pages Router).
563
- *
564
- * *Note: If the session cannot be resolved or an underlying error occurs, the promise rejects with an error.*
565
- *
566
- * @returns `MonoCloudSession` if found, or `undefined`.
567
- *
568
- * @example Middleware/Proxy
569
- *
570
- * ```typescript
571
- * import { monoCloud } from "@/lib/monocloud";
572
- * import { NextResponse } from "next/server";
573
- *
574
- * export default async function middleware() {
575
- * const session = await monoCloud.getSession();
576
- *
577
- * if (!session) {
578
- * return new NextResponse("User not signed in", { status: 401 });
579
- * }
580
- *
581
- * return NextResponse.next();
582
- * }
583
- *
584
- * export const config = {
585
- * matcher: [
586
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
587
- * ],
588
- * };
589
- * ```
590
- *
591
- * @example App Router API Handler
592
- *
593
- * ```typescript
594
- * import { NextResponse } from "next/server";
595
- * import { monoCloud } from "@/lib/monocloud";
596
- *
597
- * export const GET = async () => {
598
- * const session = await monoCloud.getSession();
599
- *
600
- * return NextResponse.json({ name: session?.user.name });
601
- * };
602
- * ```
603
- *
604
- * @example React Server Components
605
- *
606
- * ```tsx
607
- * import { monoCloud } from "@/lib/monocloud";
608
- *
609
- * export default async function Home() {
610
- * const session = await monoCloud.getSession();
611
- *
612
- * return <div>{session?.user.name}</div>;
613
- * }
614
- * ```
615
- *
616
- * @example Server Action
617
- *
618
- * ```typescript
619
- * "use server";
620
- *
621
- * import { monoCloud } from "@/lib/monocloud";
622
- *
623
- * export async function getUserAction() {
624
- * const session = await monoCloud.getSession();
625
- *
626
- * return { name: session?.user.name };
627
- * }
628
- * ```
629
- *
196
+ * @see {@link getSession} for full docs and examples.
197
+ * @returns Returns the resolved session, or `undefined` if none exists.
630
198
  */
631
199
  getSession(): Promise<MonoCloudSession$1 | undefined>;
632
200
  /**
633
- * ## Middleware/Proxy or Route Handlers
634
- *
635
- * Retrieves the session object for the currently authenticated user on the server.
636
- *
637
- * **Use Case:**
638
- * - Middleware (for both App and Pages Router).
639
- * - App Router Route Handlers (API routes).
640
- * - Edge functions.
641
- *
642
- * *Note: If the session cannot be resolved or an underlying error occurs, the promise rejects with an error.*
643
- *
644
- * @param req NextRequest
645
- * @param res An optional `NextResponse` instance. Pass this if you have already initialized a response; otherwise, omit this parameter.
646
- *
647
- * @returns `MonoCloudSession` if found, or `undefined`.
648
- *
649
- * @example Middleware/Proxy
650
- *
651
- * ```typescript
652
- * import { monoCloud } from "@/lib/monocloud";
653
- * import { NextRequest, NextResponse } from "next/server";
654
- *
655
- * export default async function middleware(req: NextRequest) {
656
- * const session = await monoCloud.getSession(req);
657
- *
658
- * if (!session) {
659
- * return new NextResponse("User not signed in", { status: 401 });
660
- * }
661
- *
662
- * return NextResponse.next();
663
- * }
664
- *
665
- * export const config = {
666
- * matcher: [
667
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
668
- * ],
669
- * };
670
- * ```
671
- *
672
- * @example Middleware/Proxy (Custom Response)
673
- *
674
- * ```typescript
675
- * import { monoCloud } from "@/lib/monocloud";
676
- * import { NextRequest, NextResponse } from "next/server";
677
- *
678
- * export default async function middleware(req: NextRequest) {
679
- * const res = NextResponse.next();
680
- *
681
- * const session = await monoCloud.getSession(req, res);
682
- *
683
- * if (!session) {
684
- * return new NextResponse("User not signed in", { status: 401 });
685
- * }
686
- *
687
- * res.headers.set("x-auth-status", "active");
688
- *
689
- * return res;
690
- * }
691
- *
692
- * export const config = {
693
- * matcher: [
694
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
695
- * ],
696
- * };
697
- * ```
698
- *
699
- * @example API Handler
700
- *
701
- * ```typescript
702
- * import { NextRequest, NextResponse } from "next/server";
703
- * import { monoCloud } from "@/lib/monocloud";
704
- *
705
- * export const GET = async (req: NextRequest) => {
706
- * const session = await monoCloud.getSession(req);
707
- *
708
- * return NextResponse.json({ name: session?.user.name });
709
- * };
710
- * ```
711
- *
712
- * @example API Handler with NextResponse
713
- *
714
- * ```typescript
715
- * import { NextRequest, NextResponse } from "next/server";
716
- * import { monoCloud } from "@/lib/monocloud";
717
- *
718
- * export const GET = async (req: NextRequest) => {
719
- * const res = new NextResponse("YOUR CUSTOM RESPONSE");
720
- *
721
- * const session = await monoCloud.getSession(req, res);
722
- *
723
- * if (session?.user) {
724
- * res.cookies.set("something", "important");
725
- * }
726
- *
727
- * return res;
728
- * };
729
- * ```
201
+ * @see {@link getSession} for full docs and examples.
202
+ * @param req Incoming request used to read authentication cookies and headers to resolve the current user's session.
203
+ * @param res Optional response to update if session resolution requires refreshed authentication cookies or headers.
204
+ * @returns Returns the resolved session, or `undefined` if none exists.
730
205
  */
731
206
  getSession(req: NextRequest | Request, res?: NextResponse | Response): Promise<MonoCloudSession$1 | undefined>;
732
207
  /**
733
- * ## Pages Router (Node.js Runtime)
734
- *
735
- * Retrieves the session object for the currently authenticated user on the server.
736
- *
737
- * *Note: If the session cannot be resolved or an underlying error occurs, the promise rejects with an error.*
738
- *
739
- * @param req NextApiRequest
740
- * @param res NextApiResponse
741
- *
742
- * @returns `MonoCloudSession` if found, or `undefined`.
743
- *
744
- * @example API Handler
745
- *
746
- * ```typescript
747
- * import { monoCloud } from "@/lib/monocloud";
748
- * import type { NextApiRequest, NextApiResponse } from "next";
749
- *
750
- * type Data = {
751
- * name?: string;
752
- * };
753
- *
754
- * export default async function handler(
755
- * req: NextApiRequest,
756
- * res: NextApiResponse<Data>
757
- * ) {
758
- * const session = await monoCloud.getSession(req, res);
759
- *
760
- * res.status(200).json({ name: session?.user.name });
761
- * }
762
- * ```
763
- *
764
- * @example SSR Component
765
- *
766
- * ```typescript
767
- * import { monoCloud } from "@/monocloud";
768
- * import type {
769
- * GetServerSideProps,
770
- * GetServerSidePropsContext,
771
- * InferGetServerSidePropsType,
772
- * } from "next";
773
- *
774
- * type HomeProps = InferGetServerSidePropsType<typeof getServerSideProps>;
775
- *
776
- * export default function Home({ session }: HomeProps) {
777
- * return <pre>Session: {JSON.stringify(session, null, 2)}</pre>;
778
- * }
779
- *
780
- * export const getServerSideProps = (async (
781
- * context: GetServerSidePropsContext,
782
- * ) => {
783
- * const session = await monoCloud.getSession(
784
- * context.req,
785
- * context.res,
786
- * );
787
- *
788
- * return {
789
- * props: {
790
- * session: session ?? null,
791
- * },
792
- * };
793
- * }) satisfies GetServerSideProps;
794
- * ```
208
+ * @see {@link getSession} for full docs and examples.
209
+ * @param req Incoming Node.js request used to read authentication cookies and resolve the current user's session.
210
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
211
+ * @returns Returns the resolved session, or `undefined` if none exists.
795
212
  */
796
213
  getSession(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>): Promise<MonoCloudSession$1 | undefined>;
797
214
  /**
798
- * ## SSR Components, Actions, Middleware or API Handlers
799
- *
800
- * Retrieves the tokens for the currently signed-in user. Optionally refreshes/fetches new tokens.
801
- *
802
- * **Use Case:**
803
- * - App Router Server Components (RSC).
804
- * - Server Actions
805
- * - Route Handlers (App Router only).
806
- * - Middleware (App Router and Pages Router).
807
- *
808
- * @param options Configuration options for token retrieval.
809
- *
810
- * @returns
811
- *
812
- * @throws {@link MonoCloudValidationError} If session is not found
813
- *
814
- * @example Middleware/Proxy
815
- *
816
- * ```typescript
817
- * import { monoCloud } from "@/lib/monocloud";
818
- * import { NextResponse } from "next/server";
819
- *
820
- * export default async function middleware() {
821
- * const tokens = await monoCloud.getTokens();
822
- *
823
- * if (tokens.isExpired) {
824
- * return new NextResponse("Tokens expired", { status: 401 });
825
- * }
826
- *
827
- * return NextResponse.next();
828
- * }
829
- *
830
- * export const config = {
831
- * matcher: [
832
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
833
- * ],
834
- * };
835
- * ```
836
- *
837
- * @example App Router API Handler
838
- *
839
- * ```typescript
840
- * import { NextResponse } from "next/server";
841
- * import { monoCloud } from "@/lib/monocloud";
842
- *
843
- * export const GET = async () => {
844
- * const tokens = await monoCloud.getTokens();
845
- *
846
- * return NextResponse.json({ expired: tokens.isExpired });
847
- * };
848
- * ```
849
- *
850
- * @example React Server Components
851
- *
852
- * ```tsx
853
- * import { monoCloud } from "@/lib/monocloud";
854
- *
855
- * export default async function Home() {
856
- * const tokens = await monoCloud.getTokens();
857
- *
858
- * return <div>Expired: {tokens.isExpired.toString()}</div>;
859
- * }
860
- * ```
861
- *
862
- * @example Server Action
863
- *
864
- * ```typescript
865
- * "use server";
866
- *
867
- * import { monoCloud } from "@/lib/monocloud";
868
- *
869
- * export async function getExpiredAction() {
870
- * const tokens = await monoCloud.getTokens();
871
- *
872
- * return { expired: tokens.isExpired };
873
- * }
874
- * ```
875
- *
876
- * @example Refresh Default Token
877
- *
878
- * The default token is an access token with scopes set through `MONOCLOUD_AUTH_SCOPES` or
879
- * `options.defaultAuthParams.scopes`, and resources set through `MONOCLOUD_AUTH_RESOURCE` or
880
- * `options.defaultAuthParams.resource`. This token is refreshed when calling getTokens without resource and scopes parameters.
881
- *
882
- * ```typescript
883
- * import { NextResponse } from "next/server";
884
- * import { monoCloud } from "@/lib/monocloud";
885
- *
886
- * export const GET = async () => {
887
- * // Although the token refreshes automatically upon expiration, we are manually refreshing it here.
888
- * const tokens = await monoCloud.getTokens({ forceRefresh: true });
889
- *
890
- * return NextResponse.json({ accessToken: tokens?.accessToken });
891
- * };
892
- * ```
893
- *
894
- * @example Request new access token for resource(s)
895
- *
896
- * **Note: Ensure that the resources and scopes are included in the initial authorization flow**
897
- *
898
- * The following example shows how to request a new token scoped to two non-exclusive resources.
899
- *
900
- * ```typescript
901
- * import { NextResponse } from "next/server";
902
- * import { monoCloud } from "@/lib/monocloud";
903
- *
904
- * export const GET = async () => {
905
- * const tokens = await monoCloud.getTokens({
906
- * resource: "https://first.example.com https://second.example.com",
907
- * scopes: "read:first read:second shared",
908
- * });
909
- *
910
- * return NextResponse.json({ accessToken: tokens?.accessToken });
911
- * };
912
- * ```
913
- *
914
- * @example Request an exclusive token
915
- *
916
- * **Note: Ensure that the resources and scopes are included in the initial authorization flow**
917
- *
918
- * ```typescript
919
- * import { NextResponse } from "next/server";
920
- * import { monoCloud } from "@/lib/monocloud";
921
- *
922
- * export const GET = async () => {
923
- * const tokens = await monoCloud.getTokens({
924
- * resource: "https://exclusive.example.com",
925
- * scopes: "read:exclusive shared",
926
- * });
927
- *
928
- * return NextResponse.json({ accessToken: tokens?.accessToken });
929
- * };
930
- * ```
215
+ * @see {@link getTokens} for full docs and examples.
216
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
217
+ * @returns The current user's tokens, refreshed if necessary.
218
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
931
219
  */
932
220
  getTokens(options?: GetTokensOptions$1): Promise<MonoCloudTokens$1>;
933
221
  /**
934
- * ## Middleware/Proxy or Route Handlers
935
- *
936
- * Retrieves the tokens for the currently signed-in user. Optionally refreshes/fetches new tokens.
937
- *
938
- * **Use Case:**
939
- * - Middleware (for both App and Pages Router).
940
- * - App Router Route Handlers (API routes).
941
- * - Edge functions.
942
- *
943
- * @param req NextRequest
944
- * @param options Configuration options for token retrieval.
945
- *
946
- * @returns
947
- *
948
- * @throws {@link MonoCloudValidationError} If session is not found
949
- *
950
- * @example Middleware/Proxy
951
- *
952
- * ```typescript
953
- * import { monoCloud } from "@/lib/monocloud";
954
- * import { NextRequest, NextResponse } from "next/server";
955
- *
956
- * export default async function middleware(req: NextRequest) {
957
- * const tokens = await monoCloud.getTokens(req);
958
- *
959
- * if (tokens.isExpired) {
960
- * return new NextResponse("Tokens expired", { status: 401 });
961
- * }
962
- *
963
- * return NextResponse.next();
964
- * }
965
- *
966
- * export const config = {
967
- * matcher: [
968
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
969
- * ],
970
- * };
971
- * ```
972
- *
973
- * @example App Router API Handler
974
- *
975
- * ```typescript
976
- * import { NextRequest, NextResponse } from "next/server";
977
- * import { monoCloud } from "@/lib/monocloud";
978
- *
979
- * export const GET = async (req: NextRequest) => {
980
- * const tokens = await monoCloud.getTokens(req);
981
- *
982
- * return NextResponse.json({ expired: tokens?.isExpired });
983
- * };
984
- * ```
985
- *
986
- * @example Refresh Default Token
987
- *
988
- * The default token is an access token with scopes set through `MONOCLOUD_AUTH_SCOPES` or
989
- * `options.defaultAuthParams.scopes`, and resources set through `MONOCLOUD_AUTH_RESOURCE` or
990
- * `options.defaultAuthParams.resource`. This token is refreshed when calling getTokens without parameters.
991
- *
992
- * ```typescript
993
- * import { NextRequest, NextResponse } from "next/server";
994
- * import { monoCloud } from "@/lib/monocloud";
995
- *
996
- * export const GET = async (req: NextRequest) => {
997
- * // Although the token refreshes automatically upon expiration, we are manually refreshing it here.
998
- * const tokens = await monoCloud.getTokens(req, { forceRefresh: true });
999
- *
1000
- * return NextResponse.json({ accessToken: tokens?.accessToken });
1001
- * };
1002
- * ```
1003
- *
1004
- * @example Request new access token for resource(s)
1005
- *
1006
- * **Note: Ensure that the resources and scopes are included in the initial authorization flow**
1007
- *
1008
- * The following example shows how to request a new token scoped to two non-exclusive resources.
1009
- *
1010
- * ```typescript
1011
- * import { NextRequest, NextResponse } from "next/server";
1012
- * import { monoCloud } from "@/lib/monocloud";
1013
- *
1014
- * export const GET = async (req: NextRequest) => {
1015
- * const tokens = await monoCloud.getTokens(req, {
1016
- * resource: "https://first.example.com https://second.example.com",
1017
- * scopes: "read:first read:second shared",
1018
- * });
1019
- *
1020
- * return NextResponse.json({ accessToken: tokens?.accessToken });
1021
- * };
1022
- * ```
1023
- *
1024
- * @example Request an exclusive token
1025
- *
1026
- * **Note: Ensure that the resources and scopes are included in the initial authorization flow**
1027
- *
1028
- * ```typescript
1029
- * import { NextRequest, NextResponse } from "next/server";
1030
- * import { monoCloud } from "@/lib/monocloud";
1031
- *
1032
- * export const GET = async (req: NextRequest) => {
1033
- * const tokens = await monoCloud.getTokens(req, {
1034
- * resource: "https://exclusive.example.com",
1035
- * scopes: "read:exclusive shared",
1036
- * });
1037
- *
1038
- * return NextResponse.json({ accessToken: tokens?.accessToken });
1039
- * };
1040
- * ```
222
+ * @see {@link getTokens} for full docs and examples.
223
+ * @param req Incoming request used to resolve authentication from cookies and headers.
224
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
225
+ * @returns The current user's tokens, refreshed if necessary.
226
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
1041
227
  */
1042
228
  getTokens(req: NextRequest | Request, options?: GetTokensOptions$1): Promise<MonoCloudTokens$1>;
1043
229
  /**
1044
- * ## Middleware/Proxy or Route Handlers (Custom Response)
1045
- *
1046
- * Retrieves the tokens for the currently signed-in user. Optionally refreshes/fetches new tokens and updates the provided response object.
1047
- *
1048
- * **Use Case:**
1049
- * - Middleware (when modifying the response).
1050
- * - App Router Route Handlers (when a NextResponse is already initialized).
1051
- *
1052
- * @param req NextRequest
1053
- * @param res An optional `NextResponse` instance. Pass this if you have already initialized a response and want token updates (e.g., refreshing) to be applied to it.
1054
- * @param options Configuration options for token retrieval.
1055
- *
1056
- * @returns
1057
- *
1058
- * @throws {@link MonoCloudValidationError} If session is not found
1059
- *
1060
- * @example Middleware/Proxy
1061
- *
1062
- *```typescript
1063
- * import { monoCloud } from "@/lib/monocloud";
1064
- * import { NextRequest, NextResponse } from "next/server";
1065
- *
1066
- * export default async function middleware(req: NextRequest) {
1067
- * const res = NextResponse.next();
1068
- *
1069
- * const tokens = await monoCloud.getTokens(req, res);
1070
- *
1071
- * res.headers.set("x-tokens-expired", tokens.isExpired.toString());
1072
- *
1073
- * return res;
1074
- * }
1075
- *
1076
- * export const config = {
1077
- * matcher: [
1078
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
1079
- * ],
1080
- * };
1081
- * ```
1082
- *
1083
- * @example API Handler with NextResponse
1084
- *
1085
- * ```typescript
1086
- * import { NextRequest, NextResponse } from "next/server";
1087
- * import { monoCloud } from "@/lib/monocloud";
1088
- *
1089
- * export const GET = async (req: NextRequest) => {
1090
- * const res = new NextResponse("Custom Body");
1091
- *
1092
- * const tokens = await monoCloud.getTokens(req, res);
1093
- *
1094
- * if (!tokens.isExpired) {
1095
- * res.headers.set("x-auth-status", "active");
1096
- * }
1097
- *
1098
- * return res;
1099
- * };
1100
- * ```
1101
- *
1102
- * @example Refresh Default Token
1103
- *
1104
- * The default token is an access token with scopes set through `MONOCLOUD_AUTH_SCOPES` or
1105
- * `options.defaultAuthParams.scopes`, and resources set through `MONOCLOUD_AUTH_RESOURCE` or
1106
- * `options.defaultAuthParams.resource`. This token is refreshed when calling getTokens without parameters.
1107
- *
1108
- * ```typescript
1109
- * import { NextRequest, NextResponse } from "next/server";
1110
- * import { monoCloud } from "@/lib/monocloud";
1111
- *
1112
- * export const GET = async (req: NextRequest) => {
1113
- * const res = new NextResponse("Custom Body");
1114
- *
1115
- * // Although the token refreshes automatically upon expiration, we are manually refreshing it here.
1116
- * const tokens = await monoCloud.getTokens(req, res, { forceRefresh: true });
1117
- *
1118
- * if (!tokens.isExpired) {
1119
- * res.headers.set("x-auth-status", "active");
1120
- * }
1121
- *
1122
- * return res;
1123
- * };
1124
- * ```
1125
- *
1126
- * @example Request new access token for resource(s)
1127
- *
1128
- * **Note: Ensure that the resources and scopes are included in the initial authorization flow**
1129
- *
1130
- * The following example shows how to request a new token scoped to two non-exclusive resources.
1131
- *
1132
- * ```typescript
1133
- * import { NextRequest, NextResponse } from "next/server";
1134
- * import { monoCloud } from "@/lib/monocloud";
1135
- *
1136
- * export const GET = async (req: NextRequest) => {
1137
- * const res = new NextResponse("Custom Body");
1138
- *
1139
- * const tokens = await monoCloud.getTokens(req, res, {
1140
- * resource: "https://first.example.com https://second.example.com",
1141
- * scopes: "read:first read:second shared",
1142
- * });
1143
- *
1144
- * if (!tokens.isExpired) {
1145
- * res.headers.set("x-auth-status", "active");
1146
- * }
1147
- *
1148
- * return res;
1149
- * };
1150
- * ```
1151
- *
1152
- * @example Request an exclusive token
1153
- *
1154
- * **Note: Ensure that the resources and scopes are included in the initial authorization flow**
1155
- *
1156
- * ```typescript
1157
- * import { NextRequest, NextResponse } from "next/server";
1158
- * import { monoCloud } from "@/lib/monocloud";
1159
- *
1160
- * export const GET = async (req: NextRequest) => {
1161
- * const res = new NextResponse("Custom Body");
1162
- *
1163
- * const tokens = await monoCloud.getTokens(req, res, {
1164
- * resource: "https://exclusive.example.com",
1165
- * scopes: "read:exclusive shared",
1166
- * });
1167
- *
1168
- * if (!tokens.isExpired) {
1169
- * res.headers.set("x-auth-status", "active");
1170
- * }
1171
- *
1172
- * return res;
1173
- * };
1174
- * ```
230
+ * @see {@link getTokens} for full docs and examples.
231
+ * @param req Incoming request used to resolve authentication from cookies and headers.
232
+ * @param res Existing response to update with refreshed authentication cookies or headers.
233
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
234
+ * @returns The current user's tokens, refreshed if necessary.
235
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
1175
236
  */
1176
237
  getTokens(req: NextRequest | Request, res: NextResponse | Response, options?: GetTokensOptions$1): Promise<MonoCloudTokens$1>;
1177
238
  /**
1178
- * ## Pages Router (Node.js Runtime)
1179
- *
1180
- * Retrieves the tokens for the currently signed-in user. Optionally refreshes/fetches new tokens.
1181
- *
1182
- * @param req The `NextApiRequest` or `IncomingMessage`.
1183
- * @param res The `NextApiResponse` or `ServerResponse`.
1184
- * @param options Configuration options for token retrieval.
1185
- *
1186
- * @returns
1187
- *
1188
- * @throws {@link MonoCloudValidationError} If session is not found
1189
- *
1190
- * @example API Route
1191
- *
1192
- * ```typescript
1193
- * import { monoCloud } from "@/lib/monocloud";
1194
- * import type { NextApiRequest, NextApiResponse } from "next";
1195
- *
1196
- * export default async function handler(
1197
- * req: NextApiRequest,
1198
- * res: NextApiResponse
1199
- * ) {
1200
- * const tokens = await monoCloud.getTokens(req, res);
1201
- *
1202
- * res.status(200).json({ accessToken: tokens?.accessToken });
1203
- * }
1204
- * ```
1205
- *
1206
- * @example SSR Component
1207
- *
1208
- * ```typescript
1209
- * import { monoCloud } from "@/lib/monocloud";
1210
- * import type { GetServerSideProps, InferGetServerSidePropsType } from "next";
1211
- *
1212
- * type HomeProps = InferGetServerSidePropsType<typeof getServerSideProps>;
1213
- *
1214
- * export default function Home({ tokens }: HomeProps) {
1215
- * return <pre>Tokens: {JSON.stringify(tokens, null, 2)}</pre>;
1216
- * }
1217
- *
1218
- * export const getServerSideProps: GetServerSideProps = async (context) => {
1219
- * const tokens = await monoCloud.getTokens(context.req, context.res);
1220
- *
1221
- * return {
1222
- * props: {
1223
- * tokens: tokens ?? null,
1224
- * },
1225
- * };
1226
- * };
1227
- * ```
1228
- *
1229
- * @example Refresh Default Token
1230
- *
1231
- * The default token is an access token with scopes set through `MONOCLOUD_AUTH_SCOPES` or
1232
- * `options.defaultAuthParams.scopes`, and resources set through `MONOCLOUD_AUTH_RESOURCE` or
1233
- * `options.defaultAuthParams.resource`. This token is refreshed when calling getTokens without parameters.
1234
- *
1235
- * ```typescript
1236
- * import { monoCloud } from "@/lib/monocloud";
1237
- * import type { NextApiRequest, NextApiResponse } from "next";
1238
- *
1239
- * export default async function handler(
1240
- * req: NextApiRequest,
1241
- * res: NextApiResponse
1242
- * ) {
1243
- * // Although the token refreshes automatically upon expiration, we are manually refreshing it here.
1244
- * const tokens = await monoCloud.getTokens(req, res, { forceRefresh: true });
1245
- *
1246
- * res.status(200).json({ accessToken: tokens?.accessToken });
1247
- * }
1248
- * ```
1249
- *
1250
- * @example Request new access token for resource(s)
1251
- *
1252
- * **Note: Ensure that the resources and scopes are included in the initial authorization flow**
1253
- *
1254
- * The following example shows how to request a new token scoped to two non-exclusive resources.
1255
- *
1256
- * ```typescript
1257
- * import { monoCloud } from "@/lib/monocloud";
1258
- * import type { NextApiRequest, NextApiResponse } from "next";
1259
- *
1260
- * export default async function handler(
1261
- * req: NextApiRequest,
1262
- * res: NextApiResponse
1263
- * ) {
1264
- * const tokens = await monoCloud.getTokens(req, res, {
1265
- * resource: "https://first.example.com https://second.example.com",
1266
- * scopes: "read:first read:second shared",
1267
- * });
1268
- *
1269
- * res.status(200).json({ accessToken: tokens?.accessToken });
1270
- * }
1271
- * ```
1272
- *
1273
- * @example Request an exclusive token
1274
- *
1275
- * **Note: Ensure that the resources and scopes are included in the initial authorization flow**
1276
- *
1277
- * ```typescript
1278
- * import { monoCloud } from "@/lib/monocloud";
1279
- * import type { NextApiRequest, NextApiResponse } from "next";
1280
- *
1281
- * export default async function handler(
1282
- * req: NextApiRequest,
1283
- * res: NextApiResponse
1284
- * ) {
1285
- * const tokens = await monoCloud.getTokens(req, res, {
1286
- * resource: "https://exclusive.example.com",
1287
- * scopes: "read:exclusive shared",
1288
- * });
1289
- *
1290
- * res.status(200).json({ accessToken: tokens?.accessToken });
1291
- * }
1292
- * ```
239
+ * @see {@link getTokens} for full docs and examples.
240
+ * @param req Incoming Node.js request used to resolve authentication from cookies.
241
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
242
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
243
+ * @returns The current user's tokens, refreshed if necessary.
244
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
1293
245
  */
1294
246
  getTokens(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>, options?: GetTokensOptions$1): Promise<MonoCloudTokens$1>;
1295
247
  /**
1296
- * ## SSR Components, Actions, Middleware or API Handlers
1297
- *
1298
- * Checks if the current user is authenticated.
1299
- *
1300
- * **Use Case:**
1301
- * - App Router Server Components (RSC).
1302
- * - Server Actions
1303
- * - Route Handlers (App Router only).
1304
- * - Middleware (App Router and Pages Router).
1305
- *
1306
- * @returns `true` if the user is authenticated, otherwise `false`.
1307
- *
1308
- * @example Middleware/Proxy
1309
- *
1310
- * ```typescript
1311
- * import { monoCloud } from "@/lib/monocloud";
1312
- * import { NextResponse } from "next/server";
1313
- *
1314
- * export default async function middleware() {
1315
- * const authenticated = await monoCloud.isAuthenticated();
1316
- *
1317
- * if (!authenticated) {
1318
- * return new NextResponse("User not signed in", { status: 401 });
1319
- * }
1320
- *
1321
- * return NextResponse.next();
1322
- * }
1323
- *
1324
- * export const config = {
1325
- * matcher: [
1326
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
1327
- * ],
1328
- * };
1329
- * ```
1330
- *
1331
- * @example App Router API Handler
1332
- *
1333
- * ```typescript
1334
- * import { NextResponse } from "next/server";
1335
- * import { monoCloud } from "@/lib/monocloud";
1336
- *
1337
- * export const GET = async () => {
1338
- * const authenticated = await monoCloud.isAuthenticated();
1339
- *
1340
- * return NextResponse.json({ authenticated });
1341
- * };
1342
- * ```
1343
- *
1344
- * @example React Server Components
1345
- *
1346
- * ```tsx
1347
- * import { monoCloud } from "@/lib/monocloud";
1348
- *
1349
- * export default async function Home() {
1350
- * const authenticated = await monoCloud.isAuthenticated();
1351
- *
1352
- * return <div>Authenticated: {authenticated.toString()}</div>;
1353
- * }
1354
- * ```
1355
- *
1356
- * @example Server Action
1357
- *
1358
- * ```typescript
1359
- * "use server";
1360
- *
1361
- * import { monoCloud } from "@/lib/monocloud";
1362
- *
1363
- * export async function checkAuthAction() {
1364
- * const authenticated = await monoCloud.isAuthenticated();
1365
- *
1366
- * return { authenticated };
1367
- * }
1368
- * ```
248
+ * @see {@link isAuthenticated} for full docs and examples.
249
+ * @returns Returns `true` if a valid session exists; otherwise `false`.
1369
250
  */
1370
251
  isAuthenticated(): Promise<boolean>;
1371
252
  /**
1372
- * ## Middleware/Proxy or Route Handlers
1373
- *
1374
- * Checks if the current user is authenticated.
1375
- *
1376
- * **Use Case:**
1377
- * - Middleware (for both App and Pages Router).
1378
- * - App Router Route Handlers (API routes).
1379
- * - Edge functions.
1380
- *
1381
- * @param req NextRequest
1382
- * @param res An optional `NextResponse` instance. Pass this if you have already initialized a response; otherwise, omit this parameter.
1383
- *
1384
- * @returns `true` if the user is authenticated, otherwise `false`.
1385
- *
1386
- * @example Middleware/Proxy
1387
- *
1388
- * ```typescript
1389
- * import { monoCloud } from "@/lib/monocloud";
1390
- * import { NextRequest, NextResponse } from "next/server";
1391
- *
1392
- * export default async function middleware(req: NextRequest) {
1393
- * const authenticated = await monoCloud.isAuthenticated(req);
1394
- *
1395
- * if (!authenticated) {
1396
- * return new NextResponse("User not signed in", { status: 401 });
1397
- * }
1398
- *
1399
- * return NextResponse.next();
1400
- * }
1401
- *
1402
- * export const config = {
1403
- * matcher: [
1404
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
1405
- * ],
1406
- * };
1407
- * ```
1408
- *
1409
- * @example Middleware/Proxy (Custom Response)
1410
- *
1411
- * ```typescript
1412
- * import { monoCloud } from "@/lib/monocloud";
1413
- * import { NextRequest, NextResponse } from "next/server";
1414
- *
1415
- * export default async function middleware(req: NextRequest) {
1416
- * const res = NextResponse.next();
1417
- *
1418
- * const authenticated = await monoCloud.isAuthenticated(req, res);
1419
- *
1420
- * if (!authenticated) {
1421
- * return new NextResponse("User not signed in", { status: 401 });
1422
- * }
1423
- *
1424
- * res.headers.set("x-authenticated", "true");
1425
- *
1426
- * return res;
1427
- * }
1428
- *
1429
- * export const config = {
1430
- * matcher: [
1431
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
1432
- * ],
1433
- * };
1434
- * ```
1435
- *
1436
- * @example API Handler
1437
- *
1438
- * ```typescript
1439
- * import { NextRequest, NextResponse } from "next/server";
1440
- * import { monoCloud } from "@/lib/monocloud";
1441
- *
1442
- * export const GET = async (req: NextRequest) => {
1443
- * const authenticated = await monoCloud.isAuthenticated(req);
1444
- *
1445
- * return NextResponse.json({ authenticated });
1446
- * };
1447
- * ```
1448
- *
1449
- * @example API Handler with NextResponse
1450
- *
1451
- * ```typescript
1452
- * import { NextRequest, NextResponse } from "next/server";
1453
- * import { monoCloud } from "@/lib/monocloud";
1454
- *
1455
- * export const GET = async (req: NextRequest) => {
1456
- * const res = new NextResponse("YOUR CUSTOM RESPONSE");
1457
- *
1458
- * const authenticated = await monoCloud.isAuthenticated(req, res);
1459
- *
1460
- * if (authenticated) {
1461
- * res.cookies.set("something", "important");
1462
- * }
1463
- *
1464
- * return res;
1465
- * };
1466
- * ```
253
+ * @see {@link isAuthenticated} for full docs and examples.
254
+ * @param req Incoming request used to resolve authentication from cookies and headers.
255
+ * @param res Optional response to update if refreshed authentication cookies or headers are required.
256
+ * @returns Returns `true` if a valid session exists; otherwise `false`.
1467
257
  */
1468
258
  isAuthenticated(req: NextRequest | Request, res?: NextResponse | Response): Promise<boolean>;
1469
259
  /**
1470
- * ## Pages Router (Node.js Runtime)
1471
- *
1472
- * Checks if the current user is authenticated.
1473
- *
1474
- * @param req NextApiRequest
1475
- * @param res NextApiResponse
1476
- *
1477
- * @returns `true` if the user is authenticated, otherwise `false`.
1478
- *
1479
- * @example API Handler
1480
- *
1481
- * ```typescript
1482
- * import { monoCloud } from "@/lib/monocloud";
1483
- * import type { NextApiRequest, NextApiResponse } from "next";
1484
- *
1485
- * type Data = {
1486
- * authenticated: boolean;
1487
- * };
1488
- *
1489
- * export default async function handler(
1490
- * req: NextApiRequest,
1491
- * res: NextApiResponse<Data>
1492
- * ) {
1493
- * const authenticated = await monoCloud.isAuthenticated(req, res);
1494
- *
1495
- * res.status(200).json({ authenticated });
1496
- * }
1497
- * ```
1498
- *
1499
- * @example SSR Component
1500
- *
1501
- * ```typescript
1502
- * import { monoCloud } from "@/lib/monocloud";
1503
- * import type { GetServerSideProps, InferGetServerSidePropsType } from "next";
1504
- *
1505
- * type HomeProps = InferGetServerSidePropsType<typeof getServerSideProps>;
1506
- *
1507
- * export default function Home({ authenticated }: HomeProps) {
1508
- * return <pre>User is {authenticated ? "logged in" : "guest"}</pre>;
1509
- * }
1510
- *
1511
- * export const getServerSideProps: GetServerSideProps = async (context) => {
1512
- * const authenticated = await monoCloud.isAuthenticated(
1513
- * context.req,
1514
- * context.res
1515
- * );
1516
- *
1517
- * return {
1518
- * props: {
1519
- * authenticated,
1520
- * },
1521
- * };
1522
- * };
1523
- * ```
260
+ * @see {@link isAuthenticated} for full docs and examples.
261
+ * @param req Incoming Node.js request used to resolve authentication from cookies.
262
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
263
+ * @returns Returns `true` if a valid session exists; otherwise `false`.
1524
264
  */
1525
265
  isAuthenticated(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>): Promise<boolean>;
1526
266
  /**
1527
- * Redirects the user to the sign-in flow if they are not authenticated.
1528
- *
1529
- * **This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).**
1530
- *
1531
- * @param options Options to customize the sign-in.
1532
- *
1533
- * @returns
1534
- *
1535
- * @example React Server Component
1536
- *
1537
- * ```tsx
1538
- * import { monoCloud } from "@/lib/monocloud";
1539
- *
1540
- * export default async function Home() {
1541
- * await monoCloud.protect();
1542
- *
1543
- * return <>You are signed in.</>;
1544
- * }
1545
- * ```
1546
- *
1547
- * @example API Handler
1548
- *
1549
- * ```typescript
1550
- * import { NextResponse } from "next/server";
1551
- * import { monoCloud } from "@/lib/monocloud";
1552
- *
1553
- * export const GET = async () => {
1554
- * await monoCloud.protect();
1555
- *
1556
- * return NextResponse.json({ secret: "ssshhhh!!!" });
1557
- * };
1558
- * ```
1559
- *
1560
- * @example Server Action
1561
- *
1562
- * ```typescript
1563
- * "use server";
1564
- *
1565
- * import { monoCloud } from "@/lib/monocloud";
1566
- *
1567
- * export async function getMessage() {
1568
- * await monoCloud.protect();
1569
- *
1570
- * return { secret: "sssshhhhh!!!" };
1571
- * }
1572
- * ```
267
+ * @see {@link protect} for full docs and examples.
268
+ * @param options Optional configuration for redirect behavior (for example, return URL or sign-in parameters).
269
+ * @returns Resolves if the user is authenticated; otherwise triggers a redirect.
1573
270
  */
1574
271
  protect(options?: ProtectOptions): Promise<void>;
1575
272
  /**
1576
- * ## SSR Components, Actions, Middleware or API Handlers
1577
- *
1578
- * Checks if the currently authenticated user is a member of any of the specified groups.
1579
- *
1580
- * **Use Case:**
1581
- * - App Router Server Components (RSC).
1582
- * - Server Actions
1583
- * - Route Handlers (App Router only).
1584
- * - Middleware (App Router and Pages Router).
1585
- *
1586
- * @param groups A list of group names or IDs to check against the user's group memberships.
1587
- * @param options Configuration options.
1588
- *
1589
- * @returns
1590
- *
1591
- * @example Middleware/Proxy
1592
- *
1593
- * ```typescript
1594
- * import { monoCloud } from "@/lib/monocloud";
1595
- * import { NextResponse } from "next/server";
1596
- *
1597
- * export default async function middleware() {
1598
- * const isAdmin = await monoCloud.isUserInGroup(["admin"]);
1599
- *
1600
- * if (!isAdmin) {
1601
- * return new NextResponse("User is not admin", { status: 403 });
1602
- * }
1603
- *
1604
- * return NextResponse.next();
1605
- * }
1606
- *
1607
- * export const config = {
1608
- * matcher: [
1609
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
1610
- * ],
1611
- * };
1612
- * ```
1613
- *
1614
- * @example App Router API Handler
1615
- *
1616
- * ```typescript
1617
- * import { NextResponse } from "next/server";
1618
- * import { monoCloud } from "@/lib/monocloud";
1619
- *
1620
- * export const GET = async () => {
1621
- * const allowed = await monoCloud.isUserInGroup(["admin", "editor"]);
1622
- *
1623
- * if (!allowed) {
1624
- * return new NextResponse("Forbidden", { status: 403 });
1625
- * }
1626
- *
1627
- * return NextResponse.json({ status: "success" });
1628
- * };
1629
- * ```
1630
- *
1631
- * @example React Server Components
1632
- *
1633
- * ```tsx
1634
- * import { monoCloud } from "@/lib/monocloud";
1635
- *
1636
- * export default async function AdminPanel() {
1637
- * const isAdmin = await monoCloud.isUserInGroup(["admin"]);
1638
- *
1639
- * if (!isAdmin) {
1640
- * return <div>Access Denied</div>;
1641
- * }
1642
- *
1643
- * return <div>Admin Control Panel</div>;
1644
- * }
1645
- * ```
1646
- *
1647
- * @example Server Action
1648
- *
1649
- * ```typescript
1650
- * "use server";
1651
- *
1652
- * import { monoCloud } from "@/lib/monocloud";
1653
- *
1654
- * export async function deletePostAction() {
1655
- * const canDelete = await monoCloud.isUserInGroup(["admin", "editor"]);
1656
- *
1657
- * if (!canDelete) {
1658
- * return { success: false };
1659
- * }
1660
- *
1661
- * return { success: true };
1662
- * }
1663
- * ```
273
+ * @see {@link isUserInGroup} for full docs and examples.
274
+ * @param groups Group IDs or names to check against the user's group memberships.
275
+ * @param options Optional configuration controlling how group membership is evaluated.
276
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
1664
277
  */
1665
278
  isUserInGroup(groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
1666
279
  /**
1667
- * ## Middleware/Proxy or Route Handlers
1668
- *
1669
- * Checks if the currently authenticated user is a member of any of the specified groups.
1670
- *
1671
- * **Use Case:**
1672
- * - Middleware (for both App and Pages Router).
1673
- * - App Router Route Handlers (API routes).
1674
- * - Edge functions.
1675
- *
1676
- * @param req NextRequest
1677
- * @param groups A list of group names or IDs to check against the user's group memberships.
1678
- * @param options Configuration options.
1679
- *
1680
- * @returns
1681
- *
1682
- * @example Middleware/Proxy
1683
- *
1684
- * ```typescript
1685
- * import { monoCloud } from "@/lib/monocloud";
1686
- * import { NextRequest, NextResponse } from "next/server";
1687
- *
1688
- * export default async function middleware(req: NextRequest) {
1689
- * const isAdmin = await monoCloud.isUserInGroup(req, ["admin"]);
1690
- *
1691
- * if (!isAdmin) {
1692
- * return new NextResponse("User is not admin", { status: 403 });
1693
- * }
1694
- *
1695
- * return NextResponse.next();
1696
- * }
1697
- *
1698
- * export const config = {
1699
- * matcher: [
1700
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
1701
- * ],
1702
- * };
1703
- * ```
1704
- *
1705
- * @example App Router API Handler
1706
- *
1707
- * ```typescript
1708
- * import { NextRequest, NextResponse } from "next/server";
1709
- * import { monoCloud } from "@/lib/monocloud";
1710
- *
1711
- * export const GET = async (req: NextRequest) => {
1712
- * const isMember = await monoCloud.isUserInGroup(req, ["admin", "editor"]);
1713
- *
1714
- * return NextResponse.json({ isMember });
1715
- * };
1716
- * ```
280
+ * @see {@link isUserInGroup} for full docs and examples.
281
+ * @param req Incoming request used to resolve authentication from cookies and headers.
282
+ * @param groups Group IDs or names to check against the user's group memberships.
283
+ * @param options Optional configuration controlling how group membership is evaluated.
284
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
1717
285
  */
1718
286
  isUserInGroup(req: NextRequest | Request, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
1719
287
  /**
1720
- * ## Middleware/Proxy or Route Handlers (Custom Response)
1721
- *
1722
- * Checks if the currently authenticated user is a member of any of the specified groups.
1723
- *
1724
- * **Use Case:**
1725
- * - Middleware (when modifying the response).
1726
- * - App Router Route Handlers (when a NextResponse is already initialized).
1727
- *
1728
- * @param req NextRequest
1729
- * @param res An optional `NextResponse` instance. Pass this if you have already initialized a response and want token updates to be applied to it.
1730
- * @param groups A list of group names or IDs to check against the user's group memberships.
1731
- * @param options Configuration options.
1732
- *
1733
- * @returns
1734
- *
1735
- * @example Middleware/Proxy
1736
- *
1737
- * ```typescript
1738
- * import { monoCloud } from "@/lib/monocloud";
1739
- * import { NextRequest, NextResponse } from "next/server";
1740
- *
1741
- * export default async function middleware(req: NextRequest) {
1742
- * const res = NextResponse.next();
1743
- *
1744
- * const isAdmin = await monoCloud.isUserInGroup(req, res, ["admin"]);
1745
- *
1746
- * if (!isAdmin) {
1747
- * return new NextResponse("User is not admin", { status: 403 });
1748
- * }
1749
- *
1750
- * res.headers.set("x-user", "admin");
1751
- *
1752
- * return res;
1753
- * }
1754
- *
1755
- * export const config = {
1756
- * matcher: [
1757
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
1758
- * ],
1759
- * };
1760
- * ```
1761
- *
1762
- * @example API Handler with NextResponse
1763
- *
1764
- * ```typescript
1765
- * import { NextRequest, NextResponse } from "next/server";
1766
- * import { monoCloud } from "@/lib/monocloud";
1767
- *
1768
- * export const GET = async (req: NextRequest) => {
1769
- * const res = new NextResponse("Restricted Content");
1770
- *
1771
- * const allowed = await monoCloud.isUserInGroup(req, res, ["admin"]);
1772
- *
1773
- * if (!allowed) {
1774
- * return new NextResponse("Not Allowed", res);
1775
- * }
1776
- *
1777
- * return res;
1778
- * };
1779
- * ```
288
+ * @see {@link isUserInGroup} for full docs and examples.
289
+ * @param req Incoming request used to resolve authentication from cookies and headers.
290
+ * @param res Existing response to update with refreshed authentication cookies or headers when required.
291
+ * @param groups Group IDs or names to check against the user's group memberships.
292
+ * @param options Optional configuration controlling how group membership is evaluated.
293
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
1780
294
  */
1781
295
  isUserInGroup(req: NextRequest | Request, res: NextResponse | Response, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
1782
296
  /**
1783
- * ## Pages Router (Node.js Runtime)
1784
- *
1785
- * Checks if the currently authenticated user is a member of any of the specified groups.
1786
- *
1787
- * @param req The `NextApiRequest` or `IncomingMessage`.
1788
- * @param res The `NextApiResponse` or `ServerResponse`.
1789
- * @param groups A list of group names or IDs to check against the user's group memberships.
1790
- * @param options Configuration options.
1791
- *
1792
- * @returns
1793
- *
1794
- * @example API Route
1795
- *
1796
- * ```typescript
1797
- * import { monoCloud } from "@/lib/monocloud";
1798
- * import type { NextApiRequest, NextApiResponse } from "next";
1799
- *
1800
- * export default async function handler(
1801
- * req: NextApiRequest,
1802
- * res: NextApiResponse
1803
- * ) {
1804
- * const isAdmin = await monoCloud.isUserInGroup(req, res, ["admin"]);
1805
- *
1806
- * if (!isAdmin) {
1807
- * return res.status(403).json({ error: "Forbidden" });
1808
- * }
1809
- *
1810
- * res.status(200).json({ message: "Welcome Admin" });
1811
- * }
1812
- * ```
1813
- *
1814
- * @example SSR Component
1815
- *
1816
- * ```typescript
1817
- * import { monoCloud } from "@/lib/monocloud";
1818
- * import type { GetServerSideProps, InferGetServerSidePropsType } from "next";
1819
- *
1820
- * type HomeProps = InferGetServerSidePropsType<typeof getServerSideProps>;
1821
- *
1822
- * export default function Home({ isAdmin }: HomeProps) {
1823
- * return <div>User is admin: {isAdmin.toString()}</div>;
1824
- * }
1825
- *
1826
- * export const getServerSideProps: GetServerSideProps = async (context) => {
1827
- * const isAdmin = await monoCloud.isUserInGroup(context.req, context.res, [
1828
- * "admin",
1829
- * ]);
1830
- *
1831
- * return {
1832
- * props: {
1833
- * isAdmin,
1834
- * },
1835
- * };
1836
- * };
1837
- * ```
297
+ * @see {@link isUserInGroup} for full docs and examples.
298
+ * @param req Incoming Node.js request used to resolve authentication from cookies.
299
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
300
+ * @param groups Group IDs or names to check against the user's group memberships.
301
+ * @param options Optional configuration controlling how group membership is evaluated.
302
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
1838
303
  */
1839
304
  isUserInGroup(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
1840
305
  /**
1841
- * Redirects the user to the sign-in flow.
1842
- *
1843
- * **This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).**
1844
- *
1845
- * @param options Options to customize the sign-in.
1846
- *
1847
- * @returns
1848
- *
1849
- * @example React Server Component
1850
- *
1851
- * ```tsx
1852
- * import { monoCloud } from "@/lib/monocloud";
1853
- *
1854
- * export default async function Home() {
1855
- * const allowed = await monoCloud.isUserInGroup(["admin"]);
1856
- *
1857
- * if (!allowed) {
1858
- * await monoCloud.redirectToSignIn({ returnUrl: "/home" });
1859
- * }
1860
- *
1861
- * return <>You are signed in.</>;
1862
- * }
1863
- * ```
1864
- *
1865
- * @example Server Action
1866
- *
1867
- * ```typescript
1868
- * "use server";
1869
- *
1870
- * import { monoCloud } from "@/lib/monocloud";
1871
- *
1872
- * export async function protectedAction() {
1873
- * const session = await monoCloud.getSession();
1874
- *
1875
- * if (!session) {
1876
- * await monoCloud.redirectToSignIn();
1877
- * }
1878
- *
1879
- * return { data: "Sensitive Data" };
1880
- * }
1881
- * ```
1882
- *
1883
- * @example API Handler
1884
- *
1885
- * ```typescript
1886
- * import { NextResponse } from "next/server";
1887
- * import { monoCloud } from "@/lib/monocloud";
1888
- *
1889
- * export const GET = async () => {
1890
- * const session = await monoCloud.getSession();
1891
- *
1892
- * if (!session) {
1893
- * await monoCloud.redirectToSignIn({
1894
- * returnUrl: "/dashboard",
1895
- * });
1896
- * }
1897
- *
1898
- * return NextResponse.json({ data: "Protected content" });
1899
- * };
1900
- * ```
306
+ * @see {@link redirectToSignIn} for full docs and examples.
307
+ * @param options Optional configuration for the redirect, such as `returnUrl` or additional sign-in parameters.
308
+ * @returns Never resolves. Triggers a redirect to the sign-in flow.
1901
309
  */
1902
310
  redirectToSignIn(options?: RedirectToSignInOptions): Promise<void>;
1903
311
  /**
1904
- * Redirects the user to the sign-out flow.
1905
- *
1906
- * **This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).**
1907
- *
1908
- * @param options Options to customize the sign out.
1909
- *
1910
- * @returns
1911
- *
1912
- * @example React Server Component
1913
- *
1914
- * ```tsx
1915
- * import { monoCloud } from "@/lib/monocloud";
1916
- *
1917
- * export default async function Page() {
1918
- * const session = await monoCloud.getSession();
1919
- *
1920
- * // Example: Force sign-out if a specific condition is met (e.g., account suspended)
1921
- * if (session?.user.isSuspended) {
1922
- * await monoCloud.redirectToSignOut();
1923
- * }
1924
- *
1925
- * return <>Welcome User</>;
1926
- * }
1927
- * ```
1928
- *
1929
- * @example Server Action
1930
- *
1931
- * ```typescript
1932
- * "use server";
1933
- *
1934
- * import { monoCloud } from "@/lib/monocloud";
1935
- *
1936
- * export async function signOutAction() {
1937
- * const session = await monoCloud.getSession();
1938
- *
1939
- * if (session) {
1940
- * await monoCloud.redirectToSignOut();
1941
- * }
1942
- * }
1943
- * ```
1944
- *
1945
- * @example API Handler
1946
- *
1947
- * ```typescript
1948
- * import { monoCloud } from "@/lib/monocloud";
1949
- * import { NextResponse } from "next/server";
1950
- *
1951
- * export const GET = async () => {
1952
- * const session = await monoCloud.getSession();
1953
- *
1954
- * if (session) {
1955
- * await monoCloud.redirectToSignOut({
1956
- * postLogoutRedirectUri: "/goodbye",
1957
- * });
1958
- * }
1959
- *
1960
- * return NextResponse.json({ status: "already_signed_out" });
1961
- * };
1962
- * ```
312
+ * @see {@link redirectToSignOut} for full docs and examples.
313
+ * @param options Optional configuration for the redirect, such as `postLogoutRedirectUri` or additional sign-out parameters.
314
+ * @returns Never resolves. Triggers a redirect to the sign-out flow.
1963
315
  */
1964
316
  redirectToSignOut(options?: RedirectToSignOutOptions): Promise<void>;
1965
317
  private getOptions;
1966
318
  private registerPublicEnvVariables;
1967
319
  }
1968
320
  //#endregion
1969
- export { type AccessToken, type AppRouterApiOnAccessDeniedHandler, type ExtraAuthParams, type GetTokensOptions, type GroupOptions, type IsUserInGroupOptions, MonoCloudAuthBaseError, type MonoCloudAuthOptions, MonoCloudHttpError, type MonoCloudMiddlewareOptions, MonoCloudNextClient, MonoCloudOPError, type MonoCloudOptions, type MonoCloudSession, MonoCloudTokenError, type MonoCloudTokens, type MonoCloudUser, MonoCloudValidationError, type PageRouterApiOnAccessDeniedHandler, type ProtectApiAppOptions, type ProtectApiPageOptions, type ProtectAppPageOptions, type ProtectOptions, type ProtectPagePageOnAccessDeniedType, type ProtectPagePageOptions, type ProtectPagePageReturnType, type RedirectToSignInOptions, type RedirectToSignOutOptions };
321
+ //#region src/initialize.d.ts
322
+ /**
323
+ * Creates a Next.js catch-all auth route handler (Pages Router and App Router) for the built-in routes (`/signin`, `/callback`, `/userinfo`, `/signout`).
324
+ *
325
+ * Mount this handler on a catch-all route (e.g. `/api/auth/[...monocloud]`).
326
+ *
327
+ * > 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.
328
+ *
329
+ * @example App Router
330
+ * ```tsx:src/app/api/auth/[...monocloud]/route.ts tab="App Router" tab-group="monoCloudAuth"
331
+ * import { monoCloudAuth } from "@monocloud/auth-nextjs";
332
+ *
333
+ * export const GET = monoCloudAuth();
334
+ *```
335
+ *
336
+ * @example App Router (Response)
337
+ * ```tsx:src/app/api/auth/[...monocloud]/route.ts tab="App Router (Response)" tab-group="monoCloudAuth"
338
+ * import { monoCloudAuth } from "@monocloud/auth-nextjs";
339
+ * import { NextRequest, NextResponse } from "next/server";
340
+ *
341
+ * export const GET = (req: NextRequest) => {
342
+ * const authHandler = monoCloudAuth();
343
+ *
344
+ * const res = new NextResponse();
345
+ *
346
+ * res.cookies.set("last_auth_requested", `${Date.now()}`);
347
+ *
348
+ * return authHandler(req, res);
349
+ * };
350
+ * ```
351
+ *
352
+ * @example Pages Router
353
+ * ```tsx:src/pages/api/auth/[...monocloud].ts tab="Pages Router" tab-group="monoCloudAuth"
354
+ * import { monoCloudAuth } from "@monocloud/auth-nextjs";
355
+ *
356
+ * export default monoCloudAuth();
357
+ *```
358
+ *
359
+ * @example Pages Router (Response)
360
+ * ```tsx:src/pages/api/auth/[...monocloud].ts tab="Pages Router (Response)" tab-group="monoCloudAuth"
361
+ * import { monoCloudAuth } from "@monocloud/auth-nextjs";
362
+ * import { NextApiRequest, NextApiResponse } from "next";
363
+ *
364
+ * export default function handler(req: NextApiRequest, res: NextApiResponse) {
365
+ * const authHandler = monoCloudAuth();
366
+ *
367
+ * res.setHeader("last_auth_requested", `${Date.now()}`);
368
+ *
369
+ * return authHandler(req, res);
370
+ * }
371
+ * ```
372
+ *
373
+ * @param options Optional configuration for the auth handler.
374
+ * @returns Returns a Next.js-compatible handler for App Router route handlers or Pages Router API routes.
375
+ *
376
+ * @category Functions
377
+ */
378
+ declare function monoCloudAuth(options?: MonoCloudAuthOptions): MonoCloudAuthHandler;
379
+ /**
380
+ * Creates a Next.js authentication middleware that protects routes.
381
+ *
382
+ * By default, all routes matched by `config.matcher` are protected unless configured otherwise.
383
+ *
384
+ * @example Protect All Routes
385
+ * ```tsx:src/proxy.ts tab="Protect All Routes" tab-group="auth-middleware"
386
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
387
+ *
388
+ * export default authMiddleware();
389
+ *
390
+ * export const config = {
391
+ * matcher: [
392
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
393
+ * ],
394
+ * };
395
+ * ```
396
+ *
397
+ * @example Protect Selected Routes
398
+ * ```tsx:src/proxy.ts tab="Protect Selected Routes" tab-group="auth-middleware"
399
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
400
+ *
401
+ * export default authMiddleware({
402
+ * protectedRoutes: ["/api/admin", "^/api/protected(/.*)?$"],
403
+ * });
404
+ *
405
+ * export const config = {
406
+ * matcher: [
407
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
408
+ * ],
409
+ * };
410
+ *```
411
+ *
412
+ * @example No Protected Routes
413
+ * ```tsx:src/proxy.ts tab="No Protected Routes" tab-group="auth-middleware"
414
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
415
+ *
416
+ * export default authMiddleware({
417
+ * protectedRoutes: [],
418
+ * });
419
+ *
420
+ * export const config = {
421
+ * matcher: [
422
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
423
+ * ],
424
+ * };
425
+ * ```
426
+ *
427
+ * @example Dynamic
428
+ * ```tsx:src/proxy.ts tab="Dynamic" tab-group="auth-middleware"
429
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
430
+ *
431
+ * export default authMiddleware({
432
+ * protectedRoutes: (req) => {
433
+ * return req.nextUrl.pathname.startsWith("/api/protected");
434
+ * },
435
+ * });
436
+ *
437
+ * export const config = {
438
+ * matcher: [
439
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
440
+ * ],
441
+ * };
442
+ * ```
443
+ *
444
+ * @example Group Protection
445
+ * ```tsx:src/proxy.ts tab="Group Protection" tab-group="auth-middleware"
446
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
447
+ *
448
+ * export default authMiddleware({
449
+ * protectedRoutes: [
450
+ * {
451
+ * groups: ["admin", "editor", "537e7c3d-a442-4b5b-b308-30837aa045a4"],
452
+ * routes: ["/internal", "/api/internal(.*)"],
453
+ * },
454
+ * ],
455
+ * });
456
+ *
457
+ * export const config = {
458
+ * matcher: [
459
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
460
+ * ],
461
+ * };
462
+ * ```
463
+ *
464
+ * @param options Optional configuration that controls how authentication is enforced (for example, redirect behavior, route matching, or custom handling of unauthenticated requests).
465
+ * @returns Returns a Next.js middleware result, such as a NextResponse, redirect, or undefined to continue processing.
466
+ *
467
+ * @category Functions
468
+ */
469
+ declare function authMiddleware(options?: MonoCloudMiddlewareOptions): NextMiddleware$1 | NextProxy$1;
470
+ /**
471
+ * Executes the authentication middleware manually.
472
+ *
473
+ * Intended for advanced scenarios where the middleware is composed within custom logic.
474
+ *
475
+ * @example Composing with custom middleware
476
+ *
477
+ * ```tsx:src/proxy.ts title="Composing with custom middleware"
478
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
479
+ * import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
480
+ *
481
+ * export default function customMiddleware(req: NextRequest, evt: NextFetchEvent) {
482
+ * if (req.nextUrl.pathname.startsWith("/api/protected")) {
483
+ * return authMiddleware(req, evt);
484
+ * }
485
+ *
486
+ * return NextResponse.next();
487
+ * }
488
+ *
489
+ * export const config = {
490
+ * matcher: [
491
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
492
+ * ],
493
+ * };
494
+ * ```
495
+ *
496
+ * @param request Incoming Next.js middleware request used to resolve authentication state.
497
+ * @param event Next.js middleware event providing lifecycle hooks such as `waitUntil`.
498
+ * @returns Returns a Next.js middleware result (`NextResponse`, redirect, or `undefined` to continue processing).
499
+ *
500
+ * @category Functions
501
+ */
502
+ declare function authMiddleware(request: NextRequest$1, event: NextFetchEvent$1): Promise<NextMiddlewareResult> | NextMiddlewareResult;
503
+ /**
504
+ * Retrieves the current user's session using the active server request context.
505
+ *
506
+ * Intended for Server Components, Server Actions, Route Handlers, and Middleware where the request is implicitly available.
507
+ *
508
+ * @example Server Component
509
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="session-ssr"
510
+ * import { getSession } from "@monocloud/auth-nextjs";
511
+ *
512
+ * export default async function Home() {
513
+ * const session = await getSession();
514
+ *
515
+ * return <div>{session?.user.name}</div>;
516
+ * }
517
+ * ```
518
+ *
519
+ * @example Server Action
520
+ * ```tsx:src/action.ts tab="Server Action" tab-group="session-ssr"
521
+ * "use server";
522
+ *
523
+ * import { getSession } from "@monocloud/auth-nextjs";
524
+ *
525
+ * export async function getUserAction() {
526
+ * const session = await getSession();
527
+ *
528
+ * return { name: session?.user.name };
529
+ * }
530
+ * ```
531
+ *
532
+ * @example API Handler
533
+ * ```tsx:src/app/api/user/route.ts tab="API Handler" tab-group="session-ssr"
534
+ * import { getSession } from "@monocloud/auth-nextjs";
535
+ * import { NextResponse } from "next/server";
536
+ *
537
+ * export const GET = async () => {
538
+ * const session = await getSession();
539
+ *
540
+ * return NextResponse.json({ name: session?.user.name });
541
+ * };
542
+ * ```
543
+ *
544
+ * @example Middleware
545
+ * ```tsx:src/proxy.ts tab="Middleware" tab-group="session-ssr"
546
+ * import { getSession } from "@monocloud/auth-nextjs";
547
+ * import { NextResponse } from "next/server";
548
+ *
549
+ * export default async function proxy() {
550
+ * const session = await getSession();
551
+ *
552
+ * if (!session) {
553
+ * return new NextResponse("User not signed in", { status: 401 });
554
+ * }
555
+ *
556
+ * return NextResponse.next();
557
+ * }
558
+ * ```
559
+ *
560
+ * @returns Returns the resolved session, or `undefined` if none exists.
561
+ *
562
+ * @category Functions
563
+ */
564
+ declare function getSession(): Promise<MonoCloudSession$2 | undefined>;
565
+ /**
566
+ * Retrieves the current user's session using an explicit Web or Next.js request.
567
+ *
568
+ * Use this overload when you already have access to a `Request` or `NextRequest` (for example in Middleware or Route Handlers).
569
+ *
570
+ * @example Middleware (Request)
571
+ * ```tsx:src/proxy.ts tab="Middleware (Request)" tab-group="session-route-handler"
572
+ * import { getSession } from "@monocloud/auth-nextjs";
573
+ * import { NextRequest, NextResponse } from "next/server";
574
+ *
575
+ * export default async function proxy(req: NextRequest) {
576
+ * const session = await getSession(req);
577
+ *
578
+ * if (!session) {
579
+ * return new NextResponse("User not signed in", { status: 401 });
580
+ * }
581
+ *
582
+ * return NextResponse.next();
583
+ * }
584
+ * ```
585
+ *
586
+ * @example Middleware (Response)
587
+ * ```tsx:src/proxy.ts tab="Middleware (Response)" tab-group="session-route-handler"
588
+ * import { getSession } from "@monocloud/auth-nextjs";
589
+ * import { NextRequest, NextResponse } from "next/server";
590
+ *
591
+ * export default async function proxy(req: NextRequest) {
592
+ * const res = NextResponse.next();
593
+ *
594
+ * const session = await getSession(req, res);
595
+ *
596
+ * if (!session) {
597
+ * return new NextResponse("User not signed in", { status: 401 });
598
+ * }
599
+ *
600
+ * res.headers.set("x-auth-status", "active");
601
+ *
602
+ * return res;
603
+ * }
604
+ * ```
605
+ *
606
+ * @example API Handler (Request)
607
+ * ```tsx:src/app/api/user/route.ts tab="API Handler (Request)" tab-group="session-route-handler"
608
+ * import { getSession } from "@monocloud/auth-nextjs";
609
+ * import { NextRequest, NextResponse } from "next/server";
610
+ *
611
+ * export const GET = async (req: NextRequest) => {
612
+ * const session = await getSession(req);
613
+ *
614
+ * return NextResponse.json({ name: session?.user.name });
615
+ * };
616
+ * ```
617
+ *
618
+ * @example API Handler (Response)
619
+ * ```tsx:src/app/api/user/route.ts tab="API Handler (Response)" tab-group="session-route-handler"
620
+ * import { getSession } from "@monocloud/auth-nextjs";
621
+ * import { NextRequest, NextResponse } from "next/server";
622
+ *
623
+ * export const GET = async (req: NextRequest) => {
624
+ * const res = new NextResponse("YOUR CUSTOM RESPONSE");
625
+ *
626
+ * const session = await getSession(req, res);
627
+ *
628
+ * if (session?.user) {
629
+ * res.cookies.set("something", "important");
630
+ * }
631
+ *
632
+ * return res;
633
+ * };
634
+ * ```
635
+ *
636
+ * @param req Incoming request used to read authentication cookies and headers to resolve the current user's session.
637
+ * @param res Optional response to update if session resolution requires refreshed authentication cookies or headers.
638
+ * @returns Returns the resolved session, or `undefined` if none exists.
639
+ *
640
+ * @category Functions
641
+ */
642
+ declare function getSession(req: NextRequest$1 | Request, res?: NextResponse$1 | Response): Promise<MonoCloudSession$2 | undefined>;
643
+ /**
644
+ * Retrieves the current user's session in the Pages Router or Node.js runtime.
645
+ *
646
+ * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.
647
+ *
648
+ * @example Pages Router (Pages)
649
+ * ```tsx:src/pages/index.tsx tab="Pages Router (Pages)" tab-group="session-pages"
650
+ * import { getSession, MonoCloudSession } from "@monocloud/auth-nextjs";
651
+ * import { GetServerSideProps } from "next";
652
+ *
653
+ * type Props = {
654
+ * session?: MonoCloudSession;
655
+ * };
656
+ *
657
+ * export default function Home({ session }: Props) {
658
+ * return <pre>Session: {JSON.stringify(session, null, 2)}</pre>;
659
+ * }
660
+ *
661
+ * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
662
+ * const session = await getSession(ctx.req, ctx.res);
663
+ *
664
+ * return {
665
+ * props: {
666
+ * session
667
+ * }
668
+ * };
669
+ * };
670
+ * ```
671
+ * @example Pages Router (API)
672
+ * ```tsx:src/pages/api/user.ts tab="Pages Router (API)" tab-group="session-pages"
673
+ * import { getSession } from "@monocloud/auth-nextjs";
674
+ * import { NextApiRequest, NextApiResponse } from "next";
675
+ *
676
+ * export default async function handler(
677
+ * req: NextApiRequest,
678
+ * res: NextApiResponse
679
+ * ) {
680
+ * const session = await getSession(req, res);
681
+ *
682
+ * res.status(200).json({ name: session?.user.name });
683
+ * }
684
+ * ```
685
+ *
686
+ * @param req Incoming Node.js request used to read authentication cookies and resolve the current user's session.
687
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
688
+ * @returns Returns the resolved session, or `undefined` if none exists.
689
+ *
690
+ * @category Functions
691
+ */
692
+ declare function getSession(req: NextApiRequest$1 | IncomingMessage, res: NextApiResponse$1 | ServerResponse<IncomingMessage>): Promise<MonoCloudSession$2 | undefined>;
693
+ /**
694
+ * Retrieves the current user's tokens using the active server request context.
695
+ *
696
+ * @example Server Component
697
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="tokens-ssr"
698
+ * import { getTokens } from "@monocloud/auth-nextjs";
699
+ *
700
+ * export default async function Home() {
701
+ * const tokens = await getTokens();
702
+ *
703
+ * return <div>Expired: {tokens.isExpired.toString()}</div>;
704
+ * }
705
+ * ```
706
+ *
707
+ * @example Server Action
708
+ * ```tsx:src/action.ts tab="Server Action" tab-group="tokens-ssr"
709
+ * "use server";
710
+ *
711
+ * import { getTokens } from "@monocloud/auth-nextjs";
712
+ *
713
+ * export async function getExpiredAction() {
714
+ * const tokens = await getTokens();
715
+ *
716
+ * return { expired: tokens.isExpired };
717
+ * }
718
+ * ```
719
+ *
720
+ * @example API Handler
721
+ * ```tsx:src/app/api/tokens/route.ts tab="API Handler" tab-group="tokens-ssr"
722
+ * import { getTokens } from "@monocloud/auth-nextjs";
723
+ * import { NextResponse } from "next/server";
724
+ *
725
+ * export const GET = async () => {
726
+ * const tokens = await getTokens();
727
+ *
728
+ * return NextResponse.json({ expired: tokens.isExpired });
729
+ * };
730
+ * ```
731
+ *
732
+ * @example Middleware
733
+ * ```tsx:src/proxy.ts tab="Middleware" tab-group="tokens-ssr"
734
+ * import { getTokens } from "@monocloud/auth-nextjs";
735
+ * import { NextResponse } from "next/server";
736
+ *
737
+ * export default async function proxy() {
738
+ * const tokens = await getTokens();
739
+ *
740
+ * if (tokens.isExpired) {
741
+ * return new NextResponse("Tokens expired", { status: 401 });
742
+ * }
743
+ *
744
+ * return NextResponse.next();
745
+ * }
746
+ * ```
747
+ *
748
+ * @example Refresh the default token
749
+ *
750
+ * The **default token** is the access token associated with your default authorization parameters:
751
+ * - Scopes: `MONOCLOUD_AUTH_SCOPES` or `options.defaultAuthParams.scopes`
752
+ * - Resource: `MONOCLOUD_AUTH_RESOURCE` or `options.defaultAuthParams.resource`
753
+ *
754
+ * 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`.
755
+ *
756
+ * ```tsx:src/app/page.tsx title="Refresh default token"
757
+ * import { getTokens } from "@monocloud/auth-nextjs";
758
+ * import { NextResponse } from "next/server";
759
+ *
760
+ * export const GET = async () => {
761
+ * // Forces a refresh of the default token
762
+ * const tokens = await getTokens({ forceRefresh: true });
763
+ *
764
+ * return NextResponse.json({ accessToken: tokens?.accessToken });
765
+ * };
766
+ * ```
767
+ *
768
+ * @example Request an access token for resource(s)
769
+ *
770
+ * Use `resource` and `scopes` to request an access token for one or more resources.
771
+ *
772
+ * > 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).
773
+ *
774
+ * ```tsx:src/app/page.tsx title="Request a new access token for resource(s)"
775
+ * import { getTokens } from "@monocloud/auth-nextjs";
776
+ * import { NextResponse } from "next/server";
777
+ *
778
+ * export const GET = async () => {
779
+ * const tokens = await getTokens({
780
+ * resource: "https://first.example.com https://second.example.com",
781
+ * scopes: "read:first read:second shared",
782
+ * });
783
+ *
784
+ * return NextResponse.json({ accessToken: tokens?.accessToken });
785
+ * };
786
+ * ```
787
+ *
788
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
789
+ * @returns The current user's tokens, refreshed if necessary.
790
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
791
+ *
792
+ * @category Functions
793
+ */
794
+ declare function getTokens(options?: GetTokensOptions$1): Promise<MonoCloudTokens$1>;
795
+ /**
796
+ * Retrieves the current user's tokens using an explicit Web or Next.js request.
797
+ *
798
+ * Use this overload when you already have access to a `Request` or `NextRequest` (for example, in Middleware or Route Handlers).
799
+ *
800
+ * @example Middleware (Request)
801
+ * ```tsx:src/proxy.ts tab="Middleware (Request)" tab-group="tokens-route-handler-request"
802
+ * import { getTokens } from "@monocloud/auth-nextjs";
803
+ * import { NextRequest, NextResponse } from "next/server";
804
+ *
805
+ * export default async function proxy(req: NextRequest) {
806
+ * const tokens = await getTokens(req);
807
+ *
808
+ * if (tokens.isExpired) {
809
+ * return new NextResponse("Tokens expired", { status: 401 });
810
+ * }
811
+ *
812
+ * return NextResponse.next();
813
+ * }
814
+ * ```
815
+ *
816
+ * @example API Handler (Request)
817
+ * ```tsx:src/app/api/tokens/route.ts tab="API Handler (Request)" tab-group="tokens-route-handler-request"
818
+ * import { getTokens } from "@monocloud/auth-nextjs";
819
+ * import { NextRequest, NextResponse } from "next/server";
820
+ *
821
+ * export const GET = async (req: NextRequest) => {
822
+ * const tokens = await getTokens(req);
823
+ *
824
+ * return NextResponse.json({ expired: tokens?.isExpired });
825
+ * };
826
+ * ```
827
+ *
828
+ * @param req Incoming request used to resolve authentication from cookies and headers.
829
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
830
+ * @returns The current user's tokens, refreshed if necessary.
831
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
832
+ *
833
+ * @category Functions
834
+ */
835
+ declare function getTokens(req: NextRequest$1 | Request, options?: GetTokensOptions$1): Promise<MonoCloudTokens$1>;
836
+ /**
837
+ * Retrieves the current user's tokens using an explicit request and response.
838
+ *
839
+ * Use this overload when you have already created a response and want refreshed authentication cookies or headers applied to it.
840
+ *
841
+ * @example Middleware (Response)
842
+ *```tsx:src/proxy.ts tab="Middleware (Response)" tab-group="tokens-route-handler-response"
843
+ * import { getTokens } from "@monocloud/auth-nextjs";
844
+ * import { NextRequest, NextResponse } from "next/server";
845
+ *
846
+ * export default async function proxy(req: NextRequest) {
847
+ * const res = NextResponse.next();
848
+ *
849
+ * const tokens = await getTokens(req, res);
850
+ *
851
+ * res.headers.set("x-tokens-expired", tokens.isExpired.toString());
852
+ *
853
+ * return res;
854
+ * }
855
+ * ```
856
+ *
857
+ * @example API Handler (Response)
858
+ * ```tsx:src/app/api/tokens/route.ts tab="API Handler (Response)" tab-group="tokens-route-handler-response"
859
+ * import { getTokens } from "@monocloud/auth-nextjs";
860
+ * import { NextRequest, NextResponse } from "next/server";
861
+ *
862
+ * export const GET = async (req: NextRequest) => {
863
+ * const res = new NextResponse("Custom Body");
864
+ *
865
+ * const tokens = await getTokens(req, res);
866
+ *
867
+ * if (!tokens.isExpired) {
868
+ * res.headers.set("x-auth-status", "active");
869
+ * }
870
+ *
871
+ * return res;
872
+ * };
873
+ * ```
874
+ *
875
+ * @param req Incoming request used to resolve authentication from cookies and headers.
876
+ * @param res Existing response to update with refreshed authentication cookies or headers.
877
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
878
+ * @returns The current user's tokens, refreshed if necessary.
879
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
880
+ *
881
+ * @category Functions
882
+ */
883
+ declare function getTokens(req: NextRequest$1 | Request, res: NextResponse$1 | Response, options?: GetTokensOptions$1): Promise<MonoCloudTokens$1>;
884
+ /**
885
+ * Retrieves the current user's tokens in the Pages Router or Node.js runtime.
886
+ *
887
+ * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.
888
+ *
889
+ * @example Pages Router (Pages)
890
+ * ```tsx:src/pages/index.tsx tab="Pages Router (Pages)" tab-group="tokens-pages"
891
+ * import { getTokens, MonoCloudTokens } from "@monocloud/auth-nextjs";
892
+ * import { GetServerSideProps } from "next";
893
+ *
894
+ * type Props = {
895
+ * tokens: MonoCloudTokens;
896
+ * };
897
+ *
898
+ * export default function Home({ tokens }: Props) {
899
+ * return <pre>Tokens: {JSON.stringify(tokens, null, 2)}</pre>;
900
+ * }
901
+ *
902
+ * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
903
+ * const tokens = await getTokens(ctx.req, ctx.res);
904
+ *
905
+ * return {
906
+ * props: {
907
+ * tokens: tokens
908
+ * }
909
+ * };
910
+ * };
911
+ * ```
912
+ *
913
+ * @example Pages Router (API)
914
+ * ```tsx:src/pages/api/tokens.ts tab="Pages Router (API)" tab-group="tokens-pages"
915
+ * import { getTokens } from "@monocloud/auth-nextjs";
916
+ * import { NextApiRequest, NextApiResponse } from "next";
917
+ *
918
+ * export default async function handler(
919
+ * req: NextApiRequest,
920
+ * res: NextApiResponse
921
+ * ) {
922
+ * const tokens = await getTokens(req, res);
923
+ *
924
+ * res.status(200).json({ accessToken: tokens?.accessToken });
925
+ * }
926
+ * ```
927
+ *
928
+ * @param req Incoming Node.js request used to resolve authentication from cookies.
929
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
930
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
931
+ * @returns The current user's tokens, refreshed if necessary.
932
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
933
+ *
934
+ * @category Functions
935
+ */
936
+ declare function getTokens(req: NextApiRequest$1 | IncomingMessage, res: NextApiResponse$1 | ServerResponse<IncomingMessage>, options?: GetTokensOptions$1): Promise<MonoCloudTokens$1>;
937
+ /**
938
+ * Checks whether the current user is authenticated using the active server request context.
939
+ *
940
+ * Intended for Server Components, Server Actions, Route Handlers, and Middleware where the request is implicitly available.
941
+ *
942
+ * @example Server Component
943
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="is-authenticated-ssr"
944
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
945
+ *
946
+ * export default async function Home() {
947
+ * const authenticated = await isAuthenticated();
948
+ *
949
+ * return <div>Authenticated: {authenticated.toString()}</div>;
950
+ * }
951
+ * ```
952
+ *
953
+ * @example Server Action
954
+ * ```tsx:src/action.ts tab="Server Action" tab-group="is-authenticated-ssr"
955
+ * "use server";
956
+ *
957
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
958
+ *
959
+ * export async function checkAuthAction() {
960
+ * const authenticated = await isAuthenticated();
961
+ *
962
+ * return { authenticated };
963
+ * }
964
+ * ```
965
+ *
966
+ * @example API Handler
967
+ * ```tsx:src/app/api/authenticated/route.ts tab="API Handler" tab-group="is-authenticated-ssr"
968
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
969
+ * import { NextResponse } from "next/server";
970
+ *
971
+ * export const GET = async () => {
972
+ * const authenticated = await isAuthenticated();
973
+ *
974
+ * return NextResponse.json({ authenticated });
975
+ * };
976
+ * ```
977
+ *
978
+ * @example Middleware
979
+ * ```tsx:src/proxy.ts tab="Middleware" tab-group="is-authenticated-ssr"
980
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
981
+ * import { NextResponse } from "next/server";
982
+ *
983
+ * export default async function proxy() {
984
+ * const authenticated = await isAuthenticated();
985
+ *
986
+ * if (!authenticated) {
987
+ * return new NextResponse("User not signed in", { status: 401 });
988
+ * }
989
+ *
990
+ * return NextResponse.next();
991
+ * }
992
+ * ```
993
+ *
994
+ * @returns Returns `true` if a valid session exists; otherwise `false`.
995
+ *
996
+ * @category Functions
997
+ */
998
+ declare function isAuthenticated(): Promise<boolean>;
999
+ /**
1000
+ * Checks whether the current user is authenticated using an explicit Web or Next.js request.
1001
+ *
1002
+ * Use this overload when you already have access to a `Request` or `NextRequest` (for example, in Middleware or Route Handlers).
1003
+ *
1004
+ * @example Middleware (Request)
1005
+ * ```tsx:src/proxy.ts tab="Middleware (Request)" tab-group="is-authenticated-route-handler"
1006
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
1007
+ * import { NextRequest, NextResponse } from "next/server";
1008
+ *
1009
+ * export default async function proxy(req: NextRequest) {
1010
+ * const authenticated = await isAuthenticated(req);
1011
+ *
1012
+ * if (!authenticated) {
1013
+ * return new NextResponse("User not signed in", { status: 401 });
1014
+ * }
1015
+ *
1016
+ * return NextResponse.next();
1017
+ * }
1018
+ * ```
1019
+ *
1020
+ * @example Middleware (Response)
1021
+ * ```tsx:src/proxy.ts tab="Middleware (Response)" tab-group="is-authenticated-route-handler"
1022
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
1023
+ * import { NextRequest, NextResponse } from "next/server";
1024
+ *
1025
+ * export default async function proxy(req: NextRequest) {
1026
+ * const res = NextResponse.next();
1027
+ *
1028
+ * const authenticated = await isAuthenticated(req, res);
1029
+ *
1030
+ * if (!authenticated) {
1031
+ * return new NextResponse("User not signed in", { status: 401 });
1032
+ * }
1033
+ *
1034
+ * res.headers.set("x-authenticated", "true");
1035
+ *
1036
+ * return res;
1037
+ * }
1038
+ * ```
1039
+ *
1040
+ * @example API Handler (Request)
1041
+ * ```tsx:src/app/api/authenticated/route.ts tab="API Handler (Request)" tab-group="is-authenticated-route-handler"
1042
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
1043
+ * import { NextRequest, NextResponse } from "next/server";
1044
+ *
1045
+ * export const GET = async (req: NextRequest) => {
1046
+ * const authenticated = await isAuthenticated(req);
1047
+ *
1048
+ * return NextResponse.json({ authenticated });
1049
+ * };
1050
+ * ```
1051
+ *
1052
+ * @example API Handler (Response)
1053
+ * ```tsx:src/app/api/authenticated/route.ts tab="API Handler (Response)" tab-group="is-authenticated-route-handler"
1054
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
1055
+ * import { NextRequest, NextResponse } from "next/server";
1056
+ *
1057
+ * export const GET = async (req: NextRequest) => {
1058
+ * const res = new NextResponse("YOUR CUSTOM RESPONSE");
1059
+ *
1060
+ * const authenticated = await isAuthenticated(req, res);
1061
+ *
1062
+ * if (authenticated) {
1063
+ * res.cookies.set("something", "important");
1064
+ * }
1065
+ *
1066
+ * return res;
1067
+ * };
1068
+ * ```
1069
+ *
1070
+ * @param req Incoming request used to resolve authentication from cookies and headers.
1071
+ * @param res Optional response to update if refreshed authentication cookies or headers are required.
1072
+ * @returns Returns `true` if a valid session exists; otherwise `false`.
1073
+ *
1074
+ * @category Functions
1075
+ */
1076
+ declare function isAuthenticated(req: NextRequest$1 | Request, res?: NextResponse$1 | Response): Promise<boolean>;
1077
+ /**
1078
+ * Checks whether the current user is authenticated in the Pages Router or Node.js runtime.
1079
+ *
1080
+ * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.
1081
+ *
1082
+ * @example Pages Router (Pages)
1083
+ * ```tsx:src/pages/index.tsx tab="Pages Router (Pages)" tab-group="is-authenticated-pages"
1084
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
1085
+ * import { GetServerSideProps } from "next";
1086
+ *
1087
+ * type Props = {
1088
+ * authenticated: boolean;
1089
+ * };
1090
+ *
1091
+ * export default function Home({ authenticated }: Props) {
1092
+ * return <pre>User is {authenticated ? "logged in" : "guest"}</pre>;
1093
+ * }
1094
+ *
1095
+ * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
1096
+ * const authenticated = await isAuthenticated(ctx.req, ctx.res);
1097
+ *
1098
+ * return {
1099
+ * props: {
1100
+ * authenticated
1101
+ * }
1102
+ * };
1103
+ * };
1104
+ * ```
1105
+ *
1106
+ * @example Pages Router (API)
1107
+ * ```tsx:src/pages/api/authenticated.ts tab="Pages Router (API)" tab-group="is-authenticated-pages"
1108
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
1109
+ * import { NextApiRequest, NextApiResponse } from "next";
1110
+ *
1111
+ * export default async function handler(
1112
+ * req: NextApiRequest,
1113
+ * res: NextApiResponse
1114
+ * ) {
1115
+ * const authenticated = await isAuthenticated(req, res);
1116
+ *
1117
+ * res.status(200).json({ authenticated });
1118
+ * }
1119
+ * ```
1120
+ *
1121
+ * @param req Incoming Node.js request used to resolve authentication from cookies.
1122
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
1123
+ * @returns Returns `true` if a valid session exists; otherwise `false`.
1124
+ *
1125
+ * @category Functions
1126
+ */
1127
+ declare function isAuthenticated(req: NextApiRequest$1 | IncomingMessage, res: NextApiResponse$1 | ServerResponse<IncomingMessage>): Promise<boolean>;
1128
+ /**
1129
+ * Ensures the current user is authenticated. If not, redirects to the sign-in flow.
1130
+ *
1131
+ * > **App Router only.** Intended for Server Components, Route Handlers, and Server Actions.
1132
+ *
1133
+ * @example Server Component
1134
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="protect"
1135
+ * import { protect } from "@monocloud/auth-nextjs";
1136
+ *
1137
+ * export default async function Home() {
1138
+ * await protect();
1139
+ *
1140
+ * return <>You are signed in.</>;
1141
+ * }
1142
+ * ```
1143
+ *
1144
+ * @example Server Action
1145
+ * ```tsx:src/action.ts tab="Server Action" tab-group="protect"
1146
+ * "use server";
1147
+ *
1148
+ * import { protect } from "@monocloud/auth-nextjs";
1149
+ *
1150
+ * export async function getMessage() {
1151
+ * await protect();
1152
+ *
1153
+ * return { secret: "sssshhhhh!!!" };
1154
+ * }
1155
+ * ```
1156
+ *
1157
+ * @example API Handler
1158
+ * ```tsx:src/app/api/protected/route.ts tab="API Handler" tab-group="protect"
1159
+ * import { protect } from "@monocloud/auth-nextjs";
1160
+ * import { NextResponse } from "next/server";
1161
+ *
1162
+ * export const GET = async () => {
1163
+ * await protect();
1164
+ *
1165
+ * return NextResponse.json({ secret: "ssshhhh!!!" });
1166
+ * };
1167
+ * ```
1168
+ *
1169
+ * @param options Optional configuration for redirect behavior (for example, return URL or sign-in parameters).
1170
+ * @returns Resolves if the user is authenticated; otherwise triggers a redirect.
1171
+ *
1172
+ * @category Functions
1173
+ */
1174
+ declare function protect(options?: ProtectOptions): Promise<void>;
1175
+ /**
1176
+ * Wraps an App Router API route handler and ensures that only authenticated (and optionally authorized) requests can access the route.
1177
+ *
1178
+ * Intended for Next.js App Router Route Handlers.
1179
+ *
1180
+ * @example
1181
+ * ```tsx:src/app/api/protected/route.ts
1182
+ * import { protectApi } from "@monocloud/auth-nextjs";
1183
+ * import { NextResponse } from "next/server";
1184
+ *
1185
+ * export const GET = protectApi(async () => {
1186
+ * return NextResponse.json({
1187
+ * message: "You accessed a protected endpoint",
1188
+ * });
1189
+ * });
1190
+ * ```
1191
+ *
1192
+ * @param handler The route handler to protect.
1193
+ * @param options Optional configuration controlling authentication and authorization behavior.
1194
+ * @returns Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.
1195
+ *
1196
+ * @category Functions
1197
+ */
1198
+ declare function protectApi(handler: AppRouterApiHandlerFn, options?: ProtectApiAppOptions): AppRouterApiHandlerFn;
1199
+ /**
1200
+ * Wraps a Pages Router API route handler and ensures that only authenticated (and optionally authorized) requests can access the route.
1201
+ *
1202
+ * Intended for Next.js Pages Router API routes.
1203
+ *
1204
+ * @example
1205
+ * ```tsx:src/pages/api/protected.ts
1206
+ * import { protectApi } from "@monocloud/auth-nextjs";
1207
+ * import { NextApiRequest, NextApiResponse } from "next";
1208
+ *
1209
+ * export default protectApi(
1210
+ * async (req: NextApiRequest, res: NextApiResponse) => {
1211
+ * return res.json({
1212
+ * message: "You accessed a protected endpoint",
1213
+ * });
1214
+ * }
1215
+ * );
1216
+ * ```
1217
+ *
1218
+ * @param handler - The route handler to protect.
1219
+ * @param options Optional configuration controlling authentication and authorization behavior.
1220
+ * @returns Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.
1221
+ *
1222
+ * @category Functions
1223
+ */
1224
+ declare function protectApi(handler: NextApiHandler$1, options?: ProtectApiPageOptions): NextApiHandler$1;
1225
+ /**
1226
+ * Restricts access to App Router server-rendered pages.
1227
+ *
1228
+ * **Access control**
1229
+ * - If the user is not authenticated, `onAccessDenied` is invoked (or default behavior applies).
1230
+ * - If the user is authenticated but fails group checks, `onGroupAccessDenied` is invoked (or the default "Access Denied" view is rendered).
1231
+ *
1232
+ * Both behaviors can be customized via options.
1233
+ *
1234
+ * @example Basic Usage
1235
+ * ```tsx:src/app/page.tsx tab="Basic Usage" tab-group="protectPage-app"
1236
+ * import { protectPage } from "@monocloud/auth-nextjs";
1237
+ *
1238
+ * export default protectPage(async function Home({ user }) {
1239
+ * return <>Hi {user.email}. You accessed a protected page.</>;
1240
+ * });
1241
+ * ```
1242
+ *
1243
+ * @example With Options
1244
+ * ```tsx:src/app/page.tsx tab="With Options" tab-group="protectPage-app"
1245
+ * import { protectPage } from "@monocloud/auth-nextjs";
1246
+ *
1247
+ * export default protectPage(
1248
+ * async function Home({ user }) {
1249
+ * return <>Hi {user.email}. You accessed a protected page.</>;
1250
+ * },
1251
+ * {
1252
+ * returnUrl: "/dashboard",
1253
+ * groups: ["admin"],
1254
+ * }
1255
+ * );
1256
+ * ```
1257
+ *
1258
+ * @param component The App Router server component to protect.
1259
+ * @param options Optional configuration for authentication, authorization, and custom access handling (`onAccessDenied`, `onGroupAccessDenied`).
1260
+ * @returns A wrapped page component that enforces authentication before rendering.
1261
+ *
1262
+ * @category Functions
1263
+ */
1264
+ declare function protectPage(component: ProtectedAppServerComponent, options?: ProtectAppPageOptions): AppRouterPageHandler;
1265
+ /**
1266
+ * Restricts access to Pages Router server-rendered pages using `getServerSideProps`.
1267
+ *
1268
+ * **Access control**
1269
+ * - If the user is not authenticated, `onAccessDenied` is invoked (or default behavior applies).
1270
+ * - 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.
1271
+ *
1272
+ * Both behaviors can be customized via options.
1273
+ *
1274
+ * @example Basic Usage
1275
+ * ```tsx:src/pages/index.tsx tab="Basic Usage" tab-group="protectPage-page"
1276
+ * import { protectPage, MonoCloudUser } from "@monocloud/auth-nextjs";
1277
+ *
1278
+ * type Props = {
1279
+ * user: MonoCloudUser;
1280
+ * };
1281
+ *
1282
+ * export default function Home({ user }: Props) {
1283
+ * return <>Hi {user.email}. You accessed a protected page.</>;
1284
+ * }
1285
+ *
1286
+ * export const getServerSideProps = protectPage();
1287
+ * ```
1288
+ *
1289
+ * @example With Options
1290
+ * ```tsx:src/pages/index.tsx tab="With Options" tab-group="protectPage-page"
1291
+ * import { protectPage, MonoCloudUser } from "@monocloud/auth-nextjs";
1292
+ * import { GetServerSidePropsContext } from "next";
1293
+ *
1294
+ * type Props = {
1295
+ * user: MonoCloudUser;
1296
+ * url: string;
1297
+ * };
1298
+ *
1299
+ * export default function Home({ user, url }: Props) {
1300
+ * console.log(url);
1301
+ * return <div>Hi {user?.email}. You accessed a protected page.</div>;
1302
+ * }
1303
+ *
1304
+ * export const getServerSideProps = protectPage({
1305
+ * returnUrl: "/dashboard",
1306
+ * groups: ["admin"],
1307
+ * getServerSideProps: async (context: GetServerSidePropsContext) => ({
1308
+ * props: { url: context.resolvedUrl }
1309
+ * })
1310
+ * });
1311
+ * ```
1312
+ *
1313
+ * @param options Optional configuration for authentication, authorization, and custom access handling (`onAccessDenied`, `onGroupAccessDenied`).
1314
+ * @typeParam P - Props returned from getServerSideProps.
1315
+ * @typeParam Q - Query parameters parsed from the URL.
1316
+ * @returns A getServerSideProps wrapper that enforces authentication before executing the page logic.
1317
+ *
1318
+ * @category Functions
1319
+ */
1320
+ declare function protectPage<P extends Record<string, any> = Record<string, any>, Q extends ParsedUrlQuery = ParsedUrlQuery>(options?: ProtectPagePageOptions<P, Q>): ProtectPagePageReturnType<P, Q>;
1321
+ /**
1322
+ * Checks whether the currently authenticated user is a member of **any** of the specified groups.
1323
+ *
1324
+ * The `groups` parameter accepts group identifiers (IDs or names).
1325
+ *
1326
+ * The authenticated user's session may contain groups represented as:
1327
+ * - Group IDs
1328
+ * - Group names
1329
+ * - `Group` objects (for example, `{ id: string; name: string }`)
1330
+ *
1331
+ * Matching is always performed against the group's **ID** and **name**, regardless of how the group is represented in the session.
1332
+ *
1333
+ * @example Server Component
1334
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="is-user-in-group-rsc"
1335
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1336
+ *
1337
+ * export default async function AdminPanel() {
1338
+ * const isAdmin = await isUserInGroup(["admin"]);
1339
+ *
1340
+ * if (!isAdmin) {
1341
+ * return <div>Access Denied</div>;
1342
+ * }
1343
+ *
1344
+ * return <div>Admin Control Panel</div>;
1345
+ * }
1346
+ * ```
1347
+ *
1348
+ * @example Server Action
1349
+ * ```tsx:src/action.ts tab="Server Action" tab-group="is-user-in-group-rsc"
1350
+ * "use server";
1351
+ *
1352
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1353
+ *
1354
+ * export async function deletePostAction() {
1355
+ * const canDelete = await isUserInGroup(["admin", "editor"]);
1356
+ *
1357
+ * if (!canDelete) {
1358
+ * return { success: false };
1359
+ * }
1360
+ *
1361
+ * return { success: true };
1362
+ * }
1363
+ * ```
1364
+ *
1365
+ * @example API Handler
1366
+ * ```tsx:src/app/api/group-check/route.ts tab="API Handler" tab-group="is-user-in-group-rsc"
1367
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1368
+ * import { NextResponse } from "next/server";
1369
+ *
1370
+ * export const GET = async () => {
1371
+ * const allowed = await isUserInGroup(["admin", "editor"]);
1372
+ *
1373
+ * if (!allowed) {
1374
+ * return new NextResponse("Forbidden", { status: 403 });
1375
+ * }
1376
+ *
1377
+ * return NextResponse.json({ status: "success" });
1378
+ * };
1379
+ * ```
1380
+ *
1381
+ * @example Middleware
1382
+ * ```tsx:src/proxy.ts tab="Middleware" tab-group="is-user-in-group-rsc"
1383
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1384
+ * import { NextResponse } from "next/server";
1385
+ *
1386
+ * export default async function proxy() {
1387
+ * const isAdmin = await isUserInGroup(["admin"]);
1388
+ *
1389
+ * if (!isAdmin) {
1390
+ * return new NextResponse("User is not admin", { status: 403 });
1391
+ * }
1392
+ *
1393
+ * return NextResponse.next();
1394
+ * }
1395
+ * ```
1396
+ *
1397
+ * @param groups Group IDs or names to check against the user's group memberships.
1398
+ * @param options Optional configuration controlling how group membership is evaluated.
1399
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
1400
+ *
1401
+ * @category Functions
1402
+ */
1403
+ declare function isUserInGroup(groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
1404
+ /**
1405
+ * Checks group membership using an explicit Web or Next.js request.
1406
+ *
1407
+ * Use this overload when you already have access to a `Request` or `NextRequest` (for example, in Middleware or Route Handlers).
1408
+ *
1409
+ * @example Middleware (Request)
1410
+ * ```tsx:src/proxy.ts tab="Middleware (Request)" tab-group="is-user-in-group-request"
1411
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1412
+ * import { NextRequest, NextResponse } from "next/server";
1413
+ *
1414
+ * export default async function proxy(req: NextRequest) {
1415
+ * const isAdmin = await isUserInGroup(req, ["admin"]);
1416
+ *
1417
+ * if (!isAdmin) {
1418
+ * return new NextResponse("User is not admin", { status: 403 });
1419
+ * }
1420
+ *
1421
+ * return NextResponse.next();
1422
+ * }
1423
+ * ```
1424
+ *
1425
+ * @example API Handler (Request)
1426
+ * ```tsx:src/app/api/group-check/route.ts tab="API Handler (Request)" tab-group="is-user-in-group-request"
1427
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1428
+ * import { NextRequest, NextResponse } from "next/server";
1429
+ *
1430
+ * export const GET = async (req: NextRequest) => {
1431
+ * const isMember = await isUserInGroup(req, ["admin", "editor"]);
1432
+ *
1433
+ * return NextResponse.json({ isMember });
1434
+ * };
1435
+ * ```
1436
+ *
1437
+ * @param req Incoming request used to resolve authentication from cookies and headers.
1438
+ * @param groups Group IDs or names to check against the user's group memberships.
1439
+ * @param options Optional configuration controlling how group membership is evaluated.
1440
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
1441
+ *
1442
+ * @category Functions
1443
+ */
1444
+ declare function isUserInGroup(req: NextRequest$1 | Request, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
1445
+ /**
1446
+ * Checks group membership using an explicit request and response.
1447
+ *
1448
+ * Use this overload when you have already created a response and want refreshed authentication cookies or headers applied to it.
1449
+ *
1450
+ * @example Middleware (Response)
1451
+ * ```tsx:src/proxy.ts tab="Middleware (Response)" tab-group="is-user-in-group-response"
1452
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1453
+ * import { NextRequest, NextResponse } from "next/server";
1454
+ *
1455
+ * export default async function proxy(req: NextRequest) {
1456
+ * const res = NextResponse.next();
1457
+ *
1458
+ * const isAdmin = await isUserInGroup(req, res, ["admin"]);
1459
+ *
1460
+ * if (!isAdmin) {
1461
+ * return new NextResponse("User is not admin", { status: 403 });
1462
+ * }
1463
+ *
1464
+ * res.headers.set("x-user", "admin");
1465
+ *
1466
+ * return res;
1467
+ * }
1468
+ * ```
1469
+ *
1470
+ * @example API Handler (Response)
1471
+ * ```tsx:src/app/api/group-check/route.ts tab="API Handler (Response)" tab-group="is-user-in-group-response"
1472
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1473
+ * import { NextRequest, NextResponse } from "next/server";
1474
+ *
1475
+ * export const GET = async (req: NextRequest) => {
1476
+ * const res = new NextResponse("Restricted Content");
1477
+ *
1478
+ * const allowed = await isUserInGroup(req, res, ["admin"]);
1479
+ *
1480
+ * if (!allowed) {
1481
+ * return new NextResponse("Not Allowed", res);
1482
+ * }
1483
+ *
1484
+ * return res;
1485
+ * };
1486
+ * ```
1487
+ *
1488
+ * @param req Incoming request used to resolve authentication from cookies and headers.
1489
+ * @param res Existing response to update with refreshed authentication cookies or headers when required.
1490
+ * @param groups Group IDs or names to check against the user's group memberships.
1491
+ * @param options Optional configuration controlling how group membership is evaluated.
1492
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
1493
+ *
1494
+ * @category Functions
1495
+ */
1496
+ declare function isUserInGroup(req: NextRequest$1 | Request, res: NextResponse$1 | Response, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
1497
+ /**
1498
+ * Checks group membership in the Pages Router or Node.js runtime.
1499
+ *
1500
+ * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.
1501
+ *
1502
+ * @example Pages Router (Pages)
1503
+ * ```tsx:src/pages/index.tsx tab="Pages Router (Pages)" tab-group="is-user-in-group-pages"
1504
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1505
+ * import { GetServerSideProps } from "next";
1506
+ *
1507
+ * type Props = {
1508
+ * isAdmin: boolean;
1509
+ * };
1510
+ *
1511
+ * export default function Home({ isAdmin }: Props) {
1512
+ * return <div>User is admin: {isAdmin.toString()}</div>;
1513
+ * }
1514
+ *
1515
+ * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
1516
+ * const isAdmin = await isUserInGroup(ctx.req, ctx.res, ["admin"]);
1517
+ *
1518
+ * return {
1519
+ * props: {
1520
+ * isAdmin
1521
+ * }
1522
+ * };
1523
+ * };
1524
+ * ```
1525
+ *
1526
+ * @example Pages Router (API)
1527
+ * ```tsx:src/pages/api/group-check.ts tab="Pages Router (API)" tab-group="is-user-in-group-pages"
1528
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1529
+ * import { NextApiRequest, NextApiResponse } from "next";
1530
+ *
1531
+ * export default async function handler(
1532
+ * req: NextApiRequest,
1533
+ * res: NextApiResponse
1534
+ * ) {
1535
+ * const isAdmin = await isUserInGroup(req, res, ["admin"]);
1536
+ *
1537
+ * if (!isAdmin) {
1538
+ * return res.status(403).json({ error: "Forbidden" });
1539
+ * }
1540
+ *
1541
+ * res.status(200).json({ message: "Welcome Admin" });
1542
+ * }
1543
+ * ```
1544
+ *
1545
+ * @param req Incoming Node.js request used to resolve authentication from cookies.
1546
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
1547
+ * @param groups Group IDs or names to check against the user's group memberships.
1548
+ * @param options Optional configuration controlling how group membership is evaluated.
1549
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
1550
+ *
1551
+ * @category Functions
1552
+ */
1553
+ declare function isUserInGroup(req: NextApiRequest$1 | IncomingMessage, res: NextApiResponse$1 | ServerResponse<IncomingMessage>, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
1554
+ /**
1555
+ * Redirects the user to the sign-in flow.
1556
+ *
1557
+ * > **App Router only**. Intended for use in Server Components, Route Handlers, and Server Actions.
1558
+ *
1559
+ * This helper performs a server-side redirect to the configured sign-in route. Execution does not continue after the redirect is triggered.
1560
+ *
1561
+ * @example Server Component
1562
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="redirect-to-sign-in"
1563
+ * import { isUserInGroup, redirectToSignIn } from "@monocloud/auth-nextjs";
1564
+ *
1565
+ * export default async function Home() {
1566
+ * const allowed = await isUserInGroup(["admin"]);
1567
+ *
1568
+ * if (!allowed) {
1569
+ * await redirectToSignIn({ returnUrl: "/home" });
1570
+ * }
1571
+ *
1572
+ * return <>You are signed in.</>;
1573
+ * }
1574
+ * ```
1575
+ *
1576
+ * @example Server Action
1577
+ * ```tsx:src/action.ts tab="Server Action" tab-group="redirect-to-sign-in"
1578
+ * "use server";
1579
+ *
1580
+ * import { getSession, redirectToSignIn } from "@monocloud/auth-nextjs";
1581
+ *
1582
+ * export async function protectedAction() {
1583
+ * const session = await getSession();
1584
+ *
1585
+ * if (!session) {
1586
+ * await redirectToSignIn();
1587
+ * }
1588
+ *
1589
+ * return { data: "Sensitive Data" };
1590
+ * }
1591
+ * ```
1592
+ *
1593
+ * @example API Handler
1594
+ * ```tsx:src/app/api/protected/route.ts tab="API Handler" tab-group="redirect-to-sign-in"
1595
+ * import { getSession, redirectToSignIn } from "@monocloud/auth-nextjs";
1596
+ * import { NextResponse } from "next/server";
1597
+ *
1598
+ * export const GET = async () => {
1599
+ * const session = await getSession();
1600
+ *
1601
+ * if (!session) {
1602
+ * await redirectToSignIn({
1603
+ * returnUrl: "/dashboard",
1604
+ * });
1605
+ * }
1606
+ *
1607
+ * return NextResponse.json({ data: "Protected content" });
1608
+ * };
1609
+ * ```
1610
+ *
1611
+ * @param options Optional configuration for the redirect, such as `returnUrl` or additional sign-in parameters.
1612
+ * @returns Never resolves. Triggers a redirect to the sign-in flow.
1613
+ *
1614
+ * @category Functions
1615
+ */
1616
+ declare function redirectToSignIn(options?: RedirectToSignInOptions): Promise<void>;
1617
+ /**
1618
+ * Redirects the user to the sign-out flow.
1619
+ *
1620
+ * > **App Router only**. Intended for use in Server Components, Route Handlers, and Server Actions.
1621
+ *
1622
+ * This helper performs a server-side redirect to the configured sign-out route. Execution does not continue after the redirect is triggered.
1623
+ *
1624
+ * @example Server Component
1625
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="redirect-to-sign-out"
1626
+ * import { getSession, redirectToSignOut } from "@monocloud/auth-nextjs";
1627
+ *
1628
+ * export default async function Page() {
1629
+ * const session = await getSession();
1630
+ *
1631
+ * // Example: Force sign-out if a specific condition is met (e.g., account suspended)
1632
+ * if (session?.user.isSuspended) {
1633
+ * await redirectToSignOut();
1634
+ * }
1635
+ *
1636
+ * return <>Welcome User</>;
1637
+ * }
1638
+ * ```
1639
+ *
1640
+ * @example Server Action
1641
+ * ```tsx:src/action.ts tab="Server Action" tab-group="redirect-to-sign-out"
1642
+ * "use server";
1643
+ *
1644
+ * import { getSession, redirectToSignOut } from "@monocloud/auth-nextjs";
1645
+ *
1646
+ * export async function signOutAction() {
1647
+ * const session = await getSession();
1648
+ *
1649
+ * if (session) {
1650
+ * await redirectToSignOut();
1651
+ * }
1652
+ * }
1653
+ * ```
1654
+ *
1655
+ * @example API Handler
1656
+ * ```tsx:src/app/api/signout/route.ts tab="API Handler" tab-group="redirect-to-sign-out"
1657
+ * import { getSession, redirectToSignOut } from "@monocloud/auth-nextjs";
1658
+ * import { NextResponse } from "next/server";
1659
+ *
1660
+ * export const GET = async () => {
1661
+ * const session = await getSession();
1662
+ *
1663
+ * if (session) {
1664
+ * await redirectToSignOut({
1665
+ * postLogoutRedirectUri: "/goodbye",
1666
+ * });
1667
+ * }
1668
+ *
1669
+ * return NextResponse.json({ status: "already_signed_out" });
1670
+ * };
1671
+ * ```
1672
+ *
1673
+ * @param options Optional configuration for the redirect, such as `postLogoutRedirectUri` or additional sign-out parameters.
1674
+ * @returns Never resolves. Triggers a redirect to the sign-out flow.
1675
+ *
1676
+ * @category Functions
1677
+ */
1678
+ declare function redirectToSignOut(options?: RedirectToSignOutOptions): Promise<void>;
1679
+ //#endregion
1680
+ export { type AccessToken, type Address, type AppOnError, type AppRouterApiHandlerFn, type AppRouterApiOnAccessDeniedHandler, type AppRouterApiOnGroupAccessDeniedHandler, type AppRouterContext, type AppRouterPageHandler, type ApplicationState, type Authenticators, type AuthorizationParams, type CodeChallengeMethod, type CustomProtectedRouteMatcher, type DisplayOptions, type ExtraAuthParams, type GetTokensOptions, type Group, type GroupOptions, type IdTokenClaims, type Indicator, type IsUserInGroupOptions, type Jwk, MonoCloudAuthBaseError, type MonoCloudAuthHandler, type MonoCloudAuthOptions, type MonoCloudCookieOptions, MonoCloudHttpError, type MonoCloudMiddlewareOptions, MonoCloudNextClient, MonoCloudOPError, type MonoCloudOptions, type MonoCloudRequest, type MonoCloudRoutes, type MonoCloudSession, type MonoCloudSessionOptions, type MonoCloudSessionOptionsBase, type MonoCloudSessionStore, type MonoCloudStateOptions, type MonoCloudStatePartialOptions, MonoCloudTokenError, type MonoCloudTokens, type MonoCloudUser, MonoCloudValidationError, type NextMiddlewareOnAccessDenied, type NextMiddlewareOnGroupAccessDenied, type NextMiddlewareResult, type OnBackChannelLogout, type OnError, type OnSessionCreating, type OnSetApplicationState, type PageOnError, type PageRouterApiOnAccessDeniedHandler, type PageRouterApiOnGroupAccessDeniedHandler, type Prompt, type ProtectApiAppOptions, type ProtectApiPageOptions, type ProtectAppPageOptions, type ProtectOptions, type ProtectPagePageOnAccessDeniedType, type ProtectPagePageOnGroupAccessDeniedType, type ProtectPagePageOptions, type ProtectPagePageReturnType, type ProtectedAppServerComponent, type ProtectedRouteMatcher, type ProtectedRoutes, type RedirectToSignInOptions, type RedirectToSignOutOptions, type ResponseModes, type ResponseTypes, type SameSiteValues, type SecurityAlgorithms, type SessionLifetime, type UserinfoResponse, authMiddleware, getSession, getTokens, isAuthenticated, isUserInGroup, monoCloudAuth, protect, protectApi, protectPage, redirectToSignIn, redirectToSignOut };
1970
1681
  //# sourceMappingURL=index.d.mts.map