@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
package/dist/index.mjs CHANGED
@@ -1,1126 +1,5 @@
1
- import { MonoCloudAuthBaseError, MonoCloudCoreClient, MonoCloudHttpError, MonoCloudOPError, MonoCloudTokenError, MonoCloudValidationError, MonoCloudValidationError as MonoCloudValidationError$1 } from "@monocloud/auth-node-core";
2
- import { NextRequest, NextResponse } from "next/server.js";
3
- import { ensureLeadingSlash, isAbsoluteUrl, isPresent } from "@monocloud/auth-node-core/internal";
4
- import { isUserInGroup as isUserInGroup$1 } from "@monocloud/auth-node-core/utils";
5
- import { serialize } from "cookie";
1
+ import { MonoCloudNextClient } from "./monocloud-next-client.mjs";
2
+ import { authMiddleware, getSession, getTokens, isAuthenticated, isUserInGroup, monoCloudAuth, protect, protectApi, protectPage, redirectToSignIn, redirectToSignOut } from "./initialize.mjs";
3
+ import { MonoCloudAuthBaseError, MonoCloudHttpError, MonoCloudOPError, MonoCloudTokenError, MonoCloudValidationError } from "@monocloud/auth-node-core";
6
4
 
7
- //#region src/requests/monocloud-app-router-request.ts
8
- var MonoCloudAppRouterRequest = class {
9
- constructor(req) {
10
- this.req = req;
11
- }
12
- getQuery(parameter) {
13
- return new URL(this.req.url).searchParams.get(parameter) ?? void 0;
14
- }
15
- getCookie(name) {
16
- var _this$req$cookies$get;
17
- return Promise.resolve((_this$req$cookies$get = this.req.cookies.get(name)) === null || _this$req$cookies$get === void 0 ? void 0 : _this$req$cookies$get.value);
18
- }
19
- async getRawRequest() {
20
- return {
21
- method: this.req.method,
22
- url: this.req.url,
23
- body: await this.req.text()
24
- };
25
- }
26
- getAllCookies() {
27
- const values = /* @__PURE__ */ new Map();
28
- this.req.cookies.getAll().forEach((x) => {
29
- values.set(x.name, x.value);
30
- });
31
- return Promise.resolve(values);
32
- }
33
- };
34
-
35
- //#endregion
36
- //#region src/requests/monocloud-page-router-request.ts
37
- var MonoCloudPageRouterRequest = class {
38
- constructor(req) {
39
- this.req = req;
40
- }
41
- /* v8 ignore next */
42
- getQuery(parameter) {
43
- return this.req.query[parameter];
44
- }
45
- /* v8 ignore next */
46
- getCookie(name) {
47
- return Promise.resolve(this.req.cookies[name]);
48
- }
49
- /* v8 ignore next */
50
- getRawRequest() {
51
- return Promise.resolve({
52
- method: this.req.method,
53
- url: this.req.url,
54
- body: this.req.body
55
- });
56
- }
57
- getAllCookies() {
58
- const values = /* @__PURE__ */ new Map();
59
- const { cookies } = this.req;
60
- Object.keys(cookies).forEach((x) => {
61
- const val = cookies[x];
62
- /* v8 ignore else -- @preserve */
63
- if (typeof x === "string" && typeof val === "string") values.set(x, val);
64
- });
65
- return Promise.resolve(values);
66
- }
67
- };
68
-
69
- //#endregion
70
- //#region src/responses/monocloud-app-router-response.ts
71
- var MonoCloudAppRouterResponse = class {
72
- constructor(res) {
73
- this.res = res;
74
- }
75
- setCookie(cookieName, value, options) {
76
- this.res.cookies.set(cookieName, value, options);
77
- return Promise.resolve();
78
- }
79
- redirect(url, statusCode = 302) {
80
- const { headers } = this.res;
81
- this.res = NextResponse.redirect(url, {
82
- status: statusCode,
83
- headers
84
- });
85
- }
86
- sendJson(data, statusCode) {
87
- const { headers } = this.res;
88
- this.res = NextResponse.json(data, {
89
- status: statusCode,
90
- headers
91
- });
92
- }
93
- /* v8 ignore next */
94
- notFound() {
95
- const { headers } = this.res;
96
- this.res = new NextResponse(null, {
97
- status: 404,
98
- headers
99
- });
100
- }
101
- internalServerError() {
102
- const { headers } = this.res;
103
- this.res = new NextResponse(null, {
104
- status: 500,
105
- headers
106
- });
107
- }
108
- noContent() {
109
- const { headers } = this.res;
110
- this.res = new NextResponse(null, {
111
- status: 204,
112
- headers
113
- });
114
- }
115
- methodNotAllowed() {
116
- const { headers } = this.res;
117
- this.res = new NextResponse(null, {
118
- status: 405,
119
- headers
120
- });
121
- }
122
- setNoCache() {
123
- this.res.headers.set("Cache-Control", "no-cache no-store");
124
- this.res.headers.set("Pragma", "no-cache");
125
- }
126
- done() {
127
- return this.res;
128
- }
129
- };
130
-
131
- //#endregion
132
- //#region src/responses/monocloud-page-router-response.ts
133
- var MonoCloudPageRouterResponse = class {
134
- constructor(res) {
135
- this.res = res;
136
- }
137
- setCookie(cookieName, value, options) {
138
- let cookies = this.res.getHeader("Set-Cookie") ?? [];
139
- /* v8 ignore if -- @preserve */
140
- if (!Array.isArray(cookies)) cookies = [cookies];
141
- this.res.setHeader("Set-Cookie", [...cookies.filter((cookie) => !cookie.startsWith(`${cookieName}=`)), serialize(cookieName, value, options)]);
142
- return Promise.resolve();
143
- }
144
- /* v8 ignore next */
145
- redirect(url, statusCode) {
146
- this.res.redirect(statusCode ?? 302, url);
147
- }
148
- /* v8 ignore next */
149
- sendJson(data, statusCode) {
150
- this.res.status(statusCode ?? 200);
151
- this.res.json(data);
152
- }
153
- /* v8 ignore next */
154
- notFound() {
155
- this.res.status(404);
156
- }
157
- /* v8 ignore next */
158
- internalServerError() {
159
- this.res.status(500);
160
- }
161
- /* v8 ignore next */
162
- noContent() {
163
- this.res.status(204);
164
- }
165
- /* v8 ignore next */
166
- methodNotAllowed() {
167
- this.res.status(405);
168
- }
169
- /* v8 ignore next */
170
- setNoCache() {
171
- this.res.setHeader("Cache-Control", "no-cache no-store");
172
- this.res.setHeader("Pragma", "no-cache");
173
- }
174
- /* v8 ignore next */
175
- done() {
176
- this.res.end();
177
- }
178
- };
179
-
180
- //#endregion
181
- //#region src/responses/monocloud-cookie-response.ts
182
- let isWarned = false;
183
- var MonoCloudCookieResponse = class {
184
- async setCookie(cookieName, value, options) {
185
- try {
186
- const { cookies } = await import("next/headers");
187
- (await cookies()).set(cookieName, value, options);
188
- } catch (e) {
189
- if (!isWarned) {
190
- console.warn(e.message);
191
- isWarned = true;
192
- }
193
- }
194
- }
195
- };
196
-
197
- //#endregion
198
- //#region src/requests/monocloud-cookie-request.ts
199
- var MonoCloudCookieRequest = class {
200
- /* v8 ignore next */
201
- async getCookie(name) {
202
- var _await$cookies$get;
203
- const { cookies } = await import("next/headers");
204
- return (_await$cookies$get = (await cookies()).get(name)) === null || _await$cookies$get === void 0 ? void 0 : _await$cookies$get.value;
205
- }
206
- async getAllCookies() {
207
- const values = /* @__PURE__ */ new Map();
208
- const { cookies } = await import("next/headers");
209
- (await cookies()).getAll().forEach((x) => {
210
- values.set(x.name, x.value);
211
- });
212
- return values;
213
- }
214
- };
215
-
216
- //#endregion
217
- //#region src/utils.ts
218
- const isMonoCloudRequest = (req) => req instanceof MonoCloudAppRouterRequest || req instanceof MonoCloudPageRouterRequest || req instanceof MonoCloudCookieRequest;
219
- const isMonoCloudResponse = (res) => res instanceof MonoCloudAppRouterResponse || res instanceof MonoCloudPageRouterResponse || res instanceof MonoCloudCookieResponse;
220
- const isAppRouter = (req) => req instanceof Request || req.headers instanceof Headers || typeof req.bodyUsed === "boolean";
221
- const isNodeRequest = (req) => {
222
- return !!(req && typeof req === "object" && "headers" in req && !("bodyUsed" in req) && typeof req.on === "function");
223
- };
224
- const isNodeResponse = (res) => {
225
- return !!(res && typeof res === "object" && "setHeader" in res && typeof res.setHeader === "function" && "end" in res && typeof res.end === "function");
226
- };
227
- const getNextRequest = (req) => {
228
- if (req instanceof NextRequest) return req;
229
- return new NextRequest(req.url, {
230
- method: req.method,
231
- headers: req.headers,
232
- body: req.body,
233
- duplex: req.duplex ?? "half"
234
- });
235
- };
236
- const getNextResponse = (res) => {
237
- if (res instanceof NextResponse) return res;
238
- if (res instanceof Response) {
239
- const nextResponse = new NextResponse(res.body, {
240
- status: res.status,
241
- statusText: res.statusText,
242
- headers: res.headers,
243
- url: res.url
244
- });
245
- try {
246
- /* v8 ignore else -- @preserve */
247
- if (!isPresent(nextResponse.url)) nextResponse.url = res.url;
248
- } catch {}
249
- return nextResponse;
250
- }
251
- return new NextResponse();
252
- };
253
- const getMonoCloudCookieReqRes = (req, resOrCtx) => {
254
- let request;
255
- let response;
256
- if (isAppRouter(req)) {
257
- request = new MonoCloudAppRouterRequest(getNextRequest(req));
258
- response = resOrCtx instanceof Response ? new MonoCloudAppRouterResponse(getNextResponse(resOrCtx)) : new MonoCloudCookieResponse();
259
- } else {
260
- if (!isNodeRequest(req) || !isNodeResponse(resOrCtx)) throw new MonoCloudValidationError$1("Invalid pages router request and response");
261
- request = new MonoCloudPageRouterRequest(req);
262
- response = new MonoCloudPageRouterResponse(resOrCtx);
263
- }
264
- return {
265
- request,
266
- response
267
- };
268
- };
269
- const mergeResponse = (responses) => {
270
- const resp = responses.pop();
271
- if (!resp) return new NextResponse();
272
- responses.forEach((response) => {
273
- response.headers.forEach((v, k) => {
274
- if (k === "location" && !resp.headers.has(k) || k !== "location") resp.headers.set(k, v);
275
- });
276
- response.cookies.getAll().forEach((c) => {
277
- const { name, value, ...cookieOpt } = c;
278
- resp.cookies.set(name, value, cookieOpt);
279
- });
280
- });
281
- return resp;
282
- };
283
-
284
- //#endregion
285
- //#region src/monocloud-next-client.ts
286
- /**
287
- * `MonoCloudNextClient` is the core SDK entry point for integrating MonoCloud authentication into a Next.js application.
288
- *
289
- * It provides:
290
- * - Authentication middleware
291
- * - Route protection helpers
292
- * - Session and token access
293
- * - Redirect utilities
294
- * - Server-side enforcement helpers
295
- *
296
- * ## 1. Add environment variables
297
- *
298
- * ```bash:.env.local
299
- * MONOCLOUD_AUTH_TENANT_DOMAIN=<tenant-domain>
300
- * MONOCLOUD_AUTH_CLIENT_ID=<client-id>
301
- * MONOCLOUD_AUTH_CLIENT_SECRET=<client-secret>
302
- * MONOCLOUD_AUTH_SCOPES=openid profile email
303
- * MONOCLOUD_AUTH_APP_URL=http://localhost:3000
304
- * MONOCLOUD_AUTH_COOKIE_SECRET=<cookie-secret>
305
- * ```
306
- *
307
- * ## 2. Register middleware
308
- *
309
- * ```typescript:src/proxy.ts
310
- * import { authMiddleware } from "@monocloud/auth-nextjs";
311
- *
312
- * export default authMiddleware();
313
- *
314
- * export const config = {
315
- * matcher: [
316
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
317
- * ],
318
- * };
319
- * ```
320
- *
321
- * ## Advanced usage
322
- *
323
- * ### Create a shared client instance
324
- *
325
- * By default, the SDK exposes function exports (for example, `authMiddleware()`, `getSession()`, `getTokens()`) that internally use a shared singleton `MonoCloudNextClient`.
326
- *
327
- * Create your own `MonoCloudNextClient` instance when you need multiple configurations, dependency injection, or explicit control over initialization.
328
- *
329
- * ```ts:src/monocloud.ts
330
- * import { MonoCloudNextClient } from "@monocloud/auth-nextjs";
331
- *
332
- * export const monoCloud = new MonoCloudNextClient();
333
- * ```
334
- *
335
- * ### Using instance methods
336
- *
337
- * Once you create a client instance, call methods directly on it instead of using the default function exports.
338
- *
339
- * ```ts:src/app/page.tsx
340
- * import { monoCloud } from "@/monocloud";
341
- *
342
- * export default async function Page() {
343
- * const session = await monoCloud.getSession();
344
- *
345
- * if (!session) {
346
- * return <>Not signed in</>;
347
- * }
348
- *
349
- * return <>Hello {session.user.name}</>;
350
- * }
351
- * ```
352
- *
353
- * #### Using constructor options
354
- *
355
- * 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.
356
- *
357
- * ```ts:src/monocloud.ts
358
- * import { MonoCloudNextClient } from "@monocloud/auth-nextjs";
359
- *
360
- * export const monoCloud = new MonoCloudNextClient({
361
- * tenantDomain: "<tenant-domain>",
362
- * clientId: "<client-id>",
363
- * clientSecret: "<client-secret>",
364
- * appUrl: "http://localhost:3000",
365
- * cookieSecret: "<cookie-secret>",
366
- * defaultAuthParams: {
367
- * scopes: "openid profile email",
368
- * },
369
- * });
370
- * ```
371
- *
372
- * ### Modifying default routes
373
- *
374
- * If you customize any of the default auth route paths:
375
- *
376
- * - Also set the corresponding `NEXT_PUBLIC_` environment variables so client-side helpers
377
- * (for example `<SignIn />`, `<SignOut />`, and `useAuth()`) can discover the correct URLs.
378
- * - Update the **Application URLs** in your MonoCloud Dashboard to match the new paths.
379
- *
380
- * Example:
381
- *
382
- * ```bash:.env.local
383
- * MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
384
- * NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
385
- * ```
386
- *
387
- * When routes are overridden, the Redirect URI configured in the dashboard
388
- * must reflect the new path. For example, during local development:
389
- *
390
- * `http://localhost:3000/api/custom_callback`
391
- *
392
- * @category Classes
393
- */
394
- var MonoCloudNextClient = class {
395
- /**
396
- * This exposes the framework-agnostic MonoCloud client used internally by the Next.js SDK.
397
- * Use it if you need access to lower-level functionality not directly exposed by MonoCloudNextClient.
398
- *
399
- * @returns Returns the underlying **Node client** instance.
400
- */
401
- get coreClient() {
402
- return this._coreClient;
403
- }
404
- /**
405
- * This is intended for advanced scenarios requiring direct control over the authorization or token flow.
406
- *
407
- * @returns Returns the underlying **OIDC client** used for OpenID Connect operations.
408
- */
409
- get oidcClient() {
410
- return this.coreClient.oidcClient;
411
- }
412
- /**
413
- * Creates a new client instance.
414
- *
415
- * @param options Optional configuration for initializing the MonoCloud client. If not provided, settings are automatically resolved from environment variables.
416
- */
417
- constructor(options) {
418
- const opt = {
419
- ...options ?? {},
420
- userAgent: (options === null || options === void 0 ? void 0 : options.userAgent) ?? `@monocloud/auth-nextjs@0.1.9`,
421
- debugger: (options === null || options === void 0 ? void 0 : options.debugger) ?? "@monocloud:auth-nextjs"
422
- };
423
- this.registerPublicEnvVariables();
424
- this._coreClient = new MonoCloudCoreClient(opt);
425
- }
426
- /**
427
- * @see {@link monoCloudAuth} for full docs and examples.
428
- * @param options Optional configuration for the auth handler.
429
- * @returns Returns a Next.js-compatible handler for App Router route handlers or Pages Router API routes.
430
- */
431
- monoCloudAuth(options) {
432
- return (req, resOrCtx) => {
433
- const { routes, appUrl } = this.getOptions();
434
- let { url = "" } = req;
435
- if (!isAbsoluteUrl(url)) url = new URL(url, appUrl).toString();
436
- const route = new URL(url);
437
- let onError;
438
- if (typeof (options === null || options === void 0 ? void 0 : options.onError) === "function") onError = (error) => options.onError(req, resOrCtx, error);
439
- let request;
440
- let response;
441
- if (isAppRouter(req)) {
442
- request = new MonoCloudAppRouterRequest(getNextRequest(req));
443
- response = new MonoCloudAppRouterResponse(getNextResponse(resOrCtx));
444
- } else {
445
- request = new MonoCloudPageRouterRequest(req);
446
- response = new MonoCloudPageRouterResponse(resOrCtx);
447
- }
448
- return this.handleAuthRoutes(request, response, route.pathname, routes, onError);
449
- };
450
- }
451
- protectPage(...args) {
452
- if (typeof args[0] === "function") return this.protectAppPage(args[0], args[1]);
453
- return this.protectPagePage(args[0]);
454
- }
455
- protectAppPage(component, options) {
456
- return async (params) => {
457
- const session = await this.getSession();
458
- if (!session) {
459
- var _options$authParams, _options$authParams2, _options$authParams3, _options$authParams4, _options$authParams5, _options$authParams6, _options$authParams7, _options$authParams8, _options$authParams9;
460
- if (options === null || options === void 0 ? void 0 : options.onAccessDenied) return options.onAccessDenied({ ...params });
461
- const { routes, appUrl } = this.getOptions();
462
- const { headers } = await import("next/headers");
463
- const path = (await headers()).get("x-monocloud-path");
464
- const signInRoute = new URL(`${appUrl}${ensureLeadingSlash(routes.signIn)}`);
465
- signInRoute.searchParams.set("return_url", (options === null || options === void 0 ? void 0 : options.returnUrl) ?? path ?? "/");
466
- if (options === null || options === void 0 || (_options$authParams = options.authParams) === null || _options$authParams === void 0 ? void 0 : _options$authParams.scopes) signInRoute.searchParams.set("scope", options.authParams.scopes);
467
- if (options === null || options === void 0 || (_options$authParams2 = options.authParams) === null || _options$authParams2 === void 0 ? void 0 : _options$authParams2.resource) signInRoute.searchParams.set("resource", options.authParams.resource);
468
- if (options === null || options === void 0 || (_options$authParams3 = options.authParams) === null || _options$authParams3 === void 0 ? void 0 : _options$authParams3.acrValues) signInRoute.searchParams.set("acr_values", options.authParams.acrValues.join(" "));
469
- if (options === null || options === void 0 || (_options$authParams4 = options.authParams) === null || _options$authParams4 === void 0 ? void 0 : _options$authParams4.display) signInRoute.searchParams.set("display", options.authParams.display);
470
- if (options === null || options === void 0 || (_options$authParams5 = options.authParams) === null || _options$authParams5 === void 0 ? void 0 : _options$authParams5.prompt) signInRoute.searchParams.set("prompt", options.authParams.prompt);
471
- if (options === null || options === void 0 || (_options$authParams6 = options.authParams) === null || _options$authParams6 === void 0 ? void 0 : _options$authParams6.authenticatorHint) signInRoute.searchParams.set("authenticator_hint", options.authParams.authenticatorHint);
472
- if (options === null || options === void 0 || (_options$authParams7 = options.authParams) === null || _options$authParams7 === void 0 ? void 0 : _options$authParams7.uiLocales) signInRoute.searchParams.set("ui_locales", options.authParams.uiLocales);
473
- if (options === null || options === void 0 || (_options$authParams8 = options.authParams) === null || _options$authParams8 === void 0 ? void 0 : _options$authParams8.maxAge) signInRoute.searchParams.set("max_age", options.authParams.maxAge.toString());
474
- if (options === null || options === void 0 || (_options$authParams9 = options.authParams) === null || _options$authParams9 === void 0 ? void 0 : _options$authParams9.loginHint) signInRoute.searchParams.set("login_hint", options.authParams.loginHint);
475
- const { redirect } = await import("next/navigation");
476
- return redirect(signInRoute.toString());
477
- }
478
- if ((options === null || options === void 0 ? void 0 : options.groups) && !isUserInGroup$1(session.user, options.groups, options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options.matchAll)) {
479
- if (options.onGroupAccessDenied) return options.onGroupAccessDenied({
480
- ...params,
481
- user: session.user
482
- });
483
- return "Access Denied";
484
- }
485
- return component({
486
- ...params,
487
- user: session.user
488
- });
489
- };
490
- }
491
- protectPagePage(options) {
492
- return async (context) => {
493
- const session = await this.getSession(context.req, context.res);
494
- if (!session) {
495
- var _options$authParams10, _options$authParams11, _options$authParams12, _options$authParams13, _options$authParams14, _options$authParams15, _options$authParams16, _options$authParams17, _options$authParams18;
496
- if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
497
- const customProps = await options.onAccessDenied({ ...context });
498
- return {
499
- ...customProps ?? {},
500
- props: { ...(customProps === null || customProps === void 0 ? void 0 : customProps.props) ?? {} }
501
- };
502
- }
503
- const { routes, appUrl } = this.getOptions();
504
- const signInRoute = new URL(`${appUrl}${ensureLeadingSlash(routes.signIn)}`);
505
- signInRoute.searchParams.set("return_url", (options === null || options === void 0 ? void 0 : options.returnUrl) ?? context.resolvedUrl);
506
- if (options === null || options === void 0 || (_options$authParams10 = options.authParams) === null || _options$authParams10 === void 0 ? void 0 : _options$authParams10.scopes) signInRoute.searchParams.set("scope", options.authParams.scopes);
507
- if (options === null || options === void 0 || (_options$authParams11 = options.authParams) === null || _options$authParams11 === void 0 ? void 0 : _options$authParams11.resource) signInRoute.searchParams.set("resource", options.authParams.resource);
508
- if (options === null || options === void 0 || (_options$authParams12 = options.authParams) === null || _options$authParams12 === void 0 ? void 0 : _options$authParams12.acrValues) signInRoute.searchParams.set("acr_values", options.authParams.acrValues.join(" "));
509
- if (options === null || options === void 0 || (_options$authParams13 = options.authParams) === null || _options$authParams13 === void 0 ? void 0 : _options$authParams13.display) signInRoute.searchParams.set("display", options.authParams.display);
510
- if (options === null || options === void 0 || (_options$authParams14 = options.authParams) === null || _options$authParams14 === void 0 ? void 0 : _options$authParams14.prompt) signInRoute.searchParams.set("prompt", options.authParams.prompt);
511
- if (options === null || options === void 0 || (_options$authParams15 = options.authParams) === null || _options$authParams15 === void 0 ? void 0 : _options$authParams15.authenticatorHint) signInRoute.searchParams.set("authenticator_hint", options.authParams.authenticatorHint);
512
- if (options === null || options === void 0 || (_options$authParams16 = options.authParams) === null || _options$authParams16 === void 0 ? void 0 : _options$authParams16.uiLocales) signInRoute.searchParams.set("ui_locales", options.authParams.uiLocales);
513
- if (options === null || options === void 0 || (_options$authParams17 = options.authParams) === null || _options$authParams17 === void 0 ? void 0 : _options$authParams17.maxAge) signInRoute.searchParams.set("max_age", options.authParams.maxAge.toString());
514
- if (options === null || options === void 0 || (_options$authParams18 = options.authParams) === null || _options$authParams18 === void 0 ? void 0 : _options$authParams18.loginHint) signInRoute.searchParams.set("login_hint", options.authParams.loginHint);
515
- return { redirect: {
516
- destination: signInRoute.toString(),
517
- permanent: false
518
- } };
519
- }
520
- if ((options === null || options === void 0 ? void 0 : options.groups) && !isUserInGroup$1(session.user, options.groups, options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options.matchAll)) {
521
- var _options$onGroupAcces;
522
- const customProps = await ((_options$onGroupAcces = options.onGroupAccessDenied) === null || _options$onGroupAcces === void 0 ? void 0 : _options$onGroupAcces.call(options, {
523
- ...context,
524
- user: session.user
525
- })) ?? { props: { groupAccessDenied: true } };
526
- return {
527
- ...customProps,
528
- props: { ...customProps.props ?? {} }
529
- };
530
- }
531
- const customProps = (options === null || options === void 0 ? void 0 : options.getServerSideProps) ? await options.getServerSideProps(context) : {};
532
- const promiseProp = customProps.props;
533
- if (promiseProp instanceof Promise) return {
534
- ...customProps,
535
- props: promiseProp.then((props) => ({
536
- user: session.user,
537
- ...props
538
- }))
539
- };
540
- return {
541
- ...customProps,
542
- props: {
543
- user: session.user,
544
- ...customProps.props
545
- }
546
- };
547
- };
548
- }
549
- protectApi(handler, options) {
550
- return (req, resOrCtx) => {
551
- if (isAppRouter(req)) return this.protectAppApi(req, resOrCtx, handler, options);
552
- return this.protectPageApi(req, resOrCtx, handler, options);
553
- };
554
- }
555
- async protectAppApi(req, ctx, handler, options) {
556
- const res = new NextResponse();
557
- const session = await this.getSession(req, res);
558
- if (!session) {
559
- if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
560
- const result = await options.onAccessDenied(req, ctx);
561
- if (result instanceof NextResponse) return mergeResponse([res, result]);
562
- return mergeResponse([res, new NextResponse(result.body, result)]);
563
- }
564
- return mergeResponse([res, NextResponse.json({ message: "unauthorized" }, { status: 401 })]);
565
- }
566
- if ((options === null || options === void 0 ? void 0 : options.groups) && !isUserInGroup$1(session.user, options.groups, options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options.matchAll)) {
567
- if (options.onGroupAccessDenied) {
568
- const result = await options.onGroupAccessDenied(req, ctx, session.user);
569
- if (result instanceof NextResponse) return mergeResponse([res, result]);
570
- return mergeResponse([res, new NextResponse(result.body, result)]);
571
- }
572
- return mergeResponse([res, NextResponse.json({ message: "forbidden" }, { status: 403 })]);
573
- }
574
- const resp = await handler(req, ctx);
575
- if (resp instanceof NextResponse) return mergeResponse([res, resp]);
576
- return mergeResponse([res, new NextResponse(resp.body, resp)]);
577
- }
578
- async protectPageApi(req, res, handler, options) {
579
- const session = await this.getSession(req, res);
580
- if (!session) {
581
- if (options === null || options === void 0 ? void 0 : options.onAccessDenied) return options.onAccessDenied(req, res);
582
- return res.status(401).json({ message: "unauthorized" });
583
- }
584
- if ((options === null || options === void 0 ? void 0 : options.groups) && !isUserInGroup$1(session.user, options.groups, options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options.matchAll)) {
585
- if (options.onGroupAccessDenied) return options.onGroupAccessDenied(req, res, session.user);
586
- return res.status(403).json({ message: "forbidden" });
587
- }
588
- return handler(req, res);
589
- }
590
- authMiddleware(...args) {
591
- let req;
592
- let evt;
593
- let options;
594
- /* v8 ignore else -- @preserve */
595
- if (Array.isArray(args)) {
596
- if (args.length === 2) {
597
- /* v8 ignore else -- @preserve */
598
- if (isAppRouter(args[0])) {
599
- req = args[0];
600
- evt = args[1];
601
- }
602
- }
603
- if (args.length === 1) options = args[0];
604
- }
605
- if (req && evt) return this.authMiddlewareHandler(req, evt, options);
606
- return (request, nxtEvt) => {
607
- return this.authMiddlewareHandler(request, nxtEvt, options);
608
- };
609
- }
610
- async authMiddlewareHandler(req, evt, options) {
611
- req = getNextRequest(req);
612
- if (req.headers.has("x-middleware-subrequest")) return NextResponse.json({ message: "forbidden" }, { status: 403 });
613
- const { routes, appUrl } = this.getOptions();
614
- if (Object.values(routes).map((x) => ensureLeadingSlash(x)).includes(req.nextUrl.pathname)) {
615
- let onError;
616
- if (typeof (options === null || options === void 0 ? void 0 : options.onError) === "function") onError = (error) => options.onError(req, evt, error);
617
- const request = new MonoCloudAppRouterRequest(req);
618
- const response = new MonoCloudAppRouterResponse(new NextResponse());
619
- return this.handleAuthRoutes(request, response, req.nextUrl.pathname, routes, onError);
620
- }
621
- const nxtResp = new NextResponse();
622
- nxtResp.headers.set("x-monocloud-path", req.nextUrl.pathname + req.nextUrl.search);
623
- let isRouteProtected = true;
624
- let allowedGroups;
625
- if (typeof (options === null || options === void 0 ? void 0 : options.protectedRoutes) === "function") isRouteProtected = await options.protectedRoutes(req);
626
- else if (typeof (options === null || options === void 0 ? void 0 : options.protectedRoutes) !== "undefined" && Array.isArray(options.protectedRoutes)) isRouteProtected = options.protectedRoutes.some((route) => {
627
- if (typeof route === "string" || route instanceof RegExp) return new RegExp(route).test(req.nextUrl.pathname);
628
- return route.routes.some((groupRoute) => {
629
- const result = new RegExp(groupRoute).test(req.nextUrl.pathname);
630
- if (result) allowedGroups = route.groups;
631
- return result;
632
- });
633
- });
634
- if (!isRouteProtected) return NextResponse.next({ headers: { "x-monocloud-path": req.nextUrl.pathname + req.nextUrl.search } });
635
- const session = await this.getSession(req, nxtResp);
636
- if (!session) {
637
- if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
638
- const result = await options.onAccessDenied(req, evt);
639
- if (result instanceof NextResponse) return mergeResponse([nxtResp, result]);
640
- if (result) return mergeResponse([nxtResp, new NextResponse(result.body, result)]);
641
- return NextResponse.next(nxtResp);
642
- }
643
- if (req.nextUrl.pathname.startsWith("/api")) return mergeResponse([nxtResp, NextResponse.json({ message: "unauthorized" }, { status: 401 })]);
644
- const signInRoute = new URL(`${appUrl}${ensureLeadingSlash(routes.signIn)}`);
645
- signInRoute.searchParams.set("return_url", req.nextUrl.pathname + req.nextUrl.search);
646
- return mergeResponse([nxtResp, NextResponse.redirect(signInRoute)]);
647
- }
648
- const groupsClaim = (options === null || options === void 0 ? void 0 : options.groupsClaim) ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM;
649
- if (allowedGroups && !isUserInGroup$1(session.user, allowedGroups, groupsClaim)) {
650
- if (options === null || options === void 0 ? void 0 : options.onGroupAccessDenied) {
651
- const result = await options.onGroupAccessDenied(req, evt, session.user);
652
- if (result instanceof NextResponse) return mergeResponse([nxtResp, result]);
653
- if (result) return mergeResponse([nxtResp, new NextResponse(result.body, result)]);
654
- return NextResponse.next(nxtResp);
655
- }
656
- if (req.nextUrl.pathname.startsWith("/api")) return mergeResponse([nxtResp, NextResponse.json({ message: "forbidden" }, { status: 403 })]);
657
- return new NextResponse(`forbidden`, { status: 403 });
658
- }
659
- return NextResponse.next(nxtResp);
660
- }
661
- handleAuthRoutes(request, response, path, routes, onError) {
662
- switch (path) {
663
- case ensureLeadingSlash(routes.signIn): return this.coreClient.signIn(request, response, { onError });
664
- case ensureLeadingSlash(routes.callback): return this.coreClient.callback(request, response, { onError });
665
- case ensureLeadingSlash(routes.userInfo): return this.coreClient.userInfo(request, response, { onError });
666
- case ensureLeadingSlash(routes.signOut): return this.coreClient.signOut(request, response, { onError });
667
- default:
668
- response.notFound();
669
- return response.done();
670
- }
671
- }
672
- async getSession(...args) {
673
- let request;
674
- let response;
675
- if (args.length === 0) {
676
- request = new MonoCloudCookieRequest();
677
- response = new MonoCloudCookieResponse();
678
- } else ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
679
- /* v8 ignore next -- @preserve */
680
- if (!isMonoCloudRequest(request) || !isMonoCloudResponse(response)) throw new MonoCloudValidationError$1("Invalid parameters passed to getSession()");
681
- return await this.coreClient.getSession(request, response);
682
- }
683
- async getTokens(...args) {
684
- let request;
685
- let response;
686
- let options;
687
- if (args.length === 0) {
688
- request = new MonoCloudCookieRequest();
689
- response = new MonoCloudCookieResponse();
690
- } else if (args.length === 1) if (args[0] instanceof Request) ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
691
- else {
692
- request = new MonoCloudCookieRequest();
693
- response = new MonoCloudCookieResponse();
694
- options = args[0];
695
- }
696
- else if (args.length === 2 && args[0] instanceof Request) if (args[1] instanceof Response) ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
697
- else {
698
- ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
699
- options = args[1];
700
- }
701
- else if (args.length === 2 && isNodeRequest(args[0]) && isNodeResponse(args[1])) ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
702
- else {
703
- ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
704
- options = args[2];
705
- }
706
- if (!isMonoCloudRequest(request) || !isMonoCloudResponse(response) || options && typeof options !== "object") throw new MonoCloudValidationError$1("Invalid parameters passed to getTokens()");
707
- return await this.coreClient.getTokens(request, response, options);
708
- }
709
- async isAuthenticated(...args) {
710
- let request;
711
- let response;
712
- if (args.length === 0) {
713
- request = new MonoCloudCookieRequest();
714
- response = new MonoCloudCookieResponse();
715
- } else ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
716
- /* v8 ignore next -- @preserve */
717
- if (!isMonoCloudRequest(request) || !isMonoCloudResponse(response)) throw new MonoCloudValidationError$1("Invalid parameters passed to isAuthenticated()");
718
- return await this.coreClient.isAuthenticated(request, response);
719
- }
720
- /**
721
- * @see {@link protect} for full docs and examples.
722
- * @param options Optional configuration for redirect behavior (for example, return URL or sign-in parameters).
723
- * @returns Resolves if the user is authenticated; otherwise triggers a redirect.
724
- */
725
- async protect(options) {
726
- var _options$authParams19, _options$authParams20, _options$authParams21, _options$authParams22, _options$authParams23, _options$authParams24, _options$authParams25, _options$authParams26, _options$authParams27;
727
- const { routes, appUrl } = this.coreClient.getOptions();
728
- let path;
729
- try {
730
- const session = await this.getSession();
731
- if (session && !(options === null || options === void 0 ? void 0 : options.groups)) return;
732
- if (session && (options === null || options === void 0 ? void 0 : options.groups) && isUserInGroup$1(session.user, options.groups, options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options.matchAll)) return;
733
- const { headers } = await import("next/headers");
734
- path = (await headers()).get("x-monocloud-path") ?? "/";
735
- } catch {
736
- throw new Error("protect() can only be used in App Router server environments (RSC, route handlers, or server actions)");
737
- }
738
- const signInRoute = new URL(`${appUrl}${routes.signIn}`);
739
- signInRoute.searchParams.set("return_url", (options === null || options === void 0 ? void 0 : options.returnUrl) ?? path);
740
- if (options === null || options === void 0 || (_options$authParams19 = options.authParams) === null || _options$authParams19 === void 0 ? void 0 : _options$authParams19.maxAge) signInRoute.searchParams.set("max_age", options.authParams.maxAge.toString());
741
- if (options === null || options === void 0 || (_options$authParams20 = options.authParams) === null || _options$authParams20 === void 0 ? void 0 : _options$authParams20.authenticatorHint) signInRoute.searchParams.set("authenticator_hint", options.authParams.authenticatorHint);
742
- if (options === null || options === void 0 || (_options$authParams21 = options.authParams) === null || _options$authParams21 === void 0 ? void 0 : _options$authParams21.scopes) signInRoute.searchParams.set("scope", options.authParams.scopes);
743
- if (options === null || options === void 0 || (_options$authParams22 = options.authParams) === null || _options$authParams22 === void 0 ? void 0 : _options$authParams22.resource) signInRoute.searchParams.set("resource", options.authParams.resource);
744
- if (options === null || options === void 0 || (_options$authParams23 = options.authParams) === null || _options$authParams23 === void 0 ? void 0 : _options$authParams23.display) signInRoute.searchParams.set("display", options.authParams.display);
745
- if (options === null || options === void 0 || (_options$authParams24 = options.authParams) === null || _options$authParams24 === void 0 ? void 0 : _options$authParams24.uiLocales) signInRoute.searchParams.set("ui_locales", options.authParams.uiLocales);
746
- if (Array.isArray(options === null || options === void 0 || (_options$authParams25 = options.authParams) === null || _options$authParams25 === void 0 ? void 0 : _options$authParams25.acrValues)) signInRoute.searchParams.set("acr_values", options.authParams.acrValues.join(" "));
747
- if (options === null || options === void 0 || (_options$authParams26 = options.authParams) === null || _options$authParams26 === void 0 ? void 0 : _options$authParams26.loginHint) signInRoute.searchParams.set("login_hint", options.authParams.loginHint);
748
- if (options === null || options === void 0 || (_options$authParams27 = options.authParams) === null || _options$authParams27 === void 0 ? void 0 : _options$authParams27.prompt) signInRoute.searchParams.set("prompt", options.authParams.prompt);
749
- const { redirect } = await import("next/navigation");
750
- redirect(signInRoute.toString());
751
- }
752
- async isUserInGroup(...args) {
753
- let request;
754
- let response;
755
- let groups;
756
- let options;
757
- if (args.length === 4) {
758
- groups = args[2];
759
- options = args[3];
760
- ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
761
- }
762
- if (args.length === 3) {
763
- if (args[0] instanceof Request) if (args[1] instanceof Response) {
764
- ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
765
- groups = args[2];
766
- } else {
767
- ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
768
- groups = args[1];
769
- options = args[2];
770
- }
771
- if (isNodeRequest(args[0]) && isNodeResponse(args[1])) {
772
- ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
773
- groups = args[2];
774
- }
775
- }
776
- if (args.length === 2) {
777
- if (args[0] instanceof Request) {
778
- ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
779
- groups = args[1];
780
- }
781
- if (Array.isArray(args[0])) {
782
- request = new MonoCloudCookieRequest();
783
- response = new MonoCloudCookieResponse();
784
- groups = args[0];
785
- options = args[1];
786
- }
787
- }
788
- if (args.length === 1) {
789
- request = new MonoCloudCookieRequest();
790
- response = new MonoCloudCookieResponse();
791
- groups = args[0];
792
- }
793
- if (!Array.isArray(groups) || !isMonoCloudRequest(request) || !isMonoCloudResponse(response) || options && typeof options !== "object") throw new MonoCloudValidationError$1("Invalid parameters passed to isUserInGroup()");
794
- return await this.coreClient.isUserInGroup(request, response, groups, (options === null || options === void 0 ? void 0 : options.groupsClaim) ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options === null || options === void 0 ? void 0 : options.matchAll);
795
- }
796
- /**
797
- * @see {@link redirectToSignIn} for full docs and examples.
798
- * @param options Optional configuration for the redirect, such as `returnUrl` or additional sign-in parameters.
799
- * @returns Never resolves. Triggers a redirect to the sign-in flow.
800
- */
801
- async redirectToSignIn(options) {
802
- const { routes, appUrl } = this.coreClient.getOptions();
803
- try {
804
- const { headers } = await import("next/headers");
805
- await headers();
806
- } catch {
807
- throw new Error("redirectToSignIn() can only be used in App Router server environments (RSC, route handlers, or server actions)");
808
- }
809
- const signInRoute = new URL(`${appUrl}${routes.signIn}`);
810
- if (options === null || options === void 0 ? void 0 : options.returnUrl) signInRoute.searchParams.set("return_url", options.returnUrl);
811
- if (options === null || options === void 0 ? void 0 : options.maxAge) signInRoute.searchParams.set("max_age", options.maxAge.toString());
812
- if (options === null || options === void 0 ? void 0 : options.authenticatorHint) signInRoute.searchParams.set("authenticator_hint", options.authenticatorHint);
813
- if (options === null || options === void 0 ? void 0 : options.scopes) signInRoute.searchParams.set("scope", options.scopes);
814
- if (options === null || options === void 0 ? void 0 : options.resource) signInRoute.searchParams.set("resource", options.resource);
815
- if (options === null || options === void 0 ? void 0 : options.display) signInRoute.searchParams.set("display", options.display);
816
- if (options === null || options === void 0 ? void 0 : options.uiLocales) signInRoute.searchParams.set("ui_locales", options.uiLocales);
817
- if (Array.isArray(options === null || options === void 0 ? void 0 : options.acrValues)) signInRoute.searchParams.set("acr_values", options.acrValues.join(" "));
818
- if (options === null || options === void 0 ? void 0 : options.loginHint) signInRoute.searchParams.set("login_hint", options.loginHint);
819
- if (options === null || options === void 0 ? void 0 : options.prompt) signInRoute.searchParams.set("prompt", options.prompt);
820
- const { redirect } = await import("next/navigation");
821
- redirect(signInRoute.toString());
822
- }
823
- /**
824
- * @see {@link redirectToSignOut} for full docs and examples.
825
- * @param options Optional configuration for the redirect, such as `postLogoutRedirectUri` or additional sign-out parameters.
826
- * @returns Never resolves. Triggers a redirect to the sign-out flow.
827
- */
828
- async redirectToSignOut(options) {
829
- var _options$postLogoutRe;
830
- const { routes, appUrl } = this.coreClient.getOptions();
831
- try {
832
- const { headers } = await import("next/headers");
833
- await headers();
834
- } catch {
835
- throw new Error("redirectToSignOut() can only be used in App Router server environments (RSC, route handlers, or server actions)");
836
- }
837
- const signOutRoute = new URL(`${appUrl}${routes.signOut}`);
838
- if (options === null || options === void 0 || (_options$postLogoutRe = options.postLogoutRedirectUri) === null || _options$postLogoutRe === void 0 ? void 0 : _options$postLogoutRe.trim().length) signOutRoute.searchParams.set("post_logout_url", options.postLogoutRedirectUri);
839
- if (typeof (options === null || options === void 0 ? void 0 : options.federated) === "boolean") signOutRoute.searchParams.set("federated", options.federated.toString());
840
- const { redirect } = await import("next/navigation");
841
- redirect(signOutRoute.toString());
842
- }
843
- getOptions() {
844
- return this.coreClient.getOptions();
845
- }
846
- registerPublicEnvVariables() {
847
- Object.keys(process.env).filter((key) => key.startsWith("NEXT_PUBLIC_MONOCLOUD_AUTH")).forEach((publicKey) => {
848
- const [, privateKey] = publicKey.split("NEXT_PUBLIC_");
849
- process.env[privateKey] = process.env[publicKey];
850
- });
851
- }
852
- };
853
-
854
- //#endregion
855
- //#region src/initialize.ts
856
- let instance;
857
- /**
858
- * Retrieves the singleton instance of the MonoCloudNextClient.
859
- * Initializes it lazily on the first call.
860
- */
861
- const getInstance = () => {
862
- instance ??= new MonoCloudNextClient();
863
- return instance;
864
- };
865
- /**
866
- * Creates a Next.js catch-all auth route handler (Pages Router and App Router) for the built-in routes (`/signin`, `/callback`, `/userinfo`, `/signout`).
867
- *
868
- * Mount this handler on a catch-all route (e.g. `/api/auth/[...monocloud]`).
869
- *
870
- * > 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.
871
- *
872
- * @example App Router
873
- * ```tsx:src/app/api/auth/[...monocloud]/route.ts tab="App Router" tab-group="monoCloudAuth"
874
- * import { monoCloudAuth } from "@monocloud/auth-nextjs";
875
- *
876
- * export const GET = monoCloudAuth();
877
- *```
878
- *
879
- * @example App Router (Response)
880
- * ```tsx:src/app/api/auth/[...monocloud]/route.ts tab="App Router (Response)" tab-group="monoCloudAuth"
881
- * import { monoCloudAuth } from "@monocloud/auth-nextjs";
882
- * import { NextRequest, NextResponse } from "next/server";
883
- *
884
- * export const GET = (req: NextRequest) => {
885
- * const authHandler = monoCloudAuth();
886
- *
887
- * const res = new NextResponse();
888
- *
889
- * res.cookies.set("last_auth_requested", `${Date.now()}`);
890
- *
891
- * return authHandler(req, res);
892
- * };
893
- * ```
894
- *
895
- * @example Pages Router
896
- * ```tsx:src/pages/api/auth/[...monocloud].ts tab="Pages Router" tab-group="monoCloudAuth"
897
- * import { monoCloudAuth } from "@monocloud/auth-nextjs";
898
- *
899
- * export default monoCloudAuth();
900
- *```
901
- *
902
- * @example Pages Router (Response)
903
- * ```tsx:src/pages/api/auth/[...monocloud].ts tab="Pages Router (Response)" tab-group="monoCloudAuth"
904
- * import { monoCloudAuth } from "@monocloud/auth-nextjs";
905
- * import { NextApiRequest, NextApiResponse } from "next";
906
- *
907
- * export default function handler(req: NextApiRequest, res: NextApiResponse) {
908
- * const authHandler = monoCloudAuth();
909
- *
910
- * res.setHeader("last_auth_requested", `${Date.now()}`);
911
- *
912
- * return authHandler(req, res);
913
- * }
914
- * ```
915
- *
916
- * @param options Optional configuration for the auth handler.
917
- * @returns Returns a Next.js-compatible handler for App Router route handlers or Pages Router API routes.
918
- *
919
- * @category Functions
920
- */
921
- function monoCloudAuth(options) {
922
- return getInstance().monoCloudAuth(options);
923
- }
924
- function authMiddleware(...args) {
925
- return getInstance().authMiddleware(...args);
926
- }
927
- function getSession(...args) {
928
- return getInstance().getSession(...args);
929
- }
930
- function getTokens(...args) {
931
- return getInstance().getTokens(...args);
932
- }
933
- function isAuthenticated(...args) {
934
- return getInstance().isAuthenticated(...args);
935
- }
936
- /**
937
- * Ensures the current user is authenticated. If not, redirects to the sign-in flow.
938
- *
939
- * > **App Router only.** Intended for Server Components, Route Handlers, and Server Actions.
940
- *
941
- * @example Server Component
942
- * ```tsx:src/app/page.tsx tab="Server Component" tab-group="protect"
943
- * import { protect } from "@monocloud/auth-nextjs";
944
- *
945
- * export default async function Home() {
946
- * await protect();
947
- *
948
- * return <>You are signed in.</>;
949
- * }
950
- * ```
951
- *
952
- * @example Server Action
953
- * ```tsx:src/action.ts tab="Server Action" tab-group="protect"
954
- * "use server";
955
- *
956
- * import { protect } from "@monocloud/auth-nextjs";
957
- *
958
- * export async function getMessage() {
959
- * await protect();
960
- *
961
- * return { secret: "sssshhhhh!!!" };
962
- * }
963
- * ```
964
- *
965
- * @example API Handler
966
- * ```tsx:src/app/api/protected/route.ts tab="API Handler" tab-group="protect"
967
- * import { protect } from "@monocloud/auth-nextjs";
968
- * import { NextResponse } from "next/server";
969
- *
970
- * export const GET = async () => {
971
- * await protect();
972
- *
973
- * return NextResponse.json({ secret: "ssshhhh!!!" });
974
- * };
975
- * ```
976
- *
977
- * @param options Optional configuration for redirect behavior (for example, return URL or sign-in parameters).
978
- * @returns Resolves if the user is authenticated; otherwise triggers a redirect.
979
- *
980
- * @category Functions
981
- */
982
- function protect(options) {
983
- return getInstance().protect(options);
984
- }
985
- function protectApi(handler, options) {
986
- return getInstance().protectApi(handler, options);
987
- }
988
- function protectPage(...args) {
989
- return getInstance().protectPage(...args);
990
- }
991
- function isUserInGroup(...args) {
992
- return getInstance().isUserInGroup(...args);
993
- }
994
- /**
995
- * Redirects the user to the sign-in flow.
996
- *
997
- * > **App Router only**. Intended for use in Server Components, Route Handlers, and Server Actions.
998
- *
999
- * This helper performs a server-side redirect to the configured sign-in route. Execution does not continue after the redirect is triggered.
1000
- *
1001
- * @example Server Component
1002
- * ```tsx:src/app/page.tsx tab="Server Component" tab-group="redirect-to-sign-in"
1003
- * import { isUserInGroup, redirectToSignIn } from "@monocloud/auth-nextjs";
1004
- *
1005
- * export default async function Home() {
1006
- * const allowed = await isUserInGroup(["admin"]);
1007
- *
1008
- * if (!allowed) {
1009
- * await redirectToSignIn({ returnUrl: "/home" });
1010
- * }
1011
- *
1012
- * return <>You are signed in.</>;
1013
- * }
1014
- * ```
1015
- *
1016
- * @example Server Action
1017
- * ```tsx:src/action.ts tab="Server Action" tab-group="redirect-to-sign-in"
1018
- * "use server";
1019
- *
1020
- * import { getSession, redirectToSignIn } from "@monocloud/auth-nextjs";
1021
- *
1022
- * export async function protectedAction() {
1023
- * const session = await getSession();
1024
- *
1025
- * if (!session) {
1026
- * await redirectToSignIn();
1027
- * }
1028
- *
1029
- * return { data: "Sensitive Data" };
1030
- * }
1031
- * ```
1032
- *
1033
- * @example API Handler
1034
- * ```tsx:src/app/api/protected/route.ts tab="API Handler" tab-group="redirect-to-sign-in"
1035
- * import { getSession, redirectToSignIn } from "@monocloud/auth-nextjs";
1036
- * import { NextResponse } from "next/server";
1037
- *
1038
- * export const GET = async () => {
1039
- * const session = await getSession();
1040
- *
1041
- * if (!session) {
1042
- * await redirectToSignIn({
1043
- * returnUrl: "/dashboard",
1044
- * });
1045
- * }
1046
- *
1047
- * return NextResponse.json({ data: "Protected content" });
1048
- * };
1049
- * ```
1050
- *
1051
- * @param options Optional configuration for the redirect, such as `returnUrl` or additional sign-in parameters.
1052
- * @returns Never resolves. Triggers a redirect to the sign-in flow.
1053
- *
1054
- * @category Functions
1055
- */
1056
- function redirectToSignIn(options) {
1057
- return getInstance().redirectToSignIn(options);
1058
- }
1059
- /**
1060
- * Redirects the user to the sign-out flow.
1061
- *
1062
- * > **App Router only**. Intended for use in Server Components, Route Handlers, and Server Actions.
1063
- *
1064
- * This helper performs a server-side redirect to the configured sign-out route. Execution does not continue after the redirect is triggered.
1065
- *
1066
- * @example Server Component
1067
- * ```tsx:src/app/page.tsx tab="Server Component" tab-group="redirect-to-sign-out"
1068
- * import { getSession, redirectToSignOut } from "@monocloud/auth-nextjs";
1069
- *
1070
- * export default async function Page() {
1071
- * const session = await getSession();
1072
- *
1073
- * // Example: Force sign-out if a specific condition is met (e.g., account suspended)
1074
- * if (session?.user.isSuspended) {
1075
- * await redirectToSignOut();
1076
- * }
1077
- *
1078
- * return <>Welcome User</>;
1079
- * }
1080
- * ```
1081
- *
1082
- * @example Server Action
1083
- * ```tsx:src/action.ts tab="Server Action" tab-group="redirect-to-sign-out"
1084
- * "use server";
1085
- *
1086
- * import { getSession, redirectToSignOut } from "@monocloud/auth-nextjs";
1087
- *
1088
- * export async function signOutAction() {
1089
- * const session = await getSession();
1090
- *
1091
- * if (session) {
1092
- * await redirectToSignOut();
1093
- * }
1094
- * }
1095
- * ```
1096
- *
1097
- * @example API Handler
1098
- * ```tsx:src/app/api/signout/route.ts tab="API Handler" tab-group="redirect-to-sign-out"
1099
- * import { getSession, redirectToSignOut } from "@monocloud/auth-nextjs";
1100
- * import { NextResponse } from "next/server";
1101
- *
1102
- * export const GET = async () => {
1103
- * const session = await getSession();
1104
- *
1105
- * if (session) {
1106
- * await redirectToSignOut({
1107
- * postLogoutRedirectUri: "/goodbye",
1108
- * });
1109
- * }
1110
- *
1111
- * return NextResponse.json({ status: "already_signed_out" });
1112
- * };
1113
- * ```
1114
- *
1115
- * @param options Optional configuration for the redirect, such as `postLogoutRedirectUri` or additional sign-out parameters.
1116
- * @returns Never resolves. Triggers a redirect to the sign-out flow.
1117
- *
1118
- * @category Functions
1119
- */
1120
- function redirectToSignOut(options) {
1121
- return getInstance().redirectToSignOut(options);
1122
- }
1123
-
1124
- //#endregion
1125
- export { MonoCloudAuthBaseError, MonoCloudHttpError, MonoCloudNextClient, MonoCloudOPError, MonoCloudTokenError, MonoCloudValidationError, authMiddleware, getSession, getTokens, isAuthenticated, isUserInGroup, monoCloudAuth, protect, protectApi, protectPage, redirectToSignIn, redirectToSignOut };
1126
- //# sourceMappingURL=index.mjs.map
5
+ export { MonoCloudAuthBaseError, MonoCloudHttpError, MonoCloudNextClient, MonoCloudOPError, MonoCloudTokenError, MonoCloudValidationError, authMiddleware, getSession, getTokens, isAuthenticated, isUserInGroup, monoCloudAuth, protect, protectApi, protectPage, redirectToSignIn, redirectToSignOut };