File size: 10,413 Bytes
15b7bb6
 
5a0b87c
e8f0b97
 
5a0b87c
e8f0b97
3e61ed6
e8f0b97
 
 
 
 
 
5a0b87c
e8f0b97
 
 
 
 
 
 
 
 
 
 
 
5a0b87c
 
e8f0b97
 
 
 
 
5a0b87c
 
e8f0b97
 
 
 
 
5a0b87c
 
e8f0b97
 
 
 
 
 
5a0b87c
e8f0b97
 
5a0b87c
 
e8f0b97
5a0b87c
e8f0b97
 
5a0b87c
e8f0b97
 
5a0b87c
 
e8f0b97
5a0b87c
 
 
 
 
 
 
 
 
 
 
e8f0b97
 
5a0b87c
 
e8f0b97
5a0b87c
 
 
 
 
 
 
 
 
 
 
e8f0b97
 
5a0b87c
 
 
 
e8f0b97
5a0b87c
 
 
 
 
 
 
 
 
 
 
e8f0b97
 
 
 
 
 
 
 
 
 
 
 
 
5a0b87c
e8f0b97
 
5a0b87c
e8f0b97
 
 
 
 
 
 
 
5a0b87c
e8f0b97
5a0b87c
e8f0b97
5a0b87c
e8f0b97
 
5a0b87c
 
 
 
e8f0b97
 
 
 
 
 
 
 
 
 
 
 
5a0b87c
 
e8f0b97
 
5a0b87c
 
e8f0b97
5a0b87c
 
e8f0b97
 
 
5a0b87c
 
e8f0b97
5a0b87c
e8f0b97
5a0b87c
e8f0b97
 
5a0b87c
 
 
 
e8f0b97
5a0b87c
 
 
 
e8f0b97
 
 
 
 
 
 
 
 
 
 
 
5a0b87c
 
e8f0b97
 
 
 
 
 
 
 
 
 
 
5a0b87c
 
e8f0b97
5a0b87c
e8f0b97
 
 
 
 
 
5a0b87c
e8f0b97
5a0b87c
e8f0b97
5a0b87c
e8f0b97
 
5a0b87c
 
e8f0b97
5a0b87c
e8f0b97
5a0b87c
e8f0b97
 
5a0b87c
 
e8f0b97
5a0b87c
 
e8f0b97
5a0b87c
 
e8f0b97
5a0b87c
e8f0b97
5a0b87c
e8f0b97
 
 
 
 
5a0b87c
 
 
e8f0b97
 
 
cf7a80b
5dc2f11
5a0b87c
 
 
 
 
e8f0b97
 
 
 
 
 
 
 
 
 
 
3e61ed6
 
 
 
e8f0b97
 
 
 
 
 
5a0b87c
3e61ed6
5a0b87c
e8f0b97
 
 
 
 
 
 
 
 
 
 
5a0b87c
 
 
 
 
3e61ed6
5a0b87c
0ba2011
e8f0b97
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import NextAuth, { type DefaultSession } from "next-auth";
import "next-auth/jwt";
import GitHubProvider from "next-auth/providers/github";
import CredentialsProvider from "next-auth/providers/credentials";
import { client as db } from "@/lib/db";
import { randomUUID } from "crypto";
import type { Adapter, AdapterUser, AdapterAccount, AdapterSession, VerificationToken } from "@auth/core/adapters";
import { AUTH_CONFIG, ROUTES } from "@/constants";

/**
 * 🛰️ CodeVerse Authentication Core
 * Final Production-Grade Implementation (April 2026).
 * Enforces 100% strict typing, JWT strategy, and local bypass resilience.
 */

// --- 🧩 Type Augmentations ---
declare module "next-auth" {
  interface Session {
    user: {
      id: string;
      github_username?: string | null;
    } & DefaultSession["user"];
  }

  interface User {
    github_username?: string | null;
  }
}

declare module "next-auth/jwt" {
  interface JWT {
    id?: string;
    github_username?: string | null;
  }
}

/**
 * 🛠️ Extended Types for Adapter Internal Use
 */
interface CodeVerseAdapterUser extends AdapterUser {
  github_username?: string | null;
}

// LibSQL input value type for explicit casting
type LibSQLValue = string | number | bigint | boolean | Uint8Array | null;

// --- 🛠️ Custom Adapter Implementation ---
const TursoAdapter: Adapter = {
  async createUser(user: AdapterUser): Promise<AdapterUser> {
    const id = randomUUID();
    const github_username = (user as CodeVerseAdapterUser).github_username ?? null;
    
    await db.execute({
      sql: "INSERT INTO users (id, name, email, image, github_username) VALUES (?, ?, ?, ?, ?)",
      args: [id, user.name ?? null, user.email, user.image ?? null, github_username] as LibSQLValue[],
    });
    
    return { ...user, id };
  },

  async getUser(id: string): Promise<AdapterUser | null> {
    const res = await db.execute({
      sql: "SELECT * FROM users WHERE id = ?",
      args: [id] as LibSQLValue[],
    });
    if (res.rows.length === 0) return null;
    const row = res.rows[0];
    return {
      id: row.id as string,
      email: row.email as string,
      emailVerified: null,
      name: row.name as string | null,
      image: row.image as string | null,
    };
  },

  async getUserByEmail(email: string): Promise<AdapterUser | null> {
    const res = await db.execute({
      sql: "SELECT * FROM users WHERE email = ?",
      args: [email] as LibSQLValue[],
    });
    if (res.rows.length === 0) return null;
    const row = res.rows[0];
    return {
      id: row.id as string,
      email: row.email as string,
      emailVerified: null,
      name: row.name as string | null,
      image: row.image as string | null,
    };
  },

  async getUserByAccount({ providerAccountId, provider }: { providerAccountId: string; provider: string }): Promise<AdapterUser | null> {
    const res = await db.execute({
      sql: `SELECT u.* FROM users u 
            JOIN accounts a ON u.id = a.userId 
            WHERE a.providerAccountId = ? AND a.provider = ?`,
      args: [providerAccountId, provider] as LibSQLValue[],
    });
    if (res.rows.length === 0) return null;
    const row = res.rows[0];
    return {
      id: row.id as string,
      email: row.email as string,
      emailVerified: null,
      name: row.name as string | null,
      image: row.image as string | null,
    };
  },

  async updateUser(user: Partial<AdapterUser> & { id: string }): Promise<AdapterUser> {
    const res = await db.execute({
      sql: "SELECT name, email, image FROM users WHERE id = ?",
      args: [user.id] as LibSQLValue[],
    });
    if (res.rows.length === 0) throw new Error("User not found");
    const existing = res.rows[0];

    const name = user.name ?? (existing.name as string | null);
    const email = user.email ?? (existing.email as string);
    const image = user.image ?? (existing.image as string | null);

    await db.execute({
      sql: "UPDATE users SET name = ?, email = ?, image = ? WHERE id = ?",
      args: [name, email, image, user.id] as LibSQLValue[],
    });
    
    return {
      id: user.id,
      email: email,
      emailVerified: null,
      name: name,
      image: image,
    };
  },

  async deleteUser(userId: string): Promise<void> {
    await db.execute({ sql: "DELETE FROM users WHERE id = ?", args: [userId] as LibSQLValue[] });
  },

  async linkAccount(account: AdapterAccount): Promise<void> {
    await db.execute({
      sql: `INSERT INTO accounts (id, userId, provider, providerAccountId, refresh_token, access_token, expires_at, token_type, scope, id_token, session_state)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      args: [
        randomUUID(), 
        account.userId, 
        account.provider, 
        account.providerAccountId,
        account.refresh_token ?? null, 
        account.access_token ?? null, 
        account.expires_at ?? null,
        account.token_type ?? null, 
        account.scope ?? null, 
        account.id_token ?? null, 
        account.session_state ?? null
      ] as LibSQLValue[],
    });
  },

  async unlinkAccount({ providerAccountId, provider }: { providerAccountId: string; provider: string }): Promise<void> {
    await db.execute({
      sql: "DELETE FROM accounts WHERE providerAccountId = ? AND provider = ?",
      args: [providerAccountId, provider] as LibSQLValue[],
    });
  },

  async createSession({ sessionToken, userId, expires }: { sessionToken: string; userId: string; expires: Date }): Promise<AdapterSession> {
    const id = randomUUID();
    await db.execute({
      sql: "INSERT INTO sessions (id, sessionToken, userId, expires) VALUES (?, ?, ?, ?)",
      args: [id, sessionToken, userId, expires.toISOString()] as LibSQLValue[],
    });
    return { sessionToken, userId, expires };
  },

  async getSessionAndUser(sessionToken: string): Promise<{ session: AdapterSession; user: AdapterUser } | null> {
    const res = await db.execute({
      sql: `SELECT s.sessionToken, s.userId, s.expires, u.id as u_id, u.name, u.email, u.image 
            FROM sessions s JOIN users u ON s.userId = u.id 
            WHERE s.sessionToken = ?`,
      args: [sessionToken] as LibSQLValue[],
    });
    if (res.rows.length === 0) return null;
    const row = res.rows[0];
    return {
      session: {
        sessionToken: row.sessionToken as string,
        userId: row.userId as string,
        expires: new Date(row.expires as string)
      },
      user: {
        id: row.u_id as string,
        name: row.name as string | null,
        email: row.email as string,
        image: row.image as string | null,
        emailVerified: null
      },
    };
  },

  async updateSession(session: Partial<AdapterSession> & { sessionToken: string }): Promise<AdapterSession | null | undefined> {
    const res = await db.execute({
      sql: "SELECT userId, expires FROM sessions WHERE sessionToken = ?",
      args: [session.sessionToken] as LibSQLValue[],
    });
    if (res.rows.length === 0) return null;
    const current = res.rows[0];

    const expires = session.expires?.toISOString() ?? (current.expires as string);
    
    await db.execute({
      sql: "UPDATE sessions SET expires = ? WHERE sessionToken = ?",
      args: [expires, session.sessionToken] as LibSQLValue[],
    });
    
    return {
      sessionToken: session.sessionToken,
      userId: current.userId as string,
      expires: new Date(expires)
    };
  },

  async deleteSession(sessionToken: string): Promise<void> {
    await db.execute({ sql: "DELETE FROM sessions WHERE sessionToken = ?", args: [sessionToken] as LibSQLValue[] });
  },

  async createVerificationToken({ identifier, expires, token }: { identifier: string; expires: Date; token: string }): Promise<VerificationToken | null | undefined> {
    await db.execute({
      sql: "INSERT INTO verification_tokens (identifier, token, expires) VALUES (?, ?, ?)",
      args: [identifier, token, expires.toISOString()] as LibSQLValue[],
    });
    return { identifier, expires, token };
  },

  async useVerificationToken({ identifier, token }: { identifier: string; token: string }): Promise<VerificationToken | null> {
    const res = await db.execute({
      sql: "SELECT * FROM verification_tokens WHERE identifier = ? AND token = ?",
      args: [identifier, token] as LibSQLValue[],
    });
    if (res.rows.length === 0) return null;
    
    await db.execute({
      sql: "DELETE FROM verification_tokens WHERE identifier = ? AND token = ?",
      args: [identifier, token] as LibSQLValue[],
    });
    
    const row = res.rows[0];
    return {
      identifier: row.identifier as string,
      token: row.token as string,
      expires: new Date(row.expires as string)
    };
  }
};

// --- 🚀 Auth Configuration ---
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: TursoAdapter,
  trustHost: true,
  secret: process.env.AUTH_SECRET,
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_ID ?? "",
      clientSecret: process.env.GITHUB_SECRET ?? "",
    }),
    ...(process.env.NODE_ENV === "development" || process.env.NEXT_PUBLIC_NODE_ENV === "development" ? [
      CredentialsProvider({
        id: "credentials",
        name: "Developer Bypass",
        credentials: {
          username: { label: "Username", type: "text" },
          password: { label: "Password", type: "password" }
        },
        async authorize(credentials) {
          if (credentials?.username === "dev" || credentials?.username === "guest") {
              return { 
                id: AUTH_CONFIG.DEV_USER_ID, 
                name: AUTH_CONFIG.DEV_USER_NAME, 
                email: AUTH_CONFIG.DEV_USER_EMAIL, 
                image: AUTH_CONFIG.DEV_AVATAR,
              };
          }
          return null;
        }
      })
    ] : []),
  ],
  session: { strategy: AUTH_CONFIG.SESSION_STRATEGY as "jwt" | "database" },
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id;
        token.github_username = user.github_username;
      }
      return token;
    },
    async session({ session, token }) {
      if (session.user && token.id) {
        session.user.id = token.id;
        session.user.github_username = token.github_username;
      }
      return session;
    },
  },
  pages: {
    signIn: ROUTES.LOGIN,
  },
  debug: process.env.NODE_ENV === "development",
});