Compare commits
267
Commits
v1.3.4
...
v1.7.45-alpha
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ec6ca98c1 | ||
|
|
dffa7e99bb | ||
|
|
8f83b37d51 | ||
|
|
4d05705315 | ||
|
|
05b41f8946 | ||
|
|
ed73e4709b | ||
|
|
0bd4e49a8c | ||
|
|
310c709aba | ||
|
|
dbf755e908 | ||
|
|
2572688468 | ||
|
|
4bf35f95e6 | ||
|
|
4edc420459 | ||
|
|
7af048cc1a | ||
|
|
2843cc1e84 | ||
|
|
c5ea41d0cb | ||
|
|
9d42645aa3 | ||
|
|
f6efe2f356 | ||
|
|
c4efb30382 | ||
|
|
cd6f8bad70 | ||
|
|
9f3d66e24e | ||
|
|
a272a79706 | ||
|
|
694e5b0a9d | ||
|
|
0f1ad47aec | ||
|
|
06dcdafda4 | ||
|
|
92612ddc70 | ||
|
|
353825b66c | ||
|
|
12f93cc15e | ||
|
|
4faac9cb74 | ||
|
|
b62b731db0 | ||
|
|
6c8cb50679 | ||
|
|
28e38a36a9 | ||
|
|
d9d5fa65e5 | ||
|
|
980c1b25f4 | ||
|
|
7e62ea07f7 | ||
|
|
576ff1a6de | ||
|
|
49b98e0271 | ||
|
|
702b5d64d3 | ||
|
|
1ad889608f | ||
|
|
0ea4f96de9 | ||
|
|
a8158b1ef5 | ||
|
|
cd69c3b2f6 | ||
|
|
39dd1d9dcc | ||
|
|
5baced5f5b | ||
|
|
cad63bdd76 | ||
|
|
bb2e3fab42 | ||
|
|
6a5fab709a | ||
|
|
2a2f10608b | ||
|
|
7257f72f4a | ||
|
|
30b31b3670 | ||
|
|
28819d1197 | ||
|
|
80765c5755 | ||
|
|
8acf7d1112 | ||
|
|
c396be8068 | ||
|
|
236a2dee85 | ||
|
|
758d3e47d8 | ||
|
|
3e9c192b48 | ||
|
|
ba8bd0bb86 | ||
|
|
6a0809d386 | ||
|
|
81c1613040 | ||
|
|
89199bb03b | ||
|
|
ca299e70e8 | ||
|
|
40a6eaca72 | ||
|
|
e103925a4e | ||
|
|
56af57a6f8 | ||
|
|
919055f3f1 | ||
|
|
0ac673deb4 | ||
|
|
d1bcf271f9 | ||
|
|
85417de952 | ||
|
|
b8d084368e | ||
|
|
36a6101026 | ||
|
|
cfc98c600e | ||
|
|
e206e1fc94 | ||
|
|
9cf1177b73 | ||
|
|
a7048f6d8e | ||
|
|
06feb85aa5 | ||
|
|
aa0677be57 | ||
|
|
974fce5870 | ||
|
|
682b93f2d6 | ||
|
|
18f0929614 | ||
|
|
1709149ebd | ||
|
|
2664074210 | ||
|
|
9868991900 | ||
|
|
0d15ca588a | ||
|
|
1c1416cc1a | ||
|
|
1735098d81 | ||
|
|
b5da6875d7 | ||
|
|
4b6a088e38 | ||
|
|
f8304aed90 | ||
|
|
40f76013dc | ||
|
|
4e2c6d210b | ||
|
|
7d8ddcccef | ||
|
|
f853d14421 | ||
|
|
f2360d570f | ||
|
|
749234b8b0 | ||
|
|
be8e5ee46b | ||
|
|
687c216e65 | ||
|
|
26630e5ffd | ||
|
|
fee690744d | ||
|
|
79f4ec4bde | ||
|
|
61bfdac7cc | ||
|
|
1e648800ad | ||
|
|
8a2cabdba9 | ||
|
|
4d1bd063e8 | ||
|
|
b8397b5ecb | ||
|
|
1e7df417a4 | ||
|
|
3db71adb55 | ||
|
|
66b4e2b313 | ||
|
|
0ea9ad9adb | ||
|
|
a9d8895395 | ||
|
|
508f8e1786 | ||
|
|
0399f45fb2 | ||
|
|
6a4d48b49f | ||
|
|
6b9b7a5a9c | ||
|
|
66785c00dd | ||
|
|
d9411c3325 | ||
|
|
00a86e6ecf | ||
|
|
361ebea85c | ||
|
|
fe963a1a8b | ||
|
|
3441ea2459 | ||
|
|
3127d50091 | ||
|
|
8466cd14f0 | ||
|
|
036db76773 | ||
|
|
da3012b75a | ||
|
|
659d44a761 | ||
|
|
4cb5c07b1b | ||
|
|
3018849cc8 | ||
|
|
c1bb7b675d | ||
|
|
73b49bd5bf | ||
|
|
423c2f8201 | ||
|
|
3ce7bb6c18 | ||
|
|
8dd57bcbb1 | ||
|
|
8fade7c435 | ||
|
|
fd8e93235f | ||
|
|
668ed1590c | ||
|
|
b77b031b8e | ||
|
|
f756365935 | ||
|
|
60758263f3 | ||
|
|
6399b6881e | ||
|
|
ab85c2e361 | ||
|
|
616f62ce4f | ||
|
|
5d2fac690e | ||
|
|
eac583c15e | ||
|
|
d63cd92bee | ||
|
|
2e8417e39b | ||
|
|
2f327183eb | ||
|
|
6ddce90e45 | ||
|
|
d80b8ce513 | ||
|
|
8b88c45262 | ||
|
|
dbd19006f2 | ||
|
|
ba825c13a5 | ||
|
|
1fdb5e5cf2 | ||
|
|
274ed008fe | ||
|
|
6b42bfd503 | ||
|
|
30a7f73ead | ||
|
|
46350f48b6 | ||
|
|
7655a5971b | ||
|
|
f5c581a725 | ||
|
|
b614c5c694 | ||
|
|
3a52c766ac | ||
|
|
7e4fed7967 | ||
|
|
cd8763f468 | ||
|
|
dbafa12596 | ||
|
|
1736f6f99e | ||
|
|
0c02d06a66 | ||
|
|
6760d11a57 | ||
|
|
5616bb74e6 | ||
|
|
164f938982 | ||
|
|
d514e0e5e4 | ||
|
|
bdacc06a2b | ||
|
|
8ef7af985d | ||
|
|
002032b7da | ||
|
|
bc3729d99f | ||
|
|
649433b7fd | ||
|
|
a360f90647 | ||
|
|
ab927afbaa | ||
|
|
f94f5da6ee | ||
|
|
019144903c | ||
|
|
dce5084451 | ||
|
|
e8a729a4c7 | ||
|
|
77eb1b907b | ||
|
|
de1b25cc78 | ||
|
|
d865136631 | ||
|
|
36cd3f4e7d | ||
|
|
3ed9243c50 | ||
|
|
18284e1592 | ||
|
|
29ff413559 | ||
|
|
0f71013952 | ||
|
|
98b570679d | ||
|
|
d378d94a05 | ||
|
|
a1f70f9c18 | ||
|
|
2d11f262dd | ||
|
|
877b3e4168 | ||
|
|
b0656b068f | ||
|
|
f586cbc499 | ||
|
|
3078d4b69e | ||
|
|
1147dbd882 | ||
|
|
e08c0d0b9f | ||
|
|
a97128bfd2 | ||
|
|
6cd67df575 | ||
|
|
8d8130109d | ||
|
|
485c4d5d98 | ||
|
|
4cab118cb2 | ||
|
|
cd08fd3c9e | ||
|
|
aae3391ce8 | ||
|
|
bb14490fb7 | ||
|
|
24f122f35a | ||
|
|
8d82666c82 | ||
|
|
2c98bdd19d | ||
|
|
0995aa1033 | ||
|
|
abf6ca000d | ||
|
|
c421fdb064 | ||
|
|
918fec0af7 | ||
|
|
548107eb8b | ||
|
|
a3217a9db4 | ||
|
|
8ffb10d7e0 | ||
|
|
401a44b40a | ||
|
|
dd5c3783ed | ||
|
|
7ca973e7b1 | ||
|
|
a147db9b70 | ||
|
|
68b02359dc | ||
|
|
b7ff0b1d38 | ||
|
|
b9044e58c7 | ||
|
|
067a3ed106 | ||
|
|
88bdba19db | ||
|
|
f8cf0afbfc | ||
|
|
e8251b5bad | ||
|
|
ca2ddc889e | ||
|
|
2517379ac3 | ||
|
|
b8a09b448b | ||
|
|
a8c6a36cd1 | ||
|
|
d0b9f168f4 | ||
|
|
07dff3e4ca | ||
|
|
b30f41f3d7 | ||
|
|
a029a4c948 | ||
|
|
ef69434364 | ||
|
|
3ee5dd6715 | ||
|
|
eebdade0d4 | ||
|
|
aa2a13d510 | ||
|
|
d7286d5f63 | ||
|
|
5f40cd2af4 | ||
|
|
42c29b99e2 | ||
|
|
b0907c48b2 | ||
|
|
6c1f316956 | ||
|
|
8e094c7ce9 | ||
|
|
5c117f5718 | ||
|
|
43ac2975dc | ||
|
|
a34075287d | ||
|
|
0ecfdd1d01 | ||
|
|
4fc6c103ba | ||
|
|
b0e5e8c00e | ||
|
|
9eb5d8cee0 | ||
|
|
d8d472f72c | ||
|
|
7a78d750f4 | ||
|
|
4c41c38b3b | ||
|
|
fddbf8ccf7 | ||
|
|
9438bad7fc | ||
|
|
209c2dcd6c | ||
|
|
42034c0ff9 | ||
|
|
54cb23f07b | ||
|
|
0760819af4 | ||
|
|
e5f695c1c4 | ||
|
|
637818c9f1 | ||
|
|
712e1c8b25 | ||
|
|
3e3dfafdfc | ||
|
|
0fca903188 | ||
|
|
1508cc3e13 | ||
|
|
24e537c027 |
@@ -1,154 +0,0 @@
|
||||
name: Build Archipelago ISO
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-iso:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
# Direct clone using stored credentials (actions/checkout token is broken)
|
||||
cd /home/archipelago/archy && git fetch origin main && git reset --hard origin/main
|
||||
echo "=== Source at commit: $(git log --oneline -1) ==="
|
||||
echo "=== Syncing to workspace ==="
|
||||
rsync -a --delete --exclude='.git' --exclude='target/' --exclude='node_modules/' \
|
||||
/home/archipelago/archy/ "$GITHUB_WORKSPACE/" || cp -a /home/archipelago/archy/* "$GITHUB_WORKSPACE/"
|
||||
cd "$GITHUB_WORKSPACE"
|
||||
echo "=== Workspace version: $(grep '^version' core/archipelago/Cargo.toml) ==="
|
||||
echo "=== Key files ==="
|
||||
echo " first-boot: $([ -f scripts/first-boot-containers.sh ] && echo PRESENT || echo MISSING)"
|
||||
echo " Cargo.toml: $(grep '^version' core/archipelago/Cargo.toml)"
|
||||
echo " package.json: $(grep '\"version\"' neode-ui/package.json | head -1)"
|
||||
|
||||
- name: Build backend
|
||||
run: |
|
||||
source $HOME/.cargo/env 2>/dev/null || true
|
||||
cargo build --release --manifest-path core/Cargo.toml
|
||||
|
||||
- name: Build frontend
|
||||
run: |
|
||||
rm -rf web/dist/neode-ui
|
||||
cd neode-ui && npm ci && npm run build
|
||||
|
||||
- name: Type check frontend
|
||||
run: cd neode-ui && npx vue-tsc -b --noEmit
|
||||
|
||||
- name: Run frontend tests
|
||||
run: cd neode-ui && npx vitest run
|
||||
|
||||
- name: Cache Debian Live ISO
|
||||
run: |
|
||||
WORK_DIR="image-recipe/build/auto-installer"
|
||||
mkdir -p "$WORK_DIR"
|
||||
CACHED="/home/archipelago/archy/image-recipe/build/auto-installer/debian-live-installer.iso"
|
||||
if [ -f "$CACHED" ] && [ ! -f "$WORK_DIR/debian-live-installer.iso" ]; then
|
||||
cp "$CACHED" "$WORK_DIR/debian-live-installer.iso"
|
||||
echo "Cached Debian Live ISO copied ($(du -h "$WORK_DIR/debian-live-installer.iso" | cut -f1))"
|
||||
fi
|
||||
|
||||
- name: Configure root podman for insecure registry
|
||||
run: |
|
||||
sudo mkdir -p /etc/containers/registries.conf.d
|
||||
echo '[[registry]]
|
||||
location = "80.71.235.15:3000"
|
||||
insecure = true' | sudo tee /etc/containers/registries.conf.d/archipelago.conf
|
||||
|
||||
- name: Include AIUI if available
|
||||
run: |
|
||||
# Copy AIUI from the deployed system (build server has it at /opt/archipelago/web-ui/aiui/)
|
||||
if [ -d "/opt/archipelago/web-ui/aiui" ] && [ -f "/opt/archipelago/web-ui/aiui/index.html" ]; then
|
||||
mkdir -p web/dist/neode-ui/aiui
|
||||
cp -r /opt/archipelago/web-ui/aiui/* web/dist/neode-ui/aiui/
|
||||
echo "AIUI included from /opt/archipelago/web-ui/aiui/"
|
||||
else
|
||||
echo "WARNING: AIUI not found on build server"
|
||||
fi
|
||||
|
||||
- name: Build unbundled ISO
|
||||
run: |
|
||||
cd image-recipe
|
||||
export ARCHIPELAGO_BIN="$(pwd)/../core/target/release/archipelago"
|
||||
ls -la "$ARCHIPELAGO_BIN" || echo "WARNING: binary not found"
|
||||
sudo -E UNBUNDLED=1 DEV_SERVER=localhost BUILD_FROM_SOURCE=0 \
|
||||
ARCHIPELAGO_BIN="$ARCHIPELAGO_BIN" \
|
||||
./build-auto-installer-iso.sh
|
||||
|
||||
- name: Copy to Builds
|
||||
run: |
|
||||
ISO=$(ls image-recipe/results/archipelago-installer-unbundled-*.iso 2>/dev/null | head -1)
|
||||
if [ -n "$ISO" ]; then
|
||||
DATE=$(date +%Y%m%d-%H%M)
|
||||
DEST="/var/lib/archipelago/filebrowser/Builds/archipelago-unbundled-${DATE}.iso"
|
||||
sudo cp "$ISO" "$DEST"
|
||||
sudo chown 1000:1000 "$DEST"
|
||||
echo "ISO: archipelago-unbundled-${DATE}.iso"
|
||||
echo "Size: $(du -h "$DEST" | cut -f1)"
|
||||
echo "SHA256: $(sha256sum "$DEST" | cut -d' ' -f1)"
|
||||
fi
|
||||
|
||||
- name: Build report
|
||||
if: always()
|
||||
continue-on-error: true
|
||||
run: |
|
||||
set +eo pipefail
|
||||
echo "══════════════════════════════════════════"
|
||||
echo "BUILD REPORT"
|
||||
echo "══════════════════════════════════════════"
|
||||
echo "Commit: $(git rev-parse --short HEAD) ($(git log -1 --format=%s))"
|
||||
echo "Branch: ${GITHUB_REF_NAME:-unknown}"
|
||||
echo "Date: $(date -u '+%Y-%m-%d %H:%M:%S UTC')"
|
||||
echo "Runner: $(hostname)"
|
||||
echo ""
|
||||
echo "── Artifacts ──"
|
||||
ls -lh image-recipe/results/*.iso 2>/dev/null || echo " No ISO produced"
|
||||
ls -lh /var/lib/archipelago/filebrowser/Builds/archipelago-unbundled-*.iso 2>/dev/null | tail -3
|
||||
echo ""
|
||||
echo "── Rootfs contents check ──"
|
||||
ROOTFS=$(ls image-recipe/build/auto-installer/archipelago-rootfs.tar 2>/dev/null) || true
|
||||
if [ -n "$ROOTFS" ]; then
|
||||
echo " rootfs.tar: $(sudo du -h "$ROOTFS" 2>/dev/null | cut -f1 || echo 'unknown')"
|
||||
echo " nginx config: $(sudo tar tf "$ROOTFS" ./etc/nginx/sites-available/archipelago 2>/dev/null && echo 'PRESENT' || echo 'MISSING')"
|
||||
echo " SSL cert: $(sudo tar tf "$ROOTFS" ./etc/archipelago/ssl/archipelago.crt 2>/dev/null && echo 'PRESENT' || echo 'MISSING')"
|
||||
echo " keyboard config: $(sudo tar tf "$ROOTFS" ./etc/default/keyboard 2>/dev/null && echo 'PRESENT' || echo 'MISSING')"
|
||||
echo " console-setup: $(sudo tar tf "$ROOTFS" ./etc/default/console-setup 2>/dev/null && echo 'PRESENT' || echo 'MISSING')"
|
||||
echo " kiosk launcher: $(sudo tar tf "$ROOTFS" ./usr/local/bin/archipelago-kiosk-launcher 2>/dev/null && echo 'PRESENT' || echo 'MISSING')"
|
||||
echo " logind lid: $(sudo tar tf "$ROOTFS" ./etc/systemd/logind.conf.d/lid-ignore.conf 2>/dev/null && echo 'PRESENT' || echo 'MISSING')"
|
||||
echo " backend binary: $(sudo tar tf "$ROOTFS" ./usr/local/bin/archipelago 2>/dev/null && echo 'PRESENT' || echo 'MISSING')"
|
||||
echo " web-ui index: $(sudo tar tf "$ROOTFS" ./opt/archipelago/web-ui/index.html 2>/dev/null && echo 'PRESENT' || echo 'MISSING')"
|
||||
echo " AIUI: $(sudo tar tf "$ROOTFS" ./opt/archipelago/web-ui/aiui/index.html 2>/dev/null && echo 'PRESENT' || echo 'MISSING')"
|
||||
echo " claude-api-proxy: $(sudo tar tf "$ROOTFS" ./opt/archipelago/claude-api-proxy.py 2>/dev/null && echo 'PRESENT' || echo 'MISSING')"
|
||||
else
|
||||
echo " rootfs.tar not found in workspace"
|
||||
fi
|
||||
echo ""
|
||||
echo "── ISO contents check ──"
|
||||
ISO=$(ls image-recipe/results/archipelago-installer-unbundled-*.iso 2>/dev/null | head -1) || true
|
||||
if [ -n "$ISO" ]; then
|
||||
echo " ISO size: $(sudo du -h "$ISO" 2>/dev/null | cut -f1 || echo 'unknown')"
|
||||
ISO_MOUNT=$(mktemp -d)
|
||||
if sudo mount -o loop,ro "$ISO" "$ISO_MOUNT" 2>/dev/null; then
|
||||
echo " auto-install.sh: $([ -f "$ISO_MOUNT/archipelago/auto-install.sh" ] && echo 'PRESENT' || echo 'MISSING')"
|
||||
echo " rootfs.tar: $([ -f "$ISO_MOUNT/archipelago/rootfs.tar" ] && echo "PRESENT ($(sudo du -h "$ISO_MOUNT/archipelago/rootfs.tar" 2>/dev/null | cut -f1))" || echo 'MISSING')"
|
||||
echo " backend bin: $([ -f "$ISO_MOUNT/archipelago/bin/archipelago" ] && echo "PRESENT ($(sudo du -h "$ISO_MOUNT/archipelago/bin/archipelago" 2>/dev/null | cut -f1))" || echo 'MISSING')"
|
||||
echo " frontend: $([ -f "$ISO_MOUNT/archipelago/web-ui/index.html" ] && echo 'PRESENT' || echo 'MISSING')"
|
||||
echo " image-versions: $([ -f "$ISO_MOUNT/archipelago/scripts/image-versions.sh" ] && echo 'PRESENT' || echo 'MISSING')"
|
||||
sudo umount "$ISO_MOUNT" 2>/dev/null || true
|
||||
else
|
||||
echo " Could not mount ISO for inspection"
|
||||
fi
|
||||
rmdir "$ISO_MOUNT" 2>/dev/null || true
|
||||
fi
|
||||
echo "══════════════════════════════════════════"
|
||||
|
||||
- name: Fix workspace permissions
|
||||
if: always()
|
||||
run: |
|
||||
sudo chown -R $(id -u):$(id -g) . 2>/dev/null || true
|
||||
sudo chmod -R u+rwX . 2>/dev/null || true
|
||||
sudo chown -R $(id -u):$(id -g) "$HOME/.cache/act" 2>/dev/null || true
|
||||
sudo chmod -R u+rwX "$HOME/.cache/act" 2>/dev/null || true
|
||||
@@ -1,63 +0,0 @@
|
||||
name: Container Orchestration Tests
|
||||
on:
|
||||
push:
|
||||
branches: [dev-iso, main]
|
||||
paths:
|
||||
- 'core/archipelago/src/**'
|
||||
- 'core/container/src/**'
|
||||
- 'scripts/container-*.sh'
|
||||
- 'scripts/reconcile-*.sh'
|
||||
- 'scripts/image-versions.sh'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
unit-tests:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Cache cargo registry
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
core/target
|
||||
key: cargo-test-${{ hashFiles('core/Cargo.lock') }}
|
||||
|
||||
- name: Run orchestration unit tests
|
||||
working-directory: core
|
||||
run: |
|
||||
source $HOME/.cargo/env 2>/dev/null || true
|
||||
echo "=== Container crate tests ==="
|
||||
cargo test -p archipelago-container --no-fail-fast 2>&1
|
||||
|
||||
echo ""
|
||||
echo "=== Orchestration integration tests ==="
|
||||
cargo test --test orchestration_tests --no-fail-fast 2>&1
|
||||
|
||||
- name: Verify cargo check (full crate)
|
||||
working-directory: core
|
||||
run: |
|
||||
source $HOME/.cargo/env 2>/dev/null || true
|
||||
cargo check --release 2>&1
|
||||
|
||||
smoke-tests:
|
||||
runs-on: ubuntu-latest
|
||||
needs: unit-tests
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Run container smoke tests on .228
|
||||
env:
|
||||
ARCHIPELAGO_SSH_KEY: ~/.ssh/archipelago-deploy
|
||||
run: |
|
||||
# Only run if SSH key exists (CI runner has deploy access)
|
||||
if [ -f "$ARCHIPELAGO_SSH_KEY" ]; then
|
||||
bash scripts/dev-container-test.sh --once
|
||||
else
|
||||
echo "⚠ SSH key not available — skipping live smoke tests"
|
||||
echo " To enable: add archipelago-deploy key to CI runner"
|
||||
fi
|
||||
@@ -73,3 +73,7 @@ loop/loop.log.bak
|
||||
# Separate repos nested in tree
|
||||
web/
|
||||
|
||||
._*
|
||||
|
||||
# Resilience harness reports (generated, contains session cookies)
|
||||
scripts/resilience/reports/
|
||||
|
||||
@@ -11,8 +11,8 @@ android {
|
||||
applicationId = "com.archipelago.app"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 1
|
||||
versionName = "0.1.0"
|
||||
versionCode = 6
|
||||
versionName = "0.4.2"
|
||||
|
||||
vectorDrawables {
|
||||
useSupportLibrary = true
|
||||
|
||||
@@ -32,6 +32,9 @@ class InputWebSocket(
|
||||
private var password: String = ""
|
||||
private var sessionCookie: String? = null
|
||||
|
||||
/** Player ID for arcade mode (0 = broadcast, 1 = P1, 2 = P2) */
|
||||
var playerId: Int = 0
|
||||
|
||||
private val _state = MutableStateFlow(ConnectionState.DISCONNECTED)
|
||||
val state: StateFlow<ConnectionState> = _state
|
||||
|
||||
@@ -109,10 +112,11 @@ class InputWebSocket(
|
||||
}
|
||||
|
||||
private fun doConnect() {
|
||||
val basePath = "/ws/remote-input" + if (playerId > 0) "?p=$playerId" else ""
|
||||
val wsUrl = serverUrl
|
||||
.replace("https://", "wss://")
|
||||
.replace("http://", "ws://")
|
||||
.trimEnd('/') + "/ws/remote-input"
|
||||
.trimEnd('/') + basePath
|
||||
|
||||
val reqBuilder = Request.Builder().url(wsUrl)
|
||||
sessionCookie?.let { reqBuilder.header("Cookie", "session=$it") }
|
||||
@@ -160,7 +164,8 @@ class InputWebSocket(
|
||||
// ─── Input senders ──────────────────────────────────────────
|
||||
|
||||
fun sendKey(key: String) {
|
||||
ws?.send("""{"t":"k","k":"$key"}""")
|
||||
val pField = if (playerId > 0) ""","p":$playerId""" else ""
|
||||
ws?.send("""{"t":"k","k":"$key"$pField}""")
|
||||
}
|
||||
|
||||
fun sendMouseMove(dx: Int, dy: Int) {
|
||||
|
||||
@@ -101,8 +101,10 @@ fun paletteFor(style: ControllerStyle) = if (style == ControllerStyle.CLASSIC) C
|
||||
@Composable
|
||||
fun NESController(
|
||||
style: ControllerStyle = ControllerStyle.CLASSIC,
|
||||
playerId: Int = 0,
|
||||
onKey: (String) -> Unit,
|
||||
onMenu: () -> Unit,
|
||||
onPlayerToggle: () -> Unit = {},
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val c = paletteFor(style)
|
||||
@@ -184,29 +186,33 @@ fun NESController(
|
||||
}
|
||||
}
|
||||
|
||||
// A/B Buttons in inlay (same size as D-pad inlay, more right margin)
|
||||
// A/B/C Buttons in inlay — triangle: C top, B+A bottom
|
||||
Inlay(c, Modifier.align(Alignment.CenterEnd).padding(end = 48.dp).size(140.dp)) {
|
||||
Row(
|
||||
Column(
|
||||
Modifier.fillMaxSize(),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
RoundBtn(c, 52.dp) { onKey("Escape") }
|
||||
Text("B", color = c.labelMuted, fontSize = 9.sp, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
RoundBtn(c, 52.dp) { onKey("Return") }
|
||||
Text("A", color = c.labelMuted, fontSize = 9.sp, fontWeight = FontWeight.Bold)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// C on top (white)
|
||||
ColorBtn(Color(0xFF888888), Color(0xFFAAAAAA), 44.dp) { onKey("c") }
|
||||
Spacer(Modifier.height(6.dp))
|
||||
// B + A on bottom row
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
ColorBtn(Color(0xFF3B82F6), Color(0xFF60A5FA), 44.dp) { onKey("b") }
|
||||
ColorBtn(Color(0xFFEA580C), Color(0xFFFB923C), 44.dp) { onKey("a") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Settings button (bottom center)
|
||||
SettingsBtn(c, Modifier.align(Alignment.BottomCenter).padding(bottom = 4.dp), onMenu)
|
||||
// Player toggle + settings (bottom center)
|
||||
Row(
|
||||
Modifier.align(Alignment.BottomCenter).padding(bottom = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
PlayerPill(c, playerId, onPlayerToggle)
|
||||
SettingsBtn(c, Modifier, onMenu)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,6 +353,28 @@ fun RoundBtn(c: NESPalette, sz: Dp = 52.dp, onClick: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Colored round button — custom color instead of palette */
|
||||
@Composable
|
||||
fun ColorBtn(color: Color, pressColor: Color, sz: Dp = 48.dp, onClick: () -> Unit) {
|
||||
var p by remember { mutableStateOf(false) }
|
||||
Box(
|
||||
Modifier
|
||||
.size(sz)
|
||||
.shadow(if (p) 1.dp else 4.dp, CircleShape)
|
||||
.clip(CircleShape)
|
||||
.background(Brush.verticalGradient(
|
||||
if (p) listOf(pressColor, color.copy(alpha = 0.85f))
|
||||
else listOf(color, color.copy(alpha = 0.8f))
|
||||
))
|
||||
.pointerInput(Unit) { detectTapGestures(onPress = { p = true; onClick(); tryAwaitRelease(); p = false }) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (!p) Box(Modifier.fillMaxSize().clip(CircleShape).background(
|
||||
Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.18f), Color.Transparent))
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/** START/SELECT capsule */
|
||||
@Composable
|
||||
fun CapsuleBtn(label: String, c: NESPalette, w: Dp = 64.dp, h: Dp = 28.dp, onClick: () -> Unit) {
|
||||
@@ -370,19 +398,39 @@ fun CapsuleBtn(label: String, c: NESPalette, w: Dp = 64.dp, h: Dp = 28.dp, onCli
|
||||
}
|
||||
}
|
||||
|
||||
/** Small settings gear button */
|
||||
/** Settings gear button (48dp — large enough for easy tap on TV) */
|
||||
@Composable
|
||||
fun SettingsBtn(c: NESPalette, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
var p by remember { mutableStateOf(false) }
|
||||
Box(
|
||||
modifier = modifier
|
||||
.size(24.dp)
|
||||
.size(48.dp)
|
||||
.clip(CircleShape)
|
||||
.background(if (p) c.capsulePress else c.capsule)
|
||||
.pointerInput(Unit) { detectTapGestures(onPress = { p = true; onClick(); tryAwaitRelease(); p = false }) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Default.Settings, "Settings", Modifier.size(14.dp), tint = c.labelMuted)
|
||||
Icon(Icons.Default.Settings, "Settings", Modifier.size(28.dp), tint = c.labelMuted)
|
||||
}
|
||||
}
|
||||
|
||||
/** Player ID toggle pill (P1/P2/ALL) */
|
||||
@Composable
|
||||
fun PlayerPill(c: NESPalette, playerId: Int, onToggle: () -> Unit) {
|
||||
val label = when (playerId) { 1 -> "P1"; 2 -> "P2"; else -> "ALL" }
|
||||
val accent = when (playerId) { 1 -> Color(0xFF00F0FF); 2 -> Color(0xFFFF0080); else -> c.labelMuted }
|
||||
var p by remember { mutableStateOf(false) }
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.height(28.dp)
|
||||
.width(44.dp)
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(if (p) c.capsulePress else c.capsule)
|
||||
.border(1.dp, accent.copy(alpha = 0.5f), RoundedCornerShape(6.dp))
|
||||
.pointerInput(Unit) { detectTapGestures(onPress = { p = true; onToggle(); tryAwaitRelease(); p = false }) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(label, color = accent, fontSize = 10.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -55,9 +55,15 @@ fun NESKeyboard(
|
||||
var layer by remember { mutableStateOf(NKLayer.ALPHA) }
|
||||
var shifted by remember { mutableStateOf(false) }
|
||||
var capsLock by remember { mutableStateOf(false) }
|
||||
var ctrlHeld by remember { mutableStateOf(false) }
|
||||
val up = shifted || capsLock
|
||||
|
||||
fun emit(k: String) { onKey(k); if (shifted && !capsLock) shifted = false }
|
||||
fun emit(k: String) {
|
||||
val key = if (ctrlHeld) "ctrl+$k" else k
|
||||
onKey(key)
|
||||
if (shifted && !capsLock) shifted = false
|
||||
if (ctrlHeld) ctrlHeld = false
|
||||
}
|
||||
fun ch(cc: String) { emit(if (up && layer == NKLayer.ALPHA) "shift+$cc" else cc) }
|
||||
|
||||
// NES body wrapping keyboard
|
||||
@@ -113,9 +119,12 @@ fun NESKeyboard(
|
||||
NKey(if (layer == NKLayer.ALPHA) "123" else "ABC", Modifier.weight(1.4f), keyBg, keyBgP, keyTxt) {
|
||||
layer = if (layer == NKLayer.ALPHA) NKLayer.NUM else NKLayer.ALPHA; shifted = false; capsLock = false
|
||||
}
|
||||
NKey(",", Modifier.weight(1f), keyBg, keyBgP, keyTxt) { emit("comma") }
|
||||
NKey("space", Modifier.weight(5f), keyBg, keyBgP, keyTxt, 12) { emit("space") }
|
||||
NKey(".", Modifier.weight(1f), keyBg, keyBgP, keyTxt) { emit("period") }
|
||||
NKey("Ctrl", Modifier.weight(1.2f), keyBg, keyBgP, if (ctrlHeld) accent else keyTxt, 11) {
|
||||
ctrlHeld = !ctrlHeld
|
||||
}
|
||||
NKey(",", Modifier.weight(0.8f), keyBg, keyBgP, keyTxt) { emit("comma") }
|
||||
NKey("space", Modifier.weight(4f), keyBg, keyBgP, keyTxt, 12) { emit("space") }
|
||||
NKey(".", Modifier.weight(0.8f), keyBg, keyBgP, keyTxt) { emit("period") }
|
||||
NKey("\u23CE", Modifier.weight(1.4f), keyBg, keyBgP, accent, 15) { emit("Return") }
|
||||
}
|
||||
}
|
||||
|
||||
+22
-10
@@ -36,11 +36,13 @@ import com.archipelago.app.ui.theme.NES
|
||||
@Composable
|
||||
fun NESPortraitController(
|
||||
style: ControllerStyle = ControllerStyle.CLASSIC,
|
||||
playerId: Int = 0,
|
||||
onKey: (String) -> Unit,
|
||||
onMouseMove: (Int, Int) -> Unit = { _, _ -> },
|
||||
onMouseClick: (Int) -> Unit = { _ -> },
|
||||
onMouseScroll: (Int) -> Unit = { _ -> },
|
||||
onMenu: () -> Unit,
|
||||
onPlayerToggle: () -> Unit = {},
|
||||
) {
|
||||
val c = paletteFor(style)
|
||||
val isClassic = style == ControllerStyle.CLASSIC
|
||||
@@ -111,16 +113,18 @@ fun NESPortraitController(
|
||||
|
||||
Spacer(Modifier.height(12.dp))
|
||||
|
||||
// A/B Buttons
|
||||
// A/B/C Buttons — triangle: C top, B+A bottom
|
||||
Inlay(c, Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
RoundBtn(c, 52.dp) { onKey("Escape") }
|
||||
Spacer(Modifier.width(24.dp))
|
||||
RoundBtn(c, 52.dp) { onKey("Return") }
|
||||
ColorBtn(Color(0xFF888888), Color(0xFFAAAAAA), 46.dp) { onKey("c") }
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
ColorBtn(Color(0xFF3B82F6), Color(0xFF60A5FA), 46.dp) { onKey("b") }
|
||||
ColorBtn(Color(0xFFEA580C), Color(0xFFFB923C), 46.dp) { onKey("a") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,8 +143,16 @@ fun NESPortraitController(
|
||||
|
||||
Spacer(Modifier.height(6.dp))
|
||||
|
||||
// Settings
|
||||
SettingsBtn(c, Modifier, onMenu)
|
||||
// Player toggle + Settings
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
PlayerPill(c, playerId, onPlayerToggle)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
SettingsBtn(c, Modifier, onMenu)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,8 +59,14 @@ fun RemoteInputScreen(onBack: () -> Unit) {
|
||||
var isGamepadMode by remember { mutableStateOf(true) }
|
||||
var showModal by remember { mutableStateOf(false) }
|
||||
var controllerStyle by remember { mutableStateOf(ControllerStyle.CLASSIC) }
|
||||
var playerId by remember { mutableStateOf(0) } // 0 = broadcast, 1 = P1, 2 = P2
|
||||
|
||||
val ws = remember { InputWebSocket(scope) }
|
||||
|
||||
fun togglePlayer() {
|
||||
playerId = when (playerId) { 0 -> 1; 1 -> 2; else -> 0 }
|
||||
ws.playerId = playerId
|
||||
}
|
||||
val connectionState by ws.state.collectAsState()
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
|
||||
@@ -98,32 +104,44 @@ fun RemoteInputScreen(onBack: () -> Unit) {
|
||||
when {
|
||||
isGamepadMode && isLandscape -> NESController(
|
||||
style = controllerStyle,
|
||||
playerId = playerId,
|
||||
onKey = { ws.sendKey(it) },
|
||||
onMenu = { showModal = true },
|
||||
onPlayerToggle = ::togglePlayer,
|
||||
)
|
||||
isGamepadMode && !isLandscape -> NESPortraitController(
|
||||
style = controllerStyle,
|
||||
playerId = playerId,
|
||||
onKey = { ws.sendKey(it) },
|
||||
onMouseMove = { dx, dy -> ws.sendMouseMove(dx, dy) },
|
||||
onMouseClick = { ws.sendClick(it) },
|
||||
onMouseScroll = { ws.sendScroll(it) },
|
||||
onMenu = { showModal = true },
|
||||
onPlayerToggle = ::togglePlayer,
|
||||
)
|
||||
else -> {
|
||||
// Keyboard mode: trackpad fills top, keyboard pinned bottom
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
Trackpad(
|
||||
onMove = { dx, dy -> ws.sendMouseMove(dx, dy) },
|
||||
onClick = { ws.sendClick(it) },
|
||||
onScroll = { ws.sendScroll(it) },
|
||||
onTwoFingerHold = { showModal = true },
|
||||
modifier = Modifier.fillMaxWidth().weight(1f)
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
NESKeyboard(
|
||||
style = controllerStyle,
|
||||
onKey = { ws.sendKey(it) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
Trackpad(
|
||||
onMove = { dx, dy -> ws.sendMouseMove(dx, dy) },
|
||||
onClick = { ws.sendClick(it) },
|
||||
onScroll = { ws.sendScroll(it) },
|
||||
onTwoFingerHold = { showModal = true },
|
||||
modifier = Modifier.fillMaxWidth().weight(1f)
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
NESKeyboard(
|
||||
style = controllerStyle,
|
||||
onKey = { ws.sendKey(it) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
// Settings icon top-right in keyboard mode
|
||||
com.archipelago.app.ui.components.SettingsBtn(
|
||||
c = com.archipelago.app.ui.components.paletteFor(controllerStyle),
|
||||
modifier = Modifier.align(Alignment.TopEnd).padding(8.dp),
|
||||
onClick = { showModal = true },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
-127
@@ -1,127 +0,0 @@
|
||||
# Quick Build Guide - Archipelago Beta Release
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Make sure you have:
|
||||
- Docker or Podman installed
|
||||
- `xorriso` installed (for ISO creation)
|
||||
- Access to dev server: archipelago@192.168.1.228
|
||||
|
||||
**Note**: When building on the target server with `sudo`, the script will automatically install missing dependencies (`xorriso`, `podman`).
|
||||
|
||||
## Build Auto-Installer ISO
|
||||
|
||||
### Option 1: Build on Target Server (Recommended)
|
||||
|
||||
```bash
|
||||
# SSH to target server
|
||||
ssh archipelago@192.168.1.228
|
||||
|
||||
# Navigate to project
|
||||
cd ~/archy/image-recipe
|
||||
|
||||
# Run build (auto-installs missing deps)
|
||||
sudo ./build-auto-installer-iso.sh
|
||||
|
||||
# Copy ISO back to your Mac
|
||||
# On your Mac:
|
||||
scp archipelago@192.168.1.228:~/archy/image-recipe/results/archipelago-auto-installer-*.iso .
|
||||
```
|
||||
|
||||
### Option 2: Build from Mac (requires Docker)
|
||||
|
||||
**Important**: This requires Docker Desktop installed on macOS.
|
||||
|
||||
```bash
|
||||
cd /Users/dorian/Projects/archy/image-recipe
|
||||
|
||||
# Capture current live server state
|
||||
DEV_SERVER=archipelago@192.168.1.228 ./build-auto-installer-iso.sh
|
||||
|
||||
# ISO will be created in: results/archipelago-auto-installer-*.iso
|
||||
```
|
||||
|
||||
## What the ISO Includes
|
||||
|
||||
✅ Complete Debian 12 root filesystem
|
||||
✅ Pre-built Archipelago backend
|
||||
✅ Pre-built frontend (web UI)
|
||||
✅ **Prepackaged container images** (Bitcoin Knots, LND, UIs, and other bundled apps), loaded on first boot
|
||||
✅ Nginx configuration (HTTPS ready)
|
||||
✅ Auto-installer that:
|
||||
- Detects internal disk
|
||||
- Creates partitions (EFI + root)
|
||||
- Extracts pre-built system
|
||||
- Installs bootloader
|
||||
- Reboots to working system
|
||||
|
||||
## What Users Need to Do Post-Install
|
||||
|
||||
1. **Start apps from the Web UI** – Container images are prepackaged and loaded on first boot. Bitcoin Knots + UI, LND + UI, and other bundled apps are ready to start from the Web UI without manual `podman run`. No need to pull or deploy core containers.
|
||||
|
||||
2. **Access Web UI** – Navigate to `http://[server-ip]`
|
||||
|
||||
## Testing the ISO
|
||||
|
||||
```bash
|
||||
# Use VirtualBox, QEMU, or real hardware
|
||||
qemu-system-x86_64 \
|
||||
-m 4G \
|
||||
-cdrom results/archipelago-auto-installer-*.iso \
|
||||
-hda archipelago-test.qcow2 \
|
||||
-boot d
|
||||
```
|
||||
|
||||
## Important Notes
|
||||
|
||||
⚠️ **The auto-installer will ERASE the target disk!**
|
||||
⚠️ Make sure to test on a non-production machine first
|
||||
⚠️ Minimum 20GB disk space required (500GB+ recommended for Bitcoin)
|
||||
|
||||
## Build from Source (Alternative)
|
||||
|
||||
If you want to build everything from scratch instead of capturing the live server:
|
||||
|
||||
```bash
|
||||
BUILD_FROM_SOURCE=1 ./build-auto-installer-iso.sh
|
||||
```
|
||||
|
||||
This will:
|
||||
- Build backend from Rust source
|
||||
- Build frontend with `npm run build`
|
||||
- Create fresh SSL certificates
|
||||
- Generate default configs
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**ISO won't boot:**
|
||||
- Ensure UEFI mode is enabled
|
||||
- Try disabling Secure Boot
|
||||
|
||||
**Installer hangs:**
|
||||
- Check the auto-start script fix is applied (see DEPLOYMENT.md)
|
||||
|
||||
**Backend doesn't detect containers:**
|
||||
- Verify `/etc/sudoers.d/archipelago-podman` exists
|
||||
- Check backend can run `sudo podman ps`
|
||||
|
||||
## Version Naming
|
||||
|
||||
ISOs are automatically named with timestamp:
|
||||
```
|
||||
archipelago-auto-installer-YYYYMMDD-HHMMSS.iso
|
||||
```
|
||||
|
||||
For releases, rename to:
|
||||
```
|
||||
archipelago-v0.1.0-beta.1.iso
|
||||
```
|
||||
|
||||
## Next Steps After Building
|
||||
|
||||
1. Test the ISO on VM
|
||||
2. Verify web UI loads
|
||||
3. Test container deployment
|
||||
4. Document any issues
|
||||
5. Tag the release in git
|
||||
6. Upload ISO to distribution point
|
||||
@@ -1,5 +1,24 @@
|
||||
# Changelog
|
||||
|
||||
## v1.7.45-alpha (2026-04-29)
|
||||
|
||||
- Bitcoin RPC auth is durable. The dashboard reliably connects across container restart, image update, and reboot. Was failing on registry-pulled images that shipped a stale baked-in password.
|
||||
- Multi-container apps show real install progress. IndeedHub (7), BTCPay (4), Mempool (3), Immich (3) — bar advances through Preparing → Pulling → Creating → Done instead of sitting at 0% until the very end.
|
||||
- Apps no longer disappear from the dashboard mid-install. The container scanner now respects in-flight installs and updates instead of evicting an entry while its containers are still being created.
|
||||
- IndeedHub installs cleanly on a fresh node. Five missing environment variables fixed; Nostr sign-in works on first install.
|
||||
- Tailscale install no longer fails with "executable not found". Container command was a malformed shell string; now a proper command array.
|
||||
- Removed three catalog entries that hung installs for ten minutes (dwn, endurain, ollama — no source images in our registries). Restored Nextcloud, sourced from docker.io.
|
||||
- Bitcoin Core update path uses the correct image name (was pulling from a non-existent path).
|
||||
- New ISO installs now allocate swap (sized to RAM, capped at 8GB, on the encrypted data partition). Without swap, container image builds and memory spikes were hitting OOM under load.
|
||||
|
||||
## v1.7.44-alpha (2026-04-28)
|
||||
|
||||
43de3b73 feat(orchestrator): complete container migration and release hardening
|
||||
ce39430b feat(self-update): sync and rebuild UI containers on OTA
|
||||
72dec5aa fix(lnd-ui): align container port across all specs
|
||||
83aacdf2 chore(release): archive ISO build recipes, tarball-only releases
|
||||
|
||||
|
||||
All notable changes to Archipelago will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
# CLAUDE.md — Archipelago (Archy)
|
||||
|
||||
## Overview
|
||||
|
||||
Archipelago is a **Bitcoin Node OS** — bootable, self-sovereign personal server. Flash to USB, install on hardware, manage via web UI.
|
||||
|
||||
**Stack**: Rust backend + Vue 3 + TypeScript (strict) + Vite 7 + Tailwind + Pinia + Podman on Debian 12
|
||||
**Version**: 1.3.0 | **Target**: x86_64 and ARM64
|
||||
|
||||
---
|
||||
|
||||
## Beta Freeze (2026-03-18)
|
||||
|
||||
**Phase 1: Feature Testing (internal) — WE ARE HERE**
|
||||
|
||||
Feature set is LOCKED. Only: bug fixes, security hardening, ISO build fixes, UI polish, testing.
|
||||
No new features, no new apps, no new deps, no scope creep.
|
||||
|
||||
Track: `docs/BETA-PROGRESS.md` | Checklist: `docs/BETA-RELEASE-CHECKLIST.md`
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```bash
|
||||
cd neode-ui && npm start # Local dev (mock backend :5959, Vite :8100)
|
||||
cd neode-ui && npm run build # Build (outputs to web/dist/neode-ui/)
|
||||
./scripts/deploy-to-target.sh --live # Deploy to live server (.228)
|
||||
```
|
||||
|
||||
## Infrastructure
|
||||
|
||||
| What | Where |
|
||||
|------|-------|
|
||||
| Dev server | `192.168.1.228` (SSH key: `~/.ssh/archipelago-deploy`) |
|
||||
| Secondary | `192.168.1.198` |
|
||||
| Git remote | `git.tx1138.com` (remote name: `tx1138`) |
|
||||
| App registry | `80.71.235.15:3000/archipelago/` (HTTP, insecure) |
|
||||
| CI runner | act_runner on .228, workflow: `.gitea/workflows/build-iso.yml` |
|
||||
| ISO builds | FileBrowser at `http://192.168.1.228:8083` → Builds/ |
|
||||
| SSH creds | Gitignored `scripts/deploy-config.sh` |
|
||||
| Web password | `password123` |
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Debian 12
|
||||
├── Podman (rootless, user archipelago)
|
||||
├── Nginx (80/443 → backend, app proxies)
|
||||
├── Rust Backend (core/) on 127.0.0.1:5678
|
||||
│ ├── core/archipelago/ — Binary, RPC, auth, sessions
|
||||
│ └── core/container/ — PodmanClient, manifests, health
|
||||
└── Vue.js UI (neode-ui/)
|
||||
├── src/api/rpc-client.ts — All backend communication
|
||||
├── src/stores/ — Pinia state
|
||||
├── src/views/ — Pages
|
||||
└── src/style.css — ALL styling (global classes only)
|
||||
```
|
||||
|
||||
**Data paths**: `/var/lib/archipelago/{app-id}/` (data), `/opt/archipelago/web-ui/` (frontend), `/usr/local/bin/archipelago` (binary)
|
||||
|
||||
## Critical Rules
|
||||
|
||||
1. **Never build Rust on macOS** — deploy script handles cross-compilation via rsync + remote build
|
||||
2. **Always deploy after changes** — `./scripts/deploy-to-target.sh --live`
|
||||
3. **Frontend builds to `web/dist/neode-ui/`** — not `neode-ui/dist/`
|
||||
4. **Container images**: `scripts/image-versions.sh` is the single source of truth. All scripts use `$*_IMAGE` variables, never hardcoded registry paths.
|
||||
5. **Type-check before committing** — `cd neode-ui && npx vue-tsc -b --noEmit`
|
||||
|
||||
## Frontend
|
||||
|
||||
- `<script setup lang="ts">` always — no Options API
|
||||
- Global CSS in `style.css` — **never inline Tailwind**
|
||||
- `.glass-button` for ALL buttons — `.gradient-button` is BANNED
|
||||
- `.glass-card` for containers, `.path-option-card` for interactive cards
|
||||
- `translateZ(0)` + `isolation: isolate` on glass elements (Chromium compositor fix)
|
||||
- Pinia for state, typed RPC client, handle loading/error/empty states
|
||||
|
||||
## Backend (Rust)
|
||||
|
||||
- No `unwrap()`/`expect()` — use `?` with `.context()`
|
||||
- `tracing` for logging, never `println!` or log secrets
|
||||
- Backend binds `127.0.0.1` only — nginx handles external access
|
||||
- Validate all input before path construction — reject `..`, `/`, null bytes
|
||||
- `tokio` runtime, timeouts on all external ops
|
||||
|
||||
## Security (Post-Pentest)
|
||||
|
||||
- RBAC: explicit method allowlists, never prefix matching
|
||||
- Session cookies: `SameSite=Lax; HttpOnly; Path=/`
|
||||
- Rate-limit auth endpoints, rotate tokens after privilege escalation
|
||||
- Validate redirect URLs with `isLocalRedirect()`, never `v-html` with user input
|
||||
- Container security: drop ALL caps, add only required, `no-new-privileges`, memory limits, health checks
|
||||
- See `.claude/rules/` for detailed crypto, API, container, and Bitcoin rules
|
||||
|
||||
## ISO Build & CI
|
||||
|
||||
CI builds on every push to `main` via git.tx1138.com Actions.
|
||||
|
||||
```bash
|
||||
# Manual build on .228:
|
||||
ssh archipelago@192.168.1.228
|
||||
cd ~/archy/image-recipe
|
||||
sudo UNBUNDLED=1 DEV_SERVER=localhost BUILD_FROM_SOURCE=0 ./build-auto-installer-iso.sh
|
||||
```
|
||||
|
||||
**Debugging fresh installs** — SSH in and check:
|
||||
```bash
|
||||
cat /var/log/archipelago-install.log # Full installer output
|
||||
cat /var/log/archipelago-first-boot-diagnostics.log # Service status, nginx, LUKS, etc.
|
||||
sudo archipelago-diagnostics # Re-run diagnostics anytime
|
||||
```
|
||||
|
||||
**Kiosk**: X11 on VT7, console on VT1. `Ctrl+Alt+F1` for terminal, `Ctrl+Alt+F7` for kiosk.
|
||||
Toggle: `sudo archipelago-kiosk enable|disable|toggle`
|
||||
|
||||
## App Integration Checklist
|
||||
|
||||
When adding/fixing apps, check ALL of these:
|
||||
- `core/archipelago/src/api/rpc/package/` — config, capabilities, deps
|
||||
- `neode-ui/src/views/marketplace/marketplaceData.ts` — marketplace entry
|
||||
- `image-recipe/configs/nginx-archipelago.conf` — proxy rules (HTTP + HTTPS)
|
||||
- `scripts/image-versions.sh` — pinned image version
|
||||
- `scripts/first-boot-containers.sh` — first boot creation
|
||||
- `scripts/deploy-to-target.sh` — deploy logic
|
||||
|
||||
## Git
|
||||
|
||||
Commits: `type: description` (`feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`, `perf:`)
|
||||
Push to: `git push tx1138 main`
|
||||
+1
-1
@@ -28,7 +28,7 @@ npm test # Run tests
|
||||
|
||||
### Backend (Rust)
|
||||
|
||||
Build on a Linux server (Debian 12), **not** macOS:
|
||||
Build on a Linux server (Debian 13), **not** macOS:
|
||||
|
||||
```bash
|
||||
cargo clippy --all-targets --all-features
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
# Demo Deployment via Portainer
|
||||
|
||||
Deploy Archipelago with the **mock backend** for demos. No real node required.
|
||||
|
||||
## Quick Deploy (Portainer)
|
||||
|
||||
1. In Portainer: **Stacks** → **Add stack**
|
||||
2. Name: `archy-demo`
|
||||
3. **Web editor** → paste contents of `docker-compose.demo.yml`
|
||||
4. Or **Build from repository**: use this repo URL and set Compose path to `docker-compose.demo.yml`
|
||||
5. Deploy
|
||||
|
||||
**Access:** http://your-host:4848
|
||||
|
||||
## Mock Backend
|
||||
|
||||
- Uses the Node.js mock backend (not the Rust backend)
|
||||
- Pre-loaded apps, fake data, simulated install/start/stop
|
||||
- **Login password:** `password123`
|
||||
|
||||
## Port
|
||||
|
||||
Default: **4848**. To change, edit the ports mapping in `docker-compose.demo.yml`:
|
||||
|
||||
```yaml
|
||||
ports:
|
||||
- "YOUR_PORT:80"
|
||||
```
|
||||
|
||||
## Chat (Claude AI)
|
||||
|
||||
Set `ANTHROPIC_API_KEY` in the Portainer stack environment to enable real AI chat:
|
||||
|
||||
1. In the stack editor, add under **Environment variables**:
|
||||
- `ANTHROPIC_API_KEY` = your Anthropic API key (starts with `sk-ant-api...`)
|
||||
2. Redeploy the stack
|
||||
|
||||
Without this key, chat shows a "not configured" error. The key is passed to the `neode-backend` container which proxies requests to `api.anthropic.com`.
|
||||
|
||||
## Dev Mode
|
||||
|
||||
`VITE_DEV_MODE=existing` skips setup/onboarding and goes straight to login. For other flows:
|
||||
|
||||
- `setup` – Password setup screen first
|
||||
- `onboarding` – Experimental onboarding flow
|
||||
- `existing` – Login only (default for demo)
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
**Archipelago** is a bootable personal server OS. Flash it to a USB drive, install on any x86_64 or ARM64 machine, and manage Bitcoin infrastructure, self-hosted apps, and decentralized identity through a glassmorphism web UI.
|
||||
|
||||
[](https://www.debian.org/)
|
||||
[](https://www.debian.org/)
|
||||
[](LICENSE)
|
||||
[](https://www.rust-lang.org/)
|
||||
[](https://vuejs.org/)
|
||||
@@ -81,7 +81,7 @@ Bitcoin (ThunderHub), Storage (FileBrowser, Immich, Nextcloud), Productivity (Pe
|
||||
|
||||
### Prerequisites
|
||||
- macOS or Linux for frontend development
|
||||
- Linux dev server (Debian 12) for backend builds — **never build Rust on macOS for Linux**
|
||||
- Linux dev server (Debian 13) for backend builds — **never build Rust on macOS for Linux**
|
||||
- Node.js 20+, Rust stable toolchain
|
||||
|
||||
### Frontend Development
|
||||
@@ -101,18 +101,24 @@ npm run build # Production build → web/dist/neode-ui/
|
||||
./scripts/deploy-to-target.sh --both # Deploy to both LAN servers
|
||||
```
|
||||
|
||||
### Build ISO
|
||||
### Release (tarball-only)
|
||||
|
||||
Releases ship as a backend binary and a frontend tarball referenced by
|
||||
`releases/manifest.json`. Nodes OTA-update via `scripts/self-update.sh`.
|
||||
|
||||
```bash
|
||||
ssh archipelago@<server>
|
||||
cd ~/archy/image-recipe
|
||||
sudo ./build-auto-installer-iso.sh
|
||||
./scripts/create-release.sh 1.2.3
|
||||
git push gitea-local main --tags
|
||||
git push gitea-vps2 main --tags
|
||||
```
|
||||
|
||||
ISO builds are archived under `image-recipe/_archived/` and not part of the
|
||||
release deliverable.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Debian 12 (Bookworm)
|
||||
Debian 13 (Trixie)
|
||||
├── Rootless Podman (30 containers, archy-net DNS)
|
||||
├── Nginx (reverse proxy, security headers, rate limiting)
|
||||
├── Rust Backend (JSON-RPC API on 127.0.0.1:5678)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Archipelago v1.0.0 Release Notes
|
||||
|
||||
**Release Date**: March 2026
|
||||
**Target Platform**: Debian 12 (Bookworm) — x86_64 and ARM64
|
||||
**Target Platform**: Debian 13 (Trixie) — x86_64 and ARM64
|
||||
|
||||
## What is Archipelago?
|
||||
|
||||
@@ -109,3 +109,4 @@ Archipelago is open source. To contribute:
|
||||
## License
|
||||
|
||||
MIT License. See `LICENSE` for details.
|
||||
# 2026-04-18 ISO build trigger
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# Archipelago App Catalog
|
||||
|
||||
Dynamic app catalog for the Archipelago marketplace. Nodes fetch this catalog to discover available apps.
|
||||
|
||||
## How it works
|
||||
|
||||
1. The Archipelago frontend fetches `catalog.json` from this repo
|
||||
2. Apps listed here appear in every node's app store automatically
|
||||
3. When a user installs an app, the backend pulls the Docker image and creates the container
|
||||
|
||||
## Adding a new app
|
||||
|
||||
Add an entry to `catalog.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "my-app",
|
||||
"title": "My App",
|
||||
"version": "1.0.0",
|
||||
"description": "What it does",
|
||||
"icon": "/assets/img/app-icons/my-app.svg",
|
||||
"author": "Author",
|
||||
"category": "data",
|
||||
"dockerImage": "git.tx1138.com/lfg2025/my-app:1.0.0",
|
||||
"repoUrl": "https://github.com/...",
|
||||
"containerConfig": {
|
||||
"ports": ["8080:8080"],
|
||||
"volumes": ["/var/lib/archipelago/my-app:/data"],
|
||||
"env": ["NODE_ENV=production"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For apps with hardcoded backend configs (Bitcoin, LND, etc.), `containerConfig` is optional.
|
||||
For new apps, include `containerConfig` so the backend knows how to create the container.
|
||||
|
||||
## Categories
|
||||
|
||||
money, commerce, data, home, nostr, networking, community, development, l484
|
||||
@@ -0,0 +1,270 @@
|
||||
{
|
||||
"version": 2,
|
||||
"updated": "2026-04-22T00:00:00Z",
|
||||
"registry": "146.59.87.168:3000/lfg2025",
|
||||
"featured": {
|
||||
"id": "indeedhub",
|
||||
"banner": "/assets/img/featured/indeedhub-banner.jpg",
|
||||
"headline": "Stream Sovereignty",
|
||||
"description": "Bitcoin documentaries with Nostr identity.",
|
||||
"tag": "NOSTR IDENTITY // YOUR NODE"
|
||||
},
|
||||
"apps": [
|
||||
{
|
||||
"id": "bitcoin-knots",
|
||||
"title": "Bitcoin Knots",
|
||||
"version": "28.1.0",
|
||||
"description": "Run a full Bitcoin node. Validate and relay blocks and transactions.",
|
||||
"icon": "/assets/img/app-icons/bitcoin-knots.webp",
|
||||
"author": "Bitcoin Knots",
|
||||
"category": "money",
|
||||
"tier": "core",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/bitcoin-knots:latest",
|
||||
"repoUrl": "https://github.com/bitcoinknots/bitcoin"
|
||||
},
|
||||
{
|
||||
"id": "bitcoin-core",
|
||||
"title": "Bitcoin Core",
|
||||
"version": "28.4",
|
||||
"description": "Reference implementation of the Bitcoin protocol. Run a full node validating and relaying blocks.",
|
||||
"icon": "/assets/img/app-icons/bitcoin-core.svg",
|
||||
"author": "Bitcoin Core contributors",
|
||||
"category": "money",
|
||||
"tier": "optional",
|
||||
"dockerImage": "docker.io/bitcoin/bitcoin:28.4",
|
||||
"repoUrl": "https://github.com/bitcoin/bitcoin"
|
||||
},
|
||||
{
|
||||
"id": "lnd",
|
||||
"title": "LND",
|
||||
"version": "0.18.4",
|
||||
"description": "Lightning Network Daemon. Fast Bitcoin payments through Lightning.",
|
||||
"icon": "/assets/img/app-icons/lnd.svg",
|
||||
"author": "Lightning Labs",
|
||||
"category": "money",
|
||||
"tier": "core",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/lnd:v0.18.4-beta",
|
||||
"repoUrl": "https://github.com/lightningnetwork/lnd",
|
||||
"requires": [
|
||||
"bitcoin-knots"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "btcpay-server",
|
||||
"title": "BTCPay Server",
|
||||
"version": "1.13.7",
|
||||
"description": "Self-hosted Bitcoin payment processor.",
|
||||
"icon": "/assets/img/app-icons/btcpay-server.png",
|
||||
"author": "BTCPay Server Foundation",
|
||||
"category": "commerce",
|
||||
"tier": "core",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/btcpayserver:1.13.7",
|
||||
"repoUrl": "https://github.com/btcpayserver/btcpayserver",
|
||||
"requires": [
|
||||
"bitcoin-knots"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "mempool",
|
||||
"title": "Mempool Explorer",
|
||||
"version": "3.0.0",
|
||||
"description": "Self-hosted Bitcoin blockchain and mempool visualizer.",
|
||||
"icon": "/assets/img/app-icons/mempool.webp",
|
||||
"author": "Mempool",
|
||||
"category": "money",
|
||||
"tier": "core",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/mempool-frontend:v3.0.0",
|
||||
"repoUrl": "https://github.com/mempool/mempool",
|
||||
"requires": [
|
||||
"bitcoin-knots",
|
||||
"electrumx"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "electrumx",
|
||||
"title": "ElectrumX",
|
||||
"version": "1.18.0",
|
||||
"description": "Electrum protocol server. Index the blockchain for fast wallet lookups.",
|
||||
"icon": "/assets/img/app-icons/electrumx.webp",
|
||||
"author": "Luke Childs",
|
||||
"category": "money",
|
||||
"tier": "core",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/electrumx:v1.18.0",
|
||||
"repoUrl": "https://github.com/spesmilo/electrumx",
|
||||
"requires": [
|
||||
"bitcoin-knots"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "indeedhub",
|
||||
"title": "IndeeHub",
|
||||
"version": "1.0.0",
|
||||
"description": "Bitcoin documentary streaming with Nostr identity.",
|
||||
"icon": "/assets/img/app-icons/indeedhub.png",
|
||||
"author": "IndeeHub",
|
||||
"category": "community",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/indeedhub:1.0.0",
|
||||
"repoUrl": "https://github.com/indeedhub/indeedhub"
|
||||
},
|
||||
{
|
||||
"id": "botfights",
|
||||
"title": "BotFights",
|
||||
"version": "1.1.0",
|
||||
"description": "Bot arena + 2-player arcade fighter with controller support and Adventure Mode.",
|
||||
"icon": "/assets/img/app-icons/botfights.svg",
|
||||
"author": "BotFights",
|
||||
"category": "community",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/botfights:1.1.0",
|
||||
"repoUrl": "https://botfights.net"
|
||||
},
|
||||
{
|
||||
"id": "gitea",
|
||||
"title": "Gitea",
|
||||
"version": "1.23",
|
||||
"description": "Self-hosted Git service with container registry, CI/CD, issue tracking.",
|
||||
"icon": "/assets/img/app-icons/gitea.svg",
|
||||
"author": "Gitea",
|
||||
"category": "development",
|
||||
"dockerImage": "docker.io/gitea/gitea:1.23",
|
||||
"repoUrl": "https://gitea.com"
|
||||
},
|
||||
{
|
||||
"id": "filebrowser",
|
||||
"title": "File Browser",
|
||||
"version": "2.27.0",
|
||||
"description": "Web-based file manager.",
|
||||
"icon": "/assets/img/app-icons/file-browser.webp",
|
||||
"author": "File Browser",
|
||||
"category": "data",
|
||||
"tier": "core",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/filebrowser:v2.27.0",
|
||||
"repoUrl": "https://github.com/filebrowser/filebrowser"
|
||||
},
|
||||
{
|
||||
"id": "vaultwarden",
|
||||
"title": "Vaultwarden",
|
||||
"version": "1.30.0",
|
||||
"description": "Self-hosted password vault with zero-knowledge encryption.",
|
||||
"icon": "/assets/img/app-icons/vaultwarden.webp",
|
||||
"author": "Vaultwarden",
|
||||
"category": "data",
|
||||
"tier": "recommended",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/vaultwarden:1.30.0-alpine",
|
||||
"repoUrl": "https://github.com/dani-garcia/vaultwarden"
|
||||
},
|
||||
{
|
||||
"id": "searxng",
|
||||
"title": "SearXNG",
|
||||
"version": "2024.1.0",
|
||||
"description": "Privacy-respecting metasearch engine.",
|
||||
"icon": "/assets/img/app-icons/searxng.png",
|
||||
"author": "SearXNG",
|
||||
"category": "data",
|
||||
"tier": "recommended",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/searxng:latest",
|
||||
"repoUrl": "https://github.com/searxng/searxng"
|
||||
},
|
||||
{
|
||||
"id": "fedimint",
|
||||
"title": "Fedimint",
|
||||
"version": "0.10.0",
|
||||
"description": "Federated Bitcoin mint with privacy through federated guardians.",
|
||||
"icon": "/assets/img/app-icons/fedimint.png",
|
||||
"author": "Fedimint",
|
||||
"category": "money",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/fedimintd:v0.10.0",
|
||||
"repoUrl": "https://github.com/fedimint/fedimint"
|
||||
},
|
||||
{
|
||||
"id": "jellyfin",
|
||||
"title": "Jellyfin",
|
||||
"version": "10.8.13",
|
||||
"description": "Free media server. Stream movies, music, and photos.",
|
||||
"icon": "/assets/img/app-icons/jellyfin.webp",
|
||||
"author": "Jellyfin",
|
||||
"category": "data",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/jellyfin:10.8.13",
|
||||
"repoUrl": "https://github.com/jellyfin/jellyfin"
|
||||
},
|
||||
{
|
||||
"id": "immich",
|
||||
"title": "Immich",
|
||||
"version": "1.90.0",
|
||||
"description": "High-performance photo and video backup with ML.",
|
||||
"icon": "/assets/img/app-icons/immich.png",
|
||||
"author": "Immich",
|
||||
"category": "data",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/immich-server:release",
|
||||
"repoUrl": "https://github.com/immich-app/immich"
|
||||
},
|
||||
{
|
||||
"id": "homeassistant",
|
||||
"title": "Home Assistant",
|
||||
"version": "2024.1",
|
||||
"description": "Open-source home automation.",
|
||||
"icon": "/assets/img/app-icons/homeassistant.png",
|
||||
"author": "Home Assistant",
|
||||
"category": "home",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/home-assistant:2024.1",
|
||||
"repoUrl": "https://github.com/home-assistant/core"
|
||||
},
|
||||
{
|
||||
"id": "grafana",
|
||||
"title": "Grafana",
|
||||
"version": "10.2.0",
|
||||
"description": "Analytics and monitoring dashboards.",
|
||||
"icon": "/assets/img/app-icons/grafana.png",
|
||||
"author": "Grafana Labs",
|
||||
"category": "data",
|
||||
"tier": "recommended",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/grafana:10.2.0",
|
||||
"repoUrl": "https://github.com/grafana/grafana"
|
||||
},
|
||||
{
|
||||
"id": "tailscale",
|
||||
"title": "Tailscale",
|
||||
"version": "1.78.0",
|
||||
"description": "Zero-config VPN with WireGuard mesh networking.",
|
||||
"icon": "/assets/img/app-icons/tailscale.webp",
|
||||
"author": "Tailscale",
|
||||
"category": "networking",
|
||||
"tier": "recommended",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/tailscale:stable",
|
||||
"repoUrl": "https://github.com/tailscale/tailscale"
|
||||
},
|
||||
{
|
||||
"id": "uptime-kuma",
|
||||
"title": "Uptime Kuma",
|
||||
"version": "1.23.0",
|
||||
"description": "Self-hosted uptime monitoring.",
|
||||
"icon": "/assets/img/app-icons/uptime-kuma.webp",
|
||||
"author": "Uptime Kuma",
|
||||
"category": "data",
|
||||
"tier": "recommended",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/uptime-kuma:1",
|
||||
"repoUrl": "https://github.com/louislam/uptime-kuma"
|
||||
},
|
||||
{
|
||||
"id": "photoprism",
|
||||
"title": "PhotoPrism",
|
||||
"version": "240915",
|
||||
"description": "AI-powered photo management with facial recognition.",
|
||||
"icon": "/assets/img/app-icons/photoprism.svg",
|
||||
"author": "PhotoPrism",
|
||||
"category": "data",
|
||||
"dockerImage": "146.59.87.168:3000/lfg2025/photoprism:240915",
|
||||
"repoUrl": "https://github.com/photoprism/photoprism"
|
||||
},
|
||||
{
|
||||
"id": "nextcloud",
|
||||
"title": "Nextcloud",
|
||||
"version": "28",
|
||||
"description": "Your own private cloud. File sync, calendars, contacts.",
|
||||
"icon": "/assets/img/app-icons/nextcloud.webp",
|
||||
"author": "Nextcloud",
|
||||
"category": "data",
|
||||
"dockerImage": "docker.io/nextcloud:28",
|
||||
"repoUrl": "https://github.com/nextcloud/server"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
app:
|
||||
id: archy-btcpay-db
|
||||
name: BTCPay Postgres
|
||||
version: 15.17
|
||||
description: Postgres backend for BTCPay and NBXplorer.
|
||||
|
||||
container:
|
||||
image: git.tx1138.com/lfg2025/postgres:15.17
|
||||
pull_policy: if-not-present
|
||||
network: archy-net
|
||||
data_uid: "100998:100998"
|
||||
secret_env:
|
||||
- key: POSTGRES_PASSWORD
|
||||
secret_file: btcpay-db-password
|
||||
|
||||
dependencies:
|
||||
- storage: 20Gi
|
||||
|
||||
resources:
|
||||
memory_limit: 1Gi
|
||||
disk_limit: 20Gi
|
||||
|
||||
security:
|
||||
capabilities: [CHOWN, FOWNER, SETUID, SETGID, DAC_OVERRIDE]
|
||||
readonly_root: false
|
||||
network_policy: isolated
|
||||
|
||||
ports: []
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/postgres-btcpay
|
||||
target: /var/lib/postgresql/data
|
||||
options: [rw]
|
||||
|
||||
environment:
|
||||
- POSTGRES_DB=btcpay
|
||||
- POSTGRES_USER=btcpay
|
||||
|
||||
health_check:
|
||||
type: tcp
|
||||
endpoint: localhost:5432
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
bitcoin_integration:
|
||||
rpc_access: none
|
||||
sync_required: false
|
||||
@@ -0,0 +1,51 @@
|
||||
app:
|
||||
id: archy-mempool-db
|
||||
name: Mempool MariaDB
|
||||
version: 11.4.10
|
||||
description: MariaDB backend for the mempool explorer stack.
|
||||
|
||||
container:
|
||||
image: git.tx1138.com/lfg2025/mariadb:11.4.10
|
||||
pull_policy: if-not-present
|
||||
network: archy-net
|
||||
data_uid: "100998:100998"
|
||||
secret_env:
|
||||
- key: MYSQL_PASSWORD
|
||||
secret_file: mempool-db-password
|
||||
- key: MYSQL_ROOT_PASSWORD
|
||||
secret_file: mysql-root-db-password
|
||||
|
||||
dependencies:
|
||||
- storage: 20Gi
|
||||
|
||||
resources:
|
||||
memory_limit: 512Mi
|
||||
disk_limit: 20Gi
|
||||
|
||||
security:
|
||||
capabilities: [CHOWN, FOWNER, SETUID, SETGID, DAC_OVERRIDE]
|
||||
readonly_root: false
|
||||
network_policy: isolated
|
||||
|
||||
ports: []
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/mysql-mempool
|
||||
target: /var/lib/mysql
|
||||
options: [rw]
|
||||
|
||||
environment:
|
||||
- MYSQL_DATABASE=mempool
|
||||
- MYSQL_USER=mempool
|
||||
|
||||
health_check:
|
||||
type: tcp
|
||||
endpoint: localhost:3306
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
bitcoin_integration:
|
||||
rpc_access: none
|
||||
sync_required: false
|
||||
@@ -0,0 +1,50 @@
|
||||
app:
|
||||
id: archy-mempool-web
|
||||
name: Mempool Web
|
||||
version: 3.0.0
|
||||
description: Frontend web UI for mempool explorer.
|
||||
container_name: mempool
|
||||
|
||||
container:
|
||||
image: git.tx1138.com/lfg2025/mempool-frontend:v3.0.0
|
||||
pull_policy: if-not-present
|
||||
network: archy-net
|
||||
|
||||
dependencies:
|
||||
- app_id: mempool-api
|
||||
version: ">=3.0.0"
|
||||
|
||||
resources:
|
||||
memory_limit: 512Mi
|
||||
|
||||
security:
|
||||
capabilities: []
|
||||
readonly_root: false
|
||||
network_policy: isolated
|
||||
|
||||
ports:
|
||||
- host: 4080
|
||||
container: 8080
|
||||
protocol: tcp
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/mempool/nginx.conf
|
||||
target: /etc/nginx/conf.d/default.conf
|
||||
options: [ro]
|
||||
|
||||
environment:
|
||||
- FRONTEND_HTTP_PORT=8080
|
||||
- BACKEND_MAINNET_HTTP_HOST=mempool-api
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost:8080
|
||||
path: /
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
bitcoin_integration:
|
||||
rpc_access: none
|
||||
sync_required: false
|
||||
@@ -0,0 +1,62 @@
|
||||
app:
|
||||
id: archy-nbxplorer
|
||||
name: NBXplorer
|
||||
version: 2.6.0
|
||||
description: BTCPay blockchain indexer service.
|
||||
|
||||
container:
|
||||
image: git.tx1138.com/lfg2025/nbxplorer:2.6.0
|
||||
pull_policy: if-not-present
|
||||
network: archy-net
|
||||
secret_env:
|
||||
- key: NBXPLORER_BTCRPCPASSWORD
|
||||
secret_file: bitcoin-rpc-password
|
||||
- key: BTCPAY_DB_PASS
|
||||
secret_file: btcpay-db-password
|
||||
|
||||
dependencies:
|
||||
- app_id: bitcoin-core
|
||||
version: ">=26.0"
|
||||
- app_id: archy-btcpay-db
|
||||
version: ">=15.17"
|
||||
|
||||
resources:
|
||||
memory_limit: 2Gi
|
||||
disk_limit: 20Gi
|
||||
|
||||
security:
|
||||
capabilities: []
|
||||
readonly_root: false
|
||||
network_policy: isolated
|
||||
|
||||
ports:
|
||||
- host: 32838
|
||||
container: 32838
|
||||
protocol: tcp
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/nbxplorer
|
||||
target: /data
|
||||
options: [rw]
|
||||
|
||||
environment:
|
||||
- NBXPLORER_DATADIR=/data
|
||||
- NBXPLORER_NETWORK=mainnet
|
||||
- NBXPLORER_CHAINS=btc
|
||||
- NBXPLORER_BIND=0.0.0.0:32838
|
||||
- NBXPLORER_BTCRPCURL=http://bitcoin-knots:8332
|
||||
- NBXPLORER_BTCRPCUSER=archipelago
|
||||
- NBXPLORER_POSTGRES=User ID=btcpay;Password=${BTCPAY_DB_PASS};Host=archy-btcpay-db;Port=5432;Database=nbxplorer;Include Error Detail=true
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost:32838
|
||||
path: /
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
bitcoin_integration:
|
||||
rpc_access: read-only
|
||||
sync_required: true
|
||||
@@ -1,61 +1,70 @@
|
||||
app:
|
||||
id: bitcoin-core
|
||||
name: Bitcoin Core
|
||||
version: 24.0.0
|
||||
description: Full Bitcoin node implementation. The reference implementation of the Bitcoin protocol.
|
||||
|
||||
name: Bitcoin Knots
|
||||
version: 28.4.0
|
||||
description: Full Bitcoin Knots node with dynamic prune/full-mode startup based on host disk.
|
||||
|
||||
container_name: bitcoin-knots
|
||||
|
||||
container:
|
||||
image: bitcoin/bitcoin:24.0
|
||||
image_signature: cosign://...
|
||||
pull_policy: verify-signature
|
||||
|
||||
image: 146.59.87.168:3000/lfg2025/bitcoin-knots:latest
|
||||
pull_policy: if-not-present
|
||||
network: archy-net
|
||||
entrypoint: ["sh", "-lc"]
|
||||
custom_args:
|
||||
- >-
|
||||
if [ "${DISK_GB:-0}" -lt 1000 ]; then
|
||||
exec bitcoind -server=1 -prune=550 -rpcallowip=0.0.0.0/0 -rpcbind=0.0.0.0:8332 -listen=1 -bind=0.0.0.0:8333 -dbcache=512 -rpcuser="${BITCOIN_RPC_USER}" -rpcpassword="${BITCOIN_RPC_PASS}";
|
||||
else
|
||||
exec bitcoind -server=1 -txindex=1 -rpcallowip=0.0.0.0/0 -rpcbind=0.0.0.0:8332 -listen=1 -bind=0.0.0.0:8333 -dbcache=4096 -rpcuser="${BITCOIN_RPC_USER}" -rpcpassword="${BITCOIN_RPC_PASS}";
|
||||
fi
|
||||
derived_env:
|
||||
- key: DISK_GB
|
||||
template: "{{DISK_GB}}"
|
||||
secret_env:
|
||||
- key: BITCOIN_RPC_PASS
|
||||
secret_file: bitcoin-rpc-password
|
||||
data_uid: "100101:100101"
|
||||
|
||||
dependencies:
|
||||
- storage: 500Gi # Minimum disk space for mainnet
|
||||
|
||||
- storage: 500Gi
|
||||
|
||||
resources:
|
||||
cpu_limit: 2
|
||||
memory_limit: 2Gi
|
||||
cpu_limit: 0
|
||||
memory_limit: 4Gi
|
||||
disk_limit: 500Gi
|
||||
|
||||
|
||||
security:
|
||||
capabilities: [] # No special capabilities needed
|
||||
readonly_root: true
|
||||
no_new_privileges: true
|
||||
user: 1000
|
||||
seccomp_profile: default
|
||||
capabilities: [CHOWN, FOWNER, SETUID, SETGID, DAC_OVERRIDE]
|
||||
readonly_root: false
|
||||
network_policy: isolated
|
||||
apparmor_profile: bitcoin-core
|
||||
|
||||
|
||||
ports:
|
||||
- host: 8332
|
||||
container: 8332
|
||||
protocol: tcp # RPC
|
||||
protocol: tcp
|
||||
- host: 8333
|
||||
container: 8333
|
||||
protocol: tcp # P2P
|
||||
|
||||
protocol: tcp
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/bitcoin
|
||||
target: /home/bitcoin/.bitcoin
|
||||
options: [rw]
|
||||
|
||||
|
||||
environment:
|
||||
- NETWORK=mainnet
|
||||
- RPC_USER=${BITCOIN_RPC_USER}
|
||||
- RPC_PASSWORD=${BITCOIN_RPC_PASSWORD}
|
||||
- PRUNE=0 # Full node (set to 550 for pruned)
|
||||
|
||||
- BITCOIN_RPC_USER=archipelago
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost:8332
|
||||
path: /
|
||||
type: tcp
|
||||
endpoint: localhost:8332
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
|
||||
bitcoin_integration:
|
||||
rpc_access: admin
|
||||
sync_required: true
|
||||
testnet_support: true
|
||||
testnet_support: false
|
||||
pruning_support: true
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
app:
|
||||
id: bitcoin-ui
|
||||
name: Bitcoin UI
|
||||
version: 1.0.0
|
||||
description: |
|
||||
Archipelago-native HTTP proxy + static site for interacting with the
|
||||
Bitcoin Core / Bitcoin Knots JSON-RPC. Runs nginx inside a container
|
||||
and reverse-proxies /bitcoin-rpc/ to 127.0.0.1:8332 on the host. The
|
||||
upstream Authorization header is substituted from
|
||||
/var/lib/archipelago/secrets/bitcoin-rpc-password by the prod
|
||||
orchestrator's pre-start hook, rendered into an nginx.conf that is
|
||||
bind-mounted read-only at container start.
|
||||
|
||||
container:
|
||||
build:
|
||||
context: /opt/archipelago/docker/bitcoin-ui
|
||||
dockerfile: Dockerfile
|
||||
tag: localhost/bitcoin-ui:local
|
||||
|
||||
dependencies:
|
||||
- app_id: bitcoin-core
|
||||
|
||||
resources:
|
||||
memory_limit: 128Mi
|
||||
|
||||
security:
|
||||
readonly_root: false
|
||||
network_policy: host
|
||||
|
||||
# Host networking: nginx listens on 8334 directly on the host IP, and
|
||||
# proxies to 127.0.0.1:8332 which is where the bitcoin backend binds
|
||||
# its RPC. `ports:` is intentionally empty because host networking
|
||||
# bypasses port mapping.
|
||||
ports: []
|
||||
|
||||
volumes:
|
||||
# Bind-mount the rendered nginx.conf read-only. The prod orchestrator
|
||||
# renders /var/lib/archipelago/bitcoin-ui/nginx.conf on every install
|
||||
# and every reconcile pass, substituting the base64 RPC auth from
|
||||
# the plaintext password secret. If the rendered bytes change (the
|
||||
# password rotated, or the template was updated by OTA), the
|
||||
# reconciler restarts this container so nginx re-reads the config.
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/bitcoin-ui/nginx.conf
|
||||
target: /etc/nginx/conf.d/default.conf
|
||||
options: [ro]
|
||||
|
||||
environment: []
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://127.0.0.1:8334
|
||||
path: /
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
@@ -0,0 +1,73 @@
|
||||
app:
|
||||
id: botfights
|
||||
name: BotFights
|
||||
version: 1.0.0
|
||||
description: Bot competition arena with 2-player arcade fighting mode. AI bots battle in trivia challenges while humans duke it out with controllers. Built for Bitcoiners.
|
||||
category: community
|
||||
|
||||
container:
|
||||
image: git.tx1138.com/lfg2025/botfights:1.1.0
|
||||
pull_policy: always
|
||||
|
||||
dependencies:
|
||||
- storage: 500Mi
|
||||
|
||||
resources:
|
||||
cpu_limit: 2
|
||||
memory_limit: 512Mi
|
||||
disk_limit: 500Mi
|
||||
|
||||
security:
|
||||
capabilities: []
|
||||
readonly_root: true
|
||||
no_new_privileges: true
|
||||
user: 1001
|
||||
seccomp_profile: default
|
||||
network_policy: bridge
|
||||
apparmor_profile: default
|
||||
|
||||
ports:
|
||||
- host: 9100
|
||||
container: 9100
|
||||
protocol: tcp # Web UI + API
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: botfights-data
|
||||
target: /app/server/data
|
||||
- type: tmpfs
|
||||
target: /tmp
|
||||
options: [rw,noexec,nosuid,size=64m]
|
||||
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost:9100
|
||||
path: /api/health
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
|
||||
interfaces:
|
||||
main:
|
||||
name: Web UI
|
||||
description: Bot arena and arcade fighter with controller support
|
||||
type: ui
|
||||
port: 9100
|
||||
protocol: http
|
||||
path: /
|
||||
|
||||
metadata:
|
||||
author: Dorian
|
||||
license: MIT
|
||||
tags:
|
||||
- bitcoin
|
||||
- gaming
|
||||
- arcade
|
||||
- fighter
|
||||
- bots
|
||||
- competition
|
||||
- controller
|
||||
@@ -1,66 +1,70 @@
|
||||
app:
|
||||
id: btcpay-server
|
||||
name: BTCPay Server
|
||||
version: 1.12.0
|
||||
version: 1.13.7
|
||||
description: Self-hosted Bitcoin payment processor. Accept Bitcoin payments without intermediaries.
|
||||
|
||||
|
||||
container:
|
||||
image: btcpayserver/btcpayserver:1.12.0
|
||||
image_signature: cosign://...
|
||||
pull_policy: verify-signature
|
||||
|
||||
image: git.tx1138.com/lfg2025/btcpayserver:1.13.7
|
||||
pull_policy: if-not-present
|
||||
network: archy-net
|
||||
secret_env:
|
||||
- key: BTCPAY_BTCRPCPASSWORD
|
||||
secret_file: bitcoin-rpc-password
|
||||
- key: BTCPAY_DB_PASS
|
||||
secret_file: btcpay-db-password
|
||||
|
||||
dependencies:
|
||||
- app_id: bitcoin-core
|
||||
version: ">=26.0"
|
||||
- app_id: lnd
|
||||
version: ">=0.18.0"
|
||||
|
||||
- app_id: archy-btcpay-db
|
||||
version: ">=15.17"
|
||||
- app_id: archy-nbxplorer
|
||||
version: ">=2.6.0"
|
||||
|
||||
resources:
|
||||
cpu_limit: 2
|
||||
memory_limit: 2Gi
|
||||
disk_limit: 20Gi
|
||||
|
||||
|
||||
security:
|
||||
capabilities: [NET_BIND_SERVICE]
|
||||
readonly_root: true
|
||||
no_new_privileges: true
|
||||
user: 1000
|
||||
seccomp_profile: default
|
||||
capabilities: []
|
||||
readonly_root: false
|
||||
network_policy: isolated
|
||||
apparmor_profile: btcpay
|
||||
|
||||
|
||||
ports:
|
||||
- host: 80
|
||||
container: 80
|
||||
- host: 23000
|
||||
container: 49392
|
||||
protocol: tcp
|
||||
- host: 443
|
||||
container: 443
|
||||
protocol: tcp
|
||||
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/btcpay
|
||||
target: /datadir
|
||||
options: [rw]
|
||||
|
||||
|
||||
environment:
|
||||
- BTCPAY_NETWORK=mainnet
|
||||
- BTCPAY_CHAIN=btc
|
||||
- BTCPAY_BTCEXPLORERURL=http://bitcoin-core:8332
|
||||
- BTCPAY_LIGHTNING=type=lnd-rest;server=http://lnd:8080;allowinsecure=true
|
||||
|
||||
- ASPNETCORE_URLS=http://0.0.0.0:49392
|
||||
- BTCPAY_PROTOCOL=http
|
||||
- BTCPAY_HOST=127.0.0.1:23000
|
||||
- BTCPAY_CHAINS=btc
|
||||
- BTCPAY_BTCEXPLORERURL=http://archy-nbxplorer:32838
|
||||
- BTCPAY_BTCRPCURL=http://bitcoin-knots:8332
|
||||
- BTCPAY_BTCRPCUSER=archipelago
|
||||
- BTCPAY_POSTGRES=User ID=btcpay;Password=${BTCPAY_DB_PASS};Host=archy-btcpay-db;Port=5432;Database=btcpay;Include Error Detail=true
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost
|
||||
path: /health
|
||||
endpoint: http://localhost:49392
|
||||
path: /
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
|
||||
bitcoin_integration:
|
||||
rpc_access: read-only
|
||||
sync_required: true
|
||||
|
||||
|
||||
lightning_integration:
|
||||
payment_processing: true
|
||||
payment_processing: false
|
||||
invoice_management: true
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
app:
|
||||
id: electrs-ui
|
||||
name: Electrs UI
|
||||
version: 1.0.0
|
||||
description: |
|
||||
Archipelago-native HTTP frontend for electrs/electrumx status. Runs
|
||||
nginx inside a container, serves static assets, and proxies
|
||||
/electrs-status to the archipelago backend on 127.0.0.1:5678.
|
||||
|
||||
container:
|
||||
build:
|
||||
context: /opt/archipelago/docker/electrs-ui
|
||||
dockerfile: Dockerfile
|
||||
tag: localhost/electrs-ui:local
|
||||
|
||||
dependencies: []
|
||||
|
||||
resources:
|
||||
memory_limit: 64Mi
|
||||
|
||||
security:
|
||||
readonly_root: false
|
||||
network_policy: host
|
||||
|
||||
# Host networking: nginx listens on 50002 directly on the host IP.
|
||||
ports: []
|
||||
|
||||
volumes: []
|
||||
|
||||
environment: []
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://127.0.0.1:50002
|
||||
path: /
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
@@ -0,0 +1,60 @@
|
||||
app:
|
||||
id: electrumx
|
||||
name: ElectrumX
|
||||
version: 1.18.0
|
||||
description: Electrum server indexing Bitcoin chain data for lightweight wallet queries.
|
||||
|
||||
container:
|
||||
image: git.tx1138.com/lfg2025/electrumx:v1.18.0
|
||||
pull_policy: if-not-present
|
||||
network: archy-net
|
||||
entrypoint: ["sh", "-lc"]
|
||||
custom_args:
|
||||
- >-
|
||||
export DAEMON_URL="http://archipelago:${BITCOIN_RPC_PASS}@bitcoin-knots:8332/";
|
||||
exec electrumx_server
|
||||
secret_env:
|
||||
- key: BITCOIN_RPC_PASS
|
||||
secret_file: bitcoin-rpc-password
|
||||
|
||||
dependencies:
|
||||
- app_id: bitcoin-core
|
||||
version: ">=26.0"
|
||||
- storage: 50Gi
|
||||
|
||||
resources:
|
||||
cpu_limit: 2
|
||||
memory_limit: 2Gi
|
||||
disk_limit: 50Gi
|
||||
|
||||
security:
|
||||
capabilities: [DAC_OVERRIDE]
|
||||
readonly_root: false
|
||||
network_policy: isolated
|
||||
|
||||
ports:
|
||||
- host: 50001
|
||||
container: 50001
|
||||
protocol: tcp
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/electrumx
|
||||
target: /data
|
||||
options: [rw]
|
||||
|
||||
environment:
|
||||
- COIN=Bitcoin
|
||||
- DB_DIRECTORY=/data
|
||||
- SERVICES=tcp://:50001,rpc://0.0.0.0:8000
|
||||
|
||||
health_check:
|
||||
type: tcp
|
||||
endpoint: localhost:50001
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
bitcoin_integration:
|
||||
rpc_access: read-only
|
||||
sync_required: true
|
||||
@@ -1,6 +0,0 @@
|
||||
node_modules
|
||||
dist
|
||||
*.log
|
||||
.git
|
||||
.gitignore
|
||||
README.md
|
||||
@@ -1,37 +0,0 @@
|
||||
FROM node:20-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files
|
||||
COPY package*.json ./
|
||||
RUN npm ci --only=production
|
||||
|
||||
# Copy source code
|
||||
COPY . .
|
||||
|
||||
# Build the application
|
||||
RUN npm run build
|
||||
|
||||
# Production stage
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy built application
|
||||
COPY --from=builder /app/dist ./dist
|
||||
COPY --from=builder /app/node_modules ./node_modules
|
||||
COPY --from=builder /app/package.json ./
|
||||
|
||||
# Create non-root user
|
||||
RUN addgroup -g 1000 appuser && \
|
||||
adduser -D -u 1000 -G appuser appuser && \
|
||||
mkdir -p /app/data && \
|
||||
chown -R appuser:appuser /app
|
||||
|
||||
USER appuser
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
ENV ENDURAIN_DATA_DIR=/app/data
|
||||
|
||||
CMD ["node", "dist/index.js"]
|
||||
@@ -1,50 +0,0 @@
|
||||
app:
|
||||
id: endurain
|
||||
name: Endurain
|
||||
version: 1.0.0
|
||||
description: Endurain application platform. Custom application runtime.
|
||||
|
||||
container:
|
||||
image: archipelago/endurain:1.0.0
|
||||
image_signature: cosign://...
|
||||
pull_policy: if-not-present
|
||||
|
||||
dependencies:
|
||||
- storage: 2Gi
|
||||
|
||||
resources:
|
||||
cpu_limit: 2
|
||||
memory_limit: 1Gi
|
||||
disk_limit: 2Gi
|
||||
|
||||
security:
|
||||
capabilities: []
|
||||
readonly_root: true
|
||||
no_new_privileges: true
|
||||
user: 1000
|
||||
seccomp_profile: default
|
||||
network_policy: isolated
|
||||
apparmor_profile: endurain
|
||||
|
||||
ports:
|
||||
- host: 8085
|
||||
container: 8080
|
||||
protocol: tcp # Web UI
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/endurain
|
||||
target: /app/data
|
||||
options: [rw]
|
||||
|
||||
environment:
|
||||
- ENDURAIN_ENV=production
|
||||
- ENDURAIN_DATA_DIR=/app/data
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost:8085
|
||||
path: /health
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
Generated
-1161
File diff suppressed because it is too large
Load Diff
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"name": "endurain",
|
||||
"version": "1.0.0",
|
||||
"description": "Endurain application platform",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"dev": "ts-node src/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^4.18.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/node": "^20.10.0",
|
||||
"typescript": "^5.3.3",
|
||||
"ts-node": "^10.9.2"
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import express from 'express';
|
||||
|
||||
const app = express();
|
||||
const port = 8080;
|
||||
|
||||
// Middleware
|
||||
app.use(express.json());
|
||||
|
||||
// Health check endpoint
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({ status: 'ok', service: 'endurain', version: '1.0.0' });
|
||||
});
|
||||
|
||||
// API endpoints
|
||||
app.get('/api/info', (req, res) => {
|
||||
res.json({
|
||||
name: 'Endurain',
|
||||
version: '1.0.0',
|
||||
status: 'running'
|
||||
});
|
||||
});
|
||||
|
||||
// Start server
|
||||
app.listen(port, '0.0.0.0', () => {
|
||||
console.log(`Endurain listening on port ${port}`);
|
||||
console.log(`Data directory: ${process.env.ENDURAIN_DATA_DIR || '/app/data'}`);
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2020"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
app:
|
||||
id: fedimint-gateway
|
||||
name: Fedimint Gateway
|
||||
version: 0.10.0
|
||||
description: Fedimint gateway service with automatic LND-or-LDK backend selection.
|
||||
|
||||
container:
|
||||
image: git.tx1138.com/lfg2025/gatewayd:v0.10.0
|
||||
pull_policy: if-not-present
|
||||
network: archy-net
|
||||
entrypoint: ["sh", "-lc"]
|
||||
custom_args:
|
||||
- >-
|
||||
if [ -f /lnd/tls.cert ] && [ -f /lnd/data/chain/bitcoin/mainnet/admin.macaroon ]; then
|
||||
exec gatewayd --data-dir /data --listen 0.0.0.0:8176 --bcrypt-password-hash "$FEDI_HASH" --network bitcoin --bitcoind-url http://bitcoin-knots:8332 --bitcoind-username "$FM_BITCOIND_USERNAME" --bitcoind-password "$FM_BITCOIND_PASSWORD" lnd --lnd-rpc-host lnd:10009 --lnd-tls-cert /lnd/tls.cert --lnd-macaroon /lnd/data/chain/bitcoin/mainnet/admin.macaroon;
|
||||
else
|
||||
exec gatewayd --data-dir /data --listen 0.0.0.0:8176 --bcrypt-password-hash "$FEDI_HASH" --network bitcoin --bitcoind-url http://bitcoin-knots:8332 --bitcoind-username "$FM_BITCOIND_USERNAME" --bitcoind-password "$FM_BITCOIND_PASSWORD" ldk --ldk-lightning-port 9737 --ldk-alias archipelago-gateway;
|
||||
fi
|
||||
secret_env:
|
||||
- key: FM_BITCOIND_PASSWORD
|
||||
secret_file: bitcoin-rpc-password
|
||||
- key: FEDI_HASH
|
||||
secret_file: fedimint-gateway-hash
|
||||
data_uid: "100000:100000"
|
||||
|
||||
dependencies:
|
||||
- app_id: bitcoin-core
|
||||
version: ">=26.0"
|
||||
- app_id: fedimint
|
||||
version: ">=0.10.0"
|
||||
|
||||
resources:
|
||||
cpu_limit: 2
|
||||
memory_limit: 2Gi
|
||||
disk_limit: 10Gi
|
||||
|
||||
security:
|
||||
capabilities: []
|
||||
readonly_root: true
|
||||
network_policy: isolated
|
||||
|
||||
ports:
|
||||
- host: 8176
|
||||
container: 8176
|
||||
protocol: tcp
|
||||
- host: 9737
|
||||
container: 9737
|
||||
protocol: tcp
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/fedimint-gateway
|
||||
target: /data
|
||||
options: [rw]
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/lnd
|
||||
target: /lnd
|
||||
options: [ro]
|
||||
|
||||
environment:
|
||||
- FM_BITCOIND_USERNAME=archipelago
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost:8176
|
||||
path: /
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
bitcoin_integration:
|
||||
rpc_access: admin
|
||||
sync_required: true
|
||||
+30
-24
@@ -3,56 +3,62 @@ app:
|
||||
name: Fedimint
|
||||
version: 0.10.0
|
||||
description: Federated Bitcoin minting service with built-in Guardian UI. Privacy-preserving Bitcoin custody.
|
||||
|
||||
|
||||
container:
|
||||
image: fedimint/fedimintd:v0.10.0
|
||||
image_signature: cosign://...
|
||||
image: git.tx1138.com/lfg2025/fedimintd:v0.10.0
|
||||
pull_policy: if-not-present
|
||||
|
||||
network: archy-net
|
||||
derived_env:
|
||||
- key: FM_P2P_URL
|
||||
template: fedimint://{{HOST_MDNS}}:8173
|
||||
- key: FM_API_URL
|
||||
template: ws://{{HOST_MDNS}}:8174
|
||||
secret_env:
|
||||
- key: FM_BITCOIND_PASSWORD
|
||||
secret_file: bitcoin-rpc-password
|
||||
data_uid: "100000:100000"
|
||||
|
||||
dependencies:
|
||||
- app_id: bitcoin-core
|
||||
version: ">=24.0"
|
||||
version: ">=26.0"
|
||||
- storage: 20Gi
|
||||
|
||||
|
||||
resources:
|
||||
cpu_limit: 4
|
||||
memory_limit: 4Gi
|
||||
disk_limit: 20Gi
|
||||
|
||||
|
||||
security:
|
||||
capabilities: []
|
||||
readonly_root: true
|
||||
no_new_privileges: true
|
||||
user: 1000
|
||||
seccomp_profile: default
|
||||
network_policy: isolated
|
||||
apparmor_profile: fedimint
|
||||
|
||||
|
||||
ports:
|
||||
- host: 8173
|
||||
container: 8173
|
||||
protocol: tcp # P2P
|
||||
protocol: tcp
|
||||
- host: 8174
|
||||
container: 8174
|
||||
protocol: tcp # API
|
||||
protocol: tcp
|
||||
- host: 8175
|
||||
container: 8175
|
||||
protocol: tcp # Built-in Guardian UI
|
||||
|
||||
protocol: tcp
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/fedimint
|
||||
target: /fedimint
|
||||
target: /data
|
||||
options: [rw]
|
||||
|
||||
|
||||
environment:
|
||||
- FM_DATA_DIR=/fedimint
|
||||
- FM_BITCOIND_URL=http://bitcoin-core:8332
|
||||
- FM_BITCOIND_USERNAME=${BITCOIN_RPC_USER}
|
||||
- FM_BITCOIND_PASSWORD=${BITCOIN_RPC_PASSWORD}
|
||||
- FM_DATA_DIR=/data
|
||||
- FM_BITCOIND_URL=http://bitcoin-knots:8332
|
||||
- FM_BITCOIND_USERNAME=archipelago
|
||||
- FM_BITCOIN_NETWORK=bitcoin
|
||||
- FM_BIND_P2P=0.0.0.0:8173
|
||||
- FM_BIND_API=0.0.0.0:8174
|
||||
- FM_BIND_UI=0.0.0.0:8175
|
||||
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost:8175
|
||||
@@ -60,7 +66,7 @@ app:
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
|
||||
bitcoin_integration:
|
||||
rpc_access: admin
|
||||
sync_required: true
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
app:
|
||||
id: filebrowser
|
||||
name: File Browser
|
||||
version: 2.27.0
|
||||
description: Baseline Archipelago file manager service.
|
||||
|
||||
container:
|
||||
image: git.tx1138.com/lfg2025/filebrowser:v2.27.0
|
||||
pull_policy: if-not-present
|
||||
network: archy-net
|
||||
custom_args: ["--config", "/data/.filebrowser.json"]
|
||||
data_uid: "100000:100000"
|
||||
|
||||
dependencies:
|
||||
- storage: 10Gi
|
||||
|
||||
resources:
|
||||
memory_limit: 256Mi
|
||||
disk_limit: 10Gi
|
||||
|
||||
security:
|
||||
capabilities: [CHOWN, FOWNER, SETUID, SETGID, DAC_OVERRIDE, NET_BIND_SERVICE]
|
||||
readonly_root: false
|
||||
network_policy: isolated
|
||||
|
||||
ports:
|
||||
- host: 8083
|
||||
container: 80
|
||||
protocol: tcp
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/filebrowser
|
||||
target: /srv
|
||||
options: [rw]
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/filebrowser-data
|
||||
target: /data
|
||||
options: [rw]
|
||||
|
||||
environment: []
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost:80
|
||||
path: /health
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
bitcoin_integration:
|
||||
rpc_access: none
|
||||
sync_required: false
|
||||
@@ -0,0 +1,53 @@
|
||||
id: gitea
|
||||
name: Gitea
|
||||
version: "1.23"
|
||||
description: Self-hosted Git service with built-in container registry, CI/CD, and package hosting.
|
||||
category: development
|
||||
icon: git-branch
|
||||
port: 3000
|
||||
internal_port: 3001
|
||||
ssh_port: 2222
|
||||
image: docker.io/gitea/gitea:1.23
|
||||
tier: optional
|
||||
|
||||
requires:
|
||||
memory_mb: 256
|
||||
disk_mb: 500
|
||||
|
||||
volumes:
|
||||
- host: /var/lib/archipelago/gitea/data
|
||||
container: /data
|
||||
- host: /var/lib/archipelago/gitea/config
|
||||
container: /etc/gitea
|
||||
|
||||
environment:
|
||||
GITEA__database__DB_TYPE: sqlite3
|
||||
GITEA__server__SSH_PORT: "2222"
|
||||
GITEA__server__SSH_LISTEN_PORT: "22"
|
||||
GITEA__server__LFS_START_SERVER: "true"
|
||||
GITEA__packages__ENABLED: "true"
|
||||
GITEA__repository__ENABLE_PUSH_CREATE_USER: "true"
|
||||
GITEA__repository__ENABLE_PUSH_CREATE_ORG: "true"
|
||||
|
||||
# Gitea hardcodes X-Frame-Options: SAMEORIGIN which blocks iframe embedding.
|
||||
# Container binds to internal_port (3001), nginx proxies public port (3000)
|
||||
# stripping the X-Frame-Options header so the app works in Archipelago's iframe.
|
||||
nginx_proxy:
|
||||
listen: 3000
|
||||
proxy_pass: "http://127.0.0.1:3001"
|
||||
extra_headers:
|
||||
- "proxy_hide_header X-Frame-Options"
|
||||
- "proxy_hide_header Content-Security-Policy"
|
||||
|
||||
health_check:
|
||||
endpoint: /
|
||||
interval: 120
|
||||
timeout: 5
|
||||
retries: 3
|
||||
|
||||
features:
|
||||
- Git repositories with web UI
|
||||
- Built-in container/package registry
|
||||
- Issue tracking and pull requests
|
||||
- CI/CD via Gitea Actions
|
||||
- Lightweight (SQLite, no external DB needed)
|
||||
@@ -6,7 +6,7 @@ app:
|
||||
category: media
|
||||
|
||||
container:
|
||||
image: git.tx1138.com/lfg2025/indeedhub:latest
|
||||
image: 146.59.87.168:3000/lfg2025/indeedhub:latest
|
||||
pull_policy: always # Pull from registry; falls back to local build
|
||||
|
||||
dependencies:
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
app:
|
||||
id: lnd-ui
|
||||
name: LND UI
|
||||
version: 1.0.0
|
||||
description: |
|
||||
Archipelago-native HTTP frontend for LND. Runs nginx inside a
|
||||
container and serves static assets. LND connection info is fetched
|
||||
via an absolute URL that the host nginx routes to the archipelago
|
||||
backend on 127.0.0.1:5678, so no upstream auth is baked in.
|
||||
|
||||
container:
|
||||
build:
|
||||
context: /opt/archipelago/docker/lnd-ui
|
||||
dockerfile: Dockerfile
|
||||
tag: localhost/lnd-ui:local
|
||||
|
||||
dependencies:
|
||||
- app_id: lnd
|
||||
|
||||
resources:
|
||||
memory_limit: 64Mi
|
||||
|
||||
security:
|
||||
readonly_root: false
|
||||
network_policy: bridge
|
||||
|
||||
# Bridge networking via archy-net. Container nginx listens on 80;
|
||||
# host nginx proxies /app/lnd/ -> 127.0.0.1:8081 -> container:80.
|
||||
ports:
|
||||
- host: 8081
|
||||
container: 80
|
||||
protocol: tcp
|
||||
|
||||
volumes: []
|
||||
|
||||
environment: []
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://127.0.0.1:8081
|
||||
path: /
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
+27
-29
@@ -1,67 +1,65 @@
|
||||
app:
|
||||
id: lnd
|
||||
name: Lightning Network Daemon
|
||||
version: 0.18.0
|
||||
version: 0.18.4
|
||||
description: Lightning Network implementation by Lightning Labs. Enables instant, low-cost Bitcoin payments.
|
||||
|
||||
|
||||
container:
|
||||
image: lightninglabs/lnd:v0.18.0
|
||||
image_signature: cosign://...
|
||||
pull_policy: verify-signature
|
||||
|
||||
image: git.tx1138.com/lfg2025/lnd:v0.18.4-beta
|
||||
pull_policy: if-not-present
|
||||
network: archy-net
|
||||
secret_env:
|
||||
- key: BITCOIND_RPCPASS
|
||||
secret_file: bitcoin-rpc-password
|
||||
data_uid: "100000:100000"
|
||||
|
||||
dependencies:
|
||||
- app_id: bitcoin-core
|
||||
version: ">=26.0"
|
||||
|
||||
|
||||
resources:
|
||||
cpu_limit: 2
|
||||
memory_limit: 1Gi
|
||||
disk_limit: 10Gi
|
||||
|
||||
|
||||
security:
|
||||
capabilities: [NET_BIND_SERVICE]
|
||||
readonly_root: true
|
||||
no_new_privileges: true
|
||||
user: 1000
|
||||
seccomp_profile: default
|
||||
capabilities: [CHOWN, FOWNER, SETUID, SETGID, DAC_OVERRIDE, NET_RAW]
|
||||
readonly_root: false
|
||||
network_policy: isolated
|
||||
apparmor_profile: lnd
|
||||
|
||||
|
||||
ports:
|
||||
- host: 9735
|
||||
container: 9735
|
||||
protocol: tcp # P2P
|
||||
protocol: tcp
|
||||
- host: 10009
|
||||
container: 10009
|
||||
protocol: tcp # gRPC
|
||||
protocol: tcp
|
||||
- host: 8080
|
||||
container: 8080
|
||||
protocol: tcp # REST
|
||||
|
||||
protocol: tcp
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/lnd
|
||||
target: /root/.lnd
|
||||
options: [rw]
|
||||
|
||||
|
||||
environment:
|
||||
- BITCOIND_HOST=bitcoin-core
|
||||
- BITCOIND_RPCUSER=${BITCOIN_RPC_USER}
|
||||
- BITCOIND_RPCPASS=${BITCOIN_RPC_PASSWORD}
|
||||
- BITCOIND_HOST=bitcoin-knots
|
||||
- BITCOIND_RPCUSER=archipelago
|
||||
- NETWORK=mainnet
|
||||
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost:8080
|
||||
path: /v1/getinfo
|
||||
type: tcp
|
||||
endpoint: localhost:10009
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
|
||||
bitcoin_integration:
|
||||
rpc_access: admin
|
||||
sync_required: true
|
||||
|
||||
|
||||
lightning_integration:
|
||||
channel_management: true
|
||||
payment_routing: true
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
app:
|
||||
id: mempool-api
|
||||
name: Mempool API
|
||||
version: 3.0.0
|
||||
description: Backend API for mempool explorer.
|
||||
|
||||
container:
|
||||
image: git.tx1138.com/lfg2025/mempool-backend:v3.0.0
|
||||
pull_policy: if-not-present
|
||||
network: archy-net
|
||||
secret_env:
|
||||
- key: CORE_RPC_PASSWORD
|
||||
secret_file: bitcoin-rpc-password
|
||||
- key: DATABASE_PASSWORD
|
||||
secret_file: mempool-db-password
|
||||
|
||||
dependencies:
|
||||
- app_id: bitcoin-core
|
||||
version: ">=26.0"
|
||||
- app_id: electrumx
|
||||
version: ">=1.18.0"
|
||||
- app_id: archy-mempool-db
|
||||
version: ">=11.4.10"
|
||||
|
||||
resources:
|
||||
memory_limit: 2Gi
|
||||
disk_limit: 20Gi
|
||||
|
||||
security:
|
||||
capabilities: []
|
||||
readonly_root: false
|
||||
network_policy: isolated
|
||||
|
||||
ports:
|
||||
- host: 8999
|
||||
container: 8999
|
||||
protocol: tcp
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/mempool
|
||||
target: /data
|
||||
options: [rw]
|
||||
|
||||
environment:
|
||||
- MEMPOOL_BACKEND=electrum
|
||||
- ELECTRUM_HOST=electrumx
|
||||
- ELECTRUM_PORT=50001
|
||||
- ELECTRUM_TLS_ENABLED=false
|
||||
- CORE_RPC_HOST=bitcoin-knots
|
||||
- CORE_RPC_PORT=8332
|
||||
- CORE_RPC_USERNAME=archipelago
|
||||
- DATABASE_ENABLED=true
|
||||
- DATABASE_HOST=archy-mempool-db
|
||||
- DATABASE_DATABASE=mempool
|
||||
- DATABASE_USERNAME=mempool
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost:8999
|
||||
path: /
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
bitcoin_integration:
|
||||
rpc_access: read-only
|
||||
sync_required: true
|
||||
@@ -1,5 +0,0 @@
|
||||
# Ollama - uses official image
|
||||
FROM ollama/ollama:latest
|
||||
|
||||
# Default configuration is in the image
|
||||
# No additional setup needed
|
||||
@@ -1,50 +0,0 @@
|
||||
app:
|
||||
id: ollama
|
||||
name: Ollama
|
||||
version: 0.1.0
|
||||
description: Run large language models locally. Privacy-preserving AI on your node.
|
||||
|
||||
container:
|
||||
image: ollama/ollama:0.6.2
|
||||
image_signature: cosign://...
|
||||
pull_policy: if-not-present
|
||||
|
||||
dependencies:
|
||||
- storage: 50Gi # Models can be large
|
||||
|
||||
resources:
|
||||
cpu_limit: 4
|
||||
memory_limit: 8Gi # LLMs need lots of RAM
|
||||
disk_limit: 50Gi
|
||||
|
||||
security:
|
||||
capabilities: []
|
||||
readonly_root: false # Ollama needs write access for models
|
||||
no_new_privileges: true
|
||||
user: 1000
|
||||
seccomp_profile: default
|
||||
network_policy: isolated
|
||||
apparmor_profile: ollama
|
||||
|
||||
ports:
|
||||
- host: 11434
|
||||
container: 11434
|
||||
protocol: tcp # API
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/ollama
|
||||
target: /root/.ollama
|
||||
options: [rw]
|
||||
|
||||
environment:
|
||||
- OLLAMA_HOST=0.0.0.0:11434
|
||||
- OLLAMA_KEEP_ALIVE=24h
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost:11434
|
||||
path: /api/tags
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
@@ -1,5 +0,0 @@
|
||||
# Penpot - uses official image
|
||||
FROM penpot/penpot:latest
|
||||
|
||||
# Default configuration is in the image
|
||||
# No additional setup needed
|
||||
@@ -1,51 +0,0 @@
|
||||
app:
|
||||
id: penpot
|
||||
name: Penpot
|
||||
version: 2.0.0
|
||||
description: Open-source design and prototyping platform. Design tools for teams.
|
||||
|
||||
container:
|
||||
image: penpotapp/frontend:2.13.3
|
||||
image_signature: cosign://...
|
||||
pull_policy: if-not-present
|
||||
|
||||
dependencies:
|
||||
- storage: 10Gi
|
||||
|
||||
resources:
|
||||
cpu_limit: 4
|
||||
memory_limit: 4Gi
|
||||
disk_limit: 10Gi
|
||||
|
||||
security:
|
||||
capabilities: []
|
||||
readonly_root: true
|
||||
no_new_privileges: true
|
||||
user: 1000
|
||||
seccomp_profile: default
|
||||
network_policy: isolated
|
||||
apparmor_profile: penpot
|
||||
|
||||
ports:
|
||||
- host: 8089
|
||||
container: 80
|
||||
protocol: tcp # Web UI
|
||||
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/lib/archipelago/penpot
|
||||
target: /app/data
|
||||
options: [rw]
|
||||
|
||||
environment:
|
||||
- PENPOT_PUBLIC_URI=http://localhost:8089
|
||||
- PENPOT_DATABASE_URI=postgresql://penpot:penpot@penpot-db:5432/penpot
|
||||
- PENPOT_REDIS_URI=redis://penpot-redis:6379
|
||||
|
||||
health_check:
|
||||
type: http
|
||||
endpoint: http://localhost:8089
|
||||
path: /api/health
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
Generated
+2
-1
@@ -80,13 +80,14 @@ checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
|
||||
|
||||
[[package]]
|
||||
name = "archipelago"
|
||||
version = "1.3.1"
|
||||
version = "1.7.45-alpha"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"archipelago-container",
|
||||
"archipelago-performance",
|
||||
"archipelago-security",
|
||||
"argon2",
|
||||
"async-trait",
|
||||
"base64 0.21.7",
|
||||
"bcrypt",
|
||||
"bip39",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "archipelago"
|
||||
version = "1.3.4"
|
||||
version = "1.7.45-alpha"
|
||||
edition = "2021"
|
||||
description = "Archipelago Bitcoin Node OS - Native backend"
|
||||
authors = ["Archipelago Team"]
|
||||
@@ -103,6 +103,9 @@ mdns-sd = "0.18"
|
||||
# Systemd watchdog notification
|
||||
sd-notify = "0.4"
|
||||
|
||||
# Trait objects for async methods (container orchestrator trait, Step 4)
|
||||
async-trait = "0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio-test = "0.4"
|
||||
tempfile = "3.10"
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
//! HTTP handlers for the content-addressed blob store.
|
||||
//!
|
||||
//! - `POST /api/blob` — session-authenticated. Raw body is the blob;
|
||||
//! headers set mime/filename. Returns `{cid, size, mime}`.
|
||||
//! - `GET /blob/<cid>?cap=<hex>&exp=<epoch>&peer=<pubkey>` — peer-facing.
|
||||
//! Capability verified against the stored HMAC key; bytes streamed back.
|
||||
|
||||
use super::{build_response, ApiHandler};
|
||||
use crate::blobs::BlobStore;
|
||||
use anyhow::Result;
|
||||
use hyper::{Body, HeaderMap, Response, StatusCode};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Read the archipelago .onion address if Tor has published one, so uploads
|
||||
/// that need to be publicly reachable (profile pictures, banners) can return
|
||||
/// a URL a peer outside the LAN can actually fetch. Returns `None` before
|
||||
/// onboarding or when Tor isn't running — callers fall back to the local
|
||||
/// self-test URL.
|
||||
async fn read_self_onion(data_dir: &Path) -> Option<String> {
|
||||
let hostnames = data_dir.join("tor-hostnames").join("archipelago");
|
||||
let legacy = Path::new("/var/lib/archipelago/tor-hostnames/archipelago");
|
||||
for p in [hostnames.as_path(), legacy] {
|
||||
if let Ok(s) = tokio::fs::read_to_string(p).await {
|
||||
let trimmed = s.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return Some(trimmed.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl ApiHandler {
|
||||
pub(super) async fn handle_blob_upload(
|
||||
store: &Arc<BlobStore>,
|
||||
self_pubkey_hex: &str,
|
||||
data_dir: &Path,
|
||||
headers: &HeaderMap,
|
||||
body: hyper::body::Bytes,
|
||||
) -> Result<Response<Body>> {
|
||||
let mime = headers
|
||||
.get("x-blob-mime")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("application/octet-stream")
|
||||
.to_string();
|
||||
let filename = headers
|
||||
.get("x-blob-filename")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
let bytes = body.to_vec();
|
||||
// Uploads through /api/blob come from the node owner's session and
|
||||
// are almost always intended for external consumption (profile
|
||||
// pictures, banners). Store them public so `/blob/<cid>` serves
|
||||
// without a capability check — external Nostr clients fetching a
|
||||
// kind-0 `picture` URL have no cap and can't get one.
|
||||
match store.put(&bytes, &mime, filename, None, true).await {
|
||||
Ok(meta) => {
|
||||
let exp =
|
||||
(chrono::Utc::now().timestamp() as u64) + crate::blobs::DEFAULT_CAP_TTL_SECS;
|
||||
let cap = store.issue_capability(&meta.cid, self_pubkey_hex, exp);
|
||||
let self_test_url = format!(
|
||||
"/blob/{}?cap={}&exp={}&peer={}",
|
||||
meta.cid, cap, exp, self_pubkey_hex
|
||||
);
|
||||
let public_url = match read_self_onion(data_dir).await {
|
||||
Some(onion) => format!("http://{}/blob/{}", onion, meta.cid),
|
||||
// Pre-onboarding / Tor-not-up: surface the local path so
|
||||
// the UI doesn't break; publishing to Nostr should wait
|
||||
// until Tor is live anyway.
|
||||
None => format!("/blob/{}", meta.cid),
|
||||
};
|
||||
let resp = serde_json::json!({
|
||||
"cid": meta.cid,
|
||||
"size": meta.size,
|
||||
"mime": meta.mime,
|
||||
"filename": meta.filename,
|
||||
"public_url": public_url,
|
||||
"self_test_url": self_test_url,
|
||||
});
|
||||
Ok(build_response(
|
||||
StatusCode::OK,
|
||||
"application/json",
|
||||
Body::from(serde_json::to_vec(&resp).unwrap_or_default()),
|
||||
))
|
||||
}
|
||||
Err(e) => Ok(build_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"text/plain",
|
||||
Body::from(format!("blob upload failed: {}", e)),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Share-to-mesh iframe intent. Mirrors `handle_blob_upload` but adds
|
||||
/// CORS headers for the requesting app origin and returns a small JSON
|
||||
/// payload the app forwards to its parent via postMessage:
|
||||
/// `{ type: "share-to-mesh", cid, size, mime, filename }`.
|
||||
pub(super) async fn handle_share_to_mesh(
|
||||
store: &Arc<BlobStore>,
|
||||
self_pubkey_hex: &str,
|
||||
headers: &HeaderMap,
|
||||
body: hyper::body::Bytes,
|
||||
origin: &str,
|
||||
) -> Result<Response<Body>> {
|
||||
let mime = headers
|
||||
.get("x-blob-mime")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("application/octet-stream")
|
||||
.to_string();
|
||||
let filename = headers
|
||||
.get("x-blob-filename")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
let bytes = body.to_vec();
|
||||
let meta = match store.put(&bytes, &mime, filename, None, false).await {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
return Ok(build_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"text/plain",
|
||||
Body::from(format!("share-to-mesh failed: {}", e)),
|
||||
));
|
||||
}
|
||||
};
|
||||
// Self-signed capability so the app can preview/download its own
|
||||
// upload before the user has picked a peer.
|
||||
let exp = (chrono::Utc::now().timestamp() as u64) + crate::blobs::DEFAULT_CAP_TTL_SECS;
|
||||
let cap = store.issue_capability(&meta.cid, self_pubkey_hex, exp);
|
||||
let self_url = format!(
|
||||
"/blob/{}?cap={}&exp={}&peer={}",
|
||||
meta.cid, cap, exp, self_pubkey_hex
|
||||
);
|
||||
let resp = serde_json::json!({
|
||||
"type": "share-to-mesh",
|
||||
"cid": meta.cid,
|
||||
"size": meta.size,
|
||||
"mime": meta.mime,
|
||||
"filename": meta.filename,
|
||||
"self_url": self_url,
|
||||
});
|
||||
let body_vec = serde_json::to_vec(&resp).unwrap_or_default();
|
||||
Ok(Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Access-Control-Allow-Origin", origin)
|
||||
.header("Access-Control-Allow-Credentials", "true")
|
||||
.header("Vary", "Origin")
|
||||
.body(Body::from(body_vec))
|
||||
.unwrap_or_else(|_| Response::new(Body::from("internal error"))))
|
||||
}
|
||||
|
||||
pub(super) async fn handle_blob_download(
|
||||
store: &Arc<BlobStore>,
|
||||
path: &str,
|
||||
query: &str,
|
||||
) -> Result<Response<Body>> {
|
||||
let cid = path.strip_prefix("/blob/").unwrap_or("");
|
||||
if cid.is_empty() || !cid.chars().all(|c| c.is_ascii_hexdigit()) || cid.len() != 64 {
|
||||
return Ok(build_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"text/plain",
|
||||
Body::from("invalid cid"),
|
||||
));
|
||||
}
|
||||
|
||||
// Public blobs (profile pictures, banners) bypass the capability
|
||||
// check — their CID is published on Nostr relays where any reader
|
||||
// can see it, and external readers have no way to obtain a cap.
|
||||
// Only blobs explicitly marked public at upload time qualify.
|
||||
let is_public = store.meta(cid).await.map(|m| m.public).unwrap_or(false);
|
||||
|
||||
if !is_public {
|
||||
let mut cap = None;
|
||||
let mut exp: Option<u64> = None;
|
||||
let mut peer = None;
|
||||
for pair in query.split('&') {
|
||||
let mut it = pair.splitn(2, '=');
|
||||
match (it.next(), it.next()) {
|
||||
(Some("cap"), Some(v)) => cap = Some(v.to_string()),
|
||||
(Some("exp"), Some(v)) => exp = v.parse().ok(),
|
||||
(Some("peer"), Some(v)) => peer = Some(v.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (Some(cap), Some(exp), Some(peer)) = (cap, exp, peer) else {
|
||||
return Ok(build_response(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"text/plain",
|
||||
Body::from("missing cap/exp/peer"),
|
||||
));
|
||||
};
|
||||
|
||||
if let Err(e) = store.verify_capability(cid, &peer, exp, &cap) {
|
||||
tracing::warn!("blob cap rejected: cid={} peer={} reason={}", cid, peer, e);
|
||||
return Ok(build_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"text/plain",
|
||||
Body::from(format!("capability rejected: {}", e)),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = match store.get(cid).await {
|
||||
Ok(b) => b,
|
||||
Err(_) => {
|
||||
return Ok(build_response(
|
||||
StatusCode::NOT_FOUND,
|
||||
"text/plain",
|
||||
Body::from("blob not found"),
|
||||
))
|
||||
}
|
||||
};
|
||||
let mime = store
|
||||
.meta(cid)
|
||||
.await
|
||||
.map(|m| m.mime)
|
||||
.unwrap_or_else(|_| "application/octet-stream".to_string());
|
||||
Ok(build_response(StatusCode::OK, &mime, Body::from(bytes)))
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
use super::build_response;
|
||||
use crate::config::Config;
|
||||
use super::build_response;use crate::content_server;
|
||||
use crate::content_server;
|
||||
use anyhow::Result;
|
||||
use hyper::{Response, StatusCode};
|
||||
|
||||
use super::{ApiHandler, is_valid_app_id};
|
||||
use super::{is_valid_app_id, ApiHandler};
|
||||
|
||||
impl ApiHandler {
|
||||
pub(super) async fn handle_content_catalog(config: &Config) -> Result<Response<hyper::Body>> {
|
||||
@@ -25,14 +26,22 @@ impl ApiHandler {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let body = serde_json::to_vec(&serde_json::json!({ "items": items }))
|
||||
.unwrap_or_default();
|
||||
Ok(build_response(StatusCode::OK, "application/json", hyper::Body::from(body)))
|
||||
let body =
|
||||
serde_json::to_vec(&serde_json::json!({ "items": items })).unwrap_or_default();
|
||||
Ok(build_response(
|
||||
StatusCode::OK,
|
||||
"application/json",
|
||||
hyper::Body::from(body),
|
||||
))
|
||||
}
|
||||
Err(e) => {
|
||||
let body = serde_json::json!({ "error": e.to_string() });
|
||||
let body_bytes = serde_json::to_vec(&body).unwrap_or_default();
|
||||
Ok(build_response(StatusCode::INTERNAL_SERVER_ERROR, "application/json", hyper::Body::from(body_bytes)))
|
||||
Ok(build_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"application/json",
|
||||
hyper::Body::from(body_bytes),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,7 +53,11 @@ impl ApiHandler {
|
||||
) -> Result<Response<hyper::Body>> {
|
||||
let content_id = path.strip_prefix("/content/").unwrap_or("");
|
||||
if content_id.is_empty() || !is_valid_app_id(content_id) {
|
||||
return Ok(build_response(StatusCode::BAD_REQUEST, "text/plain", hyper::Body::from("Invalid content ID")));
|
||||
return Ok(build_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"text/plain",
|
||||
hyper::Body::from("Invalid content ID"),
|
||||
));
|
||||
}
|
||||
|
||||
// Extract payment token from X-Payment-Token header
|
||||
@@ -90,16 +103,17 @@ impl ApiHandler {
|
||||
start,
|
||||
end,
|
||||
total,
|
||||
}) => {
|
||||
Ok(Response::builder()
|
||||
.status(StatusCode::PARTIAL_CONTENT)
|
||||
.header("Content-Type", mime_type)
|
||||
.header("Content-Length", bytes.len().to_string())
|
||||
.header("Content-Range", format!("bytes {}-{}/{}", start, end, total))
|
||||
.header("Accept-Ranges", "bytes")
|
||||
.body(hyper::Body::from(bytes))
|
||||
.unwrap())
|
||||
}
|
||||
}) => Ok(Response::builder()
|
||||
.status(StatusCode::PARTIAL_CONTENT)
|
||||
.header("Content-Type", mime_type)
|
||||
.header("Content-Length", bytes.len().to_string())
|
||||
.header(
|
||||
"Content-Range",
|
||||
format!("bytes {}-{}/{}", start, end, total),
|
||||
)
|
||||
.header("Accept-Ranges", "bytes")
|
||||
.body(hyper::Body::from(bytes))
|
||||
.unwrap()),
|
||||
Ok(content_server::ServeResult::PaymentRequired(price_sats)) => {
|
||||
let body = serde_json::json!({
|
||||
"error": "Payment required",
|
||||
@@ -107,16 +121,80 @@ impl ApiHandler {
|
||||
"payment_header": "X-Payment-Token",
|
||||
});
|
||||
let body_bytes = serde_json::to_vec(&body).unwrap_or_default();
|
||||
Ok(build_response(StatusCode::PAYMENT_REQUIRED, "application/json", hyper::Body::from(body_bytes)))
|
||||
Ok(build_response(
|
||||
StatusCode::PAYMENT_REQUIRED,
|
||||
"application/json",
|
||||
hyper::Body::from(body_bytes),
|
||||
))
|
||||
}
|
||||
Ok(content_server::ServeResult::Forbidden) => {
|
||||
Ok(build_response(StatusCode::FORBIDDEN, "application/json", hyper::Body::from(
|
||||
r#"{"error":"Access denied — federation peer required"}"#,
|
||||
)))
|
||||
Ok(content_server::ServeResult::Forbidden) => Ok(build_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"application/json",
|
||||
hyper::Body::from(r#"{"error":"Access denied — federation peer required"}"#),
|
||||
)),
|
||||
Ok(content_server::ServeResult::NotFound) | Err(_) => Ok(build_response(
|
||||
StatusCode::NOT_FOUND,
|
||||
"text/plain",
|
||||
hyper::Body::from("Content not found"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve a degraded preview of paid content (blurred image or first 2% of video).
|
||||
pub(super) async fn handle_content_preview(
|
||||
path: &str,
|
||||
config: &Config,
|
||||
) -> Result<Response<hyper::Body>> {
|
||||
// Path format: /content/{id}/preview
|
||||
let content_id = path
|
||||
.strip_prefix("/content/")
|
||||
.and_then(|s| s.strip_suffix("/preview"))
|
||||
.unwrap_or("");
|
||||
|
||||
if content_id.is_empty() || !is_valid_app_id(content_id) {
|
||||
return Ok(build_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"text/plain",
|
||||
hyper::Body::from("Invalid content ID"),
|
||||
));
|
||||
}
|
||||
|
||||
match content_server::serve_content_preview(&config.data_dir, content_id).await {
|
||||
Ok(content_server::PreviewResult::FullContent(bytes, mime_type)) => {
|
||||
let len = bytes.len();
|
||||
Ok(Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("Content-Type", mime_type)
|
||||
.header("Content-Length", len.to_string())
|
||||
.body(hyper::Body::from(bytes))
|
||||
.unwrap())
|
||||
}
|
||||
Ok(content_server::ServeResult::NotFound) | Err(_) => {
|
||||
Ok(build_response(StatusCode::NOT_FOUND, "text/plain", hyper::Body::from("Content not found")))
|
||||
Ok(content_server::PreviewResult::BlurPreview(bytes, mime_type)) => {
|
||||
let len = bytes.len();
|
||||
Ok(Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("Content-Type", mime_type)
|
||||
.header("Content-Length", len.to_string())
|
||||
.header("X-Content-Preview", "blur")
|
||||
.body(hyper::Body::from(bytes))
|
||||
.unwrap())
|
||||
}
|
||||
Ok(content_server::PreviewResult::TruncatedPreview(bytes, mime_type, total_size)) => {
|
||||
let len = bytes.len();
|
||||
Ok(Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("Content-Type", mime_type)
|
||||
.header("Content-Length", len.to_string())
|
||||
.header("X-Content-Preview", "truncated")
|
||||
.header("X-Content-Total-Size", total_size.to_string())
|
||||
.body(hyper::Body::from(bytes))
|
||||
.unwrap())
|
||||
}
|
||||
Ok(content_server::PreviewResult::NotFound) | Err(_) => Ok(build_response(
|
||||
StatusCode::NOT_FOUND,
|
||||
"text/plain",
|
||||
hyper::Body::from("Preview not available"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::build_response;
|
||||
use crate::config::Config;
|
||||
use super::build_response;use crate::network::dwn_store::DwnStore;
|
||||
use crate::network::dwn_store::DwnStore;
|
||||
use anyhow::Result;
|
||||
use hyper::{Response, StatusCode};
|
||||
|
||||
@@ -10,11 +11,14 @@ impl ApiHandler {
|
||||
pub(super) async fn handle_dwn_health(config: &Config) -> Result<Response<hyper::Body>> {
|
||||
match DwnStore::new(&config.data_dir).await {
|
||||
Ok(store) => {
|
||||
let stats = store.stats().await.unwrap_or(crate::network::dwn_store::StoreStats {
|
||||
message_count: 0,
|
||||
protocol_count: 0,
|
||||
total_bytes: 0,
|
||||
});
|
||||
let stats = store
|
||||
.stats()
|
||||
.await
|
||||
.unwrap_or(crate::network::dwn_store::StoreStats {
|
||||
message_count: 0,
|
||||
protocol_count: 0,
|
||||
total_bytes: 0,
|
||||
});
|
||||
let body = serde_json::json!({
|
||||
"status": "ok",
|
||||
"message_count": stats.message_count,
|
||||
@@ -27,7 +31,11 @@ impl ApiHandler {
|
||||
.body(hyper::Body::from(body.to_string()))
|
||||
.unwrap())
|
||||
}
|
||||
Err(_) => Ok(build_response(StatusCode::SERVICE_UNAVAILABLE, "application/json", hyper::Body::from(r#"{"status":"unavailable"}"#))),
|
||||
Err(_) => Ok(build_response(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"application/json",
|
||||
hyper::Body::from(r#"{"status":"unavailable"}"#),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,12 +70,8 @@ impl ApiHandler {
|
||||
let mut results = Vec::new();
|
||||
|
||||
for message in &messages {
|
||||
let interface = message["descriptor"]["interface"]
|
||||
.as_str()
|
||||
.unwrap_or("");
|
||||
let method = message["descriptor"]["method"]
|
||||
.as_str()
|
||||
.unwrap_or("");
|
||||
let interface = message["descriptor"]["interface"].as_str().unwrap_or("");
|
||||
let method = message["descriptor"]["method"].as_str().unwrap_or("");
|
||||
|
||||
let result = match (interface, method) {
|
||||
("Records", "Write") => {
|
||||
@@ -88,7 +92,9 @@ impl ApiHandler {
|
||||
Ok(msg) => {
|
||||
serde_json::json!({"status": {"code": 202}, "entry": msg})
|
||||
}
|
||||
Err(e) => serde_json::json!({"status": {"code": 500, "detail": e.to_string()}}),
|
||||
Err(e) => {
|
||||
serde_json::json!({"status": {"code": 500, "detail": e.to_string()}})
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -97,7 +103,9 @@ impl ApiHandler {
|
||||
.await
|
||||
{
|
||||
Ok(msg) => serde_json::json!({"status": {"code": 202}, "entry": msg}),
|
||||
Err(e) => serde_json::json!({"status": {"code": 500, "detail": e.to_string()}}),
|
||||
Err(e) => {
|
||||
serde_json::json!({"status": {"code": 500, "detail": e.to_string()}})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,26 +140,26 @@ impl ApiHandler {
|
||||
}
|
||||
}
|
||||
("Records", "Read") => {
|
||||
let record_id = message["descriptor"]["recordId"]
|
||||
.as_str()
|
||||
.unwrap_or("");
|
||||
let record_id = message["descriptor"]["recordId"].as_str().unwrap_or("");
|
||||
match store.read_message(record_id).await {
|
||||
Ok(Some(msg)) => {
|
||||
serde_json::json!({"status": {"code": 200}, "entry": msg})
|
||||
}
|
||||
Ok(None) => serde_json::json!({"status": {"code": 404, "detail": "Record not found"}}),
|
||||
Ok(None) => {
|
||||
serde_json::json!({"status": {"code": 404, "detail": "Record not found"}})
|
||||
}
|
||||
Err(e) => {
|
||||
serde_json::json!({"status": {"code": 500, "detail": e.to_string()}})
|
||||
}
|
||||
}
|
||||
}
|
||||
("Records", "Delete") => {
|
||||
let record_id = message["descriptor"]["recordId"]
|
||||
.as_str()
|
||||
.unwrap_or("");
|
||||
let record_id = message["descriptor"]["recordId"].as_str().unwrap_or("");
|
||||
match store.delete_message(record_id).await {
|
||||
Ok(true) => serde_json::json!({"status": {"code": 200}}),
|
||||
Ok(false) => serde_json::json!({"status": {"code": 404, "detail": "Record not found"}}),
|
||||
Ok(false) => {
|
||||
serde_json::json!({"status": {"code": 404, "detail": "Record not found"}})
|
||||
}
|
||||
Err(e) => {
|
||||
serde_json::json!({"status": {"code": 500, "detail": e.to_string()}})
|
||||
}
|
||||
@@ -184,6 +192,10 @@ impl ApiHandler {
|
||||
)
|
||||
};
|
||||
|
||||
Ok(build_response(http_status, "application/json", hyper::Body::from(response_body)))
|
||||
Ok(build_response(
|
||||
http_status,
|
||||
"application/json",
|
||||
hyper::Body::from(response_body),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
mod blob;
|
||||
mod content;
|
||||
mod dwn;
|
||||
mod node_message;
|
||||
@@ -7,12 +8,15 @@ mod remote_relay;
|
||||
mod websocket;
|
||||
|
||||
use crate::api::rpc::RpcHandler;
|
||||
use crate::blobs::BlobStore;
|
||||
use crate::config::Config;
|
||||
use crate::container::{ContainerOrchestrator, DevContainerOrchestrator};
|
||||
use crate::monitoring::MetricsStore;
|
||||
use crate::session::{self, SessionStore};
|
||||
use crate::state::StateManager;
|
||||
use anyhow::Result;
|
||||
use hyper::{Method, Request, Response, StatusCode};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::broadcast;
|
||||
use tracing::debug;
|
||||
@@ -20,7 +24,11 @@ use tracing::debug;
|
||||
/// Build an HTTP response without unwrap. Falls back to a plain 500 if builder fails.
|
||||
// Used by handler submodules after unwrap elimination
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn build_response(status: StatusCode, content_type: &str, body: hyper::Body) -> Response<hyper::Body> {
|
||||
pub(super) fn build_response(
|
||||
status: StatusCode,
|
||||
content_type: &str,
|
||||
body: hyper::Body,
|
||||
) -> Response<hyper::Body> {
|
||||
Response::builder()
|
||||
.status(status)
|
||||
.header("Content-Type", content_type)
|
||||
@@ -36,6 +44,10 @@ pub struct ApiHandler {
|
||||
session_store: SessionStore,
|
||||
/// Broadcast channel for relaying companion app input to remote browsers.
|
||||
input_relay_tx: broadcast::Sender<String>,
|
||||
/// Content-addressed blob store for attachments shared over mesh/federation.
|
||||
blob_store: Arc<BlobStore>,
|
||||
/// Our own node pubkey (hex) — used to self-sign debug/test capabilities.
|
||||
self_pubkey_hex: String,
|
||||
}
|
||||
|
||||
impl ApiHandler {
|
||||
@@ -43,6 +55,8 @@ impl ApiHandler {
|
||||
config: Config,
|
||||
state_manager: Arc<StateManager>,
|
||||
metrics_store: Arc<MetricsStore>,
|
||||
orchestrator: Option<Arc<dyn ContainerOrchestrator>>,
|
||||
dev_orchestrator: Option<Arc<DevContainerOrchestrator>>,
|
||||
) -> Result<Self> {
|
||||
let session_store = SessionStore::new().await;
|
||||
let rpc_handler = Arc::new(
|
||||
@@ -51,11 +65,34 @@ impl ApiHandler {
|
||||
state_manager.clone(),
|
||||
metrics_store.clone(),
|
||||
session_store.clone(),
|
||||
orchestrator,
|
||||
dev_orchestrator,
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
let (input_relay_tx, _) = broadcast::channel(64);
|
||||
|
||||
// Derive a blob-store capability key from the node's Ed25519 signing
|
||||
// key. SHA-256 domain-separated so rotating the identity rotates
|
||||
// every outstanding capability token (intentional — prevents a
|
||||
// replaced node from honouring old caps).
|
||||
let identity_dir = config.data_dir.join("identity");
|
||||
let identity = crate::identity::NodeIdentity::load_or_create(&identity_dir).await?;
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(identity.signing_key().to_bytes());
|
||||
hasher.update(b"|archipelago-blob-cap-v1");
|
||||
let mut cap_key = [0u8; 32];
|
||||
cap_key.copy_from_slice(&hasher.finalize());
|
||||
let blob_store = Arc::new(BlobStore::open(&config.data_dir, cap_key).await?);
|
||||
let self_pubkey_hex = hex::encode(identity.signing_key().verifying_key().as_bytes());
|
||||
|
||||
// Share blob store with the RPC layer so mesh.send-content /
|
||||
// mesh.fetch-content can reach the same instance (single cap_key,
|
||||
// single on-disk root) without re-opening it.
|
||||
rpc_handler
|
||||
.set_blob_store(blob_store.clone(), self_pubkey_hex.clone())
|
||||
.await;
|
||||
|
||||
Ok(Self {
|
||||
config,
|
||||
rpc_handler,
|
||||
@@ -63,6 +100,8 @@ impl ApiHandler {
|
||||
metrics_store,
|
||||
session_store,
|
||||
input_relay_tx,
|
||||
blob_store,
|
||||
self_pubkey_hex,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -79,6 +118,79 @@ impl ApiHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Server-side fetch of the upstream app catalog so the browser can
|
||||
/// load it without fighting CORS (git.tx1138.com emits no ACAO) or
|
||||
/// CSP (the fallback IP-port URL isn't in `connect-src`). The upstream
|
||||
/// list is derived from the operator's configured container registries
|
||||
/// so switching mirrors in Settings changes the App Store source too —
|
||||
/// each active registry contributes one Gitea `raw/branch/main/catalog.json`
|
||||
/// URL (http or https per `tls_verify`), tried in priority order.
|
||||
/// If registry config can't be loaded, falls back to the legacy
|
||||
/// hardcoded pair so the App Store still renders on nodes that haven't
|
||||
/// persisted a registry config yet. 15s total timeout.
|
||||
async fn handle_app_catalog_proxy(&self) -> Result<Response<hyper::Body>> {
|
||||
let mut upstreams: Vec<String> = Vec::new();
|
||||
if let Ok(config) = crate::container::registry::load_registries(&self.config.data_dir).await
|
||||
{
|
||||
for reg in config.active_registries() {
|
||||
let scheme = if reg.tls_verify { "https" } else { "http" };
|
||||
// Gitea raw URL: <scheme>://<host>/<namespace>/app-catalog/raw/branch/main/catalog.json.
|
||||
// reg.url already includes the namespace (e.g. "host/lfg2025"),
|
||||
// so we just tack on the repo + raw path.
|
||||
upstreams.push(format!(
|
||||
"{}://{}/app-catalog/raw/branch/main/catalog.json",
|
||||
scheme, reg.url
|
||||
));
|
||||
}
|
||||
}
|
||||
if upstreams.is_empty() {
|
||||
upstreams.push(
|
||||
"http://146.59.87.168:3000/lfg2025/app-catalog/raw/branch/main/catalog.json"
|
||||
.to_string(),
|
||||
);
|
||||
upstreams.push(
|
||||
"https://git.tx1138.com/lfg2025/app-catalog/raw/branch/main/catalog.json"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let client = match reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(15))
|
||||
.build()
|
||||
{
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
return Ok(build_response(
|
||||
hyper::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"text/plain",
|
||||
hyper::Body::from(format!("client build failed: {}", e)),
|
||||
));
|
||||
}
|
||||
};
|
||||
for url in &upstreams {
|
||||
match client.get(url).send().await {
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
if let Ok(bytes) = resp.bytes().await {
|
||||
return Ok(Response::builder()
|
||||
.status(hyper::StatusCode::OK)
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Cache-Control", "public, max-age=3600")
|
||||
.body(hyper::Body::from(bytes))
|
||||
.unwrap_or_else(|_| {
|
||||
Response::new(hyper::Body::from("proxy response build failed"))
|
||||
}));
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
Ok(build_response(
|
||||
hyper::StatusCode::BAD_GATEWAY,
|
||||
"text/plain",
|
||||
hyper::Body::from("all upstream catalog URLs failed"),
|
||||
))
|
||||
}
|
||||
|
||||
/// Build a 401 Unauthorized JSON response.
|
||||
fn unauthorized() -> Response<hyper::Body> {
|
||||
let body = serde_json::json!({ "error": "Unauthorized" });
|
||||
@@ -105,9 +217,7 @@ impl ApiHandler {
|
||||
/// Validate the Origin header against allowed origins.
|
||||
/// Returns the matched origin if valid, None if cross-origin is not allowed.
|
||||
fn validate_origin(&self, headers: &hyper::HeaderMap) -> Option<String> {
|
||||
let origin = headers
|
||||
.get("origin")
|
||||
.and_then(|v| v.to_str().ok())?;
|
||||
let origin = headers.get("origin").and_then(|v| v.to_str().ok())?;
|
||||
let allowed = self.allowed_origins();
|
||||
if allowed.iter().any(|a| a == origin) {
|
||||
Some(origin.to_string())
|
||||
@@ -116,10 +226,37 @@ impl ApiHandler {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handle_request(
|
||||
&self,
|
||||
req: Request<hyper::Body>,
|
||||
) -> Result<Response<hyper::Body>> {
|
||||
/// Permissive origin check for the share-to-mesh iframe intent: any scheme
|
||||
/// http(s):// followed by the configured host_ip, optionally `:port`. Apps
|
||||
/// proxied under other ports (APP_PORTS) call this from within the same
|
||||
/// node, so they share host_ip but not port. The session cookie still has
|
||||
/// to be valid — this is a sanity check, not the primary auth.
|
||||
fn validate_app_origin(&self, headers: &hyper::HeaderMap) -> Option<String> {
|
||||
let origin = headers.get("origin").and_then(|v| v.to_str().ok())?;
|
||||
// Allow localhost dev server too so the Vite frontend can exercise it.
|
||||
if self.config.dev_mode && origin == "http://localhost:8100" {
|
||||
return Some(origin.to_string());
|
||||
}
|
||||
let host_ip = &self.config.host_ip;
|
||||
let matches = |scheme: &str| -> bool {
|
||||
let prefix = format!("{}{}", scheme, host_ip);
|
||||
if origin == prefix {
|
||||
return true;
|
||||
}
|
||||
let with_port = format!("{}:", prefix);
|
||||
origin.starts_with(&with_port)
|
||||
&& origin[with_port.len()..]
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit())
|
||||
};
|
||||
if matches("http://") || matches("https://") {
|
||||
Some(origin.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handle_request(&self, req: Request<hyper::Body>) -> Result<Response<hyper::Body>> {
|
||||
let path = req.uri().path().to_string();
|
||||
let method = req.method().clone();
|
||||
|
||||
@@ -144,7 +281,12 @@ impl ApiHandler {
|
||||
tracing::warn!("401 WebSocket /ws/db — session invalid or missing");
|
||||
return Ok(Self::unauthorized());
|
||||
}
|
||||
return Self::handle_websocket(req, self.state_manager.clone(), self.metrics_store.clone()).await;
|
||||
return Self::handle_websocket(
|
||||
req,
|
||||
self.state_manager.clone(),
|
||||
self.metrics_store.clone(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// Remote input WebSocket — companion app sends keyboard/mouse events
|
||||
@@ -167,8 +309,10 @@ impl ApiHandler {
|
||||
|
||||
// Convert body to bytes for non-WS routes
|
||||
let headers = req.headers().clone();
|
||||
let query_string = req.uri().query().map(|s| s.to_string()).unwrap_or_default();
|
||||
let (parts, body) = req.into_parts();
|
||||
let body_bytes = hyper::body::to_bytes(body).await
|
||||
let body_bytes = hyper::body::to_bytes(body)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to read body: {}", e))?;
|
||||
let req_with_bytes = Request::from_parts(parts, hyper::Body::from(body_bytes.clone()));
|
||||
|
||||
@@ -176,7 +320,7 @@ impl ApiHandler {
|
||||
|
||||
match (method, path.as_str()) {
|
||||
// RPC — auth is handled inside rpc handler per-method
|
||||
(Method::POST, "/rpc/v1") => self.rpc_handler.handle(req_with_bytes).await,
|
||||
(Method::POST, "/rpc/v1") => self.rpc_handler.clone().handle(req_with_bytes).await,
|
||||
|
||||
// Health — unauthenticated, returns JSON with service status
|
||||
(Method::GET, "/health") => {
|
||||
@@ -196,7 +340,9 @@ impl ApiHandler {
|
||||
Ok(Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("Content-Type", "application/json")
|
||||
.body(hyper::Body::from(serde_json::to_vec(&status).unwrap_or_default()))
|
||||
.body(hyper::Body::from(
|
||||
serde_json::to_vec(&status).unwrap_or_default(),
|
||||
))
|
||||
.unwrap())
|
||||
}
|
||||
|
||||
@@ -205,19 +351,97 @@ impl ApiHandler {
|
||||
Self::handle_node_message(body_bytes).await
|
||||
}
|
||||
|
||||
// Mesh typed envelope relay over federation — peers POST
|
||||
// pre-encoded TypedEnvelope wire bytes here when the envelope is
|
||||
// too large for a single LoRa frame (primarily ContentRef). No
|
||||
// session auth: the body carries a pubkey + ed25519 signature
|
||||
// over the wire bytes which we verify before dispatching.
|
||||
(Method::POST, "/archipelago/mesh-typed") => {
|
||||
Self::handle_mesh_typed_relay(self.rpc_handler.clone(), body_bytes).await
|
||||
}
|
||||
|
||||
// Blob upload — local/session use only. Session-authenticated so
|
||||
// only the node owner can push attachments into the blob store.
|
||||
(Method::POST, "/api/blob") => {
|
||||
if !self.is_authenticated(&headers).await {
|
||||
return Ok(Self::unauthorized());
|
||||
}
|
||||
Self::handle_blob_upload(
|
||||
&self.blob_store,
|
||||
&self.self_pubkey_hex,
|
||||
&self.config.data_dir,
|
||||
&headers,
|
||||
body_bytes,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
// Share-to-mesh intent — marketplace app iframes POST a file here
|
||||
// to stage it as a mesh attachment. Same body format as /api/blob
|
||||
// (raw bytes + X-Blob-Mime/X-Blob-Filename headers). The app is
|
||||
// expected to postMessage `{type:'share-to-mesh', cid, ...}` to
|
||||
// its parent window afterwards so the Mesh view can pick it up.
|
||||
// Authenticated by session cookie + a relaxed Origin check (any
|
||||
// port on the archipelago host is allowed, so proxied apps on
|
||||
// their own ports can reach it with credentials:'include').
|
||||
(Method::POST, "/api/share-to-mesh") => {
|
||||
if !self.is_authenticated(&headers).await {
|
||||
return Ok(Self::unauthorized());
|
||||
}
|
||||
let origin = match self.validate_app_origin(&headers) {
|
||||
Some(o) => o,
|
||||
None => {
|
||||
return Ok(build_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"text/plain",
|
||||
hyper::Body::from("origin not allowed"),
|
||||
))
|
||||
}
|
||||
};
|
||||
Self::handle_share_to_mesh(
|
||||
&self.blob_store,
|
||||
&self.self_pubkey_hex,
|
||||
&headers,
|
||||
body_bytes,
|
||||
&origin,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
// Blob download — peer-facing. No session required; authenticated
|
||||
// by HMAC capability token signed when the blob ref was shared.
|
||||
(Method::GET, p) if p.starts_with("/blob/") => {
|
||||
Self::handle_blob_download(&self.blob_store, p, &query_string).await
|
||||
}
|
||||
|
||||
// Content preview — degraded previews for paid content (no auth, no payment)
|
||||
(Method::GET, p) if p.starts_with("/content/") && p.ends_with("/preview") => {
|
||||
Self::handle_content_preview(p, &self.config).await
|
||||
}
|
||||
|
||||
// Content serving — peers access shared content over Tor (no session auth)
|
||||
(Method::GET, p) if p.starts_with("/content/") => {
|
||||
Self::handle_content_request(p, &headers, &self.config).await
|
||||
}
|
||||
|
||||
// Content catalog — list available content (no session auth, for peers)
|
||||
(Method::GET, "/content") => {
|
||||
Self::handle_content_catalog(&self.config).await
|
||||
}
|
||||
(Method::GET, "/content") => Self::handle_content_catalog(&self.config).await,
|
||||
|
||||
// Electrs status — unauthenticated (read-only sync status)
|
||||
(Method::GET, "/electrs-status") => Self::handle_electrs_status().await,
|
||||
|
||||
// App-catalog proxy — fetches catalog.json from the configured
|
||||
// upstream URLs server-side so the browser doesn't hit CORS
|
||||
// (git.tx1138.com has no ACAO header) or CSP (IP-port upstream
|
||||
// falls outside `connect-src`). Session-authenticated so only
|
||||
// the logged-in node owner can spin up fetches.
|
||||
(Method::GET, "/api/app-catalog") => {
|
||||
if !self.is_authenticated(&headers).await {
|
||||
return Ok(Self::unauthorized());
|
||||
}
|
||||
self.handle_app_catalog_proxy().await
|
||||
}
|
||||
|
||||
// LND connect info — nginx validates session cookie (presence check),
|
||||
// backend is bound to 127.0.0.1 so only nginx can reach it.
|
||||
// No backend auth check here because the LND UI iframe fetches this
|
||||
@@ -245,14 +469,10 @@ impl ApiHandler {
|
||||
}
|
||||
|
||||
// DWN health — unauthenticated
|
||||
(Method::GET, "/dwn/health") => {
|
||||
Self::handle_dwn_health(&self.config).await
|
||||
}
|
||||
(Method::GET, "/dwn/health") => Self::handle_dwn_health(&self.config).await,
|
||||
|
||||
// DWN message processing — peers access over Tor for sync (no session auth)
|
||||
(Method::POST, "/dwn") => {
|
||||
Self::handle_dwn_message(body_bytes, &self.config).await
|
||||
}
|
||||
(Method::POST, "/dwn") => Self::handle_dwn_message(body_bytes, &self.config).await,
|
||||
|
||||
_ => Ok(Response::builder()
|
||||
.status(StatusCode::NOT_FOUND)
|
||||
@@ -266,7 +486,9 @@ impl ApiHandler {
|
||||
fn is_valid_app_id(id: &str) -> bool {
|
||||
!id.is_empty()
|
||||
&& id.len() <= 64
|
||||
&& id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||
&& id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||
&& id.as_bytes()[0] != b'-'
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
use super::build_response;
|
||||
use crate::api::rpc::RpcHandler;
|
||||
use crate::node_message as node_msg;
|
||||
use super::build_response;use anyhow::Result;
|
||||
use anyhow::Result;
|
||||
use hyper::{Response, StatusCode};
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{ApiHandler, is_valid_pubkey_hex, sanitize_html, sanitize_log_string};
|
||||
use super::{is_valid_pubkey_hex, sanitize_html, sanitize_log_string, ApiHandler};
|
||||
|
||||
impl ApiHandler {
|
||||
pub(super) async fn handle_node_message(body: hyper::body::Bytes) -> Result<Response<hyper::Body>> {
|
||||
pub(super) async fn handle_node_message(
|
||||
body: hyper::body::Bytes,
|
||||
) -> Result<Response<hyper::Body>> {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Incoming {
|
||||
from_pubkey: Option<String>,
|
||||
from_name: Option<String>,
|
||||
message: Option<String>,
|
||||
signature: Option<String>,
|
||||
#[serde(default)]
|
||||
@@ -16,21 +22,31 @@ impl ApiHandler {
|
||||
}
|
||||
let incoming: Incoming = serde_json::from_slice(&body).unwrap_or(Incoming {
|
||||
from_pubkey: None,
|
||||
from_name: None,
|
||||
message: None,
|
||||
signature: None,
|
||||
encrypted: false,
|
||||
});
|
||||
if let (Some(from), Some(msg)) = (incoming.from_pubkey.as_ref(), incoming.message.as_ref()) {
|
||||
if let (Some(from), Some(msg)) = (incoming.from_pubkey.as_ref(), incoming.message.as_ref())
|
||||
{
|
||||
// Validate from_pubkey is a valid hex ed25519 pubkey
|
||||
if !is_valid_pubkey_hex(from) {
|
||||
return Ok(build_response(StatusCode::BAD_REQUEST, "application/json", hyper::Body::from(r#"{"error":"Invalid pubkey format"}"#)));
|
||||
return Ok(build_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"application/json",
|
||||
hyper::Body::from(r#"{"error":"Invalid pubkey format"}"#),
|
||||
));
|
||||
}
|
||||
// Verify ed25519 signature if provided (required for trusted messages)
|
||||
if let Some(sig_hex) = &incoming.signature {
|
||||
match crate::identity::NodeIdentity::verify(from, msg.as_bytes(), sig_hex) {
|
||||
Ok(true) => {}
|
||||
_ => {
|
||||
return Ok(build_response(StatusCode::FORBIDDEN, "application/json", hyper::Body::from(r#"{"error":"Invalid signature"}"#)));
|
||||
return Ok(build_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"application/json",
|
||||
hyper::Body::from(r#"{"error":"Invalid signature"}"#),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,12 +60,23 @@ impl ApiHandler {
|
||||
Ok(node_id) => {
|
||||
match node_msg::decrypt_from_peer(node_id.signing_key(), from, msg) {
|
||||
Ok(decrypted) => {
|
||||
tracing::info!("Decrypted E2E message from {}...", &from[..16.min(from.len())]);
|
||||
tracing::info!(
|
||||
"Decrypted E2E message from {}...",
|
||||
&from[..16.min(from.len())]
|
||||
);
|
||||
decrypted
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("E2E decryption failed from {}: {}", &from[..16.min(from.len())], e);
|
||||
return Ok(build_response(StatusCode::BAD_REQUEST, "application/json", hyper::Body::from(r#"{"error":"Decryption failed"}"#)));
|
||||
tracing::warn!(
|
||||
"E2E decryption failed from {}: {}",
|
||||
&from[..16.min(from.len())],
|
||||
e
|
||||
);
|
||||
return Ok(build_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"application/json",
|
||||
hyper::Body::from(r#"{"error":"Decryption failed"}"#),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,13 +89,152 @@ impl ApiHandler {
|
||||
msg.clone()
|
||||
};
|
||||
|
||||
// Detect a `connection_accepted` reply: the remote peer just
|
||||
// approved an outbound request we sent, so mirror their add on
|
||||
// our side (bidirectional peering without a manual second
|
||||
// click). JSON-shape only — any non-matching payload stays in
|
||||
// the normal received-messages store below.
|
||||
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&plaintext) {
|
||||
if val.get("type").and_then(|v| v.as_str()) == Some("connection_accepted") {
|
||||
if let (Some(their_onion), Some(their_pubkey)) = (
|
||||
val.get("from_onion").and_then(|v| v.as_str()),
|
||||
val.get("from_pubkey").and_then(|v| v.as_str()),
|
||||
) {
|
||||
let data_dir = std::path::Path::new("/var/lib/archipelago");
|
||||
let peer = crate::peers::KnownPeer {
|
||||
onion: their_onion.to_string(),
|
||||
pubkey: their_pubkey.to_string(),
|
||||
name: val
|
||||
.get("from_name")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from),
|
||||
added_at: Some(chrono::Utc::now().to_rfc3339()),
|
||||
};
|
||||
match crate::peers::add_peer(data_dir, peer).await {
|
||||
Ok(_) => tracing::info!(
|
||||
from = %sanitize_log_string(from),
|
||||
"Auto-added peer after connection_accepted"
|
||||
),
|
||||
Err(e) => tracing::warn!(
|
||||
from = %sanitize_log_string(from),
|
||||
error = %e,
|
||||
"Failed to auto-add peer on connection_accepted"
|
||||
),
|
||||
}
|
||||
}
|
||||
return Ok(build_response(
|
||||
StatusCode::OK,
|
||||
"application/json",
|
||||
hyper::Body::from(r#"{"ok":true,"handled":"connection_accepted"}"#),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let safe_from = sanitize_log_string(from);
|
||||
let safe_msg = sanitize_log_string(&plaintext);
|
||||
tracing::info!("Received message from {}: {}", safe_from, safe_msg);
|
||||
let clean_from = sanitize_html(from);
|
||||
let clean_msg = sanitize_html(&plaintext);
|
||||
node_msg::store_received(&clean_from, &clean_msg).await;
|
||||
let clean_name = incoming.from_name.as_deref().map(sanitize_html);
|
||||
node_msg::store_received(&clean_from, &clean_msg, clean_name.as_deref()).await;
|
||||
}
|
||||
Ok(build_response(StatusCode::OK, "application/json", hyper::Body::from(r#"{"ok":true}"#)))
|
||||
Ok(build_response(
|
||||
StatusCode::OK,
|
||||
"application/json",
|
||||
hyper::Body::from(r#"{"ok":true}"#),
|
||||
))
|
||||
}
|
||||
|
||||
/// Federation-routed mesh typed envelope. Body:
|
||||
/// `{from_pubkey, from_name?, typed_envelope_b64, signature}`
|
||||
/// Signature is ed25519 over the raw wire bytes, verified against
|
||||
/// from_pubkey before dispatch.
|
||||
pub(super) async fn handle_mesh_typed_relay(
|
||||
rpc_handler: Arc<RpcHandler>,
|
||||
body: hyper::body::Bytes,
|
||||
) -> Result<Response<hyper::Body>> {
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Incoming {
|
||||
from_pubkey: String,
|
||||
#[serde(default)]
|
||||
from_name: Option<String>,
|
||||
typed_envelope_b64: String,
|
||||
signature: String,
|
||||
}
|
||||
let incoming: Incoming = match serde_json::from_slice(&body) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
return Ok(build_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"application/json",
|
||||
hyper::Body::from(format!(r#"{{"error":"bad json: {}"}}"#, e)),
|
||||
));
|
||||
}
|
||||
};
|
||||
if !is_valid_pubkey_hex(&incoming.from_pubkey) {
|
||||
return Ok(build_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"application/json",
|
||||
hyper::Body::from(r#"{"error":"invalid pubkey"}"#),
|
||||
));
|
||||
}
|
||||
let wire = match BASE64.decode(incoming.typed_envelope_b64.as_bytes()) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
return Ok(build_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"application/json",
|
||||
hyper::Body::from(r#"{"error":"bad base64"}"#),
|
||||
));
|
||||
}
|
||||
};
|
||||
match crate::identity::NodeIdentity::verify(
|
||||
&incoming.from_pubkey,
|
||||
&wire,
|
||||
&incoming.signature,
|
||||
) {
|
||||
Ok(true) => {}
|
||||
_ => {
|
||||
return Ok(build_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"application/json",
|
||||
hyper::Body::from(r#"{"error":"signature rejected"}"#),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Inject into mesh state via the shared MeshService. Mirrors a radio
|
||||
// receive, so the message lands in the same chat stream as LoRa-
|
||||
// delivered messages from the same peer.
|
||||
let service = rpc_handler.mesh_service_arc();
|
||||
let svc_guard = service.read().await;
|
||||
let Some(svc) = svc_guard.as_ref() else {
|
||||
return Ok(build_response(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"application/json",
|
||||
hyper::Body::from(r#"{"error":"mesh not running"}"#),
|
||||
));
|
||||
};
|
||||
if let Err(e) = svc
|
||||
.inject_typed_from_federation(
|
||||
&incoming.from_pubkey,
|
||||
incoming.from_name.as_deref(),
|
||||
wire,
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!("mesh-typed relay inject failed: {}", e);
|
||||
return Ok(build_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"application/json",
|
||||
hyper::Body::from(format!(r#"{{"error":"{}"}}"#, e)),
|
||||
));
|
||||
}
|
||||
Ok(build_response(
|
||||
StatusCode::OK,
|
||||
"application/json",
|
||||
hyper::Body::from(r#"{"ok":true}"#),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use super::build_response;
|
||||
use crate::api::rpc::RpcHandler;
|
||||
use super::build_response;use crate::electrs_status;
|
||||
use crate::electrs_status;
|
||||
use anyhow::Result;
|
||||
use hyper::{Response, StatusCode};
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{ApiHandler, is_valid_app_id};
|
||||
use super::{is_valid_app_id, ApiHandler};
|
||||
|
||||
impl ApiHandler {
|
||||
pub(super) async fn handle_container_logs_http(
|
||||
@@ -16,16 +17,15 @@ impl ApiHandler {
|
||||
.strip_prefix("/api/container/logs")
|
||||
.and_then(|s| s.strip_prefix('?'))
|
||||
.unwrap_or("");
|
||||
let params: std::collections::HashMap<String, String> =
|
||||
query
|
||||
.split('&')
|
||||
.filter_map(|p| {
|
||||
let mut it = p.splitn(2, '=');
|
||||
let k = it.next()?.to_string();
|
||||
let v = it.next()?.to_string();
|
||||
Some((k, v))
|
||||
})
|
||||
.collect();
|
||||
let params: std::collections::HashMap<String, String> = query
|
||||
.split('&')
|
||||
.filter_map(|p| {
|
||||
let mut it = p.splitn(2, '=');
|
||||
let k = it.next()?.to_string();
|
||||
let v = it.next()?.to_string();
|
||||
Some((k, v))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let app_id = params.get("app_id").map(|s| s.as_str()).unwrap_or("lnd");
|
||||
|
||||
@@ -33,7 +33,11 @@ impl ApiHandler {
|
||||
if !is_valid_app_id(app_id) {
|
||||
let body = serde_json::json!({ "error": "Invalid app_id" });
|
||||
let body_bytes = serde_json::to_vec(&body).unwrap_or_default();
|
||||
return Ok(build_response(StatusCode::BAD_REQUEST, "application/json", hyper::Body::from(body_bytes)));
|
||||
return Ok(build_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"application/json",
|
||||
hyper::Body::from(body_bytes),
|
||||
));
|
||||
}
|
||||
|
||||
let lines = params
|
||||
@@ -72,7 +76,11 @@ impl ApiHandler {
|
||||
pub(super) async fn handle_electrs_status() -> Result<Response<hyper::Body>> {
|
||||
let status = electrs_status::get_electrs_sync_status().await;
|
||||
let body = serde_json::to_vec(&status).unwrap_or_default();
|
||||
Ok(build_response(StatusCode::OK, "application/json", hyper::Body::from(body)))
|
||||
Ok(build_response(
|
||||
StatusCode::OK,
|
||||
"application/json",
|
||||
hyper::Body::from(body),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn handle_lnd_connect_info(
|
||||
@@ -81,7 +89,11 @@ impl ApiHandler {
|
||||
match rpc.handle_lnd_connect_info().await {
|
||||
Ok(val) => {
|
||||
let body = serde_json::to_vec(&val).unwrap_or_default();
|
||||
Ok(build_response(StatusCode::OK, "application/json", hyper::Body::from(body)))
|
||||
Ok(build_response(
|
||||
StatusCode::OK,
|
||||
"application/json",
|
||||
hyper::Body::from(body),
|
||||
))
|
||||
}
|
||||
Err(e) => Ok(Response::builder()
|
||||
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
@@ -93,7 +105,10 @@ impl ApiHandler {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn handle_lnd_proxy(path: &str, cors_origin: &str) -> Result<Response<hyper::Body>> {
|
||||
pub(super) async fn handle_lnd_proxy(
|
||||
path: &str,
|
||||
cors_origin: &str,
|
||||
) -> Result<Response<hyper::Body>> {
|
||||
let suffix = path.strip_prefix("/proxy/lnd").unwrap_or("/");
|
||||
let url = format!("http://127.0.0.1:8080{}", suffix);
|
||||
match reqwest::get(&url).await {
|
||||
|
||||
@@ -4,7 +4,6 @@ use hyper::{Request, Response};
|
||||
use hyper_ws_listener::WsStream;
|
||||
use serde::Deserialize;
|
||||
use std::time::Instant;
|
||||
use tokio::process::Command;
|
||||
use tokio::sync::broadcast;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tracing::{debug, info, warn};
|
||||
@@ -14,27 +13,131 @@ use super::ApiHandler;
|
||||
/// Allowed xdotool key names. Only these pass validation.
|
||||
const ALLOWED_KEYS: &[&str] = &[
|
||||
// Letters
|
||||
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
|
||||
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
|
||||
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
|
||||
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
|
||||
"a",
|
||||
"b",
|
||||
"c",
|
||||
"d",
|
||||
"e",
|
||||
"f",
|
||||
"g",
|
||||
"h",
|
||||
"i",
|
||||
"j",
|
||||
"k",
|
||||
"l",
|
||||
"m",
|
||||
"n",
|
||||
"o",
|
||||
"p",
|
||||
"q",
|
||||
"r",
|
||||
"s",
|
||||
"t",
|
||||
"u",
|
||||
"v",
|
||||
"w",
|
||||
"x",
|
||||
"y",
|
||||
"z",
|
||||
"A",
|
||||
"B",
|
||||
"C",
|
||||
"D",
|
||||
"E",
|
||||
"F",
|
||||
"G",
|
||||
"H",
|
||||
"I",
|
||||
"J",
|
||||
"K",
|
||||
"L",
|
||||
"M",
|
||||
"N",
|
||||
"O",
|
||||
"P",
|
||||
"Q",
|
||||
"R",
|
||||
"S",
|
||||
"T",
|
||||
"U",
|
||||
"V",
|
||||
"W",
|
||||
"X",
|
||||
"Y",
|
||||
"Z",
|
||||
// Numbers
|
||||
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
|
||||
"0",
|
||||
"1",
|
||||
"2",
|
||||
"3",
|
||||
"4",
|
||||
"5",
|
||||
"6",
|
||||
"7",
|
||||
"8",
|
||||
"9",
|
||||
// Navigation
|
||||
"Up", "Down", "Left", "Right",
|
||||
"Return", "Escape", "Tab", "BackSpace", "Delete",
|
||||
"Home", "End", "Prior", "Next", // Prior=PageUp, Next=PageDown
|
||||
"Up",
|
||||
"Down",
|
||||
"Left",
|
||||
"Right",
|
||||
"Return",
|
||||
"Escape",
|
||||
"Tab",
|
||||
"BackSpace",
|
||||
"Delete",
|
||||
"Home",
|
||||
"End",
|
||||
"Prior",
|
||||
"Next", // Prior=PageUp, Next=PageDown
|
||||
// Modifiers (for combos like shift+a)
|
||||
"space", "minus", "equal", "bracketleft", "bracketright",
|
||||
"backslash", "semicolon", "apostrophe", "grave", "comma",
|
||||
"period", "slash",
|
||||
"space",
|
||||
"minus",
|
||||
"equal",
|
||||
"bracketleft",
|
||||
"bracketright",
|
||||
"backslash",
|
||||
"semicolon",
|
||||
"apostrophe",
|
||||
"grave",
|
||||
"comma",
|
||||
"period",
|
||||
"slash",
|
||||
// Function keys
|
||||
"F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
|
||||
"F1",
|
||||
"F2",
|
||||
"F3",
|
||||
"F4",
|
||||
"F5",
|
||||
"F6",
|
||||
"F7",
|
||||
"F8",
|
||||
"F9",
|
||||
"F10",
|
||||
"F11",
|
||||
"F12",
|
||||
// Symbols — xdotool names
|
||||
"exclam", "at", "numbersign", "dollar", "percent", "asciicircum",
|
||||
"ampersand", "asterisk", "parenleft", "parenright", "underscore",
|
||||
"plus", "braceleft", "braceright", "bar", "colon", "quotedbl",
|
||||
"less", "greater", "question", "asciitilde",
|
||||
"exclam",
|
||||
"at",
|
||||
"numbersign",
|
||||
"dollar",
|
||||
"percent",
|
||||
"asciicircum",
|
||||
"ampersand",
|
||||
"asterisk",
|
||||
"parenleft",
|
||||
"parenright",
|
||||
"underscore",
|
||||
"plus",
|
||||
"braceleft",
|
||||
"braceright",
|
||||
"bar",
|
||||
"colon",
|
||||
"quotedbl",
|
||||
"less",
|
||||
"greater",
|
||||
"question",
|
||||
"asciitilde",
|
||||
];
|
||||
|
||||
/// Validate a key name against the whitelist.
|
||||
@@ -55,7 +158,14 @@ fn validate_key(key: &str) -> bool {
|
||||
#[serde(tag = "t")]
|
||||
enum InputCommand {
|
||||
#[serde(rename = "k")]
|
||||
Key { k: String },
|
||||
Key {
|
||||
k: String,
|
||||
/// Optional player ID (1 or 2) for multi-player arcade games.
|
||||
/// When absent, input is broadcast without player tagging.
|
||||
#[serde(default)]
|
||||
#[allow(dead_code)]
|
||||
p: Option<u8>,
|
||||
},
|
||||
#[serde(rename = "m")]
|
||||
MouseMove { x: i32, y: i32 },
|
||||
#[serde(rename = "c")]
|
||||
@@ -66,50 +176,28 @@ enum InputCommand {
|
||||
Ping,
|
||||
}
|
||||
|
||||
async fn xdotool(args: &[&str]) -> Result<()> {
|
||||
let output = Command::new("xdotool")
|
||||
.env("DISPLAY", ":0")
|
||||
.args(args)
|
||||
.output()
|
||||
.await
|
||||
.context("xdotool execution failed")?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
debug!("xdotool error: {}", stderr);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate and acknowledge input — relay-only, no xdotool.
|
||||
/// All input is forwarded to browser clients via the broadcast channel;
|
||||
/// the browser's remote-relay.ts dispatches DOM events from there.
|
||||
async fn handle_input(msg: &str) -> Result<Option<String>> {
|
||||
let cmd: InputCommand = serde_json::from_str(msg)
|
||||
.context("invalid input command")?;
|
||||
let cmd: InputCommand = serde_json::from_str(msg).context("invalid input command")?;
|
||||
|
||||
match cmd {
|
||||
InputCommand::Key { ref k } => {
|
||||
InputCommand::Key { ref k, .. } => {
|
||||
if !validate_key(k) {
|
||||
warn!("rejected key: {}", k);
|
||||
return Ok(Some(r#"{"t":"e","m":"invalid key"}"#.to_string()));
|
||||
}
|
||||
xdotool(&["key", "--clearmodifiers", k]).await?;
|
||||
}
|
||||
InputCommand::MouseMove { x, y } => {
|
||||
let x = x.clamp(-50, 50);
|
||||
let y = y.clamp(-50, 50);
|
||||
let xs = x.to_string();
|
||||
let ys = y.to_string();
|
||||
xdotool(&["mousemove_relative", "--", &xs, &ys]).await?;
|
||||
let _x = x.clamp(-50, 50);
|
||||
let _y = y.clamp(-50, 50);
|
||||
}
|
||||
InputCommand::Click { b } => {
|
||||
let b = b.clamp(1, 3);
|
||||
let bs = b.to_string();
|
||||
xdotool(&["click", &bs]).await?;
|
||||
let _b = b.clamp(1, 3);
|
||||
}
|
||||
InputCommand::Scroll { y } => {
|
||||
// xdotool: button 4 = scroll up, button 5 = scroll down
|
||||
let btn = if y < 0 { "4" } else { "5" };
|
||||
let count = y.unsigned_abs().clamp(1, 10).to_string();
|
||||
xdotool(&["click", "--repeat", &count, btn]).await?;
|
||||
let _y = y.clamp(-10, 10);
|
||||
}
|
||||
InputCommand::Ping => {
|
||||
return Ok(Some(r#"{"t":"p"}"#.to_string()));
|
||||
@@ -124,6 +212,15 @@ impl ApiHandler {
|
||||
req: Request<hyper::Body>,
|
||||
relay_tx: broadcast::Sender<String>,
|
||||
) -> Result<Response<hyper::Body>> {
|
||||
// Extract optional player ID from query string: /ws/remote-input?p=1
|
||||
let player_id: Option<u8> = req
|
||||
.uri()
|
||||
.query()
|
||||
.and_then(|q| q.split('&').find(|s| s.starts_with("p=")))
|
||||
.and_then(|s| s.get(2..))
|
||||
.and_then(|v| v.parse().ok())
|
||||
.filter(|&p: &u8| p == 1 || p == 2);
|
||||
|
||||
let (response, ws_fut_opt) = hyper_ws_listener::create_ws(req)
|
||||
.map_err(|e| anyhow::anyhow!("WebSocket upgrade failed: {}", e))?;
|
||||
|
||||
@@ -185,8 +282,28 @@ impl ApiHandler {
|
||||
continue; // silently drop
|
||||
}
|
||||
|
||||
// Relay to connected browsers (best-effort, ignore if no receivers)
|
||||
let _ = relay_tx.send(text.clone());
|
||||
// Relay to browser clients. If this connection has a
|
||||
// player ID from query string and the message is a key
|
||||
// event without a player field, inject it so the browser
|
||||
// can route input to the correct player.
|
||||
let relay_text = if let Some(pid) = player_id {
|
||||
if text.contains(r#""t":"k""#) && !text.contains(r#""p":"#) {
|
||||
// Insert "p":N before the closing brace
|
||||
if let Some(pos) = text.rfind('}') {
|
||||
let mut tagged = text[..pos].to_string();
|
||||
tagged.push_str(&format!(r#","p":{}"#, pid));
|
||||
tagged.push('}');
|
||||
tagged
|
||||
} else {
|
||||
text.clone()
|
||||
}
|
||||
} else {
|
||||
text.clone()
|
||||
}
|
||||
} else {
|
||||
text.clone()
|
||||
};
|
||||
let _ = relay_tx.send(relay_text);
|
||||
|
||||
match handle_input(&text).await {
|
||||
Ok(Some(reply)) => {
|
||||
@@ -219,11 +336,13 @@ impl ApiHandler {
|
||||
}
|
||||
}
|
||||
|
||||
info!("Remote input disconnected ({} messages processed)", msg_count);
|
||||
info!(
|
||||
"Remote input disconnected ({} messages processed)",
|
||||
msg_count
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -75,7 +75,9 @@ impl RpcHandler {
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
|
||||
let app_count = data.package_data.len();
|
||||
let running_count = data.package_data.values()
|
||||
let running_count = data
|
||||
.package_data
|
||||
.values()
|
||||
.filter(|p| matches!(p.state, crate::data_model::PackageState::Running))
|
||||
.count();
|
||||
|
||||
@@ -88,7 +90,8 @@ impl RpcHandler {
|
||||
.args(["MemTotal", "/proc/meminfo"])
|
||||
.output()
|
||||
.await;
|
||||
let total_ram_mb = mem_output.ok()
|
||||
let total_ram_mb = mem_output
|
||||
.ok()
|
||||
.and_then(|o| {
|
||||
let s = String::from_utf8_lossy(&o.stdout);
|
||||
s.split_whitespace().nth(1)?.parse::<u64>().ok()
|
||||
@@ -139,46 +142,66 @@ impl RpcHandler {
|
||||
|
||||
// Anonymous node ID — SHA-256 hash of the DID (not the DID itself)
|
||||
let node_id = {
|
||||
use sha2::{Sha256, Digest};
|
||||
use sha2::{Digest, Sha256};
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(data.server_info.pubkey.as_bytes());
|
||||
hex::encode(hasher.finalize())[..16].to_string()
|
||||
};
|
||||
|
||||
// Container states
|
||||
let containers: Vec<serde_json::Value> = data.package_data.iter().map(|(id, pkg)| {
|
||||
serde_json::json!({
|
||||
"id": id,
|
||||
"state": format!("{:?}", pkg.state),
|
||||
"version": pkg.manifest.version,
|
||||
let containers: Vec<serde_json::Value> = data
|
||||
.package_data
|
||||
.iter()
|
||||
.map(|(id, pkg)| {
|
||||
serde_json::json!({
|
||||
"id": id,
|
||||
"state": format!("{:?}", pkg.state),
|
||||
"version": pkg.manifest.version,
|
||||
})
|
||||
})
|
||||
}).collect();
|
||||
.collect();
|
||||
|
||||
// System stats
|
||||
let cpu_cores = std::thread::available_parallelism()
|
||||
.map(|n| n.get()).unwrap_or(0);
|
||||
.map(|n| n.get())
|
||||
.unwrap_or(0);
|
||||
let mem_output = tokio::process::Command::new("grep")
|
||||
.args(["MemTotal", "/proc/meminfo"])
|
||||
.output().await;
|
||||
let total_ram_mb = mem_output.ok()
|
||||
.and_then(|o| String::from_utf8_lossy(&o.stdout).split_whitespace().nth(1)?.parse::<u64>().ok())
|
||||
.map(|kb| kb / 1024).unwrap_or(0);
|
||||
.output()
|
||||
.await;
|
||||
let total_ram_mb = mem_output
|
||||
.ok()
|
||||
.and_then(|o| {
|
||||
String::from_utf8_lossy(&o.stdout)
|
||||
.split_whitespace()
|
||||
.nth(1)?
|
||||
.parse::<u64>()
|
||||
.ok()
|
||||
})
|
||||
.map(|kb| kb / 1024)
|
||||
.unwrap_or(0);
|
||||
|
||||
// Uptime
|
||||
let uptime_secs = tokio::fs::read_to_string("/proc/uptime").await
|
||||
let uptime_secs = tokio::fs::read_to_string("/proc/uptime")
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|s| s.split_whitespace().next()?.parse::<f64>().ok())
|
||||
.map(|f| f as u64)
|
||||
.unwrap_or(0);
|
||||
|
||||
// Recent alerts from metrics store
|
||||
let recent_alerts: Vec<serde_json::Value> = self.metrics_store.get_fired_alerts(10).await
|
||||
let recent_alerts: Vec<serde_json::Value> = self
|
||||
.metrics_store
|
||||
.get_fired_alerts(10)
|
||||
.await
|
||||
.into_iter()
|
||||
.map(|a| serde_json::json!({
|
||||
"rule": format!("{:?}", a.kind),
|
||||
"message": a.message,
|
||||
"timestamp": a.timestamp,
|
||||
}))
|
||||
.map(|a| {
|
||||
serde_json::json!({
|
||||
"rule": format!("{:?}", a.kind),
|
||||
"message": a.message,
|
||||
"timestamp": a.timestamp,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let report = serde_json::json!({
|
||||
@@ -208,11 +231,15 @@ impl RpcHandler {
|
||||
/// Receive a telemetry report from a fleet node.
|
||||
/// Stores it in telemetry-fleet/ directory, indexed by node_id.
|
||||
/// Does NOT require auth — called by remote nodes posting reports.
|
||||
pub(super) async fn handle_telemetry_ingest(&self, params: Option<serde_json::Value>) -> Result<serde_json::Value> {
|
||||
pub(super) async fn handle_telemetry_ingest(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let report = params.context("Missing telemetry report payload")?;
|
||||
|
||||
// Validate required fields
|
||||
let node_id = report.get("node_id")
|
||||
let node_id = report
|
||||
.get("node_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.context("Missing required field: node_id")?;
|
||||
if node_id.is_empty() || node_id.len() > 64 {
|
||||
@@ -222,39 +249,45 @@ impl RpcHandler {
|
||||
if node_id.contains('/') || node_id.contains('\\') || node_id.contains("..") {
|
||||
anyhow::bail!("Invalid node_id: contains disallowed characters");
|
||||
}
|
||||
let _version = report.get("version")
|
||||
let _version = report
|
||||
.get("version")
|
||||
.and_then(|v| v.as_str())
|
||||
.context("Missing required field: version")?;
|
||||
let _reported_at = report.get("reported_at")
|
||||
let _reported_at = report
|
||||
.get("reported_at")
|
||||
.and_then(|v| v.as_str())
|
||||
.context("Missing required field: reported_at")?;
|
||||
|
||||
let fleet_dir = self.config.data_dir.join("telemetry-fleet");
|
||||
tokio::fs::create_dir_all(&fleet_dir).await
|
||||
tokio::fs::create_dir_all(&fleet_dir)
|
||||
.await
|
||||
.context("Failed to create telemetry-fleet directory")?;
|
||||
|
||||
// Write latest report (overwrites previous)
|
||||
let latest_path = fleet_dir.join(format!("{}.json", node_id));
|
||||
let report_json = serde_json::to_string_pretty(&report)
|
||||
.context("Failed to serialize report")?;
|
||||
tokio::fs::write(&latest_path, &report_json).await
|
||||
let report_json =
|
||||
serde_json::to_string_pretty(&report).context("Failed to serialize report")?;
|
||||
tokio::fs::write(&latest_path, &report_json)
|
||||
.await
|
||||
.context("Failed to write latest fleet report")?;
|
||||
|
||||
// Append to history file (cap at 200 entries)
|
||||
let history_path = fleet_dir.join(format!("{}-history.json", node_id));
|
||||
let mut history: Vec<serde_json::Value> = match tokio::fs::read_to_string(&history_path).await {
|
||||
Ok(data) => serde_json::from_str(&data).unwrap_or_default(),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
let mut history: Vec<serde_json::Value> =
|
||||
match tokio::fs::read_to_string(&history_path).await {
|
||||
Ok(data) => serde_json::from_str(&data).unwrap_or_default(),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
history.push(report.clone());
|
||||
// Keep only the last 200 entries
|
||||
if history.len() > 200 {
|
||||
let start = history.len() - 200;
|
||||
history = history.split_off(start);
|
||||
}
|
||||
let history_json = serde_json::to_string_pretty(&history)
|
||||
.context("Failed to serialize history")?;
|
||||
tokio::fs::write(&history_path, &history_json).await
|
||||
let history_json =
|
||||
serde_json::to_string_pretty(&history).context("Failed to serialize history")?;
|
||||
tokio::fs::write(&history_path, &history_json)
|
||||
.await
|
||||
.context("Failed to write fleet history")?;
|
||||
|
||||
debug!(node_id = %node_id, "Ingested fleet telemetry report");
|
||||
@@ -274,7 +307,8 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
let mut nodes: Vec<serde_json::Value> = Vec::new();
|
||||
let mut entries = tokio::fs::read_dir(&fleet_dir).await
|
||||
let mut entries = tokio::fs::read_dir(&fleet_dir)
|
||||
.await
|
||||
.context("Failed to read telemetry-fleet directory")?;
|
||||
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
@@ -290,7 +324,8 @@ impl RpcHandler {
|
||||
match serde_json::from_str::<serde_json::Value>(&data) {
|
||||
Ok(mut report) => {
|
||||
// Compute online/offline status from reported_at
|
||||
let is_online = report.get("reported_at")
|
||||
let is_online = report
|
||||
.get("reported_at")
|
||||
.and_then(|v| v.as_str())
|
||||
.and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
|
||||
.map(|dt| {
|
||||
@@ -300,7 +335,8 @@ impl RpcHandler {
|
||||
.unwrap_or(false);
|
||||
|
||||
// Compute human-readable last_seen
|
||||
let last_seen = report.get("reported_at")
|
||||
let last_seen = report
|
||||
.get("reported_at")
|
||||
.and_then(|v| v.as_str())
|
||||
.and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
|
||||
.map(|dt| {
|
||||
@@ -349,20 +385,29 @@ impl RpcHandler {
|
||||
|
||||
/// Get history for a specific fleet node.
|
||||
/// Reads telemetry-fleet/{node_id}-history.json.
|
||||
pub(super) async fn handle_telemetry_fleet_node_history(&self, params: Option<serde_json::Value>) -> Result<serde_json::Value> {
|
||||
pub(super) async fn handle_telemetry_fleet_node_history(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let p = params.context("Missing params")?;
|
||||
let node_id = p.get("node_id")
|
||||
let node_id = p
|
||||
.get("node_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.context("Missing required field: node_id")?;
|
||||
|
||||
// Sanitize node_id
|
||||
if node_id.is_empty() || node_id.len() > 64
|
||||
|| node_id.contains('/') || node_id.contains('\\') || node_id.contains("..")
|
||||
if node_id.is_empty()
|
||||
|| node_id.len() > 64
|
||||
|| node_id.contains('/')
|
||||
|| node_id.contains('\\')
|
||||
|| node_id.contains("..")
|
||||
{
|
||||
anyhow::bail!("Invalid node_id");
|
||||
}
|
||||
|
||||
let history_path = self.config.data_dir
|
||||
let history_path = self
|
||||
.config
|
||||
.data_dir
|
||||
.join("telemetry-fleet")
|
||||
.join(format!("{}-history.json", node_id));
|
||||
|
||||
@@ -387,7 +432,8 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
let mut all_alerts: Vec<serde_json::Value> = Vec::new();
|
||||
let mut entries = tokio::fs::read_dir(&fleet_dir).await
|
||||
let mut entries = tokio::fs::read_dir(&fleet_dir)
|
||||
.await
|
||||
.context("Failed to read telemetry-fleet directory")?;
|
||||
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
@@ -407,7 +453,8 @@ impl RpcHandler {
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
let node_id = report.get("node_id")
|
||||
let node_id = report
|
||||
.get("node_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
|
||||
@@ -32,6 +32,26 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
tracing::info!("[onboarding] login successful");
|
||||
|
||||
// Ensure NostrVPN config exists — covers the case where onboardingComplete
|
||||
// was never called (e.g., user took the "already set up" shortcut).
|
||||
let data_dir = self.config.data_dir.clone();
|
||||
tokio::spawn(async move {
|
||||
// Quick check: if config.toml already exists, skip
|
||||
let config_path = data_dir.join("nostr-vpn/.config/nvpn/config.toml");
|
||||
if config_path.exists() {
|
||||
return;
|
||||
}
|
||||
// Identity must exist for VPN config
|
||||
if !data_dir.join("identity/nostr_pubkey").exists() {
|
||||
return;
|
||||
}
|
||||
match crate::vpn::configure_nostr_vpn(&data_dir).await {
|
||||
Ok(()) => tracing::info!("[login] NostrVPN auto-configured on first login"),
|
||||
Err(e) => tracing::debug!("[login] NostrVPN auto-config skipped: {}", e),
|
||||
}
|
||||
});
|
||||
|
||||
Ok(serde_json::Value::Null)
|
||||
}
|
||||
|
||||
@@ -84,7 +104,9 @@ impl RpcHandler {
|
||||
let is_setup = self.auth_manager.is_setup().await?;
|
||||
if is_setup {
|
||||
tracing::warn!("[onboarding] setup rejected — already set up");
|
||||
return Err(anyhow::anyhow!("Already set up. Use auth.changePassword to change."));
|
||||
return Err(anyhow::anyhow!(
|
||||
"Already set up. Use auth.changePassword to change."
|
||||
));
|
||||
}
|
||||
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
@@ -106,6 +128,16 @@ impl RpcHandler {
|
||||
pub(super) async fn handle_auth_onboarding_complete(&self) -> Result<serde_json::Value> {
|
||||
self.auth_manager.complete_onboarding().await?;
|
||||
tracing::info!("[onboarding] onboarding marked complete");
|
||||
|
||||
// Auto-configure NostrVPN with the node's Nostr identity
|
||||
let data_dir = self.config.data_dir.clone();
|
||||
tokio::spawn(async move {
|
||||
match crate::vpn::configure_nostr_vpn(&data_dir).await {
|
||||
Ok(()) => tracing::info!("[onboarding] NostrVPN configured and started"),
|
||||
Err(e) => tracing::warn!("[onboarding] NostrVPN setup (non-fatal): {}", e),
|
||||
}
|
||||
});
|
||||
|
||||
Ok(serde_json::json!(true))
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,11 @@ fn validate_s3_endpoint(endpoint: &str) -> Result<()> {
|
||||
// Strip port if present (handle IPv6 bracket notation)
|
||||
let host = if host_port.starts_with('[') {
|
||||
// IPv6: [::1]:443
|
||||
host_port.split(']').next().unwrap_or("").trim_start_matches('[')
|
||||
host_port
|
||||
.split(']')
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.trim_start_matches('[')
|
||||
} else {
|
||||
host_port.split(':').next().unwrap_or("")
|
||||
};
|
||||
@@ -40,12 +44,12 @@ fn validate_s3_endpoint(endpoint: &str) -> Result<()> {
|
||||
|| (v4.octets()[0] == 172 && (v4.octets()[1] & 0xf0) == 16) // 172.16.0.0/12
|
||||
|| (v4.octets()[0] == 192 && v4.octets()[1] == 168) // 192.168.0.0/16
|
||||
|| (v4.octets()[0] == 169 && v4.octets()[1] == 254) // 169.254.0.0/16
|
||||
|| v4.is_unspecified() // 0.0.0.0
|
||||
|| v4.is_unspecified() // 0.0.0.0
|
||||
}
|
||||
IpAddr::V6(v6) => {
|
||||
v6.is_loopback() // ::1
|
||||
|| (v6.segments()[0] & 0xfe00) == 0xfc00 // fc00::/7
|
||||
|| v6.is_unspecified() // ::
|
||||
|| v6.is_unspecified() // ::
|
||||
}
|
||||
};
|
||||
if is_private {
|
||||
@@ -109,7 +113,13 @@ impl RpcHandler {
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'passphrase' parameter"))?;
|
||||
|
||||
// Validate backup ID to prevent path traversal
|
||||
if id.is_empty() || id.len() > 128 || id.contains('/') || id.contains('\\') || id.contains("..") || id.contains('\0') {
|
||||
if id.is_empty()
|
||||
|| id.len() > 128
|
||||
|| id.contains('/')
|
||||
|| id.contains('\\')
|
||||
|| id.contains("..")
|
||||
|| id.contains('\0')
|
||||
{
|
||||
anyhow::bail!("Invalid backup ID");
|
||||
}
|
||||
|
||||
@@ -137,7 +147,13 @@ impl RpcHandler {
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'passphrase' parameter"))?;
|
||||
|
||||
// Validate backup ID to prevent path traversal
|
||||
if id.is_empty() || id.len() > 128 || id.contains('/') || id.contains('\\') || id.contains("..") || id.contains('\0') {
|
||||
if id.is_empty()
|
||||
|| id.len() > 128
|
||||
|| id.contains('/')
|
||||
|| id.contains('\\')
|
||||
|| id.contains("..")
|
||||
|| id.contains('\0')
|
||||
{
|
||||
anyhow::bail!("Invalid backup ID");
|
||||
}
|
||||
|
||||
@@ -156,7 +172,13 @@ impl RpcHandler {
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'id' parameter"))?;
|
||||
|
||||
// Validate backup ID to prevent path traversal
|
||||
if id.is_empty() || id.len() > 128 || id.contains('/') || id.contains('\\') || id.contains("..") || id.contains('\0') {
|
||||
if id.is_empty()
|
||||
|| id.len() > 128
|
||||
|| id.contains('/')
|
||||
|| id.contains('\\')
|
||||
|| id.contains("..")
|
||||
|| id.contains('\0')
|
||||
{
|
||||
anyhow::bail!("Invalid backup ID");
|
||||
}
|
||||
|
||||
@@ -242,7 +264,13 @@ impl RpcHandler {
|
||||
let _region = params["region"].as_str().unwrap_or("us-east-1");
|
||||
|
||||
// Validate backup ID
|
||||
if id.is_empty() || id.len() > 128 || id.contains('/') || id.contains('\\') || id.contains("..") || id.contains('\0') {
|
||||
if id.is_empty()
|
||||
|| id.len() > 128
|
||||
|| id.contains('/')
|
||||
|| id.contains('\\')
|
||||
|| id.contains("..")
|
||||
|| id.contains('\0')
|
||||
{
|
||||
anyhow::bail!("Invalid backup ID");
|
||||
}
|
||||
|
||||
@@ -281,7 +309,11 @@ impl RpcHandler {
|
||||
if !response.status().is_success() {
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
anyhow::bail!("S3 upload failed ({}): {}", status, &body[..200.min(body.len())]);
|
||||
anyhow::bail!(
|
||||
"S3 upload failed ({}): {}",
|
||||
status,
|
||||
&body[..200.min(body.len())]
|
||||
);
|
||||
}
|
||||
|
||||
info!(id = %id, bucket = %bucket, size = %size, "Backup uploaded to S3");
|
||||
@@ -317,7 +349,13 @@ impl RpcHandler {
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'secret_key' parameter"))?;
|
||||
|
||||
if id.is_empty() || id.len() > 128 || id.contains('/') || id.contains('\\') || id.contains("..") || id.contains('\0') {
|
||||
if id.is_empty()
|
||||
|| id.len() > 128
|
||||
|| id.contains('/')
|
||||
|| id.contains('\\')
|
||||
|| id.contains("..")
|
||||
|| id.contains('\0')
|
||||
{
|
||||
anyhow::bail!("Invalid backup ID");
|
||||
}
|
||||
|
||||
@@ -343,14 +381,19 @@ impl RpcHandler {
|
||||
anyhow::bail!("S3 download failed ({})", status);
|
||||
}
|
||||
|
||||
let bytes = response.bytes().await.context("Failed to read S3 response")?;
|
||||
let bytes = response
|
||||
.bytes()
|
||||
.await
|
||||
.context("Failed to read S3 response")?;
|
||||
let size = bytes.len();
|
||||
|
||||
// Save to backups directory
|
||||
let bak_dir = self.config.data_dir.join("backups");
|
||||
tokio::fs::create_dir_all(&bak_dir).await?;
|
||||
let bak_path = full::backup_file_path(&self.config.data_dir, id);
|
||||
tokio::fs::write(&bak_path, &bytes).await.context("Failed to write backup file")?;
|
||||
tokio::fs::write(&bak_path, &bytes)
|
||||
.await
|
||||
.context("Failed to write backup file")?;
|
||||
|
||||
info!(id = %id, bucket = %bucket, size = %size, "Backup downloaded from S3");
|
||||
|
||||
@@ -376,13 +419,10 @@ impl RpcHandler {
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'passphrase' parameter"))?;
|
||||
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let (did, pubkey) = crate::backup::restore_encrypted_backup(
|
||||
&identity_dir,
|
||||
backup,
|
||||
passphrase,
|
||||
)
|
||||
.await
|
||||
.context("Identity restore failed")?;
|
||||
let (did, pubkey) =
|
||||
crate::backup::restore_encrypted_backup(&identity_dir, backup, passphrase)
|
||||
.await
|
||||
.context("Identity restore failed")?;
|
||||
|
||||
info!(did = %did, "Identity restored from backup");
|
||||
|
||||
|
||||
@@ -3,6 +3,55 @@ use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use zeroize::Zeroize;
|
||||
|
||||
/// Retry configuration for [`bitcoin_rpc_post_with_retry`].
|
||||
///
|
||||
/// Exposed as a struct (rather than hard-coded constants inside the function)
|
||||
/// so tests can dial down timeouts to keep the suite fast while still
|
||||
/// exercising real retry/backoff behavior.
|
||||
#[derive(Debug, Clone)]
|
||||
struct RetryConfig {
|
||||
max_attempts: u32,
|
||||
attempt_timeout: std::time::Duration,
|
||||
/// Length must equal `max_attempts - 1` (one backoff between each
|
||||
/// successive attempt). The last attempt is not followed by a backoff.
|
||||
backoffs: Vec<std::time::Duration>,
|
||||
}
|
||||
|
||||
impl RetryConfig {
|
||||
/// Production retry policy: 3 attempts, 15s each, 500ms + 1500ms backoffs.
|
||||
/// Total worst-case wall time: 3 * 15 + 0.5 + 1.5 = 47s.
|
||||
fn production() -> Self {
|
||||
Self {
|
||||
max_attempts: BITCOIN_RPC_MAX_ATTEMPTS,
|
||||
attempt_timeout: BITCOIN_RPC_ATTEMPT_TIMEOUT,
|
||||
backoffs: BITCOIN_RPC_BACKOFFS.to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Max retry attempts for a single bitcoin_rpc_call invocation.
|
||||
/// First attempt + 2 retries = 3 total.
|
||||
const BITCOIN_RPC_MAX_ATTEMPTS: u32 = 3;
|
||||
|
||||
/// Per-attempt deadline. Must be >= the reqwest client's own timeout (we
|
||||
/// build it at 15s in handle_bitcoin_getinfo) — this is the outer safety net.
|
||||
const BITCOIN_RPC_ATTEMPT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
|
||||
|
||||
/// Backoff between attempts. Index 0 = after first failure, 1 = after second, etc.
|
||||
/// Chosen to absorb bitcoind's typical block-validation stall (2-5s) without
|
||||
/// adding noticeable latency on the happy path (first attempt succeeds in ~30ms).
|
||||
const BITCOIN_RPC_BACKOFFS: [std::time::Duration; 2] = [
|
||||
std::time::Duration::from_millis(500),
|
||||
std::time::Duration::from_millis(1500),
|
||||
];
|
||||
|
||||
/// Classify a reqwest error as transient (retryable) or fatal.
|
||||
/// Transient: timeout, connect refused, request/response body IO errors.
|
||||
/// Fatal: TLS errors, URL parse errors, redirect loops, builder errors.
|
||||
fn is_transient_transport_error(e: &reqwest::Error) -> bool {
|
||||
e.is_timeout() || e.is_connect() || e.is_request() || e.is_body()
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct BitcoinInfo {
|
||||
block_height: u64,
|
||||
@@ -37,8 +86,15 @@ struct MempoolInfo {
|
||||
|
||||
impl RpcHandler {
|
||||
pub(super) async fn handle_bitcoin_getinfo(&self) -> Result<serde_json::Value> {
|
||||
// Per-attempt timeout (see bitcoin_rpc_call for retry semantics).
|
||||
// 15s is enough room for bitcoind to answer getblockchaininfo even
|
||||
// during block validation; bitcoin_rpc_call wraps each attempt in a
|
||||
// separate tokio::time::timeout too, so this is belt-and-suspenders.
|
||||
// connect_timeout is tighter so a dead bitcoind doesn't steal the
|
||||
// whole attempt budget on TCP connect alone.
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(10))
|
||||
.timeout(std::time::Duration::from_secs(15))
|
||||
.connect_timeout(std::time::Duration::from_secs(3))
|
||||
.build()
|
||||
.context("Failed to create HTTP client")?;
|
||||
|
||||
@@ -57,21 +113,30 @@ impl RpcHandler {
|
||||
|
||||
let info = BitcoinInfo {
|
||||
block_height: blockchain_info.blocks.unwrap_or(0),
|
||||
sync_progress: blockchain_info
|
||||
.verification_progress
|
||||
.unwrap_or(0.0),
|
||||
sync_progress: blockchain_info.verification_progress.unwrap_or(0.0),
|
||||
chain: blockchain_info.chain.unwrap_or_else(|| "unknown".into()),
|
||||
difficulty: blockchain_info.difficulty.unwrap_or(0.0),
|
||||
mempool_size: mempool_info.bytes.unwrap_or(0),
|
||||
mempool_tx_count: mempool_info.size.unwrap_or(0),
|
||||
verification_progress: blockchain_info
|
||||
.verification_progress
|
||||
.unwrap_or(0.0),
|
||||
verification_progress: blockchain_info.verification_progress.unwrap_or(0.0),
|
||||
};
|
||||
|
||||
Ok(serde_json::to_value(info)?)
|
||||
}
|
||||
|
||||
/// Call a Bitcoin Core JSON-RPC method.
|
||||
///
|
||||
/// Retries up to [`BITCOIN_RPC_MAX_ATTEMPTS`] times on transient
|
||||
/// transport errors (timeout / connection refused / send/recv IO).
|
||||
/// Does **not** retry when bitcoind responds with a well-formed
|
||||
/// `{"error": ...}` body — those are real RPC errors and surfacing
|
||||
/// them quickly is the right behavior.
|
||||
///
|
||||
/// Motivation: on a syncing pruned node, bitcoind's RPC thread can block
|
||||
/// for 5-10 seconds during block validation. A single 10s timeout means
|
||||
/// ~30% of UI calls error out even though the node is perfectly healthy.
|
||||
/// With retry + backoff, the UI sees a uniform slow-but-successful
|
||||
/// response instead of intermittent failures.
|
||||
async fn bitcoin_rpc_call<T: serde::de::DeserializeOwned>(
|
||||
&self,
|
||||
client: &reqwest::Client,
|
||||
@@ -79,33 +144,15 @@ impl RpcHandler {
|
||||
params: &[serde_json::Value],
|
||||
) -> Result<T> {
|
||||
let (rpc_user, rpc_pass) = crate::bitcoin_rpc::bitcoin_rpc_credentials().await;
|
||||
let body = serde_json::json!({
|
||||
"jsonrpc": "1.0",
|
||||
"id": "archy",
|
||||
"method": method,
|
||||
"params": params,
|
||||
});
|
||||
|
||||
let resp = client
|
||||
.post(crate::constants::BITCOIN_RPC_URL)
|
||||
.basic_auth(&rpc_user, Some(&rpc_pass))
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.context("Bitcoin RPC connection failed")?;
|
||||
|
||||
let rpc_resp: BitcoinRpcResponse<T> = resp
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse Bitcoin RPC response")?;
|
||||
|
||||
if let Some(err) = rpc_resp.error {
|
||||
anyhow::bail!("Bitcoin RPC error: {}", err);
|
||||
}
|
||||
|
||||
rpc_resp
|
||||
.result
|
||||
.ok_or_else(|| anyhow::anyhow!("Bitcoin RPC returned null result"))
|
||||
bitcoin_rpc_post_with_retry(
|
||||
client,
|
||||
crate::constants::BITCOIN_RPC_URL,
|
||||
&rpc_user,
|
||||
&rpc_pass,
|
||||
method,
|
||||
params,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Initialize a Bitcoin Core descriptor wallet with keys derived from the master seed.
|
||||
@@ -116,19 +163,24 @@ impl RpcHandler {
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let password = params.get("password")
|
||||
let password = params
|
||||
.get("password")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'password' for seed access"))?;
|
||||
let wallet_name = params.get("wallet_name")
|
||||
let wallet_name = params
|
||||
.get("wallet_name")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("archipelago");
|
||||
|
||||
// Verify user password.
|
||||
self.auth_manager.verify_password(password).await
|
||||
self.auth_manager
|
||||
.verify_password(password)
|
||||
.await
|
||||
.context("Password verification failed")?;
|
||||
|
||||
// Load encrypted seed.
|
||||
let mnemonic = crate::seed::load_seed_encrypted(&self.config.data_dir, password).await
|
||||
let mnemonic = crate::seed::load_seed_encrypted(&self.config.data_dir, password)
|
||||
.await
|
||||
.context("Failed to load encrypted seed")?;
|
||||
let seed = crate::seed::MasterSeed::from_mnemonic(&mnemonic);
|
||||
|
||||
@@ -142,25 +194,30 @@ impl RpcHandler {
|
||||
.context("Failed to create HTTP client")?;
|
||||
|
||||
// Step 1: Create a blank descriptor wallet.
|
||||
let create_result = self.bitcoin_rpc_call::<serde_json::Value>(
|
||||
&client,
|
||||
"createwallet",
|
||||
&[
|
||||
serde_json::json!(wallet_name), // wallet_name
|
||||
serde_json::json!(false), // disable_private_keys
|
||||
serde_json::json!(true), // blank
|
||||
serde_json::json!(""), // passphrase
|
||||
serde_json::json!(false), // avoid_reuse
|
||||
serde_json::json!(true), // descriptors
|
||||
],
|
||||
).await;
|
||||
let create_result = self
|
||||
.bitcoin_rpc_call::<serde_json::Value>(
|
||||
&client,
|
||||
"createwallet",
|
||||
&[
|
||||
serde_json::json!(wallet_name), // wallet_name
|
||||
serde_json::json!(false), // disable_private_keys
|
||||
serde_json::json!(true), // blank
|
||||
serde_json::json!(""), // passphrase
|
||||
serde_json::json!(false), // avoid_reuse
|
||||
serde_json::json!(true), // descriptors
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
match create_result {
|
||||
Ok(_) => tracing::info!("Created blank descriptor wallet '{}'", wallet_name),
|
||||
Err(e) => {
|
||||
let msg = e.to_string();
|
||||
if msg.contains("already exists") {
|
||||
tracing::info!("Wallet '{}' already exists, importing descriptors", wallet_name);
|
||||
tracing::info!(
|
||||
"Wallet '{}' already exists, importing descriptors",
|
||||
wallet_name
|
||||
);
|
||||
} else {
|
||||
xprv_str.zeroize();
|
||||
return Err(e.context("Failed to create wallet"));
|
||||
@@ -174,18 +231,30 @@ impl RpcHandler {
|
||||
let internal_desc = format!("wpkh({}/1/*)", xprv_str);
|
||||
|
||||
// Get checksums from Bitcoin Core.
|
||||
let ext_info: serde_json::Value = self.bitcoin_rpc_call(
|
||||
&client, "getdescriptorinfo", &[serde_json::json!(external_desc)],
|
||||
).await.context("getdescriptorinfo failed for external descriptor")?;
|
||||
let ext_info: serde_json::Value = self
|
||||
.bitcoin_rpc_call(
|
||||
&client,
|
||||
"getdescriptorinfo",
|
||||
&[serde_json::json!(external_desc)],
|
||||
)
|
||||
.await
|
||||
.context("getdescriptorinfo failed for external descriptor")?;
|
||||
|
||||
let int_info: serde_json::Value = self.bitcoin_rpc_call(
|
||||
&client, "getdescriptorinfo", &[serde_json::json!(internal_desc)],
|
||||
).await.context("getdescriptorinfo failed for internal descriptor")?;
|
||||
let int_info: serde_json::Value = self
|
||||
.bitcoin_rpc_call(
|
||||
&client,
|
||||
"getdescriptorinfo",
|
||||
&[serde_json::json!(internal_desc)],
|
||||
)
|
||||
.await
|
||||
.context("getdescriptorinfo failed for internal descriptor")?;
|
||||
|
||||
let ext_desc_with_checksum = ext_info.get("descriptor")
|
||||
let ext_desc_with_checksum = ext_info
|
||||
.get("descriptor")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("No descriptor in getdescriptorinfo response"))?;
|
||||
let int_desc_with_checksum = int_info.get("descriptor")
|
||||
let int_desc_with_checksum = int_info
|
||||
.get("descriptor")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("No descriptor in getdescriptorinfo response"))?;
|
||||
|
||||
@@ -206,14 +275,18 @@ impl RpcHandler {
|
||||
}
|
||||
]);
|
||||
|
||||
let _import_result: serde_json::Value = self.bitcoin_rpc_call(
|
||||
&client, "importdescriptors", &[import_params],
|
||||
).await.context("importdescriptors failed")?;
|
||||
let _import_result: serde_json::Value = self
|
||||
.bitcoin_rpc_call(&client, "importdescriptors", &[import_params])
|
||||
.await
|
||||
.context("importdescriptors failed")?;
|
||||
|
||||
// Zeroize the xprv string from memory.
|
||||
xprv_str.zeroize();
|
||||
|
||||
tracing::info!("Bitcoin Core wallet '{}' initialized from master seed (BIP-84)", wallet_name);
|
||||
tracing::info!(
|
||||
"Bitcoin Core wallet '{}' initialized from master seed (BIP-84)",
|
||||
wallet_name
|
||||
);
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"initialized": true,
|
||||
@@ -221,3 +294,351 @@ impl RpcHandler {
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// Free-function counterpart to `RpcHandler::bitcoin_rpc_call`.
|
||||
///
|
||||
/// Takes the URL + credentials as parameters so it can be exercised by unit
|
||||
/// tests against a mock HTTP server without constructing a full `RpcHandler`.
|
||||
///
|
||||
/// Production callers go through `RpcHandler::bitcoin_rpc_call`, which loads
|
||||
/// credentials from the secrets file and points at `BITCOIN_RPC_URL`.
|
||||
async fn bitcoin_rpc_post_with_retry<T: serde::de::DeserializeOwned>(
|
||||
client: &reqwest::Client,
|
||||
url: &str,
|
||||
rpc_user: &str,
|
||||
rpc_pass: &str,
|
||||
method: &str,
|
||||
params: &[serde_json::Value],
|
||||
) -> Result<T> {
|
||||
bitcoin_rpc_post_with_retry_cfg(
|
||||
client,
|
||||
url,
|
||||
rpc_user,
|
||||
rpc_pass,
|
||||
method,
|
||||
params,
|
||||
&RetryConfig::production(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Inner implementation with configurable retry policy (for tests).
|
||||
async fn bitcoin_rpc_post_with_retry_cfg<T: serde::de::DeserializeOwned>(
|
||||
client: &reqwest::Client,
|
||||
url: &str,
|
||||
rpc_user: &str,
|
||||
rpc_pass: &str,
|
||||
method: &str,
|
||||
params: &[serde_json::Value],
|
||||
cfg: &RetryConfig,
|
||||
) -> Result<T> {
|
||||
debug_assert_eq!(
|
||||
cfg.backoffs.len(),
|
||||
(cfg.max_attempts - 1) as usize,
|
||||
"RetryConfig: backoffs.len() must equal max_attempts - 1"
|
||||
);
|
||||
|
||||
let body = serde_json::json!({
|
||||
"jsonrpc": "1.0",
|
||||
"id": "archy",
|
||||
"method": method,
|
||||
"params": params,
|
||||
});
|
||||
|
||||
let mut last_err: Option<anyhow::Error> = None;
|
||||
for attempt in 0..cfg.max_attempts {
|
||||
if attempt > 0 {
|
||||
let backoff = cfg
|
||||
.backoffs
|
||||
.get(attempt as usize - 1)
|
||||
.copied()
|
||||
.unwrap_or_else(|| std::time::Duration::from_secs(2));
|
||||
tracing::warn!(
|
||||
"bitcoin_rpc({}): attempt {} failed, backing off {:?}",
|
||||
method,
|
||||
attempt,
|
||||
backoff
|
||||
);
|
||||
tokio::time::sleep(backoff).await;
|
||||
}
|
||||
|
||||
// Per-attempt hard deadline. Independent of reqwest's built-in timeout
|
||||
// so we always cap total time even if reqwest blocks on something
|
||||
// weird (e.g., DNS starvation).
|
||||
let fut = client
|
||||
.post(url)
|
||||
.basic_auth(rpc_user, Some(rpc_pass))
|
||||
.json(&body)
|
||||
.send();
|
||||
|
||||
let send_result = match tokio::time::timeout(cfg.attempt_timeout, fut).await {
|
||||
Err(_elapsed) => {
|
||||
last_err = Some(anyhow::anyhow!(
|
||||
"Bitcoin RPC send timed out after {:?}",
|
||||
cfg.attempt_timeout
|
||||
));
|
||||
continue; // transient: retry
|
||||
}
|
||||
Ok(r) => r,
|
||||
};
|
||||
|
||||
let resp = match send_result {
|
||||
Ok(r) => r,
|
||||
Err(e) if is_transient_transport_error(&e) => {
|
||||
last_err = Some(anyhow::Error::from(e).context("Bitcoin RPC connection failed"));
|
||||
continue; // transient: retry
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(anyhow::Error::from(e).context("Bitcoin RPC connection failed"));
|
||||
}
|
||||
};
|
||||
|
||||
let rpc_resp: BitcoinRpcResponse<T> = resp
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse Bitcoin RPC response")?;
|
||||
|
||||
if let Some(err) = rpc_resp.error {
|
||||
// RPC-level error: this is a real bitcoind response, not transient.
|
||||
anyhow::bail!("Bitcoin RPC error: {}", err);
|
||||
}
|
||||
|
||||
return rpc_resp
|
||||
.result
|
||||
.ok_or_else(|| anyhow::anyhow!("Bitcoin RPC returned null result"));
|
||||
}
|
||||
|
||||
Err(last_err
|
||||
.unwrap_or_else(|| anyhow::anyhow!("Bitcoin RPC exhausted retries with no error captured")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Body, Request, Response, Server, StatusCode};
|
||||
use std::convert::Infallible;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Spin up a mock bitcoind HTTP server that behaves according to `handler`.
|
||||
/// Returns the bound URL and a JoinHandle (dropped = server shutdown via the
|
||||
/// oneshot cancel channel).
|
||||
async fn spawn_mock<F, Fut>(
|
||||
handler: F,
|
||||
) -> (
|
||||
String,
|
||||
tokio::task::JoinHandle<()>,
|
||||
tokio::sync::oneshot::Sender<()>,
|
||||
)
|
||||
where
|
||||
F: Fn(Request<Body>) -> Fut + Send + Sync + Clone + 'static,
|
||||
Fut: std::future::Future<Output = Response<Body>> + Send + 'static,
|
||||
{
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 0));
|
||||
let make_svc = make_service_fn(move |_| {
|
||||
let handler = handler.clone();
|
||||
async move {
|
||||
Ok::<_, Infallible>(service_fn(move |req| {
|
||||
let handler = handler.clone();
|
||||
async move { Ok::<_, Infallible>(handler(req).await) }
|
||||
}))
|
||||
}
|
||||
});
|
||||
let server = Server::bind(&addr).serve(make_svc);
|
||||
let url = format!("http://{}", server.local_addr());
|
||||
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
|
||||
let handle = tokio::spawn(async move {
|
||||
let graceful = server.with_graceful_shutdown(async {
|
||||
let _ = rx.await;
|
||||
});
|
||||
let _ = graceful.await;
|
||||
});
|
||||
(url, handle, tx)
|
||||
}
|
||||
|
||||
/// Reply body bitcoind would send for a successful getblockcount.
|
||||
fn ok_reply() -> Body {
|
||||
Body::from(r#"{"result":42,"error":null,"id":"archy"}"#)
|
||||
}
|
||||
|
||||
fn err_reply() -> Body {
|
||||
Body::from(r#"{"result":null,"error":{"code":-8,"message":"nope"},"id":"archy"}"#)
|
||||
}
|
||||
|
||||
/// Succeeds on first attempt — should not retry.
|
||||
#[tokio::test]
|
||||
async fn happy_path_first_attempt() {
|
||||
let count = Arc::new(AtomicU32::new(0));
|
||||
let c = count.clone();
|
||||
let (url, _h, _tx) = spawn_mock(move |_req| {
|
||||
let c = c.clone();
|
||||
async move {
|
||||
c.fetch_add(1, Ordering::SeqCst);
|
||||
Response::new(ok_reply())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
let client = reqwest::Client::builder().build().unwrap();
|
||||
let v: u64 =
|
||||
bitcoin_rpc_post_with_retry(&client, &url, "user", "pass", "getblockcount", &[])
|
||||
.await
|
||||
.expect("should succeed");
|
||||
assert_eq!(v, 42);
|
||||
assert_eq!(count.load(Ordering::SeqCst), 1, "should not have retried");
|
||||
}
|
||||
|
||||
/// HTTP 503 with non-JSON body: produces a JSON-parse error which is NOT
|
||||
/// classified as transient. Must fail after first attempt.
|
||||
/// This guards against the tempting mistake of blanket-retrying every
|
||||
/// non-2xx response — which would mask real bitcoind misconfig.
|
||||
#[tokio::test]
|
||||
async fn does_not_retry_parse_errors() {
|
||||
let count = Arc::new(AtomicU32::new(0));
|
||||
let c = count.clone();
|
||||
let (url, _h, _tx) = spawn_mock(move |_req| {
|
||||
let c = c.clone();
|
||||
async move {
|
||||
c.fetch_add(1, Ordering::SeqCst);
|
||||
Response::builder()
|
||||
.status(StatusCode::SERVICE_UNAVAILABLE)
|
||||
.body(Body::from("busy"))
|
||||
.unwrap()
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
let client = reqwest::Client::builder().build().unwrap();
|
||||
let result: Result<u64> =
|
||||
bitcoin_rpc_post_with_retry(&client, &url, "user", "pass", "getblockcount", &[]).await;
|
||||
assert!(result.is_err(), "non-JSON response should error out");
|
||||
assert_eq!(
|
||||
count.load(Ordering::SeqCst),
|
||||
1,
|
||||
"parse errors are not retryable"
|
||||
);
|
||||
}
|
||||
|
||||
/// Connect-refused (port closed) is the canonical transient transport
|
||||
/// error. Must exhaust BITCOIN_RPC_MAX_ATTEMPTS and the total elapsed
|
||||
/// time must include at least the sum of the backoffs.
|
||||
#[tokio::test]
|
||||
async fn retries_exhausted_on_persistent_connect_refused() {
|
||||
// Bind a port then immediately drop the listener so the port is closed.
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let closed_url = format!("http://{}", listener.local_addr().unwrap());
|
||||
drop(listener);
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.connect_timeout(std::time::Duration::from_millis(500))
|
||||
.build()
|
||||
.unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
let result: Result<u64> =
|
||||
bitcoin_rpc_post_with_retry(&client, &closed_url, "user", "pass", "getblockcount", &[])
|
||||
.await;
|
||||
let elapsed = start.elapsed();
|
||||
assert!(result.is_err(), "connect-refused should exhaust retries");
|
||||
let min_backoff: std::time::Duration = BITCOIN_RPC_BACKOFFS.iter().sum();
|
||||
assert!(
|
||||
elapsed >= min_backoff,
|
||||
"should have backed off between retries (elapsed={:?}, expected at least {:?})",
|
||||
elapsed,
|
||||
min_backoff
|
||||
);
|
||||
}
|
||||
|
||||
/// The motivating scenario: first attempt times out (bitcoind busy),
|
||||
/// subsequent attempt succeeds. Uses a short test-only RetryConfig so
|
||||
/// the test runs in <1s instead of 15s.
|
||||
#[tokio::test]
|
||||
async fn retries_on_timeout_then_succeeds() {
|
||||
let count = Arc::new(AtomicU32::new(0));
|
||||
let c = count.clone();
|
||||
// Mock server: first request hangs for 500ms, subsequent requests reply OK.
|
||||
let (url, _h, _tx) = spawn_mock(move |_req| {
|
||||
let c = c.clone();
|
||||
async move {
|
||||
let n = c.fetch_add(1, Ordering::SeqCst);
|
||||
if n == 0 {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
}
|
||||
Response::new(ok_reply())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
let client = reqwest::Client::builder().build().unwrap();
|
||||
// Attempt timeout 100ms < server's 500ms sleep => first attempt times out.
|
||||
// Backoff 20ms between attempts.
|
||||
let cfg = RetryConfig {
|
||||
max_attempts: 3,
|
||||
attempt_timeout: std::time::Duration::from_millis(100),
|
||||
backoffs: vec![
|
||||
std::time::Duration::from_millis(20),
|
||||
std::time::Duration::from_millis(20),
|
||||
],
|
||||
};
|
||||
let v: u64 = bitcoin_rpc_post_with_retry_cfg(
|
||||
&client,
|
||||
&url,
|
||||
"user",
|
||||
"pass",
|
||||
"getblockcount",
|
||||
&[],
|
||||
&cfg,
|
||||
)
|
||||
.await
|
||||
.expect("second attempt should succeed");
|
||||
assert_eq!(v, 42);
|
||||
assert!(
|
||||
count.load(Ordering::SeqCst) >= 2,
|
||||
"expected at least 2 attempts (got {})",
|
||||
count.load(Ordering::SeqCst)
|
||||
);
|
||||
}
|
||||
|
||||
/// bitcoind returned a well-formed `{"error": ...}` body. Must NOT retry.
|
||||
#[tokio::test]
|
||||
async fn does_not_retry_on_rpc_level_error() {
|
||||
let count = Arc::new(AtomicU32::new(0));
|
||||
let c = count.clone();
|
||||
let (url, _h, _tx) = spawn_mock(move |_req| {
|
||||
let c = c.clone();
|
||||
async move {
|
||||
c.fetch_add(1, Ordering::SeqCst);
|
||||
Response::new(err_reply())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
let client = reqwest::Client::builder().build().unwrap();
|
||||
let result: Result<u64> =
|
||||
bitcoin_rpc_post_with_retry(&client, &url, "user", "pass", "getblockcount", &[]).await;
|
||||
assert!(result.is_err());
|
||||
assert_eq!(
|
||||
count.load(Ordering::SeqCst),
|
||||
1,
|
||||
"RPC-level errors are not transient"
|
||||
);
|
||||
}
|
||||
|
||||
/// Sanity: retry budget invariants. Chosen to catch regressions where
|
||||
/// someone bumps these constants without realizing the total worst-case
|
||||
/// wall time implications.
|
||||
#[test]
|
||||
fn retry_budget_invariants() {
|
||||
assert_eq!(BITCOIN_RPC_MAX_ATTEMPTS, 3);
|
||||
assert_eq!(
|
||||
BITCOIN_RPC_BACKOFFS.len(),
|
||||
(BITCOIN_RPC_MAX_ATTEMPTS - 1) as usize
|
||||
);
|
||||
// Total wall-time ceiling:
|
||||
// 3 attempts * 15s + (0.5s + 1.5s) backoff = 47s
|
||||
let total: std::time::Duration = BITCOIN_RPC_ATTEMPT_TIMEOUT * BITCOIN_RPC_MAX_ATTEMPTS
|
||||
+ BITCOIN_RPC_BACKOFFS.iter().sum::<std::time::Duration>();
|
||||
assert!(total < std::time::Duration::from_secs(60));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::RpcHandler;
|
||||
use super::package::validate_app_id;
|
||||
use super::transitional::Op;
|
||||
use super::RpcHandler;
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
impl RpcHandler {
|
||||
@@ -7,10 +8,14 @@ impl RpcHandler {
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let orchestrator = self
|
||||
.orchestrator
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
|
||||
// The `container-install { manifest_path }` RPC is a dev-mode convenience
|
||||
// that points at an arbitrary YAML on disk. Production install happens via
|
||||
// the reconciler (BootReconciler, Step 5) and via the unified
|
||||
// ContainerOrchestrator::install(app_id) trait call, which can be exposed
|
||||
// through a separate `container-install-by-id` RPC when needed.
|
||||
let dev = self.dev_orchestrator.as_ref().ok_or_else(|| {
|
||||
anyhow::anyhow!("container-install with manifest_path is only available in dev mode")
|
||||
})?;
|
||||
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let manifest_path = params
|
||||
@@ -43,10 +48,10 @@ impl RpcHandler {
|
||||
let manifest_content = tokio::fs::read_to_string(&canonical)
|
||||
.await
|
||||
.context("Failed to read manifest file")?;
|
||||
let manifest: archipelago_container::AppManifest = serde_yaml::from_str(&manifest_content)
|
||||
.context("Failed to parse manifest")?;
|
||||
let manifest: archipelago_container::AppManifest =
|
||||
serde_yaml::from_str(&manifest_content).context("Failed to parse manifest")?;
|
||||
|
||||
let container_name = orchestrator
|
||||
let container_name = dev
|
||||
.install_container(&manifest, manifest_path)
|
||||
.await
|
||||
.context("Failed to install container")?;
|
||||
@@ -58,11 +63,6 @@ impl RpcHandler {
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let orchestrator = self
|
||||
.orchestrator
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
|
||||
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let app_id = params
|
||||
.get("app_id")
|
||||
@@ -70,23 +70,24 @@ impl RpcHandler {
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing app_id"))?;
|
||||
validate_app_id(app_id)?;
|
||||
|
||||
orchestrator
|
||||
.start_container(app_id)
|
||||
.await
|
||||
.context("Failed to start container")?;
|
||||
// User explicitly started the app — clear the user-stopped marker so
|
||||
// crash recovery / health monitor won't second-guess it. Must happen
|
||||
// BEFORE the spawn (see runtime.rs:145-148 for the symmetric stop
|
||||
// side and the ordering contract crash recovery depends on).
|
||||
crate::crash_recovery::clear_user_stopped(&self.config.data_dir, app_id).await;
|
||||
|
||||
Ok(serde_json::json!({ "status": "started" }))
|
||||
// spawn_transitional returns as soon as the background task is
|
||||
// launched (<1s). The UI sees Starting… immediately via WebSocket.
|
||||
self.spawn_transitional(Op::Start, app_id.to_string())
|
||||
.await?;
|
||||
|
||||
Ok(serde_json::json!({ "status": "starting" }))
|
||||
}
|
||||
|
||||
pub(super) async fn handle_container_stop(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let orchestrator = self
|
||||
.orchestrator
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
|
||||
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let app_id = params
|
||||
.get("app_id")
|
||||
@@ -94,12 +95,41 @@ impl RpcHandler {
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing app_id"))?;
|
||||
validate_app_id(app_id)?;
|
||||
|
||||
orchestrator
|
||||
.stop_container(app_id)
|
||||
.await
|
||||
.context("Failed to stop container")?;
|
||||
// Mark as user-stopped BEFORE the spawn — ordering is load-bearing
|
||||
// (crash recovery / health monitor inspect this flag concurrently
|
||||
// with the in-flight stop; see runtime.rs:145-148 for the package
|
||||
// path that also writes this in the same order).
|
||||
crate::crash_recovery::mark_user_stopped(&self.config.data_dir, app_id).await;
|
||||
|
||||
Ok(serde_json::json!({ "status": "stopped" }))
|
||||
// podman stop -t 600 (bitcoin-core) / -t 330 (lnd) runs in the
|
||||
// background; the RPC returns now with "stopping".
|
||||
self.spawn_transitional(Op::Stop, app_id.to_string())
|
||||
.await?;
|
||||
|
||||
Ok(serde_json::json!({ "status": "stopping" }))
|
||||
}
|
||||
|
||||
pub(super) async fn handle_container_restart(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let app_id = params
|
||||
.get("app_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing app_id"))?;
|
||||
validate_app_id(app_id)?;
|
||||
|
||||
// Restart does not mark user-stopped (the user wants the app to
|
||||
// keep running). Clear the marker as a defensive measure in case a
|
||||
// prior stop left it set and the restart is intended to revive the
|
||||
// normal running state.
|
||||
crate::crash_recovery::clear_user_stopped(&self.config.data_dir, app_id).await;
|
||||
|
||||
self.spawn_transitional(Op::Restart, app_id.to_string())
|
||||
.await?;
|
||||
|
||||
Ok(serde_json::json!({ "status": "restarting" }))
|
||||
}
|
||||
|
||||
pub(super) async fn handle_container_remove(
|
||||
@@ -109,7 +139,7 @@ impl RpcHandler {
|
||||
let orchestrator = self
|
||||
.orchestrator
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available"))?;
|
||||
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let app_id = params
|
||||
@@ -123,7 +153,7 @@ impl RpcHandler {
|
||||
.unwrap_or(false);
|
||||
|
||||
orchestrator
|
||||
.remove_container(app_id, preserve_data)
|
||||
.remove(app_id, preserve_data)
|
||||
.await
|
||||
.context("Failed to remove container")?;
|
||||
|
||||
@@ -137,33 +167,52 @@ impl RpcHandler {
|
||||
// between "installed" and "not-installed" in the UI.
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
if data.server_info.status_info.containers_scanned && !data.package_data.is_empty() {
|
||||
let containers: Vec<serde_json::Value> = data.package_data.iter().map(|(id, pkg)| {
|
||||
let state = match &pkg.state {
|
||||
crate::data_model::PackageState::Running => "running",
|
||||
crate::data_model::PackageState::Stopped => "stopped",
|
||||
crate::data_model::PackageState::Exited => "exited",
|
||||
crate::data_model::PackageState::Starting => "created",
|
||||
_ => "unknown",
|
||||
};
|
||||
let lan = pkg.installed.as_ref()
|
||||
.and_then(|i| i.interface_addresses.get("main"))
|
||||
.and_then(|a| a.lan_address.as_deref());
|
||||
serde_json::json!({
|
||||
"id": id,
|
||||
"name": id,
|
||||
"state": state,
|
||||
"image": "",
|
||||
"created": "",
|
||||
"ports": [],
|
||||
"lan_address": lan,
|
||||
let containers: Vec<serde_json::Value> = data
|
||||
.package_data
|
||||
.iter()
|
||||
.map(|(id, pkg)| {
|
||||
// Keep this mapping in sync with the UI's
|
||||
// ContainerStatus.state union in
|
||||
// neode-ui/src/api/container-client.ts. The UI maps
|
||||
// transitional variants to single-button labels
|
||||
// (Stopping… / Starting… / Restarting…).
|
||||
let state = match &pkg.state {
|
||||
crate::data_model::PackageState::Running => "running",
|
||||
crate::data_model::PackageState::Stopped => "stopped",
|
||||
crate::data_model::PackageState::Exited => "exited",
|
||||
crate::data_model::PackageState::Starting => "starting",
|
||||
crate::data_model::PackageState::Stopping => "stopping",
|
||||
crate::data_model::PackageState::Restarting => "restarting",
|
||||
crate::data_model::PackageState::Installing => "installing",
|
||||
crate::data_model::PackageState::Installed => "installed",
|
||||
crate::data_model::PackageState::Updating => "updating",
|
||||
crate::data_model::PackageState::Removing => "removing",
|
||||
crate::data_model::PackageState::CreatingBackup => "creating-backup",
|
||||
crate::data_model::PackageState::RestoringBackup => "restoring-backup",
|
||||
crate::data_model::PackageState::BackingUp => "backing-up",
|
||||
};
|
||||
let lan = pkg
|
||||
.installed
|
||||
.as_ref()
|
||||
.and_then(|i| i.interface_addresses.get("main"))
|
||||
.and_then(|a| a.lan_address.as_deref());
|
||||
serde_json::json!({
|
||||
"id": id,
|
||||
"name": id,
|
||||
"state": state,
|
||||
"image": "",
|
||||
"created": "",
|
||||
"ports": [],
|
||||
"lan_address": lan,
|
||||
})
|
||||
})
|
||||
}).collect();
|
||||
.collect();
|
||||
return Ok(serde_json::json!(containers));
|
||||
}
|
||||
|
||||
// Fallback: scanner hasn't run yet, query podman directly
|
||||
// Fallback: scanner hasn't run yet, query the orchestrator directly.
|
||||
if let Some(orchestrator) = &self.orchestrator {
|
||||
if let Ok(containers) = orchestrator.list_containers().await {
|
||||
if let Ok(containers) = orchestrator.list().await {
|
||||
if !containers.is_empty() {
|
||||
return Ok(serde_json::to_value(containers)?);
|
||||
}
|
||||
@@ -185,8 +234,8 @@ impl RpcHandler {
|
||||
return Ok(serde_json::json!([]));
|
||||
}
|
||||
|
||||
let podman_containers: Vec<serde_json::Value> = serde_json::from_str(&stdout)
|
||||
.unwrap_or_else(|_| Vec::new());
|
||||
let podman_containers: Vec<serde_json::Value> =
|
||||
serde_json::from_str(&stdout).unwrap_or_else(|_| Vec::new());
|
||||
|
||||
let containers: Vec<serde_json::Value> = podman_containers
|
||||
.iter()
|
||||
@@ -200,16 +249,25 @@ impl RpcHandler {
|
||||
"paused" => "paused",
|
||||
_ => "unknown",
|
||||
};
|
||||
let name = c.get("Names").and_then(|v| v.as_array()).and_then(|a| a.first()).and_then(|v| v.as_str()).unwrap_or("");
|
||||
let ports: Vec<String> = c.get("Ports")
|
||||
let name = c
|
||||
.get("Names")
|
||||
.and_then(|v| v.as_array())
|
||||
.and_then(|a| a.first())
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let ports: Vec<String> = c
|
||||
.get("Ports")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|a| {
|
||||
a.iter().filter_map(|p| {
|
||||
let host = p.get("host_port").and_then(|v| v.as_u64())?;
|
||||
let container = p.get("container_port").and_then(|v| v.as_u64())?;
|
||||
let proto = p.get("protocol").and_then(|v| v.as_str()).unwrap_or("tcp");
|
||||
Some(format!("0.0.0.0:{}->{}/{}", host, container, proto))
|
||||
}).collect()
|
||||
a.iter()
|
||||
.filter_map(|p| {
|
||||
let host = p.get("host_port").and_then(|v| v.as_u64())?;
|
||||
let container = p.get("container_port").and_then(|v| v.as_u64())?;
|
||||
let proto =
|
||||
p.get("protocol").and_then(|v| v.as_str()).unwrap_or("tcp");
|
||||
Some(format!("0.0.0.0:{}->{}/{}", host, container, proto))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
serde_json::json!({
|
||||
@@ -234,7 +292,7 @@ impl RpcHandler {
|
||||
let orchestrator = self
|
||||
.orchestrator
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available"))?;
|
||||
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let app_id = params
|
||||
@@ -243,12 +301,26 @@ impl RpcHandler {
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing app_id"))?;
|
||||
validate_app_id(app_id)?;
|
||||
|
||||
let status = orchestrator
|
||||
.get_container_status(app_id)
|
||||
.await
|
||||
.context("Failed to get container status")?;
|
||||
let mut last_err: Option<anyhow::Error> = None;
|
||||
for candidate in status_app_id_candidates(app_id) {
|
||||
match orchestrator.status(&candidate).await {
|
||||
Ok(status) => return Ok(serde_json::to_value(status)?),
|
||||
Err(e) => last_err = Some(e),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(serde_json::to_value(status)?)
|
||||
// Fallback for alias drift: query podman directly by likely container
|
||||
// names so status checks stay useful during migration.
|
||||
for name in status_container_name_candidates(app_id) {
|
||||
if let Some(v) = inspect_container_state_value(&name).await {
|
||||
return Ok(v);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(e) = last_err {
|
||||
return Err(e.context("Failed to get container status"));
|
||||
}
|
||||
Err(anyhow::anyhow!("Failed to get container status"))
|
||||
}
|
||||
|
||||
pub(super) async fn handle_container_logs(
|
||||
@@ -258,7 +330,7 @@ impl RpcHandler {
|
||||
let orchestrator = self
|
||||
.orchestrator
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available"))?;
|
||||
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let app_id = params
|
||||
@@ -266,13 +338,10 @@ impl RpcHandler {
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing app_id"))?;
|
||||
validate_app_id(app_id)?;
|
||||
let lines = params
|
||||
.get("lines")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(100) as u32;
|
||||
let lines = params.get("lines").and_then(|v| v.as_u64()).unwrap_or(100) as u32;
|
||||
|
||||
let logs = orchestrator
|
||||
.get_container_logs(app_id, lines)
|
||||
.logs(app_id, lines)
|
||||
.await
|
||||
.context("Failed to get container logs")?;
|
||||
|
||||
@@ -288,10 +357,10 @@ impl RpcHandler {
|
||||
let orchestrator = self
|
||||
.orchestrator
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available"))?;
|
||||
|
||||
let logs = orchestrator
|
||||
.get_container_logs(app_id, lines)
|
||||
.logs(app_id, lines)
|
||||
.await
|
||||
.context("Failed to get container logs")?;
|
||||
|
||||
@@ -305,37 +374,49 @@ impl RpcHandler {
|
||||
let orchestrator = self
|
||||
.orchestrator
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
|
||||
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available"))?;
|
||||
|
||||
// If app_id is provided, get health for that app
|
||||
// If app_id is provided, get health for that app.
|
||||
if let Some(params) = params {
|
||||
if let Some(app_id) = params.get("app_id").and_then(|v| v.as_str()) {
|
||||
let health = orchestrator
|
||||
.get_health_status(app_id)
|
||||
.health(app_id)
|
||||
.await
|
||||
.context("Failed to get container health")?;
|
||||
return Ok(serde_json::json!({ app_id: health }));
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, get health for all containers
|
||||
// Otherwise, get health for all containers.
|
||||
let containers = orchestrator
|
||||
.list_containers()
|
||||
.list()
|
||||
.await
|
||||
.context("Failed to list containers")?;
|
||||
|
||||
let mut health_map = serde_json::Map::new();
|
||||
for container in containers {
|
||||
if let Some(app_id) = container.name.strip_prefix("archipelago-") {
|
||||
if let Some(app_id) = app_id.strip_suffix("-dev") {
|
||||
match orchestrator.get_health_status(app_id).await {
|
||||
Ok(health) => {
|
||||
health_map.insert(app_id.to_string(), serde_json::Value::String(health));
|
||||
}
|
||||
Err(_) => {
|
||||
health_map.insert(app_id.to_string(), serde_json::Value::String("unknown".to_string()));
|
||||
}
|
||||
}
|
||||
// Map the runtime container name back to the app_id the orchestrator
|
||||
// knows about. Dev orchestrator uses `archipelago-<id>-dev`; Prod
|
||||
// uses bare `<id>` (or `archy-<id>` for UIs — health() accepts the
|
||||
// app_id either way since UI_APP_IDS is centralised).
|
||||
let app_id_candidate = container
|
||||
.name
|
||||
.strip_prefix("archipelago-")
|
||||
.and_then(|s| s.strip_suffix("-dev"))
|
||||
.or_else(|| container.name.strip_prefix("archy-"))
|
||||
.unwrap_or(container.name.as_str());
|
||||
match orchestrator.health(app_id_candidate).await {
|
||||
Ok(health) => {
|
||||
health_map.insert(
|
||||
app_id_candidate.to_string(),
|
||||
serde_json::Value::String(health),
|
||||
);
|
||||
}
|
||||
Err(_) => {
|
||||
health_map.insert(
|
||||
app_id_candidate.to_string(),
|
||||
serde_json::Value::String("unknown".to_string()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -343,3 +424,90 @@ impl RpcHandler {
|
||||
Ok(serde_json::Value::Object(health_map))
|
||||
}
|
||||
}
|
||||
|
||||
fn status_app_id_candidates(app_id: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut push = |s: &str| {
|
||||
if !out.iter().any(|e: &String| e == s) {
|
||||
out.push(s.to_string());
|
||||
}
|
||||
};
|
||||
|
||||
match app_id {
|
||||
"bitcoin-knots" => {
|
||||
push("bitcoin-knots");
|
||||
push("bitcoin-core");
|
||||
push("bitcoin");
|
||||
}
|
||||
"bitcoin-core" | "bitcoin" => {
|
||||
push("bitcoin-core");
|
||||
push("bitcoin-knots");
|
||||
push("bitcoin");
|
||||
}
|
||||
"electrs" | "mempool-electrs" => {
|
||||
push("electrs");
|
||||
push("mempool-electrs");
|
||||
push("electrumx");
|
||||
}
|
||||
_ => push(app_id),
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
fn status_container_name_candidates(app_id: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut push = |s: &str| {
|
||||
if !out.iter().any(|e: &String| e == s) {
|
||||
out.push(s.to_string());
|
||||
}
|
||||
};
|
||||
|
||||
match app_id {
|
||||
"bitcoin-knots" | "bitcoin-core" | "bitcoin" => push("bitcoin-knots"),
|
||||
"bitcoin-ui" => push("archy-bitcoin-ui"),
|
||||
"lnd-ui" => push("archy-lnd-ui"),
|
||||
"electrs-ui" => push("archy-electrs-ui"),
|
||||
"electrs" | "mempool-electrs" => push("electrumx"),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
push(app_id);
|
||||
if let Some(stripped) = app_id.strip_prefix("archy-") {
|
||||
push(stripped);
|
||||
} else {
|
||||
push(&format!("archy-{}", app_id));
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
async fn inspect_container_state_value(name: &str) -> Option<serde_json::Value> {
|
||||
let out = tokio::process::Command::new("podman")
|
||||
.args([
|
||||
"inspect",
|
||||
name,
|
||||
"--format",
|
||||
"{{.State.Status}} {{.State.Running}}",
|
||||
])
|
||||
.output()
|
||||
.await
|
||||
.ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let line = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
if line.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut parts = line.split_whitespace();
|
||||
let status = parts.next().unwrap_or("unknown");
|
||||
let running = parts.next().unwrap_or("false") == "true";
|
||||
Some(serde_json::json!({
|
||||
"name": name,
|
||||
"status": status,
|
||||
"state": status,
|
||||
"running": running,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::RpcHandler;
|
||||
use crate::content_server::{self, AccessControl, Availability, ContentItem};
|
||||
use crate::network::dwn_store::DwnStore;
|
||||
use crate::wallet::ecash;
|
||||
use anyhow::{Context, Result};
|
||||
use tracing::debug;
|
||||
|
||||
@@ -11,16 +12,16 @@ fn is_valid_v3_onion(addr: &str) -> bool {
|
||||
return false;
|
||||
}
|
||||
let prefix = &addr[..56];
|
||||
prefix.chars().all(|c| c.is_ascii_lowercase() || ('2'..='7').contains(&c))
|
||||
prefix
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_lowercase() || ('2'..='7').contains(&c))
|
||||
}
|
||||
|
||||
const FILE_CATALOG_PROTOCOL: &str = "https://archipelago.dev/protocols/file-catalog/v1";
|
||||
|
||||
impl RpcHandler {
|
||||
/// List content I'm sharing.
|
||||
pub(super) async fn handle_content_list_mine(
|
||||
&self,
|
||||
) -> Result<serde_json::Value> {
|
||||
pub(super) async fn handle_content_list_mine(&self) -> Result<serde_json::Value> {
|
||||
let catalog = content_server::load_catalog(&self.config.data_dir).await?;
|
||||
Ok(serde_json::json!({ "items": catalog.items }))
|
||||
}
|
||||
@@ -45,7 +46,10 @@ impl RpcHandler {
|
||||
anyhow::bail!("Invalid filename: absolute paths and hidden files not allowed");
|
||||
}
|
||||
// Reject any path segment starting with . (hidden dirs)
|
||||
if filename.split('/').any(|seg| seg.starts_with('.') || seg.is_empty()) {
|
||||
if filename
|
||||
.split('/')
|
||||
.any(|seg| seg.starts_with('.') || seg.is_empty())
|
||||
{
|
||||
anyhow::bail!("Invalid filename: hidden files/dirs or empty segments not allowed");
|
||||
}
|
||||
if filename.is_empty() || filename.len() > 512 {
|
||||
@@ -191,14 +195,21 @@ impl RpcHandler {
|
||||
.unwrap_or_default();
|
||||
Availability::Specific { peers }
|
||||
}
|
||||
_ => return Err(anyhow::anyhow!("Invalid availability: {}", availability_type)),
|
||||
_ => {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Invalid availability: {}",
|
||||
availability_type
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
content_server::set_availability(&self.config.data_dir, id, availability).await?;
|
||||
Ok(serde_json::json!({ "updated": true }))
|
||||
}
|
||||
|
||||
/// Download content from a peer over Tor, returning base64-encoded data.
|
||||
/// Download content from a peer. Prefers FIPS when the peer is known
|
||||
/// in our federation and has advertised a FIPS npub; falls back to
|
||||
/// Tor on any network failure.
|
||||
pub(super) async fn handle_content_download_peer(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
@@ -218,25 +229,19 @@ impl RpcHandler {
|
||||
return Err(anyhow::anyhow!("Invalid v3 onion address"));
|
||||
}
|
||||
|
||||
let socks_proxy = reqwest::Proxy::all(crate::constants::TOR_SOCKS_PROXY)
|
||||
.context("Failed to create SOCKS proxy")?;
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.proxy(socks_proxy)
|
||||
.timeout(std::time::Duration::from_secs(120))
|
||||
.build()
|
||||
.context("Failed to build Tor HTTP client")?;
|
||||
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
let local_did = crate::identity::did_key_from_pubkey_hex(&data.server_info.pubkey)?;
|
||||
let fips_npub = crate::federation::fips_npub_for_onion(&self.config.data_dir, onion).await;
|
||||
|
||||
let url = format!("http://{}/content/{}", onion, content_id);
|
||||
let response = client
|
||||
.get(&url)
|
||||
.header("X-Federation-DID", &local_did)
|
||||
.send()
|
||||
.await
|
||||
.context("Failed to connect to peer over Tor")?;
|
||||
let path = format!("/content/{}", content_id);
|
||||
let (response, _transport) =
|
||||
crate::fips::dial::PeerRequest::new(fips_npub.as_deref(), onion, &path)
|
||||
.service(crate::settings::transport::PeerService::PeerFiles)
|
||||
.header("X-Federation-DID", local_did)
|
||||
.timeout(std::time::Duration::from_secs(120))
|
||||
.send_get()
|
||||
.await
|
||||
.context("Failed to connect to peer")?;
|
||||
|
||||
if response.status() == reqwest::StatusCode::PAYMENT_REQUIRED {
|
||||
let body: serde_json::Value = response.json().await.unwrap_or_default();
|
||||
@@ -264,7 +269,8 @@ impl RpcHandler {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Browse a peer's content catalog over Tor.
|
||||
/// Browse a peer's content catalog. FIPS if the peer is federated,
|
||||
/// otherwise Tor.
|
||||
pub(super) async fn handle_content_browse_peer(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
@@ -280,24 +286,21 @@ impl RpcHandler {
|
||||
return Err(anyhow::anyhow!("Invalid v3 onion address"));
|
||||
}
|
||||
|
||||
// Connect via Tor SOCKS proxy to the peer's content catalog endpoint
|
||||
let socks_proxy = reqwest::Proxy::all(crate::constants::TOR_SOCKS_PROXY)
|
||||
.context("Failed to create SOCKS proxy")?;
|
||||
let fips_npub = crate::federation::fips_npub_for_onion(&self.config.data_dir, onion).await;
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.proxy(socks_proxy)
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.build()
|
||||
.context("Failed to build Tor HTTP client")?;
|
||||
debug!(
|
||||
"Browsing peer content at {} (fips={})",
|
||||
onion,
|
||||
fips_npub.is_some()
|
||||
);
|
||||
|
||||
let url = format!("http://{}/content", onion);
|
||||
debug!("Browsing peer content at {}", url);
|
||||
|
||||
let response = client
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.context("Failed to connect to peer over Tor")?;
|
||||
let (response, _transport) =
|
||||
crate::fips::dial::PeerRequest::new(fips_npub.as_deref(), onion, "/content")
|
||||
.service(crate::settings::transport::PeerService::PeerFiles)
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.send_get()
|
||||
.await
|
||||
.context("Failed to connect to peer")?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(anyhow::anyhow!(
|
||||
@@ -313,4 +316,150 @@ impl RpcHandler {
|
||||
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// Download paid content from a peer: mint ecash token, send with request.
|
||||
pub(super) async fn handle_content_download_peer_paid(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let onion = params
|
||||
.get("onion")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing onion address"))?;
|
||||
let content_id = params
|
||||
.get("content_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing content_id"))?;
|
||||
let price_sats = params
|
||||
.get("price_sats")
|
||||
.and_then(|v| v.as_u64())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing price_sats"))?;
|
||||
|
||||
if price_sats == 0 {
|
||||
return Err(anyhow::anyhow!("price_sats must be > 0"));
|
||||
}
|
||||
if !is_valid_v3_onion(onion) {
|
||||
return Err(anyhow::anyhow!("Invalid v3 onion address"));
|
||||
}
|
||||
|
||||
// Mint ecash payment token
|
||||
let token_str = ecash::send_token(&self.config.data_dir, price_sats)
|
||||
.await
|
||||
.context("Failed to create ecash payment token — check wallet balance")?;
|
||||
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
let local_did = crate::identity::did_key_from_pubkey_hex(&data.server_info.pubkey)?;
|
||||
let fips_npub = crate::federation::fips_npub_for_onion(&self.config.data_dir, onion).await;
|
||||
|
||||
let path = format!("/content/{}", content_id);
|
||||
let (response, _transport) =
|
||||
crate::fips::dial::PeerRequest::new(fips_npub.as_deref(), onion, &path)
|
||||
.service(crate::settings::transport::PeerService::PeerFiles)
|
||||
.header("X-Federation-DID", local_did)
|
||||
.header("X-Payment-Token", token_str)
|
||||
.timeout(std::time::Duration::from_secs(120))
|
||||
.send_get()
|
||||
.await
|
||||
.context("Failed to connect to peer")?;
|
||||
|
||||
if response.status() == reqwest::StatusCode::PAYMENT_REQUIRED {
|
||||
// Payment was rejected — token is spent but content not received
|
||||
return Err(anyhow::anyhow!(
|
||||
"Payment rejected by peer — token may have been insufficient or invalid"
|
||||
));
|
||||
}
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(anyhow::anyhow!("Peer returned: {}", response.status()));
|
||||
}
|
||||
|
||||
let bytes = response
|
||||
.bytes()
|
||||
.await
|
||||
.context("Failed to read response body")?;
|
||||
|
||||
use base64::Engine;
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"data": encoded,
|
||||
"size": bytes.len(),
|
||||
"paid_sats": price_sats,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Fetch a preview of paid content from a peer (no payment required).
|
||||
pub(super) async fn handle_content_preview_peer(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let onion = params
|
||||
.get("onion")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing onion address"))?;
|
||||
let content_id = params
|
||||
.get("content_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing content_id"))?;
|
||||
|
||||
if !is_valid_v3_onion(onion) {
|
||||
return Err(anyhow::anyhow!("Invalid v3 onion address"));
|
||||
}
|
||||
|
||||
let fips_npub = crate::federation::fips_npub_for_onion(&self.config.data_dir, onion).await;
|
||||
|
||||
let path = format!("/content/{}/preview", content_id);
|
||||
debug!(
|
||||
"Fetching content preview from {}{} (fips={})",
|
||||
onion,
|
||||
path,
|
||||
fips_npub.is_some()
|
||||
);
|
||||
|
||||
let (response, _transport) =
|
||||
crate::fips::dial::PeerRequest::new(fips_npub.as_deref(), onion, &path)
|
||||
.service(crate::settings::transport::PeerService::PeerFiles)
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.send_get()
|
||||
.await
|
||||
.context("Failed to connect to peer for preview")?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Peer returned error for preview: {}",
|
||||
response.status()
|
||||
));
|
||||
}
|
||||
|
||||
let is_preview = response
|
||||
.headers()
|
||||
.get("X-Content-Preview")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
let content_type = response
|
||||
.headers()
|
||||
.get("content-type")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("application/octet-stream")
|
||||
.to_string();
|
||||
|
||||
let bytes = response
|
||||
.bytes()
|
||||
.await
|
||||
.context("Failed to read preview response")?;
|
||||
|
||||
use base64::Engine;
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"data": encoded,
|
||||
"size": bytes.len(),
|
||||
"content_type": content_type,
|
||||
"preview_mode": is_preview,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +71,11 @@ impl RpcHandler {
|
||||
)
|
||||
.await?;
|
||||
|
||||
let status = if credentials::is_revoked(&vc) { "revoked" } else { "active" };
|
||||
let status = if credentials::is_revoked(&vc) {
|
||||
"revoked"
|
||||
} else {
|
||||
"active"
|
||||
};
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"id": vc.id,
|
||||
@@ -113,7 +117,11 @@ impl RpcHandler {
|
||||
})
|
||||
})?;
|
||||
|
||||
let status = if credentials::is_revoked(vc) { "revoked" } else { "active" };
|
||||
let status = if credentials::is_revoked(vc) {
|
||||
"revoked"
|
||||
} else {
|
||||
"active"
|
||||
};
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"id": vc.id,
|
||||
@@ -136,7 +144,11 @@ impl RpcHandler {
|
||||
let items: Vec<serde_json::Value> = creds
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let status = if credentials::is_revoked(&c) { "revoked" } else { "active" };
|
||||
let status = if credentials::is_revoked(&c) {
|
||||
"revoked"
|
||||
} else {
|
||||
"active"
|
||||
};
|
||||
serde_json::json!({
|
||||
"@context": c.context,
|
||||
"id": c.id,
|
||||
@@ -228,8 +240,7 @@ impl RpcHandler {
|
||||
.get("presentation")
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing presentation"))?;
|
||||
|
||||
let vp: credentials::VerifiablePresentation =
|
||||
serde_json::from_value(presentation.clone())?;
|
||||
let vp: credentials::VerifiablePresentation = serde_json::from_value(presentation.clone())?;
|
||||
|
||||
let data_dir = self.config.data_dir.clone();
|
||||
let result = credentials::verify_presentation(&vp, |did, bytes, signature| {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use super::RpcHandler;
|
||||
use anyhow::Result;
|
||||
use std::sync::Arc;
|
||||
|
||||
impl RpcHandler {
|
||||
/// Route an RPC method name to its handler, returning the result value.
|
||||
pub(super) async fn dispatch(
|
||||
&self,
|
||||
self: &Arc<Self>,
|
||||
method: &str,
|
||||
params: Option<serde_json::Value>,
|
||||
session_token: &Option<String>,
|
||||
@@ -15,7 +16,10 @@ impl RpcHandler {
|
||||
"health" => self.handle_health().await,
|
||||
"auth.login" => self.handle_auth_login(params).await,
|
||||
"auth.logout" => self.handle_auth_logout().await,
|
||||
"auth.changePassword" => self.handle_auth_change_password(params, session_token).await,
|
||||
"auth.changePassword" => {
|
||||
self.handle_auth_change_password(params, session_token)
|
||||
.await
|
||||
}
|
||||
"auth.isSetup" => self.handle_auth_is_setup().await,
|
||||
"auth.setup" => self.handle_auth_setup(params).await,
|
||||
"auth.onboardingComplete" => self.handle_auth_onboarding_complete().await,
|
||||
@@ -33,18 +37,23 @@ impl RpcHandler {
|
||||
"container-install" => self.handle_container_install(params).await,
|
||||
"container-start" => self.handle_container_start(params).await,
|
||||
"container-stop" => self.handle_container_stop(params).await,
|
||||
"container-restart" => self.handle_container_restart(params).await,
|
||||
"container-remove" => self.handle_container_remove(params).await,
|
||||
"container-list" => self.handle_container_list().await,
|
||||
"container-status" => self.handle_container_status(params).await,
|
||||
"container-logs" => self.handle_container_logs(params).await,
|
||||
"container-health" => self.handle_container_health(params).await,
|
||||
|
||||
// Package management (for docker-compose apps)
|
||||
"package.install" => self.handle_package_install(params).await,
|
||||
// Package management (for docker-compose apps).
|
||||
// install/uninstall/update return immediately with a
|
||||
// transitional status; the actual work runs in a background
|
||||
// tokio::spawn so the HTTP request doesn't block for minutes.
|
||||
"package.install" => self.clone().spawn_package_install(params).await,
|
||||
"package.start" => self.handle_package_start(params).await,
|
||||
"package.stop" => self.handle_package_stop(params).await,
|
||||
"package.restart" => self.handle_package_restart(params).await,
|
||||
"package.uninstall" => self.handle_package_uninstall(params).await,
|
||||
"package.uninstall" => self.clone().spawn_package_uninstall(params).await,
|
||||
"package.update" => self.clone().spawn_package_update(params).await,
|
||||
"app.filebrowser-token" => self.handle_filebrowser_token().await,
|
||||
|
||||
// Bundled app management (for pre-loaded container images)
|
||||
@@ -74,6 +83,8 @@ impl RpcHandler {
|
||||
"handshake.discover" => self.handle_handshake_discover().await,
|
||||
"handshake.connect" => self.handle_handshake_connect(params).await,
|
||||
"handshake.poll" => self.handle_handshake_poll().await,
|
||||
"nostr.discovery-status" => self.handle_nostr_discovery_status().await,
|
||||
"nostr.set-discovery" => self.handle_nostr_set_discovery(params).await,
|
||||
|
||||
// TOTP 2FA
|
||||
"auth.totp.setup.begin" => self.handle_totp_setup_begin(params).await,
|
||||
@@ -85,7 +96,9 @@ impl RpcHandler {
|
||||
|
||||
// Bitcoin & Lightning deep data
|
||||
"bitcoin.getinfo" => self.handle_bitcoin_getinfo().await,
|
||||
"bitcoin.init-wallet-from-seed" => self.handle_bitcoin_init_wallet_from_seed(params).await,
|
||||
"bitcoin.init-wallet-from-seed" => {
|
||||
self.handle_bitcoin_init_wallet_from_seed(params).await
|
||||
}
|
||||
"lnd.getinfo" => self.handle_lnd_getinfo().await,
|
||||
"lnd.listchannels" => self.handle_lnd_listchannels().await,
|
||||
"lnd.openchannel" => self.handle_lnd_openchannel(params).await,
|
||||
@@ -112,7 +125,9 @@ impl RpcHandler {
|
||||
"identity.verify" => self.handle_identity_verify(params).await,
|
||||
"identity.resolve-did" => self.handle_identity_resolve_did(params).await,
|
||||
"identity.resolve-remote-did" => self.handle_identity_resolve_remote_did(params).await,
|
||||
"identity.verify-did-document" => self.handle_identity_verify_did_document(params).await,
|
||||
"identity.verify-did-document" => {
|
||||
self.handle_identity_verify_did_document(params).await
|
||||
}
|
||||
"identity.create-dht-did" => self.handle_identity_create_dht_did(params).await,
|
||||
"identity.resolve-dht-did" => self.handle_identity_resolve_dht_did(params).await,
|
||||
"identity.refresh-dht-did" => self.handle_identity_refresh_dht_did(params).await,
|
||||
@@ -122,10 +137,18 @@ impl RpcHandler {
|
||||
"identity.export-keys" => self.handle_identity_export_keys(params).await,
|
||||
"identity.create-nostr-key" => self.handle_identity_create_nostr_key(params).await,
|
||||
"identity.nostr-sign" => self.handle_identity_nostr_sign(params).await,
|
||||
"identity.nostr-encrypt-nip04" => self.handle_identity_nostr_encrypt_nip04(params).await,
|
||||
"identity.nostr-decrypt-nip04" => self.handle_identity_nostr_decrypt_nip04(params).await,
|
||||
"identity.nostr-encrypt-nip44" => self.handle_identity_nostr_encrypt_nip44(params).await,
|
||||
"identity.nostr-decrypt-nip44" => self.handle_identity_nostr_decrypt_nip44(params).await,
|
||||
"identity.nostr-encrypt-nip04" => {
|
||||
self.handle_identity_nostr_encrypt_nip04(params).await
|
||||
}
|
||||
"identity.nostr-decrypt-nip04" => {
|
||||
self.handle_identity_nostr_decrypt_nip04(params).await
|
||||
}
|
||||
"identity.nostr-encrypt-nip44" => {
|
||||
self.handle_identity_nostr_encrypt_nip44(params).await
|
||||
}
|
||||
"identity.nostr-decrypt-nip44" => {
|
||||
self.handle_identity_nostr_decrypt_nip44(params).await
|
||||
}
|
||||
|
||||
// Bitcoin domain names (NIP-05)
|
||||
"identity.register-name" => self.handle_identity_register_name(params).await,
|
||||
@@ -139,8 +162,12 @@ impl RpcHandler {
|
||||
"identity.verify-credential" => self.handle_identity_verify_credential(params).await,
|
||||
"identity.list-credentials" => self.handle_identity_list_credentials(params).await,
|
||||
"identity.revoke-credential" => self.handle_identity_revoke_credential(params).await,
|
||||
"identity.create-presentation" => self.handle_identity_create_presentation(params).await,
|
||||
"identity.verify-presentation" => self.handle_identity_verify_presentation(params).await,
|
||||
"identity.create-presentation" => {
|
||||
self.handle_identity_create_presentation(params).await
|
||||
}
|
||||
"identity.verify-presentation" => {
|
||||
self.handle_identity_verify_presentation(params).await
|
||||
}
|
||||
|
||||
// Network overlay
|
||||
"network.get-visibility" => self.handle_network_get_visibility().await,
|
||||
@@ -186,12 +213,36 @@ impl RpcHandler {
|
||||
// Ecash wallet
|
||||
"wallet.ecash-balance" => self.handle_wallet_ecash_balance().await,
|
||||
"wallet.ecash-mint" => self.handle_wallet_ecash_mint(params).await,
|
||||
"wallet.ecash-mint-claim" => self.handle_wallet_ecash_mint_claim(params).await,
|
||||
"wallet.ecash-melt" => self.handle_wallet_ecash_melt(params).await,
|
||||
"wallet.ecash-melt-confirm" => self.handle_wallet_ecash_melt_confirm(params).await,
|
||||
"wallet.ecash-send" => self.handle_wallet_ecash_send(params).await,
|
||||
"wallet.ecash-receive" => self.handle_wallet_ecash_receive(params).await,
|
||||
"wallet.ecash-history" => self.handle_wallet_ecash_history().await,
|
||||
"wallet.networking-profits" => self.handle_wallet_networking_profits().await,
|
||||
|
||||
// Container registries
|
||||
"registry.list" => self.handle_registry_list().await,
|
||||
"registry.add" => self.handle_registry_add(params).await,
|
||||
"registry.remove" => self.handle_registry_remove(params).await,
|
||||
"registry.set-primary" => self.handle_registry_set_primary(params).await,
|
||||
"registry.test" => self.handle_registry_test(params).await,
|
||||
|
||||
// Streaming ecash payments
|
||||
"streaming.list-services" => self.handle_streaming_list_services().await,
|
||||
"streaming.configure-service" => self.handle_streaming_configure_service(params).await,
|
||||
"streaming.toggle-service" => self.handle_streaming_toggle_service(params).await,
|
||||
"streaming.pay" => self.handle_streaming_pay(params).await,
|
||||
"streaming.discover" => self.handle_streaming_discover().await,
|
||||
"streaming.usage" => self.handle_streaming_usage(params).await,
|
||||
"streaming.session" => self.handle_streaming_session(params).await,
|
||||
"streaming.list-sessions" => self.handle_streaming_list_sessions().await,
|
||||
"streaming.close-session" => self.handle_streaming_close_session(params).await,
|
||||
"streaming.advertise" => self.handle_streaming_advertise().await,
|
||||
"streaming.list-mints" => self.handle_streaming_list_mints().await,
|
||||
"streaming.configure-mints" => self.handle_streaming_configure_mints(params).await,
|
||||
"streaming.maintenance" => self.handle_streaming_maintenance().await,
|
||||
|
||||
// Content catalog management
|
||||
"content.list-mine" => self.handle_content_list_mine().await,
|
||||
"content.add" => self.handle_content_add(params).await,
|
||||
@@ -200,6 +251,8 @@ impl RpcHandler {
|
||||
"content.set-availability" => self.handle_content_set_availability(params).await,
|
||||
"content.browse-peer" => self.handle_content_browse_peer(params).await,
|
||||
"content.download-peer" => self.handle_content_download_peer(params).await,
|
||||
"content.download-peer-paid" => self.handle_content_download_peer_paid(params).await,
|
||||
"content.preview-peer" => self.handle_content_preview_peer(params).await,
|
||||
|
||||
// DWN (Decentralized Web Node)
|
||||
"dwn.status" => self.handle_dwn_status().await,
|
||||
@@ -232,14 +285,30 @@ impl RpcHandler {
|
||||
"federation.get-state" => self.handle_federation_get_state().await,
|
||||
"federation.peer-joined" => self.handle_federation_peer_joined(params).await,
|
||||
"federation.deploy-app" => self.handle_federation_deploy_app(params).await,
|
||||
"federation.peer-address-changed" => self.handle_federation_peer_address_changed(params).await,
|
||||
"federation.notify-did-change" => self.handle_federation_notify_did_change(params).await,
|
||||
"federation.peer-address-changed" => {
|
||||
self.handle_federation_peer_address_changed(params).await
|
||||
}
|
||||
"federation.notify-did-change" => {
|
||||
self.handle_federation_notify_did_change(params).await
|
||||
}
|
||||
"federation.peer-did-changed" => self.handle_federation_peer_did_changed(params).await,
|
||||
"federation.list-pending-requests" => {
|
||||
self.handle_federation_list_pending_requests().await
|
||||
}
|
||||
"federation.approve-request" => self.handle_federation_approve_request(params).await,
|
||||
"federation.reject-request" => self.handle_federation_reject_request(params).await,
|
||||
"federation.cancel-request" => self.handle_federation_cancel_request(params).await,
|
||||
|
||||
// VPN & Remote Access
|
||||
"vpn.status" => self.handle_vpn_status().await,
|
||||
"vpn.configure" => self.handle_vpn_configure(params).await,
|
||||
"vpn.disconnect" => self.handle_vpn_disconnect().await,
|
||||
"vpn.invite" => self.handle_vpn_invite(params).await,
|
||||
"vpn.add-participant" => self.handle_vpn_add_participant(params).await,
|
||||
"vpn.create-peer" => self.handle_vpn_create_peer(params).await,
|
||||
"vpn.list-peers" => self.handle_vpn_list_peers().await,
|
||||
"vpn.peer-config" => self.handle_vpn_peer_config(params).await,
|
||||
"vpn.remove-peer" => self.handle_vpn_remove_peer(params).await,
|
||||
"remote.setup" => self.handle_remote_setup(params).await,
|
||||
|
||||
// Marketplace
|
||||
@@ -255,12 +324,34 @@ impl RpcHandler {
|
||||
"mesh.status" => self.handle_mesh_status().await,
|
||||
"mesh.peers" => self.handle_mesh_peers().await,
|
||||
"mesh.messages" => self.handle_mesh_messages(params).await,
|
||||
"mesh.debug-dump" => self.handle_mesh_debug_dump().await,
|
||||
"mesh.send" => self.handle_mesh_send(params).await,
|
||||
"mesh.send-channel" => self.handle_mesh_send_channel(params).await,
|
||||
"mesh.broadcast" => self.handle_mesh_broadcast().await,
|
||||
"mesh.configure" => self.handle_mesh_configure(params).await,
|
||||
"mesh.send-invoice" => self.handle_mesh_send_invoice(params).await,
|
||||
"mesh.send-coordinate" => self.handle_mesh_send_coordinate(params).await,
|
||||
"mesh.send-alert" => self.handle_mesh_send_alert(params).await,
|
||||
"mesh.send-content" => self.handle_mesh_send_content(params).await,
|
||||
"mesh.send-content-inline" => self.handle_mesh_send_content_inline(params).await,
|
||||
"mesh.transport-advice" => self.handle_mesh_transport_advice(params).await,
|
||||
"mesh.fetch-content" => self.handle_mesh_fetch_content(params).await,
|
||||
"mesh.send-reply" => self.handle_mesh_send_reply(params).await,
|
||||
"mesh.send-reaction" => self.handle_mesh_send_reaction(params).await,
|
||||
"mesh.send-read-receipt" => self.handle_mesh_send_read_receipt(params).await,
|
||||
"mesh.forward-message" => self.handle_mesh_forward_message(params).await,
|
||||
"mesh.edit-message" => self.handle_mesh_edit_message(params).await,
|
||||
"mesh.delete-message" => self.handle_mesh_delete_message(params).await,
|
||||
"mesh.send-psbt" => self.handle_mesh_send_psbt(params).await,
|
||||
"mesh.broadcast-presence" => self.handle_mesh_broadcast_presence(params).await,
|
||||
"mesh.presence-list" => self.handle_mesh_presence_list(params).await,
|
||||
"mesh.contacts-list" => self.handle_mesh_contacts_list(params).await,
|
||||
"mesh.contacts-save" => self.handle_mesh_contacts_save(params).await,
|
||||
"mesh.contacts-block" => self.handle_mesh_contacts_block(params).await,
|
||||
"mesh.send-channel-invite" => self.handle_mesh_send_channel_invite(params).await,
|
||||
"conversations.list" => self.handle_conversations_list(params).await,
|
||||
"conversations.messages" => self.handle_conversations_messages(params).await,
|
||||
"mesh.clear-all" => self.handle_mesh_clear_all().await,
|
||||
"mesh.outbox" => self.handle_mesh_outbox(params).await,
|
||||
"mesh.session-status" => self.handle_mesh_session_status(params).await,
|
||||
"mesh.rotate-prekeys" => self.handle_mesh_rotate_prekeys().await,
|
||||
@@ -279,6 +370,8 @@ impl RpcHandler {
|
||||
"transport.peers" => self.handle_transport_peers().await,
|
||||
"transport.send" => self.handle_transport_send(params).await,
|
||||
"transport.set-mode" => self.handle_transport_set_mode(params).await,
|
||||
"transport.preferences" => self.handle_transport_preferences().await,
|
||||
"transport.set-preference" => self.handle_transport_set_preference(params).await,
|
||||
|
||||
// Server settings
|
||||
"server.set-name" => self.handle_server_set_name(params).await,
|
||||
@@ -292,6 +385,8 @@ impl RpcHandler {
|
||||
"system.disk-cleanup" => self.handle_system_disk_cleanup().await,
|
||||
"system.reboot" => self.handle_system_reboot(params).await,
|
||||
"system.factory-reset" => self.handle_system_factory_reset(params).await,
|
||||
"system.settings.get" => self.handle_system_settings_get(params).await,
|
||||
"system.settings.set" => self.handle_system_settings_set(params).await,
|
||||
|
||||
// Opt-in anonymous analytics
|
||||
"analytics.get-status" => self.handle_analytics_get_status().await,
|
||||
@@ -301,7 +396,9 @@ impl RpcHandler {
|
||||
"telemetry.report" => self.handle_telemetry_report().await,
|
||||
"telemetry.ingest" => self.handle_telemetry_ingest(params).await,
|
||||
"telemetry.fleet-status" => self.handle_telemetry_fleet_status().await,
|
||||
"telemetry.fleet-node-history" => self.handle_telemetry_fleet_node_history(params).await,
|
||||
"telemetry.fleet-node-history" => {
|
||||
self.handle_telemetry_fleet_node_history(params).await
|
||||
}
|
||||
"telemetry.fleet-alerts" => self.handle_telemetry_fleet_alerts().await,
|
||||
|
||||
// Real-time metrics monitoring
|
||||
@@ -311,14 +408,52 @@ impl RpcHandler {
|
||||
"monitoring.alerts" => self.handle_monitoring_alerts(params).await,
|
||||
"monitoring.alert-rules" => self.handle_monitoring_alert_rules().await,
|
||||
"monitoring.configure-alert" => self.handle_monitoring_configure_alert(params).await,
|
||||
"monitoring.acknowledge-alert" => self.handle_monitoring_acknowledge_alert(params).await,
|
||||
"monitoring.acknowledge-alert" => {
|
||||
self.handle_monitoring_acknowledge_alert(params).await
|
||||
}
|
||||
"monitoring.export" => self.handle_monitoring_export(params).await,
|
||||
|
||||
// FIPS mesh transport
|
||||
"fips.status" => self.handle_fips_status().await,
|
||||
"fips.check-update" => self.handle_fips_check_update().await,
|
||||
"fips.apply-update" => self.handle_fips_apply_update().await,
|
||||
"fips.install" => self.handle_fips_install().await,
|
||||
"fips.restart" => self.handle_fips_restart().await,
|
||||
"fips.reconnect" => self.handle_fips_reconnect().await,
|
||||
"fips.list-seed-anchors" => self.handle_fips_list_seed_anchors().await,
|
||||
"fips.add-seed-anchor" => {
|
||||
let p = params.unwrap_or(serde_json::json!({}));
|
||||
self.handle_fips_add_seed_anchor(&p).await
|
||||
}
|
||||
"fips.remove-seed-anchor" => {
|
||||
let p = params.unwrap_or(serde_json::json!({}));
|
||||
self.handle_fips_remove_seed_anchor(&p).await
|
||||
}
|
||||
"fips.apply-seed-anchors" => self.handle_fips_apply_seed_anchors().await,
|
||||
|
||||
// System updates
|
||||
"update.check" => self.handle_update_check().await,
|
||||
"update.status" => self.handle_update_status().await,
|
||||
"update.dismiss" => self.handle_update_dismiss().await,
|
||||
"update.download" => self.handle_update_download().await,
|
||||
"update.cancel-download" => self.handle_update_cancel_download().await,
|
||||
"update.list-mirrors" => self.handle_update_list_mirrors().await,
|
||||
"update.add-mirror" => {
|
||||
let p = params.unwrap_or(serde_json::json!({}));
|
||||
self.handle_update_add_mirror(&p).await
|
||||
}
|
||||
"update.remove-mirror" => {
|
||||
let p = params.unwrap_or(serde_json::json!({}));
|
||||
self.handle_update_remove_mirror(&p).await
|
||||
}
|
||||
"update.set-primary-mirror" => {
|
||||
let p = params.unwrap_or(serde_json::json!({}));
|
||||
self.handle_update_set_primary_mirror(&p).await
|
||||
}
|
||||
"update.test-mirror" => {
|
||||
let p = params.unwrap_or(serde_json::json!({}));
|
||||
self.handle_update_test_mirror(&p).await
|
||||
}
|
||||
"update.apply" => self.handle_update_apply().await,
|
||||
"update.git-apply" => self.handle_update_git_apply().await,
|
||||
"update.rollback" => self.handle_update_rollback().await,
|
||||
@@ -379,13 +514,14 @@ impl RpcHandler {
|
||||
"webhook.configure" => self.handle_webhook_configure(params).await,
|
||||
"webhook.test" => self.handle_webhook_test().await,
|
||||
|
||||
_ => {
|
||||
Err(anyhow::anyhow!("Unknown method: {}", method))
|
||||
}
|
||||
_ => Err(anyhow::anyhow!("Unknown method: {}", method)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn handle_echo(&self, params: Option<serde_json::Value>) -> Result<serde_json::Value> {
|
||||
pub(super) async fn handle_echo(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
if let Some(p) = params {
|
||||
if let Some(msg) = p.get("message").and_then(|v| v.as_str()) {
|
||||
return Ok(serde_json::json!({ "message": msg }));
|
||||
|
||||
@@ -8,10 +8,13 @@ impl RpcHandler {
|
||||
/// Get DWN status and sync state.
|
||||
pub(super) async fn handle_dwn_status(&self) -> Result<serde_json::Value> {
|
||||
let sync_state = dwn_sync::load_sync_state(&self.config.data_dir).await?;
|
||||
let server_status = dwn_sync::get_dwn_status().await.unwrap_or(dwn_sync::DwnStatusResponse {
|
||||
running: false,
|
||||
version: String::new(),
|
||||
});
|
||||
let server_status =
|
||||
dwn_sync::get_dwn_status()
|
||||
.await
|
||||
.unwrap_or(dwn_sync::DwnStatusResponse {
|
||||
running: false,
|
||||
version: String::new(),
|
||||
});
|
||||
|
||||
let store = DwnStore::new(&self.config.data_dir).await?;
|
||||
let stats = store.stats().await?;
|
||||
|
||||
@@ -1,33 +1,62 @@
|
||||
use super::*;
|
||||
use crate::api::rpc::RpcHandler;
|
||||
use crate::credentials;
|
||||
use crate::federation::{self, FederatedNode, TrustLevel};
|
||||
use crate::federation::{self, pending, FederatedNode, TrustLevel};
|
||||
use crate::identity;
|
||||
use crate::mesh;
|
||||
use crate::network::dwn_store::DwnStore;
|
||||
use anyhow::{Context, Result};
|
||||
use crate::nostr_handshake;
|
||||
use anyhow::Result;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
const FEDERATION_PROTOCOL: &str = "https://archipelago.dev/protocols/federation/v1";
|
||||
|
||||
impl RpcHandler {
|
||||
/// Register a federation node with the running mesh service so it's
|
||||
/// immediately addressable as a chat target. The mesh service seeds
|
||||
/// federation peers at startup, but federation nodes added or rotated
|
||||
/// later in the session would otherwise stay invisible to the mesh
|
||||
/// chat UI until the next mesh restart, and `mesh.send` against the
|
||||
/// frontend's synthesised contact_id would fail with "Unknown
|
||||
/// federation peer". Best-effort: silently no-ops when mesh is off.
|
||||
async fn register_federation_peer_in_mesh(
|
||||
&self,
|
||||
pubkey_hex: &str,
|
||||
did: &str,
|
||||
name: Option<&str>,
|
||||
) {
|
||||
let svc = self.mesh_service.read().await;
|
||||
if let Some(svc) = svc.as_ref() {
|
||||
mesh::upsert_federation_peer(&svc.shared_state(), pubkey_hex, did, name).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RpcHandler {
|
||||
/// federation.invite — Generate an invite code containing our DID + onion for a peer.
|
||||
pub(in crate::api::rpc) async fn handle_federation_invite(&self) -> Result<serde_json::Value> {
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
let did = identity::did_key_from_pubkey_hex(&data.server_info.pubkey)?;
|
||||
let onion = data
|
||||
.server_info
|
||||
.tor_address
|
||||
.clone()
|
||||
.unwrap_or_default();
|
||||
let onion = data.server_info.tor_address.clone().unwrap_or_default();
|
||||
let pubkey = data.server_info.pubkey.clone();
|
||||
|
||||
if onion.is_empty() {
|
||||
anyhow::bail!("Tor address not available. Tor may not be running.");
|
||||
}
|
||||
|
||||
let code = federation::create_invite(&self.config.data_dir, &did, &onion, &pubkey).await?;
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let fips_npub = identity::fips_npub(&identity_dir).await.unwrap_or(None);
|
||||
|
||||
info!(did = %did, "Generated federation invite");
|
||||
let code = federation::create_invite(
|
||||
&self.config.data_dir,
|
||||
&did,
|
||||
&onion,
|
||||
&pubkey,
|
||||
fips_npub.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
info!(did = %did, fips_advertised = fips_npub.is_some(), "Generated federation invite");
|
||||
Ok(serde_json::json!({
|
||||
"code": code,
|
||||
"did": did,
|
||||
@@ -50,21 +79,31 @@ impl RpcHandler {
|
||||
let local_did = identity::did_key_from_pubkey_hex(&data.server_info.pubkey)?;
|
||||
let local_onion = data.server_info.tor_address.clone().unwrap_or_default();
|
||||
let local_pubkey = data.server_info.pubkey.clone();
|
||||
let local_name = data.server_info.name.clone();
|
||||
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let node_identity = identity::NodeIdentity::load_or_create(&identity_dir).await?;
|
||||
let local_fips_npub = identity::fips_npub(&identity_dir).await.unwrap_or(None);
|
||||
let node = federation::accept_invite(
|
||||
&self.config.data_dir,
|
||||
code,
|
||||
&local_did,
|
||||
&local_onion,
|
||||
&local_pubkey,
|
||||
local_fips_npub.as_deref(),
|
||||
local_name.as_deref(),
|
||||
|data| node_identity.sign(data),
|
||||
)
|
||||
.await?;
|
||||
|
||||
info!(peer_did = %node.did, "Joined federation with peer");
|
||||
|
||||
// Make the new peer immediately addressable from the mesh chat UI.
|
||||
// Without this, the row exists in the federation list but `mesh.send`
|
||||
// against it fails until the next mesh service restart re-seeds.
|
||||
self.register_federation_peer_in_mesh(&node.pubkey, &node.did, node.name.as_deref())
|
||||
.await;
|
||||
|
||||
// Store federation membership as DWN message
|
||||
if let Ok(store) = DwnStore::new(&self.config.data_dir).await {
|
||||
let dwn_data = serde_json::json!({
|
||||
@@ -110,7 +149,9 @@ impl RpcHandler {
|
||||
tokio::task::block_in_place(|| {
|
||||
let rt = tokio::runtime::Handle::current();
|
||||
rt.block_on(async {
|
||||
let id = crate::identity::NodeIdentity::load_or_create(&identity_dir).await?;
|
||||
let id =
|
||||
crate::identity::NodeIdentity::load_or_create(&identity_dir)
|
||||
.await?;
|
||||
Ok(id.sign(bytes))
|
||||
})
|
||||
})
|
||||
@@ -118,7 +159,9 @@ impl RpcHandler {
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(vc) => debug!(vc_id = %vc.id, peer = %peer_did, "Issued federation trust VC"),
|
||||
Ok(vc) => {
|
||||
debug!(vc_id = %vc.id, peer = %peer_did, "Issued federation trust VC")
|
||||
}
|
||||
Err(e) => debug!(error = %e, "Federation trust VC issuance failed (non-fatal)"),
|
||||
}
|
||||
});
|
||||
@@ -136,18 +179,24 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
/// federation.list-nodes — List all federated nodes with their status, last state, and VC verification.
|
||||
pub(in crate::api::rpc) async fn handle_federation_list_nodes(&self) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_federation_list_nodes(
|
||||
&self,
|
||||
) -> Result<serde_json::Value> {
|
||||
let nodes = federation::load_nodes(&self.config.data_dir).await?;
|
||||
|
||||
// Load credentials to check for federation VCs
|
||||
let cred_store = credentials::load_credentials(&self.config.data_dir).await.ok();
|
||||
let cred_store = credentials::load_credentials(&self.config.data_dir)
|
||||
.await
|
||||
.ok();
|
||||
let vc_subjects: std::collections::HashSet<String> = cred_store
|
||||
.as_ref()
|
||||
.map(|s| {
|
||||
s.credentials
|
||||
.iter()
|
||||
.filter(|vc| {
|
||||
vc.credential_type.iter().any(|t| t == "FederationTrustCredential")
|
||||
vc.credential_type
|
||||
.iter()
|
||||
.any(|t| t == "FederationTrustCredential")
|
||||
&& !credentials::is_revoked(vc)
|
||||
})
|
||||
.map(|vc| vc.credential_subject.id.clone())
|
||||
@@ -223,7 +272,10 @@ impl RpcHandler {
|
||||
"trusted" => TrustLevel::Trusted,
|
||||
"observer" => TrustLevel::Observer,
|
||||
"untrusted" => TrustLevel::Untrusted,
|
||||
_ => anyhow::bail!("Invalid trust level: {} (expected trusted/observer/untrusted)", trust_str),
|
||||
_ => anyhow::bail!(
|
||||
"Invalid trust level: {} (expected trusted/observer/untrusted)",
|
||||
trust_str
|
||||
),
|
||||
};
|
||||
|
||||
federation::set_trust_level(&self.config.data_dir, did, trust).await?;
|
||||
@@ -236,7 +288,9 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
/// federation.sync-state — Manually trigger state sync with all federated peers.
|
||||
pub(in crate::api::rpc) async fn handle_federation_sync_state(&self) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_federation_sync_state(
|
||||
&self,
|
||||
) -> Result<serde_json::Value> {
|
||||
let nodes = federation::load_nodes(&self.config.data_dir).await?;
|
||||
|
||||
if nodes.is_empty() {
|
||||
@@ -263,12 +317,9 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
let did_clone = local_did.clone();
|
||||
match federation::sync_with_peer(
|
||||
&self.config.data_dir,
|
||||
node,
|
||||
&did_clone,
|
||||
|bytes| node_identity.sign(bytes),
|
||||
)
|
||||
match federation::sync_with_peer(&self.config.data_dir, node, &did_clone, |bytes| {
|
||||
node_identity.sign(bytes)
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(state) => {
|
||||
@@ -298,7 +349,9 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
/// federation.get-state — Return this node's state snapshot (called by peers during sync).
|
||||
pub(in crate::api::rpc) async fn handle_federation_get_state(&self) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_federation_get_state(
|
||||
&self,
|
||||
) -> Result<serde_json::Value> {
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
|
||||
// Build app statuses from package_data
|
||||
@@ -315,8 +368,60 @@ impl RpcHandler {
|
||||
let tor_active = data.server_info.tor_address.is_some();
|
||||
|
||||
let server_name = data.server_info.name.clone().filter(|n| !n.is_empty());
|
||||
|
||||
// Encode our local Nostr identity as bech32 npub so federated peers
|
||||
// can display it under our name in the mesh UI without each peer
|
||||
// having to know how to convert hex → bech32 themselves.
|
||||
let nostr_npub =
|
||||
tokio::fs::read_to_string(self.config.data_dir.join("identity/nostr_pubkey"))
|
||||
.await
|
||||
.ok()
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.and_then(|hex| nostr_sdk::PublicKey::from_hex(&hex).ok())
|
||||
.and_then(|pk| nostr_sdk::ToBech32::to_bech32(&pk).ok());
|
||||
|
||||
// Pass the current federated-peer list so the snapshot can include
|
||||
// a `federated_peers` hint for transitive federation — receivers
|
||||
// who trust us learn our Trusted peers and can route to them
|
||||
// over FIPS without a separate invite round-trip.
|
||||
let federated_peers = federation::load_nodes(&self.config.data_dir)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
// Our own FIPS npub, so pre-v1.4 federation pairs (whose
|
||||
// invite codes didn't carry it) can learn it on the next sync.
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let own_fips_npub = crate::identity::fips_npub(&identity_dir)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.or_else(|| {
|
||||
// Legacy/dev nodes without a seed-derived key fall back
|
||||
// to the upstream daemon's public key on disk.
|
||||
None
|
||||
});
|
||||
let own_fips_npub = match own_fips_npub {
|
||||
Some(n) => Some(n),
|
||||
None => crate::fips::service::read_upstream_npub()
|
||||
.await
|
||||
.ok()
|
||||
.flatten(),
|
||||
};
|
||||
|
||||
let state = federation::build_local_state(
|
||||
apps, 0.0, 0, 0, 0, 0, 0, tor_active, server_name,
|
||||
apps,
|
||||
0.0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
tor_active,
|
||||
server_name,
|
||||
nostr_npub,
|
||||
own_fips_npub,
|
||||
&federated_peers,
|
||||
);
|
||||
|
||||
Ok(serde_json::to_value(&state)?)
|
||||
@@ -341,11 +446,46 @@ impl RpcHandler {
|
||||
.get("pubkey")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'pubkey'"))?;
|
||||
// Optional, unsigned: peer's FIPS mesh npub. Carried for transport
|
||||
// selection only; FIPS handshake re-authenticates the session.
|
||||
let fips_npub = params
|
||||
.get("fips_npub")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
// Optional, unsigned: peer's display name. Display-only — identity
|
||||
// claims are anchored on the signed did/pubkey below.
|
||||
let incoming_name = params
|
||||
.get("name")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
// Reject self-peering. If somehow our own did / onion / pubkey
|
||||
// comes back at us (misconfigured invite, gossip loop), adding
|
||||
// the entry causes sync loops where the node syncs with itself
|
||||
// forever. Drop it quietly — no useful recovery path.
|
||||
let (own_data, _) = self.state_manager.get_snapshot().await;
|
||||
let own_did_result = identity::did_key_from_pubkey_hex(&own_data.server_info.pubkey).ok();
|
||||
let own_onion_trim = own_data
|
||||
.server_info
|
||||
.tor_address
|
||||
.as_deref()
|
||||
.unwrap_or("")
|
||||
.trim_end_matches(".onion")
|
||||
.to_string();
|
||||
let incoming_onion_trim = onion.trim_end_matches(".onion");
|
||||
if own_did_result.as_deref() == Some(did)
|
||||
|| pubkey == own_data.server_info.pubkey
|
||||
|| (!own_onion_trim.is_empty() && own_onion_trim == incoming_onion_trim)
|
||||
{
|
||||
tracing::warn!(
|
||||
peer_did = %did,
|
||||
"Rejected peer-joined: inbound identity matches this node"
|
||||
);
|
||||
anyhow::bail!("Refusing to peer with self");
|
||||
}
|
||||
|
||||
// Verify ed25519 signature to prevent federation spoofing (H2 security fix)
|
||||
let signature = params
|
||||
.get("signature")
|
||||
.and_then(|v| v.as_str());
|
||||
let signature = params.get("signature").and_then(|v| v.as_str());
|
||||
match signature {
|
||||
Some(sig) => {
|
||||
let sign_data = format!("peer-joined:{}:{}:{}", did, onion, pubkey);
|
||||
@@ -359,24 +499,36 @@ impl RpcHandler {
|
||||
}
|
||||
None => {
|
||||
tracing::warn!(peer_did = %did, "Rejected peer-joined: missing signature");
|
||||
anyhow::bail!("Missing signature — all federation peers must be cryptographically verified");
|
||||
anyhow::bail!(
|
||||
"Missing signature — all federation peers must be cryptographically verified"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let nodes = federation::load_nodes(&self.config.data_dir).await?;
|
||||
if let Some(existing) = nodes.iter().find(|n| n.did == did) {
|
||||
// If already known but missing onion/pubkey, update them
|
||||
if existing.onion.is_empty() || existing.pubkey.is_empty() {
|
||||
// If already known but missing onion/pubkey/fips_npub/name, update them
|
||||
let needs_onion = existing.onion.is_empty();
|
||||
let needs_pubkey = existing.pubkey.is_empty();
|
||||
let needs_fips = existing.fips_npub.is_none() && fips_npub.is_some();
|
||||
let needs_name = existing.name.is_none() && incoming_name.is_some();
|
||||
if needs_onion || needs_pubkey || needs_fips || needs_name {
|
||||
let mut updated = existing.clone();
|
||||
if existing.onion.is_empty() && !onion.is_empty() {
|
||||
if needs_onion && !onion.is_empty() {
|
||||
updated.onion = onion.to_string();
|
||||
}
|
||||
if existing.pubkey.is_empty() && !pubkey.is_empty() {
|
||||
if needs_pubkey && !pubkey.is_empty() {
|
||||
updated.pubkey = pubkey.to_string();
|
||||
}
|
||||
if needs_fips {
|
||||
updated.fips_npub = fips_npub.clone();
|
||||
}
|
||||
if needs_name {
|
||||
updated.name = incoming_name.clone();
|
||||
}
|
||||
updated.last_seen = Some(chrono::Utc::now().to_rfc3339());
|
||||
federation::update_node(&self.config.data_dir, &updated).await?;
|
||||
info!(peer_did = %did, peer_onion = %onion, "Updated existing peer with missing onion/pubkey");
|
||||
info!(peer_did = %did, peer_onion = %onion, "Updated existing peer with fresh identity fields");
|
||||
}
|
||||
return Ok(serde_json::json!({ "accepted": true, "already_known": true }));
|
||||
}
|
||||
@@ -385,16 +537,49 @@ impl RpcHandler {
|
||||
did: did.to_string(),
|
||||
pubkey: pubkey.to_string(),
|
||||
onion: onion.to_string(),
|
||||
name: None,
|
||||
name: incoming_name.clone(),
|
||||
trust_level: TrustLevel::Trusted,
|
||||
added_at: chrono::Utc::now().to_rfc3339(),
|
||||
last_seen: None,
|
||||
last_state: None,
|
||||
fips_npub,
|
||||
last_transport: None,
|
||||
last_transport_at: None,
|
||||
};
|
||||
|
||||
federation::add_node(&self.config.data_dir, node).await?;
|
||||
info!(peer_did = %did, "Peer joined our federation");
|
||||
|
||||
// Mirror into mesh state so the inbound peer is addressable from
|
||||
// the chat UI without waiting for the next mesh restart.
|
||||
self.register_federation_peer_in_mesh(pubkey, did, incoming_name.as_deref())
|
||||
.await;
|
||||
|
||||
// Bump the data-model revision so any Federation view with an
|
||||
// open WebSocket reloads its node list without waiting for the
|
||||
// user to click Sync.
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
self.state_manager.update_data(data).await;
|
||||
|
||||
// Transitive discovery: spawn a task that pulls the new peer's
|
||||
// state (its own federated peers end up as Observer entries on
|
||||
// our side) so after a join every existing peer in our list is
|
||||
// aware of the newcomer via the next pair of syncs, without the
|
||||
// user clicking anything. Best-effort; errors are logged only.
|
||||
let data_dir = self.config.data_dir.clone();
|
||||
let new_peer_did = did.to_string();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
|
||||
if let Err(e) = crate::federation::sync_with_peer_by_did(&data_dir, &new_peer_did).await
|
||||
{
|
||||
tracing::debug!(
|
||||
peer_did = %new_peer_did,
|
||||
error = %e,
|
||||
"Transitive sync on peer-joined failed (non-fatal)"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
Ok(serde_json::json!({ "accepted": true }))
|
||||
}
|
||||
|
||||
@@ -476,7 +661,8 @@ impl RpcHandler {
|
||||
Some(node) => {
|
||||
// Verify signature using the peer's KNOWN pubkey (H3 security fix)
|
||||
let sign_data = format!("address-changed:{}:{}", did, new_onion);
|
||||
match identity::NodeIdentity::verify(&node.pubkey, sign_data.as_bytes(), signature) {
|
||||
match identity::NodeIdentity::verify(&node.pubkey, sign_data.as_bytes(), signature)
|
||||
{
|
||||
Ok(true) => {}
|
||||
_ => {
|
||||
tracing::warn!(did = %did, "Rejected address change: invalid signature");
|
||||
@@ -538,14 +724,6 @@ impl RpcHandler {
|
||||
|
||||
let nodes = federation::load_nodes(&self.config.data_dir).await?;
|
||||
|
||||
let proxy = reqwest::Proxy::all(crate::constants::TOR_SOCKS_PROXY)
|
||||
.context("Invalid Tor proxy")?;
|
||||
let client = reqwest::Client::builder()
|
||||
.proxy(proxy)
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.build()
|
||||
.context("Failed to build HTTP client")?;
|
||||
|
||||
let mut notified = 0u32;
|
||||
let mut failed = 0u32;
|
||||
let mut results = Vec::new();
|
||||
@@ -556,13 +734,6 @@ impl RpcHandler {
|
||||
continue;
|
||||
}
|
||||
|
||||
let host = if node.onion.ends_with(".onion") {
|
||||
node.onion.clone()
|
||||
} else {
|
||||
format!("{}.onion", node.onion)
|
||||
};
|
||||
let url = format!("http://{}/rpc/v1", host);
|
||||
|
||||
let body = serde_json::json!({
|
||||
"method": "federation.peer-did-changed",
|
||||
"params": {
|
||||
@@ -574,23 +745,32 @@ impl RpcHandler {
|
||||
}
|
||||
});
|
||||
|
||||
match client.post(&url).json(&body).send().await {
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
let req = crate::fips::dial::PeerRequest::new(
|
||||
node.fips_npub.as_deref(),
|
||||
&node.onion,
|
||||
"/rpc/v1",
|
||||
)
|
||||
.service(crate::settings::transport::PeerService::Peers)
|
||||
.timeout(std::time::Duration::from_secs(30));
|
||||
|
||||
match req.send_json(&body).await {
|
||||
Ok((resp, transport)) if resp.status().is_success() => {
|
||||
notified += 1;
|
||||
results.push(serde_json::json!({
|
||||
"did": node.did,
|
||||
"status": "ok",
|
||||
"transport": transport.to_string(),
|
||||
}));
|
||||
info!(peer_did = %node.did, "Notified peer of DID rotation");
|
||||
info!(peer_did = %node.did, transport = %transport, "Notified peer of DID rotation");
|
||||
}
|
||||
Ok(resp) => {
|
||||
Ok((resp, transport)) => {
|
||||
failed += 1;
|
||||
results.push(serde_json::json!({
|
||||
"did": node.did,
|
||||
"status": "error",
|
||||
"error": format!("Peer returned {}", resp.status()),
|
||||
"error": format!("Peer returned {} (via {})", resp.status(), transport),
|
||||
}));
|
||||
warn!(peer_did = %node.did, status = %resp.status(), "Peer rejected DID rotation notification");
|
||||
warn!(peer_did = %node.did, status = %resp.status(), transport = %transport, "Peer rejected DID rotation notification");
|
||||
}
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
@@ -667,9 +847,7 @@ impl RpcHandler {
|
||||
// Verify the rotation proof: the old key signed
|
||||
// "did-rotate:{old_did}:{new_did}:{timestamp}" and the sender
|
||||
// forwards both the signature and the full proof_message.
|
||||
let proof_message = params
|
||||
.get("proof_message")
|
||||
.and_then(|v| v.as_str());
|
||||
let proof_message = params.get("proof_message").and_then(|v| v.as_str());
|
||||
|
||||
let verified = if let Some(msg) = proof_message {
|
||||
// Verify the proof_message starts with the expected prefix
|
||||
@@ -687,7 +865,11 @@ impl RpcHandler {
|
||||
// Fallback: verify without timestamp (backwards-compatible)
|
||||
let fallback_msg = format!("did-rotate:{}:{}", old_did, new_did);
|
||||
matches!(
|
||||
identity::NodeIdentity::verify(&node.pubkey, fallback_msg.as_bytes(), signature),
|
||||
identity::NodeIdentity::verify(
|
||||
&node.pubkey,
|
||||
fallback_msg.as_bytes(),
|
||||
signature
|
||||
),
|
||||
Ok(true)
|
||||
)
|
||||
};
|
||||
@@ -698,11 +880,31 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
let old_pubkey = node.pubkey.clone();
|
||||
let rotated_name = node.name.clone();
|
||||
node.did = new_did.to_string();
|
||||
node.pubkey = new_pubkey.to_string();
|
||||
node.last_seen = Some(chrono::Utc::now().to_rfc3339());
|
||||
federation::save_nodes(&self.config.data_dir, &nodes).await?;
|
||||
|
||||
// Drop the stale mesh peer entry keyed by the old pubkey's
|
||||
// synthetic contact_id, then upsert a fresh one under the
|
||||
// new pubkey so the chat UI doesn't show two rows post-rotation.
|
||||
{
|
||||
let svc = self.mesh_service.read().await;
|
||||
if let Some(svc) = svc.as_ref() {
|
||||
let state = svc.shared_state();
|
||||
let stale_id = mesh::federation_peer_contact_id(&old_pubkey);
|
||||
state.peers.write().await.remove(&stale_id);
|
||||
mesh::upsert_federation_peer(
|
||||
&state,
|
||||
new_pubkey,
|
||||
new_did,
|
||||
rotated_name.as_deref(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
info!(
|
||||
old_did = %old_did,
|
||||
new_did = %new_did,
|
||||
@@ -725,4 +927,213 @@ impl RpcHandler {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// federation.list-pending-requests — return the inbox of inbound peer
|
||||
/// requests received over Nostr (and our outbound `Sent` rows). Each
|
||||
/// row carries a stable `id` the FE refers to when calling
|
||||
/// `federation.approve-request` / `federation.reject-request`.
|
||||
pub(in crate::api::rpc) async fn handle_federation_list_pending_requests(
|
||||
&self,
|
||||
) -> Result<serde_json::Value> {
|
||||
let requests = pending::load_pending(&self.config.data_dir).await?;
|
||||
Ok(serde_json::json!({ "requests": requests }))
|
||||
}
|
||||
|
||||
/// federation.approve-request — turn a pending peer request into a
|
||||
/// federation invite, ship it back via NIP-44, and add the requester
|
||||
/// to our federation list as `Observer` (NOT Trusted — the user must
|
||||
/// explicitly promote afterwards via `federation.set-trust`).
|
||||
///
|
||||
/// This is the *only* code path that ever causes our onion to leave
|
||||
/// this box over Nostr, and the onion only travels inside a NIP-44
|
||||
/// ciphertext addressed to the requester's specific nostr pubkey.
|
||||
pub(in crate::api::rpc) async fn handle_federation_approve_request(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let id = params
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing id"))?;
|
||||
|
||||
let req = pending::find_by_id(&self.config.data_dir, id)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Pending request not found: {}", id))?;
|
||||
if !matches!(req.state, pending::PendingState::Pending) || req.outbound {
|
||||
anyhow::bail!(
|
||||
"Pending request is not awaiting approval (state={:?})",
|
||||
req.state
|
||||
);
|
||||
}
|
||||
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
let local_did = identity::did_key_from_pubkey_hex(&data.server_info.pubkey)?;
|
||||
let local_onion = data
|
||||
.server_info
|
||||
.tor_address
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("Tor address not available"))?;
|
||||
let local_pubkey = data.server_info.pubkey.clone();
|
||||
|
||||
// Generate a one-shot federation invite. The code embeds OUR onion
|
||||
// and OUR pubkey, but it leaves this box only inside the NIP-44
|
||||
// ciphertext below.
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let local_fips_npub = identity::fips_npub(&identity_dir).await.unwrap_or(None);
|
||||
let invite_code = federation::create_invite(
|
||||
&self.config.data_dir,
|
||||
&local_did,
|
||||
&local_onion,
|
||||
&local_pubkey,
|
||||
local_fips_npub.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Pre-add the requester to OUR federation list as Observer so that
|
||||
// when their `federation.peer-joined` callback arrives over Tor we
|
||||
// already trust their pubkey enough to accept the join. Their DID
|
||||
// and pubkey come from the request — we'll cross-check the pubkey
|
||||
// against the eventual peer-joined signature in the existing
|
||||
// verification path (handlers.rs line ~365).
|
||||
if !req.from_did.is_empty() {
|
||||
// We don't know the requester's onion or ed25519 pubkey yet —
|
||||
// they'll send those in the federation.peer-joined callback
|
||||
// after they apply our invite. Until then we can't add a real
|
||||
// FederatedNode entry. We just store the pending row as
|
||||
// Approved so the UI shows progress, and trust the existing
|
||||
// peer-joined handler to admit them as Observer when they call.
|
||||
//
|
||||
// Caveat: peer-joined currently hardcodes TrustLevel::Trusted.
|
||||
// We override that below by demoting on success.
|
||||
debug!(
|
||||
requester_did = %req.from_did,
|
||||
"Approval pending — waiting for federation.peer-joined callback over Tor"
|
||||
);
|
||||
}
|
||||
|
||||
// Encrypt + send the invite over NIP-44 to the requester.
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
nostr_handshake::send_peer_invite(
|
||||
&identity_dir,
|
||||
&req.from_nostr_pubkey,
|
||||
&invite_code,
|
||||
&self.config.nostr_relays,
|
||||
self.config.nostr_tor_proxy.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
pending::set_state(&self.config.data_dir, id, pending::PendingState::Approved).await?;
|
||||
info!(
|
||||
id = %id,
|
||||
from = %req.from_nostr_pubkey,
|
||||
"Approved peer request and shipped invite over NIP-44"
|
||||
);
|
||||
Ok(serde_json::json!({
|
||||
"approved": true,
|
||||
"id": id,
|
||||
}))
|
||||
}
|
||||
|
||||
/// federation.reject-request — drop a pending request and, if requested,
|
||||
/// ship a NIP-44 `PeerReject` to the sender so their UI can update.
|
||||
pub(in crate::api::rpc) async fn handle_federation_reject_request(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let id = params
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing id"))?;
|
||||
let reason = params.get("reason").and_then(|v| v.as_str());
|
||||
let notify = params
|
||||
.get("notify")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
|
||||
let req = pending::find_by_id(&self.config.data_dir, id)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Pending request not found: {}", id))?;
|
||||
if !matches!(req.state, pending::PendingState::Pending) || req.outbound {
|
||||
anyhow::bail!(
|
||||
"Pending request is not awaiting approval (state={:?})",
|
||||
req.state
|
||||
);
|
||||
}
|
||||
|
||||
if notify {
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let _ = nostr_handshake::send_peer_reject(
|
||||
&identity_dir,
|
||||
&req.from_nostr_pubkey,
|
||||
reason,
|
||||
&self.config.nostr_relays,
|
||||
self.config.nostr_tor_proxy.as_deref(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pending::set_state(&self.config.data_dir, id, pending::PendingState::Rejected).await?;
|
||||
info!(id = %id, from = %req.from_nostr_pubkey, "Rejected peer request");
|
||||
Ok(serde_json::json!({ "rejected": true, "id": id }))
|
||||
}
|
||||
|
||||
/// federation.cancel-request — withdraw an outbound peer request we
|
||||
/// sent but haven't heard back on. The local row is deleted and,
|
||||
/// unless `notify=false`, a PeerCancel nostr DM is sent so the
|
||||
/// target drops their inbound pending row.
|
||||
pub(in crate::api::rpc) async fn handle_federation_cancel_request(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let id = params
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing id"))?;
|
||||
let reason = params.get("reason").and_then(|v| v.as_str());
|
||||
// Default TRUE — cancelling without notifying is a footgun (the
|
||||
// recipient's UI keeps showing an unanswerable request).
|
||||
let notify = params
|
||||
.get("notify")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(true);
|
||||
|
||||
let req = pending::find_by_id(&self.config.data_dir, id)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Pending request not found: {}", id))?;
|
||||
if !req.outbound || !matches!(req.state, pending::PendingState::Sent) {
|
||||
anyhow::bail!(
|
||||
"Can only cancel outbound requests in Sent state (outbound={}, state={:?})",
|
||||
req.outbound,
|
||||
req.state
|
||||
);
|
||||
}
|
||||
|
||||
if notify {
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
// Best-effort: log but don't fail the cancel if the nostr
|
||||
// relay is unreachable — the local row is still dropped.
|
||||
if let Err(e) = nostr_handshake::send_peer_cancel(
|
||||
&identity_dir,
|
||||
&req.from_nostr_pubkey,
|
||||
reason,
|
||||
&self.config.nostr_relays,
|
||||
self.config.nostr_tor_proxy.as_deref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
id = %id,
|
||||
error = %e,
|
||||
"peer-cancel DM failed; local row dropped anyway"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pending::delete(&self.config.data_dir, id).await?;
|
||||
info!(id = %id, to = %req.from_nostr_pubkey, notified = notify, "Cancelled outbound peer request");
|
||||
Ok(serde_json::json!({ "cancelled": true, "id": id, "notified": notify }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,4 +14,3 @@ pub(super) fn validate_did(did: &str) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
//! RPC handlers for the FIPS mesh transport subsystem.
|
||||
//!
|
||||
//! Surface is deliberately thin: a read-only `fips.status`, a user-gated
|
||||
//! `fips.check-update`, a stubbed `fips.apply-update`, and a
|
||||
//! `fips.install` that (re-)materialises the daemon config + key and
|
||||
//! activates the service. All writes go through `sudo` helpers in
|
||||
//! `crate::fips`.
|
||||
|
||||
use super::RpcHandler;
|
||||
use crate::fips;
|
||||
use anyhow::Result;
|
||||
|
||||
impl RpcHandler {
|
||||
pub(super) async fn handle_fips_status(&self) -> Result<serde_json::Value> {
|
||||
let status = fips::FipsStatus::query(&self.config.data_dir).await;
|
||||
Ok(serde_json::to_value(status)?)
|
||||
}
|
||||
|
||||
pub(super) async fn handle_fips_check_update(&self) -> Result<serde_json::Value> {
|
||||
let check = fips::update::check().await?;
|
||||
Ok(serde_json::to_value(check)?)
|
||||
}
|
||||
|
||||
pub(super) async fn handle_fips_apply_update(&self) -> Result<serde_json::Value> {
|
||||
fips::update::apply().await?;
|
||||
Ok(serde_json::json!({ "applied": true }))
|
||||
}
|
||||
|
||||
/// Install config + key into /etc/fips and activate the service.
|
||||
/// Intended to be called:
|
||||
/// - once by the seed-onboarding flow, right after the FIPS key
|
||||
/// is written to /data/identity/fips_key, and
|
||||
/// - on user demand from the dashboard if something drifted.
|
||||
pub(super) async fn handle_fips_install(&self) -> Result<serde_json::Value> {
|
||||
let identity_dir = fips::identity_dir_from(&self.config.data_dir);
|
||||
fips::config::install(&identity_dir).await?;
|
||||
fips::service::activate(fips::SERVICE_UNIT).await?;
|
||||
let status = fips::FipsStatus::query(&self.config.data_dir).await;
|
||||
Ok(serde_json::to_value(status)?)
|
||||
}
|
||||
|
||||
/// Restart whichever fips unit is supervising the daemon on this host.
|
||||
/// Nodes installed from the archipelago ISO use `archipelago-fips.service`;
|
||||
/// nodes that had the upstream debian package set up first may only have
|
||||
/// `fips.service`. We resolve the active one via `service::active_unit()`
|
||||
/// so the UI button is never a no-op.
|
||||
pub(super) async fn handle_fips_restart(&self) -> Result<serde_json::Value> {
|
||||
let unit = fips::service::active_unit().await;
|
||||
fips::service::restart(unit).await?;
|
||||
Ok(serde_json::json!({ "restarted": true, "unit": unit }))
|
||||
}
|
||||
|
||||
/// Full reconnect: stop the daemon, bring it back, wait for the DHT
|
||||
/// bootstrap window, poll the identity-cache + peer list, and
|
||||
/// classify what recovered (or didn't) so the UI can explain it to
|
||||
/// the user instead of showing a generic failure.
|
||||
///
|
||||
/// Runtime: ~20s. Needs an RPC timeout ≥ 45s on the client.
|
||||
pub(super) async fn handle_fips_reconnect(&self) -> Result<serde_json::Value> {
|
||||
let identity_dir = fips::identity_dir_from(&self.config.data_dir);
|
||||
let before = fips::FipsStatus::query(&self.config.data_dir).await;
|
||||
|
||||
// Heal the pre-fix bech32-text fips_key.pub → 32-raw-bytes
|
||||
// mismatch. The daemon silently authenticates with a garbage
|
||||
// pubkey when the .pub file is 63-char text, which looks like
|
||||
// "anchor unreachable" to the user even though the real fault
|
||||
// was an identity malformed on the node itself. Re-install the
|
||||
// config + keys so /etc/fips gets the healed .pub.
|
||||
let key_src = identity_dir.join("fips_key");
|
||||
let pub_src = identity_dir.join("fips_key.pub");
|
||||
if key_src.exists() {
|
||||
let _ = fips::config::normalize_pub_file(&key_src, &pub_src).await;
|
||||
// Re-install refreshes /etc/fips/fips.pub from the healed
|
||||
// source. No-op if nothing changed.
|
||||
let _ = fips::config::install(&identity_dir).await;
|
||||
}
|
||||
|
||||
// Operate on whichever fips unit is actually up — nodes that
|
||||
// have the upstream `fips.service` rather than the
|
||||
// archipelago-managed `archipelago-fips.service` used to see
|
||||
// Reconnect silently fail because we stopped a unit that
|
||||
// didn't exist. Clean stop+start rather than `restart` so a
|
||||
// daemon that fails to come back up surfaces as
|
||||
// service_active=false instead of quietly sticking with the
|
||||
// old process.
|
||||
let unit = fips::service::active_unit().await;
|
||||
let _ = fips::service::stop(unit).await;
|
||||
tokio::time::sleep(std::time::Duration::from_millis(800)).await;
|
||||
fips::service::activate(unit).await?;
|
||||
|
||||
// Re-push seed anchors after restart so freshly-bound daemons
|
||||
// don't have to wait 5 min for the periodic apply loop.
|
||||
if let Ok(list) = fips::anchors::load(&self.config.data_dir).await {
|
||||
if !list.is_empty() {
|
||||
let _ = fips::anchors::apply(&list).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Anchor bootstrap window: poll the status every ~3s for up to
|
||||
// 20s. Bail as soon as the anchor is connected.
|
||||
let mut last_status: Option<fips::FipsStatus> = None;
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
|
||||
loop {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
|
||||
let s = fips::FipsStatus::query(&self.config.data_dir).await;
|
||||
if s.anchor_connected {
|
||||
last_status = Some(s);
|
||||
break;
|
||||
}
|
||||
last_status = Some(s);
|
||||
if std::time::Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let after = last_status.unwrap_or_else(|| before.clone());
|
||||
|
||||
let recovered = after.anchor_connected && !before.anchor_connected;
|
||||
let likely_cause = if after.anchor_connected {
|
||||
"connected"
|
||||
} else if !after.service_active {
|
||||
"daemon_down"
|
||||
} else if !after.key_present {
|
||||
"no_seed_key"
|
||||
} else if after.authenticated_peer_count == 0 {
|
||||
// Daemon is up with a key but hasn't authenticated any
|
||||
// peers — almost always outbound UDP/8668 dropped by the
|
||||
// local firewall/router, or the anchor itself being down.
|
||||
"no_outbound_udp_or_anchor_down"
|
||||
} else {
|
||||
"peers_but_no_anchor"
|
||||
};
|
||||
let hint = match likely_cause {
|
||||
"connected" => "An anchor is reachable.",
|
||||
"daemon_down" => "The FIPS daemon didn't come back up — check the FIPS service on this host.",
|
||||
"no_seed_key" => "No seed-derived FIPS key on disk. Re-run the onboarding unlock step.",
|
||||
"no_outbound_udp_or_anchor_down" =>
|
||||
"Daemon is running but no peers handshook. Your router / ISP might be blocking outbound UDP 8668, or every configured anchor could be down. Add a reachable peer in Seed Anchors.",
|
||||
"peers_but_no_anchor" =>
|
||||
"Mesh has peers but none of them are anchors we recognise. Add your cluster's anchor in Seed Anchors.",
|
||||
_ => "",
|
||||
};
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"recovered": recovered,
|
||||
"likely_cause": likely_cause,
|
||||
"hint": hint,
|
||||
"before": before,
|
||||
"after": after,
|
||||
}))
|
||||
}
|
||||
|
||||
/// List the seed-anchor entries configured on this node.
|
||||
pub(super) async fn handle_fips_list_seed_anchors(&self) -> Result<serde_json::Value> {
|
||||
let list = fips::anchors::load(&self.config.data_dir).await?;
|
||||
Ok(serde_json::json!({ "seed_anchors": list }))
|
||||
}
|
||||
|
||||
/// Add (or update) a seed anchor and immediately push it into the
|
||||
/// running daemon. Params: `{ npub, address, transport?, label? }`.
|
||||
pub(super) async fn handle_fips_add_seed_anchor(
|
||||
&self,
|
||||
params: &serde_json::Value,
|
||||
) -> Result<serde_json::Value> {
|
||||
let anchor: fips::anchors::SeedAnchor = serde_json::from_value(params.clone())
|
||||
.map_err(|e| anyhow::anyhow!("bad seed anchor payload: {}", e))?;
|
||||
if !anchor.npub.starts_with("npub1") {
|
||||
anyhow::bail!("npub must be bech32 (npub1...)");
|
||||
}
|
||||
if !anchor.address.contains(':') {
|
||||
anyhow::bail!("address must be host:port (e.g. 192.168.1.116:8668)");
|
||||
}
|
||||
let list = fips::anchors::add(&self.config.data_dir, anchor.clone()).await?;
|
||||
// Push just the newly-added anchor into the running daemon so
|
||||
// the user sees effect without waiting for the periodic apply.
|
||||
let results = fips::anchors::apply(&[anchor]).await;
|
||||
Ok(serde_json::json!({
|
||||
"seed_anchors": list,
|
||||
"apply": results.iter().map(|r| {
|
||||
serde_json::json!({ "npub": r.npub, "ok": r.ok, "message": r.message })
|
||||
}).collect::<Vec<_>>(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Remove a seed anchor by npub. Params: `{ npub }`. Does NOT tear
|
||||
/// down an already-authenticated peer connection — it only stops
|
||||
/// us from re-dialing the anchor on the next apply cycle.
|
||||
pub(super) async fn handle_fips_remove_seed_anchor(
|
||||
&self,
|
||||
params: &serde_json::Value,
|
||||
) -> Result<serde_json::Value> {
|
||||
let npub = params
|
||||
.get("npub")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("missing npub"))?;
|
||||
let list = fips::anchors::remove(&self.config.data_dir, npub).await?;
|
||||
Ok(serde_json::json!({ "seed_anchors": list }))
|
||||
}
|
||||
|
||||
/// Re-apply all seed anchors to the running daemon. Useful after a
|
||||
/// FIPS restart or when the user wants to force a reconnection
|
||||
/// attempt without waiting for the periodic apply loop.
|
||||
pub(super) async fn handle_fips_apply_seed_anchors(&self) -> Result<serde_json::Value> {
|
||||
let list = fips::anchors::load(&self.config.data_dir).await?;
|
||||
let results = fips::anchors::apply(&list).await;
|
||||
Ok(serde_json::json!({
|
||||
"applied": results.len(),
|
||||
"results": results.iter().map(|r| {
|
||||
serde_json::json!({ "npub": r.npub, "ok": r.ok, "message": r.message })
|
||||
}).collect::<Vec<_>>(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,117 @@
|
||||
//! Nostr peer-discovery RPCs.
|
||||
//!
|
||||
//! `handshake.discover` — browse other nodes' presence events on configured
|
||||
//! relays. Returns DID + nostr pubkey only; no onion is ever exposed.
|
||||
//!
|
||||
//! `handshake.connect` — send a `PeerRequest` to a discovered node's nostr
|
||||
//! pubkey. Records the outbound request locally so the user can see what
|
||||
//! they've sent. Does NOT include our onion address on the wire.
|
||||
//!
|
||||
//! `handshake.poll` — fetch new NIP-44 DMs addressed to our nostr pubkey
|
||||
//! and dispatch them: inbound `PeerRequest` is queued in
|
||||
//! `federation::pending` for manual approval; inbound `PeerInvite` is
|
||||
//! applied via the existing federation invite-acceptance flow (which
|
||||
//! adds the new peer as `Observer` — see federation.rs); inbound
|
||||
//! `PeerReject` is recorded against the matching outbound row.
|
||||
|
||||
use super::RpcHandler;
|
||||
use crate::{nostr_handshake, peers};
|
||||
use anyhow::Result;
|
||||
use crate::federation::pending::{self, PendingPeerRequest, PendingState};
|
||||
use crate::nostr_handshake::{self, HandshakeMessage};
|
||||
use anyhow::{Context, Result};
|
||||
use nostr_sdk::FromBech32;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const NOSTR_STATE_FILE: &str = "nostr_discovery_state.json";
|
||||
|
||||
/// Runtime override for `Config::nostr_discovery_enabled`. The OS-level
|
||||
/// config file is read once at boot and is OFF by default; this state file
|
||||
/// lets the user flip discoverability on/off at runtime via the Federation
|
||||
/// UI without restarting the service. Both the boot-time presence publish
|
||||
/// and the `handshake.poll` handler check this file before doing anything.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
struct NostrDiscoveryState {
|
||||
#[serde(default)]
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
async fn load_discovery_state(data_dir: &std::path::Path) -> NostrDiscoveryState {
|
||||
let path = data_dir.join(NOSTR_STATE_FILE);
|
||||
match tokio::fs::read_to_string(&path).await {
|
||||
Ok(s) => serde_json::from_str(&s).unwrap_or_default(),
|
||||
Err(_) => NostrDiscoveryState::default(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn save_discovery_state(
|
||||
data_dir: &std::path::Path,
|
||||
state: &NostrDiscoveryState,
|
||||
) -> Result<()> {
|
||||
let path = data_dir.join(NOSTR_STATE_FILE);
|
||||
let content = serde_json::to_string_pretty(state).context("serialize discovery state")?;
|
||||
tokio::fs::write(&path, content)
|
||||
.await
|
||||
.context("write discovery state")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl RpcHandler {
|
||||
/// Discover nodes (presence-only — returns Nostr pubkeys + DIDs, no onion addresses).
|
||||
/// Read the current runtime discoverability flag.
|
||||
pub(super) async fn handle_nostr_discovery_status(&self) -> Result<serde_json::Value> {
|
||||
let state = load_discovery_state(&self.config.data_dir).await;
|
||||
Ok(serde_json::json!({ "enabled": state.enabled }))
|
||||
}
|
||||
|
||||
/// Set the runtime discoverability flag. If turning ON, publish presence
|
||||
/// once immediately so the user gets visible feedback that the relays
|
||||
/// have been notified. If turning OFF, do NOT actively scrub the relays
|
||||
/// here — `nostr_handshake::publish_presence` is replaceable, so the
|
||||
/// next reboot's startup pass plus the existing legacy revocation in
|
||||
/// `nostr_discovery::revoke_legacy_advertisements` are sufficient. A
|
||||
/// future Layer 3 task adds an explicit "tombstone" publish if needed.
|
||||
pub(super) async fn handle_nostr_set_discovery(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let enabled = params
|
||||
.get("enabled")
|
||||
.and_then(|v| v.as_bool())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing enabled"))?;
|
||||
|
||||
save_discovery_state(&self.config.data_dir, &NostrDiscoveryState { enabled }).await?;
|
||||
|
||||
if enabled && !self.config.nostr_relays.is_empty() {
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let did = crate::identity::did_key_from_pubkey_hex(&data.server_info.pubkey)
|
||||
.unwrap_or_default();
|
||||
let version = data.server_info.version.clone();
|
||||
let relays = self.config.nostr_relays.clone();
|
||||
let tor_proxy = self.config.nostr_tor_proxy.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = nostr_handshake::publish_presence(
|
||||
&identity_dir,
|
||||
&did,
|
||||
&version,
|
||||
&relays,
|
||||
tor_proxy.as_deref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!("Initial presence publish failed: {}", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Ok(serde_json::json!({ "enabled": enabled }))
|
||||
}
|
||||
|
||||
/// Discover discoverable nodes via Nostr presence events.
|
||||
/// Returns (nostr_pubkey, npub, DID, version) only — never an onion.
|
||||
pub(super) async fn handle_handshake_discover(&self) -> Result<serde_json::Value> {
|
||||
// Discoverability gate: respect the runtime toggle. We allow `discover`
|
||||
// to query relays as long as the user is actively browsing — they're
|
||||
// an anonymous observer of presence events, not publishing anything.
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let nodes = nostr_handshake::discover_nodes(
|
||||
&identity_dir,
|
||||
@@ -16,59 +122,90 @@ impl RpcHandler {
|
||||
Ok(serde_json::json!({ "nodes": nodes }))
|
||||
}
|
||||
|
||||
/// Send encrypted connection request to a peer's Nostr pubkey.
|
||||
/// Params: { recipient_nostr_pubkey }
|
||||
/// Send a `PeerRequest` to a discovered node. Onion is never sent.
|
||||
/// Params: `{ recipient_nostr_pubkey, message?, name? }`.
|
||||
pub(super) async fn handle_handshake_connect(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
// Accept either hex pubkey or npub1... bech32 format
|
||||
let recipient_raw = params
|
||||
.get("recipient_nostr_pubkey")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing recipient_nostr_pubkey"))?;
|
||||
let recipient = if recipient_raw.starts_with("npub1") {
|
||||
let recipient_hex = if recipient_raw.starts_with("npub1") {
|
||||
nostr_sdk::PublicKey::from_bech32(recipient_raw)
|
||||
.map_err(|e| anyhow::anyhow!("Invalid npub: {}", e))?
|
||||
.to_hex()
|
||||
} else {
|
||||
recipient_raw.to_string()
|
||||
};
|
||||
let recipient = recipient.as_str();
|
||||
let recipient_npub = nostr_sdk::PublicKey::from_hex(&recipient_hex)
|
||||
.ok()
|
||||
.and_then(|pk| nostr_sdk::ToBech32::to_bech32(&pk).ok())
|
||||
.unwrap_or_default();
|
||||
let message = params.get("message").and_then(|v| v.as_str());
|
||||
let optional_name = params.get("name").and_then(|v| v.as_str());
|
||||
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
let our_onion = data
|
||||
.server_info
|
||||
.tor_address
|
||||
.as_deref()
|
||||
.ok_or_else(|| anyhow::anyhow!("No Tor address available — is Tor running?"))?;
|
||||
let our_node_pubkey = &data.server_info.pubkey;
|
||||
let our_did = crate::identity::did_key_from_pubkey_hex(our_node_pubkey)
|
||||
.unwrap_or_default();
|
||||
let our_did =
|
||||
crate::identity::did_key_from_pubkey_hex(&data.server_info.pubkey).unwrap_or_default();
|
||||
let our_version = &data.server_info.version;
|
||||
let our_name = data.server_info.name.as_deref();
|
||||
let our_name = optional_name.or(data.server_info.name.as_deref());
|
||||
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
nostr_handshake::send_connect_request(
|
||||
nostr_handshake::send_peer_request(
|
||||
&identity_dir,
|
||||
recipient,
|
||||
our_onion,
|
||||
our_node_pubkey,
|
||||
&recipient_hex,
|
||||
&our_did,
|
||||
our_version,
|
||||
our_name,
|
||||
message,
|
||||
&self.config.nostr_relays,
|
||||
self.config.nostr_tor_proxy.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(serde_json::json!({ "ok": true, "sent_to": recipient }))
|
||||
// Record the outbound request so the user can see "Sent" status
|
||||
// and so the eventual NIP-44 PeerInvite reply can be matched.
|
||||
let row = pending::insert_outbound(
|
||||
&self.config.data_dir,
|
||||
recipient_hex.clone(),
|
||||
recipient_npub,
|
||||
String::new(), // remote DID unknown until they reply
|
||||
None,
|
||||
message.map(String::from),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"ok": true,
|
||||
"sent_to": recipient_hex,
|
||||
"id": row.id,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Poll for incoming encrypted handshake messages (connect requests/responses).
|
||||
/// Auto-adds peers and auto-responds to requests.
|
||||
/// Poll relays for inbound NIP-44 handshake messages, then dispatch:
|
||||
/// - `PeerRequest` → queue in `federation::pending` for approval
|
||||
/// - `PeerInvite` → apply via federation invite flow (adds as Observer)
|
||||
/// - `PeerReject` → mark matching outbound row as `Rejected`
|
||||
///
|
||||
/// Never auto-adds peers, never auto-responds, never sends our onion.
|
||||
pub(super) async fn handle_handshake_poll(&self) -> Result<serde_json::Value> {
|
||||
// Runtime gate: if the user hasn't enabled discoverability, don't
|
||||
// touch the relays. The poll endpoint is a hard no-op until they
|
||||
// explicitly opt in via the Federation UI toggle.
|
||||
let state = load_discovery_state(&self.config.data_dir).await;
|
||||
if !state.enabled {
|
||||
return Ok(serde_json::json!({
|
||||
"polled": 0,
|
||||
"new_requests": Vec::<PendingPeerRequest>::new(),
|
||||
"applied_invites": Vec::<String>::new(),
|
||||
"rejected_outbound": Vec::<String>::new(),
|
||||
"skipped": Vec::<String>::new(),
|
||||
"discovery_disabled": true,
|
||||
}));
|
||||
}
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let handshakes = nostr_handshake::poll_handshakes(
|
||||
&identity_dir,
|
||||
@@ -78,72 +215,177 @@ impl RpcHandler {
|
||||
)
|
||||
.await?;
|
||||
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
let mut added_peers = Vec::new();
|
||||
let mut new_requests: Vec<PendingPeerRequest> = Vec::new();
|
||||
let mut applied_invites: Vec<String> = Vec::new();
|
||||
let mut rejected_outbound: Vec<String> = Vec::new();
|
||||
let mut cancelled_inbound: Vec<String> = Vec::new();
|
||||
let mut skipped: Vec<String> = Vec::new();
|
||||
|
||||
for hs in &handshakes {
|
||||
let (onion, node_pubkey, name) = match &hs.message {
|
||||
nostr_handshake::HandshakeMessage::ConnectRequest {
|
||||
onion,
|
||||
node_pubkey,
|
||||
match &hs.message {
|
||||
HandshakeMessage::PeerRequest {
|
||||
from_did,
|
||||
version: _,
|
||||
name,
|
||||
..
|
||||
message,
|
||||
} => {
|
||||
// Auto-respond with our details
|
||||
if let Some(our_onion) = data.server_info.tor_address.as_deref() {
|
||||
let our_did = crate::identity::did_key_from_pubkey_hex(
|
||||
&data.server_info.pubkey,
|
||||
)
|
||||
.unwrap_or_default();
|
||||
let _ = nostr_handshake::send_connect_response(
|
||||
&identity_dir,
|
||||
&hs.from_nostr_pubkey,
|
||||
our_onion,
|
||||
&data.server_info.pubkey,
|
||||
&our_did,
|
||||
&data.server_info.version,
|
||||
data.server_info.name.as_deref(),
|
||||
&self.config.nostr_relays,
|
||||
self.config.nostr_tor_proxy.as_deref(),
|
||||
)
|
||||
.await;
|
||||
match pending::insert_inbound(
|
||||
&self.config.data_dir,
|
||||
hs.from_nostr_pubkey.clone(),
|
||||
hs.from_nostr_npub.clone(),
|
||||
from_did.clone(),
|
||||
name.clone(),
|
||||
message.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(row)) => new_requests.push(row),
|
||||
Ok(None) => skipped.push(hs.from_nostr_pubkey.clone()),
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
from = %hs.from_nostr_pubkey,
|
||||
error = %e,
|
||||
"Dropped peer request (rate limit or storage error)"
|
||||
);
|
||||
skipped.push(hs.from_nostr_pubkey.clone());
|
||||
}
|
||||
}
|
||||
(onion.clone(), node_pubkey.clone(), name.clone())
|
||||
}
|
||||
nostr_handshake::HandshakeMessage::ConnectResponse {
|
||||
onion,
|
||||
node_pubkey,
|
||||
name,
|
||||
..
|
||||
} => (onion.clone(), node_pubkey.clone(), name.clone()),
|
||||
};
|
||||
HandshakeMessage::PeerInvite { invite_code } => {
|
||||
// Match against an outbound Sent request from this nostr
|
||||
// pubkey. If we never sent them anything, ignore — we
|
||||
// don't accept unsolicited invites over Nostr.
|
||||
let pendings = pending::load_pending(&self.config.data_dir).await?;
|
||||
let matching = pendings.iter().find(|r| {
|
||||
r.outbound
|
||||
&& r.from_nostr_pubkey == hs.from_nostr_pubkey
|
||||
&& matches!(r.state, PendingState::Sent)
|
||||
});
|
||||
let Some(row) = matching else {
|
||||
tracing::warn!(
|
||||
from = %hs.from_nostr_pubkey,
|
||||
"Ignoring unsolicited PeerInvite — no matching Sent request"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
let row_id = row.id.clone();
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
let local_did =
|
||||
crate::identity::did_key_from_pubkey_hex(&data.server_info.pubkey)
|
||||
.unwrap_or_default();
|
||||
let local_onion = data.server_info.tor_address.clone().unwrap_or_default();
|
||||
let local_pubkey = data.server_info.pubkey.clone();
|
||||
|
||||
// Auto-add as peer
|
||||
let peer = peers::KnownPeer {
|
||||
onion,
|
||||
pubkey: node_pubkey.clone(),
|
||||
name,
|
||||
added_at: Some(chrono::Utc::now().to_rfc3339()),
|
||||
};
|
||||
let _ = peers::add_peer(&self.config.data_dir, peer).await;
|
||||
added_peers.push(node_pubkey);
|
||||
let identity_dir2 = self.config.data_dir.join("identity");
|
||||
let node_identity =
|
||||
crate::identity::NodeIdentity::load_or_create(&identity_dir2).await?;
|
||||
let local_fips_npub = crate::identity::fips_npub(&identity_dir2)
|
||||
.await
|
||||
.unwrap_or(None);
|
||||
let local_name = data.server_info.name.clone();
|
||||
match crate::federation::accept_invite(
|
||||
&self.config.data_dir,
|
||||
invite_code,
|
||||
&local_did,
|
||||
&local_onion,
|
||||
&local_pubkey,
|
||||
local_fips_npub.as_deref(),
|
||||
local_name.as_deref(),
|
||||
|bytes| node_identity.sign(bytes),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(node) => {
|
||||
// Approved-by-them: their box already has us as Observer
|
||||
// (their approval handler added us under that trust level
|
||||
// before sending the invite). Demote our local entry to
|
||||
// Observer too — accept_invite hardcodes Trusted, but the
|
||||
// discovery flow should never auto-trust.
|
||||
let _ = crate::federation::set_trust_level(
|
||||
&self.config.data_dir,
|
||||
&node.did,
|
||||
crate::federation::TrustLevel::Observer,
|
||||
)
|
||||
.await;
|
||||
|
||||
// Mirror into the mesh peer table immediately so the
|
||||
// chat UI can address the new peer without waiting
|
||||
// for the next mesh restart.
|
||||
let svc = self.mesh_service.read().await;
|
||||
if let Some(svc) = svc.as_ref() {
|
||||
crate::mesh::upsert_federation_peer(
|
||||
&svc.shared_state(),
|
||||
&node.pubkey,
|
||||
&node.did,
|
||||
node.name.as_deref(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pending::set_state(
|
||||
&self.config.data_dir,
|
||||
&row_id,
|
||||
PendingState::Approved,
|
||||
)
|
||||
.await?;
|
||||
applied_invites.push(node.did);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
from = %hs.from_nostr_pubkey,
|
||||
error = %e,
|
||||
"Failed to apply PeerInvite"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
HandshakeMessage::PeerReject { reason } => {
|
||||
let pendings = pending::load_pending(&self.config.data_dir).await?;
|
||||
if let Some(row) = pendings.iter().find(|r| {
|
||||
r.outbound
|
||||
&& r.from_nostr_pubkey == hs.from_nostr_pubkey
|
||||
&& matches!(r.state, PendingState::Sent)
|
||||
}) {
|
||||
let row_id = row.id.clone();
|
||||
pending::set_state(&self.config.data_dir, &row_id, PendingState::Rejected)
|
||||
.await?;
|
||||
rejected_outbound.push(row_id);
|
||||
tracing::info!(
|
||||
from = %hs.from_nostr_pubkey,
|
||||
reason = ?reason,
|
||||
"Outbound peer request rejected"
|
||||
);
|
||||
}
|
||||
}
|
||||
HandshakeMessage::PeerCancel { reason } => {
|
||||
// Peer withdrew their PeerRequest — drop our matching
|
||||
// inbound pending row so it disappears from the UI.
|
||||
let pendings = pending::load_pending(&self.config.data_dir).await?;
|
||||
if let Some(row) = pendings.iter().find(|r| {
|
||||
!r.outbound
|
||||
&& r.from_nostr_pubkey == hs.from_nostr_pubkey
|
||||
&& matches!(r.state, PendingState::Pending)
|
||||
}) {
|
||||
let row_id = row.id.clone();
|
||||
pending::delete(&self.config.data_dir, &row_id).await?;
|
||||
cancelled_inbound.push(row_id);
|
||||
tracing::info!(
|
||||
from = %hs.from_nostr_pubkey,
|
||||
reason = ?reason,
|
||||
"Inbound peer request cancelled by sender"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let serialized: Vec<serde_json::Value> = handshakes
|
||||
.iter()
|
||||
.map(|hs| {
|
||||
serde_json::json!({
|
||||
"from_nostr_pubkey": hs.from_nostr_pubkey,
|
||||
"from_nostr_npub": hs.from_nostr_npub,
|
||||
"message": hs.message,
|
||||
"timestamp": hs.timestamp,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"handshakes": serialized,
|
||||
"added_peers": added_peers,
|
||||
"polled": handshakes.len(),
|
||||
"new_requests": new_requests,
|
||||
"applied_invites": applied_invites,
|
||||
"rejected_outbound": rejected_outbound,
|
||||
"cancelled_inbound": cancelled_inbound,
|
||||
"skipped": skipped,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,7 +246,9 @@ impl RpcHandler {
|
||||
.as_array()
|
||||
.ok_or_else(|| anyhow::anyhow!("DID Document missing '@context' array"))?;
|
||||
|
||||
let has_did_context = context.iter().any(|c| c.as_str() == Some("https://www.w3.org/ns/did/v1"));
|
||||
let has_did_context = context
|
||||
.iter()
|
||||
.any(|c| c.as_str() == Some("https://www.w3.org/ns/did/v1"));
|
||||
if !has_did_context {
|
||||
return Ok(serde_json::json!({
|
||||
"valid": false,
|
||||
@@ -272,12 +274,14 @@ impl RpcHandler {
|
||||
match crate::identity::pubkey_bytes_from_did_key(did) {
|
||||
Ok(pubkey_bytes) => {
|
||||
// Check that at least one verification method has matching key
|
||||
let pubkey_multibase = format!("z{}", bs58::encode(&pubkey_bytes).into_string());
|
||||
let has_matching_key = verification_methods.iter().any(|vm| {
|
||||
vm["publicKeyMultibase"].as_str() == Some(&pubkey_multibase)
|
||||
});
|
||||
let pubkey_multibase =
|
||||
format!("z{}", bs58::encode(&pubkey_bytes).into_string());
|
||||
let has_matching_key = verification_methods
|
||||
.iter()
|
||||
.any(|vm| vm["publicKeyMultibase"].as_str() == Some(&pubkey_multibase));
|
||||
if !has_matching_key {
|
||||
errors.push("No verificationMethod matches the DID's public key".to_string());
|
||||
errors
|
||||
.push("No verificationMethod matches the DID's public key".to_string());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -287,7 +291,10 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
// Check authentication is present
|
||||
if document["authentication"].as_array().map_or(true, |a| a.is_empty()) {
|
||||
if document["authentication"]
|
||||
.as_array()
|
||||
.is_none_or(|a| a.is_empty())
|
||||
{
|
||||
errors.push("Missing or empty 'authentication' field".to_string());
|
||||
}
|
||||
|
||||
@@ -343,15 +350,20 @@ impl RpcHandler {
|
||||
id.to_string()
|
||||
} else {
|
||||
// Prefer an identity with a Nostr key
|
||||
records.iter()
|
||||
records
|
||||
.iter()
|
||||
.find(|r| r.nostr_pubkey.is_some())
|
||||
.map(|r| r.id.clone())
|
||||
.ok_or_else(|| anyhow::anyhow!("No identity with Nostr key found"))?
|
||||
};
|
||||
|
||||
let identity = records.iter().find(|r| r.id == id)
|
||||
let identity = records
|
||||
.iter()
|
||||
.find(|r| r.id == id)
|
||||
.ok_or_else(|| anyhow::anyhow!("Identity not found: {}", id))?;
|
||||
let pubkey_hex = identity.nostr_pubkey.clone()
|
||||
let pubkey_hex = identity
|
||||
.nostr_pubkey
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("Identity has no Nostr key"))?;
|
||||
|
||||
if let Some(event_hash) = params.get("event_hash").and_then(|v| v.as_str()) {
|
||||
@@ -361,22 +373,32 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
// Full event signing: compute NIP-01 event hash
|
||||
let event = params.get("event")
|
||||
let event = params
|
||||
.get("event")
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'event' or 'event_hash' parameter"))?;
|
||||
|
||||
let kind = event.get("kind").and_then(|v| v.as_u64()).unwrap_or(1);
|
||||
let content = event.get("content").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let created_at = event.get("created_at").and_then(|v| v.as_u64())
|
||||
.unwrap_or_else(|| std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs());
|
||||
let tags = event.get("tags").cloned().unwrap_or_else(|| serde_json::json!([]));
|
||||
let created_at = event
|
||||
.get("created_at")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or_else(|| {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs()
|
||||
});
|
||||
let tags = event
|
||||
.get("tags")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| serde_json::json!([]));
|
||||
|
||||
// NIP-01 serialization: [0, pubkey, created_at, kind, tags, content]
|
||||
let serialized = serde_json::json!([0, pubkey_hex, created_at, kind, tags, content]);
|
||||
let serialized_str = serde_json::to_string(&serialized)?;
|
||||
|
||||
// SHA-256 hash
|
||||
use sha2::{Sha256, Digest};
|
||||
use sha2::{Digest, Sha256};
|
||||
let hash = Sha256::digest(serialized_str.as_bytes());
|
||||
let event_hash_hex = hex::encode(hash);
|
||||
|
||||
@@ -406,7 +428,8 @@ impl RpcHandler {
|
||||
return Ok(default_id);
|
||||
}
|
||||
// Fall back to first identity with a Nostr key, or just the first identity
|
||||
records.iter()
|
||||
records
|
||||
.iter()
|
||||
.find(|i| i.nostr_pubkey.is_some())
|
||||
.or(records.first())
|
||||
.map(|i| i.id.clone())
|
||||
@@ -420,9 +443,13 @@ impl RpcHandler {
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let id = self.resolve_identity_id(¶ms).await?;
|
||||
let pubkey = params.get("pubkey").and_then(|v| v.as_str())
|
||||
let pubkey = params
|
||||
.get("pubkey")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: pubkey"))?;
|
||||
let plaintext = params.get("plaintext").and_then(|v| v.as_str())
|
||||
let plaintext = params
|
||||
.get("plaintext")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: plaintext"))?;
|
||||
|
||||
let manager = IdentityManager::new(&self.config.data_dir).await?;
|
||||
@@ -438,9 +465,13 @@ impl RpcHandler {
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let id = self.resolve_identity_id(¶ms).await?;
|
||||
let pubkey = params.get("pubkey").and_then(|v| v.as_str())
|
||||
let pubkey = params
|
||||
.get("pubkey")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: pubkey"))?;
|
||||
let ciphertext = params.get("ciphertext").and_then(|v| v.as_str())
|
||||
let ciphertext = params
|
||||
.get("ciphertext")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: ciphertext"))?;
|
||||
|
||||
let manager = IdentityManager::new(&self.config.data_dir).await?;
|
||||
@@ -456,9 +487,13 @@ impl RpcHandler {
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let id = self.resolve_identity_id(¶ms).await?;
|
||||
let pubkey = params.get("pubkey").and_then(|v| v.as_str())
|
||||
let pubkey = params
|
||||
.get("pubkey")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: pubkey"))?;
|
||||
let plaintext = params.get("plaintext").and_then(|v| v.as_str())
|
||||
let plaintext = params
|
||||
.get("plaintext")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: plaintext"))?;
|
||||
|
||||
let manager = IdentityManager::new(&self.config.data_dir).await?;
|
||||
@@ -474,9 +509,13 @@ impl RpcHandler {
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let id = self.resolve_identity_id(¶ms).await?;
|
||||
let pubkey = params.get("pubkey").and_then(|v| v.as_str())
|
||||
let pubkey = params
|
||||
.get("pubkey")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: pubkey"))?;
|
||||
let ciphertext = params.get("ciphertext").and_then(|v| v.as_str())
|
||||
let ciphertext = params
|
||||
.get("ciphertext")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: ciphertext"))?;
|
||||
|
||||
let manager = IdentityManager::new(&self.config.data_dir).await?;
|
||||
@@ -528,10 +567,7 @@ impl RpcHandler {
|
||||
.await
|
||||
.context("Failed to connect to peer over Tor")?;
|
||||
|
||||
let body: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse peer response")?;
|
||||
let body: serde_json::Value = resp.json().await.context("Failed to parse peer response")?;
|
||||
|
||||
// Extract the DID Document from the RPC response
|
||||
let document = body
|
||||
@@ -539,9 +575,7 @@ impl RpcHandler {
|
||||
.ok_or_else(|| anyhow::anyhow!("Peer returned error or missing result"))?;
|
||||
|
||||
// Cache the resolved DID locally
|
||||
let did = document["id"]
|
||||
.as_str()
|
||||
.unwrap_or("unknown");
|
||||
let did = document["id"].as_str().unwrap_or("unknown");
|
||||
let cache_dir = self.config.data_dir.join("did-cache");
|
||||
tokio::fs::create_dir_all(&cache_dir).await.ok();
|
||||
let cache_file = cache_dir.join(format!("{}.json", onion.replace('.', "_")));
|
||||
@@ -550,9 +584,12 @@ impl RpcHandler {
|
||||
"resolved_at": chrono::Utc::now().to_rfc3339(),
|
||||
"onion": onion,
|
||||
});
|
||||
tokio::fs::write(&cache_file, serde_json::to_string_pretty(&cache_entry).unwrap_or_default())
|
||||
.await
|
||||
.ok();
|
||||
tokio::fs::write(
|
||||
&cache_file,
|
||||
serde_json::to_string_pretty(&cache_entry).unwrap_or_default(),
|
||||
)
|
||||
.await
|
||||
.ok();
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"document": document,
|
||||
@@ -627,7 +664,9 @@ impl RpcHandler {
|
||||
let record = manager.get(identity_id).await?;
|
||||
|
||||
if record.dht_did.is_none() {
|
||||
anyhow::bail!("Identity has no did:dht — create one first with identity.create-dht-did");
|
||||
anyhow::bail!(
|
||||
"Identity has no did:dht — create one first with identity.create-dht-did"
|
||||
);
|
||||
}
|
||||
|
||||
let signing_key = manager.get_signing_key(identity_id).await?;
|
||||
@@ -645,18 +684,41 @@ impl RpcHandler {
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let id = params.get("id").and_then(|v| v.as_str())
|
||||
let id = params
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: id"))?;
|
||||
validate_identity_id(id)?;
|
||||
|
||||
let profile = IdentityProfile {
|
||||
display_name: params.get("display_name").and_then(|v| v.as_str()).map(String::from),
|
||||
about: params.get("about").and_then(|v| v.as_str()).map(String::from),
|
||||
picture: params.get("picture").and_then(|v| v.as_str()).map(String::from),
|
||||
banner: params.get("banner").and_then(|v| v.as_str()).map(String::from),
|
||||
website: params.get("website").and_then(|v| v.as_str()).map(String::from),
|
||||
nip05: params.get("nip05").and_then(|v| v.as_str()).map(String::from),
|
||||
lud16: params.get("lud16").and_then(|v| v.as_str()).map(String::from),
|
||||
display_name: params
|
||||
.get("display_name")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from),
|
||||
about: params
|
||||
.get("about")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from),
|
||||
picture: params
|
||||
.get("picture")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from),
|
||||
banner: params
|
||||
.get("banner")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from),
|
||||
website: params
|
||||
.get("website")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from),
|
||||
nip05: params
|
||||
.get("nip05")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from),
|
||||
lud16: params
|
||||
.get("lud16")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from),
|
||||
};
|
||||
|
||||
let manager = IdentityManager::new(&self.config.data_dir).await?;
|
||||
@@ -665,27 +727,54 @@ impl RpcHandler {
|
||||
Ok(serde_json::json!({ "ok": true }))
|
||||
}
|
||||
|
||||
/// Publish kind 0 (metadata) profile to the local Nostr relay.
|
||||
/// Publish kind 0 (metadata) profile to every enabled Nostr relay
|
||||
/// configured in Manage Relays. Callers can override the default
|
||||
/// list by passing `relays: [..]` in params (e.g. to publish to a
|
||||
/// single relay for testing).
|
||||
pub(in crate::api::rpc) async fn handle_identity_publish_profile(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let id = params.get("id").and_then(|v| v.as_str())
|
||||
let id = params
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: id"))?;
|
||||
validate_identity_id(id)?;
|
||||
|
||||
let relay_url = params.get("relay")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("ws://localhost:18081");
|
||||
let relay_urls: Vec<String> =
|
||||
if let Some(arr) = params.get("relays").and_then(|v| v.as_array()) {
|
||||
arr.iter()
|
||||
.filter_map(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
.collect()
|
||||
} else if let Some(single) = params.get("relay").and_then(|v| v.as_str()) {
|
||||
vec![single.to_string()]
|
||||
} else {
|
||||
// Default: every enabled relay in the user's Manage Relays list.
|
||||
let statuses = crate::nostr_relays::list_relays(&self.config.data_dir)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
statuses
|
||||
.into_iter()
|
||||
.filter(|s| s.enabled)
|
||||
.map(|s| s.url)
|
||||
.collect()
|
||||
};
|
||||
|
||||
if relay_urls.is_empty() {
|
||||
anyhow::bail!("No enabled relays configured; add one under Manage Relays");
|
||||
}
|
||||
|
||||
let manager = IdentityManager::new(&self.config.data_dir).await?;
|
||||
let event_id = manager.publish_profile(id, relay_url).await?;
|
||||
let outcome = manager.publish_profile(id, &relay_urls).await?;
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"event_id": event_id,
|
||||
"relay": relay_url,
|
||||
"published": true,
|
||||
"event_id": outcome.event_id,
|
||||
"accepted": outcome.accepted,
|
||||
"rejected": outcome.rejected,
|
||||
"relays_attempted": relay_urls.len(),
|
||||
"published": !outcome.accepted.is_empty(),
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -9,9 +9,11 @@ pub(super) fn validate_identity_id(id: &str) -> Result<()> {
|
||||
if id.contains("..") || id.contains('/') || id.contains('\\') || id.contains('\0') {
|
||||
anyhow::bail!("Invalid identity id: contains forbidden characters");
|
||||
}
|
||||
if !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b':') {
|
||||
if !id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b':')
|
||||
{
|
||||
anyhow::bail!("Invalid identity id: must be alphanumeric, hyphens, underscores, or colons");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -77,14 +77,10 @@ impl RpcHandler {
|
||||
configure_ethernet_dhcp(interface).await?;
|
||||
}
|
||||
"static" => {
|
||||
let ip = params
|
||||
.get("ip")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: ip for static mode"))?;
|
||||
let gateway = params
|
||||
.get("gateway")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let ip = params.get("ip").and_then(|v| v.as_str()).ok_or_else(|| {
|
||||
anyhow::anyhow!("Missing required parameter: ip for static mode")
|
||||
})?;
|
||||
let gateway = params.get("gateway").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let dns = params
|
||||
.get("dns")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -140,7 +136,10 @@ impl RpcHandler {
|
||||
"quad9" => dns::DnsProvider::Quad9,
|
||||
"mullvad" => dns::DnsProvider::Mullvad,
|
||||
"custom" => dns::DnsProvider::Custom,
|
||||
other => anyhow::bail!("Unknown DNS provider: {}. Use: system, cloudflare, google, quad9, mullvad, custom", other),
|
||||
other => anyhow::bail!(
|
||||
"Unknown DNS provider: {}. Use: system, cloudflare, google, quad9, mullvad, custom",
|
||||
other
|
||||
),
|
||||
};
|
||||
|
||||
let custom_servers: Vec<String> = if provider == dns::DnsProvider::Custom {
|
||||
@@ -211,10 +210,7 @@ async fn list_interfaces() -> Result<Vec<serde_json::Value>> {
|
||||
.get("operstate")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("UNKNOWN");
|
||||
let mac = iface
|
||||
.get("address")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let mac = iface.get("address").and_then(|v| v.as_str()).unwrap_or("");
|
||||
|
||||
// Get IPv4 addresses
|
||||
let addrs: Vec<String> = iface
|
||||
@@ -236,7 +232,11 @@ async fn list_interfaces() -> Result<Vec<serde_json::Value>> {
|
||||
"wifi"
|
||||
} else if name.starts_with("en") || name.starts_with("eth") {
|
||||
"ethernet"
|
||||
} else if name.starts_with("veth") || name.starts_with("br-") || name.starts_with("docker") || name.starts_with("podman") {
|
||||
} else if name.starts_with("veth")
|
||||
|| name.starts_with("br-")
|
||||
|| name.starts_with("docker")
|
||||
|| name.starts_with("podman")
|
||||
{
|
||||
"virtual"
|
||||
} else {
|
||||
"other"
|
||||
|
||||
@@ -86,9 +86,21 @@ impl RpcHandler {
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|ch| {
|
||||
let capacity: i64 = ch.capacity.as_deref().and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
let local: i64 = ch.local_balance.as_deref().and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
let remote: i64 = ch.remote_balance.as_deref().and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
let capacity: i64 = ch
|
||||
.capacity
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let local: i64 = ch
|
||||
.local_balance
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let remote: i64 = ch
|
||||
.remote_balance
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
ChannelInfo {
|
||||
chan_id: ch.chan_id.unwrap_or_default(),
|
||||
remote_pubkey: ch.remote_pubkey.unwrap_or_default(),
|
||||
@@ -96,7 +108,11 @@ impl RpcHandler {
|
||||
local_balance: local,
|
||||
remote_balance: remote,
|
||||
active: ch.active.unwrap_or(false),
|
||||
status: if ch.active.unwrap_or(false) { "active".into() } else { "inactive".into() },
|
||||
status: if ch.active.unwrap_or(false) {
|
||||
"active".into()
|
||||
} else {
|
||||
"inactive".into()
|
||||
},
|
||||
channel_point: ch.channel_point.unwrap_or_default(),
|
||||
}
|
||||
})
|
||||
@@ -105,9 +121,21 @@ impl RpcHandler {
|
||||
let mut pending_channels: Vec<ChannelInfo> = Vec::new();
|
||||
for pch in pending_resp.pending_open_channels.unwrap_or_default() {
|
||||
if let Some(ch) = pch.channel {
|
||||
let capacity: i64 = ch.capacity.as_deref().and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
let local: i64 = ch.local_balance.as_deref().and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
let remote: i64 = ch.remote_balance.as_deref().and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
let capacity: i64 = ch
|
||||
.capacity
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let local: i64 = ch
|
||||
.local_balance
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let remote: i64 = ch
|
||||
.remote_balance
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
pending_channels.push(ChannelInfo {
|
||||
chan_id: String::new(),
|
||||
remote_pubkey: ch.remote_node_pub.unwrap_or_default(),
|
||||
@@ -136,25 +164,36 @@ impl RpcHandler {
|
||||
Ok(serde_json::to_value(result)?)
|
||||
}
|
||||
|
||||
pub(in crate::api::rpc) async fn handle_lnd_openchannel(&self, params: Option<serde_json::Value>) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_lnd_openchannel(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let pubkey = params.get("pubkey")
|
||||
let pubkey = params
|
||||
.get("pubkey")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'pubkey' parameter"))?;
|
||||
let amount = params.get("amount")
|
||||
let amount = params
|
||||
.get("amount")
|
||||
.and_then(|v| v.as_i64())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'amount' parameter (sats)"))?;
|
||||
|
||||
// Validate pubkey: must be 66-char hex (compressed secp256k1)
|
||||
if pubkey.len() != 66 || !pubkey.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err(anyhow::anyhow!("Invalid pubkey: must be 66-character hex string"));
|
||||
return Err(anyhow::anyhow!(
|
||||
"Invalid pubkey: must be 66-character hex string"
|
||||
));
|
||||
}
|
||||
|
||||
if amount < 20000 {
|
||||
return Err(anyhow::anyhow!("Channel amount must be at least 20,000 sats"));
|
||||
return Err(anyhow::anyhow!(
|
||||
"Channel amount must be at least 20,000 sats"
|
||||
));
|
||||
}
|
||||
if amount > 16_777_215 {
|
||||
return Err(anyhow::anyhow!("Channel amount exceeds maximum (16,777,215 sats)"));
|
||||
return Err(anyhow::anyhow!(
|
||||
"Channel amount exceeds maximum (16,777,215 sats)"
|
||||
));
|
||||
}
|
||||
|
||||
info!(peer = pubkey, amount = amount, "Opening Lightning channel");
|
||||
@@ -193,36 +232,61 @@ impl RpcHandler {
|
||||
.context("Failed to open channel")?;
|
||||
|
||||
let status = resp.status();
|
||||
let body: serde_json::Value = resp.json().await.context("Failed to parse open channel response")?;
|
||||
let body: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse open channel response")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let msg = body.get("message").and_then(|v| v.as_str()).unwrap_or("Unknown error");
|
||||
let msg = body
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return Err(anyhow::anyhow!("Failed to open channel: {}", msg));
|
||||
}
|
||||
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
pub(in crate::api::rpc) async fn handle_lnd_closechannel(&self, params: Option<serde_json::Value>) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_lnd_closechannel(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let channel_point = params.get("channel_point")
|
||||
let channel_point = params
|
||||
.get("channel_point")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'channel_point' parameter (txid:output_index)"))?;
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!("Missing 'channel_point' parameter (txid:output_index)")
|
||||
})?;
|
||||
|
||||
let parts: Vec<&str> = channel_point.split(':').collect();
|
||||
if parts.len() != 2 {
|
||||
return Err(anyhow::anyhow!("Invalid channel_point format. Expected 'txid:output_index'"));
|
||||
return Err(anyhow::anyhow!(
|
||||
"Invalid channel_point format. Expected 'txid:output_index'"
|
||||
));
|
||||
}
|
||||
// Validate txid is 64-char hex and output_index is numeric
|
||||
if parts[0].len() != 64 || !parts[0].chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err(anyhow::anyhow!("Invalid txid in channel_point: must be 64-character hex"));
|
||||
return Err(anyhow::anyhow!(
|
||||
"Invalid txid in channel_point: must be 64-character hex"
|
||||
));
|
||||
}
|
||||
if parts[1].parse::<u32>().is_err() {
|
||||
return Err(anyhow::anyhow!("Invalid output_index in channel_point: must be a number"));
|
||||
return Err(anyhow::anyhow!(
|
||||
"Invalid output_index in channel_point: must be a number"
|
||||
));
|
||||
}
|
||||
|
||||
let force = params.get("force").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
info!(channel_point = channel_point, force = force, "Closing Lightning channel");
|
||||
let force = params
|
||||
.get("force")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
info!(
|
||||
channel_point = channel_point,
|
||||
force = force,
|
||||
"Closing Lightning channel"
|
||||
);
|
||||
|
||||
let (client, macaroon_hex) = self.lnd_client().await?;
|
||||
|
||||
@@ -239,10 +303,16 @@ impl RpcHandler {
|
||||
.context("Failed to close channel")?;
|
||||
|
||||
let status = resp.status();
|
||||
let body: serde_json::Value = resp.json().await.context("Failed to parse close channel response")?;
|
||||
let body: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse close channel response")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let msg = body.get("message").and_then(|v| v.as_str()).unwrap_or("Unknown error");
|
||||
let msg = body
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return Err(anyhow::anyhow!("Failed to close channel: {}", msg));
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ use anyhow::{Context, Result};
|
||||
use base64::Engine;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{LndAmount, LndBalanceResponse};
|
||||
use super::{read_lnd_admin_macaroon, LndAmount, LndBalanceResponse};
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct LndInfo {
|
||||
@@ -34,12 +34,7 @@ struct LndChannelBalanceResponse {
|
||||
|
||||
impl RpcHandler {
|
||||
pub(in crate::api::rpc) async fn handle_lnd_getinfo(&self) -> Result<serde_json::Value> {
|
||||
let macaroon_path =
|
||||
"/var/lib/archipelago/lnd/data/chain/bitcoin/mainnet/admin.macaroon";
|
||||
|
||||
let macaroon_bytes = tokio::fs::read(macaroon_path)
|
||||
.await
|
||||
.context("Failed to read LND admin macaroon — is LND installed?")?;
|
||||
let macaroon_bytes = read_lnd_admin_macaroon().await?;
|
||||
let macaroon_hex = hex::encode(&macaroon_bytes);
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
@@ -115,8 +110,6 @@ impl RpcHandler {
|
||||
/// for building lndconnect:// URIs in the frontend.
|
||||
pub(crate) async fn handle_lnd_connect_info(&self) -> Result<serde_json::Value> {
|
||||
let cert_path = "/var/lib/archipelago/lnd/tls.cert";
|
||||
let macaroon_path =
|
||||
"/var/lib/archipelago/lnd/data/chain/bitcoin/mainnet/admin.macaroon";
|
||||
|
||||
// Read and encode TLS cert (PEM -> DER -> base64url)
|
||||
let cert_pem = tokio::fs::read_to_string(cert_path)
|
||||
@@ -132,9 +125,7 @@ impl RpcHandler {
|
||||
let cert_b64url = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&cert_der);
|
||||
|
||||
// Read and encode macaroon (binary -> base64url)
|
||||
let macaroon_bytes = tokio::fs::read(macaroon_path)
|
||||
.await
|
||||
.context("Failed to read LND admin macaroon")?;
|
||||
let macaroon_bytes = read_lnd_admin_macaroon().await?;
|
||||
let macaroon_b64url =
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&macaroon_bytes);
|
||||
|
||||
@@ -182,11 +173,10 @@ impl RpcHandler {
|
||||
|
||||
/// lnd.export-channel-backup -- Export all channel static backups (SCB).
|
||||
/// Returns base64-encoded multi-channel backup that can restore channels on a new node.
|
||||
pub(in crate::api::rpc) async fn handle_lnd_export_channel_backup(&self) -> Result<serde_json::Value> {
|
||||
let macaroon_path = "/var/lib/archipelago/lnd/data/chain/bitcoin/mainnet/admin.macaroon";
|
||||
let macaroon_bytes = tokio::fs::read(macaroon_path)
|
||||
.await
|
||||
.context("Failed to read LND admin macaroon")?;
|
||||
pub(in crate::api::rpc) async fn handle_lnd_export_channel_backup(
|
||||
&self,
|
||||
) -> Result<serde_json::Value> {
|
||||
let macaroon_bytes = read_lnd_admin_macaroon().await?;
|
||||
let macaroon_hex = hex::encode(&macaroon_bytes);
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
|
||||
@@ -4,7 +4,11 @@ mod payments;
|
||||
mod wallet;
|
||||
|
||||
use crate::api::rpc::RpcHandler;
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
|
||||
/// Canonical on-host path for LND's admin macaroon.
|
||||
pub(crate) const LND_ADMIN_MACAROON_PATH: &str =
|
||||
"/var/lib/archipelago/lnd/data/chain/bitcoin/mainnet/admin.macaroon";
|
||||
|
||||
// Shared LND response types used by multiple submodules
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
@@ -17,16 +21,45 @@ pub(super) struct LndAmount {
|
||||
pub sat: Option<String>,
|
||||
}
|
||||
|
||||
/// Read LND's admin macaroon from disk.
|
||||
///
|
||||
/// The macaroon lives inside LND's container data dir and is owned by a
|
||||
/// rootless-podman subordinate UID (typically 100000), mode 640. The
|
||||
/// archipelago server runs as UID 1000 and therefore cannot read it
|
||||
/// directly. We first try a plain read (works if an operator has relaxed
|
||||
/// permissions), then fall back to `sudo cat` — mirroring the pattern
|
||||
/// already used for Tor hidden-service hostnames.
|
||||
pub(crate) async fn read_lnd_admin_macaroon() -> Result<Vec<u8>> {
|
||||
match tokio::fs::read(LND_ADMIN_MACAROON_PATH).await {
|
||||
Ok(bytes) => Ok(bytes),
|
||||
Err(direct_err) => {
|
||||
let output = tokio::process::Command::new("sudo")
|
||||
.args(["-n", "cat", LND_ADMIN_MACAROON_PATH])
|
||||
.output()
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to read LND admin macaroon (direct: {direct_err}); sudo fallback also failed"
|
||||
)
|
||||
})?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(anyhow!(
|
||||
"Failed to read LND admin macaroon — is LND installed? (direct: {direct_err}; sudo: {})",
|
||||
stderr.trim()
|
||||
));
|
||||
}
|
||||
Ok(output.stdout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RpcHandler {
|
||||
/// Helper: create an authenticated LND REST client.
|
||||
/// Returns an HTTP client configured for LND's self-signed TLS and the
|
||||
/// hex-encoded admin macaroon for request headers.
|
||||
pub(crate) async fn lnd_client(&self) -> Result<(reqwest::Client, String)> {
|
||||
let macaroon_path =
|
||||
"/var/lib/archipelago/lnd/data/chain/bitcoin/mainnet/admin.macaroon";
|
||||
let macaroon_bytes = tokio::fs::read(macaroon_path)
|
||||
.await
|
||||
.context("Failed to read LND admin macaroon — is LND installed?")?;
|
||||
let macaroon_bytes = read_lnd_admin_macaroon().await?;
|
||||
let macaroon_hex = hex::encode(&macaroon_bytes);
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(15))
|
||||
|
||||
@@ -4,9 +4,13 @@ use tracing::info;
|
||||
|
||||
impl RpcHandler {
|
||||
/// Pay a Lightning invoice.
|
||||
pub(in crate::api::rpc) async fn handle_lnd_payinvoice(&self, params: Option<serde_json::Value>) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_lnd_payinvoice(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let payment_request = params.get("payment_request")
|
||||
let payment_request = params
|
||||
.get("payment_request")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'payment_request' parameter"))?;
|
||||
|
||||
@@ -15,8 +19,11 @@ impl RpcHandler {
|
||||
return Err(anyhow::anyhow!("Invalid payment request length"));
|
||||
}
|
||||
let lower = payment_request.to_lowercase();
|
||||
if !lower.starts_with("lnbc") && !lower.starts_with("lntb") && !lower.starts_with("lnbcrt") {
|
||||
return Err(anyhow::anyhow!("Invalid payment request: must be a Lightning invoice (lnbc...)"));
|
||||
if !lower.starts_with("lnbc") && !lower.starts_with("lntb") && !lower.starts_with("lnbcrt")
|
||||
{
|
||||
return Err(anyhow::anyhow!(
|
||||
"Invalid payment request: must be a Lightning invoice (lnbc...)"
|
||||
));
|
||||
}
|
||||
|
||||
info!("Paying Lightning invoice");
|
||||
@@ -36,26 +43,36 @@ impl RpcHandler {
|
||||
.context("Failed to pay invoice")?;
|
||||
|
||||
let status = resp.status();
|
||||
let body: serde_json::Value = resp.json().await
|
||||
let body: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse payment response")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let msg = body.get("message").and_then(|v| v.as_str()).unwrap_or("Unknown error");
|
||||
let msg = body
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return Err(anyhow::anyhow!("Payment failed: {}", msg));
|
||||
}
|
||||
|
||||
let payment_error = body.get("payment_error").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let payment_error = body
|
||||
.get("payment_error")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
if !payment_error.is_empty() {
|
||||
return Err(anyhow::anyhow!("Payment failed: {}", payment_error));
|
||||
}
|
||||
|
||||
let amount_sat = body.get("payment_route")
|
||||
let amount_sat = body
|
||||
.get("payment_route")
|
||||
.and_then(|r| r.get("total_amt"))
|
||||
.and_then(|v| v.as_str())
|
||||
.and_then(|s| s.parse::<i64>().ok())
|
||||
.unwrap_or(0);
|
||||
|
||||
let payment_hash = body.get("payment_hash")
|
||||
let payment_hash = body
|
||||
.get("payment_hash")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
@@ -68,7 +85,9 @@ impl RpcHandler {
|
||||
|
||||
/// List on-chain transactions from LND.
|
||||
/// Returns all transactions, with incoming (amount > 0) flagged.
|
||||
pub(in crate::api::rpc) async fn handle_lnd_gettransactions(&self) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_lnd_gettransactions(
|
||||
&self,
|
||||
) -> Result<serde_json::Value> {
|
||||
let (client, macaroon_hex) = self.lnd_client().await?;
|
||||
|
||||
let resp = client
|
||||
@@ -148,10 +167,7 @@ impl RpcHandler {
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
let block_height: i64 = tx
|
||||
.get("block_height")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(0);
|
||||
let block_height: i64 = tx.get("block_height").and_then(|v| v.as_i64()).unwrap_or(0);
|
||||
|
||||
let direction = if amount > 0 { "incoming" } else { "outgoing" };
|
||||
|
||||
|
||||
@@ -16,10 +16,13 @@ impl RpcHandler {
|
||||
.await
|
||||
.context("LND REST connection failed")?;
|
||||
|
||||
let body: serde_json::Value = resp.json().await
|
||||
let body: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse newaddress response")?;
|
||||
|
||||
let address = body.get("address")
|
||||
let address = body
|
||||
.get("address")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
@@ -28,17 +31,24 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
/// Send on-chain Bitcoin to an address.
|
||||
pub(in crate::api::rpc) async fn handle_lnd_sendcoins(&self, params: Option<serde_json::Value>) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_lnd_sendcoins(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let addr = params.get("addr")
|
||||
let addr = params
|
||||
.get("addr")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'addr' parameter"))?;
|
||||
let amount = params.get("amount")
|
||||
let amount = params
|
||||
.get("amount")
|
||||
.and_then(|v| v.as_i64())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'amount' parameter (sats)"))?;
|
||||
|
||||
if amount < 546 {
|
||||
return Err(anyhow::anyhow!("Amount must be at least 546 sats (dust limit)"));
|
||||
return Err(anyhow::anyhow!(
|
||||
"Amount must be at least 546 sats (dust limit)"
|
||||
));
|
||||
}
|
||||
if amount > 21_000_000 * 100_000_000 {
|
||||
return Err(anyhow::anyhow!("Amount exceeds maximum Bitcoin supply"));
|
||||
@@ -67,27 +77,35 @@ impl RpcHandler {
|
||||
.context("Failed to send on-chain transaction")?;
|
||||
|
||||
let status = resp.status();
|
||||
let body: serde_json::Value = resp.json().await
|
||||
.context("Failed to parse send response")?;
|
||||
let body: serde_json::Value = resp.json().await.context("Failed to parse send response")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let msg = body.get("message").and_then(|v| v.as_str()).unwrap_or("Unknown error");
|
||||
let msg = body
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return Err(anyhow::anyhow!("Failed to send: {}", msg));
|
||||
}
|
||||
|
||||
let txid = body.get("txid").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
||||
let txid = body
|
||||
.get("txid")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
Ok(serde_json::json!({ "txid": txid }))
|
||||
}
|
||||
|
||||
/// Create a Lightning invoice.
|
||||
pub(in crate::api::rpc) async fn handle_lnd_createinvoice(&self, params: Option<serde_json::Value>) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_lnd_createinvoice(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let amount_sats = params.get("amount_sats")
|
||||
let amount_sats = params
|
||||
.get("amount_sats")
|
||||
.and_then(|v| v.as_i64())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'amount_sats' parameter"))?;
|
||||
let memo = params.get("memo")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let memo = params.get("memo").and_then(|v| v.as_str()).unwrap_or("");
|
||||
|
||||
if amount_sats < 0 {
|
||||
return Err(anyhow::anyhow!("Amount must be non-negative"));
|
||||
@@ -119,15 +137,21 @@ impl RpcHandler {
|
||||
.context("Failed to create invoice")?;
|
||||
|
||||
let status = resp.status();
|
||||
let body: serde_json::Value = resp.json().await
|
||||
let body: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse invoice response")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let msg = body.get("message").and_then(|v| v.as_str()).unwrap_or("Unknown error");
|
||||
let msg = body
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return Err(anyhow::anyhow!("Failed to create invoice: {}", msg));
|
||||
}
|
||||
|
||||
let payment_request = body.get("payment_request")
|
||||
let payment_request = body
|
||||
.get("payment_request")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
@@ -140,12 +164,18 @@ impl RpcHandler {
|
||||
|
||||
/// Create an unsigned PSBT for hardware wallet signing.
|
||||
/// Uses LND's WalletKit.FundPsbt to select UTXOs and create a PSBT template.
|
||||
pub(in crate::api::rpc) async fn handle_lnd_create_psbt(&self, params: Option<serde_json::Value>) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_lnd_create_psbt(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
|
||||
let outputs = params.get("outputs")
|
||||
let outputs = params
|
||||
.get("outputs")
|
||||
.and_then(|v| v.as_array())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'outputs' array (each: address + amount_sats)"))?;
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!("Missing 'outputs' array (each: address + amount_sats)")
|
||||
})?;
|
||||
|
||||
if outputs.is_empty() {
|
||||
return Err(anyhow::anyhow!("outputs must not be empty"));
|
||||
@@ -155,28 +185,40 @@ impl RpcHandler {
|
||||
let mut lnd_outputs: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
|
||||
let mut total_amount: i64 = 0;
|
||||
for output in outputs {
|
||||
let addr = output.get("address")
|
||||
let addr = output
|
||||
.get("address")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Each output must have an 'address'"))?;
|
||||
// Validate Bitcoin address format
|
||||
if addr.len() < 14 || addr.len() > 90 || !addr.chars().all(|c| c.is_ascii_alphanumeric()) {
|
||||
if addr.len() < 14
|
||||
|| addr.len() > 90
|
||||
|| !addr.chars().all(|c| c.is_ascii_alphanumeric())
|
||||
{
|
||||
return Err(anyhow::anyhow!("Invalid Bitcoin address format in output"));
|
||||
}
|
||||
let amount = output.get("amount_sats")
|
||||
let amount = output
|
||||
.get("amount_sats")
|
||||
.and_then(|v| v.as_i64())
|
||||
.ok_or_else(|| anyhow::anyhow!("Each output must have 'amount_sats'"))?;
|
||||
if amount < 546 {
|
||||
return Err(anyhow::anyhow!("Amount must be at least 546 sats (dust limit)"));
|
||||
return Err(anyhow::anyhow!(
|
||||
"Amount must be at least 546 sats (dust limit)"
|
||||
));
|
||||
}
|
||||
lnd_outputs.insert(addr.to_string(), serde_json::json!(amount));
|
||||
total_amount += amount;
|
||||
}
|
||||
|
||||
let sat_per_vbyte = params.get("fee_rate_sat_per_vbyte")
|
||||
let sat_per_vbyte = params
|
||||
.get("fee_rate_sat_per_vbyte")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(10);
|
||||
|
||||
info!(total_amount = total_amount, fee_rate = sat_per_vbyte, "Creating PSBT for hardware wallet signing");
|
||||
info!(
|
||||
total_amount = total_amount,
|
||||
fee_rate = sat_per_vbyte,
|
||||
"Creating PSBT for hardware wallet signing"
|
||||
);
|
||||
|
||||
let (client, macaroon_hex) = self.lnd_client().await?;
|
||||
|
||||
@@ -197,20 +239,24 @@ impl RpcHandler {
|
||||
.context("Failed to create PSBT via LND")?;
|
||||
|
||||
let status = resp.status();
|
||||
let body: serde_json::Value = resp.json().await
|
||||
.context("Failed to parse PSBT response")?;
|
||||
let body: serde_json::Value = resp.json().await.context("Failed to parse PSBT response")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let msg = body.get("message").and_then(|v| v.as_str()).unwrap_or("Unknown error");
|
||||
let msg = body
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return Err(anyhow::anyhow!("Failed to create PSBT: {}", msg));
|
||||
}
|
||||
|
||||
let funded_psbt = body.get("funded_psbt")
|
||||
let funded_psbt = body
|
||||
.get("funded_psbt")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
let change_output_index = body.get("change_output_index")
|
||||
let change_output_index = body
|
||||
.get("change_output_index")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(-1);
|
||||
|
||||
@@ -224,9 +270,13 @@ impl RpcHandler {
|
||||
|
||||
/// Finalize a signed PSBT and broadcast the transaction.
|
||||
/// Takes a PSBT that has been signed by a hardware wallet.
|
||||
pub(in crate::api::rpc) async fn handle_lnd_finalize_psbt(&self, params: Option<serde_json::Value>) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_lnd_finalize_psbt(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let signed_psbt = params.get("signed_psbt_base64")
|
||||
let signed_psbt = params
|
||||
.get("signed_psbt_base64")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'signed_psbt_base64'"))?;
|
||||
|
||||
@@ -247,15 +297,21 @@ impl RpcHandler {
|
||||
.context("Failed to finalize PSBT via LND")?;
|
||||
|
||||
let status = resp.status();
|
||||
let body: serde_json::Value = resp.json().await
|
||||
let body: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse finalize response")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let msg = body.get("message").and_then(|v| v.as_str()).unwrap_or("Unknown error");
|
||||
let msg = body
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return Err(anyhow::anyhow!("Failed to finalize PSBT: {}", msg));
|
||||
}
|
||||
|
||||
let raw_final_tx = body.get("raw_final_tx")
|
||||
let raw_final_tx = body
|
||||
.get("raw_final_tx")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
@@ -274,11 +330,16 @@ impl RpcHandler {
|
||||
.context("Failed to broadcast transaction")?;
|
||||
|
||||
let pub_status = pub_resp.status();
|
||||
let pub_body: serde_json::Value = pub_resp.json().await
|
||||
let pub_body: serde_json::Value = pub_resp
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse broadcast response")?;
|
||||
|
||||
if !pub_status.is_success() {
|
||||
let msg = pub_body.get("message").and_then(|v| v.as_str()).unwrap_or("Unknown error");
|
||||
let msg = pub_body
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return Err(anyhow::anyhow!("Transaction broadcast failed: {}", msg));
|
||||
}
|
||||
|
||||
@@ -291,13 +352,18 @@ impl RpcHandler {
|
||||
/// Create a signed raw transaction WITHOUT broadcasting.
|
||||
/// Used for mesh relay: create the TX locally, then relay the hex to an
|
||||
/// internet-connected peer who broadcasts it.
|
||||
pub(in crate::api::rpc) async fn handle_lnd_create_raw_tx(&self, params: Option<serde_json::Value>) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_lnd_create_raw_tx(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
|
||||
let addr = params.get("addr")
|
||||
let addr = params
|
||||
.get("addr")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'addr'"))?;
|
||||
let amount_sats = params.get("amount_sats")
|
||||
let amount_sats = params
|
||||
.get("amount_sats")
|
||||
.and_then(|v| v.as_u64())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'amount_sats'"))?;
|
||||
|
||||
@@ -329,15 +395,18 @@ impl RpcHandler {
|
||||
.context("Failed to fund PSBT via LND")?;
|
||||
|
||||
let status = resp.status();
|
||||
let body: serde_json::Value = resp.json().await
|
||||
.context("Failed to parse fund response")?;
|
||||
let body: serde_json::Value = resp.json().await.context("Failed to parse fund response")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let msg = body.get("message").and_then(|v| v.as_str()).unwrap_or("Unknown error");
|
||||
let msg = body
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return Err(anyhow::anyhow!("Failed to create TX: {}", msg));
|
||||
}
|
||||
|
||||
let funded_psbt = body.get("funded_psbt")
|
||||
let funded_psbt = body
|
||||
.get("funded_psbt")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("No funded_psbt in response"))?;
|
||||
|
||||
@@ -355,16 +424,22 @@ impl RpcHandler {
|
||||
.context("Failed to finalize PSBT")?;
|
||||
|
||||
let status = resp.status();
|
||||
let body: serde_json::Value = resp.json().await
|
||||
let body: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse finalize response")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let msg = body.get("message").and_then(|v| v.as_str()).unwrap_or("Unknown error");
|
||||
let msg = body
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return Err(anyhow::anyhow!("Failed to sign TX: {}", msg));
|
||||
}
|
||||
|
||||
// raw_final_tx from LND is base64-encoded -- decode to hex for Bitcoin RPC
|
||||
let raw_final_tx_b64 = body.get("raw_final_tx")
|
||||
let raw_final_tx_b64 = body
|
||||
.get("raw_final_tx")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("No raw_final_tx in response"))?;
|
||||
|
||||
@@ -373,7 +448,12 @@ impl RpcHandler {
|
||||
.context("Failed to decode raw_final_tx base64")?;
|
||||
let raw_tx_hex = hex::encode(&tx_bytes);
|
||||
|
||||
info!(addr, amount_sats, tx_len = raw_tx_hex.len(), "Created raw TX for mesh relay (NOT broadcast)");
|
||||
info!(
|
||||
addr,
|
||||
amount_sats,
|
||||
tx_len = raw_tx_hex.len(),
|
||||
"Created raw TX for mesh relay (NOT broadcast)"
|
||||
);
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"raw_tx_hex": raw_tx_hex,
|
||||
@@ -391,28 +471,34 @@ impl RpcHandler {
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let password = params.get("password")
|
||||
let password = params
|
||||
.get("password")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'password' for seed access"))?;
|
||||
let wallet_password = params.get("wallet_password")
|
||||
let wallet_password = params
|
||||
.get("wallet_password")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'wallet_password' for LND"))?;
|
||||
|
||||
// Verify user password before granting seed access.
|
||||
self.auth_manager.verify_password(password).await
|
||||
self.auth_manager
|
||||
.verify_password(password)
|
||||
.await
|
||||
.context("Password verification failed")?;
|
||||
|
||||
// Load encrypted seed from disk.
|
||||
let mnemonic = crate::seed::load_seed_encrypted(&self.config.data_dir, password).await
|
||||
let mnemonic = crate::seed::load_seed_encrypted(&self.config.data_dir, password)
|
||||
.await
|
||||
.context("Failed to load encrypted seed. Was a seed phrase saved during onboarding?")?;
|
||||
let seed = crate::seed::MasterSeed::from_mnemonic(&mnemonic);
|
||||
|
||||
// Derive 16 bytes of LND entropy.
|
||||
let mut entropy = crate::seed::derive_lnd_entropy(&seed)?;
|
||||
let entropy_b64 = base64::engine::general_purpose::STANDARD.encode(&entropy);
|
||||
let entropy_b64 = base64::engine::general_purpose::STANDARD.encode(entropy);
|
||||
entropy.zeroize();
|
||||
|
||||
let wallet_password_b64 = base64::engine::general_purpose::STANDARD.encode(wallet_password.as_bytes());
|
||||
let wallet_password_b64 =
|
||||
base64::engine::general_purpose::STANDARD.encode(wallet_password.as_bytes());
|
||||
|
||||
// Call LND REST API to initialize wallet with derived entropy.
|
||||
// LND must be running but NOT yet initialized (no existing wallet).
|
||||
@@ -435,11 +521,16 @@ impl RpcHandler {
|
||||
.context("LND initwallet request failed — is LND running and uninitialized?")?;
|
||||
|
||||
let status = resp.status();
|
||||
let body: serde_json::Value = resp.json().await
|
||||
let body: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse initwallet response")?;
|
||||
|
||||
if !status.is_success() {
|
||||
let msg = body.get("message").and_then(|v| v.as_str()).unwrap_or("Unknown error");
|
||||
let msg = body
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return Err(anyhow::anyhow!("LND wallet init failed: {}", msg));
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,9 @@ impl RpcHandler {
|
||||
.collect();
|
||||
|
||||
// Load federated DIDs for trust scoring
|
||||
let fed_nodes = federation::load_nodes(&self.config.data_dir).await.unwrap_or_default();
|
||||
let fed_nodes = federation::load_nodes(&self.config.data_dir)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let federated_dids: Vec<String> = fed_nodes.iter().map(|n| n.did.clone()).collect();
|
||||
|
||||
let tor_proxy = std::env::var("ARCHIPELAGO_NOSTR_TOR_PROXY").ok();
|
||||
@@ -42,8 +44,8 @@ impl RpcHandler {
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let manifest: marketplace::AppManifest =
|
||||
serde_json::from_value(params).map_err(|e| anyhow::anyhow!("Invalid manifest: {}", e))?;
|
||||
let manifest: marketplace::AppManifest = serde_json::from_value(params)
|
||||
.map_err(|e| anyhow::anyhow!("Invalid manifest: {}", e))?;
|
||||
|
||||
// Validate before publishing
|
||||
let issues = marketplace::validate_manifest(&manifest);
|
||||
@@ -112,8 +114,8 @@ impl RpcHandler {
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let manifest: marketplace::AppManifest =
|
||||
serde_json::from_value(params).map_err(|e| anyhow::anyhow!("Invalid manifest: {}", e))?;
|
||||
let manifest: marketplace::AppManifest = serde_json::from_value(params)
|
||||
.map_err(|e| anyhow::anyhow!("Invalid manifest: {}", e))?;
|
||||
|
||||
let issues = marketplace::validate_manifest(&manifest);
|
||||
let (trust_score, trust_tier) = marketplace::calculate_trust_score(&manifest, 0, &[]);
|
||||
@@ -147,9 +149,7 @@ impl RpcHandler {
|
||||
"amount": amount_sats,
|
||||
"memo": format!("Archipelago app: {}", app_id),
|
||||
});
|
||||
let invoice_result = self
|
||||
.handle_lnd_createinvoice(Some(invoice_params))
|
||||
.await?;
|
||||
let invoice_result = self.handle_lnd_createinvoice(Some(invoice_params)).await?;
|
||||
|
||||
let payment_request = invoice_result
|
||||
.get("payment_request")
|
||||
@@ -181,15 +181,14 @@ impl RpcHandler {
|
||||
|
||||
// Validate r_hash is hex-encoded (LND payment hashes are 32 bytes = 64 hex chars)
|
||||
if r_hash.len() != 64 || !r_hash.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err(anyhow::anyhow!("Invalid r_hash: must be 64-character hex string"));
|
||||
return Err(anyhow::anyhow!(
|
||||
"Invalid r_hash: must be 64-character hex string"
|
||||
));
|
||||
}
|
||||
|
||||
let (client, macaroon_hex) = self.lnd_client().await?;
|
||||
|
||||
let url = format!(
|
||||
"https://127.0.0.1:8080/v1/invoice/{}",
|
||||
r_hash
|
||||
);
|
||||
let url = format!("https://127.0.0.1:8080/v1/invoice/{}", r_hash);
|
||||
let paid = match client
|
||||
.get(&url)
|
||||
.header("Grpc-Metadata-macaroon", &macaroon_hex)
|
||||
@@ -198,7 +197,9 @@ impl RpcHandler {
|
||||
{
|
||||
Ok(r) if r.status().is_success() => {
|
||||
let body: serde_json::Value = r.json().await.unwrap_or_default();
|
||||
body.get("settled").and_then(|v| v.as_bool()).unwrap_or(false)
|
||||
body.get("settled")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
|
||||
@@ -13,9 +13,7 @@ impl RpcHandler {
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing tx_hex"))?;
|
||||
|
||||
let relay_mode = params["relay_mode"]
|
||||
.as_str()
|
||||
.unwrap_or("archy");
|
||||
let relay_mode = params["relay_mode"].as_str().unwrap_or("archy");
|
||||
|
||||
if tx_hex.len() < 20 || tx_hex.len() > 200_000 {
|
||||
anyhow::bail!("Invalid tx_hex length");
|
||||
@@ -26,11 +24,14 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
let service = self.mesh_service.read().await;
|
||||
let svc = service.as_ref()
|
||||
let svc = service
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Mesh service not running"))?;
|
||||
|
||||
let request_id = chrono::Utc::now().timestamp() as u64;
|
||||
svc.relay_tracker.track_tx_relay(request_id, svc.our_did()).await;
|
||||
svc.relay_tracker
|
||||
.track_tx_relay(request_id, svc.our_did())
|
||||
.await;
|
||||
|
||||
let wire = crate::mesh::bitcoin_relay::build_tx_relay_request(tx_hex, request_id)?;
|
||||
|
||||
@@ -44,7 +45,9 @@ impl RpcHandler {
|
||||
|
||||
// Encrypt with first available Archy peer's shared secret
|
||||
// (any Archy node that receives it can try decrypting)
|
||||
let payload = shared_secrets.values().next()
|
||||
let payload = shared_secrets
|
||||
.values()
|
||||
.next()
|
||||
.and_then(|secret| {
|
||||
crate::mesh::crypto::encrypt(secret, &wire).ok().map(|ct| {
|
||||
let mut encrypted = Vec::with_capacity(1 + ct.len());
|
||||
@@ -60,32 +63,41 @@ impl RpcHandler {
|
||||
use base64::Engine;
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(&payload);
|
||||
let _ = shared_state
|
||||
.cmd_tx
|
||||
.send(crate::mesh::listener::MeshCommand::BroadcastChannel {
|
||||
.send_cmd(crate::mesh::listener::MeshCommand::BroadcastChannel {
|
||||
channel: 0,
|
||||
payload: b64.into_bytes(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
info!(request_id, tx_len = tx_hex.len(), "TX relay broadcast on mesh channel 0 (encrypted)");
|
||||
info!(
|
||||
request_id,
|
||||
tx_len = tx_hex.len(),
|
||||
"TX relay broadcast on mesh channel 0 (encrypted)"
|
||||
);
|
||||
} else {
|
||||
// Archy mode: E2E encrypted per-peer, direct to known Archy nodes
|
||||
let peers = svc.peers().await;
|
||||
let shared_state = svc.shared_state();
|
||||
let shared_secrets = shared_state.shared_secrets.read().await;
|
||||
for peer in &peers {
|
||||
if !peer.advert_name.starts_with("Archy-") { continue; }
|
||||
if !peer.advert_name.starts_with("Archy-") {
|
||||
continue;
|
||||
}
|
||||
if let Some(ref pk) = peer.pubkey_hex {
|
||||
if let Ok(pk_bytes) = hex::decode(pk) {
|
||||
if pk_bytes.len() >= 6 {
|
||||
let mut prefix = [0u8; 6];
|
||||
prefix.copy_from_slice(&pk_bytes[..6]);
|
||||
|
||||
let payload = if let Some(secret) = shared_secrets.get(&peer.contact_id) {
|
||||
let payload = if let Some(secret) = shared_secrets.get(&peer.contact_id)
|
||||
{
|
||||
match crate::mesh::crypto::encrypt(secret, &wire) {
|
||||
Ok(ciphertext) => {
|
||||
let mut encrypted = Vec::with_capacity(1 + ciphertext.len());
|
||||
encrypted.push(crate::mesh::message_types::ENCRYPTED_TYPED_MARKER);
|
||||
let mut encrypted =
|
||||
Vec::with_capacity(1 + ciphertext.len());
|
||||
encrypted.push(
|
||||
crate::mesh::message_types::ENCRYPTED_TYPED_MARKER,
|
||||
);
|
||||
encrypted.extend_from_slice(&ciphertext);
|
||||
encrypted
|
||||
}
|
||||
@@ -95,9 +107,9 @@ impl RpcHandler {
|
||||
wire.clone()
|
||||
};
|
||||
|
||||
let _ = svc.shared_state()
|
||||
.cmd_tx
|
||||
.send(crate::mesh::listener::MeshCommand::SendRaw {
|
||||
let _ = svc
|
||||
.shared_state()
|
||||
.send_cmd(crate::mesh::listener::MeshCommand::SendRaw {
|
||||
dest_pubkey_prefix: prefix,
|
||||
payload,
|
||||
})
|
||||
@@ -108,7 +120,12 @@ impl RpcHandler {
|
||||
}
|
||||
}
|
||||
drop(shared_secrets);
|
||||
info!(request_id, tx_len = tx_hex.len(), archy_peers = sent_count, "TX relay sent to Archy peers (E2E encrypted)");
|
||||
info!(
|
||||
request_id,
|
||||
tx_len = tx_hex.len(),
|
||||
archy_peers = sent_count,
|
||||
"TX relay sent to Archy peers (E2E encrypted)"
|
||||
);
|
||||
}
|
||||
Ok(serde_json::json!({
|
||||
"request_id": request_id,
|
||||
@@ -128,7 +145,8 @@ impl RpcHandler {
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing request_id"))?;
|
||||
|
||||
let service = self.mesh_service.read().await;
|
||||
let svc = service.as_ref()
|
||||
let svc = service
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Mesh service not running"))?;
|
||||
|
||||
// Check completed results first
|
||||
@@ -169,7 +187,8 @@ impl RpcHandler {
|
||||
.unwrap_or(10) as usize;
|
||||
|
||||
let service = self.mesh_service.read().await;
|
||||
let svc = service.as_ref()
|
||||
let svc = service
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Mesh service not running"))?;
|
||||
|
||||
let headers = svc.block_header_cache.recent_headers(count).await;
|
||||
@@ -206,14 +225,19 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
let service = self.mesh_service.read().await;
|
||||
let svc = service.as_ref()
|
||||
let svc = service
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Mesh service not running"))?;
|
||||
|
||||
let request_id = chrono::Utc::now().timestamp() as u64;
|
||||
svc.relay_tracker.track_lightning_relay(request_id, svc.our_did()).await;
|
||||
svc.relay_tracker
|
||||
.track_lightning_relay(request_id, svc.our_did())
|
||||
.await;
|
||||
|
||||
let wire = crate::mesh::bitcoin_relay::build_lightning_relay_request(
|
||||
bolt11, amount_sats, request_id,
|
||||
bolt11,
|
||||
amount_sats,
|
||||
request_id,
|
||||
)?;
|
||||
|
||||
// Send to Archipelago peers — E2E encrypted per-peer
|
||||
@@ -222,7 +246,9 @@ impl RpcHandler {
|
||||
let shared_secrets = shared_state.shared_secrets.read().await;
|
||||
let mut sent_count = 0u32;
|
||||
for peer in &peers {
|
||||
if !peer.advert_name.starts_with("Archy-") { continue; }
|
||||
if !peer.advert_name.starts_with("Archy-") {
|
||||
continue;
|
||||
}
|
||||
if let Some(ref pk) = peer.pubkey_hex {
|
||||
if let Ok(pk_bytes) = hex::decode(pk) {
|
||||
if pk_bytes.len() >= 6 {
|
||||
@@ -233,7 +259,8 @@ impl RpcHandler {
|
||||
match crate::mesh::crypto::encrypt(secret, &wire) {
|
||||
Ok(ciphertext) => {
|
||||
let mut encrypted = Vec::with_capacity(1 + ciphertext.len());
|
||||
encrypted.push(crate::mesh::message_types::ENCRYPTED_TYPED_MARKER);
|
||||
encrypted
|
||||
.push(crate::mesh::message_types::ENCRYPTED_TYPED_MARKER);
|
||||
encrypted.extend_from_slice(&ciphertext);
|
||||
encrypted
|
||||
}
|
||||
@@ -243,9 +270,9 @@ impl RpcHandler {
|
||||
wire.clone()
|
||||
};
|
||||
|
||||
let _ = svc.shared_state()
|
||||
.cmd_tx
|
||||
.send(crate::mesh::listener::MeshCommand::SendRaw {
|
||||
let _ = svc
|
||||
.shared_state()
|
||||
.send_cmd(crate::mesh::listener::MeshCommand::SendRaw {
|
||||
dest_pubkey_prefix: prefix,
|
||||
payload,
|
||||
})
|
||||
@@ -257,7 +284,12 @@ impl RpcHandler {
|
||||
}
|
||||
drop(shared_secrets);
|
||||
|
||||
info!(request_id, amount_sats, archy_peers = sent_count, "Lightning relay sent (E2E encrypted)");
|
||||
info!(
|
||||
request_id,
|
||||
amount_sats,
|
||||
archy_peers = sent_count,
|
||||
"Lightning relay sent (E2E encrypted)"
|
||||
);
|
||||
Ok(serde_json::json!({
|
||||
"request_id": request_id,
|
||||
"queued": true,
|
||||
|
||||
@@ -40,6 +40,39 @@ impl RpcHandler {
|
||||
}))
|
||||
}
|
||||
|
||||
/// mesh.send-channel — Send a text message to a mesh channel (broadcast).
|
||||
pub(in crate::api::rpc) async fn handle_mesh_send_channel(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
|
||||
let channel = params.get("channel").and_then(|v| v.as_u64()).unwrap_or(0) as u8;
|
||||
|
||||
let message = params
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing message"))?;
|
||||
|
||||
if message.is_empty() {
|
||||
anyhow::bail!("Message cannot be empty");
|
||||
}
|
||||
|
||||
let service = self.mesh_service.read().await;
|
||||
let svc = service
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Mesh service not running. Enable mesh first."))?;
|
||||
|
||||
let msg = svc.send_channel_message(channel, message).await?;
|
||||
info!(channel, "Sent mesh channel message");
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"sent": true,
|
||||
"message_id": msg.id,
|
||||
"channel": channel,
|
||||
}))
|
||||
}
|
||||
|
||||
/// mesh.broadcast — Broadcast our node identity over mesh.
|
||||
pub(in crate::api::rpc) async fn handle_mesh_broadcast(&self) -> Result<serde_json::Value> {
|
||||
let service = self.mesh_service.read().await;
|
||||
|
||||
@@ -36,9 +36,12 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
/// mesh.deadman-status — Get dead man's switch status.
|
||||
pub(in crate::api::rpc) async fn handle_mesh_deadman_status(&self) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_mesh_deadman_status(
|
||||
&self,
|
||||
) -> Result<serde_json::Value> {
|
||||
let service = self.mesh_service.read().await;
|
||||
let svc = service.as_ref()
|
||||
let svc = service
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Mesh service not running"))?;
|
||||
|
||||
let status = svc.dead_man_switch.status().await;
|
||||
@@ -53,7 +56,8 @@ impl RpcHandler {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
|
||||
let service = self.mesh_service.read().await;
|
||||
let svc = service.as_ref()
|
||||
let svc = service
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Mesh service not running"))?;
|
||||
|
||||
let mut config = svc.dead_man_switch.get_config().await;
|
||||
@@ -71,7 +75,10 @@ impl RpcHandler {
|
||||
params.get("lat").and_then(|v| v.as_f64()),
|
||||
params.get("lng").and_then(|v| v.as_f64()),
|
||||
) {
|
||||
let label = params.get("label").and_then(|v| v.as_str()).map(|s| s.to_string());
|
||||
let label = params
|
||||
.get("label")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
config.last_gps = Some(Coordinate::from_degrees(lat, lng, label));
|
||||
}
|
||||
if let Some(contacts) = params.get("contacts").and_then(|v| v.as_array()) {
|
||||
@@ -97,9 +104,12 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
/// mesh.deadman-checkin — Heartbeat to reset the dead man's switch timer.
|
||||
pub(in crate::api::rpc) async fn handle_mesh_deadman_checkin(&self) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_mesh_deadman_checkin(
|
||||
&self,
|
||||
) -> Result<serde_json::Value> {
|
||||
let service = self.mesh_service.read().await;
|
||||
let svc = service.as_ref()
|
||||
let svc = service
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Mesh service not running"))?;
|
||||
|
||||
svc.dead_man_check_in().await;
|
||||
@@ -112,7 +122,9 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
/// mesh.rotate-prekeys — Force prekey rotation for X3DH.
|
||||
pub(in crate::api::rpc) async fn handle_mesh_rotate_prekeys(&self) -> Result<serde_json::Value> {
|
||||
pub(in crate::api::rpc) async fn handle_mesh_rotate_prekeys(
|
||||
&self,
|
||||
) -> Result<serde_json::Value> {
|
||||
// Load identity signing key
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let node_key_path = identity_dir.join("node_key");
|
||||
@@ -162,7 +174,8 @@ impl RpcHandler {
|
||||
let count = params["count"].as_u64().unwrap_or(3) as usize;
|
||||
|
||||
let service = self.mesh_service.read().await;
|
||||
let svc = service.as_ref()
|
||||
let svc = service
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Mesh service not running"))?;
|
||||
|
||||
let mut sent = 0usize;
|
||||
@@ -176,7 +189,10 @@ impl RpcHandler {
|
||||
"chunked" => {
|
||||
// Send a TypedEnvelope that requires chunking (>140 base64 chars)
|
||||
let fake_tx = "0".repeat(400); // simulates TX hex
|
||||
let wire = crate::mesh::bitcoin_relay::build_tx_relay_request(&fake_tx, test_id as u64 + i as u64)?;
|
||||
let wire = crate::mesh::bitcoin_relay::build_tx_relay_request(
|
||||
&fake_tx,
|
||||
test_id as u64 + i as u64,
|
||||
)?;
|
||||
// Send via SendRaw which handles base64 + chunking
|
||||
let peers = svc.peers().await;
|
||||
if let Some(peer) = peers.iter().find(|p| p.contact_id == contact_id) {
|
||||
@@ -185,12 +201,13 @@ impl RpcHandler {
|
||||
if pk_bytes.len() >= 6 {
|
||||
let mut prefix = [0u8; 6];
|
||||
prefix.copy_from_slice(&pk_bytes[..6]);
|
||||
let _ = svc.shared_state().cmd_tx.send(
|
||||
crate::mesh::listener::MeshCommand::SendRaw {
|
||||
let _ = svc
|
||||
.shared_state()
|
||||
.send_cmd(crate::mesh::listener::MeshCommand::SendRaw {
|
||||
dest_pubkey_prefix: prefix,
|
||||
payload: wire,
|
||||
},
|
||||
).await;
|
||||
})
|
||||
.await;
|
||||
sent += 1;
|
||||
}
|
||||
}
|
||||
@@ -206,7 +223,13 @@ impl RpcHandler {
|
||||
// Send as plain text for ping/medium/large
|
||||
let _msg = svc.send_message(contact_id, &payload).await?;
|
||||
sent += 1;
|
||||
info!(test_id, seq = i, mode, len = payload.len(), "Test message sent");
|
||||
info!(
|
||||
test_id,
|
||||
seq = i,
|
||||
mode,
|
||||
len = payload.len(),
|
||||
"Test message sent"
|
||||
);
|
||||
|
||||
// Small delay between sends
|
||||
tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
|
||||
|
||||
@@ -70,6 +70,111 @@ impl RpcHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// conversations.list — Unified inbox across mesh peers, mesh channels,
|
||||
/// and federation nodes. Each conversation returns its latest message
|
||||
/// timestamp + snippet + transport tag so the UI can render one sorted list.
|
||||
pub(in crate::api::rpc) async fn handle_conversations_list(
|
||||
&self,
|
||||
_params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let mut conversations: Vec<serde_json::Value> = Vec::new();
|
||||
let service = self.mesh_service.read().await;
|
||||
if let Some(svc) = service.as_ref() {
|
||||
let peers = svc.peers().await;
|
||||
let messages = svc.messages(None).await;
|
||||
// Per-peer last message.
|
||||
for peer in &peers {
|
||||
let last = messages
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|m| m.peer_contact_id == peer.contact_id);
|
||||
let is_federation = peer.contact_id & 0x8000_0000 != 0;
|
||||
conversations.push(serde_json::json!({
|
||||
"id": format!("{}:{}", if is_federation { "federation" } else { "mesh" }, peer.contact_id),
|
||||
"transport": if is_federation { "federation" } else { "mesh" },
|
||||
"contact_id": peer.contact_id,
|
||||
"name": peer.advert_name,
|
||||
"pubkey": peer.pubkey_hex,
|
||||
"last_text": last.map(|m| m.plaintext.clone()),
|
||||
"last_timestamp": last.map(|m| m.timestamp.clone()),
|
||||
"last_direction": last.map(|m| format!("{:?}", m.direction).to_lowercase()),
|
||||
}));
|
||||
}
|
||||
// Channel 0 ("Archipelago") as a synthetic conversation.
|
||||
let channel_last = messages
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|m| m.message_type == "text" && m.peer_contact_id == 0);
|
||||
conversations.push(serde_json::json!({
|
||||
"id": "channel:0",
|
||||
"transport": "channel",
|
||||
"channel": 0,
|
||||
"name": "Archipelago",
|
||||
"last_text": channel_last.map(|m| m.plaintext.clone()),
|
||||
"last_timestamp": channel_last.map(|m| m.timestamp.clone()),
|
||||
}));
|
||||
}
|
||||
// Sort by last_timestamp desc (missing timestamps sink).
|
||||
conversations.sort_by(|a, b| {
|
||||
let at = a
|
||||
.get("last_timestamp")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let bt = b
|
||||
.get("last_timestamp")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
bt.cmp(at)
|
||||
});
|
||||
Ok(serde_json::json!({ "conversations": conversations }))
|
||||
}
|
||||
|
||||
/// conversations.messages — Return messages for a ConversationId string
|
||||
/// (format: `mesh:<contact_id>` | `federation:<contact_id>` | `channel:<u8>`).
|
||||
pub(in crate::api::rpc) async fn handle_conversations_messages(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let id = params["id"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing id"))?;
|
||||
let (kind, rest) = id
|
||||
.split_once(':')
|
||||
.ok_or_else(|| anyhow::anyhow!("Invalid conversation id"))?;
|
||||
let service = self.mesh_service.read().await;
|
||||
let svc = service
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Mesh service not running"))?;
|
||||
let all = svc.messages(None).await;
|
||||
let filtered: Vec<_> = match kind {
|
||||
"mesh" | "federation" => {
|
||||
let contact_id: u32 = rest.parse().unwrap_or(0);
|
||||
all.into_iter()
|
||||
.filter(|m| m.peer_contact_id == contact_id)
|
||||
.collect()
|
||||
}
|
||||
"channel" => {
|
||||
// For now the channel bucket keeps contact_id = 0.
|
||||
all.into_iter().filter(|m| m.peer_contact_id == 0).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
Ok(serde_json::json!({ "messages": filtered }))
|
||||
}
|
||||
|
||||
/// mesh.debug-dump — Full in-memory state snapshot for debugging.
|
||||
/// Returns peers, all messages, status, shared-secret peer ids, encrypt_relay
|
||||
/// flag, and stego mode. Intended for smoke tests and bug investigation.
|
||||
pub(in crate::api::rpc) async fn handle_mesh_debug_dump(&self) -> Result<serde_json::Value> {
|
||||
let service = self.mesh_service.read().await;
|
||||
if let Some(svc) = service.as_ref() {
|
||||
Ok(svc.debug_dump().await)
|
||||
} else {
|
||||
Ok(serde_json::json!({ "running": false }))
|
||||
}
|
||||
}
|
||||
|
||||
/// mesh.session-status — Get ratchet session info for a peer.
|
||||
pub(in crate::api::rpc) async fn handle_mesh_session_status(
|
||||
&self,
|
||||
@@ -84,7 +189,10 @@ impl RpcHandler {
|
||||
let service = self.mesh_service.read().await;
|
||||
let peer_did = if let Some(svc) = service.as_ref() {
|
||||
let peers = svc.peers().await;
|
||||
peers.iter().find(|p| p.contact_id == contact_id).and_then(|p| p.did.clone())
|
||||
peers
|
||||
.iter()
|
||||
.find(|p| p.contact_id == contact_id)
|
||||
.and_then(|p| p.did.clone())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -118,4 +226,76 @@ impl RpcHandler {
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// mesh.clear-all — Nuclear reset: wipe all mesh state files and restart
|
||||
/// the service for a completely clean slate.
|
||||
pub(in crate::api::rpc) async fn handle_mesh_clear_all(&self) -> Result<serde_json::Value> {
|
||||
let data_dir = self.config.data_dir.clone();
|
||||
// Delete all mesh state files
|
||||
for filename in &[
|
||||
"messages.json",
|
||||
"mesh-contacts.json",
|
||||
"sessions.json",
|
||||
"mesh-outbox.json",
|
||||
] {
|
||||
let _ = tokio::fs::remove_file(data_dir.join(filename)).await;
|
||||
}
|
||||
// Clear in-memory state
|
||||
let service = self.mesh_service.read().await;
|
||||
if let Some(svc) = service.as_ref() {
|
||||
let state = svc.state();
|
||||
|
||||
// Snapshot the firmware pubkeys we currently know about, then
|
||||
// add them to the radio-contact blocklist. MeshCore's on-device
|
||||
// contact table is persistent and reads back stale rows on the
|
||||
// next refresh_contacts, so without this step `clear-all` only
|
||||
// wipes the app view for a few seconds before the old entries
|
||||
// reappear. The blocklist is also saved to disk so the filter
|
||||
// survives a restart.
|
||||
let firmware_pubkeys: Vec<String> = state
|
||||
.peers
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter_map(|p| {
|
||||
// Federation-synthetic peers have their contact_id in the
|
||||
// high half of u32 and carry the archipelago key — those
|
||||
// aren't firmware contacts and must not go on the list.
|
||||
if p.contact_id & 0x8000_0000 != 0 {
|
||||
None
|
||||
} else {
|
||||
p.pubkey_hex.clone()
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
{
|
||||
let mut set = state.radio_contact_blocklist.write().await;
|
||||
for pk in &firmware_pubkeys {
|
||||
set.insert(pk.clone());
|
||||
}
|
||||
}
|
||||
let persisted: Vec<String> = state
|
||||
.radio_contact_blocklist
|
||||
.read()
|
||||
.await
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect();
|
||||
let _ = crate::mesh::save_ignored_radio_contacts(&data_dir, &persisted).await;
|
||||
|
||||
state.peers.write().await.clear();
|
||||
state.messages.write().await.clear();
|
||||
state.contacts.write().await.clear();
|
||||
state.presence.write().await.clear();
|
||||
state.chunk_buffer.write().await.clear();
|
||||
state.shared_secrets.write().await.clear();
|
||||
// Re-seed federation peers
|
||||
crate::mesh::seed_federation_peers_into_mesh(state, &data_dir).await;
|
||||
// Trigger a contact refresh from the radio device
|
||||
let _ = state
|
||||
.send_cmd(crate::mesh::listener::MeshCommand::RefreshContacts)
|
||||
.await;
|
||||
}
|
||||
Ok(serde_json::json!({ "status": "cleared" }))
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -38,10 +38,7 @@ pub(super) const UNAUTHENTICATED_METHODS: &[&str] = &[
|
||||
];
|
||||
|
||||
/// Methods whose responses can be cached for a few seconds.
|
||||
pub(super) const CACHEABLE_METHODS: &[&str] = &[
|
||||
"system.stats",
|
||||
"federation.list-nodes",
|
||||
];
|
||||
pub(super) const CACHEABLE_METHODS: &[&str] = &["system.stats", "federation.list-nodes"];
|
||||
|
||||
/// Sanitize error messages before returning to clients.
|
||||
/// Keeps user-facing validation errors but strips internal system details.
|
||||
@@ -69,7 +66,8 @@ pub(super) fn sanitize_error_message(msg: &str) -> String {
|
||||
for prefix in &user_facing_prefixes {
|
||||
if msg.starts_with(prefix) {
|
||||
// Truncate long messages and strip file paths
|
||||
let sanitized = msg.replace("/var/lib/archipelago/", "[data]/")
|
||||
let sanitized = msg
|
||||
.replace("/var/lib/archipelago/", "[data]/")
|
||||
.replace("/usr/local/bin/", "[bin]/")
|
||||
.replace("/etc/", "[config]/");
|
||||
return if sanitized.len() > 200 {
|
||||
|
||||
@@ -8,15 +8,16 @@ mod credentials;
|
||||
mod dispatcher;
|
||||
mod dwn;
|
||||
mod federation;
|
||||
mod fips;
|
||||
mod handshake;
|
||||
mod identity;
|
||||
mod interfaces;
|
||||
mod lnd;
|
||||
mod marketplace;
|
||||
mod mesh;
|
||||
mod middleware;
|
||||
mod monitoring;
|
||||
mod names;
|
||||
mod lnd;
|
||||
mod mesh;
|
||||
mod network;
|
||||
mod node;
|
||||
mod nostr;
|
||||
@@ -24,12 +25,14 @@ mod package;
|
||||
mod peers;
|
||||
mod response;
|
||||
mod router;
|
||||
mod seed_rpc;
|
||||
mod security;
|
||||
mod tor;
|
||||
mod transport;
|
||||
mod totp;
|
||||
mod seed_rpc;
|
||||
mod streaming;
|
||||
mod system;
|
||||
mod tor;
|
||||
mod totp;
|
||||
mod transitional;
|
||||
mod transport;
|
||||
mod update;
|
||||
mod vpn;
|
||||
mod wallet;
|
||||
@@ -37,7 +40,7 @@ mod webhooks;
|
||||
|
||||
use crate::auth::AuthManager;
|
||||
use crate::config::Config;
|
||||
use crate::container::DevContainerOrchestrator;
|
||||
use crate::container::{ContainerOrchestrator, DevContainerOrchestrator};
|
||||
use crate::monitoring::MetricsStore;
|
||||
use crate::port_allocator::PortAllocator;
|
||||
use crate::rate_limit::{EndpointRateLimiter, LoginRateLimiter};
|
||||
@@ -49,10 +52,10 @@ use std::sync::Arc;
|
||||
use tracing::{debug, error};
|
||||
|
||||
use middleware::{
|
||||
UNAUTHENTICATED_METHODS, CACHEABLE_METHODS,
|
||||
derive_csrf_token, extract_client_ip, extract_cookie, sanitize_error_message,
|
||||
CACHEABLE_METHODS, UNAUTHENTICATED_METHODS,
|
||||
};
|
||||
use response::{RpcRequest, RpcResponse, RpcError, ResponseCache, json_response, cookie_header};
|
||||
use response::{cookie_header, json_response, ResponseCache, RpcError, RpcRequest, RpcResponse};
|
||||
|
||||
/// Default dev password when no user is set up (matches mock-backend).
|
||||
pub(crate) const DEV_DEFAULT_PASSWORD: &str = "password123";
|
||||
@@ -60,7 +63,14 @@ pub(crate) const DEV_DEFAULT_PASSWORD: &str = "password123";
|
||||
pub struct RpcHandler {
|
||||
config: Config,
|
||||
auth_manager: AuthManager,
|
||||
orchestrator: Option<Arc<DevContainerOrchestrator>>,
|
||||
/// Shared lifecycle orchestrator (Dev or Prod). Always `Some` in a normal
|
||||
/// build — the only reason it is `Option` is so tests that don't exercise
|
||||
/// container RPCs can skip constructing one.
|
||||
orchestrator: Option<Arc<dyn ContainerOrchestrator>>,
|
||||
/// Concrete handle to the dev orchestrator, when we're in dev mode. Used by
|
||||
/// `container-install { manifest_path }` which takes an ad-hoc manifest
|
||||
/// path and is not part of the shared trait.
|
||||
dev_orchestrator: Option<Arc<DevContainerOrchestrator>>,
|
||||
state_manager: Arc<StateManager>,
|
||||
pub(crate) metrics_store: Arc<MetricsStore>,
|
||||
port_allocator: Arc<tokio::sync::Mutex<PortAllocator>>,
|
||||
@@ -70,6 +80,22 @@ pub struct RpcHandler {
|
||||
response_cache: ResponseCache,
|
||||
mesh_service: Arc<tokio::sync::RwLock<Option<crate::mesh::MeshService>>>,
|
||||
transport_router: Arc<tokio::sync::RwLock<Option<Arc<crate::transport::TransportRouter>>>>,
|
||||
/// Shared content-addressed blob store. Set by ApiHandler after construction
|
||||
/// so mesh.send-content / mesh.fetch-content RPCs can reach it without a
|
||||
/// second instance and duplicated cap_key.
|
||||
pub(crate) blob_store: Arc<tokio::sync::RwLock<Option<Arc<crate::blobs::BlobStore>>>>,
|
||||
/// Our own Ed25519 pubkey hex — needed by ContentRef senders for cap scoping
|
||||
/// and by ContentRef receivers to request caps scoped to themselves.
|
||||
pub(crate) self_pubkey_hex: Arc<tokio::sync::RwLock<Option<String>>>,
|
||||
/// Kick the package scanner to run immediately (bypassing the 60s interval).
|
||||
/// Used by install/update success paths so the fresh manifest (with populated
|
||||
/// `interfaces.main.ui`) lands before we flip state to Running — closes the
|
||||
/// "Launch button is missing for up to 60s after install" UX gap.
|
||||
pub(crate) scan_kick: Arc<tokio::sync::Notify>,
|
||||
/// Monotonic counter incremented by the scan loop after each completed scan.
|
||||
/// Install/update success paths subscribe to this to know when a kicked scan
|
||||
/// has actually finished before flipping to the terminal state.
|
||||
pub(crate) scan_tick: Arc<tokio::sync::watch::Sender<u64>>,
|
||||
}
|
||||
|
||||
impl RpcHandler {
|
||||
@@ -78,16 +104,13 @@ impl RpcHandler {
|
||||
state_manager: Arc<StateManager>,
|
||||
metrics_store: Arc<MetricsStore>,
|
||||
session_store: SessionStore,
|
||||
orchestrator: Option<Arc<dyn ContainerOrchestrator>>,
|
||||
dev_orchestrator: Option<Arc<DevContainerOrchestrator>>,
|
||||
) -> Result<Self> {
|
||||
let auth_manager = AuthManager::new(config.data_dir.clone());
|
||||
let orchestrator = if config.dev_mode {
|
||||
Some(Arc::new(
|
||||
DevContainerOrchestrator::new(config.clone()).await?,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let port_allocator = Arc::new(tokio::sync::Mutex::new(PortAllocator::new(&config.data_dir).await?));
|
||||
let port_allocator = Arc::new(tokio::sync::Mutex::new(
|
||||
PortAllocator::new(&config.data_dir).await?,
|
||||
));
|
||||
|
||||
let login_rate_limiter = LoginRateLimiter::new();
|
||||
let endpoint_rate_limiter = EndpointRateLimiter::new();
|
||||
@@ -118,6 +141,7 @@ impl RpcHandler {
|
||||
config,
|
||||
auth_manager,
|
||||
orchestrator,
|
||||
dev_orchestrator,
|
||||
state_manager,
|
||||
metrics_store,
|
||||
port_allocator,
|
||||
@@ -127,11 +151,21 @@ impl RpcHandler {
|
||||
response_cache: ResponseCache::new(5),
|
||||
mesh_service: Arc::new(tokio::sync::RwLock::new(None)),
|
||||
transport_router: Arc::new(tokio::sync::RwLock::new(None)),
|
||||
blob_store: Arc::new(tokio::sync::RwLock::new(None)),
|
||||
self_pubkey_hex: Arc::new(tokio::sync::RwLock::new(None)),
|
||||
scan_kick: Arc::new(tokio::sync::Notify::new()),
|
||||
scan_tick: Arc::new(tokio::sync::watch::channel(0u64).0),
|
||||
})
|
||||
}
|
||||
|
||||
/// Set the mesh service (called after identity is loaded).
|
||||
pub async fn set_mesh_service(&self, service: crate::mesh::MeshService) {
|
||||
// If the blob store is already initialised, propagate it into the
|
||||
// freshly-started mesh state so the listener can persist inline
|
||||
// attachments. Mirrors `set_blob_store`'s forward-propagation.
|
||||
if let Some(store) = self.blob_store.read().await.as_ref().cloned() {
|
||||
*service.shared_state().blob_store.write().await = Some(store);
|
||||
}
|
||||
*self.mesh_service.write().await = Some(service);
|
||||
}
|
||||
|
||||
@@ -140,11 +174,42 @@ impl RpcHandler {
|
||||
*self.transport_router.write().await = Some(router);
|
||||
}
|
||||
|
||||
/// Share the blob store + our pubkey so mesh.send-content / fetch-content
|
||||
/// can reach them. Called once from ApiHandler::new.
|
||||
pub async fn set_blob_store(
|
||||
&self,
|
||||
store: Arc<crate::blobs::BlobStore>,
|
||||
self_pubkey_hex: String,
|
||||
) {
|
||||
*self.blob_store.write().await = Some(store.clone());
|
||||
*self.self_pubkey_hex.write().await = Some(self_pubkey_hex);
|
||||
// Propagate into a running mesh service if one is already up — keeps
|
||||
// `set_blob_store` and `set_mesh_service` order-independent.
|
||||
if let Some(svc) = self.mesh_service.read().await.as_ref() {
|
||||
*svc.shared_state().blob_store.write().await = Some(store);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get reference to the mesh service Arc (for MeshTransport wrapper).
|
||||
pub fn mesh_service_arc(&self) -> Arc<tokio::sync::RwLock<Option<crate::mesh::MeshService>>> {
|
||||
Arc::clone(&self.mesh_service)
|
||||
}
|
||||
|
||||
/// Shared Notify handle the package-scanner loop waits on (in addition to
|
||||
/// its periodic tick). Install/update success paths call `notify_one()` to
|
||||
/// trigger an immediate scan so the fresh manifest lands before we flip to
|
||||
/// the terminal Running state.
|
||||
pub fn scan_kick(&self) -> Arc<tokio::sync::Notify> {
|
||||
Arc::clone(&self.scan_kick)
|
||||
}
|
||||
|
||||
/// Sender half of the scan-completion watch channel. The scanner bumps this
|
||||
/// counter after every finished scan; install/update wait for an advance
|
||||
/// after kicking so they know the fresh manifest has landed.
|
||||
pub fn scan_tick(&self) -> Arc<tokio::sync::watch::Sender<u64>> {
|
||||
Arc::clone(&self.scan_tick)
|
||||
}
|
||||
|
||||
fn cookie_suffix_for_request(&self, headers: &hyper::header::HeaderMap) -> &'static str {
|
||||
// Only set Secure flag when the original request was over HTTPS.
|
||||
// Nginx sends X-Forwarded-Proto: https for HTTPS connections.
|
||||
@@ -163,7 +228,7 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
pub async fn handle(
|
||||
&self,
|
||||
self: Arc<Self>,
|
||||
req: Request<hyper::Body>,
|
||||
) -> Result<Response<hyper::Body>> {
|
||||
// Extract session cookie before consuming the request
|
||||
@@ -171,11 +236,12 @@ impl RpcHandler {
|
||||
let session_token = session::extract_session_cookie(&parts.headers);
|
||||
let secure_suffix = self.cookie_suffix_for_request(&parts.headers);
|
||||
|
||||
let body_bytes = hyper::body::to_bytes(body).await
|
||||
let body_bytes = hyper::body::to_bytes(body)
|
||||
.await
|
||||
.context("Failed to read body")?;
|
||||
|
||||
let rpc_req: RpcRequest = serde_json::from_slice(&body_bytes)
|
||||
.context("Invalid RPC request")?;
|
||||
let rpc_req: RpcRequest =
|
||||
serde_json::from_slice(&body_bytes).context("Invalid RPC request")?;
|
||||
|
||||
debug!("RPC method: {}", rpc_req.method);
|
||||
|
||||
@@ -202,7 +268,11 @@ impl RpcHandler {
|
||||
}
|
||||
|
||||
if !authenticated {
|
||||
let reason = if session_token.is_none() { "no session cookie" } else { "invalid/expired token" };
|
||||
let reason = if session_token.is_none() {
|
||||
"no session cookie"
|
||||
} else {
|
||||
"invalid/expired token"
|
||||
};
|
||||
tracing::warn!(method = %rpc_req.method, reason, "401 Unauthorized — rejecting RPC call");
|
||||
return Ok(self.error_response(401, "Unauthorized", StatusCode::UNAUTHORIZED));
|
||||
}
|
||||
@@ -212,7 +282,11 @@ impl RpcHandler {
|
||||
if !is_unauthenticated {
|
||||
if let Ok(Some(user)) = self.auth_manager.get_user().await {
|
||||
if !user.role.can_access(&rpc_req.method) {
|
||||
return Ok(self.error_response(403, "Forbidden: insufficient permissions", StatusCode::FORBIDDEN));
|
||||
return Ok(self.error_response(
|
||||
403,
|
||||
"Forbidden: insufficient permissions",
|
||||
StatusCode::FORBIDDEN,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -220,11 +294,19 @@ impl RpcHandler {
|
||||
// CSRF protection: validate X-CSRF-Token header via HMAC derivation from session token.
|
||||
// Skip CSRF for read-only methods (polling, status) — CSRF prevents state-changing forgery.
|
||||
// Skip when session was just auto-restored from remember-me (browser has stale CSRF cookie).
|
||||
let csrf_exempt = matches!(rpc_req.method.as_str(),
|
||||
"node-messages-received" | "server.echo" | "server.get-state"
|
||||
| "system.stats" | "tor.status"
|
||||
| "tor.onion-addresses" | "federation.list-nodes" | "system.get-settings"
|
||||
| "system.get-node-key" | "system.get-metrics" | "system.get-version"
|
||||
let csrf_exempt = matches!(
|
||||
rpc_req.method.as_str(),
|
||||
"node-messages-received"
|
||||
| "server.echo"
|
||||
| "server.get-state"
|
||||
| "system.stats"
|
||||
| "tor.status"
|
||||
| "tor.onion-addresses"
|
||||
| "federation.list-nodes"
|
||||
| "system.get-settings"
|
||||
| "system.get-node-key"
|
||||
| "system.get-metrics"
|
||||
| "system.get-version"
|
||||
);
|
||||
if !is_unauthenticated && new_session_cookies.is_none() && !csrf_exempt {
|
||||
let csrf_header = parts
|
||||
@@ -241,7 +323,9 @@ impl RpcHandler {
|
||||
let secret = SessionStore::load_or_create_remember_secret().await;
|
||||
let mut mac = match HmacSha256::new_from_slice(&secret) {
|
||||
Ok(m) => m,
|
||||
Err(_) => { return Ok(json_response(StatusCode::INTERNAL_SERVER_ERROR, b"{}")); }
|
||||
Err(_) => {
|
||||
return Ok(json_response(StatusCode::INTERNAL_SERVER_ERROR, b"{}"));
|
||||
}
|
||||
};
|
||||
mac.update(format!("csrf:{}", token).as_bytes());
|
||||
match hex::decode(header) {
|
||||
@@ -271,7 +355,11 @@ impl RpcHandler {
|
||||
"403 CSRF validation failed — rejecting RPC call"
|
||||
);
|
||||
}
|
||||
return Ok(self.error_response(403, "CSRF token missing or invalid", StatusCode::FORBIDDEN));
|
||||
return Ok(self.error_response(
|
||||
403,
|
||||
"CSRF token missing or invalid",
|
||||
StatusCode::FORBIDDEN,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,10 +374,16 @@ impl RpcHandler {
|
||||
// Rate limit sensitive endpoints
|
||||
{
|
||||
let client_ip = extract_client_ip(&parts.headers);
|
||||
if !self.endpoint_rate_limiter.check(&rpc_req.method, client_ip).await {
|
||||
if !self
|
||||
.endpoint_rate_limiter
|
||||
.check(&rpc_req.method, client_ip)
|
||||
.await
|
||||
{
|
||||
return Ok(self.rate_limit_response());
|
||||
}
|
||||
self.endpoint_rate_limiter.record(&rpc_req.method, client_ip).await;
|
||||
self.endpoint_rate_limiter
|
||||
.record(&rpc_req.method, client_ip)
|
||||
.await;
|
||||
}
|
||||
|
||||
// Extract params; clone for post-routing use (login 2FA check needs password)
|
||||
@@ -315,7 +409,7 @@ impl RpcHandler {
|
||||
|
||||
// Route to handler (track latency for metrics)
|
||||
let rpc_start = std::time::Instant::now();
|
||||
let result = self.dispatch(&rpc_req.method, params, &session_token).await;
|
||||
let result = Self::dispatch(&self, &rpc_req.method, params, &session_token).await;
|
||||
|
||||
// Record RPC latency for monitoring
|
||||
let elapsed_ms = rpc_start.elapsed().as_secs_f64() * 1000.0;
|
||||
@@ -325,7 +419,9 @@ impl RpcHandler {
|
||||
let mut rpc_resp = match result {
|
||||
Ok(data) => {
|
||||
if is_cacheable {
|
||||
self.response_cache.set(rpc_req.method.clone(), data.clone()).await;
|
||||
self.response_cache
|
||||
.set(rpc_req.method.clone(), data.clone())
|
||||
.await;
|
||||
}
|
||||
RpcResponse {
|
||||
result: Some(data),
|
||||
@@ -346,8 +442,7 @@ impl RpcHandler {
|
||||
}
|
||||
};
|
||||
|
||||
let resp_body = serde_json::to_vec(&rpc_resp)
|
||||
.context("Failed to serialize response")?;
|
||||
let resp_body = serde_json::to_vec(&rpc_resp).context("Failed to serialize response")?;
|
||||
|
||||
let mut response = json_response(StatusCode::OK, &resp_body);
|
||||
|
||||
@@ -362,13 +457,19 @@ impl RpcHandler {
|
||||
&new_session_cookies,
|
||||
client_ip,
|
||||
secure_suffix,
|
||||
).await;
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// Build a JSON error response with the given RPC error code and HTTP status.
|
||||
fn error_response(&self, code: i32, message: &str, status: StatusCode) -> Response<hyper::Body> {
|
||||
fn error_response(
|
||||
&self,
|
||||
code: i32,
|
||||
message: &str,
|
||||
status: StatusCode,
|
||||
) -> Response<hyper::Body> {
|
||||
let rpc_resp = RpcResponse {
|
||||
result: None,
|
||||
error: Some(RpcError {
|
||||
@@ -393,7 +494,8 @@ impl RpcHandler {
|
||||
};
|
||||
let resp_body = serde_json::to_vec(&rpc_resp).unwrap_or_default();
|
||||
let mut resp = json_response(StatusCode::TOO_MANY_REQUESTS, &resp_body);
|
||||
resp.headers_mut().insert("Retry-After", cookie_header("60"));
|
||||
resp.headers_mut()
|
||||
.insert("Retry-After", cookie_header("60"));
|
||||
resp
|
||||
}
|
||||
|
||||
@@ -433,9 +535,8 @@ impl RpcHandler {
|
||||
"result": { "requires_totp": true },
|
||||
"error": null
|
||||
});
|
||||
*response.body_mut() = hyper::Body::from(
|
||||
serde_json::to_vec(&totp_body).unwrap_or_default(),
|
||||
);
|
||||
*response.body_mut() =
|
||||
hyper::Body::from(serde_json::to_vec(&totp_body).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -493,11 +594,17 @@ impl RpcHandler {
|
||||
}
|
||||
response.headers_mut().append(
|
||||
"Set-Cookie",
|
||||
cookie_header(&format!("session=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0{}", secure_suffix)),
|
||||
cookie_header(&format!(
|
||||
"session=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0{}",
|
||||
secure_suffix
|
||||
)),
|
||||
);
|
||||
response.headers_mut().append(
|
||||
"Set-Cookie",
|
||||
cookie_header(&format!("csrf_token=; SameSite=Lax; Path=/; Max-Age=0{}", secure_suffix)),
|
||||
cookie_header(&format!(
|
||||
"csrf_token=; SameSite=Lax; Path=/; Max-Age=0{}",
|
||||
secure_suffix
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -508,24 +615,48 @@ impl RpcHandler {
|
||||
}
|
||||
}
|
||||
|
||||
fn set_session_cookie(&self, response: &mut Response<hyper::Body>, token: &str, secure_suffix: &str) {
|
||||
fn set_session_cookie(
|
||||
&self,
|
||||
response: &mut Response<hyper::Body>,
|
||||
token: &str,
|
||||
secure_suffix: &str,
|
||||
) {
|
||||
response.headers_mut().append(
|
||||
"Set-Cookie",
|
||||
cookie_header(&format!("session={}; HttpOnly; SameSite=Lax; Path=/{}", token, secure_suffix)),
|
||||
cookie_header(&format!(
|
||||
"session={}; HttpOnly; SameSite=Lax; Path=/{}",
|
||||
token, secure_suffix
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
fn set_csrf_cookie(&self, response: &mut Response<hyper::Body>, csrf_token: &str, secure_suffix: &str) {
|
||||
fn set_csrf_cookie(
|
||||
&self,
|
||||
response: &mut Response<hyper::Body>,
|
||||
csrf_token: &str,
|
||||
secure_suffix: &str,
|
||||
) {
|
||||
response.headers_mut().append(
|
||||
"Set-Cookie",
|
||||
cookie_header(&format!("csrf_token={}; SameSite=Lax; Path=/{}", csrf_token, secure_suffix)),
|
||||
cookie_header(&format!(
|
||||
"csrf_token={}; SameSite=Lax; Path=/{}",
|
||||
csrf_token, secure_suffix
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
fn set_remember_cookie(&self, response: &mut Response<hyper::Body>, remember_token: &str, secure_suffix: &str) {
|
||||
fn set_remember_cookie(
|
||||
&self,
|
||||
response: &mut Response<hyper::Body>,
|
||||
remember_token: &str,
|
||||
secure_suffix: &str,
|
||||
) {
|
||||
response.headers_mut().append(
|
||||
"Set-Cookie",
|
||||
cookie_header(&format!("remember={}; HttpOnly; SameSite=Lax; Path=/; Max-Age={}{}", remember_token, REMEMBER_TTL, secure_suffix)),
|
||||
cookie_header(&format!(
|
||||
"remember={}; HttpOnly; SameSite=Lax; Path=/; Max-Age={}{}",
|
||||
remember_token, REMEMBER_TTL, secure_suffix
|
||||
)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,9 @@ impl RpcHandler {
|
||||
|
||||
match self.metrics_store.latest().await {
|
||||
Some(snapshot) => Ok(serde_json::to_value(snapshot)?),
|
||||
None => Ok(serde_json::json!({ "status": "collecting", "message": "No metrics collected yet" })),
|
||||
None => Ok(
|
||||
serde_json::json!({ "status": "collecting", "message": "No metrics collected yet" }),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,14 +151,12 @@ impl RpcHandler {
|
||||
};
|
||||
|
||||
match format {
|
||||
"json" => {
|
||||
Ok(serde_json::json!({
|
||||
"format": "json",
|
||||
"resolution": resolution,
|
||||
"count": data.len(),
|
||||
"data": data,
|
||||
}))
|
||||
}
|
||||
"json" => Ok(serde_json::json!({
|
||||
"format": "json",
|
||||
"resolution": resolution,
|
||||
"count": data.len(),
|
||||
"data": data,
|
||||
})),
|
||||
_ => {
|
||||
// CSV format
|
||||
let mut csv = String::from(
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! RPC handlers for node network visibility and overlay controls.
|
||||
|
||||
use super::RpcHandler;
|
||||
use crate::{identity, peers};
|
||||
use crate::container::docker_packages;
|
||||
use crate::{identity, peers};
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::fs;
|
||||
@@ -94,19 +94,29 @@ impl RpcHandler {
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let to_did = params.get("did").and_then(|v| v.as_str())
|
||||
let to_did = params
|
||||
.get("did")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: did"))?;
|
||||
let to_onion = params.get("onion").and_then(|v| v.as_str())
|
||||
let to_onion = params
|
||||
.get("onion")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: onion"))?;
|
||||
let to_pubkey = params.get("pubkey").and_then(|v| v.as_str())
|
||||
let to_pubkey = params
|
||||
.get("pubkey")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: pubkey"))?;
|
||||
let message = params.get("message").and_then(|v| v.as_str()).map(String::from);
|
||||
let message = params
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from);
|
||||
|
||||
// Send a message to the peer over Tor with connection request
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
let my_pubkey = &data.server_info.pubkey;
|
||||
let my_did = identity::did_key_from_pubkey_hex(my_pubkey)?;
|
||||
let my_onion = docker_packages::read_tor_address("archipelago").await
|
||||
let my_onion = docker_packages::read_tor_address("archipelago")
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
let req_msg = serde_json::json!({
|
||||
@@ -117,13 +127,18 @@ impl RpcHandler {
|
||||
"message": message,
|
||||
});
|
||||
|
||||
let to_fips_npub =
|
||||
crate::federation::fips_npub_for_onion(&self.config.data_dir, to_onion).await;
|
||||
crate::node_message::send_to_peer(
|
||||
to_onion,
|
||||
to_fips_npub.as_deref(),
|
||||
my_pubkey,
|
||||
&req_msg.to_string(),
|
||||
None,
|
||||
None,
|
||||
).await?;
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Also add them as a pending peer locally
|
||||
let req = ConnectionRequest {
|
||||
@@ -145,18 +160,25 @@ impl RpcHandler {
|
||||
Ok(serde_json::json!({ "requests": requests }))
|
||||
}
|
||||
|
||||
/// Accept a connection request — add peer to trusted list.
|
||||
/// Accept a connection request — add peer to trusted list AND send
|
||||
/// a `connection_accepted` notification back to the requester so
|
||||
/// their side auto-adds us without a second manual round-trip.
|
||||
pub(super) async fn handle_network_accept_request(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let request_id = params.get("id").and_then(|v| v.as_str())
|
||||
let request_id = params
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: id"))?;
|
||||
|
||||
let requests = self.load_requests().await?;
|
||||
let req = requests.iter().find(|r| r.id == request_id)
|
||||
.ok_or_else(|| anyhow::anyhow!("Request not found: {}", request_id))?;
|
||||
let req = requests
|
||||
.iter()
|
||||
.find(|r| r.id == request_id)
|
||||
.ok_or_else(|| anyhow::anyhow!("Request not found: {}", request_id))?
|
||||
.clone();
|
||||
|
||||
// Add to known peers
|
||||
let peer = peers::KnownPeer {
|
||||
@@ -170,6 +192,47 @@ impl RpcHandler {
|
||||
// Remove the request
|
||||
self.delete_request(request_id).await?;
|
||||
|
||||
// Notify the requester we've accepted so their UI auto-adds us and
|
||||
// clears its outbound pending row. Best-effort — if the peer is
|
||||
// offline we don't fail the accept; the next connection_request
|
||||
// retry on their side will resolve eventually.
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
let my_pubkey = data.server_info.pubkey.clone();
|
||||
let my_did = crate::identity::did_key_from_pubkey_hex(&my_pubkey).ok();
|
||||
let my_onion = crate::container::docker_packages::read_tor_address("archipelago")
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let accept_msg = serde_json::json!({
|
||||
"type": "connection_accepted",
|
||||
"request_id": request_id,
|
||||
"from_did": my_did,
|
||||
"from_onion": my_onion,
|
||||
"from_pubkey": my_pubkey,
|
||||
});
|
||||
let to_fips_npub =
|
||||
crate::federation::fips_npub_for_onion(&self.config.data_dir, &req.from_onion).await;
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let signing_key = crate::identity::NodeIdentity::load_or_create(&identity_dir)
|
||||
.await
|
||||
.ok();
|
||||
if let Err(e) = crate::node_message::send_to_peer(
|
||||
&req.from_onion,
|
||||
to_fips_npub.as_deref(),
|
||||
&my_pubkey,
|
||||
&accept_msg.to_string(),
|
||||
signing_key.as_ref().map(|i| i.signing_key()),
|
||||
Some(&req.from_pubkey),
|
||||
data.server_info.name.as_deref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
to = %req.from_did,
|
||||
error = %e,
|
||||
"connection_accepted notify failed (requester will still be able to see us on their next retry)"
|
||||
);
|
||||
}
|
||||
|
||||
tracing::info!("Accepted connection from {}", req.from_did);
|
||||
Ok(serde_json::json!({ "ok": true }))
|
||||
}
|
||||
@@ -180,7 +243,9 @@ impl RpcHandler {
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.unwrap_or_default();
|
||||
let request_id = params.get("id").and_then(|v| v.as_str())
|
||||
let request_id = params
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: id"))?;
|
||||
|
||||
self.delete_request(request_id).await?;
|
||||
@@ -200,7 +265,9 @@ impl RpcHandler {
|
||||
|
||||
async fn requests_dir(&self) -> Result<std::path::PathBuf> {
|
||||
let dir = self.config.data_dir.join(REQUESTS_DIR);
|
||||
fs::create_dir_all(&dir).await.context("Failed to create requests dir")?;
|
||||
fs::create_dir_all(&dir)
|
||||
.await
|
||||
.context("Failed to create requests dir")?;
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
@@ -208,7 +275,9 @@ impl RpcHandler {
|
||||
let dir = self.requests_dir().await?;
|
||||
let path = dir.join(format!("{}.json", req.id));
|
||||
let json = serde_json::to_string_pretty(req).context("Failed to serialize request")?;
|
||||
fs::write(&path, json).await.context("Failed to write request")?;
|
||||
fs::write(&path, json)
|
||||
.await
|
||||
.context("Failed to write request")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -233,13 +302,21 @@ impl RpcHandler {
|
||||
|
||||
async fn delete_request(&self, id: &str) -> Result<()> {
|
||||
// Validate ID to prevent path traversal
|
||||
if id.is_empty() || id.len() > 128 || id.contains('/') || id.contains('\\') || id.contains("..") || id.contains('\0') {
|
||||
if id.is_empty()
|
||||
|| id.len() > 128
|
||||
|| id.contains('/')
|
||||
|| id.contains('\\')
|
||||
|| id.contains("..")
|
||||
|| id.contains('\0')
|
||||
{
|
||||
anyhow::bail!("Invalid request ID");
|
||||
}
|
||||
let dir = self.requests_dir().await?;
|
||||
let path = dir.join(format!("{}.json", id));
|
||||
if path.exists() {
|
||||
fs::remove_file(&path).await.context("Failed to delete request")?;
|
||||
fs::remove_file(&path)
|
||||
.await
|
||||
.context("Failed to delete request")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::RpcHandler;
|
||||
use crate::{backup, identity, nostr_discovery};
|
||||
use crate::container::docker_packages;
|
||||
use crate::{backup, identity, nostr_discovery};
|
||||
use anyhow::{Context, Result};
|
||||
use ed25519_dalek::SigningKey;
|
||||
use nostr_sdk::ToBech32;
|
||||
@@ -103,21 +103,31 @@ impl RpcHandler {
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let pubkey_hex = nostr_discovery::get_nostr_pubkey(&identity_dir).await?;
|
||||
|
||||
let event = params.get("event")
|
||||
let event = params
|
||||
.get("event")
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing 'event' parameter"))?;
|
||||
|
||||
let kind = event.get("kind").and_then(|v| v.as_u64()).unwrap_or(1);
|
||||
let content = event.get("content").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let created_at = event.get("created_at").and_then(|v| v.as_u64())
|
||||
.unwrap_or_else(|| std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs());
|
||||
let tags = event.get("tags").cloned().unwrap_or_else(|| serde_json::json!([]));
|
||||
let created_at = event
|
||||
.get("created_at")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or_else(|| {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs()
|
||||
});
|
||||
let tags = event
|
||||
.get("tags")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| serde_json::json!([]));
|
||||
|
||||
// NIP-01 serialization: [0, pubkey, created_at, kind, tags, content]
|
||||
let serialized = serde_json::json!([0, pubkey_hex, created_at, kind, tags, content]);
|
||||
let serialized_str = serde_json::to_string(&serialized)?;
|
||||
|
||||
use sha2::{Sha256, Digest};
|
||||
use sha2::{Digest, Sha256};
|
||||
let hash = Sha256::digest(serialized_str.as_bytes());
|
||||
let event_hash_hex = hex::encode(hash);
|
||||
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
//! Async wrappers for `package.install`, `package.uninstall`, `package.update`.
|
||||
//!
|
||||
//! The inner `handle_package_*` functions are large (install is 480 lines with
|
||||
//! the stack dispatchers, update is 300, uninstall is 200) and do their own
|
||||
//! fine-grained progress tracking via `install_progress` and `uninstall_stage`.
|
||||
//! We wrap them rather than refactor them.
|
||||
//!
|
||||
//! Each wrapper:
|
||||
//! 1. Parses + validates the RPC params (cheap, synchronous). Errors here
|
||||
//! return immediately to the caller before any state change.
|
||||
//! 2. Flips the package state to the transitional variant
|
||||
//! (`Installing` / `Removing` / `Updating`) so the UI sees it on the
|
||||
//! next WebSocket push (before the RPC response even lands).
|
||||
//! 3. `tokio::spawn`s a background task that invokes the existing
|
||||
//! `handle_package_*` method on the Arc-held self.
|
||||
//! 4. On task success: no state change needed — the inner handler has
|
||||
//! already written the terminal state (Running for install/update, or
|
||||
//! removed the entry for uninstall).
|
||||
//! 5. On task failure: revert state to the pre-transition value (or delete
|
||||
//! the entry for install, since there was no pre-state), write a line
|
||||
//! to the persistent install log, and clear any stale progress fields.
|
||||
//! 6. Returns `{ "status": "installing" }` etc. immediately.
|
||||
//!
|
||||
//! The server package-scan loop's `merge_preserving_transitional` helper
|
||||
//! already knows to preserve `Installing` / `Removing` / `Updating` between
|
||||
//! scans, so live progress updates broadcast from inside the spawned task
|
||||
//! reach the UI correctly.
|
||||
|
||||
use super::install::install_log;
|
||||
use crate::api::rpc::RpcHandler;
|
||||
use crate::data_model::PackageState;
|
||||
use crate::state::StateManager;
|
||||
use anyhow::Result;
|
||||
use std::sync::Arc;
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
impl RpcHandler {
|
||||
/// Async wrapper for `package.install`. Returns `{ "status": "installing" }`
|
||||
/// immediately after flipping state to `Installing` and spawning the
|
||||
/// actual install pipeline. On failure, removes the package entry from
|
||||
/// state so the UI reverts to "not installed".
|
||||
pub(in crate::api::rpc) async fn spawn_package_install(
|
||||
self: Arc<Self>,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
// Extract + validate package_id synchronously so bad params fail
|
||||
// fast without touching state.
|
||||
let params_val = params
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let package_id = params_val
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing package id"))?
|
||||
.to_string();
|
||||
super::validation::validate_app_id(&package_id)?;
|
||||
|
||||
// Reject if already in a transitional lifecycle (prevents double-click
|
||||
// queuing two installs on the same package).
|
||||
{
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
if let Some(entry) = data.package_data.get(&package_id) {
|
||||
if matches!(
|
||||
entry.state,
|
||||
PackageState::Installing | PackageState::Removing | PackageState::Updating
|
||||
) {
|
||||
return Err(anyhow::anyhow!(
|
||||
"{} is already {:?}",
|
||||
package_id,
|
||||
entry.state
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Flip state to Installing BEFORE the spawn so the first WebSocket
|
||||
// push carries the transitional state. Uses the same
|
||||
// `create_installing_entry` path the inner handler would use once
|
||||
// it starts pulling, so the UI sees a consistent shape.
|
||||
flip_to_installing(&self.state_manager, &package_id).await;
|
||||
|
||||
install_log(&format!("INSTALL SPAWN: {}", package_id)).await;
|
||||
|
||||
let handler = Arc::clone(&self);
|
||||
let package_id_spawn = package_id.clone();
|
||||
tokio::spawn(async move {
|
||||
match handler.handle_package_install(params).await {
|
||||
Ok(_) => {
|
||||
info!("package.install {}: complete", package_id_spawn);
|
||||
// The install pipeline has verified the container is up
|
||||
// and healthy (see install.rs post-start exit check).
|
||||
// Kick the scanner first so the fresh manifest (with
|
||||
// `interfaces.main.ui` from the live port binding) lands
|
||||
// BEFORE we flip to Running — without this the Launch
|
||||
// button is missing for up to 60s after a successful
|
||||
// install, because the skeletal install-time manifest
|
||||
// has `interfaces: None`.
|
||||
kick_scanner_and_wait(&handler).await;
|
||||
// We MUST explicitly transition out of Installing here:
|
||||
// `merge_preserving_transitional` in the package-scan
|
||||
// loop treats Installing as RPC-owned and refuses to
|
||||
// let the scanner overwrite it with the observed
|
||||
// Running state. Without this write, the entry stays
|
||||
// stuck at Installing forever.
|
||||
set_package_state(
|
||||
&handler.state_manager,
|
||||
&package_id_spawn,
|
||||
PackageState::Running,
|
||||
)
|
||||
.await;
|
||||
handler.clear_install_progress(&package_id_spawn).await;
|
||||
}
|
||||
Err(e) => {
|
||||
error!("package.install {} failed: {:#}", package_id_spawn, e);
|
||||
install_log(&format!("INSTALL FAIL: {} — {:#}", package_id_spawn, e)).await;
|
||||
// No pre-state to revert to — remove the entry entirely so
|
||||
// the UI shows the app as not installed. The next package
|
||||
// scan will re-create it only if podman actually has a
|
||||
// container for it (partial install recovery).
|
||||
remove_package_entry(&handler.state_manager, &package_id_spawn).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"status": "installing",
|
||||
"package_id": package_id,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Async wrapper for `package.uninstall`. Returns `{ "status": "removing" }`
|
||||
/// immediately. State stays `Removing` until the inner handler finishes
|
||||
/// (including the `sudo rm -rf` of app data, which can take minutes for
|
||||
/// bitcoin-core's chainstate). On failure, reverts to the pre-transition
|
||||
/// state (usually Running or Stopped) so the user can retry.
|
||||
pub(in crate::api::rpc) async fn spawn_package_uninstall(
|
||||
self: Arc<Self>,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params_val = params
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let package_id = params_val
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing package id"))?
|
||||
.to_string();
|
||||
super::validation::validate_app_id(&package_id)?;
|
||||
|
||||
// Reject if already in a transitional lifecycle.
|
||||
{
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
if let Some(entry) = data.package_data.get(&package_id) {
|
||||
if matches!(
|
||||
entry.state,
|
||||
PackageState::Installing | PackageState::Removing | PackageState::Updating
|
||||
) {
|
||||
return Err(anyhow::anyhow!(
|
||||
"{} is already {:?}",
|
||||
package_id,
|
||||
entry.state
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let pre_state =
|
||||
flip_package_state(&self.state_manager, &package_id, PackageState::Removing).await;
|
||||
|
||||
install_log(&format!("UNINSTALL SPAWN: {}", package_id)).await;
|
||||
|
||||
let handler = Arc::clone(&self);
|
||||
let package_id_spawn = package_id.clone();
|
||||
tokio::spawn(async move {
|
||||
match handler.handle_package_uninstall(params).await {
|
||||
Ok(_) => {
|
||||
info!("package.uninstall {}: complete", package_id_spawn);
|
||||
// Inner handler already removed the package entry on
|
||||
// success. Nothing more to do here.
|
||||
}
|
||||
Err(e) => {
|
||||
error!("package.uninstall {} failed: {:#}", package_id_spawn, e);
|
||||
install_log(&format!("UNINSTALL FAIL: {} — {:#}", package_id_spawn, e)).await;
|
||||
// Revert to pre-transition state so the user can retry.
|
||||
// Also clear any stale uninstall_stage label.
|
||||
if let Some(prev) = pre_state {
|
||||
set_package_state_and_clear_uninstall_stage(
|
||||
&handler.state_manager,
|
||||
&package_id_spawn,
|
||||
prev,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"status": "removing",
|
||||
"package_id": package_id,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Async wrapper for `package.update`. Returns `{ "status": "updating" }`
|
||||
/// immediately. The inner handler already manages its own rollback on
|
||||
/// failure (restarts old containers); this wrapper just flips state and
|
||||
/// spawns.
|
||||
pub(in crate::api::rpc) async fn spawn_package_update(
|
||||
self: Arc<Self>,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params_val = params
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let package_id = params_val
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing package id"))?
|
||||
.to_string();
|
||||
super::validation::validate_app_id(&package_id)?;
|
||||
|
||||
// Reject if already in a transitional lifecycle.
|
||||
{
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
if let Some(entry) = data.package_data.get(&package_id) {
|
||||
if matches!(
|
||||
entry.state,
|
||||
PackageState::Installing | PackageState::Removing | PackageState::Updating
|
||||
) {
|
||||
return Err(anyhow::anyhow!(
|
||||
"{} is already {:?}",
|
||||
package_id,
|
||||
entry.state
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The inner handler flips state to Updating itself, but we do it
|
||||
// here too so the transitional state lands before the spawn yields.
|
||||
let pre_state =
|
||||
flip_package_state(&self.state_manager, &package_id, PackageState::Updating).await;
|
||||
|
||||
install_log(&format!("UPDATE SPAWN: {}", package_id)).await;
|
||||
|
||||
let handler = Arc::clone(&self);
|
||||
let package_id_spawn = package_id.clone();
|
||||
tokio::spawn(async move {
|
||||
match handler.handle_package_update(params).await {
|
||||
Ok(_) => {
|
||||
info!("package.update {}: complete", package_id_spawn);
|
||||
// Same reasoning as install: the merge_preserving_transitional
|
||||
// helper treats Updating as RPC-owned, so we MUST write the
|
||||
// terminal Running state ourselves or the entry will stay
|
||||
// stuck at Updating forever. The update pipeline has
|
||||
// already verified the new container is running via its
|
||||
// post-recreate check.
|
||||
// Kick the scanner first so any manifest changes from the
|
||||
// new image version (interfaces, ports, etc.) land before
|
||||
// we flip to Running.
|
||||
kick_scanner_and_wait(&handler).await;
|
||||
set_package_state(
|
||||
&handler.state_manager,
|
||||
&package_id_spawn,
|
||||
PackageState::Running,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Err(e) => {
|
||||
error!("package.update {} failed: {:#}", package_id_spawn, e);
|
||||
install_log(&format!("UPDATE FAIL: {} — {:#}", package_id_spawn, e)).await;
|
||||
// Inner handler already ran rollback_update + cleared
|
||||
// update state, but be defensive: revert to pre-state
|
||||
// in case the inner flow died before its cleanup.
|
||||
if let Some(prev) = pre_state {
|
||||
set_package_state(&handler.state_manager, &package_id_spawn, prev).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"status": "updating",
|
||||
"package_id": package_id,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// State-manager helpers (free fns, usable from inside spawned tasks)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Create or update the entry for this package with `Installing` state.
|
||||
/// Matches what the inner handler's `set_install_progress` would do on first
|
||||
/// call, but fires before the spawn so the UI sees it immediately.
|
||||
async fn flip_to_installing(state_manager: &StateManager, package_id: &str) {
|
||||
use crate::data_model::{Description, Manifest, PackageDataEntry, StaticFiles};
|
||||
let (mut data, _) = state_manager.get_snapshot().await;
|
||||
let entry = data
|
||||
.package_data
|
||||
.entry(package_id.to_string())
|
||||
.or_insert_with(|| PackageDataEntry {
|
||||
state: PackageState::Installing,
|
||||
health: None,
|
||||
exit_code: None,
|
||||
static_files: StaticFiles {
|
||||
license: String::new(),
|
||||
instructions: String::new(),
|
||||
// Leave icon empty during the transient Installing window:
|
||||
// hardcoding `<id>.png` is wrong for ~half our apps (many use
|
||||
// `.svg` / `.webp`), producing a broken-image flicker until
|
||||
// the scanner refreshes the entry. The frontend's `icon`
|
||||
// computed falls through to `curatedMap.get(id)?.icon` which
|
||||
// has the correct extensions for known apps.
|
||||
icon: String::new(),
|
||||
},
|
||||
manifest: Manifest {
|
||||
id: package_id.to_string(),
|
||||
title: package_id.to_string(),
|
||||
version: String::new(),
|
||||
description: Description {
|
||||
short: "Installing...".to_string(),
|
||||
long: String::new(),
|
||||
},
|
||||
release_notes: String::new(),
|
||||
license: String::new(),
|
||||
wrapper_repo: String::new(),
|
||||
upstream_repo: String::new(),
|
||||
support_site: String::new(),
|
||||
marketing_site: String::new(),
|
||||
donation_url: None,
|
||||
author: None,
|
||||
website: None,
|
||||
interfaces: None,
|
||||
tier: None,
|
||||
},
|
||||
installed: None,
|
||||
install_progress: None,
|
||||
uninstall_stage: None,
|
||||
available_update: None,
|
||||
});
|
||||
entry.state = PackageState::Installing;
|
||||
state_manager.update_data(data).await;
|
||||
}
|
||||
|
||||
/// Flip an existing entry's state and return the pre-flip value (or None if
|
||||
/// no entry existed). Used for revert-on-failure.
|
||||
async fn flip_package_state(
|
||||
state_manager: &StateManager,
|
||||
package_id: &str,
|
||||
new_state: PackageState,
|
||||
) -> Option<PackageState> {
|
||||
let (mut data, _) = state_manager.get_snapshot().await;
|
||||
let prev = data.package_data.get(package_id).map(|e| e.state.clone());
|
||||
if let Some(entry) = data.package_data.get_mut(package_id) {
|
||||
entry.state = new_state;
|
||||
state_manager.update_data(data).await;
|
||||
} else {
|
||||
warn!(
|
||||
"flip_package_state: no entry for {} — cannot flip",
|
||||
package_id
|
||||
);
|
||||
}
|
||||
prev
|
||||
}
|
||||
|
||||
/// Set state unconditionally (no-op if entry no longer exists).
|
||||
async fn set_package_state(
|
||||
state_manager: &StateManager,
|
||||
package_id: &str,
|
||||
new_state: PackageState,
|
||||
) {
|
||||
let (mut data, _) = state_manager.get_snapshot().await;
|
||||
if let Some(entry) = data.package_data.get_mut(package_id) {
|
||||
if entry.state != new_state {
|
||||
entry.state = new_state;
|
||||
state_manager.update_data(data).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set state and clear the uninstall_stage label. Used when an uninstall
|
||||
/// fails and we revert — the user doesn't want a stale "Removing app data"
|
||||
/// message sitting on a Running entry.
|
||||
async fn set_package_state_and_clear_uninstall_stage(
|
||||
state_manager: &StateManager,
|
||||
package_id: &str,
|
||||
new_state: PackageState,
|
||||
) {
|
||||
let (mut data, _) = state_manager.get_snapshot().await;
|
||||
if let Some(entry) = data.package_data.get_mut(package_id) {
|
||||
entry.state = new_state;
|
||||
entry.uninstall_stage = None;
|
||||
state_manager.update_data(data).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a package entry from state. Used for install-failure cleanup
|
||||
/// (since there's no pre-state to revert to — the entry was created
|
||||
/// speculatively when we flipped to Installing).
|
||||
async fn remove_package_entry(state_manager: &StateManager, package_id: &str) {
|
||||
let (mut data, _) = state_manager.get_snapshot().await;
|
||||
if data.package_data.remove(package_id).is_some() {
|
||||
state_manager.update_data(data).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Kick the container scanner to run immediately and wait for it to finish
|
||||
/// (with a 2s timeout). Used by install/update success paths so the fresh
|
||||
/// manifest — with `interfaces.main.ui` populated from the now-running
|
||||
/// container's port binding — lands BEFORE we flip state to Running.
|
||||
///
|
||||
/// Without this, the frontend sees `state = running` but the skeletal
|
||||
/// install-time manifest (interfaces = None), and hides the Launch button
|
||||
/// for up to the full 60s scan interval.
|
||||
///
|
||||
/// The scan merges via `merge_preserving_transitional`, which keeps
|
||||
/// state = Installing (we haven't flipped yet) while taking the fresh
|
||||
/// manifest. After this returns, the caller writes Running on top of the
|
||||
/// now-populated manifest.
|
||||
async fn kick_scanner_and_wait(handler: &RpcHandler) {
|
||||
let mut rx = handler.scan_tick.subscribe();
|
||||
let start = *rx.borrow_and_update();
|
||||
handler.scan_kick.notify_one();
|
||||
// 2s is well above a typical podman scan (~200ms on .228, ~500ms worst
|
||||
// case). If it times out we proceed anyway — the next 60s scan will
|
||||
// self-heal and the worst case is the pre-fix behavior (Launch button
|
||||
// appears a bit late).
|
||||
let _ = tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
||||
while *rx.borrow_and_update() == start {
|
||||
if rx.changed().await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -4,26 +4,13 @@ use anyhow::{Context, Result};
|
||||
|
||||
/// Trusted Docker registries. Only images from these sources are allowed.
|
||||
#[allow(dead_code)]
|
||||
pub(super) const TRUSTED_REGISTRIES: &[&str] = &["docker.io/", "ghcr.io/", "localhost/", "80.71.235.15:3000/"];
|
||||
|
||||
/// Detect which Bitcoin container is running on archy-net for DNS resolution.
|
||||
/// Returns the container name to use as the RPC host (e.g., "bitcoin-knots").
|
||||
pub(super) fn detect_bitcoin_container_name() -> String {
|
||||
// Synchronous check — called from get_app_config which is sync
|
||||
let output = std::process::Command::new("podman")
|
||||
.args(["ps", "--format", "{{.Names}}"])
|
||||
.output();
|
||||
if let Ok(out) = output {
|
||||
let names = String::from_utf8_lossy(&out.stdout);
|
||||
for candidate in &["bitcoin-knots", "bitcoin-core", "bitcoin"] {
|
||||
if names.lines().any(|l| l.trim() == *candidate) {
|
||||
return candidate.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
// Default to bitcoin-knots (most common)
|
||||
"bitcoin-knots".to_string()
|
||||
}
|
||||
pub(super) const TRUSTED_REGISTRIES: &[&str] = &[
|
||||
"docker.io/",
|
||||
"ghcr.io/",
|
||||
"localhost/",
|
||||
"git.tx1138.com/",
|
||||
"146.59.87.168:3000/",
|
||||
];
|
||||
|
||||
/// Validate Docker image against trusted registry allowlist.
|
||||
pub(super) fn is_valid_docker_image(image: &str) -> bool {
|
||||
@@ -40,7 +27,10 @@ pub(super) fn is_valid_docker_image(image: &str) -> bool {
|
||||
Some(r) => r,
|
||||
None => return false,
|
||||
};
|
||||
matches!(registry, "docker.io" | "ghcr.io" | "localhost" | "80.71.235.15:3000")
|
||||
matches!(
|
||||
registry,
|
||||
"docker.io" | "ghcr.io" | "localhost" | "git.tx1138.com" | "146.59.87.168:3000"
|
||||
)
|
||||
}
|
||||
|
||||
/// Per-app Linux capabilities needed beyond the default cap-drop=ALL.
|
||||
@@ -58,8 +48,7 @@ pub(super) fn get_app_capabilities(app_id: &str) -> Vec<String> {
|
||||
"--cap-add=NET_BIND_SERVICE".to_string(),
|
||||
"--cap-add=NET_RAW".to_string(),
|
||||
],
|
||||
"nextcloud" | "btcpay-server" | "btcpayserver"
|
||||
| "portainer" => vec![
|
||||
"nextcloud" | "btcpay-server" | "btcpayserver" | "portainer" => vec![
|
||||
"--cap-add=CHOWN".to_string(),
|
||||
"--cap-add=SETUID".to_string(),
|
||||
"--cap-add=SETGID".to_string(),
|
||||
@@ -83,16 +72,17 @@ pub(super) fn get_app_capabilities(app_id: &str) -> Vec<String> {
|
||||
],
|
||||
// Bitcoin and Lightning need file ownership ops + NET_BIND_SERVICE for port binding
|
||||
// LND additionally needs NET_RAW for TLS certificate generation (netlinkrib interface enumeration)
|
||||
"bitcoin" | "bitcoin-core" | "bitcoin-knots" | "lnd" | "fedimint"
|
||||
| "fedimint-gateway" => vec![
|
||||
"--cap-add=CHOWN".to_string(),
|
||||
"--cap-add=FOWNER".to_string(),
|
||||
"--cap-add=SETUID".to_string(),
|
||||
"--cap-add=SETGID".to_string(),
|
||||
"--cap-add=DAC_OVERRIDE".to_string(),
|
||||
"--cap-add=NET_BIND_SERVICE".to_string(),
|
||||
"--cap-add=NET_RAW".to_string(),
|
||||
],
|
||||
"bitcoin" | "bitcoin-core" | "bitcoin-knots" | "lnd" | "fedimint" | "fedimint-gateway" => {
|
||||
vec![
|
||||
"--cap-add=CHOWN".to_string(),
|
||||
"--cap-add=FOWNER".to_string(),
|
||||
"--cap-add=SETUID".to_string(),
|
||||
"--cap-add=SETGID".to_string(),
|
||||
"--cap-add=DAC_OVERRIDE".to_string(),
|
||||
"--cap-add=NET_BIND_SERVICE".to_string(),
|
||||
"--cap-add=NET_RAW".to_string(),
|
||||
]
|
||||
}
|
||||
// Vaultwarden needs file ownership + NET_BIND_SERVICE (binds port 80 internally)
|
||||
"vaultwarden" => vec![
|
||||
"--cap-add=CHOWN".to_string(),
|
||||
@@ -164,8 +154,8 @@ pub(super) fn is_readonly_compatible(app_id: &str) -> bool {
|
||||
/// Returns (health-cmd, interval, retries) args to append to run_args.
|
||||
pub(super) fn get_health_check_args(app_id: &str, _rpc_pass: &str) -> Vec<String> {
|
||||
// bitcoin-cli reads the .cookie file from -datadir automatically (no plaintext creds needed)
|
||||
let btc_health = "bitcoin-cli -datadir=/home/bitcoin/.bitcoin getblockchaininfo || exit 1"
|
||||
.to_string();
|
||||
let btc_health =
|
||||
"bitcoin-cli -datadir=/home/bitcoin/.bitcoin getblockchaininfo || exit 1".to_string();
|
||||
let (cmd, interval, retries) = match app_id {
|
||||
"bitcoin" | "bitcoin-core" | "bitcoin-knots" => (btc_health.as_str(), "30s", "3"),
|
||||
"lnd" => ("lncli getinfo || exit 1", "30s", "3"),
|
||||
@@ -184,15 +174,13 @@ pub(super) fn get_health_check_args(app_id: &str, _rpc_pass: &str) -> Vec<String
|
||||
("curl -sf http://localhost:8000/ || exit 1", "60s", "3")
|
||||
}
|
||||
"nextcloud" => (
|
||||
"curl -sf http://localhost:80/status.php || exit 1",
|
||||
"30s",
|
||||
"3",
|
||||
),
|
||||
"homeassistant" | "home-assistant" => (
|
||||
"curl -sf http://localhost:8123/api/ || exit 1",
|
||||
"curl -s -o /dev/null http://localhost:80/status.php || exit 1",
|
||||
"30s",
|
||||
"3",
|
||||
),
|
||||
"homeassistant" | "home-assistant" => {
|
||||
("curl -sf http://localhost:8123/api/ || exit 1", "30s", "3")
|
||||
}
|
||||
"grafana" => (
|
||||
"curl -sf http://localhost:3000/api/health || exit 1",
|
||||
"30s",
|
||||
@@ -205,12 +193,13 @@ pub(super) fn get_health_check_args(app_id: &str, _rpc_pass: &str) -> Vec<String
|
||||
),
|
||||
"vaultwarden" => ("curl -sf http://localhost:80/alive || exit 1", "30s", "3"),
|
||||
"uptime-kuma" => ("curl -sf http://localhost:3001/ || exit 1", "30s", "3"),
|
||||
"filebrowser" => (
|
||||
"curl -sf http://localhost:80/health || exit 1",
|
||||
"filebrowser" => ("curl -sf http://localhost:80/health || exit 1", "30s", "3"),
|
||||
"botfights" => (
|
||||
"node -e \"fetch(\\\"http://127.0.0.1:9100/api/health\\\").then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))\"",
|
||||
"30s",
|
||||
"3",
|
||||
),
|
||||
"searxng" => ("curl -sf http://localhost:8080/ || exit 1", "30s", "3"),
|
||||
"searxng" => ("wget -q -O /dev/null http://localhost:8080/ || exit 1", "30s", "3"),
|
||||
"photoprism" => (
|
||||
"curl -sf http://localhost:2342/api/v1/status || exit 1",
|
||||
"60s",
|
||||
@@ -226,25 +215,14 @@ pub(super) fn get_health_check_args(app_id: &str, _rpc_pass: &str) -> Vec<String
|
||||
"30s",
|
||||
"3",
|
||||
),
|
||||
"portainer" => (
|
||||
"curl -sf http://localhost:9000/api/status || exit 1",
|
||||
"30s",
|
||||
"3",
|
||||
),
|
||||
"portainer" => return vec![],
|
||||
"ollama" => ("curl -sf http://localhost:11434/ || exit 1", "30s", "3"),
|
||||
"fedimint" => (
|
||||
"curl -sf http://localhost:8174/health || exit 1",
|
||||
"60s",
|
||||
"3",
|
||||
),
|
||||
"fedimint" => ("curl -sf http://localhost:8175/ || exit 1", "60s", "3"),
|
||||
"fedimint-gateway" => ("curl -sf http://localhost:8176/ || exit 1", "60s", "3"),
|
||||
"nostr-rs-relay" | "nostr-relay" => {
|
||||
("curl -sf http://localhost:8080/ || exit 1", "30s", "3")
|
||||
}
|
||||
"nginx-proxy-manager" => (
|
||||
"curl -sf http://localhost:81/api/ || exit 1",
|
||||
"30s",
|
||||
"3",
|
||||
),
|
||||
"nginx-proxy-manager" => ("curl -sf http://localhost:81/api/ || exit 1", "30s", "3"),
|
||||
"routstr" => (
|
||||
"curl -sf http://localhost:8000/v1/models || exit 1",
|
||||
"30s",
|
||||
@@ -316,51 +294,78 @@ pub(super) fn all_container_names(package_id: &str) -> Vec<String> {
|
||||
match package_id {
|
||||
// Bitcoin: multiple historical names
|
||||
"bitcoin" | "bitcoin-core" | "bitcoin-knots" => vec![
|
||||
"bitcoin-knots".into(), "bitcoin".into(), "bitcoin-core".into(),
|
||||
"archy-bitcoin-knots".into(), "archy-bitcoin".into(),
|
||||
"bitcoin-knots".into(),
|
||||
"bitcoin".into(),
|
||||
"bitcoin-core".into(),
|
||||
"archy-bitcoin-knots".into(),
|
||||
"archy-bitcoin".into(),
|
||||
"bitcoin-ui".into(),
|
||||
"archy-bitcoin-ui".into(),
|
||||
],
|
||||
// LND + UI
|
||||
"lnd" => vec!["lnd".into(), "archy-lnd".into(), "archy-lnd-ui".into()],
|
||||
// Electrumx: multiple aliases
|
||||
"electrumx" | "electrs" | "mempool-electrs" => vec![
|
||||
"electrumx".into(), "electrs".into(), "mempool-electrs".into(),
|
||||
"archy-electrumx".into(), "archy-electrs-ui".into(),
|
||||
"electrumx".into(),
|
||||
"electrs".into(),
|
||||
"mempool-electrs".into(),
|
||||
"archy-electrumx".into(),
|
||||
"archy-electrs-ui".into(),
|
||||
],
|
||||
// Mempool: multi-container stack
|
||||
"mempool" | "mempool-web" => vec![
|
||||
"mempool".into(), "mempool-web".into(), "mempool-api".into(),
|
||||
"archy-mempool-web".into(), "archy-mempool-api".into(),
|
||||
"archy-mempool-db".into(), "mysql-mempool".into(),
|
||||
"mempool".into(),
|
||||
"mempool-web".into(),
|
||||
"mempool-api".into(),
|
||||
"archy-mempool-web".into(),
|
||||
"archy-mempool-api".into(),
|
||||
"archy-mempool-db".into(),
|
||||
"mysql-mempool".into(),
|
||||
],
|
||||
// BTCPay: multi-container + multiple aliases
|
||||
"btcpay-server" | "btcpayserver" | "btcpay" => vec![
|
||||
"btcpay-server".into(), "btcpay".into(), "btcpayserver".into(),
|
||||
"archy-btcpay".into(), "archy-btcpay-db".into(), "archy-nbxplorer".into(),
|
||||
"btcpay-server".into(),
|
||||
"btcpay".into(),
|
||||
"btcpayserver".into(),
|
||||
"archy-btcpay".into(),
|
||||
"archy-btcpay-db".into(),
|
||||
"archy-nbxplorer".into(),
|
||||
],
|
||||
// Home Assistant: two naming conventions
|
||||
"homeassistant" | "home-assistant" => vec![
|
||||
"homeassistant".into(), "home-assistant".into(),
|
||||
"homeassistant".into(),
|
||||
"home-assistant".into(),
|
||||
"archy-homeassistant".into(),
|
||||
],
|
||||
// Fedimint: multiple related containers
|
||||
"fedimint" => vec![
|
||||
"fedimint".into(), "fedimintd".into(),
|
||||
"fedimint-ui".into(), "archy-fedimint".into(),
|
||||
"fedimint".into(),
|
||||
"fedimintd".into(),
|
||||
"fedimint-ui".into(),
|
||||
"archy-fedimint".into(),
|
||||
"fedimint-gateway".into(),
|
||||
],
|
||||
"fedimint-gateway" => vec!["fedimint-gateway".into()],
|
||||
// Immich: multi-container
|
||||
"immich" => vec![
|
||||
"immich_postgres".into(), "immich_redis".into(), "immich_server".into(),
|
||||
"immich_postgres".into(),
|
||||
"immich_redis".into(),
|
||||
"immich_server".into(),
|
||||
],
|
||||
// Penpot: multi-container
|
||||
"penpot" | "penpot-frontend" => vec![
|
||||
"penpot-postgres".into(), "penpot-valkey".into(),
|
||||
"penpot-backend".into(), "penpot-exporter".into(), "penpot-frontend".into(),
|
||||
"penpot-postgres".into(),
|
||||
"penpot-valkey".into(),
|
||||
"penpot-backend".into(),
|
||||
"penpot-exporter".into(),
|
||||
"penpot-frontend".into(),
|
||||
],
|
||||
"nostr-vpn" => vec!["nostr-vpn".into(), "archy-nostr-vpn".into()],
|
||||
"fips" => vec!["fips".into(), "archy-fips".into()],
|
||||
"nostr-vpn" => vec![
|
||||
"nostr-vpn".into(),
|
||||
"archy-nostr-vpn".into(),
|
||||
"archy-nostr-vpn-ui".into(),
|
||||
],
|
||||
"fips" => vec!["fips".into(), "archy-fips".into(), "archy-fips-ui".into()],
|
||||
"routstr" => vec!["routstr".into(), "archy-routstr".into()],
|
||||
// Default: exact name + archy- prefix
|
||||
_ => vec![base, archy],
|
||||
@@ -398,17 +403,13 @@ pub(super) fn get_data_dirs_for_app(package_id: &str) -> Vec<String> {
|
||||
format!("{}/mempool", base),
|
||||
format!("{}/mysql-mempool", base),
|
||||
format!("{}/electrumx", base),
|
||||
format!("{}/mempool-electrs", base),
|
||||
],
|
||||
"fedimint" => vec![
|
||||
format!("{}/fedimint", base),
|
||||
format!("{}/fedimint-gateway", base),
|
||||
],
|
||||
"fedimint-gateway" => vec![format!("{}/fedimint-gateway", base)],
|
||||
"immich" => vec![
|
||||
format!("{}/immich", base),
|
||||
format!("{}/immich-db", base),
|
||||
],
|
||||
"immich" => vec![format!("{}/immich", base), format!("{}/immich-db", base)],
|
||||
"penpot" | "penpot-frontend" => vec![
|
||||
format!("{}/penpot-assets", base),
|
||||
format!("{}/penpot-postgres", base),
|
||||
@@ -426,6 +427,24 @@ fn read_secret(name: &str, default: &str) -> String {
|
||||
.unwrap_or_else(|_| default.to_string())
|
||||
}
|
||||
|
||||
/// Read a secret or generate and persist a random one if it doesn't exist.
|
||||
pub(super) async fn read_or_generate_secret(name: &str) -> String {
|
||||
let path = format!("/var/lib/archipelago/secrets/{}", name);
|
||||
if let Ok(val) = tokio::fs::read_to_string(&path).await {
|
||||
let trimmed = val.trim().to_string();
|
||||
if !trimmed.is_empty() {
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
// Generate a 24-byte random password (hex-encoded = 48 chars)
|
||||
let mut buf = [0u8; 24];
|
||||
rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut buf);
|
||||
let secret = hex::encode(buf);
|
||||
let _ = tokio::fs::create_dir_all("/var/lib/archipelago/secrets").await;
|
||||
let _ = tokio::fs::write(&path, &secret).await;
|
||||
secret
|
||||
}
|
||||
|
||||
/// Read the node-level Nostr secret key (hex) for identity-aware apps.
|
||||
/// Returns empty string if not yet generated.
|
||||
fn read_nostr_secret_hex() -> String {
|
||||
@@ -464,7 +483,30 @@ pub(super) async fn get_app_config(
|
||||
None,
|
||||
None,
|
||||
),
|
||||
"bitcoin" | "bitcoin-core" | "bitcoin-knots" => (
|
||||
"bitcoin-core" => (
|
||||
vec![
|
||||
"8332:8332".to_string(),
|
||||
"8333:8333".to_string(),
|
||||
"28332:28332".to_string(),
|
||||
"28333:28333".to_string(),
|
||||
],
|
||||
vec!["/var/lib/archipelago/bitcoin:/home/bitcoin/.bitcoin".to_string()],
|
||||
vec![],
|
||||
None,
|
||||
// Vanilla bitcoin/bitcoin image has no entrypoint wrapper and reads
|
||||
// only what's in bitcoin.conf + argv. The shared bitcoin.conf
|
||||
// carries rpcauth; we inject the networking flags as CLI args so
|
||||
// RPC is reachable from the bitcoin-ui companion container.
|
||||
Some(vec![
|
||||
"-server=1".to_string(),
|
||||
"-rpcbind=0.0.0.0".to_string(),
|
||||
"-rpcallowip=0.0.0.0/0".to_string(),
|
||||
"-rpcport=8332".to_string(),
|
||||
"-printtoconsole=1".to_string(),
|
||||
"-datadir=/home/bitcoin/.bitcoin".to_string(),
|
||||
]),
|
||||
),
|
||||
"bitcoin" | "bitcoin-knots" => (
|
||||
vec![
|
||||
"8332:8332".to_string(),
|
||||
"8333:8333".to_string(),
|
||||
@@ -492,8 +534,6 @@ pub(super) async fn get_app_config(
|
||||
format!("--bitcoind.rpcuser={}", rpc_user),
|
||||
format!("--bitcoind.rpcpass={}", rpc_pass),
|
||||
"--bitcoind.rpchost=bitcoin-knots:8332".to_string(),
|
||||
"--bitcoind.zmqpubrawblock=tcp://bitcoin-knots:28332".to_string(),
|
||||
"--bitcoind.zmqpubrawtx=tcp://bitcoin-knots:28333".to_string(),
|
||||
"--rpclisten=0.0.0.0:10009".to_string(),
|
||||
"--restlisten=0.0.0.0:8080".to_string(),
|
||||
"--listen=0.0.0.0:9735".to_string(),
|
||||
@@ -507,7 +547,8 @@ pub(super) async fn get_app_config(
|
||||
"BTCPAY_PROTOCOL=http".to_string(),
|
||||
format!("BTCPAY_HOST={}:23000", host_ip),
|
||||
"BTCPAY_CHAINS=btc".to_string(),
|
||||
format!("BTCPAY_BTCRPCURL=http://{}:8332", host_ip),
|
||||
"BTCPAY_BTCEXPLORERURL=http://archy-nbxplorer:32838".to_string(),
|
||||
"BTCPAY_BTCRPCURL=http://bitcoin-knots:8332".to_string(),
|
||||
format!("BTCPAY_BTCRPCUSER={}", rpc_user),
|
||||
format!("BTCPAY_BTCRPCPASSWORD={}", rpc_pass),
|
||||
format!("BTCPAY_POSTGRES=User ID=btcpay;Password={};Host=archy-btcpay-db;Port=5432;Database=btcpay;Include Error Detail=true",
|
||||
@@ -519,7 +560,7 @@ pub(super) async fn get_app_config(
|
||||
"mempool" | "mempool-web" => (
|
||||
vec!["4080:8080".to_string()],
|
||||
vec![],
|
||||
vec![format!("BACKEND_MAINNET_HTTP_HOST={}", host_ip)],
|
||||
vec!["BACKEND_MAINNET_HTTP_HOST=mempool-api".to_string()],
|
||||
None,
|
||||
None,
|
||||
),
|
||||
@@ -531,9 +572,9 @@ pub(super) async fn get_app_config(
|
||||
"ELECTRUM_HOST=electrumx".to_string(),
|
||||
"ELECTRUM_PORT=50001".to_string(),
|
||||
"ELECTRUM_TLS_ENABLED=false".to_string(),
|
||||
format!("CORE_RPC_HOST={}", host_ip),
|
||||
"CORE_RPC_HOST=bitcoin-knots".to_string(),
|
||||
"CORE_RPC_PORT=8332".to_string(),
|
||||
format!("CORE_RPC_USERNAME={}", rpc_user),
|
||||
"CORE_RPC_USERNAME=archipelago".to_string(),
|
||||
format!("CORE_RPC_PASSWORD={}", rpc_pass),
|
||||
"DATABASE_ENABLED=true".to_string(),
|
||||
"DATABASE_HOST=archy-mempool-db".to_string(),
|
||||
@@ -545,15 +586,13 @@ pub(super) async fn get_app_config(
|
||||
None,
|
||||
),
|
||||
"electrumx" | "mempool-electrs" | "electrs" => {
|
||||
// Detect which bitcoin container is running for archy-net DNS resolution
|
||||
let bitcoin_host = detect_bitcoin_container_name();
|
||||
(
|
||||
vec!["50001:50001".to_string()],
|
||||
vec!["/var/lib/archipelago/electrumx:/data".to_string()],
|
||||
vec![
|
||||
format!(
|
||||
"DAEMON_URL=http://{}:{}@{}:8332/",
|
||||
rpc_user, rpc_pass, bitcoin_host
|
||||
"DAEMON_URL=http://{}:{}@bitcoin-knots:8332/",
|
||||
rpc_user, rpc_pass
|
||||
),
|
||||
"COIN=Bitcoin".to_string(),
|
||||
"DB_DIRECTORY=/data".to_string(),
|
||||
@@ -570,7 +609,7 @@ pub(super) async fn get_app_config(
|
||||
"MYSQL_DATABASE=mempool".to_string(),
|
||||
"MYSQL_USER=mempool".to_string(),
|
||||
format!("MYSQL_PASSWORD={}", read_secret("mempool-db-password", "mempoolpass")),
|
||||
format!("MYSQL_ROOT_PASSWORD={}", read_secret("mempool-db-root-password", "rootpass")),
|
||||
format!("MYSQL_ROOT_PASSWORD={}", read_secret("mysql-root-db-password", "rootpass")),
|
||||
],
|
||||
None,
|
||||
None,
|
||||
@@ -712,14 +751,14 @@ pub(super) async fn get_app_config(
|
||||
vec!["9000:9000".to_string()],
|
||||
vec![
|
||||
"/var/lib/archipelago/portainer:/data".to_string(),
|
||||
"/var/run/podman/podman.sock:/var/run/docker.sock".to_string(),
|
||||
"/run/user/1000/podman/podman.sock:/var/run/docker.sock".to_string(),
|
||||
],
|
||||
vec![],
|
||||
None,
|
||||
None,
|
||||
),
|
||||
"uptime-kuma" => (
|
||||
vec!["3001:3001".to_string()],
|
||||
vec!["3002:3001".to_string()],
|
||||
vec!["/var/lib/archipelago/uptime-kuma:/app/data".to_string()],
|
||||
vec!["TZ=UTC".to_string()],
|
||||
None,
|
||||
@@ -729,10 +768,17 @@ pub(super) async fn get_app_config(
|
||||
vec!["8240:8240".to_string()],
|
||||
vec!["/var/lib/archipelago/tailscale:/var/lib/tailscale".to_string()],
|
||||
vec!["TS_STATE_DIR=/var/lib/tailscale".to_string()],
|
||||
Some(
|
||||
"sh -c 'tailscale web --listen 0.0.0.0:8240 & exec tailscaled'".to_string(),
|
||||
),
|
||||
// Don't use custom_command (Option<String>) — install.rs passes
|
||||
// it as a SINGLE arg to podman, which then treats the whole
|
||||
// "sh -c 'tailscale web …'" string as the executable name and
|
||||
// fails: "executable file `sh -c 'tailscale web …'` not found".
|
||||
// custom_args (Option<Vec<String>>) splits properly.
|
||||
None,
|
||||
Some(vec![
|
||||
"sh".to_string(),
|
||||
"-c".to_string(),
|
||||
"tailscale web --listen 0.0.0.0:8240 & exec tailscaled".to_string(),
|
||||
]),
|
||||
),
|
||||
"fedimint" => (
|
||||
vec![
|
||||
@@ -751,7 +797,7 @@ pub(super) async fn get_app_config(
|
||||
"FM_BIND_UI=0.0.0.0:8175".to_string(),
|
||||
format!("FM_P2P_URL=fedimint://{}:8173", host_ip),
|
||||
format!("FM_API_URL=ws://{}:8174", host_ip),
|
||||
format!("FM_BITCOIND_URL=http://{}:8332", host_ip),
|
||||
"FM_BITCOIND_URL=http://bitcoin-knots:8332".to_string(),
|
||||
],
|
||||
None,
|
||||
Some(vec![
|
||||
@@ -760,36 +806,42 @@ pub(super) async fn get_app_config(
|
||||
format!("--bitcoind-url=http://{}:{}@bitcoin-knots:8332", rpc_user, rpc_pass),
|
||||
]),
|
||||
),
|
||||
"fedimint-gateway" => (
|
||||
vec!["8176:8176".to_string(), "9737:9737".to_string()],
|
||||
vec!["/var/lib/archipelago/fedimint-gateway:/data".to_string()],
|
||||
vec![],
|
||||
None,
|
||||
Some(vec![
|
||||
"gatewayd".to_string(),
|
||||
"--data-dir".to_string(),
|
||||
"/data".to_string(),
|
||||
"--listen".to_string(),
|
||||
"0.0.0.0:8176".to_string(),
|
||||
"--bcrypt-password-hash".to_string(),
|
||||
"$2y$10$t9YjjxkiktrlYvjajB/zgOMDnSNVg4HqrbDqh47u7Jf42whNdxNqC".to_string(),
|
||||
"--network".to_string(),
|
||||
"bitcoin".to_string(),
|
||||
"--bitcoind-url".to_string(),
|
||||
format!("http://{}:8332", host_ip),
|
||||
"--bitcoind-username".to_string(),
|
||||
rpc_user.to_string(),
|
||||
"--bitcoind-password".to_string(),
|
||||
rpc_pass.to_string(),
|
||||
"ldk".to_string(),
|
||||
"--ldk-lightning-port".to_string(),
|
||||
"9737".to_string(),
|
||||
"--ldk-alias".to_string(),
|
||||
"archipelago-gateway".to_string(),
|
||||
]),
|
||||
),
|
||||
"fedimint-gateway" => {
|
||||
let fedi_hash = read_secret(
|
||||
"fedimint-gateway-hash",
|
||||
"$2y$10$t9YjjxkiktrlYvjajB/zgOMDnSNVg4HqrbDqh47u7Jf42whNdxNqC",
|
||||
);
|
||||
(
|
||||
vec!["8176:8176".to_string(), "9737:9737".to_string()],
|
||||
vec!["/var/lib/archipelago/fedimint-gateway:/data".to_string()],
|
||||
vec![],
|
||||
None,
|
||||
Some(vec![
|
||||
"gatewayd".to_string(),
|
||||
"--data-dir".to_string(),
|
||||
"/data".to_string(),
|
||||
"--listen".to_string(),
|
||||
"0.0.0.0:8176".to_string(),
|
||||
"--bcrypt-password-hash".to_string(),
|
||||
fedi_hash,
|
||||
"--network".to_string(),
|
||||
"bitcoin".to_string(),
|
||||
"--bitcoind-url".to_string(),
|
||||
"http://bitcoin-knots:8332".to_string(),
|
||||
"--bitcoind-username".to_string(),
|
||||
rpc_user.to_string(),
|
||||
"--bitcoind-password".to_string(),
|
||||
rpc_pass.to_string(),
|
||||
"ldk".to_string(),
|
||||
"--ldk-lightning-port".to_string(),
|
||||
"9737".to_string(),
|
||||
"--ldk-alias".to_string(),
|
||||
"archipelago-gateway".to_string(),
|
||||
]),
|
||||
)
|
||||
}
|
||||
"indeedhub" => (
|
||||
vec!["8190:3000".to_string()],
|
||||
vec!["7778:7777".to_string()],
|
||||
vec![],
|
||||
vec![
|
||||
"NODE_ENV=production".to_string(),
|
||||
@@ -834,18 +886,15 @@ pub(super) async fn get_app_config(
|
||||
vec!["/var/lib/archipelago/nostr-vpn:/root/.config/nvpn".to_string()],
|
||||
env,
|
||||
None,
|
||||
Some(vec![
|
||||
"start".to_string(),
|
||||
"--daemon".to_string(),
|
||||
]),
|
||||
None,
|
||||
)
|
||||
}
|
||||
"fips" => {
|
||||
let nsec = read_nostr_secret_hex();
|
||||
let mut env = vec![];
|
||||
if !nsec.is_empty() {
|
||||
env.push(format!("FIPS_NOSTR_SECRET={}", nsec));
|
||||
env.push(format!("FIPS_NOSTR_PUBKEY={}", read_nostr_pubkey_hex()));
|
||||
env.push(format!("FIPS_NSEC={}", nsec));
|
||||
env.push(format!("FIPS_NPUB={}", read_nostr_pubkey_hex()));
|
||||
}
|
||||
(
|
||||
vec![
|
||||
@@ -873,6 +922,69 @@ pub(super) async fn get_app_config(
|
||||
None,
|
||||
None,
|
||||
),
|
||||
_ => (vec![], vec![], vec![], None, None),
|
||||
"botfights" => {
|
||||
let jwt_secret = read_or_generate_secret("botfights-jwt").await;
|
||||
(
|
||||
vec!["9100:9100".to_string()],
|
||||
vec!["/var/lib/archipelago/botfights:/app/server/data".to_string()],
|
||||
vec![
|
||||
"NODE_ENV=production".to_string(),
|
||||
"PORT=9100".to_string(),
|
||||
format!("JWT_SECRET={}", jwt_secret),
|
||||
"FIGHT_LOOP_ENABLED=true".to_string(),
|
||||
"ARCHY_EMBEDDED=1".to_string(),
|
||||
],
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
// Gitea binds to 3001 internally. Nginx on port 3000 strips X-Frame-Options
|
||||
// so Gitea works in Archipelago's iframe. See nginx-gitea-iframe.conf.
|
||||
"gitea" => (
|
||||
vec!["3001:3000".to_string(), "2222:22".to_string()],
|
||||
vec![
|
||||
"/var/lib/archipelago/gitea/data:/data".to_string(),
|
||||
"/var/lib/archipelago/gitea/config:/etc/gitea".to_string(),
|
||||
],
|
||||
vec![
|
||||
"GITEA__database__DB_TYPE=sqlite3".to_string(),
|
||||
"GITEA__server__SSH_PORT=2222".to_string(),
|
||||
"GITEA__server__SSH_LISTEN_PORT=22".to_string(),
|
||||
"GITEA__server__LFS_START_SERVER=true".to_string(),
|
||||
"GITEA__packages__ENABLED=true".to_string(),
|
||||
"GITEA__repository__ENABLE_PUSH_CREATE_USER=true".to_string(),
|
||||
"GITEA__repository__ENABLE_PUSH_CREATE_ORG=true".to_string(),
|
||||
"GITEA__security__X_FRAME_OPTIONS=".to_string(),
|
||||
],
|
||||
None,
|
||||
None,
|
||||
),
|
||||
_ => {
|
||||
// Unknown app: try to load config from /var/lib/archipelago/app-configs/{id}.json
|
||||
// This allows dynamic apps from the remote catalog to be installed
|
||||
// without hardcoding their config here.
|
||||
let config_path = format!("/var/lib/archipelago/app-configs/{}.json", app_id);
|
||||
if let Ok(data) = tokio::fs::read_to_string(&config_path).await {
|
||||
if let Ok(cfg) = serde_json::from_str::<serde_json::Value>(&data) {
|
||||
let ports = cfg.get("ports")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
|
||||
.unwrap_or_default();
|
||||
let volumes = cfg.get("volumes")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
|
||||
.unwrap_or_default();
|
||||
let env_vars = cfg.get("env")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
|
||||
.unwrap_or_default();
|
||||
tracing::info!("Loaded dynamic config for app: {}", app_id);
|
||||
return (ports, volumes, env_vars, None, None);
|
||||
}
|
||||
}
|
||||
// No config found — use minimal defaults (container's own EXPOSE/VOLUME)
|
||||
tracing::warn!("No config found for app: {} — using minimal defaults", app_id);
|
||||
(vec![], vec![], vec![], None, None)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ pub(super) async fn detect_running_deps() -> Result<RunningDeps> {
|
||||
let is_running = |names: &[&str]| {
|
||||
running.lines().any(|l| {
|
||||
let name = l.trim();
|
||||
names.iter().any(|n| name == *n)
|
||||
names.contains(&name)
|
||||
})
|
||||
};
|
||||
|
||||
@@ -42,12 +42,10 @@ pub(super) async fn detect_running_deps() -> Result<RunningDeps> {
|
||||
/// Returns an error with a user-friendly message if dependencies are missing.
|
||||
pub(super) fn check_install_deps(package_id: &str, deps: &RunningDeps) -> Result<()> {
|
||||
match package_id {
|
||||
"electrumx" | "mempool-electrs" | "electrs" if !deps.has_bitcoin => {
|
||||
Err(anyhow::anyhow!(
|
||||
"ElectrumX requires a running Bitcoin node (Bitcoin Knots). \
|
||||
"electrumx" | "mempool-electrs" | "electrs" if !deps.has_bitcoin => Err(anyhow::anyhow!(
|
||||
"ElectrumX requires a running Bitcoin node (Bitcoin Knots). \
|
||||
Please install and start Bitcoin Knots first."
|
||||
))
|
||||
}
|
||||
)),
|
||||
"lnd" if !deps.has_bitcoin => Err(anyhow::anyhow!(
|
||||
"LND requires a running Bitcoin node (Bitcoin Knots). \
|
||||
Please install and start Bitcoin Knots first."
|
||||
@@ -70,10 +68,10 @@ pub(super) fn check_install_deps(package_id: &str, deps: &RunningDeps) -> Result
|
||||
missing.join(" and ")
|
||||
))
|
||||
}
|
||||
"fedimint" if !deps.has_bitcoin => Err(anyhow::anyhow!(
|
||||
"Fedimint requires a running Bitcoin node (Bitcoin Knots). \
|
||||
Please install and start Bitcoin Knots first."
|
||||
)),
|
||||
"fedimint" if !deps.has_bitcoin => {
|
||||
info!("Fedimint installing without local Bitcoin node — configure remote Bitcoin RPC in Fedimint guardian setup");
|
||||
Ok(())
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -144,9 +142,7 @@ pub(super) fn startup_order(package_id: &str) -> &'static [&'static str] {
|
||||
|
||||
/// Sort a list of container names according to the dependency-aware startup
|
||||
/// order for the given app. Unknown containers sort to the end.
|
||||
pub(super) async fn ordered_containers_for_start(
|
||||
package_id: &str,
|
||||
) -> Result<Vec<String>> {
|
||||
pub(super) async fn ordered_containers_for_start(package_id: &str) -> Result<Vec<String>> {
|
||||
let containers = get_containers_for_app(package_id).await?;
|
||||
if containers.is_empty() {
|
||||
return Ok(vec![format!("archy-{}", package_id)]);
|
||||
@@ -159,12 +155,7 @@ pub(super) async fn ordered_containers_for_start(
|
||||
order
|
||||
};
|
||||
let mut sorted = containers;
|
||||
sorted.sort_by_key(|c| {
|
||||
effective_order
|
||||
.iter()
|
||||
.position(|o| *o == c)
|
||||
.unwrap_or(99)
|
||||
});
|
||||
sorted.sort_by_key(|c| effective_order.iter().position(|o| *o == c).unwrap_or(99));
|
||||
Ok(sorted)
|
||||
}
|
||||
|
||||
@@ -179,12 +170,18 @@ pub(super) fn configure_fedimint_lnd(
|
||||
rpc_pass: &str,
|
||||
) {
|
||||
let lnd_cert = "/var/lib/archipelago/lnd/tls.cert";
|
||||
let lnd_macaroon =
|
||||
"/var/lib/archipelago/lnd/data/chain/bitcoin/mainnet/admin.macaroon";
|
||||
if std::path::Path::new(lnd_cert).exists()
|
||||
&& std::path::Path::new(lnd_macaroon).exists()
|
||||
{
|
||||
let lnd_macaroon = "/var/lib/archipelago/lnd/data/chain/bitcoin/mainnet/admin.macaroon";
|
||||
if std::path::Path::new(lnd_cert).exists() && std::path::Path::new(lnd_macaroon).exists() {
|
||||
info!("LND detected with credentials — configuring gateway in lnd mode");
|
||||
|
||||
// Read bcrypt hash from secrets file, fall back to default
|
||||
let fedi_hash =
|
||||
std::fs::read_to_string("/var/lib/archipelago/secrets/fedimint-gateway-hash")
|
||||
.map(|s| s.trim().to_string())
|
||||
.unwrap_or_else(|_| {
|
||||
"$2y$10$t9YjjxkiktrlYvjajB/zgOMDnSNVg4HqrbDqh47u7Jf42whNdxNqC".to_string()
|
||||
});
|
||||
|
||||
ports.retain(|p| p != "9737:9737");
|
||||
volumes.push(format!("{}:/lnd/tls.cert:ro", lnd_cert));
|
||||
volumes.push(format!("{}:/lnd/admin.macaroon:ro", lnd_macaroon));
|
||||
@@ -195,7 +192,7 @@ pub(super) fn configure_fedimint_lnd(
|
||||
"--listen".to_string(),
|
||||
"0.0.0.0:8176".to_string(),
|
||||
"--bcrypt-password-hash".to_string(),
|
||||
"$2y$10$t9YjjxkiktrlYvjajB/zgOMDnSNVg4HqrbDqh47u7Jf42whNdxNqC".to_string(),
|
||||
fedi_hash,
|
||||
"--network".to_string(),
|
||||
"bitcoin".to_string(),
|
||||
"--bitcoind-url".to_string(),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,4 @@
|
||||
mod async_lifecycle;
|
||||
mod config;
|
||||
mod dependencies;
|
||||
mod install;
|
||||
@@ -5,7 +6,9 @@ mod lifecycle;
|
||||
mod progress;
|
||||
mod runtime;
|
||||
mod stacks;
|
||||
mod update;
|
||||
mod validation;
|
||||
|
||||
// Re-export items needed by sibling modules (container.rs, security.rs)
|
||||
// Re-export items needed by sibling modules (container.rs, security.rs, transitional.rs)
|
||||
pub(in crate::api::rpc) use install::install_log;
|
||||
pub(super) use validation::validate_app_id;
|
||||
|
||||
@@ -2,25 +2,60 @@
|
||||
|
||||
use crate::api::rpc::RpcHandler;
|
||||
use crate::data_model::{
|
||||
Description, InstallProgress, Manifest, PackageDataEntry, PackageState, StaticFiles,
|
||||
Description, InstallPhase, InstallProgress, Manifest, PackageDataEntry, PackageState,
|
||||
StaticFiles,
|
||||
};
|
||||
|
||||
impl RpcHandler {
|
||||
/// Set install progress for a package and broadcast the update.
|
||||
/// Creates a minimal package entry if one doesn't exist yet.
|
||||
pub(super) async fn set_install_progress(
|
||||
&self,
|
||||
package_id: &str,
|
||||
downloaded: u64,
|
||||
size: u64,
|
||||
) {
|
||||
///
|
||||
/// Prefer `set_install_phase` — this byte-counter API is kept for
|
||||
/// the rare case where the pull stream actually parses, but podman
|
||||
/// almost never emits parseable progress on a piped stderr.
|
||||
pub(super) async fn set_install_progress(&self, package_id: &str, downloaded: u64, size: u64) {
|
||||
let (mut data, _rev) = self.state_manager.get_snapshot().await;
|
||||
let entry = data
|
||||
.package_data
|
||||
.entry(package_id.to_string())
|
||||
.or_insert_with(|| create_installing_entry(package_id));
|
||||
entry.state = PackageState::Installing;
|
||||
entry.install_progress = Some(InstallProgress { size, downloaded });
|
||||
let existing_phase = entry.install_progress.as_ref().and_then(|p| p.phase);
|
||||
entry.install_progress = Some(InstallProgress {
|
||||
size,
|
||||
downloaded,
|
||||
phase: existing_phase,
|
||||
});
|
||||
self.state_manager.update_data(data).await;
|
||||
}
|
||||
|
||||
/// Set the install pipeline phase and broadcast. This is the
|
||||
/// primary progress signal — the UI maps each phase to a
|
||||
/// percentage and a user-facing label. Byte counters are retained
|
||||
/// for the rare case podman emits parseable progress.
|
||||
pub(super) async fn set_install_phase(&self, package_id: &str, phase: InstallPhase) {
|
||||
let (mut data, _rev) = self.state_manager.get_snapshot().await;
|
||||
let entry = data
|
||||
.package_data
|
||||
.entry(package_id.to_string())
|
||||
.or_insert_with(|| create_installing_entry(package_id));
|
||||
// Preparing / PullingImage / CreatingContainer / StartingContainer /
|
||||
// WaitingHealthy / PostInstall all map to the Installing state.
|
||||
// Updates use Updating state — the wrapper has already flipped
|
||||
// state to Updating, so don't clobber it.
|
||||
if entry.state != PackageState::Updating {
|
||||
entry.state = PackageState::Installing;
|
||||
}
|
||||
let (size, downloaded) = entry
|
||||
.install_progress
|
||||
.as_ref()
|
||||
.map(|p| (p.size, p.downloaded))
|
||||
.unwrap_or((0, 0));
|
||||
entry.install_progress = Some(InstallProgress {
|
||||
size,
|
||||
downloaded,
|
||||
phase: Some(phase),
|
||||
});
|
||||
self.state_manager.update_data(data).await;
|
||||
}
|
||||
|
||||
@@ -33,6 +68,18 @@ impl RpcHandler {
|
||||
self.state_manager.update_data(data).await;
|
||||
}
|
||||
|
||||
/// Set the uninstall stage label so the UI can show what's happening
|
||||
/// instead of a generic spinner. Each call broadcasts a state change
|
||||
/// — call sparingly (one per pipeline phase, not per container).
|
||||
pub(super) async fn set_uninstall_stage(&self, package_id: &str, stage: &str) {
|
||||
let (mut data, _rev) = self.state_manager.get_snapshot().await;
|
||||
if let Some(entry) = data.package_data.get_mut(package_id) {
|
||||
entry.uninstall_stage = Some(stage.to_string());
|
||||
entry.state = crate::data_model::PackageState::Removing;
|
||||
}
|
||||
self.state_manager.update_data(data).await;
|
||||
}
|
||||
|
||||
/// Update install progress (static method for use in async closures).
|
||||
pub(super) async fn update_install_progress(
|
||||
state_manager: &crate::state::StateManager,
|
||||
@@ -45,9 +92,11 @@ impl RpcHandler {
|
||||
.package_data
|
||||
.entry(package_id.to_string())
|
||||
.or_insert_with(|| create_installing_entry(package_id));
|
||||
let existing_phase = entry.install_progress.as_ref().and_then(|p| p.phase);
|
||||
entry.install_progress = Some(InstallProgress {
|
||||
size: total,
|
||||
downloaded,
|
||||
phase: existing_phase,
|
||||
});
|
||||
state_manager.update_data(data).await;
|
||||
}
|
||||
@@ -62,7 +111,11 @@ fn create_installing_entry(package_id: &str) -> PackageDataEntry {
|
||||
static_files: StaticFiles {
|
||||
license: String::new(),
|
||||
instructions: String::new(),
|
||||
icon: format!("/assets/img/app-icons/{}.png", package_id),
|
||||
// Empty icon: hardcoding `<id>.png` is wrong for apps that use
|
||||
// `.svg` or `.webp` assets and produces a broken-image flicker.
|
||||
// The frontend's `icon` computed falls through to the curated
|
||||
// map which has correct extensions for known apps.
|
||||
icon: String::new(),
|
||||
},
|
||||
manifest: Manifest {
|
||||
id: package_id.to_string(),
|
||||
@@ -86,6 +139,8 @@ fn create_installing_entry(package_id: &str) -> PackageDataEntry {
|
||||
},
|
||||
installed: None,
|
||||
install_progress: None,
|
||||
uninstall_stage: None,
|
||||
available_update: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,25 +169,19 @@ fn parse_size_value(s: &str) -> Option<u64> {
|
||||
let s = s.trim();
|
||||
|
||||
let (num_str, multiplier) = if let Some(pos) = s.rfind("GiB") {
|
||||
(
|
||||
s[..pos].trim().split_whitespace().last()?,
|
||||
1024 * 1024 * 1024,
|
||||
)
|
||||
(s[..pos].split_whitespace().last()?, 1024 * 1024 * 1024)
|
||||
} else if let Some(pos) = s.rfind("MiB") {
|
||||
(s[..pos].trim().split_whitespace().last()?, 1024 * 1024)
|
||||
(s[..pos].split_whitespace().last()?, 1024 * 1024)
|
||||
} else if let Some(pos) = s.rfind("KiB") {
|
||||
(s[..pos].trim().split_whitespace().last()?, 1024)
|
||||
(s[..pos].split_whitespace().last()?, 1024)
|
||||
} else if let Some(pos) = s.rfind("GB") {
|
||||
(
|
||||
s[..pos].trim().split_whitespace().last()?,
|
||||
1_000_000_000,
|
||||
)
|
||||
(s[..pos].split_whitespace().last()?, 1_000_000_000)
|
||||
} else if let Some(pos) = s.rfind("MB") {
|
||||
(s[..pos].trim().split_whitespace().last()?, 1_000_000)
|
||||
(s[..pos].split_whitespace().last()?, 1_000_000)
|
||||
} else if let Some(pos) = s.rfind("KB") {
|
||||
(s[..pos].trim().split_whitespace().last()?, 1_000)
|
||||
(s[..pos].split_whitespace().last()?, 1_000)
|
||||
} else if let Some(pos) = s.rfind('B') {
|
||||
(s[..pos].trim().split_whitespace().last()?, 1)
|
||||
(s[..pos].split_whitespace().last()?, 1)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -3,19 +3,24 @@ use super::dependencies::ordered_containers_for_start;
|
||||
use super::install::install_log;
|
||||
use super::validation::validate_app_id;
|
||||
use crate::api::rpc::RpcHandler;
|
||||
use crate::data_model::PackageState;
|
||||
use anyhow::{Context, Result};
|
||||
use std::sync::Arc;
|
||||
use tracing::warn;
|
||||
|
||||
/// Per-container graceful shutdown timeout in seconds.
|
||||
/// Bitcoin Core needs 600s to flush UTXO set, LND 330s for channel state,
|
||||
/// indexers 300s for index flush, databases 120s for WAL/transaction commit.
|
||||
pub fn stop_timeout_secs(container_name: &str) -> &'static str {
|
||||
let id = container_name.strip_prefix("archy-").unwrap_or(container_name);
|
||||
let id = container_name
|
||||
.strip_prefix("archy-")
|
||||
.unwrap_or(container_name);
|
||||
match id {
|
||||
"bitcoin-knots" | "bitcoin-core" | "bitcoin" => "600",
|
||||
"lnd" => "330",
|
||||
"electrumx" | "electrs" | "mempool-electrs" => "300",
|
||||
"btcpay-db" | "mempool-db" | "penpot-postgres" | "immich_postgres"
|
||||
| "nextcloud-db" | "endurain-db" => "120",
|
||||
"btcpay-db" | "mempool-db" | "penpot-postgres" | "immich_postgres" | "nextcloud-db"
|
||||
| "endurain-db" => "120",
|
||||
"btcpay-server" | "nbxplorer" | "fedimint" | "fedimint-gateway" => "60",
|
||||
_ => "30",
|
||||
}
|
||||
@@ -23,6 +28,12 @@ pub fn stop_timeout_secs(container_name: &str) -> &'static str {
|
||||
|
||||
impl RpcHandler {
|
||||
/// Start a package: start all containers in dependency order.
|
||||
///
|
||||
/// Returns immediately with `{ "status": "starting" }` after flipping
|
||||
/// the package state to `Starting` in the StateManager. The actual
|
||||
/// podman-start sequence + post-start exit verification runs in a
|
||||
/// background task. On success the state becomes `Running`; on error
|
||||
/// it reverts to the pre-transition state.
|
||||
pub(in crate::api::rpc) async fn handle_package_start(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
@@ -40,79 +51,52 @@ impl RpcHandler {
|
||||
return Err(anyhow::anyhow!("No containers found for {}", package_id));
|
||||
}
|
||||
|
||||
// Clear user-stopped flag — user explicitly started this app
|
||||
// Clear user-stopped flag — user explicitly started this app.
|
||||
// Must happen BEFORE the spawn (ordering contract with crash recovery).
|
||||
crate::crash_recovery::clear_user_stopped(&self.config.data_dir, package_id).await;
|
||||
for name in &to_start {
|
||||
crate::crash_recovery::clear_user_stopped(&self.config.data_dir, name).await;
|
||||
}
|
||||
|
||||
install_log(&format!("START: {} (containers: {:?})", package_id, to_start)).await;
|
||||
let mut errors = Vec::new();
|
||||
for (i, name) in to_start.iter().enumerate() {
|
||||
// Brief delay between dependent containers to allow initialization
|
||||
if i > 0 {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
|
||||
}
|
||||
tracing::info!("Starting container: {}", name);
|
||||
let out = tokio::process::Command::new("podman")
|
||||
.args(["start", name])
|
||||
.output()
|
||||
.await
|
||||
.context(format!("Failed to exec podman start {}", name))?;
|
||||
if !out.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
|
||||
tracing::error!("Failed to start {}: {}", name, stderr);
|
||||
install_log(&format!("START FAIL: {} — {}", name, stderr)).await;
|
||||
errors.push(format!("{}: {}", name, stderr));
|
||||
}
|
||||
}
|
||||
let package_id_owned = package_id.to_string();
|
||||
let state_manager = Arc::clone(&self.state_manager);
|
||||
let pre_state =
|
||||
flip_package_state(&state_manager, &package_id_owned, PackageState::Starting).await;
|
||||
|
||||
if !errors.is_empty() {
|
||||
return Err(anyhow::anyhow!("Start failed: {}", errors.join("; ")));
|
||||
}
|
||||
install_log(&format!(
|
||||
"START: {} (containers: {:?})",
|
||||
package_id_owned, to_start
|
||||
))
|
||||
.await;
|
||||
|
||||
// Verify containers actually reached running state (podman start can
|
||||
// succeed even if the container exits immediately after)
|
||||
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
|
||||
for name in &to_start {
|
||||
let status = tokio::process::Command::new("podman")
|
||||
.args(["inspect", name, "--format", "{{.State.Status}}"])
|
||||
.output()
|
||||
.await;
|
||||
if let Ok(o) = status {
|
||||
let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
|
||||
if state == "exited" {
|
||||
let logs = tokio::process::Command::new("podman")
|
||||
.args(["logs", "--tail", "5", name])
|
||||
.output()
|
||||
tokio::spawn(async move {
|
||||
match do_package_start(&to_start).await {
|
||||
Ok(()) => {
|
||||
set_package_state(&state_manager, &package_id_owned, PackageState::Running)
|
||||
.await;
|
||||
let log_text = logs
|
||||
.map(|o| {
|
||||
let combined = format!(
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&o.stdout),
|
||||
String::from_utf8_lossy(&o.stderr)
|
||||
);
|
||||
combined.chars().take(200).collect::<String>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
tracing::error!("Container {} exited after start: {}", name, log_text);
|
||||
install_log(&format!("START EXITED: {} — {}", name, log_text)).await;
|
||||
errors.push(format!("{}: exited after start", name));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("package.start {} failed: {:#}", package_id_owned, e);
|
||||
install_log(&format!("START FAIL: {} — {:#}", package_id_owned, e)).await;
|
||||
if let Some(prev) = pre_state {
|
||||
set_package_state(&state_manager, &package_id_owned, prev).await;
|
||||
} else {
|
||||
warn!(
|
||||
"package.start {}: no pre-state recorded; relying on next scan",
|
||||
package_id_owned
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if !errors.is_empty() {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Containers exited after start: {}",
|
||||
errors.join("; ")
|
||||
));
|
||||
}
|
||||
Ok(serde_json::Value::Null)
|
||||
Ok(serde_json::json!({ "status": "starting" }))
|
||||
}
|
||||
|
||||
/// Stop a package: mark as user-stopped and stop all containers.
|
||||
///
|
||||
/// Returns immediately with `{ "status": "stopping" }`. podman stop
|
||||
/// (up to 600s for bitcoin-core) runs in the background.
|
||||
pub(in crate::api::rpc) async fn handle_package_stop(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
@@ -130,35 +114,48 @@ impl RpcHandler {
|
||||
return Err(anyhow::anyhow!("No containers found for {}", package_id));
|
||||
}
|
||||
|
||||
install_log(&format!("STOP: {} (containers: {:?})", package_id, containers)).await;
|
||||
// Mark as user-stopped so health monitor and crash recovery don't auto-restart
|
||||
// Mark as user-stopped BEFORE the spawn so health monitor and
|
||||
// crash recovery don't auto-restart mid-flight. Ordering is
|
||||
// load-bearing — see runtime.rs:145-148 original note.
|
||||
crate::crash_recovery::mark_user_stopped(&self.config.data_dir, package_id).await;
|
||||
for name in &containers {
|
||||
crate::crash_recovery::mark_user_stopped(&self.config.data_dir, name).await;
|
||||
}
|
||||
|
||||
let mut errors = Vec::new();
|
||||
for name in &containers {
|
||||
tracing::info!("Stopping container: {} (timeout: {}s)", name, stop_timeout_secs(name));
|
||||
let out = tokio::process::Command::new("podman")
|
||||
.args(["stop", "-t", stop_timeout_secs(name), name])
|
||||
.output()
|
||||
.await
|
||||
.context(format!("Failed to exec podman stop {}", name))?;
|
||||
if !out.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
|
||||
tracing::error!("Failed to stop {}: {}", name, stderr);
|
||||
errors.push(format!("{}: {}", name, stderr));
|
||||
}
|
||||
}
|
||||
let package_id_owned = package_id.to_string();
|
||||
let state_manager = Arc::clone(&self.state_manager);
|
||||
let pre_state =
|
||||
flip_package_state(&state_manager, &package_id_owned, PackageState::Stopping).await;
|
||||
|
||||
if !errors.is_empty() {
|
||||
return Err(anyhow::anyhow!("Stop failed: {}", errors.join("; ")));
|
||||
}
|
||||
Ok(serde_json::Value::Null)
|
||||
install_log(&format!(
|
||||
"STOP: {} (containers: {:?})",
|
||||
package_id_owned, containers
|
||||
))
|
||||
.await;
|
||||
|
||||
tokio::spawn(async move {
|
||||
match do_package_stop(&containers).await {
|
||||
Ok(()) => {
|
||||
set_package_state(&state_manager, &package_id_owned, PackageState::Stopped)
|
||||
.await;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("package.stop {} failed: {:#}", package_id_owned, e);
|
||||
install_log(&format!("STOP FAIL: {} — {:#}", package_id_owned, e)).await;
|
||||
if let Some(prev) = pre_state {
|
||||
set_package_state(&state_manager, &package_id_owned, prev).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(serde_json::json!({ "status": "stopping" }))
|
||||
}
|
||||
|
||||
/// Restart a package: restart all containers.
|
||||
///
|
||||
/// Returns immediately with `{ "status": "restarting" }`. The restart
|
||||
/// (up to 600s per container for bitcoin-core) runs in the background.
|
||||
pub(in crate::api::rpc) async fn handle_package_restart(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
@@ -176,45 +173,42 @@ impl RpcHandler {
|
||||
return Err(anyhow::anyhow!("No containers found for {}", package_id));
|
||||
}
|
||||
|
||||
install_log(&format!("RESTART: {} (containers: {:?})", package_id, containers)).await;
|
||||
let mut errors = Vec::new();
|
||||
// Restart does not mark user-stopped; user wants the app to keep
|
||||
// running. Clear any lingering marker so downstream layers don't
|
||||
// interpret the brief podman stop as user intent.
|
||||
crate::crash_recovery::clear_user_stopped(&self.config.data_dir, package_id).await;
|
||||
for name in &containers {
|
||||
tracing::info!("Restarting container: {}", name);
|
||||
let out = tokio::process::Command::new("podman")
|
||||
.args(["restart", "-t", stop_timeout_secs(name), name])
|
||||
.output()
|
||||
.await
|
||||
.context(format!("Failed to exec podman restart {}", name))?;
|
||||
crate::crash_recovery::clear_user_stopped(&self.config.data_dir, name).await;
|
||||
}
|
||||
|
||||
if !out.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
|
||||
tracing::warn!("podman restart {} failed: {}, trying stop+start", name, stderr);
|
||||
let package_id_owned = package_id.to_string();
|
||||
let state_manager = Arc::clone(&self.state_manager);
|
||||
let pre_state =
|
||||
flip_package_state(&state_manager, &package_id_owned, PackageState::Restarting).await;
|
||||
|
||||
// Fallback: stop then start (handles rootless podman loopback issues)
|
||||
let _ = tokio::process::Command::new("podman")
|
||||
.args(["stop", "-t", stop_timeout_secs(name), name])
|
||||
.output()
|
||||
.await;
|
||||
let start_out = tokio::process::Command::new("podman")
|
||||
.args(["start", name])
|
||||
.output()
|
||||
.await
|
||||
.context(format!("Failed to exec podman start {}", name))?;
|
||||
install_log(&format!(
|
||||
"RESTART: {} (containers: {:?})",
|
||||
package_id_owned, containers
|
||||
))
|
||||
.await;
|
||||
|
||||
if !start_out.status.success() {
|
||||
let start_err = String::from_utf8_lossy(&start_out.stderr).trim().to_string();
|
||||
tracing::error!("stop+start {} also failed: {}", name, start_err);
|
||||
errors.push(format!("{}: {}", name, start_err));
|
||||
} else {
|
||||
tracing::info!("Restarted {} via stop+start fallback", name);
|
||||
tokio::spawn(async move {
|
||||
match do_package_restart(&containers).await {
|
||||
Ok(()) => {
|
||||
set_package_state(&state_manager, &package_id_owned, PackageState::Running)
|
||||
.await;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("package.restart {} failed: {:#}", package_id_owned, e);
|
||||
install_log(&format!("RESTART FAIL: {} — {:#}", package_id_owned, e)).await;
|
||||
if let Some(prev) = pre_state {
|
||||
set_package_state(&state_manager, &package_id_owned, prev).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if !errors.is_empty() {
|
||||
return Err(anyhow::anyhow!("Restart failed: {}", errors.join("; ")));
|
||||
}
|
||||
Ok(serde_json::Value::Null)
|
||||
Ok(serde_json::json!({ "status": "restarting" }))
|
||||
}
|
||||
|
||||
/// Uninstall a package: stop and remove all related containers, clean data.
|
||||
@@ -237,12 +231,28 @@ impl RpcHandler {
|
||||
if containers_to_remove.is_empty() {
|
||||
tracing::warn!("Uninstall {}: no containers found", package_id);
|
||||
}
|
||||
let total = containers_to_remove.len();
|
||||
|
||||
let mut stopped = 0u32;
|
||||
let mut removed = 0u32;
|
||||
let mut errors = Vec::new();
|
||||
|
||||
for name in &containers_to_remove {
|
||||
self.set_uninstall_stage(
|
||||
package_id,
|
||||
&if total > 0 {
|
||||
format!("Stopping containers (0/{})", total)
|
||||
} else {
|
||||
"Cleaning up".to_string()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
for (i, name) in containers_to_remove.iter().enumerate() {
|
||||
self.set_uninstall_stage(
|
||||
package_id,
|
||||
&format!("Stopping containers ({}/{})", i + 1, total),
|
||||
)
|
||||
.await;
|
||||
tracing::info!("Uninstall {}: stopping container {}", package_id, name);
|
||||
let stop_out = tokio::process::Command::new("podman")
|
||||
.args(["stop", "-t", stop_timeout_secs(name), name])
|
||||
@@ -260,12 +270,7 @@ impl RpcHandler {
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"Uninstall {}: stop {} error: {}",
|
||||
package_id,
|
||||
name,
|
||||
e
|
||||
);
|
||||
tracing::warn!("Uninstall {}: stop {} error: {}", package_id, name, e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,7 +285,12 @@ impl RpcHandler {
|
||||
Ok(o) => {
|
||||
// If normal rm fails (e.g., still running), force as fallback
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
tracing::warn!("Uninstall {}: rm {} failed ({}), trying force", package_id, name, stderr.trim());
|
||||
tracing::warn!(
|
||||
"Uninstall {}: rm {} failed ({}), trying force",
|
||||
package_id,
|
||||
name,
|
||||
stderr.trim()
|
||||
);
|
||||
let force_rm = tokio::process::Command::new("podman")
|
||||
.args(["rm", "-f", name])
|
||||
.output()
|
||||
@@ -302,6 +312,8 @@ impl RpcHandler {
|
||||
}
|
||||
}
|
||||
|
||||
self.set_uninstall_stage(package_id, "Cleaning up volumes")
|
||||
.await;
|
||||
// Clean up dangling volumes associated with removed containers
|
||||
let _ = tokio::process::Command::new("podman")
|
||||
.args(["volume", "prune", "-f"])
|
||||
@@ -330,6 +342,8 @@ impl RpcHandler {
|
||||
|
||||
// Clean data directories unless preserve_data
|
||||
if !preserve_data {
|
||||
self.set_uninstall_stage(package_id, "Removing app data")
|
||||
.await;
|
||||
let data_dirs = get_data_dirs_for_app(package_id);
|
||||
for dir in &data_dirs {
|
||||
tracing::info!("Uninstall {}: removing data {}", package_id, dir);
|
||||
@@ -374,6 +388,31 @@ impl RpcHandler {
|
||||
removed
|
||||
);
|
||||
|
||||
// Immediately remove from in-memory state so the UI updates without
|
||||
// waiting for the scanner's absence threshold (3 scans × 60s each).
|
||||
{
|
||||
let (mut data, _rev) = self.state_manager.get_snapshot().await;
|
||||
let before = data.package_data.len();
|
||||
data.package_data.remove(package_id);
|
||||
// Also remove any alias keys (e.g. "bitcoin-knots" vs "bitcoin")
|
||||
let aliases: Vec<String> = data
|
||||
.package_data
|
||||
.keys()
|
||||
.filter(|k| {
|
||||
super::config::all_container_names(package_id)
|
||||
.iter()
|
||||
.any(|c| c.strip_prefix("archy-").unwrap_or(c) == k.as_str())
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
for alias in &aliases {
|
||||
data.package_data.remove(alias);
|
||||
}
|
||||
if data.package_data.len() < before {
|
||||
self.state_manager.update_data(data).await;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"status": "uninstalled",
|
||||
"stopped": stopped,
|
||||
@@ -512,3 +551,185 @@ impl RpcHandler {
|
||||
Ok(serde_json::json!({ "status": "stopped", "app_id": app_id }))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Background workers for async package lifecycle RPCs.
|
||||
//
|
||||
// Extracted from the pre-async RPC handlers so the transitional state is
|
||||
// visible to the UI immediately. Each worker is pure IO over podman + the
|
||||
// crash_recovery helpers — no StateManager access here so we don't need
|
||||
// a handler reference. The caller does state flipping before/after.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Start containers in dependency order. Includes the post-start 3s wait +
|
||||
/// exit-check verification from the original synchronous handler (critical
|
||||
/// for catching "podman start succeeded but container immediately exited"
|
||||
/// failure modes).
|
||||
async fn do_package_start(to_start: &[String]) -> Result<()> {
|
||||
let mut errors = Vec::new();
|
||||
for (i, name) in to_start.iter().enumerate() {
|
||||
if i > 0 {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
|
||||
}
|
||||
tracing::info!("Starting container: {}", name);
|
||||
let out = tokio::process::Command::new("podman")
|
||||
.args(["start", name])
|
||||
.output()
|
||||
.await
|
||||
.context(format!("Failed to exec podman start {}", name))?;
|
||||
if !out.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
|
||||
tracing::error!("Failed to start {}: {}", name, stderr);
|
||||
install_log(&format!("START FAIL: {} — {}", name, stderr)).await;
|
||||
errors.push(format!("{}: {}", name, stderr));
|
||||
}
|
||||
}
|
||||
if !errors.is_empty() {
|
||||
return Err(anyhow::anyhow!("Start failed: {}", errors.join("; ")));
|
||||
}
|
||||
|
||||
// Post-start exit verification (podman start can succeed even if the
|
||||
// container exits immediately after).
|
||||
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
|
||||
for name in to_start {
|
||||
let status = tokio::process::Command::new("podman")
|
||||
.args(["inspect", name, "--format", "{{.State.Status}}"])
|
||||
.output()
|
||||
.await;
|
||||
if let Ok(o) = status {
|
||||
let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
|
||||
if state == "exited" {
|
||||
let logs = tokio::process::Command::new("podman")
|
||||
.args(["logs", "--tail", "5", name])
|
||||
.output()
|
||||
.await;
|
||||
let log_text = logs
|
||||
.map(|o| {
|
||||
let combined = format!(
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&o.stdout),
|
||||
String::from_utf8_lossy(&o.stderr)
|
||||
);
|
||||
combined.chars().take(200).collect::<String>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
tracing::error!("Container {} exited after start: {}", name, log_text);
|
||||
install_log(&format!("START EXITED: {} — {}", name, log_text)).await;
|
||||
errors.push(format!("{}: exited after start", name));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !errors.is_empty() {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Containers exited after start: {}",
|
||||
errors.join("; ")
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop all containers with their per-container graceful-shutdown timeout.
|
||||
async fn do_package_stop(containers: &[String]) -> Result<()> {
|
||||
let mut errors = Vec::new();
|
||||
for name in containers {
|
||||
tracing::info!(
|
||||
"Stopping container: {} (timeout: {}s)",
|
||||
name,
|
||||
stop_timeout_secs(name)
|
||||
);
|
||||
let out = tokio::process::Command::new("podman")
|
||||
.args(["stop", "-t", stop_timeout_secs(name), name])
|
||||
.output()
|
||||
.await
|
||||
.context(format!("Failed to exec podman stop {}", name))?;
|
||||
if !out.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
|
||||
tracing::error!("Failed to stop {}: {}", name, stderr);
|
||||
errors.push(format!("{}: {}", name, stderr));
|
||||
}
|
||||
}
|
||||
if !errors.is_empty() {
|
||||
return Err(anyhow::anyhow!("Stop failed: {}", errors.join("; ")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Restart via `podman restart`, falling back to stop+start when restart
|
||||
/// fails (rootless podman loopback issues).
|
||||
async fn do_package_restart(containers: &[String]) -> Result<()> {
|
||||
let mut errors = Vec::new();
|
||||
for name in containers {
|
||||
tracing::info!("Restarting container: {}", name);
|
||||
let out = tokio::process::Command::new("podman")
|
||||
.args(["restart", "-t", stop_timeout_secs(name), name])
|
||||
.output()
|
||||
.await
|
||||
.context(format!("Failed to exec podman restart {}", name))?;
|
||||
|
||||
if !out.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
|
||||
tracing::warn!(
|
||||
"podman restart {} failed: {}, trying stop+start",
|
||||
name,
|
||||
stderr
|
||||
);
|
||||
// Fallback: stop then start
|
||||
let _ = tokio::process::Command::new("podman")
|
||||
.args(["stop", "-t", stop_timeout_secs(name), name])
|
||||
.output()
|
||||
.await;
|
||||
let start_out = tokio::process::Command::new("podman")
|
||||
.args(["start", name])
|
||||
.output()
|
||||
.await
|
||||
.context(format!("Failed to exec podman start {}", name))?;
|
||||
if !start_out.status.success() {
|
||||
let start_err = String::from_utf8_lossy(&start_out.stderr)
|
||||
.trim()
|
||||
.to_string();
|
||||
tracing::error!("stop+start {} also failed: {}", name, start_err);
|
||||
errors.push(format!("{}: {}", name, start_err));
|
||||
} else {
|
||||
tracing::info!("Restarted {} via stop+start fallback", name);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !errors.is_empty() {
|
||||
return Err(anyhow::anyhow!("Restart failed: {}", errors.join("; ")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Flip the primary package entry's state and return the pre-transition
|
||||
/// state for revert on error. Mirrors `transitional::flip_to_transitional`
|
||||
/// but lives here because the package path keys by `package_id` (which may
|
||||
/// differ from the container name used by orchestrator-level entries).
|
||||
async fn flip_package_state(
|
||||
state_manager: &crate::state::StateManager,
|
||||
package_id: &str,
|
||||
transitional: PackageState,
|
||||
) -> Option<PackageState> {
|
||||
let (mut data, _) = state_manager.get_snapshot().await;
|
||||
let prev = data.package_data.get(package_id).map(|e| e.state.clone());
|
||||
if let Some(entry) = data.package_data.get_mut(package_id) {
|
||||
entry.state = transitional;
|
||||
state_manager.update_data(data).await;
|
||||
}
|
||||
prev
|
||||
}
|
||||
|
||||
/// Write the package entry's final state. No-op if the entry has since
|
||||
/// been removed (uninstall race).
|
||||
async fn set_package_state(
|
||||
state_manager: &crate::state::StateManager,
|
||||
package_id: &str,
|
||||
new_state: PackageState,
|
||||
) {
|
||||
let (mut data, _) = state_manager.get_snapshot().await;
|
||||
if let Some(entry) = data.package_data.get_mut(package_id) {
|
||||
if entry.state != new_state {
|
||||
entry.state = new_state;
|
||||
state_manager.update_data(data).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,546 @@
|
||||
//! Per-app manual update handler.
|
||||
//!
|
||||
//! Flow: validate → set Updating state → graceful stop → pull new image(s) →
|
||||
//! remove old container(s) → recreate (orchestrator-first, legacy fallback) → verify running.
|
||||
//! Data volumes are preserved (bind mounts, not stored in container).
|
||||
|
||||
use super::config::get_containers_for_app;
|
||||
use super::install::install_log;
|
||||
use super::progress::parse_pull_progress;
|
||||
use super::runtime::stop_timeout_secs;
|
||||
use super::validation::validate_app_id;
|
||||
use crate::api::rpc::RpcHandler;
|
||||
use crate::container::image_versions;
|
||||
use crate::data_model::{InstallPhase, PackageState};
|
||||
use anyhow::{Context, Result};
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
impl RpcHandler {
|
||||
/// Update a package to the version pinned in image-versions.sh.
|
||||
/// This is a manual operation — the user clicks "Update" in the UI.
|
||||
pub(in crate::api::rpc) async fn handle_package_update(
|
||||
&self,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
|
||||
let package_id = params
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing package id"))?;
|
||||
validate_app_id(package_id)?;
|
||||
|
||||
// Verify an update is actually available
|
||||
let pinned = image_versions::pinned_image_for_app(package_id)
|
||||
.ok_or_else(|| anyhow::anyhow!("No pinned image found for {}", package_id))?;
|
||||
|
||||
// Note: the `already updating` guard lives in `spawn_package_update`
|
||||
// (the async wrapper that dispatch actually routes to). By the time
|
||||
// this inner function runs, the wrapper has already flipped state to
|
||||
// `Updating`, so duplicating the check here would be a false positive.
|
||||
|
||||
install_log(&format!("UPDATE: {} → {}", package_id, pinned)).await;
|
||||
|
||||
// Set state to Updating
|
||||
{
|
||||
let (mut data, _) = self.state_manager.get_snapshot().await;
|
||||
if let Some(entry) = data.package_data.get_mut(package_id) {
|
||||
entry.state = PackageState::Updating;
|
||||
entry.available_update = None;
|
||||
}
|
||||
self.state_manager.update_data(data).await;
|
||||
}
|
||||
|
||||
// Preferred path: for single-container apps managed by manifests, route
|
||||
// updates through the orchestrator's upgrade lifecycle instead of the
|
||||
// legacy shell/CLI flow. Keep stack-style packages on legacy for now.
|
||||
if should_try_orchestrator_update(package_id, self.orchestrator.is_some()) {
|
||||
let orchestrator_app_id = orchestrator_update_app_id(package_id);
|
||||
self.set_install_phase(package_id, InstallPhase::Preparing)
|
||||
.await;
|
||||
install_log(&format!(
|
||||
"UPDATE ORCH: {} — attempting orchestrator upgrade as {}",
|
||||
package_id, orchestrator_app_id
|
||||
))
|
||||
.await;
|
||||
|
||||
if let Some(orchestrator) = self.orchestrator.as_ref() {
|
||||
match orchestrator.upgrade(orchestrator_app_id).await {
|
||||
Ok(()) => {
|
||||
self.set_install_phase(package_id, InstallPhase::WaitingHealthy)
|
||||
.await;
|
||||
if let Ok(health) = orchestrator.health(orchestrator_app_id).await {
|
||||
if health != "healthy" {
|
||||
warn!(
|
||||
"Update {}: orchestrator upgrade completed with health={} (expected healthy)",
|
||||
package_id, health
|
||||
);
|
||||
}
|
||||
}
|
||||
install_log(&format!(
|
||||
"UPDATE ORCH OK: {} (app={})",
|
||||
package_id, orchestrator_app_id
|
||||
))
|
||||
.await;
|
||||
self.clear_install_progress(package_id).await;
|
||||
return Ok(serde_json::json!({
|
||||
"status": "updated",
|
||||
"package_id": package_id,
|
||||
}));
|
||||
}
|
||||
Err(e) if is_unknown_app_id_error(&e) => {
|
||||
info!(
|
||||
"Update {}: orchestrator has no manifest mapping yet, falling back to legacy updater",
|
||||
package_id
|
||||
);
|
||||
install_log(&format!(
|
||||
"UPDATE ORCH SKIP: {} — unknown app_id, using legacy flow",
|
||||
package_id
|
||||
))
|
||||
.await;
|
||||
}
|
||||
Err(e) => {
|
||||
install_log(&format!("UPDATE ORCH FAIL: {} — {}", package_id, e)).await;
|
||||
self.clear_install_progress(package_id).await;
|
||||
self.clear_update_state(package_id).await;
|
||||
return Err(e.context(format!("Orchestrator update {} failed", package_id)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve images to pull — either a stack or single container
|
||||
let images_to_pull = self.resolve_images_to_pull(package_id, &pinned);
|
||||
|
||||
// Get all containers for this app
|
||||
let containers = get_containers_for_app(package_id).await?;
|
||||
if containers.is_empty() {
|
||||
self.clear_update_state(package_id).await;
|
||||
return Err(anyhow::anyhow!("No containers found for {}", package_id));
|
||||
}
|
||||
|
||||
// Execute update — on failure, attempt rollback by restarting old containers
|
||||
match self
|
||||
.execute_update(package_id, &containers, &images_to_pull)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
install_log(&format!("UPDATE OK: {}", package_id)).await;
|
||||
self.clear_install_progress(package_id).await;
|
||||
Ok(serde_json::json!({
|
||||
"status": "updated",
|
||||
"package_id": package_id,
|
||||
}))
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Update {} failed: {}. Attempting rollback.", package_id, e);
|
||||
install_log(&format!(
|
||||
"UPDATE FAIL: {} — {}. Rolling back.",
|
||||
package_id, e
|
||||
))
|
||||
.await;
|
||||
self.rollback_update(package_id, &containers).await;
|
||||
self.clear_install_progress(package_id).await;
|
||||
self.clear_update_state(package_id).await;
|
||||
Err(e.context(format!("Update {} failed, rolled back", package_id)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Core update execution: stop → pull → remove → recreate → verify.
|
||||
async fn execute_update(
|
||||
&self,
|
||||
package_id: &str,
|
||||
containers: &[String],
|
||||
images_to_pull: &[(String, String)],
|
||||
) -> Result<()> {
|
||||
// Phase: Preparing — about to stop the running container(s) so
|
||||
// we can swap images. Fast.
|
||||
self.set_install_phase(package_id, InstallPhase::Preparing)
|
||||
.await;
|
||||
|
||||
// 1. Graceful stop all containers (reverse order for dependencies)
|
||||
info!(
|
||||
"Update {}: stopping {} containers",
|
||||
package_id,
|
||||
containers.len()
|
||||
);
|
||||
for name in containers.iter().rev() {
|
||||
let timeout = stop_timeout_secs(name);
|
||||
info!(
|
||||
"Update {}: stopping {} (timeout: {}s)",
|
||||
package_id, name, timeout
|
||||
);
|
||||
let out = tokio::process::Command::new("podman")
|
||||
.args(["stop", "-t", timeout, name])
|
||||
.output()
|
||||
.await
|
||||
.context(format!("Failed to stop {}", name))?;
|
||||
if !out.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
warn!(
|
||||
"Update {}: stop {} failed: {}",
|
||||
package_id,
|
||||
name,
|
||||
stderr.trim()
|
||||
);
|
||||
// Continue — container might already be stopped
|
||||
}
|
||||
}
|
||||
|
||||
// Phase: PullingImage — about to fetch each pinned image in turn.
|
||||
self.set_install_phase(package_id, InstallPhase::PullingImage)
|
||||
.await;
|
||||
|
||||
// 2. Pull new images with progress
|
||||
info!(
|
||||
"Update {}: pulling {} images",
|
||||
package_id,
|
||||
images_to_pull.len()
|
||||
);
|
||||
for (i, (name, image)) in images_to_pull.iter().enumerate() {
|
||||
info!(
|
||||
"Update {}: pulling image {}/{} ({})",
|
||||
package_id,
|
||||
i + 1,
|
||||
images_to_pull.len(),
|
||||
image
|
||||
);
|
||||
self.pull_update_image(package_id, image)
|
||||
.await
|
||||
.context(format!("Failed to pull {} for {}", image, name))?;
|
||||
}
|
||||
|
||||
// 3. Remove old containers
|
||||
info!("Update {}: removing old containers", package_id);
|
||||
for name in containers {
|
||||
let out = tokio::process::Command::new("podman")
|
||||
.args(["rm", name])
|
||||
.output()
|
||||
.await
|
||||
.context(format!("Failed to remove {}", name))?;
|
||||
if !out.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
// Force remove as fallback
|
||||
warn!(
|
||||
"Update {}: rm {} failed ({}), forcing",
|
||||
package_id,
|
||||
name,
|
||||
stderr.trim()
|
||||
);
|
||||
let _ = tokio::process::Command::new("podman")
|
||||
.args(["rm", "-f", name])
|
||||
.output()
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
// Phase: CreatingContainer — about to recreate each container.
|
||||
self.set_install_phase(package_id, InstallPhase::CreatingContainer)
|
||||
.await;
|
||||
|
||||
// 4. Recreate containers (orchestrator-first, reconcile fallback)
|
||||
info!("Update {}: recreating containers", package_id);
|
||||
for name in containers {
|
||||
self.recreate_container_for_update(package_id, name).await?;
|
||||
// Brief delay between containers for dependency initialization
|
||||
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
|
||||
}
|
||||
|
||||
// Phase: WaitingHealthy — reconcile has started every container,
|
||||
// now verifying each reached running state.
|
||||
self.set_install_phase(package_id, InstallPhase::WaitingHealthy)
|
||||
.await;
|
||||
|
||||
// 5. Verify containers reached running state
|
||||
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
|
||||
for name in containers {
|
||||
let status = tokio::process::Command::new("podman")
|
||||
.args(["inspect", name, "--format", "{{.State.Status}}"])
|
||||
.output()
|
||||
.await;
|
||||
if let Ok(o) = status {
|
||||
let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
|
||||
if state == "exited" {
|
||||
warn!(
|
||||
"Update {}: container {} exited after recreate",
|
||||
package_id, name
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn recreate_container_for_update(
|
||||
&self,
|
||||
package_id: &str,
|
||||
container_name: &str,
|
||||
) -> Result<()> {
|
||||
let Some(orchestrator) = self.orchestrator.as_ref() else {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Cannot recreate {} during update {}: orchestrator unavailable",
|
||||
container_name,
|
||||
package_id
|
||||
));
|
||||
};
|
||||
|
||||
let mut attempted = Vec::new();
|
||||
for app_id in candidate_app_ids_for_container(container_name) {
|
||||
attempted.push(app_id.clone());
|
||||
match orchestrator.install(&app_id).await {
|
||||
Ok(created_name) => {
|
||||
install_log(&format!(
|
||||
"UPDATE ORCH RECREATE OK: {} — container={} app_id={} created={}",
|
||||
package_id, container_name, app_id, created_name
|
||||
))
|
||||
.await;
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) if is_unknown_app_id_error(&e) => {
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(e.context(format!(
|
||||
"orchestrator recreate failed for update {} (container={}, app_id={})",
|
||||
package_id, container_name, app_id
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(anyhow::anyhow!(
|
||||
"No manifest mapping found while recreating {} during update {} (attempted app_ids: {})",
|
||||
container_name,
|
||||
package_id,
|
||||
attempted.join(", ")
|
||||
))
|
||||
}
|
||||
|
||||
/// Pull a single image with progress broadcasting (reuses install progress pattern).
|
||||
async fn pull_update_image(&self, package_id: &str, image: &str) -> Result<()> {
|
||||
self.set_install_progress(package_id, 0, 0).await;
|
||||
|
||||
let mut child = tokio::process::Command::new("podman")
|
||||
.args(["pull", image])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.context("Failed to start image pull")?;
|
||||
|
||||
if let Some(stderr) = child.stderr.take() {
|
||||
let reader = BufReader::new(stderr);
|
||||
let mut lines = reader.lines();
|
||||
let pkg_id = package_id.to_string();
|
||||
let state_mgr = self.state_manager.clone();
|
||||
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
if let Some((downloaded, total)) = parse_pull_progress(&line) {
|
||||
Self::update_install_progress(&state_mgr, &pkg_id, downloaded, total).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let status = child
|
||||
.wait()
|
||||
.await
|
||||
.context("Failed to wait for image pull")?;
|
||||
if !status.success() {
|
||||
return Err(anyhow::anyhow!("podman pull {} failed", image));
|
||||
}
|
||||
|
||||
self.set_install_progress(package_id, 100, 100).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Determine which images need to be pulled for this update.
|
||||
/// For multi-container stacks, pulls all component images.
|
||||
/// For single-container apps, pulls just the pinned image.
|
||||
fn resolve_images_to_pull(
|
||||
&self,
|
||||
package_id: &str,
|
||||
pinned_primary: &str,
|
||||
) -> Vec<(String, String)> {
|
||||
let stack_images = image_versions::pinned_images_for_stack(package_id);
|
||||
if stack_images.is_empty() {
|
||||
// Single container app
|
||||
vec![(package_id.to_string(), pinned_primary.to_string())]
|
||||
} else {
|
||||
stack_images
|
||||
}
|
||||
}
|
||||
|
||||
/// Rollback: restart old containers if they still exist.
|
||||
/// Called when update fails partway through.
|
||||
async fn rollback_update(&self, package_id: &str, containers: &[String]) {
|
||||
warn!("Rolling back update for {}", package_id);
|
||||
for name in containers {
|
||||
// Try to start — works if container still exists (wasn't removed yet)
|
||||
let out = tokio::process::Command::new("podman")
|
||||
.args(["start", name])
|
||||
.output()
|
||||
.await;
|
||||
match out {
|
||||
Ok(o) if o.status.success() => {
|
||||
info!("Rollback: restarted {}", name);
|
||||
}
|
||||
Ok(o) => {
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
warn!("Rollback: could not restart {}: {}", name, stderr.trim());
|
||||
// Container was already removed (forward path ran `podman rm`).
|
||||
// Recreate via orchestrator-first path with legacy fallback.
|
||||
if let Err(recreate_err) =
|
||||
self.recreate_container_for_update(package_id, name).await
|
||||
{
|
||||
error!(
|
||||
"Rollback: failed to recreate {} during rollback of {}: {}",
|
||||
name, package_id, recreate_err
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Rollback: failed to restart {}: {}", name, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear the Updating state (used on failure/rollback).
|
||||
async fn clear_update_state(&self, package_id: &str) {
|
||||
let (mut data, _) = self.state_manager.get_snapshot().await;
|
||||
if let Some(entry) = data.package_data.get_mut(package_id) {
|
||||
// Don't overwrite state from scanner — just clear if still Updating
|
||||
if entry.state == PackageState::Updating {
|
||||
entry.state = PackageState::Stopped;
|
||||
}
|
||||
}
|
||||
self.state_manager.update_data(data).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn should_try_orchestrator_update(package_id: &str, orchestrator_available: bool) -> bool {
|
||||
orchestrator_available && !uses_legacy_update_flow(package_id)
|
||||
}
|
||||
|
||||
fn orchestrator_update_app_id(package_id: &str) -> &str {
|
||||
match package_id {
|
||||
"bitcoin-knots" => "bitcoin-core",
|
||||
"electrs" | "mempool-electrs" => "electrumx",
|
||||
_ => package_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn uses_legacy_update_flow(package_id: &str) -> bool {
|
||||
matches!(
|
||||
package_id,
|
||||
// Multi-container stacks still updated via the stack-aware path.
|
||||
"immich" | "penpot" | "penpot-frontend" | "indeedhub"
|
||||
)
|
||||
}
|
||||
|
||||
fn is_unknown_app_id_error(err: &anyhow::Error) -> bool {
|
||||
err.chain()
|
||||
.any(|cause| cause.to_string().contains("unknown app_id"))
|
||||
}
|
||||
|
||||
fn candidate_app_ids_for_container(container_name: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut push = |s: &str| {
|
||||
if !out.iter().any(|e: &String| e == s) {
|
||||
out.push(s.to_string());
|
||||
}
|
||||
};
|
||||
|
||||
match container_name {
|
||||
"bitcoin-knots" | "bitcoin-core" => {
|
||||
push("bitcoin-core");
|
||||
push("bitcoin-knots");
|
||||
}
|
||||
"archy-bitcoin-ui" => push("bitcoin-ui"),
|
||||
"archy-lnd-ui" => push("lnd-ui"),
|
||||
"archy-electrs-ui" => push("electrs-ui"),
|
||||
"mempool" => {
|
||||
push("archy-mempool-web");
|
||||
push("mempool");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
push(container_name);
|
||||
if let Some(stripped) = container_name.strip_prefix("archy-") {
|
||||
push(stripped);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
candidate_app_ids_for_container, orchestrator_update_app_id,
|
||||
should_try_orchestrator_update, uses_legacy_update_flow,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn legacy_flow_for_stack_apps() {
|
||||
for app in ["immich", "penpot", "indeedhub"] {
|
||||
assert!(uses_legacy_update_flow(app), "{app} should stay legacy");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orchestrator_flow_for_single_apps() {
|
||||
for app in [
|
||||
"lnd",
|
||||
"bitcoin-core",
|
||||
"searxng",
|
||||
"grafana",
|
||||
"btcpay-server",
|
||||
"mempool",
|
||||
"fedimint",
|
||||
] {
|
||||
assert!(
|
||||
!uses_legacy_update_flow(app),
|
||||
"{app} should be orchestrator-first"
|
||||
);
|
||||
assert!(
|
||||
should_try_orchestrator_update(app, true),
|
||||
"{app} should use orchestrator when available"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_orchestrator_means_no_orchestrator_flow() {
|
||||
assert!(!should_try_orchestrator_update("lnd", false));
|
||||
assert!(!should_try_orchestrator_update("btcpay-server", false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn container_name_candidates_cover_common_aliases() {
|
||||
assert_eq!(
|
||||
candidate_app_ids_for_container("bitcoin-knots"),
|
||||
vec!["bitcoin-core", "bitcoin-knots"]
|
||||
);
|
||||
assert_eq!(
|
||||
candidate_app_ids_for_container("archy-bitcoin-ui"),
|
||||
vec!["bitcoin-ui", "archy-bitcoin-ui"]
|
||||
);
|
||||
assert_eq!(
|
||||
candidate_app_ids_for_container("mempool"),
|
||||
vec!["archy-mempool-web", "mempool"]
|
||||
);
|
||||
assert_eq!(
|
||||
candidate_app_ids_for_container("archy-mempool-db"),
|
||||
vec!["archy-mempool-db", "mempool-db"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_aliases_map_to_manifest_app_ids() {
|
||||
assert_eq!(orchestrator_update_app_id("bitcoin-knots"), "bitcoin-core");
|
||||
assert_eq!(orchestrator_update_app_id("electrs"), "electrumx");
|
||||
assert_eq!(orchestrator_update_app_id("mempool-electrs"), "electrumx");
|
||||
assert_eq!(orchestrator_update_app_id("fedimint"), "fedimint");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::RpcHandler;
|
||||
use crate::{federation, node_message, nostr_discovery, peers};
|
||||
use crate::peers::KnownPeer;
|
||||
use crate::{federation, node_message, nostr_discovery, peers};
|
||||
use anyhow::Result;
|
||||
|
||||
impl RpcHandler {
|
||||
@@ -17,7 +17,10 @@ impl RpcHandler {
|
||||
.get("pubkey")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing pubkey"))?;
|
||||
let name = params.get("name").and_then(|v| v.as_str()).map(String::from);
|
||||
let name = params
|
||||
.get("name")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from);
|
||||
|
||||
let peer = KnownPeer {
|
||||
onion: onion.to_string(),
|
||||
@@ -69,13 +72,17 @@ impl RpcHandler {
|
||||
// Validate onion is a known peer or federated node to prevent SSRF
|
||||
let known_peers = peers::load_peers(&self.config.data_dir).await?;
|
||||
let is_known_peer = known_peers.iter().any(|p| {
|
||||
p.onion == onion || p.onion == format!("{}.onion", onion)
|
||||
p.onion == onion
|
||||
|| p.onion == format!("{}.onion", onion)
|
||||
|| format!("{}.onion", p.onion) == onion
|
||||
});
|
||||
let is_known_fed = if !is_known_peer {
|
||||
let fed_nodes = federation::load_nodes(&self.config.data_dir).await.unwrap_or_default();
|
||||
let fed_nodes = federation::load_nodes(&self.config.data_dir)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
fed_nodes.iter().any(|n| {
|
||||
n.onion == onion || n.onion == format!("{}.onion", onion)
|
||||
n.onion == onion
|
||||
|| n.onion == format!("{}.onion", onion)
|
||||
|| format!("{}.onion", n.onion) == onion
|
||||
})
|
||||
} else {
|
||||
@@ -90,24 +97,44 @@ impl RpcHandler {
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
let pubkey = data.server_info.pubkey.clone();
|
||||
|
||||
// Skip sending to ourselves (prevents duplicate messages in group chat)
|
||||
if let Some(ref our_onion) = data.server_info.tor_address {
|
||||
let our = our_onion.trim_end_matches(".onion");
|
||||
let their = onion.trim_end_matches(".onion");
|
||||
if our == their {
|
||||
return Ok(serde_json::json!({ "ok": true, "sent_to": onion, "skipped": "self" }));
|
||||
}
|
||||
}
|
||||
|
||||
// Load signing key for E2E encryption
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let node_id = crate::identity::NodeIdentity::load_or_create(&identity_dir).await?;
|
||||
|
||||
// Look up recipient's pubkey from federation nodes
|
||||
let fed_nodes = federation::load_nodes(&self.config.data_dir).await.unwrap_or_default();
|
||||
let recipient_pubkey = fed_nodes.iter()
|
||||
.find(|n| n.onion == onion || n.onion == format!("{}.onion", onion)
|
||||
|| format!("{}.onion", n.onion) == onion)
|
||||
.map(|n| n.pubkey.clone());
|
||||
let fed_nodes = federation::load_nodes(&self.config.data_dir)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let recipient = fed_nodes.iter().find(|n| {
|
||||
n.onion == onion
|
||||
|| n.onion == format!("{}.onion", onion)
|
||||
|| format!("{}.onion", n.onion) == onion
|
||||
});
|
||||
let recipient_pubkey = recipient.map(|n| n.pubkey.clone());
|
||||
let recipient_fips_npub = recipient.and_then(|n| n.fips_npub.clone());
|
||||
|
||||
// Include our node name so the recipient can display it
|
||||
let node_name = data.server_info.name.clone();
|
||||
|
||||
node_message::send_to_peer(
|
||||
onion,
|
||||
recipient_fips_npub.as_deref(),
|
||||
&pubkey,
|
||||
message,
|
||||
Some(node_id.signing_key()),
|
||||
recipient_pubkey.as_deref(),
|
||||
).await?;
|
||||
node_name.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
Ok(serde_json::json!({ "ok": true, "sent_to": onion }))
|
||||
}
|
||||
|
||||
@@ -120,7 +147,10 @@ impl RpcHandler {
|
||||
.get("onion")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing onion"))?;
|
||||
let reachable = node_message::check_peer_reachable(onion).await.unwrap_or(false);
|
||||
let fips_npub = crate::federation::fips_npub_for_onion(&self.config.data_dir, onion).await;
|
||||
let reachable = node_message::check_peer_reachable(onion, fips_npub.as_deref())
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
Ok(serde_json::json!({ "onion": onion, "reachable": reachable }))
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,9 @@ pub(super) struct RpcError {
|
||||
|
||||
/// Simple TTL cache for read-only RPC responses.
|
||||
pub(super) struct ResponseCache {
|
||||
entries: tokio::sync::RwLock<std::collections::HashMap<String, (std::time::Instant, serde_json::Value)>>,
|
||||
entries: tokio::sync::RwLock<
|
||||
std::collections::HashMap<String, (std::time::Instant, serde_json::Value)>,
|
||||
>,
|
||||
ttl: std::time::Duration,
|
||||
}
|
||||
|
||||
@@ -57,11 +59,15 @@ pub(super) fn json_response(status: StatusCode, body: &[u8]) -> Response<hyper::
|
||||
.header("Content-Type", "application/json")
|
||||
.body(hyper::Body::from(body.to_vec()))
|
||||
.unwrap_or_else(|_| {
|
||||
Response::new(hyper::Body::from(r#"{"error":{"code":500,"message":"Internal error"}}"#))
|
||||
Response::new(hyper::Body::from(
|
||||
r#"{"error":{"code":500,"message":"Internal error"}}"#,
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse a Set-Cookie header value, returning a default if parsing fails.
|
||||
pub(super) fn cookie_header(value: &str) -> hyper::header::HeaderValue {
|
||||
value.parse().unwrap_or_else(|_| hyper::header::HeaderValue::from_static(""))
|
||||
value
|
||||
.parse()
|
||||
.unwrap_or_else(|_| hyper::header::HeaderValue::from_static(""))
|
||||
}
|
||||
|
||||
@@ -47,11 +47,13 @@ impl RpcHandler {
|
||||
let internal_port = params
|
||||
.get("internal_port")
|
||||
.and_then(|v| v.as_u64())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing internal_port"))? as u16;
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing internal_port"))?
|
||||
as u16;
|
||||
let external_port = params
|
||||
.get("external_port")
|
||||
.and_then(|v| v.as_u64())
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing external_port"))? as u16;
|
||||
.ok_or_else(|| anyhow::anyhow!("Missing external_port"))?
|
||||
as u16;
|
||||
let protocol = params
|
||||
.get("protocol")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -98,6 +100,7 @@ impl RpcHandler {
|
||||
"tor_connected": diag.tor_connected,
|
||||
"dns_working": diag.dns_working,
|
||||
"recommendations": diag.recommendations,
|
||||
"wifi_ssid": diag.wifi_ssid,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user