@x-tech-laboratories/x-app 0.122.0 → 0.124.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 +24 -9
- package/dist/agent/programs.d.ts +4 -0
- package/dist/agent/programs.js +24 -4
- package/dist/app/daemon.d.ts +1 -0
- package/dist/app/daemon.js +12 -5
- package/dist/app/define.d.ts +8 -1
- package/dist/app/define.js +15 -2
- package/dist/app/desktop.d.ts +1 -0
- package/dist/app/desktop.js +7 -4
- package/dist/app/host_tables.d.ts +1 -1
- package/dist/app/host_tables.js +24 -3
- package/dist/app/protocol.d.ts +2 -0
- package/dist/app/protocol.js +2 -0
- package/dist/app/server.d.ts +9 -2
- package/dist/app/server.js +76 -17
- package/dist/app/services.d.ts +4 -1
- package/dist/app/web/app_page.js +15 -10
- package/dist/app/web/portal.d.ts +1 -0
- package/dist/app/web/portal.js +12 -1
- package/dist/app/web/settings_page.d.ts +2 -0
- package/dist/app/web/settings_page.js +20 -1
- package/dist/config/electron_builder.d.ts +1 -0
- package/dist/config/electron_builder.js +1 -0
- package/dist/phone_notices.d.ts +7 -0
- package/dist/server/canonical_paths.d.ts +3 -0
- package/dist/server/canonical_paths.js +54 -0
- package/dist/server/mcp.js +2 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,15 +10,15 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
|
|
|
10
10
|
| Import | What it holds |
|
|
11
11
|
| ---------------------------------------- | ----------------------------------------------------------------------------- |
|
|
12
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. |
|
|
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, route)`, what a route of its own needs of the one asking, such as an operator's role, null for a path it does not own. The config's `second_factor_from` names the role that must set up a second factor before it changes anything and `token_days` the longest a token lasts. Every server refuses a path spelled two ways (`server/canonical_paths`) and a body that is not JSON and trusts a reverse proxy on this machine for the visitor's address; an app with `security_headers` (true, or `server/security_headers`' options) sends them on every answer. MCP offers an admin `list_backups`, `create_backup` and `get_backup_schedule` (`backup_tools`). |
|
|
14
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
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
|
|
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 its `title(parts)` names the window for its route, such as "Job 12"; 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,7 +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
|
+
| `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. |
|
|
95
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`. |
|
|
96
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`. |
|
|
97
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`. |
|
|
@@ -136,6 +136,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
|
|
|
136
136
|
| `server/events` | `EventStream`: server-sent events with a client id per page, a heartbeat, `announce_change(except_client_id)` so the page that made a change is not told, nameless or named events to all or chosen clients, headers set before the stream opens (such as `register_open_cors`'s) sent with it, and every stream ended with the app; `leading_cooldown` sends the first change at once and a burst's rest once per cooldown. |
|
|
137
137
|
| `server/call_table` | `register_call_table`: a table of calls served as POST `<path>/<method>` with the arguments as a JSON list, as a desktop app's daemon and a web server both answer them, and by name as a JSON object for the calls whose argument names `params` gives, such as the app's `api_spec` (`api_spec`'s `NamedParams` is all it needs); a name the table lacks (its prototype's included) is refused, every answer goes as JSON so a string stays a string, a read is sent uncached, and `on_change` runs after any call `is_read_only` does not pass, with the caller's client id. |
|
|
138
138
|
| `server/leases` | `Leases`: what a page holds open while it shows something costly, such as fast polling of a running job while its log is open, each lease ending when closed or once it goes unrenewed for a while. |
|
|
139
|
+
| `server/canonical_paths` | `register_canonical_paths`: a path the router would read differently from how it is spelled (an escape of a character that needs none, a dot or empty segment, a lower-case or non-UTF-8 escape, `;`, `#` or `\`) is refused with 400 before sign-in or any route sees it, so the sign-in guard and the router always see the same route (`path_refusal`); it refuses to start on a router that ignores case or slashes. |
|
|
139
140
|
| `server/security_headers` | `register_security_headers`: every answer carries a content security policy that runs only the app's own scripts (`default_content_security_policy`, with directives the app replaces through `content_security_policy`, or none with null), `X-Frame-Options` and `frame-ancestors` refusing framing unless `allow_same_origin_frames`, `nosniff`, a same-origin referrer policy and opener policy; headers a route sets itself are kept. |
|
|
140
141
|
| `server/web_folder` | `register_web_folder`: the built page from a folder, tuned for the Nix store (no etag or date, hashed `/assets/` kept a year, the page fetched fresh), a warning, error or nothing when the folder is missing, and the page for unknown paths when it routes itself. |
|
|
141
142
|
| `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`. |
|
|
@@ -247,6 +248,8 @@ run_preload(app, { contextBridge, ipcRenderer });
|
|
|
247
248
|
void render_app({ app, pages: [{ id: "plan", label: "Plan", view: () => <PlanView />, settings: plan_settings }], general_settings: money_section });
|
|
248
249
|
```
|
|
249
250
|
|
|
251
|
+
Each backup is named `<backup_prefix>-<time>.db`, or with the `backup_suffix` given, such as `.sqlite` where an app's older backups were named so.
|
|
252
|
+
|
|
250
253
|
A change an app needs in the base goes into the base, so no app keeps a copy of a base file.
|
|
251
254
|
|
|
252
255
|
An app whose work needs a computer, such as one that runs programs on checkouts, adds to that:
|
|
@@ -254,9 +257,18 @@ An app whose work needs a computer, such as one that runs programs on checkouts,
|
|
|
254
257
|
- **Host tables**: `host_tables: { stages: { hosts: ["server", "desktop"], api: stages_api } }` names calls the hosts
|
|
255
258
|
answer themselves; the services return `tables: { stages: { methods, elsewhere } }`. The page reaches them with
|
|
256
259
|
`host_table("stages")`, null where the host it works on does not answer them or does not let its viewer.
|
|
257
|
-
- **
|
|
258
|
-
|
|
259
|
-
|
|
260
|
+
- **Route tables**: a REST app's routes as a host table, `{ hosts: ["server"], routes: true, api }`, each spec naming
|
|
261
|
+
its route, such as `{ route: "GET /api/hosts/:name", description, params }`: a call runs its route inside the server
|
|
262
|
+
as the one asking, so the route's own rule (`routes.needed`) decides, a GET only reads, and a refusal comes back in
|
|
263
|
+
the route's own words and status; MCP offers them the same way, and OpenAPI documents them as their routes.
|
|
264
|
+
- **Notices**: `context.notify({ kind, title, body, key, url, urgency })` from the services; the desktop daemon shows it
|
|
265
|
+
where `notify_<kind>` in `desktop_settings` is on, and every window and phone working on that host from elsewhere
|
|
266
|
+
shows it by its own switch. The server sends it through the channels its config's `notify_channels` lists (ntfy,
|
|
267
|
+
webhook, mail or Apprise). `context.withdraw(key)` takes it back wherever it shows, such as a call that stopped ringing.
|
|
268
|
+
- **Following changes**: the services' `after_change(change)` runs after every change the pages hear of, whoever made
|
|
269
|
+
it, with the synced tables written when known, such as to follow a setting; `after_remote_change` runs only for sync's.
|
|
270
|
+
- **Plugins**: the services load `context.plugins_folder`; on the server the page loads the plugins' web sides from
|
|
271
|
+
`/api/plugins/index.json`.
|
|
260
272
|
- **Other devices**: `remote_access: true` lets the daemon serve its calls and host tables on the network, and
|
|
261
273
|
`phone: "portal"` makes the phone a window onto a host chosen under Connections, keeping no data, its notices shown
|
|
262
274
|
through `phone_notifications` (Capacitor's `LocalNotifications`).
|
|
@@ -277,7 +289,10 @@ The rest of an app's files are short calls into X-App too:
|
|
|
277
289
|
An app with git dependencies names each lock entry's https URL in `git_dependencies`, which the packages fetch and
|
|
278
290
|
copy in, and `link_scheme`, such as `"codex"`, makes the desktop entry open its links; `desktop_path`, such as
|
|
279
291
|
`pkgs: [ pkgs.libnotify ]`, puts programs the desktop app runs on its PATH, and `state_name` keeps an older service's
|
|
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;
|
|
292
|
+
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;
|
|
293
|
+
the module's `notifyChannels` and `settings` options add to that file, `settings` with keys of the machine's own,
|
|
294
|
+
winning over the module's, so an app's own module can set its keys from options of its own, its credentials and
|
|
295
|
+
firewall ports merging as in any module; the desktop wrapper sets
|
|
281
296
|
`<PREFIX>_LAUNCHER` so the login entry runs the installed command. `android_emulator_shell nixpkgs system app` adds an
|
|
282
297
|
Android 36 emulator to the Android shell, with `<name>-emulator` to start it and `<name>-emulator-install` to build
|
|
283
298
|
and open the app on it, never on a connected phone.
|
package/dist/agent/programs.d.ts
CHANGED
|
@@ -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 {
|
package/dist/agent/programs.js
CHANGED
|
@@ -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
|
|
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:
|
|
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 ? `${
|
|
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
|
|
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);
|
package/dist/app/daemon.d.ts
CHANGED
package/dist/app/daemon.js
CHANGED
|
@@ -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
|
-
//
|
|
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.
|
|
@@ -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;
|
|
@@ -209,6 +215,7 @@ export async function start_daemon(app, options) {
|
|
|
209
215
|
window_in_front: () => window_in_front,
|
|
210
216
|
icon_path: options.icon_path ?? null,
|
|
211
217
|
notify,
|
|
218
|
+
withdraw,
|
|
212
219
|
});
|
|
213
220
|
}
|
|
214
221
|
// Devices signed in from elsewhere follow the restored data too.
|
package/dist/app/define.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { type MigrationStep, type SqlDatabase } from "../sql.ts";
|
|
|
14
14
|
import { type SyncedTable } from "../sync_engine.ts";
|
|
15
15
|
import { type PeerListeningMethods, type SyncDeviceMethods, type SyncStatus } from "../sync_protocol.ts";
|
|
16
16
|
import { type RemoteAccessMethods } from "../remote_access_protocol.ts";
|
|
17
|
+
import type { SecurityHeadersOptions } from "../server/security_headers.ts";
|
|
17
18
|
import { type DataChange, type DesktopMethods, type DesktopSettingSpec, type HostAbilityMethods } from "./protocol.ts";
|
|
18
19
|
export type StoreMethod = (database: SqlDatabase, ...args: never[]) => unknown;
|
|
19
20
|
export type KeptHistory = Pick<History<unknown>, "synced_table" | "install" | "forget_touched" | "record" | "prune"> & Partial<Pick<History<unknown>, "drop_triggers">>;
|
|
@@ -36,7 +37,9 @@ export interface HostTable<Methods = Record<string, (...args: never[]) => unknow
|
|
|
36
37
|
hosts: readonly HostKind[];
|
|
37
38
|
network?: "admin" | "any" | "none";
|
|
38
39
|
needs?: (method: string) => string | null | undefined;
|
|
40
|
+
routes?: boolean;
|
|
39
41
|
}
|
|
42
|
+
export declare function route_of(table: HostTable, method: string): string | null;
|
|
40
43
|
declare const host_table_route: (name: string) => string;
|
|
41
44
|
type UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends (value: infer Both) => void ? Both : never;
|
|
42
45
|
type Bound<Methods> = {
|
|
@@ -54,6 +57,7 @@ export interface AppOptions<Features extends readonly Feature[]> {
|
|
|
54
57
|
data_name: string;
|
|
55
58
|
database_file: string;
|
|
56
59
|
backup_prefix: string;
|
|
60
|
+
backup_suffix?: string;
|
|
57
61
|
ports: {
|
|
58
62
|
server: number;
|
|
59
63
|
peer: number;
|
|
@@ -88,6 +92,7 @@ export interface AppOptions<Features extends readonly Feature[]> {
|
|
|
88
92
|
scopes: Record<string, ScopeSpec>;
|
|
89
93
|
limit_key?: string;
|
|
90
94
|
};
|
|
95
|
+
security_headers?: boolean | SecurityHeadersOptions;
|
|
91
96
|
}
|
|
92
97
|
export declare const base_setting_defaults: {
|
|
93
98
|
history_days: number;
|
|
@@ -130,6 +135,7 @@ export declare function define_app<const Features extends readonly Feature[]>(op
|
|
|
130
135
|
data_name: string;
|
|
131
136
|
database_file: string;
|
|
132
137
|
backup_prefix: string;
|
|
138
|
+
backup_suffix?: string;
|
|
133
139
|
ports: {
|
|
134
140
|
server: number;
|
|
135
141
|
peer: number;
|
|
@@ -162,6 +168,7 @@ export declare function define_app<const Features extends readonly Feature[]>(op
|
|
|
162
168
|
scopes: Record<string, ScopeSpec>;
|
|
163
169
|
limit_key?: string;
|
|
164
170
|
};
|
|
171
|
+
security_headers?: boolean | SecurityHeadersOptions;
|
|
165
172
|
features: readonly Feature<Record<string, StoreMethod>>[];
|
|
166
173
|
settings_store: SettingsStore;
|
|
167
174
|
setting_defaults: Readonly<import("../settings.ts").Settings>;
|
|
@@ -193,7 +200,7 @@ export declare function define_app<const Features extends readonly Feature[]>(op
|
|
|
193
200
|
open_store: (database: SqlDatabase) => void;
|
|
194
201
|
method_names: ((keyof UnionToIntersection<Features[number]["methods"]> | keyof SettingsMethods) & string)[];
|
|
195
202
|
api_spec: ApiSpec<Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>>;
|
|
196
|
-
is_read_only:
|
|
203
|
+
is_read_only: (method: string) => boolean;
|
|
197
204
|
page_only: PageOnlyCalls;
|
|
198
205
|
bind_methods: (database: () => SqlDatabase, on_change: () => void, caller?: Caller) => Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>;
|
|
199
206
|
record_writes: (database: SqlDatabase) => void;
|
package/dist/app/define.js
CHANGED
|
@@ -25,6 +25,13 @@ export function define_feature(feature) {
|
|
|
25
25
|
export function is_read_only(method) {
|
|
26
26
|
return /^(list|get|search|lookup|export)_/.test(method);
|
|
27
27
|
}
|
|
28
|
+
// The route a call of a route table runs, such as "GET /api/hosts/:name", or null for a call no route answers.
|
|
29
|
+
export function route_of(table, method) {
|
|
30
|
+
if (!table.routes)
|
|
31
|
+
return null;
|
|
32
|
+
const route = table.api[method]?.route;
|
|
33
|
+
return typeof route === "string" ? route : null;
|
|
34
|
+
}
|
|
28
35
|
// The path a host table's calls are posted under, such as /api/stages/.
|
|
29
36
|
const host_table_route = (name) => `/api/${name}/`;
|
|
30
37
|
// The settings every app keeps: how long its history reaches back, and this device's backup schedule.
|
|
@@ -193,7 +200,7 @@ export function define_app(options) {
|
|
|
193
200
|
};
|
|
194
201
|
// ── Backups ──────────────────────────────────────────────────────────
|
|
195
202
|
// Names such as budget-2026-06-10T09-30-00Z-auto.db.
|
|
196
|
-
const naming = backup_naming(options.backup_prefix, ".db");
|
|
203
|
+
const naming = backup_naming(options.backup_prefix, options.backup_suffix ?? ".db");
|
|
197
204
|
// This device's schedule, kept in a settings row that never syncs.
|
|
198
205
|
function read_backup_schedule(database) {
|
|
199
206
|
const stored = read_setting(database, backup_schedule_key);
|
|
@@ -254,6 +261,12 @@ export function define_app(options) {
|
|
|
254
261
|
.filter(([, table]) => table.hosts.includes(kind) && !(from_network && table.network === "none"))
|
|
255
262
|
.map(([name]) => name);
|
|
256
263
|
}
|
|
264
|
+
// A route table's call only reads when its route is a GET; any other call by its name.
|
|
265
|
+
const route_reads = new Map(Object.values(host_tables).flatMap((table) => Object.keys(table.api).flatMap((method) => {
|
|
266
|
+
const route = route_of(table, method);
|
|
267
|
+
return route === null ? [] : [[method, route.startsWith("GET ")]];
|
|
268
|
+
})));
|
|
269
|
+
const app_is_read_only = (method) => route_reads.get(method) ?? is_read_only(method);
|
|
257
270
|
// The table one of the host tables' calls belongs to, or null for any other call.
|
|
258
271
|
function table_of_call(method, kind) {
|
|
259
272
|
return tables_on(kind, true).find((name) => Object.hasOwn(host_tables[name].api, method)) ?? null;
|
|
@@ -269,7 +282,7 @@ export function define_app(options) {
|
|
|
269
282
|
open_store,
|
|
270
283
|
method_names,
|
|
271
284
|
api_spec,
|
|
272
|
-
is_read_only,
|
|
285
|
+
is_read_only: app_is_read_only,
|
|
273
286
|
page_only,
|
|
274
287
|
bind_methods,
|
|
275
288
|
record_writes,
|
package/dist/app/desktop.d.ts
CHANGED
|
@@ -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 {};
|
package/dist/app/desktop.js
CHANGED
|
@@ -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
|
}
|
|
@@ -2,7 +2,7 @@ import type { FastifyInstance, FastifyRequest } from "fastify";
|
|
|
2
2
|
import { type ApiSpec } from "../api_spec.ts";
|
|
3
3
|
import type { EventStream } from "../server/events.ts";
|
|
4
4
|
import type { SqlDatabase } from "../sql.ts";
|
|
5
|
-
import type
|
|
5
|
+
import { type App, type HostKind } from "./define.ts";
|
|
6
6
|
import type { HostAbilities } from "./protocol.ts";
|
|
7
7
|
import type { HostServices } from "./services.ts";
|
|
8
8
|
export interface HostReach {
|
package/dist/app/host_tables.js
CHANGED
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
// services handed in once they started, the network and MCP reaching only the tables and calls they may, and the
|
|
3
3
|
// tools MCP offers being the data calls and those tables together.
|
|
4
4
|
import { positional_args } from "../api_spec.js";
|
|
5
|
+
import { route_tools } from "../server/mcp.js";
|
|
5
6
|
import { send_text } from "../server/replies.js";
|
|
6
7
|
import { with_viewer } from "../server/viewer_scope.js";
|
|
8
|
+
import { route_of } from "./define.js";
|
|
7
9
|
// 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
10
|
function role_refusal(table, reach, method, request) {
|
|
9
11
|
const role = table.needs?.(method);
|
|
@@ -11,6 +13,11 @@ function role_refusal(table, reach, method, request) {
|
|
|
11
13
|
return null;
|
|
12
14
|
return `${method} needs the ${role} role.`;
|
|
13
15
|
}
|
|
16
|
+
// Runs a route table's call as its route, inside the server, as the one asking, so their sign-in and the route's own
|
|
17
|
+
// rules decide as they would for the page's request.
|
|
18
|
+
function run_route(table, method, args, request) {
|
|
19
|
+
return route_tools(request.server, table.api).call(method, args, request);
|
|
20
|
+
}
|
|
14
21
|
// The tables the one asking may reach on this host, as the page reads them to know what it can offer.
|
|
15
22
|
export function host_abilities(app, reach, request) {
|
|
16
23
|
const admin = reach.is_admin(request);
|
|
@@ -41,8 +48,8 @@ export function register_host_tables(api, app, reach, services, changes) {
|
|
|
41
48
|
const refusal = reach.from_network ? role_refusal(table, reach, method, request) : null;
|
|
42
49
|
if (refusal)
|
|
43
50
|
return send_text(reply, 403, refusal);
|
|
44
|
-
const methods = served_methods(services, name, reach.from_network);
|
|
45
|
-
if (!methods || typeof methods[method] !== "function")
|
|
51
|
+
const methods = route_of(table, method) ? null : served_methods(services, name, reach.from_network);
|
|
52
|
+
if (!route_of(table, method) && (!methods || typeof methods[method] !== "function"))
|
|
46
53
|
return send_text(reply, 503, `${app.name} is still starting; try ${method} again in a moment.`);
|
|
47
54
|
const body = request.body ?? [];
|
|
48
55
|
let args;
|
|
@@ -58,7 +65,16 @@ export function register_host_tables(api, app, reach, services, changes) {
|
|
|
58
65
|
}
|
|
59
66
|
else
|
|
60
67
|
return send_text(reply, 400, "send the arguments as a JSON list or object");
|
|
61
|
-
|
|
68
|
+
let result;
|
|
69
|
+
try {
|
|
70
|
+
result = route_of(table, method) ? await run_route(table, method, args, request) : await with_viewer(request.viewer, () => methods[method](...args));
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
// A route's refusal comes back in its own words and status.
|
|
74
|
+
if (route_of(table, method))
|
|
75
|
+
return send_text(reply, error.status ?? 500, error.message);
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
62
78
|
const read_only = app.is_read_only(method);
|
|
63
79
|
if (!read_only)
|
|
64
80
|
changes.announce_change(changes.client_id_of(request));
|
|
@@ -86,6 +102,11 @@ export function mcp_tools(app, reach, services, database, announce) {
|
|
|
86
102
|
const refusal = role_refusal(app.host_tables[name], reach, method, request);
|
|
87
103
|
if (refusal)
|
|
88
104
|
throw new Error(refusal);
|
|
105
|
+
if (route_of(app.host_tables[name], method)) {
|
|
106
|
+
if (!request)
|
|
107
|
+
throw new Error(`${method} is answered only on the server.`);
|
|
108
|
+
return run_route(app.host_tables[name], method, args, request);
|
|
109
|
+
}
|
|
89
110
|
const methods = served_methods(services, name, true);
|
|
90
111
|
if (!methods || typeof methods[method] !== "function")
|
|
91
112
|
throw new Error(`${app.name} is still starting; try ${method} again in a moment.`);
|
package/dist/app/protocol.d.ts
CHANGED
|
@@ -57,8 +57,10 @@ export interface AppNotice {
|
|
|
57
57
|
body: string;
|
|
58
58
|
key: string;
|
|
59
59
|
url: string;
|
|
60
|
+
urgency?: "low" | "normal" | "critical";
|
|
60
61
|
}
|
|
61
62
|
export declare const notice_event = "notice";
|
|
63
|
+
export declare const notice_withdrawn_event = "notice_withdrawn";
|
|
62
64
|
export declare function notice_is_on(kind: string, switches: Readonly<Record<string, boolean>>): boolean;
|
|
63
65
|
export type Host = "web" | "desktop" | "android";
|
|
64
66
|
export interface BackupFolder {
|
package/dist/app/protocol.js
CHANGED
|
@@ -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;
|
package/dist/app/server.d.ts
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import { DatabaseSync } from "node:sqlite";
|
|
2
2
|
import { type FastifyInstance } from "fastify";
|
|
3
|
+
import { type MethodSpec } from "../api_spec.ts";
|
|
3
4
|
import { type BackupMethods } from "../backups.ts";
|
|
4
5
|
import { OidcClient } from "../server/oidc.ts";
|
|
5
6
|
import { AccountStore } from "../server/account_store.ts";
|
|
7
|
+
import { type Channel } from "../server/notify/channels.ts";
|
|
6
8
|
import { EventStream } from "../server/events.ts";
|
|
7
9
|
import { type SqlDatabase } from "../sql.ts";
|
|
8
10
|
import { type ServerTheme } from "../web/theme.ts";
|
|
9
11
|
import { type SyncPeer } from "../sync_peer.ts";
|
|
10
|
-
import
|
|
12
|
+
import { type DataChange } from "../sync_protocol.ts";
|
|
13
|
+
import { type App, type HostKind } from "./define.ts";
|
|
14
|
+
import { type AppNotice } from "./protocol.ts";
|
|
11
15
|
import { type AppRoutes, type HostServices, type StartServices } from "./services.ts";
|
|
12
16
|
export interface AppDatabase {
|
|
13
17
|
database: () => DatabaseSync;
|
|
@@ -20,7 +24,7 @@ export interface AppDatabase {
|
|
|
20
24
|
close: () => void;
|
|
21
25
|
}
|
|
22
26
|
export declare function open_app_database(app: App, path: string, backups_folder: string): AppDatabase;
|
|
23
|
-
export declare function data_change_text(app: Pick<App, "take_data_change">, database: () => SqlDatabase): () => string;
|
|
27
|
+
export declare function data_change_text(app: Pick<App, "take_data_change">, database: () => SqlDatabase, after?: (change: DataChange | null) => void): () => string;
|
|
24
28
|
export declare function watch_outside_changes(database: () => SqlDatabase, on_change: () => void, every_ms?: number): () => void;
|
|
25
29
|
export declare const call_body_limit: number;
|
|
26
30
|
export declare function call_args(app: App, method: string, body: unknown): unknown[];
|
|
@@ -44,9 +48,12 @@ export interface ServerOptions {
|
|
|
44
48
|
remembered_seconds?: number | null;
|
|
45
49
|
theme?: ServerTheme;
|
|
46
50
|
plugins_folder?: string | null;
|
|
51
|
+
second_factor_from?: string | null;
|
|
47
52
|
}
|
|
53
|
+
export declare const backup_tools: Record<"list_backups" | "create_backup" | "get_backup_schedule", MethodSpec>;
|
|
48
54
|
export declare const user_only_backup_calls: ReadonlySet<string>;
|
|
49
55
|
export declare function build_server(app: App, options: ServerOptions): Promise<FastifyInstance>;
|
|
56
|
+
export declare function notify_through(channels: readonly Channel[], notice: AppNotice): void;
|
|
50
57
|
export interface RunServerOptions {
|
|
51
58
|
web_folder: URL;
|
|
52
59
|
argv?: string[];
|
package/dist/app/server.js
CHANGED
|
@@ -8,7 +8,7 @@ import { dirname, join, resolve } from "node:path";
|
|
|
8
8
|
import { DatabaseSync } from "node:sqlite";
|
|
9
9
|
import { fileURLToPath } from "node:url";
|
|
10
10
|
import fastify, {} from "fastify";
|
|
11
|
-
import { openapi_document, positional_args } from "../api_spec.js";
|
|
11
|
+
import { openapi_document, positional_args, route_openapi_document } 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";
|
|
@@ -20,6 +20,9 @@ import { AccountStore, holds_accounts, move_accounts } from "../server/account_s
|
|
|
20
20
|
import { register_call_table } from "../server/call_table.js";
|
|
21
21
|
import { register_open_cors } from "../server/cors.js";
|
|
22
22
|
import { read_server_config } from "../server/config.js";
|
|
23
|
+
import { register_canonical_paths } from "../server/canonical_paths.js";
|
|
24
|
+
import { read_channels } from "../server/notify/channels.js";
|
|
25
|
+
import { register_security_headers } from "../server/security_headers.js";
|
|
23
26
|
import { EventStream } from "../server/events.js";
|
|
24
27
|
import { register_mcp_route } from "../server/mcp.js";
|
|
25
28
|
import { register_plugin_files } from "../server/plugin_files.js";
|
|
@@ -32,8 +35,10 @@ import { tidy_database, tidy_every_ms } from "../sql.js";
|
|
|
32
35
|
import { file_sync_storage } from "../sync_file_storage.js";
|
|
33
36
|
import { read_server_theme } from "../web/theme.js";
|
|
34
37
|
import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
|
|
38
|
+
import { data_change_of } from "../sync_protocol.js";
|
|
39
|
+
import { route_of } from "./define.js";
|
|
35
40
|
import { call_path_of, mcp_tools, register_host_tables } from "./host_tables.js";
|
|
36
|
-
import { notice_event } from "./protocol.js";
|
|
41
|
+
import { notice_event, notice_withdrawn_event } from "./protocol.js";
|
|
37
42
|
import { declared_file_of, no_services, side_databases } from "./services.js";
|
|
38
43
|
// The server and the daemon run on Node, so a call's caller holds across its awaits.
|
|
39
44
|
use_caller_scope(node_caller_scope());
|
|
@@ -110,15 +115,24 @@ function adopt_schedule_file(app, database, file) {
|
|
|
110
115
|
app.adopt_backup_schedule(database, saved);
|
|
111
116
|
rmSync(file, { force: true });
|
|
112
117
|
}
|
|
113
|
-
// What a change event carries: the tables written since the last one, or nothing when that cannot be told, as
|
|
114
|
-
|
|
118
|
+
// What a change event carries: the tables written since the last one, or nothing when that cannot be told, as
|
|
119
|
+
// mid-restore. after hears of each change as it is announced, such as the app's services following a setting.
|
|
120
|
+
export function data_change_text(app, database, after) {
|
|
115
121
|
return () => {
|
|
122
|
+
let text = "";
|
|
116
123
|
try {
|
|
117
|
-
|
|
124
|
+
text = JSON.stringify(app.take_data_change(database()));
|
|
118
125
|
}
|
|
119
126
|
catch {
|
|
120
|
-
|
|
127
|
+
text = "";
|
|
121
128
|
}
|
|
129
|
+
try {
|
|
130
|
+
after?.(data_change_of(text));
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
console.error(`after a change: ${error instanceof Error ? error.message : String(error)}`);
|
|
134
|
+
}
|
|
135
|
+
return text;
|
|
122
136
|
};
|
|
123
137
|
}
|
|
124
138
|
// Another program, such as an older build of the app, may write the database file; SQLite moves data_version only
|
|
@@ -184,13 +198,25 @@ export function register_app_calls(api, app, database, changes) {
|
|
|
184
198
|
return reply.send(JSON.stringify(result));
|
|
185
199
|
});
|
|
186
200
|
}
|
|
201
|
+
// The backup calls MCP offers an admin; restoring and removing stay with the user at the page.
|
|
202
|
+
export const backup_tools = {
|
|
203
|
+
list_backups: { description: "Lists the backups of the server's database, newest first.", params: [] },
|
|
204
|
+
create_backup: { description: "Backs up the server's database now, and answers with the new backup.", params: [] },
|
|
205
|
+
get_backup_schedule: { description: "Shows whether the server's database is backed up daily, and how many backups are kept.", params: [] },
|
|
206
|
+
};
|
|
187
207
|
// The server's backups and its sync peer's pairings, which only an admin reaches.
|
|
188
208
|
const admin_paths = ["/api/backups/", "/api/sync/"];
|
|
189
209
|
// Backup calls only the user at the page may make, since a restored backup could undo what only the user may change.
|
|
190
210
|
export const user_only_backup_calls = new Set(["restore_backup", "remove_backup", "set_backup_schedule"]);
|
|
191
211
|
export async function build_server(app, options) {
|
|
192
|
-
|
|
193
|
-
|
|
212
|
+
// A reverse proxy on this machine passes on the visitor's address and whether they came over https.
|
|
213
|
+
const server = fastify({ forceCloseConnections: true, trustProxy: ["127.0.0.1", "::1"], ...(options.https ? { https: options.https } : {}) });
|
|
214
|
+
// A path the router would read differently from how it is spelled is refused before sign-in or any route sees it.
|
|
215
|
+
register_canonical_paths(server);
|
|
216
|
+
if (app.security_headers)
|
|
217
|
+
register_security_headers(server, app.security_headers === true ? {} : app.security_headers);
|
|
218
|
+
// A body that is not JSON is refused before any route takes it for no arguments.
|
|
219
|
+
register_lenient_json_body(server, { refuse_bad_json: "text" });
|
|
194
220
|
register_error_replies(server);
|
|
195
221
|
const kind = options.kind ?? "server";
|
|
196
222
|
const services = options.services ?? (() => no_services);
|
|
@@ -203,6 +229,7 @@ export async function build_server(app, options) {
|
|
|
203
229
|
reply.raw.setHeader("access-control-allow-origin", "*");
|
|
204
230
|
});
|
|
205
231
|
}
|
|
232
|
+
const table_paths = app.tables_on(kind, true).map((name) => `/api/${name}/`);
|
|
206
233
|
const admin_tables = app.tables_on(kind, true).filter((name) => app.host_tables[name].network !== "any").map((name) => `/api/${name}/`);
|
|
207
234
|
const is_admin = (request) => request.viewer !== null && request.viewer !== undefined && options.accounts.has_role(request.viewer.role, options.accounts.top_role);
|
|
208
235
|
const has_role = (request, role) => request.viewer !== null && request.viewer !== undefined && options.accounts.has_role(request.viewer.role, role);
|
|
@@ -218,12 +245,16 @@ export async function build_server(app, options) {
|
|
|
218
245
|
oidc: options.oidc ?? null,
|
|
219
246
|
...(options.session_seconds !== undefined ? { session_seconds: options.session_seconds } : {}),
|
|
220
247
|
...(options.remembered_seconds !== undefined ? { remembered_seconds: options.remembered_seconds } : {}),
|
|
248
|
+
...(options.second_factor_from ? { second_factor_from: options.second_factor_from } : {}),
|
|
221
249
|
// A read-only token may still list and read through MCP, which posts every request.
|
|
222
250
|
read_only_paths: ["/api/mcp"],
|
|
223
|
-
needed: (method, path) => {
|
|
251
|
+
needed: (method, path, route) => {
|
|
224
252
|
if ([...admin_paths, ...admin_tables].some((admin_path) => path.startsWith(admin_path)))
|
|
225
253
|
return { role: options.accounts.top_role };
|
|
226
|
-
|
|
254
|
+
// A host table's calls follow its own reach, and a route table's each run its route, which the app's rule checks.
|
|
255
|
+
if (table_paths.some((table_path) => path.startsWith(table_path)))
|
|
256
|
+
return "any";
|
|
257
|
+
return options.routes?.needed?.(method, path, route) ?? "any";
|
|
227
258
|
},
|
|
228
259
|
// 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.
|
|
229
260
|
call_of: calls_under("/api/call"),
|
|
@@ -235,20 +266,33 @@ export async function build_server(app, options) {
|
|
|
235
266
|
// A change made through MCP is announced to every page, since no page made it.
|
|
236
267
|
const tools = mcp_tools(app, reach, services, database, () => changes.announce_change());
|
|
237
268
|
const documented = Object.assign({}, app.api_spec, ...app.tables_on(kind, true).map((name) => app.host_tables[name].api));
|
|
269
|
+
const route_calls = new Set(app.tables_on(kind, true).flatMap((name) => Object.keys(app.host_tables[name].api).filter((method) => route_of(app.host_tables[name], method) !== null)));
|
|
238
270
|
await server.register(async (api) => {
|
|
239
271
|
changes.register(api, "/events");
|
|
240
272
|
api.get("/theme", async () => options.theme ?? read_server_theme(null));
|
|
241
273
|
register_app_calls(api, app, database, changes);
|
|
242
274
|
register_host_tables(api, app, reach, services, changes);
|
|
243
|
-
|
|
275
|
+
// A route table's calls are documented as the routes they run, the rest as the calls posted under /api.
|
|
276
|
+
api.get("/openapi.json", async () => {
|
|
277
|
+
const called = Object.fromEntries(Object.entries(documented).filter(([method]) => !route_calls.has(method)));
|
|
278
|
+
const document = openapi_document(called, { ...description, path_of: call_path_of(app, kind), is_read_only: app.is_read_only });
|
|
279
|
+
const routed = route_openapi_document(Object.fromEntries([...route_calls].map((method) => [method, documented[method]])), description);
|
|
280
|
+
return { ...document, paths: { ...document.paths, ...routed.paths } };
|
|
281
|
+
});
|
|
244
282
|
await register_mcp_route(api, {
|
|
245
283
|
name: app.id,
|
|
246
284
|
version: app.version,
|
|
247
285
|
instructions: app.instructions,
|
|
248
|
-
api: tools.api,
|
|
249
|
-
is_read_only: app.is_read_only,
|
|
286
|
+
api: { ...tools.api, ...backup_tools },
|
|
287
|
+
is_read_only: (method) => method === "list_backups" || method === "get_backup_schedule" || app.is_read_only(method),
|
|
250
288
|
page_only: app.mcp.page_only,
|
|
251
|
-
call: (method, args, request) =>
|
|
289
|
+
call: async (method, args, request) => {
|
|
290
|
+
if (!Object.hasOwn(backup_tools, method))
|
|
291
|
+
return tools.call(method, args, request);
|
|
292
|
+
if (!is_admin(request))
|
|
293
|
+
throw new Error(`${method} needs an admin's token.`);
|
|
294
|
+
return app.bridges.backups.dispatch(options.backup_methods, method, []);
|
|
295
|
+
},
|
|
252
296
|
});
|
|
253
297
|
// The server's backups, as the page's Settings reach them.
|
|
254
298
|
api.post("/backups/:method", async (request, reply) => {
|
|
@@ -276,6 +320,12 @@ export async function build_server(app, options) {
|
|
|
276
320
|
await register_web_folder(server, { folder: options.web_folder });
|
|
277
321
|
return server;
|
|
278
322
|
}
|
|
323
|
+
// A notice the server passes on through each of its channels; a channel that fails is only logged.
|
|
324
|
+
export function notify_through(channels, notice) {
|
|
325
|
+
const level = notice.urgency === "critical" ? "warning" : "info";
|
|
326
|
+
for (const channel of channels)
|
|
327
|
+
void channel({ title: notice.title, body: notice.body, level }).catch((error) => console.warn(`notify: ${error instanceof Error ? error.message : String(error)}`));
|
|
328
|
+
}
|
|
279
329
|
// Starts the app's web server on the database its config names, and stops it on SIGINT and SIGTERM.
|
|
280
330
|
export async function run_server(app, options) {
|
|
281
331
|
const prefix = app.env_prefix;
|
|
@@ -317,14 +367,17 @@ export async function run_server(app, options) {
|
|
|
317
367
|
app_name: app.name,
|
|
318
368
|
...(app.roles ? { roles: app.roles } : {}),
|
|
319
369
|
...(app.token_prefix ? { token_prefix: app.token_prefix } : {}),
|
|
370
|
+
...(config.token_days !== undefined ? { longest_token_days: config.token_days } : {}),
|
|
320
371
|
declared: load_accounts(`${prefix}_PASSWORD_HASH_FILE`, server_config.values.password_hash_file),
|
|
321
372
|
declared_tokens: declared_tokens.filter((token) => token.role !== null),
|
|
322
373
|
});
|
|
323
374
|
const oidc_settings = oidc_from_environment(prefix, options.env ?? process.env);
|
|
324
375
|
// Every page hears of a change, whether a page or another device made it, and which tables it touched.
|
|
325
|
-
const changes = new EventStream({ change_data: data_change_text(app, opened.database) });
|
|
326
376
|
// Answers the host tables and the app's routes once started; before then they say the server is still starting.
|
|
327
377
|
let services = no_services;
|
|
378
|
+
const changes = new EventStream({ change_data: data_change_text(app, opened.database, (change) => services.after_change?.(change)) });
|
|
379
|
+
// A mistake in a channel, or a secret file that cannot be read, stops the server starting.
|
|
380
|
+
const channels = read_channels(config.notify_channels, { name: "notify_channels" });
|
|
328
381
|
// The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be; an app
|
|
329
382
|
// whose server is the only copy keeps none.
|
|
330
383
|
const sync = app.sync === false ? null : create_sync_peer({
|
|
@@ -346,6 +399,7 @@ export async function run_server(app, options) {
|
|
|
346
399
|
...(oidc_settings ? { oidc: new OidcClient(oidc_settings) } : {}),
|
|
347
400
|
...(config.session_seconds !== undefined ? { session_seconds: config.session_seconds } : {}),
|
|
348
401
|
...(config.remembered_seconds !== undefined ? { remembered_seconds: config.remembered_seconds } : {}),
|
|
402
|
+
...(config.second_factor_from ? { second_factor_from: config.second_factor_from } : {}),
|
|
349
403
|
theme: read_server_theme(config.theme),
|
|
350
404
|
plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
|
|
351
405
|
});
|
|
@@ -378,8 +432,13 @@ export async function run_server(app, options) {
|
|
|
378
432
|
back_up: opened.back_up,
|
|
379
433
|
window_in_front: () => false,
|
|
380
434
|
icon_path: null,
|
|
381
|
-
// The server shows no notice itself
|
|
382
|
-
|
|
435
|
+
// The server shows no notice itself: it goes out through the config's channels, and the pages and phones
|
|
436
|
+
// working on the server show it.
|
|
437
|
+
notify: (notice) => {
|
|
438
|
+
notify_through(channels, notice);
|
|
439
|
+
changes.send(JSON.stringify(notice), { event: notice_event });
|
|
440
|
+
},
|
|
441
|
+
withdraw: (key) => changes.send(JSON.stringify(key), { event: notice_withdrawn_event }),
|
|
383
442
|
})
|
|
384
443
|
: no_services;
|
|
385
444
|
opened.on_restore({ before: () => services.before_restore?.(), after: () => services.after_restore?.() });
|
package/dist/app/services.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { DatabaseSync } from "node:sqlite";
|
|
|
2
2
|
import type { FastifyInstance } from "fastify";
|
|
3
3
|
import type { Need } from "../server/account_sign_in.ts";
|
|
4
4
|
import type { DeclaredToken } from "../server/declared_tokens.ts";
|
|
5
|
+
import type { DataChange } from "../sync_protocol.ts";
|
|
5
6
|
import type { App } from "./define.ts";
|
|
6
7
|
import type { AppNotice } from "./protocol.ts";
|
|
7
8
|
export interface HostContext {
|
|
@@ -23,6 +24,7 @@ export interface HostContext {
|
|
|
23
24
|
window_in_front: () => boolean;
|
|
24
25
|
icon_path: string | null;
|
|
25
26
|
notify: (notice: AppNotice) => void;
|
|
27
|
+
withdraw: (key: string) => void;
|
|
26
28
|
}
|
|
27
29
|
export interface ServedTable {
|
|
28
30
|
methods: object;
|
|
@@ -35,13 +37,14 @@ export interface HostServices {
|
|
|
35
37
|
tables?: Readonly<Record<string, ServedTable>>;
|
|
36
38
|
own?: unknown;
|
|
37
39
|
after_remote_change?: () => void;
|
|
40
|
+
after_change?: (change: DataChange | null) => void;
|
|
38
41
|
}
|
|
39
42
|
export type StartServices = (context: HostContext) => HostServices | Promise<HostServices>;
|
|
40
43
|
export interface AppRoutes {
|
|
41
44
|
open_paths?: readonly string[];
|
|
42
45
|
open_prefixes?: readonly string[];
|
|
43
46
|
guarded_paths?: readonly string[];
|
|
44
|
-
needed?: (method: string, path: string) => Need | null;
|
|
47
|
+
needed?: (method: string, path: string, route: string | null) => Need | null;
|
|
45
48
|
register: (server: FastifyInstance, services: () => HostServices) => void | Promise<void>;
|
|
46
49
|
}
|
|
47
50
|
export declare function declared_file_of(app: Pick<App, "id" | "env_prefix">, env: NodeJS.ProcessEnv): string;
|
package/dist/app/web/app_page.js
CHANGED
|
@@ -96,7 +96,14 @@ function Pages({ pages, account }) {
|
|
|
96
96
|
// A page with pages of its own shows the one the route names, or its first; with only one it is the page itself.
|
|
97
97
|
const children = shown?.children && shown.children.length > 1 ? shown.children : [];
|
|
98
98
|
const subpage = children.find((child) => child.id === rest[0]) ?? children[0];
|
|
99
|
-
|
|
99
|
+
// Each listed page's items, such as paired devices, from its hook, called in the same order every time.
|
|
100
|
+
const listed = pages.pages.filter((each) => each.in_sidebar !== false);
|
|
101
|
+
const items = listed.map((each) => each.use_items?.() ?? null);
|
|
102
|
+
const shown_items = shown ? (items[listed.indexOf(shown)] ?? []) : [];
|
|
103
|
+
const item = subpage ? undefined : shown_items.find((each) => each.id === rest[0]);
|
|
104
|
+
const named = subpage ?? item;
|
|
105
|
+
const own_title = shown?.title?.(rest) ?? null;
|
|
106
|
+
const label = own_title ?? (shown ? (named ? `${named.label} · ${shown.label}` : shown.label) : is_account ? "Your account" : "Settings");
|
|
100
107
|
const view_key = shown?.view_key ? [section, shown.view_key(rest)].join("/") : route.parts.join("/");
|
|
101
108
|
const chrome = pages.use_chrome?.(route.parts) ?? {};
|
|
102
109
|
const theme = use_theme(app);
|
|
@@ -104,24 +111,22 @@ function Pages({ pages, account }) {
|
|
|
104
111
|
document.title = `${label} · ${app.name}`;
|
|
105
112
|
}, [label, app.name]);
|
|
106
113
|
// Each listed page's badge, such as how many things wait, from its hook, called in the same order every time.
|
|
107
|
-
const listed = pages.pages.filter((each) => each.in_sidebar !== false);
|
|
108
114
|
const badges = listed.map((each) => each.use_badge?.() ?? null);
|
|
109
115
|
const row_label = (index) => (badges[index] ? `${listed[index].label} · ${badges[index]}` : listed[index].label);
|
|
110
116
|
const with_icons = listed.some((each) => each.icon);
|
|
111
117
|
// 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
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
href: `#/${each.id}`,
|
|
117
|
-
|
|
118
|
-
}));
|
|
118
|
+
const rows_under = (each, index) => (each.children && each.children.length > 1 ? each.children : (items[index] ?? []));
|
|
119
|
+
const folding = listed.some((each, index) => rows_under(each, index).length > 0);
|
|
120
|
+
const sections = listed.map((each, index) => {
|
|
121
|
+
const under = rows_under(each, index);
|
|
122
|
+
return { id: each.id, label: row_label(index), href: `#/${each.id}`, ...(under.length ? { children: under.map((child) => ({ id: child.id, label: child.label, href: `#/${each.id}/${child.id}` })) } : {}) };
|
|
123
|
+
});
|
|
119
124
|
const views = listed.map((each, index) => ({ id: each.id, label: row_label(index), href: `#/${each.id}`, ...(each.icon ? { icon: each.icon } : {}) }));
|
|
120
125
|
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 });
|
|
121
126
|
const framed = _jsx(Fragment, { children: view }, view_key);
|
|
122
127
|
if (chrome.bare)
|
|
123
128
|
return _jsx(_Fragment, { 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:
|
|
129
|
+
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: named?.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 }));
|
|
125
130
|
}
|
|
126
131
|
// ── App ──────────────────────────────────────────────────────────────────────
|
|
127
132
|
// 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.
|
package/dist/app/web/portal.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { type AppNotice, type PageApi } from "../protocol.ts";
|
|
|
4
4
|
import type { PhoneLifecycle } from "./android.ts";
|
|
5
5
|
export declare function read_notice_switches(app: Pick<App, "desktop_settings">, saved: string | null): Record<string, boolean>;
|
|
6
6
|
export declare function phone_notice_shower(plugin: LocalNotificationsLike, open_link: (url: string) => void): (notice: AppNotice) => void;
|
|
7
|
+
export declare function phone_notice_withdrawer(plugin: LocalNotificationsLike): (key: string) => void;
|
|
7
8
|
export interface PortalOptions {
|
|
8
9
|
lifecycle: PhoneLifecycle;
|
|
9
10
|
notifications?: LocalNotificationsLike;
|
package/dist/app/web/portal.js
CHANGED
|
@@ -9,7 +9,7 @@ import { phone_certificates } from "../../phone_certificates.js";
|
|
|
9
9
|
import { local_connection_storage } from "../../web/connection_storage.js";
|
|
10
10
|
import { call_remote, follow_remote } from "../../web/remote_daemon.js";
|
|
11
11
|
import { route_of_link } from "../links.js";
|
|
12
|
-
import { data_change_of, notice_event, notice_is_on } from "../protocol.js";
|
|
12
|
+
import { data_change_of, notice_event, notice_is_on, notice_withdrawn_event } from "../protocol.js";
|
|
13
13
|
import { host_tables_of, read_host_abilities } from "./hosts.js";
|
|
14
14
|
// ── Switches ─────────────────────────────────────────────────────────────────
|
|
15
15
|
// The notice switches this phone keeps, each of the app's `notify_` desktop switches at its default where unset.
|
|
@@ -36,6 +36,14 @@ export function phone_notice_shower(plugin, open_link) {
|
|
|
36
36
|
void plugin.checkPermissions().then(({ display }) => (display === "granted" || display === "denied" ? undefined : plugin.requestPermissions()));
|
|
37
37
|
return (notice) => void plugin.schedule({ notifications: [{ id: notice_id(notice.key), title: notice.title, body: notice.body, extra: { url: notice.url }, isExactNotification: false }] }).catch((error) => console.error("could not show a notice", error));
|
|
38
38
|
}
|
|
39
|
+
// Takes a notice the host withdrew off the screen, and out of those still to show.
|
|
40
|
+
export function phone_notice_withdrawer(plugin) {
|
|
41
|
+
return (key) => {
|
|
42
|
+
const notifications = [{ id: notice_id(key), title: "", body: "" }];
|
|
43
|
+
void plugin.cancel({ notifications }).catch(() => undefined);
|
|
44
|
+
void plugin.removeDeliveredNotifications?.({ notifications }).catch(() => undefined);
|
|
45
|
+
};
|
|
46
|
+
}
|
|
39
47
|
export async function portal_api(app, options) {
|
|
40
48
|
const storage = options.storage ?? localStorage;
|
|
41
49
|
const switches_key = `${app.id}-notice-kinds`;
|
|
@@ -67,6 +75,7 @@ export async function portal_api(app, options) {
|
|
|
67
75
|
location.hash = route;
|
|
68
76
|
};
|
|
69
77
|
const show = options.notifications ? phone_notice_shower(options.notifications, open_link) : null;
|
|
78
|
+
const withdraw = options.notifications ? phone_notice_withdrawer(options.notifications) : null;
|
|
70
79
|
if (link.daemon()) {
|
|
71
80
|
follow_remote(link, (event, data) => {
|
|
72
81
|
if (event === "hello")
|
|
@@ -77,6 +86,8 @@ export async function portal_api(app, options) {
|
|
|
77
86
|
const parsed = data === "" ? null : JSON.parse(data);
|
|
78
87
|
if (event === notice_event && show && notice_is_on(parsed.kind, switches()))
|
|
79
88
|
show(parsed);
|
|
89
|
+
if (event === notice_withdrawn_event && withdraw && typeof parsed === "string")
|
|
90
|
+
withdraw(parsed);
|
|
80
91
|
for (const listener of named.get(event) ?? [])
|
|
81
92
|
listener(parsed);
|
|
82
93
|
}
|
|
@@ -20,6 +20,8 @@ export interface AppPage {
|
|
|
20
20
|
active_as?: string;
|
|
21
21
|
view_key?: (parts: string[]) => string;
|
|
22
22
|
children?: readonly AppSubpage[];
|
|
23
|
+
use_items?: () => readonly AppSubpage[] | null;
|
|
24
|
+
title?: (parts: string[]) => string | null;
|
|
23
25
|
}
|
|
24
26
|
export interface AppSubpage {
|
|
25
27
|
id: string;
|
|
@@ -13,7 +13,8 @@ import { PageHeading, SettingRow, SettingsPage } from "../../web/react/layout.js
|
|
|
13
13
|
import { Loaded } from "../../web/react/states.js";
|
|
14
14
|
import { RemoteAccessSettings } from "../../web/react/remote_access_settings.js";
|
|
15
15
|
import { PeerListeningSettings, SyncSettings } from "../../web/react/sync_settings.js";
|
|
16
|
-
import {
|
|
16
|
+
import { read_picked, save_text } from "../../web/files.js";
|
|
17
|
+
import { attempt, attempt_value, toast } from "../../web/react/toasts.js";
|
|
17
18
|
import { calls, data_watch, page, use_settings } from "./page.js";
|
|
18
19
|
// ── Sections ─────────────────────────────────────────────────────────────────
|
|
19
20
|
// A phone's backups go in a folder picked once in its storage, where file managers and sync apps reach them.
|
|
@@ -57,6 +58,23 @@ function NoticeSwitches({ app, switches }) {
|
|
|
57
58
|
attempt(switches.set(key, on));
|
|
58
59
|
} }) }, key))) }));
|
|
59
60
|
}
|
|
61
|
+
// Every setting but this device's own, as a file to take to another device or install, and read back.
|
|
62
|
+
function SettingsFile({ app_id }) {
|
|
63
|
+
const settings_calls = calls();
|
|
64
|
+
const export_file = async () => {
|
|
65
|
+
const file = await attempt_value(() => settings_calls.export_settings());
|
|
66
|
+
if (file)
|
|
67
|
+
save_text(`${app_id}-settings-${new Date().toISOString().slice(0, 10)}.json`, JSON.stringify(file, null, 2));
|
|
68
|
+
};
|
|
69
|
+
const import_file = async (text) => {
|
|
70
|
+
if (text === null)
|
|
71
|
+
return;
|
|
72
|
+
const result = await attempt_value(() => settings_calls.import_settings(text));
|
|
73
|
+
if (result)
|
|
74
|
+
toast(result.changed === 1 ? "1 setting set." : `${result.changed} settings set.`, { tone: "good" });
|
|
75
|
+
};
|
|
76
|
+
return (_jsx(SettingRow, { label: "Settings file", hint: "Every setting but this device's own, such as its notifications; keys for other services stay out.", children: _jsxs("div", { className: "button-list", children: [_jsx("button", { type: "button", onClick: () => void export_file(), children: "Export" }), _jsxs("label", { className: "button", children: ["Import", _jsx("input", { type: "file", accept: ".json,application/json", className: "visually-hidden", "aria-label": "Import settings", onChange: (event) => void read_picked(event).then(import_file) })] })] }) }));
|
|
77
|
+
}
|
|
60
78
|
// A desktop window on a server's daemon, or a phone that keeps no data, works on the host's data, as a browser does.
|
|
61
79
|
function storage_category(pages, is_admin) {
|
|
62
80
|
const { app } = pages;
|
|
@@ -82,6 +100,7 @@ function storage_category(pages, is_admin) {
|
|
|
82
100
|
}
|
|
83
101
|
if (desktop && !on_server)
|
|
84
102
|
sections.push({ id: "storage", heading: "Storage", hint: `Where this computer keeps its ${data_name}.`, content: _jsx(DataFolder, { desktop: desktop }) });
|
|
103
|
+
sections.push({ id: "settings-file", heading: "Import and export", hint: `Take ${name}'s settings to another device, or bring them back.`, content: _jsx(SettingsFile, { app_id: app.id }) });
|
|
85
104
|
if (backups && (!on_server || is_admin)) {
|
|
86
105
|
const hint = backup_folder ? `This device's ${data_name}, kept in a folder of the phone's storage.` : on_server ? `The server's ${data_name}, kept in its data folder.` : `This device's ${data_name}, kept beside its database.`;
|
|
87
106
|
// This computer's backups folder opens in the file manager.
|
|
@@ -6,5 +6,6 @@ export interface ElectronBuilderOptions {
|
|
|
6
6
|
categories?: readonly string[];
|
|
7
7
|
link_scheme?: string;
|
|
8
8
|
copyright?: string;
|
|
9
|
+
flatpak_permissions?: readonly string[];
|
|
9
10
|
}
|
|
10
11
|
export declare function electron_builder_config(options: ElectronBuilderOptions): Record<string, unknown>;
|
|
@@ -37,6 +37,7 @@ export function electron_builder_config(options) {
|
|
|
37
37
|
`--filesystem=xdg-config/${options.id}:create`,
|
|
38
38
|
// The login entry that starts the app in the background.
|
|
39
39
|
"--filesystem=xdg-config/autostart:create",
|
|
40
|
+
...(options.flatpak_permissions ?? []),
|
|
40
41
|
],
|
|
41
42
|
},
|
|
42
43
|
};
|
package/dist/phone_notices.d.ts
CHANGED
|
@@ -33,6 +33,13 @@ export interface LocalNotificationsLike {
|
|
|
33
33
|
extra?: unknown;
|
|
34
34
|
};
|
|
35
35
|
}) => void): Promise<unknown>;
|
|
36
|
+
removeDeliveredNotifications?(options: {
|
|
37
|
+
notifications: {
|
|
38
|
+
id: number;
|
|
39
|
+
title: string;
|
|
40
|
+
body: string;
|
|
41
|
+
}[];
|
|
42
|
+
}): Promise<void>;
|
|
36
43
|
}
|
|
37
44
|
export interface PhoneNotice {
|
|
38
45
|
key: string;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Every request's path must be spelled canonically, so the sign-in guard, which reads the path as sent, and the router,
|
|
2
|
+
// which decodes it before matching, always see the same route. A path the router would read differently is refused
|
|
3
|
+
// with 400 before sign-in or any route sees it; the query string is left alone.
|
|
4
|
+
// ── Imports ──────────────────────────────────────────────────────────────────
|
|
5
|
+
import { send_error } from "./replies.js";
|
|
6
|
+
// ── Settings ─────────────────────────────────────────────────────────────────
|
|
7
|
+
// Characters a path writes as themselves, so an escape of one is a second spelling of the same path.
|
|
8
|
+
const unreserved_character = /^[A-Za-z0-9\-._~]$/;
|
|
9
|
+
// Characters whose escape would read as a path separator or as another escape.
|
|
10
|
+
const separator_characters = new Set(["/", "\\", "%"]);
|
|
11
|
+
// One percent escape, spelled with upper-case hex digits.
|
|
12
|
+
const canonical_escape = /^%[0-9A-F]{2}$/;
|
|
13
|
+
// ── Checking ─────────────────────────────────────────────────────────────────
|
|
14
|
+
// Why a request target's path is not canonical, or null when it is.
|
|
15
|
+
export function path_refusal(url) {
|
|
16
|
+
if (!url.startsWith("/"))
|
|
17
|
+
return "The path must start with /.";
|
|
18
|
+
const query_start = url.indexOf("?");
|
|
19
|
+
const path = query_start === -1 ? url : url.slice(0, query_start);
|
|
20
|
+
if (path.includes("#") || path.includes(";") || path.includes("\\"))
|
|
21
|
+
return "The path holds a character that must be escaped.";
|
|
22
|
+
if (path.includes("//"))
|
|
23
|
+
return "The path holds an empty segment.";
|
|
24
|
+
if (path.split("/").some((segment) => segment === "." || segment === ".."))
|
|
25
|
+
return "The path holds a dot segment.";
|
|
26
|
+
for (let index = path.indexOf("%"); index !== -1; index = path.indexOf("%", index + 1)) {
|
|
27
|
+
const escape = path.slice(index, index + 3);
|
|
28
|
+
if (!canonical_escape.test(escape))
|
|
29
|
+
return "The path holds an escape that is not two upper-case hex digits.";
|
|
30
|
+
const character = String.fromCharCode(Number.parseInt(escape.slice(1), 16));
|
|
31
|
+
if (unreserved_character.test(character) || separator_characters.has(character))
|
|
32
|
+
return "The path escapes a character that needs no escaping.";
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
decodeURIComponent(path);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return "The path holds an escape that is not UTF-8.";
|
|
39
|
+
}
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
// ── Registration ─────────────────────────────────────────────────────────────
|
|
43
|
+
// Refuses non-canonical paths ahead of every other hook, and refuses to start when the router would rewrite a canonical path.
|
|
44
|
+
export function register_canonical_paths(app) {
|
|
45
|
+
const { caseSensitive, ignoreTrailingSlash, ignoreDuplicateSlashes, useSemicolonDelimiter } = (app.initialConfig.routerOptions ?? {});
|
|
46
|
+
if (caseSensitive === false || ignoreTrailingSlash === true || ignoreDuplicateSlashes === true || useSemicolonDelimiter === true) {
|
|
47
|
+
throw new Error("The router must match paths as spelled: case-sensitive, without ignoring slashes or splitting on semicolons.");
|
|
48
|
+
}
|
|
49
|
+
app.addHook("onRequest", async (request, reply) => {
|
|
50
|
+
const refusal = path_refusal(request.url);
|
|
51
|
+
if (refusal !== null)
|
|
52
|
+
return send_error(reply, 400, refusal, "json");
|
|
53
|
+
});
|
|
54
|
+
}
|
package/dist/server/mcp.js
CHANGED
|
@@ -103,8 +103,9 @@ export function route_tools(app, routes) {
|
|
|
103
103
|
});
|
|
104
104
|
const is_json = String(answer.headers["content-type"] ?? "").includes("json") && answer.body !== "";
|
|
105
105
|
const body = is_json ? JSON.parse(answer.body) : answer.body;
|
|
106
|
+
// The refusal keeps the route's status, for a caller that passes it on.
|
|
106
107
|
if (answer.statusCode >= 400)
|
|
107
|
-
throw new Error(refusal_of(body, answer.statusCode));
|
|
108
|
+
throw Object.assign(new Error(refusal_of(body, answer.statusCode)), { status: answer.statusCode });
|
|
108
109
|
return body === "" ? undefined : body;
|
|
109
110
|
},
|
|
110
111
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x-tech-laboratories/x-app",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.124.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": {
|