From f1c8a58d7a843dfa4081de6008e2e8131062097f Mon Sep 17 00:00:00 2001 From: Vassiliy Yegorov Date: Thu, 26 Nov 2026 22:09:59 +0700 Subject: [PATCH] dsh-lan-share 0.2.0: LAN/relay sharing with QR pairing --- .gitignore | 4 + README.md | 244 +++++++++ client.js | 1147 +++++++++++++++++++++++++++++++++++++++ config.js | 365 +++++++++++++ cordis.patch.yml | 4 + index.js | 308 +++++++++++ locale/en.json | 47 ++ locale/ru.json | 47 ++ package.json | 43 ++ proxy.js | 1215 ++++++++++++++++++++++++++++++++++++++++++ qr.js | 606 +++++++++++++++++++++ relay.js | 730 +++++++++++++++++++++++++ store.js | 364 +++++++++++++ test/config.test.mjs | 51 ++ test/proxy.test.mjs | 468 ++++++++++++++++ test/qr.test.mjs | 297 +++++++++++ 16 files changed, 5940 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 client.js create mode 100644 config.js create mode 100644 cordis.patch.yml create mode 100644 index.js create mode 100644 locale/en.json create mode 100644 locale/ru.json create mode 100644 package.json create mode 100644 proxy.js create mode 100644 qr.js create mode 100644 relay.js create mode 100644 store.js create mode 100644 test/config.test.mjs create mode 100644 test/proxy.test.mjs create mode 100644 test/qr.test.mjs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..013f58f --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +.DS_Store +*.log +test/.e2e-pending/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..924c75b --- /dev/null +++ b/README.md @@ -0,0 +1,244 @@ +# @local/dsh-lan-share + +Share the DSH Desktop Web GUI over the local network or through a public relay so a tablet can drive the +same Session: send messages, answer approvals, use the terminal, and read or +edit workspace files. Pairing is a one-time QR code; paired devices are +revocable and survive a Desktop restart. + +The plugin does not modify DSH core. It adds one LAN listener inside the +Desktop Host process and proxies it to the Host's loopback Web server, keeping +the Host's own browser cookie out of the tablet. + +Repository: `ssh://git@git.realmanual.ru:2022/pub/dsh-lan-share.git` +(web page: `https://git.realmanual.ru/pub/dsh-lan-share`). + +## Requirements + +- DSH Desktop 0.2.2-rc.1 (the tested release) or a compatible build. +- The tablet and the computer on the same network (no client isolation). +- macOS may ask for incoming-connection permission the first time the listener + starts. Allow the DSH application. + +## Install into the Desktop profile + +Clone the repository next to the other shared local plugins; the profile links +to that folder, so an app update does not delete it: + + git clone ssh://git@git.realmanual.ru:2022/pub/dsh-lan-share.git \ + "$DSH_HOME/plugins/lan-share" + cd "$DSH_HOME/profiles/desktop" + pnpm add "link:$DSH_HOME/plugins/lan-share" + +Then add the package to dsh.profile.bundles in +$DSH_HOME/profiles/desktop/package.json: + + "dsh": { + "profile": { + "bundles": [ + "@deepseek-ai/dsh-base", + "@deepseek-ai/dsh-web-app", + "@local/dsh-lan-share" + ] + } + } + +Restart DSH Desktop. The client half is served by the normal plugin graph; a +running process is not hot-patched by this installation. + +If pnpm refuses with ERR_PNPM_UNEXPECTED_STORE (a profile installed from a +different global store), create the link by hand; it is equivalent for the +Loader: + + ln -sfn "$DSH_HOME/plugins/lan-share" \ + "$DSH_HOME/profiles/desktop/node_modules/@local/dsh-lan-share" + +Then add the dependency and bundle entry to package.json as shown above. This +is how the copy on this machine was installed because its profile was created +with a different pnpm store. + +## Use + +- In a Session header press **Share** (Поделиться). +- The dialog opens with a **"Нажмите, чтобы показать QR-код"** placeholder. + Tap it to create and show a one-time QR; its timer is 60 seconds. The code is + refreshed in the background while the dialog stays open; the next tap shows + the waiting code (or a fresh one when it has aged). +- Scan the QR with a tablet camera on the same Wi-Fi. The scan does **not** + create the device immediately: the host shows a confirmation card with the + device label, IP and User-Agent. The tablet waits on a loading page. Press + **Подтвердить** to create the device and release the tablet; **Отклонить** + returns a denial page. The pending request expires after 2 minutes. +- The **Settings → LAN access** page shows the listening address, paired + devices, and the same tap-to-show QR. On a paired tablet it shows the + pairing and a "Disconnect this tablet" action instead. +- The URL row has an icon-only copy button; "New code" is not needed because + the hidden code is refreshed each minute. + +Each QR code is single-use and expires after 60 seconds. A paired device gets +a revocable cookie; it is not asked for a QR again until it is disconnected or +its lifetime (7 days by default) ends. The desktop confirmation is the second +factor: scanning alone creates only a pending request. + +## Internet relay + +The same host can publish itself through the separate dsh-relay container +(see https://git.realmanual.ru/bildme/dsh-relay). The Desktop dials the relay +over WSS, so its dynamic address and NAT do not matter. The relay only carries +bytes to the LAN listener; pairing, device cookies, and approvals stay here. + +Configure the plugin in $DSH_HOME/profiles/desktop/cordis.patch.yml: + + - id: lan-share + name: '@local/dsh-lan-share' + config: + relay: + enabled: true + url: wss://dsh.bildme.ru/tunnel + token: + publicOrigin: https://dsh.bildme.ru + +- publicOrigin is optional: the plugin uses the relay hello when it is absent. +- The token is sent in the WebSocket subprotocol, not in a URL. Keep the + profile file owner-only. +- relay.token must match the relay's AGENT_TOKEN character for character. A + mismatch rejects the WSS handshake and surfaces as websocket-error; check the + relay log for tunnel authentication failed. +- Environment overrides: DSH_RELAY_ENABLED, DSH_RELAY_URL, DSH_RELAY_TOKEN, + DSH_RELAY_PUBLIC_ORIGIN, DSH_RELAY_AGENT_ID. +- If the relay is enabled but offline, ticket creation returns relay-offline + and the Share dialog shows it. Set relay.fallbackToLan: true to fall back to + a LAN QR instead. +- A QR minted while the relay is connected contains + https://dsh.bildme.ru/s/. The tablet opens it over the internet; the + relay routes it to the one connected Desktop (or by ticket/cookie when + several are connected). +- Restart DSH Desktop after changing the relay config. + +## Configuration table (relay fields) + +| Field | Default | Meaning | +|---|---|---| +| relay.enabled | false | Dial the relay. | +| relay.url | null | wss://.../tunnel. | +| relay.token | null | Shared AGENT_TOKEN. | +| relay.publicOrigin | null | Public HTTPS origin used for QR codes. | +| relay.agentId | null | Optional log identity. | +| relay.fallbackToLan | false | Mint a LAN QR when the relay is offline. | + + +## Configuration + +Defaults are compiled in. Override them in +$DSH_HOME/profiles/desktop/cordis.patch.yml by targeting the inserted row: + + - id: lan-share + name: '@local/dsh-lan-share' + config: + host: 192.168.1.20 + port: 47820 + ticketTtlSeconds: 60 + deviceTtlDays: 7 + maxDevices: 16 + tls: + certFile: /path/to/cert.pem + keyFile: /path/to/key.pem + +| Field | Default | Meaning | +|---|---|---| +| enabled | true | Start the listener. | +| host | auto | LAN IP literal to bind, or 0.0.0.0 with publicHost. Auto prefers RFC 1918 (192.168/10/172.16) and ignores Tailscale/CGNAT 100.64/10 default routes. | +| publicHost | host | Address written into QR codes; a DNS name is allowed. | +| port | 47820 | LAN port. If busy, one fallback to an OS-assigned port is reported in the UI. | +| ticketTtlSeconds | 60 | One-time QR lifetime. | +| deviceTtlDays | 7 | How long a paired device stays valid. | +| maxDevices | 16 | Rejects new pairings beyond this count. | +| stateFile | $DSH_HOME/lan-share/devices.json | Device registry; mode 0600. | +| tls | null | Optional certificate and key for the LAN listener. | + +## Security model + +- The Host Web server stays loopback-only. The LAN listener is a separate + authenticated reverse proxy. +- The tablet never receives the Host's browser cookie. The proxy mints that + cookie internally through the Host launch URL, keeps it warm, and re-mints it + when the port changes or the Host answers 401. +- A tablet authenticates with its own dsh-lan-device cookie. Only a SHA-256 + digest of its secret is written to stateFile; the cookie itself is HttpOnly, + SameSite=Lax, and host-only. +- A one-time ticket is 32 random bytes, stored only as a digest, valid for one + GET, and consumed atomically. +- Paired devices have full owner authority over this DSH instance. Pair only + people and devices you trust, and disconnect devices you stop using. +- Plain HTTP over a local network exposes the device cookie to anyone who can + observe the network. Configure tls with a certificate the tablet trusts when + that matters. +- Management routes (/api/lan-share/ticket, /revoke, /state) exist only on the + Host's loopback server. The LAN listener refuses them with 403. + +## How it works + + Tablet ──HTTP/WS──▶ LAN listener :47820 ──▶ 127.0.0.1: + │ device cookie + header rewrite + └─ minted Host browser cookie + +The proxy rewrites requests the same way the Electron shell's dsh-app://app +forwarding does: Host names the upstream authority, Origin is removed for HTTP +and set to the upstream origin for WebSocket upgrades, and the minted cookie is +attached. Streaming responses, SSE, range requests, and upgrades are passed +through without buffering. + +## Files + +| File | Role | +|---|---| +| index.js | Cordis wiring and the loopback-only control API. | +| config.js | Config validation, LAN address detection, authority helpers. | +| store.js | Device registry (durable, digest-only) and one-time tickets. | +| proxy.js | LAN listener, authentication, HTTP/WebSocket proxy. | +| qr.js | Byte-mode QR encoder (ECC M, versions 1–10). | +| client.js | Share dialog, Settings page, paired-tablet Session sync. | + +## Tests + + cd "$DSH_HOME/plugins/lan-share" + node --test test/ + +The suite covers the QR encoder (including a spec-derived decoder and +Reed-Solomon checks), device/ticket lifetimes, header rewriting, one-time +pairing, cookies, streaming, redirects, WebSocket upgrades, revocation, and +the 401 re-mint path against a fake Host. + +## Troubleshooting + +- Not listening / no LAN address: auto now prefers a real RFC 1918 LAN address. On a VPN-only machine + automatic discovery may pick the wrong interface. +- Port busy: the UI reports the fallback port. Fix port or stop the other + process. +- Tablet cannot connect: check that both devices are on the same network, the + router does not isolate clients, and the macOS firewall allows DSH. +- Code expired or already used: create a new code; a QR is one-time. +- Tablet shows "Pairing required" after a restart: its device lifetime ended + or it was disconnected. Pair again. +- A native folder picker opened on the computer: the desktop composition uses + the OS picker, which runs on the Host. This is a known limitation of remote + use; prefer existing Workspaces. + +## Known limitations + +- This is Session sharing, not screen mirroring: the tablet sees the same Web + GUI and Session, not pixels of the desktop window. +- A paired device has owner authority; there is no read-only viewer tier. +- The native directory picker and "open in app" actions execute on the Host. +- Multiple Desktop instances are not supported; the second one falls back to an + OS-assigned LAN port, and the device registry is last-writer-wins. +- The LAN address is part of the device cookie scope; changing networks (and + therefore the address) requires pairing again. +- No mDNS name, certificate provisioning, or PWA install flow. + +## Uninstall + + cd "$DSH_HOME/profiles/desktop" + pnpm remove @local/dsh-lan-share + +Remove @local/dsh-lan-share from dsh.profile.bundles, restart DSH, then delete +$DSH_HOME/lan-share/ if the device registry is no longer needed. \ No newline at end of file diff --git a/client.js b/client.js new file mode 100644 index 0000000..7b078f8 --- /dev/null +++ b/client.js @@ -0,0 +1,1147 @@ +/** + * Client half of LAN Share. + * + * On the host computer it contributes a Share control to the conversation + * header and a management page to Settings. On a paired tablet it contributes + * no controls, opens the Session recorded with the device, and remembers the + * Session the user navigates to so a reload returns there. + * + * The QR matrix is produced by the Host half; this file only renders it. That + * keeps the browser bundle small and lets the encoder be tested in Node. + */ +window.__ModuleLoader__.load({ + id: '@local/dsh-lan-share', + factory(require) { + const React = require('react'); + const ReactDOM = require('react-dom'); + const { createSnapshotStore } = require('@deepseek-ai/dsh-client-store'); + const h = React.createElement; + + const NS = 'lanShare'; + const PLUGIN_ID = '@local/dsh-lan-share'; + const CSS_ID = PLUGIN_ID + '/lan-share.css'; + const API = '/api/lan-share'; + + const en = { + 'share.label': 'Share', + 'share.tooltip': 'Share this session over the local network', + 'section.title': 'LAN access', + 'section.icon': 'LAN access', + 'dialog.title': 'Share this session', + 'dialog.subtitle': 'Scan the code with a tablet camera on the same Wi-Fi network.', + 'dialog.expires': 'One-time code. It works once and expires in {time}.', + 'dialog.expired': 'This code has expired. Refresh it to pair another device.', + 'dialog.urlLabel': 'Or open this address', + 'dialog.copy': 'Copy link', + 'dialog.copied': 'Copied', + 'dialog.refresh': 'New code', + 'dialog.close': 'Close', + 'dialog.pair': 'Pair a device', + 'dialog.pairHint': 'Create a one-time code for a tablet on the same network.', + 'dialog.showQr': 'Tap to show the QR code', + 'dialog.showHint': 'The one-time code stays valid for one minute.', + 'dialog.loading': 'Creating code…', + 'pending.title': 'A device wants to connect', + 'pending.device': 'Device: {label} · {ip}', + 'pending.expires': 'Confirm the connection within {time}.', + 'pending.approve': 'Confirm', + 'pending.deny': 'Deny', + 'pending.unknownDevice': 'Unknown device', + 'devices.title': 'Paired devices', + 'devices.empty': 'No devices are paired yet.', + 'devices.online': 'online', + 'devices.offline': 'offline', + 'devices.session': 'session {id}', + 'devices.revoke': 'Disconnect', + 'devices.revokeAll': 'Disconnect all', + 'devices.confirmRevoke': 'Disconnect this device?', + 'devices.confirmRevokeAll': 'Disconnect every paired device?', + 'status.listening': 'Listening on {origin}', + 'status.notListening': 'Not listening: {reason}', + 'status.fallback': 'The default port was busy, so this run uses {port}.', + 'status.mintError': 'The host session could not be authenticated: {detail}', + 'relay.connected': 'Internet relay: {origin}', + 'relay.offline': 'Internet relay is offline: {error}', + 'relay.disabled': 'Internet relay is not configured.', + 'relay.publicOrigin': 'Public address: {origin}', + 'relay.error.websocket': 'WSS connection failed. Check relay.url, the certificate, and that relay.token matches the relay AGENT_TOKEN.', + 'relay.error.unavailable': 'This runtime has no WebSocket client, so the relay cannot connect.', + 'warning.fullAccess': 'A paired device gets full owner control of this DSH instance, including tools and approvals.', + 'warning.http': 'Traffic is plain HTTP on the local network. Pair only on a network you trust.', + 'error.ticket': 'Could not create a pairing code.', + 'error.deviceLimit': 'The device limit is reached. Disconnect an old device first.', + 'error.unknownSession': 'This session is no longer available.', + 'error.notRunning': 'The LAN listener is not running.', + 'error.noLan': 'No LAN address was found. Set the host in the plugin configuration.', + 'error.generic': 'Could not reach the host.', + 'error.relayOffline': 'The relay is not connected. Check the internet connection on the host computer.', + 'error.unavailable': 'LAN access is unavailable in this composition.', + 'remote.title': 'Connected to a host', + 'remote.body': 'This browser is paired with the DSH desktop at {origin}. Manage pairings on the host computer.', + 'remote.device': 'This device: {label}', + 'remote.disconnect': 'Disconnect this tablet', + 'remote.confirm': 'Disconnect this tablet from the host?', + 'remote.disconnected': 'Disconnected.', + 'qr.aria': 'Pairing QR code', + 'loading': 'Loading…', + }; + + const ru = { + 'share.label': 'Поделиться', + 'share.tooltip': 'Открыть этот сеанс в локальной сети', + 'section.title': 'Общий доступ по сети', + 'section.icon': 'Общий доступ по сети', + 'dialog.title': 'Поделиться сеансом', + 'dialog.subtitle': 'Отсканируйте код камерой планшета в той же сети Wi-Fi.', + 'dialog.expires': 'Одноразовый код. Он сработает один раз и истечёт через {time}.', + 'dialog.expired': 'Код истёк. Обновите его, чтобы подключить другое устройство.', + 'dialog.urlLabel': 'Или откройте этот адрес', + 'dialog.copy': 'Скопировать ссылку', + 'dialog.copied': 'Скопировано', + 'dialog.refresh': 'Новый код', + 'dialog.close': 'Закрыть', + 'dialog.pair': 'Подключить устройство', + 'dialog.pairHint': 'Создайте одноразовый код для планшета в этой же сети.', + 'dialog.showQr': 'Нажмите, чтобы показать QR-код', + 'dialog.showHint': 'Одноразовый код будет действовать одну минуту.', + 'dialog.loading': 'Создаём код…', + 'pending.title': 'Устройство хочет подключиться', + 'pending.device': 'Устройство: {label} · {ip}', + 'pending.expires': 'Подтвердите подключение в течение {time}.', + 'pending.approve': 'Подтвердить', + 'pending.deny': 'Отклонить', + 'pending.unknownDevice': 'Неизвестное устройство', + 'devices.title': 'Подключённые устройства', + 'devices.empty': 'Пока нет подключённых устройств.', + 'devices.online': 'в сети', + 'devices.offline': 'не в сети', + 'devices.session': 'сеанс {id}', + 'devices.revoke': 'Отключить', + 'devices.revokeAll': 'Отключить все', + 'devices.confirmRevoke': 'Отключить это устройство?', + 'devices.confirmRevokeAll': 'Отключить все подключённые устройства?', + 'status.listening': 'Слушает {origin}', + 'status.notListening': 'Не запущено: {reason}', + 'status.fallback': 'Порт по умолчанию занят, поэтому используется {port}.', + 'status.mintError': 'Не удалось подтвердить сеанс на host: {detail}', + 'relay.connected': 'Интернет-релей: {origin}', + 'relay.offline': 'Интернет-релей не подключён: {error}', + 'relay.disabled': 'Интернет-релей не настроен.', + 'relay.publicOrigin': 'Публичный адрес: {origin}', + 'relay.error.websocket': 'Не удалось открыть WSS. Проверьте relay.url, сертификат и совпадение relay.token с AGENT_TOKEN релея.', + 'relay.error.unavailable': 'В этой среде нет WebSocket-клиента, поэтому релей не может подключиться.', + 'warning.fullAccess': 'Подключённое устройство получает полный доступ владельца к этому DSH, включая инструменты и подтверждения.', + 'warning.http': 'Трафик идёт по обычному HTTP в локальной сети. Подключайте устройства только в доверенной сети.', + 'error.ticket': 'Не удалось создать код подключения.', + 'error.deviceLimit': 'Достигнут лимит устройств. Сначала отключите старое.', + 'error.unknownSession': 'Этот сеанс больше недоступен.', + 'error.notRunning': 'LAN-листенер не запущен.', + 'error.noLan': 'Не найден LAN-адрес. Укажите host в конфигурации плагина.', + 'error.generic': 'Не удалось связаться с host.', + 'error.relayOffline': 'Релей недоступен. Проверьте интернет на компьютере.', + 'error.unavailable': 'Общий доступ по сети недоступен в этой конфигурации.', + 'remote.title': 'Подключено к host', + 'remote.body': 'Этот браузер подключён к DSH Desktop по адресу {origin}. Управление привязками — на компьютере.', + 'remote.device': 'Это устройство: {label}', + 'remote.disconnect': 'Отключить этот планшет', + 'remote.confirm': 'Отключить этот планшет от host?', + 'remote.disconnected': 'Отключено.', + 'qr.aria': 'QR-код для подключения', + 'loading': 'Загрузка…', + }; + + const DICTIONARIES = { en, ru }; + + /** Copy for one key with simple {name} interpolation. */ + function format(template, params) { + if (params === undefined) return template; + return template.replace(/\{(\w+)\}/g, (match, name) => String(params[name] ?? '')); + } + + /** Milliseconds as m:ss, or h:mm:ss for long waits. */ + function clock(ms) { + const total = Math.max(0, Math.ceil(ms / 1000)); + const hours = Math.floor(total / 3600); + const minutes = Math.floor((total % 3600) / 60); + const seconds = total % 60; + if (hours > 0) return hours + ':' + String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0'); + return String(minutes) + ':' + String(seconds).padStart(2, '0'); + } + + /** A live "now" that re-renders every interval. */ + function useNow(interval) { + const [now, setNow] = React.useState(() => Date.now()); + React.useEffect(() => { + const timer = setInterval(() => setNow(Date.now()), interval); + return () => clearInterval(timer); + }, [interval]); + return now; + } + + /** Copy text with a clipboard fallback for insecure origins. */ + async function copyText(text) { + try { + if (navigator.clipboard?.writeText) { + await navigator.clipboard.writeText(text); + return true; + } + } catch { + /* fall through to the legacy path */ + } + try { + const area = document.createElement('textarea'); + area.value = text; + area.style.position = 'fixed'; + area.style.opacity = '0'; + area.style.pointerEvents = 'none'; + document.body.appendChild(area); + area.select(); + const ok = document.execCommand('copy'); + area.remove(); + return ok; + } catch { + return false; + } + } + + /** Read one JSON API response, tolerating a non-JSON error page. */ + async function readJson(response) { + try { + return await response.json(); + } catch { + return null; + } + } + + /** Error copy for a control-API refusal. */ + function errorFor(t, code) { + switch (code) { + case 'DEVICE_LIMIT': + case 'device-limit': + return t('error.deviceLimit'); + case 'unknown-session': + return t('error.unknownSession'); + case 'NOT_RUNNING': + case 'not-running': + return t('error.notRunning'); + case 'no-lan-address': + return t('error.noLan'); + case 'relay-offline': + return t('error.relayOffline'); + default: + return t('error.ticket'); + } + } + + /** A small QR glyph for the tap-to-reveal placeholder. */ + function QrGlyph() { + return h( + 'svg', + { className: 'dshLanShare_qrGlyph', viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': 'true' }, + h('rect', { x: 3, y: 3, width: 7, height: 7, rx: 1, stroke: 'currentColor', strokeWidth: 1.5 }), + h('rect', { x: 14, y: 3, width: 7, height: 7, rx: 1, stroke: 'currentColor', strokeWidth: 1.5 }), + h('rect', { x: 3, y: 14, width: 7, height: 7, rx: 1, stroke: 'currentColor', strokeWidth: 1.5 }), + h('rect', { x: 5.5, y: 5.5, width: 2, height: 2, fill: 'currentColor' }), + h('rect', { x: 16.5, y: 5.5, width: 2, height: 2, fill: 'currentColor' }), + h('rect', { x: 5.5, y: 16.5, width: 2, height: 2, fill: 'currentColor' }), + h('path', { d: 'M14 14h3v3h-3zM18 14h3v3h-3zM14 18h3v3h-3zM19 19h2v2h-2z', fill: 'currentColor' }), + ); + } + + /** A QR symbol rendered from the Host-produced matrix on a white tile. */ + function QrCode({ rows, size, label }) { + const count = Array.isArray(rows) ? rows.length : 0; + if (count === 0) return null; + let path = ''; + for (let y = 0; y < count; y++) { + const row = rows[y]; + for (let x = 0; x < count; x++) { + if (row[x] === '1') path += 'M' + String(x) + ' ' + String(y) + 'h1v1h-1z'; + } + } + const quiet = 4; + return h( + 'svg', + { + className: 'dshLanShare_qr', + viewBox: String(-quiet) + ' ' + String(-quiet) + ' ' + String(count + quiet * 2) + ' ' + String(count + quiet * 2), + width: size, + height: size, + role: 'img', + 'aria-label': label, + shapeRendering: 'crispEdges', + }, + h('rect', { x: -quiet, y: -quiet, width: count + quiet * 2, height: count + quiet * 2, fill: '#fff' }), + h('path', { d: path, fill: '#0b0b0c' }), + ); + } + + /** A small share glyph. */ + function ShareIcon() { + return h( + 'svg', + { viewBox: '0 0 16 16', width: 15, height: 15, fill: 'none', 'aria-hidden': 'true' }, + h('path', { + d: 'M8 1.8v7.4M8 1.8 5.2 4.6M8 1.8l2.8 2.8M3.2 8.4v4.4c0 .8.6 1.4 1.4 1.4h6.8c.8 0 1.4-.6 1.4-1.4V8.4', + stroke: 'currentColor', + strokeWidth: 1.3, + strokeLinecap: 'round', + strokeLinejoin: 'round', + }), + ); + } + + /** A small LAN glyph for the Settings navigation. */ + function LanIcon(props) { + const size = typeof props.size === 'number' ? props.size : 16; + return h( + 'svg', + { viewBox: '0 0 16 16', width: size, height: size, fill: 'none', 'aria-hidden': 'true' }, + h('path', { + d: 'M2.5 10.8a5.5 5.5 0 0 1 11 0M5 10.8a3 3 0 0 1 6 0M7.2 11.6a.8.8 0 1 0 1.6 0 .8.8 0 0 0-1.6 0Z', + stroke: 'currentColor', + strokeWidth: 1.2, + strokeLinecap: 'round', + }), + ); + } + + /** + * One status line for the listener. + * @param {{ state: any, t: Function }} props panel props. + */ + function ListenerStatus({ state, t }) { + if (state === null || state === undefined) return h('p', { className: 'dshLanShare_hint' }, t('loading')); + if (state.running === true) { + return h( + 'div', + { className: 'dshLanShare_status' }, + h('span', { className: 'dshLanShare_dot dshLanShare_dotOn', 'aria-hidden': 'true' }), + h('span', null, format(t('status.listening'), { origin: state.origin ?? '' })), + ); + } + const reason = state.error === 'no-lan-address' ? t('error.noLan') : String(state.error ?? 'unknown'); + return h( + 'div', + { className: 'dshLanShare_status dshLanShare_statusWarn' }, + h('span', { className: 'dshLanShare_dot', 'aria-hidden': 'true' }), + h('span', null, format(t('status.notListening'), { reason })), + ); + } + + /** Human copy for a relay error code. */ + function relayErrorText(t, error) { + if (error === 'websocket-error' || error === 'connect-failed') return t('relay.error.websocket'); + if (error === 'websocket-unavailable') return t('relay.error.unavailable'); + return String(error ?? 'unknown'); + } + + /** Internet-relay status line; absent when no relay is configured. */ + function RelayStatus({ state, t }) { + const relay = state?.relay; + if (relay === null || relay === undefined || relay.enabled !== true) return null; + if (relay.connected === true) { + return h( + 'div', + { className: 'dshLanShare_status' }, + h('span', { className: 'dshLanShare_dot dshLanShare_dotOn', 'aria-hidden': 'true' }), + h('span', null, format(t('relay.connected'), { origin: relay.publicOrigin ?? '' })), + ); + } + return h( + 'div', + { className: 'dshLanShare_status dshLanShare_statusWarn' }, + h('span', { className: 'dshLanShare_dot', 'aria-hidden': 'true' }), + h('span', null, format(t('relay.offline'), { error: relayErrorText(t, relay.error) })), + ); + } + + /** The device list shared by the dialog and the Settings page. */ + function DeviceList({ devices, t, onRevoke, onRevokeAll, busy }) { + if (!Array.isArray(devices) || devices.length === 0) { + return h('p', { className: 'dshLanShare_hint' }, t('devices.empty')); + } + return h( + 'div', + { className: 'dshLanShare_devices' }, + h( + 'div', + { className: 'dshLanShare_devicesHead' }, + h('span', null, t('devices.title')), + h( + 'button', + { type: 'button', className: 'dshLanShare_link', onClick: onRevokeAll, disabled: busy }, + t('devices.revokeAll'), + ), + ), + ...devices.map((device) => + h( + 'div', + { key: device.id, className: 'dshLanShare_device' }, + h('span', { + className: 'dshLanShare_dot' + (device.online === true ? ' dshLanShare_dotOn' : ''), + 'aria-hidden': 'true', + }), + h( + 'div', + { className: 'dshLanShare_deviceBody' }, + h('span', { className: 'dshLanShare_deviceLabel' }, device.label), + h( + 'span', + { className: 'dshLanShare_deviceMeta' }, + (device.online === true ? t('devices.online') : t('devices.offline')) + + ' · ' + String(device.ip ?? '') + + (typeof device.sessionId === 'string' ? ' · ' + format(t('devices.session'), { id: device.sessionId.slice(0, 8) }) : ''), + ), + ), + h( + 'button', + { type: 'button', className: 'dshLanShare_button', onClick: () => onRevoke(device), disabled: busy }, + t('devices.revoke'), + ), + ), + ), + ); + } + + /** Copy-to-clipboard glyph for the URL row. */ + function CopyIcon() { + return h( + 'svg', + { viewBox: '0 0 16 16', width: 14, height: 14, fill: 'none', 'aria-hidden': 'true' }, + h('rect', { x: 5.5, y: 5.5, width: 8, height: 8, rx: 1.5, stroke: 'currentColor', strokeWidth: 1.3 }), + h('path', { d: 'M10.5 5.5V4A1.5 1.5 0 0 0 9 2.5H4A1.5 1.5 0 0 0 2.5 4v5A1.5 1.5 0 0 0 4 10.5h1.5', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round' }), + ); + } + + /** Confirmation check after the URL was copied. */ + function CheckIcon() { + return h( + 'svg', + { viewBox: '0 0 16 16', width: 14, height: 14, fill: 'none', 'aria-hidden': 'true' }, + h('path', { d: 'M3 8.5l3 3 7-7', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round' }), + ); + } + + /** One scanned QR waiting for the owner's decision. */ + function PendingCard({ pending, t, now, busy, onApprove, onDeny }) { + const remaining = Math.max(0, Number(pending.expiresAt ?? 0) - now); + const label = typeof pending.label === 'string' && pending.label !== '' ? pending.label : t('pending.unknownDevice'); + return h( + 'div', + { className: 'dshLanShare_pending' }, + h( + 'div', + { className: 'dshLanShare_pendingHead' }, + h('span', { className: 'dshLanShare_pendingDot', 'aria-hidden': 'true' }), + h('span', null, t('pending.title')), + ), + h('p', { className: 'dshLanShare_pendingDevice' }, format(t('pending.device'), { label, ip: String(pending.ip ?? '—') })), + typeof pending.userAgent === 'string' && pending.userAgent !== '' + ? h('p', { className: 'dshLanShare_pendingMeta', title: pending.userAgent }, pending.userAgent) + : null, + h('p', { className: 'dshLanShare_hint' }, format(t('pending.expires'), { time: clock(remaining) })), + h( + 'div', + { className: 'dshLanShare_pendingActions' }, + h('button', { type: 'button', className: 'dshLanShare_primary', onClick: onApprove, disabled: busy }, t('pending.approve')), + h('button', { type: 'button', className: 'dshLanShare_button', onClick: onDeny, disabled: busy }, t('pending.deny')), + ), + ); + } + + /** + * The pairing panel: status, QR, URL and devices. Used inside the dialog + * and embedded in Settings. + */ + function SharePanel({ sessionId, t, embedded }) { + const [ticket, setTicket] = React.useState(null); + const [revealed, setRevealed] = React.useState(false); + const [state, setState] = React.useState(null); + const [error, setError] = React.useState(''); + const [busy, setBusy] = React.useState(false); + const [copied, setCopied] = React.useState(false); + const alive = React.useRef(true); + const now = useNow(1000); + const pending = state !== null && Array.isArray(state.pending) && state.pending.length > 0 + ? state.pending[0] + : null; + const pendingId = pending === null ? null : pending.id; + + React.useEffect(() => { + alive.current = true; + return () => { + alive.current = false; + }; + }, []); + + /** Read listener status and devices. */ + const refreshState = React.useCallback(async () => { + try { + const response = await fetch(API + '/state', { headers: { accept: 'application/json' }, cache: 'no-store' }); + if (!response.ok) return; + const data = await readJson(response); + if (alive.current && data !== null) setState(data); + } catch { + /* keep the previous status */ + } + }, []); + + /** + * Mint one ticket bound to this Session. + * @param {{ reveal?: boolean }} [options] reveal immediately (true) or + * keep the fresh code behind the tap placeholder (false). + */ + const mint = React.useCallback(async (options = {}) => { + if (busy) return; + const shouldReveal = options.reveal !== false; + setBusy(true); + setError(''); + setCopied(false); + try { + const response = await fetch(API + '/ticket', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json' }, + body: JSON.stringify(typeof sessionId === 'string' && sessionId !== '' ? { sessionId } : {}), + }); + const data = await readJson(response); + if (alive.current === false) return; + if (!response.ok || data === null || data.ok !== true) { + setTicket(null); + setRevealed(false); + setError(errorFor(t, data?.code ?? (response.status === 404 ? 'unknown-session' : null))); + return; + } + setTicket(data); + setRevealed(shouldReveal); + refreshState(); + } catch { + if (alive.current) { + setTicket(null); + setRevealed(false); + setError(t('error.generic')); + } + } finally { + if (alive.current) setBusy(false); + } + }, [busy, refreshState, sessionId, t]); + + React.useEffect(() => { + refreshState(); + const timer = setInterval(refreshState, 2500); + return () => clearInterval(timer); + }, [refreshState]); + + /** Reveal the waiting code, or mint a fresh one when it went stale. */ + const reveal = React.useCallback(() => { + if (busy) return; + /* Background refresh keeps a hidden code ready. Show it only while it + * still has most of its minute; otherwise mint one with a full timer. */ + if (ticket !== null && Number(ticket.expiresAt) - Date.now() > 55_000) { + setRevealed(true); + return; + } + void mint(); + }, [busy, mint, ticket]); + + /* The hidden code is refreshed in the background every minute, so the + * next tap always reveals a usable QR. A scanned code pauses this loop: + * the pending request card takes over until the owner decides. */ + React.useEffect(() => { + if (pendingId !== null) return; + if (ticket === null) return; + if (Number(ticket.expiresAt) > now) return; + if (revealed) setRevealed(false); + void mint({ reveal: false }); + }, [now, revealed, ticket, pendingId, mint]); + + React.useEffect(() => { + if (pendingId === null) return; + setRevealed(false); + setTicket(null); + setCopied(false); + }, [pendingId]); + + /** Revoke one device after a confirmation. */ + const revoke = async (device) => { + if (!window.confirm(t('devices.confirmRevoke'))) return; + setBusy(true); + try { + await fetch(API + '/revoke', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ deviceId: device.id }), + }); + await refreshState(); + } catch { + setError(t('error.generic')); + } finally { + if (alive.current) setBusy(false); + } + }; + + /** Revoke every device after a confirmation. */ + const revokeAll = async () => { + if (!window.confirm(t('devices.confirmRevokeAll'))) return; + setBusy(true); + try { + await fetch(API + '/revoke', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ all: true }), + }); + await refreshState(); + } catch { + setError(t('error.generic')); + } finally { + if (alive.current) setBusy(false); + } + }; + + /** Approve or deny the device that scanned the QR. */ + const decide = async (action) => { + if (busy || pending === null) return; + setBusy(true); + setError(''); + try { + const response = await fetch(API + '/' + action, { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json' }, + body: JSON.stringify({ id: pending.id }), + }); + const data = await readJson(response); + if (!response.ok || data === null || data.ok !== true) { + setError(errorFor(t, data?.code ?? null)); + } + await refreshState(); + } catch { + if (alive.current) setError(t('error.generic')); + } finally { + if (alive.current) setBusy(false); + } + }; + + const remaining = revealed && ticket !== null ? Number(ticket.expiresAt) - now : 0; + const showQr = revealed && ticket !== null && remaining > 0; + + return h( + 'div', + { className: 'dshLanShare_panel' + (embedded ? ' dshLanShare_panelEmbedded' : '') }, + h(ListenerStatus, { state, t }), + h(RelayStatus, { state, t }), + state !== null && state.running === true && state.fallbackPort === true + ? h('p', { className: 'dshLanShare_hint' }, format(t('status.fallback'), { port: String(state.port ?? '') })) + : null, + state !== null && typeof state.mintError === 'string' && state.mintError !== '' + ? h('p', { className: 'dshLanShare_warn' }, format(t('status.mintError'), { detail: state.mintError })) + : null, + + pending !== null + ? h(PendingCard, { + pending, + t, + now, + busy, + onApprove: () => void decide('approve'), + onDeny: () => void decide('deny'), + }) + : !showQr + ? h( + 'div', + { className: 'dshLanShare_pairEmpty' }, + h( + 'button', + { + type: 'button', + className: 'dshLanShare_qrPlaceholder', + onClick: reveal, + disabled: busy, + 'aria-label': t('dialog.showQr'), + }, + h(QrGlyph, null), + h('span', null, busy ? t('dialog.loading') : t('dialog.showQr')), + ), + h('p', { className: 'dshLanShare_hint' }, t('dialog.showHint')), + ) + : h( + 'div', + { className: 'dshLanShare_pair' }, + h('div', { className: 'dshLanShare_qrCard' }, h(QrCode, { rows: ticket.qr?.rows ?? [], size: 240, label: t('qr.aria') })), + h( + 'div', + { className: 'dshLanShare_pairBody' }, + h('p', { className: 'dshLanShare_hint' }, t('dialog.subtitle')), + h( + 'p', + { className: 'dshLanShare_countdown' }, + format(t('dialog.expires'), { time: clock(remaining) }), + ), + h( + 'div', + { className: 'dshLanShare_urlRow' }, + h('span', { className: 'dshLanShare_url', title: ticket.url }, ticket.url), + h( + 'button', + { + type: 'button', + className: 'dshLanShare_button dshLanShare_copyButton', + title: copied ? t('dialog.copied') : t('dialog.copy'), + 'aria-label': copied ? t('dialog.copied') : t('dialog.copy'), + onClick: async () => { + if (await copyText(ticket.url)) { + setCopied(true); + setTimeout(() => { if (alive.current) setCopied(false); }, 1500); + } + }, + }, + copied ? h(CheckIcon, null) : h(CopyIcon, null), + ), + ), + ), + ), + error !== '' ? h('p', { className: 'dshLanShare_warn' }, error) : null, + h(DeviceList, { + devices: state?.devices ?? [], + t, + onRevoke: revoke, + onRevokeAll: revokeAll, + busy, + }), + h('p', { className: 'dshLanShare_warn' }, t('warning.fullAccess')), + state !== null && state.protocol === 'http:' + ? h('p', { className: 'dshLanShare_hint' }, t('warning.http')) + : null, + ); + } + + /** A modal portal shared by the header control. */ + function ShareDialog({ sessionId, t, onClose }) { + const panelRef = React.useRef(null); + React.useEffect(() => { + const previous = document.activeElement; + const { overflow } = document.body.style; + document.body.style.overflow = 'hidden'; + panelRef.current?.focus(); + const onKey = (event) => { + if (event.key === 'Escape') { + event.preventDefault(); + onClose(); + } + }; + document.addEventListener('keydown', onKey); + return () => { + document.removeEventListener('keydown', onKey); + document.body.style.overflow = overflow; + if (previous instanceof HTMLElement) previous.focus(); + }; + }, [onClose]); + + return ReactDOM.createPortal( + h( + 'div', + { className: 'dshLanShare_overlay', onMouseDown: (event) => { if (event.target === event.currentTarget) onClose(); } }, + h( + 'div', + { + className: 'dshLanShare_dialog', + role: 'dialog', + 'aria-modal': 'true', + 'aria-label': t('dialog.title'), + tabIndex: -1, + ref: panelRef, + }, + h( + 'div', + { className: 'dshLanShare_dialogHead' }, + h('div', null, + h('h2', { className: 'dshLanShare_title' }, t('dialog.title')), + h('p', { className: 'dshLanShare_subtitle' }, t('dialog.subtitle')), + ), + h( + 'button', + { type: 'button', className: 'dshLanShare_close', onClick: onClose, 'aria-label': t('dialog.close') }, + '×', + ), + ), + h(SharePanel, { sessionId, t }), + ), + ), + document.body, + ); + } + + /** The header control: opens the Share dialog. */ + function ShareAction({ sessionId, t, useBootstrap }) { + const remote = useBootstrap((snapshot) => snapshot.remote); + const [open, setOpen] = React.useState(false); + if (remote !== false) return null; + return h( + React.Fragment, + null, + h( + 'button', + { + type: 'button', + className: 'dshLanShare_action', + onClick: () => setOpen(true), + title: t('share.tooltip'), + 'aria-label': t('share.tooltip'), + }, + h(ShareIcon, null), + h('span', { className: 'dshLanShare_actionLabel' }, t('share.label')), + ), + open ? h(ShareDialog, { sessionId, t, onClose: () => setOpen(false) }) : null, + ); + } + + /** Settings → LAN access: host controls, or this tablet's pairing facts. */ + function SettingsSection({ t, useBootstrap, currentSessionId }) { + const bootstrap = useBootstrap((snapshot) => snapshot); + const [disconnecting, setDisconnecting] = React.useState(false); + + if (bootstrap.phase === 'loading') return h('p', { className: 'dshLanShare_hint' }, t('loading')); + if (bootstrap.phase === 'off') return h('p', { className: 'dshLanShare_hint' }, t('error.unavailable')); + + if (bootstrap.remote === true) { + const publicOrigin = typeof window !== 'undefined' && window.location?.origin + ? window.location.origin + : String(bootstrap.origin ?? ''); + return h( + 'div', + { className: 'dshLanShare_panel dshLanShare_panelEmbedded' }, + h('h3', { className: 'dshLanShare_title' }, t('remote.title')), + h('p', { className: 'dshLanShare_hint' }, format(t('remote.body'), { origin: publicOrigin })), + typeof bootstrap.label === 'string' + ? h('p', { className: 'dshLanShare_hint' }, format(t('remote.device'), { label: bootstrap.label })) + : null, + h( + 'button', + { + type: 'button', + className: 'dshLanShare_button', + disabled: disconnecting, + onClick: async () => { + if (!window.confirm(t('remote.confirm'))) return; + setDisconnecting(true); + try { + await fetch(API + '/forget-self', { method: 'POST', headers: { accept: 'application/json' } }); + } catch { + /* the reload still shows the pairing page */ + } + window.location.reload(); + }, + }, + t('remote.disconnect'), + ), + ); + } + + return h(SharePanel, { + sessionId: typeof currentSessionId === 'function' ? currentSessionId() : undefined, + t, + embedded: true, + }); + } + + /** + * On a tablet: open the Session recorded at pairing, then remember every + * Session the user navigates to. The opener waits for the startup + * restoration so it does not race the host's own selection. + * @param {any} ctx client context. + * @param {any} store bootstrap store. + * @param {{ sessionId: string | null }} bootstrap initial value. + * @returns {() => void} cleanup. + */ + function installRemoteSessionSync(ctx, store, bootstrap) { + const started = Date.now(); + let done = typeof bootstrap.sessionId !== 'string'; + let attempts = 0; + let lastSent = null; + const workspace = ctx.uiWorkspace; + + const openBound = () => { + if (done) return; + const snapshot = store.getSnapshot(); + if (snapshot.remote !== true) return; + const target = snapshot.sessionId; + if (typeof target !== 'string') { + done = true; + return; + } + const sessions = ctx.sessions?.list?.getSnapshot?.(); + if (sessions === undefined || sessions.phase !== 'ready') return; + const workspaces = workspace?.workspaces?.list?.getSnapshot?.(); + if (workspaces !== undefined && workspaces.phase !== 'ready') return; + if (sessions.byId === undefined || sessions.byId[target] === undefined) { + done = true; + return; + } + const current = workspace?.mainReference?.sessionId; + if (current === target) { + done = true; + return; + } + if (current === undefined && Date.now() - started < 2000) return; + if (attempts >= 3) { + done = true; + return; + } + attempts += 1; + try { + workspace.openSession(target); + } catch (error) { + console.warn('lan-share: could not open the paired Session', error); + done = true; + } + }; + + const remember = () => { + const current = workspace?.mainReference?.sessionId; + if (typeof current !== 'string' || current === lastSent) return; + lastSent = current; + fetch(API + '/session', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionId: current }), + keepalive: true, + }).catch(() => {}); + }; + + const timers = new Set(); + const tick = () => { + openBound(); + if (done) { + for (const timer of timers) clearInterval(timer); + timers.clear(); + } + }; + const fast = setInterval(tick, 400); + timers.add(fast); + const safety = setTimeout(() => { + if (!done) { + attempts = Math.max(attempts, 2); + openBound(); + } + }, 5000); + timers.add(safety); + + const unsubscribeSelection = workspace?.selection?.subscribe?.(() => { + openBound(); + remember(); + }) ?? (() => {}); + const unsubscribeSessions = ctx.sessions?.list?.subscribe?.(openBound) ?? (() => {}); + const unsubscribeConnection = ctx.get?.('connection')?.state?.subscribe?.(() => { + openBound(); + }) ?? (() => {}); + + return () => { + for (const timer of timers) { + clearInterval(timer); + clearTimeout(timer); + } + timers.clear(); + unsubscribeSelection(); + unsubscribeSessions(); + unsubscribeConnection(); + }; + } + + /** Styles for the action, dialog and Settings page. */ + const CSS = [ + '.dshLanShare_action{box-sizing:border-box;height:24px;flex:none;display:inline-flex;align-items:center;gap:6px;', + 'border-radius:9px;border:none;background:0 0;color:var(--dsw-alias-label-secondary);', + 'font:inherit;font-size:12px;line-height:1;padding:0 8px;cursor:pointer;white-space:nowrap}', + '@media (hover:hover){.dshLanShare_action:hover{background:var(--dsw-alias-interactive-bg-hover);', + 'color:var(--dsw-alias-label-primary)}}', + '.dshLanShare_action:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}', + '.dshLanShare_actionLabel{max-width:90px;overflow:hidden;text-overflow:ellipsis}', + '.dshLanShare_overlay{position:fixed;inset:0;z-index:1200;display:flex;align-items:center;justify-content:center;', + 'background:color-mix(in srgb,#000 42%,transparent);padding:20px;overscroll-behavior:contain}', + '.dshLanShare_dialog{box-sizing:border-box;width:min(680px,100%);max-height:min(86vh,900px);overflow:auto;', + 'border-radius:16px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);', + 'box-shadow:0 18px 60px rgb(0 0 0 / .32);padding:20px;outline:none}', + '.dshLanShare_dialogHead{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin-bottom:12px}', + '.dshLanShare_title{margin:0;font-size:17px;font-weight:600;line-height:1.3;color:var(--dsw-alias-label-primary)}', + '.dshLanShare_subtitle{margin:4px 0 0;font-size:13px;color:var(--dsw-alias-label-tertiary);line-height:1.45}', + '.dshLanShare_close{flex:none;width:32px;height:32px;border:none;border-radius:9px;background:0 0;', + 'color:var(--dsw-alias-label-secondary);font-size:22px;line-height:1;cursor:pointer}', + '@media (hover:hover){.dshLanShare_close:hover{background:var(--dsw-alias-interactive-bg-hover)}}', + '.dshLanShare_panel{display:flex;flex-direction:column;gap:12px;min-width:0}', + '.dshLanShare_panelEmbedded{max-width:720px}', + '.dshLanShare_status{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--dsw-alias-label-secondary);min-width:0}', + '.dshLanShare_status>span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}', + '.dshLanShare_statusWarn{color:var(--dsw-alias-state-warn-label,var(--dsw-alias-state-warn-primary))}', + '.dshLanShare_dot{width:7px;height:7px;border-radius:50%;flex:none;background:var(--dsw-alias-label-tertiary);opacity:.55}', + '.dshLanShare_dotOn{background:var(--dsw-alias-state-success-primary, #2e9e5b);opacity:1}', + '.dshLanShare_hint{margin:0;font-size:12.5px;line-height:1.5;color:var(--dsw-alias-label-tertiary)}', + '.dshLanShare_warn{margin:0;font-size:12.5px;line-height:1.5;color:var(--dsw-alias-state-warn-label,var(--dsw-alias-state-warn-primary))}', + '.dshLanShare_pair{display:grid;grid-template-columns:auto minmax(0,1fr);gap:18px;align-items:start}', + '.dshLanShare_qrCard{flex:none;display:inline-flex;padding:10px;border-radius:14px;background:#fff;', + 'border:1px solid color-mix(in srgb,#000 10%,transparent)}', + '.dshLanShare_qrPlaceholder{box-sizing:border-box;width:240px;height:240px;flex:none;display:flex;', + 'flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:16px;', + 'border-radius:14px;border:1px dashed var(--dsw-alias-border-l2);', + 'background:color-mix(in srgb,var(--dsw-alias-label-primary) 4%,transparent);', + 'color:var(--dsw-alias-label-secondary);font:inherit;font-size:13px;line-height:1.4;', + 'text-align:center;cursor:pointer}', + '@media (hover:hover){.dshLanShare_qrPlaceholder:hover{background:color-mix(in srgb,var(--dsw-alias-label-primary) 7%,transparent);', + 'color:var(--dsw-alias-label-primary)}}', + '.dshLanShare_qrPlaceholder:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}', + '.dshLanShare_qrPlaceholder:disabled{opacity:.55;cursor:default}', + '.dshLanShare_qrGlyph{width:44px;height:44px;color:var(--dsw-alias-label-tertiary)}', + '.dshLanShare_copyButton{width:30px;height:30px;padding:0;flex:none;justify-content:center}', + '.dshLanShare_pending{box-sizing:border-box;width:100%;max-width:560px;display:flex;flex-direction:column;gap:8px;', + 'padding:14px;border-radius:14px;border:1px solid color-mix(in srgb,var(--dsw-alias-state-warn-primary) 35%,transparent);', + 'background:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 6%,transparent)}', + '.dshLanShare_pendingHead{display:flex;align-items:center;gap:8px;font-size:13.5px;font-weight:600;', + 'color:var(--dsw-alias-label-primary)}', + '.dshLanShare_pendingDot{width:8px;height:8px;flex:none;border-radius:50%;', + 'background:var(--dsw-alias-state-warn-primary);box-shadow:0 0 0 3px color-mix(in srgb,var(--dsw-alias-state-warn-primary) 20%,transparent)}', + '.dshLanShare_pendingDevice{margin:0;font-size:13px;line-height:1.4;color:var(--dsw-alias-label-secondary)}', + '.dshLanShare_pendingMeta{margin:0;font-size:11.5px;line-height:1.4;color:var(--dsw-alias-label-tertiary);', + 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis}', + '.dshLanShare_pendingActions{display:flex;flex-wrap:wrap;gap:8px;margin-top:2px}', + '.dshLanShare_qr{display:block;border-radius:6px}', + '.dshLanShare_pairBody{display:flex;flex-direction:column;gap:10px;min-width:0}', + '.dshLanShare_countdown{margin:0;font-size:13px;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}', + '.dshLanShare_countdownOff{color:var(--dsw-alias-state-warn-primary)}', + '.dshLanShare_urlRow{display:flex;align-items:center;gap:8px;min-width:0}', + '.dshLanShare_url{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;', + 'font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;color:var(--dsw-alias-label-secondary);', + 'background:color-mix(in srgb,var(--dsw-alias-label-primary) 6%,transparent);padding:7px 9px;border-radius:8px}', + '.dshLanShare_button,.dshLanShare_primary{box-sizing:border-box;min-height:32px;display:inline-flex;align-items:center;', + 'justify-content:center;padding:0 12px;border-radius:9px;font:inherit;font-size:12.5px;line-height:1;cursor:pointer;', + 'border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary)}', + '.dshLanShare_primary{border-color:transparent;color:#fff;', + 'background:var(--dsw-alias-brand-primary-new-colorprimary-new-color,var(--dsw-alias-state-business-primary))}', + '@media (hover:hover){.dshLanShare_button:hover{background:var(--dsw-alias-interactive-bg-hover)}', + '.dshLanShare_primary:hover{filter:brightness(1.06)}}', + '.dshLanShare_button:disabled,.dshLanShare_primary:disabled{opacity:.5;cursor:default}', + '.dshLanShare_link{border:none;background:0 0;color:var(--dsw-alias-state-business-primary);font:inherit;', + 'font-size:12px;cursor:pointer;padding:0}', + '.dshLanShare_link:disabled{opacity:.5;cursor:default}', + '.dshLanShare_devices{display:flex;flex-direction:column;gap:2px;margin-top:4px;', + 'border-top:1px solid var(--dsw-alias-border-l1);padding-top:10px}', + '.dshLanShare_devicesHead{display:flex;align-items:center;justify-content:space-between;gap:12px;', + 'font-size:12px;color:var(--dsw-alias-label-tertiary);margin-bottom:4px}', + '.dshLanShare_device{display:flex;align-items:center;gap:9px;padding:6px 0;min-width:0}', + '.dshLanShare_deviceBody{display:flex;flex-direction:column;gap:1px;min-width:0;flex:1 1 auto}', + '.dshLanShare_deviceLabel{font-size:13px;color:var(--dsw-alias-label-primary);overflow:hidden;', + 'text-overflow:ellipsis;white-space:nowrap}', + '.dshLanShare_deviceMeta{font-size:11.5px;color:var(--dsw-alias-label-tertiary);overflow:hidden;', + 'text-overflow:ellipsis;white-space:nowrap;font-variant-numeric:tabular-nums}', + '.dshLanShare_pairEmpty{display:flex;flex-direction:column;gap:10px;align-items:flex-start}', + '@media (max-width:640px){.dshLanShare_overlay{padding:0;align-items:stretch}', + '.dshLanShare_dialog{width:100%;max-height:100%;border-radius:0;border:none;padding:18px 16px}', + '.dshLanShare_pair{grid-template-columns:1fr;justify-items:center}', + '.dshLanShare_pairBody{width:100%}.dshLanShare_actionLabel{display:none}}', + '@media (pointer:coarse){.dshLanShare_button,.dshLanShare_primary,.dshLanShare_close{min-height:42px}', + '.dshLanShare_action{min-height:36px}.dshLanShare_device{padding:9px 0}}', + ].join(''); + + /** Services the Client half requires. */ + const inject = ['slots', 'locale', 'sessions', 'uiWorkspace']; + + /** + * Register the surfaces and, on a paired tablet, install Session sync. + * @param {any} ctx client plugin context. + */ + function apply(ctx) { + const store = createSnapshotStore({ phase: 'loading', remote: null, sessionId: null, deviceId: null, label: null, origin: null, error: null }); + const tSettings = ctx.locale.bind(NS); + let cleanupRemote = null; + + ctx.effect(() => ctx.locale.register(NS, DICTIONARIES), 'lan-share: dictionaries'); + + ctx.effect(() => { + const tag = document.createElement('style'); + tag.dataset.plugin = PLUGIN_ID; + tag.dataset.pluginCss = CSS_ID; + tag.textContent = CSS; + document.head.appendChild(tag); + return () => tag.remove(); + }, 'lan-share: styles'); + + ctx.effect(() => { + const controller = new AbortController(); + (async () => { + try { + const response = await fetch(API + '/bootstrap', { + headers: { accept: 'application/json' }, + cache: 'no-store', + signal: controller.signal, + }); + if (!response.ok) { + store.set({ phase: 'off', remote: null }); + return; + } + const data = await readJson(response); + if (controller.signal.aborted) return; + if (data === null) { + store.set({ phase: 'off', remote: null }); + return; + } + store.set({ + phase: 'ready', + remote: data.remote === true, + sessionId: typeof data.sessionId === 'string' ? data.sessionId : null, + deviceId: typeof data.deviceId === 'string' ? data.deviceId : null, + label: typeof data.label === 'string' ? data.label : null, + origin: typeof data.origin === 'string' ? data.origin : null, + error: typeof data.error === 'string' ? data.error : null, + }); + if (data.remote === true) cleanupRemote = installRemoteSessionSync(ctx, store, data); + } catch (error) { + if (!controller.signal.aborted) store.set({ phase: 'off', remote: null }); + } + })(); + return () => { + controller.abort(); + if (cleanupRemote !== null) { + cleanupRemote(); + cleanupRemote = null; + } + }; + }, 'lan-share: bootstrap'); + + ctx.slots.inject('conversation.session.header.actions', () => + ctx.slots.register( + { + name: 'conversation.session.header.actions', + id: 'lan-share', + order: 30, + locale: NS, + inject: () => ({ hooks: { bootstrap: store } }), + }, + ShareAction, + ), + ); + + ctx.slots.inject('settings.section', () => + ctx.slots.register( + { + name: 'settings.section', + id: 'lan-share', + order: 55, + label: () => tSettings('section.title'), + locale: NS, + inject: () => ({ + hooks: { bootstrap: store }, + currentSessionId: () => ctx.uiWorkspace?.mainReference?.sessionId ?? undefined, + }), + }, + SettingsSection, + ), + ); + + ctx.slots.inject('settings.section.icon', () => + ctx.slots.register( + { name: 'settings.section.icon', id: 'lan-share', locale: NS }, + LanIcon, + ), + ); + } + + return { inject, apply }; + }, +}); \ No newline at end of file diff --git a/config.js b/config.js new file mode 100644 index 0000000..1aa82a0 --- /dev/null +++ b/config.js @@ -0,0 +1,365 @@ +/** + * Configuration, address discovery, and authority helpers for LAN Share. + * + * Everything here is pure Node: the host half validates its own config, finds + * the LAN address a tablet can reach, and turns host/port/protocol into the + * spellings HTTP, cookies, and QR payloads need. No bare package imports, so a + * linked plugin resolves from its own directory without the runtime's + * node_modules. + */ + +import { createSocket } from 'node:dgram'; +import { isIP } from 'node:net'; +import { homedir, networkInterfaces } from 'node:os'; +import { isAbsolute, join, resolve } from 'node:path'; + +/** The default LAN port; a fixed port keeps a paired tablet's bookmark usable across restarts. */ +export const DEFAULT_PORT = 47820; + +/** The default one-time ticket lifetime. */ +export const DEFAULT_TICKET_TTL_SECONDS = 60; + +/** The default device lifetime after pairing. */ +export const DEFAULT_DEVICE_TTL_DAYS = 7; + +/** The default device limit. */ +export const DEFAULT_MAX_DEVICES = 16; + +/** Default settings for every field. */ +export const DEFAULTS = Object.freeze({ + enabled: true, + host: null, + publicHost: null, + port: DEFAULT_PORT, + ticketTtlSeconds: DEFAULT_TICKET_TTL_SECONDS, + deviceTtlDays: DEFAULT_DEVICE_TTL_DAYS, + maxDevices: DEFAULT_MAX_DEVICES, + stateFile: null, + tls: null, + relay: { + enabled: false, + url: null, + token: null, + publicOrigin: null, + agentId: null, + fallbackToLan: false, + }, +}); + +/** + * Resolve the Harness home exactly as the host does: DSH_HOME wins, else ~/.dsh. + * @param {NodeJS.ProcessEnv} [env] environment to read. + * @returns {string} absolute home path. + */ +export function resolveDshHome(env = process.env) { + const configured = env.DSH_HOME; + if (typeof configured === 'string' && configured.trim() !== '') return resolve(configured.replace(/^~(?=$|[\\/])/, homedir())); + return join(homedir(), '.dsh'); +} + +/** + * A positive integer inside a range, or the fallback. + * @param {unknown} value candidate. + * @param {number} fallback default. + * @param {number} min inclusive minimum. + * @param {number} max inclusive maximum. + * @param {string} field field name for the diagnostic. + * @returns {number} the accepted value. + */ +function integerIn(value, fallback, min, max, field) { + if (value === undefined || value === null) return fallback; + if (!Number.isInteger(value) || value < min || value > max) { + throw new TypeError('lan-share: ' + field + ' must be an integer between ' + String(min) + ' and ' + String(max)); + } + return value; +} + +/** + * Whether a string is a concrete IP literal or an unspecified one. + * @param {string} host candidate. + * @returns {boolean} true for an IPv4 or IPv6 literal. + */ +export function isIpLiteral(host) { + return isIP(host) !== 0; +} + +/** + * Whether an address is the unspecified address of its family. + * @param {string} host bind address. + * @returns {boolean} true for 0.0.0.0 or ::. + */ +export function isWildcardHost(host) { + return host === '0.0.0.0' || host === '::' || host === '[::]'; +} + +/** + * Normalize an absolute http(s) origin without path/query/fragment. + * @param {unknown} value candidate. + * @param {string} field config field for diagnostics. + * @returns {string} origin. + */ +function normalizePublicOrigin(value, field) { + if (typeof value !== 'string' || value === '') throw new TypeError('lan-share: ' + field + ' must be an http(s) origin'); + let url; + try { + url = new URL(value); + } catch { + throw new TypeError('lan-share: ' + field + ' must be an http(s) origin'); + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new TypeError('lan-share: ' + field + ' must use http or https'); + if (url.pathname !== '/' || url.search !== '' || url.hash !== '') { + throw new TypeError('lan-share: ' + field + ' must not carry a path, query, or fragment'); + } + return url.origin; +} + +/** + * Normalize a tunnel WebSocket URL. + * @param {unknown} value candidate. + * @returns {string} ws(s) URL. + */ +function normalizeRelayUrl(value) { + if (typeof value !== 'string' || value === '') throw new TypeError('lan-share: relay.url must be a ws(s) URL'); + let url; + try { + url = new URL(value); + } catch { + throw new TypeError('lan-share: relay.url must be a ws(s) URL'); + } + if (url.protocol !== 'ws:' && url.protocol !== 'wss:') throw new TypeError('lan-share: relay.url must use ws or wss'); + if (url.hash !== '') throw new TypeError('lan-share: relay.url must not carry a fragment'); + return url.href; +} + +/** + * Validate and normalize the plugin config object. + * @param {unknown} raw config from the Loader row. + * @param {NodeJS.ProcessEnv} [env] environment for the state-file default. + * @returns {typeof DEFAULTS & { stateFile: string, ticketTtlMs: number, deviceTtlMs: number }} normalized config. + */ +export function normalizeConfig(raw, env = process.env) { + const input = raw !== null && typeof raw === 'object' ? raw : {}; + const host = input.host === undefined || input.host === null || input.host === '' ? null : String(input.host); + if (host !== null && !isIpLiteral(host)) throw new TypeError('lan-share: host must be an IP literal or null'); + const publicHost = input.publicHost === undefined || input.publicHost === null || input.publicHost === '' + ? null + : String(input.publicHost); + if (publicHost !== null) { + if (publicHost.includes('/') || publicHost.includes('://') || /\s/.test(publicHost)) { + throw new TypeError('lan-share: publicHost must be a hostname or IP literal without a scheme or path'); + } + } + const port = integerIn(input.port, DEFAULTS.port, 0, 65535, 'port'); + const ticketTtlSeconds = integerIn(input.ticketTtlSeconds, DEFAULTS.ticketTtlSeconds, 15, 3600, 'ticketTtlSeconds'); + const deviceTtlDays = integerIn(input.deviceTtlDays, DEFAULTS.deviceTtlDays, 1, 365, 'deviceTtlDays'); + const maxDevices = integerIn(input.maxDevices, DEFAULTS.maxDevices, 1, 128, 'maxDevices'); + const enabled = input.enabled === undefined ? DEFAULTS.enabled : input.enabled === true; + + let stateFile; + if (typeof input.stateFile === 'string' && input.stateFile !== '') { + stateFile = isAbsolute(input.stateFile) ? input.stateFile : resolve(input.stateFile); + } else { + stateFile = join(resolveDshHome(env), 'lan-share', 'devices.json'); + } + + let tls = null; + if (input.tls !== undefined && input.tls !== null) { + const certFile = input.tls.certFile; + const keyFile = input.tls.keyFile; + if (typeof certFile !== 'string' || certFile === '' || typeof keyFile !== 'string' || keyFile === '') { + throw new TypeError('lan-share: tls requires certFile and keyFile paths'); + } + tls = { certFile: resolve(certFile), keyFile: resolve(keyFile) }; + } + + if (host !== null && isWildcardHost(host) && publicHost === null) { + throw new TypeError('lan-share: a wildcard host needs an explicit publicHost for the QR address'); + } + + const relayRaw = input.relay !== null && typeof input.relay === 'object' ? input.relay : {}; + const relayUrlValue = env.DSH_RELAY_URL ?? relayRaw.url ?? null; + const relayTokenValue = env.DSH_RELAY_TOKEN ?? relayRaw.token ?? null; + const relayPublicValue = env.DSH_RELAY_PUBLIC_ORIGIN ?? relayRaw.publicOrigin ?? null; + const relayAgentValue = env.DSH_RELAY_AGENT_ID ?? relayRaw.agentId ?? null; + const relayEnabledRaw = env.DSH_RELAY_ENABLED ?? relayRaw.enabled; + const relayEnabled = relayEnabledRaw === undefined + ? Boolean(relayUrlValue !== null && relayTokenValue !== null) + : relayEnabledRaw === true || relayEnabledRaw === '1' || relayEnabledRaw === 'true'; + let relay = { + enabled: relayEnabled, + url: null, + token: null, + publicOrigin: null, + agentId: null, + fallbackToLan: relayRaw.fallbackToLan === true, + }; + if (relayEnabled) { + if (relayUrlValue === null || relayUrlValue === '') throw new TypeError('lan-share: relay.url is required when the relay is enabled'); + if (relayTokenValue === null || relayTokenValue === '') throw new TypeError('lan-share: relay.token is required when the relay is enabled'); + if (typeof relayTokenValue !== 'string' || relayTokenValue.length > 512) throw new TypeError('lan-share: relay.token must be a string of at most 512 characters'); + relay.url = normalizeRelayUrl(relayUrlValue); + relay.token = relayTokenValue; + relay.publicOrigin = relayPublicValue === null || relayPublicValue === '' ? null : normalizePublicOrigin(relayPublicValue, 'relay.publicOrigin'); + if (relayAgentValue !== null && relayAgentValue !== '') { + if (typeof relayAgentValue !== 'string' || !/^[A-Za-z0-9._-]{1,64}$/.test(relayAgentValue)) { + throw new TypeError('lan-share: relay.agentId must match [A-Za-z0-9._-]{1,64}'); + } + relay.agentId = relayAgentValue; + } + } + + return { + ...DEFAULTS, + enabled, + host, + publicHost, + port, + ticketTtlSeconds, + deviceTtlDays, + maxDevices, + stateFile, + tls, + relay, + ticketTtlMs: ticketTtlSeconds * 1000, + deviceTtlMs: deviceTtlDays * 24 * 60 * 60 * 1000, + }; +} + +/** + * Whether an IPv4 address is a private LAN address (RFC 1918). The UDP + * default-route probe can report a Tailscale/CGNAT address (100.64/10) or a + * VPN address that the local relay agent cannot dial back. Prefer a real LAN + * address so both the tablet and the local relay tunnel reach the listener. + * @param {string} address IPv4 text. + * @returns {boolean} true for 10/8, 172.16/12 or 192.168/16. + */ +export function isPrivateLanAddress(address) { + const parts = String(address).split('.').map(Number); + if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return false; + if (parts[0] === 10) return true; + if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true; + return parts[0] === 192 && parts[1] === 168; +} + +/** + * Ask the routing table for the local address the network would use, then fall + * back to the first non-internal IPv4 interface (physical interfaces first). + * @returns {Promise} a LAN address literal, if any. + */ +export async function detectLanAddress() { + for (const target of ['8.8.8.8', '1.1.1.1', '9.9.9.9']) { + const socket = createSocket('udp4'); + try { + await new Promise((resolveConnect, rejectConnect) => { + socket.once('error', rejectConnect); + socket.connect(53, target, resolveConnect); + }); + const address = socket.address().address; + /* A Tailscale/CGNAT or public default route is not necessarily reachable + * from the local relay tunnel or the LAN tablet; prefer RFC 1918 below. */ + if (typeof address === 'string' && address !== '' && address !== '0.0.0.0' && isPrivateLanAddress(address)) { + return address; + } + } catch { + /* try the next probe */ + } finally { + socket.close(); + } + } + + const interfaces = networkInterfaces(); + const candidates = []; + for (const [name, entries] of Object.entries(interfaces)) { + for (const entry of entries ?? []) { + if (entry.internal) continue; + if (entry.family !== 'IPv4' && entry.family !== 4) continue; + candidates.push({ name, address: entry.address }); + } + } + const rank = (name) => { + if (/^(en\d|eth\d|wlan\d|wl|Wi-?Fi)/i.test(name)) return 0; + if (/^(utun|tun|tap|bridge|vmnet|vboxnet|docker|vEthernet|awdl|llw)/i.test(name)) return 2; + return 1; + }; + candidates.sort((left, right) => { + const leftPrivate = isPrivateLanAddress(left.address) ? 0 : 1; + const rightPrivate = isPrivateLanAddress(right.address) ? 0 : 1; + if (leftPrivate !== rightPrivate) return leftPrivate - rightPrivate; + return rank(left.name) - rank(right.name); + }); + return candidates[0]?.address; +} + +/** + * The host text a URL can carry: IPv6 literals are bracketed, IPv4 is as-is. + * @param {string} host address or hostname. + * @returns {string} URL host text. + */ +export function urlHost(host) { + if (host.startsWith('[') && host.endsWith(']')) return host; + return isIP(host) === 6 ? '[' + host + ']' : host; +} + +/** + * Compose the public origin of the LAN listener. + * @param {{ protocol: string, host: string, port: number }} listener listening facts. + * @returns {string} origin with no trailing slash. + */ +export function originOf(listener) { + return listener.protocol + '//' + urlHost(listener.host) + ':' + String(listener.port); +} + +/** + * The authority spelling used for Host headers and cookie audiences. + * @param {string} origin an http(s) origin. + * @returns {string} host[:port]. + */ +export function authorityOf(origin) { + return new URL(origin).host; +} + +/** + * Extract the bind host from an upstream origin, without brackets. + * @param {string} origin upstream origin. + * @returns {string} the hostname. + */ +export function upstreamHostOf(origin) { + const url = new URL(origin); + const host = url.hostname; + return host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host; +} + +/** + * A short human label for a browser's User-Agent, for the device list. + * @param {string | undefined} userAgent request User-Agent. + * @returns {string} a label such as "iPad · Safari". + */ +export function describeUserAgent(userAgent) { + const ua = typeof userAgent === 'string' ? userAgent : ''; + let device = 'Browser'; + if (/iPad/.test(ua)) device = 'iPad'; + else if (/iPhone/.test(ua)) device = 'iPhone'; + else if (/Android/.test(ua)) device = /Mobile/.test(ua) ? 'Android phone' : 'Android tablet'; + else if (/Macintosh|Mac OS X/.test(ua)) device = 'Mac'; + else if (/Windows/.test(ua)) device = 'Windows'; + else if (/Linux/.test(ua)) device = 'Linux'; + else if (/CrOS/.test(ua)) device = 'Chromebook'; + + let browser = 'Browser'; + if (/Edg\//.test(ua)) browser = 'Edge'; + else if (/OPR\/|Opera/.test(ua)) browser = 'Opera'; + else if (/Firefox\//.test(ua)) browser = 'Firefox'; + else if (/Chrome\//.test(ua) && !/Chromium/.test(ua)) browser = 'Chrome'; + else if (/Safari\//.test(ua)) browser = 'Safari'; + return device + ' · ' + browser; +} + +/** + * Normalize a socket peer address for display and storage. + * @param {string | undefined} address remote address. + * @returns {string} an address without an IPv4-mapped prefix. + */ +export function peerAddress(address) { + if (typeof address !== 'string' || address === '') return 'unknown'; + return address.startsWith('::ffff:') ? address.slice(7) : address; +} \ No newline at end of file diff --git a/cordis.patch.yml b/cordis.patch.yml new file mode 100644 index 0000000..3d03c01 --- /dev/null +++ b/cordis.patch.yml @@ -0,0 +1,4 @@ +# Bundle layer for @local/dsh-lan-share: the LAN listener and its control API. +- insert: + - id: lan-share + name: '@local/dsh-lan-share' diff --git a/index.js b/index.js new file mode 100644 index 0000000..9dc8005 --- /dev/null +++ b/index.js @@ -0,0 +1,308 @@ +/** + * Host half of LAN Share. + * + * Three pieces compose here: the durable device registry, the one-time ticket + * registry, and the authenticated LAN listener. When the outbound relay is + * configured, one more piece joins them — a tunnel that dials a static public + * relay and replays browser requests into the same LAN listener. The control + * API stays on the Host's loopback server, so a tablet can never mint or + * revoke pairings even through the relay. + */ + +import { hostname } from 'node:os'; +import { normalizeConfig, originOf } from './config.js'; +import { DeviceStore, TicketStore } from './store.js'; +import { LanShareServer } from './proxy.js'; +import { RelayTunnel } from './relay.js'; + +/** Cordis plugin identity. */ +export const name = 'lan-share'; + +/** Services the host half needs before it can bind or register routes. */ +export const inject = ['webServer', 'connection', 'sessions']; + +/** One JSON response with no caching. */ +function json(status, body) { + return new Response(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, + }); +} + +/** + * Log through the Host's logger without assuming an exact shape. + * @param {any} ctx plugin context. + * @returns {(level: string, ...args: unknown[]) => void} bound logger. + */ +function loggerOf(ctx) { + let log; + try { + log = typeof ctx.logger === 'function' ? ctx.logger('lan-share') : ctx.logger; + } catch { + log = undefined; + } + return (level, ...args) => { + const sink = log?.[level] ?? log?.info; + if (typeof sink === 'function') sink.apply(log, args); + }; +} + +/** + * A stable relay status even before the tunnel exists. + * @param {RelayTunnel | null} relay tunnel. + * @param {ReturnType} config plugin config. + * @returns {object} status. + */ +function relaySummary(relay, config) { + if (relay !== null) return relay.state; + return { + enabled: config.relay.enabled, + connected: false, + url: config.relay.url, + publicOrigin: config.relay.publicOrigin, + agentId: config.relay.agentId, + since: null, + attempts: 0, + error: config.relay.enabled ? 'not-started' : null, + }; +} + +/** + * Register the desktop-only control routes. + * @param {any} ctx plugin context. + * @param {LanShareServer} server listener. + * @param {() => RelayTunnel | null} getRelay current tunnel. + * @param {ReturnType} config plugin config. + */ +function registerControlRoutes(ctx, server, getRelay, config) { + const disposers = []; + const register = (path, methods, fetch, requestBody = 'buffered') => { + disposers.push(ctx.connection.fetch.register({ path, methods, requestBody, fetch })); + }; + + register('/api/lan-share/bootstrap', ['GET'], async () => { + const state = server.state; + return json(200, { + remote: false, + version: 1, + running: state.running, + origin: state.origin, + protocol: state.protocol, + bindHost: state.bindHost, + port: state.port, + fallbackPort: state.fallbackPort, + error: state.error, + mintError: state.mintError, + relay: relaySummary(getRelay(), config), + }); + }); + + register('/api/lan-share/state', ['GET'], async () => { + const state = server.state; + return json(200, { ok: true, ...state, relay: relaySummary(getRelay(), config) }); + }); + + register('/api/lan-share/ticket', ['POST'], async (request) => { + let body; + try { + body = await request.json(); + } catch { + return json(400, { ok: false, code: 'bad-request' }); + } + const sessionId = body === null || typeof body !== 'object' ? undefined : body.sessionId; + if (sessionId !== undefined && sessionId !== null && (typeof sessionId !== 'string' || sessionId.length === 0)) { + return json(400, { ok: false, code: 'bad-session' }); + } + if (typeof sessionId === 'string') { + const sessions = ctx.get('sessions'); + const session = sessions?.get?.(sessionId); + if (session === undefined) return json(404, { ok: false, code: 'unknown-session' }); + } + + const relay = getRelay(); + const relayState = relaySummary(relay, config); + let origin; + if (config.relay.enabled) { + if (!relayState.connected) { + if (!config.relay.fallbackToLan) { + return json(409, { ok: false, code: 'relay-offline', error: relayState.error ?? 'relay-not-connected' }); + } + } else if (typeof relayState.publicOrigin === 'string' && relayState.publicOrigin !== '') { + origin = relayState.publicOrigin; + } else { + return json(409, { ok: false, code: 'relay-offline', error: 'relay-origin-unknown' }); + } + } + + let ticket; + try { + ticket = server.createTicket(typeof sessionId === 'string' ? sessionId : null, origin); + } catch (error) { + return json(409, { ok: false, code: error?.code ?? 'not-running', error: server.state.error }); + } + + if (origin !== undefined && relay !== null) { + const registered = relay.registerTicket(ticket.token, ticket.expiresAt, typeof sessionId === 'string' ? sessionId : null); + if (!registered) return json(409, { ok: false, code: 'relay-offline', error: 'relay-send-failed' }); + } + + const { token, ...publicTicket } = ticket; + return json(200, { ok: true, ...publicTicket, relayed: origin !== undefined }); + }); + + register('/api/lan-share/approve', ['POST'], async (request) => { + let body; + try { + body = await request.json(); + } catch { + return json(400, { ok: false, code: 'bad-request' }); + } + const id = body === null || typeof body !== 'object' ? undefined : body.id; + if (typeof id !== 'string' || id === '') return json(400, { ok: false, code: 'bad-pending' }); + let result; + try { + result = await server.approvePending(id); + } catch (error) { + return json(500, { ok: false, code: 'approve-failed', error: error?.message }); + } + if (result.ok !== true) { + return json(result.code === 'DEVICE_LIMIT' ? 409 : 404, { ok: false, code: result.code }); + } + return json(200, { ok: true }); + }); + + register('/api/lan-share/deny', ['POST'], async (request) => { + let body; + try { + body = await request.json(); + } catch { + return json(400, { ok: false, code: 'bad-request' }); + } + const id = body === null || typeof body !== 'object' ? undefined : body.id; + if (typeof id !== 'string' || id === '') return json(400, { ok: false, code: 'bad-pending' }); + const denied = server.denyPending(id); + if (!denied) return json(404, { ok: false, code: 'unknown-pending' }); + return json(200, { ok: true }); + }); + + register('/api/lan-share/revoke', ['POST'], async (request) => { + let body; + try { + body = await request.json(); + } catch { + return json(400, { ok: false, code: 'bad-request' }); + } + if (body === null || typeof body !== 'object') return json(400, { ok: false, code: 'bad-request' }); + if (body.all !== true && (typeof body.deviceId !== 'string' || body.deviceId === '')) { + return json(400, { ok: false, code: 'bad-device' }); + } + const revoked = await server.revoke({ + all: body.all === true, + deviceId: typeof body.deviceId === 'string' ? body.deviceId : undefined, + }); + return json(200, { ok: true, revoked }); + }); + + return () => { + for (const dispose of disposers.splice(0)) { + try { + dispose(); + } catch { + /* already disposed with the plugin context */ + } + } + }; +} + +/** + * Start the LAN listener, optional relay tunnel, and control API. + * @param {any} ctx host plugin context. + * @param {unknown} rawConfig Loader row config. + */ +export async function apply(ctx, rawConfig) { + const logger = loggerOf(ctx); + + let config; + try { + config = normalizeConfig(rawConfig); + } catch (error) { + logger('warn', error); + return; + } + if (!config.enabled) { + logger('info', 'lan-share: disabled by configuration'); + return; + } + + let upstreamOrigin; + try { + upstreamOrigin = ctx.webServer.getOrigin(); + } catch (error) { + logger('warn', error); + return; + } + + const devices = new DeviceStore(config.stateFile, { + ttlMs: config.deviceTtlMs, + maxDevices: config.maxDevices, + logger, + }); + await devices.load(); + + const tickets = new TicketStore({ ttlMs: config.ticketTtlMs }); + const server = new LanShareServer({ + config, + devices, + tickets, + upstream: { + origin: upstreamOrigin, + protocol: ctx.webServer.protocol, + host: ctx.webServer.host, + port: ctx.webServer.port, + }, + authenticatedUrl: () => ctx.connection.authenticatedUrl(ctx.webServer.getOrigin()), + logger, + }); + + /** @type {RelayTunnel | null} */ + let relay = null; + + ctx.effect(() => { + let stopped = false; + (async () => { + await server.start(); + if (stopped || server.state.running !== true || server.publicOrigin === null || server.port === null) return; + if (!config.relay.enabled) return; + + const bindHost = server.bindHost === '0.0.0.0' || server.bindHost === '::' ? '127.0.0.1' : server.bindHost; + const localBindOrigin = originOf({ protocol: server.protocol, host: bindHost, port: server.port }); + const agentId = config.relay.agentId ?? ('dsh-' + hostname().replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 56)); + relay = new RelayTunnel({ + url: config.relay.url, + token: config.relay.token, + agentId, + publicOrigin: config.relay.publicOrigin, + localOrigin: server.publicOrigin, + localBindOrigin, + localHost: bindHost, + localPort: server.port, + localProtocol: server.protocol, + activeTickets: () => tickets.active(), + logger, + }); + relay.start(); + })().catch((error) => logger('warn', error)); + return async () => { + stopped = true; + const current = relay; + relay = null; + if (current !== null) await current.stop(); + await server.stop(); + await devices.close(); + }; + }, 'lan-share: listener'); + + ctx.effect(() => registerControlRoutes(ctx, server, () => relay, config), 'lan-share: control routes'); + + logger('info', 'lan-share: configured for ' + config.stateFile); +} \ No newline at end of file diff --git a/locale/en.json b/locale/en.json new file mode 100644 index 0000000..b345088 --- /dev/null +++ b/locale/en.json @@ -0,0 +1,47 @@ +{ + "share.label": "Share", + "share.tooltip": "Share this session over the local network", + "section.title": "LAN access", + "section.icon": "LAN access", + "dialog.title": "Share this session", + "dialog.subtitle": "Scan the code with a tablet camera on the same Wi-Fi network.", + "dialog.expires": "One-time code. It works once and expires in {time}.", + "dialog.expired": "This code has expired. Refresh it to pair another device.", + "dialog.urlLabel": "Or open this address", + "dialog.copy": "Copy link", + "dialog.copied": "Copied", + "dialog.refresh": "New code", + "dialog.close": "Close", + "dialog.pair": "Pair a device", + "dialog.pairHint": "Create a one-time code for a tablet on the same network.", + "devices.title": "Paired devices", + "devices.empty": "No devices are paired yet.", + "devices.online": "online", + "devices.offline": "offline", + "devices.session": "session {id}", + "devices.revoke": "Disconnect", + "devices.revokeAll": "Disconnect all", + "devices.confirmRevoke": "Disconnect this device?", + "devices.confirmRevokeAll": "Disconnect every paired device?", + "status.listening": "Listening on {origin}", + "status.notListening": "Not listening: {reason}", + "status.fallback": "The default port was busy, so this run uses {port}.", + "status.mintError": "The host session could not be authenticated: {detail}", + "warning.fullAccess": "A paired device gets full owner control of this DSH instance, including tools and approvals.", + "warning.http": "Traffic is plain HTTP on the local network. Pair only on a network you trust.", + "error.ticket": "Could not create a pairing code.", + "error.deviceLimit": "The device limit is reached. Disconnect an old device first.", + "error.unknownSession": "This session is no longer available.", + "error.notRunning": "The LAN listener is not running.", + "error.noLan": "No LAN address was found. Set the host in the plugin configuration.", + "error.generic": "Could not reach the host.", + "error.unavailable": "LAN access is unavailable in this composition.", + "remote.title": "Connected to a host", + "remote.body": "This browser is paired with the DSH desktop at {origin}. Manage pairings on the host computer.", + "remote.device": "This device: {label}", + "remote.disconnect": "Disconnect this tablet", + "remote.confirm": "Disconnect this tablet from the host?", + "remote.disconnected": "Disconnected.", + "qr.aria": "Pairing QR code", + "loading": "Loading…" +} diff --git a/locale/ru.json b/locale/ru.json new file mode 100644 index 0000000..d7b47bd --- /dev/null +++ b/locale/ru.json @@ -0,0 +1,47 @@ +{ + "share.label": "Поделиться", + "share.tooltip": "Открыть этот сеанс в локальной сети", + "section.title": "Общий доступ по сети", + "section.icon": "Общий доступ по сети", + "dialog.title": "Поделиться сеансом", + "dialog.subtitle": "Отсканируйте код камерой планшета в той же сети Wi-Fi.", + "dialog.expires": "Одноразовый код. Он сработает один раз и истечёт через {time}.", + "dialog.expired": "Код истёк. Обновите его, чтобы подключить другое устройство.", + "dialog.urlLabel": "Или откройте этот адрес", + "dialog.copy": "Скопировать ссылку", + "dialog.copied": "Скопировано", + "dialog.refresh": "Новый код", + "dialog.close": "Закрыть", + "dialog.pair": "Подключить устройство", + "dialog.pairHint": "Создайте одноразовый код для планшета в этой же сети.", + "devices.title": "Подключённые устройства", + "devices.empty": "Пока нет подключённых устройств.", + "devices.online": "в сети", + "devices.offline": "не в сети", + "devices.session": "сеанс {id}", + "devices.revoke": "Отключить", + "devices.revokeAll": "Отключить все", + "devices.confirmRevoke": "Отключить это устройство?", + "devices.confirmRevokeAll": "Отключить все подключённые устройства?", + "status.listening": "Слушает {origin}", + "status.notListening": "Не запущено: {reason}", + "status.fallback": "Порт по умолчанию занят, поэтому используется {port}.", + "status.mintError": "Не удалось подтвердить сеанс на host: {detail}", + "warning.fullAccess": "Подключённое устройство получает полный доступ владельца к этому DSH, включая инструменты и подтверждения.", + "warning.http": "Трафик идёт по обычному HTTP в локальной сети. Подключайте устройства только в доверенной сети.", + "error.ticket": "Не удалось создать код подключения.", + "error.deviceLimit": "Достигнут лимит устройств. Сначала отключите старое.", + "error.unknownSession": "Этот сеанс больше недоступен.", + "error.notRunning": "LAN-листенер не запущен.", + "error.noLan": "Не найден LAN-адрес. Укажите host в конфигурации плагина.", + "error.generic": "Не удалось связаться с host.", + "error.unavailable": "Общий доступ по сети недоступен в этой конфигурации.", + "remote.title": "Подключено к host", + "remote.body": "Этот браузер подключён к DSH Desktop по адресу {origin}. Управление привязками — на компьютере.", + "remote.device": "Это устройство: {label}", + "remote.disconnect": "Отключить этот планшет", + "remote.confirm": "Отключить этот планшет от host?", + "remote.disconnected": "Отключено.", + "qr.aria": "QR-код для подключения", + "loading": "Загрузка…" +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..8ffb3c4 --- /dev/null +++ b/package.json @@ -0,0 +1,43 @@ +{ + "name": "@local/dsh-lan-share", + "version": "0.2.0", + "private": true, + "type": "module", + "description": "Share the DSH Desktop Web GUI over the local network with one-time QR pairing and revocable tablet access.", + "repository": { + "type": "git", + "url": "ssh://git@git.realmanual.ru:2022/pub/dsh-lan-share.git" + }, + "exports": { + ".": "./index.js", + "./client": "./client.js", + "./locale/*.json": "./locale/*.json" + }, + "files": [ + "index.js", + "config.js", + "store.js", + "proxy.js", + "qr.js", + "relay.js", + "client.js", + "cordis.patch.yml", + "locale/*.json", + "README.md" + ], + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + }, + "client": { + "platform": "web", + "immediately": true, + "inject": [ + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-workspace", + "@deepseek-ai/dsh-client-ui-conversation", + "@deepseek-ai/dsh-client-ui-settings" + ] + } + } +} \ No newline at end of file diff --git a/proxy.js b/proxy.js new file mode 100644 index 0000000..c72414d --- /dev/null +++ b/proxy.js @@ -0,0 +1,1215 @@ +/** + * The LAN listener: an authenticated reverse proxy in front of the Desktop + * Host's loopback Web server. + * + * The Host's own server is deliberately loopback-only and authenticates a + * browser with an authority-bound signed cookie obtained from a per-process + * launch token. This listener therefore never forwards that cookie to the + * tablet. It pairs a tablet with a one-time QR ticket, keeps its own revocable + * device cookie, and speaks to the upstream as a synthetic authenticated + * browser: it mints the upstream cookie through the Host's launch URL, keeps it + * warm, and replaces it when the upstream authority changes or answers 401. + * + * Everything that reaches the upstream is re-written exactly the way the + * Electron shell's own dsh-app://app forwarding does it: Host names the + * upstream authority, cookies are the minted set, and Origin is either removed + * (HTTP) or set to the upstream origin (WebSocket), so the Host's DNS-rebinding + * and cross-site fences keep their meaning. + */ + +import { randomBytes } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import http from 'node:http'; +import https from 'node:https'; +import net from 'node:net'; +import tls from 'node:tls'; +import { + describeUserAgent, + isWildcardHost, + originOf, + peerAddress, +} from './config.js'; +import { encodeQr } from './qr.js'; + +/** Cookie carrying the device secret to this listener. */ +const DEVICE_COOKIE = 'dsh-lan-device'; + +/** How long a minted upstream cookie is trusted when it carries no expiry. */ +const FALLBACK_COOKIE_TTL_MS = 6 * 60 * 60 * 1000; + +/** Refresh the upstream cookie before it expires. */ +const COOKIE_REFRESH_MARGIN_MS = 10 * 60 * 1000; + +/** How long a scanned QR waits for the desktop owner's confirmation. */ +const PENDING_TTL_MS = 120 * 1000; + +/** Bound on pairing requests that can wait for confirmation at once. */ +const MAX_PENDING = 8; + +/** Headers that describe one hop and never cross a proxy. */ +const HOP_BY_HOP = new Set([ + 'connection', + 'keep-alive', + 'proxy-authenticate', + 'proxy-authorization', + 'proxy-connection', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', +]); + +/** Request headers the proxy always replaces or removes. */ +const REQUEST_REWRITE = new Set([ + ...HOP_BY_HOP, + 'host', + 'origin', + 'cookie', + 'sec-fetch-site', + 'expect', +]); + +/** Response headers the proxy always replaces or removes. */ +const RESPONSE_DROP = new Set([ + 'connection', + 'keep-alive', + 'proxy-authenticate', + 'proxy-authorization', + 'proxy-connection', + 'trailer', + 'transfer-encoding', +]); + +/** + * Escape text for HTML interpolation. + * @param {string} value raw text. + * @returns {string} escaped text. + */ +function escapeHtml(value) { + return String(value) + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", '''); +} + +/** + * A self-contained status page for pairing failures and missing cookies. + * @param {{ title: string, message: string, detail?: string }} content page copy. + * @returns {string} complete HTML. + */ +function htmlPage(content) { + const detail = content.detail === undefined ? '' : '

' + escapeHtml(content.detail) + '

'; + return '' + + '' + + '' + escapeHtml(content.title) + '

' + escapeHtml(content.title) + '

' + + '

' + content.message + '

' + detail + '
'; +} + +/** + * Send a complete response. + * @param {http.ServerResponse} res response. + * @param {number} status status code. + * @param {Record} headers response headers. + * @param {string | Buffer} body response body. + */ +function send(res, status, headers, body) { + res.writeHead(status, { 'cache-control': 'no-store', ...headers }); + res.end(body); +} + +/** + * Send one JSON response. + * @param {http.ServerResponse} res response. + * @param {number} status status code. + * @param {unknown} body JSON value. + */ +function sendJson(res, status, body) { + send(res, status, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify(body)); +} + +/** + * Read a small JSON request body. + * @param {http.IncomingMessage} req request. + * @param {number} limit byte limit. + * @returns {Promise} parsed JSON, or undefined. + */ +async function readJson(req, limit = 8192) { + const chunks = []; + let size = 0; + for await (const chunk of req) { + size += chunk.length; + if (size > limit) return undefined; + chunks.push(chunk); + } + if (chunks.length === 0) return undefined; + try { + return JSON.parse(Buffer.concat(chunks).toString('utf8')); + } catch { + return undefined; + } +} + +/** + * All values of one cookie name in a Cookie header. + * @param {string | undefined} header Cookie header. + * @param {string} name cookie name. + * @returns {string | undefined} the last value. + */ +function cookieValue(header, name) { + if (typeof header !== 'string') return undefined; + let value; + for (const segment of header.split(';')) { + const equals = segment.indexOf('='); + if (equals === -1) continue; + if (segment.slice(0, equals).trim() === name) value = segment.slice(equals + 1).trim(); + } + return value; +} + +/** + * Parse the lifetime a Set-Cookie header advertises. + * @param {string} header one Set-Cookie value. + * @returns {number | undefined} absolute expiry, when parseable. + */ +function cookieExpiry(header) { + const expires = /(?:^|;)\s*expires=([^;]+)/i.exec(header); + if (expires !== null) { + const time = Date.parse(expires[1]); + if (Number.isFinite(time)) return time; + } + const maxAge = /(?:^|;)\s*max-age=(-?\d+)/i.exec(header); + if (maxAge !== null) { + const seconds = Number(maxAge[1]); + if (Number.isFinite(seconds)) return Date.now() + seconds * 1000; + } + return undefined; +} + +/** + * The LAN Share listener and proxy. + */ +export class LanShareServer { + /** + * @param {object} options composition. + * @param {ReturnType} options.config normalized config. + * @param {import('./store.js').DeviceStore} options.devices device registry. + * @param {import('./store.js').TicketStore} options.tickets ticket registry. + * @param {{ origin: string, protocol: string, host: string, port: number }} options.upstream Desktop Host facts. + * @param {() => string} options.authenticatedUrl returns the Host's launch URL. + * @param {(level: string, ...args: unknown[]) => void} [options.logger] host logger. + */ + constructor(options) { + this.config = options.config; + this.devices = options.devices; + this.tickets = options.tickets; + this.upstream = { + ...options.upstream, + authority: new URL(options.upstream.origin).host, + }; + this.authenticatedUrl = options.authenticatedUrl; + this.log = options.logger ?? (() => {}); + + /** @type {http.Server | https.Server | tls.Server | null} */ + this.server = null; + this.bindHost = null; + this.publicHost = null; + this.protocol = this.config.tls === null ? 'http:' : 'https:'; + this.port = null; + this.fallbackPort = false; + this.lastError = null; + this.ready = false; + + /** @type {{ header: string, expiresAt: number } | null} */ + this.cookie = null; + /** @type {Promise<{ header: string, expiresAt: number }> | null} */ + this.cookieMint = null; + this.lastMintError = null; + + /** @type {Map>} */ + this.sockets = new Map(); + + /** @type {Map} pairing requests waiting for the owner. */ + this.pending = new Map(); + + this.agent = new http.Agent({ keepAlive: true, maxSockets: 64, maxFreeSockets: 16 }); + this.secureAgent = new https.Agent({ keepAlive: true, maxSockets: 32, maxFreeSockets: 8, rejectUnauthorized: false }); + } + + /** The public origin a QR URL uses. */ + get publicOrigin() { + if (this.port === null || this.publicHost === null) return null; + return originOf({ protocol: this.protocol, host: this.publicHost, port: this.port }); + } + + /** Status and devices for the desktop UI. */ + get state() { + return { + enabled: this.config.enabled, + running: this.ready, + origin: this.publicOrigin, + protocol: this.protocol, + bindHost: this.bindHost, + port: this.port, + fallbackPort: this.fallbackPort, + error: this.lastError, + mintError: this.lastMintError, + upstream: this.upstream.origin, + pending: this.listPending(), + devices: this.devices.list().map((device) => ({ + ...device, + online: device.online === true || this.sockets.has(device.id), + })), + }; + } + + /** + * Start listening. A bind failure is reported through state, never thrown + * into the Host's plugin load. + */ + async start() { + if (!this.config.enabled) { + this.lastError = 'disabled'; + return; + } + let host = this.config.host; + if (host === null) host = await this.resolveAddress(); + if (host === null || host === undefined) { + this.lastError = 'no-lan-address'; + this.log('warn', 'lan-share: no LAN address was found; set config.host explicitly'); + return; + } + this.bindHost = host; + this.publicHost = this.config.publicHost ?? (isWildcardHost(host) ? null : host); + if (this.publicHost === null) { + this.lastError = 'public-host-required'; + return; + } + + let server; + try { + if (this.config.tls !== null) { + server = tls.createServer({ + cert: readFileSyncSafe(this.config.tls.certFile), + key: readFileSyncSafe(this.config.tls.keyFile), + }, (req, res) => this.handleRequest(req, res)); + } else { + server = http.createServer((req, res) => this.handleRequest(req, res)); + } + } catch (error) { + this.lastError = 'tls: ' + this.describeError(error); + this.log('warn', error); + return; + } + + server.on('upgrade', (req, socket, head) => this.handleUpgrade(req, socket, head)); + server.on('clientError', (error, socket) => { + if (socket.writable) socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n'); + socket.destroy(); + }); + + const firstPort = this.config.port; + try { + await this.listen(server, firstPort, host); + } catch (error) { + if (error?.code === 'EADDRINUSE' && firstPort !== 0) { + try { + await this.listen(server, 0, host); + this.fallbackPort = true; + } catch (fallbackError) { + this.lastError = 'bind: ' + this.describeError(fallbackError); + this.log('warn', fallbackError); + return; + } + } else { + this.lastError = 'bind: ' + this.describeError(error); + this.log('warn', error); + return; + } + } + + this.server = server; + const address = server.address(); + this.port = typeof address === 'object' && address !== null ? address.port : this.config.port; + this.ready = true; + this.lastError = null; + this.log('info', 'lan-share: listening on ' + String(this.publicOrigin)); + } + + /** + * Resolve the address to bind without importing the Host's services. + * @returns {Promise} an address, or null. + */ + async resolveAddress() { + const { detectLanAddress } = await import('./config.js'); + return (await detectLanAddress()) ?? null; + } + + /** + * Bind one server and wait for the listener. + * @param {http.Server} server server to bind. + * @param {number} port port. + * @param {string} host address. + * @returns {Promise} completion. + */ + listen(server, port, host) { + return new Promise((resolveListen, rejectListen) => { + const onError = (error) => { + server.off('listening', onListening); + rejectListen(error); + }; + const onListening = () => { + server.off('error', onError); + resolveListen(); + }; + server.once('error', onError); + server.once('listening', onListening); + server.listen(port, host); + }); + } + + /** Stop the listener and every upgraded socket. */ + async stop() { + this.ready = false; + this.cancelAllPending(); + for (const set of this.sockets.values()) for (const socket of set) socket.destroy(); + this.sockets.clear(); + const server = this.server; + this.server = null; + if (server !== null) { + await new Promise((resolveClose) => { + server.close(() => resolveClose()); + server.closeAllConnections?.(); + const timer = setTimeout(resolveClose, 2000); + if (typeof timer.unref === 'function') timer.unref(); + }); + } + this.agent.destroy(); + this.secureAgent.destroy(); + } + + /** Public pending pairing requests for the desktop confirmation card. */ + listPending() { + const now = Date.now(); + return [...this.pending.values()] + .filter((entry) => entry.done !== true && entry.expiresAt > now) + .map(({ id, label, ip, userAgent, createdAt, expiresAt }) => ({ + id, + label, + ip, + userAgent: typeof userAgent === 'string' ? userAgent : '', + createdAt, + expiresAt, + })); + } + + /** + * Register one scanned ticket and hold it until the owner decides. + * @param {{ label: string, ip: string, userAgent?: string, sessionId: string | null }} facts device facts. + * @returns {{ id: string, promise: Promise<{ outcome: string, pairing: object | null }> } | undefined} pending request. + */ + beginPending({ label, ip, userAgent, sessionId }) { + const now = Date.now(); + for (const [id, entry] of this.pending) { + if (entry.done !== true && entry.expiresAt <= now) this.finishPending(id, 'expired'); + } + if (this.pending.size >= MAX_PENDING) return undefined; + const id = randomBytes(12).toString('base64url'); + let resolve; + const promise = new Promise((done) => { resolve = done; }); + const entry = { + id, + label, + ip, + userAgent: typeof userAgent === 'string' ? userAgent : '', + sessionId: sessionId ?? null, + createdAt: now, + expiresAt: now + PENDING_TTL_MS, + done: false, + pairing: null, + resolve, + timer: null, + }; + entry.timer = setTimeout(() => this.finishPending(id, 'expired'), PENDING_TTL_MS); + if (typeof entry.timer.unref === 'function') entry.timer.unref(); + this.pending.set(id, entry); + this.log('info', 'lan-share: pairing request from ' + label + ' at ' + ip); + return { id, promise }; + } + + /** + * Settle one pending request exactly once. + * @param {string} id pending id. + * @param {'approved' | 'denied' | 'expired' | 'canceled'} outcome decision. + * @returns {object | undefined} the settled entry. + */ + finishPending(id, outcome) { + const entry = this.pending.get(id); + if (entry === undefined || entry.done === true) return undefined; + entry.done = true; + if (entry.timer !== null) clearTimeout(entry.timer); + this.pending.delete(id); + entry.resolve({ outcome, pairing: entry.pairing }); + return entry; + } + + /** + * Owner approved a request: register the device, then release the waiting + * browser. The device is created only at this point. + * @param {string} id pending id. + * @returns {Promise<{ ok: boolean, code?: string }>} decision result. + */ + approvePending(id) { + const entry = this.pending.get(id); + if (entry === undefined || entry.done === true) { + return Promise.resolve({ ok: false, code: 'unknown-pending' }); + } + return this.devices.add({ + label: entry.label, + ip: entry.ip, + sessionId: entry.sessionId, + }).then((pairing) => { + entry.pairing = pairing; + this.finishPending(id, 'approved'); + this.log('info', 'lan-share: approved ' + entry.label + ' from ' + entry.ip); + return { ok: true }; + }, (error) => { + if (error?.code === 'DEVICE_LIMIT') return { ok: false, code: 'DEVICE_LIMIT' }; + throw error; + }); + } + + /** + * Owner rejected a request; the scanning browser gets a denial page. + * @param {string} id pending id. + * @returns {boolean} whether a live request was denied. + */ + denyPending(id) { + const entry = this.pending.get(id); + if (entry === undefined || entry.done === true) return false; + this.finishPending(id, 'denied'); + this.log('info', 'lan-share: denied a pairing request'); + return true; + } + + /** + * The scanning browser went away before a decision. + * @param {string} id pending id. + */ + cancelPending(id) { + const entry = this.pending.get(id); + if (entry === undefined || entry.done === true) return; + this.finishPending(id, 'canceled'); + } + + /** Resolve every held pairing request when the listener stops. */ + cancelAllPending() { + for (const entry of [...this.pending.values()]) { + if (entry.done === true) continue; + if (entry.timer !== null) clearTimeout(entry.timer); + entry.done = true; + entry.resolve({ outcome: 'canceled', pairing: null }); + } + this.pending.clear(); + } + + /** + * Pair one tablet and return everything a QR dialog renders. + * @param {string | null} sessionId Session the device should open. + * @returns {{ ticketId: string, url: string, expiresAt: number, qr: { size: number, rows: string[] } }} ticket facts. + */ + createTicket(sessionId, origin = undefined) { + const base = origin ?? this.publicOrigin; + if (!this.ready || base === null) { + const error = new Error('lan-share: listener is not running'); + error.code = 'NOT_RUNNING'; + throw error; + } + const ticket = this.tickets.mint(sessionId ?? null); + const url = base + '/s/' + ticket.token; + return { + ticketId: ticket.ticketId, + token: ticket.token, + url, + expiresAt: ticket.expiresAt, + qr: encodeQr(url), + }; + } + + /** + * Revoke devices by id or all at once, closing their WebSockets. + * @param {{ deviceId?: string, all?: boolean }} request what to revoke. + * @returns {Promise} number of revoked devices. + */ + async revoke(request) { + if (request.all === true) { + const count = await this.devices.revokeAll(); + for (const set of this.sockets.values()) for (const socket of set) socket.destroy(); + this.sockets.clear(); + this.log('info', 'lan-share: all devices revoked (' + String(count) + ')'); + return count; + } + const id = typeof request.deviceId === 'string' ? request.deviceId : ''; + if (id === '') return 0; + const sockets = this.sockets.get(id); + if (sockets !== undefined) { + for (const socket of sockets) socket.destroy(); + this.sockets.delete(id); + } + const removed = await this.devices.revoke(id); + if (removed) this.log('info', 'lan-share: device revoked'); + return removed ? 1 : 0; + } + + /** + * Dispatch one HTTP request. + * @param {http.IncomingMessage} req request. + * @param {http.ServerResponse} res response. + */ + async handleRequest(req, res) { + try { + const pathname = this.pathnameOf(req.url); + if (pathname === undefined) return send(res, 400, { 'content-type': 'text/plain; charset=utf-8' }, 'bad request'); + + if (pathname.startsWith('/s/')) return await this.handlePair(req, res, pathname); + if (pathname === '/api/lan-share/bootstrap') return this.handleBootstrap(req, res); + if (pathname === '/api/lan-share/session') return await this.handleSession(req, res); + if (pathname === '/api/lan-share/forget-self') return await this.handleForgetSelf(req, res); + if (pathname.startsWith('/api/lan-share/')) return sendJson(res, 403, { ok: false, code: 'host-only' }); + + const device = this.deviceOf(req); + if (device === undefined) return this.rejectUnauthenticated(req, res); + + await this.forwardHttp(req, res); + } catch (error) { + this.log('warn', error); + if (!res.headersSent) { + send(res, 502, { 'content-type': 'text/plain; charset=utf-8' }, 'lan-share: upstream request failed\n'); + } else { + res.destroy(); + } + } + } + + /** + * Parse a request target's pathname. + * @param {string | undefined} url request target. + * @returns {string | undefined} pathname. + */ + pathnameOf(url) { + if (typeof url !== 'string') return undefined; + try { + return new URL(url, 'http://lan-share.invalid').pathname; + } catch { + return undefined; + } + } + + /** + * Resolve the caller's device from its cookie. + * @param {http.IncomingMessage} req request. + * @returns {import('./store.js').DeviceRecord | undefined} live device. + */ + deviceOf(req) { + return this.devices.verify(cookieValue(req.headers.cookie, DEVICE_COOKIE)); + } + + /** + * Answer a request without a valid device cookie. + * @param {http.IncomingMessage} req request. + * @param {http.ServerResponse} res response. + */ + rejectUnauthenticated(req, res) { + const accept = typeof req.headers.accept === 'string' ? req.headers.accept : ''; + const navigate = req.headers['sec-fetch-mode'] === 'navigate'; + const acceptsHtml = accept.includes('text/html') || accept.includes('*/*') || accept === ''; + if ((acceptsHtml || navigate) && (req.method === 'GET' || req.method === 'HEAD')) { + const page = htmlPage({ + title: 'Нужен QR-код / Pairing required', + message: 'Это устройство не подключено. На компьютере откройте DSH → «Поделиться» и отсканируйте новый QR-код.', + detail: 'This tablet is not paired. On the host computer, open DSH → Share and scan a new QR code.', + }); + return send(res, 401, { 'content-type': 'text/html; charset=utf-8' }, page); + } + send(res, 401, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify({ ok: false, code: 'unauthorized' })); + } + + /** + * Consume one ticket and pair the scanning browser. + * @param {http.IncomingMessage} req request. + * @param {http.ServerResponse} res response. + * @param {string} pathname request path, beginning with /s/. + */ + async handlePair(req, res, pathname) { + if (req.method !== 'GET') return send(res, 405, { allow: 'GET' }, ''); + const token = pathname.slice(3); + if (token === '' || token.includes('/')) return send(res, 404, { 'content-type': 'text/plain; charset=utf-8' }, 'not found'); + + const grant = this.tickets.consume(token); + if (grant === undefined) { + const page = htmlPage({ + title: 'Код недействителен / Code expired', + message: 'QR-код уже использован или истёк. Запросите новый код на компьютере.', + detail: 'This one-time code was already used or has expired. Request a new QR code on the host computer.', + }); + return send(res, 410, { 'content-type': 'text/html; charset=utf-8' }, page); + } + + try { + await this.ensureUpstreamCookie(); + } catch (error) { + this.log('warn', error); + const page = htmlPage({ + title: 'Не удалось авторизоваться / Host authentication failed', + message: 'Компьютер не подтвердил сеанс. Проверьте, что DSH запущен, и запросите новый код.', + detail: 'The Desktop Host did not confirm the browser session. Request a new QR code.', + }); + return send(res, 502, { 'content-type': 'text/html; charset=utf-8' }, page); + } + + const pending = this.beginPending({ + label: this.describeRequest(req), + ip: this.peerOf(req), + userAgent: req.headers['user-agent'], + sessionId: grant.sessionId, + }); + if (pending === undefined) { + const page = htmlPage({ + title: 'Слишком много запросов / Too many requests', + message: 'Подождите, пока владелец компьютера подтвердит одно из подключений.', + detail: 'Wait until the host owner confirms or rejects one of the pending connections.', + }); + return send(res, 429, { 'content-type': 'text/html; charset=utf-8' }, page); + } + + let settled = false; + const onClose = () => { + if (settled === true) return; + settled = true; + this.cancelPending(pending.id); + }; + res.on('close', onClose); + + const outcome = await pending.promise; + settled = true; + res.off('close', onClose); + + if (outcome.outcome === 'canceled') return; + + if (outcome.outcome === 'approved' && outcome.pairing !== null) { + if (res.destroyed || res.writableEnded) { + await this.devices.revoke(outcome.pairing.record.id).catch(() => {}); + return; + } + const pairing = outcome.pairing; + const maxAge = Math.max(1, Math.floor((pairing.record.expiresAt - Date.now()) / 1000)); + const secure = this.protocol === 'https:' ? '; Secure' : ''; + const cookie = DEVICE_COOKIE + '=' + pairing.cookie + '; Max-Age=' + String(maxAge) + + '; Path=/; HttpOnly; SameSite=Lax' + secure; + send(res, 303, { + location: '/', + 'set-cookie': cookie, + 'referrer-policy': 'no-referrer', + 'content-type': 'text/plain; charset=utf-8', + }, ''); + return; + } + + if (outcome.outcome === 'denied') { + const page = htmlPage({ + title: 'Подключение отклонено / Connection declined', + message: 'Владелец компьютера отклонил подключение этого устройства.', + detail: 'The host owner declined this device. Request a new QR code to try again.', + }); + return send(res, 403, { 'content-type': 'text/html; charset=utf-8' }, page); + } + + const page = htmlPage({ + title: 'Подтверждение не получено / Confirmation timed out', + message: 'Владелец компьютера не подтвердил подключение. Запросите новый QR-код.', + detail: 'The host did not confirm the connection in time. Request a new QR code.', + }); + return send(res, 408, { 'content-type': 'text/html; charset=utf-8' }, page); + } + + /** + * Tell a remote client which Session it is bound to. + * @param {http.IncomingMessage} req request. + * @param {http.ServerResponse} res response. + */ + handleBootstrap(req, res) { + if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'method' }); + const device = this.deviceOf(req); + if (device === undefined) return this.rejectUnauthenticated(req, res); + const advertised = req.headers['x-dsh-public-origin']; + sendJson(res, 200, { + remote: true, + version: 1, + deviceId: device.id, + label: device.label, + sessionId: device.sessionId, + origin: typeof advertised === 'string' && advertised !== '' ? advertised : this.publicOrigin, + }); + } + + /** + * Remember the Session a paired browser is looking at. + * @param {http.IncomingMessage} req request. + * @param {http.ServerResponse} res response. + */ + async handleSession(req, res) { + if (req.method !== 'POST') return sendJson(res, 405, { ok: false, code: 'method' }); + const device = this.deviceOf(req); + if (device === undefined) return this.rejectUnauthenticated(req, res); + const body = await readJson(req); + if (body === null || typeof body !== 'object') return sendJson(res, 400, { ok: false, code: 'bad-request' }); + const sessionId = body.sessionId; + if (sessionId !== null && (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 200)) { + return sendJson(res, 400, { ok: false, code: 'bad-session' }); + } + this.devices.setSession(device.id, sessionId); + sendJson(res, 200, { ok: true }); + } + + /** + * Remove this browser's own pairing. + * @param {http.IncomingMessage} req request. + * @param {http.ServerResponse} res response. + */ + async handleForgetSelf(req, res) { + if (req.method !== 'POST') return sendJson(res, 405, { ok: false, code: 'method' }); + const device = this.deviceOf(req); + if (device === undefined) return this.rejectUnauthenticated(req, res); + const sockets = this.sockets.get(device.id); + if (sockets !== undefined) for (const socket of sockets) socket.destroy(); + this.sockets.delete(device.id); + await this.devices.revoke(device.id); + const secure = this.protocol === 'https:' ? '; Secure' : ''; + send(res, 200, { + 'content-type': 'application/json; charset=utf-8', + 'set-cookie': DEVICE_COOKIE + '=; Max-Age=0; Path=/; HttpOnly; SameSite=Lax' + secure, + }, JSON.stringify({ ok: true })); + } + + /** + * Proxy one authenticated HTTP request to the Desktop Host. + * @param {http.IncomingMessage} req request. + * @param {http.ServerResponse} res response. + */ + async forwardHttp(req, res) { + let cookie = await this.ensureUpstreamCookie(); + + const run = (header) => new Promise((resolveRun, rejectRun) => { + const transport = this.upstream.protocol === 'https:' ? https : http; + const request = transport.request({ + protocol: this.upstream.protocol, + hostname: this.upstream.host, + port: this.upstream.port, + method: req.method, + path: req.url, + headers: this.forwardHeaders(req.headers, header), + agent: this.upstream.protocol === 'https:' ? this.secureAgent : this.agent, + ...(this.upstream.protocol === 'https:' ? { rejectUnauthorized: false } : {}), + }, (response) => { + const status = response.statusCode ?? 502; + if (status === 401) { + /* The Host rejected our synthetic cookie: replace it for the next call. */ + this.ensureUpstreamCookie(true).catch(() => {}); + if (req.method === 'GET' || req.method === 'HEAD') { + response.resume(); + resolveRun({ retry: true }); + return; + } + } + res.writeHead(status, this.responseHeaders(response.headers)); + response.pipe(res); + response.on('error', () => res.destroy()); + resolveRun({ retry: false }); + }); + request.on('error', rejectRun); + res.on('close', () => { + if (!res.writableEnded) request.destroy(); + }); + req.pipe(request); + }); + + try { + const first = await run(cookie); + if (!first.retry) return; + cookie = await this.ensureUpstreamCookie(true); + await new Promise((resolveRun, rejectRun) => { + const transport = this.upstream.protocol === 'https:' ? https : http; + const request = transport.request({ + protocol: this.upstream.protocol, + hostname: this.upstream.host, + port: this.upstream.port, + method: req.method, + path: req.url, + headers: this.forwardHeaders(req.headers, cookie), + agent: this.upstream.protocol === 'https:' ? this.secureAgent : this.agent, + ...(this.upstream.protocol === 'https:' ? { rejectUnauthorized: false } : {}), + }, (response) => { + res.writeHead(response.statusCode ?? 502, this.responseHeaders(response.headers)); + response.pipe(res); + response.on('error', () => res.destroy()); + resolveRun(); + }); + request.on('error', rejectRun); + res.on('close', () => { + if (!res.writableEnded) request.destroy(); + }); + req.pipe(request); + }); + } catch (error) { + this.log('warn', error); + if (!res.headersSent) send(res, 502, { 'content-type': 'text/plain; charset=utf-8' }, 'lan-share: upstream request failed\n'); + else res.destroy(); + } + } + + /** + * Build the headers sent upstream: the same rewriting the Electron shell + * applies to its dsh-app://app requests. + * @param {http.IncomingHttpHeaders} incoming client headers. + * @param {string} cookie minted upstream cookie. + * @returns {http.OutgoingHttpHeaders} upstream headers. + */ + forwardHeaders(incoming, cookie) { + /** @type {http.OutgoingHttpHeaders} */ + const out = {}; + for (const [name, value] of Object.entries(incoming)) { + const lower = name.toLowerCase(); + if (REQUEST_REWRITE.has(lower) || lower.startsWith('x-forwarded-') || lower === 'forwarded') continue; + if (value !== undefined) out[lower] = value; + } + out.host = this.upstream.authority; + out.cookie = cookie; + return out; + } + + /** + * Filter and rewrite upstream response headers. + * @param {http.IncomingHttpHeaders} incoming upstream headers. + * @returns {http.OutgoingHttpHeaders} response headers. + */ + responseHeaders(incoming) { + /** @type {http.OutgoingHttpHeaders} */ + const out = {}; + for (const [name, value] of Object.entries(incoming)) { + const lower = name.toLowerCase(); + if (RESPONSE_DROP.has(lower) || value === undefined) continue; + if (lower === 'set-cookie') { + const cookies = Array.isArray(value) ? value : [value]; + const kept = cookies.filter((cookie) => !String(cookie).startsWith('dsh-auth-')); + if (kept.length > 0) out['set-cookie'] = kept; + continue; + } + if (lower === 'location') { + out.location = this.rewriteLocation(String(value)); + continue; + } + out[lower] = value; + } + return out; + } + + /** + * Point an absolute upstream redirect at the public origin. + * @param {string} location Location header. + * @returns {string} rewritten Location. + */ + rewriteLocation(location) { + const upstream = this.upstream.origin; + if (location.startsWith(upstream)) { + const suffix = location.slice(upstream.length); + return (this.publicOrigin ?? '') + (suffix.startsWith('/') ? suffix : '/' + suffix); + } + return location; + } + + /** + * Ensure the Host's browser cookie is cached and fresh. + * @param {boolean} [force] mint even when the cached cookie looks valid. + * @returns {Promise} Cookie header value. + */ + async ensureUpstreamCookie(force = false) { + const now = Date.now(); + if (!force && this.cookie !== null && this.cookie.expiresAt - COOKIE_REFRESH_MARGIN_MS > now) return this.cookie.header; + if (this.cookieMint === null) { + this.cookieMint = this.mintUpstreamCookie() + .then((minted) => { + this.cookie = minted; + this.lastMintError = null; + return minted; + }) + .catch((error) => { + this.lastMintError = this.describeError(error); + throw error; + }) + .finally(() => { + this.cookieMint = null; + }); + } + const minted = await this.cookieMint; + return minted.header; + } + + /** + * Exchange the Host's launch URL for its authority-bound browser cookie. + * @returns {Promise<{ header: string, expiresAt: number }>} cookie and expiry. + */ + async mintUpstreamCookie() { + const launch = new URL(this.authenticatedUrl()); + const transport = launch.protocol === 'https:' ? https : http; + return await new Promise((resolveMint, rejectMint) => { + const request = transport.request({ + protocol: launch.protocol, + hostname: this.upstream.host, + port: this.upstream.port, + method: 'GET', + path: launch.pathname + launch.search, + headers: { host: this.upstream.authority, accept: 'text/html', 'cache-control': 'no-store' }, + ...(launch.protocol === 'https:' ? { rejectUnauthorized: false } : {}), + }, (response) => { + response.resume(); + if (response.statusCode !== 303) { + rejectMint(new Error('lan-share: host authentication answered ' + String(response.statusCode))); + return; + } + const raw = response.headers['set-cookie']; + const cookie = Array.isArray(raw) ? raw[0] : raw; + if (typeof cookie !== 'string' || cookie === '') { + rejectMint(new Error('lan-share: host authentication returned no cookie')); + return; + } + const semicolon = cookie.indexOf(';'); + const header = semicolon === -1 ? cookie : cookie.slice(0, semicolon); + resolveMint({ header, expiresAt: cookieExpiry(cookie) ?? Date.now() + FALLBACK_COOKIE_TTL_MS }); + }); + request.on('error', rejectMint); + request.setTimeout(10_000, () => request.destroy(new Error('lan-share: host authentication timed out'))); + request.end(); + }); + } + + /** + * Proxy one WebSocket upgrade, with one re-mint retry on a 401 response. + * @param {http.IncomingMessage} req upgrade request. + * @param {net.Socket} socket client socket. + * @param {Buffer} head bytes already read by the HTTP parser. + */ + async handleUpgrade(req, socket, head) { + const pathname = this.pathnameOf(req.url); + if (pathname === undefined || pathname.startsWith('/api/lan-share/')) { + socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); + return; + } + const device = this.deviceOf(req); + if (device === undefined) { + socket.end('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n'); + return; + } + + try { + let cookie = await this.ensureUpstreamCookie(); + let first = await this.openUpgrade(req, head, cookie); + if (first.status === 401) { + first.socket.destroy(); + cookie = await this.ensureUpstreamCookie(true); + first = await this.openUpgrade(req, head, cookie); + } + const upstream = first.socket; + if (first.status !== 101) { + socket.write(first.head); + upstream.pipe(socket); + socket.pipe(upstream); + const finish = () => { + socket.destroy(); + upstream.destroy(); + }; + upstream.on('error', finish); + socket.on('error', finish); + upstream.on('close', finish); + socket.on('close', finish); + return; + } + + /* Track the socket so revoking this device tears the live stream down. */ + let set = this.sockets.get(device.id); + if (set === undefined) { + set = new Set(); + this.sockets.set(device.id, set); + } + set.add(socket); + + socket.setNoDelay(true); + upstream.setNoDelay(true); + socket.write(first.head); + upstream.pipe(socket); + socket.pipe(upstream); + + const cleanup = () => { + socket.destroy(); + upstream.destroy(); + const current = this.sockets.get(device.id); + if (current !== undefined) { + current.delete(socket); + if (current.size === 0) this.sockets.delete(device.id); + } + }; + upstream.on('error', cleanup); + socket.on('error', cleanup); + upstream.on('close', cleanup); + socket.on('close', cleanup); + } catch (error) { + this.log('warn', error); + socket.end('HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n'); + } + } + + /** + * Open the upstream side of one upgrade and read its response headers. + * @param {http.IncomingMessage} req upgrade request. + * @param {Buffer} head client bytes already read. + * @param {string} cookie upstream cookie. + * @returns {Promise<{ socket: net.Socket, status: number | null, head: Buffer }>} connected socket and response. + */ + async openUpgrade(req, head, cookie) { + const headers = this.forwardHeaders(req.headers, cookie); + headers.connection = 'Upgrade'; + headers.upgrade = typeof req.headers.upgrade === 'string' ? req.headers.upgrade : 'websocket'; + headers.origin = this.upstream.origin; + headers['sec-fetch-site'] = 'same-origin'; + let requestText = req.method + ' ' + req.url + ' HTTP/1.1\r\n'; + for (const [name, value] of Object.entries(headers)) { + if (value === undefined) continue; + if (Array.isArray(value)) for (const item of value) requestText += name + ': ' + item + '\r\n'; + else requestText += name + ': ' + String(value) + '\r\n'; + } + requestText += '\r\n'; + + const socket = await this.connectUpstream(); + socket.write(requestText); + if (head.length > 0) socket.write(head); + + const response = await this.readUpgradeResponse(socket); + return { socket, status: response.status, head: response.head }; + } + + /** + * Connect to the upstream WebSocket port. + * @returns {Promise} connected socket. + */ + connectUpstream() { + return new Promise((resolveConnect, rejectConnect) => { + const socket = this.upstream.protocol === 'https:' + ? tls.connect({ host: this.upstream.host, port: this.upstream.port, rejectUnauthorized: false }) + : net.connect({ host: this.upstream.host, port: this.upstream.port }); + const event = this.upstream.protocol === 'https:' ? 'secureConnect' : 'connect'; + const onError = (error) => { + socket.off(event, onConnect); + rejectConnect(error); + }; + const onConnect = () => { + socket.off('error', onError); + resolveConnect(socket); + }; + socket.once('error', onError); + socket.once(event, onConnect); + socket.setNoDelay(true); + }); + } + + /** + * Buffer the upstream handshake response and split it from any following bytes. + * @param {net.Socket} socket upstream socket. + * @returns {Promise<{ status: number | null, head: Buffer }>} status and the response bytes. + */ + readUpgradeResponse(socket) { + return new Promise((resolveRead, rejectRead) => { + const chunks = []; + let size = 0; + const onData = (chunk) => { + chunks.push(chunk); + size += chunk.length; + const buffer = Buffer.concat(chunks, size); + const end = buffer.indexOf('\r\n\r\n'); + if (end === -1) { + if (size > 64 * 1024) { + cleanup(); + rejectRead(new Error('lan-share: oversized upstream handshake')); + } + return; + } + cleanup(); + const match = /^HTTP\/1\.[01] (\d{3})/.exec(buffer.subarray(0, end).toString('latin1')); + resolveRead({ status: match === null ? null : Number(match[1]), head: buffer }); + }; + const onError = (error) => { + cleanup(); + rejectRead(error); + }; + const onClose = () => { + cleanup(); + rejectRead(new Error('lan-share: upstream closed during handshake')); + }; + const cleanup = () => { + socket.off('data', onData); + socket.off('error', onError); + socket.off('close', onClose); + }; + socket.on('data', onData); + socket.once('error', onError); + socket.once('close', onClose); + }); + } + + /** + * Build a human device label from the request. + * @param {http.IncomingMessage} req request. + * @returns {string} label. + */ + describeRequest(req) { + return describeUserAgent(req.headers['user-agent']); + } + + /** + * The client's address for display. + * @param {http.IncomingMessage} req request. + * @returns {string} address. + */ + peerOf(req) { + return peerAddress(req.socket.remoteAddress); + } + + /** + * Turn an error into a short diagnostic without leaking contents. + * @param {unknown} error thrown value. + * @returns {string} message. + */ + describeError(error) { + return error instanceof Error ? error.message : String(error); + } +} + +/** + * Read a TLS file, reporting its path rather than its contents on failure. + * @param {string} file path. + * @returns {Buffer} file bytes. + */ +function readFileSyncSafe(file) { + try { + return readFileSync(file); + } catch (error) { + throw new Error('cannot read ' + file + ': ' + (error instanceof Error ? error.message : String(error))); + } +} \ No newline at end of file diff --git a/qr.js b/qr.js new file mode 100644 index 0000000..f0cf946 --- /dev/null +++ b/qr.js @@ -0,0 +1,606 @@ +/** + * QR Code encoder for the LAN Share pairing URL. + * + * One compact, dependency-free encoder: byte mode, error-correction level M, + * versions 1 through 10 — enough for a LAN URL of a few hundred characters at + * a module count a tablet camera reads comfortably. The implementation follows + * ISO/IEC 18004: data codewords with terminator and pad bytes, Reed-Solomon + * blocks over GF(256), the standard interleaving, function patterns, the eight + * data masks with the specification's penalty scoring, and the BCH-protected + * format and version information. + * + * The encoder is deliberately pure: it returns the module matrix and never + * touches the DOM, so the same code can be tested in Node and rendered as SVG + * by either half of the plugin. + */ + +/** Error-correction level M: 15 format bits value 0b00. */ +const ECC_FORMAT_BITS = 0b00; + +/** + * Byte-mode data capacity per version at level M: one or two block groups, + * each group a count and the data codewords in one block, plus the ECC + * codewords every block carries. + */ +const VERSIONS = { + 1: { ecc: 10, groups: [[1, 16]] }, + 2: { ecc: 16, groups: [[1, 28]] }, + 3: { ecc: 26, groups: [[1, 44]] }, + 4: { ecc: 18, groups: [[2, 32]] }, + 5: { ecc: 24, groups: [[2, 43]] }, + 6: { ecc: 16, groups: [[4, 27]] }, + 7: { ecc: 18, groups: [[4, 31]] }, + 8: { ecc: 22, groups: [[2, 38], [2, 39]] }, + 9: { ecc: 22, groups: [[3, 36], [2, 37]] }, + 10: { ecc: 26, groups: [[4, 43], [1, 44]] }, +}; + +/** Alignment-pattern centre coordinates per version (empty for version 1). */ +const ALIGNMENT = { + 1: [], + 2: [6, 18], + 3: [6, 22], + 4: [6, 26], + 5: [6, 30], + 6: [6, 34], + 7: [6, 22, 38], + 8: [6, 24, 42], + 9: [6, 26, 46], + 10: [6, 28, 50], +}; + +/** Highest version this encoder produces. */ +const MAX_VERSION = 10; + +/** Penalty weights from ISO/IEC 18004 table 24. */ +const PENALTY_N1 = 3; +const PENALTY_N2 = 3; +const PENALTY_N3 = 40; +const PENALTY_N4 = 10; + +/** GF(256) tables, primitive polynomial x^8 + x^4 + x^3 + x^2 + 1 (0x11d). */ +const GF_EXP = new Uint8Array(512); +const GF_LOG = new Uint8Array(256); + +(function buildGaloisTables() { + let value = 1; + for (let i = 0; i < 255; i++) { + GF_EXP[i] = value; + GF_LOG[value] = i; + value <<= 1; + if ((value & 0x100) !== 0) value ^= 0x11d; + } + for (let i = 255; i < 512; i++) GF_EXP[i] = GF_EXP[i - 255]; +})(); + +/** + * Multiply two field elements. + * @param {number} a first element. + * @param {number} b second element. + * @returns {number} the product. + */ +function gfMultiply(a, b) { + if (a === 0 || b === 0) return 0; + return GF_EXP[GF_LOG[a] + GF_LOG[b]]; +} + +/** + * Reed-Solomon generator polynomial of the given degree. + * @param {number} degree number of ECC codewords. + * @returns {Uint8Array} coefficients, highest order first. + */ +function reedSolomonGenerator(degree) { + const result = new Uint8Array(degree); + result[degree - 1] = 1; + let root = 1; + for (let i = 0; i < degree; i++) { + for (let j = 0; j < degree; j++) { + result[j] = gfMultiply(result[j], root); + if (j + 1 < degree) result[j] ^= result[j + 1]; + } + root = gfMultiply(root, 0x02); + } + return result; +} + +/** + * Reed-Solomon remainder of one data block. + * @param {Uint8Array} data data codewords of the block. + * @param {Uint8Array} generator generator polynomial. + * @returns {Uint8Array} ECC codewords for the block. + */ +function reedSolomonRemainder(data, generator) { + const result = new Uint8Array(generator.length); + for (const byte of data) { + const factor = byte ^ result[0]; + result.copyWithin(0, 1); + result[result.length - 1] = 0; + for (let i = 0; i < result.length; i++) result[i] ^= gfMultiply(generator[i], factor); + } + return result; +} + +/** + * Number of data bits a version reserves for the byte-mode character count. + * @param {number} version QR version. + * @returns {number} 8 for versions 1-9 and 16 from version 10. + */ +function charCountBits(version) { + return version <= 9 ? 8 : 16; +} + +/** + * Data capacity in whole bytes for one version. + * @param {number} version QR version. + * @returns {number} bytes available to mode, length and payload. + */ +function dataCapacityBytes(version) { + const spec = VERSIONS[version]; + const codewords = spec.groups.reduce((sum, [count, length]) => sum + count * length, 0); + return codewords; +} + +/** + * Largest payload this encoder accepts in one version. + * @param {number} version QR version. + * @returns {number} payload byte budget. + */ +function payloadCapacityBytes(version) { + return Math.floor((dataCapacityBytes(version) * 8 - 4 - charCountBits(version)) / 8); +} + +/** + * Choose the smallest version that fits the payload. + * @param {number} length payload length in bytes. + * @returns {number} a version between 1 and {@link MAX_VERSION}. + * @throws {RangeError} when the payload is too long for version 10. + */ +function chooseVersion(length) { + for (let version = 1; version <= MAX_VERSION; version++) { + if (length <= payloadCapacityBytes(version)) return version; + } + throw new RangeError('qr: payload is too long for a version-10 QR code'); +} + +/** + * Append the low bits of a value to a growing bit array. + * @param {number[]} bits destination. + * @param {number} value bits to append. + * @param {number} length how many bits of value to append, most significant first. + */ +function appendBits(bits, value, length) { + if (length < 0 || length > 31 || value >>> length !== 0) throw new RangeError('qr: bit append out of range'); + for (let i = length - 1; i >= 0; i--) bits.push((value >>> i) & 1); +} + +/** + * Assemble the data codewords: mode indicator, character count, payload, + * terminator, byte padding and the alternating pad bytes. + * @param {Uint8Array} bytes payload bytes. + * @param {number} version QR version. + * @returns {Uint8Array} data codewords before ECC. + */ +function buildDataCodewords(bytes, version) { + const bits = []; + appendBits(bits, 0b0100, 4); + appendBits(bits, bytes.length, charCountBits(version)); + for (const byte of bytes) appendBits(bits, byte, 8); + + const capacity = dataCapacityBytes(version); + const capacityBits = capacity * 8; + appendBits(bits, 0, Math.min(4, capacityBits - bits.length)); + appendBits(bits, 0, (8 - (bits.length % 8)) % 8); + + const codewords = new Uint8Array(capacity); + for (let i = 0; i < bits.length; i += 8) { + let value = 0; + for (let j = 0; j < 8; j++) value = (value << 1) | bits[i + j]; + codewords[i >>> 3] = value; + } + for (let i = bits.length >>> 3, pad = 0xec; i < capacity; i++, pad ^= 0xec ^ 0x11) codewords[i] = pad; + return codewords; +} + +/** + * Split data codewords into blocks and interleave data with ECC codewords. + * @param {Uint8Array} codewords data codewords. + * @param {number} version QR version. + * @returns {Uint8Array} final codeword sequence. + */ +function interleave(codewords, version) { + const spec = VERSIONS[version]; + const generator = reedSolomonGenerator(spec.ecc); + const blocks = []; + let offset = 0; + for (const [count, length] of spec.groups) { + for (let i = 0; i < count; i++) { + const block = codewords.slice(offset, offset + length); + offset += length; + blocks.push({ data: block, ecc: reedSolomonRemainder(block, generator) }); + } + } + const result = []; + const maxData = Math.max(...blocks.map((block) => block.data.length)); + for (let i = 0; i < maxData; i++) { + for (const block of blocks) if (i < block.data.length) result.push(block.data[i]); + } + for (let i = 0; i < spec.ecc; i++) { + for (const block of blocks) result.push(block.ecc[i]); + } + return Uint8Array.from(result); +} + +/** + * BCH(15,5) format bits with the specification's mask. + * @param {number} mask data mask 0-7. + * @returns {number} 15 format bits. + */ +function formatBits(mask) { + const data = (ECC_FORMAT_BITS << 3) | mask; + let remainder = data; + for (let i = 0; i < 10; i++) remainder = (remainder << 1) ^ ((remainder >>> 9) * 0x537); + return ((data << 10) | remainder) ^ 0x5412; +} + +/** + * BCH(18,6) version bits. + * @param {number} version QR version, 7 or higher. + * @returns {number} 18 version bits. + */ +function versionBits(version) { + let remainder = version; + for (let i = 0; i < 12; i++) remainder = (remainder << 1) ^ ((remainder >>> 11) * 0x1f25); + return (version << 12) | remainder; +} + +/** + * Query one bit of a value, counting from the least significant bit. + * @param {number} value source value. + * @param {number} index bit index. + * @returns {boolean} true for a set bit. + */ +function bit(value, index) { + return ((value >>> index) & 1) !== 0; +} + +/** + * One QR matrix under construction. + */ +class Matrix { + /** + * @param {number} size side length in modules. + */ + constructor(size) { + this.size = size; + this.modules = Array.from({ length: size }, () => new Array(size).fill(false)); + this.reserved = Array.from({ length: size }, () => new Array(size).fill(false)); + } + + /** + * Set a module and mark it as a function pattern. + * @param {number} row row index. + * @param {number} col column index. + * @param {boolean} dark whether the module is dark. + */ + setFunction(row, col, dark) { + this.modules[row][col] = dark; + this.reserved[row][col] = true; + } + + /** + * Draw a finder pattern and its separator. + * @param {number} row centre row. + * @param {number} col centre column. + */ + drawFinder(row, col) { + for (let dy = -4; dy <= 4; dy++) { + for (let dx = -4; dx <= 4; dx++) { + const y = row + dy; + const x = col + dx; + if (y < 0 || y >= this.size || x < 0 || x >= this.size) continue; + const distance = Math.max(Math.abs(dx), Math.abs(dy)); + this.setFunction(y, x, distance !== 2 && distance !== 4); + } + } + } + + /** + * Draw one 5x5 alignment pattern. + * @param {number} row centre row. + * @param {number} col centre column. + */ + drawAlignment(row, col) { + for (let dy = -2; dy <= 2; dy++) { + for (let dx = -2; dx <= 2; dx++) { + this.setFunction(row + dy, col + dx, Math.max(Math.abs(dx), Math.abs(dy)) !== 1); + } + } + } +} + +/** + * Draw all fixed function patterns for one version. + * @param {Matrix} matrix destination. + * @param {number} version QR version. + */ +function drawFunctionPatterns(matrix, version) { + const size = matrix.size; + matrix.drawFinder(3, 3); + matrix.drawFinder(3, size - 4); + matrix.drawFinder(size - 4, 3); + + for (let i = 8; i < size - 8; i++) { + const dark = i % 2 === 0; + matrix.setFunction(6, i, dark); + matrix.setFunction(i, 6, dark); + } + + const centres = ALIGNMENT[version]; + for (const row of centres) { + for (const col of centres) { + if ((row === 6 && col === 6) || (row === 6 && col === size - 7) || (row === size - 7 && col === 6)) continue; + matrix.drawAlignment(row, col); + } + } + + /* Reserve the format-information areas. */ + for (let i = 0; i <= 8; i++) { + if (i !== 6) { + matrix.setFunction(8, i, false); + matrix.setFunction(i, 8, false); + } + } + for (let i = 0; i < 8; i++) matrix.setFunction(8, size - 1 - i, false); + for (let i = 8; i < 15; i++) matrix.setFunction(size - 15 + i, 8, false); + matrix.setFunction(size - 8, 8, true); + + if (version >= 7) { + for (let i = 0; i < 18; i++) { + const a = size - 11 + (i % 3); + const b = Math.floor(i / 3); + matrix.setFunction(b, a, false); + matrix.setFunction(a, b, false); + } + } +} + +/** + * Draw the two format-information copies. + * @param {Matrix} matrix destination. + * @param {number} mask data mask. + */ +function drawFormatBits(matrix, mask) { + const size = matrix.size; + const bits = formatBits(mask); + for (let i = 0; i <= 5; i++) matrix.setFunction(i, 8, bit(bits, i)); + matrix.setFunction(7, 8, bit(bits, 6)); + matrix.setFunction(8, 8, bit(bits, 7)); + matrix.setFunction(8, 7, bit(bits, 8)); + for (let i = 9; i < 15; i++) matrix.setFunction(8, 14 - i, bit(bits, i)); + for (let i = 0; i < 8; i++) matrix.setFunction(8, size - 1 - i, bit(bits, i)); + for (let i = 8; i < 15; i++) matrix.setFunction(size - 15 + i, 8, bit(bits, i)); + matrix.setFunction(size - 8, 8, true); +} + +/** + * Draw the two version-information copies (versions 7 and above). + * @param {Matrix} matrix destination. + * @param {number} version QR version. + */ +function drawVersionBits(matrix, version) { + if (version < 7) return; + const size = matrix.size; + const bits = versionBits(version); + for (let i = 0; i < 18; i++) { + const a = size - 11 + (i % 3); + const b = Math.floor(i / 3); + matrix.setFunction(b, a, bit(bits, i)); + matrix.setFunction(a, b, bit(bits, i)); + } +} + +/** + * Place the final codeword stream into the remaining modules in zigzag order. + * @param {Matrix} matrix destination. + * @param {Uint8Array} codewords interleaved codewords. + */ +function drawCodewords(matrix, codewords) { + const size = matrix.size; + let index = 0; + for (let right = size - 1; right >= 1; right -= 2) { + if (right === 6) right = 5; + for (let vertical = 0; vertical < size; vertical++) { + for (let j = 0; j < 2; j++) { + const col = right - j; + const upward = ((right + 1) & 2) === 0; + const row = upward ? size - 1 - vertical : vertical; + if (matrix.reserved[row][col] || index >= codewords.length * 8) continue; + matrix.modules[row][col] = ((codewords[index >>> 3] >>> (7 - (index & 7))) & 1) !== 0; + index++; + } + } + } +} + +/** + * Whether the data mask inverts one module. + * @param {number} mask mask index 0-7. + * @param {number} row module row. + * @param {number} col module column. + * @returns {boolean} true when the module flips. + */ +function maskCondition(mask, row, col) { + switch (mask) { + case 0: return (row + col) % 2 === 0; + case 1: return row % 2 === 0; + case 2: return col % 3 === 0; + case 3: return (row + col) % 3 === 0; + case 4: return (Math.floor(row / 2) + Math.floor(col / 3)) % 2 === 0; + case 5: return ((row * col) % 2) + ((row * col) % 3) === 0; + case 6: return (((row * col) % 2) + ((row * col) % 3)) % 2 === 0; + case 7: return (((row + col) % 2) + ((row * col) % 3)) % 2 === 0; + default: throw new RangeError('qr: mask must be 0-7'); + } +} + +/** + * Apply one mask to every non-function module. + * @param {Matrix} matrix matrix to modify. + * @param {number} mask mask index 0-7. + */ +function applyMask(matrix, mask) { + for (let row = 0; row < matrix.size; row++) { + for (let col = 0; col < matrix.size; col++) { + if (!matrix.reserved[row][col] && maskCondition(mask, row, col)) matrix.modules[row][col] = !matrix.modules[row][col]; + } + } +} + +/** + * Finder-like pattern history helpers used by penalty rule 3. + */ +function addHistory(runLength, history, size) { + if (history[0] === 0) runLength += size; + history.pop(); + history.unshift(runLength); +} + +function countPatterns(history) { + const n = history[1]; + const core = n > 0 && history[2] === n && history[3] === n * 3 && history[4] === n && history[5] === n; + return (core && history[0] >= n * 4 && history[6] >= n ? 1 : 0) + + (core && history[6] >= n * 4 && history[0] >= n ? 1 : 0); +} + +function terminateAndCount(runColor, runLength, history, size) { + if (runColor) { + addHistory(runLength, history, size); + runLength = 0; + } + runLength += size; + addHistory(runLength, history, size); + return countPatterns(history); +} + +/** + * Specification penalty score of one masked matrix. + * @param {Matrix} matrix masked matrix. + * @returns {number} penalty; lower is better. + */ +function penaltyScore(matrix) { + const size = matrix.size; + const modules = matrix.modules; + let result = 0; + + for (let row = 0; row < size; row++) { + let runColor = false; + let runLength = 0; + const history = [0, 0, 0, 0, 0, 0, 0]; + for (let col = 0; col < size; col++) { + if (modules[row][col] === runColor) { + runLength++; + if (runLength === 5) result += PENALTY_N1; + else if (runLength > 5) result++; + } else { + addHistory(runLength, history, size); + if (!runColor) result += countPatterns(history) * PENALTY_N3; + runColor = modules[row][col]; + runLength = 1; + } + } + result += terminateAndCount(runColor, runLength, history, size) * PENALTY_N3; + } + + for (let col = 0; col < size; col++) { + let runColor = false; + let runLength = 0; + const history = [0, 0, 0, 0, 0, 0, 0]; + for (let row = 0; row < size; row++) { + if (modules[row][col] === runColor) { + runLength++; + if (runLength === 5) result += PENALTY_N1; + else if (runLength > 5) result++; + } else { + addHistory(runLength, history, size); + if (!runColor) result += countPatterns(history) * PENALTY_N3; + runColor = modules[row][col]; + runLength = 1; + } + } + result += terminateAndCount(runColor, runLength, history, size) * PENALTY_N3; + } + + for (let row = 0; row < size - 1; row++) { + for (let col = 0; col < size - 1; col++) { + const color = modules[row][col]; + if (color === modules[row][col + 1] && color === modules[row + 1][col] && color === modules[row + 1][col + 1]) { + result += PENALTY_N2; + } + } + } + + let dark = 0; + for (const row of modules) for (const cell of row) if (cell) dark++; + const total = size * size; + const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1; + result += k * PENALTY_N4; + return result; +} + +/** + * Encode one payload into a QR module matrix. + * @param {string} text payload, encoded as UTF-8 bytes. + * @param {{ mask?: number, minVersion?: number, maxVersion?: number }} [options] + * a fixed mask for tests, or version bounds for callers that need a minimum size. + * @returns {{ version: number, size: number, mask: number, rows: string[] }} + * the chosen version, side length, mask, and one string of '0'/'1' per row. + */ +export function encodeQr(text, options = {}) { + if (typeof text !== 'string') throw new TypeError('qr: text must be a string'); + const bytes = new TextEncoder().encode(text); + let version = chooseVersion(bytes.length); + if (options.minVersion !== undefined) { + if (!Number.isInteger(options.minVersion) || options.minVersion < 1 || options.minVersion > MAX_VERSION) { + throw new RangeError('qr: minVersion must be an integer between 1 and 10'); + } + version = Math.max(version, options.minVersion); + } + if (options.maxVersion !== undefined) { + if (!Number.isInteger(options.maxVersion) || options.maxVersion < 1 || options.maxVersion > MAX_VERSION) { + throw new RangeError('qr: maxVersion must be an integer between 1 and 10'); + } + if (version > options.maxVersion) throw new RangeError('qr: payload does not fit the requested maximum version'); + } + + const codewords = interleave(buildDataCodewords(bytes, version), version); + const size = version * 4 + 17; + const base = new Matrix(size); + drawFunctionPatterns(base, version); + drawCodewords(base, codewords); + + const masks = options.mask === undefined ? [0, 1, 2, 3, 4, 5, 6, 7] : [options.mask]; + let best; + let bestPenalty = Infinity; + for (const mask of masks) { + const candidate = new Matrix(size); + candidate.modules = base.modules.map((row) => row.slice()); + candidate.reserved = base.reserved.map((row) => row.slice()); + applyMask(candidate, mask); + drawFormatBits(candidate, mask); + drawVersionBits(candidate, version); + const penalty = penaltyScore(candidate); + if (penalty < bestPenalty) { + bestPenalty = penalty; + best = { mask, matrix: candidate }; + } + } + + return { + version, + size, + mask: best.mask, + rows: best.matrix.modules.map((row) => row.map((dark) => (dark ? '1' : '0')).join('')), + }; +} + +export const qrInternals = { payloadCapacityBytes, chooseVersion, formatBits, versionBits, penaltyScore }; \ No newline at end of file diff --git a/relay.js b/relay.js new file mode 100644 index 0000000..837f7e8 --- /dev/null +++ b/relay.js @@ -0,0 +1,730 @@ +/** + * Outbound relay tunnel for the LAN Share host. + * + * The Desktop Host cannot accept inbound connections behind NAT, so it dials + * the relay and keeps one WebSocket open. The relay turns browser requests + * into stream frames; this client replays them against the local LAN listener, + * which keeps owning pairing, device cookies, and the Host proxy. No DSH + * credential leaves this process: the relay sees only the same browser headers + * the tablet would have sent to the LAN listener. + * + * Frames are JSON text with base64 bodies. A per-stream ack window keeps both + * sides bounded; the relay never buffers a whole upload or download. + */ + +import http from 'node:http'; +import https from 'node:https'; +import net from 'node:net'; +import tls from 'node:tls'; +import { hostname } from 'node:os'; + +/** Subprotocol selected by the relay. */ +const TUNNEL_PROTOCOL = 'dsh-relay.v1'; + +/** Subprotocol prefix carrying the agent token out of URLs and access logs. */ +const TOKEN_PROTOCOL_PREFIX = 'dsh-token.'; + +/** Headers never replayed to the local listener. */ +const HOP_BY_HOP = new Set([ + 'connection', + 'keep-alive', + 'proxy-authenticate', + 'proxy-authorization', + 'proxy-connection', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'expect', +]); + +/** + * Add Secure to a Set-Cookie value when the public page is HTTPS. + * @param {string | string[]} value cookie values. + * @param {boolean} secure whether the public origin is HTTPS. + * @returns {string | string[]} values with Secure where missing. + */ +function secureCookies(value, secure) { + if (!secure) return value; + const one = (cookie) => (/;\s*secure\s*(?:;|$)/i.test(cookie) ? cookie : cookie + '; Secure'); + return Array.isArray(value) ? value.map(one) : one(value); +} + +/** + * Rewrite a private absolute redirect to the public origin. + * @param {string} value Location header. + * @param {string[]} privateOrigins origins the listener may emit. + * @param {string | null} publicOrigin public origin. + * @returns {string} rewritten value. + */ +function rewriteOrigin(value, privateOrigins, publicOrigin) { + if (typeof value !== 'string' || publicOrigin === null) return value; + for (const origin of privateOrigins) { + if (origin === '') continue; + if (value === origin) return publicOrigin + '/'; + if (value.startsWith(origin + '/')) return publicOrigin + value.slice(origin.length); + } + return value; +} + +/** + * Response headers the relay will forward. + * @param {http.IncomingHttpHeaders} headers upstream headers. + * @param {string[]} privateOrigins local listener spellings. + * @param {string | null} publicOrigin public origin. + * @param {boolean} secure whether the public origin is HTTPS. + * @returns {Record} headers. + */ +function responseHeaders(headers, privateOrigins, publicOrigin, secure) { + const out = {}; + for (const [name, value] of Object.entries(headers)) { + if (value === undefined) continue; + const lower = name.toLowerCase(); + if (lower === 'location') { + out[name] = rewriteOrigin(String(value), privateOrigins, publicOrigin); + } else if (lower === 'set-cookie') { + out[name] = secureCookies(value, secure); + } else { + out[name] = value; + } + } + return out; +} + +/** + * A tunnel to one relay. + */ +export class RelayTunnel { + /** + * @param {object} options composition. + * @param {string} options.url relay WebSocket URL. + * @param {string} options.token agent token. + * @param {string | null} options.agentId advertised identity. + * @param {string | null} options.publicOrigin configured public origin. + * @param {string} options.localOrigin LAN listener's advertised origin. + * @param {string} options.localBindOrigin LAN listener's bind origin. + * @param {string} options.localHost address the LAN listener is reachable at. + * @param {number} options.localPort LAN listener port. + * @param {string} options.localProtocol http: or https:. + * @param {() => Array<{ token: string, sessionId: string | null, expiresAt: number }>} options.activeTickets active ticket source. + * @param {number} [options.windowBytes] ack window. + * @param {number} [options.lowWaterBytes] resume threshold. + * @param {number} [options.reconnectMinMs] first reconnect delay. + * @param {number} [options.reconnectMaxMs] maximum reconnect delay. + * @param {(level: string, ...args: unknown[]) => void} [options.logger] host logger. + */ + constructor(options) { + this.url = options.url; + this.token = options.token; + this.agentId = options.agentId ?? undefined; + this.configuredOrigin = options.publicOrigin ?? null; + this.publicOrigin = this.configuredOrigin; + this.localOrigin = options.localOrigin; + this.localBindOrigin = options.localBindOrigin; + this.localHost = options.localHost; + this.localPort = options.localPort; + this.localProtocol = options.localProtocol; + this.localAuthority = new URL(options.localOrigin).host; + this.activeTickets = options.activeTickets ?? (() => []); + this.windowBytes = options.windowBytes ?? 2 * 1024 * 1024; + this.lowWaterBytes = options.lowWaterBytes ?? 512 * 1024; + this.reconnectMinMs = options.reconnectMinMs ?? 1000; + this.reconnectMaxMs = options.reconnectMaxMs ?? 30000; + this.log = options.logger ?? (() => {}); + + this.ws = null; + this.stopped = false; + this.connected = false; + this.connectedAt = null; + this.attempts = 0; + this.lastError = null; + this.reconnectTimer = null; + /** @type {Map} */ + this.streams = new Map(); + this.secure = false; + this.httpAgent = new http.Agent({ keepAlive: true, maxSockets: 64, maxFreeSockets: 16 }); + this.httpsAgent = new https.Agent({ keepAlive: true, maxSockets: 16, maxFreeSockets: 4, rejectUnauthorized: false }); + } + + /** Status for the desktop UI. Never exposes the token. */ + get state() { + return { + enabled: true, + connected: this.connected, + url: this.url, + publicOrigin: this.publicOrigin, + agentId: this.agentId ?? null, + since: this.connectedAt, + attempts: this.attempts, + error: this.lastError, + }; + } + + /** Begin dialing and reconnecting. */ + start() { + if (typeof globalThis.WebSocket !== 'function') { + this.lastError = 'websocket-unavailable'; + this.log('warn', 'lan-share: this Node runtime has no global WebSocket; relay is unavailable'); + return; + } + this.stopped = false; + this.connect(); + } + + /** Stop dialing and tear down the tunnel and its streams. */ + async stop() { + this.stopped = true; + if (this.reconnectTimer !== null) { + clearTimeout(this.reconnectTimer); + this.reconnectTimer = null; + } + const ws = this.ws; + this.ws = null; + this.connected = false; + this.failAll('relay-stopped'); + if (ws !== null) { + try { + ws.close(1000, 'agent stopping'); + } catch { + /* already closing */ + } + } + this.httpAgent.destroy(); + this.httpsAgent.destroy(); + } + + /** One dial attempt. */ + connect() { + if (this.stopped) return; + let url; + try { + url = new URL(this.url); + } catch (error) { + this.lastError = 'bad-relay-url'; + this.log('warn', error); + return; + } + if (this.agentId !== undefined) url.searchParams.set('agent', this.agentId); + const tokenSafe = /^[A-Za-z0-9._~-]+$/.test(this.token); + if (!tokenSafe) url.searchParams.set('token', this.token); + const protocols = tokenSafe ? [TUNNEL_PROTOCOL, TOKEN_PROTOCOL_PREFIX + this.token] : [TUNNEL_PROTOCOL]; + + let ws; + try { + ws = new WebSocket(url.href, protocols); + } catch (error) { + this.lastError = 'connect-failed'; + this.log('warn', error); + this.scheduleReconnect(); + return; + } + this.ws = ws; + this.lastError = null; + + ws.onopen = () => { + if (this.ws !== ws) return; + this.attempts = 0; + this.connectedAt = Date.now(); + this.send({ + t: 'hello', + agentId: this.agentId ?? null, + name: 'dsh-lan-share', + version: 1, + publicOrigin: this.configuredOrigin, + }); + }; + + ws.onmessage = (event) => { + if (this.ws !== ws) return; + if (typeof event.data !== 'string') return; + let frame; + try { + frame = JSON.parse(event.data); + } catch { + return; + } + if (frame === null || typeof frame !== 'object' || typeof frame.t !== 'string') return; + try { + this.onFrame(frame); + } catch (error) { + this.log('warn', error); + } + }; + + ws.onerror = () => { + if (this.ws !== ws) return; + this.lastError = 'websocket-error'; + }; + + ws.onclose = () => { + if (this.ws !== ws) return; + this.ws = null; + this.connected = false; + this.failAll('relay-disconnected'); + this.scheduleReconnect(); + }; + } + + /** Exponential backoff with jitter. */ + scheduleReconnect() { + if (this.stopped || this.reconnectTimer !== null) return; + const ceiling = Math.min(this.reconnectMaxMs, this.reconnectMinMs * 2 ** this.attempts); + const wait = Math.max(250, Math.floor(ceiling / 2 + Math.random() * ceiling / 2)); + this.attempts += 1; + this.reconnectTimer = setTimeout(() => { + this.reconnectTimer = null; + this.connect(); + }, wait); + if (typeof this.reconnectTimer.unref === 'function') this.reconnectTimer.unref(); + } + + /** + * Send one frame when the tunnel is open. + * @param {object} frame frame. + * @returns {boolean} whether it was handed to the socket. + */ + send(frame) { + const ws = this.ws; + if (ws === null || ws.readyState !== 1) return false; + try { + ws.send(JSON.stringify(frame)); + return true; + } catch (error) { + this.log('warn', error); + return false; + } + } + + /** + * Tell the relay about a one-time QR ticket. + * @param {string} token ticket. + * @param {number} expiresAt absolute expiry. + * @param {string | null} sessionId bound Session. + * @returns {boolean} whether the relay is connected. + */ + registerTicket(token, expiresAt, sessionId) { + return this.send({ t: 'ticket', ticket: token, expiresAt, sessionId: sessionId ?? null }); + } + + /** Withdraw a ticket the user replaced. */ + dropTicket(token) { + this.send({ t: 'ticket-drop', ticket: token }); + } + + /** Dispatch one relay frame. */ + onFrame(frame) { + if (frame.t === 'hello') { + this.connected = true; + if (typeof frame.publicOrigin === 'string' && frame.publicOrigin !== '') { + this.publicOrigin = this.configuredOrigin ?? frame.publicOrigin; + } + this.secure = this.publicOrigin !== null && this.publicOrigin.startsWith('https:'); + for (const ticket of this.activeTickets()) { + this.send({ t: 'ticket', ticket: ticket.token, expiresAt: ticket.expiresAt, sessionId: ticket.sessionId }); + } + return; + } + + if (frame.t === 'open') { + if (typeof frame.id !== 'number' || frame.id <= 0) return; + if (frame.kind === 'http') { + const stream = new HttpAgentStream(this, frame); + this.streams.set(frame.id, stream); + stream.start(); + } else if (frame.kind === 'ws') { + const stream = new WsAgentStream(this, frame); + this.streams.set(frame.id, stream); + stream.start(); + } + return; + } + + if (typeof frame.id !== 'number') return; + const stream = this.streams.get(frame.id); + if (stream === undefined) return; + switch (frame.t) { + case 'body': + if (typeof frame.data === 'string') stream.onBody(frame.data); + break; + case 'end': + stream.onEnd(); + break; + case 'cancel': + stream.cancel(); + break; + case 'ack': + stream.onAck(Number(frame.bytes) || 0); + break; + case 'ws-data': + if (typeof frame.data === 'string') stream.onWsData(frame.data); + break; + case 'ws-close': + stream.onWsClose(); + break; + case 'error': + stream.onError(typeof frame.code === 'string' ? frame.code : 'relay-error', typeof frame.message === 'string' ? frame.message : ''); + break; + default: + break; + } + } + + /** Drop one stream from the registry. */ + forget(id) { + this.streams.delete(id); + } + + /** Fail every stream after a tunnel loss. */ + failAll(reason) { + for (const stream of this.streams.values()) { + try { + stream.fail(reason); + } catch { + /* already failed */ + } + } + this.streams.clear(); + } + + /** Request options for a local HTTP call. */ + requestOptions(frame) { + const headers = {}; + for (const [name, value] of Object.entries(frame.headers ?? {})) { + const lower = name.toLowerCase(); + if (HOP_BY_HOP.has(lower) || lower.startsWith('x-forwarded-') || lower === 'forwarded') continue; + if (value !== undefined) headers[lower] = value; + } + headers.host = this.localAuthority; + return { + protocol: this.localProtocol, + hostname: this.localHost, + port: this.localPort, + method: frame.method, + path: frame.url, + headers, + ...(this.localProtocol === 'https:' ? { rejectUnauthorized: false, agent: this.httpsAgent } : { agent: this.httpAgent }), + }; + } +} + +/** + * One HTTP request/response relayed to the LAN listener. + */ +class HttpAgentStream { + /** + * @param {RelayTunnel} tunnel owning tunnel. + * @param {any} frame open frame. + */ + constructor(tunnel, frame) { + this.tunnel = tunnel; + this.id = frame.id; + this.frame = frame; + this.request = null; + this.response = null; + this.closed = false; + this.responseUnacked = 0; + this.paused = false; + this.privateOrigins = [tunnel.localOrigin, tunnel.localBindOrigin]; + } + + /** Open the local request. */ + start() { + const transport = this.tunnel.localProtocol === 'https:' ? https : http; + let request; + try { + request = transport.request(this.tunnel.requestOptions(this.frame)); + } catch (error) { + this.tunnel.send({ t: 'error', id: this.id, code: 'request-failed', message: error instanceof Error ? error.message : String(error) }); + this.finish(); + return; + } + this.request = request; + + request.on('response', (response) => { + if (this.closed) { + response.resume(); + return; + } + this.response = response; + this.tunnel.send({ + t: 'head', + id: this.id, + status: response.statusCode ?? 502, + headers: responseHeaders(response.headers, this.privateOrigins, this.tunnel.publicOrigin, this.tunnel.secure), + }); + response.on('data', (chunk) => { + if (this.closed) return; + this.responseUnacked += chunk.length; + this.tunnel.send({ t: 'body', id: this.id, data: chunk.toString('base64') }); + if (this.responseUnacked > this.tunnel.windowBytes && !this.paused) { + response.pause(); + this.paused = true; + } + }); + response.on('end', () => { + if (this.closed) return; + this.tunnel.send({ t: 'end', id: this.id }); + this.finish(); + }); + response.on('error', () => this.fail('response-error')); + }); + + request.on('error', (error) => { + if (this.closed) return; + this.tunnel.send({ t: 'error', id: this.id, code: 'local-listener-error', message: error instanceof Error ? error.message : String(error) }); + this.finish(); + }); + + request.on('close', () => { + if (!this.closed && this.response === null) this.finish(); + }); + } + + /** Write one request-body chunk and acknowledge it when flushed. */ + onBody(data) { + if (this.closed || this.request === null) return; + const buffer = Buffer.from(data, 'base64'); + const request = this.request; + try { + request.write(buffer, () => { + if (!this.closed) this.tunnel.send({ t: 'ack', id: this.id, bytes: buffer.length }); + }); + } catch { + this.fail('request-write-failed'); + } + } + + /** Finish the local request. */ + onEnd() { + if (this.closed || this.request === null) return; + try { + this.request.end(); + } catch { + this.fail('request-end-failed'); + } + } + + /** The relay accepted response bytes; resume a paused upstream response. */ + onAck(bytes) { + if (!Number.isFinite(bytes) || bytes <= 0) return; + this.responseUnacked = Math.max(0, this.responseUnacked - bytes); + if (this.paused && this.response !== null && this.responseUnacked <= this.tunnel.lowWaterBytes) { + this.paused = false; + this.response.resume(); + } + } + + /** The relay refused or cancelled the stream. */ + cancel() { + this.fail('cancelled'); + } + + /** Surface an error to the relay when possible. */ + onError(code) { + this.fail(code); + } + + /** Fail the local request and release the stream. */ + fail(reason) { + if (this.closed) return; + this.closed = true; + try { + this.request?.destroy(); + } catch { + /* already gone */ + } + this.finish(); + } + + /** Remove this stream from the tunnel. */ + finish() { + this.closed = true; + this.tunnel.forget(this.id); + } +} + +/** + * One raw browser WebSocket relayed to the LAN listener. + */ +class WsAgentStream { + /** + * @param {RelayTunnel} tunnel owning tunnel. + * @param {any} frame open frame. + */ + constructor(tunnel, frame) { + this.tunnel = tunnel; + this.id = frame.id; + this.frame = frame; + this.socket = null; + this.closed = false; + this.acked = false; + this.unacked = 0; + this.paused = false; + this.buffer = Buffer.alloc(0); + } + + /** Connect to the local listener and replay the upgrade. */ + start() { + const transport = this.tunnel.localProtocol === 'https:' ? tls : net; + let socket; + try { + socket = this.tunnel.localProtocol === 'https:' + ? tls.connect({ host: this.tunnel.localHost, port: this.tunnel.localPort, rejectUnauthorized: false }) + : net.connect({ host: this.tunnel.localHost, port: this.tunnel.localPort }); + } catch (error) { + this.tunnel.send({ t: 'ws-close', id: this.id }); + this.finish(); + return; + } + this.socket = socket; + socket.setNoDelay(true); + + const event = this.tunnel.localProtocol === 'https:' ? 'secureConnect' : 'connect'; + socket.once(event, () => this.writeUpgrade()); + socket.on('error', () => this.closeUpstream(true)); + socket.on('close', () => this.closeUpstream(true)); + + this.onFirstData = (chunk) => { + this.buffer = Buffer.concat([this.buffer, chunk]); + const end = this.buffer.indexOf('\r\n\r\n'); + if (end === -1) { + if (this.buffer.length > 64 * 1024) this.closeUpstream(); + return; + } + socket.off('data', this.onFirstData); + const head = this.buffer; + const status = /^HTTP\/1\.[01] (\d{3})/.exec(head.subarray(0, end).toString('latin1')); + const code = status === null ? 502 : Number(status[1]); + this.tunnel.send({ t: 'ws-ack', id: this.id, status: code, head: head.toString('base64') }); + if (code !== 101) { + this.finish(); + return; + } + this.acked = true; + socket.on('data', (next) => this.onUpstreamData(next)); + }; + socket.on('data', this.onFirstData); + } + + /** Write the browser's upgrade request to the local listener. */ + writeUpgrade() { + const socket = this.socket; + if (socket === null || this.closed) return; + const headers = {}; + for (const [name, value] of Object.entries(this.frame.headers ?? {})) { + const lower = name.toLowerCase(); + if (HOP_BY_HOP.has(lower) || lower.startsWith('x-forwarded-') || lower === 'forwarded') continue; + if (value !== undefined) headers[lower] = value; + } + headers.host = this.tunnel.localAuthority; + headers.connection = 'Upgrade'; + headers.upgrade = 'websocket'; + let text = this.frame.method + ' ' + this.frame.url + ' HTTP/1.1\r\n'; + for (const [name, value] of Object.entries(headers)) { + if (Array.isArray(value)) { + for (const item of value) text += name + ': ' + item + '\r\n'; + } else { + text += name + ': ' + String(value) + '\r\n'; + } + } + text += '\r\n'; + socket.write(text); + if (typeof this.frame.head === 'string' && this.frame.head !== '') { + socket.write(Buffer.from(this.frame.head, 'base64')); + } + } + + /** Forward local upstream bytes to the relay with a window. */ + onUpstreamData(chunk) { + if (this.closed) return; + this.unacked += chunk.length; + this.tunnel.send({ t: 'ws-data', id: this.id, data: chunk.toString('base64') }); + if (this.unacked > this.tunnel.windowBytes && !this.paused) { + this.paused = true; + this.socket.pause(); + } + } + + /** Write browser bytes upstream and acknowledge after the socket accepts them. */ + onWsData(data) { + if (this.closed || !this.acked || this.socket === null) return; + const buffer = Buffer.from(data, 'base64'); + let accepted; + try { + accepted = this.socket.write(buffer); + } catch { + this.closeUpstream(); + return; + } + const ack = () => { + if (!this.closed) this.tunnel.send({ t: 'ack', id: this.id, bytes: buffer.length }); + }; + if (accepted) { + ack(); + return; + } + this.socket.once('drain', ack); + } + + /** The relay consumed upstream bytes; resume a paused socket. */ + onAck(bytes) { + if (!Number.isFinite(bytes) || bytes <= 0) return; + this.unacked = Math.max(0, this.unacked - bytes); + if (this.paused && this.socket !== null && this.unacked <= this.tunnel.lowWaterBytes) { + this.paused = false; + this.socket.resume(); + } + } + + /** The relay closed the browser side. */ + onWsClose() { + this.closeUpstream(false); + } + + /** The relay cancelled the stream. */ + cancel() { + this.closeUpstream(false); + } + + /** Surface a relay error. */ + onError() { + this.closeUpstream(false); + } + + /** The tunnel is gone; release the local socket without echoing. */ + fail() { + this.closeUpstream(false); + } + + /** + * Close the local upstream socket. + * @param {boolean} notify whether to tell the relay the browser side ended. + */ + closeUpstream(notify = true) { + if (this.closed) return; + this.closed = true; + if (notify) this.tunnel.send({ t: 'ws-close', id: this.id }); + if (this.socket !== null) { + try { + this.socket.destroy(); + } catch { + /* already gone */ + } + } + this.tunnel.forget(this.id); + } + + /** Local finish that also tells the relay. */ + finish() { + if (this.closed) return; + this.closed = true; + if (this.socket !== null) { + try { + this.socket.destroy(); + } catch { + /* already gone */ + } + } + this.tunnel.forget(this.id); + } +} \ No newline at end of file diff --git a/store.js b/store.js new file mode 100644 index 0000000..602576a --- /dev/null +++ b/store.js @@ -0,0 +1,364 @@ +/** + * Durable pairing state for LAN Share: devices that survived a restart and + * short-lived, single-use QR tickets. + * + * A device record stores only a SHA-256 digest of its cookie secret; the + * secret itself lives in the tablet's HttpOnly cookie and is never written to + * disk or logged. Tickets are memory-only by design: a QR code is a one-time + * grant, not a durable credential. + */ + +import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; +import { mkdir, open, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises'; +import { dirname } from 'node:path'; + +/** Current on-disk state format. */ +const STATE_VERSION = 1; + +/** How long an online device may go without a request before the list calls it idle. */ +export const ONLINE_WINDOW_MS = 30_000; + +/** Maximum number of simultaneously valid QR tickets. */ +const MAX_TICKETS = 8; + +/** + * SHA-256 of a secret, as lowercase hex. + * @param {string} secret cookie secret. + * @returns {string} digest. + */ +function digest(secret) { + return createHash('sha256').update(secret, 'utf8').digest('hex'); +} + +/** + * Compare two hex digests without leaking where they differ. + * @param {string} left first digest. + * @param {string} right second digest. + * @returns {boolean} true only for equal digests. + */ +function digestEquals(left, right) { + if (typeof left !== 'string' || typeof right !== 'string' || left.length !== right.length) return false; + const a = Buffer.from(left, 'hex'); + const b = Buffer.from(right, 'hex'); + return a.length === b.length && timingSafeEqual(a, b); +} + +/** + * Write a file atomically with owner-only permissions. + * @param {string} file destination. + * @param {string} text content. + */ +async function writeAtomic(file, text) { + await mkdir(dirname(file), { recursive: true, mode: 0o700 }); + const temporary = file + '.tmp-' + String(process.pid) + '-' + randomBytes(4).toString('hex'); + await writeFile(temporary, text, { mode: 0o600 }); + await rename(temporary, file); +} + +/** + * Serialize writes between two Harness processes that happen to share a home. + * @template T + * @param {string} file destination whose lock guards the write. + * @param {() => Promise} work write to perform. + * @returns {Promise} the write result. + */ +async function withFileLock(file, work) { + await mkdir(dirname(file), { recursive: true, mode: 0o700 }); + const lockFile = file + '.lock'; + for (let attempt = 0; attempt < 40; attempt++) { + let handle; + try { + handle = await open(lockFile, 'wx', 0o600); + } catch (error) { + if (error?.code !== 'EEXIST') throw error; + try { + const info = await stat(lockFile); + if (Date.now() - info.mtimeMs > 5_000) { + await unlink(lockFile).catch(() => {}); + continue; + } + } catch { + /* the holder removed it between our open and stat */ + } + await new Promise((resolveDelay) => setTimeout(resolveDelay, 25)); + continue; + } + try { + return await work(); + } finally { + await handle.close().catch(() => {}); + await unlink(lockFile).catch(() => {}); + } + } + return work(); +} + +/** + * One paired device. + * @typedef {{ id: string, secretHash: string, label: string, ip: string, sessionId: string | null, createdAt: number, lastSeenAt: number, expiresAt: number }} DeviceRecord + */ + +/** + * The durable device registry. + */ +export class DeviceStore { + /** + * @param {string} file absolute state-file path. + * @param {{ ttlMs: number, maxDevices: number, logger?: (level: string, message: unknown) => void }} options lifetime and capacity. + */ + constructor(file, options) { + this.file = file; + this.ttlMs = options.ttlMs; + this.maxDevices = options.maxDevices; + this.log = options.logger ?? (() => {}); + /** @type {Map} */ + this.records = new Map(); + this.flushTimer = null; + this.writeChain = Promise.resolve(); + this.loaded = false; + } + + /** Read the state file; a missing or unreadable file starts empty. */ + async load() { + let parsed; + try { + parsed = JSON.parse(await readFile(this.file, 'utf8')); + } catch (error) { + if (error?.code !== 'ENOENT') this.log('warn', error); + parsed = undefined; + } + if (parsed !== undefined && parsed !== null && typeof parsed === 'object' && Array.isArray(parsed.devices)) { + const now = Date.now(); + for (const raw of parsed.devices) { + if (raw === null || typeof raw === 'object' === false) continue; + if (typeof raw.id !== 'string' || typeof raw.secretHash !== 'string') continue; + if (typeof raw.expiresAt !== 'number' || raw.expiresAt <= now) continue; + this.records.set(raw.id, { + id: raw.id, + secretHash: raw.secretHash, + label: typeof raw.label === 'string' ? raw.label : 'Browser', + ip: typeof raw.ip === 'string' ? raw.ip : 'unknown', + sessionId: typeof raw.sessionId === 'string' ? raw.sessionId : null, + createdAt: typeof raw.createdAt === 'number' ? raw.createdAt : now, + lastSeenAt: typeof raw.lastSeenAt === 'number' ? raw.lastSeenAt : 0, + expiresAt: raw.expiresAt, + }); + } + } + this.loaded = true; + this.prune(); + } + + /** Drop expired records. */ + prune() { + const now = Date.now(); + for (const [id, record] of this.records) if (record.expiresAt <= now) this.records.delete(id); + } + + /** + * Register a paired device. + * @param {{ label: string, ip: string, sessionId: string | null }} facts pairing facts. + * @returns {Promise<{ record: DeviceRecord, cookie: string }>} the record and its cookie value. + */ + async add(facts) { + this.prune(); + if (this.records.size >= this.maxDevices) { + const error = new Error('lan-share: device limit reached'); + error.code = 'DEVICE_LIMIT'; + throw error; + } + const id = randomBytes(9).toString('base64url'); + const secret = randomBytes(32).toString('base64url'); + const now = Date.now(); + /** @type {DeviceRecord} */ + const record = { + id, + secretHash: digest(secret), + label: facts.label, + ip: facts.ip, + sessionId: facts.sessionId ?? null, + createdAt: now, + lastSeenAt: now, + expiresAt: now + this.ttlMs, + }; + this.records.set(id, record); + try { + await this.flush(); + } catch (error) { + this.records.delete(id); + throw error; + } + return { record, cookie: id + '.' + secret }; + } + + /** + * Validate a device cookie and record activity. + * @param {string | undefined} value cookie value \`.\`. + * @returns {DeviceRecord | undefined} the live record. + */ + verify(value) { + if (typeof value !== 'string') return undefined; + const dot = value.indexOf('.'); + if (dot <= 0 || dot === value.length - 1) return undefined; + const record = this.records.get(value.slice(0, dot)); + if (record === undefined) return undefined; + if (record.expiresAt <= Date.now()) { + this.records.delete(record.id); + this.scheduleFlush(); + return undefined; + } + if (!digestEquals(record.secretHash, digest(value.slice(dot + 1)))) return undefined; + record.lastSeenAt = Date.now(); + return record; + } + + /** + * Public view of every device, newest first. + * @returns {Array & { online: boolean }>} device list. + */ + list() { + this.prune(); + const now = Date.now(); + return [...this.records.values()] + .sort((left, right) => right.createdAt - left.createdAt) + .map(({ secretHash, ...rest }) => ({ + ...rest, + online: now - rest.lastSeenAt < ONLINE_WINDOW_MS, + })); + } + + /** + * Remember the Session this device last opened. + * @param {string} id device id. + * @param {string | null} sessionId Session id. + */ + setSession(id, sessionId) { + const record = this.records.get(id); + if (record === undefined) return; + record.sessionId = sessionId; + this.scheduleFlush(); + } + + /** + * Revoke one device. + * @param {string} id device id. + * @returns {Promise} whether a record was removed. + */ + async revoke(id) { + const removed = this.records.delete(id); + if (removed) await this.flush(); + return removed; + } + + /** + * Revoke every device. + * @returns {Promise} how many records were removed. + */ + async revokeAll() { + const count = this.records.size; + this.records.clear(); + if (count > 0) await this.flush(); + return count; + } + + /** Persist after a short quiet period, so navigation does not rewrite the file per keystroke. */ + scheduleFlush() { + if (this.flushTimer !== null) return; + this.flushTimer = setTimeout(() => { + this.flushTimer = null; + this.flush().catch((error) => this.log('warn', error)); + }, 1500); + if (typeof this.flushTimer.unref === 'function') this.flushTimer.unref(); + } + + /** Write the current registry atomically. */ + flush() { + const payload = JSON.stringify({ + version: STATE_VERSION, + devices: [...this.records.values()], + }, null, 2); + this.writeChain = this.writeChain + .catch(() => {}) + .then(() => withFileLock(this.file, () => writeAtomic(this.file, payload + '\n'))); + return this.writeChain; + } + + /** Stop the pending debounce and write once more. */ + async close() { + if (this.flushTimer !== null) { + clearTimeout(this.flushTimer); + this.flushTimer = null; + } + await this.flush(); + } +} + +/** + * Single-use QR tickets. A ticket grants exactly one device pairing and dies + * with the process; nothing durable ever contains its secret. + */ +export class TicketStore { + /** + * @param {{ ttlMs: number }} options ticket lifetime. + */ + constructor(options) { + this.ttlMs = options.ttlMs; + /** @type {Map} */ + this.tickets = new Map(); + } + + /** + * Mint one ticket. + * @param {string | null | undefined} sessionId Session the new device should open. + * @returns {{ token: string, sessionId: string | null, expiresAt: number, ticketId: string }} ticket facts. + */ + mint(sessionId) { + this.prune(); + while (this.tickets.size >= MAX_TICKETS) { + const oldest = this.tickets.keys().next().value; + if (oldest === undefined) break; + this.tickets.delete(oldest); + } + const token = randomBytes(32).toString('base64url'); + const now = Date.now(); + const expiresAt = now + this.ttlMs; + this.tickets.set(digest(token), { + token, + sessionId: sessionId ?? null, + createdAt: now, + expiresAt, + }); + return { token, sessionId: sessionId ?? null, expiresAt, ticketId: digest(token).slice(0, 12) }; + } + + /** + * Consume a ticket exactly once. + * @param {string} token ticket from the QR URL. + * @returns {{ sessionId: string | null } | undefined} the bound Session, or undefined when invalid, expired or already used. + */ + consume(token) { + if (typeof token !== 'string' || token.length < 16) return undefined; + const key = digest(token); + const ticket = this.tickets.get(key); + if (ticket === undefined) return undefined; + this.tickets.delete(key); + if (ticket.expiresAt <= Date.now()) return undefined; + return { sessionId: ticket.sessionId }; + } + + /** + * The tickets still valid, with their raw tokens, so a reconnected relay can + * be told about them again. Never persisted. + * @returns {Array<{ token: string, sessionId: string | null, expiresAt: number }>} active tickets. + */ + active() { + this.prune(); + return [...this.tickets.values()].map(({ token, sessionId, expiresAt }) => ({ token, sessionId, expiresAt })); + } + + /** Drop expired tickets. */ + prune() { + const now = Date.now(); + for (const [key, ticket] of this.tickets) if (ticket.expiresAt <= now) this.tickets.delete(key); + } +} \ No newline at end of file diff --git a/test/config.test.mjs b/test/config.test.mjs new file mode 100644 index 0000000..641b936 --- /dev/null +++ b/test/config.test.mjs @@ -0,0 +1,51 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { isPrivateLanAddress, normalizeConfig } from '../config.js'; + +const HOME = { DSH_HOME: '/tmp/lan-share-config-test' }; + +test('relay config is opt-in and validated', () => { + const defaults = normalizeConfig({}, HOME); + assert.equal(defaults.ticketTtlSeconds, 60); + assert.equal(isPrivateLanAddress('192.168.8.104'), true); + assert.equal(isPrivateLanAddress('10.1.2.3'), true); + assert.equal(isPrivateLanAddress('172.16.0.1'), true); + assert.equal(isPrivateLanAddress('100.75.242.32'), false, 'Tailscale CGNAT must not win'); + assert.equal(isPrivateLanAddress('8.8.8.8'), false); + assert.equal(defaults.relay.enabled, false); + assert.equal(defaults.relay.url, null); + + const enabled = normalizeConfig({ + relay: { + enabled: true, + url: 'wss://dsh.bildme.ru/tunnel', + token: 'secret-token', + publicOrigin: 'https://dsh.bildme.ru', + agentId: 'desk-1', + }, + }, HOME); + assert.equal(enabled.relay.enabled, true); + assert.equal(enabled.relay.url, 'wss://dsh.bildme.ru/tunnel'); + assert.equal(enabled.relay.publicOrigin, 'https://dsh.bildme.ru'); + assert.equal(enabled.relay.agentId, 'desk-1'); + + assert.throws(() => normalizeConfig({ relay: { enabled: true, token: 'x', url: 'https://x/tunnel' } }, HOME), /ws/); + assert.throws(() => normalizeConfig({ relay: { enabled: true, url: 'wss://x/tunnel' } }, HOME), /token/); + assert.throws(() => normalizeConfig({ relay: { enabled: true, url: 'wss://x/tunnel', token: 'x', publicOrigin: 'https://x/path' } }, HOME), /path/); + assert.throws(() => normalizeConfig({ relay: { enabled: true, url: 'wss://x/tunnel', token: 'x', agentId: 'bad id' } }, HOME), /agentId/); +}); + +test('relay config can come from the environment', () => { + const fromEnv = normalizeConfig({}, { + DSH_HOME: '/tmp/lan-share-config-test', + DSH_RELAY_ENABLED: '1', + DSH_RELAY_URL: 'wss://relay.example/tunnel', + DSH_RELAY_TOKEN: 'env-token', + DSH_RELAY_PUBLIC_ORIGIN: 'https://relay.example', + DSH_RELAY_AGENT_ID: 'env-agent', + }); + assert.equal(fromEnv.relay.enabled, true); + assert.equal(fromEnv.relay.token, 'env-token'); + assert.equal(fromEnv.relay.agentId, 'env-agent'); + assert.equal(fromEnv.relay.publicOrigin, 'https://relay.example'); +}); \ No newline at end of file diff --git a/test/proxy.test.mjs b/test/proxy.test.mjs new file mode 100644 index 0000000..f2cf0c6 --- /dev/null +++ b/test/proxy.test.mjs @@ -0,0 +1,468 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import net from 'node:net'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { normalizeConfig } from '../config.js'; +import { DeviceStore, TicketStore } from '../store.js'; +import { LanShareServer } from '../proxy.js'; + +/** + * A fake Desktop Host: it authenticates the launch token, demands its own + * cookie on every other request, and records what the proxy sent it. + */ +function createUpstream() { + const state = { + minted: 1, + required: 1, + requests: [], + upgrades: [], + sockets: new Set(), + body: 'UPSTREAM OK', + }; + + const server = http.createServer((req, res) => { + state.requests.push({ method: req.method, url: req.url, headers: req.headers }); + const url = new URL(req.url ?? '/', 'http://upstream.invalid'); + if (url.pathname === '/' && url.searchParams.has('token')) { + res.writeHead(303, { + location: './', + 'set-cookie': 'dsh-auth-test=v' + String(state.minted++) + '; Path=/; HttpOnly; Max-Age=3600; SameSite=Strict', + }); + res.end(); + return; + } + const cookie = req.headers.cookie ?? ''; + const offered = /dsh-auth-test=v(\d+)/.exec(cookie); + const authenticated = offered !== null && Number(offered[1]) >= state.required; + if (!authenticated) { + res.writeHead(401, { 'content-type': 'text/plain' }); + res.end('unauthorized'); + return; + } + if (url.pathname === '/') { + res.writeHead(200, { + 'content-type': 'text/html; charset=utf-8', + 'set-cookie': ['dsh-auth-test2=should-drop; Path=/', 'other=keep; Path=/'], + }); + res.end('

' + state.body + '

'); + return; + } + if (url.pathname === '/redirect') { + res.writeHead(302, { location: 'http://' + req.headers.host + '/target' }); + res.end(); + return; + } + if (url.pathname === '/sse') { + res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' }); + res.write('data: one\n\n'); + setTimeout(() => { + res.write('data: two\n\n'); + res.end(); + }, 30); + return; + } + if (url.pathname === '/echo') { + const chunks = []; + req.on('data', (chunk) => chunks.push(chunk)); + req.on('end', () => { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ body: Buffer.concat(chunks).toString('utf8'), host: req.headers.host, origin: req.headers.origin ?? null })); + }); + return; + } + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end('OK'); + }); + + server.on('upgrade', (req, socket) => { + state.upgrades.push(req.headers); + state.sockets.add(socket); + socket.on('close', () => state.sockets.delete(socket)); + socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n'); + socket.on('data', (chunk) => socket.write(chunk)); + }); + + return { server, state }; +} + +function listen(server) { + return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server.address().port))); +} + +function close(server) { + return new Promise((resolve) => { + for (const socket of server.state?.sockets ?? []) socket.destroy(); + server.closeAllConnections?.(); + server.close(() => resolve()); + }); +} + +async function startFixture() { + const upstream = createUpstream(); + const upstreamPort = await listen(upstream.server); + const upstreamOrigin = 'http://127.0.0.1:' + String(upstreamPort); + const dir = await mkdtemp(join(tmpdir(), 'lan-share-test-')); + const config = normalizeConfig({ + host: '127.0.0.1', + port: 0, + stateFile: join(dir, 'devices.json'), + ticketTtlSeconds: 60, + deviceTtlDays: 1, + maxDevices: 2, + }, { DSH_HOME: dir }); + const devices = new DeviceStore(config.stateFile, { ttlMs: config.deviceTtlMs, maxDevices: config.maxDevices }); + await devices.load(); + const tickets = new TicketStore({ ttlMs: config.ticketTtlMs }); + const server = new LanShareServer({ + config, + devices, + tickets, + upstream: { origin: upstreamOrigin, protocol: 'http:', host: '127.0.0.1', port: upstreamPort }, + authenticatedUrl: () => upstreamOrigin + '/?token=LAUNCH', + }); + await server.start(); + assert.equal(server.state.running, true, 'listener must start'); + return { upstream, upstreamPort, upstreamOrigin, server, devices, tickets, dir }; +} + +async function stopFixture(fixture) { + await fixture.server.stop(); + await fixture.devices.close(); + for (const socket of fixture.upstream.state.sockets) socket.destroy(); + await close(fixture.upstream.server); + await rm(fixture.dir, { recursive: true, force: true }); +} + +/** + * Pair one fake tablet. + * @param {string} origin listener origin. + * @param {ReturnType extends Promise ? T['server'] : never} server listener. + * @returns {Promise} the device cookie. + */ +async function waitForPending(server) { + for (let attempt = 0; attempt < 200; attempt += 1) { + const pending = server.state.pending[0]; + if (pending !== undefined) return pending; + await sleep(5); + } + throw new Error('the scanned ticket did not create a pending request'); +} + +async function pair(origin, server) { + const { url } = server.createTicket(null); + const tokenPath = new URL(url).pathname; + const responsePromise = fetch(origin + tokenPath, { redirect: 'manual', headers: { accept: 'text/html' } }); + const pending = await waitForPending(server); + const approved = await server.approvePending(pending.id); + assert.equal(approved.ok, true, 'the owner approval must create the device'); + const response = await responsePromise; + assert.equal(response.status, 303); + const cookies = response.headers.getSetCookie(); + assert.equal(cookies.length, 1); + assert.match(cookies[0], /^dsh-lan-device=/); + return cookies[0].split(';', 1)[0]; +} + +test('unauthenticated requests get the pairing page, not the app', async () => { + const fixture = await startFixture(); + try { + const origin = fixture.server.publicOrigin; + const page = await fetch(origin + '/', { headers: { accept: 'text/html' } }); + assert.equal(page.status, 401); + assert.match(await page.text(), /QR/); + const api = await fetch(origin + '/api/session/list', { headers: { accept: 'application/json' } }); + assert.equal(api.status, 401); + } finally { + await stopFixture(fixture); + } +}); + +test('one-time ticket pairs exactly one device', async () => { + const fixture = await startFixture(); + try { + const origin = fixture.server.publicOrigin; + const { url } = fixture.server.createTicket(null); + const path = new URL(url).pathname; + + const firstPromise = fetch(origin + path, { redirect: 'manual' }); + const pending = await waitForPending(fixture.server); + const approved = await fixture.server.approvePending(pending.id); + assert.equal(approved.ok, true); + const first = await firstPromise; + assert.equal(first.status, 303); + assert.equal(first.headers.get('location'), '/'); + const cookie = first.headers.getSetCookie()[0].split(';', 1)[0]; + + const second = await fetch(origin + path, { redirect: 'manual' }); + assert.equal(second.status, 410); + + const app = await fetch(origin + '/', { headers: { cookie } }); + assert.equal(app.status, 200); + assert.match(await app.text(), /UPSTREAM OK/); + assert.equal(fixture.devices.list().length, 1); + } finally { + await stopFixture(fixture); + } +}); + +test('a scanned ticket waits for the owner and can be denied', async () => { + const fixture = await startFixture(); + try { + const origin = fixture.server.publicOrigin; + const { url } = fixture.server.createTicket(null); + const responsePromise = fetch(origin + new URL(url).pathname, { + redirect: 'manual', + headers: { accept: 'text/html', 'user-agent': 'DenyTest/1.0' }, + }); + const pending = await waitForPending(fixture.server); + assert.equal(pending.label.length > 0, true, 'the pending request describes the device'); + assert.equal(pending.ip.length > 0, true, 'the pending request carries the peer address'); + assert.equal(pending.userAgent, 'DenyTest/1.0'); + assert.equal(fixture.server.state.pending.length, 1); + assert.equal(fixture.server.denyPending(pending.id), true); + const response = await responsePromise; + assert.equal(response.status, 403); + assert.equal(fixture.devices.list().length, 0, 'denial must not create a device'); + const reused = await fetch(origin + new URL(url).pathname, { redirect: 'manual' }); + assert.equal(reused.status, 410, 'the scanned ticket stays consumed'); + } finally { + await stopFixture(fixture); + } +}); + +test('upstream headers are rewritten and auth cookies are withheld', async () => { + const fixture = await startFixture(); + try { + const origin = fixture.server.publicOrigin; + const cookie = await pair(origin, fixture.server); + const response = await fetch(origin + '/', { headers: { cookie, origin: 'http://192.168.1.9:1234' } }); + assert.equal(response.status, 200); + const setCookies = response.headers.getSetCookie(); + assert.ok(setCookies.every((value) => !value.startsWith('dsh-auth-')), 'auth cookie must not reach the tablet'); + assert.ok(setCookies.some((value) => value.startsWith('other=keep')), 'other cookies pass through'); + + const upstream = fixture.upstream.state.requests.at(-1); + assert.equal(upstream.headers.host, '127.0.0.1:' + String(fixture.upstreamPort), 'Host names the upstream'); + assert.match(upstream.headers.cookie, /^dsh-auth-test=v\d+$/, 'upstream sees the minted cookie'); + assert.equal(upstream.headers.origin, undefined, 'Origin is removed for HTTP'); + } finally { + await stopFixture(fixture); + } +}); + +test('request bodies, redirects and SSE stream through', async () => { + const fixture = await startFixture(); + try { + const origin = fixture.server.publicOrigin; + const cookie = await pair(origin, fixture.server); + + const echo = await fetch(origin + '/echo', { + method: 'POST', + headers: { cookie, 'content-type': 'application/json' }, + body: JSON.stringify({ hello: 'world' }), + }); + assert.equal(echo.status, 200); + const payload = await echo.json(); + assert.deepEqual(JSON.parse(payload.body), { hello: 'world' }); + assert.equal(payload.host, '127.0.0.1:' + String(fixture.upstreamPort)); + + const redirect = await fetch(origin + '/redirect', { headers: { cookie }, redirect: 'manual' }); + assert.equal(redirect.status, 302); + assert.equal(redirect.headers.get('location'), origin + '/target'); + + const sse = await fetch(origin + '/sse', { headers: { cookie } }); + assert.equal(sse.status, 200); + assert.equal(await sse.text(), 'data: one\n\ndata: two\n\n'); + } finally { + await stopFixture(fixture); + } +}); + +test('bootstrap, session binding and self-removal', async () => { + const fixture = await startFixture(); + try { + const origin = fixture.server.publicOrigin; + const cookie = await pair(origin, fixture.server); + + const bootstrap = await fetch(origin + '/api/lan-share/bootstrap', { headers: { cookie } }); + assert.equal(bootstrap.status, 200); + const first = await bootstrap.json(); + assert.equal(first.remote, true); + assert.equal(first.sessionId, null); + + const update = await fetch(origin + '/api/lan-share/session', { + method: 'POST', + headers: { cookie, 'content-type': 'application/json' }, + body: JSON.stringify({ sessionId: 'session-123' }), + }); + assert.equal(update.status, 200); + + const again = await (await fetch(origin + '/api/lan-share/bootstrap', { headers: { cookie } })).json(); + assert.equal(again.sessionId, 'session-123'); + + const forbidden = await fetch(origin + '/api/lan-share/ticket', { method: 'POST', headers: { cookie } }); + assert.equal(forbidden.status, 403); + + const forget = await fetch(origin + '/api/lan-share/forget-self', { method: 'POST', headers: { cookie } }); + assert.equal(forget.status, 200); + const after = await fetch(origin + '/', { headers: { cookie } }); + assert.equal(after.status, 401); + } finally { + await stopFixture(fixture); + } +}); + +test('revoking a device closes its WebSocket and refuses HTTP', async () => { + const fixture = await startFixture(); + try { + const origin = fixture.server.publicOrigin; + const cookie = await pair(origin, fixture.server); + const port = fixture.server.port; + + const socket = net.connect(port, '127.0.0.1'); + const response = await new Promise((resolve, reject) => { + let buffer = ''; + const onData = (chunk) => { + buffer += chunk.toString('latin1'); + if (buffer.includes('\r\n\r\n')) { + socket.off('data', onData); + resolve(buffer); + } + }; + socket.on('data', onData); + socket.on('error', reject); + socket.write('GET /api/remote.mux HTTP/1.1\r\nHost: ' + new URL(origin).host + '\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\nCookie: ' + cookie + '\r\n\r\n'); + }); + assert.match(response, /^HTTP\/1\.1 101/); + const upgrade = fixture.upstream.state.upgrades.at(-1); + assert.equal(upgrade.cookie.includes('dsh-auth-test='), true); + assert.equal(upgrade.origin, fixture.upstreamOrigin); + assert.equal(upgrade.upgrade, 'websocket'); + assert.equal(upgrade.connection, 'Upgrade'); + + await fixture.server.revoke({ all: true }); + await new Promise((resolve) => setTimeout(resolve, 60)); + assert.equal(socket.destroyed, true, 'revocation closes the live socket'); + const httpAfter = await fetch(origin + '/', { headers: { cookie } }); + assert.equal(httpAfter.status, 401); + } finally { + await stopFixture(fixture); + } +}); + +test('a stale upstream cookie is re-minted once and the GET retried', async () => { + const fixture = await startFixture(); + try { + const origin = fixture.server.publicOrigin; + const cookie = await pair(origin, fixture.server); + /* The cookie minted during pairing is v1; from now on only v2+ is + * accepted, so the first GET is refused and the proxy must re-mint. */ + fixture.upstream.state.required = 2; + const before = fixture.upstream.state.minted; + const response = await fetch(origin + '/', { headers: { cookie } }); + assert.equal(response.status, 200, 'the retry succeeds with a fresh cookie'); + assert.ok(fixture.upstream.state.minted > before, 'a new cookie was minted'); + assert.ok(fixture.upstream.state.requests.filter((request) => request.url === '/').length >= 2, 'the GET was attempted twice'); + } finally { + await stopFixture(fixture); + } +}); + +test('the device limit is enforced when the owner approves', async () => { + const fixture = await startFixture(); + try { + const origin = fixture.server.publicOrigin; + await pair(origin, fixture.server); + await pair(origin, fixture.server); + const { url } = fixture.server.createTicket(null); + const responsePromise = fetch(origin + new URL(url).pathname, { redirect: 'manual' }); + const pending = await waitForPending(fixture.server); + const approved = await fixture.server.approvePending(pending.id); + assert.equal(approved.ok, false); + assert.equal(approved.code, 'DEVICE_LIMIT'); + assert.equal(fixture.server.denyPending(pending.id), true); + const response = await responsePromise; + assert.equal(response.status, 403); + assert.equal(fixture.devices.list().length, 2); + } finally { + await stopFixture(fixture); + } +}); + +test('expired devices and tickets are refused', async () => { + const dir = await mkdtemp(join(tmpdir(), 'lan-share-expiry-')); + try { + const devices = new DeviceStore(join(dir, 'devices.json'), { ttlMs: 40, maxDevices: 2 }); + await devices.load(); + const added = await devices.add({ label: 'iPad', ip: '127.0.0.1', sessionId: 's1' }); + assert.ok(devices.verify(added.cookie) !== undefined); + await new Promise((resolve) => setTimeout(resolve, 60)); + assert.equal(devices.verify(added.cookie), undefined, 'expired device cookie'); + + const tickets = new TicketStore({ ttlMs: 30 }); + const { token } = tickets.mint('s1'); + await new Promise((resolve) => setTimeout(resolve, 50)); + assert.equal(tickets.consume(token), undefined, 'expired ticket'); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test('the device registry survives a reload', async () => { + const dir = await mkdtemp(join(tmpdir(), 'lan-share-reload-')); + try { + const file = join(dir, 'devices.json'); + const first = new DeviceStore(file, { ttlMs: 60_000, maxDevices: 4 }); + await first.load(); + const added = await first.add({ label: 'iPad', ip: '192.168.1.9', sessionId: 's-9' }); + await first.close(); + const second = new DeviceStore(file, { ttlMs: 60_000, maxDevices: 4 }); + await second.load(); + const record = second.verify(added.cookie); + assert.ok(record !== undefined); + assert.equal(record.label, 'iPad'); + assert.equal(record.sessionId, 's-9'); + assert.equal(second.list().length, 1); + await second.revokeAll(); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test('a busy port falls back to an OS-assigned port', async () => { + const blocker = http.createServer(); + const blockedPort = await listen(blocker); + const upstream = createUpstream(); + const upstreamPort = await listen(upstream.server); + const dir = await mkdtemp(join(tmpdir(), 'lan-share-port-')); + const config = normalizeConfig({ + host: '127.0.0.1', + port: blockedPort, + stateFile: join(dir, 'devices.json'), + }, { DSH_HOME: dir }); + const devices = new DeviceStore(config.stateFile, { ttlMs: config.deviceTtlMs, maxDevices: 2 }); + await devices.load(); + const server = new LanShareServer({ + config, + devices, + tickets: new TicketStore({ ttlMs: 60_000 }), + upstream: { origin: 'http://127.0.0.1:' + String(upstreamPort), protocol: 'http:', host: '127.0.0.1', port: upstreamPort }, + authenticatedUrl: () => 'http://127.0.0.1:' + String(upstreamPort) + '/?token=L', + }); + try { + await server.start(); + assert.equal(server.state.running, true); + assert.equal(server.state.fallbackPort, true); + assert.notEqual(server.port, blockedPort); + } finally { + await server.stop(); + await devices.close(); + await close(blocker); + await close(upstream.server); + await rm(dir, { recursive: true, force: true }); + } +}); \ No newline at end of file diff --git a/test/qr.test.mjs b/test/qr.test.mjs new file mode 100644 index 0000000..fad909c --- /dev/null +++ b/test/qr.test.mjs @@ -0,0 +1,297 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { encodeQr, qrInternals } from '../qr.js'; + +/** + * Independent reader used to check the encoder: the test rebuilds the + * function-module map from the specification, reverses the mask, deinterleaves + * the codewords, checks every Reed-Solomon block, and parses the byte-mode + * payload back. + */ + +const ALIGNMENT = { + 1: [], 2: [6, 18], 3: [6, 22], 4: [6, 26], 5: [6, 30], + 6: [6, 34], 7: [6, 22, 38], 8: [6, 24, 42], 9: [6, 26, 46], 10: [6, 28, 50], +}; + +const BLOCKS = { + 1: { ecc: 10, groups: [[1, 16]] }, + 2: { ecc: 16, groups: [[1, 28]] }, + 3: { ecc: 26, groups: [[1, 44]] }, + 4: { ecc: 18, groups: [[2, 32]] }, + 5: { ecc: 24, groups: [[2, 43]] }, + 6: { ecc: 16, groups: [[4, 27]] }, + 7: { ecc: 18, groups: [[4, 31]] }, + 8: { ecc: 22, groups: [[2, 38], [2, 39]] }, + 9: { ecc: 22, groups: [[3, 36], [2, 37]] }, + 10: { ecc: 26, groups: [[4, 43], [1, 44]] }, +}; + +const GF_EXP = new Uint8Array(512); +const GF_LOG = new Uint8Array(256); +{ + let value = 1; + for (let i = 0; i < 255; i++) { + GF_EXP[i] = value; + GF_LOG[value] = i; + value <<= 1; + if (value & 0x100) value ^= 0x11d; + } + for (let i = 255; i < 512; i++) GF_EXP[i] = GF_EXP[i - 255]; +} + +function multiply(a, b) { + return a === 0 || b === 0 ? 0 : GF_EXP[GF_LOG[a] + GF_LOG[b]]; +} + +function functionMap(version) { + const size = version * 4 + 17; + const map = Array.from({ length: size }, () => new Array(size).fill(false)); + const mark = (row, col) => { + if (row >= 0 && row < size && col >= 0 && col < size) map[row][col] = true; + }; + for (const [centreRow, centreCol] of [[3, 3], [3, size - 4], [size - 4, 3]]) { + for (let dr = -4; dr <= 4; dr++) for (let dc = -4; dc <= 4; dc++) mark(centreRow + dr, centreCol + dc); + } + for (let i = 0; i < size; i++) { + mark(6, i); + mark(i, 6); + } + for (const row of ALIGNMENT[version]) { + for (const col of ALIGNMENT[version]) { + if ((row === 6 && col === 6) || (row === 6 && col === size - 7) || (row === size - 7 && col === 6)) continue; + for (let dr = -2; dr <= 2; dr++) for (let dc = -2; dc <= 2; dc++) mark(row + dr, col + dc); + } + } + for (let i = 0; i <= 8; i++) { + if (i !== 6) { + mark(8, i); + mark(i, 8); + } + } + for (let i = 0; i < 8; i++) mark(8, size - 1 - i); + for (let i = 8; i < 15; i++) mark(size - 15 + i, 8); + mark(size - 8, 8); + if (version >= 7) { + for (let i = 0; i < 18; i++) { + const a = size - 11 + (i % 3); + const b = Math.floor(i / 3); + mark(b, a); + mark(a, b); + } + } + return map; +} + +function maskBit(mask, row, col) { + switch (mask) { + case 0: return (row + col) % 2 === 0; + case 1: return row % 2 === 0; + case 2: return col % 3 === 0; + case 3: return (row + col) % 3 === 0; + case 4: return (Math.floor(row / 2) + Math.floor(col / 3)) % 2 === 0; + case 5: return ((row * col) % 2) + ((row * col) % 3) === 0; + case 6: return (((row * col) % 2) + ((row * col) % 3)) % 2 === 0; + case 7: return (((row + col) % 2) + ((row * col) % 3)) % 2 === 0; + default: throw new Error('bad mask'); + } +} + +function readDataBits(rows, version, mask) { + const size = rows.length; + const map = functionMap(version); + const bits = []; + for (let right = size - 1; right >= 1; right -= 2) { + if (right === 6) right = 5; + for (let vertical = 0; vertical < size; vertical++) { + for (let j = 0; j < 2; j++) { + const col = right - j; + const upward = ((right + 1) & 2) === 0; + const row = upward ? size - 1 - vertical : vertical; + if (map[row][col]) continue; + const dark = rows[row][col] === '1'; + bits.push(dark !== maskBit(mask, row, col)); + } + } + } + return bits; +} + +function bitsToCodewords(bits) { + const out = []; + for (let i = 0; i + 8 <= bits.length; i += 8) { + let value = 0; + for (let j = 0; j < 8; j++) value = (value << 1) | (bits[i + j] ? 1 : 0); + out.push(value); + } + return out; +} + +function deinterleave(codewords, version) { + const spec = BLOCKS[version]; + const counts = spec.groups.flatMap(([count, length]) => new Array(count).fill(length)); + const total = counts.reduce((a, b) => a + b, 0); + const data = counts.map((length) => new Uint8Array(length)); + let at = 0; + const maxLength = Math.max(...counts); + for (let i = 0; i < maxLength; i++) { + for (let b = 0; b < counts.length; b++) { + if (i < counts[b]) data[b][i] = codewords[at++]; + } + } + const ecc = counts.map(() => new Uint8Array(spec.ecc)); + for (let i = 0; i < spec.ecc; i++) { + for (let b = 0; b < counts.length; b++) ecc[b][i] = codewords[at++]; + } + assert.equal(at, total + counts.length * spec.ecc); + return { data, ecc, total }; +} + +function checkSyndromes(data, ecc) { + const polynomial = Uint8Array.from([...data, ...ecc]); + for (let i = 0; i < ecc.length; i++) { + let value = 0; + for (const coefficient of polynomial) value = multiply(value, GF_EXP[i]) ^ coefficient; + assert.equal(value, 0, 'Reed-Solomon syndrome must vanish at root ' + String(i)); + } +} + +function parsePayload(data, version) { + let bitIndex = 0; + const read = (length) => { + let value = 0; + for (let i = 0; i < length; i++) value = (value << 1) | ((data[(bitIndex + i) >>> 3] >>> (7 - ((bitIndex + i) & 7))) & 1); + bitIndex += length; + return value; + }; + const mode = read(4); + assert.equal(mode, 0b0100, 'byte mode indicator'); + const count = read(version <= 9 ? 8 : 16); + const bytes = new Uint8Array(count); + for (let i = 0; i < count; i++) bytes[i] = read(8); + return bytes; +} + +function bchRemainder(value, polynomial, degree) { + for (let i = 14; i >= degree; i--) if ((value >>> i) & 1) value ^= polynomial << (i - degree); + return value; +} + +function readFormat(rows) { + const size = rows.length; + let bits = 0; + const push = (row, col) => { bits = (bits << 1) | (rows[row][col] === '1' ? 1 : 0); }; + for (let i = 14; i >= 0; i--) { + if (i <= 5) push(i, 8); + else if (i === 6) push(7, 8); + else if (i === 7) push(8, 8); + else if (i === 8) push(8, 7); + else push(8, 14 - i); + } + return bits; +} + +/** + * Decode one generated matrix and return its payload and version/mask facts. + * @param {{ version: number, size: number, mask: number, rows: string[] }} qr generated symbol. + */ +function decode(qr) { + const format = readFormat(qr.rows) ^ 0x5412; + assert.equal(bchRemainder(format, 0x537, 10), 0, 'format BCH'); + assert.equal((format >>> 13) & 0b11, 0, 'ECC level M'); + assert.equal((format >>> 10) & 0b111, qr.mask, 'format mask agrees with the encoder'); + assert.equal(qr.rows[qr.size - 8][8], '1', 'dark module'); + + const bits = readDataBits(qr.rows, qr.version, qr.mask); + const codewords = bitsToCodewords(bits); + const blocks = deinterleave(codewords, qr.version); + for (let b = 0; b < blocks.data.length; b++) checkSyndromes(blocks.data[b], blocks.ecc[b]); + const joined = Uint8Array.from(blocks.data.flatMap((block) => Array.from(block))); + const payload = parsePayload(joined, qr.version); + return { payload, codewords, blocks }; +} + +function fingerprint(rows) { + return createHash('sha256').update(rows.join('\n')).digest('hex'); +} + +test('byte-mode round trip across every supported version', () => { + const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/:'; + const lengths = [1, 5, 14, 15, 26, 27, 42, 43, 62, 63, 84, 85, 106, 107, 122, 123, 152, 153, 180, 181, 213]; + for (const length of lengths) { + let text = ''; + for (let i = 0; i < length; i++) text += alphabet[(i * 7 + length) % alphabet.length]; + for (const mask of [0, 1, 2, 3, 4, 5, 6, 7]) { + const qr = encodeQr(text, { mask }); + const decoded = decode(qr); + assert.deepEqual(Buffer.from(decoded.payload), Buffer.from(text, 'utf8'), 'payload length ' + String(length) + ' mask ' + String(mask)); + } + } +}); + +test('multi-block versions carry every payload byte', () => { + for (const version of [4, 5, 6, 7, 8, 9, 10]) { + const capacity = qrInternals.payloadCapacityBytes(version); + const prefix = 'v' + String(version) + '-'; + const text = prefix + 'b'.repeat(capacity - prefix.length); + const qr = encodeQr(text); + assert.equal(qr.version, version); + assert.deepEqual(Buffer.from(decode(qr).payload), Buffer.from(text)); + } +}); + +test('automatic mask selection returns one of the eight masks', () => { + const qr = encodeQr('http://192.168.1.5:47820/s/' + 'a'.repeat(43)); + assert.ok(qr.mask >= 0 && qr.mask <= 7); + assert.equal(qr.rows.length, qr.size); + assert.equal(qr.rows[0].length, qr.size); +}); + +test('finder, timing and alignment structure', () => { + const qr = encodeQr('structure-check'); + const { size, rows } = qr; + for (const [row, col] of [[0, 0], [0, size - 7], [size - 7, 0]]) { + for (let dr = 0; dr < 7; dr++) { + for (let dc = 0; dc < 7; dc++) { + const distance = Math.max(Math.abs(dr - 3), Math.abs(dc - 3)); + const expected = distance === 0 || distance === 1 || distance === 3 ? '1' : '0'; + assert.equal(rows[row + dr][col + dc], expected, 'finder at ' + String(row) + ',' + String(col)); + } + } + const separatorRow = row === 0 ? 7 : row - 1; + const separatorCol = col === 0 ? 7 : col - 1; + for (let i = -1; i < 8; i++) { + if (separatorRow >= 0 && separatorRow < size) { + const c = col + i; + if (c >= 0 && c < size) assert.equal(rows[separatorRow][c], '0', 'separator'); + } + if (separatorCol >= 0 && separatorCol < size) { + const r = row + i; + if (r >= 0 && r < size) assert.equal(rows[r][separatorCol], '0', 'separator'); + } + } + } + for (let i = 8; i <= size - 9; i++) { + assert.equal(rows[6][i], i % 2 === 0 ? '1' : '0', 'timing row alternates'); + assert.equal(rows[i][6], i % 2 === 0 ? '1' : '0', 'timing column alternates'); + } +}); + +test('version capacity boundaries', () => { + assert.equal(qrInternals.payloadCapacityBytes(1), 14); + assert.equal(qrInternals.payloadCapacityBytes(5), 84); + assert.equal(qrInternals.payloadCapacityBytes(10), 213); + assert.throws(() => encodeQr('x'.repeat(214)), RangeError); + assert.throws(() => encodeQr('x', { minVersion: 11 }), RangeError); + assert.throws(() => encodeQr('x'.repeat(30), { maxVersion: 1 }), RangeError); + assert.equal(encodeQr('x', { minVersion: 7 }).version, 7); +}); + +test('stable output fingerprints', () => { + assert.equal(fingerprint(encodeQr('HELLO', { mask: 0 }).rows), 'b664c5ebcc2451fb6630e63f516abd72b3cdfbf16b9ceb0d92d226f6a6d0cde0'); + assert.equal( + fingerprint(encodeQr('http://192.168.1.5:47820/s/' + 'a'.repeat(43), { mask: 0 }).rows), + '76ea5091dacf7a9656cd6f6649d358de9bcd90329de3d1032a3ca13e387df5e0', + ); +}); \ No newline at end of file