diff --git a/lib/loadSecrets.ts b/lib/loadSecrets.ts new file mode 100644 index 0000000..c7e82e7 --- /dev/null +++ b/lib/loadSecrets.ts @@ -0,0 +1,45 @@ +import fs from 'fs'; +import path from 'path'; +import { execFileSync } from 'child_process'; + +function parseDotenv(contents: string) { + contents + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith('#')) + .forEach((line) => { + const idx = line.indexOf('='); + if (idx === -1) return; + const key = line.slice(0, idx).trim(); + let value = line.slice(idx + 1).trim(); + if (!key || key in process.env) return; + if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { + value = value.slice(1, -1); + } + process.env[key] = value; + }); +} + +export function loadLocalSecrets() { + const root = process.cwd(); + const plainPath = path.join(root, 'creds', 'secrets.env'); + const encPath = path.join(root, 'creds', 'secrets.enc.env'); + + if (fs.existsSync(plainPath)) { + try { + parseDotenv(fs.readFileSync(plainPath, 'utf8')); + return; + } catch { + // ignore and try encrypted + } + } + + if (fs.existsSync(encPath) && !process.env.SKIP_SOPS_AUTOLOAD) { + try { + const output = execFileSync('sops', ['-d', encPath], { encoding: 'utf8' }); + parseDotenv(output); + } catch { + // silent fail if sops/key not available + } + } +} diff --git a/lib/prisma.ts b/lib/prisma.ts index 5378963..2ecbe16 100644 --- a/lib/prisma.ts +++ b/lib/prisma.ts @@ -1,6 +1,9 @@ import { PrismaClient } from '@prisma/client'; import { PrismaPg } from '@prisma/adapter-pg'; import { Pool } from 'pg'; +import { loadLocalSecrets } from './loadSecrets'; + +loadLocalSecrets(); const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient }; diff --git a/prisma.config.ts b/prisma.config.ts index b7780d2..c84f25e 100644 --- a/prisma.config.ts +++ b/prisma.config.ts @@ -2,6 +2,9 @@ // npm install --save-dev prisma dotenv import 'dotenv/config'; import { defineConfig } from 'prisma/config'; +import { loadLocalSecrets } from './lib/loadSecrets'; + +loadLocalSecrets(); const databaseUrl = process.env.DATABASE_URL || 'postgresql://localhost:5432/lomavuokraus?sslmode=disable';