Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ instead.
| | |
|---|---|
| `work login <email>` | Sign in (device code → your browser → your Google account). The email picks your organization; leave it off only for a personal address that belongs to none |
| `work bus enroll [name]` | Put this machine on your own private party-line bus, so the Claude sessions on your laptop and your box can message each other (and nobody else's). Defaults to this computer's name; run it again to rotate the token |
| `work` / `work <box>` | Wake the box if needed, attach its `work` tmux session |
| `work list` | Your boxes and their state |
| `work code <box> [dir]` | VS Code on this machine, Remote-SSH'd into the box |
Expand Down
123 changes: 123 additions & 0 deletions bus.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package main

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)

// Party-line is the message bus Claude sessions use to talk to each other.
// It is multi-tenant: a machine enrolls once with its owner's sign-in (the same
// token `work login` holds) and gets its own node token, so a person's laptop
// and box share a bus with each other and with nobody else.

func partyLineURL() string {
if u := os.Getenv("WORK_PARTY_LINE_URL"); u != "" {
return strings.TrimRight(u, "/")
}
return "https://party-line.jumpstartlab.com"
}

// partyLineDir is where the party-line client looks for a machine's token.
func partyLineDir() string {
dir := os.Getenv("XDG_CONFIG_HOME")
if dir == "" {
home, _ := os.UserHomeDir()
dir = filepath.Join(home, ".config")
}
return filepath.Join(dir, "party-line")
}

var machineName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)

// defaultMachine is this computer's short host name, lowercased.
func defaultMachine() string {
h, _ := os.Hostname()
h = strings.ToLower(strings.SplitN(h, ".", 2)[0])
return strings.Trim(regexp.MustCompile(`[^a-z0-9-]+`).ReplaceAllString(h, "-"), "-")
}

// busEnroll enrolls this machine on party-line as the signed-in person and
// writes its node token. Running it again rotates the token.
func busEnroll(machine string) error {
if machine == "" {
machine = defaultMachine()
}
if !machineName.MatchString(machine) {
return fmt.Errorf("%q is not a usable machine name (lowercase letters, digits and dashes)", machine)
}
tok, err := accessToken()
if err != nil {
return err
}
body, _ := json.Marshal(map[string]string{"machine": machine})
req, _ := http.NewRequest("POST", partyLineURL()+"/api/v1/enrollments", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+tok)
req.Header.Set("Content-Type", "application/json")
resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
if err != nil {
return fmt.Errorf("party-line unreachable: %w", err)
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
var out struct {
OK bool `json:"ok"`
Machine string `json:"machine"`
Token string `json:"token"`
Error string `json:"error"`
Tenant struct {
Slug string `json:"slug"`
} `json:"tenant"`
}
_ = json.Unmarshal(raw, &out)
if resp.StatusCode/100 != 2 || out.Token == "" {
msg := out.Error
if msg == "" {
msg = strings.TrimSpace(string(raw))
if len(msg) > 200 {
msg = msg[:200]
}
}
return fmt.Errorf("party-line refused enrollment (HTTP %d): %s", resp.StatusCode, msg)
}
if out.Machine != "" {
machine = out.Machine
}
dir := partyLineDir()
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
path := filepath.Join(dir, machine+".env")
env := fmt.Sprintf("PARTY_LINE_URL=%s\nNODE_TOKEN=%s\nNODE_MACHINE=%s\n", partyLineURL(), out.Token, machine)
if err := os.WriteFile(path, []byte(env), 0o600); err != nil {
return err
}
if err := os.Chmod(path, 0o600); err != nil { // WriteFile keeps an existing file's mode
return err
}
tenant := ""
if out.Tenant.Slug != "" {
tenant = " (tenant " + out.Tenant.Slug + ")"
}
fmt.Printf("Enrolled %s on party-line%s; token in %s.\n", machine, tenant, path)
return nil
}

func bus(args []string) error {
if len(args) == 0 || args[0] != "enroll" {
return errors.New("usage: work bus enroll [machine]")
}
machine := ""
if len(args) > 1 {
machine = args[1]
}
return busEnroll(machine)
}
3 changes: 3 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ func run(args []string) error {
dir = args[2]
}
return code(args[1], dir)
case "bus":
return bus(args[1:])
case "doctor":
return doctor()
case "version", "--version":
Expand Down Expand Up @@ -88,6 +90,7 @@ func run(args []string) error {

const usage = `usage: work [<box>] open your box (wakes it if asleep)
work login <email> sign in with your own work email
work bus enroll [name] put this machine on your private party-line bus
work list your boxes and their state
work code <box> [dir] VS Code here, Remote-SSH'd into the box
work doctor check the whole path
Expand Down
52 changes: 52 additions & 0 deletions work_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,55 @@ func TestStayConnectedDoesNotLoopOnARefusedLogin(t *testing.T) {
t.Fatal("a first attempt that fails at once must be an error, not a retry loop")
}
}

func TestBusEnrollWritesTheNodeToken(t *testing.T) {
withToken(t, `{"email":"guest@example.com"}`)
var got map[string]string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/enrollments" || r.Header.Get("Authorization") != "Bearer h.eyJlbWFpbCI6Imd1ZXN0QGV4YW1wbGUuY29tIn0.s" {
t.Errorf("unexpected request %s %q", r.URL.Path, r.Header.Get("Authorization"))
}
_ = json.NewDecoder(r.Body).Decode(&got)
w.Write([]byte(`{"ok":true,"machine":"guest-vm","token":"nt-123","tenant":{"slug":"guest"}}`))
}))
defer srv.Close()
t.Setenv("WORK_PARTY_LINE_URL", srv.URL)
if err := busEnroll("guest-vm"); err != nil {
t.Fatal(err)
}
if got["machine"] != "guest-vm" {
t.Fatalf("sent %v", got)
}
p := filepath.Join(partyLineDir(), "guest-vm.env")
b, err := os.ReadFile(p)
if err != nil {
t.Fatal(err)
}
want := "PARTY_LINE_URL=" + srv.URL + "\nNODE_TOKEN=nt-123\nNODE_MACHINE=guest-vm\n"
if string(b) != want {
t.Fatalf("env file:\n%s\nwant:\n%s", b, want)
}
if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o600 {
t.Fatalf("mode %v, want 0600", fi.Mode().Perm())
}
}

func TestBusEnrollReportsARefusal(t *testing.T) {
withToken(t, `{"email":"guest@example.com"}`)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte(`{"error":"enrollment is not open for this address"}`))
}))
defer srv.Close()
t.Setenv("WORK_PARTY_LINE_URL", srv.URL)
err := busEnroll("guest-vm")
if err == nil || !strings.Contains(err.Error(), "not open for this address") {
t.Fatalf("want the server's reason, got %v", err)
}
if _, statErr := os.Stat(filepath.Join(partyLineDir(), "guest-vm.env")); statErr == nil {
t.Fatal("a refused enrollment must not write a token file")
}
if busEnroll("Bad Name") == nil {
t.Fatal("bad machine name accepted")
}
}
Loading