Metadata-Version: 2.5
Name: qodalis-cli-server-plugin-users
Version: 1.0.0b34
Summary: User management plugin for Qodalis CLI servers — authentication, sessions, groups and API tokens, recorded in the audit plugin's log
Project-URL: Homepage, https://github.com/qodalis-solutions/cli-server-python
Project-URL: Repository, https://github.com/qodalis-solutions/cli-server-python
Project-URL: Issues, https://github.com/qodalis-solutions/cli-server-python/issues
Author-email: Nicolae Lupei <nicolae.lupei@qodalis.com>
License-Expression: MIT
License-File: LICENSE
Keywords: auth,cli,plugin,qodalis,sessions,users
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Requires-Dist: fastapi>=0.100.0
Requires-Dist: qodalis-cli-server-plugin-audit>=1.0.0b17
Description-Content-Type: text/markdown

# qodalis-cli-server-plugin-users

User management plugin for [Qodalis CLI Server (Python)](https://github.com/qodalis-solutions/cli-server-python). Adds FastAPI endpoints for authentication, users, groups with permissions, sessions and API tokens, records its events in the [audit plugin](../audit/README.md)'s log (which it mounts), backed by swappable storage interfaces with in-memory defaults. It is the server side of the `@qodalis/cli-users` plugin's *server mode* and implements the same contract as the node and .NET servers.

## Install

```bash
pip install qodalis-cli-server-plugin-users
```

## Quick Start

```python
from contextlib import asynccontextmanager
from qodalis_cli import create_cli_server
from qodalis_cli_users import CliUsersBuilder

result = create_cli_server(...)

users_plugin = CliUsersBuilder().build()
# Mounts the routes at /api/v1/qcli, protects every route and socket of the
# server, delivers user events only to that user's event sockets and mounts
# the audit plugin (/api/v1/qcli/audit).
result.mount_plugin(users_plugin)

original_lifespan = result.app.router.lifespan_context

@asynccontextmanager
async def lifespan(app):
    await users_plugin.startup()   # seed built-ins + start the session sweep (and adapter socket re-checks)
    try:
        async with original_lifespan(app) as state:
            yield state
    finally:
        await users_plugin.shutdown()

result.app.router.lifespan_context = lifespan
```

`startup()` seeds the built-in groups `admin` (`["*"]`) and `users` (`["commands:execute"]`) and, when the user store is empty and no external auth adapter is set, a `root` user (`root@localhost`, group `admin`). Without `set_default_admin_password(...)` a random 16-character password is generated, logged **once** (never to log sockets or the admin log buffer) and root must change it at first login; a well-known explicit password (`root`, `admin`, `password`) logs a warning. Requests that arrive before `startup()` also trigger seeding.

## Builder

| Method | Default | Description |
|--------|---------|-------------|
| `set_user_store` / `set_session_store` / `set_credential_store` / `set_group_store` / `set_audit_store` / `set_api_token_store` | in-memory | Storage implementations |
| `set_allow_non_expiring_tokens(bool)` | `False` | Allow API tokens that never expire (`expiresInDays: null`) |
| `set_allow_api_tokens(bool)` | `False` | With an external auth adapter, also accept API tokens and terminal links (see [API tokens](#api-tokens)) |
| `set_link_approval_url(url)` | `/qcli/admin/link` | The page where users approve a terminal's link request (absolute or root-relative; `{code}` is replaced, otherwise `?code=` is appended) |
| `set_default_admin_password(str)` | generated | Password of the seeded `root` user |
| `set_session_timeout(ms)` | `1800000` (30 min) | Idle timeout, checked on every request |
| `set_max_session_lifetime(ms)` | `43200000` (12 h) | Absolute session lifetime |
| `set_min_password_length(n)` | `8` | Password policy (max length 1024) |
| `set_rate_limit(n, window_ms)` | `20`, `60000` | Per-IP limit for login, verify-password and self password change |
| `set_trust_proxy(bool \| int)` | `False` | Trusted proxy hops for the client IP: `False`/`0` = socket peer (header ignored), `True` = 1, `n` = n hops; the client is the `X-Forwarded-For` entry at `len - n` (rightmost for one proxy, leftmost if fewer entries) |
| `set_allowed_origins(list)` | server's `allowed_origins` | Origins accepted for bearer-less state changes (CSRF, adapter mode) |
| `set_protect_server(bool)` | `True` | Protect every CLI server route and socket when mounted |
| `set_max_login_attempts(n)` | `5` | Consecutive failures before lockout |
| `set_lockout(ms)` | `300000` (5 min) | Lockout duration |
| `set_cleanup_interval(ms)` | `300000` (5 min) | Background expired-session sweep |
| `set_read_only_users(bool=True)` | `False` | The host owns the users: user writes answer `501` (see [Read-only stores](#read-only-stores)) |
| `set_read_only_groups(bool=True)` | `False` | The host owns the groups: group writes answer `501` |
| `set_auth_adapter(adapter)` | `None` | Delegate authentication to the host app (a sync or async callable; see below) |
| `build(broadcast_fn=None, event_bus=None)` | | Returns a `CliUsersPlugin` (`prefix`, `router`, `startup()`, `shutdown()`, `require_auth`, `require_permission(p)`, `require_cli_auth`, `api_tokens`, `protect(app)`, `auth_service`, stores) |

When mounted with `result.mount_plugin(...)`, user-scoped events (`session-kicked`) go only to event sockets authenticated as that user, and the [server events](#server-events) go to the server's event bus. `broadcast_fn` (JSON strings, sync or async) is only used when the plugin is not mounted on a CLI server (and has no `event_bus`).

### Guards for host routes

```python
@app.get("/my/route")
async def handler(ctx = Depends(users_plugin.require_permission("deploy:run"))):
    return {"user": ctx.user.name}
```

`users_plugin.require_auth` only requires an authenticated session.

Once a guard has fully passed (authentication, audience, permission), it makes the caller available to the handler as `request.state.qcli_caller` (a refused request has none), a frozen `QcliCaller(user_id,
user_name, token_id, audience, permissions)` (`token_id` / `audience` are `None` for a session or an adapter user;
`audience` is `cli` or `host` for a token; `permissions` are the live, scope-narrowed ones; `to_dict()` gives the
camelCase JSON). The returned `AuthContext` has it too (`ctx.caller`).

`users_plugin.require_host_token(permission=None)` accepts **only** `host` tokens: after authentication (same texts),
a session, an adapter user or a `cli` token gets `403 forbidden: a host token is required`, then the permission is
checked (`403 missing permission: <permission>`). Its refusals answer `{"error": "..."}` (the plugin installs the
handler when mounted); `require_auth` / `require_permission` keep FastAPI's `{"detail": "..."}` on host routes.

The guards carry `qcli_permission` and `qcli_host_token_only`, read by the
[public-api plugin](../public-api/README.md)'s OpenAPI document (`x-required-permission`, `x-host-token-only`).

These two guards are the only places that accept [host tokens](#host-tokens): API tokens a host application issues for its own routes. `users_plugin.require_cli_auth` is `require_auth` that refuses them (`403 forbidden: host tokens cannot use CLI routes`); use it for routes of a CLI plugin of your own that you include by hand. The admin plugin's API uses it.

## Config provider

The plugin brings the `users` config provider (`config_providers`, registered by `mount_plugin`): `sessions`
(`sessionTimeout`, `maxSessionLifetime`) and `security` (`maxLoginAttempts`, `lockout`, `minPasswordLength`) change
at runtime (read on every sign-in, request and password change); `access` (protectServer, signIn,
allowNonExpiringTokens, apiTokensWithExternalAuth, usersReadOnly, groupsReadOnly) is read-only. Changes are kept in
the server's default config store, or in the provider's own with `CliUsersBuilder().set_config_store(store)` (the
host's `CliServerConfigOptions(stores={"users": ...})` still wins). The server's live
allowed origins (`result.allowed_origins`, changed by the `cors` provider) are used for the CSRF check unless
`set_allowed_origins` set the plugin's own.

## Permissions

Groups carry `permissions` (`resource:action` strings, `*` wildcards such as `users:*` or `*`, case-insensitive). A user's effective permissions are the union of its groups' permissions. Built-in permissions: `users:read|create|update|delete`, `groups:read|create|update|delete`, `sessions:read|revoke`, `audit:read|clear`, `tokens:read|revoke`, plus the server permissions below.

### Permission catalog

The server keeps a catalog of the permissions a token can be given, each with a description and a group, for the dashboard's and the web CLI's token pickers. Core registers 14 entries (`commands:execute`, `shell:execute`, `http:request`, `files:read`, `files:write`, `data:query`, `jobs:read`, `jobs:manage`, `logs:read`, `admin:access`, `config:read`, `config:write`, `audit:read`, `audit:clear`) and this plugin adds 12 when mounted (`users:*`, `groups:*`, `sessions:read|revoke`, `tokens:read|revoke`), all with surface `cli`. The host adds its own routes' permissions with surface `host`:

```python
from qodalis_cli import CliPermission

def configure(builder):
    builder.add_permissions([
        CliPermission(name="rates:read", description="Official exchange rates", group="Rates"),
        {"name": "banks:read", "description": "Banks and their buy and sell rates", "group": "Rates"},
    ])  # surface="host" by default; plugins pass surface="cli"
```

The catalog is for choosing, not for validation: groups and `cli` tokens keep accepting any permission, unknown and wildcard ones included. Only [host tokens](#host-tokens) are checked against it. Registering a name that is already registered fails startup (`permission already registered: <name>`, case-insensitive), so a host that registers `users:read` itself makes mounting this plugin raise. A malformed entry raises `invalid permission entry: <name>`: the name must match `^[a-z0-9_.-]+:[a-z0-9_.-]+$`, the description must be one line of 1-200 characters and the group 1-64 characters.

`GET /api/v1/qcli/permissions` lists the entries: every `cli` entry in registration order (core, then plugins), then every `host` entry.

| Request | Result |
|---|---|
| no query, or `?all=false` | `200`, the entries the caller holds (wildcards in its permissions match; a scoped token sees only its scope) |
| `?all=true` with `users:read` | `200`, every entry |
| `?all=true` without `users:read` | `403 permission denied: users:read` |
| `?all=` anything else | `400 all must be true or false` |
| no credentials | `401 unauthorized` |
| a host token | `403 forbidden: host tokens cannot use CLI routes` |

Each entry is `{ "name": "files:read", "description": "List, read and download files", "group": "Files", "surface": "cli" }`.

A caller can never grant or exercise more than it holds: group permissions it grants, groups it adds users to, and users it acts on (update, password reset, delete, revoke sessions) must be covered by its own permissions (403).

### Server protection

When mounted on a CLI server, every route and socket requires a users session except `POST /api/v1/qcli/sessions`, version discovery (`/api/qcli/versions`, `/api/v1/qcli/version`, `/api/v1/qcli/capabilities`) and health endpoints:

| Surface | Permission |
|---|---|
| `GET /commands`, `/commands/stats` | authenticated |
| `POST /execute`, `/execute/stream` | `commands:execute` + the processor's `required_permissions` |
| `POST /api/qcli/mcp` (MCP endpoint) | `commands:execute`; each tool also needs its own permissions |
| fs `ls`, `cat`, `stat`, `download` | `files:read` |
| fs `upload`, `mkdir`, `rm` | `files:write` |
| data explorer | `data:query` |
| jobs read / manage | `jobs:read` / `jobs:manage` |
| events WebSocket | authenticated |
| logs WebSocket | `logs:read` |
| shell WebSocket (opt-in `enable_shell`) | `shell:execute` |
| admin dashboard (admin plugin with `set_users_plugin`) | `admin:access` |

WebSockets authenticate with a single-use ticket: `POST /sessions/ws-ticket` → `201 { ticket, expiresIn: 30 }`, then connect with `?ticket=<ticket>`. Missing/invalid tickets close with 4401, missing permissions with 4403 `forbidden`, a pending password change with 4403 `password change required`. Bearer tokens are not accepted in query strings, nor as a way to open a socket: a host token sent as the `Authorization` bearer closes it with 4403 `forbidden: host tokens cannot use CLI routes`.

**Host tokens are refused on every CLI route and socket**, with `403 forbidden: host tokens cannot use CLI routes` (4403 with that text on sockets), whether or not the server is protected. CLI routes are the core's (`/api/qcli`, `/api/v1/qcli`, `/ws/qcli`, `/ws/v1/qcli`, ...), the server's `base_path`, and the API and dashboard prefixes of every plugin mounted with `result.mount_plugin(...)` (`result.cli_route_prefixes`). A plugin router you include by hand counts only after `result.add_cli_route_prefix(prefix)`. With `set_protect_server(False)` the CLI routes stay unauthenticated, and anonymous and `cli`-token requests are untouched; only `qcli_pat_` bearers that are host tokens are refused (a look-up by hash: no `lastUsedAt` update, no adapter call).

Events and logs sockets stay bound to the session behind their ticket: on logout, revoke (kick), the user being disabled or deleted, or session expiry (detected on every session/user/group change and by the background sweep) they are closed with 4401 `session ended`. Revocations (kick, disable, delete, password reset) first send `session-kicked` to the user's event sockets. Sockets opened through an external auth adapter are re-checked through the adapter every `session_check_interval` (see [External auth adapter](#external-auth-adapter)).

Remote shell: when mounted, the plugin owns shell access (`shellAuth: "users"`). A shell is bound to the session that opened it and is closed with 4401 `session ended` after logout, expiry, revoke, user disable/delete or loss of `shell:execute` (re-checked immediately on every change and every 30 s by default, at most 60 s). Opens and closes are audited as `shell_opened` / `shell_closed` (`metadata: { mode, sessionId, durationMs, exitCode, reason }`; `reason` is `permission removed` when `shell:execute` was lost; never the command). See the main README, *Remote Shell Security*.

While `mustChangePassword` is true a session may only use `GET`/`DELETE /sessions/current` and `PUT /users/{self}/password`; everything else returns `403 password change required`.

## API Endpoints

All routes are mounted under `/api/v1/qcli`; collections accept paths with and without a trailing slash. Authenticated routes expect `Authorization: Bearer <token>`. Errors are always `{ "error": "<message>" }` (validation errors are `400`).

| Endpoint | Requirement | Description |
|----------|-------------|-------------|
| `POST /sessions` | public | Login `{ username, password }` (name or email) → `201 { token, session }` |
| `POST /sessions/ws-ticket` | authenticated | Single-use WebSocket ticket `{ ticket, expiresIn }` |
| `GET /sessions/current` | authenticated | Current session `{ id, user, permissions, loginTime, lastActivity, expiresAt, usersReadOnly, groupsReadOnly }` |
| `DELETE /sessions/current` | authenticated | Logout (204) |
| `GET /sessions` | `sessions:read` | Active sessions (never includes tokens) |
| `DELETE /sessions/{id}` | `sessions:revoke` or own session | Revoke (204) |
| `GET /users?query=&skip=&take=` | `users:read` | List users |
| `GET /users/{idOrName}` | `users:read` or self | Get a user |
| `GET /users/{idOrName}/permissions` | `users:read` or self | `{ userId, groups, permissions }` |
| `POST /users` | `users:create` | `{ name, email, groups?, password?, disabled?, homeDir?, data? }` → 201 |
| `PUT /users/{idOrName}` | `users:update` (self: `email`, `data` only) | Update a user |
| `DELETE /users/{idOrName}` | `users:delete` | Delete (204) |
| `PUT /users/{idOrName}/password` | self (with `currentPassword`) or `users:update` | `{ password, currentPassword?, temporary? }` → 204; an admin reset sets `mustChangePassword` unless `temporary: false` |
| `POST /users/{idOrName}/verify-password` | self or `users:update` | `{ password }` → `{ valid }` |
| `GET /groups`, `GET /groups/{name}` | authenticated | Groups |
| `GET /groups/{name}/members` | `groups:read` or member | Members |
| `POST /groups` | `groups:create` | `{ name, description?, permissions? }` → 201 |
| `PUT /groups/{name}` | `groups:update` | `{ description?, permissions? }` |
| `DELETE /groups/{name}` | `groups:delete` | Delete (204) |
| `POST` / `DELETE /groups/{name}/members/{idOrName}` | `groups:update` | Add / remove member (204) |
| `GET /audit?event=&username=&actor=&from=&to=&limit=&offset=` | `audit:read` | Audit entries, newest first (served by the [audit plugin](../audit/README.md)) |
| `DELETE /audit` | `audit:clear` | Clear the audit log (204; audit plugin) |
| `GET /tokens` | authenticated | Own API tokens (views) |
| `GET /tokens?all=true` | `tokens:read` | Every user's API tokens (`all` must be `true`/`false`, else 400) |
| `POST /tokens` | authenticated, **session only** | `{ name, expiresInDays?, permissions?, audience? }` → `201 { token, apiToken }` (`audience` absent or `"cli"`; `"host"` → `400 host tokens can only be created by the host application`; anything else → `400 audience must be cli or host`) |
| `GET /permissions` | authenticated | The [permission catalog](#permission-catalog) entries the caller holds; `?all=true` needs `users:read` |
| `DELETE /tokens/{id}` | owner or `tokens:revoke` | Revoke (204); unknown or not yours → 404 |
| `POST /link` | public, 10 per minute per address | `{ client, permissions? }` → `201 { linkId, userCode, verificationUrl, expiresIn, interval }` (see [Linking a terminal](#linking-a-terminal)) |
| `GET /link/{linkId}` | public | `{ status: 'pending' \| 'denied' }`, or `{ status: 'approved', token, userName, expiresAt }` once; 404 `{ status: 'expired' }` |
| `GET /link/code/{userCode}` | authenticated | The request the approval page shows |
| `POST /link/code/{userCode}/approve` \| `deny` | **session only** (approve) | Approve creates the approver's API token for the terminal; deny → 204 |

The admin dashboard plugin keeps its own login at `/auth/login`; both plugins can be mounted at the same prefix.

### Rules

- Duplicate user name/email or group name → 409; unknown group references → `400 unknown group: x`.
- You cannot delete yourself; the last enabled member of `admin` cannot be deleted, disabled or removed from `admin`; built-in groups cannot be deleted; the `admin` group's permissions cannot be changed (all 409).
- Deleting a group removes it from every user. Deleting a user removes its credentials and revokes its sessions. Disabling a user revokes its sessions. A password change by the user revokes their other sessions; by someone else, all of the target's sessions.
- Sessions reference users by id; the live user (groups, disabled) is resolved on every request.
- Passwords are stored as `pbkdf2$100000$<saltB64>$<hashB64>` (PBKDF2-HMAC-SHA256, computed off the event loop, at most 4 at once). After 5 consecutive failed attempts (logins, verify-password, self password change) an account is locked for 5 minutes (`429`); unknown names are locked the same way. Lockout is reserved before verification, so concurrent requests cannot exceed it.
- Session stores keep only `SHA-256(token)`; tokens, tickets and passwords never appear in logs or audit entries.
- Names and group names: 1–64 chars `^[A-Za-z0-9][A-Za-z0-9._@-]*$`; emails ≤ 254 chars; permissions ≤ 128 chars (≤ 100 per group); descriptions ≤ 256; `data` ≤ 16 KB; request bodies ≤ 1 MB; control characters are rejected. Names and emails share one namespace.
- In adapter (cookie) mode, state-changing requests without a bearer token need an `Origin` in the allowed origins (CSRF).

## API tokens

Long-lived, revocable bearer tokens for MCP clients, CI and scripts (sessions expire and need a password sign-in). A token is `qcli_pat_` + 32 random bytes (base64url, no padding); it is shown **once** at creation and only its SHA-256 hash is stored (`IApiTokenStore`, in-memory by default — replace it with `set_api_token_store`).

```bash
# create (needs a session: an API token gets 403, an external-adapter identity 501 unless set_allow_api_tokens())
curl -X POST http://localhost:8048/api/v1/qcli/tokens \
  -H "Authorization: Bearer <session token>" -H "Content-Type: application/json" \
  -d '{"name": "claude", "expiresInDays": 30, "permissions": ["commands:execute", "files:read"]}'
# → 201 { "token": "qcli_pat_…", "apiToken": { "id", "name", "userId", "userName", "createdAt", "expiresAt", "lastUsedAt", "audience", "permissions" } }
```

- `name`: 1-64 characters of `[A-Za-z0-9._ -]`, unique per user (case-insensitive; duplicate → `409`). At most 20 non-expired tokens per user (`400`; expired tokens stay listed until revoked).
- `expiresInDays`: integer 1-365, default 90; `null` (never expires) only with `set_allow_non_expiring_tokens(True)`, else `400`.
- `permissions` (optional scope): every entry must be a valid permission you hold, else `403 forbidden: cannot grant <perm>` (body field errors are `400` first). A scoped token gets the user's **live** permissions intersected with the scope; `[]` is an empty scope; an unscoped token (`permissions` omitted or `null`; omitted in the view) gets all of them.
- Views never contain the token or its hash; `lastUsedAt` is `null` until first use and updated at most once a minute.
- `audience` is always in the view: `cli` (every token `POST /tokens` creates) or `host` (see [Host tokens](#host-tokens)).

`Authorization: Bearer qcli_pat_…` is accepted everywhere a session token is (HTTP routes, `POST /sessions/ws-ticket`, the MCP endpoint). An unknown, revoked or expired token, or one whose user is disabled or deleted, gets `401`; `mustChangePassword` applies as for sessions. With a token, `GET`/`DELETE /sessions/current` answer `404 not a session` and password changes `403 forbidden: API tokens cannot change passwords`. Sockets opened with a token's ticket are closed with 4401 `session ended` when the token is revoked or expires or the user is disabled.

With an external auth adapter (`set_auth_adapter`) tokens are off: `POST /tokens` and link approval answer `501` and `qcli_pat_` bearer tokens go to the adapter. `set_allow_api_tokens()` turns them on next to the host's sign-in: `qcli_pat_` bearer tokens are checked against the token store before the adapter (which never sees them), and users signed in by the host create tokens and approve terminal links. The token's user is read from the user store by id, so the store must find the adapter's users and report `disabled`; keep the tokens in a persistent `IApiTokenStore` (the default one forgets them on restart).

Deleting a user deletes their tokens; disabling a user makes their tokens fail (they work again after re-enabling). Creation and revocation are audited as `token_created` / `token_revoked` (details: token name and id).

### Host tokens

A host application can give its users API tokens for its **own** routes, for example an exchange-rates app with `rates:read`. These tokens have the audience `host`. The host creates them through `users_plugin.api_tokens` (`ApiTokenManager`), never through `POST /tokens`. They are accepted only by `users_plugin.require_auth` and `users_plugin.require_permission(...)`, and refused on every CLI route and socket (see [Server protection](#server-protection)).

```python
from qodalis_cli_users import ApiTokenCreateOptions, UsersApiError

created = await users_plugin.api_tokens.create(user.id, ApiTokenCreateOptions(
    name="rates", audience="host", permissions=["rates:read"], expires_in_days=30, actor="rates-app",
))
created.token        # qcli_pat_… (shown once)
created.to_dict()    # {"token": ..., "apiToken": {..., "audience": "host", "permissions": ["rates:read"]}}

await users_plugin.api_tokens.list(user.id)                        # views, oldest first, both audiences
await users_plugin.api_tokens.revoke(user.id, token_id, actor="rates-app")   # False if missing or not the user's
await users_plugin.api_tokens.grantable_permissions(user.id, "host")         # catalog entries the user holds
```

`ApiTokenCreateOptions(name, expires_in_days=None, never_expires=False, permissions=None, audience="cli", actor=None)`. `create` has the validation, limits, audit entries (`token_created`, with `actor` or the owner's name) and events of `POST /tokens`. Errors are `UsersApiError` with the status and text the route would answer, checked in this order:

1. external auth without `set_allow_api_tokens()` → `501 Authentication is managed by the host application`
2. unknown user (looked up by id) → `404 user not found`; disabled → `403 account disabled`
3. audience other than `cli`/`host` → `400 audience must be cli or host`
4. name and expiry as `POST /tokens`; `never_expires` needs `set_allow_non_expiring_tokens()` (`400 non-expiring tokens are not allowed`); with `expires_in_days` too → `400 expiresInDays and neverExpires cannot both be set`
5. permission syntax as `POST /tokens`
6. host tokens only: no permissions → `400 host tokens need permissions`; an entry that is not a `host` entry of the catalog (case-insensitive; wildcards never match) → `400 not a host permission: <p>`. Entries are stored in the catalog's spelling (`RATES:READ` → `rates:read`)
7. every entry held by the user's live permissions (wildcards in groups count: `rates:*` grants `rates:read`) → else `403 forbidden: cannot grant <p>`
8. name taken → `409 token '<name>' already exists`; more than 20 tokens (both audiences together) → `400 a user may have at most 20 tokens`

A `None` or empty `user_id` raises `ValueError` in every method, before any store is read. `grantable_permissions(user_id, "cli")` returns every catalog entry the user holds, `"host"` only the host ones; an unknown user is `404 user not found`.

The catalog is checked only when a token is created; on every request the guard checks the user's live permissions, so a host token keeps working when its entry is no longer registered. Revocation (`DELETE /tokens/{id}`, deleting or disabling the user) is the same for both audiences, and the 20-token limit and name uniqueness count both. A stored audience that is missing, `None` or empty reads as `cli`; **any other value but `cli` is treated as host** (fail closed). A host route without a guard can tell a host token from the context the protection middleware stored: `qodalis_cli.security.get_auth_context(request).is_host_token`.

Use a token with the server's MCP endpoint — see the main README, [*Using the MCP endpoint from an MCP client*](../../README.md#using-the-mcp-endpoint-from-an-mcp-client):

```bash
claude mcp add --transport http qcli http://localhost:8048/api/qcli/mcp \
  --header "Authorization: Bearer <token>"
```

### Token usage

`users_plugin.set_token_usage_provider(provider)` adds `usage` to every token view of `GET /tokens` (own and
`?all=true`) and `api_tokens.list`, last, after `permissions`: `await provider(token_ids)` returns
`{token_id: {"today": 12, "last30Days": 340, "days": [{"date": "2026-10-21", "requests": 0}, ...]}}` (30 days, oldest
first). The [public-api plugin](../public-api/README.md) sets one. Without a provider the views are as before; a
failing provider is logged and the views are returned without `usage`. Creating a token never returns it.

### Guard-only mode

`CliUsersBuilder().set_guard_only()` builds a users plugin for a second service that only validates tokens (a public
API next to the service running the CLI): no users routes (sign-in, users, groups, sessions, tokens, permissions, link,
audit), no seeding, no session or link sweeps and no server protection. Its guards authenticate `qcli_pat_` tokens
against the stores you share with the other service (`set_user_store`, `set_group_store`, `set_api_token_store`).

It needs a server without CLI routes: mounting it on a server with `cli_routes=True` raises
`ValueError("guard-only needs cli_routes=False")`, and its guards answer 500 (logging that text) until it is mounted on
one.

```python
result = create_cli_server(CliServerOptions(cli_routes=False, configure=add_permissions))
users = CliUsersBuilder().set_user_store(users_db).set_group_store(groups_db).set_api_token_store(tokens_db).set_guard_only().build()
result.mount_plugin(users)
```

Tokens must be created and revoked from one service only: the name's uniqueness and the 20-token limit are checked in
the process that creates the token.

## Dashboard pages

The plugin serves three pages of the admin dashboard, embedded in this package (copied at build by
`scripts/copy_dashboard.py` from the sibling `cli-server-dashboard` repo, else the npm package) and served outside the
API when the plugin is mounted (not in guard-only mode; also when the host application signs users in):

- **Users** (users, groups, sessions; `users:read`, with the palette's user search): the module
  `@qodalis/cli-dashboard-module-users` in `qodalis_cli_users/dashboard_users`, served at `/qcli/modules/users`.
- **Account** (the signed-in user's profile and password change; every user, in the dashboard's account menu, group
  `account`): the same build, served again at `/qcli/modules/account`; the module renders the page for this id and
  hides the password change when the host application signs users in.
- **API tokens** (each user sees their own tokens): `@qodalis/cli-dashboard-module-tokens` in
  `qodalis_cli_users/dashboard`, served at `/qcli/modules/tokens`.

`CliUsersBuilder().set_users_dashboard_dir(path)` (Users and Account) and `set_dashboard_dir(path)` (API tokens) serve
another build; `False` leaves the pages out.

## Linking a terminal

`server add` in the web CLI links a terminal to the server through the browser, like the OAuth device flow:

1. The terminal sends `POST /link` with its name (`{ "client": "Qodalis CLI on Pixel 7" }`, optionally `permissions` for a scoped token) and gets a `linkId` (secret), a code such as `ABCD-2345` and the approval page (`/qcli/admin/link?code=ABCD-2345`, the admin dashboard).
2. The user opens the page, signs in, compares the code and approves. Approving creates an API token for that user named `link <client>`, with the requested permissions (never more than the user has), listed and revocable like any token.
3. The terminal polls `GET /link/{linkId}` every `interval` seconds and receives the token once.

Requests expire after 10 minutes, are single-use and live in memory. Approvals and denials are audited (`link_approved`, `link_denied`). Hosts with their own page set `set_link_approval_url`.

## Server events

Mounted on a CLI server, the plugin publishes on the server's event bus (`result.event_bus`; see the server README,
*Server Events*). Each event goes to the event sockets whose user holds its permission:

| Event | Fields | Audience |
|---|---|---|
| `user:created`, `user:updated`, `user:deleted` | `userId`, `username`, `actor` | `users:read` |
| `group:created`, `group:updated`, `group:deleted` | `group`, `actor` | `groups:read` |
| `token:created`, `token:revoked` | `tokenId`, `name`, `userId`, `actor` | `tokens:read`, or the token's owner |
| `session:opened`, `session:closed` | `userId`, `username`, `sessionId`, `actor` | `sessions:read` |

`user:updated` covers profile, enabled/disabled, password and group membership changes (deleting a group updates its
members). `session:closed` covers sign-out, revoke (kick, disable, delete, password change) and expiry. The plugin's audit
entries are published as `audit:recorded` (`audit:read`) by the [audit plugin](../audit/README.md).

## Session events

Every revoked session is broadcast as:

```json
{ "type": "session-kicked", "data": { "sessionId": "...", "userId": "...", "reason": "revoked" } }
```

Reasons: `revoked`, `user_deleted`, `user_disabled`, `password_changed`. A `@qodalis/cli-users` client in server mode logs itself out when its own session is kicked.

## Audit log

The audit log is the [audit plugin](../audit/README.md)'s (`qodalis-cli-server-plugin-audit`, a dependency of this
plugin): mounting the users plugin mounts it, so a host that only mounts the users plugin keeps its audit log at
`/api/v1/qcli/audit`. When the host mounts an audit plugin of its own (before or after), the users plugin records in it
instead. `set_audit_store(store)` does the same as `CliAuditBuilder().set_store(store)`; a store set on either side is
kept. `users_plugin.audit_plugin` is the audit plugin and `users_plugin.audit_store` its store. The contract
(`AuditEntry`, `AuditMetadata`, `AuditQueryOptions`, `IAuditStore`) is in `qodalis_cli_server_abstractions.audit`;
`qodalis_cli_users` still re-exports `AuditEntry`, `AuditQueryOptions`, `IAuditStore` and `InMemoryAuditStore`.
Server protection checks `audit:read` / `audit:clear` on the audit routes; without it (`set_protect_server(False)`) the
users plugin guards them itself.

Every entry has the `event`, the user it is about (`username`), who did it (`actor`), `details` and `metadata`. Two
optional fields make it fit an application's own changes:

- `target`: what the event is about when it is not a user, e.g. `group:admins` (the plugin's group events), a role or a job.
- `properties`: the application's own values, e.g. the old and new value of a setting.

An application records its own changes in the same log through `IAuditStore.log`, so the dashboard's Audit page and
`GET /audit` show them all. Filter by `event`, `username` (the subject) and `actor`, and page with `limit` and
`offset` (without a `limit` the newest 100, at most 1000 per request). The default store keeps the latest 1000 entries in memory; bound a store of your own with
`IAuditStore.prune(before)` (Unix time in ms; the default keeps everything).

## Custom storage

Implement any of `IUserStore`, `ISessionStore`, `ICredentialStore`, `IAuditStore`, `IGroupStore` or `IApiTokenStore` (see `qodalis_cli_users.stores.interfaces`; `IAuditStore` is `qodalis_cli_server_abstractions.audit.IAuditStore`) and pass the instance to the builder:

```python
users_plugin = CliUsersBuilder().set_user_store(PostgresUserStore(pool)).build()
```

An `IApiTokenStore` must persist `ApiToken.audience`: a store that drops it turns host tokens into CLI tokens (rows without it read as `cli`).

## External auth adapter

The middleware order and a complete setup with the admin dashboard are in [Use with your app's sign-in](../../README.md#use-with-your-apps-sign-in).

If the host application already authenticates requests, call `set_auth_adapter(adapter)`. The adapter (sync or async) receives the request and returns an `ExternalAuthResult` (user + admin flag + optional permissions) or `None`. Login, logout, password change and `verify-password` then answer `501`; no `root` user is seeded (the built-in groups still are), and adapter sessions are not stored or listed. Permissions come from the groups the adapter returns (`is_admin` adds `admin`) plus the result's `permissions`; group names missing from the group store grant nothing (and break nothing).

The adapter may return the result directly or an awaitable of it, so it can load the user, their roles or their disabled state from a database. A plain function, an `async def` function and an object with a sync or async `__call__` are all accepted; the plugin awaits the result for every request, ticket issuance and socket re-check:

```python
async def host_auth(request):
    current = await user_access.current(request)   # e.g. a database lookup
    if current is None:
        return None
    return ExternalAuthResult(user=to_cli_user(current), is_admin=current.is_admin)

users_plugin = CliUsersBuilder().set_auth_adapter(host_auth).build()
```

Hosts with their own roles can grant permissions directly instead of keeping a group per permission:

```python
return ExternalAuthResult(
    user=to_cli_user(account),                       # groups may be empty
    permissions=["commands:execute", "logs:read"],   # added to the groups' permissions
)
```

**Shells opened by adapter identities** have no stored session to re-check, so at every shell re-check (right after the shell opens, on every change event and every `session_check_interval`) the adapter is **run again on a snapshot of the request it accepted**: the `POST /sessions/ws-ticket` request the shell's ticket came from (request line, headers and cookies, client address and app; no body and no state set by middleware). The adapter must therefore be able to authenticate that request again on its own. `None`, an exception, a different user or a disabled user closes the shell with 4401 `session ended` (audit reason `session ended`); a user without `shell:execute` closes it too (audit reason `permission removed`).

**Events and logs sockets opened by adapter identities** are re-checked the same way: every `session_check_interval` (the server's `CliShellOptions.session_check_interval`, default 30 s, capped at 60 s; it applies whether or not the shell is enabled) the adapter runs again on the snapshot of the ticket request. `None`, a different user, a disabled user, an exception, or a user who no longer holds the socket's permission (`logs:read` for the logs socket; the events socket only needs authentication) closes the socket with 4401 `session ended`. The checks run from `startup()` (call it from the app's lifespan, see [Quick Start](#quick-start)), one at a time: a slow adapter delays the next check rather than stacking them. `users_plugin.recheck_external_sockets()` runs one on demand.

A user the adapter returns with `disabled=True` is refused (401 `account disabled`) on requests, ticket issuance and re-checks.

## Read-only stores

When the host application owns the users or groups (a custom `IUserStore`/`IGroupStore` over its own accounts and roles), mark them read-only instead of raising from the store's write methods:

```python
users_plugin = (
    CliUsersBuilder()
    .set_auth_adapter(host_auth)
    .set_user_store(HostUserStore())   # only the read methods need real implementations
    .set_read_only_users()
    .set_read_only_groups()
    .build()
)
```

- **`set_read_only_users()`**: `POST /users`, `PUT /users/{idOrName}` (self updates too), `DELETE /users/{idOrName}`, `PUT /users/{idOrName}/password` and `POST`/`DELETE /groups/{name}/members/{idOrName}` answer `501 { "error": "Users are managed by the host application" }` without calling any store (before authentication). No `root` user is seeded, and deleting a group leaves the users' memberships alone.
- **`set_read_only_groups()`**: `POST /groups`, `PUT /groups/{name}` and `DELETE /groups/{name}` answer `501 { "error": "Groups are managed by the host application" }` without calling the store, and the built-in `admin` and `users` groups are not seeded (the host's store provides the groups it needs).
- Reads keep working. `GET /sessions/current` and the login response (`session`) carry `usersReadOnly` and `groupsReadOnly` (always present, `false` by default) so clients can hide `adduser`, `groupadd` and the like.

## Client

Point the browser plugin at this server:

```typescript
import { usersModule } from '@qodalis/cli-users';

engine.registerModule(usersModule.configure({ server: 'python' }));
// options.servers must contain { name: 'python', url: 'http://localhost:8048' }
```

## Terminal commands

The plugin has no server-side command: the web CLI plugin [`@qodalis/cli-users`](https://www.npmjs.com/package/@qodalis/cli-users)
drives its API in server mode. Its settings (session timeouts, lockout, password length) are the core `config`
command (`config get users`).

| Command | Permission | Does |
|---|---|---|
| `login [user]`, `logout` (`exit`), `su <user>` | | Sign in, sign out, switch user |
| `whoami` (`me`), `id [user]`, `groups [user]`, `perms [user]` | signed in (`users:read` for others) | Identity, groups, effective permissions |
| `passwd [user]` | signed in (`users:update` for others) | Changes your password, or resets another user's |
| `adduser [name]` (`useradd`) | `users:create` | Creates a user |
| `usermod <user>` | `users:update` | Changes a user (groups, name, email, enabled) |
| `userdel <user>` (`deluser`) | `users:delete` | Deletes a user (asks first) |
| `listusers` (`users`) | `users:read` | Lists users (`--query`, `--skip`, `--take`) |
| `groupadd <name>`, `groupmod <group>`, `groupdel <name>` | `groups:create`, `groups:update`, `groups:delete` | Groups and their permissions |
| `w` (`who`), `sessions` | signed in, `sessions:read` | Who is signed in, active sessions |
| `session-kick <id>` | signed in (`sessions:revoke` for others) | Ends a session |
| `token create <name>`, `token list` (`ls`), `token revoke <id>` (`rm`), `token permissions` | signed in (`tokens:revoke` for others' tokens) | API tokens |
| `link approve <code> [--yes]`, `link deny <code>` | signed in | Approves or denies another terminal's link request (as the dashboard does) |
| `last [user]`, `audit`, `audit clear` | `audit:read`, `audit:clear` | Sign-in history and the audit log (the [audit plugin](../audit/README.md)) |

## Install from the dashboard

Installable at runtime from the server marketplace (the dashboard's Plugins → Marketplace, or
`admin plugins install users`; it loads at the next start), or in code through the same entry, its options the
defaults of the settings below (a saved setting overrides them):

```python
from qodalis_cli_users import plugin as users

builder.add_plugin(users, {...})
```

Entry point `users = "qodalis_cli_users.plugin:create_plugin"` (group `qodalis_cli.plugins`), load order 10. Its settings
(provider `users-plugin`, section `settings`; `config set users-plugin.settings.<key> <value>`, then a restart):

| Setting | Type | Default | |
|---|---|---|---|
| `defaultAdminPassword` | secret |  | The seeded root user's password; empty: a random one, logged once |
| `protectServer` | boolean | `true` | Every route and socket needs a sign-in |
| `allowNonExpiringTokens` | boolean | `false` | API tokens may be created without an expiry date |
| `linkApprovalUrl` | string |  | Where users approve a terminal's link request; empty: the dashboard's |

## License

MIT
