@monocloud/auth-nextjs 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +1 -1
  2. package/dist/{chunk-C0xms8kb.cjs → _virtual/_rolldown/runtime.cjs} +1 -6
  3. package/dist/client/index.cjs +3 -2
  4. package/dist/client/index.d.mts +3 -203
  5. package/dist/client/index.mjs +2 -1
  6. package/dist/{protect-client-page-BdsnH8gs.cjs → client/protect-client-page.cjs} +9 -112
  7. package/dist/client/protect-client-page.cjs.map +1 -0
  8. package/dist/client/protect-client-page.d.mts +123 -0
  9. package/dist/{protect-client-page-BFVskb3X.mjs → client/protect-client-page.mjs} +5 -91
  10. package/dist/client/protect-client-page.mjs.map +1 -0
  11. package/dist/client/use-auth.cjs +96 -0
  12. package/dist/client/use-auth.cjs.map +1 -0
  13. package/dist/client/use-auth.d.mts +84 -0
  14. package/dist/client/use-auth.mjs +94 -0
  15. package/dist/client/use-auth.mjs.map +1 -0
  16. package/dist/components/client/index.cjs +4 -156
  17. package/dist/components/client/index.d.mts +3 -189
  18. package/dist/components/client/index.mjs +3 -153
  19. package/dist/components/client/protected.cjs +89 -0
  20. package/dist/components/client/protected.cjs.map +1 -0
  21. package/dist/components/client/protected.d.mts +114 -0
  22. package/dist/components/client/protected.mjs +87 -0
  23. package/dist/components/client/protected.mjs.map +1 -0
  24. package/dist/components/client/redirect-to-signin.cjs +77 -0
  25. package/dist/components/client/redirect-to-signin.cjs.map +1 -0
  26. package/dist/components/client/redirect-to-signin.d.mts +78 -0
  27. package/dist/components/client/redirect-to-signin.mjs +76 -0
  28. package/dist/components/client/redirect-to-signin.mjs.map +1 -0
  29. package/dist/components/index.cjs +6 -168
  30. package/dist/components/index.d.mts +4 -188
  31. package/dist/components/index.mjs +4 -164
  32. package/dist/components/signin.cjs +63 -0
  33. package/dist/components/signin.cjs.map +1 -0
  34. package/dist/components/signin.d.mts +72 -0
  35. package/dist/components/signin.mjs +61 -0
  36. package/dist/components/signin.mjs.map +1 -0
  37. package/dist/components/signout.cjs +49 -0
  38. package/dist/components/signout.cjs.map +1 -0
  39. package/dist/components/signout.d.mts +55 -0
  40. package/dist/components/signout.mjs +47 -0
  41. package/dist/components/signout.mjs.map +1 -0
  42. package/dist/components/signup.cjs +67 -0
  43. package/dist/components/signup.cjs.map +1 -0
  44. package/dist/components/signup.d.mts +70 -0
  45. package/dist/components/signup.mjs +65 -0
  46. package/dist/components/signup.mjs.map +1 -0
  47. package/dist/index.cjs +15 -1136
  48. package/dist/index.d.mts +5 -1681
  49. package/dist/index.mjs +4 -1125
  50. package/dist/initialize.cjs +284 -0
  51. package/dist/initialize.cjs.map +1 -0
  52. package/dist/initialize.d.mts +1383 -0
  53. package/dist/initialize.mjs +274 -0
  54. package/dist/initialize.mjs.map +1 -0
  55. package/dist/monocloud-next-client.cjs +600 -0
  56. package/dist/monocloud-next-client.cjs.map +1 -0
  57. package/dist/monocloud-next-client.d.mts +330 -0
  58. package/dist/monocloud-next-client.mjs +599 -0
  59. package/dist/monocloud-next-client.mjs.map +1 -0
  60. package/dist/requests/monocloud-app-router-request.cjs +32 -0
  61. package/dist/requests/monocloud-app-router-request.cjs.map +1 -0
  62. package/dist/requests/monocloud-app-router-request.mjs +31 -0
  63. package/dist/requests/monocloud-app-router-request.mjs.map +1 -0
  64. package/dist/requests/monocloud-cookie-request.cjs +22 -0
  65. package/dist/requests/monocloud-cookie-request.cjs.map +1 -0
  66. package/dist/requests/monocloud-cookie-request.mjs +21 -0
  67. package/dist/requests/monocloud-cookie-request.mjs.map +1 -0
  68. package/dist/requests/monocloud-page-router-request.cjs +37 -0
  69. package/dist/requests/monocloud-page-router-request.cjs.map +1 -0
  70. package/dist/requests/monocloud-page-router-request.mjs +36 -0
  71. package/dist/requests/monocloud-page-router-request.mjs.map +1 -0
  72. package/dist/responses/monocloud-app-router-response.cjs +67 -0
  73. package/dist/responses/monocloud-app-router-response.cjs.map +1 -0
  74. package/dist/responses/monocloud-app-router-response.mjs +66 -0
  75. package/dist/responses/monocloud-app-router-response.mjs.map +1 -0
  76. package/dist/responses/monocloud-cookie-response.cjs +20 -0
  77. package/dist/responses/monocloud-cookie-response.cjs.map +1 -0
  78. package/dist/responses/monocloud-cookie-response.mjs +19 -0
  79. package/dist/responses/monocloud-cookie-response.mjs.map +1 -0
  80. package/dist/responses/monocloud-page-router-response.cjs +54 -0
  81. package/dist/responses/monocloud-page-router-response.cjs.map +1 -0
  82. package/dist/responses/monocloud-page-router-response.mjs +53 -0
  83. package/dist/responses/monocloud-page-router-response.mjs.map +1 -0
  84. package/dist/{types-ClljFIvK.d.mts → types.d.mts} +2 -2
  85. package/dist/utils.cjs +89 -0
  86. package/dist/utils.cjs.map +1 -0
  87. package/dist/utils.mjs +80 -0
  88. package/dist/utils.mjs.map +1 -0
  89. package/package.json +3 -3
  90. package/dist/components/client/index.cjs.map +0 -1
  91. package/dist/components/client/index.mjs.map +0 -1
  92. package/dist/components/index.cjs.map +0 -1
  93. package/dist/components/index.mjs.map +0 -1
  94. package/dist/index.cjs.map +0 -1
  95. package/dist/index.mjs.map +0 -1
  96. package/dist/protect-client-page-BFVskb3X.mjs.map +0 -1
  97. package/dist/protect-client-page-BdsnH8gs.cjs.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,1129 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_chunk = require('./chunk-C0xms8kb.cjs');
2
+ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
+ const require_monocloud_next_client = require('./monocloud-next-client.cjs');
4
+ const require_initialize = require('./initialize.cjs');
3
5
  let _monocloud_auth_node_core = require("@monocloud/auth-node-core");
4
- let next_server_js = require("next/server.js");
5
- let _monocloud_auth_node_core_internal = require("@monocloud/auth-node-core/internal");
6
- let _monocloud_auth_node_core_utils = require("@monocloud/auth-node-core/utils");
7
- let cookie = require("cookie");
8
6
 
9
- //#region src/requests/monocloud-app-router-request.ts
10
- var MonoCloudAppRouterRequest = class {
11
- constructor(req) {
12
- this.req = req;
13
- }
14
- getQuery(parameter) {
15
- return new URL(this.req.url).searchParams.get(parameter) ?? void 0;
16
- }
17
- getCookie(name) {
18
- var _this$req$cookies$get;
19
- return Promise.resolve((_this$req$cookies$get = this.req.cookies.get(name)) === null || _this$req$cookies$get === void 0 ? void 0 : _this$req$cookies$get.value);
20
- }
21
- async getRawRequest() {
22
- return {
23
- method: this.req.method,
24
- url: this.req.url,
25
- body: await this.req.text()
26
- };
27
- }
28
- getAllCookies() {
29
- const values = /* @__PURE__ */ new Map();
30
- this.req.cookies.getAll().forEach((x) => {
31
- values.set(x.name, x.value);
32
- });
33
- return Promise.resolve(values);
34
- }
35
- };
36
-
37
- //#endregion
38
- //#region src/requests/monocloud-page-router-request.ts
39
- var MonoCloudPageRouterRequest = class {
40
- constructor(req) {
41
- this.req = req;
42
- }
43
- /* v8 ignore next */
44
- getQuery(parameter) {
45
- return this.req.query[parameter];
46
- }
47
- /* v8 ignore next */
48
- getCookie(name) {
49
- return Promise.resolve(this.req.cookies[name]);
50
- }
51
- /* v8 ignore next */
52
- getRawRequest() {
53
- return Promise.resolve({
54
- method: this.req.method,
55
- url: this.req.url,
56
- body: this.req.body
57
- });
58
- }
59
- getAllCookies() {
60
- const values = /* @__PURE__ */ new Map();
61
- const { cookies } = this.req;
62
- Object.keys(cookies).forEach((x) => {
63
- const val = cookies[x];
64
- /* v8 ignore else -- @preserve */
65
- if (typeof x === "string" && typeof val === "string") values.set(x, val);
66
- });
67
- return Promise.resolve(values);
68
- }
69
- };
70
-
71
- //#endregion
72
- //#region src/responses/monocloud-app-router-response.ts
73
- var MonoCloudAppRouterResponse = class {
74
- constructor(res) {
75
- this.res = res;
76
- }
77
- setCookie(cookieName, value, options) {
78
- this.res.cookies.set(cookieName, value, options);
79
- return Promise.resolve();
80
- }
81
- redirect(url, statusCode = 302) {
82
- const { headers } = this.res;
83
- this.res = next_server_js.NextResponse.redirect(url, {
84
- status: statusCode,
85
- headers
86
- });
87
- }
88
- sendJson(data, statusCode) {
89
- const { headers } = this.res;
90
- this.res = next_server_js.NextResponse.json(data, {
91
- status: statusCode,
92
- headers
93
- });
94
- }
95
- /* v8 ignore next */
96
- notFound() {
97
- const { headers } = this.res;
98
- this.res = new next_server_js.NextResponse(null, {
99
- status: 404,
100
- headers
101
- });
102
- }
103
- internalServerError() {
104
- const { headers } = this.res;
105
- this.res = new next_server_js.NextResponse(null, {
106
- status: 500,
107
- headers
108
- });
109
- }
110
- noContent() {
111
- const { headers } = this.res;
112
- this.res = new next_server_js.NextResponse(null, {
113
- status: 204,
114
- headers
115
- });
116
- }
117
- methodNotAllowed() {
118
- const { headers } = this.res;
119
- this.res = new next_server_js.NextResponse(null, {
120
- status: 405,
121
- headers
122
- });
123
- }
124
- setNoCache() {
125
- this.res.headers.set("Cache-Control", "no-cache no-store");
126
- this.res.headers.set("Pragma", "no-cache");
127
- }
128
- done() {
129
- return this.res;
130
- }
131
- };
132
-
133
- //#endregion
134
- //#region src/responses/monocloud-page-router-response.ts
135
- var MonoCloudPageRouterResponse = class {
136
- constructor(res) {
137
- this.res = res;
138
- }
139
- setCookie(cookieName, value, options) {
140
- let cookies = this.res.getHeader("Set-Cookie") ?? [];
141
- /* v8 ignore if -- @preserve */
142
- if (!Array.isArray(cookies)) cookies = [cookies];
143
- this.res.setHeader("Set-Cookie", [...cookies.filter((cookie$1) => !cookie$1.startsWith(`${cookieName}=`)), (0, cookie.serialize)(cookieName, value, options)]);
144
- return Promise.resolve();
145
- }
146
- /* v8 ignore next */
147
- redirect(url, statusCode) {
148
- this.res.redirect(statusCode ?? 302, url);
149
- }
150
- /* v8 ignore next */
151
- sendJson(data, statusCode) {
152
- this.res.status(statusCode ?? 200);
153
- this.res.json(data);
154
- }
155
- /* v8 ignore next */
156
- notFound() {
157
- this.res.status(404);
158
- }
159
- /* v8 ignore next */
160
- internalServerError() {
161
- this.res.status(500);
162
- }
163
- /* v8 ignore next */
164
- noContent() {
165
- this.res.status(204);
166
- }
167
- /* v8 ignore next */
168
- methodNotAllowed() {
169
- this.res.status(405);
170
- }
171
- /* v8 ignore next */
172
- setNoCache() {
173
- this.res.setHeader("Cache-Control", "no-cache no-store");
174
- this.res.setHeader("Pragma", "no-cache");
175
- }
176
- /* v8 ignore next */
177
- done() {
178
- this.res.end();
179
- }
180
- };
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
-
218
- //#endregion
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;
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
- };
229
- const getNextRequest = (req) => {
230
- if (req instanceof next_server_js.NextRequest) return req;
231
- return new next_server_js.NextRequest(req.url, {
232
- method: req.method,
233
- headers: req.headers,
234
- body: req.body,
235
- duplex: req.duplex ?? "half"
236
- });
237
- };
238
- const getNextResponse = (res) => {
239
- if (res instanceof next_server_js.NextResponse) return res;
240
- if (res instanceof Response) {
241
- const nextResponse = new next_server_js.NextResponse(res.body, {
242
- status: res.status,
243
- statusText: res.statusText,
244
- headers: res.headers,
245
- url: res.url
246
- });
247
- try {
248
- /* v8 ignore else -- @preserve */
249
- if (!(0, _monocloud_auth_node_core_internal.isPresent)(nextResponse.url)) nextResponse.url = res.url;
250
- } catch {}
251
- return nextResponse;
252
- }
253
- return new next_server_js.NextResponse();
254
- };
255
- const getMonoCloudCookieReqRes = (req, resOrCtx) => {
256
- let request;
257
- let response;
258
- if (isAppRouter(req)) {
259
- request = new MonoCloudAppRouterRequest(getNextRequest(req));
260
- response = resOrCtx instanceof Response ? new MonoCloudAppRouterResponse(getNextResponse(resOrCtx)) : new MonoCloudCookieResponse();
261
- } else {
262
- if (!isNodeRequest(req) || !isNodeResponse(resOrCtx)) throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid pages router request and response");
263
- request = new MonoCloudPageRouterRequest(req);
264
- response = new MonoCloudPageRouterResponse(resOrCtx);
265
- }
266
- return {
267
- request,
268
- response
269
- };
270
- };
271
- const mergeResponse = (responses) => {
272
- const resp = responses.pop();
273
- if (!resp) return new next_server_js.NextResponse();
274
- responses.forEach((response) => {
275
- response.headers.forEach((v, k) => {
276
- if (k === "location" && !resp.headers.has(k) || k !== "location") resp.headers.set(k, v);
277
- });
278
- response.cookies.getAll().forEach((c) => {
279
- const { name, value, ...cookieOpt } = c;
280
- resp.cookies.set(name, value, cookieOpt);
281
- });
282
- });
283
- return resp;
284
- };
285
-
286
- //#endregion
287
- //#region src/monocloud-next-client.ts
288
- /**
289
- * `MonoCloudNextClient` is the core SDK entry point for integrating MonoCloud authentication into a Next.js application.
290
- *
291
- * It provides:
292
- * - Authentication middleware
293
- * - Route protection helpers
294
- * - Session and token access
295
- * - Redirect utilities
296
- * - Server-side enforcement helpers
297
- *
298
- * ## 1. Add environment variables
299
- *
300
- * ```bash:.env.local
301
- * MONOCLOUD_AUTH_TENANT_DOMAIN=<tenant-domain>
302
- * MONOCLOUD_AUTH_CLIENT_ID=<client-id>
303
- * MONOCLOUD_AUTH_CLIENT_SECRET=<client-secret>
304
- * MONOCLOUD_AUTH_SCOPES=openid profile email
305
- * MONOCLOUD_AUTH_APP_URL=http://localhost:3000
306
- * MONOCLOUD_AUTH_COOKIE_SECRET=<cookie-secret>
307
- * ```
308
- *
309
- * ## 2. Register middleware
310
- *
311
- * ```typescript:src/proxy.ts
312
- * import { authMiddleware } from "@monocloud/auth-nextjs";
313
- *
314
- * export default authMiddleware();
315
- *
316
- * export const config = {
317
- * matcher: [
318
- * "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
319
- * ],
320
- * };
321
- * ```
322
- *
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
338
- *
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";
361
- *
362
- * export const monoCloud = new MonoCloudNextClient({
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
- * },
371
- * });
372
- * ```
373
- *
374
- * ### Modifying default routes
375
- *
376
- * If you customize any of the default auth route paths:
377
- *
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
387
- * ```
388
- *
389
- * When routes are overridden, the Redirect URI configured in the dashboard
390
- * must reflect the new path. For example, during local development:
391
- *
392
- * `http://localhost:3000/api/custom_callback`
393
- *
394
- * @category Classes
395
- */
396
- var MonoCloudNextClient = class {
397
- /**
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.
408
- *
409
- * @returns Returns the underlying **OIDC client** used for OpenID Connect operations.
410
- */
411
- get oidcClient() {
412
- return this.coreClient.oidcClient;
413
- }
414
- /**
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.
418
- */
419
- constructor(options) {
420
- const opt = {
421
- ...options ?? {},
422
- userAgent: (options === null || options === void 0 ? void 0 : options.userAgent) ?? `@monocloud/auth-nextjs@0.1.9`,
423
- debugger: (options === null || options === void 0 ? void 0 : options.debugger) ?? "@monocloud:auth-nextjs"
424
- };
425
- this.registerPublicEnvVariables();
426
- this._coreClient = new _monocloud_auth_node_core.MonoCloudCoreClient(opt);
427
- }
428
- /**
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.
432
- */
433
- monoCloudAuth(options) {
434
- return (req, resOrCtx) => {
435
- const { routes, appUrl } = this.getOptions();
436
- let { url = "" } = req;
437
- if (!(0, _monocloud_auth_node_core_internal.isAbsoluteUrl)(url)) url = new URL(url, appUrl).toString();
438
- const route = new URL(url);
439
- let onError;
440
- if (typeof (options === null || options === void 0 ? void 0 : options.onError) === "function") onError = (error) => options.onError(req, resOrCtx, error);
441
- let request;
442
- let response;
443
- if (isAppRouter(req)) {
444
- request = new MonoCloudAppRouterRequest(getNextRequest(req));
445
- response = new MonoCloudAppRouterResponse(getNextResponse(resOrCtx));
446
- } else {
447
- request = new MonoCloudPageRouterRequest(req);
448
- response = new MonoCloudPageRouterResponse(resOrCtx);
449
- }
450
- return this.handleAuthRoutes(request, response, route.pathname, routes, onError);
451
- };
452
- }
453
- protectPage(...args) {
454
- if (typeof args[0] === "function") return this.protectAppPage(args[0], args[1]);
455
- return this.protectPagePage(args[0]);
456
- }
457
- protectAppPage(component, options) {
458
- return async (params) => {
459
- const session = await this.getSession();
460
- if (!session) {
461
- var _options$authParams, _options$authParams2, _options$authParams3, _options$authParams4, _options$authParams5, _options$authParams6, _options$authParams7, _options$authParams8, _options$authParams9;
462
- if (options === null || options === void 0 ? void 0 : options.onAccessDenied) return options.onAccessDenied({ ...params });
463
- const { routes, appUrl } = this.getOptions();
464
- const { headers } = await import("next/headers");
465
- const path = (await headers()).get("x-monocloud-path");
466
- const signInRoute = new URL(`${appUrl}${(0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn)}`);
467
- signInRoute.searchParams.set("return_url", (options === null || options === void 0 ? void 0 : options.returnUrl) ?? path ?? "/");
468
- 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);
469
- 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);
470
- 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(" "));
471
- 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);
472
- 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);
473
- 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);
474
- 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);
475
- 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());
476
- 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);
477
- const { redirect } = await import("next/navigation");
478
- return redirect(signInRoute.toString());
479
- }
480
- 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)) {
481
- if (options.onGroupAccessDenied) return options.onGroupAccessDenied({
482
- ...params,
483
- user: session.user
484
- });
485
- return "Access Denied";
486
- }
487
- return component({
488
- ...params,
489
- user: session.user
490
- });
491
- };
492
- }
493
- protectPagePage(options) {
494
- return async (context) => {
495
- const session = await this.getSession(context.req, context.res);
496
- if (!session) {
497
- var _options$authParams10, _options$authParams11, _options$authParams12, _options$authParams13, _options$authParams14, _options$authParams15, _options$authParams16, _options$authParams17, _options$authParams18;
498
- if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
499
- const customProps = await options.onAccessDenied({ ...context });
500
- return {
501
- ...customProps ?? {},
502
- props: { ...(customProps === null || customProps === void 0 ? void 0 : customProps.props) ?? {} }
503
- };
504
- }
505
- const { routes, appUrl } = this.getOptions();
506
- const signInRoute = new URL(`${appUrl}${(0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn)}`);
507
- signInRoute.searchParams.set("return_url", (options === null || options === void 0 ? void 0 : options.returnUrl) ?? context.resolvedUrl);
508
- 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);
509
- 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);
510
- 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(" "));
511
- 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);
512
- 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);
513
- 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);
514
- 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);
515
- 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());
516
- 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);
517
- return { redirect: {
518
- destination: signInRoute.toString(),
519
- permanent: false
520
- } };
521
- }
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)) {
523
- var _options$onGroupAcces;
524
- const customProps = await ((_options$onGroupAcces = options.onGroupAccessDenied) === null || _options$onGroupAcces === void 0 ? void 0 : _options$onGroupAcces.call(options, {
525
- ...context,
526
- user: session.user
527
- })) ?? { props: { groupAccessDenied: true } };
528
- return {
529
- ...customProps,
530
- props: { ...customProps.props ?? {} }
531
- };
532
- }
533
- const customProps = (options === null || options === void 0 ? void 0 : options.getServerSideProps) ? await options.getServerSideProps(context) : {};
534
- const promiseProp = customProps.props;
535
- if (promiseProp instanceof Promise) return {
536
- ...customProps,
537
- props: promiseProp.then((props) => ({
538
- user: session.user,
539
- ...props
540
- }))
541
- };
542
- return {
543
- ...customProps,
544
- props: {
545
- user: session.user,
546
- ...customProps.props
547
- }
548
- };
549
- };
550
- }
551
- protectApi(handler, options) {
552
- return (req, resOrCtx) => {
553
- if (isAppRouter(req)) return this.protectAppApi(req, resOrCtx, handler, options);
554
- return this.protectPageApi(req, resOrCtx, handler, options);
555
- };
556
- }
557
- async protectAppApi(req, ctx, handler, options) {
558
- const res = new next_server_js.NextResponse();
559
- const session = await this.getSession(req, res);
560
- if (!session) {
561
- if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
562
- const result = await options.onAccessDenied(req, ctx);
563
- if (result instanceof next_server_js.NextResponse) return mergeResponse([res, result]);
564
- return mergeResponse([res, new next_server_js.NextResponse(result.body, result)]);
565
- }
566
- return mergeResponse([res, next_server_js.NextResponse.json({ message: "unauthorized" }, { status: 401 })]);
567
- }
568
- 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)) {
569
- if (options.onGroupAccessDenied) {
570
- const result = await options.onGroupAccessDenied(req, ctx, session.user);
571
- if (result instanceof next_server_js.NextResponse) return mergeResponse([res, result]);
572
- return mergeResponse([res, new next_server_js.NextResponse(result.body, result)]);
573
- }
574
- return mergeResponse([res, next_server_js.NextResponse.json({ message: "forbidden" }, { status: 403 })]);
575
- }
576
- const resp = await handler(req, ctx);
577
- if (resp instanceof next_server_js.NextResponse) return mergeResponse([res, resp]);
578
- return mergeResponse([res, new next_server_js.NextResponse(resp.body, resp)]);
579
- }
580
- async protectPageApi(req, res, handler, options) {
581
- const session = await this.getSession(req, res);
582
- if (!session) {
583
- if (options === null || options === void 0 ? void 0 : options.onAccessDenied) return options.onAccessDenied(req, res);
584
- return res.status(401).json({ message: "unauthorized" });
585
- }
586
- 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)) {
587
- if (options.onGroupAccessDenied) return options.onGroupAccessDenied(req, res, session.user);
588
- return res.status(403).json({ message: "forbidden" });
589
- }
590
- return handler(req, res);
591
- }
592
- authMiddleware(...args) {
593
- let req;
594
- let evt;
595
- let options;
596
- /* v8 ignore else -- @preserve */
597
- if (Array.isArray(args)) {
598
- if (args.length === 2) {
599
- /* v8 ignore else -- @preserve */
600
- if (isAppRouter(args[0])) {
601
- req = args[0];
602
- evt = args[1];
603
- }
604
- }
605
- if (args.length === 1) options = args[0];
606
- }
607
- if (req && evt) return this.authMiddlewareHandler(req, evt, options);
608
- return (request, nxtEvt) => {
609
- return this.authMiddlewareHandler(request, nxtEvt, options);
610
- };
611
- }
612
- async authMiddlewareHandler(req, evt, options) {
613
- req = getNextRequest(req);
614
- if (req.headers.has("x-middleware-subrequest")) return next_server_js.NextResponse.json({ message: "forbidden" }, { status: 403 });
615
- const { routes, appUrl } = this.getOptions();
616
- if (Object.values(routes).map((x) => (0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(x)).includes(req.nextUrl.pathname)) {
617
- let onError;
618
- if (typeof (options === null || options === void 0 ? void 0 : options.onError) === "function") onError = (error) => options.onError(req, evt, error);
619
- const request = new MonoCloudAppRouterRequest(req);
620
- const response = new MonoCloudAppRouterResponse(new next_server_js.NextResponse());
621
- return this.handleAuthRoutes(request, response, req.nextUrl.pathname, routes, onError);
622
- }
623
- const nxtResp = new next_server_js.NextResponse();
624
- nxtResp.headers.set("x-monocloud-path", req.nextUrl.pathname + req.nextUrl.search);
625
- let isRouteProtected = true;
626
- let allowedGroups;
627
- if (typeof (options === null || options === void 0 ? void 0 : options.protectedRoutes) === "function") isRouteProtected = await options.protectedRoutes(req);
628
- else if (typeof (options === null || options === void 0 ? void 0 : options.protectedRoutes) !== "undefined" && Array.isArray(options.protectedRoutes)) isRouteProtected = options.protectedRoutes.some((route) => {
629
- if (typeof route === "string" || route instanceof RegExp) return new RegExp(route).test(req.nextUrl.pathname);
630
- return route.routes.some((groupRoute) => {
631
- const result = new RegExp(groupRoute).test(req.nextUrl.pathname);
632
- if (result) allowedGroups = route.groups;
633
- return result;
634
- });
635
- });
636
- if (!isRouteProtected) return next_server_js.NextResponse.next({ headers: { "x-monocloud-path": req.nextUrl.pathname + req.nextUrl.search } });
637
- const session = await this.getSession(req, nxtResp);
638
- if (!session) {
639
- if (options === null || options === void 0 ? void 0 : options.onAccessDenied) {
640
- const result = await options.onAccessDenied(req, evt);
641
- if (result instanceof next_server_js.NextResponse) return mergeResponse([nxtResp, result]);
642
- if (result) return mergeResponse([nxtResp, new next_server_js.NextResponse(result.body, result)]);
643
- return next_server_js.NextResponse.next(nxtResp);
644
- }
645
- if (req.nextUrl.pathname.startsWith("/api")) return mergeResponse([nxtResp, next_server_js.NextResponse.json({ message: "unauthorized" }, { status: 401 })]);
646
- const signInRoute = new URL(`${appUrl}${(0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn)}`);
647
- signInRoute.searchParams.set("return_url", req.nextUrl.pathname + req.nextUrl.search);
648
- return mergeResponse([nxtResp, next_server_js.NextResponse.redirect(signInRoute)]);
649
- }
650
- const groupsClaim = (options === null || options === void 0 ? void 0 : options.groupsClaim) ?? process.env.MONOCLOUD_AUTH_GROUPS_CLAIM;
651
- if (allowedGroups && !(0, _monocloud_auth_node_core_utils.isUserInGroup)(session.user, allowedGroups, groupsClaim)) {
652
- if (options === null || options === void 0 ? void 0 : options.onGroupAccessDenied) {
653
- const result = await options.onGroupAccessDenied(req, evt, session.user);
654
- if (result instanceof next_server_js.NextResponse) return mergeResponse([nxtResp, result]);
655
- if (result) return mergeResponse([nxtResp, new next_server_js.NextResponse(result.body, result)]);
656
- return next_server_js.NextResponse.next(nxtResp);
657
- }
658
- if (req.nextUrl.pathname.startsWith("/api")) return mergeResponse([nxtResp, next_server_js.NextResponse.json({ message: "forbidden" }, { status: 403 })]);
659
- return new next_server_js.NextResponse(`forbidden`, { status: 403 });
660
- }
661
- return next_server_js.NextResponse.next(nxtResp);
662
- }
663
- handleAuthRoutes(request, response, path, routes, onError) {
664
- switch (path) {
665
- case (0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signIn): return this.coreClient.signIn(request, response, { onError });
666
- case (0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.callback): return this.coreClient.callback(request, response, { onError });
667
- case (0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.userInfo): return this.coreClient.userInfo(request, response, { onError });
668
- case (0, _monocloud_auth_node_core_internal.ensureLeadingSlash)(routes.signOut): return this.coreClient.signOut(request, response, { onError });
669
- default:
670
- response.notFound();
671
- return response.done();
672
- }
673
- }
674
- async getSession(...args) {
675
- let request;
676
- let response;
677
- if (args.length === 0) {
678
- request = new MonoCloudCookieRequest();
679
- response = new MonoCloudCookieResponse();
680
- } else ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
681
- /* v8 ignore next -- @preserve */
682
- if (!isMonoCloudRequest(request) || !isMonoCloudResponse(response)) throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to getSession()");
683
- return await this.coreClient.getSession(request, response);
684
- }
685
- async getTokens(...args) {
686
- let request;
687
- let response;
688
- let options;
689
- if (args.length === 0) {
690
- request = new MonoCloudCookieRequest();
691
- response = new MonoCloudCookieResponse();
692
- } else if (args.length === 1) if (args[0] instanceof Request) ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
693
- else {
694
- request = new MonoCloudCookieRequest();
695
- response = new MonoCloudCookieResponse();
696
- options = args[0];
697
- }
698
- else if (args.length === 2 && args[0] instanceof Request) if (args[1] instanceof Response) ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
699
- else {
700
- ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
701
- options = args[1];
702
- }
703
- else if (args.length === 2 && isNodeRequest(args[0]) && isNodeResponse(args[1])) ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
704
- else {
705
- ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
706
- options = args[2];
707
- }
708
- if (!isMonoCloudRequest(request) || !isMonoCloudResponse(response) || options && typeof options !== "object") throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to getTokens()");
709
- return await this.coreClient.getTokens(request, response, options);
710
- }
711
- async isAuthenticated(...args) {
712
- let request;
713
- let response;
714
- if (args.length === 0) {
715
- request = new MonoCloudCookieRequest();
716
- response = new MonoCloudCookieResponse();
717
- } else ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
718
- /* v8 ignore next -- @preserve */
719
- if (!isMonoCloudRequest(request) || !isMonoCloudResponse(response)) throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to isAuthenticated()");
720
- return await this.coreClient.isAuthenticated(request, response);
721
- }
722
- /**
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.
726
- */
727
- async protect(options) {
728
- var _options$authParams19, _options$authParams20, _options$authParams21, _options$authParams22, _options$authParams23, _options$authParams24, _options$authParams25, _options$authParams26, _options$authParams27;
729
- const { routes, appUrl } = this.coreClient.getOptions();
730
- let path;
731
- try {
732
- const session = await this.getSession();
733
- if (session && !(options === null || options === void 0 ? void 0 : options.groups)) 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;
735
- const { headers } = await import("next/headers");
736
- path = (await headers()).get("x-monocloud-path") ?? "/";
737
- } catch {
738
- throw new Error("protect() can only be used in App Router server environments (RSC, route handlers, or server actions)");
739
- }
740
- const signInRoute = new URL(`${appUrl}${routes.signIn}`);
741
- signInRoute.searchParams.set("return_url", (options === null || options === void 0 ? void 0 : options.returnUrl) ?? path);
742
- if (options === null || options === void 0 || (_options$authParams19 = options.authParams) === null || _options$authParams19 === void 0 ? void 0 : _options$authParams19.maxAge) signInRoute.searchParams.set("max_age", options.authParams.maxAge.toString());
743
- if (options === null || options === void 0 || (_options$authParams20 = options.authParams) === null || _options$authParams20 === void 0 ? void 0 : _options$authParams20.authenticatorHint) signInRoute.searchParams.set("authenticator_hint", options.authParams.authenticatorHint);
744
- if (options === null || options === void 0 || (_options$authParams21 = options.authParams) === null || _options$authParams21 === void 0 ? void 0 : _options$authParams21.scopes) signInRoute.searchParams.set("scope", options.authParams.scopes);
745
- if (options === null || options === void 0 || (_options$authParams22 = options.authParams) === null || _options$authParams22 === void 0 ? void 0 : _options$authParams22.resource) signInRoute.searchParams.set("resource", options.authParams.resource);
746
- if (options === null || options === void 0 || (_options$authParams23 = options.authParams) === null || _options$authParams23 === void 0 ? void 0 : _options$authParams23.display) signInRoute.searchParams.set("display", options.authParams.display);
747
- if (options === null || options === void 0 || (_options$authParams24 = options.authParams) === null || _options$authParams24 === void 0 ? void 0 : _options$authParams24.uiLocales) signInRoute.searchParams.set("ui_locales", options.authParams.uiLocales);
748
- 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(" "));
749
- 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);
750
- 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);
751
- const { redirect } = await import("next/navigation");
752
- redirect(signInRoute.toString());
753
- }
754
- async isUserInGroup(...args) {
755
- let request;
756
- let response;
757
- let groups;
758
- let options;
759
- if (args.length === 4) {
760
- groups = args[2];
761
- options = args[3];
762
- ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
763
- }
764
- if (args.length === 3) {
765
- if (args[0] instanceof Request) if (args[1] instanceof Response) {
766
- ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
767
- groups = args[2];
768
- } else {
769
- ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
770
- groups = args[1];
771
- options = args[2];
772
- }
773
- if (isNodeRequest(args[0]) && isNodeResponse(args[1])) {
774
- ({request, response} = getMonoCloudCookieReqRes(args[0], args[1]));
775
- groups = args[2];
776
- }
777
- }
778
- if (args.length === 2) {
779
- if (args[0] instanceof Request) {
780
- ({request, response} = getMonoCloudCookieReqRes(args[0], void 0));
781
- groups = args[1];
782
- }
783
- if (Array.isArray(args[0])) {
784
- request = new MonoCloudCookieRequest();
785
- response = new MonoCloudCookieResponse();
786
- groups = args[0];
787
- options = args[1];
788
- }
789
- }
790
- if (args.length === 1) {
791
- request = new MonoCloudCookieRequest();
792
- response = new MonoCloudCookieResponse();
793
- groups = args[0];
794
- }
795
- if (!Array.isArray(groups) || !isMonoCloudRequest(request) || !isMonoCloudResponse(response) || options && typeof options !== "object") throw new _monocloud_auth_node_core.MonoCloudValidationError("Invalid parameters passed to isUserInGroup()");
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);
797
- }
798
- /**
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.
802
- */
803
- async redirectToSignIn(options) {
804
- const { routes, appUrl } = this.coreClient.getOptions();
805
- try {
806
- const { headers } = await import("next/headers");
807
- await headers();
808
- } catch {
809
- throw new Error("redirectToSignIn() can only be used in App Router server environments (RSC, route handlers, or server actions)");
810
- }
811
- const signInRoute = new URL(`${appUrl}${routes.signIn}`);
812
- if (options === null || options === void 0 ? void 0 : options.returnUrl) signInRoute.searchParams.set("return_url", options.returnUrl);
813
- if (options === null || options === void 0 ? void 0 : options.maxAge) signInRoute.searchParams.set("max_age", options.maxAge.toString());
814
- if (options === null || options === void 0 ? void 0 : options.authenticatorHint) signInRoute.searchParams.set("authenticator_hint", options.authenticatorHint);
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);
817
- if (options === null || options === void 0 ? void 0 : options.display) signInRoute.searchParams.set("display", options.display);
818
- if (options === null || options === void 0 ? void 0 : options.uiLocales) signInRoute.searchParams.set("ui_locales", options.uiLocales);
819
- if (Array.isArray(options === null || options === void 0 ? void 0 : options.acrValues)) signInRoute.searchParams.set("acr_values", options.acrValues.join(" "));
820
- if (options === null || options === void 0 ? void 0 : options.loginHint) signInRoute.searchParams.set("login_hint", options.loginHint);
821
- if (options === null || options === void 0 ? void 0 : options.prompt) signInRoute.searchParams.set("prompt", options.prompt);
822
- const { redirect } = await import("next/navigation");
823
- redirect(signInRoute.toString());
824
- }
825
- /**
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.
829
- */
830
- async redirectToSignOut(options) {
831
- var _options$postLogoutRe;
832
- const { routes, appUrl } = this.coreClient.getOptions();
833
- try {
834
- const { headers } = await import("next/headers");
835
- await headers();
836
- } catch {
837
- throw new Error("redirectToSignOut() can only be used in App Router server environments (RSC, route handlers, or server actions)");
838
- }
839
- const signOutRoute = new URL(`${appUrl}${routes.signOut}`);
840
- 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);
841
- if (typeof (options === null || options === void 0 ? void 0 : options.federated) === "boolean") signOutRoute.searchParams.set("federated", options.federated.toString());
842
- const { redirect } = await import("next/navigation");
843
- redirect(signOutRoute.toString());
844
- }
845
- getOptions() {
846
- return this.coreClient.getOptions();
847
- }
848
- registerPublicEnvVariables() {
849
- Object.keys(process.env).filter((key) => key.startsWith("NEXT_PUBLIC_MONOCLOUD_AUTH")).forEach((publicKey) => {
850
- const [, privateKey] = publicKey.split("NEXT_PUBLIC_");
851
- process.env[privateKey] = process.env[publicKey];
852
- });
853
- }
854
- };
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
-
1126
- //#endregion
1127
7
  Object.defineProperty(exports, 'MonoCloudAuthBaseError', {
1128
8
  enumerable: true,
1129
9
  get: function () {
@@ -1136,7 +16,7 @@ Object.defineProperty(exports, 'MonoCloudHttpError', {
1136
16
  return _monocloud_auth_node_core.MonoCloudHttpError;
1137
17
  }
1138
18
  });
1139
- exports.MonoCloudNextClient = MonoCloudNextClient;
19
+ exports.MonoCloudNextClient = require_monocloud_next_client.MonoCloudNextClient;
1140
20
  Object.defineProperty(exports, 'MonoCloudOPError', {
1141
21
  enumerable: true,
1142
22
  get: function () {
@@ -1155,15 +35,14 @@ Object.defineProperty(exports, 'MonoCloudValidationError', {
1155
35
  return _monocloud_auth_node_core.MonoCloudValidationError;
1156
36
  }
1157
37
  });
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;
1169
- //# sourceMappingURL=index.cjs.map
38
+ exports.authMiddleware = require_initialize.authMiddleware;
39
+ exports.getSession = require_initialize.getSession;
40
+ exports.getTokens = require_initialize.getTokens;
41
+ exports.isAuthenticated = require_initialize.isAuthenticated;
42
+ exports.isUserInGroup = require_initialize.isUserInGroup;
43
+ exports.monoCloudAuth = require_initialize.monoCloudAuth;
44
+ exports.protect = require_initialize.protect;
45
+ exports.protectApi = require_initialize.protectApi;
46
+ exports.protectPage = require_initialize.protectPage;
47
+ exports.redirectToSignIn = require_initialize.redirectToSignIn;
48
+ exports.redirectToSignOut = require_initialize.redirectToSignOut;