feat(housekeeping): dispatch audited commands

This commit is contained in:
Simo committed 2026-08-27 18:30:44 +02:00
1 parent ca666d9f90
commit 6aed71a8b2
8 files changed
+996

No files matched your search

@@ -0,0 +1,224 @@
import type { AuditEntry, HousekeepingAuditWriter } from "@/lib/services/audit";
import { satisfiesCapability } from "../capability-context";
import {
fail,
type HousekeepingCapabilityContext,
type HousekeepingResult,
mapUnknownError,
} from "../contracts";
import { createCorrelationId } from "../correlation";
import { writeIntent, writeOutcome } from "./audit-envelope";
import { confirmHousekeepingCommand } from "./confirmation";
import {
getHousekeepingCommand,
type HousekeepingCommand,
type HousekeepingCommandContext,
} from "./registry";
export interface HousekeepingCommandRequest {
commandId: string;
input: unknown;
reason?: string;
}
export interface HousekeepingCommandDependencies {
context: HousekeepingCapabilityContext;
ipAddress: string;
audit: HousekeepingAuditWriter;
rateLimit(key: string, attempts: number, windowMs: number): Promise<boolean>;
}
export async function dispatchHousekeepingCommand(
request: HousekeepingCommandRequest,
dependencies: HousekeepingCommandDependencies,
): Promise<HousekeepingResult<unknown>> {
const correlationId = createCorrelationId();
const command = getHousekeepingCommand(request.commandId);
if (!command) {
return fail("NOT_FOUND", "errors.housekeeping.notFound", correlationId);
}
const reason =
typeof request.reason === "string"
? request.reason.normalize("NFC").trim() || undefined
: undefined;
const auditEntry = createAuditEntry(
command,
dependencies.context,
dependencies.ipAddress,
correlationId,
reason,
);
if (command.risk === "sensitive") {
try {
await writeIntent(dependencies.audit, auditEntry);
} catch (error) {
return mapUnknownError(error, correlationId);
}
}
if (!satisfiesCapability(dependencies.context, command.capability)) {
return finishWithAudit(
dependencies.audit,
auditEntry,
"denied",
fail("FORBIDDEN", "errors.housekeeping.forbidden", correlationId),
correlationId,
);
}
const parsedInput = command.input.safeParse(request.input);
if (!parsedInput.success) {
const fieldErrors: Record<string, readonly string[]> = {};
for (const issue of parsedInput.error.issues) {
const field = String(issue.path[0] ?? "input");
fieldErrors[field] = ["errors.validation.invalid"];
}
return finishWithAudit(
dependencies.audit,
auditEntry,
"denied",
fail(
"VALIDATION",
"errors.housekeeping.validation",
correlationId,
fieldErrors,
),
correlationId,
);
}
const confirmation = confirmHousekeepingCommand(
command,
reason,
correlationId,
);
if (!confirmation.ok) {
return finishWithAudit(
dependencies.audit,
auditEntry,
"denied",
confirmation,
correlationId,
);
}
let allowed: boolean;
try {
allowed = await dependencies.rateLimit(
createRateLimitKey(
command.id,
dependencies.context,
dependencies.ipAddress,
),
command.rateLimit.attempts,
command.rateLimit.windowMs,
);
} catch (error) {
return finishWithAudit(
dependencies.audit,
auditEntry,
"failure",
mapUnknownError(error, correlationId),
correlationId,
);
}
if (!allowed) {
return finishWithAudit(
dependencies.audit,
auditEntry,
"denied",
fail("RATE_LIMITED", "errors.housekeeping.rateLimited", correlationId),
correlationId,
);
}
const commandContext: HousekeepingCommandContext = {
capability: dependencies.context,
correlationId,
ipAddress: dependencies.ipAddress,
};
let result: HousekeepingResult<unknown>;
try {
result = await command.execute(commandContext, parsedInput.data);
} catch (error) {
return finishWithAudit(
dependencies.audit,
auditEntry,
"failure",
mapUnknownError(error, correlationId),
correlationId,
);
}
const correlatedResult = withCorrelation(result, correlationId);
return finishWithAudit(
dependencies.audit,
auditEntry,
outcomeFor(correlatedResult),
correlatedResult,
correlationId,
);
}
function createAuditEntry(
command: HousekeepingCommand<unknown, unknown>,
context: HousekeepingCapabilityContext,
ipAddress: string,
correlationId: string,
reason: string | undefined,
): AuditEntry {
return {
userId: context.actor.id,
action: command.id,
target: command.owner,
correlationId,
domain: command.owner,
...(reason === undefined ? {} : { reason }),
ipAddress,
};
}
function createRateLimitKey(
commandId: string,
context: HousekeepingCapabilityContext,
ipAddress = "0.0.0.0",
): string {
return `housekeeping-command:${context.actor.id}:${ipAddress}:${commandId}`;
}
function withCorrelation<T>(
result: HousekeepingResult<T>,
correlationId: string,
): HousekeepingResult<T> {
return { ...result, correlationId };
}
function outcomeFor(
result: HousekeepingResult<unknown>,
): "success" | "failure" | "denied" {
if (result.ok) return "success";
return result.error.code === "FORBIDDEN" ||
result.error.code === "VALIDATION" ||
result.error.code === "RATE_LIMITED"
? "denied"
: "failure";
}
async function finishWithAudit<T>(
writer: HousekeepingAuditWriter,
entry: AuditEntry,
outcome: "success" | "failure" | "denied",
result: HousekeepingResult<T>,
correlationId: string,
): Promise<HousekeepingResult<T>> {
try {
await writeOutcome(writer, entry, outcome);
return result;
} catch (error) {
return mapUnknownError(error, correlationId);
}
}