Files
Kelx/SECURITY-FIXES.md
2026-11-30 16:32:37 +00:00

8090 lines
491 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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 `<nil>:<nil>`. 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 `<nil>` 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 <ctr> sh -lc <cmd>`
(`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 `<img>` (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/<safe>`, `/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:<email>`, `node:<id>`,
`server:<name>` — 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:<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.<service>`), scoped to
`path=/db-access`, `SameSite=Lax`, `Secure` following the panel's
session-cookie policy, `Max-Age` = TTL. Proxy URLs are now
`/db-access/<service>/...` — 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/<service>/__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_<username>`, 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 <paneluser>; 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|<node-uuid>|<ts>|<nonce>`. 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 '<panel>/api/node-bootstrap/<script-id>' | 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/<script-id>` serves the bootstrap script once; the
script then fetches `GET /api/node-bootstrap/<config-id>/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:<id>` (validated id), subject `Template create "<id>"`.
- `PUT /api/settings/templates/:id` — same placement contract (after the last
400-check, before the template is persisted); scope `template:<id>`.
- `DELETE /api/settings/templates/:id` — after the 404 / in-use checks, before
the list is mutated; scope `template:<id>`.
- `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
`<app>/github/<category>/*.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 `<app>/github/<category>/` 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/<category>/` 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:<id>`) 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 <serverDir>:... <image>
<shell> <script>` with network egress, an arbitrary installer/runtime image
from any registry, and the managed startup command. The manifest's SHA-256
per file was never checked on read, and install posts were resolved against
whatever bytes sat in the cache dir. Repo-account or CDN compromise therefore
meant code execution on every panel that installs, with nothing
transport-independent detecting it. Remediated in depth:
### Content authentication (new trust anchor)
- `utils/template-store-trust.js`: canonical content digest over the raw
fetched bytes (path-keyed, repo-bound), Ed25519 detached-signature
verification against a pinned vendor key, git blob SHA-1 cross-check of
listing hashes vs fetched bytes, image registry allowlist, trust-config
resolution (env > `data/template-store-trust.json` > defaults). Pure and
unit-tested (`utils/template-store-trust.test.js`).
- `index.js` sync is now two-phase: the entire upstream set is fetched,
listing-hash-checked and signature-verified **in memory**; only then are
cache files written and the manifest replaced. A failed or tampered sync
leaves the previous cache and manifest byte-for-byte intact.
- Modes: `enforce` (default once a key is pinned) refuses to promote
unverified content — the last verified cache keeps serving; `warn` (stock
behavior, no key) serves content flagged unauthenticated in the manifest,
API and store UI.
- Verified snapshots are recorded in `data/template-store-trust-state.json`;
a signed snapshot older than the last accepted one is surfaced as a
possible replay/rollback.
- Manifest now records a per-file `sha256` (of the synced bytes) plus the
diff against the previous manifest; `readTemplateStoreCategoryFromCache`
drops any cache file the manifest does not track (orphans/torn syncs) and
any tracked file whose bytes no longer match its manifest hash — the cache
dir is no longer implicitly trusted on read.
- Optional review gate: `ADPANEL_TEMPLATE_STORE_AUTO_UPDATE=0` (or
`autoUpdate: false` in the trust file) stops scheduled/stale syncs on an
existing cache; the store stays pinned to the reviewed snapshot until an
admin forces a sync through the step-up-protected endpoint.
- Vendor tooling: `scripts/sign-template-store.js` (`keygen`, `sign`,
`verify`) reusing the exact panel primitives; round-trip + tamper tested.
`TEMPLATE-STORE-SIGNING.md` documents the threat model, rollout, and key
rotation.
- Store UI (`public/js/settings.js`) shows the signature state ("Vendor
signature verified" / "NOT verified — <reason>" / "content is NOT signed")
and the last update diff (+added/~changed/-removed) above the cards.
### Image registry allowlist (execution-content bound)
Template images (installer AND runtime) are execution content; an arbitrary
registry was an arbitrary-code primitive. Now enforced at panel ingestion
(400 on template create/update/store-install, runtime and installer images)
**and mirrored at every node sink in `main.go`** — create (400), container
start, reinstall pull, installer preflight — via
`validateTemplateImageRef`, so stored legacy templates cannot bypass the
panel either. Defaults: docker.io, ghcr.io, gcr.io, quay.io,
registry.k8s.io, public.ecr.aws; operators override with
`ADPANEL_TEMPLATE_ALLOWED_REGISTRIES` (panel) /
`ADPANEL_ALLOWED_TEMPLATE_IMAGE_REGISTRIES` (node). Stored templates
violating the list log a panel-side warning; installers additionally accept
`ADPANEL_TEMPLATE_INSTALL_NETWORK` to pin the installer container to an
egress-filtered docker network.
### Verification
- `npm test` green (127/127, including 10 new trust-primitive tests and the
extended VM-slice harnesses for the review/override suites);
`go build` + `go vet` green; `node --check` on every touched JS file.
- Signing round trip: keygen → sign fixture repo → verify OK; single-byte
template tamper fails with "content digest does not match the signed
digest"; git blob SHA-1 pinned against `git hash-object` output.
### Residual risk
The pinned Ed25519 private key is the new root of trust and lives in the
vendor's CI secret; rotation is documented and operator-driven, and a missed
rotation step fails closed in enforce mode. Local overrides remain outside
the signature by design (local, opt-in, flagged untrusted, never shadow
upstream). Docker Hub namespace squatting inside an allowed registry remains
possible — the admin still reviews the full payload (image, script, env)
under step-up before install, and content hashes pin review to install.
# Audit Remediation (2026-09-04) — F9
## F9 [Informational] — Trust-configuration escape hatches now degrade safely
`CSRF_ALLOWED_HOSTS` and `REMOTE_FETCH_ALLOW_ANY_PORT` are operator-owned
trust knobs that materially weaken their flows when set. Both were
logged/warned, but careless values were applied verbatim: the CSRF list
silently trusted whatever it could parse (an installer- or admin-pasted
`*.com` would have exempted an entire TLD from the same-origin check), and
the any-port flag gave no runtime signal at all. Neither knob failed in a
direction an operator could predict. Remediation principle: **for an
allowlist, ignoring an entry fails safe** (it can only narrow trust); for a
boolean flag, strict parsing fails safe — what was missing was visibility and
input hygiene, not stricter gating of intent.
### `CSRF_ALLOWED_HOSTS` — validated at startup (`utils/csrf-allowed-hosts.js`)
- Malformed or over-broad entries are **dropped with a per-entry reason**
(startup warning lists them), never trusted: `*`, TLD-level wildcards
(`*.com`, `*.io`, …), known public/shared zones (`*.co.uk`, `*.github.io`,
`*.pages.dev`, …), malformed host:port forms, bare IPv6, placeholder
values, control characters, entries past a 25-entry cap.
- Benign formatting mistakes are **normalized so legitimate integrations keep
working**: `https://Host/path`, trailing `.`/`:port`, case — each
normalization is logged (`"from" → "to"`).
- Wildcard entries (`*.example.com`, `.example.com`) now require the explicit
second opt-in `CSRF_ALLOWED_HOSTS_ALLOW_WILDCARDS=1`; without it they are
dropped with that reason.
- The startup warning no longer cries wolf: entries equal to this panel's own
public host (`PANEL_PUBLIC_URL`) are classified as self-trust and stay
silent — the installer always writes the panel's own domain/IP into
`CSRF_ALLOWED_HOSTS`, so previously every default install logged the
"trust widened" warning and operators learned to ignore it. Only genuinely
external hosts produce the strong warning now.
- Runtime matching is unchanged (`hostAllowed()` in `index.js`); entries are
normalized exactly the way Origin/Referer hosts are, so accepted lists
behave identically to before for well-formed configs.
### `REMOTE_FETCH_ALLOW_ANY_PORT` — visible in every state, JS and Go
- Panel (`index.js`) and node (`main.go`) both warn at startup when any-port
fetching is enabled (previously only the CSRF knob warned; the port knob
was silent in both runtimes).
- Set-but-ignored values (`true`, `yes`, `on`, …) warn that only exactly `1`
enables the flag and the 80/443 allowlist stays enforced — the operator's
mental model now matches reality instead of silently diverging.
- Every fetch/upload actually accepted on a non-80/443 port leaves a
`[SECURITY]`/`[security]` audit line (throttled per `host:port` — 10 min JS,
10 min Go, bounded maps — so chatty mirrors cannot flood the log), in both
`assertSafeRemoteUrl`/`assertSafeRemoteUrlWithResolvedIp` (panel fetches,
redirects included) and `uploadURLPortAllowed` (node URL uploads, redirect
hops included).
- The Go check now trims the env value the same way the panel does, so one
`.env` value cannot enable any-port on the panel while the node keeps
rejecting the same URL (and vice versa). The Go-only alias
`ADPANEL_NODE_FETCH_ALLOW_ANY_PORT` keeps its behavior and is covered by
the same warnings/audit.
### Verification
- `node --test utils/csrf-allowed-hosts.test.js` — 19/19: normalization
(scheme/port/path/IPv6), dangerous-value rejection (public-suffix
wildcards, `*`, malformed forms), ack-gated wildcards, entry cap, dedupe,
self-vs-external classification.
- `go test -run TestUploadURLPort .` — default allowlist, both env vars lift
it, careless values fail closed, whitespace is trimmed consistently with
the panel.
- `node --check` clean on `index.js` and the new util; `go build`, `go vet`
clean; full `npm test` and `go test .` suites green.
## Audit round 2026-09-04 — F2 remediation (non-admin reinstall hardening)
Finding F2 (Medium): `POST /api/servers/:name/reinstall` wiped a server with
only a session + `server_reinstall` permission check — no action token, no
rate limiter, no step-up. A phished or XSS'd session (or a cross-site POST,
had the same-origin check ever regressed) could destroy the server instantly.
The route now sits behind three independent gates before the node rebuild is
signed or sent:
- **Dedicated rate limiter** (`serverReinstallRateLimiter`): 5 attempts per
10 minutes keyed `ip + email + session id` (pattern of
`adminUserCreateRateLimiter`). Failed step-up verifications burn the same
budget, so credential guessing against this route is bounded too; exceeds
return 429 with `code: "reinstall-rate-limit"` and a `[SECURITY]` log line.
- **One-time action token**: `GET /api/servers/:name/permissions` mints
`actionTokens.reinstallServer` (`issueActionToken`, TTL 120 s, one-time
nonce) only when `server_reinstall` is held — mirroring the `fileDelete` /
`changeTemplate` tokens. The POST verifies it via
`requireActionTokenOr403(..., "POST /api/servers/:name/reinstall",
{ serverName: name })`. The token is HMAC-signed and bound to user+session,
so a cross-site form POST cannot carry it; the one-time nonce kills replay;
the resource binding pins it to exactly this server name.
- **Destructive-action step-up** (`requireDestructiveActionStepUp`, subject
`Server reinstall "<name>"`, scope `server:<name>`, `persistGrant: false`):
fresh password or TOTP proof from the account owner, exactly like node
deletes / template store installs / session revokes. 403 responses carry
`code: password-required | 2fa-required | invalid-password | invalid-2fa`
plus `revokeSecurity` so the client can render the right prompt.
`persistGrant: false` means this route never mints a reusable grace grant —
every wipe needs its own proof. `allowGrace` keeps the framework default, so
an admin who verified for another destructive action moments ago is not
double-prompted (the grant stays bound to session, IP, user agent and its
original scope per the existing grant machinery).
Frontend (`bot.ejs` / `bot.js` / `bot.css`): the reinstall confirm view gains
a credential step. First attempt sends a freshly refreshed one-time token with
no credential; on a step-up 403 the modal reveals a password/6-digit field
(mode from `revokeSecurity`), shows the server's error on invalid credentials,
and retries with `currentPassword` / `twoFactorCode`. The credential field
resets on open, close and success (no password lingers in the DOM); the
confirm button is disabled while a request is in flight. Every attempt
refreshes the token first because the server consumes the one-time nonce even
on a step-up 403.
Not changed (documented decision): the admin route
`POST /api/settings/servers/:name/template` (template change that reissues a
reinstall) keeps its admin-only gate — F2 is about the self-service route.
`utils/agent-tools.js` describes an agent `reinstall_server` tool but is not
wired to any executor in this tree; when it lands it must go through the same
API and will inherit these gates.
### Verification
- `node --test tests/reinstall-route-protection.test.js` — 8/8: limiter
behavior executed in a vm sandbox (window/max/key/skip/429 handler), the
real `verifyActionToken` machinery executed (mint → verify once, then
replay / wrong server / wrong action / wrong session / expired / missing all
fail; `requireActionTokenOr403` 403 shape), route wiring source assertions
(limiter mounted, token gate, step-up before node signing/sending,
`persistGrant: false`), token minting under `server_reinstall`, and the
bot.js / bot.ejs frontend contract.
- `node --check` clean on `index.js` and `public/js/bot.js`; full `npm test`
suite green.
## Audit round 2026-09-05 — F4 remediation
### F4 — server delete iterates legacy-name candidates (delete-by-unverified-alias)
`deleteServerByName` (`utils/server-delete.js`) fell back to deleting by
whatever names the panel entry had ever carried — `bot`, `legacyId`,
`legacy_id`, display `name`, numeric `id`, plus the caller-supplied name —
whenever the delete of the primary technical name on the node failed with a
non-"missing" error (transport error, 5xx, unexpected error body). Each
candidate was used blind: kill + `DELETE /v1/servers/<candidate>` until one
confirmed. A stale alias that now names a *different* server on that node
(a server recreated or imported under a colliding name) would have that
server's container, directory, meta and backups deleted — the panel never
proved the thing under the alias belonged to the entry being deleted.
Remediation — verified-alias deletion, fail-safe at every layer:
- **Candidate classification** (`deleteNameCandidates`): only the entry's
current technical name is trusted outright. Every other value is a legacy
alias flagged `requiresVerification`.
- **Verification gate** (`verifyLegacyDeleteCandidate`): a legacy alias may
only be deleted after (1) the node *positively* confirms a server exists
under that name via `GET /v1/servers/<name>` — unknown/ambiguous presence
refuses — and (2) the panel index shows no *other* entry claiming the name.
The ownership check is the new injectable dep `findServerAliasConflict`
(index.js): a `servers` scan over `name`/`legacy_id`/`bot` that safely ignores
the entry being deleted by comparing unique server name, id, and bot/legacy
attributes (an entry never conflicts with itself) and returns the claimant
otherwise. `mapServerRow` explicitly exposes `legacyId` and `legacy_id`.
A missing dep, a throwing check, or a claimant all refuse the candidate —
refusals are logged with the claimant name for the audit trail, and the loop
moves on.
- **Durable-job target** (`attemptedName`): only candidates actually
destructively attempted update it, so `enqueueServerDeleteJob` retries the
primary technical name, or a legacy alias only after it passed both gates.
- **Worker re-check** (`processServerDeleteJob` in index.js): before the
destructive call, a job re-runs the ownership check: if the entry still exists
and targets a non-technical legacy alias, or if the entry has already been
removed from `servers` and a new server now claims the target name, a claimant
abandons the job (terminal: job row deleted, `[delete-job]` refusal logged)
without touching the node or claimant container; a failed check throws so the
job retries with backoff instead of deleting unverified.
- **Wiring**: a shared `serverDeleteDeps()` factory now feeds both call sites
(admin route `DELETE /api/settings/servers/:name` and the dashboard
assistant tool), so every production path carries the ownership guard.
Behaviour preserved: the primary technical name keeps its original semantics
(node 404 = confirmed gone, `200/202 ok` = accepted; no extra round trips in
the common path), and the intended legacy cleanup still works when the alias
is present on the node and unclaimed. What changed is that the destructive
reach of an alias now requires positive identity evidence.
Not changed (documented decision): `findServer` resolves user input across
`name`/`legacy_id`/`bot` with `LIMIT 1`, so a single string that matches two
entries can still pick either — that resolution ambiguity predates F4 and
affects more than deletion; the ownership guard now caps its blast radius for
deletes. A node-side creation-stamped identity token (panel-issued ID
persisted into node meta and compared before delete) would close the residual
rename-race window entirely and is the recommended follow-up.
### Verification
- `node --test tests/server-delete-verified-alias.test.js` — 19/19: collision
scenario (claimed alias never deleted, durable job retargeted to the
technical name), unknown-presence/missing-dep/failing-check fail-safe
refusals, unclaimed alias still deleted after verification (GET precedes
DELETE), verified-alias failure becomes the retry target, primary-404 and
primary-200 short-circuits unchanged, candidate classification, source
assertions locking the index.js factory wiring and the worker guard order,
plus VM-extracted execution tests verifying `mapServerRow` legacyId exposure,
self-exclusion logic in `findServerAliasConflict`, claimant detection, and
post-delete null-entry checks.
- Full `npm test` suite green (222 tests) and `node --check` clean on
`index.js` and `utils/server-delete.js`.
## Audit round 2026-09-05 — F6 remediation
### F6 — Transfer job not crash-safe (unrecoverable transferring status flag)
A server transfer sets `servers.status = 'transferring'` in the database, runs as
an in-process asynchronous task, and only resets the flag once the migration
settles. If the panel crashed or restarted mid-transfer (SIGKILL, deployment,
power loss), no recovery path existed: the server remained flagged as
`transferring` indefinitely. New transfers were rejected by the already-running
check, and the panel UI remained wedged displaying the transfer splash.
Remediation — crash-safe transfer lifecycle and autonomous recovery:
- **Ownership Heartbeat** (`utils/transfer-recovery.js`): The worker executing
a transfer maintains an active ownership lease via a short-TTL Redis key
(`transferOwnerAlive:<server>`, 45s TTL, renewed every 15s). Any panel worker
can distinguish an active transfer from one orphaned by an ungraceful shutdown.
A missing heartbeat indicates an orphaned transfer ready for rollback; Redis
outages fail safe by skipping recovery.
- **Recovery Claim & Concurrency Guard**: Autonomous recovery uses an atomic
distributed lock (`transferRecoveryClaim:<server>`, `SET NX EX 300`) to ensure
that only one panel instance recovers an orphaned transfer in cluster mode.
A double-check pattern ensures transfers started concurrently between claim
acquisition are never interrupted.
- **Ordered Fail-Safe Rollback** (`rollbackAbortedTransfer`):
1. Source node container is reconciled with the pre-transfer state (restarted
if it was running, or stopped).
2. Partially copied files on the destination node are removed via `deleteServerOnNode`.
3. Destination cleanup errors do not block status restoration; pending cleanups
are persisted and retried.
4. The database status is conditionally updated back to its original status
(`UPDATE servers SET status = ? WHERE name = ? AND status = 'transferring'`).
- **Autonomous Sweeper & Boot Recovery**: On panel boot and via a periodic
background sweeper (every 60s, unref'd timer), any orphaned servers flagged as
`transferring` without a live owner heartbeat are automatically detected,
safely rolled back, and restored to operational status.
### Verification
- `node --test tests/transfer-recovery.test.js` — 39/39 passing: ownership heartbeat,
claim concurrency, ordered rollback, crash recovery sweeper, TOCTOU handling,
and index.js wiring assertions.
- Entire test suite: 222/222 passing (`node --test tests/*.test.js utils/*.test.js`).
## F1 — destructive-action guards on template change, transfer, and create (audit round 2026-09-05)
Template change (`POST /api/settings/servers/:name/template` — a full
wipe-and-reinstall) and transfer (`POST /api/settings/servers/:name/transfer`)
required only an admin session passing the same-origin check, while delete and
suspend already required an action token plus a credential step-up. A hijacked
admin session — the exact threat the step-up exists for — could silently
destroy server data through the template route with zero friction. Server
create (`POST /api/servers/create`) had neither a step-up (unlike node create,
which does) nor a dedicated rate limiter.
Panel side (`index.js`):
- **Template change** now sits behind the same three gates as the F2 user
reinstall: `sessionRevoke2faRateLimiter` + a dedicated
`serverTemplateChangeRateLimiter` (5 per 10 min per ip+user+session, failed
step-up verifications included), an action token bound to the session and
server name (`templateChangeToken`, minted by `GET /api/settings/servers`),
and `requireDestructiveActionStepUp` scoped to `server:<name>` with
`persistGrant: false` — a wipe must never mint a reusable capability, while
a live grant for the same server still avoids a double prompt. The gate runs
after payload validation but before the reinstall claim, so a challenge
response or a malformed request never touches operation state or burns a
grace use. Success/failure is now audit-logged and recorded via
`recordActivity` like delete.
- **Transfer** gets the same class of guard, tuned like suspend (disruptive
but not a wipe): `sessionRevoke2faRateLimiter`, a session+server-bound
`transferToken`, and a server-scoped step-up with the default grace
persistence. The step-up runs after the read-only validations (duplicate
submits and bad targets cannot burn a grace use) and before the
suspension-lock/state claims.
- **Create** gets `requireDestructiveActionStepUp` with deliberately NO
scopeKey — mirroring node create — so the minted grant stays unbound and the
wizard's follow-ups plus short creation batches inside the grace window do
not re-prompt; plus a dedicated `serverCreateRateLimiter` (10 per 10 min per
ip+user+session). The step-up runs before the create lock is taken.
- `GET /api/settings/servers` now mints `templateChangeToken` and
`transferToken` alongside the existing delete/suspension tokens (10-minute
TTL, session- and server-bound, `Cache-Control: no-store` preserved).
Frontend:
- `public/js/settings.js`: `sendGuardedRequestWithStepUp` now accepts extra
headers; new `sendServerRowActionWithGuards` wrapper combines the
`x-action-token` header with the shared step-up modal and performs exactly
one token refresh+retry when the 403 is a token rejection (stale list)
rather than a step-up challenge. The template-change and transfer flows use
it; both keep their existing confirm dialogs. Token maps mirror the delete
maps (`_templateTokensByName` / `_transferTokensByName`).
- `public/js/create-server-wizard.js` rides `window.sendGuardedRequestWithStepUp`
(exported by settings.js, which always loads first on the settings page);
the bare-fetch fallback recognizes `password-required`/`2fa-required`
instead of surfacing a generic error.
- `public/js/dashboard.js` implements a self-contained challenge dialog +
retry (`createServerWithStepUp`) for the dashboard create path: first
attempt rides the grace window, a 403 challenge collects one fresh
password/2FA code, a wrong credential re-prompts with the server's error.
- Cache-bust versions bumped in `views/settings.ejs`, `views/index.ejs`,
`views/status.ejs`.
### Follow-up (same round): node disk routes + legacy quick-creator removal
A sweep of all 114 mutating routes for missing guards surfaced two more
production-relevant items, both fixed:
- **Node disk add/remove** (`POST|DELETE /api/nodes/:id/disks[/:diskId]`) sat
behind an admin check only, while node create/update/delete already require
step-up. Disk add changes where server storage lives and disk remove deletes
the node's storage configuration — the same infrastructure-trust class. Both
now mount `sessionRevoke2faRateLimiter` and run
`requireDestructiveActionStepUp` scoped to `node:<id>` after payload
validation (a malformed request cannot burn a grace use) and before the node
API call (a challenge never reaches the daemon). No action token, matching
the rest of the node-route family. `public/js/settings.js` wires both flows
through `sendNodeWriteWithStepUp` (shared modal, grace-window aware).
- **Legacy quick-creator removed** (`#createServerName` / `#createServerBtn` in
`views/settings.ejs` + its fetch handler in `public/js/settings.js`): it
POSTed to `/api/settings/servers`, a route that no longer exists server-side,
so it was dead UI that could only ever 404. Real server creation is the
wizard's step-up-gated `POST /api/servers/create`.
Left unguarded deliberately after review (not destructive, or protected by
their own mechanisms): the legacy file-manager routes `/create` and `/rename`
(still used by `bot.js`, permission-gated via `files_create`/`files_rename`,
suspension-aware), scheduler task CRUD (`scheduler_create` perm), AI-chat and
pre-auth account flows (own credential/rate-limit protections), branding/alert/
preferences/console-history (cosmetic or reversible), and
`PATCH /api/settings/servers/:name/resources` (reversible admin tuning, guarded
by the F5 operation interlock).
Friction profile (deliberately not aggressive): the grace window (5 min, max
5 reuses) is unchanged — an admin doing a batch of destructive operations
verifies at most once per window; the template route additionally never
mints a grant (`persistGrant: false`, same as user reinstall), so routine
single wipes cost one prompt, and every wipe remains individually authorized.
### Verification
- `node --test tests/destructive-route-guards.test.js` — 13/13: route wiring
and gate ordering for all three F1 routes and both disk routes, limiter
behavior (vm-executed with a stubbed express-rate-limit), mint/verify token
pairing (vm-executed real machinery, including cross-action and cross-route
confusion), and the frontend contract for all guarded call sites plus the
dead-creator removal.
- Full suite: 276/276 passing (`npm test`).
- `node --check` clean on `index.js`, `settings.js`, `dashboard.js`,
`create-server-wizard.js`.
## Audit round 2026-09-06 — webhook hardening (P4.3, P4.4, P4.5)
Low-severity follow-ups on the Discord webhook pipeline (`index.js`,
`views/settings.ejs`, `public/js/settings.js`).
### P4.3 — `multiple` mode silently fell back to the single webhook
`dispatchWebhookForActivity` routed every category without its own webhook to
the single webhook, so an admin reading "Multiple Webhooks — per category"
could believe categories were isolated when unset ones were still leaking into
the single webhook's channel. Remediation: the routing decision is now an
explicit, admin-controlled setting instead of an undocumented behavior:
- New persisted config flag `fallbackToSingle` (validated by
`sanitizeWebhooksConfig`; only a strict boolean `false` disables, anything
else keeps the historical default `true`, so existing deployments see zero
behavior change).
- `POST /api/settings/webhooks` accepts `{ fallbackToSingle: true|false }`
alongside mode/URL changes (boolean-typed or 400). It is admin-gated and
action-token gated like mode changes, requires no step-up (it touches no
credential — it only re-routes events between already-configured webhooks),
and is recorded in the activity log as `fallback_to_single:<bool>`.
- `GET /api/settings/webhooks` exposes the flag via `maskConfigForResponse`.
- The dispatcher falls back to the single webhook only when
`fallbackToSingle !== false`; with strict isolation an unset category sends
nothing.
- Settings UI (admin only): the "Multiple Webhooks" tab description states the
effective routing, and the multiple-mode section renders a notice spelling
the behavior out with a toggle ("Disable fallback" ⇄ "Enable fallback").
### P4.4 — legacy `discordapp.com` webhook URLs rejected
Discord migrated the API to `discord.com`; a legacy `discordapp.com` webhook
URL is the same Discord-operated resource (same id/token). Validation now
accepts both hosts under the identical strict shape
(`https://(discord|discordapp).com/api/webhooks/<digits>/<token>`, ≤200
chars), and `normalizeDiscordWebhookUrl` rewrites the legacy host to
`discord.com` before anything is persisted (save path and config-load path).
Stored configs therefore only ever contain the canonical host and outbound
dispatches only ever target `discord.com` — legacy input is accepted at the
boundary but adds no second egress host. The client-side format check in
`settings.js` accepts both hosts and stays in sync with the server.
### P4.5 — capacity eviction sorted the whole rate-limit map
When the 1s dispatch dedupe map reached its 500-entry cap, eviction sorted all
entries by timestamp (O(n log n)). It now runs in O(n): entries whose window
has already expired are deleted first (they no longer rate-limit anything),
then oldest-inserted keys go (Map preserves insertion order) until the same
quarter-of-capacity headroom as before is freed. Deleting during Map iteration
is safe per spec; the dispatched key is always set after eviction, and the
1s dedupe semantics are unchanged (covered by tests).
### Verification
- New `tests/webhook-dispatch-hardening.test.js` — 21/21 passing
(`node --test tests/webhook-dispatch-hardening.test.js`): validation shape
and lookalike-host rejections, legacy-host acceptance + normalization on the
load/save paths, sanitize defaults and strict-boolean flag handling,
dangerous-key/unknown-category rejection, mask-without-secret-leak, dispatch
routing for single/multiple/strict-isolation/alias cases, eviction bounds
(expired-first, insertion-order, exact headroom), and 1s dedupe preservation;
plus frontend (settings.js/settings.ejs) and POST-endpoint wiring contracts.
The pipeline is exercised by slicing it out of `index.js` into a vm sandbox
with a stubbed `fetch` — no real network, no server boot.
- `node --check` clean on `index.js` and `public/js/settings.js`;
`views/settings.ejs` compiles (`ejs.compile`).
- Full suite: see `npm test` run in this round's commit notes.
## Audit round 2026-09-06 — accurate admin feedback & webhook dormancy (P3.2, P4.1, P4.2)
Low-severity follow-ups on delete feedback, route-param decoding and the
webhook mode model (`index.js`, `utils/server-delete.js`,
`public/js/settings.js`, `views/settings.ejs`).
### P3.2 — deletion of nonexistent resources returned a misleading success
Two halves, same defect: an operation that removed nothing answered
`ok: true` and went on to write audit records for a deletion that never
happened.
- `deleteServerByName` (`utils/server-delete.js`): when `findServer` matched
no index row it still swept schedules/index and returned `{ ok: true }`, so
the admin route recorded `server_delete` activity for a server that did not
exist. It now returns `{ ok: false, statusCode: 404, error: "server not
found" }`. The idempotent orphan sweep still runs — scheduler jobs and
stale access rows can outlive their index entry — but the caller learns
nothing was deleted. The route's `!result.ok` gate then skips the
`server_delete` activity records and answers 404; the assistant's
confirm-delete flow surfaces "server not found" instead of replying
"Deleted X." for a phantom server. Concurrent/racing deletes now get an
accurate 404 instead of a fabricated second success.
- `DELETE /api/settings/webhooks`: deleting without a category set
`config.single = null` even when it was already null (and deleting a
category that had no webhook was a silent no-op), returning `ok: true` and
recording a `webhook_config_delete`. Both branches now answer 404
("No single webhook is configured" / "No webhook is configured for this
category") when there is nothing to delete. The probe runs after the admin
check (no configuration-state disclosure to non-admins) and before the
destructive-action step-up, so a no-op delete cannot burn a grace use —
same ordering rule the transfer/reinstall routes document.
### P4.1 — double `decodeURIComponent()` on the `:name` route params
Express percent-decodes route params once; the eight server `:name` routes
(delete, suspension, template change, reinstall, resources GET/PATCH,
transfer GET/POST) decoded the param a second time. That is not injectable
today (lookups are exact and parameterized), but it mangles any server name
legitimately containing a `%`-sequence — the panel would look up (or report
as missing) a different name than the caller sent — and it is the kind of
redundant decoding that turns into a filter-bypass primitive the moment such
a value reaches a filesystem path.
- All eight routes now use `req.params.name` as the framework decoded it.
- `deleteServerByName` dropped its own second `decodeURIComponent` of the
caller-provided name (the route, the assistant service and the tests all
pass plain names, so the decode was either redundant or a mangle risk).
- Deliberately untouched: `decodeServerPathSegment` and the import-filename
decode operate on raw `req.path` / `URL.pathname` segments, which are still
percent-encoded — those decodes are correct and stay. Guarded by a test so
a future sweep does not remove them.
- Adjacent same-class observation (out of scope, recommended follow-up): the
`/api/settings/accounts/:email/*` routes still double-decode
`req.params.email`, and three of them do so without a try/catch, so a
malformed `%`-sequence in the path can raise a `URIError` and surface as a
500. Not changed in this round because they sit in account-management/auth
flows that deserve their own reviewed change.
### P4.2 — category webhooks could sit dormant while the mode was `single`
Category webhooks are only dispatched while the mode is `multiple`, but the
API accepted storing one while the request explicitly pinned the mode to
`single` — a successfully saved URL that never fires — and switching the mode
back to `single` later left previously configured category webhooks stored
but inactive with no indication anywhere. Both of the finding's recommended
directions were implemented:
- Validate: `POST /api/settings/webhooks` rejects a category URL combined
with an explicit `mode: "single"` (400 "Category webhooks require webhook
mode 'multiple'"). The check is pure input validation — it runs before the
config is loaded or mutated and before the step-up. Saving a category URL
without an explicit mode keeps the existing auto-switch to `multiple`, and
the built-in UI already pins `mode: 'multiple'` for category saves (locked
by a test), so the shipped flow can never hit the 400.
- Indicate: when a save leaves category webhooks configured while the mode is
`single` (mode switch, or a single-webhook save that flips the mode), the
success response carries a `warning` stating that N configured category
webhooks will not fire until the mode is switched back; the settings UI
toasts it, and `renderWebhooks()` renders a persistent saved-but-inactive
notice in the single-mode section (the categories grid itself stays hidden
in single mode, as before).
### Verification
- New `tests/audit-p32-p41-p42.test.js` — 12/12 passing
(`node --test tests/audit-p32-p41-p42.test.js`): missing-entry delete
returns 404 with the orphan sweep preserved and no node calls; the route's
audit path stays behind the `ok` gate; webhook delete 404s for absent
single/category webhooks ordered after the admin check and before the
step-up; the `nameParam` pattern is gone from `index.js` and
`utils/server-delete.js` while the legitimate raw-path decodes remain;
the dormancy 400 and warning are wired before config-load/step-up; the
settings UI notice and mode-switch toast contracts hold.
- Full Node suite: 311/311 passing (`npm test`).
- `go vet ./...` clean; `go test ./...` passing (template render tests
included — `views/settings.ejs` compiles).
## Audit round 2026-09-06 — webhook secret encrypted at rest (finding 🟡4)
### Finding — live Discord webhook URL in plaintext on disk
`webhooks-config.json` stored the full Discord webhook URL — id **and token** —
as plaintext JSON. Permissions (0600) and git-ignore status were already
correct, and the masked API responses never leaked the token, but the file
itself was a standing secret: any file-read primitive elsewhere in the panel,
or a config backup/archive leak, handed out a **permanent** spam/phishing
channel into the admin's Discord server (webhook tokens do not expire until
Discord-side deletion).
### Remediation
Node bearer tokens already went through this exact hardening for audit
finding C2 (`utils/node-token-crypto.js`); the webhook config now uses the
same scheme:
- **Envelope.** Every URL in `webhooks-config.json` (`single` and each
`multiple.<category>`) is sealed as `enc:v1:<iv_b64>:<tag_b64>:<ct_b64>`
— AES-256-GCM, fresh random 12-byte IV per write, auth tag verified on
every read.
- **Key.** scrypt(SESSION_SECRET, `"adpanel-webhook-secret-v1"`, 32) —
domain-separated from the node-token key so one master secret never yields
the same AES key for two subsystems. SESSION_SECRET is already mandatory
(index.js exits at boot without it), so no new key file needs protecting,
backing up, or excluding from publish scripts; every pm2 cluster worker
derives the identical key from the shared environment.
- **Memory contract unchanged.** The in-memory config always holds plaintext
URLs: masking (`maskConfigForResponse`), dispatch validation, the rate-limit
keying and the step-up flows are byte-for-byte the same code paths. Only
the disk layer encrypts/decrypts (`materializeWebhooksConfigFromDisk` on
load, sealing inside `saveWebhooksConfig` before any file I/O).
- **Fail-closed writes.** All sealing happens before the tmp file is created:
without usable key material the save returns false (API 500) and *nothing*
is written — no plaintext write, no downgrade of an existing ciphertext, no
tmp litter (the failure path also unlinks the tmp file now).
- **Startup migration.** `migrateWebhooksConfigToEncryptedAtRest()` runs
fire-and-forget from `startServers()`: it rewrites a legacy plaintext file
under the same cross-process write lock as admin saves, re-checking disk
state inside the lock so booting pm2 workers converge instead of clobbering
(an admin save racing the migration cannot be lost). It is idempotent —
restarts after the migration are no-ops. Loads accept legacy plaintext
until then, so a skipped migration never breaks dispatch; the next
successful save re-encrypts everything anyway.
- **Rotation policy.** A rotated SESSION_SECRET makes stored envelopes
undecryptable (GCM auth fails — by design the URL is unrecoverable). Those
entries are dropped with a one-time-per-target error log and read as "not
configured"; the admin re-enters the webhook. Unlike node HMAC secrets
(baked into remote node configs, hence the rotate-required machinery),
webhook URLs are admin-re-enterable, so no rotation-status state was added.
- **Untouched on purpose.** The masked API response contract, the write-lock
remediation (P3.1) and the dormancy guard (P4.2) are unchanged; the panel
updater already skips `webhooks-config.json` (PROTECTED_FILES) and
`github.sh` already excludes it from publishing.
### Verification
- `tests/webhook-config-write-lock.test.js` extended (16/16 passing): saved
values are well-formed envelopes whose raw disk bytes never contain the
host or token; plaintext/ciphertext round-trips through fresh and cached
loads; each write seals with a fresh IV; the boot migration rewrites a
legacy file, preserves mode/fallback and is idempotent; undecryptable
envelopes degrade to "not configured" instead of crashing; a save without
key material fails closed and leaves no file or tmp litter. The original
P3.1 lost-update/lock-lifecycle contracts now assert through decryption.
- End-to-end smoke against a **copy** of the real production config: legacy
plaintext loads and dispatch-validates → migration seals it → the exact
URL round-trips → the masked API response contains no token → a mode-only
save preserves the URL. The real file was untouched by the smoke run.
- `node --check index.js` clean; full Node suite 336/336
(`npm test`), including `webhook-dispatch-hardening.test.js` (24/24) and
`audit-p32-p41-p42.test.js` (12/12), whose vm slices of this code region
continue to evaluate with their reduced sandboxes (the crypto helpers touch
`crypto`/`process` lazily, never at slice-eval time).
- **Deployment note:** the on-disk plaintext is replaced on the first panel
restart after this change (the boot migration must run with the new code
live — rewriting the file while old workers are running would make them
read envelopes as "unconfigured" until restart).
## Audit round 2026-09-06 — webhook config changes require step-up (finding: audit-suppression without re-verification)
`POST /api/settings/webhooks` (`index.js`) fired `requireDestructiveActionStepUp`
only when the payload carried a webhook URL (`hasUrl`). A bare
`{ mode: "multiple", fallbackToSingle: false }` — or any mode flip — from a
hijacked admin session therefore re-routed dispatching with no re-verification:
in strict isolation (multiple mode, fallback disabled, no category webhook for
an event) `dispatchWebhookForActivity` sends nothing, so events silently stop
reaching the admin's Discord. That is out-of-band log suppression stageable
right before doing something noisy; the in-panel `webhook_config_change`
activity entry still records the change, but the Discord channel it would
ordinarily be announced to is exactly the channel being suppressed, and no
single webhook exists in the strict-isolation configuration.
This supersedes the P4.3 rationale ("requires no step-up — it only re-routes
events between already-configured webhooks"): once `fallbackToSingle: false`
became an admin choice, the re-routing itself became the suppression tool.
### Remediation
- **Unconditional step-up on POST** (`index.js`): every config-affecting
payload — URL, mode switch, fallback toggle — now runs
`requireDestructiveActionStepUp` with a payload-specific subject
(`Webhook set` / `Webhook set "<category>"` / `Webhook mode switch` /
`Webhook fallback update` / `Webhook mode & fallback update`). Same grant
policy as before the change: grace-eligible, unscoped (settings saves share
the unscoped grant pool; grants bound to a user/node/server target never
authorize this), minted only by a fresh password/2FA verification. Input
validation and the admin check still run first, so a malformed or
unauthorized request burns neither a grace use nor step-up credential
budget, and the write lock is still taken after the step-up so the critical
section stays synchronous (P3.1 unchanged).
- **Out-of-band forensic trail** (`index.js`): both write routes now emit a
`[SECURITY] Webhook configuration changed | User … | Change … | IP …` console
line after a durable save (behind the `!saved` / not-found gates, so failed
and no-op attempts are never logged as changes). The in-panel activity entry
and the Discord announcement both travel through the pipeline a config
change can re-route; the server console (pm2/journal logs) is the one
channel a hijacked browser session cannot suppress. DELETE already stepped
up unconditionally — it only gains the matching log.
- **Frontend** (`public/js/settings.js`): the mode→single, mode→multiple and
fallback toggles no longer issue session-only writes. They route through a
new `sendWebhookSaveWithGuards` wrapper (same contract as the existing
`sendWebhookTestWithGuards`): the first attempt carries no credential so a
live grace grant authorizes it silently; on a 403 step-up challenge the
shared verification modal collects the password/2FA code and retries in
place; cancelling changes nothing. Exactly one token refresh+retry on a 403
token rejection. `views/settings.ejs` bumps the `settings.js` cache-buster
(`v=20260906-webhook-stepup1`) so browsers cannot keep the session-only UI —
a stale copy would fail closed with a bare challenge error, but the served
UI must know the guarded flow.
### Behavior notes
- Legitimate workflow impact: an admin without a live grace grant gets one
password/2FA prompt per webhook-settings batch (5-minute grant window, 5
reuses — the same budget URL saves already drew from). Mode/fallback toggles
within that window stay prompt-free.
- The masked API response contract, dormancy warning (P4.2), one-time
per-target delete tokens (P5.1), the write lock (P3.1) and the
encrypted-at-rest storage are unchanged.
### Verification
- New `tests/webhook-config-step-up.test.js` — 12/12 passing
(`node --test tests/webhook-config-step-up.test.js`): the `hasUrl`
conditional and fake-ok stepUp init are gone with the step-up call
unconditional; subject coverage for every payload shape; ordering
(validation → admin check → step-up → write lock); the grant stays unscoped
and grace-eligible (no options object on the call); the success payload
still reports `graceExpiresAt`; both write routes log the out-of-band
`[SECURITY]` line only after a durable save with actor/change/IP; DELETE
keeps its unconditional step-up; settings.js routes all three toggles
through the guarded save with the token refresh-retry contract, the bare
session-only fetch payloads are gone, and cancellation leaves the config
untouched; the cache-buster is bumped.
- Full Node suite 367/367 (`npm test`), including the pre-existing webhook
contracts (`webhook-dispatch-hardening.test.js`, `webhook-config-write-lock.test.js`,
`audit-p32-p41-p42.test.js`, `destructive-route-guards.test.js`,
`webhook-dispatch-result.test.js` — 92/92 combined).
- `node --check` clean on `index.js` and `public/js/settings.js`.
## Audit round 2026-09-06 — assistant delete path gets the full destructive-action gate (finding 🔴1)
`POST /api/dashboard-assistant/confirm-delete` (`routes/dashboard-assistant.js`) →
`confirmDeleteServer` (`utils/dashboard-assistant-service.js`) re-checked admin
and nothing else: no action token, no password/2FA step-up, no rate limiter, no
server-side pending-intent state, and a thin audit record. An admin session
cookie alone deleted any server — a standing "delete anything, no second
factor" capability for a hijacked session or XSS, while every other
destructive path (admin server delete, suspension, template change, transfer,
webhook set/delete/test, node operations) requires a session-bound action
token plus a fresh credential (or a scoped grace grant) behind the shared
step-up credential limiter. The only "confirmation" was a client-side modal
plus a prompt-level instruction to the model, and CSRF-safety was incidental
(JSON body, no CORS).
### New flow
1. `request_delete_server` (unchanged contract) still only pushes a
capability-free client action (`{type: "confirm_delete_server", server,
displayName}`) after validating admin + resolving the target — no token or
capability ever flows through the AI layer.
2. NEW `POST /api/dashboard-assistant/delete-intent` creates the server-side
pending intent: admin-gated, JSON-only, `Cache-Control: no-store`, a
dedicated per account+session rate limiter, and a service that re-verifies
admin, binds the intent to a chat the user owns (strict `getChatById`, no
rotation side effects), resolves the server against the servers index by
canonical name, mints a SHORT-TTL (120s) ONE-TIME action token bound to
`{intentId, chatId, serverName}` and to the admin's session, and registers
the pending intent in the session
(`req.session.assistantDeleteIntents`, TTL-pruned, capped at 3). The
response carries `revokeSecurity` so the modal can pre-render the right
credential field.
3. `POST /api/dashboard-assistant/confirm-delete` now runs the same gate stack
as `DELETE /api/settings/servers/:name`:
`sessionRevoke2faRateLimiter` → admin → JSON-only 415 → session
pending-intent validation (expiry + server + chat binding) BEFORE any
single-use artifact burns → one-time token verify → intent consumption →
`requireDestructiveActionStepUp` scoped to `server:<name>` → delete →
response with `graceExpiresAt` (202 when the delete is queued).
`failureResponseExtras` re-mints a fresh pending intent into the 403 body,
so a mistyped credential costs one more entry, not a new assistant
round-trip. The token verifier and step-up are hard deps: if either is
missing the route throws (fail closed) instead of skipping the gate.
4. The browser modal fetches the intent when opened, sends the
`x-action-token` header plus `intentId` and the credential, renders the
password/2FA field from `revokeSecurity` (fails closed to password mode
without security state), transparently re-mints once on a stale
token/intent, and never sends credentials anywhere but the gated endpoint.
The system prompt additionally forbids the assistant from collecting
credentials in chat or claiming a delete succeeded before the modal flow
reports it.
### Audit trail parity
`confirmDeleteServer` now writes the same pair the admin route writes —
`recordActivity(server, "server_delete", …)` and
`recordActivity("_system", "server_delete", …)` — with `deletedBy`, the
acting admin, `via: "dashboard-assistant"`, how the step-up was satisfied
(`stepUp: "fresh-credential" | "grace-grant"`), and a trusted-proxy-resolved
IP (`getRequestIp`) instead of raw `req.ip`. It also flushes
`invalidateServerIndexCache()` and the per-server status TTL entry (a
pre-existing gap: assistant deletes left both caches stale), validates the
chat BEFORE the irreversible delete (old ordering could delete and then throw
on chat bookkeeping), and propagates the queued-delete state (202).
### Behavior notes
- UX: the modal asks for the admin's current password or a 6-digit 2FA code
unless a scoped grace grant from a recent verification is live — identical
to the Settings delete window. A wrong password re-prompts in place; a
token/intent that expires while the modal sits open re-mints transparently
once.
- A hijacked session without the credential can, at worst, mint intents
(harmless, 10 per 5 minutes per account+session) — the standing delete
capability is gone. With a live grace grant it is additionally bounded by
single-use intents (3 pending, 10 mints/5 min) and the grant's own use cap.
### Verification
- New `tests/dashboard-assistant-delete-gate.test.js` — 20/20: pins TTL,
one-time mint, session registration, admin/chat/server validation order,
gate ordering in the confirm route (body-match → token → consume →
step-up), `server:<name>` scoping, failureExtras re-mint, hard-dep fail
closed, audit parity, limiter wiring/keying, capability-free tool action,
client contract, and the markup in both templates.
- New `tests/dashboard-assistant-delete-flow.test.js` — 7/7: boots the real
router over HTTP with contract-compatible mocks and pins the semantics:
non-admin/unknown-server mints rejected, old-client and junk intentIds fail
closed, JSON-only 415 on both endpoints, mismatched bodies burn neither the
nonce nor the intent, the 403 challenge carries revokeSecurity plus a
session-registered re-minted intent, a successful confirm deletes exactly
the bound server with the full audit pair and both cache flushes, and
replay/cross-intent/expired intents are all rejected.
- Full Node suite 394/394 (`npm test`), including the pre-existing
`destructive-route-guards.test.js` contracts.
- `node --check` clean on `index.js`, `routes/dashboard-assistant.js`,
`utils/dashboard-assistant-service.js`, `utils/dashboard-assistant-tools.js`,
and `public/js/dashboard-assistant.js`.
- Cache-busters bumped (`dashboard-assistant.js?v=20260906-delete-stepup-v44`)
in `views/index.ejs` and `public/index-real.html`.
## Audit round 2026-09-06 — update-plane hardening (panel + node update/install)
The panel/node update surface differed from the rest of the destructive admin
plane in every dimension that matters: installs needed only an admin session
plus an action token (which any session can mint — `GET /api/settings/panel-info`
mints one on request and the client auto-refreshes tokens every 3 minutes), the
install internals deliberately allowed same-or-older versions, and extraction
had none of the filesystem hygiene the Go daemon enforces. A stolen admin
cookie alone was a complete RCE chain: disable auto-update, install a known-
vulnerable older release, exploit its published CVEs, survive as code.
### H1 — step-up re-auth on update installs
- `POST /api/settings/panel-update/install` and
`POST /api/settings/node-update/install` now sit behind the same
`requireDestructiveActionStepUp` gate as node delete / server create /
maintenance (fresh password or 2FA code, session+IP+UA-bound grant, the
standard grace window). The action token stays as the CSRF layer and the
step-up as the identity layer — ordering is token gate → acting-admin
resolution → step-up → install.
- Both install routes mount `updateInstallRateLimiter` (10 per 15 min per
email+session, no credential skip — every attempt pulls a large archive,
extracts it and restarts a service) plus `sessionRevoke2faRateLimiter` to
bound credential guessing; check/auto routes mount the lightweight
`updateActionRateLimiter` (30 per 10 min).
- The install action token is one-time and is consumed by the very attempt
that triggers the step-up challenge, so both challenges carry
`failureResponseExtras` re-minting a fresh `installUpdate` token; the
challenge body of the node install re-mints the node-scoped token
(`{ nodeId }` resource, step-up scoped `node:<id>`).
- `POST /api/settings/panel-update/auto` and
`POST /api/settings/node-update/auto` now require step-up **only when
disabling** — disabling auto-update is defense suppression (the same class
as captcha disable); enabling only re-arms patching and stays frictionless.
- Client: `settings.js` routes all four flows through the shared
`sendGuardedRequestWithStepUp` guarded flow, extended with an
`onStepUpChallenge` hook that fires on the first challenge *and* every
rejected in-modal retry, so a spent one-time token is re-stashed from the
challenge body and in-modal retries never dead-end on "invalid action
token". Cancelled verifications surface as status messages. Cache-buster
bumped to `settings.js?v=20260906-update-hardening1`.
### H2 — downgrade protection
- `installPanelUpdateInternal` refuses strictly older targets with 409 before
any release lookup, download or byte of extraction. Same-version
reinstalls stay allowed as the repair path; auto-update only ever requests
strictly newer versions and is unaffected. Versions that cannot be ordered
(`unknown`, legacy two-part strings) fall through permissively
(`isComparableUpdateVersion`) so fresh installs are never locked out.
- `installNodeUpdateInternal` resolves the node's live version via
`/v1/update/info` (with the `/v1/info` fallback) and refuses downgrades
with 409 **before** preparing the payload — nothing is downloaded or sent
to the node once a rollback is detected. Unknown/unreachable versions fall
through; an unreachable node fails at the install call itself.
- The version bookkeeping this check compares against can no longer be
rewritten by the thing it measures (see M4).
### M3 — one strict version validator everywhere
- `installPanelUpdateInternal` now uses the anchored, prerelease-aware
`isValidUpdateVersion` (the validator the node path already used) instead
of the weak unanchored `/^v?\d+\.\d+\.\d+/` prefix match that accepted
trailing garbage. Client-side `doNodeInstall` mirrors the anchored form.
### M4 — panel-information.json is no longer updatable
- `panel-information.json` moved from `UPDATABLE_PATHS` to
`PROTECTED_FILES`: a malicious/compromised release can no longer rewrite
its own `panel-version` (v999.0.0 would permanently suppress update
detection) or flip `panel-auto-update`. The panel rewrites the file itself
after a verified install, preserving fields it does not own. The new
`.update-backups` directory is protected as well.
### M5 — artifact integrity verification (conscious trade-off)
- Every release archive (panel and node) is hashed (SHA-256) and verified
before extraction; the hash is always logged, so installs stay
tamper-evident. Anchors, strongest first:
1. **Admin pins** in `data/update-checksums.json`
(`{ "requirePinned": false, "panel": { "v1.2.3": "<64-hex>" }, "node": {} }`).
The file lives under `data/` (PROTECTED_FILES) and no API writes it —
the admin pins a hash only after verifying the artifact through a
channel that does not share the update path's single trust point
(GitHub account + TLS). Pin mismatch = hard fail. Setting
`"requirePinned": true` additionally refuses any artifact without a pin
(opt-in strict mode that also gates auto-update).
2. **Release-notes checksums** are advisory: the body travels with the
release it describes, so a repo compromise rewrites both, and
maintainers may list asset checksums that do not describe the source
zipball. A declared value that disagrees with the artifact is logged as
a `[SECURITY]` tamper signal, not treated as proof.
- Residual risk, consciously accepted: with no pins and `requirePinned`
false, a repo/maintainer-account compromise still yields automatic RCE
(the release *is* the trust anchor). Pins are the mitigation an operator
opts into. A minisign-style offline signing key remains the only full fix
and requires maintainer-side process, not just panel code.
### M6 — no HTTPS downgrade on redirect
- `httpGetRaw` gained a `requireHttps` option: the initial URL and every
redirect hop must be https, so an https→http redirect can no longer walk a
release download onto plaintext. Both update download call sites enable it.
### L7–L11 — low findings
- **L7 rate limiting**: dedicated `updateInstallRateLimiter` /
`updateActionRateLimiter` (see H1) — hammering installs is no longer an
unbounded self-DoS lever.
- **L8 prerelease ordering**: `compareVersions` is now semver-aware
(`1.2.3-alpha < 1.2.3-alpha.1 < 1.2.3-beta < 1.2.3`, numeric identifiers
numeric, build metadata ignored) while keeping the historical `(b − a)`
sign convention; unparseable versions compare as 0.0.0 and four-part tags
fall back to their numeric prefix, preserving previous behavior.
- **L9 symlink-safe extraction**: extraction resolves the parent directory
through any pre-planted symlinks (`realpathSync`) and refuses to write
outside the panel root even when directory components were replaced with
links; symlink targets are refused by `lstat` and — closing the check/open
race — by an `O_NOFOLLOW` open (`writePanelUpdateFileNoFollow`), matching
the Go daemon's `writeFileNoFollow` guarantee. Zip-slip (`../`,
absolute entries) handling is unchanged.
- **L10 backup/rollback + zip budget**: every overwritten file is snapshotted
to `.update-backups/<timestamp>/` before its write; a failed extraction
rolls back (overwritten files restored, created files removed) instead of
leaving a broken panel, and the version bookkeeping only moves after a
fully successful pass. Old snapshots are pruned (keep 5). Extraction is
budgeted twice: declared uncompressed sizes are summed before anything is
decompressed (512 MB total), and per-entry inflation is capped at
decompression time (64 MB via `zlib.inflateRawSync` `maxOutputLength`,
which catches lying zip headers) plus actual-bytes accounting.
- **L11 cosmetic date**: the hardcoded `2026-08-10` fallback "last update"
date is gone server- (`index.js`) and client-side (`settings.js`);
fallbacks are `unknown`.
### Not changed (documented decisions)
- The Go daemon (`main.go`) was not modified: the panel already resolves
node versions and refuses downgrades before shipping a payload, and the
daemon trusts HMAC-authenticated panel commands by design — a compromised
panel is game over regardless of daemon-side checks.
- Release-body checksums are advisory rather than hard-fail (asset tables
would false-positive hard fails and break updates); the pin file is the
hard control.
### Verification
- New `tests/update-plane-hardening.test.js` — 45/45: protected-file
membership, https-only redirect threading, strict validator, downgrade
ordering (before lookup/download), integrity-before-decompression, route
limiter/token/step-up contracts with ordering and re-mint payloads, both
limiter configs, semver comparison table, integrity anchors (pin match /
mismatch / requirePinned / advisory notes), capped inflate, O_NOFOLLOW
write vs symlink, rollback restore/remove, and end-to-end
`installPanelUpdateInternal` runs over a real temp panel root: success
(protected files skipped, backups kept, bookkeeping rewritten by the
panel), 409 downgrade, repair install, invalid versions, 404, symlink
target + symlinked directory skips, mid-extraction ENOTDIR rollback,
declared-budget abort before decompression, and pin enforcement through
the real `data/update-checksums.json` read.
- Full Node suite 439/439 (`npm test`).
- `node --check` clean on `index.js` and `public/js/settings.js`.
## 2026-11-23 Panel Information audit walkthrough
**Version selection.** In Settings, Check selects the latest stable panel
release and Update installs that checked version. Auto update checks at
startup, after enabling, and hourly. The panel install API also accepts a
specific release version after admin authorization, a one-time action token,
and credential step-up. It prefers the exact published tag and tries the
other spelling with or without `v` only if there is no exact published match.
It queries the tag endpoint, independently of the release listing. An older
version is refused; the same version can be reinstalled for repair. Release
validation and ordering use SemVer. Auto update selects only a newer release
that is neither a draft, a GitHub prerelease, nor a prerelease tag. GitHub
branch commits or tags without a published release are not updates. Check and
auto update scan up to five 100-entry pages within one 15-second lookup budget.
A failed or incomplete scan is not evidence that the panel is up to date and
does not blacklist any release. The scheduler tries again on its next cycle.
There is no arbitrary version picker in the Panel Information tab.
**Serialize installation and recovery.** Manual install, auto update, the
startup launcher, and abandoned-attempt recovery share an exclusive Linux
`flock` on the existing panel directory. It requires no lock-file allocation
and the kernel releases it when the owner dies. A durable pending record
blocks new installs between workers and through restart. The auto-update
setting uses the same lock.
**Preserve the previous install.** Record the selected version before download.
Extract checked files into a private staging directory under `.update-backups`.
Until publication, the old processes can still load old source and the displayed
installed version is unchanged. The launcher checks the staged manifest and file
digests before publishing their contents. The backup is incremental: it saves
replaced source and panel version metadata, not a clone of the installation.
Protected dependencies, virtual environments, and runtime configuration stay
untouched, including beneath updatable directories. The shared favicon, avatar
uploads, and generated logo and login background files are also excluded
because the panel writes them at runtime.
Flush the old version record, all source snapshots, and the undo journal of
affected files, missing directories, and replacement temporary paths before
changing any live paths. The publisher does not append to the journal after
replacing source starts. Replace files durably without following symlinked
targets or parent directories. On publication failure, replay
the journal in reverse, restore version metadata, and remove newly created
files and empty directories. Replay flushes the surviving parent directory
even if an earlier pass already removed an entry. Aborted snapshot setup does
not count toward the five retained backups, nor does an attempt stopped before
a live file was replaced. An archive with no updatable files cannot commit.
**Recover from disk-full errors.** Restore from a reflink or copy so the live
file and retained snapshot are independent. If cleanup, a restore copy, its
temporary record, or a recovery directory flush hits a storage limit, release
the preflight space reserve and retry. Reserved-record renames also flush their
destination and, when different, their source directory. If a same-filesystem copy still fails, fall
back to a hard link and atomic rename. That fallback is flagged in the backup
and in the saved status because later in-place edits can affect both copies.
At startup, allocate a 128 KiB reserve on the backup
filesystem. If the first update record cannot be allocated, consume the reserve
to record the failed release and defer retries. This depends on having reserved
space beforehand and on the filesystem still accepting writes. Reserve the
rollback records and backup warning before replacing files. A reserved
operator-action record lets other workers report that rollback could not finish
even when the disk cannot allocate a new file. An abandoned stage stays
pending until it is removed, even when marking it for discard needs the
reserved record instead of a new write.
Replay cleans up interrupted restore temporaries; a separate
filesystem requires room to make a copy there. If recovery cannot finish, keep
its journal and snapshots, block new updates, and report operator action.
Restore from a known-good deployment backup if storage prevents recovery.
**Check dependencies before replacing code.** The updater protects
`node_modules`, and a normal service restart does not reconcile it with the
new release's manifest. The updater now checks that manifest against the
installed production tree with bounded, offline `npm ls`, without running
lifecycle scripts. Incompatible Node engine requirements and changes to the
CommonJS startup format are also refused before writing. Deploy those releases
through a maintenance upgrade with their production dependencies and service
configuration.
**Keep configured checksum verification fail-closed.** A missing checksum
policy still permits the existing GitHub-trusted default. An unreadable or
invalid `data/update-checksums.json`, including a dangling symlink, blocks both
panel and node updates. To require independent verification,
populate the policy with SHA-256 pins obtained through a separate trusted
channel and set `requirePinned` to `true`. An unpinned install still trusts
the release repository and HTTPS; the updater does not verify maintainer
signatures.
**Keep the tab in sync.** Get a fresh one-time token for every confirmed
install and keep the existing step-up flow. The existing status area below
the tables displays the saved failure and whether recovery succeeded. An
abandoned update waiting for its first recovery attempt is shown as pending,
not as an operator failure. Status polling is limited to the visible tab and
does not mint action tokens. The
normal Update button is not offered for an ignored release; the server
rechecks that offer under the update lock after credential verification.
The install status identifies success by transaction ID, independently of an
unrelated prior failure. An ordinary feed check holding the update lock is not
a restart and does not clear a valid offer. Auto update
remembers the failed version across workers and restarts, and only attempts
a strictly newer stable GitHub release. Explicit version installs remain
available through the re-authenticated API, including deliberate repair
attempts. A failed GitHub check without a selected release does not block
a version; the scheduler checks again normally.
**Verify startup before accepting the release.** The web and Agent launchers
hold shared leases for the life of each worker. Publication takes the lease
exclusively after the old generation drains, including workers omitted from
PM2's listing during rolling reloads. Agent stops claiming work and drains via
its shutdown hook, with a bounded exit fallback. A replacement Agent does not
load application code until the web trial is verified or rolled back. Built-in
autoscaling defers while an update is pending.
Every expected PM2 slot must bind all configured listeners, settle, and report
fresh readiness. A new PM2 supervisor uses its configured replacement count;
an in-place restart verifies the captured slots. Replacement processes for
parked PM2 reload slots do not load code or participate in trial recovery.
Trial enrollment failures or
expired restart windows lead to rollback. The independent watchdog is armed
before the first live write. Publication records the first trial worker before
leaving the applying phase. Subsequent trial workers arm their own watchdog
before recording their enrollment or loading code. A crashed or hung candidate must stop before files are
restored.
Confirmation stays pending while the verified state and the archived recovery
record are flushed. The archived guard remains active after the main guard is
unlinked, so a crash or hang during the directory flush still rolls back. Only
after a provisional receipt has been flushed and readiness checked again does
an atomic rename mark completion. If a power cut loses that final rename, the
durable provisional receipt still requires rollback. A subsequent update must
flush the completion receipt before recording a new journal.
The updater submits the slot restarts to the existing PM2 daemon so it finishes
the group even if the requester exits, using PM2's normal shutdown timeout.
PM2 must allow automatic restarts, must not use stop exit codes for the panel,
and must allow at least three unstable starts. PM2 can count a planned stop of a
young worker as unstable, leaving recovery to start after two counted exits.
Workers share the durable retry budget; a survivor can retry or roll back the
staged files. An interrupted write can also be recovered on the next service
start. Listener readiness is not a guarantee that every application feature
works. File rollback does not undo database migrations or recover a failed disk
or supervisor; keep an independent deployment and database backup.
**Restore after host power loss.** The update record captures the Linux boot ID.
The protected service entry point discards an abandoned stage or restores
journaled source and version metadata before generating PM2 configuration.
After reboot it never tries the unverified release. On the same boot it leaves a
still-eligible restart or trial to the PM2 launcher, which applies the same
recovery gate for custom service startup. Restoring source does not guarantee that PM2 itself can start
on a full disk; resolve storage errors before retrying service startup.
**Rollout.** Deploy the recovery launcher, its dependencies, and the Linux
`flock` utility through a maintenance upgrade with the old panel workers stopped
and no active update. The old lock-file protocol does not interoperate with
the new kernel lock. Let the normal service startup regenerate its PM2
configuration. Confirm that production
workers launch `scripts/panel-update-recovery.cjs`, not `index.js` directly,
before enabling updates. Regenerate the systemd Agent unit as well; it must
start the launcher with `--agent`, with no legacy worker still running. A custom
PM2 setup must regenerate and reload its app definition. Do not run either
worker outside the protected launcher on a host using online updates. The
launcher, its dependencies, and startup scripts are excluded
from subsequent online archives; changing them requires maintenance.
**Review.** Inspect the update lifecycle and the tests in
`tests/update-plane-hardening.test.js` line by line. Verify version selection,
step-up, integrity checks, every journal transition and write ordering,
lock ownership, process deadlines, metadata restoration, protected paths,
failed-release suppression, and the status UI. Use only disposable fixtures;
do not publish a release or restart the installed service.
## Audit round 2026-09-06 — branding/theming hardening (findings 4–8 [LOW])
### Finding 4 — branding writes were unaudited and unthrottled
Global alert create/delete wrote `recordActivity` entries, but the branding,
login-background and dashboard-background POSTs only `console.log`'d — an
admin defacing the panel (swapping the logo/background to an attacker-chosen
URL) left no activity-log entry.
- `POST /api/admin/branding/update` now records `_system` /
`branding_update` (app name before/after, logo source upload|url|unchanged,
the resolved URL, replaced file) and `POST /api/admin/login-background`
records `_system` / `login_background_update` (mode, media/mime type,
external URL, local path, replaced path) — same shape as the existing
global-alert audit entries.
- `POST /api/settings/background` records `_system` /
`dashboard_background_update`; inline data-URL values are summarized as
`[data-url <n> chars]` instead of dumping tens of MB into the log, while
colors/paths/URLs are stored verbatim so a defacement is reconstructible.
- New always-on `brandingWriteRateLimiter` (20 per 15 min per
IP+account+session, `skip` for unauthenticated) mounted on all three POSTs.
The global `/api` limiter is operator-toggleable (`security.json:
rate_limiting` — off in this deploy), so these routes previously had no
effective throttle on 56MB parses + live-asset rewrites.
### Finding 5 — replaced logo uploads were never deleted
The login-background route removed its replaced file, but the logo upload
path left every superseded `logo-<hex>` file on disk — disk creep, and the
old logo stayed downloadable at its old random `/images/` URL.
- After a successful save the branding route removes the replaced logo;
if the config save fails, the freshly written upload is removed instead
(no orphans in either direction). The catch-block cleanup is gated on
`configSaved` so a post-save error can never unlink the live file.
- Deletion is gated on the generated-filename shape
(`^logo-[0-9a-f]{16}\.[a-z0-9]+$`): fixed-name assets (`favicon.ico`,
`logo.webp`, `adpanel-dark.*`) and anything an old config may reference by
hand can never be unlinked — worst case is an orphaned file, never a
deleted one.
- The ICO→favicon.ico copy moved after the config save, so a failed save no
longer rewrites the shared favicon while the config still points elsewhere.
### Finding 6 — non-atomic CSS rewrite + `$`-pattern expansion
`setBodyBackgroundInFile` rewrote the live `dashboard.css`/`bot.css` with a
direct `writeFileSync` (crash mid-write → truncated stylesheet) and passed
the validated value as `String.replace`'s replacement STRING, so `$&`, `$'`,
`` $` ``, `$1`… inside a legal URL (not escaped by `makeCssBackground`) expanded
as replacement patterns and mangled the CSS.
- Values are now injected through replacer FUNCTIONS (literal, no pattern
expansion), verified with a URL containing `$& $' $` $1 ${} $0`.
- The write is temp+rename with the original file mode preserved and temp
cleanup on failure — matching every other config write in the panel.
- Admin-self-inflicted only (no cross-privilege change); the fix is
correctness/robustness hardening.
### Finding 7 — external CDN trust for default logo/favicon
`/auth-assets/favicon` fetched a hardcoded `cdn.jsdelivr.net` URL FIRST — an
availability dependency for every login page and a supply-chain trust
decision in a third-party CDN repo — while `DEFAULT_LOGO_URL` hardcoded the
same origin, and the ICO "replace favicon.ico" upload was dead code because
local files were never consulted.
- `/auth-assets/favicon` resolution is now local-first, mirroring what
`resolveFaviconMimeType` always documented (so `<link type>` and served
bytes can no longer disagree): admin-uploaded logo (ICO uploads now really
become the favicon) → configured remote logo URL (proxied/validated, the
browser still never talks to that host) → local built-ins
(`adpanel-dark.webp` → `logo.webp` → `favicon.ico`) → pinned CDN asset as
a LAST resort for stripped installs, env-overridable via
`FAVICON_REMOTE_URL`.
- `DEFAULT_LOGO_URL` (`utils/branding.js`) now points at the panel's own
`/images/adpanel-dark.svg` (the same asset the CDN URL mirrored); the
hardcoded CDN fallback in `views/404.ejs` replaced with the local path.
No default-render request touches a third-party origin anymore.
### Finding 8 — low/cosmetic batch
- `GET`/`POST /api/admin/login-background` reported `mode: "upload"` for the
not-configured state; it now reports `"none"` (client shows "Default
background in use" and falls back to the upload tab).
- `restoreAlertAfterMaintenance` deleted the FIRST alert matching the
injected pre-alert text — an admin alert with identical wording could be
removed instead. Both injection sites now persist the injected alert's id
(`pre_alert._injected_alert_id`) and the restore deletes exactly that
alert. Legacy states recorded only the text, so the fallback matches by
message but explicitly skips `previous_alert_backup.id` — the backed-up
admin alert can never be the removal target.
- Global `JSON_BODY_LIMIT` default dropped 50mb → 1mb (env-overridable).
Every route with a legitimate large body keeps a scoped parser: file
write (50mb), AI chat (50mb), branding media (56mb), and a new
`DASHBOARD_BACKGROUND_JSON_LIMIT` (26mb) dispatched for
`POST /api/settings/background`, whose values may legally be inline data
URLs up to 24,000,000 chars.
### Verification
- New `tests/audit-branding-hardening.test.js` — 23/23: audit entries behind
success gates, limiter definition + mounting, `removeOldLogoFile` allow/
deny table (including traversal and non-generated names) against a fake
fs, extracted `setBodyBackgroundInFile` run against real temp files
(`$`-pattern literalness, temp+rename, mode preservation, no temp
leftovers), favicon local-first ordering, local `DEFAULT_LOGO_URL`,
mode `none` reporting, id-based maintenance restore (incl. legacy
fallback skipping the backup id), and the scoped JSON limits.
- Full Node suite 462/462 (`npm test`), `node --check` clean on `index.js`,
`utils/branding.js`, `public/js/settings.js`.
## Audit round 2026-09-08 — password policy parity on change/reset paths (finding M2)
### Finding M2 — admin password reset enforced a far weaker policy than account creation
`POST /api/settings/accounts/:email/change-password` only checked
`newPassword.length >= 8` plus confirm-match, so an admin reset could set
`password123` on any user — a password account creation rejects via
`getProvisionedPasswordError` — and a >72-byte password was silently
truncated by bcrypt before hashing on this path too.
The same gap existed on both self-service change paths, which would have let
any authenticated user downgrade their own account to a creation-rejected
password after the fact:
- `POST /api/settings/change-password` (settings modal)
- `POST /api/account/password/change` (account modal)
### Fix
- All three routes now run `getProvisionedPasswordError(newPassword, …)`
before any hashing — the shared creation-time validator (length, 72-byte
bcrypt cap, control characters, common-password blocklist, email-local-part
check, repeated/sequential rejection). The admin reset validates against
the *target's* email, since that is the account the new password protects;
the self-service routes validate against the session account. The shared
validator also rejects non-string bodies that previously slipped past the
bare `newPassword.length < 8` check and died later as a bcrypt 500.
- `views/settings.ejs`: the two account password-change modals now advertise
"8-72 characters" with `maxlength="72"`, matching the create-account modal.
The pgAdmin/MongoDB service-credential forms keep "Minimum 8 characters" on
purpose — those flows hand the credential to the database engine and are
not subject to the panel-login bcrypt cap.
Out of scope, unchanged: `scripts/create-user.js` (root CLI that also accepts
`--password-hash` directly, so no client-side policy there is a security
boundary) and the MongoDB/MySQL service-credential endpoints (different
threat model; the credential is consumed by the database itself).
### Verification
- New `tests/password-policy-parity.test.js` — 9/9: the shared validator is
behavior-tested from its live index.js source (common passwords and
symbol-mangled variants, 72-byte cap at and past the limit, email-local
part, 12+ repeats, pure sequences, control characters, non-strings, and
the accepted 8+ baseline), plus route source assertions for all three call
sites (target lookup → validator → bcrypt.hash ordering, weak length-only
check removed, exactly one validator definition that account creation
still shares), and UI parity for the two change-password modals.
- Full Node suite 554/554 (`npm test`), `node --check` clean on `index.js`.
## Audit round 2026-09-08 (2) — create-flow 2FA provisioning exposes the seed to the admin (finding M1)
### Finding M1 — create-user with 2FA returned the TOTP seed and plaintext recovery codes to the admin
`POST /api/admin/user/create` (the `enableTwoFactor` branch) generated a TOTP
secret, an otpauth QR data URL, and plaintext recovery codes, persisted them
for the new account, and handed all three back in the JSON response.
`settings.js` rendered the seed + QR + codes in the "Account Created!" modal
and offered them as a downloadable text file, leaving the material in browser
memory (`lastCreatedUserCredentials`) and in the response body of the request
the admin's browser made.
That violates the exact policy the admin 2FA reset was redesigned around
(`handleAdmin2faReset`): *the admin must NEVER learn the target user's TOTP
seed, otherwise the admin could generate valid codes for that account and
non-repudiation is broken.* The two privileged flows embodied contradictory
non-repudiation models — reset clears 2FA and makes the user re-enroll, while
create pre-provisioned a seed the admin could read. Incremental takeover risk
at creation time is low (the admin also sets the initial password), but the
seed transited the response body and browser memory, and any log/proxy that
captures admin responses captured live credentials.
### Fix
One model everywhere: accounts are created with `secret = NULL` and
`recovery_codes = NULL`; the user enrolls their own authenticator from
account security settings after their first login. The enrollment endpoints
(`/api/account/2fa/generate`, `/api/account/2fa/generate-recovery`) bind the
pending secret to the *user's own session*, so a seed never transits an admin
response. The admin's per-user `has2FA` status in the accounts list shows
whether enrollment actually happened.
- `index.js`: the create route no longer calls `speakeasy.generateSecret`,
`speakeasy.otpauthURL`, `qrcode.toDataURL`, or
`generateHashedRecoveryCodes` (the helper is deleted — it had no other
caller). The INSERT writes `NULL` constants for `secret`/`recovery_codes`.
The response is `{ ok, email, role, admin, has2FA: false, message }` — no
`secret`/`qrCodeUrl`/`recoveryCodes` keys. `enableTwoFactor` is still
parsed but ignored, so stale clients' create requests keep succeeding, and
`has2FA: false` routes their render down the existing "created without
2FA" branch. Ignored provisioning requests are recorded in the `[admin]`
audit line.
- `public/js/settings.js`: the create modal no longer sends
`enableTwoFactor`; the credentials dialog renders only email/role plus the
self-enrollment guidance (no QR/secret/code rendering, no HTML sinks); the
download note contains only what the admin already knows (email + role).
- `views/settings.ejs`: the "Enable 2FA setup" toggle is replaced by an
informational note (enrollment is the user's act; the admin never holds the
seed — same policy as 2FA resets). The credentials modal's QR/secret/
recovery blocks are removed. `settings.css`/`settings.js` cache-busters
bumped to `20260908-create2fa-policy1`.
- `tests/audit-l1-l2-l4-l6-hardening.test.js` (L1): updated — the credentials
modal's recovery-code sink and the download's raw `${code}` interpolation
no longer exist, so only the recovery-reset dialog remains as a code sink
(still escapeHtml'd).
Out of scope, unchanged: `scripts/create-user.js` and the `initialize.sh`
bootstrap that drives it. They run as root on the host: an operator who can
execute the CLI can read the users table directly, so hiding the seed from
root gains nothing, and `initialize.sh`'s first-admin seeding prints the QR
in the same root terminal. Same rationale as the M2 round's CLI note. The
recovery-reset dialog (`POST /api/admin/user/reset-recovery-codes`) also
still shows codes to the admin by design: it rotates the codes with step-up
verification, the seed is untouched, and handing the replacement codes to a
locked-out user is the feature.
### Verification
- New `tests/admin-create-2fa-nonrepudiation.test.js` — 10/10: the create
route performs no material generation and returns no seed/QR/codes, the
INSERT uses NULL constants, the dead helper is gone repo-wide, stale-client
compat (parsed-and-ignored `enableTwoFactor` + audit line), the reset-2fa
policy statement is intact and still generates no secret, exactly two
seed-generation sites exist and both are user-session-bound self-service
routes, and the frontend carries no provisioning toggle, no QR/secret/
recovery blocks, and no `enableTwoFactor` in the request body.
- Updated the three cache-buster pin tests to the new version string.
- Full Node suite 565/565 (`npm test`), `node --check` clean on `index.js`
and `public/js/settings.js`.
## Audit round 2026-09-08 (3) — CLI recovery codes move to the OS CSPRNG (CWE-338 hygiene)
Follow-up to the M1 round's CLI note. `scripts/create-user.js` generated its
printed recovery codes with `Math.random()` — a seeded, predictable PRNG that
must never produce secret material. The seed-exposure decision stands
(whoever can run this root CLI can read the users table directly), but the
codes themselves are account credentials: they are bcrypt-hashed into the
users row and shown once on the terminal, so their *unpredictability before
generation* is a real property, independent of who can read the DB
afterwards. Practical exploitation was far-fetched (the codes are never
exposed to web-facing input), but the fix is one line and the hygiene is
non-negotiable.
### Fix
- `generateRecoveryCode()` now draws every character via
`crypto.randomInt(RECOVERY_CODE_CHARS.length)` — Node's rejection-sampled
integer API, so coverage stays uniform even if the alphabet size ever stops
being a power of two (the naive `byte % 32` happens to be unbiased today,
but the API removes the trap).
- Left alone, deliberately: the `Math.random()` in `pickDefaultAvatar` picks
among three cosmetic avatar images — nothing secret, no attacker benefit.
A test tripwire now enforces that it stays the file's only use.
- The TOTP seed path was already CSPRNG-backed (speakeasy's
`generateSecret` uses `crypto.randomBytes` internally).
### Verification
- New `tests/cli-recovery-code-crypto.test.js` — 6/6: the live generator
source (extracted from main(), same technique as the parity tests) is
behavior-tested for alphabet/length conformance, per-character distribution
(32k draws, generous ±30% band), and batch collision-freedom; source
assertions pin `crypto.randomInt` usage, zero `Math.random` in executable
code outside the avatar picker, and the hash-before-persist loop.
- Full Node suite 571/571 (`npm test`), `node --check` clean on
`scripts/create-user.js`.
## Audit round 2026-09-09 — accounts `:email` param was decoded twice (low, correctness-first)
Every accounts route re-decoded `req.params.email` with `decodeURIComponent`
after Express 4 had already percent-decoded it exactly once. A second decode
only changes anything when the param legitimately contains a "%"-sequence —
and `%` is a legal email local-part character that the panel's own creator
(`normalizeProvisionedEmail`) accepts, so such accounts can really exist.
Two consequences:
- **Wrong-target actions (serious half).** For the routes whose action tokens
are not target-bound (add/remove access, agent-access, grant-perms,
change-password) the handler resolved `findUserByEmail(decoded)`. With a
second account whose email equals the decoded form, an admin managing
`bob%61@x.com` actually mutated `boba@x.com` — password reset, session
eviction, ACL rewrite — and the `[SECURITY]` audit lines recorded the
decoded email, shifting attribution too.
- **Destructive ops fail closed (unmanageable accounts).** Suspension and
deletion verify a one-time token minted (in `GET /api/settings/accounts`)
for the real target email; verified against the decoded email the binding
never matched, so `%xx`-pattern accounts could never be suspended or
deleted through the panel (403 "invalid or missing action token").
Fail-closed, not exploitable.
Practical exploitation is far-fetched (requires a %-bearing email plus, for
misdirection, a colliding account — both admin-created), hence low severity;
but the wrong-target half is an integrity defect, so it is fixed at the root.
### Fix
- All eight `:email` routes now read `req.params.email` exactly as Express
decoded it (`String(req.params.email || "").trim()`), the same remediation
as the P4.1 server `:name` round; the `try { decodeURIComponent(...) }
catch` blocks are gone. No data cleanup is needed: under the old code a
wrong-target write always landed on a *real* colliding account's identity,
and non-colliding targets 404'd before any write.
- Client compatibility verified end to end: `public/js/settings.js` decodes
the `data-email` attribute back to the raw address and re-encodes it with
`encodeURIComponent` at fetch time, so the wire form is the canonical
single encoding — the double decode had no compensating client.
- Left alone, deliberately: the five remaining `decodeURIComponent` uses in
`index.js` operate on raw `req.path`/`URL.pathname` segments and URL
credentials, which Express does not decode; they are correct.
- Not changed (documented decision): the add/remove/agent-access/grant-perms/
change-password action tokens remain minted per page load rather than
target-bound (unlike delete/suspension). Target-binding them would require
per-row mints and a client contract change; the wrong-target risk they
carried came from the double decode, which is gone. Worth revisiting if
those endpoints ever become non-admin-reachable.
### Verification
- New `tests/email-param-single-decode.test.js` — 6/6: source assertions pin
"no `decodeURIComponent(req.params.email`" and the direct read in all eight
handlers, keep the target-bound `requireActionTokenOr403` bindings and the
real-email mints in place, and guard the non-param decodes from an
overzealous sweep; a behavioral test proves against the installed Express
4.22.2 that `encodeURIComponent("bob%61@x.com")` round-trips to the stored
address on all eight route shapes and that a malformed `%zz` is rejected
400 by Express before any handler runs. Mutation-checked: reintroducing the
old pattern fails 2/6.
- Full Node suite 582/582 (`npm test`), `node --check` clean on `index.js`.
## trusted_subnets wired as a global rate-limiter bypass (dead configuration fixed)
`POST /api/settings/security` accepted, validated and persisted
`security.trusted_subnets` — and the destructive-action step-up gating that
write described it as storing "trusted-subnet bypass ranges" — but after the
db-proxy IP-authorization removal left the field orphaned, nothing ever read
`security.trusted_subnets`. Neither global rate-limiter store consulted it, so
operators who configured subnets through the settings API got silently no
effect, and step-up was protecting a no-op write.
### Fix
- **Sole new consumer: `ipMatchesTrustedSubnets(ip, subnets)` in
`utils/ip-subnet-validation.js`.** Pure and fail-closed by construction: an
unparseable address, a non-array or empty list, or junk entries all resolve
to "not trusted" — a broken configuration can never widen the bypass.
Matching goes through the existing `ip-range-check` dependency, which
normalizes IPv4-mapped IPv6 (`::ffff:10.0.0.55` matches `10.0.0.0/24`, and
a bare mapped entry matches its plain IPv4 address). IPv4-mapped CIDR
entries (`::ffff:10.0.0.0/120`) are rejected at validation: their prefix
applies to the IPv6 form while matching compares plain IPv4, so they could
never match — validation refuses to store silent no-ops.
- **Wired into both global limiter stores.** The Redis-backed
`globalLimiter`'s `skip()` and the in-memory `rateLimiterMiddleware` both
call `isRequestFromTrustedSubnet(req)` immediately after the
`rate_limiting` gate and before the tracked-IP capacity guard, so a trusted
IP can neither be counted, 429'd, nor 503'd — and the documented "identical
policy regardless of which store is active" invariant holds.
- **Scope deliberately excludes the auth-path limiters** (login, recovery,
2FA step-up) and db-proxy: network position must never soften brute-force
protection, and the db-proxy IP-authorization removal stays removed. A
source-assertion test locks the helper to exactly one definition plus the
two limiter call sites and keeps db-proxy free of any `trusted_subnets`
wiring.
- **IP resolution uses `getRequestIp`** — the trusted-proxy-aware value the
in-memory limiter keys on and `securityLog` reports, so bypass and bucket
always agree in that store. The Redis store keys on `req.ip` per
`TRUST_PROXY` instead; with the default configuration the two resolutions
coincide, and where an operator's `TRUSTED_PROXY_IPS`/`TRUST_PROXY`
settings diverge, the bypass still grants a spoofed X-Forwarded-For no
power beyond what the operator's own trusted-proxy configuration already
extends to the limiter's keying.
- **Empty list (the shipped default) = exactly the old behavior**: the
matcher fails closed to today's limiter semantics, and the write-side
validation (all-or-nothing, sanitizer on every load path) is unchanged.
- **Step-up now protects a real weakening write**: adding a subnet exempts
those sources from generic throttling (the `/api` limiter and the app-wide
in-memory limiter, which also covers non-`/api` routes), which is what the
`requireDestructiveActionStepUp` gate on `POST /api/settings/security` was
already assuming (M-2's rationale). Dedicated brute-force limiters (login,
recovery, 2FA step-up) are unaffected by the bypass.
### Verification
- New `utils/ip-subnet-validation.test.js` (14/14) — the isValidSubnet /
validateTrustedSubnetsInput / sanitizeTrustedSubnets matrices plus the
fail-closed matcher matrix: CIDR in/out, bare IP, IPv6, IPv4-mapped,
boundaries, junk entries, `unknown`, and `0.0.0.0/0` covering IPv4 only.
- New `tests/trusted-subnet-limiter-bypass.test.js` (7/7) — source
assertions: the helper is defined exactly once after `getRequestIp`, both
limiter stores call it in the right order (before redis-yield, capacity
guard and counting), the name appears exactly three times in `index.js`,
and `utils/db-proxy.js` still carries no `trusted_subnets`,
`ipMatchesTrustedSubnets`, or `isIpAuthorized` wiring.
- `node --check` clean on `index.js` and `utils/ip-subnet-validation.js`;
full Node suite 604/604 (`npm test`);
`node scripts/verify-trusted-subnet-validation.js` extended with the same
matcher matrix through the real `ip-range-check` (section [5b], 106/106).
## Audit round 2026-09-10 — DB credentials on process argv (L1, both auditors)
`/proc/<pid>/cmdline` is world-readable, so any local user could capture DB
credentials that were passed as child-process arguments. Three spots were
flagged — the MongoDB install-verification `mongosh -u admin -p <password>`
(index.js), the `mysql --password=$MYSQL_PASSWORD` admin probe and its cached
command that routine panel-driven MySQL user management reuses (index.js), and
the privileged runner's `op_mysql_admin` doing the same as root
(`privileged/adpanel-priv`) — and the sweep found the same class in seven more
places that are fixed identically.
### Remediation model
- **MySQL/MariaDB** — the password travels in the child's `MYSQL_PWD`
environment variable. `/proc/<pid>/environ` is 0400 and owned by the process
uid, so it is not readable by other local users, unlike cmdline. The client
resolves it identically to `--password=`, and no temporary files or escaping
are involved. (Already the convention in `initialize.sh`; noted as
deprecated-by-upstream, but supported across MySQL 8.x and MariaDB, and every
auth probe falls through to socket/debian.cnf methods if it ever stops
working.)
- **MongoDB** — mongosh has no environment-variable or stdin auth, so scripts
that embed passwords are written to a 0600 file inside a fresh 0700
`fs.mkdtempSync` directory and removed as soon as the child exits (the
documented `--defaults-extra-file`-style pattern adapted to mongosh). The
shared helper `_mongoshRunScriptFile(shellBin, args, script, opts)` in
`index.js` preserves the previous spawn semantics: `{code, stdout, stderr}`
results, spawn errors expose `errCode` so the mongosh→legacy-shell ENOENT
fallbacks keep working, and the settings-API runners keep their 15s timeout.
### Changes
- **index.js** — new helpers `_mysqlEnvWithPassword` and
`_mongoshRunScriptFile`; `_probeMySqlCmd` accepts a per-call env. Fixed:
the `MYSQL_PASSWORD` probe and the cached admin command now carry
`envPassword` instead of `--password=` and `runMySqlAdmin` spawns with
`MYSQL_PWD`; install-time `createUser` script (embeds the admin password)
and the auth verification (`-u adminUser -p adminPassword`) moved to staged
files — verification now prints `MONGO_VERIFY_OK` only after
`connectionStatus` shows an authenticated user AND `ping` succeeds, so the
success marker is unreachable from an unauthenticated connection (plain
`ping` is allowed without auth, the old check was weaker);
`createMongoUser`/`createMongoUserLegacy`/`updateMongoUserPassword`/
`updateMongoUserPasswordLegacy` and the three settings-API `runMongosh`
closures (create user, delete user, change password) are staged-file based.
The only remaining `--eval` spawns are the two delete-user paths whose
script contains nothing but the username.
- **privileged/adpanel-priv** — `op_mysql_admin` probes and execs with
`MYSQL_PWD="$MYSQL_PASSWORD"` instead of `--password=`, exported only when
the env-password method wins and only for the exec'd client (exec replaces
the shell, so the variable cannot leak anywhere else). Probe order and exit
semantics unchanged; verified end-to-end with a recording `mysql` shim as
root.
- **initialize.sh** — `mysql_exec_as_root` uses `MYSQL_PWD` instead of
`-p"$root_pass"`; both MYSQL/Redis URL encodings and both bcrypt hash
generations read the secret from the environment instead of `process.argv`;
`wait_for_redis` uses `REDISCLI_AUTH` instead of `redis-cli -a`; the admin
bootstrap and user-creation flows hand the TOTP secret to
`scripts/create-user.js` and the QR generator via environment variables
(`env(1)` form so it survives `$SUDO`), and the created panel password is
pre-hashed (bcrypt cost 10, identical to what `--password` produced) and
passed as `--password-hash`.
- **scripts/create-user.js** — plaintext credential flags are rejected at
parse time (exit 2 with guidance): `--password`, `--secret` and
`--current-password` would place a usable credential on the process's own
argv, so they are no longer accepted at all. The environment is the only
non-argv path (`ADPANEL_USER_PASSWORD`, `ADPANEL_USER_CURRENT_PASSWORD`,
`ADPANEL_USER_TOTP_SECRET`), and `--password-hash` stays accepted — a bcrypt
hash is not a usable credential. `initialize.sh`'s change-password flow was
converted accordingly (`ADPANEL_USER_CURRENT_PASSWORD` via `env(1)`).
`scripts/migrate-db-user-privileges.js` drops `-u/-p` from
the mongosh argv entirely: when admin credentials are used, a fail-closed
auth preamble (`db.auth` + `connectionStatus`, `quit(1)` unless
authenticated) is prepended to each eval and staged as a 0600 file in a
0700 temp dir removed at process exit; `--mongo-admin-password` on the CLI
is still accepted but warns (the password sits on that process's own argv —
`ADPANEL_MONGO_ADMIN_PASSWORD` is the safe path and stays the documented
default).
### Deliberately unchanged
- The two settings-API MongoDB user flows temporarily disable
`authorization` in `/etc/mongod.conf` (loopback-pinned maintenance window)
instead of authenticating — no credentials on argv there, and changing that
design was out of scope.
- SQL with embedded (escaped) per-user passwords flows to the mysql-admin
runner over stdin pipes, never argv — unchanged.
### Verification
- New `tests/argv-secret-exposure.test.js` (10/10): source assertions that
every argv-credential pattern is gone and the safe mechanisms are wired
(including the ENOENT fallbacks), plus functional tests —
`_mongoshRunScriptFile` extracted from `index.js` and driven against a fake
shell (secret reaches the staged file, never argv, staging dir removed,
timeout → `code -1`, ENOENT → `errCode`); `adpanel-priv mysql-admin`
executed as root with a recording `mysql` shim (both probe and exec see
`MYSQL_PWD`, argv is clean, and `MYSQL_PWD` is *not* exported on the
socket-auth path); the real migration script end-to-end with a recording
`mongosh` shim (staged 0600 file, clean argv, staging dir gone after exit);
and `create-user.js` run with each rejected flag (`--password`, `--secret`,
`--current-password`) expecting exit 2 with guidance before any sudo check
or DB access.
- `node --check` clean on `index.js`, `scripts/create-user.js`,
`scripts/migrate-db-user-privileges.js`; `bash -n` clean on
`initialize.sh` and `privileged/adpanel-priv`.
- Full node suite 659/659 (`npm test`), including the 10 new tests.
---
# Security Fixes — Database Remediation (2026-09-10)
Remediation of the database-audit findings H1, H2, M1 and M2. All verified
with `node --check` (JS), `node scripts/verify-db-user-privileges.js`
(31 checks), the full node suite 721/721 (`npm test`), and — for H1 — live
positive/negative access tests against a running MySQL 8.0 server with a
scratch account (created and dropped for the test).
## H1 — Panel-issued MySQL users held global privileges (panel DB exposure)
`createMySqlUser` granted the panel DML/DDL privilege set `ON *.*`, which
includes the panel's own schema (`users.password` hashes, 2FA secrets,
recovery codes, node tokens). The old comment claimed isolation via phpMyAdmin
`hide_db + AllowDeny rules`; `hide_db` is a UI filter only and no AllowDeny
rules existed.
- `utils/db-user-privileges.js` now holds the MySQL builders as the single
source of truth: `MYSQL_PANEL_USER_PRIVILEGES` (unchanged DML/DDL set — no
SUPER/FILE/PROCESS/GRANT OPTION), `MYSQL_SYSTEM_DATABASES`
(mysql/sys/information_schema/performance_schema), `isProtectedMySQLDatabase`
(case-insensitive), `buildMySqlGlobalGrantSql` (MySQL >= 8 with
`@@partial_revokes=ON`: global grant + `REVOKE ALL PRIVILEGES` on the panel
schema, `mysql` and `sys`) and `buildMySqlPerDatabaseGrantsSql` (MariaDB /
MySQL 5.7 / partial_revokes OFF: per-database grants over existing
non-protected databases only). All builders fail closed on identifiers.
- `createMySqlUser` classifies the running server (`SELECT VERSION()`,
`@@global.partial_revokes`, cached) and picks the strategy its privilege
tables actually support. Detection or enumeration failure grants over
whatever was enumerated (possibly nothing) — never a schema-wide fallback.
A defensive `REVOKE ALL PRIVILEGES, GRANT OPTION` strips stale global grants
from accounts created by older panel versions before re-granting (verified
as a no-op success on fresh accounts against MySQL 8.0).
- `runMySqlAdmin` now returns captured `stdout` (backward-compatible field) so
flavor probes and `SHOW DATABASES` enumeration work on every admin channel.
- `scripts/migrate-db-user-privileges.js`: the "MySQL: nothing to do" stance is
replaced by a real section (dry run / `--apply` / `--verify`). Account
discovery is scoped: only panel-recorded accounts, plus accounts
demonstrably holding schema-wide/protected-schema/admin grants, are touched —
manually created narrow app accounts can never be widened by the script.
`--verify` flags over-privileged non-panel accounts as warnings without
counting them as migration failures.
Not changed (documented decisions): the `'%'` default host and phpMyAdmin's
`hide_db` (cosmetic but harmless). On MariaDB/MySQL 5.7 the per-database
strategy means panel-issued users can no longer create brand-new databases
themselves; least privilege is the point — new databases should be granted by
the panel admin.
## H2 — MongoDB user operations disabled authentication on the live server
Every /mongodb/users operation rewrote /etc/mongod.conf to strip
`authorization: enabled`, restarted mongod, worked unauthenticated, then
re-enabled auth and restarted again — a local unauthenticated-access window on
every operation, permanent if the panel died mid-operation (restore was
catch-only), and two service bounces per operation.
- New `utils/mongo-admin-credentials.js` (pure): AES-256-GCM `enc:v1:`
envelopes with a mongo-admin-specific scrypt salt (same discipline as the
webhook secrets, distinct derived key). Fail-closed null on any failure.
- The install-time admin credential is now sealed into
`mongodb-config.json` (`adminAuth`) at setup; plaintext never at rest,
never logged.
- `ensureMongoAdminAuth(config)` returns the sealed credentials when present
(normal path: zero server changes, zero restarts). Only for legacy installs
without sealed credentials does it bootstrap ONCE — finally-guarded
restore, fresh random admin password, seal + persist before restore,
verification via `connectionStatus` after auth is back on. A one-flight
latch serializes concurrent first-ever bootstraps (the dedicated endpoints
hold `mongodbOperationMutex`; the generic endpoints do not).
- The three /mongodb/users endpoints now authenticate as the stored admin via
`runAuthenticatedMongosh` (one 0600-staged script: auth preamble +
`connectionStatus` assertion + operation; credentials never in argv) —
no mongod.conf rewrites, no restarts. Rotating users[0]'s password re-seals
the stored credential in the same request.
- Startup self-heal re-enables `authorization: enabled` for servers left
unauthenticated by older panel versions.
## M1 — Deterministic pgAdmin recovery password
The pgAdmin readiness path reset the admin password to a value derived from
`MYSQL_PASSWORD` or `sha256(SESSION_SECRET || admin email)` — a guessable
backdoor credential, and a silent lockout nobody could retrieve.
- Derivations removed. An explicit `PGADMIN_SETUP_PASSWORD` is honored
as-is; otherwise every recovery generates `crypto.randomBytes(18)`
base64url, sealed at rest (existing envelope helper) into
`pgadmin-config.json` BEFORE the reset runs, and deleted if the privileged
job fails so the retrieval endpoint can never serve an unused password.
- One-time handoff: `POST /api/settings/database/access-token` returns
`recoveredCredentials` only on the request that performed a recovery
(admin + action-token gated, `no-store`); the startup path logs the fact,
never the credential. New admin-gated, action-token-gated
`POST /api/settings/database/pgadmin/credentials` serves the sealed
credential later (envelope-only, 404 on nothing stored / undecryptable).
- Retrieval step-up: the credentials route additionally enforces the
destructive-action credential step-up (fresh password or 2FA verification,
or a live grace grant minted by an earlier verification — e.g. the
verify-install modal on the way to a setup/disable) with `persistGrant:
false`, so a read-only reveal never mints a grant that could later
authorize destructive actions. The step-up runs before the config lookup
(even the existence of a sealed credential is not disclosed unverified),
and every successful reveal is audit logged. Without this a hijacked admin
session is one `GET /api/settings/database` (which mints the one-time
token alongside the others) plus one POST away from the plaintext
credential; the client establishes the grant through the same
verification modal the install actions use.
## M2 — Generic user-management API broken (and leaky) for MongoDB
`createMongoUser` / `updateMongoUserPassword` / `deleteMongoUser` (and their
legacy fallbacks) spawned mongosh without credentials — every call failed
against the auth-enabled server the panel installs — and `deleteMongoUser`
put its eval script on world-readable argv via `--eval`.
`checkDatabaseConnection` rubber-stamped every non-mysql type as connected.
- All five generic paths now authenticate through the H2 infrastructure
(`ensureMongoAdminAuth` + `runAuthenticatedMongosh`, legacy shell included);
the argv leak is closed; auth failure maps to the stale-credential error.
Deleting the install-time admin via the generic API is refused (mirrors the
dedicated endpoint), and rotating its password re-seals `adminAuth`.
- `checkDatabaseConnection` performs a real authenticated MongoDB check
(connectionStatus, provided credentials, staged script) and a real
PostgreSQL check (`psql` with `PGPASSWORD` in the child env, never argv);
mysql logic is unchanged; unknown types fail closed. Missing client
binaries degrade to the previous pass-through with a warning.
### Verification
- `node scripts/verify-db-user-privileges.js`: 31 checks, 0 failed
(MySQL builder + delegation assertions added).
- New suites: `tests/db-mysql-scoping.test.js` (12),
`tests/mongo-admin-auth-hardening.test.js` (18),
`tests/pgadmin-recovery-hardening.test.js` (14),
`tests/mongo-generic-user-api.test.js` (18).
- Full node suite 721/721 (`npm test`).
- H1 verified live against MySQL 8.0.46 (`partial_revokes=0` → per-database
path): a freshly created user cannot `SELECT` from `adpanel.users` or
`mysql.user`, sees only its granted databases, and a stale over-granted
account is fully rescoped by the new statement batch.
# Security Fixes — Create-User Account Hijack Remediation (2026-09-12)
## C1 — "Create DB user" silently hijacked any pre-existing account (CRITICAL)
`POST /api/settings/database/users` checked existence against panel
bookkeeping only (`database-config.json` users array) and then ran a
create-or-reset batch: `CREATE USER IF NOT EXISTS ... IDENTIFIED BY` +
`ALTER USER ... IDENTIFIED BY` + `REVOKE ALL PRIVILEGES, GRANT OPTION`.
Because `IF NOT EXISTS` no-ops on a live account while `ALTER USER` does
not, posting `{"username":"root","host":"localhost"}` (or
`debian-sys-maint`, or any untracked application account) re-passworded
that account to the caller-chosen value and demoted it to panel-scoped
privileges. `root` and `debian-sys-maint` are identities of the panel's
OWN admin channel (unix socket / `MYSQL_PWD` / `/etc/mysql/debian.cnf`),
so the same POST was also a self-denial-of-service on database
management. No reserved-name blocklist, no confirmation, no live-server
probe.
The identical bug class existed on the other engines of the same route:
- PostgreSQL: `buildPostgresCreatePanelUserSql` ran
`ALTER ROLE ... PASSWORD` in the ELSE branch of its create-if-missing DO
block, then `ALTER ROLE ... NOSUPERUSER NOCREATEDB NOCREATEROLE` —
`{"username":"postgres"}` re-passworded and demoted the bootstrap
superuser (also the panel's peer-auth psql identity). Worse, the
privileged psql channel ran WITHOUT `ON_ERROR_STOP`, so psql continued
past failed statements and still exited 0: partial failures reported
success everywhere (a failed `ALTER ROLE PASSWORD` / `DROP ROLE`
counted as success; the drop taxonomy could erase bookkeeping for a
live role).
- MongoDB: `createMongoUser` treated createUser's "already exists" error
as success and appended bookkeeping — adopting an untracked account
whose live password the panel does not know as a "panel-issued" user.
Four independent layers close the class (each alone is sufficient):
1. **Reserved-name blocklist** (shared, `utils/db-user-privileges.js`):
`mySqlAccountIsReserved` refuses `root`, `debian-sys-maint`, `mysql`,
`mariadb` and the `mysql.*` / `mariadb.*` internal accounts
(case-insensitive); `postgresRoleIsReserved` refuses `postgres`,
`public` and the server-reserved `pg_` prefix. Enforced pre-token
(400, token preserved) in the create route, inside
`createMySqlUser` / `createPostgresUser`, and in the setup route for
fresh local MySQL setups (see C2).
2. **Create-only provisioning SQL**: `createMySqlUser` now runs a plain
`CREATE USER ... IDENTIFIED BY` as its first statement — no
`IF NOT EXISTS`, no `ALTER USER`, and the dead `forceRecreate`
(`DROP USER IF EXISTS`) branch is removed. A pre-existing account
fails the batch at its first statement (the mysql client aborts on
the first error on every channel: direct, privileged runner,
skip-grant job), so the mutating `REVOKE`/grant statements can never
run against an account this flow did not create. The PostgreSQL DO
block raises `ADP_PG_ROLE_ALREADY_EXISTS` instead of
`ALTER ROLE ... PASSWORD`, the redundant post-create flag clamp is
gone, and `op_psql_postgres` now runs `psql -v ON_ERROR_STOP=1`
(mirroring `scripts/migrate-db-user-privileges.js`) so the raise
aborts the batch and psql stops exiting 0 on SQL errors.
3. **Live-server pre-existence probe** (`probeMySqlAccountExists`):
before provisioning, the route queries `mysql.user` for the requested
name (LOWER()-matched SQL-side, case-insensitive JS-side — MySQL user
matching is case-insensitive; positional row parsing as in
`probeMySqlAccountHosts`). An untracked live account → 409
`MYSQL_ACCOUNT_ALREADY_EXISTS` with the remediation spelled out; a
failed probe → 500, nothing created (fail closed). Exists-errors that
slip through a race (probe → CREATE window, e.g. out-of-band DBA
work) are classified from the engines' create-only error signatures
(MySQL 1396 / "Operation CREATE USER failed", the PostgreSQL marker,
MongoDB `accountExists`) into 409s per engine. The dedicated MongoDB
route's existing refusal pattern is unchanged.
4. **Setup-flow guard**: the setup route deliberately ADOPTS a
pre-existing same-name account (staged create-if-missing, commit-time
password) — that is its purpose — so its semantics are kept, but a
fresh local MySQL setup naming a reserved account is refused with a
400 (pre-token). The only exemption is a re-setup of the SAME local
MySQL deployment whose tracked setup administrator already carries
that name: refusing it would force a rename whose teardown would then
DROP the tracked reserved-named accounts, bricking the server harder.
Remote and non-MySQL setups never provision local accounts and are
out of scope.
Deliberately unchanged: `ensureMySqlSetupAccount` keeps
`CREATE USER IF NOT EXISTS` (staged create-if-missing is the documented
setup invariant; the commit-time password application runs only after
every pre-commit check); the password and delete routes remain
bookkeeping-gated; pgAdmin's bootstrap flow keeps its explicit reset
semantics behind its own reserved-name list and step-up gate.
### Verification
- `node scripts/verify-db-user-privileges.js`: 43 checks, 0 failed
(create-only shape, probe gate, reserved lists, setup guard, and the
`ON_ERROR_STOP` requirement are all pinned as static/functional
regressions).
- `tests/db-mysql-scoping.test.js`: 14/14 — new functional tests — reserved
names refuse before ANY SQL runs (no channel call at all); the
provisioning batch contains no `DROP USER` / `IF NOT EXISTS` /
`ALTER USER`; route source must probe the live server and gate
reserved names per engine.
- Full node suite 739/739 (`npm test`).
## Audit round 2026-09-12 — db-proxy token store was not cluster-safe (availability, multi-worker installs)
The db-proxy token store was a plain per-process in-memory `Map`
(`utils/db-proxy.js`). The panel's shipped production topology is PM2
cluster mode with `INSTANCES = cores - 2` (scripts/generate-ecosystem.sh),
so the worker that minted a db-proxy token (POST
`/api/settings/database/access-token`, setting the HttpOnly
`adpanel.dbproxy.*` cookie) was usually not the worker that received the
following `/db-access/<service>/` navigation. `validateToken` missed on the
second worker → 404 plus the cookie was cleared; retries only worked when
they happened to land back on the minting worker. The "Open
phpMyAdmin/pgAdmin" buttons were therefore effectively broken on any
standard multi-core install (the flow fails closed — an availability bug,
not an exploit). This box runs `instances: 1`, so it was unaffected here;
the shipped default for bigger servers was not.
### Remediation model
The store is now backend-switchable, selected per call from configuration
injected by index.js (`dbProxy.configureTokenStore`), mirroring the two
cross-worker patterns the codebase already uses:
- **Redis** (the panel's session Redis client, when `SESSION_STORE != file`)
— one key per token with an `EX` TTL plus a ZSET index (member = token
hash, score = expiresAt) so user/service/session-wide revocations are
bounded lookups instead of `SCAN`. Cluster-safe across workers and
restarts. This is the `claimSessionRevokeTargetToken` /
write-through-transfer-job family of patterns.
- **Flat JSON files under `data/db-proxy-tokens/`** (0600 records in a 0700
directory, atomic tmp+rename writes via `utils/atomic-file.js`) — the
`install-job-store` durability pattern. Redis is not guaranteed on every
install (`SESSION_STORE=file` leaves `redisClient` null), but PM2 cluster
workers share the host filesystem, so files restore cross-worker
visibility for exactly the topology that was broken.
- **Process memory** — the legacy behavior, kept as the fallback when
nothing is configured or the file store degrades (unwritable/full disk
degrades loudly to per-process memory for that worker's lifetime; the
store is never worse than the pre-fix Map).
Credential hygiene for the now-persisted tokens (shared stores are readable
by anything that can read the panel's data dir / Redis, which already holds
the live session records — this is defense in depth, not the boundary):
records are keyed by `SHA-256(token)` (the 128-bit random token itself is
never persisted anywhere) and carry `SHA-256(sessionId)` instead of the raw
panel session id, so the store cannot be mined for replayable `adpanel.sid`
cookie values. `sessionMatchesToken` compares hashes with
`crypto.timingSafeEqual`; the live-session re-validation on every request
remains the actual authorization boundary.
Failure policy (fail closed, no new hazards):
- Minting that cannot be persisted returns `null` → the route 500s. A token
the store cannot remember is a token it cannot revoke cross-worker.
- Validation that cannot be answered (Redis down, data dir unreadable)
throws `StoreUnavailableError`; the middleware answers **503 + Retry-After
and keeps the cookie** — deliberately distinguishable from a stale-token
404 + cookie clear, so a store blip never logs an admin out of the proxy.
- Revocations never throw (logout must complete); failures are logged. The
token alone is inert — every use also requires the live minting admin
session, and logout / session revoke destroy that session independently.
- Every Redis store op races a short timeout, so a reconnecting client
(node-redis offline queue) cannot stall the `/db-access` pipeline; the
fail-fast mirrors the limiter's `isReady` check.
- Known-benign races are documented in `utils/db-proxy.js`: a touch racing a
revocation can re-persist a just-deleted record (Redis refresh therefore
uses `SET XX`, which cannot resurrect a deleted key; the file backend's
rename cannot be conditional and accepts the race). Every such token stays
session-bound and TTL-capped, and no privilege boundary depends on the
store winning.
### Changes
- **utils/db-proxy.js** — the `Map` token store is replaced by the
three-backend store (`memoryStore`, `createFileStore`, `createRedisStore`)
with a strict record sanitizer (unknown shapes sanitize to a miss, never
to an authoritative record); `generateToken`/`validateToken`/`touchToken`
/`revoke*`/`getSessionCount` are async with the error contract above; the
sliding-TTL touch throttles file rewrites (one per 60s per token) so the
per-request touch cannot turn into tmp+rename+fsync churn on phpMyAdmin
asset loads; the middleware is async and wraps every store call in a
fail-closed catch. `MAX_SESSIONS` (500) is now a global cap across workers
on shared backends, evicted oldest-first at mint time. `configureTokenStore`
and `StoreUnavailableError` are new exports; every other export keeps its
name and contract.
- **index.js** — `dbProxy.configureTokenStore({ redis: () => redisClient,
dataDir: path.join(__dirname, "data") })` right after the session-store
init block; all seven store call sites (logout revocation, the four
session-revoke sites, the access-token route's revoke-then-mint) are
`await`ed.
- **scripts/verify-db-proxy-session-auth.js** — converted to the async API
and extended with a cluster section: mint-on-A / validate-proxy-revoke-on-B
through separate module instances over the file backend, at-rest hygiene
(hashed filename, no raw token/session id on disk, 0600/0700), degrade-to-
memory on an unwritable store, and Redis-error fail-closed behavior
(503, cookie kept, mint → null).
- **scripts/verify-trusted-subnet-validation.js** — matcher checks updated to
the hashed `sessionIdHash` record field (same fail-closed matrix).
Deliberately unchanged: the cookie contract (`adpanel.dbproxy.*` name,
path, HttpOnly/SameSite/Secure attributes, TTL), the service slug parsing,
the header allowlists and response rewrites, the heartbeat route and its
sliding-cookie behavior, and `TOKEN_TTL_MS`. Tokens minted before the
upgrade were in-memory and die with the old process; users re-click "Open"
once after deploying.
### Verification
- `node scripts/verify-db-proxy-session-auth.js`: 106 checks, all pass
(sections 1–7 pin the pre-existing session-binding/cookie/header
properties; section 8 pins the cluster properties).
- `node scripts/verify-trusted-subnet-validation.js`: 110 checks, all pass
(db-proxy must stay free of trusted_subnets / IP authorization).
- `tests/db-proxy-cluster-token-store.test.js`: 12 new tests — cross-worker
mint/validate/touch/revoke/supersede on both shared backends, at-rest
hygiene, corrupt/expired/forged records fail closed, degrade-to-memory,
SET XX no-resurrection, Redis error + hang fail-closed with the op
timeout, middleware 503-vs-404 cookie behavior, and index.js wiring
assertions.
- Full node suite 827/827 (`npm test`).
## MySQL Admin Channel Hardening — ERROR 1044 / root-access reduction (2026-09-13)
Reproduced failure on a live installation: a legacy setup that adopted `root`
as its tracked database administrator demoted `root@localhost` (its staging
batch runs `REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'root'@'localhost'`).
Because the panel's admin-channel probe verified only AUTHENTICATION
(`SELECT 1` keeps passing for a demoted root), every account-management batch
then aborted at its first GRANT with:
```
ERROR 1044 (42000) at line 3: Access denied for user 'root'@'localhost' to
database 'phpmyadmin'
```
(`phpmyadmin` is the alphabetically first schema the per-database grant
strategy may touch, so it named the failure.) phpMyAdmin setup could never
complete on such a server. Additionally, the panel process held effective
MySQL root power (socket auth as OS root, root password probing through the
operator-reused `MYSQL_PASSWORD`, and a root-SQL privileged op).
Fixes, layered so the channel self-repairs on every installation:
- **Capability-aware probing** (`index.js _probeMySqlAdminCapability`,
`privileged/adpanel-priv op_mysql_admin`): every admin-channel candidate
must pass a capability probe reading its own `mysql.user` row
(`Grant_priv='Y' AND Create_user_priv='Y'`), not merely authenticate. A
demoted root is skipped instead of poisoning every later batch.
- **Dedicated least-privilege admin account** (`adpanel_admin`@'localhost'):
the panel process now prefers this account for all database-management SQL.
It holds exactly the panel DML/DDL set on `*.* WITH GRANT OPTION` plus
`CREATE USER` (which authorizes DROP USER and ALTER USER password changes on
MySQL 8 and MariaDB) — no SUPER, FILE, SHUTDOWN, RELOAD, no writes to
`mysql.*`, no dynamic privileges. A compromised panel can no longer read
password hashes with administrative authority, restart the server, read
files, or touch the privilege tables. Credentials are sealed at rest
(SESSION_SECRET-keyed AES-256-GCM, `mysql-admin-credentials.json`, 0600) and
travel to the client via `MYSQL_PWD`, never argv. The name is reserved
(`MYSQL_RESERVED_USERNAMES`), so no panel-issued credential can take it.
- **Privileged self-repair** (`privileged/jobs/mysql-admin-bootstrap.sh`):
invoked by the panel once per cooldown when the server is reachable but no
capable channel exists (demoted state) or the dedicated account is missing.
It heals `root@localhost` through skip-grant-tables (engine-aware: MariaDB
via FLUSH+GRANT, MySQL 8 via direct grant-column restore) and provisions +
canary-certifies the dedicated account (CREATE/ALTER/DROP USER, db-scoped
GRANT, REVOKE ALL+GRANT OPTION, mysql.user probe, SHOW DATABASES). The job
exits non-zero unless the canary passes. The panel PROCESS never gains root
MySQL access from this; root SQL stays behind the OS-root sudo boundary for
recovery only.
- **The panel no longer probes MySQL root's password**: the
`mysql -u root` + `MYSQL_PASSWORD` probe is gone from the panel process
(the runner retains root methods as the privileged recovery channel).
- **Reserved-account immutability**: reserved server accounts (root,
debian-sys-maint, mysql.*, adpanel_admin, ...) are refused by every
staging/create/password/rollback/drop helper at the SQL layer; teardown
drop flows skip them with a warning (a legacy tracked 'root' entry can no
longer be deleted or demoted); the tracked-'root' re-setup exemption is
removed from the setup route.
- **No `FLUSH PRIVILEGES` in account-statement batches**: account-management
statements reload the grant tables themselves, so the admin channel no
longer needs RELOAD (the skip-grant job keeps its own FLUSH for direct
table manipulation).
- **phpmyadmin control schema protected**: `phpmyadmin` joins
`MYSQL_SYSTEM_DATABASES`, so panel-issued users never receive grants on it.
- **Sudoers**: `ADPANEL_DB_ADMIN_PASSWORD` added to the closed env_keep
allowlist for the bootstrap password hand-off.
Verified on the live installation: the bootstrap provisioned and certified
the dedicated account; the previously failing staging batch (including
`GRANT ... ON phpmyadmin.*`) executes cleanly through it. Regression tests:
`tests/mysql-admin-channel-hardening.test.js` (+ updated
`db-mysql-scoping.test.js`, `argv-secret-exposure.test.js`).
## settings.js — step-up challenge dead end (2FA popup) (2026-09-13)
Reproduced behavior: the destructive database endpoints (setup, disable,
change-type, pgAdmin/MongoDB setup+disable) are gated server-side by a
credential step-up whose client-side grace snapshot (`sessionsState /
stepUpSecurityState.graceExpiresAt`) could go stale while the page sat open
(grant spent via the reuse cap, expired server-side, clock skew). The client
then SKIPPED the verification modal (trusting the stale snapshot), sent the
request without a credential, received the 403 challenge
(`2fa-required` / `password-required`), and surfaced only the bare error
message — no popup, recovery only by full page reload.
Fix (`fetchDbRequestWithTokenRetry` in `public/js/settings.js`, the funnel
for every database-tab POST): a 403 whose body is a step-up challenge now
(1) applies the challenge's `revokeSecurity` payload — the server's
authoritative grace state, which un-poisons the stale snapshot for every
later flow — (2) opens the security verification modal FORCED (the server's
requirement outranks the local grace), and (3) re-mints the one-time action
tokens and retries the request exactly once after successful verification.
Security is unchanged server-side; the change only removes the dead end.
Regression tests: `tests/mysql-admin-channel-hardening.test.js` (settings.js
contracts).
## Audit round 2026-09-16 — M3–M6 remediation (node-proxy create, duplicate names, subdomain agent calls, SSH terminal token binding)
### M3 — node-proxy create committed a daemon server with no panel index row (and skipped validations)
`POST /api/nodes/:id/servers/create` (nodes.js) used to forward the raw name
and mcFork/mcVersion (which the daemon interpolates into the PaperMC/Purpur
API URL path) and return the daemon response without ever writing a
`servers` row — the server was unmanageable, absent from ACLs, and invisible
to `getServersUsingPortsOnNode`, so a second create could be granted the same
port on panel records. Fix:
- Name sanitized via the canonical `sanitizeServerToken`
(utils/server-name.js — index.js `sanitizeServerName` now delegates to the
same function), mcFork/mcVersion validated with the same strict
allowlist (`utils/minecraft-versions.js`) as the main create route,
rejecting instead of silently rewriting.
- Duplicate-name refusal inside the per-node lock
(`panelServerNameConflict`, mirrors `findServer`'s name/legacy_id/bot
matching).
- After the daemon create (or recovery via `waitForNodeServerReady`), a panel
index row is committed inside the same lock through an injected insert-only
writer (`nodesRouter.setServerIndexWriters({ insertServerIndexEntry })`;
nodes.js cannot import index.js — circular — so index.js injects it at
startup next to `setPermissionCheckers`). Without the injection the route
fails closed: it compensates with a daemon DELETE instead of leaving an
unmanageable server.
- Any index-commit failure triggers a best-effort compensating daemon delete
and a loud 409 (`server_name_exists`) / 500 (`index_commit_failed`).
- The route handler is wrapped in try/catch (Express 4 does not catch async
throws; a transient DB error must answer 500, not kill the worker).
### M4 — duplicate server-name create silently repointed the index row
`POST /api/servers/create` never checked `findServer(name)`; `servers.name`
is UNIQUE and the index writer used `ON DUPLICATE KEY UPDATE`, so creating
"foo" on node B overwrote the row of "foo" on node A, orphaning the original
container (still running, still holding its port). The only same-name guard
was an in-memory Set wiped wholesale every 10 minutes while daemon creates
legitimately run up to 600s. Fix:
- Route-level refusal: `findServer(name)` (name/legacy_id/bot match) →
409 `server_name_exists`, before the step-up-protected create lock.
- `serverCreateLocks` is now a TTL map (`acquireServerCreateLock`, 30-minute
expiry > worst-case create path, 60s sweep); entries are removed in the
request's `finally`. The wholesale `clear()` timer is gone.
- `upsertServerIndexEntryUnlocked` split: with no pre-existing row it now
does a PLAIN INSERT and maps `ER_DUP_ENTRY` to a descriptive error instead
of silently overwriting the UNIQUE(name) row of a concurrently created
server. With a pre-existing row the previous merge-upsert behavior is
unchanged (status writers, transfer, FiveM artifact installs all hit that
path).
- Create paths use the new insert-only `insertServerIndexEntry` (write-lock
wrapped, non-mutating): the UNIQUE key is the cross-worker arbiter the
per-worker lock cannot provide (pm2 cluster mode). A lost race is answered
409 after a best-effort compensating daemon delete.
### M5 — subdomain agent-call failures silently swallowed → panel/node divergence
`nodes.httpJson` resolves `{status:0}` on network errors and never rejects,
and the subdomain routes treated resolution as success: an approved row
persisted when the daemon answered 400/500, and DELETE removed the DB row
even when the daemon call failed (orphaning the nginx vhost with no remaining
record). Fix (routes/subdomains.js):
- New `callAgentSubdomain()` helper: every agent call's response is checked —
`status !== 200 || !json.ok` is a failure carrying the daemon's error
detail; status 0 (transport) maps to 504, daemon rejections to 502.
- POST create rolls the row back unless the daemon confirms the vhost.
- verify: DNS failure → canceled (unchanged); DNS mismatch now asks the
daemon to delete the (possibly still live) vhost BEFORE flipping the row to
canceled — daemon deletes are idempotent, so this also cleans legacy
orphans; DNS match sets approved then syncs the vhost, reporting agent
failures (row stays approved; re-running verify retries the sync).
- DELETE: for non-canceled rows the daemon must confirm the removal or the
record is kept and 502/504 returned (no more orphaned vhost with no
record); canceled rows delete best-effort so they cannot wedge while the
node is down.
- Also fixed here: `nodes.nodeUrl(node)` was called without its `suffix`
argument, producing `...:8080undefined` URLs — every agent call in this
router died as an invalid URL and was swallowed as a "network error".
### M6 — SSH terminal token IP binding was dead code; metadata blocklist matched names only
The Go `tokenPayload` carried `ip` and `sameIP()` existed, but
`verifyToken` never compared the requester IP (`sameIP` had zero callers);
the panel's `verifySshTerminalToken` was symmetric, and the WS upgrade gate
checked only the HMAC. The token travels in URLs (logs, browser history), so
a single capture granted 20 minutes of arbitrary-SSH-dial capability from any
IP. Fix — enforced at BOTH ends:
- Go `verifyToken`: after the expiry check, `sameIP(payload.IP, requestIP)`
is mandatory — tokens without a usable IP binding are refused (the
issuing panel always embeds one).
- Go `requestIP(r, trusted)`: X-Forwarded-For / X-Real-IP are honored ONLY
from trusted proxy ranges (`SSH_TERM_TRUSTED_PROXIES`, default loopback =
the panel's own proxy hop), and the LAST XFF element wins. A direct
connection from any other address is attributed to its socket address, so
a client cannot assert an arbitrary bound IP. All-unparseable
configuration falls back to loopback trust (an operator typo must not
brick the terminal).
- Panel `verifySshTerminalToken(token, requestIp)`: requestIp is required
and the binding is enforced at the panel edge too (`sshTerminalTokenIpMatches`).
The WS upgrade gate passes `getRequestIp(req)`.
- `proxySshTerminalUpgrade` overwrites `x-forwarded-for` / `x-real-ip` with
the panel-resolved client IP — a client-supplied XFF can no longer pass
through to sshterm to claim its own bound address.
- Metadata blocklist: the literal-host map remains as a cheap first gate,
but the authoritative gate is now address-based — `isForbiddenMetadataIP`
(169.254.0.0/16 incl. IPv4-mapped forms, fd00:ec2::/32) is checked after
DNS resolution AND inside the dialer's `Control` hook
(`guardedSSHDialer`), which sees the concrete address about to be dialed —
closing both the hostname-resolves-to-metadata bypass and the DNS-rebinding
window between check and connect. The probe message and the real SSH
connection dial through the same guarded dialer (`openSSHSession` dials
manually and hands the conn to `ssh.NewClientConn`), and probe errors stay
sanitized.
Operational notes:
- `SSH_TERM_TRUSTED_PROXIES` (new, documented in .env.example): MUST be set
when `SSH_TERM_INTERNAL_URL` points the panel at an sshterm on a different
host — otherwise every token fails IP binding for that deployment
(fail-closed).
- A client whose address changes between page load and WebSocket connect
(WiFi↔cellular, CGNAT rotation, dual-stack family flip) is refused and
must reload the page; the panel re-mints a fresh bound token on every
`/ssh-terminal/` load (existing 401→re-issue path).
- Direct access to the sshterm port from non-trusted addresses is now
refused for tokens issued to other IPs (intended); the default bind also
remains loopback-only.
Regression tests: `cmd/sshterm/security_test.go` (metadata IP ranges,
XFF trust policy, token IP binding end-to-end, trusted-proxy parsing
edge cases), `tests/destructive-route-guards.test.js` (updated to the TTL
create lock; invariant "step-up before create lock" preserved). Full
suites: 865 JS tests + `go build ./...` + `go vet` + `go test ./...` green.
## Audit round 2026-09-18 — template export→import round trip + fail-closed env boundary (two Low findings)
### L-a — Export→import round trip silently dropped ports, portProtocols, volumes
`exportTemplate` downloads the canonical stored template shape
(`id/name/docker.*` including `docker.ports`, `docker.portProtocols`,
`docker.volumes`), but the import converter
(`adpanelStoredTemplateToTemplatePayload`) and the editor save body never
carried those fields — they were "intentionally not carried over" because the
editor form cannot represent them. Cloning a multi-volume template through
export→import therefore created servers whose plugin/world volumes never
existed: data landed in the container layer and vanished on recreate, with
no error anywhere in the flow.
Fix (`public/js/settings.js`):
- `templateEditorState.containerConfig` parks the container-mount surface a
JSON import carries. `adpanelStoredTemplateToTemplatePayload` now hoists
`docker.ports`, `docker.portProtocols` (mirroring the server's
`portProtocols || port_protocols || protocols` alias chain) and
`docker.volumes` onto the flat payload, deep-cloned so the editor state
never aliases the template listing cache.
- `templateContainerConfigFromImportPayload` parks exactly those fields
(body-level `portProtocols || port_protocols` alias, arrays/comma-strings/
single-spec shapes the server already accepts); unknown keys — including
prototype-pollution names — are never carried.
- The save handler merges the parked config into the create/update request
body, where the server's existing fail-closed boundary
(`validatePortListInput`, `validateTemplateVolumeListPayload`) rejects
invalid specs by name before any credential step-up is spent.
- State hygiene: the parked config resets in `clearTemplateForm`,
`setTemplateModalMode('create')` and `openTemplateEditModal`, so a stale
import can never ride into a later save. Plain form edits still omit the
fields, which is what keeps the PUT stored-fallback (and its workdir
auto-align) in charge — pure edits are behaviorally unchanged.
- The import feedback now states that ports/protocols/mounts were carried,
so the behavior is visible, not implicit.
Console config remains intentionally excluded (the create endpoint rebuilds
it from the image default; only the update endpoint preserves a stored
console) — documented in the importer comment.
### L-b — Invalid/oversized env entries silently dropped with 200 OK
`constructTemplateDefinition` (create + store-install) and the update
endpoint's explicit-env branch ran env through `sanitizeEnvPayload` alone:
keys like `"MY VAR"`, keys/values over the size caps and the >128-entry case
were silently dropped, so the admin's "Template created!" stored a template
whose servers ran without the env they reviewed. Inconsistent with the same
endpoint's fail-closed volume boundary.
Fix:
- New `validateTemplateEnvPayload` in `utils/server-template-payload.js`
(shared module): accepts the same shapes (missing/null env is a valid
"no variables" request), returns byte-identical output to
`sanitizeEnvPayload` for accepted input, and answers `{ error }` naming the
rejected entry otherwise — bad key charset, empty key, pollution keys,
oversized key/value, entry cap, and JSON object/array values that would
previously have been coerced to `"[object Object]"` garbage.
- `constructTemplateDefinition` and the update endpoint's explicit-env branch
now 400 with that message; validation still runs before the credential
step-up. The update endpoint's stored-fallback branch keeps the silent
sanitizer so legacy templates self-heal on save instead of becoming
uneditable (mirroring the volumes policy: explicit input fails closed,
stored data normalizes).
- The store review dialog mirrors the new boundary: the summary gained an
`envInvalid` flag (same pattern as `portsInvalid`/`volumesInvalid`) rendered
as "invalid — install will be rejected", so the dialog can never show a
sanitized env for an install that will 400. `install.env` stays on the
silent normalizer mirror — that path is normalization-only and the dialog
displays the sanitized result, so nothing is reviewed-then-dropped there.
- The editor's env JSON parser (`parseTemplateEnvJsonInput`) fails closed
where it used to silently shrink the reviewed env on the manual form path:
a literal `"__proto__"` key (swallowed by the inherited setter on
assignment, so it could never even reach the server's 400) and empty/blank
keys (previously skipped) now throw with a message naming the entry.
- Node agent policy unchanged: it keeps filtering at every sink as the last
defense layer; the panel boundary now guarantees the reviewed env is what
reaches it.
Regression tests: `utils/server-template-payload.test.js` (mirror +
fail-closed suites), `tests/template-store-install-review.test.js`
(constructor 400s naming the entry; entry cap; envInvalid mirror; install.env
asymmetry), `tests/template-export-import-roundtrip.test.js` (stored/flat/egg
imports park or omit the container fields; deep-clone; hostile-payload
field allowlist). Full suite: 943 JS tests green.
## L-6 — email enumeration on POST /api/account/email/change (ordering)
`POST /api/account/email/change` ran its new-email uniqueness pre-check
(`findUserByEmail(newEmail)` → 400 `"Email already in use"`) BEFORE the
credential gates: the bcrypt password compare and the TOTP verification only
executed afterwards, inside `if (!recoveryVerified)`. Any authenticated
session could therefore distinguish registered from unregistered addresses
without knowing the account password — a 400 "Email already in use" for a
taken address vs a 403 "Incorrect password" for a free one. The
`accountCredentialRateLimiter` (10/10min per account) slowed probing down but
did not close it.
Remediation (ordering only; `POST /api/account/username` deliberately runs
its uniqueness pre-check after its gates for exactly this reason):
- The uniqueness pre-check moved to AFTER the entire credential-gate block
(password/TOTP, or a fresh recovery verification serving as the step-up
factor) and BEFORE the recovery-code claim + email write. The existence
answer is now only obtainable by a caller who passed a credential gate.
Placement before the `claimRecoveryCode` call is deliberate: a uniqueness
failure must not burn the caller's single-use recovery code. The
`existingUser.id !== user.id` guard is unchanged, so re-saving or re-casing
your own email still succeeds (the case-insensitive lookup is unchanged).
- Race backstop: `users` carries `UNIQUE KEY uniq_users_email (email)`, so a
change racing past the pre-check into the write makes the
`UPDATE users SET email = ?` throw ER_DUP_ENTRY. The handler's catch now
answers that with the same 400 `"Email already in use"` (one log line,
mirroring the username endpoint's ER_DUP_ENTRY handling) instead of the
generic 500 "Failed to update email". The UPDATE writes only `users.email`,
so ER_DUP_ENTRY can only originate from that key.
Response contract unchanged: the pre-check still returns exactly status 400
`{ error: "Email already in use" }`, so the frontend's step-2 error display
(403s walk back to step 1; other errors show at step 2) behaves as before —
the 400 simply can no longer be observed without valid credentials.
Validation order of the non-enumerating checks (password presence, newEmail
presence/length/format/charset), rate limiting and session eviction logic are
untouched, as is `/api/account/email/verify` (whose own TOTP pre-check is a
non-consuming re-verification of a code the caller already supplied, not an
existence oracle).
### Verification
`node --check` passes for `index.js`. Full suite: 1035/1038 green — the 3
failures (`destructive-route-guards` step-up constants, `runtime-process-command`,
`template-listing-sanitization` startupHidden) are pre-existing on the working
tree and reproduce identically without this change. No test asserts on the
email/change handler's source text or ordering. Re-reading the final handler
confirms the path: auth → user load → input validation → credential gates →
uniqueness pre-check → recovery-code claim → write; no code path answers
"Email already in use" without a credential gate having passed, and no path
burns the recovery code on a uniqueness failure.
## Session lifecycle — out-of-band CLI account mutations now revoke browser sessions (session epoch + revocation queue) (2026-09-27)
Browser sessions are keyed by email, so an account deleted out-of-band
(`initialize.sh` → `scripts/create-user.js --delete`) and re-created with the
same email used to inherit the pre-deletion sessions: the old cookie kept
authenticating against the new row.
Remediation spans the CLI, the schema and the panel:
- `users.session_epoch BIGINT UNSIGNED NOT NULL DEFAULT 0` (mysql-schema.sql +
idempotent `ensureUsersSessionEpochColumn()` migration in `db.js`): every
credential mutation re-seeds it with `crypto.randomInt(1, 2147483647)`; the
value is discriminator material and is never logged.
- `pending_session_revocations` (PRIMARY KEY `email` — the key is the
cross-process claim mechanism): `scripts/create-user.js` queues a request on
every mutation — `cli-delete` inside the `--delete` transaction,
`cli-password` on `--update-password` (epoch re-randomized in the same
UPDATE), `cli-create`/`cli-create-existing` on the create upsert
(`session_epoch = VALUES(session_epoch)`, so a re-run of an existing email
re-randomizes).
- The panel runs `sweepPendingSessionRevocations()` on an unref'd 5s interval
(boot call in `startServers` after `ensureSchema`, so requests queued while
the panel was stopped are consumed at startup): atomic claim via conditional
`DELETE … WHERE email = ? AND requested_at = ?` gated on `affectedRows === 1`,
eviction via `destroyBrowserSessionsForUser({ email })` +
`disconnectSocketsForUser(email, "out-of-band-account-change")`, retry with
`attempts + 1` (requeue skipped when a newer request already covers the
email), loud give-up at 5 attempts, throttled failure logging. The
claim-then-evict ordering is safe against a same-email re-create
mid-processing: the eviction destroys the inventory scanned at claim time,
so sessions minted for the new account are not touched.
- Session identity binding: every auth mint (login, step-up, remember-restore,
email change, panel-side create) stores `req.session.accountId` +
`req.session.accountEpoch`; a request middleware tears down and 401s/redirects
any session whose binding no longer matches the resolved row (recreated
account) and quietly tears down zombie sessions whose account row is gone —
enforced BEFORE the suspension branch so a stale session never learns the
recreated account's suspension state, and never backfilled. Legacy
pre-binding sessions fail open to the sweep; `findUserByEmail`/`findUserById`
select the new column with a legacy fallback that deliberately omits it.
- `DELETE /api/settings/accounts/:email` clears the pending row after the
delete commits (a racing CLI request is already covered by the endpoint's own
eviction); `POST /api/admin/user/create` re-seeds the epoch at INSERT and
evicts leftovers for the provisioned email, so a re-created account cannot be
reached by pre-deletion sessions even when every queue hop failed.
- `initialize.sh` password prompts (options 1/2/4) hardened: non-empty, ≥8
characters, ≤72 bcrypt bytes, `read -r`, and EOF exits instead of spinning.
### Verification
`node scripts/verify-user-lifecycle-session-revocation.js`: 14 PASS / 0 FAIL /
1 SKIP (D1 by design — the sweep is inlined, so the behavioral probe is out of
the harness's no-boot contract). `node --check` on `index.js`, `db.js`,
`scripts/create-user.js`, `public/js/settings.js`, the harness;
`bash -n initialize.sh`; 79/79 green on the pure-Node utils sample
(`atomic-file`, `csrf-allowed-hosts`, `ip-subnet-validation`,
`panel-hmac-secret`, `svg-sanitizer`).
## Audit round 2026-10-08 — braces: CVE-2024-4068 floor enforced via overrides; GHSA-vfj7-8cjw-p6xm accepted (no patched release)
Ticket triage: "braces DoS CVE-2024-4068 (high) via nodemon → chokidar;
devDependency only, no production exposure; `npm audit fix` can't resolve it
because chokidar pins `braces ~3.0.2` — add `"overrides": {"braces":
"^3.0.3"}` instead."
### CVE-2024-4068 (GHSA-v6v8-xj6k-w4tq) — remediated, floor now enforced
`braces < 3.0.3` (uncontrolled resource consumption while expanding
malicious patterns) is reachable in this repo only through
`nodemon@3.1.14 → chokidar@3.6.0` (devDependencies). chokidar declares
`braces: "~3.0.2"`, which 3.0.3 satisfies, so the lockfile already resolved
to the patched 3.0.3 and `npm audit` no longer reports CVE-2024-4068. That
resolution was incidental, though — nothing pinned it, so a stale-lock
restore, an offline cache, or a future transitive consumer could silently
regress below the patch. `"braces": "^3.0.3"` was added to the existing
`overrides` block in `package.json`, making the floor explicit: every
`npm install`/`npm ci` re-resolution is now forced to ≥ 3.0.3.
Two record corrections for future triage:
- `~3.0.2` does allow 3.0.3, so `npm audit fix` was never blocked by the
chokidar range itself; the persistent audit flagging came from the
different advisory below.
- Before applying a global override, the tree was checked for 1.x/2.x
braces consumers that `^3.0.3` could break: `braces` exists exactly once
in the dependency graph (under chokidar), so the override is provably
conflict-free for this tree.
### Residual — GHSA-vfj7-8cjw-p6xm (CVE-2026-93687): accepted risk
`npm audit` still reports 3 highs on the braces/chokidar/nodemon chain for a
DIFFERENT advisory: "braces vulnerable to stack-exhaustion denial of service
through deeply nested patterns" (CWE-674). Affected range is `≤ 3.0.3` —
every published braces release — with `patchedVersions: undefined`. No
version selection (override, upgrade, `npm audit fix`) can remediate an
advisory that matches all versions; npm's only mechanical suggestion,
`npm audit fix --force` → `nodemon@1.14.10`, is a breaking downgrade to a
2018-era 1.x watcher (published 2018-01-09 vs the current 2026-02-20
3.1.14) and is rejected as a non-remediation.
Accepted risk, documented:
- **No production exposure.** braces ships only under nodemon
(devDependency); production installs run `npm install --omit=dev`
(initialize.sh) and `npm start` runs `node index.js`, never nodemon.
- **No attacker-reachable vector in development either.** The vulnerable
code is the recursive AST walker in `braces()` pattern expansion. chokidar
feeds it developer-controlled watch paths/globs; nothing in this codebase
expands attacker-supplied patterns. Exploitation would require an attacker
to control the glob strings handed to a developer's local file watcher.
- **Watch posture.** If a patched braces release is ever published, the
`"^3.0.3"` override already admits it; a plain `npm update braces` (or any
fresh resolution) picks it up. Re-check `npm audit` on dependency-review
days before acting further.
### Verification
- `npm install` clean ("up to date, audited 367 packages"); `npm ls` exit 0
(tree/lock consistent with the new override).
- `npm ls braces`: single instance `braces@3.0.3 overridden` under
`nodemon@3.1.14 → chokidar@3.6.0`; lockfile `node_modules/braces` is
3.0.3, `"dev": true`, integrity-pinned to the official registry tarball.
- `npm audit --json`: GHSA-v6v8-xj6k-w4tq (CVE-2024-4068) absent;
remaining findings are exactly the three GHSA-vfj7-8cjw-p6xm chain
entries (braces `*`, chokidar `2.0.0 - 3.6.0`, nodemon
`0.0.0-development || >=1.14.11`), all with no patched version.
- Smoke: `require('braces')` expands patterns correctly;
`require('chokidar')` / `require('nodemon')` load.
- Registry check (2026-10-08): 3.0.3 is the LATEST braces release ever
published (no 3.0.4 exists), and the latest nodemon (3.1.14 — the pinned
version) still requires `chokidar ^3.5.2`, the braces-carrying line, so
no upgrade path can clear GHSA-vfj7-8cjw-p6xm today.
- Lock reconciliation: `npm install --package-lock-only` re-resolves the
lock byte-identically against package.json with the override in place
(npm does not embed overrides in the lockfile — package.json is the
enforcement point and is cross-checked on every install), so a teammate's
`npm ci` cannot fail or silently regress.
---
# Cross-Site Read Guard Fallback + CORS Hygiene (2026-10-17)
## Background
The panel's file-read GETs (index.js `/api/servers/:name/files/{list,read,
stream,download}` and nodes.js remote-mode relays
`/api/nodes/server/:name/{entries,file,download}`) share ONE cross-site read
guard (utils/cross-site-read-guard.js). Its original contract rejected ONLY
requests carrying `Sec-Fetch-Site: cross-site` and failed open on an ABSENT
header — correct for curl/API scripts (no metadata headers), but an old
browser (Chrome < 76, Firefox < 90, Safari < 16.4) sends no Fetch Metadata
either, so a hostile page could drive its credentialed file-read GETs straight
past the guard. Every browser however old sends `Origin` on cross-site
fetch/XHR and `Referer` on cross-site navigations/subresources — that evidence
was simply unused.
## What changed
### Read guard: Origin/Referer fallback (utils/cross-site-read-guard.js)
When `Sec-Fetch-Site` is absent (or indecisive — same-site/none/malformed), the
guard now falls back to the Origin/Referer evidence old browsers always
provide, using the SAME host primitives and allowlists as the panel-wide CSRF
middleware (`sameOriginProtection`, which guards state-changing requests):
- Evidence host must match the panel's own hosts (serving Host header,
trusted `X-Forwarded-Host` via index.js's trusted-proxy resolver, the
`PANEL_PUBLIC_URL` host) or an operator-endorsed host, else 403.
- Operator endorsement = `CSRF_ALLOWED_HOSTS` entries (parsed by
utils/csrf-allowed-hosts.js, wildcard-gated) or `NODES_CORS_ORIGINS`
origins (matched at host level). Reads are thereby never stricter than
writes: a host that may drive cross-site POSTs through the CSRF middleware
may drive cross-site reads too.
- `Origin`/`Referer` literally `null` (sandboxed iframe / opaque context) →
403 when the request carries cookies (ambient authority a hostile page can
drive); cookieless requests fall through to the auth gate (401) since they
carry no authority.
- A browser-attested `sec-fetch-site: same-origin` still wins over a
contradictory Origin header — same precedence as the CSRF middleware.
- The one residual fail-open — NO evidence at all (no metadata, no Origin, no
Referer) — was first documented as deliberate, then CLOSED the same day
after adversarial review: cookie-bearing evidence-less requests are now 403
(see "Cross-site read guard: evidence-less cookie-bearing reads rejected"
below). Cookieless non-browser clients are unchanged.
- Same-site evidence from a sibling subdomain is now held to the same host
standard as the CSRF middleware (SameSite=Lax cookies attach to same-site
GETs, so sibling subdomains must be allowlisted too).
- index.js injects the panel-wide trust inputs at startup
(`setCrossOriginTrustContext`: panel public host, parsed CSRF allowlist,
trusted forwarded-host resolver) — same injection pattern as
`nodesRouter.setPermissionCheckers`. Standalone (nodes.js test harness,
no injection) the guard's allowlist degrades to the serving Host header
plus the `NODES_CORS_ORIGINS` hosts (a module-level constant, still
honored): narrower than the injected set, never wider.
- Header-host primitives (`extractHostnameFromHeader`, `parseOriginHost`,
`normalizeHostLower`, `isLocalHost`, `hostAllowed`) moved verbatim from
index.js to utils/origin-host.js so the CSRF middleware and the read guard
share one implementation and cannot drift.
### nodes.js CORS responder
Contrary to a prior review note, this surface never reflected arbitrary
origins: `applyCors` echoes `Origin` only after one of two gates — exact
same-origin when `NODES_CORS_ORIGINS` is unset, or the listed origins when it
is set (never `*`) — and that structure predates every commit in this
repository. The two gates are either-or: a non-empty allowlist replaces the
same-origin echo entirely (harmless — same-origin requests never consult
CORS — but pinned explicitly in the contract tests). Hardened anyway:
- `Vary: Origin` on every response through the router — whether ACAO is echoed
depends on the request Origin, so caches must not replay one origin's CORS
headers to another.
- Same-origin computation now compares the FIRST `X-Forwarded-Proto` entry
(the client-facing scheme on multi-hop chains, e.g. `https,http`) instead of
the raw comma-joined string, which could never match a real origin.
- `NODES_CORS_ORIGINS` is documented in .env.example (it previously existed
only in code).
### Verification
- `node --test utils/cross-site-read-guard.test.js`: 18 tests pinning the full
policy matrix (baseline contract unchanged for headerless requests,
old-browser fallback, null-origin/cookie rule, allowlist endorsements,
same-site tightening, attestation precedence).
- `node --test tests/node-relay-cross-site-guard-parity.test.js`: real nodes.js
app probed over loopback — foreign Origin/Referer without metadata → the
guard's 403 body; same-origin and cookieless-null evidence → the 401 auth
gate; source-level parity assertions for both surfaces unchanged.
- `node --test tests/node-relay-cors.test.js
tests/node-relay-cors-allowlist.test.js`: CORS contract pinned for the
default posture (no grant for foreign origins, exact same-origin echo,
Vary: Origin, multi-hop XFP) and the allowlist posture (exact-origin echo
with credentials, preflight grants, suffix look-alikes rejected,
either-or gate semantics).
### Test harness: force-exit must not mask failures
Adversarial review of this change found that the three integration test
files' original `after(() => process.exit(flag ? 0 : 1))` pattern could not
fail reliably: `await t.test()` resolves even when the subtest failed (so a
flag set after the last subtest hid the failure behind exit 0), and with two
integration tests in one file a flag set by the first masked a failure in the
second; `process.exit()` additionally truncated buffered TAP output on pipes,
cutting off the final test's result. All three files now register every test
through a `pinnedTest()` wrapper that tallies rejections before rethrowing
(node:test still reports each failure normally), and the forced exit waits
250 ms so the reporter flushes. Verified adversarially: a deliberately broken
assertion now produces exit code 1 with the `not ok` result visible in the
output, in a first test, a last test, and a source-level parity needle alike.
The tally covers cleanup too: the loopback-server teardown runs INSIDE the
tallied body (try/finally), not in a `t.after()` hook — a hook fires after
the body, outside the wrapper's try/catch, so a failed close would print
`not ok` while the tally stays 0 and direct `node <file>` mode would exit 0
(verified adversarially: an injected cleanup failure now exits 1 with the
error visible in both modes; under `node --test` the parent runner counted
it before the fix as well).
---
# Cross-site read guard: evidence-less cookie-bearing reads rejected (2026-10-17)
Adversarial review of the residual documented above ("no evidence at all →
PASS, indistinguishable from a monitoring script's curl") found the reasoning
incomplete, and the residual is now closed.
## Why the residual was not actually free
- **Read/write parity was inverted.** `sameOriginProtection` (index.js)
rejects cookie-bearing requests with no Origin/Referer/Sec-Fetch-Site on
every state-changing route. The read guard let that same combination
through to the panel's most sensitive read surface (file contents) —
looser than writes, contradicting the guard's own "reads are never
stricter than writes" rule.
- **The "old browser" framing understated the exposure.** A hostile
SAME-SITE sibling subdomain (compromised or attacker-registered host under
the panel's registrable domain) strips its own Referer and drives
`fetch(url, { mode: "no-cors", referrerPolicy: "no-referrer" })`: the
request carries `Sec-Fetch-Site: same-site`, no `Origin` (no-cors GET), no
`Referer` (stripped) — and SameSite=Lax cookies DO attach to same-site
requests. Zero evidence, cookie attached, current browsers: the guard's
evidence-less branch passed it.
- **"Log noise and bandwidth, nothing else" is not the floor either.**
Cross-origin `PerformanceResourceTiming.duration` is exposed without
Timing-Allow-Origin, so the unreadable responses still leak a weak
existence/size oracle over attacker-guessed paths. And the readability
argument leaned on incidental properties (no CORS echo, nosniff, no
attacker-plantable inline content) rather than on designed boundaries —
any future ACAO echo, image-preview endpoint or user-influenced inline
content would have re-opened exfiltration through this fail-open.
## What changed
`rejectCrossSiteRead` branch 3 (no Sec-Fetch-Site, no Origin, no Referer) now
rejects with 403 when the request carries cookies and the browser has not
attested trust. Cookie-bearing evidence-less requests pass only with
`Sec-Fetch-Site: same-origin` or `Sec-Fetch-Site: none`:
- `none` is the browser-computed "no initiator" attestation (address bar,
bookmark, reload). Hostile JS cannot forge any `Sec-Fetch-*` header
(forbidden header names), so a cookie-bearing `none` request is a genuine
top-level navigation — the paste-a-URL case panels allow by design.
- `same-site` with no evidence host is rejected: that is the
sibling-subdomain shape above. A legitimate same-site app that needs
access belongs in `CSRF_ALLOWED_HOSTS` / `NODES_CORS_ORIGINS` and sends
Origin/Referer evidence anyway (branch 4 judges it).
- Absent or malformed metadata with cookies is rejected: that is the
old-browser hostile shape.
- Cookieless requests are unchanged: curl/API scripts/monitor agents with no
session cookie still pass to the auth gate; token-authenticated clients
are entirely unaffected.
- Scripted session clients (cookie-jar curl) migrate with ONE header:
`-H "Origin: <panel-host>"` — exactly the declaration the CSRF middleware
already requires of them for any state-changing request. Same-host Origin,
Referer, the `PANEL_PUBLIC_URL` host, `CSRF_ALLOWED_HOSTS` and
`NODES_CORS_ORIGINS` all keep working through branch 4. The localhost
variants keep working through branch 4 only when the panel's own host (the
serving Host header, a trusted `X-Forwarded-Host`, or the `PANEL_PUBLIC_URL`
host) is itself loopback — on a public deployment a loopback-origin page is
foreign evidence and falls through to the ordinary allowlist like any other
host (adpanel:csrf-localhost-scoping, see the 2026-10-31 round below).
Known behavior change: a genuinely old browser (no Fetch Metadata) pasting a
file URL into the address bar now gets 403 instead of the file. Modern
browsers attest such navigations with `Sec-Fetch-Site: none` and are
unaffected.
## Verification
- `node --test utils/cross-site-read-guard.test.js`: the former
"headerless with a session cookie passes" pin flipped to 403, plus new
pins — same-site attestation with cookies but no evidence host (403),
malformed site value with cookies (403), `none` and `same-origin`
attestation with cookies (pass: address-bar navigation / attested
same-origin fetch), and the scripted-client Origin escape hatch (same-host
passes, foreign blocked).
- `node --test tests/node-relay-cross-site-guard-parity.test.js`: real
nodes.js app over loopback — cookie + no evidence and cookie + `same-site`
→ the guard's 403 body ahead of auth; cookie + `none` and cookie +
same-host `Origin` → the 401 auth gate.
## Route-family extension: the guard now covers the per-server data-read family (2026-10-17)
Post-verification review of the neighboring read surfaces found the guard's
data-class boundary drawn narrower than its own principle ("session-facing
reads reject exactly what the file routes reject"). Extended, in two passes
(the second after the verifier's red-team sweep named the remaining
per-server reads):
- nodes.js (the remote-mode relay surface): `/api/nodes/server/:name/info`
(baseDir, disk snapshots, node metadata), `/eula` (eula.txt content),
`/backups` (backup names/sizes/timestamps) and `/logs` (log file content,
`console_read`-gated) now mount `rejectCrossSiteRead` as their first
middleware, joining `entries`/`file`/`download`. All four authenticate
browsers via `checkServerAccess` (session) and are consumed by the
dashboard's same-origin fetches, so legit flows are unchanged.
- index.js, pass 1: `/api/servers/:name/console-history` (console command
content, `console_read`-gated) joins the four `/files/*` routes.
- index.js, pass 2 (verifier's red-team sweep): the remaining per-server
reads in the same family — `/api/servers/:name/planner` (planner items),
`/api/scheduler/:serverName/tasks` (scheduled task listings),
`/api/server/:name/activity` (activity log entries) and
`/api/servers/:name/permissions` (effective permissions — a GET that
mints action tokens, so a hostile page must not be able to drive repeated
mints through the victim's browser). All four are gated by session +
server access (activity and scheduler tasks additionally by their
`activity_logs` / `scheduler_access` permission; planner and permissions
by access alone) and consumed only by the panel's own same-origin pages.
- Pass 3 (second verification's red-team sweep — two blockers):
- `/api/server-info/:name` (index.js) — the panel-side twin of the
relay's `/info`: per-server connection metadata (start command, ip,
port, template, runtime), session + access gated, consumed only by
same-origin pages.
- `GET /api/subdomains/:serverName` (routes/subdomains.js) — per-server
subdomain rows plus fleet-secret-derived TXT challenge pairs, session +
`subdomain_show` gated, no in-repo consumer. The guard is mounted
first, and a session gate now runs BEFORE resolveServer: resolve-first
let an unauthenticated caller distinguish existing servers (403 after
checkPerms) from nonexistent ones (404) — the same server-name
existence oracle fixed in performPanelEulaStatus.
- `GET /api/dashboard-assistant/bootstrap` (routes/dashboard-assistant.js)
— per-user rather than per-server, but the admin bootstrap embeds
action tokens on GET: the same repeated-mint rationale as
`/permissions` applies verbatim, so it mounts the guard ahead of its
rate limiter (guard-rejected requests do not consume limiter budget).
- The same oracle fixed in the write paths `performPanelEulaAccept` and
`performPanelConsoleCommand` (nodes.js): `checkServerAccess` now runs
before `remoteContext`, matching the read paths. Browser-facing writes
remain covered by the panel-wide CSRF middleware and the relays' action
tokens; this closes the cookieless existence-only leak.
Pre-existing finding fixed en passant (verifier observation):
`performPanelEulaStatus` resolved the server through the database BEFORE
authenticating, letting unauthenticated callers distinguish existing
servers (401) from nonexistent ones (404) — a server-name existence oracle.
`checkServerAccess` now runs first (same order as
`performPanelListBackups`), collapsing the distinction; the parity suite's
uniform 401 gate assertion regression-pins the ordering.
Deliberately NOT guarded, with reasons:
- `/api/nodes/:id/config.yml` authenticates node agents via the
`X-Node-Bootstrap` header / Bearer node token — cookieless by design, so
there is no browser session authority for the guard to protect; a browser
request without the token already fails auth.
- Global operational/status GETs (`/api/scheduler/status`,
`/api/server/:name/status`, `/api/server/:name/node-status`, `/api/me`,
…) — telemetry, not per-server data content; several are rate-limit-exempt
high-frequency polls. (`/api/dashboard/servers` was named here when this
section was written but is a data read — the access-filtered server
inventory — and is now guarded by the default-secure /api read posture
below, not exempt.)
- The panel-wide sensitive-GET surface (`/api/settings/*`, `/api/admin/*`,
`/api/account`, …) was a separate policy question when this section was
written — an operator decision, deliberately not bundled here. It was
subsequently closed by the default-secure /api read posture (see the
section of that name below); the telemetry-polling family is the one
remaining deliberate exemption.
- Two GET-mint surfaces OUTSIDE the per-server family — `GET /api/ai/keys`
(mints AI-key action tokens) and `GET /api/ssh-terminal/session` (mints
SSH terminal session tokens) — were named by the pass-3 verification's
red-team sweep and left for a deliberate follow-up. That follow-up
arrived with the default-secure /api read posture below, which guards
them by default (both are same-origin-consumed; the guard adds a fourth
layer on top of their auth gate, limiter and no-store).
Test updates: the parity test's route tables now pin all ten panel routes
(source-level; index.js cannot be mounted in-process), all seven relay
routes (source + functional), and the two router-file mounts
(routes/subdomains.js `GET /:serverName`, routes/dashboard-assistant.js
`GET /bootstrap`) via a whitespace-normalized needle table that also
asserts each router file consumes the ONE shared guard implementation and
defines no local copy. Functional probes per relay: cross-site → the
guard's 403 ahead of the gate; same-origin and headerless → the gate's 401
"not authenticated". The uniform 401 doubles as the regression pin for the
/eula ordering fix (a reordering back to resolve-first would break the
deterministic 401 in the harness).
---
# Default-secure /api read posture (2026-10-17)
The operator asked whether the still-exposed GETs need fixing. Verdict per
category, then the implementation:
- **The two GET-mint surfaces — yes.** `GET /api/ai/keys` (mints AI-key
action tokens) and `GET /api/ssh-terminal/session` (mints SSH terminal
session tokens) are the same shape that justified guarding `/permissions`
and `/bootstrap`; leaving them unguarded was inconsistency, not policy.
- **The settings/admin config GETs — yes, architecturally.** Three
verification passes in a row each found the next unmounted route — that
is the failure mode of per-route enumeration itself, so the durable fix
flips the default instead of extending the list again.
- **Global telemetry GETs — no.** Status/CPU/memory/queue payloads carry
nothing an existence/size oracle can use, and several are rate-limit
EXEMPT precisely because scripted cookie-jar polling is their contract
(`RATE_LIMIT_EXEMPT_PATHS`/`PATTERNS`). Guarding them would break monitor
agents for zero security gain.
## What changed
utils/cross-site-read-guard.js exports
`createApiReadGate({ exemptPaths, exemptPatterns })`: a GET/HEAD-only
wrapper around the SAME `rejectCrossSiteRead` policy — writes are untouched
(non-GET/HEAD passes to `sameOriginProtection`, which already rejects
cookie-bearing evidence-less writes). index.js mounts it app-wide, directly
after the CSRF middleware and ahead of every router:
app.use("/api", crossSiteReadGuard.createApiReadGate({
exemptPaths: ["/me", "/me/status", "/servers/statuses",
"/scheduler/status", "/server-info", "/status/metrics/day",
"/status/metrics/summary", "/status/snapshot"],
exemptPatterns: [/^\/server\/[^/]+\/status$/,
/^\/server\/[^/]+\/node-status$/],
}));
From this point every cookie-bearing /api GET/HEAD is guarded BY DEFAULT —
including `/api/settings/*`, `/api/admin/*`, `/api/account`, `/api/ai/*`
(closing the two mint surfaces above), `/api/templates`,
`/api/dashboard/servers`, `/api/my-servers` and every route added later, so
a new data endpoint cannot silently ship unguarded. The exemptions are
exactly the telemetry-polling family (matched mount-relative, exact-path or
anchored-pattern — near-misses and sub-paths stay guarded), pinned verbatim
by the parity suite so the list cannot silently grow (widening the
unguarded surface) or shrink (breaking scripted monitors). The
`/api/status/` metrics history routes (admin-gated) are enumerated EXACTLY
rather than by a namespace prefix, so a future route under that namespace
does NOT inherit the exemption — verified by a dedicated
"no prefix inheritance" pin. The per-route mounts stay in place: they are
the documented family, and double-guarding is idempotent.
Migration: a scripted client reading a NON-exempt /api GET with a session
cookie adds one header — `-H "Origin: <panel-host>"` — the same declaration
`sameOriginProtection` already requires of it for every state-changing
request. Cookieless and token-authenticated clients are unaffected, and
browsers are unaffected (same-origin fetches are attested same-origin;
address-bar/bookmark navigations attest `none`).
## Verification
- `node --test utils/cross-site-read-guard.test.js`: factory pins — the
method gate (POST/PUT/DELETE/PATCH/OPTIONS pass untouched; HEAD is gated
like GET), exemption pass-through for the telemetry family, exact-match
discipline (`/me/keys`, `/servers/statuses-extra`, `/server-info/abc`,
`/settings/database/pgadmin/status` all stay guarded), the NO-PREFIX-
INHERITANCE pin (a future `/api/status/whatever` stays guarded),
cookie-bearing evidence-less rejection, cookieless pass-through, attested
`none`/`same-origin` pass-through, and the no-exemption default.
- `node --test tests/node-relay-cross-site-guard-parity.test.js`: source
pins for the app-wide mount, the shared-factory requirement (no local
`createApiReadGate` copy in index.js), the SINGULARITY pin (exactly one
`createApiReadGate` reference in index.js — a second mount with extra
exemptions could not hide behind the presence pin), the VERBATIM exemption
list, and the absence of the former `/^\/status\//` prefix pattern.
- `npm test`: full suite green (1455 tests).
### Post-verification tightening (same day)
The verification's two note-level observations were both actionable and
both applied: (1) the `/^\/status\//` prefix exemption — whose namespace
would silently exempt future routes — was replaced by exact enumeration of
its three admin-gated metrics routes, with a regression pin forbidding the
prefix's return; (2) the stale cross-reference naming
`/api/dashboard/servers` as unguarded telemetry was corrected (it is a data
read and is guarded by the default posture). A singularity assertion was
added for the noted presence-pin limit: index.js must reference
`createApiReadGate` exactly once.
---
# nodes.js CORS: default posture tightened to zero reflection (2026-10-18)
## Finding triage
A recurring review note describes the node relay's CORS responder as
"reflects any Origin with Access-Control-Allow-Credentials: true —
pre-existing; posture broad". Triaged against history:
- The reflection claim was, and remains, false: `applyCors` has gated every
echo since the initial commit (a6c5c37) — first behind an exact same-origin
check OR an explicit `NODES_CORS_ORIGINS` allowlist, never a wildcard. The
2026-10-17 CORS-hygiene pass (above) had already added `Vary: Origin` and
fixed the multi-hop `X-Forwarded-Proto` comparison, with contract tests.
- The "posture broad" instinct was nonetheless correct in one specific way:
the DEFAULT same-origin echo was a dynamic reflection branch carrying
`credentials: true`. It was provably inert for cross-origin attackers (a
browser-computed `Origin` equals the request's own scheme+host exactly when
the request is same-origin — the echo could only ever fire where CORS is
meaningless), and it had zero functional consumers (same-origin requests
never consult CORS; the panel frontend calls the relay with relative
`/api/...` paths). But its origin computation was live code, and any future
"convenience" widening — trusting `X-Forwarded-Host`, registrable-suffix
matching — would have silently converted it into a credentialed
cross-origin grant. The mechanism, not the current match rule, was the
residual risk.
## What changed
- `applyCors` is now ALLOWLIST-ONLY and fail-closed: an Origin receives a
credentialed grant (exact ACAO echo, never a wildcard) only when listed in
`NODES_CORS_ORIGINS`. With the allowlist unset the relay emits NO
`Access-Control-*` response header at all. There is no same-origin
computation left to widen — zero reflection leaves nothing to widen.
- The now-dead `sameOrigin()` helper (Host + first `X-Forwarded-Proto` entry
comparison) was removed. The `X-Forwarded-Proto` client-facing-scheme fix
from 2026-10-17 is thereby superseded, not reverted: the comparison it
repaired no longer exists.
- `Vary: Origin` is still emitted on every response through the router —
required under the allowlist posture (ACAO presence depends on the request
Origin), harmless without one.
- Preflight `OPTIONS` still answers 204 with no grant for unlisted Origins
(the browser then blocks the actual request; fail-closed preserved).
- `.env.example`'s `NODES_CORS_ORIGINS` entry no longer describes a
same-origin fallback; the allowlist is documented as the only grant path.
- No operator action is required and no legitimate client is affected:
same-origin callers (the panel's own frontend) never consult CORS;
cross-origin callers already needed an explicit allowlist entry.
## Verification
- `node tests/node-relay-cors.test.js` (default posture, `NODES_CORS_ORIGINS`
unset): foreign Origin → no grant; a genuine same-origin request → no
grant; a maximally same-origin-shaped request (Origin matching the Host
header with a multi-hop `X-Forwarded-Proto` chain — the exact shape the old
echo granted) → still no grant, pinning that no same-origin computation
remains to be widened; `Vary: Origin` on every response; preflight for any
Origin → 204 without a grant. Exit-code honesty harness (pinnedTest tally,
flushed forced exit, in-body teardown) unchanged per the 2026-10-17
hardening.
- `node tests/node-relay-cors-allowlist.test.js` (allowlist set): listed
Origin echoed exactly with credentials and granted preflight; scheme
variants, suffix look-alikes and unlisted same-origin Origins get nothing.
## Audit round 2026-10-24 — scheduler hardening (4 findings)
Findings against the task scheduler (`POST`/`GET /api/scheduler/:server/tasks`
and the BullMQ worker in `index.js`). Not a permission escalation anywhere —
execution already re-verifies per-run permissions — but the scheduler path
bypassed several contracts the interactive relays enforce, and shipped false
success feedback plus a reader-side disclosure.
### 1. Scheduled console commands bypassed `sanitizeConsoleCommand` (Low–Medium)
The interactive console relay enforces ≤512 chars (`MAX_CONSOLE_COMMAND_LENGTH`),
single line, no control characters (nodes.js `sanitizeConsoleCommand`, enforced
in `performPanelConsoleCommand`). The scheduler path checked only that the
command was truthy at creation (`index.js`) and sent `payload.command` raw to
the node at execution. The node daemon writes the whole string to the
container's stdin (`stdinConn.sendCommand` appends `\n`), so a stored
multi-line blob — bounded only by the JSON body limit — fired a batch of
console lines on every tick of a recurring task (as fast as every 10s).
Fix (both layers, same shared function — no private copy):
- Create route runs `payload.command` through the exported
`nodesRouter.sanitizeConsoleCommand` and stores the sanitized command;
failures return the relay's 400 shape (`error` code + `detail`). Fails
closed (400) if the sanitizer is not exported.
- The worker re-runs the contract on the STORED command before any node call.
This covers recurring jobs created before the gate, which persist in Redis
until deleted. A payload that can never pass validation gets its recurring
schedule disabled (`disableRecurringScheduleForJob`) instead of failing on
every tick forever.
### 2. `maxSchedules` had no default — quota was optional (Low)
The recurring-task cap applied only when an admin had configured
`resources.maxSchedules` / `docker.maxSchedules`; unset meant a
`scheduler_create` user could stack unlimited recurring tasks, bounded only by
the global rate limiter. New `resolveSchedulerMaxSchedules()`: an explicitly
configured positive value always wins; undefined/0/negative degrade to
`SCHEDULER_DEFAULT_MAX_SCHEDULES` (50; overridable via the
`SCHEDULER_DEFAULT_MAX_SCHEDULES` env var) — never to "unlimited". A stored 0
is ambiguous (the admin update routes collapse "field left empty" and an
explicit 0 into 0), so it deliberately falls back to the default; operators
wanting a different ceiling set a positive per-server value or raise the env
default.
### 3. Create-time permission asymmetry produced silently-dead tasks (Low, bug)
Only the backup action was permission-gated at creation; `console_command`,
`server_start`/`server_stop` and `create_file`/`modify_file` were not, so a
user holding only `scheduler_create` was told "Task created successfully!" and
the task then failed on every run at the execution-time re-check
(`ensureScheduledJobStillAuthorized`). Fail-closed, not exploitable — but
false success feedback plus a permanently failing job polluting the queue.
Fix: the create route now gates every action through the SAME
`schedulerRequiredPermissionForAction()` mapping the worker re-verifies with,
so the create-time and run-time gates cannot drift apart (the backup-specific
gate is subsumed). Task names are additionally clamped to 100 characters
server-side (`SCHEDULER_MAX_TASK_NAME_LENGTH`, matching the form's
`maxlength` in `views/bot.ejs`; the API previously accepted anything the body
limit allowed).
### 4. `GET /tasks` returned full task payloads to any `scheduler_access` user (Low)
The task list included `job.data.payload` — other users' console command
text, file-write contents and agent prompts — and `job.returnvalue`, which
echoes the executed console command. API-only disclosure (the shipped UI in
`bot.js` renders id/name/actionType/status/time only), but it let a user who
lost `console_write` keep reading scheduled commands and exposed agent prompts
to mere viewers.
Fix: both fields are stripped from the response for all readers (one-time and
recurring lists). Inspecting a stored payload is a BullMQ/Redis operator
action, not a reader API; creators confirm what they scheduled at creation
time.
### Verification
- New `tests/scheduler-hardening.test.js` (21 tests): the shared sanitizer's
full contract against the real `nodes.js` export; the create route's
fail-closed wiring (source-level); the worker's `console_command` case
sliced from source and executed against a stub node module carrying the
REAL sanitizer — multi-line/control-char/over-long/empty stored commands
are rejected before any HTTP call leaves the panel and disable the
recurring schedule, valid commands POST exactly once with the sanitized
body; quota resolution precedence + env override; permission mapping covers
every creatable action; name clamp; GET route payload/returnValue absence
and field retention; `bot.js` never consumed the removed fields.
- Full suite: 1829 tests, 1827 pass; the 2 failures are pre-existing in the
untracked `tests/node-relay-backups-action-token.test.js` (assertions over
`public/js/bot.js` backup-token wiring, untouched by this change).
### Verification round follow-up (2026-10-24)
An independent line-by-line verification confirmed all four fixes; it also
caught two follow-up items, both now addressed:
- `disableRecurringScheduleForJob` did not actually bail for one-shot jobs
(its comment claimed it did): with no `repeatJobKey` it fell through to the
(serverName, actionType, name) signature match and could delete ANOTHER
job's healthy recurring schedule — e.g. a failing legacy one-shot sharing a
name with an innocent recurring task. A job with no repeat identity at all
(no `repeatJobKey` and no `opts.repeat`) now returns without scanning; the
signature fallback remains available for genuinely repeatable jobs whose
key could not be resolved. Availability bug only (collateral deletion),
pre-existing but newly reachable from the worker's invalid-command path.
- The quota block in the create route moved after request validation and the
per-action permission gate: malformed/unauthorized requests are rejected
before the quota's four Redis roundtrips, and the current/max schedule
counts are only disclosed to callers who could actually create that action
type.
`tests/scheduler-hardening.test.js` grew to 25 tests: the three new ones pin
the one-shot bail-out (no collateral deletion), the exact-key removal, and
the preserved signature fallback for keyless repeatables, plus the quota
ordering.
## Audit round 2026-10-25 — subuser planner parity, AI chat/agent queue caps, upload and rename sink hardening
The multi-fix pass that follows each closes a gap found while auditing the
subuser feature surface; every fix is pinned by a new source-level test.
- **`planner_access` subuser permission (interactive + scheduler parity).**
The planner was the last per-server feature gated by server-level ACL
access alone: any subuser with any grant could read and mutate the queue,
and a queued "next step to agent" hand-off re-verified with no
planner-specific permission at all. `index.js` now ships a dedicated key —
added to `ALLOWED_PERM_KEYS` and to the deny-by-default `permsTemplate` in
`getEffectivePermsForUserOnServer` (grants that predate the key resolve to
false) — and `resolvePlannerContext`, the shared gate of all six
`/api/servers/:name/planner*` routes, re-checks the effective permission
for non-admins and answers 403 (admins skip the lookup).
`schedulerRequiredPermissionForAction` maps `planner_next_to_agent` to
`planner_access` so the scheduler's execution-time re-check matches the
interactive gate; `agent_prompt` keeps requiring `scheduler_access`.
Pinned by `tests/planner-access-gate.test.js`.
- **Planner toggle stale-overwrite fix (client-side).** The planner card's
done-toggle PUT its full title+prompt from the client's stale cache, so
toggling status could silently revert a teammate's concurrent content edit.
`togglePlannerItem` in `public/js/bot.js` now sends only `{ isDone }`, and
the pre-existing partial-update contract in `PUT
/api/servers/:name/planner/:id` (hasOwnProperty field detection) preserves
the canonical stored title/prompt when they are absent.
- **AI chat message caps + role restriction + truncation marker.** The
`POST /api/ai/chats/:id/messages` route stored `content`,
`thinking_content`, and `model` unbounded and accepted a client-supplied
`system` role. `index.js` now restricts the route to `user`/`assistant`
roles (no client flow sends anything else — assistant replies persist via
the agent-executor's own insert path), caps message content at
`AI_CHAT_MESSAGE_MAX_CHARS` (default 20000, env-overridable), clamps
`thinking_content` to the same cap and `model` to the column's 255 chars,
and `truncateChatMessageContent` cuts over-length input with a visible
`[Message truncated — original length N characters]` marker (dropping a
trailing lone high surrogate so the cut never splits a pair), so a stored
message never silently differs from what the client still holds in memory.
- **Per-user agent queue cap.** The shared agent-job queue had only a global
cap, so one account could fill it and starve every other user.
`index.js` adds `AI_AGENT_MAX_PENDING_JOBS_PER_USER` (default 20,
env-overridable): enqueue is rejected once a user's own pending count
reaches it, alongside the pre-existing global
`AI_AGENT_MAX_PENDING_JOBS` ceiling.
- **Upload extension default blocklist + dotfile resolution.** With no
operator policy configured, `index.js` uploads allowed every extension.
`DEFAULT_UPLOAD_BLOCKED_EXTENSIONS` (php/jsp/asp/cgi families plus
`.htaccess`/`.htpasswd`) now applies whenever `UPLOAD_ALLOWED_EXTENSIONS`
is unset, while explicit operator config keeps precedence
(`UPLOAD_BLOCKED_EXTENSIONS` denies first, a non-empty allowlist wins).
Separately, `getUploadExtension` resolves a leading-dot basename to its
own extension — `path.posix.extname('.htaccess')` returned '' and let pure
dotfiles bypass every guard — so the default blocklist's dotfile entries
and operator dotfile blocks are reachable (`.env` deliberately stays
allowed).
- **Rename destination probe blocking.** Older fleet daemons rename with
plain overwrite semantics, and the panel-side rename route never checked
the destination, so a rename could silently clobber an existing file. The
route in `index.js` now probes the destination's parent with the same
depth-1 listing the file browser uses: a SUCCESSFUL probe that sees the
destination blocks the rename with the daemon's 409 shape, for ALL
daemons; a FAILED probe (thrown request, non-200, malformed body) never
blocks, since current daemons enforce RENAME_NOREPLACE authoritatively.
The probe compares against the sanitized `newName` (trailing-space names
sanitize to a collision the raw compare would miss).
- **HTML sink escapes + planner dock gating.** `public/js/bot.js`: the eight
branding/avatar interpolations in innerHTML templates now go through
`escapeHtml` — the two planner "Send to <brand> Agent" tooltips, the three
`src="${escapeHtml(BRAND_LOGO)}"` AI avatars, the user avatar
`src="${escapeHtml(userAvatarSrc)}"`, and the agent approval/question
titles — closing stored-XSS sinks rendered to every bot-page user. The
planner dock buttons are also permission-gated client-side like every
sibling feature: `applyPermissionsToUI` now runs
`toggleDisabled('#dockPlanner, #dockPlannerBottom', !hasPerm('planner_access'))`,
and `planner_access: false` was added to both PERMS default/reset objects
(server perms merge in per user; the server enforces regardless).
### Verification
- New `tests/planner-access-gate.test.js` (4 tests, 16 assertions): the key
in `ALLOWED_PERM_KEYS` (exactly once), the `permsTemplate` default, the
ordered `resolvePlannerContext` gate (non-admin branch → effective-perms
lookup → `perms.planner_access` check → 403 → `return null`), and the
scheduler mapping for `planner_next_to_agent`/`agent_prompt`.
- New `tests/brand-html-escape-sites.test.js` (3 tests, 8 assertions): the
eight escaped sites with exact occurrence counts, plus zero unescaped
`src="${BRAND_LOGO}` / `src="${userAvatarSrc}` / unescaped tooltip sinks
anywhere in `public/js/bot.js`. The route→gate wiring for the six planner
routes was already pinned by `tests/preflight-guard-sweep.test.js`
(unchanged, 140 tests pass).
## Audit round 2026-10-31 — CSRF loopback-alias scoping, planner agent-job retract, request-integrity hardening
Follow-up round from the code review: one CSRF trust-widening closed plus the
planner/creation-surface integrity fixes from the same session. The
server-side fixes are pinned by dedicated test files; the two client-side
hardenings below are behavioral fixes in the views/scripts.
- **CSRF loopback-alias scoping (`adpanel:csrf-localhost-scoping`).** Both
cross-origin trust decisions — the shared read guard (`buildAllowedHosts` in
`utils/cross-site-read-guard.js`) and the panel-wide CSRF write check
(`sameOriginProtection` in `index.js`) — granted the
localhost/127.0.0.1/::1 allowlist aliases to ANY request whose Origin/Referer
host was loopback, so on a public deployment a hostile page served by any
other local process (`Origin: http://localhost:9999`) passed the read guard
AND the CSRF write check while riding the victim's SameSite=Lax session
cookie (host matching ignores ports; realistic on desktop deployments where
the admin browses other local web apps). The fix gates the alias grant on the
panel's OWN host being loopback too — the serving Host header, a trusted
`X-Forwarded-Host`, or the `PANEL_PUBLIC_URL` host — so on a non-loopback
deployment loopback-origin evidence falls through to the ordinary allowlist
like any other foreign host. Pinned by `tests/csrf-localhost-scoping.test.js`:
functional runs of the real guard middleware under a controlled trust context
(including the trusted forwarded-host arm — a loopback `X-Forwarded-Host`
opens the gate, a non-loopback one keeps it closed) plus source-level pins
that BOTH copies keep the same gate and evidence-side condition.
- **Planner agent-job retract (`adpanel:planner-job-retract`).** A queued
`scheduler_planner_next`/`planner_send` job executes its enqueue-time prompt
snapshot, so deleting a planner item or rewriting its text left a queued run
that would execute text that no longer exists. `cancelQueuedPlannerAgentJobs`
(`index.js`) now cancels QUEUED jobs for the item in one transaction
(`SELECT ... FOR UPDATE` pins the rows against the concurrent claim gate),
leaves a terminal assistant note so the chat does not dangle as an unanswered
prompt, and runs best-effort from the DELETE route and from the PUT route's
content-edit success path (only when the content actually changed — an
isDone-only toggle or a no-op save never retracts). The completion side
effect is guarded too: `markPlannerItemDoneAfterAgentJob` flips the item done
only when the executed prompt snapshot still byte-matches the item's CURRENT
text, so a running job cannot consume a mid-queue edit. The `ai_agent_jobs`
status ENUM was widened with `'cancelled'` in the CREATE TABLE,
`mysql-schema.sql` and an idempotent boot-time `MODIFY COLUMN` migration —
under `STRICT_TRANS_TABLES` the retract UPDATE would otherwise raise error
1265 and both best-effort call sites would silently keep the stale run
queued.
- **Planner no-op request guards (`adpanel:planner-noop-request`).** `PUT
/api/servers/:name/planner/:id` with a body containing NO actionable field
(no `title`/`prompt`/`isDone`) is now a 400: it previously fell through to
the UPDATE statements anyway, re-stamping `updated_by_email` and bumping
`updated_at` (`ON UPDATE CURRENT_TIMESTAMP`), which force-409ed a
co-planner's in-flight CAS edit keyed on the old timestamp and moved
last-editor attribution to whoever sent the empty touch. No-CAS
false-success guards were added for the zero-changed-rows case: a flip (no
CAS anchor) reporting 0 affected rows now means the row was deleted
concurrently → 404 (previously reported `ok:true`), or another writer landed
the identical flip → 409 `planner_item_modified`; a content save reporting 0
affected rows answers 404 for a concurrently-deleted row and falls through
as success only for a live row whose stored values already equal the write.
Fail-closed either way, never a false success.
- **Planner prompt-clamp truthfulness (`adpanel:planner-clamp-prompt-truth`).**
When a scheduler agent job's author is unresolvable at fire time (item
deleted, source_ref unparsable, author account deleted or suspended) but a
persisted file envelope is present, `resolveSchedulerPlannerPermsOverride`
(`index.js`) now composes the projection through the same
`computeSchedulerPlannerClampedPerms` decision core the executor uses with
`authorResolved: false` (every non-file flag forced false) instead of
returning the bare file-envelope projection. Previously the unresolved-author
branches could let the system prompt advertise a non-file capability that the
tool gate would then deny at call time.
- **Reserved server name `all` (`adpanel:reserved-server-name`).**
`serverNameGuardOutcome` (`services/server-create.js` — the one name-guard
choke point shared by the panel route, the node proxy and the assistant
tool) now rejects the name `all` (lowercased and trimmed comparison). A
`user_access` row equal to `all` grants EVERY server in
`userHasAccessToServer`, so a server literally named "all" would turn any
per-server grant of it into a panel-wide grant; `sanitizeServerToken`
accepts the name and there is no rename route, so reserving it at creation
is the only fix. The rejection renders per-variant 400 bodies mirroring the
sibling name-guard cases (the tool's prose envelope, the proxy's and the
panel's `invalid_name` tokens with a detail).
- **Planner dock gate honored by the capture handler
(`adpanel:planner-dock-gate`).** Complementing the 2026-10-25 client-side
permission gating above: the dock-button capture handler in `views/bot.ejs`
(which takes over real clicks and routes them into the inline-page system)
now honors the same disabled gate bot.js's bubble handler enforces — a
`disabled`/`aria-disabled` dock button gets `preventDefault` +
`stopImmediatePropagation` before any routing, because `showInlinePage` has
no permission check of its own.
- **Security-dialog title flattening (`adpanel:planner-confirm-title`).** The
planner item delete `confirm()` and the file-manager delete `confirm()` in
`public/js/bot.js` now collapse whitespace/newlines and cap the interpolated
title/name at 120 characters. Native dialogs render plain text (no HTML
sink), but the interpolated value is attacker-controllable text reaching a
security dialog, so the hardening keeps an authored teammate title or a
crafted file/folder name from restyling the dialog with control whitespace
or unbounded length.
### Verification
- `tests/csrf-localhost-scoping.test.js` (11 tests): the functional guard runs
— loopback evidence rejected on a public panel (with and without Fetch
Metadata; the cookieless shape pinned post-fix), allowed when the panel
itself is loopback, the trusted forwarded-host arm exercised behaviorally
both ways, same-host regression — plus source-level pins that BOTH trust
decisions gate the alias grant on the panel's own host with the same
evidence-side condition.
- `tests/planner-job-retract.test.js` (11 source-level pins): the retract
transaction's queued-only scoping, the claim-gate safety, the `'cancelled'`
ENUM in runtime DDL + `mysql-schema.sql` + the boot migration, the
DELETE/PUT retract placement and content-changed gating, the done-flip
snapshot guard, the enqueue/done-flip server-name composition, the
unresolved-author decision-core compose, and the empty-body 400 ordering.
- `tests/reserved-server-name.test.js` (the `all` reservation through the
shared guard and its per-variant bodies),
`tests/planner-agent-envelope-closure.test.js` (the clamp-truth compose
pins), `tests/planner-reorder-edit-integrity.test.js` (the no-op-save
regression pins).
# Cross-cutting review follow-ups — planner agent-job integrity, editor save concurrency, always-on read brakes, error-mask closure (2026-11-01)
Follow-up batch from the cross-cutting review: the manual planner send path
brought up to the scheduler fire's authorization posture, the text editor's
last-write-wins save replaced with an opt-in optimistic-concurrency guard,
two always-on read brakes, and one error-echo channel closed.
- **Planner send-agent file-perm clamp (`adpanel:planner-agent-perms`,
`adpanel:planner-agent-author-pin`).** The manual send route
(`POST /api/servers/:name/planner/:id/send-agent`) now captures the
enqueue-time file-permission envelope through `buildPlannerItemFilePermEnvelope`
— the ONE capture helper the scheduler fire already used — resolved against
the LOCKED planner row: the per-flag AND of the sender's and the item
author's (`created_by_email`) file perms. The author's email is pinned on
the persisted envelope JSON, so a mid-queue content rewrite (the PUT route
re-stamps `created_by_email`) cannot re-point the fire-time author clamp at
a possibly more-privileged editor; the strict all-boolean FILE flags and
the pinned author ride the same column without leaking into each other
(`normalizeFilePermEnvelope` drops unknown keys, so the merge-back happens
only in the persisted snapshot inside `insertAiAgentChatJob`).
- **`ai_agent_jobs.perm_file_envelope` schema lockstep.** The envelope column
now exists in all three homes: the boot-time CREATE TABLE (index.js),
`mysql-schema.sql`, and an idempotent boot-time `ALTER TABLE` for existing
installs — under `STRICT_TRANS_TABLES` a missing column would make every
scheduler planner job (and now every manual send) fail to enqueue.
- **Direct-console fast path gated for background jobs
(`adpanel:direct-console-fast-path`).** The chat fast path's trust
assumption is that the user TYPED the latest message: it regex-scrapes a
console command out of the raw text and executes `send_console_command`
directly, before the model loop and the `<adpanel_tool_plan>` provenance
guard. For background agent jobs (`planner_send`, `scheduler_planner_next`,
`scheduler_prompt` — the `/api/ai/background/*` request path produced only
by `buildBackgroundAgentRequest`, served by no express route) the latest
user message is second-hand — planner text authored by another user or a
stored schedule — so the fast path is skipped there and destructive
execution must go through the model's tool loop, where the provenance
guard and the fire-time perms clamp (`applyAiAgentPermClamp`) apply.
- **PLANNER_TASK data-wall framing (`adpanel:planner-prompt-data-wall`).**
`buildPlannerAgentPrompt` (the scheduler's prompt composer) previously
framed the planner text as the user's direct prompt, handing planner-authored
text open-ended operator authority. The text is now delimited
`PLANNER_TASK_BEGIN`/`PLANNER_TASK_END` task data: the agent completes the
task it describes, but instructions inside the markers cannot rewrite the
rules of execution (change the target server, claim extra authority, escape
the clamps). This is the prompt-side half of the defense — the fire-time
capability clamp remains the bound. `planner_send` prompts are deliberately
NOT composed here: the sender authorizes the exact item text via the
mandatory `expectedPrompt` echo.
- **Send-agent job insert moved inside the transaction
(`adpanel:planner-send-insert-atomic`).** `insertAiAgentChatJob` accepts an
optional external transaction connection; the pending-cap COUNT checks and
the chat/message/job inserts all join the send route's `FOR UPDATE`
transaction instead of committing the verification first and inserting on
the pool afterwards — the earlier shape left a window in which the DELETE
route's `cancelQueuedPlannerAgentJobs` and a concurrent send's dedupe check
saw no job for an already-authorized send. The queue pump
(`enqueueAiAgentJob`) runs only after the route's commit, so a rollback can
never leave a claimed or running ghost job behind.
- **Completed-item send refusal (`adpanel:planner-send-completed`).** The
scheduler consumes only `is_done = 0` rows, but the manual send route
accepted a completed item, executing (and re-queueing behind) text the team
had already marked done. It is now a 409 whose human sentence rides `error`
directly — the board alerts `err.error || err.message`, so a machine code
would be displayed verbatim while the sentence sat dead — and no machine
code is emitted at all: codes stay reserved for 409s a client actually
branches on (`planner_prompt_changed`).
- **Planner prompt/title control-char + bidi strip
(`adpanel:planner-control-strip`).** Planner text is stored verbatim,
echoed byte-for-byte by the send-agent `expectedPrompt` gate, and handed to
the agent as task data, so invisible characters are instruction carriers.
One shared class (`PLANNER_CONTROL_CHAR_RE`) strips them from BOTH fields
at their only two write paths (create + PUT): NUL, the C0 controls and DEL
except `\n`, the C1 controls, bidi overrides and isolates
(U+202A–U+202E, U+2060–U+2069), zero-width characters (U+200B–U+200F,
U+FEFF), and the Unicode line/paragraph separators (U+2028/U+2029). `\t` is
rewritten to one space in prompts rather than deleted (a tab separating two
words must not fuse into a different instruction); `\n` is preserved. The
strip is idempotent, so stored values keep satisfying the byte-compare
echo gates.
- **Editor save optimistic concurrency (`adpanel:editor-save-occ`).** The
text editor used to be last-write-wins: a buffer opened before another user
(or the server process) rewrote the file silently clobbered those changes
on save. Opt-in fix: a save that carries `expectedSha256` — the sha256 of
the content the editor loaded (absent = legacy write, so the AI write path
and every other writer are untouched) — gets the file re-read before the
write dial through ONE shared guard, `verifyNodeFileUnchanged`
(services/node-fs-relay.js), run by BOTH write entry points (the
`PUT /api/servers/:name/files/write` route and the socket `writeFile` twin).
Fail-open/fail-closed split (deliberate): a verify DIAL failure (offline,
over-cap) fails open — a verify outage must never brick editing — while a
DEFINITIVE staleness answer fails closed with `409 file_changed_on_disk`:
hash mismatch, the file deleted since it was opened, or a non-UTF-8 file on
disk (the editor only opens text). A malformed opt-in hash is a 400, never
a silently downgraded guard. The client re-bases its dirty baseline and
base hash to the saved content ONLY while the editor still shows the saved
file (`path === currentEditorPath` in `performSave`'s success path, mirroring
the 409 branch): the open entry points do not block on `editorSaving`, so
an ungated re-base would stamp file B's baseline with file A's saved
content — B's next save would 409 against hash(A) and `isEditorDirty()`
would compare against the wrong baseline. Documented residual: the guard is
a read-then-write check, not an atomic CAS — the verify and write dials are
two separate daemon calls, so a concurrent write landing between them is
still clobbered; the daemon exposes no conditional-write hook, so the 409
narrows the race to that gap without eliminating it.
- **Always-on read brakes (`adpanel:fs-read-rate-limit-account`,
`adpanel:planner-read-brake`).** Two new always-on abuse brakes,
constructed exactly like their mutate twins (dedicated Redis store
instance + DISTINCT key prefix, per-account email key, fail-open on store
errors, `skip` handing unauthenticated requests to the global limiter):
`serverFsReadRateLimiter` (480/10min, `rlfsr:`) on the four file GET routes
(list/read/stream/download — each holds a node connection for its full dial
timeout, and the upload batch's per-file refresh bounds legitimate bursts),
and `plannerReadRateLimiter` (240/10min, `rlpr:`) on the planner board GET
(re-reads the server's full items table per dial and reloads after every
mutation, so its ceiling tracks the mutate budget 4x over).
- **Path-error masker closure (`adpanel:path-error-mask`).** The shared
`maskPathErrorMessage` (services/node-fs-relay.js — ONE implementation bound
by index.js; nodes.js binds the distinct `maskPathErrorMessageRelay`
variant, a deliberate spec-D13 divergence) lost its raw `err.message`
fallback: only the exact safeJoinUnix throw set may surface as a specific
400 message, and EVERY other error caught by a panel FS catch — which can
span DB-backed pre-flight work or the relay dial — renders that catch's
generic per-route default ("invalid path", "archive failed", "Create
failed"). Internal text (a DB driver message, an internal throw, a daemon
transport failure) is never echoed to a client; every call site already
passed its own default, so no call site changed.
**Transitional deploy note.** `scheduler_planner_next` rows enqueued BEFORE
this deploy carry the old (pre-data-wall) prompt snapshot. When such a job
completes after the deploy, `markPlannerItemDoneAfterAgentJob` recomposes the
prompt with the new framing and the byte-compare against the stored
enqueue-time snapshot mismatches once: the done-flip is skipped, the item
stays active, and the scheduler's next fire re-executes it once under the new
framing (whose done-flip then matches). At-least-once semantics,
self-limiting to the in-flight rows queued before the deploy.
### Verification
- `tests/planner-send-agent-hardening.test.js` (12 pins): the send-agent
route's limiter/catch/in-flight-guard/version-echo posture plus the
`planner-send-insert-atomic` regression pins and the control-strip pins.
- `tests/node-fs-relay.test.js` (39 pins): the two masker policies —
including the closure (an internal message renders the masked default, an
empty message the fallback) — and the `verifyNodeFileUnchanged` arms
(byte-exact verify dial, 409 `file_changed_on_disk` shape on mismatch,
case-insensitive hex compare, 64-hex shape validation, not-found/binary
fail-closed, dial-failure fail-open).
- `tests/node-fs-relay-routes.test.js` (51 pins): route-level pins that the
write/read relays keep masking every non-traversal error
(`adpanel:path-error-mask`, no raw text on the wire).
- `tests/fs-op-ack.test.js` (25 pins): both write entry points run the shared
guard opt-in BEFORE the write dial, and the client-side success-path
re-base (baseline + base hash + editor originals) is pinned INSIDE the
`path === currentEditorPath` guard with the success toast/report kept
outside it.
- `tests/planner-agent-envelope-closure.test.js` (27 pins): the envelope
classify/clamp decision core and the direct-console fast-path background
gating; `tests/planner-job-retract.test.js` (11 pins) covers the data-wall
compose and the done-flip snapshot guard.
- `tests/destructive-route-guards.test.js`: the two read brakes stay defined,
mount on the planner GET and the four file GET routes, keep the DISTINCT
`rlpr:`/`rlfsr:` Redis prefixes and the fail-open store posture.
- `tests/scheduler-hardening.test.js`, `tests/scheduler-file-actions.test.js`:
the prompt/title sanitizer pins (control-char classes, `\t` rewrite,
idempotence).
---
## Review follow-ups 2026-11-01 — node write-relay scoped parser, save re-base race, relay deps arity pin
Three small review-found fixes; two close real/racy behavior, one closes a
test regression hole.
- **Scoped 10mb parser on the node write relay (`adpanel:node-file-write-scoped-parser`,
nodes.js).** The `POST /api/nodes/server/:name/file` route comment claimed a
scoped 10mb JSON parser, but the only parser on the surface was the global
`express.json({ limit: "2mb" })` — so in standalone mode (`node nodes.js`,
its supported `require.main === module` entry point) remote-mode editor
saves of ~2-10 MB files were rejected by body-parser with a bare 413 before
the handler ran, and the client's 413 branch reported a limit the relay did
not itself enforce. The route now carries the parser its comment claims: a
dispatch ahead of the global 2mb parser (an already-parsed body skips every
later body-parser via the `req._body` sentinel), with the same
`FILE_WRITE_JSON_LIMIT` env override and "10mb" default as index.js's panel
write route — the daemon caps the RAW `/v1/fs/write` body at 10 MiB
inclusive, so the parser never accepts a body the daemon would bounce
(`NODE_FS_WRITE_BODY_LIMIT_BYTES` derivation in services/node-fs-relay.js).
Parser-before-auth matches index.js's write-route order (its
`jsonParserFileWrite` also runs pre-auth at the large-body dispatch); in
integrated mode index.js's own pre-auth dispatch parses this path first and
the sub-app parser skips, so only the standalone surface changes. body-parser's
bare 413 maps to the shared `fileWriteTooLargePayload()` JSON (bound from
services/node-fs-relay.js — one home for the wire string), the exact shape
the client's 413 branch reads; the client's fallback wording already
matches `FILE_WRITE_LIMIT_CLIENT_MESSAGE` byte-for-byte and was left
untouched. Sibling write-adjacent relays (/delete, /delete-batch, /rename,
/extract, /archive, /create) send small path/name payloads and claim no
scoped parser — no other copy needed the same fix.
- **Editor save success re-base made race-free (`public/js/bot.js`
performSave).** The `path === currentEditorPath` gate was checked before
`await computeEditorBaseSha256(contentToSave)`, but the digest's await is
exactly where a mid-flight `openEditorModal(B)` can complete — A's digest
resolution (and the pre-await baseline assignment) would then stamp B's
baseline/hash. Fail-closed today, now race-free: the digest is computed
first into a local, the gate is re-checked after the await, and the four
re-base assignments are skipped silently when the editor moved on (the save
landed; the success toast stays unconditional).
- **`NODES_FS_RELAY_DEPS` arity regression pin (`tests/node-fs-relay-routes.test.js`).**
`relayFsJson` dials positionally with SIX args through
`deps.httpRequestJson || httpRequestJson`, while nodes.js's local
`httpRequestJson` GET-probe shim is a FOUR-arg wrapper — a future regression
adding `httpRequestJson: httpRequestJson` to the deps object would pass
every test while landing every relay payload in the shim's timeout slot.
The test now bounds its window to the deps object literal itself and
asserts the binding is absent; the fallback to the hardened
services/node-http.js core is load-bearing.
### Verification
- `node --check` clean on nodes.js and public/js/bot.js; simulated parser
chain: 3 MB save parses 200, 11 MB save answers the shared 413 JSON,
sibling relays keep the 2mb budget.
- `tests/fs-op-ack.test.js`: the success-path re-base pin now asserts the
digest sits inside the outer gate, the gate is re-checked AFTER the await,
and the assignments sit inside the post-await re-gate with the toast
outside it.
- `tests/node-fs-relay-routes.test.js`: new negative pin on the deps window
(no `httpRequestJson:` binding).
- Full `npm test`: 2269 pass / 0 fail. `go test .`: ok (no Go changes).
# Login/auth hardening — remediation campaign (2026-11-08)
Nine-phase remediation of the login/auth surface findings (anonymous session
flood, per-IP-only brute force, TOTP lockout, account enumeration, reflected
error text, Socket.IO binding gap, extension-keyed static fast path, 365-day
rolling session with always-on remember-me, plus the informational items).
Every phase was implemented by a dedicated agent from a fully-specified plan,
then reviewed line-by-line by independent reviewers; two cross-cutting
"wiring" analyses then re-examined the whole campaign as one system. Full
checklist verification at the end of this section.
## Phase 1 — anonymous sessions capped at 30 minutes; /login request limiter
Every cookieless `GET /login` minted a session whose store entry lived 365
days (login CSRF token + bot-proof seed), an unbounded store-growth primitive
with no throttle in front of it.
- New `utils/preauth-session.js`: an `app.use` middleware sets
`sess.cookie.maxAge` to 30 minutes (env `PREAUTH_SESSION_MAX_AGE_MS`,
clamped 5 min–24 h) while a session is anonymous. Setting `maxAge` also
resets `originalMaxAge`, so rolling refreshes keep the short lifetime and
both stores honor it (connect-redis via `cookie.expires`, session-file-store
via `originalMaxAge`); login, captcha completion and remember-restore all
`regenerate()` first, which restores the configured authenticated lifetime.
Wired between the Upgrade-only Secure sync middleware and the revoked-sid
gate.
- New `utils/login-throttle.js` `createLoginRequestLimiter`: 60/min per
source (env `LOGIN_REQUEST_RATE_LIMIT_PER_MIN`, clamped 10–10000) on GET
and POST /login, IPv6 /56-bucketed keys, shared Redis store factory (one
instance, distinct `login-req:` prefix), `passOnStoreError: true` (abuse
brake, not an auth control), content-negotiated 429 (JSON vs text). Mounted
after the attack detector so that detector still sees all traffic; blocked
requests write no session and consume no CSRF token.
## Phase 2 — online password guessing bounded per source AND per account
The old throttle was per-IP in process memory only, and success reset the
budget — anyone holding one valid account could wipe their source's budget
between guesses (insider reset bypass), while distributed guessing across IPs
was unlimited.
- `createLoginThrottle` (same module): fixed-window counters in the shared
rate-limit store — `login-fail-ip:` (10/10 min per /56 source bucket) and
`login-fail-acct:` (20/15 min per sha256(trimmed,lowercased email), unknown
emails included so no enumeration oracle). Only credential failures count
(CSRF/botProof/honeypot/empty-field/gate/429 refusals never do), success
NEVER resets either counter (they decay with their window), store errors
fail open (Redis down means the session store is down, so no login
completes anyway), and the module deliberately exposes no source/account
reset API (pinned).
- The captcha UX gate was re-keyed from the raw IP to the /56 bucket
(`loginCaptchaGates`, 10-min gate TTL, FIFO cap kept) so one host cannot
mint fresh buckets; `verifyExternalCaptcha` keeps the RAW IP for the
provider's `remoteip` — the bucketed key never reaches the provider.
- Dead code deleted (each grep-verified caller-free before deletion):
`recordLoginAttempt`, `isLoginBlocked`, `resetLoginAttempts`,
`getLoginAttemptCount`, the suspicious-login scorer family, and the
`LOGIN_WINDOW_MS`/`LOGIN_MAX_ATTEMPTS`/`LOGIN_BLOCK_MS` constants.
## Phase 3 — TOTP attempts bounded per account+source
The TOTP throttle was per-email in process memory keyed only by the email:
five wrong codes from any source locked the account's 2FA out, and a
distributed attack was unbounded.
- The pre-credential block now uses `loginThrottle.isTotpBlocked/`
`recordTotpAttempt` keyed `(sha256(email), source bucket)` in the shared
store (`login-totp-src:`, 5 per window = max(WINDOW, BLOCK), default
5/15 min); both success paths reset only the verifying account+source.
- The old in-memory map and its constants were deleted; `cleanTotpThrottle`
became `cleanTotpUsedCodes`, preserving the TOTP replay-cache sweep
(`totpUsedCodes` via `isTotpCodeRecentlyUsed`/`markTotpCodeUsed`) on the
same 60-second unref'd interval. Amended 2026-11-08
(`adpanel:totp-atomic-claim`): the DB `totp_last_counter` layer this
sentence originally pointed at — a fire-and-forget
`GREATEST(COALESCE(totp_last_counter,0), ?)` persist — was monotonic but
never exclusive (two overlapping workers holding stale snapshots both
passed and both wrote), so it is REPLACED by an atomic monotonic-step
claim (`utils/totp-claim.js`: exactly one racer's
`UPDATE users SET totp_last_counter = ? WHERE id = ? AND
(totp_last_counter IS NULL OR totp_last_counter < ?)` wins and the claim
IS the persist — a loser writes
nothing; an unadjudicable claim fails the verification CLOSED, sole
exception `ER_BAD_FIELD_ERROR`, which degrades open exactly like the old
silent GREATEST failure); the in-memory Map stays the fast same-process
replay guard layered in front of the claim.
## Phase 4 — uniform login failures (single-step login)
`POST /login` disclosed account state through branch-dependent responses: a
2FA account answered `401 requires2FA` before the password was checked
(2FA-presence oracle), suspended accounts answered 403 to any password
(suspension oracle), and with captcha enabled the armed-state JSON diverged
between branches (second oracle).
- One `failCredentials` helper now serves every credential failure (unknown
email, wrong password, wrong OR missing TOTP): one bcrypt comparison, the
captcha arms uniformly, both throttles record, and the response is the
identical `400 "Invalid credentials"` with `loginEmail` kept. Unknown
emails pay a dummy bcrypt comparison (`DUMMY_BCRYPT_HASH`) for timing
parity. Amended 2026-11-12: two supersessions. A missing 2FA code is no
longer a failure at all — it is the post-match 401 challenge
(`adpanel:login-2fa-twostep`, kept through the two-step owner reversal
below). And the compare story is no longer "one comparison": the
unknown-email dummy is minted at the cost-parity floor via
`getDummyHashForCost` (`DUMMY_BCRYPT_HASH` is fallback-only), the
wrong-password branch pads the failed attempt with fail-open
verdict-ignored compares (up to FLOOR−4) so both indistinguishable failure
shapes total the same 2^FLOOR work (`adpanel:bcrypt-cost-parity-dummy`),
and every login-path compare is admission-gated — see "Login admission +
collation-parity throttles (2026-11-12)" at the end of this file.
- `verifyTotpForUser` runs strictly after the password match (it consumes the
code on success); suspension is disclosed only after full authentication
(password + 2FA) — the standard trade-off, throttled by Phase 2.
- `requiresTwoFactor`/`requires2FA` removed from the entire login surface
(sendError options+JSON, sendCaptchaChallenge, GET /login render, and
`views/login.ejs`'s prompt state machine, whose always-visible optional 2FA
field replaces the two-step flow); the settings/assistant step-up payloads
keep their `requiresTwoFactor` contract untouched.
## Phase 5 — login page shows only server-owned error messages
`GET /login` echoed `?error=` query text into the toast on the most
phishing-relevant page.
- New `utils/login-page-errors.js` is the one home: producers send the opaque
code `/login?error=suspended`; `resolveLoginErrorMessage` maps codes through
a fixed Map and returns null for anything else (non-string qs values
included), so query text is never echoed. All three producers converted;
swept repo-wide — no others exist.
## Phase 6 — Socket.IO handshake enforces account binding + revoked sids
The HTTP middleware chain enforced the id/epoch account binding and the
revoked-sid tombstone gate, but the Socket.IO handshake skipped both: a
deleted-then-recreated account's old socket session (or a tombstoned one)
could still connect.
- New `utils/session-account-binding.js` is the ONE definition of "this
session still belongs to this account row" (`sessionAccountBindingMismatch`),
consumed by the HTTP binding/suspension teardown (replacing inline
constants) and by the handshake, which now — after `findUserByEmail` —
rejects on binding mismatch and on `isSessionSidRevoked(…, { failClosed:
false })` with `next(new Error("unauthorized"))`. No session teardown on
the socket path (no response object); the next HTTP request performs it.
## Phase 7 — static fast path narrowed; CSP nonce on every response
The `_staticAsset` classifier flagged any path with a static-looking extension
anywhere in it — server names may contain dots, so `/server/<name>.js` was
fast-pathed: no CSP nonce (helmet emitted `'nonce-undefined'`), and the
revoked-sid gate, remember middleware, binding/suspension teardown and isAdmin
computation were all skipped.
- The classifier now covers only the real static directory prefixes
(`/css/`, `/css-ext/`, `/js/`, `/images/`, `/fonts/`, `/webfonts/`,
`/vendor/`, `/favicon`, images under `/uploads/`) and single-segment root
files; nested dotted dynamic routes take the normal middleware path and get
a real nonce. The nonce middleware no longer skips flagged requests.
- Verified no dynamic routes exist under any flagged prefix; the classifier
stays self-contained (VM-sandboxed test) and mirrors
`PRE_AUTH_STATIC_PREFIXES` by comment — future allowlist changes must land
in the same change.
## Phase 8 — opt-in remember-me; idle timeout for remember-me-off sessions
Sessions rolled for 365 days and every login unconditionally issued a
remember-me token; `REMEMBER_LOGIN_MAX_AGE_MS` was coupled to the session
lifetime so the two could only change together.
- `REMEMBER_LOGIN_MAX_AGE_MS` decoupled to its own 365-day literal. A
"Keep me signed in" checkbox (unchecked by default) rides the login POST;
remember-on keeps the original behavior verbatim; remember-off sessions get
a 12-hour idle timeout (new `utils/session-idle-timeout.js`, env
`SESSION_IDLE_TIMEOUT_MS`, clamp 30 min–30 days), no remember cookie (the
guarded `setRememberLoginCookie` early-returns and clears for
`rememberLogin === false`, covering all four credential-change call sites),
no registry entry, and an audit record with an empty rememberLoginId.
Legacy sessions without the flag keep current behavior; the flag threads
through the pending-captcha state with a tolerant read so pre-deploy
in-flight pendings keep remember-on.
- Active-sessions list, revoke route (legacy-cutoff branch), logout and
`canSkipRememberLoginValidation` verified unaffected — remember-off
sessions list and remain revocable as normal rows.
## Phase 9 — informational items (owner-approved zero-risk set)
- `verifyExternalCaptcha` (all three provider branches) optionally requires
the siteverify response's `hostname` to be in `CAPTCHA_EXPECTED_HOSTNAMES`
(off by default; missing hostname fails closed; the list never derives from
the Host header) — new `utils/captcha-expected-hostnames.js`.
- The unused write-only `adpanel.bp` cookie is no longer set (name kept in
both proxy strip lists).
- Global CSP narrowed: captcha provider hosts are emitted conditionally per
request from the live provider flags (`utils/captcha-csp-origins.js`
mirroring `buildAuthPageCsp`) instead of unconditionally allowing google/
gstatic/hcaptcha/cloudflare on every authenticated page — verified first
that no authenticated page renders a captcha widget; helmet's nonce
directive functions untouched.
- login.ejs dead CSP-blocked assets removed (Google Fonts links, jsDelivr
preconnects, the jsDelivr arrow icon replaced by the byte-identical local
`/images/down-icon.svg`); jsDelivr dropped from the login page img-src
allowlist. The logo button markup is byte-identical (pinned).
- Also fixed en route: `views/bot.ejs` did not compile (an invalid
`<%-- … --%>` comment worked only by accident of the old toolchain) —
converted to a real EJS comment.
## Review-driven fixes — bcrypt cost parity (timing enumeration) and minors
- **MAJOR (adversarial review T1):** `DUMMY_BCRYPT_HASH` was built at the
configured `BCRYPT_ROUNDS` (12) but `scripts/create-user.js` and
`scripts/reset-recovery-codes.js` hashed at hardcoded cost 10 — a 6σ
account-existence timing oracle (58 ms vs 214 ms) inside the 20-probe
budget, invisible to the uniform-400 shape. New `utils/bcrypt-rounds.js`
is the ONE home of the cost decision (`resolveBcryptRounds`, env
`BCRYPT_ROUNDS`, clamp 10–15; `parseHashCost`; `rehashIfStale`); all 16
hash-writer sites now use it, and rehash-on-login upgrades cost-mismatched
rows through the same single password UPDATE password changes use (no
upsert, no epoch bump; heal compute/write errors still fail open — login
continues). Amended 2026-11-08 (`adpanel:rehash-cas`): that write is no
longer keyed by id alone — it is a compare-and-set on the exact credential
the login verified (`WHERE id = ? AND password = ?`, affectedRows-decided),
so a password reset landing mid-login can never be overwritten with a hash
of the old password; a lost CAS re-proves the submitted password against
the re-fetched row and a failed re-proof takes the uniform
`arm:stale-credential` credential-failure path (see "Login concurrency +
same-host-port rides" below). Constraint: every stored hash and the dummy
must cost the same
or enumeration re-appears through response timing. Documented residual:
rows above the ceiling compare for seconds and hit the 8 s timeout before
any heal can run; rows above the ceiling are repaired down to the
configured rounds (parity in BOTH directions) when a compare completes.
- `loginAttackMiddleware`'s plain-text 429 (unparseable by the login page's
fetch → misleading "Invalid credentials" toast) now routes through the one
shared content-negotiated `sendLoginRateLimited` responder, as does the
request limiter's handler.
- The account-429 and TOTP-429 paths pay `loginDelay()` like the IP-429, so
all three refusals are timing-similar (the adjacent comment now claims
parity accurately).
## Cross-cutting wiring fixes (post-campaign analysis)
- **Socket session liveness:** Phase 8's 12-hour idle sessions created a new
state — a dashboard socket authenticated at handshake kept streaming after
its session record expired or was destroyed (the 30 s interval re-validated
only the user row). New `utils/socket-session-liveness.js`: the handshake
pins the authenticated sid, the interval re-validates the record through
the SAME tombstone-wrapped store instance and `isSessionSidRevoked` (the
wrapper guards set/touch only — `get` is unwrapped, so revocation is
checked explicitly), and disconnects dead sockets within one interval;
store errors fail open (throttled log) so a Redis blip cannot
mass-disconnect dashboards.
- **Wire-contract pin:** `tests/login-wire-contract.test.js` derives the
client-read field list from login.ejs and pins every server builder
(sendError, sendCaptchaChallenge, sendOk, the shared 429 responder, the 409
no-pending-login body, finalize-failure) to carry its consumer's fields —
dropping `csrfToken`/`botProofSeed` from an error payload now fails the
suite.
- **One env-int resolver:** the four per-module clamped-int resolvers
(already diverging on `"0"` semantics) were consolidated into
`utils/clamped-int.js` with explicit zero-policy per call site (parity
proven empirically over 372 old-vs-new comparisons); login content
negotiation was unified into one `wantsJsonLoginResponse` predicate shared
by the handler and the limiter responder.
- Hygiene: the rehash comment now states precisely that the hash rewrite
re-fingerprints remember credentials (other devices re-fingerprint at
their next rotation; a session-dead device fails restore once); the CLI
`--password-hash` input is shape-validated instead of throwing deep in
bcrypt; the same-/56 TOTP-poisoning residual is documented next to
`TOTP_ATTEMPT_*`; `.env.example` is no longer swallowed by the `.gitignore`
dotfile rule.
### Verification
- `node --check index.js` clean; full `npm test`: 2944 pass / 0 fail (up from
2813 at campaign start; +131 tests written by the campaign).
- Writeup checklist: forbidden identifiers (`resetLoginAttempts(`,
`recordLoginAttempt(`, `isLoginBlocked(`, `isTotpThrottled(`,
`login?error=Your`, `String(req.query.error)`, `const accountIdMismatch`)
absent from index.js and login.ejs; `requires2FA` survives only in the
authenticated password-change API (pre-existing, non-login surface).
`revokeRememberLoginRegistryEntry(` = 5 calls + 1 definition;
`await revokeRememberLoginRegistryEntryConfirmed(` = 2;
`req.session.regenerate(` = 3, each with the revoked-sid tombstone guard
within the preceding 900 characters (script-verified).
- Pinned constraints re-verified: tombstone markers verbatim, remember
middleware ordering, remember-rotation counts, csrf-port-awareness io.use
ordering, logo 400-char window, CSP nonce functions byte-identical,
node-api-gate classifier (VM-sandboxed) with the narrowed classifier's new
assertions, `requiresTwoFactor` step-up contract untouched.
- Campaign diff independently audited: no loosened check, no weakened pinned
assertion (every test change classified), helmet nonce functions
untouched, trusted_subnets never exempted, captcha `remoteip` always the
raw IP, `bot.js` and `main.go` byte-untouched, index.js net code −50 lines
(comment growth only), all new logic in 10 new utils modules.
- Staging-only walkthroughs (Redis TTLs ≈1800 pre-login / 31536000
post-login, captcha grace flow, rate-limit probes) remain the operator's
final gate; all structural equivalents are test-pinned and were traced
end-to-end by code review.
## Owner reversal — remember-me is always-on again (Phase 8 opt-in removed)
Owner decision: sign-ins must last the full year with no checkbox. The Phase 8
opt-in ("Keep me signed in", `SESSION_IDLE_TIMEOUT_MS` idle sessions) is
removed; the always-on behavior it replaced is restored exactly.
- Both login completions (POST /login and the captcha-pending completion) are
back to the single remember-on path: `ensureRememberLoginSessionId`, the
full audit record with the real rememberLoginId, `setRememberLoginCookie`,
no `cookie.maxAge` override and no cookie clear. The `remember === "1"`
read and its threading through `sendCaptchaChallenge` /
`beginPendingCaptchaLogin` / the pending object are gone.
- `setRememberLoginCookie` is unconditional again (the
`rememberLogin === false` early-return is gone; all four credential-change
re-issue sites behave as before), and the remember middleware runs
`ensureRememberLoginCookie` for every authenticated session again.
- `REMEMBER_LOGIN_MAX_AGE_MS` KEEPS its decoupled 365-day literal (independent
of the session cookie lifetime; the tombstone invariant still bounds it),
and the socket session-liveness check, all throttles and the preauth-TTL
cap are kept — they are correct regardless of session length.
- `utils/session-idle-timeout.js`, its unit test and
`tests/remember-opt-in.test.js` deleted; `SESSION_IDLE_TIMEOUT_MS` removed
from `.env.example`. Sessions minted during the opt-in window with the
`rememberLogin === false` flag need no migration: with the middleware guard
gone they simply regain the year-long rolling behavior (regenerate/refresh
restores the 365-day cookie), and the orphaned flag is inert.
## Owner reversal — two-step 2FA prompt restored (post-password verification kept)
The owner also reversed Phase 4's always-visible 2FA field: the login page is
back to the classic two-step flow — the 2FA field is invisible until the
email+password verify correct, then appears only for accounts with 2FA. The
security-relevant half of Phase 4 is deliberately NOT reverted: the
pre-campaign code disclosed 2FA enrollment BEFORE checking the password
(`401 requires2FA` above the bcrypt compare — an enumeration oracle); the
restored challenge fires strictly AFTER the successful password comparison,
so seeing `requires2FA: true` still proves the caller holds the password.
- `POST /login`: after the password match, a 2FA account submitting no code
gets the challenge — `401 requires2FA: true` (sendError options→JSON/render
mapping, captcha-challenge and GET-render `requiresTwoFactor` surfaces
restored byte-identical to baseline). The challenge records NO throttle
counter, arms NO captcha and touches no gate (the password was correct —
not a credential failure); a wrong code is still a uniform counted 400;
wrong-password/unknown-email responses stay flag-less (strictly more
uniform than the baseline, which flagged them for 2FA accounts).
- `views/login.ejs` / `public/login.css`: baseline two-step client restored
(dynamic `data-requires-two-factor`, `setTwoFactorRequired`,
email-change reset, captcha `enableForm` special case, conditional
required/disabled, baseline CSS state machine; the checkbox row and its CSS
removed; placeholder exactly "2FA Code"). Deliberately kept: the campaign's
escaping fix — attribute markup is never emitted through an EJS output tag;
attribute VALUES (quote-free) are, which also fixes a no-JS gap the review
wave caught (a literal hidden state would have hard-stuck a no-JS 2FA user
on the challenge re-render; the value-only emission bakes the visible state
correctly — render-verified in both modes).
- `REMEMBER_LOGIN_MAX_AGE_MS` literal pin re-homed to
`tests/remember-lifetime-pin.test.js` after the opt-in test file's removal.
- Verification: `node --check` clean; renders compile in both modes with no
escaped-quote garbage; full `npm test` 2933 pass / 0 fail; login-surface
suites (uniform-failure 12, throttle-wiring 16, wire-contract 9) rewritten
consciously to the restored shape with swap-detection ordering pins
(challenge strictly after the bcrypt match; single `requiresTwoFactor: true`
producer).
# Login concurrency + same-host-port rides (2026-11-08)
Reviewer-mandated repairs to the login/auth surface from the Wave-2
compliance + wiring review: the login-path rehash write becomes a
compare-and-set on the verified credential, the TOTP consume becomes an
atomic cross-worker claim, and the shared CSRF port rule stops passing
one-sided explicit ports. Each fix carries its `adpanel:<topic>` comment in
code; this entry records the semantics and the consciously documented
deployment notes. The two earlier sentences in this file that described the
superseded mechanisms (the rehash's "id-keyed UPDATE ... fail-open" wording
and the TOTP sweep's "verified intact down to the DB totp_last_counter
layer" wording) were amended in place above.
- **Login rehash CAS (`adpanel:rehash-cas`).** The rehash-on-login heal wrote
its upgraded hash with an id-keyed UPDATE: an admin or email-keyed password
reset committing between the login's bcrypt compare and the heal's write
was silently overwritten with a hash of the OLD (possibly compromised)
password — un-doing the reset — and the login completed on the dead
credential. The heal's write is now `UPDATE users SET password = ? WHERE
id = ? AND password = ?`, a compare-and-set pinning the exact snapshot hash
the compare verified, with `affectedRows` deciding. A lost CAS means the
submitted password is UNPROVEN against the live row: the handler re-fetches
the row and re-compares; re-proof failure (a reset set a different
password) takes the ONE uniform `failCredentials("arm:stale-credential")`
path — same 400 "Invalid credentials", captcha arming and both throttles
count, no new response shape; re-proof success (a parallel login already
rehashed the same password) continues WITHOUT retrying the heal. The
heal's own compute/write errors still fail open (login continues) exactly
as before; the re-proof branch sits OUTSIDE that catch and fails closed.
Reset writers are untouched — the login side yields to them. The wiring is
pinned by the login suites at the source-structure level
(tests/bcrypt-cost-parity.test.js: the compare-and-set write, the lost-CAS
re-fetch/re-compare and the one uniform failure path;
tests/login-uniform-failure.test.js: branch/count pins) — the runtime
concurrency outcome (two concurrent logins with the correct password both
succeed, one via CAS and one via the re-proof path; a reset landing
mid-login makes the old password's login fail) is design-verified, not
HTTP-tested: no HTTP-level test executes those scenarios.
- **TOTP atomic step claim (`adpanel:totp-atomic-claim`).** The persistent
TOTP replay layer was a stale-snapshot pre-check plus a fire-and-forget
`GREATEST(COALESCE(totp_last_counter,0), ?)` persist: monotonic but never
exclusive, so two overlapping requests on different workers/instances with
stale snapshots both passed the pre-check, both wrote, and one code
authorized two verifications. New `utils/totp-claim.js` is the ONE home of
the cross-worker claim: a single atomic claim-by-monotonic-step
(`UPDATE users SET totp_last_counter = ? WHERE id = ? AND
(totp_last_counter IS NULL OR totp_last_counter < ?)`) where
`affectedRows >= 1` wins — and the claim IS the persist: a winning claim
writes the counter, a losing claim writes nothing. Every flow that reaches
the verifier already treats the DB as a hard dependency, so an
unadjudicable claim (timeout, unreachable DB, unexpected driver error)
FAILS CLOSED; the SOLE exception is `ER_BAD_FIELD_ERROR` (legacy schema
where the boot ALTER failed), which degrades OPEN exactly like the old
silent GREATEST failure, logged loudly once per process — the in-memory
Map remains the only replay guard in that legacy mode. `verifyTotpForUser`
is now async; the consume layers the in-memory Map (fast same-process
replay guard, unchanged) in front of the claim, and a lost or failed claim
answers exactly like a replayed code — uniform failure, the response
cannot distinguish them. The 2FA confirm burn migrated to the same claim
path and aborts BEFORE the new secret is persisted on a lost claim;
`persistTotpLastCounter` and its GREATEST SQL were deleted (net index.js
shrink). The two-step password/email change flows keep their
`consume: false` pre-check + concluding-claim shape, `TOTP_STEP_SECONDS`
and `currentTotpStep` are untouched, and the claim function never rejects
(every outcome resolves to a result object — no new unhandled-rejection
crash class). Pinned by `utils/totp-claim.test.js`: win/lose/race (two
claims of one step, exactly one wins), error fail-closed, and
ER_BAD_FIELD_ERROR degraded-open.
- **Same-host port rides closed (`adpanel:csrf-port-awareness`, extended).**
`explicitPortsDiffer` returned false when EITHER side lacked an explicit
non-default port, so `Origin: https://panel.example.com:8443` against a
portless Host passed the shared rejection decision on all three
cross-origin surfaces — sameOriginProtection (HTTP state-changing routes),
isSocketOriginAllowed (the Socket.IO handshake) and rejectCrossSiteRead
(cookie-bearing reads) — and an attacker controlling a sibling HTTPS
service on another port of the SAME hostname rode the victim's
SameSite=Lax session cookie (host matching ignores ports). The ONE shared
decision, `csrfPortMismatch` in `utils/origin-host.js`, now ALSO rejects
when exactly ONE side carries an explicit non-default port and the other
carries no port evidence: browsers send an explicit port in BOTH Origin
and Host when the port is non-default, so one-sided evidence is either
(a) the same-host sibling-service ride this closes, or (b) a
port-stripping/rewriting proxy — case (b) is what the existing escapes
serve, unchanged and load-bearing: trusted X-Forwarded-Host (both surfaces
since the 2026-11-09 round; HTTP-only when this round landed), the
PANEL_PUBLIC_URL host+port escape, portBlindTrust
(CSRF_ALLOWED_HOSTS / NODES_CORS_ORIGINS), browser-attested
sameOriginFetch, and cookie-less requests. Both portless → pass
(default-port and NAT/port-forward deployments keep working); both
explicit and equal → pass; both explicit and different → reject
(unchanged); one-sided → reject. `explicitPortsDiffer` stays exported as
the both-explicit vocabulary; the stricter decision lives only inside
`csrfPortMismatch` (no checks were added at call sites). Known accepted
edge, documented rather than fixed: a deployment serving plain HTTP on
port 443 or HTTPS on port 80 behind a rewriting proxy with no
PANEL_PUBLIC_URL is now rejected where it passed before — that shape is a
misconfiguration, and either documented remedy escapes it (the exact
`PANEL_PUBLIC_URL`, or trusted `X-Forwarded-Host` forwarded WITH the port
— both serve every guarded surface as of the 2026-11-09 round). Pinned by
`tests/csrf-port-awareness.test.js`, `tests/csrf-localhost-scoping.test.js`
and the source-structure parity pins in
`tests/node-relay-cross-site-guard-parity.test.js` (that file predates this
round and passes UNCHANGED — its parity pins were verified to hold against
the new source, their semantic-level one-home/routing assertions needing no
edit).
### Verification
- Full `npm test`: 2945+ pass / 0 fail (node --test over utils/ +
tests/); `go test .` ok (Go untouched by this round).
- Consciously documented deployment notes (the port tightening is
deliberately breaking for two shapes, each with a documented escape):
- Rewriting-proxy deployments serving the panel on a NONDEFAULT port need
serving-port evidence configured — `PANEL_PUBLIC_URL` with the exact
port, OR a trusted proxy that forwards `X-Forwarded-Host` WITH the port
(`proxy_set_header X-Forwarded-Host $http_host;` — honored on both the
HTTP and Socket.IO surfaces since the 2026-11-09 round, see that entry)
— the one-sided port rule now rejects their portless-Host traffic
otherwise. The plain-HTTP-on-443 / HTTPS-on-80 edge is accepted +
documented (see the port bullet above), not fixed: it is a
misconfiguration, and either of the same two remedies is its escape.
- `PANEL_PUBLIC_URL` must be scheme+host+port EXACT: the escape matches
the browser-sent origin host AND port (e.g.
`https://panel.example.com:8443`); a portless value never matches a
nondefault-port deployment, and a different-port value is exactly the
ride the rule rejects. The `.env.example` `PANEL_PUBLIC_URL` sample
carries the same note.
- Regression posture re-verified: default-port deployments, NAT/port
forwards, XFH-preserving proxies, loopback dev on localhost:3000 and
CSRF_ALLOWED_HOSTS users keep passing; only the one-sided explicit-port
shapes changed verdicts.
# Rewriting-proxy operability (2026-11-09)
Operability follow-up to the 2026-11-08 same-host port-ride closure above.
The one-sided port rule rejects the deployment shape "panel on a NONDEFAULT
public port behind a Host-REWRITING proxy" whenever the proxy neither
forwards a port-carrying trusted `X-Forwarded-Host` nor has
`PANEL_PUBLIC_URL` set to the exact public URL: the browser's
`Origin: https://host:8443` is then the only explicit-port evidence while
every serving-side source is portless, and that shape is indistinguishable
from the sibling-port ride — configuration is the ONLY discriminator. Until
this round the brick was also silent (bare 403 "CSRF blocked" / socket
"origin-not-allowed", no log) and only PARTIALLY fixable by proxy config:
the HTTP surface honored trusted X-Forwarded-Host, but the socket surface
ignored it entirely. This round makes the shape (a) fixable with a standard
proxy line on BOTH surfaces and (b) loudly diagnosable when it does reject.
The rule itself does NOT soften — same-host sibling-port attacks stay
rejected.
- **Socket surface accepts trusted X-Forwarded-Host serving evidence
(`adpanel:socket-forwarded-host`).** The Socket.IO handshake origin check
(`isSocketOriginAllowed`) now derives the serving host:port from the SAME
trust-screened `X-Forwarded-Host` entry the HTTP CSRF middleware uses
(`getTrustedForwardedHost` resolves it before the derivation, exactly like
the middleware): the header counts only when the direct connection peer
passes `isTrustedProxyIp`, and direct connections ignore XFH entirely —
parity with the HTTP surface, not a new trust grant; a trust-resolution
failure falls open to Host-only evidence, i.e. exactly the pre-round
behavior. The header feeds ONLY the serving-port derivation for the port
check — the host-equality grant and the operator allowlist
(`CSRF_ALLOWED_HOSTS` / `NODES_CORS_ORIGINS` / the `PANEL_PUBLIC_URL`
host / the socket surface's own `SOCKET_ALLOW_ORIGINS`) are untouched,
and rejection verdicts and wire bodies stay byte-identical. Consequence: the one nginx line
`proxy_set_header X-Forwarded-Host $http_host;` (forwards the Host header
WITH its port) fixes a nondefault-port rewriting-proxy deployment on BOTH
surfaces with ZERO panel config — no `PANEL_PUBLIC_URL` required. Pinned
by `tests/csrf-port-awareness.test.js` (explicit-port origin + port-
carrying forwarded evidence now passes; portless, different-port and
absent forwarded evidence still reject), with the structural pins in
`socketOriginWindow()` consciously updated to the mirrored serving
derivation while keeping the allowlist→port→equality ordering, the
no-local-copy property and the no-sec-fetch-site property;
`tests/node-relay-cross-site-guard-parity.test.js` passes unchanged.
- **Port-mismatch advisor (`adpanel:port-mismatch-advisor`).** New
`utils/origin-port-advisor.js` (dependency-injected, no repo-internal
requires) makes the remaining brick LOUD. What its log line MEANS when it
appears: cookie-bearing requests from an explicit-port origin (e.g.
`https://panel.example.com:8443`) are being rejected because the serving
Host header carries NO port evidence — the panel is on a nondefault port
behind a proxy that strips/rewrites the Host header, a deployment shape
indistinguishable from the sibling-port attack without configuration. The
message names the offending origin host:port (echo capped at 24 chars, so
the full diagnosis plus BOTH remedies fit securityLog's 200-char message
budget verbatim): set `PANEL_PUBLIC_URL` to the exact browser
scheme+host+port, OR the nginx `proxy_set_header X-Forwarded-Host $http_host;`.
It fires ONLY on the
brick shape — explicit non-default origin port + portless serving
evidence — and at all three rejection points (the HTTP middleware's 403
branch, the socket handshake, and the cross-site read guard's rejection
branch); it NEVER changes a verdict: rejection semantics and wire bodies
stay byte-identical. The read guard gets the SAME advisor instance via
dependency injection at index.js's `crossSiteReadGuard.setCrossOriginTrustContext`
wiring (together with a `logAdvice` sink); `nodes.js` binds the guard
WITHOUT that dep (it never calls `setCrossOriginTrustContext`), so its
copy stays byte-identically inert — the guard degrades to Host-header-only
matching, narrower trust, never wider. Because the origin header
is attacker-controlled, the log is throttled exactly like
`_logCsrfExtraAllowedUse`: per origin `host:port` key, a Map capped at 50
entries (clear-on-overflow), at most 20 emissions per fixed 1h window (the
budget window is anchored at the first emission after the previous one
expires — it does not roll; only the per-key suppression rolls),
call-driven with no timers — an attacker cannot flood the security log by
forging origins, and a legitimate operator still gets the diagnosis
within the window. Pinned by `utils/origin-port-advisor.test.js` (the
one-sided shape fires; both-explicit / serving-explicit / portless-origin
/ unparseable stay null; same-key suppression within the window, budget
cap, map cap, DI cleanliness).
- **Residual — rejection by design.** A deployment whose proxy neither
forwards `X-Forwarded-Host` with the port nor is covered by an exact
`PANEL_PUBLIC_URL` keeps rejecting cookie-bearing traffic, deliberately:
with no trustworthy signal there is nothing that distinguishes it from
the sibling-port ride the 2026-11-08 rule closes, and the panel does not
invent trust. The advisor's log line is the designed failure mode for
that shape — it names the cause and both escapes instead of a bare
403 / "origin-not-allowed". When `PANEL_PUBLIC_URL` is the chosen remedy
it stays scheme+host+port EXACT: a portless value never matches a
nondefault-port deployment (guidance unchanged in `.env.example`).
- **Installer reference (initialize.sh untouched by this round).**
Installer-generated deployments are not exposed to the shape:
`build_public_url` in initialize.sh writes `PANEL_PUBLIC_URL` WITH the
port whenever the chosen port is nondefault (the `:port` segment is
appended only for non-default ports), so installer-made panels already
satisfy remedy 1 out of the box; the remedies above matter for
hand-rolled proxy configs and post-install port moves.
- **Documentation catch-up (this file + `.env.example`).** The 2026-11-08
entry's deployment note and its known-edge sentence now present BOTH
remedies instead of `PANEL_PUBLIC_URL` alone (amended in place above,
with the trusted-XFH escape's surface scope corrected to both surfaces);
the `.env.example` `PANEL_PUBLIC_URL` block keeps the exact
scheme+host+port guidance and adds the X-Forwarded-Host alternative. The
in-code comments that still name the singular remedy (the
`adpanel:csrf-port-awareness` middleware/socket blocks and the
`csrfPortMismatch` boundary comment in `utils/origin-host.js`) are
amended to the two-remedy form with the code half of this round.
### Verification
- Full `npm test` at this round's documentation time: 2951 pass / 0 fail
(node --test over utils/ + tests/); `go test .` ok (Go untouched by this
round).
- The Phase-2 suites themselves — `utils/origin-port-advisor.test.js`, the
updated `tests/csrf-port-awareness.test.js` scenarios and the consciously
updated `socketOriginWindow()` pins — land with the code half of this
round and are reported by the campaign; this entry is the documentation
half, landed in parallel with the code agent's diff.
# Login admission + collation-parity throttles (2026-11-12)
Two POST /login fixes that postdate the sections above and were, until this
entry, documented only by their `adpanel:<topic>` comments in code: admission
control over login-path bcrypt work, and the collation-proof re-keying of the
per-account throttle. This entry records the semantics and the pinned wiring;
the Phase 4 bullet above is amended in place for the superseded compare
story.
- **Bcrypt admission control (`adpanel:login-bcrypt-admission`).** The
throttle budgets bounded only the per-attempt rate and the COUNT of
compare-bearing attempts per window, never how many of them occupy libuv
threads AT ONCE — and since the cost-parity work every credential failure
pays the same 2^FLOOR work units (BCRYPT_COST_PARITY_FLOOR), a parallel
burst of admitted logins from one /56 was an unbounded threadpool
amplifier: withTimeout is Promise.race, so a timed-out compare is
abandoned but never cancelled and keeps its threadpool thread to
completion — a burst injected ~120 threadpool-seconds against the default
4-thread pool, saturating it permanently and pushing legitimate logins and
the step-up/recovery verifies past their 8 s windows. Two halves close it.
The COUNT half: failure counting moved out of the uniform failure path
into `loginThrottle.reserveCredentialAttempt` — the ONE counting site
(exactly two gate sites: the unknown-email reservation holds the fold key
only, no account to id-key; the known-email reservation increments the
source counter AND both account keys atomically) — which admits only
under the budgets, so an over-budget reservation is refunded and refused
BEFORE any compare is ever queued (a not-admitted request records
nothing), and every non-failure exit after admission (the 2FA challenge,
the captcha challenge, suspension, the config 500, the success paths)
refunds the outstanding reservation, floored at zero, so the net recorded
failures stay exactly the CONFIRMED ones; `finalizeCredentialFailure` is
the side effects beyond counting only (captcha arming + threshold-crossing
logs, never a re-increment). The CONCURRENCY half: new
`utils/bcrypt-admission.js`, a FIFO promise semaphore
(`BCRYPT_LOGIN_MAX_CONCURRENT`, default 2, clamp 1–32) capping how many
login-path bcrypt compares run simultaneously. ONLY the POST /login
compares are wired through it — the unknown-email floor dummy, the real
credential compare, the parity-pad sequence as ONE acquisition (a single
logical parity unit per failed attempt, up to FLOOR−4 compares, so
per-compare acquisition would multiply queue traffic without changing the
bounded-work property) and the rehash-CAS re-proof; the post-auth verify
surfaces (`verifyPasswordForUser`, password-change/recovery compares) are
deliberately NOT wired: their callers are already authenticated, so they
are not part of the unauthenticated amplification chain — and
semaphore-waiting them would let a login burst starve step-up, password
change and recovery, the exact starvation this fix removes. The semaphore
wait counts INSIDE the caller's 8 s window: saturation degrades to the
disclosed fail-open posture instead of unbounded pool occupancy — since
`adpanel:login-id-refusal-parity` (L4) every login-path compare breach
settles through the ONE uniform failure path (the outstanding reservation
finalized, the byte-identical uniform unknown-email 400 — never a 500;
the pre-existing T1-B 500 posture narrows to compare consumers outside
the login surface: recovery codes, password step-ups, admin login), the
slot releases only when the compare actually settles (bcrypt work cannot
be cancelled), and FIFO waiters mean the earliest admitted attempt goes
first. Pinned by
`utils/bcrypt-admission.test.js` and `tests/bcrypt-cost-parity.test.js`,
plus the reservation/refund wiring pins in
`tests/login-uniform-failure.test.js` and
`tests/login-throttle-wiring.test.js`.
- **Collation-proof account throttle
(`adpanel:account-throttle-collation-parity`).** The per-account failure
budget was keyed `sha256(trim().toLowerCase())` while the account lookup
matches `WHERE LOWER(email) = LOWER(?)` over a utf8mb4_unicode_ci column
(live-verified against the production MySQL with the app's own mysql2
driver), so Unicode variants of one address — fullwidth
victim@example.com, jose@… against a stored josé@…, strasse@…
against a stored straße@… — MATCHED the victim's row but hashed to
DISTINCT buckets: every variant minted a fresh 20-failure budget and the
aggregate per-account spray control did not bind. Two layers close it.
(1) `foldAccountEmail` — NFKC → NFD → strip combining marks →
toLowerCase → ß/ẞ → "ss" → trim — the cheap JS-side approximation of the
collation, applied inside `hashAccount` to every pre-lookup key (no DB
round-trip); live-probed: the fullwidth, accent, eszett and ligature
classes all fold into one bucket, agreeing with the collation's equality
facts. (2) The resolved user id (`sha256("acct-id:" + user.id)`) as the
POST-lookup enforcement key — an identity no collation can reinterpret —
via id-keyed mirrors (`isAccountBlockedById`/`isTotpBlockedById`/
`recordTotpAttemptById`) sharing the SAME store instance, prefix and
window as the email-keyed counters, whose refusals keep the same
securityLog but route through the unknown path's OWN fold-only admission
(`adpanel:uniform-failure-admission`: the ONE shared helper
`refuseRowResolvedUniformFailure` reserves on the SUBMITTED email's fold +
source keys — the attacker's own string, never the resolved row's id key):
with source/fold budget headroom the reservation is ADMITTED — the parity
work burns, the failure is recorded on those budgets, and the refusal
answers the uniform unknown-email 400 shape, no 429, no `Retry-After`; once
that budget fills it answers the SAME honest 429 + `Retry-After` an
unknown email receives in that exact state (no burn, no record), so a
refusal keyed on a RESOLVED row is indistinguishable from the unknown-email
failure in wire shape AND accounting cost in EVERY budget state
(`adpanel:login-id-refusal-parity`: otherwise a collation-variant probe
converts a full id budget into a one-bit account-existence oracle)
— while the pre-lookup refusals keep the
honest 429 + `Retry-After` + `loginDelay` shape, and whose id TOTP check
still runs before the compare so the refusal reveals nothing about password
validity. The login
reservation increments BOTH account keys (fold + id) atomically, so the
admission gate above is collation-proof too. Documented residuals: the
fold is an approximation in BOTH directions — collation-equal classes the
fold misses (ς=σ — with lunate ϲ NFKC-mapping onto ς — and œ=oe;
live-verified against MySQL 8.0.46 utf8mb4_unicode_ci via
information_schema + WEIGHT_STRING, which does NOT equate æ=ae nor ł=l,
and æ has no compatibility decomposition) are still enforced for resolved
accounts by the id layer, while the mark-strip over-merges some
exotic-script classes the collation keeps distinct (Devanagari, Thai), an
accepted one-window lockout trade-off; unknown-email probes count on the
fold key only (no account exists to protect); and the DB lookup input
itself is deliberately NOT folded in JS, because JS folding could change
WHICH row matches for exotic character classes. Pinned by
`utils/login-throttle.test.js` and the dual-key/id-mirror wiring pins in
`tests/login-throttle-wiring.test.js` and
`tests/login-uniform-failure.test.js`.
### Verification
- `node --check index.js` clean; full `npm test`: 3235 pass / 0 fail
(node --test over utils/ + tests/); `go test .` ok (Go untouched by this
round).
- This round is a comment/documentation-truthfulness pass: zero code or
assertion changes. The one source edit rewords the
`adpanel:login-uniform-failure` comment's superseded "exactly one bcrypt
comparison per failure" sentence to the post-parity-pad truth (work
equalized at the floor, compare-CALL count varying per branch), and the
matching test title in `tests/login-uniform-failure.test.js` was reworded
consciously — its assertions (the one real, one floor-cost dummy and one
re-proof compare sites, the pad placement inside the wrong-password
branch) already pinned the current shape and pass unchanged.
# Stealth pre-gate session-mint cap + Redis maxmemory-policy deployment requirement (2026-11-15)
## F1 — gateless GET /login minted one Redis session per request, unthrottled (Medium — availability)
With `STEALTH_MODE` on (the default), a gateless `GET /login` ends in
`sendStealthBootstrap`: the stealth gate answers BEFORE `loginRequestLimiter`
(that limiter mounts on `/login` far below the gate), so nothing throttled the
path. The bootstrap mutates `req.session.stealthBootstrap` and calls
`req.session.save()` EXPLICITLY — one Redis session record per pre-gate
request. The 30-min preauth TTL (`utils/preauth-session.js`) caps each entry's
lifetime but not the aggregate rate. Under the repo's
`maxmemory-policy noeviction` pin a flood self-arrests fail-closed (Redis
fills, every save 500s, the login throttle's reservation refuses with reason
"store"), but on a small host that is trivially cheap to trigger — and on an
operator-supplied external Redis running `allkeys-lru` the flood additionally
EVICTS live sessions and sid tombstones.
### What changed
- `adpanel:stealth-mint-cap` (index.js): pre-gate session MINTING is now
bounded by two shared-Redis fixed-window counters built from the ONE store
factory (`buildSharedRateLimitRedisStore`, one instance + distinct prefix
per counter — `stealth-mint-src:` / `stealth-mint-global:`), checked BEFORE
any session work in `sendStealthBootstrap`. Budgets: 20 per /56-bucketed
source per 10 min (`ipKeyGenerator`, so IPv6 rotation cannot mint fresh
budgets) and 2000 global per 10 min — a human needs 1-2 bootstraps, a NAT
office shares one bucket with >10x headroom, and the global breaker caps
the worst-case mint rate at ~3.3 writes/sec. Counter store errors FAIL
CLOSED (the factory's fallbackHits=0 sentinel, the same direction as the
login throttle's reservation): a full Redis outage already fails the
explicit `save()` (same client, `disableOfflineQueue`), so refusing the
mint degrades nothing and sheds the flood at the OOM boundary. Over-cap
requesters get the plain stealth decoy (`sendStealthNotFound`, the same
static 404-empty the gate serves protected assets) with ZERO session
writes — the state token `/_stealth/authorize` validates never exists for
them, and that step fails closed (clear cookie + redirect /login). No new
mount was added (the cap lives in-handler), so the 52-registration
pre-gate census is unchanged.
- The second pre-gate stealth write amplifier closed under the same tag:
`/_stealth/authorize` previously called `req.session.save()` on EVERY
request — including stateless garbage probes (the gate deliberately skips
`/_stealth/` paths, and no limiter sees them) — persisting one orphan
EMPTY session record per probe. The save is now conditional on the request
actually consuming a bootstrap state (the save exists to persist exactly
that single-use consumption); stateless probes keep an identical response
(clear cookie + redirect) with no store write. The authorize VALIDATION is
byte-identical.
- `adpanel:redis-maxmemory-policy-advisory` (index.js boot region): on the
session Redis client's first `ready` transition the panel runs a
best-effort `CONFIG GET maxmemory-policy` and warns when the policy is not
`noeviction`. Log-only, never an exit; a provider that blocks CONFIG is
skipped silently.
### Deployment requirement (F-G): session Redis must run `maxmemory-policy noeviction`
The deployment expects the session Redis to run with
`maxmemory-policy noeviction` (the initialize.sh setup pins it via
`calculate_redis_maxmemory` → `maxmemory-policy noeviction`). With
`allkeys-lru` or `volatile-lru`, a memory flood evicts the LEAST-recently-used
keys — the LRU reaper cannot distinguish a bootstrap-flood orphan from a live
session or a revoked-sid tombstone — so (a) authenticated users get logged
out, and (b) a revoked sid's tombstone can be evicted before its TTL,
resurrecting a logged-out session cluster-wide and voiding the revoked-sid
gate's durability. With `noeviction`, the same flood self-arrests fail-closed:
writes error OOM and every consumer (session saves, tombstones, throttle
counters) already has a designed failure path. The stealth-mint cap bounds
the flood RATE but cannot make an evicting policy safe. Operators MUST set
`maxmemory-policy noeviction` and monitor `used_memory` / `maxmemory` (the
boot advisory warns when a reachable Redis reports otherwise; a provider that
blocks `CONFIG` cannot be auto-verified and the written requirement still
applies).
### Verification
- `node --check index.js` clean.
- New tests `tests/stealth-mint-cap.test.js`: under-cap mint is
byte-identical to the pre-fix response over the same captured inputs;
per-source over-cap → static decoy with zero session writes and no state
minted (authorize then fails closed); global over-cap → same; per-source
isolation (one exhausted source cannot affect another); counter store
error → fail-closed decoy; the save-failure path still 500s (existing
behavior, now pinned); stateless authorize probes write nothing; source
pins for the cap-before-session-write placement and the distinct store
prefixes/instances.
# Investigation round 2026-11-15 — maintenance-page de-fingerprinting, failed-login audit, CSP img-src posture
Three fixes from the investigation round: one confirmed stealth leak on the
only pre-gate view that still renders during a lockdown (F4c), the durable
failed-login forensic record (F3), and the documented-deliberate posture of
the global CSP `img-src *` (F4b, no code change).
## F4c — the maintenance 503 page carried pre-gate ADPanel fingerprints (confirmed)
`views/maintenance.ejs` is the ONLY pre-gate HTML view not stealth-covered —
deliberate: it must render during a lockdown. That made its `<head>` the one
pre-auth surface an unauthenticated prober could still read, and it shipped
two fingerprints:
- `preconnect` / `dns-prefetch` hint lines naming `https://cdn.jsdelivr.net` —
a host hint leaks to the visitor's resolver/CDN regardless of what the
favicon href resolves to;
- favicon and alternate-icon hrefs pointing at the operator's
`branding.faviconUrl` / `branding.logoUrl` — the shipped
`data/branding.json` sets a jsDelivr ADPanel asset URL, de-anonymizing the
panel to any unauthenticated visitor during maintenance.
What changed (`adpanel:stealth-favicon-decoy (maintenance page)`):
- Both hint lines are deleted; both favicon hrefs now point at the
same-origin `/auth-assets/favicon` route, which is reachable during
maintenance (`/auth-assets/` is a maintenance-bypass and pre-auth-gate
static prefix) and whose pre-gate answer is the 204-empty decoy
(`adpanel:stealth-favicon-decoy`) while admins get the real favicon —
byte-consistent with the existing decoy posture. The view carries an EJS
comment (emits nothing) documenting why.
- `adpanel:maintenance-503-no-store` (index.js): both maintenance 503 exits —
the `/api/` JSON and the HTML render — now set `Cache-Control: no-store`.
The global HTML no-store middleware and the `/api/` CDN middleware mount
AFTER the maintenance terminator, so a terminated request never reaches
them; these were the only pre-gate responses without an explicit cache
policy. Plain `no-store`, the same style the pre-gate login/forgot header
builders set.
- Remaining remote references on the page (Google Fonts, cdnjs font-awesome)
stay: they are generic public CDNs, not ADPanel-identifying, and the page
must keep rendering styled during the lockdown. The page's own text content
is unchanged.
Pinned by `tests/maintenance-page-stealth.test.js`: no jsDelivr /
preconnect / dns-prefetch / faviconUrl / logoUrl / adpanel-dark anywhere in
the view source; a real render (remote-branding and no-branding locals)
emits neither the fingerprints nor the comment, with both favicon hrefs =
`/auth-assets/favicon`; structural pins that both 503 exits set `no-store`
before responding.
## F3 — durable sampled failed-login audit (hardening)
Failed logins left only in-memory/Redis throttle counters and console
securityLog — no durable forensic row. The success-only durable audit
(`adpanel:login-audit-durable`, utils/login-audit.js) is extended
consciously; its three success call sites and the DDL table shape are
byte-identical (method is an existing VARCHAR(32) column — no schema change).
What changed (`adpanel:failed-login-audit`):
- `recordFailedLoginAudit({ email, req, reason })` on the same recorder —
adapted to the module's real shapes (IP/UA derived from `req` through the
same trusted-proxy-aware `getRequestIp` the success recorder uses, never a
caller-supplied raw IP). Fire-and-forget contract unchanged: never rejects,
never throws, never gates, no latency — called after the failure decision
(`finalizeCredentialFailure`), immediately before the uniform 400, never
awaited.
- Write-volume bound (the critical design constraint — an attack must not
amplify DB writes): failure rows are bounded by the throttle budgets
themselves. Every `failCredentials` caller already consumed an ADMITTED
credential reservation (admission is refused before any compare —
`adpanel:login-bcrypt-admission`), so the recording population is ≤
`LOGIN_IP_MAX_FAILURES` admitted failures per source per window (default
10/10min). The standing-block refusals (`arm:id-account-blocked`,
`arm:id-totp-blocked` — routed through the fold-only admission helper)
ALWAYS record (their rate IS that admission budget, ~10/source/10min);
ordinary credential failures record deterministically 1-in-20 (a rolling
counter — exactly 0.05× the admitted rate, ≈0.5 rows/source/10min sampled
worst case; the counter advances before the insert decision, so a failed
insert does not re-roll). NEVER recorded: pre-row 429 refusals and
reservation refusals (honest throttles — already visible via Retry-After;
they return through `rejectReservation` before the recorder is reached),
honeypot/non-browser 403s (attacker-known state, unbounded), CSRF/botProof
failures (pre-credential).
- The submitted email is ATTACKER-CONTROLLED: stored TRIMMED, control chars
stripped, ≤254 chars (the RFC 5321 operational limit, inside the column's
255) — the forensic point is what the attacker typed (collation variants
included), so it is never resolved to a canonical row (`user_id = 0`
sentinel, no schema change) and never logged to console raw.
- `reason` is the login handler's fixed `arm:*` debugLabel literal (bounded
anyway; no free text). It is NOT persisted — the frozen table shape has no
reason column and a DDL change is out of scope for this recorder; the token
drives the always-vs-sampled policy and nothing else.
- The closed method whitelist gains `'failed'` (VARCHAR column, no
migration — the whitelist's documented purpose); the success recorder's
call sites never pass it. The retention prune's WHERE is created_at-only,
so `method='failed'` rows age out on the same 180-day bound — verified, no
prune change needed.
- Both recorders now write through ONE shared insert statement (the
one-true-home rule: exactly one audit-table INSERT string in the module,
still pinned).
Pinned by the extended `tests/login-audit-durable.test.js`: whitelist is the
closed four-method set; 19 ordinary failures write NOTHING (not even the
table ensure) and the 20th writes exactly one row (deterministic 40 → 2);
both standing-block reasons record on every attempt (25/25, 2/2 with a
failing db); fail-open (never rejects, warns WITHOUT the email); email
bounding (control chars stripped before the 254-slice, all-control input
bounds to ""); user_id=0 + submitted email + method 'failed' params; the
prune's WHERE has no method filter; the failure call site sits inside
`failCredentials` after `finalizeCredentialFailure` and before `sendError`,
never awaited. The behavioral sandboxes
(`tests/login-id-refusal-parity.test.js`, `tests/login-staleness-reproof.test.js`)
gained a `recordFailedLoginAudit` stub sink — their success-audit assertions
are unchanged and their wire-shape assertions (the sendError boundary) prove
the audit call never changes the wire.
## F4b — the global CSP img-src * is deliberate (posture documentation, no code change)
The global CSP `img-src * data: blob:` is DELIBERATE (`adpanel:csp-imgsrc-global`
comment at the helmet config): operator remote branding (`logoUrl` is an
arbitrary public https host) and the admin template manager's free-text
`templateImage` URLs are unbounded at runtime, so a static allowlist cannot
be honest — it would silently break every deployment whose branding host is
not on it. The AUTH pages do not inherit the wildcard:
`applyLoginPageSecurityHeaders` / `applyForgotPasswordPageSecurityHeaders`
overwrite the header with a strict derived img-src (verified — the operator's
branding origin is added dynamically, never a hardcoded host; the code
comment references these builders by ROLE, because the
tests/login-csp-coverage.test.js pin counts every bare mention of the login
builder's name as a potential parallel wiring), and the pre-auth maintenance
page's favicon is now the same-origin decoy route (F4c above). Revisit only if `templateImage` moves behind a same-origin proxy
(e.g. a `/template-media/:id` route mirroring `/branding-media`) and branding
gains one too — then `*` can narrow to `'self' data: blob:`.
Ledger note (pre-gate name-level fingerprints): `/healthz` and `/healtz` are
documented pre-gate routes answering a name-level fingerprint
(`{ ok: true, service: "adpanel", ts }`) — deliberate; `/healtz` is the
historical-typo decoy spelling that must keep matching, and both are pinned
by `tests/pre-gate-mount-census.test.js` (exact-path census entries). This
is the documented exception to the stealth-404 posture for path-level
probes; no change.
### Verification
- `node --check index.js` clean; `node --check utils/login-audit.js` clean;
EJS render of `views/maintenance.ejs` verified (no jsDelivr/host strings in
output, both favicon hrefs = `/auth-assets/favicon`, the comment emits
nothing, null-branding locals still render).
- Targeted: `tests/login-audit-durable.test.js` (29/29),
`tests/maintenance-page-stealth.test.js` (5/5),
`tests/pre-gate-mount-census.test.js` green (the maintenance render is not
a registration — the census is untouched), the login/parity/staleness
behavioral suites green after the conscious sandbox-stub updates.
# External-review round 2026-11-15 — cookie-Secure peer-trust leg, bounded response-gating session saves
Two LOW findings from an external review, both synthesis-verified against the
tree before implementation.
## F-1 — cookieSecureForRequest's auto leg ignored the TRUSTED_PROXY_IPS view (LOW, config-dependent)
`cookieSecureForRequest` keyed its auto leg on Express's TRUST_PROXY view only
(`connection.encrypted || req.secure`, default loopback), while the login
gate's predicate (`isRemoteProxyTrustViolationRequest`) uses the wider
peer-trust view (TRUSTED_PROXY_IPS + X-Forwarded-Proto via
`getTrustedForwardedProto`/`getDirectRemoteIp`/`isTrustedProxyIp`). With
TRUSTED_PROXY_IPS set and TRUST_PROXY forgotten, POST /login passes the gate
(the proxy IS trusted in the peer-trust view) while cookies shipped WITHOUT
Secure (`req.secure` false) — and the runtime misconfig warn is structurally
blind, because a trusted peer is exactly the state that never fires
`isRemoteProxyTrustViolationRequest`. The half-fixed setup was silently the
worst state for cookie flags, with nothing pointing it out.
- The auto leg now ALSO treats the request as secure when
`getTrustedForwardedProto(req) === "https"` — the ONE resolver the login
gate keys on (`adpanel:cookie-secure-trusted-proto`), no second XFP parse.
The explicit-env leg keeps priority and is unchanged. Mirrors and extends
express-session's secure:"auto" intent: the predicate decides the Secure
attribute, nothing else.
- Consumer census re-verified (pinned by
`tests/cookie-secure-trusted-proto.test.js`): NO consumer gates or refuses
on the predicate. Every site is a `secure:` cookie attribute (remember
cookie options/clear, stealth gate options/clear, adpanel.sid clears), the
db-proxy cookie-attr plumbing (`cookieSecure` option → token cookie
attributes only), or the upgrade-only Secure-sync pin — pin-when-true, so
the widened leg makes the durable pin fire for trusted-proxy https requests
(the `cookieSecurePinned` marker still dirties the session for the store
save, per `adpanel:secure-pin-durable`). The widened leg can only ever ADD
the Secure attribute; a refusal gate on it would fail the census pin.
- Boot advisory/comment updated to say exactly which half each env fixes
(TRUSTED_PROXY_IPS: the throttle bucket AND — via this leg — cookie Secure
on its own; TRUST_PROXY: the Express req.secure view incl. the FORCE_HTTPS
redirect), plus the half-fixed note: under it the runtime warn cannot fire
(peer trusted) and the widened Secure leg is the compensation. The runtime
warn message is unchanged (it fires only on the untrusted-peer signature,
where the remedies it names remain valid).
## F-2 — the six response-gating session saves were unbounded (LOW, resilience)
The six `req.session.save(callback)` calls that gate login/captcha responses
lacked the 5s `withTimeout` discipline every other store write on this surface
has (the login binder's save, `utils/login-session-bind.js`; the restore
lookups). A stalled Redis client would wedge the request indefinitely — the
limiter already hangs first on the same client, and the 300s requestTimeout
backstop is too coarse.
- All six are now wrapped as `withTimeout(<save promise>, 5000, <label>)`
(`adpanel:response-save-bounded`): respond after the save settles OR 5s,
whichever first. Labels: `login-sendError-save` (sendError's render path),
`login-captcha-challenge-json-save` + `login-captcha-challenge-render-save`
(sendCaptchaChallenge), `captcha-verify-unlock-save`,
`captcha-verify-no-pending-save`, `captcha-verify-finalize-save`
(POST /api/captcha/verify).
- Response bodies/statuses unchanged and shipped exactly once — on settle,
on save error (the pre-fix error-ignored posture is preserved), and on
timeout (the rejection is swallowed BEFORE the response ships, so a timeout
still ships the ORIGINAL response, never a 500; `.catch` sits before
`.then`, pinned). A dropped rotated CSRF token self-heals via the
documented next-request re-403.
- Late-write safety verified against the tombstone-guarded store wrapper
(`wrapSessionStoreWithTombstoneGuard`): withTimeout leaves the underlying
save running, but the write was already dispatched — ordering of store
writes is unchanged. A late completion writing after the response is
harmless (same sid; confirmed-revocation skips refuse set()/touch() and
re-destroy, so no resurrection), and the six records are independent
single-session field writes — none participates in the binder's
tombstone→regenerate→save choreography.
### Verification
- `node --check index.js` clean; `go vet ./...` clean.
- Targeted: `tests/cookie-secure-trusted-proto.test.js` (new, 14/14 — the
real function + real peer-trust helper chain under vm: TRUSTED_PROXY_IPS
https → Secure, untrusted-peer XFP → false, loopback → true, last-hop-wins,
both explicit-env directions, consumer census) and
`tests/response-save-bounded.test.js` (new, 10/10 — real withTimeout + real
bounded save block under vm with fake timers: never-settling save ships the
original response at the 5s bound, settle-first, no double-respond on late
settle, save-error and sync-throw postures), plus the login/CSP/
staleness/parity/wire/tombstone/secure-pin/csrf/trusted-proxy suites green
(231/231 across the affected files). `tests/secure-pin-durable.test.js`
gained a conscious sandbox update — its vm extraction of
cookieSecureForRequest now injects the real peer-trust helper chain the
widened leg calls (behavioral flows unchanged: they ride req.secure or no
https claim).
- Full `npm test` green (3658 pass / 0 fail — the 3634 baseline + the 24 new
tests; no conscious pin updates beyond the secure-pin-durable sandbox noted
above).
## Audit round 2026-11-16 — authentication completion-window & credential-generation hardening
Five verified findings from a read-only authentication review, fixed through one
shared contract (`adpanel:credential-generation`): a proof verified before a
credential change must never be promoted onto the new credential generation.
The small error-path fixes landed first (AR-3, AR-4, AR-5), then findings 1+2
together through the shared contract (AR-1, AR-2) plus its enforcement side.
Every new shared mechanism lives in a DI module (`utils/session-epoch.js`,
`utils/session-account-binding.js`'s `credentialGenerationMismatch`,
`services/admin-2fa-reset.js`); index.js carries only fix-shaped edits at
existing call sites. Full-suite evidence at round end: 3861 tests, 3851 pass,
0 campaign failures (the single failure, `config-stat-revalidation-consumers`
"shared cache end-to-end", is a PRE-EXISTING mtime-granularity flake in a
stat-keyed cache test — it fails under suite load and INTERMITTENTLY in
isolation (one standalone session passed 3 of 3 whole-file runs, another
failed 2 of 2 — same machine; the file contains 19 tests and both cache-write
payloads are exactly 62 bytes, so mtime is the only cache signal), and it
fails identically in the pre-round baseline; it is unrelated
to authentication).
### AR-1 — login completion could promote a pre-change proof onto a rotated credential (login-proof-generation) (High — session takeover)
The shared login binder's regenerate→save window was unvalidated on both
completion paths. On `POST /login` the final credential check re-proved the
PASSWORD only (the MFA decision ran against the pre-reread snapshot:
`index.js` `userHasTwoFactor`/TOTP consumption), and NOTHING re-read the row
between the re-proof and the binder's asynchronous regenerate/mint/save — a
password reset + epoch bump + session sweep committing inside that window
could not see the unbound regenerated sid, so the login persisted a session
minted against a stale credential generation. `completePendingCaptchaLogin`
already re-proved the password+secret fingerprint but recorded no generation
and re-checked nothing after its row read either.
Remediation:
- Pending captcha records carry `accountEpoch` at mint
(`adpanel:login-proof-generation`); NaN→null store round-trips are guarded
(`!= null && Number.isFinite(...)` BEFORE any coercion) so an uncomparable
record is never read as epoch 0 — the fingerprint leg stays the sole
authority for it.
- `POST /login` gains an MFA-staleness gate after the re-proof, before bind:
enabled-state transition, secret-byte change, or `totpSealedError` flip
between the snapshot and the re-read row deny via the uniform
`failCredentials("arm:stale-mfa")` path (no wire disclosure of which leg
drifted; totpSealedError is never read as "MFA disabled").
- BOTH completions validate in the binder's `beforeSave` hook on a FRESH read
(never cached `req.currentUser`): row exists/unsuspended, generation
comparable-and-equal via the shared `credentialGenerationMismatch`,
MFA state/seed bytes unchanged, hash bytes unchanged — the password path
re-proves the submitted password ONCE under the admission semaphore when
only the hash moved (benign concurrent rehash stays admitted); the captcha
path denies fail-closed (no submitted password to re-prove).
- Only the labeled `arm:stale-completion` error converts (uniform 400 on the
login path, the existing 401 `login-expired` envelope on the captcha path);
the shared binder's catch has already revoked the just-minted remember
credential and tombstoned the regenerated sid before the error reaches the
route.
Verification:
- `tests/login-staleness-reproof.test.js` (rewritten harness, REAL binder +
barrier-instrumented regenerate/save): MFA-enabled-between-reads, seed
rotation after the TOTP proof, sealedError transition, benign rehash inside
every window, and reset+epoch-bump+sweep inside the window all deny with
full hygiene. `tests/captcha-completion-staleness.test.js` (new): the same
matrix for the captcha path. `tests/adversarial-auth-race-matrix.test.js`
(new, 17 scenarios) proves the sub-window variant end-to-end: when the
beforeSave read lands before a concurrent commit and the save lands after,
the persisted stale-bound record authenticates for ZERO requests — the
account-binding middleware tears it down on its next request (401,
tombstone, lineage revoke, cookie clears). `tests/login-uniform-failure.test.js`
pins exactly 10 `failCredentials` arms including the two new ones.
### AR-2 — credential writers now bump the generation in the SAME statement (credential-generation) (High — session revocation)
`users.session_epoch` existed (CLI bump + boot-ensured column) but NO
interactive credential writer touched it: sessions were invalidated only by
the event-driven eviction sweeps, and the binding middleware's epoch leg had
nothing to compare against for panel-side changes — the race window AR-1
closes needed the durable backstop.
Remediation:
- `utils/session-epoch.js` (`adpanel:credential-generation`) is the ONE
generator: `crypto.randomInt(1, 2147483647)` (the established convention),
`newSessionEpochDifferentFrom` bounded-retry so a bump never lands on the
row's present generation. Consolidates the CLI's local copy and the panel
INSERT's inline value.
- All six interactive credential writers fold `session_epoch = ?` into their
EXISTING statement — never a second UPDATE: 2FA confirm (CAS
`secret <=> ?`), both self-service password changes (CAS on the snapshot
hash), email change (CAS on password + old email), admin password reset
(id-keyed, deliberately CAS-less — documented accepted last-writer shape),
admin 2FA reset (`services/admin-2fa-reset.js`). The epoch is generated
immediately before each statement and discarded on CAS loss.
- The four interactive rebind payloads thread the NEW epoch (the rebinder
binds `accountEpoch` from the passed payload — without threading, the owner
would self-lockout on their next request). Recovery-code burns, the TOTP
counter claim, the login bcrypt rehash and all non-credential writes stay
epoch-free (pinned exhaustively by `tests/credential-change-atomic-guard.test.js`
and `scripts/verify-user-lifecycle-session-revocation.js` layer E).
- Enforcement side: restore's staleness re-verify gains the comparable-only
epoch leg and binds the FRESH row; Socket.IO liveness re-proves the
record-vs-row binding every 30s tick (`adpanel:socket-liveness-binding` —
mismatch disconnects; store read errors keep the fail-open posture); the
SSH gate already enforced the binding on its 60s sweep (unchanged).
Verification:
- `tests/credential-change-atomic-guard.test.js` pins all CAS shapes with
in-statement epochs, zero epoch-only UPDATEs, loser-persists-nothing, and
rebind-payload == statement epoch. `utils/session-epoch.test.js` pins
range/CSPRNG/distinct-from. `scripts/verify-user-lifecycle-session-revocation.js`
18/18 (layer E: the six epoch-carrying shapes + nine epoch-free
non-credential writers + shared-generator wiring). Known limitation:
layer E enumerates only index.js / scripts/create-user.js /
services/admin-2fa-reset.js — a writer added in another file is outside
its quote-anchored counts.
- Cross-worker: `tests/cross-worker-credential-race.test.js` (new, env-gated
on `ADPANEL_TEST_MYSQL_URL`, skips cleanly without it) ran against a real
shared MariaDB with two simulated workers: CAS-loser commits nothing, 12
concurrent CAS rounds have exactly one winner, epochs never repeat,
`claimRecoveryCode`'s full-array CAS stays single-use cross-worker, and the
revocation-queue claim DELETE is exactly-once. The Redis tombstone
cross-process leg ships as the same file's gated skip (no local daemon).
### AR-3 — a failed remember-restore left the request AUTHENTICATED (restore-failure-deauthorization) (High — authz)
`restoreRememberedLogin` binds `req.session.user/accountId/accountEpoch/
browserSessionAudit` and caches `req.currentUser` BEFORE its bounded save.
The remember middleware's catch cleaned the store (registry lineage revoke,
sid tombstone) but never touched the live request object — every downstream
gate in the SAME request (`getLoggedInUser`'s `req.currentUser` fast path,
the account-binding middleware, `req.isAdmin`) resolved authority off exactly
that object, so a restore that failed after binding answered as the
authenticated account. The pre-campaign catch also carried two unguarded
awaits (a rejection there escaped into Express).
Remediation:
- ONE teardown, `teardownFailedRememberRestore`
(`adpanel:restore-failure-deauthorization`), delegated from the catch:
(1) capture targeting (sid, remember id, lineage, email, account id) before
clearing; (2) clear request-local authority SYNCHRONOUSLY before any await
— session identity keys, protected pending-captcha state, `req.currentUser`,
cached `req.isAdmin`; (3) then the awaited cleanup with each step
individually guarded: lineage-scoped registry revoke from the CAPTURED
hints (re-reading the cleared session would lose targeting), sid tombstone
warn-on-false, bounded destroy strictly tombstone-before-destroy, then the
active-session cache hygiene every other sid-destroying path applies. The
caller keeps its non-rethrow posture and continues to `next()`
unauthenticated.
- `clearRememberLoginSessionState` is untouched (still deletes only the two
freshness stamps — successful restores and the authenticated silent refresh
call it).
Verification:
- `tests/remember-restore-and-confirmed-bounds.test.js`: save-rejection,
save-timeout and cleanup-rejection variants all deauthorize downstream
(`isAuthenticated`/`isAdmin` false, identity keys gone) while RETAINING the
revocation/tombstone/cookie assertions; the late-save store-guard refusal
and the success-path (bind + marks, no revocation) are pinned; the REAL
helper runs in the vm (no no-op stub). `tests/remember-rotation-bounded.test.js`
updated to pin the delegation.
### AR-4 — the admin 2FA-reset routes hung on DB rejection (admin-2fa-reset-preflight) (Medium — resilience)
`handleAdmin2faReset` ran five awaits (admin gate, action token, target
lookup, acting-admin lookup, destructive step-up) before its `try`, and both
route registrations used expression-bodied arrows whose returned promise
Express 4 ignores — any transient rejection hung the request unanswered.
The repo's one terminal error middleware never sees ignored rejections.
Remediation:
- The ONE handler moved to `services/admin-2fa-reset.js`
(`adpanel:admin-2fa-reset-preflight`), dependency-injected with fail-closed
construction-time dep validation; the ENTIRE awaited pipeline sits inside
one guard try whose catch logs its own bracketed marker and answers the
headersSent-guarded 500 (ending an already-answered response exactly once).
HARD CONTRACT: the exported handler never rejects — this is what makes the
thin adapters safe.
- index.js keeps only the two thin adapters with their own action-token
scopes, proofLabels, logSuffixes and limiter; gate ladder, the
epoch-carrying secret-clearing UPDATE, evictions, audit and the success
body are byte-identical to the pre-round handler (the write-path 500 body
changed "Failed to reset 2FA" → "internal error" per the unified catch;
every frontend consumer carries its own fallback string).
Verification:
- `tests/admin-2fa-reset-preflight.test.js` (new): REAL rejecting deps on
both aliases → completed 500, no unhandled rejection, zero db writes on
pre-write failures, headersSent path pinned. `tests/audit-l1-l2-l4-l6-hardening.test.js`
L6 follows the extraction (handler exactly once in the module, epoch-carrying
UPDATE exactly once, ordered sequence). `tests/preflight-guard-sweep.test.js`
pins both aliases in a delegated-routes table (the scanner cannot see
expression-bodied adapters) plus the module's bound-pipeline shape.
### AR-5 — recovery-code regeneration dropped to one factor on code exhaustion (recovery-regen-requires-second-factor) (High — credential minting)
The regen route's "degenerate legacy state" branch authorized password-only
minting when the stored array was empty (`existingCodes.length === 0` →
`method = "password"`, step 1 answering `requires: "none"`), and legitimately
consuming the LAST code reaches the same empty array — so a healthy
two-factor account with exhausted codes minted 7 fresh codes from the
password alone.
Remediation (policy: empty inventory is INVENTORY, not AUTHORIZATION):
- Step 1 answers `{ ok: true, requires: "totp" }` unconditionally; step 2's
second-factor resolution is strictly explicit-TOTP (consume-on-success) →
live recovery grant (atomic CAS burn) → 403 `2fa-required`. The
password-only branch and its SECURITY log are gone.
- Preserved: the password-first stamp (issuance, 5-minute expiry, identity +
password-fingerprint binding, password-stale invalidation), the
500-on-DB-error/malformed distinction (never readable as "zero codes"),
`claimRecoveryCode` itself (byte-identical; all four callers intact), the
single-use stamp delete, limiter pairing, response bodies.
- `public/js/dashboard.js`'s `requires === 'none'` auto-complete branch is
removed; the modal always advances to the TOTP step. Locked-out legacy
accounts keep the sanctioned terminal paths: the admin reset route (which
refuses admin targets) and the sudo-gated `scripts/reset-recovery-codes.js`.
Known UX parity note: the server still accepts a live recovery grant at
step 2, but the current modal hard-requires a typed TOTP — a user with
remaining codes but no working authenticator reaches the regen modal's
second factor via re-enrollment/password flows instead (no security
impact; flagged for a follow-up UX pass).
Verification:
- `tests/regen-recovery-two-step.test.js` 28/28: the exhaustion scenario
burns the LAST code through the REAL `claimRecoveryCode` (vm-extracted
verbatim, not stubbed) and asserts 403 `2fa-required` with ZERO mint
writes; TOTP and grant paths mint with the stamp consumed; missing/expired/
foreign stamps and stale fingerprints fail closed; DB error and malformed
array answer 500. Repo-wide grep: no length-based authorization remains.
### AR-6 — pre-existing, NOT fixed in this round: GET /ssh-terminal can hang on a DB rejection (proxySshTerminalIndex) (Medium — availability)
`proxySshTerminalIndex` (index.js, registered bare at the `/ssh-terminal`
route) awaits DB-backed gates (`isAuthenticated` → `getLoggedInUser`;
`hasAgentAccess` → admin/lookup) outside any try, registered as a named
function reference — the same Express-4 hang class AR-4 fixes, and invisible
to `scripts/find-unguarded-awaited-routes.js` (its analyzer only matches
inline block-bodied arrow handlers, so a named-function registration is a
scanner blind spot; the sweep reports 0 hits). Byte-identical to the
pre-round source — deliberately out of scope here. Remediation shape when
taken: wrap the two gate awaits in the same pre-flight try /
headersSent-guarded-500 posture as AR-4 (or a thin adapter over a guarded
handler) and extend the sweep table to named-function registrations.
### Verification
- Full suite at round end: `node --test utils tests` → 3861 tests, 3851 pass,
0 campaign failures, 9 skipped (7 = the env-gated cross-worker file without
infrastructure, 2 pre-existing skips). The single failure is the
pre-existing `config-stat-revalidation-consumers` mtime-granularity flake
(fails under suite load and intermittently in isolation; fails identically
in the pre-round baseline — unrelated to authentication).
- Environment-integrity fix landed with this round: the `npm test` script's
QUOTED globs ran ZERO tests on Node < 21 (`node --test "utils/*.test.js" ...`
→ "Could not find …" and exit 1, fail-fast), so on this machine's Node 20
`npm test` reported "Test failed" without executing a single test — the
green gate was unsatisfiable via npm there. The script now uses unquoted
globs the shell expands (`node --test utils/*.test.js tests/*.test.js`), so
the declared test command runs the suite under any POSIX shell on every
Node version, and everywhere on Node ≥ 21 (Windows cmd + Node < 21 remains
the one gap; the repo's other npm scripts are already POSIX-only). Chosen
over the shell-independent directory-args form (`node --test utils tests`)
on failure-mode grounds: a vanishing test set fails LOUD (exit 1) under the
glob form but is a silent green `# tests 0` under directory args — which
would recreate the vacuous-gate hazard this fix removes.
- Reconciliation: after the round-end evidence above was captured, three more
`credentialGenerationMismatch` pin tests were added to
`utils/session-account-binding.test.js` (3861 → 3864 tests, 3851 → 3854
pass); the post-fix full run is `npm test` → 3864 tests, 3854 pass, 9
skipped, the same single pre-existing flake failure.
- `node scripts/verify-user-lifecycle-session-revocation.js` 18/18;
`node scripts/find-unguarded-awaited-routes.js index.js nodes.js` → 0
findings for inline handlers (AR-6 documents the named-function blind
spot); `node --check` clean on every touched file.
- Environment gap: no Go toolchain on the round machine — `go test .` (root
suite) must run on a Go-capable host before deploy. No Go file was touched
(verified byte-identical: main.go, cmd/sshterm; no Go test references the
users table or session_epoch).
- Deploy notes: code-only round (no schema/data migration; rollback = revert
code). Existing sessions without `accountEpoch` keep the documented legacy
posture (revocation-sweep-covered) — a deployment-wide sign-out remains an
explicit deploy decision and is NOT implemented.