diff --git a/cmd/devbox-hub/main.go b/cmd/devbox-hub/main.go new file mode 100644 index 0000000..33700eb --- /dev/null +++ b/cmd/devbox-hub/main.go @@ -0,0 +1,43 @@ +// Command devbox-hub is the hub server + admin CLI. +package main + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" +) + +var version = "0.0.0-dev" + +func main() { + root := &cobra.Command{ + Use: "devbox-hub", + Short: "đŸ›°ī¸ devbox hub server", + SilenceUsage: true, + SilenceErrors: true, + } + root.AddCommand( + &cobra.Command{ + Use: "version", + Short: "print version", + Run: func(c *cobra.Command, _ []string) { fmt.Fprintln(c.OutOrStdout(), "devbox-hub", version) }, + }, + hubStub("serve", "🚀 run the hub server", "M2"), + hubStub("token", "đŸŽŸī¸ mint/rotate the join token", "M2"), + ) + if err := root.Execute(); err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } +} + +func hubStub(use, short, milestone string) *cobra.Command { + return &cobra.Command{ + Use: use, + Short: short, + RunE: func(*cobra.Command, []string) error { + return fmt.Errorf("%q not implemented yet (arrives in %s)", use, milestone) + }, + } +} diff --git a/cmd/devbox/main.go b/cmd/devbox/main.go new file mode 100644 index 0000000..7502a75 --- /dev/null +++ b/cmd/devbox/main.go @@ -0,0 +1,125 @@ +// Command devbox is the device-side CLI + daemon entrypoint. +package main + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" + + "git.shoemoney.ai/shoemoney/devbox/internal/config" + "git.shoemoney.ai/shoemoney/devbox/internal/identity" +) + +var version = "0.0.0-dev" + +func main() { + root := &cobra.Command{ + Use: "devbox", + Short: "đŸ“Ļ devbox — Dropbox for developers", + Long: "devbox keeps your dev directories live-synced across machines.", + SilenceUsage: true, + SilenceErrors: true, + } + root.AddCommand( + joinCmd(), + statusCmd(), + versionCmd(), + stub("start", "â–ļī¸ run the sync daemon", "M3"), + stub("stop", "âšī¸ stop the sync daemon", "M3"), + stub("publish", "📂 create a share from a local folder", "M2"), + ) + if err := root.Execute(); err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } +} + +func versionCmd() *cobra.Command { + return &cobra.Command{ + Use: "version", + Short: "print version", + Run: func(cmd *cobra.Command, _ []string) { + fmt.Fprintln(cmd.OutOrStdout(), "devbox", version) + }, + } +} + +func joinCmd() *cobra.Command { + return &cobra.Command{ + Use: "join ", + Short: "đŸŽŸī¸ enroll this device against a hub", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + dir, err := config.Dir() + if err != nil { + return err + } + id, err := identity.LoadOrCreate(dir) + if err != nil { + return err + } + d, err := config.LoadDaemon(dir) + if err != nil { + return err + } + d.Hub = args[0] + if err := config.SaveDaemon(dir, d); err != nil { + return err + } + out := cmd.OutOrStdout() + fmt.Fprintf(out, "device fingerprint: %s\n", id.Fingerprint()) + fmt.Fprintf(out, "hub: %s\n", args[0]) + fmt.Fprintln(out, "✅ identity ready. (hub handshake lands in M2)") + return nil + }, + } +} + +func statusCmd() *cobra.Command { + return &cobra.Command{ + Use: "status", + Short: "📊 show device + sync status", + RunE: func(cmd *cobra.Command, _ []string) error { + dir, err := config.Dir() + if err != nil { + return err + } + out := cmd.OutOrStdout() + id, err := identity.Load(dir) + if err != nil { + fmt.Fprintln(out, "not joined yet — run: devbox join ") + return nil + } + d, _ := config.LoadDaemon(dir) + fmt.Fprintf(out, "device: %s\n", id.Fingerprint()) + fmt.Fprintf(out, "hub: %s\n", orNone(d.Hub)) + fmt.Fprintf(out, "mounts: %d\n", len(d.Mounts)) + for _, m := range d.Mounts { + mode := "rw" + if m.ReadOnly { + mode = "ro" + } + fmt.Fprintf(out, " - %s/%s -> %s [%s]\n", m.Share, m.Subpath, m.Local, mode) + } + return nil + }, + } +} + +func orNone(s string) string { + if s == "" { + return "(none)" + } + return s +} + +func stub(use, short, milestone string) *cobra.Command { + return &cobra.Command{ + Use: use, + Short: short, + RunE: func(*cobra.Command, []string) error { + return fmt.Errorf("%q is not implemented yet (arrives in %s)", use, milestone) + }, + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..3119587 --- /dev/null +++ b/go.mod @@ -0,0 +1,13 @@ +module git.shoemoney.ai/shoemoney/devbox + +go 1.26 + +require ( + github.com/BurntSushi/toml v1.6.0 + github.com/spf13/cobra v1.10.2 +) + +require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/spf13/pflag v1.0.9 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..c09a7f6 --- /dev/null +++ b/go.sum @@ -0,0 +1,12 @@ +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..5e16e98 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,75 @@ +// Package config reads and writes the machine-global devbox configuration: +// the device's joined hub and its list of mounts (daemon.toml). +package config + +import ( + "os" + "path/filepath" + "runtime" + + "github.com/BurntSushi/toml" +) + +// Dir returns the machine-global devbox config directory: +// $XDG_CONFIG_HOME/devbox, else ~/.config/devbox on unix/mac, else +// %AppData%\devbox on Windows. +func Dir() (string, error) { + if x := os.Getenv("XDG_CONFIG_HOME"); x != "" { + return filepath.Join(x, "devbox"), nil + } + if runtime.GOOS == "windows" { + base, err := os.UserConfigDir() + if err != nil { + return "", err + } + return filepath.Join(base, "devbox"), nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + return filepath.Join(home, ".config", "devbox"), nil +} + +// Mount binds a hub share (or sub-path) to a local directory. +type Mount struct { + Share string `toml:"share"` + Subpath string `toml:"subpath,omitempty"` + Local string `toml:"local"` + Hub string `toml:"hub"` + ReadOnly bool `toml:"readonly,omitempty"` +} + +// Daemon is daemon.toml: which hub this device joined and what it mounts. +type Daemon struct { + Hub string `toml:"hub,omitempty"` + Mounts []Mount `toml:"mount"` +} + +func daemonPath(dir string) string { return filepath.Join(dir, "daemon.toml") } + +// LoadDaemon reads daemon.toml from dir; a missing file yields a zero Daemon. +func LoadDaemon(dir string) (Daemon, error) { + var d Daemon + b, err := os.ReadFile(daemonPath(dir)) + if os.IsNotExist(err) { + return d, nil + } + if err != nil { + return d, err + } + return d, toml.Unmarshal(b, &d) +} + +// SaveDaemon writes daemon.toml under dir (creating dir 0700). +func SaveDaemon(dir string, d Daemon) error { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + f, err := os.Create(daemonPath(dir)) + if err != nil { + return err + } + defer f.Close() + return toml.NewEncoder(f).Encode(d) +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..e7f5cff --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,34 @@ +package config + +import "testing" + +func TestDaemonRoundTrip(t *testing.T) { + dir := t.TempDir() + in := Daemon{Hub: "hub.shoemoney.ai", Mounts: []Mount{ + {Share: "projects", Local: "/Users/jh/Projects", Hub: "hub.shoemoney.ai"}, + {Share: "projects", Subpath: "p22/backend", Local: "/var/www", Hub: "hub.shoemoney.ai", ReadOnly: true}, + }} + if err := SaveDaemon(dir, in); err != nil { + t.Fatal(err) + } + out, err := LoadDaemon(dir) + if err != nil { + t.Fatal(err) + } + if out.Hub != in.Hub || len(out.Mounts) != 2 { + t.Fatalf("roundtrip mismatch: %+v", out) + } + if !out.Mounts[1].ReadOnly || out.Mounts[1].Subpath != "p22/backend" { + t.Fatalf("mount fields lost: %+v", out.Mounts[1]) + } +} + +func TestLoadDaemonMissingIsEmpty(t *testing.T) { + d, err := LoadDaemon(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if d.Hub != "" || len(d.Mounts) != 0 { + t.Fatalf("expected empty daemon for missing file, got %+v", d) + } +} diff --git a/internal/identity/identity.go b/internal/identity/identity.go new file mode 100644 index 0000000..fae9292 --- /dev/null +++ b/internal/identity/identity.go @@ -0,0 +1,85 @@ +// Package identity manages a device's Ed25519 keypair — the machine's stable, +// revocable identity on a hub. The private key never leaves the machine. +package identity + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/pem" + "fmt" + "os" + "path/filepath" +) + +// Identity is a device's Ed25519 keypair. +type Identity struct { + Pub ed25519.PublicKey + Priv ed25519.PrivateKey +} + +const ( + privName = "device.key" + pubName = "device.key.pub" +) + +// Generate makes a fresh device identity. +func Generate() (Identity, error) { + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return Identity{}, err + } + return Identity{Pub: pub, Priv: priv}, nil +} + +// Fingerprint is a short, stable id derived from the public key. +func (id Identity) Fingerprint() string { + sum := sha256.Sum256(id.Pub) + return hex.EncodeToString(sum[:8]) // 16 hex chars +} + +// Save writes the keypair under dir (private key 0600, dir 0700). +func (id Identity) Save(dir string) error { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + priv := pem.EncodeToMemory(&pem.Block{Type: "DEVBOX PRIVATE KEY", Bytes: id.Priv}) + if err := os.WriteFile(filepath.Join(dir, privName), priv, 0o600); err != nil { + return err + } + pub := pem.EncodeToMemory(&pem.Block{Type: "DEVBOX PUBLIC KEY", Bytes: id.Pub}) + return os.WriteFile(filepath.Join(dir, pubName), pub, 0o644) +} + +// Load reads a keypair previously written by Save. +func Load(dir string) (Identity, error) { + raw, err := os.ReadFile(filepath.Join(dir, privName)) + if err != nil { + return Identity{}, err + } + block, _ := pem.Decode(raw) + if block == nil { + return Identity{}, fmt.Errorf("identity: bad private key PEM in %s", dir) + } + priv := ed25519.PrivateKey(block.Bytes) + if len(priv) != ed25519.PrivateKeySize { + return Identity{}, fmt.Errorf("identity: private key wrong size %d", len(priv)) + } + return Identity{Priv: priv, Pub: priv.Public().(ed25519.PublicKey)}, nil +} + +// LoadOrCreate loads the identity in dir, creating and saving one if absent. +// It is idempotent: an existing identity is never regenerated. +func LoadOrCreate(dir string) (Identity, error) { + if _, err := os.Stat(filepath.Join(dir, privName)); err == nil { + return Load(dir) + } else if !os.IsNotExist(err) { + return Identity{}, err + } + id, err := Generate() + if err != nil { + return Identity{}, err + } + return id, id.Save(dir) +} diff --git a/internal/identity/identity_test.go b/internal/identity/identity_test.go new file mode 100644 index 0000000..3dd9dbd --- /dev/null +++ b/internal/identity/identity_test.go @@ -0,0 +1,51 @@ +package identity + +import ( + "crypto/ed25519" + "testing" +) + +func TestRoundTripAndIdempotent(t *testing.T) { + dir := t.TempDir() + + id, err := LoadOrCreate(dir) + if err != nil { + t.Fatal(err) + } + if id.Fingerprint() == "" { + t.Fatal("empty fingerprint") + } + + // Load reproduces the same identity. + got, err := Load(dir) + if err != nil { + t.Fatal(err) + } + if got.Fingerprint() != id.Fingerprint() { + t.Fatalf("fingerprint changed on load: %s != %s", got.Fingerprint(), id.Fingerprint()) + } + + // LoadOrCreate must NOT regenerate an existing identity. + again, err := LoadOrCreate(dir) + if err != nil { + t.Fatal(err) + } + if again.Fingerprint() != id.Fingerprint() { + t.Fatal("LoadOrCreate regenerated an existing identity") + } + + // The loaded key actually signs/verifies. + msg := []byte("devbox") + sig := ed25519.Sign(again.Priv, msg) + if !ed25519.Verify(again.Pub, msg, sig) { + t.Fatal("sign/verify failed for loaded key") + } +} + +func TestFingerprintDiffersPerKey(t *testing.T) { + a, _ := Generate() + b, _ := Generate() + if a.Fingerprint() == b.Fingerprint() { + t.Fatal("distinct keys produced identical fingerprints") + } +}