ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
docs: record security review and remediation handoff
Juan Denis3068fc81f091
diff --git a/docs/reviews/2026-09-05-remediation.md b/docs/reviews/2026-09-05-remediation.mdnew file mode 100644index 00000000..60c71554--- /dev/null+++ b/docs/reviews/2026-09-05-remediation.md@@ -0,0 +1,65 @@+# ServerKit review remediation — 2026-09-05++This records the implementation following [the original review](2026-09-05-serverkit-review.md). The original report describes the pre-fix checkout and remains historical evidence. The changes are committed locally on `dev`; no push or production deployment was performed.++## Local implementation commits++| Commit | Scope |+| --- | --- |+| `c8c93a8e` | Authentication, scoped API keys, passkeys and session revocation |+| `785c5780` | Socket subscriptions and authorized event delivery |+| `6bf34903` | AI resource access, redaction and chat limits |+| `c62358de` | Settings tables, access review and browser regressions |+| `da0f1814` | Security CI coverage and narrow Bandit exceptions |++The review, historical reproduction probes and this handoff are recorded in a separate documentation commit.++## Implemented++| Review item | Change |+| --- | --- |+| MFA/login-link bypass | Pending tokens expire after five minutes and fail the common JWT policy. Login-link management requires a completed browser session, and redemption honors the target account's MFA policy. |+| Scoped API-key escalation | Keys cannot mint browser credentials. Restricted keys fail closed when the endpoint lacks an explicit scope declaration, and declared scopes are checked independently of the owner's role. |+| Socket authentication and room isolation | Require a valid access-token session; authorize user, application, server, deployment and run subscriptions. Revalidate sessions and resource access before delivery, including account/session revocation. Preserve authorized terminal and job streams. |+| AI resource authorization | Built-in tools receive the actual caller, reuse application/workspace visibility, return selected metadata, and recheck authority after write confirmation. Host-wide privileged tools require an administrator. |+| Password changes, disablement and logout | Password changes require the current password, or recent authentication for accounts without a local password. Password changes and account disablement invalidate earlier sessions; logout persistently revokes the current browser's access/refresh family. |+| AI protection gaps | Recursively filter structured read and write results, apply deterministic secret filtering, and return a visible error when enabled protections fail. Sanitize model context and restored conversations too. |+| Settings table backgrounds | Users and Invitations wrappers now own an explicit theme surface. Verified with actual components in Chromium in dark and light themes. |+| Access-review UI | Show MFA, passkey enrollment and sign-in provider; add an active-admins-without-TOTP view; use locale-aware dates, shared deletion confirmation, pending-action guards and visible invitation errors. |+| Regression coverage | Add authentication, API-key, socket, AI and passkey boundary tests; add a browser job for Settings surfaces and interaction states. |++Cross-review also found and repaired passkey compatibility with pinned WebAuthn 2.5.0. Registration and passwordless authentication now require authenticator user verification. Regression tests use real cryptographic signatures with synthetic credentials, including refusal of assertions without user verification.++## Additional hardening++- AI chat accepts at most 128 KiB request bodies and 16,000-character message/context limits. The panel permits one active turn per user and eight panel-wide. Streaming queues are bounded and cancellation-aware. These are concurrency and input limits, not aggregate billing quotas.+- Security CI now includes weekly/manual runs, extension sources and requirement files, a production npm audit, full Bandit report artifacts, and a narrow reviewed exception mechanism. Broad Bandit category skips were removed. Two existing FTP compatibility findings remain explicitly documented and tied to their function fingerprint.+- Browser coverage exercises active/disabled/filtered users, loading, empty/error states, table surfaces in both themes, guarded deletion, and invitation revoke failure with pending controls.++## Upgrade behavior++- Apply Alembic migration `097_user_auth_version` with the normal application upgrade. It adds the user authentication version and persistent revoked-session records; existing-install, fresh-install and downgrade paths have regression coverage.+- Existing JWTs intentionally become invalid. Users must sign in again after upgrading.+- Restricted API keys now return 403 for endpoints without `@require_scope`. Most previously API-key-capable routes have no declaration, so integrations using restricted keys need a reviewed endpoint scope policy. Do not broaden keys to full access as a substitute for defining that policy.+- Wildcard `*` and legacy empty-scope keys retain their existing full-access meaning, subject to the owner's role. JWT-only endpoints remain JWT-only.+- Passkeys that cannot perform authenticator user verification cannot complete passwordless login under the new policy. A verified passkey remains an independent sign-in method; the Users MFA column and saved view specifically reflect TOTP enrollment.++## Validation++- Final combined backend run: **295 passed** across the affected authentication, API-key, passkey, AI, socket, workspace, run, migration and error-shape suites.+- Frontend: 163 Node tests passed; lint and integrity checks passed with zero errors; production build passed. Existing lint and large-chunk warnings remain.+- Browser: Chromium passed the Settings scenarios in both themes. Screenshots are saved to `frontend/test-results/` and uploaded by the new CI job.+- Security scan: full Bandit 1.9.3 report passed the narrowed gate; seven exception-gate tests passed. The production npm lockfile audit reported zero vulnerabilities. The Python advisory audit was not rerun locally.+- Static/backend integration checks: 25 focused migration-inventory, error-shape, crash-reporting and authorization-boundary checks passed without raising ceilings.+- All security tests used local synthetic users, resources and credentials. Real WebAuthn signature verification was exercised; no external AI provider or production service was called. The full repository backend suite was not completed; validation focused on the affected security, workspace, run and migration suites.++## Remaining work and limits++- Aggregate per-user/panel AI spend accounting remains separate work. Starting another conversation can still start another per-conversation budget; the new concurrency limits do not cap daily spend.+- CSP still permits inline scripts and eval. Tightening it requires testing the production import map and extension runtime; no CSP enforcement change is included here.+- Extend browser coverage to API-key management and complete authentication navigation. Current browser tests use synthetic responses; backend authentication tests exercise the real Flask and WebAuthn boundaries.+- Plugin-contributed AI tools still need their own resource-authorization policy. The common wrapper checks the live caller and feature permissions; it cannot infer ownership rules for arbitrary plugin data.+- An existing account-deletion issue involving `audit_logs.user_id` under enforced foreign keys was found during cross-review. The new revoked-session records support account deletion, but this unrelated audit-log relationship still needs a focused fix.+- Existing lint warnings and large build chunks remain. There was no production penetration test, provider-billing test, load test or deployment.++The historical `2026-09-05-security-probes.py` intentionally asserted the old vulnerabilities. Use the new negative regression tests under `backend/tests/` for the fixed behavior.diff --git a/docs/reviews/2026-09-05-security-probes.py b/docs/reviews/2026-09-05-security-probes.pynew file mode 100644index 00000000..ef3571d3--- /dev/null+++ b/docs/reviews/2026-09-05-security-probes.py@@ -0,0 +1,117 @@+"""Review evidence: assertions describe observed defects, not desired policy.++To reproduce against this checkout, copy this file temporarily into backend/tests/+as test_review_20260905_probe.py and run it with that directory's pytest fixtures.+Remove the temporary copy afterward. These assertions must not become permanent+security tests: remediation tests should instead assert that the attempts fail.+Only synthetic users, database records and socket events are used; no AI provider+or production service is called.+"""+from flask_jwt_extended import create_refresh_token, decode_token+from factories import make_user, headers_for, make_application+++def test_review_pending_mfa_can_mint_full_login(client, db_session):+ user = make_user(db_session, role='admin', password='ReviewPassword123!', totp_enabled=True)+ login = client.post('/api/v1/auth/login', json={'email': user.email, 'password': 'ReviewPassword123!'})+ assert login.status_code == 200, login.get_json()+ pending = login.get_json()['temp_token']+ assert 'exp' not in decode_token(pending)+ headers = {'Authorization': f'Bearer {pending}'}+ assert client.get('/api/v1/auth/me', headers=headers).status_code == 403+ minted = client.post('/api/v1/auth/login-links', headers=headers, json={})+ assert minted.status_code == 201, minted.get_json()+ redeemed = client.post('/api/v1/auth/login-links/redeem', json={'token': minted.get_json()['token']})+ assert redeemed.status_code == 200, redeemed.get_json()+ full = redeemed.get_json()['access_token']+ assert not decode_token(full).get('2fa_pending')+ assert client.get('/api/v1/admin/users', headers={'Authorization': f'Bearer {full}'}).status_code == 200+++def test_review_read_scoped_key_can_mint_full_login(client, db_session):+ from app.services.api_key_service import ApiKeyService+ user = make_user(db_session, role='admin')+ key, raw = ApiKeyService.create_key(user.id, 'review-read-only', scopes=['apps:read'])+ assert not key.has_scope('write')+ minted = client.post('/api/v1/auth/login-links', headers={'X-API-Key': raw}, json={})+ assert minted.status_code == 201, minted.get_json()+ redeemed = client.post('/api/v1/auth/login-links/redeem', json={'token': minted.get_json()['token']})+ assert redeemed.status_code == 200, redeemed.get_json()+ assert 'refresh_token' in redeemed.get_json()+++def test_review_ai_lists_foreign_application(client, db_session):+ from app.services.ai_tool_registry import ToolDescriptor+ from app.services.ai_tools_builtin import list_applications+ from app.services.ai_service import _make_read_wrapper+ viewer = make_user(db_session, role='viewer')+ foreign = make_application(db_session, name='private-review-app')+ assert client.get(f'/api/v1/apps/{foreign.id}', headers=headers_for(viewer)).status_code == 403+ descriptor = ToolDescriptor(name='list_applications', qualified_name='core__list_applications',+ func=list_applications, description='review', parameters={}, rbac_feature='applications')+ result = _make_read_wrapper(descriptor, viewer)()+ assert foreign.id in [row['id'] for row in result]+++def test_review_disabled_user_keeps_jwt_access(client, db_session):+ user = make_user(db_session)+ foreign = make_application(db_session, user_id=user.id)+ headers = headers_for(user)+ user.is_active = False+ db_session.session.commit()+ assert client.get('/api/v1/auth/me', headers=headers).status_code == 200+ assert client.get(f'/api/v1/apps/{foreign.id}', headers=headers).status_code == 200+++def test_review_password_change_needs_no_old_password_and_keeps_refresh(client, db_session):+ user = make_user(db_session, password='OldReviewPassword123!')+ headers = headers_for(user)+ refresh = create_refresh_token(identity=user.id)+ result = client.put('/api/v1/auth/me', headers=headers, json={'password': 'NewReviewPassword456!'})+ assert result.status_code == 200, result.get_json()+ assert user.check_password('NewReviewPassword456!')+ renewed = client.post('/api/v1/auth/refresh', headers={'Authorization': f'Bearer {refresh}'})+ assert renewed.status_code == 200, renewed.get_json()+++def test_review_structured_ai_results_skip_redaction(monkeypatch):+ from app.services import ai_service+ monkeypatch.setattr(ai_service, '_pii_enabled', lambda: True)+ class Redactor:+ def redact(self, text):+ raise AssertionError('Structured output never reaches redactor')+ monkeypatch.setattr(ai_service, '_get_pii_redactor', lambda: Redactor())+ payload = {'email': '[email protected]', 'nested': [{'password': 'synthetic-review-secret'}]}+ assert ai_service._maybe_redact_result(payload) == payload+++def test_review_socket_accepts_pending_mfa_and_refresh(app, db_session):+ from flask_jwt_extended import create_access_token+ from app.sockets import socketio+ user = make_user(db_session, role='admin', totp_enabled=True)+ pending = create_access_token(identity=user.id, additional_claims={'2fa_pending': True})+ for token in (pending, create_refresh_token(identity=user.id)):+ sock = socketio.test_client(app, auth={'token': token})+ try:+ assert sock.is_connected()+ finally:+ if sock.is_connected():+ sock.disconnect()+++def test_review_viewer_can_join_other_users_socket_room(app, db_session):+ from flask_jwt_extended import create_access_token+ from app.sockets import socketio+ viewer = make_user(db_session, role='viewer')+ other = make_user(db_session, role='admin')+ sock = socketio.test_client(app, auth={'token': create_access_token(identity=viewer.id)})+ try:+ assert sock.is_connected()+ sock.get_received()+ sock.emit('join_room', {'room': f'user_{other.id}'})+ socketio.emit('review_synthetic_private_event', {'marker': 'private-test-only'}, to=f'user_{other.id}')+ events = sock.get_received()+ assert any(event['name'] == 'review_synthetic_private_event' for event in events), events+ finally:+ if sock.is_connected():+ sock.disconnect()diff --git a/docs/reviews/2026-09-05-serverkit-review.md b/docs/reviews/2026-09-05-serverkit-review.mdnew file mode 100644index 00000000..e009d822--- /dev/null+++ b/docs/reviews/2026-09-05-serverkit-review.md@@ -0,0 +1,159 @@+# ServerKit security and product review — 2026-09-05++Reviewed checkout: `6c2220c5`. Scope: authentication and MFA, API-key scopes, Socket.IO, AI tools and redaction, representative authorization tests, subprocess patterns, CI, and Settings table implementation.++The largest gap is consistent authorization across entry points. REST routes, API keys, sockets, and AI tools do not always enforce the same policy. Several bypasses below were reproduced locally with disposable database records. These are more urgent than adding features or redesigning the interface.++This was a source review with isolated Flask/Socket.IO tests, not a penetration test of the production deployment. No production accounts, credentials, services, or AI providers were used. Application source was not changed. Local frontend/backend servers were unavailable on the configured ports, so UI findings are based on source and compiled styles rather than a live visual walkthrough.++## Fix first++### 1. High: an MFA-pending administrator can obtain a full session without completing MFA++Evidence: `backend/app/__init__.py:455`, `backend/app/api/auth.py:294`, `backend/app/api/auth.py:325`, `backend/app/api/auth.py:395`.++The pending-token guard exempts any path containing `/auth/login`. This also exempts `/auth/login-links`. An admin's valid password produces a `2fa_pending` token; that token passes the login-link route's admin check and can mint a link. Redeeming that link returns ordinary access and refresh tokens without a second-factor challenge.++**Local proof:** real password login for a synthetic MFA-enabled admin; the temporary token got 403 on `/auth/me`, but 201 on login-link creation. Redemption returned 200, and the resulting access token successfully accessed `/api/v1/admin/users`. No TOTP or backup code was supplied.++There is a related expiry defect: `expires_delta=False` disables expiration. The comment says it uses a short default expiry, but the actual temporary token has no `exp` claim. This was verified against the installed library and the token generated by the login route; the [library documentation](https://flask-jwt-extended.readthedocs.io/en/stable/api.html#flask_jwt_extended.create_access_token) confirms the semantics.++**Fix:** use exact endpoint allowlists for MFA challenges; require completed authentication for login-link administration; give pending tokens an explicit short lifetime. Review redemption as an authentication method, including the target user's MFA policy. Add an end-to-end regression for this complete chain, not just a role check on link creation.++**Effort:** small emergency patch plus focused tests; follow with a broader authentication-boundary review.++### 2. High: an admin-owned read-only API key can become a full browser session++Evidence: `backend/app/middleware/rbac.py:27`, `backend/app/middleware/api_key_auth.py:8`, `backend/app/api/auth.py:325`, `backend/app/middleware/api_scope_middleware.py:81`.++`admin_required` accepts API keys, but does not enforce their scopes. Login-link creation has no separate scope gate. An admin-owned key limited to `apps:read` can therefore mint and redeem a login link, yielding access and refresh tokens outside the original scope restriction. The role prerequisite matters: this is escalation of an admin-owned restricted key, not promotion of a viewer-owned key to admin.++**Local proof:** created a synthetic `apps:read` key, verified it lacked `write`, then obtained 201 from login-link creation and 200 with fresh session credentials from redemption.++**Fix:** make credential/session minting require an explicit authentication-method decision and appropriate recent authentication. Audit every API-key-capable route for scope enforcement. Add a test matrix using restricted keys against real routes. Preserve deliberately JWT-only routes; do not mechanically convert their decorators to API-key-capable ones.++**Effort:** small fix to close this chain; medium effort to finish scope coverage across the API.++### 3. High: Socket.IO accepts the wrong tokens and allows cross-user room subscriptions++Evidence: `backend/app/sockets.py:162`, `backend/app/sockets.py:181`, `backend/app/sockets.py:372`.++Two independent problems exist:++- Connection authentication decodes a JWT and checks that its user is active, but does not reject `2fa_pending` tokens or refresh tokens. Both connected successfully in local Socket.IO tests.+- The generic `join_room` event accepts arbitrary room names, with a special role check only for terminal rooms. A viewer can join `user_<another-user-id>`, bypassing the intended per-user notification boundary.++**Local proof:** a viewer joined a synthetic admin's user room and received a harmless test event sent only to that room. This proves cross-user delivery without reading anybody's real notifications. It does not establish the sensitivity of every production event payload.++Roles are also cached at connection time. Account and privilege changes need a defined policy for existing connections.++**Fix:** apply full access-token validation to socket connections; reject incomplete MFA and refresh-token use; replace arbitrary room joins with authorized, resource-specific subscriptions. Recheck ownership and privileges when subscribing, and disconnect or revalidate sessions after revocation. This matches [OWASP's WebSocket guidance](https://cheatsheetseries.owasp.org/cheatsheets/WebSocket_Security_Cheat_Sheet.html) on message authorization and session handling.++**Effort:** medium, because all consumers of the generic room event need to be inventoried.++### 4. High in shared panels: the AI can reveal applications hidden by REST authorization++Evidence: `backend/app/services/ai_tools_builtin.py:56`, `backend/app/services/ai_service.py:379`, `backend/app/services/ai_tool_registry.py:53`, `backend/app/api/apps.py:723`.++The AI's `list_applications` tool returns `Application.query_active().all()`. Its wrapper checks feature-level read permission, not app ownership, workspace membership, or resource grants. Viewers have application-read permission by default.++**Local proof:** a viewer received 403 for another user's app through the real REST detail endpoint. Calling the actual AI read wrapper with the same viewer returned that app. This tests the backend tool boundary; no live model was asked to disclose data.++The returned shape is broader than the tool description's name/status/type/port summary: it includes infrastructure and configuration metadata such as paths, identifiers, repository/build configuration, and private routing fields. The fleet/database listing tools deserve the same policy comparison, although this review's demonstrated cross-owner case is applications.++**Fix:** pass caller identity into tools and reuse the existing resource visibility services. Return a deliberately selected set of safe fields. Test that REST and AI show the same resources for owner, member, viewer, foreign user, and admin. This is an [object-level authorization problem](https://owasp.org/API-Security/editions/2023/en/0xa1-broken-object-level-authorization/), not something a prompt-injection detector can fix.++**Effort:** small-to-medium for application listing; medium for consistent tool coverage.++### 5. High: password changes and account disablement do not consistently invalidate access++Evidence: `backend/app/api/auth.py:477`, `backend/app/api/auth.py:493`, `backend/app/api/auth.py:523`, `backend/app/api/auth.py:546`, `backend/app/models/user.py:139`, `frontend/src/services/api/auth.js:39`.++The self-service password endpoint accepts a new password using an existing access token, without the old password or another recent authentication proof. Changing the password does not invalidate an already-issued refresh token. Refresh tokens default to 30 days. Logout only clears browser tokens.++Account disablement blocks password login and refresh, and role decorators check activity, but JWT-only routes do not uniformly check it. A disabled user's existing access token still read `/auth/me` and an owned application's details in the local tests. Production access tokens normally expire after 15 minutes; that is a residual-access window, not immediate offboarding.++**Local proof:** changed a synthetic user's password without providing the old one, then successfully refreshed with the token issued before the change. Separately disabled a synthetic account and verified continued reads with its existing access token.++**Fix:** require recent authentication for credential changes; add a server-side session/version or revocation mechanism checked consistently by REST and sockets. Revoke affected sessions on password reset, account disablement, and explicit logout/revoke actions. Existing JWT-only routes can gain activity/revocation checks without granting API-key access.++**Effort:** medium; schema changes require a migration.++### 6. Medium: the AI redaction toggle overstates its coverage++Evidence: `backend/app/services/ai_service.py:300`, `backend/app/services/ai_service.py:309`, `backend/app/services/ai_service.py:388`, `frontend/src/components/settings/AISettingsTab.jsx:199`.++The UI promises redaction of messages and tool output. `_maybe_redact_result` returns dictionary/list results untouched, while built-in tools commonly return exactly those types. Write-tool results also return directly. Input redaction returns the original text if the redactor raises, and prompt-injection detection treats detector failure as no detection.++**Local proof:** with redaction enabled, a nested synthetic dictionary containing an email and password reached the return boundary unchanged; the redactor was never invoked. No external transmission was performed, so this is a demonstrated coverage defect rather than a claim that a real secret was sent.++**Fix:** recursively scrub structured data, apply deterministic secret filtering before model calls, sanitize both read and write results, and define a visible failure policy when enabled protection cannot run. Treat injection detection as supplemental; authorization and confirmation must remain enforceable without it.++**Effort:** small-to-medium.++## Quick UI and product improvements++### 7. Confirmed CSS defect: Users and Invitations lose their table background++Evidence: `frontend/src/styles/pages/_settings.scss:164`, `frontend/src/styles/components/_users.scss:75`, `frontend/src/components/settings/UsersTab.jsx:392`, `frontend/src/components/settings/InvitationsTab.jsx:319`.++Settings normally gives `.sk-dtable-wrap` a background. A more-specific rule removes it under `.users-table-container`, assuming that outer wrapper already supplies a surface. The outer wrapper only has overflow, a border, and a radius. Active rows have no resting background; hover and disabled-row styles add color, explaining why the background can appear to come and go.++**Fix:** give the outer wrapper the shared surface token, or let the shared table wrapper own the surface and remove the redundant shell. Verify Users and Invitations in light/dark themes with active, disabled, empty, loading, and filtered states. Keep this in SCSS.++**Effort:** very small implementation; short visual check.++### 8. Make Users a useful access-review screen++The API already returns `totp_enabled`, `passkey_enabled`, and `auth_provider`; the Users table does not expose them. An MFA/passkey/auth-method column and an “Admins without MFA” saved view would make security debt visible using data already available.++Users also hardcodes `en-US` date formatting, renders status values directly in English, keeps page-local delete-confirmation state, and lacks a pending-state guard around delete/enable/disable actions. Reuse the existing locale, confirmation, and async-action primitives. These are targeted improvements rather than reasons to replace the design system.++**Effort:** small, well suited to one focused Settings polish change after the security fixes.++### 9. The frontend needs rendered-state coverage, not just more static rules++The frontend build and all 159 Node tests passed. Lint passed with **0 errors and 923 warnings**, including 96 hook-dependency warnings. The style-ownership checker reports 114 shared definitions across 50 class names, accepted by the current ceiling.++The existing checks are useful, but none of those successful checks caught the table-surface contradiction. The inspected frontend CI runs lint and pure-logic Node tests; it has no rendered Settings regression job.++**Fix:** add a small browser suite for critical Settings states and authentication flows. Start with Users/Invitations/API keys, light/dark themes, errors, and loading states. Review hook warnings where they affect data freshness or permissions; do not spend a sprint mechanically fixing all 923 warnings. A warning ceiling can prevent growth while fixing the backlog gradually.++**Effort:** small-to-medium initial setup, then add coverage when real regressions justify it.++## Hardening backlog, after the demonstrated bypasses++- **AI resource limits:** there is a per-conversation cost ceiling and tool-round limit, but the inspected routes do not enforce an aggregate per-user/panel spend quota or an explicit concurrent-stream cap. A new conversation gets a new budget. Add bounded concurrent work, request-size limits appropriate to chat, cancellation-aware queue writes, and aggregate spend accounting. No billing or load stress test was performed.+- **CSP:** production permits both `unsafe-inline` and `unsafe-eval` in `script-src`. Inventory extension/runtime requirements, then move toward hashes/nonces and remove unnecessary eval permission. This weakens defense in depth; it is not evidence of a standalone XSS exploit.+- **Security CI scope:** the inspected security workflow scans backend Python and requirements, has no schedule, and excludes entire Bandit categories (`B602`, `B402`, `B321`, `B202`) from its strict gate. Use narrow documented exceptions and include relevant extension sources and dependency manifests. Add periodic dependency scanning so new advisories are checked even without code changes. This review did not run a fresh dependency-advisory audit and makes no claim that current dependencies are vulnerable or clean.+- **Authorization tests:** the existing mutation sweep explicitly notes that 404s can hide missing authorization. Add real foreign-owned records and valid payloads, plus restricted keys, pending MFA, disabled users, refresh tokens, sockets, and AI tool calls. The missing dimension is cross-entry-point behavior, not simply the number of tests.++## What is already helping++The repo has explicit authorization decorators and ownership helpers, static mutation coverage, tests for scoping and secret filtering, brute-force controls, trusted-proxy handling, security headers, encrypted provider-key storage, and a server-side AI write-confirmation mechanism. Shared SCSS primitives and frontend integrity checks also exist. Build on those mechanisms rather than adding another parallel policy system.++The subprocess spot-check found extensive use of centralized execution helpers; the raw `subprocess.run` census under `backend/app/services` found one call, an explicitly documented operator-authored backup hook. The examined archive restores generally use data filters or custom validation. This is not a claim that every subprocess, path validator, installer, extension, or Linux distribution was audited.++## Suggested order++| Order | Work | Why |+| --- | --- | --- |+| 1 | Close MFA/login-link and API-key/session-minting chains | Direct compromise of intended authentication boundaries |+| 2 | Enforce socket token types and room ownership | Confirmed cross-user real-time delivery |+| 3 | Scope AI tools and fix structured redaction | Prevent the assistant from bypassing existing REST visibility |+| 4 | Implement session revocation and recent authentication | Make password changes and offboarding effective |+| 5 | Repair Settings surfaces and expose MFA status | Cheap, visible improvement with an operational security benefit |+| 6 | Add boundary/visual regressions and targeted hardening | Prevent recurrence without another broad rewrite |++## Validation record++- Initial targeted backend suite: **31 passed** (mutation authorization/static boundaries, JWT-only ratchet, setup security policy, app read scoping, socket protocol contract).+- Eight temporary isolated review probes: **8 passed**, meaning the probes successfully reproduced the current defects. These are not eight passing security protections. They covered the two login-link chains, AI foreign-app disclosure, disabled-user access, password/refresh behavior, structured redaction, socket token types, and cross-user room delivery.+- Frontend tests: **159 passed**.+- Frontend lint: passed, **0 errors / 923 warnings**; project-specific integrity checks passed.+- Frontend production build: passed; emitted large-chunk warnings. These warnings alone do not establish a runtime performance regression.+- Extended backend validation: **157 passed** in 130.17 seconds (API scopes, AI assistant/attachments, login links, brute force, headers, subprocess ratchet, raw-infrastructure authorization, files RBAC, and trusted client IP). Combined with the initial suite, **188 existing backend tests passed**.++Reproduction source is preserved alongside this report as `2026-09-05-security-probes.py`, outside the normal test suite. Its module docstring explains how to run it with the existing backend fixtures. After remediation, convert relevant probes into negative security regressions; do not preserve assertions that expect a bypass to succeed.++The temporary reproduction tests use synthetic values only. Production exposure depends on the deployed version and configuration; this review establishes behavior in the inspected checkout, not whether anyone has exploited it.