batchCooking/apps/api/test-support/reset-db.ts
Nicolas cf8ef26f63
All checks were successful
CI / lint (push) Successful in 1m4s
CI / intent-service-test (push) Successful in 10m52s
CI / build (push) Successful in 1m6s
CI / e2e (push) Successful in 5m36s
CI / test (push) Successful in 19m57s
feat(admin): fondation auth de l'application d'administration
Premiere brique de l'app d'admin independante : une surface /admin/*
ajoutee a apps/api, avec une authentification totalement distincte de
celle des utilisateurs.

- Table AdminUser isolee (aucune relation vers UserProfile), migration
  20260828120000_admin_user.
- lib/admin-jwt.ts : sign/verify d'un JWT admin, secret ADMIN_JWT_SECRET
  propre (jamais interchangeable avec JWT_SECRET).
- middlewares/require-admin.ts : cookie admin_session dedie, re-check
  tokenVersion, echoue ferme si ADMIN_JWT_SECRET absent (posture
  requireInternalWorker). res.locals.adminUser type via AdminLocals.
- modules/admin/ : admin-auth.{routes,service}.ts (POST /login, POST
  /logout, GET /me), admin.routes.ts agregateur monte /admin. Pas de
  signup expose.
- lib/safe-admin.ts : mapping AdminUser -> AdminUserView (drop passwordHash
  + tokenVersion, dates ISO).
- scripts/create-admin.ts : creation du 1er admin hors-bande (flags ou
  ADMIN_INITIAL_*).
- CORS : setupCore accepte string[] ; app.ts autorise CORS_ORIGIN +
  ADMIN_CORS_ORIGIN.
- Shared : schemas/admin.ts (adminLoginSchema), types/admin.ts
  (AdminUserView).
- Env : ADMIN_JWT_SECRET (optionnel), ADMIN_COOKIE_NAME, ADMIN_CORS_ORIGIN,
  ADMIN_INITIAL_* ; .env.example, .env.test.example, docker-compose.yml,
  ci.yml mis a jour.
- reset-db.ts truncate admin_users.
- Tests Mocha admin-auth.test.ts : 400 sans body, 401 email inconnu /
  mauvais mdp, login OK (cookie pose, lastLoginAt, pas de hash/tokenVersion
  dans la reponse), /me derriere requireAdmin, logout, et un cookie
  `session` d'utilisateur normal ne donne pas acces a /admin/*.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-28 12:02:19 +02:00

56 lines
2.7 KiB
TypeScript

import { env } from "../src/config/env.js";
import { prisma } from "../src/db/prisma.js";
import { syncRecipeSources } from "../src/db/recipe-source-sync.js";
import { seedReferenceData } from "../src/db/reference-seed-data.js";
/**
* Refuses to run outside a database that's obviously a test one — belt and
* braces alongside `config/env.ts` loading `.env.test` (not `.env`) under
* `NODE_ENV=test`: this already wiped a real local dev database once, when
* both env files shared one `DATABASE_URL`. `resetDatabase()` below
* TRUNCATEs almost the entire schema before every single test, so a
* misconfigured/missing `.env.test` must fail loudly here rather than
* silently truncate whatever `DATABASE_URL` happens to be set.
*/
function assertRunningAgainstTestDatabase() {
if (env.NODE_ENV !== "test") {
throw new Error(
`resetDatabase() TRUNCATEs almost the whole schema — refusing to run outside NODE_ENV=test (currently "${env.NODE_ENV}").`,
);
}
// "test" covers a local `.env.test` (`batchcooking_test`); "ci" covers
// CI's own service database (`batchcooking_ci`, set directly via the
// workflow's `env:`, not a `.env.test` file — see ci.yml). Neither
// matches the real dev database's name (`batchcooking`), which is the
// one case this must actually catch.
if (!env.DATABASE_URL?.includes("test") && !env.DATABASE_URL?.includes("ci")) {
throw new Error(
`resetDatabase() refuses to run against a DATABASE_URL that doesn't look like a test database (got "${env.DATABASE_URL}", expected it to contain "test" or "ci") — see .env.test.example.`,
);
}
}
// Single TRUNCATE ... CASCADE covers FK ordering and resets identity
// sequences — used between tests/scenarios to start from a clean slate.
// Re-seeds the Diet/Category/Allergy/Unit reference data right after
// truncating it, so every test starts from the same realistic reference
// data the real app seeds (`prisma/seed.ts`) rather than empty tables —
// tests exercising dietId/allergyIds/unitId need real rows to reference.
// `syncRecipeSources` runs last, for the same reason: `sources` should
// reflect whatever adapters this test run happens to have registered
// (usually none — see recipe-source-registry.ts).
export async function resetDatabase() {
assertRunningAgainstTestDatabase();
await prisma.$executeRawUnsafe(`
TRUNCATE TABLE
"user_profile_allergy", "user_preference", "allergy", "category",
"planning_item", "planning",
"recipe_ingredient", "step_tech_step", "step", "tech_step",
"recipe", "ingredients", "sources", "unit",
"user_profiles", "diet", "house",
"admin_users"
RESTART IDENTITY CASCADE;
`);
await seedReferenceData(prisma);
await syncRecipeSources(prisma);
}