export type SeedEnvironment = "production" | "development" | "test" | (string & {}); export type DbSeedDiagnosticPhase = "start" | "success" | "failure"; export type DbSeedDiagnosticEvent = { phase: DbSeedDiagnosticPhase; nodeEnv: SeedEnvironment; adminEmail?: string; error?: unknown; }; export type DbSeedDiagnostics = (event: DbSeedDiagnosticEvent) => void | Promise; export type DbSeedCallback = () => Promise | TResult; export type SeedCredential = { label?: string; email?: string; password?: string; }; export type SafeSeedCredentialOptions = { nodeEnv?: SeedEnvironment; adminEmail?: string; adminPassword?: string; seedCredentials?: SeedCredential[]; }; export type RunDbSeedOptions = SafeSeedCredentialOptions & { seed: DbSeedCallback; diagnostics?: DbSeedDiagnostics; }; const DEFAULT_ADMIN_PASSWORD = "password"; const DEFAULT_SEED_EMAILS = new Set(["admin@email.com", "john.doe@company.com", "luna.davis@company.com"]); export function assertSafeSeedCredentials({ nodeEnv = process.env.NODE_ENV ?? "development", adminEmail, adminPassword, seedCredentials = [], }: SafeSeedCredentialOptions): void { if (nodeEnv !== "production") { return; } const credentials: SeedCredential[] = [{ label: "admin", email: adminEmail, password: adminPassword }, ...seedCredentials]; if (credentials.some((credential) => !credential.email?.trim() || !credential.password?.trim())) { throw new Error("Refusing to run database seed in production with missing seed credentials."); } if ( credentials.some((credential) => (credential.email ? DEFAULT_SEED_EMAILS.has(credential.email) : false) || credential.password === DEFAULT_ADMIN_PASSWORD) ) { throw new Error("Refusing to run database seed in production with default seed credentials."); } } async function emitSeedDiagnostic(diagnostics: DbSeedDiagnostics | undefined, event: DbSeedDiagnosticEvent): Promise { await diagnostics?.(event); } export async function runDbSeed({ nodeEnv = process.env.NODE_ENV ?? "development", adminEmail, adminPassword, seedCredentials, seed, diagnostics, }: RunDbSeedOptions): Promise { assertSafeSeedCredentials({ nodeEnv, adminEmail, adminPassword, seedCredentials }); await emitSeedDiagnostic(diagnostics, { phase: "start", nodeEnv, adminEmail }); try { const result = await seed(); await emitSeedDiagnostic(diagnostics, { phase: "success", nodeEnv, adminEmail }); return result; } catch (error) { await emitSeedDiagnostic(diagnostics, { phase: "failure", nodeEnv, adminEmail, error }); throw error; } }