Commit graph

72 commits

Author SHA1 Message Date
11ea14d6db
fix: atomically accept snapshot pushes against current head 2026-11-28 00:17:41 -06:00
efc8bcc24b
fix: merge advanced hub head after sync push conflict 2026-11-28 00:17:41 -06:00
c655e941bc
fix: display release versions with a single v in the dashboard
Some checks are pending
CI / vet-build-test (push) Waiting to run
2026-11-27 21:35:05 -06:00
3605efda94 merge: 🛡️ devbox stale-ours no longer destroys an edit in the pull window 2026-08-05 11:38:32 -05:00
f1a6ac226f fix(syncer): stop pull from clobbering an edit made during the pull window
manifest.Build snapshots `ours` once before Pull applies any writes. A local
edit landing after that snapshot but before writeEntry looked unchanged
(oursCh false) and got overwritten with the hub version verbatim, with no
conflict copy — the edit's bytes ended up in no file and no snapshot.

Re-stat/re-hash the on-disk file right before a hub-only write would apply
and compare it against the entry manifest.Build captured. A mismatch routes
through the existing preserve-as-conflict path instead of clobbering. Only
checked when hub is about to write over a path `ours` already knew about —
a pure hub-only add has nothing on disk yet to race with.

This narrows the window, it doesn't close it: a rename at pull.go:424-451
still isn't atomic with this check. A real fix needs a filesystem-level
lock or lease around the whole pull, tracked separately.

Includes the untracked repro (zz_repro_stale_ours_test.go) that found this.
2026-08-05 02:35:12 -05:00
764d7d9a16 fix: push carries forward locally-excluded paths instead of deleting them 🩹
Push always treated the local .devignore/secret-guard-filtered manifest as
the FULL shared head, even on a whole-share mount — so a device with its own
--exclude for a path silently deleted that path from every other device's
copy on their next pull.

splice() now merges local entries over the parent head instead of the parent
head being consulted only for sub-path mounts: a parent-head path missing
from the local manifest is carried forward when the local ignore rules are
why it's invisible (excluded from view, not deleted). It is NOT carried
forward when the secret guard blocked it (the guard's job is to keep that
content out of the head) or when it's genuinely gone from disk with no
ignore rule hiding it (a real delete must still delete).

under()/strip() already treat subpath="" as "the whole path space," so this
is one code path for both mount kinds, not a special case bolted onto the
old one.

Includes the two repro tests (deduped from a near-copy) and a new delete-case
regression proving the fix didn't make real deletes un-deletable.
2026-08-05 02:34:38 -05:00
a8c32c4a23 fix: CLI honors secrets.extra_patterns; SaveState uses a unique temp file
Some checks failed
CI / vet-build-test (push) Has been cancelled
- add loadGuard(dir) helper in cmd/devbox/main.go; replaces all 4
  secret.New(nil) calls in publish/mount/restore/deploy so user's
  [secrets] extra_patterns from config.toml are enforced on CLI upload
  paths (was only enforced by the daemon — security leak)
- SaveState: switch from fixed .tmp suffix to os.CreateTemp(.state-*.tmp)
  mirroring SaveDaemon, eliminating concurrent-write corruption
2026-06-30 19:27:22 -05:00
4727d3d7f3 round9-client: log swallowed hook failures, doctor free-disk check, validate devbox ignore pattern 🩺⚠️🙈
Some checks are pending
CI / vet-build-test (push) Waiting to run
2026-06-30 18:07:53 -05:00
e05f4da87d round9-hub: add device id to --access-log lines (and make the auth ctx comment true)
- ctxKey/deviceKey *string holder pattern; AccessLogMiddleware allocates holder, injects into ctx, logs devID (or "-" for anon) as final field
- auth now sets the holder after resolving deviceID — comment updated to match reality
- TestAccessLogDeviceID: healthz logs "-", authed /v1/head logs the real device id; captures global log.Writer()
2026-06-30 18:07:53 -05:00
73c3f309a5 perf(hub): drop SSE streams on shutdown so redeploys don't eat the 10s drain 🛑⚡
Some checks are pending
CI / vet-build-test (push) Waiting to run
Every connected client daemon holds a long-lived /v1/events SSE stream, and
http.Server.Shutdown waits for connections to go idle — which these never do —
so a graceful shutdown always burned the full 10s drain timeout (felt on every
hub redeploy with clients connected). RegisterOnShutdown now signals the broker
to return every active /v1/events handler, so shutdown completes near-instantly.

Test: TestCloseEventStreams (live stream returns promptly after the hook).
Round 8 was 0 GO — the codebase is mined out; this is the reversed no-go.
2026-06-30 17:57:55 -05:00
d367e0ca8f fix(transport): SSE Events reuses c.hc so a hung connect can't wedge the daemon 🔌
Events() used a bare &http.Client{} (zero timeouts) — a black-holed TCP connect
blocked the daemon's reconnect loop forever (backoff only fires on stream
error/close, not a stuck connect). The bare client existed to dodge round-1's
30s TOTAL timeout on c.hc; round 2 removed that, so c.hc now bounds dial/TLS
with NO total timeout — exactly right for a long-lived SSE stream — and is
proxy-aware. One-line swap.
2026-06-30 17:27:00 -05:00
0ab6a88627 feat(hub): fsck also detects dangling snapshots (manifest refs a missing blob)
Some checks are pending
CI / vet-build-test (push) Waiting to run
2026-06-30 16:25:06 -05:00
6cf8846544 round6-client: restore HTTP_PROXY support (transport regression) + status flags daemon-not-running
- internal/transport/client.go: replace bare &http.Transport{} with
  DefaultTransport.Clone() so HTTP_PROXY/HTTPS_PROXY/NO_PROXY, ForceAttemptHTTP2,
  IdleConnTimeout, and ExpectContinueTimeout are preserved; only intentionally-tuned
  fields (DialContext, TLSHandshakeTimeout, ResponseHeaderTimeout, DisableCompression,
  MaxIdleConnsPerHost) are overridden.
- cmd/devbox/main.go: statusCmd disk path now calls control.DialState once upfront;
  prints "⚠️  daemon not running — showing last-known disk state (run: devbox start)"
  when daemon is absent so users aren't silently misled.
- Tests: TestTransportHonorsProxyEnv asserts Proxy!=nil + ForceAttemptHTTP2=true;
  TestStatusDaemonNotRunning asserts warning appears on joined-but-no-daemon device.
2026-06-30 16:25:06 -05:00
f0fe810ab6 fix(hub): derive push chunk set from the manifest, not client-supplied req.Chunks
Some checks are pending
CI / vet-build-test (push) Waiting to run
Trust boundary: handlePush previously verified that every hash in req.Chunks
existed in the blob store, but it trusted req.Chunks as the authoritative list
of chunks the pushed manifest references.  A buggy or malicious client could:

  (a) Push a manifest referencing chunk C while omitting C from req.Chunks →
      hub commits a snapshot whose manifest references a blob that may not
      exist → every subsequent pull 404s on C (dangling snapshot).

  (b) Include in req.Chunks a chunk not referenced by the manifest →
      refcount is bumped for a blob GC can never safely collect (phantom ref).

Fix: after confirming the manifest blob is present, we now fetch + unmarshal
it and derive the DISTINCT chunk hash set directly from Manifest.Entries[*].Chunks.
Each hash in that set is verified to exist in the store; any missing hash rejects
the push with 409 (same status as before).  Only manifest-referenced hashes are
passed to db.AddSnapshot() for refcounting.

Size hint: meta.ChunkRef.Size is used only for metrics/dashboard totals and is
stored once (first INSERT; ON CONFLICT only bumps refcount, not size).  GC
decisions are made on refcount, not size.  We keep req.Chunks as a size-hint
lookup (reqSizes map): if the client is honest the size is correct; if a hash is
absent from req.Chunks the size defaults to 0, which is harmless.

Happy-path unchanged: an honest client (syncer.go) always derives req.Chunks
from the same manifest, so all hashes are present with correct sizes.

Tests: TestHubHappyPath updated to push a real manifest JSON (required now that
the hub parses it); TestPushManifestChunkIntegrity asserts the malicious pattern
is rejected and the head does not advance, then confirms an honest push succeeds.
2026-06-30 15:28:02 -05:00
132978e63d round5-hub: fsck (at-rest blob integrity) + share ls 2026-06-30 15:28:02 -05:00
3ea8df85aa round4-client: surface last sync error per mount in status
Track lastErr per mount (mirroring lastSync pattern), cleared on
success so a recovered mount shows clean. Errors from LoadIgnoreWith,
Pull, and Sync all land in the map and surface through StateSnapshot
into 'devbox status' (human ⚠️ warning) and --json (last_err field).
2026-06-30 14:23:42 -05:00
dd27af3cc2 round3-hub: backup, metrics auth, device ls, gc --keep-days, access log
Some checks are pending
CI / vet-build-test (push) Waiting to run
2026-06-30 13:53:16 -05:00
8f78f65d57 round3-client: doctor clock-skew check vs hub 2026-06-30 13:53:16 -05:00
84a4ff53e8 feat(cli): doctor --json, conflicts --rm, status sync-age, opt-in default ignores 🧰🙈
- 🩺 `doctor --json`: structured check report for cron/monitoring; still exits
  non-zero on ❌ (collects checks into a slice, JSON path suppresses the human lines).
- 🗑️ `conflicts --rm`: delete every `.conflict-` copy after review (lazy cleanup,
  not a resolver). Only touches conflict copies — real files untouched.
- ⏱️ `status` shows per-mount last-sync age ("synced 12s ago" / "not synced yet")
  from a daemon-tracked timestamp (control.MountState.LastSyncUnix); also in --json.
- 🙈 the reversed no-go: `settings.sync.ignore_defaults` (opt-in, default off) layers
  a built-in junk set (node_modules, .git, target, dist, build, .venv, __pycache__,
  .next, .DS_Store) onto the matcher — don't ship gigabytes of regenerable junk over
  the now-live WAN. Reuses round-1 --exclude plumbing; honored by daemon + publish.

Tests: doctor --json valid+exit-code, conflicts --rm deletes only conflicts,
ignore.Defaults match. go test ./... -race + vet clean.
2026-06-30 13:26:24 -05:00
4333bba55b feat(hub): /metrics transfer counters + build version in /healthz 📊🩺
- 📊 /metrics gains real WAN observability counters beyond the 4 gauges:
  blob bytes in/out (the bandwidth signal now the hub is internet-reachable)
  plus pushes/conflicts totals for sync churn. Atomic, incremented at the
  blob + push handlers.
- 🩺 /healthz now reports the build version ("ok <version>") so a deploy can
  curl-verify the new binary is actually live (SetVersion wired in serve).

Test: TestMetricsCountersAndHealthVersion (version in healthz; bytes_in/out
move on a real PUT/GET).
2026-06-30 13:18:13 -05:00
963ece58b0 feat(transfer): harden the WAN sync path — timeouts, retry, parallel I/O, download gzip 🌐⚡
Now the hub is WAN-reachable, the transfer path needed real hardening:

- ⏱️  request timeout fix: replaced the 30s TOTAL http.Client.Timeout (which
  killed a 256MiB blob mid-transfer over a slow link) with granular dial / TLS /
  response-header timeouts + TCP keepalive. Body transfer is no longer wall-clocked.
- 🔁 retry + exponential backoff on transient blob transfers (network / 5xx),
  3 attempts; 4xx fails fast. Blob GET/PUT are content-addressed (idempotent),
  so retry is safe; control calls are left alone.
- 🚀 parallel blob uploads (push) and parallel chunk downloads (pull reassembly),
  bounded pools (8), sharing the existing rate limiter. WAN is RTT-bound — this
  keeps the pipe full instead of one-blob-at-a-time.
- 🗜️ download (response) gzip: round 1 compressed only uploads, but a clone is
  download-heavy. Client negotiates gzip explicitly (so the rate limiter counts
  wire bytes), hub streams the response through gzip, client decompresses
  bomb-safely. Gated by the same settings.transfer.compress flag.

Tests: retry transient-then-success + 4xx-no-retry, gzip download round-trip.
All existing push/pull round-trips green under -race (refactors behavior-preserving).
2026-06-30 13:15:17 -05:00
11fe999ca2 feat(transfer): opt-in gzip blob compression for WAN sync 🌐🗜️
The "changed my mind" feature: deferred as YAGNI on a LAN, but the hub is now
WAN-reachable (port-forwarded), so over-the-internet sync is a real path and
compression earns its keep.

- client (settings.transfer.compress, default off): gzip a blob upload only
  when it actually shrinks — incompressible chunks (media, encrypted) go raw so
  we never inflate the wire. Sets Content-Encoding: gzip. Wired into the daemon
  sync loop and the initial `publish` upload.
- hub: decompresses gzip uploads before hashing, so dedup + content-address
  integrity are unchanged. Bomb-safe — caps BOTH the compressed stream
  (MaxBytesReader) and the decompressed size (LimitReader), rejecting a gzip
  header over a non-gzip body.

Tests: client gzip-when-smaller / raw-when-not, hub decompress round-trip +
bad-gzip rejection. go test ./... -race clean, go vet clean.
2026-06-30 12:34:27 -05:00
8c5d576a72 feat(device): --json output, streaming chunker, pause --for, per-mount exclude, rescan knob ✨
Five device-side wins from the feature review:

- 🤖 `--json` on status/log/conflicts: machine-readable output for fleet
  scripting/monitoring. status prefers live daemon state (paused +
  base-snapshot), falls back to disk; not-joined → {"joined":false}.
- 🌊 streaming chunker: chunk.SplitReader feeds FastCDC from an io.Reader so
  the manifest build no longer slurps whole files into RAM — a multi-GB file
  can't OOM the daemon. Identical boundaries/hashes (proven vs fragmented reads).
- ⏱️  `devbox pause --for 2h`: control socket carries a duration; the daemon
  schedules an auto-resume timer. Re-pause replaces it; plain pause/resume
  cancel it (no surprise resume).
- 🙈 per-mount `devbox mount --exclude <pat>`: device-local ignore layered on
  the shared .devignore (LoadIgnoreWith) — skip a local build dir without
  touching the shared file. Honored by daemon sync, restore, and deploy.
- 🎛️  rescan cadence is now settings.sync.rescan_seconds (was a hardcoded 60s
  const) — tune the watcher fallback per machine without a rebuild.

#6 (doctor non-zero exit) was already shipped — doctor returns an error on ❌.
Tests: SplitReader-vs-buffered, PauseFor auto-resume + cancel, wire duration,
LoadIgnoreWith layering, status/conflicts --json. go test ./... -race clean.
2026-06-30 12:29:02 -05:00
5440054a41 feat(hub): gc --dry-run, dashboard token auth, /healthz + /readyz 🛡️🧹
Three hub-side operability/security closures:

- 🧹 `devbox-hub gc --dry-run`: previews the exact snapshots + chunks the
  sweep would remove (computed from reachability — same set the real run
  deletes) without mutating a thing. Cheap insurance before a destructive GC.
- 🔐 dashboard token auth (`--dashboard-token`): a non-loopback bind was
  unauthenticated (warning only) and leaked device names/activity. Token is
  accepted via ?token=, Authorization: Bearer, or an HttpOnly cookie pinned
  on first ?token= — so EventSource/fetch authenticate with index.html
  untouched. Constant-time compare.
- 🩺 `/healthz` (liveness) + `/readyz` (DB-ping → 503 when unreachable): real
  probes for the compose selfheal profile / LBs, which only had /metrics.

Tests: TestGCDryRun (accurate + non-destructive), TestDashboardAuth.
2026-06-30 12:14:54 -05:00
80380652cc feat(dashboard): P3 depth — pull/gc/conflict flow events + server-side history ✨📊
Some checks are pending
CI / vet-build-test (push) Waiting to run
- Hub emits 3 new flow events: pull (head fetch/propagation, handleHead), conflict
  (stale-parent push, handlePush), gc (in-process sweep). Opt-in periodic GC via
  'serve --gc-every <dur>' (default off) self-maintains the hub AND animates each
  sweep; runGC stays put (no risky refactor of mark-and-sweep).
- Server-side history ring: per-minute activity buckets (push/pull/conflict/gc +
  bytes), last 60 min, in /api/state — the sparkline now survives a page reload
  (was computed from the live stream only). Recorded under the Emit lock; race-clean.
- Frontend (index.html): pull = teal inbound pulse, conflict = red collision burst,
  gc = amber hub sweep + toast; stacked per-minute history sparkline seeded from
  /api/state and growing live. One file, no new deps.
- dashboard-fleet-verify.sh: rewritten — drives join·push·pull·conflict·gc and
  asserts all 5 on the SSE stream + the history window; adds LOCAL=1 mode (native,
  no Pi). Verified locally end-to-end. Tests: TestHistoryRing. go test ./... -race clean.
2026-06-23 20:45:31 -05:00
f8135b9d07 feat(M8a): adversarial auth audit — close +s escalation + add invite revocation 🛡️
Some checks are pending
CI / vet-build-test (push) Waiting to run
P2 adversarial audit (6 finders + skeptic verification, 13 agents). Two real
findings fixed with regression tests; rest documented as single-owner residuals.

- FIX (+s attenuation): MayGrant never constrained the GRANTED reshare bit, so an
  invite could confer +s the caller didn't hold (req.Reshare copied verbatim).
  MayGrant now takes grantReshare and rejects conferring +s you don't hold (owners
  unconstrained) — attenuation is total over role + target + reshare.
- FIX (invite revocation): invites were unrevocable 24h bearer capabilities — no
  way to kill a leaked/regretted one. Added meta.RevokeInvite (token+binding in one
  tx), POST /v1/invite/revoke (only a caller who could mint it may revoke), and
  'devbox invite revoke <token>'.
- Tests: TestMayGrant (+5 +s cases), TestInviteCannotGrantReshareCallerLacks,
  TestInviteRevoke. go test ./... -race clean (18 pkgs).
- docs/M8a-audit.md: findings, confirmed defenses, accepted residuals.

Confirmed-defended under attack: single-use redeem (atomic CAS), role bounding,
revoke-at-auth (revoked=0 in bearer+role lookups), cross-share binding, PoP.
2026-06-23 20:27:12 -05:00
03469958d3 chore: prep for public release — MIT license + github.com module path 🌍⚖️
Some checks are pending
CI / vet-build-test (push) Waiting to run
- LICENSE: MIT (enables the adoption push; public repo was all-rights-reserved).
- go.mod + all imports: git.shoemoney.ai/shoemoney/devbox -> github.com/shoemoney/devbox,
  so outsiders can 'go install github.com/shoemoney/devbox/cmd/devbox@latest'. Forgejo
  stays the self-hosted home; the registry (devbox-hub) + public dist (devbox-dist) are
  unchanged. vet + build + go test -race all green after the rename.
- README: document the go install path.

Security: full git-history scan (manual blob sweep + gitleaks, 84 commits) found
ZERO secrets — Forgejo token never committed, no keys/passwords/private keys.
2026-06-23 19:19:09 -05:00
9f662cd476 refactor: drop unused param in dashboard online() (ponytail) 🦥 2026-06-23 12:47:50 -05:00
35d4d5dfd3 docs: README live-dashboard section + ponytail cleanup 📊🦥
- README: marquee Live Dashboard section (hero screenshot, --dashboard
  usage, how-it-works table, flow Mermaid), CLI table + TOC entries.
- ponytail: dropped a hand-rolled totalsInfo.MarshalJSON — struct json
  tags do the lowercase-key mapping for free.
2026-06-23 12:47:14 -05:00
9e93f8b3a0 feat: epic live dashboard frontend — mission-control flow viz 📊✨
Single self-contained index.html (vanilla JS + canvas, zero deps/CDN,
go:embed'd, air-gap safe). Cyberpunk net-ops aesthetic: a breathing glowing
hub core with counter-rotating rings, device nodes orbiting (online bright /
idle dim), magenta share nodes; on a push a trailed particle streams
device→core→share then a fan-out ripple to subscribers, joins burst in.
7 glassmorphism metric tiles with hand-drawn canvas sparklines + eased
counters; an auto-scrolling color-coded activity stream (capped 50); SSE
auto-reconnect with a live/reconnecting indicator; ?demo=1 synthesizes a
stream for the wow-factor and offline preview. Built by a worktree subagent
(frontend-design), screenshot-verified against the REAL hub backend — live
/api/state + /api/events both drive it (see docs/images/dashboard.png).
Added a 📦 data-URI favicon (kills the only console 404).
2026-06-23 12:44:52 -05:00
2d407d418a feat: hub live dashboard backend — state + SSE flow stream 📊🛰️
Optional, off by default: devbox-hub serve --dashboard [--dashboard-addr
127.0.0.1:8099]. A separate, loopback-by-default listener (never widens the
API surface; warns if bound non-loopback since it's unauthenticated read-only).

- internal/hub/dashboard: embedded UI (go:embed index.html) + GET /api/state
  (hub/totals/devices/shares snapshot) + GET /api/events (SSE live flow stream).
  A nil *Dashboard is Emit-safe so hub handlers call it unconditionally.
- meta reads for the snapshot: Devices(), ShareStats() (one rolled-up query),
  SumChunkBytes(). 'online' is activity-tracked since hub start (2-min window).
- hub emits 'join' (device enrolled) and 'push' (device→share, bytes/chunks/
  snapshot/new_head) flow events.
Tests: state reflects the DB + a push event reaches a live SSE subscriber +
nil-safe Emit. index.html here is a placeholder — the epic frontend lands next.
2026-06-23 12:35:36 -05:00
05ebdeea77 refactor: ponytail-audit — drop the EffectiveRole delegating wrapper 🧹
It only called EffectiveMember and dropped one return; its sole prod
caller (the push gate) discarded that return anyway. Inline it: the gate
calls EffectiveMember directly and the test now targets the real method.
Kept blobstore.Store (single impl, but the documented M9 S3/R2 seam) and
control.Daemon (single impl, but breaks the daemon->control import cycle).
2026-06-23 11:52:25 -05:00
abab3b5ff9 feat(M8): restore preserves uncommitted edits (never lose a byte) 🛟
Closes the audit's deferred #18 — the right way this time. An explicit
'devbox restore' no longer silently clobbers UNCOMMITTED local edits:

- captureUncommitted reads the bytes of any local file that differs from
  BOTH the snapshot being restored AND the current hub head (== an edit
  that was never pushed) BEFORE the restore overwrites/deletes it.
- After applySnapshot runs, those bytes are written back as .conflict-
  <host>-<ts> copies (discoverable via 'devbox conflicts', and they
  propagate like any conflict copy).

The head comparison is the key: a CLEAN restore (no uncommitted edits)
captures nothing and reproduces the snapshot exactly — TestRestoreWholeTree
still passes. Capture-before / write-after ordering means applySnapshot's
delete pass never eats the copy. Refactored the conflict-name probe into a
shared freeConflictName. Deploy stays as-is (read-only/pinned mounts have
no uncommitted edits to lose). New test: an uncommitted v3 survives a
revert to v1 as a conflict copy. 18 pkgs -race green; windows builds.
2026-06-23 11:44:45 -05:00
fd873a02c3 feat(M8a): device-facing invites with privilege attenuation ✉️🔐
Completes M8a's collaboration surface. A member mints an invite; the
invitee redeems it through the EXISTING /v1/join proof-of-possession flow
and lands enrolled + assigned the bound principal + granted the bound role.

- migration #3: invites table (token_hash → principal/share/role/+s),
  chains 0→1→2→3 — verified on a copy of the real hub DB.
- POST /v1/invite (authed) enforces ATTENUATION server-side via the pure,
  unit-tested meta.MayGrant: never grant above your own role, never touch a
  principal who outranks you, viewers can't grant, editors need +s. On a
  legacy share the inviter is seeded as owner before the explicit flip so
  they (and their same-principal devices) never self-lock-out.
- /v1/join applies a redeemed invite's binding (plain token = v1 join).
- transport.Invite + devbox invite <share> <principal> <role> [--reshare].

Tests: MayGrant attenuation matrix, invite binding round-trip, and the
end-to-end TestInviteFlow (owner invites → flip preserves owner → invitee
redeems into editor → editor-without-+s denied). 18 pkgs -race green;
linux/amd64 + windows cross-build.
2026-06-23 11:31:29 -05:00
68d25dfd38 feat(M8a): GET /v1/members + devbox members — read the role grants 👥📖
The read companion to devbox-hub member set/rm/list. Additive: new
PathMembers endpoint (authed; reads stay open in M8a — gating is M9),
proto.Member/MembersResponse, transport Members(), and a devbox members
<share> client command that prints 'legacy share' or the role grants
(principal, role, +s). Role name<->level mapping moved to meta
(ParseRole/RoleName) and the devbox-hub CLI deduped onto it; new
meta.ACLMode(share). Test: legacy reads empty, a grant flips it explicit
and lists bob/editor/+s. 18 pkgs -race green; windows cross-builds.
2026-06-23 11:23:13 -05:00
3213149974 refactor: ponytail-audit cuts — dead Windows Publish stub + dedup Daemon iface 🧹
Repo-wide audit (per request) came back lean — no dead exports, no
reinvented stdlib. Two real cuts:
- delete the Windows control.Server.Publish no-op: Publish was removed
  from the real server when /events was trimmed, so nothing calls it.
- move the control.Daemon interface into shared control.go (was duplicated
  across server.go + server_windows.go build-tag split → drift risk).

Kept (disagreed with cutting): blobstore.Store interface is the documented
M9 S3 seam (6 lines, clean contract); c.Bearer() is a tiny test accessor.
2026-06-23 11:13:38 -05:00
81fbc5c81a feat(M8a): principals + per-share roles + write enforcement 👥🔐
V2-SPEC §5.2 (write-side, staged before read-side M9). Migration #2 (rides
the M8 runner, chains 0→1→2 — verified on real .10 data, version 2, all
counts preserved):

- principals table + devices.principal_id (every v1 device backfills to one
  synthetic 'owner' principal — byte-identical to v1 until a share opts in).
- members(share, principal_id, role, can_reshare) + shares.acl_mode. A share
  with zero grants is 'legacy' (every device an implicit owner = v1); the
  first grant flips it to 'explicit' = deny-by-default.
- EffectiveRole(device, share) resolves device→principal→role; legacy⇒owner.
- Push write gate: role>=editor AND the access.writable clamp (which can only
  REMOVE write). Legacy shares reduce to the v1 writable bit exactly.
- devbox-hub member set/rm/list + principal <device> <principal> admin CLI —
  the populate path, so the role layer has a real consumer now (no dead code).

Tests: legacy↔explicit lifecycle, deny-by-default, viewer<editor, HTTP push
gate (403 unmembered/viewer, opens at editor). 18 pkgs -race green; hub
cross-compiles linux/amd64; windows builds.
2026-06-23 11:09:32 -05:00
9f90f2c147 refactor(M8): drop the control /events SSE stream — no consumer yet (ponytail) ✂️
ponytail-review caught it: publishActivity -> ctrl.Publish -> broker -> SSE
was a producer with nothing on the other end. GET /events only feeds the
M11 TUI, which is demand-driven and not built. /state + /pause + /resume
cover every real caller (devbox status/pause/resume). Cut the broker,
handleEvents, Publish, publishActivity, and the ctrl handle — re-add the
(small, known) fan-out when a TUI actually consumes it. Net -100 lines.
2026-06-23 10:50:45 -05:00
051341bcf9 Merge branch 'worktree-agent-a3cf629cee851dd02' 2026-06-23 10:46:38 -05:00
9a9321adf7 feat(M8): migration runner + per-(share,id) snapshots 🏗️🔑
The v2 foundation (V2-SPEC §5.1). Two things land:

- PRAGMA user_version migration runner in internal/hub/meta: ordered,
  append-only, each step in its own txn with the version bump LAST so a
  crash rolls back cleanly. Backs up an existing DB to <path>.pre-v2.bak
  (VACUUM INTO) before migrating; refuses a DB written by a newer build.
  Every later v2 schema change rides this.

- Re-key snapshots from a GLOBAL id PK to per-(share, id). v1's global id
  meant identical content pushed to two shares collided on one row, so the
  second share never counted its chunk refcounts (undercount) and recorded
  no snapshot row. Per-share rows fix the refcount and let each share own
  its history. Wire id/Head stays the manifest hash — clients unchanged.
  Migration also backfills any share head left rowless by the v1 idempotent
  push, restoring the head-has-a-row invariant. GC reworked to prune per
  (share, id), decrementing each share's chunks and freeing a shared
  manifest blob at most once.

Tests: cross-share refcount, migration versioning + refuse-newer, and a
realistic populated-v1 -> v2 upgrade (data preserved, backup written,
head backfill). All 17 pkgs -race green; hub cross-compiles linux/amd64.

Deferred to M8-3 (conflict sidecar): restore/deploy conflict-copy — a naive
version breaks restore-reproduces-snapshot; it needs the base/ancestor
awareness the sidecar introduces. snapshot_chunks edge table deferred to
M9 (no consumer yet; the runner makes adding it a one-line migration).
2026-06-23 10:46:26 -05:00
20579b0aae feat(M8): daemon control socket + pause/resume 🎛️
Add internal/control: an HTTP/1.1 control plane the daemon hosts on a
0600 Unix socket (control.sock) in the config dir — GET /state, GET
/events (SSE), POST /pause|/resume — plus a stdlib net/http client
(DialState/Pause/Resume) that returns a typed ErrNotRunning when the
daemon is down so callers can fall back.

Wire into the daemon: paused atomic.Bool gates runMount's trigger loop
(drains while paused, no-ops the initial nudge), a per-mount nudge
registry lets Resume catch every mount up, and StateSnapshot feeds
/state. The control server starts in Run and is non-fatal — sync never
depends on it. Windows gets a build-tagged stub (named-pipe upgrade
path noted).

CLI: devbox pause/resume call the client (friendly 'daemon not running'
when absent); status prefers the live socket but ONLY on a TTY, so piped
output stays byte-identical to v1 for scripts.
2026-06-23 10:38:22 -05:00
edbae06c3d test: drop tautological byte-cap invariant test (ponytail) ♻️
Per ponytail review of the hardening batch: TestHubByteCapsAreSane only fails on
a deliberate const edit (not a real bug) and its comment described timeouts it
never tested. The happy-path limits test carries the regression weight.
2026-06-23 03:17:32 -05:00
04f94d7730 harden(auth): require proof-of-possession on join 🪪🔐
The device id is derived from the pubkey in JoinRequest, but the hub never
checked the joiner actually held that key — anyone with a token could enroll
claiming another device's identity. Now the client signs JoinChallenge(token,
pubkey) with its ed25519 private key and the hub verifies it (ed25519.Verify)
BEFORE redeeming the token — so a bad request can't burn a legitimate one-time
token either. proto gains a Signature field + the shared JoinChallenge helper.
Regression test: garbage/missing/wrong-key sigs all 401, token survives, valid
join enrolls.
2026-06-23 03:08:23 -05:00
fd361e811e harden(dos): bound request bodies + add hub server timeouts 🚪🛡️
The hub read request bodies with unbounded io.ReadAll / json.Decode and ran
http.ListenAndServe with zero timeouts — a single client could OOM it or hold
connections open (slowloris). Now:
- handleBlob caps the body at 256 MiB, decode() caps JSON at 8 MiB, both via
  http.MaxBytesReader -> 413 when exceeded.
- serve uses an http.Server with ReadHeaderTimeout/ReadTimeout/IdleTimeout +
  MaxHeaderBytes. WriteTimeout intentionally unset so the long-lived /v1/events
  SSE stream isn't killed. [fanned-out subagent: harden-dos]
2026-06-23 02:59:53 -05:00
4b6a4b97b2 harden(durability): fsync atomic writes before publishing the rename 💽
A power loss between rename and the data hitting disk could leave a truncated/
empty file despite the atomic rename — breaking 'never lose a byte'. Now both
atomic-write paths f.Sync() the temp file before rename and best-effort fsync
the parent dir after (so the rename entry is durable too):
- internal/syncer/pull.go atomicWrite (pulled file content)
- internal/hub/blobstore Disk.Put (stored blobs)
Dir fsync is best-effort (unsupported on Windows). [fanned-out subagent: harden-fsync]
2026-06-23 02:59:26 -05:00
56b8be924b fix(daemon): stagger rescans, guard jitter panic, tighten backoff reset 🔁⚙️
- rescan tickers for all mounts started in lockstep, so every 60s they rebuilt
  manifests simultaneously (self-synchronized load spike on big trees). Stagger
  the first tick by a random offset.
- jittered() called rand.Int63n(int64(d/2)) which panics for sub-2ns durations
  (d/2==0). Guard it. (Latent: a panic in a recover-less goroutine.)
- healthyStream was 2min — 4x larger than typical SSE recycle (~30-60s), so a
  recycled-but-healthy stream never reset backoff and sat at the 30s ceiling.
  Lowered to 20s. Regression test for the jitter panic.
2026-06-23 02:38:46 -05:00
9ad2a9da74 fix(dataloss): make hub GC safe against cross-share refcount undercount 🩸🗑️
Snapshots are content-addressed with a GLOBAL id, so two shares with identical
content collide on one snapshots row and the idempotent push skips the refcount
bump — a chunk two share heads both need ends up refcount=1. The old GC then
pruned the 'old' snapshot for one share and freed chunks/manifests the OTHER
share's live head still pointed at. Permanent cross-share data loss.

Rework runGC as mark-and-sweep from every share's live snapshots as roots:
nothing reachable from a kept snapshot is ever deleted, whatever the refcounts
say. Never prune a snapshot that is any share's head. Plus hardening:
- DeleteSnapshot floors refcount at 0 and only decrements if the row existed
  (no negative counts from a double-delete).
- DeleteChunkRow is now conditional (WHERE refcount<=0) and reports if it
  deleted, so a push that re-references a chunk mid-GC isn't corrupted.
Cross-share repro test + existing single-share GC test both green.

Deferred to v2 (documented): proper per-(share,id) refcount accounting — needs
a schema migration of the live hub; the ground-truth GC makes it safe meanwhile.
2026-06-23 02:35:43 -05:00
57ebed35b5 fix(dataloss): don't clobber a .devignore'd/guarded local file on pull 🩸🛟
The pull merge compared the hub against 'ours' = a .devignore/secret-guard
FILTERED manifest. A file still on disk but excluded from 'ours' looked like a
local delete, so a hub edit to that path hit 'case tOK && !oOK' and overwrote
the on-disk bytes with NO conflict copy — silently destroying ignored configs
and the very .env/keys the guard exists to protect (a teammate pushing .env
could wipe your local secret).

Now: in that branch, stat the real file first; if it's actually present,
preserve it as a .conflict-<host>-<ts> copy before applying the hub version —
honoring the 'never lose a byte' promise. Regression test proves the local
bytes survive.
2026-06-23 02:28:51 -05:00
c864461fa1 fix(sec): contain manifest paths + verify blob integrity on download 🛡️🧊
Two ways a buggy/malicious hub could corrupt the local tree:
- writeEntry/deleteFile joined hub-supplied Entry.Path into root with no
  containment check, so '../../.ssh/authorized_keys' wrote/deleted OUTSIDE the
  mount. New safeJoin() uses filepath.IsLocal to refuse absolute/.. /escaping
  paths before any write or delete.
- GetBlob returned bytes with only an HTTP-status check. Blobs (chunks AND
  manifests) are content-addressed, so now verify chunk.Hash(body)==hash —
  a corrupt/truncated transfer or hostile hub can't write wrong content
  undetected. (manifest ID == chunk.Hash(Marshal()), so the check holds there.)
Regression tests for both.
2026-06-23 02:24:32 -05:00
96fd6018a9 fix(sec): block blob-hash path traversal (arbitrary file read) 🔓🛡️
GET /v1/blob/{hash} and /v1/have passed the URL hash straight into filepath.Join
in the blob store. Go's ServeMux URL-decodes %2f/%2e in the wildcard, so
'..%2f..%2f..%2fetc%2fpasswd' (or a hash starting with '..') escaped the blob
root — any enrolled device could read arbitrary files incl. the hub token DB.

Defense in depth:
- hub: validHash() rejects non-(64 hex) keys at the HTTP boundary (404 on GET,
  400 on /have) before any store call.
- blobstore: safeKey() rejects keys that aren't a bare, separator-free filename
  in Has/Get/Put/Delete — the sink can't be escaped even if a caller forgets.
e2e + unit regression tests for both layers.
2026-06-23 02:21:03 -05:00