Commit Graph

33 Commits

Author SHA1 Message Date
Matthew Meszaros 1317ea67d6 fix: rename duplicate migration 000035 to 000037
PR #10 added 000035_api_key_suffix and PR #11 separately added
000035_api_key_smart_limits, both targeting the api_keys table.
golang-migrate refuses to load when two source files share a
version number, so the backend container failed health checks
in fresh stacks.

Bumping api_key_smart_limits to 000037 keeps PR #10 in its
original slot (it landed first) and matches the next free
version after 000036_contact_categories. The two migrations
touch different columns so apply order does not matter.
2026-05-25 11:43:14 +00:00
Matthew Meszaros c790812207 Merge pull request #11 from warmbly/feature/api-keys-dashboard
feat: ship api keys dashboard with smart limits and analytics
2026-05-25 12:26:54 +02:00
Matthew Meszaros 02c2f097e9 fix: resolve duplicate migration 000034 (api_key_suffix -> 000035, contact_categories -> 000036) 2026-05-24 16:25:42 +00:00
Matthew Meszaros 9123c4bfcf feat: full api keys product (smart limits, analytics, dashboard) 2026-05-24 16:07:18 +00:00
Matthew Meszaros 07b0c8b5ff feat: backend contacts categories, smart export, csv/xlsx import 2026-05-24 16:04:48 +00:00
Matthew Meszaros 413108db49 Merge pull request #7 from warmbly/feature/full-seed-data
chore: stabilize CI and add repo hygiene for seed tooling
2026-05-24 17:18:31 +02:00
Matthew Meszaros 8002d56b86 feat: full api key support across data routes 2026-05-24 11:59:05 +00:00
Matthew Meszaros 6eb3a3bdfd merge: bring origin/main into branch, layer full seed on top of seedRich 2026-05-24 11:54:49 +00:00
Matthew Meszaros 0c1fa08a35 feat: full dev seed (users, orgs, workers, mailboxes, campaigns, crm, admin) 2026-05-24 11:41:51 +00:00
Matthew Meszaros c822e95e7f Merge remote-tracking branch 'origin/main' into feature/danger-zone-delayed-deletions
# Conflicts:
#	cmd/backend/main.go
#	internal/api/handler/handler.go
#	internal/api/routes.go
#	internal/models/audit.go
#	internal/models/organization.go
#	internal/models/user.go
#	internal/repository/pg_organization.go
#	internal/repository/pg_user.go
2026-05-24 04:12:10 +00:00
Matthew Meszaros e42feac0e4 feat: danger zone with delayed deletion for orgs and accounts 2026-05-24 04:06:07 +00:00
Matthew Meszaros 4eb8f7babe feat: settings overhaul, avatars, RBAC, plan alignment, perf
Backend:
- Fix contact-create 500 (nil custom_fields, doubled slice, bad RETURNING SQL)
- Avatar upload: migration 000033, S3 public-read, PNG/JPG only,
  client-resized to 512px + server dimension cap (1024px)
- Pull avatar_url through user + organization repo queries

Frontend:
- Settings restructured into nested routes with a rail layout
  (/app/settings/{profile,notifications,security,members,roles,
  workspace,billing,danger}); flat Section/Row primitives replace
  the per-card rectangles; Save buttons only render when dirty
- Standalone /app/billing and /app/team removed; legacy URLs
  redirect to the settings sections; UserNav trimmed accordingly
- CRM rebuilt: Pipelines CRUD + stage editor, Deals kanban with
  HTML5 drag/drop, Tasks bucketed by due-date with inline toggle.
  Frontend models realigned with backend (Deal.name, CRMTask.status
  enum, paginated list shapes)
- Avatars: AvatarUploader component, client-side canvas resize,
  wired into Profile + Workspace settings; UserNav + OrgSwitcher
  render the uploaded image with initials fallback
- RBAC: lib/permissions.ts mirrors organization_permission.go;
  inline role picker in Members; Roles & access section shows the
  permission matrix and per-role member counts
- Audit log page at /app/audit, gated to owner+admin via canManage
- Plans aligned with warmbly-web pricing: Starter/Grow/Business/
  Enterprise via lib/plans.ts; PlanPill, billing page, sidebar
  badges and LockedSurface all read from the same catalogue
- Header PlanPill shows current plan with status-aware coloring;
  sidebar locked rows show the required-plan badge instead of a
  generic lock icon

Perf:
- QueryClient defaults (staleTime: 30s, refetchOnWindowFocus: false,
  retry: 1) — kills 3-5 round-trip storm on every navigation
- useSubscription, usePlans → staleTime: Infinity (only invalidate
  on plan-change mutations); useUser/Timezones/Orgs get long stales
  with refetchOnMount: false
- vite.config: optimizeDeps for heavy libs + server.warmup for the
  most-mounted entry pages
2026-05-23 16:04:24 +00:00
Matthew Meszaros f9c02bba6e fix(db): plug 4 tx leaks + bump pool from 4 → 25 — root cause of 10-min logout
Root cause for the 10-min auto-logout (confirmed via pg_stat_activity):
the postgres pool MaxConns was 4, and four repository functions opened
a tx without committing or rolling back. After four calls each leaked
a connection in "idle in transaction" state. Once all four were gone
the pool was permanently exhausted — every new request that needed a
connection blocked until the client gave up. The 10-min trigger is
because that's when the first /auth/refresh fires; refresh tries to
acquire a connection, hangs, eventually the browser aborts the request,
the frontend treats the failure as session expiry, kicks the user.

The four leaking sites:
  - emailRepository.Search        (drove the leak — Accounts page)
  - campaignRepository.Search
  - sequenceRepository.Create
  - contactRepository.BulkUpdate

Each now has `defer tx.Rollback(ctx)` immediately after Begin, matching
the pattern used in the non-leaky sites in the same files. Rollback is
a no-op after Commit, so this is safe for both read-only tx (Search)
and read-write tx (Create / BulkUpdate).

Additional hardening so a future leak can't silently brick the backend:
  - MaxConns 4 → 25. 4 was reckless even without leaks; one bursty
    admin page would saturate. 25 is still well under postgres'
    default max_connections=100.
  - MinConns 0 → 2. Keep a couple of warm connections at idle so the
    first request after a quiet period doesn't pay the connect cost.
  - idle_in_transaction_session_timeout=300000 (5 min) as a session
    RuntimeParam. If a code path forgets the defer, postgres aborts
    the leaked tx after 5 min and reclaims the connection.
  - statement_timeout=60000 (60 s) as a session RuntimeParam.
    Statement runaway can't pin a connection forever.

Verified after backend restart:
  SELECT count(*) FROM pg_stat_activity
    WHERE datname='warmbly_dev' AND state='idle in transaction';
  → 0
2026-05-23 04:41:40 +00:00
Matthew Meszaros 7766b690b4 feat(workers): free-form tags for categorizing the fleet
Migration 000032 + repo + endpoints for arbitrary string tags on
workers. The fixed attributes (worker_type, free_tier, risk_pool)
cover the dimensions assignment logic uses. Tags cover everything
else admins want to group by: region (eu-west, fra), provider
(hetzner, ovh), role (warmup-only, burst-capacity), customer cohort —
whatever.

Schema:
  - worker_tags(worker_id, tag) composite PK
  - tag VARCHAR(64), lowercase + dashed via CHECK constraint
  - ON DELETE CASCADE so deleting a worker drops its tags

Endpoints:
  - GET  /admin/workers/tags             list distinct tags (autocomplete)
  - PUT  /admin/workers/:id/tags         replace tag set; normalizes input

Repo:
  - GetWorkerTags / SetWorkerTags / ListAllWorkerTags
  - HydrateWorkerTags batch-loads tags onto a slice of workers in one
    round-trip so the dashboard list doesn't do N+1 queries

PUT is transactional (delete + bulk insert) so the list view never
catches a worker mid-tag-swap. Auto-derived "smart" labels
(tier:free, pool:risky, state:error) are NOT stored — those are
computed client-side from the worker row so they stay in sync with
the source attributes automatically. Next commit wires the UI.
2026-05-20 14:15:52 +00:00
Matthew Meszaros ba1c10fe19 feat(workers): risk-pool schema + per-mailbox risk band
Threat-level segregation, schema layer. Two new concepts:

  workers.risk_pool ∈ {clean, risky, quarantine}
    buckets shared workers by acceptable risk. Dedicated workers don't
    use it (single tenant = no cross-contamination risk).

  email_accounts.risk_band ∈ {clean, risky, quarantine}
    per-mailbox classification, derived from warmup_health_state by the
    rebalancer (next commit). Never set by user input.

The mapping is one-way and intentionally simple:

  healthy           → clean
  watch, throttled  → risky
  quarantined,      → quarantine
  blocked

Rebalancer code lands in the next commit. This commit just adds:

  - migration 000031 with enums + columns + filtered indexes
  - WorkerRiskPool / EmailRiskBand types + RiskBandFromHealth helper
  - WorkerRepository methods: SetWorkerRiskPool, SetEmailAccountRiskBand,
    GetSharedWorkersByTierAndPool, ListRiskCandidates
  - RiskCandidate result type joining email_accounts + warmup health
    (picks WORST state across pools via CASE ranking) + worker columns
    so the rebalancer can decide migrations in one scan
2026-05-19 05:36:25 +00:00
Matthew Meszaros 261cc439ad feat(admin): manage worker fleet from dashboard with encrypted credentials and GitHub release auto-update
Workers are no longer curl|sh-only. Admins add and manage them from the
dashboard over SSH, with all runtime config (Kafka, Schema Registry,
Redis, AWS keys) stored encrypted via the existing KMS-envelope cipher
service.

Worker lifecycle:
  1. Admin POSTs host/port/user. Backend generates an ed25519 keypair,
     encrypts the private key under uuid.Nil (platform identity), and
     stores the row in 'pending' state.
  2. Admin pastes the returned public key into the VPS's authorized_keys.
  3. Test connection — runs `true` over SSH, pins the host SHA256
     fingerprint on first success (TOFU).
  4. Install — backend scp's install-worker.sh + a per-worker env file
     and runs it. State moves pending → provisioning → installed.
  5. From then on: restart, update image, apply config, uninstall,
     rotate keys, tail logs, live status, OS package update, reboot —
     all dashboard buttons backed by SSH operations.

Credentials are reusable entities:
  - aws_credentials: named keypair, secret encrypted at rest
  - worker_profiles: bundles Kafka + Schema Registry + Redis + image +
    release channel, references one AWS credentials row
  - workers.profile_id links a worker to a profile; many workers can
    share one profile

Saving a profile doesn't restart anything. The dashboard compares
profile.updated_at to each worker's config_applied_at and shows a
"stale config" badge; Apply rewrites /etc/warmbly/worker.env over SSH
and restarts the unit.

Auto-update on GitHub release:
  - profile.release_channel ∈ {pinned, stable, dev}
  - profile.auto_update toggles automatic rollout
  - Trigger model is push, not poll: one check on backend boot, then
    the /webhooks/github/releases endpoint (HMAC-validated with
    RELEASES_WEBHOOK_SECRET) on every release event. Manual "Check now"
    button as fallback.
  - When a new tag resolves, the orchestrator SSHes into each assigned
    worker, runs install-worker.sh --update --image <new>, which now
    rewrites the systemd unit (not just `docker pull`) so the image
    actually changes. workers.image_version captures the running tag
    for the UI's "v1.2.3 → v1.2.4" diff.

Self-hostable: every release knob is env-driven —
RELEASES_GITHUB_REPO, RELEASES_WORKER_IMAGE_REPO,
RELEASES_WEBHOOK_SECRET, RELEASES_GITHUB_TOKEN, RELEASES_ENABLED. Set
RELEASES_ENABLED=false to disable the feature entirely.

OS-level updates and reboot are also exposed: detect apt / dnf / yum /
pacman / apk, run the right upgrade noninteractively, return the full
output and a reboot-required flag. Reboots are never automatic.

Migrations:
  000028_worker_ssh        — ssh fields, install_state enum, last_seen,
                              host fingerprint
  000029_worker_credentials — aws_credentials + worker_profiles +
                              workers.profile_id + workers.config_applied_at
  000030_worker_releases   — release_channel enum, auto_update,
                              resolved_image_tag, workers.image_version

Endpoints added:
  POST   /admin/workers                        (create + keypair)
  GET    /admin/workers/managed
  GET    /admin/workers/:id/managed
  POST   /admin/workers/:id/{test,install,restart,upgrade,uninstall,rotate-keys,apply,system-update,reboot}
  PUT    /admin/workers/:id/profile
  GET    /admin/workers/:id/{live-status,logs}
  DELETE /admin/workers/:id
  GET    /admin/aws-credentials                CRUD
  GET    /admin/worker-profiles                CRUD + /workers + /apply + /release
  GET    /admin/releases/state
  POST   /admin/releases/check
  POST   /webhooks/github/releases             public, HMAC-validated

Admin UI:
  /app/admin/workers           list with status + version columns
  /app/admin/workers/new       add form with profile dropdown
  /app/admin/workers/:id       detail with all actions + logs + system update
  /app/admin/credentials       tabs: AWS credentials + worker profiles,
                                Releases panel, channel selector +
                                auto-update toggle in profile form
2026-05-18 13:09:11 +00:00
Matthew Meszaros 9c4b6d21fd fix: add contact email deduplication with unique index and upsert on conflict 2026-04-09 15:12:41 +00:00
Matthew Meszaros 36f4a94814 fix: prevent race condition in dedicated worker assignment with atomic insert 2026-04-09 14:54:22 +00:00
Matthew Meszaros 306690db0a feat: add explicit position column to sequences for deterministic ordering 2026-04-09 14:52:17 +00:00
Matthew Meszaros d417b1f0a4 perf: add missing index on campaign_leads(contact_id) for reverse lookups 2026-04-09 14:43:40 +00:00
Matthew Meszaros 19d20e72b4 feat: add warmup health throttled state, complaint/bounce metrics, A/B analysis, and rate limiting 2026-04-09 12:51:30 +00:00
Matthew Meszaros d8d88c7f69 feat: add warmup health tracking, migrate repos to postgres, and overhaul web UI 2026-04-03 06:08:52 +00:00
Matthew Meszaros 21ffb6a748 feat: add advanced outreach controls with A/B testing, deliverability dashboard, and DLQ 2026-02-20 08:59:17 +00:00
Matthew Meszaros 6c6d26d8f0 Update auth and onboarding flow 2026-02-14 05:38:27 +01:00
Matthew Meszaros 141bc54974 Add sample auth UI theme 2026-02-10 19:30:47 +01:00
Máté Mészáros (Laptop) ed35ab2dbc Realtime Updates 2026-01-30 15:32:58 +01:00
Máté Mészáros (Laptop) 8e3c399232 Auto deploy on new release 2026-01-30 04:29:07 +01:00
Máté Mészáros (Laptop) 41624a6f79 Analytics & Tracking 2026-01-29 05:59:04 +01:00
Máté Mészáros (Laptop) 6adb4cdd5a Organization, Subscription, Inqueries, limits. 2026-01-27 05:55:48 +01:00
Máté Mészáros (Laptop) 5ac159d2f8 Realtime, api keys & more 2026-01-26 16:04:42 +01:00
Máté Mészáros (Laptop) 81d5970ea8 Realtime, Task Handler, Worker & Consumer Setup 2026-01-26 04:42:19 +01:00
Máté Mészáros (Laptop) 4a1c8cddeb AI integration & warmup task 2026-01-24 12:31:22 +01:00
Matthew Meszaros 772c19820d New Repository: Add Backend Code 2026-01-17 14:11:14 +00:00