package stacks import ( "fmt" "os" "path/filepath" "sort" "strings" "time" ) // ── after_setup: the app's OWN sign-up switch, set once the first admin exists (v0.282.0, `09` §3 decisions 47, 49) ── // // Decision 47 closes open sign-up once an app's first admin exists. v0.281.0 did it with an address block only // (signup_block.go). Measured 2026-09-29 evening: 9 of the 11 apps with a block also have their own switch, and every // one is read from the environment at start (gitea through its env-to-ini; the others directly). So the template // wires that switch to SIGNUP_CLOSED / SIGNUP_OPEN, whose compose default is OPEN — an installed app is unchanged by // the catalog — and declares: // // after_setup: // env: {SIGNUP_CLOSED: "true"} # merged into the app's env, then ONE `compose up -d` // // It runs when the setup gate opens (probe or the household's press) and on the household's "close sign-up now" // (decision 49), AFTER the address block is up. The block stays either way: two locks. A failed step is recorded // (`after_setup:` in app.yaml) and shown on the app page; the block still holds. // // The household's 15-minute window lifts BOTH: the env keys are removed (the compose default is open again) and the // app is started once more; when the window ends the loop puts them back (one more start). The page says the app // restarts. // // A command form (`service`, `command`, `success`, `env` names) follows after_install's argv-safe rules (R-713). // Pinned by internal/stacks/after_setup_test.go. // AfterSetupSpec is `.felhom.yml`'s `after_setup:`. type AfterSetupSpec struct { Env map[string]string `yaml:"env,omitempty" json:"env,omitempty"` Service string `yaml:"service,omitempty" json:"service,omitempty"` User string `yaml:"user,omitempty" json:"user,omitempty"` Args []string `yaml:"args_env,omitempty" json:"args_env,omitempty"` // deploy values a command may use Command []string `yaml:"command,omitempty" json:"command,omitempty"` Success string `yaml:"success,omitempty" json:"success,omitempty"` } // Native-lock states in SetupGateRecord.NativeLock. const ( NativeLockApplied = "applied" // the app's own switch says closed NativeLockLifted = "lifted" // the household's window: the switch is open again ) // afterSetupUp starts the app from its stored app.yaml (a seam: tests never reach Docker). func (m *Manager) afterSetupUp(name string) error { if m.afterSetupUpFn != nil { return m.afterSetupUpFn(name) } return m.upFromAppConfig(name) } // setNativeEnv merges (lock) or removes (lift) the after_setup env keys in app.yaml. func (m *Manager) setNativeEnv(name, dir string, spec *AfterSetupSpec, lock bool) bool { changed := false m.mutateAppConfig(name, dir, "after_setup_env", func(cfg *AppConfig) bool { if cfg.Env == nil { cfg.Env = map[string]string{} } for k, v := range spec.Env { if lock { if cfg.Env[k] != v { cfg.Env[k] = v changed = true } } else if _, ok := cfg.Env[k]; ok { delete(cfg.Env, k) changed = true } } return changed }) return changed } // applyNativeLock sets (lock=true) or lifts the app's own switch, then starts the app once when anything changed. // Records the outcome. Safe to call again: an unchanged env starts nothing. func (m *Manager) applyNativeLock(name string, lock bool, why string) error { st, ok := m.GetStack(name) if !ok || st.Meta.AfterSetup == nil { return nil } spec := st.Meta.AfterSetup dir := filepath.Dir(st.ComposePath) record := func(ok bool, detail string) { rec := &AfterInstallRecord{At: m.now().UTC().Format(time.RFC3339), OK: ok, Detail: truncateStr(detail, 300)} state := NativeLockApplied if !lock { state = NativeLockLifted } m.mutateAppConfig(name, dir, "after_setup", func(cfg *AppConfig) bool { cfg.AfterSetup = rec if ok && cfg.SetupGate != nil { cfg.SetupGate.NativeLock = state } return true }) } var err error // The switch works only if the app's INSTALLED compose reads the variable. An app installed before the template // wired it (decision 49's apps) carries the old compose until its next update: say so, never report a lock that // is not there. The address block still holds. if len(spec.Env) > 0 && lock { if miss := composeMissingVars(st.ComposePath, spec.Env); len(miss) > 0 { err = fmt.Errorf("the installed version of the app does not read %v yet — its own switch applies after its next update", miss) m.logger.Printf("[WARN] [stacks] %s: %v", name, err) record(false, err.Error()) return err } } if len(spec.Env) > 0 { if m.setNativeEnv(name, dir, spec, lock) { err = m.afterSetupUp(name) } } if err == nil && lock && len(spec.Command) > 0 { err = m.runAfterSetupCommand(name, dir, spec) } if err != nil { m.logger.Printf("[ERROR] [stacks] %s: the app's own sign-up switch could not be %s (%s): %v — the address block still holds", name, map[bool]string{true: "closed", false: "opened"}[lock], why, err) record(false, err.Error()) return err } keys := make([]string, 0, len(spec.Env)) for k := range spec.Env { keys = append(keys, k) } sort.Strings(keys) m.logger.Printf("[INFO] [stacks] %s: the app's own sign-up switch %s (%s; env %v)", name, map[bool]string{true: "CLOSED", false: "opened for the household's window"}[lock], why, keys) record(true, "") return nil } // runAfterSetupCommand runs the command form once, with after_install's argv-safe expansion and success marker. func (m *Manager) runAfterSetupCommand(name, dir string, spec *AfterSetupSpec) error { if spec.Service == "" || spec.Success == "" { return fmt.Errorf("after_setup command needs a service and a success marker") } cfg := LoadAppConfigDecrypted(dir, m.encKey) if cfg == nil { return fmt.Errorf("app.yaml unreadable") } cmd, err := expandAfterInstall(spec.Command, spec.Args, cfg.Env) if err != nil { return err } args := []string{"exec", "-T"} if spec.User != "" { args = append(args, "-u", spec.User) } args = append(args, spec.Service) args = append(args, cmd...) out, err := m.runInService(dir, args...) if err != nil || !strings.Contains(out, spec.Success) { return fmt.Errorf("after_setup command did not report %q (err %v)", spec.Success, err) } return nil } // runInService is the compose exec seam shared with after_install (afterLoadFn in tests). func (m *Manager) runInService(dir string, args ...string) (string, error) { if m.afterLoadFn != nil { return m.afterLoadFn(dir, args...) } return m.composeExecCustomEnv(dir, m.stackEnv(dir), args...) } // ── "Close sign-up now" (decision 49) ───────────────────────────────────────────────────────────────── // ErrCloseSignupNotOffered: the app is not installed, has no gate-free install, or its template has no lock. var ErrCloseSignupNotOffered = fmt.Errorf("close sign-up is not offered for this app") // CloseSignupOffered: an installed app whose template has a sign-up lock and whose install has none — an app // installed before decision 47 (demo-hp's adventurelog, opengist). Offered once: the press records a lock. func (m *Manager) CloseSignupOffered(name string) bool { st, ok := m.GetStack(name) if !ok || !st.Deployed || st.AppConfig == nil || st.AppConfig.SetupGate != nil { return false } return strings.TrimSpace(st.Meta.SignupBlock) != "" || st.Meta.AfterSetup != nil } // CloseSignupNow applies to an installed app exactly what a fresh install gets after its setup: a lock record // (never a closed gate), the address block, then the app's own switch. It never gates the app and never touches // its data. func (m *Manager) CloseSignupNow(name string) error { if !m.CloseSignupOffered(name) { return ErrCloseSignupNotOffered } st, _ := m.GetStack(name) dir := filepath.Dir(st.ComposePath) cfg := LoadAppConfigDecrypted(dir, m.encKey) if cfg == nil { return fmt.Errorf("%s: app.yaml unreadable", name) } rs, err := gateRoutersFromCompose(st.ComposePath, cfg.Env) if err != nil { return fmt.Errorf("%s: the app's addresses could not be read: %w", name, err) } hosts := gateHosts(rs) if b := strings.TrimSpace(st.Meta.SignupBlock); b != "" { if err := m.writeSignupBlock(name, hosts, b); err != nil { return fmt.Errorf("%s: the sign-up block could not be written: %w", name, err) } } now := m.now().UTC().Format(time.RFC3339) done := false m.mutateAppConfig(name, dir, "setup_gate", func(c *AppConfig) bool { if c.SetupGate != nil { return false } c.SetupGate = &SetupGateRecord{State: SetupGateOpen, Since: now, Hosts: hosts, OpenedAt: now, OpenedBy: SetupGateByCloseSignup} done = true return true }) if !done { _ = m.removeSignupBlockFile(name) return fmt.Errorf("%s: the lock could not be recorded", name) } m.logger.Printf("[INFO] [stacks] %s: the household closed sign-up on an app installed before decision 47 (hosts %v)", name, hosts) if st.Meta.AfterSetup != nil { m.goNativeLock(name, true, "close sign-up now") } return nil } // restoreSignupLock is R-773's half of PersistUnitRedeployConfig: for an app whose template locks sign-up, the lock // record (opened_by "restore", never a closed gate) and — best effort — its block file. nil, nil when the template has // no lock. A block that cannot be written now is logged and left to the loop (the record says it is wanted); hosts that // cannot be read refuse the restore before anything starts (fail closed, as the gate's own install does). // The app's own switch (`after_setup`) is the loop's: NativeLock is "" so it runs once the app is up. func (m *Manager) restoreSignupLock(name, composePath string, env map[string]string, meta *Metadata) (*SetupGateRecord, error) { block := strings.TrimSpace(meta.SignupBlock) if block == "" && meta.AfterSetup == nil { return nil, nil } rs, err := gateRoutersFromCompose(composePath, env) if err != nil { return nil, fmt.Errorf("%s: the app's addresses could not be read: %w", name, err) } hosts := gateHosts(rs) if block != "" { if err := m.writeSignupBlock(name, hosts, block); err != nil { m.logger.Printf("[ERROR] [stacks] %s: the restore's sign-up block could not be written: %v — the loop retries; sign-up is OPEN until it is", name, err) } } now := m.now().UTC().Format(time.RFC3339) m.logger.Printf("[INFO] [stacks] %s: restored after a removal — sign-up closed again as after its setup (hosts %v)", name, hosts) return &SetupGateRecord{State: SetupGateOpen, Since: now, Hosts: hosts, OpenedAt: now, OpenedBy: SetupGateByRestore}, nil } // goNativeLock runs applyNativeLock in the background, one at a time per app (a press, the window and the loop // can meet). The seam afterSetupSync makes it synchronous for tests. func (m *Manager) goNativeLock(name string, lock bool, why string) { if _, busy := m.nativeLockBusy.LoadOrStore(name, true); busy { return } run := func() { defer m.nativeLockBusy.Delete(name) _ = m.applyNativeLock(name, lock, why) } if m.afterSetupSync { run() return } go run() } // SetupGateByCloseSignup marks a lock record written by "close sign-up now" (the app was never gated). const SetupGateByCloseSignup = "close-signup" // composeMissingVars lists the after_setup env keys the compose file never reads as ${KEY...}. func composeMissingVars(composePath string, env map[string]string) []string { b, err := os.ReadFile(composePath) if err != nil { keys := make([]string, 0, len(env)) for k := range env { keys = append(keys, k) } sort.Strings(keys) return keys } var miss []string for k := range env { if !strings.Contains(string(b), "${"+k+"}") && !strings.Contains(string(b), "${"+k+":") { miss = append(miss, k) } } sort.Strings(miss) return miss }