82 KiB
Accounts and Settings Security Repair Handoff
Date: 2026-11-17
Status: repairs implemented in the working tree. The original findings and acceptance guidance below remain as the audit record. See Implementation Results for the actual changes and verification limits. No deployment, production account operation, or production service restart was performed.
2026-11-21 Review: Accounts and Transfer Rate Limiting
Low, functional: a 429 stopped transfer progress tracking. The Settings client treated the throttled status response as though no transfer existed. An active transfer continued on the server, but the open modal stopped updating. The same mistake hid an existing transfer if the first lookup on opening the modal was throttled. No account mutation or server-side transfer failure resulted from this response handling.
Repair Walkthrough
- In the Settings transfer client, distinguish
a 429 from the successful
job: nullresponse. Keep the current progress and defer status requests until the numericRetry-Afterhas elapsed (five seconds if it is missing or invalid). - Keep polling an open modal, including after a throttled initial lookup. Closing the modal still stops polling, and an expired lookup cannot start a timer for a closed or different server. A missing or finished job still ends ordinary polling.
- Refresh the script version in the Settings view. Regression tests check backoff, recovery, a genuine missing job, and closing the modal during lookup. No rate-limit threshold, authorization policy, or operator setting changed.
Accounts Walkthrough
- Create: An active admin can create either role. Creating a normal user requires the session, action token, and valid email and password. Creating an admin additionally requires the acting admin's password and enabled TOTP. Neither action provisions a QR code or a recovery-code set.
- Change or reset a password: Use your own password control for your account; prove your current password and enabled TOTP. To reset another account, use that account's password action and verify as the acting admin. Both invalidate the old credential generation; an own-account change binds the owner to a fresh session.
- Reset 2FA or recovery codes: Reset 2FA clears the target's authenticator and backup codes and revokes the old session generation. The owner signs in and enrolls a replacement in Account > Credentials. Recovery-code regeneration is separate: the admin panel allows it for non-admin targets; administrator owners regenerate their own codes with their password and a second factor.
- Delete, suspend, or manage access: The routes bind the action to the selected account and require acting-admin verification. Deletion refuses self-deletion, protects the last active administrator, and performs session eviction before transactional cleanup. Suspension revokes the old session generation. Server and Agent grants and revocation remain admin-gated. No additional material defect was confirmed in these flows.
Rate-Limit Assessment
The checkout has the optional global limiter disabled, with 300 requests per IP per 120 seconds stored. Five requests per 120 seconds is the view's initial value, not the active policy, and is too low for interactive use. When enabling the limiter, size the shared IP budget for peak requests behind the busiest NAT or proxy. Keep the distinct operation budgets: creation is six requests per account and 24 per source bucket per ten minutes; shared step-up is eight per session and 24 per account per ten minutes. Normal manual administration fits; large batches may need pacing. The separate progress budget is 240 requests per identity per minute when the optional limiter is enabled. The confirmed transfer issue was client handling of a rejection, not evidence that those caps need raising.
2026-11-21 Follow-Up: Account and Socket Identity
Medium: live sockets could adopt access from a different account. The handshake checked the authenticated account ID and credential generation, but connection initialization and the immediate permission refresh looked up the current owner of the email again without checking that binding. A stale socket still present during an account replacement could be given the new owner's role or access list before its next liveness check.
Low: account cleanup could sign out a different account. The account mutation was pinned to a user ID, but browser-session and live-socket cleanup selected by email, and saved-login cleanup treated matching email as enough even when the IDs differed. If an email was reused before cleanup completed, the replacement could lose its sessions or saved logins. The post-create sweep could also revoke a first login made after the new account committed. These were unintended sign-outs, not an authorization bypass.
Repair Walkthrough
- Keep the authenticated actor and selected target pinned to their account IDs at commit. Do not change the role or step-up policy to work around the sign-out race.
- Before a socket starts or refreshes access, compare its authenticated identity and generation with the row being used. Disconnect on a known mismatch, and scope the server-access query to the verified row ID so a subsequent email lookup cannot substitute another account's access.
- Carry the stored account ID into session inventory. Use the shared revocation matcher for browser sessions, saved logins in memory and Redis, and account-specific socket disconnects. A known different ID must not match merely because its email does. Keep email fallback for legacy records without an ID.
- Limit the post-create sweep to unbound legacy records. Modern sessions and saved logins already check their account binding, so an email-wide sweep is unnecessary and can sign out the new owner. The separate, email-based CLI revocation queue was not changed.
- Verify that mismatched sockets receive no refreshed access, the original and legacy records are revoked, a bound replacement remains signed in, and logout still targets only the chosen session. Use synthetic stores rather than deleting or resetting a real account.
The Accounts walkthrough below still applies. There was no UI, authorization-policy, or rate-limit configuration change. The Settings-wide audit found no budget that needed raising for ordinary use. The shared step-up quota can constrain bulk administration; size the optional IP quota for aggregate traffic behind the busiest NAT before enabling it. The stored optional policy remains disabled at 300 requests/IP per 120 seconds.
2026-11-21 Accounts and Settings Audit
Reviewed the Accounts controls, the client submit paths and action-token refresh, and their server-side routes and services. The rate-limit review covered Settings-wide request wiring, including reads, POST/DELETE actions, updates, database operations, and progress polls. Only the two confirmed defects below were changed. No UI, role policy, or operator configuration changed.
Confirmed Defects and Repairs
| Severity | Finding | Repair |
|---|---|---|
| Medium | Account deletion or access revocation could leave recurring schedule metadata behind: cleanup removed the delayed job before using it to identify the recurrence. Missed jobs also relied on the creator's email at execution, so a replacement account with the same email and sufficient permissions could be treated as the creator. | Shared cleanup matches the original account ID and removes a recurrence by its exact BullMQ key through the existing helper. Worker authorization rejects a missing or mismatched creator ID before evaluating server permissions. Deletion, suspension, and both access-revocation callers use the same cleanup. |
| Low | With the optional limiter enabled and Redis ready, mixed-case API paths reached the Redis limiter but could also consume the in-memory budget. This could return a premature 429 and consume capacity used by normal page requests. | The fallback now uses the same case-insensitive API boundary as Express's Redis mount. API requests still use memory when Redis is unavailable. Non-API paths and dedicated limiters are unchanged. |
Queue cleanup remains best-effort and cannot undo work already executing. The worker's creator-ID check protects pending work when cleanup misses it. Old schedules that lack a creator ID cannot be safely attributed: recreate any that are still needed through the scheduler with the intended account. Do not backfill IDs from current email ownership. Existing orphan recurrence metadata with no queued occurrence is not migrated by this change; remove any such entries by their exact schedule identity using the scheduler's existing delete flow. No live queue was inspected or modified.
Accounts Walkthrough
- Create User: Only an active administrator can create either role. A normal-user account requires an action token and validated email/password. Creating an administrator also requires the acting administrator's current password and their own TOTP if enabled. The new user enrolls their own 2FA after signing in; no authenticator secret or recovery codes are issued to the administrator at creation.
- Change password: For your own account, use the main password card and prove your current password and enabled TOTP. A successful change rotates the session generation and rebinds the current session. To reset another account, use its password action and verify as the acting admin. That resets the target's password and invalidates their old sessions and saved logins.
- Reset 2FA: Use Reset 2FA on the target account and verify as the acting admin. The reset clears the old authenticator and recovery codes together and revokes the old session generation. The owner then signs in with their password and enrolls a replacement authenticator in Account > Credentials. Recovery-code regeneration is separate; the admin-panel action is limited to non-admin targets, and admin owners can regenerate their own codes.
- Delete, suspend, or change access: Verified the server-side admin and target-ID checks, acting-admin step-up, and transactional writes. Deletion refuses self-deletion, preserves an active administrator, and confirms session/saved-login eviction before committing account and access cleanup. Suspension invalidates sessions without restoring them on unsuspension. No further material defect was confirmed in the inspected credential, permission, server access, or Agent access paths.
Rate-Limit Assessment
The workspace's stored policy has the optional global limiter disabled, with 300 requests/IP per 120 seconds saved. The template's 5/120 is a placeholder, and would be too strict if saved as an enabled policy. Even 300/120 is a shared NAT budget, not a per-user allocation. Size it from normal peak traffic and monitor 429s before lowering it. If an overly strict setting blocks in-panel recovery, an authorized server operator can correct only the rate-limit fields in the active server-side configuration and verify that all workers reload the policy. The policy store watches for valid file changes. This was not performed during the audit.
The always-on shared step-up limits are 8/session and 24/account per 10 minutes. Four fresh password-plus-TOTP target verifications can use the session budget. User creation allows 6/account and 24/source-IP bucket per 10 minutes; self-service password and TOTP families each allow 10/session and 30/account. Those are reasonable for normal manual use, restrictive for bulk work. The other operation budgets listed below remain unchanged. Install, transfer, and node-stat polls have a separate 240/identity-per-minute budget when the global limiter is enabled, so they do not exhaust ordinary Settings requests. Not every admin read has a dedicated limit. No ordinary Settings over-throttle was confirmed beyond the mixed-case dispatch inconsistency; no limits were raised.
Verification
- Focused regression suite: 180 passed. Covers original-creator binding, exact recurrence cleanup, account-deletion ordering, mixed-case limiter delegation, fallback, and Settings polling and operation budgets.
- Full
npm test: 4,302 passed, 9 skipped, zero failed.go test .passed. - Checks used source-level and synthetic test fixtures. No real account, production Redis/MySQL queue, deployment, or service restart was used.
2026-11-18 Independent Re-Review
This section records the subsequent review of the current working tree, not a new implementation of the repairs below. No additional material security or functional defect was confirmed. Production code, Accounts controls, account-role policy, and operator configuration were left unchanged; the only edit in this re-review is this walkthrough. Existing uncommitted changes were preserved. The A01-A05 and F01-F07 records below describe earlier work and must not be counted as newly discovered or newly fixed issues in this pass.
The review followed views/settings.ejs into public/js/settings.js, its selected-account identity helper, the actual route registrations in index.js, and the owning account, credential, session, policy, and rate-limit implementations. Settings-wide rate-limit coverage was inspected; unrelated features were not given a full security audit. No production accounts or backing services were used for creation, login, reset, suspension, deletion, or load testing.
Accounts Walkthrough
- Settings and account management are server-side admin-gated. A non-admin cannot provision either account type or call another-account mutations.
- Normal-user creation checks the action token, email/password policy, and active acting-admin ID/generation at commit. Administrator creation also proves the acting admin's current password and enabled TOTP. Neither creation path returns a target authenticator seed or recovery-code set.
- Your own password change proves the current password and enabled TOTP, uses a password/generation compare-and-swap, and rebinds the owner to a fresh session. Another-account password reset binds the selected target ID and verifies the acting admin, then commits the password and new generation together before invalidating old sessions and saved logins.
- Both admin 2FA-reset aliases delegate to the same service. Reset clears the target secret AND recovery codes with the session generation in one locked write. The owner enrolls a replacement authenticator after login; this action does not issue a new QR/seed to the acting admin. Panel recovery code regeneration remains restricted to non-admin targets, requires acting- admin proof, stores hashes, and returns plaintext only after commit.
- Server permissions/access, Agent access, suspension, and deletion bind the selected account ID and recheck the acting administrator under lock. Permission/access writes are transactional. Suspension invalidates the generation; unsuspension does not restore an old session or saved login. Deletion confirms eviction first, rejects self/last-active-admin deletion, and removes account-owned rows and ACLs atomically, including assistant history. Token refresh cannot silently retarget a recreated email.
Rate-Limit Conclusion
The stored optional global limiter is disabled, with 300 requests/IP per 120 seconds saved. The view's 5/120 inputs are placeholders overwritten by the settings response, not the active policy. Enabling 5/120 would be too strict for an interactive panel; sizing an enabled per-IP budget also needs the number of users behind each NAT. No operator value was changed.
The always-on step-up budget is 8 credential-bearing requests/session and 24/account per 10 minutes, shared across sensitive settings actions. A fresh password-then-TOTP interaction normally costs two requests, so four unrelated targets can exhaust the session budget. This is a documented bulk-work constraint, not evidence of an authorization bug. Creation allows 6/account and 24/source-IP-bucket attempts per 10 minutes. Self-service credential/TOTP families each allow 10/session and 30/account per 10 minutes. These are defensible manual-operation budgets; raising them would also expand guessing or abuse capacity. Separate settings operation budgets remain as tabulated below. No ordinary polling over-throttle was reproduced.
Install/transfer/node-stat polls are excluded from the generic budgets and use the optional 240/identity-per-minute progress policy. Logout has its own 10/identity-per-10-minute policy. Redis stores have distinct instances and prefixes; shared revision tests verify global-policy convergence. Dedicated limiter store-error behavior and per-worker no-Redis fallback remain as implemented. This is not a claim of blanket always-on coverage or a measured production-capacity guarantee.
Re-Review Verification
Three focused test runs completed: 670 tests, 663 passed, 7 skipped, zero failures. Coverage includes real extracted account handlers/services, credential and target interleavings, CSRF, session/saved-login invalidation, shared fake-store rate limits, global-policy publication, and polling exemptions. Skipped checks are not counted as passing integration evidence. Fresh repository-wide checks for this re-review also passed:
npm test: 4,172 tests, 4,163 passed, 9 skipped, zero failures.go test .: passed using the cached Go 1.26.9 executable withGOTOOLCHAIN=local; no Go code was changed.- The walkthrough passes whitespace checking and has no editor diagnostics.
Synthetic tests do not prove live InnoDB scheduling, production Redis behavior, browser acceptance with real accounts, or deployed worker versions.
2026-11-18 Audit Walkthrough
This section records the current source audit and supersedes earlier claims about integration where they differ. The earlier sections remain historical repair records. A helper existing or passing its unit tests is not evidence that the running application actually calls it.
Scope: views/settings.ejs, its Accounts controls in public/js/settings.js, target identity handling in public/js/settings-account-targets.js, the corresponding handlers in index.js, and their shared account, credential, session, policy, and limiter services. Settings-wide rate-limit coverage and polling were also traced. This was not a security audit of every non-Accounts settings feature or of the entire panel.
Inspection was read-only until consequential issues were confirmed. Only the repairs described below and their tests/documentation were changed. Existing uncommitted work, account-role policies, Accounts layout/controls, and operator security configuration were preserved. No real accounts were created, reset, suspended, deleted, or used for login tests.
Confirmed Findings and Repairs
| ID | Severity | Finding | Current Status |
|---|---|---|---|
| A01 | Medium | Sessions and saved logins missed by suspension eviction become usable again after unsuspension | Fixed with atomic session-generation revocation and generation-bound saved-login fingerprints |
| A02 | Medium | Seven settings operation budgets refill when the same authenticated caller changes source IP | Fixed by binding the existing shared account/session policies |
| A03 | Medium | The database-user limiter gate exists but is not mounted on the application | Fixed after the existing database admin gate |
| A04 | Low, data lifecycle | Panel account deletion leaves dashboard-assistant chats/messages behind | Fixed using the existing transaction-local cleanup helper |
| A05 | Medium | Admin 2FA reset leaves pre-reset recovery codes usable | Fixed by revoking the secret, recovery codes, and session generation in one actor-guarded write |
These findings are not unauthenticated account-management or admin-role bypasses. A02/A03 concern resource-abuse admission after authentication. A04 is retained deleted-account data, not disclosure to a replacement account: the inspected history reader already requires the immutable owner ID. The continuation independently confirmed A05; A01-A04 remain the earlier repair record, not additional newly discovered findings from the reset pass.
A01: Suspension Must Not Restore an Old Session
Owning code: setAccountSuspension in
services/account-actions.js.
Before the repair, suspension updated only suspended, suspended_at, and
suspended_by. The session sweep can fail or miss a dormant record. The
suspended flag blocks that record while suspension is active, but unsuspension
removes this block without changing the session's accountEpoch comparison.
A synthetic reproduction used the real setter and the real
sessionAccountBindingMismatch predicate: both writes committed, the old and
live epochs remained 3, and the old current-format session passed binding
after unsuspension. No production session store was accessed.
Required solution, now implemented: advance session_epoch in the SAME locked
UPDATE when suspending, using the existing newSessionEpochDifferentFrom
generator. Each suspension retry advances the live generation too, so an
in-flight session cannot remain current. Unsuspension preserves that locked
generation instead of restoring an earlier one. The existing eviction,
socket disconnect, error reporting, and actor/target authorization remain.
The saved-login boundary was checked separately. Its original fingerprint covered only password and TOTP secret, so a dormant saved login missed by revocation still matched after suspension/unsuspension and could silently restore into the new generation. A synthetic run of the actual original fingerprint confirmed identical values before and after the epoch change.
The fingerprint now lives in one utility, utils/remember-login-fingerprint.js, and includes the account generation. Issuance, restore verification, and pending login-proof verification all use that same implementation. There is no legacy-fingerprint fallback that could restore a revoked saved login. The real extracted restore regression rejects the old proof before rotation and confirms that a newly authenticated post-suspension proof still works. The existing isolated restore epoch-gate tests remain alongside that coverage.
Regression coverage in tests/account-actions-atomic.test.js checks the atomic SQL, missed-session invalidation, repeated suspension, unsuspension, new-login binding, and revoked-actor rollback. Existing response and incomplete-eviction tests in tests/credential-reset-eviction-surfacing.test.js still assert the standing failure contracts. Legacy sessions without an account ID/epoch still rely on the existing sweeps and revocation mechanisms; this audit did not migrate or purge live legacy sessions. The additional restore and fingerprint coverage is in tests/remember-restore-and-confirmed-bounds.test.js.
Compatibility effect: pre-upgrade saved-login cookie fingerprints cannot automatically restore; those browsers need a fresh password/2FA login. Old pending login proofs also require a new login attempt. Already-authenticated current-generation sessions are not forcibly logged out solely by this fingerprint-format change. Passwords, authenticator secrets, and recovery codes are unchanged. The cutover must not leave old workers accepting the old fingerprint format.
A02: Operation Budgets Must Survive Network Changes
Owning policy: services/settings-rate-limiters.js, constructed through the shared factory in utils/login-throttle.js.
The inspected application still constructed separate IP/email/SID counters for reinstall, template change, server creation, server transfer, branding writes, store version application, and permission-token minting. The same authenticated account and SID therefore received a fresh counter on each new source IP. With the optional global limiter off, that defeats the intended operation budget. The recovery path already used stable account/session keys.
Required solution, now implemented: bind all these existing policies once in the application and remove the old parallel definitions. Per-session caps and response bodies remain; the existing policy service adds its three-times- cap account backstop. Modern session keys use the account ID, so an email change does not refill that backstop. Each tier has its own Redis store and prefix, and Redis failure/no-Redis behavior is unchanged.
tests/settings-operation-rate-limits.test.js uses real express-rate-limit with shared fake stores to test IP rotation, fresh SIDs, an email change with the same ID, separate workers, independent accounts, and Retry-After. Sibling route tests verify the application bindings and existing action-token/step-up orderings. Recovery continues to use the same 5/session and 15/account budget; it was not a new bypass finding.
A03: An Unmounted Limiter Does Not Protect Routes
The existing createSettingsDatabaseRateLimitGate correctly classified all
six generic/MongoDB user create, password-change, and delete routes, but the
application never mounted it. The focused source-wiring test failed with
zero mounts. These handlers authenticate administrators and consume action
tokens, but fresh tokens can be obtained repeatedly; tokens are not an
operation-rate budget.
Required solution, now implemented: construct the existing shared gate and mount it once after database admin authorization. User mutations now consume 30/session and 90/account per 10 minutes. The existing selected settings and token-issuing reads consume 120/session and 360/account per 5 minutes. Install-progress polling is deliberately excluded and keeps its own policy.
The focused tests cover the six routes, case/trailing-slash and HEAD matching, poll exclusions, the application mount/order, and exhaustion despite fresh one-time tokens. No production database-user operation was run.
A04: Delete All Account-Owned Assistant History
The history service already prevents replacement-email ownership and locks
the owning user for writes. The CLI already called
deleteAccountAssistantHistory, but panel deletion did not, and startup
orphan cleanup omitted these tables. Successful account deletion could leave
private chats/messages stored after the account was gone. The full repository
gate exposed the missing panel integration; it was present before this audit's
edits.
Required solution, now implemented: call the existing helper on the deletion transaction's own connection before deleting the locked user row. This removes ID-owned and unassigned legacy history without touching another owner. SQL errors roll back the account deletion, and the helper retains its missing-table/legacy-schema handling. Startup also uses the existing best- effort orphan cleanup helper. No second history-deletion implementation was introduced.
tests/dashboard-assistant-history-owner.test.js and the existing deletion tests verify both callers, owner isolation, late write refusal, legacy schema behavior, cleanup ordering, rollback, and the last-active-admin guard.
A05: A 2FA Reset Must Revoke Its Recovery Codes
Owning code: resetAccountTwoFactor in
services/account-credentials.js, called
by both reset aliases through
services/admin-2fa-reset.js.
Before this repair, the locked reset cleared secret and advanced
session_epoch, but left recovery_codes unchanged. The real
/api/account/recovery/verify handler accepts a stored code without requiring
an enabled authenticator. A synthetic reproduction therefore still verified
a pre-reset code after the reset, even with a fresh session bound to the new
generation. Verification creates a short-lived recovery proof; the spending
path checks and burns that same stored hash, so retaining it also retains the
recovery authorization used by credential-change endpoints.
Impact is limited to a caller who knows an old recovery code AND has a valid authenticated session for that account. Session eviction and generation checks still block stale sessions. This is not an unauthenticated login bypass, a missing admin gate, or proof that an attacker can obtain a new session without satisfying login requirements. It is a broken credential revocation contract during an administrator's 2FA remediation action.
Required solution, now implemented: set secret = NULL,
recovery_codes = NULL, and the new session_epoch in the SAME ID-keyed
UPDATE inside the existing actor/target-locked transaction. Do not clear
codes in a later pooled write or add another reset implementation. Both
aliases inherit the repair; actor authorization, selected target identity,
self-reset refusal, session/socket eviction, and responses are unchanged.
The user enrolls their own replacement authenticator and receives fresh
recovery codes when enrollment completes. No new seed is disclosed to the
acting admin, and no schema change is needed.
The focused regression in tests/account-actions-atomic.test.js uses the real reset service and extracted recovery verification/spending functions with in-memory account state. It requires exactly one reset write, checks both credentials are cleared, checks the generation changes, refuses an old proof's hash without a recovery write, and refuses fresh verification before any bcrypt comparison. Existing alias, stale-target, revoked-actor, transaction rollback, and eviction-failure tests remain intact. Source contracts allow only the unrelated startup empty-secret normalization in the monolith, not an inline admin reset.
Deployment condition: switch all workers that can reset accounts to this version without retaining old reset writers. This change affects future resets; it does not retroactively identify or clear codes left by earlier resets. Any historical-account remediation requires separately authorized operator work. No production account or recovery inventory was modified.
Accounts Behavior Verified
| Action | Inspected Security Contract |
|---|---|
| Create a normal user | Admin session and action token; validated email/password; guarded insert; active acting-admin ID/generation rechecked at commit; no pre-provisioned 2FA |
| Create an administrator | The same checks plus the acting admin's current password and their own TOTP when enabled |
| Change your own password | Current password, enabled TOTP, shared password policy, ID/password/generation CAS; old sessions invalidated and owner rebound to a new SID |
| Reset another account's password | Admin/action token, selected expectedTargetId, acting-admin password then enabled TOTP or a sufficiently strong same-target grant; locked commit and generation invalidation |
| Reset another account's 2FA | Canonical and compatibility routes delegate to one handler; self-reset refused; selected ID and acting-admin proof required; authenticator and recovery codes revoked atomically with the session generation; no new seed issued to the admin |
| Regenerate recovery codes | Panel reset restricted to non-admin targets; acting-admin proof and locked target required; bcrypt hashes stored; plaintext returned only after a successful write |
| Manage server/agent access | Admin/action token, selected account ID, same-target step-up; permissions and access commit together; revocation triggers existing socket/job/schedule cleanup |
| Suspend/delete accounts | Selected ID and target-bound single-use token; acting-admin proof; suspension rechecks non-admin target at commit; deletion rejects self/last-active-admin and preserves atomic cleanup |
The user enrolls a replacement authenticator from their own account settings; the admin reset is not QR-code provisioning. A missing or weaker/other-target grace grant does not remove backend verification. Token refreshes preserve the original selected account ID and cannot silently retarget a recreated email. The inspected client escapes account emails and recovery-code rendering. No additional confirmed account authorization bypass was found in this pass. Minor wording or dialog feedback issues were not treated as vulnerabilities, and no new UI button or UX redesign is recommended here.
Rate-Limit Assessment
Numbers below count requests/attempts, not just successful operations. Session/account tiers share the same window but use separate counters.
| Surface | Budget | Assessment |
|---|---|---|
| Optional global limiter | Stored setting: 300/IP per 120 seconds; currently disabled | Not currently restricting settings. If enabled, multiple users behind a NAT share it. The view's 5/120 placeholder is not the effective stored value; 5/120 would be too small for interactive use. |
| Shared destructive step-up | 8/session and 24/account per 10 minutes | Strict credential-guessing budget, not a page-request budget. Shared across sensitive settings actions. Keep separate from ordinary browsing. |
| Account password/TOTP verification | 10/session and 30/account per 10 minutes, separate credential and TOTP families | Reasonable for manual credential maintenance; multi-request verification flows consume more than one slot. |
| Panel user creation | 6/account and 24/source-IP-bucket per 10 minutes | Intentionally restrictive for batch provisioning; errors/token retries count. No demonstrated normal single-account creation failure due to this cap. |
| Recovery | 5/session and 15/account per 15 minutes | Strict recovery-guessing budget; verify and use requests share it. Not a general settings limiter. |
| Reinstall, template change, transfer | Each 5/session and 15/account per 10 minutes | Restrictive for bulk destructive work, defensible for manual operations; kept as separate budgets. |
| Server creation | 10/session and 30/account per 10 minutes | Suitable for small manual setup batches; not unlimited bulk provisioning. |
| Branding/background writes | 20/session and 60/account per 15 minutes | Headroom for manual edits and retries. |
| Store version application | 15/session and 45/account per 10 minutes | Headroom for manual installation work while bounding large-file operations. |
| Permission-token minting | 60/session and 180/account per 5 minutes | Above ordinary server-page navigation; independent of the global toggle. |
| Database-user changes/selected reads | Writes: 30/session, 90/account per 10 minutes; reads: 120/session, 360/account per 5 minutes | Above manual user management and refresh cadence; install polls do not consume this budget. |
| Webhooks | Reads: 60/session per 5 minutes; writes: 40/session and 120/account per 5 minutes; tests: 15/session per 5 minutes | Reasonable for manual configuration/testing; separate from credential verification. |
| Panel/node updates | Checks/actions: 30/session per 10 minutes; installs: 10/session per 15 minutes | Above ordinary operator cadence; install and general action counters are separate. |
| Install/transfer/node-stat polling | 240/IP-bucket+user per minute, only when the optional global limiter is enabled | Generic-budget exemptions prevent polling from starving settings writes. One install polls about 30/minute, transfer 40/minute, and stats 12/minute. |
| Logout | Dedicated 10/identity per 10 minutes, generic-budget exempt | Ordinary logout remains reachable after generic budget exhaustion. |
An enabled-2FA Accounts action commonly submits a password first and then the password plus TOTP, using two shared verification slots. Fresh authorization of four unrelated targets can therefore exhaust the eight-slot session budget within ten minutes; same-target sufficiently strong grace reuse avoids fresh credential submissions and is itself capped. This is a concrete operational constraint, not proof of a security bug. Raising credential budgets to enable bulk work would weaken online guessing protection. No global toggle/value or existing per-session cap was raised by this audit.
The global toggle does not disable the always-on credential and operation budgets above. Cheap admin-only reads are not all separately budgeted, and this audit does not claim blanket rate-limit coverage of every panel route. No current normal polling over-throttle was reproduced. Live traffic is needed to size enabled global/NAT budgets or to authorize a separate bulk- administration policy change.
Verification and Deployment
- Focused account, eviction, deletion, history, real express-rate-limit, and route-wiring checks passed after each affected repair.
- Reset continuation: 95 account, alias, stale-target, authentication-race, and eviction/source-contract tests passed. The final extended 15-test account suite also confirms old recovery-proof spending is refused.
npm test: 4,149 tests, 4,140 passed, 9 skipped, zero failures.go test .: passed with the cached Go 1.26.9 executable andGOTOOLCHAIN=local; no Go production code was changed.- The read-only lifecycle verifier passes 18 checks after aligning its SQL ownership and delegation checks with the shared credential/account services. Its source checks are not live database or session-store integration proof. The older standalone account-limiter script copies historical configurations and is not used as evidence of current application limiter coverage.
- Editor diagnostics are clean for changed JavaScript. Source assertions were redirected to the extracted owning factories rather than lowered or removed, and the suspension response fixture was updated for atomic SQL. Saved-login restore, pending-login/captcha proofs, and credential-revert races also pass with the single generation-bound fingerprint utility.
These checks executed modules/extracted handlers with synthetic accounts, database state, and shared fake stores, plus disposable loopback test servers. They do not establish live InnoDB lock scheduling, real Redis availability, browser acceptance against production accounts, or deployed worker version. The application itself was never imported into tests or started for this audit.
Before deployment, quiesce affected mutations and drain incompatible old workers/CLI writers as described in the earlier cutover notes. A rolling overlap is not proven safe. The new operation-key bindings start fresh counter windows; exact cross-worker budgets require shared Redis. The suspension fix uses the already-existing epoch column and does not change passwords or TOTP secrets. Saved-login fingerprint compatibility requires the fresh-login behavior described under A01. History cleanup does not require new schema beyond the history service's existing migration. No live schema migration, account purge, service restart, or deployment was performed here.
Current Follow-Up Repairs
The subsequent Accounts audit identified four substantive issues repaired in this working tree. The minor cross-tab 2FA password-dialog retry issue is intentionally deferred, following the request to avoid unnecessary UI work. No frontend files or operator security configuration were changed by these follow-up repairs.
| Finding | Repair | Regression Coverage |
|---|---|---|
| In-flight administrator revocation | services/account-actions.js locks and checks the acting administrator's original ID, active status, and verified session_epoch. Creation, password/2FA/recovery resets, access/permission changes, suspension, and deletion use this guard. Bcrypt and session/network operations remain outside the transaction. |
Real creation-handler interleaving, stale/deleted actor, healthy commit, target identity, rollback, and last-active-admin tests |
| Deleted-account assistant history disclosure | services/dashboard-assistant-history.js owns user-ID-bound history. Async request context retains the original user ID through provider calls/retries. Writers lock the user row; panel and CLI deletion share transaction-local history cleanup. Startup cleanup removes orphaned assigned history. | Replacement email cannot read assigned or legacy chats; late writes cannot switch accounts; write-before-delete cleanup; legacy-schema and SQL-failure tests |
| IP-resettable settings operation budgets | services/settings-rate-limiters.js uses the shared account/session machinery in utils/login-throttle.js. Recovery, reinstall, template change, server creation/transfer, branding writes, store apply, and permissions minting keep their original per-session cap and gain a three-times-cap account backstop. | Real express-rate-limit with shared fake stores: IP rotation, fresh sessions, email change with the same ID, separate workers, independent users, Retry-After, and store-error contracts |
| Unbudgeted database-user mutations | One shared gate covers all six generic/MongoDB user create/password/delete routes, after the existing admin gate. Writes allow 30/session and 90/account per 10 minutes; settings/token-issuing reads allow 120/session and 360/account per 5 minutes. Existing one-time tokens and concurrency mutexes remain. Install-progress polling stays on its existing budget. | Six-route census, case/trailing-slash/HEAD matching, read issuers, poll exclusions, and cross-session budget exhaustion |
Follow-Up Deployment Conditions
- Do not overlap old workers or old account-management CLI processes with this code. Drain affected writes and stop incompatible processes before the cutover; maintenance mode alone does not quiesce admin writes.
- The assistant history service adds nullable
user_idand its owner index to the existing chat table when its schema initializer runs. The panel's database account needs the existing CREATE/ALTER privileges. Schema initialization failures refuse history access instead of falling back to email-only ownership. No migration was executed against production here. - Existing chats have no trustworthy immutable owner stamp. They remain
user_id IS NULL, retained but inaccessible to the patched reader. There is deliberately no automatic email-based backfill, which would re-create the disclosure. Any later recovery/mapping needs independent ownership evidence and separately authorized operator work. Fresh chats are assigned to the authenticated owner's ID. - Existing self-service credential limits, admin password/TOTP prompts, account-role policies, recovery-reset restrictions, and the operator's global rate-limit toggle/values are unchanged. New limiter keys begin fresh windows at deployment. Dedicated limiters retain the established Redis-error fail-open and per-process no-Redis fallback posture; exact cross-worker budgeting requires shared Redis.
Follow-Up Verification
npm test: 4,131 tests, 4,122 passed, 9 skipped, zero failures.go test .: passed with the cached Go 1.26.9 executable andGOTOOLCHAIN=local; no production Go code changed.- Syntax/editor checks passed for changed services/adapters. The focused
backend/test diff passes
git diff --check. Existing unrelated frontend whitespace was left untouched.
The tests run real services/extracted handlers with synthetic database/session state. They do not prove actual InnoDB scheduling, live Redis behavior, mixed- version deployment compatibility, or production browser acceptance. No real accounts, production database writes, installs, service restarts, or deployment were performed. These verification gaps remain explicit deployment checks, not reasons to describe the panel as bug-free.
Implementation Results
The following F01-F07 table records the earlier repair campaign; the current follow-up work and its verification are recorded above.
| Finding | Implemented Repair | Main Regression Coverage |
|---|---|---|
| F01 | utils/destructive-action-credentials.js is the shared strict parser for limiter admission and step-up verification. Non-string values cannot reach credential checks. | Step-up proof-strength tests and real express-rate-limit admission tests |
| F02 | services/account-actions.js commits the locked target server's ACL and account access together. Unrelated index upserts preserve existing ACLs. Account deletion and orphan cleanup use compatible fresh locking reads. | Atomic account-action, wildcard-revoke, and last-admin transaction tests |
| F03 | Account mutations require the original selected numeric expectedTargetId; scopes are user-id:<id>. Delete/suspension tokens bind ID and email. public/js/settings-account-targets.js prevents refreshed tokens from retargeting pending dialogs. |
All-route stale-target census, resource-token nonce tests, separate-worker scope tests, and reset retry tests |
| F04 | services/account-credentials.js checks the admin password override's ID-keyed mutation result before eviction. Zero matched rows return the existing stale-target 409. | Vanished-target and eviction-warning tests |
| F05 | services/security-policy.js uses the existing cross-process mutex and atomic-file writer. Only a committed candidate is published; failed writes preserve disk and live state. | False/throwing writer, concurrent startup, and commit-order tests |
| F06 | The same policy store persists a shared window revision. services/global-rate-limit-owner.js adopts revision as well as window and derives Redis namespaces from the shared revision, not its local diagnostic counter. | Rebuilt/restarted worker budget, missed revision, manual-edit reconciliation, and successive rename watcher tests |
| F07 | services/destructive-action-grants.js validates shared grant state without requiring a local cache entry. Reuse metadata is refreshed from the shared count. | Empty-cache, separate-worker concurrent reuse, revoked-row, and legacy-strength tests |
The original F01-F07 repairs preserved account roles, acting-admin password/TOTP prompts, owner-led 2FA enrollment, the non-admin recovery-code reset policy, configured budgets, and visible Accounts controls. The current follow-up adds the dedicated operation budgets described above. The permission GET remains read-only; target identity preconditions apply to mutations.
Deployment Notes
- Drain affected writes and stop incompatible old workers before starting the patched workers. Maintenance mode does not block admin writes. Do not overlap old whole-index ACL writers/email-scoped authorizers with the new implementation unless a separate compatible deployment barrier is proven.
- No new database columns are required for the original F01-F07 repairs. Permission writes use the existing users, servers, user_access, and destructive_action_grants tables and database row locks. The follow-up history ownership column is described separately above.
- Mutating Accounts callers must submit the positive numeric selected
expectedTargetId. The bundled client receives it from the account-listidfield, and the settings script version is bumped to refresh browser caches. Legacy clients/tokens must reload; email-only mutations cannot silently target a recreated row. Old email-scoped grants do not match new account-ID scopes, so they require fresh verification. - At patched startup, the security policy store initializes/reconciles
rate_limit_revisionandrate_limit_revision_window_msunder the shared file mutex. Initialization completes before listening. Keep the settings directory writable by the panel account; failure is a startup error, not an uncoordinated per-worker revision. Operator limit/toggle values are not changed. The first revised namespace resets the optional global counters. - Manual file edits and later atomic saves reconcile under the same policy lock. The directory watcher survives successive atomic renames. New workers sharing this file and Redis adopt the same committed revision. The existing Redis-error and no-Redis fallback posture is preserved.
Verification Limits
The required repository gates passed after the follow-up repairs:
npm test: 4096 tests, 4087 passed, 9 skipped, zero failures.go test .: passed using the already cached Go 1.26.9 toolchain.
The dashboard-assistant cache failure exposed a real shared-cache defect. Atomic replacements with equal byte lengths and equal modification timestamps were invisible to the old key. utils/config-revalidation.js now includes device/inode identity. A deterministic same-size, same-mtime replacement regression in tests/config-revalidation.test.js fails before the fix and passes afterward; existing cache consumer tests pass. The TTL and existing load-failure behavior are preserved.
The five backup-restore failures were missing test fixtures, not a reason to weaken production safety. backup_copydir_containment_test.go and backup_staging_budget_test.go now reuse the existing Docker inspect stub to establish a definitively absent container. Successful restore and staging-failure assertions now execute hermetically. Live-container refusal and restart-policy recovery tests still pass, and no production Go code changed in this follow-up.
Three bundle-version source assertions also required alignment with the newer settings script version. They still reject stale bundles, and the branding test verifies the account-target helper loads before its settings consumer.
Fake-state concurrency tests cover the real transaction functions but are not proof of actual InnoDB scheduling. Disposable MySQL integration remains a separate verification requirement; no live database was used. Production UI and deployment behavior were not exercised against real accounts. Passing repository gates does not establish that the whole panel is bug-free. No production service was restarted or deployed during these repairs.
Instructions for the Implementing Agent
Repair the seven findings below, not the Accounts UX. Preserve the current admin/non-admin account model and the documented per-route security contracts. Read AGENTS.md first. Inspect the current implementation before editing: references below identify the audited code, not immutable line numbers.
The workspace already contains substantial uncommitted work. Preserve it. Do not reset files, create a branch, commit, regenerate production configuration, or operate on real accounts unless separately authorized. Do not require index.js from tests: requiring it boots the application. Use the existing dependency-injection and VM-extraction testing patterns.
Do not claim that a patch is bug-free. Completion requires the behavioral checks below, the repository test gates, and an explicit account of anything that could not be verified.
Evidence and Deployment Conditions
The audit traced views/settings.ejs through public/js/settings.js to its backend handlers and shared services. Reproductions executed real extracted functions or modules against fake account, database, or Redis state. Some used the real Express, express-rate-limit, rate-limit-redis, and Speakeasy libraries with fake stores. They did not operate on production data or prove actual InnoDB lock scheduling.
Tests in 20 targeted regression files passed during the audit. Passing those
tests does not cover the newly reproduced scenarios. The full npm test and
go test . gates were not run as part of that read-only audit.
The checked-in ecosystem.config.js specifies one worker. scripts/generate-ecosystem.sh can generate multiple workers. Do not assume either that production currently has multiple workers or that supporting only one worker is a valid repair.
The audited security.json disables the optional global limiter and stores a limit of 300 requests per 120 seconds. Dedicated credential limiters still apply. Do not edit this operator configuration as part of the repairs.
| ID | Finding | Severity | Required Conditions |
|---|---|---|---|
| F01 | Credential type mismatch bypasses step-up throttles | High | Authenticated admin session; alternate install-verification path |
| F02 | Accounts ACL save overwrites unrelated server state | High | One worker for deleting-row loss; concurrent workers for lost ACL updates |
| F03 | Account authorization follows a reused email | High | Target deletion/recreation during an action or a live verification grant |
| F04 | Password reset succeeds after a zero-row update | Medium | Target disappears between lookup and update |
| F05 | Failed settings persistence changes effective policy | Medium | Security configuration write fails |
| F06 | Local limiter generations split shared budgets | Medium | Multiple workers with different policy/restart histories; global limiter enabled |
| F07 | Local grace cache rejects valid shared grants | Medium | Subsequent request reaches a different worker |
These are not unauthenticated account-management endpoints. Do not describe the findings as bypassing the existing session/admin/action-token gates.
Repair Order
- Record the current worktree and run a focused baseline. Add deterministic failing regression cases for the slice being repaired.
- Fix F01 in one shared credential parsing/classification implementation.
- Fix F04 using the existing stale-target outcome and loaded row identity.
- Design F03 and F02 together: immutable account identity, transactional ACL mutation, and compatible locking across account deletion and ACL writers.
- Fix F07 after the account-scope contract is settled. The shared grant row must remain authoritative for validity, scope, strength, and reuse.
- Fix F05 and F06 together: one persisted policy transition and one shared revision read consistently by all workers.
- Run focused tests after each substantive change, then full required gates. Re-read the diff and search the sibling writers/callers before finishing.
Extract the affected responsibility before adding machinery to the frozen monoliths. Reuse existing services/helpers where suitable; never require the monolith back from a service. Avoid a broad rewrite of unrelated routes.
Deployment Compatibility
Do not promise a safe mixed-version rolling rollout merely because the new source passes multi-worker tests. An already-running old worker can still write stale ACL snapshots, accept email-scoped grants, or use a different limiter namespace. Schema compatibility does not make those writes compatible.
Specify an operator-controlled cutover that quiesces the affected mutations, drains in-flight writes, and removes all incompatible workers before enabling the repaired behavior. Maintenance mode alone is not a write barrier because admins bypass it. An alternative rolling strategy is acceptable only with demonstrated mixed-version compatibility and an authoritative shared barrier. Do not execute this deployment or restart services while implementing tests.
Plan shared-policy initialization and old-grant/token invalidation as part of that cutover. Test both new-code multi-worker operation and the explicitly permitted deployment overlap; do not infer the latter from the former.
F01: Credential Types Bypass Verification Limits
Owning Code
- index.js:
hasDestructiveActionCredentialPayload. - index.js: session and account verification limiters.
- index.js:
verifyDestructiveActionStepUp. - index.js:
requireDatabaseInstallStepUp. - index.js: database install-verification endpoint.
Root Cause and Reproduction
The limiter treats credentials as present only when their payload values are strings. The verifier accepts a numeric TOTP by converting it to a string. Unlike the main destructive-action helper, the install helper can call the verifier without first enforcing that credential-presence predicate.
With one authenticated admin session and no grace, 12 incorrect numeric TOTP submissions reached verification and returned 403 rather than 429. A subsequent correct numeric code succeeded. The advertised session cap is 8 attempts per 10 minutes; the account cap is 24. This route verifies TOTP alone for a 2FA-enabled admin, so password knowledge is not a prerequisite here.
Required Repair
Use one strict parser/classifier for both limiter admission and verification.
Keep browser-compatible six-digit string codes, including leading zeroes.
Reject numeric, array, object, and boolean credentials before verification;
do not normalize them into accepted values with String(...).
Every request that can compare a password or verify a TOTP must be charged to the relevant verification budget. A malformed or absent credential may return a challenge without doing expensive verification; it must never reach verification through an uncounted alternate helper.
Inventory every caller of both step-up helpers. Keep the existing password-then-TOTP Accounts flow and the deliberate either/or behavior of other settings routes. Do not fix this by requiring passwords everywhere or raising the budgets. Preserve TOTP consume-on-success/replay protection.
Acceptance Tests
- Twelve numeric attempts cannot perform twelve unbudgeted TOTP verifications.
- Numeric, array, object, boolean, null, and malformed-string payloads cannot exploit another helper's coercion path.
- Valid string submissions exhaust the session budget on the ninth counted request; account-wide counting also survives session/IP rotation.
- A leading-zero string code still works when genuinely valid.
- A request with valid same-target grace performs no credential verification.
- Test the install helper and its setup/disable callers, not only Accounts.
Reuse tests/destructive-route-guards.test.js and the nearby step-up tests; add a focused test file only if no existing test is a suitable home.
F02: Permission Saves Rewrite the Whole Server Index
Owning Code
- index.js: Accounts
grant-permshandler. - index.js:
loadServersIndex, which excludes deleting rows. - index.js:
saveServersIndex, a full-table synchronizer. - index.js: process-local
withServersIndexWriteLock. - index.js: atomic account deletion and ACL cleanup.
Root Cause and Reproductions
An account ACL edit uses a whole-index read/mutate/save operation. The saver replaces full ACL values and deletes server rows absent from its input. The promise-chain lock cannot serialize different workers.
Two worker VMs read the same ACL snapshot. Worker A revoked an existing user's console/file-write permissions. Worker B then saved a grant for another user from its earlier snapshot. Both returned success, but the revoked permissions were restored.
In a separate one-worker reproduction, an unrelated server had status
deleting. The loader excluded it; saving permissions for another server
removed the deleting server's index row without completing its daemon delete.
Required Repair
Implement a shared transaction for the specific account/server authorization mutation. It must resolve the real server identity, lock and re-read the relevant rows, mutate only that account's ACL entry, and write its access row on the same transaction connection. Use structured JSON parsing/serialization; do not concatenate an email into a raw SQL JSON path.
Reject a vanished or deleting server. Never push a phantom { name, acl }
stub. Never delete/reinsert unrelated servers as a side effect of an ACL edit.
Do not hide addAccessForEmail failures behind a success response.
A new row lock alone is not enough: an older whole-list snapshot writer can
wait for the lock, then overwrite the newly committed ACL. Search all ACL
writers, including saveServersIndex, upsert helpers, account deletion, and
server administration. Make their read/write discipline compatible with the
shared mutation, or ensure non-ACL writes cannot replace ACL snapshots.
Coordinate lock order with deleteUserAccountAtomically. Acquire user-related
locks before server-related locks in a consistent order; include the existing
administrator-survival locking behavior in that analysis. Do not nest the
non-reentrant promise-chain lock. Do not hold a database transaction while
performing session scans, network requests, schedule cancellation, or socket
teardown. Commit first, then invalidate caches and perform the existing
post-commit effects with truthful failure reporting.
Acceptance Tests
- Two workers updating different users on one server preserve both edits.
- Revocation followed by an unrelated grant never restores the revoked ACL.
- Permission saves leave unrelated deleting rows and companion data untouched.
- A target server deleted between lookup and commit is not resurrected.
- A target account deleted/recreated during the transaction receives no grant.
- Access-row failure rolls back the ACL mutation; there is no false success.
- Exercise an account deletion racing an ACL mutation in both commit orders.
- Inject SQL errors and deadlocks; verify rollback, connection release, and bounded failure behavior.
- Validate locking with separate connections against a disposable MySQL database where feasible. Fake-state tests alone cannot prove InnoDB locks.
Reuse the nearby access-step-up, last-admin transaction, wildcard-revoke, and account-deletion tests. Retain schedule/job reauthorization and existing audit effects; do not silently remove them during extraction.
F03: Authorization Is Bound to a Reusable Email
Owning Code
- services/admin-2fa-reset.js: email scope.
- index.js: access helpers re-resolve email to user ID.
- index.js: Agent flag update is email-keyed.
- index.js: account list and target-bound token issuance.
- index.js: destructive-action scope hashing/consumption.
Root Cause and Reproductions
user:<email> identifies an address, not the account row that was authorized.
Deleting and recreating that address preserves the scope hash.
A grant for deleted user ID 42 was reused against replacement admin ID 43 with the same email. The real grant machinery and 2FA-reset service accepted it and cleared the replacement's 2FA with zero fresh password/TOTP checks. The mutation was correctly ID-keyed to 43; that existing write guard did not repair the stale authorization scope.
An in-flight access grant separately loaded ID 42, then re-resolved the email after verification and inserted the access row for replacement ID 43.
Required Repair
Use one canonical scope helper based on the loaded immutable user ID, such as
user-id:<id>. Reject missing/invalid identities; never fall back to email.
The expected identity must also survive the mutation boundary. Do not resolve
the email again to select a potentially different write target.
For per-resource delete/suspension tokens, bind both canonical email and user ID. Validate against the current row before any destructive effect. Where the client selects an account, retaining that original row ID is mandatory, not optional. Add the ID to the account-list payload and keep the selected identity in the existing JS state/maps; there is no need for a new visible control. Preserve generic repeatable action tokens where their per-route contract deliberately permits target selection, but require the mutation's target row to match the account the pending action selected.
The existing automatic token refresh reloads Accounts and resends by email in public/js/settings.js and public/js/settings.js. Do not reuse that retry unchanged: a fresh token for replacement ID 43 must not silently replace the pending action's selected ID 42. Carry and validate expected target identity through every challenge, token refresh, retry, and final request. A changed identity stops the action and requires deliberate reselection, even if the request includes valid acting-admin credentials. Client identity is a precondition, not authorization; verify it server-side against the resolved row. A legacy/missing-identity request must fail closed or force a safe refresh, never silently authorize a newly resolved account at the same email.
Apply the scope change to access add/remove, Agent access, permission grants, suspension, deletion, password reset, recovery-code reset, and both 2FA reset aliases. Session-revocation scopes also identify account owners: inspect them for compatibility without weakening their separate peer-admin safeguards.
Enforce loaded-row restrictions at commit time. Use guarded writes/locking
appropriate to the operation, and return a stale-target 409 on a race. A
non-admin-only operation must not mutate a target promoted to admin during
the request. Salted writes and idempotent setters have different
affectedRows semantics; do not make legitimate unchanged setters fail by
assuming every zero-row result means the account disappeared.
Old email-scoped grants must not be accepted as equivalent to new ID scopes.
Invalidate them or require fresh verification. Refresh old resource tokens
using the identity-safe invalid-token/reload flow above. Preserve
literal-percent email handling: Express has already decoded
req.params.email once.
Acceptance Tests
- Old grant for ID 42 cannot authorize replacement ID 43 at the same email.
- Same account ID remains the same target after an email change, subject to existing session/credential validity requirements.
- Wrong-target, old-format, expired, revoked, or spent grants fail closed.
- Old delete/suspension token does not authorize a recreated target.
- Automatic delete/suspension token retries cannot retarget a recreated email, including when valid actor credentials accompany the retry.
- Expired-token refresh and step-up challenge renewal still succeed for the same selected ID while preserving nonce, TTL, and single-retry behavior.
- Access add/remove and Agent toggles never write to a replacement ID.
- Repeated unchanged Agent/suspension setters distinguish a live no-op from disappearance without falsely reporting a stale target.
- Permission grants and deletion cannot leave orphan ACLs/access rows.
- Preserve literal
allwildcard handling, specific access rows after wildcard removal, and canonical/legacy server-name resolution. - Both 2FA-reset aliases keep distinct action-token names and share one service.
- Actor credential proof strength and target restrictions remain enforced.
Extend tests/admin-reset-target-pinning.test.js, tests/stepup-grace-proof-strength.test.js, and tests/email-param-single-decode.test.js.
F04: Password Reset Ignores the Mutation Result
Owning Code
index.js: admin per-account password update and subsequent
email-based eviction. The 2FA reset service already has a suitable
stale-target outcome; use its STALE_TARGET_409_MESSAGE rather than another
independent message string.
Root Cause and Reproduction
The ID-keyed update can match zero rows after a concurrent deletion. Its result is discarded. The handler still reports success and evicts sessions for the address, potentially affecting a newly recreated account. It does not overwrite the replacement account's password.
Required Repair
Check that the guarded update changed exactly one expected row before any success, session sweep, socket disconnect, or successful-reset audit entry. Otherwise return the established stale-target 409. DB failures remain 500.
Keep the admin reset's deliberate last-writer override: do not add a password
snapshot CAS merely to fix this missing outcome check. Keep the fresh session
epoch in the same statement as the password and use the existing generator.
Check the db.js wrapper's result shape rather than copying native
connection.execute tuple destructuring into db.query callers.
Acceptance Tests
affectedRows: 0produces 409 and no eviction, disconnect, or success.- A replacement account's password, epoch, sessions, and sockets are untouched.
- A successful write preserves policy validation, hashing, atomic epoch bump, remember-login revocation, and incomplete-eviction warnings.
- SQL error/timeout is not success and triggers no post-write effects.
Reuse tests/credential-reset-eviction-surfacing.test.js and the existing credential mutation tests.
F05: Failed Security Save Changes Live Policy
Owning Code
index.js: security settings handler.
index.js: safeWriteJson returns a boolean and swallows
write errors.
Root Cause and Reproduction
The handler mutates the live object before persistence, ignores a false write result, applies the limiter, and returns success. With a fake writer returning false, the request disabled the worker's limiter and changed its window despite no successful disk save. Other workers and a restart can retain the old policy.
Required Repair
Under the existing cross-process configuration serialization convention, read
fresh state, validate a candidate, persist it atomically, and only then publish
it to live readers and apply the policy. Reuse the existing atomic-file and
configuration-lock utilities after checking their APIs; do not globally rewrite
safeWriteJson for unrelated consumers.
A failed write must leave the old object, limiter instance, revision, and operator file unchanged and return 500. Retain unrelated configuration fields. Avoid truncation/partial JSON visibility. If publication/watch handling changes to atomic rename, verify watcher inode/re-registration behavior so other workers continue receiving later saves.
Acceptance Tests
- Writer returns false or throws: 500, no live changes, no policy apply.
- Successful persistence precedes publication/rebuild and survives reload.
- Failure between staging and rename leaves valid previous JSON.
- Concurrent saves cannot discard unrelated settings or publish different policy revisions for one committed transition.
- Other workers observe subsequent atomic saves, not just the first rename.
Extend tests/global-limiter-rebuild-on-save.test.js and tests/settings-routes-async-containment.test.js.
F06: Worker-Local Counter Generations Split the IP Budget
Owning Code
services/global-rate-limit-owner.js:
generation and the rl:g<generation>: store prefix.
Root Cause and Reproduction
One worker rebuilt after a window change and used generation 2. A newly started worker loaded the same current policy but used generation 1. With a limit of two, two requests passed each worker: four total before both refused. The workers shared Redis; their prefixes prevented sharing the same budget.
Required Repair
Assign one persisted policy revision when the window transition commits. Every worker loading that revision must derive the same counter namespace, including restarted workers and workers that missed intermediate changes. Initialize a missing revision once under cross-process serialization; never generate a different boot revision independently in each worker.
The existing hand-edited-file watcher is also a policy writer/observer. Define how a manual window edit with an absent or retained revision is reconciled under the same serialization, so it cannot reuse an obsolete namespace or cause workers to mint different revisions. A persisted record of the revision's effective window can distinguish a changed window from a revision that already describes that window. All observers must then adopt the same committed result; do not rely solely on which watcher ran first.
Adoption must compare shared revision as well as effective window. A worker
can miss 120 -> 600 -> 120 and see the same window but a different revision;
its local limiter still needs the current namespace. Returning early solely
because the window matches leaves that worker on obsolete counters.
Maintain separate store instances per limiter/rebuild. A changed effective window requires a new construction/store; limit changes remain live and flag flips preserve counters as they do today. Do not use a PID, local increment, or worker-random value as the shared prefix. A window-only hash needs special care because reverting a window can reuse old buckets; a persisted revision avoids that ambiguity.
Preserve trusted-subnet/exempt-path behavior, IPv6 bucketing, Retry-After, JSON 429 responses, and the documented Redis-outage fallback. Keep the new revision and F05's candidate policy in the same successful persistence.
Acceptance Tests
- Fresh workers with the same revision share one limit, not one per worker.
- Rebuild worker A, restart worker B, then interleave requests: aggregate admission remains the configured limit.
- Repeated watch/apply calls do not reset counters or create new revisions.
- A worker missing an intermediate policy update converges on the current prefix, window, and revision.
- A worker missing a window round trip adopts the new revision even when its old and current effective windows are equal.
- Manual window edits with missing or retained revision fields are reconciled once, and multiple observers/restarted workers converge on the result.
- Limit-only/flag-only changes preserve intended counter semantics.
- Failed saves create no enforcing generation; new windows seed the right TTL.
- Test initial deployment with old-format configuration and rolling restarts.
- Enforce the deployment cutover barrier for incompatible old workers, or demonstrate compatibility during every explicitly permitted overlap.
Extend tests/global-limiter-rebuild-on-save.test.js using its real limiter/fake Redis harness with multiple owner instances.
F07: Local Memory Is Required Before Shared Grant Validation
Owning Code
- index.js: local grace-state lookup.
- index.js: authoritative-looking async lookup returns early when the receiving worker has no memory entry.
- index.js: atomic database reuse consumption.
Root Cause and Reproduction
A grant present in the session and shared database is absent from another worker's map. That worker clears the session grant and returns null before reading the database. A two-VM reproduction showed the minting worker accepted the grant while the other worker rejected it and performed zero shared reads. This is fail-closed, but it breaks promised reuse and adds verification demand.
Required Repair
Make shared database verification authoritative. Missing local cache state must cause a bounded shared lookup, not revocation. Reconstruct validated state from the candidate and shared row only after checking all bindings. Local memory may be an optimization, not a necessary proof or an authority that can accept stale/revoked rows by itself.
Preserve actor ID/email/session binding, grant-secret HMAC, IP/user-agent
binding, proof strength, expiry, revoked state, target scope, and atomic reuse
cap. Use the database's current use_count for remaining-use metadata; do not
trust a stale worker/session count. Unavailable or unadjudicable shared state
must still deny reuse and require fresh proof.
Review synchronous informational consumers during extraction. They must not make authorization decisions from unverified local state. Preserve the existing session/credential-generation gates; do not widen a grace window across an actor password/2FA reset or session revocation.
Acceptance Tests
- Worker B accepts A's valid same-session, same-target grant without fresh credentials or clearing it merely because its local cache is empty.
- Different SID, account, grant secret, IP, user-agent, target, expired row, revoked row, or insufficient proof strength denies reuse.
- Legacy/missing
proof_strengthdegrades conservatively: unknown strength cannot satisfy a password-first gate, while existing weaker-gate policy is preserved. - Concurrent cross-worker consumption cannot exceed the cap.
- Remaining-use metadata follows the database after another worker consumes.
- Two workers reading the same pre-consumption count cannot report authoritative
remaining uses by calculating only stale
useCount + 1; check the committed shared count with concurrency-aware expectations. - A stale positive cache cannot override a revoked/removed shared row.
- DB timeout/failure fails closed with a bounded response, not an async hang.
Extend tests/stepup-grace-proof-strength.test.js with shared database state and genuinely separate worker maps/session copies.
Existing Contracts That Must Not Regress
- Only an authenticated, unsuspended admin can access Settings/Accounts APIs.
- Normal account creation remains distinct from admin creation. The latter proves the acting admin's password and enabled TOTP. Do not accidentally change its credential field names or attach the wrong shared budget.
- Account creation does not return TOTP seeds or recovery codes to the admin.
- Admin 2FA reset clears the target's secret; it does not generate a new seed for the admin. The user re-enrolls themselves after signing in.
- Admin recovery-code reset permits non-admin targets, returns their codes by the current contract, and refuses admin targets server-side. Do not redesign this product policy while repairing identity binding.
- No target-admin password/TOTP proof is required for Accounts actions. Prove the acting admin only; preserve the Sessions route's separate peer-admin rule.
- Preserve password policy, bcrypt's 72-byte limit, TOTP replay claims, and atomic credential/session-epoch changes through existing helpers.
- Preserve self-delete/self-reset refusals, transactional last-active-admin protection, owned-record/ACL cleanup, and pre-commit deletion eviction.
- Preserve action-token scope/nonce/expiry behavior and one-time token renewal on challenges. A failed step-up must not strand legitimate retries.
- Preserve single percent decoding of email parameters, input validation, CSRF/read guards, and uncacheable sensitive responses.
- Preserve session, remember-login, SSH, socket, schedule, and queued-job revocation/reauthorization effects and truthful partial-failure warnings.
- Shared handlers must contain async failures under Express 4 and answer once.
- Do not add best-practice buttons, change layout, broadly increase quotas, weaken assertions, or delete tests to make the suite pass.
Rate-Limit Policy: Do Not Confuse Limits with Bugs
| Surface | Audited Dedicated Budget | Repair Implication |
|---|---|---|
| Account creation | 6/account + 24/IP per 10 minutes | Separate from shared step-up limiter; failures also count |
| Shared settings verification | 8/session + 24/account per 10 minutes | Fix F01/F07; do not silently loosen |
| Self-service password change | 10/session per 10 minutes | Preserve |
| Webhooks | Reads 60, writes 40/session + 120/account, tests 15 per 5 minutes | Preserve |
| Update actions/installations | 30/10 minutes; 10/15 minutes | Preserve |
| Optional progress polling | 240/IP+user per minute | Keep generic-budget exemption and dedicated accounting |
| Server creation/template change/transfer | 10; 5; 5 per 10 minutes | Preserve operation budgets |
| Branding writes | 20 per 15 minutes | Preserve |
A fresh Accounts password-then-TOTP interaction normally submits the password once, receives the TOTP challenge, and submits both proofs. That is two credential-bearing requests. Four fresh target verifications can consume the 8-request session window without incorrect credentials. Valid same-target grace avoids further credential checks, subject to expiry/reuse limits.
This is a conservative operating policy, not automatically a defect. Account creation currently mounts its own two limiters, not the shared step-up pair. Keep that distinction explicit in tests and comments. Repair worker reuse and type-mismatch bugs before proposing separately authorized tuning.
Verification and Completion
Add behavioral regressions, not only checks for middleware names in source. Each reproduced failure should become a test that fails before its repair and passes afterward. Reuse existing fake-store/VM helpers where practical.
Focused audit baseline:
node --test --test-reporter=dot \
tests/admin-create-throttle-identity.test.js \
tests/admin-create-2fa-nonrepudiation.test.js \
tests/admin-stepup-password-first.test.js \
tests/admin-2fa-reset-preflight.test.js \
tests/admin-reset-target-pinning.test.js \
tests/account-delete-session-revocation.test.js \
tests/last-admin-transactional-guard.test.js \
tests/credential-reset-eviction-surfacing.test.js \
tests/stepup-grace-proof-strength.test.js \
tests/audit-l3-l5-access-stepup.test.js \
tests/email-param-single-decode.test.js \
tests/password-policy-parity.test.js \
tests/settings-action-token-refresher.test.js \
tests/settings-routes-async-containment.test.js \
tests/global-limiter-rebuild-on-save.test.js \
tests/progress-poll-budget.test.js \
tests/limiter-ipv6-bucketing.test.js \
tests/trusted-subnet-limiter-bypass.test.js \
tests/session-account-binding-pins.test.js \
tests/wildcard-revoke-conflict.test.js
Required final repository gates:
npm test
go test .
Full tests may use temporary fixture files/services. Verify isolation before running them; do not point integration tests at production databases or Redis. Source-structure tests must be updated consciously when extracting code, while retaining their original security assertions as executable behavior where appropriate. Do not treat a previously green baseline as proof of a fix.
The final implementing-agent report must list F01-F07 with the actual change, covered siblings, regression tests, and outcome. Include migrations, old-token invalidation, shared-policy initialization, rolling-restart behavior, and any unverified MySQL concurrency or deployment requirements. Mark remaining failures honestly; do not claim all seven are repaired when only one adapter or one worker path was changed.