@x-tech-laboratories/x-app 0.120.0 → 0.121.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 +20 -1
- package/dist/app/daemon.d.ts +7 -1
- package/dist/app/daemon.js +76 -8
- package/dist/app/define.d.ts +22 -1
- package/dist/app/define.js +34 -1
- package/dist/app/desktop.d.ts +13 -0
- package/dist/app/desktop.js +35 -3
- package/dist/app/host_tables.d.ts +20 -0
- package/dist/app/host_tables.js +91 -0
- package/dist/app/preload.js +5 -0
- package/dist/app/protocol.d.ts +29 -1
- package/dist/app/protocol.js +8 -1
- package/dist/app/remote_access.d.ts +17 -0
- package/dist/app/remote_access.js +85 -0
- package/dist/app/server.d.ts +11 -3
- package/dist/app/server.js +49 -14
- package/dist/app/services.d.ts +15 -0
- package/dist/app/web/app_page.js +43 -6
- package/dist/app/web/hosts.d.ts +4 -2
- package/dist/app/web/hosts.js +33 -0
- package/dist/app/web/page.d.ts +3 -0
- package/dist/app/web/page.js +24 -4
- package/dist/app/web/portal.d.ts +14 -0
- package/dist/app/web/portal.js +115 -0
- package/dist/app/web/settings_page.d.ts +5 -1
- package/dist/app/web/settings_page.js +25 -6
- package/dist/change_checks.js +1 -1
- package/dist/github_targets.d.ts +12 -0
- package/dist/github_targets.js +90 -0
- package/dist/remote_access_protocol.d.ts +26 -0
- package/dist/remote_access_protocol.js +33 -0
- package/dist/server/github_webhook.d.ts +2 -12
- package/dist/server/github_webhook.js +2 -87
- package/dist/web/react/remote_access_settings.d.ts +5 -0
- package/dist/web/react/remote_access_settings.js +55 -0
- package/dist/web/remote_daemon.d.ts +26 -0
- package/dist/web/remote_daemon.js +105 -0
- package/package.json +1 -1
|
@@ -0,0 +1,91 @@
|
|
|
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
|
+
// The tables the one asking may reach on this host, as the page reads them to know what it can offer.
|
|
7
|
+
export function host_abilities(app, reach, request) {
|
|
8
|
+
const admin = reach.is_admin(request);
|
|
9
|
+
const tables = app.tables_on(reach.kind, reach.from_network).filter((name) => admin || !reach.from_network || app.host_tables[name].network === "any");
|
|
10
|
+
return { admin, tables };
|
|
11
|
+
}
|
|
12
|
+
// What answers a table's calls for this caller, or null before the services handed it in.
|
|
13
|
+
function served_methods(services, name, from_elsewhere) {
|
|
14
|
+
const served = services().tables?.[name];
|
|
15
|
+
if (!served)
|
|
16
|
+
return null;
|
|
17
|
+
return (from_elsewhere ? (served.elsewhere ?? served.methods) : served.methods);
|
|
18
|
+
}
|
|
19
|
+
// ── Routes ───────────────────────────────────────────────────────────────────
|
|
20
|
+
// Every host table this host answers, as POST <api>/<table>/<call> with the arguments as a JSON list or by name; an
|
|
21
|
+
// admin's table refuses anyone else on the network, and a change is announced to every page but the one that made it.
|
|
22
|
+
export function register_host_tables(api, app, reach, services, changes) {
|
|
23
|
+
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))));
|
|
24
|
+
for (const name of app.tables_on(reach.kind, reach.from_network)) {
|
|
25
|
+
const table = app.host_tables[name];
|
|
26
|
+
const params = table.api;
|
|
27
|
+
api.post(`/${name}/:method`, async (request, reply) => {
|
|
28
|
+
const { method } = request.params;
|
|
29
|
+
if (!Object.hasOwn(table.api, method))
|
|
30
|
+
return send_text(reply, 404, `no call named ${method}`);
|
|
31
|
+
if (reach.from_network && table.network !== "any" && !reach.is_admin(request))
|
|
32
|
+
return send_text(reply, 403, `${method} needs an admin.`);
|
|
33
|
+
const methods = served_methods(services, name, reach.from_network);
|
|
34
|
+
if (!methods || typeof methods[method] !== "function")
|
|
35
|
+
return send_text(reply, 503, `${app.name} is still starting; try ${method} again in a moment.`);
|
|
36
|
+
const body = request.body ?? [];
|
|
37
|
+
let args;
|
|
38
|
+
if (Array.isArray(body))
|
|
39
|
+
args = body;
|
|
40
|
+
else if (typeof body === "object" && body !== null && params[method]) {
|
|
41
|
+
try {
|
|
42
|
+
args = positional_args(params[method], body);
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
return send_text(reply, 400, error.message);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
else
|
|
49
|
+
return send_text(reply, 400, "send the arguments as a JSON list or object");
|
|
50
|
+
const result = await methods[method](...args);
|
|
51
|
+
const read_only = app.is_read_only(method);
|
|
52
|
+
if (!read_only)
|
|
53
|
+
changes.announce_change(changes.client_id_of(request));
|
|
54
|
+
if (result === undefined)
|
|
55
|
+
return reply.code(204).send();
|
|
56
|
+
if (read_only)
|
|
57
|
+
reply.header("cache-control", "no-store");
|
|
58
|
+
// Fastify would send a string as bare text, which the caller could not tell from JSON.
|
|
59
|
+
return reply.type("application/json").send(JSON.stringify(result));
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
// The data calls and the host tables this host answers, as one set of MCP tools.
|
|
64
|
+
export function mcp_tools(app, reach, services, database, announce) {
|
|
65
|
+
const names = app.tables_on(reach.kind, true);
|
|
66
|
+
const api = Object.assign({}, app.mcp.api, ...names.map((name) => app.host_tables[name].api));
|
|
67
|
+
return {
|
|
68
|
+
api,
|
|
69
|
+
call: async (method, args, request) => {
|
|
70
|
+
const name = names.find((each) => Object.hasOwn(app.host_tables[each].api, method));
|
|
71
|
+
if (name === undefined)
|
|
72
|
+
return app.mcp.call(database, announce, method, args);
|
|
73
|
+
if (app.host_tables[name].network !== "any" && request && !reach.is_admin(request))
|
|
74
|
+
throw new Error(`${method} needs an admin's token`);
|
|
75
|
+
const methods = served_methods(services, name, true);
|
|
76
|
+
if (!methods || typeof methods[method] !== "function")
|
|
77
|
+
throw new Error(`${app.name} is still starting; try ${method} again in a moment.`);
|
|
78
|
+
const result = await methods[method](...args);
|
|
79
|
+
if (!app.is_read_only(method))
|
|
80
|
+
announce();
|
|
81
|
+
return result;
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
// The path each call is posted under, for the OpenAPI document.
|
|
86
|
+
export function call_path_of(app, kind) {
|
|
87
|
+
return (method) => {
|
|
88
|
+
const name = app.table_of_call(method, kind);
|
|
89
|
+
return name ? `/api/${name}/${method}` : `/api/call/${method}`;
|
|
90
|
+
};
|
|
91
|
+
}
|
package/dist/app/preload.js
CHANGED
|
@@ -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
|
}
|
package/dist/app/protocol.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ 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";
|
|
8
9
|
export { data_change_of, type DataChange } from "../sync_protocol.ts";
|
|
@@ -28,18 +29,36 @@ export interface DesktopMethods {
|
|
|
28
29
|
set_window_theme: (theme: "system" | "light" | "dark") => void;
|
|
29
30
|
get_data_paths: () => DataPaths;
|
|
30
31
|
show_data_path: (which: keyof DataPaths) => void;
|
|
32
|
+
pick_folder: (current: string) => string | null;
|
|
31
33
|
}
|
|
32
34
|
export interface DataPaths {
|
|
33
35
|
database: string;
|
|
34
36
|
backups: string;
|
|
35
37
|
}
|
|
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"];
|
|
38
|
+
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
39
|
export interface DaemonMethods {
|
|
38
40
|
get_desktop_settings: () => DesktopSettings;
|
|
39
41
|
set_desktop_setting: (key: keyof DesktopSettings, value: boolean) => void;
|
|
40
42
|
stop_daemon: () => void;
|
|
41
43
|
set_window_in_front: (in_front: boolean) => void;
|
|
42
44
|
}
|
|
45
|
+
export interface HostAbilities {
|
|
46
|
+
admin: boolean;
|
|
47
|
+
tables: string[];
|
|
48
|
+
}
|
|
49
|
+
export interface HostAbilityMethods {
|
|
50
|
+
get_host_abilities: () => HostAbilities;
|
|
51
|
+
}
|
|
52
|
+
export declare const host_ability_method_names: readonly ["get_host_abilities"];
|
|
53
|
+
export interface AppNotice {
|
|
54
|
+
kind: string;
|
|
55
|
+
title: string;
|
|
56
|
+
body: string;
|
|
57
|
+
key: string;
|
|
58
|
+
url: string;
|
|
59
|
+
}
|
|
60
|
+
export declare const notice_event = "notice";
|
|
61
|
+
export declare function notice_is_on(kind: string, switches: Readonly<Record<string, boolean>>): boolean;
|
|
43
62
|
export type Host = "web" | "desktop" | "android";
|
|
44
63
|
export interface BackupFolder {
|
|
45
64
|
name: () => Promise<string>;
|
|
@@ -56,6 +75,15 @@ export interface PageApi<Methods extends Record<keyof Methods, (...args: never[]
|
|
|
56
75
|
peer_listening?: PeerListeningClient;
|
|
57
76
|
desktop?: Client<DesktopMethods>;
|
|
58
77
|
local_mcp?: LocalMcpClient;
|
|
78
|
+
tables?: Readonly<Record<string, Client<Record<string, (...args: never[]) => unknown>>>>;
|
|
79
|
+
admin?: boolean;
|
|
80
|
+
remote_access?: RemoteAccessClient;
|
|
81
|
+
daemon_is_here?: boolean;
|
|
82
|
+
notice_switches?: {
|
|
83
|
+
get: () => Promise<Record<string, boolean>>;
|
|
84
|
+
set: (key: string, on: boolean) => Promise<void>;
|
|
85
|
+
};
|
|
86
|
+
reread_abilities?: () => Promise<Pick<PageApi, "admin" | "tables">>;
|
|
59
87
|
on_change: (listener: (change: DataChange | null) => void) => () => void;
|
|
60
88
|
on_event?: (event: string, listener: (data: unknown) => void) => () => void;
|
|
61
89
|
}
|
package/dist/app/protocol.js
CHANGED
|
@@ -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
|
+
}
|
package/dist/app/server.d.ts
CHANGED
|
@@ -5,8 +5,8 @@ import { AccountStore } from "../server/account_store.ts";
|
|
|
5
5
|
import { EventStream } from "../server/events.ts";
|
|
6
6
|
import { type SqlDatabase } from "../sql.ts";
|
|
7
7
|
import { type SyncPeer } from "../sync_peer.ts";
|
|
8
|
-
import type { App } from "./define.ts";
|
|
9
|
-
import { type StartServices } from "./services.ts";
|
|
8
|
+
import type { App, HostKind } from "./define.ts";
|
|
9
|
+
import { type AppRoutes, type HostServices, type StartServices } from "./services.ts";
|
|
10
10
|
export interface AppDatabase {
|
|
11
11
|
database: () => DatabaseSync;
|
|
12
12
|
back_up: () => Promise<void>;
|
|
@@ -27,9 +27,16 @@ export interface ServerOptions {
|
|
|
27
27
|
database: () => SqlDatabase;
|
|
28
28
|
accounts: AccountStore;
|
|
29
29
|
web_folder: string;
|
|
30
|
-
sync
|
|
30
|
+
sync?: SyncPeer;
|
|
31
31
|
changes: EventStream;
|
|
32
32
|
backup_methods: BackupMethods;
|
|
33
|
+
kind?: HostKind;
|
|
34
|
+
services?: () => HostServices;
|
|
35
|
+
routes?: AppRoutes;
|
|
36
|
+
https?: {
|
|
37
|
+
cert: Buffer;
|
|
38
|
+
key: Buffer;
|
|
39
|
+
};
|
|
33
40
|
}
|
|
34
41
|
export declare const user_only_backup_calls: ReadonlySet<string>;
|
|
35
42
|
export declare function build_server(app: App, options: ServerOptions): Promise<FastifyInstance>;
|
|
@@ -38,6 +45,7 @@ export interface RunServerOptions {
|
|
|
38
45
|
argv?: string[];
|
|
39
46
|
env?: NodeJS.ProcessEnv;
|
|
40
47
|
services?: StartServices;
|
|
48
|
+
routes?: AppRoutes;
|
|
41
49
|
}
|
|
42
50
|
export interface RunningServer {
|
|
43
51
|
server: FastifyInstance;
|
package/dist/app/server.js
CHANGED
|
@@ -16,17 +16,20 @@ import { caller_of, use_caller_scope } from "../caller.js";
|
|
|
16
16
|
import { node_caller_scope } from "../node_caller_scope.js";
|
|
17
17
|
import { AccountStore, holds_accounts, move_accounts } from "../server/account_store.js";
|
|
18
18
|
import { register_call_table } from "../server/call_table.js";
|
|
19
|
+
import { register_open_cors } from "../server/cors.js";
|
|
19
20
|
import { read_server_config } from "../server/config.js";
|
|
20
21
|
import { EventStream } from "../server/events.js";
|
|
21
22
|
import { register_mcp_route } from "../server/mcp.js";
|
|
22
23
|
import { load_accounts } from "../server/passwords.js";
|
|
23
24
|
import { BAD_JSON, register_error_replies, register_lenient_json_body, send_text } from "../server/replies.js";
|
|
24
25
|
import { sqlite_backups } from "../server/sqlite_backups.js";
|
|
25
|
-
import { register_sync_peer_routes } from "../server/sync_peer_routes.js";
|
|
26
|
+
import { register_sync_peer_routes, sync_peer_headers } from "../server/sync_peer_routes.js";
|
|
26
27
|
import { register_web_folder } from "../server/web_folder.js";
|
|
27
28
|
import { tidy_database, tidy_every_ms } from "../sql.js";
|
|
28
29
|
import { file_sync_storage } from "../sync_file_storage.js";
|
|
29
30
|
import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
|
|
31
|
+
import { call_path_of, mcp_tools, register_host_tables } from "./host_tables.js";
|
|
32
|
+
import { notice_event } from "./protocol.js";
|
|
30
33
|
import { declared_file_of, no_services, side_databases } from "./services.js";
|
|
31
34
|
// The server and the daemon run on Node, so a call's caller holds across its awaits.
|
|
32
35
|
use_caller_scope(node_caller_scope());
|
|
@@ -182,17 +185,32 @@ const admin_paths = ["/api/backups/", "/api/sync/"];
|
|
|
182
185
|
// Backup calls only the user at the page may make, since a restored backup could undo what only the user may change.
|
|
183
186
|
export const user_only_backup_calls = new Set(["restore_backup", "remove_backup", "set_backup_schedule"]);
|
|
184
187
|
export async function build_server(app, options) {
|
|
185
|
-
const server = fastify({ forceCloseConnections: true });
|
|
188
|
+
const server = fastify({ forceCloseConnections: true, ...(options.https ? { https: options.https } : {}) });
|
|
186
189
|
register_lenient_json_body(server);
|
|
187
190
|
register_error_replies(server);
|
|
191
|
+
const kind = options.kind ?? "server";
|
|
192
|
+
const services = options.services ?? (() => no_services);
|
|
193
|
+
// A phone that keeps no data calls from a page of its own with a token, the sign-in included; the event stream
|
|
194
|
+
// writes its own head, so it carries the open origin itself.
|
|
195
|
+
if (app.phone === "portal") {
|
|
196
|
+
await register_open_cors(server, { allowed_headers: sync_peer_headers });
|
|
197
|
+
server.addHook("onRequest", async (request, reply) => {
|
|
198
|
+
if (request.url.split("?")[0] === "/api/events")
|
|
199
|
+
reply.raw.setHeader("access-control-allow-origin", "*");
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
const admin_tables = app.tables_on(kind, true).filter((name) => app.host_tables[name].network !== "any").map((name) => `/api/${name}/`);
|
|
203
|
+
const is_admin = (request) => request.viewer !== null && request.viewer !== undefined && options.accounts.has_role(request.viewer.role, options.accounts.top_role);
|
|
204
|
+
const reach = { kind, from_network: true, is_admin };
|
|
188
205
|
await register_accounts(server, {
|
|
189
206
|
accounts: options.accounts,
|
|
190
207
|
cookie_name: `${app.id.replaceAll("-", "_")}_session`,
|
|
191
|
-
// Each peer call is sealed between the two devices, so it needs no sign-in
|
|
192
|
-
|
|
208
|
+
// Each peer call is sealed between the two devices, so it needs no sign-in, and the app's open routes check their
|
|
209
|
+
// callers themselves.
|
|
210
|
+
open_paths: ["/api/sync/peer", ...(options.routes?.open_paths ?? [])],
|
|
193
211
|
// A read-only token may still list and read through MCP, which posts every request.
|
|
194
212
|
read_only_paths: ["/api/mcp"],
|
|
195
|
-
needed: (_method, path) => (admin_paths.some((admin_path) => path.startsWith(admin_path)) ? { role: options.accounts.top_role } : "any"),
|
|
213
|
+
needed: (_method, path) => ([...admin_paths, ...admin_tables].some((admin_path) => path.startsWith(admin_path)) ? { role: options.accounts.top_role } : "any"),
|
|
196
214
|
// 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.
|
|
197
215
|
call_of: calls_under("/api/call"),
|
|
198
216
|
is_read_only: app.is_read_only,
|
|
@@ -200,19 +218,22 @@ export async function build_server(app, options) {
|
|
|
200
218
|
});
|
|
201
219
|
const { changes, database } = options;
|
|
202
220
|
const description = { title: app.name, version: app.version, description: app.instructions };
|
|
221
|
+
// A change made through MCP is announced to every page, since no page made it.
|
|
222
|
+
const tools = mcp_tools(app, reach, services, database, () => changes.announce_change());
|
|
223
|
+
const documented = Object.assign({}, app.api_spec, ...app.tables_on(kind, true).map((name) => app.host_tables[name].api));
|
|
203
224
|
await server.register(async (api) => {
|
|
204
225
|
changes.register(api, "/events");
|
|
205
226
|
register_app_calls(api, app, database, changes);
|
|
206
|
-
api
|
|
207
|
-
|
|
227
|
+
register_host_tables(api, app, reach, services, changes);
|
|
228
|
+
api.get("/openapi.json", async () => openapi_document(documented, { ...description, path_of: call_path_of(app, kind), is_read_only: app.is_read_only }));
|
|
208
229
|
await register_mcp_route(api, {
|
|
209
230
|
name: app.id,
|
|
210
231
|
version: app.version,
|
|
211
232
|
instructions: app.instructions,
|
|
212
|
-
api:
|
|
233
|
+
api: tools.api,
|
|
213
234
|
is_read_only: app.is_read_only,
|
|
214
235
|
page_only: app.mcp.page_only,
|
|
215
|
-
call: (method, args
|
|
236
|
+
call: (method, args, request) => tools.call(method, args, request),
|
|
216
237
|
});
|
|
217
238
|
// The server's backups, as the page's Settings reach them.
|
|
218
239
|
api.post("/backups/:method", async (request, reply) => {
|
|
@@ -229,9 +250,12 @@ export async function build_server(app, options) {
|
|
|
229
250
|
return reply.code(204).send();
|
|
230
251
|
return reply.type("application/json").header("cache-control", "no-store").send(JSON.stringify(result));
|
|
231
252
|
});
|
|
232
|
-
|
|
233
|
-
|
|
253
|
+
if (options.sync) {
|
|
254
|
+
register_sync_peer_routes(api, options.sync);
|
|
255
|
+
register_call_table(api, "/sync", sync_device_methods(options.sync), { is_read_only: app.is_read_only });
|
|
256
|
+
}
|
|
234
257
|
}, { prefix: "/api" });
|
|
258
|
+
await options.routes?.register(server, services);
|
|
235
259
|
await register_web_folder(server, { folder: options.web_folder });
|
|
236
260
|
return server;
|
|
237
261
|
}
|
|
@@ -271,6 +295,8 @@ export async function run_server(app, options) {
|
|
|
271
295
|
});
|
|
272
296
|
// Every page hears of a change, whether a page or another device made it, and which tables it touched.
|
|
273
297
|
const changes = new EventStream({ change_data: data_change_text(app, opened.database) });
|
|
298
|
+
// Answers the host tables and the app's routes once started; before then they say the server is still starting.
|
|
299
|
+
let services = no_services;
|
|
274
300
|
// The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be.
|
|
275
301
|
const sync = create_sync_peer({
|
|
276
302
|
app: app.id,
|
|
@@ -279,14 +305,17 @@ export async function run_server(app, options) {
|
|
|
279
305
|
storage: file_sync_storage({ file: join(dirname(database_path), "sync-peers.json"), back_up_before_replace: opened.back_up }),
|
|
280
306
|
device_name: `${app.name} server on ${hostname()}`,
|
|
281
307
|
addresses: () => (config.sync_address ? [config.sync_address] : []),
|
|
282
|
-
on_remote_change: () =>
|
|
308
|
+
on_remote_change: () => {
|
|
309
|
+
changes.announce_change();
|
|
310
|
+
services.after_remote_change?.();
|
|
311
|
+
},
|
|
283
312
|
});
|
|
284
|
-
const server = await build_server(app, { database: opened.database, accounts, web_folder: server_config.web_folder, sync, changes, backup_methods: opened.backup_methods });
|
|
313
|
+
const server = await build_server(app, { database: opened.database, accounts, web_folder: server_config.web_folder, sync, changes, backup_methods: opened.backup_methods, services: () => services, ...(options.routes ? { routes: options.routes } : {}) });
|
|
285
314
|
const stop_watching = watch_outside_changes(opened.database, () => changes.announce_change());
|
|
286
315
|
const address = await server.listen({ host: server_config.host, port: server_config.port });
|
|
287
316
|
sync.start();
|
|
288
317
|
const sides = side_databases(database_path);
|
|
289
|
-
|
|
318
|
+
services = options.services
|
|
290
319
|
? await options.services({
|
|
291
320
|
kind: "server",
|
|
292
321
|
database: opened.database,
|
|
@@ -296,11 +325,17 @@ export async function run_server(app, options) {
|
|
|
296
325
|
plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
|
|
297
326
|
declared_file: declared_file_of(app, options.env ?? process.env),
|
|
298
327
|
announce: (client_id) => changes.announce_change(client_id),
|
|
328
|
+
wrote: () => {
|
|
329
|
+
app.record_writes(opened.database());
|
|
330
|
+
changes.announce_change();
|
|
331
|
+
},
|
|
299
332
|
emit: (event, data) => changes.send(JSON.stringify(data), { event }),
|
|
300
333
|
side_database: sides.open,
|
|
301
334
|
back_up: opened.back_up,
|
|
302
335
|
window_in_front: () => false,
|
|
303
336
|
icon_path: null,
|
|
337
|
+
// The server shows no notice itself; the pages and phones working on it show them.
|
|
338
|
+
notify: (notice) => changes.send(JSON.stringify(notice), { event: notice_event }),
|
|
304
339
|
})
|
|
305
340
|
: no_services;
|
|
306
341
|
opened.on_restore({ before: () => services.before_restore?.(), after: () => services.after_restore?.() });
|
package/dist/app/services.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import type { FastifyInstance } from "fastify";
|
|
2
3
|
import type { App } from "./define.ts";
|
|
4
|
+
import type { AppNotice } from "./protocol.ts";
|
|
3
5
|
export interface HostContext {
|
|
4
6
|
kind: "server" | "desktop";
|
|
5
7
|
database: () => DatabaseSync;
|
|
@@ -9,18 +11,31 @@ export interface HostContext {
|
|
|
9
11
|
plugins_folder: string | null;
|
|
10
12
|
declared_file: string;
|
|
11
13
|
announce: (client_id?: string) => void;
|
|
14
|
+
wrote: () => void;
|
|
12
15
|
emit: (event: string, data: unknown) => void;
|
|
13
16
|
side_database: (name: string) => DatabaseSync;
|
|
14
17
|
back_up: () => Promise<void>;
|
|
15
18
|
window_in_front: () => boolean;
|
|
16
19
|
icon_path: string | null;
|
|
20
|
+
notify: (notice: AppNotice) => void;
|
|
21
|
+
}
|
|
22
|
+
export interface ServedTable {
|
|
23
|
+
methods: object;
|
|
24
|
+
elsewhere?: object;
|
|
17
25
|
}
|
|
18
26
|
export interface HostServices {
|
|
19
27
|
before_restore?: () => void;
|
|
20
28
|
after_restore?: () => void;
|
|
21
29
|
stop: () => void | Promise<void>;
|
|
30
|
+
tables?: Readonly<Record<string, ServedTable>>;
|
|
31
|
+
own?: unknown;
|
|
32
|
+
after_remote_change?: () => void;
|
|
22
33
|
}
|
|
23
34
|
export type StartServices = (context: HostContext) => HostServices | Promise<HostServices>;
|
|
35
|
+
export interface AppRoutes {
|
|
36
|
+
open_paths?: readonly string[];
|
|
37
|
+
register: (server: FastifyInstance, services: () => HostServices) => void | Promise<void>;
|
|
38
|
+
}
|
|
24
39
|
export declare function declared_file_of(app: Pick<App, "id" | "env_prefix">, env: NodeJS.ProcessEnv): string;
|
|
25
40
|
export interface SideDatabases {
|
|
26
41
|
open: (name: string) => DatabaseSync;
|
package/dist/app/web/app_page.js
CHANGED
|
@@ -4,18 +4,19 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
|
|
|
4
4
|
// ── Imports ──────────────────────────────────────────────────────────────────
|
|
5
5
|
import "@x-tech-laboratories/halon/halon-tokens.css";
|
|
6
6
|
import "@x-tech-laboratories/halon/halon.css";
|
|
7
|
-
import { Fragment, useEffect, useMemo, useRef } from "react";
|
|
7
|
+
import { Fragment, useEffect, useMemo, useRef, useState } from "react";
|
|
8
8
|
import { createRoot } from "react-dom/client";
|
|
9
9
|
import { create_accounts_client } from "../../web/accounts.js";
|
|
10
10
|
import { AccountView, UsersView } from "../../web/react/accounts.js";
|
|
11
11
|
import { SyncCertificatePrompt } from "../../web/react/certificates.js";
|
|
12
|
+
import { ConnectionSettings } from "../../web/react/connections.js";
|
|
12
13
|
import { PageHeading } from "../../web/react/layout.js";
|
|
13
14
|
import { Shell, use_route } from "../../web/react/shell.js";
|
|
14
15
|
import { SignInForm, use_account } from "../../web/react/sign_in.js";
|
|
15
16
|
import { SyncButton } from "../../web/react/sync_settings.js";
|
|
16
17
|
import { local_theme_storage, theme_choice } from "../../web/theme.js";
|
|
17
18
|
import { desktop_api, is_android, is_desktop, web_api } from "./hosts.js";
|
|
18
|
-
import { calls, data_watch, page, set_page_api, use_settings } from "./page.js";
|
|
19
|
+
import { calls, data_watch, page, set_page_api, set_page_reach, use_settings } from "./page.js";
|
|
19
20
|
import { SettingsView } from "./settings_page.js";
|
|
20
21
|
// ── Pages ────────────────────────────────────────────────────────────────────
|
|
21
22
|
// Relative, so a server behind a proxy under a folder keeps it.
|
|
@@ -82,7 +83,7 @@ function Pages({ pages, account }) {
|
|
|
82
83
|
const children = shown?.children && shown.children.length > 1 ? shown.children : [];
|
|
83
84
|
const subpage = children.find((child) => child.id === rest[0]) ?? children[0];
|
|
84
85
|
const label = shown ? (subpage ? `${subpage.label} · ${shown.label}` : shown.label) : is_account ? "Your account" : "Settings";
|
|
85
|
-
const view_key = route.parts.join("/");
|
|
86
|
+
const view_key = shown?.view_key ? [section, shown.view_key(rest)].join("/") : route.parts.join("/");
|
|
86
87
|
const chrome = pages.use_chrome?.(route.parts) ?? {};
|
|
87
88
|
const theme = use_theme(app);
|
|
88
89
|
useEffect(() => {
|
|
@@ -110,15 +111,44 @@ function Pages({ pages, account }) {
|
|
|
110
111
|
// A browser reaches the server's data, so it signs in; the desktop and phone apps keep their own and sign in only to sync.
|
|
111
112
|
function BrowserApp({ pages }) {
|
|
112
113
|
const { account, refresh, sign_out } = use_account(accounts);
|
|
114
|
+
// What the server lets this viewer reach is read again once they are signed in, as it was read before.
|
|
115
|
+
const [reach_read, set_reach_read] = useState(null);
|
|
116
|
+
const signed_in_as = account.state === "signed_in" ? account.me.name : null;
|
|
117
|
+
useEffect(() => {
|
|
118
|
+
if (signed_in_as === null || reach_read === signed_in_as)
|
|
119
|
+
return;
|
|
120
|
+
void (page().reread_abilities?.() ?? Promise.resolve({})).then((reach) => {
|
|
121
|
+
set_page_reach(reach);
|
|
122
|
+
set_reach_read(signed_in_as);
|
|
123
|
+
});
|
|
124
|
+
}, [signed_in_as, reach_read]);
|
|
113
125
|
if (account.state === "checking")
|
|
114
126
|
return null;
|
|
127
|
+
if (signed_in_as !== null && reach_read !== signed_in_as && page().reread_abilities)
|
|
128
|
+
return null;
|
|
115
129
|
if (account.state === "signed_out")
|
|
116
130
|
return _jsx(SignInForm, { client: accounts, title: pages.app.name, icon: pages.brand_icon ?? "icon.svg", on_signed_in: refresh });
|
|
117
131
|
return _jsx(Pages, { pages: pages, account: { me: account.me, refresh, sign_out } });
|
|
118
132
|
}
|
|
133
|
+
// A phone that keeps no data and has no host yet adds one before anything else.
|
|
134
|
+
function FirstConnection({ pages }) {
|
|
135
|
+
const { connections, certificates } = page();
|
|
136
|
+
const { app } = pages;
|
|
137
|
+
return (_jsxs(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", theme: theme_choice(local_theme_storage(`${app.id}-theme`)), children: [_jsx(PageHeading, { title: `Connect to ${app.name}`, subtitle: `Add the computer this phone works on, with its address and an admin's name and password. Turn on Let other devices connect in its Settings first.` }), _jsx(ConnectionSettings, { client: connections, certificates: certificates, placeholder: app.server_example })] }));
|
|
138
|
+
}
|
|
119
139
|
// A device that syncs asks to trust its server's certificate whenever sync fails over it.
|
|
120
140
|
function DeviceApp({ pages }) {
|
|
121
|
-
const { certificates, device } = page();
|
|
141
|
+
const { certificates, connections, device, host } = page();
|
|
142
|
+
const portal = host === "android" && pages.app.phone === "portal" && connections !== undefined;
|
|
143
|
+
const [has_host, set_has_host] = useState(portal ? null : true);
|
|
144
|
+
useEffect(() => {
|
|
145
|
+
if (portal)
|
|
146
|
+
void connections.list_connections().then((view) => set_has_host(view.current !== null), () => set_has_host(true));
|
|
147
|
+
}, [portal, connections]);
|
|
148
|
+
if (has_host === null)
|
|
149
|
+
return null;
|
|
150
|
+
if (!has_host)
|
|
151
|
+
return _jsx(FirstConnection, { pages: pages });
|
|
122
152
|
return _jsxs(_Fragment, { children: [device && certificates && _jsx(SyncCertificatePrompt, { device: device, certificates: certificates, subscribe: (listener) => data_watch.subscribe(listener) }), _jsx(Pages, { pages: pages, account: null })] });
|
|
123
153
|
}
|
|
124
154
|
export function AppView({ pages }) {
|
|
@@ -126,9 +156,14 @@ export function AppView({ pages }) {
|
|
|
126
156
|
}
|
|
127
157
|
// ── Start ────────────────────────────────────────────────────────────────────
|
|
128
158
|
// The phone's code loads only on the phone, so a browser never fetches SQLite.
|
|
129
|
-
async function host_api(app,
|
|
159
|
+
async function host_api(app, pages) {
|
|
130
160
|
if (is_desktop(app))
|
|
131
161
|
return desktop_api(app);
|
|
162
|
+
if (is_android() && app.phone === "portal") {
|
|
163
|
+
const [{ portal_api }, { App: CapacitorApp }] = await Promise.all([import("./portal.js"), import("@capacitor/app")]);
|
|
164
|
+
return portal_api(app, { lifecycle: CapacitorApp, ...(pages.phone_notifications ? { notifications: await pages.phone_notifications() } : {}) });
|
|
165
|
+
}
|
|
166
|
+
const phone_services = pages.phone_services;
|
|
132
167
|
if (is_android()) {
|
|
133
168
|
const { android_api } = await import("./android.js");
|
|
134
169
|
return android_api(app, phone_services ? { services: await phone_services() } : {});
|
|
@@ -137,7 +172,9 @@ async function host_api(app, phone_services) {
|
|
|
137
172
|
}
|
|
138
173
|
// Starts the page on whichever host it runs: the desktop app, the phone app or a browser.
|
|
139
174
|
export async function render_app(pages, root = document.getElementById("app")) {
|
|
140
|
-
const api = await host_api(pages.app, pages
|
|
175
|
+
const api = await host_api(pages.app, pages);
|
|
176
|
+
if (api.reread_abilities)
|
|
177
|
+
Object.assign(api, await api.reread_abilities());
|
|
141
178
|
set_page_api(api);
|
|
142
179
|
// A link the desktop app was opened with, or a tray row, opens its page.
|
|
143
180
|
api.on_event?.("open", (route) => {
|
package/dist/app/web/hosts.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { App } from "../define.ts";
|
|
2
|
-
import { type PageApi } from "../protocol.ts";
|
|
2
|
+
import { type HostAbilities, type PageApi } from "../protocol.ts";
|
|
3
|
+
export declare function read_host_abilities(read: () => Promise<unknown>): Promise<HostAbilities>;
|
|
4
|
+
export declare function host_tables_of(app: Pick<App, "bridges">, abilities: HostAbilities, client_of: (name: string) => unknown): NonNullable<PageApi["tables"]>;
|
|
3
5
|
export declare function web_api(app: Pick<App, "bridges">): PageApi;
|
|
4
6
|
export declare function is_desktop(app: Pick<App, "bridges">): boolean;
|
|
5
|
-
export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "local_mcp">>): Promise<PageApi>;
|
|
7
|
+
export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "local_mcp" | "remote_access">>): Promise<PageApi>;
|
|
6
8
|
export declare function is_android(): boolean;
|