Add configurable Void usage rate limits

This commit is contained in:
Meta Vens 2026-04-26 01:39:42 +01:00
commit e53e24261e
10 changed files with 633 additions and 15 deletions

View file

@ -7,3 +7,4 @@ export * from "./permission-engine";
export * from "./state-storage";
export * from "./style-pack-loader";
export * from "./system-message-catalog";
export * from "./void-usage-rate-limiter";

View file

@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { Pool, type PoolClient } from "pg";
@ -28,6 +28,11 @@ import {
type JobQueue,
FileBackedJobQueue,
} from "./job-queue";
import {
type ConsumeVoidUsageRateLimitInput,
type VoidUsageRateLimitDecision,
type VoidUsageRateLimitStore,
} from "./void-usage-rate-limiter";
const LEGACY_FILE_STATE_IMPORT = "legacy_file_state_import_v1";
@ -37,6 +42,7 @@ export interface StateStorageConfig {
jobsFile: string;
auditLogFile: string;
interactionMemoryFile: string;
rateLimitStateFile: string;
}
export interface StateStorage {
@ -44,6 +50,7 @@ export interface StateStorage {
jobQueue: JobQueue;
auditLog: AuditLog;
interactionMemory: InteractionMemoryBank;
voidUsageRateLimits: VoidUsageRateLimitStore;
close(): Promise<void>;
}
@ -56,6 +63,7 @@ export async function createStateStorage(
jobQueue: new FileBackedJobQueue(config.jobsFile),
auditLog: new FileAuditLog(config.auditLogFile),
interactionMemory: new FileInteractionMemoryBank(config.interactionMemoryFile),
voidUsageRateLimits: new FileBackedVoidUsageRateLimitStore(config.rateLimitStateFile),
close: async () => undefined,
};
}
@ -77,6 +85,7 @@ export async function createStateStorage(
jobQueue: new PostgresJobQueue(pool),
auditLog: new PostgresAuditLog(pool),
interactionMemory: new PostgresInteractionMemoryBank(pool),
voidUsageRateLimits: new PostgresVoidUsageRateLimitStore(pool),
close: async () => {
await pool.end();
},
@ -495,6 +504,247 @@ class PostgresInteractionMemoryBank implements InteractionMemoryBank {
}
}
interface VoidUsageRateLimitStateRow {
actor_id: string;
daily_bucket: string;
daily_count: number;
last_request_at: string | null;
}
class PostgresVoidUsageRateLimitStore implements VoidUsageRateLimitStore {
public constructor(private readonly pool: Pool) {}
public async consume(
input: ConsumeVoidUsageRateLimitInput,
): Promise<VoidUsageRateLimitDecision> {
const timestamp = input.timestamp ?? new Date().toISOString();
const now = new Date(timestamp);
const bucket = timestamp.slice(0, 10);
const client = await this.pool.connect();
try {
await client.query("begin");
await client.query(
`insert into void_usage_rate_limit_state (
actor_id,
daily_bucket,
daily_count,
state_json
) values ($1, $2, 0, '{}'::jsonb)
on conflict (actor_id) do nothing`,
[input.actorId, bucket],
);
const stateResult = await client.query<VoidUsageRateLimitStateRow>(
`select actor_id, daily_bucket::text, daily_count, last_request_at::text
from void_usage_rate_limit_state
where actor_id = $1
for update`,
[input.actorId],
);
const state = stateResult.rows[0];
if (!state) {
throw new Error(`Missing rate limit state for actor ${input.actorId}.`);
}
const dailyCount = state.daily_bucket === bucket ? state.daily_count : 0;
if (input.dailyLimit !== undefined && dailyCount >= input.dailyLimit) {
await client.query("commit");
return {
allowed: false,
reason: "daily_limit",
dailyCount,
resetsAt: nextUtcDay(timestamp),
policy: {
modifier: "default",
matchedSubjects: [],
},
};
}
if (input.cooldownSeconds !== undefined && state.last_request_at) {
const lastRequestAt = new Date(state.last_request_at);
const elapsedSeconds = Math.floor((now.getTime() - lastRequestAt.getTime()) / 1000);
const retryAfterSeconds = input.cooldownSeconds - elapsedSeconds;
if (retryAfterSeconds > 0) {
await client.query("commit");
return {
allowed: false,
reason: "cooldown",
dailyCount,
retryAfterSeconds,
resetsAt: now.toISOString(),
policy: {
modifier: "default",
matchedSubjects: [],
},
};
}
}
const nextDailyCount = dailyCount + 1;
await client.query(
`update void_usage_rate_limit_state
set daily_bucket = $2,
daily_count = $3,
last_request_at = $4,
updated_at = now(),
state_json = $5::jsonb
where actor_id = $1`,
[
input.actorId,
bucket,
nextDailyCount,
timestamp,
JSON.stringify({
lastCommand: input.command,
lastProvider: input.provider,
guildId: input.guildId ?? null,
channelId: input.channelId,
}),
],
);
await client.query("commit");
return {
allowed: true,
dailyCount: nextDailyCount,
resetsAt:
input.dailyLimit === undefined ? undefined : nextUtcDay(timestamp),
policy: {
modifier: "default",
matchedSubjects: [],
},
};
} catch (error) {
await client.query("rollback").catch(() => undefined);
throw error;
} finally {
client.release();
}
}
}
interface VoidUsageRateLimitFileStore {
version: 1;
actors: Record<
string,
{
dailyBucket: string;
dailyCount: number;
lastRequestAt?: string;
}
>;
}
class FileBackedVoidUsageRateLimitStore implements VoidUsageRateLimitStore {
private writeChain: Promise<void> = Promise.resolve();
public constructor(private readonly filePath: string) {}
public async consume(
input: ConsumeVoidUsageRateLimitInput,
): Promise<VoidUsageRateLimitDecision> {
return this.serialize(async () => {
const timestamp = input.timestamp ?? new Date().toISOString();
const now = new Date(timestamp);
const bucket = timestamp.slice(0, 10);
const store = await this.readUnlocked();
const existing = store.actors[input.actorId] ?? {
dailyBucket: bucket,
dailyCount: 0,
};
const dailyCount = existing.dailyBucket === bucket ? existing.dailyCount : 0;
if (input.dailyLimit !== undefined && dailyCount >= input.dailyLimit) {
return {
allowed: false,
reason: "daily_limit",
dailyCount,
resetsAt: nextUtcDay(timestamp),
policy: {
modifier: "default",
matchedSubjects: [],
},
};
}
if (input.cooldownSeconds !== undefined && existing.lastRequestAt) {
const lastRequestAt = new Date(existing.lastRequestAt);
const elapsedSeconds = Math.floor((now.getTime() - lastRequestAt.getTime()) / 1000);
const retryAfterSeconds = input.cooldownSeconds - elapsedSeconds;
if (retryAfterSeconds > 0) {
return {
allowed: false,
reason: "cooldown",
dailyCount,
retryAfterSeconds,
resetsAt: now.toISOString(),
policy: {
modifier: "default",
matchedSubjects: [],
},
};
}
}
const nextDailyCount = dailyCount + 1;
store.actors[input.actorId] = {
dailyBucket: bucket,
dailyCount: nextDailyCount,
lastRequestAt: timestamp,
};
await this.writeUnlocked(store);
return {
allowed: true,
dailyCount: nextDailyCount,
resetsAt:
input.dailyLimit === undefined ? undefined : nextUtcDay(timestamp),
policy: {
modifier: "default",
matchedSubjects: [],
},
};
});
}
private async serialize<T>(operation: () => Promise<T>): Promise<T> {
const pending = this.writeChain.then(operation, operation);
this.writeChain = pending.then(
() => undefined,
() => undefined,
);
return pending;
}
private async readUnlocked(): Promise<VoidUsageRateLimitFileStore> {
try {
const raw = await readFile(this.filePath, "utf8");
return JSON.parse(raw) as VoidUsageRateLimitFileStore;
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") {
return {
version: 1,
actors: {},
};
}
throw error;
}
}
private async writeUnlocked(store: VoidUsageRateLimitFileStore): Promise<void> {
await mkdir(dirname(this.filePath), { recursive: true });
await writeFile(this.filePath, `${JSON.stringify(store, null, 2)}\n`, "utf8");
}
}
async function bootstrapPostgres(pool: Pool): Promise<void> {
const sqlPath = resolve(process.cwd(), "packages", "core", "sql", "bootstrap.sql");
const sql = await readFile(sqlPath, "utf8");
@ -772,3 +1022,11 @@ function dedupeLegacyJobs(jobs: JobRecord[]): JobRecord[] {
left.createdAt.localeCompare(right.createdAt),
);
}
function nextUtcDay(timestamp: string): string {
const date = new Date(timestamp);
const next = new Date(
Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + 1, 0, 0, 0, 0),
);
return next.toISOString();
}

View file

@ -0,0 +1,169 @@
import { type CommandName, type ProviderName } from "@voidbot/shared";
export interface VoidUsageRateLimitConfig {
defaultCooldownSeconds: number;
defaultDailyLimit: number;
unlimitedUserIds: string[];
unlimitedRoleIds: string[];
boostedUserIds: string[];
boostedRoleIds: string[];
boostedMultiplier: number;
}
export interface VoidUsageSubject {
actorId: string;
roleIds: string[];
}
export interface EffectiveVoidUsagePolicy {
cooldownSeconds?: number;
dailyLimit?: number;
modifier: "default" | "boosted" | "unlimited";
matchedSubjects: string[];
}
export interface VoidUsageRateLimitDecision {
allowed: boolean;
reason?: "cooldown" | "daily_limit";
policy: EffectiveVoidUsagePolicy;
dailyCount: number;
retryAfterSeconds?: number;
resetsAt?: string;
}
export interface ConsumeVoidUsageRateLimitInput {
actorId: string;
command: CommandName;
provider: ProviderName;
guildId?: string;
channelId: string;
cooldownSeconds?: number;
dailyLimit?: number;
timestamp?: string;
}
export interface VoidUsageRateLimitStore {
consume(input: ConsumeVoidUsageRateLimitInput): Promise<VoidUsageRateLimitDecision>;
}
export class VoidUsageRateLimiter {
public constructor(
private readonly store: VoidUsageRateLimitStore,
private readonly config: VoidUsageRateLimitConfig,
) {}
public async consume(input: {
actorId: string;
roleIds: string[];
command: CommandName;
provider: ProviderName;
guildId?: string;
channelId: string;
timestamp?: string;
}): Promise<VoidUsageRateLimitDecision> {
const policy = resolveEffectivePolicy(this.config, {
actorId: input.actorId,
roleIds: input.roleIds,
});
if (policy.cooldownSeconds === undefined && policy.dailyLimit === undefined) {
return {
allowed: true,
policy,
dailyCount: 0,
};
}
const decision = await this.store.consume({
actorId: input.actorId,
command: input.command,
provider: input.provider,
guildId: input.guildId,
channelId: input.channelId,
cooldownSeconds: policy.cooldownSeconds,
dailyLimit: policy.dailyLimit,
timestamp: input.timestamp,
});
return {
...decision,
policy,
};
}
}
export function resolveEffectivePolicy(
config: VoidUsageRateLimitConfig,
subject: VoidUsageSubject,
): EffectiveVoidUsagePolicy {
const baseCooldownSeconds = normalizeLimitValue(config.defaultCooldownSeconds);
const baseDailyLimit = normalizeLimitValue(config.defaultDailyLimit);
const unlimitedMatches = collectMatches(subject, {
userIds: config.unlimitedUserIds,
roleIds: config.unlimitedRoleIds,
});
if (unlimitedMatches.length > 0) {
return {
modifier: "unlimited",
matchedSubjects: unlimitedMatches,
};
}
const boostedMatches = collectMatches(subject, {
userIds: config.boostedUserIds,
roleIds: config.boostedRoleIds,
});
if (boostedMatches.length === 0) {
return {
cooldownSeconds: baseCooldownSeconds,
dailyLimit: baseDailyLimit,
modifier: "default",
matchedSubjects: [],
};
}
const multiplier = config.boostedMultiplier > 1 ? config.boostedMultiplier : 10;
return {
cooldownSeconds:
baseCooldownSeconds === undefined
? undefined
: Math.max(1, Math.floor(baseCooldownSeconds / multiplier)),
dailyLimit:
baseDailyLimit === undefined ? undefined : Math.max(1, baseDailyLimit * multiplier),
modifier: "boosted",
matchedSubjects: boostedMatches,
};
}
function normalizeLimitValue(value: number | undefined): number | undefined {
if (value === undefined || !Number.isFinite(value) || value <= 0) {
return undefined;
}
return Math.floor(value);
}
function collectMatches(
subject: VoidUsageSubject,
targets: {
userIds: string[];
roleIds: string[];
},
): string[] {
const matches: string[] = [];
if (targets.userIds.includes(subject.actorId)) {
matches.push(`user:${subject.actorId}`);
}
for (const roleId of subject.roleIds) {
if (targets.roleIds.includes(roleId)) {
matches.push(`role:${roleId}`);
}
}
return matches;
}