feat: harden portal security and auditability
This commit is contained in:
1 parent
7f1ecd9322
commit
21871bb9ff
26 files changed
+2664
-4
No files matched your search
@@ -0,0 +1,140 @@
|
||||
import "server-only";
|
||||
|
||||
import { and, desc, eq, gte, lte, sql, type SQL } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import { auditEvents, users } from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type AuditEventRow = {
|
||||
id: string;
|
||||
eventType: string;
|
||||
actorUserId: string | null;
|
||||
actorEmail: string | null;
|
||||
actorType: string;
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
previousValues: unknown;
|
||||
newValues: unknown;
|
||||
occurredAt: Date;
|
||||
requestId: string | null;
|
||||
};
|
||||
|
||||
export type AuditFilters = {
|
||||
eventType?: string;
|
||||
dateFrom?: Date;
|
||||
dateTo?: Date;
|
||||
};
|
||||
|
||||
export type AuditPage = {
|
||||
events: AuditEventRow[];
|
||||
nextCursor: string | null;
|
||||
};
|
||||
|
||||
export type AuditQueryRepository = {
|
||||
listEvents(filters: AuditFilters, cursor: string | null, limit: number): Promise<AuditPage>;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Repository factory
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function createAuditQueryRepository(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
): AuditQueryRepository {
|
||||
return {
|
||||
async listEvents(filters, cursor, limit) {
|
||||
const conditions: SQL[] = [];
|
||||
|
||||
if (filters.eventType) {
|
||||
conditions.push(eq(auditEvents.eventType, filters.eventType));
|
||||
}
|
||||
if (filters.dateFrom) {
|
||||
conditions.push(gte(auditEvents.occurredAt, filters.dateFrom));
|
||||
}
|
||||
if (filters.dateTo) {
|
||||
conditions.push(lte(auditEvents.occurredAt, filters.dateTo));
|
||||
}
|
||||
|
||||
// Cursor: base64-encoded "occurredAtIso|id" for stable ordering by
|
||||
// (occurredAt DESC, id DESC). We use a composite cursor because
|
||||
// occurredAt alone is not unique.
|
||||
if (cursor) {
|
||||
const { occurredAtIso, id } = decodeCursor(cursor);
|
||||
conditions.push(
|
||||
// ponytail: row-value comparison via OR — upgrade to tuple > if
|
||||
// Drizzle adds native row-value support for our pg version.
|
||||
// (occurredAt < cursor) OR (occurredAt = cursor AND id < cursorId)
|
||||
sql`(${auditEvents.occurredAt} < ${occurredAtIso} OR (${auditEvents.occurredAt} = ${occurredAtIso} AND ${auditEvents.id} < ${id}))`,
|
||||
);
|
||||
}
|
||||
|
||||
const rows = await database
|
||||
.select({
|
||||
id: auditEvents.id,
|
||||
eventType: auditEvents.eventType,
|
||||
actorUserId: auditEvents.actorUserId,
|
||||
actorEmail: users.email,
|
||||
actorType: auditEvents.actorType,
|
||||
entityType: auditEvents.entityType,
|
||||
entityId: auditEvents.entityId,
|
||||
previousValues: auditEvents.previousValues,
|
||||
newValues: auditEvents.newValues,
|
||||
occurredAt: auditEvents.occurredAt,
|
||||
requestId: auditEvents.requestId,
|
||||
})
|
||||
.from(auditEvents)
|
||||
.leftJoin(users, eq(auditEvents.actorUserId, users.id))
|
||||
.where(conditions.length > 0 ? and(...conditions) : undefined)
|
||||
.orderBy(desc(auditEvents.occurredAt), desc(auditEvents.id))
|
||||
.limit(limit + 1);
|
||||
|
||||
const hasMore = rows.length > limit;
|
||||
const pageRows = hasMore ? rows.slice(0, limit) : rows;
|
||||
const nextCursor = hasMore
|
||||
? encodeCursor(pageRows[pageRows.length - 1].occurredAt, pageRows[pageRows.length - 1].id)
|
||||
: null;
|
||||
|
||||
return {
|
||||
events: pageRows as AuditEventRow[],
|
||||
nextCursor,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function encodeCursor(occurredAt: Date, id: string): string {
|
||||
return Buffer.from(`${occurredAt.toISOString()}|${id}`).toString("base64url");
|
||||
}
|
||||
|
||||
function decodeCursor(cursor: string): { occurredAtIso: string; id: string } {
|
||||
const decoded = Buffer.from(cursor, "base64url").toString("utf-8");
|
||||
const [occurredAtIso, id] = decoded.split("|");
|
||||
if (!occurredAtIso || !id) throw new Error("Invalid audit cursor");
|
||||
return { occurredAtIso, id };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Query layer — admin-only via requireAdmin at the route/page layer
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function createAuditQueryService(repository: AuditQueryRepository) {
|
||||
return {
|
||||
async listAuditEvents(
|
||||
filters: AuditFilters,
|
||||
cursor: string | null,
|
||||
limit = 50,
|
||||
): Promise<AuditPage> {
|
||||
const boundedLimit = Math.min(Math.max(limit, 1), 100);
|
||||
return repository.listEvents(filters, cursor, boundedLimit);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const auditQueryService = createAuditQueryService(createAuditQueryRepository(db));
|
||||
export const listAuditEvents = auditQueryService.listAuditEvents;
|
||||
@@ -0,0 +1,107 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { createAuditWriter, type AuditRepository } from "./write";
|
||||
|
||||
function createMockRepo() {
|
||||
const inserted: unknown[] = [];
|
||||
const repository: AuditRepository = {
|
||||
async insert(record) {
|
||||
inserted.push(record);
|
||||
},
|
||||
};
|
||||
const spy = vi.spyOn(repository, "insert");
|
||||
return { repository, inserted, spy };
|
||||
}
|
||||
|
||||
test("redacts secrets before writing audit metadata", async () => {
|
||||
const { repository, spy } = createMockRepo();
|
||||
const writer = createAuditWriter(repository);
|
||||
|
||||
await writer.writeAudit({
|
||||
type: "CONFIG_CHECK",
|
||||
entityType: "system",
|
||||
entityId: "config",
|
||||
metadata: { apiKey: "secret", nested: { password: "secret" }, albumId: "a1" },
|
||||
});
|
||||
|
||||
expect(spy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
metadata: {
|
||||
apiKey: "[REDACTED]",
|
||||
nested: { password: "[REDACTED]" },
|
||||
albumId: "a1",
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("redacts secrets in previousValues and newValues", async () => {
|
||||
const { repository, spy } = createMockRepo();
|
||||
const writer = createAuditWriter(repository);
|
||||
|
||||
await writer.writeAudit({
|
||||
type: "STATUS_CHANGED",
|
||||
entityType: "editorial",
|
||||
entityId: "e1",
|
||||
previousValues: { status: "active", token: "abc" },
|
||||
newValues: { status: "suspended", authorization: "bearer xyz" },
|
||||
});
|
||||
|
||||
expect(spy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
previousValues: { status: "active", token: "[REDACTED]" },
|
||||
newValues: { status: "suspended", authorization: "[REDACTED]" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("passes through non-secret values unchanged", async () => {
|
||||
const { repository, spy } = createMockRepo();
|
||||
const writer = createAuditWriter(repository);
|
||||
|
||||
await writer.writeAudit({
|
||||
type: "USAGE_CREATED",
|
||||
entityType: "usage",
|
||||
entityId: "u1",
|
||||
metadata: { albumId: "a1", priceCents: 1500, items: [{ id: "x1" }] },
|
||||
});
|
||||
|
||||
expect(spy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
metadata: { albumId: "a1", priceCents: 1500, items: [{ id: "x1" }] },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("redacts secrets inside arrays", async () => {
|
||||
const { repository, spy } = createMockRepo();
|
||||
const writer = createAuditWriter(repository);
|
||||
|
||||
await writer.writeAudit({
|
||||
type: "BULK",
|
||||
entityType: "system",
|
||||
entityId: "bulk",
|
||||
metadata: { entries: [{ apiKey: "secret", name: "foo" }] },
|
||||
});
|
||||
|
||||
expect(spy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
metadata: { entries: [{ apiKey: "[REDACTED]", name: "foo" }] },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("handles null and undefined metadata gracefully", async () => {
|
||||
const { repository, spy } = createMockRepo();
|
||||
const writer = createAuditWriter(repository);
|
||||
|
||||
await writer.writeAudit({
|
||||
type: "SIMPLE",
|
||||
entityType: "system",
|
||||
entityId: "s1",
|
||||
});
|
||||
|
||||
expect(spy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ metadata: undefined }),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import "server-only";
|
||||
|
||||
import { sql } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import { auditEvents } from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type AuditInput = {
|
||||
type: string;
|
||||
actorUserId?: string;
|
||||
actorType?: string;
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
previousValues?: Record<string, unknown>;
|
||||
newValues?: Record<string, unknown>;
|
||||
occurredAt?: Date;
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
export type AuditRepository = {
|
||||
insert(record: AuditInput): Promise<void>;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Recursive secret redaction
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SECRET_KEY_PATTERNS = [
|
||||
/key/i,
|
||||
/password/i,
|
||||
/secret/i,
|
||||
/token/i,
|
||||
/auth/i,
|
||||
/credential/i,
|
||||
];
|
||||
|
||||
const REDACTED = "[REDACTED]";
|
||||
|
||||
function isSecretKey(key: string): boolean {
|
||||
return SECRET_KEY_PATTERNS.some((pattern) => pattern.test(key));
|
||||
}
|
||||
|
||||
export function redactSecrets(value: unknown): unknown {
|
||||
if (value === null || value === undefined) return value;
|
||||
if (Array.isArray(value)) return value.map(redactSecrets);
|
||||
if (typeof value === "object") {
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
|
||||
result[key] = isSecretKey(key) ? REDACTED : redactSecrets(child);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Writer factory
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function createAuditWriter(repository: AuditRepository) {
|
||||
return {
|
||||
async writeAudit(input: AuditInput): Promise<void> {
|
||||
await repository.insert({
|
||||
...input,
|
||||
metadata: redactSecrets(input.metadata) as Record<string, unknown> | undefined,
|
||||
previousValues: redactSecrets(input.previousValues) as Record<string, unknown> | undefined,
|
||||
newValues: redactSecrets(input.newValues) as Record<string, unknown> | undefined,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Drizzle repository — maps the abstract `metadata` field into the schema's
|
||||
// existing jsonb columns. `metadata` is stored in `newValues`; explicit
|
||||
// `previousValues`/`newValues` (state changes) populate both columns.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function createAuditRepository(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
): AuditRepository {
|
||||
return {
|
||||
async insert(record) {
|
||||
const hasStateChange = record.previousValues !== undefined || record.newValues !== undefined;
|
||||
const newValues = hasStateChange
|
||||
? (record.newValues ?? null)
|
||||
: (record.metadata ?? null);
|
||||
const previousValues = hasStateChange ? (record.previousValues ?? null) : null;
|
||||
|
||||
await database.insert(auditEvents).values({
|
||||
eventType: record.type,
|
||||
actorUserId: record.actorUserId ?? null,
|
||||
actorType: record.actorType ?? "system",
|
||||
entityType: record.entityType,
|
||||
entityId: record.entityId,
|
||||
previousValues,
|
||||
newValues,
|
||||
occurredAt: record.occurredAt ?? new Date(),
|
||||
requestId: record.requestId ?? null,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Default singleton
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const auditWriter = createAuditWriter(createAuditRepository(db));
|
||||
export const writeAudit = auditWriter.writeAudit;
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
usages,
|
||||
} from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
import { writeAudit } from "@/modules/audit/write";
|
||||
import { renderBillingPdf } from "@/modules/pdf/render";
|
||||
import type { BillingReportSnapshot } from "@/modules/billing/types";
|
||||
|
||||
@@ -304,6 +305,25 @@ export function createReportService({
|
||||
legalSeparationNotice: LEGAL_SEPARATION_NOTICE,
|
||||
});
|
||||
|
||||
try {
|
||||
await writeAudit({
|
||||
type: "billing_report_finalized",
|
||||
actorUserId: input.adminUserId,
|
||||
actorType: "admin",
|
||||
entityType: "billing_report",
|
||||
entityId: result.reportId,
|
||||
metadata: {
|
||||
editorialId: input.editorialId,
|
||||
reportNumber: result.reportNumber,
|
||||
invoiceNumber: result.invoiceNumber,
|
||||
netTotalCents,
|
||||
usageCount: selectedUsages.length,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// Audit is observability, not a transaction participant.
|
||||
}
|
||||
|
||||
return {
|
||||
reportId: result.reportId,
|
||||
reportNumber: String(result.reportNumber),
|
||||
@@ -335,6 +355,19 @@ export function createReportService({
|
||||
input.adminUserId,
|
||||
report.usageIds,
|
||||
);
|
||||
|
||||
try {
|
||||
await writeAudit({
|
||||
type: "billing_report_cancelled",
|
||||
actorUserId: input.adminUserId,
|
||||
actorType: "admin",
|
||||
entityType: "billing_report",
|
||||
entityId: input.reportId,
|
||||
metadata: { reason, usageCount: report.usageIds.length },
|
||||
});
|
||||
} catch {
|
||||
// Audit is observability, not a transaction participant.
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
import type { AccountStatus } from "@/modules/auth/principal";
|
||||
import { writeAudit } from "@/modules/audit/write";
|
||||
import { mailer, type Mailer } from "@/modules/mail/mailer";
|
||||
|
||||
export type BillingAddressInput = {
|
||||
@@ -121,7 +122,22 @@ export function createEditorialService({
|
||||
},
|
||||
|
||||
async replaceBillingAddress(editorialId: string, input: BillingAddressInput): Promise<string> {
|
||||
return repository.replaceBillingAddress({ editorialId, input: validateBillingAddress(input) });
|
||||
const addressId = await repository.replaceBillingAddress({
|
||||
editorialId,
|
||||
input: validateBillingAddress(input),
|
||||
});
|
||||
try {
|
||||
await writeAudit({
|
||||
type: "billing_address_replaced",
|
||||
actorType: "admin",
|
||||
entityType: "editorial_account",
|
||||
entityId: editorialId,
|
||||
metadata: { addressId, countryCode: input.countryCode },
|
||||
});
|
||||
} catch {
|
||||
// Audit is observability, not a transaction participant.
|
||||
}
|
||||
return addressId;
|
||||
},
|
||||
|
||||
async transitionEditorialStatus(input: {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { assertSameOrigin, CrossOriginRequestError } from "./origin";
|
||||
|
||||
function requestWithHeaders({
|
||||
origin,
|
||||
host,
|
||||
}: {
|
||||
origin?: string;
|
||||
host?: string;
|
||||
}): Request {
|
||||
const headers = new Headers();
|
||||
if (origin !== undefined) headers.set("origin", origin);
|
||||
if (host !== undefined) headers.set("host", host);
|
||||
return new Request("https://portal.example.de/api/test", { headers });
|
||||
}
|
||||
|
||||
test("rejects a cross-origin state-changing request", () => {
|
||||
const request = requestWithHeaders({ origin: "https://evil.example", host: "portal.example.de" });
|
||||
expect(() => assertSameOrigin(request)).toThrow(CrossOriginRequestError);
|
||||
expect(() => assertSameOrigin(request)).toThrowError(
|
||||
expect.objectContaining({ code: "CROSS_ORIGIN_REQUEST" }),
|
||||
);
|
||||
});
|
||||
|
||||
test("allows a same-origin request", () => {
|
||||
const request = requestWithHeaders({ origin: "https://portal.example.de", host: "portal.example.de" });
|
||||
expect(() => assertSameOrigin(request)).not.toThrow();
|
||||
});
|
||||
|
||||
test("allows a request with no Origin header (same-page navigation)", () => {
|
||||
const request = requestWithHeaders({ host: "portal.example.de" });
|
||||
expect(() => assertSameOrigin(request)).not.toThrow();
|
||||
});
|
||||
|
||||
test("matches host only, ignoring scheme", () => {
|
||||
const request = requestWithHeaders({ origin: "http://portal.example.de", host: "portal.example.de" });
|
||||
expect(() => assertSameOrigin(request)).not.toThrow();
|
||||
});
|
||||
|
||||
test("matches host ignoring path in origin", () => {
|
||||
const request = requestWithHeaders({
|
||||
origin: "https://portal.example.de/some/path",
|
||||
host: "portal.example.de",
|
||||
});
|
||||
expect(() => assertSameOrigin(request)).not.toThrow();
|
||||
});
|
||||
|
||||
test("rejects when host header is missing", () => {
|
||||
const request = requestWithHeaders({ origin: "https://evil.example" });
|
||||
expect(() => assertSameOrigin(request)).toThrow(CrossOriginRequestError);
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
// ---------------------------------------------------------------------------
|
||||
// Same-origin guard for custom state-changing API routes.
|
||||
// Better Auth handles its own route; this guards the portal's custom handlers.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export class CrossOriginRequestError extends Error {
|
||||
readonly name = "CrossOriginRequestError";
|
||||
readonly code = "CROSS_ORIGIN_REQUEST" as const;
|
||||
|
||||
constructor() {
|
||||
super("Cross-origin request rejected");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares the request's `Origin` header host against the `Host` header.
|
||||
* Throws `CrossOriginRequestError` on mismatch. A request with no `Origin`
|
||||
* (same-page navigation, same-origin fetch) is allowed — the Origin header is
|
||||
* only sent on cross-origin state-changing requests per the fetch spec.
|
||||
* Only the host is compared (scheme and path are ignored).
|
||||
*/
|
||||
export function assertSameOrigin(request: Request): void {
|
||||
const origin = request.headers.get("origin");
|
||||
if (!origin) return; // Absent Origin = same-origin, allow.
|
||||
|
||||
const host = request.headers.get("host");
|
||||
if (!host) throw new CrossOriginRequestError();
|
||||
|
||||
let originHost: string;
|
||||
try {
|
||||
originHost = new URL(origin).host;
|
||||
} catch {
|
||||
throw new CrossOriginRequestError();
|
||||
}
|
||||
|
||||
if (originHost !== host) {
|
||||
throw new CrossOriginRequestError();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { createRateLimiter, loginPolicy, type RateLimitRepository } from "./rate-limit";
|
||||
|
||||
function createMockRepo(): RateLimitRepository & { counts: Map<string, number> } {
|
||||
const counts = new Map<string, number>();
|
||||
const repository: RateLimitRepository = {
|
||||
async incrementCount(key, _windowBoundary) {
|
||||
const current = (counts.get(key) ?? 0) + 1;
|
||||
counts.set(key, current);
|
||||
return { count: current };
|
||||
},
|
||||
};
|
||||
return { ...repository, counts };
|
||||
}
|
||||
|
||||
test("blocks the sixth login attempt in a fifteen-minute window", async () => {
|
||||
const repo = createMockRepo();
|
||||
const limiter = createRateLimiter(repo);
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
expect((await limiter.consume("login:hash", loginPolicy)).allowed).toBe(true);
|
||||
}
|
||||
expect((await limiter.consume("login:hash", loginPolicy)).allowed).toBe(false);
|
||||
});
|
||||
|
||||
test("returns retryAfterSeconds when blocked", async () => {
|
||||
const repo = createMockRepo();
|
||||
const limiter = createRateLimiter(repo);
|
||||
|
||||
for (let i = 0; i < 5; i++) await limiter.consume("login:hash", loginPolicy);
|
||||
const result = await limiter.consume("login:hash", loginPolicy);
|
||||
|
||||
expect(result.allowed).toBe(false);
|
||||
expect(result.retryAfterSeconds).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("allows up to the max attempts", async () => {
|
||||
const repo = createMockRepo();
|
||||
const limiter = createRateLimiter(repo);
|
||||
|
||||
const policy = { maxAttempts: 3, windowSeconds: 60 };
|
||||
for (let i = 0; i < 3; i++) {
|
||||
expect((await limiter.consume("key:hash", policy)).allowed).toBe(true);
|
||||
}
|
||||
expect((await limiter.consume("key:hash", policy)).allowed).toBe(false);
|
||||
});
|
||||
|
||||
test("tracks different keys independently", async () => {
|
||||
const repo = createMockRepo();
|
||||
const limiter = createRateLimiter(repo);
|
||||
|
||||
const policy = { maxAttempts: 1, windowSeconds: 60 };
|
||||
expect((await limiter.consume("a:hash", policy)).allowed).toBe(true);
|
||||
expect((await limiter.consume("b:hash", policy)).allowed).toBe(true);
|
||||
expect((await limiter.consume("a:hash", policy)).allowed).toBe(false);
|
||||
expect((await limiter.consume("b:hash", policy)).allowed).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import "server-only";
|
||||
|
||||
import { sql } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import { rateLimits } from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type RateLimitPolicy = {
|
||||
maxAttempts: number;
|
||||
windowSeconds: number;
|
||||
};
|
||||
|
||||
export type RateLimitResult = {
|
||||
allowed: boolean;
|
||||
retryAfterSeconds: number;
|
||||
};
|
||||
|
||||
export type RateLimitRepository = {
|
||||
incrementCount(key: string, windowBoundary: number): Promise<{ count: number }>;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Policies — bounded server-side, not configurable via env (Global Constraint)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const loginPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 15 * 60 };
|
||||
export const registrationPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 60 * 60 };
|
||||
export const passwordResetPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 60 * 60 };
|
||||
export const searchPolicy: RateLimitPolicy = { maxAttempts: 120, windowSeconds: 60 };
|
||||
export const downloadIntentsPolicy: RateLimitPolicy = { maxAttempts: 30, windowSeconds: 60 };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Limiter factory
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function createRateLimiter(repository: RateLimitRepository) {
|
||||
return {
|
||||
async consume(key: string, policy: RateLimitPolicy): Promise<RateLimitResult> {
|
||||
// ponytail: integer-arithmetic fixed window — upgrade to sliding window
|
||||
// if abuse patterns require it. No token-bucket library needed.
|
||||
const nowSeconds = Math.floor(Date.now() / 1000);
|
||||
const windowBoundary = Math.floor(nowSeconds / policy.windowSeconds);
|
||||
|
||||
const { count } = await repository.incrementCount(key, windowBoundary);
|
||||
|
||||
if (count <= policy.maxAttempts) {
|
||||
return { allowed: true, retryAfterSeconds: 0 };
|
||||
}
|
||||
|
||||
const windowEndSeconds = (windowBoundary + 1) * policy.windowSeconds;
|
||||
const retryAfterSeconds = Math.max(1, windowEndSeconds - nowSeconds);
|
||||
return { allowed: false, retryAfterSeconds };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Drizzle repository — atomic upsert via ON CONFLICT
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function createRateLimitRepository(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
): RateLimitRepository {
|
||||
return {
|
||||
async incrementCount(key, windowBoundary) {
|
||||
const result = await database
|
||||
.insert(rateLimits)
|
||||
.values({
|
||||
key,
|
||||
windowBoundary,
|
||||
count: 1,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [rateLimits.key, rateLimits.windowBoundary],
|
||||
set: {
|
||||
count: sql`${rateLimits.count} + 1`,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
})
|
||||
.returning({ count: rateLimits.count });
|
||||
return { count: result[0].count };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Default singleton
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const rateLimiter = createRateLimiter(createRateLimitRepository(db));
|
||||
export const consumeRateLimit = rateLimiter.consume;
|
||||
Reference in new issue
Block a user