@x-tech-laboratories/x-app 0.101.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. |
@@ -95,7 +96,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
95
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. |
96
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`). |
97
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. |
98
- | `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. |
99
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. |
100
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. |
101
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`. |
@@ -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();
@@ -99,6 +100,8 @@ export function register_app_calls(api, app, database, changes) {
99
100
  }
100
101
  // The server's backups and its sync peer's pairings, which only an admin reaches.
101
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");
@@ -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.
@@ -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
+ }
@@ -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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.101.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": {