From 4110da50e9725ff0d6c802d1878d1d6cb03a04ad Mon Sep 17 00:00:00 2001 From: kisfenyo Date: Tue, 29 Sep 2026 16:19:12 +0200 Subject: [PATCH] v0.282.0: after_setup (the app's own sign-up switch), close sign-up now (decision 49), probes read lists + done_status (R-715) Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS --- CHANGELOG.md | 22 + REUSE.md | 1 + controller/README.md | 5 + controller/internal/i18n/locales/en.json | 7 +- controller/internal/i18n/locales/hu.json | 7 +- controller/internal/stacks/after_setup.go | 271 ++++++++ .../internal/stacks/after_setup_test.go | 180 ++++++ controller/internal/stacks/deploy.go | 2 + controller/internal/stacks/life_records.go | 1 + controller/internal/stacks/manager.go | 5 + controller/internal/stacks/metadata.go | 4 +- controller/internal/stacks/setup_gate.go | 69 +- controller/internal/stacks/setup_gate_test.go | 6 +- controller/internal/stacks/signup_block.go | 42 +- controller/internal/web/close_signup_test.go | 35 ++ controller/internal/web/handlers.go | 6 + controller/internal/web/i18n_parity_test.go | 10 + .../internal/web/r499_system_backup_test.go | 8 +- controller/internal/web/r685_no_space_test.go | 3 +- controller/internal/web/server.go | 2 + controller/internal/web/setup_gate.go | 20 + .../internal/web/templates/app_info.html | 16 +- .../i18n_parity/app_info_close_signup.html | 587 +++++++++++++++++ .../i18n_parity/app_info_signup_native.html | 590 ++++++++++++++++++ controller/scripts/i18n_go_keys.json | 1 + 25 files changed, 1864 insertions(+), 36 deletions(-) create mode 100644 controller/internal/stacks/after_setup.go create mode 100644 controller/internal/stacks/after_setup_test.go create mode 100644 controller/internal/web/close_signup_test.go create mode 100644 controller/internal/web/testdata/i18n_parity/app_info_close_signup.html create mode 100644 controller/internal/web/testdata/i18n_parity/app_info_signup_native.html diff --git a/CHANGELOG.md b/CHANGELOG.md index 9040e6c..f444e1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,25 @@ +## v0.282.0 — the app's own sign-up switch after the setup (after_setup); "close sign-up now" (decision 49); probes read lists and a "done" status (R-715) (2026-09-29 evening) + +**MinAgent: 0.131.0** (unchanged). Needs hub v0.123.0 (unchanged). New strings: `app_info.close_signup_text`, +`app_info.close_signup_btn`, `app_info.signup_native_failed`, `app_info.signup_window_restart`, +`err.setup_gate.close_signup_not_offered` (hu + en). Evidence: `felhom.eu/documentation/audits/signup-lock-2026-09-29/`. + +- **`after_setup:`** (`.felhom.yml`): `env: {SIGNUP_CLOSED: "true"}` (or a command, with after_install's argv-safe + rules). Run once when the gate opens — after the address block is up — merged into the app's env and ONE + `compose up -d`. Measured: 9 of the 11 apps with a block have their own switch, all read from the environment; 6 of + them refuse even the household's first admin while it is on, so it goes on AFTER the setup. Two locks now: the app's + own switch and the address block. An installed version whose compose does not read the variable is reported, never + recorded as locked. The household's 15-minute window lifts both (one restart) and the loop closes both again (one + more). A failed switch retries at most every 30 minutes; the page says so; the block holds. +- **"Close sign-up now" (decision 49):** an installed app whose template has a lock and whose install has none (an + app installed before decision 47) shows one sentence and one press (`POST /apps//close-signup`). It writes a + lock record (`opened_by: close-signup` — never a closed gate), the address block, then the app's own switch. + Offered once. The box never applies it by itself. +- **R-715:** a probe's `field` may index a list (`setup.0.status`, `0.done`); `done_status:` counts a fixed non-200 + answer as done (gramps-web's 405); any other non-200 stays "cannot read" (fail closed). +- Tests: `TestAfterSetup_*`, `TestCloseSignup_*`, `TestCloseSignupPage_*`, `TestProbe_ListIndexesAndADoneStatus`. + Red-proofs RP25–RP30, each seen failing on an assertion. + ## v0.281.0 — "Done" asks the app first; open sign-up closed once the first admin exists; a password is never read as code (2026-09-29) **MinAgent: 0.131.0** (unchanged). Needs hub v0.123.0 (unchanged). New strings: `signup_closed.page_title`, diff --git a/REUSE.md b/REUSE.md index 0b6492e..27a8234 100644 --- a/REUSE.md +++ b/REUSE.md @@ -28,6 +28,7 @@ | `stacks.RunAfterInstall` / `expandAfterInstall` / `web.defaultLoginInEffect` (v0.279.0, decision 45) | controller/internal/stacks/after_install.go · controller/internal/web/known_login.go | `(name, wait)` / `(cmd, allowed, env)` / `(meta, cfg, installed)` | A fresh install replaces a known default login; the page says when a default is still in effect | **Only from the deploy-done hook** — never after a restore/kept load (R-694). A `success:` marker is required (exit 0 lies). Never log the expanded command | | `stacks.OpenSetupGate` / `SetupGateTick` / `SetupGateHost` · `web.ServeGateAuth` / `ServeGateStart` (v0.280.0, decision 46) | controller/internal/stacks/setup_gate.go · controller/internal/web/setup_gate.go | `(name, by)` / `()` / `(host)` · handlers | The setup gate: a `setup_gate: true` install is closed to everyone but the household until its probe or the household's press opens it | **Write the gate BEFORE the first start** (spike F2). Open = record first, then remove the file. Never widen the dashboard cookie — the handshake mints a host-bound one-use token | | `stacks.OpenSignupWindow` / `SignupBlocked` / `SetupGateProbe` · `web.ServeSignupClosed` (v0.281.0, decision 47) | controller/internal/stacks/signup_block.go · controller/internal/web/setup_gate.go | `(name)` | Sign-up closed at the app's own address once the gate opens; the household's 15-minute window; the press asks the probe | **The block goes up BEFORE the gate comes down** (a failed write keeps the gate closed). Never on an app this box did not gate | +| `stacks.CloseSignupNow` / `CloseSignupOffered` / `applyNativeLock` (v0.282.0, decisions 47/49) | controller/internal/stacks/after_setup.go | `(name)` | The app's own sign-up switch after the setup; "close sign-up now" for an app installed before the rule | **Check the installed compose reads the variable** (an old install carries the old compose until its next update) — never record a lock that is not there. One run per app at a time (`nativeLockBusy`) | | `backup.judgeCopy` / `HollowCopies` / `SetHollowCopyNotify` (Part D, v0.279.0) | controller/internal/backup/hollow_watch.go | `(app, tier, unitDir)` | A RUNNING app whose newest copy holds no data → operator digest once/day + page sentence | Uses `unitCarriesData` (the manifest, never size); a stopped held app is never flagged | | `web.nightChain` (R-705, v0.279.0) | controller/internal/web/night_chain.go | `POST /api/debug/backup/night-chain` | The night's four legs now, in order | Refuses while any op/update/chain runs; the leg uses `RunUpdateLegNow` | | `Router.dropLeftoverHold` + `settings.ClearUpdateHold` (R-704, v0.278.0) | controller/internal/api/router.go · controller/internal/settings/settings.go | `(name, why)` / `(stack) (bool, error)` | A new install (plain or "use my kept data") and a removal clear the update / crash-loop hold of the app's install | **A hold belongs to an INSTALL; the name is all the next install shares with it.** Never clears an R-379 restore hold (operator-only) | diff --git a/controller/README.md b/controller/README.md index cbe3766..8c51904 100644 --- a/controller/README.md +++ b/controller/README.md @@ -1940,6 +1940,11 @@ that folder is never a dead end, and an install never runs into it silently (R-6 controller's refusal page / 403 JSON), then the gate comes down. The app page's sign-up card shows `app_info.add_people` and „Regisztráció megnyitása 15 percre" (`POST /apps//signup-window`, 15 min; the loop restores the block). Never on an app this box did not gate. Code: `internal/stacks/signup_block.go`. +- **`after_setup:` + "close sign-up now" (v0.282.0, decisions 47/49)** — the app's own sign-up switch (`env:` merged + into app.yaml + one `compose up -d`, or a command) set when the gate opens, after the block. The window lifts and the + loop re-applies it. `POST /apps//close-signup` for an app installed before the rule: lock record + (`opened_by: close-signup`), block, switch; never a gate. Code: `internal/stacks/after_setup.go`. +- **Probes (v0.282.0, R-715)** — `field` may index lists; `done_status:` treats one non-200 status as done. - **R-713 (v0.281.0).** `after_install` refuses a code-bound value holding a quote, backslash, `$`, `{`, `}`, backtick or line break; `${NAME|base64}` passes any value safely. - **R-709 (v0.280.0).** An installed app's `type: password` value is not in its settings page; the eye fetches it. diff --git a/controller/internal/i18n/locales/en.json b/controller/internal/i18n/locales/en.json index 2e6be75..094a46c 100644 --- a/controller/internal/i18n/locales/en.json +++ b/controller/internal/i18n/locales/en.json @@ -2489,5 +2489,10 @@ "app_info.signup_window_btn": "Open sign-up for 15 minutes", "err.setup_gate.probe_not_done": "The app says its first setup is not done yet. Create your account, then try again.", "err.setup_gate.no_signup_block": "Sign-up is not closed on this app.", - "app_info.signup_add_how": "To add a family member:" + "app_info.signup_add_how": "To add a family member:", + "app_info.close_signup_text": "Anyone who finds this app's address can sign up. Close sign-up now — you can still add your family afterwards.", + "app_info.close_signup_btn": "Close sign-up now", + "app_info.signup_native_failed": "The app's own sign-up switch could not be closed. The address block still protects it.", + "app_info.signup_window_restart": "The app restarts for this, and once more when the 15 minutes end.", + "err.setup_gate.close_signup_not_offered": "There is nothing to close on this app." } diff --git a/controller/internal/i18n/locales/hu.json b/controller/internal/i18n/locales/hu.json index 9ec0bf3..aadaa57 100644 --- a/controller/internal/i18n/locales/hu.json +++ b/controller/internal/i18n/locales/hu.json @@ -2477,5 +2477,10 @@ "app_info.signup_window_btn": "Regisztráció megnyitása 15 percre", "err.setup_gate.probe_not_done": "Az alkalmazás szerint még nincs kész az első beállítás. Hozd létre a fiókodat, aztán próbáld újra.", "err.setup_gate.no_signup_block": "Ennél az alkalmazásnál a regisztráció nincs lezárva.", - "app_info.signup_add_how": "Családtagot így adhatsz hozzá:" + "app_info.signup_add_how": "Családtagot így adhatsz hozzá:", + "app_info.close_signup_text": "Ennél az alkalmazásnál bárki regisztrálhat, aki megtalálja a címét. Zárd le a regisztrációt most — a családtagjaidat utána is fel tudod venni.", + "app_info.close_signup_btn": "Regisztráció lezárása most", + "app_info.signup_native_failed": "Az alkalmazás saját regisztrációs kapcsolóját nem sikerült lezárni. A cím zárolása így is véd.", + "app_info.signup_window_restart": "Ehhez az alkalmazás újraindul, és a 15 perc végén még egyszer.", + "err.setup_gate.close_signup_not_offered": "Ennél az alkalmazásnál nincs mit lezárni." } diff --git a/controller/internal/stacks/after_setup.go b/controller/internal/stacks/after_setup.go new file mode 100644 index 0000000..230ac81 --- /dev/null +++ b/controller/internal/stacks/after_setup.go @@ -0,0 +1,271 @@ +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 +} + +// 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 +} diff --git a/controller/internal/stacks/after_setup_test.go b/controller/internal/stacks/after_setup_test.go new file mode 100644 index 0000000..3a8bb30 --- /dev/null +++ b/controller/internal/stacks/after_setup_test.go @@ -0,0 +1,180 @@ +package stacks + +import ( + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// v0.282.0 — the app's own sign-up switch (after_setup), "close sign-up now" (decision 49), richer probes (R-715). + +const nativeCompose = "services:\n" + + " gapp:\n image: busybox\n environment:\n - DISABLE_REGISTRATION=${SIGNUP_CLOSED:-false}\n labels:\n" + + " - \"traefik.enable=true\"\n" + + " - \"traefik.http.routers.gapp.rule=Host(`${SUBDOMAIN}.${DOMAIN}`)\"\n" + + " - \"traefik.http.services.gapp.loadbalancer.server.port=80\"\n" + +const nativeYml = "display_name: Gated App\nsetup_gate: true\nsignup_block: \"PathPrefix(`/signup`)\"\n" + + "after_setup:\n env:\n SIGNUP_CLOSED: \"true\"\n" + + "deploy_fields:\n - env_var: DOMAIN\n type: domain\n - env_var: SUBDOMAIN\n type: subdomain\n default: gapp\n" + +type upRecorder struct { + mu sync.Mutex + n int + env []string + m *Manager +} + +func (u *upRecorder) up(name string) error { + u.mu.Lock() + defer u.mu.Unlock() + u.n++ + c := LoadAppConfig(filepath.Join(u.m.cfg.Paths.StacksDir, name)) + u.env = append(u.env, c.Env["SIGNUP_CLOSED"]) + return nil +} + +func nativeManager(t *testing.T, compose string) (*Manager, *upRecorder) { + t.Helper() + m := gateManager(t, nativeYml) + must(t, os.WriteFile(filepath.Join(m.cfg.Paths.StacksDir, "gapp", "docker-compose.yml"), []byte(compose), 0o644)) + must(t, m.ScanStacks()) + m.afterSetupSync = true + u := &upRecorder{m: m} + m.afterSetupUpFn = u.up + return m, u +} + +// When the gate opens the box sets the app's own switch (then starts it once), after the block is up. +// COMPANION RED-PROOF: drop the goNativeLock call in OpenSetupGate → "the app's own switch was not set" fails. +func TestAfterSetup_TheGateOpeningSetsTheAppsOwnSwitch(t *testing.T) { + m, u := nativeManager(t, nativeCompose) + dir := closedGate(t, m) + must(t, m.OpenSetupGate("gapp", SetupGateByHousehold)) + c := LoadAppConfig(dir) + if c.Env["SIGNUP_CLOSED"] != "true" || u.n != 1 { + t.Fatalf("the app's own switch was not set: env=%q starts=%d", c.Env["SIGNUP_CLOSED"], u.n) + } + if c.AfterSetup == nil || !c.AfterSetup.OK || c.SetupGate.NativeLock != NativeLockApplied { + t.Fatalf("record %+v / native %q", c.AfterSetup, c.SetupGate.NativeLock) + } + if _, err := os.Stat(m.signupBlockPath("gapp")); err != nil { + t.Fatal("the address block is not up — two locks, not one") + } + m.SetupGateTick() // an applied lock is not re-applied (no restart per tick) + if u.n != 1 { + t.Fatalf("the loop restarted the app again (%d starts)", u.n) + } +} + +// The household's window lifts the app's own switch too, and the loop closes it again after. +// COMPANION RED-PROOF: drop the goNativeLock(true, …) in reconcileSignupBlocks → "the switch stayed open" fails. +func TestAfterSetup_TheWindowLiftsItAndTheLoopClosesItAgain(t *testing.T) { + m, u := nativeManager(t, nativeCompose) + dir := closedGate(t, m) + must(t, m.OpenSetupGate("gapp", SetupGateByHousehold)) + _, err := m.OpenSignupWindow("gapp") + must(t, err) + if c := LoadAppConfig(dir); c.Env["SIGNUP_CLOSED"] != "" || c.SetupGate.NativeLock != NativeLockLifted || u.n != 2 { + t.Fatalf("window: env=%q native=%q starts=%d", c.Env["SIGNUP_CLOSED"], c.SetupGate.NativeLock, u.n) + } + later := time.Now().Add(signupWindow + time.Minute) + m.updateNowFn = func() time.Time { return later } + m.SetupGateTick() + if c := LoadAppConfig(dir); c.Env["SIGNUP_CLOSED"] != "true" || c.SetupGate.NativeLock != NativeLockApplied || u.n != 3 { + t.Fatalf("the switch stayed open after the window: env=%q native=%q starts=%d", c.Env["SIGNUP_CLOSED"], c.SetupGate.NativeLock, u.n) + } +} + +// An installed version whose compose does not read the variable is reported, never recorded as locked. +// COMPANION RED-PROOF: drop the composeMissingVars check → the record says ok and this fails. +func TestAfterSetup_AnOldComposeIsReportedNotFaked(t *testing.T) { + m, u := nativeManager(t, strings.Replace(nativeCompose, " - DISABLE_REGISTRATION=${SIGNUP_CLOSED:-false}\n", " - TZ=x\n", 1)) + dir := closedGate(t, m) + must(t, m.OpenSetupGate("gapp", SetupGateByHousehold)) + c := LoadAppConfig(dir) + if c.AfterSetup == nil || c.AfterSetup.OK || !strings.Contains(c.AfterSetup.Detail, "SIGNUP_CLOSED") || u.n != 0 || c.SetupGate.NativeLock == NativeLockApplied { + t.Fatalf("an unread switch was recorded as set: %+v native=%q starts=%d", c.AfterSetup, c.SetupGate.NativeLock, u.n) + } + if _, err := os.Stat(m.signupBlockPath("gapp")); err != nil { + t.Fatal("the block must hold anyway") + } +} + +// Decision 49: offered only for an installed app with a template lock and no lock record; the press writes the +// block and sets the switch, never a gate; offered once. +// COMPANION RED-PROOF: return true from CloseSignupOffered when SetupGate != nil → the second press succeeds. +func TestCloseSignup_OnceOnAnAppInstalledBeforeTheRule(t *testing.T) { + m, u := nativeManager(t, nativeCompose) + dir := filepath.Join(m.cfg.Paths.StacksDir, "gapp") + cfg := &AppConfig{Deployed: true, Env: map[string]string{"DOMAIN": "example.hu", "SUBDOMAIN": "gapp"}} + must(t, SaveAppConfig(dir, cfg, m.encKey, nil)) + m.mu.Lock() + m.stacks["gapp"].Deployed, m.stacks["gapp"].State, m.stacks["gapp"].AppConfig = true, StateRunning, cfg + m.mu.Unlock() + if !m.CloseSignupOffered("gapp") { + t.Fatal("not offered on an installed app without a lock") + } + must(t, m.CloseSignupNow("gapp")) + c := LoadAppConfig(dir) + if c.SetupGate == nil || c.SetupGate.State != SetupGateOpen || c.SetupGate.OpenedBy != SetupGateByCloseSignup || strings.Join(c.SetupGate.Hosts, ",") != "gapp.example.hu" { + t.Fatalf("lock record %+v", c.SetupGate) + } + if _, err := os.Stat(m.setupGatePath("gapp")); !os.IsNotExist(err) { + t.Fatal("close sign-up GATED the app") + } + if _, err := os.Stat(m.signupBlockPath("gapp")); err != nil { + t.Fatal("no address block") + } + if c.Env["SIGNUP_CLOSED"] != "true" || u.n != 1 { + t.Fatalf("the app's own switch: env=%q starts=%d", c.Env["SIGNUP_CLOSED"], u.n) + } + m.mu.Lock() + m.stacks["gapp"].AppConfig = c + m.mu.Unlock() + if m.CloseSignupOffered("gapp") { + t.Fatal("offered twice") + } + if err := m.CloseSignupNow("gapp"); err != ErrCloseSignupNotOffered { + t.Fatalf("second press: %v", err) + } +} + +// R-715: list indexes and a "done" HTTP status. +// COMPANION RED-PROOF: drop the []interface{} case in probeSaysDone → the ghost/home-assistant rows fail. +func TestProbe_ListIndexesAndADoneStatus(t *testing.T) { + for _, c := range []struct { + body, field, done string + want bool + }{ + {`{"setup":[{"status":true}]}`, "setup.0.status", "true", true}, + {`{"setup":[{"status":false}]}`, "setup.0.status", "true", false}, + {`[{"step":"user","done":true},{"step":"core_config","done":false}]`, "0.done", "true", true}, + {`[{"step":"user","done":false}]`, "0.done", "true", false}, + {`[]`, "0.done", "true", false}, + {`{"setup":[]}`, "setup.3.status", "true", false}, + } { + if got, _ := probeSaysDone([]byte(c.body), c.field, c.done); got != c.want { + t.Errorf("%s @ %s: %v, want %v", c.body, c.field, got, c.want) + } + } + old := setupGateProbeFetch + t.Cleanup(func() { setupGateProbeFetch = old }) + status := 200 + setupGateProbeFetch = func(string) (int, []byte, error) { return status, []byte(`{"access_token":"x"}`), nil } + p := &SetupDoneProbe{URL: "u", Field: "error.code", Done: "405", DoneStatus: 405} + if done, _, _ := probeOnce(p); done { + t.Fatal("gramps-web before its setup (200 + a token) read as done") + } + status = 405 + if done, _, err := probeOnce(p); !done || err != nil { + t.Fatalf("gramps-web after its setup (405) not read as done: %v", err) + } + status = 500 + if done, _, err := probeOnce(p); done || err == nil { + t.Fatal("another status read as done (must fail closed)") + } +} diff --git a/controller/internal/stacks/deploy.go b/controller/internal/stacks/deploy.go index 4c711ba..fb021fa 100644 --- a/controller/internal/stacks/deploy.go +++ b/controller/internal/stacks/deploy.go @@ -187,6 +187,8 @@ type AppConfig struct { // DefaultLogin (v0.280.0, R-710) is the household's own word that it changed the template's known default // login by hand. The page stops naming the default. See internal/web/known_login.go. DefaultLogin *DefaultLoginRecord `yaml:"default_login,omitempty" json:"default_login,omitempty"` + // AfterSetup (v0.282.0) is what the template's after_setup (the app's own sign-up switch) last did. + AfterSetup *AfterInstallRecord `yaml:"after_setup,omitempty" json:"after_setup,omitempty"` } // DefaultLoginRecord is app.yaml's `default_login:`. diff --git a/controller/internal/stacks/life_records.go b/controller/internal/stacks/life_records.go index d4e4f1f..1c3cf01 100644 --- a/controller/internal/stacks/life_records.go +++ b/controller/internal/stacks/life_records.go @@ -37,6 +37,7 @@ func carryLifeRecords(logger *log.Logger, name string, prior, cfg *AppConfig) { // No prior record (a removed app, kept data, a rebuilt guest) = no gate: the data comes back with its admin. cfg.SetupGate = prior.SetupGate cfg.DefaultLogin = prior.DefaultLogin + cfg.AfterSetup = prior.AfterSetup if n := len(prior.EarlierConversionCopies); prior.ConversionCopy != nil || n > 0 { cur := "" if prior.ConversionCopy != nil { diff --git a/controller/internal/stacks/manager.go b/controller/internal/stacks/manager.go index 1f05280..87ad349 100644 --- a/controller/internal/stacks/manager.go +++ b/controller/internal/stacks/manager.go @@ -270,6 +270,11 @@ type Manager struct { execFn func(name string, args ...string) (string, error) // composeExecFn replaces the initial deploy's compose call (composeExecWithEnv) in tests; nil in production. composeExecFn func(dir string, env map[string]string, args ...string) (string, error) + // afterSetupUpFn replaces after_setup's `compose up -d` in tests; nil in production. + afterSetupUpFn func(name string) error + // nativeLockBusy: one after_setup run per app at a time (the loop, the window and a press can meet). + nativeLockBusy sync.Map + afterSetupSync bool // tests: run after_setup in the caller // --- guarded update (slice 4, update.go) --- updateGuards UpdateGuards // init-only, SetUpdateGuards; nil ⇒ every update is REFUSED diff --git a/controller/internal/stacks/metadata.go b/controller/internal/stacks/metadata.go index 2732679..54ba4a8 100644 --- a/controller/internal/stacks/metadata.go +++ b/controller/internal/stacks/metadata.go @@ -63,7 +63,9 @@ type Metadata struct { SetupDoneProbe *SetupDoneProbe `yaml:"setup_done_probe,omitempty" json:"setup_done_probe,omitempty"` // SignupBlock (v0.281.0, `09` §3 decision 47): a traefik matcher for the app's own sign-up address, closed once the // setup gate opens. See signup_block.go. - SignupBlock string `yaml:"signup_block,omitempty" json:"signup_block,omitempty"` + SignupBlock string `yaml:"signup_block,omitempty" json:"signup_block,omitempty"` + // AfterSetup (v0.282.0, decisions 47/49): the app's OWN sign-up switch, set when the gate opens. See after_setup.go. + AfterSetup *AfterSetupSpec `yaml:"after_setup,omitempty" json:"after_setup,omitempty"` Integrations []IntegrationDef `yaml:"integrations,omitempty" json:"integrations,omitempty"` // InitialCreds: for apps that auto-generate a first-login credential into a file inside the // container (e.g. Crafty's default-creds.txt). The controller reads + parses that file live and diff --git a/controller/internal/stacks/setup_gate.go b/controller/internal/stacks/setup_gate.go index 65546aa..96b183d 100644 --- a/controller/internal/stacks/setup_gate.go +++ b/controller/internal/stacks/setup_gate.go @@ -10,6 +10,7 @@ import ( "path/filepath" "regexp" "sort" + "strconv" "strings" "time" @@ -47,6 +48,8 @@ type SetupDoneProbe struct { URL string `yaml:"url" json:"url"` Field string `yaml:"field" json:"field"` Done string `yaml:"done" json:"done"` + // DoneStatus (v0.282.0, R-715): a non-200 HTTP status that itself means "set up" (gramps-web answers 405). + DoneStatus int `yaml:"done_status,omitempty" json:"done_status,omitempty"` } // Setup gate states. @@ -67,6 +70,8 @@ type SetupGateRecord struct { OpenedBy string `yaml:"opened_by,omitempty" json:"opened_by,omitempty"` // SignupOpenUntil (v0.281.0, decision 47): the household opened sign-up until this time (signup_block.go). SignupOpenUntil string `yaml:"signup_open_until,omitempty" json:"signup_open_until,omitempty"` + // NativeLock (v0.282.0): the app's own sign-up switch — "applied", "lifted" (the window), or "" (never set). + NativeLock string `yaml:"native_lock,omitempty" json:"native_lock,omitempty"` } // Closed reports whether the gate stands. @@ -325,6 +330,10 @@ func (m *Manager) OpenSetupGate(name, by string) error { m.logger.Printf("[ERROR] [stacks] %s: setup gate opened but its traefik file could not be removed (%v) — the reconcile retries", name, err) } m.logger.Printf("[INFO] [stacks] %s: setup gate OPENED by %s — the app is reached as without a gate", name, by) + // v0.282.0 (decision 47): the app's own sign-up switch, after the block is up and the gate is down. One restart. + if st.Meta.AfterSetup != nil { + m.goNativeLock(name, true, "the gate opened ("+by+")") + } return nil } @@ -347,33 +356,62 @@ func (m *Manager) SetupGateHost(host string) (name string, closed bool, found bo return "", false, false } -// setupGateProbeGet reads a probe URL (a seam: tests never reach a network). -var setupGateProbeGet = func(url string) ([]byte, error) { +// setupGateProbeFetch reads a probe URL: the HTTP status and the body (a seam: tests never reach a network). +var setupGateProbeFetch = func(url string) (int, []byte, error) { c := &http.Client{Timeout: 5 * time.Second} resp, err := c.Get(url) if err != nil { - return nil, err + return 0, nil, err } defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("HTTP %d", resp.StatusCode) - } - return io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + b, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + return resp.StatusCode, b, err } -// probeSaysDone reads the field at the dotted path and compares its text form with done. Anything it cannot -// read is "not done" — the gate stays closed (fail closed). +// probeOnce asks the app's own status once. v0.282.0 (R-715): `done_status:` — an app that answers a fixed non-200 +// status once it is set up (gramps-web: 405 "Users already exist") — counts as done on that status alone; any other +// non-200 is "cannot read" (fail closed). A 200 is read as JSON: `field` is a dotted path whose parts may be list +// indexes (`setup.0.status` — ghost; `0.done` — home-assistant), compared as text with `done`. +func probeOnce(p *SetupDoneProbe) (done bool, got string, err error) { + status, body, err := setupGateProbeFetch(p.URL) + if err != nil { + return false, "", err + } + if p.DoneStatus != 0 && status == p.DoneStatus { + return true, fmt.Sprintf("HTTP %d", status), nil + } + if status != http.StatusOK { + return false, fmt.Sprintf("HTTP %d", status), fmt.Errorf("HTTP %d", status) + } + if p.Field == "" { + return false, "no field", fmt.Errorf("the probe names no field") + } + done, got = probeSaysDone(body, p.Field, p.Done) + return done, got, nil +} + +// probeSaysDone reads the field at the dotted path (a numeric part indexes a list) and compares its text form with +// done. Anything it cannot read is "not done" — the gate stays closed (fail closed). func probeSaysDone(body []byte, field, done string) (bool, string) { var v interface{} if err := json.Unmarshal(body, &v); err != nil { return false, "not JSON" } for _, k := range strings.Split(field, ".") { - obj, ok := v.(map[string]interface{}) - if !ok { - return false, "no field " + field - } - if v, ok = obj[k]; !ok { + switch cur := v.(type) { + case map[string]interface{}: + nv, ok := cur[k] + if !ok { + return false, "no field " + field + } + v = nv + case []interface{}: + n, err := strconv.Atoi(k) + if err != nil || n < 0 || n >= len(cur) { + return false, "no field " + field + } + v = cur[n] + default: return false, "no field " + field } } @@ -431,14 +469,13 @@ func (m *Manager) SetupGateTick() { if it.probe == nil || it.probe.URL == "" || !it.running { continue } - body, err := setupGateProbeGet(it.probe.URL) + done, got, err := probeOnce(it.probe) if err != nil { if m.isDebug() { m.logger.Printf("[DEBUG] [stacks] %s: setup probe unreadable (%v) — gate stays closed", it.name, err) } continue } - done, got := probeSaysDone(body, it.probe.Field, it.probe.Done) if m.isDebug() { m.logger.Printf("[DEBUG] [stacks] %s: setup probe %s = %q (done when %q)", it.name, it.probe.Field, got, it.probe.Done) } diff --git a/controller/internal/stacks/setup_gate_test.go b/controller/internal/stacks/setup_gate_test.go index a68ff32..b404620 100644 --- a/controller/internal/stacks/setup_gate_test.go +++ b/controller/internal/stacks/setup_gate_test.go @@ -162,14 +162,12 @@ func TestSetupGate_TheProbeOpensItOnlyWhenTheAppSaysSetUp(t *testing.T) { dir := closedGate(t, m) answer := `{"data":{"initialized":false}}` var probeErr error - old := setupGateProbeGet - setupGateProbeGet = func(url string) ([]byte, error) { + t.Cleanup(SetSetupGateProbeGetForTest(func(url string) ([]byte, error) { if url != "http://gapp:80/api/status" { t.Errorf("probed %q", url) } return []byte(answer), probeErr - } - t.Cleanup(func() { setupGateProbeGet = old }) + })) m.SetupGateTick() if c := LoadAppConfig(dir); !c.SetupGate.Closed() { diff --git a/controller/internal/stacks/signup_block.go b/controller/internal/stacks/signup_block.go index feedc24..5818d28 100644 --- a/controller/internal/stacks/signup_block.go +++ b/controller/internal/stacks/signup_block.go @@ -134,6 +134,9 @@ func (m *Manager) OpenSignupWindow(name string) (string, error) { if err := m.removeSignupBlockFile(name); err != nil { return "", err } + if st.Meta.AfterSetup != nil && len(st.Meta.AfterSetup.Env) > 0 { // v0.282.0: the app's own switch opens too (a restart) + m.goNativeLock(name, false, "the household's window") + } m.logger.Printf("[INFO] [stacks] %s: the household opened sign-up until %s — the loop closes it again", name, until) return until, nil } @@ -178,9 +181,27 @@ func (m *Manager) reconcileSignupBlocks() { if err := m.writeSignupBlock(n, w.hosts, w.fragment); err != nil { m.logger.Printf("[ERROR] [stacks] %s: the sign-up block could not be written: %v — sign-up is OPEN until it is", n, err) } + // v0.282.0: the app's own switch back on (after the household's window), or a retry of a failed attempt — + // at most every nativeLockRetry, so a switch that cannot be set does not restart the app every tick. + if st, ok := m.GetStack(n); ok && st.Meta.AfterSetup != nil && st.AppConfig != nil && st.AppConfig.SetupGate != nil && + st.AppConfig.SetupGate.NativeLock != NativeLockApplied { + last := st.AppConfig.AfterSetup + due := last == nil || last.OK + if !due { + if t, err := time.Parse(time.RFC3339, last.At); err != nil || m.now().Sub(t) > nativeLockRetry { + due = true + } + } + if due { + m.goNativeLock(n, true, "the loop (window ended or retry)") + } + } } } +// nativeLockRetry: how often the loop retries an app's own switch that could not be set. +var nativeLockRetry = 30 * time.Minute + // SetupGateProbe asks the app's own "setup done" status once (the household's button asks it first, Part A of the // 2026-09-29 afternoon brief). has=false: the template declares no probe. func (m *Manager) SetupGateProbe(name string) (has bool, done bool, got string, err error) { @@ -192,17 +213,20 @@ func (m *Manager) SetupGateProbe(name string) (has bool, done bool, got string, if p == nil || p.URL == "" { return false, false, "", nil } - body, err := setupGateProbeGet(p.URL) - if err != nil { - return true, false, "", err - } - done, got = probeSaysDone(body, p.Field, p.Done) - return true, done, got, nil + done, got, err = probeOnce(p) + return true, done, got, err } // SetSetupGateProbeGetForTest swaps the probe's HTTP read (a test seam for other packages); returns the restore. +// f's error means "unreadable"; a nil error is a 200 with that body. func SetSetupGateProbeGetForTest(f func(url string) ([]byte, error)) func() { - old := setupGateProbeGet - setupGateProbeGet = f - return func() { setupGateProbeGet = old } + old := setupGateProbeFetch + setupGateProbeFetch = func(url string) (int, []byte, error) { + b, err := f(url) + if err != nil { + return 0, nil, err + } + return 200, b, nil + } + return func() { setupGateProbeFetch = old } } diff --git a/controller/internal/web/close_signup_test.go b/controller/internal/web/close_signup_test.go new file mode 100644 index 0000000..e051594 --- /dev/null +++ b/controller/internal/web/close_signup_test.go @@ -0,0 +1,35 @@ +package web + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// v0.282.0 (decision 49) — "close sign-up now": the card on an app installed before the rule, and the refusal on +// an app with nothing to close. +func TestCloseSignupPage_TheCardAndItsPress(t *testing.T) { + on := renderAppInfoWith(t, map[string]interface{}{"CloseSignupOffered": true}) + if !strings.Contains(on, `id="close-signup-card"`) || !strings.Contains(on, "/apps/gapp/close-signup") || !strings.Contains(on, "Zárd le a regisztrációt most") { + t.Fatal("offered, but the card, its sentence or its press is missing") + } + if off := renderAppInfoWith(t, nil); strings.Contains(off, `id="close-signup-card"`) { + t.Fatal("the card shows on an app with nothing to close") + } + native := renderAppInfoWith(t, map[string]interface{}{"SignupClosed": true, "SignupNative": true, "SignupNativeFailed": true}) + if !strings.Contains(native, "újraindul") || !strings.Contains(native, `id="signup-native-failed"`) { + t.Fatal("the window's restart line or the failed-switch line is missing") + } +} + +// COMPANION RED-PROOF: skip the CloseSignupNow error mapping → the gated app answers 500, not 409. +func TestCloseSignup_RefusedWhenNothingToClose(t *testing.T) { + s := gateHarness(t) // gapp: gated (closed), no signup_block + r := httptest.NewRequest(http.MethodPost, "/apps/gapp/close-signup", nil) + w := httptest.NewRecorder() + s.appCloseSignupHandler(w, r, "gapp") + if w.Code != http.StatusConflict { + t.Fatalf("close sign-up on an app with nothing to close: %d", w.Code) + } +} diff --git a/controller/internal/web/handlers.go b/controller/internal/web/handlers.go index ca81785..575607f 100644 --- a/controller/internal/web/handlers.go +++ b/controller/internal/web/handlers.go @@ -774,6 +774,12 @@ func (s *Server) appDetailHandler(w http.ResponseWriter, r *http.Request, slug s // v0.280.0 (decision 46): the setup gate's card, while the gate stands. data["SetupGateClosed"] = found.Deployed && found.AppConfig != nil && found.AppConfig.SetupGate.Closed() data["SetupGateHasProbe"] = found.Meta.SetupDoneProbe != nil && found.Meta.SetupDoneProbe.URL != "" + // v0.282.0 (decision 49): "close sign-up now" on an app installed before the rule; the app's own switch. + if s.stackMgr != nil { + data["CloseSignupOffered"] = s.stackMgr.CloseSignupOffered(found.Name) + } + data["SignupNative"] = found.Meta.AfterSetup != nil && len(found.Meta.AfterSetup.Env) > 0 + data["SignupNativeFailed"] = found.AppConfig != nil && found.AppConfig.AfterSetup != nil && !found.AppConfig.AfterSetup.OK // v0.281.0 (decision 47): the sign-up card — closed, or open for the household's 15 minutes. if s.stackMgr != nil { blocked, until := s.stackMgr.SignupBlocked(found.Name) diff --git a/controller/internal/web/i18n_parity_test.go b/controller/internal/web/i18n_parity_test.go index 412ee1c..eba8339 100644 --- a/controller/internal/web/i18n_parity_test.go +++ b/controller/internal/web/i18n_parity_test.go @@ -346,6 +346,16 @@ func i18nCases() []i18nCase { }} } base = append(base, signupCase("app_info_signup_closed", true, ""), signupCase("app_info_signup_window", false, "14:05")) + // v0.282.0 (decision 49): "close sign-up now"; the app's own switch (restart line, failed line). + base = append(base, i18nCase{"app_info_close_signup", "app_info", func() map[string]interface{} { + d := signupCase("x", false, "").data() + d["CloseSignupOffered"] = true + return d + }}, i18nCase{"app_info_signup_native", "app_info", func() map[string]interface{} { + d := signupCase("x", true, "").data() + d["SignupNative"], d["SignupNativeFailed"] = true, true + return d + }}) base = append(base, i18nCase{"app_info_known_login_changed", "app_info", func() map[string]interface{} { d := i18nLayoutData("stacks", "Calibre-Web") st := stacks.Stack{Name: "calibre-web", Deployed: true, State: stacks.StateRunning} diff --git a/controller/internal/web/r499_system_backup_test.go b/controller/internal/web/r499_system_backup_test.go index 324f085..f09c5e4 100644 --- a/controller/internal/web/r499_system_backup_test.go +++ b/controller/internal/web/r499_system_backup_test.go @@ -55,7 +55,9 @@ func tier2PageServer(t *testing.T, tiers func(context.Context) (agentapi.TiersRe bm.SetStackProvider(&blockProvider{hdd: ""}) // driveless: IsHDDApp false s := &Server{cfg: cfg, settings: sett, stackMgr: sm, backupMgr: bm, logger: lg, version: "test"} s.tiersFn = tiers - s.disksFn = func(context.Context) (agentapi.DisksResponse, error) { return agentapi.DisksResponse{Disks: disks}, nil } + s.disksFn = func(context.Context) (agentapi.DisksResponse, error) { + return agentapi.DisksResponse{Disks: disks}, nil + } s.loadTemplates() w := httptest.NewRecorder() s.tier2ConfigPageHandler(w, httptest.NewRequest("GET", "/stacks/privatebin/backup", nil), "privatebin") @@ -83,7 +85,9 @@ func TestR499_Tier2PageSaysWhatIsTrueForThisBox(t *testing.T) { {"same disk (the measured box)", "same_disk", primaryTier("local"), nil}, {"own drive", "protected", primaryTier("felhom-backup"), []agentapi.DiskInfo{ownDrive}}, {"configured drive gone", "absent", primaryTier("felhom-backup"), nil}, - {"agent not askable", "unknown", func(context.Context) (agentapi.TiersResponse, error) { return agentapi.TiersResponse{}, errors.New("down") }, nil}, + {"agent not askable", "unknown", func(context.Context) (agentapi.TiersResponse, error) { + return agentapi.TiersResponse{}, errors.New("down") + }, nil}, } for _, c := range cases { body := tier2PageServer(t, c.tiers, c.disks) diff --git a/controller/internal/web/r685_no_space_test.go b/controller/internal/web/r685_no_space_test.go index 9b56d7a..434b64f 100644 --- a/controller/internal/web/r685_no_space_test.go +++ b/controller/internal/web/r685_no_space_test.go @@ -73,7 +73,8 @@ func TestR685_BackupPageSaysTheBackupDoesNotFit(t *testing.T) { } out := html.UnescapeString(buf.String()) if !strings.Contains(out, c.want[lang]) || !strings.Contains(out, `data-no-space="true"`) { - i := strings.Index(out, "backup-tier-table"); t.Fatalf("%s: the rendered page does not carry the sentence; near table: %q", c.name, out[max(0, i):min(len(out), i+1500)]) + i := strings.Index(out, "backup-tier-table") + t.Fatalf("%s: the rendered page does not carry the sentence; near table: %q", c.name, out[max(0, i):min(len(out), i+1500)]) } } } diff --git a/controller/internal/web/server.go b/controller/internal/web/server.go index b90b3fc..759f215 100644 --- a/controller/internal/web/server.go +++ b/controller/internal/web/server.go @@ -818,6 +818,8 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // it" under a known default login (R-710). POST, so CsrfProtect covers them. case strings.HasPrefix(path, "/apps/") && strings.HasSuffix(path, "/setup-gate/open") && r.Method == http.MethodPost: s.appSetupGateOpenHandler(w, r, strings.TrimSuffix(strings.TrimPrefix(path, "/apps/"), "/setup-gate/open")) + case strings.HasPrefix(path, "/apps/") && strings.HasSuffix(path, "/close-signup") && r.Method == http.MethodPost: + s.appCloseSignupHandler(w, r, strings.TrimSuffix(strings.TrimPrefix(path, "/apps/"), "/close-signup")) case strings.HasPrefix(path, "/apps/") && strings.HasSuffix(path, "/signup-window") && r.Method == http.MethodPost: s.appSignupWindowHandler(w, r, strings.TrimSuffix(strings.TrimPrefix(path, "/apps/"), "/signup-window")) case strings.HasPrefix(path, "/apps/") && strings.HasSuffix(path, "/default-login/changed") && r.Method == http.MethodPost: diff --git a/controller/internal/web/setup_gate.go b/controller/internal/web/setup_gate.go index 61e8766..ec17744 100644 --- a/controller/internal/web/setup_gate.go +++ b/controller/internal/web/setup_gate.go @@ -385,3 +385,23 @@ func (s *Server) ServeSignupClosed(w http.ResponseWriter, r *http.Request) { s.logger.Printf("[ERROR] [web] signup-closed page: %v", err) } } + +// appCloseSignupHandler is decision 49's "close sign-up now" (POST /apps//close-signup) for an app installed +// before decision 47. It applies exactly what a fresh install gets after its setup; it never gates the app. +func (s *Server) appCloseSignupHandler(w http.ResponseWriter, r *http.Request, slug string) { + found := s.stackBySlug(slug) + if found == nil { + escrowJSON(w, http.StatusNotFound, nil, s.msg(r, "escrow.unknown_app")) + return + } + if err := s.stackMgr.CloseSignupNow(found.Name); err != nil { + if errors.Is(err, stacks.ErrCloseSignupNotOffered) { + escrowJSON(w, http.StatusConflict, nil, s.msg(r, "err.setup_gate.close_signup_not_offered")) + return + } + s.logger.Printf("[ERROR] [web] close sign-up %s: %v", found.Name, err) + escrowJSON(w, http.StatusInternalServerError, nil, s.msg(r, "err.setup_gate.open_failed")) + return + } + escrowJSON(w, http.StatusOK, map[string]any{"closed": true}, "") +} diff --git a/controller/internal/web/templates/app_info.html b/controller/internal/web/templates/app_info.html index 47b89c7..7a5cb2e 100644 --- a/controller/internal/web/templates/app_info.html +++ b/controller/internal/web/templates/app_info.html @@ -99,6 +99,14 @@ {{- end}} +{{- if .CloseSignupOffered}} +
+

{{T "app_info.signup_title"}}

+

{{T "app_info.close_signup_text"}}

+ + +
+{{- end}} {{- if or .SignupClosed .SignupOpenUntil}}

{{T "app_info.signup_title"}}

@@ -110,7 +118,13 @@ {{- if .AppInfo.AddPeople}}

{{T "app_info.signup_add_how"}} {{.AppInfo.AddPeople}}

{{- end}} + {{- if .SignupNativeFailed}} +

{{T "app_info.signup_native_failed"}}

+ {{- end}} {{- if .SignupClosed}} + {{- if .SignupNative}} +

{{T "app_info.signup_window_restart"}}

+ {{- end}} {{- end}} @@ -324,7 +338,7 @@ function icCopyPw(btn) { {{end}} {{template "layout_end" .}} -{{- if or .SetupGateClosed .SignupClosed (and .Stack.Deployed .KnownLoginLine)}} +{{- if or .SetupGateClosed .SignupClosed .CloseSignupOffered (and .Stack.Deployed .KnownLoginLine)}} + + + +
+ + +
+ + +
+ + + + + + + + + + + + + + + +
+ +
+ +

+ +
+ ~ RAM + + + Csak x86 + +
+ +
+
+ + +
+ + + +
+
+

Regisztráció

+

Ennél az alkalmazásnál bárki regisztrálhat, aki megtalálja a címét. Zárd le a regisztrációt most — a családtagjaidat utána is fel tudod venni.

+ + +
+ + + + + + + + + + +
+ + + + + diff --git a/controller/internal/web/testdata/i18n_parity/app_info_signup_native.html b/controller/internal/web/testdata/i18n_parity/app_info_signup_native.html new file mode 100644 index 0000000..e6a37fa --- /dev/null +++ b/controller/internal/web/testdata/i18n_parity/app_info_signup_native.html @@ -0,0 +1,590 @@ + + + + + + + + Opengist — Felhom.eu + + + + + + + + +
+ + +
+ + +
+ + + + + + + + + + + + + + + +
+ +
+ +

+ +
+ ~ RAM + + + Csak x86 + +
+ +
+
+ + +
+ + + +
+
+

Regisztráció

+

Az első admin fiók után a regisztráció zárva: idegen nem hozhat létre fiókot.

+

Családtagot így adhatsz hozzá: Admin panel → Users.

+

Az alkalmazás saját regisztrációs kapcsolóját nem sikerült lezárni. A cím zárolása így is véd.

+

Ehhez az alkalmazás újraindul, és a 15 perc végén még egyszer.

+ + +
+ + + + + + + + + + +
+ + + + + diff --git a/controller/scripts/i18n_go_keys.json b/controller/scripts/i18n_go_keys.json index 5c832f3..e0c8898 100644 --- a/controller/scripts/i18n_go_keys.json +++ b/controller/scripts/i18n_go_keys.json @@ -95,6 +95,7 @@ "err.setup_gate.not_closed": "BORN AS A KEY, v0.280.0 (09 decision 46 / R-710) -- a NEW sentence, never a Go literal. Pinned by internal/web/setup_gate_test.go / internal/stacks/setup_gate_test.go.", "err.setup_gate.open_failed": "BORN AS A KEY, v0.280.0 (09 decision 46 / R-710) -- a NEW sentence, never a Go literal. Pinned by internal/web/setup_gate_test.go / internal/stacks/setup_gate_test.go.", "err.stacks.setup_gate_failed": "BORN AS A KEY, v0.280.0 (09 decision 46 / R-710) -- a NEW sentence, never a Go literal. Pinned by internal/web/setup_gate_test.go / internal/stacks/setup_gate_test.go.", + "err.setup_gate.close_signup_not_offered": "BORN AS A KEY, v0.282.0 (09 decision 49) -- a NEW sentence, never a Go literal. Pinned by internal/web/close_signup_test.go.", "err.setup_gate.probe_not_done": "BORN AS A KEY, v0.281.0 (09 decision 46/47) -- a NEW sentence, never a Go literal. Pinned by internal/web/signup_block_test.go.", "err.setup_gate.no_signup_block": "BORN AS A KEY, v0.281.0 (09 decision 46/47) -- a NEW sentence, never a Go literal. Pinned by internal/web/signup_block_test.go.", "backups_apps.hollow_local": "BORN AS A KEY, v0.279.0 (09 decision 45 / Part D) -- a NEW sentence, never a Go literal. Pinned by internal/web/known_login_test.go / internal/web/r_partd_hollow_page_test.go.",