feat: ACN Application Security Standard V7.30 compliance (19/23 items)
CRITICAL — Authentication & Access: - TOTP MFA: otpauth-based, QR setup UI, sign-in flow integration, admin disable override, /account/security self-service page - Session Timeouts: 8h absolute (maxAge), 30min idle (updateAge) - Failed Auth Logging: Pino warn for invalid password/user/totp, info for successful login, audit entries for all auth events - Concurrent Session Limit: ActiveSession model, oldest-kick strategy, max 3 per user (configurable in SystemSettings) CRITICAL — HTTP Security: - HSTS: max-age=31536000; includeSubDomains - CSP: script/style/img/font/connect-src with Gemini/OpenAI whitelist - X-XSS-Protection: 0 (CSP replaces legacy) - Auth page cache: no-store, no-cache, must-revalidate - Rate Limiting: 100/15min general API, 5/15min auth (Map-based) Data Protection: - XSS Sanitization: DOMPurify on comment bodies - autocomplete="new-password" on all password/secret fields - SameSite=Strict on all cookies (Credentials-only, no OAuth) - File Upload Magic Bytes validation (PNG/JPEG/WebP/GIF/BMP/TIFF) Logging & Monitoring: - Login/Logout audit entries (Auth entityType) - External API call logging with timing (OpenAI, Gemini) - Input validation failure logging at warn level - Concurrent session tracking in ActiveSession table Documentation: - docs/security-architecture.md (11 sections) - docs/sdlc.md (CI pipeline, security gates, incident response) - .gitea/PULL_REQUEST_TEMPLATE.md (security checklist) Schema: User.totpSecret/totpEnabled, SystemSettings.sessionMaxAge/ sessionIdleTimeout/maxConcurrentSessions, ActiveSession model Tests: 310 engine + 37 staffing pass. TypeScript clean. Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
+191
-3
@@ -1,4 +1,7 @@
|
||||
import { prisma } from "@capakraken/db";
|
||||
import { authRateLimiter } from "@capakraken/api/middleware/rate-limit";
|
||||
import { createAuditEntry } from "@capakraken/api";
|
||||
import { logger } from "@capakraken/api/lib/logger";
|
||||
import NextAuth, { type NextAuthConfig } from "next-auth";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import { verify } from "@node-rs/argon2";
|
||||
@@ -7,6 +10,7 @@ import { z } from "zod";
|
||||
const LoginSchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(1),
|
||||
totp: z.string().optional(),
|
||||
});
|
||||
|
||||
const authConfig = {
|
||||
@@ -16,17 +20,96 @@ const authConfig = {
|
||||
credentials: {
|
||||
email: { label: "Email", type: "email" },
|
||||
password: { label: "Password", type: "password" },
|
||||
totp: { label: "TOTP", type: "text" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
const parsed = LoginSchema.safeParse(credentials);
|
||||
if (!parsed.success) return null;
|
||||
|
||||
const { email, password } = parsed.data;
|
||||
const { email, password, totp } = parsed.data;
|
||||
|
||||
// Rate limit: 5 login attempts per 15 minutes per email
|
||||
const rateLimitResult = authRateLimiter(email.toLowerCase());
|
||||
if (!rateLimitResult.allowed) {
|
||||
// Audit failed login (rate limited)
|
||||
void createAuditEntry({
|
||||
db: prisma,
|
||||
entityType: "Auth",
|
||||
entityId: email.toLowerCase(),
|
||||
entityName: email,
|
||||
action: "CREATE",
|
||||
summary: "Login blocked — rate limit exceeded",
|
||||
source: "ui",
|
||||
});
|
||||
throw new Error("Too many login attempts. Please try again later.");
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { email } });
|
||||
if (!user?.passwordHash) return null;
|
||||
if (!user?.passwordHash) {
|
||||
logger.warn({ email, reason: "user_not_found" }, "Failed login attempt");
|
||||
// Audit failed login (unknown user)
|
||||
void createAuditEntry({
|
||||
db: prisma,
|
||||
entityType: "Auth",
|
||||
entityId: email.toLowerCase(),
|
||||
entityName: email,
|
||||
action: "CREATE",
|
||||
summary: "Login failed — user not found",
|
||||
source: "ui",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const isValid = await verify(user.passwordHash, password);
|
||||
if (!isValid) return null;
|
||||
if (!isValid) {
|
||||
logger.warn({ email, reason: "invalid_password" }, "Failed login attempt");
|
||||
// Audit failed login (bad password)
|
||||
void createAuditEntry({
|
||||
db: prisma,
|
||||
entityType: "Auth",
|
||||
entityId: user.id,
|
||||
entityName: user.email,
|
||||
action: "CREATE",
|
||||
userId: user.id,
|
||||
summary: "Login failed — invalid password",
|
||||
source: "ui",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
// MFA check: if TOTP is enabled, require the token
|
||||
if (user.totpEnabled && user.totpSecret) {
|
||||
if (!totp) {
|
||||
// Signal to the client that MFA is required (include userId for re-submission)
|
||||
throw new Error("MFA_REQUIRED:" + user.id);
|
||||
}
|
||||
|
||||
const { TOTP, Secret } = await import("otpauth");
|
||||
const totpInstance = new TOTP({
|
||||
issuer: "CapaKraken",
|
||||
label: user.email,
|
||||
algorithm: "SHA1",
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: Secret.fromBase32(user.totpSecret),
|
||||
});
|
||||
|
||||
const delta = totpInstance.validate({ token: totp, window: 1 });
|
||||
if (delta === null) {
|
||||
logger.warn({ email, reason: "invalid_totp" }, "Failed MFA verification");
|
||||
void createAuditEntry({
|
||||
db: prisma,
|
||||
entityType: "Auth",
|
||||
entityId: user.id,
|
||||
entityName: user.email,
|
||||
action: "CREATE",
|
||||
userId: user.id,
|
||||
summary: "Login failed — invalid TOTP token",
|
||||
source: "ui",
|
||||
});
|
||||
throw new Error("INVALID_TOTP");
|
||||
}
|
||||
}
|
||||
|
||||
// Track last login time
|
||||
await prisma.user.update({
|
||||
@@ -34,6 +117,19 @@ const authConfig = {
|
||||
data: { lastLoginAt: new Date() },
|
||||
});
|
||||
|
||||
logger.info({ email, userId: user.id }, "Successful login");
|
||||
// Audit successful login
|
||||
void createAuditEntry({
|
||||
db: prisma,
|
||||
entityType: "Auth",
|
||||
entityId: user.id,
|
||||
entityName: user.email,
|
||||
action: "CREATE",
|
||||
userId: user.id,
|
||||
summary: "User logged in",
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
@@ -56,15 +152,107 @@ const authConfig = {
|
||||
async jwt({ token, user }) {
|
||||
if (user) {
|
||||
token.role = (user as typeof user & { role: string }).role;
|
||||
|
||||
// Generate a unique JWT ID for session tracking
|
||||
const jti = crypto.randomUUID();
|
||||
token.jti = jti;
|
||||
|
||||
// Enforce concurrent session limit (kick-oldest strategy)
|
||||
try {
|
||||
const settings = await prisma.systemSettings.findUnique({
|
||||
where: { id: "singleton" },
|
||||
select: { maxConcurrentSessions: true },
|
||||
});
|
||||
const maxSessions = settings?.maxConcurrentSessions ?? 3;
|
||||
|
||||
// Register this new session
|
||||
await prisma.activeSession.create({
|
||||
data: { userId: user.id!, jti },
|
||||
});
|
||||
|
||||
// Count active sessions and delete the oldest if over the limit
|
||||
const activeSessions = await prisma.activeSession.findMany({
|
||||
where: { userId: user.id! },
|
||||
orderBy: { createdAt: "asc" },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (activeSessions.length > maxSessions) {
|
||||
const toDelete = activeSessions.slice(0, activeSessions.length - maxSessions);
|
||||
await prisma.activeSession.deleteMany({
|
||||
where: { id: { in: toDelete.map((s) => s.id) } },
|
||||
});
|
||||
logger.info({ userId: user.id, kicked: toDelete.length, maxSessions }, "Kicked oldest sessions");
|
||||
}
|
||||
} catch (err) {
|
||||
// Non-blocking: don't prevent login if session tracking fails
|
||||
logger.error({ err }, "Failed to enforce concurrent session limit");
|
||||
}
|
||||
}
|
||||
return token;
|
||||
},
|
||||
},
|
||||
events: {
|
||||
async signOut(message) {
|
||||
// Auth.js fires this event on sign-out; extract userId from the JWT token
|
||||
const token = "token" in message ? message.token : null;
|
||||
const userId = token?.sub ?? null;
|
||||
const email = token?.email ?? "unknown";
|
||||
const jti = token?.jti as string | undefined;
|
||||
|
||||
// Remove from active session registry
|
||||
if (jti) {
|
||||
void prisma.activeSession.delete({ where: { jti } }).catch(() => { /* already gone */ });
|
||||
}
|
||||
|
||||
void createAuditEntry({
|
||||
db: prisma,
|
||||
entityType: "Auth",
|
||||
entityId: userId ?? email,
|
||||
entityName: email,
|
||||
action: "DELETE",
|
||||
...(userId ? { userId } : {}),
|
||||
summary: "User logged out",
|
||||
source: "ui",
|
||||
});
|
||||
},
|
||||
},
|
||||
cookies: {
|
||||
sessionToken: {
|
||||
name: "authjs.session-token",
|
||||
options: {
|
||||
httpOnly: true,
|
||||
sameSite: "strict" as const,
|
||||
path: "/",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
},
|
||||
},
|
||||
callbackUrl: {
|
||||
name: "authjs.callback-url",
|
||||
options: {
|
||||
httpOnly: true,
|
||||
sameSite: "strict" as const,
|
||||
path: "/",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
},
|
||||
},
|
||||
csrfToken: {
|
||||
name: "authjs.csrf-token",
|
||||
options: {
|
||||
httpOnly: true,
|
||||
sameSite: "strict" as const,
|
||||
path: "/",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
},
|
||||
},
|
||||
},
|
||||
pages: {
|
||||
signIn: "/auth/signin",
|
||||
},
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
maxAge: 28800, // 8 hours absolute timeout
|
||||
updateAge: 1800, // Refresh token every 30 minutes (idle timeout)
|
||||
},
|
||||
} satisfies NextAuthConfig;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user