package wire import ( "crypto/sha256" "encoding/hex" "fmt" "regexp" "slices" "strconv" ) // Places (spec 2026-11-26-places-config.md, slice 1): a place is a named // destination the team confirmed. ProtocolPlaces adds what the runner can // reach (a hello's Reach: the CARLOS logins it may set a site up with and // the deploy keys it may publish with), the carlos CLI's health, a // publish dispatch and its publish and mint checks bound to the confirmed // place, and the coordinator's four place tools. Below it Encode drops the hello's fields and refuses the rest: // an older runner would publish to its own fixed account. // The place tools. places and site_status are read-only; propose_place // raises a card only an owner's tap confirms; publish_site raises the // publish card only the creator's tap answers. const ( ToolPlaces = "places" ToolProposePlace = "propose_place" ToolPublishSite = "publish_site" ToolSiteStatus = "site_status" ) // PlacesTools are ProtocolPlaces's coordinator tools. var PlacesTools = []string{ToolPlaces, ToolProposePlace, ToolPublishSite, ToolSiteStatus} // CardPlace asks an owner to confirm where a project's site goes: Options // are the candidates' ids, best first, then ChoiceNotNow; Card.Place says // what each one is, in words code derived. const CardPlace = "place" // Place kinds and adapters (slice 1: a site, on a CARLOS app). const ( PlaceSite = "site" AdapterCarlosApp = "carlos_app" PlaceProposed = "proposed" PlaceConfirmed = "confirmed" PlaceRetired = "retired" FlagshipConsole = "console.carloku.com" TitoConsole = "console.platform.tito.io" MaxReachLogins = 8 MaxReachAccounts = 20 MaxReachDeploys = 50 MaxPlaceOptions = 6 placeCandidateLen = 15 ) // Reach is what a runner's carlos can do, with no secret: Logins are the // consoles an owner's CLI login on it reaches and the accounts it owns // there (a site may be set up there); Deploys are the app deploy keys it // holds (a site may be published with one). Console is a host name. type Reach struct { Logins []ReachLogin `json:"logins"` Deploys []ReachDeploy `json:"deploys"` } // ReachLogin is one console the runner's carlos is signed in to and the // accounts it owns there. type ReachLogin struct { Console string `json:"console"` Accounts []ReachAccount `json:"accounts"` } // ReachAccount is one owned account: its name (for people) and its sqid // (its identity, what every command names). type ReachAccount struct { Name string `json:"name"` Sqid string `json:"sqid"` } // ReachDeploy is one deploy key of the runner's: the console, account // sqid and app it was minted for, its CARLOS name and fingerprint. Lost: // the runner asked CARLOS for it and does not hold it (the answer was // lost or unreadable, or it stopped before storing it): it may be live on // CARLOS. The runner keeps saying so until it holds a key for the app. type ReachDeploy struct { Console string `json:"console"` Account string `json:"account"` App string `json:"app"` Name string `json:"name"` Fingerprint string `json:"fingerprint,omitempty"` Lost bool `json:"lost,omitempty"` } // CardPlaceView is a place card's proposal: the kind, the project and the // candidates in the order the card offers them. type CardPlaceView struct { Kind string `json:"kind"` Project string `json:"project"` Candidates []PlaceCandidate `json:"candidates"` } // PlaceCandidate is one destination a runner can reach: its id (what a // tool and a tap name), the console host and its label, and the account. type PlaceCandidate struct { ID string `json:"id"` Console string `json:"console"` ConsoleLabel string `json:"console_label"` Account string `json:"account"` Sqid string `json:"sqid"` } // The carlos CLI's health (ToolHealth.Carlos) and the oldest release whose // deploy and devbox share accept the preview's security headers. const ( CarlosOK = "ok" CarlosOutdated = "outdated" CarlosMissing = "missing" MinCarlos = "v0.43.0" // ReasonCarlosOutdated ends a preview or a publish whose runner's // carlos is unreadable or older than MinCarlos, before anything is // built or sent. ReasonCarlosOutdated = "carlos_outdated" ) var ( consoleHost = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$`) accountName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._@+-]{0,99}$`) accountSqid = regexp.MustCompile(`^[abcdefghjkmnpqrstuvwxyz]{3,16}$`) carlosSemver = regexp.MustCompile(`^v([0-9]{1,4})\.([0-9]{1,4})\.([0-9]{1,4})$`) candidateID = regexp.MustCompile(`^pc_[0-9a-f]{12}$`) keyName = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?$`) fingerprint = regexp.MustCompile(`^[0-9a-f]{16}$`) ) // ValidConsoleHost reports whether host is a console's host name (no // scheme, port or path). func ValidConsoleHost(host string) bool { return len(host) <= 253 && consoleHost.MatchString(host) } // ValidAccountName reports whether name may be shown as an account's name. func ValidAccountName(name string) bool { return accountName.MatchString(name) } // ValidSqid reports whether s is a CARLOS account sqid. func ValidSqid(s string) bool { return accountSqid.MatchString(s) } // ValidCandidateID reports whether id is a place candidate's id. func ValidCandidateID(id string) bool { return candidateID.MatchString(id) } // ValidDeployName reports whether n is a deploy key's CARLOS name. func ValidDeployName(n string) bool { return keyName.MatchString(n) } // ConsoleOrigin is a console host's https origin. func ConsoleOrigin(host string) string { return "https://" + host } // CandidateID is the id of the destination console and sqid: stable, // derived by code, never chosen by a model. func CandidateID(console, sqid string) string { sum := sha256.Sum256([]byte("place-candidate/v1\n" + console + "\n" + sqid)) return "pc_" + hex.EncodeToString(sum[:])[:placeCandidateLen-3] } // SiteDestination is the hash a publish's tap, dispatch, final check and // deploy are bound to: the console, the account's sqid and name, and the // app, in a versioned line. func SiteDestination(console, sqid, name, app string) string { sum := sha256.Sum256([]byte("site-destination/v1\n" + console + "\n" + sqid + "\n" + name + "\n" + app)) return hex.EncodeToString(sum[:]) } var destinationHash = regexp.MustCompile(`^[0-9a-f]{64}$`) // ValidDestination reports whether d is a SiteDestination. func ValidDestination(d string) bool { return destinationHash.MatchString(d) } // CarlosAtLeast reports whether version (vX.Y.Z) is at least min; an // unreadable one never is. func CarlosAtLeast(version, min string) bool { a, b := carlosSemver.FindStringSubmatch(version), carlosSemver.FindStringSubmatch(min) if a == nil || b == nil { return false } for i := 1; i <= 3; i++ { x, _ := strconv.Atoi(a[i]) y, _ := strconv.Atoi(b[i]) if x != y { return x > y } } return true } // ValidCarlosVersion reports whether v is a carlos release version. func ValidCarlosVersion(v string) bool { return carlosSemver.MatchString(v) } // ConsoleLabel is a console's name for people: Carloku and Tito by name, // any other console by its host. func ConsoleLabel(host string) string { switch host { case FlagshipConsole: return "Carloku" case TitoConsole: return "Tito" } return host } // validReach reports whether a runner's reach is in bounds: valid hosts, // names and sqids, no console twice, no account twice in one console, no // key twice. func validReach(r Reach) bool { if len(r.Logins) > MaxReachLogins || len(r.Deploys) > MaxReachDeploys { return false } consoles := map[string]bool{} for _, l := range r.Logins { if !ValidConsoleHost(l.Console) || consoles[l.Console] || len(l.Accounts) > MaxReachAccounts { return false } consoles[l.Console] = true sqids := map[string]bool{} for _, a := range l.Accounts { if !ValidAccountName(a.Name) || !ValidSqid(a.Sqid) || sqids[a.Sqid] { return false } sqids[a.Sqid] = true } } keys := map[string]bool{} for _, k := range r.Deploys { id := k.Console + " " + k.Account + " " + k.App + " " + k.Name if !ValidConsoleHost(k.Console) || !ValidSqid(k.Account) || !ValidSiteApp(k.App) || keys[id] || !keyName.MatchString(k.Name) || (k.Lost != (k.Fingerprint == "")) || k.Fingerprint != "" && !fingerprint.MatchString(k.Fingerprint) { return false } keys[id] = true } return true } // validCarlosHealth: a fixed state, with a version exactly when one was // read. func validCarlosHealth(state, version string) bool { switch state { case "": return version == "" case CarlosMissing: return version == "" case CarlosOK: return ValidCarlosVersion(version) && CarlosAtLeast(version, MinCarlos) case CarlosOutdated: return version == "" || ValidCarlosVersion(version) } return false } // WithoutPlaces drops a hello's reach and carlos health, in a copy. The // first hello is sent before the instance says its protocol: an older // instance's strict decoder would refuse them. It reports whether it // dropped anything. func WithoutPlaces(h *Hello) bool { if h.Capabilities == nil || h.Capabilities.Reach == nil && (h.Capabilities.Tools == nil || h.Capabilities.Tools.Carlos == "" && h.Capabilities.Tools.CarlosVersion == "") { return false } c := *h.Capabilities c.Reach = nil if c.Tools != nil { t := *c.Tools t.Carlos, t.CarlosVersion = "", "" c.Tools = &t } h.Capabilities = &c return true } // downgradePlaces clears ProtocolPlaces's fields for an older peer and // refuses what it cannot carry: a publish dispatch (an older runner would // deploy to its fixed account), a publish check (an older instance would // decide it without the destination) and a place tool's call. func downgradePlaces(body any, protocol int) (bool, error) { switch v := body.(type) { case *Hello: return WithoutPlaces(v), nil case *ToolCall: if slices.Contains(PlacesTools, v.Name) { return false, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, v.Name, protocol) } case *DispatchCommand: if v.Specialist == SpecialistPublish { return false, fmt.Errorf("%w: a place-bound publish at protocol %d", ErrProtocol, protocol) } case *StepReport: if p := v.Publish; p != nil && p.DeployHeld { c := *p c.DeployHeld = false v.Publish = &c return true, nil } case *LeaseCheck: // A publish's final check is bound to its destination; an older // instance would decide a weaker one, so it is never asked. if v.Purpose == LeasePurposePublish || v.Purpose == LeasePurposeMint || v.Destination != "" { return false, fmt.Errorf("%w: a place-bound publish check at protocol %d", ErrProtocol, protocol) } } return false, nil }