feat: session persistence, logout button, TURN HMAC fix; update docs

- Browser mode auto-rejoins saved network on reload (waste_last_network)
- Logout button (⏻) in sidebar clears session; optionally clears identity keypair
- TURN credentials now use HMAC-SHA1 of username (coturn use-auth-secret compatible)
- README: deploy scripts documented, session persistence section, serve-web.sh noted
- FUTURE.md: mark shipped items, add remaining work for daemon TURN + TUI rooms

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Fredrik Johansson
2026-06-26 20:16:18 +02:00
parent dfbdd34aaa
commit 2c71d9c5c6
7 changed files with 115 additions and 45 deletions

View File

@@ -1,7 +1,9 @@
{
"permissions": {
"allow": [
"Bash(go build *)"
"Bash(go build *)",
"Bash(npx tsc *)",
"Bash(npm run *)"
]
}
}

View File

@@ -38,19 +38,12 @@ React + Vite frontend. Two modes:
### NAT Traversal ✅ (WebRTC ICE/STUN)
Solved by using WebRTC DataChannels via pion. ICE gathers host + server-reflexive (STUN) candidates and performs UDP hole punching automatically. The anchor (`cmd/anchor`) doubles as a STUN server on UDP/3478.
### TURN relay (symmetric NAT pairs)
The one remaining gap: two peers both behind symmetric NAT (common on mobile/CGNAT) will fail to hole-punch. TURN recovers this.
### TURN relay ✅ (shipped, browser mode)
Browser mode now supports TURN relay. `iceServers()` in `browser.ts` reads `WASTE_CONFIG.turnURL` and `WASTE_CONFIG.turnSecret`, generates time-limited HMAC-SHA1 credentials (compatible with coturn `use-auth-secret`), and adds the TURN server to the ICE candidate list. Mobile/CGNAT peers that fail STUN hole-punching automatically fall back to TURN relay.
**How to add it:** `internal/anchor/client.go` already has the `ICEServers` slice. Adding a TURN entry is a one-liner:
The peer dot in the sidebar turns yellow for relayed connections (`candidate_type: relay`).
```go
ICEServers: []webrtc.ICEServer{
{URLs: []string{"stun:stun.l.google.com:19302"}},
{URLs: []string{"turn:your-vps:3478"}, Username: "waste", Credential: "secret"},
},
```
Expose as daemon flags (`-turn-url`, `-turn-user`, `-turn-credential`) and wire into the anchor client config. Run `coturn` in relay-only mode on the same VPS as the anchor. The relay sees only opaque DTLS-encrypted blobs. Opt-in, off by default.
**Daemon mode:** not yet wired. Add `-turn-url` / `-turn-secret` flags to `cmd/daemon/main.go` and pass them into the `ICEServers` slice in `internal/anchor/client.go`.
### Signaling ✅ YAW/2.1 (shipped)
Forward-secret signaling via per-session ephemeral X25519 keys. Falls back transparently to 2.0 static-key sealing for peers that don't speak 2.1.
@@ -71,24 +64,27 @@ When a new peer connects, the mesh immediately gossips the full peer list to the
## Remaining Work
### Per-Network Share Directories (next)
The IPC plumbing is done (`set_share_dir`, `ShareDir` on `NetworkInfo`, per-network mesh), but the web UI's folder picker is a single global share applied to all peers on all networks. The fix: track share state per `network_id` in the store and pass the active network's share when browsing or accepting get requests.
### Session Persistence ✅ (shipped)
Browser mode now auto-rejoins on reload. The last-used network name, alias, and anchor URL are saved to `localStorage` on join and restored on load. A ⏻ logout button in the sidebar clears session state (optionally including the identity keypair) and reloads the page.
### Additional Channels / Rooms (next)
Currently each network has a hardcoded `#general` room. The protocol supports arbitrary room names already (messages carry a `room` field). What's missing:
- IPC command `create_room {network_id, name}` / `list_rooms {network_id}`
- Daemon stores room list per network in SQLite
- TUI: room creation input
- Web UI: `+` button in the Rooms sidebar section → prompt for name → `create_room`
### Per-Network Share Directories ✅ (shipped)
Share state is tracked per `network_id` in the store (`sharedFilesByNetwork`). The folder picker shows per-network file count. Switching networks switches the active share.
Room names are just strings — no server coordination needed. Any peer that sends to a room name causes it to appear on the recipient's side automatically. The only thing to add is persistence and a creation UI.
### Additional Channels / Rooms ✅ (shipped)
The `+` button in the Rooms sidebar section creates custom rooms, stored in `customRooms` keyed by `network_id`. Room names are slugified strings — any peer that sends to a room name causes it to appear on the recipient automatically. DM rooms (`dm:<peerId>`) appear automatically when messages arrive.
### File Transfer UX
- Manual accept/reject (currently auto-accept everywhere)
- Transfer cancellation via `file-cancel`
- Progress indicator in TUI and web UI
- Resume after disconnection
- Daemon-side: write received files to `<data-dir>/downloads-<netid>/` (browser is limited to download prompt)
**Not yet done:** TUI room creation, daemon-side SQLite persistence of room lists across restarts.
### File Transfer UX ✅ (shipped)
- Manual accept/reject via the Transfers panel in the sidebar
- Transfer cancellation (`file-cancel` message, closes DataChannel)
- Live progress bar per active transfer
- Push (📎) sends directly to a peer without them needing to share a folder
**Not yet done:** resume after disconnection, daemon-side download directory.
### TURN Relay for Daemon Mode
The daemon doesn't yet support TURN. Add `-turn-url` and `-turn-secret` flags to `cmd/daemon/main.go` and wire them into the ICE server list in `internal/anchor/client.go`. The credential generation is the same HMAC-SHA1 scheme already implemented in browser mode.
### Native UI
Web frontend (React, already built) + Tauri shell for native packaging. The IPC protocol is the full boundary — the UI is already a pure consumer. Main work: Tauri setup, system tray, OS notifications.
@@ -112,10 +108,14 @@ Web frontend (React, already built) + Tauri shell for native packaging. The IPC
| ✅ shipped | Peer gossip (anchor-free mesh reconnection) |
| ✅ shipped | Web UI — browser mode + daemon mode |
| ✅ shipped | Per-peer NAT/ICE status, identity backup/restore |
| next | Per-network share directories (web UI wiring) |
| next | Additional channels/rooms per network |
| next | TURN relay (3 flags + coturn on VPS) |
| next | File transfer UX (progress, cancel, manual accept) |
| ✅ shipped | Per-network share directories |
| ✅ shipped | Additional channels/rooms per network |
| ✅ shipped | TURN relay (browser mode, coturn `use-auth-secret`) |
| ✅ shipped | File transfer UX (progress, cancel, manual accept) |
| ✅ shipped | Session persistence + logout (browser mode) |
| next | TURN relay for daemon mode |
| next | TUI room creation + daemon-side room persistence |
| next | File transfer resume after disconnection |
| future | Native UI (React + Tauri) |
---

View File

@@ -41,6 +41,21 @@ On the VPS, run the anchor and keep it alive (systemd, screen, whatever you use)
./waste-anchor -bind 127.0.0.1:8080
```
Or use the helper script which handles background execution and logging:
```bash
./setup-anchor.sh --bg # start in background, logs to waste-anchor.log
./setup-anchor.sh --stop # stop it
```
To cross-compile and redeploy the anchor binary from your local machine:
```bash
./deploy-daemon.sh
```
This kills the existing anchor, uploads the new binary, and restarts it.
The anchor listens locally on port 8080 — Nginx Proxy Manager will expose it over TLS.
### 2. Build and upload the web UI
@@ -56,6 +71,12 @@ npm run build
rsync -az web/dist/ user@your-vps:~/waste-www/
```
Or use the deploy script (builds + rsyncs in one step):
```bash
./deploy-web.sh
```
Create a `/var/www/waste-web/config.js` on the VPS (not in git — this is host-specific):
```js
@@ -81,7 +102,19 @@ Create one **Proxy Host** for your domain (e.g. `waste.example.com`) with TLS en
- Choose "Serve Static Files" (or point to a local HTTP server serving `/var/www/waste-web`)
- Enable the SPA fallback so unknown paths return `index.html` — this is required for invite links to work
If NPM doesn't support static file serving directly, run a small static server on a spare port (e.g. `npx serve -s /var/www/waste-web -l 3000`) and proxy `/` to `127.0.0.1:3000`. The key requirements:
If NPM doesn't support static file serving directly, run a small static server on a spare port and proxy `/` to it:
```bash
nohup npx serve -s ~/waste-www -l 1337 &
```
Or use `serve-web.sh` which handles PID tracking and restart:
```bash
./serve-web.sh # kills existing instance, starts fresh, logs to waste-www.log
```
The key requirements:
- `/ws` → anchor process (WebSocket, keep-alive)
- `/*` → static file server (SPA fallback: return `index.html` for unknown paths)
@@ -150,6 +183,8 @@ A user visits your domain, enters their name and a network name, and joins. Invi
**Identity note:** browser mode uses the master identity directly (same keypair on all networks, compatible with yaw2). The daemon derives a separate keypair per network via HKDF. A browser user and a daemon user on the same network will see each other and can chat — they just appear as different peers even if they're the same person.
**Session persistence:** the last-used network name, alias, and anchor URL are saved to `localStorage`. On reload, the browser automatically rejoins the saved network — no login screen. To leave a network or switch identity, click the **⏻** button in the top-left of the sidebar. You'll be asked whether to also clear the identity keypair (export a backup first if you want to keep it).
### Daemon mode (for users running the daemon locally)
`launch-web.sh` starts the Go daemon and the Vite dev server. The web UI connects to the local daemon over WebSocket IPC (`ws://127.0.0.1:17338`). The daemon handles all crypto and connects to the anchor.

View File

@@ -49,9 +49,11 @@ details summary { color: var(--muted); font-size: 12px; cursor: pointer; }
/* ── sidebar ── */
.sidebar { background: var(--surface); border-right: 1px solid var(--border); display: flex; flex-direction: column; overflow-y: auto; }
.sidebar-identity { padding: 12px 12px 10px; border-bottom: 1px solid var(--border); }
.sidebar-identity { padding: 12px 12px 10px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 6px; }
.sidebar-identity .alias { display: block; font-weight: 600; font-size: 14px; }
.sidebar-identity .peer-id { display: block; color: var(--muted); font-size: 10px; font-family: monospace; margin-top: 2px; }
.sidebar-logout { background: none; color: var(--muted); font-size: 14px; padding: 2px 4px; flex-shrink: 0; margin-left: auto; }
.sidebar-logout:hover { color: #e06060; background: none; }
.sidebar-section { display: flex; flex-direction: column; padding: 8px 0; border-bottom: 1px solid var(--border); }
.sidebar-section:last-child { border-bottom: none; flex: 1; }
.sidebar-label { font-size: 10px; text-transform: uppercase; letter-spacing: 0.1em; color: var(--muted); padding: 4px 12px 2px; }

View File

@@ -32,7 +32,7 @@ export function Sidebar() {
networks, activeNetworkId, activeRoom,
connectedPeers, peerStatus,
setActiveRoom, setActiveNetwork, messages, browseFiles, sendFileTo, adapterMode,
customRooms, createRoom,
customRooms, createRoom, logout,
} = useWaste()
const [addingRoom, setAddingRoom] = useState(false)
const [newRoomName, setNewRoomName] = useState('')
@@ -54,6 +54,11 @@ export function Sidebar() {
const displayId = localPeer?.id ?? masterId ?? ''
const card = displayId ? makeYawCard(displayId, displayAlias) : null
function handleLogout() {
const clearId = window.confirm('Also clear your identity keypair? (Cannot be undone — export a backup first if you want to keep it.)')
logout(clearId)
}
function openDM(peerId: string) {
setActiveRoom(`dm:${peerId}`)
}
@@ -64,15 +69,17 @@ export function Sidebar() {
return (
<nav className="sidebar">
<div className="sidebar-identity">
<div
className="sidebar-identity"
style={{ flex: 1, cursor: card ? 'pointer' : undefined }}
title={card ?? undefined}
onClick={() => card && navigator.clipboard?.writeText(card)}
style={{ cursor: card ? 'pointer' : undefined }}
>
<span className="alias">{displayAlias || '…'}</span>
<span className="peer-id">{displayId.slice(0, 16).replace(/(.{4})/g, '$1 ').trim()}</span>
</div>
<button className="sidebar-logout" onClick={handleLogout} title="Leave network"></button>
</div>
<div className="sidebar-section">
<span className="sidebar-label">Networks</span>

View File

@@ -61,16 +61,28 @@ export function Onboarding({ status }: Props) {
if (inv) setInviteString(inv)
}, [])
// Auto-rejoin when adapter is ready and we have saved session state
useEffect(() => {
if (adapterMode !== 'browser' || status !== 'connected') return
const { network: n, netHash: nh } = parseInviteParams()
if (n || nh) return // explicit invite — don't auto-join, show form
const savedNetwork = localStorage.getItem('waste_last_network')
if (savedNetwork) doJoin(savedNetwork, '')
}, [adapterMode, status]) // eslint-disable-line react-hooks/exhaustive-deps
function joinNetwork(e: React.FormEvent) {
e.preventDefault()
const name = network.trim()
const hash = netHash.trim()
doJoin(network.trim(), netHash.trim())
}
function doJoin(name: string, hash: string) {
if (!name && !hash) return
// In browser mode: persist anchor URL choice and pass it via localStorage
if (adapterMode === 'browser') {
localStorage.setItem('waste_anchor_url', anchorUrl)
if (nick.trim()) localStorage.setItem('waste_nick', nick.trim())
if (name) localStorage.setItem('waste_last_network', name)
else localStorage.removeItem('waste_last_network')
}
if (hash.length === 64 && !name) {

View File

@@ -69,6 +69,7 @@ interface WasteState {
rejectOffer: (peerId: string, xid: string) => void
cancelTransfer: (peerId: string, xid: string, direction: 'recv' | 'send') => void
createRoom: (name: string) => void
logout: (clearIdentity: boolean) => void
handleEvent: (msg: IpcMessage) => void
}
@@ -169,6 +170,17 @@ export const useWaste = create<WasteState>((set, get) => ({
if (a instanceof BrowserAdapter) a.cancelTransfer(peerId, xid, direction)
},
logout(clearIdentity) {
const a = get().adapter
if (a instanceof DaemonAdapter) a.disconnect()
else if (a instanceof BrowserAdapter) a.disconnect()
localStorage.removeItem('waste_last_network')
localStorage.removeItem('waste_nick')
localStorage.removeItem('waste_anchor_url')
if (clearIdentity) localStorage.removeItem('waste_seed')
window.location.reload()
},
createRoom(name) {
const netId = get().activeNetworkId
if (!netId || !name.trim()) return