Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.
Python ai-agentsaiopsdashboarddockerfastapihomelabincident-managementllmmonitoringopenaireactroot-cause-analysisself-hosteduptime-monitoring
feat(agent): confirm with password and two-factor before turning the agent on (#188)
Karlo Kajba Šimanić3ad134a9a975
diff --git a/ODSTUPANJA.md b/ODSTUPANJA.mdindex a276816..3a08f2d 100644--- a/ODSTUPANJA.md+++ b/ODSTUPANJA.md@@ -187,3 +187,6 @@ Prvi dio milestonea: provjere HTTP(s), Keyword i TCP port, pokreću ih collector| New check: timeout fiksno 48 s | Timeout se sam smanji na 80 % intervala kad je interval kraći; greške se pokazuju uz polje i u podnožju | Zadani timeout inače blokira interval ispod 49 s | #141 || New check: tagovi kao čipovi | Tekstno polje, tagovi odvojeni zarezom | Jednostavnije | #141 || Mobitel: Availability kao zaseban tab | Availability je u More (s brojem palih provjera na tabu More); popis provjera je kompaktan, s trakom zadnjih 30 provjera | Tab bar ima mjesta za četiri stavke | #146 |+| Agent confirm (`11-agent-confirm.pdf`): dizajn pokazuje samo „Diagnose new incidents automatically" | Isti popup pita i za Chat (Off → On), Chat access (Admins only → Per user, gumb „Verify and save") i spremanje providera (npr. OpenAI → Anthropic ili stari → novi model, gumb „Verify and save") | Sve te promjene šalju podatke vanjskom modelu, pa traže istu potvrdu | #184 |+| Agent confirm: admin bez 2FA | Umjesto polja za lozinku popup kaže da prvo treba uključiti 2FA, s poveznicom na Account › Security | Dizajn ne pokazuje to stanje; bez 2FA promjena nije moguća | #184 |+| Agent confirm: popup „centred on the content" | Popup je centriran na cijeli ekran, a ne na sadržaj desno od bočne trake | Karlova odluka nakon pregleda (7. 11. 2026) | #184 |diff --git a/SECURITY.md b/SECURITY.mdindex 7b79d50..2170eee 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -439,6 +439,13 @@ URL, a keyword or a value in a JSON reply, a TCP port, a TLS certificate, a DNSthe administrator's AI provider quota or database space. Setting up two-factor from a normal session needs thepassword again, and every try counts toward the lockout, the right password included. A limited(set-up-only) session lasts 30 minutes, not a day.+- **Turning the agent on is confirmed with the password and a two-factor code.** Choosing the agent's provider,+ model or API key, switching the chat or automatic diagnosis on, and opening the chat to other users all start+ sending data from the servers to an outside model, so someone with a stolen admin session can't do it alone.+ The password is checked first (`POST /auth/reauth`) and gives a token that lasts five minutes, belongs to that+ session, allows five codes and is used up by the change; every try counts toward the two-factor lockout, and an+ admin without two-factor can't make these changes. Turning things off and removing the key need no+ confirmation, so stopping the agent is never harder than starting it (`src/backend/reauth.py`).- **Sessions are stored hashed.** Redis holds only the SHA-256 of the cookie value, in the session key, theper-user index and the pending-login token. Reading Redis (a backup, a leaked dump) doesn't hand out workingsessions. Note what this does and doesn't do: hashing protects against *reading* Redis. It does not stopdiff --git a/TESTS.md b/TESTS.mdindex 8e7a8d0..95a579d 100644--- a/TESTS.md+++ b/TESTS.md@@ -4,7 +4,7 @@ Infradeck ships with an automated test suite. This page explains how to run it,covers (and what it doesn't), and what every single test is for, so you can decidewhether a failure matters before you upgrade or change your setup.-- **1482 test cases** from 799 test functions, plus 38 small tests of the frontend helpers (see [Frontend helper tests](#frontend-helper-tests)) (some functions run once per input).+- **1488 test cases** from 805 test functions, plus 38 small tests of the frontend helpers (see [Frontend helper tests](#frontend-helper-tests)) (some functions run once per input).- **About two minutes** to run. No Docker, PostgreSQL, Redis, network or root access needed.- **Safe to run next to a live install.** The tests use a throwaway in-memory databaseand fakes; they never touch your running containers or your data. (Two collectordiff --git a/docs/api.md b/docs/api.mdindex 81e922a..937d308 100644--- a/docs/api.md+++ b/docs/api.md@@ -11,6 +11,7 @@ All paths are relative to `/api` when going through the frontend/nginx.| `POST /auth/login/2fa` | pending login token | Second step of sign-in: authenticator or recovery code. || `GET /auth/2fa/status`, `POST /auth/2fa/setup`, `POST /auth/2fa/enable` | session (also the limited setup session) | Two-factor status, start and confirm setup. Starting setup from a normal session needs `{"password": ...}`; the forced first enrolment doesn't. || `POST /auth/2fa/disable`, `POST /auth/2fa/recovery-codes` | session + password + code | Turn two-factor off; replace the recovery codes. |+| `POST /auth/reauth` | session with two-factor (rate limited) | Step 1 of confirming a change that sends data to the AI provider: checks the password and returns a `reauth_token` (5 minutes, this session only, 5 codes, single use). Step 2 sends `reauth_token` and `code` with the change. || `POST /auth/password` | session + current password | Change password; signs out other sessions. || `GET /auth/sessions`, `POST /auth/sessions/revoke-others`, `DELETE /auth/sessions/{id}` | session | List and end your own sessions. || `GET /auth/config` | – | Whether registration is open and whether the first account still needs a setup token. |@@ -27,7 +28,7 @@ All paths are relative to `/api` when going through the frontend/nginx.| `POST /monitoring/join-tokens` | admin | Create the single-use join token for **Connect a server** (shown once). || `GET /monitoring/install-info` | admin | The collector address and images the panel uses. || `GET` / `POST` / `DELETE /monitoring/enrollment-key` | admin | Show status / create or rotate / revoke the enrollment key. |-| `GET` / `PUT /admin/settings` | admin | History retention (`history_retention_days`: 365, 730 or 0 for forever), chat on/off, require two-factor for admins, alert thresholds and per-mount disk thresholds; the agent's model prices, monthly budget, daily chat limit, automatic diagnosis, whether users see diagnoses, and chat access (`admins_only` or `per_user`). |+| `GET` / `PUT /admin/settings` | admin | History retention (`history_retention_days`: 365, 730 or 0 for forever), chat on/off, require two-factor for admins, alert thresholds and per-mount disk thresholds; the agent's model prices, monthly budget, daily chat limit, automatic diagnosis, whether users see diagnoses, and chat access (`admins_only` or `per_user`). Turning the chat or automatic diagnosis on, and chat access to `per_user`, also need `reauth_token` and `code` (see `POST /auth/reauth`). || `GET /admin/users`, `PATCH /admin/users/{id}` | admin | Users and invitations; change someone's role, switch them off, or (with per-user chat access) allow them the agent chat (`agent_chat_enabled`). || `GET /agent/config` | session | Whether chat with the agent can be used: switched on, allowed for you (`may_chat`), a key configured, and the monthly budget not used up. || `GET /incidents`, `GET /incidents/{id}` | session | The incident inbox; one incident with its rule-based diagnosis and, under `agent`, the agent's latest report (with `watch` progress while it is open, `reused_from` when it was reused). The report is left out (`hidden: true`) for users who aren't admins while diagnoses aren't shown to users. |@@ -35,7 +36,7 @@ All paths are relative to `/api` when going through the frontend/nginx.| `POST /incidents/{id}/diagnose` | admin | Queue a new diagnosis by the agent (409 without a key, 429 while the budget is used up). || `GET /admin/agent/usage` | admin | This month's model calls, tokens and estimated cost against the budget, per model and per day, with the prices and limits. || `GET /admin/agent/worker` | admin | Whether the agent worker is running, how many jobs wait, are running or wait to be retried, and the latest results. |-| `PUT /admin/agent/provider` | admin (rate limited) | Choose the agent's provider (`anthropic`, `openai`, `gemini`) and model, and optionally save a new API key, stored encrypted (409 without `SECRETS_KEY`). Returns the choice and whether a key is saved, never the key. |+| `PUT /admin/agent/provider` | admin (rate limited) + `reauth_token` and `code` | Choose the agent's provider (`anthropic`, `openai`, `gemini`) and model, and optionally save a new API key, stored encrypted (409 without `SECRETS_KEY`). Returns the choice and whether a key is saved, never the key. || `DELETE /admin/agent/key` | admin | Remove the chosen provider's API key; the agent stops until a new one is saved. || `POST /admin/agent/test` | admin | Checks the saved key and that the configured model exists, without spending tokens. || `POST /monitoring/collectors/register` | join token (rate limited) | Collector asks to join; returns a poll secret and pairing code. |diff --git a/docs/assistant.md b/docs/assistant.mdindex f4f9289..dcc2524 100644--- a/docs/assistant.md+++ b/docs/assistant.md@@ -12,6 +12,8 @@ change files on your servers. Everything about it is in `src/agent/` and in **Adencrypted with it, so it can't be saved without one.2. Create an API key with one of the providers: Anthropic (Claude), OpenAI or Google Gemini.3. In **Admin → Incident agent**, pick the provider, keep or change the model, paste the key and click **Save**.+ Confirm with your password and a two-factor code: this decides where the agent's data goes. Turning the chat+ or automatic diagnosis on, and setting Chat access to "Per user", ask for the same; turning things off doesn't.Models used when the field is left empty:| Provider | Default model |diff --git a/src/backend/main.py b/src/backend/main.pyindex fe85d07..d51eb36 100644--- a/src/backend/main.py+++ b/src/backend/main.py@@ -198,6 +198,16 @@ class AdminSettingsRequest(BaseModel):agent_auto_diagnose: bool | None = Noneagent_show_diagnoses_to_users: bool | None = Noneagent_chat_access: Literal["admins_only", "per_user"] | None = None+ # Turning the agent on, or letting more people use it, is confirmed with the password and a code (reauth.py).+ reauth_token: str | None = Field(default=None, max_length=100)+ code: str | None = Field(default=None, max_length=64)+++def _starts_sending_data(db, payload: AdminSettingsRequest) -> bool:+ """Whether the change turns something on that sends data to the AI provider, or lets more people do so."""+ return ((payload.agent_chat_enabled is True and not is_agent_chat_enabled(db))+ or (payload.agent_auto_diagnose is True and not agent_settings.auto_diagnose(db))+ or (payload.agent_chat_access == "per_user" and agent_settings.chat_access(db) != "per_user"))class MetricsIngestRequest(BaseModel):@@ -618,6 +628,8 @@ def get_admin_settings(session_id: Annotated[str | None, Cookie(alias=SESSION_CO@app.put("/admin/settings")def update_admin_settings(payload: AdminSettingsRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):user = _require_admin(session_id, db)+ if _starts_sending_data(db, payload):+ reauth.require(db, user, payload.reauth_token, payload.code)changes = []two_factor_tightened = Falsedays = payload.history_retention_days@@ -1769,6 +1781,7 @@ def root():# Routes split out of this file; imported last so they can reference this module's shared helpers (see routes/).+from . import reauth # noqa: E402 (uses main, so it is imported once main is defined)from .routes import account as account_routes, admin as admin_routes, auth as auth_routes, availability as availability_routes, chat as chat_routes, incidents as incidents_routes, monitoring as monitoring_routes, statistics as statistics_routes # noqa: E402app.include_router(availability_routes.router)app.include_router(incidents_routes.router)diff --git a/src/backend/reauth.py b/src/backend/reauth.pynew file mode 100644index 0000000..1d588fc--- /dev/null+++ b/src/backend/reauth.py@@ -0,0 +1,98 @@+"""Asking a signed-in user for their password and a two-factor code again before a change that sends data out of+this machine (Admin › Incident agent, #184).++Step 1 (POST /auth/reauth) checks the password and hands out a short-lived token. Step 2 sends that token and a+code together with the change itself, so the password goes over the wire once. Like the sign-in's pending token, it+is kept in Redis only as a digest, lasts five minutes, is bound to the session that asked for it, allows five codes+and is used up by the change it confirms. Every try counts toward the account's two-factor lockout.+"""+from __future__ import annotations++import hashlib+import json+import secrets++from fastapi import HTTPException++from . import main, secrets_box+from .models import User++TTL_SECONDS = 300+MAX_CODE_ATTEMPTS = 5+START_AGAIN = "The confirmation expired. Start again with your password."+++def _digest(token: str) -> str:+ return hashlib.sha256(token.encode("utf-8")).hexdigest()+++def _token_key(token: str) -> str:+ return f"infradeck:reauth:{_digest(token)}"+++def _attempts_key(token: str) -> str:+ return f"infradeck:reauth-attempts:{_digest(token)}"+++def check_second_factor(db, user: User, code: str) -> str:+ """Verify a code for the user, with the shared brute-force limit. Raises 401 (or 429/503); returns "totp" or "recovery"."""+ limit_key = main.enforce_limit(main.redis_client, scope="2fa-user", subject=user.id, limit=main.TWO_FACTOR_ATTEMPTS, window_seconds=main.TWO_FACTOR_WINDOW_SECONDS)+ try:+ method = main.verify_second_factor(db, user, code)+ except secrets_box.SecretsUnavailable as exc:+ raise HTTPException(status_code=503, detail="Two-factor codes can't be checked on this server right now (a SECRETS_KEY problem). A recovery code still works.") from exc+ if method is None:+ main.record_audit_log(db, user_id=user.id, level="WARNING", message="A wrong two-factor code was entered", source="auth")+ raise HTTPException(status_code=401, detail="Invalid code.")+ main.reset_limits(main.redis_client, limit_key)+ return method+++def check_password(db, user: User, session: dict, password: str) -> str:+ """Step 1: the password. Returns the token for step 2."""+ if not user.totp_enabled:+ raise HTTPException(status_code=403, detail="Set up two-factor in Account › Security first.")+ limit_key = main.enforce_limit(main.redis_client, scope="2fa-user", subject=user.id, limit=main.TWO_FACTOR_ATTEMPTS, window_seconds=main.TWO_FACTOR_WINDOW_SECONDS)+ if not main.verify_password(user, password):+ main.record_audit_log(db, user_id=user.id, level="WARNING", message="A wrong password was entered while confirming a change", source="auth")+ raise HTTPException(status_code=401, detail="The password is not correct.")+ main.reset_limits(main.redis_client, limit_key)+ token = secrets.token_urlsafe(32)+ main.redis_client.set(_token_key(token), json.dumps({"user_id": user.id, "public_id": session.get("public_id")}), ex=TTL_SECONDS)+ return token+++def require(db, session: dict, token: str | None, code: str | None) -> None:+ """Step 2, called by the endpoint that makes the change: the token from step 1 and a two-factor code."""+ if not token or not code:+ raise HTTPException(status_code=403, detail="Confirm this change with your password and a two-factor code.")+ user = db.get(User, session["id"])+ raw = main.redis_client.get(_token_key(token)) if 20 <= len(token) <= 100 else None+ try:+ owner = json.loads(raw) if raw else None+ except ValueError:+ owner = None+ if not owner or user is None or owner.get("user_id") != user.id or owner.get("public_id") != session.get("public_id"):+ raise HTTPException(status_code=401, detail=START_AGAIN)+ attempts = main.redis_client.incr(_attempts_key(token))+ if attempts == 1:+ main.redis_client.expire(_attempts_key(token), TTL_SECONDS)+ if attempts > MAX_CODE_ATTEMPTS:+ _forget(token)+ raise HTTPException(status_code=401, detail="Too many wrong codes. Start again with your password.")+ try:+ check_second_factor(db, user, code)+ except HTTPException as exc:+ left = MAX_CODE_ATTEMPTS - attempts+ if exc.status_code == 401 and left > 0:+ raise HTTPException(status_code=401, detail=f"That code is not valid. {left} {'try' if left == 1 else 'tries'} left.") from exc+ if exc.status_code == 401:+ _forget(token)+ raise HTTPException(status_code=401, detail="Too many wrong codes. Start again with your password.") from exc+ raise+ _forget(token)+++def _forget(token: str) -> None:+ main.redis_client.delete(_token_key(token))+ main.redis_client.delete(_attempts_key(token))diff --git a/src/backend/routes/admin.py b/src/backend/routes/admin.pyindex aef1c8b..87663f1 100644--- a/src/backend/routes/admin.py+++ b/src/backend/routes/admin.py@@ -10,7 +10,7 @@ from fastapi import APIRouter, Cookie, Depends, HTTPExceptionfrom pydantic import BaseModel, Fieldfrom sqlalchemy import func, text-from .. import incidents, main, notify, secrets_box+from .. import incidents, main, notify, reauth, secrets_boxfrom ...agent import jobs as agent_jobs, settings as agent_settings, usage as agent_usagefrom ...agent import providers as agent_providersfrom ..config import APP_VERSION, SESSION_COOKIE_NAME@@ -177,6 +177,9 @@ class AgentProviderRequest(BaseModel):model: str | None = Field(default=None, max_length=100, pattern=r"^([A-Za-z0-9][A-Za-z0-9._:/-]{0,99})?$")# Empty: keep the stored key. Keys are printable ASCII without spaces.api_key: str | None = Field(default=None, max_length=512, pattern=r"^([\x21-\x7e]{8,512})?$")+ # Where the agent's data goes is confirmed with the password and a two-factor code (reauth.py).+ reauth_token: str | None = Field(default=None, max_length=100)+ code: str | None = Field(default=None, max_length=64)@router.put("/admin/agent/provider")def admin_agent_provider(payload: AgentProviderRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):@@ -185,6 +188,7 @@ def admin_agent_provider(payload: AgentProviderRequest, session_id: Annotated[stmain.enforce_limit(main.redis_client, scope="agent-provider", subject=admin["id"], limit=20, window_seconds=600)if payload.api_key and not secrets_box.available():raise HTTPException(status_code=409, detail="Set SECRETS_KEY in .env first: the API key is stored encrypted with it.")+ reauth.require(db, admin, payload.reauth_token, payload.code)agent_providers.save(db, payload.provider, payload.model, payload.api_key)db.commit()choice = agent_providers.current(db)@@ -195,7 +199,8 @@ def admin_agent_provider(payload: AgentProviderRequest, session_id: Annotated[st@router.delete("/admin/agent/key")def admin_agent_remove_key(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):- """Remove the stored API key of the chosen provider; the agent stops until a new one is saved."""+ """Remove the stored API key of the chosen provider; the agent stops until a new one is saved. Stopping the agent+ needs no confirmation, so it is never harder than starting it."""admin = main._require_admin(session_id, db)provider = agent_providers.current(db).providerif provider:diff --git a/src/backend/routes/auth.py b/src/backend/routes/auth.pyindex 4475635..e8904f1 100644--- a/src/backend/routes/auth.py+++ b/src/backend/routes/auth.py@@ -8,7 +8,9 @@ from typing import Annotatedfrom fastapi import APIRouter, Cookie, Depends, HTTPException, Query, Request, Response-from .. import main, secrets_box, totp+from pydantic import BaseModel, Field++from .. import main, reauth, secrets_box, totpfrom ..config import SESSION_COOKIE_NAMEfrom ..db import get_dbfrom ..models import Invite, RecoveryCode, Server, User@@ -132,19 +134,6 @@ def auth_login(payload: main.LoginRequest, request: Request, response: Response,return {"status": "two_factor_required", "pending_token": main.create_pending_two_factor(main.redis_client, user.id, payload.remember)}return _complete_login(db, request, response, user, remember=payload.remember)-def _second_factor_or_error(db, user: User, code: str) -> str:- """Verify a code for the user, with the shared brute-force limit. Raises 401 (or 429/503); returns "totp" or "recovery"."""- limit_key = main.enforce_limit(main.redis_client, scope="2fa-user", subject=user.id, limit=main.TWO_FACTOR_ATTEMPTS, window_seconds=main.TWO_FACTOR_WINDOW_SECONDS)- try:- method = main.verify_second_factor(db, user, code)- except secrets_box.SecretsUnavailable as exc:- raise HTTPException(status_code=503, detail="Two-factor codes can't be checked on this server right now (a SECRETS_KEY problem). A recovery code still works.") from exc- if method is None:- main.record_audit_log(db, user_id=user.id, level="WARNING", message="A wrong two-factor code was entered", source="auth")- raise HTTPException(status_code=401, detail="Invalid code.")- main.reset_limits(main.redis_client, limit_key)- return method-@router.post("/auth/login/2fa")def auth_login_two_factor(payload: main.TwoFactorLoginRequest, request: Request, response: Response, db=Depends(get_db)):main.enforce_ip_limit(main.redis_client, scope="2fa-ip", ip_address=main._client_ip(request), limit=20, window_seconds=main.TWO_FACTOR_WINDOW_SECONDS)@@ -157,7 +146,7 @@ def auth_login_two_factor(payload: main.TwoFactorLoginRequest, request: Request,user = db.get(User, user_id)if not user or not user.is_active or not user.totp_enabled:raise expired- method = _second_factor_or_error(db, user, payload.code)+ method = reauth.check_second_factor(db, user, payload.code)db.commit() # the code that was just accepted is now spentremember = main.pending_two_factor_remember(main.redis_client, payload.pending_token)main.delete_pending_two_factor(main.redis_client, payload.pending_token)@@ -258,7 +247,7 @@ def _reauthenticate(db, user: User, password: str, code: str) -> None:main.record_audit_log(db, user_id=user.id, level="WARNING", message="A wrong password was entered while changing two-factor", source="auth")raise wrongtry:- _second_factor_or_error(db, user, code)+ reauth.check_second_factor(db, user, code)except HTTPException as exc:if exc.status_code == 401:raise wrong from exc@@ -337,3 +326,13 @@ def auth_revoke_session(public_id: str, response: Response, session_id: Annotateif public_id == session["public_id"]:response.delete_cookie(key=SESSION_COOKIE_NAME, path="/")return {"status": "ok"}+++class PasswordConfirmRequest(BaseModel):+ password: str = Field(min_length=1, max_length=1024)+[email protected]("/auth/reauth")+def reauth_password(payload: PasswordConfirmRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):+ """Step 1 of confirming a sensitive change: the password. Step 2 sends the token and a code with the change (reauth.py)."""+ session, user = main._account_session(session_id, db)+ return {"reauth_token": reauth.check_password(db, user, session, payload.password)}diff --git a/src/frontend/src/admin/AdminPage.jsx b/src/frontend/src/admin/AdminPage.jsxindex e0dbff9..b510a02 100644--- a/src/frontend/src/admin/AdminPage.jsx+++ b/src/frontend/src/admin/AdminPage.jsx@@ -13,6 +13,7 @@ import { refreshOverview, useOverview } from '../overviewStore.js'import { AppShell, serverLink } from '../shell.jsx'import { ADMIN_GROUPS } from '../more/groups.js'import AgentProvider from './AgentProvider.jsx'+import ConfirmDialog from './ConfirmDialog.jsx'import { Field, Notice, Outcome, Row, Section, SettingsLayout, ShownOnce, Soon, Switch, ago, keptFor, useAction, useLoaded, usePhone } from '../ui.jsx'const REPOSITORY = 'https://github.com/karloks2005/Infradeck'@@ -276,16 +277,38 @@ function MountOverrides({ settings, onSaved }) {)}-function Agent({ settings, system, onSaved, onSystemChanged }) {+// Turning the agent on, or letting more people use the chat, is confirmed with the password and a two-factor code+// (#184); while the popup is open the switch stays as it was and says it is waiting. Turning things off is one click.+function Waiting({ children }) {+ return <span className="flex items-center gap-3"><span className="flex items-center gap-2 text-xs text-muted"><span className="spinner" />Waiting for confirmation</span>{children}</span>+}++function Agent({ settings, system, user, onSaved, onSystemChanged }) {const [state, run] = useAction()+ const [confirming, setConfirming] = useState(null)+ const agent = system.agent+ const chosen = agent.providers.find((item) => item.id === agent.provider)+ const where = chosen ? `${chosen.name} · ${agent.model}` : 'the AI provider once a key is saved'+ const turnOn = 'Turning the agent on lets Infradeck send data from your servers to an outside model.'+ const ask = (body, change) => setConfirming({ body, change: { from: 'Off', to: 'On', intro: turnOn, action: 'Verify and turn on', ...change } })+ const toggle = (key, on, change) => (on ? ask({ [key]: true }, change) : run(async () => onSaved(await put({ [key]: false }))))+ const waiting = (key) => confirming?.body[key] !== undefined+ const autoSwitch = <Switch label="Diagnose automatically" checked={settings.agent_auto_diagnose !== false} disabled={state.busy || waiting('agent_auto_diagnose')}+ onChange={(on) => toggle('agent_auto_diagnose', on, { title: 'Diagnose new incidents automatically', detail: 'Incident evidence will be sent to', target: where })} />+ const chatSwitch = <Switch label="Chat with the agent" checked={settings.agent_chat_enabled} disabled={state.busy || waiting('agent_chat_enabled')}+ onChange={(on) => toggle('agent_chat_enabled', on, { title: 'Chat', detail: "Questions and the incident's facts will be sent to", target: where })} />+ const chooseAccess = (value) => (value === 'per_user'+ ? ask({ agent_chat_access: 'per_user' }, { title: 'Chat access', from: 'Admins only', to: 'Per user', detail: 'People you allow in Users can send questions to', target: where,+ intro: 'Letting more people use the chat lets them send data from your servers to an outside model.', action: 'Verify and save' })+ : run(async () => onSaved(await put({ agent_chat_access: value }))))return <><div className="card divide-y divide-line">- <AgentProvider agent={system.agent} secretsConfigured={system.secrets_configured} onChanged={onSystemChanged} />- <Row title="Diagnose new incidents automatically" detail="When a warning or critical incident opens or gets worse, the agent worker sends its evidence (masked) to the model and writes a diagnosis. Off: incidents keep the rule-based diagnosis, and anyone who may act on incidents can still ask for one."><Switch label="Diagnose automatically" checked={settings.agent_auto_diagnose !== false} disabled={state.busy} onChange={(on) => run(async () => onSaved(await put({ agent_auto_diagnose: on })))} /></Row>+ <AgentProvider agent={agent} user={user} secretsConfigured={system.secrets_configured} onChanged={onSystemChanged} />+ <Row title="Diagnose new incidents automatically" detail="When a warning or critical incident opens or gets worse, the agent worker sends its evidence (masked) to the model and writes a diagnosis. Off: incidents keep the rule-based diagnosis, and anyone who may act on incidents can still ask for one.">{waiting('agent_auto_diagnose') ? <Waiting>{autoSwitch}</Waiting> : autoSwitch}</Row><Row title="Read container logs" detail="Not available: Infradeck's Docker proxy can't read logs. See SECURITY.md."><Switch label="Read container logs" checked={false} disabled onChange={() => {}} /></Row>- <Row title="Chat" detail="The main switch for the chat; who may use it is set under Chat access. Questions and the incident's facts are sent to the provider."><Switch label="Chat with the agent" checked={settings.agent_chat_enabled} disabled={state.busy} onChange={(on) => run(async () => onSaved(await put({ agent_chat_enabled: on })))} /></Row>+ <Row title="Chat" detail="The main switch for the chat; who may use it is set under Chat access. Questions and the incident's facts are sent to the provider.">{waiting('agent_chat_enabled') ? <Waiting>{chatSwitch}</Waiting> : chatSwitch}</Row><Row title="Chat access" detail={settings.agent_chat_access === 'per_user' ? 'Admins always; everyone else only with the Agent chat switch next to their name in Users.' : 'Only owners and admins can use the chat.'}>- <select className="select" aria-label="Chat access" value={settings.agent_chat_access || 'admins_only'} disabled={state.busy} onChange={(event) => run(async () => onSaved(await put({ agent_chat_access: event.target.value })))}><option value="admins_only">Admins only</option><option value="per_user">Per user</option></select>+ <select className="select" aria-label="Chat access" value={settings.agent_chat_access || 'admins_only'} disabled={state.busy} onChange={(event) => chooseAccess(event.target.value)}><option value="admins_only">Admins only</option><option value="per_user">Per user</option></select></Row><Row title="Show diagnoses to users" detail="Off: only owners and admins see the agent's diagnoses and their summary in notifications; everyone else sees the rule-based diagnosis."><Switch label="Show diagnoses to users" checked={settings.agent_show_diagnoses_to_users !== false} disabled={state.busy} onChange={(on) => run(async () => onSaved(await put({ agent_show_diagnoses_to_users: on })))} />@@ -293,6 +316,7 @@ function Agent({ settings, system, onSaved, onSystemChanged }) {<Row title="Redact IPs and hostnames before sending" detail="Not available yet. Until then, turn Chat off if names must not leave this machine."><Switch label="Redact before sending" checked={false} disabled onChange={() => {}} /></Row></div><Outcome state={state} />+ {confirming && <ConfirmDialog change={confirming.change} user={user} onConfirm={async (fields) => onSaved(await put({ ...confirming.body, ...fields }))} onClose={() => setConfirming(null)} />}<AgentWorker /><AgentSpending settings={settings} onSaved={onSaved} /></>@@ -538,7 +562,7 @@ export default function AdminPage({ user, onLogout }) {</Section><Section id="users" title="Users" description="Who can sign in, what they may do, and whether they must use two-factor."><Users me={user} /></Section><Section id="rules" title="Alert rules" description="What opens an incident. Rules apply to every server. The “Fired” column shows how noisy each rule has been."><Rules onCount={setRuleCount} /><MountOverrides settings={settings.data} onSaved={settings.setData} /></Section>- <Section id="agent" title="Incident agent" description="Diagnoses incidents and answers questions using the data Infradeck already has. It is read-only: it can't run commands, restart containers or change files on your servers."><Agent settings={settings.data} system={system.data} onSaved={settings.setData} onSystemChanged={system.reload} /></Section>+ <Section id="agent" title="Incident agent" description="Diagnoses incidents and answers questions using the data Infradeck already has. It is read-only: it can't run commands, restart containers or change files on your servers."><Agent settings={settings.data} system={system.data} user={user} onSaved={settings.setData} onSystemChanged={system.reload} /></Section><Section id="retention" title="Data & retention" description="How long history is kept and how big it is."><Retention settings={settings.data} system={system.data} onSaved={settings.setData} /></Section><Section id="about" title="About"><About settings={settings.data} system={system.data} onSaved={settings.setData} /></Section></>}diff --git a/src/frontend/src/admin/AgentProvider.jsx b/src/frontend/src/admin/AgentProvider.jsxindex 4bd777c..32b9129 100644--- a/src/frontend/src/admin/AgentProvider.jsx+++ b/src/frontend/src/admin/AgentProvider.jsx@@ -1,10 +1,12 @@// Which AI provider and model the incident agent uses, and its API key. The key is sent once and stored encrypted;-// the backend never sends it back, so the field only ever shows whether one is saved.+// the backend never sends it back, so the field only ever shows whether one is saved. Saving decides where the+// agent's data goes, so it is confirmed with the password and a two-factor code first (#184).import { useState } from 'react'import { apiRequest } from '../api.js'import { Field, Outcome, Row, useAction } from '../ui.jsx'+import ConfirmDialog from './ConfirmDialog.jsx'-export default function AgentProvider({ agent, secretsConfigured, onChanged }) {+export default function AgentProvider({ agent, user, secretsConfigured, onChanged }) {const providers = agent.providersconst defaultModel = (id) => providers.find((item) => item.id === id)?.default_model || ''const [provider, setProvider] = useState(agent.provider || providers[0].id)@@ -13,6 +15,7 @@ export default function AgentProvider({ agent, secretsConfigured, onChanged }) {const [state, run] = useAction()const [test, runTestAction] = useAction()const [tested, setTested] = useState(null)+ const [confirming, setConfirming] = useState(null)const chosen = providers.find((item) => item.id === agent.provider)const switching = Boolean(agent.provider) && provider !== agent.provider@@ -20,11 +23,20 @@ export default function AgentProvider({ agent, secretsConfigured, onChanged }) {const save = (event) => {event.preventDefault()setTested(null)- run(async () => {- await apiRequest('/admin/agent/provider', { method: 'PUT', body: JSON.stringify({ provider, model: model.trim() || null, api_key: apiKey.trim() || null }) })- setApiKey('')- await onChanged()- }, 'Saved.')+ const name = providers.find((item) => item.id === provider).name+ const newModel = model.trim() || defaultModel(provider)+ const [from, to] = provider !== agent.provider ? [chosen?.name || 'None', name]+ : newModel !== agent.model ? [agent.model, newModel] : [agent.key_configured ? 'Saved key' : 'No key', 'New key']+ setConfirming({+ body: { provider, model: model.trim() || null, api_key: apiKey.trim() || null },+ change: { title: 'Model provider', from, to, detail: 'Incident evidence and chat questions will be sent to', target: `${name} · ${newModel}`,+ intro: 'The provider decides where Infradeck sends data from your servers.', action: 'Verify and save' },+ })+ }+ const confirm = async (fields) => {+ await apiRequest('/admin/agent/provider', { method: 'PUT', body: JSON.stringify({ ...confirming.body, ...fields }) })+ setApiKey('')+ await run(onChanged, 'Saved.')}const removeKey = () => {if (!window.confirm(`Remove the ${chosen.name} API key? The agent stops until a new key is saved.`)) return@@ -60,6 +72,7 @@ export default function AgentProvider({ agent, secretsConfigured, onChanged }) {</div><div className="empty:hidden md:col-span-4"><Outcome state={state} /></div></form>+ {confirming && <ConfirmDialog change={confirming.change} user={user} onConfirm={confirm} onClose={() => setConfirming(null)} />}</>)}diff --git a/src/frontend/src/admin/ConfirmDialog.jsx b/src/frontend/src/admin/ConfirmDialog.jsxnew file mode 100644index 0000000..d4487be--- /dev/null+++ b/src/frontend/src/admin/ConfirmDialog.jsx@@ -0,0 +1,153 @@+// "Confirm it's you" before a change that sends data from the servers to an AI provider (design/mobile/11-agent-confirm.pdf,+// #184). Step 1 checks the password on the server and gets a short-lived token; step 2 sends the token and a+// two-factor code with the change itself (``onConfirm``). Cancel, ✕, Escape or a click outside leave things as they were.+import { useEffect, useRef, useState } from 'react'+import { Link } from 'react-router-dom'+import { apiRequest } from '../api.js'+import { Icon } from '../icons.jsx'+import { CODE_LENGTH, CodeBoxes, useOverlay } from '../ui.jsx'++const initials = (name) => { const parts = (name || '?').trim().split(/\s+/); return (parts.length > 1 ? parts[0][0] + parts[parts.length - 1][0] : parts[0].slice(0, 2)).toUpperCase() }+const quietLink = 'font-medium text-paper underline decoration-muted underline-offset-4 hover:decoration-paper'++// What is about to change: the setting, its old and new value, and where the data will go.+function Change({ change }) {+ return (+ <div className="rounded-md border border-line bg-bg px-3.5 py-3">+ <div className="flex items-baseline justify-between gap-3 text-[13px]">+ <span className="min-w-0 text-paper">{change.title}</span>+ <span className="flex shrink-0 items-center gap-2 text-muted">{change.from}<span aria-hidden="true">→</span><span className="sr-only">to</span><span className="font-semibold text-paper">{change.to}</span></span>+ </div>+ <p className="mb-0 mt-1.5 text-xs text-muted">{change.detail} <span className="whitespace-nowrap">{change.target}</span></p>+ </div>+ )+}++function Steps({ step, icon, title, onClose }) {+ return (+ <header className="flex items-start gap-3 px-5 pb-1 pt-5">+ <span aria-hidden="true" className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-edge bg-bg text-paper"><Icon name={icon} size={15} /></span>+ <div className="min-w-0 flex-1">+ <p className="m-0 flex items-center gap-2.5 text-[10px] font-medium uppercase tracking-[0.12em] text-muted">Step {step} of 2+ <span aria-hidden="true" className="flex gap-1">{[1, 2].map((index) => <span key={index} className={`h-[3px] w-4 rounded-full ${index <= step ? 'bg-paper' : 'bg-edge'}`} />)}</span>+ </p>+ <h2 className="m-0 mt-1 text-[17px] font-semibold text-paper">{title}</h2>+ </div>+ <button type="button" onClick={onClose} aria-label="Close" className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-edge bg-ink text-soft hover:bg-raised hover:text-paper"><Icon name="close" size={14} /></button>+ </header>+ )+}++// How long the popup takes to fade and scale away before it is removed.+const LEAVE_MS = 160++export default function ConfirmDialog({ change, user, onConfirm, onClose }) {+ const [leaving, setLeaving] = useState(false)+ const timer = useRef(null)+ useEffect(() => () => clearTimeout(timer.current), [])+ const close = () => { if (leaving) return; setLeaving(true); timer.current = setTimeout(onClose, LEAVE_MS) }+ const shown = useOverlay(Boolean(change), close) && !leaving+ const [step, setStep] = useState(1)+ const [password, setPassword] = useState('')+ const [reveal, setReveal] = useState(false)+ const [token, setToken] = useState('')+ const [code, setCode] = useState('')+ const [recovery, setRecovery] = useState(false)+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState('')+ const [shake, setShake] = useState(0)+ const passwordField = useRef(null)+ // The click that opened the popup ends by focusing the switch, so the password field takes focus a frame later.+ useEffect(() => {+ if (step !== 1) return undefined+ const frame = requestAnimationFrame(() => passwordField.current?.focus())+ return () => cancelAnimationFrame(frame)+ }, [step])+ if (!change) return null++ const checkPassword = async (event) => {+ event.preventDefault()+ if (busy || !password) return+ setBusy(true); setError('')+ try {+ const result = await apiRequest('/auth/reauth', { method: 'POST', body: JSON.stringify({ password }) })+ setToken(result.reauth_token); setPassword(''); setStep(2)+ } catch (requestError) { setError(requestError.message || 'The password is not correct.') }+ setBusy(false)+ }+ const verify = async (value) => {+ if (busy || !value.trim()) return+ setBusy(true); setError('')+ try {+ await onConfirm({ reauth_token: token, code: value.trim() })+ close()+ } catch (requestError) {+ const message = requestError.message || 'That code is not valid.'+ setBusy(false); setCode('')+ if (/start again/i.test(message)) { setStep(1); setToken(''); setError(message); return }+ setError(message); setShake((count) => count + 1)+ }+ }+ const submitCode = (event) => {+ event.preventDefault()+ if (!recovery && code.length < CODE_LENGTH) setError('Type all six digits of the code.')+ else verify(code)+ }+ const back = () => { setStep(1); setToken(''); setCode(''); setError('') }++ return (+ <div className={`fixed inset-0 z-50 flex items-center justify-center px-4 transition-colors duration-200 ${shown ? 'bg-black/55' : 'bg-black/0'}`} onMouseDown={(event) => { if (event.target === event.currentTarget) close() }}>+ <div role="dialog" aria-modal="true" aria-label={step === 1 ? "Confirm it's you" : 'Enter your 2FA code'} className={`relative w-full max-w-[440px] rounded-lg border border-edge bg-ink shadow-[0_24px_48px_rgba(0,0,0,0.45)] transition duration-200 ease-out motion-reduce:transition-none ${shown ? 'translate-y-0 scale-100 opacity-100' : 'translate-y-2 scale-95 opacity-0'}`}>+ <span aria-hidden="true" className="pointer-events-none absolute -left-[2px] bottom-[18px] top-[18px] w-[3px] rounded-full bg-signal" />+ {step === 1 ? (+ <form key="password" className="dialog-step" onSubmit={checkPassword}>+ <Steps step={1} icon="lock" title="Confirm it's you" onClose={close} />+ <div className="flex flex-col gap-4 px-5 pb-5 pt-3">+ <p className="m-0 text-[13px] leading-5 text-soft">{change.intro} Enter your password to continue.</p>+ <Change change={change} />+ {user.two_factor_enabled === false+ ? <p role="alert" className="m-0 text-xs leading-5 text-warn">This needs two-factor sign-in. Set it up in <Link to="/account?section=security" className="underline underline-offset-4">Account › Security</Link> first.</p>+ : <>+ <p className="m-0 flex items-center gap-2.5 text-[13px]">+ <span aria-hidden="true" className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-line bg-raised text-[10px] font-semibold text-paper">{initials(user.name)}</span>+ <span className="min-w-0 truncate"><span className="font-medium text-paper">{user.name}</span> <span className="text-muted">· {user.email}</span></span>+ </p>+ <label className="block text-xs text-soft"><span className="mb-1.5 block">Password</span>+ <span className="relative block">+ <input ref={passwordField} type={reveal ? 'text' : 'password'} autoComplete="current-password" maxLength={1024} value={password} disabled={busy} onChange={(event) => setPassword(event.target.value)} className="field h-11 w-full pr-16" />+ <button type="button" onClick={() => setReveal((value) => !value)} className="absolute inset-y-0 right-3 text-xs text-muted hover:text-paper">{reveal ? 'Hide' : 'Show'}</button>+ </span>+ </label>+ </>}+ {error && <p role="alert" className="m-0 text-xs text-warn">{error}</p>}+ </div>+ <footer className="flex justify-end gap-2.5 border-t border-line px-5 py-3.5">+ <button type="button" className="btn" onClick={close}>Cancel</button>+ <button type="submit" className="btn btn-primary" disabled={busy || !password || user.two_factor_enabled === false}>{busy ? 'Checking…' : 'Continue'}</button>+ </footer>+ </form>+ ) : (+ <form key="code" className="dialog-step" onSubmit={submitCode}>+ <Steps step={2} icon="key" title="Enter your 2FA code" onClose={close} />+ <div className="flex flex-col gap-4 px-5 pb-5 pt-3">+ <p className="m-0 text-[13px] leading-5 text-soft">Password accepted. {recovery ? 'Type one of the recovery codes you saved when you turned two-factor on.' : <>Open your authenticator app and type the 6-digit code for <span className="font-medium text-paper">{user.email}</span>.</>}</p>+ <div key={shake} className={shake ? 'shake' : undefined}>+ {recovery+ ? <input autoFocus value={code} onChange={(event) => setCode(event.target.value)} maxLength={32} autoComplete="off" autoCapitalize="none" spellCheck={false} aria-label="Recovery code" placeholder="xxxx-xxxx-xxxx" className="field mono h-11 w-full tracking-wider" />+ : <CodeBoxes value={code} onChange={setCode} onComplete={verify} disabled={busy} />}+ </div>+ {error && <p role="alert" className="m-0 text-xs text-warn">{error}</p>}+ <p className="m-0 text-xs text-muted">{recovery ? 'Have your phone after all? ' : 'Lost your phone? '}<button type="button" className={quietLink} onClick={() => { setRecovery((mode) => !mode); setCode(''); setError('') }}>{recovery ? 'Use the 6-digit code' : 'Use a recovery code'}</button></p>+ <Change change={change} />+ </div>+ <footer className="flex items-center gap-2.5 border-t border-line px-5 py-3.5">+ <button type="button" className="mr-auto text-xs text-muted underline decoration-edge underline-offset-4 hover:text-paper" onClick={back}>Back</button>+ <button type="button" className="btn" onClick={close}>Cancel</button>+ <button type="submit" className="btn btn-primary" disabled={busy}><Icon name="check" size={13} />{busy ? 'Checking…' : change.action}</button>+ </footer>+ </form>+ )}+ </div>+ </div>+ )+}diff --git a/src/frontend/src/auth/AuthPages.jsx b/src/frontend/src/auth/AuthPages.jsxindex ed0ceb9..e6ca2ef 100644--- a/src/frontend/src/auth/AuthPages.jsx+++ b/src/frontend/src/auth/AuthPages.jsx@@ -1,14 +1,14 @@// Signing in, the two-factor step, registering and the first account on a new install. One frame for all of// them: the brand panel on the left (a band on top on a phone), the form on the right.-import { useEffect, useRef, useState } from 'react'+import { useEffect, useState } from 'react'import { Link, useNavigate, useSearchParams } from 'react-router-dom'import { apiRequest } from '../api.js'import { Icon } from '../icons.jsx'+import { CODE_LENGTH, CodeBoxes } from '../ui.jsx'import { landingPath } from '../prefs.js'export const MIN_PASSWORD_LENGTH = 16const MAX_PASSWORD_BYTES = 72-const CODE_LENGTH = 6const DOCS_URL = 'https://github.com/karloks2005/Infradeck#readme'const REPOSITORY_URL = 'https://github.com/karloks2005/Infradeck'const SETUP_TOKEN_COMMAND = 'docker compose logs backend | grep "setup token"'@@ -141,44 +141,6 @@ function Quiet({ children }) {const quietLink = 'font-medium text-paper underline decoration-muted underline-offset-4 hover:decoration-paper'-// Six boxes, one digit each. Typing moves on, backspace moves back, pasting a code fills them all, and the-// form sends itself after the sixth digit.-function CodeBoxes({ value, onChange, onComplete, disabled }) {- const refs = useRef([])- const digits = Array.from({ length: CODE_LENGTH }, (_, index) => value[index] || '')- const focus = (index) => refs.current[Math.max(0, Math.min(CODE_LENGTH - 1, index))]?.focus()- const apply = (next, from) => {- const clean = next.replace(/\D/g, '').slice(0, CODE_LENGTH)- onChange(clean)- focus(Math.min(clean.length, from))- if (clean.length === CODE_LENGTH) onComplete(clean)- }- const onInput = (index, typed) => {- const added = typed.replace(/\D/g, '')- if (!added) return- // More than one character means a paste or an autofilled one-time code: it replaces from this box on.- apply(value.slice(0, index) + added + (added.length > 1 ? '' : value.slice(index + 1)), index + added.length)- }- const onKeyDown = (index, event) => {- if (event.key === 'Backspace') {- event.preventDefault()- const target = digits[index] ? index : index - 1- if (target >= 0) { onChange(value.slice(0, target) + value.slice(target + 1)); focus(target) }- } else if (event.key === 'ArrowLeft') { event.preventDefault(); focus(index - 1) } else if (event.key === 'ArrowRight') { event.preventDefault(); focus(index + 1) }- }- return (- <div className="flex justify-between gap-2" role="group" aria-label="6-digit code">- {digits.map((digit, index) => (- <input key={index} ref={(element) => { refs.current[index] = element }} value={digit} disabled={disabled} autoFocus={index === 0}- inputMode="numeric" pattern="[0-9]*" autoComplete={index === 0 ? 'one-time-code' : 'off'} aria-label={`Digit ${index + 1}`}- onChange={(event) => onInput(index, event.target.value)} onKeyDown={(event) => onKeyDown(index, event)}- onPaste={(event) => { event.preventDefault(); apply(value.slice(0, index) + event.clipboardData.getData('text'), CODE_LENGTH) }}- onFocus={(event) => event.target.select()} className="auth-digit" />- ))}- </div>- )-}-function TwoFactorStep({ instance, email, pendingToken, onDone, onBack }) {const [code, setCode] = useState('')const [recovery, setRecovery] = useState(false)diff --git a/src/frontend/src/index.css b/src/frontend/src/index.cssindex 31caa50..1bbbf89 100644--- a/src/frontend/src/index.css+++ b/src/frontend/src/index.css@@ -619,3 +619,26 @@:root[data-density='compact'] body {zoom: 0.9;}++/* A wrong two-factor code: the boxes shake once (#184). */+@keyframes shake {+ 20%, 60% { transform: translateX(-6px); }+ 40%, 80% { transform: translateX(6px); }+}+.shake {+ animation: shake 0.35s ease-in-out;+}+@media (prefers-reduced-motion: reduce) {+ .shake { animation: none; }+}++/* Moving from the password to the code inside the confirm popup (#184). */+@keyframes dialog-step {+ from { opacity: 0; transform: translateX(8px); }+}+.dialog-step {+ animation: dialog-step 0.18s ease-out;+}+@media (prefers-reduced-motion: reduce) {+ .dialog-step { animation: none; }+}diff --git a/src/frontend/src/ui.jsx b/src/frontend/src/ui.jsxindex 4de04c0..400d378 100644--- a/src/frontend/src/ui.jsx+++ b/src/frontend/src/ui.jsx@@ -1,6 +1,6 @@// Pieces the settings-style pages (Account, Admin) share: the two-column layout with a section list, cards,// switches, notices and small helpers.-import { Children, Fragment, createContext, isValidElement, useContext, useEffect, useState } from 'react'+import { Children, Fragment, createContext, isValidElement, useContext, useEffect, useRef, useState } from 'react'import { useSearchParams } from 'react-router-dom'import { PhoneHeader } from './shell.jsx'import { apiRequest } from './api.js'@@ -227,7 +227,7 @@ export function describeBrowser(userAgent) {}// Opening an overlay: focus goes in, Escape closes, the page behind stops scrolling, and focus comes back after.-function useOverlay(open, onClose) {+export function useOverlay(open, onClose) {const [shown, setShown] = useState(false)useEffect(() => {if (!open) { setShown(false); return undefined }@@ -285,3 +285,43 @@ export function Drawer({ open, title, description, onClose, children, width = 56</div>)}++export const CODE_LENGTH = 6++// Six boxes, one digit each. Typing moves on, backspace moves back, pasting a code fills them all, and the+// form sends itself after the sixth digit.+export function CodeBoxes({ value, onChange, onComplete, disabled, autoFocus = true }) {+ const refs = useRef([])+ const digits = Array.from({ length: CODE_LENGTH }, (_, index) => value[index] || '')+ const focus = (index) => refs.current[Math.max(0, Math.min(CODE_LENGTH - 1, index))]?.focus()+ const apply = (next, from) => {+ const clean = next.replace(/\D/g, '').slice(0, CODE_LENGTH)+ onChange(clean)+ focus(Math.min(clean.length, from))+ if (clean.length === CODE_LENGTH) onComplete(clean)+ }+ const onInput = (index, typed) => {+ const added = typed.replace(/\D/g, '')+ if (!added) return+ // More than one character means a paste or an autofilled one-time code: it replaces from this box on.+ apply(value.slice(0, index) + added + (added.length > 1 ? '' : value.slice(index + 1)), index + added.length)+ }+ const onKeyDown = (index, event) => {+ if (event.key === 'Backspace') {+ event.preventDefault()+ const target = digits[index] ? index : index - 1+ if (target >= 0) { onChange(value.slice(0, target) + value.slice(target + 1)); focus(target) }+ } else if (event.key === 'ArrowLeft') { event.preventDefault(); focus(index - 1) } else if (event.key === 'ArrowRight') { event.preventDefault(); focus(index + 1) }+ }+ return (+ <div className="flex justify-between gap-2" role="group" aria-label="6-digit code">+ {digits.map((digit, index) => (+ <input key={index} ref={(element) => { refs.current[index] = element }} value={digit} disabled={disabled} autoFocus={autoFocus && index === 0}+ inputMode="numeric" pattern="[0-9]*" autoComplete={index === 0 ? 'one-time-code' : 'off'} aria-label={`Digit ${index + 1}`}+ onChange={(event) => onInput(index, event.target.value)} onKeyDown={(event) => onKeyDown(index, event)}+ onPaste={(event) => { event.preventDefault(); apply(value.slice(0, index) + event.clipboardData.getData('text'), CODE_LENGTH) }}+ onFocus={(event) => event.target.select()} className="auth-digit" />+ ))}+ </div>+ )+}diff --git a/tests/accounts/test_new_pages.py b/tests/accounts/test_new_pages.pyindex 39f8eab..bdb1bc2 100644--- a/tests/accounts/test_new_pages.py+++ b/tests/accounts/test_new_pages.py@@ -63,6 +63,15 @@ def signed_in(app, user_id):return client+def confirmed(app, client, user_id=1):+ """Both steps of confirming a change (#184): the password, then a recovery code as the second factor (a TOTP code+ can't be used twice). Returns the fields the change itself sends."""+ codes = auth.issue_recovery_codes(app.db, app.db.get(User, user_id))+ app.db.commit()+ token = client.post("/auth/reauth", json={"password": PASSWORD}).json()["reauth_token"]+ return {"reauth_token": token, "code": codes[0]}++# --- incidents ---------------------------------------------------------------------------------------def test_the_inbox_lists_open_incidents_most_severe_first_and_says_who_may_act(app):@@ -344,7 +353,7 @@ def test_admin_tests_the_agent_connection_and_the_key_never_comes_back(app, monkowner = signed_in(app, 1)monkeypatch.setattr(main, "check_provider_connection", lambda db: {"provider": "Anthropic", "model": "claude-test"})- saved = owner.put("/admin/agent/provider", json={"provider": "anthropic", "model": "claude-test", "api_key": "sk-ant-test-secret-value"})+ saved = owner.put("/admin/agent/provider", json={"provider": "anthropic", "model": "claude-test", "api_key": "sk-ant-test-secret-value", **confirmed(app, owner)})system = owner.get("/admin/system")assert system.json()["agent"]["key_configured"] is True and system.json()["agent"]["provider"] == "anthropic"result = owner.post("/admin/agent/test")@@ -387,7 +396,7 @@ def test_without_secrets_key_no_api_key_is_stored(app, monkeypatch):def test_saving_and_removing_the_agent_key_is_audited_without_the_key(app):owner = signed_in(app, 1)- saved = owner.put("/admin/agent/provider", json={"provider": "gemini", "api_key": "AIza-test-secret-value"}).json()+ saved = owner.put("/admin/agent/provider", json={"provider": "gemini", "api_key": "AIza-test-secret-value", **confirmed(app, owner)}).json()assert saved["provider"] == "gemini" and saved["model"] == "gemini-3.1-flash-lite" and saved["key_configured"] is Trueassert owner.delete("/admin/agent/key").json()["key_configured"] is False@@ -528,7 +537,7 @@ def test_asking_for_a_new_diagnosis_queues_a_job(app, monkeypatch):owner = signed_in(app, 1)assert owner.post("/incidents/42/diagnose").status_code == 409 # no key configured- assert owner.put("/admin/agent/provider", json={"provider": "openai", "api_key": "sk-test-not-real"}).status_code == 200+ assert owner.put("/admin/agent/provider", json={"provider": "openai", "api_key": "sk-test-not-real", **confirmed(app, owner)}).status_code == 200assert owner.post("/incidents/42/diagnose").json() == {"queued": True}assert owner.post("/incidents/42/diagnose").status_code == 200 # asking again is allowedqueued = [json.loads(raw) for raw in app.redis.lrange(jobs.QUEUE, 0, -1)]@@ -600,7 +609,7 @@ def test_chat_is_for_admins_unless_allowed_per_user(app, monkeypatch):ask = lambda: viewer.post("/agent/chat", json={"conversation_id": "v1", "message": "hi"}) # noqa: E731assert ask().status_code == 403 and viewer.get("/agent/config").json()["may_chat"] is False # admins only, the default- owner.put("/admin/settings", json={"agent_chat_access": "per_user"})+ assert owner.put("/admin/settings", json={"agent_chat_access": "per_user", **confirmed(app, owner)}).status_code == 200assert ask().status_code == 403 # per user, but not allowed yetusers = owner.patch("/admin/users/3", json={"agent_chat_enabled": True}).json()assert next(user for user in users["users"] if user["id"] == 3)["agent_chat_enabled"] is True and users["agent_chat_access"] == "per_user"@@ -617,3 +626,65 @@ def test_live_refresh_is_a_display_choice_from_a_fixed_list(app):assert viewer.put("/account/preferences", json={"display": {"live_refresh": 10}}).json()["display"]["live_refresh"] == 10for wrong in (7, 0, "10", True):assert viewer.put("/account/preferences", json={"display": {"live_refresh": wrong}}).json()["display"]["live_refresh"] == 10 # ignored+++# --- confirming changes that send data to the AI provider (#184) ---------------------------------------------------++def test_turning_the_agent_on_needs_the_password_and_a_code(app):+ owner = signed_in(app, 1)+ owner.put("/admin/settings", json={"agent_auto_diagnose": False, "agent_chat_enabled": False}) # stopping needs nothing++ for body in ({"agent_auto_diagnose": True}, {"agent_chat_enabled": True}, {"agent_chat_access": "per_user"}):+ assert owner.put("/admin/settings", json=body).status_code == 403+ assert owner.put("/admin/settings", json={**body, **confirmed(app, owner)}).status_code == 200+ settings = owner.get("/admin/settings").json()+ assert settings["agent_auto_diagnose"] and settings["agent_chat_enabled"] and settings["agent_chat_access"] == "per_user"+++def test_choosing_the_provider_needs_confirmation_but_removing_the_key_does_not(app):+ owner = signed_in(app, 1)+ assert owner.put("/admin/agent/provider", json={"provider": "openai", "api_key": "sk-test-not-real"}).status_code == 403+ assert app.db.get(main.AppSetting, "agent_api_key_openai") is None++ owner.put("/admin/agent/provider", json={"provider": "openai", "api_key": "sk-test-not-real", **confirmed(app, owner)})+ assert owner.delete("/admin/agent/key").json()["key_configured"] is False+++def test_a_wrong_password_gives_no_token(app):+ owner = signed_in(app, 1)+ response = owner.post("/auth/reauth", json={"password": "wrong"})++ assert response.status_code == 401 and "reauth_token" not in response.json()+ assert any("wrong password" in entry.message for entry in app.db.query(AuditLog))+++def test_without_two_factor_the_agent_cant_be_turned_on(app):+ app.db.get(User, 1).totp_enabled = False+ app.db.commit()++ response = signed_in(app, 1).post("/auth/reauth", json={"password": PASSWORD})+ assert response.status_code == 403 and "two-factor" in response.json()["detail"]+++def test_a_wrong_code_says_how_many_tries_are_left_and_the_fifth_ends_it(app):+ owner = signed_in(app, 1)+ fields = confirmed(app, owner)+ body = {"provider": "openai", "api_key": "sk-test-not-real", "reauth_token": fields["reauth_token"]}++ details = [owner.put("/admin/agent/provider", json={**body, "code": "000000"}).json()["detail"] for _ in range(5)]+ assert [detail.split(". ")[-1] for detail in details[:4]] == ["4 tries left.", "3 tries left.", "2 tries left.", "1 try left."]+ assert details[4].startswith("Too many wrong codes")++ late = owner.put("/admin/agent/provider", json={**body, "code": fields["code"]}) # the right code, too late+ assert late.status_code == 401 and app.db.get(main.AppSetting, "agent_api_key_openai") is None+++def test_a_token_works_once_and_only_in_its_own_session(app):+ owner = signed_in(app, 1)+ fields = confirmed(app, owner)+ other_session = signed_in(app, 1)+ assert other_session.put("/admin/settings", json={"agent_chat_access": "per_user", **fields}).status_code == 401++ assert owner.put("/admin/settings", json={"agent_chat_access": "per_user", **fields}).status_code == 200+ owner.put("/admin/settings", json={"agent_chat_access": "admins_only"})+ assert owner.put("/admin/settings", json={"agent_chat_access": "per_user", **fields}).status_code == 401