@x-tech-laboratories/x-app 0.119.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 +21 -2
- 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 +12 -4
- package/dist/app/server.js +63 -14
- package/dist/app/services.d.ts +15 -0
- package/dist/app/web/android.d.ts +1 -1
- package/dist/app/web/android.js +9 -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/sql.d.ts +5 -0
- package/dist/sql.js +21 -0
- 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
|
@@ -3,10 +3,10 @@ import { type FastifyInstance } from "fastify";
|
|
|
3
3
|
import { type BackupMethods } from "../backups.ts";
|
|
4
4
|
import { AccountStore } from "../server/account_store.ts";
|
|
5
5
|
import { EventStream } from "../server/events.ts";
|
|
6
|
-
import type
|
|
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,16 +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";
|
|
28
|
+
import { tidy_database, tidy_every_ms } from "../sql.js";
|
|
27
29
|
import { file_sync_storage } from "../sync_file_storage.js";
|
|
28
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";
|
|
29
33
|
import { declared_file_of, no_services, side_databases } from "./services.js";
|
|
30
34
|
// The server and the daemon run on Node, so a call's caller holds across its awaits.
|
|
31
35
|
use_caller_scope(node_caller_scope());
|
|
@@ -48,6 +52,7 @@ export function open_app_database(app, path, backups_folder) {
|
|
|
48
52
|
open: () => {
|
|
49
53
|
database = new DatabaseSync(path);
|
|
50
54
|
start(database);
|
|
55
|
+
tidy_database(database);
|
|
51
56
|
restore_hooks.after?.();
|
|
52
57
|
},
|
|
53
58
|
// The restored data no longer matches other devices', so sync asks again which copy wins.
|
|
@@ -64,6 +69,17 @@ export function open_app_database(app, path, backups_folder) {
|
|
|
64
69
|
start(database);
|
|
65
70
|
adopt_schedule_file(app, database, join(dirname(path), "backup-schedule.json"));
|
|
66
71
|
const keeper = keep_backing_up(kept, () => app.read_backup_schedule(database));
|
|
72
|
+
// The file is tidied on opening and once a day, so space freed by pruning and clean-ups goes back to the disk.
|
|
73
|
+
tidy_database(database);
|
|
74
|
+
const tidy_timer = setInterval(() => {
|
|
75
|
+
try {
|
|
76
|
+
tidy_database(database);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
// Closed for a restore, which tidies the copy it opens.
|
|
80
|
+
}
|
|
81
|
+
}, tidy_every_ms);
|
|
82
|
+
tidy_timer.unref?.();
|
|
67
83
|
return {
|
|
68
84
|
database: () => database,
|
|
69
85
|
back_up: async () => void (await kept.create()),
|
|
@@ -71,6 +87,7 @@ export function open_app_database(app, path, backups_folder) {
|
|
|
71
87
|
on_restore: (hooks) => void (restore_hooks = hooks),
|
|
72
88
|
close: () => {
|
|
73
89
|
keeper.stop();
|
|
90
|
+
clearInterval(tidy_timer);
|
|
74
91
|
database.close();
|
|
75
92
|
},
|
|
76
93
|
};
|
|
@@ -168,17 +185,32 @@ const admin_paths = ["/api/backups/", "/api/sync/"];
|
|
|
168
185
|
// Backup calls only the user at the page may make, since a restored backup could undo what only the user may change.
|
|
169
186
|
export const user_only_backup_calls = new Set(["restore_backup", "remove_backup", "set_backup_schedule"]);
|
|
170
187
|
export async function build_server(app, options) {
|
|
171
|
-
const server = fastify({ forceCloseConnections: true });
|
|
188
|
+
const server = fastify({ forceCloseConnections: true, ...(options.https ? { https: options.https } : {}) });
|
|
172
189
|
register_lenient_json_body(server);
|
|
173
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 };
|
|
174
205
|
await register_accounts(server, {
|
|
175
206
|
accounts: options.accounts,
|
|
176
207
|
cookie_name: `${app.id.replaceAll("-", "_")}_session`,
|
|
177
|
-
// Each peer call is sealed between the two devices, so it needs no sign-in
|
|
178
|
-
|
|
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 ?? [])],
|
|
179
211
|
// A read-only token may still list and read through MCP, which posts every request.
|
|
180
212
|
read_only_paths: ["/api/mcp"],
|
|
181
|
-
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"),
|
|
182
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.
|
|
183
215
|
call_of: calls_under("/api/call"),
|
|
184
216
|
is_read_only: app.is_read_only,
|
|
@@ -186,19 +218,22 @@ export async function build_server(app, options) {
|
|
|
186
218
|
});
|
|
187
219
|
const { changes, database } = options;
|
|
188
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));
|
|
189
224
|
await server.register(async (api) => {
|
|
190
225
|
changes.register(api, "/events");
|
|
191
226
|
register_app_calls(api, app, database, changes);
|
|
192
|
-
api
|
|
193
|
-
|
|
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 }));
|
|
194
229
|
await register_mcp_route(api, {
|
|
195
230
|
name: app.id,
|
|
196
231
|
version: app.version,
|
|
197
232
|
instructions: app.instructions,
|
|
198
|
-
api:
|
|
233
|
+
api: tools.api,
|
|
199
234
|
is_read_only: app.is_read_only,
|
|
200
235
|
page_only: app.mcp.page_only,
|
|
201
|
-
call: (method, args
|
|
236
|
+
call: (method, args, request) => tools.call(method, args, request),
|
|
202
237
|
});
|
|
203
238
|
// The server's backups, as the page's Settings reach them.
|
|
204
239
|
api.post("/backups/:method", async (request, reply) => {
|
|
@@ -215,9 +250,12 @@ export async function build_server(app, options) {
|
|
|
215
250
|
return reply.code(204).send();
|
|
216
251
|
return reply.type("application/json").header("cache-control", "no-store").send(JSON.stringify(result));
|
|
217
252
|
});
|
|
218
|
-
|
|
219
|
-
|
|
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
|
+
}
|
|
220
257
|
}, { prefix: "/api" });
|
|
258
|
+
await options.routes?.register(server, services);
|
|
221
259
|
await register_web_folder(server, { folder: options.web_folder });
|
|
222
260
|
return server;
|
|
223
261
|
}
|
|
@@ -257,6 +295,8 @@ export async function run_server(app, options) {
|
|
|
257
295
|
});
|
|
258
296
|
// Every page hears of a change, whether a page or another device made it, and which tables it touched.
|
|
259
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;
|
|
260
300
|
// The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be.
|
|
261
301
|
const sync = create_sync_peer({
|
|
262
302
|
app: app.id,
|
|
@@ -265,14 +305,17 @@ export async function run_server(app, options) {
|
|
|
265
305
|
storage: file_sync_storage({ file: join(dirname(database_path), "sync-peers.json"), back_up_before_replace: opened.back_up }),
|
|
266
306
|
device_name: `${app.name} server on ${hostname()}`,
|
|
267
307
|
addresses: () => (config.sync_address ? [config.sync_address] : []),
|
|
268
|
-
on_remote_change: () =>
|
|
308
|
+
on_remote_change: () => {
|
|
309
|
+
changes.announce_change();
|
|
310
|
+
services.after_remote_change?.();
|
|
311
|
+
},
|
|
269
312
|
});
|
|
270
|
-
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 } : {}) });
|
|
271
314
|
const stop_watching = watch_outside_changes(opened.database, () => changes.announce_change());
|
|
272
315
|
const address = await server.listen({ host: server_config.host, port: server_config.port });
|
|
273
316
|
sync.start();
|
|
274
317
|
const sides = side_databases(database_path);
|
|
275
|
-
|
|
318
|
+
services = options.services
|
|
276
319
|
? await options.services({
|
|
277
320
|
kind: "server",
|
|
278
321
|
database: opened.database,
|
|
@@ -282,11 +325,17 @@ export async function run_server(app, options) {
|
|
|
282
325
|
plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
|
|
283
326
|
declared_file: declared_file_of(app, options.env ?? process.env),
|
|
284
327
|
announce: (client_id) => changes.announce_change(client_id),
|
|
328
|
+
wrote: () => {
|
|
329
|
+
app.record_writes(opened.database());
|
|
330
|
+
changes.announce_change();
|
|
331
|
+
},
|
|
285
332
|
emit: (event, data) => changes.send(JSON.stringify(data), { event }),
|
|
286
333
|
side_database: sides.open,
|
|
287
334
|
back_up: opened.back_up,
|
|
288
335
|
window_in_front: () => false,
|
|
289
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 }),
|
|
290
339
|
})
|
|
291
340
|
: no_services;
|
|
292
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;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type BackupFolderPlugin } from "../../phone_backups.ts";
|
|
2
2
|
import { type FileStore } from "../../web/sqlite_wasm.ts";
|
|
3
|
-
import type
|
|
3
|
+
import { type SqlDatabase } from "../../sql.ts";
|
|
4
4
|
import type { App } from "../define.ts";
|
|
5
5
|
import type { PageApi } from "../protocol.ts";
|
|
6
6
|
export interface PhoneLifecycle {
|
package/dist/app/web/android.js
CHANGED
|
@@ -8,6 +8,7 @@ import { phone_certificates } from "../../phone_certificates.js";
|
|
|
8
8
|
import { create_sync_peer, sync_device_methods } from "../../sync_peer.js";
|
|
9
9
|
import { indexed_db_files, open_wasm_database } from "../../web/sqlite_wasm.js";
|
|
10
10
|
import { local_sync_storage } from "../../web/sync_storage.js";
|
|
11
|
+
import { tidy_database, tidy_every_ms } from "../../sql.js";
|
|
11
12
|
// An older version kept the phone's backup schedule in the page's storage; it moves into the setting once.
|
|
12
13
|
function adopt_stored_schedule(app, database, storage) {
|
|
13
14
|
const key = `${app.id}-backup-schedule`;
|
|
@@ -55,6 +56,9 @@ export async function android_api(app, options = {}) {
|
|
|
55
56
|
await kept.create();
|
|
56
57
|
app.open_store(database.connection);
|
|
57
58
|
adopt_stored_schedule(app, database.connection, options.storage ?? page_storage());
|
|
59
|
+
// Tidied on opening and on coming back after a day or more, so freed space leaves the phone's storage too.
|
|
60
|
+
let tidied_at = Date.now();
|
|
61
|
+
tidy_database(database.connection);
|
|
58
62
|
await database.save_now();
|
|
59
63
|
const keeper = keep_backing_up(kept, () => app.read_backup_schedule(database.connection));
|
|
60
64
|
const services = options.services ? await options.services({ database: () => database.connection }) : {};
|
|
@@ -80,6 +84,11 @@ export async function android_api(app, options = {}) {
|
|
|
80
84
|
// A phone may close the app at any moment once it is in the background, so the database is saved straight away.
|
|
81
85
|
lifecycle.addListener("pause", () => void database.save_now());
|
|
82
86
|
lifecycle.addListener("resume", () => {
|
|
87
|
+
if (Date.now() - tidied_at >= tidy_every_ms) {
|
|
88
|
+
tidied_at = Date.now();
|
|
89
|
+
if (tidy_database(database.connection))
|
|
90
|
+
void database.save_now();
|
|
91
|
+
}
|
|
83
92
|
void sync.sync_now();
|
|
84
93
|
services.changed?.();
|
|
85
94
|
});
|