@x-tech-laboratories/x-app 0.125.0 → 0.127.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 +22 -2
- package/dist/app/daemon.js +10 -1
- package/dist/app/define.d.ts +23 -1
- package/dist/app/define.js +19 -1
- package/dist/app/desktop.d.ts +3 -0
- package/dist/app/desktop.js +79 -12
- package/dist/app/preload.js +1 -0
- package/dist/app/protocol.d.ts +8 -1
- package/dist/app/protocol.js +7 -1
- package/dist/app/server.d.ts +4 -0
- package/dist/app/server.js +15 -2
- package/dist/app/server_fetch.d.ts +7 -0
- package/dist/app/server_fetch.js +37 -0
- package/dist/app/services.d.ts +2 -0
- package/dist/app/web/android.d.ts +4 -0
- package/dist/app/web/android.js +25 -2
- package/dist/app/web/hosts.d.ts +2 -2
- package/dist/app/web/hosts.js +13 -2
- package/dist/app/web/portal.js +3 -0
- package/dist/app/web/settings_page.d.ts +4 -0
- package/dist/app/web/settings_page.js +11 -5
- package/dist/server/account_store.js +10 -1
- package/dist/server/passwords.d.ts +2 -2
- package/dist/server/passwords.js +5 -4
- package/dist/server/synced_file_route.d.ts +3 -0
- package/dist/server/synced_file_route.js +14 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -267,8 +267,28 @@ An app whose work needs a computer, such as one that runs programs on checkouts,
|
|
|
267
267
|
webhook, mail or Apprise). `context.withdraw(key)` takes it back wherever it shows, such as a call that stopped ringing.
|
|
268
268
|
- **Following changes**: the services' `after_change(change)` runs after every change the pages hear of, whoever made
|
|
269
269
|
it, with the synced tables written when known, such as to follow a setting; `after_remote_change` runs only for sync's.
|
|
270
|
-
- **Plugins**: the services load `context.plugins_folder`;
|
|
271
|
-
`/api/plugins
|
|
270
|
+
- **Plugins**: the services load `context.plugins_folder`; the page loads the plugins' web sides from
|
|
271
|
+
`page().plugin_base` (`index.json` and the files it names): a browser from the server's `/api/plugins/`, and a desktop
|
|
272
|
+
window through `page().read_plugin_file(path)` from the plugins folder of the daemon it works on.
|
|
273
|
+
- **Synced files**: `synced_files: { folder: "covers", referenced }` keeps files named by their content beside the
|
|
274
|
+
database on every host, the phone's in IndexedDB, and sync sends the ones `referenced(database)` still names. The
|
|
275
|
+
services keep them through `context.files`, the server and daemon serve them at `/api/files/<name>` to those signed
|
|
276
|
+
in, and the page shows one from `page().file_src(name)`: the server's route, the desktop's `<id>-file://<name>` from
|
|
277
|
+
this computer or the server in use, or a blob on the phone.
|
|
278
|
+
- **A desktop portal**: `desktop: "portal"` makes the desktop app a window onto a server chosen under Connections, as
|
|
279
|
+
`phone: "portal"` does the phone: it runs no daemon, keeps no data and keeps its own switches in its profile.
|
|
280
|
+
- **Pages on REST routes**: `page().fetch("api/runs")` reaches the app's own server routes from every host: the
|
|
281
|
+
browser's own sign-in, and on a portal the server chosen under Connections with this device's token, the desktop's
|
|
282
|
+
through its main process (`app/server_fetch` does the rewriting).
|
|
283
|
+
- **Sign-in from the config**: `admin_name` names the admin a bare hash in the accounts file signs in as, and
|
|
284
|
+
`proxy_user_header` (with `trusted_proxies`, 127.0.0.1 and ::1 unless set) signs in whoever a reverse proxy on those
|
|
285
|
+
addresses names; `define_app`'s `check_access` checks a user's access when an admin sets it, such as a list of grants.
|
|
286
|
+
- **Keys in a settings export**: `render_app`'s `exports_secrets: true` offers "Include keys and tokens" on exporting
|
|
287
|
+
the settings, for an app whose settings hold other services' keys.
|
|
288
|
+
- **Links to other apps**: `run_desktop`'s `external_schemes`, such as `["stremio:", "steam:"]`, opens those links in
|
|
289
|
+
the apps installed for them, beside http and mailto.
|
|
290
|
+
- **Work after the answer**: a call returning `new Background(answer, finished)` answers at once; its writes so far are
|
|
291
|
+
recorded and announced, and again once `finished` settles, such as a refresh that downloads as it goes.
|
|
272
292
|
- **Other devices**: `remote_access: true` lets the daemon serve its calls and host tables on the network, and
|
|
273
293
|
`phone: "portal"` makes the phone a window onto a host chosen under Connections, keeping no data, its notices shown
|
|
274
294
|
through `phone_notifications` (Capacitor's `LocalNotifications`).
|
package/dist/app/daemon.js
CHANGED
|
@@ -20,6 +20,8 @@ import { file_sync_storage } from "../sync_file_storage.js";
|
|
|
20
20
|
import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
|
|
21
21
|
import { keep_listening_for_peers } from "../sync_peer_listening.js";
|
|
22
22
|
import { mcp_tools, register_host_tables } from "./host_tables.js";
|
|
23
|
+
import { folder_file_store } from "../node_file_store.js";
|
|
24
|
+
import { register_synced_files } from "../server/synced_file_route.js";
|
|
23
25
|
import { notice_event, notice_withdrawn_event, notice_is_on, read_desktop_settings } from "./protocol.js";
|
|
24
26
|
import { create_remote_access } from "./remote_access.js";
|
|
25
27
|
import { declared_file_of, no_services, side_databases } from "./services.js";
|
|
@@ -41,12 +43,15 @@ export async function start_daemon(app, options) {
|
|
|
41
43
|
const certificates = create_certificate_trust({ file: join(profile, "trusted-certificates.json"), use_in_node: true });
|
|
42
44
|
// Off until "Let other devices connect" is turned on; then other devices reach this computer's sync on its port.
|
|
43
45
|
const listening = keep_listening_for_peers({ peer: () => sync, app: app.id, file: join(profile, "sync-listening.json"), default_port: options.default_peer_port ?? app.ports.peer });
|
|
46
|
+
// The app's synced files, such as covers, kept beside the database.
|
|
47
|
+
const files = app.synced_files ? folder_file_store(join(profile, app.synced_files.folder)) : null;
|
|
44
48
|
// This computer is one sync peer among the devices, reaching out to the ones it is paired with.
|
|
45
49
|
const sync = create_sync_peer({
|
|
46
50
|
app: app.id,
|
|
47
51
|
engine: app.sync_engine,
|
|
48
52
|
database: opened.database,
|
|
49
53
|
storage: file_sync_storage({ file: join(profile, "sync-peers.json"), back_up_before_replace: opened.back_up }),
|
|
54
|
+
...(files ? { files: { store: files, referenced: app.synced_files.referenced } } : {}),
|
|
50
55
|
device_name: `${app.name} on ${hostname()}`,
|
|
51
56
|
addresses: () => listening.addresses(),
|
|
52
57
|
on_remote_change: () => {
|
|
@@ -121,12 +126,13 @@ export async function start_daemon(app, options) {
|
|
|
121
126
|
default_port: app.ports.server,
|
|
122
127
|
build: (admins, https) => build_server(app, {
|
|
123
128
|
database: opened.database,
|
|
124
|
-
accounts: new AccountStore({ database: accounts_database, app_name: app.name, declared: admins, ...(app.token_prefix ? { token_prefix: app.token_prefix } : {}) }),
|
|
129
|
+
accounts: new AccountStore({ database: accounts_database, app_name: app.name, declared: admins, ...(app.token_prefix ? { token_prefix: app.token_prefix } : {}), ...(app.check_access ? { check_access: app.check_access } : {}) }),
|
|
125
130
|
web_folder,
|
|
126
131
|
changes,
|
|
127
132
|
backup_methods: opened.backup_methods,
|
|
128
133
|
kind: "desktop",
|
|
129
134
|
services: services_now,
|
|
135
|
+
files,
|
|
130
136
|
...(options.routes ? { routes: options.routes } : {}),
|
|
131
137
|
...(https ? { https } : {}),
|
|
132
138
|
}),
|
|
@@ -154,6 +160,8 @@ export async function start_daemon(app, options) {
|
|
|
154
160
|
// This computer's own window reaches every host table, those kept to it included.
|
|
155
161
|
const reach = { kind: "desktop", from_network: false, is_admin: () => true, has_role: () => true };
|
|
156
162
|
register_host_tables(api, app, reach, services_now, changes);
|
|
163
|
+
if (files)
|
|
164
|
+
register_synced_files(api, files);
|
|
157
165
|
}, { prefix: "/api" });
|
|
158
166
|
// ── Lifecycle ──────────────────────────────────────────────────────
|
|
159
167
|
let stopping = null;
|
|
@@ -203,6 +211,7 @@ export async function start_daemon(app, options) {
|
|
|
203
211
|
declared_tokens: () => [],
|
|
204
212
|
reread_declared_tokens: () => undefined,
|
|
205
213
|
plugins_folder: join(profile, "plugins"),
|
|
214
|
+
files,
|
|
206
215
|
declared_file: options.declared_file ?? `/etc/${app.id}/declared.json`,
|
|
207
216
|
announce: (client_id) => changes.announce_change(client_id),
|
|
208
217
|
wrote: () => {
|
package/dist/app/define.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { type Caller } from "../caller.ts";
|
|
|
5
5
|
import { type CertificateMethods } from "../certificate_protocol.ts";
|
|
6
6
|
import { type ConnectionMethods } from "../connection_protocol.ts";
|
|
7
7
|
import { type Bridge } from "../electron/bridge.ts";
|
|
8
|
+
import type { FetchMethod } from "../electron/fetch.ts";
|
|
8
9
|
import { type EventsBridge } from "../electron/events.ts";
|
|
9
10
|
import type { History } from "../history.ts";
|
|
10
11
|
import type { ScopeSpec } from "../server/declared_tokens.ts";
|
|
@@ -42,8 +43,14 @@ export interface HostTable<Methods = Record<string, (...args: never[]) => unknow
|
|
|
42
43
|
export declare function route_of(table: HostTable, method: string): string | null;
|
|
43
44
|
declare const host_table_route: (name: string) => string;
|
|
44
45
|
type UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends (value: infer Both) => void ? Both : never;
|
|
46
|
+
export declare class Background<Answer> {
|
|
47
|
+
readonly answer: Answer;
|
|
48
|
+
readonly finished: Promise<unknown>;
|
|
49
|
+
constructor(answer: Answer, finished: Promise<unknown>);
|
|
50
|
+
}
|
|
51
|
+
type Answer<Result> = Result extends Background<infer Carried> ? Carried : Result;
|
|
45
52
|
type Bound<Methods> = {
|
|
46
|
-
[Name in keyof Methods]: Methods[Name] extends (database: SqlDatabase, ...args: infer Args) => infer Result ? (...args: Args) => Result : never;
|
|
53
|
+
[Name in keyof Methods]: Methods[Name] extends (database: SqlDatabase, ...args: infer Args) => infer Result ? (...args: Args) => Answer<Result> : never;
|
|
47
54
|
};
|
|
48
55
|
type StoreMethodsOf<Features extends readonly Feature[]> = UnionToIntersection<Features[number]["methods"]>;
|
|
49
56
|
export type AppMethods<Features extends readonly Feature[]> = Bound<SettingsMethods & StoreMethodsOf<Features>>;
|
|
@@ -81,11 +88,17 @@ export interface AppOptions<Features extends readonly Feature[]> {
|
|
|
81
88
|
local_mcp?: {
|
|
82
89
|
default_port: number;
|
|
83
90
|
};
|
|
91
|
+
synced_files?: {
|
|
92
|
+
folder: string;
|
|
93
|
+
referenced: (database: SqlDatabase) => string[];
|
|
94
|
+
};
|
|
84
95
|
synced_theme?: boolean;
|
|
85
96
|
host_tables?: Readonly<Record<string, HostTable>>;
|
|
86
97
|
remote_access?: boolean;
|
|
98
|
+
desktop?: "daemon" | "portal";
|
|
87
99
|
phone?: "device" | "portal";
|
|
88
100
|
roles?: readonly string[];
|
|
101
|
+
check_access?: (value: unknown) => unknown;
|
|
89
102
|
sync?: boolean;
|
|
90
103
|
declared_tokens?: {
|
|
91
104
|
key: string;
|
|
@@ -123,6 +136,9 @@ export interface AppBridges<Methods extends Record<keyof Methods, (...args: neve
|
|
|
123
136
|
events: EventsBridge<AppEvents>;
|
|
124
137
|
host: Bridge<HostAbilityMethods>;
|
|
125
138
|
remote_access: Bridge<RemoteAccessMethods>;
|
|
139
|
+
fetch: Bridge<{
|
|
140
|
+
http_fetch: FetchMethod;
|
|
141
|
+
}>;
|
|
126
142
|
host_tables: Readonly<Record<string, Bridge<Record<string, (...args: never[]) => unknown>>>>;
|
|
127
143
|
}
|
|
128
144
|
export declare function define_app<const Features extends readonly Feature[]>(options: AppOptions<Features>): {
|
|
@@ -158,10 +174,16 @@ export declare function define_app<const Features extends readonly Feature[]>(op
|
|
|
158
174
|
local_mcp?: {
|
|
159
175
|
default_port: number;
|
|
160
176
|
};
|
|
177
|
+
synced_files?: {
|
|
178
|
+
folder: string;
|
|
179
|
+
referenced: (database: SqlDatabase) => string[];
|
|
180
|
+
};
|
|
161
181
|
synced_theme?: boolean;
|
|
162
182
|
remote_access?: boolean;
|
|
183
|
+
desktop?: "daemon" | "portal";
|
|
163
184
|
phone?: "device" | "portal";
|
|
164
185
|
roles?: readonly string[];
|
|
186
|
+
check_access?: (value: unknown) => unknown;
|
|
165
187
|
sync?: boolean;
|
|
166
188
|
declared_tokens?: {
|
|
167
189
|
key: string;
|
package/dist/app/define.js
CHANGED
|
@@ -34,6 +34,16 @@ export function route_of(table, method) {
|
|
|
34
34
|
}
|
|
35
35
|
// The path a host table's calls are posted under, such as /api/stages/.
|
|
36
36
|
const host_table_route = (name) => `/api/${name}/`;
|
|
37
|
+
// A call's answer while its work goes on, such as a library refresh: the caller has the answer at once, and the
|
|
38
|
+
// features' catch-up, the history and the other pages follow once the work has finished, as after any write.
|
|
39
|
+
export class Background {
|
|
40
|
+
answer;
|
|
41
|
+
finished;
|
|
42
|
+
constructor(answer, finished) {
|
|
43
|
+
this.answer = answer;
|
|
44
|
+
this.finished = finished;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
37
47
|
// The settings every app keeps: how long its history reaches back, and this device's backup schedule.
|
|
38
48
|
export const base_setting_defaults = {
|
|
39
49
|
// How many days of changes the history keeps, each item keeping its newest version; 0 keeps them all.
|
|
@@ -170,7 +180,14 @@ export function define_app(options) {
|
|
|
170
180
|
on_change();
|
|
171
181
|
return value;
|
|
172
182
|
};
|
|
173
|
-
|
|
183
|
+
if (result instanceof Promise)
|
|
184
|
+
return result.then(done);
|
|
185
|
+
if (!(result instanceof Background))
|
|
186
|
+
return done(result);
|
|
187
|
+
// The write so far is announced now, and again once the work it left running has finished.
|
|
188
|
+
done(undefined);
|
|
189
|
+
void result.finished.then(() => done(undefined), () => done(undefined));
|
|
190
|
+
return result.answer;
|
|
174
191
|
};
|
|
175
192
|
return [name, call];
|
|
176
193
|
});
|
|
@@ -249,6 +266,7 @@ export function define_app(options) {
|
|
|
249
266
|
local_mcp: define_bridge(`${prefix}_local_mcp`, local_mcp_method_names),
|
|
250
267
|
events: define_events(`${prefix}_events`),
|
|
251
268
|
host: define_bridge(`${prefix}_host`, host_ability_method_names),
|
|
269
|
+
fetch: define_bridge(`${prefix}_fetch`, ["http_fetch"]),
|
|
252
270
|
// Letting other devices reach this computer's daemon, answered over its socket alone.
|
|
253
271
|
remote_access: define_bridge(`${prefix}_remote`, remote_access_method_names),
|
|
254
272
|
host_tables: Object.fromEntries(Object.entries(options.host_tables ?? {}).map(([name, table]) => [name, define_bridge(`${prefix}_${name}`, Object.keys(table.api))])),
|
package/dist/app/desktop.d.ts
CHANGED
|
@@ -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 ProtocolLike } from "../electron/file_protocol.ts";
|
|
9
10
|
import { type AppNotice } from "./protocol.ts";
|
|
10
11
|
type DesktopWindow = BrowserWindowLike & FocusableWindowLike & WindowLike & {
|
|
11
12
|
webContents: {
|
|
@@ -71,6 +72,7 @@ export interface ElectronLike {
|
|
|
71
72
|
}): unknown;
|
|
72
73
|
};
|
|
73
74
|
};
|
|
75
|
+
protocol?: ProtocolLike;
|
|
74
76
|
}
|
|
75
77
|
export interface SaveDialogOptionsLike {
|
|
76
78
|
defaultPath: string;
|
|
@@ -104,6 +106,7 @@ export interface DesktopOptions {
|
|
|
104
106
|
width: number;
|
|
105
107
|
height: number;
|
|
106
108
|
};
|
|
109
|
+
external_schemes?: string[];
|
|
107
110
|
argv?: string[];
|
|
108
111
|
env?: NodeJS.ProcessEnv;
|
|
109
112
|
cwd?: string;
|
package/dist/app/desktop.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// work to this computer's daemon or to a server chosen under Settings → Connections. The app hands in Electron, so this
|
|
3
3
|
// module builds without it.
|
|
4
4
|
// ── Imports ──────────────────────────────────────────────────────────────────
|
|
5
|
-
import { unwatchFile, watchFile } from "node:fs";
|
|
5
|
+
import { existsSync, readFileSync, 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";
|
|
@@ -23,7 +23,12 @@ import { call_daemon, daemon_log_path, daemon_socket_path, start_daemon } from "
|
|
|
23
23
|
import { peer_listening_method_names, sync_device_method_names } from "../sync_protocol.js";
|
|
24
24
|
import { route_of_link } from "./links.js";
|
|
25
25
|
import { remote_access_method_names } from "../remote_access_protocol.js";
|
|
26
|
-
import {
|
|
26
|
+
import { file_response, register_file_scheme } from "../electron/file_protocol.js";
|
|
27
|
+
import { create_main_fetch } from "../electron/fetch.js";
|
|
28
|
+
import { no_server_text, server_headers, server_url } from "./server_fetch.js";
|
|
29
|
+
import { folder_file_store } from "../node_file_store.js";
|
|
30
|
+
import { read_plugin_file } from "../plugin_folder.js";
|
|
31
|
+
import { file_scheme_of, host_ability_method_names, notice_event, read_desktop_settings, notice_is_on, notice_withdrawn_event } from "./protocol.js";
|
|
27
32
|
// The Save dialog's options for a file name: Downloads with that name, offering files of its kind.
|
|
28
33
|
export function save_dialog_options(file_name, downloads) {
|
|
29
34
|
const extension = extname(file_name).slice(1);
|
|
@@ -38,6 +43,8 @@ export function run_desktop(app, electron, options) {
|
|
|
38
43
|
const start = options.start_daemon ?? start_daemon;
|
|
39
44
|
const call_socket = options.call_daemon ?? call_daemon;
|
|
40
45
|
const write_autostart = options.set_autostart ?? set_autostart;
|
|
46
|
+
// A portal runs no daemon and keeps no data: it works on a server chosen under Connections.
|
|
47
|
+
const portal = app.desktop === "portal";
|
|
41
48
|
// ── Profile ──────────────────────────────────────────────────────────
|
|
42
49
|
// Dev runs set this so they never touch the installed app's data.
|
|
43
50
|
const own_profile = env[`${prefix}_USER_DATA`];
|
|
@@ -58,6 +65,8 @@ export function run_desktop(app, electron, options) {
|
|
|
58
65
|
// Opening the app replaces a daemon another build left running, such as one from before an upgrade. Only opening does:
|
|
59
66
|
// two windows of different builds that both replaced on reconnecting would stop each other's daemon in turn.
|
|
60
67
|
function ensure_daemon(replace_other_build = false) {
|
|
68
|
+
if (portal)
|
|
69
|
+
return Promise.resolve("portal");
|
|
61
70
|
// Only the user's own daemon reads what this computer's configuration declares, unless a run names a file itself.
|
|
62
71
|
const declared = is_own_profile ? {} : { [`${prefix}_DECLARED_FILE`]: env[`${prefix}_DECLARED_FILE`] ?? "" };
|
|
63
72
|
const own_env = options.daemon_env?.({ path: profile, is_own_profile }) ?? {};
|
|
@@ -80,7 +89,7 @@ export function run_desktop(app, electron, options) {
|
|
|
80
89
|
trust_certificates();
|
|
81
90
|
watchFile(certificates_file, { interval: 2000 }, trust_certificates);
|
|
82
91
|
// This computer's daemon, and servers each signed in once with a token of this device's own.
|
|
83
|
-
const connections = create_connections({ storage: connection_file_storage(join(profile, "connections.json")), offers_local:
|
|
92
|
+
const connections = create_connections({ storage: connection_file_storage(join(profile, "connections.json")), offers_local: !portal, device_name: `${app.name} on ${hostname()}` });
|
|
84
93
|
const link = create_daemon_link({ connections, socket_path });
|
|
85
94
|
const windows = () => BrowserWindow.getAllWindows();
|
|
86
95
|
// A daemon elsewhere tells of its notices as events; this computer shows them by its own switches, as its own
|
|
@@ -101,9 +110,11 @@ export function run_desktop(app, electron, options) {
|
|
|
101
110
|
const router = create_daemon_router({
|
|
102
111
|
connections,
|
|
103
112
|
link,
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
113
|
+
...(portal ? {} : {
|
|
114
|
+
call_local: (path, args, headers) => call_socket(socket_path, path, args, headers),
|
|
115
|
+
restart_local: () => ensure_daemon(),
|
|
116
|
+
}),
|
|
117
|
+
local_tables: portal ? [] : [...default_local_tables, "peer_listening", "remote", ...own_tables],
|
|
107
118
|
is_read_only: app.is_read_only,
|
|
108
119
|
on_change: (change) => {
|
|
109
120
|
app.bridges.events.emit(windows(), "changed", change);
|
|
@@ -124,16 +135,64 @@ export function run_desktop(app, electron, options) {
|
|
|
124
135
|
window.webContents.reload();
|
|
125
136
|
},
|
|
126
137
|
});
|
|
127
|
-
const { call, forwarded } = router;
|
|
138
|
+
const { call, forwarded, is_here } = router;
|
|
139
|
+
// A file a server serves by GET under its /api/, such as a synced file or a plugin's web side, fetched with this
|
|
140
|
+
// device's token; 404 while the window works on this computer.
|
|
141
|
+
async function fetch_from_server(path) {
|
|
142
|
+
const daemon = connections.current();
|
|
143
|
+
if (daemon?.kind !== "remote")
|
|
144
|
+
return new Response(null, { status: 404 });
|
|
145
|
+
const escaped = path.split("/").map((part) => encodeURIComponent(part)).join("/");
|
|
146
|
+
return fetch(`${daemon.address.replace(/\/+$/, "")}/api/${escaped}`, { headers: { authorization: `Bearer ${daemon.token}` } }).catch(() => new Response(null, { status: 502 }));
|
|
147
|
+
}
|
|
148
|
+
// The app's synced files come from this computer's folder, or from the server the window works on.
|
|
149
|
+
const synced_files = app.synced_files ? folder_file_store(join(profile, app.synced_files.folder)) : null;
|
|
150
|
+
function file_answer(request) {
|
|
151
|
+
return is_here() ? file_response(synced_files, request.url) : fetch_from_server(`files/${new URL(request.url).hostname}`);
|
|
152
|
+
}
|
|
153
|
+
// The plugins' web files of the daemon the window works on: this computer's plugins folder, or the server's.
|
|
154
|
+
async function read_plugin_web_file(path) {
|
|
155
|
+
if (is_here())
|
|
156
|
+
return read_plugin_file(join(profile, "plugins"), path);
|
|
157
|
+
const response = await fetch_from_server(`plugins/${path}`);
|
|
158
|
+
return response.ok ? response.text() : "";
|
|
159
|
+
}
|
|
160
|
+
// Named before the app is ready, as Electron asks, so the page may load the files from it.
|
|
161
|
+
if (synced_files && electron.protocol)
|
|
162
|
+
register_file_scheme(electron.protocol, file_scheme_of(app.id));
|
|
128
163
|
// This computer's own settings, always from its own daemon.
|
|
129
|
-
|
|
130
|
-
|
|
164
|
+
// A portal keeps them in the profile itself, as it runs no daemon to keep them.
|
|
165
|
+
const portal_settings_file = join(profile, "desktop.json");
|
|
166
|
+
async function get_desktop_settings() {
|
|
167
|
+
if (!portal)
|
|
168
|
+
return call("daemon/get_desktop_settings");
|
|
169
|
+
return read_desktop_settings(existsSync(portal_settings_file) ? JSON.parse(readFileSync(portal_settings_file, "utf8")) : null, app.desktop_settings);
|
|
170
|
+
}
|
|
171
|
+
async function set_desktop_setting(key, value) {
|
|
172
|
+
if (!portal)
|
|
173
|
+
return void (await call("daemon/set_desktop_setting", [key, value]));
|
|
174
|
+
await writeFile(portal_settings_file, JSON.stringify(read_desktop_settings({ ...(await get_desktop_settings()), [key]: value }, app.desktop_settings), null, 2));
|
|
175
|
+
}
|
|
176
|
+
// The page's request to its server's routes, sent to the server the window works on with this device's token.
|
|
177
|
+
const main_fetch = create_main_fetch({
|
|
178
|
+
get hosts() {
|
|
179
|
+
const daemon = connections.current();
|
|
180
|
+
return daemon?.kind === "remote" ? [new URL(daemon.address).host] : [];
|
|
181
|
+
},
|
|
182
|
+
allow_http: true,
|
|
183
|
+
});
|
|
184
|
+
function http_fetch(request) {
|
|
185
|
+
const daemon = connections.current();
|
|
186
|
+
if (daemon?.kind !== "remote")
|
|
187
|
+
throw new Error(no_server_text);
|
|
188
|
+
return main_fetch({ ...request, url: server_url(daemon.address, request.url), headers: server_headers(request.headers, daemon.token) });
|
|
131
189
|
}
|
|
132
190
|
// The tray as its setting says, and, for the user's own profile only, the login entry; a dev run never writes it.
|
|
133
191
|
async function apply_window_settings() {
|
|
134
192
|
const settings = await get_desktop_settings();
|
|
135
193
|
tray?.set_shown(settings.show_tray_icon);
|
|
136
|
-
|
|
194
|
+
// A portal has no daemon to start at login.
|
|
195
|
+
if (!is_own_profile || portal)
|
|
137
196
|
return;
|
|
138
197
|
write_autostart({ id: `${app.id}-daemon`, name: `${app.name} in the background`, comment: `Sync and backups for ${app.name}`, icon: icon_path, command: own_command(["--daemon"]) }, settings.start_at_login && settings.keep_running_in_background);
|
|
139
198
|
}
|
|
@@ -144,6 +203,8 @@ export function run_desktop(app, electron, options) {
|
|
|
144
203
|
};
|
|
145
204
|
// The daemon's services keep quiet, such as about notifications, while a window is in front.
|
|
146
205
|
function tell_in_front() {
|
|
206
|
+
if (portal)
|
|
207
|
+
return;
|
|
147
208
|
const in_front = windows().some((each) => each.isFocused() && each.isVisible());
|
|
148
209
|
void call("daemon/set_window_in_front", [in_front]).catch(() => undefined);
|
|
149
210
|
}
|
|
@@ -159,6 +220,7 @@ export function run_desktop(app, electron, options) {
|
|
|
159
220
|
min_size: options.min_size ?? { width: 360, height: 480 },
|
|
160
221
|
native_theme: electron.nativeTheme,
|
|
161
222
|
shell: electron.shell,
|
|
223
|
+
...(options.external_schemes ? { external_schemes: options.external_schemes } : {}),
|
|
162
224
|
screen: electron.screen,
|
|
163
225
|
state_file: join(profile, "window.json"),
|
|
164
226
|
});
|
|
@@ -185,7 +247,8 @@ export function run_desktop(app, electron, options) {
|
|
|
185
247
|
// Stops the daemon as well, so nothing runs until the app is opened again.
|
|
186
248
|
async function quit_completely() {
|
|
187
249
|
router.quitting();
|
|
188
|
-
|
|
250
|
+
if (!portal)
|
|
251
|
+
await call("daemon/stop_daemon").catch(() => undefined);
|
|
189
252
|
electron.app.quit();
|
|
190
253
|
}
|
|
191
254
|
// ── Tray ───────────────────────────────────────────────────────────
|
|
@@ -246,12 +309,13 @@ export function run_desktop(app, electron, options) {
|
|
|
246
309
|
if (app.remote_access)
|
|
247
310
|
bridges.remote_access.handle(ipcMain, forwarded(remote_access_method_names, "remote"), handle_options);
|
|
248
311
|
bridges.host.handle(ipcMain, forwarded(host_ability_method_names, "host"), handle_options);
|
|
312
|
+
bridges.fetch.handle(ipcMain, { http_fetch }, handle_options);
|
|
249
313
|
for (const [name, bridge] of Object.entries(bridges.host_tables))
|
|
250
314
|
bridge.handle(ipcMain, forwarded(Object.keys(app.host_tables[name].api), name), handle_options);
|
|
251
315
|
const desktop = {
|
|
252
316
|
get_desktop_settings,
|
|
253
317
|
set_desktop_setting: async (key, value) => {
|
|
254
|
-
await
|
|
318
|
+
await set_desktop_setting(String(key), value);
|
|
255
319
|
await apply_window_settings();
|
|
256
320
|
},
|
|
257
321
|
quit_completely,
|
|
@@ -268,6 +332,7 @@ export function run_desktop(app, electron, options) {
|
|
|
268
332
|
const picked = await dialog.showOpenDialog({ properties: ["openDirectory"], ...(current ? { defaultPath: current } : {}) });
|
|
269
333
|
return picked.canceled ? null : (picked.filePaths[0] ?? null);
|
|
270
334
|
},
|
|
335
|
+
read_plugin_file: read_plugin_web_file,
|
|
271
336
|
show_data_path: async (which) => {
|
|
272
337
|
if (which === "database")
|
|
273
338
|
electron.shell.showItemInFolder?.(database_path);
|
|
@@ -288,6 +353,8 @@ export function run_desktop(app, electron, options) {
|
|
|
288
353
|
electron.app.exit(1);
|
|
289
354
|
return;
|
|
290
355
|
}
|
|
356
|
+
if (synced_files && electron.protocol)
|
|
357
|
+
electron.protocol.handle(file_scheme_of(app.id), file_answer);
|
|
291
358
|
register_bridges();
|
|
292
359
|
router.start();
|
|
293
360
|
await apply_window_settings().catch(() => undefined);
|
package/dist/app/preload.js
CHANGED
|
@@ -11,6 +11,7 @@ export function run_preload(app, { contextBridge, ipcRenderer }) {
|
|
|
11
11
|
if (app.remote_access)
|
|
12
12
|
bridges.remote_access.expose(contextBridge, ipcRenderer, { envelopes: true });
|
|
13
13
|
bridges.host.expose(contextBridge, ipcRenderer, { envelopes: true });
|
|
14
|
+
bridges.fetch.expose(contextBridge, ipcRenderer, { envelopes: true });
|
|
14
15
|
for (const bridge of Object.values(bridges.host_tables))
|
|
15
16
|
bridge.expose(contextBridge, ipcRenderer, { envelopes: true });
|
|
16
17
|
bridges.events.expose(contextBridge, ipcRenderer);
|
package/dist/app/protocol.d.ts
CHANGED
|
@@ -31,12 +31,15 @@ export interface DesktopMethods {
|
|
|
31
31
|
get_data_paths: () => DataPaths;
|
|
32
32
|
show_data_path: (which: keyof DataPaths) => void;
|
|
33
33
|
pick_folder: (current: string) => string | null;
|
|
34
|
+
read_plugin_file: (path: string) => string;
|
|
34
35
|
}
|
|
35
36
|
export interface DataPaths {
|
|
36
37
|
database: string;
|
|
37
38
|
backups: string;
|
|
38
39
|
}
|
|
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"];
|
|
40
|
+
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", "read_plugin_file"];
|
|
41
|
+
export declare function file_scheme_of(app_id: string): string;
|
|
42
|
+
export declare const desktop_plugin_base = "x-app-plugins://local/";
|
|
40
43
|
export interface DaemonMethods {
|
|
41
44
|
get_desktop_settings: () => DesktopSettings;
|
|
42
45
|
set_desktop_setting: (key: keyof DesktopSettings, value: boolean) => void;
|
|
@@ -88,6 +91,10 @@ export interface PageApi<Methods extends Record<keyof Methods, (...args: never[]
|
|
|
88
91
|
};
|
|
89
92
|
reread_abilities?: () => Promise<Pick<PageApi, "admin" | "tables">>;
|
|
90
93
|
server_theme?: ServerTheme;
|
|
94
|
+
fetch?: typeof fetch;
|
|
95
|
+
file_src?: (name: string) => Promise<string>;
|
|
96
|
+
plugin_base?: string;
|
|
97
|
+
read_plugin_file?: (path: string) => Promise<string>;
|
|
91
98
|
on_change: (listener: (change: DataChange | null) => void) => () => void;
|
|
92
99
|
on_event?: (event: string, listener: (data: unknown) => void) => () => void;
|
|
93
100
|
}
|
package/dist/app/protocol.js
CHANGED
|
@@ -12,7 +12,13 @@ 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", "pick_folder"];
|
|
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", "read_plugin_file"];
|
|
16
|
+
// The desktop page's scheme for the app's synced files, as <scheme>://<name>, such as x-notes-file://<name>.
|
|
17
|
+
export function file_scheme_of(app_id) {
|
|
18
|
+
return `${app_id}-file`;
|
|
19
|
+
}
|
|
20
|
+
// Where the desktop page pretends the plugins' web files are, so their addresses resolve against each other.
|
|
21
|
+
export const desktop_plugin_base = "x-app-plugins://local/";
|
|
16
22
|
export const host_ability_method_names = ["get_host_abilities"];
|
|
17
23
|
// The named event a host sends its pages with each notice.
|
|
18
24
|
export const notice_event = "notice";
|
package/dist/app/server.d.ts
CHANGED
|
@@ -2,10 +2,12 @@ import { DatabaseSync } from "node:sqlite";
|
|
|
2
2
|
import { type FastifyInstance } from "fastify";
|
|
3
3
|
import { type MethodSpec } from "../api_spec.ts";
|
|
4
4
|
import { type BackupMethods } from "../backups.ts";
|
|
5
|
+
import { type ProxySignIn } from "../server/account_sign_in.ts";
|
|
5
6
|
import { OidcClient } from "../server/oidc.ts";
|
|
6
7
|
import { AccountStore } from "../server/account_store.ts";
|
|
7
8
|
import { type Channel } from "../server/notify/channels.ts";
|
|
8
9
|
import { EventStream } from "../server/events.ts";
|
|
10
|
+
import type { SyncFileStore } from "../sync_files.ts";
|
|
9
11
|
import { type SqlDatabase } from "../sql.ts";
|
|
10
12
|
import { type ServerTheme } from "../web/theme.ts";
|
|
11
13
|
import { type SyncPeer } from "../sync_peer.ts";
|
|
@@ -48,7 +50,9 @@ export interface ServerOptions {
|
|
|
48
50
|
remembered_seconds?: number | null;
|
|
49
51
|
theme?: ServerTheme;
|
|
50
52
|
plugins_folder?: string | null;
|
|
53
|
+
files?: SyncFileStore | null;
|
|
51
54
|
second_factor_from?: string | null;
|
|
55
|
+
proxy?: ProxySignIn | null;
|
|
52
56
|
}
|
|
53
57
|
export declare const backup_tools: Record<"list_backups" | "create_backup" | "get_backup_schedule", MethodSpec>;
|
|
54
58
|
export declare const user_only_backup_calls: ReadonlySet<string>;
|
package/dist/app/server.js
CHANGED
|
@@ -26,6 +26,8 @@ import { register_security_headers } from "../server/security_headers.js";
|
|
|
26
26
|
import { EventStream } from "../server/events.js";
|
|
27
27
|
import { register_mcp_route } from "../server/mcp.js";
|
|
28
28
|
import { register_plugin_files } from "../server/plugin_files.js";
|
|
29
|
+
import { register_synced_files } from "../server/synced_file_route.js";
|
|
30
|
+
import { folder_file_store } from "../node_file_store.js";
|
|
29
31
|
import { load_accounts } from "../server/passwords.js";
|
|
30
32
|
import { BAD_JSON, register_error_replies, register_lenient_json_body, send_text } from "../server/replies.js";
|
|
31
33
|
import { sqlite_backups } from "../server/sqlite_backups.js";
|
|
@@ -223,7 +225,8 @@ export async function build_server(app, options) {
|
|
|
223
225
|
// A phone that keeps no data calls from a page of its own with a token, the sign-in included; the event stream
|
|
224
226
|
// writes its own head, so it carries the open origin itself.
|
|
225
227
|
if (app.phone === "portal") {
|
|
226
|
-
|
|
228
|
+
// An app built on its REST routes takes PUT and DELETE from its portals too.
|
|
229
|
+
await register_open_cors(server, { allowed_headers: sync_peer_headers, methods: ["GET", "POST", "PUT", "DELETE"] });
|
|
227
230
|
server.addHook("onRequest", async (request, reply) => {
|
|
228
231
|
if (request.url.split("?")[0] === "/api/events")
|
|
229
232
|
reply.raw.setHeader("access-control-allow-origin", "*");
|
|
@@ -243,6 +246,7 @@ export async function build_server(app, options) {
|
|
|
243
246
|
open_prefixes: options.routes?.open_prefixes ?? [],
|
|
244
247
|
guarded_paths: options.routes?.guarded_paths ?? [],
|
|
245
248
|
oidc: options.oidc ?? null,
|
|
249
|
+
proxy: options.proxy ?? null,
|
|
246
250
|
...(options.session_seconds !== undefined ? { session_seconds: options.session_seconds } : {}),
|
|
247
251
|
...(options.remembered_seconds !== undefined ? { remembered_seconds: options.remembered_seconds } : {}),
|
|
248
252
|
...(options.second_factor_from ? { second_factor_from: options.second_factor_from } : {}),
|
|
@@ -272,6 +276,8 @@ export async function build_server(app, options) {
|
|
|
272
276
|
api.get("/theme", async () => options.theme ?? read_server_theme(null));
|
|
273
277
|
register_app_calls(api, app, database, changes);
|
|
274
278
|
register_host_tables(api, app, reach, services, changes);
|
|
279
|
+
if (options.files)
|
|
280
|
+
register_synced_files(api, options.files);
|
|
275
281
|
// A route table's calls are documented as the routes they run, the rest as the calls posted under /api.
|
|
276
282
|
api.get("/openapi.json", async () => {
|
|
277
283
|
const called = Object.fromEntries(Object.entries(documented).filter(([method]) => !route_calls.has(method)));
|
|
@@ -367,8 +373,9 @@ export async function run_server(app, options) {
|
|
|
367
373
|
app_name: app.name,
|
|
368
374
|
...(app.roles ? { roles: app.roles } : {}),
|
|
369
375
|
...(app.token_prefix ? { token_prefix: app.token_prefix } : {}),
|
|
376
|
+
...(app.check_access ? { check_access: app.check_access } : {}),
|
|
370
377
|
...(config.token_days !== undefined ? { longest_token_days: config.token_days } : {}),
|
|
371
|
-
declared: load_accounts(`${prefix}_PASSWORD_HASH_FILE`, server_config.values.password_hash_file),
|
|
378
|
+
declared: load_accounts(`${prefix}_PASSWORD_HASH_FILE`, server_config.values.password_hash_file, config.admin_name?.toLowerCase()),
|
|
372
379
|
declared_tokens: declared_tokens.filter((token) => token.role !== null),
|
|
373
380
|
});
|
|
374
381
|
const oidc_settings = oidc_from_environment(prefix, options.env ?? process.env);
|
|
@@ -380,11 +387,14 @@ export async function run_server(app, options) {
|
|
|
380
387
|
const channels = read_channels(config.notify_channels, { name: "notify_channels" });
|
|
381
388
|
// The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be; an app
|
|
382
389
|
// whose server is the only copy keeps none.
|
|
390
|
+
// The app's synced files, such as covers, kept beside the data.
|
|
391
|
+
const files = app.synced_files ? folder_file_store(join(dirname(database_path), app.synced_files.folder)) : null;
|
|
383
392
|
const sync = app.sync === false ? null : create_sync_peer({
|
|
384
393
|
app: app.id,
|
|
385
394
|
engine: app.sync_engine,
|
|
386
395
|
database: opened.database,
|
|
387
396
|
storage: file_sync_storage({ file: join(dirname(database_path), "sync-peers.json"), back_up_before_replace: opened.back_up }),
|
|
397
|
+
...(files ? { files: { store: files, referenced: app.synced_files.referenced } } : {}),
|
|
388
398
|
device_name: `${app.name} server on ${hostname()}`,
|
|
389
399
|
addresses: () => (config.sync_address ? [config.sync_address] : []),
|
|
390
400
|
on_remote_change: () => {
|
|
@@ -400,8 +410,10 @@ export async function run_server(app, options) {
|
|
|
400
410
|
...(config.session_seconds !== undefined ? { session_seconds: config.session_seconds } : {}),
|
|
401
411
|
...(config.remembered_seconds !== undefined ? { remembered_seconds: config.remembered_seconds } : {}),
|
|
402
412
|
...(config.second_factor_from ? { second_factor_from: config.second_factor_from } : {}),
|
|
413
|
+
...(config.proxy_user_header ? { proxy: { header: config.proxy_user_header.toLowerCase(), trusted: new Set(config.trusted_proxies ?? ["127.0.0.1", "::1"]) } } : {}),
|
|
403
414
|
theme: read_server_theme(config.theme),
|
|
404
415
|
plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
|
|
416
|
+
files,
|
|
405
417
|
});
|
|
406
418
|
const stop_watching = watch_outside_changes(opened.database, () => changes.announce_change());
|
|
407
419
|
const address = await server.listen({ host: server_config.host, port: server_config.port });
|
|
@@ -421,6 +433,7 @@ export async function run_server(app, options) {
|
|
|
421
433
|
accounts.set_declared_tokens(declared_tokens.filter((token) => token.role !== null));
|
|
422
434
|
},
|
|
423
435
|
plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
|
|
436
|
+
files,
|
|
424
437
|
declared_file: declared_file_of(app, options.env ?? process.env),
|
|
425
438
|
announce: (client_id) => changes.announce_change(client_id),
|
|
426
439
|
wrote: () => {
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const no_server_text = "No server is chosen yet. Choose one under Settings \u2192 Connections.";
|
|
2
|
+
export declare function server_url(address: string, requested: string): string;
|
|
3
|
+
export declare function server_headers(headers: Iterable<[string, string]>, token: string): [string, string][];
|
|
4
|
+
export declare function server_fetch(server: () => {
|
|
5
|
+
address: string;
|
|
6
|
+
token: string;
|
|
7
|
+
} | null, send?: typeof fetch): typeof fetch;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// A page's request to its own server's routes, such as "/api/runs?limit=5", sent from a portal on another device: the
|
|
2
|
+
// path under the server's address chosen under Connections, with this device's token in place of the page's own
|
|
3
|
+
// credentials. The desktop's main process and the phone's portal both send it so.
|
|
4
|
+
// ── Requests ─────────────────────────────────────────────────────────────────
|
|
5
|
+
export const no_server_text = "No server is chosen yet. Choose one under Settings → Connections.";
|
|
6
|
+
// The server's URL for a request the page made to its own origin; only the API is reached.
|
|
7
|
+
export function server_url(address, requested) {
|
|
8
|
+
const url = new URL(requested, "http://page.invalid");
|
|
9
|
+
// A relative path resolves against the page's own address, such as a desktop page's file:// one, so the route is
|
|
10
|
+
// read from its /api/ on.
|
|
11
|
+
const at = url.pathname.indexOf("/api/");
|
|
12
|
+
if (at === -1)
|
|
13
|
+
throw new Error(`${url.pathname} is not one of the server's routes.`);
|
|
14
|
+
return `${address.replace(/\/+$/, "")}${url.pathname.slice(at)}${url.search}`;
|
|
15
|
+
}
|
|
16
|
+
// The page's headers with this device's token in place of any credentials or origin the page's own request carried.
|
|
17
|
+
export function server_headers(headers, token) {
|
|
18
|
+
const dropped = new Set(["authorization", "cookie", "origin", "referer", "host"]);
|
|
19
|
+
const kept = [...headers].filter(([name]) => !dropped.has(name.toLowerCase()));
|
|
20
|
+
return [...kept, ["authorization", `Bearer ${token}`]];
|
|
21
|
+
}
|
|
22
|
+
// A fetch of the page's that goes to the server the connection names, or refuses while none is chosen.
|
|
23
|
+
export function server_fetch(server, send = fetch) {
|
|
24
|
+
return async (input, init) => {
|
|
25
|
+
const chosen = server();
|
|
26
|
+
if (!chosen)
|
|
27
|
+
throw new Error(no_server_text);
|
|
28
|
+
const request = new Request(new URL(String(input instanceof Request ? input.url : input), "http://page.invalid"), init);
|
|
29
|
+
const path = new URL(request.url);
|
|
30
|
+
return send(server_url(chosen.address, `${path.pathname}${path.search}`), {
|
|
31
|
+
method: request.method,
|
|
32
|
+
headers: server_headers(request.headers.entries(), chosen.token),
|
|
33
|
+
body: request.method === "GET" || request.method === "HEAD" ? null : await request.arrayBuffer(),
|
|
34
|
+
...(init?.signal ? { signal: init.signal } : {}),
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
}
|
package/dist/app/services.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { DatabaseSync } from "node:sqlite";
|
|
|
2
2
|
import type { FastifyInstance } from "fastify";
|
|
3
3
|
import type { Need } from "../server/account_sign_in.ts";
|
|
4
4
|
import type { DeclaredToken } from "../server/declared_tokens.ts";
|
|
5
|
+
import type { SyncFileStore } from "../sync_files.ts";
|
|
5
6
|
import type { DataChange } from "../sync_protocol.ts";
|
|
6
7
|
import type { App } from "./define.ts";
|
|
7
8
|
import type { AppNotice } from "./protocol.ts";
|
|
@@ -14,6 +15,7 @@ export interface HostContext {
|
|
|
14
15
|
config_file: string | null;
|
|
15
16
|
declared_tokens: () => readonly DeclaredToken[];
|
|
16
17
|
reread_declared_tokens: (config: Readonly<Record<string, unknown>>) => void;
|
|
18
|
+
files: SyncFileStore | null;
|
|
17
19
|
plugins_folder: string | null;
|
|
18
20
|
declared_file: string;
|
|
19
21
|
announce: (client_id?: string) => void;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type BackupFolderPlugin } from "../../phone_backups.ts";
|
|
2
|
+
import type { SyncFileStore } from "../../sync_files.ts";
|
|
2
3
|
import { type FileStore } from "../../web/sqlite_wasm.ts";
|
|
3
4
|
import { type SqlDatabase } from "../../sql.ts";
|
|
4
5
|
import type { App } from "../define.ts";
|
|
@@ -9,6 +10,8 @@ export interface PhoneLifecycle {
|
|
|
9
10
|
}
|
|
10
11
|
export interface PhoneContext {
|
|
11
12
|
database: () => SqlDatabase;
|
|
13
|
+
files: SyncFileStore | null;
|
|
14
|
+
wrote: () => void;
|
|
12
15
|
}
|
|
13
16
|
export interface PhoneServices {
|
|
14
17
|
changed?: () => void;
|
|
@@ -17,6 +20,7 @@ export type StartPhoneServices = (context: PhoneContext) => PhoneServices | Prom
|
|
|
17
20
|
export interface PhoneOptions {
|
|
18
21
|
lifecycle?: PhoneLifecycle;
|
|
19
22
|
files?: FileStore;
|
|
23
|
+
synced_files?: SyncFileStore;
|
|
20
24
|
folder?: BackupFolderPlugin;
|
|
21
25
|
services?: StartPhoneServices;
|
|
22
26
|
storage?: Pick<Storage, "getItem" | "removeItem">;
|
package/dist/app/web/android.js
CHANGED
|
@@ -61,7 +61,9 @@ export async function android_api(app, options = {}) {
|
|
|
61
61
|
tidy_database(database.connection);
|
|
62
62
|
await database.save_now();
|
|
63
63
|
const keeper = keep_backing_up(kept, () => app.read_backup_schedule(database.connection));
|
|
64
|
-
|
|
64
|
+
// The app's synced files, such as covers, apart from the database, which is saved whole after every change.
|
|
65
|
+
const synced = app.synced_files ? (options.synced_files ?? indexed_db_files(`${app.id}-${app.synced_files.folder}`)) : null;
|
|
66
|
+
let services = {};
|
|
65
67
|
const listeners = new Set();
|
|
66
68
|
const announce = () => {
|
|
67
69
|
let change = null;
|
|
@@ -75,12 +77,32 @@ export async function android_api(app, options = {}) {
|
|
|
75
77
|
listener(change);
|
|
76
78
|
services.changed?.();
|
|
77
79
|
};
|
|
80
|
+
if (options.services)
|
|
81
|
+
services = await options.services({ database: () => database.connection, files: synced, wrote: () => {
|
|
82
|
+
app.record_writes(database.connection);
|
|
83
|
+
announce();
|
|
84
|
+
} });
|
|
78
85
|
// The paired devices and keys stay in the app's private storage; before another copy replaces this one the data is
|
|
79
86
|
// backed up to the folder, or beside the database while there is none.
|
|
80
87
|
const before_sync_file = app.database_file.replace(/\.db$/, "") + "-before-sync.db";
|
|
81
88
|
const back_up_before_replace = async () => ((await has_folder()) ? void (await kept.create()) : files.write(before_sync_file, database.export_bytes()));
|
|
82
89
|
const storage = local_sync_storage({ key: `${app.id}-sync-peers`, back_up_before_replace });
|
|
83
|
-
const sync = create_sync_peer({
|
|
90
|
+
const sync = create_sync_peer({
|
|
91
|
+
app: app.id, engine: app.sync_engine, database: () => database.connection, storage, device_name: `${app.name} on Android`, on_remote_change: announce,
|
|
92
|
+
...(synced ? { files: { store: synced, referenced: app.synced_files.referenced } } : {}),
|
|
93
|
+
});
|
|
94
|
+
// Each kept file is read from IndexedDB once and shown from a blob address after; one not here yet is asked for
|
|
95
|
+
// again later, once sync or the app's services have brought it.
|
|
96
|
+
const file_sources = new Map();
|
|
97
|
+
const file_src = (name) => {
|
|
98
|
+
let source = file_sources.get(name);
|
|
99
|
+
if (!source) {
|
|
100
|
+
source = synced.read(name).then((bytes) => (bytes ? URL.createObjectURL(new Blob([bytes])) : ""));
|
|
101
|
+
file_sources.set(name, source);
|
|
102
|
+
void source.then((url) => url === "" && file_sources.delete(name));
|
|
103
|
+
}
|
|
104
|
+
return source;
|
|
105
|
+
};
|
|
84
106
|
// A phone may close the app at any moment once it is in the background, so the database is saved straight away.
|
|
85
107
|
lifecycle.addListener("pause", () => void database.save_now());
|
|
86
108
|
lifecycle.addListener("resume", () => {
|
|
@@ -109,6 +131,7 @@ export async function android_api(app, options = {}) {
|
|
|
109
131
|
return name;
|
|
110
132
|
},
|
|
111
133
|
},
|
|
134
|
+
...(synced ? { file_src } : {}),
|
|
112
135
|
on_change: (listener) => {
|
|
113
136
|
listeners.add(listener);
|
|
114
137
|
return () => listeners.delete(listener);
|
package/dist/app/web/hosts.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { App } from "../define.ts";
|
|
|
2
2
|
import { type HostAbilities, type PageApi } from "../protocol.ts";
|
|
3
3
|
export declare function read_host_abilities(read: () => Promise<unknown>): Promise<HostAbilities>;
|
|
4
4
|
export declare function host_tables_of(app: Pick<App, "bridges">, abilities: HostAbilities, client_of: (name: string) => unknown): NonNullable<PageApi["tables"]>;
|
|
5
|
-
export declare function web_api(app: Pick<App, "bridges"> & Partial<Pick<App, "sync">>): PageApi;
|
|
5
|
+
export declare function web_api(app: Pick<App, "bridges"> & Partial<Pick<App, "sync" | "synced_files">>): PageApi;
|
|
6
6
|
export declare function is_desktop(app: Pick<App, "bridges">): boolean;
|
|
7
|
-
export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "local_mcp" | "remote_access">>): Promise<PageApi>;
|
|
7
|
+
export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "id" | "local_mcp" | "remote_access" | "synced_files">>): Promise<PageApi>;
|
|
8
8
|
export declare function is_android(): boolean;
|
package/dist/app/web/hosts.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// Where the page runs and how it reaches the data there: a browser posts every call to the server it was loaded from
|
|
2
2
|
// and follows its event stream; the desktop app's preload has put the main process's calls on the window, which go to
|
|
3
3
|
// this computer's daemon or to the server Settings → Connections chose.
|
|
4
|
+
import { create_page_fetch } from "../../electron/fetch.js";
|
|
4
5
|
import { LOCAL_CONNECTION_ID } from "../../connection_protocol.js";
|
|
5
6
|
import { LoginNeeded } from "../../web/states.js";
|
|
6
|
-
import { data_change_of } from "../protocol.js";
|
|
7
|
+
import { data_change_of, desktop_plugin_base, file_scheme_of } from "../protocol.js";
|
|
7
8
|
// ── Host tables ──────────────────────────────────────────────────────────────
|
|
8
9
|
// What the host lets the page reach, or nothing while it cannot be asked, such as before signing in.
|
|
9
10
|
export async function read_host_abilities(read) {
|
|
@@ -105,6 +106,10 @@ export function web_api(app) {
|
|
|
105
106
|
// The server's own sync peer and backups, which only an admin reaches; an app whose server is the only copy has no peer.
|
|
106
107
|
device: app.sync === false ? null : bridges.device.web_rpc((method, args) => post_call(device_path, method, args)),
|
|
107
108
|
backups: bridges.backups.web_rpc((method, args) => post_call(backups_path, method, args)),
|
|
109
|
+
...(app.synced_files ? { file_src: async (name) => `api/files/${encodeURIComponent(name)}` } : {}),
|
|
110
|
+
plugin_base: "api/plugins/",
|
|
111
|
+
// The server's own routes, with the browser's sign-in.
|
|
112
|
+
fetch: (input, init) => fetch(input, init),
|
|
108
113
|
on_change: (listener) => {
|
|
109
114
|
listeners.add(listener);
|
|
110
115
|
return () => listeners.delete(listener);
|
|
@@ -133,6 +138,7 @@ export async function desktop_api(app) {
|
|
|
133
138
|
const is_here = (await connections.list_connections()).current === LOCAL_CONNECTION_ID;
|
|
134
139
|
const host = exposed[bridges.host.api_name];
|
|
135
140
|
const abilities = await read_host_abilities(async () => host?.get_host_abilities());
|
|
141
|
+
const desktop = exposed[bridges.desktop.api_name];
|
|
136
142
|
return {
|
|
137
143
|
host: "desktop",
|
|
138
144
|
admin: abilities.admin,
|
|
@@ -147,7 +153,12 @@ export async function desktop_api(app) {
|
|
|
147
153
|
backups: exposed[bridges.backups.api_name],
|
|
148
154
|
certificates: exposed[bridges.certificates.api_name],
|
|
149
155
|
connections,
|
|
150
|
-
desktop
|
|
156
|
+
desktop,
|
|
157
|
+
...(app.synced_files && app.id ? { file_src: async (name) => `${file_scheme_of(app.id)}://${name}` } : {}),
|
|
158
|
+
plugin_base: desktop_plugin_base,
|
|
159
|
+
read_plugin_file: (path) => desktop.read_plugin_file(path),
|
|
160
|
+
// The routes of the server the window works on, sent on by the main process with this device's token.
|
|
161
|
+
...(exposed[bridges.fetch.api_name] ? { fetch: create_page_fetch((request) => exposed[bridges.fetch.api_name].http_fetch(request)) } : {}),
|
|
151
162
|
on_change: (listener) => events.on("changed", listener),
|
|
152
163
|
on_event: (event, listener) => events.on("app_event", (sent) => sent.event === event && listener(sent.data)),
|
|
153
164
|
};
|
package/dist/app/web/portal.js
CHANGED
|
@@ -11,6 +11,7 @@ import { call_remote, follow_remote } from "../../web/remote_daemon.js";
|
|
|
11
11
|
import { route_of_link } from "../links.js";
|
|
12
12
|
import { data_change_of, notice_event, notice_is_on, notice_withdrawn_event } from "../protocol.js";
|
|
13
13
|
import { host_tables_of, read_host_abilities } from "./hosts.js";
|
|
14
|
+
import { server_fetch } from "../server_fetch.js";
|
|
14
15
|
// ── Switches ─────────────────────────────────────────────────────────────────
|
|
15
16
|
// The notice switches this phone keeps, each of the app's `notify_` desktop switches at its default where unset.
|
|
16
17
|
export function read_notice_switches(app, saved) {
|
|
@@ -100,6 +101,8 @@ export async function portal_api(app, options) {
|
|
|
100
101
|
return {
|
|
101
102
|
host: "android",
|
|
102
103
|
calls: bridges.calls.web_rpc(rpc("call")),
|
|
104
|
+
// The routes of the host this phone works on, with its token.
|
|
105
|
+
fetch: server_fetch(link.daemon, options.fetch ?? ((input, init) => fetch(input, init))),
|
|
103
106
|
device: null,
|
|
104
107
|
// The host's backups, which only an admin there reaches.
|
|
105
108
|
backups: abilities.admin ? bridges.backups.web_rpc(rpc("backups")) : null,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { IconGlyph } from "../../web/react/icons.tsx";
|
|
2
2
|
import type { AccountsClient, Me } from "../../web/accounts.ts";
|
|
3
|
+
import { type AccessEditor } from "../../web/react/accounts.tsx";
|
|
3
4
|
import { type SettingsCategory, type SettingsSection } from "../../web/react/layout.tsx";
|
|
4
5
|
import type { ShellSidePane, SidebarWidth } from "../../web/react/shell.tsx";
|
|
5
6
|
import type { LocalNotificationsLike } from "../../phone_notices.ts";
|
|
@@ -48,7 +49,10 @@ export interface AppPages {
|
|
|
48
49
|
phone_services?: () => Promise<StartPhoneServices>;
|
|
49
50
|
phone_notifications?: () => Promise<LocalNotificationsLike>;
|
|
50
51
|
remote_access_reach?: string;
|
|
52
|
+
exports_secrets?: boolean;
|
|
51
53
|
role_text?: Readonly<Record<string, string>>;
|
|
54
|
+
access_text?: (access: unknown) => string;
|
|
55
|
+
access_editor?: AccessEditor;
|
|
52
56
|
}
|
|
53
57
|
export interface SettingsViewer {
|
|
54
58
|
client: AccountsClient;
|
|
@@ -59,10 +59,11 @@ function NoticeSwitches({ app, switches }) {
|
|
|
59
59
|
} }) }, key))) }));
|
|
60
60
|
}
|
|
61
61
|
// Every setting but this device's own, as a file to take to another device or install, and read back.
|
|
62
|
-
function SettingsFile({ app_id }) {
|
|
62
|
+
function SettingsFile({ app_id, secrets }) {
|
|
63
63
|
const settings_calls = calls();
|
|
64
|
+
const [with_secrets, set_with_secrets] = useState(false);
|
|
64
65
|
const export_file = async () => {
|
|
65
|
-
const file = await attempt_value(() => settings_calls.export_settings());
|
|
66
|
+
const file = await attempt_value(() => settings_calls.export_settings(secrets && with_secrets));
|
|
66
67
|
if (file)
|
|
67
68
|
save_text(`${app_id}-settings-${new Date().toISOString().slice(0, 10)}.json`, JSON.stringify(file, null, 2));
|
|
68
69
|
};
|
|
@@ -73,7 +74,7 @@ function SettingsFile({ app_id }) {
|
|
|
73
74
|
if (result)
|
|
74
75
|
toast(result.changed === 1 ? "1 setting set." : `${result.changed} settings set.`, { tone: "good" });
|
|
75
76
|
};
|
|
76
|
-
return (
|
|
77
|
+
return (_jsxs(SettingRow, { label: "Settings file", hint: with_secrets ? "Every setting but this device's own, with your keys and tokens for other services; keep the file private." : "Every setting but this device's own, such as its notifications; keys for other services stay out.", children: [secrets && _jsx(Switch, { label: "Include keys and tokens", show_label: true, checked: with_secrets, on_change: set_with_secrets }), _jsxs("div", { className: "button-list", children: [_jsx("button", { type: "button", onClick: () => void export_file(), children: "Export" }), _jsxs("label", { className: "button", children: ["Import", _jsx("input", { type: "file", accept: ".json,application/json", className: "visually-hidden", "aria-label": "Import settings", onChange: (event) => void read_picked(event).then(import_file) })] })] })] }));
|
|
77
78
|
}
|
|
78
79
|
// A desktop window on a server's daemon, or a phone that keeps no data, works on the host's data, as a browser does.
|
|
79
80
|
function storage_category(pages, is_admin) {
|
|
@@ -100,7 +101,7 @@ function storage_category(pages, is_admin) {
|
|
|
100
101
|
}
|
|
101
102
|
if (desktop && !on_server)
|
|
102
103
|
sections.push({ id: "storage", heading: "Storage", hint: `Where this computer keeps its ${data_name}.`, content: _jsx(DataFolder, { desktop: desktop }) });
|
|
103
|
-
sections.push({ id: "settings-file", heading: "Import and export", hint: `Take ${name}'s settings to another device, or bring them back.`, content: _jsx(SettingsFile, { app_id: app.id }) });
|
|
104
|
+
sections.push({ id: "settings-file", heading: "Import and export", hint: `Take ${name}'s settings to another device, or bring them back.`, content: _jsx(SettingsFile, { app_id: app.id, secrets: pages.exports_secrets === true }) });
|
|
104
105
|
if (backups && (!on_server || is_admin)) {
|
|
105
106
|
const hint = backup_folder ? `This device's ${data_name}, kept in a folder of the phone's storage.` : on_server ? `The server's ${data_name}, kept in its data folder.` : `This device's ${data_name}, kept beside its database.`;
|
|
106
107
|
// This computer's backups folder opens in the file manager.
|
|
@@ -115,7 +116,12 @@ function storage_category(pages, is_admin) {
|
|
|
115
116
|
function users_category(pages, viewer) {
|
|
116
117
|
if (viewer === null)
|
|
117
118
|
return [];
|
|
118
|
-
const sections = users_settings({
|
|
119
|
+
const sections = users_settings({
|
|
120
|
+
client: viewer.client, me: viewer.me,
|
|
121
|
+
...(pages.role_text ? { role_text: pages.role_text } : {}),
|
|
122
|
+
...(pages.access_text ? { access_text: pages.access_text } : {}),
|
|
123
|
+
...(pages.access_editor ? { access_editor: pages.access_editor } : {}),
|
|
124
|
+
});
|
|
119
125
|
return sections.length > 0 ? [{ heading: "Users", sections }] : [];
|
|
120
126
|
}
|
|
121
127
|
export function SettingsView({ pages, is_admin = true, viewer = null }) {
|
|
@@ -147,7 +147,16 @@ export class AccountStore {
|
|
|
147
147
|
this.app_name = options.app_name;
|
|
148
148
|
this.roles = options.roles ?? default_roles;
|
|
149
149
|
this.declared = options.declared ?? new Map();
|
|
150
|
-
|
|
150
|
+
// An app's own check may throw a plain Error, such as one defined beside its page; it is refused as an account error.
|
|
151
|
+
const check = options.check_access ?? only_everything;
|
|
152
|
+
this.check_access = (value) => {
|
|
153
|
+
try {
|
|
154
|
+
return check(value);
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
throw error instanceof AccountError ? error : new AccountError(error instanceof Error ? error.message : String(error));
|
|
158
|
+
}
|
|
159
|
+
};
|
|
151
160
|
this.token_prefix = options.token_prefix ?? "xt";
|
|
152
161
|
this.shortest_password = options.shortest_password ?? 12;
|
|
153
162
|
this.declared_token_list = options.declared_tokens ?? [];
|
|
@@ -33,6 +33,6 @@ export declare class PasswordHashSlots {
|
|
|
33
33
|
private in_slot;
|
|
34
34
|
}
|
|
35
35
|
export declare const shared_password_hashes: PasswordHashSlots;
|
|
36
|
-
export declare function parse_accounts(text: string, source?: string): Accounts;
|
|
37
|
-
export declare function load_accounts(variable: string, file_path?: string | undefined): Accounts;
|
|
36
|
+
export declare function parse_accounts(text: string, source?: string, bare_name?: string): Accounts;
|
|
37
|
+
export declare function load_accounts(variable: string, file_path?: string | undefined, bare_name?: string): Accounts;
|
|
38
38
|
export declare function set_account(text: string, name: string, stored: string): string;
|
package/dist/server/passwords.js
CHANGED
|
@@ -95,14 +95,14 @@ export class PasswordHashSlots {
|
|
|
95
95
|
export const shared_password_hashes = new PasswordHashSlots();
|
|
96
96
|
// ── Accounts file ────────────────────────────────────────────────────────────
|
|
97
97
|
// Reads `name:hash` lines, skipping blank lines and `#` comments.
|
|
98
|
-
export function parse_accounts(text, source = "the accounts file") {
|
|
98
|
+
export function parse_accounts(text, source = "the accounts file", bare_name = default_account_name) {
|
|
99
99
|
const accounts = new Map();
|
|
100
100
|
for (const [index, raw_line] of text.split("\n").entries()) {
|
|
101
101
|
const line = raw_line.trim();
|
|
102
102
|
if (line === "" || line.startsWith("#"))
|
|
103
103
|
continue;
|
|
104
104
|
const separator = line.indexOf(":");
|
|
105
|
-
const name = separator === -1 ?
|
|
105
|
+
const name = separator === -1 ? bare_name : line.slice(0, separator);
|
|
106
106
|
const stored = separator === -1 ? line : line.slice(separator + 1);
|
|
107
107
|
const where = `${source} line ${index + 1}`;
|
|
108
108
|
if (!account_name_pattern.test(name))
|
|
@@ -116,10 +116,11 @@ export function parse_accounts(text, source = "the accounts file") {
|
|
|
116
116
|
return accounts;
|
|
117
117
|
}
|
|
118
118
|
// The accounts in the file the environment variable names, such as X_NIX_PASSWORD_HASH_FILE.
|
|
119
|
-
|
|
119
|
+
// A line holding a hash alone is the admin named bare_name, "admin" unless set.
|
|
120
|
+
export function load_accounts(variable, file_path = process.env[variable], bare_name = default_account_name) {
|
|
120
121
|
if (!file_path)
|
|
121
122
|
throw new Error(`${variable} is not set; create one with \`npm run hash-password -- <name> <file>\`.`);
|
|
122
|
-
const accounts = parse_accounts(readFileSync(file_path, "utf8"), file_path);
|
|
123
|
+
const accounts = parse_accounts(readFileSync(file_path, "utf8"), file_path, bare_name);
|
|
123
124
|
if (accounts.size === 0)
|
|
124
125
|
throw new Error(`${file_path} holds no users; add one with \`npm run hash-password -- <name> ${file_path}\`.`);
|
|
125
126
|
return accounts;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// An app's synced files, such as covers, served by name, the same on the web server and on the desktop daemon.
|
|
2
|
+
import { is_file_name } from "../sync_files.js";
|
|
3
|
+
import { send_text } from "./replies.js";
|
|
4
|
+
// ── Route ────────────────────────────────────────────────────────────────────
|
|
5
|
+
// GET <prefix>/files/<name>: a kept file by its name, which names its content, so it may be cached for good.
|
|
6
|
+
export function register_synced_files(api, store) {
|
|
7
|
+
api.get("/files/:name", async (request, reply) => {
|
|
8
|
+
const { name } = request.params;
|
|
9
|
+
const bytes = is_file_name(name) ? await store.read(name) : undefined;
|
|
10
|
+
if (!bytes)
|
|
11
|
+
return send_text(reply, 404, "no such file");
|
|
12
|
+
return reply.header("cache-control", "private, max-age=31536000, immutable").type("application/octet-stream").send(Buffer.from(bytes));
|
|
13
|
+
});
|
|
14
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x-tech-laboratories/x-app",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.127.0",
|
|
4
4
|
"description": "Code the X-apps share: agents and their long runs, passwords and sign-in, the Fastify server pieces, durations, and the web page's helpers and widgets",
|
|
5
5
|
"license": "GPL-3.0-or-later",
|
|
6
6
|
"repository": {
|