Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add audit log export functionality with CSV support

Kiran K85a724fec451
diff --git a/apps/web/app/(ee)/api/audit-logs/export/route.ts b/apps/web/app/(ee)/api/audit-logs/export/route.ts
new file mode 100644
index 0000000000..fd364320ab
--- /dev/null
+++ b/apps/web/app/(ee)/api/audit-logs/export/route.ts
@@ -0,0 +1,60 @@
+import { convertToCSV } from "@/lib/analytics/utils";
+import { getAuditLogs } from "@/lib/api/audit-logs/get-audit-logs";
+import { DubApiError } from "@/lib/api/errors";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
+import { z } from "zod";
+
+const auditLogExportQuerySchema = z.object({
+ start: z.string(),
+ end: z.string(),
+});
+
+// POST /api/audit-logs/export – export audit logs to CSV
+export const POST = withWorkspace(
+ async ({ req, workspace }) => {
+ const { start, end } = auditLogExportQuerySchema.parse(
+ await parseRequestBody(req),
+ );
+
+ if (!start || !end) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Must provide start and end dates.",
+ });
+ }
+
+ const { canExportAuditLogs } = getPlanCapabilities(workspace.plan);
+
+ if (!canExportAuditLogs) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "You are not authorized to export audit logs.",
+ });
+ }
+
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const auditLogs = await getAuditLogs({
+ workspaceId: workspace.id,
+ programId,
+ start: new Date(start),
+ end: new Date(end),
+ });
+
+ const csvData = convertToCSV(auditLogs);
+
+ return new Response(csvData, {
+ headers: {
+ "Content-Type": "application/csv",
+ "Content-Disposition": `attachment;`,
+ },
+ });
+ },
+ {
+ requiredPermissions: ["workspaces.write"],
+ requiredPlan: ["enterprise"],
+ },
+);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/security/audit-log.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/security/audit-log.tsx
new file mode 100644
index 0000000000..4f3d97ba48
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/security/audit-log.tsx
@@ -0,0 +1,131 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
+import { Button, TooltipContent } from "@dub/ui";
+import { subMonths } from "date-fns";
+import { useState } from "react";
+import { toast } from "sonner";
+
+const defaultDateRange = {
+ from: subMonths(new Date(), 12),
+ to: new Date(),
+} as const;
+
+export function AuditLog() {
+ const [loading, setLoading] = useState(false);
+ const { plan, slug, id: workspaceId } = useWorkspace();
+ const [dateRange, setDateRange] = useState(defaultDateRange);
+
+ const isEnterprise = plan === "enterprise";
+
+ const exportAuditLogs = async () => {
+ if (!workspaceId) {
+ return;
+ }
+
+ setLoading(true);
+
+ const lid = toast.loading("Exporting audit logs...");
+
+ try {
+ const response = await fetch(
+ `/api/audit-logs/export?workspaceId=${workspaceId}`,
+ {
+ method: "POST",
+ body: JSON.stringify({
+ start: dateRange.from.toISOString(),
+ end: dateRange.to.toISOString(),
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ },
+ },
+ );
+
+ if (!response.ok) {
+ const { error } = await response.json();
+ throw new Error(error.message);
+ }
+
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+
+ a.href = url;
+ a.download = `Dub Audit Logs Export - ${new Date().toISOString()}.csv`;
+ a.click();
+
+ toast.success("Exported successfully");
+ } catch (error) {
+ toast.error(error);
+ } finally {
+ setLoading(false);
+ toast.dismiss(lid);
+ }
+ };
+
+ return (
+ <div className="rounded-lg border border-neutral-200 bg-white">
+ <div className="flex flex-col gap-6 p-5 sm:p-10">
+ <div className="flex flex-col gap-1.5">
+ <h2 className="text-xl font-semibold">Audit Log</h2>
+ <p className="text-sm text-neutral-500">
+ Workspace partner and payout history
+ </p>
+ </div>
+ <div className="flex flex-col gap-4 rounded-md border border-neutral-200 bg-neutral-50 p-4 sm:flex-row sm:items-center sm:justify-between sm:gap-2 sm:bg-white">
+ <SimpleDateRangePicker
+ className="w-full sm:max-w-xs"
+ align="start"
+ disabled={!isEnterprise}
+ />
+
+ <Button
+ text="Export CSV"
+ variant="secondary"
+ className="w-full sm:w-auto"
+ disabledTooltip={
+ !isEnterprise && (
+ <TooltipContent
+ title="Audit log export is only available on the Enterprise Plan."
+ cta="Contact sales"
+ href="https://dub.co/enterprise"
+ target="_blank"
+ />
+ )
+ }
+ disabled={!isEnterprise}
+ onClick={exportAuditLogs}
+ loading={loading}
+ />
+ </div>
+ </div>
+
+ {!isEnterprise && (
+ <div className="flex items-center justify-between rounded-b-lg border-t border-neutral-200 bg-neutral-50 px-3 py-3 sm:px-10">
+ <span className="text-sm text-neutral-500">
+ Audit logs are available on the{" "}
+ <a
+ href="https://dub.co/enterprise"
+ target="_blank"
+ className="text-neutral-700 underline"
+ >
+ Enterprise Plan
+ </a>
+ </span>
+ <Button
+ text="Upgrade"
+ className="h-8 w-auto px-5"
+ onClick={() =>
+ window.open(
+ slug ? `/${slug}/upgrade` : "https://dub.co/enterprise",
+ "_blank",
+ )
+ }
+ />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/lib/api/audit-logs/get-audit-logs.ts b/apps/web/lib/api/audit-logs/get-audit-logs.ts
new file mode 100644
index 0000000000..69b9b809bd
--- /dev/null
+++ b/apps/web/lib/api/audit-logs/get-audit-logs.ts
@@ -0,0 +1,50 @@
+import { tb } from "@/lib/tinybird";
+import { z } from "zod";
+
+export const auditLogFilterSchemaTB = z.object({
+ workspaceId: z.string(),
+ programId: z.string(),
+ start: z.string(),
+ end: z.string(),
+});
+
+export const auditLogResponseSchemaTB = z.object({
+ id: z.string(),
+ timestamp: z.string(),
+ action: z.string(),
+ actor_id: z.string(),
+ actor_type: z.string(),
+ actor_name: z.string(),
+ description: z.string(),
+ location: z.string(),
+ user_agent: z.string(),
+ targets: z.string(),
+ metadata: z.string(),
+});
+
+export const getAuditLogs = async ({
+ workspaceId,
+ programId,
+ start,
+ end,
+}: {
+ start: Date;
+ end: Date;
+ workspaceId: string;
+ programId: string;
+}) => {
+ const pipe = tb.buildPipe({
+ pipe: "get_audit_logs",
+ parameters: auditLogFilterSchemaTB,
+ data: auditLogResponseSchemaTB,
+ });
+
+ const events = await pipe({
+ workspaceId,
+ programId,
+ start: start.toISOString().replace("T", " ").replace("Z", ""),
+ end: end.toISOString().replace("T", " ").replace("Z", ""),
+ });
+
+ return events.data;
+};
diff --git a/apps/web/lib/plan-capabilities.ts b/apps/web/lib/plan-capabilities.ts
index 94cca51975..fb6402087f 100644
--- a/apps/web/lib/plan-capabilities.ts
+++ b/apps/web/lib/plan-capabilities.ts
@@ -10,5 +10,6 @@ export const getPlanCapabilities = (
canManageCustomers: !!plan && !["free", "pro"].includes(plan),
canManageProgram: !!plan && !["free", "pro"].includes(plan),
canTrackConversions: !!plan && !["free", "pro"].includes(plan),
+ canExportAuditLogs: !!plan && ["enterprise"].includes(plan),
};
};
diff --git a/apps/web/ui/shared/simple-date-range-picker.tsx b/apps/web/ui/shared/simple-date-range-picker.tsx
index bfda903cb5..f41790e013 100644
--- a/apps/web/ui/shared/simple-date-range-picker.tsx
+++ b/apps/web/ui/shared/simple-date-range-picker.tsx
@@ -5,10 +5,12 @@ export default function SimpleDateRangePicker({
className,
align = "center",
defaultInterval = "30d",
+ disabled,
}: {
className?: string;
align?: "start" | "center" | "end";
defaultInterval?: string;
+ disabled?: boolean;
}) {
const { queryParams, searchParamsObj } = useRouterStuff();
const { start, end, interval } = searchParamsObj as {
@@ -69,6 +71,7 @@ export default function SimpleDateRangePicker({
shortcut,
};
})}
+ disabled={disabled}
/>
);
}
diff --git a/packages/tinybird/pipes/audit_logs.pipe b/packages/tinybird/pipes/audit_logs.pipe
new file mode 100644
index 0000000000..c9af353ae6
--- /dev/null
+++ b/packages/tinybird/pipes/audit_logs.pipe
@@ -0,0 +1,26 @@
+NODE endpoint
+SQL >
+
+ %
+ SELECT
+ id,
+ timestamp,
+ action,
+ actor_id,
+ actor_type,
+ actor_name,
+ targets,
+ description,
+ location,
+ user_agent,
+ metadata
+ FROM dub_audit_logs
+ WHERE
+ true
+ {% if defined(start) and defined(end) %}
+ AND timestamp >= {{ DateTime(start, '2024-06-01 00:00:00') }}
+ AND timestamp < {{ DateTime(end, '2024-06-07 00:00:00') }}
+ {% end %}
+ {% if defined(workspaceId) %} AND workspace_id = {{ String(workspaceId) }} {% end %}
+ {% if defined(programId) %} AND program_id = {{ String(programId) }} {% end %}
+ ORDER BY timestamp DESC