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

62 KiB

Deep Security Review Continuation Handoff

Updated: 2026-11-19. Workspace: /ADPanel/ADPanel-Enterprise.

Mission and Scope

Continue the code review beyond the completed login and shared-middleware passes. Read the complete controlling implementations and follow their callers, state changes, failure paths, and asynchronous boundaries. Do not stop at a template, route registration, helper name, source assertion, or dependency advisory. Those are starting points, not proof of protection or exploitation.

The user wants professional security and bug review without forced findings. Investigate read-only first. Repair a confirmed, consequential defect carefully; leave harmless presentation and speculative hardening issues alone. Do not claim that no vulnerability exists or that the entire repository has been audited. This handoff does not authorize production testing, configuration changes, or deployment. Do not launch another agent merely because this document mentions one; this is work for the receiving agent to perform.

Read First

  1. AGENTS.md: shared responsibilities, frozen monoliths, tests, dependency direction, and security-fix conventions.
  2. SECURITY-FIXES.md: the current expanded-review and login-review sections. Earlier dated entries are historical records.
  3. ACCOUNTS-SETTINGS-SECURITY-HANDOFF.md: existing actor/target/generation and Accounts repairs. Do not count them again.
  4. The current owning code and nearby tests for the first investigation you select. Current source wins over stale snippets and old line numbers.

The November 8 brief retained at the end of this document is ARCHIVED. Its findings and implementation requests are not a new task. Re-locate symbols; never apply its old patches or follow its old line references blindly.

Current Worktree and Verification

  • The worktree is heavily modified, and many working modules and tests are untracked. Preserve all existing changes. Do not reset, revert, stage, commit, or create a branch. Ordinary git diff does not show untracked files.
  • Do not require the application entry point in a test. Loading index.js boots services and can mutate state. Existing tests use extracted real functions, injected dependencies, and isolated local servers.
  • Last final full gate: npm test, 4,188 tests total, 4,179 passed, 9 skipped, zero failures. Last focused repair run: 158 passed, zero skipped or failures. These are historical results, not verification of the receiving agent's edits.
  • Syntax, editor diagnostics, and whitespace checks passed for the repaired files. Skipped tests are not integration evidence. Redis/MySQL race harnesses are not a certification of production InnoDB scheduling or worker versions.
  • The latest passes could not find Go on PATH or in the standard install locations. The Accounts handoff records an earlier run using a cached Go 1.26.9 executable with GOTOOLCHAIN=local. Check existing toolchain caches before concluding Go is unavailable; do not install or change it casually.
  • No production accounts, backing services, or deployment options were changed. Panel workers have NOT been reloaded by these reviews.

2026-11-19 Reinstall Admission and Metadata Follow-Up

The current request remains the entire reinstall feature behind views/bot.ejs, with security and functional bug review and no forced findings. This pass read the complete scene/controller, both complete panel rebuild callers/shared helpers and the complete daemon rebuild, then followed their controlling auth, retry, runtime, storage and recovery paths. Historical repairs were preserved and not counted again.

Two new consequential defects were reproduced and fixed:

  • Unreadable/missing/invalid daemon metadata allowed the wipe and could lose saved policy. Extract the existing loader once into server_policy.go, expose its checked mode to reinstall before container removal, and refuse uncertain metadata or failed migration without deleting files. Valid legacy migration and post-preflight save-error coverage remain intact.
  • Access revocation or admin demotion while step-up was pending still let both real extracted handlers dispatch. Share fresh actor/SID/access/permission admission and dispatch in utils/server-reinstall.js, reusing credential fingerprint/generation checks. Repeat admission for signing retries and optional unknown-field resends; cover local template changes too. Do not block authoritative panel commits for a rebuild already completed on the node merely because the actor lost access after dispatch.

Final npm test: 4,253 total, 4,244 passed, 9 skipped, zero failures. Touched panel/controller suites: 65/65 passed. Full root daemon go test . passed with cached Go 1.26.9. New regressions failed before repair and passed afterward; syntax, editor diagnostics, Go formatting, explicit async-route scanning and preserved-session whitespace checks passed. Details and coverage are in the new top section of SECURITY-FIXES.md.

No live reinstall, launch, reload, deployment or account/service configuration change occurred. Ship the panel caller/helper together and rebuild the full daemon package with the metadata module. Existing work remains preserved. This is not proof of zero vulnerabilities or a whole-repository audit. Live engine/providers/TLS/proxy/SQL/Redis and mixed-version rollout remain unverified. Fresh actor checks protect pre-dispatch admission, not work already sent or an atomic transaction across every account/access writer. Process-local port exclusion, non-transactional wipes and existing container-mediated quota limits remain; uncertain results need inspection before retrying.

2026-11-19 Reinstall Installer and Port-Admission Follow-Up

The latest scope remains the entire reinstall feature behind views/bot.ejs, not unrelated scenes. This pass read the complete scene/controller, both panel rebuild callers and daemon handler/helpers, then followed their authorization, runtime, retry, storage, concurrency and recovery boundaries. Three new consequential functional bugs were reproduced and fixed:

  • Installer failure after the wipe left rebuilt metadata uncommitted and the panel on its old port/template. Persist before installation and classify the explicit persisted failure once for both panel callers; keep the response a failure and never automatically retry the wipe.
  • Valid tagged Docker Hub installer shorthand was rejected by the daemon's registry parser. Extract the one existing image policy into template_image_policy.go and match the panel's slash-aware rule without widening the explicit registry allowlist.
  • A missing stored port could use an occupied template default without a free allocation. Reuse the existing ownership/liveness guard for that unclaimed default, then allocate another free port or refuse before deletion.

Final npm test passed: 4,245 total, 4,236 passed, 9 skipped, zero failures. Full daemon go test . passed with cached Go 1.26.9, as did focused route, installer, image, metadata and competing-operation checks. Syntax/EJS, editor diagnostics, scoped Go formatting and explicit route scanning passed. Details, prerequisites and coverage are in the new top section of SECURITY-FIXES.md. Historical findings were not recounted.

No live reinstall, launch, deployment/reload or production configuration change was performed. Deliver the panel caller/helper together and rebuild the whole root Go package with the extracted image policy. Existing work was preserved. No new scene injection, auth bypass or host escape was demonstrated; do not call the feature vulnerability-free. Live engine/providers/proxy/SQL/Redis and mixed-version behavior remain unverified, and existing process-local port locking, non-transactional wipes and container-mediated quota limits remain.

2026-11-19 Reinstall Failure and Recovery Follow-Up

Latest scope remains the complete reinstall feature, starting at its scene in views/bot.ejs, not other scenes or another login audit. The pass read complete scene/controller and panel/daemon rebuild bodies, then followed their authorization, retry, runtime, storage, failure, concurrency and recovery boundaries. Three NEW consequential bugs were reproduced and fixed:

  • Same-template Minecraft reinstall dropped the recorded fork/version and always selected Paper 1.21.8. Preserve recorded selection in reinstall.go, reusing strict validators before the wipe; missing legacy values and genuine template changes keep existing defaults.
  • Confirmed node rebuilds followed by startup, image-preparation or Minecraft resolution/download/quota failure left the old panel port/template. Both callers now share explicit persisted-rebuild classification in utils/server-reinstall.js, commit confirmed new configuration but return failure, and never automatically retry a wipe.
  • Export could snapshot a tree while the daemon reinstall lock was held, including after loss of the panel claim during restart recovery. The single export handler now lives in server-export.go and takes the existing fail-fast operation lock for its entire snapshot. Existing tar/no-follow security assertions remain intact.

Final full gates: npm test 4,240 total / 4,231 passed / 9 skipped / zero failures; full go test . passed with cached Go 1.26.9. Final focused panel rebuild/controller suites passed 52/52; daemon reinstall/export and owning-disk quota controls passed. Syntax/EJS, formatting, diagnostics, session-only diff and whitespace passed; explicitly invoked route scanner reports zero unguarded awaits. Detailed evidence, coverage and prerequisites are in the new top section of SECURITY-FIXES.md.

Existing dirty/untracked work was preserved. No live reinstall, service launch, deployment/reload, account or infrastructure change occurred. Deliver the panel caller/helper together and rebuild the full node package with both extracted Go modules. Do not describe this as vulnerability-free: live engine/provider, proxy/TLS, SQL/Redis and mixed-version behavior remain unverified. Existing process-local port exclusion, lack of automatic data rollback and lack of newly added hard filesystem quotas remain limits. Unknown/legacy partial outcomes and failed metadata/index persistence require inspection before retry. Historical notes on unconditional Paper 1.21.8 no longer describe recorded same-template Minecraft selections after this fix.

2026-11-19 Reinstall Port-Integrity Follow-Up

The latest request remains the entire reinstall feature, security and bug review, not just its template. The current pass re-read the scene/controller, both panel callers and daemon rebuild bodies, and followed their controlling authorization, runtime, storage, compatibility, concurrency, failure and recovery paths. Earlier complete-flow work below was preserved rather than re-counted as new findings.

Three new consequential defects were reproduced and fixed:

  • Missing/malformed stored ports bypassed the user reinstall allocation gate. Both callers now share strict checked port resolution and persist the sent port.
  • Legacy unknown-field retries could silently remove hostPort, desynchronizing the panel record from the rebuilt node. The shared protocol policy refuses it.
  • Concurrent reinstalls of different servers could select the same free port. Both callers now use the existing node-port mutex through commit, freshly load the node, and refuse competing reinstall admission immediately instead of queueing a stale destructive action.

Final gates: npm test 4,236 total / 4,227 passed / 9 skipped / zero failures; full go test . passed with cached Go 1.26.9 and GOTOOLCHAIN=local. The final focused source/behavior set passed 202; reinstall/shared-lock checks passed 58; earlier authorization/cleanup integration checks passed 277. Syntax, editor and scoped whitespace checks passed; the async scanner stays at zero. An exact shared import source pin was consciously updated for the protocol extraction before the passing full rerun. No protection assertion was removed.

Details and prerequisites are in the new top section of SECURITY-FIXES.md. No live reinstall/deployment/reload or production configuration change occurred. This pass changes panel modules only; deliver the caller with utils/server-reinstall.js, utils/daemon-protocol.js and utils/keyed-async-lock.js. Existing dirty/untracked work was preserved.

The node-port lock is process-local, matching the current one-worker config, not a distributed reservation; cross-worker and external port-consumer races remain outside its guarantee. Live Docker/provider/TLS/SQL/Redis behavior and mixed-worker delivery remain unverified. Post-wipe failures still have no data rollback. Do not call the feature vulnerability-free, re-count historical repairs, or extend this task to unrelated scenes. The existing Minecraft version and hard filesystem-quota limits remain documented below.

2026-11-19 Reinstall Complete-Flow Follow-Up

The latest request is the entire reinstall feature, not a new login or outbound audit. The current pass read its complete scene/controller, both panel rebuild callers and daemon handler/helpers, then followed the authorization, retry, runtime, storage, metadata, EULA, concurrency and recovery paths. The new scoped coverage ledger is at the top of SECURITY-FIXES.md.

Five NEW reproduced defects were fixed; do not re-count historical repairs:

  • Minecraft reinstall dropped explicit TCP/UDP policy; retain portProtocols.
  • Cross-template reinstall lost runtime-only private bindings; share effective interface resolution through server_policy.go.
  • Both panel callers could wipe a stale template/node after step-up; a shared post-claim canonical-row check refuses changed targets before daemon contact.
  • A stale orphan sweep could clear a fresh reinstall; repeat the age condition in the SQL UPDATE and fail closed if that schema evidence is unavailable.
  • Managed legacy reinstalls with absent image/tag metadata pulled <nil>:<nil> after wiping; share existing defaults and validate them before deletion.

Final full gates passed: npm test 4,225 total, 4,216 passed, 9 skipped, zero failures; full go test . passed with cached Go 1.26.9 and GOTOOLCHAIN=local. Focused panel/controller/ownership checks passed 89/89, daemon reinstall/binding/EULA checks passed, as did syntax/EJS, diagnostics, formatting and whitespace checks. The async-await scanner remains at zero; its required outer cleanup catch was retained. An unchanged unrelated asset-download temp-cleanup assertion failed in an intermediate full run, passed 8/8 in isolation, and the unchanged full rerun passed.

No production reinstall, service launch/reload, deployment or account/settings change occurred. Deliver the panel modules/caller and rebuilt daemon with both Go policy modules. Existing worktree modifications were preserved. Legacy DB schemas without servers.updated_at now require verified operator recovery instead of unsafe automatic flag clearing. Live engine/provider/TLS/DB/Redis and mixed-worker behavior remain unverified; post-wipe failures still have no automatic rollback. Do not describe this as vulnerability-free or a whole-repo audit. Stock Paper 1.21.8 and container-mediated hard-quota limits remain as documented below.

2026-11-18 Reinstall Deep Review Continuation

The latest request is the entire server-reinstall feature, starting at the reinstall scene in views/bot.ejs. This continuation did not restart the earlier login audit or count its repairs again. It read the reinstall scene/controller and both panel callers, then traced daemon auth, runtime merging, preflight, destructive reset, installer/scaffold/download, metadata commit, container startup, EULA and competing operations. The detailed coverage ledger and new findings are in the corresponding section of SECURITY-FIXES.md.

New confirmed fixes: preserve private bind/read-only policy; make DB claims exclusive under mysql2 FOUND_ROWS; refuse resource/EULA writes during reinstall; retain authoritative quota/disk metadata and bound the replacement jar; validate inherited effective runtime before the wipe; prevent cross-template runtime inheritance; preserve installer-produced entrypoints; require explicit UI success; restore legacy signing fallback when rotation is unavailable. Each confirmed failure was reproduced before its controlling fix.

The final required full gates passed: npm test reported 4,220 total, 4,211 passed, 9 skipped, zero failures; full go test . passed with temporary official Go 1.26.9 at /tmp/adpanel-reinstall-review/go/bin/go. The controller/route set passed 19/19 and the final daemon reinstall/EULA slice passed. JavaScript/EJS syntax, editor diagnostics, focused Go formatting and session-only whitespace checks passed. One preceding full Node run hit an unrelated one-millisecond preauth-session assertion; the unchanged test passed 7/7 and the unchanged full rerun passed. Pre-existing whitespace outside the template's script URL was left untouched. See the security ledger for the full verification record.

No live server was reinstalled, no backing-service settings were changed, and no workers were reloaded. Delivery requires the updated panel files plus a daemon rebuild including reinstall.go and server_policy.go. Old worktree changes were preserved; the accidental extraction patch damage was restored from the exact initial Copilot edit checkpoint and checked against it, not reset to HEAD.

Limits remain: post-wipe failures are non-transactional; stock Minecraft still uses Paper 1.21.8; container-mediated installer writes do not have a hard filesystem quota added by this patch; live TLS/Docker/provider behavior, production SQL/Redis scheduling and mixed-worker rollout were not exercised. Do not call the feature vulnerability-free or this an entire-repository audit.

2026-11-18 Auth and Reinstall Completion Follow-Up

The latest user request included both the reinstall scene and the complete login flow. This pass read their controlling implementations and failure/async paths; the older reinstall-only scope note does not apply to this pass. Detailed coverage, prerequisites, evidence and residual limits are in the new follow-up section of SECURITY-FIXES.md.

New repairs only (do not report the earlier repaired defects as new):

  • Remember restore's successful-save path now freshly verifies the proved account and SID before authorizing the same downstream request, through utils/remember-login-completion.js. A credential reset during save previously retained the cached pre-reset currentUser; the real protected-route regression now denies it and invokes existing request/store/registry teardown. This is an in-flight-request race requiring a valid remembered credential, not a durable new-generation bypass.
  • Both panel reinstall callers use the checked canonical-row commit and guarded release in utils/server-reinstall.js. Failed saves and missing rows report partial completion; alias requests update the resolved row; cleanup failure cannot resend an already-completed response.
  • Both daemon rebuild branches require authoritative metadata persistence via reinstall.go before image preparation/container start. The real handler's failed-metadata fixture previously returned 200; it now returns 500.

All pre-existing changes were retained. Tests used extracted real handlers, the actual binders/predicates and shared modules, controlled promise barriers and temporary daemon storage with stubbed Docker, without requiring the panel entry point or changing production accounts/backing services.

Final verification for this follow-up, superseding historical gate counts only:

  • Full npm test: 4,216 tests total, 4,207 passed, 9 skipped, zero failures.
  • Full daemon go test .: passed with cached Go 1.26.9 and GOTOOLCHAIN=local; no system toolchain installation was needed.
  • Focused reinstall/caller/ownership set: 106 passed, zero skipped/failures. The added auth authority/audit controls passed too.
  • The unchanged async-handler scanner reports zero unguarded awaits. Syntax, editor diagnostics, scoped Go formatting and tracked/untracked whitespace checks passed. Source pins follow the moved code; their protected invariants were retained, not removed.

Delivery requires the new panel module alongside its caller and the rebuilt daemon Go module, then an all-worker panel reload. No deployment, update-trust allowlist change, service reload or live reinstall was performed. Live TLS, Docker/providers, SQL scheduling, Redis persistence and mixed-worker rollout remain unverified. The fixed Paper 1.21.8 stock reinstall choice was observed but not changed without an established preservation contract; post-wipe failures remain non-transactional and have no automatic data rollback.

2026-11-18 Outbound Continuation Results

The receiving pass followed priority 1 below, reproduced consequential failures in the real controlling implementations, and repaired them in the working tree. Historical repairs above/below are preserved. Detailed prerequisites, evidence, compatibility, and coverage are in the new outbound continuation section of SECURITY-FIXES.md.

ID Severity NEW Finding Current Home / Status
O01 Medium, availability Transfer request errors escape after headers; failed imports do not cancel their exports Fixed in services/node-http.js and services/server-transfer-stream.js
O02 Medium, availability Remote timeout excludes DNS and redirect/body lifetime; late request failures leave consumers waiting Fixed in utils/remote-http.js, utils/remote-url-guard.js, and the shared JSON client
O03 Medium, availability Bare or pre-handoff upload-source close leaves both upload relays pending Fixed through utils/stream-lifecycle.js on both surfaces

These are not new password/MFA bypasses or SSRF-policy bypasses. O01 requires an authorized admin transfer plus a failed/misbehaving node exchange. O02 requires a reachable fetch initiated by an authorized caller or a configured upstream that misbehaves. O03 follows source cancellation/transport failure on an authorized upload. Existing auth, quotas, response vocabulary, IP pinning and HTTPS/integrity policy remain intact.

Verification for THIS pass, superseding historical gate counts only:

  • Focused outbound checks: 211 passed, zero skipped/failures.
  • Full npm test: 4204 tests, 4195 passed, 9 skipped, zero failures.
  • go test .: passed with cached Go 1.26.9 at /home/antonn/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.26.9.linux-amd64/bin/go and GOTOOLCHAIN=local. Go is absent from PATH, not unavailable.
  • Syntax and editor checks passed. Final whitespace checks include untracked files, which ordinary git diff omits.

The focused matrix covers delayed DNS/no late dial, redirect budget reuse, slow-drip bodies, post-header request failure, premature response/source close, paused consumers, byte/HTTPS guards, native loopback HTTP sockets, transfer success/failure/rollback contracts, and real getter-to-store temp cleanup with admission-slot reuse. Complete relevant functions read include the old/new getters and transfer pump, both uploaders, shared/distinct JSON clients, remote URL guard, store apply consumers, and the transfer job route. No application entry point was required or panel service launched for the new regressions. All pre-existing worktree changes were retained.

Deployment/compatibility: ship the new remote and transfer modules alongside their callers, then reload all panel workers. No reload or deployment was performed. The same numeric timeouts now impose total budgets; a previously slow but steadily progressing remote download/transfer can be refused. The daemon's intentional progress-based upload idle policy is unchanged. A native dns.lookup can continue inside the resolver after caller expiry, but cannot start a late dial. Live TLS, DB transport/scheduling, Redis persistence and cross-worker rollout remain operator verification requirements; skipped integration checks are not certification.

Continue From Here

Priority 1 is materially advanced, NOT closed for every outbound path: read uploadFileToNode setup/form cleanup in utils/server-asset-apply.js, direct/relay upload deadline policy, and callNodeApiOnce failure teardown next. Its hard timer already covers connect-time DNS; do not report that as the external-validation gap again. Probe refused setup before source listeners, late response after expiry, response close without end, and early success/failure bodies using normal controls and bounded fixtures. The Go upload receiving path was inspected for cancellation cleanup, not fully audited for tenant/quota races.

Then follow priorities 2-6 as written below. Update-plane module delivery completeness matters for these extractions but was not investigated as a deployment defect in this pass. Do not claim it is solved, weaken update guards, or launch production operations to verify it.

Repairs Already Present

Verify these remain intact, but do not report their original defects as new:

Responsibility Current Home and Invariant
Login/session completion utils/login-session-bind.js and utils/credential-session-rebind.js: regeneration, binding, persistence, and failure hygiene
Session resurrection prevention utils/session-store-guard.js: revoke checks before and after writes; utils/file-session-revocations.js: persistent hashed-SID markers
Account and proof generations utils/session-account-binding.js, utils/remember-login-fingerprint.js, and services/account-credentials.js
Shared authentication Redis deadlines utils/auth-redis-deadline.js: generated commands, explicit commands, iterators, transactions, and reconnect handling
Remember-login delayed mint/revoke utils/remember-login-redis.js: revoked identifier/lineage markers checked by guarded writes
TOTP migration and replay claims services/totp-secret-migration.js and utils/totp-claim.js: stale migration cannot restore a revoked seed; shared claims arbitrate replay
Login bcrypt compatibility/admission utils/bcrypt-rounds.js and utils/bcrypt-admission.js: valid 2y compatibility, work admission, queued-wait expiry
Response compression utils/response-compression.js, compression@1.8.2: disconnect cleanup and backpressure
MySQL auth-plugin downgrade mysql2@3.23.1 in package.json: insecure clear-password switch refused; normal handshake control passes
Oversized node response listeners services/node-http.js httpRequestJson and nodes.js callNodeApiOnce: listeners precede header-only rejection
Database proxy expansion budget utils/db-proxy.js: cap compressed input and gzip/deflate output, reject invalid/truncated text, preserve bodyless HEAD
Upload/download failure cleanup utils/stream-lifecycle.js: both uploaders stop failed sources; canceled download sinks cancel upstream; HTTP 200 failure bodies count as failure
Node-update archive allocation utils/node-update-archive.js: 8 MiB per entry, 32 files, 20 MiB encoded request, preflight and actual-size checks

The expanded fixes addressed database credential disclosure and availability, not a newly demonstrated password/MFA login bypass. Distinguish their conditions: MySQL disclosure required a rogue endpoint or interception of unencrypted DB traffic; proxy expansion required an attacker-influenced backend response; node-update expansion required a malicious or compromised release artifact.

Next Investigations, in Priority Order

These are QUESTIONS AND HYPOTHESES, not findings. Start with item 1. Follow one controlling path deeply, establish a discriminating check, then act. Do not turn this list into a shallow repository-wide keyword sweep.

1. End-to-End Outbound Deadlines and Cancellation

Anchors in index.js: httpGetRaw, ssrfPipedHttpGet, createSsrfSafeAgent, httpStreamRequest, streamExportToImport, and streamPanelUploadToNode. Also inspect httpRequestJson in services/node-http.js, callNodeApiOnce and streamUploadToNode in nodes.js, and upload/download consumers in utils/server-asset-apply.js.

Trace validation -> DNS -> connection -> redirects -> body -> consumer -> final cleanup. Does a claimed total deadline cover DNS and every redirect, or only start after setup? Can a slow-drip body evade an inactivity timer? Are discarded redirect/error bodies stopped or merely drained indefinitely? After a getter resolves with a stream, do subsequent request errors/timeouts reach that stream, or only reject an already-settled promise? Do EOF, close, abort, and cancel each settle and release both ends without a late success or write?

Cheap checks: controlled DNS promises, fake clocks/event emitters, bounded loopback servers, and promise barriers. Exercise request error AFTER headers, source close WITHOUT end, paused-consumer cancellation, refused dial before source listeners attach, and successful completion. Assert handle destruction, caller settlement, pending timers/locks, and unchanged success bytes. Do not demonstrate resource exhaustion with a huge payload or a real external target.

Reuse tests/http-straggler-listeners.test.js, tests/node-fs-relay.test.js, tests/node-response-cap.test.js, and utils/server-asset-apply-streaming.test.js.

2. Authentication Proof Lifetime Across Every Await

Use the existing binders, session guard, account-binding predicates, Redis deadline wrapper, and remember registry/fingerprint machinery above. Trace getLoggedInUser, isAuthenticated, isAdmin, restoreRememberedLogin, and ensureRememberLoginCookie through actual middleware ordering in index.js, including consumers mounted before the general gate.

The existing revalidation hooks cover specific races, not every possible interleaving. Test a credential change, suspension, account recreation, or revocation AFTER the final fresh lookup but BEFORE save completion. Check request-local authority as well as persisted authority. A 400/500 response is not proof of deauthorization; a tombstone alone does not clear req.currentUser. Conversely, a stale session that is rejected on its next request is not automatically a durable bypass. Show the actual unauthorized use.

Observe cookies, remember entries, live request identity/admin caches, session writes, cleanup, and the next protected request. Include store read-error skips, confirmed-revocation skips, timeout/lost-ACK writes, and legitimate parallel rehashes. Use current-format and legacy records without silently weakening the generation or fingerprint checks.

Reuse tests/adversarial-auth-race-matrix.test.js, tests/login-staleness-reproof.test.js, tests/login-session-bind-module.test.js, and tests/remember-restore-and-confirmed-bounds.test.js.

3. Privileged Actions After Step-Up, Including Deferred Work

Start at requireDestructiveActionStepUp, consumeDestructiveActionGraceUse, and verifyActionToken in index.js, then follow the ACTUAL mutation or queued job, not just the gate. Shared homes include services/destructive-action-grants.js, services/account-actions.js, and services/account-credentials.js.

Does each non-Accounts privileged action still belong to the proved actor, generation, resource, and proof strength at commit/execution time? Accounts already lock the actor at commit; do not assume every config writer, installer, update, transfer, or background worker does the same. Verify reusable-grant scope/cap/expiry and one-time-token claims against concurrent requests and target replacement. Demonstrate meaningful unauthorized mutation before calling a stale snapshot a vulnerability.

4. Update Completeness and Archive Metadata

Inspect PROTECTED_FILES, UPDATABLE_PATHS, UPDATABLE_DIRS, installPanelUpdateInternal, prepareNodeUpdatePayload, and getUpdateEntryDataCapped in index.js, plus the new archive module. Does an update deliver every required leaf module and the compatible dependency lock, or can updated entry points continue using stale/missing code? The current UPDATABLE_DIRS lists scripts/public/views/middleware/utils/routes; verify its contract against the application's services imports rather than assuming completeness. A deployment bug is not automatically a security finding.

Test ZIP central-directory/member counts, misleading declared sizes, method variants, duplicate normalized filenames, prefix selection, and aggregate base64-envelope accounting using bounded fixtures. Per-entry inflation limits do not by themselves bound archive metadata or all concurrent update paths. Do not weaken HTTPS, downgrade checks, checksum policy, or protected-file rules. Check main.go handleNodeUpdateInstall as the receiving contract.

Reuse tests/update-plane-hardening.test.js and tests/node-update-install-caller-budget.test.js.

5. Tenant Identity, Filesystem Scope, and Quota Concurrency

Follow real file/upload/import/extract/archive/transfer routes through services/node-fs-relay.js, the canonical server-row resolvers, permissions, action-token resources, and the daemon handlers. Verify aliases cannot authorize one row and mutate another. Read the matching safe-root/path code in pathsafe.go and main.go, and the whole lockUploadScope choreography for quota-consuming writes.

Exercise symlink replacement, no-clobber/create-only permissions, suspended or transferring servers, early rejection, cancellation, and simultaneous quota writes. Preserve intentionally distinct panel/relay contracts and streaming implementations. Do not create a second sanitizer, relay, or quota checker.

6. Pre-Auth Parsing, Trust Configuration, and Advisory Consumers

Review actual middleware mounts, parser limits/decompression, case/trailing slash/encoded-path classification, and origin/proxy trust at the deciding code. Use tests/pre-gate-mount-census.test.js and tests/store-fallback-valid-hits.test.js. In limiter code, a validation-valid fake hit of 1 is not an authoritative successful increment; login reservation counters intentionally use the 0 error sentinel. Test partial Redis availability against the real consumer contracts.

Six packages retained advisories at handoff: brace-expansion (EJS CLI jake/filelist chain), follow-redirects (PM2 tooling), ip-address (limiter and SOCKS tooling), proxy-addr (Express), qs (Express query parser), and tar (no application npm-tar consumer found). Recheck changed consumers/options before classifying reachability. The reviewed limiter native-validates IPv6 first; the qs paths did not enable comma parsing or re-stringify hostile parsed data; the default proxy trust is loopback, not the mapped-subnet advisory shape. Do not equate an audit severity or an isolated package PoC with an app exploit. Do not change operator trust/TLS policy merely to eliminate advisory counts.

Investigation and Repair Standard

For each suspected defect, record the entry point, attacker prerequisites, input/state controlled, full reachable path, violated invariant, concrete impact, and current guard that does or does not stop it. Then construct one small falsifiable test of the REAL controlling implementation, with a normal control and instrumentation for the security-relevant state/artifacts.

Once evidence identifies a fix, make the smallest owning-module change and run the focused check immediately. Apply equivalent fixes to known siblings or delegate to one existing shared implementation. Do not alter unrelated tests, policies, frontend layout, wire contracts, or configuration. Use apply_patch for manual edits and retain the adpanel:<topic> constraint-comment convention.

Use synthetic credentials and disposable local test services. Never print real secrets or execute provisioning/reset/install scripts against production. Launching the panel or requiring its entry point is not an innocuous smoke test. Ask before live destructive/load testing, dependency-wide upgrades, deployment, or any policy change. No new tests should need a production account.

Run targeted checks first, then npm test and go test . when available. For untracked artifacts, use git diff --no-index --check /dev/null <path>; expected differences may return 1 without whitespace errors. Review the final diff and search siblings. Record skipped/unavailable checks separately.

Required Final Report

  • Confirmed NEW findings first, severity ordered, with current file/symbol references, prerequisites, reproduction evidence, and fixed/open status.
  • Coverage ledger: what was read completely, what was traced/tested, and what remains unreviewed. Do not describe this as an entire-repository audit.
  • Tests and exact results, including skipped integration checks and Go status.
  • Compatibility effects, deployment action required, and remaining live TLS, database transport, worker-version, persistence, or infrastructure assumptions.
  • If no new consequential defect is confirmed, say so without inventing one. Update this handoff and the current security ledger; do not erase history.

Archived 2026-11-08 Brief

The material below preserves the original campaign record. Its code snapshots, task status, and line numbers are historical and superseded by the current source and the continuation section above.

Repo root: /ADPanel/ADPanel-Enterprise. You MUST also read AGENTS.md before writing code. Non-negotiable rules distilled:

  1. One responsibility, one implementation. Extend the existing shared module; never fork a parallel copy. The codebase has structure-pinning tests that enforce some of these — update them consciously, never weaken them.
  2. index.js (60,624 lines), public/js/bot.js, main.go are frozen against growth. Fix logic goes into utils/ modules (dependency-injected deps object pattern — see utils/bcrypt-rounds.js). index.js changes must be minimal call-site edits; if your change removes dead code from index.js, that shrink is allowed. NEVER require("./index.js") from a module.
  3. Security-fix comments: every fix carries a // adpanel:<topic> — comment explaining the CONSTRAINT the code enforces (not "what I changed"). Match the density and voice of the surrounding comments.
  4. Tests: npm test (node --test over utils/ + tests/) AND go test . must stay green. Go is untouched by this campaign, but run it once at the end.
  5. Do NOT git add/git commit anything. Edit the working tree only.
  6. No behavior change beyond the fix spec. No drive-by refactors.

The three findings (verified current)

Finding 1 — Login rehash can overwrite a concurrent password reset (Medium)

Where (current): index.js:21425-21437 (POST /login, after the bcrypt compare at 21398 succeeded). The write: index.js:21429

if (parseHashCost(user.password) !== BCRYPT_ROUNDS) {
  try {
    const upgraded = await rehashIfStale(user.password, passStr, BCRYPT_ROUNDS);
    if (upgraded) {
      await db.query("UPDATE users SET password = ? WHERE id = ?", [upgraded, user.id]);
      user.password = upgraded;
    } else {
      console.warn(`[security] bcrypt cost heal skipped for ${user.email} (stored cost ${parseHashCost(user.password)}, rounds ${BCRYPT_ROUNDS})`);
    }
  } catch (err) {
    console.warn(`[security] bcrypt cost upgrade failed for ${user.email} (login continues):`, err?.message || err);
  }
}

Bug: the rehash UPDATE is keyed by id only. If an admin password reset (index.js:52010, or the email-keyed resets at 46099 / 50641) commits between the login's bcrypt compare and the rehash write, the rehash overwrites the NEW hash with a hash of the OLD (possibly compromised) password — silently un-doing the reset. Login then completes on the old credential.

Fix spec (implement exactly):

  • Make the rehash write an atomic compare-and-set against the credential the password was actually verified against: UPDATE users SET password = ? WHERE id = ? AND password = ? with [upgraded, user.id, user.password] (the snapshot hash that matched).
  • db.query (db.js:62) returns the OkPacket for UPDATEs — use result.affectedRows.
  • If affectedRows === 0 (CAS lost — the stored credential changed concurrently): the submitted password has NOT been proven against the live credential. Re-fetch the row (findUserByEmail(user.email)), and re-run withTimeout(bcrypt.compare(passStr, latest.password), 8000, "bcrypt-timeout").
    • Re-compare FAILS (a reset set a different password) → treat exactly like a wrong password: return failCredentials("arm:stale-credential"). Uniform 400 "Invalid credentials", captcha arming and throttle counting all apply — do NOT invent a new response shape.
    • Re-compare SUCCEEDS (concurrent writer rehashed the same password, e.g. a parallel login) → continue the login with user.password = latest.password. Do NOT retry the rehash (the row may now be at parity; if not, the next login heals it).
  • If CAS won → user.password = upgraded (unchanged behavior).
  • Keep the surrounding try/catch and the rehashIfStale null path exactly as they are. Keep the rehash BEFORE the MFA check (order unchanged).
  • Comment: // adpanel:rehash-cas — explaining the lost-update constraint (a rehash must never overwrite a credential it did not verify against).
  • Do NOT touch the reset writers at 46099 / 50641 / 52010 — they are correct; the login side must yield to them.
  • Regression guard: two concurrent logins with the correct password must both succeed (one via CAS, one via the re-compare path). A password reset landing mid-login must cause the old password's login to fail.

Finding 2 — Default-port origin validation gap (Medium)

Where (current): utils/origin-host.js:170-173 (explicitPortsDiffer) and :205-214 (csrfPortMismatch — the ONE shared rejection decision). Call sites: index.js:13619 (sameOriginProtection, HTTP state-changing routes) and index.js:57590 (isSocketOriginAllowed, Socket.IO handshake), plus utils/cross-site-read-guard.js (cookie-bearing reads) through the same csrfPortMismatch.

Bug: explicitPortsDiffer(a, b) returns false when EITHER side lacks an explicit non-default port. Therefore:

Panel:   https://panel.example.com          (Host header portless → servingPort null)
Origin:  https://panel.example.com:8443     (explicit port "8443")

passes csrfPortMismatch. An attacker controlling content on another HTTPS port of the same hostname gets their Socket.IO handshake accepted with the victim's SameSite=Lax session cookie (SameSite ignores ports). The HTTP CSRF surface has the same gap (individual routes may add CSRF tokens; the socket surface does not).

Fix spec (implement exactly):

  • In utils/origin-host.js ONLY (the one true home — do NOT add checks at call sites): tighten the core comparison in csrfPortMismatch so a mismatch ALSO exists when exactly ONE side carries an explicit non-default port and the other side carries NO port evidence. Both portless → pass (default-port and NAT deployments keep working). Both explicit and equal → pass. Both explicit and different → reject (unchanged).
    • Rationale you must preserve in the comment: browsers always send an explicit port in both Origin and Host when the port is non-default, so a one-sided explicit port is either (a) a same-host sibling service — the attack — or (b) a port-stripping/rewriting proxy. Case (b) is served by the EXISTING explicit escapes: trusted X-Forwarded-Host (HTTP surface, index.js:13573-13618), PANEL_PUBLIC_URL host+port escape, portBlindTrust (CSRF_ALLOWED_HOSTS / NODES_CORS_ORIGINS), browser-attested sameOriginFetch, cookie-less requests. Those escapes are load-bearing — do not remove or reorder them.
    • Keep explicitPortsDiffer exported (its both-explicit semantics are still the right vocabulary); the stricter one-sided decision lives inside csrfPortMismatch.
  • Update the boundary comments that document the OLD accepted trade — they are now wrong and must be consciously amended, not deleted:
    • utils/origin-host.js:164-204 (the explicitPortsDiffer + csrfPortMismatch comments),
    • index.js:13587-13612 (sameOriginProtection comment — "One-sided or absent ports stay port-blind"),
    • index.js:57563-57588 (socket comment — same sentence),
    • utils/cross-site-read-guard.js comment around line 192 if it repeats the trade. Comment topic: // adpanel:csrf-port-awareness — (extend the existing topic, do not invent a new one).
  • Known accepted edge (document it, do not fix): a deployment serving plain HTTP on port 443 or HTTPS on port 80 with a rewriting proxy and no PANEL_PUBLIC_URL will now be rejected where it passed before. That shape is a misconfiguration; the fix ships with the PANEL_PUBLIC_URL escape as the documented remedy.
  • Tests to update consciously (they pin behavior and, in one case, SOURCE STRUCTURE of origin-host.js — read them first):
    • tests/csrf-port-awareness.test.js
    • tests/csrf-localhost-scoping.test.js
    • tests/node-relay-cross-site-guard-parity.test.js (pins source structure — update pins to the new source; never weaken the parity assertion itself)
  • Add tests for: (same-host origin :8443 vs portless Host → REJECT on socket predicate and HTTP predicate), (both portless → PASS), (both explicit equal → PASS), (both explicit differ → REJECT), (portless origin vs explicit serving Host → REJECT), (PANEL_PUBLIC_URL host+port escape still passes), (cookieless still passes), (foreign host unaffected end-to-end where tests exist).
  • Regression guard: default-port deployments, NAT/port-forwards, XFH-preserving proxies, loopback dev on localhost:3000, and CSRF_ALLOWED_HOSTS users must all keep passing. Run the three test files.

Finding 3 — TOTP consumption is not atomic across workers (Medium)

Where (current):

  • Verifier: index.js:2524-2582 (verifyTotpForUser, currently SYNCHRONOUS).
  • Consume block: index.js:2576-2579 — markTotpCodeUsed(accountId, code) (process-local Map, defined at 20863-20885, TTL 120s) + persistTotpLastCounter(user.id, usedStep) (fire-and-forget, index.js:2514-2522: UPDATE users SET totp_last_counter = GREATEST( COALESCE(totp_last_counter,0), ?) WHERE id = ?).
  • Second direct consume site: index.js:44185-44186 (2FA confirm burn: markTotpCodeUsed(...) + persistTotpLastCounter(...)).
  • All call sites of verifyTotpForUser (each needs await once async): 8571, 8586 (step-up helper), 21461 (login), 44066, 44567 (helper — verify its context is async; if not, make it async up to its own callers), 45877, 46005 (consume:false), 46072, 46176 (consume:false), 46264, 50629.
  • db.query returns the OkPacket for UPDATEs (affectedRows). Startup migration auto-adds totp_last_counter (index.js:60355-60369); legacy-schema fallbacks exist at 13841/13895.

Bug: check (snapshot totp_last_counter) and consume (process-local Map + fire-and-forget GREATEST) are not atomic and not shared. Two overlapping requests on different workers/instances with stale snapshots both pass the pre-checks, both call the fire-and-forget GREATEST (which is monotonic but never excludes anyone), and both get ok: true — one code authorizes two verifications.

Fix spec (implement exactly):

  • New module utils/totp-claim.js (DI pattern, exports a factory): createTotpStepClaimer({ db, logger = console, now = Date.now }) → async claimTotpStep(userId, step):
    • Atomic claim-by-monotonic-step: UPDATE users SET totp_last_counter = ? WHERE id = ? AND (totp_last_counter IS NULL OR totp_last_counter < ?) [step, userId, step]. affectedRows ≥ 1 → won. 0 → lost (another request consumed an equal-or-higher step first).
    • Wrap with withTimeout-style protection at the CALLER (index.js has withTimeout; the module itself stays dependency-free — pass a timeout in deps or await+race in index.js). On timeout or DB error → { won: false, failed: true } → the verifier FAILS CLOSED (returns ok: false), because the DB is already a hard dependency of every flow that calls the verifier. Sole exception: ER_BAD_FIELD_ERROR (legacy schema where the ALTER at boot failed) → degrade OPEN exactly like today's silent GREATEST failure, log loudly once, return { won: true, degraded: true } — the in-memory Map remains the only guard in that legacy mode.
    • The claim IS the persist: a winning claim writes the counter. A LOSING claim must NOT write anything.
  • verifyTotpForUser becomes async (same checks, same order, same return shapes). The consume block becomes:
    if (options.consume !== false) {
      markTotpCodeUsed(accountId, code);              // fast same-process replay guard — KEEP
      const claim = await claimTotpStep(user.id, usedStep);
      if (!claim.won) return { ok: false, code: "replayed", skipped: false };
    }
    
    Replays/losses must stay indistinguishable from a wrong code (the existing login-uniform-failure posture — do not leak which one happened).
  • Replace index.js:44185-44186 (2FA confirm burn) with the same claim path: markTotpCodeUsed(totpAccountKey(user), codeStr) then await claimTotpStep(user.id, currentTotpStep() + verifiedDelta.delta); if the claim loses, abort the confirm with a 403-style JSON error BEFORE the new secret is persisted (reuse the endpoint's existing error shape; never continue to the secret write on a lost claim).
  • Add await at every call site listed above. Verify each enclosing function is async (they are route handlers/helpers that already await — confirm 44567's helper chain explicitly). No floating promises; no .then() conversions.
  • DELETE persistTotpLastCounter from index.js once both callers are migrated (net shrink). Check tests for pins on it / on the GREATEST SQL first (grep -rn "GREATEST\|persistTotpLastCounter" tests/ utils/).
  • Comment: // adpanel:totp-atomic-claim — on the new module and at the consume block, explaining the exactly-one-winner constraint and fail-closed posture.
  • Keep TOTP_STEP_SECONDS, currentTotpStep, the in-memory cache and its sweeper, and the consume: false two-step flow semantics EXACTLY as they are.
  • Tests: new utils/totp-claim.test.js (win/lose/race: two claims of the same step against a fake db — exactly one wins; error → fail-closed; ER_BAD_FIELD_ERROR → degraded-open) plus updates to any pinning tests.
  • Regression guard: the two-step password/email change flows (46005 → conclude, 46176 → conclude) must still work (pre-check consume:false, final consume claims); same-worker immediate replay still rejected; login with a fresh code still succeeds exactly once.

Concurrency protocol (index.js is edited by multiple agents in parallel)

  • Keep your edits to YOUR finding's regions (listed above). Regions are disjoint by design. Do not "help" another finding.
  • If an Edit fails with a modified-since-read error: re-read the exact region and retry with the fresh content. Never reformat neighbors.
  • Run node --test <your test files> for your area, then npm test once before reporting. If ANOTHER agent's in-flight edit breaks an unrelated test, report it — do not fix outside your scope.

Review-phase instructions (reviewers & wiring agents read this section)

Reviewers: read the diff (git diff -- <files>), then read EVERY changed hunk line-by-line IN CONTEXT (open the surrounding 100 lines — the brief's line numbers WILL have shifted after fixes; locate by symbol). For each fix verify aggressively:

  1. The fix actually enforces the constraint in this brief (not a weaker variant, not dead code, not shadowed by an earlier return).
  2. No regression: enumerate the deployment shapes / flows listed under "Regression guard" and trace each through the new code.
  3. No new crash class: every new await/async path has its errors handled (unhandled rejection = worker crash in this codebase's history).
  4. No second copy created anywhere (grep for siblings — AGENTS.md rule).
  5. Tests genuinely assert the new behavior (not just pass). Output format: verdict per fix — PASS or ISSUES: numbered list, each with file:line, severity (blocker/major/minor), and the exact reason. No praise padding.

Wiring agents: you own what line-by-line reviewers cannot see. Read ALL THREE fixes plus the full login/auth surface (login handler, step-up requireDestructiveActionStepUp, 2FA confirm, password/email change flows, admin reset, remember-me fingerprinting, session regeneration, socket handshake, cross-site read guard, nodes.js relay CORS) and hunt CROSS-CUTTING breakage: interaction of the rehash CAS with the TOTP claim ordering in login; throttle/captcha side effects of the new failure paths; whether any OTHER surface in the repo (nodes.js, cmd/sshterm, main.go, dashboard-assistant) duplicates one of the fixed responsibilities and now drifts (AGENTS.md siblings rule); AGENTS.md compliance (monolith growth = index.js line count must not grow net; one-true-home; comment convention; dependency direction); npm test + go test . green. Output: numbered findings with file:line + severity, or WIRED-CLEAN.


PHASE 2 — Rewriting-proxy operability (added 2026-11-09)

The problem being solved

The one-sided port rule (Phase 1, Finding 2) rejects the deployment shape "panel on a NONDEFAULT public port behind a Host-REWRITING proxy" when the proxy neither forwards a port-carrying trusted X-Forwarded-Host nor has PANEL_PUBLIC_URL set to the exact public URL. In that shape the browser sends Origin: https://host:8443 (explicit) while every serving-port evidence source is portless — the request is indistinguishable from the sibling-port attack, so configuration is the ONLY discriminator. Today this brick is also SILENT (bare 403 "CSRF blocked" / socket "origin-not-allowed", no log) and PARTIALLY unfixable by proxy config: the HTTP surface honors trusted X-Forwarded-Host, but the socket surface ignores it entirely.

Phase 2 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.

Verified current-state facts (2026-11-09)

  • isSocketOriginAllowed(headers) — index.js:57694; sole call site index.js:57864 inside io.use((socket, next) => {; socket.request (the handshake IncomingMessage) is available there and already used at 57868.
  • getTrustedForwardedHost(req) — index.js:3057: honors x-forwarded-host ONLY when isTrustedProxyIp(getDirectRemoteIp(req)); returns the LAST comma entry ("" when absent/untrusted). getDirectRemoteIp (index.js:2881) reads req.connection?.remoteAddress || req.socket?.remoteAddress — works on the handshake request.
  • The HTTP middleware's serving derivation to mirror EXACTLY (index.js ~13638-13640): const servingPair = forwardedHost ? extractHeaderHostPort(forwardedRaw) : extractHeaderHostPort(req.headers.host || "").
  • Test harness: tests/csrf-port-awareness.test.js slices the REAL index.js block const SOCKET_ALLOWED_ORIGINS … function getSocketIp into a vm sandbox pre-loaded with the utils/origin-host functions. Any new symbol the block references (securityLog, the advisor) must be injected as sandbox stubs. Structural pins live in socketOriginWindow() (~742-780) — they pin the literal serving-derivation strings and the allowlist→port→equality ordering. middlewareWindow() pins the HTTP side. The parity test (tests/node-relay-cross-site-guard-parity.test.js) pins cross-surface routing and currently passes unchanged.
  • Throttle conventions to mirror: _logCsrfExtraAllowedUse (index.js ~13532-13545): per-key Map capped at 50 (clear-on-overflow), 20 emissions per rolling 1h window, call-driven (no timers).

Change 1 — Socket surface accepts trusted X-Forwarded-Host serving evidence

  • Signature becomes isSocketOriginAllowed(headers, forwardedRaw = "", req = null). forwardedRaw is the ALREADY trust-screened entry (the caller resolves trust — same split as the middleware, where forwardedRaw comes from getTrustedForwardedHost(req) before the pair derivation).
  • Serving derivation mirrors the middleware exactly: const servingPair = forwardedRaw ? extractHeaderHostPort(forwardedRaw) : extractHeaderHostPort(headers?.host || "");
  • Sole call site: resolve socketForwardedRaw via try { getTrustedForwardedHost(socket.request) } catch { "" } (fail-open to Host-only evidence = today's behavior), pass (handshakeHeaders, socketForwardedRaw, socket.request).
  • The host-equality grant and the operator allowlist are UNTOUCHED — XFH feeds ONLY the port check (the middleware's requestHost allowlist use is a different grant shape; do not import it).
  • Comment topic: // adpanel:socket-forwarded-host — replacing the false "this surface has no trusted X-Forwarded-Host machinery" sentence; state the trust boundary (peer must be a trusted proxy; direct connections ignore XFH) and that this is parity with the HTTP surface, not a new trust grant.

Change 2 — Port-mismatch advisor (diagnosable rejection)

  • New module utils/origin-port-advisor.js (DI, zero repo-internal requires): createPortMismatchAdvisor({ now = Date.now, intervalMs = 3600000, budgetMax = 20, mapMax = 50 }) → advice({ originHeader, servingPort }) → string | null.
  • Fires ONLY on the brick shape: parseOriginHostPort(originHeader) yields an explicit non-default port AND servingPort == null. Null otherwise (both explicit, serving-explicit, portless origin, unparseable). This condition lives ONLY here — callers must not re-derive it.
  • Message: names the origin host:port, states that cookie-bearing requests are being rejected because the serving Host header carries no port evidence, and gives BOTH remedies verbatim: set PANEL_PUBLIC_URL to the exact scheme+host+port the browser sends, OR make the proxy forward X-Forwarded-Host WITH the port (nginx: proxy_set_header X-Forwarded-Host $http_host;). Match the repo's security-log voice.
  • Throttle exactly like _logCsrfExtraAllowedUse (the origin is attacker-controlled): per host:port key, Map capped at mapMax with clear-on-overflow, budgetMax emissions per interval window, call-driven.
  • index.js binding: one createPortMismatchAdvisor() instance near the CSRF consts. Called at BOTH rejection points with the values the rejection actually saw: the middleware's 403 branch (origin header = the one that produced originPortPair — rawOrigin when originHost evidence exists, else rawReferer) and inside isSocketOriginAllowed before return false (then if (advice) securityLog(advice, req) — req may be null only from tests). Rejection semantics and wire bodies stay BYTE-IDENTICAL (403 "CSRF blocked", "origin-not-allowed" unchanged). Comment topic: // adpanel:port-mismatch-advisor —.

Change 3 — Comments catch up to the two-remedy posture

Everywhere that still states PANEL_PUBLIC_URL as the SINGULAR remedy for rewriting proxies (index.js middleware block ~13594-13626, socket block, and the csrfPortMismatch boundary comment in utils/origin-host.js — whose extractHeaderHostPort doc at 106-113 ALREADY documents trusted-XFH callers): amend to the two-remedy form. Do not delete history — amend in place.

Tests (all mandatory)

  • New utils/origin-port-advisor.test.js: fires on the one-sided shape; null for both-explicit / serving-explicit / portless origin / unparseable; first emission + same-key suppression within the window; budget cap; map cap; DI-clean (no require of index.js/db.js).
  • tests/csrf-port-awareness.test.js: sandbox gains securityLog and a RECORDING _PORT_MISMATCH_ADVISOR stub; new scenarios — check(headers, "panel.example.com:8443") with origin :8443 → TRUE (the rewriting-proxy deployment now passes on the socket surface); portless forwardedRaw → still false; different-port forwardedRaw → false; absent forwardedRaw → false (unchanged). Update existing calls to the new arity.
  • Structural pins in socketOriginWindow() updated CONSCIOUSLY to the new derivation (keep: allowlist→port→equality ordering, no-local-copy, no sec-fetch-site). middlewareWindow() pins must still pass. Parity test must pass unchanged (verify).
  • Advisor calls must not trip scripts/find-unguarded-awaited-routes.js (advisor is synchronous — confirm 0 findings). Full npm test + go test . green.