@monocloud/auth-nextjs 0.1.6 → 0.1.8

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
@@ -286,35 +286,32 @@ const mergeResponse = (responses) => {
286
286
  //#endregion
287
287
  //#region src/monocloud-next-client.ts
288
288
  /**
289
- * The MonoCloud Next.js Client.
289
+ * `MonoCloudNextClient` is the core SDK entry point for integrating MonoCloud authentication into a Next.js application.
290
290
  *
291
- * @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
292
297
  *
293
- * 1. Add following variables to your `.env`.
298
+ * ## 1. Add environment variables
294
299
  *
295
- * ```bash
300
+ * ```bash:.env.local
296
301
  * MONOCLOUD_AUTH_TENANT_DOMAIN=<tenant-domain>
297
302
  * MONOCLOUD_AUTH_CLIENT_ID=<client-id>
298
303
  * MONOCLOUD_AUTH_CLIENT_SECRET=<client-secret>
299
- * MONOCLOUD_AUTH_SCOPES=openid profile email # Default
304
+ * MONOCLOUD_AUTH_SCOPES=openid profile email
300
305
  * MONOCLOUD_AUTH_APP_URL=http://localhost:3000
301
306
  * MONOCLOUD_AUTH_COOKIE_SECRET=<cookie-secret>
302
307
  * ```
303
308
  *
304
- * 2. Instantiate the client in a shared file (e.g., lib/monocloud.ts)
309
+ * ## 2. Register middleware
305
310
  *
306
- * ```typescript
307
- * import { MonoCloudNextClient } from '@monocloud/auth-nextjs';
311
+ * ```typescript:src/proxy.ts
312
+ * import { authMiddleware } from "@monocloud/auth-nextjs";
308
313
  *
309
- * export const monoCloud = new MonoCloudNextClient();
310
- * ```
311
- *
312
- * 3. Add MonoCloud middleware/proxy
313
- *
314
- * ```typescript
315
- * import { monoCloud } from "@/lib/monocloud";
316
- *
317
- * export default monoCloud.authMiddleware();
314
+ * export default authMiddleware();
318
315
  *
319
316
  * export const config = {
320
317
  * matcher: [
@@ -323,218 +320,115 @@ const mergeResponse = (responses) => {
323
320
  * };
324
321
  * ```
325
322
  *
326
- * @example Using Constructor Options
323
+ * ## Advanced usage
324
+ *
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
+ * ```
336
+ *
337
+ * ### Using instance methods
327
338
  *
328
- * ⚠️ Security Note: Never commit your credentials to version control. Load them from environment variables.
339
+ * Once you create a client instance, call methods directly on it instead of using the default function exports.
329
340
  *
330
- * 1. Instantiate the client in a shared file (e.g., lib/monocloud.ts)
341
+ * ```ts:src/app/page.tsx
342
+ * import { monoCloud } from "@/monocloud";
331
343
  *
332
- * ```typescript
333
- * import { MonoCloudNextClient } from '@monocloud/auth-nextjs';
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";
334
361
  *
335
362
  * export const monoCloud = new MonoCloudNextClient({
336
- * tenantDomain: '<tenant-domain>',
337
- * clientId: '<client-id>',
338
- * clientSecret: '<client-secret>',
339
- * scopes: 'openid profile email', // Default
340
- * appUrl: 'http://localhost:3000',
341
- * 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
+ * },
342
371
  * });
343
372
  * ```
344
- * 2. Add MonoCloud middleware/proxy
345
373
  *
346
- * ```typescript
347
- * import { monoCloud } from "@/lib/monocloud";
374
+ * ### Modifying default routes
348
375
  *
349
- * export default monoCloud.authMiddleware();
376
+ * If you customize any of the default auth route paths:
350
377
  *
351
- * export const config = {
352
- * matcher: [
353
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
354
- * ],
355
- * };
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
356
387
  * ```
357
388
  *
358
- * <details>
359
- * <summary>All Environment Variables</summary>
360
- * <h4>Core Configuration (Required)</h4>
361
- *
362
- * <ul>
363
- * <li><strong>MONOCLOUD_AUTH_CLIENT_ID : </strong>Unique identifier for your application/client.</li>
364
- * <li><strong>MONOCLOUD_AUTH_CLIENT_SECRET : </strong>Application/client secret.</li>
365
- * <li><strong>MONOCLOUD_AUTH_TENANT_DOMAIN : </strong>The domain of your MonoCloud tenant (e.g., https://your-tenant.us.monocloud.com).</li>
366
- * <li><strong>MONOCLOUD_AUTH_APP_URL : </strong>The base URL where your application is hosted.</li>
367
- * <li><strong>MONOCLOUD_AUTH_COOKIE_SECRET : </strong>A long, random string used to encrypt and sign session cookies.</li>
368
- * </ul>
369
- *
370
- * <h4>Authentication &amp; Security</h4>
371
- *
372
- * <ul>
373
- * <li><strong>MONOCLOUD_AUTH_SCOPES : </strong>A space-separated list of OIDC scopes to request (e.g., openid profile email).</li>
374
- * <li><strong>MONOCLOUD_AUTH_RESOURCE : </strong>The default resource/audience identifier for access tokens.</li>
375
- * <li><strong>MONOCLOUD_AUTH_USE_PAR : </strong>Enables Pushed Authorization Requests.</li>
376
- * <li><strong>MONOCLOUD_AUTH_CLOCK_SKEW : </strong>The allowed clock drift in seconds when validating token timestamps.</li>
377
- * <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>
378
- * <li><strong>MONOCLOUD_AUTH_RESPONSE_TIMEOUT : </strong>The maximum time in milliseconds to wait for a response.</li>
379
- * <li><strong>MONOCLOUD_AUTH_ALLOW_QUERY_PARAM_OVERRIDES : </strong>Allows dynamic overrides of auth parameters via URL query strings.</li>
380
- * <li><strong>MONOCLOUD_AUTH_POST_LOGOUT_REDIRECT_URI : </strong>The URL users are sent to after a successful logout.</li>
381
- * <li><strong>MONOCLOUD_AUTH_USER_INFO : </strong>Determines if user profile data from the UserInfo endpoint should be fetched after authorization code exchange.</li>
382
- * <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>
383
- * <li><strong>MONOCLOUD_AUTH_ID_TOKEN_SIGNING_ALG : </strong>The expected algorithm for signing ID tokens (e.g., RS256).</li>
384
- * <li><strong>MONOCLOUD_AUTH_FILTERED_ID_TOKEN_CLAIMS : </strong>A space-separated list of claims to exclude from the session object.</li>
385
- * </ul>
386
- *
387
- * <h4>Routes</h4>
388
- *
389
- * <aside>
390
- * <strong>⚠️ Important: Modifying Default Routes</strong>
391
- * <p>If you choose to customize any of the default route paths, you must adhere to the following requirements:</p>
392
- * <ul>
393
- * <li>
394
- * <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.
395
- * </li>
396
- * <li>
397
- * <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.
398
- * </li>
399
- * </ul>
400
- * <p><em>Example:</em></p>
401
- * <code>
402
- * MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback<br />
403
- * NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
404
- * </code>
405
- * <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>
406
- * </aside>
407
- *
408
- * <ul>
409
- * <li><strong>MONOCLOUD_AUTH_CALLBACK_URL : </strong>The application path where MonoCloud sends the user after authentication.</li>
410
- * <li><strong>MONOCLOUD_AUTH_SIGNIN_URL : </strong>The internal route path to trigger the sign-in.</li>
411
- * <li><strong>MONOCLOUD_AUTH_SIGNOUT_URL : </strong>The internal route path to trigger the sign-out.</li>
412
- * <li><strong>MONOCLOUD_AUTH_USER_INFO_URL : </strong>The route that exposes the current user's profile from userinfo endpoint.</li>
413
- * </ul>
414
- *
415
- * <h4>Session Cookie Settings</h4>
416
- *
417
- * <ul>
418
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_NAME : </strong>The name of the cookie used to store the user session.</li>
419
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_PATH : </strong>The scope path for the session cookie.</li>
420
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_DOMAIN : </strong>The domain scope for the session cookie.</li>
421
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_HTTP_ONLY : </strong>Prevents client-side scripts from accessing the session cookie.</li>
422
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_SECURE : </strong>Ensures the session cookie is only sent over HTTPS.</li>
423
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_SAME_SITE : </strong>The SameSite policy for the session cookie (Lax, Strict, or None).</li>
424
- * <li><strong>MONOCLOUD_AUTH_SESSION_COOKIE_PERSISTENT : </strong>If true, the session survives browser restarts.</li>
425
- * <li><strong>MONOCLOUD_AUTH_SESSION_SLIDING : </strong>If true, the session will be a sliding session instead of absolute.</li>
426
- * <li><strong>MONOCLOUD_AUTH_SESSION_DURATION : </strong>The session lifetime in seconds.</li>
427
- * <li><strong>MONOCLOUD_AUTH_SESSION_MAX_DURATION : </strong>The absolute maximum lifetime of a session in seconds.</li>
428
- * </ul>
429
- *
430
- * <h4>State Cookie Settings</h4>
431
- *
432
- * <ul>
433
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_NAME : </strong>The name of the cookie used to store OpenID state/nonce.</li>
434
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_PATH : </strong>The scope path for the state cookie.</li>
435
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_DOMAIN : </strong>The domain scope for the state cookie.</li>
436
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_SECURE : </strong>Ensures the state cookie is only sent over HTTPS</li>
437
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_SAME_SITE : </strong>The SameSite policy for the state cookie.</li>
438
- * <li><strong>MONOCLOUD_AUTH_STATE_COOKIE_PERSISTENT : </strong>Whether the state cookie is persistent.</li>
439
- * </ul>
440
- *
441
- * <h4>Caching</h4>
442
- *
443
- * <ul>
444
- * <li><strong>MONOCLOUD_AUTH_JWKS_CACHE_DURATION : </strong>Duration in seconds to cache the JSON Web Key Set.</li>
445
- * <li><strong>MONOCLOUD_AUTH_METADATA_CACHE_DURATION : </strong>Duration in seconds to cache the OpenID discovery metadata.</li>
446
- * </ul>
447
- * </details>
389
+ * When routes are overridden, the Redirect URI configured in the dashboard
390
+ * must reflect the new path. For example, during local development:
448
391
  *
392
+ * `http://localhost:3000/api/custom_callback`
449
393
  *
394
+ * @category Classes
450
395
  */
451
396
  var MonoCloudNextClient = class {
452
397
  /**
453
- * 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.
454
400
  *
455
- * @example
456
- * // Manually revoke an access token
457
- * await client.oidcClient.revokeToken(accessToken, 'access_token');
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.
408
+ *
409
+ * @returns Returns the underlying **OIDC client** used for OpenID Connect operations.
458
410
  */
459
411
  get oidcClient() {
460
412
  return this.coreClient.oidcClient;
461
413
  }
462
414
  /**
463
- * @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.
464
418
  */
465
419
  constructor(options) {
466
420
  const opt = {
467
421
  ...options ?? {},
468
- userAgent: (options === null || options === void 0 ? void 0 : options.userAgent) ?? `@monocloud/auth-nextjs@0.1.6`,
422
+ userAgent: (options === null || options === void 0 ? void 0 : options.userAgent) ?? `@monocloud/auth-nextjs@0.1.8`,
469
423
  debugger: (options === null || options === void 0 ? void 0 : options.debugger) ?? "@monocloud:auth-nextjs"
470
424
  };
471
425
  this.registerPublicEnvVariables();
472
- this.coreClient = new _monocloud_auth_node_core.MonoCloudCoreClient(opt);
426
+ this._coreClient = new _monocloud_auth_node_core.MonoCloudCoreClient(opt);
473
427
  }
474
428
  /**
475
- * Creates a **Next.js API route handler** (for both Pages Router and App Router)
476
- * that processes all MonoCloud authentication endpoints
477
- * (`/signin`, `/callback`, `/userinfo`, `/signout`).
478
- *
479
- * @param options Authentication configuration routes.
480
- *
481
- * **Note:** If you are already using `authMiddleware()`, you typically do **not**
482
- * need this API route handler. This function is intended for applications where
483
- * middleware cannot be used—such as statically generated (SSG) deployments that still
484
- * require server-side authentication flows.
485
- *
486
- * @example App Router
487
- *
488
- * ```typescript
489
- * // app/api/auth/[...monocloud]/route.ts
490
- *
491
- * import { monoCloud } from "@/lib/monocloud";
492
- *
493
- * export const GET = monoCloud.monoCloudAuth();
494
- *```
495
- *
496
- * @example App Router with Response
497
- *
498
- * ```typescript
499
- * import { monoCloud } from "@/lib/monocloud";
500
- * import { NextRequest, NextResponse } from "next/server";
501
- *
502
- * export const GET = (req: NextRequest) => {
503
- * const authHandler = monoCloud.monoCloudAuth();
504
- *
505
- * const res = new NextResponse();
506
- *
507
- * res.cookies.set("last_auth_requested", `${Date.now()}`);
508
- *
509
- * return authHandler(req, res);
510
- * };
511
- * ```
512
- *
513
- * @example Pages Router
514
- *
515
- * ```typescript
516
- * // pages/api/auth/[...monocloud].ts
517
- *
518
- * import { monoCloud } from "@/lib/monocloud";
519
- *
520
- * export default monoCloud.monoCloudAuth();
521
- *```
522
- *
523
- * @example Page Router with Response
524
- *
525
- * ```typescript
526
- * import { monoCloud } from "@/lib/monocloud";
527
- * import { NextApiRequest, NextApiResponse } from "next";
528
- *
529
- * export default function handler(req: NextApiRequest, res: NextApiResponse) {
530
- * const authHandler = monoCloud.monoCloudAuth();
531
- *
532
- * res.setHeader("last_auth_requested", `${Date.now()}`);
533
- *
534
- * return authHandler(req, res);
535
- * }
536
- * ```
537
- *
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.
538
432
  */
539
433
  monoCloudAuth(options) {
540
434
  return (req, resOrCtx) => {
@@ -826,52 +720,9 @@ var MonoCloudNextClient = class {
826
720
  return await this.coreClient.isAuthenticated(request, response);
827
721
  }
828
722
  /**
829
- * Redirects the user to the sign-in flow if they are not authenticated.
830
- *
831
- * **This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).**
832
- *
833
- * @param options Options to customize the sign-in.
834
- *
835
- * @returns
836
- *
837
- * @example React Server Component
838
- *
839
- * ```tsx
840
- * import { monoCloud } from "@/lib/monocloud";
841
- *
842
- * export default async function Home() {
843
- * await monoCloud.protect();
844
- *
845
- * return <>You are signed in.</>;
846
- * }
847
- * ```
848
- *
849
- * @example API Handler
850
- *
851
- * ```typescript
852
- * import { NextResponse } from "next/server";
853
- * import { monoCloud } from "@/lib/monocloud";
854
- *
855
- * export const GET = async () => {
856
- * await monoCloud.protect();
857
- *
858
- * return NextResponse.json({ secret: "ssshhhh!!!" });
859
- * };
860
- * ```
861
- *
862
- * @example Server Action
863
- *
864
- * ```typescript
865
- * "use server";
866
- *
867
- * import { monoCloud } from "@/lib/monocloud";
868
- *
869
- * export async function getMessage() {
870
- * await monoCloud.protect();
871
- *
872
- * return { secret: "sssshhhhh!!!" };
873
- * }
874
- * ```
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.
875
726
  */
876
727
  async protect(options) {
877
728
  var _options$authParams19, _options$authParams20, _options$authParams21, _options$authParams22, _options$authParams23, _options$authParams24, _options$authParams25, _options$authParams26, _options$authParams27;
@@ -880,7 +731,7 @@ var MonoCloudNextClient = class {
880
731
  try {
881
732
  const session = await this.getSession();
882
733
  if (session && !(options === null || options === void 0 ? void 0 : options.groups)) return;
883
- 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;
884
735
  const { headers } = await import("next/headers");
885
736
  path = (await headers()).get("x-monocloud-path") ?? "/";
886
737
  } catch {
@@ -945,66 +796,9 @@ var MonoCloudNextClient = class {
945
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);
946
797
  }
947
798
  /**
948
- * Redirects the user to the sign-in flow.
949
- *
950
- * **This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).**
951
- *
952
- * @param options Options to customize the sign-in.
953
- *
954
- * @returns
955
- *
956
- * @example React Server Component
957
- *
958
- * ```tsx
959
- * import { monoCloud } from "@/lib/monocloud";
960
- *
961
- * export default async function Home() {
962
- * const allowed = await monoCloud.isUserInGroup(["admin"]);
963
- *
964
- * if (!allowed) {
965
- * await monoCloud.redirectToSignIn({ returnUrl: "/home" });
966
- * }
967
- *
968
- * return <>You are signed in.</>;
969
- * }
970
- * ```
971
- *
972
- * @example Server Action
973
- *
974
- * ```typescript
975
- * "use server";
976
- *
977
- * import { monoCloud } from "@/lib/monocloud";
978
- *
979
- * export async function protectedAction() {
980
- * const session = await monoCloud.getSession();
981
- *
982
- * if (!session) {
983
- * await monoCloud.redirectToSignIn();
984
- * }
985
- *
986
- * return { data: "Sensitive Data" };
987
- * }
988
- * ```
989
- *
990
- * @example API Handler
991
- *
992
- * ```typescript
993
- * import { NextResponse } from "next/server";
994
- * import { monoCloud } from "@/lib/monocloud";
995
- *
996
- * export const GET = async () => {
997
- * const session = await monoCloud.getSession();
998
- *
999
- * if (!session) {
1000
- * await monoCloud.redirectToSignIn({
1001
- * returnUrl: "/dashboard",
1002
- * });
1003
- * }
1004
- *
1005
- * return NextResponse.json({ data: "Protected content" });
1006
- * };
1007
- * ```
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.
1008
802
  */
1009
803
  async redirectToSignIn(options) {
1010
804
  const { routes, appUrl } = this.coreClient.getOptions();
@@ -1018,8 +812,8 @@ var MonoCloudNextClient = class {
1018
812
  if (options === null || options === void 0 ? void 0 : options.returnUrl) signInRoute.searchParams.set("return_url", options.returnUrl);
1019
813
  if (options === null || options === void 0 ? void 0 : options.maxAge) signInRoute.searchParams.set("max_age", options.maxAge.toString());
1020
814
  if (options === null || options === void 0 ? void 0 : options.authenticatorHint) signInRoute.searchParams.set("authenticator_hint", options.authenticatorHint);
1021
- if (Array.isArray(options === null || options === void 0 ? void 0 : options.scopes)) signInRoute.searchParams.set("scope", options.scopes.join(" "));
1022
- if (Array.isArray(options === null || options === void 0 ? void 0 : options.resource)) signInRoute.searchParams.set("resource", options.resource.join(" "));
815
+ if (options === null || options === void 0 ? void 0 : options.scopes) signInRoute.searchParams.set("scope", options.scopes);
816
+ if (options === null || options === void 0 ? void 0 : options.resource) signInRoute.searchParams.set("resource", options.resource);
1023
817
  if (options === null || options === void 0 ? void 0 : options.display) signInRoute.searchParams.set("display", options.display);
1024
818
  if (options === null || options === void 0 ? void 0 : options.uiLocales) signInRoute.searchParams.set("ui_locales", options.uiLocales);
1025
819
  if (Array.isArray(options === null || options === void 0 ? void 0 : options.acrValues)) signInRoute.searchParams.set("acr_values", options.acrValues.join(" "));
@@ -1029,65 +823,9 @@ var MonoCloudNextClient = class {
1029
823
  redirect(signInRoute.toString());
1030
824
  }
1031
825
  /**
1032
- * Redirects the user to the sign-out flow.
1033
- *
1034
- * **This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).**
1035
- *
1036
- * @param options Options to customize the sign out.
1037
- *
1038
- * @returns
1039
- *
1040
- * @example React Server Component
1041
- *
1042
- * ```tsx
1043
- * import { monoCloud } from "@/lib/monocloud";
1044
- *
1045
- * export default async function Page() {
1046
- * const session = await monoCloud.getSession();
1047
- *
1048
- * // Example: Force sign-out if a specific condition is met (e.g., account suspended)
1049
- * if (session?.user.isSuspended) {
1050
- * await monoCloud.redirectToSignOut();
1051
- * }
1052
- *
1053
- * return <>Welcome User</>;
1054
- * }
1055
- * ```
1056
- *
1057
- * @example Server Action
1058
- *
1059
- * ```typescript
1060
- * "use server";
1061
- *
1062
- * import { monoCloud } from "@/lib/monocloud";
1063
- *
1064
- * export async function signOutAction() {
1065
- * const session = await monoCloud.getSession();
1066
- *
1067
- * if (session) {
1068
- * await monoCloud.redirectToSignOut();
1069
- * }
1070
- * }
1071
- * ```
1072
- *
1073
- * @example API Handler
1074
- *
1075
- * ```typescript
1076
- * import { monoCloud } from "@/lib/monocloud";
1077
- * import { NextResponse } from "next/server";
1078
- *
1079
- * export const GET = async () => {
1080
- * const session = await monoCloud.getSession();
1081
- *
1082
- * if (session) {
1083
- * await monoCloud.redirectToSignOut({
1084
- * postLogoutRedirectUri: "/goodbye",
1085
- * });
1086
- * }
1087
- *
1088
- * return NextResponse.json({ status: "already_signed_out" });
1089
- * };
1090
- * ```
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.
1091
829
  */
1092
830
  async redirectToSignOut(options) {
1093
831
  var _options$postLogoutRe;
@@ -1115,6 +853,276 @@ var MonoCloudNextClient = class {
1115
853
  }
1116
854
  };
1117
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
+
1118
1126
  //#endregion
1119
1127
  Object.defineProperty(exports, 'MonoCloudAuthBaseError', {
1120
1128
  enumerable: true,
@@ -1147,4 +1155,15 @@ Object.defineProperty(exports, 'MonoCloudValidationError', {
1147
1155
  return _monocloud_auth_node_core.MonoCloudValidationError;
1148
1156
  }
1149
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;
1150
1169
  //# sourceMappingURL=index.cjs.map