refactor: fix all P0/P1/P2 bugs and architecture issues

Bug fixes (from bugs/ directory):

- Fix cross-module DB queries in 9 modules (homework, grades, parent, diagnostic, elective, proctoring, notifications, scheduling, classes) by routing through data-access functions

- Fix shared/lib <-> auth circular dependency via new session.ts module

- Fix divide-by-zero guard in grades data-access

- Fix audit export data truncation (paginated fetch for full datasets)

- Fix missing transactions in homework grading and elective lottery

- Fix missing revalidatePath in course-plans actions

- Fix frontend permission checks using requirePermission instead of requireAuth

- Fix dashboard role routing using session.user.roles

- Fix student auth pattern (migrate getDemoStudentUser to users module)

- Fix ActionState return type handling in components

Code quality fixes:

- Remove 60+ as type assertions (replace with type guards)

- Remove non-null assertions (use optional chaining or explicit checks)

- Convert dynamic imports to static imports (grades, diagnostic)

- Add React.cache() wrapping for read functions

- Parallelize independent queries with Promise.all

- Add explicit return types to 30+ arrow functions

- Replace any with unknown + type guards

- Fix import type for type-only imports

- Add Zod validation schemas for classes and diagnostic modules

- Extract duplicate code (normalizeRoleName, normalizeBcryptHash, logger IP extraction)

- Add console.error to silent catch blocks

- Fix permission naming consistency (exam:proctor_read -> exam:proctor:read)

Architecture doc sync:

- Update 004_architecture_impact_map.md and 005_architecture_data.json

- Update management-modules-audit.md for P0-7 cross-module fix

Moved deleted proctoring event route to deletes/ folder.
This commit is contained in:
SpecialX
2026-06-19 05:13:09 +08:00
parent 063baffe4c
commit 49291fcc31
114 changed files with 12548 additions and 3395 deletions

View File

@@ -1,33 +1,40 @@
"use server"
import { revalidatePath } from "next/cache"
import { eq } from "drizzle-orm"
import { compare, hash } from "bcryptjs"
import { z } from "zod"
import { db } from "@/shared/db"
import { users, passwordSecurity } from "@/shared/db/schema"
import type { ActionState } from "@/shared/types/action-state"
import { requireAuth, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { validatePassword } from "@/shared/lib/password-policy"
import { rateLimit, rateLimitKey, RATE_LIMIT_RULES } from "@/shared/lib/rate-limit"
import { normalizeBcryptHash } from "@/shared/lib/bcrypt-utils"
const normalizeBcryptHash = (value: string) => {
if (value.startsWith("$2")) return value
if (value.startsWith("$")) return `$2b${value}`
return `$2b$${value}`
}
import {
getPasswordSecurityByUserId,
getUserPasswordHash,
updateUserPassword,
upsertPasswordSecurityOnPasswordChange,
} from "./data-access"
const ChangePasswordSchema = z.object({
currentPassword: z.string().min(1, "Current password is required"),
newPassword: z.string().min(1, "New password is required"),
confirmPassword: z.string().min(1, "Password confirmation is required"),
})
/**
* Change the current user's password. Requires only authentication
* (no specific permission) since every user can manage their own
* credentials. Rate-limited to slow brute-force of the current password.
* Change the current user's password. Requires self-service profile update
* permission (every authenticated user has it). Rate-limited to slow
* brute-force of the current password.
*/
export async function changePasswordAction(
prevState: ActionState<null>,
formData: FormData
): Promise<ActionState<null>> {
try {
const ctx = await requireAuth()
const ctx = await requirePermission(Permissions.USER_PROFILE_UPDATE)
const userId = ctx.userId
const limitKey = rateLimitKey("pwd-change", userId)
@@ -36,13 +43,19 @@ export async function changePasswordAction(
return { success: false, message: "Too many attempts. Please try again later." }
}
const currentPassword = String(formData.get("currentPassword") ?? "")
const newPassword = String(formData.get("newPassword") ?? "")
const confirmPassword = String(formData.get("confirmPassword") ?? "")
if (!currentPassword || !newPassword || !confirmPassword) {
return { success: false, message: "All fields are required" }
const parsed = ChangePasswordSchema.safeParse({
currentPassword: formData.get("currentPassword"),
newPassword: formData.get("newPassword"),
confirmPassword: formData.get("confirmPassword"),
})
if (!parsed.success) {
return {
success: false,
message: parsed.error.issues[0]?.message ?? "Invalid form data",
}
}
const { currentPassword, newPassword, confirmPassword } = parsed.data
if (newPassword !== confirmPassword) {
return { success: false, message: "New passwords do not match" }
}
@@ -55,16 +68,17 @@ export async function changePasswordAction(
return { success: false, message: validation.errors[0] ?? "Password does not meet requirements" }
}
const [user] = await db
.select({ id: users.id, password: users.password })
.from(users)
.where(eq(users.id, userId))
.limit(1)
if (!user || !user.password) {
// Parallelize user and passwordSecurity queries
const [userRecord, existingSecurity] = await Promise.all([
getUserPasswordHash(userId),
getPasswordSecurityByUserId(userId),
])
if (!userRecord || !userRecord.password) {
return { success: false, message: "User not found or no password set" }
}
const storedHash = normalizeBcryptHash(user.password)
const storedHash = normalizeBcryptHash(userRecord.password)
if (!storedHash.startsWith("$2")) {
return { success: false, message: "Stored password is invalid" }
}
@@ -75,34 +89,8 @@ export async function changePasswordAction(
const newHash = await hash(newPassword, 10)
const now = new Date()
await db
.update(users)
.set({ password: newHash, updatedAt: now })
.where(eq(users.id, userId))
const [existing] = await db
.select({ id: passwordSecurity.id })
.from(passwordSecurity)
.where(eq(passwordSecurity.userId, userId))
.limit(1)
if (existing) {
await db
.update(passwordSecurity)
.set({
lastPasswordChange: now,
passwordChangedAt: now,
mustChangePassword: false,
updatedAt: now,
})
.where(eq(passwordSecurity.userId, userId))
} else {
await db.insert(passwordSecurity).values({
userId,
lastPasswordChange: now,
passwordChangedAt: now,
mustChangePassword: false,
})
}
await updateUserPassword(userId, newHash, now)
await upsertPasswordSecurityOnPasswordChange(userId, now, existingSecurity)
revalidatePath("/settings")
return { success: true, message: "Password changed successfully", data: null }