@oauth42/next 0.1.0

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.
@@ -0,0 +1,122 @@
1
+ import * as next_auth from 'next-auth';
2
+ import { NextAuthOptions } from 'next-auth';
3
+ import { GetServerSidePropsContext, NextApiRequest, NextApiResponse } from 'next';
4
+ import { OAuthUserConfig, OAuthConfig } from 'next-auth/providers/oauth';
5
+ import { NextRequest, NextResponse } from 'next/server';
6
+
7
+ interface OAuth42Profile {
8
+ sub: string;
9
+ email: string;
10
+ email_verified?: boolean;
11
+ name?: string;
12
+ given_name?: string;
13
+ family_name?: string;
14
+ picture?: string;
15
+ username?: string;
16
+ id?: string;
17
+ }
18
+ interface OAuth42ProviderOptions {
19
+ clientId: string;
20
+ clientSecret: string;
21
+ issuer?: string;
22
+ authorizationUrl?: string;
23
+ tokenUrl?: string;
24
+ userinfoUrl?: string;
25
+ scopes?: string[];
26
+ pkceEnabled?: boolean;
27
+ }
28
+ declare function OAuth42Provider<P extends OAuth42Profile>(options: OAuthUserConfig<P> & Partial<OAuth42ProviderOptions>): OAuthConfig<P>;
29
+
30
+ /**
31
+ * Get the OAuth42 session server-side
32
+ *
33
+ * This is the primary method for retrieving sessions in OAuth42 SDK.
34
+ * Supports both Pages Router and App Router:
35
+ *
36
+ * App Router:
37
+ * ```ts
38
+ * const session = await getOAuth42Session(authOptions);
39
+ * ```
40
+ *
41
+ * Pages Router:
42
+ * ```ts
43
+ * const session = await getOAuth42Session(req, res, authOptions);
44
+ * ```
45
+ */
46
+ declare function getOAuth42Session(...args: [GetServerSidePropsContext['req'], GetServerSidePropsContext['res'], NextAuthOptions] | [NextApiRequest, NextApiResponse, NextAuthOptions] | [NextAuthOptions]): Promise<next_auth.Session | null>;
47
+ /**
48
+ * Helper for protecting API routes
49
+ */
50
+ declare function withOAuth42Session(handler: (req: NextApiRequest, res: NextApiResponse, session: any) => Promise<void> | void, authOptions: NextAuthOptions): (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
51
+ /**
52
+ * Helper for protecting server-side props
53
+ */
54
+ declare function withOAuth42ServerSideProps(getServerSideProps: (context: GetServerSidePropsContext, session: any) => Promise<any>, authOptions: NextAuthOptions): (context: GetServerSidePropsContext) => Promise<any>;
55
+
56
+ interface CreateAuthOptions {
57
+ clientId?: string;
58
+ clientSecret?: string;
59
+ issuer?: string;
60
+ scopes?: string[];
61
+ pkceEnabled?: boolean;
62
+ debug?: boolean;
63
+ callbacks?: NextAuthOptions['callbacks'];
64
+ pages?: NextAuthOptions['pages'];
65
+ session?: NextAuthOptions['session'];
66
+ }
67
+ /**
68
+ * Create a pre-configured NextAuth instance for OAuth42
69
+ * This provides a simplified setup with sensible defaults
70
+ */
71
+ declare function createAuth(options?: CreateAuthOptions): {
72
+ auth: NextAuthOptions;
73
+ handlers: any;
74
+ };
75
+ /**
76
+ * Create NextAuth handlers for API routes
77
+ */
78
+ declare function createHandlers(authOptions: NextAuthOptions): {
79
+ GET: any;
80
+ POST: any;
81
+ };
82
+ /**
83
+ * Helper to get the current session server-side
84
+ * @deprecated Use getOAuth42Session instead - this is now just an alias for backward compatibility
85
+ *
86
+ * This function is maintained for backward compatibility but internally
87
+ * calls getOAuth42Session which properly handles both App Router and Pages Router
88
+ */
89
+ declare const getServerSession: typeof getOAuth42Session;
90
+ /**
91
+ * Token refresh helper
92
+ */
93
+ declare function refreshAccessToken(token: any, clientId: string, clientSecret: string, issuer?: string): Promise<any>;
94
+
95
+ interface OAuth42AuthOptions {
96
+ pages?: {
97
+ signIn?: string;
98
+ error?: string;
99
+ };
100
+ callbacks?: {
101
+ authorized?: (params: {
102
+ token: any;
103
+ req: NextRequest;
104
+ }) => boolean | Promise<boolean>;
105
+ };
106
+ protectedPaths?: string[];
107
+ publicPaths?: string[];
108
+ }
109
+ /**
110
+ * Middleware helper for protecting routes with OAuth42
111
+ */
112
+ declare function withOAuth42Auth(options?: OAuth42AuthOptions): (req: NextRequest) => Promise<NextResponse<unknown>>;
113
+ /**
114
+ * Helper to create middleware configuration
115
+ */
116
+ declare function createMiddlewareConfig(protectedPaths?: string[], publicPaths?: string[]): {
117
+ matcher: string[];
118
+ protectedPaths: string[];
119
+ publicPaths: string[];
120
+ };
121
+
122
+ export { type CreateAuthOptions as C, OAuth42Provider as O, type OAuth42Profile as a, type OAuth42ProviderOptions as b, createAuth as c, createMiddlewareConfig as d, type OAuth42AuthOptions as e, getOAuth42Session as f, getServerSession as g, withOAuth42Session as h, withOAuth42ServerSideProps as i, createHandlers as j, refreshAccessToken as r, withOAuth42Auth as w };
@@ -0,0 +1,44 @@
1
+ export { C as CreateAuthOptions, e as OAuth42AuthOptions, a as OAuth42Profile, O as OAuth42Provider, b as OAuth42ProviderOptions, c as createAuth, d as createMiddlewareConfig, f as getOAuth42Session, g as getServerSession, r as refreshAccessToken, w as withOAuth42Auth, i as withOAuth42ServerSideProps, h as withOAuth42Session } from './index-xJCMwWtK.mjs';
2
+ import { DefaultSession } from 'next-auth';
3
+ export { Session, User } from 'next-auth';
4
+ import 'next';
5
+ import 'next-auth/providers/oauth';
6
+ import 'next/server';
7
+
8
+ declare module 'next-auth' {
9
+ interface Session extends DefaultSession {
10
+ accessToken?: string;
11
+ idToken?: string;
12
+ user?: {
13
+ id?: string;
14
+ email?: string | null;
15
+ name?: string | null;
16
+ image?: string | null;
17
+ username?: string;
18
+ emailVerified?: boolean;
19
+ };
20
+ }
21
+ interface JWT {
22
+ accessToken?: string;
23
+ refreshToken?: string;
24
+ idToken?: string;
25
+ expiresAt?: number;
26
+ username?: string;
27
+ emailVerified?: boolean;
28
+ error?: string;
29
+ }
30
+ }
31
+ interface OAuth42Config {
32
+ clientId: string;
33
+ clientSecret?: string;
34
+ issuer?: string;
35
+ authorizationUrl?: string;
36
+ tokenUrl?: string;
37
+ userinfoUrl?: string;
38
+ jwksUrl?: string;
39
+ scopes?: string[];
40
+ pkceEnabled?: boolean;
41
+ debug?: boolean;
42
+ }
43
+
44
+ export type { OAuth42Config };
@@ -0,0 +1,44 @@
1
+ export { C as CreateAuthOptions, e as OAuth42AuthOptions, a as OAuth42Profile, O as OAuth42Provider, b as OAuth42ProviderOptions, c as createAuth, d as createMiddlewareConfig, f as getOAuth42Session, g as getServerSession, r as refreshAccessToken, w as withOAuth42Auth, i as withOAuth42ServerSideProps, h as withOAuth42Session } from './index-xJCMwWtK.js';
2
+ import { DefaultSession } from 'next-auth';
3
+ export { Session, User } from 'next-auth';
4
+ import 'next';
5
+ import 'next-auth/providers/oauth';
6
+ import 'next/server';
7
+
8
+ declare module 'next-auth' {
9
+ interface Session extends DefaultSession {
10
+ accessToken?: string;
11
+ idToken?: string;
12
+ user?: {
13
+ id?: string;
14
+ email?: string | null;
15
+ name?: string | null;
16
+ image?: string | null;
17
+ username?: string;
18
+ emailVerified?: boolean;
19
+ };
20
+ }
21
+ interface JWT {
22
+ accessToken?: string;
23
+ refreshToken?: string;
24
+ idToken?: string;
25
+ expiresAt?: number;
26
+ username?: string;
27
+ emailVerified?: boolean;
28
+ error?: string;
29
+ }
30
+ }
31
+ interface OAuth42Config {
32
+ clientId: string;
33
+ clientSecret?: string;
34
+ issuer?: string;
35
+ authorizationUrl?: string;
36
+ tokenUrl?: string;
37
+ userinfoUrl?: string;
38
+ jwksUrl?: string;
39
+ scopes?: string[];
40
+ pkceEnabled?: boolean;
41
+ debug?: boolean;
42
+ }
43
+
44
+ export type { OAuth42Config };
package/dist/index.js ADDED
@@ -0,0 +1,305 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ OAuth42Provider: () => OAuth42Provider,
34
+ createAuth: () => createAuth,
35
+ createMiddlewareConfig: () => createMiddlewareConfig,
36
+ getOAuth42Session: () => getOAuth42Session,
37
+ getServerSession: () => getServerSession,
38
+ refreshAccessToken: () => refreshAccessToken,
39
+ withOAuth42Auth: () => withOAuth42Auth,
40
+ withOAuth42ServerSideProps: () => withOAuth42ServerSideProps,
41
+ withOAuth42Session: () => withOAuth42Session
42
+ });
43
+ module.exports = __toCommonJS(src_exports);
44
+
45
+ // src/provider.ts
46
+ function OAuth42Provider(options) {
47
+ const issuer = options.issuer || process.env.OAUTH42_ISSUER || "https://oauth42.com";
48
+ const baseUrl = issuer.replace(/\/$/, "");
49
+ return {
50
+ id: "oauth42",
51
+ name: "OAuth42",
52
+ type: "oauth",
53
+ version: "2.0",
54
+ // Use OIDC discovery to automatically find endpoints
55
+ wellKnown: `${baseUrl}/.well-known/openid-configuration`,
56
+ // Also set individual endpoints for compatibility
57
+ authorization: {
58
+ url: `${baseUrl}/oauth2/authorize`,
59
+ params: {
60
+ scope: (options.scopes || ["openid", "profile", "email"]).join(" "),
61
+ response_type: "code"
62
+ }
63
+ },
64
+ token: `${baseUrl}/oauth2/token`,
65
+ userinfo: `${baseUrl}/oauth2/userinfo`,
66
+ client: {
67
+ id: options.clientId,
68
+ secret: options.clientSecret,
69
+ token_endpoint_auth_method: "client_secret_post",
70
+ id_token_signed_response_alg: "HS256"
71
+ // OAuth42 uses HS256 for ID tokens
72
+ },
73
+ issuer: baseUrl,
74
+ checks: options.pkceEnabled !== false ? ["pkce", "state"] : ["state"],
75
+ profile(profile, tokens) {
76
+ return {
77
+ id: profile.sub || profile.id || profile.email,
78
+ email: profile.email,
79
+ emailVerified: profile.email_verified ? /* @__PURE__ */ new Date() : null,
80
+ name: profile.name || `${profile.given_name || ""} ${profile.family_name || ""}`.trim(),
81
+ image: profile.picture
82
+ };
83
+ },
84
+ style: {
85
+ logo: "/oauth42-logo.svg",
86
+ bg: "#1e40af",
87
+ text: "#ffffff"
88
+ },
89
+ options
90
+ };
91
+ }
92
+
93
+ // src/server/auth.ts
94
+ var import_next_auth2 = __toESM(require("next-auth"));
95
+
96
+ // src/server/session.ts
97
+ var import_next_auth = require("next-auth");
98
+ async function getOAuth42Session(...args) {
99
+ return (0, import_next_auth.getServerSession)(...args);
100
+ }
101
+ function withOAuth42Session(handler, authOptions) {
102
+ return async (req, res) => {
103
+ const session = await getOAuth42Session(req, res, authOptions);
104
+ if (!session) {
105
+ return res.status(401).json({ error: "Unauthorized" });
106
+ }
107
+ return handler(req, res, session);
108
+ };
109
+ }
110
+ function withOAuth42ServerSideProps(getServerSideProps, authOptions) {
111
+ return async (context) => {
112
+ const session = await getOAuth42Session(
113
+ context.req,
114
+ context.res,
115
+ authOptions
116
+ );
117
+ if (!session) {
118
+ return {
119
+ redirect: {
120
+ destination: "/auth/signin",
121
+ permanent: false
122
+ }
123
+ };
124
+ }
125
+ return getServerSideProps(context, session);
126
+ };
127
+ }
128
+
129
+ // src/server/auth.ts
130
+ var NextAuth = import_next_auth2.default.default || import_next_auth2.default;
131
+ function createAuth(options = {}) {
132
+ const clientId = options.clientId || process.env.OAUTH42_CLIENT_ID;
133
+ const clientSecret = options.clientSecret || process.env.OAUTH42_CLIENT_SECRET;
134
+ if (!clientId || !clientSecret) {
135
+ throw new Error(
136
+ "OAuth42 client credentials are required. Set OAUTH42_CLIENT_ID and OAUTH42_CLIENT_SECRET environment variables or pass them in the options."
137
+ );
138
+ }
139
+ const authOptions = {
140
+ providers: [
141
+ OAuth42Provider({
142
+ clientId,
143
+ clientSecret,
144
+ issuer: options.issuer,
145
+ scopes: options.scopes,
146
+ pkceEnabled: options.pkceEnabled
147
+ })
148
+ ],
149
+ callbacks: {
150
+ async jwt({ token, account, profile }) {
151
+ if (account) {
152
+ token.accessToken = account.access_token;
153
+ token.refreshToken = account.refresh_token;
154
+ token.expiresAt = account.expires_at;
155
+ token.idToken = account.id_token;
156
+ }
157
+ if (profile) {
158
+ const oauth42Profile = profile;
159
+ token.email = oauth42Profile.email;
160
+ token.username = oauth42Profile.username;
161
+ token.emailVerified = oauth42Profile.email_verified;
162
+ }
163
+ if (options.callbacks?.jwt) {
164
+ return options.callbacks.jwt({ token, account, profile });
165
+ }
166
+ return token;
167
+ },
168
+ async session({ session, token }) {
169
+ session.accessToken = token.accessToken;
170
+ session.idToken = token.idToken;
171
+ if (session.user) {
172
+ session.user.email = token.email;
173
+ session.user.username = token.username;
174
+ session.user.emailVerified = token.emailVerified;
175
+ }
176
+ if (options.callbacks?.session) {
177
+ return options.callbacks.session({ session, token });
178
+ }
179
+ return session;
180
+ },
181
+ ...options.callbacks
182
+ },
183
+ pages: {
184
+ signIn: "/auth/signin",
185
+ signOut: "/auth/signout",
186
+ error: "/auth/error",
187
+ ...options.pages
188
+ },
189
+ session: {
190
+ strategy: "jwt",
191
+ ...options.session
192
+ },
193
+ debug: options.debug || process.env.NODE_ENV === "development",
194
+ secret: process.env.NEXTAUTH_SECRET
195
+ };
196
+ return {
197
+ auth: authOptions,
198
+ handlers: NextAuth(authOptions)
199
+ };
200
+ }
201
+ var getServerSession = getOAuth42Session;
202
+ async function refreshAccessToken(token, clientId, clientSecret, issuer) {
203
+ try {
204
+ const baseUrl = issuer || process.env.OAUTH42_ISSUER || "https://oauth42.com";
205
+ const tokenUrl = `${baseUrl}/oauth2/token`;
206
+ const fetchOptions = {
207
+ method: "POST",
208
+ headers: {
209
+ "Content-Type": "application/x-www-form-urlencoded"
210
+ },
211
+ body: new URLSearchParams({
212
+ grant_type: "refresh_token",
213
+ refresh_token: token.refreshToken,
214
+ client_id: clientId,
215
+ client_secret: clientSecret
216
+ })
217
+ };
218
+ if (process.env.NODE_ENV !== "production" && tokenUrl.startsWith("https://")) {
219
+ const https = await import("https");
220
+ fetchOptions.agent = new https.Agent({
221
+ rejectUnauthorized: false
222
+ });
223
+ }
224
+ const response = await fetch(tokenUrl, fetchOptions);
225
+ const refreshedTokens = await response.json();
226
+ if (!response.ok) {
227
+ throw refreshedTokens;
228
+ }
229
+ return {
230
+ ...token,
231
+ accessToken: refreshedTokens.access_token,
232
+ refreshToken: refreshedTokens.refresh_token ?? token.refreshToken,
233
+ // Store expiration time in seconds (Unix timestamp)
234
+ expiresAt: Math.floor(Date.now() / 1e3) + (refreshedTokens.expires_in || 3600),
235
+ // Explicitly remove any error property on successful refresh
236
+ error: void 0
237
+ };
238
+ } catch (error) {
239
+ console.error("Failed to refresh access token:", error);
240
+ return {
241
+ ...token,
242
+ error: "RefreshAccessTokenError"
243
+ };
244
+ }
245
+ }
246
+
247
+ // src/server/middleware.ts
248
+ var import_server = require("next/server");
249
+ var import_jwt = require("next-auth/jwt");
250
+ function withOAuth42Auth(options = {}) {
251
+ return async function middleware(req) {
252
+ const token = await (0, import_jwt.getToken)({
253
+ req,
254
+ secret: process.env.NEXTAUTH_SECRET
255
+ });
256
+ const pathname = req.nextUrl.pathname;
257
+ if (options.publicPaths?.some((path) => pathname.startsWith(path))) {
258
+ return import_server.NextResponse.next();
259
+ }
260
+ const needsProtection = options.protectedPaths ? options.protectedPaths.some((path) => pathname.startsWith(path)) : true;
261
+ if (!needsProtection) {
262
+ return import_server.NextResponse.next();
263
+ }
264
+ let isAuthorized = !!token;
265
+ if (options.callbacks?.authorized) {
266
+ isAuthorized = await options.callbacks.authorized({ token, req });
267
+ }
268
+ if (!isAuthorized) {
269
+ const signInUrl = options.pages?.signIn || "/auth/signin";
270
+ const url = new URL(signInUrl, req.url);
271
+ url.searchParams.set("callbackUrl", pathname);
272
+ return import_server.NextResponse.redirect(url);
273
+ }
274
+ return import_server.NextResponse.next();
275
+ };
276
+ }
277
+ function createMiddlewareConfig(protectedPaths = ["/protected"], publicPaths = ["/auth", "/api/auth"]) {
278
+ return {
279
+ matcher: [
280
+ /*
281
+ * Match all request paths except for the ones starting with:
282
+ * - _next/static (static files)
283
+ * - _next/image (image optimization files)
284
+ * - favicon.ico (favicon file)
285
+ * - public folder
286
+ */
287
+ "/((?!_next/static|_next/image|favicon.ico|public).*)"
288
+ ],
289
+ protectedPaths,
290
+ publicPaths
291
+ };
292
+ }
293
+ // Annotate the CommonJS export names for ESM import in node:
294
+ 0 && (module.exports = {
295
+ OAuth42Provider,
296
+ createAuth,
297
+ createMiddlewareConfig,
298
+ getOAuth42Session,
299
+ getServerSession,
300
+ refreshAccessToken,
301
+ withOAuth42Auth,
302
+ withOAuth42ServerSideProps,
303
+ withOAuth42Session
304
+ });
305
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/provider.ts","../src/server/auth.ts","../src/server/session.ts","../src/server/middleware.ts"],"sourcesContent":["// Main exports\nexport { OAuth42Provider } from './provider';\nexport type { OAuth42Profile, OAuth42ProviderOptions } from './provider';\n\n// Server-side exports\nexport { createAuth, getServerSession, refreshAccessToken } from './server/auth';\nexport type { CreateAuthOptions } from './server/auth';\n\nexport { withOAuth42Auth, createMiddlewareConfig } from './server/middleware';\nexport type { OAuth42AuthOptions } from './server/middleware';\n\nexport { getOAuth42Session, withOAuth42Session, withOAuth42ServerSideProps } from './server/session';\n\n// Type exports\nexport type { OAuth42Config } from './types';\n\n// Re-export NextAuth types for convenience\nexport type { Session, User } from 'next-auth';","import type { OAuthConfig, OAuthUserConfig } from 'next-auth/providers/oauth';\n\nexport interface OAuth42Profile {\n sub: string;\n email: string;\n email_verified?: boolean;\n name?: string;\n given_name?: string;\n family_name?: string;\n picture?: string;\n username?: string;\n id?: string;\n}\n\nexport interface OAuth42ProviderOptions {\n clientId: string;\n clientSecret: string;\n issuer?: string;\n authorizationUrl?: string;\n tokenUrl?: string;\n userinfoUrl?: string;\n scopes?: string[];\n pkceEnabled?: boolean;\n}\n\nexport function OAuth42Provider<P extends OAuth42Profile>(\n options: OAuthUserConfig<P> & Partial<OAuth42ProviderOptions>\n): OAuthConfig<P> {\n const issuer = options.issuer || process.env.OAUTH42_ISSUER || 'https://oauth42.com';\n const baseUrl = issuer.replace(/\\/$/, '');\n \n return {\n id: 'oauth42',\n name: 'OAuth42',\n type: 'oauth',\n version: '2.0',\n \n // Use OIDC discovery to automatically find endpoints\n wellKnown: `${baseUrl}/.well-known/openid-configuration`,\n \n // Also set individual endpoints for compatibility\n authorization: {\n url: `${baseUrl}/oauth2/authorize`,\n params: {\n scope: (options.scopes || ['openid', 'profile', 'email']).join(' '),\n response_type: 'code',\n },\n },\n token: `${baseUrl}/oauth2/token`,\n userinfo: `${baseUrl}/oauth2/userinfo`,\n \n client: {\n id: options.clientId,\n secret: options.clientSecret,\n token_endpoint_auth_method: 'client_secret_post',\n id_token_signed_response_alg: 'HS256', // OAuth42 uses HS256 for ID tokens\n },\n \n issuer: baseUrl,\n \n checks: options.pkceEnabled !== false ? ['pkce', 'state'] : ['state'],\n \n profile(profile: OAuth42Profile, tokens: any) {\n return {\n id: profile.sub || profile.id || profile.email,\n email: profile.email,\n emailVerified: profile.email_verified ? new Date() : null,\n name: profile.name || `${profile.given_name || ''} ${profile.family_name || ''}`.trim(),\n image: profile.picture,\n };\n },\n \n style: {\n logo: '/oauth42-logo.svg',\n bg: '#1e40af',\n text: '#ffffff',\n },\n \n options,\n };\n}","import NextAuthDefault from 'next-auth';\nimport type { NextAuthOptions } from 'next-auth';\nimport { OAuth42Provider, OAuth42Profile } from '../provider';\nimport { getOAuth42Session } from './session';\n\n// Handle both CommonJS and ESM exports\nconst NextAuth = (NextAuthDefault as any).default || NextAuthDefault;\n\nexport { type NextAuthOptions };\n\nexport interface CreateAuthOptions {\n clientId?: string;\n clientSecret?: string;\n issuer?: string;\n scopes?: string[];\n pkceEnabled?: boolean;\n debug?: boolean;\n callbacks?: NextAuthOptions['callbacks'];\n pages?: NextAuthOptions['pages'];\n session?: NextAuthOptions['session'];\n}\n\n/**\n * Create a pre-configured NextAuth instance for OAuth42\n * This provides a simplified setup with sensible defaults\n */\nexport function createAuth(options: CreateAuthOptions = {}) {\n const clientId = options.clientId || process.env.OAUTH42_CLIENT_ID;\n const clientSecret = options.clientSecret || process.env.OAUTH42_CLIENT_SECRET;\n \n if (!clientId || !clientSecret) {\n throw new Error(\n 'OAuth42 client credentials are required. ' +\n 'Set OAUTH42_CLIENT_ID and OAUTH42_CLIENT_SECRET environment variables ' +\n 'or pass them in the options.'\n );\n }\n \n const authOptions: NextAuthOptions = {\n providers: [\n OAuth42Provider({\n clientId,\n clientSecret,\n issuer: options.issuer,\n scopes: options.scopes,\n pkceEnabled: options.pkceEnabled,\n }),\n ],\n \n callbacks: {\n async jwt({ token, account, profile }) {\n // Store OAuth tokens in the JWT\n if (account) {\n token.accessToken = account.access_token;\n token.refreshToken = account.refresh_token;\n token.expiresAt = account.expires_at;\n token.idToken = account.id_token;\n }\n \n // Add user profile data\n if (profile) {\n const oauth42Profile = profile as OAuth42Profile;\n token.email = oauth42Profile.email;\n token.username = oauth42Profile.username;\n token.emailVerified = oauth42Profile.email_verified;\n }\n \n // Call custom callback if provided\n if (options.callbacks?.jwt) {\n return options.callbacks.jwt({ token, account, profile } as any);\n }\n \n return token;\n },\n \n async session({ session, token }) {\n // Add OAuth42-specific data to session\n session.accessToken = token.accessToken as string;\n session.idToken = token.idToken as string;\n \n if (session.user) {\n session.user.email = token.email as string;\n session.user.username = token.username as string;\n session.user.emailVerified = token.emailVerified as boolean;\n }\n \n // Call custom callback if provided\n if (options.callbacks?.session) {\n return options.callbacks.session({ session, token } as any);\n }\n \n return session;\n },\n \n ...options.callbacks,\n },\n \n pages: {\n signIn: '/auth/signin',\n signOut: '/auth/signout',\n error: '/auth/error',\n ...options.pages,\n },\n \n session: {\n strategy: 'jwt',\n ...options.session,\n },\n \n debug: options.debug || process.env.NODE_ENV === 'development',\n \n secret: process.env.NEXTAUTH_SECRET,\n };\n \n // Return the configuration and a function to create handlers\n return {\n auth: authOptions,\n handlers: NextAuth(authOptions),\n };\n}\n\n/**\n * Create NextAuth handlers for API routes\n */\nexport function createHandlers(authOptions: NextAuthOptions) {\n const handler = NextAuth(authOptions);\n return { GET: handler, POST: handler };\n}\n\n/**\n * Helper to get the current session server-side\n * @deprecated Use getOAuth42Session instead - this is now just an alias for backward compatibility\n * \n * This function is maintained for backward compatibility but internally\n * calls getOAuth42Session which properly handles both App Router and Pages Router\n */\nexport const getServerSession = getOAuth42Session;\n\n/**\n * Token refresh helper\n */\nexport async function refreshAccessToken(token: any, clientId: string, clientSecret: string, issuer?: string) {\n try {\n const baseUrl = issuer || process.env.OAUTH42_ISSUER || 'https://oauth42.com';\n const tokenUrl = `${baseUrl}/oauth2/token`;\n \n // In development, we need to handle self-signed certificates\n const fetchOptions: any = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: token.refreshToken,\n client_id: clientId,\n client_secret: clientSecret,\n }),\n };\n \n // Add agent for self-signed certificates in development\n if (process.env.NODE_ENV !== 'production' && tokenUrl.startsWith('https://')) {\n const https = await import('https');\n fetchOptions.agent = new https.Agent({\n rejectUnauthorized: false\n });\n }\n \n const response = await fetch(tokenUrl, fetchOptions);\n const refreshedTokens = await response.json();\n \n if (!response.ok) {\n throw refreshedTokens;\n }\n \n return {\n ...token,\n accessToken: refreshedTokens.access_token,\n refreshToken: refreshedTokens.refresh_token ?? token.refreshToken,\n // Store expiration time in seconds (Unix timestamp)\n expiresAt: Math.floor(Date.now() / 1000) + (refreshedTokens.expires_in || 3600),\n // Explicitly remove any error property on successful refresh\n error: undefined,\n };\n } catch (error) {\n console.error('Failed to refresh access token:', error);\n return {\n ...token,\n error: 'RefreshAccessTokenError',\n };\n }\n}","import { getServerSession as getNextAuthSession } from 'next-auth';\nimport { NextAuthOptions } from 'next-auth';\nimport { GetServerSidePropsContext, NextApiRequest, NextApiResponse } from 'next';\n\n/**\n * Get the OAuth42 session server-side\n * \n * This is the primary method for retrieving sessions in OAuth42 SDK.\n * Supports both Pages Router and App Router:\n * \n * App Router:\n * ```ts\n * const session = await getOAuth42Session(authOptions);\n * ```\n * \n * Pages Router:\n * ```ts\n * const session = await getOAuth42Session(req, res, authOptions);\n * ```\n */\nexport async function getOAuth42Session(\n ...args: \n | [GetServerSidePropsContext['req'], GetServerSidePropsContext['res'], NextAuthOptions]\n | [NextApiRequest, NextApiResponse, NextAuthOptions]\n | [NextAuthOptions]\n) {\n return getNextAuthSession(...args as any);\n}\n\n/**\n * Helper for protecting API routes\n */\nexport function withOAuth42Session(\n handler: (req: NextApiRequest, res: NextApiResponse, session: any) => Promise<void> | void,\n authOptions: NextAuthOptions\n) {\n return async (req: NextApiRequest, res: NextApiResponse) => {\n const session = await getOAuth42Session(req, res, authOptions);\n \n if (!session) {\n return res.status(401).json({ error: 'Unauthorized' });\n }\n \n return handler(req, res, session);\n };\n}\n\n/**\n * Helper for protecting server-side props\n */\nexport function withOAuth42ServerSideProps(\n getServerSideProps: (\n context: GetServerSidePropsContext,\n session: any\n ) => Promise<any>,\n authOptions: NextAuthOptions\n) {\n return async (context: GetServerSidePropsContext) => {\n const session = await getOAuth42Session(\n context.req,\n context.res,\n authOptions\n );\n \n if (!session) {\n return {\n redirect: {\n destination: '/auth/signin',\n permanent: false,\n },\n };\n }\n \n return getServerSideProps(context, session);\n };\n}","import { NextRequest, NextResponse } from 'next/server';\nimport { getToken } from 'next-auth/jwt';\n\nexport interface OAuth42AuthOptions {\n pages?: {\n signIn?: string;\n error?: string;\n };\n callbacks?: {\n authorized?: (params: { token: any; req: NextRequest }) => boolean | Promise<boolean>;\n };\n protectedPaths?: string[];\n publicPaths?: string[];\n}\n\n/**\n * Middleware helper for protecting routes with OAuth42\n */\nexport function withOAuth42Auth(options: OAuth42AuthOptions = {}) {\n return async function middleware(req: NextRequest) {\n const token = await getToken({ \n req: req as any, \n secret: process.env.NEXTAUTH_SECRET \n });\n \n const pathname = req.nextUrl.pathname;\n \n // Check if path is explicitly public\n if (options.publicPaths?.some(path => pathname.startsWith(path))) {\n return NextResponse.next();\n }\n \n // Check if path needs protection\n const needsProtection = options.protectedPaths\n ? options.protectedPaths.some(path => pathname.startsWith(path))\n : true; // Default to protecting all paths\n \n if (!needsProtection) {\n return NextResponse.next();\n }\n \n // Check authorization\n let isAuthorized = !!token;\n \n if (options.callbacks?.authorized) {\n isAuthorized = await options.callbacks.authorized({ token, req });\n }\n \n if (!isAuthorized) {\n const signInUrl = options.pages?.signIn || '/auth/signin';\n const url = new URL(signInUrl, req.url);\n url.searchParams.set('callbackUrl', pathname);\n return NextResponse.redirect(url);\n }\n \n return NextResponse.next();\n };\n}\n\n/**\n * Helper to create middleware configuration\n */\nexport function createMiddlewareConfig(\n protectedPaths: string[] = ['/protected'],\n publicPaths: string[] = ['/auth', '/api/auth']\n) {\n return {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - favicon.ico (favicon file)\n * - public folder\n */\n '/((?!_next/static|_next/image|favicon.ico|public).*)',\n ],\n protectedPaths,\n publicPaths,\n };\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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