import { eq, inArray } from "drizzle-orm"; import { db } from "../db/client.js"; import { dnsZonesCache, domains } from "../db/schema.js"; import { defaultDeps, lookupRegistration, normalizeDomain, resolveRegistration, type LookupDeps, type LookupResult } from "./domainLookup.js"; import { computeSecretStatus } from "./secretStatus.js"; import { notifyDomainExpiry } from "./notify.js"; import { getSettings } from "./settingsStore.js"; import { noteRenewal } from "./renewals.js"; export type DomainRow = typeof domains.$inferSelect; /** An expiry date that couldn't be refreshed for this long is worth a mention alongside the reminders. */ const STALE_AFTER_MS = 3 * 24 * 60 * 60 * 1000; const REFRESH_AFTER_MS = 24 * 60 * 60 * 1000; /** Registries rate-limit; one lookup at a time with a short pause is plenty for a handful of domains. */ const PAUSE_MS = 250; const NO_EXPIRY_PUBLISHED = "The registry doesn't publish an expiry date for this domain."; let running = false; export const isDomainCheckRunning = () => running; const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); // ─── Applying a lookup result to a row ────────────────────────────────────── function outcomeFields(result: LookupResult, row: Pick, now: string) { if (result.ok) { return { expiresAt: result.expiresAt ?? row.expiresAt, registrar: result.registrar ?? row.registrar, lookupSource: result.source, lastCheckedAt: now, lastCheckedOkAt: now, // The registry answered — it just doesn't say when the domain expires (.de and .eu, for instance). lastCheckError: result.expiresAt ? null : NO_EXPIRY_PUBLISHED, }; } // Keep the last known expiry: a failed lookup must not blank out a date we still rely on. return { lastCheckedAt: now, lastCheckError: result.reason === "not_found" ? `No longer found in the registry — has it expired and been deleted? (${result.message})` : result.message, }; } /** Re-reads one tracked domain from its registry and records the outcome on its row. */ export async function checkDomain(id: number, deps: LookupDeps = defaultDeps): Promise { const [row] = await db.select().from(domains).where(eq(domains.id, id)).limit(1); if (!row) return null; const result = await lookupRegistration(row.name, deps); const [updated] = await db.update(domains).set(outcomeFields(result, row, new Date(deps.now()).toISOString())).where(eq(domains.id, id)).returning(); // A registration that now runs much longer than it did was renewed. await noteRenewal("domain", row.name, row.expiresAt, updated.expiresAt, new Date(deps.now())); return updated; } /** Finds the registration a typed name belongs to and starts tracking it. */ export async function addManualDomain( input: string, deps: LookupDeps = defaultDeps, ): Promise<{ ok: true; row: DomainRow; resolvedFrom: string | null } | { ok: false; status: 400 | 409 | 422 | 502; message: string }> { const name = normalizeDomain(input); if (!name) return { ok: false, status: 400, message: `"${input.trim()}" doesn't look like a domain name — use something like example.com.` }; const result = await resolveRegistration(name, deps); if (!result.ok) { if (result.reason === "error") return { ok: false, status: 502, message: `Couldn't look up ${name}: ${result.message}` }; return { ok: false, status: 422, message: result.reason === "unsupported" ? `Can't track ${name}: ${result.message}` : `${name} isn't registered (or its registry doesn't answer for it).`, }; } const [existing] = await db.select().from(domains).where(eq(domains.name, result.domain)).limit(1); if (existing) return { ok: false, status: 409, message: `${result.domain} is already being tracked.` }; const now = new Date(deps.now()).toISOString(); const [row] = await db .insert(domains) .values({ name: result.domain, origin: "manual", expiresAt: result.expiresAt, registrar: result.registrar, lookupSource: result.source, lastCheckedAt: now, lastCheckedOkAt: now, lastCheckError: result.expiresAt ? null : NO_EXPIRY_PUBLISHED, }) .returning(); return { ok: true, row, resolvedFrom: result.domain !== name ? name : null }; } // ─── Domains that come from DNS zones ─────────────────────────────────────── /** * Makes sure every DNS zone we already know about is covered by a tracked domain, and drops zone-derived rows * nothing covers any more. A zone like "lab.example.se" is covered by the row for "example.se". Zones that don't * resolve to a real registration (".lan", ".local", a domain that isn't registered) simply don't get a row. * Returns the ids of rows it just created, so the caller needn't look them up a second time. */ export async function syncZoneDomains(deps: LookupDeps = defaultDeps, pauseMs = PAUSE_MS): Promise> { const zoneNames = [...new Set((await db.select({ name: dnsZonesCache.zoneName }).from(dnsZonesCache)).map((z) => z.name))] .map((n) => normalizeDomain(n)) .filter((n): n is string => n !== null); const covers = (rowName: string, zone: string) => zone === rowName || zone.endsWith(`.${rowName}`); const created = new Set(); for (const zone of zoneNames) { const existing = await db.select({ name: domains.name }).from(domains); if (existing.some((r) => covers(r.name, zone))) continue; if (pauseMs) await sleep(pauseMs); const result = await resolveRegistration(zone, deps); if (!result.ok) { if (result.reason === "error") console.error(`[domains] couldn't look up zone ${zone}: ${result.message}`); continue; } if (existing.some((r) => r.name === result.domain)) continue; const now = new Date(deps.now()).toISOString(); const [row] = await db .insert(domains) .values({ name: result.domain, origin: "zone", expiresAt: result.expiresAt, registrar: result.registrar, lookupSource: result.source, lastCheckedAt: now, lastCheckedOkAt: now, lastCheckError: result.expiresAt ? null : NO_EXPIRY_PUBLISHED, }) .returning(); created.add(row.id); } const zoneRows = await db.select().from(domains).where(eq(domains.origin, "zone")); const orphaned = zoneRows.filter((r) => !zoneNames.some((z) => covers(r.name, z))).map((r) => r.id); if (orphaned.length > 0) await db.delete(domains).where(inArray(domains.id, orphaned)); return created; } // ─── Refreshing everything ────────────────────────────────────────────────── /** Syncs zone-derived domains, then re-reads every tracked domain. One run at a time. Returns false if one was already running. */ export async function refreshAllDomains(deps: LookupDeps = defaultDeps, pauseMs = PAUSE_MS): Promise { if (running) return false; running = true; try { const fresh = await syncZoneDomains(deps, pauseMs); for (const row of await db.select({ id: domains.id }).from(domains)) { if (fresh.has(row.id)) continue; if (pauseMs) await sleep(pauseMs); await checkDomain(row.id, deps); } return true; } finally { running = false; } } /** At startup: catch up if nothing has been read in the last day (a fresh upgrade, or the app was off over the daily check). Not awaited by the caller. */ export async function refreshDomainsIfStale(now: number = Date.now()): Promise { const rows = await db.select({ checkedAt: domains.lastCheckedAt }).from(domains); const stale = rows.length === 0 || rows.some((r) => !r.checkedAt || now - Date.parse(r.checkedAt) > REFRESH_AFTER_MS); if (stale) await refreshAllDomains(); } // ─── Alerts ───────────────────────────────────────────────────────────────── export function domainStatus(row: Pick, warnDays: number, now: Date = new Date()) { if (!row.expiresAt) return { status: "unknown" as const, daysLeft: null }; return computeSecretStatus(row.expiresAt, warnDays, now); } export async function collectDomainAlerts(now: Date = new Date()) { const { healthChecks } = await getSettings(); const rows = await db.select().from(domains); const expiring = rows.flatMap((r) => { const s = domainStatus(r, healthChecks.domainWarnDays, now); return s.status === "expired" || s.status === "expiring" ? [{ name: r.name, status: s.status, daysLeft: s.daysLeft!, expiresAt: r.expiresAt!, registrar: r.registrar }] : []; }); // Only failures that have gone on a while: one bad night at the registry isn't news, several days of a possibly stale date is. const staleChecks = rows.flatMap((r) => { if (!r.lastCheckError || r.lastCheckError === NO_EXPIRY_PUBLISHED) return []; const since = Date.parse(r.lastCheckedOkAt ?? r.createdAt.replace(" ", "T") + "Z"); return now.getTime() - since > STALE_AFTER_MS ? [{ name: r.name, error: r.lastCheckError, lastOkAt: r.lastCheckedOkAt }] : []; }); return { expiring, staleChecks }; } /** The daily pass: re-read every domain, then remind about the ones that need renewing. */ export async function runDomainCheck(deps: LookupDeps = defaultDeps, pauseMs = PAUSE_MS): Promise { await refreshAllDomains(deps, pauseMs); const { expiring, staleChecks } = await collectDomainAlerts(); await notifyDomainExpiry(expiring, staleChecks); }