oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package wire
2
3import (
4 "crypto/sha256"
5 "encoding/hex"
6 "fmt"
7 "regexp"
8 "slices"
9 "strconv"
10)
11
12// Places (spec 2026-11-26-places-config.md, slice 1): a place is a named
13// destination the team confirmed. ProtocolPlaces adds what the runner can
14// reach (a hello's Reach: the CARLOS logins it may set a site up with and
15// the deploy keys it may publish with), the carlos CLI's health, a
16// publish dispatch and its publish and mint checks bound to the confirmed
17// place, and the coordinator's four place tools. Below it Encode drops the hello's fields and refuses the rest:
18// an older runner would publish to its own fixed account.
19
20// The place tools. places and site_status are read-only; propose_place
21// raises a card only an owner's tap confirms; publish_site raises the
22// publish card only the creator's tap answers.
23const (
24 ToolPlaces = "places"
25 ToolProposePlace = "propose_place"
26 ToolPublishSite = "publish_site"
27 ToolSiteStatus = "site_status"
28)
29
30// PlacesTools are ProtocolPlaces's coordinator tools.
31var PlacesTools = []string{ToolPlaces, ToolProposePlace, ToolPublishSite, ToolSiteStatus}
32
33// CardPlace asks an owner to confirm where a project's site goes: Options
34// are the candidates' ids, best first, then ChoiceNotNow; Card.Place says
35// what each one is, in words code derived.
36const CardPlace = "place"
37
38// Place kinds and adapters (slice 1: a site, on a CARLOS app).
39const (
40 PlaceSite = "site"
41 AdapterCarlosApp = "carlos_app"
42 PlaceProposed = "proposed"
43 PlaceConfirmed = "confirmed"
44 PlaceRetired = "retired"
45 FlagshipConsole = "console.carloku.com"
46 TitoConsole = "console.platform.tito.io"
47 MaxReachLogins = 8
48 MaxReachAccounts = 20
49 MaxReachDeploys = 50
50 MaxPlaceOptions = 6
51 placeCandidateLen = 15
52)
53
54// Reach is what a runner's carlos can do, with no secret: Logins are the
55// consoles an owner's CLI login on it reaches and the accounts it owns
56// there (a site may be set up there); Deploys are the app deploy keys it
57// holds (a site may be published with one). Console is a host name.
58type Reach struct {
59 Logins []ReachLogin `json:"logins"`
60 Deploys []ReachDeploy `json:"deploys"`
61}
62
63// ReachLogin is one console the runner's carlos is signed in to and the
64// accounts it owns there.
65type ReachLogin struct {
66 Console string `json:"console"`
67 Accounts []ReachAccount `json:"accounts"`
68}
69
70// ReachAccount is one owned account: its name (for people) and its sqid
71// (its identity, what every command names).
72type ReachAccount struct {
73 Name string `json:"name"`
74 Sqid string `json:"sqid"`
75}
76
77// ReachDeploy is one deploy key of the runner's: the console, account
78// sqid and app it was minted for, its CARLOS name and fingerprint. Lost:
79// the runner asked CARLOS for it and does not hold it (the answer was
80// lost or unreadable, or it stopped before storing it): it may be live on
81// CARLOS. The runner keeps saying so until it holds a key for the app.
82type ReachDeploy struct {
83 Console string `json:"console"`
84 Account string `json:"account"`
85 App string `json:"app"`
86 Name string `json:"name"`
87 Fingerprint string `json:"fingerprint,omitempty"`
88 Lost bool `json:"lost,omitempty"`
89}
90
91// CardPlaceView is a place card's proposal: the kind, the project and the
92// candidates in the order the card offers them.
93type CardPlaceView struct {
94 Kind string `json:"kind"`
95 Project string `json:"project"`
96 Candidates []PlaceCandidate `json:"candidates"`
97}
98
99// PlaceCandidate is one destination a runner can reach: its id (what a
100// tool and a tap name), the console host and its label, and the account.
101type PlaceCandidate struct {
102 ID string `json:"id"`
103 Console string `json:"console"`
104 ConsoleLabel string `json:"console_label"`
105 Account string `json:"account"`
106 Sqid string `json:"sqid"`
107}
108
109// The carlos CLI's health (ToolHealth.Carlos) and the oldest release whose
110// deploy and devbox share accept the preview's security headers.
111const (
112 CarlosOK = "ok"
113 CarlosOutdated = "outdated"
114 CarlosMissing = "missing"
115 MinCarlos = "v0.43.0"
116 // ReasonCarlosOutdated ends a preview or a publish whose runner's
117 // carlos is unreadable or older than MinCarlos, before anything is
118 // built or sent.
119 ReasonCarlosOutdated = "carlos_outdated"
120)
121
122var (
123 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])?)+$`)
124 accountName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._@+-]{0,99}$`)
125 accountSqid = regexp.MustCompile(`^[abcdefghjkmnpqrstuvwxyz]{3,16}$`)
126 carlosSemver = regexp.MustCompile(`^v([0-9]{1,4})\.([0-9]{1,4})\.([0-9]{1,4})$`)
127 candidateID = regexp.MustCompile(`^pc_[0-9a-f]{12}$`)
128 keyName = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?$`)
129 fingerprint = regexp.MustCompile(`^[0-9a-f]{16}$`)
130)
131
132// ValidConsoleHost reports whether host is a console's host name (no
133// scheme, port or path).
134func ValidConsoleHost(host string) bool { return len(host) <= 253 && consoleHost.MatchString(host) }
135
136// ValidAccountName reports whether name may be shown as an account's name.
137func ValidAccountName(name string) bool { return accountName.MatchString(name) }
138
139// ValidSqid reports whether s is a CARLOS account sqid.
140func ValidSqid(s string) bool { return accountSqid.MatchString(s) }
141
142// ValidCandidateID reports whether id is a place candidate's id.
143func ValidCandidateID(id string) bool { return candidateID.MatchString(id) }
144
145// ValidDeployName reports whether n is a deploy key's CARLOS name.
146func ValidDeployName(n string) bool { return keyName.MatchString(n) }
147
148// ConsoleOrigin is a console host's https origin.
149func ConsoleOrigin(host string) string { return "https://" + host }
150
151// CandidateID is the id of the destination console and sqid: stable,
152// derived by code, never chosen by a model.
153func CandidateID(console, sqid string) string {
154 sum := sha256.Sum256([]byte("place-candidate/v1\n" + console + "\n" + sqid))
155 return "pc_" + hex.EncodeToString(sum[:])[:placeCandidateLen-3]
156}
157
158// SiteDestination is the hash a publish's tap, dispatch, final check and
159// deploy are bound to: the console, the account's sqid and name, and the
160// app, in a versioned line.
161func SiteDestination(console, sqid, name, app string) string {
162 sum := sha256.Sum256([]byte("site-destination/v1\n" + console + "\n" + sqid + "\n" + name + "\n" + app))
163 return hex.EncodeToString(sum[:])
164}
165
166var destinationHash = regexp.MustCompile(`^[0-9a-f]{64}$`)
167
168// ValidDestination reports whether d is a SiteDestination.
169func ValidDestination(d string) bool { return destinationHash.MatchString(d) }
170
171// CarlosAtLeast reports whether version (vX.Y.Z) is at least min; an
172// unreadable one never is.
173func CarlosAtLeast(version, min string) bool {
174 a, b := carlosSemver.FindStringSubmatch(version), carlosSemver.FindStringSubmatch(min)
175 if a == nil || b == nil {
176 return false
177 }
178 for i := 1; i <= 3; i++ {
179 x, _ := strconv.Atoi(a[i])
180 y, _ := strconv.Atoi(b[i])
181 if x != y {
182 return x > y
183 }
184 }
185 return true
186}
187
188// ValidCarlosVersion reports whether v is a carlos release version.
189func ValidCarlosVersion(v string) bool { return carlosSemver.MatchString(v) }
190
191// ConsoleLabel is a console's name for people: Carloku and Tito by name,
192// any other console by its host.
193func ConsoleLabel(host string) string {
194 switch host {
195 case FlagshipConsole:
196 return "Carloku"
197 case TitoConsole:
198 return "Tito"
199 }
200 return host
201}
202
203// validReach reports whether a runner's reach is in bounds: valid hosts,
204// names and sqids, no console twice, no account twice in one console, no
205// key twice.
206func validReach(r Reach) bool {
207 if len(r.Logins) > MaxReachLogins || len(r.Deploys) > MaxReachDeploys {
208 return false
209 }
210 consoles := map[string]bool{}
211 for _, l := range r.Logins {
212 if !ValidConsoleHost(l.Console) || consoles[l.Console] || len(l.Accounts) > MaxReachAccounts {
213 return false
214 }
215 consoles[l.Console] = true
216 sqids := map[string]bool{}
217 for _, a := range l.Accounts {
218 if !ValidAccountName(a.Name) || !ValidSqid(a.Sqid) || sqids[a.Sqid] {
219 return false
220 }
221 sqids[a.Sqid] = true
222 }
223 }
224 keys := map[string]bool{}
225 for _, k := range r.Deploys {
226 id := k.Console + " " + k.Account + " " + k.App + " " + k.Name
227 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) {
228 return false
229 }
230 keys[id] = true
231 }
232 return true
233}
234
235// validCarlosHealth: a fixed state, with a version exactly when one was
236// read.
237func validCarlosHealth(state, version string) bool {
238 switch state {
239 case "":
240 return version == ""
241 case CarlosMissing:
242 return version == ""
243 case CarlosOK:
244 return ValidCarlosVersion(version) && CarlosAtLeast(version, MinCarlos)
245 case CarlosOutdated:
246 return version == "" || ValidCarlosVersion(version)
247 }
248 return false
249}
250
251// WithoutPlaces drops a hello's reach and carlos health, in a copy. The
252// first hello is sent before the instance says its protocol: an older
253// instance's strict decoder would refuse them. It reports whether it
254// dropped anything.
255func WithoutPlaces(h *Hello) bool {
256 if h.Capabilities == nil || h.Capabilities.Reach == nil && (h.Capabilities.Tools == nil || h.Capabilities.Tools.Carlos == "" && h.Capabilities.Tools.CarlosVersion == "") {
257 return false
258 }
259 c := *h.Capabilities
260 c.Reach = nil
261 if c.Tools != nil {
262 t := *c.Tools
263 t.Carlos, t.CarlosVersion = "", ""
264 c.Tools = &t
265 }
266 h.Capabilities = &c
267 return true
268}
269
270// downgradePlaces clears ProtocolPlaces's fields for an older peer and
271// refuses what it cannot carry: a publish dispatch (an older runner would
272// deploy to its fixed account), a publish check (an older instance would
273// decide it without the destination) and a place tool's call.
274func downgradePlaces(body any, protocol int) (bool, error) {
275 switch v := body.(type) {
276 case *Hello:
277 return WithoutPlaces(v), nil
278 case *ToolCall:
279 if slices.Contains(PlacesTools, v.Name) {
280 return false, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, v.Name, protocol)
281 }
282 case *DispatchCommand:
283 if v.Specialist == SpecialistPublish {
284 return false, fmt.Errorf("%w: a place-bound publish at protocol %d", ErrProtocol, protocol)
285 }
286 case *StepReport:
287 if p := v.Publish; p != nil && p.DeployHeld {
288 c := *p
289 c.DeployHeld = false
290 v.Publish = &c
291 return true, nil
292 }
293 case *LeaseCheck:
294 // A publish's final check is bound to its destination; an older
295 // instance would decide a weaker one, so it is never asked.
296 if v.Purpose == LeasePurposePublish || v.Purpose == LeasePurposeMint || v.Destination != "" {
297 return false, fmt.Errorf("%w: a place-bound publish check at protocol %d", ErrProtocol, protocol)
298 }
299 }
300 return false, nil
301}
302