39 lines · 1.5 KB
import { run } from "../db";

const DAY_MS = 24 * 60 * 60 * 1000;
/** Dynamically registered clients that never completed an authorization are garbage after this long. */
const UNUSED_DCR_CLIENT_MS = 7 * DAY_MS;
/** Refresh tokens are rotated (`used_at` set) and kept for reuse detection; drop them after the grant window. */
const USED_REFRESH_TOKEN_MS = 30 * DAY_MS;
const PRUNE_BATCH = 500;

/**
 * Keeps the OAuth tables bounded (INT-A24): unexchanged authorization codes, dynamic-client registrations
 * nobody ever used, and refresh tokens that expired or were rotated long ago. All deletes are batched so a
 * backlog never turns into one giant statement.
 */
export async function runMcpCron(now = Date.now()): Promise<void> {
  await run(
    "DELETE FROM oauth_codes WHERE code_hash IN (SELECT code_hash FROM oauth_codes WHERE expires_at < ? LIMIT ?)",
    now,
    PRUNE_BATCH,
  );
  await run(
    `DELETE FROM oauth_clients WHERE id IN (
       SELECT c.id FROM oauth_clients c WHERE c.kind = 'dcr' AND c.last_used_at IS NULL AND c.created_at < ?
         AND NOT EXISTS (SELECT 1 FROM oauth_refresh_tokens r WHERE r.client_id = c.id)
         AND NOT EXISTS (SELECT 1 FROM oauth_codes o WHERE o.client_id = c.id)
       LIMIT ?)`,
    now - UNUSED_DCR_CLIENT_MS,
    PRUNE_BATCH,
  );
  await run(
    `DELETE FROM oauth_refresh_tokens WHERE token_hash IN (
       SELECT token_hash FROM oauth_refresh_tokens
       WHERE expires_at < ? OR (used_at IS NOT NULL AND used_at < ?) LIMIT ?)`,
    now,
    now - USED_REFRESH_TOKEN_MS,
    PRUNE_BATCH,
  );
}