swadhinbiswas feat: finalize platform polish - discussions, gists, webhook queue, realtime, push-mirror, auth/metrics hardening · 8/28/2026
f02976d
193 lines · 5.0 KB
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
/**
 * Auth API - Login
 */
import { getDatabase, schema } from "@/db";
import { sessions, users } from "@/db/schema";
import { error, parseBody, success, unauthorized } from "@/lib/api";
import {
  createSession,
  createToken,
  verify2FAToken,
  verifyPassword,
} from "@/lib/auth";
import { withErrorHandler } from "@/lib/errors";
import {
  clearLoginFailures,
  ipKey,
  isLockedOut,
  recordLoginFailure,
  userIpKey,
} from "@/lib/login-lockout";
import { logger } from "@/lib/logger";
import { applyRateLimit } from "@/middleware/rate-limit";
import { type APIRoute } from "astro";
import { eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { z } from "zod";

const loginSchema = z.object({
  login: z.string(), // username or email
  password: z.string(),
  totpCode: z.string().optional(), // 2FA code
});

export const POST: APIRoute = withErrorHandler(async ({ request, cookies }) => {
  // Apply rate limiting for authentication endpoints
  const rateLimitResponse = await applyRateLimit(request, "auth");
  if (rateLimitResponse) {
    return rateLimitResponse;
  }

  // Parse and validate request body
  const parsed = await parseBody(request, loginSchema);
  if ("error" in parsed) return parsed.error;

  const { login, password, totpCode } = parsed.data;
  const db = getDatabase() as NodePgDatabase<typeof schema>;

  const ipAddress =
    request.headers.get("X-Forwarded-For")?.split(",")[0].trim() ||
    request.headers.get("X-Real-IP") ||
    undefined;

  // Brute-force lockout: check per-credentials and per-IP limits
  const userLockKey = userIpKey(login, ipAddress);
  const ipLockKey = ipKey(ipAddress);
  const [userLockout, ipLockout] = await Promise.all([
    isLockedOut(userLockKey),
    isLockedOut(ipLockKey),
  ]);

  if (userLockout.locked || ipLockout.locked) {
    const retryAfter = Math.max(
      userLockout.retryAfterSecs ?? 0,
      ipLockout.retryAfterSecs ?? 0,
    );
    logger.warn(
      { login: userLockKey, ip: ipLockKey },
      "Login blocked: too many failed attempts",
    );
    const response = error("RATE_LIMITED", "Too many failed attempts", 429);
    response.headers.set("Retry-After", String(retryAfter));
    return response;
  }

  // Find user by username or email
  const user = await db.query.users.findFirst({
    where: (users, { or, eq }) =>
      or(eq(users.username, login), eq(users.email, login)),
  });

  if (!user) {
    await Promise.all([
      recordLoginFailure(userLockKey),
      recordLoginFailure(ipLockKey),
    ]);
    return unauthorized("Invalid credentials");
  }

  // Check if account is active
  if (!user.isActive) {
    return unauthorized("Account is disabled");
  }

  // Verify password
  if (!user.passwordHash) {
    await Promise.all([
      recordLoginFailure(userLockKey),
      recordLoginFailure(ipLockKey),
    ]);
    return unauthorized("Invalid credentials");
  }

  const isValid = await verifyPassword(password, user.passwordHash);

  if (!isValid) {
    logger.warn({ user: user.username }, "Invalid password attempt");
    await Promise.all([
      recordLoginFailure(userLockKey),
      recordLoginFailure(ipLockKey),
    ]);
    return unauthorized("Invalid credentials");
  }

  // Check 2FA if enabled
  if (user.twoFactorEnabled) {
    if (!totpCode) {
      return success({
        requiresTwoFactor: true,
        message: "Two-factor authentication required",
      });
    }

    if (!user.twoFactorSecret) {
      throw new Error("2FA configuration error"); // Let error handler catch it
    }

    const isValid2FA = verify2FAToken(totpCode, user.twoFactorSecret);
    if (!isValid2FA) {
      return unauthorized("Invalid 2FA code");
    }
  }

  // Create session
  const userAgent = request.headers.get("User-Agent") || undefined;

  await Promise.all([
    clearLoginFailures(userLockKey),
    clearLoginFailures(ipLockKey),
  ]);

  const session = await createSession(user.id, userAgent, ipAddress);

  // Store session in database
  await db.insert(sessions).values({
    id: session.id,
    userId: user.id,
    token: session.token,
    userAgent: session.userAgent,
    ipAddress: session.ipAddress,
    expiresAt: new Date(session.expiresAt),
    createdAt: new Date(session.createdAt),
  });

  // Update last login
  await db
    .update(users)
    .set({ lastLoginAt: new Date() })
    .where(eq(users.id, user.id));

  // Create JWT token
  const token = await createToken({
    userId: user.id,
    username: user.username,
    email: user.email,
    isAdmin: user.isAdmin || false,
    sessionId: session.id,
  });

  // Set session cookie
  cookies.set("och_session", token, {
    path: "/",
    httpOnly: true,
    secure: import.meta.env.PROD,
    sameSite: "lax",
    expires: new Date(session.expiresAt),
  });

  logger.info({ userId: user.id }, "User logged in");

  return success({
    user: {
      id: user.id,
      username: user.username,
      email: user.email,
      displayName: user.displayName,
      avatarUrl: user.avatarUrl,
      isAdmin: user.isAdmin,
    },
    token,
    expiresAt: session.expiresAt,
  });
});