@x-tech-laboratories/x-app 0.123.0 → 0.125.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 +10 -3
- package/dist/app/define.d.ts +8 -1
- package/dist/app/define.js +15 -2
- package/dist/app/host_tables.d.ts +1 -1
- package/dist/app/host_tables.js +24 -3
- package/dist/app/server.d.ts +4 -1
- package/dist/app/server.js +44 -9
- package/dist/app/services.d.ts +1 -1
- package/dist/app/web/app_page.js +2 -1
- package/dist/app/web/settings_page.d.ts +1 -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/dist/web/react/layout.d.ts +5 -1
- package/dist/web/react/layout.js +4 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,14 +10,14 @@ 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
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, Backups and Import and export, the settings as a file) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. The page API's `on_event(name, listener)` hears the named events the app's services `emit`, on the web and the desktop. A page may have an `icon` (the sidebar then shows icon rows), a `use_badge` hook ("Inbox · 3"), `in_sidebar: false` with `active_as` for a page reached only by its route; `default_page` names the page an empty route opens, and the `use_chrome(parts)` hook gives the `sidebar` content under the rows, header `tools`, a `side_pane`, a `contained` window where only the page scrolls with a `main_class` for its box, `around`, which wraps the page, such as in the app's own context or with dialogs over any page, and `bare` for the page alone with no sidebar or header, such as a strip embedded in another program. `settings_categories(props)` adds the app's own Settings categories after General, for settings no one page owns. A page's `children` fold open under its row in the sidebar (`#/diet/foods`, the title "Foods · Diet", the first shown when none is named, a single child leaving the page one row); its `use_items` hook gives rows worked out as the page runs, such as each paired device, folding open under it onto `#/devices/<id>` with the title "Pixel · Devices"; and `phone_services` loads the app's own work on the phone only there, such as reminders handed to Android, told of every write, every change from another device and each return to the app; an older version's backup schedule in the page's storage moves into the setting. In a browser, Settings ends with Users and Tokens (`users_settings`) for an admin of the server, with the app's `role_text`; an app's own `use_chrome` sidebar, such as a tree, sits under the pages' rows. |
|
|
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
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. |
|
|
@@ -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`. |
|
|
@@ -164,7 +165,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
|
|
|
164
165
|
| `web/prefs`, `web/react/prefs` | Remembered view settings that read as their default when stored corrupt, stale or of the wrong shape; `use_pref` keeps one as component state. |
|
|
165
166
|
| `web/selection`, `web/virtual`, `web/drag` | Picking rows with plain, Ctrl and Shift clicks from a fixed anchor, or as lists of ids with the anchor kept by id, the row an arrow or page key moves to; which rows of a long list a viewport needs; a badge such as "3 tasks" as the drag image. |
|
|
166
167
|
| `web/react/shell` | `Shell`: top bar with the brand and its icon and the app's `tools`; section links, or, once a section has `children`, a `SectionTree` of section rows folding open onto their items on `Tree`, the folded ones kept in the `sections_pref` pref and a folded section lit up in place of its hidden `active_item`; or the app's `views` as rows with their icons (from `web/react/icons`) in the sidebar's navigation, the one `active` names raised and marked as the current page, above the app's own sidebar in a `.sidebar-content` box, the sidebar then an aside so the views are its only navigation landmark, or that sidebar alone, scrolling above a foot pinned to the sidebar's bottom that holds the app's `sidebar_foot` rows, then the theme, the signed-in `user` linked to `user_href` with Sign out, and `settings` last; resizable; a `side_pane` docked on the right beside main ([A pane on the right](#a-pane-on-the-right)), its open state kept by `use_side_pane` in a pref; `brand_logo` for a full logo that already holds the name, drawn alone in its place; a `status_bar` at the foot of the window, toasts, dialogs and menus, with or without logins (no account row without a `user`, `logged_out` hiding the sidebar and tools), its phone menu held by the Shell or the app, and for app-like pages a `contained` window where only main scrolls and the brand heading the sidebar; `labels` for its own words in another language; `ThemeRow`, the theme as a sidebar row, `ThemeButton`, as an icon button, both drawing the system theme on a server and until the page is picked up, and `use_route`. |
|
|
167
|
-
| `web/react/layout`, `badges`, `states` | `PageHeading` with a subtitle, icon, banner, actions and a `level` for inside dialogs and panels; panels (`Section`, with a `level` for one inside a dialog or under another heading), `GroupSections`, a panel per group from `group_items` headed by its name and count, facts, tiles, cards, tabs, `Crumbs` with chevrons between steps that link, run a function or mark where the reader is, `PathText` for a path shown with the same chevrons, steppers, `FormRow` for a form's labelled fields, `FormGroup` folding part of a form under a summary line such as "More options", `SettingsPage` with an `Outline` beside its sections, settings rows, `RowActions` and `moved` for ordered lists, `SelectionBar` for picked rows, their count with its thousands separated; badges, `StateBadge` naming each state's text and tone and `ToneBadge` showing the state's own name in its tone, chips in an item's own colour, dashed or removable, `ColorDot` and `StatusPill`, a state dot with text and an action; `use_resource` with its `status` (idle until `enabled`, loading, loaded, failed), a `watch` that reloads it quietly (bumps during a load fold into one load after it), and its loading states, `Loaded` going by the status so a null result shows its `empty` slot or the children. |
|
|
168
|
+
| `web/react/layout`, `badges`, `states` | `PageHeading` with a subtitle, icon, banner, actions and a `level` for inside dialogs and panels; panels (`Section`, with a `level` for one inside a dialog or under another heading, and a `fold` for one that opens and shuts from its head), `GroupSections`, a panel per group from `group_items` headed by its name and count, facts, tiles, cards, tabs, `Crumbs` with chevrons between steps that link, run a function or mark where the reader is, `PathText` for a path shown with the same chevrons, steppers, `FormRow` for a form's labelled fields, `FormGroup` folding part of a form under a summary line such as "More options", `SettingsPage` with an `Outline` beside its sections, settings rows, `RowActions` and `moved` for ordered lists, `SelectionBar` for picked rows, their count with its thousands separated; badges, `StateBadge` naming each state's text and tone and `ToneBadge` showing the state's own name in its tone, chips in an item's own colour, dashed or removable, `ColorDot` and `StatusPill`, a state dot with text and an action; `use_resource` with its `status` (idle until `enabled`, loading, loaded, failed), a `watch` that reloads it quietly (bumps during a load fold into one load after it), and its loading states, `Loaded` going by the status so a null result shows its `empty` slot or the children. |
|
|
168
169
|
| `web/react/sync_settings`, `backup_settings` | The settings rows every device shows: `SyncSettings`, the sync status, this device with its id and where others reach it, a pairing code to show when they can, each paired device with how it was last reached and Remove after a confirm, and a field to enter another device's code; `SyncButton`, the same status as a sidebar row with the changes waiting, syncing on a click or opening the settings when sync failed or no device is paired, and shown even then; `BackupSettings`, back up now, the daily schedule, and each backup to restore or delete after a confirm. |
|
|
169
170
|
| `web/react/connections` | `ConnectionSettings`: the Connections section of Settings, every daemon the app can talk to with the one in use marked Connected, Connect to switch, Rename and Remove (after a confirm) for daemons on other hosts, and a form to add one by address, name and password, asking for the code when the daemon does and offering to trust a certificate the device refuses given `certificates`. |
|
|
170
171
|
| `web/react/remote_access_settings` | `RemoteAccessSettings`: "Let other devices connect" for a desktop daemon, with its state (listening where, or why not), address, port, https certificate and key files, Save, and the admins other devices sign in as, added with a password of 10 characters or more and removed after asking; `reach` words what they can do once in. The base app shows it under Settings → Other devices. |
|
|
@@ -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,6 +257,10 @@ 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.
|
|
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.
|
|
257
264
|
- **Notices**: `context.notify({ kind, title, body, key, url, urgency })` from the services; the desktop daemon shows it
|
|
258
265
|
where `notify_<kind>` in `desktop_settings` is on, and every window and phone working on that host from elsewhere
|
|
259
266
|
shows it by its own switch. The server sends it through the channels its config's `notify_channels` lists (ntfy,
|
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,
|
|
@@ -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/server.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
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";
|
|
@@ -9,7 +10,7 @@ import { type SqlDatabase } from "../sql.ts";
|
|
|
9
10
|
import { type ServerTheme } from "../web/theme.ts";
|
|
10
11
|
import { type SyncPeer } from "../sync_peer.ts";
|
|
11
12
|
import { type DataChange } from "../sync_protocol.ts";
|
|
12
|
-
import type
|
|
13
|
+
import { type App, type HostKind } from "./define.ts";
|
|
13
14
|
import { type AppNotice } from "./protocol.ts";
|
|
14
15
|
import { type AppRoutes, type HostServices, type StartServices } from "./services.ts";
|
|
15
16
|
export interface AppDatabase {
|
|
@@ -47,7 +48,9 @@ export interface ServerOptions {
|
|
|
47
48
|
remembered_seconds?: number | null;
|
|
48
49
|
theme?: ServerTheme;
|
|
49
50
|
plugins_folder?: string | null;
|
|
51
|
+
second_factor_from?: string | null;
|
|
50
52
|
}
|
|
53
|
+
export declare const backup_tools: Record<"list_backups" | "create_backup" | "get_backup_schedule", MethodSpec>;
|
|
51
54
|
export declare const user_only_backup_calls: ReadonlySet<string>;
|
|
52
55
|
export declare function build_server(app: App, options: ServerOptions): Promise<FastifyInstance>;
|
|
53
56
|
export declare function notify_through(channels: readonly Channel[], notice: AppNotice): void;
|
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,7 +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";
|
|
23
24
|
import { read_channels } from "../server/notify/channels.js";
|
|
25
|
+
import { register_security_headers } from "../server/security_headers.js";
|
|
24
26
|
import { EventStream } from "../server/events.js";
|
|
25
27
|
import { register_mcp_route } from "../server/mcp.js";
|
|
26
28
|
import { register_plugin_files } from "../server/plugin_files.js";
|
|
@@ -34,6 +36,7 @@ import { file_sync_storage } from "../sync_file_storage.js";
|
|
|
34
36
|
import { read_server_theme } from "../web/theme.js";
|
|
35
37
|
import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
|
|
36
38
|
import { data_change_of } from "../sync_protocol.js";
|
|
39
|
+
import { route_of } from "./define.js";
|
|
37
40
|
import { call_path_of, mcp_tools, register_host_tables } from "./host_tables.js";
|
|
38
41
|
import { notice_event, notice_withdrawn_event } from "./protocol.js";
|
|
39
42
|
import { declared_file_of, no_services, side_databases } from "./services.js";
|
|
@@ -195,13 +198,25 @@ export function register_app_calls(api, app, database, changes) {
|
|
|
195
198
|
return reply.send(JSON.stringify(result));
|
|
196
199
|
});
|
|
197
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
|
+
};
|
|
198
207
|
// The server's backups and its sync peer's pairings, which only an admin reaches.
|
|
199
208
|
const admin_paths = ["/api/backups/", "/api/sync/"];
|
|
200
209
|
// Backup calls only the user at the page may make, since a restored backup could undo what only the user may change.
|
|
201
210
|
export const user_only_backup_calls = new Set(["restore_backup", "remove_backup", "set_backup_schedule"]);
|
|
202
211
|
export async function build_server(app, options) {
|
|
203
|
-
|
|
204
|
-
|
|
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" });
|
|
205
220
|
register_error_replies(server);
|
|
206
221
|
const kind = options.kind ?? "server";
|
|
207
222
|
const services = options.services ?? (() => no_services);
|
|
@@ -214,6 +229,7 @@ export async function build_server(app, options) {
|
|
|
214
229
|
reply.raw.setHeader("access-control-allow-origin", "*");
|
|
215
230
|
});
|
|
216
231
|
}
|
|
232
|
+
const table_paths = app.tables_on(kind, true).map((name) => `/api/${name}/`);
|
|
217
233
|
const admin_tables = app.tables_on(kind, true).filter((name) => app.host_tables[name].network !== "any").map((name) => `/api/${name}/`);
|
|
218
234
|
const is_admin = (request) => request.viewer !== null && request.viewer !== undefined && options.accounts.has_role(request.viewer.role, options.accounts.top_role);
|
|
219
235
|
const has_role = (request, role) => request.viewer !== null && request.viewer !== undefined && options.accounts.has_role(request.viewer.role, role);
|
|
@@ -229,12 +245,16 @@ export async function build_server(app, options) {
|
|
|
229
245
|
oidc: options.oidc ?? null,
|
|
230
246
|
...(options.session_seconds !== undefined ? { session_seconds: options.session_seconds } : {}),
|
|
231
247
|
...(options.remembered_seconds !== undefined ? { remembered_seconds: options.remembered_seconds } : {}),
|
|
248
|
+
...(options.second_factor_from ? { second_factor_from: options.second_factor_from } : {}),
|
|
232
249
|
// A read-only token may still list and read through MCP, which posts every request.
|
|
233
250
|
read_only_paths: ["/api/mcp"],
|
|
234
|
-
needed: (method, path) => {
|
|
251
|
+
needed: (method, path, route) => {
|
|
235
252
|
if ([...admin_paths, ...admin_tables].some((admin_path) => path.startsWith(admin_path)))
|
|
236
253
|
return { role: options.accounts.top_role };
|
|
237
|
-
|
|
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";
|
|
238
258
|
},
|
|
239
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.
|
|
240
260
|
call_of: calls_under("/api/call"),
|
|
@@ -246,20 +266,33 @@ export async function build_server(app, options) {
|
|
|
246
266
|
// A change made through MCP is announced to every page, since no page made it.
|
|
247
267
|
const tools = mcp_tools(app, reach, services, database, () => changes.announce_change());
|
|
248
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)));
|
|
249
270
|
await server.register(async (api) => {
|
|
250
271
|
changes.register(api, "/events");
|
|
251
272
|
api.get("/theme", async () => options.theme ?? read_server_theme(null));
|
|
252
273
|
register_app_calls(api, app, database, changes);
|
|
253
274
|
register_host_tables(api, app, reach, services, changes);
|
|
254
|
-
|
|
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
|
+
});
|
|
255
282
|
await register_mcp_route(api, {
|
|
256
283
|
name: app.id,
|
|
257
284
|
version: app.version,
|
|
258
285
|
instructions: app.instructions,
|
|
259
|
-
api: tools.api,
|
|
260
|
-
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),
|
|
261
288
|
page_only: app.mcp.page_only,
|
|
262
|
-
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
|
+
},
|
|
263
296
|
});
|
|
264
297
|
// The server's backups, as the page's Settings reach them.
|
|
265
298
|
api.post("/backups/:method", async (request, reply) => {
|
|
@@ -334,6 +367,7 @@ export async function run_server(app, options) {
|
|
|
334
367
|
app_name: app.name,
|
|
335
368
|
...(app.roles ? { roles: app.roles } : {}),
|
|
336
369
|
...(app.token_prefix ? { token_prefix: app.token_prefix } : {}),
|
|
370
|
+
...(config.token_days !== undefined ? { longest_token_days: config.token_days } : {}),
|
|
337
371
|
declared: load_accounts(`${prefix}_PASSWORD_HASH_FILE`, server_config.values.password_hash_file),
|
|
338
372
|
declared_tokens: declared_tokens.filter((token) => token.role !== null),
|
|
339
373
|
});
|
|
@@ -365,6 +399,7 @@ export async function run_server(app, options) {
|
|
|
365
399
|
...(oidc_settings ? { oidc: new OidcClient(oidc_settings) } : {}),
|
|
366
400
|
...(config.session_seconds !== undefined ? { session_seconds: config.session_seconds } : {}),
|
|
367
401
|
...(config.remembered_seconds !== undefined ? { remembered_seconds: config.remembered_seconds } : {}),
|
|
402
|
+
...(config.second_factor_from ? { second_factor_from: config.second_factor_from } : {}),
|
|
368
403
|
theme: read_server_theme(config.theme),
|
|
369
404
|
plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
|
|
370
405
|
});
|
package/dist/app/services.d.ts
CHANGED
|
@@ -44,7 +44,7 @@ export interface AppRoutes {
|
|
|
44
44
|
open_paths?: readonly string[];
|
|
45
45
|
open_prefixes?: readonly string[];
|
|
46
46
|
guarded_paths?: readonly string[];
|
|
47
|
-
needed?: (method: string, path: string) => Need | null;
|
|
47
|
+
needed?: (method: string, path: string, route: string | null) => Need | null;
|
|
48
48
|
register: (server: FastifyInstance, services: () => HostServices) => void | Promise<void>;
|
|
49
49
|
}
|
|
50
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
|
@@ -102,7 +102,8 @@ function Pages({ pages, account }) {
|
|
|
102
102
|
const shown_items = shown ? (items[listed.indexOf(shown)] ?? []) : [];
|
|
103
103
|
const item = subpage ? undefined : shown_items.find((each) => each.id === rest[0]);
|
|
104
104
|
const named = subpage ?? item;
|
|
105
|
-
const
|
|
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");
|
|
106
107
|
const view_key = shown?.view_key ? [section, shown.view_key(rest)].join("/") : route.parts.join("/");
|
|
107
108
|
const chrome = pages.use_chrome?.(route.parts) ?? {};
|
|
108
109
|
const theme = use_theme(app);
|
|
@@ -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
|
};
|
|
@@ -19,9 +19,13 @@ interface SectionProps {
|
|
|
19
19
|
class_name?: string;
|
|
20
20
|
on_context_menu?: (event: MouseEvent<HTMLElement>) => void;
|
|
21
21
|
level?: 2 | 3 | 4;
|
|
22
|
+
fold?: {
|
|
23
|
+
open: boolean;
|
|
24
|
+
on_toggle: () => void;
|
|
25
|
+
};
|
|
22
26
|
children?: ReactNode;
|
|
23
27
|
}
|
|
24
|
-
export declare function Section({ title, tools, class_name, on_context_menu, level, children }: SectionProps): import("react").JSX.Element;
|
|
28
|
+
export declare function Section({ title, tools, class_name, on_context_menu, level, fold, children }: SectionProps): import("react").JSX.Element;
|
|
25
29
|
interface GroupSectionsProps<Item> {
|
|
26
30
|
groups: ItemGroup<Item>[];
|
|
27
31
|
name_of: (key: string | null) => string;
|
package/dist/web/react/layout.js
CHANGED
|
@@ -9,9 +9,11 @@ export function PageHeading({ title, subtitle, icon, banner, actions, class_name
|
|
|
9
9
|
const Title = `h${level}`;
|
|
10
10
|
return (_jsxs("header", { className: class_name ? `page-head ${class_name}` : "page-head", children: [typeof banner === "string" ? _jsx("img", { className: "page-banner", src: banner, alt: "", loading: "lazy" }) : banner, _jsxs("div", { className: "page-title spread", children: [_jsxs("div", { className: "page-identity", children: [icon, _jsxs("div", { children: [_jsx(Title, { children: title }), subtitle && _jsx("p", { className: "page-subtitle muted", children: subtitle })] })] }), actions && _jsx("div", { className: "head-actions", children: actions })] }), children] }));
|
|
11
11
|
}
|
|
12
|
-
export function Section({ title, tools, class_name, on_context_menu, level = 2, children }) {
|
|
12
|
+
export function Section({ title, tools, class_name, on_context_menu, level = 2, fold, children }) {
|
|
13
13
|
const Title = `h${level}`;
|
|
14
|
-
|
|
14
|
+
const classes = ["panel", fold && "folds", fold && !fold.open && "folded", class_name].filter(Boolean).join(" ");
|
|
15
|
+
return (_jsxs("section", { className: classes, onContextMenu: on_context_menu, children: [_jsxs("div", { className: "panel-head", onClick: fold ? (event) => { if (!event.target.closest(".panel-tools, button"))
|
|
16
|
+
fold.on_toggle(); } : undefined, children: [fold && _jsx("button", { type: "button", className: "tree-toggle", "aria-expanded": fold.open, "aria-label": fold.open ? "Fold" : "Open", onClick: fold.on_toggle, children: fold.open ? "▾" : "▸" }), _jsx(Title, { children: title }), tools && _jsx("div", { className: "panel-tools", children: tools })] }), children] }));
|
|
15
17
|
}
|
|
16
18
|
// A section per group from `group_items`, headed by its name and how many items it holds.
|
|
17
19
|
export function GroupSections({ groups, name_of, level, children }) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x-tech-laboratories/x-app",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.125.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": {
|