# Security Fixes — Audit Remediation (2026-08-28) Remediation of the security audit findings (H1, H2, H3, M3, M4, L1–L3). All items verified with `node --check` (JS) and `go vet` + `go build` (sshterm). ## Reinstall Partial-Teardown Review - **Medium (operational):** Docker can stop the original container and then fail to remove it. The reinstall refused to replace files but did not report the stop, so the panel could restore a stale running status. The [daemon](reinstall.go) now checks the original container ID after a removal error and reports a stopped state only if Docker confirms it. A failed removal still leaves the original files, backup data, and allocation intact. Reviewed the complete [reinstall scene](views/bot.ejs#L7115) and controller, the two panel rebuild callers, and the daemon path through rollback and recovery. No new authorization bypass or scene-level injection was confirmed. The regression covers both a container that remains running and one that exits before removal fails. The full Node and Go suites passed. No live reinstall or service restart was performed; after an unconfirmed outcome, check the node and panel records before retrying. ## Reinstall Recovery and Container Ownership Review Reviewed the complete [reinstall scene](views/bot.ejs#L7115) and browser controller, both panel routes that dispatch a rebuild, and the daemon handler and rebuild helpers. Traced permissions, one-time tokens, password/TOTP, transport, runtime and storage policy, competing operations, cancellation, Minecraft consent, partial success, and recovery. No scene-level injection, CSRF bypass, or unauthorized wipe was confirmed. No scene edit was needed. - **Medium, interrupted file replacement:** A daemon exit between directory renames or between publishing the replacement and saving its metadata left the server missing or inconsistent. [Recovery](reinstall.go) now records both directory identities before moving files. On restart it restores the verified original or keeps the verified committed rebuild. If ownership or metadata is ambiguous, it leaves the files for operator inspection. This covers process interruption with a recovery record, not host power loss or unfinished rebuilds from older binaries. - **Medium, wrong-container removal:** Reinstall could remove a Docker container by a reused name after preflight, including during startup. It now removes only the verified container ID, requires matching volume evidence for unlabeled legacy containers, and lets Docker report a name conflict without removing the conflicting container. Compatibility retry cleanup uses the ID created by that startup attempt. - **Medium, installer resource isolation:** The [shared template installer](docker_engine.go) now applies configured CPU, memory, swap, and process limits to staged installs. Those limits apply to the installer container itself; they are not a combined quota with the still-running server or a hard disk quota. Regression coverage uses temporary storage and stubbed Docker. No live node was reinstalled or deployed. The panel does not automatically reconcile a lost reply after daemon commit: check the node and panel allocation/template before retrying an unconfirmed rebuild. Verified HTTPS and adequate staging disk headroom remain deployment requirements. Production Docker, providers, proxy deadlines, SQL/Redis behavior, and mixed-version rollout were not tested. ## Reinstall Transport and Preflight Review (2026-11-20) Reviewed the reinstall scene and controller, both panel rebuild routes, and the daemon from authorization through staging, replacement, startup, and failure handling. No template injection, CSRF bypass, or unauthenticated wipe was found in the scene itself. The fixes are in the shared paths behind the scene: - **High, conditional on an untrusted network path:** The node signature did not cover the full reinstall configuration or authenticate the result. Both panel routes now [require verified HTTPS](utils/server-reinstall.js) before sending node credentials or running port probes. Configure a trusted node certificate with hostname verification before deploying to HTTP-only nodes. With a reverse proxy, secure the origin connection too. The panel cannot validate the proxy-to-node transport. - **Medium, avoidable downtime and container ownership:** [Daemon preflight](reinstall.go) now verifies existing container ownership before teardown and checks for port conflicts that do not depend on first releasing its current bindings. All bindings are checked again before the file commit. Both panel routes also require the same node identity when refreshing its port allocation. - **Medium, recovery safety:** Reinstall refuses to initialize new files over a missing or non-directory live volume. The directory handoff also refuses to publish a replacement when the original tree is absent. - **Medium, memory and entrypoint integrity:** [Shared scaffold detection](runtime-scaffold.go) bounds reads when looking for legacy generated stubs, leaving large installer-generated entrypoints untouched. An interrupted daemon swap can still require manual recovery. A lost result after a commit can leave panel allocation or template metadata out of sync; verify both records before retrying. Staged installers still need disk headroom and an infrastructure quota for a hard write limit. The regression checks use local fixtures and stubbed services, not a live server reinstall. ## Reinstall Pre-Commit and Runtime Review (2026-11-19) Reviewed the complete [reinstall scene](views/bot.ejs#L7115), its browser controller and permission/token paths, both panel rebuild callers, and the daemon handler and helpers. Followed the authorization and suspension gates, signed transport and legacy retries, allocation and operation locks, file and backup handling, installer and Minecraft preparation, startup/EULA, the panel commit, and failure and recovery paths. No new browser injection, CSRF, or unauthenticated wipe was found; the scene itself did not require an edit. - **File permission containment.** The daemon's installer and startup paths shared a permission walk that could change modes outside the server tree by following symlinks. [The shared walk](server_policy.go#L28) now works on pinned regular files and directories on Linux and skips symlink entries. - **Destructive work before preparation.** Minecraft could commit a wipe before verifying runtime image availability, and other templates ran their installer after committing. [Reinstall staging](reinstall.go) now verifies the Minecraft image and runs custom installers before stopping or replacing the existing server. A failed, canceled, or over-budget staged installation leaves its original files, allocation, and backups in place. Installer cleanup uses the Docker-issued container ID, not a possibly unowned name. - **Daemon replay window.** The nonce lifetime now covers the entire allowed timestamp interval, including future clock skew. The default nonce requirement and explicitly configured legacy behavior are unchanged. - **Stale or incorrect power state.** The daemon verifies running state and reports a confirmed early exit as a startup failure after the file commit. Both panel callers use [the shared result handler](utils/server-reinstall.js#L153) to release the claim to the confirmed state. Legacy or inconclusive replies do not imply that the container is running. Regressions use local fixtures, stubbed Docker, and isolated route/controller harnesses. No live server was reinstalled. Staged installs need temporary disk headroom; the pre-commit quota check is not a hard filesystem quota while the installer runs. Post-commit startup failures do not restore old files, and a lost or interrupted result still requires checking the node and panel records before retrying. Live Docker/providers, proxy timeouts, and deployed SQL/Redis and mixed-version behavior were not verified. Use authenticated TLS for remote node API connections and keep nonce enforcement enabled. ## Reinstall Commit and Request-Bound Review (2026-11-19) This pass traced the [Reinstall scene](views/bot.ejs#L7115), its browser controller, the direct and settings template-change panel routes, and the shared daemon rebuild. No new browser injection, CSRF, or authorization bypass was confirmed in that flow. No scene markup change was needed. - **Data loss on a failed commit.** The daemon deleted the old directory before the replacement or metadata write could fail. Reinstall now retains the original directory until the staged tree and authoritative metadata are in place. A failed handoff or metadata save restores the original before replying. If the filesystem also refuses rollback, the daemon preserves the original tree and logs its recovery path. The [shared metadata writer](server_policy.go#L212) does not truncate the previous record in place. If deleting the old directory fails after commit, both panel routes report partial completion, retain the actual allocation and template, and leave the server stopped. - **Oversized daemon configuration.** Reinstall JSON inherited the file-upload limit (1 GiB by default). It now has a [4 MiB ceiling](reinstall.go#L19), honors a lower configured limit, and refuses oversized JSON before any destructive work. - **Silent compatibility downgrade.** A legacy node's rejection of an explicit Minecraft Java version no longer triggers a second reinstall without that selection. Server creation's existing compatibility behavior is unchanged. The regressions use temporary storage, isolated panel route harnesses, and stubbed Docker. No live server was reinstalled or configuration deployed. A lost response after the daemon commits can still leave the panel on the old allocation or template; runtime polling does not reconcile those fields. Inspect the node and panel records before retrying an unconfirmed reinstall. This fix does not provide automatic crash recovery or roll back files after an installer or startup failure following a successful commit. Keep legacy plaintext node connections on loopback or use authenticated TLS for remote nodes. ## Reinstall Admission and Metadata Review (2026-11-19) This pass read the complete reinstall scene and controller, both panel rebuild handlers and their shared machinery, and the complete daemon reinstall handler and helpers. It followed the controlling navigation, authorization, transport, runtime, storage, failure and recovery paths. Earlier repairs below remain present and are not new findings from this pass. ### New Reproduced Findings | ID | Severity / Impact | Evidence and Repair | | --- | --- | --- | | R26 | Medium, destructive admission and policy loss | Missing, corrupt, null, empty or unreadable daemon metadata was treated as an empty configuration. The real daemon regression returned success after wiping files for five cases, and wiped before reporting a save failure for a read-error case. An authorized rebuild could discard authoritative binding, resource, quota and disk policy or destroy data despite an already-detectable metadata failure. The existing loader now lives once in [server_policy.go](server_policy.go), with a checked mode used before container removal by [main.go](main.go). Uncertain metadata and failed legacy migration refuse with `reinstall_meta_read_failed`; files and operation-lock cleanup remain intact. Valid legacy metadata preserves policy. The existing save-failure fixture now injects its fault after preflight, preserving its original post-wipe assertion. | | R27 | Medium, pending-request authorization revocation | Both real extracted panel handlers still called the daemon and returned HTTP 200 after server access removal or admin demotion during step-up. Server target snapshots do not cover account status, credential generation, SID revocation or the separate access list. [utils/server-reinstall.js](utils/server-reinstall.js) now shares a fresh actor/session/access check and dispatch for both callers, reusing the existing credential fingerprint and generation comparison. Credential changes, account replacement/suspension, demotion, revoked sessions and lost permission refuse before dispatch. Signing retries and optional unknown-field resends repeat the same check; local template changes check before commit. Already-confirmed remote rebuilds still commit their authoritative configuration if revocation occurs after dispatch. | Both findings are fixed in the working tree with regressions in [reinstall_backup_race_test.go](reinstall_backup_race_test.go), [tests/reinstall-route-protection.test.js](tests/reinstall-route-protection.test.js) and [tests/template-change-port-binding.test.js](tests/template-change-port-binding.test.js). R26 requires damaged or unavailable saved metadata; R27 requires an initially authorized request and a concurrent revocation/change before its dispatch. Neither is a demonstrated unauthenticated wipe or host escape. No new reinstall-scene XSS or CSRF bypass was demonstrated. Harmless presentation details were left unchanged. ### Coverage and Verification - Read all reinstall markup/controller states: warning, confirmation, password/TOTP, close/reopen, pending requests, explicit success and uncertain errors; related navigation/permissions/token refresh, escaped markup and text-only rendering. - Read both complete panel rebuild paths and the shared helpers; traced session/account access, ACL/suspension, token mint/consume, request and credential budgets, step-up/scoped grace, fresh target and actor admission, canonical row commit, port allocation, activity and claim cleanup/recovery. - Read the complete daemon rebuild and helpers; traced bearer/HMAC/nonce, legacy retries, owning-disk routing, metadata migration/persistence, runtime inheritance/preflight, container removal, reset, installer/scaffold, Minecraft selection/download/quota/EULA, mounts and subsequent runtime seed. Followed operation/storage locks and relevant competing backup/restore, export/transfer/import, power, resource/consent and file-write boundaries. This is not an independent audit of unrelated scenes or every dependency. - Final full `npm test`: 4,253 total, 4,244 passed, 9 skipped, zero failures. Final touched panel/controller suites: 65/65 passed. Full daemon `go test .` passed with cached Go 1.26.9. New reproductions failed before their fixes and passed afterward; daemon metadata, migration and competing-op checks and the neighboring panel authorization/cleanup/source guards passed. - JavaScript syntax, editor diagnostics, touched Go formatting, explicit async-route scanning (zero unguarded awaits) and session-snapshot whitespace checks passed, including untracked modules and tests. Reviewed the diff and searched the sibling callers; no parallel metadata loader or authorization implementation was introduced. ### Delivery and Limits Ship the changed panel caller with [utils/server-reinstall.js](utils/server-reinstall.js) and rebuild the complete root daemon package with [server_policy.go](server_policy.go). Changes are not deployed. No live server was reinstalled, no application/service was launched or reloaded, and unrelated dirty/untracked work was preserved. Servers lacking trustworthy metadata now require administrator repair rather than destructive default reconstruction. Concurrent credential or access changes require a new authorized request. This is not proof of zero vulnerabilities. Tests use temporary storage, synthetic credentials, injected route dependencies and stubbed Docker, not live installers/providers, production SQL/Redis scheduling, TLS/proxy timeouts or a mixed-version rollout. The fresh actor check is pre-dispatch admission, not a distributed transaction with account/access changes or cancellation of work already sent to the daemon. Node-port locking remains process-local for the current one-worker configuration. Container writes still rely on existing infrastructure/monitor enforcement, not a newly added hard filesystem quota. Post-wipe failures have no automatic data rollback; uncertain transport or failed metadata/index saves require inspection before retrying. ## Reinstall Policy-Preservation Review (2026-11-19) Read the complete reinstall scene and controller, both panel rebuild handlers, and the full daemon reinstall handler and helpers. Followed the controlling navigation, token, permission, step-up, transport, storage, runtime, persistence and recovery paths, including the next managed-runtime start after reinstall. Earlier fixes below were preserved and are not counted as new findings. ### New Reproduced Findings | ID | Severity / Impact | Reproduction and Repair | | --- | --- | --- | | R23 | Medium, lost filesystem restriction | Changing templates discarded the old runtime's explicit read-only root policy along with its execution settings. Real-handler regressions failed for both `readonlyRootfs` and `readOnly`. [reinstall.go](reinstall.go) now retains only the security-policy subset across a template switch; old commands and environment secrets remain excluded. | | R24 | Medium, unintended network exposure | A private interface saved on the primary port allocation became `0.0.0.0` when reinstall rebound the server to a different pool port. Real-handler regressions reproduced both top-level and resource-level allocation forms. The existing allocation-IP resolver was extracted once into [server_policy.go](server_policy.go), shared with Docker binding construction. Reinstall carries the old primary interface to an unconfigured destination; explicit destination policy, additional ports and unchanged-port precedence remain intact. | | R25 | Medium, post-reinstall policy loss | The next Python/Node.js/Discord-bot start re-seeds daemon metadata. The real reinstall-to-runtime-seed regression showed that seed dropping read-only and private-interface/allocation policy plus `__diskId`; a UDP-only allocation also became TCP-only. The seed's existing metadata merge was extracted from [main.go](main.go) into [server_policy.go](server_policy.go). Reinstall and seed now share runtime and metadata policy preservation, retaining security, protocol and disk identity without inheriting unrelated execution settings. | All three are fixed with regressions in [reinstall_backup_race_test.go](reinstall_backup_race_test.go). They require affected saved policy and an authorized reinstall/template change or subsequent managed start; they are not demonstrated unauthenticated wipes or host escapes. No new scene XSS, CSRF bypass or authorization bypass was demonstrated. Harmless presentation details were left unchanged. ### Coverage and Verification - Reviewed dialog confirmation/password/TOTP/close/reopen/error/success states, escaped markup, inline navigation, permission refresh and token retry; panel access/ACL/suspension, single-use session/server tokens, rate budgets, destructive proof/grace, target snapshots, node bearer/HMAC/nonce and retry; host-port checks, canonical commits, activity, claim release and recovery. - Reviewed runtime inheritance/preflight, container removal, filesystem reset, installer/scaffold/download, metadata and owning-disk/backup routing, quota and storage locks, runtime mounts, startup/EULA and the next runtime seed. Followed competing power, suspension, resource/EULA, file-write, backup/restore, delete, import/export and transfer paths where they interact with reinstall. This is not an independent line-by-line audit of unrelated sibling features or every transitive dependency. - Final `npm test`: 4,245 tests, 4,236 passed, 9 skipped, zero failures. Final `go test .` passed using the existing cached Go 1.26.9 toolchain. Focused regressions failed before the respective repairs and passed after. Go formatting, editor diagnostics, JavaScript syntax, explicit async-route scanning and session-baseline whitespace checks passed. ### Delivery and Limits Rebuild the full root daemon package including [reinstall.go](reinstall.go) and [server_policy.go](server_policy.go). Changes are not deployed. No live server was reinstalled, no application or service was launched/reloaded, and existing unrelated dirty/untracked work was preserved. This is not proof of zero vulnerabilities. Tests used temporary storage, synthetic credentials and stubbed Docker, not live installers/providers, production SQL/Redis concurrency, TLS/proxy timeouts or a mixed-version rollout. Node-port locking is still process-local for the current one-worker deployment; container writes still rely on existing infrastructure/monitor enforcement, not a newly added hard filesystem quota. Post-wipe failures have no automatic data rollback; unknown transport results or failed metadata/index saves require inspection before retrying. Provider resolution is not byte-identical jar restoration. These limits were not silently changed or certified by this review. ## Reinstall Installer and Port-Admission Review (2026-11-19) This continuation read the entire reinstall scene and controller, both complete panel rebuild handlers, and the complete daemon handler and rebuild helpers. It followed navigation and credential states, permission refresh, action-token mint/verification/consumption, access/ACL/suspension, account/session budgets, password/TOTP and scoped grace, node bearer/HMAC/nonce authentication, signing rotation and compatibility retries, host-port selection, index commits and activity/cleanup. Daemon coverage included runtime inheritance and preflight, container removal, installer/scaffold/download, external metadata, cold-cache disk and backup routing, quota/storage locks, runtime mounts and startup/EULA, and claim/heartbeat/recovery. Competing power, backup/restore, transfer/export, runtime seed, resource/EULA and file writes were followed where they interact with reinstall. This is not an independent audit of unrelated scenes or every transitive dependency. Historical repairs below were preserved, not recounted. ### New Reproduced Findings | ID | Severity / Impact | Reproduction and Repair | | --- | --- | --- | | R20 | Medium, post-wipe configuration divergence | A non-Minecraft installer failure after deletion returned generic `install failed` before saving the rebuilt metadata. The panel therefore retained the previous host port/template. A real daemon regression reproduced that failure. [reinstall.go](reinstall.go) now persists rebuilt metadata before running the installer and returns explicit `reinstall_install_failed` / `reinstalled: true`. Both panel handlers share classification in [utils/server-reinstall.js](utils/server-reinstall.js), commit confirmed rebuilt allocation/template, return failure, and neither report success nor automatically repeat a wipe. The existing non-Minecraft preparation was extracted from the frozen monolith, not duplicated. R18's historical exclusion of installer failures is superseded for this explicit persisted outcome. | | R21 | Low, valid installer configuration rejected | The daemon classified slashless tagged Docker Hub images such as `alpine:3.20` as registry hostnames, while the panel accepted them as Docker Hub references. A focused parser regression reproduced the mismatch. The existing shared daemon image policy now lives once in [template_image_policy.go](template_image_policy.go) and matches the panel's first-component-with-slash rule. Tagged/digest shorthand works; unapproved explicit registries still refuse. | | R22 | Medium, destructive port admission | A legacy server with no saved port could take an occupied template-default host port merely because it belonged to the node pool. A real extracted admin rebuild handler called the daemon despite an exhausted pool. The shared resolver now checks an unclaimed default through the existing ownership/liveness guard before authorizing deletion. A conflicting default uses the regular free allocator or refuses 409; lookup failures refuse without a wipe and release the claim. Existing owned ports and genuinely available defaults retain their behavior. | All three are fixed in this working tree with focused regressions. These are functional rebuild defects, not demonstrated unauthenticated attacks. No new reinstall-scene XSS, CSRF bypass, unauthorized wipe or host escape was demonstrated. Harmless presentation differences were left unchanged. ### Verification and Limits - Final full `npm test`: 4,245 total, 4,236 passed, 9 skipped, zero failures. Final full daemon `go test .` passed using cached Go 1.26.9. Focused panel rebuild/controller tests, real daemon installer failure, image policy, metadata, backup/export/storage and operation-lock checks passed. - JavaScript/EJS syntax, editor diagnostics and scoped Go formatting passed; the explicitly invoked async-route scanner reports zero unguarded awaits. - Touched implementation and review-record whitespace checks passed against preserved edit checkpoints, including untracked modules and tests. - Tests use synthetic credentials, deterministic route dependencies and temporary storage with stubbed Docker. No live server was reinstalled, and no application launch, service reload, deployment or account/backing-service configuration change was performed. Existing dirty/untracked work remains. Ship the panel caller and shared reinstall helper together; rebuild the full root Go package including [reinstall.go](reinstall.go) and [template_image_policy.go](template_image_policy.go). Changes are not deployed. This is not proof of zero vulnerabilities: live Docker/installers/providers, TLS/proxy timeouts, production SQL/Redis and mixed-version delivery were not exercised. Node-port locking remains process-local for the configured one panel worker; external consumers are not reserved by it. Container writes still rely on existing infrastructure/monitor enforcement, not a new hard filesystem quota. Post-wipe failures have no automatic data rollback, and unknown transport results or failed metadata/index saves need inspection before retrying. Provider resolution is not byte-identical jar restoration. ## Reinstall Failure and Recovery Review (2026-11-19) This pass read the complete reinstall scene markup and controller, their navigation/close/credential/token paths, both complete panel rebuild handlers, and the daemon reinstall handler and helpers. It followed the controlling authorization, ACL/suspension, account/session rate budgets, destructive step-up, bearer/HMAC/nonce checks, compatibility retry, allocation and index commit, storage/quota/disk/backups, installer/scaffold/download, container startup/EULA, claim/heartbeat/recovery and competing-operation boundaries. Unrelated scenes and independent audits of every sibling feature remain outside scope. Previous repairs below were preserved and are not new findings. ### New Reproduced Findings | ID | Severity / Impact | Evidence and Repair | | --- | --- | --- | | R17 | Medium, rebuild correctness | Same-template Minecraft reinstall discarded the recorded fork/version and always rebuilt Paper 1.21.8. The metadata regression failed before the fix. [reinstall.go](reinstall.go) now carries the recorded selection into preparation and reuses the existing strict Minecraft validators before deleting files. Missing legacy selections and genuine template changes retain existing defaults; malformed recorded selections refuse without a wipe. This preserves recorded metadata, not an arbitrary manually uploaded jar or its exact build. | | R18 | Medium, panel/node configuration divergence after failure | Both panel handlers returned before committing a rebuilt runtime when container startup failed, leaving the old port/template in the panel. Runtime image preparation and Minecraft jar-resolution/download/quota failures also occur after authoritative rebuilt metadata commits. [utils/server-reinstall.js](utils/server-reinstall.js) now classifies explicit persisted-rebuild outcomes once for both callers; they commit the new port/template but still return failure, with no success activity or automatic destructive retry. Daemon responses carry stage-specific codes and a boolean partial-completion marker. The exact legacy startup-failure contract remains recognized. Preflight/installer failures and unknown transport outcomes do not falsely assert a persisted rebuild. | | R19 | Medium, snapshot integrity during recovery | The real daemon export handler returned a tar snapshot while the reinstall operation lock was held. A panel restart can clear an orphaned panel claim while its background node rebuild continues, so panel admission alone cannot protect the snapshot. The single export implementation now lives in [server-export.go](server-export.go) and holds the existing fail-fast server operation lock for the complete snapshot. Conflicts return 409 without queueing; successful/early-return lock cleanup and existing pinned-root/no-follow/bounded-copy assertions pass. | All three are fixed in this working tree. No new reinstall-scene XSS, CSRF, unauthenticated wipe, authorization bypass or host escape was demonstrated. Harmless presentation details were not counted as findings or redesigned. ### Verification - Final `npm test`: 4,240 total, 4,231 passed, 9 skipped, zero failures. - Final full daemon `go test .`: passed using cached Go 1.26.9. - Final focused panel/controller and template-change suites: 52/52 passed. Daemon reinstall/export tests passed, including real HTTP auth refusals, pre-wipe selection rejection, persisted startup/image failures, owning-disk quota refusal, backup preservation, concurrency and export lock cleanup. - JavaScript/EJS syntax, scoped Go formatting, editor diagnostics and session-baseline whitespace checks passed. The explicitly invoked async-handler scanner reports zero unguarded awaits in both monoliths. - Export source-location assertions were updated for extraction, preserving all pinned-root/no-follow/header-size assertions and adding single-owner and operation-lock checks. No assertion protecting behavior was weakened. ### Delivery and Limits Ship the changed panel caller with [utils/server-reinstall.js](utils/server-reinstall.js) and rebuild the node from the complete root Go package, including [reinstall.go](reinstall.go), [server-export.go](server-export.go) and the existing policy modules. Reload panel workers only as an explicit deployment action. No production reinstall, app launch, installation, deployment, service reload, account or backing-service configuration change was performed here. This is not proof of zero vulnerabilities. Live Docker/installer/providers, TLS/proxy timeout behavior, production SQL/Redis concurrency and mixed-version rollout were not exercised. The existing node-port mutex remains process-local, not a distributed reservation. Container-mediated writes still rely on existing infrastructure/monitor enforcement, not a newly added hard filesystem quota. Post-wipe failures have no automatic data rollback; unknown transport outcomes, legacy download failures without an explicit marker and failed metadata/index saves require operator inspection before retrying. Minecraft reinstall uses the recorded fork/version through the existing provider resolver, not a guarantee of byte-identical jar restoration or an independent provider audit. Older review entries describing an unconditional Paper 1.21.8 reinstall are historical; R17 supersedes that behavior for recorded same-template selections. ## Reinstall Port-Integrity Review (2026-11-19) Reviewed the current reinstall scene/controller and traced the full controlling flow: navigation, permission refresh, session/server action tokens, access/ACL, suspension, password/TOTP step-up, both panel rebuild callers, daemon bearer and signed-envelope/nonce checks, compatibility retries, storage locks, destructive reset, installer/scaffold/download, metadata/disk/backups/quota, container startup and EULA, operation claims, heartbeat/recovery and competing operations. Earlier complete-flow reviews below are historical evidence, not new findings from this pass. The scene was not redesigned, and harmless presentation details were left alone. ### New Reproduced Findings | ID | Severity / Impact | Evidence and Repair | | --- | --- | --- | | R14 | Medium, allocation and rebuild integrity | The user reinstall route skipped allocation checks for missing/nonpositive stored ports and accepted partial numeric strings via `parseInt`. A real extracted route test returned 200 and called the daemon despite a missing port and exhausted allocation pool. Both rebuild callers now use `resolveReinstallHostPort` in [utils/server-reinstall.js](utils/server-reinstall.js), reusing the existing strict parser and allocator. Every request carries a checked numeric port, exhausted pools refuse before the wipe, and the panel commits exactly the sent port. | | R15 | Medium, legacy-node port desynchronization | The real unknown-field retry helper removed `hostPort` after a legacy daemon rejected it, then retried successfully without the checked allocation. The panel could record the rebound port while the node used its stored/default port. The existing required-field set now lives in [utils/daemon-protocol.js](utils/daemon-protocol.js) and includes `hostPort`. Both callers refuse that incompatibility without a second destructive attempt; optional-field retry remains covered and unchanged. | | R16 | Medium, concurrent rebuild failure | Two different servers needing a rebound port could select the same free allocation and both reach the daemon before either panel commit. Deterministic real-route barriers reproduced that overlap. Both rebuild callers use one `withReinstallNodePortLock` through the shared [utils/keyed-async-lock.js](utils/keyed-async-lock.js) mutex, retaining the existing node-ports -> templates-write -> servers-index lock order. A fresh node row is loaded under the lock; competing reinstall requests return 409 immediately rather than queueing a later wipe. Lookup/operation failures release the lock, and claims still release through their existing finally paths. | All three are fixed in the working tree. R14 requires affected legacy/stored port data, R15 an older or incompatible daemon, and R16 overlapping authorized port rebindings. No new reinstall-scene XSS, CSRF, unauthenticated wipe or host escape was demonstrated. Existing auth, ACL, suspension, step-up, signed-envelope and storage policies were preserved. ### Verification and Limits - Final `npm test`: 4,236 total, 4,227 passed, 9 skipped, zero failures. - Full `go test .`: passed using cached Go 1.26.9 with `GOTOOLCHAIN=local`. - Final focused source/behavior set: 202 passed; reinstall/shared-lock set: 58 passed. The earlier authorization/cleanup integration set passed 277. - JavaScript syntax, editor diagnostics and scoped whitespace checks passed. The async-handler scanner still reports zero unguarded awaits. An initial full Node run exposed an exact import source pin after the protocol extraction; it was updated without weakening its shared-implementation assertion, and the final full rerun passed. The node-port mutex is process-local, matching the current one-worker deployment configuration. It is not a distributed reservation or an all-worker guarantee; multiple panel workers and external port consumers remain outside this fix's exclusion guarantee. A rebuild holds the existing node-port lock until its request and index commit settle, so other operations using that key must wait; competing reinstall admission is deliberately fail-fast. No live reinstall, service launch/reload, deployment, production account or backing-service configuration change was performed. Ship the changed panel caller with its reinstall, protocol and keyed-lock modules together. The daemon was reviewed and tested, not modified in this pass. Live Docker/providers, TLS/proxy timeouts, production SQL/Redis behavior and mixed-worker rollout were not tested. Post-wipe failures still have no automatic data rollback; an uncertain result must be inspected before retrying. Stock Minecraft's Paper 1.21.8 choice and container-mediated hard-filesystem-quota limits remain as documented below. This is a scoped code and regression review, not proof of zero vulnerabilities. ## Reinstall Complete-Flow Follow-Up (2026-11-19) Scope: the reinstall scene in [views/bot.ejs](views/bot.ejs), its complete controller and request helpers, both panel rebuild callers, the daemon rebuild and the controlling authorization, storage, runtime and recovery paths. Earlier reinstall repairs below remain present and are not counted as new findings. No production server, account, backing-service configuration or worker was changed. ### New Confirmed Fixes | ID | Severity / Impact | Evidence and Repair | | --- | --- | --- | | R09 | Medium, network policy | Minecraft rebuild copied ports but dropped `portProtocols`, turning TCP-only and UDP-only allocations into both protocols. The real Minecraft runtime-rebuild fixture reproduced the added bindings without a download. [reinstall.go](reinstall.go) now retains the validated protocol map. | | R10 | Medium, unintended exposure | Changing templates correctly discarded old execution settings, but also dropped runtime-only private bind policy. The real daemon handler rebuilt a loopback-only service on `0.0.0.0`. Reinstall retains the effective interface through `serverHostBindIP` in [server_policy.go](server_policy.go), also used by Docker binding construction. Precedence controls cover top-level aliases and private overrides of wildcard settings; old commands/environment still stay excluded. | | R11 | Medium, destructive-target integrity | Both panel callers retained template/node/port/runtime snapshots across asynchronous step-up. A completed template change or transfer during that wait allowed a wipe using the old target, then a commit against the current row. Both real extracted handlers reproduced HTTP 200 with that interleaving. One post-claim `validateReinstallTarget` in [utils/server-reinstall.js](utils/server-reinstall.js) now compares a fresh canonical row, including row ID, runtime, ACL and allocation. Changed targets return 409 before any node call; unavailable reads fail closed and release the claim. Status/display-only changes remain allowed. | | R12 | Medium, operation exclusion | An orphan sweep's age-gated SELECT was followed by an UPDATE that checked only the marker. A fresh reinstall acquired after the orphan snapshot could be cleared by that stale sweep. The deterministic claim/recovery regression reproduced it. [utils/server-op-guard.js](utils/server-op-guard.js) now repeats the age condition atomically in the UPDATE and refuses unsafe recovery if `updated_at` cannot be read. Normal orphans and live-owner/outage controls remain covered. | | R13 | Medium, functional rebuild failure | Managed legacy runtimes with missing image/tag metadata wiped files, then attempted to pull literal `:`. The real daemon handler reproduced this for Python, Node.js and Discord-bot. `managedRuntimeImage` shares the existing built-in defaults between startup and [reinstall.go](reinstall.go), resolving and validating the effective image before deletion and persisting it for later starts. Explicit image/tag configuration is retained. | All five are fixed in the working tree. R09/R10 require affected saved network policy, R11/R12 require concurrent operations, and R13 requires missing managed image metadata. Reinstall still requires authorized access, `server_reinstall` permission or admin authority, one-time session/server proof and step-up; direct daemon requests require bearer authentication plus the panel signature. No reinstall-scene XSS, CSRF, unauthenticated wipe or host escape was demonstrated. Harmless presentation issues were not promoted to findings or redesigned. ### Coverage and Verification Read the complete reinstall markup/controller and its navigation, close/reopen, permission refresh, one-time token and error/success paths; panel permission mint/verification, access/ACL, suspension, account/session budgets and destructive step-up; both complete rebuild callers, canonical row mapping/commit, signed request and compatibility retry, port selection, shared JSON transport, claim, heartbeat, recovery and guarded status writes; the complete daemon handler and helpers, body/bearer/HMAC/nonce enforcement, effective runtime merge/preflight, container removal, installer/scaffold/download, metadata/disk/backups/quota, container starts and EULA handling. Followed competing backup/restore/delete, transfer/import/export, runtime seed, power, resource/EULA and file-writer paths where they interact with reinstall. This does not claim an independent audit of every sibling feature or every transitive dependency. Final full gates: `npm test` passed, 4,225 total / 4,216 passed / 9 skipped / zero failures; full daemon `go test .` passed using cached Go 1.26.9 with `GOTOOLCHAIN=local`. The focused panel/controller/ownership set passed 89/89; the final daemon reinstall/binding/EULA slice passed. JS/EJS syntax, editor diagnostics, focused Go formatting, tracked/untracked whitespace and the session-baseline implementation diff were checked. The async-handler scanner reports zero unguarded awaits; its required outer cleanup catch was preserved. An intermediate full Node run hit an unchanged asset-download temp-cleanup assertion; that file passed 8/8 in isolation and the unchanged full rerun passed. No unrelated fix was made to that feature. ### Delivery and Limits Ship the panel caller and updated shared reinstall/operation modules together, rebuild the daemon with [reinstall.go](reinstall.go) and [server_policy.go](server_policy.go), then reload all panel workers. No deployment, service launch or reload was performed. Existing worktree edits were preserved. Legacy schemas lacking `servers.updated_at` now keep uncertain reinstall markers instead of clearing them automatically; operator recovery requires first confirming the daemon operation is no longer active. This is not a guarantee of zero vulnerabilities. Live Docker/installer/provider, TLS/proxy timeout, production SQL/Redis scheduling/persistence and mixed-worker rollout were not exercised. Failures after the wipe remain non-transactional and do not restore deleted data automatically. Stock Minecraft still selects Paper 1.21.8; that existing version contract was not silently changed. Jar downloads have the existing quota checks, but container-mediated writes do not gain a hard filesystem quota from this patch. Inspect an uncertain outcome before retrying. ## Reinstall Deep Review Continuation (2026-11-18) Scope: the entire reinstall feature behind the reinstall scene, not the unrelated scenes in [views/bot.ejs](views/bot.ejs) or a repeated login audit. Historical repairs below were preserved and are not new findings. Evidence uses the real daemon handlers/shared helpers, extracted panel handlers, synthetic credentials, deterministic concurrency barriers and temporary storage with stubbed Docker. No production reinstall or service reload was performed. ### New Confirmed Findings | ID | Severity / Impact | Reproduction and Fix | | --- | --- | --- | | R01 | Medium, unintended network exposure and lost runtime policy | A server saved with a loopback bind rebuilt with `0.0.0.0`; explicit read-only root policy disappeared. Preserve top-level and same-template runtime policy in [reinstall.go](reinstall.go). Real handler tests inspect the resulting Docker port bindings. | | R02 | Medium, concurrent operation ownership | mysql2 enables FOUND_ROWS, contrary to the old guard's assumption; simultaneous reinstall claims both won. [utils/server-op-guard.js](utils/server-op-guard.js) now atomically excludes every guarded marker for non-idempotent operations. Tests cover matched- and changed-row semantics; delete remains idempotent. | | R03 | Medium, metadata/consent races | Resource updates and EULA acceptance returned 200 and mutated state while reinstall held its daemon lock. Both original handlers now live once in [server_policy.go](server_policy.go) and take the existing operation lock; EULA writes also take the storage lock. Conflict tests prove no metadata or consent mutation. | | R04 | Medium, quota and failure-state integrity | Reset deleted external metadata, making the saved storage quota disappear before rebuilding; the jar download used the unrestricted downloader. Retain authoritative metadata until replacement commit and apply existing server quota plus owning-disk allowance in [reinstall.go](reinstall.go). Boundary tests count retained backups and verify aborted downloads leave no committed jar or temporary file. | | R05 | Medium, destructive preflight/runtime correctness | Invalid inherited startup and effective Minecraft runtime settings could reach the wipe. Changing templates also merged the old command/startup/environment into the new runtime. Validate inherited effective configuration before reset, retain runtime only for the same template or unidentified legacy metadata, and use template-appropriate start defaults. These are configuration/data-integrity defects, not demonstrated host escapes. | | R06 | Medium, installer output corruption | The custom scaffold truncated an installer-produced entrypoint; missing start metadata became a literal `` file. Use the existing non-clobbering generated-file writer and typed start metadata in [reinstall.go](reinstall.go). Tests preserve installed bytes and reject fabricated entrypoints. | | R07 | Low, reliable completion/retry behavior | The controller reported success for `{}` or `{ok:false}` behind HTTP 200, and advised blindly retrying after a lost connection. [public/js/server-reinstall.js](public/js/server-reinstall.js) requires explicit success and warns that the destructive result may be unknown. The controller URL is versioned to invalidate immutable caching. | | R08 | Low, legacy-node compatibility | If secret rotation was unavailable, the signing retry state stayed null and skipped the documented legacy fallback. One injected retry implementation in [utils/server-reinstall.js](utils/server-reinstall.js) serves both panel callers, retries only signature rejections, and stops on transport/execution/consent results. | All R01-R08 are fixed in the working tree. The threat prerequisites remain important: reinstall requires existing access/permission, session-bound one-use action proof and destructive step-up; direct daemon reinstalls require bearer authentication and a panel-admin signature. R01 matters for previously private services, R02/R03 require concurrent operations, R04 requires bounded storage or a rebuild failure, and R05/R06 require affected stored/template configuration. No arbitrary unauthenticated wipe, scene XSS, CSRF bypass or host escape was demonstrated. Safe authorization controls are not listed as findings. ### Coverage Ledger - Read the reinstall markup and related navigation/close/inline-page behavior, the complete reinstall controller, permission-token refresh and retry helper, and permission mint/verification, access/ACL, suspension, limiter and step-up controlling paths. Unrelated UI scenes were not audited. - Read both complete panel rebuild callers, signing/rotation/fallback and unknown-field retry, port selection, canonical-row commit, audit/cleanup, operation claims, heartbeat/recovery and guarded status writers. Transport error/abort/body-cap/deadline handling was followed through the shared client. - Read the complete daemon reinstall handler and extracted helpers, request routing/bearer/HMAC/nonce enforcement, runtime reconstruction, destructive reset, template installer/preflight, scaffold/download, external metadata, runtime container starts and EULA gates. Traced owning-disk and backup routing and the quota/storage lock contract. - Followed competing power/backup/restore/runtime seed/import/export/resource/ EULA/file-write paths where they interact with reinstall. This is interaction coverage, not a full independent audit of every sibling feature. - Tests cover rejected/expired/replayed authorization, password/2FA and permission loss, pending UI admission, text-only errors, explicit completion, signature fallback and stop conditions, concurrent claims, storage/policy exclusions, preflight preservation, failed metadata/index commit, entrypoint preservation, quota-boundary cleanup, backup preservation and a real secondary-disk rebuild. ### Verification and Limits The final required full gates passed: `npm test` reported 4,220 total, 4,211 passed, 9 skipped and zero failures; full daemon `go test .` passed using temporary official Go 1.26.9. The final controller/route set passed 19/19; the daemon reinstall/EULA slice and stock Minecraft image compatibility controls passed. The earlier panel caller/guard set passed 83 tests. JavaScript and EJS syntax, editor diagnostics, focused Go formatting and session-only whitespace checks passed. A preceding full Node run hit an unrelated one-millisecond preauth-session assertion; its unchanged isolated rerun passed 7/7 and the unchanged full rerun passed. Existing unrelated template whitespace was not reformatted; exact edit-checkpoint comparison confirmed its only change was the reinstall-controller cache URL. Deployment still requires all updated panel modules, a daemon rebuild including [server_policy.go](server_policy.go), and an all-worker panel reload. None was performed. Go was downloaded only into `/tmp/adpanel-reinstall-review`, without changing system PATH or project dependencies. This is not proof of zero vulnerabilities. Live Docker/providers, TLS/proxy timeouts, production InnoDB/Redis scheduling/persistence and mixed-worker rollout were not tested. Reinstall intentionally destroys the old tree and still has no automatic rollback after a later failure; uncertain outcomes must be inspected before retry. Stock Minecraft reinstall still selects Paper 1.21.8. Installer shell remains trusted template execution inside a constrained container; this patch bounds the jar download and serializes daemon writes, but does not add a hard filesystem quota for container-mediated installer/runtime writes or make all storage operations transactional. Those infrastructure/engine protections are not certified by the synthetic tests. ## Authentication and Reinstall Completion Follow-Up (2026-11-18) This follow-up includes authentication because the latest user request explicitly asked for the full login flow as well as the reinstall scene. The narrower reinstall-only review below is a historical pass, not the scope of this one. Existing worktree repairs were preserved and were not counted as new findings. No application entry point, production account, live reinstall, deployment or worker reload was used for reproduction. Confirmed new findings, fixed in the worktree: 1. **Medium, security: remembered-login completion could retain stale authority after a credential reset during session persistence.** Restore bound `req.currentUser` before awaiting its session save. A reset inside that save could miss the not-yet-persisted SID; the downstream account-binding check then reused the cached pre-reset row and accepted the same protected request. The bounded real-handler matrix demonstrates this with the actual auth functions and the protected security-settings route. This requires a valid remembered credential and the concurrent reset/save interleaving; it is not an arbitrary password/MFA bypass or durable promotion onto the new generation. Completion now delegates to [utils/remember-login-completion.js](utils/remember-login-completion.js), checks SID revocation after the save, freshly checks identity, suspension, MFA-seal state, account generation and the proved fingerprint, then updates request authority and records success. Stale/error completion uses the existing teardown, clearing current-request authority and revoking the rotated credential and SID. Normal and legacy restores still work. The new check adds one bounded account lookup and a fail-closed SID check per successful restore. 2. **Medium, correctness: the panel could report reinstall success without committing its rebuilt-server record.** `saveServersIndex` can return false after rollback, but the user reinstall route ignored it. Alias requests could also rebuild the resolved canonical server yet skip its row update because the post-rebuild lookup used the URL alias. A rebound port could therefore remain incorrectly recorded while the scene displayed success. Both panel callers now use `commitCompletedReinstall` in [utils/server-reinstall.js](utils/server-reinstall.js), under the existing index/template locks. The helper commits the canonical row, checks persistence and reports explicit partial completion on a failed/missing record, warning against blindly retrying the destructive operation. Success is not recorded after a failed panel commit. This does not roll back an already-completed wipe. 3. **Medium, correctness: the daemon ignored rebuilt metadata save errors.** A temporary non-file metadata target made the real handler return HTTP 200 even though its authoritative runtime/port/disk metadata did not persist. Both Minecraft and non-Minecraft branches now use `prepareReinstallRuntime` in [reinstall.go](reinstall.go), requiring the save before image preparation or container start. Tests cover failed persistence and ordinary metadata/disk persistence with bounded temporary storage and stubbed Docker. These are failures after an authorized wipe; existing data is not automatically restored. 4. **Low, reliability: claim-release rejection could attempt a second response.** The user reinstall's `finally` could reject after a success/error response, sending another 500 from the outer catch and rejecting the Express 4 handler. The real-handler regression reproduced the double settlement. Both panel callers now delegate to the same guarded `releaseReinstallClaim` helper. Cleanup errors remain logged; the existing orphan-operation recovery is still responsible for a DB marker whose release could not commit. Coverage is the complete controlling bodies and traced callers, not keyword hits alone: reinstall markup/controller/navigation and token fetch, permission mint and verification, access/ACL, rate/step-up checks, both panel rebuild callers, signed node auth/retry, daemon validation/reset/storage locks, runtime reconstruction and completion; login markup and submit/captcha controllers, login CSRF/bot-proof and browser checks, password lookup/rehash/proof checks, TOTP/recovery, captcha provider verification and pending-login completion, session bind/rebind, cookie/proxy policy, both session backends and revocation guard, remembered-token parsing/registry/rotation/revocation/completion, HTTP account/admin gates, socket handshake/liveness, and logout cleanup. Existing credential-commit services and recovery/MFA route bodies were read too. No reinstall-scene XSS, CSRF or unauthorized-reinstall bypass was demonstrated. The escaped EJS names, literal error rendering, one-time session/server tokens, step-up, suspension refusal and operation/backup exclusion remain intact. The stock Minecraft reinstall's fixed Paper 1.21.8 choice was observed but not changed: preserving a selected fork/version was not established as its contract and this review did not exercise live provider compatibility. Cosmetic issues and speculative hardening were not promoted to findings. Verification: full `npm test` passed (4,216 total, 4,207 passed, 9 skipped, zero failures); full `go test .` passed with cached Go 1.26.9 and `GOTOOLCHAIN=local`. The focused reinstall/caller/ownership set passed 106 tests. The final authority/audit controls, syntax/editor diagnostics, scoped Go formatting and tracked/untracked whitespace checks passed. The unchanged async-handler scanner reports zero unguarded awaits. Results are also recorded in [SECURITY-REPAIR-BRIEF.md](SECURITY-REPAIR-BRIEF.md). Existing source pins were moved with extracted code without removing their audit/timeout/ownership invariants. Local fixtures do not certify live TLS/proxy settings, Docker, provider downloads, database scheduling, Redis persistence or cross-worker rollout. Skipped integrations are not verification of those requirements. Delivery: ship the new completion module and changed reinstall helper with the panel callers, rebuild/release the daemon with the changed Go module, and reload all panel workers together. No update allowlist or operator configuration was changed, and no deployment/reload occurred. This is a scoped review, not a guarantee that no vulnerability exists or a line-by-line audit of every feature and dependency in the repository. ## Reinstall Scene Review (2026-11-18) Scope: the reinstall scene in [views/bot.ejs](views/bot.ejs), its full browser controller, permission/action-token/step-up gates, both panel callers of the same daemon reinstall, signing/retry behavior, operation ownership, and the daemon's reset, runtime reconstruction, backup separation and completion paths. The user clarified that authentication generally is out of scope; no login or authentication implementation was changed by this pass. Confirmed consequential bugs, all repaired in the worktree: - Invalid Java, workdir, runtime/startup or installer configuration could reject after removing the old container and files. Real-handler regressions demonstrated data deletion on rejected requests. Configuration and image policy checks now precede destructive reset in [reinstall.go](reinstall.go); ten rejection controls retain the seeded files and metadata. - Docker removal failures were ignored, allowing a wipe while the old container remained alive. Reinstall now delegates to the existing checked `brutalRemoveContainer` operation and preserves files when removal cannot be confirmed. The stubborn-container and missing-container controls pass. - Reinstall held the server-operation lock but not the storage-writer lock, so an upload or editor save could interleave with the wipe and rebuild. Reinstall now holds the same `lockUploadScope` used by these writers until completion, using the existing server-operation-before-storage lock order. - A completed Minecraft rebuild waiting for EULA consent was returned as a generic panel failure, skipping the index commit. Both panel callers now use [utils/server-reinstall.js](utils/server-reinstall.js) to recognize that exact completion state. Consent still gates starting Minecraft; other conflicts and failures remain refused. The real template-change handler regression verifies template and rebound-port persistence. - Closing/reopening the scene cleared its in-flight guard, admitting a second destructive request. The controller now lives in [public/js/server-reinstall.js](public/js/server-reinstall.js); only request completion releases admission. The nonce-bearing script loads before the caller, and the caller's cache suffix changes. Credential retry, cancellation, permission-loss and literal-error-rendering controls pass. Security gates were retained: access and `server_reinstall` permission, one-time session/server-bound action tokens, bounded verification attempts, password/TOTP step-up, suspension refusal, signed daemon authorization and operation/backup exclusion. No new unauthorized-reinstall or template-scene XSS bypass was demonstrated. This is not a guarantee of no vulnerabilities. Verification: `npm test` passed (4,209 tests, 4,200 passed, 9 skipped, zero failures); `go test .` passed using cached Go 1.26.9 with `GOTOOLCHAIN=local`. Syntax and editor checks passed. Existing unrelated whitespace in [public/js/bot.js](public/js/bot.js) and [views/bot.ejs](views/bot.ejs) was left unchanged. Local tests stub Docker and provider exchanges; live Docker, Minecraft downloads, TLS/proxy configuration and cross-worker deployment were not exercised. Reinstall remains intentionally destructive: network, installer or disk failures after an admitted wipe do not provide automatic rollback. Delivery: include the new Go module in the daemon build/release, and both JS modules with their callers. The panel helper uses the updater-supported `utils` directory; no updater trust allowlist was widened. No production reinstall, worker reload, service launch, deployment or account change occurred. ## Outbound deadline and cancellation continuation (2026-11-18) This pass followed the first investigation in [SECURITY-REPAIR-BRIEF.md](SECURITY-REPAIR-BRIEF.md). The findings below are NEW availability and lifecycle defects, not repeats of the earlier response listener, upload-failure cleanup, or authentication repairs. None establishes an authentication bypass or a way around the public-address SSRF policy. The existing modified worktree was preserved; no panel launch, deployment, worker reload, operator configuration change, or production account action was performed. | ID | Severity | Confirmed Finding | Status | | --- | --- | --- | --- | | O01 | Medium, availability | Transfer dials remove request error/timeout listeners at headers; failed imports can leave exports running | Fixed | | O02 | Medium, availability | Remote fetch deadlines omit DNS, reset per redirect, and allow slow-drip bodies; late request failures do not reach handed-off streams | Fixed | | O03 | Medium, availability | Both upload relays remain pending when their source closes without end, including a source already failed before handoff | Fixed | ### O01: Transfer Lifetime Includes the Body Entry point: the admin/action-token/step-up guarded `POST /api/settings/servers/:name/transfer` in [index.js](index.js). Prerequisites: an authorized transfer between configured nodes, with a transport failure or misbehaving/compromised source or destination. This is not a tenant-callable transfer authorization bypass. The original `httpStreamRequest` removed its only request `error` listener when headers arrived. The real extracted function's regression emitted a request error after headers and observed an uncaught EventEmitter error. Timeouts no longer reached the body consumer either. Separately, the real transfer pump rejected a destination 507 but left both the source response and source request open. A source close without end could keep a transfer pending, retaining its operation status/heartbeat/suspension lock until a later transport timeout instead of reaching the existing rollback/finally. The streaming dial now lives in [services/node-http.js](services/node-http.js) and retains request/response error, aborted, and premature-close handling through body completion. Its existing timeout budgets are hard deadlines, including socket setup, body pumping, and the response body. The pump now lives in [services/server-transfer-stream.js](services/server-transfer-stream.js). Every failed import cancels both ends, source failure independently rejects the awaiting transfer, and early success before export EOF is refused. The synchronous destination-request capture, disk selection, progress, non-JSON response compatibility, and HTTP 200 `{ok:false}` refusal remain. The route's existing rollback, heartbeat cleanup, and lock release are unchanged. Tests retain success-byte and recovery controls. ### O02: One Deadline for the Remote Exchange Reachable paths include authorized `/upload-url` and store-version apply, admin-created deferred imports, and configured remote assets/releases. A caller able to start one of these operations can point it at an allowed public endpoint, or an upstream can misbehave independently. The SSRF guard and byte cap did not bound elapsed time: URL/DNS validation preceded the socket timer, every redirect restarted it, and incoming bytes reset the inactivity timeout. Discarded redirect/error bodies were drained without a total bound. After streaming headers, request errors/timeouts only rejected the already-resolved getter promise, leaving its consumer waiting. Failing pre-repair checks demonstrated a pending controlled DNS lookup, a post-header request failure leaving the stream open, and a standalone URL preflight remaining pending past the test backstop. The shared JSON client's external-URL branch also started its hard timer after validation. Buffered and streaming remote getters now share one engine in [utils/remote-http.js](utils/remote-http.js). A single deadline starts before validation and spans all redirects and body consumption, including a paused consumer. Expired validation cannot create a late dial. Request failures reach the returned stream, premature close/abort fails it, and unused responses are destroyed rather than drained. Byte caps, validated-IP pinning, Host/SNI shaping, redirect count, and release HTTPS-only policy are retained. The shared JSON client starts its existing deadline before external validation and preserves its panel/relay failure envelopes. Standalone validation in [utils/remote-url-guard.js](utils/remote-url-guard.js) also bounds its DNS wait so a preflight before the getter cannot hold a store operation claim indefinitely. Its default is the positive `REMOTE_FETCH_TIMEOUT_MS` value or 20000 ms; a positive per-call `timeoutMs` overrides it. Public/private address, credential, protocol, and port policy are unchanged. Late DNS resolution or rejection cannot grant an accepted URL or become an unhandled rejection. Native `dns.lookup`/getaddrinfo is not cancellable here: a pending system resolver can continue after the caller has failed; this repair prevents late dials, not resolver exhaustion. Deterministic regressions cover DNS, redirects, slow-drip bodies, errors, abort/close without end, caps, paused consumers, timer release and success. Bounded native loopback HTTP checks verify success bytes, total-deadline failure despite incoming bytes, and peer-socket close after cancellation. The real getter-to-store consumer regression checks that failure removes the partial panel temp file, performs no upload, and frees the download slot. ### O03: A Source Close Is an Upload Failure The authenticated direct and node-relay uploaders, and remote streams fed into the panel uploader, listened for source `error` and `end` but not a bare close. Regressions against both actual extracted uploaders demonstrated an unresolved upload after source destruction. An already-failed remote stream at handoff had the same result. Depending on downstream progress, this retained the node request until its long inactivity timeout. Both uploaders now use `onPrematureClose` from the existing shared [utils/stream-lifecycle.js](utils/stream-lifecycle.js), reporting the existing masked `upload_stream_error` outcome and releasing the node request. The guard also checks an already-destroyed source. Normal EOF, success responses, multipart content, byte limits, and per-surface response contracts are unchanged. No second upload implementation or quota checker was introduced. ### Coverage and Verification Complete controlling functions read/traced: both remote getters, the pinned agent/SNI helpers, the shared remote URL guard, shared `httpRequestJson`, `nodes.js` `callNodeApiOnce`, both upload relays, `httpStreamRequest`, the transfer pump and its complete route/job failure choreography, and `applyRemoteAssetToServer` including its download and upload consumers. The daemon multipart upload and its scoped write/cleanup were inspected to confirm the receiving cancellation contract; this was not a new filesystem or quota-concurrency audit. The distinct `callNodeApiOnce` has a hard timer covering its connect-time lookup already and was not rewritten. - Focused outbound set: 211 tests, 211 passed, zero skipped/failures. - Full `npm test`: 4204 tests, 4195 passed, 9 skipped, zero failures. - `GOTOOLCHAIN=local` with cached Go 1.26.9: `go test .` passed. No Go edits. - Changed JavaScript syntax and editor diagnostics passed. Whitespace and tracked/untracked diff review cover the touched files. Skipped integration checks are not passing integration evidence. No real account, live node transfer, production backing-service operation, or load test was used to reproduce these findings. Synthetic races do not certify production database scheduling, deployed worker versions, or live TLS. Compatibility: timeout values are unchanged but now bound total elapsed time; a legitimate remote download/transfer that used to exceed its configured budget through steady progress can now fail. Existing upload idle-time policy, response envelopes, permissions and transport trust are unchanged. Ship both new modules with all changed callers and reload all panel workers to activate the repairs. No reload was performed. Release/update delivery completeness, including delivery of service modules, remains the separate priority-4 investigation, not a certified deployment path. Remaining scope: full cancellation of store uploads after refused setup, direct-upload total-duration policy, and the distinct `callNodeApiOnce` failure teardown still need deeper review. Authentication proof lifetimes, non-Accounts deferred step-up commits, update completeness/metadata, filesystem identity/quota races, and pre-auth parsing remain open as listed in the brief. This pass is not an entire-repository audit and does not certify live proxy/TLS, database transport, Redis persistence or worker configuration. ## Expanded middleware and dependency review (2026-11-18) The login review was expanded into the actual consumers of all remaining production dependency advisories, shared node HTTP clients, remote URL and DNS guards, database connection probes, database proxy response decoding, upload relay cleanup, and panel/node update ZIP processing. This was not a line-by-line audit of every application feature or a live penetration test of the deployment. - **MySQL auth-plugin downgrade:** the installed mysql2 3.16.0 accepted a server-requested switch to `mysql_clear_password` on plaintext TCP. A real handshake against an isolated loopback endpoint disclosed a synthetic test password. A rogue database endpoint or a network attacker on an unencrypted database connection could therefore recover the database credential; the normal loopback deployment is not evidence of a remote exploit. mysql2 is now pinned to 3.23.1, covering the main pool and the settings connection probes without parallel plugin implementations. The real-handshake regression now refuses the downgrade, and its normal native-password authentication control still passes. The upgrade also fixes the compressed-protocol inflate advisory; `compress: true` was not enabled in the reviewed connection options. GHSA-3f6p-5ww8-9rcr and GHSA-rgwj-5xj2-c3m3 no longer appear in the dependency audit. - **Database proxy decoded-body budget:** phpMyAdmin/pgAdmin text rewriting capped compressed input but inflated gzip/deflate without an output limit. A hostile or compromised backend response could exceed the intended 5 MiB budget and allocate excessive memory. Oversized plain text was also silently truncated, and decode failures were forwarded as text. Both wire bytes and decompressed output are now capped, with decode failures and over-budget responses routed through the existing single-settle teardown. Valid compressed HTML retains rewriting and heartbeat injection; HEAD responses remain bodyless. Regressions use bounded synthetic responses, not production backends. - **Node response refusal listeners:** both the shared client in `services/node-http.js` and the distinct error-string client in `nodes.js` rejected an oversized Content-Length before attaching response error and aborted listeners. Those listeners now attach before every early return. Synthetic HTTP/HTTPS error/abort interleavings verify the refusal cannot leave an unhandled response event or replace the size-limit result. The existing 16 MiB caps and per-client response contracts are unchanged. - **Failed upload and canceled download cleanup:** an early node rejection, request error or timeout left the unfinished upload source open. Canceling an IP-pinned remote download's sink likewise left its upstream response and request alive, including backpressured exchanges. The cleanup lives once in `utils/stream-lifecycle.js`, used by both upload streamers and the remote-download sink. HTTP 200 failure bodies follow the same failure cleanup as their callers; successful uploads and fully consumed downloads are not canceled. Source streams and sockets are released without changing response envelopes or exception-detail masking. - **Node-update ZIP allocation:** source entries were inflated by adm-zip before the panel checked its 8 MiB accepted-file limit. Many accepted entries could also accumulate an encoded payload the daemon's 32-file and 20 MiB request gates would refuse only after the panel allocated it. The decoder now lives in `utils/node-update-archive.js` and reuses the existing capped-inflate helper. Declared sizes and encoded payload budgets are checked before inflation, actual sizes are checked before base64 encoding, and the existing allowed-file policy is retained. This requires an attacker-influenced or compromised release artifact; it is not an unauthenticated archive-upload path. The HTTPS and integrity-pin policy remains unchanged. Verification: the full Node suite passed after these repairs: 4,179 passed, 9 skipped, no failures. Regression checks include normal workflows as well as refused handshakes, decompression budgets, response errors and stream cancellation. No production accounts, database endpoints, services or deployment options were changed. Go is not installed in this environment, so `go test .` could not run; no Go sources changed. All panel workers must reload to use the repaired modules and driver. Six advisory-bearing packages remain: brace-expansion, follow-redirects, ip-address, proxy-addr, qs and tar. Their reported severities alone are not confirmed application vulnerabilities. The reviewed EJS server renderer does not invoke its jake/filelist CLI chain; no application npm-tar consumer was found; follow-redirects is in PM2 tooling rather than the panel's guarded HTTP clients. The reviewed qs parser uses neither comma parsing nor a parse-to-stringify sink, and the limiter calls ip-address only after native IPv6 validation; SSRF guards do not use that library. proxy-addr's mapped subnet advisory requires a permissive IPv6 trust configuration absent from the default loopback policy. These are scoped reachability assessments, not a certification of all tooling or future configuration changes. The dependency tree is not advisory-clean, and live TLS/proxy, database transport and cross-worker behavior remain deployment verification requirements. ## Login-flow review fixes (2026-11-18) - Session writes now run through `utils/session-store-guard.js`, the one shared guard for both session backends. Revocation is checked before a write and again before its completion callback: a save admitted before logout can no longer recreate the record after logout's destroy. Existing callback settlement and skipped-write signals are preserved. In file mode, hashed-SID markers are atomically persisted with mode 0600 beneath the private `.sessions-revoked/` directory before revocation reports success. They last 370 days and survive process restart and local-cache eviction; malformed or unreadable markers never grant authority. Failed writes enter the existing tombstone retry queue. File mode still requires one worker because consumed action-token markers remain process-local. - The startup legacy TOTP sealing pass now lives in `services/totp-secret-migration.js`. Its update compares the exact original seed bytes with `BINARY secret = BINARY ?`, so a concurrent reset, rotation, or another sealing worker wins without the migration restoring the old authenticator. A CAS loser is not counted as a migrated row. Sealing an unchanged factor does not alter the account generation or encryption format. - `utils/auth-redis-deadline.js` bounds the shared authentication Redis client before any store or limiter consumes it. Generated commands, explicit commands, scan iterators, and transaction execution receive total deadlines, including initial session loads and registry freshness reads. The default is 5000 ms; `AUTH_REDIS_COMMAND_TIMEOUT_MS` clamps to 1000..15000 ms. A timeout rejects the operation, drains late replies, and resets/reconnects the stalled client once; explicit shutdown never triggers reconnect. The native socket timeout also bounds setup handshakes; a heartbeat at half that interval keeps healthy idle connections open instead of reconnecting them. Native command errors still reach their existing consumer-specific failure handling. A timeout is not proof that a write did not commit, so existing CAS, tombstone, and retry mechanisms remain authoritative. - The shared bcrypt loader and import validator now live together in `utils/bcrypt-rounds.js`. Valid `$2y$` hashes are normalized to the equivalent `$2b$` form only during comparison, fixing native-bcrypt login and CLI verification without rewriting stored hashes or remembered-login fingerprints. The panel and credential CLIs use that same loader; malformed hashes and invalid costs are refused by the shared import validator. - Delayed first writes of remembered-login registry entries could land after a different worker completed logout. Advancing the registry version did not prevent the minting worker from preserving its never-synced entry and writing it at the new version, making the already-issued cookie valid again. The shared scripts in `utils/remember-login-redis.js` now atomically mark the revoked identifier and lineage, and every guarded registry write checks both markers before publishing. Targeted deletes also mark the identifier in the same transaction. Markers last 370 days, beyond the 365-day credential lifetime; a refused delayed mint is discarded from the worker's registry and mint-provenance set. Normal rotation and unrelated fresh logins are unchanged. - Login bcrypt admissions waiting for a slot now expire after eight seconds. Previously the caller's response timeout abandoned only the promise: queued comparisons still started later, extending login starvation after a burst. Expiry removes only work that has not started. Running comparisons retain their slots until completion, and hand-off checks the deadline even when a timer callback is delayed. Existing concurrency and FIFO behavior is retained. - The optional Node response compressor ignored downstream backpressure and kept gzip/Brotli streams alive after a client disconnected. This pre-auth middleware affected login HTML and could retain native buffers or continue queueing output for slow clients. The inline implementation was extracted into `utils/response-compression.js`, using the maintained `compression` middleware pinned to 1.8.2 (the first release fixing premature-close cleanup, GHSA-vc2v-76pw-4v95). Gzip level 4 and the clamped Brotli quality are retained. SSE, HEAD, pre-encoded and no-transform responses are excluded, and Vary headers are preserved. Both lifecycle regressions failed against the old mounted middleware and pass after the repair. Real loopback HTTP checks verified gzip/Brotli round trips, streaming, exclusions, disconnect cleanup, and native-handle release. The post-repair Node suite passed: 4,165 passed, 9 skipped, no failures. Node compression remains off by default behind nginx; nginx compression and live TLS configuration were not changed or certified. Verification: the actual Redis scripts were exercised against an isolated temporary Redis instance, covering logout before and after the first write, revoked-lineage replacements, marker lifetime, and an unrelated-login control. The final Node test suite passed: 4,163 tests passed, 9 skipped, no failures. The new repair regressions cover late callback/promise session writes, durable file-mode markers after restart, corruption and retry handling, legacy TOTP migration races, and native bcrypt import compatibility. Real node-redis and connect-redis clients were also exercised against a synthetic local RESP server to verify healthy operation and stalled session, registry, scan, and transaction deadlines, plus unresponsive reconnect handshakes and healthy idle heartbeats. JavaScript syntax and editor diagnostics were clean. No production accounts, services, credentials, or configuration were modified by these repairs. `go test .` was unavailable in the review environment because Go is not installed; no Go sources changed. Deployment: reload all panel workers together. Older workers do not check the new revocation markers. Keep Redis persistence and `maxmemory-policy noeviction` configured, as required for the existing session tombstones too. Keep `.sessions-revoked/` private and persistent when using file-mode sessions. This review does not certify the live TLS/proxy or database configuration. ## Authentication hardening (2026-11-17) - Self-service password, email and MFA commits now use the shared `services/account-credentials.js` service. The verified credential and `session_epoch` are pinned in the same SQL UPDATE that commits the new credential and generation. A concurrent change to a different credential therefore refuses the stale request before session rebinding or disclosure of new recovery codes. Administrator password overrides retain their existing ID-bound contract. - Both MFA setup paths record `pending2faAccountEpoch` when the existing credential authorizes setup. Confirmation must use that original generation, not the row's generation at confirmation time. An MFA setup started before this field existed must be generated again. Missing or malformed account generations fail closed; the existing `users.session_epoch` migration must have completed for self-service credential changes to succeed. - Password/email and MFA verification keep their 10-request per-session, 10-minute budgets and additionally enforce 30 requests per account per 10 minutes. The account tier is keyed by immutable account ID, with folded email fallback for legacy sessions, and each tier has its own shared Redis store and namespace. Remember-token rotation, new session IDs, network changes and email changes do not refill the account budget. These controls remain active when the optional global rate limiter is disabled. - `utils/session-middleware.js` gives express-session a request-local view of the panel's existing trusted transport resolver at creation, regeneration and cookie emission. Password login, CAPTCHA completion, remembered login and credential rebinding therefore preserve Secure session cookies through trusted TLS proxies even when Express's separate proxy setting does not recognize the proxy. The original request's security view, proxy allowlists, explicit cookie settings and plaintext deployment policy are unchanged. Regressions cover stale cross-credential commits, missing proof generations, normal enrollment and rotation, stable guessing budgets, and actual emitted Set-Cookie headers. Run `npm test` and `go test .`; live cross-worker database checks require explicitly configured disposable MySQL/Redis test services. ## H1 — console_write is in-container shell RCE (risk transparency) `console_write` on exec/shell-mode servers runs `docker exec sh -lc ` (`main.go`, `executeShellConsoleCommand`). That is intentional product behavior, so the fix is to make the grant decision honest instead of hiding it: - Permission relabeled from "Write to console" to **"Console commands (shell access)"** in `public/js/settings.js` and `public/js/settings.min.js`, with a red warning note rendered under the checkbox ("full in-container code execution: files, secrets, network"). - Granting `console_write` now triggers a `confirm()` dialog spelling out the risk before the ACL is saved. - Server-side description (`describeBotPermissionKey` in `index.js`) updated to the same wording. - New `.perm-note` / `.perm-item` wrap styles in `public/settings.css`. Container isolation audit (finding's verification ask): - `resolveStructuredBinds` (`main.go:6179`) drops any volume whose host path does not resolve under the server's own volume root (`ensureResolvedUnder`), so Docker socket / arbitrary host paths cannot be mounted through server metadata. Templates in `templates.json` only mount `{SERVER_DIR}`-style paths. `sanitizeCustomImageDefaultBinds` only remaps paths, never adds host mounts. - Not changed (documented decision): forcing stdin-mode templates / per-node egress network policy would alter behavior for existing exec-mode game servers; the panel's value prop includes real shells. Ops teams that want it can now make an informed grant decision, and network limits already exist per server (`networkInboundLimitMb` / `networkOutboundLimitMb` anti-abuse resource options). ## H2 — SSH terminal available to any authenticated user The sshterm service is a generic web SSH client dialing user-supplied targets from the panel host (pivot risk into internal networks / cloud metadata). Panel side (`index.js`): - `GET /api/ssh-terminal/session` and the `/ssh-terminal` index proxy now require `hasAgentAccess(req)` (admin or `agent_access` flag) in addition to authentication — 403 with `permission: "agent_access"` otherwise. - New `sshTerminalRateLimiter`: 10 requests/min per IP+account. - The websocket upgrade proxy (`attachSshTerminalUpgradeProxy`) now validates the HMAC token itself (`verifySshTerminalToken`, constant-time compare) before forwarding, so unauthenticated sockets never reach the sshterm process through the panel. Service side (`cmd/sshterm/main.go`): - Optional target allowlist via `SSH_TERMINAL_ALLOWED_HOSTS` (comma-separated exact hosts or `*.suffix` globs), enforced by `sshTargetAllowed()` before reachability probing (so denied targets can't be used as port scanners). - Cloud metadata endpoints (`169.254.169.254`, `169.254.169.253`, `fd00:ec2::254`, `metadata`, `metadata.internal`, `metadata.google.internal`) are always refused. - Documented in `.env.example`. ## H3 — cross-tenant dashboard leakage Audit of dashboard paths: `join`, `dashboard:watch`, `dashboard:subscribe` all filter through `canAccessBot` / the user's access set, and `_updateAccessSet` reaps rooms every 30s after revocation — server data does not leak across tenants. One aggregate did: `broadcastNodeUpdate` emitted the node-wide `serverCount` to per-server `dashboard:node:*` rooms, letting a tenant infer how many other servers share their node. Now only the admin room receives `serverCount`; per-server rooms get online/latency/updatedAt only (no client consumes `serverCount` from this event, so nothing breaks). ## M3 — phantom subdomain_* keys Investigated, no fix required: `subdomain_show` / `subdomain_add` are not phantom. `routes/subdomains.js` enforces both per server (`checkPerms` requires `user_access` + the ACL entry, admins bypass), and the ACL grant flow (`ALLOWED_PERM_KEYS` → `servers.acl`) feeds exactly that check. ## M4 — unlocked read-modify-write on the servers index `loadServersIndex()` → mutate → `saveServersIndex()` races could clobber concurrent admin operations (e.g. resurrect a just-removed ACL entry from a stale snapshot; `saveServersIndex` syncs the whole table including deletes). - Added `withServersIndexWriteLock(task)` — a serialized promise chain — and `loadServersIndexFresh()` (cache-bypassing read) in `index.js`. - All six load→mutate→save sites now run inside the lock with a fresh read: 1. `POST /api/settings/accounts/:email/grant-perms` 2. `DELETE /api/settings/accounts/:email` (ACL cleanup) 3. `POST /api/servers/:bot/template` (store template change) 4. `POST /api/settings/servers/:name/template` — additionally re-reads fresh *after* the up-to-1h node reinstall completes, since its original snapshot could be arbitrarily stale by then 5. `POST /api/servers/:name/reinstall` (post-reinstall entry cleanup) 6. `PATCH` resources update (`/api/settings/servers/:name/resources`) ## L1 — CSRF heuristic Kept the Origin/Referer/Sec-Fetch-Site heuristic (per-request tokens for all state-changing routes would be a larger migration; destructive endpoints already require HMAC action tokens with nonce replay protection). Added a startup warning whenever `CSRF_ALLOWED_HOSTS` is set, since each entry trusts that origin for every state-changing route. The sibling-subdomain trust is closed: `Sec-Fetch-Site: same-site` no longer bypasses the Origin/Referer host check (same-site covers sibling subdomains, and SameSite=Lax cookies still attach to same-site POSTs, so any sibling could previously forge credentialed requests). Only the browser-attested `same-origin` value bypasses it; anything else must match the host allowlist or be granted explicitly via `CSRF_ALLOWED_HOSTS`. Browsers without Fetch Metadata fall back to the Origin/Referer host match, which passes all same-origin traffic anyway. ## L2 — dead legacy auth surface `middleware/auth.js` was already deleted. The last remnant — `GET /register`, which generated a 2FA secret into the session and rendered the (missing) register view, i.e. a guaranteed 500 — now explicitly returns 404 via the standard 404 view. No `POST /register` exists; account creation is admin-only. ## L3 — socket spam guard vs automated clients Packet cap is now role-based at connection time: 60/min for regular users (overridable via `SOCKET_PACKET_LIMIT`), 600/min for admin/`agent_access` users (overridable via `SOCKET_PACKET_LIMIT_PRIVILEGED`), so the assistant / scheduler automated clients no longer get disconnected while the flood protection stays for everyone else. ## L4 — pre-auth static file surface `express.static(public)` used to be mounted ahead of the auth gate, so every file in `public/` was served unauthenticated — wider than the gate's own pre-auth allowlist, and any sensitive file dropped into `public/` later would have leaked. The static handler is now gated: unauthenticated callers are served only the asset path prefixes the gate already allows (`/css/`, `/css-ext/`, `/js/`, `/images/`, `/fonts/`, `/webfonts/`, `/vendor/`, `/uploads/`) plus common asset extensions (.css/.js/.webp/.woff2/...). Everything else in `public/` — e.g. `index-real.html`, or a stray .json/.html/.map dropped there — falls through to the auth gate (login redirect). Authenticated sessions get the previous behavior unchanged. ## L5 — `GET /api/maintenance/status` Info-only endpoint (active flag, scheduled time). It is reachable pre-auth (added to the gate's allowlist) because the maintenance 503 page — rendered to logged-out visitors — polls it to auto-recover when maintenance ends; previously that poll got a 401 and the page's error handler reloaded on it, producing a reload loop. The page's poll reloads only on a definitive "not active" answer instead of on any failed request, and reads only the `active` flag. `scheduled_at` is returned to authenticated users only. The `reason` field was later removed from the payload entirely (see the 2026-08-31 round below): the poller never used it, so it was a pure pre-auth reflection channel for admin-authored text. ## L6 — 15-minute step-up grace window applies to all destructive actions One successful step-up (current password or TOTP code) creates a grant in `destructive_action_grants` (DB row + process memory + session state, bound to session ID, IP, and User-Agent hashes) and unlocks every destructive action — password reset, 2FA reset/disable, user suspension/deletion, server deletion, session revocation — without re-prompting until the grant expires (`requireDestructiveActionStepUp` / `requireDatabaseInstallStepUp`, grace constant `SESSION_REVOKE_2FA_GRACE_MS` in `index.js`). A session hijacked inside the window inherits the full destructive capability. Resolution (accepted risk, tightened and made explicit): - Default window reduced from 15 minutes to **5 minutes** (`SESSION_REVOKE_2FA_GRACE_DEFAULT_MS`), cutting the hijack exposure window for destructive capability by 3×. Users performing legitimate bulk destructive workflows re-verify at most every 5 minutes. - New env knob `DESTRUCTIVE_ACTION_GRACE_MS` (milliseconds) makes the tradeoff an explicit operator decision: clamped to `0..5min` since the 2026-09-02 round below (previously `0..15min`). `0` disables the grace entirely (fresh step-up per destructive action — most hardened); the hard cap prevents configuring the panel looser than the hardened baseline. An explicit `0` is honored (finite-check, not the `parseInt(...) || default` idiom, which would coerce 0 to the default). - The constant feeds both grant creation and the tamper validation (`expiresAt - verifiedAt > SESSION_REVOKE_2FA_GRACE_MS`), so grants outstanding from a longer previous configuration fail validation and are cleared — the change is fail-closed. Leftover DB rows are garbage-collected by `cleanupExpiredDestructiveActionGrants`' existing 5-minute sweep. - Accepted risk documented: a hijacked session within the window retains destructive capability. Mitigations already in place narrow the hijack scenario: grants are bound to session ID + client IP + User-Agent hashes (cookie theft with replay from a different network/UA fails validation), the grant secret lives in session state, and DB rows are re-verified on every use. Not changed: per-action tiering (e.g. always-fresh verification for password/2FA changes specifically) was considered and deferred — it changes UX semantics on the highest-friction routes and is recommended as follow-up hardening if the threat model shifts toward session theft. ## Audit finding 6 — missing rate limiters on in-session credential-verification endpoints Login, suspension, session revoke and the other destructive admin actions were rate limited, but the in-session endpoints that verify a current password or a TOTP code were not. With a stolen session an attacker could brute-force the 6-digit TOTP space on `2fa/generate`/`2fa/confirm` (~3 valid codes per 1,000,000 with `window: 1`) or grind the bcrypt current-password checks, unbounded. Fix (`index.js`), following the shape of the existing `sessionRevoke2faRateLimiter` (windowed counter, `standardHeaders`, JSON 429 body with `code: "verification-rate-limit"`, `securityLog` on trip): - New `accountTotpRateLimiter` (10 req / 10 min) attached to `POST /api/account/2fa/generate` and `POST /api/account/2fa/confirm`. At 10 guesses per 10 minutes the TOTP space is mathematically out of reach, while the legitimate generate→confirm flow (plus typos) fits comfortably. - New `accountCredentialRateLimiter` (10 req / 10 min) attached to `POST /api/account/password/verify`, `POST /api/account/password/change`, `POST /api/account/email/verify`, `POST /api/account/email/change` and the legacy `POST /api/settings/change-password`. The budget covers two full modal flows (verify + change) with a few typos per window. - Existing `sessionRevoke2faRateLimiter` attached to `POST /api/admin/user/reset-2fa` and `POST /api/admin/user/confirm-2fa-reset` — same step-up family as `reset-recovery-codes`, which already carried it. Its `hasDestructiveActionCredentialPayload` skip predicate is correct for these routes: only credential-bearing attempts are counted; grace-window re-submissions (already authorized by a fresh, limited verification) skip. - `adminUserCreateRateLimiter` existed but was never attached; now attached to `POST /api/admin/user/create` (which performs an admin password+2FA step-up). Keying: both new limiters key on account + session ID (`account-…:${email}:${sid}`) instead of the IP+email+sid tuple used by the older limiters. The threat here is a hijacked session, so a counter keyed partly on IP is resettable by rotating source IPs (proxies), and IP keying lets one attacker lock out unrelated users behind a shared NAT. Session-scoped keying is rotation-proof — the sid is fixed by the stolen cookie — and a victim sharing the hijacked sid is throttled together with the attacker, which is the intended outcome. Unauthenticated requests are skipped (the handlers 401 them anyway), so there is no shared anonymous bucket. Verified: `reset-recovery-codes` from the finding already had `sessionRevoke2faRateLimiter` (no gap once credential-bearing attempts are counted). `node --check` passes; `scripts/verify-account-rate-limiters.js` drives the exact limiter configs through express + express-session and passes: bucket exhausts at 10 → 429 contract body + standard headers, separate sessions get separate buckets, per-guess IP rotation does not reset the counter, unauthenticated requests are skipped. ## Already fixed elsewhere (verified, no change) - C1 sudoers: `adpanel-sudoers` is restricted to the root-owned `/usr/local/lib/adpanel/adpanel-priv` allowlist runner. - Path traversal (`safeJoinUnix`), upload one-time tokens, node install-lock 409, SSE/console room separation, session-secret length enforcement — confirmed present. ## Login background pipeline — `POST /api/admin/login-background` (audit section 2) Verification of the audit's observations plus remediation of the residuals. ### Finding 1.1 (SVG) — verified closed on every entry path An SVG cannot reach `public/images/` through this pipeline (checked, not assumed): 1. **Upload mode** — `getMediaTypeFromFilename` → `getValidatedExtension` (`utils/branding.js`): the extension whitelist (`png,jpg,jpeg,webp,ico,avif,gif` / `webm,mp4,ogg,ogv`) excludes `svg`, including trailing-ext smuggling (`x.png.svg`, `x.png%00.svg`). 2. **URL mode** — `getMediaTypeFromUrl` / `getExtensionFromUrl` apply the same whitelist to the URL pathname. 3. **Content gate** — `downloadLoginBackgroundToLocal` re-validates the downloaded body by magic bytes (`validateImageBuffer` / `validateVideoBuffer`), so a mislabeled SVG body (e.g. served at a `.png` URL — fragments like `x.png#.svg` are invisible to the URL gate by design) still cannot be stored. 4. **Boot mirror** (`ensureLocalLoginBackgroundMirror`) — same URL whitelist plus the same content gate; even a hand-edited `data/branding.json` cannot pull an SVG (or anything else failing validation) onto disk. 5. **Legacy files** — pre-existing SVGs under `public/` are served with `Content-Security-Policy: default-src 'none'; sandbox` + `nosniff` (`applySvgContentSecurityHeaders` on both the static handler and the private asset routes). Added: an explicit `.svg` URL rejection with a dedicated error message in the login-background URL branch, for parity with the branding endpoint — the whitelist already refused SVGs, so this is a guard against future whitelist regressions as much as clearer admin feedback. ### Residual fixed: unauthenticated cache-miss amplification `/branding-media/*`, `/auth-assets/background|logo|favicon` proxy the configured remote asset; the audit rated the 40 MB-per-cache-miss fetch "trivial", but the actual amplification was worse than bandwidth: on a cold cache, **N concurrent requests each buffered their own copy** of up to 40 MB in memory (≈4 GB at N=100 — an OOM vector with zero authentication), and failed fetches were not negatively cached, so a remote outage converted every login-page hit into a fresh origin fetch. Fixes in `loadBrandingRemoteAsset`: - **Single-flight dedup** — concurrent cache misses share one in-flight download; N parallel requests now cost one origin fetch and one buffer. - **10-second negative cache** — a failed fetch short-circuits subsequent requests for 10s instead of re-fetching per request. Cleared by `clearBrandingRemoteAssetCache` (admin re-save) and scoped per asset kind, so one broken asset cannot poison another. ### Residual fixed: no rate limit on pre-auth asset proxies New `brandingAssetRateLimiter` (240 req/min per source IP, standard RateLimit headers, plain-text 429) attached to `/branding-media/:kind`, `/auth-assets/logo|christmas-logo|background|favicon` and `/favicon.ico`. The cap is deliberately generous — a page view costs only a handful of asset loads, so shared-NAT offices are unaffected — while sustained scripted flooding is rejected before reaching the proxy handlers. `/auth-assets/login.css` stays unlimited: it is generated locally, triggers no origin fetch, and a 429 there would render the login page unstyled for NAT'd users for no gain. The limiter keys on the direct socket IP (with trusted-proxy resolution via `getRequestIp`), so a spoofed `X-Forwarded-For` cannot rotate the bucket. ### Verified, no change needed - **SSRF posture** (`httpGetRaw` / `assertSafeRemoteUrlWithResolvedIp`): scheme allowlist, credentials-in-URL refusal, localhost/`.local` refusal, ports 80/443 only (unless `REMOTE_FETCH_ALLOW_ANY_PORT=1`), all resolved addresses must be public, connection pinned to the validated IP with SNI + Host preserved, every redirect hop fully re-validated, byte cap + timeout. Applies equally to the boot-time mirror. - **Replacement cleanup** — old background files are basename-sanitized and unlinked only under `public/images/`; no unbounded disk growth. - **Boot mirror control** — `data/branding.json` is root-owned mode 0600 (verified on disk; `saveBrandingConfig` writes 0600 atomically), so the "who controls the file controls an outbound fetch" quirk requires root already. - **Info note (accepted):** the shipped default `DEFAULT_LOGO_URL` in `utils/branding.js` still points at a remote SVG on jsDelivr. It is only ever rendered through `` (sandboxed — SVG-in-img cannot execute script) and is CSP-governed; the `/auth-assets/logo` proxy refuses to fetch it (magic-byte gate) and serves the local `adpanel-dark.webp` instead. Aligning `DEFAULT_LOGO_URL` with the `.webp` favicon default is a branding decision, not a security fix. ### Verification `node --check` passes for `index.js` and `scripts/verify-branding-asset-hardening.js`. The script (43 checks) proves: SVG rejection through the real `utils/branding.js` gates used by the endpoint; the explicit-SVG regex variants; the single-flight + negative-cache copy (50 concurrent misses → exactly 1 origin fetch, fail-fast during outage, kind scoping, admin clear); and the rate-limiter contract through a real express app (200×240 then 429, RateLimit headers, XFF-spoof resistance, independent buckets per source IP via distinct loopback addresses). ## Audit round 2026-08-31 — L-7 / L-5 remediation ### L-7 — pre-auth reflection of admin text on `GET /api/maintenance/status` While maintenance was active, the pre-auth status payload included the admin-authored `reason` string. Nothing consumed it client-side — the 503 page's recovery poller reads only `active`, and the page itself renders the reason server-side through EJS escaping — so the field was a pure public reflection channel for stored admin text (and a standing invitation for any future consumer to trust it). Remediation: - `reason` removed from the response entirely. Visitors still see the reason as server-rendered, HTML-escaped text on the 503 page (`views/maintenance.ejs` uses `<%= reason %>`); authenticated admins read the full state from the admin-gated `/api/settings/maintenance`. The response is now `{ active, scheduled_at }` with `scheduled_at` still gated to authenticated users. - `Cache-Control: no-store` added: the answer flips the moment an admin toggles maintenance, and cached 200s would stall the 503 page's auto-recovery poll. - Write-path hardening in `POST /api/settings/maintenance`: the stored reason is now stripped of control characters and trimmed before the existing 500-char cap (same character class as `sanitizeGlobalAlertMessage`), so the value persisted for pre-auth rendering is plain printable text. EJS escaping at render time remains the XSS boundary. ### L-5 — missing email validation on admin 2FA/recovery reset endpoints `POST /api/admin/user/reset-2fa`, `POST /api/admin/user/confirm-2fa-reset` and `POST /api/admin/user/reset-recovery-codes` (same family, same gap) accepted an unvalidated, unlength-capped `email` body field, unlike the suspension/delete/change-password endpoints (`/api/settings/accounts/:email/...`) which enforce trim + `@` + ≤255 chars. Parameterized SQL kept the gap harmless, but the inconsistency is exactly how future regressions start. Remediation: - New `normalizeAdminTargetEmail()` helper enforcing the identical contract as the suspension/delete endpoints: string, trimmed, contains `@`, at most 255 characters; anything else is rejected with `400 invalid email`. - All three endpoints now look the target up (and write/log) through the normalized value / canonical `targetUser.email`, matching the sibling endpoints' behavior. No legitimate stored address is excluded that the suspension/delete endpoints don't already exclude. ### Verification `node --check` passes for `index.js`. Repo-wide search confirms `/api/maintenance/status` has exactly one consumer (`views/maintenance.ejs`'s poller, which reads only `data.active`), and no remaining occurrences of the old weak `"Target email required"` validation exist. Frontends display the new `invalid email` error via the generic `data.error` path (no string matching anywhere), and `confirm-2fa-reset` has no in-repo frontend caller (legacy compatibility endpoint), so the tightened contract breaks nothing. ## Audit round 2026-08-31 (2) — L-1 / L-4 remediation ### L-1 — step-up grace window allows unlimited destructive reuse per verification Follow-up to the L6 round above, which cut the window to 5 minutes and made it operator-tunable. The residual finding: within the window, one successful verification still authorized an UNLIMITED number of destructive actions. The realistic attack is a 2FA-protected admin whose password plus a single phished TOTP code convert into full destructive capability for the whole window — every subsequent action would otherwise have required a fresh code. (For accounts without 2FA the re-prompt is only the password the attacker already has, so the grace adds nothing for them.) Remediation adds a second, quantitative bound on top of the time window: - New reuse cap `SESSION_REVOKE_2FA_GRACE_MAX_USES` (default **5**, hard cap also **5** since the 2026-09-02 round below — previously 25, env knob `DESTRUCTIVE_ACTION_GRACE_MAX_USES`). The counter tracks grace REUSES — the action that created the grant does not consume one — so one verification now authorizes at most `cap + 1` destructive actions instead of unbounded. `0` disables reuses entirely (fresh step-up per action); values above the cap clamp down and invalid input falls back to the default, so misconfiguration can only make the panel stricter, never looser. - Enforcement is atomic at the DB row (`consumeDestructiveActionGraceUse`): `UPDATE ... SET use_count = use_count + 1 WHERE grant_id = ? AND revoked_at IS NULL AND expires_at > ? AND use_count < ?` with an `affectedRows === 1` check. Concurrent requests or multiple panel processes sharing the database can never exceed the cap; any non-apply (cap reached, expired, revoked, DB error) clears the local grant state and falls through to a fresh verification — the cap always fails closed, mirroring the existing DB-validation failure mode of the grace system. - Wired into both gatekeepers (`requireDestructiveActionStepUp`, `requireDatabaseInstallStepUp`), which are the single consumption points all destructive routes go through; `verifyAdminProvisioningStepUp` already requires fresh credentials every time and does not use the grace. Each grace-based authorization now writes a `[SECURITY]` audit line including the reuse counter (`Reuse n/N`), making "repeated destructive use" visible in logs — the exact pattern the finding describes. - Schema: `destructive_action_grants.use_count BIGINT UNSIGNED NOT NULL DEFAULT 0` added to `mysql-schema.sql`, plus the repo's standard `SHOW COLUMNS`/`ALTER TABLE` runtime migration for existing deployments (`CREATE TABLE IF NOT EXISTS` never alters an existing table). While the column is missing, consumption fails closed (fresh step-up per action). - Client contract: `revokeSecurity` payloads now also carry `graceUsesRemaining` / `graceUsesLimit` (additive; the frontends ignore unknown fields). When the cap trips, the server answers the usual `password-required` / `2fa-required` 403, which is the step-up dialog flow the clients already handle, so no frontend change is needed. Accepted risk remains, now bounded: a hijacked session inside the window can perform at most `cap + 1` destructive actions instead of unbounded, still bound to the original session/IP/UA hashes. ### L-4 — maintenance gate bypasses broader than intended `MAINTENANCE_BYPASS_PATHS` included `/register` and `/forgot-password`, and any path merely ENDING in `.css/.js/.webp/.png/.avif/.ico/.woff2` skipped the gate outright — so any future API route with such a suffix would silently escape maintenance lockdown, and state-changing pre-auth endpoints stayed live during it. Remediation: - `/register` and `/forgot-password` removed from the bypass set. They are active endpoints (account creation, reset mail), not read-only pages, and belong behind the lockdown. Admins bypass the gate via `req.isAdmin` and keep full access; the stealth gate runs before this one, so in stealth mode strangers still get the fake-404 first (no new signal leak). - Extension matching removed entirely. Static assets now bypass via `MAINTENANCE_BYPASS_PREFIXES` — exact directory prefixes mirroring the pre-auth static allowlist (`/css/`, `/css-ext/`, `/js/`, `/images/`, `/fonts/`, `/webfonts/`, `/vendor/`, plus the `/auth-assets/` and `/branding-media/` brand proxies) — restricted to GET/HEAD and with `/api/` excluded outright. A future route cannot escape the lockdown by naming, and writes to asset paths no longer bypass either. - The prefix list is verified sufficient for the only pages reachable during maintenance: `views/maintenance.ejs` loads just the favicon plus CDN assets, and `views/login.ejs` loads `/js/cdn-fallback.js`, `/vendor/fontawesome/*`, `/auth-assets/*` and `/images/*` (branding URLs resolve only to `/images/`, `/auth-assets/*`, `/branding-media/*` — never `/uploads/*`, which is therefore no longer bypassed). This also fixes a latent bug: `/auth-assets/logo`, `/auth-assets/favicon`, `/auth-assets/background` and `/branding-media/login-background` have no file extension and used to 503 during maintenance, breaking the login page's logo/background/favicon images while its CSS/JS loaded. - Root cause in the same class closed at the early static-asset marker (`req._staticAsset`, `index.js` ~line 2200): `/api/` paths no longer get marked as static assets, so a future `/api/*.js` route cannot skip session restore, the suspension check, CSP nonce generation, or cache-control by virtue of a static-looking extension. Verified no current `/api/` route ends in a static extension, so no existing behavior changes. ### Verification `node --check` passes for `index.js`. The bypass predicate and the conditional-UPDATE semantics were exercised in a standalone harness (36 checks): all login/maintenance-page asset paths still bypass, `/register`, `/forgot-password`, every `/api/*.js|*.css` shape, non-GET/HEAD writes to asset paths, `/uploads/*` and root-level static files are locked down; the reuse cap allows exactly `cap` reuses then fails closed, and expired / revoked / DB-error grants never authorize. Asset coverage was checked against the actual local references in `views/login.ejs` and `views/maintenance.ejs`, and no in-repo consumer of the removed suffix bypass exists (no `/api/` route ends in a static extension; no pre-auth page references root-level static files). ## Audit round 2026-09-01 — M-2 remediation ### M-2 — security-weakening toggles skipped step-up entirely `POST /api/settings/security` (disable the rate limiter, loosen its bounds, write up to 50 trusted-subnet bypass ranges — an API-only surface with no in-repo UI) and `POST /api/settings/captcha` (wipe the configured keys) were gated only by the admin session plus a 10-minute action token. The action token proves the session, not the operator, so a hijacked admin cookie could silently strip both anti-brute-force protections inside the token TTL and then hammer the login endpoint — precisely the attack the rate limiter exists to stop. Remediation brings both endpoints under the same step-up/grace-window regime as maintenance activation and the other destructive actions: - `POST /api/settings/security` now resolves the acting admin and requires `requireDestructiveActionStepUp` (password, or TOTP when 2FA is enabled) before any mutation. The gate is uniform for every write to this endpoint: the same request that disables the limiter can also loosen its bounds or add bypass subnets, so per-field "is this weakening?" classification would leave re-enabling with `limit=10000` as a trivial bypass. Payload validation (bounds, subnet syntax) still runs first so a malformed request cannot burn a grace-window use. - `POST /api/settings/captcha` requires the same step-up for every write: `enabled:false` wipes the keys, and a key replacement swaps login verification to operator-chosen key material (a session hijacker could point the panel at the attacker's own site/secret pair, which their bots can satisfy) — both directions strip the login bot protection. - Both routes sit behind `sessionRevoke2faRateLimiter` (8 credential attempts / 10 min, keyed IP+account+session, skipped for requests without credential payload), so the new prompts cannot be used to brute-force the admin password or TOTP. Success responses carry `graceExpiresAt` / `revokeSecurity` like the other step-up endpoints. - `GET /api/settings/security` now returns `revokeSecurity` so the settings UI knows whether a step-up credential is needed before submitting. - Frontend (`views/settings.ejs`, `public/js/settings.js`): the rate-limiter card gained a credential field (revealed and focused when a save is attempted without one; hidden automatically while a grace grant is active, and the failed toggle re-syncs with server state); the captcha key modal gained the same field; disabling captcha now opens a dedicated confirmation modal that collects the credential instead of a bare `confirm()`. All three fields register with the shared step-up state (`refreshStepUpCredentialFields`), clear after successful submission, and the payloads use the existing `appendStepUpCredentialPayload` helper — grace-active requests send no credential and consume a grace use, exactly like maintenance. ### Verification `node --check` passes for `index.js` and `public/js/settings.js`; `views/settings.ejs` renders with all fourteen new element IDs present. Repo-wide search confirms the only frontend callers of the two endpoints are the updated settings-page flows (no bot/assistant/automation callers exist to break), and the step-up failure contract (`password-required` / `2fa-required` 403 plus `revokeSecurity`) is the dialog flow the shared helpers already render. Within an active grace grant the panels submit without prompting, preserving the documented bounded-reuse risk model instead of a per-action re-prompt. ## Audit round 2026-09-01 — M-1 remediation ### M-1 — suspended accounts were not rejected at auth-check time `findUserByEmail` returns suspended rows (by design — login, the suspension endpoint and the session-teardown middleware all need the suspension metadata), but the auth primitives built on top of it (`isAuthenticated`, `isAdmin`) treated a suspended account exactly like an active one. The only enforcement was eviction at suspend time (`destroyBrowserSessionsForUser`), and that path collected scan/destroy failures as warnings returned inside an `ok:true` response — so if the session store hiccuped during a suspension, the admin was told the account was locked down while surviving sessions still authenticated. The remediation makes suspension a first-class, fail-closed input to every authorization decision instead of relying on eviction side effects: - **Choke point (`index.js`)**: `isAuthenticated` now returns false and `isAdmin` false for `user.suspended`, regardless of session validity. A session that survives a failed eviction now fails every auth gate in the panel — routes guarded by these functions, the global `req.isAdmin` computation (and with it the maintenance-mode admin bypass), the dashboard-assistant router (which receives these functions as injected dependencies), and the SSH terminal token mint. DB lookup failure still throws into the error handler (500) — the check fails closed, never open. - **Single lookup per request**: the suspension-teardown middleware now resolves the user through `getLoggedInUser` instead of its own `findUserByEmail` call, so the teardown check and every later auth decision in the request read the same row exactly once — removing the two-queries-per-request cost and the TOCTOU window between them. The middleware keeps its job of destroying the session, revoking remember-me tokens and answering 403/redirect; the primitives above now enforce the same policy even where the middleware does not run (static-asset fast path consumers, future early-registered routes). - **Capability checks**: `hasAgentAccess` (SSH terminal / agent surfaces) no longer grants on `agent_access` while suspended; `userHasAccessToServer` denies outright; `getEffectivePermsForUserOnServer` resolves to the all-false template, so schedule re-validation, socket access sync and per-route permission projections cannot resurrect a stale ACL entry for a suspended account. - **Raw `.admin` decision points**: `POST /api/admin/user/create` and the AI chat scope computation (`completeAiChatConversation`) checked `user.admin` directly; both are now suspension-aware (the former via `isAdmin`). `routes/subdomains.js` `checkPerms` authorizes from its own user query and now rejects suspended users before its admin/access branches. The remaining direct checks were verified covered: the socket sync/init paths test `user.suspended` explicitly, and every other raw check sits behind an `isAuthenticated` gate or in the scheduler's execution-time re-validation (`ensureScheduledJobStillAuthorized`). - **Honest suspension reporting**: `POST /api/settings/accounts/:email/ suspension` now retries failed session eviction once after 250ms (fresh store scan) and, if eviction still cannot be confirmed, answers 500 with `ok:false` / `sessionEvictionFailed:true` and a prominent `[SECURITY] Account suspension incomplete` log line instead of `ok:true` with the failures buried in `sessionInvalidationWarnings`. The suspension itself is never rolled back on eviction failure — with auth-time enforcement in place the account is already blocked on every request, and the non-2xx response tells the admin to retry the (idempotent) suspension to force the sign-out. The success response shape (`sessionsDestroyed`, `sessionInvalidationWarnings`, `rememberLoginsRevoked`, `graceExpiresAt`) is unchanged, so the existing settings UI flow is unaffected; it renders the 500's `error` message in the confirmation dialog. ### Verification `node --check` passes for `index.js` and `routes/subdomains.js`. Every consumer of the changed primitives was enumerated (`isAuthenticated`, `isAdmin`, `req.isAdmin`, `hasAgentAccess`, `userHasAccessToServer`, `getEffectivePermsForUserOnServer`, the dashboard-assistant and nodes-router injections) and confirmed to be an authorization gate — no flow relies on a suspended account authenticating. Suspension re-checks that already existed were left untouched: login/captcha-completion/2FA flows, remember-me restore, socket handshake and socket init, the per-request teardown middleware, and the scheduled-job execution-time re-validation. mysql2's default `FOUND_ROWS` flag makes re-suspending an already-suspended account report `affectedRows: 1`, so the retry-the-eviction operational path passes the endpoint's `affectedRows` guard. ## Audit round 2026-09-02 — revoke TOCTOU, grace blast radius, limiter keying ### R-1 — revocation TOCTOU window (check-then-destroy race) The revoke handler read the target session, validated it, and destroyed it later, with the listing cache TTL (15s) on top. A request already in flight from the target session (every authenticated request runs `session.touch()`) could re-save the record between the check and the `destroy`, resurrecting a session the admin believes is dead. - New `destroySessionStoreSessionVerified(sid)`: after every `destroy` the store is re-read; if the record is back, it is destroyed again (up to 3 iterations) and success is only reported when a final read finds nothing. Store differences are handled: connect-redis resolves `null` for a missing key while session-file-store rejects with `ENOENT` — both count as "gone". A failed `destroy` on an already-absent record is logged and retried rather than failing the revoke; a `get` error that is not a miss leaves the outcome unknown, so the loop retries and callers fail closed on false. - Wired into every destroy path of `POST /api/settings/sessions/revoke`: non-self session destroy, self (current-session) destroy, and both saved-login (remembered) paths. `req.session.destroy()` still runs first on self paths so THIS request's response-end save cannot resurrect anything; the verified loop covers saves racing in from other in-flight requests. - On unverifiable destruction the endpoint answers `503` with code `session-destroy-unverified` (and a `[SECURITY]` warning line) instead of a success the admin would trust. The saved-login paths keep their existing contract: the persistent login is already revoked, and `destroyedSession: false` reports the unverified live-session destroy. The revoke token is consumed only after verified success, so a failed verification can be retried with the same token (10-minute TTL). - The active-session cache entry is still removed before responding (unchanged ordering). Dead targets now 404 BEFORE the step-up prompt, so stale UI entries can no longer spend a grace reuse on a no-op. ### R-2 — step-up grace window blast radius (policy hardening) The grace feature itself was sound; the policy was generous. Three changes, all fail-closed: - **Quantitative**: hard caps lowered from 15 minutes / 25 reuses to **5 minutes / 5 reuses** (`SESSION_REVOKE_2FA_GRACE_MAX_MS`, `SESSION_REVOKE_2FA_GRACE_USES_CAP`). The env knobs can still lower the values (0 disables) but can never raise them above the caps; grants minted under an older, longer configuration fail the existing `expiresAt - verifiedAt` tamper check and are cleared. - **One target per grant**: `destructive_action_grants.scope_hash` (new nullable column, standard `SHOW COLUMNS`/`ALTER TABLE` runtime migration) binds a grant to ONE logical target — `user:`, `node:`, `server:` — HMAC'd like the other grant fields. Fresh verifications pre-bind the grant at INSERT; the atomic consumption UPDATE binds an unbound row on the first scoped reuse (`scope_hash = COALESCE(..., scope_hash)`) and only applies when the row's scope matches or is still NULL. Once bound, reuses against any other target fail closed and fall through to a fresh verification. Unscoped actions (settings saves, webhooks, maintenance, database installs) can only consume grants that are still unbound, so a grant scoped to a user cannot be laundered through a settings route. While the column is missing, scoped consumption fails closed (fresh step-up per action). Every grace authorization's audit line now includes the bound scope. - **Peer-admin targets never ride a grant**: revoking a session (or saved login) belonging to a DIFFERENT admin bypasses the grace entirely (`allowGrace: false`) and a fresh verification for such a target mints no grant (`persistGrant: false`) — the verification authorizes exactly that one action. Own sessions and regular users keep the scoped grace flow. ### R-3 — step-up rate limiter keyed per IP The step-up limiter key `session-revoke-verify:ip:email:sid` let a network-hopping attacker multiply the 8-attempt budget by rotating source IPs. The key is now `session-revoke-verify:email:sid` (session-scoped, so rotating IPs no longer resets anything), and a second account-wide backstop limiter (`session-revoke-verify-email:`, 24 per 10 minutes) caps the multiplier for an attacker holding several hijacked sessions. Both budgets apply to every step-up-protected route via a composed middleware; IP removal from the key also stops one attacker from burning the budget of unrelated users behind a shared NAT, matching the `accountCredentialRateLimiter` keying that already followed this pattern. ### Verification `node --check` passes for `index.js`. All `requireDestructiveActionStepUp` call sites were enumerated: target-scoped routes (session revoke, node delete/rotate-token, server delete/suspend, account grant-perms/suspend/ delete/password-reset, admin 2FA + recovery-code resets) pass a scope key; unscoped routes (security/captcha/maintenance settings, webhooks, database installs) intentionally consume only unbound grants. The revoke handler's response shapes are unchanged except for the new 503 branch, so the existing settings UI flows (including the `password-required`/`revokeSecurity` 403 step-up dialog) keep working. ## Audit round 2026-09-02 (2) — single-use revoke target tokens ### R-4 — revoke target tokens are replayable within their TTL `resolveSessionRevokeTargetToken` validated the per-row `revokeToken` without consuming it; deletion happened only on confirmed success or dead-target 404 paths. A revoke attempt that failed (wrong step-up credential, transient 5xx, unverified destroy) therefore left the token valid for the rest of its 10-minute TTL. A token captured via XSS/logs/referer degraded from a one-shot target proof into a 10-minute capability: once replayed by an attacker who also satisfied step-up — or while a grace grant scoped to the same target was live — it authorized a second destructive action the original verification never intended. **Fix — consume on first verification, not first success:** - `resolveSessionRevokeTargetToken` + `clearSessionRevokeTargetToken` are replaced by a single `consumeSessionRevokeTargetToken` primitive that verifies the token and destroys the entry in one step. The revoke handler keeps the resolved target in a local (`resolvedTarget`); every later decision (store reads, peer-admin check, grace scope key, destroy) uses the local, never the client-supplied token. The six success/404-path token clears became dead code and were removed. - Failed attempts an admin is meant to retry mint a FRESH token bound to the SAME resolved target (`reissueRevokeToken`), carried in retryable failure responses only: - step-up 403s (`password-required` / `2fa-required` / `invalid-password` / `invalid-2fa`) via a new opt-in `failureResponseExtras` option on `requireDestructiveActionStepUp` (defensively evaluated — a throw in the extras callback can never mask the step-up 403; no other call site passes it, so their 403 bodies are byte-identical to before); - the non-self `session-destroy-unverified` 503; - both 500 catch blocks (retries against partially-applied state resolve safely as 404 saved-login-not-found / session-not-active). Capability never grows: same target, same session binding, fresh TTL, and a token is only ever renewed in a response that just failed to act on the previous one. No renewal on self-revoke paths (the acting admin's session is destroyed; a token bound to a destroyed session is inert), 404s, 400s, or action-token failures (which occur before consumption). - Client (`public/js/settings.js`) adopts `data.revokeToken` on failure responses: the local working token, `sessionsState.selectedSession` (token-matched guard so unrelated modal state is untouched), and the row button dataset. Any stale token that slips through fails closed — the server answers `session-action-expired` and the existing handler reloads the sessions list, which mints fresh tokens. - Residual, documented: the map lives in the admin's express-session object, so two racing requests of the same session can still interleave read-modify-write saves (an express-session property, shared by all session-scoped state here). The window is sub-second and requires an already-hijacked session; the TTL cap (10 min) and LRU bound (250) are unchanged. ### Verification `node --check` passes for `index.js` and `public/js/settings.js`. A unit harness extracted the token primitives verbatim and asserted: consume returns the target once and replays resolve to nothing; malformed/oversize/ unknown/expired tokens are rejected without side effects; the 250-entry LRU cap still evicts; consuming one token leaves siblings intact. A full end-to-end suite against a booted panel (isolated copy, scratch MySQL DB, file session store, 2FA-enabled admin + two target sessions) verified on the wire: wrong TOTP → 403 invalid-2fa with renewed token; step-up-required 403 with renewed token; replay of the consumed original WITH a valid fresh TOTP code → 400 session-action-expired (the finding closed); renewed token → 200 revoked and the target session destroyed; grace-riding revokes keep single-use semantics; hostile tokens (empty, path traversal, oversize, unknown, unicode) fail closed. The remembered-login ("saved login") path shows the same behavior end-to-end, and the shared step-up 403 shape for other routes (security settings) is unchanged — no `revokeToken` leaks into response bodies that do not opt in. ## 2.6 — database bind host: `0.0.0.0` was a first-class option (2026-09-02) `validateDbHost` (`index.js`) accepted `0.0.0.0` verbatim and passed it to the installers, which wrote it as PostgreSQL `listen_addresses` / MongoDB `bindIp`. Combined with the opt-in `ADPANEL_AUTO_MANAGE_FIREWALL` flow this made "root-privileged database exposed to every interface" a two-click outcome. Fix (`utils/db-bind-policy.js`, new module — single source of truth): - **Wildcard binds are gone.** `0.0.0.0` and every all-zero IPv6 textual form (`::`, `::0`, `0:0:...:0`) are rejected by `validateDbHost` itself — for bind hosts *and* as connection targets, where they were never meaningful. - **Bind gate.** The pgAdmin/MongoDB setup routes and both install functions now use `validateDbBindHost`: loopback (`localhost`, `127.0.0.1`, `::1`) always allowed; anything else must match the operator allowlist `ADPANEL_DB_ALLOWED_HOSTS` (IPs, CIDRs, or hostnames; max 32 entries; parsed fail-closed per entry with the valid ones logged at startup). Wildcards are checked *before* the allowlist, so listing `0.0.0.0` or `::/0`-style entries can never re-enable an all-interfaces bind. - **Step-up confirmation.** Non-loopback binds additionally require `confirmRemoteBind: true` from the UI, which asks a two-stage confirmation explaining the exposure (recommending SSH tunnel / proxied web UI instead). API callers without the flag get a distinct `REMOTE_BIND_CONFIRMATION_REQUIRED` error. Enforcement is server-side; the dialog is UX, not the boundary. - **Defense in depth.** `maybeOpenFirewallPort` independently refuses to open a firewall port for a wildcard bind and logs loudly when it opens a port for a non-loopback one. `ADPANEL_AUTO_MANAGE_FIREWALL` stays default-off; loopback binds never touch the firewall. - **Remote access path unchanged.** phpMyAdmin/pgAdmin remain reverse- proxied through the panel; phpMyAdmin's DB *connection* host still accepts remote targets (a client target, not a bind). - The setup-modal copy that advertised "UFW firewall rules for ports 5432/5050/27017" was replaced with the real behavior. - `initialize.sh` audited: the installer only ever opens the panel's own HTTP/HTTPS/SSH-terminal ports, never database ports. Not changed (documented decision): `HOST=0.0.0.0` for the panel's own web listener — that is the product itself and unrelated to DB binds. ### Verification `node --check` passes for `index.js`, `utils/db-bind-policy.js`, `public/js/settings.js`. `scripts/verify-db-bind-policy.js` (21 checks) asserts the matrix: wildcard IPv4 + six IPv6 textual forms rejected; loopback always passes the bind gate; non-loopback requires allowlist (exact IP, CIDR membership via ip-range-check, hostname); wildcard entries in the allowlist still cannot enable wildcard binds; allowlist parsing is fail-closed, dedupes, caps at 32, and strips injection metacharacters; `maybeOpenFirewallPort` skips wildcard hosts and stays default-off. ## 2.4 — `/db-access` proxy authorized by IP without any session `utils/db-proxy.js` treated a matching source IP as a *substitute* for the admin session: `if (!sessionMatched && !isIpAuthorized(requestIp, sess.userIp))` meant that anyone on the IP recorded at token issuance (or inside a trusted subnet) could use a live proxy token with no Express session at all. Three concrete failures followed: the token kept working for the rest of its 30 minutes after the admin logged out; on NAT'd networks anyone sharing the IP could use the token URL (it lived in the URL path, so it leaked via browser history and Referer); and `X-Forwarded-For`-trusting proxies made the IP check itself spoofable. The token URL was effectively a 30-minute bearer credential for the database backends. ### Fix - **Session is now mandatory.** The IP fallback branch and the `isIpAuthorized`/`loadTrustedSubnets` helpers were deleted. Every proxied request must present a token that is bound to the exact minting session (`sessionMatchesToken`: `sess.sessionId === req.sessionID` AND `sess.username === req.session.user`) — IP is recorded for audit trails only and plays no part in any authorization decision. "Keep the tab working" is handled by re-validating the live session server-side on every request (and the heartbeat), never by substituting IP. - **Token removed from URLs entirely.** The token is delivered only as a short-lived HttpOnly cookie (`adpanel.dbproxy.`), scoped to `path=/db-access`, `SameSite=Lax`, `Secure` following the panel's session-cookie policy, `Max-Age` = TTL. Proxy URLs are now `/db-access//...` — the service slug is public information, not a credential — so nothing secret lands in history or Referer. The "Copy URL" affordances in Settings were removed (a shared URL cannot work without the cookie); only the session-bound Open flow remains. - **Logout revocation.** `POST /logout` now revokes every proxy token minted by the logging-out admin (`revokeAllForUser`) and clears the proxy cookies. The admin session-revocation route (Sessions panel) revokes `revokeAllForSessionId(...)` at each of its verified destroy paths (self/other, session/saved-login targets). Minting a new token for a service revokes the admin's previous token for that service (`revokeAllForUserAndService`) so superseded tokens cannot linger. - **TTL 30 → 10 minutes**, sliding: every proxied request and the heartbeat renew it. The old unauthenticated keep-alive oracle (`POST /api/settings/database/access-heartbeat`, token in body, reachable pre-auth) and the unused `POST /api/settings/database/revoke-token` route were removed; the heartbeat moved into the proxy middleware as `POST /db-access//__heartbeat`, where it validates the session against the token, slides the server-side TTL *and* re-sets the browser cookie (so an actively used tab never loses its cookie mid-session), and returns 404 without detail on any failure. The injected page script no longer carries the token at all. - **Backend hygiene (defense in depth).** All `adpanel.*` cookies are stripped before the request is forwarded to phpMyAdmin/pgAdmin, so the panel session id, remember-login, and proxy token are never echoed into backend logs/forms. The proxy 404s are sent with `Cache-Control: no-store`. ### Verification `node --check` passes for `index.js`, `utils/db-proxy.js`, `public/js/settings.js`, and both verify scripts. `scripts/verify-db-proxy-session-auth.js` (59 checks, mocked Express req/res + stubbed upstream) asserts: the authorization matrix (valid cookie + minting session passes; no session, wrong session id, wrong username, revoked/expired token, missing cookie, cross-service cookie, and legacy token-in-URL forms all 404 with the cookie cleared where presented); the token never appears in proxied HTML, Location, Set-Cookie, or the injected script; Location/HTML/Set-Cookie rewrites map `/phpmyadmin` → `/db-access/phpmyadmin`; the heartbeat slides both TTLs (deterministic clock) and rejects no-session/GET/unknown-service probes; all three revocation scopes; cookie attribute and backend-cookie-stripping contracts. A full-stack pass (real Express + express-session + fake phpMyAdmin backend over real HTTP, 24 checks) additionally exercised login → mint → proxy → heartbeat → logout-rejects → re-login end to end. `scripts/verify-trusted-subnet-validation.js` was updated to assert the IP fallback stays gone (`dbProxy.isIpAuthorized === undefined`) plus the session-matcher fail-closed matrix. Not changed (documented decision): `security.json`'s `trusted_subnets` setting and its settings API/UI remain — the panel still stores and serves it, but db-proxy no longer consumes it for authorization, so it is now inert for this feature; operators relying on it for proxy access should rely on the admin session instead (that is the point of the fix). [Later update: the field was since wired as the sole input to a global rate-limiter bypass — see "trusted_subnets wired as a global rate-limiter bypass (dead configuration fixed)" at the end of this file — it remains unused for db-proxy authorization.] ## 2.5 — Proxy strips upstream security headers and forwards panel session cookie `utils/db-proxy.js` previously wholesale-stripped security headers (`x-frame-options`, `content-security-policy`, etc.) from every proxied response and forwarded the incoming `req.headers` wholesale to upstream phpMyAdmin/pgAdmin backends, forwarding the ADPanel session cookie (`adpanel.sid`) and other sensitive panel cookies to third-party backends. ### Fix - **Outbound request headers built from empty object.** `buildProxyRequestHeaders` copies only allowlisted standard headers (`accept`, `content-type`, `user-agent`, etc.) plus application `x-*` headers (e.g. `X-pgA-CSRFToken`). Hop-by-hop headers, `Authorization`, and spoofable proxy headers (`X-Forwarded-*`, `X-Real-IP`) are explicitly denied. - **Strict cookie filtering.** `buildBackendCookieHeader` strips all panel cookies (`adpanel.*`, `adpanel_gate`, and configured stealth cookies) before passing cookies upstream. Only backend-issued session cookies (e.g., `pga4_session`, `phpMyAdmin`) reach the backend. - **Preserve upstream security headers.** `sanitizeUpstreamResponseHeaders` strips only hop-by-hop headers, stack fingerprinting (`Server`, `X-Powered-By`, `Via`), and obsolete headers. Upstream `content-security-policy`, `x-content-type-options`, and `referrer-policy` are preserved. - **Enforce clickjacking & framing defense.** `applyProxyResponseSecurityHeaders` enforces `X-Frame-Options: DENY` and appends a supplementary `frame-ancestors 'none'` policy (or a full fallback CSP if upstream provided none). - **Helmet isolation.** Panel-specific helmet headers (nonce-based CSP) are cleared from the response before applying proxy security headers to avoid breaking upstream inline scripts. ### Verification `scripts/verify-db-proxy-session-auth.js` contains a dedicated section (section 7) asserting all 27 checks covering request header allowlisting, cookie stripping, upstream CSP preservation, supplementary framing denial, and headerless fallback. All 86 checks in the test suite pass with 100% success. ## 2.1 — Panel-created DB users were all-powerful superusers Every database credential the panel issued through its UI carried server-wide administrative privilege, converting any single leaked credential into full database-server takeover: - MongoDB `createMongoUser` granted `root`, `userAdminAnyDatabase`, `dbAdminAnyDatabase`, `readWriteAnyDatabase` on `admin` (and the legacy `mongo`-shell path granted `root`). - The standalone MongoDB management endpoint granted `readWriteAnyDatabase`. - PostgreSQL `createPostgresUser` created `SUPERUSER CREATEDB CREATEROLE` roles; the pgAdmin bootstrap user (`createPostgresDbUser`) did the same. - MySQL was already correctly scoped (DML/DDL on `*.*`, no admin privileges) and served as the reference pattern. ### Fix New `utils/db-user-privileges.js` (pure, fail-closed builders; the security invariant lives in exactly one auditable place): - **MongoDB panel users** get `readWrite` + `dbAdmin` on a single per-user database (`user_`, deterministic; long names truncated with a short SHA-256 suffix so two users can never share a database). The install-time admin created by `installMongoDB` keeps the one reserved `root` account and is never re-shown or re-issued by the UI. - **PostgreSQL unified users** are `CREATE ROLE ... LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE` and own their per-user database, created idempotently via a `WHERE NOT EXISTS ... \gexec` guard (CREATE DATABASE cannot run inside the DO block). - **PostgreSQL pgAdmin bootstrap** is `NOSUPERUSER NOCREATEROLE CREATEDB` — a leaked pgAdmin session can no longer mint superusers or read every database; CREATEDB is kept because database creation is core pgAdmin functionality. - **Dollar-quote hardening**: passwords are embedded via randomly tagged dollar-quoted literals with two independent tags (DO block vs password literal — a shared tag let the DO-body scan terminate inside the password and execute the remainder as SQL, found by live testing). Tags are redrawn/fail-closed if they occur in the password; identifiers are rejected unless strictly `[A-Za-z0-9_-]` (no leading dash). - `createMongoUser`, `createMongoUserLegacy`, the standalone MongoDB user endpoint, `createPostgresUser`, and `createPostgresDbUser` all delegate to the shared builders and refuse (500/fail-closed) on invalid input. ### Regression tests `node scripts/verify-db-user-privileges.js` — 27 checks: - executes the generated mongosh eval scripts against a mock shell API and asserts the created/granted roles are exactly the scoped set, that the rescope script revokes exactly the dangerous `{role, db}` pairs, and that scoped roles are never flagged as dangerous; - asserts every emitted PostgreSQL statement contains no un-negated `SUPERUSER`/`CREATEDB`/`CREATEROLE`, that passwords round-trip through dollar-quoted literals byte-for-byte with tags absent from the password, and that the DO tag and password tag always differ; - static checks over `index.js`: all five creation paths use the shared builders, `installMongoDB` keeps exactly one reserved `root` admin, the MySQL grant list stays DML/DDL-only, and the 2.8 mutex contract holds. ### Migration for existing installations `node scripts/migrate-db-user-privileges.js` (dry run by default): - enumerates panel-created users from `database-config.json`, `mongodb-config.json`, `pgadmin-config.json`; protects the install-time MongoDB admin (`users[0]`), `--mongo-admin-user`, `--protect-user` entries, and reserved roles (`postgres`, `admin`, `root`, `pg_*`); - `--apply` re-issues scoped grants (PostgreSQL via psql stdin as the `postgres` OS user; MongoDB via authenticated `mongosh` or, without credentials, the panel's own maintenance-window pattern — temporarily disable authorization on a loopback-only bind, rescope, restore, with restore guaranteed in `finally` and a loud FATAL if it fails); - `--verify` is strictly read-only (it never disables authorization) and checks the live ground truth — `pg_roles` flags, `db.getUser()` role pairs, `SHOW GRANTS` for MySQL — exiting non-zero if any panel user still holds `SUPERUSER`/`root`/`*AnyDatabase`-class privilege; - MySQL needs no migration (path was always scoped); `--verify` reports any manually granted admin privileges. Validated end-to-end against a live PostgreSQL 18 cluster: legacy `t/t/t` roles rescope to `f/f/f` (unified) and `f/t/f` (pgAdmin), per-user databases are created and owned correctly, `--verify` detects a deliberately re-superusered account (exit 1), re-runs are idempotent, and `SET ROLE ; CREATE ROLE ...` is denied. ## 2.8 — Racy `mongodbOperationLock` boolean `mongodbOperationLock` was a module-level boolean with check-then-set semantics; safe only while no `await` sat between the check and the set. ### Fix Replaced by `mongodbOperationMutex` (`index.js`): a promise mutex whose `tryAcquire()` performs the check-and-set synchronously (atomic on the event loop), hands ownership to queued waiters on release, and ignores double-releases and stale-owner releases via epoch tickets. The three MongoDB mutation endpoints (create user, delete user, change password) acquire fail-fast and answer 429 when an operation is in progress, matching the previous contract; releases run in `finally` blocks. `acquire()`/`runExclusive()` exist if queued serialization is ever needed. The mutex is deliberately not reentrant. ### Verification Covered by `scripts/verify-db-user-privileges.js`: the mutex must exist, the old boolean must not be assigned anywhere, and all three mutation endpoints must acquire it. ## Unauthenticated heartbeat + client-trusted online gate (link-node setup) Finding: the node heartbeat endpoint (`POST /api/nodes/:id/heartbeat` in `nodes.js`) is reachable without an admin session (bootstrap by design), and the link-node wizard's "Complete" button (`public/js/settings.js`, `checkCreateNodeHealth`) enabled purely on `data.online` from `GET /api/admin/nodes/:id/stats`. Anyone who could guess a node UUID could forge a heartbeat (or answer the panel's stats probe with a canned `{"ok":true}` from the node's address) and make a fake node appear healthy through the whole setup flow — after which the panel schedules servers on it. ### Fix — cryptographic identity proof on every path to "online" All three legs now use the per-node HMAC secret the panel already issues (`utils/node-hmac.js`, HKDF from `PANEL_HMAC_SECRET`, persisted on the daemon as `panel.hmac_secret`): 1. **Signed stats probe with nonce echo** (`index.js` `probeNodeStatsVerified` ↔ daemon `verifyPanelProbe` in `main.go`): the panel signs `GET /api/system/stats` with the standard admin envelope (`action="probe"`, `subject="stats"`, fresh single-use nonce). A genuine daemon verifies the envelope with its shared secret and echoes the nonce in the response (`panel_nonce`). Only a matching echo yields `verified: true`; an impostor on a plaintext link or a rogue 200-ok server on the node host cannot produce it, and every probe's fresh nonce makes captured responses unreplayable. The response carries `verified` / `verificationAvailable` / `verifyReason` alongside the existing fields (fully additive — dashboard popups and the server wizard are unaffected). The same challenge is applied to `GET /v1/info` in `activeCheckNode` (`nodes.js` `fetchNodeInfoVerified`). 2. **Replay-resistant heartbeat** (`nodes.js` + `utils/heartbeat-auth.js`): when a per-node signing secret exists, heartbeats MUST carry `x-node-ts` / `x-node-sign` / `x-node-nonce` over `heartbeat|||`. The ±5 min drift window bounds a captured heartbeat's lifetime and the single-use nonce (in-memory replay cache, mirroring the daemon's `recordPanelNonce`) makes each heartbeat unique; presented bearer/body credentials are still verified as defense in depth. Panels without `PANEL_HMAC_SECRET` keep the exact legacy token-only path (no silent regression for unconfigured deployments). 3. **Client gate hardened** (`public/js/settings.js`): "Complete" now needs **two consecutive** stat samples that are both `online` **and** `verified` (or from a panel where verification is unavailable, still two consecutive online samples). A node that answers without proving identity shows an explicit amber "identity NOT verified" state and never unlocks the button. **Backward compatibility**: legacy daemons that ignore the signed headers still answer (200, no echo) → `verified: false, reason: "legacy-daemon"`, and the unsigned `/v1/info` fallback keeps fleet monitoring working; the UI surfaces the unverified state instead of silently trusting it. Once `PANEL_REQUIRE_NONCE` is rolled out fleet-wide, panels can treat `verified: false` as offline for admin workflows. ### Deployment flag closed — the master secret is now always configured The one operational requirement above ("set `PANEL_HMAC_SECRET` so verification engages") is itself resolved: panels no longer depend on the operator remembering the env var. `utils/panel-hmac-secret.js` resolves the fleet master at panel startup in both processes (`index.js` and the nodes service): 1. `PANEL_HMAC_SECRET` env — explicit operator config, always wins. 2. previously persisted master — `data/panel-hmac-secret.json`. 3. otherwise a fresh 256-bit master is generated and persisted (first boot). Persistence is race-safe for simultaneous boots (tmp file + `link(2)`, which fails with `EEXIST` instead of overwriting, so racing processes converge on one value — `rename(2)` would cause a split brain and is deliberately avoided), written with mode `0600`, and atomic (`link` publishes the file fully formed). Failure policy is fail-closed: a corrupt/unparseable existing file or an unwritable data dir returns "" (legacy, unsigned behavior) with a console warning explaining recovery — never a silently regenerated master, which would invalidate the derived secret inside every deployed node config. Operational notes: - `data/panel-hmac-secret.json` is state, not a cache: back it up with the rest of `data/`. Losing it (or restoring a panel without it) changes the master, and node configs carrying a derived `panel.hmac_secret` from the old master must be re-deployed — signed admin requests fail with `bad-signature` until then (probes/monitoring keep working via the legacy fallback). - Setting the env var later overrides the file; removing it falls back to the file. Only delete the file deliberately, with the re-deploy note above. - The resolver logs a one-time warning on generation so operators know the file exists. **Verification**: `panel_probe_test.go` (echo, replay rejection, bad signature, legacy path unchanged, signed-without-bearer still rejected), `utils/heartbeat-auth.test.js` (envelope accept/replay/expiry/forgery, nonce-smuggling, cache TTL), and `utils/panel-hmac-secret.test.js` (env precedence without file creation, generate+persist+0600+reuse, loser-converges EEXIST race, corrupt/blank-file fail-closed with file left untouched, unwritable-location degradation, unreadable-target fail-closed); full suites `go test ./...`, `node --test utils/heartbeat-auth.test.js` and `node --test utils/panel-hmac-secret.test.js` pass. ## 3.2 — one-time setup command put the node credential in shell history (2026-09-03) **Finding (Medium)**: `oneTimeCommand()` built the setup command by wrapping the full `config.yml` — the daemon bearer token (twice: top-level `token` and `auth.token`) plus the derived `panel.hmac_secret` — inside a heredoc the admin pasted into a terminal on the node host. Anything pasted is written verbatim into `~/.bash_history` / zsh history and terminal scrollback, so a long-lived bearer credential (and HMAC key) ended up at rest on a third machine — the node host — outside the panel's encrypted-at-rest envelope, on exactly the machines most likely to be shared, casually reimaged, or have dotfiles synced/backed up. **Fix — fetch-on-boot, secret-free command.** The pasted command no longer contains any secret material: ``` curl -fsSL '/api/node-bootstrap/' | bash ``` - `oneTimeCommand()` (nodes.js) mints a fresh enrollment pair per reveal and returns only the one-liner above. The legacy heredoc builder (`buildNodeConfigRestartCommand`) was removed. - `GET /api/node-bootstrap/` serves the bootstrap script once; the script then fetches `GET /api/node-bootstrap//config.yml` over TLS from the panel. Secrets exist only in the TLS stream and in the final `/var/lib/node/config.yml` (mode 0640, `adaemon:adaemon`) — never in history, scrollback, or the command string. - Both IDs are 32 random bytes (base64url, 43 chars). Each download **consumes** the ID before any data is built — first download wins, every replay gets `410 Gone`. Unconsumed entries expire after 10 minutes (`NODE_ENROLL_TTL_MS`, default 10 min). The store is in-memory (matches the panel's single-process deployment, like the heartbeat nonce cache); a panel restart just means the admin reveals a fresh command. - The script handler refuses to serve when the paired config link is already consumed/expired (fail closed with a clear message instead of a command that dies halfway on the node), and both handlers rate-limit per IP (30/min, `NODE_ENROLL_RATE_MAX`), log every serve/consume, and mark responses `no-store` + `nosniff`. - Transport security: `isOpenNodeBootstrapRoute()` (nodes.js, wired into index.js `isOpenNodeRoute()`) classifies the endpoints as open routes only for GETs with an exact enrollment-ID shape; the TLS requirement is applied right beside that classification in index.js via the same trusted-proxy-aware `isRequestSecure()` + explicit `ALLOW_INSECURE_NODE_BOOTSTRAP=1` lab override the `config.yml` bootstrap endpoint uses. Anything else falls through to the normal auth chain. - The downloaded config is validated by the script before it can replace an existing one (`uuid:`/`token:` markers) so a captive portal or proxy error page cannot clobber a working config; deploys via `install -m 0640`, then restarts the daemon service (systemd/OpenRC/SysV, same as before). **Scope notes**: the step-up verified reveal (`POST /api/nodes/:id/one-time-command`) is unchanged — identity verification, audit logging and reveal-on-screen TTL still apply; only the artifact content changed. The config.yml reveal endpoint and the daemon installer flow (`install-daemon.sh`, signed installer tokens) are untouched. **Verification**: `utils/node-bootstrap.test.js` (15 tests: enrollment pair minting, single-use consumption and replay `410`, TTL expiry, malformed-ID rejection, LRU cap eviction, limiter windowing, script content guarantees — URL embedded single-quoted, no secret channels, no config echo — plus full HTTP flow tests over a real express listener: script-once/config-once, wrong-kind fail-closed, dead-paired-link refusal, missing-node 410 with consumption, garbage IDs never 500, and 429 tripping) and `utils/node-bootstrap.integration.test.js` (end-to-end through the real exported nodes.js app with a stubbed DB: the command returned by `oneTimeCommand()` mints into the same store the mounted routes consume, the served script contains no credential material, the config download delivers the bearer token + derived hmac secret exactly once, and both links are dead afterwards). `npm test` runs the full JS suite (33 tests pass). The generated bootstrap script additionally passes `sh -n`, `bash -n` and `dash -n` syntax checks. ## 3.3 — Node creation accepted arbitrary addresses → admin-gated SSRF (2026-09-03) **Finding (Medium)**: `POST /api/nodes` accepted any non-empty string as `address`; the panel then dials that address for every health check, port probe and API call and renders the results back in the UI. Even though node creation is admin-gated, this is a live SSRF primitive: a hijacked admin session (the assumed threat model — see the step-up grace findings) could point a node at `http://169.254.169.254/latest/meta-data/`, `http://127.0.0.1:6379/` or any internal service and use the panel's probing as an internal network scanner. On cloud hosts the metadata endpoint yields cloud credentials. `activeCheckNode`/`callNodeApi` did no validation beyond "non-empty"; only Cloudflare-mode addresses were constrained (DNS check against real Cloudflare ranges). **Fix — three fail-closed layers in the new `utils/node-ssrf-guard.js`.** 1. *Creation/update-time validation* (`validateNodeAddressInput`, wired into `POST /api/nodes` and `PATCH /api/nodes/:id`): the literal address is classified and loopback (127/8, ::1), link-local (169.254/16, fe80::/10), private (10/8, 172.16/12, 192.168/16, fc00::/7), CGNAT (100.64/10), benchmarking (198.18/15), documentation (192.0.2/24, 198.51.100/24, 203.0.113/24, 2001:db8::/32), multicast/reserved (224/4, ff00::/8) and the cloud metadata targets are rejected — unless the deployment explicitly opts in with `ADPANEL_ALLOW_PRIVATE_NODES=1` for genuine LAN deployments. Hostnames must additionally not be reserved internal names (`localhost`, `.local`, `.internal`, `.home.arpa`, `metadata`) and must resolve, with **every** resolved address public. Unparseable input fails closed. Embedded-IPv4 smuggling forms inside IPv6 literals are unwrapped and the embedded address is classified with the same rules: IPv4-mapped `::ffff:10.0.0.1`, deprecated IPv4-compatible `::127.0.0.1`, 6to4 `2002:7f00:1::`, Teredo (obfuscated client address) and NAT64 `64:ff9b::7f00:1`. Bracketed and zoned forms are normalized first. Under-Cloudflare nodes skip this check because `verifyCloudflareProxiedAddress()` is strictly stronger there (the name must resolve exclusively to Cloudflare's public edge ranges). `additional_ips` are bind/bookkeeping metadata the panel never dials, so they get a bounded syntax check (shape, charset, count ≤ 32) rather than the full filter — injection junk is still rejected. 2. *Connect-time re-validation* (`guardedNodeLookup`, attached as the socket `lookup` to every outbound node request — `httpRequestJson`, `httpRequestJsonWithBody`, `httpJson`, `callNodeApiOnce`, the multipart upload proxy, the file-download proxy, the SSE logs proxy, and `tcpCheck`): the addresses the socket would actually connect to are re-validated at request time, which closes the two bypass classes a one-off string check cannot. (a) getaddrinfo numeric shorthand — `dns.lookup("127.1")`, `dns.lookup("2130706433")` and `dns.lookup("0x7f000001")` all resolve to 127.0.0.1 (verified); the WHATWG URL parser additionally canonicalizes those forms in the host, so the synchronous pre-flight below catches them even earlier. (b) DNS rebinding — a public-looking name re-pointed at an internal IP is re-resolved and re-checked at every connect; only validated literal addresses are ever connected to, and a 15 s cache serves previously validated literals only (a stale entry cannot smuggle a fresh resolution). Node's `net.Socket` isIP fast path skips custom `lookup` implementations for literal-IP hosts (verified on Node 22), so every primitive also runs the synchronous `assertNodeUrlHostAllowed(fullUrl)` pre-flight before issuing the request — literal private targets are refused before any socket exists. Blocked connects log a rate-limited `console.warn` (one per host per minute) telling the operator about `ADPANEL_ALLOW_PRIVATE_NODES=1`, and surface as the node simply being unreachable (status 0), exactly like a down daemon. 3. *Redirect safety*: the outbound node client uses Node's core `http`/`https` modules, which never follow redirects — a 302 cannot bounce a request to a different host. Nothing needed disabling; this property is documented here and in the guard so it survives any future client swap. **Deliberate exemptions**: `resolveLoopbackNodeBase()` still probes `127.0.0.1`/`localhost` on the panel host — that is the designed same-host fallback (daemon and panel share a machine, the public address is not hairpin-reachable). It is exempt from the guard explicitly (`bypassAddressGuard`): fixed targets, no user input, and its result is only used when the daemon echoes the node's UUID, which an attacker does not know. Same-host deployments registered with a public address keep working through it; cross-host LAN deployments set `ADPANEL_ALLOW_PRIVATE_NODES=1`. **Compatibility notes**: pre-existing private-address nodes keep working via the UUID-gated loopback fallback when the daemon really is on the panel host; otherwise they surface offline after the upgrade, with the rate-limited `[ssrf-guard]` warning explaining why — set `ADPANEL_ALLOW_PRIVATE_NODES=1` to restore them. `PATCH` re-validates only *changed* addresses, so admins are never locked out of editing other fields of a legacy node. The `/api/nodes/:id/build` endpoint only toggles TLS/Cloudflare flags and never mutates the address, so it introduces no new dialable target. No other code path writes `address` (verified: `INSERT INTO nodes` / `UPDATE nodes SET` writers only touch token/health fields). **Verification**: `utils/node-ssrf-guard.test.js` (25 tests: IPv4/IPv6 classification incl. all embedded-IPv4 smuggling forms and boundary neighbors, host extraction accepted/rejected shapes, creation-time validation with stubbed DNS — reserved names, mixed public/private resolution, unresolvable names, env opt-in — guarded-lookup caching/family handling/ error propagation, the pre-flight block matrix, and end-to-end integration through the exact primitive pattern over a real HTTP listener: literal loopback and hex-shorthand targets refused with `EADPANEL_SSRF_BLOCKED`, traffic delivered under the env opt-in, 302 responses surfaced as-is without following). Full `npm test` suite: 58/58 pass (33 pre-existing + 25 new). `node --check` clean on `nodes.js`, `utils/node-ssrf-guard.js` and the test file; `nodes.js` module-load smoke-tested (boots, exports intact). The wiring audit (grep) confirms all eight dynamic outbound request sites carry both the pre-flight and the guarded lookup; the only unguarded outbound fetch left is the fixed Cloudflare IP-list download in `httpsGetText`. --- # Template Startup Pipeline Hardening (2026-09-03) Remediation of the template-system review findings F1–F8 (raw docker in the template system, managed-startup script injection, template-granted root, store supply chain, legacy dead code). All changes verified with `go build` + `go vet` + full `go test .` suite, `node --check` on every touched JS file, `node --test` (58/58), and JSON validation of every template file. ## F1 — Managed startup scripts (`adpanelStartup`) are now validated everywhere `sanitizeADPanelStartupInput` only stripped NULs/CR and truncated; the script then ran via `sh -lc` with no content checks at any layer. - New shared validator `validateADPanelStartupScriptInput` (`index.js`) and its mirror `validateADPanelStartupScript` (`main.go`). Both enforce the 32 KiB cap and reject the highest-value host-boundary primitives: container runtime sockets (`docker.sock`, `podman.sock`, `containerd.sock`), container runtime CLI invocations (`docker run/exec/ build/...`, `podman`, `nerdctl`, `nsenter`, `unshare`), `--privileged`, `--pid=host`, `--network=host`, `/proc/1/root`. - Enforcement points: template create route, template update route (HTTP 400 with the reason), and `normalizeTemplateDockerForRuntime` — the choke point for templates.json loading, template-store sync, template-change reinstalls, and server creation (violating scripts are dropped with a `[templates]` warning). The node agent additionally rejects violating scripts on its server-create/update API (HTTP 400) and logs a `[security] WARNING` for pre-existing stored scripts at start time (they are not blocked at start so upgrades cannot strand running servers). - Best-effort by design: a managed script remains arbitrary in-container shell (that is the product's managed-runtime feature). The container boundary itself is enforced by cap-drop-all, no-new-privileges, the bind allowlist, and (now) default-non-root — see F3. ## F2 — `{{VAR}}` substitution into `sh -lc` is no longer a template-injection sink `renderADPanelStartupTemplate` spliced raw environment values into the script text before shell execution, so any value containing `$( )`, `` ` ``, `;`, quotes, etc. executed as code. The shipped cs2 template even relied on splices inside double quotes (`+hostname "{{SERVER_NAME}}"`), which is where a malicious value breaks out. - Rewritten as a quoting-context-aware renderer (`main.go`). `{{KEY}}` tokens are rewritten to `${KEY}` shell references and the values travel through the container environment: variable expansion is data-only, values are never re-parsed as code. Unquoted and double-quoted contexts (including inside `$( )`) use `${KEY}`. - Single-quoted contexts cannot express `${KEY}` expansion; there the value is spliced with the `'\''` idiom, which provably stays shell data and is byte-identical to the old splice for values without single quotes (keeps cs2's `printf %s ' +sv_setsteamaccount {{STEAM_GSLT}}'` behavior). - Non-identifier keys (`my-key`) splice as one fully quoted word; unknown keys keep their literal `{{KEY}}` token (legacy behavior). Rewritten keys are backfilled into the exported env so `${KEY}` always resolves. - `renderRuntimeEnvTemplates` keeps the historical textual splice under a new name (`renderTemplateValueTextual`) with an explicit contract comment: env values are literal Docker env data, never shell code. - New test file `startup_template_render_test.go` locks the contract down, including hostile values (`$(reboot); rm -rf /; \`id\``) in every quoting context and a full cs2 end-to-end render. ## F3 — Templates can no longer request a root container `runAsRoot: true` (fivem/redm) previously flowed from template files through `sanitizeDockerTemplatePayload` and `normalizeTemplateDockerForRuntime` into the server runtime, where the agent granted root (empty `User`) plus extra capabilities (CHOWN, FOWNER, SETUID, SETGID), and the CFX layout normalizer even force-enabled it. - `sanitizeDockerTemplatePayload` no longer emits `runAsRoot`; `normalizeTemplateDockerForRuntime` hardcodes `runAsRoot: false`; `dockerConfigForNodeRequest` no longer forwards the field. - `runAsRoot: true` removed from `templates.json` (fivem) and from `Templates/games/fivem.json` / `redm.json` / `github/Games/fivem.json` / `redm.json`. - Agent side: every container-user and capability decision now goes through `templateMayRunAsRoot`, which requires the node operator to explicitly set `ADPANEL_ALLOW_TEMPLATE_ROOT=1`. Default is deny; a denial logs `[security] denying runAsRoot request ...`. The CFX force-root and the two request handlers that persist the flag are gated the same way. - Rollout: existing stored runtimes that still carry `runAsRoot: true` switch to non-root on nodes without the flag. If a legacy workload genuinely needs the image's root bootstrap, the operator can set `ADPANEL_ALLOW_TEMPLATE_ROOT=1` on that node; the long-term fix is re-owning the server directory. ## F4 — Template store ingestion is schema-checked, not pass-through - `sanitizeDockerTemplatePayload` (the store-sync normalizer) no longer passes `console` through raw: `sanitizeConsolePayload` accepts only the normalized `{type, targetProcesses?}` shape (mode whitelist, 12 targets, 120 chars each, deduped — matching the agent's `sanitizeConsoleProcessTargets` bounds) and rebuilds string/array shorthand forms. - Volume specs are validated by `sanitizeVolumeSpec`: `host:container[:mode]` with an absolute container path, no whitespace, and a host side restricted to `{PLACEHOLDER}` tokens or named volumes. Absolute host paths (`/etc:/etc`, `/var/run/docker.sock:...`) are rejected at ingestion; the agent's bind allowlist (`resolveStructuredBinds` → `ensureResolvedUnder`) remains the runtime backstop. - `runAsRoot` from remote templates is dropped (F3). - Store sync still fetches hourly from `antonndev/ADTemplates`; content hashes in `Templates/manifest.json` are download-time hashes, so the origin GitHub repo remains the trust root — pinning/signing is a follow-up if third-party stores ever become a thing. ## F5 — Legacy raw-docker machinery deleted, not kill-switched Removed ~1,120 lines: `executeStartupCommand`, `buildEffectiveDockerCommand`, `validateDockerRunCommandSafety`, the `legacyRawDockerStartupCommandsDisabled` flag, and the now-orphaned helpers (`dockerRunInteractiveArgs`, `dockerRunInteractivePrefix`, `extractContainerPortFromMapping`, `extractHostPortFromMapping`, `extractDockerImageFromCommand`, `normalizeDockerImage`). Nothing referenced them; the raw path is gone, not one edit away from resurrection. The JS-side `extractHostPortsFromDockerCommand` parser remains only as a display helper for legacy stored strings — it never executes anything. ## F6 — Artifacts and content cleanup - Deleted the atomic-write crash leftover `Templates/games/redm.json.350874.1786882282807.tmp`; `pruneTemplateStoreCategory` now also removes `*.tmp` leftovers so the next sync self-heals. - Kept (documented decision): cs2's `$( [ ... ] || printf %s ... )` conditionals — they are plain POSIX shell that the fixed renderer handles safely (F2); re-authoring them as argv would risk breaking existing CS2 servers for zero security gain now that values cannot execute. The image-default entrypoint `startupDisplay` strings (ark's `/docker-entrypoint.sh`, palworld, rust, hytale) are accurate display-only descriptions and stay. ## F7 — Variable grammar map (one engine per context) After F2 the grammars are: | Grammar | Context | Engine | Injection risk | | --- | --- | --- | --- | | `{{KEY}}` | Managed startup script (`sh -lc`) | `renderADPanelStartupTemplate` — rewrites to `${KEY}`, env-delivered | none: values are expansion data, never spliced as code | | `{{KEY}}` | Env values (Docker env, literal) | `renderTemplateValueTextual` — textual splice | none: env values are never parsed as shell | | `{RAM_MB}`, `{DATA_DIR}`, `{START_FILE}`, ... | Process command template | `renderRuntimeCommandTemplate` — spliced, then re-validated (`validateRuntimeProcessCommand`) and parsed to argv | none: exec'd directly, no shell | | `{BOT_DIR}`, `{SERVER_DIR}`, `{DATA_DIR}` | Volume specs / paths | string substitution before the bind allowlist | none: never reaches a shell | The frontend may still classify and display with any of these, but every execution-relevant substitution now has exactly one audited engine. ## Verification - `go build ./...`, `go vet ./...` clean; full `go test .` suite green (includes the new renderer tests and the updated CFX-layout test, which now asserts both the default deny and the `ADPANEL_ALLOW_TEMPLATE_ROOT=1` opt-in). - `node --check` clean on `index.js` and `utils/server-template-payload.js`; `node --test` 58/58. - All shipped template JSON validated; cs2/dayz/zomboid/7dtd startup scripts pass the new validator; hostile fixtures (docker.sock binds, nsenter/ podman scripts, root requests, junk console configs) are all rejected or stripped. # Env Payload Invariants (2026-09-03) ## Audit finding 8 [Low] — env sanitization enforced almost no invariants `sanitizeEnvPayload` (`utils/server-template-payload.js`) blocked only `__proto__`/`constructor`/`prototype`; keys could contain `=`, whitespace or control characters, and values were arbitrary (NUL included, unbounded). That was safe only because the node happens to launch containers via argv today — the safety silently depended on every future consumer keeping that property. Meanwhile the actual container-env sinks split entries on the first `=` themselves: - Docker Engine API container create takes `Env: ["KEY=VALUE", ...]` and splits on the first `=` (`envMapToList` at the three create sites). - The installer builds `docker run -e KEY=VALUE` argv. So a key like `PATH=/evil` or `LD_PRELOAD=/lib/x` in template JSON was already being *renamed* at the sink (container sees `PATH`, not `PATH=/evil`), and could carry any name past a future key-based allowlist/denylist. `=`-in-key was the core framing bug; whitespace, NUL and control characters break `KEY=VALUE` / argv / env-file framing the same way, and NUL in a value makes runc reject the whole container start. ## Fix — one invariant set, enforced at the parse boundary and at every sink New invariants (documented at each enforcement site): 1. **Key is identity.** After trimming, a key must match `[A-Za-z0-9_][A-Za-z0-9_.-]*` — no `=`, no whitespace, no NUL/control characters, nothing flag-looking (`-FOO`). The charset is exactly what the `{{KEY}}` startup-template tokenizer accepts, so every key that survives sanitization stays referenceable from startup templates, and non-identifier keys like `my-key` keep working through the node's quoted-splice path (`TestRenderADPanelStartupTemplateNonIdentifierKeyQuotedSplice`). 2. **Values are opaque bounded strings.** NUL stripped (execve cannot carry it), max 32768 bytes; newlines stay legal (PEM/JSON blobs) because no consumer writes env to line-oriented files and the startup renderer passes values as quoted/expansion data, never code. 3. **Bounded payloads.** Keys ≤ 128 bytes, ≤ 128 entries per payload. 4. **Prototype-pollution keys stay blocked** (`__proto__`, `constructor`, `prototype`), so the sanitized object remains safe to merge/assign panel-side. Enforcement points — the invariant now holds even if a future consumer forgets the argv property: - JS panel side: `sanitizeEnvPayload` rewritten with the invariant set; the PUT `/api/settings/templates/:id` endpoint no longer carries its own weaker inline copy and routes through the shared sanitizer (which also re-sanitizes stored env on every save, so legacy data self-heals). `sanitizeDockerTemplatePayload` / `sanitizeDockerInstallPayload` inherit the invariants for store ingestion and the dashboard assistant. - Go node side, all untrusted env passes through the same rules: - `runtimeEnvMap` (every `runtime.env` JSON decode: minecraft/runtime/cfx starts, rust normalization, command rendering) sanitizes via `sanitizeEnvMap`. - `envMapToList` (Engine API `Env` for all three container-create sites) emits only normalized entries, in sorted order for deterministic container configs. - `dockerEnvArgs` (new) builds the installer's `-e` pairs from `sanitizeEnvMap` output — defense in depth at the argv boundary, no longer relying on `mergeStringEnv` upstream. - `mergeStringEnv` and `normalizeTemplateInstallConfig` upgraded from a narrow `=\0\r\n` filter to the full invariant via `normalizeEnvEntry`. Behavior change for hostile/legacy data only: entries that violate the invariants are dropped (never renamed), consistently on both sides. All 31 env entries across the 5 shipped templates pass the new sanitizer byte-identical; legitimate multi-line values and `my-key`-style keys are unaffected. ## Verification - `go build ./...`, `go vet ./...` clean; new `env_invariants_test.go` covers the framing property structurally (for any map, every emitted `KEY=VALUE` token splits back to the sanitized key — a `=`-bearing key can never rename a variable at either sink), the caps, deterministic entry-cap behavior, and `{{KEY}}` referenceability; full `go test .` green. - New `utils/server-template-payload.test.js` (13 tests) covers the JS invariants through `sanitizeEnvPayload`, `sanitizeDockerTemplatePayload` and `sanitizeDockerInstallPayload`; `npm test` 74/74. # Template Step-Up & Rate Limiting (2026-09-04) Remediation of finding 6 (Medium): template create/update/delete and the template-store force-sync only had the session-level `isAdmin` check, while node deletion already demanded a 2FA/password step-up (`requireDestructiveActionStepUp`). Templates compile straight into the container launch configuration (image, entrypoint, env, install script), so a hijacked admin session could seed a malicious template and start servers from it with zero re-auth friction. ## Changes Backend (`index.js`), all four endpoints now carry the shared step-up gate plus the verification rate limiter (`sessionRevoke2faRateLimiter` — 8 credential attempts per session / 24 per account per 10 min, requests without a credential payload are not counted): - `POST /api/settings/templates` (create and store install) — step-up runs after input validation (a malformed payload answers 400 without spending a credential prompt) and before anything is persisted; scope `template:` (validated id), subject `Template create ""`. - `PUT /api/settings/templates/:id` — same placement contract (after the last 400-check, before the template is persisted); scope `template:`. - `DELETE /api/settings/templates/:id` — after the 404 / in-use checks, before the list is mutated; scope `template:`. - `POST /api/settings/template-store/sync` (force sync) — scope `template-store:sync`, deliberately separate so a template grant cannot be burned by a sync and vice versa. Grace semantics: a fresh verification mints a grant bound to the action's scope, so re-saving or deleting the SAME template within the grace window (5 uses / short TTL) does not re-prompt; other templates, nodes and syncs still require their own verification. An unscoped grant (e.g. freshly minted by the node-create wizard) may be adopted once by a scoped action — the pre-existing, intentional design shared with every other step-up endpoint. Frontend (`public/js/settings.js`): - `sendNodeWriteWithStepUp` generalized into `sendGuardedRequestWithStepUp` (same body; the node helper is now a thin alias, node call sites untouched). - Template create/edit save, template delete, and store install now send the first attempt credential-free (a live server-side grant authorizes it silently); on a 403 step-up challenge the shared Security Verification modal collects a password/2FA code and retries in place, re-prompting on rejection or 429. DELETE retries carry the credential in the JSON body — the global body parser already covers non-GET methods (same mechanism as the existing server-delete step-up flow). - Read endpoints (`GET /api/settings/templates`, `GET /api/settings/template-store/*`) intentionally remain prompt-free. ## Verification - `node --check` clean on `index.js` and `public/js/settings.js`; full `npm test` green (77/77). - Challenge contract re-traced end to end: challenge bodies (`password-required` / `2fa-required` / `invalid-*` / `verification-rate-limit` plus `revokeSecurity`) match `isStepUpChallengeResponse`; the modal's credential field reconfigures from the challenge's `authMethod`; cancel paths surface explicit "nothing was changed" copy. --- # Security Fixes — Follow-up Audit (2026-09-04) ## Finding 5 [Medium] — Local override directory silently merged into the store as vetted `/github//*.json` (the template-store local-override channel, `index.js`) was merged into the store cache on every sync with full trust: - Any local writer to that directory (world-adjacent process, container with a bind mount over the app dir, drifted permissions, backup tooling, malicious dependency postinstall) got its templates listed to admins as ordinary store items — the install step-up was then completed *by the admin*, laundering the attacker's image/env/install script into a template every user can deploy. Zero panel credentials required. - An override whose filename matched an upstream file **replaced** the manifest entry for the vetted template (`minecraft.json` etc.), so a silently swapped payload hid behind a known name. - `readTemplateStoreCategoryFromCache` fabricated github.com / jsdelivr URLs (`meta.html_url || templateStoreGithubBlobUrl(...)`) for any cached file lacking them — exactly the local-override case — so unvetted local files rendered with links that "proved" upstream provenance. - The local read path enforced none of the remote path's limits: no size cap, no symlink/ownership/permission checks. ### Remediation (defense in depth) Panel (`index.js`): - **Opt-in, off by default.** `ADPANEL_TEMPLATE_STORE_LOCAL_OVERRIDES=1` is required for the merge to run at all. When the directory is non-empty but the feature is disabled, one startup warning names the env var — no silent behavior change. - **Filesystem trust checks when enabled** (`templateStoreOverrideTrustRejection`): category dirs and override files must be real dirs/regular files (lstat — symlinks refused), owned by the panel uid (or root), and not group/world writable (`mode & 0o022`). Files are additionally capped at `TEMPLATE_STORE_FILE_MAX_BYTES`, matching the remote fetch path. Rejections are logged with the path and reason. - **No shadowing** (`selectTemplateStoreLocalOverrideDisposition`): an override colliding with an upstream filename is skipped — the upstream entry always wins. Skips surface as sync warnings in the manifest (`warning`), the store API `cache` payloads, and `templateStoreLastSyncWarning`. - **Honest provenance at serve time** (`templateStoreCacheFileProvenance`): only files the manifest attributes to the upstream repo (`github-raw` / `jsdelivr`) may carry upstream URLs; local overrides and orphaned cache drops get `untrusted: true` with empty `html_url`/`download_url`. Override manifest entries also carry `untrusted: true`. - Store `cache` API payloads now include `warning` and `localOverridesEnabled` so operators can see the channel state. Frontend (`public/js/settings.js`, `public/settings.css`): - Store items carry `source`/`untrusted`; untrusted cards render an amber **"Local override"** badge (with tooltip) instead of blending in. - Installing an untrusted item requires an explicit `confirm()` dialog spelling out that the file is unvetted, and the credential step-up modal subtitle/reason/confirm-button all name it as a LOCAL OVERRIDE. ### Verification - New suite `tests/template-store-local-override.test.js` (9 tests, vm extraction per repo convention): disabled-by-default, accepted trusted file, group-writable file / world-writable dir / symlink / foreign-uid / oversized rejections, shadow refusal, and serve-time URL fabrication refusal. - `node --check` clean on `index.js` and `public/js/settings.js`; full `npm test` green. ### Operator notes To keep using local overrides (development/contribution workflow): 1. `ADPANEL_TEMPLATE_STORE_LOCAL_OVERRIDES=1` 2. Ensure `/github//` and the JSON files are owned by the panel user and not group/world writable (`chown`, `chmod 755`/`644`). 3. Rename any file that matches an upstream filename — collisions are skipped by design. Existing deployments: any override files already merged into `Templates//` by the old code are pruned on the next successful sync (disabled feature → not in `keepNames`), and until then they are served with `untrusted: true` and no upstream URLs. Categories that relied on locally-shipped templates will lose those store entries until an operator explicitly opts back in. Residual risk: the permission/ownership checks are path-based, so a local attacker with write access to the category directory could swap a file between the `lstat` and the read (TOCTOU). The layering above is what carries the guarantee: the channel is opt-in, the file must remain panel-owned at read time, and the installing admin sees an explicit unvetted-content warning and completes credential step-up. Operators who need stronger guarantees should keep the feature disabled and submit templates to the upstream repo. ## Finding 2 [High] — The install UI hides exactly the fields that matter The template-store card rendered only the marketing surface — name, description, docker image (`renderTemplateStoreCards`). The payload actually submitted by "Install" (`buildTemplateStoreInstallPayload`) cloned the entire store JSON and POSTed it to `POST /api/settings/templates`, carrying `docker.install` (a shell script executed in a separate installer container, with its own image and env), `docker.volumes`, `docker.env`, and the runtime `command`/`adpanelStartup`. The only "review" surface was the step-up modal's reason string, which *named* those fields but showed none of their values, so "install what you see" was structurally false: an approving admin authorized a summary while persisting whatever the page's JS sent. A compromised admin session (or any script running in it, e.g. through a store-provided description) could also submit content different from what the store listing served. ### Fix — review the full payload, then let the panel install its own copy Frontend (`public/js/settings.js`, `views/settings.ejs`, `public/settings.css`): - **Mandatory pre-install review dialog.** Every install now opens a dialog built from a new pure helper `summarizeStoreTemplatePayload`, which mirrors `constructTemplateDefinition` field-for-field (same destructure precedence, same env sanitization, same install-job clamps, same workdir auto-volume, same managed-startup suppression of the plain command). It renders: identity (id/category/source), container launch config (image:tag, default port, ports + protocols, workdir, console), volumes, environment variables (keys **and** values), the runtime command and/or the full managed startup script, and the complete install job (installer image, mount/runtime paths, timeout, storage floor, installer env, and the entire script in a scrollable block). A footnote states that nothing else is submitted. All content is inserted via `textContent`/`createElement` — store JSON is third-party content, so the review surface cannot become an XSS sink. - **Card risk chips.** Cards now show compact chips for the executable fields they carry ("Install script", "Startup script", "Command", "Env ×N", "Volumes ×N") so the blast radius is visible before clicking Install. - **Fail-closed reference install.** The install request no longer submits template fields at all — only `{category, fileName, entryIndex, sha256}` (`entryIndex` names the card inside a multi-template array file; the listing renders each array entry as its own card sharing one file hash). If the hash or the review dialog is missing, nothing is sent. Backend (`index.js`): - **New `POST /api/settings/templates/store-install`.** Takes the reference (category + file name + entry index + sha256), resolves the template content from the panel's own store cache via the pure, unit-tested `resolveStoreTemplateInstallEntry` (unknown file → 404, hash drift → 409 `store-template-changed`, out-of-range index or non-object entry → 404), and pins it to the hash: a store re-sync (or an edited local override) between review and install answers `409 store-template-changed` instead of installing un-reviewed content — the client then drops its cached listing and re-renders so the next click reviews the new content. The persisted template is built by the same constructor the create endpoint uses, with the same id/name fallbacks the listing applied. Auth, `sessionRevoke2faRateLimiter`, and credential step-up (scope `template:`) match the create endpoint; validation answers 400 before a credential prompt is spent; the duplicate-id check stays after step-up, as before. - **Per-file `sha256` in the store listing** — added by `readTemplateStoreCategoryFromCache` and echoed back by the client, binding the reviewed listing to the persisted object. - **`constructTemplateDefinition` extracted** from `POST /api/settings/templates` (behavior preserved verbatim; validation now fully precedes step-up, so invalid ports/env no longer burn a credential prompt) and shared with the install route, so both ingestion paths enforce byte-identical invariants. ### Adjacent bug fixed en route - `PUT /api/settings/templates/:id` referenced `sourceDocker` without declaring it (a `ReferenceError`, i.e. a broken update on every successful save). The declaration now mirrors the create path. ### Verification - New suite `tests/template-store-install-review.test.js` (12 tests, vm extraction per repo convention): constructor persists the full executable payload; rejections (missing image, invalid id, raw startup command, relative workdir, invalid ports, embedded shell operators, blocked startup patterns, invalid template image URL); workdir auto-volume; server slugify parity with the frontend; **summary == persisted object** (including a check that every persisted `docker.*` key is covered by the review); managed-startup precedence; reject-shape surfacing (`startup_command`, invalid ports); install-job sanitizer mirroring; empty-payload safety; reference resolution (entry selection in array files, 409 hash drift, out-of-range/non-object entries) and the client card carrying the hash + entry index the reference needs. - Ad-hoc run of the resolution + constructor over every cached store file (all categories): 14/14 construct cleanly. - `node --check` clean on `index.js` and `public/js/settings.js`; `views/settings.ejs` compiles; full `npm test` green (95/95). ### Residual risk The review dialog shows the template as submitted; the panel's runtime normalization of `command` (shell-wrapper unwrapping) can only *narrow* what runs, never add to it, and the persisted form is what the invariant tests pin. The hash pin is as strong as the store cache directory's integrity — which is the existing threat model shared by the listing itself (local override trust checks, audit finding 5 above). ## Finding 3 [High] — install scripts bypassed the template command validator by design `docker.command` is validated as pure argv (shell-wrapper unwrapping, shell operator / expansion rejection, container-runtime CLI rejection) on every panel path and again at the node, but the two sibling executable fields had a different reality: - `install.script` (the "Install script" textarea, store templates, egg imports) is a full shell script executed in the installer container, and got only NUL-stripping and a length cap (`cleanScript`) — no semantic validation anywhere. - `adpanelStartup` was boundary-validated on manual create/update and at the node, but the dashboard-assistant path (`sanitizeDockerTemplatePayload`) forwarded it unvalidated, relying solely on the node's 400. The policy promise ("no shell semantics reach execution unchecked in templates") was therefore an illusion for the one field that is *entirely* shell. ### Policy (now explicit) Templates carry three executable surfaces with different execution models: | Field | Model | Rule | |---|---|---| | `docker.command` | argv, no shell | No shell semantics at all (unchanged). | | `adpanelStartup` | shell in the server container | Anything inside the boundary; no runtime sockets/CLIs, namespace tools, or host namespaces. | | `install.script` | shell in the installer container | Same boundary rule **plus whole-word runtime-tool rejection** (`docker`, `podman`, `nerdctl`, `ctr`, `nsenter`, `unshare`): the installer image is attacker-chosen and networked, so a runtime reference there can only be an escape attempt — no legitimate install script manages containers. | Ordinary installer content (apt-get, curl/wget — including the `curl | sh` pattern, git, tar, steamcmd) is explicitly *not* blocked; every shipped template and store file was scanned against the pattern set before the rule was chosen (zero hits; `startupDisplay` strings like `/docker-entrypoint.sh` are display-only and are not validated). ### Changes - **`utils/server-template-payload.js`** — new shared policy home: `validateADPanelStartupScriptInput` (moved verbatim from `index.js`) and `validateTemplateInstallScriptInput` (same boundary pattern table plus the stricter runtime-word rule). `sanitizeDockerTemplatePayload` now drops an install script or managed startup the boundary refuses (console.warn with the offending pattern) so the runtime normalizer and the dashboard-assistant path can never forward one. - **`index.js`** — `constructTemplateDefinition` (manual create **and** store install) answers 400 for a violating `install.script`, next to the existing managed-startup check and still before the credential step-up. `PUT /api/settings/templates/:id` enforces the same 400, including on the stored fallback — a legacy violating script blocks the save with the pattern named; clearing the script (`install: null`) removes it and the save succeeds. The old `ADPANEL_STARTUP_*` constants/validator were removed in favor of the shared module (no second copy to drift). - **`main.go` (node agent)** — new `validateTemplateInstallScript` mirrors the JS validator (cross-language duplication is inherent; both copies are flagged in comments). Enforced twice: the create endpoint answers 400 (same gate as `command`/`adpanelStartup`), and `checkTemplateInstallPreflight` fails the install job with an actionable message — covering reinstall of pre-existing stored templates that never pass the panel boundary again. `normalizeTemplateInstallConfig` stays pure normalization: a violating script is rejected loudly, never silently skipped. - **Installer container hardening** — `runTemplateInstall` now launches the installer with the same baseline as runtime containers: `--cap-drop=ALL` + the panel-safe cap set, `no-new-privileges`, `--pids-limit=512`. Previously the installer container ran with Docker's default capabilities — it was the *least* hardened container in the system while executing the least trusted input. No `--user`/read-only change: installers provision the mounted volume as container root by design. - **Review dialog** (`public/js/settings.js`) — `summarizeStoreTemplatePayload` mirrors the install-script validator (behavior-duplicated like the command-validator copies) and flags `installScriptInvalid` with a danger banner and a warn row, so an admin sees a would-be 400 before approving a store install. ### Defense-in-depth layering (per surface) 1. Panel boundary 400 (`constructTemplateDefinition`, both ingestion paths). 2. Panel update 400 (including stored fallback → self-heal on explicit edit). 3. Runtime normalization drop+warn (assistant path, legacy templates). 4. Node create 400. 5. Node preflight failure on install/reinstall (stored content, direct node API callers). 6. Installer container runs with the runtime security baseline. ### Verification - `utils/server-template-payload.test.js`: 6 new suites (accept/reject tables for both validators, drop-on-normalize, sanitizer purity so the boundary can distinguish "no script" from "dropped"). - `tests/template-store-install-review.test.js`: constructor rejects seven boundary-violating install scripts with 400 and accepts the canonical installer payload; the review summary's `installScriptInvalid` flag agrees with the server verdict on both sides of the parity assertions. - `install_script_validation_test.go`: node-side accept/reject tables, word-boundary precision (no substring false positives), and a pin that `normalizeTemplateInstallConfig` never swallows a violating script. - Fixture sweep: every `.json` under `templates.json`, `store-templates.json`, `Templates/`, `github/`, `data/`, `tests/`, `utils/` checked against the pattern set — no install/startup script content trips it. - `npm test` green (117/117), `go build` + `go vet` + full `go test ./...` green. ### Residual risk The installer image itself remains attacker-chosen (that is the feature — like the runtime image), so the script gate + container baseline bound what it can do but a malicious image still has in-container freedom and network reach; operators who need more can apply per-node egress policy. Store templates carry arbitrary shell by design; the review dialog renders the full script and now also flags the reject cases, and the boundary 400 is the authoritative gate. --- # Security Fixes — Audit Remediation (2026-09-04) ## C1 — Template store is a supply-chain RCE path with no integrity verification Store content synced hourly from `antonndev/ADTemplates` (jsDelivr fallback as a second trust anchor) compiled straight into container launch configuration — 256 KB install scripts executed via `docker run -v :...