export type RetrievalSecurityCode = "UNAUTHORIZED" | "FORBIDDEN"; export type RetrievalSecuritySource = "memory" | "wiki"; function publicMessage( source: RetrievalSecuritySource, code: RetrievalSecurityCode, ): string { const label = source === "memory" ? "Memory" : "Wiki"; return code === "UNAUTHORIZED" ? `${label} authentication failed` : `${label} access is forbidden`; } export class FatalRetrievalSecurityError extends Error { readonly source: RetrievalSecuritySource; readonly code: RetrievalSecurityCode; constructor(source: RetrievalSecuritySource, code: RetrievalSecurityCode) { super(publicMessage(source, code)); this.name = "FatalRetrievalSecurityError"; this.source = source; this.code = code; } } function errorRecord(value: unknown): Record { return value !== null && typeof value === "object" ? (value as Record) : {}; } function codeFromStatus(status: unknown): RetrievalSecurityCode | undefined { if (status === 401) return "UNAUTHORIZED"; if (status === 403) return "FORBIDDEN"; return undefined; } export function retrievalSecurityCode( value: unknown, ): RetrievalSecurityCode | undefined { if (value instanceof FatalRetrievalSecurityError) return value.code; const record = errorRecord(value); if (record.code === "UNAUTHORIZED" || record.code === "FORBIDDEN") { return record.code; } const details = errorRecord(record.details); return ( codeFromStatus(details.upstreamStatus) ?? codeFromStatus(record.upstreamStatus) ?? codeFromStatus(record.httpStatus) ?? codeFromStatus(record.status) ); }