clavarium 0.2.236-next.1 → 0.2.237-beta.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.
Files changed (104) hide show
  1. package/config/launch/claude-code.sh +40 -19
  2. package/config/launch/codex.sh +37 -0
  3. package/config/launch/json-set.mjs +5 -2
  4. package/config/launch/mcp-relay.mjs +98 -0
  5. package/config/launch/mcp-sock.sh +31 -0
  6. package/config/launch/screen-watch.mjs +173 -0
  7. package/config/launch/toml-block.mjs +26 -0
  8. package/config/launch/tools-host.mjs +93 -0
  9. package/config/launch/vibe.sh +40 -0
  10. package/config/machine/clavarium-beat +44 -0
  11. package/config/machine/clavarium-beat-one +40 -0
  12. package/config/machine/clavarium-enter +60 -0
  13. package/config/tools.json +170 -12
  14. package/deploy/clavarium-host +385 -31
  15. package/deploy/clavarium-tunnel +14 -3
  16. package/deploy/clavarium.mjs +4 -0
  17. package/deploy/git-read +57 -5
  18. package/deploy/install.sh +11 -5
  19. package/deploy/maintenance.html +5 -2
  20. package/deploy/online.mjs +251 -8
  21. package/deploy/relay.sh +53 -27
  22. package/deploy/tunnel.mjs +7 -5
  23. package/deploy/updater.mjs +168 -25
  24. package/npm-shrinkwrap.json +245 -19
  25. package/package.json +9 -6
  26. package/server/agenda.mjs +140 -0
  27. package/server/api.mjs +392 -28
  28. package/server/apikeys.mjs +1372 -0
  29. package/server/beat.mjs +189 -0
  30. package/server/binders.mjs +42 -0
  31. package/server/boxcollect.mjs +276 -0
  32. package/server/boxes.mjs +348 -29
  33. package/server/bridge.mjs +13 -4
  34. package/server/browsers.mjs +364 -0
  35. package/server/capacity.mjs +37 -10
  36. package/server/carry.mjs +143 -0
  37. package/server/catalog.mjs +48 -0
  38. package/server/contactview.mjs +122 -0
  39. package/server/conversations.mjs +1122 -46
  40. package/server/copywork.mjs +34 -0
  41. package/server/demandes.mjs +251 -0
  42. package/server/desktop.mjs +102 -0
  43. package/server/devices.mjs +1 -0
  44. package/server/dictation-engines.mjs +91 -0
  45. package/server/dockets.mjs +49 -6
  46. package/server/door.mjs +19 -5
  47. package/server/events.mjs +3 -0
  48. package/server/features.mjs +366 -0
  49. package/server/files.mjs +43 -1
  50. package/server/gitaccess.mjs +12 -3
  51. package/server/gitchecks.mjs +17 -3
  52. package/server/gitkeeper.mjs +45 -10
  53. package/server/gitpush.mjs +286 -71
  54. package/server/gitrunner.mjs +144 -10
  55. package/server/grants.mjs +47 -11
  56. package/server/guide.mjs +31 -10
  57. package/server/health.mjs +138 -12
  58. package/server/jobs.mjs +138 -0
  59. package/server/linkguard.mjs +191 -0
  60. package/server/machinelist.mjs +58 -0
  61. package/server/mailref.mjs +90 -0
  62. package/server/mailview.mjs +204 -0
  63. package/server/main.mjs +425 -47
  64. package/server/mcpoauth.mjs +338 -0
  65. package/server/mcpx.mjs +175 -0
  66. package/server/network.mjs +125 -13
  67. package/server/profile.mjs +129 -0
  68. package/server/relayjoin.mjs +67 -0
  69. package/server/resources.mjs +6 -0
  70. package/server/revive.mjs +70 -0
  71. package/server/rooms.mjs +462 -0
  72. package/server/secrets.mjs +25 -12
  73. package/server/serverlogs.mjs +30 -4
  74. package/server/settingswords.mjs +375 -0
  75. package/server/signinhelp.mjs +239 -0
  76. package/server/speech.mjs +40 -4
  77. package/server/spoken.mjs +60 -0
  78. package/server/sshconsole.mjs +99 -0
  79. package/server/sshmachine.mjs +76 -0
  80. package/server/store.mjs +15 -1
  81. package/server/suggest.mjs +66 -0
  82. package/server/talk.mjs +228 -55
  83. package/server/tethers.mjs +223 -13
  84. package/server/toolbox.mjs +30 -7
  85. package/server/tools.mjs +38 -6
  86. package/server/updates.mjs +7 -2
  87. package/server/vm.mjs +215 -46
  88. package/server/vmwatch.mjs +82 -23
  89. package/server/voice.mjs +183 -51
  90. package/server/wakelearn.mjs +214 -0
  91. package/server/wakeups.mjs +42 -2
  92. package/server/watchdog.mjs +102 -0
  93. package/web/app.js +5590 -1237
  94. package/web/desk.js +531 -0
  95. package/web/device.html +15 -2
  96. package/web/features.js +480 -0
  97. package/web/index.html +874 -490
  98. package/web/kit.js +1142 -0
  99. package/web/links.js +2 -2
  100. package/web/mail-view.js +386 -0
  101. package/web/manifest.webmanifest +4 -0
  102. package/web/style.css +1592 -268
  103. package/web/voice-core.js +48 -0
  104. package/web/voice.js +13 -5
@@ -4,7 +4,13 @@
4
4
  # written by install.sh and kept up to date by the updater). Root installs it at
5
5
  # /usr/local/sbin/clavarium-tunnel; it runs as the clavarium-tunnel account.
6
6
  #
7
- # clavarium-tunnel RELAY PORT
7
+ # clavarium-tunnel RELAY PORT [TLS-PORT HTTP-PORT]
8
+ #
9
+ # WITHOUT TLS-PORT AND HTTP-PORT: the relay's first home (its principal), on
10
+ # 8443 and 8080, held on every address of the relay, as it always was. WITH
11
+ # THEM: a home the principal added (clavarium-relay add-home), on the ports it
12
+ # was given, held on the relay's 127.0.0.1 only -- its router alone reaches
13
+ # them, and the relay lets this key hold no other port.
8
14
  #
9
15
  # A CUT OF THE NETWORK is noticed in 20 to 30 seconds (a keepalive every 10 s,
10
16
  # two missed), and the tunnel is tried again 5 s later by systemd, as long as it
@@ -17,8 +23,13 @@
17
23
  # the count starts over.
18
24
  # ---------------------------------------------------------------------------
19
25
  set -u
20
- [ $# -eq 2 ] || { echo "usage: clavarium-tunnel RELAY PORT" >&2; exit 64; }
26
+ [ $# -eq 2 ] || [ $# -eq 4 ] || { echo "usage: clavarium-tunnel RELAY PORT [TLS-PORT HTTP-PORT]" >&2; exit 64; }
21
27
  relay="$1"; port="$2"
28
+ forwards=(-R '*:8443:127.0.0.1:443' -R '*:8080:127.0.0.1:80')
29
+ if [ $# -eq 4 ]; then
30
+ for p in "$3" "$4"; do [[ "$p" =~ ^[0-9]{4,5}$ ]] && [ "$p" -le 65535 ] || { echo "clavarium-tunnel: not a port: $p" >&2; exit 64; }; done
31
+ forwards=(-R "127.0.0.1:$3:127.0.0.1:443" -R "127.0.0.1:$4:127.0.0.1:80")
32
+ fi
22
33
  [[ "$relay" =~ ^[A-Za-z0-9.-]{1,253}$ ]] || { echo "clavarium-tunnel: not a host name: $relay" >&2; exit 64; }
23
34
  [[ "$port" =~ ^[0-9]{1,5}$ ]] || { echo "clavarium-tunnel: not a port: $port" >&2; exit 64; }
24
35
  home=/var/lib/clavarium-tunnel
@@ -30,7 +41,7 @@ trap 'rm -f "$said"' EXIT
30
41
  started=$SECONDS
31
42
  ssh -N -T -o BatchMode=yes -o IdentitiesOnly=yes -o "IdentityFile=$home/key" -o "UserKnownHostsFile=$home/known_hosts" \
32
43
  -o StrictHostKeyChecking=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=10 -o ServerAliveCountMax=2 -o ConnectTimeout=15 \
33
- -R '*:8443:127.0.0.1:443' -R '*:8080:127.0.0.1:80' -p "$port" "clavarium-tunnel@$relay" 2>"$said"
44
+ "${forwards[@]}" -p "$port" "clavarium-tunnel@$relay" 2>"$said"
34
45
  code=$?
35
46
  # Said to the journal once it ended -- read through a second writer (tee) it could still be on its way
36
47
  # when it was looked at (found on a CI runner): the refusal then passed for a cut.
@@ -11,7 +11,9 @@
11
11
  * sudo clavarium online --relay HOST --domain NAME [...] see deploy/online.mjs
12
12
  * sudo clavarium online --port --domain NAME [...]
13
13
  * sudo clavarium key the public keys, text and QR
14
+ * sudo clavarium online --relay PRINCIPAL --domain NAME --join CODE another home on the same relay
14
15
  * sudo clavarium relay status | repair | update-os | update-relay | forget-setup-key
16
+ * sudo clavarium relay homes | invite NAME | add-home NAME --key KEY | remove-home NAME
15
17
  * sudo clavarium doctor [--fix] what works, what does not, what to do
16
18
  * sudo clavarium password EMAIL a new password for an administrator
17
19
  * sudo clavarium client-id [ID] the sign-in client id (no ID: a random one)
@@ -70,7 +72,9 @@ if (verb !== 'install') {
70
72
  + ' sudo clavarium online --relay HOST --domain NAME then online, through a relay of yours\n'
71
73
  + ' sudo clavarium online --port --domain NAME or with ports 80 and 443 open\n'
72
74
  + ' sudo clavarium key the public keys again (text and QR)\n'
75
+ + ' sudo clavarium online --relay PRINCIPAL --domain NAME --join CODE another home on the relay of PRINCIPAL\n'
73
76
  + ' sudo clavarium relay status|repair|update-os|update-relay|forget-setup-key\n'
77
+ + ' sudo clavarium relay homes|invite NAME|add-home NAME --key KEY|remove-home NAME\n'
74
78
  + ' sudo clavarium doctor [--fix] what works, what does not, what to do\n'
75
79
  + ' sudo clavarium password EMAIL a new password for an administrator\n'
76
80
  + ' sudo clavarium client-id [ID] the sign-in client id (no ID: a random one)\n\n'
package/deploy/git-read CHANGED
@@ -27,12 +27,37 @@
27
27
  # Every setting the repository could use to run something is overridden on
28
28
  # every git command.
29
29
  #
30
+ # Two more ways, after the same checks (the same refusals, the same list):
31
+ # --tips the header alone: the list of branches, no pack. What
32
+ # To send needs to see which branches moved, at the cost of
33
+ # one for-each-ref.
34
+ # --have <id>... the pack leaves out what those commits reach, for the
35
+ # server has it already (the remote's history, the last
36
+ # read): only what is new travels. A commit the repository
37
+ # does not have is left out of that list, never an error.
38
+ # The header is the same whole list of branches: a branch
39
+ # whose commits did not travel is still listed, and the
40
+ # server checks that it has every object each one needs.
41
+ #
30
42
  # Exit codes: 0; 3 (refs unreadable); 128 only with the 17 bytes of an
31
43
  # empty bundle (no branches); 66 for anything else, with one line on stderr
32
44
  # saying what. git's own codes become 66, so that a code systemd uses for
33
45
  # itself (200-243) can only come from systemd. A git killed by a signal is
34
46
  # killed again here by the same signal, so that the host still sees a signal.
35
47
  NAME="$1"
48
+ MODE="${2:-}"
49
+ case "$MODE" in
50
+ "") [ $# -eq 1 ] || { echo "BAD ARGUMENTS" >&2; exit 66; } ;;
51
+ --tips) [ $# -eq 2 ] || { echo "BAD ARGUMENTS" >&2; exit 66; } ;;
52
+ --have)
53
+ shift 2
54
+ [ $# -ge 1 ] && [ $# -le 256 ] || { echo "BAD ARGUMENTS" >&2; exit 66; }
55
+ for id in "$@"; do
56
+ case "$id" in *[!0-9a-f]*) echo "BAD ARGUMENTS" >&2; exit 66 ;; esac
57
+ [ "${#id}" -eq 40 ] || { echo "BAD ARGUMENTS" >&2; exit 66; }
58
+ done ;;
59
+ *) echo "BAD ARGUMENTS" >&2; exit 66 ;;
60
+ esac
36
61
  [ -d .git ] && [ ! -L .git ] && [ ! -e .git/commondir ] && [ ! -L .git/commondir ] \
37
62
  || { echo "NOT A PLAIN .git DIRECTORY" >&2; exit 66; }
38
63
  for p in .git/refs .git/packed-refs; do
@@ -66,12 +91,31 @@ format=$(g rev-parse --show-object-format) || failed $? "GIT COULD NOT OPEN THE
66
91
  [ "$format" = "sha1" ] || { echo "NOT SHA-1" >&2; exit 66; }
67
92
 
68
93
  refs=$(g for-each-ref --format='%(objectname) %(refname)' refs/heads/) || failed $? "GIT COULD NOT LIST THE BRANCHES"
69
- listed=$(printf '%s\n' "$refs" | sed -n 's|^[0-9a-f]\{40\} ||p' | sort -u)
94
+ listed=$(printf '%s\n' "$refs" | sed -n 's|^[0-9a-f]\{40\} ||p')
95
+ # A file or folder whose name starts with a dot is no ref, for git either: no
96
+ # ref name may have a part that starts with one (check-ref-format), so git
97
+ # can never make it and never lists it. Such files do appear on their own:
98
+ # a folder shared into a machine (sshfs, FUSE) keeps a ref file that was
99
+ # replaced while something still had it open as .fuse_hidden<number>, beside
100
+ # the new one, until it is closed. Counted, it refused healthy repositories
101
+ # as "broken or changing".
70
102
  on_disk=$( {
71
- [ -d .git/refs/heads ] && find -L .git/refs/heads -type f ! -name '*.lock' -printf 'refs/heads/%P\n'
103
+ [ -d .git/refs/heads ] && find -L .git/refs/heads -mindepth 1 -name '.*' -prune -o -type f ! -name '*.lock' -printf 'refs/heads/%P\n'
72
104
  [ -f .git/packed-refs ] && sed -n 's|^[0-9a-f]\{40\} \(refs/heads/.*\)$|\1|p' .git/packed-refs
73
- } | sort -u)
74
- [ "$listed" = "$on_disk" ] || { echo "BROKEN OR CHANGING REFS" >&2; exit 66; }
105
+ })
106
+ # The two lists compared as sets, in the shell alone. No sort, no cut, nothing
107
+ # of coreutils here: on a host whose coreutils are the Rust ones (uutils),
108
+ # sort crashed inside this sandbox ("Aborted (core dumped)"), the list on disk
109
+ # came out empty, and healthy repositories were refused as "broken or
110
+ # changing". Every line of each list must be a line of the other.
111
+ nl='
112
+ '
113
+ in_list() { case "$nl$2$nl" in *"$nl$1$nl"*) return 0 ;; esac; return 1; }
114
+ same=yes; saved=$IFS; IFS=$nl; set -f
115
+ for x in $listed; do in_list "$x" "$on_disk" || same=no; done
116
+ for x in $on_disk; do in_list "$x" "$listed" || same=no; done
117
+ set +f; IFS=$saved
118
+ [ "$same" = yes ] || { echo "BROKEN OR CHANGING REFS" >&2; exit 66; }
75
119
  [ "$(printf '%s\n' "$refs" | grep -c .)" -le 1000 ] || { echo "MORE THAN 1000 BRANCHES" >&2; exit 66; }
76
120
 
77
121
  if [ -z "$refs" ]; then
@@ -79,7 +123,15 @@ if [ -z "$refs" ]; then
79
123
  exit 128
80
124
  fi
81
125
  printf '# v2 git bundle\n%s\n\n' "$refs"
82
- printf '%s\n' "$refs" | cut -c1-40 | g pack-objects --stdout --revs --delta-base-offset -q
126
+ [ "$MODE" = "--tips" ] && exit 0
127
+ # The commits to leave out: only those this repository has (a name of
128
+ # another kind, or none, would stop pack-objects). Should this look fail,
129
+ # nothing is left out: the whole pack goes, larger, never wrong.
130
+ have=""
131
+ if [ "$MODE" = "--have" ]; then
132
+ have=$(printf '%s\n' "$@" | g cat-file --batch-check='%(objectname) %(objecttype)' | sed -n 's/^\([0-9a-f]\{40\}\) commit$/^\1/p')
133
+ fi
134
+ { printf '%s\n' "$refs" | sed -n 's/^\([0-9a-f]\{40\}\) .*/\1/p'; [ -z "$have" ] || printf '%s\n' "$have"; } | g pack-objects --stdout --revs --delta-base-offset -q
83
135
  rc=$?
84
136
  [ "$rc" -eq 0 ] && exit 0
85
137
  failed "$rc" "GIT COULD NOT PACK THE BRANCHES"
package/deploy/install.sh CHANGED
@@ -38,6 +38,8 @@
38
38
  # server mode)
39
39
  # --relay-installed the relay was set up already (by `clavarium online`):
40
40
  # do not print the command to run on it
41
+ # --relay-ports T,H the two ports the relay gave this machine, when it is
42
+ # not the relay's first home (`clavarium online --join`)
41
43
  # --name NAME the name of this Clavarium, under its icon and in its
42
44
  # tab (default: drawn from --domain); changed in Settings.
43
45
  # Letters, digits, spaces, dots, hyphens: 30 at most
@@ -118,7 +120,7 @@ bad() { echo "install: $*" >&2; echo "usage: install.sh --domain NAME --operator
118
120
  refuse() { echo "install: REFUSED: $*" >&2; exit 78; }
119
121
  step() { echo "== $*"; }
120
122
 
121
- DOMAIN=""; OPERATORS=""; PORT="7717"; CORE_ONLY="no"; DRY="no"; RELAY=""; RELAY_PORT="22"; LOCAL="no"; KEEP_RELEASE="no"; RELAY_INSTALLED="no"
123
+ DOMAIN=""; OPERATORS=""; PORT="7717"; CORE_ONLY="no"; DRY="no"; RELAY=""; RELAY_PORT="22"; RELAY_PORTS=""; LOCAL="no"; KEEP_RELEASE="no"; RELAY_INSTALLED="no"
122
124
  VERSION=""; FROM_DIR=""; UPDATES=""; WINDOW=""; CHANNEL=""; APP_NAME=""; CLIENT_ID=""
123
125
  while [ $# -gt 0 ]; do
124
126
  case "$1" in
@@ -136,6 +138,7 @@ while [ $# -gt 0 ]; do
136
138
  --channel) CHANNEL="${2:-}"; shift 2 || bad "--channel needs a value" ;;
137
139
  --keep-release) KEEP_RELEASE="yes"; shift ;;
138
140
  --relay-installed) RELAY_INSTALLED="yes"; shift ;;
141
+ --relay-ports) RELAY_PORTS="${2:-}"; shift 2 || bad "--relay-ports needs a value" ;;
139
142
  --name) APP_NAME="${2:-}"; [ -n "$APP_NAME" ] || bad "--name needs a value"; shift 2 ;;
140
143
  --client-id) CLIENT_ID="${2:-}"; [ -n "$CLIENT_ID" ] || bad "--client-id needs a value"; shift 2 ;;
141
144
  --dry-run) DRY="yes"; shift ;;
@@ -161,7 +164,9 @@ if [ -n "$RELAY" ]; then
161
164
  [[ "$RELAY" =~ ^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,24}$|^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] || bad "--relay is the name or the address of the relay machine"
162
165
  [[ "$RELAY_PORT" =~ ^[0-9]{1,5}$ ]] && [ "$RELAY_PORT" -ge 1 ] && [ "$RELAY_PORT" -le 65535 ] || bad "--relay-port is a port number"
163
166
  [ "$CORE_ONLY" = "no" ] || bad "--relay comes with the edge: it cannot go with --core-only"
167
+ [ -z "$RELAY_PORTS" ] || [[ "$RELAY_PORTS" =~ ^[0-9]{4,5},[0-9]{4,5}$ ]] || bad "--relay-ports is two ports: TLS,HTTP"
164
168
  fi
169
+ [ -z "$RELAY_PORTS" ] || [ -n "$RELAY" ] || bad "--relay-ports goes with --relay"
165
170
 
166
171
  # WHAT IS INSTALLED: an exact version from npm, or a working tree (development).
167
172
  [ -z "$VERSION" ] || [[ "$VERSION" =~ ^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,6}(-[0-9A-Za-z.-]{1,40})?$ ]] || bad "--version is an exact version, like 1.2.3 or 1.3.0-next.1"
@@ -553,9 +558,10 @@ skip_provider_button = true
553
558
  approval_prompt = "auto"
554
559
  http_address = "127.0.0.1:4180"
555
560
  upstreams = ["http://127.0.0.1:$PORT/"]
556
- # A paired device does not sign in: its own door (/c/) checks its key. The
561
+ # A paired device does not sign in: its own door (/c/) checks its key; nor
562
+ # does a program with an API key (/api/ext/, server/apikeys.mjs). The
557
563
  # identity headers are stripped there, so nobody can claim to be an operator.
558
- skip_auth_routes = ["^/c/"]
564
+ skip_auth_routes = ["^/c/", "^/api/ext/"]
559
565
  skip_auth_strip_headers = true
560
566
  # Two sign-ins at once (two tabs, a reload during it) each have their own CSRF
561
567
  # cookie; and there is time to type a password (deploy/updater.mjs, PROXY_LINES).
@@ -743,8 +749,8 @@ if [ -n "$RELAY" ]; then
743
749
  fi
744
750
  # The unit is the updater's (deploy/tunnel.mjs, tunnelUnit): one text, kept up to date by each update.
745
751
  install -o root -g root -m 0755 "$APP/deploy/clavarium-tunnel" /usr/local/sbin/clavarium-tunnel
746
- "$NODE_DIR/bin/node" --input-type=module -e 'const { tunnelUnit } = await import(process.argv[1]); process.stdout.write(tunnelUnit(process.argv[2], process.argv[3]));' \
747
- "$APP/deploy/tunnel.mjs" "$RELAY" "$RELAY_PORT" > /etc/systemd/system/clavarium-tunnel.service
752
+ "$NODE_DIR/bin/node" --input-type=module -e 'const { tunnelUnit } = await import(process.argv[1]); const [t, h] = (process.argv[4] || "").split(","); process.stdout.write(tunnelUnit(process.argv[2], process.argv[3], undefined, t ? { tls: t, http: h } : null));' \
753
+ "$APP/deploy/tunnel.mjs" "$RELAY" "$RELAY_PORT" "$RELAY_PORTS" > /etc/systemd/system/clavarium-tunnel.service
748
754
  systemctl daemon-reload
749
755
  systemctl enable --quiet clavarium-tunnel.service
750
756
  systemctl restart clavarium-tunnel.service
@@ -56,17 +56,20 @@ const VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,6}(-[0-9A-Za-z.-]{1,40})?$/;
56
56
  when the server still announces an update about to stop it. */
57
57
  const next = ({ kind, startedAt, now, seenDown, answer }) => {
58
58
  const up = !!answer && !answer.down && !answer.update && !(answer.status >= 502 && answer.status <= 504);
59
- if (up && !(kind === 'restart' && !seenDown && now - startedAt < RESTART_GRACE_MS)) return 'back';
59
+ /* The whole server (reboot): five seconds before it stops, a minute of grace. */
60
+ const grace = kind === 'reboot' ? 4 * RESTART_GRACE_MS : kind === 'restart' ? RESTART_GRACE_MS : 0;
61
+ if (up && !(grace && !seenDown && now - startedAt < grace)) return 'back';
60
62
  return now - startedAt > STUCK_MS ? 'stuck' : 'wait';
61
63
  };
62
64
 
63
- /* WHAT IT SAYS, from its address (?kind=update|back|restart&to=<version>): the edge serves
65
+ /* WHAT IT SAYS, from its address (?kind=update|back|restart|reboot&to=<version>): the edge serves
64
66
  it at any address, with none of these: then it cannot know which. */
65
67
  const title = (kind, to) => {
66
68
  const v = VERSION.test(to ?? '') ? to : '';
67
69
  if (kind === 'update') return v ? `Updating Clavarium to ${v}...` : 'Updating Clavarium...';
68
70
  if (kind === 'back') return v ? `Going back to Clavarium ${v}...` : 'Going back to the previous Clavarium...';
69
71
  if (kind === 'restart') return 'Restarting Clavarium...';
72
+ if (kind === 'reboot') return 'Restarting the server: every machine starts again in a few minutes...';
70
73
  return 'Clavarium is being updated or restarted...';
71
74
  };
72
75
 
package/deploy/online.mjs CHANGED
@@ -13,6 +13,26 @@
13
13
  * --port this machine is reachable on 80 and 443 (a server at a host,
14
14
  * or a router whose ports were opened).
15
15
  *
16
+ * SEVERAL HOMES ON ONE RELAY. The machine that set the relay up is its
17
+ * PRINCIPAL: it alone holds the relay's maintenance key. Another Clavarium
18
+ * joins the same relay without any access to it:
19
+ *
20
+ * on the principal sudo clavarium relay invite NAME a one-time code (8 letters and
21
+ * digits, 30 minutes, good once) for the domain NAME
22
+ * on the new home sudo clavarium online --relay PRINCIPAL --domain NAME --join CODE
23
+ *
24
+ * The new home sends the code and its PUBLIC tunnel key to the principal over
25
+ * HTTPS (POST /c/relay-join, server/relayjoin.mjs, then the host program, then
26
+ * `clavarium relay join` here, as root). The principal checks the code, spends
27
+ * it, adds the key to the relay (clavarium-relay add-home, through its
28
+ * maintenance key) and answers with the relay's address, its host key's
29
+ * fingerprint and the two ports the relay gave. The new home checks that
30
+ * fingerprint against the relay itself, and goes online on its own ports.
31
+ * Nothing else is copied by hand. By hand all the same (no code): on the
32
+ * principal `sudo clavarium relay add-home NAME --key KEY`, which prints the
33
+ * line to type on the new home (--relay-ports, --relay-fingerprint).
34
+ * A second owner is let in this way only: by the principal's owner.
35
+ *
16
36
  * NOTHING IS CUT BEFORE A REAL TEST FROM THE INTERNET HAS PASSED: Let's
17
37
  * Encrypt's staging service is asked for a certificate for the domain, so it
18
38
  * really comes to this machine (through the relay, or through the open
@@ -24,6 +44,7 @@
24
44
  * `sys`, so the tests can stand in for SSH, npm and DNS.
25
45
  */
26
46
  import { spawn } from 'node:child_process';
47
+ import { createHash, randomInt } from 'node:crypto';
27
48
  import { relayOfUnit, TUNNEL_UNIT } from './tunnel.mjs';
28
49
  import { createReadStream, existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, mkdtempSync, renameSync, openSync, readSync, writeSync, closeSync } from 'node:fs';
29
50
  import { promises as dns } from 'node:dns';
@@ -37,6 +58,8 @@ import { doctor, servedCert, DOCTOR_PATHS } from './doctor.mjs';
37
58
  export const PATHS = {
38
59
  access: '/var/lib/clavarium-relay-access',
39
60
  tunnel: '/var/lib/clavarium-tunnel',
61
+ tunnelUnit: TUNNEL_UNIT,
62
+ relayDone: '/var/lib/clavarium/update/relay-version',
40
63
  relayConf: '/etc/clavarium/relay.conf',
41
64
  updateConf: '/etc/clavarium/update.conf',
42
65
  unit: '/etc/systemd/system/clavarium.service',
@@ -62,11 +85,13 @@ export class Failed extends Error {}
62
85
  export const USAGE = [
63
86
  'usage: sudo clavarium online --relay HOST --domain NAME [--relay-user USER] [--relay-port N] [--admin EMAIL]',
64
87
  ' [--relay-fingerprint SHA256:...] [--keep-setup-key] [--yes]',
88
+ ' or: sudo clavarium online --relay PRINCIPAL --domain NAME --join CODE [--admin EMAIL]',
89
+ ' or: sudo clavarium online --relay HOST --domain NAME --relay-ports TLS,HTTP --relay-fingerprint SHA256:... [--relay-port N]',
65
90
  ' or: sudo clavarium online --port --domain NAME [--admin EMAIL]',
66
91
  ].join('\n');
67
92
 
68
93
  export function parseOnline(args) {
69
- const o = { askRelay: false, relay: '', user: 'root', relayPort: '22', domain: '', admin: '', fingerprint: '', keepSetupKey: false, yes: false, port: false };
94
+ const o = { askRelay: false, relay: '', user: 'root', relayPort: '22', domain: '', admin: '', fingerprint: '', keepSetupKey: false, yes: false, port: false, join: '', ports: null };
70
95
  const value = (i, name) => { const v = args[i + 1]; if (v === undefined || v.startsWith('--')) throw new Bad(`${name} needs a value`); return v; };
71
96
  for (let i = 0; i < args.length; i++) {
72
97
  const a = args[i];
@@ -80,9 +105,25 @@ export function parseOnline(args) {
80
105
  case '--keep-setup-key': o.keepSetupKey = true; break;
81
106
  case '--yes': o.yes = true; break;
82
107
  case '--port': o.port = true; break;
108
+ case '--join': o.join = normalCode(value(i, a)); i++; if (!CODE.test(o.join)) throw new Bad('--join is the code the principal gave: 8 letters and digits, like ABCD-EFGH'); break;
109
+ case '--relay-ports': {
110
+ const m = /^(\d{4,5}),(\d{4,5})$/.exec(value(i, a)); i++;
111
+ if (!m || [m[1], m[2]].some((p) => +p < 1024 || +p > 65535)) throw new Bad('--relay-ports is the two ports the relay gave: TLS,HTTP');
112
+ o.ports = { tls: m[1], http: m[2] }; break;
113
+ }
83
114
  default: throw new Bad(`unknown parameter: ${a}`);
84
115
  }
85
116
  }
117
+ if (o.join || o.ports) {
118
+ /* A home the principal adds: the relay is not set up from here, and no account of it is used. */
119
+ if (o.join && o.ports) throw new Bad('--join or --relay-ports, not both');
120
+ if (!o.relay) throw new Bad(o.join ? '--join goes with --relay PRINCIPAL: the name of the Clavarium that gave the code' : '--relay-ports goes with --relay HOST');
121
+ if (o.keepSetupKey || o.user !== 'root') throw new Bad('--relay-user and --keep-setup-key are for the relay\'s first home; a home that joins uses no account of the relay');
122
+ if (o.join && !DOMAIN.test(o.relay)) throw new Bad('--relay is the NAME of the Clavarium that gave the code (it is asked over HTTPS)');
123
+ if (o.join && (o.fingerprint || o.relayPort !== '22')) throw new Bad('with --join, the principal says the relay\'s address and fingerprint');
124
+ if (o.ports && !o.fingerprint) throw new Bad('--relay-ports goes with --relay-fingerprint (what the principal printed)');
125
+ if (o.join) o.principal = o.relay;
126
+ }
86
127
  if (o.relay && o.port) throw new Bad('say how it will be reached: --relay HOST or --port, not both');
87
128
  /* Neither: the usual case -- the domain points to the relay, which is
88
129
  reached by the domain itself (its address is not needed). */
@@ -168,6 +209,15 @@ export function readRelayConf(P = PATHS) {
168
209
  try { for (const line of readFileSync(P.relayConf, 'utf8').split('\n')) { const m = /^([A-Z_]+)=(.*)$/.exec(line.trim()); if (m) conf[m[1]] = m[2]; } } catch { return null; }
169
210
  return conf.HOST ? conf : null;
170
211
  }
212
+ /* The relay of a machine put online before relay.conf existed (07-11, found on a test machine): only
213
+ its tunnel unit says it. Read there, as the updater does (tunnel.mjs, relayOfUnit); never written back. */
214
+ export function relayOf(P = PATHS) {
215
+ const conf = readRelayConf(P);
216
+ if (conf) return conf;
217
+ let unit = null;
218
+ try { unit = relayOfUnit(readFileSync(P.tunnelUnit ?? TUNNEL_UNIT, 'utf8')); } catch { return null; }
219
+ return unit ? { HOST: unit.relay, PORT: unit.port } : null;
220
+ }
171
221
  function writeRelayConf(P, conf) {
172
222
  mkdirSync(join(P.relayConf, '..'), { recursive: true });
173
223
  writeFileSync(`${P.relayConf}.new`, `# The relay of this Clavarium. Written by clavarium online.\n${Object.entries(conf).map(([k, v]) => `${k}=${v}`).join('\n')}\n`, { mode: 0o644 });
@@ -196,12 +246,19 @@ export async function keepRelayCurrent(sys, P = PATHS, { done, unit = TUNNEL_UNI
196
246
  let conf = readRelayConf(P);
197
247
  if (!conf) { try { const at = relayOfUnit(readFileSync(unit, 'utf8')); if (at) conf = { HOST: at.relay, PORT: at.port }; } catch { /* no tunnel */ } }
198
248
  if (!conf) return { state: 'none' };
249
+ /* A home the principal added: the relay is the principal's to keep. */
250
+ if (conf.ROLE === 'home') return { state: 'none' };
199
251
  if (!existsSync(keyFiles(P).keeper)) return { state: 'no-key' };
200
252
  const version = relayVersion(P);
201
253
  if (!version) return { state: 'none' };
202
254
  let last = '';
203
255
  try { last = readFileSync(done, 'utf8').trim(); } catch { /* never brought */ }
204
256
  if (last === version) return { state: 'current', version };
257
+ /* A new GENERATION of the relay program (0.1 -> 0.2: one relay for several homes, 07-11) is never brought
258
+ by the updater: the owner brings it once, `sudo clavarium relay update-relay`, when they want it.
259
+ Fixes within a generation still come by themselves. */
260
+ const gen = (v) => String(v).split('.').slice(0, 2).join('.');
261
+ if (gen(version) !== gen(last || '0.1.0')) return { state: 'held', version, why: `the relay program ${version} is a new generation: bring it with sudo clavarium relay update-relay` };
205
262
  const r = await keeper(sys, P, conf, ['update-relay', version]);
206
263
  if (r.code !== 0) {
207
264
  /* sys.run says { code, out, err } (realSys). */
@@ -407,6 +464,7 @@ async function setUpRelay(sys, P, o, keys) {
407
464
  const f = keyFiles(P);
408
465
  const conf = { HOST: o.relay, PORT: o.relayPort, USER: o.user };
409
466
  const prior = readRelayConf(P);
467
+ if (prior?.ROLE === 'home') throw new Refused(`this machine is a home of the relay ${prior.HOST}, added by its principal: it does not set a relay up`);
410
468
  /* Run again after the relay was set up (a test that failed, a DNS record
411
469
  made late): the maintenance account answers, the setup key is not needed. */
412
470
  if (prior && prior.HOST === o.relay && existsSync(f.knownHosts)) {
@@ -447,7 +505,7 @@ async function setUpRelay(sys, P, o, keys) {
447
505
  input, a program it starts (apt-get...) could eat the rest of it. */
448
506
  const runner = 'f="$(mktemp)"; cat > "$f"; bash "$f" "$@" </dev/null; s=$?; rm -f -- "$f"; exit $s';
449
507
  const r = await sys.run(['ssh', ...sshOptions(f.setup, f.knownHosts, o.relayPort), `${o.user}@${o.relay}`,
450
- `${sudo}bash -c ${quote(runner)} relay.sh --key ${quote(keys.tunnel)} --keeper-key ${quote(keys.keeper)}`], { input: script, stream: true });
508
+ `${sudo}bash -c ${quote(runner)} relay.sh --key ${quote(keys.tunnel)} --keeper-key ${quote(keys.keeper)} --name ${quote(o.domain)}`], { input: script, stream: true });
451
509
  if (r.code !== 0) throw new Failed(`the relay could not be set up (exit ${r.code}, above: why). This machine is still in local mode`);
452
510
  const next = { ...conf, SETUP_KEY: 'kept' };
453
511
  writeRelayConf(P, next);
@@ -459,11 +517,52 @@ async function setUpRelay(sys, P, o, keys) {
459
517
  return readRelayConf(P);
460
518
  }
461
519
 
462
- /* The tunnel, for the test only: the service comes with server mode. */
520
+ /* A HOME THE PRINCIPAL ADDED: the relay's host key checked against the fingerprint the principal gave
521
+ (`from`: who gave it), kept for the tunnel, and the relay and its ports kept in relay.conf. The relay
522
+ is maintained by its principal: this machine holds no key of its maintenance account. */
523
+ async function useRelay(sys, P, o, at, from) {
524
+ o.relay = at.host; o.relayPort = String(at.port); o.ports = { tls: String(at.tls), http: String(at.http) };
525
+ const scanned = await scanRelay(sys, o, sys.now() + WAIT_MS);
526
+ const { file: pending, print } = await fingerprintOf(sys, P, scanned);
527
+ rmSync(pending, { force: true });
528
+ if (print !== at.fingerprint) throw new Refused(`${o.relay} answers with the key ${print}, not ${at.fingerprint} (said by ${from}): it may not be the relay. Nothing was changed`);
529
+ sys.print(`The relay ${o.relay}: its fingerprint is the one ${from} gave. Its ports for this machine: ${o.ports.tls} and ${o.ports.http}.`);
530
+ writeFileSync(join(P.tunnel, 'known_hosts'), `${scanned}\n`, { mode: 0o644 });
531
+ await sys.run(['chown', 'clavarium-tunnel:clavarium-tunnel', join(P.tunnel, 'known_hosts')]);
532
+ writeRelayConf(P, { HOST: o.relay, PORT: o.relayPort, TLS_PORT: o.ports.tls, HTTP_PORT: o.ports.http, ROLE: 'home', ...(o.principal ? { PRINCIPAL: o.principal } : {}) });
533
+ }
534
+
535
+ /* --join: the code and this machine's PUBLIC tunnel key to the principal, over HTTPS (its certificate
536
+ checked as any browser would); its answer is read field by field. Run again after a failed test: the
537
+ relay and the ports kept from the first time, no code needed. */
538
+ async function joinRelay(sys, P, o, keys) {
539
+ const prior = readRelayConf(P);
540
+ if (prior?.ROLE === 'home' && prior.TLS_PORT && existsSync(join(P.tunnel, 'known_hosts'))) {
541
+ Object.assign(o, { relay: prior.HOST, relayPort: prior.PORT, ports: { tls: prior.TLS_PORT, http: prior.HTTP_PORT } });
542
+ sys.print(`This machine joined the relay ${prior.HOST} already (ports ${prior.TLS_PORT} and ${prior.HTTP_PORT}).`);
543
+ return;
544
+ }
545
+ sys.print(`Asking ${o.principal} to add this machine to its relay (code ${o.join.slice(0, 4)}-${o.join.slice(4)})...`);
546
+ let r;
547
+ try { r = await sys.post(`https://${o.principal}${JOIN_PATH}`, { code: o.join, key: keys.tunnel.split(' ').slice(0, 2).join(' ') }); } catch (error) { throw new Failed(`${o.principal} did not answer over HTTPS: ${error.message}`); }
548
+ const said = typeof r?.body?.error === 'string' ? r.body.error.slice(0, 200) : '';
549
+ if (r?.status === 403) throw new Refused(`${o.principal} refused the code${said ? `: ${said}` : ''}. Ask its owner for a new one: sudo clavarium relay invite ${o.domain}`);
550
+ if (r?.status === 429) throw new Failed(`${o.principal} says too many tries: wait a minute, then run this again`);
551
+ if (r?.status !== 200) throw new Failed(`${o.principal} did not add this machine (HTTP ${r?.status})${said ? `: ${said}` : ''}`);
552
+ const a = r.body ?? {};
553
+ if (a.name !== o.domain) throw new Refused(`the code was made for ${String(a.name).slice(0, 80)}, not ${o.domain}`);
554
+ const port = (v, lo) => Number.isInteger(v) && v >= lo && v <= 65535;
555
+ if (!HOST.test(a.relay?.host ?? '') || !port(a.relay?.port, 1) || !PRINT.test(a.relay?.fingerprint ?? '') || !port(a.ports?.tls, 1024) || !port(a.ports?.http, 1024)) throw new Failed(`${o.principal} answered something else than a relay and two ports`);
556
+ await useRelay(sys, P, o, { host: a.relay.host, port: a.relay.port, fingerprint: a.relay.fingerprint, tls: a.ports.tls, http: a.ports.http }, o.principal);
557
+ }
558
+
559
+ /* The tunnel, for the test only: the service comes with server mode. The relay's first home on 8443
560
+ and 8080 (every address, as ever); a home it added on its own ports, on the relay's loopback. */
463
561
  function startTunnel(sys, P, o) {
464
562
  const lines = [];
563
+ const forwards = o.ports ? ['-R', `127.0.0.1:${o.ports.tls}:127.0.0.1:443`, '-R', `127.0.0.1:${o.ports.http}:127.0.0.1:80`] : ['-R', '*:8443:127.0.0.1:443', '-R', '*:8080:127.0.0.1:80'];
465
564
  const proc = sys.start(['sudo', '-u', 'clavarium-tunnel', 'ssh', '-N', '-T', ...sshOptions(join(P.tunnel, 'key'), join(P.tunnel, 'known_hosts'), o.relayPort),
466
- '-o', 'ExitOnForwardFailure=yes', '-R', '*:8443:127.0.0.1:443', '-R', '*:8080:127.0.0.1:80', `clavarium-tunnel@${o.relay}`], { onLine: (l) => lines.push(l) });
565
+ '-o', 'ExitOnForwardFailure=yes', ...forwards, `clavarium-tunnel@${o.relay}`], { onLine: (l) => lines.push(l) });
467
566
  return { proc, lines };
468
567
  }
469
568
 
@@ -477,6 +576,7 @@ async function switchToServer(sys, P, o) {
477
576
  const port = readConf(P.updateConf).PORT;
478
577
  const argv = ['/bin/bash', join(app, 'deploy', 'install.sh'), '--keep-release', '--domain', o.domain, '--operator', o.admin, '--port', port];
479
578
  if (o.relay) argv.push('--relay', o.relay, '--relay-port', o.relayPort, '--relay-installed');
579
+ if (o.relay && o.ports) argv.push('--relay-ports', `${o.ports.tls},${o.ports.http}`);
480
580
  sys.print('');
481
581
  sys.print('Switching to server mode: HTTPS, sign-in, the administrator...');
482
582
  const r = await sys.run(argv, { stream: true, inherit: true, env: { CLAVARIUM_PASSWORDS_TO: P.passwords } });
@@ -514,7 +614,9 @@ export async function online(o, sys, P = PATHS) {
514
614
  }
515
615
  await checkDns(sys, o);
516
616
  await portsFree(sys);
517
- if (o.relay) await setUpRelay(sys, P, o, keys);
617
+ if (o.join) await joinRelay(sys, P, o, keys);
618
+ else if (o.ports) await useRelay(sys, P, o, { host: o.relay, port: o.relayPort, fingerprint: o.fingerprint, tls: o.ports.tls, http: o.ports.http }, 'the principal');
619
+ else if (o.relay) await setUpRelay(sys, P, o, keys);
518
620
  let tunnel = null;
519
621
  try {
520
622
  if (o.relay) {
@@ -532,7 +634,13 @@ export async function online(o, sys, P = PATHS) {
532
634
  await doctor(sys, {}, { ...DOCTOR_PATHS, unit: P.unit, relayConf: P.relayConf });
533
635
  sys.print('');
534
636
  sys.print(`Online: https://${o.domain}`);
535
- if (o.relay) sys.print('The relay is watched from here: sudo clavarium relay status');
637
+ if (o.relay && !o.ports) sys.print('The relay is watched from here: sudo clavarium relay status');
638
+ if (o.relay && o.ports) {
639
+ sys.print(`The relay is kept by its principal${o.principal ? `, ${o.principal}` : ''}.`);
640
+ sys.print(`TO KEEP THE RELAY BLIND for ${o.domain}, add a CAA record to your DNS that names this machine's`);
641
+ sys.print('certificate account (accounturi=...); without it, whoever controls the relay could obtain a');
642
+ sys.print(`certificate for ${o.domain}. The account address: sudo grep -rho '"location": *"[^"]*"' /var/lib/caddy/caddy/acme`);
643
+ }
536
644
  sys.print('Anything wrong later: sudo clavarium doctor (it says what to do; --fix repairs what it can)');
537
645
  const pw = existsSync(P.passwords) ? readFileSync(P.passwords, 'utf8') : '';
538
646
  sys.print('');
@@ -543,12 +651,138 @@ export async function online(o, sys, P = PATHS) {
543
651
  } finally { rmSync(P.passwords, { force: true }); }
544
652
  }
545
653
 
654
+ /* ------------------------- other homes on this relay ------------------------- */
655
+ /* 31 letters and digits a person can read and type: no I, L, O, 0, 1. Eight of them: some 10^12 codes,
656
+ against WRONG_MAX wrong tries before every invitation is cancelled. */
657
+ export const CODE_LETTERS = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
658
+ const CODE = /^[A-HJKMNP-Z2-9]{8}$/;
659
+ export const INVITE_MS = 30 * 60_000;
660
+ export const WRONG_MAX = 10;
661
+ export const JOIN_PATH = '/c/relay-join';
662
+ export const normalCode = (s) => String(s ?? '').toUpperCase().replace(/[\s-]/g, '');
663
+ const hashOf = (code) => createHash('sha256').update(code).digest('hex');
664
+ const invitesFile = (P) => join(P.access, 'invites.json');
665
+ /* Root's, in the access folder (0700): only the hash of each code is kept, with its name and its end. */
666
+ function readInvites(P, now) {
667
+ let j = {};
668
+ try { j = JSON.parse(readFileSync(invitesFile(P), 'utf8')); } catch { /* none yet */ }
669
+ return {
670
+ invites: (Array.isArray(j.invites) ? j.invites : []).filter((x) => x && /^[0-9a-f]{64}$/.test(x.hash) && DOMAIN.test(x.name ?? '') && x.until > now),
671
+ wrong: (Array.isArray(j.wrong) ? j.wrong : []).filter((t) => typeof t === 'number' && t > now - INVITE_MS),
672
+ };
673
+ }
674
+ function writeInvites(P, v) {
675
+ mkdirSync(P.access, { recursive: true, mode: 0o700 });
676
+ writeFileSync(`${invitesFile(P)}.new`, `${JSON.stringify(v)}\n`, { mode: 0o600 });
677
+ renameSync(`${invitesFile(P)}.new`, invitesFile(P));
678
+ }
679
+ /* Only the principal adds homes: the machine that holds the relay's maintenance key, online. */
680
+ function principal(P) {
681
+ const conf = relayOf(P);
682
+ if (!conf) throw new Refused('this machine has no relay (sudo clavarium online --relay HOST --domain NAME)');
683
+ if (conf.ROLE === 'home') throw new Refused(`this machine is a home of the relay ${conf.HOST}: only its principal${conf.PRINCIPAL ? ` (${conf.PRINCIPAL})` : ''} adds or removes homes`);
684
+ const domain = serverModeOf(P);
685
+ if (!domain) throw new Refused('this machine is not online yet (sudo clavarium online ...)');
686
+ return { conf, domain };
687
+ }
688
+
689
+ /* `relay invite NAME`: a one-time code for the home that will be NAME. A new one for the same name
690
+ replaces the one before. */
691
+ export async function invite(sys, P, name) {
692
+ if (!DOMAIN.test(name ?? '')) throw new Bad('relay invite NAME: the domain of the new home, lower case, like clav2.example.com');
693
+ const { conf, domain } = principal(P);
694
+ if (name === domain) throw new Bad(`${name} is this machine`);
695
+ const now = sys.now();
696
+ const v = readInvites(P, now);
697
+ const code = Array.from({ length: 8 }, () => CODE_LETTERS[randomInt(CODE_LETTERS.length)]).join('');
698
+ v.invites = [...v.invites.filter((x) => x.name !== name), { hash: hashOf(code), name, until: now + INVITE_MS }];
699
+ writeInvites(P, v);
700
+ const shown = `${code.slice(0, 4)}-${code.slice(4)}`;
701
+ sys.print(`One-time code for ${name} (good once, for ${INVITE_MS / 60_000} minutes): ${shown}`);
702
+ sys.print(`On that machine (Clavarium installed; ${name} leading to the relay, like ${domain}), type:`);
703
+ sys.print(` sudo clavarium online --relay ${domain} --domain ${name} --join ${shown}`);
704
+ sys.print(`It joins the relay ${conf.HOST} on ports of its own. Then, for ${name}, a CAA record as for ${domain} keeps the relay blind.`);
705
+ return { code: shown, name };
706
+ }
707
+
708
+ /* The principal's name told to the relay (a relay set up before 0.2.0 knew none), then the home added.
709
+ What the relay printed, read line by line. */
710
+ async function addHomeOnRelay(sys, P, conf, domain, name, key) {
711
+ const older = (r) => (/not a verb|unknown verb/.test(`${r.err ?? ''}`) ? ': the relay\'s program is older (sudo clavarium relay update-relay)' : '');
712
+ const n = await keeper(sys, P, conf, ['name-principal', domain]);
713
+ if (n.code !== 0) throw new Failed(`the relay did not take this machine's name (${tail(n)})${older(n)}`);
714
+ const r = await keeper(sys, P, conf, ['add-home', name, key]);
715
+ if (r.code === 78) throw new Refused(`the relay refused: ${tail(r).replace(/^clavarium-relay: REFUSED: /, '')}`);
716
+ if (r.code !== 0) throw new Failed(`the relay did not add ${name} (${tail(r)})${older(r)}`);
717
+ const get = (k) => new RegExp(`^${k} (\\S+)$`, 'm').exec(r.out ?? '')?.[1] ?? '';
718
+ const tls = Number(get('tls-port')); const http = Number(get('http-port')); const fingerprint = get('fingerprint');
719
+ if (!(tls >= 1024 && tls <= 65535 && http >= 1024 && http <= 65535) || !PRINT.test(fingerprint)) throw new Failed('the relay\'s answer is not two ports and a fingerprint');
720
+ return { name, relay: { host: conf.HOST, port: Number(conf.PORT), fingerprint }, ports: { tls, http } };
721
+ }
722
+
723
+ /* `relay join CODE KEY`, as root, for the server's /c/relay-join (through the host program): the code
724
+ must be one of the owner's, unused and not expired. It is spent BEFORE the relay is asked (good once,
725
+ whatever happens next); a wrong one is counted, and WRONG_MAX of them within INVITE_MS cancel every
726
+ invitation. The answer holds nothing secret: the relay's address, its public fingerprint, two ports. */
727
+ export async function joinWithCode(sys, P, given, key) {
728
+ const code = normalCode(given);
729
+ if (!CODE.test(code) || !KEY.test(key ?? '')) throw new Bad('relay join CODE KEY');
730
+ const { conf, domain } = principal(P);
731
+ const now = sys.now();
732
+ const v = readInvites(P, now);
733
+ const at = v.invites.findIndex((x) => x.hash === hashOf(code));
734
+ if (at < 0) {
735
+ v.wrong.push(now);
736
+ const cancel = v.wrong.length >= WRONG_MAX;
737
+ if (cancel) v.invites = [];
738
+ writeInvites(P, v);
739
+ throw new Refused(cancel ? 'not a valid code; too many wrong codes: every invitation was cancelled' : 'not a valid code (wrong, used or expired)');
740
+ }
741
+ const [spent] = v.invites.splice(at, 1);
742
+ writeInvites(P, v);
743
+ return addHomeOnRelay(sys, P, conf, domain, spent.name, key);
744
+ }
745
+
546
746
  /* `sudo clavarium relay VERB` */
547
747
  export async function relayCommand(args, sys, P = PATHS) {
548
- const conf = readRelayConf(P);
748
+ const conf = relayOf(P);
549
749
  if (!conf) throw new Refused('this machine has no relay (sudo clavarium online --relay HOST --domain NAME)');
550
750
  const [verb, ...rest] = args;
751
+ if (conf.ROLE === 'home') throw new Refused(`this machine is a home of the relay ${conf.HOST}: the relay is kept by its principal${conf.PRINCIPAL ? `, ${conf.PRINCIPAL}` : ''}`);
551
752
  switch (verb) {
753
+ case 'invite': {
754
+ if (rest.length !== 1) throw new Bad('relay invite NAME');
755
+ await invite(sys, P, rest[0]);
756
+ return;
757
+ }
758
+ case 'join': {
759
+ if (rest.length !== 2) throw new Bad('relay join CODE KEY');
760
+ sys.print(JSON.stringify(await joinWithCode(sys, P, rest[0], rest[1])));
761
+ return;
762
+ }
763
+ case 'add-home': {
764
+ const [name, flag, ...words] = rest;
765
+ const key = words.join(' ');
766
+ if (!DOMAIN.test(name ?? '') || flag !== '--key' || !KEY.test(key)) throw new Bad('relay add-home NAME --key "ssh-ed25519 AAAA..." (the new home\'s tunnel key: sudo clavarium key tunnel, there)');
767
+ const { domain } = principal(P);
768
+ const a = await addHomeOnRelay(sys, P, conf, domain, name, key);
769
+ sys.print(`${name} is a home of the relay ${a.relay.host}, on its ports ${a.ports.tls} and ${a.ports.http}. On that machine, type:`);
770
+ sys.print(` sudo clavarium online --relay ${a.relay.host} --domain ${name} --relay-ports ${a.ports.tls},${a.ports.http} --relay-fingerprint ${a.relay.fingerprint}${a.relay.port !== 22 ? ` --relay-port ${a.relay.port}` : ''}`);
771
+ return;
772
+ }
773
+ case 'remove-home': {
774
+ if (rest.length !== 1 || !DOMAIN.test(rest[0])) throw new Bad('relay remove-home NAME');
775
+ principal(P);
776
+ const r = await keeper(sys, P, conf, ['remove-home', rest[0]], { stream: true });
777
+ if (r.code !== 0) throw new Failed(`the relay did not remove ${rest[0]} (exit ${r.code})`);
778
+ return;
779
+ }
780
+ case 'homes': {
781
+ if (rest.length) throw new Bad('relay homes takes nothing');
782
+ const r = await keeper(sys, P, conf, ['homes'], { stream: true });
783
+ if (r.code !== 0) throw new Failed(`the relay answered with exit ${r.code}`);
784
+ return;
785
+ }
552
786
  case 'forget-setup-key': return forgetSetupKey(sys, P, conf);
553
787
  case 'status': case 'repair': case 'update-os': {
554
788
  if (rest.length && !(verb === 'update-os' && rest.length === 1 && rest[0] === '--reboot')) throw new Bad(`relay ${verb} takes nothing`);
@@ -561,9 +795,11 @@ export async function relayCommand(args, sys, P = PATHS) {
561
795
  if (!/^\d{1,4}\.\d{1,4}\.\d{1,6}(-[0-9A-Za-z.-]{1,40})?$/.test(version ?? '')) throw new Bad('relay update-relay [X.Y.Z]');
562
796
  const r = await keeper(sys, P, conf, ['update-relay', version], { stream: true });
563
797
  if (r.code !== 0) throw new Failed(`the relay did not update (exit ${r.code})`);
798
+ /* Said to the updater (keepRelayCurrent): this generation is the owner's choice now, its fixes come by themselves. */
799
+ try { const done = P.relayDone ?? '/var/lib/clavarium/update/relay-version'; writeFileSync(`${done}.new`, `${version}\n`); renameSync(`${done}.new`, done); } catch { /* the updater asks again: no harm */ }
564
800
  return;
565
801
  }
566
- default: throw new Bad('usage: sudo clavarium relay status | repair | update-os [--reboot] | update-relay [X.Y.Z] | forget-setup-key');
802
+ default: throw new Bad('usage: sudo clavarium relay status | repair | update-os [--reboot] | update-relay [X.Y.Z] | forget-setup-key | homes | invite NAME | add-home NAME --key KEY | remove-home NAME');
567
803
  }
568
804
  }
569
805
 
@@ -601,6 +837,13 @@ export function realSys() {
601
837
  timer = setTimeout(done, ms);
602
838
  try { tty = createReadStream('/dev/tty'); tty.on('data', (d) => { if (d.includes(10) || d.includes(13)) done(); }); tty.on('error', () => {}); } catch { /* no keyboard: the timer alone */ }
603
839
  }),
840
+ /* JSON to an address in https, its certificate checked; never a redirect. */
841
+ post: async (url, body) => {
842
+ const r = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), redirect: 'error', signal: AbortSignal.timeout(60_000) });
843
+ let json = null;
844
+ try { json = await r.json(); } catch { /* not JSON */ }
845
+ return { status: r.status, body: json };
846
+ },
604
847
  hasKeyboard: () => { try { closeSync(openSync('/dev/tty', 'r')); return true; } catch { return false; } },
605
848
  askLine: async (question) => {
606
849
  let fd;