@imtbl/auth-nextjs 2.12.4-alpha.4 → 2.12.4-alpha.6

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.
@@ -16,7 +16,9 @@ import {
16
16
  signIn,
17
17
  signOut
18
18
  } from "next-auth/react";
19
- import { Auth } from "@imtbl/auth";
19
+ import {
20
+ Auth
21
+ } from "@imtbl/auth";
20
22
 
21
23
  // src/utils/token.ts
22
24
  import { decodeJwtPayload } from "@imtbl/auth";
@@ -161,11 +163,11 @@ function useImmutableAuth() {
161
163
  email: session.user.email,
162
164
  nickname: session.user.nickname
163
165
  } : null;
164
- const handleSignIn = useCallback(async () => {
166
+ const handleSignIn = useCallback(async (options) => {
165
167
  if (!auth) {
166
168
  throw new Error("Auth not initialized");
167
169
  }
168
- const authUser = await auth.login();
170
+ const authUser = await auth.login(options);
169
171
  if (!authUser) {
170
172
  throw new Error("Login failed");
171
173
  }
@@ -238,7 +240,7 @@ function useAccessToken() {
238
240
 
239
241
  // src/client/callback.tsx
240
242
  import { useEffect as useEffect2, useState as useState2, useRef as useRef2 } from "react";
241
- import { useRouter } from "next/router";
243
+ import { useRouter, useSearchParams } from "next/navigation";
242
244
  import { signIn as signIn2 } from "next-auth/react";
243
245
  import { Auth as Auth2 } from "@imtbl/auth";
244
246
  import { jsx as jsx2, jsxs } from "react/jsx-runtime";
@@ -249,6 +251,7 @@ function CallbackPage({
249
251
  errorComponent
250
252
  }) {
251
253
  const router = useRouter();
254
+ const searchParams = useSearchParams();
252
255
  const [error, setError] = useState2(null);
253
256
  const callbackProcessedRef = useRef2(false);
254
257
  useEffect2(() => {
@@ -300,31 +303,20 @@ function CallbackPage({
300
303
  }
301
304
  };
302
305
  const handleOAuthError = () => {
303
- const errorCode = router.query.error;
304
- const errorDescription = router.query.error_description;
306
+ const errorCode = searchParams.get("error");
307
+ const errorDescription = searchParams.get("error_description");
305
308
  const errorMessage = errorDescription || errorCode || "Authentication failed";
306
309
  setError(errorMessage);
307
310
  };
308
- if (!router.isReady) {
309
- return;
310
- }
311
- if (router.query.error) {
311
+ if (searchParams.get("error")) {
312
312
  handleOAuthError();
313
313
  return;
314
314
  }
315
- if (router.query.code && !callbackProcessedRef.current) {
315
+ if (searchParams.get("code") && !callbackProcessedRef.current) {
316
316
  callbackProcessedRef.current = true;
317
317
  handleCallback();
318
318
  }
319
- }, [
320
- router.isReady,
321
- router.query.code,
322
- router.query.error,
323
- router.query.error_description,
324
- router,
325
- config,
326
- redirectTo
327
- ]);
319
+ }, [searchParams, router, config, redirectTo]);
328
320
  if (error) {
329
321
  if (errorComponent) {
330
322
  return errorComponent(error);
@@ -336,6 +328,7 @@ function CallbackPage({
336
328
  "button",
337
329
  {
338
330
  onClick: () => router.push("/"),
331
+ type: "button",
339
332
  style: {
340
333
  padding: "0.5rem 1rem",
341
334
  marginTop: "1rem",
@@ -351,9 +344,13 @@ function CallbackPage({
351
344
  }
352
345
  return /* @__PURE__ */ jsx2("div", { style: { padding: "2rem", textAlign: "center" }, children: /* @__PURE__ */ jsx2("p", { children: "Completing authentication..." }) });
353
346
  }
347
+
348
+ // src/client/index.ts
349
+ import { MarketingConsentStatus } from "@imtbl/auth";
354
350
  export {
355
351
  CallbackPage,
356
352
  ImmutableAuthProvider,
353
+ MarketingConsentStatus,
357
354
  useAccessToken,
358
355
  useImmutableAuth
359
356
  };
@@ -30,7 +30,14 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
+ DEFAULT_AUDIENCE: () => DEFAULT_AUDIENCE,
34
+ DEFAULT_AUTH_DOMAIN: () => DEFAULT_AUTH_DOMAIN,
35
+ DEFAULT_NEXTAUTH_BASE_PATH: () => DEFAULT_NEXTAUTH_BASE_PATH,
36
+ DEFAULT_SCOPE: () => DEFAULT_SCOPE,
33
37
  ImmutableAuth: () => ImmutableAuth,
38
+ MarketingConsentStatus: () => import_auth.MarketingConsentStatus,
39
+ createAuthConfig: () => createAuthConfig,
40
+ createImmutableAuth: () => createImmutableAuth,
34
41
  isTokenExpired: () => isTokenExpired,
35
42
  refreshAccessToken: () => refreshAccessToken
36
43
  });
@@ -42,7 +49,10 @@ var import_credentials = __toESM(require("next-auth/providers/credentials"), 1);
42
49
 
43
50
  // src/constants.ts
44
51
  var DEFAULT_AUTH_DOMAIN = "https://auth.immutable.com";
52
+ var DEFAULT_AUDIENCE = "platform_api";
53
+ var DEFAULT_SCOPE = "openid profile email offline_access transact";
45
54
  var IMMUTABLE_PROVIDER_ID = "immutable";
55
+ var DEFAULT_NEXTAUTH_BASE_PATH = "/api/auth";
46
56
  var DEFAULT_TOKEN_EXPIRY_SECONDS = 900;
47
57
  var DEFAULT_TOKEN_EXPIRY_MS = DEFAULT_TOKEN_EXPIRY_SECONDS * 1e3;
48
58
  var TOKEN_EXPIRY_BUFFER_SECONDS = 60;
@@ -110,7 +120,7 @@ function isTokenExpired(accessTokenExpires, bufferSeconds = TOKEN_EXPIRY_BUFFER_
110
120
  }
111
121
 
112
122
  // src/config.ts
113
- var CredentialsProvider = import_credentials.default.default || import_credentials.default;
123
+ var Credentials = import_credentials.default.default || import_credentials.default;
114
124
  async function validateTokens(accessToken, authDomain) {
115
125
  try {
116
126
  const response = await fetch(`${authDomain}/userinfo`, {
@@ -129,18 +139,18 @@ async function validateTokens(accessToken, authDomain) {
129
139
  return null;
130
140
  }
131
141
  }
132
- function createAuthOptions(config) {
142
+ function createAuthConfig(config) {
133
143
  const authDomain = config.authenticationDomain || DEFAULT_AUTH_DOMAIN;
134
144
  return {
135
145
  providers: [
136
- CredentialsProvider({
146
+ Credentials({
137
147
  id: IMMUTABLE_PROVIDER_ID,
138
148
  name: "Immutable",
139
149
  credentials: {
140
150
  tokens: { label: "Tokens", type: "text" }
141
151
  },
142
152
  async authorize(credentials) {
143
- if (!credentials?.tokens) {
153
+ if (!credentials?.tokens || typeof credentials.tokens !== "string") {
144
154
  return null;
145
155
  }
146
156
  let tokenData;
@@ -183,6 +193,7 @@ function createAuthOptions(config) {
183
193
  })
184
194
  ],
185
195
  callbacks: {
196
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
186
197
  async jwt({
187
198
  token,
188
199
  user,
@@ -203,13 +214,14 @@ function createAuthOptions(config) {
203
214
  };
204
215
  }
205
216
  if (trigger === "update" && sessionUpdate) {
217
+ const update = sessionUpdate;
206
218
  return {
207
219
  ...token,
208
- ...sessionUpdate.accessToken && { accessToken: sessionUpdate.accessToken },
209
- ...sessionUpdate.refreshToken && { refreshToken: sessionUpdate.refreshToken },
210
- ...sessionUpdate.idToken && { idToken: sessionUpdate.idToken },
211
- ...sessionUpdate.accessTokenExpires && { accessTokenExpires: sessionUpdate.accessTokenExpires },
212
- ...sessionUpdate.zkEvm && { zkEvm: sessionUpdate.zkEvm }
220
+ ...update.accessToken ? { accessToken: update.accessToken } : {},
221
+ ...update.refreshToken ? { refreshToken: update.refreshToken } : {},
222
+ ...update.idToken ? { idToken: update.idToken } : {},
223
+ ...update.accessTokenExpires ? { accessTokenExpires: update.accessTokenExpires } : {},
224
+ ...update.zkEvm ? { zkEvm: update.zkEvm } : {}
213
225
  };
214
226
  }
215
227
  if (!isTokenExpired(token.accessTokenExpires)) {
@@ -217,10 +229,12 @@ function createAuthOptions(config) {
217
229
  }
218
230
  return refreshAccessToken(token, config);
219
231
  },
232
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
220
233
  async session({ session, token }) {
221
234
  return {
222
235
  ...session,
223
236
  user: {
237
+ ...session.user,
224
238
  sub: token.sub,
225
239
  email: token.email,
226
240
  nickname: token.nickname
@@ -238,25 +252,24 @@ function createAuthOptions(config) {
238
252
  strategy: "jwt",
239
253
  // Session max age in seconds (30 days default)
240
254
  maxAge: DEFAULT_SESSION_MAX_AGE_SECONDS
241
- },
242
- // Use NEXTAUTH_SECRET from environment
243
- secret: process.env.NEXTAUTH_SECRET
255
+ }
244
256
  };
245
257
  }
246
258
 
247
259
  // src/index.ts
260
+ var import_auth = require("@imtbl/auth");
248
261
  var NextAuth = import_next_auth.default.default || import_next_auth.default;
249
- function ImmutableAuth(config, overrides) {
250
- const authOptions = createAuthOptions(config);
262
+ function createImmutableAuth(config, overrides) {
263
+ const authConfig = createAuthConfig(config);
251
264
  if (!overrides) {
252
- return NextAuth(authOptions);
265
+ return NextAuth(authConfig);
253
266
  }
254
267
  const composedCallbacks = {
255
- ...authOptions.callbacks
268
+ ...authConfig.callbacks
256
269
  };
257
270
  if (overrides.callbacks) {
258
271
  if (overrides.callbacks.jwt) {
259
- const internalJwt = authOptions.callbacks?.jwt;
272
+ const internalJwt = authConfig.callbacks?.jwt;
260
273
  const userJwt = overrides.callbacks.jwt;
261
274
  composedCallbacks.jwt = async (params) => {
262
275
  const token = internalJwt ? await internalJwt(params) : params.token;
@@ -264,7 +277,7 @@ function ImmutableAuth(config, overrides) {
264
277
  };
265
278
  }
266
279
  if (overrides.callbacks.session) {
267
- const internalSession = authOptions.callbacks?.session;
280
+ const internalSession = authConfig.callbacks?.session;
268
281
  const userSession = overrides.callbacks.session;
269
282
  composedCallbacks.session = async (params) => {
270
283
  const session = internalSession ? await internalSession(params) : params.session;
@@ -278,16 +291,24 @@ function ImmutableAuth(config, overrides) {
278
291
  composedCallbacks.redirect = overrides.callbacks.redirect;
279
292
  }
280
293
  }
281
- const mergedOptions = {
282
- ...authOptions,
294
+ const mergedConfig = {
295
+ ...authConfig,
283
296
  ...overrides,
284
297
  callbacks: composedCallbacks
285
298
  };
286
- return NextAuth(mergedOptions);
299
+ return NextAuth(mergedConfig);
287
300
  }
301
+ var ImmutableAuth = createImmutableAuth;
288
302
  // Annotate the CommonJS export names for ESM import in node:
289
303
  0 && (module.exports = {
304
+ DEFAULT_AUDIENCE,
305
+ DEFAULT_AUTH_DOMAIN,
306
+ DEFAULT_NEXTAUTH_BASE_PATH,
307
+ DEFAULT_SCOPE,
290
308
  ImmutableAuth,
309
+ MarketingConsentStatus,
310
+ createAuthConfig,
311
+ createImmutableAuth,
291
312
  isTokenExpired,
292
313
  refreshAccessToken
293
314
  });
@@ -1,53 +1,24 @@
1
1
  import {
2
- createAuthOptions,
2
+ DEFAULT_AUDIENCE,
3
+ DEFAULT_AUTH_DOMAIN,
4
+ DEFAULT_NEXTAUTH_BASE_PATH,
5
+ DEFAULT_SCOPE,
6
+ ImmutableAuth,
7
+ MarketingConsentStatus,
8
+ createAuthConfig,
9
+ createImmutableAuth,
3
10
  isTokenExpired,
4
11
  refreshAccessToken
5
- } from "./chunk-OPPMGNFZ.js";
6
-
7
- // src/index.ts
8
- import NextAuthDefault from "next-auth";
9
- var NextAuth = NextAuthDefault.default || NextAuthDefault;
10
- function ImmutableAuth(config, overrides) {
11
- const authOptions = createAuthOptions(config);
12
- if (!overrides) {
13
- return NextAuth(authOptions);
14
- }
15
- const composedCallbacks = {
16
- ...authOptions.callbacks
17
- };
18
- if (overrides.callbacks) {
19
- if (overrides.callbacks.jwt) {
20
- const internalJwt = authOptions.callbacks?.jwt;
21
- const userJwt = overrides.callbacks.jwt;
22
- composedCallbacks.jwt = async (params) => {
23
- const token = internalJwt ? await internalJwt(params) : params.token;
24
- return userJwt({ ...params, token });
25
- };
26
- }
27
- if (overrides.callbacks.session) {
28
- const internalSession = authOptions.callbacks?.session;
29
- const userSession = overrides.callbacks.session;
30
- composedCallbacks.session = async (params) => {
31
- const session = internalSession ? await internalSession(params) : params.session;
32
- return userSession({ ...params, session });
33
- };
34
- }
35
- if (overrides.callbacks.signIn) {
36
- composedCallbacks.signIn = overrides.callbacks.signIn;
37
- }
38
- if (overrides.callbacks.redirect) {
39
- composedCallbacks.redirect = overrides.callbacks.redirect;
40
- }
41
- }
42
- const mergedOptions = {
43
- ...authOptions,
44
- ...overrides,
45
- callbacks: composedCallbacks
46
- };
47
- return NextAuth(mergedOptions);
48
- }
12
+ } from "./chunk-BRDI4KXS.js";
49
13
  export {
14
+ DEFAULT_AUDIENCE,
15
+ DEFAULT_AUTH_DOMAIN,
16
+ DEFAULT_NEXTAUTH_BASE_PATH,
17
+ DEFAULT_SCOPE,
50
18
  ImmutableAuth,
19
+ MarketingConsentStatus,
20
+ createAuthConfig,
21
+ createImmutableAuth,
51
22
  isTokenExpired,
52
23
  refreshAccessToken
53
24
  };
@@ -30,13 +30,16 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/server/index.ts
31
31
  var server_exports = {};
32
32
  __export(server_exports, {
33
- getImmutableSession: () => getImmutableSession,
34
- withPageAuthRequired: () => withPageAuthRequired
33
+ createAuthConfig: () => createAuthConfig,
34
+ createAuthMiddleware: () => createAuthMiddleware,
35
+ createImmutableAuth: () => createImmutableAuth,
36
+ withAuth: () => withAuth
35
37
  });
36
38
  module.exports = __toCommonJS(server_exports);
39
+ var import_server = require("next/server");
37
40
 
38
- // src/server/with-page-auth.ts
39
- var import_next_auth = require("next-auth");
41
+ // src/index.ts
42
+ var import_next_auth = __toESM(require("next-auth"), 1);
40
43
 
41
44
  // src/config.ts
42
45
  var import_credentials = __toESM(require("next-auth/providers/credentials"), 1);
@@ -111,7 +114,7 @@ function isTokenExpired(accessTokenExpires, bufferSeconds = TOKEN_EXPIRY_BUFFER_
111
114
  }
112
115
 
113
116
  // src/config.ts
114
- var CredentialsProvider = import_credentials.default.default || import_credentials.default;
117
+ var Credentials = import_credentials.default.default || import_credentials.default;
115
118
  async function validateTokens(accessToken, authDomain) {
116
119
  try {
117
120
  const response = await fetch(`${authDomain}/userinfo`, {
@@ -130,18 +133,18 @@ async function validateTokens(accessToken, authDomain) {
130
133
  return null;
131
134
  }
132
135
  }
133
- function createAuthOptions(config) {
136
+ function createAuthConfig(config) {
134
137
  const authDomain = config.authenticationDomain || DEFAULT_AUTH_DOMAIN;
135
138
  return {
136
139
  providers: [
137
- CredentialsProvider({
140
+ Credentials({
138
141
  id: IMMUTABLE_PROVIDER_ID,
139
142
  name: "Immutable",
140
143
  credentials: {
141
144
  tokens: { label: "Tokens", type: "text" }
142
145
  },
143
146
  async authorize(credentials) {
144
- if (!credentials?.tokens) {
147
+ if (!credentials?.tokens || typeof credentials.tokens !== "string") {
145
148
  return null;
146
149
  }
147
150
  let tokenData;
@@ -184,6 +187,7 @@ function createAuthOptions(config) {
184
187
  })
185
188
  ],
186
189
  callbacks: {
190
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
187
191
  async jwt({
188
192
  token,
189
193
  user,
@@ -204,13 +208,14 @@ function createAuthOptions(config) {
204
208
  };
205
209
  }
206
210
  if (trigger === "update" && sessionUpdate) {
211
+ const update = sessionUpdate;
207
212
  return {
208
213
  ...token,
209
- ...sessionUpdate.accessToken && { accessToken: sessionUpdate.accessToken },
210
- ...sessionUpdate.refreshToken && { refreshToken: sessionUpdate.refreshToken },
211
- ...sessionUpdate.idToken && { idToken: sessionUpdate.idToken },
212
- ...sessionUpdate.accessTokenExpires && { accessTokenExpires: sessionUpdate.accessTokenExpires },
213
- ...sessionUpdate.zkEvm && { zkEvm: sessionUpdate.zkEvm }
214
+ ...update.accessToken ? { accessToken: update.accessToken } : {},
215
+ ...update.refreshToken ? { refreshToken: update.refreshToken } : {},
216
+ ...update.idToken ? { idToken: update.idToken } : {},
217
+ ...update.accessTokenExpires ? { accessTokenExpires: update.accessTokenExpires } : {},
218
+ ...update.zkEvm ? { zkEvm: update.zkEvm } : {}
214
219
  };
215
220
  }
216
221
  if (!isTokenExpired(token.accessTokenExpires)) {
@@ -218,10 +223,12 @@ function createAuthOptions(config) {
218
223
  }
219
224
  return refreshAccessToken(token, config);
220
225
  },
226
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
221
227
  async session({ session, token }) {
222
228
  return {
223
229
  ...session,
224
230
  user: {
231
+ ...session.user,
225
232
  sub: token.sub,
226
233
  email: token.email,
227
234
  nickname: token.nickname
@@ -239,62 +246,103 @@ function createAuthOptions(config) {
239
246
  strategy: "jwt",
240
247
  // Session max age in seconds (30 days default)
241
248
  maxAge: DEFAULT_SESSION_MAX_AGE_SECONDS
242
- },
243
- // Use NEXTAUTH_SECRET from environment
244
- secret: process.env.NEXTAUTH_SECRET
249
+ }
245
250
  };
246
251
  }
247
252
 
248
- // src/server/with-page-auth.ts
249
- async function getImmutableSession(req, res, config) {
250
- const authOptions = createAuthOptions(config);
251
- return (0, import_next_auth.getServerSession)(req, res, authOptions);
252
- }
253
- function withPageAuthRequired(config, options = {}) {
254
- const {
255
- loginUrl = "/login",
256
- returnTo,
257
- getServerSideProps: customGetServerSideProps
258
- } = options;
259
- const authOptions = createAuthOptions(config);
260
- return async (ctx) => {
261
- const session = await (0, import_next_auth.getServerSession)(ctx.req, ctx.res, authOptions);
262
- if (!session) {
263
- let destination = loginUrl;
264
- if (returnTo !== false) {
265
- const returnPath = returnTo || ctx.resolvedUrl;
266
- const separator = loginUrl.includes("?") ? "&" : "?";
267
- destination = `${loginUrl}${separator}returnTo=${encodeURIComponent(returnPath)}`;
268
- }
269
- return {
270
- redirect: {
271
- destination,
272
- permanent: false
273
- }
253
+ // src/index.ts
254
+ var import_auth = require("@imtbl/auth");
255
+ var NextAuth = import_next_auth.default.default || import_next_auth.default;
256
+ function createImmutableAuth(config, overrides) {
257
+ const authConfig = createAuthConfig(config);
258
+ if (!overrides) {
259
+ return NextAuth(authConfig);
260
+ }
261
+ const composedCallbacks = {
262
+ ...authConfig.callbacks
263
+ };
264
+ if (overrides.callbacks) {
265
+ if (overrides.callbacks.jwt) {
266
+ const internalJwt = authConfig.callbacks?.jwt;
267
+ const userJwt = overrides.callbacks.jwt;
268
+ composedCallbacks.jwt = async (params) => {
269
+ const token = internalJwt ? await internalJwt(params) : params.token;
270
+ return userJwt({ ...params, token });
274
271
  };
275
272
  }
276
- if (customGetServerSideProps) {
277
- const result = await customGetServerSideProps(ctx, session);
278
- if ("redirect" in result || "notFound" in result) {
279
- return result;
280
- }
281
- const userProps = await result.props;
282
- return {
283
- props: {
284
- ...userProps,
285
- session
286
- }
273
+ if (overrides.callbacks.session) {
274
+ const internalSession = authConfig.callbacks?.session;
275
+ const userSession = overrides.callbacks.session;
276
+ composedCallbacks.session = async (params) => {
277
+ const session = internalSession ? await internalSession(params) : params.session;
278
+ return userSession({ ...params, session });
287
279
  };
288
280
  }
289
- return {
290
- props: {
291
- session
281
+ if (overrides.callbacks.signIn) {
282
+ composedCallbacks.signIn = overrides.callbacks.signIn;
283
+ }
284
+ if (overrides.callbacks.redirect) {
285
+ composedCallbacks.redirect = overrides.callbacks.redirect;
286
+ }
287
+ }
288
+ const mergedConfig = {
289
+ ...authConfig,
290
+ ...overrides,
291
+ callbacks: composedCallbacks
292
+ };
293
+ return NextAuth(mergedConfig);
294
+ }
295
+
296
+ // src/server/index.ts
297
+ function createAuthMiddleware(auth, options = {}) {
298
+ const { loginUrl = "/login", protectedPaths, publicPaths } = options;
299
+ return async function middleware(request) {
300
+ const { pathname } = request.nextUrl;
301
+ if (publicPaths) {
302
+ const isPublic = publicPaths.some((pattern) => {
303
+ if (typeof pattern === "string") {
304
+ return pathname === pattern || pathname.startsWith(pattern);
305
+ }
306
+ return pattern.test(pathname);
307
+ });
308
+ if (isPublic) {
309
+ return import_server.NextResponse.next();
292
310
  }
293
- };
311
+ }
312
+ if (protectedPaths) {
313
+ const isProtected = protectedPaths.some((pattern) => {
314
+ if (typeof pattern === "string") {
315
+ return pathname === pattern || pathname.startsWith(pattern);
316
+ }
317
+ return pattern.test(pathname);
318
+ });
319
+ if (!isProtected) {
320
+ return import_server.NextResponse.next();
321
+ }
322
+ }
323
+ const session = await auth();
324
+ if (!session) {
325
+ const url = new URL(loginUrl, request.url);
326
+ const returnTo = request.nextUrl.search ? `${pathname}${request.nextUrl.search}` : pathname;
327
+ url.searchParams.set("returnTo", returnTo);
328
+ return import_server.NextResponse.redirect(url);
329
+ }
330
+ return import_server.NextResponse.next();
331
+ };
332
+ }
333
+ function withAuth(auth, handler) {
334
+ return async (...args) => {
335
+ const session = await auth();
336
+ if (!session) {
337
+ throw new Error("Unauthorized: No active session");
338
+ }
339
+ return handler(session, ...args);
294
340
  };
295
341
  }
296
342
  // Annotate the CommonJS export names for ESM import in node:
297
343
  0 && (module.exports = {
298
- getImmutableSession,
299
- withPageAuthRequired
344
+ createAuthConfig,
345
+ createAuthMiddleware,
346
+ createImmutableAuth,
347
+ withAuth
300
348
  });
@@ -1,57 +1,58 @@
1
1
  import {
2
- createAuthOptions
3
- } from "../chunk-OPPMGNFZ.js";
2
+ createAuthConfig,
3
+ createImmutableAuth
4
+ } from "../chunk-BRDI4KXS.js";
4
5
 
5
- // src/server/with-page-auth.ts
6
- import { getServerSession as nextAuthGetServerSession } from "next-auth";
7
- async function getImmutableSession(req, res, config) {
8
- const authOptions = createAuthOptions(config);
9
- return nextAuthGetServerSession(req, res, authOptions);
10
- }
11
- function withPageAuthRequired(config, options = {}) {
12
- const {
13
- loginUrl = "/login",
14
- returnTo,
15
- getServerSideProps: customGetServerSideProps
16
- } = options;
17
- const authOptions = createAuthOptions(config);
18
- return async (ctx) => {
19
- const session = await nextAuthGetServerSession(ctx.req, ctx.res, authOptions);
20
- if (!session) {
21
- let destination = loginUrl;
22
- if (returnTo !== false) {
23
- const returnPath = returnTo || ctx.resolvedUrl;
24
- const separator = loginUrl.includes("?") ? "&" : "?";
25
- destination = `${loginUrl}${separator}returnTo=${encodeURIComponent(returnPath)}`;
26
- }
27
- return {
28
- redirect: {
29
- destination,
30
- permanent: false
6
+ // src/server/index.ts
7
+ import { NextResponse } from "next/server";
8
+ function createAuthMiddleware(auth, options = {}) {
9
+ const { loginUrl = "/login", protectedPaths, publicPaths } = options;
10
+ return async function middleware(request) {
11
+ const { pathname } = request.nextUrl;
12
+ if (publicPaths) {
13
+ const isPublic = publicPaths.some((pattern) => {
14
+ if (typeof pattern === "string") {
15
+ return pathname === pattern || pathname.startsWith(pattern);
31
16
  }
32
- };
33
- }
34
- if (customGetServerSideProps) {
35
- const result = await customGetServerSideProps(ctx, session);
36
- if ("redirect" in result || "notFound" in result) {
37
- return result;
17
+ return pattern.test(pathname);
18
+ });
19
+ if (isPublic) {
20
+ return NextResponse.next();
38
21
  }
39
- const userProps = await result.props;
40
- return {
41
- props: {
42
- ...userProps,
43
- session
44
- }
45
- };
46
22
  }
47
- return {
48
- props: {
49
- session
23
+ if (protectedPaths) {
24
+ const isProtected = protectedPaths.some((pattern) => {
25
+ if (typeof pattern === "string") {
26
+ return pathname === pattern || pathname.startsWith(pattern);
27
+ }
28
+ return pattern.test(pathname);
29
+ });
30
+ if (!isProtected) {
31
+ return NextResponse.next();
50
32
  }
51
- };
33
+ }
34
+ const session = await auth();
35
+ if (!session) {
36
+ const url = new URL(loginUrl, request.url);
37
+ const returnTo = request.nextUrl.search ? `${pathname}${request.nextUrl.search}` : pathname;
38
+ url.searchParams.set("returnTo", returnTo);
39
+ return NextResponse.redirect(url);
40
+ }
41
+ return NextResponse.next();
42
+ };
43
+ }
44
+ function withAuth(auth, handler) {
45
+ return async (...args) => {
46
+ const session = await auth();
47
+ if (!session) {
48
+ throw new Error("Unauthorized: No active session");
49
+ }
50
+ return handler(session, ...args);
52
51
  };
53
52
  }
54
53
  export {
55
- getImmutableSession,
56
- withPageAuthRequired
54
+ createAuthConfig,
55
+ createAuthMiddleware,
56
+ createImmutableAuth,
57
+ withAuth
57
58
  };