mirror of
https://github.com/Dvorinka/Containr.git
synced 2026-10-28 07:41:27 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6949c01464 | ||
|
|
17e429b86b | ||
|
|
e881747388 | ||
|
|
f9ae5b962c | ||
|
|
15b5b0e6e7 | ||
|
|
32b52d121f |
No files matched your search
@@ -0,0 +1 @@
|
|||||||
|
github: Dvorinka
|
||||||
@@ -56,7 +56,7 @@ dedicated console.
|
|||||||
- **Template catalog** — 30 official templates (NocoDB, Plausible, MinIO, n8n, …) plus user-defined templates with JSON upload and owner-scoped edit/delete
|
- **Template catalog** — 30 official templates (NocoDB, Plausible, MinIO, n8n, …) plus user-defined templates with JSON upload and owner-scoped edit/delete
|
||||||
- **Metrics** — per-service Docker stats plus host CPU/memory/disk telemetry
|
- **Metrics** — per-service Docker stats plus host CPU/memory/disk telemetry
|
||||||
- **HA & scaling** — failover policies, node agents, autoscaling rules
|
- **HA & scaling** — failover policies, node agents, autoscaling rules
|
||||||
- **Auth & security** — Better Auth sessions (email/password self-hosted), audit logs, vulnerability scans
|
- **Auth & security** — Better Auth sessions (email/password self-hosted), personal access tokens with `read`/`write`/`admin` scopes for CLI and agents, audit logs, vulnerability scans
|
||||||
- **Integrated docs** — searchable documentation rendered in-app on the landing page and `/docs`; syncs from GitHub, falls back to a bundled snapshot offline
|
- **Integrated docs** — searchable documentation rendered in-app on the landing page and `/docs`; syncs from GitHub, falls back to a bundled snapshot offline
|
||||||
- **Networking** — Traefik reverse proxy, optional Cloudflare Tunnel
|
- **Networking** — Traefik reverse proxy, optional Cloudflare Tunnel
|
||||||
|
|
||||||
|
|||||||
+396
@@ -0,0 +1,396 @@
|
|||||||
|
# Containr — Roadmap 2: The dflow Convergence
|
||||||
|
|
||||||
|
Last verified: **2026-10-08** — deep pass over the full dflow codebase
|
||||||
|
(`~/Desktop/PROG+HTML/dflow`, community fork of dflow-sh/dflow, frozen for
|
||||||
|
preservation) against Containr `main` (`15b5b0e`).
|
||||||
|
|
||||||
|
Goal: make Containr the superior successor — absorb everything worth having
|
||||||
|
from dflow, then go past it and past Railway. Same power for humans and
|
||||||
|
agents: the UI is the friendly face, the CLI and MCP are the machine face,
|
||||||
|
all three sit on the same API. **Branding stays Containr/Vertice** —
|
||||||
|
white-labeling is an admin option, not an identity change.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. What dflow actually is (verified)
|
||||||
|
|
||||||
|
Next.js 15 + PayloadCMS 3 + MongoDB + Redis/BullMQ. Runtime model: every
|
||||||
|
host is a remote server driven **over SSH** with Dokku auto-installed as the
|
||||||
|
per-app container manager. Async work = 43 BullMQ queue processors
|
||||||
|
(`src/queues/**`), live logs via Redis pub/sub → SSE endpoint, persisted to
|
||||||
|
deployment records. ~30 collections, ~180 server actions, 11 dashboard
|
||||||
|
routes per service (general, deployments, logs, environment, domains,
|
||||||
|
volumes, proxy, scaling, backups, settings).
|
||||||
|
|
||||||
|
### Full capability matrix — dflow → Containr
|
||||||
|
|
||||||
|
Legend: ✅ done · 🟡 partial/different · ❌ missing · ➖ not applicable (dokku/SSH-specific)
|
||||||
|
|
||||||
|
#### Deployment pipeline
|
||||||
|
| dflow capability | Containr status | Action |
|
||||||
|
|---|---|---|
|
||||||
|
| Queued deployments, serialized per server, cancellable while queued | ❌ goroutine fire-and-forget; `CancelDeployment` exists in engine but is **never routed** | Add deploy queue + cancel route |
|
||||||
|
| Deployment states `queued → building → success/failed`, live SSE logs + persisted record | 🟡 states exist (`building→running`); WS streams builds; no queued state | Extend status + stream |
|
||||||
|
| Redeploy cache modes (`ps:rebuild` vs fresh pull); webhook pushes force `no-cache` | ❌ always rebuilds | Add `cache` flag on deploy/redeploy |
|
||||||
|
| Cancel queued deployment from UI | ❌ (engine fn unrouted) | Route it |
|
||||||
|
| Per-service job ordering | ❌ concurrent deploys of one service can race | Serialize per service |
|
||||||
|
|
||||||
|
#### Service configuration
|
||||||
|
| dflow capability | Containr status | Action |
|
||||||
|
|---|---|---|
|
||||||
|
| Multi-domain per service + default flag + cert type | ❌ single `services.domain` | `service_domains` table |
|
||||||
|
| Cert types: letsencrypt / none / Cloudflare Origin / **CF-for-SaaS custom hostnames** | 🟡 Traefik ACME only | LE default; CF custom hostnames deferred (only needed if hosting tenant domains) |
|
||||||
|
| DNS preflight check (`checkDNSConfigAction`) | ❌ | `GET /services/:id/domains/check` |
|
||||||
|
| Volumes per service + dangling-volume browser/attach/delete | ❌ engine supports `VolumeMounts`; no API/UI | `services.volumes` jsonb + Volumes tab |
|
||||||
|
| Resource **limits and reservations**, per-server defaults | 🟡 `cpu_limit`/`memory_limit` int columns (unclear units) | explicit string units + reserves + instance defaults |
|
||||||
|
| Pre-deploy capacity check (dokku binary interceptor) | ❌ | Node capacity check pre-deploy/scale |
|
||||||
|
| Maintenance mode toggle | ❌ | Traefik middleware label |
|
||||||
|
| Basic-auth gate per service (`toggleHttpAuth`) | ❌ | Traefik basic-auth middleware |
|
||||||
|
| Raw proxy config override (`setServiceNginxConfig`) | ❌ | Allowlisted `traefik_labels` jsonb |
|
||||||
|
| Service clone (full config copy) | ❌ | `POST /services/:id/clone` |
|
||||||
|
| Move service between projects (`SwitchServiceProjectDialog`) | ❌ | `PUT /services/:id {project_id}` |
|
||||||
|
| Env var save → hot-apply + optional restart (`noRestart`) | ❌ rows rewritten; containers keep stale env until manual redeploy | Apply→redeploy flow |
|
||||||
|
| Static-site builder; Heroku buildpacks | 🟡 railpack/nixpacks/dockerfile auto-detect, no user override | `services.builder` enum + static builder |
|
||||||
|
| Docker registry accounts (private registries) | ❌ | `registry_credentials` per service/instance |
|
||||||
|
|
||||||
|
#### Databases
|
||||||
|
| dflow capability | Containr status | Action |
|
||||||
|
|---|---|---|
|
||||||
|
| Managed DBs (pg/mysql/mariadb/mongo/redis/clickhouse via dokku plugins) | ✅ plus dragonfly | — |
|
||||||
|
| **External DB registration** (Neon/Atlas/RDS conn details + test) | ❌ | `provider=external` + test endpoint |
|
||||||
|
| Internal backups + restore (same-type enforced) | ✅ | — |
|
||||||
|
| Scheduled backups | ✅ cron field | — |
|
||||||
|
| **External S3 backups** (auth/schedule/unschedule ops) | ❌ | `backup_targets` + shipper |
|
||||||
|
| **Cross-server DB migration** (export → sftp hop → import) | ❌ | `POST /databases/:id/migrate` |
|
||||||
|
| Public DB port expose/unexpose | ❌ loopback only | opt-in TCP expose |
|
||||||
|
| DB → service env linking (`dokku link`) | ✅ Bind action injects `DATABASE_URL` | — |
|
||||||
|
|
||||||
|
#### Servers / infrastructure
|
||||||
|
| dflow capability | Containr status | Action |
|
||||||
|
|---|---|---|
|
||||||
|
| Attach server = paste IP + SSH key; Dokku auto-installs | 🟡 agents exist, manual install | **SSH bootstrap**: one SSH session installs agent, never needed again |
|
||||||
|
| Tailscale/Headscale, NetBird, ZeroTier enroll + mesh connect | ❌ | Agent mesh-IP detection first; auth-key enroll optional |
|
||||||
|
| AWS EC2 + Hetzner provisioning w/ cloud-init | ❌ | IaC (ROADMAP §2.2): Terraform Proxmox/AWS + Hetzner module |
|
||||||
|
| Security groups (AWS SG rules, sync) | ❌ | Under IaC provider modules |
|
||||||
|
| Server-level global/wildcard domain (`updateServerDomain`) | ❌ | `nodes.default_domain` |
|
||||||
|
| Scheduled server cleanup (dokku cleanup → docker prune) | ❌ | Agent `prune` command + schedule |
|
||||||
|
| Queue flush/inspect per server (`flushServerQueues`, `getServerQueues`) | ➖ no queue yet | Ops page shows jobs once queue exists |
|
||||||
|
| Arbitrary SSH command on server (`executeCommand`) | ➖ exec is container-scoped | Node terminal via agent (PTY) |
|
||||||
|
| Server onboarding wizard, reset, cleanup-on-delete | 🟡 token issue/revoke only | Onboarding flow + `nodes add` UX |
|
||||||
|
| Ansible playbooks (stored, runnable per server, exec history) | ➖ | **Defer** — security surface; SSH bootstrap covers provisioning |
|
||||||
|
| Per-node resource dashboards | 🟡 heartbeat telemetry exists | Node detail page |
|
||||||
|
|
||||||
|
#### Platform / org
|
||||||
|
| dflow capability | Containr status | Action |
|
||||||
|
|---|---|---|
|
||||||
|
| Multi-tenant organisations + custom RBAC (per-resource CRUD, create-limits, read-scope) | 🟡 `is_admin` + `project_members` | Defer full RBAC; design PAT scopes role-compatible |
|
||||||
|
| Team invite links/emails | 🟡 manual user create only | `POST /invites` → link join |
|
||||||
|
| User API keys → full REST API | ❌ **the big gap** — session/JWT only | PATs (Phase A) |
|
||||||
|
| Outbound webhooks (collection events, HMAC, custom headers) | ❌ | `webhooks` table + delivery log |
|
||||||
|
| Banners (global + per-tenant, dismissible) | ❌ | `banners` table + top bar |
|
||||||
|
| White-label (logo/favicon/title/OG/theme colors) | ❌ | `app_settings.branding` — **Containr remains the default brand** |
|
||||||
|
| Activity feed (icon/severity/category/metadata, 90-day TTL job) | 🟡 `audit_logs` coarser | Enrich + project feed UI |
|
||||||
|
| Admin metrics dashboard (users/servers/queued/failed counts) | 🟡 `/admin` exists | Extend |
|
||||||
|
| **Impersonate user** | ❌ | Admin support tool |
|
||||||
|
| In-app docs (content-collections markdown) | ✅ `/docs` | — |
|
||||||
|
| Dynamic client-side filter framework (535-line `filter.utils`) | 🟡 audit page filters only | Reuse pattern for tables |
|
||||||
|
| Ops "bubble" (queue monitor, terminal, sync) | ❌ | Operations page |
|
||||||
|
|
||||||
|
#### Agent surface
|
||||||
|
| dflow capability | Containr status | Action |
|
||||||
|
|---|---|---|
|
||||||
|
| Payload REST/GraphQL auto-API + per-user API keys | ❌ | PATs + OpenAPI (better: typed, documented) |
|
||||||
|
| CLI | ❌ | none in dflow — **Containr CLI is a genuine leap past it** |
|
||||||
|
| MCP | ❌ | none — same leap |
|
||||||
|
| Railway migrator script | ❌ | `containr migrate railway` |
|
||||||
|
| GitHub App **manifest flow** (instance self-provisions the App) | 🟡 env-configured App | `POST /git/github-app/manifest` flow |
|
||||||
|
| fork-sync webhook deploy trigger | ❌ | ~20 lines on receiver |
|
||||||
|
| Azure DevOps provider | ❌ | Optional (dflow does token-clone only) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. The spine: agent-first platform
|
||||||
|
|
||||||
|
*Agent and user on the same level.* Concretely:
|
||||||
|
|
||||||
|
- Every operation reachable by a **personal access token**, not just
|
||||||
|
sessions.
|
||||||
|
- Every operation in the **CLI** with `--json`, stable exit codes, `--yes`.
|
||||||
|
- Every operation in an **MCP server** (stdio first) so Devin/Claude Code/
|
||||||
|
Cursor/Codex drive Containr natively.
|
||||||
|
- `openapi.yaml` stays the single source of truth; UI, CLI, MCP are thin
|
||||||
|
clients.
|
||||||
|
|
||||||
|
### Phase A — Agent surface (do this FIRST; everything after inherits it)
|
||||||
|
|
||||||
|
- [ ] **Personal access tokens.** `user_tokens` table — `id`, `user_id`,
|
||||||
|
`name`, `key_prefix` (`cnp_…`), `key_hash` (sha256), `scopes`
|
||||||
|
(`read`/`write`/`admin`, later resource-scoped), `expires_at`,
|
||||||
|
`last_used_at`. Model on `agent_auth_tokens` (raw shown once, hash stored).
|
||||||
|
`POST/GET/DELETE /api/v1/user/tokens`; `middleware.Auth` accepts
|
||||||
|
`Bearer cnp_…`; Settings → Access tokens UI with one-time display +
|
||||||
|
copyable CLI/MCP config snippets.
|
||||||
|
- [ ] **CLI v2.** Current `cmd/cli` is auth + projects only. Full client:
|
||||||
|
- `auth login [--token] [--url] [--profile]` (multi-instance profiles).
|
||||||
|
- Resources: `projects services deploy logs exec variables databases
|
||||||
|
cron templates nodes scaling ha security gateway notifications
|
||||||
|
webhooks domains volumes backups admin`.
|
||||||
|
- `containr up` / `deploy` — cwd→service create-or-update→watch
|
||||||
|
(the `railway up` equivalent; single most important command).
|
||||||
|
- `containr link` (bind cwd→service), `containr open`, `containr run`,
|
||||||
|
`containr shell` (PTY once exec upgrade lands), `completion`.
|
||||||
|
- Universal `--json`, `-o yaml`, `--watch`, `--yes`; exit codes
|
||||||
|
0/1/2/3/4 (ok/err/not-found/unauthorized/conflict).
|
||||||
|
- GoReleaser → GH releases + `install.sh`; `version` command.
|
||||||
|
- Conventions from docsync/envdiff/cix/repolint.
|
||||||
|
- [ ] **MCP server** (`cmd/mcp`, same module, stdio). Tools mirror the
|
||||||
|
CLI: `list_projects create_service deploy get_logs set_variable
|
||||||
|
restart rollback create_database trigger_cron deploy_template exec
|
||||||
|
get_metrics security_scan …`. Auth: `CONTAINR_URL` + `CONTAINR_TOKEN`
|
||||||
|
or shared `~/.containr/config`. `containr mcp serve` + install snippets
|
||||||
|
for Devin/Claude/Cursor.
|
||||||
|
- [ ] **API agent ergonomics.** `Idempotency-Key` on mutating endpoints;
|
||||||
|
uniform `{error, code, details}` envelope (audit bare-string returns);
|
||||||
|
cursor pagination on growing lists; name-or-id lookup everywhere.
|
||||||
|
- [ ] **Agent docs.** Root `AGENTS.md`, `/docs` serves `llms.txt` +
|
||||||
|
`llms-full.txt`, MCP tool list generated from OpenAPI where possible.
|
||||||
|
|
||||||
|
**Gate**: an agent holding only a PAT registers a project, deploys from a
|
||||||
|
git repo, streams logs, sets vars, rolls back — zero UI. Same via CLI
|
||||||
|
for a human.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Phase B — Deployment pipeline maturity
|
||||||
|
|
||||||
|
dflow's one real architectural edge. Containr deploys are fire-and-forget
|
||||||
|
goroutines; this fixes correctness *and* unlocks the ops surface.
|
||||||
|
|
||||||
|
- [ ] **Deploy job queue.** Lightweight internal queue (Postgres
|
||||||
|
`deployment_queue` table + single worker loop — no new infra; Redis
|
||||||
|
exists but don't add BullMQ-style sprawl). Serialize per service;
|
||||||
|
optional per-node serialization. Status gains `queued`.
|
||||||
|
- [ ] **Cancel deployments.** Route `POST /deployments/:id/cancel` →
|
||||||
|
engine `CancelDeployment` (exists, unrouted). Queued jobs cancel
|
||||||
|
cleanly; building jobs cancel context where safe.
|
||||||
|
- [ ] **Cache modes.** `?cache=full` on redeploy → rebuild from existing
|
||||||
|
image layers vs clean pull/checkout. Webhook-triggered deploys default
|
||||||
|
to no-cache (dflow convention — prevents stale-layer surprises).
|
||||||
|
- [ ] **Queued→building→running status + persisted step logs.** Already
|
||||||
|
mostly there; add `queued`, stream over existing `/ws`.
|
||||||
|
- [ ] **Env var apply → redeploy.** Saving variables asks "restart to
|
||||||
|
apply?" (or `--apply` flag in CLI); backend triggers redeploy honoring
|
||||||
|
running state. Currently rows update but containers keep stale env —
|
||||||
|
silent-drift bug class, not just UX.
|
||||||
|
- [ ] **Encrypt variables at rest.** `environment_variables.value` is
|
||||||
|
plaintext today (verified). Envelope-encrypt `is_secret` values
|
||||||
|
(AES-GCM, key from `JWT_SECRET` or dedicated `SECRETS_KEY`); dflow
|
||||||
|
encrypts every var, we encrypt secrets — migration = transparent
|
||||||
|
encrypt-on-write + decrypt-on-read.
|
||||||
|
|
||||||
|
## 4. Phase C — Service configuration parity
|
||||||
|
|
||||||
|
- [ ] **Volumes on services** — `services.volumes` jsonb
|
||||||
|
`[{volume|host_path, container_path, read_only}]`; engine accepts
|
||||||
|
`VolumeMounts` already. Volumes tab + orphan-volume listing
|
||||||
|
(`docker volume ls -f dangling`) with delete/attach.
|
||||||
|
- [ ] **Multi-domain** — `service_domains(service_id, domain, is_default,
|
||||||
|
cert_type, status, last_checked_at)`. Domains tab: add/remove/
|
||||||
|
set-default/DNS-status badge. Keep `services.domain` as derived
|
||||||
|
default for compat.
|
||||||
|
- [ ] **DNS preflight** — `GET /services/:id/domains/check` resolves and
|
||||||
|
compares vs edge IP → `ok|wrong-target|pending`.
|
||||||
|
- [ ] **Maintenance mode + basic-auth gate** — Traefik middleware labels;
|
||||||
|
no proxy code needed.
|
||||||
|
- [ ] **Routing overrides** — `services.traefik_labels` jsonb with
|
||||||
|
allowlist validation (middlewares, headers, redirects).
|
||||||
|
- [ ] **Builder override** — `services.builder` enum
|
||||||
|
`auto|railpack|nixpacks|dockerfile|static`; fix hardcoded `nixpacks`
|
||||||
|
at `deployments.go:406`. Static builder = build + nginx sidecar.
|
||||||
|
- [ ] **Resource limits + reserves** — adopt dflow-style explicit units
|
||||||
|
(`"0.5"`/`"512m"`); add `cpu_reserve`/`memory_reserve` →
|
||||||
|
`NanoCPUs`/`Memory`/`MemoryReservation`; instance defaults in
|
||||||
|
`app_settings`.
|
||||||
|
- [ ] **Pre-deploy capacity check** — sum reservations vs node capacity
|
||||||
|
(agent telemetry); warn or block per policy flag.
|
||||||
|
- [ ] **Service clone** + **move between projects**.
|
||||||
|
- [ ] **Private registries** — `registry_credentials`
|
||||||
|
(server/username/secret, encrypted); `docker login` at pull time;
|
||||||
|
per-service registry link.
|
||||||
|
- [ ] **Service detail tabs to match dflow's surface**: add Domains,
|
||||||
|
Volumes, Proxy/access-controls, Backups sections to the service page
|
||||||
|
(Cron/Previews/Scaling already exist).
|
||||||
|
|
||||||
|
## 5. Phase D — Data layer maturity
|
||||||
|
|
||||||
|
- [ ] **External DB registration** — `provider='managed'|'external'`,
|
||||||
|
conn fields, `POST /databases/test-connection`, same bind flow.
|
||||||
|
- [ ] **Public DB port expose** — opt-in Traefik TCP route or host port;
|
||||||
|
default stays loopback.
|
||||||
|
- [ ] **Offsite backups** — `backup_targets` (S3-compatible:
|
||||||
|
endpoint/bucket/keys encrypted); per-DB destination; ship archives via
|
||||||
|
utility container + s3 SDK; restore-from-S3.
|
||||||
|
- [ ] **Cross-node DB migration** — `POST /databases/:id/migrate
|
||||||
|
{target_node_id}`: dump → stream transfer → provision → restore →
|
||||||
|
re-point bound services. Needs ≥2 nodes or local↔node.
|
||||||
|
- [ ] **Backup import** — upload archive → new restore point (pairs with
|
||||||
|
migrators).
|
||||||
|
|
||||||
|
## 6. Phase E — Templates v2 (absorbs compose-catalog spec + dflow graph templates)
|
||||||
|
|
||||||
|
- [ ] **Template = ordered service graph** — `services[]` entries with
|
||||||
|
`{name, type, source, build, ports, volumes, variables, depends_on}`;
|
||||||
|
deploy order from dependency refs.
|
||||||
|
- [ ] **Expressions** — `${{service.KEY}}` (already the runtime ref
|
||||||
|
syntax — reuse), `{{secret(len,"charset")}}`, `{{random:int}}`,
|
||||||
|
`{{VAR:-default}}`; `POST /templates/:id/plan` returns the resolved
|
||||||
|
graph without deploying (agents love this).
|
||||||
|
- [ ] **Compose import** — `POST /templates/import/compose` (compose-go
|
||||||
|
parser → graph), `POST /templates/import/github` (compose file from
|
||||||
|
repo path). Implements `docs/superpowers/specs/2026-04-14-*`.
|
||||||
|
- [ ] **Graph deploy pipeline** — creates project + services in
|
||||||
|
dependency order, resolves vars, triggers builds; defined
|
||||||
|
partial-failure policy.
|
||||||
|
- [ ] **Visual template builder** — canvas mode: drop git/image/db
|
||||||
|
nodes, wire refs, set order, save/publish. Reuses existing canvas
|
||||||
|
primitives (dflow's `templates/compose` is exactly this).
|
||||||
|
- [ ] **Catalog growth** — convert `templates/*.md` (20 app guides) into
|
||||||
|
real graph templates; screenshots + badges per the old spec.
|
||||||
|
|
||||||
|
**Gate**: paste n8n compose → 3-service project with generated secrets
|
||||||
|
and wired refs, one click or one CLI call.
|
||||||
|
|
||||||
|
## 7. Phase F — Nodes & infrastructure
|
||||||
|
|
||||||
|
- [ ] **SSH bootstrap install** — `containr nodes add --ssh user@host` +
|
||||||
|
UI flow: one SSH session runs agent install (binary + systemd +
|
||||||
|
enroll token), SSH closed forever. dflow onboarding UX, agent-model
|
||||||
|
security.
|
||||||
|
- [ ] **Mesh awareness** — agent detects + reports tailscale0/netbird0/
|
||||||
|
zt0 IPs at register; backend stores + displays. Optional
|
||||||
|
`TAILSCALE_AUTH_KEY` enroll-at-provision later.
|
||||||
|
- [ ] **Node detail page** — placed services, telemetry history, agent
|
||||||
|
version + self-upgrade, **drain/cordon**, remove.
|
||||||
|
- [ ] **Node housekeeping** — agent `prune` command (docker system
|
||||||
|
prune, bounded) + optional schedule (`setServerAutoCleanup` analog —
|
||||||
|
disk pressure is the #1 small-VPS killer).
|
||||||
|
- [ ] **Multi-node scheduling** — wire `scheduling_rules` (table exists):
|
||||||
|
pin/spread/affinity, prefer-lowest-usage; deploy engine routes to
|
||||||
|
`services.node_id` via agent commands (agent already runs containers).
|
||||||
|
- [ ] **Build-on-node** — agents currently `docker run` prebuilt images
|
||||||
|
only; extend agent to pull registry images (build stays central) —
|
||||||
|
private registry creds flow through Phase C.
|
||||||
|
- [ ] **IaC provisioning (ROADMAP §2.2, unchanged)** — Terraform/
|
||||||
|
OpenTofu, `infra_connections`, Proxmox + AWS modules, + Hetzner module
|
||||||
|
(dflow's second provider), cloud-init → auto-enroll.
|
||||||
|
- [ ] **Global/wildcard domain per node** (`nodes.default_domain`) —
|
||||||
|
auto-domains for services on that node.
|
||||||
|
|
||||||
|
## 8. Phase G — Platform polish
|
||||||
|
|
||||||
|
- [ ] **Outbound webhooks** — `webhooks(url, secret, events[], headers,
|
||||||
|
enabled)` + `webhook_deliveries` log; HMAC `X-Containr-Signature`;
|
||||||
|
events: `deployment.* service.* database.* security.* agent.*`.
|
||||||
|
- [ ] **Activity feed** — enrich `audit_logs` with `severity category
|
||||||
|
icon label metadata`; per-project timeline + global feed; TTL job.
|
||||||
|
- [ ] **Banners** — `banners(title, body, level, scope, active)`; top
|
||||||
|
bar in UI + surfaced to CLI on `auth status`.
|
||||||
|
- [ ] **White-label** — `app_settings.branding`: product name, logos,
|
||||||
|
favicon, accent override, docs/support links. `GET /api/v1/branding`
|
||||||
|
public + cached. **Containr/Vertice remains default;** this is for
|
||||||
|
self-hosters who rebrand their instance.
|
||||||
|
- [ ] **Operations page** — unified view of running/queued/failed jobs
|
||||||
|
(deploys, builds, backups, cron, scans, agent commands) — dflow's
|
||||||
|
bubble panel as a real page; flush/stuck-job tools once queue exists.
|
||||||
|
- [ ] **Interactive terminal** — upgrade exec to WS PTY (`xterm.js`);
|
||||||
|
`nodes/:id/terminal` via agent (dflow's wetty without the extra
|
||||||
|
container).
|
||||||
|
- [ ] **Team invites** — `POST /invites` → signed link → join flow;
|
||||||
|
replaces manual-only user creation.
|
||||||
|
- [ ] **Impersonate user** — admin support tool, audit-logged.
|
||||||
|
- [ ] **GitHub App manifest flow** — `POST /git/github-app/manifest`
|
||||||
|
returns manifest + redirect; instance self-provisions its App
|
||||||
|
(dflow pattern — removes the env-setup barrier).
|
||||||
|
- [ ] **fork-sync trigger** — accept repo-sync events on webhook
|
||||||
|
receiver.
|
||||||
|
- [ ] **Dynamic filter framework** — port dflow's `filter.utils`
|
||||||
|
pattern (typed filter configs → URL state → client filtering) for
|
||||||
|
audit logs, deployments, notifications tables.
|
||||||
|
- [ ] **Notification producers round-out** — backups, agent offline,
|
||||||
|
upgrade available, security findings.
|
||||||
|
- [ ] **Custom roles/RBAC** — defer until demanded; PAT scopes designed
|
||||||
|
forward-compatible now.
|
||||||
|
|
||||||
|
## 9. Phase H — Migration & ecosystem
|
||||||
|
|
||||||
|
- [ ] **Railway migrator** — `containr migrate railway --token --project
|
||||||
|
--dry-run`: Railway GraphQL → services/vars/domains → recreate via
|
||||||
|
PAT. Landing-page pitch: "off Railway in one command."
|
||||||
|
- [ ] **dflow importer** — `containr migrate dflow` via Payload REST
|
||||||
|
export or Mongo dump: servers→nodes, projects, services(+vars/
|
||||||
|
domains/volumes), databases, templates. Onboards dflow refugees.
|
||||||
|
- [ ] **`containr import compose`** — Phase-E parser straight to a
|
||||||
|
project (no template intermediate).
|
||||||
|
- [ ] **Template registry** — optional `CONTAINR_TEMPLATE_REGISTRY_URL`
|
||||||
|
fetch/publish; bundled catalog works offline (dflow's self-contained
|
||||||
|
principle — nothing phones home).
|
||||||
|
|
||||||
|
## 10. Carried-over debt (ROADMAP.md items still open)
|
||||||
|
|
||||||
|
- [ ] **Gateway traffic path** — mount `/g/:slug/*` → key → rate-limit →
|
||||||
|
`gateway/proxy.go` → metrics. Management API exists; proxy unwired.
|
||||||
|
- [ ] **Preview environments runtime** — real build+deploy+subdomain+TTL
|
||||||
|
(bookkeeping only now). Pairs with clone + multi-domain.
|
||||||
|
- [ ] **Environments** — env switcher, per-env vars/domains, promote.
|
||||||
|
- [ ] **sqlc port** — ~140 raw `database/sql` sites → `sqlc/queries/`.
|
||||||
|
- [ ] **Tests** — canvas/wizard frontend coverage, deployment/template/
|
||||||
|
webhook table tests, Playwright e2e golden path.
|
||||||
|
- [ ] **First-run wizard** — admin → GitHub App (manifest flow from
|
||||||
|
Phase G makes this self-serve) → Tunnel → done.
|
||||||
|
- [ ] **Self-upgrade loop verification**, docs freshness, v1.0.0 release.
|
||||||
|
|
||||||
|
## 11. Deliberately not imported from dflow
|
||||||
|
|
||||||
|
- Dokku-over-SSH runtime — our Docker API + agent model is strictly
|
||||||
|
better.
|
||||||
|
- Per-server-named BullMQ queues — our queue stays a single ordered
|
||||||
|
table.
|
||||||
|
- Payload/Mongo/Next.js stack, multi-tenant plugin machinery.
|
||||||
|
- Ansible playbook runner — arbitrary code-on-node is a security
|
||||||
|
surface; SSH bootstrap + agent commands cover the real needs.
|
||||||
|
Revisit only with a concrete demand.
|
||||||
|
- `isAdmin`-only collection access — our owner/admin/public model is
|
||||||
|
richer already.
|
||||||
|
- Netdata install flow — our agent telemetry + optional Beszel covers
|
||||||
|
monitoring; don't ship a third dashboard stack.
|
||||||
|
|
||||||
|
## 12. Recommended order
|
||||||
|
|
||||||
|
```
|
||||||
|
A (agent surface) ──► B (deploy pipeline) ──► C/D (service+data depth)
|
||||||
|
│ │
|
||||||
|
▼ ▼
|
||||||
|
CLI/MCP dogfood every feature E (templates v2)
|
||||||
|
│
|
||||||
|
F (nodes/infra) ──► H (migrators)
|
||||||
|
│
|
||||||
|
G (polish) + debt
|
||||||
|
```
|
||||||
|
|
||||||
|
Why this order: PATs+CLI+MCP first = every later feature ships
|
||||||
|
user-and-agent-visible at once. The queue (B) is prerequisite for
|
||||||
|
the ops surface and correct concurrency. Templates v2 needs volumes,
|
||||||
|
multi-domain, clone. Migrators last — they're launch marketing, not
|
||||||
|
foundation.
|
||||||
|
|
||||||
|
## 13. Design rules
|
||||||
|
|
||||||
|
- **API is the contract.** UI, CLI, MCP are thin clients over
|
||||||
|
`openapi.yaml`. A feature isn't done until all three reach it.
|
||||||
|
- **Everything scriptable.** JSON in/out, `--json`/`--yes`, uniform
|
||||||
|
pagination, name-or-id addressing.
|
||||||
|
- **Same powers, same position.** Nothing user-facing that isn't
|
||||||
|
API-facing; agent-visible state (tokens, jobs) visible to users too.
|
||||||
|
- **dflow is a donor, not a dependency.** Port semantics, not code.
|
||||||
|
- **Containr branding is the default**; white-label is instance config.
|
||||||
|
- **Self-hosted first** — no required external service, no phone-home.
|
||||||
@@ -23,6 +23,7 @@ import (
|
|||||||
|
|
||||||
dockercontainer "github.com/docker/docker/api/types/container"
|
dockercontainer "github.com/docker/docker/api/types/container"
|
||||||
"github.com/docker/docker/api/types/mount"
|
"github.com/docker/docker/api/types/mount"
|
||||||
|
"github.com/docker/docker/api/types/network"
|
||||||
"github.com/docker/docker/api/types/registry"
|
"github.com/docker/docker/api/types/registry"
|
||||||
"github.com/docker/go-connections/nat"
|
"github.com/docker/go-connections/nat"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -196,7 +197,7 @@ func (h *DatabaseHandler) GetDatabases(c *gin.Context) {
|
|||||||
db.Backups = DatabaseBackupConfig{Backups: []DatabaseBackup{}}
|
db.Backups = DatabaseBackupConfig{Backups: []DatabaseBackup{}}
|
||||||
}
|
}
|
||||||
db.Settings = h.generateMockSettings()
|
db.Settings = h.generateMockSettings()
|
||||||
db.ConnectionURL = h.resolveConnectionURL(db)
|
db.ConnectionURL = rewriteLoopbackURL(h.resolveConnectionURL(db), requestHostname(c))
|
||||||
} else {
|
} else {
|
||||||
db.Backups = DatabaseBackupConfig{Backups: []DatabaseBackup{}}
|
db.Backups = DatabaseBackupConfig{Backups: []DatabaseBackup{}}
|
||||||
db.ConnectionURL = ""
|
db.ConnectionURL = ""
|
||||||
@@ -235,7 +236,7 @@ func (h *DatabaseHandler) GetDatabase(c *gin.Context) {
|
|||||||
db.Backups = DatabaseBackupConfig{Backups: []DatabaseBackup{}}
|
db.Backups = DatabaseBackupConfig{Backups: []DatabaseBackup{}}
|
||||||
}
|
}
|
||||||
db.Settings = h.generateMockSettings()
|
db.Settings = h.generateMockSettings()
|
||||||
db.ConnectionURL = h.resolveConnectionURL(db)
|
db.ConnectionURL = rewriteLoopbackURL(h.resolveConnectionURL(db), requestHostname(c))
|
||||||
} else {
|
} else {
|
||||||
db.Backups = DatabaseBackupConfig{Backups: []DatabaseBackup{}}
|
db.Backups = DatabaseBackupConfig{Backups: []DatabaseBackup{}}
|
||||||
db.ConnectionURL = ""
|
db.ConnectionURL = ""
|
||||||
@@ -942,33 +943,47 @@ func (h *DatabaseHandler) generateMockSettings() DatabaseSettings {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resolveConnectionURL returns the stored connection URL for privileged
|
||||||
|
// viewers, or "" when the runtime has not produced one (not provisioned yet).
|
||||||
func (h *DatabaseHandler) resolveConnectionURL(db DatabaseService) string {
|
func (h *DatabaseHandler) resolveConnectionURL(db DatabaseService) string {
|
||||||
if strings.TrimSpace(db.ConnectionURL) != "" {
|
return strings.TrimSpace(db.ConnectionURL)
|
||||||
return db.ConnectionURL
|
|
||||||
}
|
|
||||||
return h.generateConnectionURL(db)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *DatabaseHandler) generateConnectionURL(db DatabaseService) string {
|
// requestHostname returns the host the client used to reach the API, without
|
||||||
safeName := sanitizeDBIdentifier(db.Name, "app")
|
// the port. Empty when it cannot be determined.
|
||||||
switch db.Type {
|
func requestHostname(c *gin.Context) string {
|
||||||
case "postgresql":
|
host := strings.TrimSpace(c.Request.Host)
|
||||||
return fmt.Sprintf("postgresql://user:password@%s.containr.local:5432/%s", safeName, safeName)
|
if host == "" {
|
||||||
case "redis":
|
|
||||||
return fmt.Sprintf("redis://%s.containr.local:6379", safeName)
|
|
||||||
case "dragonfly":
|
|
||||||
return fmt.Sprintf("redis://%s.containr.local:6379", safeName)
|
|
||||||
case "mysql":
|
|
||||||
return fmt.Sprintf("mysql://user:password@%s.containr.local:3306/%s", safeName, safeName)
|
|
||||||
case "mariadb":
|
|
||||||
return fmt.Sprintf("mysql://user:password@%s.containr.local:3306/%s", safeName, safeName)
|
|
||||||
case "mongodb":
|
|
||||||
return fmt.Sprintf("mongodb://user:password@%s.containr.local:27017/%s", safeName, safeName)
|
|
||||||
case "clickhouse":
|
|
||||||
return fmt.Sprintf("http://%s.containr.local:8123", safeName)
|
|
||||||
default:
|
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
if h, _, err := net.SplitHostPort(host); err == nil {
|
||||||
|
return strings.Trim(h, "[]")
|
||||||
|
}
|
||||||
|
return strings.Trim(host, "[]")
|
||||||
|
}
|
||||||
|
|
||||||
|
// rewriteLoopbackURL swaps loopback/unspecified hosts in rawURL for the host
|
||||||
|
// the caller actually used, so URLs handed to remote browsers are usable.
|
||||||
|
func rewriteLoopbackURL(rawURL, host string) string {
|
||||||
|
if rawURL == "" || host == "" {
|
||||||
|
return rawURL
|
||||||
|
}
|
||||||
|
u, err := url.Parse(rawURL)
|
||||||
|
if err != nil {
|
||||||
|
return rawURL
|
||||||
|
}
|
||||||
|
switch strings.ToLower(u.Hostname()) {
|
||||||
|
case "localhost", "127.0.0.1", "0.0.0.0", "::1", "":
|
||||||
|
default:
|
||||||
|
return rawURL
|
||||||
|
}
|
||||||
|
port := u.Port()
|
||||||
|
if port == "" {
|
||||||
|
u.Host = host
|
||||||
|
} else {
|
||||||
|
u.Host = net.JoinHostPort(host, port)
|
||||||
|
}
|
||||||
|
return u.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *DatabaseHandler) reconcileManagedDatabaseState(ctx context.Context, db DatabaseService) DatabaseService {
|
func (h *DatabaseHandler) reconcileManagedDatabaseState(ctx context.Context, db DatabaseService) DatabaseService {
|
||||||
@@ -1223,13 +1238,13 @@ func (h *DatabaseHandler) provisionDatabaseWithVariables(databaseID, databaseNam
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
if h.dockerClient == nil {
|
if h.dockerClient == nil {
|
||||||
fallbackURL := h.generateConnectionURL(DatabaseService{Name: databaseName, Type: dbType})
|
_ = h.setDatabaseStatusAndConnection(databaseID, "running", sql.NullString{})
|
||||||
_ = h.setDatabaseStatusAndConnection(databaseID, "running", sql.NullString{String: fallbackURL, Valid: fallbackURL != ""})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
connectionURL, err := h.provisionDatabaseRuntime(ctx, databaseID, databaseName, dbType, runtimeVariables)
|
connectionURL, err := h.provisionDatabaseRuntime(ctx, databaseID, databaseName, dbType, runtimeVariables)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Printf("containr: managed database %s (%s) provisioning failed: %v", databaseID, dbType, err)
|
||||||
_ = h.setDatabaseStatusAndConnection(databaseID, "error", sql.NullString{})
|
_ = h.setDatabaseStatusAndConnection(databaseID, "error", sql.NullString{})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -1337,7 +1352,7 @@ func (h *DatabaseHandler) provisionDatabaseRuntime(ctx context.Context, database
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if err := waitForRuntimePortReadiness(ctx, hostPort); err != nil {
|
if err := h.waitForDatabaseReadiness(ctx, containerID, hostPort, plan.Port.Port()); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1371,12 +1386,24 @@ func (h *DatabaseHandler) resolvePublishedHostPort(ctx context.Context, containe
|
|||||||
return "", fmt.Errorf("published host port not available")
|
return "", fmt.Errorf("published host port not available")
|
||||||
}
|
}
|
||||||
|
|
||||||
func waitForRuntimePortReadiness(ctx context.Context, hostPort string) error {
|
// waitForDatabaseReadiness probes the database's TCP port until it accepts a
|
||||||
addr := net.JoinHostPort("127.0.0.1", strings.TrimSpace(hostPort))
|
// connection. The published port lives on host loopback, which a containerized
|
||||||
deadline := time.Now().Add(30 * time.Second)
|
// backend cannot reach; in that case the database is additionally attached to
|
||||||
|
// the backend's own network and probed by container IP.
|
||||||
|
func (h *DatabaseHandler) waitForDatabaseReadiness(ctx context.Context, containerID, hostPort, containerPort string) error {
|
||||||
|
probeAddr := net.JoinHostPort("127.0.0.1", strings.TrimSpace(hostPort))
|
||||||
|
if backendNet := h.dockerClient.OwnNetworkName(ctx); backendNet != "" {
|
||||||
|
if err := h.dockerClient.ConnectNetwork(ctx, backendNet, containerID, network.EndpointSettings{}); err != nil {
|
||||||
|
log.Printf("containr: attach database %s to %s failed: %v", containerID, backendNet, err)
|
||||||
|
}
|
||||||
|
if ip := h.containerIPOnNetwork(ctx, containerID, backendNet); ip != "" {
|
||||||
|
probeAddr = net.JoinHostPort(ip, containerPort)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deadline := time.Now().Add(30 * time.Second)
|
||||||
for time.Now().Before(deadline) {
|
for time.Now().Before(deadline) {
|
||||||
conn, err := net.DialTimeout("tcp", addr, 1500*time.Millisecond)
|
conn, err := net.DialTimeout("tcp", probeAddr, 1500*time.Millisecond)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
_ = conn.Close()
|
_ = conn.Close()
|
||||||
return nil
|
return nil
|
||||||
@@ -1389,7 +1416,18 @@ func waitForRuntimePortReadiness(ctx context.Context, hostPort string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return fmt.Errorf("database runtime did not become reachable on %s", addr)
|
return fmt.Errorf("database runtime did not become reachable on %s", probeAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *DatabaseHandler) containerIPOnNetwork(ctx context.Context, containerID, networkName string) string {
|
||||||
|
inspect, err := h.dockerClient.GetContainer(ctx, containerID)
|
||||||
|
if err != nil || inspect.NetworkSettings == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if ep, ok := inspect.NetworkSettings.Networks[networkName]; ok && ep != nil {
|
||||||
|
return strings.TrimSpace(ep.IPAddress)
|
||||||
|
}
|
||||||
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *DatabaseHandler) ensureImage(ctx context.Context, imageRef string) error {
|
func (h *DatabaseHandler) ensureImage(ctx context.Context, imageRef string) error {
|
||||||
|
|||||||
@@ -51,15 +51,16 @@ func TestDatabaseConnectionURLAndDefaultVersion(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
url := handler.generateConnectionURL(DatabaseService{
|
plan, err := buildDatabaseRuntimePlan(tc.dbType, "example", nil)
|
||||||
Type: tc.dbType,
|
if err != nil {
|
||||||
Name: "example",
|
t.Fatalf("buildDatabaseRuntimePlan(%q) failed: %v", tc.dbType, err)
|
||||||
})
|
|
||||||
if url == "" {
|
|
||||||
t.Fatalf("generateConnectionURL returned empty for type %q", tc.dbType)
|
|
||||||
}
|
}
|
||||||
|
url := plan.ConnectionURL("15432")
|
||||||
if len(tc.urlContains) > 0 && !strings.HasPrefix(url, tc.urlContains) {
|
if len(tc.urlContains) > 0 && !strings.HasPrefix(url, tc.urlContains) {
|
||||||
t.Fatalf("generateConnectionURL(%q) = %q, expected prefix %q", tc.dbType, url, tc.urlContains)
|
t.Fatalf("ConnectionURL(%q) = %q, expected prefix %q", tc.dbType, url, tc.urlContains)
|
||||||
|
}
|
||||||
|
if !strings.Contains(url, ":15432") {
|
||||||
|
t.Fatalf("ConnectionURL(%q) = %q, expected published port", tc.dbType, url)
|
||||||
}
|
}
|
||||||
|
|
||||||
gotVersion := handler.getDefaultVersion(tc.dbType)
|
gotVersion := handler.getDefaultVersion(tc.dbType)
|
||||||
@@ -69,6 +70,17 @@ func TestDatabaseConnectionURLAndDefaultVersion(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestResolveConnectionURLNeverFabricates(t *testing.T) {
|
||||||
|
handler := &DatabaseHandler{}
|
||||||
|
|
||||||
|
if got := handler.resolveConnectionURL(DatabaseService{Type: "postgresql", Name: "example"}); got != "" {
|
||||||
|
t.Fatalf("resolveConnectionURL with no stored URL = %q, want empty", got)
|
||||||
|
}
|
||||||
|
if got := handler.resolveConnectionURL(DatabaseService{ConnectionURL: "postgresql://u:p@localhost:15432/db"}); got != "postgresql://u:p@localhost:15432/db" {
|
||||||
|
t.Fatalf("resolveConnectionURL = %q, want stored URL", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestBuildDatabaseRuntimePlanSupportsAllTypes(t *testing.T) {
|
func TestBuildDatabaseRuntimePlanSupportsAllTypes(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
dbType string
|
dbType string
|
||||||
@@ -199,3 +211,23 @@ func TestHumanReadableBytes(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRewriteLoopbackURL(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name, raw, host, want string
|
||||||
|
}{
|
||||||
|
{"service url", "http://localhost:35981", "10.0.0.182", "http://10.0.0.182:35981"},
|
||||||
|
{"db url keeps creds", "postgresql://u:p@localhost:35432/db?sslmode=disable", "10.0.0.182", "postgresql://u:[email protected]:35432/db?sslmode=disable"},
|
||||||
|
{"ipv4 loopback", "redis://:[email protected]:36379/0", "host.lan", "redis://:[email protected]:36379/0"},
|
||||||
|
{"unspecified", "http://0.0.0.0:9000/x", "10.0.0.182", "http://10.0.0.182:9000/x"},
|
||||||
|
{"external host untouched", "https://example.com:443/x", "10.0.0.182", "https://example.com:443/x"},
|
||||||
|
{"empty raw", "", "10.0.0.182", ""},
|
||||||
|
{"empty host", "http://localhost:35981", "", "http://localhost:35981"},
|
||||||
|
{"no port", "http://localhost/path", "10.0.0.182", "http://10.0.0.182/path"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
if got := rewriteLoopbackURL(tt.raw, tt.host); got != tt.want {
|
||||||
|
t.Errorf("%s: rewriteLoopbackURL(%q,%q) = %q, want %q", tt.name, tt.raw, tt.host, got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -356,6 +356,12 @@ func runDeploymentAndSyncWithImage(
|
|||||||
replicas = 1
|
replicas = 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var publishedPort int32
|
||||||
|
// Best effort: reuse the host port from the last live deployment so public
|
||||||
|
// URLs survive redeploys. Column exists post-migration; older DBs get
|
||||||
|
// ephemeral ports.
|
||||||
|
_ = db.QueryRow(`SELECT published_port FROM services WHERE id = $1`, service.ID).Scan(&publishedPort)
|
||||||
|
|
||||||
deployReq := &deployment.DeploymentRequest{
|
deployReq := &deployment.DeploymentRequest{
|
||||||
ProjectID: service.ProjectID.String(),
|
ProjectID: service.ProjectID.String(),
|
||||||
ServiceID: service.ID.String(),
|
ServiceID: service.ID.String(),
|
||||||
@@ -367,6 +373,7 @@ func runDeploymentAndSyncWithImage(
|
|||||||
Environment: env,
|
Environment: env,
|
||||||
Replicas: replicas,
|
Replicas: replicas,
|
||||||
PublicPort: int32(service.Port),
|
PublicPort: int32(service.Port),
|
||||||
|
PublishedPort: publishedPort,
|
||||||
Domain: service.Domain,
|
Domain: service.Domain,
|
||||||
HealthPath: service.HealthCheckPath,
|
HealthPath: service.HealthCheckPath,
|
||||||
RestartPolicy: service.RestartPolicy,
|
RestartPolicy: service.RestartPolicy,
|
||||||
|
|||||||
@@ -57,6 +57,33 @@ func SetupRoutes(router *gin.Engine, db *database.DB, redis *database.Redis, cfg
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
haManager := ha.NewHighAvailabilityManager(scheduler, metricsCollector)
|
haManager := ha.NewHighAvailabilityManager(scheduler, metricsCollector)
|
||||||
|
if db != nil && db.DB != nil {
|
||||||
|
haManager.WithPersistence(db.DB)
|
||||||
|
if err := haManager.LoadHealthChecks(context.Background()); err != nil {
|
||||||
|
log.Printf("Failed to restore health checks: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if dockerClient != nil && db != nil {
|
||||||
|
// Service-bound checks probe the service DNS name on the project
|
||||||
|
// network — the backend container joins it on demand. The old
|
||||||
|
// 127.0.0.1 fallback stays for node-bound checks.
|
||||||
|
docker := dockerClient
|
||||||
|
haManager.WithServiceResolver(func(ctx context.Context, serviceID string) (string, int, error) {
|
||||||
|
var name, projectID string
|
||||||
|
var port int
|
||||||
|
err := db.QueryRowContext(ctx,
|
||||||
|
`SELECT name, project_id::text, COALESCE(port, 0) FROM services WHERE id = $1`,
|
||||||
|
serviceID,
|
||||||
|
).Scan(&name, &projectID, &port)
|
||||||
|
if err != nil {
|
||||||
|
return "", 0, err
|
||||||
|
}
|
||||||
|
if err := docker.ConnectSelfToNetwork(ctx, deployment.ProjectNetworkName(projectID)); err != nil {
|
||||||
|
return "", 0, err
|
||||||
|
}
|
||||||
|
return name, port, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
haAPIManager := NewHAManager(haManager)
|
haAPIManager := NewHAManager(haManager)
|
||||||
|
|
||||||
// Initialize scaling handler
|
// Initialize scaling handler
|
||||||
@@ -233,6 +260,11 @@ func SetupRoutes(router *gin.Engine, db *database.DB, redis *database.Redis, cfg
|
|||||||
authed.GET("/user/profile", handleGetProfile)
|
authed.GET("/user/profile", handleGetProfile)
|
||||||
authed.PUT("/user/profile", handleUpdateProfile)
|
authed.PUT("/user/profile", handleUpdateProfile)
|
||||||
|
|
||||||
|
// Personal access tokens for CLI/MCP/agent auth.
|
||||||
|
authed.GET("/user/tokens", handleListUserTokens)
|
||||||
|
authed.POST("/user/tokens", handleCreateUserToken)
|
||||||
|
authed.DELETE("/user/tokens/:id", handleDeleteUserToken)
|
||||||
|
|
||||||
authed.GET("/notifications", handleListNotifications)
|
authed.GET("/notifications", handleListNotifications)
|
||||||
authed.POST("/notifications/:id/read", handleMarkNotificationRead)
|
authed.POST("/notifications/:id/read", handleMarkNotificationRead)
|
||||||
authed.POST("/notifications/read-all", handleMarkAllNotificationsRead)
|
authed.POST("/notifications/read-all", handleMarkAllNotificationsRead)
|
||||||
|
|||||||
@@ -36,6 +36,10 @@ func serviceRuntimeSpec(db *database.DB, service Service) (deployment.RuntimeSpe
|
|||||||
HealthPath: service.HealthCheckPath,
|
HealthPath: service.HealthCheckPath,
|
||||||
RestartPolicy: service.RestartPolicy,
|
RestartPolicy: service.RestartPolicy,
|
||||||
}
|
}
|
||||||
|
// Best effort: reuse the host port from the last live deployment so the
|
||||||
|
// public URL survives restarts. Column exists post-migration; older DBs
|
||||||
|
// silently get ephemeral ports.
|
||||||
|
_ = db.QueryRow(`SELECT published_port FROM services WHERE id = $1`, service.ID).Scan(&spec.PublishedPort)
|
||||||
if cmd := strings.TrimSpace(service.Command); cmd != "" {
|
if cmd := strings.TrimSpace(service.Command); cmd != "" {
|
||||||
spec.Command = strings.Fields(cmd)
|
spec.Command = strings.Fields(cmd)
|
||||||
}
|
}
|
||||||
@@ -283,6 +287,13 @@ func handleGetServiceRuntime(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
engine.ProbeServiceHealth(c.Request.Context(), state, service.ProjectID.String(), service.Name, service.Port, service.HealthCheckPath)
|
||||||
|
persistPublishedPort(db, service.ID, state.Ports)
|
||||||
|
if host := requestHostname(c); host != "" {
|
||||||
|
for i, u := range state.URLs {
|
||||||
|
state.URLs[i] = rewriteLoopbackURL(u, host)
|
||||||
|
}
|
||||||
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{"runtime": state})
|
c.JSON(http.StatusOK, gin.H{"runtime": state})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,6 +313,7 @@ func reconcileNow(c *gin.Context, engine *deployment.DeploymentEngine, db *datab
|
|||||||
status := "stopped"
|
status := "stopped"
|
||||||
if state != nil {
|
if state != nil {
|
||||||
status = state.Status
|
status = state.Status
|
||||||
|
persistPublishedPort(db, service.ID, state.Ports)
|
||||||
}
|
}
|
||||||
_, _ = db.Exec(`UPDATE services SET status = $1, updated_at = $2 WHERE id = $3`, status, time.Now(), service.ID)
|
_, _ = db.Exec(`UPDATE services SET status = $1, updated_at = $2 WHERE id = $3`, status, time.Now(), service.ID)
|
||||||
c.JSON(http.StatusOK, gin.H{"runtime": state})
|
c.JSON(http.StatusOK, gin.H{"runtime": state})
|
||||||
@@ -397,6 +409,18 @@ func handleServiceRedeploy(c *gin.Context) {
|
|||||||
reconcileNow(c, engine, db, service)
|
reconcileNow(c, engine, db, service)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// persistPublishedPort records the host port Docker actually bound so later
|
||||||
|
// redeploys can reuse it. Idempotent — only writes when the value changed.
|
||||||
|
func persistPublishedPort(db *database.DB, serviceID uuid.UUID, ports []uint16) {
|
||||||
|
if len(ports) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = db.Exec(
|
||||||
|
`UPDATE services SET published_port = $1 WHERE id = $2 AND published_port <> $1`,
|
||||||
|
int(ports[0]), serviceID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// liveServiceStatus reconciles the stored status with real container state.
|
// liveServiceStatus reconciles the stored status with real container state.
|
||||||
// No-op when Docker is unavailable — the stored status is returned as-is.
|
// No-op when Docker is unavailable — the stored status is returned as-is.
|
||||||
func liveServiceStatus(c *gin.Context, db *database.DB, service *Service) {
|
func liveServiceStatus(c *gin.Context, db *database.DB, service *Service) {
|
||||||
@@ -415,10 +439,11 @@ func liveServiceStatus(c *gin.Context, db *database.DB, service *Service) {
|
|||||||
service.Status = state.Status
|
service.Status = state.Status
|
||||||
_, _ = db.Exec(`UPDATE services SET status = $1, updated_at = $2 WHERE id = $3`, state.Status, time.Now(), service.ID)
|
_, _ = db.Exec(`UPDATE services SET status = $1, updated_at = $2 WHERE id = $3`, state.Status, time.Now(), service.ID)
|
||||||
}
|
}
|
||||||
|
persistPublishedPort(db, service.ID, state.Ports)
|
||||||
if service.Domain != "" {
|
if service.Domain != "" {
|
||||||
service.PublicURL = "https://" + service.Domain
|
service.PublicURL = "https://" + service.Domain
|
||||||
} else if len(state.URLs) > 0 {
|
} else if len(state.URLs) > 0 {
|
||||||
service.PublicURL = state.URLs[0]
|
service.PublicURL = rewriteLoopbackURL(state.URLs[0], requestHostname(c))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -475,9 +500,13 @@ func runtimeScaleService(c *gin.Context, serviceID string, replicas int) error {
|
|||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if _, err := engine.ReconcileService(ctx, spec); err != nil {
|
state, err := engine.ReconcileService(ctx, spec)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if state != nil {
|
||||||
|
persistPublishedPort(db, service.ID, state.Ports)
|
||||||
|
}
|
||||||
_, _ = db.Exec(`UPDATE services SET replicas = $1, updated_at = $2 WHERE id = $3`, replicas, time.Now(), service.ID)
|
_, _ = db.Exec(`UPDATE services SET replicas = $1, updated_at = $2 WHERE id = $3`, replicas, time.Now(), service.ID)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -520,7 +520,9 @@ func handleUpdateService(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
_, _ = engine.ReconcileService(ctx, spec)
|
if state, err := engine.ReconcileService(ctx, spec); err == nil && state != nil {
|
||||||
|
persistPublishedPort(db.(*database.DB), serviceCopy.ID, state.Ports)
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,9 @@ type hostMonitoringResponse struct {
|
|||||||
UptimeSeconds int64 `json:"uptime_seconds"`
|
UptimeSeconds int64 `json:"uptime_seconds"`
|
||||||
DockerAvailable bool `json:"docker_available"`
|
DockerAvailable bool `json:"docker_available"`
|
||||||
Docker map[string]any `json:"docker,omitempty"`
|
Docker map[string]any `json:"docker,omitempty"`
|
||||||
|
// Scope names what the telemetry actually measures: the physical host for
|
||||||
|
// native dockerd, or the Docker Desktop VM when the daemon runs in one.
|
||||||
|
Scope string `json:"scope"`
|
||||||
CollectedAt string `json:"collected_at"`
|
CollectedAt string `json:"collected_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,6 +162,7 @@ func handleGetHostMonitoring(c *gin.Context) {
|
|||||||
Storage: storage,
|
Storage: storage,
|
||||||
Load: load,
|
Load: load,
|
||||||
UptimeSeconds: uptime,
|
UptimeSeconds: uptime,
|
||||||
|
Scope: "host",
|
||||||
CollectedAt: time.Now().UTC().Format(time.RFC3339),
|
CollectedAt: time.Now().UTC().Format(time.RFC3339),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,6 +177,10 @@ func handleGetHostMonitoring(c *gin.Context) {
|
|||||||
"images": info.Images,
|
"images": info.Images,
|
||||||
"driver": info.Driver,
|
"driver": info.Driver,
|
||||||
"server": info.ServerVersion,
|
"server": info.ServerVersion,
|
||||||
|
"os": info.OperatingSystem,
|
||||||
|
}
|
||||||
|
if strings.Contains(strings.ToLower(info.OperatingSystem), "docker desktop") {
|
||||||
|
response.Scope = "docker-desktop-vm"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -336,6 +336,16 @@ func handleCreateFromTemplate(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// sqlc's schema predates the runtime columns; port and healthcheck_path are
|
||||||
|
// written via raw SQL like every other service mutation path.
|
||||||
|
if _, err = tx.ExecContext(ctx,
|
||||||
|
`UPDATE services SET port = $1, healthcheck_path = $2 WHERE id = $3`,
|
||||||
|
config.Port, strings.TrimSpace(config.HealthCheck), serviceID,
|
||||||
|
); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create service from template"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
for key, value := range envVars {
|
for key, value := range envVars {
|
||||||
if strings.TrimSpace(key) == "" {
|
if strings.TrimSpace(key) == "" {
|
||||||
continue
|
continue
|
||||||
@@ -731,7 +741,7 @@ func SeedTemplates() []ServiceTemplate {
|
|||||||
Name: "Background Worker",
|
Name: "Background Worker",
|
||||||
Description: "Background job processing service",
|
Description: "Background job processing service",
|
||||||
Category: "worker",
|
Category: "worker",
|
||||||
Logo: "https://cdn.simpleicons.org/terminal",
|
Logo: "https://cdn.simpleicons.org/gnubash",
|
||||||
Config: `{"type":"worker","runtime":"node","build_command":"npm install","start_command":"npm run worker"}`,
|
Config: `{"type":"worker","runtime":"node","build_command":"npm install","start_command":"npm run worker"}`,
|
||||||
Variables: `[{"key":"WORKER_CONCURRENCY","label":"Concurrency","default":"4","required":false,"secret":false}]`,
|
Variables: `[{"key":"WORKER_CONCURRENCY","label":"Concurrency","default":"4","required":false,"secret":false}]`,
|
||||||
IsOfficial: true,
|
IsOfficial: true,
|
||||||
@@ -741,7 +751,7 @@ func SeedTemplates() []ServiceTemplate {
|
|||||||
Name: "Cron Job",
|
Name: "Cron Job",
|
||||||
Description: "Scheduled task runner",
|
Description: "Scheduled task runner",
|
||||||
Category: "cron",
|
Category: "cron",
|
||||||
Logo: "https://cdn.simpleicons.org/clock",
|
Logo: "https://cdn.simpleicons.org/clockify",
|
||||||
Config: `{"type":"cron","runtime":"node","build_command":"npm install","start_command":"npm run cron"}`,
|
Config: `{"type":"cron","runtime":"node","build_command":"npm install","start_command":"npm run cron"}`,
|
||||||
Variables: `[{"key":"CRON_SCHEDULE","label":"Schedule","default":"0 * * * *","required":true,"secret":false}]`,
|
Variables: `[{"key":"CRON_SCHEDULE","label":"Schedule","default":"0 * * * *","required":true,"secret":false}]`,
|
||||||
IsOfficial: true,
|
IsOfficial: true,
|
||||||
|
|||||||
@@ -0,0 +1,194 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"containr/internal/database"
|
||||||
|
sqlcdb "containr/internal/database/sqlcdb"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Personal access tokens let the CLI, MCP server, and third-party agents
|
||||||
|
// authenticate without a browser session. The raw token (cnp_…) is
|
||||||
|
// returned exactly once at creation; only its sha256 hash persists.
|
||||||
|
|
||||||
|
var userTokenScopes = map[string]bool{"read": true, "write": true, "admin": true}
|
||||||
|
|
||||||
|
func generateUserToken() (token string, prefix string, hash string, err error) {
|
||||||
|
buf := make([]byte, 24)
|
||||||
|
if _, err = rand.Read(buf); err != nil {
|
||||||
|
return "", "", "", err
|
||||||
|
}
|
||||||
|
token = "cnp_" + hex.EncodeToString(buf)
|
||||||
|
prefix = token[:12] // cnp_ + 8 hex chars, enough to identify in a list
|
||||||
|
sum := sha256.Sum256([]byte(token))
|
||||||
|
return token, prefix, hex.EncodeToString(sum[:]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func userTokenJSON(t sqlcdb.UserToken) gin.H {
|
||||||
|
row := gin.H{
|
||||||
|
"id": t.ID.String(),
|
||||||
|
"name": t.Name,
|
||||||
|
"key_prefix": t.KeyPrefix,
|
||||||
|
"scope": t.Scope,
|
||||||
|
}
|
||||||
|
if t.CreatedAt.Valid {
|
||||||
|
row["created_at"] = t.CreatedAt.Time
|
||||||
|
}
|
||||||
|
if t.LastUsedAt.Valid {
|
||||||
|
row["last_used_at"] = t.LastUsedAt.Time
|
||||||
|
}
|
||||||
|
if t.ExpiresAt.Valid {
|
||||||
|
row["expires_at"] = t.ExpiresAt.Time
|
||||||
|
}
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleCreateUserToken(c *gin.Context) {
|
||||||
|
userID, ok := requireAuthenticatedUserID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db := c.MustGet("db").(*database.DB)
|
||||||
|
queries := sqlcdb.New(db.DB)
|
||||||
|
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
ExpiresInDays int `json:"expires_in_days"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Name = strings.TrimSpace(req.Name)
|
||||||
|
if req.Name == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.Scope == "" {
|
||||||
|
req.Scope = "write"
|
||||||
|
}
|
||||||
|
if !userTokenScopes[req.Scope] {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "scope must be one of: read, write, admin"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// A token can never outrank its owner: non-admin users cannot mint
|
||||||
|
// admin-scope tokens even for themselves.
|
||||||
|
if req.Scope == "admin" && !c.GetBool("is_admin") {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "admin scope requires a platform admin account"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.ExpiresInDays < 0 || req.ExpiresInDays > 3650 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "expires_in_days must be between 0 (never) and 3650"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
token, prefix, hash, err := generateUserToken()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ownerUUID, err := uuid.Parse(userID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid user context"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
expiresAt := sql.NullTime{}
|
||||||
|
if req.ExpiresInDays > 0 {
|
||||||
|
expiresAt = sql.NullTime{Time: time.Now().Add(time.Duration(req.ExpiresInDays) * 24 * time.Hour), Valid: true}
|
||||||
|
}
|
||||||
|
|
||||||
|
row, err := queries.CreateUserToken(c.Request.Context(), sqlcdb.CreateUserTokenParams{
|
||||||
|
UserID: ownerUUID,
|
||||||
|
Name: req.Name,
|
||||||
|
KeyPrefix: prefix,
|
||||||
|
TokenHash: hash,
|
||||||
|
Scope: req.Scope,
|
||||||
|
ExpiresAt: expiresAt,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to store token"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
LogAudit(userID, "user_token", row.ID.String(), "create", map[string]interface{}{"name": req.Name, "scope": req.Scope})
|
||||||
|
|
||||||
|
payload := userTokenJSON(row)
|
||||||
|
payload["token"] = token
|
||||||
|
c.JSON(http.StatusCreated, payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleListUserTokens(c *gin.Context) {
|
||||||
|
userID, ok := requireAuthenticatedUserID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db := c.MustGet("db").(*database.DB)
|
||||||
|
queries := sqlcdb.New(db.DB)
|
||||||
|
|
||||||
|
ownerUUID, err := uuid.Parse(userID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid user context"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, err := queries.ListUserTokens(c.Request.Context(), ownerUUID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch tokens"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
out := make([]gin.H, 0, len(rows))
|
||||||
|
for _, t := range rows {
|
||||||
|
out = append(out, userTokenJSON(t))
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"tokens": out})
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleDeleteUserToken(c *gin.Context) {
|
||||||
|
userID, ok := requireAuthenticatedUserID(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db := c.MustGet("db").(*database.DB)
|
||||||
|
queries := sqlcdb.New(db.DB)
|
||||||
|
|
||||||
|
ownerUUID, err := uuid.Parse(userID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid user context"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tokenUUID, err := uuid.Parse(c.Param("id"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid token ID"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
affected, err := queries.RevokeUserToken(c.Request.Context(), sqlcdb.RevokeUserTokenParams{
|
||||||
|
ID: tokenUUID,
|
||||||
|
UserID: ownerUUID,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to revoke token"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if affected == 0 {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Token not found"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
LogAudit(userID, "user_token", tokenUUID.String(), "revoke", nil)
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Token revoked"})
|
||||||
|
}
|
||||||
@@ -195,6 +195,12 @@ type Service struct {
|
|||||||
BuildPath sql.NullString `json:"build_path"`
|
BuildPath sql.NullString `json:"build_path"`
|
||||||
Cpu sql.NullString `json:"cpu"`
|
Cpu sql.NullString `json:"cpu"`
|
||||||
Memory sql.NullString `json:"memory"`
|
Memory sql.NullString `json:"memory"`
|
||||||
|
Replicas int32 `json:"replicas"`
|
||||||
|
Port int32 `json:"port"`
|
||||||
|
Domain string `json:"domain"`
|
||||||
|
HealthcheckPath string `json:"healthcheck_path"`
|
||||||
|
RestartPolicy string `json:"restart_policy"`
|
||||||
|
PublishedPort int32 `json:"published_port"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ServiceTemplate struct {
|
type ServiceTemplate struct {
|
||||||
@@ -211,3 +217,16 @@ type ServiceTemplate struct {
|
|||||||
CreatedAt sql.NullTime `json:"created_at"`
|
CreatedAt sql.NullTime `json:"created_at"`
|
||||||
UpdatedAt sql.NullTime `json:"updated_at"`
|
UpdatedAt sql.NullTime `json:"updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type UserToken struct {
|
||||||
|
ID uuid.UUID `json:"id"`
|
||||||
|
UserID uuid.UUID `json:"user_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
KeyPrefix string `json:"key_prefix"`
|
||||||
|
TokenHash string `json:"token_hash"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
ExpiresAt sql.NullTime `json:"expires_at"`
|
||||||
|
LastUsedAt sql.NullTime `json:"last_used_at"`
|
||||||
|
RevokedAt sql.NullTime `json:"revoked_at"`
|
||||||
|
CreatedAt sql.NullTime `json:"created_at"`
|
||||||
|
}
|
||||||
@@ -26,6 +26,7 @@ type Querier interface {
|
|||||||
CreateProject(ctx context.Context, arg CreateProjectParams) (Project, error)
|
CreateProject(ctx context.Context, arg CreateProjectParams) (Project, error)
|
||||||
CreateServiceFromTemplate(ctx context.Context, arg CreateServiceFromTemplateParams) error
|
CreateServiceFromTemplate(ctx context.Context, arg CreateServiceFromTemplateParams) error
|
||||||
CreateUserTemplate(ctx context.Context, arg CreateUserTemplateParams) error
|
CreateUserTemplate(ctx context.Context, arg CreateUserTemplateParams) error
|
||||||
|
CreateUserToken(ctx context.Context, arg CreateUserTokenParams) (UserToken, error)
|
||||||
DatabaseServiceExistsByIDAndUser(ctx context.Context, arg DatabaseServiceExistsByIDAndUserParams) (bool, error)
|
DatabaseServiceExistsByIDAndUser(ctx context.Context, arg DatabaseServiceExistsByIDAndUserParams) (bool, error)
|
||||||
DeleteAgent(ctx context.Context, id string) error
|
DeleteAgent(ctx context.Context, id string) error
|
||||||
DeleteDatabaseServiceByIDAndUser(ctx context.Context, arg DeleteDatabaseServiceByIDAndUserParams) error
|
DeleteDatabaseServiceByIDAndUser(ctx context.Context, arg DeleteDatabaseServiceByIDAndUserParams) error
|
||||||
@@ -46,6 +47,7 @@ type Querier interface {
|
|||||||
GetProjectOwnerID(ctx context.Context, id uuid.UUID) (uuid.UUID, error)
|
GetProjectOwnerID(ctx context.Context, id uuid.UUID) (uuid.UUID, error)
|
||||||
GetProjectRoleForUser(ctx context.Context, arg GetProjectRoleForUserParams) (string, error)
|
GetProjectRoleForUser(ctx context.Context, arg GetProjectRoleForUserParams) (string, error)
|
||||||
GetServiceTemplateByID(ctx context.Context, id string) (ServiceTemplate, error)
|
GetServiceTemplateByID(ctx context.Context, id string) (ServiceTemplate, error)
|
||||||
|
GetUserTokenByHash(ctx context.Context, tokenHash string) (UserToken, error)
|
||||||
InsertAgentHeartbeat(ctx context.Context, arg InsertAgentHeartbeatParams) error
|
InsertAgentHeartbeat(ctx context.Context, arg InsertAgentHeartbeatParams) error
|
||||||
InsertProjectEnvironment(ctx context.Context, arg InsertProjectEnvironmentParams) error
|
InsertProjectEnvironment(ctx context.Context, arg InsertProjectEnvironmentParams) error
|
||||||
ListAgentAuthTokens(ctx context.Context) ([]AgentAuthToken, error)
|
ListAgentAuthTokens(ctx context.Context) ([]AgentAuthToken, error)
|
||||||
@@ -66,9 +68,11 @@ type Querier interface {
|
|||||||
ListProjectsWithStatsByUser(ctx context.Context, arg ListProjectsWithStatsByUserParams) ([]ListProjectsWithStatsByUserRow, error)
|
ListProjectsWithStatsByUser(ctx context.Context, arg ListProjectsWithStatsByUserParams) ([]ListProjectsWithStatsByUserRow, error)
|
||||||
ListServiceTemplatesByCategoryForUser(ctx context.Context, arg ListServiceTemplatesByCategoryForUserParams) ([]ServiceTemplate, error)
|
ListServiceTemplatesByCategoryForUser(ctx context.Context, arg ListServiceTemplatesByCategoryForUserParams) ([]ServiceTemplate, error)
|
||||||
ListServiceTemplatesForUser(ctx context.Context, ownerID uuid.NullUUID) ([]ServiceTemplate, error)
|
ListServiceTemplatesForUser(ctx context.Context, ownerID uuid.NullUUID) ([]ServiceTemplate, error)
|
||||||
|
ListUserTokens(ctx context.Context, userID uuid.UUID) ([]UserToken, error)
|
||||||
MarkAllNotificationsReadByUser(ctx context.Context, arg MarkAllNotificationsReadByUserParams) error
|
MarkAllNotificationsReadByUser(ctx context.Context, arg MarkAllNotificationsReadByUserParams) error
|
||||||
MarkNotificationReadByIDAndUser(ctx context.Context, arg MarkNotificationReadByIDAndUserParams) error
|
MarkNotificationReadByIDAndUser(ctx context.Context, arg MarkNotificationReadByIDAndUserParams) error
|
||||||
RevokeAgentAuthToken(ctx context.Context, id uuid.UUID) (AgentAuthToken, error)
|
RevokeAgentAuthToken(ctx context.Context, id uuid.UUID) (AgentAuthToken, error)
|
||||||
|
RevokeUserToken(ctx context.Context, arg RevokeUserTokenParams) (int64, error)
|
||||||
SetDatabaseBackupScheduleByIDAndUser(ctx context.Context, arg SetDatabaseBackupScheduleByIDAndUserParams) error
|
SetDatabaseBackupScheduleByIDAndUser(ctx context.Context, arg SetDatabaseBackupScheduleByIDAndUserParams) error
|
||||||
SetDatabaseBackupStatusByID(ctx context.Context, arg SetDatabaseBackupStatusByIDParams) error
|
SetDatabaseBackupStatusByID(ctx context.Context, arg SetDatabaseBackupStatusByIDParams) error
|
||||||
SetDatabaseNextBackupAt(ctx context.Context, arg SetDatabaseNextBackupAtParams) error
|
SetDatabaseNextBackupAt(ctx context.Context, arg SetDatabaseNextBackupAtParams) error
|
||||||
@@ -77,6 +81,7 @@ type Querier interface {
|
|||||||
SetDatabaseServiceStatusByIDAndUser(ctx context.Context, arg SetDatabaseServiceStatusByIDAndUserParams) error
|
SetDatabaseServiceStatusByIDAndUser(ctx context.Context, arg SetDatabaseServiceStatusByIDAndUserParams) error
|
||||||
SetProjectApproved(ctx context.Context, arg SetProjectApprovedParams) (int64, error)
|
SetProjectApproved(ctx context.Context, arg SetProjectApprovedParams) (int64, error)
|
||||||
TouchAgentAuthToken(ctx context.Context, tokenHash string) error
|
TouchAgentAuthToken(ctx context.Context, tokenHash string) error
|
||||||
|
TouchUserToken(ctx context.Context, id uuid.UUID) error
|
||||||
UpdateAgent(ctx context.Context, arg UpdateAgentParams) (NodeAgent, error)
|
UpdateAgent(ctx context.Context, arg UpdateAgentParams) (NodeAgent, error)
|
||||||
UpdateAgentHeartbeat(ctx context.Context, arg UpdateAgentHeartbeatParams) error
|
UpdateAgentHeartbeat(ctx context.Context, arg UpdateAgentHeartbeatParams) error
|
||||||
UpdateContainerStatus(ctx context.Context, arg UpdateContainerStatusParams) error
|
UpdateContainerStatus(ctx context.Context, arg UpdateContainerStatusParams) error
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.31.1
|
||||||
|
// source: user_tokens.sql
|
||||||
|
|
||||||
|
package sqlcdb
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
const createUserToken = `-- name: CreateUserToken :one
|
||||||
|
INSERT INTO user_tokens (user_id, name, key_prefix, token_hash, scope, expires_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6)
|
||||||
|
RETURNING id, user_id, name, key_prefix, token_hash, scope, expires_at, last_used_at, revoked_at, created_at
|
||||||
|
`
|
||||||
|
|
||||||
|
type CreateUserTokenParams struct {
|
||||||
|
UserID uuid.UUID `json:"user_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
KeyPrefix string `json:"key_prefix"`
|
||||||
|
TokenHash string `json:"token_hash"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
ExpiresAt sql.NullTime `json:"expires_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) CreateUserToken(ctx context.Context, arg CreateUserTokenParams) (UserToken, error) {
|
||||||
|
row := q.db.QueryRowContext(ctx, createUserToken,
|
||||||
|
arg.UserID,
|
||||||
|
arg.Name,
|
||||||
|
arg.KeyPrefix,
|
||||||
|
arg.TokenHash,
|
||||||
|
arg.Scope,
|
||||||
|
arg.ExpiresAt,
|
||||||
|
)
|
||||||
|
var i UserToken
|
||||||
|
err := row.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.UserID,
|
||||||
|
&i.Name,
|
||||||
|
&i.KeyPrefix,
|
||||||
|
&i.TokenHash,
|
||||||
|
&i.Scope,
|
||||||
|
&i.ExpiresAt,
|
||||||
|
&i.LastUsedAt,
|
||||||
|
&i.RevokedAt,
|
||||||
|
&i.CreatedAt,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
|
const getUserTokenByHash = `-- name: GetUserTokenByHash :one
|
||||||
|
SELECT id, user_id, name, key_prefix, token_hash, scope, expires_at, last_used_at, revoked_at, created_at FROM user_tokens
|
||||||
|
WHERE token_hash = $1
|
||||||
|
AND revoked_at IS NULL
|
||||||
|
AND (expires_at IS NULL OR expires_at > NOW())
|
||||||
|
LIMIT 1
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) GetUserTokenByHash(ctx context.Context, tokenHash string) (UserToken, error) {
|
||||||
|
row := q.db.QueryRowContext(ctx, getUserTokenByHash, tokenHash)
|
||||||
|
var i UserToken
|
||||||
|
err := row.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.UserID,
|
||||||
|
&i.Name,
|
||||||
|
&i.KeyPrefix,
|
||||||
|
&i.TokenHash,
|
||||||
|
&i.Scope,
|
||||||
|
&i.ExpiresAt,
|
||||||
|
&i.LastUsedAt,
|
||||||
|
&i.RevokedAt,
|
||||||
|
&i.CreatedAt,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
|
const listUserTokens = `-- name: ListUserTokens :many
|
||||||
|
SELECT id, user_id, name, key_prefix, token_hash, scope, expires_at, last_used_at, revoked_at, created_at FROM user_tokens
|
||||||
|
WHERE user_id = $1 AND revoked_at IS NULL
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) ListUserTokens(ctx context.Context, userID uuid.UUID) ([]UserToken, error) {
|
||||||
|
rows, err := q.db.QueryContext(ctx, listUserTokens, userID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
items := []UserToken{}
|
||||||
|
for rows.Next() {
|
||||||
|
var i UserToken
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.UserID,
|
||||||
|
&i.Name,
|
||||||
|
&i.KeyPrefix,
|
||||||
|
&i.TokenHash,
|
||||||
|
&i.Scope,
|
||||||
|
&i.ExpiresAt,
|
||||||
|
&i.LastUsedAt,
|
||||||
|
&i.RevokedAt,
|
||||||
|
&i.CreatedAt,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const revokeUserToken = `-- name: RevokeUserToken :execrows
|
||||||
|
UPDATE user_tokens SET revoked_at = NOW()
|
||||||
|
WHERE id = $1 AND user_id = $2 AND revoked_at IS NULL
|
||||||
|
`
|
||||||
|
|
||||||
|
type RevokeUserTokenParams struct {
|
||||||
|
ID uuid.UUID `json:"id"`
|
||||||
|
UserID uuid.UUID `json:"user_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) RevokeUserToken(ctx context.Context, arg RevokeUserTokenParams) (int64, error) {
|
||||||
|
result, err := q.db.ExecContext(ctx, revokeUserToken, arg.ID, arg.UserID)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return result.RowsAffected()
|
||||||
|
}
|
||||||
|
|
||||||
|
const touchUserToken = `-- name: TouchUserToken :exec
|
||||||
|
UPDATE user_tokens SET last_used_at = NOW()
|
||||||
|
WHERE id = $1 AND revoked_at IS NULL
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) TouchUserToken(ctx context.Context, id uuid.UUID) error {
|
||||||
|
_, err := q.db.ExecContext(ctx, touchUserToken, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -59,6 +59,9 @@ type ServiceConfig struct {
|
|||||||
Domain string `json:"domain,omitempty"`
|
Domain string `json:"domain,omitempty"`
|
||||||
// HealthPath is an HTTP path probed on PublicPort for container health.
|
// HealthPath is an HTTP path probed on PublicPort for container health.
|
||||||
HealthPath string `json:"health_path,omitempty"`
|
HealthPath string `json:"health_path,omitempty"`
|
||||||
|
// PublishedPort is the host port bound by the previous deployment; replica 0
|
||||||
|
// reuses it so public URLs survive restarts. 0 = pick ephemeral.
|
||||||
|
PublishedPort int32 `json:"published_port,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type PortMapping struct {
|
type PortMapping struct {
|
||||||
@@ -315,6 +318,7 @@ func (de *DeploymentEngine) deployService(ctx context.Context, deployment *Deplo
|
|||||||
Env: cfg.Environment,
|
Env: cfg.Environment,
|
||||||
Replicas: cfg.Replicas,
|
Replicas: cfg.Replicas,
|
||||||
Port: cfg.PublicPort,
|
Port: cfg.PublicPort,
|
||||||
|
PublishedPort: cfg.PublishedPort,
|
||||||
Domain: cfg.Domain,
|
Domain: cfg.Domain,
|
||||||
HealthPath: cfg.HealthPath,
|
HealthPath: cfg.HealthPath,
|
||||||
RestartPolicy: cfg.RestartPolicy,
|
RestartPolicy: cfg.RestartPolicy,
|
||||||
|
|||||||
@@ -5,8 +5,11 @@ import (
|
|||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net/http"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -38,6 +41,7 @@ type RuntimeSpec struct {
|
|||||||
Env map[string]string // already resolved
|
Env map[string]string // already resolved
|
||||||
Replicas int
|
Replicas int
|
||||||
Port int32 // container port to expose publicly; 0 = none
|
Port int32 // container port to expose publicly; 0 = none
|
||||||
|
PublishedPort int32 // preferred host port for replica 0; 0 = pick ephemeral
|
||||||
Domain string // public hostname routed via Traefik; empty = none
|
Domain string // public hostname routed via Traefik; empty = none
|
||||||
HealthPath string // http path probed on Port for container healthcheck
|
HealthPath string // http path probed on Port for container healthcheck
|
||||||
RestartPolicy string
|
RestartPolicy string
|
||||||
@@ -58,10 +62,14 @@ type RuntimeState struct {
|
|||||||
Desired int `json:"desired"`
|
Desired int `json:"desired"`
|
||||||
Containers []RuntimeContainer `json:"containers"`
|
Containers []RuntimeContainer `json:"containers"`
|
||||||
URLs []string `json:"urls"`
|
URLs []string `json:"urls"`
|
||||||
|
Ports []uint16 `json:"ports"`
|
||||||
|
Health string `json:"health,omitempty"` // healthy, unhealthy, unreachable
|
||||||
Status string `json:"status"` // running, degraded, stopped
|
Status string `json:"status"` // running, degraded, stopped
|
||||||
}
|
}
|
||||||
|
|
||||||
func projectNetworkName(projectID string) string {
|
// ProjectNetworkName is the deterministic docker network every service in a
|
||||||
|
// project joins — containr-proj-<first 12 hex chars of the project uuid>.
|
||||||
|
func ProjectNetworkName(projectID string) string {
|
||||||
short := strings.ReplaceAll(projectID, "-", "")
|
short := strings.ReplaceAll(projectID, "-", "")
|
||||||
if len(short) > 12 {
|
if len(short) > 12 {
|
||||||
short = short[:12]
|
short = short[:12]
|
||||||
@@ -76,7 +84,7 @@ func serviceNamePrefix(serviceID string) string {
|
|||||||
// EnsureProjectNetwork creates the per-project bridge network if missing.
|
// EnsureProjectNetwork creates the per-project bridge network if missing.
|
||||||
// Containers on it resolve each other by service name (private networking).
|
// Containers on it resolve each other by service name (private networking).
|
||||||
func (de *DeploymentEngine) EnsureProjectNetwork(ctx context.Context, projectID string) (string, error) {
|
func (de *DeploymentEngine) EnsureProjectNetwork(ctx context.Context, projectID string) (string, error) {
|
||||||
name := projectNetworkName(projectID)
|
name := ProjectNetworkName(projectID)
|
||||||
|
|
||||||
networks, err := de.dockerClient.ListNetworks(ctx)
|
networks, err := de.dockerClient.ListNetworks(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -237,31 +245,70 @@ func (de *DeploymentEngine) createReplica(ctx context.Context, spec RuntimeSpec,
|
|||||||
Networks: endpoints,
|
Networks: endpoints,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var wantPort nat.Port
|
||||||
if spec.Port > 0 {
|
if spec.Port > 0 {
|
||||||
port := nat.Port(fmt.Sprintf("%d/tcp", spec.Port))
|
wantPort = nat.Port(fmt.Sprintf("%d/tcp", spec.Port))
|
||||||
cfg.ExposedPorts = nat.PortSet{port: struct{}{}}
|
cfg.ExposedPorts = nat.PortSet{wantPort: struct{}{}}
|
||||||
// Always publish an ephemeral host port for direct access; a configured
|
|
||||||
// domain is additionally routed via Traefik when the edge network exists.
|
|
||||||
cfg.PortBindings = nat.PortMap{port: []nat.PortBinding{{HostIP: "0.0.0.0", HostPort: ""}}}
|
|
||||||
if spec.HealthPath != "" {
|
|
||||||
cfg.Healthcheck = &container.HealthConfig{
|
|
||||||
Test: []string{"CMD-SHELL", fmt.Sprintf("wget -q -O /dev/null http://127.0.0.1:%d%s || exit 1", spec.Port, spec.HealthPath)},
|
|
||||||
Interval: 30 * time.Second,
|
|
||||||
Timeout: 5 * time.Second,
|
|
||||||
Retries: 3,
|
|
||||||
StartPeriod: 10 * time.Second,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// tryBind creates and starts a container publishing wantPort on hostPort
|
||||||
|
// ("" = ephemeral). A requested port is verified after start: Docker
|
||||||
|
// Desktop accepts a conflicting binding at create/start but publishes
|
||||||
|
// nothing, which would leave the service running with no endpoint.
|
||||||
|
tryBind := func(hostPort string) (string, error) {
|
||||||
|
if spec.Port > 0 {
|
||||||
|
cfg.PortBindings = nat.PortMap{wantPort: []nat.PortBinding{{HostIP: "0.0.0.0", HostPort: hostPort}}}
|
||||||
|
}
|
||||||
id, err := de.dockerClient.CreateContainer(ctx, cfg)
|
id, err := de.dockerClient.CreateContainer(ctx, cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if err := de.dockerClient.StartContainer(ctx, id); err != nil {
|
if err := de.dockerClient.StartContainer(ctx, id); err != nil {
|
||||||
|
_ = de.dockerClient.RemoveContainer(ctx, id, true)
|
||||||
return "", fmt.Errorf("start: %w", err)
|
return "", fmt.Errorf("start: %w", err)
|
||||||
}
|
}
|
||||||
|
if hostPort != "" {
|
||||||
|
info, err := de.dockerClient.GetContainer(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
_ = de.dockerClient.RemoveContainer(ctx, id, true)
|
||||||
|
return "", fmt.Errorf("inspect: %w", err)
|
||||||
|
}
|
||||||
|
if info.NetworkSettings == nil || len(info.NetworkSettings.Ports[wantPort]) == 0 {
|
||||||
|
_ = de.dockerClient.RemoveContainer(ctx, id, true)
|
||||||
|
return "", errPortNotBound
|
||||||
|
}
|
||||||
|
}
|
||||||
return id, nil
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
preferred := ""
|
||||||
|
if index == 0 && spec.PublishedPort > 0 {
|
||||||
|
preferred = strconv.Itoa(int(spec.PublishedPort))
|
||||||
|
}
|
||||||
|
id, err := tryBind(preferred)
|
||||||
|
if err != nil && preferred != "" && (isPortConflict(err) || errors.Is(err, errPortNotBound)) {
|
||||||
|
// Stored port got taken since last deploy — fall back to ephemeral; the
|
||||||
|
// new assignment is persisted on the next runtime read.
|
||||||
|
id, err = tryBind("")
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// errPortNotBound marks a container that started but failed to publish the
|
||||||
|
// requested host port (seen on Docker Desktop, which reports success while
|
||||||
|
// vpnkit drops a conflicting binding).
|
||||||
|
var errPortNotBound = errors.New("requested host port not bound")
|
||||||
|
|
||||||
|
// isPortConflict reports whether a container create failed because the
|
||||||
|
// requested host port was already bound.
|
||||||
|
func isPortConflict(err error) bool {
|
||||||
|
msg := strings.ToLower(err.Error())
|
||||||
|
return strings.Contains(msg, "port is already allocated") ||
|
||||||
|
strings.Contains(msg, "address already in use") ||
|
||||||
|
strings.Contains(msg, "cannot assign requested address")
|
||||||
}
|
}
|
||||||
|
|
||||||
// RuntimeState reads live container state for a service.
|
// RuntimeState reads live container state for a service.
|
||||||
@@ -282,6 +329,7 @@ func (de *DeploymentEngine) RuntimeState(ctx context.Context, serviceID string,
|
|||||||
for _, p := range c.Ports {
|
for _, p := range c.Ports {
|
||||||
if p.PublicPort != 0 {
|
if p.PublicPort != 0 {
|
||||||
state.URLs = append(state.URLs, fmt.Sprintf("http://localhost:%d", p.PublicPort))
|
state.URLs = append(state.URLs, fmt.Sprintf("http://localhost:%d", p.PublicPort))
|
||||||
|
state.Ports = append(state.Ports, p.PublicPort)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -299,6 +347,57 @@ func (de *DeploymentEngine) RuntimeState(ctx context.Context, serviceID string,
|
|||||||
return state, nil
|
return state, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProbeServiceHealth performs an HTTP GET on healthPath and records the
|
||||||
|
// outcome on state.Health. When the backend runs containerized it first
|
||||||
|
// attaches to the service's project network and probes the service by DNS
|
||||||
|
// name — this works for every image (no shell or wget required inside the
|
||||||
|
// container) and checks the service itself, not the published edge. A
|
||||||
|
// host-run backend falls back to probing the published host port.
|
||||||
|
func (de *DeploymentEngine) ProbeServiceHealth(ctx context.Context, state *RuntimeState, projectID, serviceName string, port int, healthPath string) {
|
||||||
|
if state == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state.Health = ""
|
||||||
|
if healthPath == "" || port <= 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(healthPath, "/") {
|
||||||
|
healthPath = "/" + healthPath
|
||||||
|
}
|
||||||
|
|
||||||
|
probeURL := ""
|
||||||
|
if networkName := ProjectNetworkName(projectID); networkName != "" {
|
||||||
|
if err := de.dockerClient.ConnectSelfToNetwork(ctx, networkName); err == nil {
|
||||||
|
probeURL = fmt.Sprintf("http://%s:%d%s", serviceName, port, healthPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if probeURL == "" && len(state.Ports) > 0 {
|
||||||
|
probeURL = fmt.Sprintf("http://%s:%d%s", de.dockerClient.HostProbeHost(ctx), state.Ports[0], healthPath)
|
||||||
|
}
|
||||||
|
if probeURL == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
reqCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, probeURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
state.Health = "unreachable"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
state.Health = "unreachable"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode >= 200 && resp.StatusCode < 400 {
|
||||||
|
state.Health = "healthy"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state.Health = "unhealthy"
|
||||||
|
}
|
||||||
|
|
||||||
// StopService stops (but keeps) all replicas of a service.
|
// StopService stops (but keeps) all replicas of a service.
|
||||||
func (de *DeploymentEngine) StopService(ctx context.Context, serviceID string) error {
|
func (de *DeploymentEngine) StopService(ctx context.Context, serviceID string) error {
|
||||||
containers, err := de.ListServiceContainers(ctx, serviceID)
|
containers, err := de.ListServiceContainers(ctx, serviceID)
|
||||||
@@ -359,7 +458,7 @@ func (de *DeploymentEngine) RemoveProjectContainers(ctx context.Context, project
|
|||||||
|
|
||||||
// RemoveProjectNetwork removes the per-project bridge network if present.
|
// RemoveProjectNetwork removes the per-project bridge network if present.
|
||||||
func (de *DeploymentEngine) RemoveProjectNetwork(ctx context.Context, projectID string) error {
|
func (de *DeploymentEngine) RemoveProjectNetwork(ctx context.Context, projectID string) error {
|
||||||
return de.dockerClient.RemoveNetwork(ctx, projectNetworkName(projectID))
|
return de.dockerClient.RemoveNetwork(ctx, ProjectNetworkName(projectID))
|
||||||
}
|
}
|
||||||
|
|
||||||
func replicaIndex(c container.Summary) int {
|
func replicaIndex(c container.Summary) int {
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"os"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/docker/docker/api/types"
|
"github.com/docker/docker/api/types"
|
||||||
@@ -24,6 +27,7 @@ import (
|
|||||||
// Client wraps the Docker client with additional functionality
|
// Client wraps the Docker client with additional functionality
|
||||||
type Client struct {
|
type Client struct {
|
||||||
cli *client.Client
|
cli *client.Client
|
||||||
|
probeHost string
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient creates a new Docker client
|
// NewClient creates a new Docker client
|
||||||
@@ -45,6 +49,75 @@ func NewClient() (*Client, error) {
|
|||||||
return &Client{cli: cli}, nil
|
return &Client{cli: cli}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HostProbeHost returns an address through which host-published container
|
||||||
|
// ports are reachable. When this process runs inside a container, host
|
||||||
|
// loopback is unreachable; the bridge gateway IP routes to ports published
|
||||||
|
// on 0.0.0.0. Result is cached for the process lifetime.
|
||||||
|
func (c *Client) HostProbeHost(ctx context.Context) string {
|
||||||
|
if c.probeHost != "" {
|
||||||
|
return c.probeHost
|
||||||
|
}
|
||||||
|
host := "127.0.0.1"
|
||||||
|
if self, err := c.self(ctx); err == nil && self.NetworkSettings != nil {
|
||||||
|
for _, n := range self.NetworkSettings.Networks {
|
||||||
|
if n != nil && n.Gateway != "" {
|
||||||
|
host = n.Gateway
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.probeHost = host
|
||||||
|
return host
|
||||||
|
}
|
||||||
|
|
||||||
|
// OwnNetworkName returns the name of the platform network this process's
|
||||||
|
// container is attached to, or "" when not running containerized. Per-project
|
||||||
|
// and default Docker networks are never selected; among remaining networks
|
||||||
|
// the lexicographically first wins so the choice is deterministic.
|
||||||
|
func (c *Client) OwnNetworkName(ctx context.Context) string {
|
||||||
|
self, err := c.self(ctx)
|
||||||
|
if err != nil || self.NetworkSettings == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
names := make([]string, 0, len(self.NetworkSettings.Networks))
|
||||||
|
for name := range self.NetworkSettings.Networks {
|
||||||
|
switch {
|
||||||
|
case name == "bridge" || name == "host" || name == "none":
|
||||||
|
case strings.HasPrefix(name, "containr-proj-"):
|
||||||
|
default:
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(names)
|
||||||
|
if len(names) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return names[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
// self inspects the container this process runs in (hostname == container ID).
|
||||||
|
func (c *Client) self(ctx context.Context) (types.ContainerJSON, error) {
|
||||||
|
hostname, err := os.Hostname()
|
||||||
|
if err != nil || hostname == "" {
|
||||||
|
return types.ContainerJSON{}, fmt.Errorf("hostname unavailable")
|
||||||
|
}
|
||||||
|
return c.cli.ContainerInspect(ctx, hostname)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectSelfToNetwork attaches this process's container to the given network.
|
||||||
|
// No-op when already attached or when not running containerized.
|
||||||
|
func (c *Client) ConnectSelfToNetwork(ctx context.Context, networkName string) error {
|
||||||
|
hostname, err := os.Hostname()
|
||||||
|
if err != nil || hostname == "" {
|
||||||
|
return fmt.Errorf("hostname unavailable")
|
||||||
|
}
|
||||||
|
err = c.cli.NetworkConnect(ctx, networkName, hostname, &network.EndpointSettings{})
|
||||||
|
if err != nil && strings.Contains(strings.ToLower(err.Error()), "already exists") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// ListContainers returns all containers
|
// ListContainers returns all containers
|
||||||
func (c *Client) ListContainers(ctx context.Context, all bool) ([]types.Container, error) {
|
func (c *Client) ListContainers(ctx context.Context, all bool) ([]types.Container, error) {
|
||||||
return c.cli.ContainerList(ctx, container.ListOptions{
|
return c.cli.ContainerList(ctx, container.ListOptions{
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package ha
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"database/sql"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
@@ -80,6 +81,8 @@ type HealthChecker struct {
|
|||||||
results map[string]*HealthCheckResult
|
results map[string]*HealthCheckResult
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
checkInterval time.Duration
|
checkInterval time.Duration
|
||||||
|
serviceResolver func(ctx context.Context, serviceID string) (host string, port int, err error)
|
||||||
|
db *sql.DB
|
||||||
}
|
}
|
||||||
|
|
||||||
// HealthCheck represents a health check configuration
|
// HealthCheck represents a health check configuration
|
||||||
@@ -596,7 +599,11 @@ func (hc *HealthChecker) performHealthChecks(ctx context.Context) error {
|
|||||||
result := hc.performHealthCheck(ctx, check)
|
result := hc.performHealthCheck(ctx, check)
|
||||||
hc.mu.Lock()
|
hc.mu.Lock()
|
||||||
hc.results[check.ID] = result
|
hc.results[check.ID] = result
|
||||||
|
check.Status = result.Status
|
||||||
|
check.LastCheck = result.Timestamp
|
||||||
hc.mu.Unlock()
|
hc.mu.Unlock()
|
||||||
|
// Persist last-known state so a restart resumes with honest history.
|
||||||
|
hc.persistCheck(check)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -617,12 +624,20 @@ func (hc *HealthChecker) performHealthCheck(ctx context.Context, check *HealthCh
|
|||||||
checkCtx, cancel := context.WithTimeout(ctx, timeout)
|
checkCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
var err error
|
host, port, err := hc.resolveTarget(ctx, check)
|
||||||
|
if err != nil {
|
||||||
|
result.Status = HealthStatusUnhealthy
|
||||||
|
result.Message = err.Error()
|
||||||
|
result.ErrorCode = "TARGET_UNRESOLVED"
|
||||||
|
result.Latency = time.Since(start)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
switch check.Type {
|
switch check.Type {
|
||||||
case HealthCheckTypeHTTP:
|
case HealthCheckTypeHTTP:
|
||||||
err = hc.performHTTPCheck(checkCtx, check)
|
err = hc.performHTTPCheck(checkCtx, check, host, port)
|
||||||
case HealthCheckTypeTCP:
|
case HealthCheckTypeTCP:
|
||||||
err = hc.performTCPCheck(checkCtx, check)
|
err = hc.performTCPCheck(checkCtx, check, host, port)
|
||||||
case HealthCheckTypeCommand:
|
case HealthCheckTypeCommand:
|
||||||
err = hc.performCommandCheck(checkCtx, check)
|
err = hc.performCommandCheck(checkCtx, check)
|
||||||
default:
|
default:
|
||||||
@@ -642,13 +657,11 @@ func (hc *HealthChecker) performHealthCheck(ctx context.Context, check *HealthCh
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthChecker) performHTTPCheck(ctx context.Context, check *HealthCheck) error {
|
func (hc *HealthChecker) performHTTPCheck(ctx context.Context, check *HealthCheck, host string, port int) error {
|
||||||
host := hc.resolveHealthCheckHost(check)
|
|
||||||
protocol := strings.ToLower(strings.TrimSpace(check.Config.Protocol))
|
protocol := strings.ToLower(strings.TrimSpace(check.Config.Protocol))
|
||||||
if protocol == "" {
|
if protocol == "" {
|
||||||
protocol = "http"
|
protocol = "http"
|
||||||
}
|
}
|
||||||
port := check.Config.Port
|
|
||||||
if port <= 0 {
|
if port <= 0 {
|
||||||
if protocol == "https" {
|
if protocol == "https" {
|
||||||
port = 443
|
port = 443
|
||||||
@@ -684,9 +697,7 @@ func (hc *HealthChecker) performHTTPCheck(ctx context.Context, check *HealthChec
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthChecker) performTCPCheck(ctx context.Context, check *HealthCheck) error {
|
func (hc *HealthChecker) performTCPCheck(ctx context.Context, check *HealthCheck, host string, port int) error {
|
||||||
host := hc.resolveHealthCheckHost(check)
|
|
||||||
port := check.Config.Port
|
|
||||||
if port <= 0 {
|
if port <= 0 {
|
||||||
port = 80
|
port = 80
|
||||||
}
|
}
|
||||||
@@ -723,6 +734,27 @@ func (hc *HealthChecker) performCommandCheck(ctx context.Context, check *HealthC
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WithServiceResolver lets the API layer plug in service-aware targeting: a
|
||||||
|
// ServiceID-bound check resolves to the service's DNS name on its project
|
||||||
|
// network instead of the backend container's loopback, where dialing
|
||||||
|
// 127.0.0.1:<host port> can never succeed.
|
||||||
|
func (m *HighAvailabilityManager) WithServiceResolver(fn func(ctx context.Context, serviceID string) (host string, port int, err error)) *HighAvailabilityManager {
|
||||||
|
m.healthChecker.serviceResolver = fn
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithPersistence attaches Postgres so configured checks survive restarts.
|
||||||
|
// Call LoadHealthChecks once during startup to hydrate state.
|
||||||
|
func (m *HighAvailabilityManager) WithPersistence(db *sql.DB) *HighAvailabilityManager {
|
||||||
|
m.healthChecker.db = db
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadHealthChecks hydrates persisted health checks during startup.
|
||||||
|
func (m *HighAvailabilityManager) LoadHealthChecks(ctx context.Context) error {
|
||||||
|
return m.healthChecker.LoadHealthChecks(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
func (hc *HealthChecker) resolveHealthCheckHost(check *HealthCheck) string {
|
func (hc *HealthChecker) resolveHealthCheckHost(check *HealthCheck) string {
|
||||||
if strings.TrimSpace(check.NodeID) != "" && hc.scheduler != nil {
|
if strings.TrimSpace(check.NodeID) != "" && hc.scheduler != nil {
|
||||||
nodes := hc.scheduler.GetNodes()
|
nodes := hc.scheduler.GetNodes()
|
||||||
@@ -739,19 +771,109 @@ func (hc *HealthChecker) resolveHealthCheckHost(check *HealthCheck) string {
|
|||||||
return "127.0.0.1"
|
return "127.0.0.1"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resolveTarget picks the dial target for a check: service-bound checks go to
|
||||||
|
// the service DNS name on the project network; node-bound and free-standing
|
||||||
|
// checks keep the old host behavior. A service-bound resolver failure is
|
||||||
|
// surfaced as an error — falling back to loopback would only produce a
|
||||||
|
// misleading "service down" result.
|
||||||
|
func (hc *HealthChecker) resolveTarget(ctx context.Context, check *HealthCheck) (string, int, error) {
|
||||||
|
port := check.Config.Port
|
||||||
|
if strings.TrimSpace(check.NodeID) == "" && check.ServiceID != "" && hc.serviceResolver != nil {
|
||||||
|
resolveCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
h, p, err := hc.serviceResolver(resolveCtx, check.ServiceID)
|
||||||
|
if err != nil {
|
||||||
|
return "", 0, fmt.Errorf("resolve service target: %w", err)
|
||||||
|
}
|
||||||
|
if h == "" {
|
||||||
|
return "", 0, fmt.Errorf("resolve service target: service %s not found", check.ServiceID)
|
||||||
|
}
|
||||||
|
if port <= 0 {
|
||||||
|
port = p
|
||||||
|
}
|
||||||
|
return h, port, nil
|
||||||
|
}
|
||||||
|
return hc.resolveHealthCheckHost(check), port, nil
|
||||||
|
}
|
||||||
|
|
||||||
// AddHealthCheck adds a new health check
|
// AddHealthCheck adds a new health check
|
||||||
func (hc *HealthChecker) AddHealthCheck(check *HealthCheck) {
|
func (hc *HealthChecker) AddHealthCheck(check *HealthCheck) {
|
||||||
hc.mu.Lock()
|
hc.mu.Lock()
|
||||||
defer hc.mu.Unlock()
|
|
||||||
hc.checks[check.ID] = check
|
hc.checks[check.ID] = check
|
||||||
|
hc.mu.Unlock()
|
||||||
|
hc.persistCheck(check)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RemoveHealthCheck removes a health check
|
// RemoveHealthCheck removes a health check
|
||||||
func (hc *HealthChecker) RemoveHealthCheck(checkID string) {
|
func (hc *HealthChecker) RemoveHealthCheck(checkID string) {
|
||||||
hc.mu.Lock()
|
hc.mu.Lock()
|
||||||
defer hc.mu.Unlock()
|
|
||||||
delete(hc.checks, checkID)
|
delete(hc.checks, checkID)
|
||||||
delete(hc.results, checkID)
|
delete(hc.results, checkID)
|
||||||
|
hc.mu.Unlock()
|
||||||
|
if hc.db != nil {
|
||||||
|
_, _ = hc.db.ExecContext(context.Background(), `DELETE FROM ha_health_checks WHERE id = $1`, checkID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// persistCheck upserts one check. Best effort — a write failure never blocks
|
||||||
|
// the in-memory path, matching the scaling-policy persistence style.
|
||||||
|
func (hc *HealthChecker) persistCheck(check *HealthCheck) {
|
||||||
|
if hc.db == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg, _ := json.Marshal(check.Config)
|
||||||
|
var lastCheck interface{}
|
||||||
|
if !check.LastCheck.IsZero() {
|
||||||
|
lastCheck = check.LastCheck
|
||||||
|
}
|
||||||
|
_, _ = hc.db.ExecContext(context.Background(),
|
||||||
|
`INSERT INTO ha_health_checks (id, service_id, node_id, type, config, status, last_check, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, now())
|
||||||
|
ON CONFLICT (id) DO UPDATE
|
||||||
|
SET service_id = EXCLUDED.service_id, node_id = EXCLUDED.node_id,
|
||||||
|
type = EXCLUDED.type, config = EXCLUDED.config,
|
||||||
|
status = EXCLUDED.status, last_check = EXCLUDED.last_check,
|
||||||
|
updated_at = now()`,
|
||||||
|
check.ID, check.ServiceID, check.NodeID, string(check.Type), cfg, string(check.Status), lastCheck,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadHealthChecks hydrates checks persisted across restarts.
|
||||||
|
func (hc *HealthChecker) LoadHealthChecks(ctx context.Context) error {
|
||||||
|
if hc.db == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
rows, err := hc.db.QueryContext(ctx,
|
||||||
|
`SELECT id, service_id, node_id, type, config, status, last_check FROM ha_health_checks`)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
loaded := 0
|
||||||
|
for rows.Next() {
|
||||||
|
var check HealthCheck
|
||||||
|
var cfg []byte
|
||||||
|
var status, checkType string
|
||||||
|
var lastCheck sql.NullTime
|
||||||
|
if err := rows.Scan(&check.ID, &check.ServiceID, &check.NodeID, &checkType, &cfg, &status, &lastCheck); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
check.Type = HealthCheckType(checkType)
|
||||||
|
check.Status = HealthStatus(status)
|
||||||
|
if lastCheck.Valid {
|
||||||
|
check.LastCheck = lastCheck.Time
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(cfg, &check.Config)
|
||||||
|
hc.mu.Lock()
|
||||||
|
hc.checks[check.ID] = &check
|
||||||
|
hc.mu.Unlock()
|
||||||
|
loaded++
|
||||||
|
}
|
||||||
|
if loaded > 0 {
|
||||||
|
log.Printf("Restored %d health checks", loaded)
|
||||||
|
}
|
||||||
|
return rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetHealthCheck returns one configured health check.
|
// GetHealthCheck returns one configured health check.
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ package middleware
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"containr/internal/database"
|
"containr/internal/database"
|
||||||
|
sqlcdb "containr/internal/database/sqlcdb"
|
||||||
|
"crypto/sha256"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -75,6 +78,14 @@ func RequestID() gin.HandlerFunc {
|
|||||||
func resolveRequestUser(c *gin.Context, jwtSecret string, sessionVerifier *betterAuthSessionVerifier) (userID, email, tokenErr string, hasToken, ok bool) {
|
func resolveRequestUser(c *gin.Context, jwtSecret string, sessionVerifier *betterAuthSessionVerifier) (userID, email, tokenErr string, hasToken, ok bool) {
|
||||||
tokenString, tokenErr, hasToken := extractJWTToken(c)
|
tokenString, tokenErr, hasToken := extractJWTToken(c)
|
||||||
if tokenString != "" {
|
if tokenString != "" {
|
||||||
|
// Personal access tokens (cnp_…) are not JWTs — they resolve
|
||||||
|
// against the user_tokens table by sha256 hash.
|
||||||
|
if strings.HasPrefix(tokenString, patPrefix) {
|
||||||
|
if id, mail, verified := resolvePersonalAccessToken(c, tokenString); verified {
|
||||||
|
return id, mail, "", hasToken, true
|
||||||
|
}
|
||||||
|
return "", "", "Invalid token", hasToken, false
|
||||||
|
}
|
||||||
if claims, valid := validateJWTClaims(tokenString, jwtSecret); valid {
|
if claims, valid := validateJWTClaims(tokenString, jwtSecret); valid {
|
||||||
userIDClaim, exists := claims["user_id"]
|
userIDClaim, exists := claims["user_id"]
|
||||||
if exists {
|
if exists {
|
||||||
@@ -101,12 +112,67 @@ func resolveRequestUser(c *gin.Context, jwtSecret string, sessionVerifier *bette
|
|||||||
return "", "", tokenErr, hasToken, false
|
return "", "", tokenErr, hasToken, false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const patPrefix = "cnp_"
|
||||||
|
|
||||||
|
// resolvePersonalAccessToken authenticates a `cnp_` bearer token against the
|
||||||
|
// user_tokens table (sha256 hash match, not revoked, not expired). On success
|
||||||
|
// it stamps last_used_at, records the token scope on the context, and
|
||||||
|
// returns the owner's id and email.
|
||||||
|
func resolvePersonalAccessToken(c *gin.Context, token string) (string, string, bool) {
|
||||||
|
dbValue, exists := c.Get("db")
|
||||||
|
if !exists {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
db, ok := dbValue.(*database.DB)
|
||||||
|
if !ok || db == nil || db.DB == nil {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
sum := sha256.Sum256([]byte(token))
|
||||||
|
queries := sqlcdb.New(db.DB)
|
||||||
|
row, err := queries.GetUserTokenByHash(c.Request.Context(), hex.EncodeToString(sum[:]))
|
||||||
|
if err != nil {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
var email string
|
||||||
|
if err := db.QueryRowContext(c.Request.Context(),
|
||||||
|
`SELECT email FROM users WHERE id = $1`, row.UserID).Scan(&email); err != nil {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = queries.TouchUserToken(c.Request.Context(), row.ID)
|
||||||
|
c.Set("pat_scope", row.Scope)
|
||||||
|
return row.UserID.String(), email, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// patScopeAllows reports whether a PAT-authenticated request may proceed.
|
||||||
|
// read scope permits only safe methods; write and admin are unrestricted at
|
||||||
|
// this layer (admin routes still require the admin scope AND a platform
|
||||||
|
// admin account — enforced via is_admin in setAuthenticatedContext).
|
||||||
|
func patScopeAllows(c *gin.Context) bool {
|
||||||
|
if c.GetString("pat_scope") != "read" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
switch c.Request.Method {
|
||||||
|
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// setAuthenticatedContext stores the resolved identity plus the admin flag on
|
// setAuthenticatedContext stores the resolved identity plus the admin flag on
|
||||||
// the gin context so handlers and RequireAdmin can rely on it.
|
// the gin context so handlers and RequireAdmin can rely on it.
|
||||||
func setAuthenticatedContext(c *gin.Context, userID, email string) {
|
func setAuthenticatedContext(c *gin.Context, userID, email string) {
|
||||||
c.Set("user_id", userID)
|
c.Set("user_id", userID)
|
||||||
c.Set("email", email)
|
c.Set("email", email)
|
||||||
c.Set("is_admin", loadIsAdmin(c, userID))
|
isAdmin := loadIsAdmin(c, userID)
|
||||||
|
// A PAT can never outrank its scope: non-admin scopes cap the token at
|
||||||
|
// non-admin even when the owning user is a platform admin.
|
||||||
|
if scope := c.GetString("pat_scope"); scope != "" && scope != "admin" {
|
||||||
|
isAdmin = false
|
||||||
|
}
|
||||||
|
c.Set("is_admin", isAdmin)
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadIsAdmin(c *gin.Context, userID string) bool {
|
func loadIsAdmin(c *gin.Context, userID string) bool {
|
||||||
@@ -133,6 +199,14 @@ func Auth(jwtSecret string) gin.HandlerFunc {
|
|||||||
userID, email, tokenErr, hasToken, ok := resolveRequestUser(c, jwtSecret, sessionVerifier)
|
userID, email, tokenErr, hasToken, ok := resolveRequestUser(c, jwtSecret, sessionVerifier)
|
||||||
if ok {
|
if ok {
|
||||||
setAuthenticatedContext(c, userID, email)
|
setAuthenticatedContext(c, userID, email)
|
||||||
|
if !patScopeAllows(c) {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{
|
||||||
|
"error": "Token scope is read-only",
|
||||||
|
"code": "SCOPE_INSUFFICIENT",
|
||||||
|
})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
c.Next()
|
c.Next()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -131,6 +131,61 @@ func TestAuthStoresStringUserIDForValidClaims(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAuthRejectsPATWithoutDatabase(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
router := gin.New()
|
||||||
|
router.Use(Auth("secret"))
|
||||||
|
router.GET("/test", func(c *gin.Context) {
|
||||||
|
c.String(http.StatusOK, "ok")
|
||||||
|
})
|
||||||
|
|
||||||
|
// A cnp_-prefixed token takes the PAT path, not JWT parsing — without a
|
||||||
|
// db handle it must fail closed with 401.
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer cnp_"+strings.Repeat("ab", 24))
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("expected status %d, got %d", http.StatusUnauthorized, rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPATScopeAllows(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
scope string
|
||||||
|
method string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"read allows GET", "read", http.MethodGet, true},
|
||||||
|
{"read allows HEAD", "read", http.MethodHead, true},
|
||||||
|
{"read allows OPTIONS", "read", http.MethodOptions, true},
|
||||||
|
{"read blocks POST", "read", http.MethodPost, false},
|
||||||
|
{"read blocks DELETE", "read", http.MethodDelete, false},
|
||||||
|
{"write allows POST", "write", http.MethodPost, true},
|
||||||
|
{"write allows DELETE", "write", http.MethodDelete, true},
|
||||||
|
{"admin allows PATCH", "admin", http.MethodPatch, true},
|
||||||
|
{"no scope (session/JWT) unrestricted", "", http.MethodPost, true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(rec)
|
||||||
|
c.Request = httptest.NewRequest(tc.method, "/x", nil)
|
||||||
|
if tc.scope != "" {
|
||||||
|
c.Set("pat_scope", tc.scope)
|
||||||
|
}
|
||||||
|
if got := patScopeAllows(c); got != tc.want {
|
||||||
|
t.Fatalf("patScopeAllows(scope=%q, method=%s) = %v, want %v", tc.scope, tc.method, got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func issueJWT(t *testing.T, secret string, claims jwt.MapClaims) string {
|
func issueJWT(t *testing.T, secret string, claims jwt.MapClaims) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- +goose Up
|
||||||
|
-- Stable public host port for service replica 0. 0 means "not yet assigned";
|
||||||
|
-- the runtime writes the ephemeral port it picked back here so restarts and
|
||||||
|
-- redeploys keep the same public endpoint instead of churning.
|
||||||
|
ALTER TABLE public.services ADD COLUMN IF NOT EXISTS published_port integer NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
ALTER TABLE public.services DROP COLUMN IF EXISTS published_port;
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
-- +goose Up
|
||||||
|
-- Persisted HA health checks. Previously checks lived only in memory, so a
|
||||||
|
-- backend restart silently deleted every configured check while services kept
|
||||||
|
-- running unmonitored.
|
||||||
|
CREATE TABLE IF NOT EXISTS ha_health_checks (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
service_id uuid NOT NULL REFERENCES services(id) ON DELETE CASCADE,
|
||||||
|
node_id varchar(255) NOT NULL DEFAULT '',
|
||||||
|
type varchar(20) NOT NULL,
|
||||||
|
config jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
status varchar(20) NOT NULL DEFAULT 'unknown',
|
||||||
|
last_check timestamptz,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
DROP TABLE IF EXISTS ha_health_checks;
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
-- +goose Up
|
||||||
|
-- Personal access tokens for CLI/MCP/agent authentication.
|
||||||
|
-- Only sha256 hashes are stored — raw tokens (cnp_…) are shown once at
|
||||||
|
-- creation and never persisted. Scope gates what the token may do:
|
||||||
|
-- read = GET/HEAD only, write = all non-admin routes, admin = everything
|
||||||
|
-- (admin still requires the owning user to be a platform admin).
|
||||||
|
CREATE TABLE IF NOT EXISTS public.user_tokens (
|
||||||
|
id uuid DEFAULT gen_random_uuid() NOT NULL PRIMARY KEY,
|
||||||
|
user_id uuid NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
|
||||||
|
name character varying(255) NOT NULL,
|
||||||
|
key_prefix character varying(16) NOT NULL,
|
||||||
|
token_hash text NOT NULL UNIQUE,
|
||||||
|
scope character varying(20) NOT NULL DEFAULT 'write'
|
||||||
|
CHECK (scope IN ('read', 'write', 'admin')),
|
||||||
|
expires_at timestamp with time zone,
|
||||||
|
last_used_at timestamp with time zone,
|
||||||
|
revoked_at timestamp with time zone,
|
||||||
|
created_at timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_tokens_user_id ON public.user_tokens(user_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_tokens_token_hash ON public.user_tokens(token_hash);
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
DROP TABLE IF EXISTS public.user_tokens;
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
-- name: CreateUserToken :one
|
||||||
|
INSERT INTO user_tokens (user_id, name, key_prefix, token_hash, scope, expires_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6)
|
||||||
|
RETURNING *;
|
||||||
|
|
||||||
|
-- name: ListUserTokens :many
|
||||||
|
SELECT * FROM user_tokens
|
||||||
|
WHERE user_id = $1 AND revoked_at IS NULL
|
||||||
|
ORDER BY created_at DESC;
|
||||||
|
|
||||||
|
-- name: GetUserTokenByHash :one
|
||||||
|
SELECT * FROM user_tokens
|
||||||
|
WHERE token_hash = $1
|
||||||
|
AND revoked_at IS NULL
|
||||||
|
AND (expires_at IS NULL OR expires_at > NOW())
|
||||||
|
LIMIT 1;
|
||||||
|
|
||||||
|
-- name: TouchUserToken :exec
|
||||||
|
UPDATE user_tokens SET last_used_at = NOW()
|
||||||
|
WHERE id = $1 AND revoked_at IS NULL;
|
||||||
|
|
||||||
|
-- name: RevokeUserToken :execrows
|
||||||
|
UPDATE user_tokens SET revoked_at = NOW()
|
||||||
|
WHERE id = $1 AND user_id = $2 AND revoked_at IS NULL;
|
||||||
@@ -52,7 +52,13 @@ CREATE TABLE services (
|
|||||||
git_branch VARCHAR(100),
|
git_branch VARCHAR(100),
|
||||||
build_path VARCHAR(500),
|
build_path VARCHAR(500),
|
||||||
cpu VARCHAR(50),
|
cpu VARCHAR(50),
|
||||||
memory VARCHAR(50)
|
memory VARCHAR(50),
|
||||||
|
replicas INTEGER NOT NULL DEFAULT 1,
|
||||||
|
port INTEGER NOT NULL DEFAULT 0,
|
||||||
|
domain VARCHAR(255) NOT NULL DEFAULT '',
|
||||||
|
healthcheck_path VARCHAR(255) NOT NULL DEFAULT '',
|
||||||
|
restart_policy VARCHAR(50) NOT NULL DEFAULT 'unless-stopped',
|
||||||
|
published_port INTEGER NOT NULL DEFAULT 0
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE deployments (
|
CREATE TABLE deployments (
|
||||||
@@ -198,3 +204,16 @@ CREATE TABLE notifications (
|
|||||||
read_at TIMESTAMP WITH TIME ZONE,
|
read_at TIMESTAMP WITH TIME ZONE,
|
||||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE user_tokens (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
key_prefix VARCHAR(16) NOT NULL,
|
||||||
|
token_hash TEXT NOT NULL UNIQUE,
|
||||||
|
scope VARCHAR(20) NOT NULL DEFAULT 'write',
|
||||||
|
expires_at TIMESTAMP WITH TIME ZONE,
|
||||||
|
last_used_at TIMESTAMP WITH TIME ZONE,
|
||||||
|
revoked_at TIMESTAMP WITH TIME ZONE,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||||
|
);
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Link, Navigate, Outlet, Route, Routes, useLocation } from 'react-router-dom';
|
import { Link, Navigate, Outlet, Route, Routes, useLocation } from 'react-router-dom';
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { ShieldCheck } from 'lucide-react';
|
import { Compass, ShieldCheck } from 'lucide-react';
|
||||||
import { PlatformShell } from './layout/PlatformShell';
|
import { PlatformShell } from './layout/PlatformShell';
|
||||||
import { ProjectsPage } from '@/features/projects/pages/ProjectsPage';
|
import { ProjectsPage } from '@/features/projects/pages/ProjectsPage';
|
||||||
import { ProjectWorkspacePage } from '@/features/workspace/pages/ProjectWorkspacePage';
|
import { ProjectWorkspacePage } from '@/features/workspace/pages/ProjectWorkspacePage';
|
||||||
@@ -103,6 +103,26 @@ function AdminRequired() {
|
|||||||
return <Outlet />;
|
return <Outlet />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function NotFoundPage() {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-[60vh] flex-col items-center justify-center gap-4 px-6 text-center">
|
||||||
|
<Compass size={32} className="text-[var(--text-tertiary)]" />
|
||||||
|
<div>
|
||||||
|
<h1 className="text-lg font-semibold text-[var(--text-primary)]">Page not found</h1>
|
||||||
|
<p className="mt-1 max-w-sm text-sm text-[var(--text-secondary)]">
|
||||||
|
The page you are looking for does not exist or was moved.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Link
|
||||||
|
to="/"
|
||||||
|
className="rounded-[var(--radius-md)] border border-[var(--border-default)] px-4 py-2 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
|
||||||
|
>
|
||||||
|
Back to home
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
<ErrorBoundary>
|
<ErrorBoundary>
|
||||||
@@ -138,14 +158,14 @@ export default function App() {
|
|||||||
<Route element={<AdminRequired />}>
|
<Route element={<AdminRequired />}>
|
||||||
<Route path="/admin" element={<AdminPage />} />
|
<Route path="/admin" element={<AdminPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
|
|
||||||
|
<Route path="*" element={<NotFoundPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
|
|
||||||
{/* Full-bleed design demo — renders its own chrome, no app shell */}
|
{/* Full-bleed design demo — renders its own chrome, no app shell */}
|
||||||
<Route element={<AuthRequired />}>
|
<Route element={<AuthRequired />}>
|
||||||
<Route path="/metrics-demo" element={<ServiceMetricsDashboard />} />
|
<Route path="/metrics-demo" element={<ServiceMetricsDashboard />} />
|
||||||
</Route>
|
</Route>
|
||||||
|
|
||||||
<Route path="*" element={<Navigate to="/" replace />} />
|
|
||||||
</Routes>
|
</Routes>
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -25,10 +25,10 @@ const demoDeploys = [
|
|||||||
{ id: 'd4', name: 'Marketing Site', project: 'Growth Surface', status: 'DEPLOYED', when: '2h' },
|
{ id: 'd4', name: 'Marketing Site', project: 'Growth Surface', status: 'DEPLOYED', when: '2h' },
|
||||||
];
|
];
|
||||||
|
|
||||||
function getHealthStatus(stats: ProjectStats): 'healthy' | 'degraded' | 'critical' {
|
function getHealthStatus(stats: ProjectStats): 'healthy' | 'idle' | 'degraded' | 'critical' {
|
||||||
if (stats.service_count === 0) return 'healthy';
|
if (stats.service_count === 0) return 'idle';
|
||||||
if (stats.running_services === stats.service_count) return 'healthy';
|
if (stats.running_services === stats.service_count) return 'healthy';
|
||||||
if (stats.running_services >= stats.service_count / 2) return 'degraded';
|
if (stats.running_services > 0) return 'degraded';
|
||||||
return 'critical';
|
return 'critical';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,6 +36,8 @@ function healthBadge(health: ReturnType<typeof getHealthStatus>) {
|
|||||||
switch (health) {
|
switch (health) {
|
||||||
case 'healthy':
|
case 'healthy':
|
||||||
return { label: 'RUNNING', cls: 'v-st-ok' };
|
return { label: 'RUNNING', cls: 'v-st-ok' };
|
||||||
|
case 'idle':
|
||||||
|
return { label: 'IDLE', cls: '' };
|
||||||
case 'degraded':
|
case 'degraded':
|
||||||
return { label: 'DEGRADED', cls: 'v-st-warn' };
|
return { label: 'DEGRADED', cls: 'v-st-warn' };
|
||||||
case 'critical':
|
case 'critical':
|
||||||
@@ -70,7 +72,6 @@ function MiniCanvas({ project }: { project: ProjectEntity }) {
|
|||||||
{Array.from({ length: shown }).map((_, i) => (
|
{Array.from({ length: shown }).map((_, i) => (
|
||||||
<div key={i} className="v-node" style={positions[i]}>
|
<div key={i} className="v-node" style={positions[i]}>
|
||||||
<b className={`v-nd ${i < running ? '' : 'r'}`} />
|
<b className={`v-nd ${i < running ? '' : 'r'}`} />
|
||||||
svc{i + 1}
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
{extra > 0 ? (
|
{extra > 0 ? (
|
||||||
@@ -85,6 +86,7 @@ function ProjectCard({ project, href }: { project: ProjectEntity; href: string }
|
|||||||
const health = getHealthStatus(project.stats);
|
const health = getHealthStatus(project.stats);
|
||||||
const badge = healthBadge(health);
|
const badge = healthBadge(health);
|
||||||
const envOk = health === 'healthy';
|
const envOk = health === 'healthy';
|
||||||
|
const envLabel = envOk ? 'production' : health === 'idle' ? 'idle' : health === 'critical' ? 'down' : 'degraded';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<article
|
<article
|
||||||
@@ -101,10 +103,10 @@ function ProjectCard({ project, href }: { project: ProjectEntity; href: string }
|
|||||||
<div className="v-mono mt-3 flex items-center gap-2 text-[10.5px] text-[var(--text-tertiary)]">
|
<div className="v-mono mt-3 flex items-center gap-2 text-[10.5px] text-[var(--text-tertiary)]">
|
||||||
<i
|
<i
|
||||||
className="inline-block h-1.5 w-1.5 rounded-full"
|
className="inline-block h-1.5 w-1.5 rounded-full"
|
||||||
style={{ background: envOk ? 'var(--success)' : 'var(--warning)' }}
|
style={{ background: envOk ? 'var(--success)' : health === 'idle' ? 'var(--text-tertiary)' : health === 'critical' ? 'var(--error)' : 'var(--warning)' }}
|
||||||
/>
|
/>
|
||||||
<span className="text-[var(--text-secondary)]">
|
<span className="text-[var(--text-secondary)]">
|
||||||
{envOk ? 'production' : 'degraded'}
|
{envLabel}
|
||||||
</span>
|
</span>
|
||||||
<span>·</span>
|
<span>·</span>
|
||||||
<span>
|
<span>
|
||||||
@@ -179,6 +181,7 @@ export function ProjectsPage() {
|
|||||||
const totalServices = projects.reduce((sum, p) => sum + p.stats.service_count, 0);
|
const totalServices = projects.reduce((sum, p) => sum + p.stats.service_count, 0);
|
||||||
const runningServices = projects.reduce((sum, p) => sum + p.stats.running_services, 0);
|
const runningServices = projects.reduce((sum, p) => sum + p.stats.running_services, 0);
|
||||||
const host = hostQuery.data;
|
const host = hostQuery.data;
|
||||||
|
const hostLabel = host?.scope === 'docker-desktop-vm' ? 'VM' : 'HOST';
|
||||||
const cpuPct = isDemoMode ? 14 : host && host.cpu.cores > 0
|
const cpuPct = isDemoMode ? 14 : host && host.cpu.cores > 0
|
||||||
? Math.min(100, Math.round((host.load.load1m / host.cpu.cores) * 100))
|
? Math.min(100, Math.round((host.load.load1m / host.cpu.cores) * 100))
|
||||||
: null;
|
: null;
|
||||||
@@ -220,7 +223,7 @@ export function ProjectsPage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2.5">
|
<div className="flex items-center gap-2.5">
|
||||||
<div className="search-box" style={{ width: 240 }}>
|
<div className="search-box" style={{ width: 'min(240px, 42vw)' }}>
|
||||||
<Search size={13} />
|
<Search size={13} />
|
||||||
<input
|
<input
|
||||||
value={search}
|
value={search}
|
||||||
@@ -230,16 +233,18 @@ export function ProjectsPage() {
|
|||||||
style={{ fontSize: 11.5 }}
|
style={{ fontSize: 11.5 }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
{signedIn && (
|
||||||
<button onClick={openCreate} className="v-btn">
|
<button onClick={openCreate} className="v-btn">
|
||||||
+ new project
|
+ new project
|
||||||
</button>
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Host stat row */}
|
{/* Host stat row */}
|
||||||
<div className="mb-7 grid grid-cols-2 gap-3 lg:grid-cols-4">
|
<div className="mb-7 grid grid-cols-2 gap-3 lg:grid-cols-4">
|
||||||
<div className="v-stat">
|
<div className="v-stat">
|
||||||
<div className="v-k"><span>HOST.CPU</span><span className="v-live" /></div>
|
<div className="v-k"><span>{hostLabel}.CPU</span><span className="v-live" /></div>
|
||||||
<div className="v-v">{cpuPct ?? '—'}<span>%</span></div>
|
<div className="v-v">{cpuPct ?? '—'}<span>%</span></div>
|
||||||
{isDemoMode ? (
|
{isDemoMode ? (
|
||||||
<div className="v-spark">
|
<div className="v-spark">
|
||||||
@@ -255,13 +260,13 @@ export function ProjectsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="v-stat">
|
<div className="v-stat">
|
||||||
<div className="v-k"><span>HOST.MEM</span><span className="v-live" /></div>
|
<div className="v-k"><span>{hostLabel}.MEM</span><span className="v-live" /></div>
|
||||||
<div className="v-v">{memPct ?? '—'}<span>%</span></div>
|
<div className="v-v">{memPct ?? '—'}<span>%</span></div>
|
||||||
<div className="v-meter"><i className={memPct !== null && memPct > 85 ? 'r' : 'y'} style={{ width: `${memPct ?? 0}%` }} /></div>
|
<div className="v-meter"><i className={memPct !== null && memPct > 85 ? 'r' : 'y'} style={{ width: `${memPct ?? 0}%` }} /></div>
|
||||||
<div className="v-d">{isDemoMode ? '9.8G / 13G' : host ? `${fmtGB(host.memory.used)} / ${fmtGB(host.memory.total)}` : 'no telemetry'}</div>
|
<div className="v-d">{isDemoMode ? '9.8G / 13G' : host ? `${fmtGB(host.memory.used)} / ${fmtGB(host.memory.total)}` : 'no telemetry'}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="v-stat">
|
<div className="v-stat">
|
||||||
<div className="v-k"><span>HOST.DISK</span><span className="v-live" /></div>
|
<div className="v-k"><span>{hostLabel}.DISK</span><span className="v-live" /></div>
|
||||||
<div className="v-v">{diskPct ?? '—'}<span>%</span></div>
|
<div className="v-v">{diskPct ?? '—'}<span>%</span></div>
|
||||||
<div className="v-meter"><i className="r" style={{ width: `${diskPct ?? 0}%` }} /></div>
|
<div className="v-meter"><i className="r" style={{ width: `${diskPct ?? 0}%` }} /></div>
|
||||||
<div className="v-d">{isDemoMode ? '338G of 465G · high' : host ? `${fmtGB(host.storage.used)} of ${fmtGB(host.storage.total)}` : 'no telemetry'}</div>
|
<div className="v-d">{isDemoMode ? '338G of 465G · high' : host ? `${fmtGB(host.storage.used)} of ${fmtGB(host.storage.total)}` : 'no telemetry'}</div>
|
||||||
|
|||||||
@@ -17,6 +17,9 @@ import {
|
|||||||
createAgentToken,
|
createAgentToken,
|
||||||
listAgentTokens,
|
listAgentTokens,
|
||||||
revokeAgentToken,
|
revokeAgentToken,
|
||||||
|
createUserToken,
|
||||||
|
listUserTokens,
|
||||||
|
revokeUserToken,
|
||||||
listDatabases,
|
listDatabases,
|
||||||
databaseAction,
|
databaseAction,
|
||||||
updateDatabaseBackupSchedule,
|
updateDatabaseBackupSchedule,
|
||||||
@@ -46,6 +49,8 @@ import {
|
|||||||
updateVulnerability,
|
updateVulnerability,
|
||||||
getSecurityMetrics,
|
getSecurityMetrics,
|
||||||
type AgentAuthTokenCreated,
|
type AgentAuthTokenCreated,
|
||||||
|
type UserTokenCreated,
|
||||||
|
type UserTokenScope,
|
||||||
type CreateDatabaseInput,
|
type CreateDatabaseInput,
|
||||||
type DatabaseEntity,
|
type DatabaseEntity,
|
||||||
type FailoverPolicy,
|
type FailoverPolicy,
|
||||||
@@ -1267,6 +1272,164 @@ function PlatformSettingsSection() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const PAT_EXPIRY_OPTIONS: { label: string; days: number }[] = [
|
||||||
|
{ label: 'Never', days: 0 },
|
||||||
|
{ label: '30 days', days: 30 },
|
||||||
|
{ label: '90 days', days: 90 },
|
||||||
|
{ label: '1 year', days: 365 },
|
||||||
|
];
|
||||||
|
|
||||||
|
function UserTokensSection({ isAdmin }: { isAdmin: boolean }) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const tokensQuery = useQuery({
|
||||||
|
queryKey: ['user-tokens'],
|
||||||
|
queryFn: listUserTokens,
|
||||||
|
});
|
||||||
|
const [tokenName, setTokenName] = useState('');
|
||||||
|
const [tokenScope, setTokenScope] = useState<UserTokenScope>('write');
|
||||||
|
const [expiryDays, setExpiryDays] = useState(0);
|
||||||
|
const [issuedToken, setIssuedToken] = useState<UserTokenCreated | null>(null);
|
||||||
|
|
||||||
|
const createMutation = useMutation({
|
||||||
|
mutationFn: () =>
|
||||||
|
createUserToken({
|
||||||
|
name: tokenName.trim(),
|
||||||
|
scope: tokenScope,
|
||||||
|
expiresInDays: expiryDays,
|
||||||
|
}),
|
||||||
|
onSuccess: (data) => {
|
||||||
|
setIssuedToken(data);
|
||||||
|
setTokenName('');
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['user-tokens'] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const revokeMutation = useMutation({
|
||||||
|
mutationFn: (id: string) => revokeUserToken(id),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['user-tokens'] }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const tokens = tokensQuery.data ?? [];
|
||||||
|
const scopeOptions: { value: UserTokenScope; label: string }[] = isAdmin
|
||||||
|
? [
|
||||||
|
{ value: 'read', label: 'Read - GET requests only' },
|
||||||
|
{ value: 'write', label: 'Write - read and manage resources' },
|
||||||
|
{ value: 'admin', label: 'Admin - everything, incl. platform settings' },
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
{ value: 'read', label: 'Read - GET requests only' },
|
||||||
|
{ value: 'write', label: 'Write - read and manage resources' },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="panel p-6">
|
||||||
|
<div className="flex items-center gap-3 mb-4">
|
||||||
|
<div className="w-10 h-10 rounded-[var(--radius-md)] bg-[var(--accent-primary-soft)] flex items-center justify-center">
|
||||||
|
<Key size={18} className="text-[var(--accent-primary)]" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold text-[var(--text-primary)]">Personal Access Tokens</h2>
|
||||||
|
<p className="text-xs text-[var(--text-tertiary)]">Authenticate the CLI, MCP server, and scripts - same rights as you, bounded by scope</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<input
|
||||||
|
value={tokenName}
|
||||||
|
onChange={(e) => setTokenName(e.target.value)}
|
||||||
|
placeholder="Token name (e.g. laptop cli)"
|
||||||
|
className="h-9 flex-1 min-w-[180px] rounded-[var(--radius-md)] border border-[var(--border-subtle)] bg-[var(--surface-muted)] px-3 text-sm text-[var(--text-primary)] placeholder:text-[var(--text-muted)] focus:border-[var(--accent-primary)] transition-all"
|
||||||
|
/>
|
||||||
|
<select
|
||||||
|
value={tokenScope}
|
||||||
|
onChange={(e) => setTokenScope(e.target.value as UserTokenScope)}
|
||||||
|
className="h-9 rounded-[var(--radius-md)] border border-[var(--border-subtle)] bg-[var(--surface-muted)] px-3 text-sm text-[var(--text-primary)] focus:border-[var(--accent-primary)] transition-all"
|
||||||
|
>
|
||||||
|
{scopeOptions.map((option) => (
|
||||||
|
<option key={option.value} value={option.value}>{option.label}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<select
|
||||||
|
value={expiryDays}
|
||||||
|
onChange={(e) => setExpiryDays(Number(e.target.value))}
|
||||||
|
className="h-9 rounded-[var(--radius-md)] border border-[var(--border-subtle)] bg-[var(--surface-muted)] px-3 text-sm text-[var(--text-primary)] focus:border-[var(--accent-primary)] transition-all"
|
||||||
|
>
|
||||||
|
{PAT_EXPIRY_OPTIONS.map((option) => (
|
||||||
|
<option key={option.days} value={option.days}>{option.label}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
onClick={() => createMutation.mutate()}
|
||||||
|
disabled={createMutation.isPending || !tokenName.trim()}
|
||||||
|
className="h-9 px-4 rounded-[var(--radius-md)] text-sm font-medium text-[var(--accent-on)] disabled:opacity-50 disabled:cursor-not-allowed transition-all"
|
||||||
|
style={{ background: 'var(--accent-primary)' }}
|
||||||
|
>
|
||||||
|
{createMutation.isPending ? 'Creating…' : 'Create token'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{issuedToken ? (
|
||||||
|
<div className="rounded-[var(--radius-md)] border border-[var(--success)]/30 bg-[var(--success-soft)] p-3">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<span className="mono text-xs text-[var(--text-primary)] break-all">{issuedToken.token}</span>
|
||||||
|
<button
|
||||||
|
onClick={() => void navigator.clipboard.writeText(issuedToken.token ?? '')}
|
||||||
|
className="flex items-center gap-1 text-xs text-[var(--accent-primary)] hover:underline shrink-0"
|
||||||
|
>
|
||||||
|
<Copy size={11} />
|
||||||
|
Copy
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-xs text-[var(--text-tertiary)]">
|
||||||
|
Shown once - store it now. Use with <span className="mono">containr auth login --token</span> or as a Bearer token.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{createMutation.isError ? (
|
||||||
|
<p className="text-xs text-[var(--error)]">
|
||||||
|
{createMutation.error instanceof Error ? createMutation.error.message : 'Failed to create token'}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{tokensQuery.isLoading ? (
|
||||||
|
<div className="py-4 text-center">
|
||||||
|
<Loader2 size={16} className="animate-spin mx-auto text-[var(--text-tertiary)]" />
|
||||||
|
</div>
|
||||||
|
) : tokens.length === 0 ? (
|
||||||
|
<p className="text-xs text-[var(--text-tertiary)]">No tokens yet. Create one to connect the CLI or an agent.</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-1.5 border-t border-[var(--border-subtle)] pt-3">
|
||||||
|
{tokens.map((token) => (
|
||||||
|
<div key={token.id} className="flex items-center justify-between gap-2 text-xs">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<span className="text-[var(--text-primary)]">{token.name}</span>
|
||||||
|
<span className="ml-2 mono text-[var(--text-muted)]">{token.key_prefix}…</span>
|
||||||
|
<span className="ml-2 rounded px-1.5 py-0.5 bg-[var(--surface-muted)] text-[var(--text-secondary)]">{token.scope}</span>
|
||||||
|
<span className="ml-2 text-[var(--text-muted)]">
|
||||||
|
{token.last_used_at ? `used ${formatRelative(token.last_used_at)}` : 'unused'}
|
||||||
|
{token.expires_at ? ` · expires ${formatRelative(token.expires_at)}` : ''}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
if (window.confirm(`Revoke token "${token.name}"? Clients using it lose access immediately.`)) {
|
||||||
|
revokeMutation.mutate(token.id ?? '');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={revokeMutation.isPending}
|
||||||
|
className="text-[var(--error)] hover:underline disabled:opacity-50 shrink-0"
|
||||||
|
>
|
||||||
|
Revoke
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function SettingsPage() {
|
export function SettingsPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
@@ -1438,6 +1601,9 @@ export function SettingsPage() {
|
|||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
{/* Personal Access Tokens */}
|
||||||
|
<UserTokensSection isAdmin={profileQuery.data?.isAdmin ?? false} />
|
||||||
|
|
||||||
{/* Platform Settings - owner only */}
|
{/* Platform Settings - owner only */}
|
||||||
{profileQuery.data?.isAdmin ? <PlatformSettingsSection /> : null}
|
{profileQuery.data?.isAdmin ? <PlatformSettingsSection /> : null}
|
||||||
|
|
||||||
|
|||||||
@@ -972,31 +972,60 @@ export function ServiceDetailPage() {
|
|||||||
<p className="text-sm font-medium text-[var(--text-primary)]">Networking</p>
|
<p className="text-sm font-medium text-[var(--text-primary)]">Networking</p>
|
||||||
<p className="text-xs text-[var(--text-tertiary)]">Public endpoints and ports</p>
|
<p className="text-xs text-[var(--text-tertiary)]">Public endpoints and ports</p>
|
||||||
</div>
|
</div>
|
||||||
|
{runtimeQuery.data?.health === 'healthy' && (
|
||||||
|
<span className="ml-auto v-st v-st-ok">HEALTHY</span>
|
||||||
|
)}
|
||||||
|
{runtimeQuery.data?.health === 'unhealthy' && (
|
||||||
|
<span className="ml-auto v-st v-st-fail">UNHEALTHY</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
{service.domain && (
|
||||||
<div className="flex items-center justify-between p-3 rounded-lg bg-[var(--surface-muted)] border border-[var(--border-subtle)]">
|
<div className="flex items-center justify-between p-3 rounded-lg bg-[var(--surface-muted)] border border-[var(--border-subtle)]">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="w-2 h-2 rounded-full bg-[var(--success)]" />
|
<div className="w-2 h-2 rounded-full bg-[var(--success)]" />
|
||||||
<span className="text-xs text-[var(--text-secondary)]">HTTPS</span>
|
<span className="text-xs text-[var(--text-secondary)]">Domain</span>
|
||||||
</div>
|
</div>
|
||||||
<a
|
<a
|
||||||
href={`https://${service.name}.containr.dev`}
|
href={`https://${service.domain}`}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="mono text-xs text-[var(--accent-primary)] hover:underline"
|
className="mono text-xs text-[var(--accent-primary)] hover:underline"
|
||||||
>
|
>
|
||||||
{service.name}.containr.dev
|
{service.domain}
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
{(runtimeQuery.data?.urls ?? []).map((url) => (
|
||||||
|
<div key={url} className="flex items-center justify-between p-3 rounded-lg bg-[var(--surface-muted)] border border-[var(--border-subtle)]">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="w-2 h-2 rounded-full bg-[var(--success)]" />
|
||||||
|
<span className="text-xs text-[var(--text-secondary)]">HTTP</span>
|
||||||
|
</div>
|
||||||
|
<a
|
||||||
|
href={url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="mono text-xs text-[var(--accent-primary)] hover:underline"
|
||||||
|
>
|
||||||
|
{url.replace(/^https?:\/\//, '')}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
<div className="flex items-center justify-between p-3 rounded-lg bg-[var(--surface-muted)] border border-[var(--border-subtle)]">
|
<div className="flex items-center justify-between p-3 rounded-lg bg-[var(--surface-muted)] border border-[var(--border-subtle)]">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="w-2 h-2 rounded-full bg-[var(--accent-secondary)]" />
|
<div className="w-2 h-2 rounded-full bg-[var(--accent-secondary)]" />
|
||||||
<span className="text-xs text-[var(--text-secondary)]">Port</span>
|
<span className="text-xs text-[var(--text-secondary)]">Internal</span>
|
||||||
</div>
|
</div>
|
||||||
<span className="mono text-xs text-[var(--text-primary)]">8080 → 443</span>
|
<span className="mono text-xs text-[var(--text-primary)]">{service.name}{service.port ? `:${service.port}` : ''}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{!service.domain && (runtimeQuery.data?.urls ?? []).length === 0 && (
|
||||||
|
<p className="mt-3 text-xs text-[var(--text-tertiary)]">
|
||||||
|
No public endpoint. Publish a port or set a domain in Settings → Networking to expose this service.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1099,6 +1099,7 @@ function CanvasInner({ projectId, services, variablesByService, onAddService, on
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{!readOnly && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => addGroup()}
|
onClick={() => addGroup()}
|
||||||
@@ -1108,6 +1109,7 @@ function CanvasInner({ projectId, services, variablesByService, onAddService, on
|
|||||||
<Layers size={13} />
|
<Layers size={13} />
|
||||||
Group
|
Group
|
||||||
</button>
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Floating: zoom controls (bottom-left) */}
|
{/* Floating: zoom controls (bottom-left) */}
|
||||||
@@ -1170,6 +1172,7 @@ function CanvasInner({ projectId, services, variablesByService, onAddService, on
|
|||||||
Add a service from a git repo or Docker image - it runs on a private network with the rest of this
|
Add a service from a git repo or Docker image - it runs on a private network with the rest of this
|
||||||
project.
|
project.
|
||||||
</p>
|
</p>
|
||||||
|
{!readOnly && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onAddService}
|
onClick={onAddService}
|
||||||
@@ -1179,6 +1182,7 @@ function CanvasInner({ projectId, services, variablesByService, onAddService, on
|
|||||||
<Plus size={15} />
|
<Plus size={15} />
|
||||||
Add Service
|
Add Service
|
||||||
</button>
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -1190,6 +1194,8 @@ function CanvasInner({ projectId, services, variablesByService, onAddService, on
|
|||||||
style={{ left: contextMenu.x, top: contextMenu.y }}
|
style={{ left: contextMenu.x, top: contextMenu.y }}
|
||||||
>
|
>
|
||||||
{contextMenu.kind === 'pane' && (
|
{contextMenu.kind === 'pane' && (
|
||||||
|
<>
|
||||||
|
{!readOnly && (
|
||||||
<>
|
<>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -1217,6 +1223,8 @@ function CanvasInner({ projectId, services, variablesByService, onAddService, on
|
|||||||
<Layers size={13} />
|
<Layers size={13} />
|
||||||
Add group here
|
Add group here
|
||||||
</button>
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
<div className="border-t border-[var(--border-subtle)] mt-1 pt-1">
|
<div className="border-t border-[var(--border-subtle)] mt-1 pt-1">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -719,7 +719,7 @@ export function ProjectWorkspacePage() {
|
|||||||
<Search size={12} />
|
<Search size={12} />
|
||||||
<kbd className="px-1 py-0.5 rounded bg-[var(--surface-card)] text-[10px] font-mono">⌘K</kbd>
|
<kbd className="px-1 py-0.5 rounded bg-[var(--surface-card)] text-[10px] font-mono">⌘K</kbd>
|
||||||
</button>
|
</button>
|
||||||
{!isDemoMode && (
|
{!isDemoMode && signedIn && (
|
||||||
<button
|
<button
|
||||||
onClick={openAddService}
|
onClick={openAddService}
|
||||||
className="flex items-center gap-1.5 h-8 px-3 rounded-[var(--radius-md)] text-[var(--accent-on)] text-xs font-semibold shadow-lg hover:shadow-xl transition-all"
|
className="flex items-center gap-1.5 h-8 px-3 rounded-[var(--radius-md)] text-[var(--accent-on)] text-xs font-semibold shadow-lg hover:shadow-xl transition-all"
|
||||||
@@ -742,7 +742,7 @@ export function ProjectWorkspacePage() {
|
|||||||
onAddService={openAddService}
|
onAddService={openAddService}
|
||||||
onOpenService={(serviceId) => navigate(serviceHref(serviceId))}
|
onOpenService={(serviceId) => navigate(serviceHref(serviceId))}
|
||||||
onOpenSection={(serviceId, section) => navigate(serviceSectionHref(serviceId, section))}
|
onOpenSection={(serviceId, section) => navigate(serviceSectionHref(serviceId, section))}
|
||||||
readOnly={isDemoMode}
|
readOnly={isDemoMode || !signedIn}
|
||||||
/>
|
/>
|
||||||
{isDemoMode && (
|
{isDemoMode && (
|
||||||
<div className="absolute top-4 left-1/2 -translate-x-1/2 pointer-events-none">
|
<div className="absolute top-4 left-1/2 -translate-x-1/2 pointer-events-none">
|
||||||
|
|||||||
@@ -231,6 +231,153 @@ export interface paths {
|
|||||||
patch?: never;
|
patch?: never;
|
||||||
trace?: never;
|
trace?: never;
|
||||||
};
|
};
|
||||||
|
"/user/tokens": {
|
||||||
|
parameters: {
|
||||||
|
query?: never;
|
||||||
|
header?: never;
|
||||||
|
path?: never;
|
||||||
|
cookie?: never;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* List personal access tokens
|
||||||
|
* @description Returns the caller's non-revoked personal access token metadata. Token values and hashes are never returned.
|
||||||
|
*/
|
||||||
|
get: {
|
||||||
|
parameters: {
|
||||||
|
query?: never;
|
||||||
|
header?: never;
|
||||||
|
path?: never;
|
||||||
|
cookie?: never;
|
||||||
|
};
|
||||||
|
requestBody?: never;
|
||||||
|
responses: {
|
||||||
|
/** @description Token list */
|
||||||
|
200: {
|
||||||
|
headers: {
|
||||||
|
[name: string]: unknown;
|
||||||
|
};
|
||||||
|
content: {
|
||||||
|
"application/json": {
|
||||||
|
tokens?: components["schemas"]["UserToken"][];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
/** @description Unauthorized */
|
||||||
|
401: {
|
||||||
|
headers: {
|
||||||
|
[name: string]: unknown;
|
||||||
|
};
|
||||||
|
content: {
|
||||||
|
"application/json": components["schemas"]["Error"];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
put?: never;
|
||||||
|
/**
|
||||||
|
* Create personal access token
|
||||||
|
* @description Issues a `cnp_` bearer token for CLI/MCP/agent authentication. The raw token is returned exactly once and never stored — only its SHA-256 hash persists. Admin-scope tokens require a platform admin account.
|
||||||
|
*/
|
||||||
|
post: {
|
||||||
|
parameters: {
|
||||||
|
query?: never;
|
||||||
|
header?: never;
|
||||||
|
path?: never;
|
||||||
|
cookie?: never;
|
||||||
|
};
|
||||||
|
requestBody: {
|
||||||
|
content: {
|
||||||
|
"application/json": components["schemas"]["CreateUserTokenRequest"];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
responses: {
|
||||||
|
/** @description Token created; raw value returned once */
|
||||||
|
201: {
|
||||||
|
headers: {
|
||||||
|
[name: string]: unknown;
|
||||||
|
};
|
||||||
|
content: {
|
||||||
|
"application/json": components["schemas"]["UserTokenCreated"];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
/** @description Invalid input */
|
||||||
|
400: {
|
||||||
|
headers: {
|
||||||
|
[name: string]: unknown;
|
||||||
|
};
|
||||||
|
content: {
|
||||||
|
"application/json": components["schemas"]["Error"];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
/** @description Admin scope requires platform admin */
|
||||||
|
403: {
|
||||||
|
headers: {
|
||||||
|
[name: string]: unknown;
|
||||||
|
};
|
||||||
|
content: {
|
||||||
|
"application/json": components["schemas"]["Error"];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
delete?: never;
|
||||||
|
options?: never;
|
||||||
|
head?: never;
|
||||||
|
patch?: never;
|
||||||
|
trace?: never;
|
||||||
|
};
|
||||||
|
"/user/tokens/{id}": {
|
||||||
|
parameters: {
|
||||||
|
query?: never;
|
||||||
|
header?: never;
|
||||||
|
path?: never;
|
||||||
|
cookie?: never;
|
||||||
|
};
|
||||||
|
get?: never;
|
||||||
|
put?: never;
|
||||||
|
post?: never;
|
||||||
|
/**
|
||||||
|
* Revoke personal access token
|
||||||
|
* @description Marks one of the caller's tokens as revoked. Clients presenting it are rejected from then on.
|
||||||
|
*/
|
||||||
|
delete: {
|
||||||
|
parameters: {
|
||||||
|
query?: never;
|
||||||
|
header?: never;
|
||||||
|
path: {
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
|
cookie?: never;
|
||||||
|
};
|
||||||
|
requestBody?: never;
|
||||||
|
responses: {
|
||||||
|
/** @description Token revoked */
|
||||||
|
200: {
|
||||||
|
headers: {
|
||||||
|
[name: string]: unknown;
|
||||||
|
};
|
||||||
|
content: {
|
||||||
|
"application/json": {
|
||||||
|
message?: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
/** @description Token not found */
|
||||||
|
404: {
|
||||||
|
headers: {
|
||||||
|
[name: string]: unknown;
|
||||||
|
};
|
||||||
|
content: {
|
||||||
|
"application/json": components["schemas"]["Error"];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
options?: never;
|
||||||
|
head?: never;
|
||||||
|
patch?: never;
|
||||||
|
trace?: never;
|
||||||
|
};
|
||||||
"/projects": {
|
"/projects": {
|
||||||
parameters: {
|
parameters: {
|
||||||
query?: never;
|
query?: never;
|
||||||
@@ -637,7 +784,15 @@ export interface paths {
|
|||||||
desired?: number;
|
desired?: number;
|
||||||
/** @enum {string} */
|
/** @enum {string} */
|
||||||
status?: "running" | "degraded" | "stopped";
|
status?: "running" | "degraded" | "stopped";
|
||||||
|
/** @description Reachable service URLs; rewritten to the request Host for remote clients. Null/empty when nothing is published. */
|
||||||
urls?: string[];
|
urls?: string[];
|
||||||
|
/** @description Host ports actually bound for replica 0+; persisted on the service so restarts reuse the same public port. Null/empty when nothing is published. */
|
||||||
|
ports?: number[];
|
||||||
|
/**
|
||||||
|
* @description Result of the backend's HTTP probe of the service on its project network. Omitted when the service declares no healthcheck path.
|
||||||
|
* @enum {string}
|
||||||
|
*/
|
||||||
|
health?: "healthy" | "unhealthy" | "unreachable";
|
||||||
containers?: {
|
containers?: {
|
||||||
id?: string;
|
id?: string;
|
||||||
name?: string;
|
name?: string;
|
||||||
@@ -8299,7 +8454,13 @@ export interface components {
|
|||||||
images?: number;
|
images?: number;
|
||||||
driver?: string;
|
driver?: string;
|
||||||
server?: string;
|
server?: string;
|
||||||
|
os?: string;
|
||||||
};
|
};
|
||||||
|
/**
|
||||||
|
* @description What the telemetry measures — `host` for a native daemon, `docker-desktop-vm` when Docker runs inside a Desktop VM.
|
||||||
|
* @enum {string}
|
||||||
|
*/
|
||||||
|
scope?: "host" | "docker-desktop-vm";
|
||||||
/** Format: date-time */
|
/** Format: date-time */
|
||||||
collected_at?: string;
|
collected_at?: string;
|
||||||
};
|
};
|
||||||
@@ -8462,6 +8623,37 @@ export interface components {
|
|||||||
/** @description Human-readable label for the token (e.g. node name) */
|
/** @description Human-readable label for the token (e.g. node name) */
|
||||||
label?: string;
|
label?: string;
|
||||||
};
|
};
|
||||||
|
UserToken: {
|
||||||
|
/** Format: uuid */
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
/** @description First 12 chars of the token, for identification in lists */
|
||||||
|
key_prefix: string;
|
||||||
|
/** @enum {string} */
|
||||||
|
scope: "read" | "write" | "admin";
|
||||||
|
/** Format: date-time */
|
||||||
|
expires_at?: string;
|
||||||
|
/** Format: date-time */
|
||||||
|
last_used_at?: string;
|
||||||
|
/** Format: date-time */
|
||||||
|
created_at: string;
|
||||||
|
};
|
||||||
|
UserTokenCreated: components["schemas"]["UserToken"] & {
|
||||||
|
/** @description Raw cnp_ token value, returned exactly once at creation */
|
||||||
|
token: string;
|
||||||
|
};
|
||||||
|
CreateUserTokenRequest: {
|
||||||
|
/** @description Human-readable label (e.g. "laptop cli", "ci deploy") */
|
||||||
|
name: string;
|
||||||
|
/**
|
||||||
|
* @description read = GET/HEAD only; write = all non-admin routes; admin = everything (requires admin account)
|
||||||
|
* @default write
|
||||||
|
* @enum {string}
|
||||||
|
*/
|
||||||
|
scope: "read" | "write" | "admin";
|
||||||
|
/** @description 0 or omitted = never expires */
|
||||||
|
expires_in_days?: number;
|
||||||
|
};
|
||||||
AgentCapabilities: {
|
AgentCapabilities: {
|
||||||
container_runtimes?: string[];
|
container_runtimes?: string[];
|
||||||
supported_architectures?: string[];
|
supported_architectures?: string[];
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ export const bundledDocs: BundledDoc[] = [
|
|||||||
"path": "guides/OPERATIONS.md",
|
"path": "guides/OPERATIONS.md",
|
||||||
"section": "guides",
|
"section": "guides",
|
||||||
"title": "Operations",
|
"title": "Operations",
|
||||||
"markdown": "# Operations\n\nDay-2 features for running services: scheduled jobs, ad-hoc exec, managed\ndatabases, preview environments, security scans, and high availability.\n\n## Cron jobs\n\nService detail → **Cron**. Standard 5-field cron expressions (`robfig/cron`\nsyntax), per-job timezone, enable/disable, manual trigger, and execution\nhistory with captured stdout/stderr.\n\n- The scheduler ticks every minute and runs due jobs via `docker exec`\n (`sh -c <command>`) inside the service's container.\n- Executions are retained per-job (`retention` count) and visible in the UI.\n- Requires a running container — a stopped service's due job records a\n failure, it does not queue.\n\n```\nGET/POST /api/v1/cron-jobs PUT/DELETE /api/v1/cron-jobs/:id\nPOST /api/v1/cron-jobs/:id/trigger\nGET /api/v1/cron-jobs/:id/executions\n```\n\n## Exec console\n\nService detail → **Console**. One-off `sh -c` commands against the running\ncontainer: 30s ceiling, 64KB output cap, exit code + captured output shown\nper run. Debugging aid — not an interactive shell.\n\n```\nPOST /api/v1/services/:id/exec {command}\n```\n\n## Managed databases\n\n**/databases** page — provision PostgreSQL/Redis/MySQL/MariaDB/MongoDB/\nClickHouse/Dragonfly as managed containers on the `containr` network.\n\n- Start/stop/restart actions; connection URL with copy.\n- **Backups**: manual snapshot now, or set a cron expression\n (`backup_schedule`) — due backups run inside the same scheduler tick as\n cron jobs. Archives live in the `containr-db-backups` volume and are\n downloadable (`GET /databases/:id/backups/:bid/download`) and restorable.\n- **Bind to service**: injects `connection_url` into a service's variables\n as a secret (`DATABASE_URL` by default). Redeploy the service afterward —\n variables are read at deploy time.\n\n## Preview environments\n\nService detail → **Previews**. Create a preview per branch/PR with a TTL,\npromote it to production, or delete it.\n\nCurrent limitation: previews are bookkeeping records — they do not build,\ndeploy, or route a real container. The generated `*.preview.containr.local`\nURL is a placeholder. Real preview runtime is tracked on the roadmap.\n\n## Security scans\n\n**/security** page — pick a project, run a scan (dependency / configuration\n/ comprehensive, optionally scoped to one service).\n\nThe scanner is heuristic config analysis, not Trivy/Grype: it flags\nunpinned image tags, `http://` source/public URLs, `npm install` without\n`npm ci`, `pip install` without hashes, `curl|sh` build steps, missing\nhealth checks, and similar smells. Findings get severity badges and can be\nresolved or ignored; the page also shows a security score, open/resolved\ncounts, scan history, and compliance status.\n\n```\nPOST /api/v1/security/scans {project_id, service_id?, scan_type}\nGET /api/v1/projects/:id/vulnerabilities\nPUT /api/v1/vulnerabilities/:id {status: open|resolved|ignored}\nGET /api/v1/projects/:id/security/metrics\nGET /api/v1/projects/:id/security/history\n```\n\n## High availability\n\n**/ha** page — manager enable/disable, node/health-check/alert status\ncards, manual failover (with confirmation), per-service failover policies\n(project → service picker, strategy, min healthy nodes, max failures),\nactive alerts with resolve, and health check results.\n\nHA state is in-memory like autoscaling — policies and alerts reset on\nbackend restart.\n\n## Node agents\n\n**/usage** page → *Connect node*: issue a per-node token (`cagt_…`, shown\nonce), copy the prefilled install command, revoke tokens when done. Agents\nregister over `POST /api/agents/register` and heartbeat via\n`POST /api/agents/heartbeat`.\n"
|
"markdown": "# Operations\n\nDay-2 features for running services: scheduled jobs, ad-hoc exec, managed\ndatabases, preview environments, security scans, and high availability.\n\n## Cron jobs\n\nService detail → **Cron**. Standard 5-field cron expressions (`robfig/cron`\nsyntax), per-job timezone, enable/disable, manual trigger, and execution\nhistory with captured stdout/stderr.\n\n- The scheduler ticks every minute and runs due jobs via `docker exec`\n (`sh -c <command>`) inside the service's container.\n- Executions are retained per-job (`retention` count) and visible in the UI.\n- Requires a running container — a stopped service's due job records a\n failure, it does not queue.\n\n```\nGET/POST /api/v1/cron-jobs PUT/DELETE /api/v1/cron-jobs/:id\nPOST /api/v1/cron-jobs/:id/trigger\nGET /api/v1/cron-jobs/:id/executions\n```\n\n## Exec console\n\nService detail → **Console**. One-off `sh -c` commands against the running\ncontainer: 30s ceiling, 64KB output cap, exit code + captured output shown\nper run. Debugging aid — not an interactive shell.\n\n```\nPOST /api/v1/services/:id/exec {command}\n```\n\n## Managed databases\n\n**/databases** page — provision PostgreSQL/Redis/MySQL/MariaDB/MongoDB/\nClickHouse/Dragonfly as managed containers on the `containr` network.\n\n- Start/stop/restart actions; connection URL with copy.\n- **Backups**: manual snapshot now, or set a cron expression\n (`backup_schedule`) — due backups run inside the same scheduler tick as\n cron jobs. Archives live in the `containr-db-backups` volume and are\n downloadable (`GET /databases/:id/backups/:bid/download`) and restorable.\n- **Bind to service**: injects `connection_url` into a service's variables\n as a secret (`DATABASE_URL` by default). Redeploy the service afterward —\n variables are read at deploy time.\n\n## Preview environments\n\nService detail → **Previews**. Create a preview per branch/PR with a TTL,\npromote it to production, or delete it.\n\nCurrent limitation: previews are bookkeeping records — they do not build,\ndeploy, or route a real container. The generated `*.preview.containr.local`\nURL is a placeholder. Real preview runtime is tracked on the roadmap.\n\n## Security scans\n\n**/security** page — pick a project, run a scan (dependency / configuration\n/ comprehensive, optionally scoped to one service).\n\nThe scanner is heuristic config analysis, not Trivy/Grype: it flags\nunpinned image tags, `http://` source/public URLs, `npm install` without\n`npm ci`, `pip install` without hashes, `curl|sh` build steps, missing\nhealth checks, and similar smells. Findings get severity badges and can be\nresolved or ignored; the page also shows a security score, open/resolved\ncounts, scan history, and compliance status.\n\n```\nPOST /api/v1/security/scans {project_id, service_id?, scan_type}\nGET /api/v1/projects/:id/vulnerabilities\nPUT /api/v1/vulnerabilities/:id {status: open|resolved|ignored}\nGET /api/v1/projects/:id/security/metrics\nGET /api/v1/projects/:id/security/history\n```\n\n## High availability\n\n**/ha** page — manager enable/disable, node/health-check/alert status\ncards, manual failover (with confirmation), per-service failover policies\n(project → service picker, strategy, min healthy nodes, max failures),\nactive alerts with resolve, and health check results.\n\nHA state is in-memory like autoscaling — policies and alerts reset on\nbackend restart.\n\n## Node agents\n\n**/usage** page → *Connect node*: issue a per-node token (`cagt_…`, shown\nonce), copy the prefilled install command, revoke tokens when done. Agents\nregister over `POST /api/agents/register` and heartbeat via\n`POST /api/agents/heartbeat`.\n\n## Personal access tokens\n\n**Settings → Personal Access Tokens**: issue `cnp_…` bearer tokens for the\nCLI, MCP server, and scripts — the same privileges as your account, bounded\nby scope. The raw token is shown once at creation; only its SHA-256 hash is\nstored.\n\nScopes:\n\n- `read` — `GET`/`HEAD`/`OPTIONS` only; mutations return `403 SCOPE_INSUFFICIENT`.\n- `write` — everything except admin routes.\n- `admin` — full access; requires a platform admin account, and the token is\n still capped at the owner's privileges.\n\nA token can never outrank its owner: non-admin scopes report\n`is_admin = false` even on admin accounts.\n\n```\nGET /api/v1/user/tokens list (metadata only, never hashes)\nPOST /api/v1/user/tokens {name, scope?, expires_in_days?} → raw token once\nDELETE /api/v1/user/tokens/:id revoke (owner-scoped)\n```\n\nUse as `Authorization: Bearer cnp_…`, or `containr auth login cnp_…`.\nRevocation takes effect on the next request; `last_used_at` updates on each\nauthenticated call.\n"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"path": "guides/README_BACKEND.md",
|
"path": "guides/README_BACKEND.md",
|
||||||
|
|||||||
@@ -1523,6 +1523,7 @@ textarea {
|
|||||||
background: var(--accent-primary); color: var(--accent-on);
|
background: var(--accent-primary); color: var(--accent-on);
|
||||||
border: none; border-radius: 8px; padding: 9px 17px;
|
border: none; border-radius: 8px; padding: 9px 17px;
|
||||||
font: 700 12px 'JetBrains Mono', monospace; cursor: pointer;
|
font: 700 12px 'JetBrains Mono', monospace; cursor: pointer;
|
||||||
|
white-space: nowrap; flex-shrink: 0;
|
||||||
transition: background 0.15s, transform 0.15s;
|
transition: background 0.15s, transform 0.15s;
|
||||||
box-shadow: 0 2px 12px rgba(180, 227, 74, 0.22);
|
box-shadow: 0 2px 12px rgba(180, 227, 74, 0.22);
|
||||||
}
|
}
|
||||||
@@ -1534,6 +1535,7 @@ textarea {
|
|||||||
background: var(--surface-card); color: var(--text-secondary);
|
background: var(--surface-card); color: var(--text-secondary);
|
||||||
border: 1px solid var(--border-subtle); border-radius: 8px; padding: 8px 16px;
|
border: 1px solid var(--border-subtle); border-radius: 8px; padding: 8px 16px;
|
||||||
font: 600 12px 'JetBrains Mono', monospace; cursor: pointer; transition: 0.15s;
|
font: 600 12px 'JetBrains Mono', monospace; cursor: pointer; transition: 0.15s;
|
||||||
|
white-space: nowrap; flex-shrink: 0;
|
||||||
}
|
}
|
||||||
.v-btn-ghost:hover { color: var(--text-primary); border-color: var(--border-default); }
|
.v-btn-ghost:hover { color: var(--text-primary); border-color: var(--border-default); }
|
||||||
|
|
||||||
|
|||||||
@@ -68,6 +68,8 @@ export type ServiceRuntime = {
|
|||||||
desired: number;
|
desired: number;
|
||||||
status: 'running' | 'degraded' | 'stopped';
|
status: 'running' | 'degraded' | 'stopped';
|
||||||
urls: string[];
|
urls: string[];
|
||||||
|
ports: number[];
|
||||||
|
health?: 'healthy' | 'unhealthy' | 'unreachable' | '';
|
||||||
containers: RuntimeContainer[];
|
containers: RuntimeContainer[];
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -223,7 +225,9 @@ export type HostMonitoring = {
|
|||||||
images?: number;
|
images?: number;
|
||||||
driver?: string;
|
driver?: string;
|
||||||
server?: string;
|
server?: string;
|
||||||
|
os?: string;
|
||||||
};
|
};
|
||||||
|
scope: 'host' | 'docker-desktop-vm';
|
||||||
collectedAt: string;
|
collectedAt: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -886,6 +890,7 @@ function normalizeHostMonitoring(payload: RawHostMonitoring): HostMonitoring {
|
|||||||
uptimeSeconds: payload.uptime_seconds ?? 0,
|
uptimeSeconds: payload.uptime_seconds ?? 0,
|
||||||
dockerAvailable: Boolean(payload.docker_available),
|
dockerAvailable: Boolean(payload.docker_available),
|
||||||
docker: payload.docker,
|
docker: payload.docker,
|
||||||
|
scope: payload.scope === 'docker-desktop-vm' ? 'docker-desktop-vm' : 'host',
|
||||||
collectedAt: payload.collected_at ?? '',
|
collectedAt: payload.collected_at ?? '',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -988,6 +993,34 @@ export async function revokeAgentToken(id: string): Promise<void> {
|
|||||||
await requestJson(`/agent-tokens/${id}`, { method: 'DELETE' });
|
await requestJson(`/agent-tokens/${id}`, { method: 'DELETE' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type UserToken = components['schemas']['UserToken'];
|
||||||
|
export type UserTokenCreated = components['schemas']['UserTokenCreated'];
|
||||||
|
export type UserTokenScope = 'read' | 'write' | 'admin';
|
||||||
|
|
||||||
|
export async function createUserToken(input: {
|
||||||
|
name: string;
|
||||||
|
scope?: UserTokenScope;
|
||||||
|
expiresInDays?: number;
|
||||||
|
}): Promise<UserTokenCreated> {
|
||||||
|
return requestJson<UserTokenCreated>(`/user/tokens`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
name: input.name,
|
||||||
|
scope: input.scope ?? 'write',
|
||||||
|
expires_in_days: input.expiresInDays ?? 0,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listUserTokens(): Promise<UserToken[]> {
|
||||||
|
const payload = await requestJson<{ tokens?: UserToken[] }>(`/user/tokens`);
|
||||||
|
return payload.tokens ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function revokeUserToken(id: string): Promise<void> {
|
||||||
|
await requestJson(`/user/tokens/${id}`, { method: 'DELETE' });
|
||||||
|
}
|
||||||
|
|
||||||
export async function createProject(input: CreateProjectInput): Promise<ProjectEntity> {
|
export async function createProject(input: CreateProjectInput): Promise<ProjectEntity> {
|
||||||
const payload = await requestJson<RawProject | { project?: RawProject }>(`/projects`, {
|
const payload = await requestJson<RawProject | { project?: RawProject }>(`/projects`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -1080,16 +1113,15 @@ export async function deleteService(serviceId: string): Promise<void> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function normalizeRuntime(runtime?: ServiceRuntime): ServiceRuntime {
|
||||||
|
const state = runtime ?? { desired: 0, status: 'stopped' as const, urls: [], ports: [], containers: [] };
|
||||||
|
// The API emits null (not []) for empty collections — coerce at the boundary.
|
||||||
|
return { ...state, urls: state.urls ?? [], ports: state.ports ?? [], containers: state.containers ?? [] };
|
||||||
|
}
|
||||||
|
|
||||||
export async function getServiceRuntime(serviceId: string): Promise<ServiceRuntime> {
|
export async function getServiceRuntime(serviceId: string): Promise<ServiceRuntime> {
|
||||||
const payload = await requestJson<{ runtime?: ServiceRuntime }>(`/services/${serviceId}/runtime`);
|
const payload = await requestJson<{ runtime?: ServiceRuntime }>(`/services/${serviceId}/runtime`);
|
||||||
return (
|
return normalizeRuntime(payload.runtime);
|
||||||
payload.runtime ?? {
|
|
||||||
desired: 0,
|
|
||||||
status: 'stopped',
|
|
||||||
urls: [],
|
|
||||||
containers: [],
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function serviceAction(serviceId: string, action: 'start' | 'stop' | 'restart'): Promise<void> {
|
async function serviceAction(serviceId: string, action: 'start' | 'stop' | 'restart'): Promise<void> {
|
||||||
@@ -1104,7 +1136,7 @@ export async function redeployService(serviceId: string): Promise<ServiceRuntime
|
|||||||
const payload = await requestJson<{ runtime?: ServiceRuntime }>(`/services/${serviceId}/redeploy`, {
|
const payload = await requestJson<{ runtime?: ServiceRuntime }>(`/services/${serviceId}/redeploy`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
});
|
});
|
||||||
return payload.runtime ?? { desired: 0, status: 'stopped', urls: [], containers: [] };
|
return normalizeRuntime(payload.runtime);
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeServiceVariables(rows: RawServiceVariable[] | undefined): ServiceVariable[] {
|
function normalizeServiceVariables(rows: RawServiceVariable[] | undefined): ServiceVariable[] {
|
||||||
|
|||||||
@@ -456,6 +456,7 @@ export const demoHostMonitoring: HostMonitoring = {
|
|||||||
uptimeSeconds: 1_828_800,
|
uptimeSeconds: 1_828_800,
|
||||||
dockerAvailable: true,
|
dockerAvailable: true,
|
||||||
docker: { containers: 11, images: 34, driver: 'overlay2', server: '27.3.1' },
|
docker: { containers: 11, images: 34, driver: 'overlay2', server: '27.3.1' },
|
||||||
|
scope: 'host',
|
||||||
collectedAt: new Date().toISOString(),
|
collectedAt: new Date().toISOString(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Vendored
-2
@@ -1,2 +0,0 @@
|
|||||||
declare const _default: import("vite").UserConfig;
|
|
||||||
export default _default;
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
import { defineConfig } from 'vite';
|
|
||||||
import react from '@vitejs/plugin-react';
|
|
||||||
import path from 'path';
|
|
||||||
// https://vite.dev/config/
|
|
||||||
export default defineConfig({
|
|
||||||
plugins: [react()],
|
|
||||||
resolve: {
|
|
||||||
alias: {
|
|
||||||
"@": path.resolve(__dirname, "./src"),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
build: {
|
|
||||||
// Enable code splitting and optimization
|
|
||||||
rollupOptions: {
|
|
||||||
output: {
|
|
||||||
manualChunks: {
|
|
||||||
// Split vendor libraries
|
|
||||||
vendor: ['react', 'react-dom', '@tanstack/react-query'],
|
|
||||||
ui: ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu', 'lucide-react'],
|
|
||||||
utils: ['date-fns', 'clsx', 'tailwind-merge']
|
|
||||||
},
|
|
||||||
// Optimize chunk naming for better caching
|
|
||||||
chunkFileNames: 'assets/js/[name]-[hash].js',
|
|
||||||
entryFileNames: 'assets/js/[name]-[hash].js',
|
|
||||||
assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
// Enable source maps for production debugging
|
|
||||||
sourcemap: true,
|
|
||||||
// Optimize bundle size
|
|
||||||
minify: 'terser',
|
|
||||||
// Set appropriate chunk size limit for better caching
|
|
||||||
chunkSizeWarningLimit: 1000
|
|
||||||
},
|
|
||||||
// Optimize dependencies during build
|
|
||||||
optimizeDeps: {
|
|
||||||
include: ['react', 'react-dom', '@tanstack/react-query', 'date-fns']
|
|
||||||
},
|
|
||||||
// Development server optimization
|
|
||||||
server: {
|
|
||||||
fs: {
|
|
||||||
// Allow serving files from project root
|
|
||||||
allow: ['..']
|
|
||||||
}
|
|
||||||
},
|
|
||||||
// Preview server optimization
|
|
||||||
preview: {
|
|
||||||
port: 4173,
|
|
||||||
strictPort: true
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -30,7 +30,9 @@ export default defineConfig({
|
|||||||
// Split vendor libraries
|
// Split vendor libraries
|
||||||
vendor: ['react', 'react-dom', '@tanstack/react-query'],
|
vendor: ['react', 'react-dom', '@tanstack/react-query'],
|
||||||
ui: ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu', 'lucide-react'],
|
ui: ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu', 'lucide-react'],
|
||||||
utils: ['date-fns', 'clsx', 'tailwind-merge']
|
utils: ['date-fns', 'clsx', 'tailwind-merge'],
|
||||||
|
canvas: ['@xyflow/react'],
|
||||||
|
charts: ['recharts']
|
||||||
},
|
},
|
||||||
// Optimize chunk naming for better caching
|
// Optimize chunk naming for better caching
|
||||||
chunkFileNames: 'assets/js/[name]-[hash].js',
|
chunkFileNames: 'assets/js/[name]-[hash].js',
|
||||||
|
|||||||
@@ -152,6 +152,97 @@ paths:
|
|||||||
schema:
|
schema:
|
||||||
$ref: '#/components/schemas/Error'
|
$ref: '#/components/schemas/Error'
|
||||||
|
|
||||||
|
/user/tokens:
|
||||||
|
get:
|
||||||
|
tags:
|
||||||
|
- User
|
||||||
|
summary: List personal access tokens
|
||||||
|
description: Returns the caller's non-revoked personal access token metadata. Token values and hashes are never returned.
|
||||||
|
security:
|
||||||
|
- bearerAuth: []
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Token list
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
tokens:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
$ref: '#/components/schemas/UserToken'
|
||||||
|
'401':
|
||||||
|
description: Unauthorized
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/Error'
|
||||||
|
post:
|
||||||
|
tags:
|
||||||
|
- User
|
||||||
|
summary: Create personal access token
|
||||||
|
description: Issues a `cnp_` bearer token for CLI/MCP/agent authentication. The raw token is returned exactly once and never stored — only its SHA-256 hash persists. Admin-scope tokens require a platform admin account.
|
||||||
|
security:
|
||||||
|
- bearerAuth: []
|
||||||
|
requestBody:
|
||||||
|
required: true
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/CreateUserTokenRequest'
|
||||||
|
responses:
|
||||||
|
'201':
|
||||||
|
description: Token created; raw value returned once
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/UserTokenCreated'
|
||||||
|
'400':
|
||||||
|
description: Invalid input
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/Error'
|
||||||
|
'403':
|
||||||
|
description: Admin scope requires platform admin
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/Error'
|
||||||
|
|
||||||
|
/user/tokens/{id}:
|
||||||
|
delete:
|
||||||
|
tags:
|
||||||
|
- User
|
||||||
|
summary: Revoke personal access token
|
||||||
|
description: Marks one of the caller's tokens as revoked. Clients presenting it are rejected from then on.
|
||||||
|
security:
|
||||||
|
- bearerAuth: []
|
||||||
|
parameters:
|
||||||
|
- name: id
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
format: uuid
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Token revoked
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
'404':
|
||||||
|
description: Token not found
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/Error'
|
||||||
|
|
||||||
# Projects
|
# Projects
|
||||||
/projects:
|
/projects:
|
||||||
get:
|
get:
|
||||||
@@ -458,6 +549,16 @@ paths:
|
|||||||
type: array
|
type: array
|
||||||
items:
|
items:
|
||||||
type: string
|
type: string
|
||||||
|
description: Reachable service URLs; rewritten to the request Host for remote clients. Null/empty when nothing is published.
|
||||||
|
ports:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
type: integer
|
||||||
|
description: Host ports actually bound for replica 0+; persisted on the service so restarts reuse the same public port. Null/empty when nothing is published.
|
||||||
|
health:
|
||||||
|
type: string
|
||||||
|
enum: [healthy, unhealthy, unreachable]
|
||||||
|
description: Result of the backend's HTTP probe of the service on its project network. Omitted when the service declares no healthcheck path.
|
||||||
containers:
|
containers:
|
||||||
type: array
|
type: array
|
||||||
items:
|
items:
|
||||||
@@ -6052,6 +6153,12 @@ components:
|
|||||||
type: string
|
type: string
|
||||||
server:
|
server:
|
||||||
type: string
|
type: string
|
||||||
|
os:
|
||||||
|
type: string
|
||||||
|
scope:
|
||||||
|
type: string
|
||||||
|
description: What the telemetry measures — `host` for a native daemon, `docker-desktop-vm` when Docker runs inside a Desktop VM.
|
||||||
|
enum: [host, docker-desktop-vm]
|
||||||
collected_at:
|
collected_at:
|
||||||
type: string
|
type: string
|
||||||
format: date-time
|
format: date-time
|
||||||
@@ -6379,6 +6486,66 @@ components:
|
|||||||
type: string
|
type: string
|
||||||
description: Human-readable label for the token (e.g. node name)
|
description: Human-readable label for the token (e.g. node name)
|
||||||
|
|
||||||
|
UserToken:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
id:
|
||||||
|
type: string
|
||||||
|
format: uuid
|
||||||
|
name:
|
||||||
|
type: string
|
||||||
|
key_prefix:
|
||||||
|
type: string
|
||||||
|
description: First 12 chars of the token, for identification in lists
|
||||||
|
scope:
|
||||||
|
type: string
|
||||||
|
enum: [read, write, admin]
|
||||||
|
expires_at:
|
||||||
|
type: string
|
||||||
|
format: date-time
|
||||||
|
last_used_at:
|
||||||
|
type: string
|
||||||
|
format: date-time
|
||||||
|
created_at:
|
||||||
|
type: string
|
||||||
|
format: date-time
|
||||||
|
required:
|
||||||
|
- id
|
||||||
|
- name
|
||||||
|
- key_prefix
|
||||||
|
- scope
|
||||||
|
- created_at
|
||||||
|
|
||||||
|
UserTokenCreated:
|
||||||
|
allOf:
|
||||||
|
- $ref: '#/components/schemas/UserToken'
|
||||||
|
- type: object
|
||||||
|
properties:
|
||||||
|
token:
|
||||||
|
type: string
|
||||||
|
description: Raw cnp_ token value, returned exactly once at creation
|
||||||
|
required:
|
||||||
|
- token
|
||||||
|
|
||||||
|
CreateUserTokenRequest:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
name:
|
||||||
|
type: string
|
||||||
|
description: Human-readable label (e.g. "laptop cli", "ci deploy")
|
||||||
|
scope:
|
||||||
|
type: string
|
||||||
|
enum: [read, write, admin]
|
||||||
|
default: write
|
||||||
|
description: read = GET/HEAD only; write = all non-admin routes; admin = everything (requires admin account)
|
||||||
|
expires_in_days:
|
||||||
|
type: integer
|
||||||
|
minimum: 0
|
||||||
|
maximum: 3650
|
||||||
|
description: 0 or omitted = never expires
|
||||||
|
required:
|
||||||
|
- name
|
||||||
|
|
||||||
AgentCapabilities:
|
AgentCapabilities:
|
||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
|
|||||||
@@ -90,3 +90,30 @@ backend restart.
|
|||||||
once), copy the prefilled install command, revoke tokens when done. Agents
|
once), copy the prefilled install command, revoke tokens when done. Agents
|
||||||
register over `POST /api/agents/register` and heartbeat via
|
register over `POST /api/agents/register` and heartbeat via
|
||||||
`POST /api/agents/heartbeat`.
|
`POST /api/agents/heartbeat`.
|
||||||
|
|
||||||
|
## Personal access tokens
|
||||||
|
|
||||||
|
**Settings → Personal Access Tokens**: issue `cnp_…` bearer tokens for the
|
||||||
|
CLI, MCP server, and scripts — the same privileges as your account, bounded
|
||||||
|
by scope. The raw token is shown once at creation; only its SHA-256 hash is
|
||||||
|
stored.
|
||||||
|
|
||||||
|
Scopes:
|
||||||
|
|
||||||
|
- `read` — `GET`/`HEAD`/`OPTIONS` only; mutations return `403 SCOPE_INSUFFICIENT`.
|
||||||
|
- `write` — everything except admin routes.
|
||||||
|
- `admin` — full access; requires a platform admin account, and the token is
|
||||||
|
still capped at the owner's privileges.
|
||||||
|
|
||||||
|
A token can never outrank its owner: non-admin scopes report
|
||||||
|
`is_admin = false` even on admin accounts.
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /api/v1/user/tokens list (metadata only, never hashes)
|
||||||
|
POST /api/v1/user/tokens {name, scope?, expires_in_days?} → raw token once
|
||||||
|
DELETE /api/v1/user/tokens/:id revoke (owner-scoped)
|
||||||
|
```
|
||||||
|
|
||||||
|
Use as `Authorization: Bearer cnp_…`, or `containr auth login cnp_…`.
|
||||||
|
Revocation takes effect on the next request; `last_used_at` updates on each
|
||||||
|
authenticated call.
|
||||||
Reference in new issue
Block a user