From 8c648dcac20aa49fb4d5d93cf4abb7d4c9076ec9 Mon Sep 17 00:00:00 2001 From: Aliaksei Smirnou Date: Thu, 19 Nov 2026 08:34:01 +0100 Subject: [PATCH 1/9] chore: switch to TypeScript on Node 22.18+ and drop the 1.x sources Version 2 is a rewrite with a new wire protocol, so the 1.x files go away. Node.js 22.18+ runs the TypeScript sources directly; tsc only type-checks. - chalk is replaced by util.styleText (respects NO_COLOR and non-TTY output) - clipboardy 4 -> 5.3.2: native Wayland support (wl-clipboard) - bonjour-service for mDNS discovery; typescript 7 and @types/node 22 for checks - package-lock.json had a stale "ISC" license; regenerated Co-Authored-By: Claude Opus 5.5 --- client.js | 66 --- config.js | 6 - encryption.js | 55 --- fragmenter.js | 98 ----- messageHandler.js | 41 -- monitorClipboard.js | 58 --- package-lock.json | 973 ++++++++++++++++++++++++++++++++++++++++---- package.json | 42 +- passphrase.js | 49 --- sendUpdate.js | 19 - server.js | 75 ---- src/config.ts | 56 +++ src/log.ts | 42 ++ src/version.ts | 5 + tsconfig.json | 23 ++ 15 files changed, 1065 insertions(+), 543 deletions(-) delete mode 100644 client.js delete mode 100644 config.js delete mode 100644 encryption.js delete mode 100644 fragmenter.js delete mode 100644 messageHandler.js delete mode 100644 monitorClipboard.js delete mode 100644 passphrase.js delete mode 100644 sendUpdate.js delete mode 100644 server.js create mode 100644 src/config.ts create mode 100644 src/log.ts create mode 100644 src/version.ts create mode 100644 tsconfig.json diff --git a/client.js b/client.js deleted file mode 100644 index b3aefb6..0000000 --- a/client.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @fileoverview Entry point for the client-side of the Netpaste application. - * - * @name client.js - * @author Aliaksei Smirnou - */ - -import net from 'net'; -import { encrypt } from './encryption.js'; -import { getPassphrase } from './passphrase.js'; -import { monitorClipboard } from './monitorClipboard.js'; -import { handleMessage } from './messageHandler.js'; -import { sendUpdate } from './sendUpdate.js'; -import { DEFAULT_PORT } from './config.js'; -import MessageAssembler from './fragmenter.js'; -const messageAssembler = new MessageAssembler(); - -let passphrase = ''; -let client; - -function createConnection(hostname, port, disableClipboard = false) { - client = net.createConnection({ host: hostname, port: port }, () => { - console.log('Connected to server!'); - const message = 'NETPASTE_HELLO:Netpaste client v1.0'; - const encryptedMessage = encrypt(message, passphrase); - client.write(encryptedMessage); - if (!disableClipboard) { - monitorClipboard(sendUpdate.bind(null, client), passphrase).catch(console.error); - } - }); - - client.on('data', (data) => { - messageAssembler.addData(data, (completeMessage) => { - handleMessage(completeMessage, passphrase, disableClipboard); - }); -}); - - client.on('end', () => { - console.log('Disconnected from server'); - setTimeout(createConnection, 5000); - }); - - client.on('error', (err) => { - console.error(err); - console.log('Attempting to reconnect...'); - setTimeout(createConnection, 5000); - }); -} - -function parseCommandLineArgs() { - const args = process.argv.slice(2); - const hostname = args[0]; - const disableClipboard = args.includes('--no-clipboard'); - const port = parseInt(args[1], 10) || DEFAULT_PORT; - if (!hostname || isNaN(port) || port < 0 || port > 65535) { - console.error('Invalid command-line arguments. Usage: node client.js [port]'); - process.exit(1); - } - return { hostname, port, disableClipboard }; -} - -getPassphrase((input) => { - passphrase = input; - const { hostname, port, disableClipboard } = parseCommandLineArgs(); - createConnection(hostname, port, disableClipboard); -}); diff --git a/config.js b/config.js deleted file mode 100644 index da0cf85..0000000 --- a/config.js +++ /dev/null @@ -1,6 +0,0 @@ -/** - * @name config.js - */ - -export const DEFAULT_PORT = 8134; -export const MAX_FRAGMENT_SIZE = 1024; \ No newline at end of file diff --git a/encryption.js b/encryption.js deleted file mode 100644 index 1f036b7..0000000 --- a/encryption.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @fileoverview This module provides encryption and decryption functions for the Netpaste application. - * - * @name encryption.js - * @author Aliaksei Smirnou - */ - -import crypto from 'crypto'; - -// Cryptographic configuration -const config = { - algorithm: 'aes-256-ctr', - messageFlag: 'NETPASTE_FLAG', - saltLength: 16, - ivLength: 16, - keyLength: 32, - hashFunction: 'sha512', - iterations: 10000 -}; - -function encrypt(text, passphrase) { - const salt = crypto.randomBytes(config.saltLength); - const iv = crypto.randomBytes(config.ivLength); - const key = crypto.pbkdf2Sync(passphrase, salt, config.iterations, config.keyLength, config.hashFunction); - const cipher = crypto.createCipheriv(config.algorithm, key, iv); - const textWithFlag = `${config.messageFlag}:${text}`; - const encrypted = Buffer.concat([cipher.update(textWithFlag, 'utf8'), cipher.final()]); - return `${salt.toString('hex')}:${iv.toString('hex')}:${encrypted.toString('hex')}`; -} - -function decrypt(data, passphrase) { - const [saltHex, ivHex, encryptedHex] = data.split(':'); - - // verify length of salt and iv, if not x2 from config throw error - if (saltHex.length !== config.saltLength * 2 || ivHex.length !== config.ivLength * 2) { - throw new Error('Integrity check failed. Data corrupted.'); - } - - const salt = Buffer.from(saltHex, 'hex'); - const iv = Buffer.from(ivHex, 'hex'); - const key = crypto.pbkdf2Sync(passphrase, salt, config.iterations, config.keyLength, config.hashFunction); - const decipher = crypto.createDecipheriv(config.algorithm, key, iv); - const decrypted = Buffer.concat([decipher.update(Buffer.from(encryptedHex, 'hex')), decipher.final()]); - return verifyMessage(decrypted.toString()); -} - -function verifyMessage(data) { - if (!data.startsWith(config.messageFlag)) { - throw new Error('Integrity check failed. Verify your passphrase.'); - } - // Remove the flag from the decrypted text - return data.substring(config.messageFlag.length + 1); -} - -export { encrypt, decrypt }; \ No newline at end of file diff --git a/fragmenter.js b/fragmenter.js deleted file mode 100644 index 319ba41..0000000 --- a/fragmenter.js +++ /dev/null @@ -1,98 +0,0 @@ -// fragmenter.js - -import { MAX_FRAGMENT_SIZE } from './config.js'; - -export function fragmentAndSendMessage(message, client) { - const messageBuffer = Buffer.from(message); - const totalParts = Math.ceil(messageBuffer.length / MAX_FRAGMENT_SIZE); - const uid = Date.now(); - const magicNumber = Buffer.from([0x4E, 0x65, 0x74, 0x50]); // 'NetP' in hex - - for (let part = 0; part < totalParts; part++) { - const start = part * MAX_FRAGMENT_SIZE; - const end = start + MAX_FRAGMENT_SIZE; - const fragment = messageBuffer.slice(start, end); - - const header = Buffer.alloc(20); // Adjust based on UID size - header.writeBigInt64BE(BigInt(uid), 0); // UID - header.writeUInt8(part + 1, 8); // Part number - header.writeUInt8(totalParts, 9); // Total parts - - const packet = Buffer.concat([magicNumber, header, fragment]); - client.write(packet); - } -} - -class MessageAssembler { - constructor() { - this.messages = {}; - this.magicNumber = Buffer.from([0x4E, 0x65, 0x74, 0x50]); // 'NetP' - } - - addData(data, callback) { - let start = 0; - let nextMagicNumberIndex = data.indexOf(this.magicNumber, start); - - while (nextMagicNumberIndex !== -1) { - // Move past the magic number for the start of the actual data - const fragmentStart = nextMagicNumberIndex + this.magicNumber.length; - - // Find the next occurrence of the magic number - const nextStart = data.indexOf(this.magicNumber, fragmentStart); - - let fragment; - if (nextStart === -1) { - // If there's no other magic number, slice from the current start to the end of data - fragment = data.slice(fragmentStart); - } else { - // Slice the data from the current start to the next magic number - fragment = data.slice(fragmentStart, nextStart); - } - - // Now that the fragment is correctly sliced (without the magic number), process it - this.addFragment(fragment, callback); - - if (nextStart === -1) { - break; // Exit if there are no more fragments - } else { - // Prepare to search for the next fragment - nextMagicNumberIndex = nextStart; - } - } - } - addFragment(data, callback) { - // Extract the header info - const uid = data.readBigInt64BE(0); - const part = data.readUInt8(8); - const totalParts = data.readUInt8(9); - const fragment = data.slice(20); // Assuming the header is 20 bytes - - // If this is the first fragment received for a message, initialize storage - if (!this.messages[uid]) { - this.messages[uid] = { parts: new Array(totalParts), received: 0 }; - } - - // Store the fragment - if (!this.messages[uid].parts[part - 1]) { // Prevent overriding in case of duplicate fragments - this.messages[uid].parts[part - 1] = fragment; - this.messages[uid].received++; - - // Check if all parts have been received - if (this.messages[uid].received === totalParts) { - // Sort the parts - const completeMessage = Buffer.concat(this.messages[uid].parts); - delete this.messages[uid]; // Remove stored parts to free memory - - // Invoke the callback with the complete message - if (typeof callback === 'function') { - callback(completeMessage); - } - } - } - - // Return null if the message is not yet fully assembled - return null; - } -} - -export default MessageAssembler; diff --git a/messageHandler.js b/messageHandler.js deleted file mode 100644 index dca60a8..0000000 --- a/messageHandler.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @fileoverview Decrypts and handles messages received from the server. - * - * @name messageHandler.js - * @author Aliaksei Smirnou - */ - -import { decrypt } from './encryption.js'; -import chalk from 'chalk'; -import clipboardy from 'clipboardy'; -import { setClipboardUpdateSource } from './monitorClipboard.js'; - -function logReceived(content) { - const currentTime = new Date().toLocaleTimeString(); - process.stdout.write(`${chalk.gray(`[${currentTime}]`)} ${chalk.blue('Received content: ')}${chalk.green(content.length.toString())} characters.\n`); -} - -export function handleMessage(data, passphrase, disableClipboard = false) { - try { - const decryptedMessage = decrypt(data.toString(), passphrase); - if (decryptedMessage.startsWith('NETPASTE_HELLO:')) { - const clientMessage = decryptedMessage.replace('NETPASTE_HELLO:', '').trim(); - console.log(`Peer message: ${clientMessage}`); - } else if (decryptedMessage.startsWith('NETPASTE_UPDATE:')) { - const updateMessage = decryptedMessage.replace('NETPASTE_UPDATE:', '').trim(); - logReceived(updateMessage) - if (!disableClipboard) { - setClipboardUpdateSource(true); - clipboardy.writeSync(updateMessage); - - setTimeout(() => { - setClipboardUpdateSource(false); - }, 2000); - } - } else { - console.log('Decrypted:', decryptedMessage); - } - } catch (error) { - console.error('Decryption error', error); - } -} diff --git a/monitorClipboard.js b/monitorClipboard.js deleted file mode 100644 index 93211e7..0000000 --- a/monitorClipboard.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @fileoverview Monitors the clipboard for changes and sends updates to the server. - * - * @name monitorClipboard.js - * @author Aliaksei Smirnou - */ - -import chalk from 'chalk'; -import clipboardy from 'clipboardy'; - -let isUpdatingFromNetwork = false; - -async function readClipboard() { - try { - return await clipboardy.read(); - } catch (error) { - console.error(`Failed to read clipboard: ${error.message}`); - return null; - } -} - -function logSending(content) { - const currentTime = new Date().toLocaleTimeString(); - process.stdout.write(`${chalk.gray(`[${currentTime}]`)} ${chalk.blue('Sending content: ')}${chalk.yellow(content.length.toString())} characters...`); -} - -function logResult(result) { - process.stdout.write(result ? chalk.green(' Ok.\n') : chalk.red(' Error.\n')); -} - -export async function monitorClipboard(sendUpdate, passphrase) { - let lastClipboardContent = await readClipboard(); - - setInterval(async () => { - const content = await readClipboard(); - - if (isUpdatingFromNetwork) { - lastClipboardContent = content - return; - } - - if (content && content !== lastClipboardContent) { - logSending(content); - lastClipboardContent = content; - try { - await sendUpdate(content, passphrase); - logResult(true); - } catch (error) { - console.error(`Error sending update: ${error.message}`); - logResult(false); - } - } - }, 1000); -} - -export function setClipboardUpdateSource(isFromNetwork) { - isUpdatingFromNetwork = isFromNetwork; -} diff --git a/package-lock.json b/package-lock.json index 3b88442..2db3743 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,49 +1,455 @@ { "name": "netpaste", - "version": "1.0.0", + "version": "2.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "netpaste", - "version": "1.0.0", - "license": "ISC", + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "bonjour-service": "^1.4.4", + "clipboardy": "^5.3.2" + }, + "bin": { + "netpaste": "src/cli.ts" + }, + "devDependencies": { + "@types/node": "^22.20.5", + "typescript": "^7.0.2" + }, + "engines": { + "node": ">=22.18" + } + }, + "node_modules/@leichtgewicht/ip-codec": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz", + "integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==", + "license": "MIT" + }, + "node_modules/@sec-ant/readable-stream": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@sec-ant/readable-stream/-/readable-stream-0.4.1.tgz", + "integrity": "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==", + "license": "MIT" + }, + "node_modules/@sindresorhus/merge-streams": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-4.0.0.tgz", + "integrity": "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/bonjour-service": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/bonjour-service/-/bonjour-service-1.4.4.tgz", + "integrity": "sha512-jCZcVv7eoc4QesRscwEZtSROBen+6LpKAmBIsQYQrsAeVHLyMXWX/t6eIV5KiRZYNUBl8eVqImEEMQ8L5+c/Kw==", + "license": "MIT", "dependencies": { - "chalk": "^5.3.0", - "clipboardy": "^4.0.0" + "fast-deep-equal": "^3.1.3", + "multicast-dns": "^7.2.5" } }, - "node_modules/chalk": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", - "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", + "node_modules/clipboard-image": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/clipboard-image/-/clipboard-image-0.1.0.tgz", + "integrity": "sha512-SWk7FgaXLNFld19peQ/rTe0n97lwR1WbkqxV6JKCAOh7U52AKV/PeMFCyt/8IhBdqyDA8rdyewQMKZqvWT5Akg==", + "license": "MIT", + "dependencies": { + "run-jxa": "^3.0.0" + }, + "bin": { + "clipboard-image": "cli.js" + }, "engines": { - "node": "^12.17.0 || ^14.13 || >=16.0.0" + "node": ">=20" }, "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/clipboardy": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/clipboardy/-/clipboardy-4.0.0.tgz", - "integrity": "sha512-5mOlNS0mhX0707P2I0aZ2V/cmHUEO/fL7VFLqszkhUsxt7RwnmrInf/eEQKlf5GzvYeHIjT+Ov1HRfNmymlG0w==", + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/clipboardy/-/clipboardy-5.3.2.tgz", + "integrity": "sha512-R35PENCHFCw6lsd5SjYPuAVV3Zawr74mKc7ogFNzoDPoQsmWDoJgUNNnWCk/czeqdZGZs8Y0M8zkOlVoySfHEQ==", + "license": "MIT", "dependencies": { - "execa": "^8.0.1", + "clipboard-image": "^0.1.0", + "execa": "^9.6.1", + "is-wayland": "^0.1.0", "is-wsl": "^3.1.0", - "is64bit": "^2.0.0" + "is64bit": "^2.0.0", + "powershell-utils": "^0.2.0" }, "engines": { - "node": ">=18" + "node": ">=20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -53,51 +459,134 @@ "node": ">= 8" } }, + "node_modules/crypto-random-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-4.0.0.tgz", + "integrity": "sha512-x8dy3RnvYdlUcPOjkEHqozhiwzKNSq7GcPuXFbnyMOCHxX8V3OgIg/pYuabl2sbUPfIJaeAQB7PMOK8DFIdoRA==", + "license": "MIT", + "dependencies": { + "type-fest": "^1.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/crypto-random-string/node_modules/type-fest": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-1.4.0.tgz", + "integrity": "sha512-yGSza74xk0UG8k+pLh5oeoYirvIiWo5t0/o3zHHAO2tRDiZcxWP7fywNlXhqb6/r6sWvwi+RsyQMWhVLe4BVuA==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/dns-packet": { + "version": "5.6.1", + "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz", + "integrity": "sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==", + "license": "MIT", + "dependencies": { + "@leichtgewicht/ip-codec": "^2.0.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", + "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/execa": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", - "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==", + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-9.6.1.tgz", + "integrity": "sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA==", + "license": "MIT", "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^8.0.1", - "human-signals": "^5.0.0", - "is-stream": "^3.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^5.1.0", - "onetime": "^6.0.0", + "@sindresorhus/merge-streams": "^4.0.0", + "cross-spawn": "^7.0.6", + "figures": "^6.1.0", + "get-stream": "^9.0.0", + "human-signals": "^8.0.1", + "is-plain-obj": "^4.1.0", + "is-stream": "^4.0.1", + "npm-run-path": "^6.0.0", + "pretty-ms": "^9.2.0", "signal-exit": "^4.1.0", - "strip-final-newline": "^3.0.0" + "strip-final-newline": "^4.0.0", + "yoctocolors": "^2.1.1" }, "engines": { - "node": ">=16.17" + "node": "^18.19.0 || >=20.5.0" }, "funding": { "url": "https://github.com/sindresorhus/execa?sponsor=1" } }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/figures": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-6.1.0.tgz", + "integrity": "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==", + "license": "MIT", + "dependencies": { + "is-unicode-supported": "^2.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-stream": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", - "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-9.0.1.tgz", + "integrity": "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==", + "license": "MIT", + "dependencies": { + "@sec-ant/readable-stream": "^0.4.1", + "is-stream": "^4.0.1" + }, "engines": { - "node": ">=16" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/human-signals": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", - "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-8.0.1.tgz", + "integrity": "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ==", + "license": "Apache-2.0", "engines": { - "node": ">=16.17.0" + "node": ">=18.18.0" } }, "node_modules/is-docker": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz", "integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==", + "license": "MIT", "bin": { "is-docker": "cli.js" }, @@ -112,6 +601,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz", "integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==", + "license": "MIT", "dependencies": { "is-docker": "^3.0.0" }, @@ -125,21 +615,59 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-plain-obj": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", + "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-stream": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", - "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-4.0.1.tgz", + "integrity": "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A==", + "license": "MIT", "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", + "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-wayland": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-wayland/-/is-wayland-0.1.0.tgz", + "integrity": "sha512-QkbMsWkIfkrzOPxenwye0h56iAXirZYHG9eHVPb22fO9y+wPbaX/CHacOWBa/I++4ohTcByimhM1/nyCsH8KNA==", + "license": "MIT", + "engines": { + "node": ">=20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-wsl": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.0.tgz", - "integrity": "sha512-UcVfVfaK4Sc4m7X3dUSoHoozQGBEFeDC+zVo06t98xe8CzHSZZBekNXH+tu0NalHolcJ/QAGqS46Hef7QXBIMw==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.1.tgz", + "integrity": "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==", + "license": "MIT", "dependencies": { "is-inside-container": "^1.0.0" }, @@ -154,6 +682,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/is64bit/-/is64bit-2.0.0.tgz", "integrity": "sha512-jv+8jaWCl0g2lSBkNSVXdzfBA0npK1HGC2KtWM9FumFRoGS94g3NbCCLVnCYHLjp4GrW2KZeeSTMo5ddtznmGw==", + "license": "MIT", "dependencies": { "system-architecture": "^0.1.0" }, @@ -167,33 +696,63 @@ "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/macos-version": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/macos-version/-/macos-version-6.0.0.tgz", + "integrity": "sha512-O2S8voA+pMfCHhBn/TIYDXzJ1qNHpPDU32oFxglKnVdJABiYYITt45oLkV9yhwA3E2FDwn3tQqUFrTsr1p3sBQ==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, "node_modules/merge-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==" + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "license": "MIT" }, "node_modules/mimic-fn": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", - "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "license": "MIT", "engines": { - "node": ">=12" + "node": ">=6" + } + }, + "node_modules/multicast-dns": { + "version": "7.2.5", + "resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-7.2.5.tgz", + "integrity": "sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg==", + "license": "MIT", + "dependencies": { + "dns-packet": "^5.2.2", + "thunky": "^1.0.2" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "bin": { + "multicast-dns": "cli.js" } }, "node_modules/npm-run-path": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz", - "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-6.0.0.tgz", + "integrity": "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==", + "license": "MIT", "dependencies": { - "path-key": "^4.0.0" + "path-key": "^4.0.0", + "unicorn-magic": "^0.3.0" }, "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -203,6 +762,7 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", + "license": "MIT", "engines": { "node": ">=12" }, @@ -211,14 +771,27 @@ } }, "node_modules/onetime": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", - "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "license": "MIT", "dependencies": { - "mimic-fn": "^4.0.0" + "mimic-fn": "^2.1.0" }, "engines": { - "node": ">=12" + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse-ms": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-4.0.0.tgz", + "integrity": "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==", + "license": "MIT", + "engines": { + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -228,14 +801,156 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/powershell-utils": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/powershell-utils/-/powershell-utils-0.2.1.tgz", + "integrity": "sha512-C+y9x90UElAddDZmV4qOx9W53B61PO7cIqWz2dQsWlwswuq4mr8NEwytdGKboYbQlGZ3awrkTeNvcZiZNHnQ8A==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/pretty-ms": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.3.1.tgz", + "integrity": "sha512-HzMy3Geq23nVALD/M2LliU+F+M+gVNsvkQWWqeBZ8HDiCgzo6YPJ/Omrmtq24EFrIsk0a3EkQGEd7bDOo+IhGA==", + "license": "MIT", + "dependencies": { + "parse-ms": "^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/run-jxa": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/run-jxa/-/run-jxa-3.0.0.tgz", + "integrity": "sha512-4f2CrY7H+sXkKXJn/cE6qRA3z+NMVO7zvlZ/nUV0e62yWftpiLAfw5eV9ZdomzWd2TXWwEIiGjAT57+lWIzzvA==", + "license": "MIT", + "dependencies": { + "execa": "^5.1.1", + "macos-version": "^6.0.0", + "subsume": "^4.0.0", + "type-fest": "^2.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/run-jxa/node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/run-jxa/node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/run-jxa/node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "license": "Apache-2.0", + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/run-jxa/node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/run-jxa/node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "license": "MIT", + "dependencies": { + "path-key": "^3.0.0" + }, "engines": { "node": ">=8" } }, + "node_modules/run-jxa/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/run-jxa/node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" }, @@ -247,6 +962,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", "engines": { "node": ">=8" } @@ -255,6 +971,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", "engines": { "node": ">=14" }, @@ -263,11 +980,28 @@ } }, "node_modules/strip-final-newline": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", - "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-4.0.0.tgz", + "integrity": "sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==", + "license": "MIT", "engines": { - "node": ">=12" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/subsume": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/subsume/-/subsume-4.0.0.tgz", + "integrity": "sha512-BWnYJElmHbYZ/zKevy+TG+SsyoFCmRPDHJbR1MzLxkPOv1Jp/4hGhVUtP98s+wZBsBsHwCXvPTP0x287/WMjGg==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^5.0.0", + "unique-string": "^3.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -277,6 +1011,79 @@ "version": "0.1.0", "resolved": "https://registry.npmjs.org/system-architecture/-/system-architecture-0.1.0.tgz", "integrity": "sha512-ulAk51I9UVUyJgxlv9M6lFot2WP3e7t8Kz9+IS6D4rVba1tR9kON+Ey69f+1R4Q8cd45Lod6a4IcJIxnzGc/zA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/thunky": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz", + "integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==", + "license": "MIT" + }, + "node_modules/type-fest": { + "version": "2.19.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-2.19.0.tgz", + "integrity": "sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/unicorn-magic": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.3.0.tgz", + "integrity": "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==", + "license": "MIT", "engines": { "node": ">=18" }, @@ -284,10 +1091,26 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/unique-string": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-3.0.0.tgz", + "integrity": "sha512-VGXBUVwxKMBUznyffQweQABPRRW1vHZAbadFZud4pLFAqRGvv/96vafgjWFqzourzr8YonlQiPgH0YCJfawoGQ==", + "license": "MIT", + "dependencies": { + "crypto-random-string": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", "dependencies": { "isexe": "^2.0.0" }, @@ -297,6 +1120,18 @@ "engines": { "node": ">= 8" } + }, + "node_modules/yoctocolors": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/yoctocolors/-/yoctocolors-2.2.0.tgz", + "integrity": "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } } } } diff --git a/package.json b/package.json index c80a591..71b36c8 100644 --- a/package.json +++ b/package.json @@ -1,17 +1,45 @@ { "name": "netpaste", + "version": "2.0.0", + "description": "Encrypted clipboard sync between your machines on a local network", "type": "module", - "version": "1.0.0", - "description": "", - "main": "server.js", + "bin": { + "netpaste": "./bin/netpaste.js" + }, + "files": [ + "bin", + "src", + "contrib", + "docs" + ], + "engines": { + "node": ">=22.18" + }, "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "start": "node bin/netpaste.js", + "typecheck": "tsc", + "test": "node --test \"test/**/*.test.ts\"", + "check": "npm run typecheck && npm test" }, - "keywords": [], + "repository": { + "type": "git", + "url": "git+https://github.com/leplik/netpaste.git" + }, + "keywords": [ + "clipboard", + "sync", + "lan", + "cli", + "encryption" + ], "author": "Aliaksei Smirnou", "license": "MIT", "dependencies": { - "chalk": "^5.3.0", - "clipboardy": "^4.0.0" + "bonjour-service": "^1.4.4", + "clipboardy": "^5.3.2" + }, + "devDependencies": { + "@types/node": "^22.20.5", + "typescript": "^7.0.2" } } diff --git a/passphrase.js b/passphrase.js deleted file mode 100644 index 56143dd..0000000 --- a/passphrase.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @fileoverview Captures user input for the passphrase in a secure manner. - * - * @name passphrase.js - * @author Aliaksei Smirnou - */ - -import readline from 'readline'; -import { Writable } from 'stream'; - -function getPassphrase(callback) { - let mutableStdout = new Writable({ - write: function(chunk, encoding, callback) { - if (!this.muted) process.stdout.write(chunk, encoding); - callback(); - } - }); - mutableStdout.muted = false; - - let passphrase = ''; - - let rl = readline.createInterface({ - input: process.stdin, - output: mutableStdout, - terminal: true - }); - - process.stdout.write('Passphrase for session: '); - mutableStdout.muted = true; // Mute the output to prevent displaying the password - - process.stdin.on('keypress', (char, key) => { - if (key && key.name == 'return') { - process.stdin.removeAllListeners('keypress'); - rl.close(); - mutableStdout.muted = false; - console.log('\n'); // Move to the next line - callback(passphrase); // Pass the captured passphrase to the callback - } else if (key && key.ctrl && key.name == 'c') { - process.exit(); // Allow exit on CTRL+C - } else { - passphrase += char; - process.stdout.write("*"); - } - }); - - rl.question('', () => {}); // Empty question as we handle input manually -} - -export { getPassphrase }; \ No newline at end of file diff --git a/sendUpdate.js b/sendUpdate.js deleted file mode 100644 index 6b9ee87..0000000 --- a/sendUpdate.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * @fileoverview Sends an update to the server. - * - * @name sendUpdate.js - * @author Aliaksei Smirnou - */ - -import { encrypt } from './encryption.js'; -import { fragmentAndSendMessage } from './fragmenter.js'; - -export async function sendUpdate(client, message, passphrase) { - if (!client) { - console.log('No connection to server. Attempting to reconnect...'); - return; - } - - const encryptedMessage = encrypt('NETPASTE_UPDATE:' + message, passphrase); - fragmentAndSendMessage(encryptedMessage, client); -} \ No newline at end of file diff --git a/server.js b/server.js deleted file mode 100644 index 4772ac1..0000000 --- a/server.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @fileoverview Server entry point - * - * @name server.js - * @author Aliaksei Smirnou - */ - -import net from 'net'; -import { getPassphrase } from './passphrase.js'; -import { handleMessage } from './messageHandler.js'; -import { encrypt } from './encryption.js'; -import { monitorClipboard } from './monitorClipboard.js'; -import { sendUpdate } from './sendUpdate.js'; -import { DEFAULT_PORT } from './config.js'; -import MessageAssembler from './fragmenter.js'; -const messageAssembler = new MessageAssembler(); - -let passphrase = ''; - -function startServer(port, disableClipboard) { - const server = net.createServer((socket) => { - console.log('Client connection attempt.'); - - const message = 'NETPASTE_HELLO:Netpaste server v1.0'; - const encryptedMessage = encrypt(message, passphrase); - socket.write(encryptedMessage); - - if (!disableClipboard) { - monitorClipboard(sendUpdate.bind(null, socket), passphrase).catch(console.error); - } - - socket.on('data', (data) => { - // Use the addData method with a callback to handle the complete message. - messageAssembler.addData(data, (completeMessage) => { - handleMessage(completeMessage, passphrase, disableClipboard); - }); - }); - - socket.on('end', () => { - console.log('Client disconnected'); - }); - - socket.on('error', (err) => { - console.error('Socket error:', err.message); - }); - }); - - server.on('error', (err) => { - console.error('Server error:', err.message); - }); - - server.listen(port, () => { - console.log(`Server listening on port ${port}`); - }); -} - -function parseCommandLineArgs() { - const args = process.argv.slice(2); // Slice to remove the node and script paths - const portArg = args.find(arg => !isNaN(parseInt(arg, 10))); - const disableClipboard = args.includes('--no-clipboard'); - - const port = parseInt(portArg, 10) || DEFAULT_PORT; - if (portArg && (port < 0 || port > 65535 || isNaN(port))) { - console.error('Invalid port number. Usage: node server.js [port] [--no-clipboard]'); - process.exit(1); - } - - return { port, disableClipboard }; -} - -getPassphrase((input) => { - passphrase = input; - const { port, disableClipboard } = parseCommandLineArgs(); - startServer(port, disableClipboard); -}); diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..939a860 --- /dev/null +++ b/src/config.ts @@ -0,0 +1,56 @@ +/** Wire protocol version spoken by this build. Version 1 (netpaste 1.x) is not compatible. */ +export const PROTOCOL_VERSION = 2; + +export const DEFAULT_PORT = 8134; + +/** mDNS / DNS-SD service type: `_netpaste._tcp.local`. */ +export const MDNS_SERVICE_TYPE = 'netpaste'; + +/** Default upper limit for one clipboard text, in UTF-8 bytes. */ +export const DEFAULT_MAX_TEXT_BYTES = 10 * 1024 * 1024; +export const MIN_TEXT_BYTES = 1024; +export const MAX_TEXT_BYTES_CEILING = 256 * 1024 * 1024; + +export const DEFAULT_POLL_INTERVAL_MS = 1000; +export const MIN_POLL_INTERVAL_MS = 100; +export const MAX_POLL_INTERVAL_MS = 60_000; + +/** The server drops new TCP connections above this number (authenticated or not). */ +export const MAX_CONNECTIONS = 32; + +/** How many passphrase key derivations (scrypt, ~128 MiB each) the server runs at once. */ +export const MAX_CONCURRENT_KDF = 2; + +export interface Timings { + /** Time from TCP connect to a finished handshake. */ + handshakeTimeoutMs: number; + /** Send a PING when nothing was sent for this long. */ + heartbeatIntervalMs: number; + /** Close the connection when nothing was received for this long. */ + idleTimeoutMs: number; + /** First reconnect delay of the client. The delay doubles up to `reconnectMaxMs`. */ + reconnectMinMs: number; + reconnectMaxMs: number; + /** The server waits this long before it reports a wrong passphrase. Slows down online guessing. */ + authFailureDelayMs: number; + /** + * After a wrong passphrase the server refuses that IP address for this long. + * The time doubles with every further failure, up to `authBlockMaxMs`. + */ + authBlockBaseMs: number; + authBlockMaxMs: number; + /** TCP connect timeout of the client. */ + connectTimeoutMs: number; +} + +export const DEFAULT_TIMINGS: Timings = { + handshakeTimeoutMs: 10_000, + heartbeatIntervalMs: 15_000, + idleTimeoutMs: 45_000, + reconnectMinMs: 1_000, + reconnectMaxMs: 30_000, + authFailureDelayMs: 1_000, + authBlockBaseMs: 1_000, + authBlockMaxMs: 60_000, + connectTimeoutMs: 10_000, +}; diff --git a/src/log.ts b/src/log.ts new file mode 100644 index 0000000..c62daa6 --- /dev/null +++ b/src/log.ts @@ -0,0 +1,42 @@ +import { styleText } from 'node:util'; + +type Style = Parameters[0]; + +export interface Logger { + info(message: string): void; + warn(message: string): void; + error(message: string): void; + debug(message: string): void; +} + +export interface LoggerOptions { + verbose?: boolean; + out?: NodeJS.WriteStream; + err?: NodeJS.WriteStream; +} + +/** Colors only when the stream is a terminal and NO_COLOR is not set (checked by `styleText`). */ +export function createLogger({ verbose = false, out = process.stdout, err = process.stderr }: LoggerOptions = {}): Logger { + const paint = (style: Style, text: string, stream: NodeJS.WriteStream) => styleText(style, text, { stream }); + const stamp = (stream: NodeJS.WriteStream) => paint('gray', new Date().toLocaleTimeString('en-GB'), stream); + return { + info: (message) => out.write(`${stamp(out)} ${message}\n`), + warn: (message) => err.write(`${stamp(err)} ${paint('yellow', 'warning:', err)} ${message}\n`), + error: (message) => err.write(`${stamp(err)} ${paint('red', 'error:', err)} ${message}\n`), + debug: (message) => { + if (verbose) out.write(`${stamp(out)} ${paint('dim', message, out)}\n`); + }, + }; +} + +export const silentLogger: Logger = { info() {}, warn() {}, error() {}, debug() {} }; + +/** Removes control characters (terminal escape sequences) and limits the length of peer-supplied text. */ +export function sanitizeForTerminal(text: string, maxLength = 64): string { + const clean = text.replace(/[\p{Cc}\p{Cf}]/gu, '').trim(); + return clean.length > maxLength ? `${clean.slice(0, maxLength - 1)}…` : clean; +} + +export function formatCount(n: number): string { + return n.toLocaleString('en-US'); +} diff --git a/src/version.ts b/src/version.ts new file mode 100644 index 0000000..03eb8ae --- /dev/null +++ b/src/version.ts @@ -0,0 +1,5 @@ +import { readFileSync } from 'node:fs'; + +const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }; + +export const VERSION: string = manifest.version; diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..ee363d1 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "target": "es2024", + "lib": ["es2024"], + "module": "nodenext", + "moduleResolution": "nodenext", + "types": ["node"], + + "noEmit": true, + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "erasableSyntaxOnly": true, + "isolatedModules": true, + + "strict": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "noFallthroughCasesInSwitch": true, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true + }, + "include": ["src", "test"] +} From 469a346522a116945312c586d2e077d832463384 Mon Sep 17 00:00:00 2001 From: Aliaksei Smirnou Date: Thu, 19 Nov 2026 08:34:01 +0100 Subject: [PATCH 2/9] feat: protocol v2 framing, mutual passphrase handshake, AES-256-GCM Framing: u32 length | u8 type | body, decoded from a byte stream with a size check before buffering. 1.x split messages on a "NetP" marker and assumed that every TCP read starts with a whole fragment: texts larger than one segment arrived corrupted, and 4 bytes crashed the process. Handshake: ephemeral X25519 + scrypt(passphrase, per-connection salt) + HKDF-SHA256. The client proves the passphrase first; the server proves it back. A passive eavesdropper cannot test guesses, a stranger receives nothing. Wrong passphrase: delayed ERROR, so online guessing is slow. Messages: AES-256-GCM with per-direction keys and counter nonces, the frame header as AAD. Changed, replayed, reordered or reflected messages fail. 1.x used AES-CTR without a MAC, so text could be changed or forged. Co-Authored-By: Claude Opus 5.5 --- src/crypto.ts | 159 ++++++++++++++++++++++++++++++++ src/frame-reader.ts | 59 ++++++++++++ src/frame.ts | 117 ++++++++++++++++++++++++ src/handshake.ts | 202 +++++++++++++++++++++++++++++++++++++++++ src/limiter.ts | 24 +++++ test/crypto.test.ts | 101 +++++++++++++++++++++ test/frame.test.ts | 81 +++++++++++++++++ test/handshake.test.ts | 118 ++++++++++++++++++++++++ test/helpers.ts | 78 ++++++++++++++++ 9 files changed, 939 insertions(+) create mode 100644 src/crypto.ts create mode 100644 src/frame-reader.ts create mode 100644 src/frame.ts create mode 100644 src/handshake.ts create mode 100644 src/limiter.ts create mode 100644 test/crypto.test.ts create mode 100644 test/frame.test.ts create mode 100644 test/handshake.test.ts create mode 100644 test/helpers.ts diff --git a/src/crypto.ts b/src/crypto.ts new file mode 100644 index 0000000..7f8b4cd --- /dev/null +++ b/src/crypto.ts @@ -0,0 +1,159 @@ +/** + * Cryptographic building blocks. Only `node:crypto` is used. + * + * - Passphrase key: scrypt (memory-hard), salted per connection. + * - Key agreement: ephemeral X25519 (forward secrecy). + * - Key schedule: HKDF-SHA256 over (X25519 secret || passphrase key). + * - Messages: AES-256-GCM. The nonce is a per-direction counter, so a replayed, + * reordered or dropped message fails authentication. + */ +import crypto from 'node:crypto'; +import { type Frame, FrameType, frameHeader } from './frame.ts'; + +export interface KdfParams { + N: number; + r: number; + p: number; +} + +/** OWASP-recommended scrypt cost: 128 MiB of memory, about 0.2 s on a laptop. */ +export const DEFAULT_KDF: KdfParams = { N: 2 ** 17, r: 8, p: 1 }; + +export const KEY_BYTES = 32; +export const TAG_BYTES = 16; +const NONCE_BYTES = 12; +const MAX_COUNTER = 2n ** 64n - 1n; + +export class IntegrityError extends Error { + override name = 'IntegrityError'; +} + +export function sha256(...parts: Uint8Array[]): Buffer { + const hash = crypto.createHash('sha256'); + for (const part of parts) hash.update(part); + return hash.digest(); +} + +export function hmacSha256(key: Uint8Array, ...parts: Uint8Array[]): Buffer { + const mac = crypto.createHmac('sha256', key); + for (const part of parts) mac.update(part); + return mac.digest(); +} + +export function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean { + return a.length === b.length && crypto.timingSafeEqual(a, b); +} + +/** + * Unicode NFC normalization: the same passphrase typed on macOS and Linux can arrive + * in different normalization forms (for example "й" as one or as two code points). + */ +export function normalizePassphrase(passphrase: string): string { + return passphrase.normalize('NFC'); +} + +export function derivePassphraseKey(passphrase: string, salt: Uint8Array, params: KdfParams = DEFAULT_KDF): Promise { + const maxmem = 128 * params.N * params.r * params.p + 32 * 1024 * 1024; + return new Promise((resolve, reject) => { + crypto.scrypt(normalizePassphrase(passphrase), salt, KEY_BYTES, { ...params, maxmem }, (error, key) => { + if (error) reject(error); + else resolve(key); + }); + }); +} + +export interface EphemeralKey { + privateKey: crypto.KeyObject; + /** Raw 32-byte X25519 public key. */ + publicKey: Buffer; +} + +export function generateEphemeralKey(): EphemeralKey { + const { privateKey, publicKey } = crypto.generateKeyPairSync('x25519'); + const { x } = publicKey.export({ format: 'jwk' }); + if (!x) throw new Error('cannot export the X25519 public key'); + return { privateKey, publicKey: Buffer.from(x, 'base64url') }; +} + +export function x25519(privateKey: crypto.KeyObject, peerPublicKey: Uint8Array): Buffer { + if (peerPublicKey.length !== KEY_BYTES) throw new IntegrityError('invalid X25519 public key length'); + const publicKey = crypto.createPublicKey({ + key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(peerPublicKey).toString('base64url') }, + format: 'jwk', + }); + let shared: Buffer; + try { + shared = crypto.diffieHellman({ privateKey, publicKey }); + } catch { + throw new IntegrityError('invalid X25519 public key'); + } + // An all-zero result means a low-order public key: the peer would control the secret. + if (shared.every((byte) => byte === 0)) throw new IntegrityError('invalid X25519 public key (low-order point)'); + return shared; +} + +export interface SessionSecrets { + clientToServer: Buffer; + serverToClient: Buffer; + clientProofKey: Buffer; + serverProofKey: Buffer; +} + +export function deriveSessionSecrets(sharedSecret: Buffer, passphraseKey: Buffer, transcriptHash: Buffer): SessionSecrets { + const okm = Buffer.from( + crypto.hkdfSync('sha256', Buffer.concat([sharedSecret, passphraseKey]), transcriptHash, 'netpaste/2 session keys', 4 * KEY_BYTES), + ); + return { + clientToServer: okm.subarray(0, KEY_BYTES), + serverToClient: okm.subarray(KEY_BYTES, 2 * KEY_BYTES), + clientProofKey: okm.subarray(2 * KEY_BYTES, 3 * KEY_BYTES), + serverProofKey: okm.subarray(3 * KEY_BYTES, 4 * KEY_BYTES), + }; +} + +/** Encrypts outgoing and decrypts incoming `Sealed` frames of one connection. */ +export class SecureChannel { + #sendKey: Buffer; + #receiveKey: Buffer; + #sendCounter = 0n; + #receiveCounter = 0n; + + constructor(sendKey: Buffer, receiveKey: Buffer) { + this.#sendKey = sendKey; + this.#receiveKey = receiveKey; + } + + /** Returns a complete frame (header + ciphertext + tag). The header is authenticated too. */ + seal(plaintext: Uint8Array): Buffer { + const header = frameHeader(FrameType.Sealed, plaintext.length + TAG_BYTES); + const cipher = crypto.createCipheriv('aes-256-gcm', this.#sendKey, nonce(this.#sendCounter), { authTagLength: TAG_BYTES }); + this.#sendCounter++; + cipher.setAAD(header); + return Buffer.concat([header, cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]); + } + + open(frame: Frame): Buffer { + if (frame.type !== FrameType.Sealed) throw new IntegrityError(`expected an encrypted frame, got type 0x${frame.type.toString(16)}`); + if (frame.body.length < TAG_BYTES) throw new IntegrityError('encrypted frame is too short'); + const decipher = crypto.createDecipheriv('aes-256-gcm', this.#receiveKey, nonce(this.#receiveCounter), { + authTagLength: TAG_BYTES, + }); + decipher.setAAD(frame.header); + decipher.setAuthTag(frame.body.subarray(frame.body.length - TAG_BYTES)); + let plaintext: Buffer; + try { + plaintext = Buffer.concat([decipher.update(frame.body.subarray(0, frame.body.length - TAG_BYTES)), decipher.final()]); + } catch { + throw new IntegrityError('message failed authentication: it was changed, replayed or reordered'); + } + this.#receiveCounter++; + return plaintext; + } +} + +function nonce(counter: bigint): Buffer { + if (counter > MAX_COUNTER) throw new IntegrityError('message counter exhausted; reconnect'); + const value = Buffer.alloc(NONCE_BYTES); + value.writeBigUInt64BE(counter, NONCE_BYTES - 8); + return value; +} diff --git a/src/frame-reader.ts b/src/frame-reader.ts new file mode 100644 index 0000000..86882c8 --- /dev/null +++ b/src/frame-reader.ts @@ -0,0 +1,59 @@ +import type { Duplex } from 'node:stream'; +import { FrameDecoder, type Frame } from './frame.ts'; + +export class ConnectionClosedError extends Error { + override name = 'ConnectionClosedError'; +} + +/** + * Pull-based frame reader over a socket: `await reader.next()` returns one frame at a time. + * The caller can change `maxBodyBytes` between frames, for example after the handshake. + * After the connection ends, the reader still returns the frames that arrived before the end, + * then it throws the reason (`ConnectionClosedError`, a socket error, or a `FrameError`). + */ +export class FrameReader { + #decoder: FrameDecoder; + #wake: (() => void) | null = null; + #end: Error | null = null; + + constructor(socket: Duplex, maxBodyBytes: number) { + this.#decoder = new FrameDecoder(maxBodyBytes); + socket.on('data', (chunk: Buffer) => { + this.#decoder.push(chunk); + this.#notify(); + }); + socket.on('end', () => this.#finish(new ConnectionClosedError('the peer closed the connection'))); + socket.on('close', () => this.#finish(new ConnectionClosedError('the connection was closed'))); + socket.on('error', (error: Error) => this.#finish(error)); + } + + get maxBodyBytes(): number { + return this.#decoder.maxBodyBytes; + } + + set maxBodyBytes(value: number) { + this.#decoder.maxBodyBytes = value; + } + + async next(): Promise { + for (;;) { + const frame = this.#decoder.next(); + if (frame) return frame; + if (this.#end) throw this.#end; + await new Promise((resolve) => { + this.#wake = resolve; + }); + } + } + + #notify(): void { + const wake = this.#wake; + this.#wake = null; + wake?.(); + } + + #finish(error: Error): void { + this.#end ??= error; + this.#notify(); + } +} diff --git a/src/frame.ts b/src/frame.ts new file mode 100644 index 0000000..36efeac --- /dev/null +++ b/src/frame.ts @@ -0,0 +1,117 @@ +/** + * Length-prefixed framing on top of the TCP byte stream. + * + * frame = length (u32 big-endian, counts type + body) | type (u8) | body + * + * TCP does not keep message boundaries: one `data` event can hold half a frame or + * several frames. The decoder buffers bytes until a whole frame is available and checks + * the declared length against a limit before it buffers the body. + */ + +export const FrameType = { + /** Handshake: protocol version, role and ephemeral X25519 key (plaintext). */ + Hello: 0x01, + /** Handshake: proof of the passphrase (HMAC over the transcript). */ + Auth: 0x02, + /** Handshake failure reported to the peer (plaintext, error code only). */ + Error: 0x03, + /** Any message after the handshake, encrypted with AES-256-GCM. */ + Sealed: 0x10, +} as const; + +export const HEADER_BYTES = 5; +const LENGTH_BYTES = 4; + +export interface Frame { + /** The 5 header bytes (length + type). Sealed frames use them as additional authenticated data. */ + header: Buffer; + type: number; + body: Buffer; +} + +export class FrameError extends Error { + override name = 'FrameError'; +} + +export function frameHeader(type: number, bodyBytes: number): Buffer { + const header = Buffer.alloc(HEADER_BYTES); + header.writeUInt32BE(bodyBytes + 1, 0); + header.writeUInt8(type, LENGTH_BYTES); + return header; +} + +export function encodeFrame(type: number, body: Uint8Array = Buffer.alloc(0)): Buffer { + return Buffer.concat([frameHeader(type, body.length), body]); +} + +export class FrameDecoder { + /** Largest accepted body. The owner can change it between frames (for example after the handshake). */ + maxBodyBytes: number; + #chunks: Buffer[] = []; + #buffered = 0; + + constructor(maxBodyBytes: number) { + this.maxBodyBytes = maxBodyBytes; + } + + get bufferedBytes(): number { + return this.#buffered; + } + + push(chunk: Buffer): void { + if (chunk.length === 0) return; + this.#chunks.push(chunk); + this.#buffered += chunk.length; + } + + /** Returns the next complete frame, or `null` when more bytes are needed. */ + next(): Frame | null { + if (this.#buffered < LENGTH_BYTES) return null; + const length = this.#peek(LENGTH_BYTES).readUInt32BE(0); + if (length === 0) throw new FrameError('received a frame without a type byte'); + const bodyBytes = length - 1; + if (bodyBytes > this.maxBodyBytes) { + throw new FrameError(`frame of ${bodyBytes} bytes is larger than the limit of ${this.maxBodyBytes} bytes`); + } + if (this.#buffered < LENGTH_BYTES + length) return null; + const raw = this.#take(LENGTH_BYTES + length); + return { header: raw.subarray(0, HEADER_BYTES), type: raw.readUInt8(LENGTH_BYTES), body: raw.subarray(HEADER_BYTES) }; + } + + #peek(n: number): Buffer { + const first = this.#chunks[0]!; + if (first.length >= n) return first.subarray(0, n); + const out = Buffer.alloc(n); + let offset = 0; + for (const chunk of this.#chunks) { + offset += chunk.copy(out, offset, 0, Math.min(chunk.length, n - offset)); + if (offset === n) break; + } + return out; + } + + #take(n: number): Buffer { + const first = this.#chunks[0]!; + if (first.length >= n) { + if (first.length === n) this.#chunks.shift(); + else this.#chunks[0] = first.subarray(n); + this.#buffered -= n; + return first.subarray(0, n); + } + const out = Buffer.alloc(n); + let offset = 0; + while (offset < n) { + const chunk = this.#chunks[0]!; + const want = n - offset; + if (chunk.length <= want) { + offset += chunk.copy(out, offset); + this.#chunks.shift(); + } else { + offset += chunk.copy(out, offset, 0, want); + this.#chunks[0] = chunk.subarray(want); + } + } + this.#buffered -= n; + return out; + } +} diff --git a/src/handshake.ts b/src/handshake.ts new file mode 100644 index 0000000..efe4d7c --- /dev/null +++ b/src/handshake.ts @@ -0,0 +1,202 @@ +/** + * Mutual passphrase authentication and key agreement. + * + * client server + * │── HELLO "NETPASTE" | ver | role=0 | X25519 eC ──▶│ + * │◀── HELLO "NETPASTE" | ver | role=1 | X25519 eS ───│ + * │ transcript = SHA-256(label | helloC | helloS) │ + * │ pk = scrypt(passphrase, SHA-256(label | transcript)) + * │ keys = HKDF(X25519(e, e') | pk, transcript) │ + * │── AUTH HMAC(clientProofKey, transcript) ────────▶│ wrong → delay, ERROR, close + * │◀── AUTH HMAC(serverProofKey, transcript) ────────│ + * │════════ Sealed frames, AES-256-GCM ════════════════│ + * + * - A passive eavesdropper cannot test passphrase guesses: the proofs depend on the X25519 secret. + * - The server proves nothing before the client does, so a stranger that connects learns nothing. + * - Both sides add a fresh key to the scrypt salt, so a fake server cannot reuse precomputed guesses. + * - An active man-in-the-middle (or a fake server) can still guess the passphrase offline from the + * client proof, one scrypt run per guess. A long passphrase makes this impractical. + */ +import type { Duplex } from 'node:stream'; +import { + type KdfParams, + SecureChannel, + constantTimeEqual, + derivePassphraseKey, + deriveSessionSecrets, + generateEphemeralKey, + hmacSha256, + sha256, + x25519, +} from './crypto.ts'; +import { PROTOCOL_VERSION } from './config.ts'; +import { type Frame, FrameError, FrameType, encodeFrame } from './frame.ts'; +import { ConnectionClosedError, type FrameReader } from './frame-reader.ts'; +import type { Limiter } from './limiter.ts'; + +const MAGIC = Buffer.from('NETPASTE', 'ascii'); +const HELLO_BYTES = MAGIC.length + 1 + 1 + 32; +const PROOF_BYTES = 32; + +/** Largest frame body allowed before authentication. */ +export const HANDSHAKE_MAX_BODY_BYTES = 256; + +const Role = { Client: 0, Server: 1 } as const; +type RoleValue = (typeof Role)[keyof typeof Role]; + +export const HandshakeErrorCode = { + AuthFailed: 1, + VersionMismatch: 2, + ProtocolError: 3, +} as const; + +export type HandshakeFailure = + /** The peer reported that our passphrase is wrong. */ + | 'rejected' + /** The peer sent a wrong proof: different passphrase or an impostor. */ + | 'peer-unverified' + | 'version-mismatch' + | 'protocol'; + +export class HandshakeError extends Error { + override name = 'HandshakeError'; + readonly failure: HandshakeFailure; + + constructor(failure: HandshakeFailure, message: string) { + super(message); + this.failure = failure; + } +} + +export interface HandshakeOptions { + passphrase: string; + kdf?: KdfParams; + /** Server: limits parallel scrypt runs (each needs ~128 MiB). */ + kdfLimiter?: Limiter; + /** Server: wait this long before it reports a wrong passphrase. */ + authFailureDelayMs?: number; +} + +export async function clientHandshake(socket: Duplex, reader: FrameReader, options: HandshakeOptions): Promise { + const ephemeral = generateEphemeralKey(); + const helloClient = encodeHello(Role.Client, ephemeral.publicKey); + socket.write(encodeFrame(FrameType.Hello, helloClient)); + + const helloServer = expectFrame(await readHandshakeFrame(reader), FrameType.Hello).body; + const peerKey = parseHello(helloServer, Role.Server); + const transcript = transcriptHash(helloClient, helloServer); + const shared = x25519(ephemeral.privateKey, peerKey); + const passphraseKey = await derivePassphraseKey(options.passphrase, kdfSalt(transcript), options.kdf); + const secrets = deriveSessionSecrets(shared, passphraseKey, transcript); + + socket.write(encodeFrame(FrameType.Auth, proof(secrets.clientProofKey, 'client', transcript))); + + const serverProof = expectFrame(await readHandshakeFrame(reader), FrameType.Auth).body; + if (!constantTimeEqual(serverProof, proof(secrets.serverProofKey, 'server', transcript))) { + throw new HandshakeError('peer-unverified', 'the server could not prove that it knows the passphrase'); + } + return new SecureChannel(secrets.clientToServer, secrets.serverToClient); +} + +export async function serverHandshake(socket: Duplex, reader: FrameReader, options: HandshakeOptions): Promise { + const helloClient = expectFrame(await readHandshakeFrame(reader), FrameType.Hello).body; + let peerKey: Buffer; + try { + peerKey = parseHello(helloClient, Role.Client); + } catch (error) { + if (error instanceof HandshakeError) { + const code = error.failure === 'version-mismatch' ? HandshakeErrorCode.VersionMismatch : HandshakeErrorCode.ProtocolError; + socket.end(encodeFrame(FrameType.Error, Buffer.of(code))); + } + throw error; + } + + const ephemeral = generateEphemeralKey(); + const helloServer = encodeHello(Role.Server, ephemeral.publicKey); + socket.write(encodeFrame(FrameType.Hello, helloServer)); + + const transcript = transcriptHash(helloClient, helloServer); + const shared = x25519(ephemeral.privateKey, peerKey); + const derive = async () => { + if (socket.destroyed) throw new ConnectionClosedError('the connection was closed'); + return derivePassphraseKey(options.passphrase, kdfSalt(transcript), options.kdf); + }; + const passphraseKey = await (options.kdfLimiter ? options.kdfLimiter.run(derive) : derive()); + const secrets = deriveSessionSecrets(shared, passphraseKey, transcript); + + const clientProof = expectFrame(await readHandshakeFrame(reader), FrameType.Auth).body; + if (!constantTimeEqual(clientProof, proof(secrets.clientProofKey, 'client', transcript))) { + await delay(options.authFailureDelayMs ?? 0); + if (!socket.destroyed) socket.end(encodeFrame(FrameType.Error, Buffer.of(HandshakeErrorCode.AuthFailed))); + throw new HandshakeError('peer-unverified', 'the client sent a wrong passphrase'); + } + + socket.write(encodeFrame(FrameType.Auth, proof(secrets.serverProofKey, 'server', transcript))); + return new SecureChannel(secrets.serverToClient, secrets.clientToServer); +} + +function encodeHello(role: RoleValue, publicKey: Buffer): Buffer { + return Buffer.concat([MAGIC, Buffer.of(PROTOCOL_VERSION, role), publicKey]); +} + +function parseHello(body: Buffer, expectedRole: RoleValue): Buffer { + if (body.length < MAGIC.length + 1 || !body.subarray(0, MAGIC.length).equals(MAGIC)) { + throw new HandshakeError('protocol', 'the peer is not a netpaste 2 endpoint'); + } + const version = body.readUInt8(MAGIC.length); + if (version !== PROTOCOL_VERSION) { + throw new HandshakeError('version-mismatch', `the peer speaks protocol version ${version}, this build speaks ${PROTOCOL_VERSION}`); + } + if (body.length !== HELLO_BYTES) throw new HandshakeError('protocol', 'malformed HELLO message'); + if (body.readUInt8(MAGIC.length + 1) !== expectedRole) throw new HandshakeError('protocol', 'the peer has the wrong role'); + return body.subarray(MAGIC.length + 2); +} + +async function readHandshakeFrame(reader: FrameReader): Promise { + let frame: Frame; + try { + frame = await reader.next(); + } catch (error) { + if (error instanceof FrameError) { + throw new HandshakeError('protocol', 'unexpected data from the peer (is it netpaste 1.x or another program?)'); + } + throw error; + } + if (frame.type === FrameType.Error) throw remoteError(frame.body); + return frame; +} + +function expectFrame(frame: Frame, type: number): Frame { + if (frame.type !== type) throw new HandshakeError('protocol', `unexpected message type 0x${frame.type.toString(16)} during the handshake`); + return frame; +} + +/** Maps the peer's error code to our own text; the peer's bytes never reach the terminal. */ +function remoteError(body: Buffer): HandshakeError { + switch (body.length > 0 ? body.readUInt8(0) : 0) { + case HandshakeErrorCode.AuthFailed: + return new HandshakeError('rejected', 'the server rejected the passphrase'); + case HandshakeErrorCode.VersionMismatch: + return new HandshakeError('version-mismatch', 'the server speaks a different protocol version; update netpaste on both machines'); + default: + return new HandshakeError('protocol', 'the peer reported a protocol error'); + } +} + +function transcriptHash(helloClient: Buffer, helloServer: Buffer): Buffer { + return sha256(Buffer.from('netpaste/2 transcript'), helloClient, helloServer); +} + +function kdfSalt(transcript: Buffer): Buffer { + return sha256(Buffer.from('netpaste/2 kdf salt'), transcript); +} + +function proof(key: Buffer, role: 'client' | 'server', transcript: Buffer): Buffer { + const value = hmacSha256(key, Buffer.from(`netpaste/2 ${role} proof`), transcript); + if (value.length !== PROOF_BYTES) throw new Error('unexpected proof length'); + return value; +} + +function delay(ms: number): Promise { + return ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve(); +} diff --git a/src/limiter.ts b/src/limiter.ts new file mode 100644 index 0000000..676d63f --- /dev/null +++ b/src/limiter.ts @@ -0,0 +1,24 @@ +/** Runs at most `max` async tasks at the same time; the other tasks wait in FIFO order. */ +export class Limiter { + readonly #max: number; + #active = 0; + #waiting: Array<() => void> = []; + + constructor(max: number) { + if (!Number.isInteger(max) || max < 1) throw new RangeError('max must be a positive integer'); + this.#max = max; + } + + async run(task: () => Promise): Promise { + if (this.#active < this.#max) this.#active++; + else await new Promise((resolve) => this.#waiting.push(resolve)); + try { + return await task(); + } finally { + // Hand the slot to the next task, or free it. + const next = this.#waiting.shift(); + if (next) next(); + else this.#active--; + } + } +} diff --git a/test/crypto.test.ts b/test/crypto.test.ts new file mode 100644 index 0000000..53a3538 --- /dev/null +++ b/test/crypto.test.ts @@ -0,0 +1,101 @@ +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import { describe, it } from 'node:test'; +import { + DEFAULT_KDF, + IntegrityError, + SecureChannel, + derivePassphraseKey, + deriveSessionSecrets, + generateEphemeralKey, + x25519, +} from '../src/crypto.ts'; +import { FrameDecoder, FrameType } from '../src/frame.ts'; +import { FAST_KDF } from './helpers.ts'; + +function pair(): { a: SecureChannel; b: SecureChannel } { + const k1 = crypto.randomBytes(32); + const k2 = crypto.randomBytes(32); + return { a: new SecureChannel(k1, k2), b: new SecureChannel(k2, k1) }; +} + +function decode(bytes: Buffer) { + const decoder = new FrameDecoder(1 << 20); + decoder.push(bytes); + const frame = decoder.next(); + assert.ok(frame); + return frame; +} + +describe('SecureChannel', () => { + it('round-trips messages in both directions', () => { + const { a, b } = pair(); + for (const text of ['one', '', 'three 🙂']) { + assert.equal(b.open(decode(a.seal(Buffer.from(text)))).toString(), text); + assert.equal(a.open(decode(b.seal(Buffer.from(text)))).toString(), text); + } + }); + + it('rejects a changed ciphertext (AES-CTR in 1.x accepted this)', () => { + const { a, b } = pair(); + const sealed = a.seal(Buffer.from('ls -la ~/project')); + sealed[8] = sealed[8]! ^ 0x01; + assert.throws(() => b.open(decode(sealed)), IntegrityError); + }); + + it('rejects a changed header (the header is authenticated)', () => { + const { a, b } = pair(); + const frame = decode(a.seal(Buffer.from('hello'))); + const header = Buffer.from(frame.header); + header[4] = FrameType.Hello; + assert.throws(() => b.open({ ...frame, header, type: FrameType.Sealed }), IntegrityError); + }); + + it('rejects a replayed and a reordered message', () => { + const { a, b } = pair(); + const first = a.seal(Buffer.from('first')); + const second = a.seal(Buffer.from('second')); + assert.throws(() => b.open(decode(second)), IntegrityError, 'reordered'); + assert.equal(b.open(decode(first)).toString(), 'first'); + assert.throws(() => b.open(decode(first)), IntegrityError, 'replayed'); + assert.equal(b.open(decode(second)).toString(), 'second'); + }); + + it('does not accept its own messages back (separate keys per direction)', () => { + const { a } = pair(); + assert.throws(() => a.open(decode(a.seal(Buffer.from('echo')))), IntegrityError); + }); +}); + +describe('key agreement and derivation', () => { + it('gives both sides the same X25519 secret', () => { + const alice = generateEphemeralKey(); + const bob = generateEphemeralKey(); + assert.deepEqual(x25519(alice.privateKey, bob.publicKey), x25519(bob.privateKey, alice.publicKey)); + }); + + it('rejects malformed and low-order X25519 keys', () => { + const key = generateEphemeralKey(); + assert.throws(() => x25519(key.privateKey, Buffer.alloc(31)), IntegrityError); + assert.throws(() => x25519(key.privateKey, Buffer.alloc(32)), IntegrityError); + }); + + it('derives the same passphrase key for NFC and NFD spellings', async () => { + const salt = crypto.randomBytes(32); + const composed = 'пароль-й'.normalize('NFC'); + const decomposed = 'пароль-й'.normalize('NFD'); + assert.notEqual(composed, decomposed); + assert.deepEqual(await derivePassphraseKey(composed, salt, FAST_KDF), await derivePassphraseKey(decomposed, salt, FAST_KDF)); + }); + + it('runs scrypt with the production cost (128 MiB)', async () => { + const key = await derivePassphraseKey('correct horse battery staple', crypto.randomBytes(32), DEFAULT_KDF); + assert.equal(key.length, 32); + }); + + it('splits the key material into four different keys', () => { + const secrets = deriveSessionSecrets(crypto.randomBytes(32), crypto.randomBytes(32), crypto.randomBytes(32)); + const keys = Object.values(secrets).map((key) => key.toString('hex')); + assert.equal(new Set(keys).size, 4); + }); +}); diff --git a/test/frame.test.ts b/test/frame.test.ts new file mode 100644 index 0000000..003f06c --- /dev/null +++ b/test/frame.test.ts @@ -0,0 +1,81 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { type Frame, FrameDecoder, FrameError, FrameType, encodeFrame } from '../src/frame.ts'; + +const frames = [ + encodeFrame(FrameType.Hello, Buffer.from('first')), + encodeFrame(FrameType.Sealed, Buffer.alloc(3000, 0x61)), + encodeFrame(FrameType.Auth), + encodeFrame(FrameType.Sealed, Buffer.from('Ünïcødé 🙂')), +]; +const stream = Buffer.concat(frames); + +function decodeAll(decoder: FrameDecoder): Frame[] { + const out: Frame[] = []; + for (let frame = decoder.next(); frame; frame = decoder.next()) out.push(frame); + return out; +} + +function assertSameFrames(actual: Frame[]): void { + assert.equal(actual.length, frames.length); + actual.forEach((frame, i) => assert.deepEqual(Buffer.concat([frame.header, frame.body]), frames[i])); +} + +describe('FrameDecoder', () => { + it('decodes frames that arrive in one chunk', () => { + const decoder = new FrameDecoder(10_000); + decoder.push(stream); + assertSameFrames(decodeAll(decoder)); + assert.equal(decoder.bufferedBytes, 0); + }); + + it('decodes the same frames for a split at every byte position', () => { + for (let split = 0; split <= stream.length; split++) { + const decoder = new FrameDecoder(10_000); + const out: Frame[] = []; + decoder.push(stream.subarray(0, split)); + out.push(...decodeAll(decoder)); + decoder.push(stream.subarray(split)); + out.push(...decodeAll(decoder)); + assertSameFrames(out); + } + }); + + it('decodes a stream fed one byte at a time and in MSS-sized chunks', () => { + for (const size of [1, 7, 1448]) { + const decoder = new FrameDecoder(10_000); + const out: Frame[] = []; + for (let i = 0; i < stream.length; i += size) { + decoder.push(stream.subarray(i, i + size)); + out.push(...decodeAll(decoder)); + } + assertSameFrames(out); + } + }); + + it('rejects a frame above the limit as soon as the length is known', () => { + const decoder = new FrameDecoder(100); + decoder.push(encodeFrame(FrameType.Sealed, Buffer.alloc(101)).subarray(0, 4)); + assert.throws(() => decoder.next(), FrameError); + }); + + it('rejects a zero-length frame', () => { + const decoder = new FrameDecoder(100); + decoder.push(Buffer.alloc(4)); + assert.throws(() => decoder.next(), FrameError); + }); + + it('applies a raised limit to the following frames', () => { + const decoder = new FrameDecoder(10); + decoder.push(Buffer.concat([encodeFrame(FrameType.Hello, Buffer.alloc(5)), encodeFrame(FrameType.Sealed, Buffer.alloc(500))])); + assert.equal(decoder.next()?.type, FrameType.Hello); + decoder.maxBodyBytes = 1000; + assert.equal(decoder.next()?.body.length, 500); + }); + + it('treats the 4 bytes "NetP" (netpaste 1.x crash input) as an incomplete or oversized frame, not a crash', () => { + const decoder = new FrameDecoder(256); + decoder.push(Buffer.from('NetP')); + assert.throws(() => decoder.next(), FrameError); + }); +}); diff --git a/test/handshake.test.ts b/test/handshake.test.ts new file mode 100644 index 0000000..1b2b8b3 --- /dev/null +++ b/test/handshake.test.ts @@ -0,0 +1,118 @@ +import assert from 'node:assert/strict'; +import { once } from 'node:events'; +import net from 'node:net'; +import { describe, it } from 'node:test'; +import { IntegrityError } from '../src/crypto.ts'; +import { FrameDecoder, FrameType, encodeFrame } from '../src/frame.ts'; +import { FrameReader } from '../src/frame-reader.ts'; +import { + HANDSHAKE_MAX_BODY_BYTES, + HandshakeError, + HandshakeErrorCode, + clientHandshake, + serverHandshake, +} from '../src/handshake.ts'; +import { FAST_KDF } from './helpers.ts'; + +async function socketPair(): Promise<{ client: net.Socket; server: net.Socket }> { + const listener = net.createServer(); + await new Promise((resolve) => listener.listen(0, '127.0.0.1', resolve)); + const { port } = listener.address() as net.AddressInfo; + const accepted = once(listener, 'connection'); + const client = net.connect(port, '127.0.0.1'); + const connected = once(client, 'connect'); + const [server] = (await accepted) as [net.Socket]; + await connected; + listener.close(); + return { client, server }; +} + +function handshakes(pair: { client: net.Socket; server: net.Socket }, clientPassphrase: string, serverPassphrase: string) { + return Promise.allSettled([ + clientHandshake(pair.client, new FrameReader(pair.client, HANDSHAKE_MAX_BODY_BYTES), { passphrase: clientPassphrase, kdf: FAST_KDF }), + serverHandshake(pair.server, new FrameReader(pair.server, HANDSHAKE_MAX_BODY_BYTES), { passphrase: serverPassphrase, kdf: FAST_KDF }), + ]); +} + +function failure(result: PromiseSettledResult): string { + assert.equal(result.status, 'rejected'); + const reason = (result as PromiseRejectedResult).reason; + assert.ok(reason instanceof HandshakeError, `expected HandshakeError, got ${reason}`); + return reason.failure; +} + +describe('handshake', () => { + it('connects peers with the same passphrase and gives working channels', async () => { + const pair = await socketPair(); + const [client, server] = await handshakes(pair, 'correct horse battery staple', 'correct horse battery staple'); + assert.equal(client.status, 'fulfilled'); + assert.equal(server.status, 'fulfilled'); + const decoder = new FrameDecoder(1024); + decoder.push(client.value.seal(Buffer.from('hello hub'))); + assert.equal(server.value.open(decoder.next()!).toString(), 'hello hub'); + pair.client.destroy(); + pair.server.destroy(); + }); + + it('rejects a different passphrase on both sides', async () => { + const pair = await socketPair(); + const [client, server] = await handshakes(pair, 'passphrase one', 'passphrase two'); + assert.equal(failure(client), 'rejected'); + assert.equal(failure(server), 'peer-unverified'); + pair.client.destroy(); + }); + + it('fails when a man-in-the-middle changes one byte of the server key', async () => { + const left = await socketPair(); + const right = await socketPair(); + left.server.on('data', (data: Buffer) => right.client.write(data)); + let offset = 0; + right.client.on('data', (data: Buffer) => { + const copy = Buffer.from(data); + const target = 20 - offset; // inside the X25519 key of the server HELLO + if (target >= 0 && target < copy.length) copy[target] = copy[target]! ^ 0x01; + offset += data.length; + left.server.write(copy); + }); + const [client, server] = await Promise.allSettled([ + clientHandshake(left.client, new FrameReader(left.client, HANDSHAKE_MAX_BODY_BYTES), { passphrase: 'same', kdf: FAST_KDF }), + serverHandshake(right.server, new FrameReader(right.server, HANDSHAKE_MAX_BODY_BYTES), { passphrase: 'same', kdf: FAST_KDF }), + ]); + assert.equal(client.status, 'rejected'); + assert.equal(server.status, 'rejected'); + for (const socket of [left.client, left.server, right.client, right.server]) socket.destroy(); + }); + + it('answers another protocol version with an error code', async () => { + const pair = await socketPair(); + const serverDone = assert.rejects( + serverHandshake(pair.server, new FrameReader(pair.server, HANDSHAKE_MAX_BODY_BYTES), { passphrase: 'x', kdf: FAST_KDF }), + (error: unknown) => error instanceof HandshakeError && error.failure === 'version-mismatch', + ); + const reader = new FrameReader(pair.client, HANDSHAKE_MAX_BODY_BYTES); + pair.client.write(encodeFrame(FrameType.Hello, Buffer.concat([Buffer.from('NETPASTE'), Buffer.of(3, 0), Buffer.alloc(32, 9)]))); + const reply = await reader.next(); + assert.equal(reply.type, FrameType.Error); + assert.equal(reply.body.readUInt8(0), HandshakeErrorCode.VersionMismatch); + await serverDone; + pair.client.destroy(); + }); + + it('rejects a low-order X25519 key', async () => { + const pair = await socketPair(); + const serverDone = serverHandshake(pair.server, new FrameReader(pair.server, HANDSHAKE_MAX_BODY_BYTES), { passphrase: 'x', kdf: FAST_KDF }); + pair.client.write(encodeFrame(FrameType.Hello, Buffer.concat([Buffer.from('NETPASTE'), Buffer.of(2, 0), Buffer.alloc(32)]))); + await assert.rejects(serverDone, IntegrityError); + pair.client.destroy(); + pair.server.destroy(); + }); + + it('turns netpaste 1.x traffic into a protocol error', async () => { + const pair = await socketPair(); + const serverDone = serverHandshake(pair.server, new FrameReader(pair.server, HANDSHAKE_MAX_BODY_BYTES), { passphrase: 'x', kdf: FAST_KDF }); + pair.client.write('3ef272b5cddc68b4154a11c50ed1dd65:83ec914fc393d2a4ac95cfa93475d7fc:143cf00c'); + await assert.rejects(serverDone, (error: unknown) => error instanceof HandshakeError && error.failure === 'protocol'); + pair.client.destroy(); + pair.server.destroy(); + }); +}); diff --git a/test/helpers.ts b/test/helpers.ts new file mode 100644 index 0000000..a1a94db --- /dev/null +++ b/test/helpers.ts @@ -0,0 +1,78 @@ +import { setTimeout as sleep } from 'node:timers/promises'; +import type { Timings } from '../src/config.ts'; +import type { KdfParams } from '../src/crypto.ts'; +import type { Logger } from '../src/log.ts'; + +/** Cheap scrypt cost for tests. Production uses DEFAULT_KDF. */ +export const FAST_KDF: KdfParams = { N: 2 ** 10, r: 8, p: 1 }; + +export const FAST_TIMINGS: Partial = { + handshakeTimeoutMs: 2000, + heartbeatIntervalMs: 100, + idleTimeoutMs: 600, + reconnectMinMs: 50, + reconnectMaxMs: 200, + authFailureDelayMs: 10, + authBlockBaseMs: 400, + authBlockMaxMs: 1000, + connectTimeoutMs: 1000, +}; + +/** + * In-memory clipboard (a ClipboardBackend by its shape). + * `read()` captures the text when the read starts, like a real subprocess. + */ +export class MemoryClipboard { + text: string; + reads = 0; + writes: string[] = []; + readDelayMs = 0; + failReads = false; + failNextWrite = false; + + constructor(text = '') { + this.text = text; + } + + async read(): Promise { + this.reads++; + if (this.failReads) throw new Error("Can't open display"); + const value = this.text; + if (this.readDelayMs > 0) await sleep(this.readDelayMs); + return value; + } + + async write(text: string): Promise { + if (this.failNextWrite) { + this.failNextWrite = false; + throw new Error('pbcopy failed'); + } + this.writes.push(text); + this.text = text; + } +} + +export interface RecordingLogger extends Logger { + lines: Array<{ level: 'info' | 'warn' | 'error' | 'debug'; message: string }>; + has(level: 'info' | 'warn' | 'error' | 'debug', pattern: RegExp): boolean; +} + +export function recordingLogger(): RecordingLogger { + const lines: RecordingLogger['lines'] = []; + return { + lines, + info: (message) => lines.push({ level: 'info', message }), + warn: (message) => lines.push({ level: 'warn', message }), + error: (message) => lines.push({ level: 'error', message }), + debug: (message) => lines.push({ level: 'debug', message }), + has: (level, pattern) => lines.some((line) => line.level === level && pattern.test(line.message)), + }; +} + +export async function waitFor(condition: () => boolean, what: string, timeoutMs = 4000): Promise { + const deadline = Date.now() + timeoutMs; + while (!condition()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for: ${what}`); + await sleep(10); + } +} From f5734a212f1402c9e95b1ba191858e1ade6e0dfb Mon Sep 17 00:00:00 2001 From: Aliaksei Smirnou Date: Thu, 19 Nov 2026 08:34:01 +0100 Subject: [PATCH 3/9] feat: clipboard watcher without trim, echo races or time windows - Text is passed through unchanged; 1.x trimmed indentation and final newlines. - Echo suppression by content instead of a 2-second flag. 1.x lost copies made within 2 s of a received one, echoed copies made about 2 s apart, and a single failed write blocked all later copies. - One sequential poll loop; a read that overlaps a network write is dropped. - After a failed first read, the first successful read is the baseline, so old clipboard content is not sent just because netpaste started. - A failed write resynchronizes instead of sending the old text out as new. Co-Authored-By: Claude Opus 5.5 --- src/clipboard.ts | 154 +++++++++++++++++++++++++++++++++++++++++ test/clipboard.test.ts | 136 ++++++++++++++++++++++++++++++++++++ 2 files changed, 290 insertions(+) create mode 100644 src/clipboard.ts create mode 100644 test/clipboard.test.ts diff --git a/src/clipboard.ts b/src/clipboard.ts new file mode 100644 index 0000000..1f379f5 --- /dev/null +++ b/src/clipboard.ts @@ -0,0 +1,154 @@ +import { EventEmitter } from 'node:events'; +import { setTimeout as sleep } from 'node:timers/promises'; +import type { Logger } from './log.ts'; + +export interface ClipboardBackend { + read(): Promise; + write(text: string): Promise; +} + +/** The system clipboard (pbcopy/pbpaste, wl-clipboard, xsel, PowerShell) through clipboardy. */ +export async function systemClipboard(): Promise { + const { default: clipboardy } = await import('clipboardy'); + return { + read: () => clipboardy.read(), + write: (text) => clipboardy.write(text), + }; +} + +export interface ClipboardWatcherOptions { + intervalMs: number; + log: Logger; +} + +interface ClipboardWatcherEvents { + /** The user changed the local clipboard. Not emitted for text that came from `apply()`. */ + change: [text: string]; +} + +/** + * Polls the clipboard in a sequential loop (one read at a time) and reports local changes. + * + * Echo suppression is content-based: `apply()` records the text it writes, so the next poll + * sees no change. A read that overlaps a write is dropped, because it can return the old text. + * There is no time window, so a local copy right after a received one is not lost. + * + * The hub and the client start the watcher only while a peer is connected: without a peer + * there is nowhere to send the text, so netpaste does not read the clipboard at all. + */ +export class ClipboardWatcher extends EventEmitter { + readonly #backend: ClipboardBackend; + readonly #options: ClipboardWatcherOptions; + #last: string | null = null; + #generation = 0; + #pendingWrites = 0; + #writeQueue: Promise = Promise.resolve(); + #readFailing = false; + #running: AbortController | null = null; + /** The next successful read is the baseline: it is remembered, not reported. */ + #baselinePending = false; + + constructor(backend: ClipboardBackend, options: ClipboardWatcherOptions) { + super(); + this.#backend = backend; + this.#options = options; + } + + get running(): boolean { + return this.#running !== null; + } + + /** + * Takes the current text as the baseline (it is not reported) and starts polling. + * When the first read fails (no display yet), the first successful read becomes the baseline, + * so old clipboard content is never sent out just because netpaste started. + * Does nothing when the watcher already runs. + */ + async start(): Promise { + if (this.#running) return; + const controller = new AbortController(); + this.#running = controller; + this.#baselinePending = true; + await this.poll(); + if (controller.signal.aborted) return; + void this.#loop(controller.signal); + } + + stop(): void { + this.#running?.abort(); + this.#running = null; + } + + /** One polling step. `start()` calls it in a loop; tests call it directly. */ + async poll(): Promise { + if (this.#pendingWrites > 0) return; + const generation = this.#generation; + const text = await this.#read(); + if (text === null) return; + if (generation !== this.#generation || this.#pendingWrites > 0) return; + if (this.#baselinePending) { + this.#baselinePending = false; + this.#last = text; + return; + } + if (text === this.#last) return; + this.#last = text; + // An empty result means a cleared clipboard or non-text content (an image, files): nothing to send. + if (text.length === 0) return; + this.emit('change', text); + } + + /** Writes text from the network to the local clipboard without reporting it as a local change. */ + async apply(text: string): Promise { + this.#baselinePending = false; + if (text === this.#last && this.#pendingWrites === 0) return; + this.#last = text; + this.#generation++; + this.#pendingWrites++; + const write = this.#writeQueue.then(() => this.#backend.write(text)); + this.#writeQueue = write.catch(() => undefined); + try { + await write; + } catch (error) { + this.#options.log.error(`cannot write to the clipboard: ${errorMessage(error)}`); + // Resynchronize with what is really in the clipboard, so the old text is not sent out as "new". + const actual = await this.#read(); + if (actual !== null) this.#last = actual; + } finally { + this.#pendingWrites--; + this.#generation++; + } + } + + async #loop(signal: AbortSignal): Promise { + while (!signal.aborted) { + try { + await sleep(this.#options.intervalMs, undefined, { signal }); + } catch { + return; + } + await this.poll(); + } + } + + async #read(): Promise { + try { + const text = await this.#backend.read(); + if (this.#readFailing) { + this.#readFailing = false; + this.#options.log.info('the clipboard is readable again'); + } + return text; + } catch (error) { + if (!this.#readFailing) { + this.#readFailing = true; + this.#options.log.warn(`cannot read the clipboard: ${errorMessage(error)}`); + } + return null; + } + } +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message.split('\n')[0]! : String(error); +} diff --git a/test/clipboard.test.ts b/test/clipboard.test.ts new file mode 100644 index 0000000..a3f4ca2 --- /dev/null +++ b/test/clipboard.test.ts @@ -0,0 +1,136 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { ClipboardWatcher } from '../src/clipboard.ts'; +import { MemoryClipboard, recordingLogger } from './helpers.ts'; + +function setup(initial = 'initial') { + const backend = new MemoryClipboard(initial); + const log = recordingLogger(); + const watcher = new ClipboardWatcher(backend, { intervalMs: 60_000, log }); + const changes: string[] = []; + watcher.on('change', (text) => changes.push(text)); + return { backend, log, watcher, changes }; +} + +describe('ClipboardWatcher', () => { + it('does not report the text that was there at start', async () => { + const { watcher, changes } = setup(); + await watcher.start(); + await watcher.poll(); + watcher.stop(); + assert.deepEqual(changes, []); + }); + + it('reports a local change once and keeps the text exactly (no trim)', async () => { + const { backend, watcher, changes } = setup(); + await watcher.start(); + const text = ' indented();\n\tmore();\r\n🙂 trailing \n\n'; + backend.text = text; + await watcher.poll(); + await watcher.poll(); + watcher.stop(); + assert.deepEqual(changes, [text]); + }); + + it('does not echo text that came from the network', async () => { + const { backend, watcher, changes } = setup(); + await watcher.start(); + await watcher.apply('from the network'); + assert.equal(backend.text, 'from the network'); + await watcher.poll(); + watcher.stop(); + assert.deepEqual(changes, []); + }); + + it('sends a local copy made right after a received one (1.x lost it for 2 s)', async () => { + const { backend, watcher, changes } = setup(); + await watcher.start(); + await watcher.apply('received'); + backend.text = 'copied 100 ms later'; + await watcher.poll(); + watcher.stop(); + assert.deepEqual(changes, ['copied 100 ms later']); + }); + + it('drops a read that overlapped a network write, so the old text is not sent back', async () => { + const { backend, watcher, changes } = setup('old'); + await watcher.start(); + backend.readDelayMs = 50; + const polling = watcher.poll(); // reads "old", slowly + await watcher.apply('new from network'); + await polling; + backend.readDelayMs = 0; + await watcher.poll(); + watcher.stop(); + assert.deepEqual(changes, []); + assert.equal(backend.text, 'new from network'); + }); + + it('ignores an empty clipboard (cleared, or an image)', async () => { + const { backend, watcher, changes } = setup(); + await watcher.start(); + backend.text = ''; + await watcher.poll(); + watcher.stop(); + assert.deepEqual(changes, []); + }); + + it('after a failed first read, takes the first successful read as the baseline', async () => { + const { backend, watcher, changes } = setup('old private text'); + backend.failReads = true; // for example, the display is not ready yet at login + await watcher.start(); + await watcher.poll(); + backend.failReads = false; + await watcher.poll(); // baseline: not sent + backend.text = 'a real copy'; + await watcher.poll(); + watcher.stop(); + assert.deepEqual(changes, ['a real copy']); + }); + + it('takes a new baseline after stop and start', async () => { + const { backend, watcher, changes } = setup(); + await watcher.start(); + watcher.stop(); + backend.text = 'copied while no peer was connected'; + await watcher.start(); + await watcher.poll(); + watcher.stop(); + assert.deepEqual(changes, []); + }); + + it('logs a read failure once and the recovery once', async () => { + const { backend, log, watcher, changes } = setup(); + await watcher.start(); + backend.failReads = true; + await watcher.poll(); + await watcher.poll(); + backend.failReads = false; + backend.text = 'after recovery'; + await watcher.poll(); + watcher.stop(); + assert.equal(log.lines.filter((line) => line.level === 'warn').length, 1); + assert.ok(log.has('info', /readable again/)); + assert.deepEqual(changes, ['after recovery']); + }); + + it('after a failed write it does not send the old text out as new', async () => { + const { backend, log, watcher, changes } = setup('old'); + await watcher.start(); + backend.failNextWrite = true; + await watcher.apply('lost'); + await watcher.poll(); + watcher.stop(); + assert.ok(log.has('error', /cannot write/)); + assert.deepEqual(changes, []); + }); + + it('serializes writes in arrival order', async () => { + const { backend, watcher } = setup(); + await watcher.start(); + await Promise.all([watcher.apply('one'), watcher.apply('two'), watcher.apply('three')]); + watcher.stop(); + assert.deepEqual(backend.writes, ['one', 'two', 'three']); + assert.equal(backend.text, 'three'); + }); +}); From 97ebf585188ce65e0e87ff81c824c85ca55513da Mon Sep 17 00:00:00 2001 From: Aliaksei Smirnou Date: Thu, 19 Nov 2026 08:34:01 +0100 Subject: [PATCH 4/9] feat: passphrase from a terminal, a file or the environment; CLI parsing Passphrase input in 1.x stored Backspace as \x7f and arrow keys as the text "undefined", so a corrected typo silently gave the machines different passphrases. It also never finished when stdin was a pipe. - Raw-mode line editor: Backspace, Ctrl+U, escape sequences (also split across reads), bracketed paste, Ctrl+C / Ctrl+D. - --passphrase-file (warns about group/world-readable files) and NETPASTE_PASSPHRASE (removed from the environment of child processes). - util.parseArgs with strict validation: no silent fallback to port 8134, flags in any order, per-command options, sizes like 10mb. Co-Authored-By: Claude Opus 5.5 --- src/args.ts | 177 ++++++++++++++++++++++++++++++++++++++++ src/passphrase.ts | 155 +++++++++++++++++++++++++++++++++++ test/args.test.ts | 92 +++++++++++++++++++++ test/passphrase.test.ts | 147 +++++++++++++++++++++++++++++++++ 4 files changed, 571 insertions(+) create mode 100644 src/args.ts create mode 100644 src/passphrase.ts create mode 100644 test/args.test.ts create mode 100644 test/passphrase.test.ts diff --git a/src/args.ts b/src/args.ts new file mode 100644 index 0000000..26d0666 --- /dev/null +++ b/src/args.ts @@ -0,0 +1,177 @@ +import { parseArgs } from 'node:util'; +import { + DEFAULT_MAX_TEXT_BYTES, + DEFAULT_POLL_INTERVAL_MS, + DEFAULT_PORT, + MAX_POLL_INTERVAL_MS, + MAX_TEXT_BYTES_CEILING, + MIN_POLL_INTERVAL_MS, + MIN_TEXT_BYTES, +} from './config.ts'; + +export interface CommonOptions { + passphraseFile: string | undefined; + intervalMs: number; + maxTextBytes: number; + verbose: boolean; +} + +export type Command = + | { name: 'serve'; port: number; host: string | undefined; clipboard: boolean; mdns: boolean; options: CommonOptions } + | { name: 'connect'; target: { host: string; port: number } | null; clipboard: boolean; options: CommonOptions } + | { name: 'discover'; timeoutMs: number; verbose: boolean } + | { name: 'help' } + | { name: 'version' }; + +export class UsageError extends Error { + override name = 'UsageError'; +} + +export const USAGE = `netpaste — encrypted clipboard sync between your machines + +Usage: + netpaste serve [--port N] [--host ADDR] [--no-clipboard] [--no-mdns] + netpaste connect [HOST[:PORT]] [--port N] [--no-clipboard] + netpaste discover [--timeout SEC] + +Run "serve" on one machine and "connect" on the others. Without HOST, +"connect" finds the server on the local network (mDNS). + +Options: + -p, --port N TCP port (default ${DEFAULT_PORT}) + --host ADDR serve: listen only on this address (default: all) + --no-clipboard do not use the local clipboard + (serve: only relay text between clients) + --no-mdns serve: do not announce the server on the network + --passphrase-file F read the passphrase from file F + --interval MS clipboard check interval (default ${DEFAULT_POLL_INTERVAL_MS}) + --max-size SIZE largest text to send or accept (default 10mb) + --timeout SEC discover: search time (default 3) + --verbose show debug messages + -h, --help show this help + -v, --version show the version + +Passphrase: --passphrase-file, else the NETPASTE_PASSPHRASE variable, else a prompt. +Use the same passphrase on all machines.`; + +const OPTIONS = { + port: { type: 'string', short: 'p' }, + host: { type: 'string' }, + 'no-clipboard': { type: 'boolean' }, + 'no-mdns': { type: 'boolean' }, + 'passphrase-file': { type: 'string' }, + interval: { type: 'string' }, + 'max-size': { type: 'string' }, + timeout: { type: 'string' }, + verbose: { type: 'boolean' }, + help: { type: 'boolean', short: 'h' }, + version: { type: 'boolean', short: 'v' }, +} as const; + +type OptionName = keyof typeof OPTIONS; + +const ALLOWED: Record<'serve' | 'connect' | 'discover', readonly OptionName[]> = { + serve: ['port', 'host', 'no-clipboard', 'no-mdns', 'passphrase-file', 'interval', 'max-size', 'verbose'], + connect: ['port', 'no-clipboard', 'passphrase-file', 'interval', 'max-size', 'verbose'], + discover: ['timeout', 'verbose'], +}; + +export function parseCommandLine(argv: readonly string[]): Command { + let parsed; + try { + parsed = parseArgs({ args: [...argv], options: OPTIONS, allowPositionals: true, strict: true }); + } catch (error) { + throw new UsageError((error as Error).message); + } + const { values, positionals } = parsed; + if (values.help) return { name: 'help' }; + if (values.version) return { name: 'version' }; + + const [name, ...rest] = positionals; + if (name === undefined || name === 'help') return { name: 'help' }; + if (name === 'version') return { name: 'version' }; + if (name !== 'serve' && name !== 'connect' && name !== 'discover') { + throw new UsageError(`unknown command "${name}"`); + } + for (const option of Object.keys(values) as OptionName[]) { + if (!ALLOWED[name].includes(option)) throw new UsageError(`option --${option} does not apply to "${name}"`); + } + + const verbose = values.verbose ?? false; + if (name === 'discover') { + if (rest.length > 0) throw new UsageError('"discover" takes no arguments'); + const seconds = values.timeout === undefined ? 3 : parseNumber(values.timeout, '--timeout', 0.5, 60); + return { name, timeoutMs: Math.round(seconds * 1000), verbose }; + } + + const options: CommonOptions = { + passphraseFile: values['passphrase-file'], + intervalMs: + values.interval === undefined + ? DEFAULT_POLL_INTERVAL_MS + : Math.round(parseNumber(values.interval, '--interval', MIN_POLL_INTERVAL_MS, MAX_POLL_INTERVAL_MS)), + maxTextBytes: values['max-size'] === undefined ? DEFAULT_MAX_TEXT_BYTES : parseSize(values['max-size']), + verbose, + }; + const clipboard = !values['no-clipboard']; + const flagPort = values.port === undefined ? undefined : parsePort(values.port); + + if (name === 'serve') { + if (rest.length > 0) throw new UsageError(`unexpected argument "${rest[0]}" for "serve"`); + return { name, port: flagPort ?? DEFAULT_PORT, host: values.host, clipboard, mdns: !values['no-mdns'], options }; + } + + if (rest.length > 1) throw new UsageError(`unexpected argument "${rest[1]}" for "connect"`); + const target = rest[0] === undefined ? null : parseTarget(rest[0], flagPort); + if (!target && flagPort !== undefined) throw new UsageError('--port needs a HOST; without HOST the port comes from mDNS'); + return { name, target, clipboard, options }; +} + +/** "host", "host:port", "[v6]:port", "v6" (a bare IPv6 address has more than one colon). */ +export function parseTarget(value: string, flagPort?: number): { host: string; port: number } { + let host = value; + let port: number | undefined; + const bracketed = /^\[([^\]]+)\](?::(.*))?$/.exec(value); + if (bracketed) { + host = bracketed[1]!; + if (bracketed[2] !== undefined) port = parsePort(bracketed[2]); + } else if (value.split(':').length === 2) { + const [h, p] = value.split(':') as [string, string]; + host = h; + port = parsePort(p); + } + if (host.length === 0) throw new UsageError(`invalid host "${value}"`); + if (port !== undefined && flagPort !== undefined && port !== flagPort) { + throw new UsageError(`port ${port} in "${value}" conflicts with --port ${flagPort}`); + } + return { host, port: port ?? flagPort ?? DEFAULT_PORT }; +} + +export function parsePort(value: string): number { + if (!/^\d+$/.test(value)) throw new UsageError(`invalid port "${value}"`); + const port = Number(value); + if (port < 1 || port > 65535) throw new UsageError(`port must be 1–65535, got ${value}`); + return port; +} + +const UNITS: Record = { '': 1, b: 1, k: 1024, kb: 1024, kib: 1024, m: 1024 ** 2, mb: 1024 ** 2, mib: 1024 ** 2 }; + +/** "10mb", "512k", "1048576" → bytes (binary units). */ +export function parseSize(value: string): number { + const match = /^(\d+(?:\.\d+)?)\s*([a-z]*)$/i.exec(value.trim()); + const unit = match ? UNITS[match[2]!.toLowerCase()] : undefined; + if (!match || unit === undefined) throw new UsageError(`invalid size "${value}" (examples: 512kb, 10mb)`); + const bytes = Math.floor(Number(match[1]) * unit); + if (bytes < MIN_TEXT_BYTES || bytes > MAX_TEXT_BYTES_CEILING) { + throw new UsageError(`--max-size must be between 1kb and ${MAX_TEXT_BYTES_CEILING / 1024 ** 2}mb`); + } + return bytes; +} + +function parseNumber(value: string, option: string, min: number, max: number): number { + const number = Number(value); + if (!Number.isFinite(number) || number < min || number > max) { + throw new UsageError(`${option} must be a number between ${min} and ${max}`); + } + return number; +} diff --git a/src/passphrase.ts b/src/passphrase.ts new file mode 100644 index 0000000..219002c --- /dev/null +++ b/src/passphrase.ts @@ -0,0 +1,155 @@ +import { readFile, stat } from 'node:fs/promises'; +import type { Logger } from './log.ts'; + +export const PASSPHRASE_ENV = 'NETPASTE_PASSPHRASE'; +const RECOMMENDED_LENGTH = 12; + +export class PassphraseError extends Error { + override name = 'PassphraseError'; +} + +export class PromptCancelledError extends Error { + override name = 'PromptCancelledError'; +} + +export interface PassphraseSources { + /** Path from --passphrase-file. It wins over the environment variable. */ + file?: string | undefined; + env: NodeJS.ProcessEnv; + stdin: NodeJS.ReadStream; + prompt: NodeJS.WritableStream; + log: Logger; +} + +/** Order: --passphrase-file, then NETPASTE_PASSPHRASE, then a hidden prompt on the terminal. */ +export async function resolvePassphrase({ file, env, stdin, prompt, log }: PassphraseSources): Promise { + let passphrase: string; + if (file) { + passphrase = await readPassphraseFile(file, log); + } else if (env[PASSPHRASE_ENV]) { + passphrase = env[PASSPHRASE_ENV]; + // Child processes (pbcopy, xsel …) do not need it. + delete env[PASSPHRASE_ENV]; + } else if (stdin.isTTY) { + passphrase = await promptHidden('Passphrase: ', stdin, prompt); + } else { + throw new PassphraseError(`no passphrase: stdin is not a terminal. Use --passphrase-file or set ${PASSPHRASE_ENV}.`); + } + if (passphrase.length === 0) throw new PassphraseError('the passphrase is empty'); + if ([...passphrase].length < RECOMMENDED_LENGTH) { + log.warn(`the passphrase is short; use ${RECOMMENDED_LENGTH}+ characters or 4+ random words`); + } + return passphrase; +} + +export async function readPassphraseFile(path: string, log: Logger): Promise { + let content: string; + try { + const info = await stat(path); + if (process.platform !== 'win32' && (info.mode & 0o077) !== 0) { + log.warn(`${path} can be read by other users; run: chmod 600 ${path}`); + } + content = await readFile(path, 'utf8'); + } catch (error) { + throw new PassphraseError(`cannot read the passphrase file: ${(error as Error).message}`); + } + // Editors add a final newline; it is not part of the passphrase. + return content.replace(/\r?\n$/, ''); +} + +export function promptHidden(question: string, input: NodeJS.ReadStream, output: NodeJS.WritableStream): Promise { + return new Promise((resolve, reject) => { + const editor = new HiddenLineEditor(); + const wasRaw = input.isRaw; + output.write(question); + input.setRawMode(true); + input.setEncoding('utf8'); + const onData = (data: string) => { + const echo = editor.feed(data); + if (echo) output.write(echo); + if (!editor.done && !editor.cancelled) return; + input.off('data', onData); + input.setRawMode(wasRaw); + input.pause(); + output.write('\n'); + if (editor.cancelled) reject(new PromptCancelledError('cancelled')); + else resolve(editor.value); + }; + input.on('data', onData); + input.resume(); + }); +} + +/** + * Minimal line editor for a hidden input in raw terminal mode. It prints "*" for each character. + * - Enter ends the input; Ctrl+C cancels; Ctrl+D on an empty line cancels. + * - Backspace deletes one character (a whole code point, also an emoji); Ctrl+U clears the line. + * - Escape sequences (arrows, Home, F-keys, bracketed-paste markers) are skipped, + * also when a sequence is split between two reads. + */ +export class HiddenLineEditor { + #chars: string[] = []; + #escape: string | null = null; + done = false; + cancelled = false; + + get value(): string { + return this.#chars.join(''); + } + + /** Processes raw input and returns the text to echo. */ + feed(input: string): string { + let echo = ''; + for (const ch of input) { + if (this.done || this.cancelled) break; + if (this.#escape !== null) { + this.#escape += ch; + if (isCompleteEscape(this.#escape)) this.#escape = null; + continue; + } + switch (ch) { + case '\r': + case '\n': + this.done = true; + break; + case '\u0003': // Ctrl+C + this.cancelled = true; + break; + case '\u0004': // Ctrl+D + if (this.#chars.length === 0) this.cancelled = true; + break; + case '\u007f': // Backspace on most terminals + case '\b': + if (this.#chars.pop() !== undefined) echo += '\b \b'; + break; + case '\u0015': // Ctrl+U + echo += '\b \b'.repeat(this.#chars.length); + this.#chars = []; + break; + case '\u001b': + this.#escape = ch; + break; + default: + if (!/\p{Cc}/u.test(ch)) { + this.#chars.push(ch); + echo += '*'; + } + } + } + return echo; + } +} + +/** ESC x (Alt+key), ESC O x (SS3), ESC [ params final (CSI, final byte 0x40–0x7E). */ +function isCompleteEscape(sequence: string): boolean { + if (sequence.length < 2) return false; + const kind = sequence[1]; + if (kind === '[') { + // "ESC [ [ A" is how the Linux console sends F1–F5. + if (sequence.length < 3 || sequence === '\u001b[[') return false; + const last = sequence.charCodeAt(sequence.length - 1); + return last >= 0x40 && last <= 0x7e; + } + if (kind === 'O') return sequence.length >= 3; + return true; +} diff --git a/test/args.test.ts b/test/args.test.ts new file mode 100644 index 0000000..7c974ea --- /dev/null +++ b/test/args.test.ts @@ -0,0 +1,92 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { UsageError, parseCommandLine, parseSize, parseTarget } from '../src/args.ts'; + +describe('parseCommandLine', () => { + it('parses serve with defaults and with all options', () => { + assert.deepEqual(parseCommandLine(['serve']), { + name: 'serve', + port: 8134, + host: undefined, + clipboard: true, + mdns: true, + options: { passphraseFile: undefined, intervalMs: 1000, maxTextBytes: 10 * 1024 * 1024, verbose: false }, + }); + const command = parseCommandLine(['serve', '-p', '9000', '--host', '127.0.0.1', '--no-clipboard', '--no-mdns', '--max-size', '1mb']); + assert.equal(command.name, 'serve'); + if (command.name !== 'serve') return; + assert.equal(command.port, 9000); + assert.equal(command.host, '127.0.0.1'); + assert.equal(command.clipboard, false); + assert.equal(command.mdns, false); + assert.equal(command.options.maxTextBytes, 1024 * 1024); + }); + + it('parses connect with and without a host', () => { + const withHost = parseCommandLine(['connect', 'box.local:9000', '--interval', '250']); + assert.ok(withHost.name === 'connect'); + assert.deepEqual(withHost.target, { host: 'box.local', port: 9000 }); + assert.equal(withHost.options.intervalMs, 250); + const discovered = parseCommandLine(['connect']); + assert.ok(discovered.name === 'connect'); + assert.equal(discovered.target, null); + }); + + it('accepts flags before the host (1.x took "--no-clipboard" as the host name)', () => { + const command = parseCommandLine(['connect', '--no-clipboard', 'box']); + assert.ok(command.name === 'connect'); + assert.deepEqual(command.target, { host: 'box', port: 8134 }); + assert.equal(command.clipboard, false); + }); + + it('rejects bad input instead of silently using port 8134', () => { + for (const argv of [ + ['connect', 'box', 'extra'], + ['connect', 'box:abc'], + ['connect', 'box', '--port', '0'], + ['connect', 'box:9000', '--port', '9001'], + ['connect', '--port', '9000'], + ['serve', '--port', '70000'], + ['serve', '--timeout', '3'], + ['serve', '--unknown'], + ['serve', '--interval', '5'], + ['discover', 'host'], + ['launch'], + ]) { + assert.throws(() => parseCommandLine(argv), UsageError, argv.join(' ')); + } + }); + + it('shows help and version', () => { + assert.deepEqual(parseCommandLine([]), { name: 'help' }); + assert.deepEqual(parseCommandLine(['serve', '--help']), { name: 'help' }); + assert.deepEqual(parseCommandLine(['-v']), { name: 'version' }); + }); + + it('parses discover', () => { + assert.deepEqual(parseCommandLine(['discover', '--timeout', '1.5']), { name: 'discover', timeoutMs: 1500, verbose: false }); + }); +}); + +describe('parseTarget', () => { + it('handles IPv4, names, IPv6 with and without brackets', () => { + assert.deepEqual(parseTarget('192.168.1.5'), { host: '192.168.1.5', port: 8134 }); + assert.deepEqual(parseTarget('[::1]:9000'), { host: '::1', port: 9000 }); + assert.deepEqual(parseTarget('[fe80::1]'), { host: 'fe80::1', port: 8134 }); + assert.deepEqual(parseTarget('fe80::1'), { host: 'fe80::1', port: 8134 }); + assert.deepEqual(parseTarget('box', 9100), { host: 'box', port: 9100 }); + }); +}); + +describe('parseSize', () => { + it('understands units', () => { + assert.equal(parseSize('10mb'), 10 * 1024 * 1024); + assert.equal(parseSize('512KB'), 512 * 1024); + assert.equal(parseSize('0.5m'), 512 * 1024); + assert.equal(parseSize('4096'), 4096); + }); + + it('rejects junk and out-of-range values', () => { + for (const value of ['abc', '10tb', '1b', '1000mb', '']) assert.throws(() => parseSize(value), UsageError, value); + }); +}); diff --git a/test/passphrase.test.ts b/test/passphrase.test.ts new file mode 100644 index 0000000..340da62 --- /dev/null +++ b/test/passphrase.test.ts @@ -0,0 +1,147 @@ +import assert from 'node:assert/strict'; +import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { PassThrough } from 'node:stream'; +import { after, before, describe, it } from 'node:test'; +import { + HiddenLineEditor, + PassphraseError, + PromptCancelledError, + promptHidden, + resolvePassphrase, +} from '../src/passphrase.ts'; +import { recordingLogger } from './helpers.ts'; + +function typed(...chunks: string[]): HiddenLineEditor { + const editor = new HiddenLineEditor(); + for (const chunk of chunks) editor.feed(chunk); + return editor; +} + +describe('HiddenLineEditor', () => { + it('handles Backspace (1.x stored it as \\x7f)', () => { + const editor = typed('ab\u007fc\r'); + assert.equal(editor.done, true); + assert.equal(editor.value, 'ac'); + }); + + it('ignores arrow keys (1.x appended "undefined")', () => { + assert.equal(typed('ab\u001b[Dc\u001b[A\u001bOB\r').value, 'abc'); + }); + + it('ignores an escape sequence split between reads', () => { + assert.equal(typed('ab\u001b', '[', '1;5D', 'c\r').value, 'abc'); + }); + + it('ignores Linux console F-keys and Alt+key', () => { + assert.equal(typed('a\u001b[[Ab\u001bxc\r').value, 'abc'); + }); + + it('keeps a pasted passphrase and drops the bracketed-paste markers', () => { + assert.equal(typed('\u001b[200~correct horse battery\u001b[201~\r').value, 'correct horse battery'); + }); + + it('clears the line with Ctrl+U', () => { + assert.equal(typed('wrong\u0015right\n').value, 'right'); + }); + + it('deletes a whole emoji with one Backspace', () => { + assert.equal(typed('a🙂\u007f\r').value, 'a'); + }); + + it('cancels with Ctrl+C, and with Ctrl+D on an empty line', () => { + assert.equal(typed('abc\u0003').cancelled, true); + assert.equal(typed('\u0004').cancelled, true); + assert.equal(typed('a\u0004').cancelled, false); + }); + + it('echoes stars and erases them', () => { + const editor = new HiddenLineEditor(); + assert.equal(editor.feed('ab'), '**'); + assert.equal(editor.feed('\u007f'), '\b \b'); + }); +}); + +function fakeTty(): NodeJS.ReadStream { + const stream = new PassThrough() as unknown as NodeJS.ReadStream & { isRaw: boolean }; + stream.isTTY = true; + stream.isRaw = false; + stream.setRawMode = function (mode: boolean) { + this.isRaw = mode; + return this; + }; + return stream; +} + +describe('promptHidden', () => { + it('reads a line in raw mode and restores the mode', async () => { + const input = fakeTty(); + const output = new PassThrough(); + const answer = promptHidden('Passphrase: ', input, output); + input.push('se\u007fecret\r'); + assert.equal(await answer, 'secret'); + assert.equal(input.isRaw, false); + }); + + it('rejects on Ctrl+C', async () => { + const input = fakeTty(); + const answer = promptHidden('Passphrase: ', input, new PassThrough()); + input.push('\u0003'); + await assert.rejects(answer, PromptCancelledError); + }); +}); + +describe('resolvePassphrase', () => { + let dir = ''; + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), 'netpaste-test-')); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + const notTty = () => Object.assign(new PassThrough(), { isTTY: false }) as unknown as NodeJS.ReadStream; + + it('prefers --passphrase-file and strips one final newline', async () => { + const file = path.join(dir, 'pass'); + await writeFile(file, 'from file with spaces \n\n', { mode: 0o600 }); + const env = { NETPASTE_PASSPHRASE: 'from env' }; + const result = await resolvePassphrase({ file, env, stdin: notTty(), prompt: new PassThrough(), log: recordingLogger() }); + assert.equal(result, 'from file with spaces \n'); + }); + + it('uses NETPASTE_PASSPHRASE and removes it from the environment', async () => { + const env: NodeJS.ProcessEnv = { NETPASTE_PASSPHRASE: 'correct horse battery staple' }; + const result = await resolvePassphrase({ env, stdin: notTty(), prompt: new PassThrough(), log: recordingLogger() }); + assert.equal(result, 'correct horse battery staple'); + assert.equal(env.NETPASTE_PASSPHRASE, undefined); + }); + + it('warns about a file that other users can read', { skip: process.platform === 'win32' }, async () => { + const file = path.join(dir, 'open'); + await writeFile(file, 'correct horse battery staple\n'); + await chmod(file, 0o644); + const log = recordingLogger(); + await resolvePassphrase({ file, env: {}, stdin: notTty(), prompt: new PassThrough(), log }); + assert.ok(log.has('warn', /chmod 600/)); + }); + + it('warns about a short passphrase', async () => { + const log = recordingLogger(); + await resolvePassphrase({ env: { NETPASTE_PASSPHRASE: 'short' }, stdin: notTty(), prompt: new PassThrough(), log }); + assert.ok(log.has('warn', /short/)); + }); + + it('fails without a terminal and without other sources (1.x hung here)', async () => { + await assert.rejects(resolvePassphrase({ env: {}, stdin: notTty(), prompt: new PassThrough(), log: recordingLogger() }), PassphraseError); + }); + + it('fails on an empty file and on a missing file', async () => { + const empty = path.join(dir, 'empty'); + await writeFile(empty, '\n', { mode: 0o600 }); + const sources = { env: {}, stdin: notTty(), prompt: new PassThrough(), log: recordingLogger() }; + await assert.rejects(resolvePassphrase({ ...sources, file: empty }), PassphraseError); + await assert.rejects(resolvePassphrase({ ...sources, file: path.join(dir, 'missing') }), PassphraseError); + }); +}); From 22c97d58a7aa29d73ee91c5a4fba604bfbe2b6cc Mon Sep 17 00:00:00 2001 From: Aliaksei Smirnou Date: Thu, 19 Nov 2026 08:34:01 +0100 Subject: [PATCH 5/9] feat: mDNS discovery of the hub The hub announces _netpaste._tcp; "netpaste connect" without HOST finds it. Two problems of bonjour-service are worked around: - It announces A/AAAA records for os.hostname(). On macOS that is the name that mDNSResponder owns, so macOS renames the computer (Name-2.local). We announce a unique SRV target, netpaste--.local. - It does not listen for 'error' on its multicast socket, so a busy UDP port would crash the process. We report it as a warning instead. Co-Authored-By: Claude Opus 5.5 --- src/discovery.ts | 116 +++++++++++++++++++++++++++++++++++++++++ test/discovery.test.ts | 88 +++++++++++++++++++++++++++++++ 2 files changed, 204 insertions(+) create mode 100644 src/discovery.ts create mode 100644 test/discovery.test.ts diff --git a/src/discovery.ts b/src/discovery.ts new file mode 100644 index 0000000..f1c7516 --- /dev/null +++ b/src/discovery.ts @@ -0,0 +1,116 @@ +/** + * LAN discovery with mDNS / DNS-SD: the server announces `_netpaste._tcp.local`, + * `netpaste connect` without HOST looks for it. + * + * mDNS is not authenticated: any device on the network can announce a service. + * A fake server still cannot pass the handshake, but see docs/PROTOCOL.md about offline guessing. + */ +import crypto from 'node:crypto'; +import net from 'node:net'; +import { setTimeout as sleep } from 'node:timers/promises'; +import Bonjour from 'bonjour-service'; +import { MDNS_SERVICE_TYPE, PROTOCOL_VERSION } from './config.ts'; +import { type Logger, sanitizeForTerminal } from './log.ts'; + +export interface FoundServer { + name: string; + host: string; + port: number; +} + +export interface MdnsTransport { + /** multicast-dns options. Tests use a private port on the loopback interface. */ + interface?: string; + bind?: string; + port?: number; + reuseAddr?: boolean; +} + +export interface Advertisement { + stop(): Promise; +} + +type BonjourOptions = ConstructorParameters[0]; + +/** + * bonjour-service does not listen for 'error' on its multicast-dns socket, so a failed bind + * (UDP 5353 taken, no permission) would be an uncaught exception that stops netpaste. + */ +function createBonjour(transport: MdnsTransport | undefined, onError: (error: Error) => void): Bonjour { + const bonjour = new Bonjour(transport as BonjourOptions, onError); + const mdns = (bonjour as unknown as { server?: { mdns?: NodeJS.EventEmitter } }).server?.mdns; + mdns?.on('error', onError); + mdns?.on('warning', () => undefined); + return bonjour; +} + +/** + * The SRV target host name, unique to this process. + * + * bonjour-service uses os.hostname() by default and announces A/AAAA records for it. + * On macOS that is "Name.local", which mDNSResponder already owns: it sees a conflict and + * renames the computer ("Name-2.local"). Avahi on Linux can react the same way. + * Our own name avoids the conflict; clients use the addresses from the answer anyway. + */ +export function serviceHostName(name: string, suffix = crypto.randomBytes(3).toString('hex')): string { + const slug = name.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'host'; + return `netpaste-${slug}-${suffix}.local`; +} + +export function advertise(port: number, name: string, log: Logger, transport?: MdnsTransport): Advertisement { + const report = (error: Error) => log.warn(`mDNS announcement failed: ${error.message}`); + const bonjour = createBonjour(transport, report); + const service = bonjour.publish({ + name, + host: serviceHostName(name), + type: MDNS_SERVICE_TYPE, + port, + txt: { v: String(PROTOCOL_VERSION) }, + }); + service.on('error', report); + let stopped: Promise | null = null; + return { + stop() { + stopped ??= Promise.race([ + new Promise((resolve) => bonjour.unpublishAll(() => bonjour.destroy(() => resolve()))), + sleep(1500), + ]); + return stopped; + }, + }; +} + +export async function discoverServers(timeoutMs: number, transport?: MdnsTransport): Promise { + let failure: Error | null = null; + const bonjour = createBonjour(transport, (error: Error) => { + failure ??= error; + }); + const found = new Map(); + const browser = bonjour.find({ type: MDNS_SERVICE_TYPE }, (service) => { + const txt = (service.txt ?? {}) as Record; + if (String(txt.v) !== String(PROTOCOL_VERSION)) return; + const host = pickAddress(service.addresses ?? [], service.referer?.address); + if (!host || !Number.isInteger(service.port)) return; + const name = sanitizeForTerminal(service.name) || 'unnamed'; + found.set(`${name}|${host}|${service.port}`, { name, host, port: service.port }); + }); + await sleep(timeoutMs); + browser.stop(); + await Promise.race([new Promise((resolve) => bonjour.destroy(() => resolve())), sleep(1000)]); + if (failure && found.size === 0) throw new Error(`mDNS search failed: ${(failure as Error).message}`); + return [...found.values()].sort((a, b) => a.name.localeCompare(b.name) || a.host.localeCompare(b.host)); +} + +/** + * Chooses the address to connect to. Prefers the address the answer came from: the server + * announces all its interfaces (Docker bridges and VPNs too), but it answers from the one + * that faces us. Then IPv4, then a non-link-local IPv6 address (link-local needs a zone index). + */ +export function pickAddress(addresses: readonly string[], referer?: string): string | null { + if (referer && net.isIPv4(referer)) return referer; + const ipv4 = addresses.find((address) => net.isIPv4(address)); + if (ipv4) return ipv4; + const ipv6 = addresses.find((address) => net.isIPv6(address) && !/^fe[89ab]/i.test(address)); + if (ipv6) return ipv6; + return referer && net.isIP(referer) ? referer : null; +} diff --git a/test/discovery.test.ts b/test/discovery.test.ts new file mode 100644 index 0000000..99e5ae3 --- /dev/null +++ b/test/discovery.test.ts @@ -0,0 +1,88 @@ +import assert from 'node:assert/strict'; +import dgram from 'node:dgram'; +import { once } from 'node:events'; +import os from 'node:os'; +import { describe, it } from 'node:test'; +import { setTimeout as sleep } from 'node:timers/promises'; +import Bonjour from 'bonjour-service'; +import { advertise, discoverServers, pickAddress, serviceHostName } from '../src/discovery.ts'; +import { recordingLogger, waitFor } from './helpers.ts'; + +describe('pickAddress', () => { + it('prefers the address the answer came from', () => { + assert.equal(pickAddress(['172.17.0.1', '192.168.1.5'], '192.168.1.5'), '192.168.1.5'); + assert.equal(pickAddress(['192.168.1.5'], '127.0.0.1'), '127.0.0.1'); + }); + + it('falls back to IPv4, then to a routable IPv6 address', () => { + assert.equal(pickAddress(['fe80::1', '192.168.1.5']), '192.168.1.5'); + assert.equal(pickAddress(['fe80::1', '2001:db8::5']), '2001:db8::5'); + assert.equal(pickAddress(['fe80::1']), null); + }); +}); + +// Real multicast on the loopback interface and a private port, so nothing leaves this machine. +// CI runners often have no multicast; set NETPASTE_TEST_MDNS=1 to force the test there. +const skipLive = process.env.CI !== undefined && process.env.NETPASTE_TEST_MDNS !== '1'; +const privateTransport = () => ({ interface: '127.0.0.1', bind: '0.0.0.0', port: 20000 + Math.floor(Math.random() * 20000) }); + +describe('mDNS', () => { + it('finds an announced server', { skip: skipLive }, async () => { + const transport = privateTransport(); + const log = recordingLogger(); + const announcement = advertise(9555, 'test-hub', log, transport); + try { + const servers = await discoverServers(1500, transport); + assert.deepEqual( + servers.filter((server) => server.name === 'test-hub'), + [{ name: 'test-hub', host: '127.0.0.1', port: 9555 }], + ); + } finally { + await announcement.stop(); + } + assert.equal(log.lines.filter((line) => line.level === 'warn' || line.level === 'error').length, 0); + }); + + it('never announces records for the computer host name (macOS would rename the computer)', { skip: skipLive }, async () => { + const transport = privateTransport(); + const sniffer = new Bonjour(transport as ConstructorParameters[0]); + const mdns = (sniffer as unknown as { server: { mdns: NodeJS.EventEmitter } }).server.mdns; + const records: Array<{ name: string; type: string; data: unknown }> = []; + mdns.on('response', (packet: { answers: typeof records; additionals: typeof records }) => { + records.push(...packet.answers, ...packet.additionals); + }); + const announcement = advertise(9556, 'Aliaksei MacBook', recordingLogger(), transport); + const browser = sniffer.find({ type: 'netpaste' }); + await sleep(1500); + browser.stop(); + await announcement.stop(); + await new Promise((resolve) => sniffer.destroy(() => resolve())); + + const own = os.hostname().toLowerCase().replace(/\.local$/, ''); + const names = records.map((record) => record.name.toLowerCase()); + assert.ok(names.length > 0, 'the announcement was captured'); + assert.ok(!names.some((name) => name === own || name === `${own}.local`), `no record for ${own}.local`); + const srv = records.find((record) => record.type === 'SRV'); + assert.match((srv?.data as { target: string }).target, /^netpaste-aliaksei-macbook-[0-9a-f]{6}\.local$/); + }); + + it('builds a valid DNS label for the service host', () => { + assert.equal(serviceHostName('Aliaksei’s MacBook Pro', 'abc123'), 'netpaste-aliaksei-s-macbook-pro-abc123.local'); + assert.equal(serviceHostName('***', 'abc123'), 'netpaste-host-abc123.local'); + }); + + it('reports a busy mDNS port as a warning instead of crashing', async () => { + const blocker = dgram.createSocket({ type: 'udp4', reuseAddr: false }); + blocker.bind(0, '0.0.0.0'); + await once(blocker, 'listening'); + const transport = { ...privateTransport(), port: blocker.address().port, reuseAddr: false }; + const log = recordingLogger(); + const announcement = advertise(9555, 'blocked-hub', log, transport); + try { + await waitFor(() => log.has('warn', /mDNS announcement failed/), 'warning about the busy port'); + } finally { + await announcement.stop(); + blocker.close(); + } + }); +}); From c5c2695c4b4e644cadeca20bfbb37f166510ed4b Mon Sep 17 00:00:00 2001 From: Aliaksei Smirnou Date: Thu, 19 Nov 2026 08:34:01 +0100 Subject: [PATCH 6/9] feat: hub with relay, reconnecting client, heartbeats, netpaste CLI - netpaste serve | connect [HOST[:PORT]] | discover - The hub relays text from one client to all others (1.x did not); --no-clipboard turns it into a pure relay. - The client reconnects with exponential backoff and jitter. 1.x crashed on its first reconnect: setTimeout(createConnection) passed no arguments. - PING/PONG heartbeats, idle timeout and TCP keepalive detect dead peers after sleep or a network change. - One clipboard poller per process, active only while a peer is connected. 1.x started a new poller per connection and never stopped it. - After a wrong passphrase the hub blocks the address, 1 s doubling to 60 s. - Clear errors and exit codes: wrong passphrase, busy port, old protocol, no TTY. - bin/netpaste.js checks the Node.js version before it loads TypeScript. Co-Authored-By: Claude Opus 5.5 --- bin/netpaste.js | 8 ++ src/cli.ts | 15 +++ src/client.ts | 216 +++++++++++++++++++++++++++++++++++++++++ src/main.ts | 174 +++++++++++++++++++++++++++++++++ src/server.ts | 215 +++++++++++++++++++++++++++++++++++++++++ src/session.ts | 199 ++++++++++++++++++++++++++++++++++++++ test/e2e.test.ts | 243 +++++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 1070 insertions(+) create mode 100755 bin/netpaste.js create mode 100644 src/cli.ts create mode 100644 src/client.ts create mode 100644 src/main.ts create mode 100644 src/server.ts create mode 100644 src/session.ts create mode 100644 test/e2e.test.ts diff --git a/bin/netpaste.js b/bin/netpaste.js new file mode 100755 index 0000000..f063533 --- /dev/null +++ b/bin/netpaste.js @@ -0,0 +1,8 @@ +#!/usr/bin/env node +// Plain JavaScript on purpose: it runs on any Node.js version and explains what is missing. +const [major, minor] = process.versions.node.split('.').map(Number); +if (major < 22 || (major === 22 && minor < 18)) { + console.error(`netpaste needs Node.js 22.18 or newer (it runs TypeScript directly); this is Node.js ${process.versions.node}.`); + process.exit(1); +} +await import('../src/cli.ts'); diff --git a/src/cli.ts b/src/cli.ts new file mode 100644 index 0000000..4d339c4 --- /dev/null +++ b/src/cli.ts @@ -0,0 +1,15 @@ +import { main } from './main.ts'; + +try { + const code = await main({ + argv: process.argv.slice(2), + env: process.env, + stdin: process.stdin, + stdout: process.stdout, + stderr: process.stderr, + }); + process.exit(code); +} catch (error) { + process.stderr.write(`netpaste: unexpected error\n${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`); + process.exit(1); +} diff --git a/src/client.ts b/src/client.ts new file mode 100644 index 0000000..6c84796 --- /dev/null +++ b/src/client.ts @@ -0,0 +1,216 @@ +/** + * The client: connects to a hub, keeps the connection alive, and reconnects with backoff. + * + * connect ─▶ handshake ─▶ session ─▶ (connection lost) ─▶ wait 1, 2, 4 … 30 s ─▶ connect + * │ + * └─ wrong passphrase / other protocol version ─▶ stop with an error + */ +import { EventEmitter, once } from 'node:events'; +import net from 'node:net'; +import { setTimeout as sleep } from 'node:timers/promises'; +import type { ClipboardWatcher } from './clipboard.ts'; +import { DEFAULT_TIMINGS, type Timings } from './config.ts'; +import type { KdfParams } from './crypto.ts'; +import { FrameReader } from './frame-reader.ts'; +import { HANDSHAKE_MAX_BODY_BYTES, HandshakeError, clientHandshake } from './handshake.ts'; +import { type Logger, formatCount } from './log.ts'; +import { Session, formatAddress } from './session.ts'; + +export interface Target { + host: string; + port: number; +} + +export interface ClientOptions { + /** Server address; null = call `findServer` before every connection attempt. */ + target: Target | null; + findServer?: (() => Promise) | undefined; + passphrase: string; + /** null = do not use the local clipboard (only log what arrives). */ + clipboard: ClipboardWatcher | null; + maxTextBytes: number; + localName: string; + version: string; + log: Logger; + timings?: Partial; + kdf?: KdfParams; +} + +interface ClientEvents { + connected: [session: Session]; + disconnected: [session: Session, error: Error | null]; +} + +/** An error that retrying cannot fix, for example a wrong passphrase. */ +export class FatalError extends Error { + override name = 'FatalError'; +} + +export class Client extends EventEmitter { + readonly #options: ClientOptions; + readonly #timings: Timings; + readonly #stop = new AbortController(); + #session: Session | null = null; + #socket: net.Socket | null = null; + + constructor(options: ClientOptions) { + super(); + if (!options.target && !options.findServer) throw new TypeError('either target or findServer is required'); + this.#options = options; + this.#timings = { ...DEFAULT_TIMINGS, ...options.timings }; + options.clipboard?.on('change', (text) => this.#onLocalChange(text)); + } + + get session(): Session | null { + return this.#session; + } + + /** Connects and reconnects until `close()`. Rejects with `FatalError` when retrying cannot help. */ + async run(): Promise { + const { signal } = this.#stop; + const { log } = this.#options; + let attempt = 0; + while (!signal.aborted) { + let where = 'server'; + try { + const target = this.#options.target ?? (await this.#options.findServer!()); + where = formatAddress(target.host, target.port); + if (await this.#connectOnce(target)) attempt = 0; + } catch (error) { + if (signal.aborted) break; + const fatal = toFatal(error); + if (fatal) throw fatal; + logRetry(log, where, error); + } + if (signal.aborted) break; + const wait = backoffDelay(attempt++, this.#timings.reconnectMinMs, this.#timings.reconnectMaxMs); + log.info(`reconnecting in ${(wait / 1000).toFixed(1)} s`); + try { + await sleep(wait, undefined, { signal }); + } catch { + break; + } + } + } + + async close(): Promise { + this.#stop.abort(); + this.#options.clipboard?.stop(); + this.#session?.close(); + this.#socket?.destroy(); + } + + /** Returns true when a session was established (the backoff starts again from the minimum). */ + async #connectOnce(target: Target): Promise { + const { log } = this.#options; + const address = formatAddress(target.host, target.port); + log.debug(`connecting to ${address}`); + const socket = await connectTcp(target, this.#timings.connectTimeoutMs, this.#stop.signal); + this.#socket = socket; + const reader = new FrameReader(socket, HANDSHAKE_MAX_BODY_BYTES); + const timer = setTimeout(() => socket.destroy(new Error('handshake timed out')), this.#timings.handshakeTimeoutMs); + let channel; + try { + channel = await clientHandshake(socket, reader, { + passphrase: this.#options.passphrase, + ...(this.#options.kdf ? { kdf: this.#options.kdf } : {}), + }); + } catch (error) { + socket.destroy(); + throw error; + } finally { + clearTimeout(timer); + } + + const session = new Session(socket, reader, channel, { + maxTextBytes: this.#options.maxTextBytes, + heartbeatIntervalMs: this.#timings.heartbeatIntervalMs, + idleTimeoutMs: this.#timings.idleTimeoutMs, + localName: this.#options.localName, + version: this.#options.version, + }); + this.#session = session; + session.once('info', () => { + log.info(`connected to ${session.label}`); + // Read the clipboard only while connected: without a peer there is nowhere to send it. + void this.#options.clipboard?.start(); + this.emit('connected', session); + }); + session.on('clip', (text) => { + log.info(`← ${formatCount(text.length)} chars from ${session.label}`); + void this.#options.clipboard?.apply(text); + }); + const closed = once(session, 'close'); + session.start(); + const [error] = (await closed) as [Error | null]; + this.#session = null; + this.#options.clipboard?.stop(); + if (!this.#stop.signal.aborted) log.info(`disconnected from ${session.label}${error ? `: ${error.message}` : ''}`); + this.emit('disconnected', session, error); + return true; + } + + #onLocalChange(text: string): void { + const { log } = this.#options; + const session = this.#session; + if (!session || !session.peer) { + log.info(`not connected: local copy of ${formatCount(text.length)} chars was not sent`); + return; + } + const result = session.sendClip(text); + if (result === 'sent') log.info(`→ ${formatCount(text.length)} chars sent to ${session.label}`); + else if (result === 'too-large') log.warn(`not sent: ${formatCount(Buffer.byteLength(text))} bytes is above the size limit`); + else log.info('not connected: local copy was not sent'); + } +} + +/** Exponential backoff with ±20 % jitter, so many clients do not reconnect at the same moment. */ +export function backoffDelay(attempt: number, minMs: number, maxMs: number, random: () => number = Math.random): number { + const base = Math.min(maxMs, minMs * 2 ** Math.min(attempt, 30)); + return Math.round(base * (0.8 + 0.4 * random())); +} + +function toFatal(error: unknown): FatalError | null { + if (error instanceof FatalError) return error; + if (error instanceof HandshakeError && error.failure === 'rejected') { + return new FatalError('wrong passphrase: the server rejected it. Use the same passphrase on all machines.'); + } + if (error instanceof HandshakeError && error.failure === 'version-mismatch') return new FatalError(error.message); + return null; +} + +function logRetry(log: Logger, where: string, error: unknown): void { + if (error instanceof HandshakeError && error.failure === 'peer-unverified') { + log.warn(`${where} could not prove the passphrase: it uses a different passphrase or it is not your server`); + } else { + log.warn(`cannot connect to ${where}: ${error instanceof Error ? error.message : String(error)}`); + } +} + +function connectTcp(target: Target, timeoutMs: number, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const socket = net.connect({ host: target.host, port: target.port }); + const cleanup = () => { + clearTimeout(timer); + socket.off('connect', onConnect); + socket.off('error', onError); + signal.removeEventListener('abort', onAbort); + }; + const onError = (error: Error) => { + cleanup(); + socket.destroy(); + reject(error); + }; + const onAbort = () => onError(new Error('stopped')); + const onConnect = () => { + cleanup(); + socket.setNoDelay(true); + socket.setKeepAlive(true, 15_000); + resolve(socket); + }; + const timer = setTimeout(() => onError(new Error(`no answer after ${timeoutMs / 1000} s`)), timeoutMs); + socket.once('connect', onConnect); + socket.once('error', onError); + signal.addEventListener('abort', onAbort, { once: true }); + }); +} diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..ff30bfb --- /dev/null +++ b/src/main.ts @@ -0,0 +1,174 @@ +import os from 'node:os'; +import { type Command, USAGE, UsageError, parseCommandLine } from './args.ts'; +import { Client, FatalError, type Target } from './client.ts'; +import { ClipboardWatcher, systemClipboard } from './clipboard.ts'; +import { type FoundServer, advertise, discoverServers } from './discovery.ts'; +import { type Logger, createLogger, sanitizeForTerminal } from './log.ts'; +import { PassphraseError, PromptCancelledError, resolvePassphrase } from './passphrase.ts'; +import { Hub } from './server.ts'; +import { formatAddress } from './session.ts'; +import { VERSION } from './version.ts'; + +const DISCOVERY_TIMEOUT_MS = 3000; + +export interface MainIO { + argv: string[]; + env: NodeJS.ProcessEnv; + stdin: NodeJS.ReadStream; + stdout: NodeJS.WriteStream; + stderr: NodeJS.WriteStream; +} + +/** Runs the command line and returns the exit code. */ +export async function main(io: MainIO): Promise { + let command: Command; + try { + command = parseCommandLine(io.argv); + } catch (error) { + if (!(error instanceof UsageError)) throw error; + io.stderr.write(`netpaste: ${error.message}\nRun "netpaste --help" for usage.\n`); + return 2; + } + + switch (command.name) { + case 'help': + io.stdout.write(`${USAGE}\n`); + return 0; + case 'version': + io.stdout.write(`${VERSION}\n`); + return 0; + case 'discover': + return discover(command.timeoutMs, createLogger({ verbose: command.verbose, out: io.stdout, err: io.stderr }), io); + case 'serve': + case 'connect': { + const log = createLogger({ verbose: command.options.verbose, out: io.stdout, err: io.stderr }); + try { + return command.name === 'serve' ? await serve(command, log, io) : await connect(command, log, io); + } catch (error) { + if (error instanceof PromptCancelledError) return 130; + if (error instanceof PassphraseError || error instanceof FatalError) { + log.error(error.message); + return 1; + } + throw error; + } + } + } +} + +async function serve(command: Extract, log: Logger, io: MainIO): Promise { + const passphrase = await resolvePassphrase({ file: command.options.passphraseFile, env: io.env, stdin: io.stdin, prompt: io.stderr, log }); + const clipboard = command.clipboard ? new ClipboardWatcher(await systemClipboard(), { intervalMs: command.options.intervalMs, log }) : null; + const localName = shortHostname(); + const hub = new Hub({ + port: command.port, + host: command.host, + passphrase, + clipboard, + maxTextBytes: command.options.maxTextBytes, + localName, + version: VERSION, + log, + }); + + let address; + try { + address = await hub.listen(); + } catch (error) { + throw new FatalError(listenError(error as NodeJS.ErrnoException, command.port, command.host)); + } + const where = formatAddress(address.address === '::' || address.address === '0.0.0.0' ? '*' : address.address, address.port); + log.info(`netpaste ${VERSION} is listening on ${where}; ${clipboard ? 'clipboard sync is on' : 'relay only (--no-clipboard)'}`); + const announcement = command.mdns ? advertise(address.port, localName, log) : null; + if (announcement) log.info(`announced on the local network as "${localName}"`); + + await waitForSignal(); + log.info('stopping'); + clipboard?.stop(); + await announcement?.stop(); + await hub.close(); + return 0; +} + +async function connect(command: Extract, log: Logger, io: MainIO): Promise { + const passphrase = await resolvePassphrase({ file: command.options.passphraseFile, env: io.env, stdin: io.stdin, prompt: io.stderr, log }); + const clipboard = command.clipboard ? new ClipboardWatcher(await systemClipboard(), { intervalMs: command.options.intervalMs, log }) : null; + const client = new Client({ + target: command.target, + findServer: command.target ? undefined : () => findSingleServer(log), + passphrase, + clipboard, + maxTextBytes: command.options.maxTextBytes, + localName: shortHostname(), + version: VERSION, + log, + }); + log.info(`netpaste ${VERSION}; ${clipboard ? 'clipboard sync is on' : 'clipboard is off (--no-clipboard)'}`); + + void waitForSignal().then(() => { + log.info('stopping'); + return client.close(); + }); + await client.run(); + return 0; +} + +async function discover(timeoutMs: number, log: Logger, io: MainIO): Promise { + let servers: FoundServer[]; + try { + servers = await discoverServers(timeoutMs); + } catch (error) { + log.error((error as Error).message); + return 1; + } + if (servers.length === 0) { + io.stdout.write('No netpaste servers found on the local network.\n'); + return 0; + } + for (const server of servers) io.stdout.write(`${server.name}\t${formatAddress(server.host, server.port)}\n`); + return 0; +} + +async function findSingleServer(log: Logger): Promise { + log.debug('looking for a netpaste server on the local network'); + const servers = await discoverServers(DISCOVERY_TIMEOUT_MS); + if (servers.length === 0) throw new Error('no netpaste server found on the local network'); + if (servers.length > 1) { + const list = servers.map((s) => `"${s.name}" at ${formatAddress(s.host, s.port)}`).join(', '); + throw new FatalError(`found ${servers.length} servers: ${list}. Choose one: netpaste connect HOST[:PORT]`); + } + const [server] = servers as [FoundServer]; + log.info(`found server "${server.name}" at ${formatAddress(server.host, server.port)}`); + return server; +} + +function listenError(error: NodeJS.ErrnoException, port: number, host: string | undefined): string { + switch (error.code) { + case 'EADDRINUSE': + return `port ${port} is already in use. Is another netpaste running? Use --port to choose another port.`; + case 'EACCES': + return `no permission to listen on port ${port}`; + case 'EADDRNOTAVAIL': + return `address ${host ?? ''} does not belong to this machine`; + default: + return `cannot listen on port ${port}: ${error.message}`; + } +} + +function shortHostname(): string { + return sanitizeForTerminal(os.hostname().replace(/\.local$/i, ''), 63) || 'netpaste'; +} + +/** Resolves on the first SIGINT/SIGTERM. A second Ctrl+C exits at once. */ +function waitForSignal(): Promise { + return new Promise((resolve) => { + const onSignal = () => { + process.off('SIGINT', onSignal); + process.off('SIGTERM', onSignal); + process.once('SIGINT', () => process.exit(130)); + resolve(); + }; + process.on('SIGINT', onSignal); + process.on('SIGTERM', onSignal); + }); +} diff --git a/src/server.ts b/src/server.ts new file mode 100644 index 0000000..b4270cc --- /dev/null +++ b/src/server.ts @@ -0,0 +1,215 @@ +/** + * The hub: accepts clients, checks the passphrase, and relays clipboard text. + * + * client A ──▶ hub ──▶ client B, client C … (never back to A) + * └────▶ local clipboard (unless --no-clipboard) + * local clipboard change ──▶ all clients + */ +import { EventEmitter } from 'node:events'; +import net from 'node:net'; +import type { ClipboardWatcher } from './clipboard.ts'; +import { DEFAULT_TIMINGS, MAX_CONCURRENT_KDF, MAX_CONNECTIONS, type Timings } from './config.ts'; +import type { KdfParams } from './crypto.ts'; +import { FrameReader } from './frame-reader.ts'; +import { HANDSHAKE_MAX_BODY_BYTES, HandshakeError, serverHandshake } from './handshake.ts'; +import { Limiter } from './limiter.ts'; +import { type Logger, formatCount } from './log.ts'; +import { Session, formatAddress } from './session.ts'; + +export interface HubOptions { + port: number; + /** Listen address; all interfaces when undefined. */ + host?: string | undefined; + passphrase: string; + /** null = relay only, the local clipboard is not used. */ + clipboard: ClipboardWatcher | null; + maxTextBytes: number; + localName: string; + version: string; + log: Logger; + timings?: Partial; + kdf?: KdfParams; +} + +interface HubEvents { + 'peer-connected': [session: Session]; + 'peer-disconnected': [session: Session]; + 'auth-failed': [remoteAddress: string]; +} + +export class Hub extends EventEmitter { + readonly #options: HubOptions; + readonly #timings: Timings; + readonly #server: net.Server; + readonly #sessions = new Set(); + readonly #pending = new Set(); + readonly #kdfLimiter = new Limiter(MAX_CONCURRENT_KDF); + /** Wrong-passphrase history per IP address, to slow down online guessing. */ + readonly #authFailures = new Map(); + #closing = false; + + constructor(options: HubOptions) { + super(); + this.#options = options; + this.#timings = { ...DEFAULT_TIMINGS, ...options.timings }; + this.#server = net.createServer((socket) => void this.#accept(socket)); + this.#server.maxConnections = MAX_CONNECTIONS; + options.clipboard?.on('change', (text) => this.#onLocalChange(text)); + } + + get peers(): Session[] { + return [...this.#sessions]; + } + + /** Starts listening. Rejects when the port is busy or the address is invalid. */ + async listen(): Promise { + await new Promise((resolve, reject) => { + const onError = (error: Error) => { + this.#server.off('listening', onListening); + reject(error); + }; + const onListening = () => { + this.#server.off('error', onError); + resolve(); + }; + this.#server.once('error', onError); + this.#server.once('listening', onListening); + this.#server.listen(this.#options.port, this.#options.host); + }); + this.#server.on('error', (error) => this.#options.log.error(`server: ${error.message}`)); + return this.#server.address() as net.AddressInfo; + } + + async close(): Promise { + this.#closing = true; + this.#options.clipboard?.stop(); + const closed = new Promise((resolve) => this.#server.close(() => resolve())); + for (const socket of this.#pending) socket.destroy(); + for (const session of this.#sessions) session.close(); + await closed; + } + + /** Returns how long the address is now blocked. */ + #recordAuthFailure(ip: string): number { + const now = Date.now(); + if (this.#authFailures.size > 1000) { + for (const [key, entry] of this.#authFailures) { + if (entry.blockedUntil < now) this.#authFailures.delete(key); + } + } + const count = (this.#authFailures.get(ip)?.count ?? 0) + 1; + const blockMs = Math.min(this.#timings.authBlockMaxMs, this.#timings.authBlockBaseMs * 2 ** Math.min(count - 1, 20)); + this.#authFailures.set(ip, { count, blockedUntil: now + blockMs }); + return blockMs; + } + + /** Reads the clipboard only while at least one peer is ready to receive. */ + #updateClipboardWatcher(): void { + const { clipboard } = this.#options; + if (!clipboard || this.#closing) return; + if ([...this.#sessions].some((session) => session.peer !== null)) void clipboard.start(); + else clipboard.stop(); + } + + async #accept(socket: net.Socket): Promise { + const { log } = this.#options; + const remote = formatAddress(socket.remoteAddress, socket.remotePort); + const ip = formatAddress(socket.remoteAddress, undefined); + if (this.#closing) { + socket.destroy(); + return; + } + const blocked = this.#authFailures.get(ip); + if (blocked && Date.now() < blocked.blockedUntil) { + log.debug(`refused ${remote}: wrong passphrase recently, blocked for ${Math.ceil((blocked.blockedUntil - Date.now()) / 1000)} s`); + socket.destroy(); + return; + } + socket.setNoDelay(true); + socket.setKeepAlive(true, this.#timings.heartbeatIntervalMs); + this.#pending.add(socket); + log.debug(`connection from ${remote}`); + + const reader = new FrameReader(socket, HANDSHAKE_MAX_BODY_BYTES); + const timer = setTimeout(() => socket.destroy(new Error('handshake timed out')), this.#timings.handshakeTimeoutMs); + let channel; + try { + channel = await serverHandshake(socket, reader, { + passphrase: this.#options.passphrase, + kdfLimiter: this.#kdfLimiter, + authFailureDelayMs: this.#timings.authFailureDelayMs, + ...(this.#options.kdf ? { kdf: this.#options.kdf } : {}), + }); + } catch (error) { + socket.destroy(); + if (error instanceof HandshakeError && error.failure === 'peer-unverified') { + const blockMs = this.#recordAuthFailure(ip); + log.warn(`rejected ${remote}: wrong passphrase; this address is blocked for ${(blockMs / 1000).toFixed(0)} s`); + this.emit('auth-failed', remote); + } else if (error instanceof HandshakeError) { + log.warn(`rejected ${remote}: ${error.message}`); + } else { + log.debug(`handshake with ${remote} failed: ${(error as Error).message}`); + } + return; + } finally { + clearTimeout(timer); + this.#pending.delete(socket); + } + this.#authFailures.delete(ip); + + const session = new Session(socket, reader, channel, { + maxTextBytes: this.#options.maxTextBytes, + heartbeatIntervalMs: this.#timings.heartbeatIntervalMs, + idleTimeoutMs: this.#timings.idleTimeoutMs, + localName: this.#options.localName, + version: this.#options.version, + }); + this.#sessions.add(session); + session.once('info', () => { + log.info(`connected: ${session.label}; peers online: ${this.#sessions.size}`); + this.#updateClipboardWatcher(); + this.emit('peer-connected', session); + }); + session.on('clip', (text) => this.#onRemoteClip(session, text)); + session.on('close', (error) => { + this.#sessions.delete(session); + const reason = error ? `: ${error.message}` : ''; + if (!this.#closing) log.info(`disconnected: ${session.label}${reason}`); + this.#updateClipboardWatcher(); + this.emit('peer-disconnected', session); + }); + session.start(); + } + + #onRemoteClip(from: Session, text: string): void { + const { log, clipboard } = this.#options; + log.info(`← ${formatCount(text.length)} chars from ${from.label}`); + void clipboard?.apply(text); + const forwarded = this.#broadcast(text, from); + if (forwarded > 0) log.debug(` forwarded to ${forwarded} peer${forwarded === 1 ? '' : 's'}`); + } + + #onLocalChange(text: string): void { + const { log } = this.#options; + if (this.#sessions.size === 0) { + log.debug(`local copy of ${formatCount(text.length)} chars: no peers connected`); + return; + } + const sent = this.#broadcast(text, null); + if (sent > 0) log.info(`→ ${formatCount(text.length)} chars sent to ${sent} peer${sent === 1 ? '' : 's'}`); + } + + #broadcast(text: string, except: Session | null): number { + let sent = 0; + for (const session of this.#sessions) { + if (session === except) continue; + const result = session.sendClip(text); + if (result === 'sent') sent++; + else if (result === 'too-large') { + this.#options.log.warn(`not sent to ${session.label}: ${formatCount(Buffer.byteLength(text))} bytes is above the size limit`); + } + } + return sent; + } +} diff --git a/src/session.ts b/src/session.ts new file mode 100644 index 0000000..32bd2a4 --- /dev/null +++ b/src/session.ts @@ -0,0 +1,199 @@ +/** + * An authenticated, encrypted connection to one peer. + * + * Plaintext of every Sealed frame: kind (u8) | payload + * CLIP 1 UTF-8 text, exactly as it was in the clipboard + * PING 2 empty; the peer answers with PONG + * PONG 3 empty + * INFO 4 JSON {"name": string, "version": string, "maxTextBytes": number} + * Unknown kinds are ignored, so later versions can add messages. + */ +import { EventEmitter } from 'node:events'; +import type { Socket } from 'node:net'; +import { MAX_TEXT_BYTES_CEILING, MIN_TEXT_BYTES } from './config.ts'; +import { type SecureChannel, TAG_BYTES } from './crypto.ts'; +import { FrameType } from './frame.ts'; +import { ConnectionClosedError, type FrameReader } from './frame-reader.ts'; +import { sanitizeForTerminal } from './log.ts'; + +export const MessageKind = { Clip: 1, Ping: 2, Pong: 3, Info: 4 } as const; + +export interface PeerInfo { + name: string; + version: string; + maxTextBytes: number; +} + +export interface SessionOptions { + /** Largest text we accept and send. */ + maxTextBytes: number; + heartbeatIntervalMs: number; + idleTimeoutMs: number; + localName: string; + version: string; +} + +interface SessionEvents { + clip: [text: string]; + info: [info: PeerInfo]; + /** `error` is null for a normal close. */ + close: [error: Error | null]; +} + +export type SendResult = 'sent' | 'too-large' | 'closed'; + +export class ProtocolError extends Error { + override name = 'ProtocolError'; +} + +export class PeerTimeoutError extends Error { + override name = 'PeerTimeoutError'; +} + +/** INFO and other control messages must fit even when the text limit is small. */ +const MIN_BODY_BYTES = 4096; + +export class Session extends EventEmitter { + readonly remoteAddress: string; + peer: PeerInfo | null = null; + readonly #socket: Socket; + readonly #reader: FrameReader; + readonly #channel: SecureChannel; + readonly #options: SessionOptions; + #closed = false; + #lastSentAt = 0; + #heartbeat: NodeJS.Timeout | undefined; + #idle: NodeJS.Timeout | undefined; + + constructor(socket: Socket, reader: FrameReader, channel: SecureChannel, options: SessionOptions) { + super(); + this.#socket = socket; + this.#reader = reader; + this.#channel = channel; + this.#options = options; + this.remoteAddress = formatAddress(socket.remoteAddress, socket.remotePort); + } + + /** "name (address)" once the peer has introduced itself, otherwise the address. */ + get label(): string { + return this.peer ? `${this.peer.name} (${this.remoteAddress})` : this.remoteAddress; + } + + get closed(): boolean { + return this.#closed; + } + + start(): void { + this.#reader.maxBodyBytes = Math.max(this.#options.maxTextBytes, MIN_BODY_BYTES) + 1 + TAG_BYTES; + const info = { name: this.#options.localName, version: this.#options.version, maxTextBytes: this.#options.maxTextBytes }; + this.#send(MessageKind.Info, Buffer.from(JSON.stringify(info))); + this.#idle = setTimeout(() => { + this.#finish(new PeerTimeoutError(`no data from the peer for ${Math.round(this.#options.idleTimeoutMs / 1000)} s`)); + }, this.#options.idleTimeoutMs); + this.#heartbeat = setInterval(() => { + if (Date.now() - this.#lastSentAt >= this.#options.heartbeatIntervalMs) this.#send(MessageKind.Ping); + }, this.#options.heartbeatIntervalMs); + void this.#readLoop(); + } + + /** Sends clipboard text. Text larger than our or the peer's limit is not sent. */ + sendClip(text: string): SendResult { + if (this.#closed) return 'closed'; + const bytes = Buffer.from(text, 'utf8'); + const limit = Math.min(this.#options.maxTextBytes, this.peer?.maxTextBytes ?? Number.POSITIVE_INFINITY); + if (bytes.length > limit) return 'too-large'; + this.#send(MessageKind.Clip, bytes); + return 'sent'; + } + + /** Closes the connection. Queued data is still delivered on a normal close. */ + close(error: Error | null = null): void { + this.#finish(error); + } + + #send(kind: number, payload: Buffer = Buffer.alloc(0)): void { + if (this.#closed || this.#socket.destroyed) return; + this.#socket.write(this.#channel.seal(Buffer.concat([Buffer.of(kind), payload]))); + this.#lastSentAt = Date.now(); + } + + async #readLoop(): Promise { + try { + for (;;) { + const frame = await this.#reader.next(); + this.#idle?.refresh(); + if (frame.type !== FrameType.Sealed) throw new ProtocolError(`unexpected frame type 0x${frame.type.toString(16)}`); + const plaintext = this.#channel.open(frame); + if (plaintext.length === 0) throw new ProtocolError('empty message'); + this.#handle(plaintext.readUInt8(0), plaintext.subarray(1)); + } + } catch (error) { + this.#finish(error instanceof ConnectionClosedError ? null : asError(error)); + } + } + + #handle(kind: number, payload: Buffer): void { + switch (kind) { + case MessageKind.Clip: + if (payload.length > this.#options.maxTextBytes) throw new ProtocolError('the peer sent text above the agreed limit'); + if (payload.length > 0) this.emit('clip', payload.toString('utf8')); + break; + case MessageKind.Ping: + this.#send(MessageKind.Pong); + break; + case MessageKind.Pong: + break; + case MessageKind.Info: + this.peer = parsePeerInfo(payload); + this.emit('info', this.peer); + break; + default: + break; + } + } + + #finish(error: Error | null): void { + if (this.#closed) return; + this.#closed = true; + clearInterval(this.#heartbeat); + clearTimeout(this.#idle); + if (error) { + this.#socket.destroy(); + } else { + // Flush queued frames, but do not wait forever for a peer that does not answer. + this.#socket.end(); + setTimeout(() => this.#socket.destroy(), 2000).unref(); + } + this.emit('close', error); + } +} + +export function parsePeerInfo(payload: Buffer): PeerInfo { + let data: unknown; + try { + data = JSON.parse(payload.toString('utf8')); + } catch { + throw new ProtocolError('malformed INFO message'); + } + const record = typeof data === 'object' && data !== null ? (data as Record) : {}; + const name = typeof record.name === 'string' ? sanitizeForTerminal(record.name) : ''; + const version = typeof record.version === 'string' ? sanitizeForTerminal(record.version, 32) : '?'; + const limit = typeof record.maxTextBytes === 'number' && Number.isFinite(record.maxTextBytes) ? Math.floor(record.maxTextBytes) : MIN_TEXT_BYTES; + return { + name: name || 'unnamed', + version: version || '?', + maxTextBytes: Math.min(Math.max(limit, MIN_TEXT_BYTES), MAX_TEXT_BYTES_CEILING), + }; +} + +/** "192.168.1.5:8134", "[fe80::1]:8134"; IPv4-mapped IPv6 addresses are shown as IPv4. */ +export function formatAddress(address: string | undefined, port: number | undefined): string { + if (!address) return 'unknown'; + const host = address.startsWith('::ffff:') ? address.slice(7) : address; + const shown = host.includes(':') ? `[${host}]` : host; + return port === undefined ? shown : `${shown}:${port}`; +} + +function asError(value: unknown): Error { + return value instanceof Error ? value : new Error(String(value)); +} diff --git a/test/e2e.test.ts b/test/e2e.test.ts new file mode 100644 index 0000000..dfce6d4 --- /dev/null +++ b/test/e2e.test.ts @@ -0,0 +1,243 @@ +import assert from 'node:assert/strict'; +import { once } from 'node:events'; +import net from 'node:net'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { afterEach, describe, it } from 'node:test'; +import { Client, FatalError } from '../src/client.ts'; +import { ClipboardWatcher } from '../src/clipboard.ts'; +import { FrameType, encodeFrame } from '../src/frame.ts'; +import { FrameReader } from '../src/frame-reader.ts'; +import { HANDSHAKE_MAX_BODY_BYTES, serverHandshake } from '../src/handshake.ts'; +import { Hub } from '../src/server.ts'; +import { FAST_KDF, FAST_TIMINGS, MemoryClipboard, type RecordingLogger, recordingLogger, waitFor } from './helpers.ts'; + +const PASSPHRASE = 'correct horse battery staple'; +const cleanups: Array<() => Promise | void> = []; + +afterEach(async () => { + while (cleanups.length > 0) await cleanups.pop()!(); +}); + +interface Machine { + backend: MemoryClipboard; + watcher: ClipboardWatcher; + log: RecordingLogger; +} + +function machine(initial: string): Machine { + const backend = new MemoryClipboard(initial); + const log = recordingLogger(); + const watcher = new ClipboardWatcher(backend, { intervalMs: 20, log }); + cleanups.push(() => watcher.stop()); + return { backend, watcher, log }; +} + +async function startHub(options: { clipboard?: Machine; port?: number; maxTextBytes?: number } = {}) { + const log = options.clipboard?.log ?? recordingLogger(); + const hub = new Hub({ + port: options.port ?? 0, + host: '127.0.0.1', + passphrase: PASSPHRASE, + clipboard: options.clipboard?.watcher ?? null, + maxTextBytes: options.maxTextBytes ?? 10 * 1024 * 1024, + localName: 'hub', + version: 'test', + log, + timings: FAST_TIMINGS, + kdf: FAST_KDF, + }); + const { port } = await hub.listen(); + cleanups.push(() => hub.close()); + return { hub, port, log }; +} + +async function startClient(port: number, name: string, m: Machine | null, options: { passphrase?: string; maxTextBytes?: number } = {}) { + const log = m?.log ?? recordingLogger(); + const client = new Client({ + target: { host: '127.0.0.1', port }, + passphrase: options.passphrase ?? PASSPHRASE, + clipboard: m?.watcher ?? null, + maxTextBytes: options.maxTextBytes ?? 10 * 1024 * 1024, + localName: name, + version: 'test', + log, + timings: FAST_TIMINGS, + kdf: FAST_KDF, + }); + const running = client.run(); + cleanups.push(async () => { + await client.close(); + await running.catch(() => undefined); + }); + return { client, running, log }; +} + +const connectedPeers = (hub: Hub) => hub.peers.filter((session) => session.peer !== null).length; + +describe('hub with clients', () => { + it('syncs text between all machines without echo and without changing it', async () => { + const hubMachine = machine('hub initial'); + const a = machine('a initial'); + const b = machine('b initial'); + const { hub, port } = await startHub({ clipboard: hubMachine }); + const ca = await startClient(port, 'a', a); + const cb = await startClient(port, 'b', b); + await waitFor(() => connectedPeers(hub) === 2 && !!ca.client.session?.peer && !!cb.client.session?.peer, 'two clients'); + + const fromA = ' indented();\n'; + a.backend.text = fromA; + await waitFor(() => hubMachine.backend.text === fromA && b.backend.text === fromA, 'A → hub and B'); + + const fromB = 'Привет 🙂\r\n'; + b.backend.text = fromB; + await waitFor(() => hubMachine.backend.text === fromB && a.backend.text === fromB, 'B → hub and A'); + + const fromHub = '\tfrom the hub\n\n'; + hubMachine.backend.text = fromHub; + await waitFor(() => a.backend.text === fromHub && b.backend.text === fromHub, 'hub → A and B'); + + await sleep(200); // room for an echo, if there was one + assert.deepEqual(a.backend.writes, [fromB, fromHub]); + assert.deepEqual(b.backend.writes, [fromA, fromHub]); + assert.deepEqual(hubMachine.backend.writes, [fromA, fromB]); + }); + + it('reads the clipboard only while a peer is connected', async () => { + const hubMachine = machine('hub'); + const a = machine('a'); + const { hub, port } = await startHub({ clipboard: hubMachine }); + await sleep(150); + assert.equal(hubMachine.backend.reads, 0, 'no reads without peers'); + + const ca = await startClient(port, 'a', a); + await waitFor(() => connectedPeers(hub) === 1 && hubMachine.backend.reads > 2 && a.backend.reads > 2, 'polling while connected'); + + await ca.client.close(); + await waitFor(() => connectedPeers(hub) === 0, 'disconnect'); + await sleep(50); + const hubReads = hubMachine.backend.reads; + const clientReads = a.backend.reads; + await sleep(200); + assert.equal(hubMachine.backend.reads, hubReads, 'hub stopped reading'); + assert.equal(a.backend.reads, clientReads, 'client stopped reading'); + }); + + it('relays between clients when the hub has no clipboard', async () => { + const a = machine('a'); + const b = machine('b'); + const { hub, port } = await startHub(); + await startClient(port, 'a', a); + await startClient(port, 'b', b); + await waitFor(() => connectedPeers(hub) === 2, 'two clients'); + a.backend.text = 'relayed'; + await waitFor(() => b.backend.text === 'relayed', 'A → B through a relay'); + }); + + it('delivers a 3 MB text intact', async () => { + const a = machine('a'); + const b = machine('b'); + const { hub, port } = await startHub(); + await startClient(port, 'a', a); + await startClient(port, 'b', b); + await waitFor(() => connectedPeers(hub) === 2, 'two clients'); + const big = 'строка текста 0123456789\n'.repeat(80_000); + a.backend.text = big; + await waitFor(() => b.backend.text === big, '3 MB text', 8000); + }); + + it('does not forward text above the receiver limit and keeps the connection', async () => { + const a = machine('a'); + const b = machine('b'); + const { hub, port, log } = await startHub(); + await startClient(port, 'a', a); + await startClient(port, 'b', b, { maxTextBytes: 2048 }); + await waitFor(() => connectedPeers(hub) === 2, 'two clients'); + a.backend.text = 'x'.repeat(4096); + await waitFor(() => log.has('warn', /above the size limit/), 'size warning'); + a.backend.text = 'small'; + await waitFor(() => b.backend.text === 'small', 'small text after the big one'); + assert.deepEqual(b.backend.writes, ['small']); + }); +}); + +describe('security and robustness', () => { + it('stops a client with a wrong passphrase and reports it on the hub', async () => { + const { hub, port } = await startHub(); + const failed = once(hub, 'auth-failed'); + const { running } = await startClient(port, 'intruder', null, { passphrase: 'wrong passphrase' }); + await assert.rejects(running, (error: unknown) => error instanceof FatalError && /wrong passphrase/.test(error.message)); + await failed; + }); + + it('blocks an address for a while after a wrong passphrase', async () => { + const { hub, port, log } = await startHub(); + const intruder = await startClient(port, 'intruder', null, { passphrase: 'wrong passphrase' }); + await assert.rejects(intruder.running, FatalError); + const blockedAt = Date.now(); + await startClient(port, 'owner', null); + await waitFor(() => connectedPeers(hub) === 1, 'connection after the block'); + assert.ok(Date.now() - blockedAt >= 300, 'the address was blocked first'); + assert.ok(log.has('debug', /refused .*blocked for/)); + }); + + it('survives junk from the network (1.x crashed on 4 bytes)', async () => { + const { hub, port } = await startHub(); + for (const junk of [Buffer.from('NetP'), Buffer.from('3ef272b5:83ec914f:143cf00c'), Buffer.from([0, 0, 0, 0]), Buffer.from([0xff, 0xff, 0xff, 0xff, 1])]) { + const socket = net.connect(port, '127.0.0.1'); + await once(socket, 'connect'); + socket.on('error', () => undefined); + socket.end(junk); + await once(socket, 'close'); + } + const a = machine('a'); + await startClient(port, 'a', a); + await waitFor(() => connectedPeers(hub) === 1, 'a normal client after the junk'); + }); + + it('sends nothing but its HELLO to a peer that has not proved the passphrase', async () => { + const hubMachine = machine('hub'); + const { port } = await startHub({ clipboard: hubMachine }); + const socket = net.connect(port, '127.0.0.1'); + cleanups.push(() => void socket.destroy()); + await once(socket, 'connect'); + let received = 0; + socket.on('data', (data: Buffer) => (received += data.length)); + socket.write(encodeFrame(FrameType.Hello, Buffer.concat([Buffer.from('NETPASTE'), Buffer.of(2, 0), Buffer.alloc(32, 7)]))); + await sleep(100); + hubMachine.backend.text = 'secret text'; + await sleep(300); + assert.equal(received, 5 + 42, 'only the server HELLO'); + }); + + it('reconnects after the hub restarts', async () => { + const first = await startHub(); + const a = machine('a'); + const { client } = await startClient(first.port, 'a', a); + await waitFor(() => connectedPeers(first.hub) === 1, 'first connection'); + await first.hub.close(); + await waitFor(() => client.session === null, 'disconnect'); + const second = await startHub({ port: first.port }); + await waitFor(() => connectedPeers(second.hub) === 1, 'reconnection', 5000); + }); + + it('drops a peer that stops answering and keeps a quiet but healthy one', async () => { + // A fake server: it completes the handshake, then never sends anything (no INFO, no PONG). + const silent = net.createServer((socket) => { + socket.on('error', () => undefined); + void serverHandshake(socket, new FrameReader(socket, HANDSHAKE_MAX_BODY_BYTES), { passphrase: PASSPHRASE, kdf: FAST_KDF }).catch(() => undefined); + }); + await new Promise((resolve) => silent.listen(0, '127.0.0.1', resolve)); + cleanups.push(() => new Promise((resolve) => silent.close(() => resolve()))); + const silentPort = (silent.address() as net.AddressInfo).port; + const { log } = await startClient(silentPort, 'a', null); + await waitFor(() => log.has('info', /no data from the peer/), 'idle timeout'); + + const { hub, port } = await startHub(); + const healthy = await startClient(port, 'b', null); + await waitFor(() => connectedPeers(hub) === 1, 'healthy connection'); + const session = healthy.client.session; + await sleep(1500); // well above idleTimeoutMs: heartbeats keep it open + assert.equal(healthy.client.session, session); + assert.equal(session?.closed, false); + }); +}); From 7419d80459ad2f23ef4bfd7f6635efebe0898a43 Mon Sep 17 00:00:00 2001 From: Aliaksei Smirnou Date: Thu, 19 Nov 2026 08:34:01 +0100 Subject: [PATCH 7/9] docs: README, protocol and changelog; autostart templates; CI - README: install, usage, passphrase sources, firewall, autostart, security limits, upgrade notes from 1.x. - docs/PROTOCOL.md: framing, handshake, key schedule, messages, threat model. - CHANGELOG.md: every 1.x problem that 2.0 fixes. - launchd LaunchAgent and systemd user service templates. - GitHub Actions: typecheck and tests on Linux and macOS, Node.js 22/24/26. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 27 +++ CHANGELOG.md | 69 +++++++ README.md | 195 +++++++++++++++--- .../launchd/io.github.leplik.netpaste.plist | 36 ++++ contrib/systemd/netpaste.service | 18 ++ docs/PROTOCOL.md | 139 +++++++++++++ 6 files changed, 451 insertions(+), 33 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 CHANGELOG.md create mode 100644 contrib/launchd/io.github.leplik.netpaste.plist create mode 100644 contrib/systemd/netpaste.service create mode 100644 docs/PROTOCOL.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..61a04f7 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,27 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + test: + name: Node ${{ matrix.node }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + node: [22, 24, 26] + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: ${{ matrix.node }} + cache: npm + - run: npm ci + - run: npm run typecheck + - run: npm test diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..23ae5b2 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,69 @@ +# Changelog + +## 2.0.0 — 2026-11-19 + +A rewrite. The protocol is not compatible with 1.x: update all machines. + +### Security + +- **Messages are authenticated and encrypted with AES-256-GCM.** 1.x used AES-CTR without a MAC. + A man-in-the-middle could change text (for example `ls -la` into `rm -rf`) without the passphrase. + Any machine on the network could also forge clipboard text and terminal escape sequences: + it only had to take the keystream from the HELLO message, whose plaintext is known. +- **Mutual passphrase check before any data.** 1.x sent HELLO and every clipboard change to any + machine that connected. That also gave material for offline passphrase guessing. +- **Strong key derivation:** scrypt (128 MiB) once per connection. + 1.x ran PBKDF2 with 10,000 iterations for every message, on the main thread. +- **Forward secrecy and replay protection:** ephemeral X25519 keys and per-direction message counters. +- **Online guessing is slowed down:** after a wrong passphrase, the hub blocks the IP address + (1 s, then doubling up to 60 s). +- Peer-supplied names are cleaned of control characters before they are printed. + +### Fixed + +- **Any 4 bytes (`NetP`) from the network crashed the server or the client.** A crafted header did the same. +- **Text larger than one TCP segment arrived corrupted, or was lost.** The receiver assumed that every + `data` event starts with a whole fragment. On Wi-Fi/Ethernet a 3,000-character text arrived as 1,822 + characters of garbage. The integrity check passed it, so the garbage went into the clipboard. +- **The client crashed on its first reconnect attempt:** `setTimeout(createConnection)` passed no host or port. +- **Leading and trailing whitespace was removed** from received text (`trim()`): indentation and final newlines were lost. +- **Texts above ~130 KB (~65,000 Cyrillic characters) were never sent:** the part counter was one byte. +- **Copies were lost or echoed back** because of the 2-second "ignore" window. A copy made within 2 s after a + received one was never sent. Two copies about 2 s apart were echoed back and could overwrite a newer copy. + One failed clipboard write blocked all later copies. +- **Every connection started another clipboard poller that never stopped.** After N reconnects, `pbpaste` ran N + times per second, and copies went to dead sockets with an "Ok." message. +- **The hub did not relay** text from one client to the other clients. +- **All clients shared one message assembler**, so fragments of different clients could mix. +- **The HELLO message was never processed** (it had no framing), so passphrase or version mismatches were not detected. +- **Passphrase input:** + - Backspace added a `\x7f` character, and arrow keys added the text `undefined`. A typo made the + passphrases on the two machines different, without an error message. + - Input from a pipe never finished. + - An empty passphrase was accepted. +- **Dead connections were not detected** after sleep or a network change; copies were lost with an "Ok." message. +- **Command line:** + - A port that was not a number silently became 8134. + - `--no-clipboard` before the host was taken as the host name. + - Arguments were checked only after the passphrase prompt. + - A busy port ended the program with exit code 0. +- On Linux under Wayland, clipboardy 4 used only `xsel` through XWayland. +- Unknown messages were printed in full, including clipboard text. + +### New + +- One command: `netpaste serve`, `netpaste connect [HOST[:PORT]]`, `netpaste discover`. +- Hub for many machines; `--no-clipboard` on the hub makes it a relay. +- mDNS discovery: `netpaste connect` without an address finds the hub. +- Passphrase from `--passphrase-file` or `NETPASTE_PASSPHRASE`, for autostart. Templates for launchd and systemd. +- Heartbeats, idle timeout, TCP keepalive, reconnect with exponential backoff and jitter. +- `--max-size` (default 10 MB), `--interval`, `--host`, `--no-mdns`, `--verbose`. +- The clipboard is read only while a peer is connected. +- Clear messages for a wrong passphrase, an old protocol version, a busy port, and a missing terminal. + +### Internal + +- TypeScript (strict), run directly by Node.js 22.18+ without a build step. +- `chalk` replaced by `util.styleText`; argument parsing with `util.parseArgs`; clipboardy 5 (native Wayland support). +- Tests with `node:test`: framing at every split point, crypto, handshake (including a man-in-the-middle), + clipboard races, passphrase input, CLI, and end-to-end hub tests. CI on Linux and macOS, Node.js 22/24/26. diff --git a/README.md b/README.md index 6a329fc..75d15bf 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,189 @@ # netpaste -Netpaste is a utility crafted for developers who frequently work across Linux and macOS environments, providing a seamless method to share clipboard data between machines. Created out of necessity by a full-stack developer tired of the lack of simple tools for this task, **netpaste** offers an efficient, peer-to-peer clipboard sharing solution that's both secure and easy to use. +Encrypted clipboard sync between your machines on a local network. +Copy on one machine, paste on another. Works on macOS and Linux (X11 and Wayland). -## Features +- **Encrypted and authenticated.** Each machine proves that it knows the shared passphrase. + Messages use AES-256-GCM with new keys for every connection (X25519 + scrypt + HKDF). + A machine that has not proved the passphrase receives nothing. +- **One hub, many machines.** One machine runs `netpaste serve`, the others run `netpaste connect`. + The hub relays text between all clients. A headless machine can be a pure relay (`--no-clipboard`). +- **Finds the hub by itself.** `netpaste connect` without an address looks for the hub on the local network (mDNS). +- **Stays connected.** Heartbeats detect dead connections (laptop sleep, Wi-Fi change). + The client reconnects automatically. +- **Exact text.** Spaces, line endings and Unicode arrive unchanged. Up to 10 MB per copy (configurable). +- **No cloud, no account.** The traffic stays on your network. -- **Encryption:** All data shared between clients is encrypted. -- **Peer-to-Peer (P2P):** Directly shares clipboard data between machines. -- **Automatic Clipboard Monitoring:** Actively monitors your clipboard for changes. +## Requirements -## Installation +- Node.js 22.18 or newer. netpaste runs its TypeScript sources directly, without a build step. +- macOS: nothing else. +- Linux: `wl-clipboard` on Wayland, or `xsel` on X11 (a bundled `xsel` is used when it is missing). -Before you dive into using Netpaste, there are a few prerequisites and steps to follow: +## Install -### Dependencies +```bash +git clone https://github.com/leplik/netpaste.git +cd netpaste +npm install +npm install -g . # adds the `netpaste` command (a link to this folder) +``` + +Without the global install, use `node bin/netpaste.js` instead of `netpaste`. -- Node.js and npm (Node Package Manager) +## Use -### Steps +Use the same passphrase on all machines. Make it long: 4 or more random words, or 12+ characters. -1. Clone the Netpaste repository to your local machine. ```bash -git clone https://github.com/leplik/netpaste.git; +# On the hub (any machine that stays on): +netpaste serve + +# On every other machine: +netpaste connect # finds the hub on the local network +netpaste connect 192.168.1.10 # or give the address (HOST or HOST:PORT) +``` + +```text +$ netpaste connect +Passphrase: **************************** +14:02:11 netpaste 2.0.0; clipboard sync is on +14:02:14 found server "studio" at 192.168.1.10:8134 +14:02:14 connected to studio (192.168.1.10:8134) +14:02:31 → 1,204 chars sent to studio (192.168.1.10:8134) +14:03:05 ← 87 chars from studio (192.168.1.10:8134) ``` -2. Navigate into the Netpaste directory and run `npm install` to install the required Node.js dependencies. + +netpaste prints only the size of the text, never the text. +Copies are sent only while a connection is open; a copy made while disconnected is not sent later. + +### Commands and options + +| Command | What it does | +|---|---| +| `netpaste serve` | Start the hub. Listens on port 8134 and announces itself with mDNS. | +| `netpaste connect [HOST[:PORT]]` | Connect to the hub. Without HOST it finds the hub with mDNS. | +| `netpaste discover` | List the hubs on the local network. | + +| Option | Default | Meaning | +|---|---|---| +| `-p, --port N` | 8134 | TCP port. | +| `--host ADDR` | all interfaces | `serve`: listen only on this address. | +| `--no-clipboard` | | Do not use the local clipboard. With `serve`: only relay between clients. | +| `--no-mdns` | | `serve`: do not announce the hub on the network. | +| `--passphrase-file F` | | Read the passphrase from file F. | +| `--interval MS` | 1000 | How often to check the clipboard. | +| `--max-size SIZE` | 10mb | Largest text to send or accept, for example `512kb`. | +| `--timeout SEC` | 3 | `discover`: how long to search. | +| `--verbose` | | Show debug messages. | + +### Passphrase without a prompt + +netpaste takes the passphrase from the first source that is set: + +1. `--passphrase-file FILE`: the content of the file (one final newline is removed); +2. the `NETPASTE_PASSPHRASE` environment variable; +3. a prompt on the terminal. + ```bash -cd netpaste -npm install +mkdir -p ~/.config/netpaste +touch ~/.config/netpaste/passphrase && chmod 600 ~/.config/netpaste/passphrase +nano ~/.config/netpaste/passphrase # type the passphrase and save +netpaste connect --passphrase-file ~/.config/netpaste/passphrase ``` -3. Allow Netpaste server through your firewall to ensure it can communicate over the network. This process varies by operating system: - - **Linux:** Use UFW or your distro's firewall settings to allow traffic on the default port (8134): `sudo ufw allow 8134` - - **macOS:** Go to `System Preferences > Security & Privacy > Firewall`, and add an exception for Netpaste. -## Usage +netpaste warns when other users can read the file. + +### Firewall + +- **macOS:** when macOS asks whether `node` may accept incoming connections, allow it (only on the hub). +- **Linux:** open TCP 8134 on the hub, and UDP 5353 for mDNS, for example `sudo ufw allow 8134/tcp && sudo ufw allow 5353/udp`. -Netpaste is comprised of two parts: the server and the client. Each machine should run its instance of the utility. +## Start automatically -### Server +Both templates run `netpaste connect` (find the hub with mDNS) with a passphrase file. +For the hub, replace `connect` with `serve`. To connect to a fixed address, add it after `connect`. -Start the server on the machine that will be... server (no matters for copy-pasting process): +### macOS (launchd) ```bash -node server.js [port] +cd netpaste +sed -e "s|__NODE__|$(command -v node)|" -e "s|__NETPASTE__|$PWD/bin/netpaste.js|" -e "s|__HOME__|$HOME|g" \ + contrib/launchd/io.github.leplik.netpaste.plist > ~/Library/LaunchAgents/io.github.leplik.netpaste.plist +launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/io.github.leplik.netpaste.plist +tail -f ~/Library/Logs/netpaste.log +``` + +Stop: `launchctl bootout gui/$(id -u)/io.github.leplik.netpaste`. +The template contains the full path to `node`. If you change the Node.js version (for example with nvm), install the template again. + +Tip: to keep the passphrase in the Keychain instead of a file, store it with +`security add-generic-password -a "$USER" -s netpaste -w` and start netpaste through +`/bin/sh -c 'NETPASTE_PASSPHRASE="$(security find-generic-password -s netpaste -w)" exec …'`. + +### Linux (systemd user service) + +```bash +cd netpaste +mkdir -p ~/.config/systemd/user +sed -e "s|__NODE__|$(command -v node)|" -e "s|__NETPASTE__|$PWD/bin/netpaste.js|" \ + contrib/systemd/netpaste.service > ~/.config/systemd/user/netpaste.service +systemctl --user daemon-reload +systemctl --user enable --now netpaste.service +journalctl --user -u netpaste -f ``` -If no port is specified, Netpaste uses the default port 8134. -### Client -On other machine start the client: +The service starts with the graphical session, because it needs the display for the clipboard. +If netpaste cannot read the clipboard, run +`systemctl --user import-environment DISPLAY WAYLAND_DISPLAY XAUTHORITY` and restart the service. +For a headless relay hub, use `serve --no-clipboard`, change `WantedBy=` to `default.target`, +and run `loginctl enable-linger $USER` so that the service runs without a login. + +## Security + +The full design is in [docs/PROTOCOL.md](docs/PROTOCOL.md). In short: + +**Protects against:** + +- eavesdroppers: they cannot read the text, and they cannot test passphrase guesses; +- changed, replayed or reordered messages: they fail authentication and close the connection; +- strangers who connect to the hub: they receive nothing until they prove the passphrase. + After a wrong passphrase, the hub blocks that address for 1 s, then 2 s, 4 s … up to 60 s; +- malformed input: it closes that one connection, never the program. + +**Does not protect against:** + +- **a weak passphrase.** An attacker who pretends to be the hub (a fake mDNS announcement or a + man-in-the-middle) can try passphrase guesses offline. Each guess costs one scrypt run (128 MiB, about + 0.2 s), so a long random passphrase makes this impractical, and a short one does not; +- text sizes: the size of each copy is visible on the network; +- machines that know the passphrase: they can read your copies and write to your clipboard; +- password managers: netpaste syncs a copied password like any other text, and the other + machine keeps it after the password manager clears its own clipboard. + +## Upgrading from 1.x + +Version 2 uses a new protocol. It cannot talk to 1.x, so update all machines. + +| 1.x | 2.x | +|---|---| +| `node server.js [port]` | `netpaste serve [--port N]` | +| `node client.js HOST [port]` | `netpaste connect HOST[:PORT]` | +| `--no-clipboard` | `--no-clipboard` (on the hub it now means "relay only") | + +The list of fixed problems is in [CHANGELOG.md](CHANGELOG.md). + +## Development ```bash -node client.js [port] +npm run typecheck # tsc --noEmit, strict +npm test # node:test: unit, protocol, security and end-to-end tests +node bin/netpaste.js serve --no-clipboard --verbose ``` -``: The IP address or hostname of the server. -`[port]`: The port number (optional, defaults to 8134 if not provided). -### Supported Platforms -Netpaste is tested and supported on Linux and macOS platforms. It leverages platform-independent technologies but adheres closely to Unix-like operating system behaviors. +The tests never touch the real clipboard: they use an in-memory clipboard. +The mDNS test uses multicast on the loopback interface only. + +## Author -### Author -Aliaksei Smirnou \ No newline at end of file +Aliaksei Smirnou. MIT License. diff --git a/contrib/launchd/io.github.leplik.netpaste.plist b/contrib/launchd/io.github.leplik.netpaste.plist new file mode 100644 index 0000000..f7e3747 --- /dev/null +++ b/contrib/launchd/io.github.leplik.netpaste.plist @@ -0,0 +1,36 @@ + + + + + + Label + io.github.leplik.netpaste + ProgramArguments + + __NODE__ + __NETPASTE__ + connect + --passphrase-file + __HOME__/.config/netpaste/passphrase + + RunAtLoad + + KeepAlive + + ThrottleInterval + 30 + EnvironmentVariables + + NO_COLOR + 1 + + StandardOutPath + __HOME__/Library/Logs/netpaste.log + StandardErrorPath + __HOME__/Library/Logs/netpaste.log + + diff --git a/contrib/systemd/netpaste.service b/contrib/systemd/netpaste.service new file mode 100644 index 0000000..9e477dc --- /dev/null +++ b/contrib/systemd/netpaste.service @@ -0,0 +1,18 @@ +# netpaste as a systemd user service (Linux). +# Install: see "Start automatically" in README.md (sed replaces __NODE__ and __NETPASTE__). +# Hub: replace "connect" with "serve". Fixed address: add HOST after "connect". +# Headless relay hub: "serve --no-clipboard" and WantedBy=default.target. + +[Unit] +Description=netpaste clipboard sync +After=graphical-session.target +PartOf=graphical-session.target + +[Service] +ExecStart=__NODE__ __NETPASTE__ connect --passphrase-file %h/.config/netpaste/passphrase +Environment=NO_COLOR=1 +Restart=on-failure +RestartSec=10 + +[Install] +WantedBy=graphical-session.target diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md new file mode 100644 index 0000000..8f34624 --- /dev/null +++ b/docs/PROTOCOL.md @@ -0,0 +1,139 @@ +# netpaste protocol, version 2 + +This document describes the wire protocol and the security design of netpaste 2. +Version 1 (netpaste 1.x) is not compatible. + +## Overview + +``` +client hub + │── TCP connect ─────────────────────────────────────────▶│ + │── HELLO "NETPASTE" | 2 | role=0 | X25519 key eC ───────▶│ + │◀── HELLO "NETPASTE" | 2 | role=1 | X25519 key eS ────────│ + │ both: transcript, scrypt, X25519, HKDF (see below) │ + │── AUTH client proof ─────────────────────────────────▶│ wrong → wait 1 s, ERROR, close, + │◀── AUTH hub proof ──────────────────────────────────────│ block the IP address + │══ SEALED INFO ═══════════════════════════════════════════│ both directions + │══ SEALED CLIP / PING / PONG ══════════════════════════════│ +``` + +## Framing + +TCP is a byte stream, so every message is a frame: + +``` +length (u32, big-endian; counts type + body) | type (u8) | body +``` + +| Type | Name | When | Body | +|---|---|---|---| +| `0x01` | HELLO | handshake | 42 bytes, see below | +| `0x02` | AUTH | handshake | 32-byte proof | +| `0x03` | ERROR | handshake | 1-byte code: 1 wrong passphrase, 2 other version, 3 protocol error | +| `0x10` | SEALED | after the handshake | AES-256-GCM ciphertext + 16-byte tag | + +The receiver checks the length before it buffers the body: + +- before authentication, the largest body is 256 bytes; +- after authentication, the largest body is the text limit (`--max-size`, at least 4 KiB) + 17 bytes. + +A frame above the limit, an unknown frame type during the handshake, or a failed decryption +closes the connection. + +## Handshake + +`HELLO` body: `"NETPASTE"` (8 bytes) | protocol version (u8, = 2) | role (u8: 0 client, 1 hub) | ephemeral X25519 public key (32 bytes). + +Both sides compute: + +``` +transcript = SHA-256("netpaste/2 transcript" | helloClient | helloHub) +salt = SHA-256("netpaste/2 kdf salt" | transcript) +pk = scrypt(NFC(passphrase), salt, N = 2^17, r = 8, p = 1, 32 bytes) +dh = X25519(own ephemeral private key, peer ephemeral public key) (all-zero result is rejected) +keys = HKDF-SHA256(ikm = dh | pk, salt = transcript, info = "netpaste/2 session keys", 128 bytes) + = clientToHub | hubToClient | clientProofKey | hubProofKey +``` + +- The client sends `AUTH = HMAC-SHA256(clientProofKey, "netpaste/2 client proof" | transcript)`. +- The hub checks the client proof with a constant-time comparison. + - **Wrong proof:** the hub waits 1 s, sends `ERROR 1`, and closes the connection. It also blocks the IP address for 1 s; every further failure doubles the block, up to 60 s. + - **Correct proof:** the hub sends `AUTH = HMAC-SHA256(hubProofKey, "netpaste/2 server proof" | transcript)`. +- The client checks the hub proof. If it is wrong, the client closes the connection and tries again later. + +The passphrase is normalized to Unicode NFC, so the same passphrase typed on macOS and on Linux gives the same key. +The hub runs at most 2 scrypt computations at the same time (each needs 128 MiB). +The whole handshake must finish within 10 s. + +## Messages + +Every message after the handshake is a SEALED frame: + +- **Key:** `clientToHub` or `hubToClient`, depending on the direction. +- **Nonce:** 12 bytes: 4 zero bytes | 64-bit message counter of that direction, starting at 0. +- **Additional authenticated data:** the 5-byte frame header. + +The plaintext is `kind (u8) | payload`: + +| Kind | Name | Payload | +|---|---|---| +| 1 | CLIP | clipboard text, UTF-8, unchanged | +| 2 | PING | empty; the peer answers with PONG | +| 3 | PONG | empty | +| 4 | INFO | JSON `{"name": string, "version": string, "maxTextBytes": number}`, sent first by both sides | + +A receiver ignores unknown kinds, so later versions can add messages. +The sender never sends text above `min(own limit, peer limit)`. +The receiver closes the connection when the text is above its own limit. + +Liveness: + +- A side sends PING when it sent nothing for 15 s. +- A side closes the connection when it received nothing for 45 s. +- TCP keepalive is on as well. + +## Hub behaviour + +- **Text from a client:** the hub writes it to its own clipboard (unless `--no-clipboard`) and forwards it to all other clients. The sender does not get it back. +- **Local copy on the hub:** the hub sends it to all clients. +- **No peers connected:** the clipboard is not read. +- **Echo suppression:** based on content, not on a time window. The text that netpaste writes becomes the "last known" value, so the next poll sees no change. A poll that overlaps a write is discarded. + +## Discovery + +The hub announces `_netpaste._tcp.local` with TXT `v=2`. The instance name is the computer name. + +The SRV target is a separate name for each run, `netpaste--.local`, not the computer's own +`.local`. The system mDNS responder (mDNSResponder on macOS, Avahi on Linux) owns `.local`. +If a second responder announces A/AAAA records for that name, the system sees a conflict and renames the +computer, for example to `-2.local`. Clients connect to the address the answer came from. + +`netpaste connect` without HOST searches for 3 s: + +- exactly one hub found: the client connects to it; +- several hubs found: the client stops and lists them; +- no hub found: the client tries again with backoff. + +## Security properties + +| Threat | Result | +|---|---| +| Passive eavesdropper | Cannot read messages. Cannot test passphrase guesses: the proofs depend on the X25519 secret. | +| Stranger connects to the hub | Receives only the hub's HELLO: one ephemeral key, nothing that depends on the passphrase. Gets one online guess per connection, then the IP address is blocked. | +| Changed, replayed, reordered or reflected message | GCM authentication fails, the connection closes. Keys differ per direction and per connection. | +| Recorded traffic, passphrase leaks later | Old sessions stay secret: the keys also depend on ephemeral X25519 keys (forward secrecy). | +| Active attacker poses as the hub (mDNS spoofing, MITM) | Can try passphrase guesses **offline** against the client proof, one scrypt run per guess. Both sides contribute to the salt, so precomputed tables do not help. Only a long passphrase protects here; a PAKE (for example CPace) would remove this attack. | +| Malformed input | Closes that connection. Frame sizes are checked before buffering. | + +Not hidden: the size of each message, and the time of each copy. + +## Changes from version 1 + +Version 1 had these problems: + +- unauthenticated AES-CTR: anyone could change text, and could forge messages from the known HELLO plaintext; +- the HELLO message gave material for offline passphrase guessing to anyone who connected; +- the framing broke on normal TCP segmentation; +- input of 4 bytes crashed the process. + +Version 2 replaces the whole wire format. From 071af1c08d8621cc869c1e80ab23e182a51eb815 Mon Sep 17 00:00:00 2001 From: Aliaksei Smirnou Date: Thu, 19 Nov 2026 09:25:31 +0100 Subject: [PATCH 8/9] fix: harden v2 after an independent review Security and robustness: - Unread input is bounded: FrameReader pauses the socket when more than one maximum-size frame + 64 KiB waits unread. Before, a stranger could make the hub buffer 600 MB while it ran scrypt. - The hub runs scrypt only after the client proof arrives, so a HELLO alone costs it nothing; a connection dropped during scrypt gets no answer. - Connections without the passphrase are limited (4 per address, 32 total), separately from authenticated peers (32). IPv6 addresses count per /64. - A wrong passphrase blocks the address at once (the block counts from the delayed reply) and closes its other pending connections: at most 2 guesses per block period instead of 32. - ERROR frames are not authenticated: "wrong passphrase" counts only after our own proof, and it stops the client only for an explicitly given hub. For a hub found with mDNS (or several of them) the client keeps trying. Correctness: - Client.close() during mDNS discovery stopped nothing; the search is now abortable and the client checks the signal before it connects. - The idle timeout counts every received chunk, so a large text on a slow link is not cut; heartbeats use a monotonic clock and are checked every 5 s. - The hub sends no text to a peer before its INFO (unknown limit), nor to a peer that does not read (bounded send queue). - Clipboard watcher: after a failed write, the next read becomes the baseline instead of a concurrent re-read (no echo, no old text sent out). - Passphrase prompt: a stray ESC no longer swallows Enter or Ctrl+C; TAB is kept; NETPASTE_PASSPHRASE is removed even when --passphrase-file wins. - CLI: host names are validated; --host with a specific address turns the mDNS announcement off; --max-size is capped at 64 MiB (clipboardy reads through a 100 MB buffer); the Node.js check also rejects 23.0-23.5. Co-Authored-By: Claude Opus 5.5 --- bin/netpaste.js | 4 +- src/address.ts | 32 +++++++ src/args.ts | 7 +- src/client.ts | 27 ++++-- src/clipboard.ts | 8 +- src/config.ts | 12 ++- src/discovery.ts | 13 ++- src/frame-reader.ts | 34 ++++++- src/handshake.ts | 37 +++++--- src/main.ts | 16 ++-- src/passphrase.ts | 23 +++-- src/server.ts | 122 +++++++++++++++---------- src/session.ts | 46 ++++++---- test/address.test.ts | 22 +++++ test/args.test.ts | 10 ++- test/clipboard.test.ts | 26 ++++++ test/e2e.test.ts | 182 ++++++++++++++++++++++++++++++++++++-- test/frame-reader.test.ts | 52 +++++++++++ test/handshake.test.ts | 45 ++++++---- test/helpers.ts | 16 ++++ test/passphrase.test.ts | 13 ++- 21 files changed, 616 insertions(+), 131 deletions(-) create mode 100644 src/address.ts create mode 100644 test/address.test.ts create mode 100644 test/frame-reader.test.ts diff --git a/bin/netpaste.js b/bin/netpaste.js index f063533..61ecda0 100755 --- a/bin/netpaste.js +++ b/bin/netpaste.js @@ -1,7 +1,9 @@ #!/usr/bin/env node // Plain JavaScript on purpose: it runs on any Node.js version and explains what is missing. +// Node.js runs TypeScript without flags from 22.18 (22.x line), 23.6 and every later version. const [major, minor] = process.versions.node.split('.').map(Number); -if (major < 22 || (major === 22 && minor < 18)) { +const supported = major > 23 || (major === 23 && minor >= 6) || (major === 22 && minor >= 18); +if (!supported) { console.error(`netpaste needs Node.js 22.18 or newer (it runs TypeScript directly); this is Node.js ${process.versions.node}.`); process.exit(1); } diff --git a/src/address.ts b/src/address.ts new file mode 100644 index 0000000..d2bed4d --- /dev/null +++ b/src/address.ts @@ -0,0 +1,32 @@ +import net from 'node:net'; + +/** "192.168.1.5:8134", "[fe80::1]:8134"; IPv4-mapped IPv6 addresses are shown as IPv4. */ +export function formatAddress(address: string | undefined, port: number | undefined): string { + if (!address) return 'unknown'; + const host = unmapIPv4(address); + const shown = host.includes(':') ? `[${host}]` : host; + return port === undefined ? shown : `${shown}:${port}`; +} + +/** + * Key for per-address limits and blocks: the IPv4 address, or the /64 prefix of an IPv6 address. + * One host usually owns a whole IPv6 /64, so blocking single IPv6 addresses would be easy to evade. + */ +export function addressKey(address: string | undefined): string { + if (!address) return 'unknown'; + const host = unmapIPv4(address); + if (!net.isIPv6(host)) return host; + const [withoutZone = ''] = host.split('%'); + const [head = '', tail] = withoutZone.split('::'); + const headGroups = head ? head.split(':') : []; + const tailGroups = tail ? tail.split(':') : []; + const groups = tail === undefined ? headGroups : [...headGroups, ...Array(8 - headGroups.length - tailGroups.length).fill('0'), ...tailGroups]; + return `${groups + .slice(0, 4) + .map((group) => parseInt(group || '0', 16).toString(16)) + .join(':')}::/64`; +} + +function unmapIPv4(address: string): string { + return address.startsWith('::ffff:') && net.isIPv4(address.slice(7)) ? address.slice(7) : address; +} diff --git a/src/args.ts b/src/args.ts index 26d0666..2b4a189 100644 --- a/src/args.ts +++ b/src/args.ts @@ -1,3 +1,4 @@ +import net from 'node:net'; import { parseArgs } from 'node:util'; import { DEFAULT_MAX_TEXT_BYTES, @@ -134,19 +135,23 @@ export function parseTarget(value: string, flagPort?: number): { host: string; p const bracketed = /^\[([^\]]+)\](?::(.*))?$/.exec(value); if (bracketed) { host = bracketed[1]!; + if (!net.isIPv6(host)) throw new UsageError(`only an IPv6 address can be in brackets: "${value}"`); if (bracketed[2] !== undefined) port = parsePort(bracketed[2]); } else if (value.split(':').length === 2) { const [h, p] = value.split(':') as [string, string]; host = h; port = parsePort(p); } - if (host.length === 0) throw new UsageError(`invalid host "${value}"`); + if (!net.isIP(host) && !HOST_NAME.test(host)) throw new UsageError(`invalid host "${value}" (examples: studio.local, 192.168.1.10, [fe80::1]:8134)`); if (port !== undefined && flagPort !== undefined && port !== flagPort) { throw new UsageError(`port ${port} in "${value}" conflicts with --port ${flagPort}`); } return { host, port: port ?? flagPort ?? DEFAULT_PORT }; } +/** DNS host name: labels of letters, digits, "-" (and "_", which some LAN names use), dot-separated. */ +const HOST_NAME = /^(?=.{1,253}\.?$)[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?(?:\.[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?)*\.?$/i; + export function parsePort(value: string): number { if (!/^\d+$/.test(value)) throw new UsageError(`invalid port "${value}"`); const port = Number(value); diff --git a/src/client.ts b/src/client.ts index 6c84796..c27cf9c 100644 --- a/src/client.ts +++ b/src/client.ts @@ -14,7 +14,8 @@ import type { KdfParams } from './crypto.ts'; import { FrameReader } from './frame-reader.ts'; import { HANDSHAKE_MAX_BODY_BYTES, HandshakeError, clientHandshake } from './handshake.ts'; import { type Logger, formatCount } from './log.ts'; -import { Session, formatAddress } from './session.ts'; +import { formatAddress } from './address.ts'; +import { Session } from './session.ts'; export interface Target { host: string; @@ -24,7 +25,8 @@ export interface Target { export interface ClientOptions { /** Server address; null = call `findServer` before every connection attempt. */ target: Target | null; - findServer?: (() => Promise) | undefined; + /** Finds the server (mDNS). It should stop early when the signal aborts. */ + findServer?: ((signal: AbortSignal) => Promise) | undefined; passphrase: string; /** null = do not use the local clipboard (only log what arrives). */ clipboard: ClipboardWatcher | null; @@ -65,22 +67,29 @@ export class Client extends EventEmitter { return this.#session; } - /** Connects and reconnects until `close()`. Rejects with `FatalError` when retrying cannot help. */ + /** + * Connects and reconnects until `close()`. Rejects with `FatalError` when retrying cannot help. + * Only an explicitly given server can make an error fatal: a server found with mDNS may be an + * impostor, and handshake ERROR frames are not authenticated. + */ async run(): Promise { const { signal } = this.#stop; const { log } = this.#options; + const discovered = this.#options.target === null; let attempt = 0; while (!signal.aborted) { let where = 'server'; try { - const target = this.#options.target ?? (await this.#options.findServer!()); + const target = this.#options.target ?? (await this.#options.findServer!(signal)); + signal.throwIfAborted(); where = formatAddress(target.host, target.port); if (await this.#connectOnce(target)) attempt = 0; } catch (error) { if (signal.aborted) break; const fatal = toFatal(error); - if (fatal) throw fatal; - logRetry(log, where, error); + if (fatal && !discovered) throw fatal; + if (fatal) log.error(`${where}: ${fatal.message}`); + else logRetry(log, where, error); } if (signal.aborted) break; const wait = backoffDelay(attempt++, this.#timings.reconnectMinMs, this.#timings.reconnectMaxMs); @@ -160,6 +169,7 @@ export class Client extends EventEmitter { const result = session.sendClip(text); if (result === 'sent') log.info(`→ ${formatCount(text.length)} chars sent to ${session.label}`); else if (result === 'too-large') log.warn(`not sent: ${formatCount(Buffer.byteLength(text))} bytes is above the size limit`); + else if (result === 'too-slow') log.warn('not sent: the server has not received the earlier data yet'); else log.info('not connected: local copy was not sent'); } } @@ -189,6 +199,11 @@ function logRetry(log: Logger, where: string, error: unknown): void { function connectTcp(target: Target, timeoutMs: number, signal: AbortSignal): Promise { return new Promise((resolve, reject) => { + // addEventListener('abort') does not fire for a signal that is already aborted. + if (signal.aborted) { + reject(new Error('stopped')); + return; + } const socket = net.connect({ host: target.host, port: target.port }); const cleanup = () => { clearTimeout(timer); diff --git a/src/clipboard.ts b/src/clipboard.ts index 1f379f5..20f853b 100644 --- a/src/clipboard.ts +++ b/src/clipboard.ts @@ -111,9 +111,11 @@ export class ClipboardWatcher extends EventEmitter { await write; } catch (error) { this.#options.log.error(`cannot write to the clipboard: ${errorMessage(error)}`); - // Resynchronize with what is really in the clipboard, so the old text is not sent out as "new". - const actual = await this.#read(); - if (actual !== null) this.#last = actual; + // The clipboard content is unknown now. The next successful poll takes it as the baseline + // and does not send it, so old text never goes out as a "new" copy. A copy that the user + // makes during this short window is not sent either: that is the safer of the two failures. + // (A re-read here could overlap the next queued write and cause an echo.) + this.#baselinePending = true; } finally { this.#pendingWrites--; this.#generation++; diff --git a/src/config.ts b/src/config.ts index 939a860..1220ff5 100644 --- a/src/config.ts +++ b/src/config.ts @@ -9,14 +9,20 @@ export const MDNS_SERVICE_TYPE = 'netpaste'; /** Default upper limit for one clipboard text, in UTF-8 bytes. */ export const DEFAULT_MAX_TEXT_BYTES = 10 * 1024 * 1024; export const MIN_TEXT_BYTES = 1024; -export const MAX_TEXT_BYTES_CEILING = 256 * 1024 * 1024; +/** clipboardy reads through execa with a 100 MB output limit; stay well below it. */ +export const MAX_TEXT_BYTES_CEILING = 64 * 1024 * 1024; export const DEFAULT_POLL_INTERVAL_MS = 1000; export const MIN_POLL_INTERVAL_MS = 100; export const MAX_POLL_INTERVAL_MS = 60_000; -/** The server drops new TCP connections above this number (authenticated or not). */ -export const MAX_CONNECTIONS = 32; +/** Most authenticated peers of one hub. */ +export const MAX_SESSIONS = 32; +/** Most connections that have not proved the passphrase yet: in total, and from one address (IPv6: one /64). */ +export const MAX_PENDING = 32; +export const MAX_PENDING_PER_ADDRESS = 4; +/** Hard cap for all TCP connections of the hub; Node closes connections above it. */ +export const MAX_CONNECTIONS = MAX_SESSIONS + MAX_PENDING + 16; /** How many passphrase key derivations (scrypt, ~128 MiB each) the server runs at once. */ export const MAX_CONCURRENT_KDF = 2; diff --git a/src/discovery.ts b/src/discovery.ts index f1c7516..9276796 100644 --- a/src/discovery.ts +++ b/src/discovery.ts @@ -80,7 +80,9 @@ export function advertise(port: number, name: string, log: Logger, transport?: M }; } -export async function discoverServers(timeoutMs: number, transport?: MdnsTransport): Promise { +/** Searches for `timeoutMs`. Rejects with the signal's reason when the signal aborts first. */ +export async function discoverServers(timeoutMs: number, transport?: MdnsTransport, signal?: AbortSignal): Promise { + signal?.throwIfAborted(); let failure: Error | null = null; const bonjour = createBonjour(transport, (error: Error) => { failure ??= error; @@ -94,9 +96,12 @@ export async function discoverServers(timeoutMs: number, transport?: MdnsTranspo const name = sanitizeForTerminal(service.name) || 'unnamed'; found.set(`${name}|${host}|${service.port}`, { name, host, port: service.port }); }); - await sleep(timeoutMs); - browser.stop(); - await Promise.race([new Promise((resolve) => bonjour.destroy(() => resolve())), sleep(1000)]); + try { + await sleep(timeoutMs, undefined, signal ? { signal } : {}); + } finally { + browser.stop(); + await Promise.race([new Promise((resolve) => bonjour.destroy(() => resolve())), sleep(1000)]); + } if (failure && found.size === 0) throw new Error(`mDNS search failed: ${(failure as Error).message}`); return [...found.values()].sort((a, b) => a.name.localeCompare(b.name) || a.host.localeCompare(b.host)); } diff --git a/src/frame-reader.ts b/src/frame-reader.ts index 86882c8..02b0423 100644 --- a/src/frame-reader.ts +++ b/src/frame-reader.ts @@ -1,25 +1,36 @@ import type { Duplex } from 'node:stream'; -import { FrameDecoder, type Frame } from './frame.ts'; +import { type Frame, FrameDecoder, HEADER_BYTES } from './frame.ts'; export class ConnectionClosedError extends Error { override name = 'ConnectionClosedError'; } +/** Bytes that may wait in the decoder beyond one maximum-size frame before reading pauses. */ +const SLACK_BYTES = 64 * 1024; + /** * Pull-based frame reader over a socket: `await reader.next()` returns one frame at a time. * The caller can change `maxBodyBytes` between frames, for example after the handshake. + * + * Memory is bounded: when more than one maximum-size frame (+ 64 KiB) waits unread, the reader + * pauses the socket, and TCP flow control stops the sender. Without this, a peer could stream + * gigabytes while the hub is busy with scrypt and nobody calls `next()`. + * * After the connection ends, the reader still returns the frames that arrived before the end, * then it throws the reason (`ConnectionClosedError`, a socket error, or a `FrameError`). */ export class FrameReader { - #decoder: FrameDecoder; + readonly #socket: Duplex; + readonly #decoder: FrameDecoder; #wake: (() => void) | null = null; #end: Error | null = null; constructor(socket: Duplex, maxBodyBytes: number) { + this.#socket = socket; this.#decoder = new FrameDecoder(maxBodyBytes); socket.on('data', (chunk: Buffer) => { this.#decoder.push(chunk); + if (this.#decoder.bufferedBytes > this.#highWaterMark()) socket.pause(); this.#notify(); }); socket.on('end', () => this.#finish(new ConnectionClosedError('the peer closed the connection'))); @@ -35,17 +46,34 @@ export class FrameReader { this.#decoder.maxBodyBytes = value; } + /** Bytes received but not yet returned as frames. */ + get bufferedBytes(): number { + return this.#decoder.bufferedBytes; + } + async next(): Promise { for (;;) { const frame = this.#decoder.next(); - if (frame) return frame; + if (frame) { + this.#resumeIfRoom(); + return frame; + } if (this.#end) throw this.#end; + this.#resumeIfRoom(); await new Promise((resolve) => { this.#wake = resolve; }); } } + #highWaterMark(): number { + return this.#decoder.maxBodyBytes + HEADER_BYTES + SLACK_BYTES; + } + + #resumeIfRoom(): void { + if (this.#socket.isPaused() && this.#decoder.bufferedBytes <= this.#highWaterMark()) this.#socket.resume(); + } + #notify(): void { const wake = this.#wake; this.#wake = null; diff --git a/src/handshake.ts b/src/handshake.ts index efe4d7c..04a3de0 100644 --- a/src/handshake.ts +++ b/src/handshake.ts @@ -7,12 +7,14 @@ * │ transcript = SHA-256(label | helloC | helloS) │ * │ pk = scrypt(passphrase, SHA-256(label | transcript)) * │ keys = HKDF(X25519(e, e') | pk, transcript) │ - * │── AUTH HMAC(clientProofKey, transcript) ────────▶│ wrong → delay, ERROR, close + * │── AUTH HMAC(clientProofKey, transcript) ────────▶│ wrong → block address, delay, ERROR, close * │◀── AUTH HMAC(serverProofKey, transcript) ────────│ * │════════ Sealed frames, AES-256-GCM ════════════════│ * * - A passive eavesdropper cannot test passphrase guesses: the proofs depend on the X25519 secret. * - The server proves nothing before the client does, so a stranger that connects learns nothing. + * - The server runs scrypt only after it has the client proof, so each scrypt run costs the + * other side a passphrase attempt (and a wrong attempt blocks its address). * - Both sides add a fresh key to the scrypt salt, so a fake server cannot reuse precomputed guesses. * - An active man-in-the-middle (or a fake server) can still guess the passphrase offline from the * client proof, one scrypt run per guess. A long passphrase makes this impractical. @@ -75,6 +77,10 @@ export interface HandshakeOptions { kdfLimiter?: Limiter; /** Server: wait this long before it reports a wrong passphrase. */ authFailureDelayMs?: number; + /** Server: asked right before scrypt; false drops the connection (for example, its address was blocked meanwhile). */ + admit?: () => boolean; + /** Server: called at once when the client proof is wrong, before the delay. */ + onWrongPassphrase?: () => void; } export async function clientHandshake(socket: Duplex, reader: FrameReader, options: HandshakeOptions): Promise { @@ -82,7 +88,7 @@ export async function clientHandshake(socket: Duplex, reader: FrameReader, optio const helloClient = encodeHello(Role.Client, ephemeral.publicKey); socket.write(encodeFrame(FrameType.Hello, helloClient)); - const helloServer = expectFrame(await readHandshakeFrame(reader), FrameType.Hello).body; + const helloServer = expectFrame(await readHandshakeFrame(reader, false), FrameType.Hello).body; const peerKey = parseHello(helloServer, Role.Server); const transcript = transcriptHash(helloClient, helloServer); const shared = x25519(ephemeral.privateKey, peerKey); @@ -91,7 +97,7 @@ export async function clientHandshake(socket: Duplex, reader: FrameReader, optio socket.write(encodeFrame(FrameType.Auth, proof(secrets.clientProofKey, 'client', transcript))); - const serverProof = expectFrame(await readHandshakeFrame(reader), FrameType.Auth).body; + const serverProof = expectFrame(await readHandshakeFrame(reader, true), FrameType.Auth).body; if (!constantTimeEqual(serverProof, proof(secrets.serverProofKey, 'server', transcript))) { throw new HandshakeError('peer-unverified', 'the server could not prove that it knows the passphrase'); } @@ -99,7 +105,7 @@ export async function clientHandshake(socket: Duplex, reader: FrameReader, optio } export async function serverHandshake(socket: Duplex, reader: FrameReader, options: HandshakeOptions): Promise { - const helloClient = expectFrame(await readHandshakeFrame(reader), FrameType.Hello).body; + const helloClient = expectFrame(await readHandshakeFrame(reader, false), FrameType.Hello).body; let peerKey: Buffer; try { peerKey = parseHello(helloClient, Role.Client); @@ -117,15 +123,21 @@ export async function serverHandshake(socket: Duplex, reader: FrameReader, optio const transcript = transcriptHash(helloClient, helloServer); const shared = x25519(ephemeral.privateKey, peerKey); + + // Wait for the client proof before the expensive scrypt run: then every scrypt run on the hub + // belongs to a passphrase attempt, and a wrong attempt blocks the address. + const clientProof = expectFrame(await readHandshakeFrame(reader, false), FrameType.Auth).body; const derive = async () => { - if (socket.destroyed) throw new ConnectionClosedError('the connection was closed'); + if (socket.destroyed || options.admit?.() === false) throw new ConnectionClosedError('the connection was dropped'); return derivePassphraseKey(options.passphrase, kdfSalt(transcript), options.kdf); }; const passphraseKey = await (options.kdfLimiter ? options.kdfLimiter.run(derive) : derive()); + // The connection can be dropped during scrypt (another wrong guess from the same address): no answer then. + if (socket.destroyed) throw new ConnectionClosedError('the connection was dropped'); const secrets = deriveSessionSecrets(shared, passphraseKey, transcript); - const clientProof = expectFrame(await readHandshakeFrame(reader), FrameType.Auth).body; if (!constantTimeEqual(clientProof, proof(secrets.clientProofKey, 'client', transcript))) { + options.onWrongPassphrase?.(); await delay(options.authFailureDelayMs ?? 0); if (!socket.destroyed) socket.end(encodeFrame(FrameType.Error, Buffer.of(HandshakeErrorCode.AuthFailed))); throw new HandshakeError('peer-unverified', 'the client sent a wrong passphrase'); @@ -152,7 +164,8 @@ function parseHello(body: Buffer, expectedRole: RoleValue): Buffer { return body.subarray(MAGIC.length + 2); } -async function readHandshakeFrame(reader: FrameReader): Promise { +/** `proofSent`: whether we already sent our AUTH; a "wrong passphrase" error before that is not believable. */ +async function readHandshakeFrame(reader: FrameReader, proofSent: boolean): Promise { let frame: Frame; try { frame = await reader.next(); @@ -162,7 +175,7 @@ async function readHandshakeFrame(reader: FrameReader): Promise { } throw error; } - if (frame.type === FrameType.Error) throw remoteError(frame.body); + if (frame.type === FrameType.Error) throw remoteError(frame.body, proofSent); return frame; } @@ -171,10 +184,14 @@ function expectFrame(frame: Frame, type: number): Frame { return frame; } -/** Maps the peer's error code to our own text; the peer's bytes never reach the terminal. */ -function remoteError(body: Buffer): HandshakeError { +/** + * Maps the peer's error code to our own text; the peer's bytes never reach the terminal. + * ERROR frames are not authenticated, so callers must not trust them too much. + */ +function remoteError(body: Buffer, proofSent: boolean): HandshakeError { switch (body.length > 0 ? body.readUInt8(0) : 0) { case HandshakeErrorCode.AuthFailed: + if (!proofSent) return new HandshakeError('protocol', 'the peer reported a wrong passphrase before the passphrase check'); return new HandshakeError('rejected', 'the server rejected the passphrase'); case HandshakeErrorCode.VersionMismatch: return new HandshakeError('version-mismatch', 'the server speaks a different protocol version; update netpaste on both machines'); diff --git a/src/main.ts b/src/main.ts index ff30bfb..2b641f6 100644 --- a/src/main.ts +++ b/src/main.ts @@ -6,7 +6,7 @@ import { type FoundServer, advertise, discoverServers } from './discovery.ts'; import { type Logger, createLogger, sanitizeForTerminal } from './log.ts'; import { PassphraseError, PromptCancelledError, resolvePassphrase } from './passphrase.ts'; import { Hub } from './server.ts'; -import { formatAddress } from './session.ts'; +import { formatAddress } from './address.ts'; import { VERSION } from './version.ts'; const DISCOVERY_TIMEOUT_MS = 3000; @@ -79,7 +79,10 @@ async function serve(command: Extract, log: Logger, } const where = formatAddress(address.address === '::' || address.address === '0.0.0.0' ? '*' : address.address, address.port); log.info(`netpaste ${VERSION} is listening on ${where}; ${clipboard ? 'clipboard sync is on' : 'relay only (--no-clipboard)'}`); - const announcement = command.mdns ? advertise(address.port, localName, log) : null; + // bonjour-service announces the addresses of all interfaces, so a hub limited by --host is not announced. + const listensEverywhere = command.host === undefined || command.host === '0.0.0.0' || command.host === '::'; + if (command.mdns && !listensEverywhere) log.info('mDNS announcement is off because --host limits the listen address'); + const announcement = command.mdns && listensEverywhere ? advertise(address.port, localName, log) : null; if (announcement) log.info(`announced on the local network as "${localName}"`); await waitForSignal(); @@ -95,7 +98,7 @@ async function connect(command: Extract, log: Logg const clipboard = command.clipboard ? new ClipboardWatcher(await systemClipboard(), { intervalMs: command.options.intervalMs, log }) : null; const client = new Client({ target: command.target, - findServer: command.target ? undefined : () => findSingleServer(log), + findServer: command.target ? undefined : (signal) => findSingleServer(log, signal), passphrase, clipboard, maxTextBytes: command.options.maxTextBytes, @@ -129,13 +132,14 @@ async function discover(timeoutMs: number, log: Logger, io: MainIO): Promise { +/** Not fatal on purpose: anyone on the network can announce a service, and the client keeps trying. */ +async function findSingleServer(log: Logger, signal: AbortSignal): Promise { log.debug('looking for a netpaste server on the local network'); - const servers = await discoverServers(DISCOVERY_TIMEOUT_MS); + const servers = await discoverServers(DISCOVERY_TIMEOUT_MS, undefined, signal); if (servers.length === 0) throw new Error('no netpaste server found on the local network'); if (servers.length > 1) { const list = servers.map((s) => `"${s.name}" at ${formatAddress(s.host, s.port)}`).join(', '); - throw new FatalError(`found ${servers.length} servers: ${list}. Choose one: netpaste connect HOST[:PORT]`); + throw new Error(`found ${servers.length} servers: ${list}. Choose one: netpaste connect HOST[:PORT]`); } const [server] = servers as [FoundServer]; log.info(`found server "${server.name}" at ${formatAddress(server.host, server.port)}`); diff --git a/src/passphrase.ts b/src/passphrase.ts index 219002c..f4a26ba 100644 --- a/src/passphrase.ts +++ b/src/passphrase.ts @@ -23,13 +23,14 @@ export interface PassphraseSources { /** Order: --passphrase-file, then NETPASTE_PASSPHRASE, then a hidden prompt on the terminal. */ export async function resolvePassphrase({ file, env, stdin, prompt, log }: PassphraseSources): Promise { + const fromEnv = env[PASSPHRASE_ENV]; + // Child processes (pbcopy, xsel …) inherit the environment; they must not see the passphrase. + delete env[PASSPHRASE_ENV]; let passphrase: string; if (file) { passphrase = await readPassphraseFile(file, log); - } else if (env[PASSPHRASE_ENV]) { - passphrase = env[PASSPHRASE_ENV]; - // Child processes (pbcopy, xsel …) do not need it. - delete env[PASSPHRASE_ENV]; + } else if (fromEnv) { + passphrase = fromEnv; } else if (stdin.isTTY) { passphrase = await promptHidden('Passphrase: ', stdin, prompt); } else { @@ -103,9 +104,14 @@ export class HiddenLineEditor { for (const ch of input) { if (this.done || this.cancelled) break; if (this.#escape !== null) { - this.#escape += ch; - if (isCompleteEscape(this.#escape)) this.#escape = null; - continue; + // ESC followed by Enter, Ctrl+C, Backspace … : the ESC was a stray key press, not a sequence. + if (this.#escape === '\u001b' && /\p{Cc}/u.test(ch) && ch !== '\u001b') { + this.#escape = null; + } else { + this.#escape += ch; + if (isCompleteEscape(this.#escape)) this.#escape = null; + continue; + } } switch (ch) { case '\r': @@ -130,7 +136,8 @@ export class HiddenLineEditor { this.#escape = ch; break; default: - if (!/\p{Cc}/u.test(ch)) { + // TAB is a valid passphrase character (it is kept in files and in the environment too). + if (ch === '\t' || !/\p{Cc}/u.test(ch)) { this.#chars.push(ch); echo += '*'; } diff --git a/src/server.ts b/src/server.ts index b4270cc..b7f4f25 100644 --- a/src/server.ts +++ b/src/server.ts @@ -4,17 +4,29 @@ * client A ──▶ hub ──▶ client B, client C … (never back to A) * └────▶ local clipboard (unless --no-clipboard) * local clipboard change ──▶ all clients + * + * Connections that have not proved the passphrase are limited per address and in total, + * and an address that sent a wrong passphrase is blocked for a while. */ import { EventEmitter } from 'node:events'; import net from 'node:net'; +import { addressKey, formatAddress } from './address.ts'; import type { ClipboardWatcher } from './clipboard.ts'; -import { DEFAULT_TIMINGS, MAX_CONCURRENT_KDF, MAX_CONNECTIONS, type Timings } from './config.ts'; +import { + DEFAULT_TIMINGS, + MAX_CONCURRENT_KDF, + MAX_CONNECTIONS, + MAX_PENDING, + MAX_PENDING_PER_ADDRESS, + MAX_SESSIONS, + type Timings, +} from './config.ts'; import type { KdfParams } from './crypto.ts'; import { FrameReader } from './frame-reader.ts'; import { HANDSHAKE_MAX_BODY_BYTES, HandshakeError, serverHandshake } from './handshake.ts'; import { Limiter } from './limiter.ts'; import { type Logger, formatCount } from './log.ts'; -import { Session, formatAddress } from './session.ts'; +import { Session } from './session.ts'; export interface HubOptions { port: number; @@ -42,9 +54,10 @@ export class Hub extends EventEmitter { readonly #timings: Timings; readonly #server: net.Server; readonly #sessions = new Set(); - readonly #pending = new Set(); + /** Connections in the handshake, with their address key. */ + readonly #pending = new Map(); readonly #kdfLimiter = new Limiter(MAX_CONCURRENT_KDF); - /** Wrong-passphrase history per IP address, to slow down online guessing. */ + /** Wrong-passphrase history per address key, to slow down online guessing. */ readonly #authFailures = new Map(); #closing = false; @@ -54,6 +67,7 @@ export class Hub extends EventEmitter { this.#timings = { ...DEFAULT_TIMINGS, ...options.timings }; this.#server = net.createServer((socket) => void this.#accept(socket)); this.#server.maxConnections = MAX_CONNECTIONS; + this.#server.on('drop', (data) => options.log.debug(`dropped a connection from ${formatAddress(data?.remoteAddress, data?.remotePort)}: too many connections`)); options.clipboard?.on('change', (text) => this.#onLocalChange(text)); } @@ -84,67 +98,52 @@ export class Hub extends EventEmitter { this.#closing = true; this.#options.clipboard?.stop(); const closed = new Promise((resolve) => this.#server.close(() => resolve())); - for (const socket of this.#pending) socket.destroy(); + for (const socket of this.#pending.keys()) socket.destroy(); for (const session of this.#sessions) session.close(); await closed; } - /** Returns how long the address is now blocked. */ - #recordAuthFailure(ip: string): number { - const now = Date.now(); - if (this.#authFailures.size > 1000) { - for (const [key, entry] of this.#authFailures) { - if (entry.blockedUntil < now) this.#authFailures.delete(key); - } - } - const count = (this.#authFailures.get(ip)?.count ?? 0) + 1; - const blockMs = Math.min(this.#timings.authBlockMaxMs, this.#timings.authBlockBaseMs * 2 ** Math.min(count - 1, 20)); - this.#authFailures.set(ip, { count, blockedUntil: now + blockMs }); - return blockMs; - } - - /** Reads the clipboard only while at least one peer is ready to receive. */ - #updateClipboardWatcher(): void { - const { clipboard } = this.#options; - if (!clipboard || this.#closing) return; - if ([...this.#sessions].some((session) => session.peer !== null)) void clipboard.start(); - else clipboard.stop(); - } - async #accept(socket: net.Socket): Promise { const { log } = this.#options; const remote = formatAddress(socket.remoteAddress, socket.remotePort); - const ip = formatAddress(socket.remoteAddress, undefined); - if (this.#closing) { + const key = addressKey(socket.remoteAddress); + const refuse = (reason: string) => { + log.debug(`refused ${remote}: ${reason}`); socket.destroy(); - return; - } - const blocked = this.#authFailures.get(ip); - if (blocked && Date.now() < blocked.blockedUntil) { - log.debug(`refused ${remote}: wrong passphrase recently, blocked for ${Math.ceil((blocked.blockedUntil - Date.now()) / 1000)} s`); - socket.destroy(); - return; - } + }; + if (this.#closing) return refuse('the hub is stopping'); + const blockedFor = this.#blockedFor(key); + if (blockedFor > 0) return refuse(`wrong passphrase recently, blocked for ${Math.ceil(blockedFor / 1000)} s`); + if (this.#sessions.size >= MAX_SESSIONS) return refuse(`the hub already has ${MAX_SESSIONS} peers`); + if (this.#pending.size >= MAX_PENDING) return refuse('too many connections without a passphrase'); + if (this.#pendingFrom(key) >= MAX_PENDING_PER_ADDRESS) return refuse('too many connections without a passphrase from this address'); + socket.setNoDelay(true); socket.setKeepAlive(true, this.#timings.heartbeatIntervalMs); - this.#pending.add(socket); + this.#pending.set(socket, key); log.debug(`connection from ${remote}`); const reader = new FrameReader(socket, HANDSHAKE_MAX_BODY_BYTES); const timer = setTimeout(() => socket.destroy(new Error('handshake timed out')), this.#timings.handshakeTimeoutMs); + let blockMs = 0; let channel; try { channel = await serverHandshake(socket, reader, { passphrase: this.#options.passphrase, kdfLimiter: this.#kdfLimiter, authFailureDelayMs: this.#timings.authFailureDelayMs, + admit: () => !this.#closing && this.#blockedFor(key) === 0, + onWrongPassphrase: () => { + blockMs = this.#recordAuthFailure(key); + // Other connections from the same address must not keep guessing in parallel. + for (const [other, otherKey] of this.#pending) if (otherKey === key && other !== socket) other.destroy(); + }, ...(this.#options.kdf ? { kdf: this.#options.kdf } : {}), }); } catch (error) { socket.destroy(); if (error instanceof HandshakeError && error.failure === 'peer-unverified') { - const blockMs = this.#recordAuthFailure(ip); - log.warn(`rejected ${remote}: wrong passphrase; this address is blocked for ${(blockMs / 1000).toFixed(0)} s`); + log.warn(`rejected ${remote}: wrong passphrase; the address is blocked for ${Math.round(blockMs / 1000)} s`); this.emit('auth-failed', remote); } else if (error instanceof HandshakeError) { log.warn(`rejected ${remote}: ${error.message}`); @@ -156,7 +155,7 @@ export class Hub extends EventEmitter { clearTimeout(timer); this.#pending.delete(socket); } - this.#authFailures.delete(ip); + this.#authFailures.delete(key); const session = new Session(socket, reader, channel, { maxTextBytes: this.#options.maxTextBytes, @@ -182,6 +181,39 @@ export class Hub extends EventEmitter { session.start(); } + #pendingFrom(key: string): number { + let count = 0; + for (const pendingKey of this.#pending.values()) if (pendingKey === key) count++; + return count; + } + + /** Milliseconds the address is still blocked, or 0. */ + #blockedFor(key: string): number { + const entry = this.#authFailures.get(key); + return entry ? Math.max(0, entry.blockedUntil - Date.now()) : 0; + } + + /** Records a wrong passphrase and returns how long the address is now blocked. */ + #recordAuthFailure(key: string): number { + const now = Date.now(); + if (this.#authFailures.size > 1000) { + for (const [other, entry] of this.#authFailures) if (entry.blockedUntil < now) this.#authFailures.delete(other); + } + const count = (this.#authFailures.get(key)?.count ?? 0) + 1; + const blockMs = Math.min(this.#timings.authBlockMaxMs, this.#timings.authBlockBaseMs * 2 ** Math.min(count - 1, 20)); + // The block starts now, but the ERROR goes out only after the failure delay: count the block from then. + this.#authFailures.set(key, { count, blockedUntil: now + this.#timings.authFailureDelayMs + blockMs }); + return blockMs; + } + + /** Reads the clipboard only while at least one peer is ready to receive. */ + #updateClipboardWatcher(): void { + const { clipboard } = this.#options; + if (!clipboard || this.#closing) return; + if ([...this.#sessions].some((session) => session.peer !== null)) void clipboard.start(); + else clipboard.stop(); + } + #onRemoteClip(from: Session, text: string): void { const { log, clipboard } = this.#options; log.info(`← ${formatCount(text.length)} chars from ${from.label}`); @@ -192,14 +224,12 @@ export class Hub extends EventEmitter { #onLocalChange(text: string): void { const { log } = this.#options; - if (this.#sessions.size === 0) { - log.debug(`local copy of ${formatCount(text.length)} chars: no peers connected`); - return; - } const sent = this.#broadcast(text, null); if (sent > 0) log.info(`→ ${formatCount(text.length)} chars sent to ${sent} peer${sent === 1 ? '' : 's'}`); + else log.debug(`local copy of ${formatCount(text.length)} chars: no peer received it`); } + /** Sends to every ready peer except `except`; returns how many peers got the text. */ #broadcast(text: string, except: Session | null): number { let sent = 0; for (const session of this.#sessions) { @@ -208,6 +238,8 @@ export class Hub extends EventEmitter { if (result === 'sent') sent++; else if (result === 'too-large') { this.#options.log.warn(`not sent to ${session.label}: ${formatCount(Buffer.byteLength(text))} bytes is above the size limit`); + } else if (result === 'too-slow') { + this.#options.log.warn(`not sent to ${session.label}: the peer has not received the earlier data yet`); } } return sent; diff --git a/src/session.ts b/src/session.ts index 32bd2a4..ae830d9 100644 --- a/src/session.ts +++ b/src/session.ts @@ -10,6 +10,7 @@ */ import { EventEmitter } from 'node:events'; import type { Socket } from 'node:net'; +import { formatAddress } from './address.ts'; import { MAX_TEXT_BYTES_CEILING, MIN_TEXT_BYTES } from './config.ts'; import { type SecureChannel, TAG_BYTES } from './crypto.ts'; import { FrameType } from './frame.ts'; @@ -40,7 +41,11 @@ interface SessionEvents { close: [error: Error | null]; } -export type SendResult = 'sent' | 'too-large' | 'closed'; +/** + * - `not-ready`: the peer has not sent INFO yet, so its size limit is unknown; + * - `too-slow`: the peer has not received the earlier data yet (the send queue is full). + */ +export type SendResult = 'sent' | 'too-large' | 'too-slow' | 'not-ready' | 'closed'; export class ProtocolError extends Error { override name = 'ProtocolError'; @@ -52,6 +57,8 @@ export class PeerTimeoutError extends Error { /** INFO and other control messages must fit even when the text limit is small. */ const MIN_BODY_BYTES = 4096; +/** Room in the send queue above one maximum-size text. Above it, texts are skipped for that peer. */ +const QUEUE_SLACK_BYTES = 1024 * 1024; export class Session extends EventEmitter { readonly remoteAddress: string; @@ -90,18 +97,26 @@ export class Session extends EventEmitter { this.#idle = setTimeout(() => { this.#finish(new PeerTimeoutError(`no data from the peer for ${Math.round(this.#options.idleTimeoutMs / 1000)} s`)); }, this.#options.idleTimeoutMs); - this.#heartbeat = setInterval(() => { - if (Date.now() - this.#lastSentAt >= this.#options.heartbeatIntervalMs) this.#send(MessageKind.Ping); - }, this.#options.heartbeatIntervalMs); + // Any received bytes prove that the peer is alive, also in the middle of a large text on a slow link. + this.#socket.on('data', () => this.#idle?.refresh()); + // Check three times per interval, so a PING goes out 15–20 s after the last frame, not 15–30 s. + // performance.now() is monotonic: a clock change does not stop the heartbeats. + this.#heartbeat = setInterval( + () => { + if (performance.now() - this.#lastSentAt >= this.#options.heartbeatIntervalMs) this.#send(MessageKind.Ping); + }, + Math.max(1, Math.floor(this.#options.heartbeatIntervalMs / 3)), + ); void this.#readLoop(); } - /** Sends clipboard text. Text larger than our or the peer's limit is not sent. */ + /** Sends clipboard text, unless it is above our or the peer's limit, or the peer is not ready or too slow. */ sendClip(text: string): SendResult { if (this.#closed) return 'closed'; + if (!this.peer) return 'not-ready'; const bytes = Buffer.from(text, 'utf8'); - const limit = Math.min(this.#options.maxTextBytes, this.peer?.maxTextBytes ?? Number.POSITIVE_INFINITY); - if (bytes.length > limit) return 'too-large'; + if (bytes.length > Math.min(this.#options.maxTextBytes, this.peer.maxTextBytes)) return 'too-large'; + if (this.#queueFull()) return 'too-slow'; this.#send(MessageKind.Clip, bytes); return 'sent'; } @@ -114,7 +129,12 @@ export class Session extends EventEmitter { #send(kind: number, payload: Buffer = Buffer.alloc(0)): void { if (this.#closed || this.#socket.destroyed) return; this.#socket.write(this.#channel.seal(Buffer.concat([Buffer.of(kind), payload]))); - this.#lastSentAt = Date.now(); + this.#lastSentAt = performance.now(); + } + + /** A peer that does not read must not make our send queue grow without a limit. */ + #queueFull(): boolean { + return this.#socket.writableLength > this.#options.maxTextBytes + QUEUE_SLACK_BYTES; } async #readLoop(): Promise { @@ -139,7 +159,7 @@ export class Session extends EventEmitter { if (payload.length > 0) this.emit('clip', payload.toString('utf8')); break; case MessageKind.Ping: - this.#send(MessageKind.Pong); + if (!this.#queueFull()) this.#send(MessageKind.Pong); break; case MessageKind.Pong: break; @@ -186,14 +206,6 @@ export function parsePeerInfo(payload: Buffer): PeerInfo { }; } -/** "192.168.1.5:8134", "[fe80::1]:8134"; IPv4-mapped IPv6 addresses are shown as IPv4. */ -export function formatAddress(address: string | undefined, port: number | undefined): string { - if (!address) return 'unknown'; - const host = address.startsWith('::ffff:') ? address.slice(7) : address; - const shown = host.includes(':') ? `[${host}]` : host; - return port === undefined ? shown : `${shown}:${port}`; -} - function asError(value: unknown): Error { return value instanceof Error ? value : new Error(String(value)); } diff --git a/test/address.test.ts b/test/address.test.ts new file mode 100644 index 0000000..ae2b1cf --- /dev/null +++ b/test/address.test.ts @@ -0,0 +1,22 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { addressKey, formatAddress } from '../src/address.ts'; + +describe('addresses', () => { + it('formats IPv4, IPv4-mapped and IPv6 addresses', () => { + assert.equal(formatAddress('192.168.1.5', 8134), '192.168.1.5:8134'); + assert.equal(formatAddress('::ffff:192.168.1.5', 8134), '192.168.1.5:8134'); + assert.equal(formatAddress('fe80::1', 8134), '[fe80::1]:8134'); + assert.equal(formatAddress(undefined, 1), 'unknown'); + }); + + it('blocks IPv4 per address and IPv6 per /64', () => { + assert.equal(addressKey('192.168.1.5'), '192.168.1.5'); + assert.equal(addressKey('::ffff:192.168.1.5'), '192.168.1.5'); + assert.equal(addressKey('2001:db8:1:2:aaaa:bbbb:cccc:dddd'), '2001:db8:1:2::/64'); + assert.equal(addressKey('2001:db8:1:2::99'), '2001:db8:1:2::/64'); + assert.equal(addressKey('2001:db8::1'), '2001:db8:0:0::/64'); + assert.equal(addressKey('::1'), '0:0:0:0::/64'); + assert.equal(addressKey('fe80::1%en0'), 'fe80:0:0:0::/64'); + }); +}); diff --git a/test/args.test.ts b/test/args.test.ts index 7c974ea..6d0e828 100644 --- a/test/args.test.ts +++ b/test/args.test.ts @@ -75,6 +75,13 @@ describe('parseTarget', () => { assert.deepEqual(parseTarget('[fe80::1]'), { host: 'fe80::1', port: 8134 }); assert.deepEqual(parseTarget('fe80::1'), { host: 'fe80::1', port: 8134 }); assert.deepEqual(parseTarget('box', 9100), { host: 'box', port: 9100 }); + assert.deepEqual(parseTarget('my_box.local.'), { host: 'my_box.local.', port: 8134 }); + }); + + it('rejects things that are not host names instead of retrying DNS forever', () => { + for (const value of ['box:9000:1', 'http://box:8134', 'bad host', '-box', 'a..b', '[nonsense]:8134']) { + assert.throws(() => parseTarget(value), UsageError, value); + } }); }); @@ -87,6 +94,7 @@ describe('parseSize', () => { }); it('rejects junk and out-of-range values', () => { - for (const value of ['abc', '10tb', '1b', '1000mb', '']) assert.throws(() => parseSize(value), UsageError, value); + for (const value of ['abc', '10tb', '1b', '1000mb', '100mb', '']) assert.throws(() => parseSize(value), UsageError, value); + assert.equal(parseSize('64mb'), 64 * 1024 * 1024); }); }); diff --git a/test/clipboard.test.ts b/test/clipboard.test.ts index a3f4ca2..ecf8362 100644 --- a/test/clipboard.test.ts +++ b/test/clipboard.test.ts @@ -125,6 +125,32 @@ describe('ClipboardWatcher', () => { assert.deepEqual(changes, []); }); + it('after a failed write, the next queued write is not echoed back', async () => { + const { backend, watcher, changes } = setup('old'); + await watcher.start(); + backend.failNextWrite = true; + await Promise.all([watcher.apply('first (fails)'), watcher.apply('second')]); + await watcher.poll(); + await watcher.poll(); + watcher.stop(); + assert.equal(backend.text, 'second'); + assert.deepEqual(changes, []); + }); + + it('when the first read and a write both fail, old text is never sent', async () => { + const { backend, watcher, changes } = setup('old private text'); + backend.failReads = true; // display not ready at login + await watcher.start(); + backend.failNextWrite = true; + await watcher.apply('from the network'); + backend.failReads = false; + await watcher.poll(); + backend.text = 'a real copy'; + await watcher.poll(); + watcher.stop(); + assert.deepEqual(changes, ['a real copy']); + }); + it('serializes writes in arrival order', async () => { const { backend, watcher } = setup(); await watcher.start(); diff --git a/test/e2e.test.ts b/test/e2e.test.ts index dfce6d4..8d26f86 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -7,9 +7,11 @@ import { Client, FatalError } from '../src/client.ts'; import { ClipboardWatcher } from '../src/clipboard.ts'; import { FrameType, encodeFrame } from '../src/frame.ts'; import { FrameReader } from '../src/frame-reader.ts'; -import { HANDSHAKE_MAX_BODY_BYTES, serverHandshake } from '../src/handshake.ts'; +import { MAX_CONCURRENT_KDF, MAX_PENDING_PER_ADDRESS } from '../src/config.ts'; +import { HANDSHAKE_MAX_BODY_BYTES, HandshakeErrorCode, clientHandshake, serverHandshake } from '../src/handshake.ts'; import { Hub } from '../src/server.ts'; -import { FAST_KDF, FAST_TIMINGS, MemoryClipboard, type RecordingLogger, recordingLogger, waitFor } from './helpers.ts'; +import { Session } from '../src/session.ts'; +import { FAST_KDF, FAST_TIMINGS, MemoryClipboard, type RecordingLogger, recordingLogger, socketPair, waitFor } from './helpers.ts'; const PASSPHRASE = 'correct horse battery staple'; const cleanups: Array<() => Promise | void> = []; @@ -32,11 +34,11 @@ function machine(initial: string): Machine { return { backend, watcher, log }; } -async function startHub(options: { clipboard?: Machine; port?: number; maxTextBytes?: number } = {}) { +async function startHub(options: { clipboard?: Machine; port?: number; maxTextBytes?: number; host?: string } = {}) { const log = options.clipboard?.log ?? recordingLogger(); const hub = new Hub({ port: options.port ?? 0, - host: '127.0.0.1', + host: options.host ?? '127.0.0.1', passphrase: PASSPHRASE, clipboard: options.clipboard?.watcher ?? null, maxTextBytes: options.maxTextBytes ?? 10 * 1024 * 1024, @@ -51,10 +53,19 @@ async function startHub(options: { clipboard?: Machine; port?: number; maxTextBy return { hub, port, log }; } -async function startClient(port: number, name: string, m: Machine | null, options: { passphrase?: string; maxTextBytes?: number } = {}) { +interface ClientTestOptions { + passphrase?: string; + maxTextBytes?: number; + host?: string; + /** Simulates mDNS discovery: the client gets the address from this function. */ + findServer?: (signal: AbortSignal) => Promise<{ host: string; port: number }>; +} + +async function startClient(port: number, name: string, m: Machine | null, options: ClientTestOptions = {}) { const log = m?.log ?? recordingLogger(); const client = new Client({ - target: { host: '127.0.0.1', port }, + target: options.findServer ? null : { host: options.host ?? '127.0.0.1', port }, + findServer: options.findServer, passphrase: options.passphrase ?? PASSPHRASE, clipboard: m?.watcher ?? null, maxTextBytes: options.maxTextBytes ?? 10 * 1024 * 1024, @@ -74,6 +85,56 @@ async function startClient(port: number, name: string, m: Machine | null, option const connectedPeers = (hub: Hub) => hub.peers.filter((session) => session.peer !== null).length; +/** A TCP server for fake hubs; `onConnection` gets every accepted socket. */ +async function fakeServer(onConnection: (socket: net.Socket) => void): Promise { + const server = net.createServer((socket) => { + socket.on('error', () => undefined); + onConnection(socket); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const sockets = new Set(); + server.on('connection', (socket) => sockets.add(socket)); + cleanups.push(() => { + for (const socket of sockets) socket.destroy(); + return new Promise((resolve) => server.close(() => resolve())); + }); + return (server.address() as net.AddressInfo).port; +} + +/** A proxy that forwards client→hub at full speed and hub→client at `bytesPerSecond`. */ +async function throttledProxy(hubPort: number, bytesPerSecond: number): Promise { + return fakeServer((client) => { + const upstream = net.connect(hubPort, '127.0.0.1'); + upstream.on('error', () => undefined); + client.pipe(upstream); + const queue: Buffer[] = []; + upstream.on('data', (data: Buffer) => queue.push(data)); + const timer = setInterval(() => { + let budget = bytesPerSecond / 20; + while (budget > 0 && queue.length > 0) { + const head = queue[0]!; + const part = head.subarray(0, budget); + client.write(part); + budget -= part.length; + if (part.length === head.length) queue.shift(); + else queue[0] = head.subarray(part.length); + } + }, 50); + const end = () => { + clearInterval(timer); + client.destroy(); + upstream.destroy(); + }; + client.on('close', end); + upstream.on('close', end); + }); +} + +const hasIPv6Loopback = await new Promise((resolve) => { + const probe = net.createServer().once('error', () => resolve(false)); + probe.listen(0, '::1', () => probe.close(() => resolve(true))); +}); + describe('hub with clients', () => { it('syncs text between all machines without echo and without changing it', async () => { const hubMachine = machine('hub initial'); @@ -241,3 +302,112 @@ describe('security and robustness', () => { assert.equal(session?.closed, false); }); }); + +describe('connections without the passphrase', () => { + it('are limited per address, so other machines still get in', { skip: !hasIPv6Loopback }, async () => { + const { hub, port } = await startHub({ host: '::' }); + let closed = 0; + for (let i = 0; i < 8; i++) { + const socket = net.connect(port, '127.0.0.1'); + socket.on('error', () => undefined); + socket.on('close', () => closed++); + cleanups.push(() => void socket.destroy()); + } + await waitFor(() => closed === 8 - MAX_PENDING_PER_ADDRESS, 'the hub refuses the extra connections'); + await startClient(port, 'other machine', null, { host: '::1' }); + await waitFor(() => connectedPeers(hub) === 1, 'a client from another address'); + }); + + it('cannot test many passphrases in parallel from one address', async () => { + const { hub, port } = await startHub(); + let checked = 0; + hub.on('auth-failed', () => checked++); + const attempts = Array.from({ length: MAX_PENDING_PER_ADDRESS }, async () => { + const socket = net.connect(port, '127.0.0.1'); + socket.on('error', () => undefined); + cleanups.push(() => void socket.destroy()); + await once(socket, 'connect'); + return clientHandshake(socket, new FrameReader(socket, HANDSHAKE_MAX_BODY_BYTES), { passphrase: 'a wrong guess', kdf: FAST_KDF }); + }); + const results = await Promise.allSettled(attempts); + assert.ok(results.every((result) => result.status === 'rejected')); + await sleep(100); + assert.ok(checked >= 1 && checked <= MAX_CONCURRENT_KDF, `${checked} guesses were checked`); + }); +}); + +describe('client lifecycle', () => { + it('stops when it is closed during discovery', async () => { + const { hub, port } = await startHub(); + const { client, running } = await startClient(port, 'a', null, { + // Ignores the signal on purpose: the client must still stop after it returns. + findServer: async () => { + await sleep(300); + return { host: '127.0.0.1', port }; + }, + }); + await sleep(100); + await client.close(); + const state = await Promise.race([running.then(() => 'stopped'), sleep(1000).then(() => 'still running')]); + assert.equal(state, 'stopped'); + await sleep(200); + assert.equal(hub.peers.length, 0); + }); + + it('keeps trying after a forged "wrong passphrase" that came before its own proof', async () => { + const port = await fakeServer((socket) => socket.end(encodeFrame(FrameType.Error, Buffer.of(HandshakeErrorCode.AuthFailed)))); + const { running, log } = await startClient(port, 'a', null); + const state = await Promise.race([running.then(() => 'stopped', () => 'stopped'), sleep(500).then(() => 'running')]); + assert.equal(state, 'running'); + assert.ok(log.has('warn', /before the passphrase check/)); + }); + + it('does not stop when a server found by mDNS rejects the passphrase (it may be an impostor)', async () => { + const { port } = await startHub(); + const { running, log } = await startClient(port, 'a', null, { + passphrase: 'wrong passphrase', + findServer: async () => ({ host: '127.0.0.1', port }), + }); + await waitFor(() => log.has('error', /wrong passphrase/), 'an error message'); + const state = await Promise.race([running.then(() => 'stopped', () => 'stopped'), sleep(300).then(() => 'running')]); + assert.equal(state, 'running'); + }); +}); + +describe('session', () => { + it('does not cut a large text on a slow link with the idle timeout', { timeout: 20_000 }, async () => { + const a = machine('a'); + const b = machine('b'); + const { hub, port } = await startHub(); + await startClient(port, 'a', a); + const slowPort = await throttledProxy(port, 100 * 1024); + await startClient(slowPort, 'b', b); + await waitFor(() => connectedPeers(hub) === 2, 'two clients'); + const text = 'x'.repeat(300 * 1024); // 3 s at 100 KB/s; the idle timeout is 0.6 s + a.backend.text = text; + await waitFor(() => b.backend.text === text, 'the text over the slow link', 15_000); + }); + + it('does not send text to a peer that has not introduced itself yet', async () => { + const pair = await socketPair(); + cleanups.push(() => { + pair.client.destroy(); + pair.server.destroy(); + }); + const serverReader = new FrameReader(pair.server, HANDSHAKE_MAX_BODY_BYTES); + const [, serverChannel] = await Promise.all([ + clientHandshake(pair.client, new FrameReader(pair.client, HANDSHAKE_MAX_BODY_BYTES), { passphrase: PASSPHRASE, kdf: FAST_KDF }), + serverHandshake(pair.server, serverReader, { passphrase: PASSPHRASE, kdf: FAST_KDF }), + ]); + const session = new Session(pair.server, serverReader, serverChannel, { + maxTextBytes: 1024 * 1024, + heartbeatIntervalMs: 1000, + idleTimeoutMs: 5000, + localName: 'hub', + version: 'test', + }); + session.start(); + assert.equal(session.sendClip('text'), 'not-ready'); + session.close(); + }); +}); diff --git a/test/frame-reader.test.ts b/test/frame-reader.test.ts new file mode 100644 index 0000000..13d5d36 --- /dev/null +++ b/test/frame-reader.test.ts @@ -0,0 +1,52 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { FrameType, encodeFrame } from '../src/frame.ts'; +import { FrameReader } from '../src/frame-reader.ts'; +import { socketPair } from './helpers.ts'; + +describe('FrameReader', () => { + it('stops reading when nobody consumes frames, so a flood cannot fill the memory', { timeout: 20_000 }, async () => { + const { client, server } = await socketPair(); + try { + const reader = new FrameReader(server, 256); + const frame = encodeFrame(FrameType.Hello, Buffer.alloc(200, 1)); + const chunk = Buffer.concat(Array.from({ length: 5000 }, () => frame)); // ~1 MB of valid frames + const total = 20 * chunk.length; + let written = 0; + const writeMore = () => { + while (written < total) { + written += chunk.length; + if (!client.write(chunk)) { + client.once('drain', writeMore); + return; + } + } + }; + writeMore(); + + await sleep(300); // like the hub during scrypt: nobody calls next() + assert.ok(reader.bufferedBytes < 256 + 64 * 1024 + 128 * 1024, `buffered ${reader.bufferedBytes} bytes`); + + // Consuming frames resumes the socket, and every frame arrives. + for (let i = 0; i < 100_000; i++) await reader.next(); + } finally { + client.destroy(); + server.destroy(); + } + }); + + it('returns frames that arrived before the peer closed, then the close reason', { timeout: 5_000 }, async () => { + const { client, server } = await socketPair(); + try { + const reader = new FrameReader(server, 256); + client.end(Buffer.concat([encodeFrame(FrameType.Hello, Buffer.from('a')), encodeFrame(FrameType.Auth, Buffer.from('b'))])); + assert.equal((await reader.next()).type, FrameType.Hello); + assert.equal((await reader.next()).type, FrameType.Auth); + await assert.rejects(reader.next(), { name: 'ConnectionClosedError' }); + } finally { + client.destroy(); + server.destroy(); + } + }); +}); diff --git a/test/handshake.test.ts b/test/handshake.test.ts index 1b2b8b3..177b668 100644 --- a/test/handshake.test.ts +++ b/test/handshake.test.ts @@ -1,8 +1,8 @@ import assert from 'node:assert/strict'; -import { once } from 'node:events'; import net from 'node:net'; import { describe, it } from 'node:test'; -import { IntegrityError } from '../src/crypto.ts'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { IntegrityError, generateEphemeralKey } from '../src/crypto.ts'; import { FrameDecoder, FrameType, encodeFrame } from '../src/frame.ts'; import { FrameReader } from '../src/frame-reader.ts'; import { @@ -12,20 +12,8 @@ import { clientHandshake, serverHandshake, } from '../src/handshake.ts'; -import { FAST_KDF } from './helpers.ts'; - -async function socketPair(): Promise<{ client: net.Socket; server: net.Socket }> { - const listener = net.createServer(); - await new Promise((resolve) => listener.listen(0, '127.0.0.1', resolve)); - const { port } = listener.address() as net.AddressInfo; - const accepted = once(listener, 'connection'); - const client = net.connect(port, '127.0.0.1'); - const connected = once(client, 'connect'); - const [server] = (await accepted) as [net.Socket]; - await connected; - listener.close(); - return { client, server }; -} +import type { Limiter } from '../src/limiter.ts'; +import { FAST_KDF, socketPair } from './helpers.ts'; function handshakes(pair: { client: net.Socket; server: net.Socket }, clientPassphrase: string, serverPassphrase: string) { return Promise.allSettled([ @@ -98,6 +86,31 @@ describe('handshake', () => { pair.client.destroy(); }); + it('runs scrypt on the server only after the client proof arrives', async () => { + const pair = await socketPair(); + let runs = 0; + const limiter = { run: async (task: () => Promise) => (runs++, task()) } as unknown as Limiter; + const serverDone = serverHandshake(pair.server, new FrameReader(pair.server, HANDSHAKE_MAX_BODY_BYTES), { + passphrase: 'x', + kdf: FAST_KDF, + kdfLimiter: limiter, + }).catch(() => undefined); + pair.client.write(encodeFrame(FrameType.Hello, Buffer.concat([Buffer.from('NETPASTE'), Buffer.of(2, 0), generateEphemeralKey().publicKey]))); + await sleep(200); + assert.equal(runs, 0, 'a HELLO without AUTH costs the server nothing'); + pair.client.destroy(); + await serverDone; + }); + + it('does not believe a "wrong passphrase" error that arrives before its own proof', async () => { + const pair = await socketPair(); + const clientDone = clientHandshake(pair.client, new FrameReader(pair.client, HANDSHAKE_MAX_BODY_BYTES), { passphrase: 'x', kdf: FAST_KDF }); + pair.server.write(encodeFrame(FrameType.Error, Buffer.of(HandshakeErrorCode.AuthFailed))); + await assert.rejects(clientDone, (error: unknown) => error instanceof HandshakeError && error.failure === 'protocol'); + pair.client.destroy(); + pair.server.destroy(); + }); + it('rejects a low-order X25519 key', async () => { const pair = await socketPair(); const serverDone = serverHandshake(pair.server, new FrameReader(pair.server, HANDSHAKE_MAX_BODY_BYTES), { passphrase: 'x', kdf: FAST_KDF }); diff --git a/test/helpers.ts b/test/helpers.ts index a1a94db..4797e0c 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -1,3 +1,5 @@ +import { once } from 'node:events'; +import net from 'node:net'; import { setTimeout as sleep } from 'node:timers/promises'; import type { Timings } from '../src/config.ts'; import type { KdfParams } from '../src/crypto.ts'; @@ -69,6 +71,20 @@ export function recordingLogger(): RecordingLogger { }; } +/** Two connected TCP sockets on the loopback interface. */ +export async function socketPair(host = '127.0.0.1'): Promise<{ client: net.Socket; server: net.Socket }> { + const listener = net.createServer(); + await new Promise((resolve) => listener.listen(0, host, resolve)); + const { port } = listener.address() as net.AddressInfo; + const accepted = once(listener, 'connection'); + const client = net.connect(port, host); + const connected = once(client, 'connect'); + const [server] = (await accepted) as [net.Socket]; + await connected; + listener.close(); + return { client, server }; +} + export async function waitFor(condition: () => boolean, what: string, timeoutMs = 4000): Promise { const deadline = Date.now() + timeoutMs; while (!condition()) { diff --git a/test/passphrase.test.ts b/test/passphrase.test.ts index 340da62..8cfd33e 100644 --- a/test/passphrase.test.ts +++ b/test/passphrase.test.ts @@ -50,6 +50,16 @@ describe('HiddenLineEditor', () => { assert.equal(typed('a🙂\u007f\r').value, 'a'); }); + it('does not swallow Enter or Ctrl+C after a stray ESC', () => { + assert.equal(typed('abc\u001b\r').done, true); + assert.equal(typed('abc\u001b\r').value, 'abc'); + assert.equal(typed('abc\u001b\u0003').cancelled, true); + }); + + it('keeps TAB, like a passphrase file or the environment do', () => { + assert.equal(typed('a\tb\r').value, 'a\tb'); + }); + it('cancels with Ctrl+C, and with Ctrl+D on an empty line', () => { assert.equal(typed('abc\u0003').cancelled, true); assert.equal(typed('\u0004').cancelled, true); @@ -106,9 +116,10 @@ describe('resolvePassphrase', () => { it('prefers --passphrase-file and strips one final newline', async () => { const file = path.join(dir, 'pass'); await writeFile(file, 'from file with spaces \n\n', { mode: 0o600 }); - const env = { NETPASTE_PASSPHRASE: 'from env' }; + const env: NodeJS.ProcessEnv = { NETPASTE_PASSPHRASE: 'from env' }; const result = await resolvePassphrase({ file, env, stdin: notTty(), prompt: new PassThrough(), log: recordingLogger() }); assert.equal(result, 'from file with spaces \n'); + assert.equal(env.NETPASTE_PASSPHRASE, undefined, 'removed for child processes even when unused'); }); it('uses NETPASTE_PASSPHRASE and removes it from the environment', async () => { From 121337df51fdef6849bbf6daf0eb5095d0e9e435 Mon Sep 17 00:00:00 2001 From: Aliaksei Smirnou Date: Thu, 19 Nov 2026 09:25:31 +0100 Subject: [PATCH 9/9] docs: hub limits, liveness rules and known limitations Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 +++++++--- README.md | 12 ++++++--- docs/PROTOCOL.md | 63 +++++++++++++++++++++++++++++++++++++++--------- 3 files changed, 69 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 23ae5b2..839f4d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,8 +15,15 @@ A rewrite. The protocol is not compatible with 1.x: update all machines. - **Strong key derivation:** scrypt (128 MiB) once per connection. 1.x ran PBKDF2 with 10,000 iterations for every message, on the main thread. - **Forward secrecy and replay protection:** ephemeral X25519 keys and per-direction message counters. -- **Online guessing is slowed down:** after a wrong passphrase, the hub blocks the IP address - (1 s, then doubling up to 60 s). +- **Strangers cannot make the hub work for free or lock out real clients:** + - the hub runs scrypt only after it receives a passphrase proof; + - connections without the passphrase are limited to 4 per address and 32 in total; + - unread input is limited by TCP flow control, so nobody can fill the hub's memory. +- **Online guessing is slowed down:** after a wrong passphrase, the hub blocks the address (IPv6: the /64): + 1 s, then doubling up to 60 s. Parallel connections from that address are closed, so one address can + test at most 2 passphrases per block period. +- Handshake ERROR frames are not authenticated, so a "wrong passphrase" reply stops the client only when + you gave the hub address, and only after the client sent its proof. - Peer-supplied names are cleaned of control characters before they are printed. ### Fixed @@ -57,7 +64,7 @@ A rewrite. The protocol is not compatible with 1.x: update all machines. - mDNS discovery: `netpaste connect` without an address finds the hub. - Passphrase from `--passphrase-file` or `NETPASTE_PASSPHRASE`, for autostart. Templates for launchd and systemd. - Heartbeats, idle timeout, TCP keepalive, reconnect with exponential backoff and jitter. -- `--max-size` (default 10 MB), `--interval`, `--host`, `--no-mdns`, `--verbose`. +- `--max-size` (default 10 MB, up to 64 MB), `--interval`, `--host`, `--no-mdns`, `--verbose`. - The clipboard is read only while a peer is connected. - Clear messages for a wrong passphrase, an old protocol version, a busy port, and a missing terminal. diff --git a/README.md b/README.md index 75d15bf..11096da 100644 --- a/README.md +++ b/README.md @@ -68,12 +68,12 @@ Copies are sent only while a connection is open; a copy made while disconnected | Option | Default | Meaning | |---|---|---| | `-p, --port N` | 8134 | TCP port. | -| `--host ADDR` | all interfaces | `serve`: listen only on this address. | +| `--host ADDR` | all interfaces | `serve`: listen only on this address (the hub is then not announced with mDNS). | | `--no-clipboard` | | Do not use the local clipboard. With `serve`: only relay between clients. | | `--no-mdns` | | `serve`: do not announce the hub on the network. | | `--passphrase-file F` | | Read the passphrase from file F. | | `--interval MS` | 1000 | How often to check the clipboard. | -| `--max-size SIZE` | 10mb | Largest text to send or accept, for example `512kb`. | +| `--max-size SIZE` | 10mb | Largest text to send or accept, from `1kb` to `64mb`. | | `--timeout SEC` | 3 | `discover`: how long to search. | | `--verbose` | | Show debug messages. | @@ -148,8 +148,9 @@ The full design is in [docs/PROTOCOL.md](docs/PROTOCOL.md). In short: - eavesdroppers: they cannot read the text, and they cannot test passphrase guesses; - changed, replayed or reordered messages: they fail authentication and close the connection; - strangers who connect to the hub: they receive nothing until they prove the passphrase. - After a wrong passphrase, the hub blocks that address for 1 s, then 2 s, 4 s … up to 60 s; -- malformed input: it closes that one connection, never the program. + The hub limits their connections (4 per address, 32 in total) and runs scrypt only for a real passphrase attempt. + After a wrong passphrase, the hub blocks that address (IPv6: the /64) for 1 s, then 2 s, 4 s … up to 60 s; +- malformed input and floods: they close that one connection, never the program. **Does not protect against:** @@ -161,6 +162,9 @@ The full design is in [docs/PROTOCOL.md](docs/PROTOCOL.md). In short: - password managers: netpaste syncs a copied password like any other text, and the other machine keeps it after the password manager clears its own clipboard. +**Known limitation:** if you copy on two machines within about a second, the copies can cross: +each machine keeps the other's text until the next copy. See [docs/PROTOCOL.md](docs/PROTOCOL.md#known-limitations). + ## Upgrading from 1.x Version 2 uses a new protocol. It cannot talk to 1.x, so update all machines. diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 8f34624..e81e488 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -10,9 +10,10 @@ client hub │── TCP connect ─────────────────────────────────────────▶│ │── HELLO "NETPASTE" | 2 | role=0 | X25519 key eC ───────▶│ │◀── HELLO "NETPASTE" | 2 | role=1 | X25519 key eS ────────│ - │ both: transcript, scrypt, X25519, HKDF (see below) │ - │── AUTH client proof ─────────────────────────────────▶│ wrong → wait 1 s, ERROR, close, - │◀── AUTH hub proof ──────────────────────────────────────│ block the IP address + │ client: transcript, scrypt, X25519, HKDF (see below) │ + │── AUTH client proof ─────────────────────────────────▶│ hub: scrypt only now, then check + │◀── AUTH hub proof ──────────────────────────────────────│ wrong → block the address, + │ │ wait 1 s, ERROR, close │══ SEALED INFO ═══════════════════════════════════════════│ both directions │══ SEALED CLIP / PING / PONG ══════════════════════════════│ ``` @@ -40,6 +41,10 @@ The receiver checks the length before it buffers the body: A frame above the limit, an unknown frame type during the handshake, or a failed decryption closes the connection. +The receiver also stops reading from the socket when more than one maximum-size frame + 64 KiB +waits unread, for example while the hub runs scrypt. TCP flow control then stops the sender, +so a peer cannot make the receiver buffer more than that. + ## Handshake `HELLO` body: `"NETPASTE"` (8 bytes) | protocol version (u8, = 2) | role (u8: 0 client, 1 hub) | ephemeral X25519 public key (32 bytes). @@ -56,15 +61,33 @@ keys = HKDF-SHA256(ikm = dh | pk, salt = transcript, info = "netpaste/2 se ``` - The client sends `AUTH = HMAC-SHA256(clientProofKey, "netpaste/2 client proof" | transcript)`. +- The hub waits for this AUTH **before** it runs scrypt. So every scrypt run on the hub belongs to a + passphrase attempt, and a stranger who sends only HELLO costs the hub nothing. - The hub checks the client proof with a constant-time comparison. - - **Wrong proof:** the hub waits 1 s, sends `ERROR 1`, and closes the connection. It also blocks the IP address for 1 s; every further failure doubles the block, up to 60 s. + - **Wrong proof:** the hub blocks the address at once (see below), waits 1 s, sends `ERROR 1`, and closes the connection. + It also closes the other unauthenticated connections from that address. - **Correct proof:** the hub sends `AUTH = HMAC-SHA256(hubProofKey, "netpaste/2 server proof" | transcript)`. - The client checks the hub proof. If it is wrong, the client closes the connection and tries again later. +ERROR frames are not authenticated. The client believes `ERROR 1` (wrong passphrase) only after it sent its AUTH. +It stops with an error only when the user gave the hub address; for a hub found with mDNS it keeps trying. + The passphrase is normalized to Unicode NFC, so the same passphrase typed on macOS and on Linux gives the same key. -The hub runs at most 2 scrypt computations at the same time (each needs 128 MiB). The whole handshake must finish within 10 s. +Limits on the hub, so that strangers cannot block real clients: + +| Limit | Value | +|---|---| +| Connections without the passphrase, from one address (IPv6: one /64) | 4 | +| Connections without the passphrase, in total | 32 | +| Authenticated peers | 32 | +| Parallel scrypt runs (128 MiB each) | 2 | +| Block after a wrong passphrase (per address, IPv6 per /64) | 1 s, doubling with every failure, up to 60 s | + +A blocked address is refused at once, also by connections that were already open. +So one address can test at most 2 passphrases (the parallel scrypt runs) per block period. + ## Messages Every message after the handshake is a SEALED frame: @@ -83,13 +106,18 @@ The plaintext is `kind (u8) | payload`: | 4 | INFO | JSON `{"name": string, "version": string, "maxTextBytes": number}`, sent first by both sides | A receiver ignores unknown kinds, so later versions can add messages. -The sender never sends text above `min(own limit, peer limit)`. -The receiver closes the connection when the text is above its own limit. +The receiver closes the connection when the text is above its own limit (`--max-size`, at most 64 MiB). +The sender does not send text: + +- above `min(own limit, peer limit)`; +- to a peer that has not sent INFO yet (its limit is unknown); +- to a peer whose send queue already holds more than one maximum-size text + 1 MiB (the peer does not read). Liveness: -- A side sends PING when it sent nothing for 15 s. -- A side closes the connection when it received nothing for 45 s. +- A side sends PING when it sent nothing for 15 s (it checks every 5 s, on a monotonic clock). +- A side closes the connection when it received no bytes for 45 s. Every received chunk counts, + so a large text on a slow link does not trigger the timeout. - TCP keepalive is on as well. ## Hub behaviour @@ -111,22 +139,33 @@ computer, for example to `-2.local`. Clients connect to the address the an `netpaste connect` without HOST searches for 3 s: - exactly one hub found: the client connects to it; -- several hubs found: the client stops and lists them; +- several hubs found: the client lists them and tries again with backoff (give HOST to choose one); - no hub found: the client tries again with backoff. +`netpaste serve --host ADDR` with a specific address does not announce the hub: bonjour-service +announces the addresses of all interfaces, and clients would connect to an address the hub does not listen on. + ## Security properties | Threat | Result | |---|---| | Passive eavesdropper | Cannot read messages. Cannot test passphrase guesses: the proofs depend on the X25519 secret. | -| Stranger connects to the hub | Receives only the hub's HELLO: one ephemeral key, nothing that depends on the passphrase. Gets one online guess per connection, then the IP address is blocked. | +| Stranger connects to the hub | Receives only the hub's HELLO: one ephemeral key, nothing that depends on the passphrase. Costs the hub a scrypt run only together with a passphrase attempt. At most 2 guesses per block period from one address (see the limits above). | | Changed, replayed, reordered or reflected message | GCM authentication fails, the connection closes. Keys differ per direction and per connection. | | Recorded traffic, passphrase leaks later | Old sessions stay secret: the keys also depend on ephemeral X25519 keys (forward secrecy). | | Active attacker poses as the hub (mDNS spoofing, MITM) | Can try passphrase guesses **offline** against the client proof, one scrypt run per guess. Both sides contribute to the salt, so precomputed tables do not help. Only a long passphrase protects here; a PAKE (for example CPace) would remove this attack. | -| Malformed input | Closes that connection. Frame sizes are checked before buffering. | +| Malformed input or a flood | Closes that connection. Frame sizes are checked before buffering; unread input is limited by TCP flow control. | Not hidden: the size of each message, and the time of each copy. +## Known limitations + +- **Crossing copies.** If two machines copy different texts within about one poll interval (1 s), + the hub forwards each text to the other machine. Each machine then keeps the other's text, and the hub + keeps the one it received last, until the next copy. A fix (the hub orders all copies and echoes them to + the sender) would make the sender's clipboard flicker, so it is not done. +- **Copies while disconnected** are not sent later: the clipboard can change on other machines meanwhile. + ## Changes from version 1 Version 1 had these problems: