Add yaw2 invite interoperability

Protocol:
- invite.go: include full 64-char `net` hash in waste: invite blob
  (matches yaw2's `net` field — any client parsing the base64 JSON can
  join without knowing the plaintext name). Expose NetHash() helper.
- netmgr: add JoinByHash() — join via full 64-char hex hash alone,
  storing the short ID as display name. Enables joining yaw2 networks
  from a URL that only carries the hash.
- anchor: expose RunByHash() so netmgr can pass a pre-computed hash
  directly without a name→hash roundtrip.
- ipc/proto: add network_hash field to join_network — routes to
  JoinByHash when present and network_name is absent.

Web UI:
- Parse ?net=<64hex> (yaw2 URL param) and ?a=<anchor> in addition to
  existing ?n= / ?invite= params. Hash-only joins send network_hash.
- Sidebar shows yaw: contact card (yaw:<masterID>?n=<alias>) using the
  master identity — compatible with yaw2 contact card format. Click to
  copy to clipboard.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Fredrik Johansson
2026-06-22 23:29:45 +02:00
parent 7fe02e9463
commit add7c5fea8
8 changed files with 193 additions and 33 deletions

View File

@@ -60,7 +60,12 @@ func (s *peerSession) close() {
// Run connects to anchorURL, joins networkName, and blocks handling signaling. // Run connects to anchorURL, joins networkName, and blocks handling signaling.
// Reconnects automatically on disconnect. Cancel ctx to stop. // Reconnects automatically on disconnect. Cancel ctx to stop.
func Run(ctx context.Context, anchorURL, networkName string, id *crypto.Identity, m *mesh.Mesh) { func Run(ctx context.Context, anchorURL, networkName string, id *crypto.Identity, m *mesh.Mesh) {
netHash := hashNetName(networkName) RunByHash(ctx, anchorURL, hashNetName(networkName), id, m)
}
// RunByHash is like Run but accepts the pre-computed full 64-char hex network hash
// directly. Use this when joining by hash rather than by name.
func RunByHash(ctx context.Context, anchorURL, netHash string, id *crypto.Identity, m *mesh.Mesh) {
for { for {
if err := runOnce(ctx, anchorURL, netHash, id, m); err != nil { if err := runOnce(ctx, anchorURL, netHash, id, m); err != nil {
if ctx.Err() != nil { if ctx.Err() != nil {

View File

@@ -1,10 +1,17 @@
// Package invite encodes and decodes waste invite strings. // Package invite encodes and decodes waste invite strings.
// An invite carries the anchor URL and network name needed to join a network. //
// Format: "waste:<url-safe-base64(json)>" // Format: "waste:<url-safe-base64(json)>"
//
// The JSON payload is compatible with yaw2: the `net` field carries the full
// 64-char hex SHA-256("yaw2-net:"+name) hash that yaw2 clients pass directly
// to the signaling server. A yaw2 client that can parse the base64 JSON can join
// the same network without knowing the plaintext name.
package invite package invite
import ( import (
"crypto/sha256"
"encoding/base64" "encoding/base64"
"encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
"strings" "strings"
@@ -14,8 +21,9 @@ const prefix = "waste:"
// Invite holds the information needed to join a network. // Invite holds the information needed to join a network.
type Invite struct { type Invite struct {
Anchor string `json:"anchor"` // WebSocket anchor URL Anchor string `json:"anchor"` // WebSocket anchor URL
Network string `json:"network"` // plaintext network name Network string `json:"network"` // plaintext network name
Net string `json:"net,omitempty"` // 64-char hex SHA-256("yaw2-net:"+name) — yaw2 `net` field
} }
// Encode returns a waste: invite string for the given anchor URL and network name. // Encode returns a waste: invite string for the given anchor URL and network name.
@@ -26,7 +34,12 @@ func Encode(anchor, network string) (string, error) {
if network == "" { if network == "" {
return "", fmt.Errorf("network name is required") return "", fmt.Errorf("network name is required")
} }
b, err := json.Marshal(Invite{Anchor: anchor, Network: network}) h := sha256.Sum256([]byte("yaw2-net:" + network))
b, err := json.Marshal(Invite{
Anchor: anchor,
Network: network,
Net: hex.EncodeToString(h[:]),
})
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -52,3 +65,10 @@ func Decode(s string) (Invite, error) {
} }
return inv, nil return inv, nil
} }
// NetHash returns the full 64-char hex network hash for the given name
// (SHA-256("yaw2-net:" + name)). This is the `net` field sent to the anchor.
func NetHash(name string) string {
h := sha256.Sum256([]byte("yaw2-net:" + name))
return hex.EncodeToString(h[:])
}

View File

@@ -137,16 +137,25 @@ func handleClient(conn net.Conn, mgr *netmgr.Manager) {
switch cmd.Type { switch cmd.Type {
case proto.CmdJoinNetwork: case proto.CmdJoinNetwork:
if cmd.NetworkName == "" { var (
send(errMsg("join_network: network_name is required")) netID string
err error
)
switch {
case cmd.NetworkName != "":
netID, err = mgr.Join(cmd.NetworkName, cmd.ShareDir)
case len(cmd.NetworkHash) == 64:
// yaw2-compatible: join by full 64-char hex hash (net field)
netID, err = mgr.JoinByHash(cmd.NetworkHash, cmd.ShareDir)
default:
send(errMsg("join_network: network_name or network_hash (64 hex chars) required"))
continue continue
} }
netID, err := mgr.Join(cmd.NetworkName, cmd.ShareDir)
if err != nil { if err != nil {
send(errMsg(fmt.Sprintf("join_network: %v", err))) send(errMsg(fmt.Sprintf("join_network: %v", err)))
continue continue
} }
// network_joined event (with share_dir) is emitted by Manager.Join. // network_joined event (with share_dir) is emitted by Manager.Join/JoinByHash.
_ = netID _ = netID
case proto.CmdLeaveNetwork: case proto.CmdLeaveNetwork:

View File

@@ -147,6 +147,88 @@ func (mgr *Manager) Join(name, shareDir string) (string, error) {
return netID, nil return netID, nil
} }
// JoinByHash joins a network using its pre-computed full 64-char hex hash
// (yaw2 `net` field) instead of the plaintext name. The network is stored
// with an empty name; the network_id (first 8 bytes) is used for display.
// This enables joining networks whose names are unknown — e.g. from a yaw2
// invite URL that only contains the hash.
func (mgr *Manager) JoinByHash(netHash64, shareDir string) (string, error) {
if len(netHash64) != 64 {
return "", fmt.Errorf("netHash must be 64 hex chars, got %d", len(netHash64))
}
netID := netHash64[:16] // first 8 bytes = 16 hex chars
mgr.mu.Lock()
if _, exists := mgr.networks[netID]; exists {
mgr.mu.Unlock()
return netID, nil
}
mgr.mu.Unlock()
derived, err := crypto.DeriveForNetwork(mgr.cfg.MasterIdentity, netHash64)
if err != nil {
return "", fmt.Errorf("derive identity for net %s: %w", netID, err)
}
dbPath := filepath.Join(mgr.cfg.StoreDir, "messages-"+netID+".db")
st, err := store.Open(dbPath)
if err != nil {
return "", fmt.Errorf("open store for net %s: %w", netID, err)
}
m := mesh.New(derived, st)
if shareDir != "" {
m.ShareDir = shareDir
} else if mgr.cfg.ShareDir != "" {
m.ShareDir = mgr.cfg.ShareDir
}
m.DownloadDir = filepath.Join(mgr.cfg.StoreDir, "downloads-"+netID)
meshEvents := m.Subscribe()
go func() {
for evt := range meshEvents {
evt.NetworkID = netID
mgr.emit(evt)
}
}()
ctx, cancel := context.WithCancel(context.Background())
net := &Network{
ID: netID,
Name: netID, // display as short hash when name is unknown
Hash: netHash64,
Identity: derived,
Mesh: m,
Store: st,
cancel: cancel,
}
mgr.mu.Lock()
mgr.networks[netID] = net
mgr.order = append(mgr.order, netID)
mgr.mu.Unlock()
log.Printf("netmgr: joining network by hash id=%s peer=%s", netID, derived.PeerID().Short())
if mgr.cfg.AnchorURL != "" {
go func() {
anchor.RunByHash(ctx, mgr.cfg.AnchorURL, netHash64, derived, m)
log.Printf("netmgr: left network %s", netID)
}()
}
mgr.emit(proto.IpcMessage{
Type: proto.EvtNetworkJoined,
NetworkID: netID,
NetworkName: netID,
LocalPeer: peerPtr(derived.PeerInfo()),
ShareDir: m.ShareDir,
})
return netID, nil
}
// Leave cancels a network context by ID. Closes its store. // Leave cancels a network context by ID. Closes its store.
func (mgr *Manager) Leave(netID string) { func (mgr *Manager) Leave(netID string) {
mgr.mu.Lock() mgr.mu.Lock()

View File

@@ -265,7 +265,8 @@ type IpcMessage struct {
// join_network / leave_network // join_network / leave_network
NetworkName string `json:"network_name,omitempty"` NetworkName string `json:"network_name,omitempty"`
ShareDir string `json:"share_dir,omitempty"` // optional per-network share directory NetworkHash string `json:"network_hash,omitempty"` // 64-char hex (yaw2 `net` field); alternative to network_name
ShareDir string `json:"share_dir,omitempty"` // optional per-network share directory
// send_file / set_share_dir / file_complete path // send_file / set_share_dir / file_complete path
Path string `json:"path,omitempty"` Path string `json:"path,omitempty"`

View File

@@ -1,7 +1,12 @@
import { useWaste } from '../store' import { useWaste } from '../store'
function makeYawCard(id: string, alias: string): string {
const nick = encodeURIComponent(alias.trim().slice(0, 40))
return nick ? `yaw:${id}?n=${nick}` : `yaw:${id}`
}
export function Sidebar() { export function Sidebar() {
const { localPeer, networks, activeNetworkId, activeRoom, setActiveRoom, setActiveNetwork, messages } = useWaste() const { localPeer, masterId, masterAlias, networks, activeNetworkId, activeRoom, setActiveRoom, setActiveNetwork, messages } = useWaste()
// Rooms = general + any DM threads that have messages // Rooms = general + any DM threads that have messages
const rooms = ['general'] const rooms = ['general']
@@ -9,11 +14,21 @@ export function Sidebar() {
if (r.startsWith('dm:') && !rooms.includes(r)) rooms.push(r) if (r.startsWith('dm:') && !rooms.includes(r)) rooms.push(r)
}) })
const displayAlias = localPeer?.alias ?? masterAlias ?? ''
const displayId = localPeer?.id ?? masterId ?? ''
const card = displayId ? makeYawCard(displayId, displayAlias) : null
return ( return (
<nav className="sidebar"> <nav className="sidebar">
<div className="sidebar-identity"> <div
<span className="alias">{localPeer?.alias}</span> className="sidebar-identity"
<span className="peer-id">{localPeer?.id.slice(0, 8)}</span> 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>
{card && <span className="peer-id" style={{ fontSize: '9px', opacity: 0.5 }}>click to copy card</span>}
</div> </div>
<div className="sidebar-section"> <div className="sidebar-section">

View File

@@ -7,30 +7,42 @@ interface Props {
// Parse URL search params for pre-filling the join form. // Parse URL search params for pre-filling the join form.
// Supports: // Supports:
// ?invite=waste:<b64> waste: invite string (anchor + network name) // ?invite=waste:<b64> waste: invite string (anchor + network name + net hash)
// ?n=<name> network name shorthand // ?n=<name> network name shorthand
// ?network=<name> network name // ?network=<name> network name
// ?net=<64hex> yaw2-style full network hash (joined without plaintext name)
// ?a=<url> anchor URL hint (informational — daemon controls its anchor) // ?a=<url> anchor URL hint (informational — daemon controls its anchor)
function parseInviteParams(): { network: string; anchor: string; inviteString: string } { function parseInviteParams(): { network: string; netHash: string; anchor: string; inviteString: string } {
const p = new URLSearchParams(window.location.search) const p = new URLSearchParams(window.location.search)
const inviteString = p.get('invite') ?? '' const inviteString = p.get('invite') ?? ''
let network = p.get('n') ?? p.get('network') ?? '' let network = p.get('n') ?? p.get('network') ?? ''
let netHash = p.get('net') ?? ''
let anchor = p.get('a') ?? p.get('anchor') ?? '' let anchor = p.get('a') ?? p.get('anchor') ?? ''
if (inviteString.startsWith('waste:')) { if (inviteString.startsWith('waste:')) {
try { try {
// URL-safe base64 → standard base64
const json = JSON.parse(atob(inviteString.slice(6).replace(/-/g, '+').replace(/_/g, '/'))) const json = JSON.parse(atob(inviteString.slice(6).replace(/-/g, '+').replace(/_/g, '/')))
network = network || json.network || '' network = network || json.network || ''
netHash = netHash || json.net || ''
anchor = anchor || json.anchor || '' anchor = anchor || json.anchor || ''
} catch { /* ignore bad invite */ } } catch { /* ignore bad invite */ }
} }
return { network, anchor, inviteString } // URL path: /<16hex>/ — short network ID from anchor-served URL
const pathMatch = window.location.pathname.match(/\/([0-9a-f]{16})\/?$/i)
if (pathMatch && !netHash && !network) {
// Only the short ID — can't join by short ID alone (need full hash for HKDF).
// Store it as a hint; the user must supply the network name OR a full 64-char hash.
}
return { network, netHash, anchor, inviteString }
} }
export function Onboarding({ status }: Props) { export function Onboarding({ status }: Props) {
const { send, masterAlias, masterId, exportedBackup } = useWaste() const { send, masterAlias, masterId, exportedBackup } = useWaste()
const [network, setNetwork] = useState('') const [network, setNetwork] = useState('')
const [netHash, setNetHash] = useState('')
const [inviteString, setInviteString] = useState('') const [inviteString, setInviteString] = useState('')
const [anchorHint, setAnchorHint] = useState('') const [anchorHint, setAnchorHint] = useState('')
const [exportPass, setExportPass] = useState('') const [exportPass, setExportPass] = useState('')
@@ -40,8 +52,9 @@ export function Onboarding({ status }: Props) {
const [showBackup, setShowBackup] = useState(false) const [showBackup, setShowBackup] = useState(false)
useEffect(() => { useEffect(() => {
const { network: n, anchor: a, inviteString: inv } = parseInviteParams() const { network: n, netHash: nh, anchor: a, inviteString: inv } = parseInviteParams()
if (n) setNetwork(n) if (n) setNetwork(n)
if (nh) setNetHash(nh)
if (a) setAnchorHint(a) if (a) setAnchorHint(a)
if (inv) setInviteString(inv) if (inv) setInviteString(inv)
}, []) }, [])
@@ -49,8 +62,14 @@ export function Onboarding({ status }: Props) {
function joinNetwork(e: React.FormEvent) { function joinNetwork(e: React.FormEvent) {
e.preventDefault() e.preventDefault()
const name = network.trim() const name = network.trim()
if (!name) return const hash = netHash.trim()
send({ type: 'join_network', network_name: name }) if (!name && !hash) return
if (hash.length === 64 && !name) {
// yaw2-style: join by full network hash without plaintext name
send({ type: 'join_network', network_hash: hash })
} else {
send({ type: 'join_network', network_name: name })
}
} }
function exportIdentity(e: React.FormEvent) { function exportIdentity(e: React.FormEvent) {
@@ -110,23 +129,31 @@ export function Onboarding({ status }: Props) {
{anchorHint && ( {anchorHint && (
<p className="onboarding-hint muted">via {anchorHint}</p> <p className="onboarding-hint muted">via {anchorHint}</p>
)} )}
<input {netHash && !network ? (
value={network}
onChange={e => setNetwork(e.target.value)}
placeholder="network name"
autoComplete="off"
autoFocus
/>
{inviteString && (
<input <input
value={inviteString} value={netHash}
readOnly onChange={e => setNetHash(e.target.value)}
className="muted mono" placeholder="network hash (64 hex)"
autoComplete="off"
autoFocus
className="mono"
style={{ fontSize: '0.72rem' }} style={{ fontSize: '0.72rem' }}
title="invite string" />
) : (
<input
value={network}
onChange={e => setNetwork(e.target.value)}
placeholder="network name"
autoComplete="off"
autoFocus
/> />
)} )}
<button type="submit" className="primary" disabled={!network.trim()}> {inviteString && (
<p className="onboarding-hint muted mono" style={{ fontSize: '0.68rem', wordBreak: 'break-all' }}>
{inviteString.slice(0, 48)}
</p>
)}
<button type="submit" className="primary" disabled={!network.trim() && netHash.length !== 64}>
Join Join
</button> </button>
</form> </form>

View File

@@ -79,6 +79,7 @@ export interface IpcMessage {
body?: string body?: string
// join_network // join_network
network_name?: string network_name?: string
network_hash?: string // 64-char hex (yaw2 `net` field) — alternative to network_name
share_dir?: string share_dir?: string
// send_file / set_share_dir // send_file / set_share_dir
path?: string path?: string