From f6e1f91d67cb949bceb71089a657a10b1cd7a75c Mon Sep 17 00:00:00 2001 From: shoemoney Date: Mon, 22 Jun 2026 23:30:01 -0500 Subject: [PATCH] =?UTF-8?q?feat(M2):=20wire=20protocol=20foundation=20?= =?UTF-8?q?=F0=9F=94=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pkg/proto: hub<->device wire types + endpoint paths (join/publish/have/blob/push/head/metrics) - manifest: Marshal/Unmarshal (JSON); ID = BLAKE3 of canonical bytes = blob key = snapshot id - meta: bearer-token column + IssueBearer/DeviceByBearer + Count (for /metrics) - identity: FingerprintOf(pubkey) so hub derives the same device id the device does --- internal/hub/meta/meta.go | 32 +++++++++++++- internal/identity/identity.go | 10 ++++- internal/manifest/manifest.go | 26 ++++++++---- pkg/proto/proto.go | 79 +++++++++++++++++++++++++++++++++++ 4 files changed, 137 insertions(+), 10 deletions(-) create mode 100644 pkg/proto/proto.go diff --git a/internal/hub/meta/meta.go b/internal/hub/meta/meta.go index f39635d..0f6db51 100644 --- a/internal/hub/meta/meta.go +++ b/internal/hub/meta/meta.go @@ -19,6 +19,7 @@ CREATE TABLE IF NOT EXISTS devices ( id TEXT PRIMARY KEY, name TEXT NOT NULL, pubkey BLOB NOT NULL, + bearer TEXT, last_seen INTEGER, revoked INTEGER NOT NULL DEFAULT 0 ); @@ -98,12 +99,41 @@ func (d *DB) Revoked(id string) (bool, error) { return revoked != 0, nil } -// Revoke marks a device revoked; its access ends immediately. +// Revoke marks a device revoked; its access (and bearer) ends immediately. func (d *DB) Revoke(id string) error { _, err := d.sql.Exec(`UPDATE devices SET revoked=1 WHERE id=?`, id) return err } +// IssueBearer sets a device's bearer token (used to authenticate requests). +func (d *DB) IssueBearer(deviceID, bearer string) error { + _, err := d.sql.Exec(`UPDATE devices SET bearer=? WHERE id=?`, bearer, deviceID) + return err +} + +// DeviceByBearer resolves a bearer token to a non-revoked device id. +func (d *DB) DeviceByBearer(bearer string) (id string, ok bool, err error) { + if bearer == "" { + return "", false, nil + } + err = d.sql.QueryRow(`SELECT id FROM devices WHERE bearer=? AND revoked=0`, bearer).Scan(&id) + if errors.Is(err, sql.ErrNoRows) { + return "", false, nil + } + if err != nil { + return "", false, err + } + return id, true, nil +} + +// CountDevices, CountShares, CountSnapshots, CountChunks back the /metrics page. +func (d *DB) Count(table string) (int64, error) { + var n int64 + // table is a fixed internal constant, never user input. + err := d.sql.QueryRow(`SELECT COUNT(*) FROM ` + table).Scan(&n) + return n, err +} + // --- tokens -------------------------------------------------------------- // CreateToken stores a join token hash with an optional expiry (0 = none). diff --git a/internal/identity/identity.go b/internal/identity/identity.go index b51b591..99280fd 100644 --- a/internal/identity/identity.go +++ b/internal/identity/identity.go @@ -35,8 +35,14 @@ func Generate() (Identity, error) { // 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 + return FingerprintOf(id.Pub) +} + +// FingerprintOf returns the device id (16 hex chars) for a public key. The hub +// uses this to derive the same device id the device computes for itself. +func FingerprintOf(pub ed25519.PublicKey) string { + sum := sha256.Sum256(pub) + return hex.EncodeToString(sum[:8]) } // Save writes the keypair under dir atomically (private key 0600, dir 0700). diff --git a/internal/manifest/manifest.go b/internal/manifest/manifest.go index 6c412e2..0d5a1ff 100644 --- a/internal/manifest/manifest.go +++ b/internal/manifest/manifest.go @@ -4,12 +4,12 @@ package manifest import ( + "encoding/json" "fmt" "io/fs" "os" "path/filepath" "sort" - "strings" "git.shoemoney.ai/shoemoney/devbox/internal/chunk" "git.shoemoney.ai/shoemoney/devbox/internal/ignore" @@ -97,13 +97,25 @@ func Build(root string, ig *ignore.Matcher, guard *secret.Guard) (Manifest, []st return Manifest{Entries: entries}, blocked, nil } -// ID is the content address of the manifest (BLAKE3 of its canonical form). +// Marshal returns the manifest's canonical JSON bytes. Build sorts Entries, so +// this is deterministic and serves as the content-addressed manifest blob. +func (m Manifest) Marshal() ([]byte, error) { + return json.Marshal(m) +} + +// Unmarshal parses manifest bytes produced by Marshal. +func Unmarshal(b []byte) (Manifest, error) { + var m Manifest + err := json.Unmarshal(b, &m) + return m, err +} + +// ID is the content address of the manifest (BLAKE3 of its canonical bytes). It +// is the blob key the manifest is stored under and the id of the snapshot it +// represents. func (m Manifest) ID() string { - var b strings.Builder - for _, e := range m.Entries { - fmt.Fprintf(&b, "%s\x00%o\x00%d\x00%s\n", e.Path, e.Mode, e.Size, strings.Join(e.Chunks, ",")) - } - return chunk.Hash([]byte(b.String())) + b, _ := m.Marshal() // json.Marshal of this struct cannot fail + return chunk.Hash(b) } // Changes is the difference between two manifests. diff --git a/pkg/proto/proto.go b/pkg/proto/proto.go new file mode 100644 index 0000000..8735f4b --- /dev/null +++ b/pkg/proto/proto.go @@ -0,0 +1,79 @@ +// Package proto defines devbox's hub<->device wire types and endpoint paths. +// Transport is JSON over HTTP (blobs are raw bytes). One TLS endpoint, bearer +// auth. WebSocket change events arrive in M3. +package proto + +// Endpoint paths (all under the hub base URL). +const ( + PathJoin = "/v1/join" // POST, no auth: redeem a join token, enroll a device + PathPublish = "/v1/publish" // POST, auth: create a share + PathHave = "/v1/have" // POST, auth: which chunk hashes is the hub missing? + PathBlob = "/v1/blob/" // PUT /v1/blob/{hash}, auth: upload one blob's bytes + PathPush = "/v1/push" // POST, auth: commit a snapshot + PathHead = "/v1/head" // GET ?share=, auth: current head snapshot id + PathMetrics = "/metrics" // GET, no auth: Prometheus text exposition +) + +// AuthHeader carries the device bearer token: "Authorization: Bearer ". +const AuthHeader = "Authorization" + +// JoinRequest enrolls a device by redeeming a one-time join token. +type JoinRequest struct { + Token string `json:"token"` + Name string `json:"name"` + Pubkey []byte `json:"pubkey"` // ed25519 public key +} + +// JoinResponse returns the device id and the bearer token for future requests. +type JoinResponse struct { + DeviceID string `json:"device_id"` + Bearer string `json:"bearer"` +} + +// PublishRequest creates a share owned by the calling device. +type PublishRequest struct { + Share string `json:"share"` +} + +// HaveRequest asks the hub which of these chunk hashes it does NOT already have. +type HaveRequest struct { + Hashes []string `json:"hashes"` +} + +// HaveResponse lists the hashes the hub is missing (and the client must upload). +type HaveResponse struct { + Missing []string `json:"missing"` +} + +// ChunkRef is a chunk a snapshot references. +type ChunkRef struct { + Hash string `json:"hash"` + Size int64 `json:"size"` +} + +// PushRequest commits a snapshot. The manifest blob (key = ManifestHash) and all +// referenced chunk blobs must already be uploaded via PathBlob. +type PushRequest struct { + Share string `json:"share"` + Parent string `json:"parent"` // client's last-known head ("" if none) + ManifestHash string `json:"manifest_hash"` // hash of the uploaded manifest blob + Chunks []ChunkRef `json:"chunks"` // every distinct chunk + size +} + +// PushResponse reports the new snapshot id and head. Conflict handling is M3 +// (Conflict is always false in M2's one-way push). +type PushResponse struct { + Snapshot string `json:"snapshot"` + Head string `json:"head"` + Conflict bool `json:"conflict"` +} + +// HeadResponse is the current head snapshot id of a share ("" if none). +type HeadResponse struct { + Head string `json:"head"` +} + +// Error is the JSON body returned for non-2xx responses. +type Error struct { + Error string `json:"error"` +}