@monocloud/auth-nextjs 0.1.10 → 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,600 @@
1
+ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
2
+ const require_monocloud_app_router_request = require('./requests/monocloud-app-router-request.cjs');
3
+ const require_monocloud_page_router_request = require('./requests/monocloud-page-router-request.cjs');
4
+ const require_monocloud_app_router_response = require('./responses/monocloud-app-router-response.cjs');
5
+ const require_monocloud_page_router_response = require('./responses/monocloud-page-router-response.cjs');
6
+ const require_monocloud_cookie_response = require('./responses/monocloud-cookie-response.cjs');
7
+ const require_monocloud_cookie_request = require('./requests/monocloud-cookie-request.cjs');
8
+ const require_utils = require('./utils.cjs');
9
+ let _monocloud_auth_node_core = require("@monocloud/auth-node-core");
10
+ let next_server_js = require("next/server.js");
11
+ let _monocloud_auth_node_core_internal = require("@monocloud/auth-node-core/internal");
12
+ let _monocloud_auth_node_core_utils = require("@monocloud/auth-node-core/utils");
13
+
14
+ //#region src/monocloud-next-client.ts
15
+ /**
16
+ * `MonoCloudNextClient` is the core SDK entry point for integrating MonoCloud authentication into a Next.js application.
17
+ *
18
+ * It provides:
19
+ * - Authentication middleware
20
+ * - Route protection helpers
21
+ * - Session and token access
22
+ * - Redirect utilities
23
+ * - Server-side enforcement helpers
24
+ *
25
+ * ## 1. Add environment variables
26
+ *
27
+ * ```bash:.env.local
28
+ * MONOCLOUD_AUTH_TENANT_DOMAIN=<tenant-domain>
29
+ * MONOCLOUD_AUTH_CLIENT_ID=<client-id>
30
+ * MONOCLOUD_AUTH_CLIENT_SECRET=<client-secret>
31
+ * MONOCLOUD_AUTH_SCOPES=openid profile email
32
+ * MONOCLOUD_AUTH_APP_URL=http://localhost:3000
33
+ * MONOCLOUD_AUTH_COOKIE_SECRET=<cookie-secret>
34
+ * ```
35
+ *
36
+ * ## 2. Register middleware
37
+ *
38
+ * ```typescript:src/proxy.ts
39
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
40
+ *
41
+ * export default authMiddleware();
42
+ *
43
+ * export const config = {
44
+ * matcher: [
45
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
46
+ * ],
47
+ * };
48
+ * ```
49
+ *
50
+ * ## Advanced usage
51
+ *
52
+ * ### Create a shared client instance
53
+ *
54
+ * By default, the SDK exposes function exports (for example, `authMiddleware()`, `getSession()`, `getTokens()`) that internally use a shared singleton `MonoCloudNextClient`.
55
+ *
56
+ * Create your own `MonoCloudNextClient` instance when you need multiple configurations, dependency injection, or explicit control over initialization.
57
+ *
58
+ * ```ts:src/monocloud.ts
59
+ * import { MonoCloudNextClient } from "@monocloud/auth-nextjs";
60
+ *
61
+ * export const monoCloud = new MonoCloudNextClient();
62
+ * ```
63
+ *
64
+ * ### Using instance methods
65
+ *
66
+ * Once you create a client instance, call methods directly on it instead of using the default function exports.
67
+ *
68
+ * ```ts:src/app/page.tsx
69
+ * import { monoCloud } from "@/monocloud";
70
+ *
71
+ * export default async function Page() {
72
+ * const session = await monoCloud.getSession();
73
+ *
74
+ * if (!session) {
75
+ * return <>Not signed in</>;
76
+ * }
77
+ *
78
+ * return <>Hello {session.user.name}</>;
79
+ * }
80
+ * ```
81
+ *
82
+ * #### Using constructor options
83
+ *
84
+ * 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.
85
+ *
86
+ * ```ts:src/monocloud.ts
87
+ * import { MonoCloudNextClient } from "@monocloud/auth-nextjs";
88
+ *
89
+ * export const monoCloud = new MonoCloudNextClient({
90
+ * tenantDomain: "<tenant-domain>",
91
+ * clientId: "<client-id>",
92
+ * clientSecret: "<client-secret>",
93
+ * appUrl: "http://localhost:3000",
94
+ * cookieSecret: "<cookie-secret>",
95
+ * defaultAuthParams: {
96
+ * scopes: "openid profile email",
97
+ * },
98
+ * });
99
+ * ```
100
+ *
101
+ * ### Modifying default routes
102
+ *
103
+ * If you customize any of the default auth route paths:
104
+ *
105
+ * - Also set the corresponding `NEXT_PUBLIC_` environment variables so client-side helpers
106
+ * (for example `<SignIn />`, `<SignOut />`, and `useAuth()`) can discover the correct URLs.
107
+ * - Update the **Application URLs** in your MonoCloud Dashboard to match the new paths.
108
+ *
109
+ * Example:
110
+ *
111
+ * ```bash:.env.local
112
+ * MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
113
+ * NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
114
+ * ```
115
+ *
116
+ * When routes are overridden, the Redirect URI configured in the dashboard
117
+ * must reflect the new path. For example, during local development:
118
+ *
119
+ * `http://localhost:3000/api/custom_callback`
120
+ *
121
+ * @category Classes
122
+ */
123
+ var MonoCloudNextClient = class {
124
+ /**
125
+ * This exposes the framework-agnostic MonoCloud client used internally by the Next.js SDK.
126
+ * Use it if you need access to lower-level functionality not directly exposed by MonoCloudNextClient.
127
+ *
128
+ * @returns Returns the underlying **Node client** instance.
129
+ */
130
+ get coreClient() {
131
+ return this._coreClient;
132
+ }
133
+ /**
134
+ * This is intended for advanced scenarios requiring direct control over the authorization or token flow.
135
+ *
136
+ * @returns Returns the underlying **OIDC client** used for OpenID Connect operations.
137
+ */
138
+ get oidcClient() {
139
+ return this.coreClient.oidcClient;
140
+ }
141
+ /**
142
+ * Creates a new client instance.
143
+ *
144
+ * @param options Optional configuration for initializing the MonoCloud client. If not provided, settings are automatically resolved from environment variables.
145
+ */
146
+ constructor(options) {
147
+ const opt = {
148
+ ...options ?? {},
149
+ userAgent: (options === null || options === void 0 ? void 0 : options.userAgent) ?? `@monocloud/auth-nextjs@0.1.11`,
150
+ debugger: (options === null || options === void 0 ? void 0 : options.debugger) ?? "@monocloud:auth-nextjs"
151
+ };
152
+ this.registerPublicEnvVariables();
153
+ this._coreClient = new _monocloud_auth_node_core.MonoCloudCoreClient(opt);
154
+ }
155
+ /**
156
+ * @see {@link monoCloudAuth} for full docs and examples.
157
+ * @param options Optional configuration for the auth handler.
158
+ * @returns Returns a Next.js-compatible handler for App Router route handlers or Pages Router API routes.
159
+ */
160
+ monoCloudAuth(options) {
161
+ return (req, resOrCtx) => {
162
+ const { routes, appUrl } = this.getOptions();
163
+ let { url = "" } = req;
164
+ if (!(0, _monocloud_auth_node_core_internal.isAbsoluteUrl)(url)) url = new URL(url, appUrl).toString();
165
+ const route = new URL(url);
166
+ let onError;
167
+ if (typeof (options === null || options === void 0 ? void 0 : options.onError) === "function") onError = (error) => options.onError(req, resOrCtx, error);
168
+ let request;
169
+ let response;
170
+ if (require_utils.isAppRouter(req)) {
171
+ request = new require_monocloud_app_router_request.default(require_utils.getNextRequest(req));
172
+ response = new require_monocloud_app_router_response.default(require_utils.getNextResponse(resOrCtx));
173
+ } else {
174
+ request = new require_monocloud_page_router_request.default(req);
175
+ response = new require_monocloud_page_router_response.default(resOrCtx);
176
+ }
177
+ return this.handleAuthRoutes(request, response, route.pathname, routes, onError);
178
+ };
179
+ }
180
+ protectPage(...args) {
181
+ if (typeof args[0] === "function") return this.protectAppPage(args[0], args[1]);
182
+ return this.protectPagePage(args[0]);
183
+ }
184
+ protectAppPage(component, options) {
185
+ return async (params) => {
186
+ const session = await this.getSession();
187
+ if (!session) {
188
+ var _options$authParams, _options$authParams2, _options$authParams3, _options$authParams4, _options$authParams5, _options$authParams6, _options$authParams7, _options$authParams8, _options$authParams9;
189
+ if (options === null || options === void 0 ? void 0 : options.onAccessDenied) return options.onAccessDenied({ ...params });
190
+ const { routes, appUrl } = this.getOptions();
191
+ const { headers } = await import("next/headers");
192
+ const path = (await headers()).get("x-monocloud-path");
193
+ const signInRoute = new URL(`${appUrl}${(0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn)}`);
194
+ signInRoute.searchParams.set("return_url", (options === null || options === void 0 ? void 0 : options.returnUrl) ?? path ?? "/");
195
+ 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);
196
+ 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);
197
+ 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(" "));
198
+ 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);
199
+ 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);
200
+ 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);
201
+ 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);
202
+ 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());
203
+ 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);
204
+ const { redirect } = await import("next/navigation");
205
+ return redirect(signInRoute.toString());
206
+ }
207
+ if ((options === null || options === void 0 ? void 0 : options.groups) && !(0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, options.groups, options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options.matchAll)) {
208
+ if (options.onGroupAccessDenied) return options.onGroupAccessDenied({
209
+ ...params,
210
+ user: session.user
211
+ });
212
+ return "Access Denied";
213
+ }
214
+ return component({
215
+ ...params,
216
+ user: session.user
217
+ });
218
+ };
219
+ }
220
+ protectPagePage(options) {
221
+ return async (context) => {
222
+ const session = await this.getSession(context.req, context.res);
223
+ if (!session) {
224
+ var _options$authParams10, _options$authParams11, _options$authParams12, _options$authParams13, _options$authParams14, _options$authParams15, _options$authParams16, _options$authParams17, _options$authParams18;
225
+ if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
226
+ const customProps = await options.onAccessDenied({ ...context });
227
+ return {
228
+ ...customProps ?? {},
229
+ props: { ...(customProps === null || customProps === void 0 ? void 0 : customProps.props) ?? {} }
230
+ };
231
+ }
232
+ const { routes, appUrl } = this.getOptions();
233
+ const signInRoute = new URL(`${appUrl}${(0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn)}`);
234
+ signInRoute.searchParams.set("return_url", (options === null || options === void 0 ? void 0 : options.returnUrl) ?? context.resolvedUrl);
235
+ 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);
236
+ 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);
237
+ 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(" "));
238
+ 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);
239
+ 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);
240
+ 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);
241
+ 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);
242
+ 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());
243
+ 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);
244
+ return { redirect: {
245
+ destination: signInRoute.toString(),
246
+ permanent: false
247
+ } };
248
+ }
249
+ if ((options === null || options === void 0 ? void 0 : options.groups) && !(0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, options.groups, options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options.matchAll)) {
250
+ var _options$onGroupAcces;
251
+ const customProps = await ((_options$onGroupAcces = options.onGroupAccessDenied) === null || _options$onGroupAcces === void 0 ? void 0 : _options$onGroupAcces.call(options, {
252
+ ...context,
253
+ user: session.user
254
+ })) ?? { props: { groupAccessDenied: true } };
255
+ return {
256
+ ...customProps,
257
+ props: { ...customProps.props ?? {} }
258
+ };
259
+ }
260
+ const customProps = (options === null || options === void 0 ? void 0 : options.getServerSideProps) ? await options.getServerSideProps(context) : {};
261
+ const promiseProp = customProps.props;
262
+ if (promiseProp instanceof Promise) return {
263
+ ...customProps,
264
+ props: promiseProp.then((props) => ({
265
+ user: session.user,
266
+ ...props
267
+ }))
268
+ };
269
+ return {
270
+ ...customProps,
271
+ props: {
272
+ user: session.user,
273
+ ...customProps.props
274
+ }
275
+ };
276
+ };
277
+ }
278
+ protectApi(handler, options) {
279
+ return (req, resOrCtx) => {
280
+ if (require_utils.isAppRouter(req)) return this.protectAppApi(req, resOrCtx, handler, options);
281
+ return this.protectPageApi(req, resOrCtx, handler, options);
282
+ };
283
+ }
284
+ async protectAppApi(req, ctx, handler, options) {
285
+ const res = new next_server_js.NextResponse();
286
+ const session = await this.getSession(req, res);
287
+ if (!session) {
288
+ if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
289
+ const result = await options.onAccessDenied(req, ctx);
290
+ if (result instanceof next_server_js.NextResponse) return require_utils.mergeResponse([res, result]);
291
+ return require_utils.mergeResponse([res, new next_server_js.NextResponse(result.body, result)]);
292
+ }
293
+ return require_utils.mergeResponse([res, next_server_js.NextResponse.json({ message: "unauthorized" }, { status: 401 })]);
294
+ }
295
+ if ((options === null || options === void 0 ? void 0 : options.groups) && !(0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, options.groups, options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options.matchAll)) {
296
+ if (options.onGroupAccessDenied) {
297
+ const result = await options.onGroupAccessDenied(req, ctx, session.user);
298
+ if (result instanceof next_server_js.NextResponse) return require_utils.mergeResponse([res, result]);
299
+ return require_utils.mergeResponse([res, new next_server_js.NextResponse(result.body, result)]);
300
+ }
301
+ return require_utils.mergeResponse([res, next_server_js.NextResponse.json({ message: "forbidden" }, { status: 403 })]);
302
+ }
303
+ const resp = await handler(req, ctx);
304
+ if (resp instanceof next_server_js.NextResponse) return require_utils.mergeResponse([res, resp]);
305
+ return require_utils.mergeResponse([res, new next_server_js.NextResponse(resp.body, resp)]);
306
+ }
307
+ async protectPageApi(req, res, handler, options) {
308
+ const session = await this.getSession(req, res);
309
+ if (!session) {
310
+ if (options === null || options === void 0 ? void 0 : options.onAccessDenied) return options.onAccessDenied(req, res);
311
+ return res.status(401).json({ message: "unauthorized" });
312
+ }
313
+ if ((options === null || options === void 0 ? void 0 : options.groups) && !(0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, options.groups, options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options.matchAll)) {
314
+ if (options.onGroupAccessDenied) return options.onGroupAccessDenied(req, res, session.user);
315
+ return res.status(403).json({ message: "forbidden" });
316
+ }
317
+ return handler(req, res);
318
+ }
319
+ authMiddleware(...args) {
320
+ let req;
321
+ let evt;
322
+ let options;
323
+ /* v8 ignore else -- @preserve */
324
+ if (Array.isArray(args)) {
325
+ if (args.length === 2) {
326
+ /* v8 ignore else -- @preserve */
327
+ if (require_utils.isAppRouter(args[0])) {
328
+ req = args[0];
329
+ evt = args[1];
330
+ }
331
+ }
332
+ if (args.length === 1) options = args[0];
333
+ }
334
+ if (req && evt) return this.authMiddlewareHandler(req, evt, options);
335
+ return (request, nxtEvt) => {
336
+ return this.authMiddlewareHandler(request, nxtEvt, options);
337
+ };
338
+ }
339
+ async authMiddlewareHandler(req, evt, options) {
340
+ req = require_utils.getNextRequest(req);
341
+ if (req.headers.has("x-middleware-subrequest")) return next_server_js.NextResponse.json({ message: "forbidden" }, { status: 403 });
342
+ const { routes, appUrl } = this.getOptions();
343
+ if (Object.values(routes).map((x) => (0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(x)).includes(req.nextUrl.pathname)) {
344
+ let onError;
345
+ if (typeof (options === null || options === void 0 ? void 0 : options.onError) === "function") onError = (error) => options.onError(req, evt, error);
346
+ const request = new require_monocloud_app_router_request.default(req);
347
+ const response = new require_monocloud_app_router_response.default(new next_server_js.NextResponse());
348
+ return this.handleAuthRoutes(request, response, req.nextUrl.pathname, routes, onError);
349
+ }
350
+ const nxtResp = new next_server_js.NextResponse();
351
+ nxtResp.headers.set("x-monocloud-path", req.nextUrl.pathname + req.nextUrl.search);
352
+ let isRouteProtected = true;
353
+ let allowedGroups;
354
+ if (typeof (options === null || options === void 0 ? void 0 : options.protectedRoutes) === "function") isRouteProtected = await options.protectedRoutes(req);
355
+ else if (typeof (options === null || options === void 0 ? void 0 : options.protectedRoutes) !== "undefined" && Array.isArray(options.protectedRoutes)) isRouteProtected = options.protectedRoutes.some((route) => {
356
+ if (typeof route === "string" || route instanceof RegExp) return new RegExp(route).test(req.nextUrl.pathname);
357
+ return route.routes.some((groupRoute) => {
358
+ const result = new RegExp(groupRoute).test(req.nextUrl.pathname);
359
+ if (result) allowedGroups = route.groups;
360
+ return result;
361
+ });
362
+ });
363
+ if (!isRouteProtected) return next_server_js.NextResponse.next({ headers: { "x-monocloud-path": req.nextUrl.pathname + req.nextUrl.search } });
364
+ const session = await this.getSession(req, nxtResp);
365
+ if (!session) {
366
+ if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
367
+ const result = await options.onAccessDenied(req, evt);
368
+ if (result instanceof next_server_js.NextResponse) return require_utils.mergeResponse([nxtResp, result]);
369
+ if (result) return require_utils.mergeResponse([nxtResp, new next_server_js.NextResponse(result.body, result)]);
370
+ return next_server_js.NextResponse.next(nxtResp);
371
+ }
372
+ if (req.nextUrl.pathname.startsWith("/api")) return require_utils.mergeResponse([nxtResp, next_server_js.NextResponse.json({ message: "unauthorized" }, { status: 401 })]);
373
+ const signInRoute = new URL(`${appUrl}${(0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn)}`);
374
+ signInRoute.searchParams.set("return_url", req.nextUrl.pathname + req.nextUrl.search);
375
+ return require_utils.mergeResponse([nxtResp, next_server_js.NextResponse.redirect(signInRoute)]);
376
+ }
377
+ const groupsClaim = (options === null || options === void 0 ? void 0 : options.groupsClaim) ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM;
378
+ if (allowedGroups && !(0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, allowedGroups, groupsClaim)) {
379
+ if (options === null || options === void 0 ? void 0 : options.onGroupAccessDenied) {
380
+ const result = await options.onGroupAccessDenied(req, evt, session.user);
381
+ if (result instanceof next_server_js.NextResponse) return require_utils.mergeResponse([nxtResp, result]);
382
+ if (result) return require_utils.mergeResponse([nxtResp, new next_server_js.NextResponse(result.body, result)]);
383
+ return next_server_js.NextResponse.next(nxtResp);
384
+ }
385
+ if (req.nextUrl.pathname.startsWith("/api")) return require_utils.mergeResponse([nxtResp, next_server_js.NextResponse.json({ message: "forbidden" }, { status: 403 })]);
386
+ return new next_server_js.NextResponse(`forbidden`, { status: 403 });
387
+ }
388
+ return next_server_js.NextResponse.next(nxtResp);
389
+ }
390
+ handleAuthRoutes(request, response, path, routes, onError) {
391
+ switch (path) {
392
+ case (0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn): return this.coreClient.signIn(request, response, { onError });
393
+ case (0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.callback): return this.coreClient.callback(request, response, { onError });
394
+ case (0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.userInfo): return this.coreClient.userInfo(request, response, { onError });
395
+ case (0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signOut): return this.coreClient.signOut(request, response, { onError });
396
+ default:
397
+ response.notFound();
398
+ return response.done();
399
+ }
400
+ }
401
+ async getSession(...args) {
402
+ let request;
403
+ let response;
404
+ let options;
405
+ if (args.length === 0) {
406
+ request = new require_monocloud_cookie_request.default();
407
+ response = new require_monocloud_cookie_response.default();
408
+ } else if (args.length === 1) if (args[0] instanceof Request) ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], void 0));
409
+ else {
410
+ request = new require_monocloud_cookie_request.default();
411
+ response = new require_monocloud_cookie_response.default();
412
+ options = args[0];
413
+ }
414
+ else if (args.length === 2 && args[0] instanceof Request) if (args[1] instanceof Response) ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], args[1]));
415
+ else {
416
+ ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], void 0));
417
+ options = args[1];
418
+ }
419
+ else if (args.length === 2 && require_utils.isNodeRequest(args[0]) && require_utils.isNodeResponse(args[1])) ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], args[1]));
420
+ else {
421
+ ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], args[1]));
422
+ options = args[2];
423
+ }
424
+ if (!require_utils.isMonoCloudRequest(request) || !require_utils.isMonoCloudResponse(response) || options && typeof options !== "object") throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to getSession()");
425
+ return await this.coreClient.getSession(request, response, options);
426
+ }
427
+ async getTokens(...args) {
428
+ let request;
429
+ let response;
430
+ let options;
431
+ if (args.length === 0) {
432
+ request = new require_monocloud_cookie_request.default();
433
+ response = new require_monocloud_cookie_response.default();
434
+ } else if (args.length === 1) if (args[0] instanceof Request) ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], void 0));
435
+ else {
436
+ request = new require_monocloud_cookie_request.default();
437
+ response = new require_monocloud_cookie_response.default();
438
+ options = args[0];
439
+ }
440
+ else if (args.length === 2 && args[0] instanceof Request) if (args[1] instanceof Response) ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], args[1]));
441
+ else {
442
+ ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], void 0));
443
+ options = args[1];
444
+ }
445
+ else if (args.length === 2 && require_utils.isNodeRequest(args[0]) && require_utils.isNodeResponse(args[1])) ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], args[1]));
446
+ else {
447
+ ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], args[1]));
448
+ options = args[2];
449
+ }
450
+ if (!require_utils.isMonoCloudRequest(request) || !require_utils.isMonoCloudResponse(response) || options && typeof options !== "object") throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to getTokens()");
451
+ return await this.coreClient.getTokens(request, response, options);
452
+ }
453
+ async isAuthenticated(...args) {
454
+ let request;
455
+ let response;
456
+ if (args.length === 0) {
457
+ request = new require_monocloud_cookie_request.default();
458
+ response = new require_monocloud_cookie_response.default();
459
+ } else ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], args[1]));
460
+ /* v8 ignore next -- @preserve */
461
+ if (!require_utils.isMonoCloudRequest(request) || !require_utils.isMonoCloudResponse(response)) throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to isAuthenticated()");
462
+ return await this.coreClient.isAuthenticated(request, response);
463
+ }
464
+ /**
465
+ * @see {@link protect} for full docs and examples.
466
+ * @param options Optional configuration for redirect behavior (for example, return URL or sign-in parameters).
467
+ * @returns Resolves if the user is authenticated; otherwise triggers a redirect.
468
+ */
469
+ async protect(options) {
470
+ var _options$authParams19, _options$authParams20, _options$authParams21, _options$authParams22, _options$authParams23, _options$authParams24, _options$authParams25, _options$authParams26, _options$authParams27;
471
+ const { routes, appUrl } = this.coreClient.getOptions();
472
+ let path;
473
+ try {
474
+ const session = await this.getSession();
475
+ if (session && !(options === null || options === void 0 ? void 0 : options.groups)) return;
476
+ if (session && (options === null || options === void 0 ? void 0 : options.groups) && (0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, options.groups, options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options.matchAll)) return;
477
+ const { headers } = await import("next/headers");
478
+ path = (await headers()).get("x-monocloud-path") ?? "/";
479
+ } catch {
480
+ throw new Error("protect() can only be used in App Router server environments (RSC, route handlers, or server actions)");
481
+ }
482
+ const signInRoute = new URL(`${appUrl}${routes.signIn}`);
483
+ signInRoute.searchParams.set("return_url", (options === null || options === void 0 ? void 0 : options.returnUrl) ?? path);
484
+ 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());
485
+ 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);
486
+ 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);
487
+ 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);
488
+ 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);
489
+ 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);
490
+ 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(" "));
491
+ 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);
492
+ 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);
493
+ const { redirect } = await import("next/navigation");
494
+ redirect(signInRoute.toString());
495
+ }
496
+ async isUserInGroup(...args) {
497
+ let request;
498
+ let response;
499
+ let groups;
500
+ let options;
501
+ if (args.length === 4) {
502
+ groups = args[2];
503
+ options = args[3];
504
+ ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], args[1]));
505
+ }
506
+ if (args.length === 3) {
507
+ if (args[0] instanceof Request) if (args[1] instanceof Response) {
508
+ ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], args[1]));
509
+ groups = args[2];
510
+ } else {
511
+ ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], void 0));
512
+ groups = args[1];
513
+ options = args[2];
514
+ }
515
+ if (require_utils.isNodeRequest(args[0]) && require_utils.isNodeResponse(args[1])) {
516
+ ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], args[1]));
517
+ groups = args[2];
518
+ }
519
+ }
520
+ if (args.length === 2) {
521
+ if (args[0] instanceof Request) {
522
+ ({request, response} = require_utils.getMonoCloudCookieReqRes(args[0], void 0));
523
+ groups = args[1];
524
+ }
525
+ if (Array.isArray(args[0])) {
526
+ request = new require_monocloud_cookie_request.default();
527
+ response = new require_monocloud_cookie_response.default();
528
+ groups = args[0];
529
+ options = args[1];
530
+ }
531
+ }
532
+ if (args.length === 1) {
533
+ request = new require_monocloud_cookie_request.default();
534
+ response = new require_monocloud_cookie_response.default();
535
+ groups = args[0];
536
+ }
537
+ if (!Array.isArray(groups) || !require_utils.isMonoCloudRequest(request) || !require_utils.isMonoCloudResponse(response) || options && typeof options !== "object") throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to isUserInGroup()");
538
+ 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);
539
+ }
540
+ /**
541
+ * @see {@link redirectToSignIn} for full docs and examples.
542
+ * @param options Optional configuration for the redirect, such as `returnUrl` or additional sign-in parameters.
543
+ * @returns Never resolves. Triggers a redirect to the sign-in flow.
544
+ */
545
+ async redirectToSignIn(options) {
546
+ const { routes, appUrl } = this.coreClient.getOptions();
547
+ try {
548
+ const { headers } = await import("next/headers");
549
+ await headers();
550
+ } catch {
551
+ throw new Error("redirectToSignIn() can only be used in App Router server environments (RSC, route handlers, or server actions)");
552
+ }
553
+ const signInRoute = new URL(`${appUrl}${routes.signIn}`);
554
+ if (options === null || options === void 0 ? void 0 : options.returnUrl) signInRoute.searchParams.set("return_url", options.returnUrl);
555
+ if (options === null || options === void 0 ? void 0 : options.maxAge) signInRoute.searchParams.set("max_age", options.maxAge.toString());
556
+ if (options === null || options === void 0 ? void 0 : options.authenticatorHint) signInRoute.searchParams.set("authenticator_hint", options.authenticatorHint);
557
+ if (options === null || options === void 0 ? void 0 : options.scopes) signInRoute.searchParams.set("scope", options.scopes);
558
+ if (options === null || options === void 0 ? void 0 : options.resource) signInRoute.searchParams.set("resource", options.resource);
559
+ if (options === null || options === void 0 ? void 0 : options.display) signInRoute.searchParams.set("display", options.display);
560
+ if (options === null || options === void 0 ? void 0 : options.uiLocales) signInRoute.searchParams.set("ui_locales", options.uiLocales);
561
+ if (Array.isArray(options === null || options === void 0 ? void 0 : options.acrValues)) signInRoute.searchParams.set("acr_values", options.acrValues.join(" "));
562
+ if (options === null || options === void 0 ? void 0 : options.loginHint) signInRoute.searchParams.set("login_hint", options.loginHint);
563
+ if (options === null || options === void 0 ? void 0 : options.prompt) signInRoute.searchParams.set("prompt", options.prompt);
564
+ const { redirect } = await import("next/navigation");
565
+ redirect(signInRoute.toString());
566
+ }
567
+ /**
568
+ * @see {@link redirectToSignOut} for full docs and examples.
569
+ * @param options Optional configuration for the redirect, such as `postLogoutRedirectUri` or additional sign-out parameters.
570
+ * @returns Never resolves. Triggers a redirect to the sign-out flow.
571
+ */
572
+ async redirectToSignOut(options) {
573
+ var _options$postLogoutRe;
574
+ const { routes, appUrl } = this.coreClient.getOptions();
575
+ try {
576
+ const { headers } = await import("next/headers");
577
+ await headers();
578
+ } catch {
579
+ throw new Error("redirectToSignOut() can only be used in App Router server environments (RSC, route handlers, or server actions)");
580
+ }
581
+ const signOutRoute = new URL(`${appUrl}${routes.signOut}`);
582
+ 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);
583
+ if (typeof (options === null || options === void 0 ? void 0 : options.federated) === "boolean") signOutRoute.searchParams.set("federated", options.federated.toString());
584
+ const { redirect } = await import("next/navigation");
585
+ redirect(signOutRoute.toString());
586
+ }
587
+ getOptions() {
588
+ return this.coreClient.getOptions();
589
+ }
590
+ registerPublicEnvVariables() {
591
+ Object.keys(process.env).filter((key) => key.startsWith("NEXT_PUBLIC_MONOCLOUD_AUTH")).forEach((publicKey) => {
592
+ const [, privateKey] = publicKey.split("NEXT_PUBLIC_");
593
+ process.env[privateKey] = process.env[publicKey];
594
+ });
595
+ }
596
+ };
597
+
598
+ //#endregion
599
+ exports.MonoCloudNextClient = MonoCloudNextClient;
600
+ //# sourceMappingURL=monocloud-next-client.cjs.map