@monocloud/auth-nextjs 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,21 +1,15 @@
1
1
  const require_chunk = require('./chunk-CbDLau6x.cjs');
2
2
  let _monocloud_auth_node_core = require("@monocloud/auth-node-core");
3
- let next_server = require("next/server");
4
- let next_navigation = require("next/navigation");
3
+ let next_server_js = require("next/server.js");
5
4
  let _monocloud_auth_node_core_internal = require("@monocloud/auth-node-core/internal");
6
5
  let _monocloud_auth_node_core_utils = require("@monocloud/auth-node-core/utils");
7
6
  let cookie = require("cookie");
7
+ let node_http = require("node:http");
8
8
 
9
9
  //#region src/requests/monocloud-app-router-request.ts
10
10
  var MonoCloudAppRouterRequest = class {
11
- constructor(req, ctx) {
11
+ constructor(req) {
12
12
  this.req = req;
13
- this.ctx = ctx;
14
- }
15
- /* v8 ignore next */
16
- getRoute(parameter) {
17
- var _this$ctx$params;
18
- return (_this$ctx$params = this.ctx.params) === null || _this$ctx$params === void 0 ? void 0 : _this$ctx$params[parameter];
19
13
  }
20
14
  getQuery(parameter) {
21
15
  return new URL(this.req.url).searchParams.get(parameter) ?? void 0;
@@ -47,10 +41,6 @@ var MonoCloudPageRouterRequest = class {
47
41
  this.req = req;
48
42
  }
49
43
  /* v8 ignore next */
50
- getRoute(parameter) {
51
- return this.req.query[parameter];
52
- }
53
- /* v8 ignore next */
54
44
  getQuery(parameter) {
55
45
  return this.req.query[parameter];
56
46
  }
@@ -90,14 +80,14 @@ var MonoCloudAppRouterResponse = class {
90
80
  }
91
81
  redirect(url, statusCode = 302) {
92
82
  const { headers } = this.res;
93
- this.res = next_server.NextResponse.redirect(url, {
83
+ this.res = next_server_js.NextResponse.redirect(url, {
94
84
  status: statusCode,
95
85
  headers
96
86
  });
97
87
  }
98
88
  sendJson(data, statusCode) {
99
89
  const { headers } = this.res;
100
- this.res = next_server.NextResponse.json(data, {
90
+ this.res = next_server_js.NextResponse.json(data, {
101
91
  status: statusCode,
102
92
  headers
103
93
  });
@@ -105,28 +95,28 @@ var MonoCloudAppRouterResponse = class {
105
95
  /* v8 ignore next */
106
96
  notFound() {
107
97
  const { headers } = this.res;
108
- this.res = new next_server.NextResponse(null, {
98
+ this.res = new next_server_js.NextResponse(null, {
109
99
  status: 404,
110
100
  headers
111
101
  });
112
102
  }
113
103
  internalServerError() {
114
104
  const { headers } = this.res;
115
- this.res = new next_server.NextResponse(null, {
105
+ this.res = new next_server_js.NextResponse(null, {
116
106
  status: 500,
117
107
  headers
118
108
  });
119
109
  }
120
110
  noContent() {
121
111
  const { headers } = this.res;
122
- this.res = new next_server.NextResponse(null, {
112
+ this.res = new next_server_js.NextResponse(null, {
123
113
  status: 204,
124
114
  headers
125
115
  });
126
116
  }
127
117
  methodNotAllowed() {
128
118
  const { headers } = this.res;
129
- this.res = new next_server.NextResponse(null, {
119
+ this.res = new next_server_js.NextResponse(null, {
130
120
  status: 405,
131
121
  headers
132
122
  });
@@ -189,17 +179,64 @@ var MonoCloudPageRouterResponse = class {
189
179
  }
190
180
  };
191
181
 
182
+ //#endregion
183
+ //#region src/responses/monocloud-cookie-response.ts
184
+ let isWarned = false;
185
+ var MonoCloudCookieResponse = class {
186
+ async setCookie(cookieName, value, options) {
187
+ try {
188
+ const { cookies } = await import("next/headers");
189
+ (await cookies()).set(cookieName, value, options);
190
+ } catch (e) {
191
+ if (!isWarned) {
192
+ console.warn(e.message);
193
+ isWarned = true;
194
+ }
195
+ }
196
+ }
197
+ };
198
+
199
+ //#endregion
200
+ //#region src/requests/monocloud-cookie-request.ts
201
+ var MonoCloudCookieRequest = class {
202
+ /* v8 ignore next */
203
+ async getCookie(name) {
204
+ var _await$cookies$get;
205
+ const { cookies } = await import("next/headers");
206
+ return (_await$cookies$get = (await cookies()).get(name)) === null || _await$cookies$get === void 0 ? void 0 : _await$cookies$get.value;
207
+ }
208
+ async getAllCookies() {
209
+ const values = /* @__PURE__ */ new Map();
210
+ const { cookies } = await import("next/headers");
211
+ (await cookies()).getAll().forEach((x) => {
212
+ values.set(x.name, x.value);
213
+ });
214
+ return values;
215
+ }
216
+ };
217
+
192
218
  //#endregion
193
219
  //#region src/utils.ts
220
+ const isMonoCloudRequest = (req) => req instanceof MonoCloudAppRouterRequest || req instanceof MonoCloudPageRouterRequest || req instanceof MonoCloudCookieRequest;
221
+ const isMonoCloudResponse = (res) => res instanceof MonoCloudAppRouterResponse || res instanceof MonoCloudPageRouterResponse || res instanceof MonoCloudCookieResponse;
194
222
  const isAppRouter = (req) => req instanceof Request || req.headers instanceof Headers || typeof req.bodyUsed === "boolean";
195
- const getMonoCloudReqRes = (req, resOrCtx) => {
223
+ const getNextRequest = (req) => {
224
+ if (req instanceof next_server_js.NextRequest) return req;
225
+ return new next_server_js.NextRequest(req);
226
+ };
227
+ const getNextResponse = (res) => {
228
+ if (res instanceof next_server_js.NextResponse) return res;
229
+ if (res instanceof Response) return new next_server_js.NextResponse(res.body, res);
230
+ return new next_server_js.NextResponse();
231
+ };
232
+ const getMonoCloudCookieReqRes = (req, resOrCtx) => {
196
233
  let request;
197
234
  let response;
198
235
  if (isAppRouter(req)) {
199
- request = new MonoCloudAppRouterRequest(req, resOrCtx instanceof next_server.NextResponse ? { params: {} } : resOrCtx);
200
- response = new MonoCloudAppRouterResponse(resOrCtx instanceof next_server.NextResponse ? resOrCtx : new next_server.NextResponse());
236
+ request = new MonoCloudAppRouterRequest(getNextRequest(req));
237
+ response = resOrCtx instanceof Response ? new MonoCloudAppRouterResponse(getNextResponse(resOrCtx)) : new MonoCloudCookieResponse();
201
238
  } else {
202
- /* c8 ignore start */
239
+ if (!(req instanceof node_http.IncomingMessage) || !(resOrCtx instanceof node_http.ServerResponse)) throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid pages router request and response");
203
240
  request = new MonoCloudPageRouterRequest(req);
204
241
  response = new MonoCloudPageRouterResponse(resOrCtx);
205
242
  }
@@ -210,7 +247,7 @@ const getMonoCloudReqRes = (req, resOrCtx) => {
210
247
  };
211
248
  const mergeResponse = (responses) => {
212
249
  const resp = responses.pop();
213
- if (!resp) return new next_server.NextResponse();
250
+ if (!resp) return new next_server_js.NextResponse();
214
251
  responses.forEach((response) => {
215
252
  response.headers.forEach((v, k) => {
216
253
  if (k === "location" && !resp.headers.has(k) || k !== "location") resp.headers.set(k, v);
@@ -223,214 +260,189 @@ const mergeResponse = (responses) => {
223
260
  return resp;
224
261
  };
225
262
 
226
- //#endregion
227
- //#region src/requests/monocloud-cookie-request.ts
228
- var MonoCloudCookieRequest = class {
229
- /* v8 ignore next */
230
- async getCookie(name) {
231
- var _await$cookies$get;
232
- const { cookies } = await import("next/headers");
233
- return (_await$cookies$get = (await cookies()).get(name)) === null || _await$cookies$get === void 0 ? void 0 : _await$cookies$get.value;
234
- }
235
- async getAllCookies() {
236
- const values = /* @__PURE__ */ new Map();
237
- const { cookies } = await import("next/headers");
238
- (await cookies()).getAll().forEach((x) => {
239
- values.set(x.name, x.value);
240
- });
241
- return values;
242
- }
243
- };
244
-
245
- //#endregion
246
- //#region src/responses/monocloud-cookie-response.ts
247
- let isWarned = false;
248
- var MonoCloudCookieResponse = class {
249
- async setCookie(cookieName, value, options) {
250
- try {
251
- const { cookies } = await import("next/headers");
252
- (await cookies()).set(cookieName, value, options);
253
- } catch (e) {
254
- if (!isWarned) {
255
- console.warn(e.message);
256
- isWarned = true;
257
- }
258
- }
259
- }
260
- };
261
-
262
263
  //#endregion
263
264
  //#region src/monocloud-next-client.ts
265
+ /**
266
+ * The MonoCloud Next.js Client.
267
+ *
268
+ * @example Using Environment Variables (Recommended)
269
+ *
270
+ * 1. Add following variables to your `.env`.
271
+ *
272
+ * ```bash
273
+ * MONOCLOUD_AUTH_TENANT_DOMAIN=<tenant-domain>
274
+ * MONOCLOUD_AUTH_CLIENT_ID=<client-id>
275
+ * MONOCLOUD_AUTH_CLIENT_SECRET=<client-secret>
276
+ * MONOCLOUD_AUTH_SCOPES=openid profile email # Default
277
+ * MONOCLOUD_AUTH_APP_URL=http://localhost:3000
278
+ * MONOCLOUD_AUTH_COOKIE_SECRET=<cookie-secret>
279
+ * ```
280
+ *
281
+ * 2. Instantiate the client in a shared file (e.g., lib/monocloud.ts)
282
+ *
283
+ * ```typescript
284
+ * import { MonoCloudNextClient } from '@monocloud/auth-nextjs';
285
+ *
286
+ * export const monoCloud = new MonoCloudNextClient();
287
+ * ```
288
+ *
289
+ * 3. Add MonoCloud middleware/proxy
290
+ *
291
+ * ```typescript
292
+ * import { monoCloud } from "@/lib/monocloud";
293
+ *
294
+ * export default monoCloud.authMiddleware();
295
+ *
296
+ * export const config = {
297
+ * matcher: [
298
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
299
+ * ],
300
+ * };
301
+ * ```
302
+ *
303
+ * @example Using Constructor Options
304
+ *
305
+ * ⚠️ Security Note: Never commit your credentials to version control. Load them from environment variables.
306
+ *
307
+ * 1. Instantiate the client in a shared file (e.g., lib/monocloud.ts)
308
+ *
309
+ * ```typescript
310
+ * import { MonoCloudNextClient } from '@monocloud/auth-nextjs';
311
+ *
312
+ * export const monoCloud = new MonoCloudNextClient({
313
+ * tenantDomain: '<tenant-domain>',
314
+ * clientId: '<client-id>',
315
+ * clientSecret: '<client-secret>',
316
+ * scopes: 'openid profile email', // Default
317
+ * appUrl: 'http://localhost:3000',
318
+ * cookieSecret: '<cookie-secret>'
319
+ * });
320
+ * ```
321
+ * 2. Add MonoCloud middleware/proxy
322
+ *
323
+ * ```typescript
324
+ * import { monoCloud } from "@/lib/monocloud";
325
+ *
326
+ * export default monoCloud.authMiddleware();
327
+ *
328
+ * export const config = {
329
+ * matcher: [
330
+ * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
331
+ * ],
332
+ * };
333
+ * ```
334
+ *
335
+ * <details>
336
+ * <summary>All Environment Variables</summary>
337
+ * <h4>Core Configuration (Required)</h4>
338
+ *
339
+ * <ul>
340
+ * <li><strong>MONOCLOUD_AUTH_CLIENT_ID : </strong>Unique identifier for your application/client.</li>
341
+ * <li><strong>MONOCLOUD_AUTH_CLIENT_SECRET : </strong>Application/client secret.</li>
342
+ * <li><strong>MONOCLOUD_AUTH_TENANT_DOMAIN : </strong>The domain of your MonoCloud tenant (e.g., https://your-tenant.us.monocloud.com).</li>
343
+ * <li><strong>MONOCLOUD_AUTH_APP_URL : </strong>The base URL where your application is hosted.</li>
344
+ * <li><strong>MONOCLOUD_AUTH_COOKIE_SECRET : </strong>A long, random string used to encrypt and sign session cookies.</li>
345
+ * </ul>
346
+ *
347
+ * <h4>Authentication &amp; Security</h4>
348
+ *
349
+ * <ul>
350
+ * <li><strong>MONOCLOUD_AUTH_SCOPES : </strong>A space-separated list of OIDC scopes to request (e.g., openid profile email).</li>
351
+ * <li><strong>MONOCLOUD_AUTH_RESOURCE : </strong>The default resource/audience identifier for access tokens.</li>
352
+ * <li><strong>MONOCLOUD_AUTH_USE_PAR : </strong>Enables Pushed Authorization Requests.</li>
353
+ * <li><strong>MONOCLOUD_AUTH_CLOCK_SKEW : </strong>The allowed clock drift in seconds when validating token timestamps.</li>
354
+ * <li><strong>MONOCLOUD_AUTH_FEDERATED_SIGNOUT : </strong>If true, signs the user out of MonoCloud (SSO sign-out) when they sign out of the app.</li>
355
+ * <li><strong>MONOCLOUD_AUTH_RESPONSE_TIMEOUT : </strong>The maximum time in milliseconds to wait for a response.</li>
356
+ * <li><strong>MONOCLOUD_AUTH_ALLOW_QUERY_PARAM_OVERRIDES : </strong>Allows dynamic overrides of auth parameters via URL query strings.</li>
357
+ * <li><strong>MONOCLOUD_AUTH_POST_LOGOUT_REDIRECT_URI : </strong>The URL users are sent to after a successful logout.</li>
358
+ * <li><strong>MONOCLOUD_AUTH_USER_INFO : </strong>Determines if user profile data from the UserInfo endpoint should be fetched after authorization code exchange.</li>
359
+ * <li><strong>MONOCLOUD_AUTH_REFETCH_USER_INFO : </strong>If true, re-fetches user information on every request to userinfo endpoint or when calling getTokens()</li>
360
+ * <li><strong>MONOCLOUD_AUTH_ID_TOKEN_SIGNING_ALG : </strong>The expected algorithm for signing ID tokens (e.g., RS256).</li>
361
+ * <li><strong>MONOCLOUD_AUTH_FILTERED_ID_TOKEN_CLAIMS : </strong>A space-separated list of claims to exclude from the session object.</li>
362
+ * </ul>
363
+ *
364
+ * <h4>Routes</h4>
365
+ *
366
+ * <aside>
367
+ * <strong>⚠️ Important: Modifying Default Routes</strong>
368
+ * <p>If you choose to customize any of the default route paths, you must adhere to the following requirements:</p>
369
+ * <ul>
370
+ * <li>
371
+ * <strong>Client-Side Synchronization:</strong> You must also define a corresponding <code>NEXT_PUBLIC_</code> version of the environment variable (e.g., <code>NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL</code>). This ensures that client-side components like <code>&lt;SignIn /&gt;</code>, <code>&lt;SignOut /&gt;</code>, and the <code>useAuth()</code> hook can correctly identify your custom endpoints.
372
+ * </li>
373
+ * <li>
374
+ * <strong>Dashboard Configuration:</strong> Changing these URLs will alter the endpoints required by MonoCloud. You must update the <strong>Application URLs</strong> section in your MonoCloud Dashboard to match these new paths.
375
+ * </li>
376
+ * </ul>
377
+ * <p><em>Example:</em></p>
378
+ * <code>
379
+ * MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback<br />
380
+ * NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
381
+ * </code>
382
+ * <p>In this case, the Redirect URI in your dashboard should be set to: <code>http://localhost:3000/api/custom_callback</code> (assuming local development).</p>
383
+ * </aside>
384
+ *
385
+ * <ul>
386
+ * <li><strong>MONOCLOUD_AUTH_CALLBACK_URL : </strong>The application path where MonoCloud sends the user after authentication.</li>
387
+ * <li><strong>MONOCLOUD_AUTH_SIGNIN_URL : </strong>The internal route path to trigger the sign-in.</li>
388
+ * <li><strong>MONOCLOUD_AUTH_SIGNOUT_URL : </strong>The internal route path to trigger the sign-out.</li>
389
+ * <li><strong>MONOCLOUD_AUTH_USER_INFO_URL : </strong>The route that exposes the current user's profile from userinfo endpoint.</li>
390
+ * </ul>
391
+ *
392
+ * <h4>Session Cookie Settings</h4>
393
+ *
394
+ * <ul>
395
+ * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_NAME : </strong>The name of the cookie used to store the user session.</li>
396
+ * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_PATH : </strong>The scope path for the session cookie.</li>
397
+ * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_DOMAIN : </strong>The domain scope for the session cookie.</li>
398
+ * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_HTTP_ONLY : </strong>Prevents client-side scripts from accessing the session cookie.</li>
399
+ * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_SECURE : </strong>Ensures the session cookie is only sent over HTTPS.</li>
400
+ * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_SAME_SITE : </strong>The SameSite policy for the session cookie (Lax, Strict, or None).</li>
401
+ * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_PERSISTENT : </strong>If true, the session survives browser restarts.</li>
402
+ * <li><strong>MONOCLOUD_AUTH_SESSION_SLIDING : </strong>If true, the session will be a sliding session instead of absolute.</li>
403
+ * <li><strong>MONOCLOUD_AUTH_SESSION_DURATION : </strong>The session lifetime in seconds.</li>
404
+ * <li><strong>MONOCLOUD_AUTH_SESSION_MAX_DURATION : </strong>The absolute maximum lifetime of a session in seconds.</li>
405
+ * </ul>
406
+ *
407
+ * <h4>State Cookie Settings</h4>
408
+ *
409
+ * <ul>
410
+ * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_NAME : </strong>The name of the cookie used to store OpenID state/nonce.</li>
411
+ * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_PATH : </strong>The scope path for the state cookie.</li>
412
+ * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_DOMAIN : </strong>The domain scope for the state cookie.</li>
413
+ * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_SECURE : </strong>Ensures the state cookie is only sent over HTTPS</li>
414
+ * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_SAME_SITE : </strong>The SameSite policy for the state cookie.</li>
415
+ * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_PERSISTENT : </strong>Whether the state cookie is persistent.</li>
416
+ * </ul>
417
+ *
418
+ * <h4>Caching</h4>
419
+ *
420
+ * <ul>
421
+ * <li><strong>MONOCLOUD_AUTH_JWKS_CACHE_DURATION : </strong>Duration in seconds to cache the JSON Web Key Set.</li>
422
+ * <li><strong>MONOCLOUD_AUTH_METADATA_CACHE_DURATION : </strong>Duration in seconds to cache the OpenID discovery metadata.</li>
423
+ * </ul>
424
+ * </details>
425
+ *
426
+ *
427
+ */
264
428
  var MonoCloudNextClient = class {
265
- /* v8 ignore next -- @preserve */
429
+ /**
430
+ * The underlying OIDC client instance used for low-level OpenID Connect operations.
431
+ *
432
+ * @example
433
+ * // Manually revoke an access token
434
+ * await client.oidcClient.revokeToken(accessToken, 'access_token');
435
+ */
266
436
  get oidcClient() {
267
437
  return this.coreClient.oidcClient;
268
438
  }
439
+ /**
440
+ * @param options Configuration options including domain, client ID, and secret.
441
+ */
269
442
  constructor(options) {
270
- this.protectPage = (...args) => {
271
- if (typeof args[0] === "function") return this.protectAppPage(args[0], args[1]);
272
- return this.protectPagePage(args[0]);
273
- };
274
- this.protectAppPage = (component, options$1) => {
275
- return async (params) => {
276
- const session = await this.getSession();
277
- if (!session) {
278
- var _options$authParams, _options$authParams2, _options$authParams3, _options$authParams4, _options$authParams5, _options$authParams6, _options$authParams7, _options$authParams8, _options$authParams9;
279
- if (options$1 === null || options$1 === void 0 ? void 0 : options$1.onAccessDenied) return options$1.onAccessDenied({ ...params });
280
- const { routes, appUrl } = this.getOptions();
281
- const { headers } = await import("next/headers");
282
- const path = (await headers()).get("x-monocloud-path");
283
- const signInRoute = new URL(`${appUrl}${(0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn)}`);
284
- signInRoute.searchParams.set("return_url", (options$1 === null || options$1 === void 0 ? void 0 : options$1.returnUrl) ?? path ?? "/");
285
- if (options$1 === null || options$1 === void 0 || (_options$authParams = options$1.authParams) === null || _options$authParams === void 0 ? void 0 : _options$authParams.scopes) signInRoute.searchParams.set("scope", options$1.authParams.scopes);
286
- if (options$1 === null || options$1 === void 0 || (_options$authParams2 = options$1.authParams) === null || _options$authParams2 === void 0 ? void 0 : _options$authParams2.resource) signInRoute.searchParams.set("resource", options$1.authParams.resource);
287
- if (options$1 === null || options$1 === void 0 || (_options$authParams3 = options$1.authParams) === null || _options$authParams3 === void 0 ? void 0 : _options$authParams3.acrValues) signInRoute.searchParams.set("acr_values", options$1.authParams.acrValues.join(" "));
288
- if (options$1 === null || options$1 === void 0 || (_options$authParams4 = options$1.authParams) === null || _options$authParams4 === void 0 ? void 0 : _options$authParams4.display) signInRoute.searchParams.set("display", options$1.authParams.display);
289
- if (options$1 === null || options$1 === void 0 || (_options$authParams5 = options$1.authParams) === null || _options$authParams5 === void 0 ? void 0 : _options$authParams5.prompt) signInRoute.searchParams.set("prompt", options$1.authParams.prompt);
290
- if (options$1 === null || options$1 === void 0 || (_options$authParams6 = options$1.authParams) === null || _options$authParams6 === void 0 ? void 0 : _options$authParams6.authenticatorHint) signInRoute.searchParams.set("authenticator_hint", options$1.authParams.authenticatorHint);
291
- if (options$1 === null || options$1 === void 0 || (_options$authParams7 = options$1.authParams) === null || _options$authParams7 === void 0 ? void 0 : _options$authParams7.uiLocales) signInRoute.searchParams.set("ui_locales", options$1.authParams.uiLocales);
292
- if (options$1 === null || options$1 === void 0 || (_options$authParams8 = options$1.authParams) === null || _options$authParams8 === void 0 ? void 0 : _options$authParams8.maxAge) signInRoute.searchParams.set("max_age", options$1.authParams.maxAge.toString());
293
- if (options$1 === null || options$1 === void 0 || (_options$authParams9 = options$1.authParams) === null || _options$authParams9 === void 0 ? void 0 : _options$authParams9.loginHint) signInRoute.searchParams.set("login_hint", options$1.authParams.loginHint);
294
- return (0, next_navigation.redirect)(signInRoute.toString());
295
- }
296
- if ((options$1 === null || options$1 === void 0 ? void 0 : options$1.groups) && !(0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, options$1.groups, options$1.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options$1.matchAll)) {
297
- if (options$1.onAccessDenied) return options$1.onAccessDenied({
298
- ...params,
299
- user: session.user
300
- });
301
- return "Access Denied";
302
- }
303
- return component({
304
- ...params,
305
- user: session.user
306
- });
307
- };
308
- };
309
- this.protectPagePage = (options$1) => {
310
- return async (context) => {
311
- const session = await this.getSession(context.req, context.res);
312
- if (!session) {
313
- var _options$authParams10, _options$authParams11, _options$authParams12, _options$authParams13, _options$authParams14, _options$authParams15, _options$authParams16, _options$authParams17, _options$authParams18;
314
- if (options$1 === null || options$1 === void 0 ? void 0 : options$1.onAccessDenied) {
315
- const customProps$1 = await options$1.onAccessDenied({ ...context });
316
- return {
317
- ...customProps$1 ?? {},
318
- props: { ...(customProps$1 === null || customProps$1 === void 0 ? void 0 : customProps$1.props) ?? {} }
319
- };
320
- }
321
- const { routes, appUrl } = this.getOptions();
322
- const signInRoute = new URL(`${appUrl}${(0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn)}`);
323
- signInRoute.searchParams.set("return_url", (options$1 === null || options$1 === void 0 ? void 0 : options$1.returnUrl) ?? context.resolvedUrl);
324
- if (options$1 === null || options$1 === void 0 || (_options$authParams10 = options$1.authParams) === null || _options$authParams10 === void 0 ? void 0 : _options$authParams10.scopes) signInRoute.searchParams.set("scope", options$1.authParams.scopes);
325
- if (options$1 === null || options$1 === void 0 || (_options$authParams11 = options$1.authParams) === null || _options$authParams11 === void 0 ? void 0 : _options$authParams11.resource) signInRoute.searchParams.set("resource", options$1.authParams.resource);
326
- if (options$1 === null || options$1 === void 0 || (_options$authParams12 = options$1.authParams) === null || _options$authParams12 === void 0 ? void 0 : _options$authParams12.acrValues) signInRoute.searchParams.set("acr_values", options$1.authParams.acrValues.join(" "));
327
- if (options$1 === null || options$1 === void 0 || (_options$authParams13 = options$1.authParams) === null || _options$authParams13 === void 0 ? void 0 : _options$authParams13.display) signInRoute.searchParams.set("display", options$1.authParams.display);
328
- if (options$1 === null || options$1 === void 0 || (_options$authParams14 = options$1.authParams) === null || _options$authParams14 === void 0 ? void 0 : _options$authParams14.prompt) signInRoute.searchParams.set("prompt", options$1.authParams.prompt);
329
- if (options$1 === null || options$1 === void 0 || (_options$authParams15 = options$1.authParams) === null || _options$authParams15 === void 0 ? void 0 : _options$authParams15.authenticatorHint) signInRoute.searchParams.set("authenticator_hint", options$1.authParams.authenticatorHint);
330
- if (options$1 === null || options$1 === void 0 || (_options$authParams16 = options$1.authParams) === null || _options$authParams16 === void 0 ? void 0 : _options$authParams16.uiLocales) signInRoute.searchParams.set("ui_locales", options$1.authParams.uiLocales);
331
- if (options$1 === null || options$1 === void 0 || (_options$authParams17 = options$1.authParams) === null || _options$authParams17 === void 0 ? void 0 : _options$authParams17.maxAge) signInRoute.searchParams.set("max_age", options$1.authParams.maxAge.toString());
332
- if (options$1 === null || options$1 === void 0 || (_options$authParams18 = options$1.authParams) === null || _options$authParams18 === void 0 ? void 0 : _options$authParams18.loginHint) signInRoute.searchParams.set("login_hint", options$1.authParams.loginHint);
333
- return { redirect: {
334
- destination: signInRoute.toString(),
335
- permanent: false
336
- } };
337
- }
338
- if ((options$1 === null || options$1 === void 0 ? void 0 : options$1.groups) && !(0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, options$1.groups, options$1.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options$1.matchAll)) {
339
- var _options$onAccessDeni;
340
- const customProps$1 = await ((_options$onAccessDeni = options$1.onAccessDenied) === null || _options$onAccessDeni === void 0 ? void 0 : _options$onAccessDeni.call(options$1, {
341
- ...context,
342
- user: session.user
343
- })) ?? { props: { accessDenied: true } };
344
- return {
345
- ...customProps$1,
346
- props: { ...customProps$1.props ?? {} }
347
- };
348
- }
349
- const customProps = (options$1 === null || options$1 === void 0 ? void 0 : options$1.getServerSideProps) ? await options$1.getServerSideProps(context) : {};
350
- const promiseProp = customProps.props;
351
- if (promiseProp instanceof Promise) return {
352
- ...customProps,
353
- props: promiseProp.then((props) => ({
354
- user: session.user,
355
- ...props
356
- }))
357
- };
358
- return {
359
- ...customProps,
360
- props: {
361
- user: session.user,
362
- ...customProps.props
363
- }
364
- };
365
- };
366
- };
367
- this.protectApi = (handler, options$1) => {
368
- return (req, resOrCtx) => {
369
- if (isAppRouter(req)) return this.protectAppApi(req, resOrCtx, handler, options$1);
370
- return this.protectPageApi(req, resOrCtx, handler, options$1);
371
- };
372
- };
373
- this.protectAppApi = async (req, ctx, handler, options$1) => {
374
- const res = new next_server.NextResponse();
375
- const session = await this.getSession(req, res);
376
- if (!session) {
377
- if (options$1 === null || options$1 === void 0 ? void 0 : options$1.onAccessDenied) {
378
- const result = await options$1.onAccessDenied(req, ctx);
379
- if (result instanceof next_server.NextResponse) return mergeResponse([res, result]);
380
- return mergeResponse([res, new next_server.NextResponse(result.body, result)]);
381
- }
382
- return mergeResponse([res, next_server.NextResponse.json({ message: "unauthorized" }, { status: 401 })]);
383
- }
384
- if ((options$1 === null || options$1 === void 0 ? void 0 : options$1.groups) && !(0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, options$1.groups, options$1.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options$1.matchAll)) {
385
- if (options$1.onAccessDenied) {
386
- const result = await options$1.onAccessDenied(req, ctx);
387
- if (result instanceof next_server.NextResponse) return mergeResponse([res, result]);
388
- return mergeResponse([res, new next_server.NextResponse(result.body, result)]);
389
- }
390
- return mergeResponse([res, next_server.NextResponse.json({ message: "forbidden" }, { status: 403 })]);
391
- }
392
- const resp = await handler(req, ctx);
393
- if (resp instanceof next_server.NextResponse) return mergeResponse([res, resp]);
394
- return mergeResponse([res, new next_server.NextResponse(resp.body, resp)]);
395
- };
396
- this.protectPageApi = async (req, res, handler, options$1) => {
397
- const session = await this.getSession(req, res);
398
- if (!session) {
399
- if (options$1 === null || options$1 === void 0 ? void 0 : options$1.onAccessDenied) return options$1.onAccessDenied(req, res);
400
- return res.status(401).json({ message: "unauthorized" });
401
- }
402
- if ((options$1 === null || options$1 === void 0 ? void 0 : options$1.groups) && !(0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, options$1.groups, options$1.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options$1.matchAll)) {
403
- if (options$1.onAccessDenied) return options$1.onAccessDenied(req, res, session.user);
404
- return res.status(403).json({ message: "forbidden" });
405
- }
406
- return handler(req, res);
407
- };
408
- this.authMiddleware = (...args) => {
409
- let req;
410
- let evt;
411
- let options$1;
412
- /* v8 ignore else -- @preserve */
413
- if (Array.isArray(args)) {
414
- if (args.length === 2) {
415
- /* v8 ignore else -- @preserve */
416
- if (isAppRouter(args[0])) {
417
- req = args[0];
418
- evt = args[1];
419
- }
420
- }
421
- if (args.length === 1) options$1 = args[0];
422
- }
423
- if (req && evt) return this.authMiddlewareHandler(req, evt, options$1);
424
- return (request, nxtEvt) => {
425
- return this.authMiddlewareHandler(request, nxtEvt, options$1);
426
- };
427
- };
428
- this.getSession = this.resolveFunction(this.resolvedGetSession.bind(this));
429
- this.getTokens = this.resolveFunction(this.resolvedGetTokens.bind(this));
430
- this.isAuthenticated = this.resolveFunction(this.resolvedIsAuthenticated.bind(this));
431
443
  const opt = {
432
444
  ...options ?? {},
433
- userAgent: (options === null || options === void 0 ? void 0 : options.userAgent) ?? `@monocloud/auth-nextjs@0.1.1`,
445
+ userAgent: (options === null || options === void 0 ? void 0 : options.userAgent) ?? `@monocloud/auth-nextjs@0.1.2`,
434
446
  debugger: (options === null || options === void 0 ? void 0 : options.debugger) ?? "@monocloud:auth-nextjs"
435
447
  };
436
448
  this.registerPublicEnvVariables();
@@ -441,12 +453,65 @@ var MonoCloudNextClient = class {
441
453
  * that processes all MonoCloud authentication endpoints
442
454
  * (`/signin`, `/callback`, `/userinfo`, `/signout`).
443
455
  *
444
- * @param {MonoCloudAuthOptions} [options] Optional configuration authentication routes.
456
+ * @param options Authentication configuration routes.
445
457
  *
446
458
  * **Note:** If you are already using `authMiddleware()`, you typically do **not**
447
459
  * need this API route handler. This function is intended for applications where
448
460
  * middleware cannot be used—such as statically generated (SSG) deployments that still
449
461
  * require server-side authentication flows.
462
+ *
463
+ * @example App Router
464
+ *
465
+ * ```typescript
466
+ * // app/api/auth/[...monocloud]/route.ts
467
+ *
468
+ * import { monoCloud } from "@/lib/monocloud";
469
+ *
470
+ * export const GET = monoCloud.monoCloudAuth();
471
+ *```
472
+ *
473
+ * @example App Router with Response
474
+ *
475
+ * ```typescript
476
+ * import { monoCloud } from "@/lib/monocloud";
477
+ * import { NextRequest, NextResponse } from "next/server";
478
+ *
479
+ * export const GET = (req: NextRequest) => {
480
+ * const authHandler = monoCloud.monoCloudAuth();
481
+ *
482
+ * const res = new NextResponse();
483
+ *
484
+ * res.cookies.set("last_auth_requested", `${Date.now()}`);
485
+ *
486
+ * return authHandler(req, res);
487
+ * };
488
+ * ```
489
+ *
490
+ * @example Pages Router
491
+ *
492
+ * ```typescript
493
+ * // pages/api/auth/[...monocloud].ts
494
+ *
495
+ * import { monoCloud } from "@/lib/monocloud";
496
+ *
497
+ * export default monoCloud.monoCloudAuth();
498
+ *```
499
+ *
500
+ * @example Page Router with Response
501
+ *
502
+ * ```typescript
503
+ * import { monoCloud } from "@/lib/monocloud";
504
+ * import { NextApiRequest, NextApiResponse } from "next";
505
+ *
506
+ * export default function handler(req: NextApiRequest, res: NextApiResponse) {
507
+ * const authHandler = monoCloud.monoCloudAuth();
508
+ *
509
+ * res.setHeader("last_auth_requested", `${Date.now()}`);
510
+ *
511
+ * return authHandler(req, res);
512
+ * }
513
+ * ```
514
+ *
450
515
  */
451
516
  monoCloudAuth(options) {
452
517
  return (req, resOrCtx) => {
@@ -456,21 +521,189 @@ var MonoCloudNextClient = class {
456
521
  const route = new URL(url);
457
522
  let onError;
458
523
  if (typeof (options === null || options === void 0 ? void 0 : options.onError) === "function") onError = (error) => options.onError(req, resOrCtx, error);
459
- const { request, response } = getMonoCloudReqRes(req, resOrCtx);
524
+ let request;
525
+ let response;
526
+ if (isAppRouter(req)) {
527
+ request = new MonoCloudAppRouterRequest(getNextRequest(req));
528
+ response = new MonoCloudAppRouterResponse(getNextResponse(resOrCtx));
529
+ } else {
530
+ request = new MonoCloudPageRouterRequest(req);
531
+ response = new MonoCloudPageRouterResponse(resOrCtx);
532
+ }
460
533
  return this.handleAuthRoutes(request, response, route.pathname, routes, onError);
461
534
  };
462
535
  }
536
+ protectPage(...args) {
537
+ if (typeof args[0] === "function") return this.protectAppPage(args[0], args[1]);
538
+ return this.protectPagePage(args[0]);
539
+ }
540
+ protectAppPage(component, options) {
541
+ return async (params) => {
542
+ const session = await this.getSession();
543
+ if (!session) {
544
+ var _options$authParams, _options$authParams2, _options$authParams3, _options$authParams4, _options$authParams5, _options$authParams6, _options$authParams7, _options$authParams8, _options$authParams9;
545
+ if (options === null || options === void 0 ? void 0 : options.onAccessDenied) return options.onAccessDenied({ ...params });
546
+ const { routes, appUrl } = this.getOptions();
547
+ const { headers } = await import("next/headers");
548
+ const path = (await headers()).get("x-monocloud-path");
549
+ const signInRoute = new URL(`${appUrl}${(0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn)}`);
550
+ signInRoute.searchParams.set("return_url", (options === null || options === void 0 ? void 0 : options.returnUrl) ?? path ?? "/");
551
+ 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);
552
+ 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);
553
+ 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(" "));
554
+ 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);
555
+ 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);
556
+ 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);
557
+ 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);
558
+ 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());
559
+ 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);
560
+ const { redirect } = await import("next/navigation");
561
+ return redirect(signInRoute.toString());
562
+ }
563
+ 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)) {
564
+ if (options.onAccessDenied) return options.onAccessDenied({
565
+ ...params,
566
+ user: session.user
567
+ });
568
+ return "Access Denied";
569
+ }
570
+ return component({
571
+ ...params,
572
+ user: session.user
573
+ });
574
+ };
575
+ }
576
+ protectPagePage(options) {
577
+ return async (context) => {
578
+ const session = await this.getSession(context.req, context.res);
579
+ if (!session) {
580
+ var _options$authParams10, _options$authParams11, _options$authParams12, _options$authParams13, _options$authParams14, _options$authParams15, _options$authParams16, _options$authParams17, _options$authParams18;
581
+ if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
582
+ const customProps$1 = await options.onAccessDenied({ ...context });
583
+ return {
584
+ ...customProps$1 ?? {},
585
+ props: { ...(customProps$1 === null || customProps$1 === void 0 ? void 0 : customProps$1.props) ?? {} }
586
+ };
587
+ }
588
+ const { routes, appUrl } = this.getOptions();
589
+ const signInRoute = new URL(`${appUrl}${(0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn)}`);
590
+ signInRoute.searchParams.set("return_url", (options === null || options === void 0 ? void 0 : options.returnUrl) ?? context.resolvedUrl);
591
+ 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);
592
+ 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);
593
+ 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(" "));
594
+ 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);
595
+ 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);
596
+ 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);
597
+ 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);
598
+ 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());
599
+ 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);
600
+ return { redirect: {
601
+ destination: signInRoute.toString(),
602
+ permanent: false
603
+ } };
604
+ }
605
+ 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)) {
606
+ var _options$onAccessDeni;
607
+ const customProps$1 = await ((_options$onAccessDeni = options.onAccessDenied) === null || _options$onAccessDeni === void 0 ? void 0 : _options$onAccessDeni.call(options, {
608
+ ...context,
609
+ user: session.user
610
+ })) ?? { props: { accessDenied: true } };
611
+ return {
612
+ ...customProps$1,
613
+ props: { ...customProps$1.props ?? {} }
614
+ };
615
+ }
616
+ const customProps = (options === null || options === void 0 ? void 0 : options.getServerSideProps) ? await options.getServerSideProps(context) : {};
617
+ const promiseProp = customProps.props;
618
+ if (promiseProp instanceof Promise) return {
619
+ ...customProps,
620
+ props: promiseProp.then((props) => ({
621
+ user: session.user,
622
+ ...props
623
+ }))
624
+ };
625
+ return {
626
+ ...customProps,
627
+ props: {
628
+ user: session.user,
629
+ ...customProps.props
630
+ }
631
+ };
632
+ };
633
+ }
634
+ protectApi(handler, options) {
635
+ return (req, resOrCtx) => {
636
+ if (isAppRouter(req)) return this.protectAppApi(req, resOrCtx, handler, options);
637
+ return this.protectPageApi(req, resOrCtx, handler, options);
638
+ };
639
+ }
640
+ async protectAppApi(req, ctx, handler, options) {
641
+ const res = new next_server_js.NextResponse();
642
+ const session = await this.getSession(req, res);
643
+ if (!session) {
644
+ if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
645
+ const result = await options.onAccessDenied(req, ctx);
646
+ if (result instanceof next_server_js.NextResponse) return mergeResponse([res, result]);
647
+ return mergeResponse([res, new next_server_js.NextResponse(result.body, result)]);
648
+ }
649
+ return mergeResponse([res, next_server_js.NextResponse.json({ message: "unauthorized" }, { status: 401 })]);
650
+ }
651
+ 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)) {
652
+ if (options.onAccessDenied) {
653
+ const result = await options.onAccessDenied(req, ctx);
654
+ if (result instanceof next_server_js.NextResponse) return mergeResponse([res, result]);
655
+ return mergeResponse([res, new next_server_js.NextResponse(result.body, result)]);
656
+ }
657
+ return mergeResponse([res, next_server_js.NextResponse.json({ message: "forbidden" }, { status: 403 })]);
658
+ }
659
+ const resp = await handler(req, ctx);
660
+ if (resp instanceof next_server_js.NextResponse) return mergeResponse([res, resp]);
661
+ return mergeResponse([res, new next_server_js.NextResponse(resp.body, resp)]);
662
+ }
663
+ async protectPageApi(req, res, handler, options) {
664
+ const session = await this.getSession(req, res);
665
+ if (!session) {
666
+ if (options === null || options === void 0 ? void 0 : options.onAccessDenied) return options.onAccessDenied(req, res);
667
+ return res.status(401).json({ message: "unauthorized" });
668
+ }
669
+ 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)) {
670
+ if (options.onAccessDenied) return options.onAccessDenied(req, res, session.user);
671
+ return res.status(403).json({ message: "forbidden" });
672
+ }
673
+ return handler(req, res);
674
+ }
675
+ authMiddleware(...args) {
676
+ let req;
677
+ let evt;
678
+ let options;
679
+ /* v8 ignore else -- @preserve */
680
+ if (Array.isArray(args)) {
681
+ if (args.length === 2) {
682
+ /* v8 ignore else -- @preserve */
683
+ if (isAppRouter(args[0])) {
684
+ req = args[0];
685
+ evt = args[1];
686
+ }
687
+ }
688
+ if (args.length === 1) options = args[0];
689
+ }
690
+ if (req && evt) return this.authMiddlewareHandler(req, evt, options);
691
+ return (request, nxtEvt) => {
692
+ return this.authMiddlewareHandler(request, nxtEvt, options);
693
+ };
694
+ }
463
695
  async authMiddlewareHandler(req, evt, options) {
464
- if (req.headers.has("x-middleware-subrequest")) return next_server.NextResponse.json({ message: "forbidden" }, { status: 403 });
696
+ req = getNextRequest(req);
697
+ if (req.headers.has("x-middleware-subrequest")) return next_server_js.NextResponse.json({ message: "forbidden" }, { status: 403 });
465
698
  const { routes, appUrl } = this.getOptions();
466
699
  if (Object.values(routes).map((x) => (0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(x)).includes(req.nextUrl.pathname)) {
467
700
  let onError;
468
701
  if (typeof (options === null || options === void 0 ? void 0 : options.onError) === "function") onError = (error) => options.onError(req, evt, error);
469
- const request = new MonoCloudAppRouterRequest(req, { params: {} });
470
- const response = new MonoCloudAppRouterResponse(new next_server.NextResponse());
702
+ const request = new MonoCloudAppRouterRequest(req);
703
+ const response = new MonoCloudAppRouterResponse(new next_server_js.NextResponse());
471
704
  return this.handleAuthRoutes(request, response, req.nextUrl.pathname, routes, onError);
472
705
  }
473
- const nxtResp = new next_server.NextResponse();
706
+ const nxtResp = new next_server_js.NextResponse();
474
707
  nxtResp.headers.set("x-monocloud-path", req.nextUrl.pathname + req.nextUrl.search);
475
708
  let isRouteProtected = true;
476
709
  let allowedGroups;
@@ -483,33 +716,33 @@ var MonoCloudNextClient = class {
483
716
  return result;
484
717
  });
485
718
  });
486
- if (!isRouteProtected) return next_server.NextResponse.next({ headers: { "x-monocloud-path": req.nextUrl.pathname + req.nextUrl.search } });
719
+ if (!isRouteProtected) return next_server_js.NextResponse.next({ headers: { "x-monocloud-path": req.nextUrl.pathname + req.nextUrl.search } });
487
720
  const session = await this.getSession(req, nxtResp);
488
721
  if (!session) {
489
722
  if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
490
723
  const result = await options.onAccessDenied(req, evt);
491
- if (result instanceof next_server.NextResponse) return mergeResponse([nxtResp, result]);
492
- if (result) return mergeResponse([nxtResp, new next_server.NextResponse(result.body, result)]);
493
- return next_server.NextResponse.next(nxtResp);
724
+ if (result instanceof next_server_js.NextResponse) return mergeResponse([nxtResp, result]);
725
+ if (result) return mergeResponse([nxtResp, new next_server_js.NextResponse(result.body, result)]);
726
+ return next_server_js.NextResponse.next(nxtResp);
494
727
  }
495
- if (req.nextUrl.pathname.startsWith("/api")) return mergeResponse([nxtResp, next_server.NextResponse.json({ message: "unauthorized" }, { status: 401 })]);
728
+ if (req.nextUrl.pathname.startsWith("/api")) return mergeResponse([nxtResp, next_server_js.NextResponse.json({ message: "unauthorized" }, { status: 401 })]);
496
729
  const signInRoute = new URL(`${appUrl}${(0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn)}`);
497
730
  signInRoute.searchParams.set("return_url", req.nextUrl.pathname + req.nextUrl.search);
498
- return mergeResponse([nxtResp, next_server.NextResponse.redirect(signInRoute)]);
731
+ return mergeResponse([nxtResp, next_server_js.NextResponse.redirect(signInRoute)]);
499
732
  }
500
733
  const groupsClaim = (options === null || options === void 0 ? void 0 : options.groupsClaim) ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM;
501
734
  const onAccessDenied = options === null || options === void 0 ? void 0 : options.onAccessDenied;
502
735
  if (allowedGroups && !(0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, allowedGroups, groupsClaim)) {
503
736
  if (onAccessDenied) {
504
737
  const result = await onAccessDenied(req, evt, session.user);
505
- if (result instanceof next_server.NextResponse) return mergeResponse([nxtResp, result]);
506
- if (result) return mergeResponse([nxtResp, new next_server.NextResponse(result.body, result)]);
507
- return next_server.NextResponse.next(nxtResp);
738
+ if (result instanceof next_server_js.NextResponse) return mergeResponse([nxtResp, result]);
739
+ if (result) return mergeResponse([nxtResp, new next_server_js.NextResponse(result.body, result)]);
740
+ return next_server_js.NextResponse.next(nxtResp);
508
741
  }
509
- if (req.nextUrl.pathname.startsWith("/api")) return mergeResponse([nxtResp, next_server.NextResponse.json({ message: "forbidden" }, { status: 403 })]);
510
- return new next_server.NextResponse(`forbidden`, { status: 403 });
742
+ if (req.nextUrl.pathname.startsWith("/api")) return mergeResponse([nxtResp, next_server_js.NextResponse.json({ message: "forbidden" }, { status: 403 })]);
743
+ return new next_server_js.NextResponse(`forbidden`, { status: 403 });
511
744
  }
512
- return next_server.NextResponse.next(nxtResp);
745
+ return next_server_js.NextResponse.next(nxtResp);
513
746
  }
514
747
  handleAuthRoutes(request, response, path, routes, onError) {
515
748
  switch (path) {
@@ -522,10 +755,101 @@ var MonoCloudNextClient = class {
522
755
  return response.done();
523
756
  }
524
757
  }
758
+ async getSession(...args) {
759
+ let request;
760
+ let response;
761
+ if (args.length === 0) {
762
+ request = new MonoCloudCookieRequest();
763
+ response = new MonoCloudCookieResponse();
764
+ } else ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
765
+ /* v8 ignore next -- @preserve */
766
+ if (!isMonoCloudRequest(request) || !isMonoCloudResponse(response)) throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to getSession()");
767
+ return await this.coreClient.getSession(request, response);
768
+ }
769
+ async getTokens(...args) {
770
+ let request;
771
+ let response;
772
+ let options;
773
+ if (args.length === 0) {
774
+ request = new MonoCloudCookieRequest();
775
+ response = new MonoCloudCookieResponse();
776
+ } else if (args.length === 1) if (args[0] instanceof Request) ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
777
+ else {
778
+ request = new MonoCloudCookieRequest();
779
+ response = new MonoCloudCookieResponse();
780
+ options = args[0];
781
+ }
782
+ else if (args.length === 2 && args[0] instanceof Request) if (args[1] instanceof Response) ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
783
+ else {
784
+ ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
785
+ options = args[1];
786
+ }
787
+ else if (args.length === 2 && args[0] instanceof node_http.IncomingMessage && args[1] instanceof node_http.ServerResponse) ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
788
+ else {
789
+ ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
790
+ options = args[2];
791
+ }
792
+ if (!isMonoCloudRequest(request) || !isMonoCloudResponse(response) || options && typeof options !== "object") throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to getTokens()");
793
+ return await this.coreClient.getTokens(request, response, options);
794
+ }
795
+ async isAuthenticated(...args) {
796
+ let request;
797
+ let response;
798
+ if (args.length === 0) {
799
+ request = new MonoCloudCookieRequest();
800
+ response = new MonoCloudCookieResponse();
801
+ } else ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
802
+ /* v8 ignore next -- @preserve */
803
+ if (!isMonoCloudRequest(request) || !isMonoCloudResponse(response)) throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to isAuthenticated()");
804
+ return await this.coreClient.isAuthenticated(request, response);
805
+ }
525
806
  /**
526
- * Redirects the user to sign-in if not authenticated.
807
+ * Redirects the user to the sign-in flow if they are not authenticated.
808
+ *
809
+ * **This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).**
810
+ *
811
+ * @param options Options to customize the sign-in.
812
+ *
813
+ * @returns
814
+ *
815
+ * @example React Server Component
816
+ *
817
+ * ```tsx
818
+ * import { monoCloud } from "@/lib/monocloud";
819
+ *
820
+ * export default async function Home() {
821
+ * await monoCloud.protect();
822
+ *
823
+ * return <>You are signed in.</>;
824
+ * }
825
+ * ```
826
+ *
827
+ * @example API Handler
527
828
  *
528
- * **Note: This function only works on App Router.**
829
+ * ```typescript
830
+ * import { NextResponse } from "next/server";
831
+ * import { monoCloud } from "@/lib/monocloud";
832
+ *
833
+ * export const GET = async () => {
834
+ * await monoCloud.protect();
835
+ *
836
+ * return NextResponse.json({ secret: "ssshhhh!!!" });
837
+ * };
838
+ * ```
839
+ *
840
+ * @example Server Action
841
+ *
842
+ * ```typescript
843
+ * "use server";
844
+ *
845
+ * import { monoCloud } from "@/lib/monocloud";
846
+ *
847
+ * export async function getMessage() {
848
+ * await monoCloud.protect();
849
+ *
850
+ * return { secret: "sssshhhhh!!!" };
851
+ * }
852
+ * ```
529
853
  */
530
854
  async protect(options) {
531
855
  var _options$authParams19, _options$authParams20, _options$authParams21, _options$authParams22, _options$authParams23, _options$authParams24, _options$authParams25, _options$authParams26, _options$authParams27;
@@ -538,7 +862,7 @@ var MonoCloudNextClient = class {
538
862
  const { headers } = await import("next/headers");
539
863
  path = (await headers()).get("x-monocloud-path") ?? "/";
540
864
  } catch {
541
- throw new Error("protect() can only be used in App Router project");
865
+ throw new Error("protect() can only be used in App Router server environments (RSC, route handlers, or server actions)");
542
866
  }
543
867
  const signInRoute = new URL(`${appUrl}${routes.signIn}`);
544
868
  signInRoute.searchParams.set("return_url", (options === null || options === void 0 ? void 0 : options.returnUrl) ?? path);
@@ -551,7 +875,8 @@ var MonoCloudNextClient = class {
551
875
  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(" "));
552
876
  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);
553
877
  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);
554
- (0, next_navigation.redirect)(signInRoute.toString());
878
+ const { redirect } = await import("next/navigation");
879
+ redirect(signInRoute.toString());
555
880
  }
556
881
  async isUserInGroup(...args) {
557
882
  let request;
@@ -559,44 +884,105 @@ var MonoCloudNextClient = class {
559
884
  let groups;
560
885
  let options;
561
886
  if (args.length === 4) {
562
- const req = args[0];
563
- const res = args[1];
564
887
  groups = args[2];
565
888
  options = args[3];
566
- const reqRes = getMonoCloudReqRes(req, res);
567
- ({request} = reqRes);
568
- ({response} = reqRes);
889
+ ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
569
890
  }
570
891
  if (args.length === 3) {
571
- const req = args[0];
572
- const res = args[1];
573
- groups = args[2];
574
- const reqRes = getMonoCloudReqRes(req, res);
575
- ({request} = reqRes);
576
- ({response} = reqRes);
892
+ if (args[0] instanceof Request) if (args[1] instanceof Response) {
893
+ ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
894
+ groups = args[2];
895
+ } else {
896
+ ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
897
+ groups = args[1];
898
+ options = args[2];
899
+ }
900
+ if (args[0] instanceof node_http.IncomingMessage && args[1] instanceof node_http.ServerResponse) {
901
+ ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
902
+ groups = args[2];
903
+ }
577
904
  }
578
905
  if (args.length === 2) {
579
- request = new MonoCloudCookieRequest();
580
- response = new MonoCloudCookieResponse();
581
- groups = args[0];
582
- options = args[1];
906
+ if (args[0] instanceof Request) {
907
+ ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
908
+ groups = args[1];
909
+ }
910
+ if (Array.isArray(args[0])) {
911
+ request = new MonoCloudCookieRequest();
912
+ response = new MonoCloudCookieResponse();
913
+ groups = args[0];
914
+ options = args[1];
915
+ }
583
916
  }
584
917
  if (args.length === 1) {
585
918
  request = new MonoCloudCookieRequest();
586
919
  response = new MonoCloudCookieResponse();
587
920
  groups = args[0];
588
921
  }
589
- if (!Array.isArray(groups) || !request || !response) throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to isUserInGroup()");
922
+ if (!Array.isArray(groups) || !isMonoCloudRequest(request) || !isMonoCloudResponse(response) || options && typeof options !== "object") throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to isUserInGroup()");
590
923
  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);
591
924
  }
592
925
  /**
593
- * Redirects the user to the sign-in route.
926
+ * Redirects the user to the sign-in flow.
927
+ *
928
+ * **This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).**
929
+ *
930
+ * @param options Options to customize the sign-in.
594
931
  *
595
- * This helper is intended for **App Router** only (server components,
596
- * route handlers, server actions). It constructs the MonoCloud sign-in URL
597
- * with optional parameters and issues a framework redirect.
932
+ * @returns
598
933
  *
599
- * @throws Error if used outside of an App Router context.
934
+ * @example React Server Component
935
+ *
936
+ * ```tsx
937
+ * import { monoCloud } from "@/lib/monocloud";
938
+ *
939
+ * export default async function Home() {
940
+ * const allowed = await monoCloud.isUserInGroup(["admin"]);
941
+ *
942
+ * if (!allowed) {
943
+ * await monoCloud.redirectToSignIn({ returnUrl: "/home" });
944
+ * }
945
+ *
946
+ * return <>You are signed in.</>;
947
+ * }
948
+ * ```
949
+ *
950
+ * @example Server Action
951
+ *
952
+ * ```typescript
953
+ * "use server";
954
+ *
955
+ * import { monoCloud } from "@/lib/monocloud";
956
+ *
957
+ * export async function protectedAction() {
958
+ * const session = await monoCloud.getSession();
959
+ *
960
+ * if (!session) {
961
+ * await monoCloud.redirectToSignIn();
962
+ * }
963
+ *
964
+ * return { data: "Sensitive Data" };
965
+ * }
966
+ * ```
967
+ *
968
+ * @example API Handler
969
+ *
970
+ * ```typescript
971
+ * import { NextResponse } from "next/server";
972
+ * import { monoCloud } from "@/lib/monocloud";
973
+ *
974
+ * export const GET = async () => {
975
+ * const session = await monoCloud.getSession();
976
+ *
977
+ * if (!session) {
978
+ * await monoCloud.redirectToSignIn({
979
+ * returnUrl: "/dashboard",
980
+ * });
981
+ * }
982
+ *
983
+ * return NextResponse.json({ data: "Protected content" });
984
+ * };
985
+ * ```
600
986
  */
601
987
  async redirectToSignIn(options) {
602
988
  const { routes, appUrl } = this.coreClient.getOptions();
@@ -604,7 +990,7 @@ var MonoCloudNextClient = class {
604
990
  const { headers } = await import("next/headers");
605
991
  await headers();
606
992
  } catch {
607
- throw new Error("redirectToSignIn() can only be used in App Router project");
993
+ throw new Error("redirectToSignIn() can only be used in App Router server environments (RSC, route handlers, or server actions)");
608
994
  }
609
995
  const signInRoute = new URL(`${appUrl}${routes.signIn}`);
610
996
  if (options === null || options === void 0 ? void 0 : options.returnUrl) signInRoute.searchParams.set("return_url", options.returnUrl);
@@ -617,15 +1003,69 @@ var MonoCloudNextClient = class {
617
1003
  if (Array.isArray(options === null || options === void 0 ? void 0 : options.acrValues)) signInRoute.searchParams.set("acr_values", options.acrValues.join(" "));
618
1004
  if (options === null || options === void 0 ? void 0 : options.loginHint) signInRoute.searchParams.set("login_hint", options.loginHint);
619
1005
  if (options === null || options === void 0 ? void 0 : options.prompt) signInRoute.searchParams.set("prompt", options.prompt);
620
- (0, next_navigation.redirect)(signInRoute.toString());
1006
+ const { redirect } = await import("next/navigation");
1007
+ redirect(signInRoute.toString());
621
1008
  }
622
1009
  /**
623
- * Redirects the user to the sign-out route.
1010
+ * Redirects the user to the sign-out flow.
1011
+ *
1012
+ * **This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).**
1013
+ *
1014
+ * @param options Options to customize the sign out.
1015
+ *
1016
+ * @returns
624
1017
  *
625
- * This helper is intended for **App Router** only. It builds the sign-out
626
- * URL and optionally attaches a `post_logout_redirect_uri` override.
1018
+ * @example React Server Component
627
1019
  *
628
- * @throws Error if used outside of an App Router context.
1020
+ * ```tsx
1021
+ * import { monoCloud } from "@/lib/monocloud";
1022
+ *
1023
+ * export default async function Page() {
1024
+ * const session = await monoCloud.getSession();
1025
+ *
1026
+ * // Example: Force sign-out if a specific condition is met (e.g., account suspended)
1027
+ * if (session?.user.isSuspended) {
1028
+ * await monoCloud.redirectToSignOut();
1029
+ * }
1030
+ *
1031
+ * return <>Welcome User</>;
1032
+ * }
1033
+ * ```
1034
+ *
1035
+ * @example Server Action
1036
+ *
1037
+ * ```typescript
1038
+ * "use server";
1039
+ *
1040
+ * import { monoCloud } from "@/lib/monocloud";
1041
+ *
1042
+ * export async function signOutAction() {
1043
+ * const session = await monoCloud.getSession();
1044
+ *
1045
+ * if (session) {
1046
+ * await monoCloud.redirectToSignOut();
1047
+ * }
1048
+ * }
1049
+ * ```
1050
+ *
1051
+ * @example API Handler
1052
+ *
1053
+ * ```typescript
1054
+ * import { monoCloud } from "@/lib/monocloud";
1055
+ * import { NextResponse } from "next/server";
1056
+ *
1057
+ * export const GET = async () => {
1058
+ * const session = await monoCloud.getSession();
1059
+ *
1060
+ * if (session) {
1061
+ * await monoCloud.redirectToSignOut({
1062
+ * postLogoutRedirectUri: "/goodbye",
1063
+ * });
1064
+ * }
1065
+ *
1066
+ * return NextResponse.json({ status: "already_signed_out" });
1067
+ * };
1068
+ * ```
629
1069
  */
630
1070
  async redirectToSignOut(options) {
631
1071
  var _options$postLogoutRe;
@@ -634,70 +1074,13 @@ var MonoCloudNextClient = class {
634
1074
  const { headers } = await import("next/headers");
635
1075
  await headers();
636
1076
  } catch {
637
- throw new Error("redirectToSignOut() can only be used in App Router project");
1077
+ throw new Error("redirectToSignOut() can only be used in App Router server environments (RSC, route handlers, or server actions)");
638
1078
  }
639
1079
  const signOutRoute = new URL(`${appUrl}${routes.signOut}`);
640
1080
  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);
641
- (0, next_navigation.redirect)(signOutRoute.toString());
642
- }
643
- resolveFunction(baseHandler) {
644
- return ((...args) => {
645
- if (args.length === 3) {
646
- const req = args[0];
647
- const res = args[1];
648
- const options = args[2];
649
- return baseHandler(req, res, options);
650
- }
651
- if (args.length === 2) {
652
- const req = args[0];
653
- const res = args[1];
654
- return baseHandler(req, res);
655
- }
656
- if (args.length === 1) {
657
- const options = args[0];
658
- return baseHandler(void 0, void 0, options);
659
- }
660
- return baseHandler();
661
- });
662
- }
663
- resolvedGetSession(req, resOrCtx) {
664
- let request;
665
- let response;
666
- if (req && resOrCtx) {
667
- const result = getMonoCloudReqRes(req, resOrCtx);
668
- ({request} = result);
669
- ({response} = result);
670
- } else {
671
- request = new MonoCloudCookieRequest();
672
- response = new MonoCloudCookieResponse();
673
- }
674
- return this.coreClient.getSession(request, response);
675
- }
676
- resolvedGetTokens(req, resOrCtx, options) {
677
- let request;
678
- let response;
679
- if (req && resOrCtx) {
680
- const result = getMonoCloudReqRes(req, resOrCtx);
681
- ({request} = result);
682
- ({response} = result);
683
- } else {
684
- request = new MonoCloudCookieRequest();
685
- response = new MonoCloudCookieResponse();
686
- }
687
- return this.coreClient.getTokens(request, response, options);
688
- }
689
- resolvedIsAuthenticated(req, resOrCtx) {
690
- let request;
691
- let response;
692
- if (req && resOrCtx) {
693
- const result = getMonoCloudReqRes(req, resOrCtx);
694
- ({request} = result);
695
- ({response} = result);
696
- } else {
697
- request = new MonoCloudCookieRequest();
698
- response = new MonoCloudCookieResponse();
699
- }
700
- return this.coreClient.isAuthenticated(request, response);
1081
+ if (typeof (options === null || options === void 0 ? void 0 : options.federated) === "boolean") signOutRoute.searchParams.set("federated", options.federated.toString());
1082
+ const { redirect } = await import("next/navigation");
1083
+ redirect(signOutRoute.toString());
701
1084
  }
702
1085
  getOptions() {
703
1086
  return this.coreClient.getOptions();