@x-tech-laboratories/x-app 0.120.0 → 0.122.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.
Files changed (48) hide show
  1. package/README.md +27 -6
  2. package/dist/agent/ssh_config.d.ts +12 -0
  3. package/dist/agent/ssh_config.js +72 -0
  4. package/dist/app/daemon.d.ts +7 -1
  5. package/dist/app/daemon.js +82 -8
  6. package/dist/app/define.d.ts +38 -1
  7. package/dist/app/define.js +34 -1
  8. package/dist/app/desktop.d.ts +13 -0
  9. package/dist/app/desktop.js +35 -3
  10. package/dist/app/host_tables.d.ts +21 -0
  11. package/dist/app/host_tables.js +105 -0
  12. package/dist/app/preload.js +5 -0
  13. package/dist/app/protocol.d.ts +31 -1
  14. package/dist/app/protocol.js +8 -1
  15. package/dist/app/remote_access.d.ts +17 -0
  16. package/dist/app/remote_access.js +85 -0
  17. package/dist/app/server.d.ts +20 -5
  18. package/dist/app/server.js +101 -22
  19. package/dist/app/services.d.ts +25 -2
  20. package/dist/app/web/app_page.d.ts +1 -1
  21. package/dist/app/web/app_page.js +73 -12
  22. package/dist/app/web/hosts.d.ts +5 -3
  23. package/dist/app/web/hosts.js +35 -2
  24. package/dist/app/web/page.d.ts +3 -0
  25. package/dist/app/web/page.js +24 -4
  26. package/dist/app/web/portal.d.ts +14 -0
  27. package/dist/app/web/portal.js +115 -0
  28. package/dist/app/web/settings_page.d.ts +13 -2
  29. package/dist/app/web/settings_page.js +36 -8
  30. package/dist/change_checks.js +1 -1
  31. package/dist/github_targets.d.ts +12 -0
  32. package/dist/github_targets.js +90 -0
  33. package/dist/remote_access_protocol.d.ts +26 -0
  34. package/dist/remote_access_protocol.js +33 -0
  35. package/dist/server/github_webhook.d.ts +2 -12
  36. package/dist/server/github_webhook.js +2 -87
  37. package/dist/server/sqlite_backups.d.ts +2 -2
  38. package/dist/server/sqlite_backups.js +2 -2
  39. package/dist/server/viewer_scope.d.ts +3 -0
  40. package/dist/server/viewer_scope.js +14 -0
  41. package/dist/web/react/remote_access_settings.d.ts +5 -0
  42. package/dist/web/react/remote_access_settings.js +55 -0
  43. package/dist/web/react/shell.js +1 -1
  44. package/dist/web/remote_daemon.d.ts +26 -0
  45. package/dist/web/remote_daemon.js +105 -0
  46. package/dist/web/theme.d.ts +8 -0
  47. package/dist/web/theme.js +23 -0
  48. package/package.json +1 -1
@@ -16,7 +16,8 @@ import { migrate } from "../sql.js";
16
16
  import { create_sync_engine } from "../sync_engine.js";
17
17
  import { backup_method_names } from "../backups.js";
18
18
  import { peer_listening_method_names, sync_device_method_names } from "../sync_protocol.js";
19
- import { desktop_method_names } from "./protocol.js";
19
+ import { remote_access_method_names } from "../remote_access_protocol.js";
20
+ import { desktop_method_names, host_ability_method_names } from "./protocol.js";
20
21
  export function define_feature(feature) {
21
22
  return feature;
22
23
  }
@@ -24,6 +25,8 @@ export function define_feature(feature) {
24
25
  export function is_read_only(method) {
25
26
  return /^(list|get|search|lookup|export)_/.test(method);
26
27
  }
28
+ // The path a host table's calls are posted under, such as /api/stages/.
29
+ const host_table_route = (name) => `/api/${name}/`;
27
30
  // The settings every app keeps: how long its history reaches back, and this device's backup schedule.
28
31
  export const base_setting_defaults = {
29
32
  // How many days of changes the history keeps, each item keeping its newest version; 0 keeps them all.
@@ -166,6 +169,15 @@ export function define_app(options) {
166
169
  });
167
170
  return Object.fromEntries(bound);
168
171
  }
172
+ // After the app's own work wrote to the database outside a call, such as a job's progress: the features catch up and
173
+ // the versions are recorded, as after a call that writes.
174
+ function record_writes(database) {
175
+ for (const feature of features)
176
+ feature.after_write?.(database);
177
+ for (const history of histories)
178
+ history.record(database);
179
+ prune_daily(database);
180
+ }
169
181
  // What MCP offers: the app's own tools when it has them, otherwise the page's calls.
170
182
  const tools = options.tools;
171
183
  const mcp = {
@@ -229,7 +241,23 @@ export function define_app(options) {
229
241
  // The desktop app's own MCP endpoint, for AI clients on the same computer.
230
242
  local_mcp: define_bridge(`${prefix}_local_mcp`, local_mcp_method_names),
231
243
  events: define_events(`${prefix}_events`),
244
+ host: define_bridge(`${prefix}_host`, host_ability_method_names),
245
+ // Letting other devices reach this computer's daemon, answered over its socket alone.
246
+ remote_access: define_bridge(`${prefix}_remote`, remote_access_method_names),
247
+ host_tables: Object.fromEntries(Object.entries(options.host_tables ?? {}).map(([name, table]) => [name, define_bridge(`${prefix}_${name}`, Object.keys(table.api))])),
232
248
  };
249
+ // ── Host tables ──────────────────────────────────────────────────────
250
+ const host_tables = options.host_tables ?? {};
251
+ // The tables a kind of host answers, and of those, the ones the network and MCP reach.
252
+ function tables_on(kind, from_network) {
253
+ return Object.entries(host_tables)
254
+ .filter(([, table]) => table.hosts.includes(kind) && !(from_network && table.network === "none"))
255
+ .map(([name]) => name);
256
+ }
257
+ // The table one of the host tables' calls belongs to, or null for any other call.
258
+ function table_of_call(method, kind) {
259
+ return tables_on(kind, true).find((name) => Object.hasOwn(host_tables[name].api, method)) ?? null;
260
+ }
233
261
  return {
234
262
  ...options,
235
263
  features,
@@ -244,11 +272,16 @@ export function define_app(options) {
244
272
  is_read_only,
245
273
  page_only,
246
274
  bind_methods,
275
+ record_writes,
247
276
  mcp,
248
277
  backup_naming: naming,
249
278
  read_backup_schedule,
250
279
  adopt_backup_schedule,
251
280
  backup_methods,
252
281
  bridges,
282
+ host_tables,
283
+ tables_on,
284
+ table_of_call,
285
+ host_table_path: host_table_route,
253
286
  };
254
287
  }
@@ -6,6 +6,7 @@ import { type TrayElectronLike, type TrayLike, type TrayRow } from "../electron/
6
6
  import { type BrowserWindowLike, type BrowserWindowOptionsLike, type NativeThemeLike, type ScreenLike, type ShellLike } from "../electron/window.ts";
7
7
  import { call_daemon, start_daemon } from "../local_daemon.ts";
8
8
  import type { App } from "./define.ts";
9
+ import { type AppNotice } from "./protocol.ts";
9
10
  type DesktopWindow = BrowserWindowLike & FocusableWindowLike & WindowLike & {
10
11
  webContents: {
11
12
  reload(): void;
@@ -33,6 +34,13 @@ export interface ElectronLike {
33
34
  canceled: boolean;
34
35
  filePath?: string;
35
36
  }>;
37
+ showOpenDialog?(options: {
38
+ properties: "openDirectory"[];
39
+ defaultPath?: string;
40
+ }): Promise<{
41
+ canceled: boolean;
42
+ filePaths: string[];
43
+ }>;
36
44
  };
37
45
  powerMonitor?: {
38
46
  getSystemIdleTime(): number;
@@ -104,6 +112,11 @@ export interface DesktopOptions {
104
112
  set_autostart?: (options: AutostartOptions, on: boolean) => void;
105
113
  tray?: AppTrayRows;
106
114
  route_of_link?: (link: string) => string | null;
115
+ daemon_env?: (profile: {
116
+ path: string;
117
+ is_own_profile: boolean;
118
+ }) => Record<string, string>;
119
+ show_notice?: (notice: AppNotice) => void;
107
120
  }
108
121
  export declare function run_desktop(app: App, electron: ElectronLike, options: DesktopOptions): void;
109
122
  export {};
@@ -6,6 +6,7 @@ import { unwatchFile, watchFile } from "node:fs";
6
6
  import { homedir, hostname } from "node:os";
7
7
  import { writeFile } from "node:fs/promises";
8
8
  import { extname, join, resolve } from "node:path";
9
+ import { Notifier } from "../agent/desktop_notify.js";
9
10
  import { launch_command, set_autostart } from "../autostart.js";
10
11
  import { backup_method_names } from "../backups.js";
11
12
  import { certificate_method_names } from "../certificate_protocol.js";
@@ -21,6 +22,8 @@ import { create_window, is_app_page } from "../electron/window.js";
21
22
  import { call_daemon, daemon_log_path, daemon_socket_path, start_daemon } from "../local_daemon.js";
22
23
  import { peer_listening_method_names, sync_device_method_names } from "../sync_protocol.js";
23
24
  import { route_of_link } from "./links.js";
25
+ import { remote_access_method_names } from "../remote_access_protocol.js";
26
+ import { host_ability_method_names, notice_event, notice_is_on } from "./protocol.js";
24
27
  // The Save dialog's options for a file name: Downloads with that name, offering files of its kind.
25
28
  export function save_dialog_options(file_name, downloads) {
26
29
  const extension = extname(file_name).slice(1);
@@ -57,7 +60,8 @@ export function run_desktop(app, electron, options) {
57
60
  function ensure_daemon(replace_other_build = false) {
58
61
  // Only the user's own daemon reads what this computer's configuration declares, unless a run names a file itself.
59
62
  const declared = is_own_profile ? {} : { [`${prefix}_DECLARED_FILE`]: env[`${prefix}_DECLARED_FILE`] ?? "" };
60
- return start({ socket_path, script: join(options.main_dir, "daemon.js"), env: { [`${prefix}_DB`]: database_path, [`${prefix}_SOCKET`]: socket_path, [`${prefix}_ICON`]: icon_path, ...declared }, log_file, replace_other_build });
63
+ const own_env = options.daemon_env?.({ path: profile, is_own_profile }) ?? {};
64
+ return start({ socket_path, script: join(options.main_dir, "daemon.js"), env: { [`${prefix}_DB`]: database_path, [`${prefix}_SOCKET`]: socket_path, [`${prefix}_ICON`]: icon_path, ...declared, ...own_env }, log_file, replace_other_build });
61
65
  }
62
66
  // Saves the text where the user picks, starting in Downloads; false when the dialog was cancelled.
63
67
  async function save_text_file(file_name, text) {
@@ -79,13 +83,26 @@ export function run_desktop(app, electron, options) {
79
83
  const connections = create_connections({ storage: connection_file_storage(join(profile, "connections.json")), offers_local: true, device_name: `${app.name} on ${hostname()}` });
80
84
  const link = create_daemon_link({ connections, socket_path });
81
85
  const windows = () => BrowserWindow.getAllWindows();
86
+ // A daemon elsewhere tells of its notices as events; this computer shows them by its own switches, as its own
87
+ // daemon shows its own.
88
+ const notifier = new Notifier({ app_name: app.name, icons: { app: icon_path }, on_error: (message) => console.error(`${app.id} notifications: ${message}`) });
89
+ const show_notice = options.show_notice ?? ((notice) => void notifier.show({ title: notice.title, body: notice.body, key: notice.key, ...(notice.url ? { url: notice.url } : {}), icon: "app" }));
90
+ async function notice_from_elsewhere(data) {
91
+ if (router.is_here())
92
+ return;
93
+ const notice = JSON.parse(data);
94
+ if (notice_is_on(notice.kind, await get_desktop_settings()))
95
+ show_notice(notice);
96
+ }
97
+ // Host tables kept to this computer stay with its own daemon, as does who may connect to it.
98
+ const own_tables = Object.entries(app.host_tables).filter(([, table]) => table.network === "none").map(([name]) => name);
82
99
  // Calls and change events go to the chosen daemon; another daemon chosen reloads every window.
83
100
  const router = create_daemon_router({
84
101
  connections,
85
102
  link,
86
103
  call_local: (path, args, headers) => call_socket(socket_path, path, args, headers),
87
104
  restart_local: () => ensure_daemon(),
88
- local_tables: [...default_local_tables, "peer_listening"],
105
+ local_tables: [...default_local_tables, "peer_listening", "remote", ...own_tables],
89
106
  is_read_only: app.is_read_only,
90
107
  on_change: (change) => {
91
108
  app.bridges.events.emit(windows(), "changed", change);
@@ -94,7 +111,11 @@ export function run_desktop(app, electron, options) {
94
111
  },
95
112
  on_sync_status: (status) => app.bridges.events.emit(windows(), "sync_status", status),
96
113
  // The app's own events, such as a reply as it is written, go to every window by name.
97
- on_event: (event, data) => app.bridges.events.emit(windows(), "app_event", { event, data: data === "" ? null : JSON.parse(data) }),
114
+ on_event: (event, data) => {
115
+ if (event === notice_event)
116
+ void notice_from_elsewhere(data).catch(() => undefined);
117
+ app.bridges.events.emit(windows(), "app_event", { event, data: data === "" ? null : JSON.parse(data) });
118
+ },
98
119
  on_switch: () => {
99
120
  for (const window of windows())
100
121
  window.webContents.reload();
@@ -219,6 +240,11 @@ export function run_desktop(app, electron, options) {
219
240
  bridges.connections.handle(ipcMain, connections.methods, handle_options);
220
241
  if (app.local_mcp)
221
242
  bridges.local_mcp.handle(ipcMain, forwarded(local_mcp_method_names, "local_mcp"), handle_options);
243
+ if (app.remote_access)
244
+ bridges.remote_access.handle(ipcMain, forwarded(remote_access_method_names, "remote"), handle_options);
245
+ bridges.host.handle(ipcMain, forwarded(host_ability_method_names, "host"), handle_options);
246
+ for (const [name, bridge] of Object.entries(bridges.host_tables))
247
+ bridge.handle(ipcMain, forwarded(Object.keys(app.host_tables[name].api), name), handle_options);
222
248
  const desktop = {
223
249
  get_desktop_settings,
224
250
  set_desktop_setting: async (key, value) => {
@@ -233,6 +259,12 @@ export function run_desktop(app, electron, options) {
233
259
  electron.nativeTheme.themeSource = theme;
234
260
  },
235
261
  get_data_paths: () => ({ database: database_path, backups: join(profile, "backups") }),
262
+ pick_folder: async (current) => {
263
+ if (!dialog.showOpenDialog)
264
+ throw new Error("This desktop app cannot show a folder dialog.");
265
+ const picked = await dialog.showOpenDialog({ properties: ["openDirectory"], ...(current ? { defaultPath: current } : {}) });
266
+ return picked.canceled ? null : (picked.filePaths[0] ?? null);
267
+ },
236
268
  show_data_path: async (which) => {
237
269
  if (which === "database")
238
270
  electron.shell.showItemInFolder?.(database_path);
@@ -0,0 +1,21 @@
1
+ import type { FastifyInstance, FastifyRequest } from "fastify";
2
+ import { type ApiSpec } from "../api_spec.ts";
3
+ import type { EventStream } from "../server/events.ts";
4
+ import type { SqlDatabase } from "../sql.ts";
5
+ import type { App, HostKind } from "./define.ts";
6
+ import type { HostAbilities } from "./protocol.ts";
7
+ import type { HostServices } from "./services.ts";
8
+ export interface HostReach {
9
+ kind: HostKind;
10
+ from_network: boolean;
11
+ is_admin: (request: FastifyRequest) => boolean;
12
+ has_role: (request: FastifyRequest, role: string) => boolean;
13
+ }
14
+ export declare function host_abilities(app: App, reach: HostReach, request: FastifyRequest): HostAbilities;
15
+ export declare function register_host_tables(api: FastifyInstance, app: App, reach: HostReach, services: () => HostServices, changes: EventStream): void;
16
+ export interface McpTools {
17
+ api: ApiSpec<Record<string, (...args: never[]) => unknown>>;
18
+ call: (method: string, args: unknown[], request?: FastifyRequest) => Promise<unknown>;
19
+ }
20
+ export declare function mcp_tools(app: App, reach: HostReach, services: () => HostServices, database: () => SqlDatabase, announce: () => void): McpTools;
21
+ export declare function call_path_of(app: App, kind: HostKind): (method: string) => string;
@@ -0,0 +1,105 @@
1
+ // The app's host tables as a host serves them: each call posted under its table's path, answered by what the app's
2
+ // services handed in once they started, the network and MCP reaching only the tables and calls they may, and the
3
+ // tools MCP offers being the data calls and those tables together.
4
+ import { positional_args } from "../api_spec.js";
5
+ import { send_text } from "../server/replies.js";
6
+ import { with_viewer } from "../server/viewer_scope.js";
7
+ // Why the one asking may not make a call of a table's that needs a role of its own, or null when they may.
8
+ function role_refusal(table, reach, method, request) {
9
+ const role = table.needs?.(method);
10
+ if (!role || !request || reach.has_role(request, role))
11
+ return null;
12
+ return `${method} needs the ${role} role.`;
13
+ }
14
+ // The tables the one asking may reach on this host, as the page reads them to know what it can offer.
15
+ export function host_abilities(app, reach, request) {
16
+ const admin = reach.is_admin(request);
17
+ const tables = app.tables_on(reach.kind, reach.from_network).filter((name) => admin || !reach.from_network || app.host_tables[name].network === "any");
18
+ return { admin, tables };
19
+ }
20
+ // What answers a table's calls for this caller, or null before the services handed it in.
21
+ function served_methods(services, name, from_elsewhere) {
22
+ const served = services().tables?.[name];
23
+ if (!served)
24
+ return null;
25
+ return (from_elsewhere ? (served.elsewhere ?? served.methods) : served.methods);
26
+ }
27
+ // ── Routes ───────────────────────────────────────────────────────────────────
28
+ // Every host table this host answers, as POST <api>/<table>/<call> with the arguments as a JSON list or by name; an
29
+ // admin's table refuses anyone else on the network, and a change is announced to every page but the one that made it.
30
+ export function register_host_tables(api, app, reach, services, changes) {
31
+ api.post("/host/get_host_abilities", async (request, reply) => reply.type("application/json").header("cache-control", "no-store").send(JSON.stringify(host_abilities(app, reach, request))));
32
+ for (const name of app.tables_on(reach.kind, reach.from_network)) {
33
+ const table = app.host_tables[name];
34
+ const params = table.api;
35
+ api.post(`/${name}/:method`, async (request, reply) => {
36
+ const { method } = request.params;
37
+ if (!Object.hasOwn(table.api, method))
38
+ return send_text(reply, 404, `no call named ${method}`);
39
+ if (reach.from_network && table.network !== "any" && !reach.is_admin(request))
40
+ return send_text(reply, 403, `${method} needs an admin.`);
41
+ const refusal = reach.from_network ? role_refusal(table, reach, method, request) : null;
42
+ if (refusal)
43
+ return send_text(reply, 403, refusal);
44
+ const methods = served_methods(services, name, reach.from_network);
45
+ if (!methods || typeof methods[method] !== "function")
46
+ return send_text(reply, 503, `${app.name} is still starting; try ${method} again in a moment.`);
47
+ const body = request.body ?? [];
48
+ let args;
49
+ if (Array.isArray(body))
50
+ args = body;
51
+ else if (typeof body === "object" && body !== null && params[method]) {
52
+ try {
53
+ args = positional_args(params[method], body);
54
+ }
55
+ catch (error) {
56
+ return send_text(reply, 400, error.message);
57
+ }
58
+ }
59
+ else
60
+ return send_text(reply, 400, "send the arguments as a JSON list or object");
61
+ const result = await with_viewer(request.viewer, () => methods[method](...args));
62
+ const read_only = app.is_read_only(method);
63
+ if (!read_only)
64
+ changes.announce_change(changes.client_id_of(request));
65
+ if (result === undefined)
66
+ return reply.code(204).send();
67
+ if (read_only)
68
+ reply.header("cache-control", "no-store");
69
+ // Fastify would send a string as bare text, which the caller could not tell from JSON.
70
+ return reply.type("application/json").send(JSON.stringify(result));
71
+ });
72
+ }
73
+ }
74
+ // The data calls and the host tables this host answers, as one set of MCP tools.
75
+ export function mcp_tools(app, reach, services, database, announce) {
76
+ const names = app.tables_on(reach.kind, true);
77
+ const api = Object.assign({}, app.mcp.api, ...names.map((name) => app.host_tables[name].api));
78
+ return {
79
+ api,
80
+ call: async (method, args, request) => {
81
+ const name = names.find((each) => Object.hasOwn(app.host_tables[each].api, method));
82
+ if (name === undefined)
83
+ return app.mcp.call(database, announce, method, args);
84
+ if (app.host_tables[name].network !== "any" && request && !reach.is_admin(request))
85
+ throw new Error(`${method} needs an admin's token`);
86
+ const refusal = role_refusal(app.host_tables[name], reach, method, request);
87
+ if (refusal)
88
+ throw new Error(refusal);
89
+ const methods = served_methods(services, name, true);
90
+ if (!methods || typeof methods[method] !== "function")
91
+ throw new Error(`${app.name} is still starting; try ${method} again in a moment.`);
92
+ const result = await with_viewer(request?.viewer, () => methods[method](...args));
93
+ if (!app.is_read_only(method))
94
+ announce();
95
+ return result;
96
+ },
97
+ };
98
+ }
99
+ // The path each call is posted under, for the OpenAPI document.
100
+ export function call_path_of(app, kind) {
101
+ return (method) => {
102
+ const name = app.table_of_call(method, kind);
103
+ return name ? `/api/${name}/${method}` : `/api/call/${method}`;
104
+ };
105
+ }
@@ -8,5 +8,10 @@ export function run_preload(app, { contextBridge, ipcRenderer }) {
8
8
  }
9
9
  if (app.local_mcp)
10
10
  bridges.local_mcp.expose(contextBridge, ipcRenderer, { envelopes: true });
11
+ if (app.remote_access)
12
+ bridges.remote_access.expose(contextBridge, ipcRenderer, { envelopes: true });
13
+ bridges.host.expose(contextBridge, ipcRenderer, { envelopes: true });
14
+ for (const bridge of Object.values(bridges.host_tables))
15
+ bridge.expose(contextBridge, ipcRenderer, { envelopes: true });
11
16
  bridges.events.expose(contextBridge, ipcRenderer);
12
17
  }
@@ -3,8 +3,10 @@ import type { CertificateClient } from "../certificate_protocol.ts";
3
3
  import type { ConnectionClient } from "../connection_protocol.ts";
4
4
  import type { LocalMcpClient } from "../local_mcp_protocol.ts";
5
5
  import type { Client } from "../electron/bridge.ts";
6
+ import type { RemoteAccessClient } from "../remote_access_protocol.ts";
6
7
  import type { PeerListeningClient, SyncDeviceClient } from "../sync_protocol.ts";
7
8
  import type { DataChange } from "../sync_protocol.ts";
9
+ import type { ServerTheme } from "../web/theme.ts";
8
10
  export { data_change_of, type DataChange } from "../sync_protocol.ts";
9
11
  export interface DesktopSettings {
10
12
  show_tray_icon: boolean;
@@ -28,18 +30,36 @@ export interface DesktopMethods {
28
30
  set_window_theme: (theme: "system" | "light" | "dark") => void;
29
31
  get_data_paths: () => DataPaths;
30
32
  show_data_path: (which: keyof DataPaths) => void;
33
+ pick_folder: (current: string) => string | null;
31
34
  }
32
35
  export interface DataPaths {
33
36
  database: string;
34
37
  backups: string;
35
38
  }
36
- export declare const desktop_method_names: readonly ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file", "set_window_theme", "get_data_paths", "show_data_path"];
39
+ export declare const desktop_method_names: readonly ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file", "set_window_theme", "get_data_paths", "show_data_path", "pick_folder"];
37
40
  export interface DaemonMethods {
38
41
  get_desktop_settings: () => DesktopSettings;
39
42
  set_desktop_setting: (key: keyof DesktopSettings, value: boolean) => void;
40
43
  stop_daemon: () => void;
41
44
  set_window_in_front: (in_front: boolean) => void;
42
45
  }
46
+ export interface HostAbilities {
47
+ admin: boolean;
48
+ tables: string[];
49
+ }
50
+ export interface HostAbilityMethods {
51
+ get_host_abilities: () => HostAbilities;
52
+ }
53
+ export declare const host_ability_method_names: readonly ["get_host_abilities"];
54
+ export interface AppNotice {
55
+ kind: string;
56
+ title: string;
57
+ body: string;
58
+ key: string;
59
+ url: string;
60
+ }
61
+ export declare const notice_event = "notice";
62
+ export declare function notice_is_on(kind: string, switches: Readonly<Record<string, boolean>>): boolean;
43
63
  export type Host = "web" | "desktop" | "android";
44
64
  export interface BackupFolder {
45
65
  name: () => Promise<string>;
@@ -56,6 +76,16 @@ export interface PageApi<Methods extends Record<keyof Methods, (...args: never[]
56
76
  peer_listening?: PeerListeningClient;
57
77
  desktop?: Client<DesktopMethods>;
58
78
  local_mcp?: LocalMcpClient;
79
+ tables?: Readonly<Record<string, Client<Record<string, (...args: never[]) => unknown>>>>;
80
+ admin?: boolean;
81
+ remote_access?: RemoteAccessClient;
82
+ daemon_is_here?: boolean;
83
+ notice_switches?: {
84
+ get: () => Promise<Record<string, boolean>>;
85
+ set: (key: string, on: boolean) => Promise<void>;
86
+ };
87
+ reread_abilities?: () => Promise<Pick<PageApi, "admin" | "tables">>;
88
+ server_theme?: ServerTheme;
59
89
  on_change: (listener: (change: DataChange | null) => void) => () => void;
60
90
  on_event?: (event: string, listener: (data: unknown) => void) => () => void;
61
91
  }
@@ -12,4 +12,11 @@ export function read_desktop_settings(saved, specs = {}) {
12
12
  const defaults = { ...desktop_setting_defaults, ...Object.fromEntries(Object.entries(specs).map(([key, spec]) => [key, spec.default])) };
13
13
  return Object.fromEntries(Object.entries(defaults).map(([key, fallback]) => [key, typeof settings[key] === "boolean" ? settings[key] : fallback]));
14
14
  }
15
- export const desktop_method_names = ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file", "set_window_theme", "get_data_paths", "show_data_path"];
15
+ export const desktop_method_names = ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file", "set_window_theme", "get_data_paths", "show_data_path", "pick_folder"];
16
+ export const host_ability_method_names = ["get_host_abilities"];
17
+ // The named event a host sends its pages with each notice.
18
+ export const notice_event = "notice";
19
+ // Whether this device shows a notice of the kind given: its switch, where the app has one, or always.
20
+ export function notice_is_on(kind, switches) {
21
+ return switches[`notify_${kind}`] ?? true;
22
+ }
@@ -0,0 +1,17 @@
1
+ import type { FastifyInstance } from "fastify";
2
+ import { type RemoteAccessMethods } from "../remote_access_protocol.ts";
3
+ import { type Accounts } from "../server/passwords.ts";
4
+ export interface RemoteAccessOptions {
5
+ profile: string;
6
+ build: (admins: Accounts, https: {
7
+ cert: Buffer;
8
+ key: Buffer;
9
+ } | undefined) => Promise<FastifyInstance>;
10
+ default_port: number;
11
+ }
12
+ export interface RemoteAccess {
13
+ methods: RemoteAccessMethods;
14
+ restart: () => Promise<void>;
15
+ stop: () => Promise<void>;
16
+ }
17
+ export declare function create_remote_access({ profile, build, default_port }: RemoteAccessOptions): RemoteAccess;
@@ -0,0 +1,85 @@
1
+ // "Let other devices connect": the daemon's own network address, behind the same sign-in as the web server, kept in
2
+ // the profile folder with the admins who may sign in from elsewhere. It listens only while turned on, and the settings
3
+ // and admins change only over the daemon's own socket.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { read_remote_access, remote_access_problem } from "../remote_access_protocol.js";
8
+ import { account_name_pattern, hash_password, parse_accounts, set_account } from "../server/passwords.js";
9
+ const shortest_password = 10;
10
+ // ── Remote access ────────────────────────────────────────────────────────────
11
+ export function create_remote_access({ profile, build, default_port }) {
12
+ const settings_file = join(profile, "remote.json");
13
+ const accounts_file = join(profile, "remote-admins");
14
+ let server = null;
15
+ let listening = "";
16
+ let problem = "";
17
+ function read_settings() {
18
+ return read_remote_access(existsSync(settings_file) ? JSON.parse(readFileSync(settings_file, "utf8")) : null, default_port);
19
+ }
20
+ function read_admins() {
21
+ return existsSync(accounts_file) ? parse_accounts(readFileSync(accounts_file, "utf8"), accounts_file) : new Map();
22
+ }
23
+ // Only this user may read the hashes.
24
+ function write_admins(text) {
25
+ mkdirSync(profile, { recursive: true });
26
+ writeFileSync(accounts_file, text, { mode: 0o600 });
27
+ chmodSync(accounts_file, 0o600);
28
+ }
29
+ function status() {
30
+ return { settings: read_settings(), admins: [...read_admins().keys()].sort(), listening, problem };
31
+ }
32
+ async function stop() {
33
+ const closing = server;
34
+ server = null;
35
+ listening = "";
36
+ await closing?.close();
37
+ }
38
+ async function restart() {
39
+ await stop();
40
+ const settings = read_settings();
41
+ problem = "";
42
+ if (!settings.enabled)
43
+ return;
44
+ try {
45
+ const admins = read_admins();
46
+ problem = remote_access_problem(settings, [...admins.keys()]);
47
+ if (problem)
48
+ return;
49
+ const https = settings.certificate_file ? { cert: readFileSync(settings.certificate_file), key: readFileSync(settings.key_file) } : undefined;
50
+ const built = await build(admins, https);
51
+ await built.listen({ host: settings.host, port: settings.port });
52
+ server = built;
53
+ listening = `${https ? "https" : "http"}://${settings.host.includes(":") ? `[${settings.host}]` : settings.host}:${settings.port}`;
54
+ }
55
+ catch (error) {
56
+ problem = error instanceof Error ? error.message : String(error);
57
+ }
58
+ }
59
+ const methods = {
60
+ get_remote_access: status,
61
+ set_remote_access: async (settings) => {
62
+ mkdirSync(profile, { recursive: true });
63
+ writeFileSync(settings_file, JSON.stringify(read_remote_access(settings, default_port), null, 2));
64
+ await restart();
65
+ return status();
66
+ },
67
+ set_remote_admin: async (typed_name, password) => {
68
+ const name = typed_name.trim().toLowerCase();
69
+ if (!account_name_pattern.test(name))
70
+ throw new Error("A name is lowercase letters, digits, '.', '_' and '-'.");
71
+ if (password.length < shortest_password)
72
+ throw new Error(`A password needs at least ${shortest_password} characters.`);
73
+ write_admins(set_account(existsSync(accounts_file) ? readFileSync(accounts_file, "utf8") : "", name, hash_password(password)));
74
+ await restart();
75
+ return status();
76
+ },
77
+ remove_remote_admin: async (name) => {
78
+ const kept = [...read_admins()].filter(([admin]) => admin !== name);
79
+ write_admins(kept.map(([admin, stored]) => `${admin}:${stored}\n`).join(""));
80
+ await restart();
81
+ return status();
82
+ },
83
+ };
84
+ return { methods, restart, stop };
85
+ }
@@ -1,19 +1,21 @@
1
1
  import { DatabaseSync } from "node:sqlite";
2
2
  import { type FastifyInstance } from "fastify";
3
3
  import { type BackupMethods } from "../backups.ts";
4
+ import { OidcClient } from "../server/oidc.ts";
4
5
  import { AccountStore } from "../server/account_store.ts";
5
6
  import { EventStream } from "../server/events.ts";
6
7
  import { type SqlDatabase } from "../sql.ts";
8
+ import { type ServerTheme } from "../web/theme.ts";
7
9
  import { type SyncPeer } from "../sync_peer.ts";
8
- import type { App } from "./define.ts";
9
- import { type StartServices } from "./services.ts";
10
+ import type { App, HostKind } from "./define.ts";
11
+ import { type AppRoutes, type HostServices, type StartServices } from "./services.ts";
10
12
  export interface AppDatabase {
11
13
  database: () => DatabaseSync;
12
14
  back_up: () => Promise<void>;
13
15
  backup_methods: BackupMethods;
14
16
  on_restore: (hooks: {
15
- before?: () => void;
16
- after?: () => void;
17
+ before?: () => void | Promise<void>;
18
+ after?: () => void | Promise<void>;
17
19
  }) => void;
18
20
  close: () => void;
19
21
  }
@@ -27,9 +29,21 @@ export interface ServerOptions {
27
29
  database: () => SqlDatabase;
28
30
  accounts: AccountStore;
29
31
  web_folder: string;
30
- sync: SyncPeer;
32
+ sync?: SyncPeer;
31
33
  changes: EventStream;
32
34
  backup_methods: BackupMethods;
35
+ kind?: HostKind;
36
+ services?: () => HostServices;
37
+ routes?: AppRoutes;
38
+ https?: {
39
+ cert: Buffer;
40
+ key: Buffer;
41
+ };
42
+ oidc?: OidcClient | null;
43
+ session_seconds?: number | null;
44
+ remembered_seconds?: number | null;
45
+ theme?: ServerTheme;
46
+ plugins_folder?: string | null;
33
47
  }
34
48
  export declare const user_only_backup_calls: ReadonlySet<string>;
35
49
  export declare function build_server(app: App, options: ServerOptions): Promise<FastifyInstance>;
@@ -38,6 +52,7 @@ export interface RunServerOptions {
38
52
  argv?: string[];
39
53
  env?: NodeJS.ProcessEnv;
40
54
  services?: StartServices;
55
+ routes?: AppRoutes;
41
56
  }
42
57
  export interface RunningServer {
43
58
  server: FastifyInstance;