@x-tech-laboratories/x-app 0.121.0 → 0.122.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,15 +9,15 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
9
9
 
10
10
  | Import | What it holds |
11
11
  | ---------------------------------------- | ----------------------------------------------------------------------------- |
12
- | `app/define` | The base app: `define_app` puts an X-app's name, ports, files, its own settings and its `define_feature` features (tables, migrations, calls, `api_spec`, settings, histories) together into one store every device keeps (`open_store` calling each feature's `on_open`, `needs_upgrade`, `bind_methods(database, on_change, caller)` running each call as its `caller`, calling each feature's `after_write`, recording versions and announcing writes, `is_read_only`), `page_only` (the specs' `page_only` calls and the writes of `user_only` settings, refused with `page_only_refusal`), its sync engine, its backups' names and schedule, and its bridges named after the app; `AppMethodsOf<typeof app>` types the app's calls. `history_days` sets how far an app's history reaches back until the user chooses (365 unless set); what opening changed is recorded as this device's version, and old versions are pruned on opening and after a write once a day. `settings_knows(key)` lets an import take keys without a spec of their own, such as `diet.target_protein`; `upgrade_layout: { needed, run }` brings a database an older version laid out its own way, such as a versions table keyed another way, in line before any migration, backed up first; `adopt_backup_schedule(database, saved)` moves a schedule an older version kept elsewhere into the setting once. `tools`, a feature of the app's own, is what MCP offers in place of the page's calls, such as tools that take names rather than ids, each run as the `program` caller (`app.mcp`). Sync's and history's triggers come off while migrations run, so a step may drop a column they name. `take_data_change(database)` names the synced tables written since the last call for that connection (null on its first call and after a restore); the server and daemon send it with each change, so a page's `on_change(listener)` hears `{ tables }` and fetches only what it shows from them, or everything on null. `synced_theme` keeps the light, dark or system theme as a synced setting, `theme`, so every device shows the one picked last. |
13
- | `app/server`, `app/daemon` | `run_server(app, { web_folder })`: the web server from `<PREFIX>_CONFIG` with accounts in `accounts.db` (moved there once from the data's own file, tokens starting with the app's `token_prefix`), the calls, OpenAPI, MCP, the server's backups and its sync peer, a token or MCP client refused the app's `page_only` calls and the `user_only_backup_calls` (restore, remove, schedule) and its calls run as the `program` caller; `run_daemon(app)`: the desktop daemon from `<PREFIX>_DB` with sync, letting devices connect, backups, certificates and the desktop settings; Both take the app's `services` (see `app/services`), `run_daemon(app, env, { services })`. A `backup-schedule.json` an older version kept beside the database moves into this device's setting on opening. Both tell every page when another program, such as an older build, writes the database file (`watch_outside_changes`, on SQLite's `data_version`). `build_server`, `start_daemon`, `open_app_database` (with `on_restore` hooks) and `register_app_calls` for tests and apps that add their own. |
14
- | `app/services` | An app's own work beside its calls, run by both hosts: `StartServices` gets a `HostContext` (`kind`, `database()`, `profile`, `device_name`, the server's raw `config`, `plugins_folder`, `declared_file` from `<PREFIX>_DECLARED_FILE` or `/etc/<id>/declared.json`, `announce`, `emit(event, data)` for the page's `on_event`, `side_database(name)` for a never-backed-up file such as `<base>-index.db`, `back_up`) and returns `HostServices` (`before_restore`, `after_restore`, `stop`), stopped before sync and the database. |
15
- | `app/host_tables`, `app/remote_access`, `remote_access_protocol` | What an app's hosts answer themselves beside its data calls, such as files a computer keeps or programs it runs: `define_app({ host_tables })` names each table with its `api`, the `hosts` that answer it (`"server"`, `"desktop"`) and who reaches it from the network or MCP (`network`: `"admin"` unless set, `"any"`, or `"none"` for this computer's own window alone); the services hand in each table's `methods`, and `elsewhere`, the same calls refusing what only this computer's user may do, for the network and MCP. Every host serves them under `/api/<table>/<call>` (503 until the services started), `/api/host/get_host_abilities` says what the viewer reaches (`admin`, `tables`), MCP and OpenAPI offer them beside the data calls, and the desktop bridges them, a `"none"` table staying on this computer's daemon. `remote_access: true` is the daemon's "Let other devices connect" for its own calls (`create_remote_access`: `remote.json` and the admins in `remote-admins`, mode 0600, https from a certificate and key, listening only while on, changed only over the socket), on `build_server` with the accounts in `accounts.db`, moved there once from the data's own file; `read_remote_access`, `remote_access_problem`. |
12
+ | `app/define` | The base app: `define_app` puts an X-app's name, ports, files, its own settings and its `define_feature` features (tables, migrations, calls, `api_spec`, settings, histories) together into one store every device keeps (`open_store` calling each feature's `on_open`, `needs_upgrade`, `bind_methods(database, on_change, caller)` running each call as its `caller`, calling each feature's `after_write`, recording versions and announcing writes, `is_read_only`), `page_only` (the specs' `page_only` calls and the writes of `user_only` settings, refused with `page_only_refusal`), its sync engine, its backups' names and schedule, and its bridges named after the app; `AppMethodsOf<typeof app>` types the app's calls. `history_days` sets how far an app's history reaches back until the user chooses (365 unless set); what opening changed is recorded as this device's version, and old versions are pruned on opening and after a write once a day. `settings_knows(key)` lets an import take keys without a spec of their own, such as `diet.target_protein`; `upgrade_layout: { needed, run }` brings a database an older version laid out its own way, such as a versions table keyed another way, in line before any migration, backed up first; `adopt_backup_schedule(database, saved)` moves a schedule an older version kept elsewhere into the setting once. `tools`, a feature of the app's own, is what MCP offers in place of the page's calls, such as tools that take names rather than ids, each run as the `program` caller (`app.mcp`). Sync's and history's triggers come off while migrations run, so a step may drop a column they name. `take_data_change(database)` names the synced tables written since the last call for that connection (null on its first call and after a restore); the server and daemon send it with each change, so a page's `on_change(listener)` hears `{ tables }` and fetches only what it shows from them, or everything on null. `synced_theme` keeps the light, dark or system theme as a synced setting, `theme`, so every device shows the one picked last. `roles` gives the accounts' roles from least to most able (`["user", "admin"]` unless set); `sync: false` is an app whose server is the only copy of its data, such as one watching other machines, so the server keeps no sync peer and Settings shows no Sync section; `declared_tokens: { key, scopes }` reads tokens from that key of the server's config through `server/declared_tokens`. |
13
+ | `app/server`, `app/daemon` | `run_server(app, { web_folder })`: the web server from `<PREFIX>_CONFIG` with accounts in `accounts.db` (moved there once from the data's own file, tokens starting with the app's `token_prefix`), the calls, OpenAPI, MCP, the server's backups and its sync peer, a token or MCP client refused the app's `page_only` calls and the `user_only_backup_calls` (restore, remove, schedule) and its calls run as the `program` caller; `run_daemon(app)`: the desktop daemon from `<PREFIX>_DB` with sync, letting devices connect, backups, certificates and the desktop settings; Both take the app's `services` (see `app/services`), `run_daemon(app, env, { services })`. A `backup-schedule.json` an older version kept beside the database moves into this device's setting on opening. Both tell every page when another program, such as an older build, writes the database file (`watch_outside_changes`, on SQLite's `data_version`). `build_server`, `start_daemon`, `open_app_database` (with `on_restore` hooks) and `register_app_calls` for tests and apps that add their own. The server also signs in through OpenID Connect from `<PREFIX>_OIDC_*` (`oidc_from_environment`), bounds sessions by the config's `session_seconds` and `remembered_seconds`, and serves the config's `theme` (`{ scheme, colors }`, read by `read_server_theme`) at the open `GET /api/theme`, which the browser's page applies before it draws: a pinned scheme leaves the Shell's theme row out, and each colour sets a Halon token over both schemes. With the config's `plugins_folder` it serves each plugin's page side under `/api/plugins` (`server/plugin_files`). The app's `routes` may name `open_prefixes`, such as `/api/push/`, `guarded_paths` outside the API, such as `/metrics`, and `needed(method, path)`, what a route of its own needs of the one asking, such as an operator's role. |
14
+ | `app/services` | An app's own work beside its calls, run by both hosts: `StartServices` gets a `HostContext` (`kind`, `database()`, `profile`, `device_name`, the server's raw `config`, `plugins_folder`, `declared_file` from `<PREFIX>_DECLARED_FILE` or `/etc/<id>/declared.json`, `announce`, `emit(event, data)` for the page's `on_event`, `side_database(name)` for a never-backed-up file such as `<base>-index.db`, `back_up`) and returns `HostServices` (`before_restore`, `after_restore`, `stop`), stopped before sync and the database. On the server it also gets `config_file`, the path of the config it read, for an app that reads its own keys again when the file changes (with `config_watch`), `declared_tokens()` and `reread_declared_tokens(config)` after such a reload. `before_restore` and `after_restore` may return a promise, which the restore waits for, such as a writer flushing first. |
15
+ | `app/host_tables`, `app/remote_access`, `remote_access_protocol` | What an app's hosts answer themselves beside its data calls, such as files a computer keeps or programs it runs: `define_app({ host_tables })` names each table with its `api`, the `hosts` that answer it (`"server"`, `"desktop"`) and who reaches it from the network or MCP (`network`: `"admin"` unless set, `"any"`, or `"none"` for this computer's own window alone); the services hand in each table's `methods`, and `elsewhere`, the same calls refusing what only this computer's user may do, for the network and MCP. Every host serves them under `/api/<table>/<call>` (503 until the services started), `/api/host/get_host_abilities` says what the viewer reaches (`admin`, `tables`), MCP and OpenAPI offer them beside the data calls, and the desktop bridges them, a `"none"` table staying on this computer's daemon. `remote_access: true` is the daemon's "Let other devices connect" for its own calls (`create_remote_access`: `remote.json` and the admins in `remote-admins`, mode 0600, https from a certificate and key, listening only while on, changed only over the socket), on `build_server` with the accounts in `accounts.db`, moved there once from the data's own file; `read_remote_access`, `remote_access_problem`. A table's `needs(method)` names the role a call needs from the network or MCP beyond the table's reach, such as an operator's for the calls that change something, refused with 403; every call runs with its request's viewer, which `current_viewer()` of `server/viewer_scope` reads, so the services can name who asked. |
16
16
  | `app/links` | `app_link(scheme, route)` and `route_of_link(scheme, link)`: an app's links such as `x-notes://note/<id>` and the page route they open. |
17
17
  | `app/desktop`, `app/preload` | `run_desktop(app, electron, { main_dir })`: Electron's main process as a portal onto this computer's daemon or a server, with the window (`default_size` fixed or from the screen's free area, the daemon told while one is in front for its services' `window_in_front`), the tray (`show_tray_icon`, the app's own `tray` rows above Show, Quit and Quit completely, a write a row makes reaching every window at once, closing the last window leaving the app in it, `--hidden` starting there), the app's `link_scheme` links opening the window on their page (`route_of_link` to map them its own way; the page follows the `open` event), the login entry, a second launch and `--daemon`; the app's own `desktop_settings` switches sit in Settings → Desktop app beside the base's; `run_preload(app, electron)` puts every bridge on the page. The page's `desktop` calls also give the computer's idle seconds (`get_idle_seconds`, from Electron's `powerMonitor`) `set_window_theme`, which the page calls so the window's own parts follow its theme, `get_data_paths` and `show_data_path`, which show this computer's database and backups folder in the file manager from Settings, and `save_text_file`, which asks where through the Save dialog, starting in Downloads (`save_dialog_options`); opening the window replaces a daemon another build left running, and a Flatpak keeps its profile in `~/.config/<id>` as the other builds do. Electron is handed in, so neither imports it. An app with `local_mcp: { default_port }` serves its calls as MCP on 127.0.0.1 from the desktop daemon (`electron/mcp`, page-only calls left out, calls run as `program`), turned on under Settings → MCP server. |
18
18
  | `app/window_size` | `fit_window_size(work_area)`: a first window of most of the screen's free area, between 960×640 and 1800×1200 and never past the screen; hand it to `run_desktop` as `default_size`. |
19
19
  | `app/seed` | A development database of an app's example data, made by its own calls: `seed_app_database(app, { file, reset, seed })` opens a fresh file with the app's schema and hands `seed` the app's calls, refusing a file already there without `reset` (which takes its `-wal` and `-shm` too) and the desktop app's real database in `~/.config/<id>` (`real_database_path`) whatever path leads there; `run_seed(app, seed)` is the seed script's whole command line, `<file> [--reset]`, read by `seed_target`. |
20
- | `app/web/app_page`, `app/web/page` | `render_app({ app, pages, general_settings })`: the page on the web, the desktop or Android in the `Shell`, with sign-in in a browser, the theme kept in this browser or, for an app with `synced_theme`, in its synced setting, the sidebar's dragged width remembered on this device (`default_sidebar_width`) unless the chrome's `sidebar_width` holds it, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync and Backups) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. The page API's `on_event(name, listener)` hears the named events the app's services `emit`, on the web and the desktop. A page may have an `icon` (the sidebar then shows icon rows), a `use_badge` hook ("Inbox · 3"), `in_sidebar: false` with `active_as` for a page reached only by its route; `default_page` names the page an empty route opens, and the `use_chrome(parts)` hook gives the `sidebar` content under the rows, header `tools`, a `side_pane`, a `contained` window where only the page scrolls with a `main_class` for its box, `around`, which wraps the page, such as in the app's own context or with dialogs over any page, and `bare` for the page alone with no sidebar or header, such as a strip embedded in another program. `settings_categories(props)` adds the app's own Settings categories after General, for settings no one page owns. A page's `children` fold open under its row in the sidebar (`#/diet/foods`, the title "Foods · Diet", the first shown when none is named, a single child leaving the page one row), and `phone_services` loads the app's own work on the phone only there, such as reminders handed to Android, told of every write, every change from another device and each return to the app; an older version's backup schedule in the page's storage moves into the setting. |
20
+ | `app/web/app_page`, `app/web/page` | `render_app({ app, pages, general_settings })`: the page on the web, the desktop or Android in the `Shell`, with sign-in in a browser, the theme kept in this browser or, for an app with `synced_theme`, in its synced setting, the sidebar's dragged width remembered on this device (`default_sidebar_width`) unless the chrome's `sidebar_width` holds it, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync and Backups) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. The page API's `on_event(name, listener)` hears the named events the app's services `emit`, on the web and the desktop. A page may have an `icon` (the sidebar then shows icon rows), a `use_badge` hook ("Inbox · 3"), `in_sidebar: false` with `active_as` for a page reached only by its route; `default_page` names the page an empty route opens, and the `use_chrome(parts)` hook gives the `sidebar` content under the rows, header `tools`, a `side_pane`, a `contained` window where only the page scrolls with a `main_class` for its box, `around`, which wraps the page, such as in the app's own context or with dialogs over any page, and `bare` for the page alone with no sidebar or header, such as a strip embedded in another program. `settings_categories(props)` adds the app's own Settings categories after General, for settings no one page owns. A page's `children` fold open under its row in the sidebar (`#/diet/foods`, the title "Foods · Diet", the first shown when none is named, a single child leaving the page one row), and `phone_services` loads the app's own work on the phone only there, such as reminders handed to Android, told of every write, every change from another device and each return to the app; an older version's backup schedule in the page's storage moves into the setting. In a browser, Settings ends with Users and Tokens (`users_settings`) for an admin of the server, with the app's `role_text`; an app's own `use_chrome` sidebar, such as a tree, sits under the pages' rows. |
21
21
  | `config/vite`, `config/electron_vite`, `config/vitest`, `config/electron_builder`, `config/tsconfig/*.json` | An X-app's configs as presets: `web_vite_config({ port })` and `android_vite_config()` for the page, `desktop_vite_config()` for electron-vite's window, daemon, preload and page, `vitest_config()` for tests in `tests/` in UTC with coverage of `src/` to the terminal, merged with the app's own floor so `autoUpdate` still raises it, and `base`, `node`, `web` and `tests` tsconfigs to extend. The page presets stand in for Capacitor where the app has none installed (`config/capacitor`'s `capacitor_stand_in`), so a web and desktop app needs no phone packages, and the dev server proxies `/api/`, leaving the page's own `api.ts` to Vite. `electron_builder_config({ id, name, app_id, comment, categories, link_scheme })` is the desktop app's AppImage and Flatpak bundle for electron-builder, the Flatpak keeping its data in `~/.config/<id>` as the other builds do. |
22
22
  | `app_new` | The `x-app-new <X-Name>` command: a new X-app's files written once, laid out as the Application Standard asks, on the base app, the presets, X-App's Nix lib and its CI actions, with an example notes feature; `--port`, `--folder`, `--no-desktop` and `--no-android`. |
23
23
  | `idle_watch` | `step_idle_watch`: time away from the computer while something runs, such as a timer: each look at the idle seconds (the desktop's `get_idle_seconds`) moves the watch on, and once someone comes back it hands back the stretch away (`AwaySpan`) when it passed the threshold, a long gap between looks, as when the computer slept, counting as time away from the last look; `fresh_idle_watch` to start. |
@@ -91,6 +91,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
91
91
  | `electron/mcp`, `local_mcp_protocol`, `web/react/local_mcp_settings` | A desktop app's own MCP endpoint, for AI clients on the same computer: `create_local_mcp` serves an `api_spec`'s calls as tools through `server/mcp` on 127.0.0.1 only, leaving out page-only calls and refusing the uses its `page_only` rule names, since the window reaches those over the daemon's socket, refusing any request whose Host or Origin is not a local name, turned on and given a port by `LocalMcpMethods` and kept in a settings file; with `require_token` on it also refuses any request without its token as `Authorization: Bearer`, the token made by the daemon and kept in `token_file` (`mcp-token` beside the settings unless set, mode 0600), kept across restarts and forgotten when the setting is turned off, and the status then carries `token` and `token_file`; `local_mcp_client_config` gives the `mcpServers` entry with its `headers`, and `local_mcp_add_command` the `claude mcp add` line reading the token from its file; `LocalMcpSettings` is the Settings rows to turn it on, pick the port, require a token, copy the `claude mcp add` command and show or copy the client config. |
92
92
  | `agent/commands` | `run_command` and `stream_command`: one shell command, in its own process group. |
93
93
  | `agent/programs` | `run_program`: one program with its arguments and no shell, each stream shown to a sink, kept, both or dropped, stopped by an abort signal and, in a process group of its own, with all it started; 127 when it is not installed; `start_line_program`, a program talked to in lines both ways while it runs, each whole line it prints handed on as it arrives (a character split across chunks kept whole), lines written to it until `end_input`, its group stopped by the signal; `BoundedBuffer`, `signal_group` and `on_path`; `whole_lines(sink)` passes on only whole lines, decoding characters split across chunks, with `flush()` for the rest, so programs printing side by side into one output never split each other's lines. |
94
+ | `agent/ssh_config` | `ssh_host_options(text, host, { home, local_user })`: what an OpenSSH client config such as `~/.ssh/config` says of one host (`host_name`, `user`, `port`, `identity_files` with `~`, `%h`, `%u` filled in), the first value of each keyword winning and Host patterns taking `*`, `?` and `!`, so a program reaching hosts over SSH honours its user's aliases as `ssh` and asyncssh do; `host_line_matches`. Match blocks and Include are not followed. |
94
95
  | `agent/firefox_bookmarks` | Firefox's bookmarks on this computer: `firefox_profile(set_folder)` (the folder set, with `~`, or the default profile from `profiles.ini`, read by `default_profile_of`), `read_firefox_bookmarks(profile)` from a copy of `places.sqlite` with its write-ahead log, since Firefox keeps it locked, read again only once either changes, tags left out; `bookmark_folders` by path, `bookmark_folder_path`, `bookmarks_in_folder` with every folder inside, `search_bookmarks` by every word of the title or address, `bookmarks_by_guid` and `is_page_bookmark`. |
95
96
  | `agent/claude_stream` | `start_claude_stream`: a Claude Code session driven over its stream-json protocol (`claude -p --input-format stream-json --output-format stream-json`) on `start_line_program`: `send_user` writes a message with the id the session echoes once it has read it, `control` sends a control request such as an interrupt or a change of permission mode and settles with the answer, a refusal or a timeout, the session's own requests such as `can_use_tool` go to `on_request` and are answered with `respond` (`allow_tool`, `deny_tool`), any not taken refused, and every other line is handed on with its JSON; `user_message_line`. |
96
97
  | `agent/git` | Git through `run_program`, never a shell: `git` throws git's own last words on an exit code not allowed; `default_branch` from origin's HEAD; `add_worktree` makes a worktree once at a path on its own branch, from the freshly fetched default branch or a `base`, or takes the branch when it exists; `list_worktrees`, the main checkout first with each head and branch; `reset_worktree` back to a commit, new files cleaned; `remove_worktree`, forced or not, with its branch; `read_raw_changes` and `read_numstat` for `git diff --raw -z` and `--numstat -z` (renames by their new path, binary files as null), `sum_numstat` and `untracked_files`. |
@@ -140,6 +141,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
140
141
  | `server/replies` | `register_error_replies`: errors and unknown paths answered in plain text or as `{ error }`; `register_lenient_json_body`: an empty body as no arguments and bad JSON as `BAD_JSON`, for the route to refuse in its own words, or refused with 400 before any route runs with `refuse_bad_json`; `send_text`. |
141
142
  | `server/config` | `read_server_config`: host, port, web folder and the app's options from flags, then the environment, then defaults, with usage text for `--help`, the secret from `<PREFIX>_TOKEN_FILE` or `<PREFIX>_TOKEN`, and no listening beyond this machine without one; `read_secret_file`; `create_secret_file`, a new random secret, such as a webhook's, in a file only its owner reads (mode 0600, tightened over an older file), read back only when the app is asked for it, and `has_secret_file`, whether there is one without reading it out; a secret printed by a command, such as a password manager's, so a setting names the program and never holds the secret: `command_words` splits the setting as a shell would without expanding anything, `secret_command_reader({ what, secret })` runs it without a shell and keeps its first line, refusing a failure, an empty or an overlong line (`max_secret_chars`) in words that never hold what it printed, `read_secret_command` with the default words, and `secret_from_command(line, read)`, `""` when no command is set. |
142
143
  | `server/declared_tokens` | Tokens declared in the app's config, so a scraper's token can live in a NixOS config: `read_declared_tokens` reads each entry's name, its `token_hash` (`sha256:<hex>` from `token_hash`), `token_file` or plain `token`, and a scope the app maps onto a role, read-only or not, or onto no role for a token only the app's own routes check, optionally limited to some of the app's items; bad entries are skipped and explained. Given to `AccountStore` as `declared_tokens` (or `set_declared_tokens` after a reload), they sign in with `server/account_sign_in` as their scope's role, cannot be revoked from the page, and `check_declared_token` finds the role-less ones. |
144
+ | `server/viewer_scope` | `with_viewer(viewer, work)` runs work as a request's viewer, kept across its awaits, and `current_viewer()` reads it, so work a route hands off, such as a host table's call, can name who asked. Node only. |
143
145
  | `config_watch` | `watch_config`: re-reads a config file when it changes, checking a fingerprint of what its path points at (symlinks followed, inode, change time, size) every few seconds, waiting one more check for it to hold still, and reloading only when the content's sha256 differs from what was loaded; a failed reload is reported and the watch goes on. |
144
146
  | `server/prometheus` | `render_metrics`: metric families in Prometheus' text format, with HELP and TYPE lines, labels in order, names made valid, label values and help escaped and infinities written as the format asks; `metrics_content_type`. |
145
147
  | `server/mqtt_discovery` | Home Assistant's MQTT discovery: `slug` for topic levels and ids, `discovery_topic`, and `reading_traits`, the device class and unit a reading's name implies, such as `_bytes` or `_temp_c`. |
@@ -149,7 +151,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
149
151
  | `server/mcp_client` | `create_mcp_client({ name, version, limits })`: a client of the MCP servers a user adds (`McpServerTarget` from `mcp_servers`, whose shapes it also re-exports), on the official SDK's client (`@modelcontextprotocol/client`): streamable HTTP with an optional bearer token, or a local command started without a shell with only the SDK's safe variables and those named (`passed_variables`); `list_tools` with the server's instructions (`instructions_of`) and each tool's read-only mark, `call_tool` answering in text (`result_text`), `forget` and `open_connections`; one connection per server kept while used and closed when idle, a server that exits, hangs or answers badly a plain error naming it and never its token. |
150
152
  | `server/address_guard` | Which web addresses a server may fetch for its user or a program: `checked_web_address` (http or https, no name or password, port 80 or 443 unless `allowed_ports`, read from a setting by `ports_of`, with a `ports_hint`), `is_public_address` and `public_addresses`, refusing a host any of whose addresses is loopback, private, link-local or otherwise not public, IPv4 inside IPv6 judged as itself, and `guarded_lookup` for node:http's `lookup`, so a name that answers differently when connecting still reaches only checked addresses. |
151
153
  | `server/cors` | `register_open_cors`: any origin may call the API, as a native or mobile shell does from a page of its own, with the client id header allowed. |
152
- | `web/dom`, `web/format`, `web/router`, `web/theme` | The page's element builder and `cx` class joiner, formatters (including `compact_count`, such as `"1.4M"`, and `format_count`, such as `"60,000"`), hash router and theme choice, kept in this browser or the app's settings, and `follow_host_theme` for taking a host page's colours, such as the Linux sidebar's. |
154
+ | `web/dom`, `web/format`, `web/router`, `web/theme` | The page's element builder and `cx` class joiner, formatters (including `compact_count`, such as `"1.4M"`, and `format_count`, such as `"60,000"`), hash router and theme choice, kept in this browser or the app's settings, and `follow_host_theme` for taking a host page's colours, such as the Linux sidebar's. `web/theme` also reads a server's `{ scheme, colors }` (`read_server_theme`), pins a scheme (`pinned_theme_choice`, whose `pinned` the Shell reads to leave out its theme row) and sets Halon tokens on the root (`apply_theme_colors`). |
153
155
  | `web/sqlite_wasm` | `open_wasm_database`: SQLite in WebAssembly for a page that keeps its own database, such as a phone app, saved whole to IndexedDB through `indexed_db_files` shortly after each change; `indexed_db_files` with `has` also keeps synced files. |
154
156
  | `web/pictures` | `shrink_picture`: a picture file or data URL redrawn at most 480 pixels on its longest side, or another limit, as a WebP data URL small enough to store and sync, such as a photo from a phone's camera. |
155
157
  | `web/markdown_text` | `as_code_block` and `code_fence`: text as a fenced code block whose fence outruns any backticks inside it, with no page needed, such as for a database upgrade. |
@@ -275,7 +277,7 @@ The rest of an app's files are short calls into X-App too:
275
277
  An app with git dependencies names each lock entry's https URL in `git_dependencies`, which the packages fetch and
276
278
  copy in, and `link_scheme`, such as `"codex"`, makes the desktop entry open its links; `desktop_path`, such as
277
279
  `pkgs: [ pkgs.libnotify ]`, puts programs the desktop app runs on its PATH, and `state_name` keeps an older service's
278
- data folder `/var/lib/<state_name>`, and `server_config`, such as `dir: { stages_folder = "${dir}/stages"; }`, adds the app's own keys to the server's config file; the desktop wrapper sets
280
+ data folder `/var/lib/<state_name>`, and `server_config`, such as `dir: { stages_folder = "${dir}/stages"; }`, adds the app's own keys to the server's config file; `sources`, such as `[ "src/core" "src/monitors" ]`, are more folders the server package runs from, and `programs`, such as `{ x-monitor-agent = "src/agent/main.ts"; }`, more commands it installs; the module's `settings` option adds keys of the machine's own to that file, winning over the module's; the desktop wrapper sets
279
281
  `<PREFIX>_LAUNCHER` so the login entry runs the installed command. `android_emulator_shell nixpkgs system app` adds an
280
282
  Android 36 emulator to the Android shell, with `<name>-emulator` to start it and `<name>-emulator-install` to build
281
283
  and open the app on it, never on a connected phone.
@@ -0,0 +1,12 @@
1
+ export interface SshHostOptions {
2
+ host_name: string | null;
3
+ user: string | null;
4
+ port: number | null;
5
+ identity_files: string[];
6
+ }
7
+ export interface SshConfigContext {
8
+ home: string;
9
+ local_user: string;
10
+ }
11
+ export declare function host_line_matches(patterns: readonly string[], host: string): boolean;
12
+ export declare function ssh_host_options(text: string, host: string, context: SshConfigContext): SshHostOptions;
@@ -0,0 +1,72 @@
1
+ // What an OpenSSH client config, such as ~/.ssh/config, says of one host: its real name, user, port and identity
2
+ // files, so a program connecting over SSH honours the aliases its user already set up, as ssh and asyncssh do. As
3
+ // OpenSSH reads it, the first value given for each keyword wins, and a Host line's patterns take * and ? and a !
4
+ // pattern that rules a host out. Match blocks and Include are not followed.
5
+ // ── Patterns ─────────────────────────────────────────────────────────────────
6
+ function pattern_matches(pattern, host) {
7
+ const expression = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*").replaceAll("?", ".");
8
+ return new RegExp(`^${expression}$`, "i").test(host);
9
+ }
10
+ // Whether a Host line's patterns take the host: one matches and no ! pattern rules it out.
11
+ export function host_line_matches(patterns, host) {
12
+ let matched = false;
13
+ for (const pattern of patterns) {
14
+ if (pattern.startsWith("!")) {
15
+ if (pattern_matches(pattern.slice(1), host))
16
+ return false;
17
+ }
18
+ else if (pattern_matches(pattern, host))
19
+ matched = true;
20
+ }
21
+ return matched;
22
+ }
23
+ // ── Reading ──────────────────────────────────────────────────────────────────
24
+ // A line's keyword and its arguments, quotes kept together, or null for a blank line or a comment.
25
+ function split_line(line) {
26
+ const text = line.trim();
27
+ if (text === "" || text.startsWith("#"))
28
+ return null;
29
+ const words = [...text.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2]);
30
+ const [first = "", ...rest] = words;
31
+ // "Keyword=value" and "Keyword = value" both name a value.
32
+ const equals = first.indexOf("=");
33
+ if (equals > 0)
34
+ return [first.slice(0, equals).toLowerCase(), [first.slice(equals + 1), ...rest].filter((word) => word !== "")];
35
+ return [first.toLowerCase(), rest.filter((word, index) => !(index === 0 && word === "="))];
36
+ }
37
+ function expand(path, host, context) {
38
+ const filled = path.replace(/%([%hu])/g, (_whole, code) => (code === "%" ? "%" : code === "h" ? host : context.local_user));
39
+ return filled === "~" ? context.home : filled.startsWith("~/") ? `${context.home}/${filled.slice(2)}` : filled;
40
+ }
41
+ // What the config's text says of the host given, the first value of each keyword winning.
42
+ export function ssh_host_options(text, host, context) {
43
+ const options = { host_name: null, user: null, port: null, identity_files: [] };
44
+ // Lines before any Host or Match line apply to every host.
45
+ let applies = true;
46
+ for (const line of text.split(/\r?\n/)) {
47
+ const split = split_line(line);
48
+ if (split === null)
49
+ continue;
50
+ const [keyword, args] = split;
51
+ if (keyword === "host") {
52
+ applies = host_line_matches(args, host);
53
+ continue;
54
+ }
55
+ if (keyword === "match") {
56
+ applies = false;
57
+ continue;
58
+ }
59
+ if (!applies || args.length === 0)
60
+ continue;
61
+ const value = args[0];
62
+ if (keyword === "hostname" && options.host_name === null)
63
+ options.host_name = value.replaceAll("%h", host);
64
+ else if (keyword === "user" && options.user === null)
65
+ options.user = value;
66
+ else if (keyword === "port" && options.port === null && /^\d+$/.test(value))
67
+ options.port = Number(value);
68
+ else if (keyword === "identityfile" && value.toLowerCase() !== "none")
69
+ options.identity_files.push(expand(value, options.host_name ?? host, context));
70
+ }
71
+ return options;
72
+ }
@@ -72,7 +72,7 @@ export async function start_daemon(app, options) {
72
72
  const services_now = () => services;
73
73
  // This computer's own AI clients reach the host tables too, as callers from elsewhere do, so what only this
74
74
  // computer's user may change stays refused.
75
- const local_tools = mcp_tools(app, { kind: "desktop", from_network: true, is_admin: () => true }, services_now, opened.database, () => changes.announce_change());
75
+ const local_tools = mcp_tools(app, { kind: "desktop", from_network: true, is_admin: () => true, has_role: () => true }, services_now, opened.database, () => changes.announce_change());
76
76
  // Off until turned on in Settings; a change made through it reaches the open windows and syncs like any other.
77
77
  const local_mcp = app.local_mcp
78
78
  ? create_local_mcp({
@@ -146,7 +146,7 @@ export async function start_daemon(app, options) {
146
146
  if (remote)
147
147
  register_call_table(api, "/remote", remote.methods, { is_read_only });
148
148
  // This computer's own window reaches every host table, those kept to it included.
149
- const reach = { kind: "desktop", from_network: false, is_admin: () => true };
149
+ const reach = { kind: "desktop", from_network: false, is_admin: () => true, has_role: () => true };
150
150
  register_host_tables(api, app, reach, services_now, changes);
151
151
  }, { prefix: "/api" });
152
152
  // ── Lifecycle ──────────────────────────────────────────────────────
@@ -193,6 +193,9 @@ export async function start_daemon(app, options) {
193
193
  profile,
194
194
  device_name: `${app.name} on ${hostname()}`,
195
195
  config: {},
196
+ config_file: null,
197
+ declared_tokens: () => [],
198
+ reread_declared_tokens: () => undefined,
196
199
  plugins_folder: join(profile, "plugins"),
197
200
  declared_file: options.declared_file ?? `/etc/${app.id}/declared.json`,
198
201
  announce: (client_id) => changes.announce_change(client_id),
@@ -209,7 +212,10 @@ export async function start_daemon(app, options) {
209
212
  });
210
213
  }
211
214
  // Devices signed in from elsewhere follow the restored data too.
212
- opened.on_restore({ before: () => services.before_restore?.(), after: () => (services.after_restore?.(), void remote?.restart()) });
215
+ opened.on_restore({ before: () => services.before_restore?.(), after: async () => {
216
+ await services.after_restore?.();
217
+ void remote?.restart();
218
+ } });
213
219
  await remote?.restart();
214
220
  // Without "Keep running in the background", the daemon stops a while after its last window has gone.
215
221
  let unused_since = Date.now();
@@ -7,6 +7,7 @@ import { type ConnectionMethods } from "../connection_protocol.ts";
7
7
  import { type Bridge } from "../electron/bridge.ts";
8
8
  import { type EventsBridge } from "../electron/events.ts";
9
9
  import type { History } from "../history.ts";
10
+ import type { ScopeSpec } from "../server/declared_tokens.ts";
10
11
  import { type LocalMcpMethods } from "../local_mcp_protocol.ts";
11
12
  import { type SettingSpec, type SettingsMethods, type SettingsStore, type SettingsStoreOptions } from "../settings.ts";
12
13
  import { type MigrationStep, type SqlDatabase } from "../sql.ts";
@@ -34,6 +35,7 @@ export interface HostTable<Methods = Record<string, (...args: never[]) => unknow
34
35
  api: ApiSpec<Methods>;
35
36
  hosts: readonly HostKind[];
36
37
  network?: "admin" | "any" | "none";
38
+ needs?: (method: string) => string | null | undefined;
37
39
  }
38
40
  declare const host_table_route: (name: string) => string;
39
41
  type UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends (value: infer Both) => void ? Both : never;
@@ -79,6 +81,13 @@ export interface AppOptions<Features extends readonly Feature[]> {
79
81
  host_tables?: Readonly<Record<string, HostTable>>;
80
82
  remote_access?: boolean;
81
83
  phone?: "device" | "portal";
84
+ roles?: readonly string[];
85
+ sync?: boolean;
86
+ declared_tokens?: {
87
+ key: string;
88
+ scopes: Record<string, ScopeSpec>;
89
+ limit_key?: string;
90
+ };
82
91
  }
83
92
  export declare const base_setting_defaults: {
84
93
  history_days: number;
@@ -146,6 +155,13 @@ export declare function define_app<const Features extends readonly Feature[]>(op
146
155
  synced_theme?: boolean;
147
156
  remote_access?: boolean;
148
157
  phone?: "device" | "portal";
158
+ roles?: readonly string[];
159
+ sync?: boolean;
160
+ declared_tokens?: {
161
+ key: string;
162
+ scopes: Record<string, ScopeSpec>;
163
+ limit_key?: string;
164
+ };
149
165
  features: readonly Feature<Record<string, StoreMethod>>[];
150
166
  settings_store: SettingsStore;
151
167
  setting_defaults: Readonly<import("../settings.ts").Settings>;
@@ -9,6 +9,7 @@ export interface HostReach {
9
9
  kind: HostKind;
10
10
  from_network: boolean;
11
11
  is_admin: (request: FastifyRequest) => boolean;
12
+ has_role: (request: FastifyRequest, role: string) => boolean;
12
13
  }
13
14
  export declare function host_abilities(app: App, reach: HostReach, request: FastifyRequest): HostAbilities;
14
15
  export declare function register_host_tables(api: FastifyInstance, app: App, reach: HostReach, services: () => HostServices, changes: EventStream): void;
@@ -3,6 +3,14 @@
3
3
  // tools MCP offers being the data calls and those tables together.
4
4
  import { positional_args } from "../api_spec.js";
5
5
  import { send_text } from "../server/replies.js";
6
+ import { with_viewer } from "../server/viewer_scope.js";
7
+ // Why the one asking may not make a call of a table's that needs a role of its own, or null when they may.
8
+ function role_refusal(table, reach, method, request) {
9
+ const role = table.needs?.(method);
10
+ if (!role || !request || reach.has_role(request, role))
11
+ return null;
12
+ return `${method} needs the ${role} role.`;
13
+ }
6
14
  // The tables the one asking may reach on this host, as the page reads them to know what it can offer.
7
15
  export function host_abilities(app, reach, request) {
8
16
  const admin = reach.is_admin(request);
@@ -30,6 +38,9 @@ export function register_host_tables(api, app, reach, services, changes) {
30
38
  return send_text(reply, 404, `no call named ${method}`);
31
39
  if (reach.from_network && table.network !== "any" && !reach.is_admin(request))
32
40
  return send_text(reply, 403, `${method} needs an admin.`);
41
+ const refusal = reach.from_network ? role_refusal(table, reach, method, request) : null;
42
+ if (refusal)
43
+ return send_text(reply, 403, refusal);
33
44
  const methods = served_methods(services, name, reach.from_network);
34
45
  if (!methods || typeof methods[method] !== "function")
35
46
  return send_text(reply, 503, `${app.name} is still starting; try ${method} again in a moment.`);
@@ -47,7 +58,7 @@ export function register_host_tables(api, app, reach, services, changes) {
47
58
  }
48
59
  else
49
60
  return send_text(reply, 400, "send the arguments as a JSON list or object");
50
- const result = await methods[method](...args);
61
+ const result = await with_viewer(request.viewer, () => methods[method](...args));
51
62
  const read_only = app.is_read_only(method);
52
63
  if (!read_only)
53
64
  changes.announce_change(changes.client_id_of(request));
@@ -72,10 +83,13 @@ export function mcp_tools(app, reach, services, database, announce) {
72
83
  return app.mcp.call(database, announce, method, args);
73
84
  if (app.host_tables[name].network !== "any" && request && !reach.is_admin(request))
74
85
  throw new Error(`${method} needs an admin's token`);
86
+ const refusal = role_refusal(app.host_tables[name], reach, method, request);
87
+ if (refusal)
88
+ throw new Error(refusal);
75
89
  const methods = served_methods(services, name, true);
76
90
  if (!methods || typeof methods[method] !== "function")
77
91
  throw new Error(`${app.name} is still starting; try ${method} again in a moment.`);
78
- const result = await methods[method](...args);
92
+ const result = await with_viewer(request?.viewer, () => methods[method](...args));
79
93
  if (!app.is_read_only(method))
80
94
  announce();
81
95
  return result;
@@ -6,6 +6,7 @@ import type { Client } from "../electron/bridge.ts";
6
6
  import type { RemoteAccessClient } from "../remote_access_protocol.ts";
7
7
  import type { PeerListeningClient, SyncDeviceClient } from "../sync_protocol.ts";
8
8
  import type { DataChange } from "../sync_protocol.ts";
9
+ import type { ServerTheme } from "../web/theme.ts";
9
10
  export { data_change_of, type DataChange } from "../sync_protocol.ts";
10
11
  export interface DesktopSettings {
11
12
  show_tray_icon: boolean;
@@ -84,6 +85,7 @@ export interface PageApi<Methods extends Record<keyof Methods, (...args: never[]
84
85
  set: (key: string, on: boolean) => Promise<void>;
85
86
  };
86
87
  reread_abilities?: () => Promise<Pick<PageApi, "admin" | "tables">>;
88
+ server_theme?: ServerTheme;
87
89
  on_change: (listener: (change: DataChange | null) => void) => () => void;
88
90
  on_event?: (event: string, listener: (data: unknown) => void) => () => void;
89
91
  }
@@ -1,9 +1,11 @@
1
1
  import { DatabaseSync } from "node:sqlite";
2
2
  import { type FastifyInstance } from "fastify";
3
3
  import { type BackupMethods } from "../backups.ts";
4
+ import { OidcClient } from "../server/oidc.ts";
4
5
  import { AccountStore } from "../server/account_store.ts";
5
6
  import { EventStream } from "../server/events.ts";
6
7
  import { type SqlDatabase } from "../sql.ts";
8
+ import { type ServerTheme } from "../web/theme.ts";
7
9
  import { type SyncPeer } from "../sync_peer.ts";
8
10
  import type { App, HostKind } from "./define.ts";
9
11
  import { type AppRoutes, type HostServices, type StartServices } from "./services.ts";
@@ -12,8 +14,8 @@ export interface AppDatabase {
12
14
  back_up: () => Promise<void>;
13
15
  backup_methods: BackupMethods;
14
16
  on_restore: (hooks: {
15
- before?: () => void;
16
- after?: () => void;
17
+ before?: () => void | Promise<void>;
18
+ after?: () => void | Promise<void>;
17
19
  }) => void;
18
20
  close: () => void;
19
21
  }
@@ -37,6 +39,11 @@ export interface ServerOptions {
37
39
  cert: Buffer;
38
40
  key: Buffer;
39
41
  };
42
+ oidc?: OidcClient | null;
43
+ session_seconds?: number | null;
44
+ remembered_seconds?: number | null;
45
+ theme?: ServerTheme;
46
+ plugins_folder?: string | null;
40
47
  }
41
48
  export declare const user_only_backup_calls: ReadonlySet<string>;
42
49
  export declare function build_server(app: App, options: ServerOptions): Promise<FastifyInstance>;
@@ -12,6 +12,8 @@ import { openapi_document, positional_args } from "../api_spec.js";
12
12
  import { keep_backing_up } from "../backups.js";
13
13
  import { backup_method_names } from "../backups.js";
14
14
  import { calls_under, register_accounts } from "../server/account_sign_in.js";
15
+ import { read_declared_tokens } from "../server/declared_tokens.js";
16
+ import { OidcClient, oidc_from_environment } from "../server/oidc.js";
15
17
  import { caller_of, use_caller_scope } from "../caller.js";
16
18
  import { node_caller_scope } from "../node_caller_scope.js";
17
19
  import { AccountStore, holds_accounts, move_accounts } from "../server/account_store.js";
@@ -20,6 +22,7 @@ import { register_open_cors } from "../server/cors.js";
20
22
  import { read_server_config } from "../server/config.js";
21
23
  import { EventStream } from "../server/events.js";
22
24
  import { register_mcp_route } from "../server/mcp.js";
25
+ import { register_plugin_files } from "../server/plugin_files.js";
23
26
  import { load_accounts } from "../server/passwords.js";
24
27
  import { BAD_JSON, register_error_replies, register_lenient_json_body, send_text } from "../server/replies.js";
25
28
  import { sqlite_backups } from "../server/sqlite_backups.js";
@@ -27,6 +30,7 @@ import { register_sync_peer_routes, sync_peer_headers } from "../server/sync_pee
27
30
  import { register_web_folder } from "../server/web_folder.js";
28
31
  import { tidy_database, tidy_every_ms } from "../sql.js";
29
32
  import { file_sync_storage } from "../sync_file_storage.js";
33
+ import { read_server_theme } from "../web/theme.js";
30
34
  import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
31
35
  import { call_path_of, mcp_tools, register_host_tables } from "./host_tables.js";
32
36
  import { notice_event } from "./protocol.js";
@@ -45,15 +49,15 @@ export function open_app_database(app, path, backups_folder) {
45
49
  naming: app.backup_naming,
46
50
  database: () => database,
47
51
  database_path: () => path,
48
- close: () => {
49
- restore_hooks.before?.();
52
+ close: async () => {
53
+ await restore_hooks.before?.();
50
54
  database.close();
51
55
  },
52
- open: () => {
56
+ open: async () => {
53
57
  database = new DatabaseSync(path);
54
58
  start(database);
55
59
  tidy_database(database);
56
- restore_hooks.after?.();
60
+ await restore_hooks.after?.();
57
61
  },
58
62
  // The restored data no longer matches other devices', so sync asks again which copy wins.
59
63
  after_restore: (restored) => app.sync_engine.forget_history(restored),
@@ -201,16 +205,26 @@ export async function build_server(app, options) {
201
205
  }
202
206
  const admin_tables = app.tables_on(kind, true).filter((name) => app.host_tables[name].network !== "any").map((name) => `/api/${name}/`);
203
207
  const is_admin = (request) => request.viewer !== null && request.viewer !== undefined && options.accounts.has_role(request.viewer.role, options.accounts.top_role);
204
- const reach = { kind, from_network: true, is_admin };
208
+ const has_role = (request, role) => request.viewer !== null && request.viewer !== undefined && options.accounts.has_role(request.viewer.role, role);
209
+ const reach = { kind, from_network: true, is_admin, has_role };
205
210
  await register_accounts(server, {
206
211
  accounts: options.accounts,
207
212
  cookie_name: `${app.id.replaceAll("-", "_")}_session`,
208
213
  // Each peer call is sealed between the two devices, so it needs no sign-in, and the app's open routes check their
209
214
  // callers themselves.
210
- open_paths: ["/api/sync/peer", ...(options.routes?.open_paths ?? [])],
215
+ open_paths: ["/api/sync/peer", "/api/theme", ...(options.routes?.open_paths ?? [])],
216
+ open_prefixes: options.routes?.open_prefixes ?? [],
217
+ guarded_paths: options.routes?.guarded_paths ?? [],
218
+ oidc: options.oidc ?? null,
219
+ ...(options.session_seconds !== undefined ? { session_seconds: options.session_seconds } : {}),
220
+ ...(options.remembered_seconds !== undefined ? { remembered_seconds: options.remembered_seconds } : {}),
211
221
  // A read-only token may still list and read through MCP, which posts every request.
212
222
  read_only_paths: ["/api/mcp"],
213
- needed: (_method, path) => ([...admin_paths, ...admin_tables].some((admin_path) => path.startsWith(admin_path)) ? { role: options.accounts.top_role } : "any"),
223
+ needed: (method, path) => {
224
+ if ([...admin_paths, ...admin_tables].some((admin_path) => path.startsWith(admin_path)))
225
+ return { role: options.accounts.top_role };
226
+ return options.routes?.needed?.(method, path) ?? "any";
227
+ },
214
228
  // A token is refused the calls only the user at the page may make; a read-only one may make the calls that only read.
215
229
  call_of: calls_under("/api/call"),
216
230
  is_read_only: app.is_read_only,
@@ -223,6 +237,7 @@ export async function build_server(app, options) {
223
237
  const documented = Object.assign({}, app.api_spec, ...app.tables_on(kind, true).map((name) => app.host_tables[name].api));
224
238
  await server.register(async (api) => {
225
239
  changes.register(api, "/events");
240
+ api.get("/theme", async () => options.theme ?? read_server_theme(null));
226
241
  register_app_calls(api, app, database, changes);
227
242
  register_host_tables(api, app, reach, services, changes);
228
243
  api.get("/openapi.json", async () => openapi_document(documented, { ...description, path_of: call_path_of(app, kind), is_read_only: app.is_read_only }));
@@ -255,6 +270,8 @@ export async function build_server(app, options) {
255
270
  register_call_table(api, "/sync", sync_device_methods(options.sync), { is_read_only: app.is_read_only });
256
271
  }
257
272
  }, { prefix: "/api" });
273
+ if (options.plugins_folder)
274
+ register_plugin_files(server, { folder: options.plugins_folder, prefix: "/api/plugins", side: "web" });
258
275
  await options.routes?.register(server, services);
259
276
  await register_web_folder(server, { folder: options.web_folder });
260
277
  return server;
@@ -287,18 +304,30 @@ export async function run_server(app, options) {
287
304
  await opened.back_up();
288
305
  move_accounts(opened.database(), accounts_database);
289
306
  }
307
+ // Tokens the config declares, read again whenever the app's services read a changed config.
308
+ const declare_tokens = (from) => {
309
+ const declared = app.declared_tokens;
310
+ if (!declared)
311
+ return [];
312
+ return read_declared_tokens(from[declared.key], { scopes: declared.scopes, ...(declared.limit_key ? { limit_key: declared.limit_key } : {}), new_token_command: `${app.id} token new` });
313
+ };
314
+ let declared_tokens = declare_tokens(config);
290
315
  const accounts = new AccountStore({
291
316
  database: accounts_database,
292
317
  app_name: app.name,
318
+ ...(app.roles ? { roles: app.roles } : {}),
293
319
  ...(app.token_prefix ? { token_prefix: app.token_prefix } : {}),
294
320
  declared: load_accounts(`${prefix}_PASSWORD_HASH_FILE`, server_config.values.password_hash_file),
321
+ declared_tokens: declared_tokens.filter((token) => token.role !== null),
295
322
  });
323
+ const oidc_settings = oidc_from_environment(prefix, options.env ?? process.env);
296
324
  // Every page hears of a change, whether a page or another device made it, and which tables it touched.
297
325
  const changes = new EventStream({ change_data: data_change_text(app, opened.database) });
298
326
  // Answers the host tables and the app's routes once started; before then they say the server is still starting.
299
327
  let services = no_services;
300
- // The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be.
301
- const sync = create_sync_peer({
328
+ // The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be; an app
329
+ // whose server is the only copy keeps none.
330
+ const sync = app.sync === false ? null : create_sync_peer({
302
331
  app: app.id,
303
332
  engine: app.sync_engine,
304
333
  database: opened.database,
@@ -310,10 +339,19 @@ export async function run_server(app, options) {
310
339
  services.after_remote_change?.();
311
340
  },
312
341
  });
313
- const server = await build_server(app, { database: opened.database, accounts, web_folder: server_config.web_folder, sync, changes, backup_methods: opened.backup_methods, services: () => services, ...(options.routes ? { routes: options.routes } : {}) });
342
+ const server = await build_server(app, {
343
+ database: opened.database, accounts, web_folder: server_config.web_folder, changes, backup_methods: opened.backup_methods, services: () => services,
344
+ ...(sync ? { sync } : {}),
345
+ ...(options.routes ? { routes: options.routes } : {}),
346
+ ...(oidc_settings ? { oidc: new OidcClient(oidc_settings) } : {}),
347
+ ...(config.session_seconds !== undefined ? { session_seconds: config.session_seconds } : {}),
348
+ ...(config.remembered_seconds !== undefined ? { remembered_seconds: config.remembered_seconds } : {}),
349
+ theme: read_server_theme(config.theme),
350
+ plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
351
+ });
314
352
  const stop_watching = watch_outside_changes(opened.database, () => changes.announce_change());
315
353
  const address = await server.listen({ host: server_config.host, port: server_config.port });
316
- sync.start();
354
+ sync?.start();
317
355
  const sides = side_databases(database_path);
318
356
  services = options.services
319
357
  ? await options.services({
@@ -322,6 +360,12 @@ export async function run_server(app, options) {
322
360
  profile: dirname(database_path),
323
361
  device_name: `${app.name} server on ${hostname()}`,
324
362
  config: config,
363
+ config_file: resolve(server_config.values.config),
364
+ declared_tokens: () => declared_tokens,
365
+ reread_declared_tokens: (from) => {
366
+ declared_tokens = declare_tokens(from);
367
+ accounts.set_declared_tokens(declared_tokens.filter((token) => token.role !== null));
368
+ },
325
369
  plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
326
370
  declared_file: declared_file_of(app, options.env ?? process.env),
327
371
  announce: (client_id) => changes.announce_change(client_id),
@@ -344,7 +388,7 @@ export async function run_server(app, options) {
344
388
  const stop = () => (stopping ??= server.close().then(async () => {
345
389
  await services.stop();
346
390
  stop_watching();
347
- sync.stop();
391
+ sync?.stop();
348
392
  sides.close_all();
349
393
  opened.close();
350
394
  accounts_database.close();
@@ -1,5 +1,7 @@
1
1
  import { DatabaseSync } from "node:sqlite";
2
2
  import type { FastifyInstance } from "fastify";
3
+ import type { Need } from "../server/account_sign_in.ts";
4
+ import type { DeclaredToken } from "../server/declared_tokens.ts";
3
5
  import type { App } from "./define.ts";
4
6
  import type { AppNotice } from "./protocol.ts";
5
7
  export interface HostContext {
@@ -8,6 +10,9 @@ export interface HostContext {
8
10
  profile: string;
9
11
  device_name: string;
10
12
  config: Readonly<Record<string, unknown>>;
13
+ config_file: string | null;
14
+ declared_tokens: () => readonly DeclaredToken[];
15
+ reread_declared_tokens: (config: Readonly<Record<string, unknown>>) => void;
11
16
  plugins_folder: string | null;
12
17
  declared_file: string;
13
18
  announce: (client_id?: string) => void;
@@ -24,8 +29,8 @@ export interface ServedTable {
24
29
  elsewhere?: object;
25
30
  }
26
31
  export interface HostServices {
27
- before_restore?: () => void;
28
- after_restore?: () => void;
32
+ before_restore?: () => void | Promise<void>;
33
+ after_restore?: () => void | Promise<void>;
29
34
  stop: () => void | Promise<void>;
30
35
  tables?: Readonly<Record<string, ServedTable>>;
31
36
  own?: unknown;
@@ -34,6 +39,9 @@ export interface HostServices {
34
39
  export type StartServices = (context: HostContext) => HostServices | Promise<HostServices>;
35
40
  export interface AppRoutes {
36
41
  open_paths?: readonly string[];
42
+ open_prefixes?: readonly string[];
43
+ guarded_paths?: readonly string[];
44
+ needed?: (method: string, path: string) => Need | null;
37
45
  register: (server: FastifyInstance, services: () => HostServices) => void | Promise<void>;
38
46
  }
39
47
  export declare function declared_file_of(app: Pick<App, "id" | "env_prefix">, env: NodeJS.ProcessEnv): string;
@@ -2,7 +2,7 @@ import "@x-tech-laboratories/halon/halon-tokens.css";
2
2
  import "@x-tech-laboratories/halon/halon.css";
3
3
  import type { App } from "../define.ts";
4
4
  import { type AppPages } from "./settings_page.tsx";
5
- export type { AppPage, AppPages, AppSubpage, PageSettingsProps } from "./settings_page.tsx";
5
+ export type { AppChrome, AppPage, AppPages, AppSubpage, PageSettingsProps } from "./settings_page.tsx";
6
6
  export declare const default_sidebar_width: {
7
7
  default_width: number;
8
8
  min: number;
@@ -14,7 +14,7 @@ import { PageHeading } from "../../web/react/layout.js";
14
14
  import { Shell, use_route } from "../../web/react/shell.js";
15
15
  import { SignInForm, use_account } from "../../web/react/sign_in.js";
16
16
  import { SyncButton } from "../../web/react/sync_settings.js";
17
- import { local_theme_storage, theme_choice } from "../../web/theme.js";
17
+ import { apply_theme_colors, local_theme_storage, pinned_theme_choice, read_server_theme, theme_choice } from "../../web/theme.js";
18
18
  import { desktop_api, is_android, is_desktop, web_api } from "./hosts.js";
19
19
  import { calls, data_watch, page, set_page_api, set_page_reach, use_settings } from "./page.js";
20
20
  import { SettingsView } from "./settings_page.js";
@@ -40,13 +40,27 @@ function is_theme(value) {
40
40
  }
41
41
  // The theme kept in this browser, or for an app with synced_theme in its synced setting, which a change on another
42
42
  // device applies here too; this browser's copy shows it before the settings arrive.
43
+ // The look a browser's server pins, read once before the page draws.
44
+ async function read_theme_of_server() {
45
+ try {
46
+ const reply = await fetch("api/theme", { cache: "no-store" });
47
+ return reply.ok ? read_server_theme(await reply.json()) : read_server_theme(null);
48
+ }
49
+ catch {
50
+ return read_server_theme(null);
51
+ }
52
+ }
53
+ // A scheme the server pins wins over both, and the page then offers no way to change it.
43
54
  function use_theme(app) {
55
+ const pinned = page().server_theme?.scheme ?? null;
44
56
  const settings = use_settings();
45
57
  const synced = app.synced_theme === true;
46
58
  const stored = synced ? settings.data?.theme : undefined;
47
59
  const latest = useRef(undefined);
48
60
  latest.current = stored;
49
61
  const theme = useMemo(() => {
62
+ if (pinned)
63
+ return pinned_theme_choice(pinned);
50
64
  const local = local_theme_storage(`${app.id}-theme`);
51
65
  if (!synced)
52
66
  return theme_choice(local);
@@ -58,7 +72,7 @@ function use_theme(app) {
58
72
  void calls().set_setting("theme", chosen).catch(() => undefined);
59
73
  },
60
74
  });
61
- }, [app.id, synced]);
75
+ }, [app.id, synced, pinned]);
62
76
  // The desktop window's own parts, such as menus, follow the page's theme.
63
77
  useEffect(() => {
64
78
  const tell = (chosen) => void page().desktop?.set_window_theme(chosen).catch(() => undefined);
@@ -66,11 +80,11 @@ function use_theme(app) {
66
80
  return theme.on_change(tell);
67
81
  }, [theme]);
68
82
  useEffect(() => {
69
- if (!is_theme(stored))
83
+ if (pinned || !is_theme(stored))
70
84
  return;
71
85
  local_theme_storage(`${app.id}-theme`).write(stored);
72
86
  theme.apply(stored);
73
- }, [stored, theme]);
87
+ }, [stored, theme, pinned]);
74
88
  return theme;
75
89
  }
76
90
  function Pages({ pages, account }) {
@@ -94,6 +108,8 @@ function Pages({ pages, account }) {
94
108
  const badges = listed.map((each) => each.use_badge?.() ?? null);
95
109
  const row_label = (index) => (badges[index] ? `${listed[index].label} · ${badges[index]}` : listed[index].label);
96
110
  const with_icons = listed.some((each) => each.icon);
111
+ // An app's own sidebar content, such as a tree, takes the place of plain sections, so the pages show as rows above it.
112
+ const folding = listed.some((each) => each.children && each.children.length > 1);
97
113
  const sections = listed.map((each, index) => ({
98
114
  id: each.id,
99
115
  label: row_label(index),
@@ -101,11 +117,11 @@ function Pages({ pages, account }) {
101
117
  ...(each.children && each.children.length > 1 ? { children: each.children.map((child) => ({ id: child.id, label: child.label, href: `#/${each.id}/${child.id}` })) } : {}),
102
118
  }));
103
119
  const views = listed.map((each, index) => ({ id: each.id, label: row_label(index), href: `#/${each.id}`, ...(each.icon ? { icon: each.icon } : {}) }));
104
- const view = shown ? shown.view(rest) : is_account ? _jsx(AccountPage, { account: account }) : _jsx(SettingsView, { pages: pages, is_admin: account === null || is_admin(account.me) });
120
+ const view = shown ? shown.view(rest) : is_account ? _jsx(AccountPage, { account: account }) : _jsx(SettingsView, { pages: pages, is_admin: account === null || is_admin(account.me), viewer: account ? { client: accounts, me: account.me } : null });
105
121
  const framed = _jsx(Fragment, { children: view }, view_key);
106
122
  if (chrome.bare)
107
123
  return _jsx(_Fragment, { children: chrome.around ? chrome.around(framed) : framed });
108
- return (_jsx(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", ...(with_icons ? { views } : { sections }), active: shown?.active_as ?? section, active_item: subpage?.id ?? null, sections_pref: `${app.id}-sidebar-collapsed`, ...(chrome.sidebar ? { sidebar: chrome.sidebar } : {}), ...(chrome.tools ? { tools: chrome.tools } : {}), ...(chrome.side_pane ? { side_pane: chrome.side_pane } : {}), ...(chrome.contained ? { contained: true } : {}), ...(chrome.main_class ? { main_class: chrome.main_class } : {}), theme: theme, sidebar_width: chrome.sidebar_width ?? { ...default_sidebar_width, storage_key: `${app.id}-sidebar-width` }, view_key: view_key, user: account ? account.me.name : undefined, user_href: account ? "#/account" : undefined, on_logout: account ? () => void account.sign_out() : undefined, sidebar_foot: _jsx(SidebarFoot, {}), settings: { href: "#/settings" }, children: chrome.around ? chrome.around(framed) : framed }));
124
+ return (_jsx(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", ...(with_icons || (chrome.sidebar && !folding) ? { views } : { sections }), active: shown?.active_as ?? section, active_item: subpage?.id ?? null, sections_pref: `${app.id}-sidebar-collapsed`, ...(chrome.sidebar ? { sidebar: chrome.sidebar } : {}), ...(chrome.tools ? { tools: chrome.tools } : {}), ...(chrome.side_pane ? { side_pane: chrome.side_pane } : {}), ...(chrome.contained ? { contained: true } : {}), ...(chrome.main_class ? { main_class: chrome.main_class } : {}), theme: theme, sidebar_width: chrome.sidebar_width ?? { ...default_sidebar_width, storage_key: `${app.id}-sidebar-width` }, view_key: view_key, user: account ? account.me.name : undefined, user_href: account ? "#/account" : undefined, on_logout: account ? () => void account.sign_out() : undefined, sidebar_foot: _jsx(SidebarFoot, {}), settings: { href: "#/settings" }, children: chrome.around ? chrome.around(framed) : framed }));
109
125
  }
110
126
  // ── App ──────────────────────────────────────────────────────────────────────
111
127
  // A browser reaches the server's data, so it signs in; the desktop and phone apps keep their own and sign in only to sync.
@@ -173,6 +189,14 @@ async function host_api(app, pages) {
173
189
  // Starts the page on whichever host it runs: the desktop app, the phone app or a browser.
174
190
  export async function render_app(pages, root = document.getElementById("app")) {
175
191
  const api = await host_api(pages.app, pages);
192
+ // A browser takes the look its server pins before anything draws, the sign-in page included.
193
+ if (api.host === "web") {
194
+ const server_theme = await read_theme_of_server();
195
+ api.server_theme = server_theme;
196
+ apply_theme_colors(server_theme.colors);
197
+ if (server_theme.scheme)
198
+ pinned_theme_choice(server_theme.scheme).apply();
199
+ }
176
200
  if (api.reread_abilities)
177
201
  Object.assign(api, await api.reread_abilities());
178
202
  set_page_api(api);
@@ -2,7 +2,7 @@ import type { App } from "../define.ts";
2
2
  import { type HostAbilities, type PageApi } from "../protocol.ts";
3
3
  export declare function read_host_abilities(read: () => Promise<unknown>): Promise<HostAbilities>;
4
4
  export declare function host_tables_of(app: Pick<App, "bridges">, abilities: HostAbilities, client_of: (name: string) => unknown): NonNullable<PageApi["tables"]>;
5
- export declare function web_api(app: Pick<App, "bridges">): PageApi;
5
+ export declare function web_api(app: Pick<App, "bridges"> & Partial<Pick<App, "sync">>): PageApi;
6
6
  export declare function is_desktop(app: Pick<App, "bridges">): boolean;
7
7
  export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "local_mcp" | "remote_access">>): Promise<PageApi>;
8
8
  export declare function is_android(): boolean;
@@ -102,8 +102,8 @@ export function web_api(app) {
102
102
  admin: false,
103
103
  reread_abilities: async () => reach(await read_abilities()),
104
104
  calls: bridges.calls.web_rpc((method, args) => post_call(call_path, method, args)),
105
- // The server's own sync peer and backups, which only an admin reaches.
106
- device: bridges.device.web_rpc((method, args) => post_call(device_path, method, args)),
105
+ // The server's own sync peer and backups, which only an admin reaches; an app whose server is the only copy has no peer.
106
+ device: app.sync === false ? null : bridges.device.web_rpc((method, args) => post_call(device_path, method, args)),
107
107
  backups: bridges.backups.web_rpc((method, args) => post_call(backups_path, method, args)),
108
108
  on_change: (listener) => {
109
109
  listeners.add(listener);
@@ -1,4 +1,5 @@
1
1
  import type { IconGlyph } from "../../web/react/icons.tsx";
2
+ import type { AccountsClient, Me } from "../../web/accounts.ts";
2
3
  import { type SettingsCategory, type SettingsSection } from "../../web/react/layout.tsx";
3
4
  import type { ShellSidePane, SidebarWidth } from "../../web/react/shell.tsx";
4
5
  import type { LocalNotificationsLike } from "../../phone_notices.ts";
@@ -45,8 +46,14 @@ export interface AppPages {
45
46
  phone_services?: () => Promise<StartPhoneServices>;
46
47
  phone_notifications?: () => Promise<LocalNotificationsLike>;
47
48
  remote_access_reach?: string;
49
+ role_text?: Readonly<Record<string, string>>;
48
50
  }
49
- export declare function SettingsView({ pages, is_admin }: {
51
+ export interface SettingsViewer {
52
+ client: AccountsClient;
53
+ me: Me;
54
+ }
55
+ export declare function SettingsView({ pages, is_admin, viewer }: {
50
56
  pages: AppPages;
51
57
  is_admin?: boolean;
58
+ viewer?: SettingsViewer | null;
52
59
  }): import("react").JSX.Element;
@@ -8,6 +8,7 @@ import { TrustedCertificates } from "../../web/react/certificates.js";
8
8
  import { ConnectionSettings } from "../../web/react/connections.js";
9
9
  import { LocalMcpSettings } from "../../web/react/local_mcp_settings.js";
10
10
  import { Switch } from "../../web/react/controls.js";
11
+ import { users_settings } from "../../web/react/accounts.js";
11
12
  import { PageHeading, SettingRow, SettingsPage } from "../../web/react/layout.js";
12
13
  import { Loaded } from "../../web/react/states.js";
13
14
  import { RemoteAccessSettings } from "../../web/react/remote_access_settings.js";
@@ -90,8 +91,15 @@ function storage_category(pages, is_admin) {
90
91
  }
91
92
  return sections.length === 0 ? [] : [{ heading: host === "web" ? "Server" : "This device", sections }];
92
93
  }
93
- // ── Page ─────────────────────────────────────────────────────────────────────
94
- export function SettingsView({ pages, is_admin = true }) {
94
+ // ── Users ────────────────────────────────────────────────────────────────────
95
+ // The server's users and every token, for its admin in a browser; nobody else sees the category.
96
+ function users_category(pages, viewer) {
97
+ if (viewer === null)
98
+ return [];
99
+ const sections = users_settings({ client: viewer.client, me: viewer.me, ...(pages.role_text ? { role_text: pages.role_text } : {}) });
100
+ return sections.length > 0 ? [{ heading: "Users", sections }] : [];
101
+ }
102
+ export function SettingsView({ pages, is_admin = true, viewer = null }) {
95
103
  const settings = use_settings();
96
104
  const set_setting = async (key, value) => void (await calls().set_setting(key, value));
97
105
  return (_jsxs(_Fragment, { children: [_jsx(PageHeading, { title: "Settings" }), _jsx(Loaded, { resource: settings, children: (values) => {
@@ -104,6 +112,7 @@ export function SettingsView({ pages, is_admin = true }) {
104
112
  .map((each) => ({ heading: each.label, sections: each.settings?.(props) ?? [] }))
105
113
  .filter((category) => category.sections.length > 0),
106
114
  ...storage_category(pages, is_admin && page().admin !== false),
115
+ ...users_category(pages, viewer),
107
116
  ] }));
108
117
  } })] }));
109
118
  }
@@ -5,8 +5,8 @@ export interface SqliteBackupOptions {
5
5
  naming: BackupNaming;
6
6
  database: () => SqlDatabase;
7
7
  database_path: () => string;
8
- close?: () => void;
9
- open?: () => void;
8
+ close?: () => void | Promise<void>;
9
+ open?: () => void | Promise<void>;
10
10
  after_restore?: (database: SqlDatabase) => void;
11
11
  after_staging?: () => void;
12
12
  }
@@ -33,14 +33,14 @@ export function sqlite_backups(options) {
33
33
  options.after_staging?.();
34
34
  return;
35
35
  }
36
- close();
36
+ await close();
37
37
  try {
38
38
  rmSync(`${target}-wal`, { force: true });
39
39
  rmSync(`${target}-shm`, { force: true });
40
40
  copyFileSync(source, target);
41
41
  }
42
42
  finally {
43
- open();
43
+ await open();
44
44
  }
45
45
  options.after_restore?.(options.database());
46
46
  };
@@ -0,0 +1,3 @@
1
+ import type { Viewer } from "./account_sign_in.ts";
2
+ export declare function with_viewer<Result>(viewer: Viewer | null | undefined, work: () => Result): Result;
3
+ export declare function current_viewer(): Viewer | null;
@@ -0,0 +1,14 @@
1
+ // Who a request a host answers came from, kept across the call's awaits, so work a route hands off, such as an app's
2
+ // host table call, can name who asked in its audit log or refuse what they may not do.
3
+ // ── Imports ──────────────────────────────────────────────────────────────────
4
+ import { AsyncLocalStorage } from "node:async_hooks";
5
+ // ── Scope ────────────────────────────────────────────────────────────────────
6
+ const storage = new AsyncLocalStorage();
7
+ // Runs the work with the viewer given as the one asking.
8
+ export function with_viewer(viewer, work) {
9
+ return storage.run(viewer ?? null, work);
10
+ }
11
+ // The viewer of the request in hand, or null outside one or when nobody signed in, as on a daemon's own socket.
12
+ export function current_viewer() {
13
+ return storage.getStore() ?? null;
14
+ }
@@ -248,7 +248,7 @@ export function Shell({ brand, brand_icon, brand_logo, sections = [], views, act
248
248
  window.scrollTo(0, 0);
249
249
  main.current?.scrollTo?.(0, 0);
250
250
  }, [view_key]);
251
- return (_jsxs(_Fragment, { children: [_jsx("a", { className: "skip", href: "#main", children: labels.skip_to_content }), _jsxs("header", { className: "topbar", children: [_jsx("button", { ref: menu_button, className: "icon menu-button", "aria-label": labels.open_menu, "aria-expanded": menu_open, "aria-controls": "sidebar", onClick: () => set_menu_open(!menu_open), children: "\u2630" }), !(brand_in_sidebar && !logged_out) && _jsx("a", { href: brand_href, className: "brand", children: _jsx(BrandMark, { brand: brand, icon: brand_icon, logo: brand_logo }) }), !logged_out && tools, pane_open && !narrow && !logged_out && pane_head] }), _jsxs("div", { className: "layout", style: width === undefined ? undefined : { "--sidebar-width": `${width}px` }, children: [_jsxs(Sidebar, { ref: sidebar, id: "sidebar", className: "sidebar", "aria-label": views ? undefined : labels.main_navigation, children: [brand_in_sidebar && _jsx("a", { href: brand_href, className: "sidebar-brand", children: _jsx(BrandMark, { brand: brand, icon: brand_icon, logo: brand_logo }) }), views || has_content || folding ? (_jsxs("div", { className: "sidebar-content", children: [views && (_jsx("nav", { className: "sidebar-nav", "aria-label": labels.main_navigation, children: views.map((view) => (_jsx(RowLink, { href: view.href, current: view.id === active, icon: view.icon && _jsx(Icon, { icon: view.icon }), label: view.label }, view.id))) })), folding && _jsx(SectionTree, { sections: sections, active: active, active_item: active_item, pref_key: sections_pref, label: labels.main_navigation }), sidebar_content] })) : (_jsx("div", { className: "sidebar-links", children: sections.map((section) => (_jsx("a", { href: section.href, "data-section": section.id, className: section.id === active ? "active" : undefined, "aria-current": section.id === active ? "page" : undefined, children: section.label }, section.id))) })), _jsxs("div", { className: "sidebar-foot", children: [sidebar_foot, _jsx(ThemeRow, { choice: theme, labels: labels }), user_name !== undefined && (_jsxs("div", { className: "sidebar-account", children: [user_href
251
+ return (_jsxs(_Fragment, { children: [_jsx("a", { className: "skip", href: "#main", children: labels.skip_to_content }), _jsxs("header", { className: "topbar", children: [_jsx("button", { ref: menu_button, className: "icon menu-button", "aria-label": labels.open_menu, "aria-expanded": menu_open, "aria-controls": "sidebar", onClick: () => set_menu_open(!menu_open), children: "\u2630" }), !(brand_in_sidebar && !logged_out) && _jsx("a", { href: brand_href, className: "brand", children: _jsx(BrandMark, { brand: brand, icon: brand_icon, logo: brand_logo }) }), !logged_out && tools, pane_open && !narrow && !logged_out && pane_head] }), _jsxs("div", { className: "layout", style: width === undefined ? undefined : { "--sidebar-width": `${width}px` }, children: [_jsxs(Sidebar, { ref: sidebar, id: "sidebar", className: "sidebar", "aria-label": views ? undefined : labels.main_navigation, children: [brand_in_sidebar && _jsx("a", { href: brand_href, className: "sidebar-brand", children: _jsx(BrandMark, { brand: brand, icon: brand_icon, logo: brand_logo }) }), views || has_content || folding ? (_jsxs("div", { className: "sidebar-content", children: [views && (_jsx("nav", { className: "sidebar-nav", "aria-label": labels.main_navigation, children: views.map((view) => (_jsx(RowLink, { href: view.href, current: view.id === active, icon: view.icon && _jsx(Icon, { icon: view.icon }), label: view.label }, view.id))) })), folding && _jsx(SectionTree, { sections: sections, active: active, active_item: active_item, pref_key: sections_pref, label: labels.main_navigation }), sidebar_content] })) : (_jsx("div", { className: "sidebar-links", children: sections.map((section) => (_jsx("a", { href: section.href, "data-section": section.id, className: section.id === active ? "active" : undefined, "aria-current": section.id === active ? "page" : undefined, children: section.label }, section.id))) })), _jsxs("div", { className: "sidebar-foot", children: [sidebar_foot, !theme.pinned && _jsx(ThemeRow, { choice: theme, labels: labels }), user_name !== undefined && (_jsxs("div", { className: "sidebar-account", children: [user_href
252
252
  ? _jsx(RowLink, { href: user_href, current: location.hash === user_href, icon: _jsx(PersonIcon, {}), label: user_name })
253
253
  : _jsx("span", { className: "tree-row", children: _jsxs("span", { className: "tree-label", children: [_jsx(PersonIcon, {}), _jsx("span", { className: "user-name", children: user_name })] }) }), on_logout && _jsx("button", { className: "tree-row", onClick: on_logout, children: labels.sign_out })] })), settings && _jsx(RowLink, { href: settings.href, current: settings.active ?? active === "settings", icon: _jsx(CogIcon, {}), label: labels.settings, on_open: settings.on_open })] }), sidebar_width && width !== undefined && (_jsx(ResizeHandle, { side: "left", size: width, min: sidebar_width.min, max: sidebar_width.max, default_size: sidebar_width.default_width, on_resize: (next) => change_width(next, false), on_resize_end: (next) => change_width(next, true), label: labels.resize_sidebar, class_name: "sidebar-resize" }))] }), _jsx("div", { className: "scrim", hidden: !menu_open, onClick: () => set_menu_open(false) }), side_pane ? (_jsxs("main", { ref: main, id: "main", className: [main_class, "with-side-pane"].filter(Boolean).join(" "), tabIndex: -1,
254
254
  // Closed, the pane's column takes no room, so main's children keep their place and their state.
@@ -4,6 +4,7 @@ export interface ThemeChoice {
4
4
  set(theme: Theme): void;
5
5
  on_change(listener: (theme: Theme) => void): () => void;
6
6
  apply(theme?: Theme): void;
7
+ readonly pinned?: boolean;
7
8
  }
8
9
  export interface ThemeStorage {
9
10
  read(): Theme | undefined;
@@ -13,3 +14,10 @@ export declare function local_theme_storage(storage_key: string): ThemeStorage;
13
14
  export declare function theme_choice(where: string | ThemeStorage): ThemeChoice;
14
15
  export declare function next_theme(theme: Theme): Theme;
15
16
  export declare function follow_host_theme(): boolean;
17
+ export interface ServerTheme {
18
+ scheme: Theme | null;
19
+ colors: Record<string, string>;
20
+ }
21
+ export declare function read_server_theme(value: unknown): ServerTheme;
22
+ export declare function pinned_theme_choice(theme: Theme): ThemeChoice;
23
+ export declare function apply_theme_colors(colors: Readonly<Record<string, string>>, root?: HTMLElement): void;
package/dist/web/theme.js CHANGED
@@ -56,3 +56,26 @@ export function follow_host_theme() {
56
56
  document.documentElement.classList.toggle("follows-host-theme", is_hosted);
57
57
  return is_hosted;
58
58
  }
59
+ const token_name = /^[a-z][a-z0-9-]*$/;
60
+ // The config's theme block as a server theme, leaving out what is not a scheme, a token name or a colour.
61
+ export function read_server_theme(value) {
62
+ const block = typeof value === "object" && value !== null ? value : {};
63
+ const scheme = block.scheme === "light" || block.scheme === "dark" || block.scheme === "system" ? block.scheme : null;
64
+ const colors = {};
65
+ if (typeof block.colors === "object" && block.colors !== null) {
66
+ for (const [name, color] of Object.entries(block.colors)) {
67
+ if (token_name.test(name) && typeof color === "string" && /^[#a-zA-Z0-9(),.%\s-]+$/.test(color))
68
+ colors[name] = color.trim();
69
+ }
70
+ }
71
+ return { scheme, colors };
72
+ }
73
+ // The scheme the server pins, which a pick does not change, so the page shows that scheme alone and no theme switch.
74
+ export function pinned_theme_choice(theme) {
75
+ return { ...theme_choice({ read: () => (theme === "system" ? undefined : theme), write: () => undefined }), pinned: true };
76
+ }
77
+ // Sets the server's colours on the page's root, where they win over both schemes' tokens.
78
+ export function apply_theme_colors(colors, root = document.documentElement) {
79
+ for (const [name, color] of Object.entries(colors))
80
+ root.style.setProperty(`--${name}`, color);
81
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.121.0",
3
+ "version": "0.122.0",
4
4
  "description": "Code the X-apps share: agents and their long runs, passwords and sign-in, the Fastify server pieces, durations, and the web page's helpers and widgets",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {