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.

audit log discount actions

Kiran K07d7d5a23fc3
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
index 578de9b305..30d5010368 100644
--- a/apps/web/lib/actions/partners/create-discount.ts
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -1,5 +1,6 @@
"use server";
+import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { createId } from "@/lib/api/create-id";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
@@ -13,7 +14,7 @@ import { authActionClient } from "../safe-action";
export const createDiscountAction = authActionClient
.schema(createDiscountSchema)
.action(async ({ parsedInput, ctx }) => {
- const { workspace } = ctx;
+ const { workspace, user } = ctx;
const { partnerIds, amount, type, maxDuration, couponId, couponTestId } =
parsedInput;
@@ -97,14 +98,33 @@ export const createDiscountAction = authActionClient
}
waitUntil(
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
- body: {
- programId,
- discountId: discount.id,
- isDefault,
- action: "discount-created",
- },
- }),
+ (async () => {
+ await Promise.allSettled([
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
+ body: {
+ programId,
+ discountId: discount.id,
+ isDefault,
+ action: "discount-created",
+ },
+ }),
+
+ recordAuditLog({
+ workspaceId: workspace.id,
+ programId,
+ action: "discount.created",
+ description: `Discount ${discount.id} created`,
+ actor: user,
+ targets: [
+ {
+ type: "discount",
+ id: discount.id,
+ metadata: discount,
+ },
+ ],
+ }),
+ ]);
+ })(),
);
});
diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.ts
index 83b60d2a68..90acd3804f 100644
--- a/apps/web/lib/actions/partners/delete-discount.ts
+++ b/apps/web/lib/actions/partners/delete-discount.ts
@@ -1,5 +1,6 @@
"use server";
+import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { getDiscountOrThrow } from "@/lib/api/partners/get-discount-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
@@ -19,7 +20,7 @@ const deleteDiscountSchema = z.object({
export const deleteDiscountAction = authActionClient
.schema(deleteDiscountSchema)
.action(async ({ parsedInput, ctx }) => {
- const { workspace } = ctx;
+ const { workspace, user } = ctx;
const { discountId } = parsedInput;
const programId = getDefaultProgramIdOrThrow(workspace);
@@ -29,7 +30,7 @@ export const deleteDiscountAction = authActionClient
programId,
});
- await getDiscountOrThrow({
+ const discount = await getDiscountOrThrow({
programId,
discountId,
});
@@ -98,15 +99,34 @@ export const deleteDiscountAction = authActionClient
if (deletedDiscountId) {
waitUntil(
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
- body: {
- programId,
- discountId,
- isDefault,
- action: "discount-deleted",
- },
- }),
+ (async () => {
+ await Promise.allSettled([
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
+ body: {
+ programId,
+ discountId,
+ isDefault,
+ action: "discount-deleted",
+ },
+ }),
+
+ recordAuditLog({
+ workspaceId: workspace.id,
+ programId,
+ action: "discount.deleted",
+ description: `Discount ${discountId} deleted`,
+ actor: user,
+ targets: [
+ {
+ type: "discount",
+ id: discountId,
+ metadata: discount,
+ },
+ ],
+ }),
+ ]);
+ })(),
);
}
});
diff --git a/apps/web/lib/actions/partners/update-discount.ts b/apps/web/lib/actions/partners/update-discount.ts
index fadb8c4b08..c1056a6727 100644
--- a/apps/web/lib/actions/partners/update-discount.ts
+++ b/apps/web/lib/actions/partners/update-discount.ts
@@ -1,5 +1,6 @@
"use server";
+import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { getDiscountOrThrow } from "@/lib/api/partners/get-discount-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
@@ -13,7 +14,7 @@ import { authActionClient } from "../safe-action";
export const updateDiscountAction = authActionClient
.schema(updateDiscountSchema)
.action(async ({ parsedInput, ctx }) => {
- const { workspace } = ctx;
+ const { workspace, user } = ctx;
const {
discountId,
partnerIds,
@@ -119,19 +120,34 @@ export const updateDiscountAction = authActionClient
},
);
- if (!shouldExpireCache) {
- return;
- }
+ await Promise.allSettled([
+ shouldExpireCache
+ ? qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
+ body: {
+ programId,
+ discountId,
+ isDefault,
+ action: "discount-updated",
+ },
+ })
+ : Promise.resolve(),
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
- body: {
+ recordAuditLog({
+ workspaceId: workspace.id,
programId,
- discountId,
- isDefault,
- action: "discount-updated",
- },
- });
+ action: "discount.updated",
+ description: `Discount ${discount.id} updated`,
+ actor: user,
+ targets: [
+ {
+ type: "discount",
+ id: discount.id,
+ metadata: updatedDiscount,
+ },
+ ],
+ }),
+ ]);
})(),
);
});
diff --git a/apps/web/lib/api/audit-logs/record-audit-log.ts b/apps/web/lib/api/audit-logs/record-audit-log.ts
index 482ff52213..f2be898e12 100644
--- a/apps/web/lib/api/audit-logs/record-audit-log.ts
+++ b/apps/web/lib/api/audit-logs/record-audit-log.ts
@@ -6,11 +6,7 @@ import { createId } from "../create-id";
import { getIP } from "../utils";
import { auditLogSchemaTB, recordAuditLogInputSchema } from "./schemas";
-export const recordAuditLogTB = tb.buildIngestEndpoint({
- datasource: "dub_audit_logs",
- event: auditLogSchemaTB,
- wait: true,
-});
+const ENABLE_AUDIT_LOGS = true;
// TODO:
// Support array of logs
@@ -21,28 +17,45 @@ export const recordAuditLog = async (
const location = data.req ? ipAddress(data.req) : getIP();
const userAgent = headersList.get("user-agent");
+ const auditLogInput = recordAuditLogInputSchema.parse({
+ ...data,
+ location,
+ userAgent,
+ });
+
const auditLog: z.infer<typeof auditLogSchemaTB> = {
id: createId({ prefix: "audit_" }),
timestamp: new Date().toISOString(),
- workspace_id: data.workspaceId,
- program_id: data.programId,
- action: data.action,
- actor_id: data.actor.id,
- actor_type: data.actor.type || "user",
- actor_name: data.actor.name || "",
- description: data.description || "",
+ workspace_id: auditLogInput.workspaceId,
+ program_id: auditLogInput.programId,
+ action: auditLogInput.action,
+ actor_id: auditLogInput.actor.id,
+ actor_type: auditLogInput.actor.type || "user",
+ actor_name: auditLogInput.actor.name || "",
+ description: auditLogInput.description || "",
+ targets: auditLogInput.targets ? JSON.stringify(auditLogInput.targets) : "",
+ metadata: auditLogInput.metadata
+ ? JSON.stringify(auditLogInput.metadata)
+ : "",
location: location || "",
user_agent: userAgent || "",
- targets: data.targets ? JSON.stringify(data.targets) : "",
- metadata: data.metadata ? JSON.stringify(data.metadata) : "",
};
- if (process.env.NODE_ENV === "development") {
- console.info("Inserting audit log", auditLog);
+ if (!ENABLE_AUDIT_LOGS) {
+ console.info(auditLog);
return;
}
await recordAuditLogTB(auditLog).catch((error) => {
- console.error("Failed to record audit log", error);
+ console.error("Failed to record audit log", error, auditLog);
+
+ // TODO:
+ // Send a Slack notification
});
};
+
+const recordAuditLogTB = tb.buildIngestEndpoint({
+ datasource: "dub_audit_logs",
+ event: auditLogSchemaTB,
+ wait: true,
+});
diff --git a/apps/web/lib/api/audit-logs/schemas.ts b/apps/web/lib/api/audit-logs/schemas.ts
index 54d3fa92ad..3c1f08cb88 100644
--- a/apps/web/lib/api/audit-logs/schemas.ts
+++ b/apps/web/lib/api/audit-logs/schemas.ts
@@ -20,7 +20,7 @@ export const auditLogSchemaTB = z.object({
});
// Schema that represents the audit log in the CSV file
-export const AuditLogSchema = z.object({
+export const auditLogSchema = z.object({
id: z.string(),
timestamp: z.string(),
workspaceId: z.string(),
@@ -36,7 +36,19 @@ export const AuditLogSchema = z.object({
metadata: z.record(z.string(), z.any()).nullable(),
});
-const RewardEvent = z.object({
+const actionSchema = z.enum([
+ // Rewards
+ "reward.created",
+ "reward.updated",
+ "reward.deleted",
+
+ // Discounts
+ "discount.created",
+ "discount.updated",
+ "discount.deleted",
+]);
+
+const rewardEvent = z.object({
type: z.literal("reward"),
id: z.string(),
metadata: RewardSchema.pick({
@@ -47,31 +59,32 @@ const RewardEvent = z.object({
}),
});
-const DiscountEvent = z.object({
+const discountEvent = z.object({
type: z.literal("discount"),
id: z.string(),
metadata: DiscountSchema.pick({
type: true,
amount: true,
maxDuration: true,
+ couponId: true,
}),
});
-export const AuditLogEvent = z.union([RewardEvent, DiscountEvent]);
+export const auditLogEvent = z.union([rewardEvent, discountEvent]);
export const recordAuditLogInputSchema = z.object({
workspaceId: z.string(),
programId: z.string(),
- action: z.string(),
+ action: actionSchema,
actor: z.object({
id: z.string(),
- name: z.string().nullable(),
- type: z.string().optional(),
+ name: z.string().nullish(),
+ type: z.string().nullish(),
}),
- description: z.string().optional(),
- location: z.string().optional(),
- userAgent: z.string().optional(),
- targets: z.array(AuditLogEvent).nullable(),
- metadata: z.record(z.string(), z.any()).nullable(),
- req: z.instanceof(Request).optional(),
+ description: z.string().nullish(),
+ location: z.string().nullish(),
+ userAgent: z.string().nullish(),
+ targets: z.array(auditLogEvent).nullish(),
+ metadata: z.record(z.string(), z.any()).nullish(),
+ req: z.instanceof(Request).nullish(),
});
diff --git a/packages/tinybird/datasources/dub_audit_logs.datasource b/packages/tinybird/datasources/dub_audit_logs.datasource
index 9633ab0580..2b32c46ecf 100644
--- a/packages/tinybird/datasources/dub_audit_logs.datasource
+++ b/packages/tinybird/datasources/dub_audit_logs.datasource
@@ -16,4 +16,4 @@ SCHEMA >
ENGINE "MergeTree"
ENGINE_PARTITION_KEY "toYYYYMM(timestamp)"
ENGINE_SORTING_KEY "workspace_id, program_id, timestamp"
-ENGINE_TTL "timestamp + INTERVAL 1 YEAR"
\ No newline at end of file
+ENGINE_TTL "toDateTime(timestamp) + INTERVAL 1 YEAR"
\ No newline at end of file