@monocloud/auth-nextjs 0.1.5 → 0.1.7

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,10 +1,10 @@
1
- const require_chunk = require('./chunk-CbDLau6x.cjs');
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_chunk = require('./chunk-C0xms8kb.cjs');
2
3
  let _monocloud_auth_node_core = require("@monocloud/auth-node-core");
3
4
  let next_server_js = require("next/server.js");
4
5
  let _monocloud_auth_node_core_internal = require("@monocloud/auth-node-core/internal");
5
6
  let _monocloud_auth_node_core_utils = require("@monocloud/auth-node-core/utils");
6
7
  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 {
@@ -220,6 +220,12 @@ var MonoCloudCookieRequest = class {
220
220
  const isMonoCloudRequest = (req) => req instanceof MonoCloudAppRouterRequest || req instanceof MonoCloudPageRouterRequest || req instanceof MonoCloudCookieRequest;
221
221
  const isMonoCloudResponse = (res) => res instanceof MonoCloudAppRouterResponse || res instanceof MonoCloudPageRouterResponse || res instanceof MonoCloudCookieResponse;
222
222
  const isAppRouter = (req) => req instanceof Request || req.headers instanceof Headers || typeof req.bodyUsed === "boolean";
223
+ const isNodeRequest = (req) => {
224
+ return !!(req && typeof req === "object" && "headers" in req && !("bodyUsed" in req) && typeof req.on === "function");
225
+ };
226
+ const isNodeResponse = (res) => {
227
+ return !!(res && typeof res === "object" && "setHeader" in res && typeof res.setHeader === "function" && "end" in res && typeof res.end === "function");
228
+ };
223
229
  const getNextRequest = (req) => {
224
230
  if (req instanceof next_server_js.NextRequest) return req;
225
231
  return new next_server_js.NextRequest(req.url, {
@@ -253,7 +259,7 @@ const getMonoCloudCookieReqRes = (req, resOrCtx) => {
253
259
  request = new MonoCloudAppRouterRequest(getNextRequest(req));
254
260
  response = resOrCtx instanceof Response ? new MonoCloudAppRouterResponse(getNextResponse(resOrCtx)) : new MonoCloudCookieResponse();
255
261
  } else {
256
- if (!(req instanceof node_http.IncomingMessage) || !(resOrCtx instanceof node_http.ServerResponse)) throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid pages router request and response");
262
+ if (!isNodeRequest(req) || !isNodeResponse(resOrCtx)) throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid pages router request and response");
257
263
  request = new MonoCloudPageRouterRequest(req);
258
264
  response = new MonoCloudPageRouterResponse(resOrCtx);
259
265
  }
@@ -280,35 +286,32 @@ const mergeResponse = (responses) => {
280
286
  //#endregion
281
287
  //#region src/monocloud-next-client.ts
282
288
  /**
283
- * The MonoCloud Next.js Client.
289
+ * `MonoCloudNextClient` is the core SDK entry point for integrating MonoCloud authentication into a Next.js application.
284
290
  *
285
- * @example Using Environment Variables (Recommended)
291
+ * It provides:
292
+ * - Authentication middleware
293
+ * - Route protection helpers
294
+ * - Session and token access
295
+ * - Redirect utilities
296
+ * - Server-side enforcement helpers
286
297
  *
287
- * 1. Add following variables to your `.env`.
298
+ * ## 1. Add environment variables
288
299
  *
289
- * ```bash
300
+ * ```bash:.env.local
290
301
  * MONOCLOUD_AUTH_TENANT_DOMAIN=<tenant-domain>
291
302
  * MONOCLOUD_AUTH_CLIENT_ID=<client-id>
292
303
  * MONOCLOUD_AUTH_CLIENT_SECRET=<client-secret>
293
- * MONOCLOUD_AUTH_SCOPES=openid profile email # Default
304
+ * MONOCLOUD_AUTH_SCOPES=openid profile email
294
305
  * MONOCLOUD_AUTH_APP_URL=http://localhost:3000
295
306
  * MONOCLOUD_AUTH_COOKIE_SECRET=<cookie-secret>
296
307
  * ```
297
308
  *
298
- * 2. Instantiate the client in a shared file (e.g., lib/monocloud.ts)
299
- *
300
- * ```typescript
301
- * import { MonoCloudNextClient } from '@monocloud/auth-nextjs';
302
- *
303
- * export const monoCloud = new MonoCloudNextClient();
304
- * ```
305
- *
306
- * 3. Add MonoCloud middleware/proxy
309
+ * ## 2. Register middleware
307
310
  *
308
- * ```typescript
309
- * import { monoCloud } from "@/lib/monocloud";
311
+ * ```typescript:src/proxy.ts
312
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
310
313
  *
311
- * export default monoCloud.authMiddleware();
314
+ * export default authMiddleware();
312
315
  *
313
316
  * export const config = {
314
317
  * matcher: [
@@ -317,218 +320,115 @@ const mergeResponse = (responses) => {
317
320
  * };
318
321
  * ```
319
322
  *
320
- * @example Using Constructor Options
323
+ * ## Advanced usage
321
324
  *
322
- * ⚠️ Security Note: Never commit your credentials to version control. Load them from environment variables.
325
+ * ### Create a shared client instance
326
+ *
327
+ * By default, the SDK exposes function exports (for example, `authMiddleware()`, `getSession()`, `getTokens()`) that internally use a shared singleton `MonoCloudNextClient`.
328
+ *
329
+ * Create your own `MonoCloudNextClient` instance when you need multiple configurations, dependency injection, or explicit control over initialization.
330
+ *
331
+ * ```ts:src/monocloud.ts
332
+ * import { MonoCloudNextClient } from "@monocloud/auth-nextjs";
333
+ *
334
+ * export const monoCloud = new MonoCloudNextClient();
335
+ * ```
323
336
  *
324
- * 1. Instantiate the client in a shared file (e.g., lib/monocloud.ts)
337
+ * ### Using instance methods
325
338
  *
326
- * ```typescript
327
- * import { MonoCloudNextClient } from '@monocloud/auth-nextjs';
339
+ * Once you create a client instance, call methods directly on it instead of using the default function exports.
340
+ *
341
+ * ```ts:src/app/page.tsx
342
+ * import { monoCloud } from "@/monocloud";
343
+ *
344
+ * export default async function Page() {
345
+ * const session = await monoCloud.getSession();
346
+ *
347
+ * if (!session) {
348
+ * return <>Not signed in</>;
349
+ * }
350
+ *
351
+ * return <>Hello {session.user.name}</>;
352
+ * }
353
+ * ```
354
+ *
355
+ * #### Using constructor options
356
+ *
357
+ * 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.
358
+ *
359
+ * ```ts:src/monocloud.ts
360
+ * import { MonoCloudNextClient } from "@monocloud/auth-nextjs";
328
361
  *
329
362
  * export const monoCloud = new MonoCloudNextClient({
330
- * tenantDomain: '<tenant-domain>',
331
- * clientId: '<client-id>',
332
- * clientSecret: '<client-secret>',
333
- * scopes: 'openid profile email', // Default
334
- * appUrl: 'http://localhost:3000',
335
- * cookieSecret: '<cookie-secret>'
363
+ * tenantDomain: "<tenant-domain>",
364
+ * clientId: "<client-id>",
365
+ * clientSecret: "<client-secret>",
366
+ * appUrl: "http://localhost:3000",
367
+ * cookieSecret: "<cookie-secret>",
368
+ * defaultAuthParams: {
369
+ * scopes: "openid profile email",
370
+ * },
336
371
  * });
337
372
  * ```
338
- * 2. Add MonoCloud middleware/proxy
339
373
  *
340
- * ```typescript
341
- * import { monoCloud } from "@/lib/monocloud";
374
+ * ### Modifying default routes
342
375
  *
343
- * export default monoCloud.authMiddleware();
376
+ * If you customize any of the default auth route paths:
344
377
  *
345
- * export const config = {
346
- * matcher: [
347
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
348
- * ],
349
- * };
378
+ * - Also set the corresponding `NEXT_PUBLIC_` environment variables so client-side helpers
379
+ * (for example `<SignIn />`, `<SignOut />`, and `useAuth()`) can discover the correct URLs.
380
+ * - Update the **Application URLs** in your MonoCloud Dashboard to match the new paths.
381
+ *
382
+ * Example:
383
+ *
384
+ * ```bash:.env.local
385
+ * MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
386
+ * NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
350
387
  * ```
351
388
  *
352
- * <details>
353
- * <summary>All Environment Variables</summary>
354
- * <h4>Core Configuration (Required)</h4>
355
- *
356
- * <ul>
357
- * <li><strong>MONOCLOUD_AUTH_CLIENT_ID : </strong>Unique identifier for your application/client.</li>
358
- * <li><strong>MONOCLOUD_AUTH_CLIENT_SECRET : </strong>Application/client secret.</li>
359
- * <li><strong>MONOCLOUD_AUTH_TENANT_DOMAIN : </strong>The domain of your MonoCloud tenant (e.g., https://your-tenant.us.monocloud.com).</li>
360
- * <li><strong>MONOCLOUD_AUTH_APP_URL : </strong>The base URL where your application is hosted.</li>
361
- * <li><strong>MONOCLOUD_AUTH_COOKIE_SECRET : </strong>A long, random string used to encrypt and sign session cookies.</li>
362
- * </ul>
363
- *
364
- * <h4>Authentication &amp; Security</h4>
365
- *
366
- * <ul>
367
- * <li><strong>MONOCLOUD_AUTH_SCOPES : </strong>A space-separated list of OIDC scopes to request (e.g., openid profile email).</li>
368
- * <li><strong>MONOCLOUD_AUTH_RESOURCE : </strong>The default resource/audience identifier for access tokens.</li>
369
- * <li><strong>MONOCLOUD_AUTH_USE_PAR : </strong>Enables Pushed Authorization Requests.</li>
370
- * <li><strong>MONOCLOUD_AUTH_CLOCK_SKEW : </strong>The allowed clock drift in seconds when validating token timestamps.</li>
371
- * <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>
372
- * <li><strong>MONOCLOUD_AUTH_RESPONSE_TIMEOUT : </strong>The maximum time in milliseconds to wait for a response.</li>
373
- * <li><strong>MONOCLOUD_AUTH_ALLOW_QUERY_PARAM_OVERRIDES : </strong>Allows dynamic overrides of auth parameters via URL query strings.</li>
374
- * <li><strong>MONOCLOUD_AUTH_POST_LOGOUT_REDIRECT_URI : </strong>The URL users are sent to after a successful logout.</li>
375
- * <li><strong>MONOCLOUD_AUTH_USER_INFO : </strong>Determines if user profile data from the UserInfo endpoint should be fetched after authorization code exchange.</li>
376
- * <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>
377
- * <li><strong>MONOCLOUD_AUTH_ID_TOKEN_SIGNING_ALG : </strong>The expected algorithm for signing ID tokens (e.g., RS256).</li>
378
- * <li><strong>MONOCLOUD_AUTH_FILTERED_ID_TOKEN_CLAIMS : </strong>A space-separated list of claims to exclude from the session object.</li>
379
- * </ul>
380
- *
381
- * <h4>Routes</h4>
382
- *
383
- * <aside>
384
- * <strong>⚠️ Important: Modifying Default Routes</strong>
385
- * <p>If you choose to customize any of the default route paths, you must adhere to the following requirements:</p>
386
- * <ul>
387
- * <li>
388
- * <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.
389
- * </li>
390
- * <li>
391
- * <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.
392
- * </li>
393
- * </ul>
394
- * <p><em>Example:</em></p>
395
- * <code>
396
- * MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback<br />
397
- * NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
398
- * </code>
399
- * <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>
400
- * </aside>
401
- *
402
- * <ul>
403
- * <li><strong>MONOCLOUD_AUTH_CALLBACK_URL : </strong>The application path where MonoCloud sends the user after authentication.</li>
404
- * <li><strong>MONOCLOUD_AUTH_SIGNIN_URL : </strong>The internal route path to trigger the sign-in.</li>
405
- * <li><strong>MONOCLOUD_AUTH_SIGNOUT_URL : </strong>The internal route path to trigger the sign-out.</li>
406
- * <li><strong>MONOCLOUD_AUTH_USER_INFO_URL : </strong>The route that exposes the current user's profile from userinfo endpoint.</li>
407
- * </ul>
408
- *
409
- * <h4>Session Cookie Settings</h4>
410
- *
411
- * <ul>
412
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_NAME : </strong>The name of the cookie used to store the user session.</li>
413
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_PATH : </strong>The scope path for the session cookie.</li>
414
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_DOMAIN : </strong>The domain scope for the session cookie.</li>
415
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_HTTP_ONLY : </strong>Prevents client-side scripts from accessing the session cookie.</li>
416
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_SECURE : </strong>Ensures the session cookie is only sent over HTTPS.</li>
417
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_SAME_SITE : </strong>The SameSite policy for the session cookie (Lax, Strict, or None).</li>
418
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_PERSISTENT : </strong>If true, the session survives browser restarts.</li>
419
- * <li><strong>MONOCLOUD_AUTH_SESSION_SLIDING : </strong>If true, the session will be a sliding session instead of absolute.</li>
420
- * <li><strong>MONOCLOUD_AUTH_SESSION_DURATION : </strong>The session lifetime in seconds.</li>
421
- * <li><strong>MONOCLOUD_AUTH_SESSION_MAX_DURATION : </strong>The absolute maximum lifetime of a session in seconds.</li>
422
- * </ul>
423
- *
424
- * <h4>State Cookie Settings</h4>
425
- *
426
- * <ul>
427
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_NAME : </strong>The name of the cookie used to store OpenID state/nonce.</li>
428
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_PATH : </strong>The scope path for the state cookie.</li>
429
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_DOMAIN : </strong>The domain scope for the state cookie.</li>
430
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_SECURE : </strong>Ensures the state cookie is only sent over HTTPS</li>
431
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_SAME_SITE : </strong>The SameSite policy for the state cookie.</li>
432
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_PERSISTENT : </strong>Whether the state cookie is persistent.</li>
433
- * </ul>
434
- *
435
- * <h4>Caching</h4>
436
- *
437
- * <ul>
438
- * <li><strong>MONOCLOUD_AUTH_JWKS_CACHE_DURATION : </strong>Duration in seconds to cache the JSON Web Key Set.</li>
439
- * <li><strong>MONOCLOUD_AUTH_METADATA_CACHE_DURATION : </strong>Duration in seconds to cache the OpenID discovery metadata.</li>
440
- * </ul>
441
- * </details>
389
+ * When routes are overridden, the Redirect URI configured in the dashboard
390
+ * must reflect the new path. For example, during local development:
442
391
  *
392
+ * `http://localhost:3000/api/custom_callback`
443
393
  *
394
+ * @category Classes
444
395
  */
445
396
  var MonoCloudNextClient = class {
446
397
  /**
447
- * The underlying OIDC client instance used for low-level OpenID Connect operations.
398
+ * This exposes the framework-agnostic MonoCloud client used internally by the Next.js SDK.
399
+ * Use it if you need access to lower-level functionality not directly exposed by MonoCloudNextClient.
400
+ *
401
+ * @returns Returns the underlying **Node client** instance.
402
+ */
403
+ get coreClient() {
404
+ return this._coreClient;
405
+ }
406
+ /**
407
+ * This is intended for advanced scenarios requiring direct control over the authorization or token flow.
448
408
  *
449
- * @example
450
- * // Manually revoke an access token
451
- * await client.oidcClient.revokeToken(accessToken, 'access_token');
409
+ * @returns Returns the underlying **OIDC client** used for OpenID Connect operations.
452
410
  */
453
411
  get oidcClient() {
454
412
  return this.coreClient.oidcClient;
455
413
  }
456
414
  /**
457
- * @param options Configuration options including domain, client ID, and secret.
415
+ * Creates a new client instance.
416
+ *
417
+ * @param options Optional configuration for initializing the MonoCloud client. If not provided, settings are automatically resolved from environment variables.
458
418
  */
459
419
  constructor(options) {
460
420
  const opt = {
461
421
  ...options ?? {},
462
- userAgent: (options === null || options === void 0 ? void 0 : options.userAgent) ?? `@monocloud/auth-nextjs@0.1.5`,
422
+ userAgent: (options === null || options === void 0 ? void 0 : options.userAgent) ?? `@monocloud/auth-nextjs@0.1.7`,
463
423
  debugger: (options === null || options === void 0 ? void 0 : options.debugger) ?? "@monocloud:auth-nextjs"
464
424
  };
465
425
  this.registerPublicEnvVariables();
466
- this.coreClient = new _monocloud_auth_node_core.MonoCloudCoreClient(opt);
426
+ this._coreClient = new _monocloud_auth_node_core.MonoCloudCoreClient(opt);
467
427
  }
468
428
  /**
469
- * Creates a **Next.js API route handler** (for both Pages Router and App Router)
470
- * that processes all MonoCloud authentication endpoints
471
- * (`/signin`, `/callback`, `/userinfo`, `/signout`).
472
- *
473
- * @param options Authentication configuration routes.
474
- *
475
- * **Note:** If you are already using `authMiddleware()`, you typically do **not**
476
- * need this API route handler. This function is intended for applications where
477
- * middleware cannot be used—such as statically generated (SSG) deployments that still
478
- * require server-side authentication flows.
479
- *
480
- * @example App Router
481
- *
482
- * ```typescript
483
- * // app/api/auth/[...monocloud]/route.ts
484
- *
485
- * import { monoCloud } from "@/lib/monocloud";
486
- *
487
- * export const GET = monoCloud.monoCloudAuth();
488
- *```
489
- *
490
- * @example App Router with Response
491
- *
492
- * ```typescript
493
- * import { monoCloud } from "@/lib/monocloud";
494
- * import { NextRequest, NextResponse } from "next/server";
495
- *
496
- * export const GET = (req: NextRequest) => {
497
- * const authHandler = monoCloud.monoCloudAuth();
498
- *
499
- * const res = new NextResponse();
500
- *
501
- * res.cookies.set("last_auth_requested", `${Date.now()}`);
502
- *
503
- * return authHandler(req, res);
504
- * };
505
- * ```
506
- *
507
- * @example Pages Router
508
- *
509
- * ```typescript
510
- * // pages/api/auth/[...monocloud].ts
511
- *
512
- * import { monoCloud } from "@/lib/monocloud";
513
- *
514
- * export default monoCloud.monoCloudAuth();
515
- *```
516
- *
517
- * @example Page Router with Response
518
- *
519
- * ```typescript
520
- * import { monoCloud } from "@/lib/monocloud";
521
- * import { NextApiRequest, NextApiResponse } from "next";
522
- *
523
- * export default function handler(req: NextApiRequest, res: NextApiResponse) {
524
- * const authHandler = monoCloud.monoCloudAuth();
525
- *
526
- * res.setHeader("last_auth_requested", `${Date.now()}`);
527
- *
528
- * return authHandler(req, res);
529
- * }
530
- * ```
531
- *
429
+ * @see {@link monoCloudAuth} for full docs and examples.
430
+ * @param options Optional configuration for the auth handler.
431
+ * @returns Returns a Next.js-compatible handler for App Router route handlers or Pages Router API routes.
532
432
  */
533
433
  monoCloudAuth(options) {
534
434
  return (req, resOrCtx) => {
@@ -596,10 +496,10 @@ var MonoCloudNextClient = class {
596
496
  if (!session) {
597
497
  var _options$authParams10, _options$authParams11, _options$authParams12, _options$authParams13, _options$authParams14, _options$authParams15, _options$authParams16, _options$authParams17, _options$authParams18;
598
498
  if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
599
- const customProps$1 = await options.onAccessDenied({ ...context });
499
+ const customProps = await options.onAccessDenied({ ...context });
600
500
  return {
601
- ...customProps$1 ?? {},
602
- props: { ...(customProps$1 === null || customProps$1 === void 0 ? void 0 : customProps$1.props) ?? {} }
501
+ ...customProps ?? {},
502
+ props: { ...(customProps === null || customProps === void 0 ? void 0 : customProps.props) ?? {} }
603
503
  };
604
504
  }
605
505
  const { routes, appUrl } = this.getOptions();
@@ -621,13 +521,13 @@ var MonoCloudNextClient = class {
621
521
  }
622
522
  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)) {
623
523
  var _options$onGroupAcces;
624
- const customProps$1 = await ((_options$onGroupAcces = options.onGroupAccessDenied) === null || _options$onGroupAcces === void 0 ? void 0 : _options$onGroupAcces.call(options, {
524
+ const customProps = await ((_options$onGroupAcces = options.onGroupAccessDenied) === null || _options$onGroupAcces === void 0 ? void 0 : _options$onGroupAcces.call(options, {
625
525
  ...context,
626
526
  user: session.user
627
527
  })) ?? { props: { groupAccessDenied: true } };
628
528
  return {
629
- ...customProps$1,
630
- props: { ...customProps$1.props ?? {} }
529
+ ...customProps,
530
+ props: { ...customProps.props ?? {} }
631
531
  };
632
532
  }
633
533
  const customProps = (options === null || options === void 0 ? void 0 : options.getServerSideProps) ? await options.getServerSideProps(context) : {};
@@ -800,7 +700,7 @@ var MonoCloudNextClient = class {
800
700
  ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
801
701
  options = args[1];
802
702
  }
803
- else if (args.length === 2 && args[0] instanceof node_http.IncomingMessage && args[1] instanceof node_http.ServerResponse) ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
703
+ else if (args.length === 2 && isNodeRequest(args[0]) && isNodeResponse(args[1])) ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
804
704
  else {
805
705
  ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
806
706
  options = args[2];
@@ -820,52 +720,9 @@ var MonoCloudNextClient = class {
820
720
  return await this.coreClient.isAuthenticated(request, response);
821
721
  }
822
722
  /**
823
- * Redirects the user to the sign-in flow if they are not authenticated.
824
- *
825
- * **This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).**
826
- *
827
- * @param options Options to customize the sign-in.
828
- *
829
- * @returns
830
- *
831
- * @example React Server Component
832
- *
833
- * ```tsx
834
- * import { monoCloud } from "@/lib/monocloud";
835
- *
836
- * export default async function Home() {
837
- * await monoCloud.protect();
838
- *
839
- * return <>You are signed in.</>;
840
- * }
841
- * ```
842
- *
843
- * @example API Handler
844
- *
845
- * ```typescript
846
- * import { NextResponse } from "next/server";
847
- * import { monoCloud } from "@/lib/monocloud";
848
- *
849
- * export const GET = async () => {
850
- * await monoCloud.protect();
851
- *
852
- * return NextResponse.json({ secret: "ssshhhh!!!" });
853
- * };
854
- * ```
855
- *
856
- * @example Server Action
857
- *
858
- * ```typescript
859
- * "use server";
860
- *
861
- * import { monoCloud } from "@/lib/monocloud";
862
- *
863
- * export async function getMessage() {
864
- * await monoCloud.protect();
865
- *
866
- * return { secret: "sssshhhhh!!!" };
867
- * }
868
- * ```
723
+ * @see {@link protect} for full docs and examples.
724
+ * @param options Optional configuration for redirect behavior (for example, return URL or sign-in parameters).
725
+ * @returns Resolves if the user is authenticated; otherwise triggers a redirect.
869
726
  */
870
727
  async protect(options) {
871
728
  var _options$authParams19, _options$authParams20, _options$authParams21, _options$authParams22, _options$authParams23, _options$authParams24, _options$authParams25, _options$authParams26, _options$authParams27;
@@ -874,7 +731,7 @@ var MonoCloudNextClient = class {
874
731
  try {
875
732
  const session = await this.getSession();
876
733
  if (session && !(options === null || options === void 0 ? void 0 : options.groups)) return;
877
- if (session && options && options.groups && (0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, options.groups, options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options.matchAll)) return;
734
+ if (session && (options === null || options === void 0 ? void 0 : options.groups) && (0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, options.groups, options.groupsClaim ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM, options.matchAll)) return;
878
735
  const { headers } = await import("next/headers");
879
736
  path = (await headers()).get("x-monocloud-path") ?? "/";
880
737
  } catch {
@@ -913,7 +770,7 @@ var MonoCloudNextClient = class {
913
770
  groups = args[1];
914
771
  options = args[2];
915
772
  }
916
- if (args[0] instanceof node_http.IncomingMessage && args[1] instanceof node_http.ServerResponse) {
773
+ if (isNodeRequest(args[0]) && isNodeResponse(args[1])) {
917
774
  ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
918
775
  groups = args[2];
919
776
  }
@@ -939,66 +796,9 @@ var MonoCloudNextClient = class {
939
796
  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);
940
797
  }
941
798
  /**
942
- * Redirects the user to the sign-in flow.
943
- *
944
- * **This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).**
945
- *
946
- * @param options Options to customize the sign-in.
947
- *
948
- * @returns
949
- *
950
- * @example React Server Component
951
- *
952
- * ```tsx
953
- * import { monoCloud } from "@/lib/monocloud";
954
- *
955
- * export default async function Home() {
956
- * const allowed = await monoCloud.isUserInGroup(["admin"]);
957
- *
958
- * if (!allowed) {
959
- * await monoCloud.redirectToSignIn({ returnUrl: "/home" });
960
- * }
961
- *
962
- * return <>You are signed in.</>;
963
- * }
964
- * ```
965
- *
966
- * @example Server Action
967
- *
968
- * ```typescript
969
- * "use server";
970
- *
971
- * import { monoCloud } from "@/lib/monocloud";
972
- *
973
- * export async function protectedAction() {
974
- * const session = await monoCloud.getSession();
975
- *
976
- * if (!session) {
977
- * await monoCloud.redirectToSignIn();
978
- * }
979
- *
980
- * return { data: "Sensitive Data" };
981
- * }
982
- * ```
983
- *
984
- * @example API Handler
985
- *
986
- * ```typescript
987
- * import { NextResponse } from "next/server";
988
- * import { monoCloud } from "@/lib/monocloud";
989
- *
990
- * export const GET = async () => {
991
- * const session = await monoCloud.getSession();
992
- *
993
- * if (!session) {
994
- * await monoCloud.redirectToSignIn({
995
- * returnUrl: "/dashboard",
996
- * });
997
- * }
998
- *
999
- * return NextResponse.json({ data: "Protected content" });
1000
- * };
1001
- * ```
799
+ * @see {@link redirectToSignIn} for full docs and examples.
800
+ * @param options Optional configuration for the redirect, such as `returnUrl` or additional sign-in parameters.
801
+ * @returns Never resolves. Triggers a redirect to the sign-in flow.
1002
802
  */
1003
803
  async redirectToSignIn(options) {
1004
804
  const { routes, appUrl } = this.coreClient.getOptions();
@@ -1023,65 +823,9 @@ var MonoCloudNextClient = class {
1023
823
  redirect(signInRoute.toString());
1024
824
  }
1025
825
  /**
1026
- * Redirects the user to the sign-out flow.
1027
- *
1028
- * **This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).**
1029
- *
1030
- * @param options Options to customize the sign out.
1031
- *
1032
- * @returns
1033
- *
1034
- * @example React Server Component
1035
- *
1036
- * ```tsx
1037
- * import { monoCloud } from "@/lib/monocloud";
1038
- *
1039
- * export default async function Page() {
1040
- * const session = await monoCloud.getSession();
1041
- *
1042
- * // Example: Force sign-out if a specific condition is met (e.g., account suspended)
1043
- * if (session?.user.isSuspended) {
1044
- * await monoCloud.redirectToSignOut();
1045
- * }
1046
- *
1047
- * return <>Welcome User</>;
1048
- * }
1049
- * ```
1050
- *
1051
- * @example Server Action
1052
- *
1053
- * ```typescript
1054
- * "use server";
1055
- *
1056
- * import { monoCloud } from "@/lib/monocloud";
1057
- *
1058
- * export async function signOutAction() {
1059
- * const session = await monoCloud.getSession();
1060
- *
1061
- * if (session) {
1062
- * await monoCloud.redirectToSignOut();
1063
- * }
1064
- * }
1065
- * ```
1066
- *
1067
- * @example API Handler
1068
- *
1069
- * ```typescript
1070
- * import { monoCloud } from "@/lib/monocloud";
1071
- * import { NextResponse } from "next/server";
1072
- *
1073
- * export const GET = async () => {
1074
- * const session = await monoCloud.getSession();
1075
- *
1076
- * if (session) {
1077
- * await monoCloud.redirectToSignOut({
1078
- * postLogoutRedirectUri: "/goodbye",
1079
- * });
1080
- * }
1081
- *
1082
- * return NextResponse.json({ status: "already_signed_out" });
1083
- * };
1084
- * ```
826
+ * @see {@link redirectToSignOut} for full docs and examples.
827
+ * @param options Optional configuration for the redirect, such as `postLogoutRedirectUri` or additional sign-out parameters.
828
+ * @returns Never resolves. Triggers a redirect to the sign-out flow.
1085
829
  */
1086
830
  async redirectToSignOut(options) {
1087
831
  var _options$postLogoutRe;
@@ -1109,6 +853,276 @@ var MonoCloudNextClient = class {
1109
853
  }
1110
854
  };
1111
855
 
856
+ //#endregion
857
+ //#region src/initialize.ts
858
+ let instance;
859
+ /**
860
+ * Retrieves the singleton instance of the MonoCloudNextClient.
861
+ * Initializes it lazily on the first call.
862
+ */
863
+ const getInstance = () => {
864
+ instance ??= new MonoCloudNextClient();
865
+ return instance;
866
+ };
867
+ /**
868
+ * Creates a Next.js catch-all auth route handler (Pages Router and App Router) for the built-in routes (`/signin`, `/callback`, `/userinfo`, `/signout`).
869
+ *
870
+ * Mount this handler on a catch-all route (e.g. `/api/auth/[...monocloud]`).
871
+ *
872
+ * > If you already use `authMiddleware()`, you typically don’t need this handler. Use `monoCloudAuth()` when middleware cannot be used or when auth routes need customization.
873
+ *
874
+ * @example App Router
875
+ * ```tsx:src/app/api/auth/[...monocloud]/route.ts tab="App Router" tab-group="monoCloudAuth"
876
+ * import { monoCloudAuth } from "@monocloud/auth-nextjs";
877
+ *
878
+ * export const GET = monoCloudAuth();
879
+ *```
880
+ *
881
+ * @example App Router (Response)
882
+ * ```tsx:src/app/api/auth/[...monocloud]/route.ts tab="App Router (Response)" tab-group="monoCloudAuth"
883
+ * import { monoCloudAuth } from "@monocloud/auth-nextjs";
884
+ * import { NextRequest, NextResponse } from "next/server";
885
+ *
886
+ * export const GET = (req: NextRequest) => {
887
+ * const authHandler = monoCloudAuth();
888
+ *
889
+ * const res = new NextResponse();
890
+ *
891
+ * res.cookies.set("last_auth_requested", `${Date.now()}`);
892
+ *
893
+ * return authHandler(req, res);
894
+ * };
895
+ * ```
896
+ *
897
+ * @example Pages Router
898
+ * ```tsx:src/pages/api/auth/[...monocloud].ts tab="Pages Router" tab-group="monoCloudAuth"
899
+ * import { monoCloudAuth } from "@monocloud/auth-nextjs";
900
+ *
901
+ * export default monoCloudAuth();
902
+ *```
903
+ *
904
+ * @example Pages Router (Response)
905
+ * ```tsx:src/pages/api/auth/[...monocloud].ts tab="Pages Router (Response)" tab-group="monoCloudAuth"
906
+ * import { monoCloudAuth } from "@monocloud/auth-nextjs";
907
+ * import { NextApiRequest, NextApiResponse } from "next";
908
+ *
909
+ * export default function handler(req: NextApiRequest, res: NextApiResponse) {
910
+ * const authHandler = monoCloudAuth();
911
+ *
912
+ * res.setHeader("last_auth_requested", `${Date.now()}`);
913
+ *
914
+ * return authHandler(req, res);
915
+ * }
916
+ * ```
917
+ *
918
+ * @param options Optional configuration for the auth handler.
919
+ * @returns Returns a Next.js-compatible handler for App Router route handlers or Pages Router API routes.
920
+ *
921
+ * @category Functions
922
+ */
923
+ function monoCloudAuth(options) {
924
+ return getInstance().monoCloudAuth(options);
925
+ }
926
+ function authMiddleware(...args) {
927
+ return getInstance().authMiddleware(...args);
928
+ }
929
+ function getSession(...args) {
930
+ return getInstance().getSession(...args);
931
+ }
932
+ function getTokens(...args) {
933
+ return getInstance().getTokens(...args);
934
+ }
935
+ function isAuthenticated(...args) {
936
+ return getInstance().isAuthenticated(...args);
937
+ }
938
+ /**
939
+ * Ensures the current user is authenticated. If not, redirects to the sign-in flow.
940
+ *
941
+ * > **App Router only.** Intended for Server Components, Route Handlers, and Server Actions.
942
+ *
943
+ * @example Server Component
944
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="protect"
945
+ * import { protect } from "@monocloud/auth-nextjs";
946
+ *
947
+ * export default async function Home() {
948
+ * await protect();
949
+ *
950
+ * return <>You are signed in.</>;
951
+ * }
952
+ * ```
953
+ *
954
+ * @example Server Action
955
+ * ```tsx:src/action.ts tab="Server Action" tab-group="protect"
956
+ * "use server";
957
+ *
958
+ * import { protect } from "@monocloud/auth-nextjs";
959
+ *
960
+ * export async function getMessage() {
961
+ * await protect();
962
+ *
963
+ * return { secret: "sssshhhhh!!!" };
964
+ * }
965
+ * ```
966
+ *
967
+ * @example API Handler
968
+ * ```tsx:src/app/api/protected/route.ts tab="API Handler" tab-group="protect"
969
+ * import { protect } from "@monocloud/auth-nextjs";
970
+ * import { NextResponse } from "next/server";
971
+ *
972
+ * export const GET = async () => {
973
+ * await protect();
974
+ *
975
+ * return NextResponse.json({ secret: "ssshhhh!!!" });
976
+ * };
977
+ * ```
978
+ *
979
+ * @param options Optional configuration for redirect behavior (for example, return URL or sign-in parameters).
980
+ * @returns Resolves if the user is authenticated; otherwise triggers a redirect.
981
+ *
982
+ * @category Functions
983
+ */
984
+ function protect(options) {
985
+ return getInstance().protect(options);
986
+ }
987
+ function protectApi(handler, options) {
988
+ return getInstance().protectApi(handler, options);
989
+ }
990
+ function protectPage(...args) {
991
+ return getInstance().protectPage(...args);
992
+ }
993
+ function isUserInGroup(...args) {
994
+ return getInstance().isUserInGroup(...args);
995
+ }
996
+ /**
997
+ * Redirects the user to the sign-in flow.
998
+ *
999
+ * > **App Router only**. Intended for use in Server Components, Route Handlers, and Server Actions.
1000
+ *
1001
+ * This helper performs a server-side redirect to the configured sign-in route. Execution does not continue after the redirect is triggered.
1002
+ *
1003
+ * @example Server Component
1004
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="redirect-to-sign-in"
1005
+ * import { isUserInGroup, redirectToSignIn } from "@monocloud/auth-nextjs";
1006
+ *
1007
+ * export default async function Home() {
1008
+ * const allowed = await isUserInGroup(["admin"]);
1009
+ *
1010
+ * if (!allowed) {
1011
+ * await redirectToSignIn({ returnUrl: "/home" });
1012
+ * }
1013
+ *
1014
+ * return <>You are signed in.</>;
1015
+ * }
1016
+ * ```
1017
+ *
1018
+ * @example Server Action
1019
+ * ```tsx:src/action.ts tab="Server Action" tab-group="redirect-to-sign-in"
1020
+ * "use server";
1021
+ *
1022
+ * import { getSession, redirectToSignIn } from "@monocloud/auth-nextjs";
1023
+ *
1024
+ * export async function protectedAction() {
1025
+ * const session = await getSession();
1026
+ *
1027
+ * if (!session) {
1028
+ * await redirectToSignIn();
1029
+ * }
1030
+ *
1031
+ * return { data: "Sensitive Data" };
1032
+ * }
1033
+ * ```
1034
+ *
1035
+ * @example API Handler
1036
+ * ```tsx:src/app/api/protected/route.ts tab="API Handler" tab-group="redirect-to-sign-in"
1037
+ * import { getSession, redirectToSignIn } from "@monocloud/auth-nextjs";
1038
+ * import { NextResponse } from "next/server";
1039
+ *
1040
+ * export const GET = async () => {
1041
+ * const session = await getSession();
1042
+ *
1043
+ * if (!session) {
1044
+ * await redirectToSignIn({
1045
+ * returnUrl: "/dashboard",
1046
+ * });
1047
+ * }
1048
+ *
1049
+ * return NextResponse.json({ data: "Protected content" });
1050
+ * };
1051
+ * ```
1052
+ *
1053
+ * @param options Optional configuration for the redirect, such as `returnUrl` or additional sign-in parameters.
1054
+ * @returns Never resolves. Triggers a redirect to the sign-in flow.
1055
+ *
1056
+ * @category Functions
1057
+ */
1058
+ function redirectToSignIn(options) {
1059
+ return getInstance().redirectToSignIn(options);
1060
+ }
1061
+ /**
1062
+ * Redirects the user to the sign-out flow.
1063
+ *
1064
+ * > **App Router only**. Intended for use in Server Components, Route Handlers, and Server Actions.
1065
+ *
1066
+ * This helper performs a server-side redirect to the configured sign-out route. Execution does not continue after the redirect is triggered.
1067
+ *
1068
+ * @example Server Component
1069
+ * ```tsx:src/app/page.tsx tab="Server Component" tab-group="redirect-to-sign-out"
1070
+ * import { getSession, redirectToSignOut } from "@monocloud/auth-nextjs";
1071
+ *
1072
+ * export default async function Page() {
1073
+ * const session = await getSession();
1074
+ *
1075
+ * // Example: Force sign-out if a specific condition is met (e.g., account suspended)
1076
+ * if (session?.user.isSuspended) {
1077
+ * await redirectToSignOut();
1078
+ * }
1079
+ *
1080
+ * return <>Welcome User</>;
1081
+ * }
1082
+ * ```
1083
+ *
1084
+ * @example Server Action
1085
+ * ```tsx:src/action.ts tab="Server Action" tab-group="redirect-to-sign-out"
1086
+ * "use server";
1087
+ *
1088
+ * import { getSession, redirectToSignOut } from "@monocloud/auth-nextjs";
1089
+ *
1090
+ * export async function signOutAction() {
1091
+ * const session = await getSession();
1092
+ *
1093
+ * if (session) {
1094
+ * await redirectToSignOut();
1095
+ * }
1096
+ * }
1097
+ * ```
1098
+ *
1099
+ * @example API Handler
1100
+ * ```tsx:src/app/api/signout/route.ts tab="API Handler" tab-group="redirect-to-sign-out"
1101
+ * import { getSession, redirectToSignOut } from "@monocloud/auth-nextjs";
1102
+ * import { NextResponse } from "next/server";
1103
+ *
1104
+ * export const GET = async () => {
1105
+ * const session = await getSession();
1106
+ *
1107
+ * if (session) {
1108
+ * await redirectToSignOut({
1109
+ * postLogoutRedirectUri: "/goodbye",
1110
+ * });
1111
+ * }
1112
+ *
1113
+ * return NextResponse.json({ status: "already_signed_out" });
1114
+ * };
1115
+ * ```
1116
+ *
1117
+ * @param options Optional configuration for the redirect, such as `postLogoutRedirectUri` or additional sign-out parameters.
1118
+ * @returns Never resolves. Triggers a redirect to the sign-out flow.
1119
+ *
1120
+ * @category Functions
1121
+ */
1122
+ function redirectToSignOut(options) {
1123
+ return getInstance().redirectToSignOut(options);
1124
+ }
1125
+
1112
1126
  //#endregion
1113
1127
  Object.defineProperty(exports, 'MonoCloudAuthBaseError', {
1114
1128
  enumerable: true,
@@ -1141,4 +1155,15 @@ Object.defineProperty(exports, 'MonoCloudValidationError', {
1141
1155
  return _monocloud_auth_node_core.MonoCloudValidationError;
1142
1156
  }
1143
1157
  });
1158
+ exports.authMiddleware = authMiddleware;
1159
+ exports.getSession = getSession;
1160
+ exports.getTokens = getTokens;
1161
+ exports.isAuthenticated = isAuthenticated;
1162
+ exports.isUserInGroup = isUserInGroup;
1163
+ exports.monoCloudAuth = monoCloudAuth;
1164
+ exports.protect = protect;
1165
+ exports.protectApi = protectApi;
1166
+ exports.protectPage = protectPage;
1167
+ exports.redirectToSignIn = redirectToSignIn;
1168
+ exports.redirectToSignOut = redirectToSignOut;
1144
1169
  //# sourceMappingURL=index.cjs.map