@x-tech-laboratories/x-app 0.100.0 → 0.102.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,8 +9,8 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
9
9
 
10
10
  | Import | What it holds |
11
11
  | ---------------------------------------- | ----------------------------------------------------------------------------- |
12
- | `app/define` | The base app: `define_app` puts an X-app's name, ports, files, its own settings and its `define_feature` features (tables, migrations, calls, `api_spec`, settings, histories) together into one store every device keeps (`open_store`, `needs_upgrade`, `bind_methods` recording versions and announcing writes, `is_read_only`), its sync engine, its backups' names and schedule, and its bridges named after the app; `AppMethodsOf<typeof app>` types the app's calls. |
13
- | `app/server`, `app/daemon` | `run_server(app, { web_folder })`: the web server from `<PREFIX>_CONFIG` with accounts, the calls, OpenAPI, MCP, the server's backups and its sync peer; `run_daemon(app)`: the desktop daemon from `<PREFIX>_DB` with sync, letting devices connect, backups, certificates and the desktop settings; `build_server`, `start_daemon`, `open_app_database` and `register_app_calls` for tests and apps that add their own. |
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. |
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; `build_server`, `start_daemon`, `open_app_database` and `register_app_calls` for tests and apps that add their own. |
14
14
  | `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, the login entry, a second launch and `--daemon`; `run_preload(app, electron)` puts every bridge on the page. Electron is handed in, so neither imports it. |
15
15
  | `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, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync and Backups) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. |
16
16
  | `config/vite`, `config/electron_vite`, `config/vitest`, `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. |
@@ -31,6 +31,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
31
31
  | `i18n` | Words in the reader's language: `create_translator` looks each key up in catalogs in turn, so a missing translation falls back to the next, with `{name}` placeholders filled; `merge_messages`; `best_locale`, the available locale that best fits the reader's preferred ones, an exact tag before the same language; `text_direction` for the `dir` attribute. |
32
32
  | `sql` | `SqlDatabase`, the part of a synchronous SQLite connection the apps use, met by node:sqlite and by `web/sqlite_wasm`; `in_transaction`, and `migrate`, each step once in its own transaction, through `user_version` or, with an `owner` such as a feature or plugin, its own row in `schema_versions`. |
33
33
  | `settings` | An app's settings feature: one synced `settings (key, value)` table of JSON values, the same table and first step (`settings_migration` under the owner `"settings"`) every app already ran. Each feature declares a `SettingSpec` per key (`default`, `user_only`, `local` for this device alone, `secret` for another service's key, or its own `hide` and `keep`), `settings_of` giving every key of a defaults table the same spec; `create_settings_store(tables, { app })` merges them, refusing a key declared twice, and gives the migration, the synced table entry with its `local_keys`, `defaults`, the `user_only` set, `is_user_only_call` for `page_only_calls` (a user-only write, an import holding one, an export with secrets), `is_device_only` for `register_sync_routes`, `value_of`, and `get_settings`, `set_setting`, `export_settings` and `import_settings` with their api specs. Secrets read as `hidden_secret` and are kept when it comes back; the settings file is the standard's `{ app, kind: "settings", version, exported_at, settings }`, an import ignoring unknown keys and those of one device. `read_setting`, `write_setting` and `read_stored_settings` reach rows directly. No `node:` or DOM imports. |
34
+ | `caller` | Who is making the call in hand: `as_caller("page" \| "program" \| "engine", work)` around a call's synchronous part, `current_caller()` read by a store, and `caller_of(request)` (a token is a program). |
34
35
  | `api_spec` | An app's calls described once for other programs: `ApiSpec` gives each method its words and a JSON Schema per argument, so a method without one fails to compile; `input_schema` takes the arguments as one object, `positional_args` puts named arguments back in the method's order from a spec or any `NamedParams`, `openapi_document` writes an OpenAPI 3.1 document with one POST per call, and `route_openapi_document` one for REST routes such as `server/mcp`'s `route_tools` serves, each under its own path and verb with its path, query and body arguments; `check_known_ids` refuses a call naming an id that does not exist, such as "no such track a1", before it acts, `unknown_ids` lists them, and `keep_known_ids` cuts a remembered list, such as picked columns, down to the ids that still exist. A spec marked `page_only: true` is a call only the user may make at the app's own page (a signed-in browser, or a desktop window through its daemon's socket), such as approving what an assistant proposed: `page_only_calls(api, { rule?, refusal? })` gives the `PageOnlyCalls` the other modules take (`is_page_only(method)` for the marks, `is_page_only_call(method, args)` adding the app's `rule(method, args)` such as a write to some settings, `is_page_only_request(method, body)` for arguments as a list or by name, unchecked so a call with wrong names is left to refuse them itself, and the `refusal` text, `default_page_only_refusal` unless set), and both OpenAPI documents mark such a call with `x-page-only: true` and a 403. |
35
36
  | `filter`, `filter_sql` | Filters as one JSON tree of conditions under and, or and not, over fields the app lists in a catalogue (`define_catalogue`): a column, an SQL expression over the row, a related table matched when any of its rows matches, a set of values in a link table, kept as they are or once in a table of their own, or a `custom` field; tables and columns named as text or as the Drizzle schema's own objects. `compile_filter` makes one parameterised query for any `SqlDatabase` (`query_rows`), missing values last whichever way it sorts and ties broken by id so pages never shift, and a `random` sort key's whole-number `seed` giving the same shuffle each time, in SQL and in memory (`shuffle_position`); `compile_group_by` counts and sums each value of a field for panes; `evaluate` and `select_ids` check records in memory and `sort_records` sorts them, with exactly the same answers and order, which a property test holds them to; text, number, set and date operators, `top` and `bottom`, `in_last` in milliseconds, seconds or ISO dates, `in_filter` for a saved filter with `find_cycle`, the app's own `operators` such as full-text search, `regexp_matches` for the REGEXP a `regex` calls, and `FilterStack`, the removable chips a view shows. |
36
37
  | `filter_query` | `parse_filter_query`: search text such as `artist:beatles rating:>3 year:1965..1970 -live played:<30d` read into one filter over the fields the app lists (text, set, number or date, each with the names users type), so one search box serves every field. A text field takes `:` for contains, `=` for exact, `a,b` for either and `/pattern/` (matched with case, as `regex` is); a set field finds its listed values whatever their case; numbers take `>`, `>=`, `<`, `<=` and `a..b` through the field's own `parse_number`, such as stars into a rating; dates take `<30d` and `>6m` (h, d, w, m, y) and whole years, months or days such as `2024-03`, in the field's clock. A leading `-` leaves a term out. Each term comes back with where it is, its filter and a label for a chip, and `without_term` takes one out of the text; anything not readable as a field's condition is searched as words through the app's own text filter, never an error. |
@@ -38,8 +39,9 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
38
39
  | `email_links` | `bare_message_id` and `email_uri`: an email linked by its Message-ID as an RFC 2392 `mid:` link, which mail programs such as Thunderbird open wherever the message was filed. |
39
40
  | `snippets` | `shorten(text, length = 200)`: text put on one line and cut with an ellipsis, for an excerpt under a title. |
40
41
  | `drizzle`, `drizzle_migrations` | Typed SQLite on Drizzle ORM 1.0.0-rc.5, chosen over Kysely and hand-written SQL because it types rows from one schema in TypeScript, writes the migration SQL from it with drizzle-kit and runs synchronously: `open_drizzle` over any `SqlDatabase`, and `drizzle_of`, which the stores call, making it once per connection, so the same queries run on node:sqlite and in a phone's page, `synced_tables` reading the sync list from the schema's primary keys, `migrate_drizzle` per owner, the schema builders and query operators so an app never imports Drizzle, with `AnySQLiteColumn` for a table whose rows point at its own, and `x-app-bundle-migrations <folder>`, which turns drizzle-kit's migration folders into an `index.ts` a server running .ts files can import. |
41
- | `sync_engine`, `sync_peer`, `sync_protocol`, `sync_seal`, `server/sync_peer_routes`, `sync_peer_discovery`, `sync_peer_listening` | SQLite kept alike on every device with no server: `create_sync_engine` stamps each value of the tables it is given through triggers, so the app's own writes need no change, and the newest write of each value wins, each key of a table's `map_columns` (JSON objects such as ids from many sources) counting as a value of its own so two devices adding different keys keep both. Every copy is a peer: `create_sync_peer` pairs with another device through a one-time code (`create_pairing_code`, `pair_device`), the two copies merging with nothing asked, then sends each paired device its changes within seconds, takes theirs in the same round trip, holds a waiting call open to hear of theirs at once, and passes on what it took from the others, so devices that never reach each other still end up alike; the group's list of devices travels too, so a new device is introduced to the rest and a removed one (`remove_device`) is refused by all. Each call is sealed with both devices' keys on tweetnacl's box (`sync_seal`), chosen over TLS with pinned certificates because it runs alike on Node and in a phone's page and needs no certificate, so a call may travel over plain http on a home network. After a restore (`forget_history`) each peer is made to match the restored copy once, keeping a copy of its own first. `register_sync_peer_routes` answers other devices at `sync/peer` under a daemon's prefix, `listen_for_peers` opens a desktop daemon's own port for them, `discover_peers` finds paired devices on the local network by mDNS, on bonjour-service, and `keep_listening_for_peers` (`sync_peer_listening`) is a desktop daemon's "Let other devices connect" setting, kept in a file beside the database, whose `PeerListeningMethods` the page shows with `PeerListeningSettings`. |
42
+ | `sync_engine`, `sync_peer`, `sync_protocol`, `sync_seal`, `server/sync_peer_routes`, `sync_peer_discovery`, `sync_peer_listening` | SQLite kept alike on every device with no server: `create_sync_engine` stamps each value of the tables it is given through triggers, so the app's own writes need no change, and the newest write of each value wins, each key of a table's `map_columns` (JSON objects such as ids from many sources) counting as a value of its own so two devices adding different keys keep both. Every copy is a peer: `create_sync_peer` pairs with another device through a one-time code (`create_pairing_code`, `pair_device`), the two copies merging with nothing asked, then sends each paired device its changes within seconds, takes theirs in the same round trip, holds a waiting call open to hear of theirs at once, and passes on what it took from the others, so devices that never reach each other still end up alike; the group's list of devices travels too, so a new device is introduced to the rest and a removed one (`remove_device`) is refused by all. Each call is sealed with both devices' keys on tweetnacl's box (`sync_seal`), chosen over TLS with pinned certificates because it runs alike on Node and in a phone's page; calls still travel over https only. After a restore (`forget_history`) each peer is made to match the restored copy once, keeping a copy of its own first. `register_sync_peer_routes` answers other devices at `sync/peer` under a daemon's prefix, `listen_for_peers` opens a desktop daemon's own port for them, `discover_peers` finds paired devices on the local network by mDNS, on bonjour-service, and `keep_listening_for_peers` (`sync_peer_listening`) is a desktop daemon's "Let other devices connect" setting, kept in a file beside the database, which answers over https with a self-signed certificate made once (`peer_certificate`, on selfsigned, chosen because it makes one with Node's own crypto) and whose `PeerListeningMethods`, its fingerprint included, the page shows with `PeerListeningSettings`; `SyncSettings` given `certificates` asks to review and trust that certificate when pairing fails over it, and pairs again. |
42
43
  | `sync_files`, `node_file_store`, `electron/file_protocol` | Files that sync beside the rows that name them, such as covers or photos, so a large picture never travels with every change: each is named by the sha256 of its bytes (`hash_bytes`, `put_file`, `is_file_name`) and kept in a `SyncFileStore`, a folder on Node (`folder_file_store`, written through a rename) or IndexedDB on a phone (`indexed_db_files`); given `files: { store, referenced }`, the sync peer sends each paired device the named files it lacks and fetches those this device lacks after each exchange, a few at a time, trying a file neither has yet again next round, and keeps the ones it is sent, refusing bytes that do not match their name; `register_file_scheme` and `serve_files` show them in a desktop page as `<scheme>://<name>`. |
44
+ | `app_android` | `x-app-android [app folder]`: the app's Capacitor project in `android/`, made from Capacitor's template when it is missing, given X-App's `config/android/release.gradle` (the version CI hands each build, and signing when the release key is in the environment), its launcher icons from `x-app-icons`, then `cap sync android`. Run after the Android page is built; the app keeps `android/` out of git. |
43
45
  | `app_icons` | `x-app-icons [app folder]`: every icon an app ships generated from its `resources/icon.svg`, as the Design Guidelines ask: `resources/icon.png` for the desktop, the Android launcher icons at each density with an adaptive icon on white when there is an `android/` project, and `icon.svg`, `icon-192.png` and `icon-512.png` in `src/web/public` when there is one. Drawn with `@resvg/resvg-js`, an optional peer the app installs as a dev dependency. |
44
46
  | `change_checks`, `change_checks_git`, `change_checks_cli` | Checks on a change that any repository's CI runs, as `x-app-check` (see [Change checks](#change-checks)): `commits` (Conventional Commits, the `Assisted-by` trailer in the organisation's repositories and nowhere else, no AI mention outside it), `secrets` (keys and tokens in added lines, commit messages and added `.env` files, naming only the kind and place, never the value), `leftovers` (console logging, `debugger`, code commented out, a TODO without an issue), `comments` (a comment longer than one line, but for a file's overview), `coverage` (a floor lowered or code newly left out), `x-libs` (an import of a library X-App wraps) and `dependencies` (each new one named with its licence, failing a licence not allowed, read as SPDX by `spdx-satisfies`); each a pure function on a described `Change` giving `{ gate, outcome, findings }` with file:line, reading only the code around strings and regular expressions; `create_check_registry` for an app's own checks, `x_tech_options` the defaults, and `read_change` reading a change from git, its `base` resolved to a commit; `run_check_command` runs the command for an app with its own checks, defaults and name. |
45
47
  | `certificates`, `certificate_protocol`, `electron/certificates` | Servers whose https certificate the device refuses, such as a home server's self-signed one: `check_certificate` reads the certificate and what is wrong with it (self-signed, unknown authority, wrong name, expired, not yet valid), `create_certificate_trust` keeps the ones the user trusts in a JSON file, each for its own host and exact fingerprint, re-checked before it is saved, and its `methods` are the page's calls; `trust_in_session` makes Chromium accept them in a session, the window's from the next start, and `trusting_fetch` sends the main process's requests, such as the sync client's, through a Chromium session made fresh each time the list changes, so a new choice holds at once; `use_in_node` also hands them to Node's own https, which then accepts a self-signed server whose name matches. |
@@ -94,7 +96,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
94
96
  | `server/backup_routes`, `web/backups` | A server's backups for the page's `BackupSettings`: `register_backup_routes` serves the list, backing up now, the daily schedule, restoring and deleting, with the schedule in a JSON file through `json_backup_schedule`; `backup_client` is the page's side. |
95
97
  | `server/sign_in`, `server/login_page` | `register_token_sign_in`: a server with one secret signs browsers in on its own login page, keeps them in by an HMAC-derived cookie, takes the secret as a bearer header, waits after a wrong try, answers 429 with Retry-After once an address has `address_tries_allowed` (20) wrong tries in `address_try_window_seconds` (300), on the login page or as a bearer header on a guarded path, the right ones not counted and a request without one never, and turns the rest away (401 in text or JSON under the API prefix, 303 to the login page elsewhere, with open paths); `register_sign_in_guard` is the turning-away alone, for an app with its own sessions, and given `address_tries` it counts a bearer header that does not sign in against that `AttemptLimit`. Both judge the path as the router reads it, count any route matched under the API prefix as the API, and answer 400 to a path that reads two ways (see `server/request_path`). |
96
98
  | `server/request_path` | `path_of`: a request's path as Fastify's router reads it (escapes decoded as it decodes them, its semicolon, trailing-slash, duplicate-slash and case options followed); `route_of`: the matched route's pattern; `is_plain_path`: false for a path that reads two ways (an escaped letter, digit or `-._~`, a `#`, a target not starting with `/`, an empty, `.` or `..` segment, or a path not beginning as its route does), which the sign-in guards refuse. Escapes such as `%20` and `%2F` stay allowed. |
97
- | `server/account_store` | `AccountStore`: users with the app's ordered roles and its own access rules, checked by `check_access`, the accounts file's users declared at the highest role, second factor with recovery codes, sessions and tokens, all in the app's SQLite database under `account_*` tables. Request handlers call `authenticate_async`, `change_password_async`, `create_user_async` and `update_user_async`, which hash in `password_hashes` (`shared_password_hashes` unless set); the synchronous ones stay for scripts and tests. A user gets `secret_tries_allowed` (5) wrong second-factor or recovery codes, signing in or turning the second factor off, in `secret_try_window_seconds` (300), and as many wrong current passwords apart from those, before waiting: `authenticate` then answers `retry_after_seconds` and the others throw a 429 `AccountError` carrying it. `token_scopes` names the narrower tokens the app offers beside full and read-only ones, such as `{ add_items: { label: "Add items", hint, calls: ["add_item"] } }`: a token made with `create_token(owner, { name, read_only, scope })` reads as a read-only one does and may also make its scope's calls. A token lasts `days` when given; `longest_token_days` caps that and is how long a token lasts without it, and an ended token no longer signs in. Each token has a `kind`: `device` when the device sign-in made it (`create_token(..., { kind: "device" })`, always a full token), `program` for one made on the account page; a full, unscoped token made before kinds were kept counts as a device, so no device is cut off, and the token lists show a device chip so a program's token from then can be revoked. |
99
+ | `server/account_store` | `AccountStore`: users with the app's ordered roles and its own access rules, checked by `check_access`, the accounts file's users declared at the highest role, second factor with recovery codes, sessions and tokens, all in the app's SQLite database under `account_*` tables. `move_accounts(from, to)` moves them, as they are, out of an app's own database into their own once, and `holds_accounts` says whether a database keeps them. Request handlers call `authenticate_async`, `change_password_async`, `create_user_async` and `update_user_async`, which hash in `password_hashes` (`shared_password_hashes` unless set); the synchronous ones stay for scripts and tests. A user gets `secret_tries_allowed` (5) wrong second-factor or recovery codes, signing in or turning the second factor off, in `secret_try_window_seconds` (300), and as many wrong current passwords apart from those, before waiting: `authenticate` then answers `retry_after_seconds` and the others throw a 429 `AccountError` carrying it. `token_scopes` names the narrower tokens the app offers beside full and read-only ones, such as `{ add_items: { label: "Add items", hint, calls: ["add_item"] } }`: a token made with `create_token(owner, { name, read_only, scope })` reads as a read-only one does and may also make its scope's calls. A token lasts `days` when given; `longest_token_days` caps that and is how long a token lasts without it, and an ended token no longer signs in. Each token has a `kind`: `device` when the device sign-in made it (`create_token(..., { kind: "device" })`, always a full token), `program` for one made on the account page; a full, unscoped token made before kinds were kept counts as a device, so no device is cut off, and the token lists show a device chip so a program's token from then can be revoked. |
98
100
  | `server/account_sign_in` | `register_accounts`: the standard sign-in. A name and password (then the code when the user has a second factor), single sign-on or a trusted proxy opens a session kept in the database; "Keep me signed in" unticked ends it with the browser, ticked keeps it until revoked, both bounded by `session_seconds` and `remembered_seconds`. One name from one address gets `tries_allowed` (5) tries in `try_window` ("5 minutes"), and one address gets `address_tries_allowed` (20) failing or running sign-ins in `address_try_window_seconds` (300) whatever names it gives, a right password not counted, with each wrong bearer token on a guarded path counted in the same limit and a right one refused too once it is used up; either answers 429 `{ error }` with Retry-After, the same for a name that exists and one that does not, and a code refused by the store's own limit adds `code_needed` (see [Accounts](#accounts)). `second_factor_from` names the lowest role that must use a second factor: until such a user sets one up, their session only reads, signs out and sets up the second factor or password, and cannot make tokens or sign in devices; `/api/me` says so with `second_factor_needed`. A device signs in with `device` and gets a token of kind `device` instead; a request's `viewer.token_kind` says which kind of token it came with (a declared token's is `program`), and `is_user_or_device(viewer)` whether it is the user at the page or on one of their devices rather than a program. It also serves the account routes (password, second factor, sessions, tokens), the admin's users and tokens, and checks each app route, and any `guarded_paths` outside the API such as `/metrics`, against `needed(method, path, route)`, which gets the path as the router reads it and the matched route's pattern (such as `/api/builds/:id`, or null); `open_prefixes` leaves routes that check their own credentials, such as a push URL, open; a read-only token only reads, except on `read_only_paths` such as `/api/mcp` that keep it to reading themselves. Given `call_of` (such as `calls_under("/api/call")` for a call table) and `is_read_only`, a read-only token may also POST the calls that only read, and a scoped token its scope's calls, on the API as over MCP; `GET <api>/account/token_scopes` lists the scopes for the token form. Given `call_of` and `page_only` (from `api_spec`'s `page_only_calls`), every token, a device's included, is refused the calls only the user at the page may make, by their marks before the body is read and by the app's rule once it is; a session or the trusted proxy makes them. |
99
101
  | `server/account_prefs` | Each signed-in user's own preferences kept on the server, so they follow the user between devices, such as their dashboards: `register_accounts` given `prefs: { keys, largest_bytes }` serves `GET` and `PUT <api>/account/prefs/<key>` (`{ value }` in, `{ key, value, changed_epoch }` out, a null value and time when none is kept), each key the app allows with a check that hands back the value to keep or throws, an unknown key refused (404), a stored value its check no longer passes read as none, a value over `largest_bytes` (`default_largest_pref_bytes`, 256 KB) refused (413); a user only reaches their own, a token may read them but only a full one write, a read-only token or a session waiting for its second factor only reads, and a token from the config has none. They live in `account_prefs`, one row per user and key, and go with the user; `read_account_pref` and `write_account_pref` do the same from the app's own code. |
100
102
  | `server/totp`, `server/oidc` | Authenticator-app codes (RFC 6238) and their `otpauth://` links; `OidcClient`, single sign-on by the code flow with PKCE and a checked ID token, set up from `<PREFIX>_OIDC_*` by `oidc_from_environment`. |
@@ -217,9 +219,13 @@ The rest of an app's files are short calls into X-App too:
217
219
  - **Nix**: X-App's flake has a `lib` with `package`, `desktop_package`, `module`, `shell` and `android_shell`, each
218
220
  taking the app's package set and its `nix/app.nix` (name, display name, variables' prefix, port, database file and
219
221
  words); the app's `nix/flake.nix` takes `github:x-tech-laboratories/X-App` as an input and calls them.
222
+ - **Android**: `npm run build:android` builds the phone's page and runs `x-app-android`, which makes or updates the
223
+ Capacitor project in `android/`, so the app keeps only `capacitor.config.json` and leaves `android/` out of git.
220
224
  - **CI**: the app's `ci` job runs `x-tech-laboratories/X-App/.github/actions/app-ci@main`, its `nix` job
221
- `app-nix@main` with the targets to build, and its Dependabot workflow `app-dependabot-auto-merge@main`. They are
222
- composite actions, so the jobs keep the names `ci` and `nix` the ruleset requires.
225
+ `app-nix@main` with the targets to build, an Android app's `android` job `app-android@main` with the release key's
226
+ secrets (the APK as the run's artifact, and a GitHub release from a `v*` tag), and its Dependabot workflow
227
+ `app-dependabot-auto-merge@main`. They are composite actions, so the jobs keep the names `ci` and `nix` the ruleset
228
+ requires.
223
229
 
224
230
  `npx x-app-new X-Notes` writes all of it for a new app.
225
231
 
@@ -425,10 +431,8 @@ const sync = create_sync_peer({ ...options, storage: local_sync_storage({ key: "
425
431
  ```
426
432
 
427
433
  The bridge answers `sync_device_methods(sync)`, and the Sync section is `SyncSettings`, with
428
- `<PeerListeningSettings listening={...} />` in its `extra` on the desktop. A server lets the route through its sign-in
429
- with `open_paths: ["/api/sync/peer"]`, since every call carries its own seal. A phone's page reaches a
430
- desktop daemon over plain http, so its Capacitor config sets `android.allowMixedContent`; every call is sealed, so
431
- nothing travels readable. A restore runs `after_restore: engine.forget_history`, and each paired device is then made
434
+ `<PeerListeningSettings listening={...} />` in its `extra` and `certificates` on the desktop and the phone, so the other device's self-signed certificate is reviewed and trusted when pairing first reaches it. A server lets the route through its sign-in
435
+ with `open_paths: ["/api/sync/peer"]`, since every call carries its own seal, and serves `sync_device_methods(sync)` as a call table under `/api/sync/` that only an admin may reach, for the browser's Sync section. Every peer answers over https; a desktop's certificate is its own and self-signed, so the other device's user checks the fingerprint its Sync section shows before trusting it. A restore runs `after_restore: engine.forget_history`, and each paired device is then made
432
436
  to match the restored copy, backing itself up first.
433
437
 
434
438
  ## A pane on the right
@@ -0,0 +1,25 @@
1
+ // X-App's release settings for an X-app's Android package, which x-app-android applies from android/app/build.gradle.
2
+ // CI numbers each build and names it after its version tag, so the phone and Obtainium see it as an update, and signs
3
+ // it when the release key is in the environment; a build without the key stays unsigned.
4
+ android {
5
+ defaultConfig {
6
+ versionCode((System.getenv("ANDROID_VERSION_CODE") ?: "1") as Integer)
7
+ versionName System.getenv("ANDROID_VERSION_NAME") ?: "0.0.0-dev"
8
+ }
9
+ def keystore_file = System.getenv("ANDROID_KEYSTORE_FILE")
10
+ if (keystore_file) {
11
+ signingConfigs {
12
+ release {
13
+ storeFile file(keystore_file)
14
+ storePassword System.getenv("ANDROID_KEYSTORE_PASSWORD")
15
+ keyAlias System.getenv("ANDROID_KEY_ALIAS")
16
+ keyPassword System.getenv("ANDROID_KEYSTORE_PASSWORD")
17
+ }
18
+ }
19
+ buildTypes {
20
+ release {
21
+ signingConfig signingConfigs.release
22
+ }
23
+ }
24
+ }
25
+ }
@@ -1,6 +1,7 @@
1
- import type { ApiSpec } from "../api_spec.ts";
1
+ import { type ApiSpec, type PageOnlyCalls } from "../api_spec.ts";
2
2
  import { type BackupMethods, type Backups, type BackupNaming } from "../backups.ts";
3
3
  import type { BackupSchedule } from "../backup_protocol.ts";
4
+ import { type Caller } from "../caller.ts";
4
5
  import { type CertificateMethods } from "../certificate_protocol.ts";
5
6
  import { type ConnectionMethods } from "../connection_protocol.ts";
6
7
  import { type Bridge } from "../electron/bridge.ts";
@@ -21,6 +22,8 @@ export interface Feature<Methods extends Record<string, StoreMethod> = Record<st
21
22
  api: ApiSpec<Methods>;
22
23
  settings?: Record<string, SettingSpec>;
23
24
  histories?: readonly KeptHistory[];
25
+ on_open?: (database: SqlDatabase) => void;
26
+ after_write?: (database: SqlDatabase) => void;
24
27
  }
25
28
  export declare function define_feature<Methods extends Record<string, StoreMethod>>(feature: Feature<Methods>): Feature<Methods>;
26
29
  export declare function is_read_only(method: string): boolean;
@@ -49,6 +52,8 @@ export interface AppOptions<Features extends readonly Feature[]> {
49
52
  settings?: Record<string, SettingSpec>;
50
53
  settings_descriptions?: SettingsStoreOptions["descriptions"];
51
54
  setting_key_example?: string;
55
+ page_only_refusal?: string;
56
+ token_prefix?: string;
52
57
  }
53
58
  export declare const base_setting_defaults: {
54
59
  history_days: number;
@@ -90,6 +95,8 @@ export declare function define_app<const Features extends readonly Feature[]>(op
90
95
  settings?: Record<string, SettingSpec>;
91
96
  settings_descriptions?: SettingsStoreOptions["descriptions"];
92
97
  setting_key_example?: string;
98
+ page_only_refusal?: string;
99
+ token_prefix?: string;
93
100
  features: readonly Feature<Record<string, StoreMethod>>[];
94
101
  settings_store: SettingsStore;
95
102
  setting_defaults: Readonly<import("../settings.ts").Settings>;
@@ -117,7 +124,8 @@ export declare function define_app<const Features extends readonly Feature[]>(op
117
124
  method_names: ((keyof UnionToIntersection<Features[number]["methods"]> | keyof SettingsMethods) & string)[];
118
125
  api_spec: ApiSpec<Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>>;
119
126
  is_read_only: typeof is_read_only;
120
- bind_methods: (database: () => SqlDatabase, on_change: () => void) => Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>;
127
+ page_only: PageOnlyCalls;
128
+ bind_methods: (database: () => SqlDatabase, on_change: () => void, caller?: Caller) => Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>;
121
129
  backup_naming: BackupNaming;
122
130
  read_backup_schedule: (database: SqlDatabase) => BackupSchedule;
123
131
  backup_methods: (kept: Restorable, database: () => SqlDatabase, check_schedule: () => void) => BackupMethods;
@@ -126,7 +134,7 @@ export declare function define_app<const Features extends readonly Feature[]>(op
126
134
  type ErasedCalls = any;
127
135
  export type App = Omit<ReturnType<typeof define_app<readonly Feature[]>>, "bridges" | "bind_methods" | "api_spec" | "method_names"> & {
128
136
  bridges: AppBridges<ErasedCalls>;
129
- bind_methods: (database: () => SqlDatabase, on_change: () => void) => ErasedCalls;
137
+ bind_methods: (database: () => SqlDatabase, on_change: () => void, caller?: Caller) => ErasedCalls;
130
138
  api_spec: ApiSpec<ErasedCalls>;
131
139
  method_names: readonly string[];
132
140
  };
@@ -2,7 +2,10 @@
2
2
  // and settings. define_app puts them together into the one database every device keeps, the calls the page makes
3
3
  // through whichever host it runs on, and the names every host shares, so the server, the daemon, the desktop window and
4
4
  // the page are all run from the same object.
5
+ // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { page_only_calls } from "../api_spec.js";
5
7
  import { backup_naming, default_backup_schedule } from "../backups.js";
8
+ import { as_caller } from "../caller.js";
6
9
  import { certificate_method_names } from "../certificate_protocol.js";
7
10
  import { connection_method_names } from "../connection_protocol.js";
8
11
  import { define_bridge } from "../electron/bridge.js";
@@ -71,6 +74,8 @@ export function define_app(options) {
71
74
  for (const history of histories)
72
75
  history.install(database);
73
76
  sync_engine.install(database);
77
+ for (const feature of features)
78
+ feature.on_open?.(database);
74
79
  prune_history(database);
75
80
  }
76
81
  // Versions older than the days set go, each item keeping its newest; 0 keeps them all.
@@ -87,15 +92,21 @@ export function define_app(options) {
87
92
  const method_names = Object.keys(all_methods);
88
93
  // Every call described once, for MCP and OpenAPI.
89
94
  const api_spec = Object.assign({}, ...features.map((feature) => feature.api));
90
- // The calls run on the database given, telling on_change after each write so the other pages and devices hear of it.
91
- function bind_methods(database, on_change) {
95
+ // The calls a spec marks page-only and the writes of settings only the user may change, which every host refuses a
96
+ // token and an MCP client.
97
+ const page_only = page_only_calls(api_spec, { rule: settings_store.is_user_only_call, ...(options.page_only_refusal ? { refusal: options.page_only_refusal } : {}) });
98
+ // The calls run on the database given as the caller given, telling on_change after each write so the other pages
99
+ // and devices hear of it.
100
+ function bind_methods(database, on_change, caller = "page") {
92
101
  const bound = method_names.map((name) => {
93
102
  const method = all_methods[name];
94
103
  const call = (...args) => {
95
- const result = method(database(), ...args);
104
+ const result = as_caller(caller, () => method(database(), ...args));
96
105
  if (is_read_only(name))
97
106
  return result;
98
107
  const done = (value) => {
108
+ for (const feature of features)
109
+ feature.after_write?.(database());
99
110
  for (const history of histories)
100
111
  history.record(database());
101
112
  on_change();
@@ -160,6 +171,7 @@ export function define_app(options) {
160
171
  method_names,
161
172
  api_spec,
162
173
  is_read_only,
174
+ page_only,
163
175
  bind_methods,
164
176
  backup_naming: naming,
165
177
  read_backup_schedule,
@@ -24,6 +24,7 @@ export interface ServerOptions {
24
24
  changes: EventStream;
25
25
  backup_methods: BackupMethods;
26
26
  }
27
+ export declare const user_only_backup_calls: ReadonlySet<string>;
27
28
  export declare function build_server(app: App, options: ServerOptions): Promise<FastifyInstance>;
28
29
  export interface RunServerOptions {
29
30
  web_folder: URL;
@@ -10,8 +10,9 @@ import { fileURLToPath } from "node:url";
10
10
  import fastify, {} from "fastify";
11
11
  import { openapi_document, positional_args } from "../api_spec.js";
12
12
  import { keep_backing_up } from "../backups.js";
13
- import { register_accounts } from "../server/account_sign_in.js";
14
- import { AccountStore } from "../server/account_store.js";
13
+ import { calls_under, register_accounts } from "../server/account_sign_in.js";
14
+ import { caller_of } from "../caller.js";
15
+ import { AccountStore, holds_accounts, move_accounts } from "../server/account_store.js";
15
16
  import { register_call_table } from "../server/call_table.js";
16
17
  import { read_server_config } from "../server/config.js";
17
18
  import { EventStream } from "../server/events.js";
@@ -86,7 +87,7 @@ export function register_app_calls(api, app, database, changes) {
86
87
  catch (error) {
87
88
  return send_text(reply, 400, error.message);
88
89
  }
89
- const methods = app.bind_methods(database, () => changes.announce_change(changes.client_id_of(request)));
90
+ const methods = app.bind_methods(database, () => changes.announce_change(changes.client_id_of(request)), caller_of(request));
90
91
  const result = await app.bridges.calls.dispatch(methods, request.params.method, args);
91
92
  if (result === undefined)
92
93
  return reply.code(204).send();
@@ -98,7 +99,9 @@ export function register_app_calls(api, app, database, changes) {
98
99
  });
99
100
  }
100
101
  // The server's backups and its sync peer's pairings, which only an admin reaches.
101
- const admin_paths = ["/api/backups/", "/api/device/"];
102
+ const admin_paths = ["/api/backups/", "/api/sync/"];
103
+ // Backup calls only the user at the page may make, since a restored backup could undo what only the user may change.
104
+ export const user_only_backup_calls = new Set(["restore_backup", "remove_backup", "set_backup_schedule"]);
102
105
  export async function build_server(app, options) {
103
106
  const server = fastify({ forceCloseConnections: true });
104
107
  register_lenient_json_body(server);
@@ -111,6 +114,10 @@ export async function build_server(app, options) {
111
114
  // A read-only token may still list and read through MCP, which posts every request.
112
115
  read_only_paths: ["/api/mcp"],
113
116
  needed: (_method, path) => (admin_paths.some((admin_path) => path.startsWith(admin_path)) ? { role: options.accounts.top_role } : "any"),
117
+ // 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.
118
+ call_of: calls_under("/api/call"),
119
+ is_read_only: app.is_read_only,
120
+ page_only: app.page_only,
114
121
  });
115
122
  const { changes, database } = options;
116
123
  const description = { title: app.name, version: app.version, description: app.instructions };
@@ -125,10 +132,14 @@ export async function build_server(app, options) {
125
132
  instructions: app.instructions,
126
133
  api: app.api_spec,
127
134
  is_read_only: app.is_read_only,
128
- call: (method, args) => app.bridges.calls.dispatch(app.bind_methods(database, () => changes.announce_change()), method, args),
135
+ page_only: app.page_only,
136
+ call: (method, args) => app.bridges.calls.dispatch(app.bind_methods(database, () => changes.announce_change(), "program"), method, args),
129
137
  });
130
138
  // The server's backups, as the page's Settings reach them.
131
139
  api.post("/backups/:method", async (request, reply) => {
140
+ const via = request.viewer?.via;
141
+ if (user_only_backup_calls.has(request.params.method) && via !== "session" && via !== "proxy")
142
+ return send_text(reply, 403, app.page_only.refusal);
132
143
  const args = request.body ?? [];
133
144
  if (args === BAD_JSON || !Array.isArray(args))
134
145
  return send_text(reply, 400, "send the arguments as a JSON list");
@@ -138,7 +149,7 @@ export async function build_server(app, options) {
138
149
  return reply.type("application/json").header("cache-control", "no-store").send(JSON.stringify(result));
139
150
  });
140
151
  register_sync_peer_routes(api, options.sync);
141
- register_call_table(api, "/device", sync_device_methods(options.sync), { is_read_only: app.is_read_only });
152
+ register_call_table(api, "/sync", sync_device_methods(options.sync), { is_read_only: app.is_read_only });
142
153
  }, { prefix: "/api" });
143
154
  await register_web_folder(server, { folder: options.web_folder });
144
155
  return server;
@@ -166,9 +177,15 @@ export async function run_server(app, options) {
166
177
  const opened = open_app_database(app, database_path, resolve(config.backups_folder));
167
178
  // Accounts are a file of their own beside the data, so restoring it never changes who can sign in.
168
179
  const accounts_database = new DatabaseSync(join(dirname(database_path), "accounts.db"));
180
+ // An older version kept them in the data's own file; they move out once, after a backup of the file as it was.
181
+ if (holds_accounts(opened.database()) && !holds_accounts(accounts_database)) {
182
+ await opened.back_up();
183
+ move_accounts(opened.database(), accounts_database);
184
+ }
169
185
  const accounts = new AccountStore({
170
186
  database: accounts_database,
171
187
  app_name: app.name,
188
+ ...(app.token_prefix ? { token_prefix: app.token_prefix } : {}),
172
189
  declared: load_accounts(`${prefix}_PASSWORD_HASH_FILE`, server_config.values.password_hash_file),
173
190
  });
174
191
  // Every page hears of a change, whether a page or another device made it.
@@ -7,7 +7,8 @@ import { LoginNeeded } from "../../web/states.js";
7
7
  // Relative, so a server behind a proxy under a folder keeps it.
8
8
  const call_path = "api/call/";
9
9
  const backups_path = "api/backups/";
10
- const device_path = "api/device/";
10
+ // The server's own sync calls sit beside the route paired devices sync through.
11
+ const device_path = "api/sync/";
11
12
  const events_path = "api/events";
12
13
  const client_id_header = "x-client-id";
13
14
  const reconnect_delay_ms = 5000;
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ export declare const release_line = "apply from: \"../../node_modules/@x-tech-laboratories/x-app/config/android/release.gradle\"";
3
+ export declare function apply_release_settings(app_folder: string): boolean;
4
+ export type RunCapacitor = (app_folder: string, args: string[]) => void;
5
+ export declare function prepare_android(app_folder: string, run?: RunCapacitor): string[];
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ // The `x-app-android [app folder]` command: an app's Android project, made and kept up to date from X-App, so no app
3
+ // keeps Capacitor's generated project by hand. It adds the project from Capacitor's template when the app has none,
4
+ // applies X-App's release settings (the version CI gives each build, and signing when the release key is present),
5
+ // draws the launcher icons from `resources/icon.svg`, and syncs the built page and plugins into it. Run it after the
6
+ // Android page is built, since Capacitor copies that page in.
7
+ // ── Imports ──────────────────────────────────────────────────────────────────
8
+ import { spawnSync } from "node:child_process";
9
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { join, resolve } from "node:path";
11
+ import { write_app_icons } from "./app_icons.js";
12
+ // ── Release settings ─────────────────────────────────────────────────────────
13
+ // The line that applies X-App's release settings, from the app's own node_modules so it follows X-App's version.
14
+ export const release_line = `apply from: "../../node_modules/@x-tech-laboratories/x-app/config/android/release.gradle"`;
15
+ // Adds the release line to the app module's build file once, and says whether it had to.
16
+ export function apply_release_settings(app_folder) {
17
+ const build_file = join(app_folder, "android", "app", "build.gradle");
18
+ const build = readFileSync(build_file, "utf8");
19
+ if (build.includes(release_line))
20
+ return false;
21
+ writeFileSync(build_file, `${build.trimEnd()}\n\n// X-App's release settings: the build's version and, when the key is present, its signature.\n${release_line}\n`);
22
+ return true;
23
+ }
24
+ const run_capacitor = (app_folder, args) => {
25
+ const result = spawnSync("npx", ["cap", ...args], { cwd: app_folder, stdio: "inherit" });
26
+ if (result.status !== 0)
27
+ throw new Error(`cap ${args.join(" ")} failed`);
28
+ };
29
+ // Brings the app's Android project up to date and returns what it did, one line each.
30
+ export function prepare_android(app_folder, run = run_capacitor) {
31
+ if (!existsSync(join(app_folder, "capacitor.config.json")))
32
+ throw new Error(`no Android app: ${join(app_folder, "capacitor.config.json")} is missing`);
33
+ const done = [];
34
+ if (!existsSync(join(app_folder, "android"))) {
35
+ run(app_folder, ["add", "android"]);
36
+ done.push("Added the Android project from Capacitor's template");
37
+ }
38
+ if (apply_release_settings(app_folder))
39
+ done.push("Applied X-App's release settings");
40
+ done.push(`Drew ${write_app_icons(app_folder).length} icons`);
41
+ run(app_folder, ["sync", "android"]);
42
+ done.push("Synced the page and plugins into the Android project");
43
+ return done;
44
+ }
45
+ if (import.meta.main) {
46
+ try {
47
+ for (const line of prepare_android(resolve(process.argv[2] ?? ".")))
48
+ console.info(line);
49
+ }
50
+ catch (error) {
51
+ console.error(error instanceof Error ? error.message : String(error));
52
+ process.exit(1);
53
+ }
54
+ }
package/dist/app_new.js CHANGED
@@ -40,7 +40,7 @@ function package_json(names, options) {
40
40
  ...(options.desktop ? { dev: `${prefix}_USER_DATA=\${${prefix}_USER_DATA:-dev-data/desktop} electron-vite dev -c config/electron.vite.config.ts` } : {}),
41
41
  build: "tsc -b && vite build -c config/vite.config.ts",
42
42
  ...(options.desktop ? { "build:desktop": "tsc -b && electron-vite build -c config/electron.vite.config.ts" } : {}),
43
- ...(options.android ? { "build:android": "tsc -b && vite build -c config/vite.android.config.ts && cap sync android" } : {}),
43
+ ...(options.android ? { "build:android": "tsc -b && vite build -c config/vite.android.config.ts && x-app-android" } : {}),
44
44
  start: "NODE_ENV=production node src/server/main.ts",
45
45
  ...(options.desktop ? { "start:desktop": "electron-vite preview -c config/electron.vite.config.ts" } : {}),
46
46
  typecheck: "tsc -b",
@@ -354,7 +354,8 @@ export default defineConfig(android_vite_config());
354
354
  }
355
355
  : {}),
356
356
  "config.example.json": json({ database: `dev-data/server/${names.short}.db`, backups_folder: "dev-data/server/backups" }),
357
- ".gitignore": [".claude/", "node_modules", "out/", "dist/", "result", "result-*", "*.tsbuildinfo", "dev-data/", "coverage/", ""].join("\n"),
357
+ // The Android project is Capacitor's template that x-app-android makes and keeps up to date, so it is not kept.
358
+ ".gitignore": [".claude/", "node_modules", "out/", "dist/", "result", "result-*", "*.tsbuildinfo", "dev-data/", "coverage/", ...(options.android ? ["android/"] : []), ""].join("\n"),
358
359
  };
359
360
  }
360
361
  function nix_files(names, options) {
@@ -411,13 +412,29 @@ in
411
412
  `,
412
413
  };
413
414
  }
415
+ // Every push to main builds the Android package once the tests pass, signed when the repository holds the release key,
416
+ // and a version tag publishes it as a release.
417
+ const android_job = `
418
+ android:
419
+ needs: ci
420
+ if: github.event_name != 'pull_request'
421
+ runs-on: ubuntu-latest
422
+ permissions:
423
+ contents: write
424
+ steps:
425
+ - uses: x-tech-laboratories/X-App/.github/actions/app-android@main
426
+ with:
427
+ keystore-base64: \${{ secrets.ANDROID_KEYSTORE_BASE64 }}
428
+ keystore-password: \${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
429
+ key-alias: \${{ secrets.ANDROID_KEY_ALIAS }}
430
+ `;
414
431
  function github_files(options) {
415
432
  return {
416
433
  ".github/workflows/ci.yml": `name: CI
417
434
 
418
435
  on:
419
436
  push:
420
- branches: [main]
437
+ branches: [main]${options.android ? '\n tags: ["v*"]' : ""}
421
438
  pull_request:
422
439
  branches: [main]
423
440
  workflow_dispatch:
@@ -435,7 +452,7 @@ jobs:
435
452
  - uses: x-tech-laboratories/X-App/.github/actions/app-nix@main
436
453
  with:
437
454
  targets: ./nix#default${options.desktop ? " ./nix#desktop" : ""}
438
- `,
455
+ ${options.android ? android_job : ""}`,
439
456
  ".github/workflows/dependabot-auto-merge.yml": `name: Dependabot auto-merge
440
457
 
441
458
  on: pull_request
@@ -601,7 +618,7 @@ if (import.meta.main) {
601
618
  console.info(`Wrote ${options.name} into ${folder}. Next:
602
619
  cd ${folder} && git init && npm install
603
620
  nix flake lock ./nix
604
- npm run icons${options.android ? "\n npx cap add android" : ""}
621
+ npm run icons
605
622
  npm test`);
606
623
  }
607
624
  catch (error) {
@@ -0,0 +1,4 @@
1
+ export type Caller = "page" | "program" | "engine";
2
+ export declare function as_caller<Result>(caller: Caller, work: () => Result): Result;
3
+ export declare function current_caller(): Caller;
4
+ export declare function caller_of(request: object): Caller;
package/dist/caller.js ADDED
@@ -0,0 +1,23 @@
1
+ // Who is making the call in hand: the user at the app's own page (a signed-in browser or the desktop window), the
2
+ // app's own assistant or background work acting on its own, or another program through a token or MCP. It is set
3
+ // around each call's synchronous part, which is where a store reads it.
4
+ let current = "page";
5
+ // Runs the work as the caller given; the caller before comes back once its synchronous part ends.
6
+ export function as_caller(caller, work) {
7
+ const before = current;
8
+ current = caller;
9
+ try {
10
+ return work();
11
+ }
12
+ finally {
13
+ current = before;
14
+ }
15
+ }
16
+ export function current_caller() {
17
+ return current;
18
+ }
19
+ // The caller a server request is: a token is a program, a browser signed in itself or through a proxy is the user.
20
+ export function caller_of(request) {
21
+ const viewer = request.viewer;
22
+ return viewer?.via === "token" ? "program" : "page";
23
+ }
@@ -0,0 +1,7 @@
1
+ export interface PeerCertificate {
2
+ cert: string;
3
+ key: string;
4
+ fingerprint: string;
5
+ }
6
+ export declare function make_peer_certificate(name: string, addresses: readonly string[]): Promise<PeerCertificate>;
7
+ export declare function read_or_make_peer_certificate(file: string, name: string, addresses: readonly string[]): Promise<PeerCertificate>;
@@ -0,0 +1,46 @@
1
+ // The https certificate a desktop daemon answers paired devices with: self-signed, made once on selfsigned and kept
2
+ // beside the database, so its fingerprint stays the same and a device that trusted it keeps reaching it. Only this user
3
+ // can read the file, since it holds the private key.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { X509Certificate } from "node:crypto";
6
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { hostname } from "node:os";
8
+ import { dirname } from "node:path";
9
+ import { generate } from "selfsigned";
10
+ const valid_years = 10;
11
+ // The names and addresses the certificate covers, so a device reaching one of them sees no wrong-name problem.
12
+ function alt_names(addresses) {
13
+ return [{ type: 2, value: hostname() }, { type: 2, value: `${hostname()}.local` }, { type: 2, value: "localhost" }, ...addresses.map((ip) => ({ type: 7, ip }))];
14
+ }
15
+ export async function make_peer_certificate(name, addresses) {
16
+ const now = new Date();
17
+ const until = new Date(now);
18
+ until.setFullYear(until.getFullYear() + valid_years);
19
+ const made = await generate([{ name: "commonName", value: name }], {
20
+ keyType: "ec",
21
+ curve: "P-256",
22
+ algorithm: "sha256",
23
+ notBeforeDate: now,
24
+ notAfterDate: until,
25
+ extensions: [{ name: "subjectAltName", altNames: alt_names(addresses) }],
26
+ });
27
+ return { cert: made.cert, key: made.private, fingerprint: new X509Certificate(made.cert).fingerprint256 };
28
+ }
29
+ // Reads the kept certificate, or makes and keeps one when there is none or the file is damaged.
30
+ export async function read_or_make_peer_certificate(file, name, addresses) {
31
+ try {
32
+ if (existsSync(file)) {
33
+ const saved = JSON.parse(readFileSync(file, "utf8"));
34
+ if (typeof saved.cert === "string" && typeof saved.key === "string")
35
+ return { cert: saved.cert, key: saved.key, fingerprint: new X509Certificate(saved.cert).fingerprint256 };
36
+ }
37
+ }
38
+ catch {
39
+ // A damaged file is replaced by a new certificate below.
40
+ }
41
+ const made = await make_peer_certificate(name, addresses);
42
+ mkdirSync(dirname(file), { recursive: true });
43
+ writeFileSync(file, JSON.stringify({ cert: made.cert, key: made.key }, null, 2), { mode: 0o600 });
44
+ chmodSync(file, 0o600);
45
+ return made;
46
+ }
@@ -84,6 +84,8 @@ export interface AccountStoreOptions {
84
84
  secret_try_window_seconds?: number;
85
85
  password_hashes?: PasswordHashSlots;
86
86
  }
87
+ export declare function holds_accounts(database: SqlDatabase): boolean;
88
+ export declare function move_accounts(from: SqlDatabase, to: SqlDatabase): boolean;
87
89
  export declare class AccountStore {
88
90
  readonly app_name: string;
89
91
  readonly roles: readonly string[];
@@ -75,6 +75,54 @@ const schema = [`
75
75
  PRIMARY KEY (name, key)
76
76
  );
77
77
  `];
78
+ // ── Moving ───────────────────────────────────────────────────────────────────
79
+ function has_table(database, name) {
80
+ return database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== undefined;
81
+ }
82
+ // Whether a database keeps accounts, as an older version kept them in the app's own.
83
+ export function holds_accounts(database) {
84
+ return has_table(database, "account_users");
85
+ }
86
+ // Moves the accounts an older version kept in the app's own database into their own, once: their tables, indexes, rows
87
+ // and schema version go across as they are and leave the app's database, so a restored backup no longer holds them.
88
+ // Does nothing when the accounts database already has accounts or the app's has none; says whether it moved them.
89
+ export function move_accounts(from, to) {
90
+ if (!holds_accounts(from) || holds_accounts(to))
91
+ return false;
92
+ const objects = from.prepare("SELECT type, name, sql FROM sqlite_master WHERE name LIKE 'account\\_%' ESCAPE '\\' AND sql IS NOT NULL ORDER BY type = 'index', rowid").all();
93
+ const versions = from.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'schema_versions'").get();
94
+ to.exec("BEGIN");
95
+ try {
96
+ if (versions && !has_table(to, "schema_versions"))
97
+ to.exec(versions.sql);
98
+ for (const object of objects) {
99
+ to.exec(object.sql);
100
+ if (object.type !== "table")
101
+ continue;
102
+ for (const row of from.prepare(`SELECT * FROM "${object.name}"`).all()) {
103
+ const columns = Object.keys(row);
104
+ to.prepare(`INSERT INTO "${object.name}" (${columns.map((column) => `"${column}"`).join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`).run(...columns.map((column) => row[column]));
105
+ }
106
+ }
107
+ const version = versions ? from.prepare("SELECT * FROM schema_versions WHERE owner = 'accounts'").get() : undefined;
108
+ if (version) {
109
+ const columns = Object.keys(version);
110
+ to.prepare(`INSERT INTO schema_versions (${columns.join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`).run(...columns.map((column) => version[column]));
111
+ }
112
+ to.exec("COMMIT");
113
+ }
114
+ catch (error) {
115
+ to.exec("ROLLBACK");
116
+ throw error;
117
+ }
118
+ from.exec("BEGIN");
119
+ for (const object of objects.filter((each) => each.type === "table"))
120
+ from.exec(`DROP TABLE "${object.name}"`);
121
+ if (versions)
122
+ from.prepare("DELETE FROM schema_versions WHERE owner = 'accounts'").run();
123
+ from.exec("COMMIT");
124
+ return true;
125
+ }
78
126
  // ── Store ────────────────────────────────────────────────────────────────────
79
127
  export class AccountStore {
80
128
  app_name;
@@ -10,11 +10,15 @@ export interface PeerListenerOptions {
10
10
  host?: string;
11
11
  port: number;
12
12
  body_limit?: number;
13
+ https?: {
14
+ cert: string;
15
+ key: string;
16
+ };
13
17
  }
14
18
  export interface PeerListener {
15
19
  close: () => Promise<void>;
16
20
  port: number;
17
21
  addresses: () => string[];
18
22
  }
19
- export declare function reachable_addresses(port: number, interfaces?: NodeJS.Dict<import("os").NetworkInterfaceInfo[]>): string[];
23
+ export declare function reachable_addresses(port: number, interfaces?: NodeJS.Dict<import("os").NetworkInterfaceInfo[]>, scheme?: "http" | "https"): string[];
20
24
  export declare function listen_for_peers(options: PeerListenerOptions): Promise<PeerListener>;
@@ -27,23 +27,24 @@ export function register_sync_peer_routes(app, peer, options = {}) {
27
27
  });
28
28
  }
29
29
  // The computer's own addresses other devices on its networks can reach, leaving out loopback and link-local ones.
30
- export function reachable_addresses(port, interfaces = networkInterfaces()) {
30
+ export function reachable_addresses(port, interfaces = networkInterfaces(), scheme = "http") {
31
31
  const found = [];
32
32
  for (const entries of Object.values(interfaces)) {
33
33
  for (const entry of entries ?? []) {
34
34
  if (entry.internal || (entry.family === "IPv6" && entry.address.toLowerCase().startsWith("fe80")))
35
35
  continue;
36
- found.push(entry.family === "IPv6" ? `http://[${entry.address}]:${port}/` : `http://${entry.address}:${port}/`);
36
+ found.push(entry.family === "IPv6" ? `${scheme}://[${entry.address}]:${port}/` : `${scheme}://${entry.address}:${port}/`);
37
37
  }
38
38
  }
39
39
  return found;
40
40
  }
41
41
  // A desktop daemon's port for other devices, opened only once the user lets other devices connect.
42
42
  export async function listen_for_peers(options) {
43
- const app = fastify({ forceCloseConnections: true });
43
+ const app = fastify({ forceCloseConnections: true, ...(options.https ? { https: options.https } : {}) });
44
44
  await register_open_cors(app, { allowed_headers: sync_peer_headers });
45
45
  register_sync_peer_routes(app, options.peer, { body_limit: options.body_limit });
46
46
  await app.listen({ host: options.host ?? "::", port: options.port });
47
47
  const port = app.server.address().port;
48
- return { close: () => app.close(), port, addresses: () => reachable_addresses(port) };
48
+ const scheme = options.https ? "https" : "http";
49
+ return { close: () => app.close(), port, addresses: () => reachable_addresses(port, networkInterfaces(), scheme) };
49
50
  }
@@ -1,3 +1,4 @@
1
+ import { read_or_make_peer_certificate } from "./peer_certificate.ts";
1
2
  import { listen_for_peers } from "./server/sync_peer_routes.ts";
2
3
  import type { SyncPeer } from "./sync_peer.ts";
3
4
  import { discover_peers } from "./sync_peer_discovery.ts";
@@ -7,8 +8,10 @@ export interface PeerListeningOptions {
7
8
  app: string;
8
9
  file: string;
9
10
  default_port: number;
11
+ certificate_file?: string;
10
12
  listen?: typeof listen_for_peers;
11
13
  discover?: typeof discover_peers;
14
+ certificate?: typeof read_or_make_peer_certificate;
12
15
  }
13
16
  export type PeerListeningControl = ReturnType<typeof keep_listening_for_peers>;
14
17
  export declare function keep_listening_for_peers(options: PeerListeningOptions): {
@@ -1,18 +1,28 @@
1
- // A desktop daemon's "Let other devices connect": off until the user turns it on, then a port of its own that paired
2
- // devices reach it on, announced on the local network. The setting belongs to this computer, so it is kept in a file
3
- // beside the database, never synced. Paired devices are found on the network either way.
1
+ // A desktop daemon's "Let other devices connect": off until the user turns it on, then an https port of its own that
2
+ // paired devices reach it on, announced on the local network, with a self-signed certificate made once, whose fingerprint
3
+ // the Sync section shows so the other device's user can check it before trusting it. The setting belongs to this
4
+ // computer, so it is kept in a file beside the database, never synced. Paired devices are found on the network either way.
4
5
  // ── Imports ──────────────────────────────────────────────────────────────────
5
6
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
- import { dirname } from "node:path";
7
+ import { networkInterfaces } from "node:os";
8
+ import { dirname, join } from "node:path";
9
+ import { read_or_make_peer_certificate } from "./peer_certificate.js";
7
10
  import { listen_for_peers } from "./server/sync_peer_routes.js";
8
11
  import { discover_peers } from "./sync_peer_discovery.js";
9
12
  // ── Listening ────────────────────────────────────────────────────────────────
10
13
  export function keep_listening_for_peers(options) {
11
14
  const listen = options.listen ?? listen_for_peers;
12
15
  const discover = options.discover ?? discover_peers;
16
+ const certificate = options.certificate ?? read_or_make_peer_certificate;
17
+ const certificate_file = options.certificate_file ?? join(dirname(options.file), "sync-certificate.json");
13
18
  let listener = null;
19
+ let fingerprint = "";
14
20
  let discovery = null;
15
21
  let error = "";
22
+ // The computer's own network addresses, for the certificate to cover.
23
+ function local_ip_addresses() {
24
+ return Object.values(networkInterfaces()).flatMap((entries) => (entries ?? []).filter((entry) => !entry.internal).map((entry) => entry.address));
25
+ }
16
26
  // A missing or damaged file reads as off on the default port.
17
27
  function read_saved() {
18
28
  try {
@@ -37,7 +47,9 @@ export function keep_listening_for_peers(options) {
37
47
  error = "";
38
48
  if (saved.on) {
39
49
  try {
40
- listener = await listen({ peer: options.peer(), port: saved.port });
50
+ const own = await certificate(certificate_file, `${options.app} on this computer`, local_ip_addresses());
51
+ fingerprint = own.fingerprint;
52
+ listener = await listen({ peer: options.peer(), port: saved.port, https: { cert: own.cert, key: own.key } });
41
53
  }
42
54
  catch (failure) {
43
55
  error = failure instanceof Error ? failure.message : String(failure);
@@ -50,7 +62,7 @@ export function keep_listening_for_peers(options) {
50
62
  }
51
63
  function get_peer_listening() {
52
64
  const saved = read_saved();
53
- return { ...saved, addresses: addresses(), error };
65
+ return { ...saved, addresses: addresses(), fingerprint, error };
54
66
  }
55
67
  const methods = {
56
68
  get_peer_listening,
@@ -169,6 +169,7 @@ export interface PeerListening {
169
169
  on: boolean;
170
170
  port: number;
171
171
  addresses: string[];
172
+ fingerprint: string;
172
173
  error: string;
173
174
  }
174
175
  export interface PeerListeningMethods {
@@ -1,12 +1,14 @@
1
1
  import { type ReactNode } from "react";
2
+ import type { CertificateClient } from "../../certificate_protocol.ts";
2
3
  import { type PeerListeningClient, type SyncDeviceClient } from "../../sync_protocol.ts";
3
4
  export interface SyncSettingsProps {
4
5
  device: SyncDeviceClient;
5
6
  subscribe?: (listener: () => void) => () => void;
6
7
  data_name?: string;
7
8
  extra?: ReactNode;
9
+ certificates?: CertificateClient;
8
10
  }
9
- export declare function SyncSettings({ device, subscribe, data_name, extra }: SyncSettingsProps): import("react").JSX.Element | null;
11
+ export declare function SyncSettings({ device, subscribe, data_name, extra, certificates }: SyncSettingsProps): import("react").JSX.Element | null;
10
12
  export declare function PeerListeningSettings({ listening }: {
11
13
  listening: PeerListeningClient;
12
14
  }): import("react").JSX.Element | null;
@@ -8,12 +8,24 @@ import { useEffect, useState } from "react";
8
8
  import { format_device_id } from "../../sync_protocol.js";
9
9
  import { describe_error } from "../errors.js";
10
10
  import { StatusPill } from "./badges.js";
11
+ import { offer_certificate_trust } from "./certificates.js";
11
12
  import { Switch } from "./controls.js";
12
13
  import { confirm_dialog, text_dialog } from "./dialog.js";
13
14
  import { SettingRow } from "./layout.js";
14
15
  import { toast } from "./toasts.js";
15
16
  const tones = { off: "none", idle: "good", syncing: "info", offline: "warn", failed: "bad" };
16
17
  const state_text = { off: "Not paired with another device", idle: "Synced", syncing: "Syncing", offline: "Offline", failed: "Failed" };
18
+ // The addresses a pairing code says its device answers at, or none when it is not a whole code; it checks nothing else.
19
+ function addresses_in_pairing_code(code) {
20
+ try {
21
+ const text = code.replace(/\s+/g, "").replace(/^x-sync:/, "").replaceAll("-", "+").replaceAll("_", "/");
22
+ const offer = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(text.padEnd(Math.ceil(text.length / 4) * 4, "=")), (letter) => letter.charCodeAt(0))));
23
+ return Array.isArray(offer.addresses) ? offer.addresses.filter((address) => typeof address === "string") : [];
24
+ }
25
+ catch {
26
+ return [];
27
+ }
28
+ }
17
29
  // Strips what Electron adds in front of an error that crossed from the main process.
18
30
  function error_text(error) {
19
31
  return describe_error(error).replace(/^Error invoking remote method '[^']+': (Error: )?/, "");
@@ -26,7 +38,7 @@ function PeerRow({ peer, on_remove }) {
26
38
  const hint = `${format_device_id(peer.device)} · ${reached} · last synced ${when_text(peer.last_synced_at)}${peer.error ? ` · ${peer.error}` : ""}`;
27
39
  return (_jsxs(SettingRow, { label: peer.name, hint: hint, children: [_jsx(StatusPill, { tone: tones[peer.state], busy: peer.state === "syncing", label: state_text[peer.state] }), _jsx("button", { type: "button", onClick: on_remove, children: "Remove" })] }));
28
40
  }
29
- export function SyncSettings({ device, subscribe, data_name = "data", extra }) {
41
+ export function SyncSettings({ device, subscribe, data_name = "data", extra, certificates }) {
30
42
  const [status, set_status] = useState(null);
31
43
  const [code, set_code] = useState("");
32
44
  const [busy, set_busy] = useState(false);
@@ -44,8 +56,18 @@ export function SyncSettings({ device, subscribe, data_name = "data", extra }) {
44
56
  toast(error_text(error), { tone: "bad" });
45
57
  }
46
58
  }
47
- async function pair(event) {
48
- event.preventDefault();
59
+ // The first https address whose certificate the user trusts after reviewing it, if any.
60
+ async function trusted_after_review() {
61
+ if (!certificates)
62
+ return false;
63
+ for (const address of addresses_in_pairing_code(code).filter((each) => each.startsWith("https:"))) {
64
+ if (await offer_certificate_trust(address, certificates))
65
+ return true;
66
+ }
67
+ return false;
68
+ }
69
+ async function pair(event, is_retry = false) {
70
+ event?.preventDefault();
49
71
  set_busy(true);
50
72
  try {
51
73
  set_status(await device.pair_device(code));
@@ -53,6 +75,8 @@ export function SyncSettings({ device, subscribe, data_name = "data", extra }) {
53
75
  toast(`Paired. The ${data_name} on both devices are merged, the newest change to each winning.`, { tone: "good" });
54
76
  }
55
77
  catch (error) {
78
+ if (!is_retry && (await trusted_after_review()))
79
+ return void (await pair(null, true));
56
80
  toast(error_text(error), { tone: "bad" });
57
81
  }
58
82
  finally {
@@ -92,7 +116,9 @@ export function PeerListeningSettings({ listening }) {
92
116
  }
93
117
  if (!state)
94
118
  return null;
95
- const hint = state.on && state.addresses.length > 0 ? `Paired devices reach this one at ${state.addresses.join(", ")}.` : "Lets paired devices on your networks reach this one, so they sync without a server between them.";
119
+ const reached = state.on && state.addresses.length > 0 ? `Paired devices reach this one at ${state.addresses.join(", ")}.` : "Lets paired devices on your networks reach this one over https, so they sync without a server between them.";
120
+ // The other device asks to trust this one's self-signed certificate once; its fingerprint there should match this one.
121
+ const hint = state.fingerprint ? `${reached} Its certificate's fingerprint is ${state.fingerprint}.` : reached;
96
122
  return (_jsxs(_Fragment, { children: [_jsx(SettingRow, { label: "Let other devices connect", hint: state.error ? `The port could not be opened: ${state.error}` : hint, as_label: true, children: _jsx(Switch, { label: "Let other devices connect", checked: state.on, on_change: (on) => change(on) }) }), _jsx(SettingRow, { label: "Port", hint: "The port other devices connect to.", as_label: true, children: _jsx("input", { type: "number", min: 1, max: 65535, value: port, onChange: (event) => set_port(event.currentTarget.value), onBlur: () => state.on && Number(port) !== state.port && void change(true) }) })] }));
97
123
  }
98
124
  // ── Sidebar button ───────────────────────────────────────────────────────────
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.100.0",
3
+ "version": "0.102.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": {
@@ -18,6 +18,7 @@
18
18
  "android/src/main/"
19
19
  ],
20
20
  "bin": {
21
+ "x-app-android": "dist/app_android.js",
21
22
  "x-app-bundle-migrations": "dist/drizzle_migrations.js",
22
23
  "x-app-check": "dist/change_checks_cli.js",
23
24
  "x-app-icons": "dist/app_icons.js",
@@ -251,6 +252,7 @@
251
252
  "react-error-boundary": "^6.1.6",
252
253
  "react-grid-layout": "^2.3.0",
253
254
  "rrule": "^2.8.1",
255
+ "selfsigned": "^5.5.0",
254
256
  "semver": "^7.8.6",
255
257
  "spdx-satisfies": "^6.0.1",
256
258
  "sshpk": "^1.18.0",