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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { AuditLogViewer } from '@/components/sections/AuditLogViewer';
|
||||
|
||||
export default function AuditPage() {
|
||||
return <AuditLogViewer />;
|
||||
}
|
||||
+220
-37
@@ -20,8 +20,11 @@ interface SdkClientItem {
|
||||
token?: string;
|
||||
}
|
||||
|
||||
type SdkLanguageTab = 'python' | 'node' | 'curl';
|
||||
|
||||
export default function SdkGuidePage() {
|
||||
const { success, error } = useToast();
|
||||
const [activeTab, setActiveTab] = useState<SdkLanguageTab>('python');
|
||||
const [clients, setClients] = useState<SdkClientItem[]>(() =>
|
||||
getCached<SdkClientItem[]>('vcon:clients', [])
|
||||
);
|
||||
@@ -128,13 +131,14 @@ export default function SdkGuidePage() {
|
||||
const sampleToken = loadingToken
|
||||
? 'LOADING_CLIENT_JWT_TOKEN...'
|
||||
: resolvedToken || 'YOUR_SIGNED_CLIENT_JWT_TOKEN';
|
||||
const clientIdValue = activeClient?.clientId || '';
|
||||
|
||||
const configSnippet = `# config.datastack.py — Place in your Python project root
|
||||
const pythonConfigSnippet = `# config.datastack.py — Place in your Python project root
|
||||
DATASTACK_CONFIG = {
|
||||
"SERVER_URL": "${serverUrl}",
|
||||
"API_URL": "${apiUrl}",
|
||||
"CLIENT_TOKEN": "${sampleToken}",
|
||||
"CLIENT_ID": "${activeClient?.clientId || ''}",
|
||||
"CLIENT_ID": "${clientIdValue}",
|
||||
"AUTO_CONNECT": True,
|
||||
"ENABLE_HTTP_FALLBACK": True,
|
||||
"HEARTBEAT_INTERVAL_SEC": 5.0,
|
||||
@@ -173,6 +177,109 @@ print("SDK Status:", client.status())
|
||||
|
||||
client.disconnect()`;
|
||||
|
||||
const nodeConfigSnippet = `// datastack.config.json — Place in your Node.js / TypeScript project root
|
||||
{
|
||||
"serverUrl": "${serverUrl}",
|
||||
"apiUrl": "${apiUrl}",
|
||||
"clientToken": "${sampleToken}",
|
||||
"clientId": "${clientIdValue}",
|
||||
"autoConnect": true,
|
||||
"enableHttpFallback": true,
|
||||
"heartbeatIntervalMs": 5000,
|
||||
"maxRetries": 3,
|
||||
"batchChunkSize": 250,
|
||||
"offlineSpoolEnabled": true,
|
||||
"offlineSpoolDir": ".datastack_spool"
|
||||
}`;
|
||||
|
||||
const nodeSnippet = `import { DataStack } from '@datastack/sdk';
|
||||
|
||||
// Loads datastack.config.json or explicit constructor options
|
||||
const client = new DataStack({
|
||||
serverUrl: '${serverUrl}',
|
||||
apiUrl: '${apiUrl}',
|
||||
token: '${sampleToken}',
|
||||
clientId: '${clientIdValue}',
|
||||
autoConnect: true,
|
||||
});
|
||||
|
||||
// 1. Single Event (Socket.IO Primary + Auto HTTP Fallback + Offline Spool)
|
||||
const res = await client.send({
|
||||
event_type: 'checkout_completed',
|
||||
order_id: 'ord_9942',
|
||||
amount_usd: 149.5,
|
||||
});
|
||||
console.log('Event response:', res);
|
||||
|
||||
// 2. Batch Events (Auto-chunked & 413/429 resilient)
|
||||
const batchRes = await client.sendBatch([
|
||||
{ sensor: 'temp', value: 24.5, unit: 'C' },
|
||||
{ sensor: 'humidity', value: 61.2, unit: '%' },
|
||||
]);
|
||||
console.log('Batch response:', batchRes);
|
||||
|
||||
// 3. Direct File Ingestion (.csv, .json, .jsonl, .ndjson with SHA-256 deterministic eventId)
|
||||
const fileRes = await client.sendFile('./events_dataset.csv', { chunkSize: 250 });
|
||||
console.log('File ingestion:', fileRes);
|
||||
|
||||
// 4. Graceful Shutdown Drain (awaits in-flight + drains offline spool)
|
||||
await client.shutdown(5000);`;
|
||||
|
||||
const curlConfigSnippet = `# Environment exports for HTTP / cURL ingestion
|
||||
export DATASTACK_API_URL="${apiUrl}"
|
||||
export DATASTACK_CLIENT_ID="${clientIdValue}"
|
||||
export DATASTACK_CLIENT_TOKEN="${sampleToken}"`;
|
||||
|
||||
const curlSnippet = `# 1. Single Event Ingestion via HTTP POST /api/events
|
||||
curl -X POST "${apiUrl}/api/events" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-H "Authorization: Bearer ${sampleToken}" \\
|
||||
-d '{
|
||||
"clientId": "${clientIdValue}",
|
||||
"data": {
|
||||
"event_type": "deployment_finished",
|
||||
"service": "billing-api",
|
||||
"status": "healthy"
|
||||
}
|
||||
}'
|
||||
|
||||
# 2. Batch Event Ingestion via HTTP POST /api/events
|
||||
curl -X POST "${apiUrl}/api/events" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-H "Authorization: Bearer ${sampleToken}" \\
|
||||
-d '{
|
||||
"clientId": "${clientIdValue}",
|
||||
"batch": [
|
||||
{ "data": { "metric": "cpu_pct", "value": 31.4 } },
|
||||
{ "data": { "metric": "mem_pct", "value": 58.2 } }
|
||||
]
|
||||
}'`;
|
||||
|
||||
const activeConfigSnippet =
|
||||
activeTab === 'node'
|
||||
? nodeConfigSnippet
|
||||
: activeTab === 'curl'
|
||||
? curlConfigSnippet
|
||||
: pythonConfigSnippet;
|
||||
const activeCodeSnippet =
|
||||
activeTab === 'node'
|
||||
? nodeSnippet
|
||||
: activeTab === 'curl'
|
||||
? curlSnippet
|
||||
: pythonSnippet;
|
||||
const activeConfigLabel =
|
||||
activeTab === 'node'
|
||||
? 'datastack.config.json'
|
||||
: activeTab === 'curl'
|
||||
? 'Environment Variables'
|
||||
: 'config.datastack.py';
|
||||
const activeCodeLabel =
|
||||
activeTab === 'node'
|
||||
? 'Node.js / TypeScript SDK snippet'
|
||||
: activeTab === 'curl'
|
||||
? 'cURL REST snippet'
|
||||
: 'Python SDK snippet';
|
||||
|
||||
const copySnippet = async (text: string, label: string) => {
|
||||
try {
|
||||
if (!navigator?.clipboard?.writeText) {
|
||||
@@ -192,7 +299,7 @@ client.disconnect()`;
|
||||
|
||||
return (
|
||||
<PageShell
|
||||
title="Python SDK"
|
||||
title="Client SDKs (Python & Node.js / TypeScript)"
|
||||
actions={
|
||||
<>
|
||||
{resolvedToken && (
|
||||
@@ -211,7 +318,7 @@ client.disconnect()`;
|
||||
variant="secondary"
|
||||
icon="FileCode"
|
||||
disabled={loadingToken}
|
||||
onClick={() => void copySnippet(configSnippet, 'config.datastack.py')}
|
||||
onClick={() => void copySnippet(activeConfigSnippet, activeConfigLabel)}
|
||||
>
|
||||
Copy Config
|
||||
</Button>
|
||||
@@ -219,7 +326,7 @@ client.disconnect()`;
|
||||
size="xs"
|
||||
variant="secondary"
|
||||
icon="Copy"
|
||||
onClick={() => void copySnippet(pythonSnippet, 'Python SDK snippet')}
|
||||
onClick={() => void copySnippet(activeCodeSnippet, activeCodeLabel)}
|
||||
>
|
||||
Copy Code
|
||||
</Button>
|
||||
@@ -228,7 +335,16 @@ client.disconnect()`;
|
||||
>
|
||||
<StatStrip
|
||||
items={[
|
||||
{ label: 'SDK package', value: 'datastack (v2.2.0)', dot: 'ok' },
|
||||
{
|
||||
label: 'SDK packages',
|
||||
value:
|
||||
activeTab === 'node'
|
||||
? '@datastack/sdk (v2.2.0)'
|
||||
: activeTab === 'curl'
|
||||
? 'REST HTTP/1.1 & HTTP/2'
|
||||
: 'datastack (v2.2.0)',
|
||||
dot: 'ok',
|
||||
},
|
||||
{ label: 'Transport', value: 'WS + HTTP Fallback + Offline Spool' },
|
||||
{ label: 'Server endpoint', value: serverUrl },
|
||||
{
|
||||
@@ -243,36 +359,103 @@ client.disconnect()`;
|
||||
]}
|
||||
/>
|
||||
|
||||
<Card
|
||||
compact
|
||||
className="flex w-full flex-col gap-1.5 bg-[var(--surface)] px-3 py-2.5"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2 font-mono text-[11.5px]">
|
||||
<span className="truncate text-[var(--accent)]">
|
||||
pip install /path/to/datastack/sdk/python/datastack
|
||||
</span>
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2 border border-[var(--border)] bg-[var(--surface)] px-3 py-2">
|
||||
<div className="flex items-center gap-1.5" role="tablist" aria-label="SDK Language Selector">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
icon="Copy"
|
||||
aria-label="Copy pip install command"
|
||||
onClick={() =>
|
||||
void copySnippet(
|
||||
'pip install /path/to/datastack/sdk/python/datastack',
|
||||
'Pip command'
|
||||
)
|
||||
}
|
||||
/>
|
||||
variant={activeTab === 'python' ? 'primary' : 'secondary'}
|
||||
onClick={() => setActiveTab('python')}
|
||||
>
|
||||
Python SDK (v2.2.0)
|
||||
</Button>
|
||||
<Button
|
||||
size="xs"
|
||||
variant={activeTab === 'node' ? 'primary' : 'secondary'}
|
||||
onClick={() => setActiveTab('node')}
|
||||
>
|
||||
Node.js / TypeScript SDK (v2.2.0)
|
||||
</Button>
|
||||
<Button
|
||||
size="xs"
|
||||
variant={activeTab === 'curl' ? 'primary' : 'secondary'}
|
||||
onClick={() => setActiveTab('curl')}
|
||||
>
|
||||
HTTP / cURL
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-[11px] text-[var(--text-faint)]">
|
||||
Self-hosted package bundled in <code className="font-mono text-[var(--text-muted)]">sdk/python/datastack</code>. From inside the repo run{' '}
|
||||
<code className="font-mono text-[var(--text-muted)]">pip install ./sdk/python/datastack</code>, or build a portable wheel with{' '}
|
||||
<code className="font-mono text-[var(--text-muted)]">pip wheel ./sdk/python/datastack -w dist/</code> for external projects.
|
||||
</p>
|
||||
</Card>
|
||||
<span className="font-mono text-[10.5px] text-[var(--text-faint)]">
|
||||
{activeTab === 'node'
|
||||
? 'sdk/node/datastack'
|
||||
: activeTab === 'curl'
|
||||
? 'POST /api/events'
|
||||
: 'sdk/python/datastack'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{activeTab === 'python' && (
|
||||
<Card
|
||||
compact
|
||||
className="flex w-full flex-col gap-1.5 bg-[var(--surface)] px-3 py-2.5"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2 font-mono text-[11.5px]">
|
||||
<span className="truncate text-[var(--accent)]">
|
||||
pip install /path/to/datastack/sdk/python/datastack
|
||||
</span>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
icon="Copy"
|
||||
aria-label="Copy pip install command"
|
||||
onClick={() =>
|
||||
void copySnippet(
|
||||
'pip install /path/to/datastack/sdk/python/datastack',
|
||||
'Pip command'
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-[11px] text-[var(--text-faint)]">
|
||||
Self-hosted package bundled in <code className="font-mono text-[var(--text-muted)]">sdk/python/datastack</code>. From inside the repo run{' '}
|
||||
<code className="font-mono text-[var(--text-muted)]">pip install ./sdk/python/datastack</code>, or build a portable wheel with{' '}
|
||||
<code className="font-mono text-[var(--text-muted)]">pip wheel ./sdk/python/datastack -w dist/</code> for external projects.
|
||||
</p>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{activeTab === 'node' && (
|
||||
<Card
|
||||
compact
|
||||
className="flex w-full flex-col gap-1.5 bg-[var(--surface)] px-3 py-2.5"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2 font-mono text-[11.5px]">
|
||||
<span className="truncate text-[var(--accent)]">
|
||||
npm install /path/to/datastack/sdk/node/datastack
|
||||
</span>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
icon="Copy"
|
||||
aria-label="Copy npm install command"
|
||||
onClick={() =>
|
||||
void copySnippet(
|
||||
'npm install /path/to/datastack/sdk/node/datastack',
|
||||
'NPM command'
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-[11px] text-[var(--text-faint)]">
|
||||
Official Node.js & TypeScript package bundled in{' '}
|
||||
<code className="font-mono text-[var(--text-muted)]">sdk/node/datastack</code> (Node >= 20). Supports Socket.IO primary streaming, automatic{' '}
|
||||
<code className="font-mono text-[var(--text-muted)]">POST /api/events</code> fallback, deterministic{' '}
|
||||
<code className="font-mono text-[var(--text-muted)]">sendFile()</code> SHA-256 deduplication, offline disk spooling, and graceful{' '}
|
||||
<code className="font-mono text-[var(--text-muted)]">await client.shutdown()</code>.
|
||||
</p>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Panel
|
||||
title="Step 1 — config.datastack.py"
|
||||
title={`Step 1 — ${activeConfigLabel}`}
|
||||
className="w-full"
|
||||
action={
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -296,14 +479,14 @@ client.disconnect()`;
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
icon="Copy"
|
||||
aria-label="Copy config.datastack.py"
|
||||
aria-label={`Copy ${activeConfigLabel}`}
|
||||
disabled={loadingToken}
|
||||
onClick={() => void copySnippet(configSnippet, 'config.datastack.py')}
|
||||
onClick={() => void copySnippet(activeConfigSnippet, activeConfigLabel)}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<CodeBlock>{configSnippet}</CodeBlock>
|
||||
<CodeBlock>{activeConfigSnippet}</CodeBlock>
|
||||
</Panel>
|
||||
|
||||
<Panel
|
||||
@@ -314,12 +497,12 @@ client.disconnect()`;
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
icon="Copy"
|
||||
aria-label="Copy Python SDK snippet"
|
||||
onClick={() => void copySnippet(pythonSnippet, 'Python SDK snippet')}
|
||||
aria-label={`Copy ${activeCodeLabel}`}
|
||||
onClick={() => void copySnippet(activeCodeSnippet, activeCodeLabel)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<CodeBlock>{pythonSnippet}</CodeBlock>
|
||||
<CodeBlock>{activeCodeSnippet}</CodeBlock>
|
||||
</Panel>
|
||||
</PageShell>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { TeamWorkspace } from '@/components/sections/TeamWorkspace';
|
||||
|
||||
export default function TeamPage() {
|
||||
return <TeamWorkspace />;
|
||||
}
|
||||
Reference in new issue
Block a user