feat(M2): wire protocol foundation 🔌

- 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
This commit is contained in:
shoemoney 2026-06-22 23:30:01 -05:00
parent 3884f732b5
commit f6e1f91d67
4 changed files with 137 additions and 10 deletions

View file

@ -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).

View file

@ -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).

View file

@ -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).
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, ","))
// 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)
}
return chunk.Hash([]byte(b.String()))
// 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 {
b, _ := m.Marshal() // json.Marshal of this struct cannot fail
return chunk.Hash(b)
}
// Changes is the difference between two manifests.

79
pkg/proto/proto.go Normal file
View file

@ -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 <token>".
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"`
}