@monocloud/auth-nextjs 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +1 -1
  2. package/dist/{chunk-C0xms8kb.cjs → _virtual/_rolldown/runtime.cjs} +1 -6
  3. package/dist/client/index.cjs +3 -2
  4. package/dist/client/index.d.mts +3 -203
  5. package/dist/client/index.mjs +2 -1
  6. package/dist/{protect-client-page-BdsnH8gs.cjs → client/protect-client-page.cjs} +9 -112
  7. package/dist/client/protect-client-page.cjs.map +1 -0
  8. package/dist/client/protect-client-page.d.mts +123 -0
  9. package/dist/{protect-client-page-BFVskb3X.mjs → client/protect-client-page.mjs} +5 -91
  10. package/dist/client/protect-client-page.mjs.map +1 -0
  11. package/dist/client/use-auth.cjs +96 -0
  12. package/dist/client/use-auth.cjs.map +1 -0
  13. package/dist/client/use-auth.d.mts +84 -0
  14. package/dist/client/use-auth.mjs +94 -0
  15. package/dist/client/use-auth.mjs.map +1 -0
  16. package/dist/components/client/index.cjs +4 -156
  17. package/dist/components/client/index.d.mts +3 -189
  18. package/dist/components/client/index.mjs +3 -153
  19. package/dist/components/client/protected.cjs +89 -0
  20. package/dist/components/client/protected.cjs.map +1 -0
  21. package/dist/components/client/protected.d.mts +114 -0
  22. package/dist/components/client/protected.mjs +87 -0
  23. package/dist/components/client/protected.mjs.map +1 -0
  24. package/dist/components/client/redirect-to-signin.cjs +77 -0
  25. package/dist/components/client/redirect-to-signin.cjs.map +1 -0
  26. package/dist/components/client/redirect-to-signin.d.mts +78 -0
  27. package/dist/components/client/redirect-to-signin.mjs +76 -0
  28. package/dist/components/client/redirect-to-signin.mjs.map +1 -0
  29. package/dist/components/index.cjs +6 -168
  30. package/dist/components/index.d.mts +4 -188
  31. package/dist/components/index.mjs +4 -164
  32. package/dist/components/signin.cjs +63 -0
  33. package/dist/components/signin.cjs.map +1 -0
  34. package/dist/components/signin.d.mts +72 -0
  35. package/dist/components/signin.mjs +61 -0
  36. package/dist/components/signin.mjs.map +1 -0
  37. package/dist/components/signout.cjs +49 -0
  38. package/dist/components/signout.cjs.map +1 -0
  39. package/dist/components/signout.d.mts +55 -0
  40. package/dist/components/signout.mjs +47 -0
  41. package/dist/components/signout.mjs.map +1 -0
  42. package/dist/components/signup.cjs +67 -0
  43. package/dist/components/signup.cjs.map +1 -0
  44. package/dist/components/signup.d.mts +70 -0
  45. package/dist/components/signup.mjs +65 -0
  46. package/dist/components/signup.mjs.map +1 -0
  47. package/dist/index.cjs +15 -1136
  48. package/dist/index.d.mts +5 -1681
  49. package/dist/index.mjs +4 -1125
  50. package/dist/initialize.cjs +284 -0
  51. package/dist/initialize.cjs.map +1 -0
  52. package/dist/initialize.d.mts +1383 -0
  53. package/dist/initialize.mjs +274 -0
  54. package/dist/initialize.mjs.map +1 -0
  55. package/dist/monocloud-next-client.cjs +600 -0
  56. package/dist/monocloud-next-client.cjs.map +1 -0
  57. package/dist/monocloud-next-client.d.mts +330 -0
  58. package/dist/monocloud-next-client.mjs +599 -0
  59. package/dist/monocloud-next-client.mjs.map +1 -0
  60. package/dist/requests/monocloud-app-router-request.cjs +32 -0
  61. package/dist/requests/monocloud-app-router-request.cjs.map +1 -0
  62. package/dist/requests/monocloud-app-router-request.mjs +31 -0
  63. package/dist/requests/monocloud-app-router-request.mjs.map +1 -0
  64. package/dist/requests/monocloud-cookie-request.cjs +22 -0
  65. package/dist/requests/monocloud-cookie-request.cjs.map +1 -0
  66. package/dist/requests/monocloud-cookie-request.mjs +21 -0
  67. package/dist/requests/monocloud-cookie-request.mjs.map +1 -0
  68. package/dist/requests/monocloud-page-router-request.cjs +37 -0
  69. package/dist/requests/monocloud-page-router-request.cjs.map +1 -0
  70. package/dist/requests/monocloud-page-router-request.mjs +36 -0
  71. package/dist/requests/monocloud-page-router-request.mjs.map +1 -0
  72. package/dist/responses/monocloud-app-router-response.cjs +67 -0
  73. package/dist/responses/monocloud-app-router-response.cjs.map +1 -0
  74. package/dist/responses/monocloud-app-router-response.mjs +66 -0
  75. package/dist/responses/monocloud-app-router-response.mjs.map +1 -0
  76. package/dist/responses/monocloud-cookie-response.cjs +20 -0
  77. package/dist/responses/monocloud-cookie-response.cjs.map +1 -0
  78. package/dist/responses/monocloud-cookie-response.mjs +19 -0
  79. package/dist/responses/monocloud-cookie-response.mjs.map +1 -0
  80. package/dist/responses/monocloud-page-router-response.cjs +54 -0
  81. package/dist/responses/monocloud-page-router-response.cjs.map +1 -0
  82. package/dist/responses/monocloud-page-router-response.mjs +53 -0
  83. package/dist/responses/monocloud-page-router-response.mjs.map +1 -0
  84. package/dist/{types-ClljFIvK.d.mts → types.d.mts} +2 -2
  85. package/dist/utils.cjs +89 -0
  86. package/dist/utils.cjs.map +1 -0
  87. package/dist/utils.mjs +80 -0
  88. package/dist/utils.mjs.map +1 -0
  89. package/package.json +3 -3
  90. package/dist/components/client/index.cjs.map +0 -1
  91. package/dist/components/client/index.mjs.map +0 -1
  92. package/dist/components/index.cjs.map +0 -1
  93. package/dist/components/index.mjs.map +0 -1
  94. package/dist/index.cjs.map +0 -1
  95. package/dist/index.mjs.map +0 -1
  96. package/dist/protect-client-page-BFVskb3X.mjs.map +0 -1
  97. package/dist/protect-client-page-BdsnH8gs.cjs.map +0 -1
@@ -0,0 +1,1383 @@
1
+ import { AppRouterApiHandlerFn, AppRouterPageHandler, IsUserInGroupOptions, MonoCloudAuthHandler, MonoCloudAuthOptions, MonoCloudMiddlewareOptions, NextMiddlewareResult, ProtectApiAppOptions, ProtectApiPageOptions, ProtectAppPageOptions, ProtectOptions, ProtectPagePageOptions, ProtectPagePageReturnType, ProtectedAppServerComponent, RedirectToSignInOptions, RedirectToSignOutOptions } from "./types.mjs";
2
+ import { GetSessionOptions, GetTokensOptions, MonoCloudTokens } from "@monocloud/auth-node-core";
3
+ import { NextFetchEvent, NextMiddleware, NextProxy, NextRequest, NextResponse } from "next/server";
4
+ import { ParsedUrlQuery } from "node:querystring";
5
+ import { MonoCloudSession as MonoCloudSession$1 } from "@monocloud/auth-core";
6
+ import { IncomingMessage, ServerResponse } from "node:http";
7
+ import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
8
+
9
+ //#region src/initialize.d.ts
10
+ /**
11
+ * Creates a Next.js catch-all auth route handler (Pages Router and App Router) for the built-in routes (`/signin`, `/callback`, `/userinfo`, `/signout`).
12
+ *
13
+ * Mount this handler on a catch-all route (e.g. `/api/auth/[...monocloud]`).
14
+ *
15
+ * > 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.
16
+ *
17
+ * @example App Router
18
+ * ```tsx:src/app/api/auth/[...monocloud]/route.ts tab="App Router" tab-group="monoCloudAuth"
19
+ * import { monoCloudAuth } from "@monocloud/auth-nextjs";
20
+ *
21
+ * export const GET = monoCloudAuth();
22
+ *```
23
+ *
24
+ * @example App Router (Response)
25
+ * ```tsx:src/app/api/auth/[...monocloud]/route.ts tab="App Router (Response)" tab-group="monoCloudAuth"
26
+ * import { monoCloudAuth } from "@monocloud/auth-nextjs";
27
+ * import { NextRequest, NextResponse } from "next/server";
28
+ *
29
+ * export const GET = (req: NextRequest) => {
30
+ * const authHandler = monoCloudAuth();
31
+ *
32
+ * const res = new NextResponse();
33
+ *
34
+ * res.cookies.set("last_auth_requested", `${Date.now()}`);
35
+ *
36
+ * return authHandler(req, res);
37
+ * };
38
+ * ```
39
+ *
40
+ * @example Pages Router
41
+ * ```tsx:src/pages/api/auth/[...monocloud].ts tab="Pages Router" tab-group="monoCloudAuth"
42
+ * import { monoCloudAuth } from "@monocloud/auth-nextjs";
43
+ *
44
+ * export default monoCloudAuth();
45
+ *```
46
+ *
47
+ * @example Pages Router (Response)
48
+ * ```tsx:src/pages/api/auth/[...monocloud].ts tab="Pages Router (Response)" tab-group="monoCloudAuth"
49
+ * import { monoCloudAuth } from "@monocloud/auth-nextjs";
50
+ * import { NextApiRequest, NextApiResponse } from "next";
51
+ *
52
+ * export default function handler(req: NextApiRequest, res: NextApiResponse) {
53
+ * const authHandler = monoCloudAuth();
54
+ *
55
+ * res.setHeader("last_auth_requested", `${Date.now()}`);
56
+ *
57
+ * return authHandler(req, res);
58
+ * }
59
+ * ```
60
+ *
61
+ * @param options Optional configuration for the auth handler.
62
+ * @returns Returns a Next.js-compatible handler for App Router route handlers or Pages Router API routes.
63
+ *
64
+ * @category Functions
65
+ */
66
+ declare function monoCloudAuth(options?: MonoCloudAuthOptions): MonoCloudAuthHandler;
67
+ /**
68
+ * Creates a Next.js authentication middleware that protects routes.
69
+ *
70
+ * By default, all routes matched by `config.matcher` are protected unless configured otherwise.
71
+ *
72
+ * @example Protect All Routes
73
+ * ```tsx:src/proxy.ts tab="Protect All Routes" tab-group="auth-middleware"
74
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
75
+ *
76
+ * export default authMiddleware();
77
+ *
78
+ * export const config = {
79
+ * matcher: [
80
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
81
+ * ],
82
+ * };
83
+ * ```
84
+ *
85
+ * @example Protect Selected Routes
86
+ * ```tsx:src/proxy.ts tab="Protect Selected Routes" tab-group="auth-middleware"
87
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
88
+ *
89
+ * export default authMiddleware({
90
+ * protectedRoutes: ["/api/admin", "^/api/protected(/.*)?$"],
91
+ * });
92
+ *
93
+ * export const config = {
94
+ * matcher: [
95
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
96
+ * ],
97
+ * };
98
+ *```
99
+ *
100
+ * @example No Protected Routes
101
+ * ```tsx:src/proxy.ts tab="No Protected Routes" tab-group="auth-middleware"
102
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
103
+ *
104
+ * export default authMiddleware({
105
+ * protectedRoutes: [],
106
+ * });
107
+ *
108
+ * export const config = {
109
+ * matcher: [
110
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
111
+ * ],
112
+ * };
113
+ * ```
114
+ *
115
+ * @example Dynamic
116
+ * ```tsx:src/proxy.ts tab="Dynamic" tab-group="auth-middleware"
117
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
118
+ *
119
+ * export default authMiddleware({
120
+ * protectedRoutes: (req) => {
121
+ * return req.nextUrl.pathname.startsWith("/api/protected");
122
+ * },
123
+ * });
124
+ *
125
+ * export const config = {
126
+ * matcher: [
127
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
128
+ * ],
129
+ * };
130
+ * ```
131
+ *
132
+ * @example Group Protection
133
+ * ```tsx:src/proxy.ts tab="Group Protection" tab-group="auth-middleware"
134
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
135
+ *
136
+ * export default authMiddleware({
137
+ * protectedRoutes: [
138
+ * {
139
+ * groups: ["admin", "editor", "537e7c3d-a442-4b5b-b308-30837aa045a4"],
140
+ * routes: ["/internal", "/api/internal(.*)"],
141
+ * },
142
+ * ],
143
+ * });
144
+ *
145
+ * export const config = {
146
+ * matcher: [
147
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
148
+ * ],
149
+ * };
150
+ * ```
151
+ *
152
+ * @param options Optional configuration that controls how authentication is enforced (for example, redirect behavior, route matching, or custom handling of unauthenticated requests).
153
+ * @returns Returns a Next.js middleware result, such as a `NextResponse`, `redirect`, or `undefined` to continue processing.
154
+ *
155
+ * @category Functions
156
+ */
157
+ declare function authMiddleware(options?: MonoCloudMiddlewareOptions): NextMiddleware | NextProxy;
158
+ /**
159
+ * Executes the authentication middleware manually.
160
+ *
161
+ * Intended for advanced scenarios where the middleware is composed within custom logic.
162
+ *
163
+ * @example Composing with custom middleware
164
+ *
165
+ * ```tsx:src/proxy.ts title="Composing with custom middleware"
166
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
167
+ * import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
168
+ *
169
+ * export default function customMiddleware(req: NextRequest, evt: NextFetchEvent) {
170
+ * if (req.nextUrl.pathname.startsWith("/api/protected")) {
171
+ * return authMiddleware(req, evt);
172
+ * }
173
+ *
174
+ * return NextResponse.next();
175
+ * }
176
+ *
177
+ * export const config = {
178
+ * matcher: [
179
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
180
+ * ],
181
+ * };
182
+ * ```
183
+ *
184
+ * @param request Incoming Next.js middleware request used to resolve authentication state.
185
+ * @param event Next.js middleware event providing lifecycle hooks such as `waitUntil`.
186
+ * @returns Returns a Next.js middleware result (`NextResponse`, redirect, or `undefined` to continue processing).
187
+ *
188
+ * @category Functions
189
+ */
190
+ declare function authMiddleware(request: NextRequest, event: NextFetchEvent): Promise<NextMiddlewareResult> | NextMiddlewareResult;
191
+ /**
192
+ * Retrieves the current user's session using the active server request context.
193
+ *
194
+ * Intended for Server Components, Server Actions, Route Handlers, and Middleware where the request is implicitly available.
195
+ *
196
+ * @example Server Component
197
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="session-ssr"
198
+ * import { getSession } from "@monocloud/auth-nextjs";
199
+ *
200
+ * export default async function Home() {
201
+ * const session = await getSession();
202
+ *
203
+ * return <div>{session?.user.name}</div>;
204
+ * }
205
+ * ```
206
+ *
207
+ * @example Server Action
208
+ * ```tsx:src/action.ts tab="Server Action" tab-group="session-ssr"
209
+ * "use server";
210
+ *
211
+ * import { getSession } from "@monocloud/auth-nextjs";
212
+ *
213
+ * export async function getUserAction() {
214
+ * const session = await getSession();
215
+ *
216
+ * return { name: session?.user.name };
217
+ * }
218
+ * ```
219
+ *
220
+ * @example API Handler
221
+ * ```tsx:src/app/api/user/route.ts tab="API Handler" tab-group="session-ssr"
222
+ * import { getSession } from "@monocloud/auth-nextjs";
223
+ * import { NextResponse } from "next/server";
224
+ *
225
+ * export const GET = async () => {
226
+ * const session = await getSession();
227
+ *
228
+ * return NextResponse.json({ name: session?.user.name });
229
+ * };
230
+ * ```
231
+ *
232
+ * @example Middleware
233
+ * ```tsx:src/proxy.ts tab="Middleware" tab-group="session-ssr"
234
+ * import { getSession } from "@monocloud/auth-nextjs";
235
+ * import { NextResponse } from "next/server";
236
+ *
237
+ * export default async function proxy() {
238
+ * const session = await getSession();
239
+ *
240
+ * if (!session) {
241
+ * return new NextResponse("User not signed in", { status: 401 });
242
+ * }
243
+ *
244
+ * return NextResponse.next();
245
+ * }
246
+ * ```
247
+ * @param options Optional configuration to control session retrieval behavior.
248
+ * @returns Returns the resolved session, or `undefined` if none exists.
249
+ *
250
+ * @category Functions
251
+ */
252
+ declare function getSession(options?: GetSessionOptions): Promise<MonoCloudSession$1 | undefined>;
253
+ /**
254
+ * Retrieves the current user's session using an explicit Web or Next.js request.
255
+ *
256
+ * Use this overload when you already have access to a `Request` or `NextRequest` (for example in Middleware or Route Handlers).
257
+ *
258
+ * @example Middleware (Request)
259
+ * ```tsx:src/proxy.ts tab="Middleware (Request)" tab-group="session-route-handler"
260
+ * import { getSession } from "@monocloud/auth-nextjs";
261
+ * import { NextRequest, NextResponse } from "next/server";
262
+ *
263
+ * export default async function proxy(req: NextRequest) {
264
+ * const session = await getSession(req);
265
+ *
266
+ * if (!session) {
267
+ * return new NextResponse("User not signed in", { status: 401 });
268
+ * }
269
+ *
270
+ * return NextResponse.next();
271
+ * }
272
+ * ```
273
+ *
274
+ * @example API Handler (Request)
275
+ * ```tsx:src/app/api/user/route.ts tab="API Handler (Request)" tab-group="session-route-handler"
276
+ * import { getSession } from "@monocloud/auth-nextjs";
277
+ * import { NextRequest, NextResponse } from "next/server";
278
+ *
279
+ * export const GET = async (req: NextRequest) => {
280
+ * const session = await getSession(req);
281
+ *
282
+ * return NextResponse.json({ name: session?.user.name });
283
+ * };
284
+ * ```
285
+ *
286
+ * @param req Incoming request used to read authentication cookies and headers to resolve the current user's session.
287
+ * @param options Optional configuration to control session retrieval behavior.
288
+ * @returns Returns the resolved session, or `undefined` if none exists.
289
+ *
290
+ * @category Functions
291
+ */
292
+ declare function getSession(req: NextRequest | Request, options?: GetSessionOptions): Promise<MonoCloudSession$1 | undefined>;
293
+ /**
294
+ * Retrieves the current user's session using explicit request and response objects.
295
+ *
296
+ * Use this overload when you have already created a response and want refreshed authentication cookies or headers applied to it.
297
+ *
298
+ * @example Middleware (Response)
299
+ * ```tsx:src/proxy.ts tab="Middleware (Response)" tab-group="session-route-handler"
300
+ * import { getSession } from "@monocloud/auth-nextjs";
301
+ * import { NextRequest, NextResponse } from "next/server";
302
+ *
303
+ * export default async function proxy(req: NextRequest) {
304
+ * const res = NextResponse.next();
305
+ *
306
+ * const session = await getSession(req, res);
307
+ *
308
+ * if (!session) {
309
+ * return new NextResponse("User not signed in", { status: 401 });
310
+ * }
311
+ *
312
+ * res.headers.set("x-auth-status", "active");
313
+ *
314
+ * return res;
315
+ * }
316
+ * ```
317
+ *
318
+ * @example API Handler (Response)
319
+ * ```tsx:src/app/api/user/route.ts tab="API Handler (Response)" tab-group="session-route-handler"
320
+ * import { getSession } from "@monocloud/auth-nextjs";
321
+ * import { NextRequest, NextResponse } from "next/server";
322
+ *
323
+ * export const GET = async (req: NextRequest) => {
324
+ * const res = new NextResponse("YOUR CUSTOM RESPONSE");
325
+ *
326
+ * const session = await getSession(req, res);
327
+ *
328
+ * if (session?.user) {
329
+ * res.cookies.set("something", "important");
330
+ * }
331
+ *
332
+ * return res;
333
+ * };
334
+ * ```
335
+ *
336
+ * @param req Incoming request used to read authentication cookies and headers to resolve the current user's session.
337
+ * @param res Response object to update when session resolution requires refreshed authentication cookies or headers.
338
+ * @param options Optional configuration to control session retrieval behavior.
339
+ * @returns Returns the resolved session, or `undefined` if none exists.
340
+ *
341
+ * @category Functions
342
+ */
343
+ declare function getSession(req: NextRequest | Request, res: NextResponse | Response, options?: GetSessionOptions): Promise<MonoCloudSession$1 | undefined>;
344
+ /**
345
+ * Retrieves the current user's session in the Pages Router or Node.js runtime.
346
+ *
347
+ * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.
348
+ *
349
+ * @example Pages Router (Pages)
350
+ * ```tsx:src/pages/index.tsx tab="Pages Router (Pages)" tab-group="session-pages"
351
+ * import { getSession, MonoCloudSession } from "@monocloud/auth-nextjs";
352
+ * import { GetServerSideProps } from "next";
353
+ *
354
+ * type Props = {
355
+ * session?: MonoCloudSession;
356
+ * };
357
+ *
358
+ * export default function Home({ session }: Props) {
359
+ * return <pre>Session: {JSON.stringify(session, null, 2)}</pre>;
360
+ * }
361
+ *
362
+ * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
363
+ * const session = await getSession(ctx.req, ctx.res);
364
+ *
365
+ * return {
366
+ * props: {
367
+ * session
368
+ * }
369
+ * };
370
+ * };
371
+ * ```
372
+ * @example Pages Router (API)
373
+ * ```tsx:src/pages/api/user.ts tab="Pages Router (API)" tab-group="session-pages"
374
+ * import { getSession } from "@monocloud/auth-nextjs";
375
+ * import { NextApiRequest, NextApiResponse } from "next";
376
+ *
377
+ * export default async function handler(
378
+ * req: NextApiRequest,
379
+ * res: NextApiResponse
380
+ * ) {
381
+ * const session = await getSession(req, res);
382
+ *
383
+ * res.status(200).json({ name: session?.user.name });
384
+ * }
385
+ * ```
386
+ *
387
+ * @param req Incoming Node.js request used to read authentication cookies and resolve the current user's session.
388
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
389
+ * @param options Optional configuration to control session retrieval behavior.
390
+ * @returns Returns the resolved session, or `undefined` if none exists.
391
+ *
392
+ * @category Functions
393
+ */
394
+ declare function getSession(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>, options?: GetSessionOptions): Promise<MonoCloudSession$1 | undefined>;
395
+ /**
396
+ * Retrieves the current user's tokens using the active server request context.
397
+ *
398
+ * @example Server Component
399
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="tokens-ssr"
400
+ * import { getTokens } from "@monocloud/auth-nextjs";
401
+ *
402
+ * export default async function Home() {
403
+ * const tokens = await getTokens();
404
+ *
405
+ * return <div>Expired: {tokens.isExpired.toString()}</div>;
406
+ * }
407
+ * ```
408
+ *
409
+ * @example Server Action
410
+ * ```tsx:src/action.ts tab="Server Action" tab-group="tokens-ssr"
411
+ * "use server";
412
+ *
413
+ * import { getTokens } from "@monocloud/auth-nextjs";
414
+ *
415
+ * export async function getExpiredAction() {
416
+ * const tokens = await getTokens();
417
+ *
418
+ * return { expired: tokens.isExpired };
419
+ * }
420
+ * ```
421
+ *
422
+ * @example API Handler
423
+ * ```tsx:src/app/api/tokens/route.ts tab="API Handler" tab-group="tokens-ssr"
424
+ * import { getTokens } from "@monocloud/auth-nextjs";
425
+ * import { NextResponse } from "next/server";
426
+ *
427
+ * export const GET = async () => {
428
+ * const tokens = await getTokens();
429
+ *
430
+ * return NextResponse.json({ expired: tokens.isExpired });
431
+ * };
432
+ * ```
433
+ *
434
+ * @example Middleware
435
+ * ```tsx:src/proxy.ts tab="Middleware" tab-group="tokens-ssr"
436
+ * import { getTokens } from "@monocloud/auth-nextjs";
437
+ * import { NextResponse } from "next/server";
438
+ *
439
+ * export default async function proxy() {
440
+ * const tokens = await getTokens();
441
+ *
442
+ * if (tokens.isExpired) {
443
+ * return new NextResponse("Tokens expired", { status: 401 });
444
+ * }
445
+ *
446
+ * return NextResponse.next();
447
+ * }
448
+ * ```
449
+ *
450
+ * @example Refresh the default token
451
+ *
452
+ * The **default token** is the access token associated with your default authorization parameters:
453
+ * - Scopes: `MONOCLOUD_AUTH_SCOPES` or `options.defaultAuthParams.scopes`
454
+ * - Resource: `MONOCLOUD_AUTH_RESOURCE` or `options.defaultAuthParams.resource`
455
+ *
456
+ * 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`.
457
+ *
458
+ * ```tsx:src/app/page.tsx title="Refresh default token"
459
+ * import { getTokens } from "@monocloud/auth-nextjs";
460
+ * import { NextResponse } from "next/server";
461
+ *
462
+ * export const GET = async () => {
463
+ * // Forces a refresh of the default token
464
+ * const tokens = await getTokens({ forceRefresh: true });
465
+ *
466
+ * return NextResponse.json({ accessToken: tokens?.accessToken });
467
+ * };
468
+ * ```
469
+ *
470
+ * @example Request an access token for resource(s)
471
+ *
472
+ * Use `resource` and `scopes` to request an access token for one or more resources.
473
+ *
474
+ * > 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).
475
+ *
476
+ * ```tsx:src/app/page.tsx title="Request a new access token for resource(s)"
477
+ * import { getTokens } from "@monocloud/auth-nextjs";
478
+ * import { NextResponse } from "next/server";
479
+ *
480
+ * export const GET = async () => {
481
+ * const tokens = await getTokens({
482
+ * resource: "https://first.example.com https://second.example.com",
483
+ * scopes: "read:first read:second shared",
484
+ * });
485
+ *
486
+ * return NextResponse.json({ accessToken: tokens?.accessToken });
487
+ * };
488
+ * ```
489
+ *
490
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
491
+ * @returns The current user's tokens, refreshed if necessary.
492
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
493
+ *
494
+ * @category Functions
495
+ */
496
+ declare function getTokens(options?: GetTokensOptions): Promise<MonoCloudTokens>;
497
+ /**
498
+ * Retrieves the current user's tokens using an explicit Web or Next.js request.
499
+ *
500
+ * Use this overload when you already have access to a `Request` or `NextRequest` (for example, in Middleware or Route Handlers).
501
+ *
502
+ * @example Middleware (Request)
503
+ * ```tsx:src/proxy.ts tab="Middleware (Request)" tab-group="tokens-route-handler-request"
504
+ * import { getTokens } from "@monocloud/auth-nextjs";
505
+ * import { NextRequest, NextResponse } from "next/server";
506
+ *
507
+ * export default async function proxy(req: NextRequest) {
508
+ * const tokens = await getTokens(req);
509
+ *
510
+ * if (tokens.isExpired) {
511
+ * return new NextResponse("Tokens expired", { status: 401 });
512
+ * }
513
+ *
514
+ * return NextResponse.next();
515
+ * }
516
+ * ```
517
+ *
518
+ * @example API Handler (Request)
519
+ * ```tsx:src/app/api/tokens/route.ts tab="API Handler (Request)" tab-group="tokens-route-handler-request"
520
+ * import { getTokens } from "@monocloud/auth-nextjs";
521
+ * import { NextRequest, NextResponse } from "next/server";
522
+ *
523
+ * export const GET = async (req: NextRequest) => {
524
+ * const tokens = await getTokens(req);
525
+ *
526
+ * return NextResponse.json({ expired: tokens?.isExpired });
527
+ * };
528
+ * ```
529
+ *
530
+ * @param req Incoming request used to resolve authentication from cookies and headers.
531
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
532
+ * @returns The current user's tokens, refreshed if necessary.
533
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
534
+ *
535
+ * @category Functions
536
+ */
537
+ declare function getTokens(req: NextRequest | Request, options?: GetTokensOptions): Promise<MonoCloudTokens>;
538
+ /**
539
+ * Retrieves the current user's tokens using an explicit request and response.
540
+ *
541
+ * Use this overload when you have already created a response and want refreshed authentication cookies or headers applied to it.
542
+ *
543
+ * @example Middleware (Response)
544
+ *```tsx:src/proxy.ts tab="Middleware (Response)" tab-group="tokens-route-handler-response"
545
+ * import { getTokens } from "@monocloud/auth-nextjs";
546
+ * import { NextRequest, NextResponse } from "next/server";
547
+ *
548
+ * export default async function proxy(req: NextRequest) {
549
+ * const res = NextResponse.next();
550
+ *
551
+ * const tokens = await getTokens(req, res);
552
+ *
553
+ * res.headers.set("x-tokens-expired", tokens.isExpired.toString());
554
+ *
555
+ * return res;
556
+ * }
557
+ * ```
558
+ *
559
+ * @example API Handler (Response)
560
+ * ```tsx:src/app/api/tokens/route.ts tab="API Handler (Response)" tab-group="tokens-route-handler-response"
561
+ * import { getTokens } from "@monocloud/auth-nextjs";
562
+ * import { NextRequest, NextResponse } from "next/server";
563
+ *
564
+ * export const GET = async (req: NextRequest) => {
565
+ * const res = new NextResponse("Custom Body");
566
+ *
567
+ * const tokens = await getTokens(req, res);
568
+ *
569
+ * if (!tokens.isExpired) {
570
+ * res.headers.set("x-auth-status", "active");
571
+ * }
572
+ *
573
+ * return res;
574
+ * };
575
+ * ```
576
+ *
577
+ * @param req Incoming request used to resolve authentication from cookies and headers.
578
+ * @param res Existing response to update with refreshed authentication cookies or headers.
579
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
580
+ * @returns The current user's tokens, refreshed if necessary.
581
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
582
+ *
583
+ * @category Functions
584
+ */
585
+ declare function getTokens(req: NextRequest | Request, res: NextResponse | Response, options?: GetTokensOptions): Promise<MonoCloudTokens>;
586
+ /**
587
+ * Retrieves the current user's tokens in the Pages Router or Node.js runtime.
588
+ *
589
+ * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.
590
+ *
591
+ * @example Pages Router (Pages)
592
+ * ```tsx:src/pages/index.tsx tab="Pages Router (Pages)" tab-group="tokens-pages"
593
+ * import { getTokens, MonoCloudTokens } from "@monocloud/auth-nextjs";
594
+ * import { GetServerSideProps } from "next";
595
+ *
596
+ * type Props = {
597
+ * tokens: MonoCloudTokens;
598
+ * };
599
+ *
600
+ * export default function Home({ tokens }: Props) {
601
+ * return <pre>Tokens: {JSON.stringify(tokens, null, 2)}</pre>;
602
+ * }
603
+ *
604
+ * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
605
+ * const tokens = await getTokens(ctx.req, ctx.res);
606
+ *
607
+ * return {
608
+ * props: {
609
+ * tokens: tokens
610
+ * }
611
+ * };
612
+ * };
613
+ * ```
614
+ *
615
+ * @example Pages Router (API)
616
+ * ```tsx:src/pages/api/tokens.ts tab="Pages Router (API)" tab-group="tokens-pages"
617
+ * import { getTokens } from "@monocloud/auth-nextjs";
618
+ * import { NextApiRequest, NextApiResponse } from "next";
619
+ *
620
+ * export default async function handler(
621
+ * req: NextApiRequest,
622
+ * res: NextApiResponse
623
+ * ) {
624
+ * const tokens = await getTokens(req, res);
625
+ *
626
+ * res.status(200).json({ accessToken: tokens?.accessToken });
627
+ * }
628
+ * ```
629
+ *
630
+ * @param req Incoming Node.js request used to resolve authentication from cookies.
631
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
632
+ * @param options Optional configuration controlling refresh behavior and resource/scope selection.
633
+ * @returns The current user's tokens, refreshed if necessary.
634
+ * @throws {@link MonoCloudValidationError} If no valid session exists.
635
+ *
636
+ * @category Functions
637
+ */
638
+ declare function getTokens(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>, options?: GetTokensOptions): Promise<MonoCloudTokens>;
639
+ /**
640
+ * Checks whether the current user is authenticated using the active server request context.
641
+ *
642
+ * Intended for Server Components, Server Actions, Route Handlers, and Middleware where the request is implicitly available.
643
+ *
644
+ * @example Server Component
645
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="is-authenticated-ssr"
646
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
647
+ *
648
+ * export default async function Home() {
649
+ * const authenticated = await isAuthenticated();
650
+ *
651
+ * return <div>Authenticated: {authenticated.toString()}</div>;
652
+ * }
653
+ * ```
654
+ *
655
+ * @example Server Action
656
+ * ```tsx:src/action.ts tab="Server Action" tab-group="is-authenticated-ssr"
657
+ * "use server";
658
+ *
659
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
660
+ *
661
+ * export async function checkAuthAction() {
662
+ * const authenticated = await isAuthenticated();
663
+ *
664
+ * return { authenticated };
665
+ * }
666
+ * ```
667
+ *
668
+ * @example API Handler
669
+ * ```tsx:src/app/api/authenticated/route.ts tab="API Handler" tab-group="is-authenticated-ssr"
670
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
671
+ * import { NextResponse } from "next/server";
672
+ *
673
+ * export const GET = async () => {
674
+ * const authenticated = await isAuthenticated();
675
+ *
676
+ * return NextResponse.json({ authenticated });
677
+ * };
678
+ * ```
679
+ *
680
+ * @example Middleware
681
+ * ```tsx:src/proxy.ts tab="Middleware" tab-group="is-authenticated-ssr"
682
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
683
+ * import { NextResponse } from "next/server";
684
+ *
685
+ * export default async function proxy() {
686
+ * const authenticated = await isAuthenticated();
687
+ *
688
+ * if (!authenticated) {
689
+ * return new NextResponse("User not signed in", { status: 401 });
690
+ * }
691
+ *
692
+ * return NextResponse.next();
693
+ * }
694
+ * ```
695
+ *
696
+ * @returns Returns `true` if a valid session exists; otherwise `false`.
697
+ *
698
+ * @category Functions
699
+ */
700
+ declare function isAuthenticated(): Promise<boolean>;
701
+ /**
702
+ * Checks whether the current user is authenticated using an explicit Web or Next.js request.
703
+ *
704
+ * Use this overload when you already have access to a `Request` or `NextRequest` (for example, in Middleware or Route Handlers).
705
+ *
706
+ * @example Middleware (Request)
707
+ * ```tsx:src/proxy.ts tab="Middleware (Request)" tab-group="is-authenticated-route-handler"
708
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
709
+ * import { NextRequest, NextResponse } from "next/server";
710
+ *
711
+ * export default async function proxy(req: NextRequest) {
712
+ * const authenticated = await isAuthenticated(req);
713
+ *
714
+ * if (!authenticated) {
715
+ * return new NextResponse("User not signed in", { status: 401 });
716
+ * }
717
+ *
718
+ * return NextResponse.next();
719
+ * }
720
+ * ```
721
+ *
722
+ * @example Middleware (Response)
723
+ * ```tsx:src/proxy.ts tab="Middleware (Response)" tab-group="is-authenticated-route-handler"
724
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
725
+ * import { NextRequest, NextResponse } from "next/server";
726
+ *
727
+ * export default async function proxy(req: NextRequest) {
728
+ * const res = NextResponse.next();
729
+ *
730
+ * const authenticated = await isAuthenticated(req, res);
731
+ *
732
+ * if (!authenticated) {
733
+ * return new NextResponse("User not signed in", { status: 401 });
734
+ * }
735
+ *
736
+ * res.headers.set("x-authenticated", "true");
737
+ *
738
+ * return res;
739
+ * }
740
+ * ```
741
+ *
742
+ * @example API Handler (Request)
743
+ * ```tsx:src/app/api/authenticated/route.ts tab="API Handler (Request)" tab-group="is-authenticated-route-handler"
744
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
745
+ * import { NextRequest, NextResponse } from "next/server";
746
+ *
747
+ * export const GET = async (req: NextRequest) => {
748
+ * const authenticated = await isAuthenticated(req);
749
+ *
750
+ * return NextResponse.json({ authenticated });
751
+ * };
752
+ * ```
753
+ *
754
+ * @example API Handler (Response)
755
+ * ```tsx:src/app/api/authenticated/route.ts tab="API Handler (Response)" tab-group="is-authenticated-route-handler"
756
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
757
+ * import { NextRequest, NextResponse } from "next/server";
758
+ *
759
+ * export const GET = async (req: NextRequest) => {
760
+ * const res = new NextResponse("YOUR CUSTOM RESPONSE");
761
+ *
762
+ * const authenticated = await isAuthenticated(req, res);
763
+ *
764
+ * if (authenticated) {
765
+ * res.cookies.set("something", "important");
766
+ * }
767
+ *
768
+ * return res;
769
+ * };
770
+ * ```
771
+ *
772
+ * @param req Incoming request used to resolve authentication from cookies and headers.
773
+ * @param res Optional response to update if refreshed authentication cookies or headers are required.
774
+ * @returns Returns `true` if a valid session exists; otherwise `false`.
775
+ *
776
+ * @category Functions
777
+ */
778
+ declare function isAuthenticated(req: NextRequest | Request, res?: NextResponse | Response): Promise<boolean>;
779
+ /**
780
+ * Checks whether the current user is authenticated in the Pages Router or Node.js runtime.
781
+ *
782
+ * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.
783
+ *
784
+ * @example Pages Router (Pages)
785
+ * ```tsx:src/pages/index.tsx tab="Pages Router (Pages)" tab-group="is-authenticated-pages"
786
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
787
+ * import { GetServerSideProps } from "next";
788
+ *
789
+ * type Props = {
790
+ * authenticated: boolean;
791
+ * };
792
+ *
793
+ * export default function Home({ authenticated }: Props) {
794
+ * return <pre>User is {authenticated ? "logged in" : "guest"}</pre>;
795
+ * }
796
+ *
797
+ * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
798
+ * const authenticated = await isAuthenticated(ctx.req, ctx.res);
799
+ *
800
+ * return {
801
+ * props: {
802
+ * authenticated
803
+ * }
804
+ * };
805
+ * };
806
+ * ```
807
+ *
808
+ * @example Pages Router (API)
809
+ * ```tsx:src/pages/api/authenticated.ts tab="Pages Router (API)" tab-group="is-authenticated-pages"
810
+ * import { isAuthenticated } from "@monocloud/auth-nextjs";
811
+ * import { NextApiRequest, NextApiResponse } from "next";
812
+ *
813
+ * export default async function handler(
814
+ * req: NextApiRequest,
815
+ * res: NextApiResponse
816
+ * ) {
817
+ * const authenticated = await isAuthenticated(req, res);
818
+ *
819
+ * res.status(200).json({ authenticated });
820
+ * }
821
+ * ```
822
+ *
823
+ * @param req Incoming Node.js request used to resolve authentication from cookies.
824
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
825
+ * @returns Returns `true` if a valid session exists; otherwise `false`.
826
+ *
827
+ * @category Functions
828
+ */
829
+ declare function isAuthenticated(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>): Promise<boolean>;
830
+ /**
831
+ * Ensures the current user is authenticated. If not, redirects to the sign-in flow.
832
+ *
833
+ * > **App Router only.** Intended for Server Components, Route Handlers, and Server Actions.
834
+ *
835
+ * @example Server Component
836
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="protect"
837
+ * import { protect } from "@monocloud/auth-nextjs";
838
+ *
839
+ * export default async function Home() {
840
+ * await protect();
841
+ *
842
+ * return <>You are signed in.</>;
843
+ * }
844
+ * ```
845
+ *
846
+ * @example Server Action
847
+ * ```tsx:src/action.ts tab="Server Action" tab-group="protect"
848
+ * "use server";
849
+ *
850
+ * import { protect } from "@monocloud/auth-nextjs";
851
+ *
852
+ * export async function getMessage() {
853
+ * await protect();
854
+ *
855
+ * return { secret: "sssshhhhh!!!" };
856
+ * }
857
+ * ```
858
+ *
859
+ * @example API Handler
860
+ * ```tsx:src/app/api/protected/route.ts tab="API Handler" tab-group="protect"
861
+ * import { protect } from "@monocloud/auth-nextjs";
862
+ * import { NextResponse } from "next/server";
863
+ *
864
+ * export const GET = async () => {
865
+ * await protect();
866
+ *
867
+ * return NextResponse.json({ secret: "ssshhhh!!!" });
868
+ * };
869
+ * ```
870
+ *
871
+ * @param options Optional configuration for redirect behavior (for example, return URL or sign-in parameters).
872
+ * @returns Resolves if the user is authenticated; otherwise triggers a redirect.
873
+ *
874
+ * @category Functions
875
+ */
876
+ declare function protect(options?: ProtectOptions): Promise<void>;
877
+ /**
878
+ * Wraps an App Router API route handler and ensures that only authenticated (and optionally authorized) requests can access the route.
879
+ *
880
+ * Intended for Next.js App Router Route Handlers.
881
+ *
882
+ * @example
883
+ * ```tsx:src/app/api/protected/route.ts
884
+ * import { protectApi } from "@monocloud/auth-nextjs";
885
+ * import { NextResponse } from "next/server";
886
+ *
887
+ * export const GET = protectApi(async () => {
888
+ * return NextResponse.json({
889
+ * message: "You accessed a protected endpoint",
890
+ * });
891
+ * });
892
+ * ```
893
+ *
894
+ * @param handler The route handler to protect.
895
+ * @param options Optional configuration controlling authentication and authorization behavior.
896
+ * @returns Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.
897
+ *
898
+ * @category Functions
899
+ */
900
+ declare function protectApi(handler: AppRouterApiHandlerFn, options?: ProtectApiAppOptions): AppRouterApiHandlerFn;
901
+ /**
902
+ * Wraps a Pages Router API route handler and ensures that only authenticated (and optionally authorized) requests can access the route.
903
+ *
904
+ * Intended for Next.js Pages Router API routes.
905
+ *
906
+ * @example
907
+ * ```tsx:src/pages/api/protected.ts
908
+ * import { protectApi } from "@monocloud/auth-nextjs";
909
+ * import { NextApiRequest, NextApiResponse } from "next";
910
+ *
911
+ * export default protectApi(
912
+ * async (req: NextApiRequest, res: NextApiResponse) => {
913
+ * return res.json({
914
+ * message: "You accessed a protected endpoint",
915
+ * });
916
+ * }
917
+ * );
918
+ * ```
919
+ *
920
+ * @param handler - The route handler to protect.
921
+ * @param options Optional configuration controlling authentication and authorization behavior.
922
+ * @returns Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.
923
+ *
924
+ * @category Functions
925
+ */
926
+ declare function protectApi(handler: NextApiHandler, options?: ProtectApiPageOptions): NextApiHandler;
927
+ /**
928
+ * Restricts access to App Router server-rendered pages.
929
+ *
930
+ * **Access control**
931
+ * - If the user is not authenticated, `onAccessDenied` is invoked (or default behavior applies).
932
+ * - If the user is authenticated but fails group checks, `onGroupAccessDenied` is invoked (or the default "Access Denied" view is rendered).
933
+ *
934
+ * Both behaviors can be customized via options.
935
+ *
936
+ * @example Basic Usage
937
+ * ```tsx:src/app/page.tsx tab="Basic Usage" tab-group="protectPage-app"
938
+ * import { protectPage } from "@monocloud/auth-nextjs";
939
+ *
940
+ * export default protectPage(async function Home({ user }) {
941
+ * return <>Hi {user.email}. You accessed a protected page.</>;
942
+ * });
943
+ * ```
944
+ *
945
+ * @example With Options
946
+ * ```tsx:src/app/page.tsx tab="With Options" tab-group="protectPage-app"
947
+ * import { protectPage } from "@monocloud/auth-nextjs";
948
+ *
949
+ * export default protectPage(
950
+ * async function Home({ user }) {
951
+ * return <>Hi {user.email}. You accessed a protected page.</>;
952
+ * },
953
+ * {
954
+ * returnUrl: "/dashboard",
955
+ * groups: ["admin"],
956
+ * }
957
+ * );
958
+ * ```
959
+ *
960
+ * @param component The App Router server component to protect.
961
+ * @param options Optional configuration for authentication, authorization, and custom access handling (`onAccessDenied`, `onGroupAccessDenied`).
962
+ * @returns A wrapped page component that enforces authentication before rendering.
963
+ *
964
+ * @category Functions
965
+ */
966
+ declare function protectPage(component: ProtectedAppServerComponent, options?: ProtectAppPageOptions): AppRouterPageHandler;
967
+ /**
968
+ * Restricts access to Pages Router server-rendered pages using `getServerSideProps`.
969
+ *
970
+ * **Access control**
971
+ * - If the user is not authenticated, `onAccessDenied` is invoked (or default behavior applies).
972
+ * - 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.
973
+ *
974
+ * Both behaviors can be customized via options.
975
+ *
976
+ * @example Basic Usage
977
+ * ```tsx:src/pages/index.tsx tab="Basic Usage" tab-group="protectPage-page"
978
+ * import { protectPage, MonoCloudUser } from "@monocloud/auth-nextjs";
979
+ *
980
+ * type Props = {
981
+ * user: MonoCloudUser;
982
+ * };
983
+ *
984
+ * export default function Home({ user }: Props) {
985
+ * return <>Hi {user.email}. You accessed a protected page.</>;
986
+ * }
987
+ *
988
+ * export const getServerSideProps = protectPage();
989
+ * ```
990
+ *
991
+ * @example With Options
992
+ * ```tsx:src/pages/index.tsx tab="With Options" tab-group="protectPage-page"
993
+ * import { protectPage, MonoCloudUser } from "@monocloud/auth-nextjs";
994
+ * import { GetServerSidePropsContext } from "next";
995
+ *
996
+ * type Props = {
997
+ * user: MonoCloudUser;
998
+ * url: string;
999
+ * };
1000
+ *
1001
+ * export default function Home({ user, url }: Props) {
1002
+ * console.log(url);
1003
+ * return <div>Hi {user?.email}. You accessed a protected page.</div>;
1004
+ * }
1005
+ *
1006
+ * export const getServerSideProps = protectPage({
1007
+ * returnUrl: "/dashboard",
1008
+ * groups: ["admin"],
1009
+ * getServerSideProps: async (context: GetServerSidePropsContext) => ({
1010
+ * props: { url: context.resolvedUrl }
1011
+ * })
1012
+ * });
1013
+ * ```
1014
+ *
1015
+ * @param options Optional configuration for authentication, authorization, and custom access handling (`onAccessDenied`, `onGroupAccessDenied`).
1016
+ * @typeParam P - Props returned from `getServerSideProps`.
1017
+ * @typeParam Q - Query parameters parsed from the URL.
1018
+ * @returns A getServerSideProps wrapper that enforces authentication before executing the page logic.
1019
+ *
1020
+ * @category Functions
1021
+ */
1022
+ declare function protectPage<P extends Record<string, any> = Record<string, any>, Q extends ParsedUrlQuery = ParsedUrlQuery>(options?: ProtectPagePageOptions<P, Q>): ProtectPagePageReturnType<P, Q>;
1023
+ /**
1024
+ * Checks whether the currently authenticated user is a member of **any** of the specified groups.
1025
+ *
1026
+ * The `groups` parameter accepts group identifiers (IDs or names).
1027
+ *
1028
+ * The authenticated user's session may contain groups represented as:
1029
+ * - Group IDs
1030
+ * - Group names
1031
+ * - `Group` objects (for example, `{ id: string; name: string }`)
1032
+ *
1033
+ * Matching is always performed against the group's **ID** and **name**, regardless of how the group is represented in the session.
1034
+ *
1035
+ * @example Server Component
1036
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="is-user-in-group-rsc"
1037
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1038
+ *
1039
+ * export default async function AdminPanel() {
1040
+ * const isAdmin = await isUserInGroup(["admin"]);
1041
+ *
1042
+ * if (!isAdmin) {
1043
+ * return <div>Access Denied</div>;
1044
+ * }
1045
+ *
1046
+ * return <div>Admin Control Panel</div>;
1047
+ * }
1048
+ * ```
1049
+ *
1050
+ * @example Server Action
1051
+ * ```tsx:src/action.ts tab="Server Action" tab-group="is-user-in-group-rsc"
1052
+ * "use server";
1053
+ *
1054
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1055
+ *
1056
+ * export async function deletePostAction() {
1057
+ * const canDelete = await isUserInGroup(["admin", "editor"]);
1058
+ *
1059
+ * if (!canDelete) {
1060
+ * return { success: false };
1061
+ * }
1062
+ *
1063
+ * return { success: true };
1064
+ * }
1065
+ * ```
1066
+ *
1067
+ * @example API Handler
1068
+ * ```tsx:src/app/api/group-check/route.ts tab="API Handler" tab-group="is-user-in-group-rsc"
1069
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1070
+ * import { NextResponse } from "next/server";
1071
+ *
1072
+ * export const GET = async () => {
1073
+ * const allowed = await isUserInGroup(["admin", "editor"]);
1074
+ *
1075
+ * if (!allowed) {
1076
+ * return new NextResponse("Forbidden", { status: 403 });
1077
+ * }
1078
+ *
1079
+ * return NextResponse.json({ status: "success" });
1080
+ * };
1081
+ * ```
1082
+ *
1083
+ * @example Middleware
1084
+ * ```tsx:src/proxy.ts tab="Middleware" tab-group="is-user-in-group-rsc"
1085
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1086
+ * import { NextResponse } from "next/server";
1087
+ *
1088
+ * export default async function proxy() {
1089
+ * const isAdmin = await isUserInGroup(["admin"]);
1090
+ *
1091
+ * if (!isAdmin) {
1092
+ * return new NextResponse("User is not admin", { status: 403 });
1093
+ * }
1094
+ *
1095
+ * return NextResponse.next();
1096
+ * }
1097
+ * ```
1098
+ *
1099
+ * @param groups Group IDs or names to check against the user's group memberships.
1100
+ * @param options Optional configuration controlling how group membership is evaluated.
1101
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
1102
+ *
1103
+ * @category Functions
1104
+ */
1105
+ declare function isUserInGroup(groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
1106
+ /**
1107
+ * Checks group membership using an explicit Web or Next.js request.
1108
+ *
1109
+ * Use this overload when you already have access to a `Request` or `NextRequest` (for example, in Middleware or Route Handlers).
1110
+ *
1111
+ * @example Middleware (Request)
1112
+ * ```tsx:src/proxy.ts tab="Middleware (Request)" tab-group="is-user-in-group-request"
1113
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1114
+ * import { NextRequest, NextResponse } from "next/server";
1115
+ *
1116
+ * export default async function proxy(req: NextRequest) {
1117
+ * const isAdmin = await isUserInGroup(req, ["admin"]);
1118
+ *
1119
+ * if (!isAdmin) {
1120
+ * return new NextResponse("User is not admin", { status: 403 });
1121
+ * }
1122
+ *
1123
+ * return NextResponse.next();
1124
+ * }
1125
+ * ```
1126
+ *
1127
+ * @example API Handler (Request)
1128
+ * ```tsx:src/app/api/group-check/route.ts tab="API Handler (Request)" tab-group="is-user-in-group-request"
1129
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1130
+ * import { NextRequest, NextResponse } from "next/server";
1131
+ *
1132
+ * export const GET = async (req: NextRequest) => {
1133
+ * const isMember = await isUserInGroup(req, ["admin", "editor"]);
1134
+ *
1135
+ * return NextResponse.json({ isMember });
1136
+ * };
1137
+ * ```
1138
+ *
1139
+ * @param req Incoming request used to resolve authentication from cookies and headers.
1140
+ * @param groups Group IDs or names to check against the user's group memberships.
1141
+ * @param options Optional configuration controlling how group membership is evaluated.
1142
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
1143
+ *
1144
+ * @category Functions
1145
+ */
1146
+ declare function isUserInGroup(req: NextRequest | Request, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
1147
+ /**
1148
+ * Checks group membership using an explicit request and response.
1149
+ *
1150
+ * Use this overload when you have already created a response and want refreshed authentication cookies or headers applied to it.
1151
+ *
1152
+ * @example Middleware (Response)
1153
+ * ```tsx:src/proxy.ts tab="Middleware (Response)" tab-group="is-user-in-group-response"
1154
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1155
+ * import { NextRequest, NextResponse } from "next/server";
1156
+ *
1157
+ * export default async function proxy(req: NextRequest) {
1158
+ * const res = NextResponse.next();
1159
+ *
1160
+ * const isAdmin = await isUserInGroup(req, res, ["admin"]);
1161
+ *
1162
+ * if (!isAdmin) {
1163
+ * return new NextResponse("User is not admin", { status: 403 });
1164
+ * }
1165
+ *
1166
+ * res.headers.set("x-user", "admin");
1167
+ *
1168
+ * return res;
1169
+ * }
1170
+ * ```
1171
+ *
1172
+ * @example API Handler (Response)
1173
+ * ```tsx:src/app/api/group-check/route.ts tab="API Handler (Response)" tab-group="is-user-in-group-response"
1174
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1175
+ * import { NextRequest, NextResponse } from "next/server";
1176
+ *
1177
+ * export const GET = async (req: NextRequest) => {
1178
+ * const res = new NextResponse("Restricted Content");
1179
+ *
1180
+ * const allowed = await isUserInGroup(req, res, ["admin"]);
1181
+ *
1182
+ * if (!allowed) {
1183
+ * return new NextResponse("Not Allowed", res);
1184
+ * }
1185
+ *
1186
+ * return res;
1187
+ * };
1188
+ * ```
1189
+ *
1190
+ * @param req Incoming request used to resolve authentication from cookies and headers.
1191
+ * @param res Existing response to update with refreshed authentication cookies or headers when required.
1192
+ * @param groups Group IDs or names to check against the user's group memberships.
1193
+ * @param options Optional configuration controlling how group membership is evaluated.
1194
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
1195
+ *
1196
+ * @category Functions
1197
+ */
1198
+ declare function isUserInGroup(req: NextRequest | Request, res: NextResponse | Response, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
1199
+ /**
1200
+ * Checks group membership in the Pages Router or Node.js runtime.
1201
+ *
1202
+ * Use this overload in API routes or `getServerSideProps`, where Node.js request and response objects are available.
1203
+ *
1204
+ * @example Pages Router (Pages)
1205
+ * ```tsx:src/pages/index.tsx tab="Pages Router (Pages)" tab-group="is-user-in-group-pages"
1206
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1207
+ * import { GetServerSideProps } from "next";
1208
+ *
1209
+ * type Props = {
1210
+ * isAdmin: boolean;
1211
+ * };
1212
+ *
1213
+ * export default function Home({ isAdmin }: Props) {
1214
+ * return <div>User is admin: {isAdmin.toString()}</div>;
1215
+ * }
1216
+ *
1217
+ * export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
1218
+ * const isAdmin = await isUserInGroup(ctx.req, ctx.res, ["admin"]);
1219
+ *
1220
+ * return {
1221
+ * props: {
1222
+ * isAdmin
1223
+ * }
1224
+ * };
1225
+ * };
1226
+ * ```
1227
+ *
1228
+ * @example Pages Router (API)
1229
+ * ```tsx:src/pages/api/group-check.ts tab="Pages Router (API)" tab-group="is-user-in-group-pages"
1230
+ * import { isUserInGroup } from "@monocloud/auth-nextjs";
1231
+ * import { NextApiRequest, NextApiResponse } from "next";
1232
+ *
1233
+ * export default async function handler(
1234
+ * req: NextApiRequest,
1235
+ * res: NextApiResponse
1236
+ * ) {
1237
+ * const isAdmin = await isUserInGroup(req, res, ["admin"]);
1238
+ *
1239
+ * if (!isAdmin) {
1240
+ * return res.status(403).json({ error: "Forbidden" });
1241
+ * }
1242
+ *
1243
+ * res.status(200).json({ message: "Welcome Admin" });
1244
+ * }
1245
+ * ```
1246
+ *
1247
+ * @param req Incoming Node.js request used to resolve authentication from cookies.
1248
+ * @param res Outgoing Node.js response used to apply refreshed authentication cookies when required.
1249
+ * @param groups Group IDs or names to check against the user's group memberships.
1250
+ * @param options Optional configuration controlling how group membership is evaluated.
1251
+ * @returns Returns `true` if the user belongs to at least one specified group; otherwise `false`.
1252
+ *
1253
+ * @category Functions
1254
+ */
1255
+ declare function isUserInGroup(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>;
1256
+ /**
1257
+ * Redirects the user to the sign-in flow.
1258
+ *
1259
+ * > **App Router only**. Intended for use in Server Components, Route Handlers, and Server Actions.
1260
+ *
1261
+ * This helper performs a server-side redirect to the configured sign-in route. Execution does not continue after the redirect is triggered.
1262
+ *
1263
+ * @example Server Component
1264
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="redirect-to-sign-in"
1265
+ * import { isUserInGroup, redirectToSignIn } from "@monocloud/auth-nextjs";
1266
+ *
1267
+ * export default async function Home() {
1268
+ * const allowed = await isUserInGroup(["admin"]);
1269
+ *
1270
+ * if (!allowed) {
1271
+ * await redirectToSignIn({ returnUrl: "/home" });
1272
+ * }
1273
+ *
1274
+ * return <>You are signed in.</>;
1275
+ * }
1276
+ * ```
1277
+ *
1278
+ * @example Server Action
1279
+ * ```tsx:src/action.ts tab="Server Action" tab-group="redirect-to-sign-in"
1280
+ * "use server";
1281
+ *
1282
+ * import { getSession, redirectToSignIn } from "@monocloud/auth-nextjs";
1283
+ *
1284
+ * export async function protectedAction() {
1285
+ * const session = await getSession();
1286
+ *
1287
+ * if (!session) {
1288
+ * await redirectToSignIn();
1289
+ * }
1290
+ *
1291
+ * return { data: "Sensitive Data" };
1292
+ * }
1293
+ * ```
1294
+ *
1295
+ * @example API Handler
1296
+ * ```tsx:src/app/api/protected/route.ts tab="API Handler" tab-group="redirect-to-sign-in"
1297
+ * import { getSession, redirectToSignIn } from "@monocloud/auth-nextjs";
1298
+ * import { NextResponse } from "next/server";
1299
+ *
1300
+ * export const GET = async () => {
1301
+ * const session = await getSession();
1302
+ *
1303
+ * if (!session) {
1304
+ * await redirectToSignIn({
1305
+ * returnUrl: "/dashboard",
1306
+ * });
1307
+ * }
1308
+ *
1309
+ * return NextResponse.json({ data: "Protected content" });
1310
+ * };
1311
+ * ```
1312
+ *
1313
+ * @param options Optional configuration for the redirect, such as `returnUrl` or additional sign-in parameters.
1314
+ * @returns Never resolves. Triggers a redirect to the sign-in flow.
1315
+ *
1316
+ * @category Functions
1317
+ */
1318
+ declare function redirectToSignIn(options?: RedirectToSignInOptions): Promise<void>;
1319
+ /**
1320
+ * Redirects the user to the sign-out flow.
1321
+ *
1322
+ * > **App Router only**. Intended for use in Server Components, Route Handlers, and Server Actions.
1323
+ *
1324
+ * This helper performs a server-side redirect to the configured sign-out route. Execution does not continue after the redirect is triggered.
1325
+ *
1326
+ * @example Server Component
1327
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="redirect-to-sign-out"
1328
+ * import { getSession, redirectToSignOut } from "@monocloud/auth-nextjs";
1329
+ *
1330
+ * export default async function Page() {
1331
+ * const session = await getSession();
1332
+ *
1333
+ * // Example: Force sign-out if a specific condition is met (e.g., account suspended)
1334
+ * if (session?.user.isSuspended) {
1335
+ * await redirectToSignOut();
1336
+ * }
1337
+ *
1338
+ * return <>Welcome User</>;
1339
+ * }
1340
+ * ```
1341
+ *
1342
+ * @example Server Action
1343
+ * ```tsx:src/action.ts tab="Server Action" tab-group="redirect-to-sign-out"
1344
+ * "use server";
1345
+ *
1346
+ * import { getSession, redirectToSignOut } from "@monocloud/auth-nextjs";
1347
+ *
1348
+ * export async function signOutAction() {
1349
+ * const session = await getSession();
1350
+ *
1351
+ * if (session) {
1352
+ * await redirectToSignOut();
1353
+ * }
1354
+ * }
1355
+ * ```
1356
+ *
1357
+ * @example API Handler
1358
+ * ```tsx:src/app/api/signout/route.ts tab="API Handler" tab-group="redirect-to-sign-out"
1359
+ * import { getSession, redirectToSignOut } from "@monocloud/auth-nextjs";
1360
+ * import { NextResponse } from "next/server";
1361
+ *
1362
+ * export const GET = async () => {
1363
+ * const session = await getSession();
1364
+ *
1365
+ * if (session) {
1366
+ * await redirectToSignOut({
1367
+ * postLogoutRedirectUri: "/goodbye",
1368
+ * });
1369
+ * }
1370
+ *
1371
+ * return NextResponse.json({ status: "already_signed_out" });
1372
+ * };
1373
+ * ```
1374
+ *
1375
+ * @param options Optional configuration for the redirect, such as `postLogoutRedirectUri` or additional sign-out parameters.
1376
+ * @returns Never resolves. Triggers a redirect to the sign-out flow.
1377
+ *
1378
+ * @category Functions
1379
+ */
1380
+ declare function redirectToSignOut(options?: RedirectToSignOutOptions): Promise<void>;
1381
+ //#endregion
1382
+ export { authMiddleware, getSession, getTokens, isAuthenticated, isUserInGroup, monoCloudAuth, protect, protectApi, protectPage, redirectToSignIn, redirectToSignOut };
1383
+ //# sourceMappingURL=initialize.d.mts.map