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