# Production deployment

Pushing (or merging) to the **`deploy`** branch deploys automatically:

| Repo | Workflow | What it does |
|---|---|---|
| `hostelcare-backend` | `.github/workflows/deploy.yml` | SSH → pull, `npm ci`, build, `prisma migrate deploy`, `pm2 restart`, health check |
| `hostelcare-frontend` | `.github/workflows/deploy.yml` | builds on the runner, rsyncs `dist/` to `/var/www/hostelcare-app` |

The backend builds **on the server** because `prisma migrate deploy` needs the
server's `DATABASE_URL`. The frontend builds **on the runner** because Vite
inlines `VITE_API_BASE_URL` at build time, and the server needs no toolchain to
serve static files.

> GitHub runs the workflow file as it exists on the branch being pushed. These
> files must be merged into `deploy` before any of this takes effect.

---

## 1. One-time server preparation (EC2)

```bash
# Backend checkout, owned by the deploy user
sudo mkdir -p /home/ubuntu/hostelcare-backend
sudo chown -R ubuntu:ubuntu /home/ubuntu/hostelcare-backend
git clone git@github.com:rajkumariparihar/hostelcare-backend.git /home/ubuntu/hostelcare-backend
cd /home/ubuntu/hostelcare-backend && git checkout deploy

# Frontend web root — must be writable by the deploy user, or rsync fails
sudo mkdir -p /var/www/hostelcare-app
sudo chown -R ubuntu:ubuntu /var/www/hostelcare-app

# First boot of the API (creates the pm2 process the workflow later restarts)
cd /home/ubuntu/hostelcare-backend
npm ci && npm run build && npx prisma migrate deploy
pm2 start dist/server.js --name hostelcare-api
pm2 save && pm2 startup   # run the sudo line it prints, so pm2 survives reboots
```

The EC2 instance needs read access to the GitHub repo (deploy key or a machine
user), because the backend workflow does `git fetch` **on the server**.

## 2. Production `.env` (backend, on the server)

`.env` is gitignored, so it never arrives via `git pull` — create it once at
`/home/ubuntu/hostelcare-backend/.env`. Four values **must** differ from dev:

```ini
NODE_ENV=production
ALLOW_SUPER_ADMIN_SIGNUP=false          # or anyone can claim Super Admin if the table is ever empty
CORS_ORIGIN=https://app.hostelcare.in   # defaults to localhost:5173, which blocks the real frontend
JWT_ACCESS_SECRET=<fresh 32+ char secret>
JWT_REFRESH_SECRET=<different fresh secret>
```

Reusing the dev JWT secrets in production means anyone holding them can mint
valid tokens for any account. Generate new ones: `openssl rand -base64 48`.

**Email (needed for two-step verification and email reminders).** Without a
provider the server runs in dry-run mode, and outside development it refuses
to let anyone turn on two-step verification — a code that cannot be delivered
would lock the user out at their next sign-in.

```ini
EMAIL_PROVIDER=resend
EMAIL_API_KEY=<Resend API key>
EMAIL_FROM="HostelCare <no-reply@your-verified-domain>"
# OTP_TTL_MINUTES=10                    # optional, 2–30
# AUTH_OTP_ECHO must stay unset: the server refuses to boot with it in production
```

See `docs/two-factor-auth.md` for the sign-in contract the mobile app must follow.

## 3. GitHub secrets and variables

In **both** repos → Settings → Secrets and variables → Actions:

| Name | Kind | Value |
|---|---|---|
| `EC2_HOST` | secret | EC2 public DNS or IP |
| `EC2_USER` | secret | `ubuntu` |
| `EC2_SSH_KEY` | secret | full private key, including the BEGIN/END lines |
| `VITE_API_BASE_URL` | **variable** (frontend only) | `https://api.hostelcare.in` |

Prefer a dedicated deploy key over your personal one, so access can be revoked
without rotating your own.

Both workflows target the `production` GitHub **Environment** — add required
reviewers there if you want a human approval step before anything ships.

## 4. nginx

The frontend is a single-page app: any unknown path must return `index.html`,
or a refresh on `/login` gives a 404.

```nginx
server {
  server_name app.hostelcare.in;
  root /var/www/hostelcare-app;

  location / {
    try_files $uri $uri/ /index.html;
  }
}

server {
  server_name api.hostelcare.in;
  location / {
    proxy_pass http://127.0.0.1:4000;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
  }
}
```

Terminate TLS on both (certbot). The refresh token is an httpOnly cookie, so it
needs HTTPS to be sent as `Secure`.

## 5. Notes and limits

- **Migrations run automatically** on every backend deploy. `prisma migrate
  deploy` only applies migrations forward and never resets, but a migration that
  drops or rewrites a column is still irreversible — review those in the PR, and
  take a DB snapshot before deploying one.
- **`pm2 restart` drops in-flight requests.** If you switch pm2 to cluster mode
  (`instances: 'max'`), change the workflow to `pm2 reload hostelcare-api` for
  zero-downtime restarts. The app already handles `SIGTERM` and closes its
  listener cleanly, so reload works properly.
- **Rollback** is `git revert` on `deploy` (which redeploys), or on the server:
  `git reset --hard <last-good-sha> && npm ci && npm run build && pm2 restart
  hostelcare-api`. Note this does *not* roll a migration back — that needs a new
  forward migration.
- The backend builds on the server. On a small instance (t3.micro, 1 GB) `tsc`
  can be OOM-killed; if that happens, add swap or move to building artifacts on
  the runner and rsyncing `dist/`.
