99 lines
2.6 KiB
TypeScript
99 lines
2.6 KiB
TypeScript
import { getDbClient } from "./client.server.js";
|
|
export { IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION } from "./impersonation-audit.constants.js";
|
|
|
|
const SENSITIVE_METADATA_KEY_PATTERN = /cookie|password|totp|recovery|token|secret/i;
|
|
|
|
export type ImpersonationAuditAction = "start" | "destructive_action_blocked" | (string & {});
|
|
|
|
export type ImpersonationAuditCreateData = {
|
|
actorUserId: string;
|
|
targetUserId: string;
|
|
tenantId?: string | null;
|
|
action: ImpersonationAuditAction;
|
|
reason?: string | null;
|
|
requestPath: string;
|
|
metadata?: Record<string, unknown> | null;
|
|
};
|
|
|
|
export type ImpersonationAuditRecord = {
|
|
id: string;
|
|
createdAt: Date;
|
|
actorUserId: string;
|
|
targetUserId: string;
|
|
tenantId: string | null;
|
|
action: string;
|
|
reason: string | null;
|
|
requestPath: string;
|
|
metadata: string | null;
|
|
};
|
|
|
|
export type ImpersonationAuditWriterClient = {
|
|
impersonationAudit: {
|
|
create(args: {
|
|
data: {
|
|
actorUserId: string;
|
|
targetUserId: string;
|
|
tenantId: string | null;
|
|
action: string;
|
|
reason: string | null;
|
|
requestPath: string;
|
|
metadata: string | null;
|
|
};
|
|
}): Promise<ImpersonationAuditRecord>;
|
|
};
|
|
};
|
|
|
|
function redactMetadataValue(value: unknown): string {
|
|
if (value === null || value === undefined) {
|
|
return "";
|
|
}
|
|
|
|
if (typeof value === "string") {
|
|
return value;
|
|
}
|
|
|
|
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
|
return String(value);
|
|
}
|
|
|
|
if (value instanceof Date) {
|
|
return value.toISOString();
|
|
}
|
|
|
|
return JSON.stringify(value);
|
|
}
|
|
|
|
export function serializeImpersonationAuditMetadata(metadata?: Record<string, unknown> | null): string | null {
|
|
if (!metadata) {
|
|
return null;
|
|
}
|
|
|
|
const redactedEntries = Object.entries(metadata)
|
|
.filter(([key]) => !SENSITIVE_METADATA_KEY_PATTERN.test(key))
|
|
.map(([key, value]) => [key, redactMetadataValue(value)] as const)
|
|
.filter(([, value]) => value.length > 0);
|
|
|
|
if (redactedEntries.length === 0) {
|
|
return null;
|
|
}
|
|
|
|
return JSON.stringify(Object.fromEntries(redactedEntries));
|
|
}
|
|
|
|
export async function createImpersonationAudit(
|
|
data: ImpersonationAuditCreateData,
|
|
client: ImpersonationAuditWriterClient = getDbClient() as unknown as ImpersonationAuditWriterClient,
|
|
): Promise<ImpersonationAuditRecord> {
|
|
return client.impersonationAudit.create({
|
|
data: {
|
|
actorUserId: data.actorUserId,
|
|
targetUserId: data.targetUserId,
|
|
tenantId: data.tenantId ?? null,
|
|
action: data.action,
|
|
reason: data.reason ?? null,
|
|
requestPath: data.requestPath,
|
|
metadata: serializeImpersonationAuditMetadata(data.metadata),
|
|
},
|
|
});
|
|
}
|