@x-tech-laboratories/x-app 0.120.0 → 0.122.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +27 -6
  2. package/dist/agent/ssh_config.d.ts +12 -0
  3. package/dist/agent/ssh_config.js +72 -0
  4. package/dist/app/daemon.d.ts +7 -1
  5. package/dist/app/daemon.js +82 -8
  6. package/dist/app/define.d.ts +38 -1
  7. package/dist/app/define.js +34 -1
  8. package/dist/app/desktop.d.ts +13 -0
  9. package/dist/app/desktop.js +35 -3
  10. package/dist/app/host_tables.d.ts +21 -0
  11. package/dist/app/host_tables.js +105 -0
  12. package/dist/app/preload.js +5 -0
  13. package/dist/app/protocol.d.ts +31 -1
  14. package/dist/app/protocol.js +8 -1
  15. package/dist/app/remote_access.d.ts +17 -0
  16. package/dist/app/remote_access.js +85 -0
  17. package/dist/app/server.d.ts +20 -5
  18. package/dist/app/server.js +101 -22
  19. package/dist/app/services.d.ts +25 -2
  20. package/dist/app/web/app_page.d.ts +1 -1
  21. package/dist/app/web/app_page.js +73 -12
  22. package/dist/app/web/hosts.d.ts +5 -3
  23. package/dist/app/web/hosts.js +35 -2
  24. package/dist/app/web/page.d.ts +3 -0
  25. package/dist/app/web/page.js +24 -4
  26. package/dist/app/web/portal.d.ts +14 -0
  27. package/dist/app/web/portal.js +115 -0
  28. package/dist/app/web/settings_page.d.ts +13 -2
  29. package/dist/app/web/settings_page.js +36 -8
  30. package/dist/change_checks.js +1 -1
  31. package/dist/github_targets.d.ts +12 -0
  32. package/dist/github_targets.js +90 -0
  33. package/dist/remote_access_protocol.d.ts +26 -0
  34. package/dist/remote_access_protocol.js +33 -0
  35. package/dist/server/github_webhook.d.ts +2 -12
  36. package/dist/server/github_webhook.js +2 -87
  37. package/dist/server/sqlite_backups.d.ts +2 -2
  38. package/dist/server/sqlite_backups.js +2 -2
  39. package/dist/server/viewer_scope.d.ts +3 -0
  40. package/dist/server/viewer_scope.js +14 -0
  41. package/dist/web/react/remote_access_settings.d.ts +5 -0
  42. package/dist/web/react/remote_access_settings.js +55 -0
  43. package/dist/web/react/shell.js +1 -1
  44. package/dist/web/remote_daemon.d.ts +26 -0
  45. package/dist/web/remote_daemon.js +105 -0
  46. package/dist/web/theme.d.ts +8 -0
  47. package/dist/web/theme.js +23 -0
  48. package/package.json +1 -1
@@ -12,21 +12,28 @@ import { openapi_document, positional_args } from "../api_spec.js";
12
12
  import { keep_backing_up } from "../backups.js";
13
13
  import { backup_method_names } from "../backups.js";
14
14
  import { calls_under, register_accounts } from "../server/account_sign_in.js";
15
+ import { read_declared_tokens } from "../server/declared_tokens.js";
16
+ import { OidcClient, oidc_from_environment } from "../server/oidc.js";
15
17
  import { caller_of, use_caller_scope } from "../caller.js";
16
18
  import { node_caller_scope } from "../node_caller_scope.js";
17
19
  import { AccountStore, holds_accounts, move_accounts } from "../server/account_store.js";
18
20
  import { register_call_table } from "../server/call_table.js";
21
+ import { register_open_cors } from "../server/cors.js";
19
22
  import { read_server_config } from "../server/config.js";
20
23
  import { EventStream } from "../server/events.js";
21
24
  import { register_mcp_route } from "../server/mcp.js";
25
+ import { register_plugin_files } from "../server/plugin_files.js";
22
26
  import { load_accounts } from "../server/passwords.js";
23
27
  import { BAD_JSON, register_error_replies, register_lenient_json_body, send_text } from "../server/replies.js";
24
28
  import { sqlite_backups } from "../server/sqlite_backups.js";
25
- import { register_sync_peer_routes } from "../server/sync_peer_routes.js";
29
+ import { register_sync_peer_routes, sync_peer_headers } from "../server/sync_peer_routes.js";
26
30
  import { register_web_folder } from "../server/web_folder.js";
27
31
  import { tidy_database, tidy_every_ms } from "../sql.js";
28
32
  import { file_sync_storage } from "../sync_file_storage.js";
33
+ import { read_server_theme } from "../web/theme.js";
29
34
  import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
35
+ import { call_path_of, mcp_tools, register_host_tables } from "./host_tables.js";
36
+ import { notice_event } from "./protocol.js";
30
37
  import { declared_file_of, no_services, side_databases } from "./services.js";
31
38
  // The server and the daemon run on Node, so a call's caller holds across its awaits.
32
39
  use_caller_scope(node_caller_scope());
@@ -42,15 +49,15 @@ export function open_app_database(app, path, backups_folder) {
42
49
  naming: app.backup_naming,
43
50
  database: () => database,
44
51
  database_path: () => path,
45
- close: () => {
46
- restore_hooks.before?.();
52
+ close: async () => {
53
+ await restore_hooks.before?.();
47
54
  database.close();
48
55
  },
49
- open: () => {
56
+ open: async () => {
50
57
  database = new DatabaseSync(path);
51
58
  start(database);
52
59
  tidy_database(database);
53
- restore_hooks.after?.();
60
+ await restore_hooks.after?.();
54
61
  },
55
62
  // The restored data no longer matches other devices', so sync asks again which copy wins.
56
63
  after_restore: (restored) => app.sync_engine.forget_history(restored),
@@ -182,17 +189,42 @@ const admin_paths = ["/api/backups/", "/api/sync/"];
182
189
  // Backup calls only the user at the page may make, since a restored backup could undo what only the user may change.
183
190
  export const user_only_backup_calls = new Set(["restore_backup", "remove_backup", "set_backup_schedule"]);
184
191
  export async function build_server(app, options) {
185
- const server = fastify({ forceCloseConnections: true });
192
+ const server = fastify({ forceCloseConnections: true, ...(options.https ? { https: options.https } : {}) });
186
193
  register_lenient_json_body(server);
187
194
  register_error_replies(server);
195
+ const kind = options.kind ?? "server";
196
+ const services = options.services ?? (() => no_services);
197
+ // A phone that keeps no data calls from a page of its own with a token, the sign-in included; the event stream
198
+ // writes its own head, so it carries the open origin itself.
199
+ if (app.phone === "portal") {
200
+ await register_open_cors(server, { allowed_headers: sync_peer_headers });
201
+ server.addHook("onRequest", async (request, reply) => {
202
+ if (request.url.split("?")[0] === "/api/events")
203
+ reply.raw.setHeader("access-control-allow-origin", "*");
204
+ });
205
+ }
206
+ const admin_tables = app.tables_on(kind, true).filter((name) => app.host_tables[name].network !== "any").map((name) => `/api/${name}/`);
207
+ const is_admin = (request) => request.viewer !== null && request.viewer !== undefined && options.accounts.has_role(request.viewer.role, options.accounts.top_role);
208
+ const has_role = (request, role) => request.viewer !== null && request.viewer !== undefined && options.accounts.has_role(request.viewer.role, role);
209
+ const reach = { kind, from_network: true, is_admin, has_role };
188
210
  await register_accounts(server, {
189
211
  accounts: options.accounts,
190
212
  cookie_name: `${app.id.replaceAll("-", "_")}_session`,
191
- // Each peer call is sealed between the two devices, so it needs no sign-in.
192
- open_paths: ["/api/sync/peer"],
213
+ // Each peer call is sealed between the two devices, so it needs no sign-in, and the app's open routes check their
214
+ // callers themselves.
215
+ open_paths: ["/api/sync/peer", "/api/theme", ...(options.routes?.open_paths ?? [])],
216
+ open_prefixes: options.routes?.open_prefixes ?? [],
217
+ guarded_paths: options.routes?.guarded_paths ?? [],
218
+ oidc: options.oidc ?? null,
219
+ ...(options.session_seconds !== undefined ? { session_seconds: options.session_seconds } : {}),
220
+ ...(options.remembered_seconds !== undefined ? { remembered_seconds: options.remembered_seconds } : {}),
193
221
  // A read-only token may still list and read through MCP, which posts every request.
194
222
  read_only_paths: ["/api/mcp"],
195
- needed: (_method, path) => (admin_paths.some((admin_path) => path.startsWith(admin_path)) ? { role: options.accounts.top_role } : "any"),
223
+ needed: (method, path) => {
224
+ if ([...admin_paths, ...admin_tables].some((admin_path) => path.startsWith(admin_path)))
225
+ return { role: options.accounts.top_role };
226
+ return options.routes?.needed?.(method, path) ?? "any";
227
+ },
196
228
  // A token is refused the calls only the user at the page may make; a read-only one may make the calls that only read.
197
229
  call_of: calls_under("/api/call"),
198
230
  is_read_only: app.is_read_only,
@@ -200,19 +232,23 @@ export async function build_server(app, options) {
200
232
  });
201
233
  const { changes, database } = options;
202
234
  const description = { title: app.name, version: app.version, description: app.instructions };
235
+ // A change made through MCP is announced to every page, since no page made it.
236
+ const tools = mcp_tools(app, reach, services, database, () => changes.announce_change());
237
+ const documented = Object.assign({}, app.api_spec, ...app.tables_on(kind, true).map((name) => app.host_tables[name].api));
203
238
  await server.register(async (api) => {
204
239
  changes.register(api, "/events");
240
+ api.get("/theme", async () => options.theme ?? read_server_theme(null));
205
241
  register_app_calls(api, app, database, changes);
206
- api.get("/openapi.json", async () => openapi_document(app.api_spec, { ...description, path_of: (method) => `/api/call/${method}`, is_read_only: app.is_read_only }));
207
- // A change made through MCP is announced to every page, since no page made it.
242
+ register_host_tables(api, app, reach, services, changes);
243
+ api.get("/openapi.json", async () => openapi_document(documented, { ...description, path_of: call_path_of(app, kind), is_read_only: app.is_read_only }));
208
244
  await register_mcp_route(api, {
209
245
  name: app.id,
210
246
  version: app.version,
211
247
  instructions: app.instructions,
212
- api: app.mcp.api,
248
+ api: tools.api,
213
249
  is_read_only: app.is_read_only,
214
250
  page_only: app.mcp.page_only,
215
- call: (method, args) => app.mcp.call(database, () => changes.announce_change(), method, args),
251
+ call: (method, args, request) => tools.call(method, args, request),
216
252
  });
217
253
  // The server's backups, as the page's Settings reach them.
218
254
  api.post("/backups/:method", async (request, reply) => {
@@ -229,9 +265,14 @@ export async function build_server(app, options) {
229
265
  return reply.code(204).send();
230
266
  return reply.type("application/json").header("cache-control", "no-store").send(JSON.stringify(result));
231
267
  });
232
- register_sync_peer_routes(api, options.sync);
233
- register_call_table(api, "/sync", sync_device_methods(options.sync), { is_read_only: app.is_read_only });
268
+ if (options.sync) {
269
+ register_sync_peer_routes(api, options.sync);
270
+ register_call_table(api, "/sync", sync_device_methods(options.sync), { is_read_only: app.is_read_only });
271
+ }
234
272
  }, { prefix: "/api" });
273
+ if (options.plugins_folder)
274
+ register_plugin_files(server, { folder: options.plugins_folder, prefix: "/api/plugins", side: "web" });
275
+ await options.routes?.register(server, services);
235
276
  await register_web_folder(server, { folder: options.web_folder });
236
277
  return server;
237
278
  }
@@ -263,44 +304,82 @@ export async function run_server(app, options) {
263
304
  await opened.back_up();
264
305
  move_accounts(opened.database(), accounts_database);
265
306
  }
307
+ // Tokens the config declares, read again whenever the app's services read a changed config.
308
+ const declare_tokens = (from) => {
309
+ const declared = app.declared_tokens;
310
+ if (!declared)
311
+ return [];
312
+ return read_declared_tokens(from[declared.key], { scopes: declared.scopes, ...(declared.limit_key ? { limit_key: declared.limit_key } : {}), new_token_command: `${app.id} token new` });
313
+ };
314
+ let declared_tokens = declare_tokens(config);
266
315
  const accounts = new AccountStore({
267
316
  database: accounts_database,
268
317
  app_name: app.name,
318
+ ...(app.roles ? { roles: app.roles } : {}),
269
319
  ...(app.token_prefix ? { token_prefix: app.token_prefix } : {}),
270
320
  declared: load_accounts(`${prefix}_PASSWORD_HASH_FILE`, server_config.values.password_hash_file),
321
+ declared_tokens: declared_tokens.filter((token) => token.role !== null),
271
322
  });
323
+ const oidc_settings = oidc_from_environment(prefix, options.env ?? process.env);
272
324
  // Every page hears of a change, whether a page or another device made it, and which tables it touched.
273
325
  const changes = new EventStream({ change_data: data_change_text(app, opened.database) });
274
- // The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be.
275
- const sync = create_sync_peer({
326
+ // Answers the host tables and the app's routes once started; before then they say the server is still starting.
327
+ let services = no_services;
328
+ // The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be; an app
329
+ // whose server is the only copy keeps none.
330
+ const sync = app.sync === false ? null : create_sync_peer({
276
331
  app: app.id,
277
332
  engine: app.sync_engine,
278
333
  database: opened.database,
279
334
  storage: file_sync_storage({ file: join(dirname(database_path), "sync-peers.json"), back_up_before_replace: opened.back_up }),
280
335
  device_name: `${app.name} server on ${hostname()}`,
281
336
  addresses: () => (config.sync_address ? [config.sync_address] : []),
282
- on_remote_change: () => changes.announce_change(),
337
+ on_remote_change: () => {
338
+ changes.announce_change();
339
+ services.after_remote_change?.();
340
+ },
341
+ });
342
+ const server = await build_server(app, {
343
+ database: opened.database, accounts, web_folder: server_config.web_folder, changes, backup_methods: opened.backup_methods, services: () => services,
344
+ ...(sync ? { sync } : {}),
345
+ ...(options.routes ? { routes: options.routes } : {}),
346
+ ...(oidc_settings ? { oidc: new OidcClient(oidc_settings) } : {}),
347
+ ...(config.session_seconds !== undefined ? { session_seconds: config.session_seconds } : {}),
348
+ ...(config.remembered_seconds !== undefined ? { remembered_seconds: config.remembered_seconds } : {}),
349
+ theme: read_server_theme(config.theme),
350
+ plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
283
351
  });
284
- const server = await build_server(app, { database: opened.database, accounts, web_folder: server_config.web_folder, sync, changes, backup_methods: opened.backup_methods });
285
352
  const stop_watching = watch_outside_changes(opened.database, () => changes.announce_change());
286
353
  const address = await server.listen({ host: server_config.host, port: server_config.port });
287
- sync.start();
354
+ sync?.start();
288
355
  const sides = side_databases(database_path);
289
- const services = options.services
356
+ services = options.services
290
357
  ? await options.services({
291
358
  kind: "server",
292
359
  database: opened.database,
293
360
  profile: dirname(database_path),
294
361
  device_name: `${app.name} server on ${hostname()}`,
295
362
  config: config,
363
+ config_file: resolve(server_config.values.config),
364
+ declared_tokens: () => declared_tokens,
365
+ reread_declared_tokens: (from) => {
366
+ declared_tokens = declare_tokens(from);
367
+ accounts.set_declared_tokens(declared_tokens.filter((token) => token.role !== null));
368
+ },
296
369
  plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
297
370
  declared_file: declared_file_of(app, options.env ?? process.env),
298
371
  announce: (client_id) => changes.announce_change(client_id),
372
+ wrote: () => {
373
+ app.record_writes(opened.database());
374
+ changes.announce_change();
375
+ },
299
376
  emit: (event, data) => changes.send(JSON.stringify(data), { event }),
300
377
  side_database: sides.open,
301
378
  back_up: opened.back_up,
302
379
  window_in_front: () => false,
303
380
  icon_path: null,
381
+ // The server shows no notice itself; the pages and phones working on it show them.
382
+ notify: (notice) => changes.send(JSON.stringify(notice), { event: notice_event }),
304
383
  })
305
384
  : no_services;
306
385
  opened.on_restore({ before: () => services.before_restore?.(), after: () => services.after_restore?.() });
@@ -309,7 +388,7 @@ export async function run_server(app, options) {
309
388
  const stop = () => (stopping ??= server.close().then(async () => {
310
389
  await services.stop();
311
390
  stop_watching();
312
- sync.stop();
391
+ sync?.stop();
313
392
  sides.close_all();
314
393
  opened.close();
315
394
  accounts_database.close();
@@ -1,26 +1,49 @@
1
1
  import { DatabaseSync } from "node:sqlite";
2
+ import type { FastifyInstance } from "fastify";
3
+ import type { Need } from "../server/account_sign_in.ts";
4
+ import type { DeclaredToken } from "../server/declared_tokens.ts";
2
5
  import type { App } from "./define.ts";
6
+ import type { AppNotice } from "./protocol.ts";
3
7
  export interface HostContext {
4
8
  kind: "server" | "desktop";
5
9
  database: () => DatabaseSync;
6
10
  profile: string;
7
11
  device_name: string;
8
12
  config: Readonly<Record<string, unknown>>;
13
+ config_file: string | null;
14
+ declared_tokens: () => readonly DeclaredToken[];
15
+ reread_declared_tokens: (config: Readonly<Record<string, unknown>>) => void;
9
16
  plugins_folder: string | null;
10
17
  declared_file: string;
11
18
  announce: (client_id?: string) => void;
19
+ wrote: () => void;
12
20
  emit: (event: string, data: unknown) => void;
13
21
  side_database: (name: string) => DatabaseSync;
14
22
  back_up: () => Promise<void>;
15
23
  window_in_front: () => boolean;
16
24
  icon_path: string | null;
25
+ notify: (notice: AppNotice) => void;
26
+ }
27
+ export interface ServedTable {
28
+ methods: object;
29
+ elsewhere?: object;
17
30
  }
18
31
  export interface HostServices {
19
- before_restore?: () => void;
20
- after_restore?: () => void;
32
+ before_restore?: () => void | Promise<void>;
33
+ after_restore?: () => void | Promise<void>;
21
34
  stop: () => void | Promise<void>;
35
+ tables?: Readonly<Record<string, ServedTable>>;
36
+ own?: unknown;
37
+ after_remote_change?: () => void;
22
38
  }
23
39
  export type StartServices = (context: HostContext) => HostServices | Promise<HostServices>;
40
+ export interface AppRoutes {
41
+ open_paths?: readonly string[];
42
+ open_prefixes?: readonly string[];
43
+ guarded_paths?: readonly string[];
44
+ needed?: (method: string, path: string) => Need | null;
45
+ register: (server: FastifyInstance, services: () => HostServices) => void | Promise<void>;
46
+ }
24
47
  export declare function declared_file_of(app: Pick<App, "id" | "env_prefix">, env: NodeJS.ProcessEnv): string;
25
48
  export interface SideDatabases {
26
49
  open: (name: string) => DatabaseSync;
@@ -2,7 +2,7 @@ import "@x-tech-laboratories/halon/halon-tokens.css";
2
2
  import "@x-tech-laboratories/halon/halon.css";
3
3
  import type { App } from "../define.ts";
4
4
  import { type AppPages } from "./settings_page.tsx";
5
- export type { AppPage, AppPages, AppSubpage, PageSettingsProps } from "./settings_page.tsx";
5
+ export type { AppChrome, AppPage, AppPages, AppSubpage, PageSettingsProps } from "./settings_page.tsx";
6
6
  export declare const default_sidebar_width: {
7
7
  default_width: number;
8
8
  min: number;
@@ -4,18 +4,19 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
4
4
  // ── Imports ──────────────────────────────────────────────────────────────────
5
5
  import "@x-tech-laboratories/halon/halon-tokens.css";
6
6
  import "@x-tech-laboratories/halon/halon.css";
7
- import { Fragment, useEffect, useMemo, useRef } from "react";
7
+ import { Fragment, useEffect, useMemo, useRef, useState } from "react";
8
8
  import { createRoot } from "react-dom/client";
9
9
  import { create_accounts_client } from "../../web/accounts.js";
10
10
  import { AccountView, UsersView } from "../../web/react/accounts.js";
11
11
  import { SyncCertificatePrompt } from "../../web/react/certificates.js";
12
+ import { ConnectionSettings } from "../../web/react/connections.js";
12
13
  import { PageHeading } from "../../web/react/layout.js";
13
14
  import { Shell, use_route } from "../../web/react/shell.js";
14
15
  import { SignInForm, use_account } from "../../web/react/sign_in.js";
15
16
  import { SyncButton } from "../../web/react/sync_settings.js";
16
- import { local_theme_storage, theme_choice } from "../../web/theme.js";
17
+ import { apply_theme_colors, local_theme_storage, pinned_theme_choice, read_server_theme, theme_choice } from "../../web/theme.js";
17
18
  import { desktop_api, is_android, is_desktop, web_api } from "./hosts.js";
18
- import { calls, data_watch, page, set_page_api, use_settings } from "./page.js";
19
+ import { calls, data_watch, page, set_page_api, set_page_reach, use_settings } from "./page.js";
19
20
  import { SettingsView } from "./settings_page.js";
20
21
  // ── Pages ────────────────────────────────────────────────────────────────────
21
22
  // Relative, so a server behind a proxy under a folder keeps it.
@@ -39,13 +40,27 @@ function is_theme(value) {
39
40
  }
40
41
  // The theme kept in this browser, or for an app with synced_theme in its synced setting, which a change on another
41
42
  // device applies here too; this browser's copy shows it before the settings arrive.
43
+ // The look a browser's server pins, read once before the page draws.
44
+ async function read_theme_of_server() {
45
+ try {
46
+ const reply = await fetch("api/theme", { cache: "no-store" });
47
+ return reply.ok ? read_server_theme(await reply.json()) : read_server_theme(null);
48
+ }
49
+ catch {
50
+ return read_server_theme(null);
51
+ }
52
+ }
53
+ // A scheme the server pins wins over both, and the page then offers no way to change it.
42
54
  function use_theme(app) {
55
+ const pinned = page().server_theme?.scheme ?? null;
43
56
  const settings = use_settings();
44
57
  const synced = app.synced_theme === true;
45
58
  const stored = synced ? settings.data?.theme : undefined;
46
59
  const latest = useRef(undefined);
47
60
  latest.current = stored;
48
61
  const theme = useMemo(() => {
62
+ if (pinned)
63
+ return pinned_theme_choice(pinned);
49
64
  const local = local_theme_storage(`${app.id}-theme`);
50
65
  if (!synced)
51
66
  return theme_choice(local);
@@ -57,7 +72,7 @@ function use_theme(app) {
57
72
  void calls().set_setting("theme", chosen).catch(() => undefined);
58
73
  },
59
74
  });
60
- }, [app.id, synced]);
75
+ }, [app.id, synced, pinned]);
61
76
  // The desktop window's own parts, such as menus, follow the page's theme.
62
77
  useEffect(() => {
63
78
  const tell = (chosen) => void page().desktop?.set_window_theme(chosen).catch(() => undefined);
@@ -65,11 +80,11 @@ function use_theme(app) {
65
80
  return theme.on_change(tell);
66
81
  }, [theme]);
67
82
  useEffect(() => {
68
- if (!is_theme(stored))
83
+ if (pinned || !is_theme(stored))
69
84
  return;
70
85
  local_theme_storage(`${app.id}-theme`).write(stored);
71
86
  theme.apply(stored);
72
- }, [stored, theme]);
87
+ }, [stored, theme, pinned]);
73
88
  return theme;
74
89
  }
75
90
  function Pages({ pages, account }) {
@@ -82,7 +97,7 @@ function Pages({ pages, account }) {
82
97
  const children = shown?.children && shown.children.length > 1 ? shown.children : [];
83
98
  const subpage = children.find((child) => child.id === rest[0]) ?? children[0];
84
99
  const label = shown ? (subpage ? `${subpage.label} · ${shown.label}` : shown.label) : is_account ? "Your account" : "Settings";
85
- const view_key = route.parts.join("/");
100
+ const view_key = shown?.view_key ? [section, shown.view_key(rest)].join("/") : route.parts.join("/");
86
101
  const chrome = pages.use_chrome?.(route.parts) ?? {};
87
102
  const theme = use_theme(app);
88
103
  useEffect(() => {
@@ -93,6 +108,8 @@ function Pages({ pages, account }) {
93
108
  const badges = listed.map((each) => each.use_badge?.() ?? null);
94
109
  const row_label = (index) => (badges[index] ? `${listed[index].label} · ${badges[index]}` : listed[index].label);
95
110
  const with_icons = listed.some((each) => each.icon);
111
+ // An app's own sidebar content, such as a tree, takes the place of plain sections, so the pages show as rows above it.
112
+ const folding = listed.some((each) => each.children && each.children.length > 1);
96
113
  const sections = listed.map((each, index) => ({
97
114
  id: each.id,
98
115
  label: row_label(index),
@@ -100,25 +117,54 @@ function Pages({ pages, account }) {
100
117
  ...(each.children && each.children.length > 1 ? { children: each.children.map((child) => ({ id: child.id, label: child.label, href: `#/${each.id}/${child.id}` })) } : {}),
101
118
  }));
102
119
  const views = listed.map((each, index) => ({ id: each.id, label: row_label(index), href: `#/${each.id}`, ...(each.icon ? { icon: each.icon } : {}) }));
103
- const view = shown ? shown.view(rest) : is_account ? _jsx(AccountPage, { account: account }) : _jsx(SettingsView, { pages: pages, is_admin: account === null || is_admin(account.me) });
120
+ const view = shown ? shown.view(rest) : is_account ? _jsx(AccountPage, { account: account }) : _jsx(SettingsView, { pages: pages, is_admin: account === null || is_admin(account.me), viewer: account ? { client: accounts, me: account.me } : null });
104
121
  const framed = _jsx(Fragment, { children: view }, view_key);
105
122
  if (chrome.bare)
106
123
  return _jsx(_Fragment, { children: chrome.around ? chrome.around(framed) : framed });
107
- return (_jsx(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", ...(with_icons ? { views } : { sections }), active: shown?.active_as ?? section, active_item: subpage?.id ?? null, sections_pref: `${app.id}-sidebar-collapsed`, ...(chrome.sidebar ? { sidebar: chrome.sidebar } : {}), ...(chrome.tools ? { tools: chrome.tools } : {}), ...(chrome.side_pane ? { side_pane: chrome.side_pane } : {}), ...(chrome.contained ? { contained: true } : {}), ...(chrome.main_class ? { main_class: chrome.main_class } : {}), theme: theme, sidebar_width: chrome.sidebar_width ?? { ...default_sidebar_width, storage_key: `${app.id}-sidebar-width` }, view_key: view_key, user: account ? account.me.name : undefined, user_href: account ? "#/account" : undefined, on_logout: account ? () => void account.sign_out() : undefined, sidebar_foot: _jsx(SidebarFoot, {}), settings: { href: "#/settings" }, children: chrome.around ? chrome.around(framed) : framed }));
124
+ return (_jsx(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", ...(with_icons || (chrome.sidebar && !folding) ? { views } : { sections }), active: shown?.active_as ?? section, active_item: subpage?.id ?? null, sections_pref: `${app.id}-sidebar-collapsed`, ...(chrome.sidebar ? { sidebar: chrome.sidebar } : {}), ...(chrome.tools ? { tools: chrome.tools } : {}), ...(chrome.side_pane ? { side_pane: chrome.side_pane } : {}), ...(chrome.contained ? { contained: true } : {}), ...(chrome.main_class ? { main_class: chrome.main_class } : {}), theme: theme, sidebar_width: chrome.sidebar_width ?? { ...default_sidebar_width, storage_key: `${app.id}-sidebar-width` }, view_key: view_key, user: account ? account.me.name : undefined, user_href: account ? "#/account" : undefined, on_logout: account ? () => void account.sign_out() : undefined, sidebar_foot: _jsx(SidebarFoot, {}), settings: { href: "#/settings" }, children: chrome.around ? chrome.around(framed) : framed }));
108
125
  }
109
126
  // ── App ──────────────────────────────────────────────────────────────────────
110
127
  // A browser reaches the server's data, so it signs in; the desktop and phone apps keep their own and sign in only to sync.
111
128
  function BrowserApp({ pages }) {
112
129
  const { account, refresh, sign_out } = use_account(accounts);
130
+ // What the server lets this viewer reach is read again once they are signed in, as it was read before.
131
+ const [reach_read, set_reach_read] = useState(null);
132
+ const signed_in_as = account.state === "signed_in" ? account.me.name : null;
133
+ useEffect(() => {
134
+ if (signed_in_as === null || reach_read === signed_in_as)
135
+ return;
136
+ void (page().reread_abilities?.() ?? Promise.resolve({})).then((reach) => {
137
+ set_page_reach(reach);
138
+ set_reach_read(signed_in_as);
139
+ });
140
+ }, [signed_in_as, reach_read]);
113
141
  if (account.state === "checking")
114
142
  return null;
143
+ if (signed_in_as !== null && reach_read !== signed_in_as && page().reread_abilities)
144
+ return null;
115
145
  if (account.state === "signed_out")
116
146
  return _jsx(SignInForm, { client: accounts, title: pages.app.name, icon: pages.brand_icon ?? "icon.svg", on_signed_in: refresh });
117
147
  return _jsx(Pages, { pages: pages, account: { me: account.me, refresh, sign_out } });
118
148
  }
149
+ // A phone that keeps no data and has no host yet adds one before anything else.
150
+ function FirstConnection({ pages }) {
151
+ const { connections, certificates } = page();
152
+ const { app } = pages;
153
+ return (_jsxs(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", theme: theme_choice(local_theme_storage(`${app.id}-theme`)), children: [_jsx(PageHeading, { title: `Connect to ${app.name}`, subtitle: `Add the computer this phone works on, with its address and an admin's name and password. Turn on Let other devices connect in its Settings first.` }), _jsx(ConnectionSettings, { client: connections, certificates: certificates, placeholder: app.server_example })] }));
154
+ }
119
155
  // A device that syncs asks to trust its server's certificate whenever sync fails over it.
120
156
  function DeviceApp({ pages }) {
121
- const { certificates, device } = page();
157
+ const { certificates, connections, device, host } = page();
158
+ const portal = host === "android" && pages.app.phone === "portal" && connections !== undefined;
159
+ const [has_host, set_has_host] = useState(portal ? null : true);
160
+ useEffect(() => {
161
+ if (portal)
162
+ void connections.list_connections().then((view) => set_has_host(view.current !== null), () => set_has_host(true));
163
+ }, [portal, connections]);
164
+ if (has_host === null)
165
+ return null;
166
+ if (!has_host)
167
+ return _jsx(FirstConnection, { pages: pages });
122
168
  return _jsxs(_Fragment, { children: [device && certificates && _jsx(SyncCertificatePrompt, { device: device, certificates: certificates, subscribe: (listener) => data_watch.subscribe(listener) }), _jsx(Pages, { pages: pages, account: null })] });
123
169
  }
124
170
  export function AppView({ pages }) {
@@ -126,9 +172,14 @@ export function AppView({ pages }) {
126
172
  }
127
173
  // ── Start ────────────────────────────────────────────────────────────────────
128
174
  // The phone's code loads only on the phone, so a browser never fetches SQLite.
129
- async function host_api(app, phone_services) {
175
+ async function host_api(app, pages) {
130
176
  if (is_desktop(app))
131
177
  return desktop_api(app);
178
+ if (is_android() && app.phone === "portal") {
179
+ const [{ portal_api }, { App: CapacitorApp }] = await Promise.all([import("./portal.js"), import("@capacitor/app")]);
180
+ return portal_api(app, { lifecycle: CapacitorApp, ...(pages.phone_notifications ? { notifications: await pages.phone_notifications() } : {}) });
181
+ }
182
+ const phone_services = pages.phone_services;
132
183
  if (is_android()) {
133
184
  const { android_api } = await import("./android.js");
134
185
  return android_api(app, phone_services ? { services: await phone_services() } : {});
@@ -137,7 +188,17 @@ async function host_api(app, phone_services) {
137
188
  }
138
189
  // Starts the page on whichever host it runs: the desktop app, the phone app or a browser.
139
190
  export async function render_app(pages, root = document.getElementById("app")) {
140
- const api = await host_api(pages.app, pages.phone_services);
191
+ const api = await host_api(pages.app, pages);
192
+ // A browser takes the look its server pins before anything draws, the sign-in page included.
193
+ if (api.host === "web") {
194
+ const server_theme = await read_theme_of_server();
195
+ api.server_theme = server_theme;
196
+ apply_theme_colors(server_theme.colors);
197
+ if (server_theme.scheme)
198
+ pinned_theme_choice(server_theme.scheme).apply();
199
+ }
200
+ if (api.reread_abilities)
201
+ Object.assign(api, await api.reread_abilities());
141
202
  set_page_api(api);
142
203
  // A link the desktop app was opened with, or a tray row, opens its page.
143
204
  api.on_event?.("open", (route) => {
@@ -1,6 +1,8 @@
1
1
  import type { App } from "../define.ts";
2
- import { type PageApi } from "../protocol.ts";
3
- export declare function web_api(app: Pick<App, "bridges">): PageApi;
2
+ import { type HostAbilities, type PageApi } from "../protocol.ts";
3
+ export declare function read_host_abilities(read: () => Promise<unknown>): Promise<HostAbilities>;
4
+ export declare function host_tables_of(app: Pick<App, "bridges">, abilities: HostAbilities, client_of: (name: string) => unknown): NonNullable<PageApi["tables"]>;
5
+ export declare function web_api(app: Pick<App, "bridges"> & Partial<Pick<App, "sync">>): PageApi;
4
6
  export declare function is_desktop(app: Pick<App, "bridges">): boolean;
5
- export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "local_mcp">>): Promise<PageApi>;
7
+ export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "local_mcp" | "remote_access">>): Promise<PageApi>;
6
8
  export declare function is_android(): boolean;
@@ -4,6 +4,22 @@
4
4
  import { LOCAL_CONNECTION_ID } from "../../connection_protocol.js";
5
5
  import { LoginNeeded } from "../../web/states.js";
6
6
  import { data_change_of } from "../protocol.js";
7
+ // ── Host tables ──────────────────────────────────────────────────────────────
8
+ // What the host lets the page reach, or nothing while it cannot be asked, such as before signing in.
9
+ export async function read_host_abilities(read) {
10
+ try {
11
+ const found = (await read());
12
+ return { admin: found?.admin === true, tables: Array.isArray(found?.tables) ? found.tables.filter((name) => typeof name === "string") : [] };
13
+ }
14
+ catch {
15
+ return { admin: false, tables: [] };
16
+ }
17
+ }
18
+ // The host tables the abilities name, each a client built by the host's own way of calling.
19
+ export function host_tables_of(app, abilities, client_of) {
20
+ const known = abilities.tables.filter((name) => Object.hasOwn(app.bridges.host_tables, name));
21
+ return Object.fromEntries(known.map((name) => [name, client_of(name)]));
22
+ }
7
23
  // ── Web ──────────────────────────────────────────────────────────────────────
8
24
  // Relative, so a server behind a proxy under a folder keeps it.
9
25
  const call_path = "api/call/";
@@ -11,6 +27,7 @@ const backups_path = "api/backups/";
11
27
  // The server's own sync calls sit beside the route paired devices sync through.
12
28
  const device_path = "api/sync/";
13
29
  const events_path = "api/events";
30
+ const host_path = "api/host/";
14
31
  const client_id_header = "x-client-id";
15
32
  const reconnect_delay_ms = 5000;
16
33
  // A greeting after the first means the stream reconnected and may have missed changes, so the page reloads too.
@@ -72,11 +89,21 @@ export function web_api(app) {
72
89
  listener(change);
73
90
  }, (given) => (client_id = given), named);
74
91
  const { bridges } = app;
92
+ // What this viewer reaches on the server, read again once they sign in.
93
+ const read_abilities = () => read_host_abilities(() => post_call(host_path, "get_host_abilities", []));
94
+ const reach = (abilities) => ({
95
+ admin: abilities.admin,
96
+ tables: host_tables_of(app, abilities, (name) => bridges.host_tables[name].web_rpc((method, args) => post_call(`api/${name}/`, method, args))),
97
+ });
75
98
  return {
76
99
  host: "web",
100
+ // None until read, which render_app does before the page shows, and again once the viewer signs in.
101
+ tables: {},
102
+ admin: false,
103
+ reread_abilities: async () => reach(await read_abilities()),
77
104
  calls: bridges.calls.web_rpc((method, args) => post_call(call_path, method, args)),
78
- // The server's own sync peer and backups, which only an admin reaches.
79
- device: bridges.device.web_rpc((method, args) => post_call(device_path, method, args)),
105
+ // 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
+ device: app.sync === false ? null : bridges.device.web_rpc((method, args) => post_call(device_path, method, args)),
80
107
  backups: bridges.backups.web_rpc((method, args) => post_call(backups_path, method, args)),
81
108
  on_change: (listener) => {
82
109
  listeners.add(listener);
@@ -104,8 +131,14 @@ export async function desktop_api(app) {
104
131
  const events = exposed[bridges.events.api_name];
105
132
  const connections = exposed[bridges.connections.api_name];
106
133
  const is_here = (await connections.list_connections()).current === LOCAL_CONNECTION_ID;
134
+ const host = exposed[bridges.host.api_name];
135
+ const abilities = await read_host_abilities(async () => host?.get_host_abilities());
107
136
  return {
108
137
  host: "desktop",
138
+ admin: abilities.admin,
139
+ tables: host_tables_of(app, abilities, (name) => exposed[bridges.host_tables[name].api_name]),
140
+ daemon_is_here: is_here,
141
+ ...(is_here && app.remote_access && exposed[bridges.remote_access.api_name] ? { remote_access: exposed[bridges.remote_access.api_name] } : {}),
109
142
  calls: exposed[bridges.calls.api_name],
110
143
  // Sync belongs to this computer's own daemon, so it shows only while that daemon is in use.
111
144
  device: is_here ? exposed[bridges.device.api_name] : null,
@@ -4,8 +4,10 @@ import type { PageApi } from "../protocol.ts";
4
4
  type AnyMethods = Record<string, (...args: never[]) => unknown>;
5
5
  export declare const data_watch: import("../../web/watch.ts").Watch;
6
6
  export declare function set_page_api<Methods extends Record<keyof Methods, (...args: never[]) => unknown>>(api: PageApi<Methods>): void;
7
+ export declare function set_page_reach(reach: Pick<PageApi, "admin" | "tables">): void;
7
8
  export declare function page(): PageApi;
8
9
  export declare function calls(): Client<AnyMethods>;
10
+ export declare function host_table<Methods extends Record<keyof Methods, (...args: never[]) => unknown> = AnyMethods>(name: string): Client<Methods> | null;
9
11
  export declare function use_data<Data>(load: (api: Client<AnyMethods>) => Promise<Data>, dependencies?: unknown[]): Resource<Data>;
10
12
  export declare function use_settings(): Resource<Record<string, unknown>>;
11
13
  export declare function page_hooks<Methods extends Record<keyof Methods, (...args: never[]) => unknown>>(): {
@@ -13,5 +15,6 @@ export declare function page_hooks<Methods extends Record<keyof Methods, (...arg
13
15
  calls: () => Client<Methods>;
14
16
  use_data: <Data>(load: (api: Client<Methods>) => Promise<Data>, dependencies?: unknown[]) => Resource<Data>;
15
17
  use_settings: typeof use_settings;
18
+ host_table: typeof host_table;
16
19
  };
17
20
  export {};