Commit Graph

18 Commits

Author SHA1 Message Date
Keysat 0178f8f5cc v1.2.0:2 — retry login/signup server action once on transport failure
iOS Safari reuses a keep-alive socket the server closed while the login
form sat idle during typing, so the first Sign In / Create account POST
dies instantly with NSURLErrorNetworkConnectionLost ("The network
connection was lost"). That rejects the server-action call, hitting the
client-side catch in LoginForm/SignupForm and showing "An unexpected
error occurred"; the second tap lands on a fresh connection and works.

Add lib/retryAction.ts: retryOnTransportError() retries the action once
only when the call throws. A returned { error } (bad password, rate
limit) is a real result and passes straight through. A lost-on-a-stale-
socket POST never reached the server, so retrying it once is safe.
2026-06-15 16:44:33 -05:00
Keysat f487204b73 v1.2.0:1 — upgrade to Next.js 15 / React 19
CI / proof-of-work (Next.js app) (push) Has been cancelled
CI / start9/0.4 (StartOS package code) (push) Has been cancelled
Closes the remaining P1: move off Next 14 onto the CVE-patched Next 15
line (15.5.x), eliminating the framework's RSC DoS/source-exposure
advisories and the middleware-auth-bypass class that applied to the 14.x
auth gate. App Router on Next 15 requires React 19, so react/react-dom
move to 19.x in lockstep; lucide-react and next-themes bump to their
React-19-compatible releases.

The code surface was the Next 15 async-request-API change: params and
searchParams are now Promises. All [id] route handlers (10 files) and the
four server pages that read them now await the resolved value, using a
uniform re-derive idiom that leaves handler bodies untouched. cookies()/
headers() were already awaited, so no other request-API changes were
needed; all routes stay dynamic, so the uncached-by-default change is a
no-op. next.config.js (static CSP) and the middleware matcher are
unchanged. No schema, no API contract change, no data migration.

Verified: tsc + lint clean, 209 tests pass, next build succeeds with the
standalone bundle tracing the Prisma engine.
2026-06-13 00:29:47 -05:00
Keysat 3f22ef7600 v1.1.0:9 — P2 hardening: input-validation 400s, auth rate-limit, XFF anti-spoof, non-root container
CI / proof-of-work (Next.js app) (push) Has been cancelled
CI / start9/0.4 (StartOS package code) (push) Has been cancelled
P2 batch from the 2026-06-13 full-eval (EVALUATION.md / ROADMAP.md), reviewed by the reviewer agent. App-code + packaging only; no schema or data change, existing /data untouched.

Input validation: malformed JSON bodies, invalid date, and out-of-range or non-numeric pagination on /api/workouts now return 400 instead of 500. New lib/http.ts readJsonBody maps a bad body to a ZodError across the 11 CRUD routes whose catch maps ZodError to 400; me/import and admin/signups guard request.json() in an explicit try/catch.

Rate limiting: POST /api/auth now shares the UI login server action's per-IP 10-per-15min cap and returns 429 + Retry-After. clientIpFromHeaders reads the rightmost (trusted-proxy-appended) X-Forwarded-For entry instead of the spoofable leftmost.

Container: drops root. The entrypoint prepares /data as root, chowns it to nextjs, then exec su-exec nextjs:nodejs node server.js (su-exec added to the runner image). The container drop needs live sideload verification.
2026-06-13 00:03:47 -05:00
Keysat 988a3cca9a v1.1.0:8 — admin-gate whole-DB routes + AI custom-URL providers; SSRF guard
CI / proof-of-work (Next.js app) (push) Has been cancelled
CI / start9/0.4 (StartOS package code) (push) Has been cancelled
Multi-user authorization hardening from a full security evaluation (EVALUATION.md):

- P0: /api/settings/{export,import}-db are now admin-only. Previously any signed-in user could download the whole instance DB (all bcrypt hashes + plaintext AI keys) or replace it wholesale. Per-user CSV export/import stays open.

- AI custom-URL providers (Ollama, OpenAI-compatible) are now admin-only, and every server fetch to a user-supplied URL passes through assertSafeProviderUrl (blocks link-local/cloud-metadata; private LAN allowed by design). Fixed-URL cloud providers stay per-user. Removed the dead legacy /api/ai/config route.

- Dev: fixed broken quick-start (added npm run create-admin; rewrote README; dropped dead CLAUDE_API_KEY) and the export-db 0-byte path resolution (resolveDatabasePath now matches Prisma).

ExVer bumped to 1.1.0:8 (no schema/data migration). Tests 197 pass, build green, tsc clean.
2026-06-12 23:15:09 -05:00
Keysat 1a77a0bfc2 v1.1.0:7 — exercise-history popup auto-loads on scroll
The popup HAD an IntersectionObserver-based infinite scroll (since
v1.0.0:6 alongside the main workout-history page), but the observer
was unreliable inside an `absolute`-positioned scroll container with
a small 60px rootMargin. It often didn't fire at all — leaving the
user with a popup that scrolled internally but never fetched more
data even when hundreds of history entries existed server-side.

Fix: replace IntersectionObserver with a plain `scroll` event
listener on the popup. Fires whenever the user scrolls within 300px
of the bottom (matching WorkoutsList's lookahead on the main page).
Also runs once on mount in case the first page doesn't fill the
popup.

Bottom status row now shows "Loading more..." / "Scroll to load
more" / "End of history" so the user has feedback on state.

No schema, no API, no data.
2026-05-13 09:35:53 -05:00
Keysat 01529204cb v1.1.0:6 — exercise history popup scrolls further
The clock-icon popup in the workout editor was capped at max-h-80
(~320px = ~5 history rows). Users with multi-year history saw older
sessions hidden behind a tiny inner scrollbar. Bumped to 70vh so it
scales with the viewport — ~15+ rows on a normal display, more on a
large monitor.

The IntersectionObserver pagination already loaded more rows on
demand; the old cap just kept them off-screen.

Pure CSS-class change. No schema, no API, no data.
2026-05-13 09:28:32 -05:00
Keysat 35539a9341 v1.1.0:5 — Gemini model menu correctness
User pointed out their Google AI Studio dropdown shows gemini-3-pro,
gemini-3.1-pro, gemini-3-flash and gemini-2.5-flash — not the longer
preview names I shipped in v1.1.0:4. The menu was missing all the
Flash variants entirely.

Fix:
  - Add gemini-3.1-pro (short form, what AI Studio shows)
  - Add gemini-3.1-flash + gemini-3.1-flash-lite (the cheapest 3.x)
  - Add gemini-3-pro + gemini-3-flash (older tier, still available)
  - Pricing entries for all of the above (~$0.50/$3 per M for Flash)

Pure data fix; no schema or behavior changes.
2026-05-11 12:51:17 -05:00
Keysat 7a62690a4a v1.1.0:4 — multi-config AI, background generation, ollama auto-detect, system prompt overhaul
User-feedback-driven release after testing v1.1.0:3. Nine themes:

1. Multi-config persistence
   - New AIConfigProfile table (per-user). Save N configs, toggle one
     active. Switching providers no longer wipes the previous setup.
   - UserPreferences gains activeAIConfigId; legacy single-config
     columns are mirrored from the active profile so existing reads
     keep working without conditional logic.
   - Idempotent boot migration lifts any existing single-config row
     into a default profile.

2. Ollama auto-detect
   - The "Add config" form probes /api/tags on the StartOS internal
     addresses (ollama.startos / ollama.embassy on :11434). If
     reachable: URL pre-fills, model field becomes a dropdown of
     installed models. Fixes the copy-paste UX.

3. Curated model dropdowns for major providers
   - Claude: Opus 4.7, Sonnet 4.6 (1M ctx), Haiku 4.5
   - OpenAI: GPT-5.5, 5.4, 5.4-mini, 5.4-nano
   - Gemini: 3.1-pro-preview, 2.5-pro, 2.5-flash, etc.
   - "Other (type your own)" stays for niche models.
   - Fixes "I tried gemini-3.0-pro and got 404."

4. Background generation
   - lib/ai/generationRunner.ts: detached runner with in-memory
     pub/sub bus. POST /api/ai/generate kicks it off and returns
     immediately. SSE stream attaches by id. The runner survives
     request cancellation; navigating away no longer kills it.
   - New AIGeneration columns: progressText (in-flight stream),
     durationMs (final wall-clock).
   - Generate UI shows a banner explaining background-safety.
   - History detail page polls progress + renders partial JSON
     live for cross-process resume (page refresh, new tab).

5. System prompt overhaul
   - lib/ai/systemPromptBase.ts: structural contract prepended to
     every template. Forces JSON-only output, library-exerciseId
     usage (kills "exerciseId doesn't belong to this user" errors),
     and per-resistance-exercise suggestedWeight (with-history vs
     without-history variants).
   - aiExerciseSchema + ProgramExercise gain suggestedWeight +
     suggestedWeightUnit. Starting a workout from a ProgramDay
     pre-populates SetLog.weight from the suggestion.

6. Test connection improvements
   - Latency in seconds (was ms — confusing for slow Ollama).
   - Stale "✓ Connected" clears on form change.
   - Per-config Test (no need to activate first).
   - Generous maxOutputTokens for thinking models.
   - Gemini surfaces finishReason on empty response (e.g. "blocked
     by safety filter") instead of generic "empty response."
   - Test endpoint accepts a draft body so you can verify before
     saving + before activating.

7. History detail view
   - Click row → full program tree + exact prompts sent. Apply from
     here without re-generating. Pending rows poll for progress.

8. Sidebar sub-navigation
   - AI: Generate / History / Templates
   - Settings: General / Password / Sessions / AI integration /
     Export / Instance (admin) / Danger zone, with anchor scroll.

9. API key UX
   - "Key saved" indicator on saved configs (was confusing to see
     an empty input after a successful save).

Schema migrations (additive, idempotent in entrypoint):
  - AIConfigProfile table created
  - UserPreferences.activeAIConfigId
  - AIGeneration.progressText + durationMs
  - ProgramExercise.suggestedWeight + suggestedWeightUnit

Tests: 16 new (systemPromptBase, modelMenu, generationRunner). 177
total pass.
2026-05-11 08:09:01 -05:00
Keysat dba478aa23 v1.1.0:3 — AI upgrades: history context, test connection, cost estimator, streaming preview
Four incremental upgrades to the AI program generator. No schema change, no /data migration.

1. History as context (the killer feature)
   - lib/ai/historyContext.ts builds a 90-day per-exercise rollup:
     frequency, recent weights, estimated 1RM (Epley), avg RPE,
     days-since-last, plus a STAGNANT flag when the heaviest weight in
     the new half doesn't beat the old half.
   - Generate page surfaces an "Include my workout history as context"
     checkbox (default on at >=10 logged workouts). When checked, the
     ~1-3 KB summary is appended to the system prompt so the model can
     recommend things like "you've stalled bench at 245 — try paused reps."
   - We deliberately don't ship raw set logs (privacy + token cost).

2. Test connection
   - POST /api/ai/test sends a tiny "say hi in 3 words" prompt and
     reports latency + first sample, or the error inline.
   - "Test connection" button next to "Save AI config" in
     Settings -> AI integration. Verifies provider/model/key/baseUrl
     without going through full program generation.

3. Cost estimator
   - lib/ai/pricing.ts ships a price table for major models
     (Claude 3.5/3.7/4/4.5, GPT-4o/5/o1/o3/o4-mini, Gemini 1.5/2.0/2.5).
     Ollama always returns 0; openai-compatible returns null.
   - Generation history shows per-row cost + a 30-day rolling total
     at the top of the page.

4. Streaming preview render
   - lib/ai/lenientJson.ts: stack-aware partial-JSON parser that
     auto-closes open strings/brackets/braces in reverse-of-opening
     order, drops dangling key:value pairs and partial keywords.
     Returns a best-effort snapshot of the program-so-far on each chunk.
   - Generate UI now renders a live "Building program..." panel that
     updates as weeks/days/exercises arrive instead of just showing
     raw text and waiting for stream end.

Tests: 26 new (ai-historyContext.test.ts, ai-lenientJson.test.ts,
ai-pricing.test.ts). 161 total pass.
2026-05-10 22:17:35 -05:00
Keysat 974c3eb07d v1.1.0:2 — model-agnostic AI program generation (5 providers)
Five providers behind one streaming abstraction:
  - claude              (Anthropic)
  - openai              (api.openai.com)
  - openai-compatible   (any base URL — OpenRouter / LiteLLM /
                         vLLM / Together / your own gateway)
  - gemini              (Google)
  - ollama              (self-hosted; no key; LAN URL like
                         http://ollama.embassy:11434)

The "self-hosted Ollama on Start9" angle is the killer use case —
configure Settings → AI integration with the LAN URL of your Ollama
service and no API keys ever leave your network.

Architecture
  - lib/ai/types.ts              LLMProvider streaming interface
  - lib/ai/sse.ts                shared SSE + NDJSON line iterators
  - lib/ai/providers/*.ts        5 implementations + factory
  - lib/ai/programSchema.ts      Zod schema + JSON-schema-for-prompt +
                                  parseAIProgram with markdown-fence
                                  stripping and balanced-brace JSON
                                  extraction
  - lib/ai/apply.ts              materializes parsed AIProgram into
                                  Program tree (validates exerciseIds,
                                  rejects unresolved nulls, atomic
                                  transaction, sets aiGenerated=true)

Schema
  - UserPreferences gets aiProvider/aiModel/aiBaseUrl/aiApiKey
    (plaintext — same threat model as the rest of /data). Dead
    enableClaudeAI/claudeApiKey columns from v1.0.0:1-7 stay as
    no-op fields.
  - AIPromptTemplate (userId nullable; userId=NULL = built-in)
  - AIGeneration (raw response + parsed program + status +
    appliedProgramId + token counts)
  - All compat-ALTER'd in docker_entrypoint.sh on first boot.

API
  - POST   /api/ai/generate              SSE streaming: emits
                                           generation/text/usage/complete
                                           events; persists AIGeneration
                                           row up front so failures show
                                           in history too
  - POST   /api/ai/apply                 takes user-edited AIProgram,
                                           creates Program, marks
                                           generation as applied
  - GET    /api/ai/templates             built-ins + this user's own
  - POST   /api/ai/templates             create user-owned template
  - PATCH  /api/ai/templates/[id]        edit; built-ins admin-only
  - DELETE /api/ai/templates/[id]        delete; built-ins admin-only
  - GET    /api/ai/generations           list (paginated)
  - GET    /api/ai/generations/[id]      full row
  - DELETE /api/ai/generations/[id]      delete one (Program survives)
  - GET    /api/ai/config                returns aiKeyConfigured flag,
                                           never plaintext key
  - POST   /api/ai/config                update provider config
  - DELETE /api/admin/ai/generations     admin-only "clear all" with
                                           optional userId / olderThanDays

UI
  - Settings → AI integration            provider/model/URL/key form;
                                           plaintext key warning visible
  - /main/ai                             hub page with cards
  - /main/ai/generate                    template picker + textarea +
                                           live SSE stream + cancel +
                                           ProgramPreview with inline
                                           unknown-exercise resolver +
                                           apply button + redirect to
                                           the new Program
  - /main/ai/templates                   list + create + edit + delete;
                                           per-row "show prompt" expand;
                                           built-in delete warns about
                                           reconcile re-creation
  - /main/ai/history                     list + delete; status badges;
                                           link to applied Program
  - Nav: "AI" entry between Programs and Exercises (Sparkles icon)

Built-in templates
  - prisma/aiTemplates.seed.json: 5 starter templates (hypertrophy /
    strength / endurance / recovery / custom)
  - prisma/ensurePromptTemplates.cjs: per-boot reconcile,
    INSERT-or-UPDATE keyed on (userId IS NULL AND name=...);
    user-created templates never touched

Tests
  - tests/ai-programSchema.test.ts: extractJson + parseAIProgram
    edge cases (markdown fences, balanced braces, malformed JSON,
    Zod shape rejection, unresolved-exerciseId tolerance)
  - tests/ai-apply.test.ts: materializes valid AIProgram, rejects
    cross-user exerciseIds, rejects unresolved exercises, honors
    isActive flag
  - tests/routes-ai-templates.test.ts: built-in vs user permissions,
    cross-user template isolation, /api/ai/config plaintext-key safety,
    provider enum validation
  - 123 tests across 14 files, all passing.

No data migration. Existing /data is augmented with the new columns
+ tables only.
2026-05-10 15:35:35 -05:00
Keysat 3a5b929284 v1.1.0:1 — Programs UI (manual create / save / follow)
Schema
- Workout.programDayId added (nullable FK to ProgramDay) so a
  Workout logged from a program day can be tied back to the planned
  session for adherence analytics. Compat ALTER in entrypoint adds
  the column + index to existing /data; ON DELETE SET NULL so
  deleting a program doesn't remove historical workouts logged
  against it.
- Back-relation `workouts: Workout[]` added to ProgramDay.

API (proof-of-work/app/api/programs/...)
- GET    /api/programs                       — list user's programs
- POST   /api/programs                       — create with full nested
                                                 weeks/days/exercises
                                                 tree in one transaction
- GET    /api/programs/[id]                  — full tree
- PATCH  /api/programs/[id]                  — update metadata AND/OR
                                                 replace entire weeks
                                                 tree (same shape as
                                                 POST). UI editor + AI
                                                 apply flow share this.
- DELETE /api/programs/[id]                  — cascading
- POST   /api/programs/[id]/days/[dayId]/start
                                              — creates a Workout
                                                 pre-populated with
                                                 empty SetLogs (one per
                                                 planned set), tagged
                                                 with programDayId.

UI (proof-of-work/app/main/programs/...)
- /main/programs               — list with cards, today's-session
                                  callout, "active" badge
- /main/programs/new           — create form using ProgramEditor
- /main/programs/[id]          — detail + edit using same editor;
                                  today's-session card + Start button
                                  if program is active
- ProgramEditor component (components/programs/ProgramEditor.tsx) —
  expandable tree editor for weeks -> days -> exercises with
  per-row sets/reps/RPE/rest/notes fields + library exercise picker
- ProgramActions: delete button
- StartSessionButton: POSTs to start endpoint, redirects to new
  workout

Navigation
- "Programs" link added to bottom nav + sidebar (between Workouts
  and Exercises).
- /main/programs page itself shows the today's-session card; the
  same component pattern can be lifted into the dashboard later
  if we want.

lib/db/programs.ts
- getPrograms, getProgramById, getActivePrograms,
  computeTodaysSessionForProgram, getTodaysSession helpers.
- Today's session math: floor((todayUTC - startDateUTC) / 1day),
  weekNumber = floor(.../7) + 1, dayOfWeek = today.getUTCDay().
  Returns null if not started, past durationWeeks, or no day
  matching today's slot (= rest day).

Tests (tests/routes-programs.test.ts)
- 11 new tests covering: 401 unauthenticated, full-tree create
  with nested weeks+days+exercises, cross-user exerciseId
  rejection, list scoped to actor, GET detail returns 404 for
  another user's program, PATCH replace-tree atomicity,
  cascading DELETE, start-day Workout creation with the right
  number of empty SetLogs + programDayId stamped, start-day
  refused for cross-user program day.
- Total: 96 tests across 11 files.

This is the foundation for v1.1.0:2's AI-generated programs —
the AI will produce the same JSON shape POST /api/programs
already accepts, so the apply path is `editor.tsx + POST
/api/programs` with no new API surface.
2026-05-10 07:15:31 -05:00
Keysat 55c17614b8 v1.0.0:7 — exercise library cleanup, photo-import removal, AI-section honesty
Library JSON cleanup (proof-of-work/prisma/exercises.seed.json)
  19 exercises corrected:
  - Cycling/Jump Rope/Rowing/Running: type=cardio with proper
    inputFields (duration/distance/calories — no more reps/weight).
  - Walking Lunge/Wall Sit/Headstand/Hip Extension: reclassified
    out of cardio into bodyweight.
  - Plank/Mace warmup/Hollow Body Landmine/Soccer: inputFields
    fixed.
  - Descriptions added for ~10 cryptic exercises (Core, Resistance
    Band, Stir the pot, Slide Board, Neck Circuit, TGU, Captains
    of Crush, etc.).

Reconcile-on-boot (ensureExerciseLibrary.cjs)
  Changed from INSERT-OR-IGNORE to INSERT-OR-UPDATE keyed on
  (userId, name). Existing rows where isCustom = 0 get
  description/type/muscleGroups/inputFields/defaultWeightUnit
  refreshed from the curated JSON. Rows where isCustom = 1 are
  skipped — user customizations always win.

  Verified end-to-end: applied patches propagate to a copy of the
  user's snapshot DB; manually-tampered isCustom=1 rows survive a
  second reconcile pass untouched.

PATCH /api/exercises/[id] flips isCustom -> true on user edits
  Once you edit a library exercise via the in-app UI, the row's
  isCustom flag becomes 1 and the boot-time reconcile leaves it
  alone forever. Closes the only failure mode where a maintainer
  curated-library refresh could overwrite user edits.

Photo-import (Claude vision) removed
  - app/api/workouts/import/route.ts deleted.
  - components/import/WorkoutImportClient.tsx deleted (orphan
    component — wasn't referenced anywhere by the live UI).
  - CSV import (app/main/import → page-csv.tsx →
    /api/workouts/import/save) is unchanged. The save endpoint
    stays — it's used by the CSV flow too.

Settings UI: "Claude AI Integration" section removed
  The toggle + API key input promised "personalized workout
  recommendations" that the codebase never delivered (the only
  actually-wired use was the photo-import we just removed).
  Schema columns User.enableClaudeAI / User.claudeApiKey stay
  as harmless dead fields — they'll get cleaned up or repurposed
  when the model-agnostic AI work lands. The preferences API
  no longer accepts or returns those fields.

No data migration. /data on existing installs is untouched.
v1.0.0:7 promoted to current; :1-:6 in other.
2026-05-09 21:24:00 -05:00
Keysat ffa8e0d480 v1.0.0:6 — paginate workout history (infinite scroll)
Two surfaces had invisible 50-row caps that this commit removes.

Exercise history popup (clock button in WorkoutForm):
  - /api/exercises/[id] now accepts ?offset=N&limit=N (default 25,
    max 100) and returns { exercise, history, hasMore }. Pagination
    uses take: limit + 1 to detect hasMore without a second COUNT
    round-trip.
  - Query rewritten to use Prisma's setLogs.some filter — single SQL
    that hits the (userId, deletedAt, date) composite index, instead
    of fetching all set logs then grouping in JS.
  - ExerciseHistoryPopup now uses an IntersectionObserver on a
    sentinel div. When sentinel scrolls into view (root: the popup
    itself, not the viewport), fetches next page and appends. Status
    row at the bottom shows a spinner while loading and "End of
    history" when done.
  - Container max height bumped from h-64 -> h-80 for a bit more
    breathing room on first render.

Workout history page (/main/workouts):
  - Page still server-renders the first 50 workouts (instant paint
    + correct date filter forwarding). Now uses take: PAGE_SIZE + 1
    to detect hasMore.
  - New WorkoutsList client component takes initial workouts +
    hasMore + filter values as props. IntersectionObserver on a
    sentinel below the cards auto-fetches the next page from
    /api/workouts?offset=N&limit=50&q=...&dateFrom=...&dateTo=...
    when scrolled to. Filters round-trip through URL params, so a
    filter change re-renders the page from scratch with a fresh
    first page.
  - "End of history · N workouts" line shown once everything is
    loaded.

Tests:
  - tests/routes-exercise-history.test.ts: 6 new tests covering
    auth, cross-user 404, first-page hasMore=true, second-page
    hasMore=false + no overlap, set-log filter scoped to the
    queried exerciseId, soft-deleted workouts excluded.
  - All 87 tests pass.

No schema changes, no migration. /data untouched.
2026-05-09 20:18:31 -05:00
Keysat dc6a3b1116 v1.0.0:5 — remove caloriesBurned raw-SQL workaround
The three exported helpers in lib/prisma.ts (getCaloriesBurned,
setCaloriesBurned, getCaloriesBurnedBulk) existed because an early
Prisma client generation didn't include the column. Schema and
client have been aligned for several releases — the workaround is
dead weight.

Removed: the helpers from lib/prisma.ts (~30 lines of
$queryRawUnsafe / $executeRawUnsafe).

Updated callers to use plain caloriesBurned field references:
- app/api/workouts/route.ts (GET list + POST create)
- app/api/workouts/[id]/route.ts (GET detail + PATCH update)
- app/api/settings/export-csv/route.ts (CSV export)

All call sites now go through normal type-safe Prisma queries.
Net effect for users: zero. Net effect for the codebase: cleaner
read paths, stronger TS coverage on caloriesBurned, fewer SQL
strings to audit.

No schema changes, no migration. Existing /data is untouched.

v1.0.0:5 promoted to current; :1, :2, :3, :4 in other.
2026-05-09 19:42:45 -05:00
Keysat 5f7b3b6b7a v1.0.0:4 — remove default admin@local credentials; require StartOS action to bootstrap
Security: shipping admin@local / workout123 as a default that the
operator was supposed-to-rotate-but-might-not is the kind of footgun
that turns into "default-credential exposure" headlines. Eliminated.

prisma/seed.ts now ONLY seeds the InstanceSettings singleton — no
admin user, no UserPreferences, no exercises in the build-time
fallback DB. The image still ships with prisma/exercises.seed.json
(curated 164-exercise library) but those rows aren't inserted until
an admin is created via the StartOS Action.

The change-admin-credentials Action now does INSERT-or-UPDATE in one
shot. CREATE mode (no admin exists) inserts the User row, inserts
UserPreferences with sensible defaults, and runs
ensureExerciseLibrary.cjs for the new admin so they don't have to
wait for the next service start to see the curated library. UPDATE
mode (admin exists) keeps the v1.0.0:1-3 rotation behavior. The
mode is auto-detected by counting `WHERE isAdmin = 1`.

The login page is now a server component that reads the admin count
upfront. Zero admins -> renders a "needs setup" panel pointing at
the StartOS Action ("Services -> Proof of Work -> Actions -> Set
admin credentials"). Otherwise renders the existing LoginForm
(extracted to LoginForm.tsx). Eliminates the
"I tried admin@local/workout123 and it failed, what's wrong"
fresh-installer confusion.

Backward compatible for upgrades from v1.0.0:1-3:
  - /data already has an admin user; the no-admin detection never
    triggers; login behaves identically to before.
  - The Action's UPDATE mode still works for rotation.

Version graph: v1.0.0:4 promoted to current; v1.0.0:1, :2, :3 all
listed as `other` for in-place upgrade paths.

README updated to call out the explicit no-default-account design
and how to bootstrap an admin in local dev (Prisma Studio, since
the StartOS action isn't available off-StartOS).
2026-05-09 19:13:49 -05:00
Keysat 97ed07fd07 v1.0.0:3 — post-cutover seed strip
Removes the one-time `/data` snapshot from the deployed Docker image now
that the cutover from the legacy `workout-log` package is verified done
(v1.0.0:1 + :2 in production).

Dockerfile
- Drops `COPY start9/0.4/seed/data /app/seed/data`.
- Drops the `WORKOUT_BAKED_SEED_DB_PATH` env var.
- Comment block explains the rationale + how to re-seed if ever needed.

docker_entrypoint.sh
- Step 1 collapses to single-branch fallback: if /data is empty AND
  /app/prisma/data/app.db exists, copy the empty-schema fallback. The
  baked-seed branch is gone.
- Comment cross-references v1.0.0:3 for the rationale.

start9/0.4/seed/README.md rewritten to reflect historical-only status
+ how to re-seed for the rare "spin up another instance with this
history" case.

Version graph
- Adds startos/versions/v1.0.0.3.ts with empty up/down migrations and
  release notes.
- Promotes v1.0.0:3 to `current`; v1.0.0:1 and :2 move to `other` so
  hosts on either upgrade in place.

No schema changes, no data migration. /data on existing installs is
left exactly as-is. Image size drops by ~1.7MB (the snapshot size).
2026-05-09 13:40:58 -05:00
Keysat edeb1eb148 v1.0.0:2 — revert CSP nonces; restore inline-friendly CSP
v1.0.0:1 shipped a per-request nonce-based CSP via Next.js middleware.
In production it produced a blank first paint: Next 14.2.x's bootstrap
inline scripts weren't picking up the nonce reliably from the x-nonce
request header, so the browser blocked them.

This release reverts to the pre-experiment posture:
- middleware.ts back to auth gating only (no nonce, no CSP).
- next.config.js restores the static CSP with `'unsafe-inline'` allowed
  for script-src and style-src. Same headers (HSTS, Referrer-Policy,
  Permissions-Policy, frame-ancestors 'none', etc.) all stay.
- New startos/versions/v1.0.0.2.ts with empty up/down migrations and
  a release note explaining the bug + revert. Promoted to `current`
  in the version graph; v1.0.0:1 moves to `other` so existing
  installs upgrade in place.

No schema changes, no data migration. Existing v1.0.0:1 installs
keep their /data.

Re-attempt path documented in middleware.ts and next.config.js
comments: future PR can revisit nonce CSP using Next's documented
pattern verbatim (notably setting CSP on BOTH request headers and
response headers — we only set it on response).
2026-05-09 12:05:11 -05:00
Keysat aa407b5f67 Rebrand to Proof of Work; multi-user 0.4 package with curated library sync
Repo cleanup
- Add top-level .gitignore (was missing; node_modules, .next, *.s9pk,
  image.tar, seed/data/*.db, log files, etc.) and a root README.
- Delete legacy start9/0.3.5/ package (StartOS 0.3.5 wrapper, no longer
  the deploy target).
- Delete start9-example-packaging/ (template from another project).
- Delete planning docs (START9_PACKAGING_LOG.md, VERSIONING.md,
  STARTOS_0.4_UPGRADE_PROMPT.md, ICON_FILES_INDEX.md, etc.) — info now
  lives in the deploy guide and code comments.
- Drop the standalone Dockerfile, docker-compose.yml, ICON_*, and dev
  log/build artifacts from the app dir.
- Drop the v0.1.0:18/19/20 version files (they belonged to the legacy
  workout-log package and don't apply to the new id).

Rename + new package
- Rename app dir workout-planner/ -> proof-of-work/.
- Rename StartOS package id workout-log -> proof-of-work; the new id
  makes this a brand new StartOS service (clean cutover from the old
  one rather than in-place upgrade).
- Reset version graph; v1.0.0:1 is the seeded cutover release. The
  Dockerfile bakes a one-time /data snapshot and docker_entrypoint.sh
  copies it into the new volume on truly-fresh first boot only (both
  /data/app.db missing AND /data/.seeded absent).
- Move start9/0.4-migration/ -> start9/0.4/; the old start9/0.4/ stub
  is gone.

Curated exercise library (multi-user-aware)
- proof-of-work/prisma/exercises.seed.json is the canonical library
  shipped to every install (164 exercises today, dumped from the live
  snapshot).
- proof-of-work/scripts/sync-library.cjs (npm run sync-library) refreshes
  the JSON from start9/0.4/seed/data/app.db after refresh_seed.sh.
- proof-of-work/prisma/seed.ts now reads from the JSON instead of a
  hardcoded 52-exercise array; runs at Docker build time to seed the
  fallback DB and on first boot for fresh installs.
- proof-of-work/prisma/ensureExerciseLibrary.cjs runs on every container
  boot (from docker_entrypoint.sh) and INSERT OR IGNOREs every library
  entry for every user, keyed on (userId, name). Library updates flow
  to existing installs on package upgrade; user-custom exercises
  (isCustom=true) and any colliding names are never overwritten;
  removed exercises stay on existing installs (additive-only).

Deploy guide (start9/0.4/DEPLOY_040.md)
- Rewritten end-to-end for the workout-log -> proof-of-work cutover:
  refresh_seed, sync-library, build, sideload, verify, rotate creds,
  stop the old service, then post-cutover cleanup release v1.0.0:2.
2026-05-08 20:12:25 -05:00