gates / gates (push) Successful in 41s
Built, not released; no box has run it. felhom.eu `07-backup-architecture.md` §8.2f.
It does nothing without a hub that knows it: an older hub agrees to no id.
- The record: settings `offsite_ends` {app, removed_at, ends_at}. One writer
(backup.StartOffsiteEnd), called by a removal only with „delete backup data”
and by „Törlés 30 nap múlva” on the restore page. A second press changes
nothing. No record, no deletion. Only on the hub-provisioned tier.
- The date is on the remove dialog before the press; the restore page shows
„Törlésre kijelölve …” with „Mégis megtartom”, and one history line per
carried-out end. An install of the same app deletes the record.
- The weekly window: after the guard has passed the policy's plan under the cap
as before, it adds the snapshots whose app tags are ALL due records, that the
hub agreed to and the box named in the same request; the result names them
apart (removed_for_ended_apps). `_shares`, the box's own stacks and an
installed app are never due.
- The report carries the pending records; the household gets one mail per
press (offsite_end_scheduled), in both languages.
MinAgent unchanged (0.158.1). 143 parity fixtures gained the dialog's one new
script line (patched, not regenerated); one new parity case.
Tests TestD72_*, TestD84_*; 56 mutations seen red
(felhom.eu documentation/audits/build-release-4-2026-11-15/A/redproof-ctrl-*.txt).
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
3151 lines
137 KiB
Go
3151 lines
137 KiB
Go
package settings
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"gitea.dooplex.hu/admin/felhom-controller/internal/util"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"gitea.dooplex.hu/admin/felhom-controller/internal/appbackup"
|
|
"gitea.dooplex.hu/admin/felhom-controller/internal/i18n"
|
|
)
|
|
|
|
// Settings holds customer-modifiable overrides and cached state.
|
|
// Persisted as a single JSON file (settings.json) in the data directory.
|
|
type Settings struct {
|
|
mu sync.RWMutex `json:"-"`
|
|
path string `json:"-"`
|
|
log *log.Logger `json:"-"`
|
|
debug bool `json:"-"`
|
|
|
|
// LoadWarning is set (non-empty, Hungarian) when Load recovered from a corrupt settings.json —
|
|
// surfaced to the dashboard as a persistent banner. Not persisted.
|
|
LoadWarning string `json:"-"`
|
|
|
|
// configLanguage (v0.256.0, R-558) is `customer.language` from controller.yaml — the language
|
|
// the hub says this box should START in. It is consulted ONLY when the household has never
|
|
// chosen: GetLanguage prefers the stored choice, always. Not persisted, and deliberately not a
|
|
// field of the JSON: it belongs to the config, which is re-pulled, and writing it into
|
|
// settings.json would turn a default into a choice the household never made.
|
|
configLanguage string `json:"-"`
|
|
|
|
// Auth
|
|
PasswordHash string `json:"password_hash,omitempty"` // bcrypt hash, overrides controller.yaml
|
|
|
|
// Guest launcher share (v0.165.0). LauncherShareToken is the ≥160-bit URL capability token that
|
|
// serves the read-only guest launcher at /s/<token>; empty means sharing is OFF (there is no
|
|
// separate enabled flag — an empty token matches nothing). LauncherSharePasswordHash is an
|
|
// OPTIONAL bcrypt hash for a per-share password, ALWAYS SEPARATE from the admin PasswordHash above.
|
|
// The token is a secret and must never be logged.
|
|
LauncherShareToken string `json:"launcher_share_token,omitempty"`
|
|
// Language (v0.247.0, i18n) — the household's dashboard language: "hu" | "en". Empty means never
|
|
// chosen and reads as Hungarian (GetLanguage). Reported to the hub so its e-mails can follow.
|
|
Language string `json:"language,omitempty"`
|
|
LauncherSharePasswordHash string `json:"launcher_share_password_hash,omitempty"`
|
|
|
|
// FileBrowser admin login (R-513, v0.243.0). Every box used to accept admin/admin. The controller
|
|
// sets a generated password ONCE through FileBrowser's own API when admin/admin still works, and
|
|
// records "set by the operator" when it does not (a hand-set password is never overwritten).
|
|
// FileBrowserAdminPasswordEnc is AES-encrypted with the controller's app key (crypto.Encrypt),
|
|
// never plaintext. FileBrowserAdminState: "" (not yet decided) | "generated" | "operator".
|
|
FileBrowserAdminPasswordEnc string `json:"filebrowser_admin_password_enc,omitempty"`
|
|
FileBrowserAdminState string `json:"filebrowser_admin_state,omitempty"`
|
|
FileBrowserAdminDecidedAt string `json:"filebrowser_admin_decided_at,omitempty"` // RFC3339
|
|
|
|
// Customer-claim arc (v0.122.0, F-4). Claimed is SET-ONLY (a claim or reset completed at
|
|
// least once — never cleared). ClaimCode* cache the freshest hub-delivered code state (report
|
|
// ACK; beats controller.yaml when its generation is newer). ClaimConsumedGeneration records
|
|
// the last code generation successfully consumed — a code of a consumed generation is dead
|
|
// even if its hash still matches (single-use).
|
|
Claimed bool `json:"claimed,omitempty"`
|
|
ClaimCodeHash string `json:"claim_code_hash,omitempty"`
|
|
ClaimCodeGeneration int `json:"claim_code_generation,omitempty"`
|
|
ClaimCodeIssuedAt string `json:"claim_code_issued_at,omitempty"` // RFC3339
|
|
ClaimConsumedGeneration int `json:"claim_consumed_generation,omitempty"`
|
|
|
|
// Notification preferences (Phase 2 — define struct now, leave empty)
|
|
Notifications *NotificationPrefs `json:"notifications,omitempty"`
|
|
|
|
// OffboxEnlargeNoticeSeeded (v0.135.0) guards the ONE-TIME seed of offbox_enlarge_blocked into an
|
|
// existing customer's stored prefs. Persisted so a later opt-out sticks (the 3a-fix getter append
|
|
// re-enabled it on every read — this replaces it).
|
|
OffboxEnlargeNoticeSeeded bool `json:"offbox_enlarge_notice_seeded,omitempty"`
|
|
// AppUpdateEventsSeeded (v0.264.0) guards the ONE-TIME add of app_update_undone / app_update_held
|
|
// into an existing household's stored prefs (seedAppUpdateEvents).
|
|
AppUpdateEventsSeeded bool `json:"app_update_events_seeded,omitempty"`
|
|
|
|
// Upwatch (the upload and CPU watch, internal/upwatch) keeps its own state here as one opaque JSON block: the
|
|
// measured upload line (the last 14 off-site pushes) and qBittorrent's default-limit record (who owns the limit).
|
|
// Opaque on purpose — this package does not know the watch's types, and the watch does not reach into settings.
|
|
Upwatch json.RawMessage `json:"upwatch,omitempty"`
|
|
|
|
// MediaRestartLaterAt is the household's „later" media restart (RFC3339 UTC; empty = none) — stored so a controller
|
|
// restart before 03:30 does not forget it (R-1282).
|
|
MediaRestartLaterAt string `json:"media_restart_later_at,omitempty"`
|
|
// UnhealthyStopEventSeeded (v0.269.0) guards the ONE-TIME add of app_stopped_unhealthy (the
|
|
// seedAppUpdateEvents shape).
|
|
UnhealthyStopEventSeeded bool `json:"unhealthy_stop_event_seeded,omitempty"`
|
|
|
|
// HubEscrowIdentityPresent (v0.199.0, R-204 item 4 / R-193) caches the report ACK's
|
|
// `escrow.identity_blob_present` — whether the HUB is holding a sealed recovery package for this
|
|
// box. It is recorded on EVERY ACK that carries an escrow object, including when no off-site
|
|
// target is configured, which is the whole point: until now that field was read only by the
|
|
// auto-confirm, which returns early on an unconfigured box, so a REBUILT box threw away the one
|
|
// fact that distinguishes it from a box that never had off-site backups.
|
|
//
|
|
// It is half of the "I am rebuilt and stranded" predicate (see backup.OffboxReportStatus). The
|
|
// other half is local: no repository password on disk. **Freshness alone is a box that never had
|
|
// off-site backups; an escrow alone is a healthy box. Only both together mean rebuilt.**
|
|
//
|
|
// Cached, not derived: a rebuilt box has an empty settings.json, so this is re-learned from its
|
|
// first ACK — which is correct, because the hub is the authority on what the hub holds.
|
|
HubEscrowIdentityPresent bool `json:"hub_escrow_identity_present,omitempty"`
|
|
|
|
// HubEscrowSupersededPresent / HubEscrowSupersededAt (v0.201.0, R-222) cache the report ACK's
|
|
// `escrow.superseded_present` / `superseded_at` — whether the hub is ALSO keeping an EARLIER
|
|
// sealed package for this box, and when it was set aside.
|
|
//
|
|
// They exist for one message and nothing else. Without them the recovery screen cannot tell a
|
|
// genuinely wrong recovery code from a code that is RIGHT about an earlier package, because both
|
|
// look identical from here: the unseal fails closed against the package the hub currently serves.
|
|
// Measured on 2026-08-05 (CAMPAIGN-11 Phase 3 step 7) — the customer entered the correct code for
|
|
// their orphaned history and was told to check their typing.
|
|
//
|
|
// ⚠ These grant NO read path. The hub serves the CURRENT package only; retrieving a superseded one
|
|
// is a link that has never been built (R-199's inventory). The screen may say an earlier package is
|
|
// kept and when — both true, both non-secret — and must not promise it can be opened.
|
|
HubEscrowSupersededPresent bool `json:"hub_escrow_superseded_present,omitempty"`
|
|
HubEscrowSupersededAt string `json:"hub_escrow_superseded_at,omitempty"`
|
|
|
|
// HubEscrowKeySHA256 / HubEscrowKeyCheckedAt (v0.206.0, R-241) cache the report ACK's
|
|
// `escrow.restic_pw_sha256` — the sha256 of the repository password the hub's sealed package
|
|
// COVERS — and when it was last recorded.
|
|
//
|
|
// ⚠ THIS FACT WAS ALREADY COMPUTED EVERY CYCLE AND KEPT NOWHERE, and that is the whole of R-241's
|
|
// second half. `report.EscrowAutoConfirmer.Reconcile` has compared this hash against the local key
|
|
// on every ACK since SLICE 3; on the final-walk venue it logged, at 03:28:03Z and thirty-five
|
|
// minutes before the customer looked, *"the hub's escrow blob does not cover the CURRENT repo
|
|
// password (hub hash 30ef574f… != local 9b4a9a9d…)"* — and then dropped it on the floor. The
|
|
// recovery screen, evaluating in the same process, went on asking a question that could not see it.
|
|
//
|
|
// It is the ONE fact that answers the screen's real question directly: *does the hub hold a package
|
|
// for a key other than the one I am using?* Shape (a) ("no key at all") and shape (b) ("a run
|
|
// proved the repo will not open") are both proxies for it, and both have now been wrong in
|
|
// opposite directions — (a) goes false the moment anything mints, (b) is unreachable while the
|
|
// escrow is pending.
|
|
//
|
|
// NON-SECRET: the sha256 of a 256-bit random secret is non-reversible and is already logged and
|
|
// served over the ACK. It must still never reach a customer-facing message.
|
|
//
|
|
// EMPTY IS MEANINGFUL AND IS NOT "THEY DIFFER": the hub sends "" for a legacy hash-less escrow
|
|
// (a package that provably seals no repository password). Shape (c) requires a NON-EMPTY hash —
|
|
// see backup.OffsiteRecoveryOffer for the staleness reasoning.
|
|
HubEscrowKeySHA256 string `json:"hub_escrow_key_sha256,omitempty"`
|
|
HubEscrowKeyCheckedAt string `json:"hub_escrow_key_checked_at,omitempty"` // RFC3339
|
|
|
|
// RecoveryNoticePostponed (v0.200.0, R-193) — the customer chose "most nem" on the full-page
|
|
// recovery screen. It suppresses THE FULL-PAGE INTERRUPTION ONLY. The entry point in the backups
|
|
// area stays, permanently, for as long as the situation lasts: the data is still there whether or
|
|
// not anyone clicked, and a one-shot notice a flustered person clicks past is a notice that never
|
|
// happened. It is deliberately NOT cleared by anything except the situation ending.
|
|
RecoveryNoticePostponed bool `json:"recovery_notice_postponed,omitempty"`
|
|
|
|
// ── THE OFFER EPOCH (v0.206.0, R-241) ───────────────────────────────────────────────────────
|
|
//
|
|
// RecoveryOfferEpoch counts ENTRIES into the offered state; RecoveryOfferActive is the edge
|
|
// detector that makes counting possible. Together they turn "once ever" into "once per entry".
|
|
//
|
|
// ⚠ WHY THIS IS NOT THE FLAG §2.1 FORBIDS. That ruling forbids remembering *that the customer
|
|
// decided* so the screen can be suppressed while the underlying state stays wrong. These record
|
|
// something else entirely: WHICH SITUATION a dismissal was about. A box that abandons, is rebuilt
|
|
// months later and enters the offered state afresh is in a NEW situation, and a dismissal of the
|
|
// old one must not swallow it. `RecoveryNoticePostponed` alone did exactly that — it was
|
|
// deliberately never cleared by anything.
|
|
//
|
|
// RecoveryNoticePostponedEpoch / RecoveryRemindOptOutEpoch record the epoch a choice was made in.
|
|
// The full page interrupts while `Epoch > PostponedEpoch`, and the banner reminds while
|
|
// `Epoch > OptOutEpoch` — so a fresh entry resets BOTH by arithmetic, with nothing to clear and
|
|
// nothing that can be forgotten to clear (§7.1 condition 2).
|
|
RecoveryOfferEpoch int `json:"recovery_offer_epoch,omitempty"`
|
|
RecoveryOfferActive bool `json:"recovery_offer_active,omitempty"`
|
|
// RecoveryOfferSince (RFC3339) stamps when the CURRENT epoch began — the anchor the undecided
|
|
// reminders escalate against (§2.3). Re-stamped on every entry, so a box that settles and is later
|
|
// rebuilt starts its reminder ladder again rather than inheriting an old one.
|
|
RecoveryOfferSince string `json:"recovery_offer_since,omitempty"`
|
|
RecoveryNoticePostponedEpoch int `json:"recovery_notice_postponed_epoch,omitempty"`
|
|
// RecoveryRemindOptOutEpoch — the customer ticked „ne emlékeztessen újra" in this epoch.
|
|
//
|
|
// It silences THE BANNER AND NOTHING ELSE (§7.1 condition 3). It is not an abandonment, it starts
|
|
// no countdown, and the entry point on the backups page never goes away because of it — silencing
|
|
// a reminder is not the same as removing the route, and this session exists partly because a route
|
|
// disappeared.
|
|
RecoveryRemindOptOutEpoch int `json:"recovery_remind_optout_epoch,omitempty"`
|
|
|
|
// Cached state
|
|
DBValidations map[string]DBValidationCache `json:"db_validations,omitempty"`
|
|
|
|
// Per-app backup preferences
|
|
AppBackup map[string]AppBackupPrefs `json:"app_backup,omitempty"`
|
|
// OffboxOfferDismissed (decision 50): the household answered „Nem most" to the one-press offer that
|
|
// switches off-site on for apps installed before v0.283.0. The offer is shown once, not forever.
|
|
OffboxOfferDismissed bool `json:"offbox_offer_dismissed,omitempty"`
|
|
|
|
// OffsiteDataAt (v0.275.0, R-696) — per app, the DATA time of the recovery unit this box last pushed
|
|
// off-site, and when. An off-site snapshot's own time is when it was TAKEN; a run whose dump leg failed
|
|
// still pushes the older dumps, so the snapshot time can overstate its data. The update's precondition
|
|
// caps the off-site copy's age with this record.
|
|
OffsiteDataAt map[string]OffsiteDataRecord `json:"offsite_data_at,omitempty"`
|
|
|
|
// Customer-configurable backup-window start "HH:MM" (v0.168.0). "" = use controller.yaml
|
|
// db_dump_schedule (then the "02:30" default). Every nightly leg derives from this at fixed
|
|
// offsets; overrides yaml when a valid value is present (mirrors PasswordHash precedence).
|
|
BackupWindowStart string `json:"backup_window_start,omitempty"`
|
|
|
|
// AppUpdate (v0.271.0, `09` §3 decision 12) — the per-box switch for AUTOMATIC app updates. The key
|
|
// is `app_update.unattended`; ABSENT MEANS ON (the operator's ruling: on by default), so a box that
|
|
// never saved the switch, and every box upgraded from before v0.271.0, updates its apps by itself.
|
|
// Only an explicit false turns it off. NOT `self_update.auto_update` — that is the controller's own.
|
|
AppUpdate *AppUpdateSettings `json:"app_update,omitempty"`
|
|
|
|
// Storage paths registry
|
|
StoragePaths []StoragePath `json:"storage_paths,omitempty"`
|
|
|
|
// RestoreHolds (R-379/R-380, v0.220.0) records apps this controller is DELIBERATELY keeping
|
|
// stopped because a database restore failed AND the rollback to the customer's own pre-restore
|
|
// copy also failed. Keyed by stack name.
|
|
//
|
|
// WHY THIS AND NOT `AppConfig.DesiredState`: that field is the CUSTOMER'S stated intent — what
|
|
// they asked for. Writing our own failure into it would make our fault indistinguishable from
|
|
// their choice, which is the exact confusion its own comment says it exists to end. The fenced
|
|
// act is "writing DesiredState from the restore path"; reading it stays fine.
|
|
//
|
|
// WHY NOT the app-stop marker: that marker means "owed a restart". A held app is not owed one —
|
|
// leaving the marker active would have Recover() start the broken app at the next controller
|
|
// boot, hours later and quietly, which is the outcome the hold exists to prevent.
|
|
RestoreHolds map[string]RestoreHold `json:"restore_holds,omitempty"`
|
|
|
|
// OffsiteEnds (D72/D84, `07` §8.2f) — the pending off-site end records, by app: no record, no deletion.
|
|
// OffsiteEndsDone is the short history of ends a clean-up window has carried out. See offsite_ends.go.
|
|
OffsiteEnds map[string]OffsiteEnd `json:"offsite_ends,omitempty"`
|
|
OffsiteEndsDone []OffsiteEndDone `json:"offsite_ends_done,omitempty"`
|
|
// UnhealthyStops (v0.269.0, decision 28) — when the box last stopped each app for a crash loop or an
|
|
// out-of-memory storm (RFC3339). Survives the hold being lifted by Start, so a second stop within
|
|
// 24 h is known to be a second one.
|
|
UnhealthyStops map[string]string `json:"unhealthy_stops,omitempty"`
|
|
// ReportedHolds (D53, `08` §10) — the holds last told to the hub as app_held: stack → „reason|at". The hold
|
|
// reporter (internal/holdreport) compares it with RestoreHolds to send app_held for a new or changed hold and
|
|
// app_hold_cleared for one that is gone — also one cleared while the controller was down, because it is kept here.
|
|
ReportedHolds map[string]string `json:"reported_holds,omitempty"`
|
|
|
|
// Cross-drive restic repo password (auto-generated on first use)
|
|
CrossDriveResticPassword string `json:"cross_drive_restic_password,omitempty"`
|
|
|
|
// Last-seen guest boot-id (intermediary-mount model): persisted so the controller can detect a guest
|
|
// reboot across its own restart (it restarts with the guest) and deterministically recreate
|
|
// drive-backed apps once the agent re-propagates the drive.
|
|
LastGuestBootID string `json:"last_guest_boot_id,omitempty"`
|
|
|
|
// Hub verification state
|
|
HubVerified bool `json:"hub_verified,omitempty"`
|
|
HubVerifiedAt string `json:"hub_verified_at,omitempty"` // RFC3339
|
|
HubLastCheck string `json:"hub_last_check,omitempty"` // RFC3339
|
|
|
|
// AppliedConfigVersion is the hub config_version this controller has last pulled + applied
|
|
// (v0.26.0 pull-based config-refresh). 0 = none recorded yet → the first report ACK records the
|
|
// baseline without restarting. A change vs. the ACK triggers a re-pull + self-restart.
|
|
AppliedConfigVersion int `json:"applied_config_version,omitempty"`
|
|
|
|
// Recovery credentials (saved from setup wizard input)
|
|
RetrievalPassword string `json:"retrieval_password,omitempty"`
|
|
|
|
// Pending events (queued for next Hub push)
|
|
PendingEvents []PendingEvent `json:"pending_events,omitempty"`
|
|
|
|
// Geo-restriction settings (Cloudflare WAF rules)
|
|
GeoRestriction *GeoRestriction `json:"geo_restriction,omitempty"`
|
|
|
|
// App-to-app integration state (e.g., "onlyoffice:filebrowser" → state)
|
|
Integrations map[string]IntegrationState `json:"integrations,omitempty"`
|
|
|
|
// AppEmail is the global app-email (SMTP relay) toggle. When on, deployed apps with an
|
|
// smtp_mapping can send mail via the in-controller shim → hub → Resend. Relay-only:
|
|
// no BYO host/port/user/pass (that escape hatch is deferred).
|
|
AppEmail *AppEmail `json:"app_email,omitempty"`
|
|
|
|
// Offbox is the off-box (NAS) restic-SFTP backup target (Part B). One per box. No secrets here —
|
|
// the repo password + SSH key are 0600 files in the data dir.
|
|
Offbox *OffboxTarget `json:"offbox,omitempty"`
|
|
|
|
// SMB holds the LAN network-sharing (Samba) feature state (R-7 slice 1). The household SMB
|
|
// password is NEVER stored here — only UserSet records that one exists (it lives in the samba
|
|
// container's passdb volume). nil = feature never touched (disabled). See internal/settings/smb.go.
|
|
SMB *SMBSettings `json:"smb,omitempty"`
|
|
// SMBShares is the ordered registry of exported folders. Each Path is an absolute host path under
|
|
// a registered storage root; the smb.conf + compose + backup classification all ride this list.
|
|
SMBShares []SMBShare `json:"smb_shares,omitempty"`
|
|
// KeptCopies (D25, operator ruling 2026-10-21; R-1175 + R-1181): second-drive copies whose SOURCE is gone (a drive
|
|
// away or decommissioned, a declared folder missing). They are kept until the household releases one with
|
|
// „Eltávolítás"; no night job removes them. See internal/settings/kept_copies.go.
|
|
KeptCopies []KeptCopy `json:"kept_copies,omitempty"`
|
|
}
|
|
|
|
// AppEmail holds the global app-email toggle and an optional household display name.
|
|
type AppEmail struct {
|
|
Enabled bool `json:"enabled"`
|
|
FromName string `json:"from_name,omitempty"` // optional household display name for the From line
|
|
}
|
|
|
|
// IntegrationState holds the state of a provider:target integration pair.
|
|
type IntegrationState struct {
|
|
Enabled bool `json:"enabled"`
|
|
EnabledAt string `json:"enabled_at,omitempty"` // RFC3339
|
|
Status string `json:"status,omitempty"` // "active", "error", "disabled", "provider_stopped", "target_unavailable"
|
|
LastError string `json:"last_error,omitempty"`
|
|
}
|
|
|
|
// AppBackupPrefs holds per-app backup toggle state.
|
|
type AppBackupPrefs struct {
|
|
// Existing: includes app data in nightly restic (same drive)
|
|
Enabled bool `json:"enabled"`
|
|
|
|
// Cross-drive backup to secondary storage
|
|
CrossDrive *CrossDriveBackup `json:"cross_drive,omitempty"`
|
|
|
|
// Offbox: include this app's recovery unit + DB dumps in the off-box (NAS) restic-SFTP backup
|
|
// (Part B — the "1 off-site" leg of 3-2-1, distinct from the local cross-drive copy and PBS whole-CT).
|
|
Offbox bool `json:"offbox,omitempty"`
|
|
}
|
|
|
|
// OffboxTarget configures the single off-box (NAS) backup destination: an encrypted restic repo reached
|
|
// over SFTP (Part B). It holds NO secrets — the repo password + SSH private key live in 0600 files in the
|
|
// controller data dir (off-box of the secrets rides DR via the PBS whole-CT snapshot of the rootfs); the
|
|
// known-host key is pinned out-of-band. Runtime status is persisted for the UI.
|
|
type OffboxTarget struct {
|
|
Enabled bool `json:"enabled"`
|
|
Host string `json:"host"`
|
|
Port int `json:"port"` // default 22
|
|
User string `json:"user"`
|
|
RepoPath string `json:"repo_path"` // absolute path on the NAS, e.g. /volume1/felhom-backup/repo
|
|
Schedule string `json:"schedule"` // "daily" | "manual"
|
|
// QuotaGB is the shared-model SOFT quota (SLICE 4), mapped from the hub descriptor by the
|
|
// apply-bridge. 0 = no soft limit (dedicated boxes are Hetzner-enforced; manual targets unset).
|
|
// Felhom-enforced: at ≥100% NEW backup runs are refused (prune/restore never are); ≥80% warns.
|
|
QuotaGB int `json:"quota_gb,omitempty"`
|
|
// Transport (v0.289.0, decision 69): "rclone-pinned" for the HUB-provisioned Storage Box tier — the
|
|
// box's key reaches only an append-only rclone server and cannot delete; "" (the default) is the
|
|
// household's own SFTP NAS target, unchanged. Set by ApplyOffsiteTarget, never by a form.
|
|
Transport string `json:"transport,omitempty"`
|
|
|
|
// Runtime status (written by the off-box runner; never holds a secret).
|
|
LastRun string `json:"last_run,omitempty"` // RFC3339
|
|
// LastStatus — "ok" | "incomplete" | "error" | "running". R-203 added "incomplete": the run
|
|
// completed and what it captured is real, but a directory the app declares MANDATORY could not be
|
|
// captured, so the app is NOT fully protected. Distinct from "error" (the run failed) on purpose;
|
|
// SnapshotCount and LastSuccess still record what WAS captured.
|
|
LastStatus string `json:"last_status,omitempty"`
|
|
// LastSuccess (R-100) is the RFC3339 stamp of the last run that actually SUCCEEDED.
|
|
//
|
|
// IT EXISTS BECAUSE LastRun RECORDS AN ATTEMPT, NOT A RESULT. LastRun is written
|
|
// unconditionally at the end of every run, including failures, so "how long since LastRun" answers
|
|
// "how long since we last TRIED" — which is not the question any freshness verdict is asking. The
|
|
// hub's OffsiteChecker asked exactly that question of exactly that field, so a tier failing on
|
|
// every run read as perfectly fresh forever.
|
|
//
|
|
// Written ONLY on the success branch. Never cleared by a failure: a tier that succeeded on Monday
|
|
// and has failed every night since must keep Monday's stamp, because that stamp is precisely what
|
|
// makes the staleness threshold elapse. Clearing it on failure would restore the bug in mirror
|
|
// image (an instantly-stale tier on the first blip — the F-A1 noise path).
|
|
LastSuccess string `json:"last_success,omitempty"` // RFC3339
|
|
// LastIntegrityCheck / LastIntegrityOK (R-359) record the last time `restic check` actually RAN
|
|
// against this repository and what it found. They live HERE, beside LastSuccess, because this is
|
|
// where the off-site tier's state already is — one store, one lifetime, one atomic write.
|
|
//
|
|
// TWO FIELDS AND NOT ONE, for the reason StatsKnown exists two fields below: a surface must be able
|
|
// to tell "never checked" (LastIntegrityCheck empty) from "checked and BAD" (set, and OK false).
|
|
// A single bool cannot, and reading an unchecked store as healthy is the direction that costs data.
|
|
//
|
|
// LastIntegrityCheck is the DUE-NESS anchor and is written on a check that ran and reached a
|
|
// verdict — pass OR fail. It is deliberately NOT written when the check was skipped (a sibling
|
|
// operation held the single-writer flag) or when the repository could not be reached: neither
|
|
// looked at the data, so neither may reset the clock. R-341 is the failure this shape avoids —
|
|
// a dated check that is quietly missed and never catches up.
|
|
LastIntegrityCheck string `json:"last_integrity_check,omitempty"` // RFC3339
|
|
LastIntegrityOK bool `json:"last_integrity_ok,omitempty"`
|
|
// LastIntegrityDepth (R-399) records HOW DEEP that verdict looked: "structure" for the
|
|
// structure-and-index check, or the subset spec that was re-read ("100%", "10%", "1/7", ...).
|
|
//
|
|
// It is a third field rather than a flag for the same reason there are two above: "checked, OK"
|
|
// means two different things at structure depth and at 100%, and a verdict that cannot say which
|
|
// cannot be judged afterwards. EMPTY means NOT RECORDED — a verdict written by a controller older
|
|
// than v0.228.0 — and never "structure"; absence means the box cannot answer, exactly as StatsKnown
|
|
// below establishes for the counts.
|
|
LastIntegrityDepth string `json:"last_integrity_depth,omitempty"`
|
|
// ── R-87: the nightly off-site PROOF ────────────────────────────────────────────────────────────
|
|
//
|
|
// ProvedSnapshots maps a stack name to the SNAPSHOT ID last proved for it — never a timestamp, and
|
|
// the distinction is the whole scheduling model (R-86, 07 §3). A timestamp re-proves the same
|
|
// snapshot forever and says nothing about the newest one; a snapshot ID makes an app due again the
|
|
// moment a new backup lands, and never before. Not a secret (app names + restic short IDs).
|
|
ProvedSnapshots map[string]string `json:"proved_snapshots,omitempty"`
|
|
// The newest verdict, for the report card. LastProofResult is "" when NO proof has ever reached a
|
|
// verdict on this box — a box older than v0.231.0 sends no key at all — and that MUST read as NOT
|
|
// RECORDED, never as a failure. Same rule as StatsKnown above and LastIntegrityDepth's reserved
|
|
// empty: absence and "no" are opposite news and the wire cannot tell them apart unless we do.
|
|
LastProofRun string `json:"last_proof_run,omitempty"` // RFC3339
|
|
LastProofStack string `json:"last_proof_stack,omitempty"`
|
|
LastProofSnapshot string `json:"last_proof_snapshot,omitempty"`
|
|
LastProofResult string `json:"last_proof_result,omitempty"` // "pass" | "fail" | "cannot_judge"
|
|
LastProofReason string `json:"last_proof_reason,omitempty"`
|
|
LastError string `json:"last_error,omitempty"`
|
|
LastDuration string `json:"last_duration,omitempty"`
|
|
RepoSizeHuman string `json:"repo_size_human,omitempty"`
|
|
// RepoSizeBytes (SLICE 4) is the machine-readable repo size from `restic stats` — the soft-quota
|
|
// gate's input (last-known value; a failed stats call keeps the previous one — stale-but-safe).
|
|
RepoSizeBytes int64 `json:"repo_size_bytes,omitempty"`
|
|
SnapshotCount int `json:"snapshot_count,omitempty"`
|
|
// StatsKnown — R-225. Whether SnapshotCount / RepoSizeBytes above were ever actually READ from the
|
|
// repository, as opposed to never having been measured.
|
|
//
|
|
// ⚠ IT IS NAMED RATHER THAN INFERRED FROM THE COUNTS, for the same reason `OffsiteInventory.Empty`
|
|
// is: **zero is what an unread store and a genuinely empty one both look like**, and the two are
|
|
// opposite news. Both fields are `omitempty` ints, so on the wire and on disk "absent" and "0" are
|
|
// the same bytes — the distinction cannot be recovered downstream and has to be carried.
|
|
//
|
|
// Measured live on 2026-08-05 (CAMPAIGN-11, R-225): after a rebuild the box rendered
|
|
// „Tároló méret · 0 pillanatkép" and „Tárhelykeret: 0 / 50 GB (0%)" — directly above a card saying
|
|
// the store held backups made under another key. An SFTP listing found snapshot `f3d9cd67` and
|
|
// 12 535 KB really there. The keys were simply ABSENT from settings.json and the zero value spoke
|
|
// for them.
|
|
//
|
|
// Set true by the run that reads the stats, whatever it reads — a true zero is knowledge too.
|
|
StatsKnown bool `json:"stats_known,omitempty"`
|
|
// LastWarning is a customer-visible notice set on an otherwise-OK run when SOME toggled apps had
|
|
// no discoverable recovery unit (partial run). Empty on a fully-successful or failed run.
|
|
LastWarning string `json:"last_warning,omitempty"`
|
|
// LastWarningKind names WHAT LastWarning is about, so the page can react to it without reading its
|
|
// Hungarian words (R-553). Today one kind exists: OffboxWarnNoAppsSelected, the zero-selection
|
|
// notice the Távoli mentés page replaces once apps HAVE been selected. Written by the run that
|
|
// writes LastWarning, cleared with it.
|
|
LastWarningKind string `json:"last_warning_kind,omitempty"`
|
|
// EnlargedBlocked (3a) lists the apps whose ENLARGED (mandatory-userdata) offsite push was refused
|
|
// by the pre-push quota gate on the last run — their unit-only push still succeeded. Replaced each
|
|
// OK run (sorted; empty clears). Drives the per-app "config+DB only" note on /backups/remote and
|
|
// the edge-triggered enlarge-blocked notification. Not a secret (app-name list).
|
|
EnlargedBlocked []string `json:"enlarged_blocked,omitempty"`
|
|
// Shares offsite leg status (R-7b). The offsite run gained a SIBLING shares source that pushes the
|
|
// „Felhőmentés"-marked SMB shares plus the share-definition manifest under the reserved `_shares`
|
|
// tag. These three fields let the „Megosztás" page state per-tier truth instead of inferring it
|
|
// from the app-wide LastStatus. SharesLastCount is the number of share folders in the push (0 = a
|
|
// definitions-only push, e.g. quota-degraded or no share is marked for the cloud). Not secrets.
|
|
SharesLastRun string `json:"shares_last_run,omitempty"` // RFC3339
|
|
SharesLastStatus string `json:"shares_last_status,omitempty"` // "ok" | "error" | "blocked" | "skipped"
|
|
SharesLastCount int `json:"shares_last_count,omitempty"`
|
|
// EscrowState (fork-4) gates offsite RUNS on the repo password being escrowed under R: ""|"pending"
|
|
// |"escrowed". Enabling offsite stages the password to the agent and sets "pending"; no offsite run
|
|
// proceeds until an operator confirms the escrow ceremony ("escrowed") — so no un-recoverable
|
|
// offsite ciphertext can exist. It is NOT a secret (a state label); the password never lives here.
|
|
EscrowState string `json:"escrow_state,omitempty"`
|
|
// CeremonyCompletedAt (v0.138.0) is the RFC3339 stamp of the last successful escrow ceremony
|
|
// (recovery-code claim) taken while EscrowState is still "pending". It drives the "awaiting hub
|
|
// confirmation" card on /backups/remote during the report-cycle gap between the ceremony and the
|
|
// hub-verified pending→escrowed flip (report.EscrowAutoConfirmer). Zeroed by that flip (and the
|
|
// deprecated manual confirm). Persisted, so it survives a controller restart mid-wait. Not a secret.
|
|
CeremonyCompletedAt string `json:"ceremony_completed_at,omitempty"`
|
|
|
|
// RepoState (v0.142.0, offsite continuity) classifies the offsite REPO — "" normal | "orphaned".
|
|
// ORPHANED = the remote repo exists but was keyed under a passphrase this controller no longer has
|
|
// (the reinstall/recreated-volume shape: `restic cat config` → "wrong password or no key found").
|
|
// While orphaned, scheduled runs SKIP (one event, not nightly) and the remote page shows the orphan
|
|
// card instead of the raw restic error; a reset (move-aside + init) clears it. Not a secret.
|
|
RepoState string `json:"repo_state,omitempty"`
|
|
// OrphanedAt is the RFC3339 stamp of the orphan detection (drives the card copy).
|
|
OrphanedAt string `json:"orphaned_at,omitempty"`
|
|
// OrphanedRenamedTo records the move-aside path of the last reset (e.g. <repo>.orphaned-20260717),
|
|
// so the card/log can name where the old history was set aside.
|
|
//
|
|
// ⚠ R-228 (2026-08-06) — THIS WAS WRITTEN AND READ BY NOBODY, and this comment used to call the
|
|
// set-aside history "recovery-code-recoverable", which is **not true today**: serving a superseded
|
|
// blob is an unbuilt link (R-199's inventory), so the old store cannot be opened by the customer,
|
|
// the operator, or anyone else. Measured on 2026-08-05 (CAMPAIGN-11 F7): after a customer chose to
|
|
// set their old backups aside, 12 535 KB sat at this exact path and `/backups/remote` mentioned it
|
|
// nowhere — a census found zero references to this field in any template or handler. The screen
|
|
// promised the data was kept and then showed nothing.
|
|
//
|
|
// It is surfaced now, as a plain statement that an earlier history is KEPT and NOT DELETED. It must
|
|
// NOT promise the history can be reopened — that is the R-202 lesson, and a conditional promise
|
|
// that turns out false is worse on this surface than saying less.
|
|
OrphanedRenamedTo string `json:"orphaned_renamed_to,omitempty"`
|
|
|
|
// ── ABANDONMENT (v0.206.0, R-241) — deciding to give up the old history is a FINISHABLE thing ──
|
|
//
|
|
// Until now "set aside" renamed the remote store and touched nothing else, so the hub went on
|
|
// holding a package for a key the box no longer used — and the recovery question came back at
|
|
// every login, for ever. The operator's ruling (2026-08-07) is that the answer is NOT to remember
|
|
// that the customer decided, but to reach a state where the question stops arising: **fix the
|
|
// state, do not remember that it is wrong.** These fields are that countdown.
|
|
//
|
|
// ⚠ THEY ARE NOT A "THEY DECIDED" FLAG, and the distinction is the ruling. Nothing here suppresses
|
|
// the recovery offer — the offer stays reachable for the whole 14 days, because a grace period in
|
|
// which nothing can be done is decorative (Scenario E). What ends the offer is the TERMINAL STEP
|
|
// removing the store and the sealed package together, after which shape (c) has nothing to
|
|
// compare and falls silent on its own.
|
|
//
|
|
// AbandonStartedAt / AbandonAt are RFC3339; AbandonRepoPath is the move-aside path the terminal
|
|
// step deletes. AbandonRepoPath is separate from OrphanedRenamedTo deliberately: that field is
|
|
// overwritten by the NEXT reset, and a countdown that loses the path it is counting down to would
|
|
// delete nothing and report success.
|
|
AbandonStartedAt string `json:"abandon_started_at,omitempty"`
|
|
AbandonAt string `json:"abandon_at,omitempty"`
|
|
AbandonRepoPath string `json:"abandon_repo_path,omitempty"`
|
|
// AbandonPurgeRequested — the remote store IS deleted and the hub has not yet confirmed the sealed
|
|
// package is gone. It is a two-phase-commit marker for an operation in flight, NOT a memory of a
|
|
// decision: it is set by the terminal step, declared in the report, and cleared the moment the
|
|
// hub's ACK stops reporting a superseded package. If the two halves could not be removed together
|
|
// this marker is what makes the box keep asking until they are (Scenario F).
|
|
AbandonPurgeRequested bool `json:"abandon_purge_requested,omitempty"`
|
|
// AbandonHubDueAt (v0.290.0, decision 74) — RFC3339: the deletion was HANDED TO THE HUB, which deletes
|
|
// the set-aside copy at this time unless cancelled. The box's own key cannot delete (decision 69).
|
|
AbandonHubDueAt string `json:"abandon_hub_due_at,omitempty"`
|
|
// AbandonPinnedEscrowKeySHA256 (R-302) — the hub's escrow key fingerprint AS CACHED AT THE MOMENT
|
|
// THE CUSTOMER DECIDED. It is NOT the current key and NOT re-read: the banner's retrieval promise
|
|
// is rendered only while the hub is still holding that same package.
|
|
//
|
|
// ⚠ IT IS A RECORDED ASSUMPTION, NOT A PROOF, AND THAT IS DELIBERATE. Nothing on the box records
|
|
// which key wrote the set-aside copies — that key is gone, which is why they were set aside. What
|
|
// is pinned is the package the hub held at the decision, which in the ordinary rebuilt-box story IS
|
|
// the pre-rebuild escrow covering the pre-rebuild repo password, i.e. the one that wrote them. On a
|
|
// TWICE-rebuilt box that presumption can be wrong: the hub may hold rebuild #2's package while the
|
|
// set-aside copies are rebuild #1's, and no key on file opens them. This pin cannot detect that.
|
|
//
|
|
// What it DOES detect, and what the rejected alternative could not: the package being REPLACED
|
|
// after the decision — a fresh escrow ceremony, which is exactly the act that cost both demo boxes
|
|
// their history on 2026-08-04. The rejected proxy (hub fingerprint vs the CURRENT key, compared at
|
|
// render) answers "does the hub hold a different key?", which is TRUE in the co-render case and so
|
|
// would promise precisely where the promise is least safe.
|
|
//
|
|
// EMPTY IS MEANINGFUL AND IS NOT A MATCH: the hub sends "" for a legacy package that provably seals
|
|
// no repository password, and a countdown started before R-302 has no pin at all. Both take the
|
|
// cautious branch. NEVER rendered, logged or reported — it is the hash of a secret.
|
|
AbandonPinnedEscrowKeySHA256 string `json:"abandon_pinned_escrow_key_sha256,omitempty"`
|
|
}
|
|
|
|
// CrossDriveBackup configures per-app backup to a secondary drive.
|
|
type CrossDriveBackup struct {
|
|
Enabled bool `json:"enabled"`
|
|
Method string `json:"method"` // "rsync" or "restic"
|
|
DestinationPath string `json:"destination_path"` // e.g., "/mnt/hdd_1"
|
|
Schedule string `json:"schedule"` // "daily", "weekly", "manual"
|
|
|
|
// Runtime state (updated by backup runner, persisted for display)
|
|
LastRun string `json:"last_run,omitempty"` // RFC3339
|
|
LastStatus string `json:"last_status,omitempty"` // "ok", "error", "running"
|
|
LastError string `json:"last_error,omitempty"`
|
|
// LastSuccess (R-101) is the last COPY that actually succeeded — the only timestamp a customer may
|
|
// be shown as evidence that a copy exists. LastRun above is written on failure too
|
|
// (recordTier2Failure), so it records an ATTEMPT; presenting it as „Legutóbbi másolat" in the
|
|
// restore dialog told a customer a copy existed from last night when last night had failed.
|
|
// Same rule and shape as the offsite tier's anchor — see backup.offboxAnchorAfterRun.
|
|
LastSuccess string `json:"last_success,omitempty"` // RFC3339
|
|
// SuccessTracked distinguishes "this row predates the anchor" from "this row has an anchor and it
|
|
// is empty, i.e. nothing has succeeded". Without it the two are indistinguishable (both are
|
|
// LastSuccess=="") and every pre-existing row on the fleet would render as never-succeeded on the
|
|
// deploy — all 7 rows on the two demo boxes were in exactly that state. Set by every runner write.
|
|
SuccessTracked bool `json:"success_tracked,omitempty"`
|
|
LastWarning string `json:"last_warning,omitempty"` // Tier-2 3b: capture-gap / state-only notice (Hungarian)
|
|
// UnitLegSkipped / UnitPackageDate (R-403) — the newest run PRESERVED the copy's recovery unit
|
|
// instead of refreshing it, because the source unit carried no data and this one does. Both exist
|
|
// so the surface cannot render a preserved package as a fresh one: LastRun/LastSuccess describe
|
|
// the RUN, and after a skip they no longer describe the PACKAGE. UnitPackageDate is read from the
|
|
// destination unit's own manifest, so it is a fact about the copy; "" means UNKNOWN, never "now".
|
|
UnitLegSkipped bool `json:"unit_leg_skipped,omitempty"`
|
|
UnitPackageDate string `json:"unit_package_date,omitempty"`
|
|
LastDuration string `json:"last_duration,omitempty"` // "2m34s"
|
|
LastSizeHuman string `json:"last_size_human,omitempty"` // "1.2 GB"
|
|
|
|
// Customer preference (set from the per-app Tier-2 config panel; PRESERVED across the runner's
|
|
// status writes). UserDisabled turns Tier 2 off for this app; PreferredTarget pins a chosen
|
|
// destination drive (a registered storage Path) instead of the auto-pick ("" = auto).
|
|
UserDisabled bool `json:"user_disabled,omitempty"`
|
|
PreferredTarget string `json:"preferred_target,omitempty"`
|
|
// Unproven (v0.317.0, `16` D2): the last copy sits on a drive the host agent cannot prove is another
|
|
// physical disk (a VM, a hidden USB serial). It was made; it does not count as a second copy.
|
|
Unproven bool `json:"unproven,omitempty"`
|
|
UnprovenReason string `json:"unproven_reason,omitempty"`
|
|
}
|
|
|
|
// Storage path kinds. A DRIVE is a physical disk with the full enroll/eject/decommission/migrate/wipe
|
|
// lifecycle (agent /disks). A NETWORK share is a NAS (Part A2) proxied to the agent /netstorage — a
|
|
// DISTINCT class with NO drive lifecycle (no eject/decommission/migrate/wipe/SMART; remove is the only
|
|
// lifecycle action). An empty Kind means "drive" (back-compat with already-persisted paths).
|
|
const (
|
|
StorageKindDrive = "drive"
|
|
StorageKindNetwork = "network"
|
|
// StorageKindInternal (v0.318.0, felhom.eu architecture/16 §5) is the one-disk box's internal data place
|
|
// („Belső tárhely"): a volume on the SYSTEM disk the agent mounts like a drive. Apps and their data live there;
|
|
// the drive lifecycle that would remove or format it (eject, decommission, wipe) does not apply — moving its data
|
|
// to another drive does.
|
|
StorageKindInternal = "internal"
|
|
)
|
|
|
|
// NetworkMountRoot is the in-guest path under which the agent propagates NAS shares (mirrors the agent's
|
|
// /mnt/felhom-drives bind root). A registered network path is NetworkMountRoot + "/" + <share name>.
|
|
const NetworkMountRoot = "/mnt/felhom-drives"
|
|
|
|
// StoragePath represents a registered external storage location.
|
|
type StoragePath struct {
|
|
Path string `json:"path"` // e.g., "/mnt/hdd_1" (drive) or "/mnt/felhom-drives/<name>" (network)
|
|
Label string `json:"label,omitempty"` // e.g., "Külső HDD 1TB"
|
|
IsDefault bool `json:"is_default,omitempty"` // the deploy FORM pre-selects it (templates/deploy.html); the deploy API applies no default (R-368)
|
|
Schedulable bool `json:"schedulable"` // whether new apps can be deployed here
|
|
AddedAt string `json:"added_at"` // RFC3339
|
|
Disconnected bool `json:"disconnected,omitempty"` // true when drive detected as disconnected
|
|
DisconnectedAt string `json:"disconnected_at,omitempty"` // RFC3339 timestamp of disconnect detection
|
|
StoppedStacks []string `json:"stopped_stacks,omitempty"` // stacks auto-stopped on disconnect
|
|
Decommissioned bool `json:"decommissioned,omitempty"` // true when drive data migrated to another
|
|
DecommissionedAt string `json:"decommissioned_at,omitempty"` // RFC3339 timestamp
|
|
MigratedTo string `json:"migrated_to,omitempty"` // path of target drive
|
|
|
|
// The media drive events (v0.313.0, R-1023/R-1038/R-1044, `09` §3 decisions 238/239/245). MediaChangedAt: the drive
|
|
// was added, removed, or came back — the media apps must restart to see it; MediaRestartedAt: they were restarted
|
|
// after that (the drive card's „apps restarted since this drive changed"). Ejected*: a SAFE removal keeps the drive
|
|
// registered (R-1044): EjectedAt marks it, EjectDurableID finds it again, EjectSeenGone says the disk left after the
|
|
// eject (so its return is a return, not the still-mounted raw disk), EjectPaused lists the torrents the removal
|
|
// paused ("qbit:<hash>", "trans:<hash>") so its return resumes exactly those.
|
|
MediaChangedAt string `json:"media_changed_at,omitempty"`
|
|
MediaChange string `json:"media_change,omitempty"` // added | removed | returned
|
|
MediaRestartedAt string `json:"media_restarted_at,omitempty"`
|
|
EjectedAt string `json:"ejected_at,omitempty"`
|
|
EjectDurableID string `json:"eject_durable_id,omitempty"`
|
|
EjectSeenGone bool `json:"eject_seen_gone,omitempty"`
|
|
EjectPaused []string `json:"eject_paused,omitempty"`
|
|
|
|
// Kind discriminates a physical drive ("" / "drive") from a NAS network share ("network"). A network
|
|
// share is bulk-media only and carries the fields below; the drive lifecycle does NOT apply to it.
|
|
Kind string `json:"kind,omitempty"`
|
|
|
|
// BackupTarget (E-2) marks the drive the WHOLE-GUEST vzdump is written to — the sibling role to
|
|
// Schedulable/IsDefault/Kind.
|
|
//
|
|
// THIS FIELD IS INTENT, NOT TRUTH. The authority is the agent's `backup.local_backup_target` in
|
|
// agent.json; this records which drive the customer ASSIGNED so the controller can (a) render the
|
|
// degraded/healthy state, (b) notice when the assigned drive goes absent, and (c) detect drift from
|
|
// what the agent is actually doing. Read the agent's `GET /backup/tiers` for truth; never assume
|
|
// this flag and the agent agree.
|
|
//
|
|
// THE RULE THIS EXISTS TO ENFORCE: a drive NEVER acquires this role by appearing. Nothing in the
|
|
// registration path sets it — only an explicit customer choice through SetBackupTarget does.
|
|
// Attributes (transport, removable, size) may SUGGEST a candidate and may refuse the absurd; they
|
|
// may never select one. The reference hardware settles it: demo-felhom's backup drive is an
|
|
// external USB HDD and BOTH demo boxes' drives report removable=0, so a transport rule would
|
|
// disqualify the reference drive and a removable rule would find no candidate at all.
|
|
//
|
|
// Exactly one path may carry it (SetBackupTarget clears the others), and it is STICKY: it does not
|
|
// move because a new drive appeared, and it is never cleared just because the drive is absent —
|
|
// an absent target must stay assigned and ALARM (E-2 Part 5), because silently retargeting is how
|
|
// a backup lands somewhere nobody expects. See [[storage-authz-redesign]] for the role vocabulary.
|
|
BackupTarget bool `json:"backup_target,omitempty"`
|
|
// Network-storage descriptors (Kind=="network" only; mirror the agent A1 add request). NO password
|
|
// is stored — the SMB credential is passed through to the agent at add-time and never persisted here.
|
|
Protocol string `json:"protocol,omitempty"` // nfs | smb
|
|
Server string `json:"server,omitempty"`
|
|
Export string `json:"export,omitempty"`
|
|
MappedUID int `json:"mapped_uid,omitempty"`
|
|
MappedGID int `json:"mapped_gid,omitempty"`
|
|
}
|
|
|
|
// IsNetwork reports whether this is a NAS network-storage path (vs a physical drive). The drive
|
|
// lifecycle (eject/decommission/migrate/wipe/SMART) must NEVER be applied to a network path.
|
|
func (p StoragePath) IsNetwork() bool { return p.Kind == StorageKindNetwork }
|
|
|
|
// IsInternal reports whether this is the internal data place (`16` §5).
|
|
func (p StoragePath) IsInternal() bool { return p.Kind == StorageKindInternal }
|
|
|
|
// NotificationPrefs holds customer notification preferences.
|
|
type NotificationPrefs struct {
|
|
Email string `json:"email,omitempty"`
|
|
// EnabledEvents: no omitempty since R-1199 reopened (2026-10-22) — a household that unticks every mail saves [],
|
|
// and omitempty dropped it, so after the next start the page showed every default mail ticked while the hub mailed
|
|
// by the empty list (measured on Tester 1 and demo-hp: their file held only `cooldown_hours`).
|
|
EnabledEvents []string `json:"enabled_events"`
|
|
CooldownHours int `json:"cooldown_hours,omitempty"` // default: 6
|
|
// EmailCleared (R-922, operator ruling 2026-10-09 option A) marks a DELIBERATE clear: the household
|
|
// saved an empty address where one was stored. Every hub push carries it as `email_cleared: true`
|
|
// while the address stays empty, so the hub deletes the address it holds — and a push the hub missed
|
|
// is repaired by the next one. A box that never had an address never sets it (the hub's no-clobber
|
|
// guard must keep protecting a seeded address); a new address drops it. Set only by
|
|
// web.settingsNotificationsHandler via ClearedBy. Pinned by internal/web TestR922_*.
|
|
EmailCleared bool `json:"email_cleared,omitempty"`
|
|
}
|
|
|
|
// ClearedBy reports whether saving `newEmail` over these stored prefs is (or keeps) a deliberate clear:
|
|
// the new address is empty AND the stored one was not — or the stored prefs already record a clear.
|
|
func (p *NotificationPrefs) ClearedBy(newEmail string) bool {
|
|
if newEmail != "" || p == nil {
|
|
return false
|
|
}
|
|
return p.Email != "" || p.EmailCleared
|
|
}
|
|
|
|
// SyncOnStartup reports whether the startup push should run: an address to restore after a hub DB
|
|
// rebuild, or a household clear the hub may not have received yet (R-922).
|
|
func (p *NotificationPrefs) SyncOnStartup() bool {
|
|
return p != nil && (p.Email != "" || p.EmailCleared)
|
|
}
|
|
|
|
// NotificationPrefsSaved reports whether the household ever saved its notification choice on this box. A box that never
|
|
// did shows DefaultEnabledEvents ticked on its page (GetNotificationPrefs) — R-1199: the hub must then mail by that
|
|
// same list, so the start-up sync pushes it (main.go, prefsSyncAtStartup).
|
|
func (s *Settings) NotificationPrefsSaved() bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.Notifications != nil
|
|
}
|
|
|
|
// DefaultEnabledEvents are the events enabled by default for new customers.
|
|
var DefaultEnabledEvents = []string{
|
|
"backup_failed",
|
|
"db_dump_failed",
|
|
"disk_warning",
|
|
"disk_critical",
|
|
"storage_disconnected",
|
|
"node_down",
|
|
"health_critical",
|
|
"expected_backup_missed",
|
|
"expected_dbdump_missed",
|
|
"offbox_enlarge_blocked", // 3a-fix (warning-class): remote enlargement refused by the quota gate
|
|
// v0.264.0 (`09` §3 decision 15): the household is told ONCE when an update is undone, and when it
|
|
// (or its undo) failed and the app is held. On by default; seeded into existing prefs once below.
|
|
"app_update_undone",
|
|
"app_update_held",
|
|
// v0.269.0 (`09` §3 decision 28): the box stopped an app that kept crashing / ran out of memory.
|
|
"app_stopped_unhealthy",
|
|
// v0.309.0 (R-388 slice 1, operator Q1 2026-10-12): the default completes the page's groups 1 and 3
|
|
// („A gépem és a meghajtóim", „Amit mi intézünk" — on by default). Only households with NO saved list
|
|
// follow this; no saved choice is changed and nothing is seeded into stored prefs.
|
|
// Pinned by TestR388_DefaultListAsGroups.
|
|
"storage_reconnected",
|
|
"backup_integrity_failed",
|
|
"crossdrive_failed",
|
|
"health_recovered",
|
|
}
|
|
|
|
// PendingEvent is an event queued for the next Hub push cycle.
|
|
type PendingEvent struct {
|
|
EventType string `json:"event_type"`
|
|
Severity string `json:"severity"`
|
|
Message string `json:"message"`
|
|
Details string `json:"details"` // JSON string
|
|
CreatedAt string `json:"created_at"` // RFC3339
|
|
}
|
|
|
|
// GeoRestriction holds global and per-app geo-restriction settings.
|
|
type GeoRestriction struct {
|
|
Enabled bool `json:"enabled"`
|
|
AllowedCountries []string `json:"allowed_countries"`
|
|
AppOverrides map[string]AppGeoOverride `json:"app_overrides,omitempty"`
|
|
|
|
// Sync state (updated by geo sync manager)
|
|
LastSync string `json:"last_sync,omitempty"` // RFC3339
|
|
LastSyncError string `json:"last_sync_error,omitempty"`
|
|
ZoneID string `json:"zone_id,omitempty"` // cached Cloudflare zone ID
|
|
RulesetID string `json:"ruleset_id,omitempty"` // cached Cloudflare ruleset ID
|
|
}
|
|
|
|
// AppGeoOverride holds per-app country override.
|
|
type AppGeoOverride struct {
|
|
AllowedCountries []string `json:"allowed_countries"`
|
|
}
|
|
|
|
// DBValidationCache holds cached DB dump validation results.
|
|
type DBValidationCache struct {
|
|
ValidatedAt string `json:"validated_at"` // RFC3339
|
|
TableCount int `json:"table_count"`
|
|
HasHeader bool `json:"has_header"`
|
|
Error string `json:"error,omitempty"`
|
|
// M18: Size + ModTime let ListDumpFiles skip the expensive line-by-line re-validation on every
|
|
// ~5-min scheduler cycle when the dump file is unchanged. A cache entry is a HIT only when both the
|
|
// file size and (RFC3339, second-precision) modtime match the on-disk file.
|
|
Size int64 `json:"size,omitempty"`
|
|
ModTime string `json:"mod_time,omitempty"` // RFC3339 (UTC)
|
|
}
|
|
|
|
// SetDebug enables or disables debug logging for settings operations.
|
|
func (s *Settings) SetDebug(debug bool) {
|
|
s.debug = debug
|
|
}
|
|
|
|
// Load reads settings from the given file path.
|
|
// Returns empty Settings if the file doesn't exist (not an error).
|
|
func Load(path string, logger *log.Logger) (*Settings, error) {
|
|
s := &Settings{
|
|
path: path,
|
|
log: logger,
|
|
}
|
|
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
logger.Printf("[INFO] [settings] No settings.json found, using defaults")
|
|
// A fresh box's defaults already carry every type the one-time add-only seeds add, so they are DONE for it.
|
|
// Unset, they ran at the second start and re-added a type the household had just switched off — the
|
|
// „a later opt-out sticks" promise of each seed was false on every new box (found 2026-10-22, R-1199
|
|
// reopened). Persisted with the first save. Pinned by TestR1199Reopened_AnEmptySavedListStaysEmpty.
|
|
s.OffboxEnlargeNoticeSeeded, s.AppUpdateEventsSeeded, s.UnhealthyStopEventSeeded = true, true, true
|
|
return s, nil
|
|
}
|
|
return nil, fmt.Errorf("reading settings file: %w", err)
|
|
}
|
|
|
|
if err := json.Unmarshal(data, s); err != nil {
|
|
// CORRUPT primary — never crash-loop. Recover from the last-known-good .bak; failing that,
|
|
// preserve the corrupt file for forensics and start on safe defaults (recoverable: an empty
|
|
// PasswordHash falls back to controller.yaml; the storage registry re-discovers on startup).
|
|
logger.Printf("[ERROR] [settings] primary settings corrupt (%v) — attempting recovery from .bak", err)
|
|
if bak, berr := os.ReadFile(path + ".bak"); berr == nil {
|
|
s2 := &Settings{path: path, log: logger}
|
|
if json.Unmarshal(bak, s2) == nil {
|
|
logger.Printf("[WARN] [settings] recovered settings from .bak; re-promoting to primary")
|
|
_ = os.WriteFile(path, bak, 0644) // best-effort promote
|
|
s2.LoadWarning = "settings.json volt sérült — visszaállítva biztonsági másolatból"
|
|
s2.migrateResticToRsync()
|
|
s2.seedOffboxEnlargeNotice()
|
|
return s2, nil
|
|
}
|
|
}
|
|
corrupt := fmt.Sprintf("%s.corrupt-%d", path, time.Now().Unix())
|
|
_ = os.Rename(path, corrupt)
|
|
logger.Printf("[ERROR] [settings] settings unrecoverable — preserved as %s; starting with safe defaults", corrupt)
|
|
return &Settings{path: path, log: logger, LoadWarning: "settings.json sérült és helyreállíthatatlan — alapértelmezett beállítások"}, nil
|
|
}
|
|
|
|
logger.Printf("[INFO] [settings] Loaded settings from %s", path)
|
|
if s.debug {
|
|
s.log.Printf("[DEBUG] [settings] loaded: storage_paths=%d integrations=%d pending_events=%d",
|
|
len(s.StoragePaths), len(s.Integrations), len(s.PendingEvents))
|
|
}
|
|
s.migrateResticToRsync()
|
|
s.seedOffboxEnlargeNotice()
|
|
s.seedAppUpdateEvents()
|
|
s.seedUnhealthyStopEvent()
|
|
return s, nil
|
|
}
|
|
|
|
// seedOffboxEnlargeNotice runs ONCE (guarded by OffboxEnlargeNoticeSeeded): an existing customer whose
|
|
// stored prefs predate offbox_enlarge_blocked (v0.135.0) gets it appended enabled — they could not have
|
|
// deliberately disabled a type that did not exist. Persisted, so a LATER opt-out sticks (unlike the
|
|
// 3a-fix getter append, which re-enabled it on every read). Fresh customers (nil prefs) get the type via
|
|
// DefaultEnabledEvents; the seed only touches customers with an explicit stored EnabledEvents list.
|
|
func (s *Settings) seedOffboxEnlargeNotice() {
|
|
if s.OffboxEnlargeNoticeSeeded {
|
|
return
|
|
}
|
|
s.OffboxEnlargeNoticeSeeded = true
|
|
if s.Notifications != nil && s.Notifications.EnabledEvents != nil {
|
|
s.Notifications.EnabledEvents = appendIfAbsent(s.Notifications.EnabledEvents, "offbox_enlarge_blocked")
|
|
}
|
|
if err := s.save(); err != nil && s.log != nil {
|
|
s.log.Printf("[ERROR] [settings] Failed to save offbox-enlarge-notice seed: %v", err)
|
|
}
|
|
}
|
|
|
|
// seedAppUpdateEvents runs ONCE (guarded by AppUpdateEventsSeeded, v0.264.0) — the
|
|
// seedOffboxEnlargeNotice shape. A household whose stored prefs predate app_update_undone /
|
|
// app_update_held gets both appended: they could not have switched off a type that did not exist.
|
|
// ADD-ONLY, never removes a choice; persisted, so a LATER opt-out sticks. The hub runs the same one-time
|
|
// add on its side — BOTH are needed, because this list is pushed to the hub on every save of the
|
|
// notification page and would otherwise take the types away again.
|
|
func (s *Settings) seedAppUpdateEvents() {
|
|
if s.AppUpdateEventsSeeded {
|
|
return
|
|
}
|
|
s.AppUpdateEventsSeeded = true
|
|
if s.Notifications != nil && s.Notifications.EnabledEvents != nil {
|
|
s.Notifications.EnabledEvents = appendIfAbsent(s.Notifications.EnabledEvents, "app_update_undone")
|
|
s.Notifications.EnabledEvents = appendIfAbsent(s.Notifications.EnabledEvents, "app_update_held")
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] app update events added to the household's notification prefs (one-time, add-only)")
|
|
}
|
|
}
|
|
if err := s.save(); err != nil && s.log != nil {
|
|
s.log.Printf("[ERROR] [settings] Failed to save the app-update-events seed: %v", err)
|
|
}
|
|
}
|
|
|
|
// seedUnhealthyStopEvent runs ONCE (v0.269.0, decision 28) — the seedAppUpdateEvents shape, ADD-ONLY:
|
|
// a household whose stored prefs predate app_stopped_unhealthy gets it; a later opt-out sticks. The hub
|
|
// (v0.123.0) runs the same one-time add on its side, because this list is pushed to it on every save.
|
|
func (s *Settings) seedUnhealthyStopEvent() {
|
|
if s.UnhealthyStopEventSeeded {
|
|
return
|
|
}
|
|
s.UnhealthyStopEventSeeded = true
|
|
if s.Notifications != nil && s.Notifications.EnabledEvents != nil {
|
|
s.Notifications.EnabledEvents = appendIfAbsent(s.Notifications.EnabledEvents, "app_stopped_unhealthy")
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] app_stopped_unhealthy added to the household's notification prefs (one-time, add-only)")
|
|
}
|
|
}
|
|
if err := s.save(); err != nil && s.log != nil {
|
|
s.log.Printf("[ERROR] [settings] Failed to save the unhealthy-stop event seed: %v", err)
|
|
}
|
|
}
|
|
|
|
// migrateResticToRsync converts any cross-drive backup configs using restic to rsync.
|
|
// Called once during Load() before the mutex is exposed.
|
|
func (s *Settings) migrateResticToRsync() {
|
|
changed := false
|
|
for name, prefs := range s.AppBackup {
|
|
if prefs.CrossDrive != nil && prefs.CrossDrive.Method == "restic" {
|
|
prefs.CrossDrive.Method = "rsync"
|
|
s.AppBackup[name] = prefs
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] Migrated cross-drive backup for %s from restic to rsync", name)
|
|
}
|
|
changed = true
|
|
}
|
|
}
|
|
if changed {
|
|
if err := s.save(); err != nil && s.log != nil {
|
|
s.log.Printf("[ERROR] [settings] Failed to save restic→rsync migration: %v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Save writes settings to disk atomically (write to .tmp, rename).
|
|
// Caller must hold the write lock or call this from a method that does.
|
|
// GetUpwatch returns a copy of the watch's state block (nil when none was ever written).
|
|
func (s *Settings) GetUpwatch() json.RawMessage {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if s.Upwatch == nil {
|
|
return nil
|
|
}
|
|
return append(json.RawMessage(nil), s.Upwatch...)
|
|
}
|
|
|
|
// UpdateUpwatch replaces the watch's state block through fn (read-modify-write under the lock) and saves.
|
|
func (s *Settings) UpdateUpwatch(fn func(old json.RawMessage) (json.RawMessage, error)) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
nv, err := fn(append(json.RawMessage(nil), s.Upwatch...))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.Upwatch = nv
|
|
return s.save()
|
|
}
|
|
|
|
func (s *Settings) save() error {
|
|
data, err := json.MarshalIndent(s, "", " ")
|
|
if err != nil {
|
|
if s.log != nil {
|
|
s.log.Printf("[ERROR] [settings] Failed to save: %v", err)
|
|
}
|
|
return fmt.Errorf("marshaling settings: %w", err)
|
|
}
|
|
|
|
tmpPath := s.path + ".tmp"
|
|
if err := os.MkdirAll(filepath.Dir(s.path), 0755); err != nil {
|
|
if s.log != nil {
|
|
s.log.Printf("[ERROR] [settings] Failed to save: %v", err)
|
|
}
|
|
return fmt.Errorf("creating settings dir: %w", err)
|
|
}
|
|
|
|
if err := os.WriteFile(tmpPath, data, 0644); err != nil {
|
|
os.Remove(tmpPath) // clean up partial file
|
|
if s.log != nil {
|
|
s.log.Printf("[ERROR] [settings] Failed to save: %v", err)
|
|
}
|
|
return fmt.Errorf("writing tmp settings: %w", err)
|
|
}
|
|
|
|
if err := os.Rename(tmpPath, s.path); err != nil {
|
|
os.Remove(tmpPath)
|
|
if s.log != nil {
|
|
s.log.Printf("[ERROR] [settings] Failed to save: %v", err)
|
|
}
|
|
return fmt.Errorf("renaming settings file: %w", err)
|
|
}
|
|
|
|
// last-known-good: written AFTER the primary rename succeeds, so .bak only ever holds settings that
|
|
// parsed + saved cleanly. Best-effort — a failed .bak must NOT fail the save.
|
|
if err := os.WriteFile(s.path+".bak", data, 0644); err != nil && s.log != nil {
|
|
s.log.Printf("[WARN] [settings] could not write .bak: %v", err)
|
|
}
|
|
|
|
if s.debug {
|
|
s.log.Printf("[DEBUG] [settings] saved to %s (%d bytes)", s.path, len(data))
|
|
}
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] Settings saved")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetPasswordHash returns the stored password hash (thread-safe).
|
|
func (s *Settings) GetPasswordHash() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.PasswordHash
|
|
}
|
|
|
|
// SetPasswordHash updates the password hash and saves to disk.
|
|
func (s *Settings) SetPasswordHash(hash string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.PasswordHash = hash
|
|
return s.save()
|
|
}
|
|
|
|
// ── Guest launcher share (v0.165.0) ──────────────────────────────────────────────
|
|
|
|
// ── Backup window (v0.168.0) ─────────────────────────────────────────────────────
|
|
|
|
// GetBackupWindowStart returns the customer-set backup-window start "HH:MM" ("" = fall back to
|
|
// controller.yaml, then the default — resolve via backupwindow.EffectiveWindow, never in isolation).
|
|
func (s *Settings) GetBackupWindowStart() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.BackupWindowStart
|
|
}
|
|
|
|
// SetBackupWindowStart stores (or clears, on "") the backup-window start and saves. The caller
|
|
// validates the HH:MM format first (the scheduler/backupwindow gate) and fans the change out to the
|
|
// three daily legs via UpdateDaily — this only persists the single source-of-truth value.
|
|
func (s *Settings) SetBackupWindowStart(start string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.BackupWindowStart = start
|
|
return s.save()
|
|
}
|
|
|
|
// AppUpdateSettings is settings.json's `app_update` object (v0.271.0).
|
|
type AppUpdateSettings struct {
|
|
// Unattended nil = the default, ON (decision 12). Pinned by TestAppUpdateUnattended_DefaultOn.
|
|
Unattended *bool `json:"unattended,omitempty"`
|
|
}
|
|
|
|
// GetAppUpdateUnattended reports whether this box may update its apps by itself (decision 12).
|
|
// Absent = ON.
|
|
func (s *Settings) GetAppUpdateUnattended() bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if s.AppUpdate == nil || s.AppUpdate.Unattended == nil {
|
|
return true
|
|
}
|
|
return *s.AppUpdate.Unattended
|
|
}
|
|
|
|
// SetAppUpdateUnattended stores the household's choice and saves. It takes effect at the leg's next
|
|
// start (and before its next step, if a leg is running) — the leg reads it each time.
|
|
func (s *Settings) SetAppUpdateUnattended(on bool) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.AppUpdate == nil {
|
|
s.AppUpdate = &AppUpdateSettings{}
|
|
}
|
|
v := on
|
|
s.AppUpdate.Unattended = &v
|
|
return s.save()
|
|
}
|
|
|
|
// SetConfigLanguage records the language controller.yaml says this box should start in.
|
|
//
|
|
// Called once at startup and again after each config pull. It never touches s.Language: a
|
|
// re-delivered config must not be able to change what a household chose.
|
|
func (s *Settings) SetConfigLanguage(lang string) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.configLanguage = lang
|
|
}
|
|
|
|
// GetLanguage returns the household's dashboard language, normalised.
|
|
//
|
|
// THE ORDER, and it is the whole of the bootstrap rule (R-558):
|
|
//
|
|
// 1. What the HOUSEHOLD chose, from settings.json. An explicit choice always wins, and it wins
|
|
// forever — a later config pull cannot unseat it.
|
|
// 2. What the hub said to start in (`customer.language`), for a box nobody has told yet. This is
|
|
// what makes "create the customer as English" produce an English box on first boot.
|
|
// 3. Hungarian.
|
|
//
|
|
// Steps 1 and 2 are DIFFERENT KINDS OF FACT and the difference is the reason this is not one field:
|
|
// an empty s.Language means "never chosen", which is not the same as "chose Hungarian". Collapsing
|
|
// them would make an English household's box silently revert to Hungarian the first time anyone
|
|
// looked at a config default.
|
|
func (s *Settings) GetLanguage() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if i18n.IsSupported(s.Language) {
|
|
return s.Language
|
|
}
|
|
if i18n.IsSupported(s.configLanguage) {
|
|
return s.configLanguage
|
|
}
|
|
return i18n.Default
|
|
}
|
|
|
|
// SetLanguage stores the household's dashboard language and saves. Only a supported language is
|
|
// accepted; anything else is refused and nothing is written.
|
|
func (s *Settings) SetLanguage(lang string) error {
|
|
if !i18n.IsSupported(lang) {
|
|
return fmt.Errorf("unsupported language %q", lang)
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.Language = lang
|
|
return s.save()
|
|
}
|
|
|
|
// GetLauncherShareToken returns the guest-launcher capability token ("" = sharing disabled).
|
|
func (s *Settings) GetLauncherShareToken() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.LauncherShareToken
|
|
}
|
|
|
|
// SetLauncherShareToken stores (or clears, on "") the guest-launcher token and saves. A new value
|
|
// rotates the link; because the guest gate cookie is bound to the token, any outstanding cookie is
|
|
// invalidated automatically. Never log the value.
|
|
func (s *Settings) SetLauncherShareToken(token string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.LauncherShareToken = token
|
|
return s.save()
|
|
}
|
|
|
|
// GetLauncherSharePasswordHash returns the optional per-share bcrypt hash ("" = no share password).
|
|
func (s *Settings) GetLauncherSharePasswordHash() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.LauncherSharePasswordHash
|
|
}
|
|
|
|
// SetLauncherSharePasswordHash stores (or clears, on "") the per-share bcrypt hash and saves. It is
|
|
// ALWAYS distinct from the admin password hash. Changing it invalidates outstanding guest cookies
|
|
// (they bind the hash into the signature).
|
|
func (s *Settings) SetLauncherSharePasswordHash(hash string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.LauncherSharePasswordHash = hash
|
|
return s.save()
|
|
}
|
|
|
|
// ── FileBrowser admin login (R-513) ─────────────────────────────────────────────
|
|
|
|
const (
|
|
FileBrowserAdminGenerated = "generated"
|
|
FileBrowserAdminOperator = "operator"
|
|
)
|
|
|
|
// GetFileBrowserAdmin returns the recorded decision: state ("" = undecided), the ENCRYPTED password
|
|
// (empty unless state is generated) and when it was decided.
|
|
func (s *Settings) GetFileBrowserAdmin() (state, passwordEnc, decidedAt string) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.FileBrowserAdminState, s.FileBrowserAdminPasswordEnc, s.FileBrowserAdminDecidedAt
|
|
}
|
|
|
|
// SetFileBrowserAdmin records the decision and saves. passwordEnc must already be encrypted.
|
|
func (s *Settings) SetFileBrowserAdmin(state, passwordEnc, decidedAt string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.FileBrowserAdminState = state
|
|
s.FileBrowserAdminPasswordEnc = passwordEnc
|
|
s.FileBrowserAdminDecidedAt = decidedAt
|
|
return s.save()
|
|
}
|
|
|
|
// ── Hub-held recovery package (v0.199.0, R-204 item 4) ─────────────────────────
|
|
|
|
// GetHubEscrowIdentityPresent reports whether the hub is holding a sealed identity/recovery package
|
|
// for this box, as last stated by a report ACK. False when no ACK has carried an escrow object yet.
|
|
func (s *Settings) GetHubEscrowIdentityPresent() bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.HubEscrowIdentityPresent
|
|
}
|
|
|
|
// SetHubEscrowIdentityPresent records the ACK's `escrow.identity_blob_present`. It is a plain
|
|
// last-write-wins mirror of the hub's statement — NOT set-only, because the hub losing an escrow row
|
|
// (a customer RESET) must be able to turn the box's declaration back off. Saves only on a change, so
|
|
// the ordinary 15-minute ACK does not rewrite settings.json every cycle.
|
|
func (s *Settings) SetHubEscrowIdentityPresent(present bool) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.HubEscrowIdentityPresent == present {
|
|
return nil
|
|
}
|
|
s.HubEscrowIdentityPresent = present
|
|
return s.save()
|
|
}
|
|
|
|
// GetHubEscrowSuperseded reports whether the hub is keeping an EARLIER sealed package for this box,
|
|
// and when it was set aside (R-222). Both zero until an ACK has said so.
|
|
func (s *Settings) GetHubEscrowSuperseded() (present bool, at string) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.HubEscrowSupersededPresent, s.HubEscrowSupersededAt
|
|
}
|
|
|
|
// SetHubEscrowSuperseded records the ACK's `escrow.superseded_present` / `superseded_at`. Same
|
|
// last-write-wins mirror discipline as SetHubEscrowIdentityPresent — the hub is the authority, and a
|
|
// customer RESET that clears the retained rows must be able to turn the box's message back off.
|
|
// Saves only on a change.
|
|
func (s *Settings) SetHubEscrowSuperseded(present bool, at string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.HubEscrowSupersededPresent == present && s.HubEscrowSupersededAt == at {
|
|
return nil
|
|
}
|
|
s.HubEscrowSupersededPresent, s.HubEscrowSupersededAt = present, at
|
|
return s.save()
|
|
}
|
|
|
|
// ── Recovery screen (v0.200.0, R-193) ──────────────────────────────────────────
|
|
|
|
// GetRecoveryNoticePostponed reports whether the customer chose "most nem" on the recovery page.
|
|
// Suppresses the full-page interruption ONLY — never the backups-area entry point.
|
|
func (s *Settings) GetRecoveryNoticePostponed() bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.RecoveryNoticePostponed
|
|
}
|
|
|
|
// SetRecoveryNoticePostponed records the "most nem" choice.
|
|
func (s *Settings) SetRecoveryNoticePostponed(v bool) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.RecoveryNoticePostponed == v {
|
|
return nil
|
|
}
|
|
s.RecoveryNoticePostponed = v
|
|
return s.save()
|
|
}
|
|
|
|
// ── Customer-claim arc (v0.122.0) ──────────────────────────────────────────────
|
|
|
|
// GetClaimed reports whether this box has completed a claim (set-only).
|
|
func (s *Settings) GetClaimed() bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.Claimed
|
|
}
|
|
|
|
// SetClaimed marks the box claimed (never un-claims) and saves.
|
|
func (s *Settings) SetClaimed() error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.Claimed {
|
|
return nil
|
|
}
|
|
s.Claimed = true
|
|
return s.save()
|
|
}
|
|
|
|
// GetClaimCode returns the cached hub-delivered code state (hash, generation, issuedAt RFC3339).
|
|
func (s *Settings) GetClaimCode() (hash string, generation int, issuedAt string) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.ClaimCodeHash, s.ClaimCodeGeneration, s.ClaimCodeIssuedAt
|
|
}
|
|
|
|
// ReloadClaimCode re-reads the PERSISTED claim-code state from settings.json into the in-process
|
|
// cache, so a code minted by ANOTHER PROCESS is visible without restarting this one.
|
|
//
|
|
// WHY THIS EXISTS (R-204 item 1, v0.198.0). `--print-reset-code` runs as a separate process
|
|
// (`docker exec`): it loads settings itself, mints a code, persists it and exits. The running
|
|
// server's cache never heard, so it kept validating against the previous hash and the code the
|
|
// customer was told to type was refused until the controller restarted. Nothing said so. During the
|
|
// 2026-08-04 recovery drill that cost two failed attempts with an operator present; a customer alone
|
|
// stops there. THE READ IS THE FIX — it is not a cache refresh for tidiness.
|
|
//
|
|
// READ-THROUGH, NOT A WATCHER AND NOT A TTL, deliberately (R-204 §8.1). A watcher/signal/background
|
|
// reloader is a new failure mode for one stale read. A TTL is worse than the bug: it opens a window
|
|
// in which a SUPERSEDED code still works. Pinned by
|
|
// web.TestClaimCode_SupersededByASecondMint_RefusedImmediately, whose stated red-proof is exactly
|
|
// that TTL. The read happens on the claim path only — see web.effectiveClaimCode — and only while the
|
|
// box carries no password, i.e. exactly the gate window.
|
|
//
|
|
// WHAT IT REFRESHES AND WHAT IT DELIBERATELY DOES NOT: hash/generation/issuedAt only.
|
|
// ClaimConsumedGeneration is NOT re-read. This process is its only writer and its in-memory value is
|
|
// monotonic; re-reading it could move it BACKWARDS if a save had failed, which would resurrect an
|
|
// already-consumed code — the exact widening this fix is not allowed to introduce.
|
|
//
|
|
// An ABSENT file is not an error: a box before its first save legitimately has no persisted state and
|
|
// falls back to the controller.yaml bake. A present-but-unreadable or corrupt file IS an error, and
|
|
// the caller fails closed on it.
|
|
func (s *Settings) ReloadClaimCode() error {
|
|
if s.path == "" {
|
|
return nil // no persistence configured (tests) — the cache is all there is
|
|
}
|
|
data, err := os.ReadFile(s.path)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("reading persisted claim state: %w", err)
|
|
}
|
|
var onDisk struct {
|
|
ClaimCodeHash string `json:"claim_code_hash"`
|
|
ClaimCodeGeneration int `json:"claim_code_generation"`
|
|
ClaimCodeIssuedAt string `json:"claim_code_issued_at"`
|
|
}
|
|
if err := json.Unmarshal(data, &onDisk); err != nil {
|
|
return fmt.Errorf("parsing persisted claim state: %w", err)
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.ClaimCodeHash = onDisk.ClaimCodeHash
|
|
s.ClaimCodeGeneration = onDisk.ClaimCodeGeneration
|
|
s.ClaimCodeIssuedAt = onDisk.ClaimCodeIssuedAt
|
|
return nil
|
|
}
|
|
|
|
// SetClaimCode caches a hub-delivered code state (idempotent by generation — the caller guards).
|
|
func (s *Settings) SetClaimCode(hash string, generation int, issuedAt string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.ClaimCodeHash = hash
|
|
s.ClaimCodeGeneration = generation
|
|
s.ClaimCodeIssuedAt = issuedAt
|
|
return s.save()
|
|
}
|
|
|
|
// GetClaimConsumedGeneration returns the last successfully consumed code generation.
|
|
func (s *Settings) GetClaimConsumedGeneration() int {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.ClaimConsumedGeneration
|
|
}
|
|
|
|
// SetClaimConsumedGeneration records a consumed code generation (single-use enforcement).
|
|
func (s *Settings) SetClaimConsumedGeneration(gen int) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if gen > s.ClaimConsumedGeneration {
|
|
s.ClaimConsumedGeneration = gen
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// OffsiteDataRecord is one app's entry in Settings.OffsiteDataAt. RFC3339 UTC both.
|
|
type OffsiteDataRecord struct {
|
|
PushedAt string `json:"pushed_at"`
|
|
DataAt string `json:"data_at"`
|
|
}
|
|
|
|
// GetOffsiteDataAt returns the app's record, false when none was written.
|
|
func (s *Settings) GetOffsiteDataAt(app string) (OffsiteDataRecord, bool) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
r, ok := s.OffsiteDataAt[app]
|
|
return r, ok
|
|
}
|
|
|
|
// SetOffsiteDataAt records the app's pushed data time and persists to disk.
|
|
func (s *Settings) SetOffsiteDataAt(app string, r OffsiteDataRecord) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.OffsiteDataAt == nil {
|
|
s.OffsiteDataAt = make(map[string]OffsiteDataRecord)
|
|
}
|
|
s.OffsiteDataAt[app] = r
|
|
return s.save()
|
|
}
|
|
|
|
// GetDBValidations returns a copy of the cached DB validations.
|
|
func (s *Settings) GetDBValidations() map[string]DBValidationCache {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if s.DBValidations == nil {
|
|
return nil
|
|
}
|
|
result := make(map[string]DBValidationCache, len(s.DBValidations))
|
|
for k, v := range s.DBValidations {
|
|
result[k] = v
|
|
}
|
|
return result
|
|
}
|
|
|
|
// SetDBValidation saves a validation result for a dump file and persists to disk.
|
|
func (s *Settings) SetDBValidation(filename string, cache DBValidationCache) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.DBValidations == nil {
|
|
s.DBValidations = make(map[string]DBValidationCache)
|
|
}
|
|
s.DBValidations[filename] = cache
|
|
return s.save()
|
|
}
|
|
|
|
// GetNotificationPrefs returns a copy of the notification preferences.
|
|
func (s *Settings) GetNotificationPrefs() *NotificationPrefs {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if s.Notifications == nil {
|
|
events := make([]string, len(DefaultEnabledEvents))
|
|
copy(events, DefaultEnabledEvents)
|
|
return &NotificationPrefs{
|
|
EnabledEvents: events,
|
|
CooldownHours: 6,
|
|
}
|
|
}
|
|
prefs := *s.Notifications
|
|
if prefs.CooldownHours == 0 {
|
|
prefs.CooldownHours = 6
|
|
}
|
|
if prefs.EnabledEvents == nil {
|
|
// A SAVED list with no events is a household that unticked every mail (the only writer is the settings page;
|
|
// before R-1199 reopened omitempty dropped its []). It reads as empty — never as the defaults, which the hub
|
|
// does not mail by. Pinned by TestR1199Reopened_AnEmptySavedListStaysEmpty.
|
|
prefs.EnabledEvents = []string{}
|
|
}
|
|
// Return a copy of the slice verbatim. The offbox_enlarge_blocked seed is a ONE-TIME persisted
|
|
// migration (seedOffboxEnlargeNotice at Load), NOT a getter append — so a customer's later opt-out
|
|
// sticks instead of being re-enabled on every read.
|
|
events := make([]string, len(prefs.EnabledEvents))
|
|
copy(events, prefs.EnabledEvents)
|
|
prefs.EnabledEvents = events
|
|
return &prefs
|
|
}
|
|
|
|
// appendIfAbsent appends want to list only if it is not already present (idempotent).
|
|
func appendIfAbsent(list []string, want string) []string {
|
|
for _, e := range list {
|
|
if e == want {
|
|
return list
|
|
}
|
|
}
|
|
return append(list, want)
|
|
}
|
|
|
|
// SetNotificationPrefs updates notification preferences and saves to disk.
|
|
// H17: Deep-copies prefs so caller mutations after the call don't affect stored state.
|
|
func (s *Settings) SetNotificationPrefs(prefs *NotificationPrefs) error {
|
|
if prefs == nil {
|
|
return fmt.Errorf("notification preferences cannot be nil")
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
cp := *prefs
|
|
if len(prefs.EnabledEvents) > 0 {
|
|
cp.EnabledEvents = make([]string, len(prefs.EnabledEvents))
|
|
for i, e := range prefs.EnabledEvents {
|
|
cp.EnabledEvents[i] = e
|
|
}
|
|
}
|
|
s.Notifications = &cp
|
|
return s.save()
|
|
}
|
|
|
|
// GetOffboxTarget returns a copy of the off-box target config (nil if unconfigured).
|
|
func (s *Settings) GetOffboxTarget() *OffboxTarget {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if s.Offbox == nil {
|
|
return nil
|
|
}
|
|
cp := *s.Offbox
|
|
return &cp
|
|
}
|
|
|
|
// SetOffboxTarget saves (or clears, on nil) the off-box target config.
|
|
// TransportRclonePinned marks the hub-provisioned, append-only off-site tier (decision 69).
|
|
const TransportRclonePinned = "rclone-pinned"
|
|
|
|
// Pinned reports whether the target is the append-only hub tier.
|
|
func (t *OffboxTarget) Pinned() bool { return t != nil && t.Transport == TransportRclonePinned }
|
|
|
|
func (s *Settings) SetOffboxTarget(t *OffboxTarget) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.Offbox = t
|
|
return s.save()
|
|
}
|
|
|
|
// UpdateOffboxStatus mutates the off-box target's runtime status in-place (no-op if unconfigured).
|
|
func (s *Settings) UpdateOffboxStatus(fn func(*OffboxTarget)) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.Offbox == nil {
|
|
return nil
|
|
}
|
|
fn(s.Offbox)
|
|
return s.save()
|
|
}
|
|
|
|
// IsAppOffbox reports whether a stack is toggled for off-box backup.
|
|
func (s *Settings) IsAppOffbox(stackName string) bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if s.AppBackup == nil {
|
|
return false
|
|
}
|
|
return s.AppBackup[stackName].Offbox
|
|
}
|
|
|
|
// SetAppOffbox toggles a stack's off-box backup inclusion.
|
|
func (s *Settings) SetAppOffbox(stackName string, on bool) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.AppBackup == nil {
|
|
s.AppBackup = make(map[string]AppBackupPrefs)
|
|
}
|
|
existing := s.AppBackup[stackName]
|
|
existing.Offbox = on
|
|
s.AppBackup[stackName] = existing
|
|
return s.save()
|
|
}
|
|
|
|
// DeleteAppBackupPrefs (R-474, v0.240.0) forgets every per-app backup preference of an app whose
|
|
// backups the customer asked to delete on removal — the off-site toggle and the cross-drive record
|
|
// together. Before it, "delete backups" left `app_backup[<app>]` behind, and a reinstall inherited it.
|
|
func (s *Settings) DeleteAppBackupPrefs(stackName string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if _, ok := s.AppBackup[stackName]; !ok {
|
|
return nil
|
|
}
|
|
delete(s.AppBackup, stackName)
|
|
return s.save()
|
|
}
|
|
|
|
// GetOffboxApps returns the stack names toggled for off-box backup.
|
|
func (s *Settings) GetOffboxApps() []string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
var out []string
|
|
for name, p := range s.AppBackup {
|
|
if p.Offbox {
|
|
out = append(out, name)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// GetCrossDriveConfig returns the cross-drive backup config for a stack (nil if not set).
|
|
func (s *Settings) GetCrossDriveConfig(stackName string) *CrossDriveBackup {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if s.AppBackup == nil {
|
|
return nil
|
|
}
|
|
prefs, ok := s.AppBackup[stackName]
|
|
if !ok || prefs.CrossDrive == nil {
|
|
return nil
|
|
}
|
|
cp := *prefs.CrossDrive
|
|
return &cp
|
|
}
|
|
|
|
// SetCrossDriveConfig saves (or clears) the cross-drive backup config for a stack.
|
|
func (s *Settings) SetCrossDriveConfig(stackName string, cfg *CrossDriveBackup) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.AppBackup == nil {
|
|
s.AppBackup = make(map[string]AppBackupPrefs)
|
|
}
|
|
existing := s.AppBackup[stackName]
|
|
existing.CrossDrive = cfg
|
|
s.AppBackup[stackName] = existing
|
|
return s.save()
|
|
}
|
|
|
|
// UpdateCrossDriveStatus updates runtime status fields for a cross-drive backup in-place.
|
|
// fn receives a pointer to the CrossDriveBackup and may mutate it.
|
|
// If no cross-drive config exists for the stack, does nothing and returns nil.
|
|
func (s *Settings) UpdateCrossDriveStatus(stackName string, fn func(*CrossDriveBackup)) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.AppBackup == nil {
|
|
s.AppBackup = make(map[string]AppBackupPrefs)
|
|
}
|
|
existing := s.AppBackup[stackName]
|
|
if existing.CrossDrive == nil {
|
|
return nil // don't create config from thin air — just skip status update
|
|
}
|
|
fn(existing.CrossDrive)
|
|
s.AppBackup[stackName] = existing
|
|
return s.save()
|
|
}
|
|
|
|
// SetTier2Preference records the customer's Tier-2 choice (from the per-app config panel) WITHOUT
|
|
// disturbing the runner's status fields: it merges into the existing config if one is present, else
|
|
// seeds a minimal config carrying just the preference. The Tier-2 runner reads UserDisabled (skip)
|
|
// and PreferredTarget (pin a destination) and preserves both on every status write.
|
|
func (s *Settings) SetTier2Preference(stackName string, disabled bool, preferredTarget string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.AppBackup == nil {
|
|
s.AppBackup = make(map[string]AppBackupPrefs)
|
|
}
|
|
existing := s.AppBackup[stackName]
|
|
if existing.CrossDrive == nil {
|
|
existing.CrossDrive = &CrossDriveBackup{Method: "rsync", Schedule: "daily"}
|
|
}
|
|
existing.CrossDrive.UserDisabled = disabled
|
|
existing.CrossDrive.PreferredTarget = preferredTarget
|
|
s.AppBackup[stackName] = existing
|
|
return s.save()
|
|
}
|
|
|
|
// GetAllCrossDriveConfigs returns all apps with a cross-drive config (enabled or not).
|
|
func (s *Settings) GetAllCrossDriveConfigs() map[string]*CrossDriveBackup {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
result := make(map[string]*CrossDriveBackup)
|
|
for name, prefs := range s.AppBackup {
|
|
if prefs.CrossDrive != nil {
|
|
cp := *prefs.CrossDrive
|
|
result[name] = &cp
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// NOTE: GetCrossDriveResticPassword, SetCrossDriveResticPassword, and
|
|
// GetOrCreateCrossDrivePassword were removed in the Tier 2 restic deprecation.
|
|
// The CrossDriveResticPassword field is kept in the struct for backward-compat
|
|
// JSON loading but is no longer used.
|
|
|
|
// --- Storage Paths ---
|
|
|
|
// GetStoragePaths returns a copy of all registered storage paths.
|
|
func (s *Settings) GetStoragePaths() []StoragePath {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if len(s.StoragePaths) == 0 {
|
|
return nil
|
|
}
|
|
result := make([]StoragePath, len(s.StoragePaths))
|
|
copy(result, s.StoragePaths)
|
|
return result
|
|
}
|
|
|
|
// GetDefaultStoragePath returns the default storage path string, or "".
|
|
func (s *Settings) GetDefaultStoragePath() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
for _, sp := range s.StoragePaths {
|
|
if sp.IsDefault {
|
|
return sp.Path
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// GetStorageLabel returns the label for a storage path, or the base name if not found.
|
|
func (s *Settings) GetStorageLabel(path string) string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
for _, sp := range s.StoragePaths {
|
|
if sp.Path == path && sp.Label != "" {
|
|
return sp.Label
|
|
}
|
|
}
|
|
return filepath.Base(path)
|
|
}
|
|
|
|
// GetSchedulableStoragePaths returns paths available for new deployments.
|
|
func (s *Settings) GetSchedulableStoragePaths() []StoragePath {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
var result []StoragePath
|
|
for _, sp := range s.StoragePaths {
|
|
if sp.Schedulable && !sp.Decommissioned {
|
|
result = append(result, sp)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// AddStoragePath registers a new storage path. Validation is done by caller.
|
|
func (s *Settings) AddStoragePath(sp StoragePath) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.debug {
|
|
s.log.Printf("[DEBUG] [settings] AddStoragePath path=%q label=%q default=%v", sp.Path, sp.Label, sp.IsDefault)
|
|
}
|
|
for _, existing := range s.StoragePaths {
|
|
if existing.Path == sp.Path {
|
|
return fmt.Errorf("storage path %q already registered", sp.Path)
|
|
}
|
|
}
|
|
if sp.IsDefault {
|
|
for i := range s.StoragePaths {
|
|
s.StoragePaths[i].IsDefault = false
|
|
}
|
|
}
|
|
s.StoragePaths = append(s.StoragePaths, sp)
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] Added storage path: %s", sp.Path)
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// RemoveStoragePath removes a path by its path string.
|
|
func (s *Settings) RemoveStoragePath(path string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.debug {
|
|
s.log.Printf("[DEBUG] [settings] RemoveStoragePath path=%q", path)
|
|
}
|
|
var kept []StoragePath
|
|
for _, sp := range s.StoragePaths {
|
|
if sp.Path != path {
|
|
kept = append(kept, sp)
|
|
}
|
|
}
|
|
s.StoragePaths = kept
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] Removed storage path: %s", path)
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// RepointStoragePath changes a registered path's Path string in place (intermediary-mount migration:
|
|
// /mnt/<name> → /mnt/felhom-drives/<name>), preserving all other fields (label, default, schedulable,
|
|
// disconnect/decommission state). No-op (nil) if oldPath isn't registered or already equals newPath.
|
|
// Errors if newPath collides with a different existing entry.
|
|
func (s *Settings) RepointStoragePath(oldPath, newPath string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if oldPath == newPath {
|
|
return nil
|
|
}
|
|
idx := -1
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == newPath {
|
|
return fmt.Errorf("repoint target %q already registered", newPath)
|
|
}
|
|
if s.StoragePaths[i].Path == oldPath {
|
|
idx = i
|
|
}
|
|
}
|
|
if idx < 0 {
|
|
return nil // nothing to repoint
|
|
}
|
|
s.StoragePaths[idx].Path = newPath
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] Repointed storage path: %s → %s", oldPath, newPath)
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// SetDefaultStoragePath changes which path is the default.
|
|
func (s *Settings) SetDefaultStoragePath(path string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
found := false
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
s.StoragePaths[i].IsDefault = true
|
|
found = true
|
|
} else {
|
|
s.StoragePaths[i].IsDefault = false
|
|
}
|
|
}
|
|
if !found {
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// SetSchedulable enables/disables a path for new deployments.
|
|
func (s *Settings) SetSchedulable(path string, schedulable bool) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
s.StoragePaths[i].Schedulable = schedulable
|
|
return s.save()
|
|
}
|
|
}
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
|
|
// SetBackupTarget assigns the whole-guest backup-target role to exactly one storage path, clearing it
|
|
// from every other. This is the ONLY writer that GRANTS StoragePath.BackupTarget (ClearBackupTarget also writes
|
|
// the field, only ever false) — registration must never set it (E-2 §3: a drive never acquires a role by
|
|
// appearing). Pinned by TestR263_OnlySetBackupTargetGrantsTheRole (a scan of every non-test file).
|
|
//
|
|
// Refusals, both structural rather than advisory:
|
|
// - a NETWORK share can never be the target. vzdump writes a multi-GB archive through the host, and
|
|
// the whole point of the role is surviving a local disk failure — a share that is itself remote,
|
|
// credential-bound and mounted at its own root (R-108) is a different risk model entirely.
|
|
// - a path that is not registered cannot hold a role.
|
|
//
|
|
// It deliberately does NOT refuse a DISCONNECTED path: reassigning to a drive that is currently absent
|
|
// is a legitimate recovery order ("this is the drive, go find it"), and the absent-target alarm is what
|
|
// covers the gap. Refusing here would instead force a silent retarget elsewhere.
|
|
func (s *Settings) SetBackupTarget(path string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
idx := -1
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
idx = i
|
|
break
|
|
}
|
|
}
|
|
if idx < 0 {
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
if s.StoragePaths[idx].IsNetwork() {
|
|
return util.MsgError("err.settings.a_halozati_tarhely_nem_lehet_a", path)
|
|
}
|
|
for i := range s.StoragePaths {
|
|
s.StoragePaths[i].BackupTarget = i == idx
|
|
}
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] backup target assigned: %s", path)
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// ClearBackupTarget removes the role from every path, leaving the box with no assigned target (the
|
|
// degraded state). Separate from SetBackupTarget on purpose: "no target" is a real, nameable state
|
|
// that must be reachable deliberately, not an accident of passing an empty string to a setter.
|
|
func (s *Settings) ClearBackupTarget() error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for i := range s.StoragePaths {
|
|
s.StoragePaths[i].BackupTarget = false
|
|
}
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] backup target cleared — the box is now in the degraded (system-drive) state")
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// BackupTargetPath returns the assigned target's path, or "" when none is assigned (degraded).
|
|
func (s *Settings) BackupTargetPath() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
for _, sp := range s.StoragePaths {
|
|
if sp.BackupTarget {
|
|
return sp.Path
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// BackupTargetAssigned reports whether ANY path carries the role. The negation is the degraded state
|
|
// the customer must be told about (E-2 Part 4).
|
|
func (s *Settings) BackupTargetAssigned() bool { return s.BackupTargetPath() != "" }
|
|
|
|
// SetStorageLabel updates the label for a storage path.
|
|
func (s *Settings) SetStorageLabel(path, label string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
s.StoragePaths[i].Label = label
|
|
return s.save()
|
|
}
|
|
}
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
|
|
// AutoDiscoverStoragePaths scans for HDD_PATH values and registers any that are not
|
|
// already in the registry. It is ADDITIVE: pre-existing entries are never removed,
|
|
// modified, or reactivated.
|
|
// - discoveredPaths are pre-scanned HDD_PATH values from deployed apps' app.yaml.
|
|
//
|
|
// Invariants:
|
|
// - A path already present in the registry IN ANY STATE (including a Decommissioned
|
|
// soft-marked entry) is SKIPPED — never re-added and never re-activated.
|
|
// - A manually-added path is never removed or modified.
|
|
// - IsDefault is never flipped on an existing entry. A newly-discovered path becomes
|
|
// default ONLY if the registry currently has no default at all (and then only the
|
|
// first such new path).
|
|
func (s *Settings) AutoDiscoverStoragePaths(discoveredPaths []string, logger *log.Logger) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
if s.debug {
|
|
s.log.Printf("[DEBUG] [settings] AutoDiscoverStoragePaths discovered=%v existing=%d", discoveredPaths, len(s.StoragePaths))
|
|
}
|
|
|
|
// Index existing paths (in ANY state) and whether a default already exists.
|
|
existing := make(map[string]bool, len(s.StoragePaths))
|
|
hasDefault := false
|
|
for i := range s.StoragePaths {
|
|
existing[filepath.Clean(s.StoragePaths[i].Path)] = true
|
|
if s.StoragePaths[i].IsDefault {
|
|
hasDefault = true
|
|
}
|
|
}
|
|
|
|
// Build the de-duplicated, cleaned candidate list.
|
|
seen := make(map[string]bool)
|
|
var ordered []string
|
|
for _, p := range discoveredPaths {
|
|
cleaned := filepath.Clean(p)
|
|
if cleaned != "" && cleaned != "." && !seen[cleaned] {
|
|
seen[cleaned] = true
|
|
ordered = append(ordered, cleaned)
|
|
}
|
|
}
|
|
|
|
added := 0
|
|
for _, path := range ordered {
|
|
if existing[path] {
|
|
continue // already registered in some state — never re-add or reactivate
|
|
}
|
|
sp := StoragePath{
|
|
Path: path,
|
|
Label: InferStorageLabel(path),
|
|
IsDefault: !hasDefault, // first newly-added path defaults only if none exists yet
|
|
Schedulable: true,
|
|
AddedAt: time.Now().UTC().Format(time.RFC3339),
|
|
}
|
|
if sp.IsDefault {
|
|
hasDefault = true // don't promote a second new path
|
|
}
|
|
s.StoragePaths = append(s.StoragePaths, sp)
|
|
existing[path] = true
|
|
added++
|
|
}
|
|
|
|
if added == 0 {
|
|
return // nothing new to register
|
|
}
|
|
|
|
if err := s.save(); err != nil {
|
|
logger.Printf("[ERROR] [settings] Failed to save auto-discovered storage paths: %v", err)
|
|
return
|
|
}
|
|
logger.Printf("[INFO] [settings] Auto-discovered %d new storage path(s)", added)
|
|
for _, sp := range s.StoragePaths {
|
|
logger.Printf("[INFO] [settings] %s (%s) default=%v decommissioned=%v", sp.Path, sp.Label, sp.IsDefault, sp.Decommissioned)
|
|
}
|
|
}
|
|
|
|
// InferStorageLabel generates a human-readable label for a storage path.
|
|
func InferStorageLabel(path string) string {
|
|
base := filepath.Base(path)
|
|
// The internal system volume's data path ends in the felhom-data namespace dir
|
|
// (e.g. /mnt/sys_drive/felhom-data) — Model-A user drives register their MOUNT ROOT
|
|
// (e.g. /mnt/felhom-usb), never .../felhom-data, so this can't mislabel a user drive.
|
|
if base == appbackup.FelhomDataDir {
|
|
return "Belső SSD (rendszer)"
|
|
}
|
|
if strings.HasPrefix(base, "hdd") || strings.HasPrefix(base, "ssd") || strings.HasPrefix(base, "usb") {
|
|
return fmt.Sprintf("Külső tárhely (%s)", base)
|
|
}
|
|
return fmt.Sprintf("Tárhely (%s)", base)
|
|
}
|
|
|
|
// RestoreHold is one app held stopped after a failed restore whose rollback also failed. It carries
|
|
// the reason so every refusal can NAME it — a refusal without a reason and a route is how a customer
|
|
// is left with nothing to do.
|
|
type RestoreHold struct {
|
|
Stack string `json:"stack"`
|
|
At string `json:"at"` // RFC3339 UTC
|
|
ReplayError string `json:"replay_error,omitempty"` // what the restore hit
|
|
RollbackErr string `json:"rollback_error,omitempty"` // what the rollback then hit
|
|
SafetyDump string `json:"safety_dump,omitempty"` // basename of the undo copy that could not be applied
|
|
|
|
// Reason (update arc slice 4, v0.237.0) says WHICH operation put the hold in place. Empty means
|
|
// HoldReasonRestoreFailed — every hold written before this field existed was a restore hold, so
|
|
// the zero value keeps their meaning and no migration is needed.
|
|
//
|
|
// ONE STORAGE, ONE GATE, TWO REASONS — deliberately not a second map. Every start path already
|
|
// consults GetRestoreHold (the customer's button, the boot sweep, the app-stop guard's Recover),
|
|
// and "a hold that only one path honours is not a hold". A second map would need every one of
|
|
// those paths found and changed again, and the one that got missed would be the next R-439.
|
|
Reason string `json:"reason,omitempty"`
|
|
// CopyDate is the RFC3339 time of the proven backup the customer is told they can restore from.
|
|
// Only set for HoldReasonUpdateFailed.
|
|
CopyDate string `json:"copy_date,omitempty"`
|
|
// CopyTier (R-475, v0.239.0) is WHICH backup tier CopyDate belongs to: 1 the app's own recovery
|
|
// unit, 2 the second drive, 3 off-site. 0 means a hold written before the field existed; it keeps
|
|
// its original sentence (backup.UpdateHoldLegacyFmt). Only set for HoldReasonUpdateFailed.
|
|
CopyTier int `json:"copy_tier,omitempty"`
|
|
// CopyHolds (R-479, v0.241.0) is the customer phrase for WHAT the named copy holds — e.g. „a
|
|
// beállításokat, az adatbázist és a fájlokat tartalmazza" — recorded at hold time, because an app's
|
|
// data layout (bind-mounted files vs. named volumes) decides it and may not be readable later.
|
|
CopyHolds string `json:"copy_holds,omitempty"`
|
|
// UndoState (v0.263.0) is what a FAILED automatic undo left the data as — "untouched", "half" or
|
|
// "not_started" (stacks.UndoState*). Empty: no undo was attempted (every hold written before the
|
|
// field existed). Only set for HoldReasonUpdateFailed.
|
|
UndoState string `json:"undo_state,omitempty"`
|
|
// NoWholeCopy (v0.268.0, R-659; operator ruling 2026-09-24, option A) — at hold time NO copy on
|
|
// this box could bring the app back whole (backup.WholeOnTier), so the sentence names none and
|
|
// says support is informed. CopiesSeen lists what WAS there ("tier N at RFC3339"), for support.
|
|
NoWholeCopy bool `json:"no_whole_copy,omitempty"`
|
|
CopiesSeen []string `json:"copies_seen,omitempty"`
|
|
// UnhealthyKind / Trip (v0.269.0, decision 28): "crash_loop" or "oom_storm", and whether this is the
|
|
// first stop or a repeat within 24 h (Trip >= 2 → the sentence says support is informed).
|
|
UnhealthyKind string `json:"unhealthy_kind,omitempty"`
|
|
Trip int `json:"trip,omitempty"`
|
|
|
|
// R-1340 (2026-10-29): what put a restore hold in place, so the operator's „HELD STOPPED" mail tells the real
|
|
// story instead of the option-C database story for every cause. All empty on a hold written before them: the mail
|
|
// then names only what the record carries (cmd/controller heldStoppedOperatorText).
|
|
//
|
|
// RestoreKind is which restore: RestoreKindOffsite or RestoreKindLocal.
|
|
RestoreKind string `json:"restore_kind,omitempty"`
|
|
// MixedCause (restore_mixed only) is the branch that held the app: MixedCause*.
|
|
MixedCause string `json:"mixed_cause,omitempty"`
|
|
// FailedStep is the put-back step that failed, with its error (MixedCausePutBack).
|
|
FailedStep string `json:"failed_step,omitempty"`
|
|
// DBReplay: the restore's own failure was its database replay. False = the app's database was never touched
|
|
// by the failure, so the mail never says „database".
|
|
DBReplay bool `json:"db_replay,omitempty"`
|
|
}
|
|
|
|
// Restore kinds and mixed-hold causes (R-1340). See RestoreHold.RestoreKind / MixedCause.
|
|
const (
|
|
RestoreKindOffsite = "offsite"
|
|
RestoreKindLocal = "local"
|
|
|
|
// MixedCauseDefinitionWrite: the backup's definition could not be written (no data moved yet) and writing the
|
|
// live definition back failed too (R-1256 H4).
|
|
MixedCauseDefinitionWrite = "definition_write"
|
|
// MixedCausePutBack: the restore failed and putting the live data back failed at FailedStep (D20/R-1256 H5).
|
|
MixedCausePutBack = "put_back"
|
|
// MixedCauseInterruptedPutBack: a restore cut by a stop could not be put back at the next start (R-1251 H2).
|
|
MixedCauseInterruptedPutBack = "interrupted_put_back"
|
|
)
|
|
|
|
// Hold reasons. See RestoreHold.Reason.
|
|
const (
|
|
HoldReasonRestoreFailed = "" // R-379/R-380: a restore AND its rollback failed
|
|
HoldReasonUpdateFailed = "update_failed" // slice 4: the new version did not come up healthy
|
|
// HoldReasonUnhealthyStop (v0.269.0, `09` §3 decision 28): the box stopped an app in a crash loop or
|
|
// an out-of-memory storm. Lifted by the household's Start (one more try); nothing else starts it.
|
|
HoldReasonUnhealthyStop = "unhealthy_stop"
|
|
// HoldReasonRestoreMixed (R-893, `09` §3 decision 192): an off-site restore of one app failed its database
|
|
// replay AFTER the snapshot's definition was written or a named volume was replaced. The database was
|
|
// rolled back, the live definition written back, and the app is held: its files and volumes are the
|
|
// snapshot's, its database the pre-restore one. Cleared like a restore hold — by the operator.
|
|
HoldReasonRestoreMixed = "restore_mixed"
|
|
// HoldReasonPutBackPending (R-1251): a restore was cut after its copy of the live data was taken, and the copy
|
|
// is on a drive that was not bound when the box came back. Nothing may start the app until the copy is poured
|
|
// back (backup.AppStopGuard.ResumePutBack); SafetyDump holds the copy's folder. Cleared by the put-back.
|
|
HoldReasonPutBackPending = "putback_pending"
|
|
)
|
|
|
|
// WireReason is the hold's reason as the hub reads it (D53): the empty legacy value is named restore_failed.
|
|
func (h RestoreHold) WireReason() string {
|
|
if h.Reason == HoldReasonRestoreFailed {
|
|
return "restore_failed"
|
|
}
|
|
return h.Reason
|
|
}
|
|
|
|
// Why says which operation put a hold in place and what lifts it — one sentence per reason (R-1286). English,
|
|
// operator-facing: the controller's own -list-restore-holds output and the hub's „Held apps" list (D53) both use it.
|
|
func (h RestoreHold) Why() string {
|
|
switch h.Reason {
|
|
case HoldReasonUpdateFailed:
|
|
return "held after a failed update (" + h.At + ") — restore it from its backup to start it"
|
|
case HoldReasonUnhealthyStop:
|
|
kind := h.UnhealthyKind
|
|
if kind == "" {
|
|
kind = "unhealthy"
|
|
}
|
|
return "stopped by the box for a " + strings.ReplaceAll(kind, "_", " ") + " (" + h.At + ") — the household's Start gives it one more try"
|
|
case HoldReasonRestoreMixed:
|
|
return h.mixedWhy() + " (" + h.At + ") — clear the hold to start it"
|
|
case HoldReasonPutBackPending:
|
|
return "held until the pre-restore copy is poured back (" + h.At + ") — the put-back starts it"
|
|
default:
|
|
return "held after a failed restore whose rollback also failed (" + h.At + ") — clear the hold to start it"
|
|
}
|
|
}
|
|
|
|
// mixedWhy (R-1340) names a restore_mixed hold from what its record carries — never „database" or „off-site" unless the
|
|
// record says so. A record written before these fields („legacy") gets the neutral sentence. Pinned by
|
|
// TestR1340_WhyNamesTheMixedCause.
|
|
func (h RestoreHold) mixedWhy() string {
|
|
kind := "a restore"
|
|
switch h.RestoreKind {
|
|
case RestoreKindOffsite:
|
|
kind = "an off-site restore"
|
|
case RestoreKindLocal:
|
|
kind = "a local restore"
|
|
}
|
|
switch h.MixedCause {
|
|
case MixedCauseDefinitionWrite:
|
|
return "held after " + kind + " could not write its definition and writing the live definition back failed too"
|
|
case MixedCauseInterruptedPutBack:
|
|
return "held after a restore was interrupted and its live data could not be put back at the next start"
|
|
case MixedCausePutBack:
|
|
what := "failed"
|
|
if h.DBReplay {
|
|
what = "failed its database replay"
|
|
}
|
|
s := "held after " + kind + " " + what + " and putting the live data back failed"
|
|
if h.FailedStep != "" {
|
|
s += " (" + h.FailedStep + ")"
|
|
}
|
|
return s
|
|
}
|
|
return "held after a restore stopped half-way"
|
|
}
|
|
|
|
// SetRestoreHold records a hold. Modelled on SetDisconnected: a condition, plus what it is holding.
|
|
func (s *Settings) SetRestoreHold(h RestoreHold) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.RestoreHolds == nil {
|
|
s.RestoreHolds = map[string]RestoreHold{}
|
|
}
|
|
s.RestoreHolds[h.Stack] = h
|
|
if s.log != nil {
|
|
s.log.Printf("[WARN] [settings] restore hold SET for %s — the app stays stopped until it is cleared", h.Stack)
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// GetRestoreHold returns the hold for a stack, if one is in force.
|
|
func (s *Settings) GetRestoreHold(stack string) (RestoreHold, bool) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
h, ok := s.RestoreHolds[stack]
|
|
return h, ok
|
|
}
|
|
|
|
// ListRestoreHolds returns every hold in force.
|
|
func (s *Settings) ListRestoreHolds() []RestoreHold {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
out := make([]RestoreHold, 0, len(s.RestoreHolds))
|
|
for _, h := range s.RestoreHolds {
|
|
out = append(out, h)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// GetReportedHolds returns a copy of the holds last reported to the hub (D53): stack → „reason|at".
|
|
func (s *Settings) GetReportedHolds() map[string]string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
out := make(map[string]string, len(s.ReportedHolds))
|
|
for k, v := range s.ReportedHolds {
|
|
out[k] = v
|
|
}
|
|
return out
|
|
}
|
|
|
|
// SetReportedHolds replaces the record of the holds reported to the hub (D53). An empty map removes the field.
|
|
func (s *Settings) SetReportedHolds(m map[string]string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if len(m) == 0 {
|
|
s.ReportedHolds = nil
|
|
} else {
|
|
s.ReportedHolds = make(map[string]string, len(m))
|
|
for k, v := range m {
|
|
s.ReportedHolds[k] = v
|
|
}
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// ClearRestoreHold removes a hold. Returns false when there was none, so a caller can tell "cleared"
|
|
// from "there was nothing to clear" rather than reporting success either way.
|
|
func (s *Settings) ClearRestoreHold(stack string) (bool, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if _, ok := s.RestoreHolds[stack]; !ok {
|
|
return false, nil
|
|
}
|
|
delete(s.RestoreHolds, stack)
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] restore hold CLEARED for %s", stack)
|
|
}
|
|
return true, s.save()
|
|
}
|
|
|
|
// ClearUpdateHold (R-491, v0.242.0) removes an app's hold when it belongs to the app's INSTALL: an update
|
|
// hold, and since v0.278.0 (R-704) the box's crash-loop/OOM stop (HoldReasonUnhealthyStop) — both name an
|
|
// install that a removal ends, and the name is all a later install shares with it. An R-379 restore hold
|
|
// stays: that one means a database was left in an unknown state and is cleared by the operator
|
|
// (`-clear-restore-hold`), never by a removal or an install. Returns whether a hold was cleared.
|
|
// Pinned by TestR704_ClearUpdateHoldClearsTheInstallsHoldsOnly.
|
|
// R-1251: a put-back still waiting for its drive (HoldReasonPutBackPending) belongs to the install too — its copy is
|
|
// of the removed install's volumes, and a later install of the same name must not wait for it.
|
|
func (s *Settings) ClearUpdateHold(stack string) (bool, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
h, ok := s.RestoreHolds[stack]
|
|
if !ok || (h.Reason != HoldReasonUpdateFailed && h.Reason != HoldReasonUnhealthyStop && h.Reason != HoldReasonPutBackPending) {
|
|
return false, nil
|
|
}
|
|
delete(s.RestoreHolds, stack)
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] %s hold CLEARED for %s (set %s; its install is gone)", h.Reason, stack, h.At)
|
|
}
|
|
return true, s.save()
|
|
}
|
|
|
|
// SetDisconnected marks a storage path as disconnected (or connected) and records which stacks were stopped.
|
|
func (s *Settings) SetDisconnected(path string, disconnected bool, stoppedStacks []string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.debug {
|
|
s.log.Printf("[DEBUG] [settings] SetDisconnected path=%q disconnected=%v stopped_stacks=%d", path, disconnected, len(stoppedStacks))
|
|
}
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] Storage path %s disconnected=%v", path, disconnected)
|
|
}
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
s.StoragePaths[i].Disconnected = disconnected
|
|
if disconnected {
|
|
s.StoragePaths[i].DisconnectedAt = time.Now().UTC().Format(time.RFC3339)
|
|
s.StoragePaths[i].StoppedStacks = stoppedStacks
|
|
} else {
|
|
s.StoragePaths[i].DisconnectedAt = ""
|
|
// Preserve StoppedStacks on reconnect so the UI can offer restart
|
|
if stoppedStacks != nil {
|
|
s.StoragePaths[i].StoppedStacks = stoppedStacks
|
|
}
|
|
}
|
|
return s.save()
|
|
}
|
|
}
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
|
|
// ClearDisconnected marks a path as connected and clears all disconnect-related fields.
|
|
func (s *Settings) ClearDisconnected(path string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
s.StoragePaths[i].Disconnected = false
|
|
s.StoragePaths[i].DisconnectedAt = ""
|
|
s.StoragePaths[i].StoppedStacks = nil
|
|
return s.save()
|
|
}
|
|
}
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
|
|
// IsDisconnected returns whether a storage path is marked as disconnected.
|
|
func (s *Settings) IsDisconnected(path string) bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
for _, sp := range s.StoragePaths {
|
|
if sp.Path == path {
|
|
return sp.Disconnected
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// GetDisconnectedPaths returns a copy of all storage paths that are marked disconnected.
|
|
func (s *Settings) GetDisconnectedPaths() []StoragePath {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
var result []StoragePath
|
|
for _, sp := range s.StoragePaths {
|
|
if sp.Disconnected {
|
|
result = append(result, sp)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// GetConnectedPaths returns a copy of all storage paths that are NOT disconnected and NOT decommissioned.
|
|
func (s *Settings) GetConnectedPaths() []StoragePath {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
var result []StoragePath
|
|
for _, sp := range s.StoragePaths {
|
|
if !sp.Disconnected && !sp.Decommissioned {
|
|
result = append(result, sp)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// IsStoragePathKnown returns whether a path belongs to any registered storage path
|
|
// (connected, disconnected, or decommissioned). A path removed entirely from
|
|
// storage_paths is NOT known.
|
|
func (s *Settings) IsStoragePathKnown(path string) bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
for _, sp := range s.StoragePaths {
|
|
if path == sp.Path || strings.HasPrefix(path, sp.Path+"/") {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// IsNetworkStoragePath reports whether `path` belongs to a registered NAS network-storage path
|
|
// (Kind=="network"). The drive lifecycle (eject/decommission/migrate/wipe) must refuse such a path —
|
|
// a NAS has no device lifecycle. Matches the exact path or a child under it.
|
|
func (s *Settings) IsNetworkStoragePath(path string) bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
for _, sp := range s.StoragePaths {
|
|
if path == sp.Path || strings.HasPrefix(path, sp.Path+"/") {
|
|
return sp.IsNetwork()
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// RefuseAsAppNamespace reports whether `path` must be REFUSED as an app's data namespace (its
|
|
// HDD_PATH), and why. It is the single predicate every placement surface consults — R-108.
|
|
//
|
|
// WHY AN APP NAMESPACE MAY NOT LIVE ON A NAS (operator ruling, 2026-07-30). An app's namespace root is
|
|
// also where its backups go: `namespaceRoot(drivePath)` returns a non-system drive path AS-IS, so the
|
|
// app's recovery unit lands at `<path>/backups/primary/<stack>/` (appbackup.RecoveryUnitPath). For a
|
|
// network share that directory would sit inside the share ROOT — which FileBrowser binds whole, with
|
|
// `download: true`, and MUST keep binding whole: the `:rslave` share-root bind is load-bearing for
|
|
// automount wake/idle propagation into the running container (R-67), and scoping it is impossible
|
|
// besides — apps on a share store at `<share>/<app>`, there is no `userdata/` layer, and creating one
|
|
// would write Felhom's convention onto a customer's own NAS, which R-67 forbids outright.
|
|
//
|
|
// So the browsing surface cannot be narrowed and the backup tree must therefore never be placed under
|
|
// it. Tier 2 already refuses network targets for exactly this class of reason (F-6C-1); this closes the
|
|
// PRIMARY namespace, which was the remaining way a `backups/` tree could appear inside a share-root
|
|
// bind. That is the precondition D5 was waiting on.
|
|
//
|
|
// FAIL CLOSED, and the two non-obvious cases are why this is a function and not an `IsNetwork()` call:
|
|
//
|
|
// - `NetworkMountRoot` holds BOTH kinds in-guest (`/mnt/felhom-drives/hdd_1` is a local drive,
|
|
// `/mnt/felhom-drives/Felhom-Share` is a NAS), so a path prefix CANNOT classify. `Kind` is the only
|
|
// discriminator, and it exists only on a REGISTERED path.
|
|
// - therefore an UNREGISTERED path under `NetworkMountRoot` is un-classifiable, and un-classifiable
|
|
// must refuse. Allowing it would be a fallback to "probably a drive" on the one surface that
|
|
// accepts an arbitrary caller-supplied path (the deploy POST validates only `os.Stat` existence).
|
|
// Every NAS share is registered under this root by construction (see NetworkMountRoot), so refusing
|
|
// the unregistered case makes the network set completely covered without touching drives.
|
|
//
|
|
// An empty path is ALLOWED: it means the app is system/SSD-resident and has no external namespace at
|
|
// all. A nil receiver refuses — we cannot consult the registry, so we cannot tell.
|
|
func (s *Settings) RefuseAsAppNamespace(path string) (bool, string) {
|
|
path = strings.TrimSpace(path)
|
|
if path == "" {
|
|
return false, "" // SSD-resident: no external namespace to place
|
|
}
|
|
if s == nil {
|
|
return true, refuseAppNamespaceUndeterminable
|
|
}
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
for _, sp := range s.StoragePaths {
|
|
if path == sp.Path || strings.HasPrefix(path, sp.Path+"/") {
|
|
if sp.IsNetwork() {
|
|
return true, refuseAppNamespaceNetwork
|
|
}
|
|
return false, "" // a registered DRIVE — the supported case, unchanged
|
|
}
|
|
}
|
|
// Not registered. Under the shared mount root its kind is undeterminable → refuse (see above).
|
|
if path == NetworkMountRoot || strings.HasPrefix(path, NetworkMountRoot+"/") {
|
|
return true, refuseAppNamespaceUndeterminable
|
|
}
|
|
return false, ""
|
|
}
|
|
|
|
// DriveOfSubPath reports the registered storage path that `path` lies strictly INSIDE (R-839). An app's
|
|
// HDD_PATH names a drive root — the namespace root, the userdata dir and the backups tree are all
|
|
// derived from it — so a value one or more segments below a registered drive is never valid: the boot
|
|
// sweep's mountpoint check then asks about a folder rather than the drive, and HOLDS the app after
|
|
// every restart (measured on 9202: `<drive>/userdata/paperless-ngx`, written by a drill harness through
|
|
// the deploy API, which accepted it because RefuseAsAppNamespace matches by prefix). Exact matches and
|
|
// unregistered paths return ok=false. Pinned by TestR839_DeployRefusesASubPathOfADrive.
|
|
func (s *Settings) DriveOfSubPath(path string) (string, bool) {
|
|
path = strings.TrimRight(strings.TrimSpace(path), "/")
|
|
if path == "" || s == nil {
|
|
return "", false
|
|
}
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
for _, sp := range s.StoragePaths {
|
|
root := strings.TrimRight(sp.Path, "/")
|
|
if root != "" && strings.HasPrefix(path, root+"/") {
|
|
return sp.Path, true
|
|
}
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
// Refusal reasons for RefuseAsAppNamespace. Hungarian, adult tone, no emoji — these reach the customer
|
|
// through the deploy/migrate error surfaces. They name the storage class and what to do instead, never
|
|
// an internal path or field name.
|
|
const (
|
|
refuseAppNamespaceNetwork = "Hálózati tárhelyen (NAS) nem futtatható alkalmazás adatkönyvtára — " +
|
|
"a NAS megosztás tallózásra és médiatárolásra használható. Válassz csatlakoztatott meghajtót."
|
|
// ⚠ R-220 / SCENARIO G — THIS SENTENCE USED TO NAME AN IMPOSSIBLE ACTION.
|
|
//
|
|
// It said *"Válasszon a listából csatlakoztatott meghajtót"* — choose an attached drive from the
|
|
// list — and on a rebuilt box that list is EMPTY, for a reason the customer had no part in and no
|
|
// way to see. Measured three times live (CAMPAIGN-11 Phase 1, and twice on the R-201 re-walk).
|
|
// Telling someone to pick from an empty list is the I3 breach the campaign recorded: a refusal must
|
|
// name a reason a person can act on.
|
|
//
|
|
// It now says what is true — the drive is not registered ON THIS MACHINE, which is what a rebuild
|
|
// causes — and points at the page where re-attaching happens, rather than at a list that may hold
|
|
// nothing. It promises no outcome, because whether the drive can be re-attached is not knowable
|
|
// from here.
|
|
refuseAppNamespaceUndeterminable = "A megadott tárhely nem azonosítható regisztrált meghajtóként, " +
|
|
"ezért alkalmazás adatkönyvtáraként nem használható. Ha a gépet nemrég telepítettük újra, a " +
|
|
"meghajtóid megvannak, de még nincsenek újra csatlakoztatva ehhez a géphez — a Tárhely → " +
|
|
"Meghajtók oldalon csatlakoztathatod őket, és utána indítsd újra a telepítést. Ha ott sem " +
|
|
"látszanak, keresd a Felhom ügyfélszolgálatát."
|
|
)
|
|
|
|
// IsStoragePathSchedulable returns whether a path belongs to a registered,
|
|
// schedulable (active) storage path. Returns false if the path is unknown,
|
|
// disconnected, decommissioned, or inactive.
|
|
func (s *Settings) IsStoragePathSchedulable(path string) bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
for _, sp := range s.StoragePaths {
|
|
if path == sp.Path || strings.HasPrefix(path, sp.Path+"/") {
|
|
return sp.Schedulable && !sp.Disconnected && !sp.Decommissioned
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// GetStoppedStacks returns the list of stacks that were auto-stopped for a storage path.
|
|
func (s *Settings) GetStoppedStacks(path string) []string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
for _, sp := range s.StoragePaths {
|
|
if sp.Path == path {
|
|
if len(sp.StoppedStacks) == 0 {
|
|
return nil
|
|
}
|
|
result := make([]string, len(sp.StoppedStacks))
|
|
copy(result, sp.StoppedStacks)
|
|
return result
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ClearStoppedStacks removes the stopped stacks list for a storage path (e.g., after restart).
|
|
func (s *Settings) ClearStoppedStacks(path string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
s.StoragePaths[i].StoppedStacks = nil
|
|
return s.save()
|
|
}
|
|
}
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
|
|
// SetDecommissioned marks a storage path as decommissioned with migration target.
|
|
// Clears IsDefault and Schedulable.
|
|
func (s *Settings) SetDecommissioned(path, migratedTo string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.debug {
|
|
s.log.Printf("[DEBUG] [settings] SetDecommissioned path=%q migrated_to=%q", path, migratedTo)
|
|
}
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] Storage path %s decommissioned (migrated_to=%s)", path, migratedTo)
|
|
}
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
s.StoragePaths[i].Decommissioned = true
|
|
s.StoragePaths[i].DecommissionedAt = time.Now().UTC().Format(time.RFC3339)
|
|
s.StoragePaths[i].MigratedTo = migratedTo
|
|
s.StoragePaths[i].IsDefault = false
|
|
s.StoragePaths[i].Schedulable = false
|
|
return s.save()
|
|
}
|
|
}
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
|
|
// ClearDecommissioned removes the decommissioned state from a storage path.
|
|
func (s *Settings) ClearDecommissioned(path string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
s.StoragePaths[i].Decommissioned = false
|
|
s.StoragePaths[i].DecommissionedAt = ""
|
|
s.StoragePaths[i].MigratedTo = ""
|
|
return s.save()
|
|
}
|
|
}
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
|
|
// IsDecommissioned returns whether a storage path is marked as decommissioned.
|
|
func (s *Settings) IsDecommissioned(path string) bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
for _, sp := range s.StoragePaths {
|
|
if sp.Path == path {
|
|
return sp.Decommissioned
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// GetDecommissionedPaths returns a copy of all decommissioned storage paths.
|
|
func (s *Settings) GetDecommissionedPaths() []StoragePath {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
var result []StoragePath
|
|
for _, sp := range s.StoragePaths {
|
|
if sp.Decommissioned {
|
|
result = append(result, sp)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// --- Hub Verification ---
|
|
|
|
// GetHubVerified returns the hub verification state.
|
|
func (s *Settings) GetHubVerified() (verified bool, verifiedAt string) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.HubVerified, s.HubVerifiedAt
|
|
}
|
|
|
|
// SetHubVerified updates the hub verification state and saves to disk.
|
|
func (s *Settings) SetHubVerified(verified bool, at time.Time) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.HubVerified = verified
|
|
s.HubVerifiedAt = at.UTC().Format(time.RFC3339)
|
|
s.HubLastCheck = at.UTC().Format(time.RFC3339)
|
|
return s.save()
|
|
}
|
|
|
|
// GetAppliedConfigVersion returns the last-applied hub config_version (0 = none recorded yet).
|
|
func (s *Settings) GetAppliedConfigVersion() int {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.AppliedConfigVersion
|
|
}
|
|
|
|
// SetAppliedConfigVersion persists the config_version this controller has pulled + applied. Recorded
|
|
// BEFORE a config-refresh self-restart so the restarted process sees it applied and does not loop.
|
|
func (s *Settings) SetAppliedConfigVersion(v int) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.AppliedConfigVersion = v
|
|
return s.save()
|
|
}
|
|
|
|
// SetHubLastCheck updates the last Hub check timestamp without changing verification status.
|
|
// GetLastGuestBootID returns the persisted last-seen guest boot-id ("" if never recorded).
|
|
func (s *Settings) GetLastGuestBootID() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.LastGuestBootID
|
|
}
|
|
|
|
// SetLastGuestBootID persists the current guest boot-id (after a deterministic boot-recreate pass).
|
|
func (s *Settings) SetLastGuestBootID(id string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.LastGuestBootID = id
|
|
return s.save()
|
|
}
|
|
|
|
func (s *Settings) SetHubLastCheck(at time.Time) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.HubLastCheck = at.UTC().Format(time.RFC3339)
|
|
return s.save()
|
|
}
|
|
|
|
// IsLimitedMode returns true if the controller should operate in limited mode
|
|
// (new deployments blocked). This happens when:
|
|
// - Never verified AND >7 days since controller started, OR
|
|
// - Hub explicitly set customer as blocked (HubVerified=false after a successful check)
|
|
func (s *Settings) IsLimitedMode() bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
|
|
if s.HubVerified {
|
|
return false
|
|
}
|
|
|
|
// If we have a last check timestamp and it says not verified, limited mode
|
|
if s.HubLastCheck != "" {
|
|
return true
|
|
}
|
|
|
|
// Never checked yet — check if grace period (7 days) expired
|
|
if s.HubVerifiedAt == "" {
|
|
// No verification timestamp at all — not yet in limited mode (grace period from startup)
|
|
return false
|
|
}
|
|
t, err := time.Parse(time.RFC3339, s.HubVerifiedAt)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return time.Since(t) > 7*24*time.Hour
|
|
}
|
|
|
|
// --- Retrieval Password ---
|
|
|
|
// GetRetrievalPassword returns the stored retrieval password (thread-safe).
|
|
func (s *Settings) GetRetrievalPassword() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.RetrievalPassword
|
|
}
|
|
|
|
// SetRetrievalPassword updates the retrieval password and saves to disk.
|
|
func (s *Settings) SetRetrievalPassword(password string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.RetrievalPassword = password
|
|
return s.save()
|
|
}
|
|
|
|
// --- Pending Events ---
|
|
|
|
// AddPendingEvent queues an event for the next Hub push cycle.
|
|
func (s *Settings) AddPendingEvent(event PendingEvent) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.debug {
|
|
s.log.Printf("[DEBUG] [settings] AddPendingEvent type=%q severity=%q", event.EventType, event.Severity)
|
|
}
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] Added pending event: %s", event.EventType)
|
|
}
|
|
s.PendingEvents = append(s.PendingEvents, event)
|
|
return s.save()
|
|
}
|
|
|
|
// DrainPendingEvents returns and clears all pending events (thread-safe).
|
|
func (s *Settings) DrainPendingEvents() []PendingEvent {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if len(s.PendingEvents) == 0 {
|
|
return nil
|
|
}
|
|
if s.debug {
|
|
s.log.Printf("[DEBUG] [settings] DrainPendingEvents count=%d", len(s.PendingEvents))
|
|
}
|
|
events := make([]PendingEvent, len(s.PendingEvents))
|
|
copy(events, s.PendingEvents)
|
|
s.PendingEvents = nil
|
|
if err := s.save(); err != nil {
|
|
s.log.Printf("[ERROR] [settings] Failed to save after draining pending events: %v — restoring events", err)
|
|
s.PendingEvents = events
|
|
return nil
|
|
}
|
|
return events
|
|
}
|
|
|
|
// --- Geo-Restriction ---
|
|
|
|
// GetGeoRestriction returns a deep copy of the geo-restriction settings.
|
|
func (s *Settings) GetGeoRestriction() *GeoRestriction {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if s.GeoRestriction == nil {
|
|
return nil
|
|
}
|
|
geo := *s.GeoRestriction
|
|
if len(s.GeoRestriction.AllowedCountries) > 0 {
|
|
geo.AllowedCountries = make([]string, len(s.GeoRestriction.AllowedCountries))
|
|
copy(geo.AllowedCountries, s.GeoRestriction.AllowedCountries)
|
|
}
|
|
if len(s.GeoRestriction.AppOverrides) > 0 {
|
|
geo.AppOverrides = make(map[string]AppGeoOverride, len(s.GeoRestriction.AppOverrides))
|
|
for k, v := range s.GeoRestriction.AppOverrides {
|
|
ov := AppGeoOverride{AllowedCountries: make([]string, len(v.AllowedCountries))}
|
|
copy(ov.AllowedCountries, v.AllowedCountries)
|
|
geo.AppOverrides[k] = ov
|
|
}
|
|
}
|
|
return &geo
|
|
}
|
|
|
|
// SetGeoRestriction replaces the entire geo-restriction config and saves to disk.
|
|
func (s *Settings) SetGeoRestriction(geo *GeoRestriction) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.debug {
|
|
if geo == nil {
|
|
s.log.Printf("[DEBUG] [settings] SetGeoRestriction geo=nil (clearing)")
|
|
} else {
|
|
s.log.Printf("[DEBUG] [settings] SetGeoRestriction enabled=%v countries=%d", geo.Enabled, len(geo.AllowedCountries))
|
|
}
|
|
}
|
|
if geo == nil {
|
|
s.GeoRestriction = nil
|
|
return s.save()
|
|
}
|
|
cp := *geo
|
|
if len(geo.AllowedCountries) > 0 {
|
|
cp.AllowedCountries = make([]string, len(geo.AllowedCountries))
|
|
copy(cp.AllowedCountries, geo.AllowedCountries)
|
|
}
|
|
if len(geo.AppOverrides) > 0 {
|
|
cp.AppOverrides = make(map[string]AppGeoOverride, len(geo.AppOverrides))
|
|
for k, v := range geo.AppOverrides {
|
|
ov := AppGeoOverride{AllowedCountries: make([]string, len(v.AllowedCountries))}
|
|
copy(ov.AllowedCountries, v.AllowedCountries)
|
|
cp.AppOverrides[k] = ov
|
|
}
|
|
}
|
|
s.GeoRestriction = &cp
|
|
return s.save()
|
|
}
|
|
|
|
// SetGeoAppOverride sets a per-app geo override. Creates the GeoRestriction if nil.
|
|
// Pass override=nil to remove the override (same as RemoveGeoAppOverride).
|
|
func (s *Settings) SetGeoAppOverride(appName string, override *AppGeoOverride) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if override == nil {
|
|
// nil override = remove (fall back to global)
|
|
if s.GeoRestriction != nil && s.GeoRestriction.AppOverrides != nil {
|
|
delete(s.GeoRestriction.AppOverrides, appName)
|
|
}
|
|
return s.save()
|
|
}
|
|
if s.GeoRestriction == nil {
|
|
s.GeoRestriction = &GeoRestriction{AllowedCountries: []string{"HU"}}
|
|
}
|
|
if s.GeoRestriction.AppOverrides == nil {
|
|
s.GeoRestriction.AppOverrides = make(map[string]AppGeoOverride)
|
|
}
|
|
ov := AppGeoOverride{AllowedCountries: make([]string, len(override.AllowedCountries))}
|
|
copy(ov.AllowedCountries, override.AllowedCountries)
|
|
s.GeoRestriction.AppOverrides[appName] = ov
|
|
return s.save()
|
|
}
|
|
|
|
// RemoveGeoAppOverride removes a per-app override (app falls back to global).
|
|
func (s *Settings) RemoveGeoAppOverride(appName string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.GeoRestriction == nil || s.GeoRestriction.AppOverrides == nil {
|
|
return nil
|
|
}
|
|
delete(s.GeoRestriction.AppOverrides, appName)
|
|
return s.save()
|
|
}
|
|
|
|
// SetGeoSyncState updates the geo sync status fields.
|
|
func (s *Settings) SetGeoSyncState(zoneID, rulesetID, syncError string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.GeoRestriction == nil {
|
|
return nil
|
|
}
|
|
s.GeoRestriction.LastSync = time.Now().UTC().Format(time.RFC3339)
|
|
s.GeoRestriction.LastSyncError = syncError
|
|
if zoneID != "" {
|
|
s.GeoRestriction.ZoneID = zoneID
|
|
}
|
|
if rulesetID != "" {
|
|
s.GeoRestriction.RulesetID = rulesetID
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// --- App email (SMTP relay) ---
|
|
|
|
// GetAppEmail returns the global app-email toggle (a copy; never the live pointer).
|
|
func (s *Settings) GetAppEmail() AppEmail {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if s.AppEmail == nil {
|
|
return AppEmail{}
|
|
}
|
|
return *s.AppEmail
|
|
}
|
|
|
|
// AppEmailEnabled reports whether app-email is globally on.
|
|
func (s *Settings) AppEmailEnabled() bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.AppEmail != nil && s.AppEmail.Enabled
|
|
}
|
|
|
|
// SetAppEmail updates the global app-email toggle and persists it.
|
|
func (s *Settings) SetAppEmail(enabled bool, fromName string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.debug {
|
|
s.log.Printf("[DEBUG] [settings] SetAppEmail enabled=%v from_name=%q", enabled, fromName)
|
|
}
|
|
s.AppEmail = &AppEmail{Enabled: enabled, FromName: strings.TrimSpace(fromName)}
|
|
return s.save()
|
|
}
|
|
|
|
// --- App-to-app integrations ---
|
|
|
|
// GetIntegrationState returns the state for a specific integration key (e.g., "onlyoffice:filebrowser").
|
|
func (s *Settings) GetIntegrationState(key string) (IntegrationState, bool) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if s.Integrations == nil {
|
|
return IntegrationState{}, false
|
|
}
|
|
state, ok := s.Integrations[key]
|
|
return state, ok
|
|
}
|
|
|
|
// SetIntegrationState updates (or creates) the state for a single integration key.
|
|
func (s *Settings) SetIntegrationState(key string, state IntegrationState) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.debug {
|
|
s.log.Printf("[DEBUG] [settings] SetIntegrationState key=%q status=%q enabled=%v", key, state.Status, state.Enabled)
|
|
}
|
|
if s.Integrations == nil {
|
|
s.Integrations = make(map[string]IntegrationState)
|
|
}
|
|
s.Integrations[key] = state
|
|
return s.save()
|
|
}
|
|
|
|
// RemoveIntegrationState removes an integration key entirely.
|
|
func (s *Settings) RemoveIntegrationState(key string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.Integrations != nil {
|
|
delete(s.Integrations, key)
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// GetIntegrationsForProvider returns all integration states where key starts with "provider:".
|
|
func (s *Settings) GetIntegrationsForProvider(provider string) map[string]IntegrationState {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
prefix := provider + ":"
|
|
result := make(map[string]IntegrationState)
|
|
for k, v := range s.Integrations {
|
|
if strings.HasPrefix(k, prefix) {
|
|
result[k] = v
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// GetIntegrationsForTarget returns all integration states where key ends with ":target".
|
|
func (s *Settings) GetIntegrationsForTarget(target string) map[string]IntegrationState {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
suffix := ":" + target
|
|
result := make(map[string]IntegrationState)
|
|
for k, v := range s.Integrations {
|
|
if strings.HasSuffix(k, suffix) {
|
|
result[k] = v
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// GetHubEscrowKeySHA256 returns the sha256 the hub's sealed package covers, and when it was last
|
|
// recorded from an ACK ("" / "" when never learned). See the field comment: empty is "the hub never
|
|
// told us", not "they match".
|
|
func (s *Settings) GetHubEscrowKeySHA256() (sha, checkedAt string) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.HubEscrowKeySHA256, s.HubEscrowKeyCheckedAt
|
|
}
|
|
|
|
// SetHubEscrowKeySHA256 records the ACK's `escrow.restic_pw_sha256` and stamps when. Same
|
|
// last-write-wins mirror discipline as SetHubEscrowIdentityPresent — the hub is the authority on
|
|
// what the hub holds, and a re-ceremony legitimately moves this.
|
|
//
|
|
// The timestamp is refreshed on EVERY ack that carries a hash, including an unchanged one, because
|
|
// it records *when we last heard*, not *when it last changed* — a distinction this project has got
|
|
// wrong before (R-100: LastRun recorded an attempt and was read as a result). A no-op save is
|
|
// avoided only when BOTH the hash and the day are unchanged, so an idle box does not rewrite
|
|
// settings.json every fifteen minutes.
|
|
func (s *Settings) SetHubEscrowKeySHA256(sha, checkedAt string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.HubEscrowKeySHA256 == sha && sameDayStamp(s.HubEscrowKeyCheckedAt, checkedAt) {
|
|
return nil
|
|
}
|
|
s.HubEscrowKeySHA256, s.HubEscrowKeyCheckedAt = sha, checkedAt
|
|
return s.save()
|
|
}
|
|
|
|
// sameDayStamp reports whether two RFC3339 stamps fall on the same UTC day — the write-damper for
|
|
// SetHubEscrowKeySHA256. Unparseable stamps are treated as different, so a malformed value always
|
|
// gets replaced rather than sticking.
|
|
func sameDayStamp(a, b string) bool {
|
|
if a == "" || b == "" {
|
|
return false
|
|
}
|
|
ta, erra := time.Parse(time.RFC3339, a)
|
|
tb, errb := time.Parse(time.RFC3339, b)
|
|
if erra != nil || errb != nil {
|
|
return false
|
|
}
|
|
return ta.UTC().Format("2006-01-02") == tb.UTC().Format("2006-01-02")
|
|
}
|
|
|
|
// ── The recovery-offer epoch (v0.206.0, R-241) ─────────────────────────────────
|
|
|
|
// RecoveryOfferView is the epoch read model.
|
|
type RecoveryOfferView struct {
|
|
Epoch int
|
|
Active bool
|
|
PostponedEpoch int
|
|
OptOutEpoch int
|
|
Since string // RFC3339 — when the current epoch began
|
|
}
|
|
|
|
// GetRecoveryOfferView returns the epoch state in one lock.
|
|
func (s *Settings) GetRecoveryOfferView() RecoveryOfferView {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return RecoveryOfferView{
|
|
Epoch: s.RecoveryOfferEpoch,
|
|
Active: s.RecoveryOfferActive,
|
|
PostponedEpoch: s.RecoveryNoticePostponedEpoch,
|
|
OptOutEpoch: s.RecoveryRemindOptOutEpoch,
|
|
Since: s.RecoveryOfferSince,
|
|
}
|
|
}
|
|
|
|
// SyncRecoveryOfferEpoch advances the epoch on the EDGE into the offered state and returns the view.
|
|
// Idempotent: called on every landing page load, it writes only on a transition.
|
|
//
|
|
// THE LEGACY MIGRATION IS HERE AND HAPPENS ONCE. A box upgrading from ≤v0.205.0 may carry
|
|
// `RecoveryNoticePostponed=true` — a customer who already said "most nem" about the situation they
|
|
// are still in. Re-interrupting them on upgrade would be a regression dressed as a feature, so the
|
|
// first epoch inherits that choice and the legacy flag is retired. A box that never dismissed keeps
|
|
// PostponedEpoch 0 and is interrupted, which is correct.
|
|
func (s *Settings) SyncRecoveryOfferEpoch(offered bool, now time.Time) (RecoveryOfferView, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
changed := false
|
|
if offered && !s.RecoveryOfferActive {
|
|
s.RecoveryOfferActive = true
|
|
s.RecoveryOfferEpoch++
|
|
s.RecoveryOfferSince = now.UTC().Format(time.RFC3339)
|
|
if s.RecoveryOfferEpoch == 1 && s.RecoveryNoticePostponed {
|
|
s.RecoveryNoticePostponedEpoch = 1 // inherit the pre-epoch dismissal, once
|
|
s.RecoveryNoticePostponed = false
|
|
}
|
|
changed = true
|
|
} else if !offered && s.RecoveryOfferActive {
|
|
s.RecoveryOfferActive = false
|
|
changed = true
|
|
}
|
|
view := RecoveryOfferView{
|
|
Epoch: s.RecoveryOfferEpoch, Active: s.RecoveryOfferActive,
|
|
PostponedEpoch: s.RecoveryNoticePostponedEpoch, OptOutEpoch: s.RecoveryRemindOptOutEpoch,
|
|
Since: s.RecoveryOfferSince,
|
|
}
|
|
if !changed {
|
|
return view, nil
|
|
}
|
|
return view, s.save()
|
|
}
|
|
|
|
// PostponeRecoveryNoticeForEpoch records "most nem" for the CURRENT epoch. It suppresses the
|
|
// full-page interruption only — the banner and the backups-area entry point both survive.
|
|
func (s *Settings) PostponeRecoveryNoticeForEpoch() error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.RecoveryNoticePostponedEpoch == s.RecoveryOfferEpoch {
|
|
return nil
|
|
}
|
|
s.RecoveryNoticePostponedEpoch = s.RecoveryOfferEpoch
|
|
return s.save()
|
|
}
|
|
|
|
// OptOutRecoveryRemindersForEpoch records „ne emlékeztessen újra" for the CURRENT epoch. It silences
|
|
// the BANNER and nothing else: no countdown starts, nothing is abandoned, and the entry point on the
|
|
// backups page remains. A later fresh entry into the offered state advances the epoch and reminds
|
|
// again — the §7.1 conditions, satisfied by arithmetic rather than by remembering to clear a flag.
|
|
func (s *Settings) OptOutRecoveryRemindersForEpoch() error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.RecoveryRemindOptOutEpoch == s.RecoveryOfferEpoch {
|
|
return nil
|
|
}
|
|
s.RecoveryRemindOptOutEpoch = s.RecoveryOfferEpoch
|
|
return s.save()
|
|
}
|
|
|
|
// LastUnhealthyStop returns when the box last stopped `stack` for being unhealthy (decision 28).
|
|
func (s *Settings) LastUnhealthyStop(stack string) (time.Time, bool) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
v, ok := s.UnhealthyStops[stack]
|
|
if !ok {
|
|
return time.Time{}, false
|
|
}
|
|
t, err := time.Parse(time.RFC3339, v)
|
|
return t, err == nil
|
|
}
|
|
|
|
// RecordUnhealthyStop stores the time of a stop (decision 28).
|
|
func (s *Settings) RecordUnhealthyStop(stack string, at time.Time) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.UnhealthyStops == nil {
|
|
s.UnhealthyStops = map[string]string{}
|
|
}
|
|
s.UnhealthyStops[stack] = at.UTC().Format(time.RFC3339)
|
|
return s.save()
|
|
}
|
|
|
|
// ClearUnhealthyStopHold lifts an app's hold ONLY when it is an unhealthy stop (the Start button's
|
|
// one more try). Any other hold stays. Returns whether one was lifted.
|
|
func (s *Settings) ClearUnhealthyStopHold(stack string) (bool, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
h, ok := s.RestoreHolds[stack]
|
|
if !ok || h.Reason != HoldReasonUnhealthyStop {
|
|
return false, nil
|
|
}
|
|
delete(s.RestoreHolds, stack)
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] unhealthy-stop hold LIFTED for %s (Start)", stack)
|
|
}
|
|
return true, s.save()
|
|
}
|
|
|
|
// MarkMediaChanged records a media drive event (added | removed | returned) — the media apps must restart to see it.
|
|
func (s *Settings) MarkMediaChanged(path, change string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
s.StoragePaths[i].MediaChangedAt = time.Now().UTC().Format(mediaTS)
|
|
s.StoragePaths[i].MediaChange = change
|
|
if s.log != nil {
|
|
s.log.Printf("[INFO] [settings] media drive event: %s %s — the media apps must restart to see it", path, change)
|
|
}
|
|
return s.save()
|
|
}
|
|
}
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
|
|
// MarkMediaRestarted records that the media apps were restarted now, after every pending drive event.
|
|
func (s *Settings) MarkMediaRestarted() error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
now := time.Now().UTC().Format(mediaTS)
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].MediaChangedAt != "" {
|
|
s.StoragePaths[i].MediaRestartedAt = now
|
|
}
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// GetMediaRestartLater returns the stored „later" media restart time (zero = none or unreadable).
|
|
func (s *Settings) GetMediaRestartLater() time.Time {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
t, err := time.Parse(time.RFC3339, s.MediaRestartLaterAt)
|
|
if err != nil {
|
|
return time.Time{}
|
|
}
|
|
return t
|
|
}
|
|
|
|
// SetMediaRestartLater stores (or, with a zero time, clears) the „later" media restart time and saves.
|
|
func (s *Settings) SetMediaRestartLater(at time.Time) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if at.IsZero() {
|
|
s.MediaRestartLaterAt = ""
|
|
} else {
|
|
s.MediaRestartLaterAt = at.UTC().Format(time.RFC3339)
|
|
}
|
|
return s.save()
|
|
}
|
|
|
|
// MediaRestartPending reports whether a drive changed after the media apps last restarted.
|
|
func (sp StoragePath) MediaRestartPending() bool {
|
|
return sp.MediaChangedAt != "" && sp.MediaRestartedAt < sp.MediaChangedAt
|
|
}
|
|
|
|
// SetEjected records a SAFE removal: the drive stays registered and disconnected, with the torrents the removal paused.
|
|
func (s *Settings) SetEjected(path, durableID string, paused []string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
sp := &s.StoragePaths[i]
|
|
sp.Disconnected, sp.DisconnectedAt = true, time.Now().UTC().Format(time.RFC3339)
|
|
sp.EjectedAt, sp.EjectDurableID, sp.EjectSeenGone, sp.EjectPaused = sp.DisconnectedAt, durableID, false, paused
|
|
return s.save()
|
|
}
|
|
}
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
|
|
// SetEjectSeenGone records that a safely removed drive's disk left the host after the eject.
|
|
func (s *Settings) SetEjectSeenGone(path string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
s.StoragePaths[i].EjectSeenGone = true
|
|
return s.save()
|
|
}
|
|
}
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
|
|
// ClearEjected ends a safe removal (the drive came back): connected, the eject fields cleared.
|
|
func (s *Settings) ClearEjected(path string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for i := range s.StoragePaths {
|
|
if s.StoragePaths[i].Path == path {
|
|
sp := &s.StoragePaths[i]
|
|
sp.Disconnected, sp.DisconnectedAt, sp.StoppedStacks = false, "", nil
|
|
// EjectPaused is KEPT: the torrents resume after the media apps' restart (TakeResumable), when the download
|
|
// apps see the drive again — resumed before, they would report their files missing.
|
|
sp.EjectedAt, sp.EjectDurableID, sp.EjectSeenGone = "", "", false
|
|
return s.save()
|
|
}
|
|
}
|
|
return fmt.Errorf("storage path %q not found", path)
|
|
}
|
|
|
|
// mediaTS is a FIXED-width timestamp, so two of them compare correctly as strings (RFC3339Nano trims trailing zeros).
|
|
const mediaTS = "2006-01-02T15:04:05.000000000Z"
|
|
|
|
// TakeResumable returns, and clears, the torrents paused by a safe removal of drives that are back.
|
|
func (s *Settings) TakeResumable() []string {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
var out []string
|
|
for i := range s.StoragePaths {
|
|
sp := &s.StoragePaths[i]
|
|
if sp.EjectedAt == "" && len(sp.EjectPaused) > 0 {
|
|
out = append(out, sp.EjectPaused...)
|
|
sp.EjectPaused = nil
|
|
}
|
|
}
|
|
if len(out) > 0 {
|
|
_ = s.save()
|
|
}
|
|
return out
|
|
}
|