The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): a signed-in Webapp tab is the machine owner, the same identity native Desktop uses
Teknium8497ce931899
diff --git a/gateway/owner_identity.py b/gateway/owner_identity.pynew file mode 100644index 00000000000..85f3d6be06e--- /dev/null+++ b/gateway/owner_identity.py@@ -0,0 +1,81 @@+"""The Webapp is the machine owner: one identity for every signed-in surface of this host.++Hermes is single-user. Native Desktop, the TUI and the CLI reach the gateway as the owner's own OS+user (``uid:<n>`` / ``sid:<sid>``, minted only for a same-user peer by the control channel). A Webapp+tab, a standalone dashboard's forwarded login or a phone signed in through the dashboard login is+that same person: sign-in only decides whether a browser may open the Webapp at all, it never names a+second owner. So every authenticated non-native principal acts as :func:`host_owner_subject`, and+the login stamps older builds stored (``auth:v1:[provider, issuer, user]`` subjects, the+``<provider>:<user>`` labels ``hermes serve`` stamped on Desktop rows) read as the owner's too.+"""+from __future__ import annotations+++def host_owner_subject() -> str:+ """The owner's own OS identity: the subject native Desktop's ticket carries on this host."""+ from gateway.session_worker_reservation import owner_worker_subject+ return owner_worker_subject()+++def principal_subject(identity: dict) -> str:+ """The subject a connection acts as. Whatever the private control channel or a native grant+ minted (provider ``local``: Desktop, the TUI, the CLI, a managed worker) keeps its subject; every+ login (a Webapp tab, the loopback session token, the server's own PTY child, or a dashboard login+ a standalone backend forwards in a local ticket) is the owner. An identity naming nobody stays+ unbound, exactly as before."""+ from gateway.session_identity import authenticated_subject, parse_authenticated_subject+ subject = authenticated_subject(identity)+ if not identity.get('user_id'):+ return subject+ provider = str(identity.get('provider') or '').strip()+ if provider == 'local':+ login = parse_authenticated_subject(subject)+ return host_owner_subject() if login is not None and _login_provider(login[0]) and login[0] != 'local' else subject+ return host_owner_subject() if _login_provider(provider) else subject+++# The interactive sign-ins Hermes bundles, plus the native grant a served Desktop presented+# (``local:uid:<n>``); a plugin-registered dashboard provider counts too (:func:`_login_provider`).+# ``session-token`` is the loopback Webapp's own credential and ``server-internal`` the PTY child a+# signed-in dashboard spawns: both act for whoever opened that page, the owner.+_BUNDLED_LOGINS = frozenset({'basic', 'nous', 'self-hosted', 'local', 'session-token', 'server-internal'})+++def _login_provider(provider: str) -> bool:+ if provider in _BUNDLED_LOGINS:+ return True+ from hermes_cli.dashboard_auth.registry import list_session_providers+ return any(p.name == provider for p in list_session_providers())+++def _login_label(value: str) -> bool:+ """``<provider>:<user>`` for a dashboard sign-in: the label ``hermes serve`` stamped for a login+ (session_transports). Any other prefix (``telegram:42``, ``uid:501``) names someone else, and a+ ``nous:`` stamp keeps its own rule (``legacy_account_label``: a Desktop row's account label)."""+ provider, sep, user = value.partition(':')+ return bool(sep and user.strip()) and provider != 'nous' and _login_provider(provider)+++def _login_subject(value) -> bool:+ """An ``auth:v1:[provider, issuer, user]`` subject a sign-in stored (a provider is named)."""+ from gateway.session_identity import parse_authenticated_subject+ parts = parse_authenticated_subject(value)+ return parts is not None and bool(parts[2].strip()) and _login_provider(parts[0])+++def same_owner(stored, subject) -> bool:+ """Whether a stored owner subject (room owner, history binding) belongs to *subject*: equal, or a+ login subject a Webapp/dashboard sign-in stored while *subject* is the host owner."""+ if stored == subject:+ return True+ return subject == host_owner_subject() and _login_subject(stored)+++def owns_row_stamp(user_id, subject) -> bool:+ """Whether a routeless local row's ``user_id`` stamp names *subject*: :func:`same_owner`, the+ label of *subject*'s own login, or any ``<provider>:<user>`` login label a served dashboard+ stamped while *subject* is the host owner."""+ from hermes_state_mutation_binding import _login_label as label_of+ if same_owner(user_id, subject) or (user_id is not None and user_id == label_of(subject)):+ return True+ return isinstance(user_id, str) and subject == host_owner_subject() and _login_label(user_id)diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex fdea539c2fe..680c452ceb6 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -150,8 +150,8 @@ class AuthorityConnection:if (not identity.get('user_id')or identity.get('instance_id', authority.instance_id) != authority.instance_id):capabilities = frozenset()- from gateway.session_identity import authenticated_subject- self.actor = Principal(authenticated_subject(identity),+ from gateway.owner_identity import principal_subject+ self.actor = Principal(principal_subject(identity),identity.get('profile_id', authority.profile_id),capabilities, uuid.uuid4().hex)from gateway.session_local_migration import bind_native_transportdiff --git a/gateway/session_hosted_service.py b/gateway/session_hosted_service.pyindex 30c6ef5d0e3..da7755d0ef4 100644--- a/gateway/session_hosted_service.py+++ b/gateway/session_hosted_service.py@@ -113,7 +113,8 @@ class CanonicalHostedRoomService(HostedControls, HostedRoomService):if historical is None:conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (key, actor_subject))return True- if row is None or row[0] != actor_subject:+ from gateway.owner_identity import same_owner+ if row is None or not same_owner(row[0], actor_subject):raise RuntimeStoreError('permission_denied')return Truereturn write(conn) if conn is not None else self.authority.db._execute_write(write)diff --git a/gateway/session_local_migration.py b/gateway/session_local_migration.pyindex fd2015b7529..1344e5753ed 100644--- a/gateway/session_local_migration.py+++ b/gateway/session_local_migration.py@@ -1,7 +1,7 @@"""Owner-only adoption of pre-authority local transcripts.-An old transcript has no authenticated subject. Only a redeemed same-profile-native control ticket may adopt it; remote login is not evidence of ownership.+An old transcript has no authenticated subject. Only the machine owner (a redeemed same-profile+native control ticket, or the owner signed in to the Webapp: gateway.owner_identity) may adopt it.The historical ID becomes the stable logical owner without copying its messages.Compression and reset may later advance the physical target, never FIFO identity."""@@ -17,9 +17,11 @@ from hermes_state_runtime import RuntimeStoreErrordef bind_native_transport(authority, actor, identity):- if (identity.get('provider') == 'local'- and identity.get('profile_id') == authority.profile_id- and identity.get('instance_id') == authority.instance_id+ # The machine owner signed in to the Webapp is the same person native Desktop is (owner_identity).+ from gateway.owner_identity import host_owner_subject+ native = (identity.get('provider') == 'local' and identity.get('profile_id') == authority.profile_id+ and identity.get('instance_id') == authority.instance_id)+ if ((native or actor.subject == host_owner_subject())and actor.profile_id == authority.profile_idand 'session:create' in actor.capabilities):if not hasattr(authority, '_native_legacy_transports'):@@ -33,15 +35,16 @@ def unbind_native_transport(authority, actor):def require_history_claim(authority, conn, actor, sid):"""Import receipts confer ownership; merely knowing an old ID does not."""- from hermes_state_mutation_binding import BINDING_PREFIX, _login_label, _owner_user+ from gateway.owner_identity import owns_row_stamp+ from hermes_state_mutation_binding import BINDING_PREFIX, _owner_userrow = conn.execute('SELECT * FROM sessions WHERE id=?', (sid,)).fetchone()if row is None or row['session_key'] or row['chat_id'] or row['origin_json']:returnif conn.execute('SELECT 1 FROM state_meta WHERE key=?', (BINDING_PREFIX + sid,)).fetchone():return # authorize_history checks the already committed importer identity.own_profile = row['profile_name'] in (None, '', authority.db._own_profile_name() or 'default')- if own_profile and _owner_user(row) and row['user_id'] in (actor.subject, _login_label(actor.subject)):- return # The login that created it (a served remote Desktop); authorize_history re-checks it.+ if own_profile and _owner_user(row) and owns_row_stamp(row['user_id'], actor.subject):+ return # Its owner (a login stamp is the machine owner's); authorize_history re-checks it.if getattr(authority, '_native_legacy_transports', {}).get(actor.transport_id) != actor:raise RuntimeStoreError('permission_denied')diff --git a/hermes_cli/web_server_sessions.py b/hermes_cli/web_server_sessions.pyindex 0ea01c36057..b9cdb24b48e 100644--- a/hermes_cli/web_server_sessions.py+++ b/hermes_cli/web_server_sessions.py@@ -95,12 +95,12 @@ def _session_mutation_context(request, profile):if native is not None:subject = native['subject']elif session is not None:- from gateway.session_identity import authenticated_subject- subject = authenticated_subject({"user_id": session.user_id,+ from gateway.owner_identity import principal_subject+ subject = principal_subject({"user_id": session.user_id,"provider": session.provider, "issuer": session.issuer})elif not getattr(request.app.state, 'auth_required', False) and _has_valid_session_token(request):- from gateway.session_identity import authenticated_subject- subject = authenticated_subject({'user_id': 'legacy-token-owner', 'provider': 'session-token'})+ from gateway.owner_identity import host_owner_subject+ subject = host_owner_subject()else:raise HTTPException(status_code=401, detail='Unauthorized')authority = getattr(request.app.state, 'session_authority', None)diff --git a/hermes_state_local_migration.py b/hermes_state_local_migration.pyindex a098f4c81d8..caac43ef386 100644--- a/hermes_state_local_migration.py+++ b/hermes_state_local_migration.py@@ -25,20 +25,18 @@ def legacy_account_label(row):def login_owned_by(row, subject):- """Whether *subject* is the login a served remote backend stamped on this Desktop row.+ """Whether *subject* owns the login stamp a served dashboard put on this row.- ``hermes serve`` stamps the WS-upgrade login as ``<provider>:<user id>``- (tui_gateway/session_transports.py). Unlike the Nous label that stamp IS an owner: once a- login's dashboard writes reach the gateway as that login, reading it as no-owner let login bob- rename, claim and delete alice's chats (#140183 review F1). So it adopts only for the caller- whose authenticated subject spells exactly that label (``_login_label``: issuer-less logins- only); every other caller, the host's own native peer included, still meets a foreign owner.+ Older ``hermes serve`` builds stamped the WS-upgrade login as ``<provider>:<user id>``+ (tui_gateway/session_transports.py), and the gateway stored a Webapp login as its+ ``auth:v1:[...]`` subject. Hermes is single-user and sign-in is owner-only, so both name the+ machine owner: the host owner's subject adopts them (gateway.owner_identity.owns_row_stamp)."""user_id = row.get('user_id')- if row['source'] != 'desktop' or not isinstance(user_id, str) or not subject:+ if not isinstance(user_id, str) or not subject:return False- from hermes_state_mutation_binding import _login_label- return _login_label(subject) == user_id+ from gateway.owner_identity import owns_row_stamp+ return owns_row_stamp(user_id, subject)def validate_legacy_row(db, row, *, subject=None):diff --git a/hermes_state_mutation_binding.py b/hermes_state_mutation_binding.pyindex 7c3fc94a5f3..d80d4597bd6 100644--- a/hermes_state_mutation_binding.py+++ b/hermes_state_mutation_binding.py@@ -35,6 +35,17 @@ def _login_label(subject):return None if label.startswith('auth:') else label+def _bound_to(saved, actor):+ """Whether a stored ``[profile_id, subject]`` binding names *actor*: same profile, and the same+ owner (a binding a Webapp login stored belongs to the machine owner, gateway.owner_identity)."""+ try:+ profile_id, subject = json.loads(saved)+ except (TypeError, ValueError):+ return False+ from gateway.owner_identity import same_owner+ return profile_id == actor.profile_id and same_owner(subject, actor.subject)++def import_history_control(conn, actor, session_ids):binding = json.dumps([actor.profile_id, actor.subject], separators=(',', ':'))for sid in session_ids:@@ -54,12 +65,13 @@ def authorize_history(conn, actor, session_id, *, claim=False):binding = json.dumps([actor.profile_id, actor.subject], separators=(',', ':'))saved = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()if saved is not None:- if saved[0] != binding:+ if not _bound_to(saved[0], actor):raise RuntimeStoreError('permission_denied')return Trueif row['source'] not in _history_sources():return False- if _owner_user(row) and row['user_id'] not in (actor.subject, _login_label(actor.subject)):+ from gateway.owner_identity import owns_row_stamp+ if _owner_user(row) and not owns_row_stamp(row['user_id'], actor.subject):raise RuntimeStoreError('permission_denied')if 'session:create' not in actor.capabilities:raise RuntimeStoreError('permission_denied')diff --git a/plugins/dashboard_auth/self_hosted/__init__.py b/plugins/dashboard_auth/self_hosted/__init__.pyindex f65a24ec348..8cd4fbe79ca 100644--- a/plugins/dashboard_auth/self_hosted/__init__.py+++ b/plugins/dashboard_auth/self_hosted/__init__.py@@ -21,7 +21,7 @@ from typing import Any, Dict, Optionalimport httpx-from hermes_cli.dashboard_auth import LoginStart, ProviderError, Session+from hermes_cli.dashboard_auth import InvalidCodeError, LoginStart, ProviderError, Sessionfrom plugins.dashboard_auth._shared import (DEFAULT_TOKEN_LEEWAY_SECONDS,JSON_HEADERS,@@ -89,7 +89,7 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):def __init__(self, *, issuer: str, client_id: str, scopes: str = _DEFAULT_SCOPES, client_secret: str = "",- id_token_leeway: float = DEFAULT_TOKEN_LEEWAY_SECONDS,+ id_token_leeway: float = DEFAULT_TOKEN_LEEWAY_SECONDS, owner: str = "",) -> None:if not issuer:raise ValueError("issuer is required")@@ -107,6 +107,7 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):# Empty/whitespace secret ⇒ public client, so a provisioned-but-blank secret# can't flip us into a broken confidential mode.self._client_secret = (client_secret or "").strip()+ self._owner = (owner or "").strip()# Discovery + JWKS resolve lazily so registration never hits the network# (the IDP may be down at boot; fail per-request instead).self._discovery: dict[str, Any] | None = None@@ -183,7 +184,12 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):"OIDC token response missing id_token — ensure the 'openid' ""scope is configured and the client is allowed to receive an ""ID token."))- claims = self._verify_id_token(id_token)+ try:+ claims = self._owner_claims(id_token)+ except InvalidCodeError as exc:+ if bad_request_exc is InvalidCodeError:+ raise+ raise bad_request_exc(str(exc)) from exc # a refresh for another account just ends# Prefer a freshly-issued RT, else keep the previous (some IDPs don't rotate).return self._session(id_token, refresh_token_from(payload, previous_refresh_token), claims)@@ -267,7 +273,17 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):id_token, self._get_jwks_client(), algorithms=list(_ALLOWED_ID_TOKEN_ALGS),audience=self._client_id, issuer=issuer, label="ID token", leeway=self._id_token_leeway)- _claims_for = _verify_id_token+ def _owner_claims(self, id_token: str) -> dict[str, Any]:+ """Verified claims of the machine owner's IdP account only. Hermes is single-user: a signed-in+ Webapp tab acts as the owner (gateway.owner_identity), so any other account of the same IdP+ must not sign in at all. ``dashboard.oauth.self_hosted.owner`` names the owner's ``sub``;+ unset, the first account that signs in is pinned as the owner (``owner_pin``)."""+ claims = self._verify_id_token(id_token)+ from plugins.dashboard_auth.self_hosted.owner_pin import require_owner+ require_owner(self._issuer, str(claims.get("sub", "")), self._owner)+ return claims++ _claims_for = _owner_claimsdef _session(self, id_token: str, refresh_token: str, claims: dict[str, Any]) -> Session:"""Map verified OIDC claims onto a Session. The verified ID token is stored in@@ -314,7 +330,9 @@ def _settings() -> dict:# Credential: canonical home is the env var / ~/.hermes/.env. Empty ⇒ public client."client_secret": setting("HERMES_DASHBOARD_OIDC_CLIENT_SECRET", "client_secret"),# Clock-skew tolerance for ID-token exp/nbf/iat (config.yaml only; default 60s, 0 = strict).- "id_token_leeway": parse_leeway(oidc_cfg.get("id_token_leeway"))}+ "id_token_leeway": parse_leeway(oidc_cfg.get("id_token_leeway")),+ # The owner's ``sub`` (config.yaml only): the one IdP account that may sign in.+ "owner": str(oidc_cfg.get("owner") or "")}def register(ctx) -> None:diff --git a/plugins/dashboard_auth/self_hosted/owner_pin.py b/plugins/dashboard_auth/self_hosted/owner_pin.pynew file mode 100644index 00000000000..915ed33c14f--- /dev/null+++ b/plugins/dashboard_auth/self_hosted/owner_pin.py@@ -0,0 +1,50 @@+"""Self-hosted OIDC sign-in is owner-only: one IdP account, the machine owner's.++Hermes is single-user, and a signed-in Webapp tab acts as the machine owner (gateway.owner_identity).+An OIDC provider can hold many accounts, so the sign-in admits exactly one: the ``sub`` named by+``dashboard.oauth.self_hosted.owner``, or, when that is unset, the first account that signs in, whose+``[issuer, sub]`` is pinned in ``dashboard-auth/self-hosted-owner.json`` under the Hermes root home.+Any other account is refused like an invalid token (the callback reports a failed sign-in).+"""+from __future__ import annotations++import json+import logging+import os+import threading++from hermes_cli.dashboard_auth import InvalidCodeError++logger = logging.getLogger(__name__)+_lock = threading.Lock()+++def _pin_path():+ from hermes_constants import get_process_hermes_home+ return get_process_hermes_home() / "dashboard-auth" / "self-hosted-owner.json"+++def require_owner(issuer: str, sub: str, configured: str) -> None:+ """Raise :class:`InvalidCodeError` unless *sub* is the owner's account."""+ if not sub:+ raise InvalidCodeError("ID token names no account")+ if configured:+ if sub != configured:+ raise InvalidCodeError("this account is not the owner of this Hermes")+ return+ path = _pin_path()+ with _lock:+ try:+ pinned = json.loads(path.read_text(encoding="utf-8-sig"))+ except FileNotFoundError:+ pinned = None+ if pinned is None:+ path.parent.mkdir(parents=True, exist_ok=True)+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ json.dump([issuer, sub], handle)+ logger.warning("dashboard-auth-self-hosted: pinned the first account to sign in as this Hermes's "+ "owner (%s); set dashboard.oauth.self_hosted.owner to choose it", path)+ return+ if pinned != [issuer, sub]:+ raise InvalidCodeError("this account is not the owner of this Hermes")diff --git a/tests/gateway/test_authenticated_session_identity.py b/tests/gateway/test_authenticated_session_identity.pyindex 8e01e562b84..f5483785bef 100644--- a/tests/gateway/test_authenticated_session_identity.py+++ b/tests/gateway/test_authenticated_session_identity.py@@ -67,7 +67,7 @@ def connection(authority, session, monkeypatch):@pytest.mark.asyncio-async def test_bundled_provider_issuer_subject_owns_durable_receipts(tmp_path, monkeypatch, oidc):+async def test_every_bundled_sign_in_acts_as_the_owner_and_keeps_durable_receipts(tmp_path, monkeypatch, oidc):from gateway import runfrom gateway.config import GatewayConfigfrom gateway.session import SessionStore@@ -100,21 +100,19 @@ async def test_bundled_provider_issuer_subject_owns_durable_receipts(tmp_path, moauth = oidc('user-a')basic = BasicAuthProvider(username='user-a', password_hash=hash_password('fixture-password'), secret=b'fixture-secret-32-characters-long')password = basic.complete_password_login(username='user-a', password='fixture-password')- owner, other, same_sub = await actor(oauth), await actor(oidc('user-b')), await actor(password)+ owner, by_password = await actor(oauth), await actor(password)+ # The Webapp is single-user: whichever bundled sign-in opened it, the tab acts as the machine+ # owner, the same subject native Desktop's ticket carries (gateway.owner_identity).+ from gateway.owner_identity import host_owner_subject+ assert owner.subject == by_password.subject == host_owner_subject()params = {'request_id': 'same-request', 'source': 'gui', 'cwd': str(tmp_path), 'model': 'fixture', 'toolsets': []}ref = create_local_session(authority, owner, params)from gateway.session_mutations import mutate_sessionedit = dict(session_id=ref.session_id, request_id='oauth-rename', expected_revision=0,operation='rename', payload={'title': 'OAuth owned'})receipt = await mutate_session(authority, owner, ref, edit)- for foreign in (other, same_sub):- with pytest.raises(RuntimeStoreError, match='permission_denied'):- await authority.resolve(foreign, ref)- assert create_local_session(authority, foreign, params) != ref- # Same provider name under a different verified issuer is a different authority.- foreign_issuer = await actor(oidc('user-a', '/other'))- with pytest.raises(RuntimeStoreError, match='permission_denied'):- await authority.resolve(foreign_issuer, ref)+ assert create_local_session(authority, by_password, params) == ref+ assert await mutate_session(authority, by_password, ref, edit) == receiptfrom gateway.session_identity import authenticated_principal_digestassert authenticated_principal_digest({'provider': oauth.provider, 'issuer': oauth.issuer, 'user_id': oauth.user_id}) != authenticated_principal_digest({'provider': oauth.provider, 'issuer': oauth.issuer + '/other', 'user_id': oauth.user_id})@@ -124,12 +122,11 @@ async def test_bundled_provider_issuer_subject_owns_durable_receipts(tmp_path, massert create_local_session(cold, reconnect, params) == refassert await mutate_session(cold, reconnect, ref, edit) == receiptassert (await cold.resolve(reconnect, ref)).ref == ref- # Pre-cutover remote records have no issuer provenance: never adopt on first request.+ # A bare pre-cutover subject is not a sign-in the owner stored: never adopted on first request.old = create_local_session(cold, Principal('user-a', owner.profile_id, owner.capabilities, 'old'),{**params, 'request_id': 'old-ambiguous'})- for current in (reconnect, same_sub):- with pytest.raises(RuntimeStoreError, match='permission_denied'):- await cold.resolve(current, old)+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ await cold.resolve(reconnect, old)@pytest.mark.asynciodiff --git a/tests/gateway/test_legacy_session_migration.py b/tests/gateway/test_legacy_session_migration.pyindex 9a87f9e0f38..ae4b06daee3 100644--- a/tests/gateway/test_legacy_session_migration.py+++ b/tests/gateway/test_legacy_session_migration.py@@ -213,23 +213,16 @@ async def test_upgraded_desktop_history_resumes_by_id(tmp_path, monkeypatch):stamped = await native.dispatch({'id': 2, 'method': 'session.resume', 'params': {'session_id': 'old-desktop-account'}})assert stamped.get('result', {}).get('session_id') == 'old-desktop-account', stampedassert [m['content'] for m in stamped['result']['messages']] == ['OLD-DESKTOP-ACCOUNT']- # A served remote backend stamped its basic-auth login on the row at creation (#139818). That- # stamp is the login's ownership, not a label (#140183 review F1): another login and the host's- # own native peer are refused without a write; the same login adopts it once its serve is gone.+ # A served remote backend stamped its basic-auth login on the row at creation (#139818). Hermes+ # is single-user and sign-in is owner-only, so that login is the machine owner: the owner's own+ # native ticket (native Desktop, the TUI) adopts it once its serve is gone (gateway.owner_identity).caps = ['session:create', 'session:read', 'session:submit', 'session:control', 'session:approve','session:respond']-- def login(user):- subject = 'auth:v1:' + json.dumps(['basic', '', user], separators=(',', ':'))- return AuthorityConnection(authority, object(), {'provider': 'local', 'user_id': subject,- 'profile_id': str(tmp_path), 'instance_id': 'first', 'capabilities': caps})- for stranger in (login('bob'), native):- refused = await stranger.dispatch({'id': 4, 'method': 'session.resume',- 'params': {'session_id': 'old-desktop-remote'}})- assert refused.get('error', {}).get('message') == 'not_found', refused- assert db.get_session('old-desktop-remote')['user_id'] == 'basic:hermes'- remote = await login('hermes').dispatch({'id': 5, 'method': 'session.resume',- 'params': {'session_id': 'old-desktop-remote'}})+ from gateway.owner_identity import host_owner_subject+ owner = AuthorityConnection(authority, object(), {'provider': 'local', 'user_id': host_owner_subject(),+ 'profile_id': str(tmp_path), 'instance_id': 'first', 'capabilities': caps})+ remote = await owner.dispatch({'id': 5, 'method': 'session.resume',+ 'params': {'session_id': 'old-desktop-remote'}})assert remote.get('result', {}).get('session_id') == 'old-desktop-remote', remoteassert [m['content'] for m in remote['result']['messages']] == ['OLD-DESKTOP-REMOTE']# Any other identity, or a Nous stamp on a non-Desktop row, still needs its own authority.diff --git a/tests/gateway/test_webapp_owner_identity.py b/tests/gateway/test_webapp_owner_identity.pynew file mode 100644index 00000000000..a77917ca810--- /dev/null+++ b/tests/gateway/test_webapp_owner_identity.py@@ -0,0 +1,78 @@+"""The Webapp is the machine owner: a signed-in tab and native Desktop share Group Chats and history.++Hermes is single-user. Sign-in only decides whether a browser may open the Webapp; it never names a+second owner. So a Webapp tab's Group Chats are native Desktop's (and the reverse), and the rooms an+older build stored under the tab's ``auth:v1`` login subject are still the owner's, while another OS+user's subject or a messaging identity stays foreign (gateway.owner_identity).+"""+from types import SimpleNamespace++import pytest++from gateway.owner_identity import host_owner_subject, owns_row_stamp+from hermes_state import SessionDB+from hermes_state_runtime import begin_runtime_epoch++MEMBERS = [{'member_id': 'one', 'profile': 'default', 'handle': 'one'},+ {'member_id': 'two', 'profile': 'two', 'handle': 'two'}]+NATIVE = {'provider': 'local', 'user_id': host_owner_subject(), 'profile_id': None, 'instance_id': 'owner',+ 'capabilities': ['session:create', 'session:read', 'session:submit', 'session:control']}+++def authority(tmp_path, monkeypatch):+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ (tmp_path / 'profiles' / 'two').mkdir(parents=True)+ (tmp_path / 'config.yaml').write_text(+ 'hosted_rooms:\n profiles:\n two: ' + str((tmp_path / 'profiles' / 'two').resolve()) + '\n')+ from gateway.session_hosted_service import CanonicalHostedRoomService+ with SessionDB(tmp_path / 'state.db') as db:+ authority = SimpleNamespace(db=db, profile_id=str(tmp_path), instance_id='owner', events={},+ epoch=begin_runtime_epoch(db, instance_id='test'))+ authority.hosted_room_service = CanonicalHostedRoomService(authority, None)+ yield authority+++async def _call(connection, method, **params):+ reply = await connection.dispatch({'id': 1, 'method': method, 'params': params})+ return reply.get('result', reply.get('error', {}).get('message'))+++def _connect(authority, identity):+ from gateway.session_controls import AuthorityConnection+ if identity.get('provider') == 'local':+ identity = {**identity, 'profile_id': authority.profile_id}+ return AuthorityConnection(authority, object(), identity)+++async def test_a_webapp_tab_and_native_desktop_share_one_group_chat_list(authority):+ webapp = _connect(authority, {'user_id': 'admin', 'provider': 'basic'})+ desktop = _connect(authority, NATIVE)+ assert webapp.actor.subject == desktop.actor.subject == host_owner_subject()+ assert await _call(webapp, 'groups.create', room_id='web-room', name='Web', members=MEMBERS) is not None+ assert await _call(desktop, 'groups.create', room_id='desk-room', name='Desk', members=MEMBERS) is not None+ for surface in (webapp, desktop):+ listed = await _call(surface, 'groups.list')+ assert {room['room_id'] for room in listed['rooms']} == {'web-room', 'desk-room'}+++async def test_a_room_an_older_build_stored_under_the_login_stays_the_owners(authority):+ from gateway.session_hosted_service import _OWNER+ desktop = _connect(authority, NATIVE)+ assert await _call(desktop, 'groups.create', room_id='old-web-room', name='Old', members=MEMBERS) is not None+ authority.db._execute_write(lambda conn: conn.execute('UPDATE state_meta SET value=? WHERE key=?',+ ('auth:v1:["basic","","admin"]', _OWNER + 'old-web-room')))+ assert [r['room_id'] for r in (await _call(desktop, 'groups.list'))['rooms']] == ['old-web-room']+ stranger = _connect(authority, {**NATIVE, 'user_id': 'uid:999999'})+ assert (await _call(stranger, 'groups.list'))['rooms'] == []++[email protected]('stamp, owned', [+ ('basic:admin', True), ('local:uid:1000', True), ('auth:v1:["self-hosted","https://idp","sub"]', True),+ ('telegram:42', False), ('uid:999999', False), ('nous:account', False), ('auth:v1:["","","x"]', False),+])+def test_only_sign_in_stamps_read_as_the_owners(stamp, owned):+ assert owns_row_stamp(stamp, host_owner_subject()) is owned+ assert owns_row_stamp(stamp, 'uid:999999') is (stamp == 'uid:999999')diff --git a/tests/plugins/dashboard_auth/test_self_hosted_owner_only.py b/tests/plugins/dashboard_auth/test_self_hosted_owner_only.pynew file mode 100644index 00000000000..cc9575b080e--- /dev/null+++ b/tests/plugins/dashboard_auth/test_self_hosted_owner_only.py@@ -0,0 +1,27 @@+"""Self-hosted OIDC sign-in admits one account, the machine owner's (the Webapp is single-user)."""+import pytest++from hermes_cli.dashboard_auth import InvalidCodeError+from plugins.dashboard_auth.self_hosted import owner_pin+++def pin_file(tmp_path, monkeypatch):+ path = tmp_path / "dashboard-auth" / "self-hosted-owner.json"+ monkeypatch.setattr(owner_pin, "_pin_path", lambda: path)+ return path+++def test_the_configured_owner_is_the_only_account_that_signs_in(pin_file):+ owner_pin.require_owner("https://idp", "owner-sub", "owner-sub")+ with pytest.raises(InvalidCodeError):+ owner_pin.require_owner("https://idp", "colleague-sub", "owner-sub")+ assert not pin_file.exists()+++def test_unconfigured_the_first_account_is_pinned_and_no_other_signs_in(pin_file):+ owner_pin.require_owner("https://idp", "first-sub", "")+ owner_pin.require_owner("https://idp", "first-sub", "")+ for issuer, sub in (("https://idp", "second-sub"), ("https://other-idp", "first-sub")):+ with pytest.raises(InvalidCodeError):+ owner_pin.require_owner(issuer, sub, "")diff --git a/tests/tui_gateway/test_desktop_session_login_identity.py b/tests/tui_gateway/test_desktop_session_login_identity.pyindex dc90d84d270..fa4ba9a9d1b 100644--- a/tests/tui_gateway/test_desktop_session_login_identity.py+++ b/tests/tui_gateway/test_desktop_session_login_identity.py@@ -14,12 +14,15 @@ identity-less: nothing is inferred and nothing is stamped.from __future__ import annotations+from gateway.owner_identity import host_owner_subjectfrom hermes_state import SessionDBfrom tui_gateway import serverfrom tui_gateway.transport import bind_transport, reset_transport_LOADED_USER = "alice"-_LOGIN = f"basic:{_LOADED_USER}"+# A signed-in login is the machine owner (gateway.owner_identity): its row carries the owner's OS+# subject, the one native Desktop's own sessions carry, so Desktop and the TUI resume it.+_LOGIN = host_owner_subject()class _LoginSocket:@@ -62,7 +65,7 @@ def _create_desktop_session(transport, tmp_path) -> tuple[dict, str, str]:def test_desktop_session_row_records_the_logged_in_user(monkeypatch, tmp_path):- """Login succeeded, then a conversation: the row must name the human."""+ """Login succeeded, then a conversation: the row must name the owner."""db = _real_db(monkeypatch, tmp_path)record, sid, key = _create_desktop_session(_LoginSocket(), tmp_path)try:diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex 00832e49063..46bd163dc45 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -13,6 +13,7 @@ from unittest.mock import Mock, patchimport pytest+from gateway.owner_identity import host_owner_subject as _ownerfrom hermes_constants import reset_hermes_home_override, set_hermes_home_overridefrom hermes_cli.active_sessions import active_session_registry_snapshotfrom hermes_cli.browser_connect import ChromeDebugLaunch@@ -4665,18 +4666,17 @@ def _capture_make_agent_kwargs(monkeypatch) -> dict:@pytest.mark.parametrize("identity, user_id", [- ({"user_id": "oidc|abc123", "provider": "oidc"}, "oidc:oidc|abc123"),- ({"user_id": "alice", "provider": "basic"}, "basic:alice"),- ({"user_id": "alice", "provider": "oidc"}, "oidc:alice"),+ ({"user_id": "oidc|abc123", "provider": "oidc"}, _owner()),+ ({"user_id": "alice", "provider": "basic"}, _owner()),+ ({"user_id": "alice", "provider": "oidc"}, _owner()),(None, None),({"user_id": "server-internal", "provider": "server-internal"}, None),({"user_id": "", "provider": "oidc"}, None),({"user_id": "abc", "provider": ""}, None),])def test_make_agent_passes_the_authenticated_dashboard_user_as_user_id(monkeypatch, identity, user_id):- """WSTransport.auth_identity reaches the agent as ``user_id`` prefixed with the login provider, so a- basic-auth ``alice`` and an OIDC ``alice`` stay two memory peers. The legacy token, stdio and the PTY- child's server-internal credential name no human, so the agent gets no user id for them."""+ """A signed-in login is the machine owner (gateway.owner_identity): the agent gets native Desktop's OS subject+ as ``user_id``. The legacy token, stdio and the PTY child's server-internal credential stay unstamped."""captured = _capture_make_agent_kwargs(monkeypatch)transport = types.SimpleNamespace(auth_identity=identity)monkeypatch.setitem(server._sessions, "sid-auth", {"session_key": "k", "transport": transport})@@ -4723,11 +4723,11 @@ def test_make_agent_keeps_the_login_after_a_second_window_attaches_and_detaches(assert server._attach_session_transport(record, popout)server._make_agent("sid-popout", "k")- assert captured["user_id"] == "basic:alice"+ assert captured["user_id"] == _owner()server._detach_session_transport(record, popout)server._make_agent("sid-popout", "k")- assert captured["user_id"] == "basic:alice"+ assert captured["user_id"] == _owner()def test_build_branch_agent_carries_the_parent_login(monkeypatch, tmp_path):@@ -4750,8 +4750,8 @@ def test_build_branch_agent_carries_the_parent_login(monkeypatch, tmp_path):finally:reset_transport(token)- assert captured["user_id"] == "basic:alice"- assert server._sessions["sid-branch"]["auth_user_id"] == "basic:alice"+ assert captured["user_id"] == _owner()+ assert server._sessions["sid-branch"]["auth_user_id"] == _owner()def test_deferred_session_record_stamps_the_creating_login():@@ -4762,8 +4762,8 @@ def test_deferred_session_record_stamps_the_creating_login():finally:reset_transport(token)- assert record["auth_user_id"] == "oidc:carol"- assert server._session_auth_user_id(record) == "oidc:carol"+ assert record["auth_user_id"] == _owner()+ assert server._session_auth_user_id(record) == _owner()def test_compute_host_turn_frame_carries_the_session_login(monkeypatch):@@ -4773,7 +4773,7 @@ def test_compute_host_turn_frame_carries_the_session_login(monkeypatch):frame = server._compute_host_turn_frame("rid", "sid-host", record, "hello")- assert frame["auth_user_id"] == "basic:alice"+ assert frame["auth_user_id"] == _owner()def test_attaching_a_different_login_keeps_the_creator_and_warns_once(monkeypatch):@@ -4785,7 +4785,7 @@ def test_attaching_a_different_login_keeps_the_creator_and_warns_once(monkeypatcassert server._attach_session_transport(record, other)assert server._attach_session_transport(record, other)- assert server._session_auth_user_id(record) == "basic:alice"+ assert server._session_auth_user_id(record) == _owner()def test_background_agent_kwargs_preserves_full_fallback_chain(monkeypatch):diff --git a/tui_gateway/session_transports.py b/tui_gateway/session_transports.pyindex 77da8a77189..1cfeaca8fc8 100644--- a/tui_gateway/session_transports.py+++ b/tui_gateway/session_transports.py@@ -36,13 +36,13 @@ def _session_has_live_transport(session: dict | None, *, excluding=None) -> booldef _transport_auth_user_id(transport) -> str | None:- """``<provider>:<user id>`` the WS-upgrade credential authenticated for ``transport``, or None for the legacy- token, stdio and the PTY child's server-internal credential. The prefix keeps a basic-auth ``alice`` and an- OIDC ``alice`` apart."""+ """The owner a row created over ``transport`` belongs to: the host owner's OS subject for any WS-upgrade+ login (a signed-in Webapp or dashboard tab is the machine owner, gateway.owner_identity), so native Desktop+ and the TUI resume it; None for the legacy token, stdio and the PTY child's server-internal credential."""from gateway.session_identity import is_authenticated_identity- identity = getattr(transport, "auth_identity", None)- if is_authenticated_identity(identity):- return f"{str(identity['provider']).strip()}:{str(identity['user_id']).strip()}"+ if is_authenticated_identity(getattr(transport, "auth_identity", None)):+ from gateway.owner_identity import host_owner_subject+ return host_owner_subject()return Nonediff --git a/website/docs/user-guide/features/web-dashboard.md b/website/docs/user-guide/features/web-dashboard.mdindex 237ea018e25..db8f8ce1869 100644--- a/website/docs/user-guide/features/web-dashboard.md+++ b/website/docs/user-guide/features/web-dashboard.md@@ -883,6 +883,7 @@ dashboard:client_id: hermes-dashboard # requiredscopes: "openid profile email" # optional (this is the default)id_token_leeway: 60 # optional; seconds of clock-skew tolerance+ owner: "<your sub claim>" # optional; the one account that may sign in```**Environment variables** — operator overrides (env wins over `config.yaml` when set non-empty; an empty value is treated as unset):@@ -897,6 +898,8 @@ In your IDP, register a **public** application/client with the authorization-cod#### What it verifies+Hermes is single-user, so this sign-in admits exactly one IdP account: the machine owner's. Name it with `dashboard.oauth.self_hosted.owner` (the account's `sub` claim). Unset, the first account that signs in is pinned as the owner in `dashboard-auth/self-hosted-owner.json` under your Hermes home (delete that file to choose again), and every other account of the IdP gets a failed sign-in. A signed-in browser acts as you on this machine: it sees and resumes the same chats and Group Chats as native Desktop.+The provider verifies the OpenID Connect **ID token** (RS256/ES256) against the discovered `jwks_uri`, with the `iss` and `aud` claims pinned to your configured `issuer` and `client_id`. The time claims (`exp`/`nbf`/`iat`) are verified with a 60-second clock-skew leeway (RFC 7519 §4.1.4-4.1.6), so a dashboard host whose clock lags the IDP's doesn't fail login; tune it with `dashboard.oauth.self_hosted.id_token_leeway` in `config.yaml` (any value below `60` tightens it, `0` restores strict verification, and an invalid value fails closed to `0`). Standard OIDC claims map onto the dashboard session:| Session field | Claim(s) |