diff --git a/accessibility_standards.md b/accessibility_standards.md new file mode 100644 index 0000000..e02e137 --- /dev/null +++ b/accessibility_standards.md @@ -0,0 +1,64 @@ +# CutTheCard Accessibility Standards (project file) +Last Updated: 2026-10-11 + +**Standing rule — applies to every human and every AI that touches this project:** nothing ships to QA or Production unless it meets **WCAG 2.2 Level AA**. This is a release requirement, not a polish item. When asked to build any page, modal, form, email, blog template or export, build it to this document by default without being asked. + +Why this standard: WCAG 2.x AA is the benchmark courts, the U.S. DOJ (ADA Titles II/III), Section 508, and state laws (e.g. California Unruh Act, New York, Florida) use in practice. No automated tool or document can *guarantee* legal compliance; this file defines our engineering standard and evidence trail. Legal questions go to counsel. + +## 1. What is built in (do not undo) +| Piece | File | Purpose | +|---|---|---| +| Accessibility stylesheet | `static/a11y.css` | Focus rings, skip link, 24px targets, reduced motion, forced-colours, 320px reflow, link underlines | +| Runtime layer | `static/a11y.js` | Skip link, `
`, names for controls, keyboard access for click handlers, dialog focus trap/Esc/restore, live regions, table headers, new-tab notice, `deA11y.announce()` | +| Design tokens | `shared.css` `:root` blocks | Every text token is >= 4.5:1 on every surface in BOTH themes | +| Statement page | `static/accessibility.html` | Public statement + feedback route; linked from every footer and the sitemap | +| Blog gate | `blog_sanitize.accessibility_problems()` | Publishing/scheduling is refused if an image lacks `alt`, a link is empty/vague, headings skip, or a table lacks `` | +| Audit tool | `a11y/a11y_audit.py` | axe-core + 320px reflow + focus-visible + source lint; run before every Deploy to Prod | + +**Every new HTML page MUST include, in ``:** `` and ``, plus ``, a unique ``, and `<meta name="viewport" content="width=device-width, initial-scale=1.0" />` (never `user-scalable=no`). Server-rendered HTML (e.g. `routers/blog.py`, email) follows the same rules. + +## 2. Build rules (the checklist) +1. **Structure:** one `<h1>`; headings never skip levels; one `<main id="main-content" tabindex="-1">`; header/nav/footer outside `<main>`; every `<nav>` has `aria-label`. +2. **Colour:** use tokens (`var(--text-muted)` etc.), never raw hex for text. New text/background pairs must be >= 4.5:1 (3:1 for 18px+ bold/24px+ and UI borders/icons). Never use `opacity` to dim text. White text on `--link` blue fails: use `#2563b8`. +3. **Not colour alone:** status needs text or an icon with a text name; in-text links stay underlined. +4. **Controls:** use real `<button>` / `<a href>`. Never `onclick` on `div`/`span`/`a` without href. Min target 24x24 CSS px. Icon-only buttons need `aria-label`. +5. **Forms:** every input has a visible `<label for>`; placeholder is a hint, never the label. Use `autocomplete` tokens for name/email/password. Errors: text next to the field, `aria-invalid="true"` (use `deSetFieldError`), message in an element with `role="alert"` or `aria-live`. Say how to fix it. +6. **Dialogs:** use the existing overlay/backdrop classes (`.modal-backdrop`, `.modal-overlay`, `.auth-overlay`, ids ending `Overlay`/`Backdrop`) with an `<h2>` title and a Close/Cancel button — `a11y.js` then supplies `role="dialog"`, focus trap, Esc, and focus return. Never open a dialog without a heading. +7. **Images/charts:** informative image = real `alt`; decorative = `alt=""`. Any chart/graph needs a text or table equivalent of the data. Animated content that auto-plays > 5 s needs a pause control and must respect `prefers-reduced-motion`. +8. **Tables:** `<th scope>` headers, `<caption>` or `aria-label`; no layout tables. +9. **Dynamic updates:** announce results/toasts with `deA11y.announce('Saved', 'polite')`. +10. **Keyboard:** everything reachable and operable with Tab/Enter/Space/Esc; focus order matches reading order; focus never hidden by sticky UI; no keyboard traps. +11. **Reflow/zoom:** no horizontal scrolling at 320px wide (400% zoom); do not set fixed widths on content containers. +12. **Time limits / auth:** no CAPTCHA or cognitive-test login; password fields allow paste and password managers; warn before any session timeout. +13. **Language:** plain wording; consistent navigation/labels across pages. +14. **Documents we generate** (Records Archive .xlsx/.docx, emails): real headings/header rows, document title set, alt text on images, meaningful link text, language set, no information in colour alone. +15. **Blog/content authors:** descriptive alt text; descriptive link text (not "click here"); heading levels in order; the publish gate enforces the mechanical parts. + +### Navigation pattern (sidebar groups, added 2026-10-11) +The grouped sidebar (`server_debteliminator.md` §8b) follows the **disclosure pattern**, not a menu/tab widget: each group header is a real `<button type="button">` with `aria-expanded` and `aria-controls` pointing at a `<ul>` panel (hidden with the `hidden` attribute when closed); child links are normal `<a>`s in `<li>`s; the current page's link has `aria-current="page"`. Top-level icons are inline SVG with `aria-hidden="true"`; in the collapsed rail the text labels stay in the DOM (visually clipped) so names are never lost. New nav entries must be added to `DE_NAV_ALL` / `DE_NAV_ADMIN` in `shared.js` - never hand-written per page. Do not use `role="menu"`/`menuitem` here, and do not put `role="group"` on a `<ul>` (axe fails it). + +## 3. Release gate (every deploy) +1. `python3 a11y/a11y_audit.py --app <qa app dir> --fail-on serious` → must print **PASS** (both themes). +2. Manual 5-minute pass on every NEW or CHANGED screen: (a) unplug the mouse — complete the task with keyboard only, focus always visible; (b) 200% and 400% zoom — nothing lost; (c) VoiceOver (Mac/iOS) or NVDA (Windows) — headings, form labels and errors are read sensibly; (d) light AND dark theme. +3. DevLog task notes: record "A11y audit PASS + manual pass done" before clicking Deploy to Prod. +4. `a11y.js` debug output (QA hostname, or `?a11y=1`): fix every "repaired at runtime" message in the source — the runtime layer is a safety net, not the plan. + +## 4. Known gaps / open items (update as closed) +- Full manual screen-reader review of: Debt Reduction Plan timeline, Payment Register grid, Windfall/Milestones, charts. +- Records Archive .xlsx/.docx accessibility structure not yet reviewed. +- Placeholder-as-label still exists in some index/account/donate forms (named via the runtime layer; add visible labels when touching them). +- Click-only `span`/`div` controls remain in index/payoff/milestones/windfall (made keyboard operable by the runtime layer; convert to `<button>`). +- Email templates (`email_templates.py`, mailer) not yet audited. +- Grouped sidebar (2026-10-11): axe (WCAG 2.x A/AA) clean in dark + light and 320 px reflow verified in headless Chromium; **`a11y_audit.py` and the manual keyboard/screen-reader pass still to be done** on the new nav and the Household page before Deploy to Prod. +- Household page and banner (v2.1.20): not yet in the manual screen-reader review list. +- Start Here home page (Home Page Swap, 2026-10-11, `public_pages/home.html` served at `/`): headings are now `<h1>`/`<h2>`/`<h3>`, decorative emoji are `aria-hidden`, link colours use `var(--link)`; **`a11y_audit.py` and the manual keyboard/screen-reader pass (signed-in and signed-out, both themes, 320 px) still to be done before Deploy to Prod.** The audit tool should be pointed at `public_pages/` as well as `static/` if it only crawls `static/`. Sidebar footer link renamed "Start Here". +- Consider a third-party audit / VPAT and periodic re-test (at least twice a year and after major redesigns). + +## 5. Summary for AI systems +- Read this file before building ANY UI. Default to the rules above without being asked. +- Include `a11y.css` + `a11y.js` in every page; keep `<main>`, labels, headings, alt text, contrast tokens. +- Do not weaken `a11y.css` / `a11y.js` or remove focus outlines to "fix a look". +- Never claim the site "is ADA compliant"; say it targets WCAG 2.2 AA and was tested as described here. +- Before Deploy to Prod: run `a11y_audit.py`; report its result. + +# ✔️ End of File diff --git a/claude_token_efficiency_tips.md b/claude_token_efficiency_tips.md index e89bf0d..d7d57c8 100644 --- a/claude_token_efficiency_tips.md +++ b/claude_token_efficiency_tips.md @@ -1,5 +1,5 @@ # Token Efficiency Tips for KingDezigns / Fund Tracker Work with Claude -Last Updated: 2026-08-17 +Last Updated: 2026-10-11 **Read this file first, before starting other work in this project.** It captures patterns observed across a long Fund Tracker build/deploy conversation that burned more tokens than necessary — mostly from long back-and-forth deployment troubleshooting. None of this changes what Claude can do, only how efficiently a conversation gets there. @@ -28,6 +28,14 @@ Several rounds in this project asked for one small thing, got it built and deplo The deploy pattern for this project (SCP to a scratch directory → `sudo cp` into the OMV-managed project directory → rebuild or restart depending on what changed) is now stable and documented. A short deploy script run directly on KingDezigns001/NAS16 will do this identically every time without needing a guided chat conversation at all. Ask Claude to write that script once; use it going forward instead of a fresh guided walkthrough per deploy. +## Mandatory: every file delivery opens with the deploy commands + +Efficiency never means dropping the deploy block. Whenever Claude delivers files, the reply +**starts** with the full SCP → `sudo cp` → restart command sequence in a single block (real file +names, `sudo rm` for deleted files, restart-vs-rebuild stated, a verification line or two), then +explains the change. Batching into one block is the efficient part; omitting it is never acceptable, +even on small changes and follow-up revisions. Template: `server_debteliminator.md` §3a-0. + ## When reporting an error, paste full context in one message Partial command output followed by a follow-up asking for more context costs an extra round trip every time. Pasting the full command **and** its full output together the first time (even if it looks noisy) usually resolves faster than an incremental back-and-forth. diff --git a/debteliminator_subscription_model.md b/debteliminator_subscription_model.md new file mode 100644 index 0000000..46a280a --- /dev/null +++ b/debteliminator_subscription_model.md @@ -0,0 +1,322 @@ +# Debt Eliminator / CutTheCard — Subscription Model Transition Plan + +Last Updated: 2026-10-11 + +> **Status update (2026-09-30):** the v2.1.3 production backup contains +> the SitePay code this plan describes — `routers/subscribe.py` (paid +> Checkout + Customer Portal), `subscription_reconcile.py` (daily +> reconciliation, trial-ending emails), `User.access_status`, the +> `billing-locked.html` lockout page, `subscribe.html`, admin endpoints for +> reconciliation / donor migration / settings, and the Admin → Subscriptions +> page. Individual phase checkboxes below have **not** been re-verified +> against source. Also new: subscription payments are now recorded in the +> `donations` ledger with `payment_kind="subscription"` and surfaced on +> Admin → Subscriptions (tiles, per-user amounts, year selector) and the new +> Admin → Revenue page — see `server_debteliminator.md` §12g (this departs +> from Phase 3's original "writes no Donation row" wording for invoices). +> +> **Note (2026-10-11):** v2.1.20 added **Household Sharing** +> (`server_debteliminator.md` §12j). Per the Help Center text, *sharing your +> accounts is part of a paid plan; opening a household you were invited to is +> not limited* - so `access_status` interacts with household features (an +> owner whose access lapses should lose the ability to share; a member's +> own access is independent). Enforcement details were not verified against +> source. The QA compose file in the v2.1.20 backup now contains a +> `STRIPE_SECRET_KEY` entry, so the "QA has no Stripe keys" blocker listed in +> Phase 1 may be resolved - confirm test-mode keys and a separate QA webhook. +> +> **Original status: Planning — not yet built.** This document defines the target +> architecture and phased build plan for converting CutTheCard from a +> donation-supported free tool to a free-trial → paid-subscription model, +> with Stripe remaining the payment processor. Nothing in this document is +> live yet. Once Phase 1 work begins, treat `server_debteliminator.md` as +> authoritative for what has actually shipped, and this file as the plan +> being executed against — update this file's checkboxes/status as phases +> complete rather than letting it silently go stale. +> +> This document should be linked from `network_index.md` alongside the +> other `server_debteliminator.md`-adjacent docs once added to the project. + +--- + +## 0. Why This Document Exists + +CutTheCard currently supports itself via optional one-time and recurring +Stripe donations (see `server_debteliminator.md` §12a). This plan covers +converting to: free trial for new signups, a paid monthly subscription +after the trial, permanent free access for admin accounts, and an +admin-controlled mechanism to grant free access (forever or until a date) +to specific users. Stripe remains the payment processor — this is a +billing-model change, not a payment-processor change. + +--- + +## 1. Business Model Decisions (confirmed) + +| Decision | Value | +|---|---| +| Admin accounts (including the primary admin) | Never pay, always full access — no Stripe involvement | +| Admin-grantable free access | Forever, or until a specific date — admin-set, audit-logged | +| New-signup trial | **60 days, no credit card required at signup** (see §2) | +| Existing **one-time** donors | Granted **4 months of free access** as a thank-you, starting at paywall launch | +| Existing **recurring/monthly** donors | **Auto-converted to subscriber status** — their existing Stripe subscription continues uninterrupted; this is not a new checkout | +| Payment processor | Stripe (unchanged) | +| Pricing / plan tiers | Not yet set — single plan assumed for launch; multi-tier is explicitly out of scope until there's demand (see Phase 5) | + +**Open item to confirm before Phase 4:** anonymous one-time donations +(`Donation.user_id IS NULL`) have no account to grant free access to. +Decide whether to (a) leave as-is — no account, nothing to grant, or +(b) email anonymous donors with a matching donor_email inviting them to +create/link an account to claim their 4 free months. Recommend (a) for +launch simplicity, with (b) as a possible Phase 5 follow-up. + +--- + +## 2. Trial Length — 60 Days, and Why + +CutTheCard's value doesn't show up on day one — the debt-free date +visibly moving, a balance-transfer opportunity appearing, the plan +re-ranking after a real payment lands, all take at least one full billing +cycle to happen. A 30-day trial mostly captures people before the product +has done anything for them. + +**Decision: 60-day trial, no card required at signup.** Rationale: + +- Covers two monthly cycles for nearly every user — enough to see at + least one "the plan updated because you made a payment" moment. +- No card at signup means zero billing risk during the trial — nothing + to auto-charge, nothing to fail — which also keeps "trial expired" and + "payment failed" as two separate, simpler code paths at launch instead + of one tangled one. +- The admin free-access grant is the escape valve for the "this + particular person needs month 3" case, so the trial length doesn't need + to be solved perfectly up front — an admin can just extend someone + manually after a support conversation. +- Instrumented from Phase 1 (see below) so the number can be revisited + with real data in Phase 5, rather than guessed a second time. + +**Trial length must be admin-configurable** via `SystemSetting` (same +pattern as `donation_enabled`/`default_theme`), not hardcoded — so it can +be tuned later without a deploy. + +--- + +## 3. Target Data Model + +### `users` — new columns +| Column | Purpose | +|---|---| +| `trial_ends_at` | Set at registration from the `SystemSetting` trial-length value | +| `free_access_forever` | Bool — admin grant, never expires | +| `free_access_until` | Nullable date — admin grant, expires on this date | +| `free_access_granted_by` | Username of the granting admin (or `"system-migration"` for the donor grandfather, §6) | +| `free_access_reason` | Free text, shown in Admin UI | +| `stripe_customer_id` | Stripe Customer, distinct from any anonymous donation's customer record | +| `stripe_subscription_id` | Stripe Subscription | +| `subscription_status` | Mirrors Stripe's `status` (`trialing`/`active`/`past_due`/`canceled`/`unpaid`) — written **only** by webhook handlers or the reconciliation job, never directly | +| `subscription_current_period_end` | Mirrors Stripe | +| `subscription_cancel_at_period_end` | Mirrors Stripe | + +### New table — `processed_stripe_events` +`stripe_event_id` (unique), `processed_at`. Every webhook handler checks +this first and skips if already present — Stripe redelivers events, and +none of the handlers below are safe to run twice without this. + +### Computed, not stored — `access_status` +A property/function, evaluated at request time from the columns above and +`is_admin`/`is_primary_admin`, in this priority order: + +``` +is_admin or is_primary_admin → "admin" (always full access) +free_access_forever → "free_grant" +free_access_until >= today → "free_grant" +trial_ends_at >= today → "trial" +subscription_status in → "subscriber" + (active, trialing) +subscription_status == past_due → "grace" (full access + banner) + AND within grace window +otherwise → "expired" +``` + +Computing this rather than storing it means it can never drift out of +sync with its inputs — the same reasoning already applied to +`is_primary_admin` being a property, not a column. + +--- + +## 4. Phase 1 — Billing Infrastructure (invisible to users) + +Nothing user-facing changes. Goal: the plumbing exists and is proven in +QA before anything can lock a real user out. + +- [ ] Migration: add the `users` columns above (§3) +- [ ] Migration: create `processed_stripe_events` +- [ ] New webhook handlers in `routers/donate.py` (or a new + `routers/subscriptions.py`, TBD at build time): + `customer.subscription.updated`, `invoice.payment_failed` — + alongside the existing `checkout.session.completed`, + `invoice.paid`, `customer.subscription.deleted` +- [ ] Idempotency: every handler checks/writes `processed_stripe_events` + first +- [ ] New scheduled job: daily Stripe subscription reconciliation + (same cadence/pattern as the weekly overdue-item digest in + `devlog.py`) — pages Stripe, corrects any local + `subscription_status` drift +- [ ] Instrumentation fields/log for `first_debt_account_created_at` and + `first_payment_logged_at` per user — this is what makes the Phase 5 + trial-length review possible +- [ ] **QA gets its own Stripe test-mode keys and its own webhook + endpoint.** Currently only Production has Stripe configured at all + (`server_debteliminator.md` §5) — this must exist before any of the + above can be tested. + +**Exit criteria:** in QA, create a test subscription, fail a payment, +cancel it, and confirm local `subscription_status` tracks Stripe's real +state — both via webhook delivery, and via the reconciliation job alone +with webhook delivery disabled. + +--- + +## 5. Phase 2 — Access-Status Logic and Enforcement + +Still mostly invisible — this is where lockout becomes *possible*, but is +not turned on for any real user yet. + +- [ ] Implement `access_status` (§3) as a computed property +- [ ] New dependency `require_active_access`, modeled directly on the + existing `require_not_suspended` (`routers/auth.py`) — applied to + the same core routers: Accounts, Transactions, Payment Register, + Debt Reduction Plan, Records Archive +- [ ] Lockout page (redirect target for `expired`) and a non-blocking + banner for the `grace`/`past_due` state +- [ ] Admin endpoint `POST /admin/accounts/{username}/grant-free-access` + — `forever: bool` or `until: date`, plus `reason` — audit-logged + the same way as other admin account actions +- [ ] Decide final grace-period length for `past_due` (recommend + matching however long Stripe's Smart Retries run, so a user is + never locked out mid-retry-cycle) + +**Exit criteria:** a QA test user can be walked trial → expired → locked, +and separately admin / free-grant / subscriber → never locked, with no +ambiguity in the access-status logic. + +--- + +## 6. Phase 3 — Real Subscription Checkout, Signup Flow, and Donor Migration + +This is where it becomes a real product change. + +- [ ] `trial_ends_at` auto-set on registration from the configurable + trial-length `SystemSetting` +- [ ] New subscription Checkout Session flow, distinct from the existing + one-time/recurring donation flow, and a pricing/upgrade page +- [ ] **Stripe Customer Portal integration** — self-service + cancel/update-card/view-invoices. Do not build this UI by hand; + use `billingPortal.Session`. +- [ ] Transactional emails (immediate `force=True`, same pattern as + password-reset — not routed through the throttled campaign system + in `routers/campaigns.py`, since these are time-sensitive to one + user): trial-ending-soon (~day 53), payment-failed, + subscription-canceled confirmation +- [ ] **Donor migration script** (run once, at cutover): + - **Recurring donors** — for every `Donation` row with `recurring=true` + and an active `stripe_subscription_id`, copy that subscription ID + onto the linked `User`, set `subscription_status` from the next + reconciliation run (do not guess it), and treat as `subscriber`. + **No new Stripe checkout — the existing subscription simply becomes + their paid access.** + - **One-time donors** — for every `Donation` row with `recurring=false`, + `status='completed'`, and a non-null `user_id`, set + `free_access_until = launch_date + 4 months`, + `free_access_granted_by = "system-migration"`, + `free_access_reason = "One-time donor — 4 months free at launch"`. + A donor with multiple qualifying one-time donations should not stack + — one 4-month grant per user, not per donation. + - **Anonymous one-time donors** — see the open item in §1. + +**Exit criteria:** a brand-new QA signup can go trial → real Stripe +test-mode subscription → cancel → resubscribe end to end, with correct +emails at each step; the migration script runs cleanly against a copy of +Production data and produces the expected grant/subscriber counts. + +--- + +## 7. Phase 4 — Legal, Admin Visibility, Launch Prep + +- [ ] Terms of Use / new **Billing Terms** section: refund policy, what + cancellation actually does and when, clear auto-renewal disclosure +- [ ] Admin **Subscriptions** view — status, current period end, grant + reason, per user (extend the existing Admin → Donations page or add + a new one) +- [ ] New Support request type: billing issue + (`SUPPORT_REQUEST_TYPES` in `models.py`) +- [ ] Decide the fate of the existing donate button — likely kept as a + one-time "tip" option for trial/free users, reworded so it's not + confused with the subscription +- [ ] Communication plan to existing users about the change (the new + campaign-email infrastructure in `routers/campaigns.py` is + well-timed for this) +- [ ] Full QA dry run covering: trial expiry, payment failure + dunning + + recovery, self-cancel via Customer Portal, admin free-grant, + admin extending a near-trial-expiry user, and both donor-migration + paths from §6 + +--- + +## 8. Phase 5 — Post-Launch (data-driven, not pre-planned) + +- [ ] Revisit the 60-day trial length using the §4 instrumentation — + look specifically at conversion timing relative to + `first_payment_logged_at` +- [ ] Only build engagement-based auto-extension (e.g., extend trial for + users who've logged 2+ payment cycles but haven't converted) if the + data actually shows a meaningful cluster of month-3 converters who + would've been lost at 60 days +- [ ] Multiple pricing tiers, proration, annual billing — out of scope + until there's real demand for any of them + +--- + +## 9. Standing Open Decisions + +| Item | Status | +|---|---| +| Anonymous one-time donor grandfathering | Not decided — see §1 | +| Exact `past_due` grace-period length | Not decided — see §5 | +| Pricing (monthly amount) | Not yet set | +| Whether the donate button survives post-launch | Leaning yes, as a tip jar — not finalized | + +--- + +## 10. Summary for AI Systems + +- This is a **plan document, not yet built** — do not describe any of + this as live functionality until `server_debteliminator.md` reflects it. +- Target model: admin/primary-admin always free; admin can grant free + access (forever or until a date); new signups get a **60-day, + no-card-required trial**; existing **recurring** donors auto-convert to + subscribers on their existing Stripe subscription (no new checkout); + existing **one-time** donors get **4 months free** from launch. +- Access is governed by a single **computed** `access_status` property, + not a stored/cached value — priority order: admin > free_grant > trial + > subscriber > grace (past_due) > expired. +- The `require_active_access` dependency is modeled directly on the + existing `require_not_suspended` pattern — reuse the lockout mechanism + already built for self-suspension rather than inventing a new one. +- Stripe is the source of truth for subscription state — local + `subscription_status` is written only by webhook handlers and the + daily reconciliation job, never set directly. Webhook idempotency via + `processed_stripe_events` is required, since Stripe redelivers events. +- QA currently has **no Stripe keys at all** — Phase 1 cannot be tested + without adding QA-specific Stripe test-mode keys and a separate webhook + endpoint. +- Five phases: (1) billing infra, invisible; (2) access-status + + enforcement, invisible; (3) real checkout + signup flow + donor + migration, user-facing; (4) legal/admin/launch prep; (5) post-launch + data-driven tuning of the trial length. +- The 60-day trial number is a starting hypothesis, deliberately + instrumented for revision — not a final answer. + +--- + +# ✔️ End of File diff --git a/kingdezigns-ai-001-summary.md b/kingdezigns-ai-001-summary.md new file mode 100644 index 0000000..dd444f2 --- /dev/null +++ b/kingdezigns-ai-001-summary.md @@ -0,0 +1,434 @@ +# OpenCode + Ollama Setup Summary + +**Machine:** KingDezigns-AI-001 +**Originally written:** September 14, 2026 +**Last Updated:** September 19, 2026 + +> **What changed on 2026-09-19 (fast summary):** Ollama was upgraded from +> v0.17.5 to v0.34.2 (required to pull the `qwen3.6` models), which exposed +> a Vulkan regression on this machine's Radeon 780M, so Ollama is now +> **pinned to v0.32.9**. A duplicate context-length setting was fixed +> (effective context is now 32768, was silently 16384), KV-cache +> quantization and an iGPU-enable override were added, and a backup/restore +> script (`~/ollama-safe.sh`) was created. Kilo Code was evaluated and +> removed. Full detail in the sections below; the current known-good state +> is summarized in "Current Known-Good State." + +## 🛟 Quick Reference — Backup and Rollback (read this first) + +**Before ANY Ollama change (update, downgrade, config edit), take a backup:** + +```bash +~/ollama-safe.sh backup # asks for sudo; takes a minute; ~3.9 GB each +~/ollama-safe.sh list # confirm the new backup appears +``` + +Wait for the line `Backed up Ollama v<version> to ~/ollama-backups/<timestamp>-v<version>` before changing anything. + +**If something breaks, roll back to a specific backup (recommended):** + +```bash +~/ollama-safe.sh list # find the directory name you want +~/ollama-safe.sh restore ~/ollama-backups/<directory-name> # restore that exact state +``` + +Plain `~/ollama-safe.sh restore` (no directory) restores the **newest** +backup by name — usually the state you are trying to get away from — so +always pass the directory when rolling back to an older version. + +**What restore does:** stops Ollama, puts back the saved binary, the bundled +libraries (including Vulkan), the service file and all drop-in config files, +reloads systemd, restarts Ollama, and prints the version and model list. +It does **not** touch downloaded model files. + +**After any restore, verify:** + +```bash +ollama --version # expect the version you restored +ollama list # all models still listed +systemctl show ollama -p Environment --no-pager | tr ' ' '\n' | grep -i -E "kv_cache|context|igpu|vulkan" +ollama run gpt-oss:20b "say hi" && ollama ps # expect 100% GPU +``` + +**Which backup to restore:** + +| Goal | Restore this | +|---|---| +| Back to the original working setup (Ollama v0.17.5, no qwen3.6 support) | `~/ollama-backups/20260918-233357-v0.17.5` | +| Back to v0.34.2 (has the Vulkan regression for large models — not recommended) | `~/ollama-backups/20260919-204850-v0.34.2` | +| Back to the current working state (v0.32.9) | `~/ollama-backups/20260919-205838-v0.32.9` | + +The script lives at `~/ollama-safe.sh`. If it is ever lost, it can be +recreated; see "Backup and Restore Script" below for what it backs up. + +--- + +## Hardware + +**GMKtec NucBox K8 Plus** — Linux Mint 22.3 (Cinnamon), kernel 6.8.0-139-generic + +| Component | Details | +|---|---| +| CPU/APU | AMD Ryzen 7 8845HS w/ Radeon 780M Graphics (8 cores) | +| GPU | Radeon 780M integrated (RDNA3, gfx1103) — not on AMD's official ROCm support list | +| RAM | 29.6 GB unified (shared CPU/iGPU) | +| GPU memory Ollama can actually use | **~17.1 GiB total / ~16.3 GiB available** as reported by Ollama's Vulkan discovery (`Vulkan0`, AMD Radeon 780M, RADV PHOENIX) | +| Storage | ~1 TB (NVMe, `/dev/nvme0n1p5` root, ~768 GB, ~42% used on 2026-09-19) | + +The ~16.3 GiB GPU budget is the number that decides which models run fully on +the GPU. In practice: **models of roughly 15 GB or less load at 100% GPU; +models of 17 GB or more need a CPU/GPU split** (see "Model Findings"). + +## Original Problem + +OpenCode (AI coding agent) + Ollama + `qwen3.5:9b` would generate tool calls (file creation, shell commands) but only print them as text instead of actually executing them — nothing got created on disk. + +## Fixes and Build (original, 2026-09-14) + +1. **Ollama pinned to v0.17.5** — a known bug in other versions causes the "tool calls print but don't execute" symptom with qwen3.5 models. + ```bash + curl -fsSL https://ollama.com/install.sh | OLLAMA_VERSION=0.17.5 sh + ``` + **Superseded 2026-09-19 — Ollama is now pinned to v0.32.9.** See + "Ollama Version History and Current Pin." Whether the qwen3.5 + tool-calling bug still exists on v0.32.9 has **not been retested yet** + (open item). + +2. **GPU acceleration switched from ROCm to Vulkan** — ROCm's runner crashes on the Radeon 780M (gfx1103 unsupported). Forced Ollama onto its Vulkan backend (Mesa RADV driver) via systemd overrides in `/etc/systemd/system/ollama.service.d/` (see "Ollama systemd Configuration" for the current file set). Confirmed working via `ollama ps` showing `100% GPU`. + +3. **Model** — `qwen3.5:9b` pulled and confirmed with `tools` + `thinking` capabilities. Later testing expanded to many other models (see "Model Findings"). + +4. **OpenCode installed** — v1.18.31 via the official install script, `~/.opencode/bin` added to PATH. + +5. **Provider config** — `~/.config/opencode/opencode.json` points OpenCode at Ollama's OpenAI-compatible endpoint (`http://localhost:11434/v1`) and explicitly marks `qwen3.5:9b` as tool-capable. + +6. **Global instructions** — `~/.config/opencode/AGENTS.md` sets a standing rule so the agent defaults to creating files under `/home/rufusking/Documents/workspace/projects` without being told every time. + +7. **Web access** — `opencode web --port 4096` starts a local browser UI showing projects/sessions instead of just a terminal. + +8. **Desktop shortcuts** — two `.desktop` launcher icons (Start/Stop OpenCode) backed by shell scripts in `~/.local/bin/`, tracking the server via a PID file so it can be toggled without a terminal. + +## Network Access Change (2026-09-14) + +**Goal:** reach the OpenCode web UI from another PC on the LAN, while keeping Ollama and all model inference local to this machine only. + +### What changed + +`~/.local/bin/opencode-start.sh` — the server launch line was updated to bind on all network interfaces instead of just loopback: + +```bash +# Before +nohup opencode web --port 4096 > "$LOGFILE" 2>&1 & + +# After +nohup opencode web --port 4096 --hostname 0.0.0.0 > "$LOGFILE" 2>&1 & +``` + +Ollama itself was **not** touched — it still listens on `127.0.0.1:11434` only (confirmed again in the v0.34.2 server config log on 2026-09-19), so the remote PC cannot call it directly. All inference stays on this machine; the remote PC only talks to the OpenCode web UI, which relays to Ollama locally. + +### Firewall + +```bash +sudo ufw allow 4096/tcp +sudo ufw enable +``` + +### Result — confirmed working + +``` +Local access: http://localhost:4096 +Network access: http://192.168.100.50:4096 +Network access: http://192.168.100.51:4096 +``` + +Verified reachable from a second PC on the LAN. + +## ⚠️ Outstanding security item + +The server log shows: + +``` +! OPENCODE_SERVER_PASSWORD is not set; server is unsecured. +``` + +Anyone on the LAN who can reach `192.168.100.50:4096` can currently create files and run shell commands on this machine through the web UI — there's no login. Recommended next step: set `OPENCODE_SERVER_PASSWORD` (check `opencode web --help` / docs for the exact env var and how OpenCode expects it to be supplied) before treating this as anything beyond a trusted-home-network convenience. Do not port-forward this port to the public internet. **Still open as of 2026-09-19.** + +--- + +## Ollama Version History and Current Pin (2026-09-19) + +| Step | Version | What happened | +|---|---|---| +| Original | **v0.17.5** | Pinned on 2026-09-14 to avoid the qwen3.5 tool-call bug. Worked, but `ollama pull qwen3.6:35b-a3b` failed with a **412 "requires a newer version of Ollama"** error. | +| Upgrade | **v0.34.2** | Installed via the plain install script. Existing models were all kept (the update does not touch model files). | +| Problem 1 | v0.34.2 | First model run showed **100% CPU** — newer Ollama treats integrated GPUs as opt-in. Fixed with `OLLAMA_IGPU_ENABLE=1` (see systemd config). After that, discovery logged `library=Vulkan ... AMD Radeon 780M Graphics (RADV PHOENIX)`. | +| Problem 2 | v0.34.2 | Models of ~17 GB and larger (`qwen3-coder:30b`, `GLM-4.7-Flash`, `qwen3.6:27b`, `qwen3.6:35b-a3b`) crashed on load with `radv/amdgpu: Not enough memory for command submission` / `vk::Queue::submit: ErrorDeviceLost`, at any context size. Both `qwen3-coder:30b` and `GLM-4.7-Flash` had loaded fine on v0.17.5. Ruled out the KV-cache setting as the cause by removing it and retesting (still crashed). | +| Downgrade | **v0.32.9** | Pinned to the last version reported working in an upstream bug report (below). **All models loaded**, including the four that crashed on v0.34.2. **This is the current pin.** | + +### Upstream bug reports matching this failure + +- **ollama/ollama #17748** — "AMD Radeon 780M Vulkan regression in Ollama >=0.32.10": larger models fail on a 780M with the same error text; downgrading to 0.32.9 with the same hardware/model/config restores it; small models keep working on the GPU. The reporter's env vars match this machine's (Vulkan, iGPU enable, flash attention, q8_0 KV cache). +- **ollama/ollama #18272** — related report on an AMD iGPU with a very large model; says the failure appeared from v0.32.12 and suggests the newer llama.cpp Vulkan backend changed memory allocation on iGPUs. +- **ggml-org/llama.cpp #27360** — on a Radeon 680M, a change to the default iGPU model-loading path looks like a possible cause; adding `--load-mode mmap` fixed it there. **Unconfirmed upstream, and it is not known whether Ollama exposes an equivalent setting.** Watch these threads for a fix in a newer Ollama release. + +### Current pin — how to install/re-install the correct version + +```bash +curl -fsSL https://ollama.com/install.sh | OLLAMA_VERSION=0.32.9 sh +``` + +> ⚠️ **Do NOT re-run the plain `curl ... | sh` install script without the +> `OLLAMA_VERSION=0.32.9` prefix** — it installs the latest version and +> brings the Vulkan regression back. The installer also always downloads +> ROCm libraries and prints "AMD GPU ready"; that message is misleading on +> this machine (gfx1103 is unsupported by ROCm — Vulkan is what actually +> runs). + +Verify after any install: + +```bash +ollama --version # expect 0.32.9 +ollama list # all models still present +systemctl show ollama -p Environment --no-pager | tr ' ' '\n' | grep -i -E "kv_cache|context|igpu|vulkan" +ollama run gpt-oss:20b "say hi" && ollama ps # expect 100% GPU +``` + +--- + +## Ollama systemd Configuration + +Ollama runs as a systemd service. Environment settings live in drop-in files +in `/etc/systemd/system/ollama.service.d/`. Systemd applies drop-ins in +**filename order** and a later file overrides an earlier one for the same +variable. + +| File | Contents | +|---|---| +| `context.conf` | `OLLAMA_CONTEXT_LENGTH=32768` | +| `vulkan.conf` | `OLLAMA_VULKAN=1`, `GGML_VK_VISIBLE_DEVICES=0`, `LD_LIBRARY_PATH=/usr/local/lib/ollama/vulkan:/usr/local/lib/ollama`, `OLLAMA_FLASH_ATTENTION=1`, `OLLAMA_KEEP_ALIVE=10m` | +| `override.conf` | `OLLAMA_IGPU_ENABLE=1` (added 2026-09-19 — required on newer Ollama, which treats iGPUs as opt-in) | +| `kvcache.conf` | `OLLAMA_KV_CACHE_TYPE=q8_0` (added 2026-09-19 — roughly halves KV-cache memory; requires flash attention, already on) | + +Other facts confirmed from the server config log: Ollama listens on +`127.0.0.1:11434`; models are stored at `/usr/share/ollama/.ollama/models`; +`OLLAMA_NUM_PARALLEL` is 1. + +### Duplicate context-length bug (fixed 2026-09-19) + +`vulkan.conf` originally also contained `Environment="OLLAMA_CONTEXT_LENGTH=16384"`. +Because `vulkan.conf` loads after `context.conf`, the **effective context was +16384**, not 32768 — meaning all earlier model tests ran at 16K, not 32K. +Fixed by deleting that line from `vulkan.conf`: + +```bash +sudo sed -i '/OLLAMA_CONTEXT_LENGTH/d' /etc/systemd/system/ollama.service.d/vulkan.conf +sudo systemctl daemon-reload && sudo systemctl restart ollama +``` + +Effective value is now confirmed 32768. To check any time: + +```bash +systemctl show ollama -p Environment --no-pager | tr ' ' '\n' | grep -i context +``` + +`ollama ps` also shows the context per loaded model. Note that the OpenCode +path goes through Ollama's OpenAI-compatible endpoint, so it uses this +**global** setting — a per-request `num_ctx` override only works when calling +Ollama's native API directly (used for the tests below). + +### Reading `ollama ps` + +`PROCESSOR` shows the GPU/CPU split. `100% GPU` = fully on the iGPU. A split +like `15%/85% CPU/GPU` means part of the model is in system memory (slower). +Blank output right after a request means the load failed — check +`journalctl -u ollama --no-pager --since "10 minutes ago"`. + +--- + +## Backup and Restore Script — `~/ollama-safe.sh` + +Created 2026-09-19 so an Ollama update can be undone quickly. It backs up the +Ollama **binary, bundled libraries (including the Vulkan libs), systemd unit +and drop-ins, and the model list** — but **not the model files themselves** +(a version change does not touch them, and they are many GB). + +```bash +~/ollama-safe.sh backup # snapshot the current state (do this BEFORE any update) +~/ollama-safe.sh list # show existing backups +~/ollama-safe.sh restore # restore the NEWEST backup (by name) +~/ollama-safe.sh restore <backup-dir> # restore a specific backup +``` + +- Backups go to `~/ollama-backups/<timestamp>-v<version>/`. +- Each backup is ~3.9 GB (mostly `lib.tgz`, the bundled GPU libraries) and + asks for `sudo`. +- **Gotcha:** plain `restore` uses the *newest* backup, which is usually the + state you are trying to get away from. To go back to a specific version, + pass its directory explicitly. +- The script file needed `sudo chown $USER:$USER ~/ollama-safe.sh` + `chmod +x` + after creation because it was originally created root-owned. +- It saves `manifests.tgz` only if models are in a standard location; here the + models path did not match its defaults, so that file is absent from backups + (harmless — model files are not touched by version changes). + +### Existing backups (as of 2026-09-19) + +| Backup directory | Contains | Use | +|---|---|---| +| `20260918-233357-v0.17.5` | Original working state | Full rollback to the original v0.17.5 setup (note: `qwen3.6` cannot be pulled/run on it) | +| `20260919-202238-v0.34.2` | v0.34.2 with context fix applied | Only needed to return to v0.34.2 | +| `20260919-204850-v0.34.2` | v0.34.2 with context fix + KV cache config | Only needed to return to v0.34.2 | +| `20260919-205838-v0.32.9` | **Current working state** — v0.32.9 with all settings (context 32768, KV cache q8_0, iGPU enable, Vulkan) | **The one to restore to if a future change breaks things** | + +The two v0.34.2 backups can be deleted to reclaim ~8 GB once v0.32.9 has +proven itself (`rm -rf ~/ollama-backups/20260919-202238-v0.34.2 +~/ollama-backups/20260919-204850-v0.34.2`). Keep the v0.17.5 backup as the +original known-good state until the 7-test round is finished. + +To return to the original v0.17.5 setup: + +```bash +~/ollama-safe.sh restore ~/ollama-backups/20260918-233357-v0.17.5 +``` + +--- + +## Model Findings + +### Memory rules of thumb (this machine) + +- Usable GPU memory ≈ **16.3 GiB**. Weights **plus** KV cache must fit. +- Context size drives KV-cache size. With `OLLAMA_KV_CACHE_TYPE=q8_0` the + cache is roughly half the size. +- `devstral:24b` (14 GB weights) measurements on v0.34.2 to find the limit: + + | KV cache | Context | Result | + |---|---|---| + | default | 8192 | 15 GB loaded, 100% GPU | + | default | 16384 | 17 GB, 5% CPU / 95% GPU | + | default | 24576 | **crash** (out of memory) | + | q8_0 | 24576 | 16 GB, 100% GPU | + | q8_0 | 32768 | 17 GB, 5% CPU / 95% GPU | + +- On v0.34.2, models that don't fit crash instead of splitting gracefully. + On v0.32.9 the split works (below). + +### Current results on v0.32.9 (load test, `num_ctx=16384`, prompt "say hi") + +| Model | Loaded size | Processor | +|---|---|---| +| `qwen3-coder:30b` | 19 GB | 15% CPU / 85% GPU | +| `qwen3.6:35b-a3b` | 22 GB | 30% CPU / 70% GPU | +| `qwen3.6:27b` | 18 GB | 17% CPU / 83% GPU | +| `devstral:24b` | 15 GB | 100% GPU | +| `gpt-oss:20b` | 12 GB | 100% GPU | + +`gpt-oss:20b` also loaded at the global 32768 context on v0.34.2 with +100% GPU. **Not yet tested on v0.32.9 at 32768 for the larger models — open +item.** The qwen3.6 and gpt-oss models return "thinking" output, so replies +take longer than raw token speed suggests. + +### Original 7-test results (on v0.17.5, effective context 16384) + +Only **`gpt-oss:20b`** came close to completing all 7 tests. The goal is a +model that codes reliably and completes assigned work. + +| Model | Pulled | Size | Time | +|---|---|---|---| +| qwen2.5-coder:7b | Y | 4.7 GB | 0m 2.4s | +| qwen2.5-coder:14b | Y | 9.0 GB | 1m 40s | +| ministral-3:14b | Y | 9.1 GB | 1m 36s | +| gpt-oss:20b | Y | 13 GB | 0m 39.9s | +| devstral:24b | removed at the time | 14 GB | n/a | +| qwen3-coder:30b | Y | 18 GB | 1m 20s | +| GLM-4.7-Flash | Y | 19 GB | 0m 24s | +| qwen2.5-coder:32b | Y | 20 GB | ERROR | + +Working theory (not proven): the `qwen2.5-coder` models are built for +fill-in-the-middle autocomplete rather than the read-file / edit-file tool +loop an agent runs, which is why they struggle in OpenCode. + +### Models currently pulled + +`qwen3.6:27b`, `qwen3.6:35b-a3b`, `devstral:24b`, `granite-code:20b-instruct`, +`qwen2.5-coder:32b`, `ministral-3:14b`, `GLM-4.7-Flash`, `gpt-oss:20b`, +`qwen2.5-coder:14b`, `qwen2.5-coder:7b`, `qwen2.5:7b`, `qwen3.5:27b`, +`qwen2.5:14b`, `qwen3-coder:30b`, `qwen3.5:9b`. + +### Next round of testing (not yet done) + +Run the 7 tests in the OpenCode web UI on v0.32.9, in this order, and record +time + pass/fail + what broke: + +1. `devstral:24b` (only local coder with a published agentic benchmark — 46.8% SWE-Bench Verified per a third-party guide; 100% GPU) +2. `qwen3.6:27b` +3. `qwen3.6:35b-a3b` (MoE, ~3B active parameters — expected to tolerate the CPU spill best) +4. `gpt-oss:20b` as the baseline +5. One file-creation task with `qwen3.5:9b` to check whether the original tool-calling bug (the reason for the v0.17.5 pin) still exists on v0.32.9 + +--- + +## Kilo Code Evaluation (2026-09-19) — Tried and Removed + +Kilo Code was tried as a more polished alternative to OpenCode's web UI. +Summary of what was learned (nothing from Kilo remains installed): + +- Kilo's CLI is built on the OpenCode codebase, so its engine is similar. +- Installed via npm after fixing a global-install permission error by giving + npm a user-owned prefix: `npm config set prefix ~/.npm-global` with + `~/.npm-global/bin` added to PATH in `~/.bashrc`. **That npm prefix change + is still in place and is harmless** — future `npm install -g` works without sudo. +- Version 7.7.5 had **no `kilo web` command** (`kilo web` was misread as a + project folder). The only browser UI was **`kilo console`**, which is + marked deprecated ("will be removed in a future release"). The server + returned pages correctly (verified with `curl`), but the console did not + work in the browser (blank page after sign-in), so it was abandoned. +- Removed with `kilo daemon stop`, `kilo uninstall`, and + `npm uninstall -g @kilocode/cli`, then verified with `pgrep`, `which`, and + `ss` (nothing left). +- Options identified but **not tried**: running the Kilo VS Code extension + inside `code-server` (a locally hosted browser IDE), or OpenHands' + Agent Canvas. OpenCode's web UI was kept as the daily driver. + +--- + +## Current Known-Good State (2026-09-19) + +- **Ollama:** v0.32.9 (pinned — do not run the plain installer). +- **Backend:** Vulkan (RADV) on the Radeon 780M, ~16.3 GiB usable. +- **Effective settings:** context 32768, KV cache q8_0, flash attention on, + keep-alive 10 min, iGPU enabled. +- **Verified loading:** `qwen3-coder:30b`, `qwen3.6:35b-a3b`, `qwen3.6:27b`, + `devstral:24b`, `gpt-oss:20b` (at 16384 on v0.32.9). +- **Agent front end:** OpenCode v1.18.31, web UI on port 4096 (still no + server password). +- **Rollback tool:** `~/ollama-safe.sh` (see above). + +## Open Items + +1. Run the 7 tests on `devstral:24b`, `qwen3.6:27b`, `qwen3.6:35b-a3b` and record results (see "Next round of testing"). +2. Retest `qwen3.5:9b` tool calling on v0.32.9 (the original reason for the v0.17.5 pin). +3. Verify the larger models load at the global 32768 context on v0.32.9 (only tested at 16384); lower the global context if they crash. +4. Watch ollama/ollama #17748 and #18272 for a fix before moving past v0.32.9. +5. Set `OPENCODE_SERVER_PASSWORD` for the OpenCode web UI (still unset). +6. Other project docs (`network_index.md`, `vlan1_infrastructure.md`) still describe Ollama as "pinned to v0.17.5" — update to v0.32.9 when convenient. + +*(Done 2026-09-19: v0.32.9 state backed up as `20260919-205838-v0.32.9`.)* + +--- + +## 🧠 Summary for AI Systems + +- KingDezigns-AI-001 is a local AI coding workstation on VLAN 1 (192.168.100.50/.51): Ryzen 7 8845HS, Radeon 780M iGPU (Vulkan, not ROCm), ~29.6 GB unified RAM, of which ~16.3 GiB is usable by the GPU. +- **Ollama is pinned to v0.32.9** (was v0.17.5 originally; briefly v0.34.2). v0.32.10+ has a Vulkan regression on 780M-class iGPUs that crashes models above ~16 GB with `radv/amdgpu: Not enough memory for command submission` / `ErrorDeviceLost` (ollama/ollama #17748, #18272). Never run the unpinned installer: use `curl -fsSL https://ollama.com/install.sh | OLLAMA_VERSION=0.32.9 sh`. +- The installer always fetches ROCm libs and prints "AMD GPU ready" — misleading here; Vulkan is what runs. +- Config lives in `/etc/systemd/system/ollama.service.d/`: `context.conf` (32768), `vulkan.conf`, `override.conf` (`OLLAMA_IGPU_ENABLE=1`), `kvcache.conf` (`OLLAMA_KV_CACHE_TYPE=q8_0`). Drop-ins load in filename order and later files win — a duplicate `OLLAMA_CONTEXT_LENGTH=16384` in `vulkan.conf` had been silently overriding 32768 and was removed. +- `~/ollama-safe.sh backup|restore|list` snapshots/restores the Ollama binary, libs, and systemd config (not models). Plain `restore` uses the newest backup; pass a directory to target a specific one. Take a backup before any Ollama change. +- Models that fit fully on the GPU: ≤ ~15 GB (`gpt-oss:20b`, `devstral:24b`). Larger models (`qwen3-coder:30b`, `qwen3.6:27b`, `qwen3.6:35b-a3b`) run with a CPU/GPU split on v0.32.9. +- Only `gpt-oss:20b` came close to passing all 7 agent tests so far (run on v0.17.5 at effective 16K context); `devstral:24b`, `qwen3.6:27b`, `qwen3.6:35b-a3b` are the next candidates and are untested on the 7-test suite. +- OpenCode's web UI (port 4096) still has no server password; Ollama stays loopback-only. Kilo Code was trialed and removed — nothing left installed. +- Not to be confused with **KingDezigns001**, the separate VLAN 20 admin workstation. + +--- + +# ✔️ End of File diff --git a/network_index.md b/network_index.md index a319372..9d1d6e4 100644 --- a/network_index.md +++ b/network_index.md @@ -1,212 +1,329 @@ # KingDezigns Network Documentation Index -Last Updated: 2026-08-19 -This index provides a structured overview of all VLANs, servers, and firewall policies in the KingDezigns network. -Each section links to its own dedicated Markdown file for clarity and modularity. +Last Updated: 2026-10-11 ---- +This index provides a structured overview of the KingDezigns network, +including VLANs, servers, firewall/security architecture, and hosted +applications. + +------------------------------------------------------------------------ # 📁 VLAN Documentation ## 🔧 Core VLANs -- [VLAN 1 — Infrastructure](vlan1_infrastructure.md) -- [VLAN 10 — Management](vlan10_management.md) + +- [VLAN 1 --- Infrastructure](vlan1_infrastructure.md) +- [VLAN 10 --- Management](vlan10_management.md) ## 🧑‍💻 Trusted User VLANs -- [VLAN 20 — Trusted Devices](vlan20_trusted.md) + +- [VLAN 20 --- Trusted Devices](vlan20_trusted.md) ## 🏠 Smart Home & Guest VLANs -- [VLAN 30 — IoT](vlan30_iot.md) -- [VLAN 40 — Guest](vlan40_guest.md) + +- [VLAN 30 --- IoT](vlan30_iot.md) +- [VLAN 40 --- Guest](vlan40_guest.md) ## 🧪 Server & Lab VLAN -- [VLAN 50 — Lab / Servers](vlan50_lab.md) ---- +- [VLAN 50 --- Lab / Servers](vlan50_lab.md) + +------------------------------------------------------------------------ # 🖥️ Server Documentation ## Core Services -- [Home Assistant Server](server_homeassistant.md) -- [NAS08 — Pi-hole, Nextcloud (+ ONLYOFFICE/Collabora), Vaultwarden, STOCKPROXY](server_nas08.md) -- [NAS16 — LAMP Stack, MariaDB, Webmin, Forgejo, Fund Tracker](server_nas16.md) -- [PLEX32 — Plex Media Server + Tautulli](server_plex32.md) -- [Forgejo — Self-Hosted Git Server (hosted on NAS16)](server_forgejo.md) -- [Fund Tracker — Multi-Profile Mutual Fund/Stock Tracking (hosted on NAS16)](server_fundtracker.md) + +- [Home Assistant Server](server_homeassistant.md) +- [NAS08 --- Pi-hole, Nextcloud, Office, Vaultwarden, + STOCKPROXY](server_nas08.md) +- [NAS16 --- LAMP Stack, MariaDB, Webmin, Forgejo, Fund Tracker, Debt + Eliminator, Umami](server_nas16.md) +- [PLEX32 --- Plex Media Server + Tautulli](server_plex32.md) +- [Forgejo --- Self-Hosted Git Server](server_forgejo.md) +- [Fund Tracker --- Multi-Profile Mutual Fund/Stock + Tracking](server_fundtracker.md) +- [Debt Eliminator / CutTheCard --- Personal Debt + Tracking](server_debteliminator.md) +- [CutTheCard Subscription Model --- transition plan](debteliminator_subscription_model.md) +- [Umami --- Self-Hosted Web Analytics](server_umami.md) + +## AI / Development Workstations + +- [KingDezigns-AI-001 --- OpenCode + Ollama Local AI Coding + Agent](kingdezigns-ai-001-summary.md) ## Network Hardware -- [UCG Gateway Max](server_ucg.md) ---- +- [UCG Gateway Max](server_ucg.md) + +------------------------------------------------------------------------ # 🔥 Firewall Policies -- [Firewall Policies Overview](firewall_policies.md) +- [Firewall Policies Overview](firewall_policies.md) ---- +Firewall rules themselves remain documented centrally in +`firewall_policies.md`. Service documentation should describe required +connectivity but should not duplicate the authoritative firewall rule +definitions. + +------------------------------------------------------------------------ # 🛡️ Security Stack ## Intrusion Prevention -- **CrowdSec** — installed on HAS as a native HA add-on - - Agent reads NPM, HA, and SSH logs via journald - - 60 active detection scenarios - - Community blocklist updates every 2 hours - - Firewall Bouncer enforces bans at nftables level - - Email alerts on every ban decision - - All LAN VLANs whitelisted — internal IPs can never be banned - - Applies automatically to every service proxied through NPM, including Forgejo and Fund Tracker — no per-service configuration needed - - See [Home Assistant Server](server_homeassistant.md) for full configuration details -## Perimeter Defense (per server) -- **Fail2Ban** — NAS16 (active), PLEX32 (active), NAS08 (recommended) - - `ignoreip` includes `192.168.150.0/24` to prevent HAS proxy IP from being banned - - Real IP forwarding configured on NAS16 (nginx + Apache) and NAS08 +- **CrowdSec** --- installed on Home Assistant Server as a native HA + add-on + - Agent reads NPM, HA, and SSH logs via journald + - Community blocklist updates every 2 hours + - Firewall Bouncer enforces bans at nftables level + - All LAN VLANs are whitelisted + - Applies automatically to NPM-proxied services, including + Forgejo, Fund Tracker, and Debt Eliminator + - See `server_homeassistant.md` + +## Perimeter Defense + +- **Fail2Ban** + - NAS16 active + - PLEX32 active + - NAS08 recommended + - Backend proxy IPs are protected from accidental bans + - Real IP forwarding is configured on NAS16 and NAS08 ## DNS-level Protection -- **Pi-hole** — NAS08 (192.168.150.35) - - Blocks ads, trackers, and malicious domains for all VLANs - - All VLANs forced to use Pi-hole via global firewall rule 20001 - - **Local DNS overrides required** for any internally-hosted service accessed by its public hostname from within the LAN (e.g. `cloud.kingdezigns.com` → `192.168.150.30`), to avoid NAT hairpin failures. See `server_nas08.md` ONLYOFFICE section for a documented example and fix. -## Application-level Auth (per service, where applicable) -- **Fund Tracker** — session-cookie auth (httponly, bcrypt-hashed passwords), account lockout after 5 failed attempts, forced password change on new/seeded accounts, versioned legal-document acceptance gating. See `server_fundtracker.md`. +- **Pi-hole** --- NAS08 (`192.168.150.35`) + - Network-wide DNS filtering + - All VLANs forced to Pi-hole through the documented firewall + policy + - Local DNS overrides are required when internal clients access an + internally hosted service through its public hostname ---- +## Application Authentication + +### Fund Tracker + +- Session-cookie authentication +- bcrypt password hashing +- Admin/user roles +- Versioned legal-document acceptance +- See `server_fundtracker.md` + +### Debt Eliminator / CutTheCard + +- Session-cookie authentication +- `HttpOnly`, `SameSite=Strict` cookies +- Secure cookies behind HTTPS +- bcrypt password hashing +- Five failed-login attempts → 15-minute lockout +- Disabled accounts blocked and active sessions invalidated +- Admin-managed accounts +- Versioned Terms of Use, Privacy Statement, and Affiliate Disclosure acceptance +- Self-service account suspend/unsuspend and two-step self-delete (v2.2.0) +- **Admin Roles v2** (per-permission admin access; Primary Admin + Supervisor can assign roles) +- **Household Sharing (v2.1.20):** owner invites another user by email as view/edit; members never see full account numbers, billing, profile or Budget; owner-visible activity log +- **Accessibility:** WCAG 2.2 AA is a release requirement - see `accessibility_standards.md` +- Searchable security/audit log +- AES-256-GCM account-number encryption +- Stripe-powered donations (one-time + recurring), public Support/Contact form, downloadable Records Archive export, and a public SEO/Learning Center — see `server_debteliminator.md` for detail +- **Domains — CONFIRMED (2026-09-15):** Production is now `https://www.cutthecard.net` (was `debt.kingdezigns.com`); QA is now `https://debt.qa.cutthecard.net` (was `debt.qa.kingdezigns.com`). NPM on HAS and Dreamhost DNS were both updated for both. `cutthecard.org` redirects to `cutthecard.net` at Dreamhost only, not in NPM. Both old `kingdezigns.com` hostnames are deprecated — see `server_debteliminator.md` §0a/§2a for the standing reminder to scrub remaining references +- **Blog Engine (2026-09-30):** public SEO articles at `/blog` (outside the paywall, crawlable, in `sitemap.xml`), each revision on its own URL, with Preview/Schedule/Publish/Archive/Unpublish and scheduled go-live; no new ingress, NPM or CrowdSec changes were needed +- **Admin → Revenue / Subscriptions (2026-09-30):** unified revenue ledger (`donations.payment_kind`), subscription summary tiles, per-user monthly/yearly amounts +- **Navigation regroup (2026-10-11):** sidebar is now task-based collapsible groups (Phase 1); see `server_debteliminator.md` §8b +- **Analytics loader (2026-10-02):** one `site-scripts.js` loader tag per page; Umami page-level analytics on public and app pages (admin never tracked) — see `server_debteliminator.md` §12h +- See `server_debteliminator.md` + +## Web Analytics + +### Umami (self-hosted) + +- `https://stats.cutthecard.net` — Docker on NAS16 (`192.168.150.40:3001`), proxied by NPM on HAS, Force SSL +- Cookie-free, first-party; no data sent to third parties +- Pi-hole local DNS override `stats.cutthecard.net` → `192.168.150.30` +- Tracks CutTheCard (public + app pages, page-level only, admin excluded) and the personal kingdezigns.com site +- Chosen over Google Analytics (privacy/trust) and Plausible (ClickHouse too heavy for a Pi) +- Default login must be changed on first login +- See `server_umami.md` + +------------------------------------------------------------------------ # 🌐 Network Architecture Overview -This documentation set is designed around: +The KingDezigns network is designed around: -- Clear segmentation -- Explicit inter-VLAN access -- Isolation of untrusted devices -- Preservation of Home Assistant functionality -- AI-friendly structure and formatting -- Layered security — DNS filtering, intrusion prevention, firewall enforcement +- Clear VLAN segmentation +- Explicit inter-VLAN access +- Isolation of untrusted devices +- Preservation of Home Assistant functionality +- AI-friendly documentation +- Layered security +- Single external ingress through NPM ## Security Layer Model -``` + +``` text Internet ↓ -UCG Max — firewall, VLAN segmentation, geo-blocking (future) +UCG Max — firewall / VLAN segmentation ↓ -CrowdSec Firewall Bouncer — nftables ban enforcement +CrowdSec Firewall Bouncer — nftables enforcement ↓ -NPM on HAS — single ingress, SSL termination +NPM on HAS — HTTPS termination / reverse proxy ↓ -CrowdSec Agent — log analysis, attack detection +Backend Services + ├── NAS08 + ├── NAS16 + └── PLEX32 ↓ -Backend Services (NAS08, NAS16, PLEX32) - ↓ -Fail2Ban — last-line brute force protection +Fail2Ban — backend brute-force protection ↑ -Pi-hole — DNS-level ad/tracker/malware blocking (all VLANs) +Pi-hole — DNS filtering ``` ---- +------------------------------------------------------------------------ # 🔑 SSH Key Authentication Map -SSH key authentication is configured between the following machines — no passwords required: +SSH key authentication is configured between the documented +administrative hosts and VLAN 50 servers. -| From | To | Purpose | -|------|----|---------| -| KingDezigns001 | PLEX32 (192.168.150.45) | Remote launcher script | -| KingDezigns001 | NAS08 (192.168.150.35) | Direct SSH access | -| KingDezigns001 | NAS16 (192.168.150.40) | Direct SSH access | -| PLEX32 | NAS08 (192.168.150.35) | Backup script disk stats via SSH | +Key type: ED25519. -Key type: ED25519. Keys generated per machine — not shared. +Keys are generated per machine and are not shared. ---- +------------------------------------------------------------------------ -# 🖥️ KingDezigns001 — Admin Workstation Tools +# 🖥️ KingDezigns001 --- Admin Workstation -KingDezigns001 is the primary Linux administrative workstation on VLAN 20 (Trusted). +KingDezigns001 is the primary Linux administrative workstation on VLAN +20. -## Remote Launcher -A menu-driven launcher script provides one-click access to run scripts on PLEX32: +It is the normal starting point for application deployments because +NAS16 has no browser. -- **Script:** `~/scripts/plex32_launcher.sh` -- **Desktop shortcut:** `~/Desktop/PLEX32-Launcher.desktop` -- **Terminal:** gnome-terminal +For Debt Eliminator: -### Menu Options -| Option | Runs on | Script | -|--------|---------|--------| -| 1) Update Check | PLEX32 | `/usr/scripts/plex32/plex32_update_check.sh` | -| 2) Health Report | PLEX32 | `/usr/scripts/plex32/plex32_health_report.sh` | -| 3) Plex32 Backup | PLEX32 | `/usr/scripts/plex32/plex32_backup.sh` | +``` text +KingDezigns001 ~/Downloads + ↓ +SCP → NAS16 ~/deploys/ (never /tmp) + ↓ +SSH → NAS16 + ↓ +sudo cp → QA + ↓ +sudo docker restart (or rebuild) QA container + ↓ +QA testing + ↓ +Dev Log Deploy to Prod (automated pipeline) + ↓ +Production verification +``` ---- +**Standing rule (mandatory, every time):** any reply that delivers files for +Debt Eliminator or Fund Tracker must *open* with the full SCP → `sudo cp` → +restart command block (real file names and paths, `sudo rm` for deleted files, +restart-vs-rebuild stated, verification lines) before explaining the change. +See `server_debteliminator.md` §3a-0 for the template. + +------------------------------------------------------------------------ + +# 🤖 KingDezigns-AI-001 --- Local AI Coding Workstation + +**Not to be confused with KingDezigns001 above** — similar name, different +machine, different VLAN. + +KingDezigns-AI-001 is a **GMKtec NucBox K8 Plus** (AMD Ryzen 7 8845HS, +Radeon 780M iGPU, ~29.6GB unified RAM, Linux Mint 22.3) running +**Ollama** (local LLM inference) and **OpenCode** (an AI coding agent), +so coding-agent work can run entirely on local hardware rather than a +cloud API. Static IP reservations: **192.168.100.50** and +**192.168.100.51** — VLAN 1 (Infrastructure). + +- Ollama is pinned to **v0.32.9** (since 2026-09-19; was v0.17.5 — newer + versions ≥ 0.32.10 have a Vulkan regression on this iGPU that crashes + models above ~16 GB; the original v0.17.5 pin was for a qwen3.5 + tool-calling bug, retest pending) and runs on its **Vulkan** + backend (Mesa RADV) rather than ROCm, since ROCm doesn't support this + iGPU (gfx1103). +- Ollama itself listens on `127.0.0.1:11434` only — **all model + inference stays local to this machine.** +- The OpenCode web UI (`opencode web`) was opened up to the LAN + (`--hostname 0.0.0.0`, port 4096, allowed through the host's `ufw`) so + it can be reached from other VLAN 1/20 devices, while Ollama itself + remains loopback-only — remote devices talk to OpenCode, which relays + to Ollama locally. +- **⚠️ Open security item:** as of the 2026-09-14 setup, the OpenCode + server has **no password configured** + (`OPENCODE_SERVER_PASSWORD` unset) — anyone who can reach + `192.168.100.50:4096` or `.51:4096` can create files and run shell + commands on this machine with no login. This is treated as acceptable + for a trusted home LAN for now, but **port 4096 must never be + port-forwarded to the internet**, and setting a server password is a + recommended follow-up. See `kingdezigns-ai-001-summary.md` for the + exact env var and setup detail once addressed. + +Full setup detail, the Ollama/OpenCode fixes applied, and the exact +network-exposure change are in +[kingdezigns-ai-001-summary.md](kingdezigns-ai-001-summary.md). + +------------------------------------------------------------------------ # 🧠 Notes for AI Systems -- **File update workflow (read this first):** When asked to "update" a project file, take the existing file, make the requested changes, and present the updated file for download — do not explain the read-only/re-upload mechanism unless something about the process itself is actually in question. The user re-uploads it to the Project themselves. No caveat, disclaimer, or explanation of Claude's file access model is needed before or after doing this — just do it. -- Each file is self-contained and structured consistently. -- Section headers follow a predictable pattern for easy parsing. -- No duplicated firewall rules — all rules live in `firewall_policies.md`. -- CrowdSec configuration lives entirely on HAS — see `server_homeassistant.md`. -- VLAN files contain: - - Purpose - - Access types - - Subnet - - Expected devices - - Security rules - - AI summary -- Plex Media Server migrated from NAS08 to PLEX32 (dedicated Dell Wyse 5070) on 2026-06-18 — see `server_plex32.md`. -- PLEX32 now runs Plex + Tautulli with Intel Quick Sync hardware transcoding — optimized 2026-06-20. -- KingDezigns001 has SSH keys to all VLAN 50 servers — passwordless access for all admin tasks. -- PLEX32 has SSH key to NAS08 — required for backup script to fetch disk stats. -- **NAS08 Nextcloud update check** runs daily at 7AM — `/usr/scripts/omv/nextcloud_update_check.sh` — emails HTML report with copy-paste `occ` commands. Never use the browser UI for Nextcloud app updates (causes Apache segfault → maintenance mode deadlock). -- **NAS08 Nextcloud update check — core-update false negative fixed (2026-07-25):** the script previously checked app updates only (`occ app:update`) and had no code path for Nextcloud core/server releases, so it silently missed a core update (34.0.1 → 34.0.2) and emailed a false "up to date" report. Fixed by adding a core check via `occ update:check`, correcting the emailed Compose commands to the real path (`/kingdezignsnas/Docker/Compose/nextcloud/`, root-only, non-default filenames requiring `-f nextcloud.yml -f compose.override.yml`), and fixing a bash quoting bug that made emailed multi-line commands unreadable. Also documented: the official Nextcloud Docker image auto-upgrades on container restart via its own entrypoint — checking version status immediately after `up -d` can race that process and show a stale version for ~30 seconds. Full detail in `server_nas08.md`. -- **NAS08 Nextcloud Office editing** uses ONLYOFFICE Document Server (free Community Edition) as of 2026-07-18. Only one Office integration app should ever be enabled at a time (exception: the Collabora trial below, run as a time-boxed disable/enable swap, never simultaneous). Requires a Pi-hole local DNS override for `cloud.kingdezigns.com`, `ALLOW_PRIVATE_IP_ADDRESS=true` on the container, and matching JWT secrets between Nextcloud and the container. Full details and troubleshooting history in `server_nas08.md`. -- **NAS08 Collabora Online trial (2026-07-21, ongoing):** A second Office editor, Collabora Online (CODE), was deployed as a standalone Docker container (`collabora`, its own OMV Compose project "Collabora Office") for a head-to-head reliability trial against ONLYOFFICE — triggered by confirmed ONLYOFFICE bugs (conditional formatting crashing on formula cells; silent reverts to hours-old document versions). Only one Office app is ever enabled in Nextcloud at a time — currently `richdocuments`/Collabora is enabled, `onlyoffice` is disabled but still installed for easy rollback. Public URL `https://collabora.kingdezigns.com/`, requires its own Pi-hole local DNS override and a WOPI allow-list (`192.168.150.35`). First real-document test succeeded with a notably fast load time. Full config, setup troubleshooting, and rollback steps in `server_nas08.md`. -- **NAS08 Collabora stock/fund price macro integration (2026-07-22, working):** The ONLYOFFICE `FUNDPRICE`/`FUNDPRICE_HIST`/`STOCKPRICE`/`STOCKTIME` custom functions were ported to Collabora as a LibreOffice Basic module (`StockFunctions.bas`), calling the same STOCKPROXY backend with no backend changes required. Two `coolwsd.xml` server-config changes were required — macro execution enabling and a `net.lok_allow` hostname allowlist entry for `stocks.kingdezigns.com` — plus a fix to the previously non-functional `stocks.kingdezigns.com` Pi-hole DNS override. Confirmed working with a live price pull as of 2026-07-22. Full troubleshooting detail, exact config edits, and remaining follow-up items (recreating the full ~50-fund table, conditional-formatting re-test, recalc performance) in `server_nas08.md`. -- **NAS08 systemd-resolved DNS bug** (fixed 2026-07-18): a stray global `DNS=` override in `/etc/systemd/resolved.conf` caused duplicate/incorrect DNS answers for internal hostnames network-wide on that host. Any future "works from browser but fails from a container/script on NAS08" symptom should check `resolvectl status` for stray global DNS servers first. -- **NAS08 STOCKPROXY service (2026-07-21):** Self-hosted Flask API, Docker container `stockproxy` (`~/docker/stockproxy/`), port 5005, public URL `https://stocks.kingdezigns.com/` proxied via NPM on HAS (see Proxy Hosts table in `server_homeassistant.md`). Supplies current + historical mutual fund prices to ONLYOFFICE custom functions (`FUNDPRICE`, `FUNDPRICE_HIST`) via Yahoo Finance, scraped server-side to dodge the browser CORS block that rules out calling Yahoo directly from a spreadsheet macro. Finnhub was evaluated first but dropped from this service — confirmed no mutual fund NAV coverage on the free tier. Current-price cache: 15 min in-memory. Historical-price cache: permanent, SQLite. All endpoints require a shared-secret `key` param (Vaultwarden). Built to support the "HSA Investiments Choices" tab in `Rufus Retirement Account Tracking 2026.xlsx`. `stocks.kingdezigns.com` A record added to the daily Dreamhost DDNS refresh script. Full config and known limitations in `server_nas08.md`. -- **NAS08 RANK.EQ Err:522 circular reference fix (2026-07-23, working):** The - "HSA Investiments Choices" fund-ranking formula broke with a circular-reference error on - any sheet edit (worked fine on load) because it depended on ~50 cells fed by live - `FUNDPRICE`/`FUNDPRICE_HIST` network calls. Fixed with a button-triggered LibreOffice - Basic macro that snapshots the live price columns into static value-only columns via - `setDataArray()`, with percent-change and rank formulas rebuilt to read from the static - snapshot instead of the live columns. Full root-cause analysis and macro in - `server_nas08.md`. -- **NAS08 Collabora Finnhub removal (2026-07-23, working):** `STOCKPRICE`/`STOCKTIME` - (Finnhub-backed equity functions) errored due to a missing `net.lok_allow` entry for - Finnhub. Instead of allowlisting Finnhub, it was removed entirely — `FUNDPRICE` (STOCKPROXY) - now covers equity tickers too, and a new `FUNDTIME` function replaces `STOCKTIME`, returning - STOCKPROXY's `resolved_date` (date only, not a time-of-day timestamp — accepted tradeoff). - No `coolwsd.xml` changes required. Full detail in `server_nas08.md`. -- **Synaplan AI integration** (added 2026-07-18, not yet functional): Nextcloud connector app installed, but the required self-hosted Synaplan backend stack (PHP/MariaDB/Qdrant/optional Ollama) has not been deployed. Treat as a future project, not a bug — see `server_nas08.md` for details before troubleshooting. -- **Forgejo self-hosted Git server** (added 2026-07-26): Deployed on NAS16 (192.168.150.40) via Docker Compose — chosen over Gitea for non-profit/community governance (Codeberg e.V.). Public web UI at `https://forgejo.kingdezigns.com/` (proxied via NPM on HAS), SSH git access on port 2222 (LAN-only, no external port-forward). Provides version control with in-browser file editing/history for the `07 - Projects` folder on NAS16's share, organized as one Forgejo org per host (`NAS08`, `NAS16`, `PLEX32`) with a `<hostname>-scripts` repo in each. Data (`/opt/forgejo/data`) folded into the existing `nas16-backup.sh` job. A companion `forgejo_autosync.sh` script (not yet scheduled as of this writing) auto-commits/pushes any uncommitted changes on a timer as a safety net alongside normal manual commits. Full setup, config, and troubleshooting history in `server_forgejo.md`. -- **Fund Tracker multi-profile mutual fund/stock tracker** (added 2026-08-17): Deployed on NAS16 (192.168.150.40) via Docker Compose — FastAPI + PostgreSQL, containers `fundtracker_api`/`fundtracker_db`. Public web UI at `https://funds.kingdezigns.com/` (proxied via NPM on HAS, Force SSL). Core design: security data (ticker, price history, group classification) is shared across all profiles and synced once regardless of how many profiles track it; each profile's holdings, cost basis, and watchlist membership are private. Scoring built from quality (risk-adjusted), opportunity (quality + genuine price dip, requires both a return z-score AND a drawdown-from-high to agree), combined (harmonic mean of quality+opportunity), and rebound (peer-relative "usually near the top of its group, currently collapsed" detector, reconstructed retroactively from existing price history) scores. Market data via `yfinance` + `curl_cffi` Chrome-impersonation session — required to avoid Yahoo Finance's bot-detection blocking, and a real fix (not a sandbox artifact). Session-cookie auth (httponly, bcrypt), admin role with anonymized cross-profile Census and versioned legal-document (Terms of Use + Investment Disclaimer) publishing — a version bump immediately requires every profile to re-accept. Daily sync + personalized-per-profile email report runs via an in-process APScheduler inside the container at 06:00 UTC, **not** an OMV Scheduled Job. Full architecture, scoring methodology, deployment pattern (code-only changes = folder swap + restart; dependency changes = rebuild; compose/env changes = `up -d`; structural DB migrations require a `pg_dump` backup first), and known-issue history in `server_fundtracker.md`. -- **Fund Tracker — Portfolio/transaction tracking system documented 2026-08-19** (built in an earlier session, previously undocumented in this project): a buy-lot/sale/split register sits alongside the scoring system — FIFO/LIFO/Specific-ID sale matching, split handling that only touches lots active before the split date, a `GET /portfolio/register` endpoint, and edit/delete with lock-on-sale-allocation protection (deleting the sale restores shares and unlocks the lot). Full endpoint list, data model, and known deployment gotchas now in `server_fundtracker.md`'s dedicated Portfolio section. -- **Fund Tracker Portfolio UI — three-level collapsible register (2026-08-19):** the Portfolio page now renders **Ticker (collapsed by default) → Buy Lot → Sale(s)**, instead of showing every buy lot for every ticker at once. Frontend-only change to `portfolio.html`; deployed via scp to a `/tmp` scratch path → `sudo cp` into the root-owned `/Kingdezignsnas16/fundtracker/` project dir → `sudo docker restart fundtracker_api` (no rebuild needed for a static-file-only change, consistent with the documented code-only deployment pattern). Full detail in `server_fundtracker.md`. +- **MANDATORY — deploy commands first:** whenever you hand the user files to deploy + (tarball, patch or single file), begin the reply with the exact SCP → `sudo cp` → + `sudo docker restart <container>` block, using real file names and paths, before any + description of the change. State restart-only vs rebuild. This applies every time, to + every revision, without being asked. Template: `server_debteliminator.md` §3a-0; + Fund Tracker equivalents: `server_fundtracker.md`. +- Treat the dedicated server documentation as authoritative for + service-specific configuration. +- `firewall_policies.md` is authoritative for firewall rules. +- Do not duplicate firewall rule definitions into service files. +- When updating a project file, preserve its existing organization and + terminology unless the project itself has changed. +- Debt Eliminator / CutTheCard is hosted on NAS16. +- Branded as **CutTheCard** in all UI. As of 2026-09-15, **confirmed**: + Production is `https://www.cutthecard.net` and QA is + `https://debt.qa.cutthecard.net` — NPM on HAS and Dreamhost DNS were + both updated to match, for both environments (not just the + application's own config). `cutthecard.org` redirects to + `cutthecard.net` at Dreamhost only, not in NPM. Both + `debt.kingdezigns.com` and `debt.qa.kingdezigns.com` are deprecated; + remaining references to either across the doc set/app are tracked as + a standing reminder in `server_debteliminator.md` §0a until fully + scrubbed. See `server_debteliminator.md` §2a for detail. +- Debt Eliminator has independent QA and Production environments from launch. +- Debt Eliminator Production is port 8002. +- Debt Eliminator QA is port 8003. +- NPM on HAS is the external ingress point. +- Debt Eliminator uses PostgreSQL, FastAPI, Python 3.12, and a vanilla HTML/JS/CSS frontend. +- Debt Eliminator's transaction register uses a recompute-from-scratch ledger. +- Charge-level interest rates and promotional APR (standard + deferred) are supported per transaction. +- 0% Balance Transfer strategy evaluates donor/receiver pairs in Avalanche order; `credit_limit` field limits recommended amount. +- The Debt Reduction Plan page (formerly Payoff Strategy) has a four-step progressive layout. +- Payment Register is a year-at-a-glance application page and supports a saved Payments-Only/All-Transactions preference. +- Debt Eliminator's My Account, Admin Accounts, and Help Center pages are current application functionality. +- Debt Eliminator's DevLog supports deployment instructions, attach-to-existing-version no-version projects, an automated QA → Production deploy pipeline (`deploy_engine.py`), per-item assignment/due-date/on-hold tracking with a weekly overdue-item alert email, and a permanent deployment-history table separate from the single-generation file backup. +- **2026-09-30:** DevLog is now **v2.1.3** (app source string still 1.10.1). New since 2026-09-15: Blog Engine with revisions/archive/scheduling, unified revenue ledger + Admin → Revenue page, Subscriptions admin tiles/per-user amounts; SitePay and Email Campaigns are in the code (summary-level in `server_debteliminator.md` §0b). The latest backup is `debteliminator-v2.1.3-backup-2026-09-30_08-47-16.tar.gz`. Standing reminder still open: `APP_SECRET_KEY` unset in Production + live Stripe keys in plaintext in the compose file. +- **Earlier — since the 2026-09-03 reconciliation (DevLog v2.0.19 / app source v1.10.1 at the time):** Stripe donations (one-time + recurring), a public Support/Contact request form, self-service account suspend/delete, a Privacy Statement + Affiliate Disclosure legal document (affiliate links themselves not yet live), a downloadable Records Archive (.xlsx/.docx) export, an SEO foundation with a public six-article Learning Center, and a dark/light theme. Full detail in `server_debteliminator.md`. +- **Version namespaces must be kept separate:** the 2026-09-15 Production backup is named **v2.0.19** because that is the latest deployed DevLog version, while the application source reports **v1.10.1** and shared frontend assets are **no longer on a single cache-marker value** — split between v1.8.3 and v1.8.4 depending on the page (see `server_debteliminator.md` §4.3). +- The dedicated Debt Eliminator backup covers Production application files and the Production PostgreSQL database; it does not include the independent QA database/project tree. +- Never document actual production passwords, SMTP passwords, database passwords, encryption keys, session secrets, Stripe keys, or other credentials. +- `APP_SECRET_KEY` should be explicitly configured in QA and Production before relying on encrypted account numbers — **still open as of 2026-09-15, now higher-priority** because live Stripe secret/publishable/webhook keys were also found stored in plaintext in the Production compose file. User has acknowledged and deferred this — tracked as a standing reminder (re-surface every ~5 days) in `server_debteliminator.md` §0a/§26. +- **KingDezigns-AI-001** (added 2026-09-14) is a local AI coding workstation on VLAN 1 (192.168.100.50/.51) running Ollama + OpenCode entirely on local hardware — not to be confused with **KingDezigns001**, the separate VLAN 20 admin workstation used for Debt Eliminator/Fund Tracker deployments. Model inference (Ollama) is loopback-only; the OpenCode web UI is exposed to the LAN on port 4096 with **no server password currently set** — a known, accepted-for-now risk on the trusted home LAN, but port 4096 must never be forwarded externally. See `kingdezigns-ai-001-summary.md`. +- **Umami analytics (added 2026-10-01):** self-hosted, cookie-free web analytics on NAS16 (`stats.cutthecard.net` → NPM → `192.168.150.40:3001`; containers `umami`, `umami_db`). Secrets live in `/opt/umami/umami.secrets` via `env_file` — OMV regenerates `umami.env` and wipes manual edits, so never rely on it. CutTheCard loads tracking through a single loader, `/dashboard/site-scripts.js` (add future scripts there, not on pages). See `server_umami.md` and `server_debteliminator.md` §12h. Open: confirm custom reading events in production, add Umami to `nas16-backup.sh`, disclose analytics in the Privacy Statement, confirm default admin password changed. ---- +------------------------------------------------------------------------ -# 📌 Future Expansion +- **2026-10-11 (Debt Eliminator):** DevLog is **v2.1.20** (seen in a **QA** backup, `debteliminator-v2_1_20-backup-2026-10-10_23-51-34.tar.gz` - not the usual Production-only archive). New since v2.1.7: Admin Roles v2, public Demo Calculator, Milestones, Windfall Allocator, CSV/Statement Import (nothing stored), accessibility layer, reminders, Credit Utilization, Budget-to-Payoff, blog auto-archive, **Household Sharing**. Sidebar regrouped into collapsible groups (Phase 1). Details in `server_debteliminator.md` §0d, §8b, §12i-12j; accessibility rules in `accessibility_standards.md`. Standing open item: `APP_SECRET_KEY` unset (also absent from QA compose) - overdue for a reminder. -Additional files may be added for: +- **2026-10-11 (Debt Eliminator, Home Page Swap):** the old About page is now the site home page ("Start Here") at `https://www.cutthecard.net/` (and `/index.html`); the `/` → `/dashboard/` redirect was removed; Accounts remains `/dashboard/index.html`; `/dashboard/about.html` 301s to `/`; sign-in from an entry page lands on `/`. Built against the v2.1.21 QA backup; package `home-page-swap-v2.1.22.tar.gz` delivered, QA deployment not yet confirmed. Detail in `server_debteliminator.md` §0e. +------------------------------------------------------------------------ -- Device inventories -- Application-specific firewall rules -- Backup and recovery procedures -- Monitoring and alerting configuration -- CrowdSec Console dashboard enrollment -- Geo-blocking configuration on UCG Max -- Authelia / forward authentication layer -- Expand remote launcher to cover NAS08 and NAS16 scripts -- **Synaplan self-hosted AI stack deployment** (PHP backend, MariaDB, Qdrant, optional Ollama) — scope resource requirements and deployment plan when ready -- **Collabora vs. ONLYOFFICE trial decision** (started 2026-07-21) — once a winner is chosen, update `server_nas08.md` and this index to reflect the final state (remove trial framing, decommission or keep the losing container, update firewall/NPM docs if the losing editor's proxy host is removed) -- **STOCKPROXY hardening** — not yet stress-tested at full ~50-ticker scale for Yahoo-side rate limiting; revisit if widespread simultaneous lookup failures are observed -- **Fund Tracker — pending feature work** (as of 2026-08-17, not yet built): self-service user account page (email update, relocated change-password), stronger primary-admin delete/demote protection, Eastern-time display throughout (currently UTC), always-visible logout control in the sidebar (currently inconsistent across pages per user report), confirmation of cookie/session behavior over the new HTTPS domain, fully-qualified-domain links everywhere (email + in-app) instead of the internal IP, public self-service signup with an admin on/off toggle and disclaimer acceptance, and open questions on geo-blocking / additional security hardening / anti-infiltration monitoring / PII collection policy. See the dedicated handoff summary provided at the end of the deployment conversation before starting this work. -- **Fund Tracker — pre-existing documentation gap fixed 2026-08-17:** the Forgejo proxy host (`192.168.150.40:3000`) was missing from `server_homeassistant.md`'s Current Proxy Hosts table despite Forgejo being deployed and documented since 2026-07-26 — added along with the new Fund Tracker entry. -- **Fund Tracker — Portfolio system testing ongoing (as of 2026-08-19):** the buy-lot/sale/split register is working but not yet exhaustively tested. Per the project's own handoff notes, remaining test cases include: purchases entered out of chronological order, sales entered against multiple lots, partial vs. complete sales, sale deletion, editing an unmatched lot, splits entered after transactions exist, reverse splits, purchases made after a historical split, lots fully sold before a split, and confirming one ticker's sales don't affect another ticker's lots. Continue from the current known-good state rather than rebuilding — see the Portfolio section of `server_fundtracker.md`. - ---- - -# ✔️ End of Index +# ✔️ End of File diff --git a/server_debteliminator.md b/server_debteliminator.md new file mode 100644 index 0000000..03acd28 --- /dev/null +++ b/server_debteliminator.md @@ -0,0 +1,1893 @@ +# Debt Eliminator / CutTheCard — Personal Debt Tracking Service + +Device Type: **Docker application hosted on NAS16**\ +Host: **NAS16 (`192.168.150.40`)**\ +VLAN: **50 --- Lab / Servers**\ +Documentation Updated: **2026-10-11** + +> **2026-10-11 (later) update:** Home Page Swap built against the **v2.1.21** QA backup +> (`debteliminator-v2_1_21-backup-2026-10-11_15-59-10`) - the new "Start Here" page now +> lives at `/`; see §0e. Package `home-page-swap-v2.1.22.tar.gz` was **delivered but its QA +> deployment had not been confirmed** at the time of writing. v2.1.21's own contents were +> not itemized. **§3a is a standing rule: every delivery of files must open with the SCP / cp / +> restart commands.** + +> **2026-10-11 update:** reconciled against the **QA** backup +> `debteliminator-v2_1_20-backup-2026-10-10_23-51-34.tar.gz` (DevLog +> **v2.1.20**, MANIFEST "Site Version v2.1.20"). **Scope note:** this +> archive is a **QA** backup (project source `/Kingdezignsnas16/debteliminator-qa`), +> not the usual Production-only backup, so Production's compose file and +> database were **not** inspected this round. Features added since v2.1.7 +> are documented at **summary level** from the code's own module docstrings +> and DevLog task titles (§0d, §12i-12j) - not line-by-line. The sidebar +> navigation was regrouped (§8b). +> +> **2026-09-30 update:** reconciled against the 2026-09-30 production +> backup `debteliminator-v2.1.3-backup-2026-09-30_08-47-16.tar.gz` +> (DevLog **v2.1.3**) plus the work designed/built in the following +> sessions (Blog Engine, blog scheduling, subscription admin tiles, unified +> Revenue ledger/page). See §0b for what changed. **Honest scope note:** the +> SitePay (subscriptions) and Email Campaign modules were first seen in +> this backup; §0b records what their source states (module docstrings, +> endpoints, file names) but they have **not** been reconciled line-by-line +> the way §1–§29 were for v2.0.19 — treat those two areas as summary-level +> until a dedicated pass is done. +> +> **Earlier source note (2026-09-15):** This document was reconciled against the +> 2026-09-15 production backup +> `debteliminator-v2.0.19-backup-2026-09-15_00-00-01.tar.gz`, the +> production PostgreSQL dump contained in that archive, and the prior +> KingDezigns project documentation (last reconciled at DevLog v2.0.3 / +> app source v1.9.5 on 2026-09-03). +> +> **This update covers a large amount of new ground** — the app has grown +> from a pure debt-tracking tool into a small public-facing product +> (CutTheCard.net) with donations, a support desk, SEO/educational +> content, and account self-service. See §0 for a fast summary of what +> changed since the last reconciliation. +> +> **Version distinction still applies and has drifted further:** the +> backup filename is now `v2.0.19` (latest deployed DevLog version). The +> application source (`main.py`) now reports **1.10.1**. The frontend +> shared-asset cache marker is **no longer a single consistent value** — +> see §25 for detail. Treat these as three independent identifiers, per +> the existing project convention. + +--- + +## 0. What Changed Since the Last Reconciliation (v2.0.3 → v2.0.19) + +This is the highest-level summary; full detail is in the sections below. + +- **Public rebrand to CutTheCard.net is now complete — confirmed, not + just observed, and covers both environments.** Production + `PUBLIC_BASE_URL` is `https://www.cutthecard.net`; QA moved to + `https://debt.qa.cutthecard.net`. The user has confirmed NPM on HAS and + Dreamhost DNS were both updated, for both hostnames. `cutthecard.org` + redirects to `cutthecard.net` at Dreamhost only (not in NPM). + `debt.kingdezigns.com` and `debt.qa.kingdezigns.com` are now deprecated + hostnames. See §2a and the reminder tracker in §0a — there are still + stray `debt.kingdezigns.com` references to clean up in this doc set and + in the app's own generated text. +- **Stripe donations** (one-time and recurring/subscription), with full + structured donation records, donor tracking on the User model, an + anonymous public donate page, and an admin Donations log. (§12a) +- **Support / Contact request form**, public-facing, with a 48-hour SLA, + admin request queue, and automatic confirmation emails. (§12b) +- **Self-service account suspension and deletion** — distinct from + admin-managed disable/delete. (§17a) +- **Privacy Statement** as a second, independently-versioned legal + document alongside Terms of Use, plus a new **Affiliate Disclosure** + view-only legal document (affiliate links themselves are not live yet + — see §12c). (§17b) +- **Records Archive** — downloadable year-end .xlsx/.docx exports, + grouped by account type and paid-off/delinquent status. (§13a) +- **SEO foundation + a public "Learning Center"** of six educational + articles, `robots.txt`/`sitemap.xml`, and an about/contact/donate page + set that's intentionally open to search crawlers while the app itself + stays gated. (§12d) +- **Dark/light theme**, per-user with an admin-set site default. (§8a) +- **Dev Log** gained assignment/due-date/on-hold fields with a weekly + overdue-item email digest, a permanent deployment history table + (separate from the single-generation file backup), and a + default-collapsed "last 5 releases" view. (§20) +- Application source version bumped **1.9.5 → 1.10.1**; DevLog deployed + version **v2.0.3 → v2.0.19** (17 releases). +- **Known issue is still open:** `APP_SECRET_KEY` is still not set in the + Production compose file. This is now more urgent — see §26. +- **New finding:** live Stripe secret keys are stored in plaintext in the + Production compose file, alongside the same issue. See §26. + +--- + +## 0a. ⏰ Standing Reminders — Open Follow-Up Items + +**Instructions for whoever (or whichever AI) reads this file next:** the +two items below are open, user-acknowledged action items, not just +observations. Re-surface them to the user under the stated cadence until +each is marked resolved or explicitly abandoned. Once an item is +resolved, delete its entry from this table (and, for the domain item, +strike the now-irrelevant reference-scrubbing note from §2a/§26 — it +won't be relevant any longer). + +| Item | First flagged | Remind | Status | +|---|---|---|---| +| **`APP_SECRET_KEY` unset in Production + live Stripe keys sitting in plaintext in `debteliminator.yml`.** User has acknowledged this and said "we will circle back to this." Re-remind every ~5 days (or the next time this file is read, if more than 5 days have passed) until fixed or explicitly abandoned. See §26 for the full recommendation. | 2026-09-15 | Every 5 days | 🔴 Open — **still unset as of the v2.1.3 backup (2026-09-30)**; **also absent from the QA compose file in the v2.1.20 backup (2026-10-10)**; Production not re-checked. 26 days since first flagged (2026-10-11) - overdue for a reminder | +| **Stray `debt.kingdezigns.com` / `debt.qa.kingdezigns.com` references need to be scrubbed and replaced with `cutthecard.net` / `debt.qa.cutthecard.net`** — both in this documentation set (now mostly done in this pass, see §2a) and in the application's own generated text (`routers/devlog.py`'s two hardcoded manual-recovery strings still reference the old Production hostname). Remind until confirmed fully clean, then remove this row and the related callouts in §2a/§26. **2026-09-30 update:** the v2.1.3 source no longer contains either old hostname in `routers/devlog.py` (verified by search; the only remaining `kingdezigns.com` string in app code is the legitimate Fund Tracker link in `main.py`). The remaining mentions in this doc set are intentional "deprecated" notes. Awaiting the user's confirmation that the doc set/NPM are clean, then delete this row. | 2026-09-15 | Until user confirms | 🟡 Code clean — awaiting confirmation | + +--- + +## 0b. What Changed Since 2026-09-15 (→ v2.1.3, 2026-09-30) + +**Built in these sessions (fully documented below):** +- **Blog Engine** with revisions, archive, preview and **scheduling** — §12f. +- **Unified revenue ledger** (`donations.payment_kind`), **Subscriptions + admin summary tiles + per-user monthly/yearly amounts + year selector**, + **Sync Payments from Stripe**, and a combined **Admin → Revenue** page — + §12g. +- Admin sidebar gained **Blog** and **Revenue** links. + +**Present in the v2.1.3 backup, summary-level only (not yet reconciled):** +- **SitePay / subscriptions** — `routers/subscribe.py` (real paid + subscription Checkout + Stripe Customer Portal: `GET /subscribe/status`, + `POST /subscribe/create-checkout-session`, `POST /subscribe/portal-session`), + `subscription_reconcile.py` (daily Stripe reconciliation + trial-ending + emails), `User.access_status` computed property, `static/subscribe.html`, + `static/billing-locked.html` (lockout page), admin + `GET /admin/billing/subscriptions`, reconciliation/migration endpoints + (`POST /admin/billing/reconcile-subscriptions`, + `/send-trial-ending-soon-emails`, `/migrate-onetime-donors`) and trial / + price / launch-date / enforcement settings on Admin → Subscriptions. + Plan and intent: `debteliminator_subscription_model.md`. +- **Email Campaigns** — `routers/campaigns.py` (admin; throttled, + per-recipient background sends, default 30 s apart, suppressed in QA, + `/test-send` for QA), `routers/email_prefs.py` (per-user preferences + + no-login one-click unsubscribe), `email_templates.py`, + `static/admin/campaigns.html`. +- DevLog production version is **v2.1.3** (was v2.0.19). + +**Version identifiers (unchanged convention):** DevLog deployment **v2.1.3**; +application source string still reads **1.10.1** in `main.py` (not bumped +despite the added modules) and the startup log line still says +`"Starting CutTheCard v1.9.2"`; frontend cache marker has moved to +`?v=1.8.5` on the pages touched in these sessions — re-verify all pages +share one marker at the next `shared.css`/`shared.js` change (§4.3/§25). + +--- + +## 0c. What Changed Since 2026-09-30 (→ v2.1.7 backup, 2026-10-01; analytics added 2026-10-02) + +- The 2026-10-01 backup (`debteliminator-v2.1.7-backup-2026-10-01_16-35-01.tar.gz`) + reports **DevLog v2.1.7**. Versions **v2.1.4 – v2.1.7** were deployed + between 2026-09-30 and 2026-10-01; their contents are **not itemized in + this document** (sections above were last reconciled at v2.1.3, and the + DevLog task titles for 2.1.4–2.1.7 were not reviewed). Reconcile when + convenient. +- **New:** site-wide script loader + Umami analytics (§12h). Changes are one + edit to `routers/blog.py` (`_page()` shell), two new static files, and one + loader tag added to 21 static pages. No new Python dependencies, no compose + changes, no new tables, no application version bump. +- **In flight (not documented here):** an external demo of the Debt Reduction + Plan flow was being built in QA at the same time. Any new demo pages need + the loader tag if they should be tracked. + +--- + +## 0d. What Changed Since 2026-10-02 (-> v2.1.20, 2026-10-10) + +DevLog versions **v2.1.8 - v2.1.20** shipped between 2026-10-02 and +2026-10-10 (titles below are from the DevLog task table in the QA database +dump). Application source string in `main.py` is **still `1.10.1`** and the +startup log still says `"Starting CutTheCard v1.9.2"` (neither bumped). + +| DevLog | Deployed | Task | +|---|---|---| +| 2.1.4 | 2026-09-30 | Integrated Blog Engine; HTML Builder; blog links on login/nav | +| 2.1.5 | 2026-09-30 | Combined donation + subscription modeling (revenue ledger, §12g) | +| 2.1.6 | 2026-09-30 | **Role Playing** - Admin Roles v2 (`routers/roles.py`, `roles`/`user_roles` tables) | +| 2.1.7 | 2026-10-01 | UI: Developer drop-down in DevLog project form | +| 2.1.8 | 2026-10-01 | **Demo Calculator** - public `/debt-payoff-calculator` (§12i) | +| 2.1.9 | 2026-10-02 | Umami analytics loader (§12h) | +| 2.1.10 | 2026-10-04 | Debt Reduction Plan - fine tuning #1 | +| 2.1.11 | 2026-10-05 | Triggering Balance Transfers | +| 2.1.12 | 2026-10-06 | **Milestones and Progress Dashboard** (§12i) | +| 2.1.13 | 2026-10-06 | Bug: monthly interest on the Accounts page | +| 2.1.14 | 2026-10-06 | **Windfall Allocator** (§12i) | +| 2.1.15 | 2026-10-10 | **CSV / Statement Import** (§12i) (+ a no-version bug fix) | +| 2.1.16 | 2026-10-09 | **ADA / WCAG 2.2 AA accessibility** layer - see `accessibility_standards.md` | +| 2.1.17 | 2026-10-10 | **Due-Date and Promo-Expiry Reminders** (§12i) | +| 2.1.18 | 2026-10-10 | **Credit Utilization Tracker** (§12i) | +| 2.1.19 | 2026-10-10 | **Budget-to-Payoff Cash Flow** (§12i) | +| 2.1.20 | 2026-10-11 | **Household Sharing** (§12j) | + +Also in this window (not DevLog versions): **blog auto-archive / rotating +archive picks** (`blog_rotation.py`, §12i) and the **sidebar navigation +Phase 1 regroup** (§8b - front-end only, built after the v2.1.19 backup; the +DevLog queue item "Nav grouping" is still `pending` in the QA database dump, +i.e. the work had not been logged/promoted yet). + +**Dates caveat:** the v2.1.15 / v2.1.16 deploy timestamps in the raw table +are not monotonic with their version numbers (v2.1.15 shows 2026-10-10 after +v2.1.16's 2026-10-09). Recorded as found. + +**Operational facts from the QA compose file (values never recorded):** +`APP_SECRET_KEY` is **not** set in the QA compose file either; the QA +compose file now contains a `STRIPE_SECRET_KEY` entry (earlier docs said +only Production had Stripe configured - see `debteliminator_subscription_model.md` +Phase 1). Whether those are test-mode keys was not checked. + +--- + +## 0e. Home Page Swap - "Start Here" at `/` (built 2026-10-11, package v2.1.22) + +**What changed** +- The old About page is now the **site home page**, titled **Start Here**, served at + **`https://www.cutthecard.net/`** (also answers at `/index.html`; canonical is `/`). + Source: `public_pages/home.html`, served by new `routers/home.py` (same pattern as the public + calculator page; `__BASE_URL__` / `__ROBOTS__` placeholders; `Cache-Control: no-cache`). + QA renders `noindex, nofollow`; Production `index, follow`. +- `GET /` **no longer redirects** to `/dashboard/` (the `root()` redirect was removed from `main.py`). +- The Accounts page is unchanged at **`/dashboard/index.html`** (`/dashboard/`). +- `/dashboard/about.html` is a **301 -> `/`** (query string preserved, e.g. `?suspended=1`), + registered *before* the `/dashboard` static mount so it wins even if a stale + `static/about.html` remains on disk. `static/about.html` was deleted from QA; **Production keeps + an orphan copy after the file-copy deploy** (harmless, the route takes precedence; clean up + whenever convenient). +- **Login landing:** `deDoLogin()` in `shared.js` sends the user to `/` after sign-in when they + signed in from an entry page (`/`, `/index.html`, `/dashboard/`, `/dashboard/index.html`, no query + string); on any other page (deep links) it reloads in place so the destination is kept. Logout now goes to `/`. +- **Nav:** logo click -> `/`; sidebar footer link renamed **About CutTheCard -> Start Here** + (`/`); onboarding-modal text updated; `DE_ACCESS_ALWAYS_ALLOWED` now lists `/` (so + expired/locked users can still reach Start Here); suspended-account redirect is `/?suspended=1`. +- **Page layout/copy:** hero cut to one heading ("Start here: your debt-free date in 3 steps") plus a + one-line summary (hero logo and tagline removed; the sidebar already shows the logo); **"3 Simple + Steps" moved above "How CutTheCard Helps You Win"** (steps + CTA are fully above the fold at + 1280x720); feature headings un-numbered so they don't clash with the numbered steps; section labels + are real `<h2>`, feature headings `<h3>`, emoji icons `aria-hidden`. CTA button: "Go to Accounts". +- **Links:** every "About" link in the blog shell (`routers/blog.py`), Learning Center, + calculator and accessibility pages now points at `/`. +- **SEO:** `sitemap.xml` lists `/` (priority 1.0) instead of `/dashboard/` and `about.html`; + `robots.txt` allows `/$` and `/index.html` instead of `about.html`; the Accounts page's + canonical now points at `/` (signed-out visitors see the same login screen at both URLs). +- **Cache marker:** `shared.js` changed, so `shared.css`/`shared.js` moved **`?v=1.9.5` -> + `?v=1.9.6`** on every app/public static page, including `household.html`, which was found still on + `1.9.4`. `blog.py` and `public_pages/debt-payoff-calculator.html` still reference `shared.css?v=1.9.2` + (no sidebar; unify at the next `shared.*` change). +- Files touched: new `routers/home.py`, `public_pages/home.html`; changed `main.py`, `seo_router.py`, + `shared.js`, `routers/blog.py`, `public_pages/debt-payoff-calculator.html`, `static/index.html`, + accessibility/learn pages and all pages carrying the cache marker; deleted `static/about.html`. + No new dependencies, tables or compose changes -> **restart-only** deploy. + +**Verified in a headless Chromium test (not on the live QA site):** `/` 200, `/index.html` 200, +`/dashboard/about.html?suspended=1` 301 -> `/?suspended=1`, QA vs Production robots meta, signed-in +dark/light/mobile and signed-out rendering. **Not run:** `a11y_audit.py`, the manual keyboard / +screen-reader pass (see `accessibility_standards.md` §4). + +--- + +## 1. Role & Purpose + +Debt Eliminator (branded as **CutTheCard**, now primarily presented at +**`https://www.cutthecard.net`**) is a self-hosted, per-user debt +tracking application for credit cards, auto loans, personal loans, +student loans, mortgages, medical debt, and other liabilities. It has +grown beyond an internal tool into a small public product with its own +donation/support/SEO surface, while remaining hosted on KingDezigns +infrastructure. + +The application provides: + +- Current debt balances, minimum/current payment tracking, due-day tracking +- Per-account payment/transaction history +- Charge-level interest rates and promotional APR tracking +- Debt-avalanche and snowball payoff projections; estimated debt-free date +- 0% Balance Transfer opportunity evaluation with promo balance protection +- Encrypted account-number storage +- User self-service account management, including **self-suspend and + self-delete** (new — §17a) +- Administrator account/security management +- Versioned **Terms of Use, Privacy Statement, and Affiliate Disclosure** (new — §17b) +- Security/audit logging +- A year-at-a-glance Payment Register +- A **Records Archive** downloadable year-end export (new — §13a) +- A Debt Reduction Plan page +- **Stripe-powered donations**, one-time and recurring (new — §12a) +- A **public Support/Contact request form** (new — §12b) +- A **public SEO/Learning Center content section** (new — §12d) +- **Dark/light theme** (new — §8a) +- A QA → Production Dev Log and automated deployment pipeline, now with + assignment/due-date tracking and permanent deployment history (§20) + +Debt Eliminator does **not** execute payments. Payments, charges, fees, +refunds, and balance corrections are entered manually and become ledger +transactions. + +--- + +## 2. Deployment / Environment Architecture + +Unchanged at the infrastructure level — Production and QA remain +independent environments on NAS16. + +| Item | Production | QA | +|---|---|---| +| Public URL | `https://www.cutthecard.net/` | `https://debt.qa.cutthecard.net/` | +| Internal URL | `http://192.168.150.40:8002/dashboard/` | `http://192.168.150.40:8003/dashboard/` | +| API container | `debteliminator_api` | `debteliminator_qa_api` | +| PostgreSQL container | `debteliminator_db` | `debteliminator_qa_db` | +| Host port | 8002 | 8003 | +| App port inside container | 8000 | 8000 | +| App source | `/Kingdezignsnas16/debteliminator/api/` | `/Kingdezignsnas16/debteliminator-qa/api/` | +| PostgreSQL data | `/opt/debteliminator/pgdata` | `/opt/debteliminator_qa/pgdata` | +| `APP_ENV` | `production` | `qa` | +| Email/scheduled behavior | Enabled | Suppressed | +| QA banner | No | Amber QA banner | +| Automated deploy pipeline | Not available | Available (see §20) | + +### 2a. Public domains — CONFIRMED: both Production and QA moved to `cutthecard.net` (2026-09-15) + +As of this backup, the Production compose file sets: + +```text +PUBLIC_BASE_URL=https://www.cutthecard.net +``` + +**Confirmed with the user (2026-09-15):** this is a deliberate, +completed rebrand covering **both environments**, not just an +in-progress application-side change to Production. + +- **Production:** NPM on HAS has been updated — the proxy host for this + service now serves `cutthecard.net` (and `www.cutthecard.net`) + directly, not `debt.kingdezigns.com`. +- **QA:** NPM has likewise been updated — the QA proxy host now serves + **`debt.qa.cutthecard.net`**, not `debt.qa.kingdezigns.com`. +- Dreamhost DNS has been updated to point both `cutthecard.net` and + `debt.qa.cutthecard.net` at the KingDezigns network. +- `cutthecard.org` still exists but is **not** configured in NPM — it + 302-redirects to `cutthecard.net` entirely at the Dreamhost DNS/domain + level, before traffic ever reaches the KingDezigns network. +- Both `debt.kingdezigns.com` (Production) and `debt.qa.kingdezigns.com` + (QA) are now **deprecated old hostnames**. Every remaining reference + to either in this documentation set (and in the application's own + generated text — see below) needs to be scrubbed and replaced with the + corresponding `cutthecard.net` hostname. + +Every outward-facing piece of the application already agrees with the +new Production domain: + +- All password-reset/support/donation-confirmation email links are built + from `PUBLIC_BASE_URL`. +- `robots.txt`/`sitemap.xml` default to `https://cutthecard.net` if the + env var is ever unset. +- Canonical/Open Graph tags on `about.html` and other public pages + hard-code `cutthecard.net`. +- Support inbox and no-reply addresses are `support@cutthecard.net` / + `noreply@cutthecard.net`. +- **No occurrence of `kingdezigns.com` remains in any static HTML page.** + +(QA's own `PUBLIC_BASE_URL` — presumably `https://debt.qa.cutthecard.net` +— is not visible in this backup, since this archive is Production-only +per §22. Worth a quick confirmation the next time QA's compose file is +touched, so QA's password-reset/email links agree with the new QA +hostname too.) + +**One inconsistency found — still needs a code fix:** `routers/devlog.py` +still generates manual-recovery/verification instructions referencing +`https://debt.kingdezigns.com` in two places. This is cosmetic (it only +affects text shown to an admin during a manual deployment fallback) but +is now confirmed stale, not just possibly stale. See the reminder tracker +in §0a. + +Traffic path (internal architecture unchanged): + +```text +Internet + ↓ +UCG Max + ↓ +Nginx Proxy Manager on HAS (192.168.150.30) + ├── cutthecard.net / www.cutthecard.net → 192.168.150.40:8002 (Production) + └── debt.qa.cutthecard.net → 192.168.150.40:8003 (QA) + ↓ +NAS16 + ├── :8002 → Debt Eliminator Production API + └── :8003 → Debt Eliminator QA API +``` + +`cutthecard.org` → `cutthecard.net` redirect happens entirely at +Dreamhost, upstream of NPM — it never appears in NPM's proxy host list +and has no KingDezigns-side configuration to document. + +### Site Branding & Alternate Domains + +The application is branded **CutTheCard** (FastAPI title and all page +`<title>` elements). **Current (2026-09-15) domain relationship:** +`cutthecard.net` (and `www.cutthecard.net`) is the primary, NPM-proxied +Production hostname; `debt.qa.cutthecard.net` is the equivalent for QA. +`cutthecard.org` 302-redirects to `cutthecard.net` at the Dreamhost DNS +level only — not in NPM. Both `debt.kingdezigns.com` and +`debt.qa.kingdezigns.com` are deprecated and should be scrubbed from +documentation and from the application's own generated text (see §0a). +Internal documentation continues to use "Debt Eliminator" as the service +name for infrastructure purposes. + +--- + +## 3. Deployment Policy — QA First, Then Automated Pipeline to Production + +### 3a-0. ⚠️ STANDING RULE — every delivery starts with the deploy commands (mandatory) + +Whenever Claude (or any AI) hands over files for this project — a tarball, a patch, a single +file — the **reply must open with the SCP / cp / restart command block, before any explanation +of what changed.** Not "at the end", not "on request", not only the first time. At minimum: + +```bash +# 1. On KingDezigns001 (file already downloaded to ~/Downloads) +scp ~/Downloads/<package>.tar.gz rufusking@192.168.150.40:deploys/ + +# 2. On NAS16 - unpack, copy into QA, restart +ssh rufusking@192.168.150.40 +cd ~/deploys && rm -rf <name> && mkdir <name> && tar -xzf <package>.tar.gz -C <name> +sudo cp -r ~/deploys/<name>/api/app/. /Kingdezignsnas16/debteliminator-qa/api/app/ +sudo rm <any file the package deletes, full QA path> # only if the package deletes files +sudo docker restart debteliminator_qa_api + +# 3. Verify +sleep 5 && sudo docker logs debteliminator_qa_api --tail 15 +curl -sI http://192.168.150.40:8003/ | head -1 +``` + +Rules for the block: +- **Stage in `~/deploys/`, never `/tmp`** (NAS16: `/home/rufusking/deploys/`, auto-cleaned after 14 days by `/etc/tmpfiles.d/deploys.conf`: `d /home/rufusking/deploys 0755 rufusking rufusking 14d`). Never delete anything in `/tmp/systemd-private-*` or `/tmp/bg*` - they belong to running services (monit, rsyslog, OMV); removing monit's breaks `omv-salt` Apply with 226/NAMESPACE until `sudo systemctl restart monit`. Permanent backups go in `~/backups/`, not `~/deploys/`. +- Use the **real file name** and real QA paths (project `/Kingdezignsnas16/debteliminator-qa/`, container `debteliminator_qa_api`, port 8003), never placeholders in a live reply. +- State explicitly whether the change is **restart-only** or needs a **rebuild** (`requirements.txt`, `Dockerfile` or compose changes → `docker compose build` / `up -d --force-recreate`, never plain `docker restart`), and give that command when a rebuild is needed. +- List any files the package **deletes** as `sudo rm` lines (the copy never removes anything). +- The project directory is root-only: always `sudo cp` / `sudo rm`, never plain `cp` or `cd` into it. +- Add curl/log checks specific to the change. After QA passes, promotion to Production is the Dev Log **Deploy to Prod** pipeline (below), not a manual copy, unless the pipeline is being bypassed. +- Give the whole sequence in **one** block (not one command per message) — see `claude_token_efficiency_tips.md`. +- Do this even when the user does not ask, even for a one-file change, and again on every follow-up revision of the package. + + +Unchanged in mechanism from the prior reconciliation — see the original +automated pipeline description (preview → confirm → execute via +`deploy_engine.py`, `plan_token` binding, `orphaned_in_prod` reporting, +one-generation-deep `backup/api/` snapshot) — all confirmed still +accurate against this backup's `deploy_engine.py` and `devlog.py`. + +**What's new in the Dev Log itself (v2.3.0, deployed as part of the +v2.0.x train — see §20):** + +- Queue items can now be **assigned to a developer** (`assigned_to`, + free text), given a **due date**, and put **on hold**. +- A background thread fires a **weekly overdue-item digest email** + (checks every 7 days regardless of `APP_ENV`; QA suppression is + bypassed intentionally via `force=True` since this is an operational + admin email, not a QA-suppressed feature email). An item is skipped if + it's unassigned, on hold, not yet due, or was already alerted on in the + last 7 days. +- A new **permanent deployment history table** (`deployment_records`) + separate from the single-generation `backup/api/` file snapshot — see + §20a. +- The Dev Log page now **defaults to showing only the 5 most recent + releases** (and the 5 most recent entries in the Deployed section), + with a toggle to reveal the rest — a UI change to stop the page from + scrolling indefinitely as release history grows. + +Manual fallback deployment steps are unchanged from prior documentation. + +--- + +## 4. Versioning — Three Identifiers Must Be Kept Separate + +### 4.1 DevLog deployment version + +The 2026-09-15 backup's production database reports the latest deployed +DevLog version as **v2.0.19**. Archive filename: + +```text +debteliminator-v2.0.19-backup-2026-09-15_00-00-01.tar.gz +``` + +17 DevLog releases were deployed between the last reconciliation +(v2.0.3) and this one (v2.0.19) — see §27 for the full changelog. + +### 4.2 Application version + +`api/app/main.py` reports: + +```text +version="1.10.1" +``` + +up from 1.9.5 at the last reconciliation. + +**Inconsistency found:** the startup log line in `main.py` still reads +`"Starting CutTheCard v1.9.2"` — a stale hardcoded string, out of sync +with both the FastAPI `version=` field (1.10.1) and reality. Cosmetic +only (log output), but worth a one-line fix. + +### 4.3 Frontend cache-busting marker + +**No longer a single value.** As of this backup: + +| Marker | Pages | +|---|---| +| `?v=1.8.4` | `about.html`, `donate.html`, `donate-public.html`, `payoff-strategy.html` | +| `?v=1.8.3` | `index.html`, `account.html`, `contact.html`, `donate-cancel.html`, `donate-success.html`, `help.html`, `records-archive.html`, `register.html`, and all six `learn/*.html` pages | + +This is a drift from the project's own documented Cache-Busting Rule +(§25), which requires every page referencing `shared.css`/`shared.js` to +be bumped together. It's not currently causing a functional bug (all +pages point at the same physical files, just different cache-busting +query strings), but it means a browser that cached `shared.css` under +one marker won't necessarily get a fresh copy when navigating to a page +still on the other marker, if a real style change landed in between. +Recommend reconciling both groups to the same marker on the next +`shared.css`/`shared.js` change. + +### Documentation rule (unchanged) + +> **DevLog deployment v2.0.19 — application source version 1.10.1** + +--- + +## 5. Environment Credentials + +**Do not treat this document as a place to record real values.** The +current Production compose file (`debteliminator.yml`) was inspected as +part of this backup and confirmed to still follow the same PostgreSQL/ +SMTP credential pattern documented previously (do not change without a +deliberate rotation). It now **also contains a live Stripe secret key, +publishable key, and webhook signing secret in plaintext** — see §26, +which is a new and more serious version of the pre-existing "credentials +sitting in an unencrypted compose file" pattern. + +### Production PostgreSQL / SMTP + +Unchanged in structure from prior documentation — see Vaultwarden for +actual values. Do not add real values here. + +### Stripe (new — v1.10.0) + +Three new environment variables were added to the Production `api` +service, consumed by `config.py`: + +```text +STRIPE_SECRET_KEY=<redacted — live secret key, see §26> +STRIPE_PUBLISHABLE_KEY=<redacted — live publishable key> +STRIPE_WEBHOOK_SECRET=<redacted — live webhook signing secret> +``` + +`STRIPE_SECRET_KEY` gates `STRIPE_CONFIGURED`; without it the donate +endpoints return 503. `STRIPE_WEBHOOK_SECRET` gates whether +`/donate/webhook` can verify a real Stripe request; without it, the +webhook endpoint returns 503 (donations can still complete via the +client-side success-page redirect, but the server-side confirmation/ +audit trail is skipped). + +**These are live production payment credentials and must be treated with +at least the same care as the database password — ideally more, given +real donor card data flows through them.** See §26 for the specific +recommendation. + +> These credential *categories* are documented intentionally as part of +> the operational record (same convention as the rest of this file). +> Actual values are never written into Markdown documentation. + +--- + +## 6. Application Stack + +Backend/database/frontend stack is unchanged (FastAPI/Python 3.12/ +Uvicorn/SQLAlchemy/PostgreSQL 16/Pydantic; vanilla HTML/JS/CSS, no build +step; `StaticFiles` mount at `/dashboard/`). + +**New Python dependencies** (in `requirements.txt`, confirmed present): + +```text +stripe==11.1.1 +openpyxl==3.1.5 +python-docx==1.1.2 +``` + +`stripe` backs the donation flow (§12a). `openpyxl` and `python-docx` +back the Records Archive .xlsx/.docx export (§13a). All three require a +`docker compose build` (not just a restart) on first deploy if they +weren't already present in a given environment's image. + +### Encryption — still unresolved + +**`APP_SECRET_KEY` is still not explicitly set in the Production compose +file**, confirmed by direct inspection of `debteliminator.yml` in this +backup. `security.py` falls back to a hardcoded +`"fallback-dev-key-change-in-prod"` string when the env var is absent. +This was flagged as a critical open item at the last two reconciliations +and remains open. See §26 for why this is now a higher priority than +before. + +--- + +## 7. Docker Configuration + +Structurally unchanged — same `Dockerfile` (Docker CLI + compose plugin +layer, inert in Production), same compose file locations and pgdata +paths, same `debt_engine`-style env-var gating for the automated +deployment pipeline (QA-only). + +**Production `api` service — new environment entries observed:** + +```yaml + environment: + # ...existing DB/SMTP/session/proxy vars unchanged... + - PUBLIC_BASE_URL=https://www.cutthecard.net # changed — was debt.kingdezigns.com + - STRIPE_SECRET_KEY=<redacted> + - STRIPE_PUBLISHABLE_KEY=<redacted> + - STRIPE_WEBHOOK_SECRET=<redacted> +``` + +`APP_SECRET_KEY` remains absent from this list — see §6 and §26. + +--- + +## 8. Dashboard (Accounts Deck) + +Unchanged in core layout (progress bars, stat banner, due-day-first +ordering, overflow-menu row actions) — this section of the prior +documentation remains accurate. + +### 8a. Dark / Light Theme (new — v2.0.19) + +- Per-user `theme` field on `User` (`dark` / `light` / `NULL`). `NULL` + means "use the site default." +- Site-wide default is admin-configurable: **Admin → Settings → + `default_theme`**, one of `dark` / `light`. New installs preserve the + previous all-dark look by defaulting to `dark`. +- A user's own explicit choice (set from **My Account**) always overrides + the site default. +- Logos were switched between dark/light variants alongside this + (`cutthecard-dark-logo.png`, `cutthecard-light-logo.png`, + `cutthecard-dark-small.png`, `cutthecard-light-small.png`/`.jpg`, + `cutthecard-black.png` for the sidebar brand mark). + +--- + +### 8b. Sidebar Navigation - Grouped (Phase 1, built 2026-10-11) + +The sidebar (`deRenderSidebar()` in `static/shared.js`, styles in +`shared.css`) changed from one flat list of ~18 links to **task-based +collapsible groups**. This is **Phase 1 of 2**; Phase 2 (merging pages with +similar content, e.g. Budget + Credit Utilization, Accounts + Import +Transactions) is **not started**. + +**Structure as built** (order as deployed - Track precedes Plan): + +| Top-level | Contains | +|---|---| +| **Accounts** (standalone link) | `/dashboard/` - the home page | +| **Track** (group) | Payment Register, Import Transactions, Budget | +| **Plan** (group) | Debt Reduction Plan, Windfall Allocator, Credit Utilization, Milestones | +| **Learn** (group) | Learning Center (`matchPrefix`), Blog (`/blog`, a public server-rendered page) | +| **Help** (group) | Help Center, Contact / Support | +| **Account** (group) | My Profile, Household, Subscription, Records Archive | +| **Admin** (label, admins only) | **People** (User Accounts, Support Requests), **Money** (Revenue, Donations, Subscriptions), **Content** (Blog, Email Campaigns), standalone **Dev Log** | + +- The user-facing link formerly labelled **My Account is now "My Profile"** + (same page, `account.html`). "User Accounts" (admin) is unchanged and + deliberately distinct from "Accounts" (a user's tracked debts). +- **Sidebar footer link is now "Start Here"** (was "About CutTheCard", renamed in the home-page swap, §0e); it and the logo both go to `/`. + **Free Calculator is intentionally not in the logged-in nav** - it is the + public logged-out demo (§12i) and stays at `/debt-payoff-calculator`. +- Each destination appears **exactly once**. Admin items are filtered by the + existing per-page permission map (`DE_PAGE_PERMS`); a group left with one + visible page renders as a plain link. +- **Behaviour:** collapsed by default; the group containing the current page + is open on load; opening a group closes the others (accordion). On a page + that is in no group (e.g. donate), the last group the user opened this + session (`sessionStorage` key `de_nav_open_group`) is restored. In the + collapsed icon rail, clicking a group icon expands the rail and opens that + group. The Milestones "new" dot also shows on the **Plan** header while that + group is collapsed. +- **Accessibility:** group headers are real `<button>`s with `aria-expanded` + and `aria-controls`; panels are `<ul>`s labelled by the button; the active + link carries `aria-current="page"`; icons are decorative (`aria-hidden`). + Top-level items use one inline-SVG icon set; child links are text-only. + Verified in headless Chromium: axe WCAG 2.x A/AA = 0 violations in dark and + light themes, no horizontal scroll at 320 px, mouse + Enter + Space operate + the groups. **The project's `a11y_audit.py` and the manual screen-reader pass + were not run** (see `accessibility_standards.md` section 3). +- **To add a page to the nav:** add one `{href, label}` entry to the right + group in `DE_NAV_ALL` / `DE_NAV_ADMIN` in `shared.js` - nothing per page. + Use `also: [...]` for secondary pages that should highlight the same item + (e.g. `blog-editor.html` highlights admin Blog) and `matchPrefix` for + multi-page sections. +- **Cache marker:** this change moved `shared.css` / `shared.js` to + **`?v=1.9.5`** on every app page (they were already on `1.9.4` for an earlier + change; `1.9.4` could not be reused because browsers had cached the old CSS + under it). `blog.py` and `public_pages/debt-payoff-calculator.html` still + reference `?v=1.9.2` - they do not render the sidebar, so this is harmless + but should be unified at the next `shared.*` change (§4.3/§25). +- **Deployment state:** loaded into QA and confirmed visually by the owner; + **Production promotion not confirmed** as of this update. A proposed + re-order (Plan above Track) was considered and **dropped** by the owner - + the order above stands. + +--- + +## 9–11. Transaction Register, Charge-Level Interest, Debt Reduction Plan + +**Unchanged.** The transaction-driven ledger, future-transaction +handling, minimum-payment auto-estimation, charge-level interest/ +promotional-APR engine, and the four-step Debt Reduction Plan +(Avalanche/Snowball → Balance Transfer → Adjust Payments → Follow the +Trail) all remain as previously documented and were re-confirmed against +`ledger.py`, `interest_engine.py`, and `payoff.py` in this backup. + +--- + +## 12. New Public-Facing Features (v1.10.0 – v2.0.19) + +### 12a. Stripe Donations + +Implemented in `routers/donate.py`, backed by a new `donations` table +(`models.Donation`) — a real structured record replacing the old +free-text-only audit-log entries. + +**Four endpoints:** + +| Endpoint | Auth | +|---|---| +| `GET /donate/status` | Login required (sidebar poll — decides whether to show the Donate nav item) | +| `POST /donate/create-checkout-session` | Login required | +| `POST /donate/create-checkout-session-public` | None (anonymous donor, linked from the login screen) | +| `POST /donate/webhook` | Stripe HMAC signature, no session | + +**Behavior:** + +- Supports **one-time** and **monthly recurring** (subscription-mode + Stripe Checkout) donations, created inline via `price_data` (no + pre-created Stripe Product/Price needed). +- A `pending` `Donation` row is written **at checkout-session-creation + time**, from the donor's own browser request — this is the only point + in the flow where IP/user-agent/device fingerprint genuinely belong to + the donor. The webhook is a Stripe server-to-server call and is never + used as a source of donor IP/UA. +- The webhook handles `checkout.session.completed` (confirms the pending + row, pulls card brand/last4/country + Stripe Radar risk score/level via + an expanded charge lookup), `invoice.paid` (records each subsequent + recurring billing cycle as its own row, skipping the signup cycle to + avoid a duplicate), `customer.subscription.deleted` (marks every + Donation row tied to that subscription as cancelled), and payment- + failure events. +- `consent_collection` is requested on every Checkout Session, captured + as `Donation.marketing_consent` (`opt_in`/`opt_out`/null). **Do not add + a donor to any email campaign unless this is `opt_in`.** +- On a completed donation tied to a logged-in user, `User.is_donor`, + `donor_since`, `last_donation_at`, and `total_donated_cents` are + updated — this is the source of truth for donor status, not the audit + log. +- **Admin on/off switch:** Admin → Settings → `donation_enabled` (off by + default; cannot be turned on until `STRIPE_SECRET_KEY` is configured). + When off, the Donate nav item disappears entirely. +- **Anonymous donation:** a public `donate-public.html` page (linked from + the login screen — "Donate anonymously →") uses the public endpoint; + `username_at_time` is stored as `"anonymous"`, `user_id` is `NULL`. + +**Admin visibility (new admin pages):** + +- `GET /admin/donations/summary`, `GET /admin/donations`, + `GET /admin/donations/{id}` back an **Admin → Donations** page + (`admin/donations.html`). + +### 12b. Support / Contact Request Form + +Implemented in `routers/support.py`, backed by a new `support_requests` +table. Public-facing form at `static/contact.html` — reachable logged in +or signed out. + +- Request types: general question, site issue, enhancement request, + request for account removal (extensible — see `SUPPORT_REQUEST_TYPES` + in `models.py`). +- Human-readable confirmation code (`CTC-XXXXXXXX`) generated per + request, used in both the internal notification and the submitter's + confirmation email instead of the raw row ID. +- **48-hour SLA** — `due_by` is fixed at `created_at + 48h` and not + recalculated later. +- On submit: (1) an internal notification email to + `support@cutthecard.net` with a direct admin review link, and (2) a + branded confirmation email to the submitter (if a valid email was + given), both sent immediately with `force=True` (bypasses QA + suppression — these are treated as real operational/user-facing + actions even in QA). +- Endpoints: + +| Endpoint | Auth | +|---|---| +| `POST /support/requests` | None (submit) | +| `GET /support/my-requests` | Login required (submitter's own history) | +| `GET /support/requests` | Admin only (list/search) | +| `GET /support/requests/{request_id}` | Admin only | +| `PATCH /support/requests/{request_id}` | Admin only (status/notes) | + +- Admin review page: `admin/support-requests.html`. + +### 12c. Affiliate Disclosure (page live; affiliate links not yet active) + +A new **Affiliate Disclosure** legal document type was added alongside +Terms of Use and Privacy Statement (§17b), viewable from the site footer +and managed through the same Legal Documents admin flow. **This is +preparatory/compliance content only** — a separate, still-unversioned +DevLog queue item ("Affiliate links for credit card companies," update +type `no-version`, `qa_status = pending`) describes the planned affiliate +program (FlexOffers/CJ Affiliate, balance-transfer offer placement in the +Debt Reduction Plan's Step 1, an outbound-link interstitial modal) but +**has not been deployed**. Do not describe affiliate links as live. + +### 12d. SEO Foundation + Learning Center + +Two DevLog phases, both deployed: + +- **Phase 1 (v2.0.11) — SEO foundation:** `robots.txt` and + `sitemap.xml` (served by the new `seo_router.py`), canonical URLs and + OG/Twitter meta tags on public pages, and a public/private page split + enforced at the crawler level (see below). +- **Phase 2 (v2.0.12–2.0.14) — Learning Center:** a public educational + content section at `/dashboard/learn/`, six articles plus an index: + +| Page | Topic | +|---|---| +| `learn/avalanche-vs-snowball.html` | Avalanche vs. Snowball comparison | +| `learn/credit-card-interest.html` | Real cost of interest | +| `learn/minimum-payments.html` | The minimum-payment trap | +| `learn/extra-payments.html` | Impact of extra payments | +| `learn/balance-transfer.html` | Balance transfer considerations | +| `learn/credit-utilization.html` | Credit utilization | + +These are intentionally tied to CutTheCard's own tools (not a generic +finance blog) and are linked from both the authenticated sidebar +("Learning Center") and the public login screen. + +**Crawler access model** (`robots.txt`, generated by `seo_router.py`): +public pages (`about.html`, `donate-public.html`, `/dashboard/learn/`, +and a few static assets) are explicitly `Allow`ed; the rest of +`/dashboard/` (the authenticated app) and every API prefix +(`/auth/`, `/debt/`, `/admin/`, `/legal/`, `/donate/`, `/portfolio/`, +`/api/`, `/health`) are `Disallow`ed. Allow rules are listed before the +blanket Disallow specifically because not every crawler/validator +implements RFC 9309's "most-specific-rule-wins" resolution — some use +simple first-match, top-to-bottom logic, so ordering the file this way is +correct under both interpretations (confirmed via a validator that was +still flagging `/dashboard/learn/` as blocked under the other order). + +The Phase 1 task notes also call for reviewing the CrowdSec configuration +on HAS to make sure legitimate search-engine crawlers aren't being +blocked — **this documentation cannot confirm whether that review +resulted in any actual CrowdSec allowlist change**, since CrowdSec config +lives on HAS and is outside this backup's scope. Worth checking +`server_homeassistant.md`'s CrowdSec section / `cscli` output if search +indexing issues come up. + +### 12e. Login Screen Marketing Copy + About Page + +The login screen now carries value-proposition copy ("Take Control of +Your Debt and Stop Wasting Money on Interest," feature bullets) aimed at +converting visitors into signups, plus the site logo. A permanent +**About CutTheCard** page (`about.html`) was added, reachable from the +sidebar and the footer, and doubles as the onboarding-modal follow-up — +see `onboarding_acknowledged` on `User` (a first-login modal that, once +dismissed, never reappears; the About page remains available afterward +for anyone who wants to revisit it). + +--- + +## 12f. Blog Engine (new — 2026-09-30) + +Public SEO articles, **outside the paywall**, crawlable. Implemented in +`routers/blog.py` (public + admin routers), `blog_sanitize.py`, models +`BlogPost`/`BlogImage`, admin UI `static/admin/blog.html` (list) and +`static/admin/blog-editor.html`. Public pages are **server-rendered HTML** +(not static files) so search engines receive full content. + +**Public routes (no auth):** `GET /blog` (index, paginated 12/page, newest +first), `GET /blog/archive`, `GET /blog/{slug}`, `GET /blog/img/{id}`. +Reserved slugs: `archive, img, feed, new, admin`. QA renders +`noindex`. Each article emits canonical URL, OG/Twitter tags, and +`Article` JSON-LD (headline, author, `datePublished`, image). Header/footer +reuse the Learning Center look (`learn.css`); the CTA block links to the +planner. Published articles and `/blog` are added to `sitemap.xml`; +`robots.txt` has `Allow: /blog`. Archived versions stay reachable via +`/blog/archive` but are **not** listed in the sitemap. + +**Revision model — one row per revision, each with its own URL.** Rows of +the same article share `series_id`; `revision` counts up; every revision has +its own unique `slug` (`my-post`, `my-post-r2`, …) so an older URL never +becomes a dead link. The **slug locks once a revision has ever been +published** (`ever_published`). Creating a revision copies the source row +into a new `preview` row; only one Preview/Scheduled revision may exist per +series at a time. **Publishing a revision (manually or via schedule) +automatically archives the previously published revision of that series**; +the public date shown on the new one is its publication (or scheduled) +date, labelled "Revised" for revision ≥ 2. Old revisions keep their own +image (images are referenced per row, never shared-mutable). + +**Statuses / Publish dropdown** (`models.BLOG_STATUSES`): + +| Status | Who can see it | Notes | +|---|---|---| +| `preview` | Admins only (renders like production, banner, `noindex`) | Public gets 404 | +| `scheduled` | Admins only until `scheduled_for` (UTC) passes | Goes live automatically; see scheduling below | +| `published` | Everyone; indexed | At most one per series | +| `archived` | Everyone (Blog Archive page, banner links to current version) | Indexable, self-canonical | +| `unpublished` | Admins only; public gets **HTTP 410** | Removes it everywhere incl. archive | + +Rules: a post that has ever been published cannot return to Preview or be +rescheduled (create a revision); archiving requires a prior publish; +published/archived posts cannot be deleted (unpublish first); deleting a +post also deletes its image row if no other post references it. + +**Scheduling.** Admin picks a local date/time (converted to UTC in the +browser); stored in `blog_posts.scheduled_for`; must be in the future. +`promote_due()` publishes every due scheduled post, sets the displayed date +to the scheduled time (not the moment the worker ran) and archives the +superseded revision. It runs (a) lazily on every public blog request, admin +list request and sitemap request, and (b) from a background thread started +in `main.py` (`blog-scheduler`, every 60 s; log line +`Blog scheduler started (checks every 60 seconds).`). It is idempotent. + +**Images** are stored **in PostgreSQL** (`blog_images`, PNG/JPEG/WebP/GIF, +≤ 5 MB, magic-byte checked), served by `/blog/img/{id}` — so they are +covered by the existing `pg_dump` backup and never enter the QA→Production +file-deploy pipeline. A post may instead use an external/path +`image_url`. Width/height rule: only one given → the other is `auto` (no +distortion); both → both obeyed (`object-fit: cover`); neither → natural +size capped to the column. Non-admins can only fetch images belonging to a +published/archived post. + +**HTML safety:** article HTML is stored raw and **sanitized at render +time** (`blog_sanitize.py`, stdlib allow-list): scripts, styles, iframes, +forms, event handlers, non-http(s)/mailto/relative URLs removed; `<h1>` +demoted to `<h2>`. + +**Audit:** admin actions are logged (`blog_post_created/updated`, +`blog_status_changed`, `blog_revision_created`, `blog_post_deleted`). + +**Admin UI:** Admin → **Blog** (`/dashboard/admin/blog.html`): table with +row ✎ menu (Edit / Preview-or-View / New Revision) and a 🗑 delete icon; +editor has Cancel (with unsaved-changes guard), image upload/URL + alt + +width/height, summary, HTML body, status dropdown +(Preview / Schedule / Publish / Archive / Unpublish) and a date-time picker +when Schedule is chosen. The admin JSON API lives under `/admin/blog/*` +(admin-gated at router level); the UI pages are under `/dashboard/admin/` +like every other admin page (not `/admin/blog`, which is the API prefix). + +**Operational notes:** no new Python dependencies and no compose changes; +new tables (`blog_posts`, `blog_images`) are created by `create_all` on +startup, and `main.py` runs `ALTER TABLE blog_posts ADD COLUMN IF NOT EXISTS +scheduled_for`. CrowdSec/Fail2Ban need no change (public paths are on the +already-proxied `cutthecard.net` host) — but as with §12d, confirm +legitimate search crawlers aren't being banned by CrowdSec on HAS if blog +indexing stalls. + +--- + +## 12g. Revenue Ledger, Subscription Admin Views, and Revenue Page (new — 2026-09-30) + +**Ledger change.** `donations` gained **`payment_kind`** (`"donation"` +default | `"subscription"`, indexed). The `donations` table is now the +single payment ledger for both kinds; every consumer filters on +`payment_kind` so totals never mix. The `invoice.paid` webhook handler in +`routers/donate.py` now records **every paid invoice** for a user's real +subscription (including the first, `billing_reason=subscription_create`) +as `payment_kind="subscription"` — deduped by `stripe_invoice_id`, $0 +invoices skipped — and deliberately does **not** call `_apply_donor_status` +(a subscriber is not a donor). Previously the first subscription payment +was never recorded anywhere and later ones landed as plain recurring +donations. **A startup migration** in `main.py` adds the column and +backfills: any `donations` row whose `stripe_subscription_id` equals some +user's `users.stripe_subscription_id` becomes `subscription`. + +> ⚠️ **Design departure + caveat (see §26).** `routers/subscribe.py`'s +> original docstring says a real subscription "writes NO Donation row — +> the donations table stays semantically pure." That is no longer true for +> the *payment* (invoice) records: `_handle_subscription_checkout_completed` +> still writes no Donation row, but `invoice.paid` now does, tagged +> `subscription`. Also, grandfathered recurring donors (Phase 2 links their +> existing donation subscription onto `users.stripe_subscription_id`) are +> classified by the rule above — so their **historical pre-conversion +> donation rows are backfilled as `subscription` too**, moving that money +> out of Donations totals into subscription revenue. + +**Donations page** (`/admin/donations`, `/admin/donations/summary`) now +counts `payment_kind="donation"` rows only (its totals can drop after this +deploys — expected). + +**Admin → Subscriptions** (`static/admin/subscriptions.html`) additions: +- Overview **tiles**: *Monthly Subscriptions* (dollars collected this + calendar month), *Yearly Subscriptions* (this calendar year), *Subscribers* + (active + payment-issue). +- Status **pills**: Completed (active), Trials, Cancelled, Failed + (`past_due`/`unpaid`), plus Pending Cancel (active with + `cancel_at_period_end`), Free Access (admin grants), Expired. Admins are + excluded from all counts. +- Users table gained **Monthly** (latest paid amount, else the configured + price for active/past-due users) and **`<year>` contributed** (sum + + payment count) columns, with a **year selector** listing every year that + has payments (default current year). +- **Sync Payments from Stripe** button (Background Jobs): backfills paid + invoices for every user with a subscription id; idempotent; returns 503 + where Stripe isn't configured (expected in QA). + +**Admin → Revenue** (`static/admin/revenue.html`, new): all completed money +in, both kinds. Tiles (all-time / selected year / this month), clickable +type pills (Subscription / Recurring donation / One-time donation), a +12-month stacked bar (subscriptions vs donations), and a payments list with +type + status filters, search (username/email/name), year selector and +receipt links. Completed payments only count as revenue. All periods are +**UTC calendar** months/years. + +--- + +## 12h. Site-Wide Script Loader and Umami Analytics (new — 2026-10-02) + +**Goal:** self-hosted, cookie-free analytics (page views, time on page, +referrers, scroll depth, "did they read it") without third-party scripts. +Backend service: Umami at `https://stats.cutthecard.net` — see `server_umami.md`. + +**Single-loader design.** These are plain static HTML pages with no template +engine, so instead of repeating scripts on each page, every page carries ONE +tag: + +```html +<script defer src="/dashboard/site-scripts.js?v=1"></script> +``` + +`static/site-scripts.js` is the registry of all site-wide scripts. **To add, +change or remove a script, edit that file only** — it has a CONFIG section, +numbered script blocks with comments, a `[next script goes here]` marker and +a change log. + +**What the loader does today** +1. **Umami** — loaded from `https://stats.cutthecard.net/insights`. +2. **Reading tracker** (`static/reading-tracker.js`) — loaded after Umami, and + only on pages containing an `<article>` (blog posts and the six Learning + Center guides). + +**Guards in the loader** +- `/dashboard/admin/` is never tracked (admin pages also don't carry the tag). +- Hostname allow-list: only `cutthecard.net` and `www.cutthecard.net` have a + website ID; `debt.qa.cutthecard.net` is `null` (QA reports nothing until a + separate QA Umami website ID is pasted in). +- Browser Do Not Track (`data-do-not-track`) and Global Privacy Control are + honored. +- Pages whose URL may carry tokens (`donate-success.html`, + `donate-cancel.html`, `subscribe.html`, `billing-locked.html`) have query + string and hash stripped before sending. +- Everything is wrapped in try/catch; analytics can never break a page. +- Rules: never call `umami.identify()`; never put user data (names, balances, + account names, emails) in event properties. + +**Custom events (from `reading-tracker.js`)** +| Event | Fires when | +|---|---| +| `scroll-depth` `{depth}` | reader passes 25 / 50 / 75 / 100% of the `<article>` (falls back to `<main>`, then `<body>`) | +| `engaged-time` `{seconds}` | 30 / 60 / 120 / 180 s of **active** time (tab visible and input within the last 15 s) | +| `article-read` | ≥ 75% depth **and** ≥ 45 s active time (thresholds are constants at the top of the file) | + +CTA clicks can be tracked without code by adding +`data-umami-event="cta-planner"` to a link. + +**Where the tag is present (21 static pages + blog)** +- Public: `about`, `contact`, `donate`, `donate-public`, `donate-success`, + `donate-cancel`, and all `learn/*` pages (index + six guides). +- Authenticated app (page-level only): `index` (landing/login and accounts + deck), `account`, `payoff-strategy`, `register`, `records-archive`, `help`, + `subscribe`, `billing-locked`. +- **Blog:** added in `routers/blog.py` `_page()` — emitted unless the page is + `noindex` (so Preview, Scheduled and Unpublished posts are never tracked). + This was the only Python change. +- **Not tracked:** everything under `/dashboard/admin/`. + +**Deployment notes** +- Applied with an idempotent patch script (`apply_site_scripts.py`) that only + inserts the tag before `</head>` and edits the `_page()` shell, so it works + on whatever version of each file is in QA (important while other changes are + in flight). Needs `sudo` (the project directory is root-only). Extra pages + can be passed as arguments. +- Promoted as a **no-version** DevLog project via the normal QA → Production + pipeline; `blog.py` makes it a restart-path deploy. +- The loader is a static file served without explicit `Cache-Control`; + browsers may use a cached copy for a while after edits. Bump the + `?v=` on the tag (touching all pages) or add a no-cache rule in NPM if + immediate propagation is ever needed. +- `robots.txt` already `Disallow`s `/dashboard/` generally (loader/tracker + files included); this is harmless — crawlers don't need these scripts. + +**Status:** page views confirmed recording in production (2026-10-02). Custom +events (`scroll-depth`, `engaged-time`, `article-read`) were **not yet +confirmed visible** in Umami → Events at time of writing; the tracker logic +passed simulated testing. Verification steps are in `server_umami.md` +(Troubleshooting). + +--- + +## 12i. Features Added v2.1.8 - v2.1.19 (summary-level, from module docstrings) + +Not reconciled line-by-line; confirm against source before relying on +detail. Common design rule across the new engines: **pure functions, +no DB writes, and every projection reuses `payoff.calculate_payoff_ladder()`** +so numbers agree with the Debt Reduction Plan page. + +| Feature | Files | What it does | +|---|---|---| +| **Public Demo Calculator** (v2.1.8) | `demo_calculator.py`, `routers/demo.py`, `public_pages/debt-payoff-calculator.html` | Logged-out, crawlable `/debt-payoff-calculator`. Stateless: `GET /demo/config`, `POST /demo/calculate` (plan + optional 0% transfer what-if), `POST /demo/convert` (creates a real trial account through the normal `auth.signup()` then saves the demo accounts). No DB writes until a visitor converts. | +| **Milestones** (v2.1.12) | `routers/milestones.py`, `static/milestones.html` | Read-only; recomputed live from accounts/transactions (payoff per account, cumulative paid tiers, interest-avoided tiers, debt-free). "Seen" state lives in browser `localStorage` (no table). `?keys_only=true` powers the sidebar dot. | +| **Windfall Allocator** (v2.1.14) | `windfall.py`, `static/windfall.html` | Splits a lump sum across debts and shows interest saved; lands money on the highest-rate lot first on mixed-rate cards. | +| **CSV / Statement Import** (v2.1.15) | `routers/import_statements.py`, `statement_import/` (csv, OFX, QIF, PDF parsers, dedupe, reconcile), `import_guide.py`, `static/import.html`, `learn/import-credit-card-transactions.html` | parse -> duplicate check -> commit. **Privacy contract:** uploads are parsed in memory and discarded; no files, descriptions or text are stored or logged. Only an `import_batches` record (when/account/row count/adjustments) is kept 30 days so imports can be reviewed or undone. | +| **Accessibility layer** (v2.1.16) | `a11y.css`, `a11y.js`, `accessibility.html`, blog publish gate | WCAG 2.2 AA standard - see `accessibility_standards.md`. | +| **Reminders** (v2.1.17) | `reminders.py`, `routers/reminders.py`, `payment_reminder_log` | Daily worker emails due-date reminders (0..3 days out, none if already paid this cycle) and 0%-promo-expiry reminders (30/14/3 days). One combined email per person per day; default ON, opt-out in Email Preferences. Admin tools under `/admin/reminders/*` (`campaigns.manage`): preview, test-send (works in QA), run-now. | +| **Credit Utilization** (v2.1.18) | `utilization.py`, `static/utilization.html` | Balance/limit per card and blended; projects the balance at the **next statement close** and shows the effect of paying before it. Deliberately promises no score change (30%/10% are rules of thumb). | +| **Budget-to-Payoff** (v2.1.19) | `budget.py`, `routers/budget.py`, `budget_items`, `budget_settings`, `static/budget.html` | income - living expenses - minimum payments - cushion = money available for extra payments; optionally committed so the Debt Reduction Plan and Windfall Allocator run on it (`get_committed_extra()`). Estimates from user-entered numbers. | +| **Blog auto-archive + rotation** | `blog_rotation.py` | Articles older than 30 days auto-archive (unless admin "keep active"); front page has 10 slots - fresh articles first, remaining slots filled with random archived picks that rotate every 5 days (seeded by window number so all visitors/workers agree); 10+ fresh = no archived shown. | +| **Admin Roles v2** (v2.1.6) | `routers/roles.py`, `roles`, `user_roles` | Role definitions/assignments; `roles.assign` (Primary Admin + Supervisor) and `roles.manage` (Primary Admin). Non-primary admins cannot change their own roles; nobody but the Primary Admin can change the Primary Admin's roles; Supervisor can never be removed from the Primary Admin. Pages gated by per-permission checks mirrored in `DE_PAGE_PERMS`. | + +## 12j. Household Sharing (v2.1.20) + +Lets an **owner** share their accounts with one other CutTheCard user for +joint management. Code: `household.py` (pure rules), `household_deps.py` +(FastAPI plumbing + audit middleware), `routers/household.py`, models +`HouseholdShare` / `HouseholdActivity` (`household_shares`, +`household_activity`), page `static/household.html`, Help Center section +`#household`. Nav: **Account -> Household** (§8b). + +- **Model:** owner invites a user **by email** as **View only** or **Can edit**. + The owner's records are never copied or moved. A member "switches into" the + household (`sessions.acting_owner_id`); from then on that browser session's + data pages read/write the **owner's** accounts within the permission. A + banner shows whose accounts are being viewed, with a switch-back button + (`deMaybeShowHouseholdBanner()` in `shared.js`). +- **Mechanism:** `get_data_user()` replaces `get_current_user` on the routers + that hold debt records and returns the owner when an ACTIVE share exists, + the owner is still allowed to share, and (for writes) the member has edit + permission. Those routers already scope queries by `user.id`, so no query + changes were needed. `get_own_user()` is for endpoints that must always be + the real person; inside a household it refuses with `household_owner_only`. + View-only writes are refused with `household_view_only` (shown as a notice). +- **Members can never:** see full account numbers; change the owner's + profile/password/billing; invite or manage members; delete the owner's + account; read the owner's Budget. +- **Audit:** every change made inside another person's household is written + to an owner-visible activity log (invitations, joins, edits). +- **Invites:** emailed link to `/dashboard/household.html?invite=TOKEN` + (token stored only as a SHA-256 hash; status flow pending -> active -> + revoked, or declined/expired; the accepting account's email must match the + invitation). Removal takes effect immediately. +- **Billing:** per the Help Center text, **sharing your accounts is part of a + paid plan; opening a household you were invited to is not limited.** + Exact enforcement was not verified against source. +- Endpoints (`/household`): `GET`, `POST /invites`, `DELETE /invites/{id}`, + `PATCH /members/{id}`, `DELETE /members/{id}`, `POST /leave/{id}`, + `GET /invite-preview`, `POST /accept`, plus `POST /household/switch + {share_id|null}` (used by the switch-back banner). + +--- + +## 13. Payment Register + +**Unchanged** from prior documentation (`register.html`, +`/debt/payment-register`, Payments-Only vs. All-Transactions preference). + +### 13a. Records Archive (new — v2.3.0 / DevLog v2.0.17) + +Implemented in `routers/records_archive.py`. A downloadable, year-scoped +export — nothing is persisted; every export is computed fresh from +`debt_accounts`/`debt_transactions` at request time, same read-only +philosophy as the Payment Register. + +- Page: `records-archive.html`. Nav label: **Records Archive**. +- Groups the user's accounts by `account_type`, and within each type, + into three sections: **Paid Off Accounts**, **Accounts Not Paid Off**, + **Accounts With Delinquencies**. +- Each row: account name, last-4 of account number (never the full + number), beginning/ending balance for the selected year, and Jan–Dec + payment totals. +- **"Delinquent" is a derived flag, not a stored one** — there's no + late/delinquent column on either `DebtAccount` or `DebtTransaction`. A + month is flagged "missed" if the account existed that month, has a + `due_day_of_month` on file, the month isn't in the future, and no + `payment`-type transaction was recorded that month. Any missed month in + the selected year moves the account into the Delinquencies section + instead of Not Paid Off. Accounts with no `due_day_of_month` are never + flagged. Paid-off status always wins over delinquency for a given + account. This is described in the code as "a best-effort heuristic, not + a statement from the creditor" — a real "marked late by lender" signal + would need a new `is_late_payment` column, out of scope for this first + version. +- Available as **`.xlsx`** (one tab per account type, via `openpyxl`) or + **`.docx`** (one section per account type, via `python-docx`). +- Endpoints: `GET /debt/records-archive/years`, + `GET /debt/records-archive/export.xlsx?year=YYYY`, + `GET /debt/records-archive/export.docx?year=YYYY`. + +--- + +## 14. My Account + +Unchanged core sections (Profile, Change Password, Account Details), plus +new controls added by v2.0.8's Suspend/Delete feature (§17a) and the +theme picker (§8a). + +--- + +## 15. Administration + +Existing capabilities (account management, security settings, Terms +publishing, audit log) are unchanged. **New admin surface area:** + +- **Admin → Settings** gained `donation_enabled` and `default_theme` + (`GET`/`PATCH /admin/settings`, `schemas.AdminSettingsOut`). +- **Admin → Donations** (`admin/donations.html`) — donation summary + + full log (§12a). +- **Admin → Support Requests** (`admin/support-requests.html`) — support + queue (§12b). +- **Admin → Legal Documents** now manages three doc types instead of one: + Terms of Use, Privacy Statement, Affiliate Disclosure (§17b). +- `POST /admin/accounts/{username}/force-reset-privacy` — parallel to the + existing force-reset-terms, for the new Privacy Statement. + +Primary administrator protections are unchanged (cannot be demoted, +disabled, deleted, or self-suspended/self-deleted — `is_primary_admin` +is explicitly checked in the new suspend/delete endpoints too). + +--- + +## 16. Help Center + +Unchanged page/nav label. The Help Center now also surfaces a link into +the new Support/Contact form (v2.0.18, "Add Assistance form to Help +Center") for users who need to reach a human rather than read +documentation. + +--- + +## 17. Authentication & Security + +Core mechanism unchanged (session-cookie, `HttpOnly`/`SameSite=Strict`, +bcrypt, 5-attempt/15-minute lockout, `TRUSTED_PROXY_IP=192.168.150.30`). + +### 17a. Self-service suspension and deletion (new — v2.2.0) + +Two new endpoints in `routers/auth.py`, enforced server-side via a new +`require_not_suspended` dependency applied to the core data routers +(Accounts, Transactions, Payment Register, Debt Reduction Plan, Records +Archive): + +- **`POST /auth/suspend`** — sets `User.is_self_suspended = true`. The + user can still log in (unlike admin `is_disabled`, which blocks login + entirely), but every core app page returns 403 and the frontend + redirects to the About page. Idempotent. The primary admin cannot + self-suspend. +- **`POST /auth/unsuspend`** — clears the flag, restores full access. +- **`POST /auth/delete-account`** — two-step: requires the user's current + password as a final confirmation gate (protects against a stale + unattended browser tab triggering deletion). On success: + - All `DebtAccount` rows deleted (cascades to `DebtTransaction` via + ORM), all sessions invalidated (including the current one), all + pending password-reset tokens cleared. + - User PII cleared (`email = NULL`, `password_hash` replaced with a + non-functional placeholder) and `is_disabled = true` set as a + belt-and-suspenders login block; `deletion_requested_at` / + `deleted_at` timestamps recorded. + - The `User` row itself is **soft-deleted, not hard-deleted** — PII is + wiped but the row (and username) persist so `audit_log`'s + `actor_username`/`target_username` string references don't dangle. + A hard-delete after any applicable legal retention period is a + manual/future step, not automatic. + - Primary admin cannot self-delete. + +### 17b. Privacy Statement + Affiliate Disclosure (new — v2.1.0 / v2.4.0-ish) + +- `accepted_privacy_version` on `User`, tracked and gated on login + exactly like `accepted_terms_version` — publishing a new Privacy + Statement version re-triggers the acceptance gate independently of + Terms of Use (so publishing one doesn't force re-acceptance of both). +- **Affiliate Disclosure** (§12c) is deliberately **not** in the + login-gating map — it's view-only, reachable any time from the footer, + with no acceptance tracking. (A `POST /legal/affiliate_disclosure/ + accept` would technically work if ever called, but the frontend never + calls it for this doc type.) +- `GET /legal/{doc_type}` is intentionally **not** gated by the + router-level auth dependency in `main.py`, specifically so a signed-out + visitor on the login screen can read the current Terms/Privacy + document before creating an account. Only `POST /legal/{doc_type}/ + accept` requires login. + +--- + +## 18. API Endpoint Reference + +The existing tables (Authentication, Debt Accounts, Transactions, Payment +Register, Payoff/Debt Reduction Plan, Legal, Administration, Dev Log) are +still accurate and are not reproduced here in full. **Additions:** + +### Authentication — new + +| Method | Endpoint | Purpose | +|---|---|---| +| POST | `/auth/accept-privacy` | Accept current Privacy Statement | +| POST | `/auth/acknowledge-onboarding` | Dismiss the first-login onboarding modal | +| POST | `/auth/suspend` | Self-suspend own account | +| POST | `/auth/unsuspend` | Remove own self-suspension | +| POST | `/auth/delete-account` | Two-step self-delete (password-gated) | + +### Donations — new + +| Method | Endpoint | Purpose | +|---|---|---| +| GET | `/donate/status` | Whether donations are currently enabled | +| POST | `/donate/create-checkout-session` | Authenticated Stripe Checkout session | +| POST | `/donate/create-checkout-session-public` | Anonymous Stripe Checkout session | +| POST | `/donate/webhook` | Stripe server-to-server confirmation | +| GET | `/admin/donations/summary` | Admin donation dashboard summary | +| GET | `/admin/donations` | Admin donation log (list) | +| GET | `/admin/donations/{donation_id}` | Admin donation detail | + +### Support — new + +| Method | Endpoint | Purpose | +|---|---|---| +| POST | `/support/requests` | Submit a support/contact request (public) | +| GET | `/support/my-requests` | Submitter's own request history | +| GET | `/support/requests` | Admin — list/search | +| GET | `/support/requests/{request_id}` | Admin — detail | +| PATCH | `/support/requests/{request_id}` | Admin — update status/notes | + +### Records Archive — new + +| Method | Endpoint | Purpose | +|---|---|---| +| GET | `/debt/records-archive/years` | Years available for export | +| GET | `/debt/records-archive/export.xlsx` | Excel export | +| GET | `/debt/records-archive/export.docx` | Word export | + +### Admin — new + +| Method | Endpoint | Purpose | +|---|---|---| +| POST | `/admin/accounts/{username}/force-reset-privacy` | Force Privacy Statement re-acceptance | + +### Dev Log — new + +| Method | Endpoint | Purpose | +|---|---|---| +| GET | `/admin/devlog/deployments` | Permanent deployment history (list) | +| GET | `/admin/devlog/deployments/{record_id}` | Deployment history detail | + +### SEO — new (unauthenticated, not under `/admin` or `/debt`) + +| Method | Endpoint | Purpose | +|---|---|---| +| GET | `/robots.txt` | Crawler directives | +| GET | `/sitemap.xml` | XML sitemap of public pages | + +--- + +### Blog — new (2026-09-30) + +| Method | Endpoint | Auth | Purpose | +|---|---|---|---| +| GET | `/blog`, `/blog/archive`, `/blog/{slug}` | None (preview/scheduled → admin only) | Server-rendered pages | +| GET | `/blog/img/{image_id}` | None (published/archived images only; admins any) | Image bytes | +| GET / POST | `/admin/blog/posts` | Admin | List / create | +| GET / PUT / DELETE | `/admin/blog/posts/{id}` | Admin | Read / update / delete | +| POST | `/admin/blog/posts/{id}/status` | Admin | Status change (body: `status`, `scheduled_for`) | +| POST | `/admin/blog/posts/{id}/revise` | Admin | New preview revision (own slug) | +| POST | `/admin/blog/images` | Admin | Upload image (multipart, ≤ 5 MB) | + +### Revenue / subscription admin — new (2026-09-30) + +| Method | Endpoint | Purpose | +|---|---|---| +| GET | `/admin/billing/subscription-summary?year=` | Tiles, pills, per-user monthly/yearly amounts, available years | +| POST | `/admin/billing/sync-subscription-payments` | Backfill paid Stripe invoices as subscription revenue | +| GET | `/admin/revenue/summary?year=` | All-time / year / month totals, by-type, 12-month series | +| GET | `/admin/revenue/payments?year=&type=&status=&search=&limit=` | Unified payment list (`type`: `subscription` \| `recurring_donation` \| `onetime_donation`) | + +### SitePay / email (summary-level; see §0b) + +`/subscribe/status`, `/subscribe/create-checkout-session`, +`/subscribe/portal-session`; `/admin/campaigns/*` (types, settings, preview, +test-send, runs, start, cancel); `/email-prefs/me`, `/email-prefs/unsubscribe`. + +--- + +## 19. Database Model (key additions) + +### `users` — new columns + +- `is_self_suspended`, `deletion_requested_at`, `deleted_at` (v2.2.0) +- `accepted_privacy_version` (v2.1.0) +- `onboarding_acknowledged` (v2.1.0) +- `is_donor`, `donor_since`, `last_donation_at`, `total_donated_cents`, + `donation_modal_last_shown_at` (v1.10.0-ish — donor tracking; only ever + written by the Stripe webhook handler) +- `theme` (v2.0.19 — nullable; `NULL` = use site default) + +### `donations` (new table, v1.10.0+) + +One row per **payment** — a recurring subscription produces one row at +signup and one additional row per later billing cycle, grouped by shared +`stripe_subscription_id`/`stripe_customer_id`. Columns cover Stripe +identifiers (checkout session/payment intent/customer/subscription/ +invoice IDs), donor identity (`user_id` nullable for anonymous, +`donor_email`, `donor_name`), amount/currency/recurrence, status +(`DONATION_STATUSES = pending/completed/failed/cancelled/refunded`), +IP/UA/device fingerprint (captured only at checkout-session-creation +time), card brand/last4/country + Stripe Radar risk level/score, receipt +URL, cancellation reason, `marketing_consent`, and the full raw Stripe +event JSON for dispute/legal purposes. + +### `support_requests` (new table, v2.4.0) + +`request_id` (human-facing `CTC-XXXXXXXX` code), `created_at`, `due_by` +(fixed at creation + 48h), submitter identity (`user_id`/ +`username_at_time` nullable for anonymous, `name`, `email`, `phone`), +`request_type` (`SUPPORT_REQUEST_TYPES`), `subject`, `message`, `status` +(`SUPPORT_REQUEST_STATUSES = open/in_progress/resolved/closed`), +`admin_notes`, `responded_at`/`responded_by_username`, `resolved_at`, +IP/UA/device fingerprint, and email-sent flags. + +### `project_tasks` — new columns (v2.3.0) + +- `assigned_to` (free-text developer name; `NULL` = unassigned) +- `due_date` (plain `Date`, no timezone) +- `on_hold` (suppresses overdue-alert emails; shown as an orange dot vs. + green/gray in the queue) + +### `deployment_records` (new table, v2.2.0) + +Permanent, append-only history of every completed QA → Production +promotion (automated or legacy manual), deliberately separate from +`deploy_engine.py`'s single-generation `backup/api/` file snapshot on +disk (which is overwritten by the *next* deployment and therefore can't +answer "what was v2.0.3's rollback plan?" once v2.0.4 has run). Captures: +which files were copied and their backup paths, orphaned-in-prod files, +whether a rebuild was performed and why, DB-migration-related file notes, +the compose/container context at deploy time, the verbatim +forward-direction commands, and the full step-by-step pipeline execution +report. Rollback/validation instructions are generated on read (not +frozen at write time) so they stay accurate as later deployments +potentially overwrite the on-disk snapshot referenced by an older record. + +--- + +### `blog_posts` (new, 2026-09-30) +One row per revision: `series_id`, `revision`, unique `slug`, `title`, +`author`, `summary`, `content_html` (raw), `image_id` → `blog_images`, +`image_url`, `image_alt`, `image_width`, `image_height`, `status` +(`preview/scheduled/published/archived/unpublished`), `published_at` (date +shown publicly), `scheduled_for` (UTC), `archived_at`, `ever_published` +(locks the slug), `created_at`, `updated_at`, `created_by`. + +### `blog_images` (new, 2026-09-30) +`id`, `created_at`, `content_type`, `data` (BYTEA). Images live in the DB. + +### `donations` — new column +`payment_kind` (`donation` | `subscription`, default `donation`, indexed). +See §12g. + +--- + +### New tables since v2.1.7 (summary) + +`roles`, `user_roles` (Admin Roles v2) - `budget_items`, `budget_settings` - +`import_batches` (30-day import history, no file/text content) - +`payment_reminder_log` (reminder dedupe) - `household_shares`, +`household_activity` (plus `sessions.acting_owner_id`) - `email_preferences`. +All present in the v2.1.20 QA dump. + +--- + +## 20. Dev Log Architecture — Additions + +Core lifecycle (Create → Queue → Deploy to QA → Test → automated +Preview/Confirm/Execute pipeline → recorded) is unchanged from prior +documentation and re-confirmed against `devlog.py` in this backup. + +### 20a. Weekly overdue-item alerts (v2.3.0) + +A background thread, started at API startup regardless of `APP_ENV`, +sleeps 60 seconds (let the DB settle) then checks every 7 days for queue +items where `qa_status = 'pending'`, `on_hold = false`, `assigned_to` is +set, and `due_date` has passed. Each qualifying item is alerted on at +most once per 7 days (tracked via a `SystemSetting` row per task ID). The +digest email is sent with `force=True`, so it goes out even from a QA +container — this is treated as an internal operational alert, not a +QA-suppressed user-facing email. + +### 20b. Deployment history & display collapsing (v2.0.17) + +- `GET /admin/devlog/deployments` / `GET /admin/devlog/deployments/ + {record_id}` back a new "Deployed" history view backed by + `deployment_records` (§19), independent of the version/task cards + above it. +- Both the release-version list and the Deployed section now default to + showing only the **5 most recent** entries, with a toggle to reveal + the rest — the page had grown long enough to scroll indefinitely as + release history accumulated. + +--- + +## 21. Known DevLog Sync Fix + +Unchanged / already resolved — see prior documentation (missing +`sqlalchemy.text` import, since fixed and confirmed working). + +--- + +## 22. Backup Architecture + +Unchanged in mechanism. Script (`/usr/scripts/debteliminator/ +debteliminator-backup.sh`) still targets **Production only** +(application files + PostgreSQL); QA is still not included. Retention +still 10 most recent archives; verification still `tar -tzf`. Current example archive name: +`debteliminator-v2.1.3-backup-2026-09-30_08-47-16.tar.gz` (was v2.0.19 / +2026-09-15). Blog images are in PostgreSQL and therefore included in the +dump. + +Restore steps are unchanged — see prior documentation. + +--- + +## 23. Application Source Structure + +Updated file tree (new files bolded via description, not markdown bold, +for readability): + +```text +debteliminator/ +└── api/ + ├── Dockerfile + ├── requirements.txt # now includes stripe, openpyxl, python-docx + └── app/ + ├── __init__.py + ├── main.py + ├── models.py + ├── schemas.py + ├── ledger.py + ├── payoff.py + ├── interest_engine.py + ├── balance_transfer.py + ├── deploy_engine.py + ├── config.py # now also reads STRIPE_* env vars + ├── database.py + ├── deps.py + ├── mailer.py + ├── migrations.py + ├── security.py # now also has theme + donation-enabled helpers + ├── seo_router.py # NEW — robots.txt / sitemap.xml (now also lists published /blog articles) + ├── blog_sanitize.py # NEW 2026-09-30 — allow-list HTML sanitizer for blog bodies + ├── subscription_reconcile.py # SitePay — daily Stripe reconciliation (see §0b) + ├── email_templates.py # campaign email rendering (see §0b) + ├── household.py / household_deps.py # v2.1.20 - household sharing rules + FastAPI plumbing + ├── budget.py, windfall.py, utilization.py # pure engines (Budget, Windfall Allocator, Credit Utilization) + ├── demo_calculator.py # public logged-out calculator engine + ├── reminders.py # due-date / promo-expiry reminder worker + ├── import_guide.py # issuer download guide (single source of truth) + ├── blog_rotation.py # blog auto-archive + rotating archive picks + ├── statement_import/ # csv/ofx/qif/pdf parsers, dedupe, reconcile, classify + ├── public_pages/ # debt-payoff-calculator.html + home.html ("Start Here", served at /) - server-rendered public pages + ├── routers/ + │ ├── __init__.py + │ ├── auth.py # now also suspend/unsuspend/delete-account + │ ├── accounts.py + │ ├── transactions.py + │ ├── payment_register.py + │ ├── payoff_strategy.py + │ ├── records_archive.py # NEW + │ ├── legal.py # now also Privacy Statement / Affiliate Disclosure + │ ├── donate.py # NEW (invoice.paid now records real-subscription payments as payment_kind=subscription) + │ ├── blog.py # NEW 2026-09-30 — public blog + admin API + promote_due scheduler + │ ├── subscribe.py # SitePay — paid subscription checkout + Customer Portal (see §0b) + │ ├── campaigns.py # admin email campaigns (see §0b) + │ ├── household.py, budget.py, milestones.py, import_statements.py # v2.1.12-2.1.20 + │ ├── roles.py, reminders.py, demo.py # Admin Roles v2, reminders admin, public calculator + │ ├── email_prefs.py # email preferences + unsubscribe (see §0b) + │ ├── support.py # NEW + │ ├── home.py # NEW 2026-10-11 - / and /index.html (Start Here) + 301 for /dashboard/about.html + │ ├── admin.py # now also settings/donations endpoints + │ └── devlog.py # now also deployments history + overdue alerts + └── static/ + ├── index.html + ├── register.html + ├── records-archive.html # NEW + ├── payoff-strategy.html + ├── help.html + ├── account.html + ├── (about.html removed 2026-10-11 - /dashboard/about.html now 301s to /; see §0e) + ├── contact.html # NEW + ├── donate.html # NEW + ├── donate-public.html # NEW + ├── donate-success.html # NEW + ├── donate-cancel.html # NEW + ├── shared.css + ├── shared.js + ├── site-scripts.js # NEW 2026-10-02 — single site-wide script loader (Umami etc.) + ├── reading-tracker.js # NEW 2026-10-02 — scroll-depth / engaged-time / article-read events + ├── household.html, budget.html, windfall.html, utilization.html, milestones.html, import.html # NEW since 2026-10-02 + ├── a11y.css, a11y.js, accessibility.html # NEW 2026-10-09 - see accessibility_standards.md + ├── favicon.svg + ├── cutthecard-*.png/.jpg # NEW — dark/light logo variants + ├── learn/ # NEW — public educational content + │ ├── index.html + │ ├── learn.css + │ ├── avalanche-vs-snowball.html + │ ├── extra-payments.html + │ ├── credit-utilization.html + │ ├── credit-card-interest.html + │ ├── minimum-payments.html + │ └── balance-transfer.html + └── admin/ + ├── accounts.html + ├── devlog.html + ├── donations.html # NEW + ├── revenue.html # NEW 2026-09-30 — combined revenue view + ├── blog.html # NEW 2026-09-30 — blog post list + ├── blog-editor.html # NEW 2026-09-30 — blog editor + ├── subscriptions.html # SitePay admin (tiles/columns added 2026-09-30) + ├── campaigns.html # email campaigns admin + └── support-requests.html # NEW +``` + +The `backup/api/` single-generation snapshot directory (inside the +Production project root, written/overwritten by `deploy_engine.py`) is +still present and unchanged in purpose — it now also contains the full +current source tree as of the last deployment (confirmed present in this +backup, same structure as `api/`). + +--- + +## 24. Payoff Methodology + +**Unchanged.** Single-account payoff (`payoff.calculate_payoff()`) and +cascading payoff (`payoff.calculate_payoff_ladder()`) logic re-confirmed +against this backup's `payoff.py` with no material differences from +prior documentation. + +--- + +## 25. Cache-Busting Rule — now inconsistently followed + +Prior documentation described a single site-wide marker. **As of this +backup that is no longer true** — see §4.3 for the actual current split +(`1.8.3` on 12 pages, `1.8.4` on 4 pages). The documented procedure +itself is unchanged and still correct as a policy; it just wasn't fully +followed on whichever change bumped the 4 pages to `1.8.4` (most likely +the donation/about/payoff-strategy work, given which pages are on the +newer marker): + +1. Increase the query-string version. +2. Update **all** HTML pages that reference `shared.css`/`shared.js`. +3. Deploy those files together. +4. Test QA. +5. Promote to Production. + +Recommend a cleanup pass that bumps every page to a single new marker +the next time `shared.css` or `shared.js` changes, rather than trying to +retroactively figure out which of the two current values is "more +correct." + +--- + +## 26. Known Issues / Required Follow-Up + +### Critical — acknowledged, deferred, tracked (see §0a) + +**`APP_SECRET_KEY` is still not explicitly set in Production, and the +same compose file now also contains live Stripe secret/publishable/ +webhook keys in plaintext.** This was first flagged when account-number +encryption was the only thing riding on `APP_SECRET_KEY`; it's now +higher-priority given the Stripe keys sitting alongside it. **The user +has acknowledged this (2026-09-15) and asked to circle back to it rather +than fix it immediately** — this is not being silently deferred. Per +§0a, re-remind the user about this every ~5 days (or the next time this +file is read, if more than 5 days have elapsed) until it's fixed or the +user explicitly says to abandon it. Once fixed, remove this callout and +the corresponding row in §0a's reminder table. + +Recommended next step, updated for the current stakes: + +1. Generate a strong Production secret: `openssl rand -hex 32`. +2. Move it — and the Stripe keys, which are equally sensitive — into the + project's approved secret-management system (Vaultwarden, referenced + the same way SMTP/DB credentials already are) rather than plaintext in + `debteliminator.yml`. +3. Configure `APP_SECRET_KEY` in Production; use a separate one in QA. +4. Recreate the containers. +5. Never rotate the Production `APP_SECRET_KEY` after encrypted account + numbers have been stored. +6. Consider whether the Stripe keys specifically warrant an env file + (`.env`, `docker compose --env-file`, `chmod 600`, excluded from any + future version-control or unencrypted-backup handling) rather than + living directly in the checked-in-style compose YAML, given they're + live payment-processing credentials rather than internal-service + credentials. + +### Open — confirmed, tracked (see §0a) + +- `routers/devlog.py` generates two manual-recovery/verification + instruction strings still hardcoded to `https://debt.kingdezigns.com` + — **confirmed stale** now that `cutthecard.net` is the confirmed + primary domain (§2a), not just possibly stale. Per §0a, keep + reminding until this — and any other stray `debt.kingdezigns.com` + reference found in code or docs — is scrubbed. +- `main.py`'s startup log line still says `"Starting CutTheCard v1.9.2"` + — out of sync with the actual `version="1.10.1"` field a few lines + above it. Cosmetic, no reminder needed, just worth a one-line fix + whenever someone's next in that file. +- Cache-busting marker inconsistency across pages (§4.3/§25). + +### New open items (2026-09-30) + +- **Revenue classification of grandfathered recurring donors.** The + `payment_kind` backfill and the `invoice.paid` rule classify by + `users.stripe_subscription_id`. Phase 2 links recurring *donors'* + subscriptions onto that column, so their **pre-conversion donation + history is reclassified as subscription revenue** and leaves the + Donations totals. If donation history must stay intact, restrict the + backfill/rule to payments on/after `subscription_launch_date` (not + implemented — needs a decision). +- **Ledger purity vs. the original Phase 3 docstring** (`subscribe.py` says + no Donation row is written) — now only true for the checkout-completed + step; revise that docstring when next in the file. +- **Revenue periods are UTC**, so a charge made late on the last day of a + month in US time can land in the next UTC month. Acceptable for now; + note when reconciling against Stripe's dashboard. +- **Blog:** archived versions are indexable and self-canonical (chosen so + old URLs keep resolving); if duplicate-content dilution appears in Search + Console, switch archived canonicals to the current version. +- **Doc reconciliation debt:** SitePay and Email Campaigns need a full + §-level write-up from source (§0b is summary only). `main.py` version + string (1.10.1) and startup log (v1.9.2) are stale relative to DevLog + v2.1.3. + +### New open items (2026-10-02) + +- **Privacy Statement needs an analytics disclosure** (first-party, cookie-free, + page-level only including inside the app; no financial data, no identity). + Legal review; publishing a new version triggers the re-acceptance gate for + all users, so bundle with another legal change if possible. +- **Verify custom reading events in production** (see §12h Status). +- **Doc reconciliation debt:** DevLog v2.1.4–2.1.7 contents are not itemized + (§0c); SitePay/Email Campaigns still summary-level (§0b). +- **In-flight demo pages** are not documented and are untagged unless added + to the loader tag set (`apply_site_scripts.py <app-dir> static/<page>.html`). +- Optional: separate "CutTheCard QA" Umami website so the loader can be tested + in QA; CTA click events for funnel measurement. + +### New open items (2026-10-11) + +- **Nav Phase 2** (merge similar pages) not started; Phase 1 (§8b) is in QA, Production promotion unconfirmed. Log it in the DevLog (queue item "Nav grouping" is still pending). +- **Run `a11y_audit.py` and the manual screen-reader pass** for the new nav and the Household page before Deploy to Prod (§8b, `accessibility_standards.md`). +- **Doc reconciliation debt:** v2.1.4-2.1.20 features are summary-level (§0d, §12i-12j). `main.py` version string (1.10.1) and startup log (v1.9.2) are stale. +- **Household:** confirm how "paid plan" is enforced for owners, and include Household in the Privacy Statement review (members' access to an owner's records and the activity log are personal-data processing). +- **Backups:** the v2.1.20 archive is a **QA** backup; the standing backup script is Production-only. Note which environment each archive covers when filing it. +- **Cache markers:** unify `blog.py` / public calculator page (`?v=1.9.2`) with the app pages (`?v=1.9.5`) at the next `shared.*` change. +- `APP_SECRET_KEY` is also unset in the QA compose file (§0a). + +### New open items (2026-10-11, home page swap) + +- **Confirm QA deployment** of `home-page-swap-v2.1.22.tar.gz`, then promote via Deploy to Prod; create/attach the DevLog item (the package label v2.1.22 is an assumption - use whatever version the Dev Log assigns). +- **Run `a11y_audit.py` and the manual keyboard/screen-reader pass on the new Start Here page** (and on the signed-out view at `/`) before Deploy to Prod. +- Delete the orphan `static/about.html` from Production after the deploy (optional; the 301 route takes precedence). +- Watch Search Console for the `/` canonical move and the retired `/dashboard/about.html` URL. +- Signed-out visitors see only the login/marketing overlay at `/` - the Start Here copy is in the page but hidden until sign-in (same behaviour About had). Consider whether crawlers should see it. + +### Carried forward, still accurate + +- Automated pipeline first-use recommendations (verify docker CLI/mounts + before trusting a `models.py`/`Dockerfile`-touching deployment; always + review the preview diff). +- Backup coverage: the dedicated Debt Eliminator backup still protects + **Production only** — QA recovery still requires a separate strategy. + +### Needs a decision, not a bug + +- **Affiliate program** (§12c) — disclosure page is live, actual + affiliate links are still an unversioned queue item. Don't let the two + drift further apart than necessary (a disclosure page for a program + that isn't running yet is fine short-term, but worth revisiting if it + sits open a long time). + +--- + +## 27. Version / Feature History + +### DevLog production deployment history — additions since v2.0.3 + +| DevLog version | Date deployed | Production task(s) | +|---|---|---| +| v2.0.4 | 2026-09-04 | New logo added to site; logo bug fix | +| v2.0.5 | 2026-09-04 | Accounts Deck + Debt Reduction Plan layout/styling enhancement | +| v2.0.6 | 2026-09-05* | About CutTheCard page; login screen marketing message + layout | +| v2.0.7 | 2026-09-07 | Donation link text update; **Stripe Donation Integration** | +| v2.0.8 | 2026-09-07 | Suspend & Delete My Account (self-service) | +| v2.0.9 | 2026-09-07 | Recurring/subscription donation option | +| v2.0.10 | 2026-09-08 | `support@cutthecard.net` mailbox; Privacy Statement (US-based only) | +| v2.0.11 | 2026-09-08 | Phase 1 — SEO Foundation & Search Engine Accessibility | +| v2.0.12 | 2026-09-09 | Phase 2 — Educational Content & SEO Growth (Learning Center) | +| v2.0.13 | 2026-09-09 | Log donation data (structured `donations` table) | +| v2.0.14 | 2026-09-09 | Learning Center links added to the login page | +| v2.0.15 | 2026-09-09 | Affiliate Disclosure page (legal document) | +| v2.0.16 | 2026-09-09 | Admin — View Donation Log | +| v2.0.17 | 2026-09-10 | Dev Log — collapsed/last-5 release display; Records Archive (.xlsx/.docx year-end export) | +| v2.0.18 | 2026-09-10 | Support/Assistance form added to Help Center | +| v2.0.19 | 2026-09-12 | Dark vs. Light theme, per-user + admin default | + +\* v2.0.2 shows a later `deployed_at` timestamp (2026-09-05) than +v2.0.3–v2.0.6 in the raw DevLog table, which is an out-of-order artifact +in the source data itself (deploy timestamps not monotonic with version +numbers around that range) — noted here rather than silently +"corrected," since it reflects the actual DevLog record. + +### Application source milestones — additions since 1.9.5 + +| App version | Features | +|---|---| +| 1.9.5–1.10.0 | Stripe donations (one-time + recurring), donor tracking on `User` | +| ~1.10.1 (current) | Self-service suspend/delete, Privacy Statement, Affiliate Disclosure, SEO foundation + Learning Center, Records Archive export, Support/Contact form, Dev Log assignment/due-date/overdue-alerts + deployment history, dark/light theme | + +(Exact per-version app-source mapping wasn't preserved with the same +granularity as the 1.7.0–1.9.5 range in prior documentation — the DevLog +production history table above is the more reliable source for "what +shipped when" going forward.) + +--- + +## 28. Current Backup Audit — 2026-09-15 + +The 2026-09-15 archive (`debteliminator-v2.0.19-backup-2026-09-15_00-00-01.tar.gz`) +contains: + +- Production application files, including all new modules + (`seo_router.py`, `routers/donate.py`, `routers/support.py`, + `routers/records_archive.py`) alongside the previously-documented + `deploy_engine.py`, `balance_transfer.py`, `interest_engine.py` +- Production PostgreSQL dump +- MANIFEST (host `kingdezigns16`, source `/Kingdezignsnas16/ + debteliminator`, destination `/export/kingdezignsnas-16/Public/07 - + Projects/NAS16/debteliminator`) +- Docker Compose configuration (`debteliminator.yml`, + `debteliminator.env`, `compose.override.yml`) — `debteliminator.env` + and `compose.override.yml` are both currently empty templates (OMV + boilerplate only); all real configuration lives in `debteliminator.yml` +- A `backup/api/` single-generation deploy-engine snapshot, structurally + parallel to the live `api/` tree +- 20 static HTML/asset files under `api/app/static/` (up from 7 + previously), including the full `learn/` subtree and new logo variants + +The database confirms the latest deployed DevLog version is **v2.0.19**. +The source confirms the application reports **1.10.1**. The frontend +cache marker is **split between 1.8.3 and 1.8.4** (§4.3) rather than a +single value. The backup is internally consistent once these version +namespaces — and the cache-marker split — are understood. + +--- + +## 29. Summary for AI Systems + +- Debt Eliminator / CutTheCard runs on **NAS16 / VLAN 50 / 192.168.150.40**. Production port **8002**, QA port **8003**, unchanged. +- **Public branding has moved to `cutthecard.net` — confirmed for both environments.** Production is `https://www.cutthecard.net`; QA is `https://debt.qa.cutthecard.net`. NPM on HAS and Dreamhost DNS have both been updated for both hostnames. `cutthecard.org` redirects to `cutthecard.net` at Dreamhost only, not in NPM. `debt.kingdezigns.com` and `debt.qa.kingdezigns.com` are deprecated — stray references to either (in this doc set and in `routers/devlog.py`'s generated text) are tracked in §0a until fully scrubbed. +- DevLog deployed version is now **v2.0.19** (was v2.0.3); application source is now **1.10.1** (was 1.9.5); the frontend cache marker is **no longer a single value** — split between 1.8.3 and 1.8.4 across pages. +- Major feature additions since the last reconciliation: **Stripe donations** (one-time + recurring, structured `donations` table, admin log, anonymous public donate page), **Support/Contact request form** (public, 48h SLA, admin queue), **self-service account suspend/delete**, **Privacy Statement + Affiliate Disclosure** legal documents (affiliate links themselves not yet live), **Records Archive** (.xlsx/.docx year-end export with a derived delinquency heuristic), **SEO foundation + public Learning Center** (six educational articles, robots.txt/sitemap.xml), and **dark/light theme**. +- Dev Log gained **assignment/due-date/on-hold** fields on queue items, a **weekly overdue-item alert email** (fires every 7 days regardless of `APP_ENV`), a **permanent deployment-history table** (`deployment_records`, separate from the single-generation file snapshot), and a **default-collapsed "last 5 releases" view**. +- New Python dependencies: `stripe`, `openpyxl`, `python-docx` — require an image rebuild on first deploy to an environment that doesn't already have them. +- **`APP_SECRET_KEY` is still not set in Production** — was already a known issue, now more urgent because **live Stripe secret/publishable/webhook keys are also stored in plaintext in the same Production compose file**. User has acknowledged and deferred this (2026-09-15) — see the standing reminder in §0a, and re-surface it every ~5 days until resolved. +- Minor stale references found and worth a quick fix: `devlog.py`'s generated manual-recovery instructions still hardcode `debt.kingdezigns.com`; `main.py`'s startup log line still says `v1.9.2` instead of matching the real `1.10.1` app version. +- The dedicated Debt Eliminator backup still covers **Production only** (not QA) — unchanged. +- **2026-09-30:** DevLog is **v2.1.3**. New: **Blog Engine** (`/blog`, `/blog/archive`, `/blog/{slug}`; revisions each have their own URL/slug; Preview/Schedule/Publish/Archive/Unpublish; scheduling via `promote_due()` lazily + 60 s background worker; images in PostgreSQL; HTML sanitized at render; admin UI under `/dashboard/admin/blog*.html`), **`donations.payment_kind`** unified revenue ledger, **Subscriptions admin tiles/pills/per-user amounts/year selector + Sync Payments from Stripe**, and **Admin → Revenue** combined page. SitePay and Email Campaigns exist in the code but are documented at summary level only (§0b). +- Open: `APP_SECRET_KEY` still unset in Production (overdue reminder, §0a); grandfathered-donor revenue reclassification decision (§26). +- **2026-10-02:** Production backup seen is **DevLog v2.1.7** (v2.1.4–2.1.7 not itemized). New: **site-wide script loader** — every page carries one `<script defer src="/dashboard/site-scripts.js?v=1">`; scripts are added/changed only in `static/site-scripts.js`. It loads **Umami** (self-hosted at `stats.cutthecard.net`, see `server_umami.md`) and, on pages with an `<article>`, `reading-tracker.js` (`scroll-depth`, `engaged-time`, `article-read`). Admin pages are never tracked; only production hostnames report (QA is null); Do Not Track / Global Privacy Control honored; Stripe-return pages have query/hash stripped; tracking is page-level only with no `identify()`. Blog gets it via `routers/blog.py` `_page()` (skipped for noindex/preview pages). Open: Privacy Statement disclosure, confirm custom events, document the in-flight demo. +- **2026-10-11:** DevLog is **v2.1.20** (from the QA backup). Since v2.1.7: Admin Roles v2, public Demo Calculator, Debt Reduction Plan tuning + balance-transfer triggers, Milestones, Windfall Allocator, CSV/Statement Import (in memory, nothing stored), WCAG 2.2 AA accessibility layer, due-date/promo-expiry reminders, Credit Utilization, Budget-to-Payoff, blog auto-archive/rotation, and **Household Sharing** (owner invites by email as view/edit; member "switches into" the owner's data via `get_data_user()`; members never see full account numbers, billing, profile, Budget or manage members; owner-visible activity log; sharing is a paid-plan feature per Help Center text). Details are summary-level (§0d, §12i-12j). +- **Sidebar nav is grouped (Phase 1, §8b):** Accounts | Track (Payment Register, Import Transactions, Budget) | Plan (Debt Reduction Plan, Windfall Allocator, Credit Utilization, Milestones) | Learn (Learning Center, Blog) | Help (Help Center, Contact / Support) | Account (My Profile, Household, Subscription, Records Archive); admin groups People / Money / Content + Dev Log. Accordion, active group open, real `<button>`s with `aria-expanded`. About CutTheCard is in the sidebar footer; Free Calculator is logged-out only. Edit `DE_NAV_ALL` / `DE_NAV_ADMIN` in `shared.js` to add pages. Cache marker is `?v=1.9.5`. Phase 2 (merge similar pages) not started. +- **2026-10-11 Home Page Swap (§0e):** the old About page is now the home page ("Start Here") at `/` and `/index.html`; `/` no longer redirects to `/dashboard/`; Accounts stays at `/dashboard/index.html`; `/dashboard/about.html` 301s to `/`; sign-in from an entry page lands on `/`; logo and sidebar footer ("Start Here") point to `/`; steps section moved above "How CutTheCard Helps You Win"; hero shortened. Source `public_pages/home.html` + `routers/home.py`. Cache marker now `?v=1.9.6`. Restart-only deploy. +- **STANDING RULE (§3a-0):** every delivery of files must OPEN with the SCP -> `sudo cp` -> `sudo docker restart debteliminator_qa_api` command block (real file names and QA paths, `sudo rm` for deletions, restart-vs-rebuild stated, verification lines), before any explanation. Mandatory every time, even for one-file changes and follow-up revisions. +- Never document actual production passwords, SMTP passwords, database passwords, encryption keys, session secrets, or Stripe keys. diff --git a/server_fundtracker.md b/server_fundtracker.md index e982553..f7363e0 100644 --- a/server_fundtracker.md +++ b/server_fundtracker.md @@ -1,10 +1,10 @@ # Fund Tracker — Multi-Profile Mutual Fund & Stock Tracking Service Device Type: **Docker Container (hosted on NAS16)** -Containers: **fundtracker_api**, **fundtracker_db** +Containers: **fundtracker_api**, **fundtracker_db** (production) / **fundtracker_qa_api**, **fundtracker_qa_db** (QA) IP Address: **192.168.150.40** (shares NAS16's host IP) VLAN: **50 — Lab / Servers** -Last Updated: 2026-08-19 +Last Updated: 2026-10-11 --- @@ -16,214 +16,485 @@ It is **not** a data source or execution platform — it pulls public price hist --- ## 🌐 Public Access + +### Production - **Domain:** `https://funds.kingdezigns.com/` - **Proxy:** NPM on HAS (192.168.150.30) → `192.168.150.40:8000` -- **SSL:** Force SSL enabled, Let's Encrypt via NPM — same pattern as every other public KingDezigns service -- **Internal LAN access:** `http://192.168.150.40:8000/dashboard/` (unchanged, still works from VLAN 20) -- No CrowdSec/Fail2Ban changes were required — traffic proxied through NPM inherits the same protection (CrowdSec reads NPM's logs regardless of backend) as every other service behind it. +- **SSL:** Force SSL enabled, Let's Encrypt via NPM +- **Internal LAN access:** `http://192.168.150.40:8000/dashboard/` + +### QA +- **Domain:** `https://funds.qa.kingdezigns.com/` +- **Proxy:** NPM on HAS (192.168.150.30) → `192.168.150.40:8001` +- **SSL:** Force SSL enabled, Let's Encrypt via NPM +- **Internal LAN access:** `http://192.168.150.40:8001/dashboard/` + +No CrowdSec/Fail2Ban changes were required — traffic proxied through NPM inherits the same protection as every other service behind it. + +--- + +## 🔀 QA → Production Deployment Workflow (v1.8.0+) + +All changes follow a structured deployment path. **No changes are ever made directly to production as a development workflow.** + +``` +DEVELOPMENT + ↓ +QA (funds.qa.kingdezigns.com) + ↓ +Test / Verify in QA + ↓ +1. cp files to Production + docker restart fundtracker_api +2. Verify the site works +3. Click "Deploy to Prod" in the Dev Log on the QA site + → auto-syncs DevLog records to prod DB + → nav version updates for all users +``` + +**Critical order:** always copy files and restart FIRST, then click Deploy to Prod. If you click Deploy to Prod before copying files, the nav will show the new version number while the old code is still running. + +### Promoting a tested QA version to Production + +```bash +# Copy changed files (adjust list to what actually changed) +sudo cp /Kingdezignsnas16/fundtracker-qa/api/app/config.py /Kingdezignsnas16/fundtracker/api/app/config.py +sudo cp /Kingdezignsnas16/fundtracker-qa/api/app/main.py /Kingdezignsnas16/fundtracker/api/app/main.py +sudo cp /Kingdezignsnas16/fundtracker-qa/api/app/routers/devlog.py /Kingdezignsnas16/fundtracker/api/app/routers/devlog.py +sudo cp /Kingdezignsnas16/fundtracker-qa/api/app/static/admin/devlog.html /Kingdezignsnas16/fundtracker/api/app/static/admin/devlog.html +sudo docker restart fundtracker_api +``` + +Then verify: +```bash +curl https://funds.kingdezigns.com/health +# → {"status":"ok","app_env":"production"} +sudo docker logs fundtracker_api --tail 15 +``` + +Then click **Deploy to Prod** in the Dev Log on the QA site — this simultaneously marks the project as prod-deployed in the QA database and syncs the DevLog records to the production database. + +### Post-promotion verification checklist +- `app_env: production` in `/health` response +- Scheduler registered in logs: `Added job "sync_and_report"` and `Scheduler started (APP_ENV=production)` +- No QA banner visible on the production site +- Production site loads and functions normally +- Nav footer shows the new version number --- ## 🖥️ Architecture ### Stack -- **API:** FastAPI (Python 3.12), Docker container `fundtracker_api` -- **Database:** PostgreSQL 16 (Alpine), Docker container `fundtracker_db`, bind-mounted at `/opt/fundtracker/pgdata` +- **API:** FastAPI (Python 3.12), Docker container `fundtracker_api` (prod) / `fundtracker_qa_api` (QA) +- **Database:** PostgreSQL 16 (Alpine), separate containers and storage per environment - **Frontend:** Vanilla HTML/JS/CSS (no build step), served directly by FastAPI's `StaticFiles` mount at `/dashboard/` -- **Scheduler:** APScheduler, in-process (not an OMV Scheduled Job) — runs the daily sync + report job inside the `fundtracker_api` container itself -- **Market data:** Yahoo Finance via the `yfinance` library, using a `curl_cffi` session with Chrome browser impersonation (see Known Issues below — this is required, not optional) +- **Scheduler:** APScheduler, in-process — runs the daily sync + report job inside the API container (production only; disabled in QA) +- **Market data:** Yahoo Finance via the `yfinance` library, using a `curl_cffi` session with Chrome browser impersonation (required — Yahoo's bot detection blocks the default HTTP client) + +### Environment Configuration (v1.7.0+) + +A single authoritative environment flag controls all environment-specific behaviour: + +| Setting | Production | QA | +|---|---|---| +| `APP_ENV` | `production` | `qa` | +| Automatic stock sync | ✅ Enabled | ❌ Disabled | +| Scheduled emails | ✅ Enabled | ❌ Suppressed | +| Manual stock sync endpoint | Available | Available | +| QA banner in UI | Absent | ✅ Amber banner | +| `/api/env-info` endpoint | `is_qa: false` | `is_qa: true` | +| DevLog sync to prod DB | ❌ Not available | ✅ Available (via `PROD_DATABASE_URL`) | + +**`APP_ENV` is the only flag.** There are no `IS_DEV`/`IS_PROD` split flags — any unrecognised value defaults to `production` so the live site can never be left in a broken state. + +### Email behaviour in QA +- `send_email()` in `mailer.py` accepts a `force` parameter (default `False`) +- Automatic/scheduled sends return `False` silently in QA without touching SMTP +- Explicit manual actions (password reset) use `force=True` and still deliver +- Any QA email that does send has `[QA TEST]` prepended to the subject ### Data model — shared securities, private watchlists The core design decision: **security data is shared across all profiles, personal data is private.** | Concept | Table | Shared or private | Contains | |---|---|---|---| -| Security | `instruments` | **Shared** — one row per ticker, regardless of how many profiles track it | ticker, name, category, group tag, price history (via `price_points`), benchmark link | -| Watchlist entry | `watchlist_entries` | **Private** per profile | is_held, held_since, cost_basis — a profile's personal relationship to a shared security | -| Metric snapshot | `metric_snapshots` | Shared (security-level) | Daily-recorded quality/opportunity/combined/rebound scores, used for trend detection | -| Settings | `settings` | Private per profile | Currently just each profile's rebalance date | - -**Practical effect:** if two profiles both track GOOGL, its price history is synced exactly once and shared instantly between them — adding a ticker someone else already tracks is immediate, no re-sync wait, no duplicate Yahoo API traffic. Only `is_held`/`cost_basis`/which-tickers-you-track are private; ticker, name, group, and all performance scores are identical for every profile tracking that security. +| Security | `instruments` | **Shared** — one row per ticker | ticker, name, category, group tag, price history, benchmark link | +| Watchlist entry | `watchlist_entries` | **Private** per profile | is_held, held_since, cost_basis | +| Metric snapshot | `metric_snapshots` | Shared (security-level) | Daily-recorded quality/opportunity/combined/rebound scores | +| Settings | `settings` | Private per profile | Each profile's rebalance date | ### Multi-profile auth -- Session-cookie based (httponly, `SameSite=Strict`), **not** JWT-in-localStorage — a cookie can't be read by injected JavaScript, meaningfully reducing XSS token-theft risk for a public-facing app +- Session-cookie based (httponly, `SameSite=Strict`), **not** JWT-in-localStorage - Passwords hashed with `bcrypt` - 5 failed login attempts locks the account for 15 minutes - Forced password change on any seeded or admin-created account — cannot be skipped -- Admin role can create/delete/promote accounts, force password resets, and view the anonymized cross-profile Census (see below) — but is **not** shown other profiles' actual holdings or cost basis by design +- Admin role can create/delete/promote accounts, force password resets, and view the anonymized cross-profile Census --- ## 📊 Scoring Methodology -All scores are computed from price history only (no fundamentals data). Four are per-security (shared, identical for every profile); one is per-holding (private). +All scores are computed from price history only (no fundamentals data). ### Quality score (0–100) -Long-run risk-adjusted strength, deliberately blind to short-term noise: +Long-run risk-adjusted strength: - 35% annualized Sharpe ratio -- 20% annualized Sortino ratio (downside-only volatility) +- 20% annualized Sortino ratio - 25% CAGR -- 20% consistency (% of historical rolling windows, of the selected length, that were positive) +- 20% consistency (% of historical rolling windows that were positive) -Requires 30+ price points to compute; below that, returns null rather than a misleading number. +Requires 30+ price points; below that returns null. ### Opportunity score (0–100) -`0.6 × quality + 0.4 × depressed-ness`. Depressed-ness requires **both** of the following to agree (via `min()`, not an average) — this was a deliberate fix after an early version let a low-volatility fund sitting exactly at its 52-week high still score as a strong "opportunity" purely on quality alone: -1. `current_return_zscore` — is the current rolling-window return unusual *for this specific security's own history* -2. `drawdown_from_52wk_high_pct` — is it actually below its recent peak, not just statistically unusual +`0.6 × quality + 0.4 × depressed-ness`. Depressed-ness uses `min()` of: +1. `current_return_zscore` — is the current rolling return unusual for this security's own history +2. `drawdown_from_52wk_high_pct` — is it actually below its recent peak ### Combined score (0–100) -Harmonic mean of quality and opportunity (not a plain average) — deliberately punishes imbalance, so a security only scores high here if it's strong on **both** axes, not exceptional on one while mediocre on the other. +Harmonic mean of quality and opportunity — punishes imbalance. -### Rebound score (0–100) — the core "proven leader, currently crashed" signal -Answers a different question than opportunity score: *does this security normally rank near the top of its peer group by raw return, and has it recently fallen hard in that ranking?* Reconstructed retroactively from price history already on file (no waiting for new data to accumulate) by: -1. Computing every security's rolling-window return, for every date, within its shared group tag (e.g. all `STOCK`-tagged securities) -2. Ranking them against each other on every date → a full history of peer-relative percentile rank per security -3. Comparing today's percentile to the security's own historical average percentile -4. Combining "how strong is it historically" and "how far has it fallen right now" via harmonic mean, same imbalance-punishing logic as combined score - -Requires a peer group of 5+ securities sharing the same group tag to compute at all. +### Rebound score (0–100) +Does this security normally rank near the top of its peer group by raw return, and has it recently fallen hard in that ranking? Requires a peer group of 5+ securities sharing the same group tag. ### Buy / Sell / Hold signal (held positions only) -A simple, explainable, threshold-based heuristic — not a black box, and explicitly documented as a screening aid rather than a trade instruction: -- **SELL** if quality has fallen below 40, or dropped 15+ points in the trailing 7 days, or the position is deeply below its own normal range with no rebound signal backing it up -- **BUY** (add to position) if opportunity ≥ 65 with quality ≥ 60, or rebound score ≥ 65 -- **HOLD** otherwise - -Trend-based triggers (the 7-day quality delta) only become meaningful once daily snapshots have accumulated for about a week post-deployment — this is a genuine cold-start limitation, not a bug. +Simple threshold-based heuristic — screening aid, not a trade instruction. ### Quality lookback (adjustable, default 3 years) -All of the above can be restricted to a trailing window (6mo/1yr/2yr/3yr/5yr/all) rather than always using full history. This matters: a fund that compounded fast for several early years and has since flattened out will look artificially strong if scored on all-time history — the early years hide what it's actually doing now. Verified with a synthetic test: a fund with 4 strong years then 1 flat year scored 84.6 quality on all-history, 25.9 restricted to the trailing year. +All scores can be restricted to a trailing window (6mo/1yr/2yr/3yr/5yr/all). + +--- + +## 📋 Dev Log — Auto-Versioning System (v1.8.0) + +### Overview +The Dev Log tracks all projects through a QA → Production pipeline with automatic version assignment. Versions are never manually entered — they are calculated and assigned at deployment time. + +### Update Types +| Type | Version Bump | Use For | +|---|---|---| +| Minor | +0.0.1 | Normal incremental changes | +| Major | +0.1.0 | Larger feature / functionality changes | +| Platform | +1.0.0 | Significant platform-level changes | +| No Version | no bump | Changes that should not count as a version (hotfixes, config tweaks) | + +### Lifecycle +``` +Create Project (select update type) + ↓ +Queue (no version assigned yet) + ↓ +Deploy to QA → version auto-assigned based on update type + current highest version + ↓ +QA column (grouped by version, collapsible cards) + ↓ +Deploy to Prod → same version used, DevLog records auto-synced to prod DB + ↓ +Production column +``` + +### Nav version behaviour +- The nav footer version updates **only when a project is deployed to Production** — not on QA deploy +- This is intentional: the nav reflects what is actually live in production, not what's in QA +- The Dev Log page shows both the current QA version and Production version in the env info bar at the top + +### DevLog DB sync (QA → Production) +- **Automatic per-project sync:** clicking "Deploy to Prod" in the Dev Log auto-syncs that project's version row and task row to the production database — no manual SQL needed +- **One-time bulk sync:** `POST /admin/devlog/sync-to-prod` — available via the "↑ Sync DevLog to Prod DB" button visible on the Dev Log page in QA only. Safe to run multiple times (upserts by version_number and title+created_at) +- Sync is **non-fatal** — if the prod DB connection fails, the QA-side deploy still succeeds and an error is logged + +### Docker network configuration (required for sync) +The QA API container must be on the same Docker network as the production DB container. Configured in the QA compose file: + +```yaml +# In qa_api service: +networks: + - default + - fundtracker_prod + +# At bottom of compose file: +networks: + fundtracker_prod: + external: true + name: fundtracker_default +``` + +`PROD_DATABASE_URL` in the QA compose environment points at the production DB by container name: +``` +PROD_DATABASE_URL=postgresql+psycopg2://fundtracker:Valerie8545@fundtracker_db:5432/fundtracker +``` + +Production compose does **not** have `PROD_DATABASE_URL` — sync endpoints return 503 in production by design. + +### Dev Log API endpoints +| Endpoint | Purpose | +|---|---| +| `GET /admin/devlog/projects` | List all projects | +| `POST /admin/devlog/projects` | Create project (queue entry) | +| `PATCH /admin/devlog/projects/{id}` | Edit title, category, update_type, notes, status | +| `DELETE /admin/devlog/projects/{id}` | Delete (queue only — cannot delete deployed projects) | +| `POST /admin/devlog/projects/{id}/deploy-qa` | Assign next version + deploy to QA | +| `POST /admin/devlog/projects/{id}/deploy-prod` | Promote to Production + auto-sync to prod DB | +| `POST /admin/devlog/projects/{id}/undeploy-qa` | Roll back QA deployment | +| `POST /admin/devlog/projects/{id}/undeploy-prod` | Roll back Production deployment | +| `POST /admin/devlog/sync-to-prod` | Bulk sync all DevLog data to prod DB (QA only) | +| `GET /admin/devlog/versions` | List all versions | +| `PATCH /admin/devlog/versions/{id}` | Edit version label/notes | +| `GET /admin/devlog/deployed` | Current production version (used by nav footer) | +| `GET /admin/devlog/qa-version` | Current QA version | --- ## 🔐 Admin Features ### Census (anonymized cross-profile leaderboard) -`Admin → Census` page. Aggregates every tracked security across **all** profiles, showing how many profiles track it and its shared performance scores — deliberately does **not** reveal which specific profile tracks what, consistent with the private-watchlist design above. +`Admin → Census` page. Aggregates every tracked security across all profiles — does not reveal which specific profile tracks what. ### Legal document versioning -Two independently-versioned, admin-editable documents, stored in the database: -- **Terms of Use** — gated immediately after login, blocks all dashboard access until accepted -- **Investment Disclaimer** — gated specifically before adding any ticker to a watchlist (not a one-time login gate) +Two independently-versioned, admin-editable documents: +- **Terms of Use** — gated immediately after login +- **Investment Disclaimer** — gated specifically before adding any ticker -Publishing a new version (`Admin → Accounts → Legal documents`) **immediately** requires every profile to re-accept before continuing — acceptance is tracked per specific version number, so a version bump is itself the "flag everyone to re-agree" mechanism, no separate manual flag needed. An admin can also force one specific account to re-accept without republishing for everyone. - -> **Not a substitute for actual legal review.** The shipped default text is comprehensive boilerplate covering no-liability-for-losses, educational-use-only, no-fiduciary-relationship, and indemnification — drafted carefully, but worth having an attorney glance at given this is a public-facing tool touching real investment decisions. +Publishing a new version immediately requires every profile to re-accept. --- -## 💼 Portfolio / Transaction Tracking (added, undated prior session — first documented here 2026-08-19) +## 💼 Portfolio / Transaction Tracking -In addition to the shared-security screening/scoring system described above, Fund Tracker also includes a full **buy-lot/sale/split transaction register** per profile — this had been built in an earlier session but was never previously written up in this file. It lives alongside (not instead of) the scheduler, pricing/NAV sync, auth, admin functionality, settings, and watchlist behavior documented elsewhere in this file. +Full buy-lot/sale/split transaction register per profile. ### Data model -- **Buy lots** — each purchase is its own row: original quantity, remaining quantity, buy price, buy fees, notes/source. Selling from a lot reduces its remaining quantity but the lot itself is never deleted. -- **Sales** — recorded as their own rows, linked to the buy lot(s) they draw down via **sale allocations**, so the relationship between a sale and the lot(s) it consumed is preserved. -- **Matching methods** — FIFO, LIFO, and Specific Lot Identification (user picks exact per-lot quantities, validated to sum to the total sold) are all supported at time of sale. -- **Lot status** — `ACTIVE` (untouched), `PARTIAL` (some shares sold, some remain), `CLOSED` (fully sold) — a closed lot stays visible in the register rather than disappearing, preserving full history. -- **Stock splits / reverse splits** — a recorded split only adjusts share count and per-share cost basis on lots that were **active and purchased before** the split date. Lots purchased on/after the split date, and lots already fully sold before the split date, are left untouched. +- **Buy lots** — each purchase is its own row: original quantity, remaining quantity, buy price, buy fees, notes/source +- **Sales** — linked to buy lot(s) via sale allocations; FIFO, LIFO, and Specific Lot Identification supported +- **Lot status** — `ACTIVE`, `PARTIAL`, `CLOSED` +- **Stock splits** — only adjusts lots active and purchased before the split date ### Key endpoints | Endpoint | Purpose | |---|---| | `GET /portfolio/holdings` | Active holdings dashboard view | -| `GET/POST /portfolio/lots/{ticker}` | List / create buy lots for a ticker | -| `PATCH /portfolio/lots/{lot_id}` | Edit a buy lot — only allowed while it has zero sale allocations (see locking, below) | -| `DELETE /portfolio/lots/{lot_id}` | Delete a buy lot (same zero-allocation restriction) | -| `GET/POST /portfolio/sales` | List / record sales (FIFO/LIFO/Specific ID) | -| `DELETE /portfolio/sales/{sale_id}` | Delete a sale — **restores** the allocated quantity back to the affected buy lot(s), which also unlocks them for editing | +| `GET/POST /portfolio/lots/{ticker}` | List / create buy lots | +| `PATCH /portfolio/lots/{lot_id}` | Edit a buy lot (zero-allocation only) | +| `DELETE /portfolio/lots/{lot_id}` | Delete a buy lot (zero-allocation only) | +| `GET/POST /portfolio/sales` | List / record sales | +| `DELETE /portfolio/sales/{sale_id}` | Delete a sale — restores allocated quantity to lot(s) | | `GET/POST /portfolio/splits` | List / apply stock splits | -| `GET /portfolio/register` | The full buy-lot register: each lot with its associated sale allocations, current price, unrealized G/L, realized G/L, and status — this is what the Portfolio page renders | -| `POST /portfolio/import/csv` | Bulk import buys/sells from pasted CSV text | +| `GET /portfolio/register` | Full lot+sale register view | +| `POST /portfolio/import/csv` | Bulk import from CSV | -### Editing & locking -A buy lot can be edited or deleted only while it has **no** sale allocations against it — once a sale references a lot, that lot locks (shown as 🔒 in the UI) to protect the historical/tax record. The recovery path is to delete the associated sale first (which restores the shares to the lot), then edit/delete the now-unlocked lot. - -### Portfolio UI — three-level collapsible hierarchy (updated 2026-08-19) -The Portfolio page (`/dashboard/portfolio.html`) renders the register as **Ticker → Buy Lot → Sale(s)**, both levels collapsible: - -- **Ticker rows** — one row per ticker held, **collapsed by default** on page load. Clicking the row's twistie (▶/▼) expands it to reveal that ticker's individual buy lots. This was the 2026-08-19 change — previously every buy lot for every ticker rendered at once, making the register long and hard to scan. -- **Buy lot rows** — nested under their ticker once expanded. Each lot that has associated sales shows its own twistie (e.g. `▶ 2`) which expands to reveal the sale row(s) consumed from that specific lot. This twistie already existed prior to 2026-08-19 and was left unchanged. -- Expanding a ticker does not auto-expand its lots' sale twisties, and collapsing a ticker hides its lots' sale rows regardless of their own expand/collapse state — the two levels are independent, but a lot's sales can only ever be visible while its parent ticker is also expanded. -- Implementation notes: both expand states are tracked client-side only (`_expandedTickers` and `_expanded` JS `Set`s in `portfolio.html`), not persisted to the backend or across page reloads. Toggling is done via direct DOM show/hide rather than a full table re-render, so toggling one ticker/lot does not disturb the expand state of others. -- **Deployment note:** this was a frontend-only change to `api/app/static/portfolio.html` — no router, schema, or model changes. Deployed via the standard code-only pattern: file copied to a `/tmp` scratch path via `scp`, moved into `/Kingdezignsnas16/fundtracker/api/app/static/` with `sudo cp` (the project directory is root-owned), then `sudo docker restart fundtracker_api` (plain restart is sufficient since `app/` is bind-mounted — no rebuild needed for a static-file-only change). - -### Known deployment gotchas (from earlier portfolio build work — kept here to avoid repeating) -- `models.py` has previously broken from using `Decimal` or `CheckConstraint` without importing them — always verify imports after any model change before restarting the container. -- Files transferred from a stale `/tmp` copy have previously overwritten newer code (e.g. an old portfolio router missing the `register` endpoint) — always confirm the source file being copied is the actual latest version, not a leftover scratch copy. -- `BuyLotEdit` (in `schemas.py`) has previously been referenced by `portfolio.py` before being defined — a reminder that schema and router changes need to land together, not the router first. -- General rule reaffirmed: after any deploy, check container startup logs, hit `/health`, then explicitly test the specific endpoint/UI behavior that changed — don't assume a clean restart means the change is live and correct. - -### Admin — user account email management -Two admin endpoints exist for managing account emails, separate from the Census/legal-document admin features described above: -``` -PATCH /admin/users/{id}/email -GET /admin/users/{id}/email-changes -``` -Email changes are logged in an audit trail that requires a reason at time of change. +### Portfolio UI — three-level collapsible hierarchy +**Ticker (collapsed by default) → Buy Lot → Sale(s)** --- ## 🐳 Docker Configuration +### Production Managed via OMV → Services → Compose, project `fundtracker`, at `/Kingdezignsnas16/fundtracker/`. -### Key environment variables -| Variable | Purpose | -|---|---| -| `DATABASE_URL` | Postgres connection string | -| `SYNC_HOUR_UTC` / `SYNC_MINUTE_UTC` | Daily sync+report time (default 06:00 UTC) | -| `SMTP_HOST/PORT/USER/PASSWORD/FROM` | Same Zoho account used by every other KingDezigns notification | -| `ADMIN_SEED_USERNAME/PASSWORD/EMAIL` | Bootstrap admin, only used if the `users` table is completely empty | -| `SESSION_TTL_DAYS` | Login session length (default 14) | -| `COOKIE_SECURE` | **Must be `true`** now that this is exposed externally over HTTPS — `false` is LAN-testing-only and sends credentials in cleartext if left on over plain HTTP | -| `PUBLIC_BASE_URL` | Should be `https://funds.kingdezigns.com` — used to build password-reset email links | -| `REPORT_WINDOW_DAYS/LOOKBACK_YEARS/TOP_N` | Daily email report defaults | +| Container | Name | Port | +|---|---|---| +| API | `fundtracker_api` | `8000:8000` | +| Database | `fundtracker_db` | (internal only) | -### Deployment pattern (established across multiple rounds of iteration) -- **Code-only changes** (edits inside `api/app/`): copy the updated `app/` folder into the OMV project directory, then `sudo docker restart fundtracker_api`. A plain restart is sufficient since `app/` is bind-mounted. -- **New Python dependencies** (`requirements.txt` changes): a restart is **not** enough — requires `docker compose build --no-cache api` followed by `up -d`, since dependencies are baked into the image at build time. -- **Compose YAML / environment variable changes**: requires `up -d` (recreate), not `restart` — a plain restart reuses the old in-memory environment. This distinction caused real deploy failures twice during development (once for the `curl_cffi` fix, once for the `bcrypt` addition) before being nailed down. -- Because `/Kingdezignsnas16/fundtracker/` is root-owned (`drwx------`, contains DB credentials), file transfers land in a `rufusking`-writable scratch path first (e.g. `/tmp/ft_upload/`), then get moved into place with `sudo cp -r`. +- **Compose file:** `/Kingdezignsnas16/fundtracker/fundtracker.yml` (OMV-managed, do not hand-edit) +- **pgdata:** `/opt/fundtracker/pgdata` +- **DB credentials:** user `fundtracker`, db `fundtracker`, password `Valerie8545` +- **Network:** `fundtracker_default` — production DB is reachable by container name `fundtracker_db` from any container on this network + +### QA +Managed via OMV → Services → Compose, project `fundtracker-qa`, at `/Kingdezignsnas16/fundtracker-qa/`. + +| Container | Name | Port | +|---|---|---| +| API | `fundtracker_qa_api` | `8001:8000` | +| Database | `fundtracker_qa_db` | (internal only) | + +- **Compose file:** `/Kingdezignsnas16/fundtracker-qa/fundtracker-qa.yml` (OMV-managed, do not hand-edit) +- **pgdata:** `/opt/fundtracker_qa/pgdata` (owned by UID/GID 70:70 — the postgres user on this host) +- **DB credentials:** user `fundtracker_qa`, db `fundtracker_qa`, password `Valerie8545_qa` +- **Service names in compose:** `qa_db` and `qa_api` (not `db`/`api` — OMV named them differently) +- **Networks:** QA API is on both `default` (its own network) and `fundtracker_prod` (external, mapped to `fundtracker_default`) — required for DevLog DB sync to reach the prod DB container + +### Key environment variables (both environments) +| Variable | Production | QA | Purpose | +|---|---|---|---| +| `APP_ENV` | `production` | `qa` | Single environment flag | +| `DATABASE_URL` | prod connection string | QA connection string | Primary DB | +| `PROD_DATABASE_URL` | *(not set)* | prod connection string | DevLog sync target | +| `SYNC_HOUR_UTC` / `SYNC_MINUTE_UTC` | `6` / `0` | (ignored in QA) | Daily sync+report time | +| `SMTP_*` | Zoho creds | Zoho creds (suppressed in QA) | Email | +| `ADMIN_SEED_USERNAME/PASSWORD/EMAIL` | Bootstrap admin | Bootstrap admin | Only used if `users` table empty | +| `SESSION_TTL_DAYS` | `14` | `14` | Login session length | +| `COOKIE_SECURE` | `true` | `true` | Required for HTTPS | +| `PUBLIC_BASE_URL` | `https://funds.kingdezigns.com` | `https://funds.qa.kingdezigns.com` | Password reset links | +| `PRIMARY_ADMIN_USERNAME` | `rufusking` | `rufusking` | Cannot be deleted or demoted | +| `TRUSTED_PROXY_IP` | `192.168.150.30` | `192.168.150.30` | Real IP forwarding from NPM | + +### Deployment patterns +- **Code-only changes** (edits inside `api/app/`): copy updated files into the project directory, then `sudo docker restart fundtracker_api`. Plain restart is sufficient since `app/` is bind-mounted. +- **New Python dependencies** (`requirements.txt` changes): requires `docker compose build --no-cache api` followed by `up -d`. +- **Compose YAML / environment variable changes**: requires `up -d --force-recreate` — a plain restart reuses the old in-memory environment. +- **Structural DB migrations**: take a `pg_dump` backup first. + +### QA-specific compose commands +```bash +# Start QA +sudo docker compose -f /Kingdezignsnas16/fundtracker-qa/fundtracker-qa.yml up -d + +# Restart QA API only (code change) +sudo docker restart fundtracker_qa_api + +# Force-recreate QA API (compose/env change) +sudo docker compose -f /Kingdezignsnas16/fundtracker-qa/fundtracker-qa.yml up -d --force-recreate qa_api + +# View QA logs +sudo docker logs fundtracker_qa_api --tail 30 + +# View QA DB logs +sudo docker logs fundtracker_qa_db --tail 20 +``` ### Database migrations Two tiers, by risk: - **Additive** (`ADD COLUMN IF NOT EXISTS`) — safe, runs on every startup, no backup needed. -- **Structural** (e.g. the shared-security/private-watchlist split, the per-profile settings conversion) — genuinely restructures data, including column drops. These are idempotent (safe to run repeatedly) but a `pg_dump` backup is taken before deploying any update in this category, restorable via `psql` into a fresh container. +- **Structural** — requires a `pg_dump` backup before deploying. + +```bash +# Production backup +sudo docker exec fundtracker_db pg_dump -U fundtracker fundtracker | gzip > /tmp/fundtracker-prod-$(date +%Y%m%d).sql.gz + +# QA backup +sudo docker exec fundtracker_qa_db pg_dump -U fundtracker_qa fundtracker_qa | gzip > /tmp/fundtracker-qa-$(date +%Y%m%d).sql.gz +``` + +### Re-cloning production data into QA +When QA needs a fresh copy of production data: +```bash +sudo docker exec fundtracker_db pg_dump -U fundtracker fundtracker \ + | sudo docker exec -i fundtracker_qa_db psql -U fundtracker_qa fundtracker_qa +``` +The `ERROR: role "fundtracker" does not exist` messages are harmless — ownership assignment fails but all table structure and data copies correctly. + +--- + +## 📊 Watch Alerts — Intraday BUY Signal Monitoring (v1.9.0) + +Per-profile, intraday monitoring of up to 5 tickers for BUY signal transitions. Sends one email alert when a signal changes *to* BUY — not repeatedly while it stays BUY. Once the signal leaves BUY and returns, a new alert fires. + +- **Module:** `watch_alerts.py` — self-contained: migration, scheduler job, API router +- **DB table:** `watch_alert_monitors` — `user_id`, `ticker`, `last_signal`, `last_checked_at`, `alert_sent_at` +- **Poll interval:** per-user setting (`watch_poll_minutes` in the `settings` table, valid: 5/10/15/30/45/60). Scheduler job fires on a 5-minute base tick; each monitor's `last_checked_at` gates whether the user's chosen interval has elapsed. +- **Market hours:** `pandas-market-calendars` (NYSE calendar) — correctly excludes weekends AND NYSE holidays. Graceful fallback to weekday-only check if library unavailable. +- **Price refresh:** `period="5d"` Yahoo pull per unique monitored ticker — lightweight, not a full 5-year re-download. +- **Live dashboard row refresh:** frontend polls `/watch-alerts/monitors` on the user's chosen interval and surgically updates only the Signal cell for monitored tickers — no full page reload. +- **New dependency:** `pandas-market-calendars>=4.3.1` added to `requirements.txt` — requires image rebuild on first deploy. +- **UI panel:** "Watch Alerts" panel on dashboard — single row layout: interval dropdown | ticker chips with signal badges | Add input | Track button. Market Open badge updates every minute client-side. + +### Watch Alerts API endpoints +| Endpoint | Purpose | +|---|---| +| `GET /watch-alerts/monitors` | List user's monitors with last_signal | +| `POST /watch-alerts/monitors` | Add ticker (max 5, ticker must exist in instruments) | +| `DELETE /watch-alerts/monitors/{ticker}` | Remove monitor | +| `GET /watch-alerts/poll-interval` | Get user's poll interval (minutes) | +| `PUT /watch-alerts/poll-interval` | Set user's poll interval | + +--- + +## 🩺 Ticker Health Panel (v1.9.0) + +Admin-only self-service panel to identify and remediate broken or stale instruments without SSH or psql access. + +- **Page:** `Admin → Ticker Health` (`/dashboard/admin/ticker-health.html`) +- **Backend:** `ticker_health_router` appended to `admin.py`, registered in `main.py` +- **Migration:** `migrate_sync_metadata()` in `migrations.py` — adds `last_sync_at`, `last_sync_rows`, `last_sync_error` to `instruments` table via `ADD COLUMN IF NOT EXISTS`. Safe, additive, no backup needed. + +### Flags surfaced +| Flag | Condition | +|---|---| +| `no_prices` | 0 price points ever stored | +| `last_sync_empty` | Most recent sync returned 0 rows | +| `never_synced` | `last_sync_at` is NULL | +| `stale` | `last_sync_at` > 3 days ago | +| `suspicious_symbol` | Ticker contains `.` `/` `\` `,` or space | +| `sync_error` | `last_sync_error` is non-null | + +### Admin actions (all inline, no DB access needed) +- **↻ Re-sync** — force immediate Yahoo sync, shows row count or error inline +- **✎ Rename** — inline ticker rename (e.g. `BRK.B` → `BRK-B`), immediately re-syncs to verify, updates `WatchAlertMonitor` rows, logs to audit log +- **✕ Delete** — dry-run first (shows price count + affected profile count), then `?confirm=true` to execute. Cascades: price points, watchlist entries, metric snapshots, watch alert monitors. + +### Sync metadata stamping +`data_fetch.sync_instrument_from_yahoo()` now stamps `last_sync_at`, `last_sync_rows`, and `last_sync_error` on every call — success, empty, and exception all leave a clear trail. Covers daily job and admin force-syncs. + +--- + +## 📈 Signal Logic Refinement — WATCH Threshold Tightening (v1.9.0) + +WATCH was previously a catch-all "else" for non-held securities — anything that didn't trigger BUY/SELL/null got WATCH, which was the majority of the portfolio. Reclassified as a high-value alert requiring positive evidence. + +**New WATCH criteria (non-held only, all require quality ≥ 55):** +- Opportunity ≥ 55 — a real dip is developing +- Z-score ≤ -1.2 — return running meaningfully below normal (early-warning dip) +- Rebound ≥ 50 — moderate peer-relative anomaly forming + +**Securities that now get null instead of WATCH:** solid quality, normal z-score, no dip forming, no peer anomaly — "nothing to see here" is correctly represented as no signal. + +**MUTF null case fully preserved:** `quality_score is None` still returns null for non-held (the "do not touch" marker). No change to that path. + +**Key threshold constants** (all in `signals.py`, named for easy adjustment): +- `_WATCH_QUALITY_FLOOR = 55.0` +- `_WATCH_OPPORTUNITY = 55.0` +- `_WATCH_ZSCORE = -1.2` +- `_WATCH_REBOUND = 50.0` + +--- + +## 🖥️ Dashboard Layout Consolidation (v1.9.0) + +View Controls and Add Ticker panels merged into a single split panel (left/right) to reduce vertical space. Export/Import, Send Report, and Held Only moved from a third row under View Controls to a second row under Add Ticker (right column). "Send email report now" button renamed to "Send Report". --- ## ⚠️ Known Issues & Fixes Already Shipped -- **Yahoo Finance blocking (fixed):** `yfinance`'s default HTTP client gets silently blocked by Yahoo's bot detection with increasing frequency — the library misreports this as "no data" rather than "blocked." Fixed by routing all requests through a `curl_cffi` session impersonating a real Chrome browser's TLS fingerprint. -- **Bogus-ticker crash (fixed):** a nonexistent ticker could make `yfinance`'s internal metadata lookup throw an unhandled exception (a JSON decode error) instead of just returning empty data, crashing the add-ticker request entirely. Now caught and treated as "0 rows synced," which correctly triggers the verification-failure flow instead. -- **Ticker verification with override:** adding a brand-new ticker attempts a real sync as verification. Zero rows returned prompts a warning with an explicit "add anyway" override (rather than a hard block) — specifically to handle legitimate cases like a recent ticker rename Yahoo hasn't caught up to yet (e.g. Siemens Energy's SMNEY → SMERY change). -- **Rate-limit-driven data source risk:** noted, not yet acted on — if Yahoo's blocking becomes more aggressive over time, alternative data sources may need evaluation. Deferred as a future consideration. +- **Yahoo Finance blocking (fixed):** `yfinance`'s default HTTP client gets silently blocked by Yahoo's bot detection. Fixed by routing all requests through a `curl_cffi` session impersonating a real Chrome browser's TLS fingerprint. +- **Bogus-ticker crash (fixed):** a nonexistent ticker could make `yfinance`'s internal metadata lookup throw an unhandled exception. Now caught and treated as "0 rows synced." +- **Ticker verification with override:** adding a brand-new ticker attempts a real sync as verification. Zero rows returned prompts a warning with an explicit "add anyway" override. --- ## 💾 Backup -- `/opt/fundtracker/pgdata` (bind-mounted Postgres data) can fold into `nas16-backup.sh` the same way Forgejo's data was — not yet formally added as of this writing. -- A raw file-copy backup of a *live* Postgres directory can be inconsistent; `pg_dump` is the reliable method (see Deployment pattern above). Given nearly all price data is re-derivable by re-syncing from Yahoo, a stale/imperfect backup mainly costs a re-sync, not real data loss — the one exception is user accounts, watchlist memberships (which securities each profile tracks), cost basis, and legal-acceptance records, which are **not** re-derivable and are the actual reason to keep backups current. +- `/opt/fundtracker/pgdata` (production) and `/opt/fundtracker_qa/pgdata` (QA) can both fold into `nas16-backup.sh`. +- Use `pg_dump` rather than raw file-copy for reliable backups of live Postgres data. +- The one exception to "re-syncable from Yahoo": user accounts, watchlist memberships, cost basis, and legal-acceptance records — keep backups current for these. --- ## 🧠 Summary for AI Systems +- **MANDATORY (added 2026-10-11):** every delivery of Fund Tracker files must OPEN with the exact `scp` → `sudo cp` (QA path `/Kingdezignsnas16/fundtracker-qa/api/app/...`) → `sudo docker restart fundtracker_qa_api` command block, with real file names and restart-vs-rebuild stated, before any explanation — then, after QA passes, the production copy + `sudo docker restart fundtracker_api` + Deploy to Prod order described above. See `server_debteliminator.md` §3a-0 for the template. - Fund Tracker = **multi-profile mutual fund/stock tracking web app**, Docker Compose on NAS16, VLAN 50. -- Public at `https://funds.kingdezigns.com/` via NPM on HAS, Force SSL. Also reachable internally at `http://192.168.150.40:8000/dashboard/`. -- Two containers: `fundtracker_api` (FastAPI) and `fundtracker_db` (Postgres 16). -- **Shared security data, private watchlists**: ticker/price history/group tag are shared across all profiles; is_held/cost_basis/which-tickers-tracked are private per profile. -- Scoring: quality (risk-adjusted, security-level) → opportunity (quality + genuine dip, requires both z-score AND drawdown to agree) → combined (harmonic mean of quality+opportunity) → rebound (peer-relative "usually top of its group, currently collapsed" detector, reconstructed retroactively from existing price history). -- Buy/Sell/Hold signals apply only to positions flagged `is_held` — simple threshold heuristic, documented as a screening aid, not a trade instruction. +- **Two environments:** production (`funds.kingdezigns.com`, port 8000, containers `fundtracker_api`/`fundtracker_db`) and QA (`funds.qa.kingdezigns.com`, port 8001, containers `fundtracker_qa_api`/`fundtracker_qa_db`). Both run on NAS16 simultaneously with completely separate databases. +- **Single environment flag:** `APP_ENV=production` or `APP_ENV=qa`. No `IS_DEV`/`IS_PROD` flags. Unrecognised values default to `production`. +- **QA behaviour:** scheduler idle, `send_email()` suppresses automatic sends, password-reset emails use `force=True` and still deliver, amber "⚠️ QA ENVIRONMENT" banner in UI, DevLog sync to prod DB available. +- **Production behaviour:** scheduler runs at 06:00 UTC, emails send normally, no QA banner, no `PROD_DATABASE_URL`. +- **Deployment workflow:** changes → QA → test → (1) cp files to prod + docker restart → (2) verify → (3) click Deploy to Prod in Dev Log on QA site. Never reverse steps 1 and 3. +- **Dev Log auto-versioning (v1.8.0):** projects created in Queue with update_type (minor/major/platform/no-version). Deploy to QA auto-assigns next version. Deploy to Prod uses same version + auto-syncs DevLog records to prod DB. Nav version only updates on Deploy to Prod. Cards collapsed by default, click to expand. +- **DevLog DB sync:** QA API is joined to `fundtracker_default` network so it can reach `fundtracker_db` by container name. `PROD_DATABASE_URL` set in QA compose. Auto-syncs on Deploy to Prod. Bulk sync via `POST /admin/devlog/sync-to-prod` (button on Dev Log page in QA only). Non-fatal if prod DB unreachable. +- **QA compose network config:** `qa_api` service has `networks: [default, fundtracker_prod]`; bottom of compose declares `networks: fundtracker_prod: external: true, name: fundtracker_default`. Required for DevLog sync. If QA API can't reach prod DB, verify this network config and run `docker compose up -d --force-recreate qa_api` (not just `docker restart`). +- **`docker restart` vs `up -d --force-recreate`:** restart reuses the existing in-memory container environment — compose file changes (env vars, networks, volumes) are NOT picked up. Always use `force-recreate` after editing the compose file. +- **Production compose project:** `fundtracker` at `/Kingdezignsnas16/fundtracker/`, compose file `fundtracker.yml`, pgdata at `/opt/fundtracker/pgdata`. +- **QA compose project:** `fundtracker-qa` at `/Kingdezignsnas16/fundtracker-qa/`, compose file `fundtracker-qa.yml`, pgdata at `/opt/fundtracker_qa/pgdata` (owned 70:70), service names `qa_api`/`qa_db` in compose. +- Scoring: quality → opportunity → combined → rebound (all from price history via `yfinance`+`curl_cffi`). - Auth: httponly session cookies, bcrypt, 5-attempt lockout, forced password change on seeded accounts. -- Admin: account management, anonymized cross-profile Census, versioned legal document publishing (version bump = automatic re-acceptance requirement for everyone). -- Market data via `yfinance` + `curl_cffi` (Chrome impersonation) — required workaround for Yahoo's bot detection, not optional. -- Deployment: code-only changes = folder swap + `docker restart`; dependency changes = rebuild; compose/env changes = `up -d`. Structural DB migrations require a `pg_dump` backup first. -- `COOKIE_SECURE=true` and `PUBLIC_BASE_URL=https://funds.kingdezigns.com` must both be set now that this is publicly exposed — leaving `COOKIE_SECURE=false` on a public HTTPS deployment would send credentials in cleartext. -- **Portfolio / transaction tracking (documented here 2026-08-19, built in an earlier session):** a full buy-lot/sale/split register sits alongside the scoring/screening system — buy lots (with remaining-qty tracking), sales (FIFO/LIFO/Specific ID matching via `/portfolio/sales`), and splits (`/portfolio/splits`, only affects lots active and purchased before the split date). `GET /portfolio/register` returns the full lot+sale view the Portfolio page renders. Lots lock against edit/delete once a sale references them — deleting the sale restores shares and unlocks the lot. CSV bulk import via `/portfolio/import/csv`. Full endpoint list and locking rules in the dedicated section above. -- **Portfolio UI updated 2026-08-19:** the register now renders as a three-level collapsible hierarchy — **Ticker (collapsed by default) → Buy Lot → Sale(s)** — instead of showing every lot for every ticker at once. Frontend-only change to `portfolio.html`, deployed via the standard code-only pattern (scp to `/tmp` → `sudo cp` into the root-owned project dir → `sudo docker restart fundtracker_api`, no rebuild required). -- **Known portfolio deployment gotchas** (missing `Decimal`/`CheckConstraint` imports in `models.py`, stale `/tmp` copies overwriting newer router code, schema/router ordering) are logged in the Portfolio section above — check there before re-diagnosing the same class of failure. +- Admin: account management, anonymized cross-profile Census, versioned legal document publishing. +- **Portfolio / transaction tracking:** buy-lot/sale/split register, FIFO/LIFO/Specific ID matching, `GET /portfolio/register`, lot locking on sale allocation. +- **Portfolio UI:** three-level collapsible hierarchy — Ticker (collapsed by default) → Buy Lot → Sale(s). +- `COOKIE_SECURE=true` and correct `PUBLIC_BASE_URL` must both be set in both environments. +- **Watch Alerts (v1.9.0):** Per-profile intraday BUY-transition monitoring. Up to 5 tickers per profile. Email fires once on BUY transition, resets when signal leaves BUY. Poll interval is per-user (5/10/15/30/45/60 min), stored in `settings` table as `watch_poll_minutes`. Scheduler base tick is 5 min; `last_checked_at` on each monitor gates the user's chosen interval. Market hours via `pandas-market-calendars` (NYSE, excludes holidays). Live dashboard row refresh on user's chosen interval — only Signal cell updated, no page reload. New dependency: `pandas-market-calendars>=4.3.1` (requires image rebuild on first deploy). Module: `watch_alerts.py`. Table: `watch_alert_monitors`. +- **Ticker Health panel (v1.9.0):** Admin-only page at `Admin → Ticker Health`. Surfaces instruments with `no_prices`, `last_sync_empty`, `never_synced`, `stale` (>3d), `suspicious_symbol`, or `sync_error` flags. Inline Re-sync, Rename (with immediate re-sync verification + audit log), and Delete (dry-run then confirm). `data_fetch.sync_instrument_from_yahoo()` now stamps `last_sync_at`/`last_sync_rows`/`last_sync_error` on every call. Migration: `migrate_sync_metadata()` adds three columns to `instruments` via `ADD COLUMN IF NOT EXISTS`. Router: `ticker_health_router` in `admin.py`. +- **WATCH signal tightened (v1.9.0):** WATCH was previously a catch-all else for non-held securities. Now requires quality ≥ 55 AND one of: opportunity ≥ 55, z-score ≤ -1.2, or rebound ≥ 50. Securities that are "fine but unexciting" now correctly return null. MUTF null (insufficient history) preserved unchanged. Thresholds are named constants at the top of `signals.py`. +- **Dashboard layout (v1.9.0):** View Controls and Add Ticker merged into one split panel. Export/Import + Send Report + Held Only moved to second row of right column. "Send email report now" → "Send Report". --- diff --git a/server_homeassistant.md b/server_homeassistant.md index 7eca29b..efb4ebb 100644 --- a/server_homeassistant.md +++ b/server_homeassistant.md @@ -4,7 +4,7 @@ Hostname: **homeassistant** IP Address: **192.168.150.30** VLAN: **50 — Lab / Servers** -Last Updated: 2026-08-17 +Last Updated: 2026-10-02 --- @@ -68,6 +68,9 @@ This placement ensures: | 192.168.150.40:3670 | NAS16 service | | 192.168.150.40:3000 | Forgejo — self-hosted Git server (`forgejo.kingdezigns.com`, Force SSL, see `server_forgejo.md`) | | 192.168.150.40:8000 | Fund Tracker — multi-profile mutual fund/stock tracking web app (`funds.kingdezigns.com`, Force SSL, see `server_fundtracker.md` and `server_nas16.md`) | +| 192.168.150.40:8002 | Debt Eliminator (production) — personal debt tracking web app (`cutthecard.net` / `www.cutthecard.net`, Force SSL, see `server_debteliminator.md`) | +| 192.168.150.40:8003 | Debt Eliminator (QA) — `debt.qa.cutthecard.net`, Force SSL, see `server_debteliminator.md` | +| 192.168.150.40:3001 | Umami analytics — `stats.cutthecard.net`, Force SSL + HTTP/2, websockets off, see `server_umami.md` | | 192.168.150.35:8080 | NAS08 service | | 192.168.150.35:8081 | NAS08 service | | 192.168.150.35:8082 | NAS08 service | @@ -110,7 +113,7 @@ Internet → UCG Max → NPM (192.168.150.30:80/443) - Banned IPs are blocked before traffic ever reaches NPM or backend services - **Email notifications are handled externally by NAS16** — not by CrowdSec's native notification system - Native CrowdSec email notifications are **disabled** in profiles.yaml -- **Applies uniformly to every service proxied through NPM**, including Fund Tracker and Forgejo — no per-service CrowdSec configuration is required; anything routed through NPM inherits this protection automatically. +- **Applies uniformly to every service proxied through NPM**, including Fund Tracker, Forgejo, and Debt Eliminator — no per-service CrowdSec configuration is required; anything routed through NPM inherits this protection automatically. #### Active Collections | Collection | Protects Against | @@ -288,7 +291,7 @@ These are essential for: ## 🧠 Summary for AI Systems - HAS = **automation hub + network reverse proxy + intrusion prevention** located in VLAN 50. - Runs Home Assistant core, Nginx Proxy Manager (port 81), CrowdSec Agent + LAPI (port 8080), and CrowdSec Firewall Bouncer. -- NPM is the single external ingress point for all internal web services, including Forgejo and Fund Tracker. +- NPM is the single external ingress point for all internal web services, including Forgejo, Fund Tracker, and Debt Eliminator. - CrowdSec is the single intrusion prevention layer — blocks at nftables before NPM, applies uniformly to every NPM-proxied service. - NPM logs are read via journald using SYSLOG_IDENTIFIER `addon_a0d7b954_nginxproxymanager`. - 60 active detection scenarios covering HTTP attacks, CVEs, brute force, and SSH. @@ -304,6 +307,8 @@ These are essential for: - Uses Pi‑hole in VLAN 50 for DNS. - All proxied traffic to backends appears to originate from 192.168.150.30. - **Fund Tracker added 2026-08-17** — `funds.kingdezigns.com` → 192.168.150.40:8000, Force SSL. Full detail in `server_fundtracker.md`. +- **Debt Eliminator added 2026-08-24, rebranded 2026-09** — both domains changed: production moved from `debt.kingdezigns.com` to `cutthecard.net` / `www.cutthecard.net` → 192.168.150.40:8002, and QA moved from `debt.qa.kingdezigns.com` to `debt.qa.cutthecard.net` → 192.168.150.40:8003 (both NPM proxy hosts updated, confirmed 2026-09-15). `cutthecard.org` redirects to `cutthecard.net` at Dreamhost DNS only, not configured in NPM. Both Force SSL. Full detail in `server_debteliminator.md`. +- **Umami analytics added 2026-10-01** — `stats.cutthecard.net` → 192.168.150.40:3001, Force SSL + HTTP/2, websockets off. Public DNS via the Dreamhost A record + NAS16 DDNS script; Pi-hole local override `stats.cutthecard.net` → 192.168.150.30 (avoids NAT hairpin). No CrowdSec/firewall changes needed. Full detail in `server_umami.md`. --- diff --git a/server_nas08.md b/server_nas08.md index ba8ff87..c4d8a81 100644 --- a/server_nas08.md +++ b/server_nas08.md @@ -4,7 +4,7 @@ Hostname: **NAS08** IP Address: **192.168.150.35** VLAN: **50 — Lab / Servers** -Last Updated: 2026-07-25 +Last Updated: 2026-10-20 --- @@ -31,6 +31,7 @@ This device is a **critical infrastructure component**, supporting both internal | /dev/sdc | Crucial BX500 (CT1000BX500SSD1) | 1TB | Data | | /dev/sdd | Crucial BX500 (CT1000BX500SSD1) | 1TB | Data | | /dev/sde | Crucial BX500 (CT1000BX500SSD1) | 1TB | Data | +| /dev/sdf | Crucial MX500 (CT1000MX500SSD1) | 1TB | Data — added 2026-10-19, being added to `kingdezignsnas` via RAIDZ expansion (see ZFS Pool section) | --- @@ -651,6 +652,60 @@ This setting should remain enabled if/when the Synaplan backend is deployed loca --- +## 🧱 ZFS Pool — kingdezignsnas (RAIDZ2 expansion, 2026-10-19) + +### **Layout** +- Pool: `kingdezignsnas`, OpenZFS **2.4.4** (Debian backports `zfs-2.4.4-1~bpo13+1`) +- Single vdev `raidz2-0` (RAIDZ2 = two-disk parity) +- Before: 4 x Crucial BX500 1TB (raw 3.62T, ~91% full, ~297G free) +- After expansion: 4 x BX500 + 1 x Crucial MX500 1TB (`ata-CT1000MX500SSD1_2415E8A6E7AC`, `/dev/sdf`) = 5 disks +- Last clean scrub before the expansion: 2026-10-18, 0 errors (1h16m) +- Only `feature@raidz_expansion` was enabled; no full `zpool upgrade` was run, so other feature flags are still pending (the "Some supported and requested features are not enabled" notice is expected) + +### **New-drive qualification (before attaching)** +The MX500 arrived with an NTFS partition (empty apart from `System Volume Information`), 963 power-on hours and ~3.2 TB written. Tests run on 2026-10-19: +1. `smartctl -a`: PASSED; 0 reallocated, 0 pending, 0 uncorrectable; lifetime remaining 100%; `UDMA_CRC_Error_Count` = 1 (watch item, did not increase) +2. SMART short + extended self-tests: completed without error +3. `badblocks -b 4096 -c 16384 -wsv -t 0x55`: one full write/read-verify pass, 0 bad blocks, empty log +4. SMART re-check after the write test: all counters unchanged +Harmless smartctl output on this model: attribute 180 (`Unused_Reserve_NAND_Blk`) normalized value 000, and "ATA error count 0 inconsistent with error log pointer". + +### **Expansion procedure used** +```bash +# NAS16 sync run first so the backup copy was current (NAS16: /usr/scripts/nas/nas08_to_nas16_sync.sh) +sudo umount /dev/sdf1 2>/dev/null +sudo wipefs -a /dev/sdf +sudo partprobe /dev/sdf +sudo zpool set feature@raidz_expansion=enabled kingdezignsnas +sudo zpool attach kingdezignsnas raidz2-0 /dev/disk/by-id/ata-CT1000MX500SSD1_2415E8A6E7AC +``` +Always address disks by `/dev/disk/by-id/...`, not `/dev/sdX`. + +### **Status** +- Started **2026-10-19 19:59:42 EDT**. Initial estimate was ~5 hours at ~198 MB/s. +- Progress check on 2026-10-20: **36.44% (1.22T of 3.33T) at 22.8 MB/s, estimate 1 day 3 hours remaining.** Far slower than the first estimate; cause not yet diagnosed (see below). Pool stayed `ONLINE` with 0 errors. +- The expansion must not be interrupted: no reboot or power-off until `zpool status` shows it complete. +- **Extra capacity only appears when the expansion completes** (`zpool list`, `zfs list`, and therefore OMV). + +### **Why it is slow / what to check** +- Expansion rewrites all existing data (~3.33T), about 4x the data of a single-disk resilver. +- Likely contributors: DRAM-less BX500 drives falling out of their SLC cache on sustained writes, the Pi's CPU doing parity work, and normal NAS08 load (Nextcloud, DNS, sync jobs) competing for the pool. +- Diagnostics: `sudo zpool iostat -v kingdezignsnas 5 3`, `iostat -x 5 3`, `sudo dmesg -T | grep -i -E "ata|sd[b-f]|reset|error" | tail -30`, `top` (CPU), and `smartctl -A` CRC counts on all five disks (the MX500 sits on the eSATA/SATA-HAT path; watch for link resets or CRC growth). + +### **After it finishes** +```bash +sudo zpool status kingdezignsnas +sudo zpool list -v kingdezignsnas +zfs list kingdezignsnas +sudo zpool scrub kingdezignsnas +``` +Expected usable space: roughly 730 GiB free vs ~150 GiB before (estimates). Existing data keeps its old 2-data + 2-parity layout until rewritten; only new writes use the 3-data + 2-parity ratio. OpenZFS 2.4 provides `zfs rewrite` (`rewrite [-Prvx] [-o offset] [-l length] <directory|file ...>`) to re-lay-out existing data and reclaim the rest (~0.9 TiB free after a full rewrite). Considerations before using it: snapshots hold the old blocks, it needs free space as it works, it is heavy I/O (run it when Nextcloud is quiet and away from the Sunday 3:00 AM scrub and 2:30 AM sync), and take a current NAS16 backup first. Not yet run. + +### **OMV note** +OMV reads pool size from ZFS, so it should show the larger capacity after completion. If the Storage / ZFS page still shows the old size, reload the page; verify with `zpool list` and `df -h` first. + +--- + ## 🔒 Required Firewall Behavior ### **Inbound to NAS08** @@ -1026,7 +1081,8 @@ run of the script correctly reported "up to date." - Outbound blocked to all VLANs except local + DNS responses. - Critical infrastructure component for network‑wide DNS and storage. - SSD hardening active: TRIM (weekly Wednesday 1AM), noatime (flashmemory plugin), SMART monitoring via weekly HTML email report. -- Five drives: 1x PNY CS900 500GB (OS), 4x Crucial BX500 1TB (data). +- Six drives: 1x PNY CS900 500GB (OS), 4x Crucial BX500 1TB (data) plus 1x Crucial MX500 1TB (data, added 2026-10-19). +- **ZFS pool `kingdezignsnas`** (OpenZFS 2.4.4) is a single RAIDZ2 vdev. On 2026-10-19 the MX500 was qualified (SMART short/long, full badblocks pass, 0 errors) and attached with `zpool attach kingdezignsnas raidz2-0 /dev/disk/by-id/ata-CT1000MX500SSD1_2415E8A6E7AC` (RAIDZ expansion, `feature@raidz_expansion` enabled). Expansion started 19:59 on 2026-10-19 and was ~36% done at 22.8 MB/s with ~27 h estimated on 2026-10-20 (initially ~5 h). Do not reboot NAS08 until it completes; new space appears only after completion; run a scrub afterward; `zfs rewrite` can later reclaim old-layout overhead. See the ZFS Pool section. - **Shared permissions:** `ncshare` group (GID 1001) shared by `www-data` and `rufusking` — allows both Nextcloud and NFS to read/write the same files. - NFS exports use `all_squash,anonuid=33,anongid=1001` — all NFS uploads land as `www-data:ncshare` automatically. - Default ACLs on `/export/kingdezigns-public` ensure all new files/folders inherit `ncshare` group permissions. diff --git a/server_nas16.md b/server_nas16.md index 0004d24..544c18b 100644 --- a/server_nas16.md +++ b/server_nas16.md @@ -1,387 +1,766 @@ -# NAS16 — LAMP Stack & Database Server -Device Type: **Raspberry Pi** -Hostname: **NAS16** -IP Address: **192.168.150.40** -VLAN: **50 — Lab / Servers** +# NAS16 --- LAMP Stack & Database Server -Last Updated: 2026-08-17 +Device Type: **Raspberry Pi**\ +Hostname: **NAS16**\ +IP Address: **192.168.150.40**\ +VLAN: **50 --- Lab / Servers** ---- +Last Updated: 2026-10-11 + +------------------------------------------------------------------------ ## 🧩 Role & Purpose -NAS16 is the **dedicated LAMP stack and database server** for the KingDezigns network. -It runs **OpenMediaVault (OMV)** as its base OS, which manages nginx as the web GUI frontend. -It provides backend services, web hosting, and database support for internal applications, development environments, and externally accessible virtual host websites. -In addition to its LAMP role, NAS16 hosts the **CrowdSec external notification system**, **Forgejo** (self-hosted Git server), and, as of 2026-08, **Fund Tracker** — a multi-profile mutual fund/stock tracking web application. +NAS16 is the dedicated LAMP stack, database, application-hosting, and +administrative server for the KingDezigns network. -This system is designed for: -- Web application hosting (internal and external) -- MariaDB database services -- Internal development and testing -- Lightweight administrative tools (Webmin via OMV) -- External virtual host websites proxied through HAS (NPM) -- CrowdSec email notification delivery (local attack alerts + CAPI daily digest) -- Self-hosted Git version control for network-wide scripts and project files (Forgejo) -- Multi-profile mutual fund/stock tracking with automated daily email reports (Fund Tracker) +It runs OpenMediaVault as its base operating system and provides: -NAS16 operates entirely within VLAN 50 and benefits from the strict containment rules that prevent lateral movement into trusted networks. +- Apache web hosting +- MariaDB services +- PHP applications +- Webmin administration +- CrowdSec notification scripts +- Forgejo +- Fund Tracker +- Debt Eliminator +- Umami (web analytics) +- Network and application backup scripts ---- +NAS16 is located entirely within VLAN 50 and is protected by the VLAN's +containment and firewall policies. + +------------------------------------------------------------------------ ## 🖥️ Hardware -- Raspberry Pi (model unspecified) -- SSD storage (see drive inventory below) -- Gigabit Ethernet -### **Drive Inventory** -| Device | Model | Capacity | Role | -|--------|-------|----------|------| -| /dev/sda | Unknown (standard SMART attrs) | ~256GB | OS / system drive | +- Raspberry Pi +- SSD storage +- Gigabit Ethernet -> Note: Drive model unconfirmed — uses standard SMART attribute names (Wear_Leveling_Count, Reallocated_Sector_Ct, Current_Pending_Sector, Offline_Uncorrectable). Power_Cycle_Count of 7,079 at 891 power-on hours noted — likely reflects frequent reboots during setup. Monitor over time. +### Drive Inventory ---- + Device Model Capacity Role + ------------ --------- ---------- ----------------- + `/dev/sda` Unknown \~256 GB OS/system drive + +Drive model should be confirmed during a future hardware inventory +update. + +------------------------------------------------------------------------ ## 🌐 Network Placement -- VLAN: **50 — Lab / Servers** -- IP: **192.168.150.40** -- Access Type: LAN / Cable -This placement ensures: -- Isolation from trusted user devices -- Controlled access to sensitive database services -- Local access to Pi‑hole DNS -- Reduced attack surface +- VLAN: **50 --- Lab / Servers** +- IP: **192.168.150.40** +- Access: LAN / cable ---- +NAS16 must remain reachable from: + +- Trusted administrative devices +- VLAN 50 services +- Home Assistant Server/NPM for reverse-proxy traffic +- Required internal Docker networks + +------------------------------------------------------------------------ ## 📦 Primary Functions -### **Core Services** -- **OpenMediaVault (OMV)** — base OS and NAS management UI -- **LAMP Stack** - - Linux - - Apache (serves internal and external virtual host websites) - - MariaDB - - PHP -- **Webmin** (administrative interface, managed via OMV) +### Core Services -### **Additional Roles** -- Internal web hosting -- External virtual host websites (proxied via NPM on HAS) -- Database backend for internal applications -- Development and testing environment -- **CrowdSec external notification system** (see below) -- **Forgejo self-hosted Git server** (see below) -- **Fund Tracker mutual fund/stock tracking service** (see below) +- OpenMediaVault +- Apache +- MariaDB +- PHP +- Webmin +- nginx as part of the OMV management stack ---- +### Additional Roles + +- CrowdSec external notification handler +- Forgejo +- Fund Tracker +- Debt Eliminator +- Umami (web analytics) +- NAS08 → NAS16 rsync destination +- NAS16 system/application backup operations + +------------------------------------------------------------------------ ## 🌍 External Access Architecture -NAS16 hosts multiple public-facing websites served by Apache. -External traffic reaches NAS16 via the following proxy chain: +Public web traffic follows: -``` -Internet → NPM on HAS (192.168.150.30:80/443) → nginx on NAS16 (OMV frontend) → Apache (virtual hosts) +``` text +Internet + ↓ +NPM on Home Assistant Server + ↓ +NAS16 + ↓ +Application service ``` -### **Real IP Forwarding** -Because all proxied traffic arrives at NAS16 from HAS's IP (192.168.150.30), both nginx and Apache are configured to extract and log the real client IP from the `X-Forwarded-For` header passed by NPM. +Real client IP information is forwarded through `X-Forwarded-For`. -**nginx** — `/etc/nginx/conf.d/real_ip.conf`: -```nginx -set_real_ip_from 192.168.150.30; -real_ip_header X-Forwarded-For; -real_ip_recursive on; +NAS16's nginx and Apache configurations are responsible for extracting +the real client IP so backend security tools such as Fail2Ban do not +treat HAS as the attacker. + +------------------------------------------------------------------------ + +## 🔧 Fail2Ban / Real IP + +Fail2Ban is active on NAS16. + +The proxy IP is trusted so that NPM traffic cannot cause HAS itself to +be banned. + +The current documented `ignoreip` pattern includes: + +``` text +127.0.0.1/8 +::1 +192.168.150.0/24 ``` -**Apache** — `/etc/apache2/conf-available/real_ip.conf`: -```apache -RemoteIPHeader X-Forwarded-For -RemoteIPTrustedProxy 192.168.150.30 +Real IP forwarding remains required for public services behind NPM. + +------------------------------------------------------------------------ + +## 🔧 Forgejo + +NAS16 hosts Forgejo as a Docker service. + +- Internal web UI: `http://192.168.150.40:3000` +- Public URL: `https://forgejo.kingdezigns.com/` +- Git SSH: LAN-only on port 2222 +- SQLite database +- Data path: `/opt/forgejo/data` + +Full Forgejo configuration is maintained in `server_forgejo.md`. + +------------------------------------------------------------------------ + +## 📈 Fund Tracker + +NAS16 hosts Fund Tracker. + +- Production port: 8000 +- Public URL: `https://funds.kingdezigns.com/` +- FastAPI + PostgreSQL +- Independent QA/Production environments +- Application-specific details: `server_fundtracker.md` + +------------------------------------------------------------------------ + +## 📊 Umami Analytics + +NAS16 hosts Umami (self-hosted, cookie-free web analytics) as two Docker +containers. + +- Project: `umami` at `/Kingdezignsnas16/umami/` (OMV Compose) +- Containers: `umami` (host port **3001**), `umami_db` (Postgres 16, internal) +- Public URL: `https://stats.cutthecard.net/` (NPM on HAS, Force SSL) +- Data: `/opt/umami/pgdata` (owned 70:70) +- Secrets: `/opt/umami/umami.secrets` (root, 600) — loaded via `env_file`; + OMV's generated `umami.env` is not used for secrets because OMV + regenerates it and wipes manual edits +- Backup: not yet in `nas16-backup.sh` (use `pg_dump`) +- Full configuration, lessons learned, and open items: + `server_umami.md` + +------------------------------------------------------------------------ + +## 💳 Debt Eliminator / CutTheCard + +NAS16 hosts Debt Eliminator (branded as **CutTheCard**) as two +independent Docker environments. + +> **Domain update — CONFIRMED (2026-09-15):** both public domains +> changed. Production moved from `debt.kingdezigns.com` to +> **`https://www.cutthecard.net`**; QA moved from +> `debt.qa.kingdezigns.com` to **`https://debt.qa.cutthecard.net`**. NPM +> on HAS and Dreamhost DNS have both been updated for both environments — +> this is a completed rebrand, not just an application-side change. +> `cutthecard.org` redirects to `cutthecard.net` at the Dreamhost DNS +> level only (not configured in NPM). `debt.kingdezigns.com` and +> `debt.qa.kingdezigns.com` are now deprecated; remaining references to +> either anywhere in this doc set should be scrubbed and replaced +> (tracked as a standing reminder in `server_debteliminator.md` §0a +> until fully clean). Internal access (`192.168.150.40:8002`/`:8003`) is +> unaffected. Full detail in `server_debteliminator.md` §2a. + +### Production + +``` text +Project: + /Kingdezignsnas16/debteliminator/ + +Compose: + /Kingdezignsnas16/debteliminator/debteliminator.yml + +API: + debteliminator_api + +Database: + debteliminator_db + +Host port: + 8002 + +Internal URL: + http://192.168.150.40:8002/dashboard/ + +Public URL: + https://cutthecard.net/ (www.cutthecard.net also serves the app; cutthecard.org redirects to cutthecard.net at Dreamhost) ``` -Apache module enabled: `remoteip` -Config enabled: `real_ip` +### QA -This ensures Fail2Ban sees and bans real attacker IPs, not HAS's proxy IP. +``` text +Project: + /Kingdezignsnas16/debteliminator-qa/ ---- +Compose: + /Kingdezignsnas16/debteliminator-qa/debteliminator-qa.yml -## 🔔 CrowdSec External Notification System +API: + debteliminator_qa_api -NAS16 is the sole email notification handler for CrowdSec. Native CrowdSec notifications are disabled on HAS. NAS16 polls the CrowdSec LAPI stream endpoint and routes decisions by origin. +Database: + debteliminator_qa_db -### **Why NAS16** -- Offloads notification work from HAS (which runs HA, NPM, CrowdSec Agent + Bouncer) -- NAS16 has the most headroom of any Pi in the fleet (16GB RAM, consistently underutilized) -- Fits cleanly into existing OMV Scheduled Jobs infrastructure +Host port: + 8003 -### **Architecture** -``` -CrowdSec LAPI on HAS (192.168.150.30:8080) - ↓ -NAS16 polls /v1/decisions/stream every 5 min - ↓ - origin = crowdsec? origin = CAPI? - ↓ ↓ - Append to local_pending.json Append to capi_digest.json - ↓ ↓ - Every 4 hours: Midnight: send digest - send batched digest email + clear log - email + clear log +Internal URL: + http://192.168.150.40:8003/dashboard/ + +Public URL: + https://debt.qa.cutthecard.net/ ``` -### **Scripts** -| Script | Path | Purpose | -|--------|------|---------| -| cs_notifier.sh | `/usr/scripts/crowdsec/cs_notifier.sh` | Polls LAPI stream every 5 min, routes decisions by origin into pending log files (no emails sent) | -| cs_local_digest.sh | `/usr/scripts/crowdsec/cs_local_digest.sh` | Reads local_pending.json, sends batched local-attack digest every 4 hours, clears log | -| cs_digest.sh | `/usr/scripts/crowdsec/cs_digest.sh` | Reads CAPI digest log, builds summary email, sends at midnight, clears log | +### Database storage -### **Key Design Details** -- Uses `/v1/decisions/stream?startup=true` on first run to initialize cursor silently (no emails for existing decisions) -- Uses `/v1/decisions/stream?startup=false` on all subsequent runs — LAPI maintains cursor server-side per API key -- First run flag: `/var/log/crowdsec-notifier/stream_initialized.flag` -- Local pending log: `/var/log/crowdsec-notifier/local_pending.json` (one JSON decision per line, cleared every 4 hours after digest send) -- CAPI digest log: `/var/log/crowdsec-notifier/capi_digest.json` (one JSON decision per line, cleared at midnight after digest send) -- Notifier log: `/var/log/crowdsec-notifier/notifier.log` -- All email sending uses inline Python with `timeout=15` on SMTP_SSL to prevent hangs -- Digest scripts use a single Python call to process all decisions — handles large batches efficiently -- **IMPORTANT:** Python heredocs (`python3 << PYEOF`) do NOT read from a preceding pipe — the heredoc itself becomes stdin. Data must be passed as an inline shell variable inside the heredoc (e.g. `snapshot = """$SNAPSHOT"""`), not piped in. +``` text +Production: + /opt/debteliminator/pgdata -### **Email Notifications** -| Type | Trigger | Style | Content | -|------|---------|-------|---------| -| Local attack digest | Every 4 hours (cron: `0 0,4,8,12,16,20 * * *`) — skipped if zero bans | Red / CRITICAL | Stat cards (ban count, origin, CAPI today) + table of all banned IPs with scenario, type, duration, scope, detected time, and CTI/WHOIS/AbuseIPDB links | -| CAPI daily digest | Midnight cron | Amber / WARNING (or green if zero bans) | Total ban count, top 10 scenarios, first 20 sample IPs | - -> **Note:** Local attack alerting was changed from immediate per-IP emails (one email per ban, dozens-to-hundreds/week) to a 4-hour batched digest to reduce notification volume while preserving full visibility into attack activity. - -### **CrowdSec API Key** -- Bouncer name: `NAS16-notifier` -- Credentials stored in Vaultwarden under `CrowdSec NAS16-notifier` -- LAPI endpoint: `http://192.168.150.30:8080` - -### **LAPI Port Requirement** -Port 8080 must be exposed on HAS's host network interface. Configured in the CrowdSec add-on Network settings. If HAS is rebuilt or the add-on is reinstalled, re-enable port 8080 mapping. - ---- - -## 🔧 Forgejo — Self-Hosted Git Server (added 2026-07-26) - -NAS16 hosts **Forgejo**, the self-hosted Git server providing version control and a web UI for editing/browsing scripts and project files across the KingDezigns network. Chosen for placement on NAS16 specifically because it has the most spare RAM/CPU headroom of any host in the fleet — the same reasoning previously used to place the CrowdSec notifier scripts here instead of on HAS. - -- **Container:** `forgejo` (Docker, image `codeberg.org/forgejo/forgejo:10`), Compose-managed via OMV -- **Web UI:** `http://192.168.150.40:3000` internally, public at `https://forgejo.kingdezigns.com/` (proxied via NPM on HAS, Force SSL) -- **SSH git access:** `ssh://git@192.168.150.40:2222/...` — LAN-only, no external port-forward configured -- **Database:** SQLite — no separate DB container -- **Data path:** `/opt/forgejo/data` (bind-mounted, not a Docker volume) — folded into the existing `nas16-backup.sh` scheduled backup job -- **Organizations:** `NAS08`, `NAS16`, `PLEX32` — one repo per org (`<hostname>-scripts`), mirroring the `07 - Projects/<HOST>` folder structure on NAS16's own NFS share -- **Registration:** disabled — accounts are admin-created only - -Full configuration, troubleshooting history, and operational details are documented separately in `server_forgejo.md`. - ---- - -## 📈 Fund Tracker — Multi-Profile Mutual Fund/Stock Tracking (added 2026-08-17) - -NAS16 hosts **Fund Tracker**, a self-hosted, multi-profile web application for tracking mutual funds and stocks — built around a "buy the proven dip" screening thesis: identifying securities that are historically strong performers but currently trading below where they normally sit, rather than simply chasing whatever's up the most. - -- **Containers:** `fundtracker_api` (FastAPI, Python 3.12) and `fundtracker_db` (PostgreSQL 16), Compose-managed via OMV at `/Kingdezignsnas16/fundtracker/` -- **Web UI:** `http://192.168.150.40:8000/dashboard/` internally, public at `https://funds.kingdezigns.com/` (proxied via NPM on HAS, Force SSL) -- **Database:** PostgreSQL, bind-mounted at `/opt/fundtracker/pgdata` -- **Market data:** Yahoo Finance via `yfinance` + `curl_cffi` (Chrome browser impersonation — required to avoid Yahoo's bot-detection blocking) -- **Multi-profile design:** security data (ticker, price history, group classification) is shared across all profiles and synced once regardless of how many profiles track it; each profile's holdings, cost basis, and watchlist membership are private -- **Scoring:** quality (risk-adjusted), opportunity (quality + genuine price dip), combined (harmonic mean of both), and rebound (peer-relative "usually near the top of its group, currently collapsed" detector) — all derived purely from price history -- **Auth:** session-cookie based (httponly, bcrypt-hashed passwords), admin/user roles, versioned legal document acceptance (Terms of Use + Investment Disclaimer) -- **Daily job:** in-process scheduler (not an OMV Scheduled Job) syncs all tracked securities and emails each profile a personalized report of their own holdings/watchlist at 06:00 UTC - -Full architecture, scoring methodology, deployment pattern, and known issues are documented separately in `server_fundtracker.md`. - ---- - -## 🗂️ Shared Permissions — NFS + rsync Backup - -NAS16 receives rsync backups from NAS08 via `nas08_to_nas16_sync.sh` every 2 days. To ensure rsync can write files on the destination without errors, NAS16 uses the same `ncshare` group configuration as NAS08. - -### **Group Configuration** -| Item | Value | -|------|-------| -| Group name | `ncshare` | -| GID | `1001` | -| Members | `www-data`, `rufusking` | - -> GID **must match NAS08** (1001) — rsync syncs permissions across both systems and they must be consistent. - -Verify with: -```bash -getent group ncshare +QA: + /opt/debteliminator_qa/pgdata ``` -### **Directory Permissions** -Applied to `/export/kingdezignsnas-16/Public` (and all subdirectories recursively): -```bash -sudo chown -R www-data:ncshare /export/kingdezignsnas-16/Public -sudo chmod -R 2770 /export/kingdezignsnas-16/Public -sudo setfacl -R -m g:ncshare:rwx /export/kingdezignsnas-16/Public -sudo setfacl -R -d -m g:ncshare:rwx /export/kingdezignsnas-16/Public +### Application stack + +- FastAPI +- Python 3.12 +- PostgreSQL 16 +- Vanilla HTML/JavaScript/CSS +- SQLAlchemy +- AES-256-GCM account-number encryption +- Charge-level interest rates and promotional APR engine +- 0% Balance Transfer strategy engine +- Automated QA → Production deployment engine (deploy_engine.py) +- **Stripe** (`stripe` package, v1.10.0+) — one-time and recurring + donations +- **openpyxl** / **python-docx** (v2.3.0+) — Records Archive .xlsx/ + .docx year-end export + +The app has also grown a small public-facing surface (about/contact/ +donate pages, a six-article SEO "Learning Center," `robots.txt`/ +`sitemap.xml`) alongside the authenticated dashboard. Full detail — +including the domain/branding change, self-service account suspend/ +delete, and the current known-issues list — is in +`server_debteliminator.md`, which should be treated as authoritative +over this summary for anything Debt Eliminator-specific. + +### Debt Eliminator Database Credentials + +Production: + +``` text +Container: debteliminator_db +Database: debteliminator +User: debteliminator +Password: debteliminator_db_pass ``` -- `2770` (setgid) ensures new items inherit the `ncshare` group -- Default ACLs (`-d`) ensure all new files/folders created by rsync inherit `rwx` for `ncshare` +QA: -> **Note:** You should not need to run these commands manually. The sync script checks and self-corrects destination ownership before every run. These are documented here as reference only. - -### **Backup Script** -The sync runs on NAS16 via OMV Scheduled Jobs: -```bash -/usr/scripts/nas/nas08_to_nas16_sync.sh -``` -- Source: `/mnt/kingdezigns08/Public/` (NAS08 mounted via NFS) -- Destination: `/export/kingdezignsnas-16/Public/` -- Schedule: Every 2 days at 2:30 AM - -### **rsync Flags — NFS all_squash Compatibility** -The sync script uses the following rsync flags to work correctly over NFS `all_squash`: - -``` ---archive Recursive, preserve symlinks, owner, group, devices ---no-perms Skip chmod — NFS all_squash prevents non-owner chmod ---omit-dir-times Skip directory utimes — NFS all_squash prevents utimes on dirs not owned by www-data ---update Skip files that are newer on destination +``` text +Container: debteliminator_qa_db +Database: debteliminator +User: debteliminator +Password: debteliminator_qa_db_pass ``` -- **File timestamps are fully preserved** — `--omit-dir-times` only skips directory mtimes, not file mtimes -- **Directory timestamps are intentionally skipped** — directory mtimes are not meaningful for backup purposes -- **Permissions are not synced** — destination ACLs (`ncshare` group, `2770`) control access instead +### Debt Eliminator SMTP Credentials -### **Permission Precheck (Automatic)** -Before every sync run, the script checks that the destination root is owned by `www-data:ncshare`. If it is not, it automatically runs `chown`, `chmod`, and `setfacl` to correct it before rsync starts. This is logged and flagged in the email report with an amber warning notice if it fires. - -A clean run looks like: -``` -[TIMESTAMP] Destination ownership OK (www-data:ncshare). -[TIMESTAMP] ===== NAS08 → NAS16 Sync Started ===== -[TIMESTAMP] ===== Sync Completed Successfully ===== -Done — Status: SUCCESS | Transferred: N file(s) | Duration: Xm Xs +``` text +SMTP_HOST=smtppro.zoho.com +SMTP_PORT=465 +SMTP_USER=rufus.king@kingdezigns.com +SMTP_PASSWORD=zoho_mail_password +SMTP_FROM=rufus.king@kingdezigns.com +SMTP_TO=rufus.king@kingdezigns.com ``` ---- +These values are intentionally retained in the private NAS16 +documentation for operational convenience. + +### Debt Eliminator deployment commands — standing rule + +Every delivery of Debt Eliminator files must open with the exact command block below (real file +names; `sudo` is required because the project directory is root-only). Full template and rules: +`server_debteliminator.md` §3a-0. + +``` bash +scp ~/Downloads/<package>.tar.gz rufusking@192.168.150.40:deploys/ # from KingDezigns001 +ssh rufusking@192.168.150.40 +cd ~/deploys && rm -rf <name> && mkdir <name> && tar -xzf <package>.tar.gz -C <name> +sudo cp -r ~/deploys/<name>/api/app/. /Kingdezignsnas16/debteliminator-qa/api/app/ +sudo docker restart debteliminator_qa_api # restart-only change +``` + +Rebuild instead of restart when `requirements.txt`, `Dockerfile` or compose files change. + +### Debt Eliminator architecture + +``` text +KingDezigns001 + ↓ +SCP → NAS16 ~/deploys/ (manual path) + ↓ +QA application + ↓ +QA PostgreSQL + ↓ +QA browser testing + ↓ +[Automated] Dev Log → Deploy to Prod (preview → confirm → execute) + — deploy_engine.py diffs QA vs Production, copies changed files, + rebuilds if needed, restarts, verifies container status + ↓ +Production application + ↓ +Production PostgreSQL +``` + +The QA container requires `/var/run/docker.sock` and bind mounts of +both project directories for the automated pipeline. See +`server_debteliminator.md` §3a for the required compose additions. + +> **2026-09-30 update (host-level summary — `server_debteliminator.md` +> §0b/§12f/§12g is authoritative):** DevLog is now **v2.1.3**. Added: a +> public **Blog Engine** (`/blog`, scheduled publishing via an in-app +> 60-second worker, images stored in PostgreSQL — no new files on disk, no +> compose changes, no new Python dependencies), a unified revenue ledger +> (`donations.payment_kind`), subscription admin tiles, and an +> **Admin → Revenue** page. SitePay (real paid subscriptions, Stripe +> Customer Portal, daily reconciliation) and Email Campaigns are present in +> the code (see `server_debteliminator.md` §0b). + +> **2026-10-02 update:** Production backup is now **v2.1.7** +> (`debteliminator-v2.1.7-backup-2026-10-01_16-35-01.tar.gz`; v2.1.4–2.1.7 +> deployed 2026-09-30/10-01, contents not itemized here). Added a +> site-wide script loader (`static/site-scripts.js`) feeding Umami analytics +> — see `server_debteliminator.md` §12h and `server_umami.md`. Static files +> only plus one edit to `routers/blog.py`; no new dependencies or compose +> changes. + +> **2026-10-11 update (host-level summary - `server_debteliminator.md` +> §0d/§8b/§12i-12j is authoritative):** DevLog is now **v2.1.20** +> (seen in a **QA** backup, `debteliminator-v2_1_20-backup-2026-10-10_23-51-34.tar.gz`). +> New: Admin Roles v2, public Demo Calculator, Milestones, Windfall Allocator, +> CSV/Statement Import (in memory only, 30-day import history), reminders, +> Credit Utilization, Budget-to-Payoff, blog auto-archive, **Household +> Sharing**, a WCAG 2.2 AA accessibility layer, and a regrouped sidebar. New +> tables: `roles`, `user_roles`, `budget_items`, `budget_settings`, +> `import_batches`, `payment_reminder_log`, `household_shares`, +> `household_activity`. No new containers or ports. `APP_SECRET_KEY` is +> still unset (also absent from the QA compose file). + +### Important application behavior + +Debt Eliminator uses a transaction-driven ledger: + +``` text +opening_balance + + +SUM(transaction signed_amount) + = +current_balance +``` + +The ledger is recomputed on every transaction create/edit/delete. + +Future-dated transactions immediately affect displayed balance but are +excluded from the interest/payoff balance until their date. + +Supported transaction types: + +- Payment +- Charge (supports per-charge interest rate + promotional APR) +- Fee +- Refund +- Adjustment + +### Payment Register + +Debt Eliminator includes: + +``` text +/dashboard/register.html +``` + +The Payment Register provides a year-at-a-glance view and supports a +saved Payments-Only versus All-Transactions preference. + +### Debt Reduction Plan + +``` text +/dashboard/payoff-strategy.html +``` + +Four-step progressive page: pick a strategy (Avalanche/Snowball), claim +0% balance-transfer savings, adjust payments, follow the rollover +timeline. Evaluates balance-transfer opportunities with credit-limit +awareness and promo-balance protection warnings. + +### My Account + +All users have: + +``` text +/dashboard/account.html +``` + +### Administration + +Administrators have: + +``` text +/dashboard/admin/accounts.html +``` + +This manages accounts, security settings, Terms of Use, and audit +logging. + +### Help Center + +``` text +/dashboard/help.html +``` + +Built-in documentation covering all application features. Nav link and +page title read **Help Center**. + +### Dev Log + +Administrators have: + +``` text +/dashboard/admin/devlog.html +``` + +The DevLog records the QA → Production workflow. Includes deployment +instructions, attach-to-existing-version for no-version projects, and +the automated Deploy to Prod pipeline (preview → confirm → execute via +`deploy_engine.py`). + +------------------------------------------------------------------------ + +## 🔢 Debt Eliminator Version Namespaces + +The 2026-09-30 Production backup (v2.1.3) shows these have moved on +since the 2026-09-15 backup (v2.0.19), and the frontend cache marker +is still not a single value: + + ----------------------------------------------------------------------- + Identifier Current value Meaning + ----------------------- ----------------------- ----------------------- + DevLog Production **v2.1.3** Latest deployed version + version stored in + `project_versions`; + used by the backup + filename + + Application source **1.10.1** Version reported by + version `main.py` + + Frontend cache marker **mixed: 1.8.5 on pages `?v=` used for shared + touched 2026-09-30, CSS/JS — not yet + 1.8.3/1.8.4 on others** consistent across + pages; see + `server_debteliminator.md` + §4.3/§25 + ----------------------------------------------------------------------- + +When referring to a Debt Eliminator release, documentation should state +which namespace is intended. + +Recommended wording: + +``` text +DevLog deployment v2.1.20 (2026-10-10 QA backup; Production latest not re-checked) +Application source v1.10.1 (string not bumped; startup log still says v1.9.2) +Frontend cache marker — app pages ?v=1.9.5; blog.py / public calculator page still ?v=1.9.2, see server_debteliminator.md +``` + +------------------------------------------------------------------------ + +## 💾 Debt Eliminator Backup + +Dedicated script: + +``` text +/usr/scripts/debteliminator/debteliminator-backup.sh +``` + +Destination: + +``` text +/export/kingdezignsnas-16/Public/07 - Projects/NAS16/debteliminator/ +``` + +The script: + +1. Verifies NAS16 storage +2. Verifies the Production project directory +3. Verifies Docker +4. Verifies the Production PostgreSQL container +5. Queries the latest deployed DevLog version +6. Runs `pg_dump` +7. Compresses the SQL dump +8. Copies the Production project files +9. Creates a manifest +10. Creates a tar.gz archive +11. Verifies the archive can be read +12. Removes temporary files +13. Retains the 10 newest Debt Eliminator backups + +### Backup scope + +The dedicated backup, most recently reconfirmed on 2026-09-15, is a +**Production-only backup**. + +It does not include: + +- QA PostgreSQL data +- QA project files +- QA Docker Compose project + +Do not describe the dedicated backup as a complete QA/Production backup. + +### Archive naming + +The backup script queries: + +``` sql +SELECT version_number +FROM project_versions +WHERE status = 'deployed' +ORDER BY deployed_at DESC NULLS LAST +LIMIT 1; +``` + +The latest Production DevLog version in the 2026-09-30 backup is: + +``` text +v2.1.3 +``` + +Therefore the archive is: + +``` text +debteliminator-v2.1.3-backup-2026-09-30_08-47-16.tar.gz +``` + +### Security + +Debt Eliminator backup archives contain the Production database and +application configuration. + +Treat them as confidential. + +Never place actual passwords, SMTP credentials, database passwords, +encryption keys, or session secrets into network documentation. + +------------------------------------------------------------------------ + +## 📅 NAS16 Scheduled Jobs + +Existing NAS16 jobs include: + + -------------------------------------------------------------------------------- + Schedule Script Purpose + ----------------- -------------------------------------------- ----------------- + Every 3 days `/usr/scripts/omv/nas16-backup.sh` NAS16 system + backup + + Every 2 days at `/usr/scripts/nas/nas08_to_nas16_sync.sh` NAS08 → NAS16 + 2:30 AM rsync + + Daily midnight `/usr/scripts/zfs/nas16_zfs_report.sh` ZFS status + + Sunday 3:00 AM `/usr/scripts/zfs/nas16_zfs_scrub.sh` ZFS scrub + + Every 15 minutes `/usr/scripts/ddns/ddns_update.sh` DDNS + + Wednesday 1:30 AM `/usr/scripts/omv/fstrim-report.sh` SSD TRIM/SMART + report + + Every 5 minutes `/usr/scripts/crowdsec/cs_notifier.sh` CrowdSec notifier + + Every 4 hours `/usr/scripts/crowdsec/cs_local_digest.sh` CrowdSec local + digest + + Daily midnight `/usr/scripts/crowdsec/cs_digest.sh` CrowdSec CAPI + digest + -------------------------------------------------------------------------------- + +Debt Eliminator's dedicated backup script is intended to be run through +OMV Scheduled Jobs when configured. + +------------------------------------------------------------------------ ## 🔒 Required Firewall Behavior -### **Inbound to NAS16** -- Allowed from VLAN 1 (Infrastructure) -- Allowed from VLAN 20 (Trusted) -- Allowed from VLAN 50 (local VLAN) -- Proxied external traffic arrives from HAS (192.168.150.30) via NPM -- IoT and Guest access depend on default policy -- No explicit inbound blocks except those applied to VLAN 50 as a whole +### Inbound -### **Outbound from NAS16** -- Subject to VLAN 50's global final drop: - - Cannot initiate to VLANs 1, 10, 20, 30, 40 -- Allowed exceptions: - - DNS responses - - Local VLAN 50 traffic (including LAPI calls to HAS at 192.168.150.30:8080) +NAS16 must accept required traffic from: -### **Critical Requirement** -- Must remain reachable from trusted administrative devices for management and database access. -- Must remain reachable from HAS (192.168.150.30) for proxied external traffic. -- Must be able to reach HAS LAPI at 192.168.150.30:8080 for CrowdSec notification polling. +- VLAN 1 +- VLAN 20 +- VLAN 50 +- HAS/NPM at `192.168.150.30` ---- +### Outbound -## 🔐 Security Measures -- **Fail2Ban enabled** (via OMV Fail2Ban plugin) -- **Fail2Ban ignoreip** includes `192.168.150.0/24` — prevents HAS proxy IP from being banned -- **Real IP forwarding** configured in nginx and Apache — ensures real attacker IPs are logged and banned -- Webmin access restricted to trusted VLANs -- Database ports not exposed outside VLAN 50 -- VLAN‑level containment prevents lateral movement +NAS16 remains subject to VLAN 50's containment rules. -### **Fail2Ban Configuration** -`/etc/fail2ban/jail.local`: -```ini -[DEFAULT] -ignoreip = 127.0.0.1/8 ::1 192.168.150.0/24 -``` +Required local exceptions include: -This ensures internal VLAN 50 devices (including HAS) are never banned regardless of proxied traffic volume. +- VLAN 50 traffic +- DNS +- HAS CrowdSec LAPI at `192.168.150.30:8080` +- Required application/proxy connectivity ---- +Database ports for application databases should not be exposed beyond +their required Docker/network scope. -## 🛠️ SSD Hardening & Maintenance +------------------------------------------------------------------------ -### **TRIM** -- TRIM support confirmed on all drives (`DISC-GRAN: 4K`, `DISC-MAX: 4G`) -- systemd `fstrim.timer` **disabled** — replaced by OMV Scheduled Job -- Weekly TRIM script: `/usr/scripts/omv/fstrim-report.sh` -- Scheduled: **Wednesday at 1:30 AM** via OMV Scheduled Jobs -- Script runs `fstrim -av`, gathers SMART health data, sends HTML email report, saves dated log to `/var/log/fstrim/` -- Log retention: 90 days +## 🛡️ Security Notes -### **noatime** -- All filesystems mounted with `noatime` — confirmed via `findmnt` -- Managed automatically by the `openmediavault-flashmemory` plugin -- No manual configuration required +- Fail2Ban active +- Real IP forwarding configured +- Webmin access restricted +- Database services are not publicly exposed directly +- External application access is through NPM +- CrowdSec provides perimeter intrusion prevention on HAS +- VLAN 50 limits lateral movement +- Debt Eliminator account numbers require stable encryption + configuration -### **openmediavault-flashmemory Plugin** -- Installed and active -- Automatically handles: `noatime`, tmpfs for `/var/log` and `/tmp`, swap disabled -- Significantly reduces unnecessary SSD write amplification +### Debt Eliminator encryption follow-up — still open, now higher priority -### **SMART Monitoring** -- Monitored weekly as part of the TRIM report script -- Drive uses standard SMART attribute names — no vendor-specific mapping required +The Production Compose file, re-inspected as of the 2026-09-15 backup, +**still** does not explicitly define `APP_SECRET_KEY`. This was already +flagged as a known issue at the prior reconciliation and remains +unresolved. ---- +**This is now more urgent**: the same Production compose file has since +had live Stripe secret/publishable/webhook keys added to it in plaintext +(see `server_debteliminator.md` §5/§26) to support the new donation +feature. The compose file is therefore a more sensitive artifact than it +was previously, while its most basic secret-hygiene gap is still open. +**The user has acknowledged this (2026-09-15) and asked to circle back +to it later rather than fix it immediately** — this is being tracked +with a standing reminder in `server_debteliminator.md` §0a (re-surface +every ~5 days until resolved), not silently deferred. -## 📅 Scheduled Jobs (OMV) +Before relying on stored account-number encryption: -| Schedule | Script | Tag | -|----------|--------|-----| -| Every 3 days at 2:00 AM | `/usr/scripts/omv/nas16-backup.sh` | NAS16 Backup | -| Every 2 days at 2:30 AM | `bash /usr/scripts/nas/nas08_to_nas16_sync.sh` | NAS Drive Backup | -| Daily at 12:00 AM | `/usr/scripts/zfs/nas16_zfs_report.sh` | ZFS Status Report | -| Sunday at 3:00 AM | `/usr/scripts/zfs/nas16_zfs_scrub.sh` | ZFS Scrub | -| Every 15 minutes | `/usr/scripts/ddns/ddns_update.sh` | DDNS Update | -| Wednesday at 1:30 AM | `/usr/scripts/omv/fstrim-report.sh` | TRIM Report | -| Every 5 minutes | `/usr/scripts/crowdsec/cs_notifier.sh` | CrowdSec Local Notifier | -| Every 4 hours (0:00, 4:00, 8:00, 12:00, 16:00, 20:00) | `/usr/scripts/crowdsec/cs_local_digest.sh` | CrowdSec Local Attack Digest | -| Daily at 12:00 AM | `/usr/scripts/crowdsec/cs_digest.sh` | CrowdSec CAPI Digest | +1. Generate a strong Production secret. +2. Store it — and the Stripe keys — in the approved secret-management + system. +3. Configure `APP_SECRET_KEY` in Production. +4. Configure a separate secret in QA. +5. Recreate the containers. +6. Never rotate the Production key after encrypted account numbers have + been stored. -> Note: Fund Tracker's daily sync + per-profile email job (06:00 UTC) runs via an **in-process APScheduler inside the `fundtracker_api` container**, not an OMV Scheduled Job — it is not in the table above because OMV has no visibility into it. See `server_fundtracker.md`. +The actual secret must not be written into this file. ---- +------------------------------------------------------------------------ ## 🧠 Summary for AI Systems -- NAS16 = **OMV-based LAMP + database server + CrowdSec notifier + Forgejo + Fund Tracker** in VLAN 50. -- Inbound allowed from VLAN 1, VLAN 20, local VLAN 50, and HAS proxy (192.168.150.30). -- Outbound blocked to all VLANs except local + DNS responses. -- Hosts Apache (virtual hosts), MariaDB, PHP, Webmin, and OMV management UI. -- External traffic is proxied through NPM on HAS — real IPs forwarded via X-Forwarded-For. -- nginx and Apache both configured to log real client IPs, not proxy IP. -- Fail2Ban ignoreip covers VLAN 50 to prevent HAS from being banned. -- Protected by VLAN 50's strict containment rules. -- SSD hardening active: TRIM (weekly Wednesday 1:30AM), noatime (flashmemory plugin), SMART monitoring via weekly HTML email report. -- High Power_Cycle_Count (7,079) relative to power-on hours (891) — monitor trend over time. -- **Hosts CrowdSec notification scripts** — polls HAS LAPI stream at 192.168.150.30:8080 every 5 minutes. -- Local attack decisions are batched and sent as one digest email every 4 hours (skipped if zero bans) — no longer one email per ban. -- CAPI cloud ban digest sent daily at midnight — single Python call handles 10,000+ decisions efficiently. -- CrowdSec API key stored in Vaultwarden under `CrowdSec NAS16-notifier`. -- **Gotcha:** when piping data into `python3 -` with a heredoc, the heredoc replaces stdin — pass data as an inline variable instead. -- **Forgejo:** Self-hosted Git server, Docker container `forgejo`, public at `https://forgejo.kingdezigns.com/` via NPM, SSH git access LAN-only on port 2222, SQLite DB, data at `/opt/forgejo/data` (folded into `nas16-backup.sh`). See `server_forgejo.md`. -- **Fund Tracker (added 2026-08-17):** Multi-profile mutual fund/stock tracker. Docker containers `fundtracker_api` + `fundtracker_db`, public at `https://funds.kingdezigns.com/` via NPM Force SSL. Shared security data (ticker/price history/group) across profiles; private per-profile holdings/cost-basis/watchlist membership. Scoring built from quality/opportunity/combined/rebound scores derived from price history via `yfinance`+`curl_cffi`. Session-cookie auth, admin role with anonymized cross-profile Census and versioned legal-document publishing. Daily sync+report job runs via in-process APScheduler at 06:00 UTC, NOT an OMV Scheduled Job. Full detail in `server_fundtracker.md`. -- **Shared permissions:** `ncshare` group (GID 1001) shared by `www-data` and `rufusking` — must match NAS08 GID for rsync compatibility. -- Default ACLs on `/export/kingdezignsnas-16/Public` ensure all rsync-written files inherit `ncshare` group permissions. -- **NAS08→NAS16 sync script self-heals destination permissions on every run** — checks for `www-data:ncshare` ownership, runs `chown`/`chmod`/`setfacl` automatically if wrong. Flagged in email subject and body if it fires. -- Sync script uses `--no-perms` and `--omit-dir-times` for NFS `all_squash` compatibility — all individual file timestamps are fully preserved; only directory timestamps are skipped (intentional, not meaningful for backup). -- **Do not manually run chown/chmod/setfacl on the sync destination** — the script handles this automatically. ---- +- NAS16 = **OMV + LAMP + database + Forgejo + Fund Tracker + Debt + Eliminator (CutTheCard) + CrowdSec notifier**. +- Debt Eliminator is branded **CutTheCard**. As of 2026-09-15, both + public domains changed and are **confirmed** — production is + `https://www.cutthecard.net` (was `debt.kingdezigns.com`), QA is + `https://debt.qa.cutthecard.net` (was `debt.qa.kingdezigns.com`). + NPM on HAS and Dreamhost DNS were both updated for both. + `cutthecard.org` redirects to `cutthecard.net` at Dreamhost only. + Both `kingdezigns.com` domains are deprecated; scrub remaining + references (tracked in `server_debteliminator.md` §0a until clean). +- Debt Eliminator Production = `192.168.150.40:8002`. +- Debt Eliminator QA = `192.168.150.40:8003`. +- Both environments have independent PostgreSQL containers and + storage. +- NPM on HAS provides external HTTPS. +- Debt Eliminator deployments are QA-first. +- The QA Dev Log now drives an **automated Deploy to Prod pipeline** + (preview → confirm → execute via `deploy_engine.py`), which requires + the Docker socket and project bind-mounts in the QA compose config. +- KingDezigns001 is the deployment workstation for the manual path. +- Debt Eliminator has a transaction-driven balance ledger. +- Charge-level interest rates and promotional APR (standard + deferred) + are supported per transaction via `interest_engine.py`. +- 0% Balance Transfer strategy is in `balance_transfer.py`; evaluates + donor/receiver pairs in Avalanche order; credit_limit field caps + recommended amount with a 0.5% safety buffer. +- The Debt Reduction Plan page (formerly Payoff Strategy) has a + four-step progressive layout. +- Payment Register is a separate dashboard page. +- My Account and Admin Accounts are current application pages. +- Help Center page (formerly User Guide) is at `/dashboard/help.html`. +- DevLog is QA-driven and carries deployment instructions; it now also + tracks assignment/due-date/on-hold per queue item, sends a weekly + overdue-item alert email, and keeps a permanent deployment-history + table separate from the single-generation file backup. +- **As of the 2026-09-15 backup (DevLog v2.0.19, app source v1.10.1):** + Debt Eliminator has grown Stripe donations (one-time + recurring), + a public Support/Contact form, self-service account suspend/delete, + a Privacy Statement + Affiliate Disclosure (affiliate links + themselves not yet live), a downloadable Records Archive export, an + SEO foundation with a public six-article Learning Center, and a + dark/light theme. Full detail is in `server_debteliminator.md`, + which should be treated as authoritative for anything Debt + Eliminator-specific — this file only tracks the NAS16-host-level + facts. +- **2026-09-30:** DevLog v2.1.3; Blog Engine, revenue ledger/page and subscription admin views added (see the update note above and `server_debteliminator.md`). The backup archive name is now `debteliminator-v2.1.3-backup-2026-09-30_08-47-16.tar.gz`. +- **`APP_SECRET_KEY` is still not configured in Production** — now a + higher-priority gap since live Stripe keys were added to the same + compose file in plaintext. See the encryption follow-up section + above. +- **DevLog v2.0.19 is not the same identifier as application source + v1.10.1.** +- Frontend cache marker is currently **split between 1.8.3 and 1.8.4** + depending on the page — no longer a single consistent value; see + `server_debteliminator.md` §4.3/§25. +- The dedicated Debt Eliminator backup is Production-only. +- **2026-10-02:** Umami analytics runs on NAS16 (`umami`, `umami_db`, port 3001, `/opt/umami/`); CutTheCard pages load it through one loader (`/dashboard/site-scripts.js`). Latest Debt Eliminator backup seen: v2.1.7. See `server_umami.md`. +- **2026-10-11:** Home Page Swap — the Debt Eliminator home page ("Start Here") is now served at `/` and `/index.html`; `/` no longer redirects to `/dashboard/`. See `server_debteliminator.md` §0e. +- **MANDATORY:** every delivery of application files opens with the SCP → `sudo cp` → `sudo docker restart debteliminator_qa_api` command block (restart-vs-rebuild stated). See the standing rule above and `server_debteliminator.md` §3a-0. +- Never document actual credentials or encryption keys. +- `APP_SECRET_KEY` should be explicitly configured before relying on + account-number encryption. + +------------------------------------------------------------------------ # ✔️ End of File diff --git a/server_plex32.md b/server_plex32.md index e75225e..18ce59e 100644 --- a/server_plex32.md +++ b/server_plex32.md @@ -4,7 +4,7 @@ Hostname: **plex32** IP Address: **192.168.150.45** VLAN: **50 — Lab / Servers** -Last Updated: 2026-08-19 +Last Updated: 2026-09-03 --- @@ -23,17 +23,19 @@ This device is the **single Plex Media Server** for the KingDezigns network and - Intel Celeron J4105 — 1.50GHz (4 cores) — Intel Quick Sync supported - 8GB RAM - 32GB eMMC (OS drive — no SMART support, health monitored via filesystem) +- 240GB External USB SSD (Plex config & transcode scratch) - Gigabit Ethernet ### **Storage** | Device | Type | Capacity | Role | |--------|------|----------|------| | mmcblk0 | eMMC | 29.1GB | OS / system drive | +| /dev/sda2 (`/mnt/external_ssd`) | USB SSD | 238GB | Local Plex config & transcode scratch storage | | /mnt/plex/config | NFS (NAS08) | — | Plex config backup destination only — not used by container | -| /mnt/plex/transcode | NFS (NAS08) | — | Transcode scratch (local at /opt/plex/transcode) | +| /mnt/plex/transcode | NFS (NAS08) | — | Legacy NFS transcode entry (active transcode local at `/mnt/external_ssd/plex/transcode`) | | /mnt/plex/media | NFS (NAS08) | 1.8TB | Media library | -> Note: Plex config and transcode directories are stored **locally** at `/opt/plex/` — not on NFS. The NFS config mount (`/mnt/plex/config`) is used as the backup destination by `plex32_backup.sh`. Only the media library is actively used by the container. +> Note: Plex config and transcode directories are stored **locally** on the external SSD at `/mnt/external_ssd/plex/` — offloading storage write cycles from the internal eMMC. The NFS config mount (`/mnt/plex/config`) is used as the backup destination by `plex32_backup.sh`. Only the media library is actively used by the container via NFS. --- @@ -81,9 +83,7 @@ This placement ensures: ## 🐳 Docker Configuration ### **Compose File Location** -``` -~/docker/plex/docker-compose.yml -``` +`/home/rufusking/docker/plex/docker-compose.yml` ### **Compose Contents** ```yaml @@ -103,8 +103,8 @@ services: - "44" - "993" volumes: - - /opt/plex/config:/config - - /opt/plex/transcode:/transcode + - /mnt/external_ssd/plex/config:/config + - /mnt/external_ssd/plex/transcode:/transcode - /mnt/plex/media:/media restart: unless-stopped @@ -196,17 +196,20 @@ Uses same Zoho SMTP credentials as all other KingDezigns email alerts: --- -## 📁 NFS Mounts +## 📁 Mounts & Storage Configuration -Configured in `/etc/fstab` — mounts automatically on boot: - -``` +### **FSTAB Configuration (`/etc/fstab`)** +```text 192.168.150.35:/export/kingdezigns-all/Docker/plex/config /mnt/plex/config nfs defaults,_netdev 0 0 192.168.150.35:/export/kingdezigns-all/Docker/plex/transcode /mnt/plex/transcode nfs defaults,_netdev 0 0 192.168.150.35:/export/kingdezigns-public /mnt/plex/media nfs defaults,_netdev 0 0 + +# External USB SSD - Dedicated Plex Data Drive +UUID=463eb922-e181-43b1-a90d-cc5241701d69 /mnt/external_ssd ext4 defaults,nofail,x-systemd.device-timeout=5s 0 2 ``` -> Note: `/mnt/plex/config` is used by `plex32_backup.sh` as the backup destination — not by the Plex container. `/mnt/plex/transcode` exists in fstab but Plex uses the local `/opt/plex/transcode` directory instead. +> **Safeguard Notes on External SSD:** +> The USB SSD uses `nofail` and `x-systemd.device-timeout=5s`. If the external drive fails or is physically disconnected, the host system will still boot cleanly within 5 seconds without locking up or becoming inoperable. --- @@ -348,12 +351,12 @@ cd ~/docker/plex && docker compose down # 2. Copy archive from NAS08 cp /mnt/plex/config/backups/plex/plex-config-YYYY-MM-DD.tar.gz /tmp/ -# 3. Clear current config -sudo rm -rf /opt/plex/config/Library +# 3. Clear current config on external SSD +sudo rm -rf /mnt/external_ssd/plex/config/* # 4. Extract backup -sudo tar -xzf /tmp/plex-config-YYYY-MM-DD.tar.gz -C /opt/plex -sudo chown -R rufusking:ncshare /opt/plex/config +sudo tar -xzf /tmp/plex-config-YYYY-MM-DD.tar.gz -C /mnt/external_ssd/plex/ +sudo chown -R rufusking:ncshare /mnt/external_ssd/plex/config # 5. Restart containers cd ~/docker/plex && docker compose up -d @@ -361,7 +364,7 @@ cd ~/docker/plex && docker compose up -d # 6. Verify docker ps # Both plex and tautulli should show Up -# Open http://192.168.150.45:32400/web and confirm library and watch history intact +# Open [http://192.168.150.45:32400/web](http://192.168.150.45:32400/web) and confirm library and watch history intact # 7. Cleanup rm /tmp/plex-config-YYYY-MM-DD.tar.gz @@ -464,11 +467,11 @@ Resolved — verified with a manual run; each issue now renders as one complete ## 🧠 Summary for AI Systems - PLEX32 = **dedicated Plex Media Server + Tautulli** on VLAN 50 at 192.168.150.45. -- Runs on Dell Wyse 5070 (Celeron J4105, 8GB RAM, 32GB eMMC). +- Runs on Dell Wyse 5070 (Celeron J4105, 8GB RAM, 32GB eMMC OS drive + 240GB External USB SSD). - Plex and Tautulli run as Docker containers via `~/docker/plex/docker-compose.yml`. +- **External USB SSD Mounted safely at `/mnt/external_ssd`** using `nofail,x-systemd.device-timeout=5s` — holds local Plex config (`/mnt/external_ssd/plex/config`) and transcode scratch space (`/mnt/external_ssd/plex/transcode`). Prevents eMMC wear and expanded root drive space to ~19GB free. - **Intel Quick Sync hardware transcoding active** — requires `/dev/dri` device passthrough and `group_add: ["44","993"]` in compose. Without group_add, Plex silently falls back to software transcoding. - **Lifetime Plex Pass** active — Sonic Radio, hardware transcoding, all Plex Pass features enabled. -- Config and transcode stored **locally** at `/opt/plex/` — not on NFS. - Media library mounted from NAS08 via NFS at `/mnt/plex/media`. - `/mnt/plex/config` NFS mount used as backup destination only — not by Plex container. - Library is ~75% HEVC Main 10, ~25% H.264, 100% AAC audio — audio never transcodes. @@ -495,9 +498,8 @@ Resolved — verified with a manual run; each issue now renders as one complete - **`plex32_health_report.sh` fixed 2026-07-12** — fixed the "Issues Detected" email block rendering each word on its own line, caused by a multi-character `IFS='. '` split; issues are now newline-delimited and read back with a `while read` loop. - **`plex32_update_check.sh` updated 2026-08-18** — replaced heavy `docker pull` layer downloads with `skopeo inspect` for fast manifest digest comparisons. Adjusted Step 5 logic to prioritize "Updates Available" blue banner over non-fatal script check warnings. - **Systemd override for Docker added 2026-08-19** — added `/etc/systemd/system/docker.service.d/override.conf` with `After=network-online.target remote-fs.target` and `Wants=network-online.target remote-fs.target` so Docker waits for NFS mounts on boot before starting containers. ---- -# ✔️ End of File +--- ### **Systemd Startup / NFS Dependency Fix (2026-08-19)** After a system reboot at 8:53 AM, Plex failed to auto-start despite having `restart: unless-stopped` in `docker-compose.yml`. @@ -515,3 +517,6 @@ After a system reboot at 8:53 AM, Plex failed to auto-start despite having `rest - Verified drop-in file is actively picked up by `docker.service`. Resolved — Docker will now delay container startup on boot until network mounts are fully established. + + +# ✔️ End of File diff --git a/server_umami.md b/server_umami.md new file mode 100644 index 0000000..44ae71d --- /dev/null +++ b/server_umami.md @@ -0,0 +1,192 @@ +# Umami — Self-Hosted Web Analytics +Device Type: **Docker Containers (hosted on NAS16)** +Containers: **umami**, **umami_db** +Hostname / URL: **stats.cutthecard.net** +IP Address: **192.168.150.40** (shares NAS16's host IP), host port **3001** +VLAN: **50 — Lab / Servers** + +Last Updated: 2026-10-02 + +--- + +## 🧩 Role & Purpose +Umami is the **self-hosted, cookie-free web analytics service** for CutTheCard and other KingDezigns sites. It answers: which pages people open, how long they stay, where they come from, whether they scroll/read articles, and which content they favor. + +**Why Umami (decision record, 2026-10-01):** +- **Not Google Analytics** — CutTheCard handles financial data and trades on privacy; GA would put a third party's script on the site, force Privacy Statement changes and likely a consent banner, and contradicts the self-hosted philosophy used elsewhere (DNS, Git, proxy, stock API). +- **Not Plausible Community Edition** — needs ClickHouse as well as Postgres; too heavy for a Raspberry Pi already running Forgejo, Fund Tracker (x2), CutTheCard (x2) and Apache. +- **Umami** — one app container plus a Postgres 16 container (same pattern as Fund Tracker/CutTheCard), official ARM64 image (confirmed working on NAS16), no cookies, data stays on KingDezigns hardware. +- Google Search Console (no script on the site) is still recommended alongside it for search-query data. + +--- + +## 🌐 Public Access +- **Domain:** `https://stats.cutthecard.net/` +- **Proxy:** NPM on HAS (192.168.150.30) → `192.168.150.40:3001` (scheme `http`) +- **NPM settings:** Let's Encrypt cert, **Force SSL** + **HTTP/2** on, Websockets **off** (not needed), Block Common Exploits on +- **Public DNS:** Dreamhost A record, kept current by the DDNS script on NAS16 (`/usr/scripts/ddns/ddns_update.sh` — `stats.cutthecard.net` was added to its subdomain list) +- **Pi-hole local DNS:** `stats.cutthecard.net` → `192.168.150.30` (avoids the NAT-hairpin failure; after editing Pi-hole v6 records use `docker restart pihole`, not `reloaddns`) +- **Tracker script URL:** `https://stats.cutthecard.net/insights` (renamed from the default `script.js` via `TRACKER_SCRIPT_NAME=insights`, so generic ad-block lists are less likely to match) + +CrowdSec/Fail2Ban need no changes — traffic proxied through NPM inherits protection like every other service. No firewall changes were required (existing NPM → NAS16 inbound path). + +--- + +## 🐳 Docker Configuration + +### Project +OMV → Services → Compose, project/file name `umami`, at `/Kingdezignsnas16/umami/` (root-only directory; use `sudo bash -c "cd ... && ..."`). + +| Item | Value | +|---|---| +| Compose file | `/Kingdezignsnas16/umami/umami.yml` (OMV-managed, symlinked as `compose.yml`) | +| Database data | `/opt/umami/pgdata` — owned `70:70` (postgres alpine UID/GID), mode `700` | +| Secrets file | `/opt/umami/umami.secrets` — **outside OMV's control**, `root:root`, mode `600` | +| App image | `ghcr.io/umami-software/umami:postgresql-latest` (ARM64 confirmed working) | +| DB image | `postgres:16-alpine` | +| Host port | `3001` → container `3000` (3000 on NAS16 is Forgejo) | +| Network | `umami_default` (created by compose) | + +### Compose file (no secrets in it) +```yaml +services: + umami_db: + image: postgres:16-alpine + container_name: umami_db + restart: unless-stopped + env_file: + - /opt/umami/umami.secrets + environment: + - POSTGRES_DB=umami + - POSTGRES_USER=umami + volumes: + - /opt/umami/pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U umami -d umami"] + interval: 10s + timeout: 5s + retries: 5 + + umami: + image: ghcr.io/umami-software/umami:postgresql-latest + container_name: umami + restart: unless-stopped + depends_on: + umami_db: + condition: service_healthy + ports: + - "3001:3000" + env_file: + - /opt/umami/umami.secrets + environment: + - DISABLE_TELEMETRY=1 + - TRACKER_SCRIPT_NAME=insights +``` + +### Secrets file — variable names only (values live in Vaultwarden and in the file itself) +```text +POSTGRES_PASSWORD=<secret> +DATABASE_URL=postgresql://umami:<same password>@umami_db:5432/umami +APP_SECRET=<secret> +``` +Generate values with `openssl rand -hex 24` (hex avoids URL-encoding problems in `DATABASE_URL`). **Never write real values into documentation.** Changing the Postgres password after the database is initialized requires changing it inside Postgres too (the env var only applies on first init). + +### Why `env_file` and not the OMV Environment box (lesson learned 2026-10-01) +- OMV **regenerates `umami.env` from its own stored settings** on every apply (the file carries a "do not edit, changes will be lost" header). Values typed into the file by hand are wiped, and the UI Environment box did not populate it in this setup. Compose therefore saw blank `${UMAMI_DB_PASSWORD}` and Postgres refused to start (`Database is uninitialized and superuser password is not specified`). +- Putting `UMAMI_DB_PASSWORD=...` in a *service's* `environment:` list does **not** fix `${...}` substitution — interpolation reads the project `.env`, not service environments. +- Fix: external `env_file` (above). Values go directly to each container, nothing depends on `umami.env`, and nothing is lost when OMV re-saves the project. +- Apply changes with **down then up** (not `docker restart`), which recreates containers with the new environment. + +### Key commands +```bash +# Start / recreate +sudo bash -c "cd /Kingdezignsnas16/umami && docker compose down && docker compose up -d" + +# Status / logs +sudo docker ps | grep umami +sudo docker logs umami --tail 30 +sudo docker logs umami_db --tail 20 + +# Local health +curl -I http://192.168.150.40:3001 # expect 200 + +# Update images (both are real registry images, so pull is safe) +sudo bash -c "cd /Kingdezignsnas16/umami && docker compose pull && docker compose up -d" +``` + +--- + +## 📊 Websites Configured in Umami +| Website | Domain(s) | Notes | +|---|---|---| +| **CutTheCard** | `cutthecard.net`, `www.cutthecard.net` | Tracked via `/dashboard/site-scripts.js` (below). Website ID is embedded in that file; IDs are not secrets (visible in page source). | +| **kingdezigns.com** (personal site) | `kingdezigns.com`, `www.kingdezigns.com` | Separate Umami website with its own ID; tag added directly to that site's HTML, optionally with a copy of `reading-tracker.js`. | + +Optional: a third website "CutTheCard QA" (its ID pasted into the `debt.qa.cutthecard.net` entry in `site-scripts.js`) would allow testing in QA without polluting production data. Not created yet. + +--- + +## 🔌 How CutTheCard Loads Tracking +Full detail is in `server_debteliminator.md` §12h. Summary: +- Every public/app page carries **one** tag: `<script defer src="/dashboard/site-scripts.js?v=1"></script>`. +- `site-scripts.js` is the single registry of site-wide scripts. It loads Umami (page views, duration, referrers) and, on pages containing an `<article>`, `reading-tracker.js`. +- Custom events from `reading-tracker.js`: `scroll-depth` (25/50/75/100), `engaged-time` (30/60/120/180 s of active time), `article-read` (≥75% depth + ≥45 s active). +- CTA clicks can be tracked with `data-umami-event="..."` attributes on links — no JavaScript needed. +- Guards: admin area never tracked; only production hostnames report; Do Not Track and Global Privacy Control honored; Stripe-return pages have query/hash stripped; no `identify()` and no user data in event properties. + +--- + +## 🔐 Security & Privacy +- **Default login is `admin` / `umami` — it must be changed on first login** (Settings → Profile), with the new password stored in Vaultwarden. Umami has no built-in 2FA or lockout; use a long random password. +- Tracking is cookie-free and first-party. Inside the logged-in app it is **page-level only** (no user identity, no financial data). +- The Privacy Statement should disclose the analytics (see open items); legal wording should be reviewed, and publishing a new version triggers the re-acceptance gate for all users. +- Your own visits can be excluded per browser per site: `localStorage.setItem('umami.disabled', 1)` on that site's origin. + +--- + +## 💾 Backup +- Data to protect: `/opt/umami/pgdata` and `/opt/umami/umami.secrets`. +- Use `pg_dump`, not a raw copy of a live Postgres directory: + ```bash + sudo docker exec umami_db pg_dump -U umami umami | gzip > /tmp/umami-$(date +%Y%m%d).sql.gz + ``` +- **Status (2026-10-02): not yet folded into `/usr/scripts/omv/nas16-backup.sh`** — see open items. + +--- + +## 🛠️ Troubleshooting & Gotchas +| Symptom | Cause / Fix | +|---|---| +| `umami_db` unhealthy, log says superuser password not specified | Secrets not reaching the container — see "Why env_file" above. | +| `WARN The "UMAMI_DB_PASSWORD" variable is not set` | Compose still using `${...}` from an empty `umami.env`; use the `env_file` version of the compose file. | +| Chrome prompt "kingdezigns.com wants to access other devices on your local network" | Chrome Local Network Access. On the LAN, Pi-hole resolves `stats.cutthecard.net` to a private IP, and a **public** site loading a script from a private address triggers the prompt. Affects only the admin's own LAN browsers; real visitors resolve the public IP. Click Allow (remembered per site). | +| Tracker never sends data | Script `src` must be `https://` (an `http://` URL is blocked as mixed content on HTTPS pages); `data-domains` must be plain text matching the page's hostname (a copied markdown-link artifact like `[www.x.com](https://www.x.com)` breaks it); check `umami.disabled` in localStorage. | +| `dig: command not found` on NAS16 | Not installed; use `getent hosts stats.cutthecard.net` or `sudo apt install dnsutils`. | +| Pageviews appear but no Events | Events fire only on pages containing an `<article>` (blog posts and the six Learning Center guides), after scrolling/active time; confirm `reading-tracker.js` returns 200 in production; use Umami → Realtime to watch live. | +| `apply_site_scripts.py` crashes with PermissionError on `main.py` | The project directory is root-only; run the script with `sudo` (a dry run needs it too). | + +--- + +## ⏳ Open Items (2026-10-02) +1. **Verify custom events in production** — page views confirmed recording; `scroll-depth` / `engaged-time` / `article-read` not yet confirmed visible in Events (tracker logic passed simulated testing; check production file availability and test on a single article page). +2. Confirm the default `admin` password was changed and stored in Vaultwarden. +3. Add `/opt/umami/pgdata` (via `pg_dump`) and `/opt/umami/umami.secrets` to `nas16-backup.sh`. +4. Update the Privacy Statement to disclose first-party, cookie-free analytics (including page-level tracking inside the app); legal review; bundle with another legal version bump if possible. +5. Optional: create a QA website in Umami and paste its ID into `site-scripts.js`. +6. Tag the in-flight external demo page(s) if they should be tracked (`apply_site_scripts.py` accepts extra page paths). +7. Consider CTA click events (`data-umami-event`) for planner/signup funnel measurement. + +--- + +## 🧠 Summary for AI Systems +- Umami = **self-hosted, cookie-free analytics** on NAS16 (VLAN 50): containers `umami` (port 3001→3000) and `umami_db` (Postgres 16), OMV Compose project `umami` at `/Kingdezignsnas16/umami/`, public URL `https://stats.cutthecard.net` via NPM on HAS (Force SSL). Tracker script path is `/insights`. +- **Secrets are in `/opt/umami/umami.secrets` (outside OMV) via `env_file`** — OMV regenerates `umami.env` and wipes manual edits; `${VAR}` interpolation does not read service `environment:` entries. Never document secret values. +- Chosen over Google Analytics (privacy/trust/self-hosting philosophy) and Plausible CE (ClickHouse too heavy for the Pi). +- CutTheCard loads tracking through **one** loader (`/dashboard/site-scripts.js`); future scripts are added there only. See `server_debteliminator.md` §12h. +- Two Umami websites: CutTheCard and the personal kingdezigns.com site. +- Pi-hole override `stats.cutthecard.net → 192.168.150.30`; DDNS script updated; the Chrome Local Network Access prompt on LAN-side public sites is expected and harmless. +- Default login must be changed; backup is **not yet** in `nas16-backup.sh`; custom reading events were not yet confirmed at time of writing. + +--- + +# ✔️ End of File diff --git a/vlan1_infrastructure.md b/vlan1_infrastructure.md index 893deb4..064436a 100644 --- a/vlan1_infrastructure.md +++ b/vlan1_infrastructure.md @@ -1,7 +1,7 @@ # VLAN 1 — Infrastructure / Default Network Subnet: **192.168.100.0/24** -Last Updated: 2026-05-21 +Last Updated: 2026-09-15 --- @@ -31,6 +31,7 @@ This network remains active during ongoing migration and should not be aggressiv - Switches & access points - Emergency recovery access - At least one wired management workstation +- **KingDezigns-AI-001** (added 2026-09-14) — GMKtec NucBox K8 Plus running Ollama + OpenCode (local AI coding agent). Static reservations `192.168.100.50` / `192.168.100.51`. See `kingdezigns-ai-001-summary.md` and the note below. --- @@ -61,6 +62,13 @@ This network remains active during ongoing migration and should not be aggressiv - Infrastructure remains on VLAN 1 during migration. - Avoid strict firewall enforcement until migration is complete. - Maintain at least one wired management workstation for safety. +- **KingDezigns-AI-001's OpenCode web UI (port 4096) currently has no + server password set** (`OPENCODE_SERVER_PASSWORD` unset) — any device + that can reach `192.168.100.50:4096` / `.51:4096` can create files and + run shell commands on that host with no authentication. Accepted for + now as a trusted-home-LAN convenience, but **port 4096 must never be + port-forwarded to the internet**, and setting a server password is a + recommended follow-up. See `kingdezigns-ai-001-summary.md`. --- @@ -72,6 +80,12 @@ This network remains active during ongoing migration and should not be aggressiv - Guest VLAN 40 behavior depends on default policy. - All VLANs may send DNS to Pi‑hole in VLAN 50. - VLAN 1 is a reachable core network but protected from lower‑trust zones. +- **KingDezigns-AI-001** (192.168.100.50/.51) is a local AI coding + workstation on this VLAN — Ollama (loopback-only, `127.0.0.1:11434`) + + OpenCode (LAN-exposed web UI, port 4096, currently **no server + password**). Not the same machine as KingDezigns001 (VLAN 20 admin + workstation). See `kingdezigns-ai-001-summary.md` and + `network_index.md`. ---