dsh-lan-share 0.2.0: LAN/relay sharing with QR pairing
This commit is contained in:
16 files changed
+5940
No files matched your search
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
.DS_Store
|
||||
*.log
|
||||
test/.e2e-pending/
|
||||
@@ -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: <AGENT_TOKEN from the relay .env>
|
||||
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/<ticket>. 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:<host port>
|
||||
│ 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.
|
||||
@@ -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<string | undefined>} 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;
|
||||
}
|
||||
@@ -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'
|
||||
@@ -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<typeof normalizeConfig>} 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<typeof normalizeConfig>} 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);
|
||||
}
|
||||
@@ -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…"
|
||||
}
|
||||
@@ -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": "Загрузка…"
|
||||
}
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
@@ -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<string, string | string[]>} 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<number, any>} */
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<T>} work write to perform.
|
||||
* @returns {Promise<T>} 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<string, DeviceRecord>} */
|
||||
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 \`<id>.<secret>\`.
|
||||
* @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<Omit<DeviceRecord, 'secretHash'> & { 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<boolean>} 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<number>} 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<string, { token: string, sessionId: string | null, createdAt: number, expiresAt: number }>} */
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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('<h1>' + state.body + '</h1>');
|
||||
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<typeof startFixture> extends Promise<infer T> ? T['server'] : never} server listener.
|
||||
* @returns {Promise<string>} 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 });
|
||||
}
|
||||
});
|
||||
@@ -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',
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user