v2 Planning cont

This commit is contained in:
Ccjcarkbla
2026-06-10 22:27:30 -04:00
parent c70d2a391a
commit 817da60fd3
2 changed files with 259 additions and 3 deletions
+232
View File
@@ -0,0 +1,232 @@
# VitFit V2 — Audit Logs
## Purpose
Audit logs record who did what, when, and to which record. They serve two purposes:
1. **Security / compliance** — detect unauthorized changes, investigate incidents
2. **Operational accountability** — know who uploaded a video, who deleted a workout, who changed a password
Audit logs are **append-only**. No log record is ever updated or deleted.
---
## Event Catalog
### Authentication Events
| Action | Trigger | Details |
|--------|---------|---------|
| `auth.login.success` | Successful login | `{ username }` |
| `auth.login.failed` | Failed login attempt | `{ username, reason }` |
| `auth.logout` | Explicit logout | — |
| `auth.device.registered` | "Remember this device" issued | `{ deviceName, deviceType, expiresAt }` |
| `auth.device.revoked` | Device token revoked by admin | `{ deviceName, revokedBy }` |
| `auth.token.refreshed` | Silent JWT refresh via device token | — |
### User Management
| Action | Trigger | Details |
|--------|---------|---------|
| `user.create` | New user created | `{ after: { username, role } }` |
| `user.deactivate` | User deactivated | `{ before: { isActive: true }, after: { isActive: false } }` |
| `user.role.change` | Role changed | `{ before: { role }, after: { role } }` |
| `user.password.reset` | Admin resets a user's password | `{ targetUserId }` (no password in log) |
| `user.profile.update` | User updates own profile | `{ before: { firstName, lastName }, after: {...} }` |
| `coach.client.assign` | Coach assigned to client | `{ coachId, clientId }` |
| `coach.client.unassign` | Coach/client link removed | `{ coachId, clientId }` |
### Video Library
| Action | Trigger | Details |
|--------|---------|---------|
| `video.upload` | Video file uploaded | `{ filename, description, category, fileSizeBytes }` |
| `video.delete` | Video deleted | `{ before: { filename, description, category } }` |
| `category.create` | New category created | `{ name }` |
| `category.delete` | Category deleted | `{ before: { name } }` |
### Group Workouts
| Action | Trigger | Details |
|--------|---------|---------|
| `workout.create` | Workout created | `{ after: { name, workoutDate, videoIds } }` |
| `workout.delete` | Workout deleted | `{ before: { name, workoutDate } }` |
| `workout.display.launch` | Workout sent to TV display | `{ workoutId, name }` |
### Timers
| Action | Trigger | Details |
|--------|---------|---------|
| `timer.create` | Timer configuration created | `{ after: { name, totalTime, setTime, ... } }` |
| `timer.delete` | Timer deleted | `{ before: { name } }` |
| `timer.launch` | Timer started (sent to display) | `{ timerId, name }` |
| `timer.stop` | Running timer stopped early | `{ timerId, elapsedSeconds }` |
### CrossFit Workouts
| Action | Trigger | Details |
|--------|---------|---------|
| `crossfit.create` | CrossFit workout created | `{ after: { name, workoutDate, itemCount } }` |
| `crossfit.delete` | CrossFit workout deleted | `{ before: { name, workoutDate } }` |
### Client Workouts (1-on-1)
| Action | Trigger | Details |
|--------|---------|---------|
| `client_workout.create` | Workout created for client | `{ clientId, after: { name, scheduledDate } }` |
| `client_workout.update` | Workout modified | `{ clientId, before: {...}, after: {...} }` |
| `client_workout.delete` | Workout deleted | `{ clientId, before: { name } }` |
| `client_workout.complete` | Marked as completed | `{ clientId, workoutId }` |
### Calendar
| Action | Trigger | Details |
|--------|---------|---------|
| `session.create` | Session scheduled | `{ after: { clientId, startAt, endAt, type } }` |
| `session.update` | Session rescheduled or modified | `{ before: {...}, after: {...} }` |
| `session.cancel` | Session cancelled | `{ before: { startAt }, cancelledBy }` |
| `session.status.change` | Status updated (e.g., completed, no-show) | `{ before: { status }, after: { status } }` |
### Organization & Branding
| Action | Trigger | Details |
|--------|---------|---------|
| `org.create` | New organization created | `{ after: { name, slug } }` (SystemAdmin only) |
| `org.update` | Org settings changed | `{ before: {...}, after: {...} }` |
| `branding.update` | Logo/colors changed | `{ before: { primaryColor, ... }, after: {...} }` (logo path, not binary) |
| `logo.upload` | Logo file uploaded | `{ filename, fileSizeBytes }` |
### Storage / System
| Action | Trigger | Details |
|--------|---------|---------|
| `storage.warning` | Disk space drops below warn threshold | `{ available, threshold }` (system-generated) |
| `upload.rejected.storage` | Upload rejected due to low disk | `{ attemptedBy, availableBytes }` |
---
## Implementation
### Where Logs Are Written
Logs are written explicitly in route handlers, not via generic middleware. This is intentional — automatic middleware logging produces too much noise (every GET request) and misses the context (what changed, before/after values).
```js
// Example: video upload route
router.post('/upload', authenticateToken, upload.single('video'), async (req, res) => {
const video = await Video.create({ ... });
await AuditLog.create({
organizationId: req.user.organizationId,
userId: req.user.id,
userRole: req.user.role,
action: 'video.upload',
entityType: 'video',
entityId: video.id,
details: JSON.stringify({ filename: video.filename, category: video.category, fileSizeBytes: video.fileSizeBytes }),
ipAddress: req.ip,
userAgent: req.get('User-Agent'),
});
res.json(video);
});
```
A helper function keeps this concise:
```js
// core/audit.js
async function log(req, action, entityType, entityId, details = {}) {
await AuditLog.create({
organizationId: req.user?.organizationId ?? null,
userId: req.user?.id ?? null,
userRole: req.user?.role ?? 'system',
action,
entityType,
entityId,
details: JSON.stringify(details),
ipAddress: req.ip,
userAgent: req.get('User-Agent'),
});
}
module.exports = { log };
// Usage:
await audit.log(req, 'video.upload', 'video', video.id, { filename: video.filename });
```
### Failed Login Logging
Login failures need to be logged even when there's no `req.user`. The auth route handles this directly:
```js
router.post('/auth/login', loginRateLimiter, async (req, res) => {
const user = await User.findOne({ where: { username: req.body.username } });
if (!user || !await bcrypt.compare(req.body.password, user.password)) {
await AuditLog.create({
action: 'auth.login.failed',
details: JSON.stringify({ username: req.body.username, reason: user ? 'bad_password' : 'unknown_user' }),
ipAddress: req.ip,
userAgent: req.get('User-Agent'),
});
return res.sendStatus(401);
}
// ...
});
```
Note: `username` is logged on failed login (not password). This is useful for detecting brute-force attempts.
---
## API Endpoints
```
GET /audit-logs Owner: paginated log for their org
SystemAdmin: query param ?orgId= for cross-org
GET /audit-logs/export Download as CSV (Owner+ only)
```
Query params for `GET /audit-logs`:
- `?page=1&limit=50` — pagination
- `?action=video.upload` — filter by action
- `?userId=123` — filter by user
- `?from=2025-01-01&to=2025-12-31` — date range
- `?entityType=video` — filter by entity type
---
## Frontend (Audit Log Viewer)
Accessible from Owner panel and SystemAdmin panel.
Layout:
- Filterable table: timestamp, user, role, action, entity, details summary
- Expandable row: shows full `details` JSON formatted
- Filter bar: action type, date range, user dropdown
- "Export CSV" button
- Paginated (50 records per page, no infinite scroll — avoids memory issues on long sessions)
Color-code rows by action category:
- Auth events: blue
- Deletes: red
- Creates: green
- Updates: yellow
- System/storage: gray
---
## Retention
Audit logs are never automatically deleted. On a single-gym SQLite installation, logs are small (a few KB per entry) and accumulate slowly. Tens of thousands of entries are not a concern for SQLite.
If the table grows problematic (unlikely within a gym's operating lifespan), a SystemAdmin can export to CSV and truncate via a manual SQL operation — there is no automated purge in V2.
---
## What Is NOT Logged
- Successful read requests (too noisy, no value)
- Timer tick events (too frequent)
- Page views / navigation
- Failed requests due to auth (401/403) — except failed logins
- Health check endpoint calls
+27 -3
View File
@@ -2,26 +2,50 @@
This folder contains all planning documentation for the V2 redesign.
## Documents
| Document | What it covers |
|----------|---------------|
| [PRODUCT_VISION.md](PRODUCT_VISION.md) | Resale strategy, multi-instance vs SaaS decision, branding, feature tiers, roadmap phases |
| [REQUIREMENTS.md](REQUIREMENTS.md) | What V2 must do — functional features, stability, security, and platform constraints |
| [ARCHITECTURE.md](ARCHITECTURE.md) | How to build it — stack decisions, module system, real-time strategy, dependency plan |
| [ROLES_AND_PERMISSIONS.md](ROLES_AND_PERMISSIONS.md) | Full role hierarchy (SystemAdmin/Owner/Coach/Client), permission matrix, UI nav by role |
| [DATA_MODEL.md](DATA_MODEL.md) | All database entities with fields — Organizations, Users, DeviceTokens, ClientWorkouts, CalendarSessions, AuditLogs, Branding |
| [ARCHITECTURE.md](ARCHITECTURE.md) | How to build it — stack decisions, module system, real-time strategy, storage monitoring, video streaming |
| [AUDIT_LOGS.md](AUDIT_LOGS.md) | What gets logged, event catalog, implementation pattern, API, frontend viewer |
| [DISPLAY_DESIGN.md](DISPLAY_DESIGN.md) | iPad + Safari + AirPlay + TV specifics — PWA config, 24h session stability, typography, Safari quirks |
| [MIGRATION_PLAN.md](MIGRATION_PLAN.md) | How to move V1 data to V2 without loss — Sequelize migration strategy, rollback plan |
## Key Decisions at a Glance
### Product
- **Model:** Multi-instance (one deployment per gym). Data model is SaaS-ready (`organizationId` on all tables) but no multi-tenant routing in V2.
- **Resale:** White-label branding per org (logo, colors, name), configurable per instance
- **Roles:** SystemAdmin (platform) → Owner → Coach → Client
- **Current customer:** Single gym, maps to one Organization; existing accounts map to Owner/Coach roles
### Architecture
- **Stack:** Express.js + SQLite (Sequelize with migrations) + Socket.io + Nginx
- **Frontend:** Vanilla JS + shared CSS (no heavy framework)
- **Timer:** Server-side state machine via Socket.io — drift-free, survives reconnects
- **Display:** PWA (`apple-mobile-web-app-capable`) to remove Safari chrome from TV mirror
- **Auth:** JWT 7-day TTL + silent background refresh, admin-only user creation
- **Auth:** JWT 7-day TTL + silent background refresh; Device Tokens for iPad kiosk auto-login
- **Modules:** Drop-in feature folders — add/remove without touching core
- **Process:** PM2 with memory limit restart, auto-start on server reboot
### Infrastructure
- **Server access:** PuTTY (SSH) + WinSCP (SFTP) only — no other access method
- **Video files:** Stay at `/home/ubuntu/site/uploads/` — served via authenticated streaming route with Range support (required by Safari), never as static files
- **Video files:** Stay at `/home/ubuntu/site/uploads/` — authenticated streaming route with Range support (Safari requires this), never static
- **Storage monitoring:** Admin panel shows disk usage + uploads size; upload endpoint blocks new files when disk is low
### New Features vs V1
- Organization model + multi-role hierarchy
- 1-on-1 client programming (ClientWorkouts)
- Calendar/scheduling (CalendarSessions)
- Audit logs (append-only, viewable by Owner+)
- Branding settings per org
- Device token for iPad kiosk credential saving
- Storage monitoring in admin panel
## V1 Reference
The full V1 code walkthrough is at the repo root: [`CODEBASE_REFERENCE.md`](../../CODEBASE_REFERENCE.md)