Files
vitfit-r2/V2/planning/OPERATIONS.md
T
2026-06-11 10:52:07 -04:00

272 lines
10 KiB
Markdown

# VitFit V2 — Operations
## First-Run Bootstrap
New deployments have no users and no open `/register`. The first Owner and SystemAdmin are created through a one-time setup script that runs before the server starts for the first time.
### Setup Script
```bash
# On the server (via PuTTY), after deploying files and .env:
node scripts/setup.js
```
The script:
1. Checks that the database is accessible
2. Checks that no Organizations exist yet — if one does, it exits with an error (setup already done)
3. Prompts for:
- Organization name
- Owner username
- Owner password (typed twice; never echoed to terminal; bcrypt-hashed before storage)
- SystemAdmin username
- SystemAdmin password
4. Creates the Organization, Branding (defaults), Owner user, and SystemAdmin user in a single transaction
5. Prints a confirmation and exits
```js
// scripts/setup.js
const readline = require('readline');
const { sequelize, Organization, User, Branding } = require('../core/db');
const bcrypt = require('bcryptjs');
async function run() {
const orgCount = await Organization.count();
if (orgCount > 0) {
console.error('Setup already complete. Use the Owner panel to manage users.');
process.exit(1);
}
// ... prompt and create
}
run();
```
### After First Run
- The script is not deleted — but it refuses to run if any Organization exists
- Confirm the Owner can log in at `https://yourdomain.com/` before going live
- The SystemAdmin account should use a strong, unique password stored in a password manager — it is not used day-to-day
---
## Backup Strategy
### What to Back Up
| Item | Location | Criticality |
|------|----------|-------------|
| SQLite database | `/home/ubuntu/site/database.sqlite` | Critical — all data |
| Video files | `/home/ubuntu/site/uploads/` | High — cannot be re-uploaded cheaply |
| `.env` file | `/home/ubuntu/site/.env` | Critical — secrets, config |
### Automated SQLite Backup
SQLite's `.backup` command produces a consistent snapshot even while the database is open. A cron job runs this daily:
```bash
# Add via: crontab -e
# Runs daily at 3:00 AM
0 3 * * * sqlite3 /home/ubuntu/site/database.sqlite ".backup '/home/ubuntu/backups/db_$(date +\%Y-\%m-\%d).sqlite'" >> /home/ubuntu/backups/backup.log 2>&1
```
Backup directory: `/home/ubuntu/backups/`
**Retention:** Keep 14 daily backups. A cleanup line in the same cron entry:
```bash
0 3 * * * sqlite3 /home/ubuntu/site/database.sqlite ".backup '/home/ubuntu/backups/db_$(date +\%Y-\%m-\%d).sqlite'" && find /home/ubuntu/backups -name "db_*.sqlite" -mtime +14 -delete >> /home/ubuntu/backups/backup.log 2>&1
```
### Video File Backup
Video files change infrequently (new uploads only). A weekly rsync to a secondary location:
```bash
# Weekly on Sunday at 4:00 AM
0 4 * * 0 rsync -a --delete /home/ubuntu/site/uploads/ /home/ubuntu/backups/uploads/ >> /home/ubuntu/backups/backup.log 2>&1
```
If an offsite backup is required, WinSCP can be used manually to pull `/home/ubuntu/backups/` to a local machine. Automated offsite backup (e.g., S3) is a future enhancement.
### Restore Procedure
**Database restore:**
```bash
# Stop the app
pm2 stop vitfit
# Replace the database (use the desired backup date)
cp /home/ubuntu/site/database.sqlite /home/ubuntu/site/database.sqlite.pre-restore
cp /home/ubuntu/backups/db_2025-06-10.sqlite /home/ubuntu/site/database.sqlite
# Restart
pm2 start vitfit
pm2 logs vitfit --lines 20 # verify clean start
```
**Consistency note:** If restoring a database backup from day X, video files from after day X still exist on disk but their DB rows are gone — the videos will be orphaned (files exist, no DB record). This is benign; they will not appear in the UI. The converse (DB rows pointing to deleted files) cannot happen because deletes remove both.
**Video restore:** Copy files back from `/home/ubuntu/backups/uploads/` via WinSCP. Then re-run the sync to `uploads/`.
---
## Update / Patch Process
For multi-instance deployments, each customer's server must be updated separately.
### Routine Update Checklist (via PuTTY + WinSCP)
```
1. [ ] Read the release notes — identify whether migrations run, whether .env changes are needed
2. [ ] SSH in, take a DB backup manually:
sqlite3 /home/ubuntu/site/database.sqlite ".backup '/home/ubuntu/backups/db_pre-update.sqlite'"
3. [ ] WinSCP: transfer updated files (app.js, core/, modules/, public/)
Do NOT overwrite: .env, database.sqlite, uploads/
4. [ ] SSH: npm install (only if package.json changed)
5. [ ] SSH: npx sequelize-cli db:migrate (only if new migrations exist; idempotent if not)
6. [ ] SSH: pm2 restart vitfit
7. [ ] SSH: pm2 logs vitfit --lines 30 (verify clean start)
8. [ ] Test: log in, run a timer, check the admin panel
9. [ ] [ ] Mark update as complete in the customer log
```
### Version Numbering
Files released under `MAJOR.MINOR.PATCH`:
- PATCH — bug fixes, no migration, no .env changes
- MINOR — new features, may include migrations, .env additions documented
- MAJOR — breaking changes, significant migrations, manual steps required
Version is stored in `package.json` and displayed in the SystemAdmin panel and health endpoint response.
### Urgent Security Patches
For critical vulnerabilities:
1. Prepare the patch and test locally
2. Notify the customer of a maintenance window (even if short)
3. Follow the standard checklist — do not skip the DB backup step even under time pressure
4. Document the patch in the customer's history
---
## Monitoring and Alerts
### PM2 Log Management
PM2 writes logs to `~/.pm2/logs/`. Without rotation, these grow unbounded.
Enable PM2 log rotation:
```bash
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 20M
pm2 set pm2-logrotate:retain 7
pm2 set pm2-logrotate:compress true
```
### Health Endpoint
`GET /health` returns:
```json
{
"status": "ok",
"version": "1.0.0",
"uptime": 86423,
"db": "ok",
"diskAvailableGB": 28.4,
"diskWarnActive": false
}
```
If the database is unreachable or disk is in warning state, `status` returns `"degraded"` (HTTP 200 still — avoids false positives from monitors that check only status codes).
### External Uptime Monitoring
Use a free uptime monitor (UptimeRobot, BetterStack free tier, or similar) pointed at `https://yourdomain.com/health`. Alert channel: email or SMS to the operator.
This requires no server-side work — just register the URL in the external service. Set check interval to 5 minutes.
### Disk Space Alert
The storage monitoring feature (`/admin/storage`) already flags when disk is below `STORAGE_WARN_BYTES`. For automated alerting without a user looking at the panel:
A PM2 cron job script can check disk space and write an alert to the app log:
```bash
# Check disk and log warning (runs every hour via cron)
0 * * * * df /home/ubuntu/site/uploads/ | awk 'NR==2 {if ($5+0 > 85) print "DISK ALERT: " $5 " used on uploads partition"}' >> /home/ubuntu/site/app.log
```
The uptime monitor will surface this if you configure it to scan the health endpoint for `"diskWarnActive": true`.
### Let's Encrypt Certificate Renewal
Certbot auto-renews via a systemd timer (Ubuntu 24.04 default). Verify it is active:
```bash
systemctl status certbot.timer
```
If renewal fails, the cert expires in 90 days and the site goes HTTPS-broken — which breaks the PWA and AirPlay. Set the uptime monitor to also check the cert expiry date, or use the Certbot renewal hook to log failures to `app.log`.
---
## Support Diagnostics
When investigating a problem on a customer's instance, collect a support bundle:
```bash
# Run on the server via PuTTY
node scripts/support-bundle.js
```
The script outputs (to stdout, safe to copy from PuTTY):
```
VitFit Support Bundle — 2025-06-11 14:32:01 UTC
Version: 1.2.0
Node: v20.11.0
DB migrations: up to date (last: 005-add-video-mime-type)
DB size: 14.2 MB
Uploads size: 3.8 GB (47 files)
Disk available: 28.1 GB
Org count: 1
User count: 4 (1 Owner, 2 Coach, 1 Client)
PM2 status: online (uptime 12d 4h)
Recent errors: [last 5 error-level log lines, redacted of PII]
```
What the script does NOT include: passwords, JWT secrets, client personal data, video filenames, session notes. These are explicitly excluded in the generation script.
Redaction rules in `scripts/support-bundle.js`:
- Strip any log line containing `password`, `token`, `secret`, `email`
- Truncate any string > 100 chars in the error lines to prevent leaking session data
---
## Device Security Policy
### iPad Kiosk Security
The iPad running VitFit display is a shared device that is never turned off. Physical security is the gym owner's responsibility, but the following configuration is recommended:
| Setting | Recommendation |
|---------|---------------|
| iPad Passcode | 6-digit minimum, required for screen access |
| Auto-Lock | 15 minutes (AirPlay keeps screen active via mirroring, so lock only triggers if AirPlay drops) |
| Guided Access | Enable for the VitFit PWA to prevent staff accidentally navigating away or accessing iPad settings |
| Apple ID | Registered to the gym owner (not a personal Apple ID) |
| Find My | Enabled — required for remote wipe if stolen |
### Lost or Stolen iPad Response
1. Log in to the Owner panel from any device
2. Navigate to Settings → Devices
3. Revoke the device token for the lost iPad — this invalidates its silent auto-login
4. Use Find My (icloud.com) to locate or remote-wipe the device
5. The JWT on the stolen iPad expires within 7 days regardless; the device token revocation is immediate
### Device Token Rotation
Kiosk device tokens rotate on use: each time a device token is used to silently re-authenticate, the old token is invalidated and a new one is issued. This means a captured token can only be replayed before the iPad uses it next (typically within hours). Token rotation is automatic and transparent to the user.
Personal (non-kiosk) device tokens do not rotate — they are used less frequently and rely on the 30-day expiry instead.
### Kiosk Tokens Are Owner/Coach Only
Device tokens can only be created for accounts with role `Owner` or `Coach`. Client accounts cannot create device tokens — clients log in manually each session on their own devices.