Sessions UI, CSV parser tests, route tests, composite indexes, verify-db action

Per-user sessions UI (Settings -> Active sessions)
- listMySessions returns the current user's still-valid sessions with
  last-8-char token suffix (UX hint) and an isCurrent flag (the
  authoritative "this device" marker).
- revokeSession refuses if the target is the actor's current token —
  use Sign out for that flow. Per-row Revoke button on every other.
- revokeAllOtherSessions = the previously-internal `deleteOtherSessions`
  helper exposed as a single button "Sign out other devices".
- All gated to the actor's own userId (never lets a user touch another
  user's sessions).

CSV parser refactor + tests
- Extracted parseCSV, NAME_MAP, parseFloatMaybe, parseIntMaybe,
  getVariationNote, resolveExerciseName, parseDate from
  app/api/import/parse/route.ts to lib/csvParser.ts. Behavior
  byte-identical; route is now a thin wrapper that imports from the
  lib.
- 18 tests covering: empty input, simple rows, lowercased headers,
  quoted-field commas, escaped double quotes, CRLF normalization,
  empty-line handling; numeric maybe-parsers; getVariationNote known
  patterns + null pass-through; ALL 27 NAME_MAP entries map to their
  canonical target; named CSV-shorthand examples; M/D/YYYY + ISO date
  parsing with noon-UTC anchoring (so US negative-offset zones still
  see the same calendar day).

Workout + exercise CRUD route tests
- New tests/routes-crud.test.ts: GET/POST /api/exercises, GET/POST
  /api/workouts. 401 on unauthenticated, per-user data isolation,
  query filtering, soft-delete exclusion, isCustom stamping, duplicate
  detection, type-driven inputFields defaults (cardio gets
  duration+calories), Zod validation rejection, set creation with
  weight/reps/rpe persisted, negative-reps rejected.
- Helper builds NextRequest objects so the routes' nextUrl.searchParams
  access works.

Composite indexes for hot query paths (schema.prisma + entrypoint)
- Session: (userId, expiresAt) for "list my still-valid sessions" and
  per-user cleanup.
- Workout: (userId, deletedAt, date) for the workout list query
  (filter by user + alive + date order).
- SetLog: (workoutId, setNumber) for the always-ordered set fetch
  under each workout.
- Existing single-column indexes kept; composites are additive.
- Entrypoint runs CREATE INDEX IF NOT EXISTS so live snapshots pick
  up the new indexes on first boot after upgrade.

verify-database StartOS action (start9/0.4/startos/actions/verifyDatabase.ts)
- Read-only. Runs PRAGMA integrity_check + quick_check + row-count
  queries against /data/app.db, reports as a structured result.
- allowedStatuses: only-running. Mounts the volume read-only.
- Use after a StartOS Backup, after a host crash, or after a fresh
  sideload to confirm the data is sound before relying on it.

Test suite now 67 tests across 7 files in ~2.4s.
This commit is contained in:
Keysat
2026-05-09 10:53:30 -05:00
parent 5de974edaf
commit 54fa77f2eb
11 changed files with 1001 additions and 146 deletions
+14
View File
@@ -123,6 +123,20 @@ if command -v sqlite3 >/dev/null 2>&1 && [ -f "$DB_PATH" ]; then
sqlite3 "$DB_PATH" "PRAGMA journal_mode=WAL;" >/dev/null
fi
sqlite3 "$DB_PATH" "PRAGMA synchronous=NORMAL;" >/dev/null
# Composite indexes for hot query paths. CREATE INDEX IF NOT EXISTS is
# idempotent — no-op if Prisma already created them via db push on a
# fresh install. These are also declared in schema.prisma so any future
# `prisma db push` keeps them in sync.
log "ensuring composite indexes are present"
sqlite3 "$DB_PATH" "
CREATE INDEX IF NOT EXISTS Session_userId_expiresAt_idx
ON Session(userId, expiresAt);
CREATE INDEX IF NOT EXISTS Workout_userId_deletedAt_date_idx
ON Workout(userId, deletedAt, date);
CREATE INDEX IF NOT EXISTS SetLog_workoutId_setNumber_idx
ON SetLog(workoutId, setNumber);
" >/dev/null
fi
# -----------------------------------------------------------------------------
+4
View File
@@ -1,6 +1,7 @@
import { sdk } from '../sdk'
import { changeAdminCredentials } from './changeAdminCredentials'
import { toggleSignups } from './toggleSignups'
import { verifyDatabase } from './verifyDatabase'
/**
* Package actions registered with StartOS.
@@ -11,7 +12,10 @@ import { toggleSignups } from './toggleSignups'
* - toggle-signups: open/close the multi-user sign-up gate. The same
* toggle is also available in-app at Settings -> Instance Settings
* (admin only). See toggleSignups.ts.
* - verify-database: read-only PRAGMA integrity_check + quick_check
* plus row-count snapshot. Run after a backup or a host crash.
*/
export const actions = sdk.Actions.of()
.addAction(changeAdminCredentials)
.addAction(toggleSignups)
.addAction(verifyDatabase)
@@ -0,0 +1,123 @@
import { sdk } from '../sdk'
/**
* verify-database — StartOS Package Action.
*
* Operator confidence check. Runs SQLite's `PRAGMA integrity_check` and
* a `PRAGMA quick_check` against /data/app.db, plus a few row-count
* sanity queries. Reports the results in the StartOS UI as a
* structured `result` so the operator can spot anomalies at a glance
* without dropping into a shell.
*
* Use cases:
* - "Did the StartOS Backup last night actually capture a healthy
* DB?" (Run the action AFTER a backup completes; integrity_check
* ok means the file is consistent.)
* - "I had a power loss / the host crashed — is the DB ok?"
* - "I just sideloaded a fresh image — did the seed copy correctly?"
*
* Read-only. Safe to run while the service is running. We use
* allowedStatuses: 'only-running' so the SQL goes through the live
* service's data-mounted subcontainer rather than starting one.
*/
export const verifyDatabase = sdk.Action.withoutInput(
'verify-database',
async () => ({
name: 'Verify database integrity',
description:
"Read-only. Runs SQLite PRAGMA integrity_check + quick_check against /data/app.db and reports row counts. Useful after a backup, a host crash, or a fresh sideload.",
warning: null,
visibility: 'enabled',
allowedStatuses: 'only-running',
group: null,
}),
async ({ effects }) => {
let result = { integrity: 'unknown', quickCheck: 'unknown', counts: {} as Record<string, string> }
await sdk.SubContainer.withTemp(
effects,
{ imageId: 'main' },
sdk.Mounts.of().mountVolume({
volumeId: 'main',
subpath: null,
mountpoint: '/data',
readonly: true,
}),
'verify-database',
async (sc) => {
const sql = [
"SELECT 'integrity:' || (SELECT * FROM pragma_integrity_check LIMIT 1);",
"SELECT 'quick:' || (SELECT * FROM pragma_quick_check LIMIT 1);",
"SELECT 'count:' || 'User' || '=' || (SELECT COUNT(*) FROM User);",
"SELECT 'count:' || 'Workout' || '=' || (SELECT COUNT(*) FROM Workout WHERE deletedAt IS NULL);",
"SELECT 'count:' || 'Exercise' || '=' || (SELECT COUNT(*) FROM Exercise);",
"SELECT 'count:' || 'SetLog' || '=' || (SELECT COUNT(*) FROM SetLog);",
"SELECT 'count:' || 'Session' || '=' || (SELECT COUNT(*) FROM Session WHERE expiresAt > CURRENT_TIMESTAMP);",
].join('\n')
const res = await sc.execFail(['sqlite3', '/data/app.db'], { input: sql }, 60_000)
const lines = res.stdout
.toString()
.split('\n')
.map((s) => s.trim())
.filter(Boolean)
for (const line of lines) {
if (line.startsWith('integrity:')) {
result.integrity = line.slice('integrity:'.length)
} else if (line.startsWith('quick:')) {
result.quickCheck = line.slice('quick:'.length)
} else if (line.startsWith('count:')) {
const [name, value] = line.slice('count:'.length).split('=')
if (name && value !== undefined) {
result.counts[name] = value
}
}
}
},
)
const ok = result.integrity === 'ok' && result.quickCheck === 'ok'
return {
version: '1',
title: ok ? 'Database is healthy' : 'Database integrity issues detected',
message: ok
? 'integrity_check + quick_check both returned ok. Row counts below.'
: `integrity_check returned: ${result.integrity}; quick_check returned: ${result.quickCheck}. Investigate before relying on the next backup.`,
result: {
type: 'group',
value: [
{
type: 'single',
name: 'integrity_check',
description: 'PRAGMA integrity_check result. Should be "ok".',
value: result.integrity,
copyable: false,
qr: false,
masked: false,
},
{
type: 'single',
name: 'quick_check',
description: 'PRAGMA quick_check result. Should be "ok".',
value: result.quickCheck,
copyable: false,
qr: false,
masked: false,
},
...Object.entries(result.counts).map(([name, value]) => ({
type: 'single' as const,
name: `${name} rows`,
description: name === 'Session' ? 'Active (unexpired) sessions.' : null,
value,
copyable: false,
qr: false,
masked: false,
})),
],
},
}
},
)