package provision import ( "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" stdjson "encoding/json" "fmt" "regexp" "slices" "strings" "amadan.net/oficina/home/roster" ) // LabelPattern is Alta's label rule (§5): deliberately tighter than // Home's ValidLabel, so every derived host stays well inside DNS limits. var LabelPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{1,30}[a-z0-9]$`) // ReservedLabels are never offered to a new team. This is the one list // (a test pins it): a label becomes the first DNS label of every team // host and the team's name at Home, so it must never collide with a name // the suite or the platform already answers to (Paul, 2026-11-12). var ReservedLabels = map[string]bool{ // The suite's own canonical apps (docs.oficina.works and the rest), // which Home adopts as an existing team on its own path (Home // discussion 103), and the dashboard team they already carry. "oficina": true, // Every app's name, provisioned by Alta or not yet: a team called // "docs" would own docs.calls.oficina.works and read as an app. "docs": true, "sheets": true, "slides": true, "calendar": true, "calls": true, "memoria": true, "equipo": true, "fichas": true, "mapa": true, // The suite's and the platform's own hosts and paths. "api": true, "auth": true, "healthz": true, "static": true, "www": true, "id": true, "admin": true, "portero": true, "home": true, "alta": true, "base": true, "forget": true, } // LabelRefusal is the code a label is refused with at step 0, or "" for a // label Alta will offer. A label never holds "--": that is the shape // of IDNA's xn-- (punycode) labels, which would render as another name. func LabelRefusal(label string) string { switch { case !LabelPattern.MatchString(label): return "label-shape" case strings.Contains(label, "--"): return "label-double-hyphen" case ReservedLabels[label]: return "label-reserved" } return "" } // PublicDomain is the only public suffix Home's directory admits for a // team instance (internal/home directoryRouteAllowed). const PublicDomain = "oficina.works" // App is one Oficina app as Alta provisions it: the env prefix it reads, // whether it has roster mode, which SMTP prefixes its binary reads, and // whether it needs the platform relay. type App struct { // AdoptionOnly admits an existing canonical instance, without offering an // unimplemented recipe for fresh team instances. No app is adoption-only // since Equipo and Base gained recipes (team-bundle spec, slices 1–2); // the flag stays for the next app that is. AdoptionOnly bool // Seeded is an app with no Home roster mode whose owners are seeded // from its environment (EQUIPO_OWNERS, BASE_OWNER). It reaches // steps 11–12 through its seeded /api/team probe instead of a roster // (team-bundle spec §1.2), and its recipe writes the owner's address. Seeded bool // OwnOnly is an app offered only under profile own (team-bundle spec // §5.1 rule 3): its roster diverges from Home's, which is acceptable // only for Paul's own teams until it has roster mode. OwnOnly bool Slug string Name string Prefix string // Roster is true for an app with team (roster) mode on main. Only // those reach steps 11–12; the rest stop at 10 with their directory // row pending (§6). Roster bool // MailPrefixes are the _SMTP_* sets the binary reads, in its // own order. The mail walk writes the set the app declared; a set the // binary does not read leaves it without mail, which step 7 refuses. MailPrefixes []string // SubmitPrefix is the one prefix whose From the binary reads when it // is switched to CARLOS mail submission: it calls rastrillo's // mail.FromCarlos with this prefix's stem, so it reads only // MailFromKey(SubmitPrefix). CARLOS delivers the From under the stem // of the app's declared prefix, so a switched app declared under any // other prefix (Slides under SLIDES_SMTP, say) gets a From its binary // never reads, and step 7 refuses it. CARLOS_SMTP for every app but // Docs, which is declared and read as DOCS_SMTP. Required: an app // with none refuses every From. SubmitPrefix string // Relay is true when CARLOS_RELAY is a PLATFORM key (Calls). Relay bool // Store is true for an app whose instances may carry an object store // of their own (Slides: the private-storage policy). Its StoreKeys // are PLATFORM keys the audit admits, and never requires. Store bool // Dashboard is true for an app whose binary reads // OFICINA_DASHBOARD_TEAM (internal//dashboard.go): the own // profile names the team there. Dashboard bool } // Apps is the compiled registry, in Home's order (directory_runtime.go). var Apps = []App{ {Slug: "docs", Name: "Docs", Prefix: "DOCS", Roster: true, MailPrefixes: []string{"DOCS_SMTP"}, SubmitPrefix: "DOCS_SMTP", Dashboard: true}, {Slug: "sheets", Name: "Sheets", Prefix: "SHEETS", Roster: true, MailPrefixes: []string{"CARLOS_SMTP"}, SubmitPrefix: "CARLOS_SMTP", Dashboard: true}, {Slug: "slides", Name: "Slides", Prefix: "SLIDES", Roster: true, MailPrefixes: []string{"SLIDES_SMTP", "CARLOS_SMTP"}, SubmitPrefix: "CARLOS_SMTP", Dashboard: true, Store: true}, {Slug: "calendar", Name: "Calendar", Prefix: "CALENDAR", Roster: true, MailPrefixes: []string{"CALENDAR_SMTP", "CARLOS_SMTP"}, SubmitPrefix: "CARLOS_SMTP", Dashboard: true}, {Slug: "calls", Name: "Calls", Prefix: "CALLS", Roster: true, MailPrefixes: []string{"CALLS_SMTP", "CARLOS_SMTP"}, SubmitPrefix: "CARLOS_SMTP", Relay: true}, {Slug: "memoria", Name: "Memoria", Prefix: "MEMORIA", Roster: true, MailPrefixes: []string{"CARLOS_SMTP"}, SubmitPrefix: "CARLOS_SMTP"}, {Slug: "equipo", Name: "Equipo", Prefix: "EQUIPO", Seeded: true, OwnOnly: true, MailPrefixes: []string{"CARLOS_SMTP"}, SubmitPrefix: "CARLOS_SMTP"}, {Slug: "base", Name: "Base", Prefix: "BASE", Seeded: true, OwnOnly: true, MailPrefixes: []string{"CARLOS_SMTP"}, SubmitPrefix: "CARLOS_SMTP"}, } // ProvisioningApps are the apps with supported fresh-instance recipes. func ProvisioningApps() []App { var out []App for _, a := range Apps { if !a.AdoptionOnly { out = append(out, a) } } return out } // AppBySlug finds a registry app. func AppBySlug(slug string) (App, bool) { for _, a := range Apps { if a.Slug == slug { return a, true } } return App{}, false } // Slugs is the registry's slugs. func Slugs() []string { out := make([]string, len(Apps)) for i, a := range Apps { out[i] = a.Slug } return out } // SortApps orders apps as the registry does and drops unknowns. func SortApps(apps []string) []string { var out []string for _, a := range Apps { if slices.Contains(apps, a.Slug) { out = append(out, a.Slug) } } return out } // Hosts derives a team instance's two hostnames. func RouteHost(label, app, account string) string { return label + "-" + app + "." + account + ".oncarlos.com" } // PublicHost, PublicOrigin and ConsumerID name a team's public tuple. The // adoption label is the one exception to label.app: Home's canonical // tuple for the six existing instances is host .oficina.works and // consumer (homeop.CanonicalOrigin). Every other label is unchanged. func PublicHost(label, app string) string { if label == AdoptionLabel { return app + "." + PublicDomain } return label + "." + app + "." + PublicDomain } func PublicOrigin(label, app string) string { return "https://" + PublicHost(label, app) } func ConsumerID(label, app string) string { if label == AdoptionLabel { return app } return label + "-" + app } // AdoptionLabel is the directory label of the existing suite's team. It is // reserved (ReservedLabels), so no ordinary run reaches the canonical // answers above. const AdoptionLabel = "oficina" // Class is a recipe key's treatment (§5). type Class string const ( Generated Class = "generated" Set Class = "set" Platform Class = "platform" ) // Key is one recipe key. Value is known for SET keys only; a GENERATED // key's value exists only on its way to the console, sealed. type Key struct { Name string Class Class Value string Secret bool // OwnerAddress marks a SET key whose value is the owner's address // (the stopgap allowlist). After step 13 Alta no longer knows it. OwnerAddress bool // FromHome marks a GENERATED key whose value Home minted (the roster // bearer), fetched by exact replay of step 5. FromHome bool } // HomeConfig is the Home material every recipe carries: Alta's pinned // copies, none of them secret. type HomeConfig struct { Issuer string // credential origin, https://id.oficina.works Directory string // https://oficina.works KeysBase64 string // the assertion keys manifest, as ALTA_HOME_KEYS_BASE64 Provisioner string // the directory's provisioning public key, base64url } // Profile is a run's recipe variant (Paul, 2026-11-12). type Profile string const ( // ProfileOutside is the recipes as the design has them: for anyone // else's team (an outsider's), and the default. ProfileOutside Profile = "outside" // ProfileOwn is for Paul's own teams. It differs from outside only in // Calls' quality reports (on), each dashboard app's // OFICINA_DASHBOARD_TEAM (the label), and Memoria's AI pair, which the // audit admits once Paul has set it by hand (OperatorKeys). Alta never // holds or writes the TensorX key. ProfileOwn Profile = "own" ) // Profiles is every profile, in the order the run form offers them. var Profiles = []Profile{ProfileOutside, ProfileOwn} // RunOptions is what Paul chooses per run beside its apps, recorded on the // run and shown with its plan. type RunOptions struct { Profile Profile // Samples sets DOCS_SAMPLE_DOCUMENTS: a new person's Docs starts with // the sample documents. Separate from the profile, because only a // sample team gets it. Samples bool } // Normal is o with an unset profile read as outside; ok is false for a // profile Alta does not know. func (o RunOptions) Normal() (RunOptions, bool) { switch o.Profile { case "": o.Profile = ProfileOutside case ProfileOutside, ProfileOwn: default: return o, false } return o, true } // Inputs is what a recipe is built from. type Inputs struct { Label string // Account is the CARLOS account's sqid, for a value that names an // instance's platform host (Equipo's execution marker, OperatorKeys). Account string Owner string // empty once deleted (§4) TeamSQID string Record []byte // step 5's signed record (Docs) Home HomeConfig CallsZone string // RunOptions is the run's profile and samples choice. The zero value // is the outside recipe without samples. RunOptions } // Recipe is one app's GENERATED and SET keys. PLATFORM keys are added by // PlatformKeys once the walks have delivered them. func Recipe(app App, in Inputs) []Key { p := app.Prefix keys := []Key{ {Name: p + "_ORIGIN", Class: Set, Value: PublicOrigin(in.Label, app.Slug)}, {Name: p + "_INSTANCE_KEY", Class: Generated, Secret: true}, {Name: p + "_HOME_ISSUER", Class: Set, Value: in.Home.Issuer}, {Name: p + "_HOME_CONSUMER_ID", Class: Set, Value: ConsumerID(in.Label, app.Slug)}, {Name: p + "_HOME_KEYS_BASE64", Class: Set, Value: in.Home.KeysBase64}, {Name: p + "_HOME_DEK_BASE64", Class: Generated, Secret: true}, {Name: "HOME_DIRECTORY_ORIGIN", Class: Set, Value: in.Home.Directory}, } own := in.Profile == ProfileOwn if own && app.Dashboard { // The team's own dashboard feed in Home (home/dashboard): the // provider answers only for this team's name. keys = append(keys, Key{Name: "OFICINA_DASHBOARD_TEAM", Class: Set, Value: in.Label}) } switch app.Slug { case "docs": keys = append(keys, Key{Name: "DOCS_CONTENT_KEY", Class: Generated, Secret: true}, Key{Name: "DOCS_ALLOWED_ADDRESSES", Class: Set, Value: ""}, ) if in.Samples { // cmd/docs reads it permissively ("1", "true", "yes"; anything // else is off), and seeds each new person's list once. keys = append(keys, Key{Name: "DOCS_SAMPLE_DOCUMENTS", Class: Set, Value: "1"}) } keys = append(keys, teamKeys(p, in)...) case "sheets": // Team mode (oficina/sheets team-mode @ b0264ff): SHEETS_OWNERS is // not needed beside SHEETS_TEAM_*, so the owner is not written. keys = append(keys, Key{Name: "SHEETS_DEK", Class: Generated, Secret: true}) keys = append(keys, teamKeys(p, in)...) case "slides": // Uploads (Paul, 2026-11-12): Slides' app-wide private-storage // policy gives every instance Alta creates, under either profile, // its environment's own bucket at step 8, and CARLOS's objstore // walk delivers CARLOS_STORE_* into the environment. Those are // PLATFORM keys (StoreKeys): never written by Alta, admitted by // the audit, and optional, since an instance created before the // policy has none and its uploads answer 503. // Team mode (oficina/slides team-mode @ 80fd3c9, through Home's // teammode): SLIDES_ALLOWED_ADDRESSES is optional beside // SLIDES_TEAM_*, so the owner is not written. keys = append(keys, teamKeys(p, in)...) case "calendar": // Team mode (oficina/calendar #35, team-mode @ e8e509d, through // Home's teammode): CALENDAR_ALLOWED_ADDRESSES is optional beside // CALENDAR_TEAM_*, so the owner is not written. keys = append(keys, Key{Name: "CALENDAR_DEK", Class: Generated, Secret: true}) keys = append(keys, teamKeys(p, in)...) case "calls": // Team mode (oficina/meet #31, team-mode, through Home's // teammode; spec §16.9): CALLS_ALLOWED_ADDRESSES is optional // beside CALLS_TEAM_*, so the owner is not written. CARLOS_RELAY // stays PLATFORM, minted per environment. No CALLS_APNS_*: cmd/calls // does not read them, so a team's Calls has no push. keys = append(keys, Key{Name: "CALLS_DEK", Class: Generated, Secret: true}, Key{Name: "CALLS_ZONE", Class: Set, Value: in.CallsZone}, // A team's call-quality logs would land in the operator's // `carlos logs`; off until that team's owner and Paul agree, // and on for Paul's own teams. Key{Name: "CALLS_QUALITY_REPORTS", Class: Set, Value: qualityReports(own)}, ) keys = append(keys, teamKeys(p, in)...) case "memoria": // AI off: MEMORIA_AI, _TENSORX_KEY, _SIBLINGS, _SIBLING_TOKEN_* // and _ALLOW_LOGGED_MAIL are simply absent (Paul: AI is off, and // his key is never used). In both profiles: memoria refuses to // boot with MEMORIA_AI=on and no MEMORIA_TENSORX_KEY, and Alta // never holds the key, so an own team's AI is Paul's post-run // step (OperatorKeys). // Team mode (oficina/memoria #32, team-mode @ 88f6cec, through // Home's teammode): MEMORIA_OWNERS is optional beside // MEMORIA_TEAM_*, so the owner is not written. MEMORIA_TEAM is the // sibling transport's host label, which in team mode must be the // first label of MEMORIA_ORIGIN (team_siblings.go): both are the // team's label. keys = append(keys, Key{Name: "MEMORIA_DEK", Class: Generated, Secret: true}, Key{Name: "MEMORIA_TEAM", Class: Set, Value: in.Label}, ) keys = append(keys, teamKeys(p, in)...) case "equipo": // Seeded (team-bundle spec §1.2): no roster mode, so the owner is // written and Alta's wait rule keeps the address until this // environment is written. Execution is not written here: it is // Paul's post-run pair (OperatorKeys). The assistant host is the // label's own Base, written whether or not Base exists yet: // Equipo admits only that origin, so naming one not yet created is // harmless, and the value never depends on the run (plan rev 2). // No EQUIPO_AGENT_*: agent access for fresh teams is a follow-up. keys = append(keys, ownerKey("EQUIPO_OWNERS", in), Key{Name: "EQUIPO_ASSISTANT_HOSTS", Class: Set, Value: PublicOrigin(in.Label, "base")}, ) case "base": // Seeded, no Store (team-bundle spec §2.2): no BASE_PLATFORM_*, // BASE_APPS_DOMAIN or BASE_ASSERTION_KEY, so installs are off. // Base comes last (step 0, BaseRefusal): the team has every other // app, so the tile list is fixed and Ask always has its Equipo. keys = append(keys, ownerKey("BASE_OWNER", in), Key{Name: "BASE_NAME", Class: Set, Value: in.Label}, Key{Name: "BASE_SLUG", Class: Set, Value: in.Label}, Key{Name: "BASE_OFICINA_APPS", Class: Set, Value: BaseOficinaApps(in.Label)}, Key{Name: "BASE_EQUIPO_ORIGIN", Class: Set, Value: PublicOrigin(in.Label, "equipo")}, ) } return keys } // BaseOficinaApps is BASE_OFICINA_APPS for label: every other registry app // as id=origin, in registry order (Base internal/config/oficina.go). Base // is not in its own list: an unknown id refuses Base's boot. func BaseOficinaApps(label string) string { var parts []string for _, a := range Apps { if a.Slug != "base" { parts = append(parts, a.Slug+"="+PublicOrigin(label, a.Slug)) } } return strings.Join(parts, ",") } // BaseSlugMax is Base's longest BASE_SLUG (Base internal/config maxSlug). const BaseSlugMax = 19 // AppsRefusal is step 0's rule for the apps a run names, beside what the // team already has (active), under the run's profile: "" to proceed. func AppsRefusal(label string, apps []string, active map[string]bool, p Profile) string { has := func(slug string) bool { return active[slug] || slices.Contains(apps, slug) } for _, slug := range apps { app, ok := AppBySlug(slug) switch { case !ok, app.AdoptionOnly: return "unknown-app" case app.OwnOnly && p != ProfileOwn: return "app-own-only" } } if slices.Contains(apps, "base") { if len(label) > BaseSlugMax { return "label-too-long-for-base" } for _, a := range Apps { if a.Slug != "base" && !has(a.Slug) { return "base-needs-team-apps" } } } return "" } func qualityReports(own bool) string { if own { return "on" } return "off" } // OperatorKey is a key Paul sets by hand after a run, never Alta: the // audit admits it, under its profile, only beside every other key of the // app's OperatorKeys, with its kind and (for an env key) its value. type OperatorKey struct { Name string Secret bool Value string } // OperatorKeys is app's post-run group under in's profile. On an own // team: Memoria's AI (MEMORIA_AI=on and the TensorX key, both or // neither; memoria refuses to boot with one alone), and Equipo's // execution (team-bundle spec slice 3b: EQUIPO_EXECUTION_ENABLED=1 and // the marker inside the instance's own CARLOS directory, whose name is // its platform host; a path naming any other directory fails Equipo's // boot, and the exact value is what the audit admits). Outside teams // have none. func OperatorKeys(app App, in Inputs) []OperatorKey { if in.Profile != ProfileOwn { return nil } switch app.Slug { case "equipo": return []OperatorKey{ {Name: "EQUIPO_EXECUTION_ENABLED", Value: "1"}, {Name: "EQUIPO_EXECUTION_MARKER_PATH", Value: ExecutionMarkerPath(in.Label, in.Account)}, } case "memoria": default: return nil } return []OperatorKey{ {Name: "MEMORIA_AI", Value: "on"}, {Name: "MEMORIA_TENSORX_KEY", Secret: true}, } } // ExecutionMarkerPath is a team Equipo's EQUIPO_EXECUTION_MARKER_PATH: // under the instance's own /data/instances/, apart from its // database, as the canonical instance's is. func ExecutionMarkerPath(label, account string) string { return "/data/instances/" + RouteHost(label, "equipo", account) + "/execution/witness" } // profileWrites is every env key some run's choice writes into app's // environment for label beyond the outside recipe, with the exact value // it writes: a later run may take back out a key that is still exactly // Alta's own, and nothing else (a foreign value is an extra key). func profileWrites(app App, label string) map[string]string { base := map[string]bool{} for _, k := range Recipe(app, Inputs{Label: label}) { base[k.Name] = true } out := map[string]string{} for _, p := range Profiles { for _, k := range Recipe(app, Inputs{Label: label, RunOptions: RunOptions{Profile: p, Samples: true}}) { if !base[k.Name] && k.Class == Set { out[k.Name] = k.Value } } } return out } // OperatorState is how much of app's post-run group an environment holds. type OperatorState int const ( OperatorNone OperatorState = iota // no key of the group (or no group) OperatorPartial // some, not all OperatorWhole // all, each with its kind and value OperatorInvalid // all, but one has the wrong kind or value ) // operatorState reads an environment's keys (name → kind, value) against // group. func operatorState(group []OperatorKey, kind func(name string) (k, value string, ok bool)) OperatorState { held, bad := 0, false for _, g := range group { k, v, ok := kind(g.Name) if !ok { continue } held++ switch { case g.Secret && k != "secret", !g.Secret && k != "env", !g.Secret && v != g.Value: bad = true } } switch { case held == 0: return OperatorNone case held < len(group): return OperatorPartial case bad: return OperatorInvalid } return OperatorWhole } // ownerKey is a stopgap allowlist holding the owner's address, for an app // without roster mode (Track 1's shape). Every app has roster mode now, so // no recipe uses it; it stays so the address rules (§4: deleted once every // allowlist is written, retyped if needed again) keep one definition. func ownerKey(name string, in Inputs) Key { return Key{Name: name, Class: Set, Value: in.Owner, OwnerAddress: true} } // NeedsOwner reports whether app's recipe writes the owner's address. func NeedsOwner(app App) bool { for _, k := range Recipe(app, Inputs{}) { if k.OwnerAddress { return true } } return false } // teamKeys is a roster-mode app's

_TEAM_* five, as Docs and Sheets read // them: the team sqid, the directory, the signed provisioning record and // the directory's provisioning key (SET), and Home's roster bearer // (GENERATED by Home, sealed, fetched by exact replay of step 5). func teamKeys(p string, in Inputs) []Key { return []Key{ {Name: p + "_TEAM_ROSTER_TOKEN", Class: Generated, Secret: true, FromHome: true}, {Name: p + "_TEAM_ID", Class: Set, Value: in.TeamSQID}, {Name: p + "_TEAM_DIRECTORY_ORIGIN", Class: Set, Value: in.Home.Directory}, {Name: p + "_TEAM_PROVISIONING_BASE64", Class: Set, Value: base64.StdEncoding.EncodeToString(in.Record)}, {Name: p + "_TEAM_OPERATOR_KEYS_BASE64", Class: Set, Value: operatorKeys(in.Home.Provisioner)}, } } // TeamKeyNames is the names teamKeys produces for app: the

_TEAM_ five // an adoption must never write. func TeamKeyNames(app App) []string { keys := teamKeys(app.Prefix, Inputs{}) names := make([]string, len(keys)) for i, k := range keys { names[i] = k.Name } return names } // operatorKeys is

_TEAM_OPERATOR_KEYS_BASE64: the directory's // provisioning key as a one-entry []roster.Key, JSON, standard base64. func operatorKeys(public string) string { if public == "" { return "" } raw, err := base64.RawURLEncoding.DecodeString(public) if err != nil { return "" } sum := sha256.Sum256(raw) b, _ := stdjson.Marshal([]roster.Key{{ID: hex.EncodeToString(sum[:]), Public: public}}) return base64.StdEncoding.EncodeToString(b) } // ProvisionerKeys is the same key for roster.VerifyProvisioning. func ProvisionerKeys(public string) []roster.Key { raw, err := base64.RawURLEncoding.DecodeString(public) if err != nil { return nil } sum := sha256.Sum256(raw) return []roster.Key{{ID: hex.EncodeToString(sum[:]), Public: public}} } var smtpSuffixes = []string{"HOST", "PORT", "USER", "PASS", "FROM"} // SMTPKeys is a prefix's five. func SMTPKeys(prefix string) []string { out := make([]string, len(smtpSuffixes)) for i, s := range smtpSuffixes { out[i] = prefix + "_" + s } return out } var smtpKey = regexp.MustCompile(`^([A-Z][A-Z0-9_]*_SMTP)_(HOST|PORT|USER|PASS|FROM)$`) // mailFromKey is the From variable CARLOS delivers for an app switched to // platform mail submission. Its stem is the declared prefix without // _SMTP: CARLOS_SMTP gives CARLOS_MAIL_FROM, DOCS_SMTP gives // DOCS_MAIL_FROM (carlos internal/mail MailFromName). var mailFromKey = regexp.MustCompile(`^([A-Z][A-Z0-9_]*)_MAIL_FROM$`) // MailFromKey is the From variable a switched app's environment holds for // prefix, in place of SMTPKeys(prefix). "" for a prefix that does not end // in _SMTP, which CARLOS refuses to switch. func MailFromKey(prefix string) string { stem, ok := strings.CutSuffix(prefix, "_SMTP") if !ok || stem == "" { return "" } return stem + "_MAIL_FROM" } // PlatformState is what the walks have delivered into one environment. type PlatformState struct { // Keys are the PLATFORM keys present that this app reads. Keys []string // Missing is the PLATFORM keys still to arrive. Missing []string // WrongPrefix names a prefix delivered that the binary does not read: // five SMTP variables outside MailPrefixes, or a From whose stem is // not SubmitPrefix's. Either is a declaration under the wrong prefix // (§5, §6 step 0). WrongPrefix string // Store is the object-store keys present, for an app with a Store. // Kept apart from Keys: the store arrives at step 8, after step 7 // records the binding, and is never waited for. Store []string } // StoreKey is one object-store coordinate as CARLOS's objstore walk // delivers it (internal/objstore EnvNames and writeEnv, prefix // CARLOS_STORE, the one Slides' declaration and rastrillo's // blobs.S3FromEnv use): bucket and region as env, both key halves sealed. // The endpoint is delivered only by a deployment that has one. type StoreKey struct { Name string Secret bool Optional bool } // StoreKeys is the set, all-or-none but for the endpoint. Alta's console // guard refuses any write of them (console.PlatformManaged). var StoreKeys = []StoreKey{ {Name: "CARLOS_STORE_BUCKET"}, {Name: "CARLOS_STORE_REGION"}, {Name: "CARLOS_STORE_ENDPOINT", Optional: true}, {Name: "CARLOS_STORE_ACCESS_KEY", Secret: true}, {Name: "CARLOS_STORE_SECRET_KEY", Secret: true}, } // PlatformKeys classifies an environment's present key names against // what the app's binary reads. // // Mail arrives one of two ways. An app on SMTP gets the five // _SMTP_* of its declared prefix. An app switched to CARLOS mail // submission gets only _MAIL_FROM, and its instances send through // the box's mailer with no credential at all: the agent adds // CARLOS_MAIL=submit and the control socket at start, never the bundle. // The binary reads exactly one From, MailFromKey(app.SubmitPrefix); a // From under any other stem is a declaration under the wrong prefix, // refused like a wrong SMTP prefix, because the switched binary would // find no From and refuse to start. Either channel is mail; the From // alone is not waited past for the five. During a switch-on CARLOS // delivers the From before it takes the five out, and during a // switch-off the five before it takes the From out, so an environment // caught between holds both and every one present is admitted. func PlatformKeys(app App, present map[string]bool) PlatformState { var st PlatformState prefixes := map[string]int{} submit := map[string]bool{} for k := range present { if m := smtpKey.FindStringSubmatch(k); m != nil { prefixes[m[1]]++ } else if m := mailFromKey.FindStringSubmatch(k); m != nil { submit[m[1]+"_SMTP"] = true } } for p := range prefixes { if !slices.Contains(app.MailPrefixes, p) { st.WrongPrefix = p } } for p := range submit { if p != app.SubmitPrefix { st.WrongPrefix = p } } smtp := "" for _, p := range app.MailPrefixes { if prefixes[p] > 0 { smtp = p break } } switched := submit[app.SubmitPrefix] var want []string if switched { want = append(want, MailFromKey(app.SubmitPrefix)) } switch { case smtp != "": want = append(want, SMTPKeys(smtp)...) case !switched: want = append(want, SMTPKeys(app.MailPrefixes[0])...) } if app.Relay { want = append(want, "CARLOS_RELAY") } if app.Store { for _, k := range StoreKeys { if present[k.Name] { st.Store = append(st.Store, k.Name) } } } for _, k := range want { if present[k] { st.Keys = append(st.Keys, k) } else { st.Missing = append(st.Missing, k) } } return st } // EnvironmentBinding is §7's environment_binding: base64url(SHA-256) of // Alta's canonical recipe JSON for this instance — sorted names, each with // its class and, for a SET key, the SHA-256 of its value. GENERATED and // PLATFORM keys contribute name and class only. func EnvironmentBinding(env string, keys []Key, platform []string) string { type row = [3]string var rows []row for _, k := range keys { h := "" if k.Class == Set { s := sha256.Sum256([]byte(k.Value)) h = hex.EncodeToString(s[:]) } rows = append(rows, row{k.Name, string(k.Class), h}) } for _, k := range platform { rows = append(rows, row{k, string(Platform), ""}) } slices.SortFunc(rows, func(a, b row) int { return strings.Compare(a[0], b[0]) }) b, _ := stdjson.Marshal([]any{"oficina/alta/environment-binding/v1", env, rows}) sum := sha256.Sum256(b) return base64.RawURLEncoding.EncodeToString(sum[:]) } // freshKey is a GENERATED value: 32 random bytes, standard base64, the // shape every DEK and instance key in the suite takes. func freshKey() string { b := make([]byte, 32) if _, err := rand.Read(b); err != nil { panic(fmt.Sprintf("provision: no randomness: %v", err)) } return base64.StdEncoding.EncodeToString(b) } // RetypeAllowed reports whether Paul may retype a forgotten owner address // for a team with these apps (name → active|retired). Only a stopgap // allowlist still needs one (none since every app has roster mode). A // seeded app's owner is never retyped: the address Home confirmed at // create-team is the only one a seeded recipe may write, and a retyped // address, checked for shape alone, would make someone else its owner // (team-bundle, Fable's whole-branch review P2-2). With retype refused, // a held owner is always Home's confirmed one. // // That holds only while no stopgap-allowlist app exists. If one returns // beside a seeded app, retype is allowed again and ownOnlyFits would take // a retyped address for a late seeded app: mark held owners as retyped // first, and have ownOnlyFits refuse them. func RetypeAllowed(apps map[string]string) bool { for slug, st := range apps { if app, ok := AppBySlug(slug); ok && st == "active" && NeedsOwner(app) && !app.Seeded { return true } } return false }