@x-tech-laboratories/x-app 0.100.0 → 0.101.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 CHANGED
@@ -38,8 +38,9 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
38
38
  | `email_links` | `bare_message_id` and `email_uri`: an email linked by its Message-ID as an RFC 2392 `mid:` link, which mail programs such as Thunderbird open wherever the message was filed. |
39
39
  | `snippets` | `shorten(text, length = 200)`: text put on one line and cut with an ellipsis, for an excerpt under a title. |
40
40
  | `drizzle`, `drizzle_migrations` | Typed SQLite on Drizzle ORM 1.0.0-rc.5, chosen over Kysely and hand-written SQL because it types rows from one schema in TypeScript, writes the migration SQL from it with drizzle-kit and runs synchronously: `open_drizzle` over any `SqlDatabase`, and `drizzle_of`, which the stores call, making it once per connection, so the same queries run on node:sqlite and in a phone's page, `synced_tables` reading the sync list from the schema's primary keys, `migrate_drizzle` per owner, the schema builders and query operators so an app never imports Drizzle, with `AnySQLiteColumn` for a table whose rows point at its own, and `x-app-bundle-migrations <folder>`, which turns drizzle-kit's migration folders into an `index.ts` a server running .ts files can import. |
41
- | `sync_engine`, `sync_peer`, `sync_protocol`, `sync_seal`, `server/sync_peer_routes`, `sync_peer_discovery`, `sync_peer_listening` | SQLite kept alike on every device with no server: `create_sync_engine` stamps each value of the tables it is given through triggers, so the app's own writes need no change, and the newest write of each value wins, each key of a table's `map_columns` (JSON objects such as ids from many sources) counting as a value of its own so two devices adding different keys keep both. Every copy is a peer: `create_sync_peer` pairs with another device through a one-time code (`create_pairing_code`, `pair_device`), the two copies merging with nothing asked, then sends each paired device its changes within seconds, takes theirs in the same round trip, holds a waiting call open to hear of theirs at once, and passes on what it took from the others, so devices that never reach each other still end up alike; the group's list of devices travels too, so a new device is introduced to the rest and a removed one (`remove_device`) is refused by all. Each call is sealed with both devices' keys on tweetnacl's box (`sync_seal`), chosen over TLS with pinned certificates because it runs alike on Node and in a phone's page and needs no certificate, so a call may travel over plain http on a home network. After a restore (`forget_history`) each peer is made to match the restored copy once, keeping a copy of its own first. `register_sync_peer_routes` answers other devices at `sync/peer` under a daemon's prefix, `listen_for_peers` opens a desktop daemon's own port for them, `discover_peers` finds paired devices on the local network by mDNS, on bonjour-service, and `keep_listening_for_peers` (`sync_peer_listening`) is a desktop daemon's "Let other devices connect" setting, kept in a file beside the database, whose `PeerListeningMethods` the page shows with `PeerListeningSettings`. |
41
+ | `sync_engine`, `sync_peer`, `sync_protocol`, `sync_seal`, `server/sync_peer_routes`, `sync_peer_discovery`, `sync_peer_listening` | SQLite kept alike on every device with no server: `create_sync_engine` stamps each value of the tables it is given through triggers, so the app's own writes need no change, and the newest write of each value wins, each key of a table's `map_columns` (JSON objects such as ids from many sources) counting as a value of its own so two devices adding different keys keep both. Every copy is a peer: `create_sync_peer` pairs with another device through a one-time code (`create_pairing_code`, `pair_device`), the two copies merging with nothing asked, then sends each paired device its changes within seconds, takes theirs in the same round trip, holds a waiting call open to hear of theirs at once, and passes on what it took from the others, so devices that never reach each other still end up alike; the group's list of devices travels too, so a new device is introduced to the rest and a removed one (`remove_device`) is refused by all. Each call is sealed with both devices' keys on tweetnacl's box (`sync_seal`), chosen over TLS with pinned certificates because it runs alike on Node and in a phone's page; calls still travel over https only. After a restore (`forget_history`) each peer is made to match the restored copy once, keeping a copy of its own first. `register_sync_peer_routes` answers other devices at `sync/peer` under a daemon's prefix, `listen_for_peers` opens a desktop daemon's own port for them, `discover_peers` finds paired devices on the local network by mDNS, on bonjour-service, and `keep_listening_for_peers` (`sync_peer_listening`) is a desktop daemon's "Let other devices connect" setting, kept in a file beside the database, which answers over https with a self-signed certificate made once (`peer_certificate`, on selfsigned, chosen because it makes one with Node's own crypto) and whose `PeerListeningMethods`, its fingerprint included, the page shows with `PeerListeningSettings`; `SyncSettings` given `certificates` asks to review and trust that certificate when pairing fails over it, and pairs again. |
42
42
  | `sync_files`, `node_file_store`, `electron/file_protocol` | Files that sync beside the rows that name them, such as covers or photos, so a large picture never travels with every change: each is named by the sha256 of its bytes (`hash_bytes`, `put_file`, `is_file_name`) and kept in a `SyncFileStore`, a folder on Node (`folder_file_store`, written through a rename) or IndexedDB on a phone (`indexed_db_files`); given `files: { store, referenced }`, the sync peer sends each paired device the named files it lacks and fetches those this device lacks after each exchange, a few at a time, trying a file neither has yet again next round, and keeps the ones it is sent, refusing bytes that do not match their name; `register_file_scheme` and `serve_files` show them in a desktop page as `<scheme>://<name>`. |
43
+ | `app_android` | `x-app-android [app folder]`: the app's Capacitor project in `android/`, made from Capacitor's template when it is missing, given X-App's `config/android/release.gradle` (the version CI hands each build, and signing when the release key is in the environment), its launcher icons from `x-app-icons`, then `cap sync android`. Run after the Android page is built; the app keeps `android/` out of git. |
43
44
  | `app_icons` | `x-app-icons [app folder]`: every icon an app ships generated from its `resources/icon.svg`, as the Design Guidelines ask: `resources/icon.png` for the desktop, the Android launcher icons at each density with an adaptive icon on white when there is an `android/` project, and `icon.svg`, `icon-192.png` and `icon-512.png` in `src/web/public` when there is one. Drawn with `@resvg/resvg-js`, an optional peer the app installs as a dev dependency. |
44
45
  | `change_checks`, `change_checks_git`, `change_checks_cli` | Checks on a change that any repository's CI runs, as `x-app-check` (see [Change checks](#change-checks)): `commits` (Conventional Commits, the `Assisted-by` trailer in the organisation's repositories and nowhere else, no AI mention outside it), `secrets` (keys and tokens in added lines, commit messages and added `.env` files, naming only the kind and place, never the value), `leftovers` (console logging, `debugger`, code commented out, a TODO without an issue), `comments` (a comment longer than one line, but for a file's overview), `coverage` (a floor lowered or code newly left out), `x-libs` (an import of a library X-App wraps) and `dependencies` (each new one named with its licence, failing a licence not allowed, read as SPDX by `spdx-satisfies`); each a pure function on a described `Change` giving `{ gate, outcome, findings }` with file:line, reading only the code around strings and regular expressions; `create_check_registry` for an app's own checks, `x_tech_options` the defaults, and `read_change` reading a change from git, its `base` resolved to a commit; `run_check_command` runs the command for an app with its own checks, defaults and name. |
45
46
  | `certificates`, `certificate_protocol`, `electron/certificates` | Servers whose https certificate the device refuses, such as a home server's self-signed one: `check_certificate` reads the certificate and what is wrong with it (self-signed, unknown authority, wrong name, expired, not yet valid), `create_certificate_trust` keeps the ones the user trusts in a JSON file, each for its own host and exact fingerprint, re-checked before it is saved, and its `methods` are the page's calls; `trust_in_session` makes Chromium accept them in a session, the window's from the next start, and `trusting_fetch` sends the main process's requests, such as the sync client's, through a Chromium session made fresh each time the list changes, so a new choice holds at once; `use_in_node` also hands them to Node's own https, which then accepts a self-signed server whose name matches. |
@@ -217,9 +218,13 @@ The rest of an app's files are short calls into X-App too:
217
218
  - **Nix**: X-App's flake has a `lib` with `package`, `desktop_package`, `module`, `shell` and `android_shell`, each
218
219
  taking the app's package set and its `nix/app.nix` (name, display name, variables' prefix, port, database file and
219
220
  words); the app's `nix/flake.nix` takes `github:x-tech-laboratories/X-App` as an input and calls them.
221
+ - **Android**: `npm run build:android` builds the phone's page and runs `x-app-android`, which makes or updates the
222
+ Capacitor project in `android/`, so the app keeps only `capacitor.config.json` and leaves `android/` out of git.
220
223
  - **CI**: the app's `ci` job runs `x-tech-laboratories/X-App/.github/actions/app-ci@main`, its `nix` job
221
- `app-nix@main` with the targets to build, and its Dependabot workflow `app-dependabot-auto-merge@main`. They are
222
- composite actions, so the jobs keep the names `ci` and `nix` the ruleset requires.
224
+ `app-nix@main` with the targets to build, an Android app's `android` job `app-android@main` with the release key's
225
+ secrets (the APK as the run's artifact, and a GitHub release from a `v*` tag), and its Dependabot workflow
226
+ `app-dependabot-auto-merge@main`. They are composite actions, so the jobs keep the names `ci` and `nix` the ruleset
227
+ requires.
223
228
 
224
229
  `npx x-app-new X-Notes` writes all of it for a new app.
225
230
 
@@ -425,10 +430,8 @@ const sync = create_sync_peer({ ...options, storage: local_sync_storage({ key: "
425
430
  ```
426
431
 
427
432
  The bridge answers `sync_device_methods(sync)`, and the Sync section is `SyncSettings`, with
428
- `<PeerListeningSettings listening={...} />` in its `extra` on the desktop. A server lets the route through its sign-in
429
- with `open_paths: ["/api/sync/peer"]`, since every call carries its own seal. A phone's page reaches a
430
- desktop daemon over plain http, so its Capacitor config sets `android.allowMixedContent`; every call is sealed, so
431
- nothing travels readable. A restore runs `after_restore: engine.forget_history`, and each paired device is then made
433
+ `<PeerListeningSettings listening={...} />` in its `extra` and `certificates` on the desktop and the phone, so the other device's self-signed certificate is reviewed and trusted when pairing first reaches it. A server lets the route through its sign-in
434
+ with `open_paths: ["/api/sync/peer"]`, since every call carries its own seal, and serves `sync_device_methods(sync)` as a call table under `/api/sync/` that only an admin may reach, for the browser's Sync section. Every peer answers over https; a desktop's certificate is its own and self-signed, so the other device's user checks the fingerprint its Sync section shows before trusting it. A restore runs `after_restore: engine.forget_history`, and each paired device is then made
432
435
  to match the restored copy, backing itself up first.
433
436
 
434
437
  ## A pane on the right
@@ -0,0 +1,25 @@
1
+ // X-App's release settings for an X-app's Android package, which x-app-android applies from android/app/build.gradle.
2
+ // CI numbers each build and names it after its version tag, so the phone and Obtainium see it as an update, and signs
3
+ // it when the release key is in the environment; a build without the key stays unsigned.
4
+ android {
5
+ defaultConfig {
6
+ versionCode((System.getenv("ANDROID_VERSION_CODE") ?: "1") as Integer)
7
+ versionName System.getenv("ANDROID_VERSION_NAME") ?: "0.0.0-dev"
8
+ }
9
+ def keystore_file = System.getenv("ANDROID_KEYSTORE_FILE")
10
+ if (keystore_file) {
11
+ signingConfigs {
12
+ release {
13
+ storeFile file(keystore_file)
14
+ storePassword System.getenv("ANDROID_KEYSTORE_PASSWORD")
15
+ keyAlias System.getenv("ANDROID_KEY_ALIAS")
16
+ keyPassword System.getenv("ANDROID_KEYSTORE_PASSWORD")
17
+ }
18
+ }
19
+ buildTypes {
20
+ release {
21
+ signingConfig signingConfigs.release
22
+ }
23
+ }
24
+ }
25
+ }
@@ -98,7 +98,7 @@ export function register_app_calls(api, app, database, changes) {
98
98
  });
99
99
  }
100
100
  // The server's backups and its sync peer's pairings, which only an admin reaches.
101
- const admin_paths = ["/api/backups/", "/api/device/"];
101
+ const admin_paths = ["/api/backups/", "/api/sync/"];
102
102
  export async function build_server(app, options) {
103
103
  const server = fastify({ forceCloseConnections: true });
104
104
  register_lenient_json_body(server);
@@ -138,7 +138,7 @@ export async function build_server(app, options) {
138
138
  return reply.type("application/json").header("cache-control", "no-store").send(JSON.stringify(result));
139
139
  });
140
140
  register_sync_peer_routes(api, options.sync);
141
- register_call_table(api, "/device", sync_device_methods(options.sync), { is_read_only: app.is_read_only });
141
+ register_call_table(api, "/sync", sync_device_methods(options.sync), { is_read_only: app.is_read_only });
142
142
  }, { prefix: "/api" });
143
143
  await register_web_folder(server, { folder: options.web_folder });
144
144
  return server;
@@ -7,7 +7,8 @@ import { LoginNeeded } from "../../web/states.js";
7
7
  // Relative, so a server behind a proxy under a folder keeps it.
8
8
  const call_path = "api/call/";
9
9
  const backups_path = "api/backups/";
10
- const device_path = "api/device/";
10
+ // The server's own sync calls sit beside the route paired devices sync through.
11
+ const device_path = "api/sync/";
11
12
  const events_path = "api/events";
12
13
  const client_id_header = "x-client-id";
13
14
  const reconnect_delay_ms = 5000;
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ export declare const release_line = "apply from: \"../../node_modules/@x-tech-laboratories/x-app/config/android/release.gradle\"";
3
+ export declare function apply_release_settings(app_folder: string): boolean;
4
+ export type RunCapacitor = (app_folder: string, args: string[]) => void;
5
+ export declare function prepare_android(app_folder: string, run?: RunCapacitor): string[];
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ // The `x-app-android [app folder]` command: an app's Android project, made and kept up to date from X-App, so no app
3
+ // keeps Capacitor's generated project by hand. It adds the project from Capacitor's template when the app has none,
4
+ // applies X-App's release settings (the version CI gives each build, and signing when the release key is present),
5
+ // draws the launcher icons from `resources/icon.svg`, and syncs the built page and plugins into it. Run it after the
6
+ // Android page is built, since Capacitor copies that page in.
7
+ // ── Imports ──────────────────────────────────────────────────────────────────
8
+ import { spawnSync } from "node:child_process";
9
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { join, resolve } from "node:path";
11
+ import { write_app_icons } from "./app_icons.js";
12
+ // ── Release settings ─────────────────────────────────────────────────────────
13
+ // The line that applies X-App's release settings, from the app's own node_modules so it follows X-App's version.
14
+ export const release_line = `apply from: "../../node_modules/@x-tech-laboratories/x-app/config/android/release.gradle"`;
15
+ // Adds the release line to the app module's build file once, and says whether it had to.
16
+ export function apply_release_settings(app_folder) {
17
+ const build_file = join(app_folder, "android", "app", "build.gradle");
18
+ const build = readFileSync(build_file, "utf8");
19
+ if (build.includes(release_line))
20
+ return false;
21
+ writeFileSync(build_file, `${build.trimEnd()}\n\n// X-App's release settings: the build's version and, when the key is present, its signature.\n${release_line}\n`);
22
+ return true;
23
+ }
24
+ const run_capacitor = (app_folder, args) => {
25
+ const result = spawnSync("npx", ["cap", ...args], { cwd: app_folder, stdio: "inherit" });
26
+ if (result.status !== 0)
27
+ throw new Error(`cap ${args.join(" ")} failed`);
28
+ };
29
+ // Brings the app's Android project up to date and returns what it did, one line each.
30
+ export function prepare_android(app_folder, run = run_capacitor) {
31
+ if (!existsSync(join(app_folder, "capacitor.config.json")))
32
+ throw new Error(`no Android app: ${join(app_folder, "capacitor.config.json")} is missing`);
33
+ const done = [];
34
+ if (!existsSync(join(app_folder, "android"))) {
35
+ run(app_folder, ["add", "android"]);
36
+ done.push("Added the Android project from Capacitor's template");
37
+ }
38
+ if (apply_release_settings(app_folder))
39
+ done.push("Applied X-App's release settings");
40
+ done.push(`Drew ${write_app_icons(app_folder).length} icons`);
41
+ run(app_folder, ["sync", "android"]);
42
+ done.push("Synced the page and plugins into the Android project");
43
+ return done;
44
+ }
45
+ if (import.meta.main) {
46
+ try {
47
+ for (const line of prepare_android(resolve(process.argv[2] ?? ".")))
48
+ console.info(line);
49
+ }
50
+ catch (error) {
51
+ console.error(error instanceof Error ? error.message : String(error));
52
+ process.exit(1);
53
+ }
54
+ }
package/dist/app_new.js CHANGED
@@ -40,7 +40,7 @@ function package_json(names, options) {
40
40
  ...(options.desktop ? { dev: `${prefix}_USER_DATA=\${${prefix}_USER_DATA:-dev-data/desktop} electron-vite dev -c config/electron.vite.config.ts` } : {}),
41
41
  build: "tsc -b && vite build -c config/vite.config.ts",
42
42
  ...(options.desktop ? { "build:desktop": "tsc -b && electron-vite build -c config/electron.vite.config.ts" } : {}),
43
- ...(options.android ? { "build:android": "tsc -b && vite build -c config/vite.android.config.ts && cap sync android" } : {}),
43
+ ...(options.android ? { "build:android": "tsc -b && vite build -c config/vite.android.config.ts && x-app-android" } : {}),
44
44
  start: "NODE_ENV=production node src/server/main.ts",
45
45
  ...(options.desktop ? { "start:desktop": "electron-vite preview -c config/electron.vite.config.ts" } : {}),
46
46
  typecheck: "tsc -b",
@@ -354,7 +354,8 @@ export default defineConfig(android_vite_config());
354
354
  }
355
355
  : {}),
356
356
  "config.example.json": json({ database: `dev-data/server/${names.short}.db`, backups_folder: "dev-data/server/backups" }),
357
- ".gitignore": [".claude/", "node_modules", "out/", "dist/", "result", "result-*", "*.tsbuildinfo", "dev-data/", "coverage/", ""].join("\n"),
357
+ // The Android project is Capacitor's template that x-app-android makes and keeps up to date, so it is not kept.
358
+ ".gitignore": [".claude/", "node_modules", "out/", "dist/", "result", "result-*", "*.tsbuildinfo", "dev-data/", "coverage/", ...(options.android ? ["android/"] : []), ""].join("\n"),
358
359
  };
359
360
  }
360
361
  function nix_files(names, options) {
@@ -411,13 +412,29 @@ in
411
412
  `,
412
413
  };
413
414
  }
415
+ // Every push to main builds the Android package once the tests pass, signed when the repository holds the release key,
416
+ // and a version tag publishes it as a release.
417
+ const android_job = `
418
+ android:
419
+ needs: ci
420
+ if: github.event_name != 'pull_request'
421
+ runs-on: ubuntu-latest
422
+ permissions:
423
+ contents: write
424
+ steps:
425
+ - uses: x-tech-laboratories/X-App/.github/actions/app-android@main
426
+ with:
427
+ keystore-base64: \${{ secrets.ANDROID_KEYSTORE_BASE64 }}
428
+ keystore-password: \${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
429
+ key-alias: \${{ secrets.ANDROID_KEY_ALIAS }}
430
+ `;
414
431
  function github_files(options) {
415
432
  return {
416
433
  ".github/workflows/ci.yml": `name: CI
417
434
 
418
435
  on:
419
436
  push:
420
- branches: [main]
437
+ branches: [main]${options.android ? '\n tags: ["v*"]' : ""}
421
438
  pull_request:
422
439
  branches: [main]
423
440
  workflow_dispatch:
@@ -435,7 +452,7 @@ jobs:
435
452
  - uses: x-tech-laboratories/X-App/.github/actions/app-nix@main
436
453
  with:
437
454
  targets: ./nix#default${options.desktop ? " ./nix#desktop" : ""}
438
- `,
455
+ ${options.android ? android_job : ""}`,
439
456
  ".github/workflows/dependabot-auto-merge.yml": `name: Dependabot auto-merge
440
457
 
441
458
  on: pull_request
@@ -601,7 +618,7 @@ if (import.meta.main) {
601
618
  console.info(`Wrote ${options.name} into ${folder}. Next:
602
619
  cd ${folder} && git init && npm install
603
620
  nix flake lock ./nix
604
- npm run icons${options.android ? "\n npx cap add android" : ""}
621
+ npm run icons
605
622
  npm test`);
606
623
  }
607
624
  catch (error) {
@@ -0,0 +1,7 @@
1
+ export interface PeerCertificate {
2
+ cert: string;
3
+ key: string;
4
+ fingerprint: string;
5
+ }
6
+ export declare function make_peer_certificate(name: string, addresses: readonly string[]): Promise<PeerCertificate>;
7
+ export declare function read_or_make_peer_certificate(file: string, name: string, addresses: readonly string[]): Promise<PeerCertificate>;
@@ -0,0 +1,46 @@
1
+ // The https certificate a desktop daemon answers paired devices with: self-signed, made once on selfsigned and kept
2
+ // beside the database, so its fingerprint stays the same and a device that trusted it keeps reaching it. Only this user
3
+ // can read the file, since it holds the private key.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { X509Certificate } from "node:crypto";
6
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { hostname } from "node:os";
8
+ import { dirname } from "node:path";
9
+ import { generate } from "selfsigned";
10
+ const valid_years = 10;
11
+ // The names and addresses the certificate covers, so a device reaching one of them sees no wrong-name problem.
12
+ function alt_names(addresses) {
13
+ return [{ type: 2, value: hostname() }, { type: 2, value: `${hostname()}.local` }, { type: 2, value: "localhost" }, ...addresses.map((ip) => ({ type: 7, ip }))];
14
+ }
15
+ export async function make_peer_certificate(name, addresses) {
16
+ const now = new Date();
17
+ const until = new Date(now);
18
+ until.setFullYear(until.getFullYear() + valid_years);
19
+ const made = await generate([{ name: "commonName", value: name }], {
20
+ keyType: "ec",
21
+ curve: "P-256",
22
+ algorithm: "sha256",
23
+ notBeforeDate: now,
24
+ notAfterDate: until,
25
+ extensions: [{ name: "subjectAltName", altNames: alt_names(addresses) }],
26
+ });
27
+ return { cert: made.cert, key: made.private, fingerprint: new X509Certificate(made.cert).fingerprint256 };
28
+ }
29
+ // Reads the kept certificate, or makes and keeps one when there is none or the file is damaged.
30
+ export async function read_or_make_peer_certificate(file, name, addresses) {
31
+ try {
32
+ if (existsSync(file)) {
33
+ const saved = JSON.parse(readFileSync(file, "utf8"));
34
+ if (typeof saved.cert === "string" && typeof saved.key === "string")
35
+ return { cert: saved.cert, key: saved.key, fingerprint: new X509Certificate(saved.cert).fingerprint256 };
36
+ }
37
+ }
38
+ catch {
39
+ // A damaged file is replaced by a new certificate below.
40
+ }
41
+ const made = await make_peer_certificate(name, addresses);
42
+ mkdirSync(dirname(file), { recursive: true });
43
+ writeFileSync(file, JSON.stringify({ cert: made.cert, key: made.key }, null, 2), { mode: 0o600 });
44
+ chmodSync(file, 0o600);
45
+ return made;
46
+ }
@@ -10,11 +10,15 @@ export interface PeerListenerOptions {
10
10
  host?: string;
11
11
  port: number;
12
12
  body_limit?: number;
13
+ https?: {
14
+ cert: string;
15
+ key: string;
16
+ };
13
17
  }
14
18
  export interface PeerListener {
15
19
  close: () => Promise<void>;
16
20
  port: number;
17
21
  addresses: () => string[];
18
22
  }
19
- export declare function reachable_addresses(port: number, interfaces?: NodeJS.Dict<import("os").NetworkInterfaceInfo[]>): string[];
23
+ export declare function reachable_addresses(port: number, interfaces?: NodeJS.Dict<import("os").NetworkInterfaceInfo[]>, scheme?: "http" | "https"): string[];
20
24
  export declare function listen_for_peers(options: PeerListenerOptions): Promise<PeerListener>;
@@ -27,23 +27,24 @@ export function register_sync_peer_routes(app, peer, options = {}) {
27
27
  });
28
28
  }
29
29
  // The computer's own addresses other devices on its networks can reach, leaving out loopback and link-local ones.
30
- export function reachable_addresses(port, interfaces = networkInterfaces()) {
30
+ export function reachable_addresses(port, interfaces = networkInterfaces(), scheme = "http") {
31
31
  const found = [];
32
32
  for (const entries of Object.values(interfaces)) {
33
33
  for (const entry of entries ?? []) {
34
34
  if (entry.internal || (entry.family === "IPv6" && entry.address.toLowerCase().startsWith("fe80")))
35
35
  continue;
36
- found.push(entry.family === "IPv6" ? `http://[${entry.address}]:${port}/` : `http://${entry.address}:${port}/`);
36
+ found.push(entry.family === "IPv6" ? `${scheme}://[${entry.address}]:${port}/` : `${scheme}://${entry.address}:${port}/`);
37
37
  }
38
38
  }
39
39
  return found;
40
40
  }
41
41
  // A desktop daemon's port for other devices, opened only once the user lets other devices connect.
42
42
  export async function listen_for_peers(options) {
43
- const app = fastify({ forceCloseConnections: true });
43
+ const app = fastify({ forceCloseConnections: true, ...(options.https ? { https: options.https } : {}) });
44
44
  await register_open_cors(app, { allowed_headers: sync_peer_headers });
45
45
  register_sync_peer_routes(app, options.peer, { body_limit: options.body_limit });
46
46
  await app.listen({ host: options.host ?? "::", port: options.port });
47
47
  const port = app.server.address().port;
48
- return { close: () => app.close(), port, addresses: () => reachable_addresses(port) };
48
+ const scheme = options.https ? "https" : "http";
49
+ return { close: () => app.close(), port, addresses: () => reachable_addresses(port, networkInterfaces(), scheme) };
49
50
  }
@@ -1,3 +1,4 @@
1
+ import { read_or_make_peer_certificate } from "./peer_certificate.ts";
1
2
  import { listen_for_peers } from "./server/sync_peer_routes.ts";
2
3
  import type { SyncPeer } from "./sync_peer.ts";
3
4
  import { discover_peers } from "./sync_peer_discovery.ts";
@@ -7,8 +8,10 @@ export interface PeerListeningOptions {
7
8
  app: string;
8
9
  file: string;
9
10
  default_port: number;
11
+ certificate_file?: string;
10
12
  listen?: typeof listen_for_peers;
11
13
  discover?: typeof discover_peers;
14
+ certificate?: typeof read_or_make_peer_certificate;
12
15
  }
13
16
  export type PeerListeningControl = ReturnType<typeof keep_listening_for_peers>;
14
17
  export declare function keep_listening_for_peers(options: PeerListeningOptions): {
@@ -1,18 +1,28 @@
1
- // A desktop daemon's "Let other devices connect": off until the user turns it on, then a port of its own that paired
2
- // devices reach it on, announced on the local network. The setting belongs to this computer, so it is kept in a file
3
- // beside the database, never synced. Paired devices are found on the network either way.
1
+ // A desktop daemon's "Let other devices connect": off until the user turns it on, then an https port of its own that
2
+ // paired devices reach it on, announced on the local network, with a self-signed certificate made once, whose fingerprint
3
+ // the Sync section shows so the other device's user can check it before trusting it. The setting belongs to this
4
+ // computer, so it is kept in a file beside the database, never synced. Paired devices are found on the network either way.
4
5
  // ── Imports ──────────────────────────────────────────────────────────────────
5
6
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
- import { dirname } from "node:path";
7
+ import { networkInterfaces } from "node:os";
8
+ import { dirname, join } from "node:path";
9
+ import { read_or_make_peer_certificate } from "./peer_certificate.js";
7
10
  import { listen_for_peers } from "./server/sync_peer_routes.js";
8
11
  import { discover_peers } from "./sync_peer_discovery.js";
9
12
  // ── Listening ────────────────────────────────────────────────────────────────
10
13
  export function keep_listening_for_peers(options) {
11
14
  const listen = options.listen ?? listen_for_peers;
12
15
  const discover = options.discover ?? discover_peers;
16
+ const certificate = options.certificate ?? read_or_make_peer_certificate;
17
+ const certificate_file = options.certificate_file ?? join(dirname(options.file), "sync-certificate.json");
13
18
  let listener = null;
19
+ let fingerprint = "";
14
20
  let discovery = null;
15
21
  let error = "";
22
+ // The computer's own network addresses, for the certificate to cover.
23
+ function local_ip_addresses() {
24
+ return Object.values(networkInterfaces()).flatMap((entries) => (entries ?? []).filter((entry) => !entry.internal).map((entry) => entry.address));
25
+ }
16
26
  // A missing or damaged file reads as off on the default port.
17
27
  function read_saved() {
18
28
  try {
@@ -37,7 +47,9 @@ export function keep_listening_for_peers(options) {
37
47
  error = "";
38
48
  if (saved.on) {
39
49
  try {
40
- listener = await listen({ peer: options.peer(), port: saved.port });
50
+ const own = await certificate(certificate_file, `${options.app} on this computer`, local_ip_addresses());
51
+ fingerprint = own.fingerprint;
52
+ listener = await listen({ peer: options.peer(), port: saved.port, https: { cert: own.cert, key: own.key } });
41
53
  }
42
54
  catch (failure) {
43
55
  error = failure instanceof Error ? failure.message : String(failure);
@@ -50,7 +62,7 @@ export function keep_listening_for_peers(options) {
50
62
  }
51
63
  function get_peer_listening() {
52
64
  const saved = read_saved();
53
- return { ...saved, addresses: addresses(), error };
65
+ return { ...saved, addresses: addresses(), fingerprint, error };
54
66
  }
55
67
  const methods = {
56
68
  get_peer_listening,
@@ -169,6 +169,7 @@ export interface PeerListening {
169
169
  on: boolean;
170
170
  port: number;
171
171
  addresses: string[];
172
+ fingerprint: string;
172
173
  error: string;
173
174
  }
174
175
  export interface PeerListeningMethods {
@@ -1,12 +1,14 @@
1
1
  import { type ReactNode } from "react";
2
+ import type { CertificateClient } from "../../certificate_protocol.ts";
2
3
  import { type PeerListeningClient, type SyncDeviceClient } from "../../sync_protocol.ts";
3
4
  export interface SyncSettingsProps {
4
5
  device: SyncDeviceClient;
5
6
  subscribe?: (listener: () => void) => () => void;
6
7
  data_name?: string;
7
8
  extra?: ReactNode;
9
+ certificates?: CertificateClient;
8
10
  }
9
- export declare function SyncSettings({ device, subscribe, data_name, extra }: SyncSettingsProps): import("react").JSX.Element | null;
11
+ export declare function SyncSettings({ device, subscribe, data_name, extra, certificates }: SyncSettingsProps): import("react").JSX.Element | null;
10
12
  export declare function PeerListeningSettings({ listening }: {
11
13
  listening: PeerListeningClient;
12
14
  }): import("react").JSX.Element | null;
@@ -8,12 +8,24 @@ import { useEffect, useState } from "react";
8
8
  import { format_device_id } from "../../sync_protocol.js";
9
9
  import { describe_error } from "../errors.js";
10
10
  import { StatusPill } from "./badges.js";
11
+ import { offer_certificate_trust } from "./certificates.js";
11
12
  import { Switch } from "./controls.js";
12
13
  import { confirm_dialog, text_dialog } from "./dialog.js";
13
14
  import { SettingRow } from "./layout.js";
14
15
  import { toast } from "./toasts.js";
15
16
  const tones = { off: "none", idle: "good", syncing: "info", offline: "warn", failed: "bad" };
16
17
  const state_text = { off: "Not paired with another device", idle: "Synced", syncing: "Syncing", offline: "Offline", failed: "Failed" };
18
+ // The addresses a pairing code says its device answers at, or none when it is not a whole code; it checks nothing else.
19
+ function addresses_in_pairing_code(code) {
20
+ try {
21
+ const text = code.replace(/\s+/g, "").replace(/^x-sync:/, "").replaceAll("-", "+").replaceAll("_", "/");
22
+ const offer = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(text.padEnd(Math.ceil(text.length / 4) * 4, "=")), (letter) => letter.charCodeAt(0))));
23
+ return Array.isArray(offer.addresses) ? offer.addresses.filter((address) => typeof address === "string") : [];
24
+ }
25
+ catch {
26
+ return [];
27
+ }
28
+ }
17
29
  // Strips what Electron adds in front of an error that crossed from the main process.
18
30
  function error_text(error) {
19
31
  return describe_error(error).replace(/^Error invoking remote method '[^']+': (Error: )?/, "");
@@ -26,7 +38,7 @@ function PeerRow({ peer, on_remove }) {
26
38
  const hint = `${format_device_id(peer.device)} · ${reached} · last synced ${when_text(peer.last_synced_at)}${peer.error ? ` · ${peer.error}` : ""}`;
27
39
  return (_jsxs(SettingRow, { label: peer.name, hint: hint, children: [_jsx(StatusPill, { tone: tones[peer.state], busy: peer.state === "syncing", label: state_text[peer.state] }), _jsx("button", { type: "button", onClick: on_remove, children: "Remove" })] }));
28
40
  }
29
- export function SyncSettings({ device, subscribe, data_name = "data", extra }) {
41
+ export function SyncSettings({ device, subscribe, data_name = "data", extra, certificates }) {
30
42
  const [status, set_status] = useState(null);
31
43
  const [code, set_code] = useState("");
32
44
  const [busy, set_busy] = useState(false);
@@ -44,8 +56,18 @@ export function SyncSettings({ device, subscribe, data_name = "data", extra }) {
44
56
  toast(error_text(error), { tone: "bad" });
45
57
  }
46
58
  }
47
- async function pair(event) {
48
- event.preventDefault();
59
+ // The first https address whose certificate the user trusts after reviewing it, if any.
60
+ async function trusted_after_review() {
61
+ if (!certificates)
62
+ return false;
63
+ for (const address of addresses_in_pairing_code(code).filter((each) => each.startsWith("https:"))) {
64
+ if (await offer_certificate_trust(address, certificates))
65
+ return true;
66
+ }
67
+ return false;
68
+ }
69
+ async function pair(event, is_retry = false) {
70
+ event?.preventDefault();
49
71
  set_busy(true);
50
72
  try {
51
73
  set_status(await device.pair_device(code));
@@ -53,6 +75,8 @@ export function SyncSettings({ device, subscribe, data_name = "data", extra }) {
53
75
  toast(`Paired. The ${data_name} on both devices are merged, the newest change to each winning.`, { tone: "good" });
54
76
  }
55
77
  catch (error) {
78
+ if (!is_retry && (await trusted_after_review()))
79
+ return void (await pair(null, true));
56
80
  toast(error_text(error), { tone: "bad" });
57
81
  }
58
82
  finally {
@@ -92,7 +116,9 @@ export function PeerListeningSettings({ listening }) {
92
116
  }
93
117
  if (!state)
94
118
  return null;
95
- const hint = state.on && state.addresses.length > 0 ? `Paired devices reach this one at ${state.addresses.join(", ")}.` : "Lets paired devices on your networks reach this one, so they sync without a server between them.";
119
+ const reached = state.on && state.addresses.length > 0 ? `Paired devices reach this one at ${state.addresses.join(", ")}.` : "Lets paired devices on your networks reach this one over https, so they sync without a server between them.";
120
+ // The other device asks to trust this one's self-signed certificate once; its fingerprint there should match this one.
121
+ const hint = state.fingerprint ? `${reached} Its certificate's fingerprint is ${state.fingerprint}.` : reached;
96
122
  return (_jsxs(_Fragment, { children: [_jsx(SettingRow, { label: "Let other devices connect", hint: state.error ? `The port could not be opened: ${state.error}` : hint, as_label: true, children: _jsx(Switch, { label: "Let other devices connect", checked: state.on, on_change: (on) => change(on) }) }), _jsx(SettingRow, { label: "Port", hint: "The port other devices connect to.", as_label: true, children: _jsx("input", { type: "number", min: 1, max: 65535, value: port, onChange: (event) => set_port(event.currentTarget.value), onBlur: () => state.on && Number(port) !== state.port && void change(true) }) })] }));
97
123
  }
98
124
  // ── Sidebar button ───────────────────────────────────────────────────────────
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.100.0",
3
+ "version": "0.101.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": {
@@ -18,6 +18,7 @@
18
18
  "android/src/main/"
19
19
  ],
20
20
  "bin": {
21
+ "x-app-android": "dist/app_android.js",
21
22
  "x-app-bundle-migrations": "dist/drizzle_migrations.js",
22
23
  "x-app-check": "dist/change_checks_cli.js",
23
24
  "x-app-icons": "dist/app_icons.js",
@@ -251,6 +252,7 @@
251
252
  "react-error-boundary": "^6.1.6",
252
253
  "react-grid-layout": "^2.3.0",
253
254
  "rrule": "^2.8.1",
255
+ "selfsigned": "^5.5.0",
254
256
  "semver": "^7.8.6",
255
257
  "spdx-satisfies": "^6.0.1",
256
258
  "sshpk": "^1.18.0",