Integrate granular audit logging for admin actions, transition to role-based API access via `requireAdminApiSession`, and update session tokens to persist user roles and IDs for consistent multi-admin management.
106 lines
3.1 KiB
TypeScript
106 lines
3.1 KiB
TypeScript
import {
|
|
type AdminRole,
|
|
getAdminRoleRank,
|
|
normalizeAdminRole,
|
|
} from "@/core/auth/adminSession";
|
|
import { verifyRequestAdminSession } from "@/core/auth/adminUsers";
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
|
|
export const ADMIN_SESSION_COOKIE = "datastack_admin_session";
|
|
|
|
export interface RequireAdminSessionOptions {
|
|
minRole?: AdminRole;
|
|
allowedRoles?: AdminRole[];
|
|
}
|
|
|
|
export async function requireAdminApiSession(
|
|
req: NextRequest,
|
|
options?: RequireAdminSessionOptions,
|
|
) {
|
|
const token = req.cookies.get(ADMIN_SESSION_COOKIE)?.value;
|
|
const auth = await verifyRequestAdminSession(token);
|
|
if (!auth.valid) {
|
|
return {
|
|
valid: false as const,
|
|
response: NextResponse.json(
|
|
{
|
|
error:
|
|
auth.reason === "UNAUTHORIZED"
|
|
? "Authentication required."
|
|
: "Admin authentication is temporarily unavailable.",
|
|
},
|
|
{ status: auth.reason === "UNAUTHORIZED" ? 401 : 503 },
|
|
),
|
|
};
|
|
}
|
|
|
|
const currentRole = normalizeAdminRole(auth.session.role, "owner");
|
|
|
|
if (options?.minRole) {
|
|
const currentRank = getAdminRoleRank(currentRole);
|
|
const requiredRank = getAdminRoleRank(options.minRole);
|
|
if (currentRank < requiredRank) {
|
|
return {
|
|
valid: false as const,
|
|
response: NextResponse.json(
|
|
{
|
|
error: `INSUFFICIENT_ROLE_PERMISSION: Role '${currentRole}' does not have permission for this action (requires '${options.minRole}').`,
|
|
code: "INSUFFICIENT_ROLE_PERMISSION",
|
|
currentRole,
|
|
requiredRole: options.minRole,
|
|
},
|
|
{ status: 403 },
|
|
),
|
|
};
|
|
}
|
|
}
|
|
|
|
if (options?.allowedRoles && options.allowedRoles.length > 0) {
|
|
const allowedRanks = options.allowedRoles.map((r) => normalizeAdminRole(r));
|
|
if (!allowedRanks.includes(currentRole)) {
|
|
return {
|
|
valid: false as const,
|
|
response: NextResponse.json(
|
|
{
|
|
error: `INSUFFICIENT_ROLE_PERMISSION: Role '${currentRole}' is not permitted for this action.`,
|
|
code: "INSUFFICIENT_ROLE_PERMISSION",
|
|
currentRole,
|
|
allowedRoles: allowedRanks,
|
|
},
|
|
{ status: 403 },
|
|
),
|
|
};
|
|
}
|
|
}
|
|
|
|
return { valid: true as const, auth };
|
|
}
|
|
|
|
/**
|
|
* Extracts the client IP for authentication throttling in a reverse-proxy-safe order:
|
|
* 1. `x-real-ip` (overwritten directly by Nginx/Coolify with `$remote_addr`)
|
|
* 2. Rightmost non-empty hop of `x-forwarded-for` (appended by the trusted edge proxy,
|
|
* preventing attackers from spoofing arbitrary leftmost client IPs)
|
|
* 3. Fallback `"unknown"`
|
|
*/
|
|
export function extractClientIp(request: NextRequest): string {
|
|
const realIp = request.headers.get("x-real-ip")?.trim();
|
|
if (realIp) {
|
|
return realIp.slice(0, 128);
|
|
}
|
|
|
|
const forwardedFor = request.headers.get("x-forwarded-for");
|
|
if (forwardedFor) {
|
|
const hops = forwardedFor
|
|
.split(",")
|
|
.map((part) => part.trim())
|
|
.filter(Boolean);
|
|
const rightmost = hops[hops.length - 1];
|
|
if (rightmost) {
|
|
return rightmost.slice(0, 128);
|
|
}
|
|
}
|
|
|
|
return "unknown";
|
|
}
|