# hostelcare-backend

Multi-tenant hostel management SaaS — backend. Node.js + Express + TypeScript + Prisma (PostgreSQL).

## Stack
- Express + TypeScript
- Prisma ORM → PostgreSQL (shared-schema multi-tenancy, `tenantId` discriminator)
- JWT auth (access + refresh), bcrypt hashing
- AWS S3 for uploads (KYC docs, photos)

## Getting started

```bash
npm install
cp .env.example .env      # then fill DATABASE_URL + AWS_* (secrets)
npm run prisma:generate
npm run prisma:migrate     # needs a reachable DATABASE_URL
npm run dev
```

Server: http://localhost:4000 — health check at `/api/health`, DB readiness at `/api/health/db`.

## Scripts
| Script | Purpose |
|---|---|
| `npm run dev` | Hot-reload dev server (ts-node-dev) |
| `npm run build` | `prisma generate` + `tsc` → `dist/` |
| `npm start` | Run compiled `dist/server.js` |
| `npm run typecheck` | Type-check without emitting |
| `npm run prisma:migrate` | Create/apply a dev migration |
| `npm run prisma:studio` | Open Prisma Studio |
| `npm run test:isolation` | Tenant-isolation test (runs against a throwaway `hc_test` schema) |
| `npm run smoke` | End-to-end auth/role smoke test (throwaway `hc_smoke` schema) |

> `test:isolation` and `smoke` connect to the Postgres in your `.env` and create/drop
> their own isolated schemas, so they never touch dev data. They need a reachable
> `DATABASE_URL`, which is why CI runs build/typecheck only.

## Multi-tenancy (Sprint 1)
Cross-tenant isolation is enforced centrally in [`src/lib/prisma.ts`](src/lib/prisma.ts):
- `db` — tenant-scoped client; auto-injects `tenantId` from the request's
  AsyncLocalStorage context ([`authenticate`](src/middleware/authenticate.ts) sets it). Fail-closed.
- `prismaUnscoped` — raw client, only for pre-auth (login) and SUPER_ADMIN work.

Proven by `npm run test:isolation` (Tenant A cannot read/modify Tenant B's data).

## Sprint 1 API
| Method & path | Role | Purpose |
|---|---|---|
| `POST /api/auth/signup` | public (once) | Bootstrap the first SUPER_ADMIN |
| `POST /api/auth/login` | public | Login → access token + refresh cookie |
| `POST /api/auth/refresh` | cookie | New access token |
| `POST /api/auth/logout` | — | Clear refresh cookie |
| `GET /api/auth/me` | any | Current user |
| `POST /api/tenants` | SUPER_ADMIN | Create tenant + first HOSTEL_ADMIN |
| `GET /api/tenants` | SUPER_ADMIN | List tenants |
| `PATCH /api/tenants/:id/plan` | SUPER_ADMIN | Set tenant plan |
| `POST /api/sub-admins` | HOSTEL_ADMIN | Create Warden / Mess Admin (tenant-scoped) |
| `GET /api/sub-admins` | HOSTEL_ADMIN | List sub-admins |

## Environment
See [`.env.example`](.env.example). `DATABASE_URL` and AWS keys are secrets — never commit `.env`.
