import { html, useState, useEffect, useCallback, useMemo, useRef, } from './vendor/htm-preact.js'; import { t } from './i18n.js'; import { Icon } from './icon.js'; import { CollapsibleSection, ToggleSwitch } from './settings-ui.js'; import { hubFetch, navigate } from './hub-client.js'; import { availableApps, configurableApps } from './apps.js'; import * as platform from './platform.js'; // ── Shared Directories Table ──────────────────────────────────────────── /** * A group's root directories, and the operator's controls over them. * * One component, two modes, because the Create Group wizard and the Settings * page were drifting apart while showing the same thing: * * mode="live" — a hosted group. Every change is a signed operator op sent * over MNP, or the loopback API when the node is on this * machine and there is no live connection. * mode="local" — the wizard, before the group exists. Changes are held in * an array the caller owns; nothing is persisted until the * group is attached. * * **Both paths matter and neither is optional.** The operator of a node is not * necessarily sitting at it: they may be signing in from any browser, and the * only thing that reaches their node from there is MNP. An earlier version of * this read its roots exclusively from the loopback API, which resolves to * "not available" in a browser — so the section rendered for nobody on the * web, while the controls it replaced had worked there. `mnpRoots` is the * source whenever a connection exists; the loopback list is the fallback for * a local node that is not currently connected (a group still scanning, say). * * Props: * roots — the node's current roots: { name, path, writable, * removable, ejected, available, kind } * groupId — the group id * transport — MeshBayTransport instance, or null when not connected * signFn — signing function for admin ops * nodeDetected — whether the loopback node API answers * onRootsChange — called after a change, to re-read the loopback list * onRefreshIndex — full index refresh. Not called after a root change: see * `run()` for why the node's own push is what settles it * mode — "live" (default) or "local" * localRoots / onLocalRootsChange — the array, in "local" mode */ function SharedDirectoriesTable({ roots, groupId, transport, signFn, nodeDetected: nodeAvail, onRootsChange, onRefreshIndex, mode = 'live', localRoots, onLocalRootsChange }) { const isLocal = mode === 'local'; const serverRoots = isLocal ? (localRoots || []) : (roots || []); const [busy, setBusy] = useState(false); // `{ text, error }` — a refusal has to look like one. Every message here was // a `settings-hint`, which is dim grey body text, so "two roots would both // be called uploads" read as a footnote to the section rather than as the // reason nothing happened. const [msg, setMsg] = useState(null); const [indexProgress, setIndexProgress] = useState(null); const say = useCallback((text) => setMsg(text ? { text, error: false } : null), []); const refuse = useCallback((text) => setMsg({ text, error: true }), []); // Rendered at the foot of the section, under the Add button — the last thing // below the control that caused it, rather than above a table the eye has // already moved past. const message = !msg ? '' : html`

${msg.text}

`; const [pathDraft, setPathDraft] = useState(''); const [addingByPath, setAddingByPath] = useState(false); // A toggle has to move under the finger, and the answer only comes back // when the node has signed, written node.toml and pushed the new table. // The patch is therefore held until the incoming `roots` actually agrees // with it — clearing it when the request resolves (which is what this did) // drops it in the frame *before* the new table arrives, so the switch // visibly snaps back and then forward again. const [optimistic, setOptimistic] = useState({}); useEffect(() => { setOptimistic((prev) => { const keys = Object.keys(prev); if (!keys.length) return prev; const next = {}; let changed = false; for (const name of keys) { const server = serverRoots.find(r => r.name === name); const patch = prev[name]; // Gone from the table, or the server now says what we asked for: // either way this patch has nothing left to hide. const settled = !server || Object.keys(patch).every(k => server[k] === patch[k]); if (settled) changed = true; else next[name] = patch; } return changed ? next : prev; }); }, [serverRoots]); const displayRoots = serverRoots.map(r => optimistic[r.name] ? { ...r, ...optimistic[r.name] } : r); // Paths are the operator's own view and do not cross MNP: the roots table // rides in the index payload, which every member receives, and it tells them // what exists and whether it is readable — never where on the operator's // disk it lives. So the column appears when the answer is actually // available (the loopback API, which is already this machine only) and is // left out otherwise, rather than printing a row of blanks. const hasPaths = displayRoots.some((r) => r.path); // Which door a change goes through. MNP first: it is the only one that // exists for an operator on the web, and it is signed, which the loopback // API is not (it is authorized by being on localhost with the run token). const overMnp = !isLocal && transport && transport.connected; const overLoopback = !isLocal && !overMnp && nodeAvail; const canEdit = isLocal || overMnp || overLoopback; const rootUrl = (name, suffix = '') => '/api/groups/' + groupId + '/roots/' + encodeURIComponent(name) + suffix; // Deliberately no index refresh after a root change. // // Adding a root makes the node reload, which rescans — minutes on a real // library — and the reload is fire-and-forget for that reason. Fetching the // index in the moment after therefore returns the set from *before* it, and // `applyIndex` writes that over the roots the ack had just delivered: the // new directory appeared for one paint and vanished, which is what "it only // shows up after a refresh" was. // // Nothing is lost by waiting. The ack carries the new table immediately, and // the delta the node pushes when the scan finishes carries it again along // with the files. const run = useCallback(async (work) => { setBusy(true); setMsg(null); try { await work(); if (onRootsChange) await onRootsChange(); return true; } catch (err) { refuse(platform.bridgeMessage(err)); return false; } finally { setBusy(false); } }, [onRootsChange, refuse]); const doUpdateRoot = useCallback(async (rootName, updates) => { if (isLocal) { if (onLocalRootsChange) { onLocalRootsChange((localRoots || []).map(r => r.name === rootName ? { ...r, ...updates } : r)); } return; } setOptimistic(prev => ({ ...prev, [rootName]: { ...(prev[rootName] || {}), ...updates }, })); const ok = await run(async () => { if (overMnp) await transport.updateRoot(groupId, rootName, updates, signFn); else if (overLoopback) await platform.node.call('PATCH', rootUrl(rootName), updates); else throw new Error(t('node.root_no_route')); }); // Only a failure clears the patch here; a success waits for the node's // own table, so the switch never travels backwards on its way forwards. if (!ok) { setOptimistic(prev => { const next = { ...prev }; delete next[rootName]; return next; }); } }, [isLocal, localRoots, onLocalRootsChange, overMnp, overLoopback, transport, groupId, signFn, run]); const doEjectRoot = useCallback((rootName) => run(async () => { if (overMnp) await transport.ejectRoot(groupId, rootName, signFn); else if (overLoopback) await platform.node.call('PUT', rootUrl(rootName, '/eject')); else throw new Error(t('node.root_no_route')); }), [overMnp, overLoopback, transport, groupId, signFn, run]); const doPlugRoot = useCallback((rootName) => run(async () => { if (overMnp) await transport.plugRoot(groupId, rootName, signFn); else if (overLoopback) await platform.node.call('PUT', rootUrl(rootName, '/plug')); else throw new Error(t('node.root_no_route')); }), [overMnp, overLoopback, transport, groupId, signFn, run]); const doRemoveRoot = useCallback(async (rootName) => { if (isLocal) { if (onLocalRootsChange) { onLocalRootsChange((localRoots || []).filter(r => r.name !== rootName)); } return; } if (!confirm(t('node.root_remove_confirm', { name: rootName }))) return; const ok = await run(async () => { if (overMnp) await transport.removeRoot(groupId, rootName, signFn); else if (overLoopback) { await platform.node.call('DELETE', rootUrl(rootName)); await platform.node.call('POST', '/api/reload'); } else throw new Error(t('node.root_no_route')); }); if (ok) say(t('node.root_removed')); }, [isLocal, localRoots, onLocalRootsChange, overMnp, overLoopback, transport, groupId, signFn, run]); // Adding a root needs a directory that exists on the *node's* filesystem. // With the node on this machine that is a native folder picker; from any // other browser the operator has to type the path, because nothing in a web // page can browse a remote disk. Both end at the same signed op. const addRootAtPath = useCallback(async (path, name) => { if (isLocal) { if ((localRoots || []).some(r => r.path === path)) return true; const isFirst = (localRoots || []).length === 0; // The first directory is writable so a new group can receive an upload // without the operator having to find this switch first. Every later // one is read-only until they say otherwise. if (onLocalRootsChange) { onLocalRootsChange([...(localRoots || []), { name, path, writable: isFirst, removable: false }]); } return true; } setIndexProgress(null); return run(async () => { if (overMnp) { await transport.addRoot(groupId, path, { name }, signFn); } else if (overLoopback) { await platform.node.call('POST', '/api/groups/' + groupId + '/roots', { path, name }); await platform.node.call('POST', '/api/reload'); await platform.watchIndexProgress(groupId, setIndexProgress); } else throw new Error(t('node.root_no_route')); }); }, [isLocal, localRoots, onLocalRootsChange, overMnp, overLoopback, transport, groupId, signFn, run]); const doPickRoot = useCallback(async () => { const chosen = await platform.rootPicker.choose(); if (!chosen) return; const ok = await addRootAtPath(chosen.path, chosen.name); if (ok && !isLocal) say(t('node.root_added')); }, [addRootAtPath, isLocal]); const doAddByPath = useCallback(async () => { const path = pathDraft.trim(); if (!path) return; // The name is the node's business — it derives the basename and refuses a // duplicate. Sending one guessed from a string typed here would be a // second opinion about something already decided in one place. const ok = await addRootAtPath(path, ''); if (ok) { setPathDraft(''); setAddingByPath(false); if (!isLocal) say(t('node.root_added')); } }, [pathDraft, addRootAtPath, isLocal]); const addControls = !canEdit ? '' : html` ${platform.rootPicker.available ? html` ` : addingByPath ? html`
setPathDraft(e.target.value)} onKeyDown=${(e) => { if (e.key === 'Enter') doAddByPath(); }} />

${t('node.root_path_hint')}

` : html` `} `; if (!displayRoots.length) { return html`

${t('settings_node.shared_directories_hint')}

${addControls} ${message}
`; } return html`
${hasPaths && html``} ${canEdit && html``} ${canEdit && !isLocal && html``} ${displayRoots.map(r => { const rowClass = r.ejected ? 'sdt-row-ejected' : (!isLocal && r.available === false) ? 'sdt-row-unavail' : ''; return html` ${hasPaths && html` `} ${/* The same string as the column head above, and deliberately the same key: below 768px the head is gone — the row is two stacked lines there, not a table row — and a bare switch with nothing beside it says nothing at all. The label is hidden by the stylesheet at every width where the column head is doing the job. */''} ${canEdit && html` `} ${canEdit && !isLocal && html` `} `; })}
${t('node.directory')}${t('node.root_path')}${t('node.root_rw')}${t('node.removable')}
<${Icon} name="folder" /> ${r.name} ${r.ejected && html` ${t('group.root_ejected')}`} ${!isLocal && r.available === false && !r.ejected && html` ${t('node.unavailable')}`} ${r.path || ''} <${ToggleSwitch} checked=${!!r.writable} disabled=${busy || !!r.ejected} label=${t('node.root_rw')} onChange=${(v) => doUpdateRoot(r.name, { writable: v })} /> <${ToggleSwitch} checked=${!!r.removable} disabled=${busy} label=${t('node.removable')} onChange=${(v) => doUpdateRoot(r.name, { removable: v })} /> ${canEdit && !isLocal && html` `} ${canEdit && html` `}
${addControls} ${message} ${indexProgress && indexProgress.scanning && html`
${t('wizard.indexing_progress', { pct: indexProgress.total_bytes ? Math.min(100, Math.round( 100 * indexProgress.scanned_bytes / indexProgress.total_bytes)) : 0, })}
`}
`; } // ── Members Panel ──────────────────────────────────────────────────────── /** * Everything about the group that is not its files or its chat. * * Was "Members", which was a list with three unrelated forms stacked on top of * it and the group's own controls somewhere else entirely — leaving or deleting * a group lived in the header, beside its title. One tab now, in sections, with * the roster last: it is the part that grows without limit, and burying the * controls under two hundred names is how a tab stops being usable. */ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef, isNodeAdmin, userId, operatorPaired, connected, mnpRoots, enabledApps, onEnabledApps, scanSettings, onScanSettings, searchListed, entries, nodeDirs, appSettings, onAppDirectories, onRefreshIndex, onPaired, onLeft }) { const [members, setMembers] = useState([]); const [adminId, setAdminId] = useState(''); const [loading, setLoading] = useState(true); const [inviteUser, setInviteUser] = useState(''); const [inviting, setInviting] = useState(false); const [error, setError] = useState(''); // Node loopback state (Electron-only) const [nodeDetected, setNodeDetected] = useState(false); const [nodeRoots, setNodeRoots] = useState([]); const [nodeGroupName, setNodeGroupName] = useState(''); const [nodeBusy, setNodeBusy] = useState(false); const [nodeMsg, setNodeMsg] = useState(''); // Bytes-based indexing progress while a newly added directory is being // scanned — same source as the Create Group wizard's step, see // platform.watchIndexProgress. const [nodeIndexProgress, setNodeIndexProgress] = useState(null); // The roots to show, from whichever source can actually answer. // // `mnpRoots` comes from the index payload the node pushes over the live // connection, and is the only source an operator signing in from an // ordinary browser has. `nodeRoots` comes from the loopback API and exists // only on the machine running the node. Preferring MNP when connected also // keeps this table on the same data Files and the apps read, so an eject // shows in one place at the same instant it shows in the other. const effectiveRoots = (connected && mnpRoots && mnpRoots.length) ? mnpRoots : nodeRoots; // Declared here rather than inline at the call site: a function rebuilt on // every render is a new prop identity every render, and the callbacks that // close over it in the table below are memoised on it. const adminSignFn = useCallback((transcript) => { const sk = transportRef.current && transportRef.current.sessionKeys && transportRef.current.sessionKeys.skEdB64; if (!sk || !window.MeshBayKeys) { throw new Error(t('node.root_no_signing_key')); } return window.MeshBayKeys.signBytes(sk, transcript); }, [transportRef]); const loadNodeInfo = useCallback(async () => { if (!platform.node.available) return; try { const detect = await platform.node.detect(); if (!detect.detected) { setNodeDetected(false); return; } setNodeDetected(true); const data = await platform.node.call('GET', '/api/groups'); const groups = data.groups || []; const ng = groups.find(g => g.id === groupId); if (ng) { setNodeRoots(ng.roots || []); setNodeGroupName(ng.name || ''); } } catch { setNodeDetected(false); } }, [groupId]); useEffect(() => { loadNodeInfo(); }, [loadNodeInfo]); /** * Poll /api/groups until the root count actually matches what an * add/remove just did, instead of trusting a single loadNodeInfo() call * right after /api/reload. Found live: /api/reload is fire-and-forget on * the node (ops.start_reload schedules the real work and returns * immediately, deliberately — a brand-new group's initial scan can take * minutes, see its own docstring) — and the list this section renders * (ops.list_groups) reads the *runtime* root set * (groups_ctx[gid]["roots"]), which only gets replaced once * _reload_config_inner's retarget actually finishes, not the config-file * list add_root/remove_root already updated synchronously. A single * fetch right after can land in that gap and show the old count. */ const waitForRootCount = useCallback(async (expectedCount) => { for (let i = 0; i < 10; i++) { try { const data = await platform.node.call('GET', '/api/groups'); const ng = (data.groups || []).find(g => g.id === groupId); const roots = (ng && ng.roots) || []; if (roots.length === expectedCount) { setNodeRoots(roots); if (ng) setNodeGroupName(ng.name || ''); return true; } } catch { /* keep trying — the node may be mid-reload */ } await new Promise(r => setTimeout(r, 400)); } return false; }, [groupId]); const [inviteCode, setInviteCode] = useState(null); const [pairCode, setPairCode] = useState(''); const [pairStatus, setPairStatus] = useState(''); const [pairing, setPairing] = useState(false); // Your own devices on this node. Not a members feature — it is beside them // because this is where a live connection to the node exists. const [devices, setDevices] = useState([]); const [approveCode, setApproveCode] = useState(''); const [deviceMsg, setDeviceMsg] = useState(''); // Pairing lives here rather than in Settings because this is where a live // connection to the node exists — and it is offered only when the node itself // says this account is its operator (is_node_admin comes from the authenticated // handshake_ack, not from the hub). const loadDevices = useCallback(async () => { const transport = transportRef.current; if (!transport || !transport.connected) return; try { const out = await transport.listDevices(); setDevices(out.devices); } catch { /* a node that has none says so by listing none */ } }, [transportRef]); useEffect(() => { loadDevices(); }, [loadDevices]); const approveDevice = useCallback(async (e) => { e.preventDefault(); const code = approveCode.trim(); if (!code) return; setDeviceMsg(''); try { await transportRef.current.approveDevice(userId, code); setApproveCode(''); setDeviceMsg(t('device.approved')); await loadDevices(); } catch (err) { setDeviceMsg(err.message); } }, [approveCode, userId, transportRef, loadDevices]); const revokeDevice = useCallback(async (device) => { if (!confirm(t('device.revoke_confirm'))) return; setDeviceMsg(''); try { await transportRef.current.revokeDevice( userId, device.pk_ed25519, device.pk_x25519 || ''); await loadDevices(); } catch (err) { setDeviceMsg(err.message); } }, [userId, transportRef, loadDevices]); const doPair = useCallback(async (e) => { e.preventDefault(); const code = pairCode.trim(); if (!code) return; setPairing(true); setPairStatus(''); try { const transport = transportRef && transportRef.current; if (!transport || !transport.connected) throw new Error('Not connected to the node'); await transport.pairOperator(userId, code); setPairCode(''); setPairStatus('paired'); // The node has pinned this key as an operator key; the form has nothing // left to do. It used to stay put through a refresh, because what governed // it was the account, which pairing does not change. if (onPaired) onPaired(); } catch (err) { setPairStatus(err.message); } finally { setPairing(false); } }, [pairCode, transportRef, userId]); // DEPRECATED: upload toggle removed — per-root writable flag replaces it. const [appsBusy, setAppsBusy] = useState(false); const [appsMsg, setAppsMsg] = useState(''); // `availableApps()` rather than the raw registry: an app the reader is not // shown must not be turned on for the whole group by falling back to "all of // them". Found by adding one that is hidden by default — an ordinary app // would never have exposed the difference. const activeApps = enabledApps && enabledApps.length ? enabledApps : availableApps().map(a => a.key); /** * Toggle one app in or out of the group's enabled set. Same shape as * `setUploads`: signed, and the checkbox does not move until the node has * said it did it. Refuses to submit an empty set client-side — the node * refuses it too, but there is no reason to make a round trip to learn that. */ const toggleApp = useCallback(async (key) => { const next = activeApps.includes(key) ? activeApps.filter(k => k !== key) : [...activeApps, key]; if (next.length === 0) { setAppsMsg(t('members.apps_need_one')); return; } const transport = transportRef && transportRef.current; setAppsMsg(''); setAppsBusy(true); try { if (!transport || !transport.connected) { throw new Error('Not connected to the node'); } const sk = transport.sessionKeys && transport.sessionKeys.skEdB64; const signFn = (sk && window.MeshBayKeys) ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript) : null; await transport.setAppsEnabled(next, signFn); if (onEnabledApps) onEnabledApps(next); } catch (err) { setAppsMsg(err.message); } finally { setAppsBusy(false); } }, [transportRef, onEnabledApps, activeApps]); const [scanBusy, setScanBusy] = useState(false); const [scanMsg, setScanMsg] = useState(''); const [reconcileMinutes, setReconcileMinutes] = useState( scanSettings ? Math.round(scanSettings.reconcile_interval_secs / 60) : 10); const [debounceSeconds, setDebounceSeconds] = useState( scanSettings ? Math.round(scanSettings.debounce_secs) : 2); // The node is the source of truth; once it has answered, the fields track // it rather than whatever this browser guessed before connecting. useEffect(() => { if (!scanSettings) return; setReconcileMinutes(Math.round(scanSettings.reconcile_interval_secs / 60)); setDebounceSeconds(Math.round(scanSettings.debounce_secs)); }, [scanSettings]); /** * How often the reconciliation backstop runs, and how long a changed file * is left alone before being hashed. Same shape as toggleApp: signed, and * the fields do not claim success until the node has confirmed it. */ const saveScanSettings = useCallback(async () => { const transport = transportRef && transportRef.current; setScanMsg(''); setScanBusy(true); try { if (!transport || !transport.connected) { throw new Error('Not connected to the node'); } const sk = transport.sessionKeys && transport.sessionKeys.skEdB64; const signFn = (sk && window.MeshBayKeys) ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript) : null; await transport.setScanSettings(reconcileMinutes * 60, debounceSeconds, signFn); const applied = { reconcile_interval_secs: reconcileMinutes * 60, debounce_secs: debounceSeconds, }; if (onScanSettings) onScanSettings(applied); setScanMsg(t('settings_node.scan_saved')); } catch (err) { setScanMsg(err.message); } finally { setScanBusy(false); } }, [transportRef, onScanSettings, reconcileMinutes, debounceSeconds]); // Whether members' cross-group Search lists this group. The switch follows // the node's answer: the ack is broadcast and replayed to the requester // (transport.js BROADCAST_ACK_TYPES), which is what moves `searchListed`. const [listedBusy, setListedBusy] = useState(false); const [listedMsg, setListedMsg] = useState(''); const toggleSearchListed = useCallback(async (next) => { const transport = transportRef && transportRef.current; setListedMsg(''); setListedBusy(true); try { if (!transport || !transport.connected) { throw new Error('Not connected to the node'); } await transport.setSearchListed(next, adminSignFn); } catch (err) { setListedMsg(err.message); } finally { setListedBusy(false); } }, [transportRef, adminSignFn]); // ── Per-app settings ──────────────────────────────────────────────── // // What every app's settings pane is given, and the one operation the page // performs on their behalf. TMDB, MusicBrainz and each app's folder pickers // used to be hand-written sections here, ~470 lines of them, each with its // own draft state and save handler saying the same thing about a different // key. They live in `-app-settings.js` now; this is the whole of what // the page still knows about any of it. // Every folder anywhere in the group's shared index. `entries[].path` is a // file's containing directory (files-app.js's convention), so every ancestor // prefix of it is a real folder; `nodeDirs` covers the ones with nothing in // them yet. Derived here rather than in the picker so all of them agree, and // so it is computed once per change instead of once per open. const folderOptions = useMemo(() => { const set = new Set(); const addAncestors = (path) => { if (!path) return; const parts = path.split('/'); for (let i = 1; i <= parts.length; i++) set.add(parts.slice(0, i).join('/')); }; for (const e of (entries || [])) addAncestors(e.path); for (const d of (nodeDirs || [])) addAncestors(d); return [...set].sort(); }, [entries, nodeDirs]); /** * Point one app at folders — the only app-specific operation this page * performs, and it is generic. * * Everything else a pane needs it does itself with the transport it is * given. That is the line: what every app has (directories) is here, what * one app alone has (a TMDB key, a link-preview switch) is in its own file, * and adding an app that only needs directories touches neither. */ const saveAppDirectories = useCallback(async (appKey, paths) => { const transport = transportRef && transportRef.current; if (!transport || !transport.connected) { throw new Error(t('node.root_no_route')); } await transport.setAppDirectories(appKey, paths, adminSignFn); if (onAppDirectories) onAppDirectories(appKey, paths); }, [transportRef, adminSignFn, onAppDirectories]); const [removing, setRemoving] = useState(''); /** * Take someone out of this group: both halves, in the order that fails safe. * * The node first, because that is the half that stops the group key being * wrapped for them; if the hub removal then fails, they are a member on paper * with no key. The other order would leave them able to reach a node that * still serves them. */ const removeMember = useCallback(async (member) => { const transport = transportRef && transportRef.current; setError(''); setRemoving(member.user_id); try { if (platform.node.available) { try { await platform.node.call('POST', `/api/members/${member.user_id}/revoke?group_id=${groupId}`); } catch { /* best effort — node may not host this group */ } try { await platform.node.call('POST', `/api/members/${member.user_id}/unpin`); } catch { /* best effort */ } } else if (transport && transport.connected && operatorPaired) { const sk = transport.sessionKeys && transport.sessionKeys.skEdB64; const signFn = (sk && window.MeshBayKeys) ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript) : null; await transport.revokeMember(member.user_id, signFn); } await hubFetch(`/v1/groups/${groupId}/members/${member.username}`, { method: 'DELETE', token, }); loadMembers(); } catch (err) { setError(err.message); } finally { setRemoving(''); } }, [groupId, token, transportRef, operatorPaired]); const loadMembers = useCallback(() => { setLoading(true); hubFetch(`/v1/groups/${groupId}/members`, { token }) .then(data => { setMembers(data.members || []); setAdminId(data.admin_id || ''); }) .catch(() => {}) .finally(() => setLoading(false)); }, [groupId, token]); useEffect(() => { loadMembers(); }, [loadMembers]); const isAdmin = group && group.is_admin; const doInvite = useCallback(async (e) => { e.preventDefault(); if (!inviteUser.trim()) return; setInviting(true); setError(''); setInviteCode(null); try { const transport = transportRef && transportRef.current; const username = inviteUser.trim(); if (!transport || !transport.connected) { throw new Error('Not connected to the node — it must be online to invite'); } // The hub is asked for the account id, and nothing else. It is no longer // asked for the invitee's public key: the node wraps the group key itself, // for a key the invitee proves possession of when they connect (H3). A hub // that answered with the wrong account here would produce an invite whose // code it never learns — the code goes to a human, out of band. const account = await hubFetch(`/v1/users/${username}/pubkeys`, { token }); // Signed with the identity this node pinned for us — the only one it // will accept, and the only one we hold here. const sk = transport.sessionKeys && transport.sessionKeys.skEdB64; const signFn = (sk && window.MeshBayKeys) ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript) : null; const result = await transport.createInvite( account.user_id, groupId, username, signFn); // Membership on the hub is what lets them reach the node at all; the code // is what gets them the key. await hubFetch(`/v1/groups/${groupId}/members/${username}`, { method: 'POST', token, body: {}, }); // Send an email notification to the invitee with the code. // The hub decrypts their email server-side — the inviter never sees it. let emailStatus = 'no_email'; try { const notif = await hubFetch(`/v1/groups/${groupId}/invite-notify`, { method: 'POST', token, // No group_name: the hub reads it from the group row it has already // loaded. Sending one offered a second answer to a settled question, // and that answer was the subject line of an email the hub signs. body: { username, code: result.code }, }); emailStatus = notif.status; } catch { /* best effort */ } setInviteCode({ username, code: result.code, expires: result.expires_at, emailSent: emailStatus === 'sent', }); setInviteUser(''); loadMembers(); } catch (err) { setError(err.message); } finally { setInviting(false); } }, [groupId, token, inviteUser, loadMembers, transportRef]); if (loading) return html`

${t('explore.loading')}

`; const isOwner = Boolean(isAdmin); return html`
${error && html`
${error}
`} ${/* Inviting needs the node: it is the node that wraps the group key and issues the code, not the hub. Public groups admit anyone — no invite. The form stays in the DOM so a brief reconnect does not destroy the input the user is typing into — controls are disabled instead. */ isAdmin && group?.join_policy !== 'open' && html`

${t('members.invite_title')}

${!connected ? html`

${t('group.offline_title')}

` : !operatorPaired ? html`

${isNodeAdmin ? t('members.invite_needs_pairing') : t('members.invite_ask_operator')}

` : ''}
${inviteCode && html`

${t('members.invite_code_ready', { user: inviteCode.username })}

${inviteCode.code}

${inviteCode.emailSent ? html`

${t('members.invite_email_sent')}

` : html`

${t('members.invite_email_failed')}

` }

${t('members.invite_code_hint')}

`}
setInviteUser(e.target.value)} disabled=${!connected || !operatorPaired} required />
`} ${isNodeAdmin && !operatorPaired && connected && html`

${t('members.pair_title')}

${t('members.pair_hint')}

${pairStatus && html`

${pairStatus === 'paired' ? t('members.pair_success') : pairStatus}

`}
setPairCode(e.target.value)} required />
`} ${/* Shared directories — the group's root folders, and the structural control everything else in this page sits on top of, so it comes first. Rendered whenever the operator has a route to their node: a live MNP connection (any browser, anywhere) or the loopback API (the node on this machine). It used to require the second, which meant it rendered for nobody on the web. */ isNodeAdmin && (connected || nodeDetected) && html` <${CollapsibleSection} titleKey="settings_node.shared_directories_title">

${t('settings_node.shared_directories_hint')}

${!connected && nodeDetected && html`

${t('settings_node.roots_offline_hint')}

`} <${SharedDirectoriesTable} roots=${effectiveRoots} groupId=${groupId} transport=${transportRef.current} signFn=${adminSignFn} nodeDetected=${nodeDetected} onRootsChange=${loadNodeInfo} onRefreshIndex=${onRefreshIndex} /> `} ${/* One collapsible section per application, from the registry. Adding an app adds an entry to `apps.js` and a settings file; this loop names none of them. The toggle in the header *is* the enablement control — a separate checkbox list somewhere else meant the operator turned an app on in one place and configured it in another, with the two able to disagree. Collapsed by default, and the settings inside are not rendered at all while the app is off: a form for something that is not running is a form whose Save button does nothing anyone can see. */ isNodeAdmin && connected && configurableApps().map((app) => html` <${CollapsibleSection} key=${app.key} defaultOpen=${false} title=${html` <${Icon} name=${app.icon} />${' '}${t(app.labelKey)} `} action=${html` <${ToggleSwitch} checked=${activeApps.includes(app.key)} disabled=${appsBusy} onChange=${() => toggleApp(app.key)} /> `}> ${activeApps.includes(app.key) ? html`<${app.Settings} roots=${effectiveRoots} dirs=${folderOptions} settings=${appSettings} saveDirectories=${(paths) => saveAppDirectories(app.key, paths)} transport=${transportRef.current} signFn=${adminSignFn} />` : html`

${t('settings_app.disabled_hint')}

`} `)} ${appsMsg && html`

${appsMsg}

`} ${/* Whether this group shows up in members' cross-group Search. A listing preference, not a permission: the hint says so, because a switch next to "members" and "devices" reads as access control. */ isNodeAdmin && connected && html` <${CollapsibleSection} titleKey="settings_node.search_listed_title" defaultOpen=${false}>
<${ToggleSwitch} checked=${searchListed !== false} disabled=${listedBusy} onChange=${toggleSearchListed} label=${t('settings_node.search_listed_label')} />

${t('settings_node.search_listed_hint')}

${listedMsg && html`

${listedMsg}

`} `} ${/* How hard the node works watching its own disk — indexer.py DirectoryIndexer. A performance knob, not a permission: it changes nothing about who can see or do what. */ isNodeAdmin && connected && html` <${CollapsibleSection} titleKey="settings_node.scan_title" defaultOpen=${false}>

${t('settings_node.scan_hint')}

${scanMsg && html`

${scanMsg}

`} `} ${/* Delete/leave — node detach first (reversible), then hub delete (irreversible). Closed by default: a danger-zone action is one click away either way, but not the first thing seen on open. */ html` <${CollapsibleSection} defaultOpen=${false} title=${isOwner ? t('group.delete_group') : t('group.leave')}>
${isOwner ? t('members.danger_delete_hint') : t('members.danger_leave_hint')} ${isOwner ? html` ` : html` `}
`} ${/* Collapsed by default, unlike the sections around it. Nothing here needs attention in the ordinary case: the device you are reading this on is already linked, and the panel exists for the two rare errands — approving another device, or removing one. The prompt that *is* actionable, "this browser is not linked to this node yet" (device.add_title), lives in group-page.js and is unaffected. */''} ${connected && html` <${CollapsibleSection} title=${t('device.mine_title')} defaultOpen=${false}>

${t('device.mine_hint')}

${deviceMsg && html`

${deviceMsg}

`} ${devices.length === 0 ? html`

${t('device.mine_empty')}

` : html` `}

${t('device.approve_hint')}

setApproveCode(e.target.value)} />
`} <${CollapsibleSection} title=${`${t('group.tab_members')} (${members.length})`}> ${members.map(m => html` `)}
${t('admin.col_username')} ${t('members.group_role')}
${m.username} ${m.user_id === adminId ? html`${t('members.owner')}` : html`${t('members.member')}` } ${isAdmin && m.user_id !== adminId && html` `}
${isAdmin && members.length > 1 && html`

${t('members.remove_hint')}

`}
`; } // ── Chat Panel ────────────────────────────────────────────────────────── /** * Message text with its links made clickable. * * Only http and https, and built as elements rather than markup: a message is * something another member wrote, so it must never become HTML. `javascript:` * and `data:` are not matched at all, and the anchors carry noopener so the new * tab cannot reach back into this one. */ const URL_RE = /\bhttps?:\/\/[^\s<>"']+/gi; export { GroupSettingsPanel, SharedDirectoriesTable };