chore(config): update auth, env, i18n, proxy, and dependencies
- Update src/auth.ts auth configuration - Update src/env.mjs environment variable validation - Update src/i18n/request.ts locale handling - Update src/proxy.ts middleware - Update src/next-auth.d.ts type declarations - Update package.json and package-lock.json dependencies
This commit is contained in:
201
src/auth.ts
201
src/auth.ts
@@ -1,23 +1,14 @@
|
||||
import { compare } from "bcryptjs"
|
||||
import NextAuth from "next-auth"
|
||||
import Credentials from "next-auth/providers/credentials"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { resolvePermissions } from "@/shared/lib/permissions"
|
||||
import { isRole } from "@/shared/types/permissions"
|
||||
import { logLoginEvent } from "@/shared/lib/login-logger"
|
||||
import {
|
||||
PASSWORD_RULES,
|
||||
isAccountLocked,
|
||||
} from "@/shared/lib/password-policy"
|
||||
import { RATE_LIMIT_RULES, rateLimit, rateLimitKey, resetRateLimit } from "@/shared/lib/rate-limit"
|
||||
import { normalizeBcryptHash } from "@/shared/lib/bcrypt-utils"
|
||||
import { resolveClientIp } from "@/shared/lib/http-utils"
|
||||
import {
|
||||
getOrCreatePasswordSecurity,
|
||||
recordFailedLogin,
|
||||
resetFailedLogin,
|
||||
} from "@/shared/lib/password-security-service"
|
||||
import { normalizeRole, resolvePrimaryRole } from "@/shared/lib/role-utils"
|
||||
import {
|
||||
encodePermissionsBitmap,
|
||||
decodePermissionsBitmap,
|
||||
} from "@/shared/lib/permission-bitmap"
|
||||
import { trackAuthEvent } from "@/shared/lib/track-event"
|
||||
|
||||
export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
trustHost: true,
|
||||
@@ -31,126 +22,32 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
password: { label: "Password", type: "password" },
|
||||
totpCode: { label: "2FA Code", type: "text" },
|
||||
},
|
||||
// audit-P1-3 重构:authorize 回调原混合 7 类职责(107 行),
|
||||
// 已抽取至 modules/auth/services/login-service.ts 的 authenticateUser 函数。
|
||||
// 此处为薄包装,仅负责动态 import(避免 server-only 模块在模块评估期加载)
|
||||
// 与委托调用。所有登录逻辑(速率限制/账户锁定/密码校验/2FA/角色加载)均在
|
||||
// login-service 中实现,可独立测试。
|
||||
authorize: async (credentials) => {
|
||||
const email = String(credentials?.email ?? "").trim().toLowerCase()
|
||||
const password = String(credentials?.password ?? "")
|
||||
const totpCode = String(credentials?.totpCode ?? "").trim()
|
||||
if (!email || !password) return null
|
||||
|
||||
// Rate limit by IP + email to slow brute-force attempts
|
||||
const clientIp = await resolveClientIp()
|
||||
const loginLimitKey = rateLimitKey("login", `${clientIp}:${email}`)
|
||||
const limit = rateLimit({
|
||||
key: loginLimitKey,
|
||||
...RATE_LIMIT_RULES.LOGIN,
|
||||
})
|
||||
if (!limit.success) {
|
||||
await logLoginEvent({
|
||||
userEmail: email,
|
||||
action: "signin",
|
||||
status: "failure",
|
||||
errorMessage: "Rate limit exceeded",
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
const [{ db }, { users, roles, usersToRoles, passwordSecurity }] = await Promise.all([
|
||||
import("@/shared/db"),
|
||||
import("@/shared/db/schema"),
|
||||
])
|
||||
|
||||
const user = await db.query.users.findFirst({
|
||||
where: eq(users.email, email),
|
||||
})
|
||||
if (!user) return null
|
||||
|
||||
// Account lockout check
|
||||
const security = await getOrCreatePasswordSecurity(db, passwordSecurity, user.id)
|
||||
const lastFailedAt = security.lockedUntil
|
||||
? new Date(security.lockedUntil.getTime() - PASSWORD_RULES.lockoutDurationMinutes * 60 * 1000)
|
||||
: null
|
||||
if (isAccountLocked(security.failedLoginAttempts, lastFailedAt)) {
|
||||
await logLoginEvent({
|
||||
userId: user.id,
|
||||
userEmail: email,
|
||||
action: "signin",
|
||||
status: "failure",
|
||||
errorMessage: "Account locked",
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
const storedPassword = user.password ?? null
|
||||
if (!storedPassword) return null
|
||||
const normalizedPassword = normalizeBcryptHash(storedPassword)
|
||||
if (!normalizedPassword.startsWith("$2")) return null
|
||||
const ok = await compare(password, normalizedPassword)
|
||||
|
||||
if (!ok) {
|
||||
await recordFailedLogin(db, passwordSecurity, user.id)
|
||||
await logLoginEvent({
|
||||
userId: user.id,
|
||||
userEmail: email,
|
||||
action: "signin",
|
||||
status: "failure",
|
||||
errorMessage: "Invalid credentials",
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
// Successful login: reset counters and rate limit
|
||||
await resetFailedLogin(db, passwordSecurity, user.id)
|
||||
resetRateLimit(loginLimitKey)
|
||||
|
||||
// 2FA verification (if user has enabled it)
|
||||
const { verifyTwoFactorForLogin } = await import("@/modules/settings/actions-security")
|
||||
const twoFactorResult = await verifyTwoFactorForLogin({
|
||||
userId: user.id,
|
||||
token: totpCode || undefined,
|
||||
})
|
||||
if (twoFactorResult.required && !twoFactorResult.valid) {
|
||||
await logLoginEvent({
|
||||
userId: user.id,
|
||||
userEmail: email,
|
||||
action: "signin",
|
||||
status: "failure",
|
||||
errorMessage: totpCode
|
||||
? "Invalid 2FA code"
|
||||
: "2FA required but not provided",
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
const roleRows = await db
|
||||
.select({ name: roles.name })
|
||||
.from(usersToRoles)
|
||||
.innerJoin(roles, eq(usersToRoles.roleId, roles.id))
|
||||
.where(eq(usersToRoles.userId, user.id))
|
||||
|
||||
const roleNames = roleRows.map((r) => r.name)
|
||||
const resolvedRole = resolvePrimaryRole(roleNames)
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
name: user.name ?? undefined,
|
||||
email: user.email,
|
||||
role: resolvedRole,
|
||||
roles: roleNames,
|
||||
}
|
||||
const { authenticateUser } = await import("@/modules/auth/services/login-service")
|
||||
return authenticateUser(credentials)
|
||||
},
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
jwt: async ({ token, user }) => {
|
||||
if (user) {
|
||||
const u = user as { id: string; role?: string; roles?: string[]; name?: string }
|
||||
token.id = u.id
|
||||
token.role = normalizeRole(u.role)
|
||||
token.name = u.name ?? undefined
|
||||
// P0-5 修复:User 接口已在 next-auth.d.ts 中扩展了 role/roles 字段,
|
||||
// 无需 `as` 断言即可安全访问。
|
||||
if (user && user.id) {
|
||||
token.id = user.id
|
||||
token.role = normalizeRole(user.role)
|
||||
token.name = user.name ?? undefined
|
||||
// Store all roles (not just primary) and resolved permissions
|
||||
const allRoles = (u.roles ?? [u.role ?? "student"]).filter(isRole)
|
||||
const allRoles = (user.roles ?? [user.role ?? "student"]).filter(isRole)
|
||||
token.roles = allRoles
|
||||
token.permissions = resolvePermissions(allRoles)
|
||||
// audit-P1-7:JWT 中仅存位图(~14 字符),不存数组(~1.1KB)。
|
||||
// Session callback 解码还原为 Permission[] 供业务使用。
|
||||
const permissions = await resolvePermissions(allRoles)
|
||||
token.permissionsBitmap = encodePermissionsBitmap(permissions)
|
||||
// Onboarding status is resolved from DB below; default to false on first login
|
||||
token.onboarded = false
|
||||
}
|
||||
@@ -181,7 +78,9 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
token.role = resolvePrimaryRole(allRoles)
|
||||
token.name = fresh.name ?? token.name
|
||||
token.roles = allRoles
|
||||
token.permissions = resolvePermissions(allRoles)
|
||||
// audit-P1-7:刷新位图,不再写 token.permissions 数组
|
||||
const permissions = await resolvePermissions(allRoles)
|
||||
token.permissionsBitmap = encodePermissionsBitmap(permissions)
|
||||
token.onboarded = Boolean(fresh.onboardedAt)
|
||||
}
|
||||
}
|
||||
@@ -189,11 +88,15 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
return token
|
||||
},
|
||||
session: async ({ session, token }) => {
|
||||
// audit-P1-7:session.user.permissions 由位图解码得到,
|
||||
// 业务代码(getAuthContext / usePermission)无需感知位图存在。
|
||||
if (session.user) {
|
||||
session.user.id = String(token.id ?? "")
|
||||
session.user.role = normalizeRole(token.role)
|
||||
session.user.roles = (token.roles ?? []).filter(isRole)
|
||||
session.user.permissions = (token.permissions ?? []) as typeof token.permissions
|
||||
session.user.permissions = decodePermissionsBitmap(
|
||||
token.permissionsBitmap ?? "",
|
||||
)
|
||||
session.user.onboarded = Boolean(token.onboarded)
|
||||
if (typeof token.name === "string") {
|
||||
session.user.name = token.name
|
||||
@@ -210,17 +113,34 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
action: "signin",
|
||||
status: "success",
|
||||
})
|
||||
// audit-P1-9:登录成功埋点(用于登录成功率、异常登录地理/设备告警)
|
||||
// 非阻塞:trackEvent 内部已吞掉异常
|
||||
await trackAuthEvent("auth.signin_success", {
|
||||
userId: user.id,
|
||||
properties: {
|
||||
// user.role 是单一主角色,user.roles 是全部角色(可能未填充)
|
||||
roles: (user.roles ?? (user.role ? [user.role] : [])),
|
||||
},
|
||||
})
|
||||
},
|
||||
async signOut(message) {
|
||||
// NextAuth v5 signOut event receives the session/token info
|
||||
const userId =
|
||||
(message as { userId?: string })?.userId ??
|
||||
(message as { token?: { id?: string } })?.token?.id ??
|
||||
""
|
||||
const userEmail =
|
||||
(message as { token?: { email?: string } })?.token?.email ??
|
||||
(message as { session?: { user?: { email?: string } } })?.session?.user?.email ??
|
||||
""
|
||||
// P0-5 修复:使用 `in` 操作符对联合类型进行类型收窄,替代 `as` 断言。
|
||||
// NextAuth v5 signOut 事件 message 为联合类型:
|
||||
// { session: ... } | { token: JWT }
|
||||
// JWT 策略下实际收到 { token: JWT },其中 JWT 已在 next-auth.d.ts 扩展。
|
||||
let userId = ""
|
||||
let userEmail = ""
|
||||
let roles: string[] = []
|
||||
|
||||
if ("token" in message) {
|
||||
const token = message.token
|
||||
if (token) {
|
||||
userId = String(token.id ?? "")
|
||||
userEmail = String(token.email ?? "")
|
||||
roles = (token.roles ?? []).filter(isRole)
|
||||
}
|
||||
}
|
||||
|
||||
if (userEmail) {
|
||||
await logLoginEvent({
|
||||
userId: userId || undefined,
|
||||
@@ -229,6 +149,13 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
status: "success",
|
||||
})
|
||||
}
|
||||
// audit-P1-9:登出埋点
|
||||
if (userId) {
|
||||
await trackAuthEvent("auth.signout", {
|
||||
userId,
|
||||
properties: { roles },
|
||||
})
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user