feat(auth): implement RBAC audit logging and session security
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.
This commit is contained in:
1 parent
2873b9904a
commit
5c977d6977
37 files changed
+5939
-349
No files matched your search
@@ -0,0 +1,41 @@
|
||||
import { listAdminAuditLogsAsync } from "@/core/auth/auditLog";
|
||||
import { requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireAdminApiSession(req, { minRole: "viewer" });
|
||||
if (!auth.valid) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
try {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const rawLimit = Number(searchParams.get("limit") || "100");
|
||||
const limit = Number.isFinite(rawLimit)
|
||||
? Math.min(Math.max(Math.floor(rawLimit), 1), 500)
|
||||
: 100;
|
||||
const action = searchParams.get("action") || undefined;
|
||||
const actorEmail =
|
||||
searchParams.get("actor") ||
|
||||
searchParams.get("actorEmail") ||
|
||||
undefined;
|
||||
const search =
|
||||
searchParams.get("q") || searchParams.get("search") || undefined;
|
||||
|
||||
const logs = await listAdminAuditLogsAsync({
|
||||
limit,
|
||||
action,
|
||||
actorEmail,
|
||||
search,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
logs,
|
||||
total: logs.length,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Unable to fetch audit logs.";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
type AdminRole,
|
||||
createAdminSessionToken,
|
||||
getAdminSessionSecret,
|
||||
getSessionCookieOptions,
|
||||
@@ -9,6 +10,7 @@ import {
|
||||
clearAdminLoginAttempts,
|
||||
consumeAdminLoginAttempt,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { extractClientIp } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
@@ -79,7 +81,13 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
let authResult: { authenticated: boolean; tokenVersion: number };
|
||||
let authResult: {
|
||||
authenticated: boolean;
|
||||
tokenVersion: number;
|
||||
role: AdminRole;
|
||||
memberId: string;
|
||||
email: string;
|
||||
};
|
||||
try {
|
||||
authResult = await authenticateAdminCredentials(email, password);
|
||||
} catch (err) {
|
||||
@@ -117,13 +125,29 @@ export async function POST(request: NextRequest) {
|
||||
const remember = body.remember === true;
|
||||
const maxAge = remember ? REMEMBERED_SESSION_SECONDS : SESSION_SECONDS;
|
||||
const expiresAt = Date.now() + maxAge * 1000;
|
||||
const effectiveEmail = authResult.email || email;
|
||||
const token = await createAdminSessionToken(
|
||||
email,
|
||||
effectiveEmail,
|
||||
sessionSecret,
|
||||
expiresAt,
|
||||
authResult.tokenVersion,
|
||||
authResult.role,
|
||||
authResult.memberId,
|
||||
);
|
||||
const response = NextResponse.json({ success: true });
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: effectiveEmail,
|
||||
actorRole: authResult.role || "owner",
|
||||
action: "ADMIN_LOGIN",
|
||||
target: effectiveEmail,
|
||||
ipAddress: clientIp,
|
||||
metadata: { remember },
|
||||
});
|
||||
|
||||
const response = NextResponse.json({
|
||||
success: true,
|
||||
role: authResult.role || "owner",
|
||||
});
|
||||
|
||||
response.cookies.set(
|
||||
SESSION_COOKIE,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
createAdminSessionToken,
|
||||
formatAdminRoleLabel,
|
||||
getSessionCookieOptions,
|
||||
} from "@/core/auth/adminSession";
|
||||
import {
|
||||
@@ -7,6 +8,8 @@ import {
|
||||
updateAdminAccount,
|
||||
verifyRequestAdminSession,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { extractClientIp } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const SESSION_COOKIE = "datastack_admin_session";
|
||||
@@ -33,10 +36,13 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
try {
|
||||
const account = await getAdminAccountInfo(auth.session.email);
|
||||
const effectiveRole = auth.session.role || account.role || "owner";
|
||||
return NextResponse.json({
|
||||
profile: {
|
||||
email: account.email,
|
||||
role: "Owner",
|
||||
role: formatAdminRoleLabel(effectiveRole),
|
||||
roleKey: effectiveRole,
|
||||
memberId: auth.session.memberId || account.memberId || "owner-1",
|
||||
storageMode: account.storageMode,
|
||||
createdAt: account.createdAt,
|
||||
sessionExpiresAt: new Date(auth.session.expiresAt).toISOString(),
|
||||
@@ -125,24 +131,42 @@ export async function PUT(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
// Preserve remaining session duration (e.g., 30-day "Remember me" session)
|
||||
const remainingSeconds = Math.max(
|
||||
SESSION_SECONDS,
|
||||
Math.ceil((auth.session.expiresAt - Date.now()) / 1000),
|
||||
);
|
||||
const expiresAt = Date.now() + remainingSeconds * 1000;
|
||||
const effectiveRole = result.role || auth.session.role || "owner";
|
||||
const effectiveMemberId =
|
||||
result.memberId || auth.session.memberId || "owner-1";
|
||||
const nextToken = await createAdminSessionToken(
|
||||
result.email,
|
||||
auth.sessionSecret,
|
||||
expiresAt,
|
||||
result.tokenVersion,
|
||||
effectiveRole,
|
||||
effectiveMemberId,
|
||||
);
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: result.email,
|
||||
actorRole: effectiveRole,
|
||||
action: newPassword ? "ADMIN_PASSWORD_UPDATED" : "ADMIN_PROFILE_UPDATED",
|
||||
target: result.email,
|
||||
ipAddress: extractClientIp(request),
|
||||
metadata: {
|
||||
emailChanged: result.email !== account.email,
|
||||
passwordRotated: Boolean(newPassword),
|
||||
},
|
||||
});
|
||||
|
||||
const response = NextResponse.json({
|
||||
success: true,
|
||||
profile: {
|
||||
email: result.email,
|
||||
role: "Owner",
|
||||
role: formatAdminRoleLabel(effectiveRole),
|
||||
roleKey: effectiveRole,
|
||||
memberId: effectiveMemberId,
|
||||
storageMode: account.storageMode,
|
||||
createdAt: account.createdAt,
|
||||
sessionExpiresAt: new Date(expiresAt).toISOString(),
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { verifyRequestAdminSession } from "@/core/auth/adminUsers";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { SDKManager } from "@/core/sdk/sdkManager";
|
||||
import {
|
||||
validateAllowedIpsInput,
|
||||
validateClientExpiresAtInput,
|
||||
} from "@/core/Security/ipAllowlist";
|
||||
import { extractClientIp, requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const SESSION_COOKIE = "datastack_admin_session";
|
||||
const ALLOWED_PATCH_KEYS = new Set([
|
||||
"action",
|
||||
"name",
|
||||
@@ -21,14 +21,12 @@ export async function GET(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const auth = await verifyRequestAdminSession(
|
||||
req.cookies.get(SESSION_COOKIE)?.value,
|
||||
);
|
||||
const includeToken = req.nextUrl.searchParams.get("includeToken") === "true";
|
||||
const auth = await requireAdminApiSession(req, {
|
||||
minRole: includeToken ? "operator" : "viewer",
|
||||
});
|
||||
if (!auth.valid) {
|
||||
return NextResponse.json(
|
||||
{ error: "Authentication required." },
|
||||
{ status: auth.reason === "UNAUTHORIZED" ? 401 : 503 },
|
||||
);
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
@@ -40,7 +38,6 @@ export async function GET(
|
||||
}
|
||||
const { secret, token, ...clientSummary } = client;
|
||||
void secret;
|
||||
const includeToken = req.nextUrl.searchParams.get("includeToken") === "true";
|
||||
return NextResponse.json({
|
||||
client: {
|
||||
...clientSummary,
|
||||
@@ -65,14 +62,9 @@ export async function PATCH(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const auth = await verifyRequestAdminSession(
|
||||
req.cookies.get(SESSION_COOKIE)?.value,
|
||||
);
|
||||
const auth = await requireAdminApiSession(req, { minRole: "operator" });
|
||||
if (!auth.valid) {
|
||||
return NextResponse.json(
|
||||
{ error: "Authentication required." },
|
||||
{ status: auth.reason === "UNAUTHORIZED" ? 401 : 503 },
|
||||
);
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
@@ -90,7 +82,10 @@ export async function PATCH(
|
||||
|
||||
if (!rawBody || typeof rawBody !== "object" || Array.isArray(rawBody)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Update payload must be a JSON object.", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: "Update payload must be a JSON object.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
@@ -120,8 +115,23 @@ export async function PATCH(
|
||||
try {
|
||||
const refreshed = await SDKManager.regenerateTokenAsync(normalizedId);
|
||||
if (!refreshed) {
|
||||
return NextResponse.json({ error: "Client not found" }, { status: 404 });
|
||||
return NextResponse.json(
|
||||
{ error: "Client not found" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || "owner",
|
||||
action: "CLIENT_TOKEN_ROTATED",
|
||||
target: refreshed.clientId,
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: {
|
||||
clientId: refreshed.clientId,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ client: refreshed });
|
||||
} catch (err: unknown) {
|
||||
const message =
|
||||
@@ -130,7 +140,9 @@ export async function PATCH(
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: message,
|
||||
code: isDbWrite ? "DATABASE_WRITE_FAILED" : "TOKEN_REGENERATION_FAILED",
|
||||
code: isDbWrite
|
||||
? "DATABASE_WRITE_FAILED"
|
||||
: "TOKEN_REGENERATION_FAILED",
|
||||
},
|
||||
{ status: isDbWrite ? 503 : 500 },
|
||||
);
|
||||
@@ -152,7 +164,10 @@ export async function PATCH(
|
||||
body.name.trim().length > 120
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: "Client name must be a non-empty string (max 120 characters).", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: "Client name must be a non-empty string (max 120 characters).",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
@@ -166,7 +181,10 @@ export async function PATCH(
|
||||
body.rateLimit > 100000
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: "rateLimit must be an integer between 1 and 100000.", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: "rateLimit must be an integer between 1 and 100000.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
@@ -180,7 +198,10 @@ export async function PATCH(
|
||||
body.storageQuotaMb > 1048576
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: "storageQuotaMb must be an integer between 0 and 1048576.", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: "storageQuotaMb must be an integer between 0 and 1048576.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
@@ -196,7 +217,10 @@ export async function PATCH(
|
||||
const ipValidation = validateAllowedIpsInput(body.allowedIps);
|
||||
if (!ipValidation.valid) {
|
||||
return NextResponse.json(
|
||||
{ error: ipValidation.error || "Invalid allowedIps.", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: ipValidation.error || "Invalid allowedIps.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
@@ -206,16 +230,22 @@ export async function PATCH(
|
||||
const expValidation = validateClientExpiresAtInput(body.expiresAt);
|
||||
if (!expValidation.valid) {
|
||||
return NextResponse.json(
|
||||
{ error: expValidation.error || "Invalid expiresAt.", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: expValidation.error || "Invalid expiresAt.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
updates.expiresAt = expValidation.normalized;
|
||||
updates.expiresAt = expValidation.iso ?? null;
|
||||
}
|
||||
if (body.status !== undefined) {
|
||||
if (body.status !== "active" && body.status !== "revoked") {
|
||||
return NextResponse.json(
|
||||
{ error: "status must be 'active' or 'revoked'.", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: "status must be 'active' or 'revoked'.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
@@ -224,7 +254,10 @@ export async function PATCH(
|
||||
|
||||
if (Object.keys(updates).length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "No valid fields provided for update.", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: "No valid fields provided for update.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
@@ -234,6 +267,16 @@ export async function PATCH(
|
||||
if (!updated) {
|
||||
return NextResponse.json({ error: "Client not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || "owner",
|
||||
action: "CLIENT_UPDATED",
|
||||
target: updated.clientId,
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: updates,
|
||||
});
|
||||
|
||||
return NextResponse.json({ client: updated });
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : "Update failed";
|
||||
@@ -252,14 +295,9 @@ export async function DELETE(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const auth = await verifyRequestAdminSession(
|
||||
req.cookies.get(SESSION_COOKIE)?.value,
|
||||
);
|
||||
const auth = await requireAdminApiSession(req, { minRole: "operator" });
|
||||
if (!auth.valid) {
|
||||
return NextResponse.json(
|
||||
{ error: "Authentication required." },
|
||||
{ status: auth.reason === "UNAUTHORIZED" ? 401 : 503 },
|
||||
);
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
@@ -272,13 +310,27 @@ export async function DELETE(
|
||||
if (!result.deleted) {
|
||||
return NextResponse.json({ error: "Client not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || "owner",
|
||||
action: "CLIENT_DELETED",
|
||||
target: normalizedId,
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: {
|
||||
purgeFiles,
|
||||
purgedFiles: result.purgedFiles,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `Client ${normalizedId} deleted`,
|
||||
purgedFiles: result.purgedFiles,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : "Client deletion failed";
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Client deletion failed";
|
||||
const isDbWrite = message.includes("DATABASE_WRITE_FAILED");
|
||||
return NextResponse.json(
|
||||
{
|
||||
|
||||
+60
-27
@@ -1,22 +1,16 @@
|
||||
import { verifyRequestAdminSession } from "@/core/auth/adminUsers";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { SDKManager } from "@/core/sdk/sdkManager";
|
||||
import {
|
||||
validateAllowedIpsInput,
|
||||
validateClientExpiresAtInput,
|
||||
} from "@/core/Security/ipAllowlist";
|
||||
import { extractClientIp, requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const SESSION_COOKIE = "datastack_admin_session";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await verifyRequestAdminSession(
|
||||
req.cookies.get(SESSION_COOKIE)?.value,
|
||||
);
|
||||
const auth = await requireAdminApiSession(req, { minRole: "viewer" });
|
||||
if (!auth.valid) {
|
||||
return NextResponse.json(
|
||||
{ error: "Authentication required." },
|
||||
{ status: auth.reason === "UNAUTHORIZED" ? 401 : 503 },
|
||||
);
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -37,14 +31,9 @@ export async function GET(req: NextRequest) {
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await verifyRequestAdminSession(
|
||||
req.cookies.get(SESSION_COOKIE)?.value,
|
||||
);
|
||||
const auth = await requireAdminApiSession(req, { minRole: "operator" });
|
||||
if (!auth.valid) {
|
||||
return NextResponse.json(
|
||||
{ error: "Authentication required." },
|
||||
{ status: auth.reason === "UNAUTHORIZED" ? 401 : 503 },
|
||||
);
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
@@ -71,9 +60,17 @@ export async function POST(req: NextRequest) {
|
||||
expiresAt,
|
||||
} = body;
|
||||
|
||||
if (typeof clientId !== "string" || typeof name !== "string" || !clientId.trim() || !name.trim()) {
|
||||
if (
|
||||
typeof clientId !== "string" ||
|
||||
typeof name !== "string" ||
|
||||
!clientId.trim() ||
|
||||
!name.trim()
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: "clientId and name are required strings", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: "clientId and name are required strings",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
@@ -87,17 +84,32 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
const parsedRateLimit = rateLimit === undefined ? 100 : Number(rateLimit);
|
||||
if (!Number.isInteger(parsedRateLimit) || parsedRateLimit < 1 || parsedRateLimit > 100000) {
|
||||
if (
|
||||
!Number.isInteger(parsedRateLimit) ||
|
||||
parsedRateLimit < 1 ||
|
||||
parsedRateLimit > 100000
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: "rateLimit must be an integer between 1 and 100000.", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: "rateLimit must be an integer between 1 and 100000.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const parsedQuotaMb = storageQuotaMb === undefined ? 0 : Number(storageQuotaMb);
|
||||
if (!Number.isInteger(parsedQuotaMb) || parsedQuotaMb < 0 || parsedQuotaMb > 1048576) {
|
||||
const parsedQuotaMb =
|
||||
storageQuotaMb === undefined ? 0 : Number(storageQuotaMb);
|
||||
if (
|
||||
!Number.isInteger(parsedQuotaMb) ||
|
||||
parsedQuotaMb < 0 ||
|
||||
parsedQuotaMb > 1048576
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: "storageQuotaMb must be an integer between 0 and 1048576.", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: "storageQuotaMb must be an integer between 0 and 1048576.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
@@ -113,7 +125,10 @@ export async function POST(req: NextRequest) {
|
||||
const ipValidation = validateAllowedIpsInput(allowedIps);
|
||||
if (!ipValidation.valid) {
|
||||
return NextResponse.json(
|
||||
{ error: ipValidation.error || "Invalid allowedIps.", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: ipValidation.error || "Invalid allowedIps.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
@@ -125,11 +140,14 @@ export async function POST(req: NextRequest) {
|
||||
const expValidation = validateClientExpiresAtInput(expiresAt);
|
||||
if (!expValidation.valid) {
|
||||
return NextResponse.json(
|
||||
{ error: expValidation.error || "Invalid expiresAt.", code: "VALIDATION_ERROR" },
|
||||
{
|
||||
error: expValidation.error || "Invalid expiresAt.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
normalizedExpiresAt = expValidation.normalized;
|
||||
normalizedExpiresAt = expValidation.iso ?? null;
|
||||
}
|
||||
|
||||
const existing = await SDKManager.getClientAsync(safeClientId);
|
||||
@@ -149,6 +167,21 @@ export async function POST(req: NextRequest) {
|
||||
expiresAt: normalizedExpiresAt,
|
||||
});
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || "owner",
|
||||
action: "CLIENT_CREATED",
|
||||
target: newClient.clientId,
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: {
|
||||
name: newClient.name,
|
||||
rateLimit: newClient.rateLimit,
|
||||
storageQuotaMb: newClient.storageQuotaMb,
|
||||
allowedIps: newClient.allowedIps,
|
||||
expiresAt: newClient.expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ client: newClient }, { status: 201 });
|
||||
} catch (err: unknown) {
|
||||
const message =
|
||||
|
||||
@@ -73,12 +73,13 @@ export async function GET(req: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
const [clients, storageStats, diskHealth, bufferStats] = await Promise.all([
|
||||
const [clients, allFiles, diskHealth, bufferStats] = await Promise.all([
|
||||
SDKManager.listClientsAsync(),
|
||||
CSVStorageManager.getStatsAsync(),
|
||||
CSVStorageManager.getDiskSpaceHealthAsync(),
|
||||
CSVStorageManager.listAllFilesAsync(),
|
||||
CSVStorageManager.getDiskUsageAsync(),
|
||||
DataBufferEngine.getBufferStatsAsync(),
|
||||
]);
|
||||
const storageStats = CSVStorageManager.formatStorageStats(allFiles);
|
||||
|
||||
let activeSockets = 0;
|
||||
let bridgeUp = 0;
|
||||
@@ -117,7 +118,9 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
let activeClientsCount = 0;
|
||||
let revokedClientsCount = 0;
|
||||
let totalEventsCounter = 0;
|
||||
for (const c of clients) {
|
||||
totalEventsCounter += Math.max(0, Number(c.totalEvents) || 0);
|
||||
if (c.status === "revoked") {
|
||||
revokedClientsCount += 1;
|
||||
} else {
|
||||
@@ -135,6 +138,9 @@ export async function GET(req: NextRequest) {
|
||||
"# HELP datastack_active_sockets Currently connected Socket.IO SDK clients on Port 4000.",
|
||||
"# TYPE datastack_active_sockets gauge",
|
||||
`datastack_active_sockets ${activeSockets}`,
|
||||
"# HELP datastack_events_total Cumulative events ingested across all registered clients.",
|
||||
"# TYPE datastack_events_total counter",
|
||||
`datastack_events_total ${Math.max(totalEventsCounter, storageStats.totalRows)}`,
|
||||
"# HELP datastack_buffer_events_total Total events currently queued in memory or Redis awaiting CSV flush.",
|
||||
"# TYPE datastack_buffer_events_total gauge",
|
||||
`datastack_buffer_events_total ${totalBufferedEvents}`,
|
||||
@@ -143,7 +149,7 @@ export async function GET(req: NextRequest) {
|
||||
`datastack_storage_files_total ${storageStats.totalFiles}`,
|
||||
"# HELP datastack_storage_bytes_total Total bytes occupied by CSV and gzipped CSV partition files on disk.",
|
||||
"# TYPE datastack_storage_bytes_total gauge",
|
||||
`datastack_storage_bytes_total ${storageStats.totalSizeBytes}`,
|
||||
`datastack_storage_bytes_total ${storageStats.totalBytes}`,
|
||||
"# HELP datastack_storage_rows_total Total telemetry rows persisted across all partition files.",
|
||||
"# TYPE datastack_storage_rows_total gauge",
|
||||
`datastack_storage_rows_total ${storageStats.totalRows}`,
|
||||
@@ -152,7 +158,7 @@ export async function GET(req: NextRequest) {
|
||||
`datastack_disk_used_percent ${diskHealth.usedPct}`,
|
||||
"# HELP datastack_disk_free_bytes Free bytes available on the underlying storage volume.",
|
||||
"# TYPE datastack_disk_free_bytes gauge",
|
||||
`datastack_disk_free_bytes ${diskHealth.freeBytes}`,
|
||||
`datastack_disk_free_bytes ${diskHealth.availableBytes}`,
|
||||
"# HELP datastack_disk_total_bytes Total capacity in bytes of the underlying storage volume.",
|
||||
"# TYPE datastack_disk_total_bytes gauge",
|
||||
`datastack_disk_total_bytes ${diskHealth.totalBytes}`,
|
||||
@@ -177,7 +183,7 @@ export async function GET(req: NextRequest) {
|
||||
);
|
||||
|
||||
const perClientBytes = new Map<string, number>();
|
||||
for (const f of storageStats.files) {
|
||||
for (const f of allFiles) {
|
||||
perClientBytes.set(
|
||||
f.clientId,
|
||||
(perClientBytes.get(f.clientId) || 0) + f.sizeBytes,
|
||||
|
||||
+16
-27
@@ -2,12 +2,11 @@ import {
|
||||
SettingsManager,
|
||||
type AdminSettingsUpdateInput,
|
||||
} from "@/core/adminSettings/settingsManager";
|
||||
import { verifyRequestAdminSession } from "@/core/auth/adminUsers";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { SecretVaultError } from "@/core/Security/secretVault";
|
||||
import { extractClientIp, requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const SESSION_COOKIE = "datastack_admin_session";
|
||||
|
||||
const ALLOWED_SETTING_KEYS = new Set([
|
||||
"maxEventsPerSec",
|
||||
"maxPayloadSizeKb",
|
||||
@@ -69,19 +68,9 @@ function parseOptionalString(
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const auth = await verifyRequestAdminSession(
|
||||
req.cookies.get(SESSION_COOKIE)?.value,
|
||||
);
|
||||
const auth = await requireAdminApiSession(req, { minRole: "viewer" });
|
||||
if (!auth.valid) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
auth.reason === "UNAUTHORIZED"
|
||||
? "Authentication required."
|
||||
: "Admin authentication is temporarily unavailable.",
|
||||
},
|
||||
{ status: auth.reason === "UNAUTHORIZED" ? 401 : 503 },
|
||||
);
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const settings = await SettingsManager.getPublicSettingsAsync();
|
||||
@@ -94,19 +83,9 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const auth = await verifyRequestAdminSession(
|
||||
req.cookies.get(SESSION_COOKIE)?.value,
|
||||
);
|
||||
const auth = await requireAdminApiSession(req, { minRole: "owner" });
|
||||
if (!auth.valid) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
auth.reason === "UNAUTHORIZED"
|
||||
? "Authentication required."
|
||||
: "Admin authentication is temporarily unavailable.",
|
||||
},
|
||||
{ status: auth.reason === "UNAUTHORIZED" ? 401 : 503 },
|
||||
);
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
let rawBody: unknown;
|
||||
@@ -368,6 +347,16 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
await SettingsManager.updateSettingsAsync(validated);
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || "owner",
|
||||
action: "SETTINGS_UPDATED",
|
||||
target: "admin_settings",
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: {
|
||||
updatedFields: Object.keys(validated),
|
||||
},
|
||||
});
|
||||
const settings = await SettingsManager.getPublicSettingsAsync();
|
||||
const bridgeSync = SettingsManager.getLastBridgeSyncStatus();
|
||||
return NextResponse.json({
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { SettingsManager } from "@/core/adminSettings/settingsManager";
|
||||
import { dispatchWebhookAlertAsync } from "@/core/alerts/webhookNotifier";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { SecretVaultError } from "@/core/Security/secretVault";
|
||||
import { requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { extractClientIp, requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireAdminApiSession(req);
|
||||
const auth = await requireAdminApiSession(req, { minRole: "owner" });
|
||||
if (!auth.valid) {
|
||||
return auth.response;
|
||||
}
|
||||
@@ -73,7 +74,7 @@ export async function POST(req: NextRequest) {
|
||||
title: "Webhook Verification",
|
||||
message: "Test alert dispatched from DataStack Admin Console.",
|
||||
details: {
|
||||
triggeredBy: auth.auth.user?.email || "admin",
|
||||
triggeredBy: auth.auth.session.email || "admin",
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -85,6 +86,18 @@ export async function POST(req: NextRequest) {
|
||||
{ bypassCooldown: true },
|
||||
);
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || "owner",
|
||||
action: "WEBHOOK_TEST_TRIGGERED",
|
||||
target: webhookUrl,
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: {
|
||||
ok: result.ok,
|
||||
status: result.status,
|
||||
},
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { SettingsManager } from "@/core/adminSettings/settingsManager";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { SecretVaultError } from "@/core/Security/secretVault";
|
||||
import { CSVStorageManager } from "@/core/Storage/csvStorage";
|
||||
import {
|
||||
@@ -6,11 +7,11 @@ import {
|
||||
normalizeS3EndpointUrl,
|
||||
uploadFileToS3,
|
||||
} from "@/core/Storage/s3Archive";
|
||||
import { requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { extractClientIp, requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireAdminApiSession(req);
|
||||
const auth = await requireAdminApiSession(req, { minRole: "operator" });
|
||||
if (!auth.valid) {
|
||||
return auth.response;
|
||||
}
|
||||
@@ -135,6 +136,20 @@ export async function POST(req: NextRequest) {
|
||||
});
|
||||
}
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || "owner",
|
||||
action: "S3_ARCHIVE_TRIGGERED",
|
||||
target: s3Config.bucket,
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: {
|
||||
archivedCount: archiveResult.archivedCount,
|
||||
prunedCount: archiveResult.prunedCount,
|
||||
compressedCount,
|
||||
pruneAfterUpload,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: archiveResult.errors.length === 0,
|
||||
compressedCount,
|
||||
|
||||
@@ -50,7 +50,7 @@ export async function GET(req: NextRequest) {
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireAdminApiSession(req);
|
||||
const auth = await requireAdminApiSession(req, { minRole: 'operator' });
|
||||
if (!auth.valid) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import { requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireAdminApiSession(req);
|
||||
const auth = await requireAdminApiSession(req, { minRole: "operator" });
|
||||
if (!auth.valid) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import {
|
||||
deleteAdminTeamMemberAsync,
|
||||
PrimaryOwnerProtectedError,
|
||||
TeamMemberValidationError,
|
||||
updateAdminTeamMemberAsync,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { extractClientIp, requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function PATCH(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const auth = await requireAdminApiSession(req, { minRole: "owner" });
|
||||
if (!auth.valid) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
const parsed = await req.json();
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "Team member update payload must be a JSON object.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
body = parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid JSON request payload.", code: "INVALID_JSON" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const { id } = await params;
|
||||
const updated = await updateAdminTeamMemberAsync(id, {
|
||||
role: typeof body.role === "string" ? body.role : undefined,
|
||||
status: typeof body.status === "string" ? body.status : undefined,
|
||||
password: typeof body.password === "string" ? body.password : undefined,
|
||||
revokeSessions: body.revokeSessions === true,
|
||||
});
|
||||
|
||||
const action =
|
||||
body.status === "disabled" || body.revokeSessions === true
|
||||
? "TEAM_MEMBER_REVOKED"
|
||||
: "TEAM_MEMBER_UPDATED";
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || "owner",
|
||||
action,
|
||||
target: updated.email,
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: {
|
||||
memberId: updated.id,
|
||||
role: updated.role,
|
||||
status: updated.status,
|
||||
passwordReset: Boolean(body.password),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true, member: updated });
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof PrimaryOwnerProtectedError) {
|
||||
return NextResponse.json(
|
||||
{ error: err.message, code: err.code },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (err instanceof TeamMemberValidationError) {
|
||||
const status = err.code === "TEAM_MEMBER_NOT_FOUND" ? 404 : 400;
|
||||
return NextResponse.json(
|
||||
{ error: err.message, code: err.code },
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Unable to update team member.";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const auth = await requireAdminApiSession(req, { minRole: "owner" });
|
||||
if (!auth.valid) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
try {
|
||||
const { id } = await params;
|
||||
const deleted = await deleteAdminTeamMemberAsync(id);
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || "owner",
|
||||
action: "TEAM_MEMBER_DELETED",
|
||||
target: deleted.email,
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: {
|
||||
memberId: deleted.id,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
deletedId: deleted.id,
|
||||
email: deleted.email,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof PrimaryOwnerProtectedError) {
|
||||
return NextResponse.json(
|
||||
{ error: err.message, code: err.code },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (err instanceof TeamMemberValidationError) {
|
||||
const status = err.code === "TEAM_MEMBER_NOT_FOUND" ? 404 : 400;
|
||||
return NextResponse.json(
|
||||
{ error: err.message, code: err.code },
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Unable to delete team member.";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import {
|
||||
createAdminTeamMemberAsync,
|
||||
listAdminTeamMembersAsync,
|
||||
TeamMemberValidationError,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { extractClientIp, requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireAdminApiSession(req, { minRole: "viewer" });
|
||||
if (!auth.valid) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
try {
|
||||
const members = await listAdminTeamMembersAsync();
|
||||
return NextResponse.json({
|
||||
members,
|
||||
currentRole: auth.auth.session.role || "owner",
|
||||
currentEmail: auth.auth.session.email,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Unable to list team members.";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireAdminApiSession(req, { minRole: "owner" });
|
||||
if (!auth.valid) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
const parsed = await req.json();
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "Team member payload must be a JSON object.",
|
||||
code: "VALIDATION_ERROR",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
body = parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid JSON request payload.", code: "INVALID_JSON" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const email = typeof body.email === "string" ? body.email : "";
|
||||
const password = typeof body.password === "string" ? body.password : "";
|
||||
const role = typeof body.role === "string" ? body.role : "viewer";
|
||||
|
||||
const created = await createAdminTeamMemberAsync({
|
||||
email,
|
||||
password,
|
||||
role,
|
||||
invitedBy: auth.auth.session.email,
|
||||
});
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || "owner",
|
||||
action: "TEAM_MEMBER_CREATED",
|
||||
target: created.email,
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: {
|
||||
memberId: created.id,
|
||||
role: created.role,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{ success: true, member: created },
|
||||
{ status: 201 },
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof TeamMemberValidationError) {
|
||||
const status = err.code === "TEAM_MEMBER_EXISTS" ? 409 : 400;
|
||||
return NextResponse.json(
|
||||
{ error: err.message, code: err.code },
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Unable to create team member.";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user