@x-tech-laboratories/x-app 0.121.0 → 0.123.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,16 +9,16 @@ 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
- | `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. |
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, worked out with `call(method)` or a host table's `call("<table>/<call>")`, 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. |
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. |
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, Backups and Import and export, the settings as a file) 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); its `use_items` hook gives rows worked out as the page runs, such as each paired device, folding open under it onto `#/devices/<id>` with the title "Pixel · Devices"; 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
+ | `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, and reaching what else `flatpak_permissions` names, such as `--system-talk-name=org.bluez`. |
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. |
24
24
  | `durations` | `parse_duration` for settings such as `"2h30m"`, `format_duration` in months down to seconds and "less than a second" below one, `format_age`, and `format_clock` for a playing time such as `"3:07"`, with `{ hours: "always" }` writing `"0:03:07"` so a column of times lines up and `empty` for no time. |
@@ -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.; `on_host: true` runs the computer's own program from inside a Flatpak through `flatpak-spawn --host` (`host_argv`, `in_flatpak`), which the Flatpak needs `--talk-name=org.freedesktop.Flatpak` for. |
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. |
@@ -252,9 +254,14 @@ An app whose work needs a computer, such as one that runs programs on checkouts,
252
254
  - **Host tables**: `host_tables: { stages: { hosts: ["server", "desktop"], api: stages_api } }` names calls the hosts
253
255
  answer themselves; the services return `tables: { stages: { methods, elsewhere } }`. The page reaches them with
254
256
  `host_table("stages")`, null where the host it works on does not answer them or does not let its viewer.
255
- - **Notices**: `context.notify({ kind, title, body, key, url })` from the services; the desktop daemon shows it where
256
- `notify_<kind>` in `desktop_settings` is on, and every window and phone working on that host from elsewhere shows it
257
- by its own switch.
257
+ - **Notices**: `context.notify({ kind, title, body, key, url, urgency })` from the services; the desktop daemon shows it
258
+ where `notify_<kind>` in `desktop_settings` is on, and every window and phone working on that host from elsewhere
259
+ shows it by its own switch. The server sends it through the channels its config's `notify_channels` lists (ntfy,
260
+ webhook, mail or Apprise). `context.withdraw(key)` takes it back wherever it shows, such as a call that stopped ringing.
261
+ - **Following changes**: the services' `after_change(change)` runs after every change the pages hear of, whoever made
262
+ it, with the synced tables written when known, such as to follow a setting; `after_remote_change` runs only for sync's.
263
+ - **Plugins**: the services load `context.plugins_folder`; on the server the page loads the plugins' web sides from
264
+ `/api/plugins/index.json`.
258
265
  - **Other devices**: `remote_access: true` lets the daemon serve its calls and host tables on the network, and
259
266
  `phone: "portal"` makes the phone a window onto a host chosen under Connections, keeping no data, its notices shown
260
267
  through `phone_notifications` (Capacitor's `LocalNotifications`).
@@ -275,7 +282,10 @@ The rest of an app's files are short calls into X-App too:
275
282
  An app with git dependencies names each lock entry's https URL in `git_dependencies`, which the packages fetch and
276
283
  copy in, and `link_scheme`, such as `"codex"`, makes the desktop entry open its links; `desktop_path`, such as
277
284
  `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
285
+ 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; `native_modules`, such as `[ "usocket" ]`, are built for Node in the server package and for Electron in the desktop one;
286
+ the module's `notifyChannels` and `settings` options add to that file, `settings` with keys of the machine's own,
287
+ winning over the module's, so an app's own module can set its keys from options of its own, its credentials and
288
+ firewall ports merging as in any module; the desktop wrapper sets
279
289
  `<PREFIX>_LAUNCHER` so the login entry runs the installed command. `android_emulator_shell nixpkgs system app` adds an
280
290
  Android 36 emulator to the Android shell, with `<name>-emulator` to start it and `<name>-emulator-install` to build
281
291
  and open the app on it, never on a connected phone.
@@ -12,6 +12,7 @@ export interface ProgramOptions {
12
12
  cwd?: string;
13
13
  signal?: AbortSignal;
14
14
  own_group?: boolean;
15
+ on_host?: boolean;
15
16
  }
16
17
  export interface ProgramResult {
17
18
  exit_code: number;
@@ -36,11 +37,14 @@ export declare function on_path(name: string): Promise<string | null>;
36
37
  export declare function whole_lines(sink: Sink): Sink & {
37
38
  flush(): void;
38
39
  };
40
+ export declare function in_flatpak(variables?: NodeJS.ProcessEnv): boolean;
41
+ export declare function host_argv(argv: readonly string[], cwd?: string, variables?: NodeJS.ProcessEnv): string[];
39
42
  export declare function run_program(argv: readonly string[], options?: ProgramOptions): Promise<ProgramResult>;
40
43
  export interface LineProgramOptions {
41
44
  cwd?: string;
42
45
  env?: NodeJS.ProcessEnv;
43
46
  signal?: AbortSignal;
47
+ on_host?: boolean;
44
48
  on_line: (line: string) => void;
45
49
  }
46
50
  export interface LineProgramExit {
@@ -90,6 +90,24 @@ export function whole_lines(sink) {
90
90
  },
91
91
  };
92
92
  }
93
+ // ── The computer's programs ──────────────────────────────────────────────────
94
+ // Whether this process runs in a Flatpak's sandbox, which has its own programs rather than the computer's.
95
+ export function in_flatpak(variables = process.env) {
96
+ return Boolean(variables.FLATPAK_ID);
97
+ }
98
+ // The command that runs a program on the computer itself: through flatpak-spawn --host from inside a Flatpak, in the
99
+ // folder given, which the Flatpak needs --talk-name=org.freedesktop.Flatpak for; the program as given otherwise.
100
+ export function host_argv(argv, cwd, variables = process.env) {
101
+ if (!in_flatpak(variables))
102
+ return [...argv];
103
+ return ["flatpak-spawn", "--host", "--watch-bus", ...(cwd ? [`--directory=${cwd}`] : []), ...argv];
104
+ }
105
+ // What to start, and where: the program as asked, or flatpak-spawn starting it on the computer, which takes the folder itself.
106
+ function spawned(argv, on_host, cwd) {
107
+ if (!on_host || !in_flatpak())
108
+ return { command: [...argv], cwd };
109
+ return { command: host_argv(argv, cwd), cwd: undefined };
110
+ }
93
111
  // ── Running ──────────────────────────────────────────────────────────────────
94
112
  // Runs the program to its end and never rejects: a program that cannot start answers 127 or -1 with why.
95
113
  export function run_program(argv, options = {}) {
@@ -100,11 +118,12 @@ export function run_program(argv, options = {}) {
100
118
  resolve({ exit_code: -1, stdout: "", stderr: "Stopped before it started" });
101
119
  return;
102
120
  }
103
- const child = spawn(argv[0], argv.slice(1), {
121
+ const start = spawned(argv, options.on_host, options.cwd);
122
+ const child = spawn(start.command[0], start.command.slice(1), {
104
123
  detached: options.own_group ?? false,
105
124
  stdio: [options.stdin == null ? "ignore" : "pipe", "pipe", "pipe"],
106
125
  env: options.env,
107
- cwd: options.cwd,
126
+ cwd: start.cwd,
108
127
  });
109
128
  if (options.stdin != null) {
110
129
  child.stdin.on("error", () => { });
@@ -142,7 +161,7 @@ export function run_program(argv, options = {}) {
142
161
  };
143
162
  child.on("error", (error) => {
144
163
  const missing = error.code === "ENOENT";
145
- const message = missing ? `${argv[0]} is not installed on this host` : `Could not start ${argv[0]}: ${error.message}`;
164
+ const message = missing ? `${start.command[0]} is not installed on this host` : `Could not start ${start.command[0]}: ${error.message}`;
146
165
  if (shows(stderr_use))
147
166
  options.err?.write(`${message}\n`);
148
167
  settle({ exit_code: missing ? not_installed_exit_code : -1, stdout: "", stderr: message });
@@ -158,7 +177,8 @@ export function run_program(argv, options = {}) {
158
177
  export function start_line_program(argv, options) {
159
178
  if (options.signal?.aborted)
160
179
  return { write_line: () => undefined, end_input: () => undefined, is_open: () => false, finished: Promise.resolve({ exit_code: -1, stderr: "Stopped before it started" }) };
161
- const child = spawn(argv[0], argv.slice(1), { detached: true, stdio: ["pipe", "pipe", "pipe"], env: options.env, cwd: options.cwd });
180
+ const start = spawned(argv, options.on_host, options.cwd);
181
+ const child = spawn(start.command[0], start.command.slice(1), { detached: true, stdio: ["pipe", "pipe", "pipe"], env: options.env, cwd: start.cwd });
162
182
  let open = true;
163
183
  child.stdin.on("error", () => (open = false));
164
184
  const stderr = new BoundedBuffer(stderr_limit_in_bytes);
@@ -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
+ }
@@ -14,6 +14,7 @@ export interface DaemonOptions {
14
14
  routes?: AppRoutes;
15
15
  web_folder?: string;
16
16
  show_notice?: (notice: AppNotice) => void;
17
+ withdraw_notice?: (key: string) => void;
17
18
  }
18
19
  export interface Daemon {
19
20
  shut_down: () => Promise<void>;
@@ -20,7 +20,7 @@ import { file_sync_storage } from "../sync_file_storage.js";
20
20
  import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
21
21
  import { keep_listening_for_peers } from "../sync_peer_listening.js";
22
22
  import { mcp_tools, register_host_tables } from "./host_tables.js";
23
- import { notice_event, notice_is_on, read_desktop_settings } from "./protocol.js";
23
+ import { notice_event, notice_withdrawn_event, notice_is_on, read_desktop_settings } from "./protocol.js";
24
24
  import { create_remote_access } from "./remote_access.js";
25
25
  import { declared_file_of, no_services, side_databases } from "./services.js";
26
26
  import { build_server, call_body_limit, data_change_text, open_app_database, register_app_calls, watch_outside_changes } from "./server.js";
@@ -33,10 +33,10 @@ export async function start_daemon(app, options) {
33
33
  const unused_check_ms = options.unused_check_ms ?? 5000;
34
34
  // Backed up before an upgrade, before another copy replaces it, and daily, beside the database.
35
35
  const opened = open_app_database(app, database_path, join(profile, "backups"));
36
- // Every window's event stream, told when the data changed or sync's status moved.
37
- const changes = new EventStream({ change_data: data_change_text(app, opened.database) });
38
- // The app's services once started, which answer its host tables and hear of sync's changes.
36
+ // The app's services once started, which answer its host tables and hear of every change.
39
37
  let services = no_services;
38
+ // Every window's event stream, told when the data changed or sync's status moved.
39
+ const changes = new EventStream({ change_data: data_change_text(app, opened.database, (change) => services.after_change?.(change)) });
40
40
  // Server certificates the user trusted, such as a home server's self-signed one, handed to Node's own fetch.
41
41
  const certificates = create_certificate_trust({ file: join(profile, "trusted-certificates.json"), use_in_node: true });
42
42
  // Off until "Let other devices connect" is turned on; then other devices reach this computer's sync on its port.
@@ -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({
@@ -89,7 +89,8 @@ export async function start_daemon(app, options) {
89
89
  : null;
90
90
  // ── Notices ────────────────────────────────────────────────────────
91
91
  const notifier = new Notifier({ app_name: app.name, icons: options.icon_path ? { app: options.icon_path } : {}, on_error: (message) => console.error(`${app.id} notifications: ${message}`) });
92
- const show_notice = options.show_notice ?? ((notice) => void notifier.show({ title: notice.title, body: notice.body, key: notice.key, ...(notice.url ? { url: notice.url } : {}), icon: "app" }));
92
+ const show_notice = options.show_notice ?? ((notice) => void notifier.show({ title: notice.title, body: notice.body, key: notice.key, urgency: notice.urgency ?? "normal", ...(notice.url ? { url: notice.url } : {}), icon: "app" }));
93
+ const withdraw_notice = options.withdraw_notice ?? ((key) => void notifier.dismiss({ key }));
93
94
  // Shown here where this computer's switch for its kind is on, and sent to every window, for those working on this
94
95
  // daemon from another computer to show there.
95
96
  function notify(notice) {
@@ -97,6 +98,11 @@ export async function start_daemon(app, options) {
97
98
  show_notice(notice);
98
99
  changes.send(JSON.stringify(notice), { event: notice_event });
99
100
  }
101
+ // Taken back here and in every window that showed it.
102
+ function withdraw(key) {
103
+ withdraw_notice(key);
104
+ changes.send(JSON.stringify(key), { event: notice_withdrawn_event });
105
+ }
100
106
  // ── Other devices ──────────────────────────────────────────────────
101
107
  // Accounts that sign other devices in are a file of their own beside the data, as on the server.
102
108
  const accounts_database = app.remote_access ? new DatabaseSync(join(profile, "accounts.db")) : null;
@@ -146,7 +152,7 @@ export async function start_daemon(app, options) {
146
152
  if (remote)
147
153
  register_call_table(api, "/remote", remote.methods, { is_read_only });
148
154
  // 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 };
155
+ const reach = { kind: "desktop", from_network: false, is_admin: () => true, has_role: () => true };
150
156
  register_host_tables(api, app, reach, services_now, changes);
151
157
  }, { prefix: "/api" });
152
158
  // ── Lifecycle ──────────────────────────────────────────────────────
@@ -193,6 +199,9 @@ export async function start_daemon(app, options) {
193
199
  profile,
194
200
  device_name: `${app.name} on ${hostname()}`,
195
201
  config: {},
202
+ config_file: null,
203
+ declared_tokens: () => [],
204
+ reread_declared_tokens: () => undefined,
196
205
  plugins_folder: join(profile, "plugins"),
197
206
  declared_file: options.declared_file ?? `/etc/${app.id}/declared.json`,
198
207
  announce: (client_id) => changes.announce_change(client_id),
@@ -206,10 +215,14 @@ export async function start_daemon(app, options) {
206
215
  window_in_front: () => window_in_front,
207
216
  icon_path: options.icon_path ?? null,
208
217
  notify,
218
+ withdraw,
209
219
  });
210
220
  }
211
221
  // 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()) });
222
+ opened.on_restore({ before: () => services.before_restore?.(), after: async () => {
223
+ await services.after_restore?.();
224
+ void remote?.restart();
225
+ } });
213
226
  await remote?.restart();
214
227
  // Without "Keep running in the background", the daemon stops a while after its last window has gone.
215
228
  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>;
@@ -117,6 +117,7 @@ export interface DesktopOptions {
117
117
  is_own_profile: boolean;
118
118
  }) => Record<string, string>;
119
119
  show_notice?: (notice: AppNotice) => void;
120
+ withdraw_notice?: (key: string) => void;
120
121
  }
121
122
  export declare function run_desktop(app: App, electron: ElectronLike, options: DesktopOptions): void;
122
123
  export {};
@@ -23,7 +23,7 @@ import { call_daemon, daemon_log_path, daemon_socket_path, start_daemon } from "
23
23
  import { peer_listening_method_names, sync_device_method_names } from "../sync_protocol.js";
24
24
  import { route_of_link } from "./links.js";
25
25
  import { remote_access_method_names } from "../remote_access_protocol.js";
26
- import { host_ability_method_names, notice_event, notice_is_on } from "./protocol.js";
26
+ import { host_ability_method_names, notice_event, notice_is_on, notice_withdrawn_event } from "./protocol.js";
27
27
  // The Save dialog's options for a file name: Downloads with that name, offering files of its kind.
28
28
  export function save_dialog_options(file_name, downloads) {
29
29
  const extension = extname(file_name).slice(1);
@@ -86,7 +86,8 @@ export function run_desktop(app, electron, options) {
86
86
  // A daemon elsewhere tells of its notices as events; this computer shows them by its own switches, as its own
87
87
  // daemon shows its own.
88
88
  const notifier = new Notifier({ app_name: app.name, icons: { app: icon_path }, on_error: (message) => console.error(`${app.id} notifications: ${message}`) });
89
- const show_notice = options.show_notice ?? ((notice) => void notifier.show({ title: notice.title, body: notice.body, key: notice.key, ...(notice.url ? { url: notice.url } : {}), icon: "app" }));
89
+ const show_notice = options.show_notice ?? ((notice) => void notifier.show({ title: notice.title, body: notice.body, key: notice.key, urgency: notice.urgency ?? "normal", ...(notice.url ? { url: notice.url } : {}), icon: "app" }));
90
+ const withdraw_notice = options.withdraw_notice ?? ((key) => void notifier.dismiss({ key }));
90
91
  async function notice_from_elsewhere(data) {
91
92
  if (router.is_here())
92
93
  return;
@@ -114,6 +115,8 @@ export function run_desktop(app, electron, options) {
114
115
  on_event: (event, data) => {
115
116
  if (event === notice_event)
116
117
  void notice_from_elsewhere(data).catch(() => undefined);
118
+ if (event === notice_withdrawn_event && !router.is_here())
119
+ withdraw_notice(JSON.parse(data));
117
120
  app.bridges.events.emit(windows(), "app_event", { event, data: data === "" ? null : JSON.parse(data) });
118
121
  },
119
122
  on_switch: () => {
@@ -188,8 +191,8 @@ export function run_desktop(app, electron, options) {
188
191
  // ── Tray ───────────────────────────────────────────────────────────
189
192
  // A write from a tray row reaches every window and the tray at once, as the daemon tells this process of no change it made.
190
193
  async function tray_call(method, args = []) {
191
- const result = await call(`call/${method}`, args);
192
- if (!app.is_read_only(method)) {
194
+ const result = await call(method.includes("/") ? method : `call/${method}`, args);
195
+ if (!app.is_read_only(method.slice(method.lastIndexOf("/") + 1))) {
193
196
  app.bridges.events.emit(windows(), "changed", null);
194
197
  void tray?.refresh();
195
198
  }
@@ -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;
@@ -56,8 +57,10 @@ export interface AppNotice {
56
57
  body: string;
57
58
  key: string;
58
59
  url: string;
60
+ urgency?: "low" | "normal" | "critical";
59
61
  }
60
62
  export declare const notice_event = "notice";
63
+ export declare const notice_withdrawn_event = "notice_withdrawn";
61
64
  export declare function notice_is_on(kind: string, switches: Readonly<Record<string, boolean>>): boolean;
62
65
  export type Host = "web" | "desktop" | "android";
63
66
  export interface BackupFolder {
@@ -84,6 +87,7 @@ export interface PageApi<Methods extends Record<keyof Methods, (...args: never[]
84
87
  set: (key: string, on: boolean) => Promise<void>;
85
88
  };
86
89
  reread_abilities?: () => Promise<Pick<PageApi, "admin" | "tables">>;
90
+ server_theme?: ServerTheme;
87
91
  on_change: (listener: (change: DataChange | null) => void) => () => void;
88
92
  on_event?: (event: string, listener: (data: unknown) => void) => () => void;
89
93
  }
@@ -16,6 +16,8 @@ export const desktop_method_names = ["get_desktop_settings", "set_desktop_settin
16
16
  export const host_ability_method_names = ["get_host_abilities"];
17
17
  // The named event a host sends its pages with each notice.
18
18
  export const notice_event = "notice";
19
+ // The named event a host sends its pages when a notice is taken back, its data the notice's key.
20
+ export const notice_withdrawn_event = "notice_withdrawn";
19
21
  // Whether this device shows a notice of the kind given: its switch, where the app has one, or always.
20
22
  export function notice_is_on(kind, switches) {
21
23
  return switches[`notify_${kind}`] ?? true;