Files
Behavision/agent/pkg/enrol/enrol.go
Suriyakumarvijayanayagam 5f83a1077d Enrolment hands out the broker CA, and now the PC keeps it
The server has always sent the broker's CA certificate in the enrolment
response, precisely so it never has to ship in an installer. Nothing on
the receiving end wrote it anywhere: the agent read the field under the
wrong name (ca_pem, the server says ca_cert) and the desktop app read it
correctly and dropped it. Every claimed PC therefore dialled
tls://mcp.loyaly.ai:8883 with the system trust store, the private CA
failed verification, and the agent reported 'the broker did not accept
this PC' - a TLS failure is indistinguishable from a refusal at that
layer. No real site could ever have published a visit.

Found by claiming this Mac as a real shop against production; fixed by
writing the CA to broker-ca.crt beside agent.json on both claim paths.
Verified: broker connected over TLS, camera pushed from head office,
engine streaming it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KGcjxF1cNLcuwc3DAPcnfj
2026-09-18 12:16:43 +05:30

114 lines
4.0 KiB
Go

// Package enrol links a PC to a shop, using the one-shot code an operator is
// given.
//
// It existed only inside the desktop app, which meant a HEADLESS install - a
// back-office PC with no window, the configuration the agent binary is for -
// could not be claimed at all. The only route was hand-editing agent.json,
// which is exactly the state the desktop's Setup screen was built to end.
//
// The endpoint behind this is deliberately unauthenticated: the PC doing it has
// nobody signed in yet, and requiring a login would mean shipping a password to
// every shop that installs the software.
package enrol
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
// Bootstrap is what the server hands back: which shop this PC is, and the
// credentials it needs to say so.
type Bootstrap struct {
ClientSlug string `json:"client_slug"`
SiteSlug string `json:"site_slug"`
SiteName string `json:"site_name"`
MQTTURL string `json:"mqtt_url"`
MQTTUser string `json:"mqtt_username"`
MQTTPass string `json:"mqtt_password"`
CACert string `json:"ca_cert,omitempty"`
AgentToken string `json:"agent_token"`
}
// Claim redeems an installation code.
//
// The code is read aloud down a phone and photographed off screens, so what is
// typed here can be as untidy as it needs to be: the server strips spaces,
// dashes and case at its end. Sending it as typed keeps ONE implementation of
// that normalisation, on the side that also issued the code - two would
// eventually disagree and hash to something the redeemer never produces.
func Claim(ctx context.Context, base, code string) (Bootstrap, error) {
var out Bootstrap
base = strings.TrimRight(base, "/")
if base == "" {
return out, fmt.Errorf("no server address configured (set cloud_base or BEHAVISION_CLOUD)")
}
body, err := json.Marshal(map[string]string{"site_token": code})
if err != nil {
return out, err
}
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
base+"/api/agent/enrol", bytes.NewReader(body))
if err != nil {
return out, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return out, fmt.Errorf("could not reach %s: %w", base, err)
}
defer resp.Body.Close()
blob, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if resp.StatusCode != http.StatusOK {
// The server answers unknown, expired and already-used identically on
// purpose - the difference only helps somebody guessing codes, and the
// operator's next step is the same in all three cases. Its own words
// are passed through rather than reworded here.
var e struct {
Message string `json:"message"`
}
_ = json.Unmarshal(blob, &e)
if e.Message != "" {
return out, fmt.Errorf("%s", e.Message)
}
return out, fmt.Errorf("head office: %s", resp.Status)
}
if err := json.Unmarshal(blob, &out); err != nil {
return out, err
}
if out.SiteSlug == "" || out.MQTTURL == "" {
return out, fmt.Errorf("head office returned an incomplete setup")
}
return out, nil
}
// SaveCA writes the broker's CA beside the agent config and returns its path.
//
// The server hands the CA out at enrolment precisely so it never has to be
// shipped in an installer - and for a while nothing on the receiving end
// wrote it anywhere. Every claimed PC then dialled tls://mcp.loyaly.ai:8883
// with the system trust store, the private CA failed verification, and the
// agent reported "the broker did not accept this PC" (a TLS failure is
// indistinguishable from a refusal at that layer). No real site could ever
// publish a visit. An empty CA returns "" so a deployment on a public
// certificate keeps working unchanged.
func SaveCA(pem, path string) (string, error) {
if strings.TrimSpace(pem) == "" {
return "", nil
}
if err := os.WriteFile(path, []byte(pem), 0o600); err != nil {
return "", fmt.Errorf("write broker CA: %w", err)
}
return path, nil
}