clavarium 0.2.29 → 0.2.30-next.1

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.
@@ -128,9 +128,36 @@ HAND_UNIT="clavarium-network-handover"
128
128
  HAND_WAIT="90"
129
129
  # Where the kernel lists the network devices (a physical one has a "device" link there).
130
130
  SYS_NET="/sys/class/net"
131
+ # THE REMOTE SCREEN (verbs "meshcentral ..."): a self-hosted MeshCentral server (Apache-2.0),
132
+ # OFF by default, turned on from Settings. It is installed in a directory of its own, owned by
133
+ # a dedicated unprivileged account, and run under a hardened unit; it is reached only through
134
+ # the existing front (Caddy), under a path -- no second name and no second certificate. The
135
+ # turn-on (install, which can take minutes, then start) runs in a unit of its own, and the
136
+ # outcome is read back by "meshcentral status".
137
+ # MESH_DATA the install and its data (the account's; npm tree + meshcentral-data)
138
+ # MESH_STATE root's record of the turn-on, read back by "meshcentral status"
139
+ # MESH_USER the dedicated unprivileged account
140
+ # MESH_UNIT / MESH_SETUP_UNIT the server unit; the unit the turn-on runs in
141
+ # MESH_PORT the loopback port it listens on (TLS is done by Caddy in front)
142
+ # MESH_PATH where the front publishes it
143
+ # MESH_VERSION the version pinned (confirmed on a real host; bump here)
144
+ MESH_DATA="/var/lib/clavarium-meshcentral"
145
+ MESH_STATE="/var/lib/clavarium/meshcentral"
146
+ MESH_USER="clavarium-mesh"
147
+ MESH_UNIT="clavarium-meshcentral"
148
+ MESH_SETUP_UNIT="clavarium-meshcentral-setup"
149
+ MESH_PORT="4443"
150
+ MESH_PATH="/meshcentral"
151
+ MESH_VERSION="1.1.35"
152
+ # Node and npm: the release's own if it is there (always present on a server), else the system's.
153
+ MESH_NODE="/opt/clavarium/current/node/bin/node"
154
+ MESH_NPM="/opt/clavarium/current/node/bin/npm"
155
+ # The front's config, and the snippet imported into it for the remote screen's route.
156
+ CADDYFILE="/etc/caddy/Caddyfile"
157
+ MESH_CADDY="/etc/caddy/clavarium-meshcentral.caddy"
131
158
 
132
159
  refuse() { echo "REFUSED: $*" >&2; exit 78; }
133
- usage() { echo "usage: clavarium-host [--say-only [--data DIR] [--mnt DIR]] <vm|shelf|folder|work|view|tools|mounts|operator|machines|disks|net|git|server|update|wifi> <verb> [arguments]" >&2; exit 64; }
160
+ usage() { echo "usage: clavarium-host [--say-only [--data DIR] [--mnt DIR]] <vm|shelf|folder|work|view|tools|mounts|operator|machines|disks|net|git|server|update|wifi|meshcentral> <verb> [arguments]" >&2; exit 64; }
134
161
 
135
162
  SAY="no"; DATA=""; MNT=""; TEST=""
136
163
  while [ $# -gt 0 ]; do
@@ -141,7 +168,8 @@ while [ $# -gt 0 ]; do
141
168
  --test) [ "$(id -u)" != "0" ] || refuse "--test is never for root"; [ "$SAY" = "no" ] || refuse "--test runs for real: not with --say-only"
142
169
  TEST="${2:-}"; case "$TEST" in /*) : ;; *) refuse "--test takes an absolute path" ;; esac
143
170
  DATA="$TEST"; MNT="$TEST"; WIFI_STATE="$TEST/wifi"; NM_KEYFILES="$TEST/system-connections"; WIFI_WAIT="3"; WIFI_UP_WAIT="3"; WIFI_STEP="0.2"
144
- HAND_STATE="$TEST/network"; NETPLAN_DIR="$TEST/netplan"; HAND_WAIT="3"; SYS_NET="$TEST/sys-net"; shift 2 ;;
171
+ HAND_STATE="$TEST/network"; NETPLAN_DIR="$TEST/netplan"; HAND_WAIT="3"; SYS_NET="$TEST/sys-net"
172
+ MESH_DATA="$TEST/mesh"; MESH_STATE="$TEST/meshcentral"; CADDYFILE="$TEST/Caddyfile"; MESH_CADDY="$TEST/clavarium-meshcentral.caddy"; shift 2 ;;
145
173
  *) break ;;
146
174
  esac
147
175
  done
@@ -521,6 +549,137 @@ wifi_record() {
521
549
  mv -f -- "$WIFI_STATE/last.new" "$WIFI_STATE/last"
522
550
  }
523
551
 
552
+ # ---- THE REMOTE SCREEN (MeshCentral) ----
553
+ # Installed: the npm tree and a written config are both there. Running: its unit is active.
554
+ mesh_installed() { [ -f "$MESH_DATA/node_modules/meshcentral/package.json" ] && [ -f "$MESH_DATA/meshcentral-data/config.json" ]; }
555
+ mesh_running() { [ -z "$TEST" ] && systemctl is-active --quiet "$MESH_UNIT.service" 2>/dev/null; }
556
+ # The version as the installed package declares it, or nothing.
557
+ mesh_version() {
558
+ local v
559
+ v="$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([0-9][0-9A-Za-z.+-]*\)".*/\1/p' "$MESH_DATA/node_modules/meshcentral/package.json" 2>/dev/null | head -1 || true)"
560
+ [[ "$v" =~ ^[0-9][0-9A-Za-z.+-]{0,30}$ ]] && printf '%s' "$v" || printf 'none'
561
+ }
562
+ # Where the front publishes it: the front's own name, this path. Just the path when no name is set yet.
563
+ mesh_url() {
564
+ local dom
565
+ dom="$(sed -n 's/^\([A-Za-z0-9][A-Za-z0-9.*-]*\) {[[:space:]]*$/\1/p' "$CADDYFILE" 2>/dev/null | grep -v '^http' | head -1 || true)"
566
+ if [[ "$dom" =~ ^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$ ]]; then printf 'https://%s%s/' "$dom" "$MESH_PATH"; else printf '%s/' "$MESH_PATH"; fi
567
+ }
568
+ # The turn-on's step, read back by "meshcentral status": <step> [<why>].
569
+ mesh_record() {
570
+ install -d -m 0700 "$MESH_STATE"
571
+ { printf 'step %s %s\n' "$1" "$(date +%s)"; [ -z "${2:-}" ] || printf 'why %s\n' "$2"; } > "$MESH_STATE/last.new"
572
+ mv -f -- "$MESH_STATE/last.new" "$MESH_STATE/last"
573
+ }
574
+ mesh_step() { sed -n 's/^step \([a-z-]*\) [0-9]*$/\1/p' "$MESH_STATE/last" 2>/dev/null | head -1 || true; }
575
+ mesh_busy() { [ -z "$TEST" ] && systemctl is-active --quiet "$MESH_SETUP_UNIT.service" 2>/dev/null; }
576
+
577
+ # The route into the front: a snippet of its own, imported once into the site block. Reused on
578
+ # a rerun, never doubled; removed whole when the screen is turned off (an import with no file
579
+ # would stop the front, so the line and the file always go together).
580
+ mesh_caddy_reload() {
581
+ [ -z "$TEST" ] || return 0
582
+ /usr/local/bin/caddy validate --config "$CADDYFILE" >/dev/null 2>&1 || return 1
583
+ systemctl reload caddy.service >/dev/null 2>&1 || systemctl restart caddy.service >/dev/null 2>&1 || true
584
+ }
585
+ mesh_caddy_on() {
586
+ [ -f "$CADDYFILE" ] || return 1
587
+ local tmp; tmp="$(mktemp -p "$(dirname "$MESH_CADDY")" .clavarium-mesh.XXXXXX)" || return 1
588
+ { printf '# Written by Clavarium (Settings, Remote screen). Removed when it is turned off.\n'
589
+ printf 'handle %s* {\n\treverse_proxy 127.0.0.1:%s\n}\n' "$MESH_PATH" "$MESH_PORT"; } > "$tmp"
590
+ [ -n "$TEST" ] || chown root:root -- "$tmp"; chmod 0644 -- "$tmp"; mv -f -- "$tmp" "$MESH_CADDY"
591
+ if ! grep -q '# clavarium-meshcentral$' "$CADDYFILE"; then
592
+ local out; out="$(mktemp -p "$(dirname "$CADDYFILE")" .clavarium-caddy.XXXXXX)" || return 1
593
+ awk 'BEGIN { done = 0 } { print }
594
+ done == 0 && $0 !~ /^http/ && /^[A-Za-z0-9].*\{[[:space:]]*$/ { print "\timport " FULL " # clavarium-meshcentral"; done = 1 }' \
595
+ FULL="$MESH_CADDY" "$CADDYFILE" > "$out" || { rm -f -- "$out"; return 1; }
596
+ cat -- "$out" > "$CADDYFILE"; rm -f -- "$out"
597
+ fi
598
+ mesh_caddy_reload || { mesh_caddy_off; return 1; }
599
+ }
600
+ mesh_caddy_off() {
601
+ rm -f -- "$MESH_CADDY"
602
+ if [ -f "$CADDYFILE" ] && grep -q '# clavarium-meshcentral$' "$CADDYFILE"; then
603
+ local out; out="$(mktemp -p "$(dirname "$CADDYFILE")" .clavarium-caddy.XXXXXX)" || return 1
604
+ grep -v '# clavarium-meshcentral$' "$CADDYFILE" > "$out" || true
605
+ cat -- "$out" > "$CADDYFILE"; rm -f -- "$out"
606
+ fi
607
+ mesh_caddy_reload || true
608
+ }
609
+
610
+ # The config the server is given: TLS is the front's, so it listens plain on the loopback; it
611
+ # makes no certificate of its own and asks Let's Encrypt for none. Written once, kept on a rerun.
612
+ mesh_write_config() {
613
+ install -d -m 0750 "$MESH_DATA/meshcentral-data"
614
+ [ -n "$TEST" ] || chown -R "$MESH_USER:$MESH_USER" "$MESH_DATA/meshcentral-data"
615
+ [ ! -f "$MESH_DATA/meshcentral-data/config.json" ] || return 0
616
+ local tmp; tmp="$(mktemp -p "$MESH_DATA/meshcentral-data" .clavarium-mesh.XXXXXX)" || return 1
617
+ cat > "$tmp" <<MESHCONF
618
+ {
619
+ "__comment": "Written by Clavarium (Settings, Remote screen). TLS and the public name are the front's.",
620
+ "settings": {
621
+ "cert": "localhost",
622
+ "TLSOffload": true,
623
+ "WANproxy": true,
624
+ "Port": $MESH_PORT,
625
+ "RedirPort": 0,
626
+ "ExactPorts": true,
627
+ "AllowFraming": false,
628
+ "SelfUpdate": false
629
+ },
630
+ "domains": {
631
+ "": {
632
+ "certUrl": "https://127.0.0.1:$MESH_PORT/"
633
+ }
634
+ },
635
+ "letsencrypt": null
636
+ }
637
+ MESHCONF
638
+ chmod 0640 -- "$tmp"; [ -n "$TEST" ] || chown "$MESH_USER:$MESH_USER" -- "$tmp"
639
+ mv -f -- "$tmp" "$MESH_DATA/meshcentral-data/config.json"
640
+ }
641
+
642
+ # The hardened unit: a dedicated account, nothing of the system writable but its own data dir,
643
+ # no new privileges, no home, a private /tmp. Written every turn-on (kept in step with this file).
644
+ mesh_write_unit() {
645
+ [ -z "$TEST" ] || return 0
646
+ local node; node="$MESH_NODE"; [ -x "$node" ] || node="$(command -v node || true)"
647
+ [ -n "$node" ] || return 1
648
+ cat > "/etc/systemd/system/$MESH_UNIT.service" <<MESHUNIT
649
+ [Unit]
650
+ Description=Clavarium - the remote screen (MeshCentral), isolated behind the front
651
+ After=network-online.target caddy.service
652
+ Wants=network-online.target
653
+
654
+ [Service]
655
+ User=$MESH_USER
656
+ Group=$MESH_USER
657
+ WorkingDirectory=$MESH_DATA
658
+ ExecStart=$node $MESH_DATA/node_modules/meshcentral --datapath $MESH_DATA/meshcentral-data
659
+ Restart=on-failure
660
+ RestartSec=5
661
+ # Isolation: the whole system read-only but its own data, no new privileges, no home, a private /tmp.
662
+ NoNewPrivileges=yes
663
+ ProtectSystem=strict
664
+ ProtectHome=yes
665
+ PrivateTmp=yes
666
+ ProtectControlGroups=yes
667
+ ProtectKernelModules=yes
668
+ ProtectKernelTunables=yes
669
+ RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
670
+ RestrictSUIDSGID=yes
671
+ LockPersonality=yes
672
+ ReadWritePaths=$MESH_DATA
673
+ # Reached only on the loopback (the front is in front): no low port, no raw network.
674
+ IPAddressAllow=localhost
675
+ IPAddressDeny=any
676
+
677
+ [Install]
678
+ WantedBy=multi-user.target
679
+ MESHUNIT
680
+ systemctl daemon-reload
681
+ }
682
+
524
683
  [ $# -ge 2 ] || usage
525
684
  AREA="$1"; VERB="$2"; shift 2
526
685
 
@@ -1509,6 +1668,143 @@ case "$AREA $VERB" in
1509
1668
  [ "$SAY" = "yes" ] || refuse "unknown verb: git code"
1510
1669
  [ $# -eq 3 ] || usage
1511
1670
  unit_code "$1" "$2" "$3"; exit 0 ;;
1671
+ "meshcentral status")
1672
+ # THE REMOTE SCREEN, for Settings (Remote screen): installed, running, version, url, and
1673
+ # how a turn-on is going. Read-only, nothing asked of the server it runs.
1674
+ # installed <yes|no> running <yes|no> version <x.y.z|none> url <https://.../meshcentral/>
1675
+ # step <installing|starting|running|interrupted|failed> why <a word> (only while or after a turn-on)
1676
+ [ $# -eq 0 ] || usage
1677
+ if [ "$SAY" = "yes" ]; then echo "systemctl is-active $MESH_UNIT; the installed version; the route in $CADDYFILE (read-only)"; exit 0; fi
1678
+ inst=no; mesh_installed && inst=yes
1679
+ up=no; mesh_running && up=yes
1680
+ printf 'installed %s\n' "$inst"
1681
+ printf 'running %s\n' "$up"
1682
+ printf 'version %s\n' "$(mesh_version)"
1683
+ printf 'url %s\n' "$(mesh_url)"
1684
+ step="$(mesh_step)"
1685
+ if [ -n "$step" ]; then
1686
+ # A turn-on cut short (a reboot in its middle): no longer going, and it never finished.
1687
+ if ! mesh_busy && { [ "$step" = "installing" ] || [ "$step" = "starting" ]; }; then step="interrupted"; fi
1688
+ printf 'step %s\n' "$step"
1689
+ why="$(sed -n 's/^why \([a-z-]\{1,20\}\)$/\1/p' "$MESH_STATE/last" 2>/dev/null | head -1 || true)"
1690
+ [ -z "$why" ] || printf 'why %s\n' "$why"
1691
+ fi
1692
+ exit 0 ;;
1693
+ "meshcentral install")
1694
+ # MeshCentral installed into a directory of its own, as a dedicated account: the npm tree
1695
+ # at a pinned version, then its config written (kept on a rerun). Idempotent.
1696
+ [ $# -eq 0 ] || usage
1697
+ if [ "$SAY" = "yes" ]; then
1698
+ printf '%s\n' "useradd --system $MESH_USER" "install -d $MESH_DATA" \
1699
+ "npm install --prefix $MESH_DATA --omit=dev meshcentral@$MESH_VERSION" \
1700
+ "write $MESH_DATA/meshcentral-data/config.json"
1701
+ exit 0
1702
+ fi
1703
+ install -d -m 0700 "$MESH_STATE"
1704
+ id "$MESH_USER" >/dev/null 2>&1 || useradd --system --home-dir "$MESH_DATA" --no-create-home --shell /usr/sbin/nologin "$MESH_USER"
1705
+ install -d -o "$MESH_USER" -g "$MESH_USER" -m 0750 "$MESH_DATA"
1706
+ npm="$MESH_NPM"; [ -x "$npm" ] || npm="$(command -v npm || true)"
1707
+ [ -n "$npm" ] || refuse "there is no npm on this server to install the remote screen"
1708
+ # No secret is printed: npm's own output (and only it) goes to a root-only log.
1709
+ if ! HOME="$MESH_DATA" npm_config_cache="$MESH_DATA/.npm" "$npm" install --prefix "$MESH_DATA" \
1710
+ --no-save --no-audit --no-fund --omit=dev "meshcentral@$MESH_VERSION" > "$MESH_STATE/install.log" 2>&1; then
1711
+ refuse "MeshCentral could not be installed (see $MESH_STATE/install.log on the server)"
1712
+ fi
1713
+ [ -f "$MESH_DATA/node_modules/meshcentral/package.json" ] || refuse "MeshCentral was not installed as expected"
1714
+ mesh_write_config || refuse "the remote screen's config could not be written"
1715
+ chown -R "$MESH_USER:$MESH_USER" "$MESH_DATA"
1716
+ printf 'installed %s\n' "$(mesh_version)"
1717
+ exit 0 ;;
1718
+ "meshcentral start")
1719
+ # The hardened unit written and enabled, the server started, and the route added to the
1720
+ # front (Caddy reloaded). Idempotent: a rerun rewrites the unit and the route as they are.
1721
+ [ $# -eq 0 ] || usage
1722
+ if [ "$SAY" = "yes" ]; then
1723
+ printf '%s\n' "write /etc/systemd/system/$MESH_UNIT.service (hardened: $MESH_USER, NoNewPrivileges, ProtectSystem=strict, ProtectHome, PrivateTmp, its own data dir)" \
1724
+ "systemctl enable --now $MESH_UNIT.service" \
1725
+ "add 'import $MESH_CADDY' to the site in $CADDYFILE; caddy validate; systemctl reload caddy"
1726
+ exit 0
1727
+ fi
1728
+ mesh_installed || refuse "the remote screen is not installed yet"
1729
+ mesh_write_unit || refuse "the remote screen's unit could not be written (no node found?)"
1730
+ systemctl enable --quiet "$MESH_UNIT.service" >/dev/null 2>&1 || true
1731
+ systemctl restart "$MESH_UNIT.service" || refuse "the remote screen did not start (journalctl -u $MESH_UNIT)"
1732
+ mesh_caddy_on || refuse "the route to the remote screen could not be added to the front"
1733
+ printf 'started %s\n' "$(mesh_url)"
1734
+ exit 0 ;;
1735
+ "meshcentral stop")
1736
+ # The route removed from the front (Caddy reloaded) and the unit stopped and disabled.
1737
+ # What was installed is kept. Idempotent: safe to run when it is off already.
1738
+ [ $# -eq 0 ] || usage
1739
+ if [ "$SAY" = "yes" ]; then
1740
+ printf '%s\n' "remove 'import $MESH_CADDY' from $CADDYFILE; rm $MESH_CADDY; systemctl reload caddy" \
1741
+ "systemctl disable --now $MESH_UNIT.service"
1742
+ exit 0
1743
+ fi
1744
+ mesh_caddy_off
1745
+ systemctl disable --quiet "$MESH_UNIT.service" >/dev/null 2>&1 || true
1746
+ systemctl stop "$MESH_UNIT.service" >/dev/null 2>&1 || true
1747
+ systemctl reset-failed "$MESH_UNIT.service" >/dev/null 2>&1 || true
1748
+ echo "stopped"
1749
+ exit 0 ;;
1750
+ "meshcentral enable")
1751
+ # TURNED ON from Settings: install (minutes, the first time) then start, in a unit of its
1752
+ # own, and this returns at once ("enabling"). The outcome is read back by "meshcentral status".
1753
+ [ $# -eq 0 ] || usage
1754
+ if [ "$SAY" = "yes" ]; then echo "systemd-run --unit=$MESH_SETUP_UNIT --collect clavarium-host meshcentral setup (install, then start)"; exit 0; fi
1755
+ ! mesh_busy || refuse "the remote screen is being turned on already: wait for its end"
1756
+ mesh_record installing
1757
+ self=(/bin/bash "$(readlink -f -- "$0")"); [ -z "$TEST" ] || self+=(--test "$TEST")
1758
+ if ! systemd-run --quiet --unit="$MESH_SETUP_UNIT" --collect --description="Clavarium - turning on the remote screen (install, then start)" \
1759
+ --property=TimeoutStartSec=0 "${self[@]}" meshcentral setup; then
1760
+ mesh_record failed start
1761
+ refuse "the turn-on could not be started (another one still running?)"
1762
+ fi
1763
+ echo "enabling"
1764
+ exit 0 ;;
1765
+ "meshcentral setup")
1766
+ # THE TURN-ON ITSELF, run by "meshcentral enable" in its unit, as root: install if it is
1767
+ # not installed, then start; each step recorded for "meshcentral status".
1768
+ [ $# -eq 0 ] || usage
1769
+ if [ "$SAY" = "yes" ]; then echo "see: meshcentral enable"; exit 0; fi
1770
+ [ "$(mesh_step)" = "installing" ] || refuse "no turn-on was asked"
1771
+ self=(/bin/bash "$(readlink -f -- "$0")"); [ -z "$TEST" ] || self+=(--test "$TEST")
1772
+ if ! mesh_installed; then
1773
+ if ! "${self[@]}" meshcentral install >/dev/null 2>&1; then mesh_record failed install; exit 0; fi
1774
+ fi
1775
+ mesh_record starting
1776
+ if ! "${self[@]}" meshcentral start >/dev/null 2>&1; then mesh_record failed start; exit 0; fi
1777
+ mesh_record running
1778
+ exit 0 ;;
1779
+ "meshcentral disable")
1780
+ # TURNED OFF from Settings: stopped and its route removed (what was installed is kept).
1781
+ [ $# -eq 0 ] || usage
1782
+ if [ "$SAY" = "yes" ]; then echo "see: meshcentral stop"; exit 0; fi
1783
+ ! mesh_busy || refuse "the remote screen is being turned on: wait for its end"
1784
+ self=(/bin/bash "$(readlink -f -- "$0")"); [ -z "$TEST" ] || self+=(--test "$TEST")
1785
+ "${self[@]}" meshcentral stop >/dev/null 2>&1 || true
1786
+ mesh_record idle
1787
+ echo "disabled"
1788
+ exit 0 ;;
1789
+ "meshcentral uninstall")
1790
+ # EVERYTHING REMOVED: stopped, its route and unit gone, its data dir and account removed.
1791
+ [ $# -eq 0 ] || usage
1792
+ if [ "$SAY" = "yes" ]; then
1793
+ printf '%s\n' "systemctl disable --now $MESH_UNIT; rm the unit; remove the route" \
1794
+ "rm -rf $MESH_DATA; userdel $MESH_USER"
1795
+ exit 0
1796
+ fi
1797
+ ! mesh_busy || refuse "the remote screen is being turned on: wait for its end"
1798
+ mesh_caddy_off
1799
+ systemctl disable --quiet "$MESH_UNIT.service" >/dev/null 2>&1 || true
1800
+ systemctl stop "$MESH_UNIT.service" >/dev/null 2>&1 || true
1801
+ systemctl reset-failed "$MESH_UNIT.service" >/dev/null 2>&1 || true
1802
+ rm -f -- "/etc/systemd/system/$MESH_UNIT.service"; systemctl daemon-reload >/dev/null 2>&1 || true
1803
+ rm -rf -- "$MESH_DATA"
1804
+ ! id "$MESH_USER" >/dev/null 2>&1 || userdel "$MESH_USER" >/dev/null 2>&1 || true
1805
+ rm -f -- "$MESH_STATE/last"
1806
+ echo "uninstalled"
1807
+ exit 0 ;;
1512
1808
  *)
1513
1809
  refuse "unknown verb: $AREA $VERB" ;;
1514
1810
  esac
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.29",
3
+ "version": "0.2.30-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.29",
9
+ "version": "0.2.30-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.29",
3
+ "version": "0.2.30-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
package/server/api.mjs CHANGED
@@ -87,6 +87,7 @@
87
87
  * POST /api/wifi/join {ssid, password}: the switch started, back by itself if it does not work
88
88
  * POST /api/wifi/forget {ssid}: a kept network deleted (never the one in use)
89
89
  * POST /api/wifi/handover: the network handed over to NetworkManager (back as it was if it does not work)
90
+ * GET /api/meshcentral: the remote screen (MeshCentral); POST /api/meshcentral/enable (turned on, in the background) /disable
90
91
  * GET /api/events?kind=&conversation=&q=&before=&limit= what happened, newest first
91
92
  * GET /api/history?of=server|<name>&span=1h|24h|7d the curves of memory, CPU and disk (and the reserve, for the server)
92
93
  * GET /api/server/logs?source=&span= what the server's programs said POST /api/server/restart
@@ -145,7 +146,7 @@ function readBody(request, max = BODY_MAX) {
145
146
  }
146
147
 
147
148
  /* Returns true when the request was an API request (answered here). */
148
- export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders) {
149
+ export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral) {
149
150
  const { pathname } = new URL(request.url ?? '/', 'http://local');
150
151
  if (!pathname.startsWith('/api/')) return false;
151
152
  let send = (status, body) => {
@@ -282,6 +283,7 @@ export async function handleApi(request, response, conversations, headers, resou
282
283
  if (pathname === '/api/machines/moving' && machinesMove) return send(200, await machinesMove.moving()), true;
283
284
  if (pathname === '/api/wifi' && wifi) return send(200, await wifi.status()), true;
284
285
  if (pathname === '/api/wifi/scan' && wifi) return send(200, await wifi.scan()), true;
286
+ if (pathname === '/api/meshcentral' && meshcentral) return send(200, await meshcentral.status()), true;
285
287
  if (pathname === '/api/operators') return send(200, team ? { operators: team.list(), me: identity } : { local: true }), true;
286
288
  if (pathname === '/api/binder/people' && binders) return send(200, { people: binders.people(identity), changes: binders.changes() }), true;
287
289
  if (pathname === '/api/certificate' && certificate) return send(200, await certificate.about({ fresh: query.get('fresh') === '1' })), true;
@@ -422,6 +424,8 @@ export async function handleApi(request, response, conversations, headers, resou
422
424
  if (pathname === '/api/wifi/join' && wifi) return send(202, await wifi.join(body.ssid, body.password ?? '')), true;
423
425
  if (pathname === '/api/wifi/forget' && wifi) return send(200, await wifi.forget(body.ssid)), true;
424
426
  if (pathname === '/api/wifi/handover' && wifi) return send(202, await wifi.handover()), true;
427
+ if (pathname === '/api/meshcentral/enable' && meshcentral) return send(202, await meshcentral.enable()), true;
428
+ if (pathname === '/api/meshcentral/disable' && meshcentral) return send(200, await meshcentral.disable()), true;
425
429
  if (pathname === '/api/operators' && team) return send(201, await team.add(body.email)), true;
426
430
  const op = /^\/api\/operators\/([^/]{3,200})\/(password|disable|enable|remove)$/.exec(pathname);
427
431
  if (op && team) {
package/server/main.mjs CHANGED
@@ -64,6 +64,7 @@ import { HealthReact } from './healthreact.mjs';
64
64
  import { HealthDocket } from './healthdocket.mjs';
65
65
  import { MachinesMove } from './machinesmove.mjs';
66
66
  import { Wifi } from './wifi.mjs';
67
+ import { MeshCentral } from './meshcentral.mjs';
67
68
  import { Binders } from './binders.mjs';
68
69
  import { ServerLogs } from './serverlogs.mjs';
69
70
  import { History, STEP_MS as HISTORY_STEP_MS } from './history.mjs';
@@ -153,7 +154,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
153
154
 
154
155
  const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
155
156
 
156
- function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders } = {}) {
157
+ function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral } = {}) {
157
158
  /* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
158
159
  const sendManifest = (response, url) => response.writeHead(200, { ...HEADERS, 'content-type': 'application/manifest+json' }).end(instance.manifest(new URL(url ?? '/', 'http://local').searchParams.get('name') ?? undefined));
159
160
  const sendFile = async (response, file) => {
@@ -196,7 +197,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
196
197
  response.writeHead(403, { ...HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
197
198
  return;
198
199
  }
199
- if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders)) return;
200
+ if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral)) return;
200
201
  if (pathname === '/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
201
202
  const file = FILES[pathname];
202
203
  if (!file || (request.method !== 'GET' && request.method !== 'HEAD')) {
@@ -491,12 +492,14 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
491
492
  const serverLogs = new ServerLogs({ host: asHost });
492
493
  /* This server's Wi-Fi, from Settings (wifi.mjs): how a switch ended, said in What happened. */
493
494
  const wifi = new Wifi({ host: asHost, said: (text) => events.add({ kind: 'server', text }) });
495
+ /* The remote screen (MeshCentral), from Settings (meshcentral.mjs): how a turn-on ended, said in What happened. */
496
+ const meshcentral = new MeshCentral({ host: asHost, said: (text) => events.add({ kind: 'server', text }) });
494
497
  if (team) {
495
498
  team.useAlerts(alerts);
496
499
  void team.refresh().catch((error) => console.error(`operators: ${error.message}`));
497
500
  const watching = setInterval(() => { void team.watch().catch(() => {}); }, 60_000); watching.unref?.();
498
501
  }
499
- const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
502
+ const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
500
503
  server.on('close', () => { closing = true; stopBinders(); clearInterval(historyTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
501
504
  let closing = false;
502
505
  bridge = attachBridge(server, {
@@ -0,0 +1,86 @@
1
+ /* THE REMOTE SCREEN (MeshCentral), from Settings (Remote screen): a self-hosted MeshCentral
2
+ * server (Apache-2.0), OFF by default, turned on in a few clicks. All of it is done by the host
3
+ * program as root (deploy/clavarium-host, verbs "meshcentral ..."): MeshCentral is installed in a
4
+ * directory of its own, run under a hardened unit as a dedicated unprivileged account, and reached
5
+ * only through the existing front (Caddy) under a path. This module drives that lifecycle; it does
6
+ * NOT drive the screen (that is the separate screen connector).
7
+ *
8
+ * Turning it on installs MeshCentral the first time, which can take minutes: the turn-on runs in a
9
+ * unit of the host's own and this returns at once, so the page shows its progress and the outcome
10
+ * is read back from status().
11
+ *
12
+ * status() { installed, running, version, url, step, why, on }
13
+ * step (only while or after a turn-on): installing, starting, running, interrupted, failed, idle
14
+ * enable() the turn-on started: { started: true }; the page follows it with status()
15
+ * disable() stopped and its route removed, what was installed kept: { disabled: true }
16
+ */
17
+ import { Refusal } from './conversations.mjs';
18
+
19
+ const firstLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).pop()?.replace(/^REFUSED: /, '').slice(0, 200) ?? '';
20
+ const STEPS = ['installing', 'starting', 'running', 'interrupted', 'failed', 'idle'];
21
+ /* After a turn-on, the outcome is looked for this often and this long, to be said once in What happened. */
22
+ const WATCH_EVERY_MS = 5000;
23
+ const WATCH_FOR_MS = 30 * 60_000;
24
+
25
+ /* "meshcentral status", line by line: only the lines of the expected shapes. */
26
+ export function readStatus(text) {
27
+ const out = { installed: false, running: false, version: null, url: null, step: null, why: null };
28
+ for (const line of String(text ?? '').split('\n').slice(0, 50)) {
29
+ const word = line.split(' ', 1)[0]; const rest = line.slice(word.length + 1);
30
+ if (word === 'installed') out.installed = rest === 'yes';
31
+ else if (word === 'running') out.running = rest === 'yes';
32
+ else if (word === 'version' && /^[0-9][0-9A-Za-z.+-]{0,30}$/.test(rest)) out.version = rest;
33
+ else if (word === 'url' && /^(https:\/\/[A-Za-z0-9.-]{1,255})?\/[A-Za-z0-9/._-]{0,64}$/.test(rest)) out.url = rest;
34
+ else if (word === 'step' && STEPS.includes(rest)) out.step = rest;
35
+ else if (word === 'why' && /^[a-z-]{1,20}$/.test(rest)) out.why = rest;
36
+ }
37
+ out.on = out.running;
38
+ return out;
39
+ }
40
+
41
+ export class MeshCentral {
42
+ #host; #said; #watching = null; #everyMs; #forMs;
43
+ /* `said(text)`: an outcome, in What happened (events.mjs). */
44
+ constructor({ host, said = () => {}, watchEveryMs = WATCH_EVERY_MS, watchForMs = WATCH_FOR_MS }) {
45
+ this.#host = host; this.#said = said; this.#everyMs = watchEveryMs; this.#forMs = watchForMs;
46
+ }
47
+ async status() {
48
+ const r = await this.#host(['meshcentral', 'status'], { timeoutMs: 30_000 });
49
+ if (r.code !== 0) return { ...readStatus(''), step: null, why: null, said: firstLine(r.stderr) || `exit ${r.code}` };
50
+ return readStatus(r.stdout);
51
+ }
52
+ async enable() {
53
+ const r = await this.#host(['meshcentral', 'enable'], { timeoutMs: 60_000 });
54
+ if (r.code !== 0) throw new Refusal(r.code === 78 ? 409 : 502, firstLine(r.stderr) || `exit ${r.code}`);
55
+ this.#watch();
56
+ return { started: true };
57
+ }
58
+ async disable() {
59
+ const r = await this.#host(['meshcentral', 'disable'], { timeoutMs: 120_000 });
60
+ if (r.code !== 0) throw new Refusal(r.code === 78 ? 409 : 502, firstLine(r.stderr) || `exit ${r.code}`);
61
+ return { disabled: true };
62
+ }
63
+ /* The outcome, said once in What happened, whoever looks at the page: the turn-on goes on in
64
+ its own unit, so it ends even if no page is there to see it. */
65
+ #watch() {
66
+ clearTimeout(this.#watching);
67
+ const until = Date.now() + this.#forMs;
68
+ const look = async () => {
69
+ const s = await this.status().catch(() => null);
70
+ const step = s?.step;
71
+ if (step && !['installing', 'starting'].includes(step)) {
72
+ this.#watching = null;
73
+ const why = { install: 'could not install', start: 'did not start' }[s?.why] ?? s?.why ?? 'no reason given';
74
+ const words = {
75
+ running: `Remote screen: on now${s?.url ? ` at ${s.url}` : ''}`,
76
+ failed: `Remote screen: did not turn on (${why})`,
77
+ interrupted: 'Remote screen: the turn-on was interrupted',
78
+ };
79
+ try { this.#said(words[step] ?? `Remote screen: ${step}`); } catch { /* never in the way */ }
80
+ return;
81
+ }
82
+ if (Date.now() < until) { this.#watching = setTimeout(look, this.#everyMs); this.#watching.unref?.(); }
83
+ };
84
+ this.#watching = setTimeout(look, this.#everyMs); this.#watching.unref?.();
85
+ }
86
+ }
package/web/app.js CHANGED
@@ -4490,6 +4490,7 @@
4490
4490
  $('settings-about').textContent = `Clavarium ${platform.version ?? ''}`;
4491
4491
  void paintInstance();
4492
4492
  if ($('settings-wifi-top').open) void paintWifi();
4493
+ if ($('settings-mesh-top').open) void paintScreen();
4493
4494
  await Promise.all([paintHosts(), paintShelf(), paintServer(), paintUpdates()]);
4494
4495
  }
4495
4496
 
@@ -5096,6 +5097,41 @@
5096
5097
  $('wifi-join-error').textContent = error.message; $('wifi-join-error').hidden = false; $('wifi-join-go').disabled = false;
5097
5098
  });
5098
5099
  });
5100
+ /* ---------- Remote screen, in Settings: a self-hosted MeshCentral (server/meshcentral.mjs) ----------
5101
+ OFF by default. Turning it on installs it (minutes, the first time) then starts it, in the background:
5102
+ its progress is shown and the outcome read back from status(). */
5103
+ let meshTimer;
5104
+ async function paintScreen() {
5105
+ clearTimeout(meshTimer);
5106
+ const s = await fetch(`${API}/meshcentral`, { cache: 'no-store' }).then((r) => (r.ok ? r.json() : null)).catch(() => null);
5107
+ const line = $('mesh-line'); const state = $('mesh-state'); const toggle = $('mesh-toggle');
5108
+ const url = $('mesh-url'); const progress = $('mesh-progress');
5109
+ if (!s) { state.textContent = 'State cannot be read just now.'; line.dataset.tone = 'warn'; toggle.hidden = true; url.hidden = true; progress.hidden = true; return; }
5110
+ const turningOn = ['installing', 'starting'].includes(s.step);
5111
+ /* One short line of state. */
5112
+ state.textContent = turningOn ? 'Turning on...' : s.running ? 'On' : s.step === 'failed' ? 'Off (turn-on failed)' : s.installed ? 'Installed, off' : 'Off';
5113
+ line.dataset.tone = s.running ? 'ok' : s.step === 'failed' ? 'bad' : turningOn ? 'warn' : '';
5114
+ /* On: its address. */
5115
+ if (s.running && s.url) { url.replaceChildren('At ', el('a', '', s.url)); const a = url.querySelector('a'); a.href = s.url; a.target = '_blank'; a.rel = 'noreferrer'; url.hidden = false; }
5116
+ else url.hidden = true;
5117
+ /* Turning on: install can take a while; the page keeps watching. */
5118
+ progress.textContent = turningOn ? (s.step === 'installing' ? 'Installing, this can take a few minutes...' : 'Starting...') : '';
5119
+ progress.hidden = !turningOn;
5120
+ toggle.hidden = false; toggle.disabled = turningOn;
5121
+ toggle.textContent = turningOn ? 'Turning on...' : s.running ? 'Turn off' : 'Turn on';
5122
+ toggle.dataset.on = s.running ? 'yes' : '';
5123
+ if (turningOn && $('settings-mesh-top').open && !$('settings').hidden) meshTimer = setTimeout(() => { void paintScreen(); }, 4000);
5124
+ }
5125
+ $('settings-mesh-top').addEventListener('toggle', () => { if ($('settings-mesh-top').open) void paintScreen(); else clearTimeout(meshTimer); });
5126
+ $('mesh-toggle').addEventListener('click', () => {
5127
+ const toggle = $('mesh-toggle'); const on = toggle.dataset.on === 'yes';
5128
+ $('mesh-error').hidden = true;
5129
+ toggle.disabled = true;
5130
+ const path = on ? `${API}/meshcentral/disable` : `${API}/meshcentral/enable`;
5131
+ void post(path, {}).then(() => { void paintScreen(); }).catch((error) => {
5132
+ $('mesh-error').textContent = error.message; $('mesh-error').hidden = false; toggle.disabled = false;
5133
+ });
5134
+ });
5099
5135
  /* WHAT HAPPENED: newest first, a page at a time; chosen by kind, searched. */
5100
5136
  const EVENT_WORDS = { conversation: 'Conversation', machine: 'Machine', access: 'Access', asset: 'Asset', update: 'Update', server: 'Server', 'sign-in': 'Sign-in' };
5101
5137
  let eventsShown = []; let eventsAsk = 0;
package/web/index.html CHANGED
@@ -689,6 +689,20 @@
689
689
  </div>
690
690
  </div>
691
691
  </details>
692
+ <!-- REMOTE SCREEN: a self-hosted MeshCentral (server/meshcentral.mjs), OFF by default. Installed,
693
+ run isolated under a hardened unit, and reached only through the front (Caddy) by the host program. -->
694
+ <details class="chapter" id="settings-mesh-top" data-chapter="s-remote-screen">
695
+ <summary><span class="chapter-title">Remote screen</span><span class="chapter-about">See a screen remotely.</span></summary>
696
+ <div class="chapter-body">
697
+ <div id="mesh" tabindex="-1">
698
+ <div class="set-row mesh-head"><div class="status-line" id="mesh-line" role="status"><span id="mesh-state"></span></div><div class="set-control"><button type="button" class="primary" id="mesh-toggle"></button></div></div>
699
+ <div class="set-row"><div class="set-what"><span>MeshCentral</span><small>A screen reached through this server, off unless on</small></div></div>
700
+ <p id="mesh-url" class="hint" hidden></p>
701
+ <p id="mesh-progress" class="hint" role="status" hidden></p>
702
+ <p id="mesh-error" class="error" role="alert" hidden></p>
703
+ </div>
704
+ </div>
705
+ </details>
692
706
  <details class="chapter" id="settings-updates-top" data-chapter="s-updates">
693
707
  <summary><span class="chapter-title">Updates</span><span class="chapter-about">Version and updates.</span></summary>
694
708
  <div class="chapter-body">