├── .gitattributes ├── .gitignore ├── .images └── baofeng.jpg ├── .npmignore ├── src ├── declerations.d.ts ├── subcommands │ ├── addkey.ts │ ├── genkey.ts │ ├── removekey.ts │ ├── showkey.ts │ ├── chat.ts │ ├── send.ts │ ├── tty.ts │ ├── receive.ts │ └── exec.ts ├── compression.ts ├── utils.ts ├── ui │ ├── chat.ts │ └── init.ts ├── config.ts ├── Packet.ts ├── Keystore.ts ├── Messenger.ts └── main.ts ├── .travis.yml ├── LICENSE ├── test ├── compression.test.js ├── utils.test.js ├── Keystore.test.js ├── config.test.js └── Packet.test.js ├── pkg.sh ├── package.json ├── CHANGELOG.md ├── tsconfig.json ├── FAQ.md ├── README.md └── GPLv3.txt /.gitattributes: -------------------------------------------------------------------------------- 1 | test/**/*.js linguist-detectable=false 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | build/ 3 | pkg/ 4 | .vscode/ 5 | coverage/ 6 | -------------------------------------------------------------------------------- /.images/baofeng.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aaronpk/chattervox/master/.images/baofeng.jpg -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | *.map 2 | .images/ 3 | .vscode/ 4 | test/ 5 | pkg/ 6 | coverage/ 7 | .travis.yml 8 | -------------------------------------------------------------------------------- /src/declerations.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'kiss-tnc' 2 | declare module 'ax25' 3 | declare module 'elliptic' 4 | declare module 'command-exists' 5 | declare module 'terminal-kit' 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | node_js: 4 | - "8" 5 | before_script: 6 | - npm run build 7 | script: 8 | - npm run test 9 | after_script: 10 | - npm run coveralls 11 | cache: 12 | directories: 13 | - "node_modules" -------------------------------------------------------------------------------- /src/subcommands/addkey.ts: -------------------------------------------------------------------------------- 1 | 2 | import { Config, save } from '../config' 3 | import { Keystore } from '../Keystore'; 4 | 5 | export async function main(args: any, conf: Config, ks: Keystore): Promise { 6 | 7 | ks.addPublicKey(args.callsign.toUpperCase(), args.publickey) 8 | save(conf, args.config) 9 | 10 | return 0 11 | } 12 | -------------------------------------------------------------------------------- /src/subcommands/genkey.ts: -------------------------------------------------------------------------------- 1 | import { Config, save } from '../config' 2 | import { Keystore, Key } from '../Keystore' 3 | 4 | export async function main(args: any, conf: Config, ks: Keystore): Promise { 5 | 6 | const key: Key = ks.genKeyPair(conf.callsign) 7 | if (args.makeSigning) conf.signingKey = key.public 8 | save(conf, args.config) 9 | console.log(key.public) 10 | 11 | return 0 12 | } 13 | -------------------------------------------------------------------------------- /src/subcommands/removekey.ts: -------------------------------------------------------------------------------- 1 | import { Config } from '../config' 2 | import { Keystore } from '../Keystore' 3 | 4 | export async function main(args: any, conf: Config, ks: Keystore): Promise { 5 | 6 | if (ks.revoke(args.callsign.toUpperCase(), args.publickey)) { 7 | console.log(`Removed key ${args.publickey}`) 8 | } else { 9 | console.log(`Failed to remove key ${args.publickey}, are you sure it exists?`) 10 | } 11 | return 0 12 | } 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Chattervox: An AX.25 packet radio chat protocol with support for 2 | digital signatures and binary compression. 3 | 4 | Copyright (C) 2018 Brannon Dorsey 5 | 6 | This program is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 3 of the License, or 9 | any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | -------------------------------------------------------------------------------- /test/compression.test.js: -------------------------------------------------------------------------------- 1 | const compression = require('../build/compression.js') 2 | const assert = require('assert') 3 | 4 | describe('compression', async () => { 5 | 6 | let text = 'This is a bit of ASCII text to use for compression. And here is some UTF-8 徴枠ヌイヘ' 7 | let compressed = null 8 | let decompressed = null 9 | 10 | it('should compress text', async () => { 11 | compressed = await compression.compress(Buffer.from(text, 'utf8')) 12 | }) 13 | 14 | it('should decompress text', async () => { 15 | decompressed = await compression.decompress(compressed) 16 | }) 17 | 18 | it('decompressed text should match original text', () => { 19 | assert.ok(decompressed.toString('utf8') == text) 20 | }) 21 | }) 22 | -------------------------------------------------------------------------------- /src/compression.ts: -------------------------------------------------------------------------------- 1 | import * as zlib from 'zlib' 2 | 3 | const compressionOptions: zlib.ZlibOptions = { 4 | level: zlib.constants.Z_BEST_COMPRESSION, 5 | } 6 | 7 | export async function compress(buffer: Buffer): Promise { 8 | return new Promise((resolve, reject) => { 9 | zlib.deflateRaw(buffer, compressionOptions, (err, data: Buffer) => { 10 | if (err) reject(err) 11 | else resolve(data) 12 | }) 13 | }) 14 | } 15 | 16 | export async function decompress(buffer: Buffer): Promise { 17 | return new Promise((resolve, reject) => { 18 | zlib.inflateRaw(buffer, compressionOptions, (err, data) => { 19 | if (err) reject(err) 20 | else resolve(data) 21 | }) 22 | }) 23 | } 24 | -------------------------------------------------------------------------------- /src/subcommands/showkey.ts: -------------------------------------------------------------------------------- 1 | import { Config } from '../config' 2 | import { Keystore, Key } from '../Keystore' 3 | 4 | export async function main(args: any, conf: Config, ks: Keystore): Promise { 5 | 6 | if (args.callsign) { 7 | printKeys(args.callsign.toUpperCase(), ks, conf) 8 | } else { 9 | ks.getCallsigns().forEach((callsign) => printKeys(callsign, ks, conf)) 10 | } 11 | 12 | return 0 13 | } 14 | 15 | function printKeys(callsign: string, keystore: Keystore, conf: Config): void { 16 | 17 | const keys: Key[] = keystore.getKeys(callsign) 18 | keys.forEach((key) => { 19 | if (key.public) { 20 | if (key.public === conf.signingKey) { 21 | console.log(`${callsign} Public Key (your signing key): ${key.public}`) 22 | } else { 23 | console.log(`${callsign} Public Key: ${key.public}`) 24 | } 25 | } 26 | if (key.private) console.log(`${callsign} Private Key: ${key.private}`) 27 | }) 28 | } 29 | -------------------------------------------------------------------------------- /pkg.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | OS="$(uname -s)" 3 | 4 | rm -rf ./pkg 5 | 6 | if [ ! -f "build/main.js" ] ; then 7 | echo "No build to package. Run 'npm run build' first." 8 | exit 1 9 | fi 10 | 11 | if [ "$OS" == "Linux" ]; then 12 | echo "Building for Linux..." 13 | 14 | # linux x64 15 | OUTPUT_DIR=chattervox-linux-x64 16 | pkg --out-path "pkg/${OUTPUT_DIR}" \ 17 | --targets node8-linux-x64 . && \ 18 | cp node_modules/serialport/build/Release/serialport.node "pkg/${OUTPUT_DIR}" 19 | 20 | pushd pkg 21 | tar -zcvf "${OUTPUT_DIR}.tar.gz" "${OUTPUT_DIR}" 22 | popd 23 | 24 | # linux x86 25 | OUTPUT_DIR=chattervox-linux-x86 26 | pkg --out-path "pkg/${OUTPUT_DIR}" \ 27 | --targets node8-linux-x86 . && \ 28 | cp node_modules/serialport/build/Release/serialport.node "pkg/${OUTPUT_DIR}" 29 | 30 | pushd pkg 31 | tar -zcvf "${OUTPUT_DIR}.tar.gz" "${OUTPUT_DIR}" 32 | popd 33 | elif [ "$OS" == "Darwin" ]; then 34 | echo "Building for MacOS..." 35 | 36 | # MacOS 37 | OUTPUT_DIR=chattervox-macos 38 | pkg --out-path "pkg/${OUTPUT_DIR}" \ 39 | --targets node8-macos-x64 . && \ 40 | cp node_modules/serialport/build/Release/serialport.node "pkg/${OUTPUT_DIR}" 41 | 42 | pushd pkg 43 | tar -zcvf "${OUTPUT_DIR}.tar.gz" "${OUTPUT_DIR}" 44 | popd 45 | else 46 | echo "unsupported OS $OS, exiting." 47 | fi 48 | -------------------------------------------------------------------------------- /src/subcommands/chat.ts: -------------------------------------------------------------------------------- 1 | import { Config } from '../config' 2 | import { Keystore } from '../Keystore' 3 | import { Messenger, MessageEvent } from '../Messenger' 4 | import * as ui from '../ui/chat' 5 | import { stationToCallsignSSID, isBrokenPipeError } from '../utils'; 6 | 7 | export async function main(args: any, conf: Config, ks: Keystore): Promise { 8 | 9 | const messenger = new Messenger(conf) 10 | 11 | try { 12 | await messenger.openTNC() 13 | } catch (err) { 14 | console.error(`Error opening a connection to the KISS TNC that should be listening at ${conf.kissPort}. Are you sure your TNC is running?`) 15 | console.error(`If you have Direwolf installed you can start it in another window with "direwolf -p -q d -t 0"`) 16 | return 1 17 | } 18 | 19 | messenger.on('close', () => { 20 | console.error(`The connection to KISS TNC at ${conf.kissPort} is now closed. Exiting.`) 21 | ui.exit(1) 22 | }) 23 | 24 | messenger.on('tnc-error', (err) => { 25 | // if this is a broken pipe error we'll return immediately 26 | // because that error is going to be caught and printed in main.ts 27 | if (isBrokenPipeError(err)) return 28 | console.error(`The connection to KISS TNC ${conf.kissPort} experienced the following error:`) 29 | console.error(err) 30 | }) 31 | 32 | messenger.on('message', (message: MessageEvent) => { 33 | if (message.to.callsign === 'CQ' || 34 | (message.to.callsign === conf.callsign && 35 | message.to.ssid === conf.ssid)) { 36 | ui.printReceivedMessage(message, conf.callsign) 37 | } 38 | }) 39 | 40 | ui.enter() 41 | 42 | // only sign if the user's config has a signing key 43 | const sign: boolean = typeof conf.signingKey === 'string' 44 | const callsignSSID: string = stationToCallsignSSID({ callsign: conf.callsign, ssid: conf.ssid }) 45 | await ui.inputLoop(callsignSSID, messenger, sign) 46 | 47 | return 0 48 | } 49 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "chattervox", 3 | "version": "0.7.0", 4 | "description": "An AX.25 packet radio chat protocol with support for digital signatures and binary compression. Like IRC over radio waves 📡〰.", 5 | "main": "build/main.js", 6 | "bin": { 7 | "chattervox": "build/main.js" 8 | }, 9 | "keywords": [ 10 | "ax25", 11 | "packet radio", 12 | "ham radio", 13 | "amateur radio", 14 | "ecdsa", 15 | "digital signatures" 16 | ], 17 | "preferGlobal": true, 18 | "scripts": { 19 | "build": "tsc", 20 | "pkg": "bash ./pkg.sh", 21 | "watch": "tsc --watch", 22 | "test": "mocha test", 23 | "coverage": "nyc --reporter=html --reporter=text mocha test && rm -rf .nyc_output/", 24 | "coveralls": "istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage" 25 | }, 26 | "repository": { 27 | "type": "git", 28 | "url": "git+https://github.com/brannondorsey/chattervox.git" 29 | }, 30 | "author": "Brannon Dorsey ", 31 | "license": "GPL-3.0", 32 | "bugs": { 33 | "url": "https://github.com/brannondorsey/chattervox/issues" 34 | }, 35 | "homepage": "https://github.com/brannondorsey/chattervox#readme", 36 | "dependencies": { 37 | "argparse": "^1.0.10", 38 | "ax25": "git+https://github.com/echicken/node-ax25.git#124b496631fa448d95ac97553cdd1c8120d4f9cb", 39 | "command-exists": "^1.2.7", 40 | "elliptic": "^6.4.1", 41 | "kiss-tnc": "git+https://github.com/brannondorsey/kiss-tnc.git#3320a26e7d5abd586ca558dccfb4cbfcd291768b", 42 | "terminal-kit": "^1.26.2" 43 | }, 44 | "devDependencies": { 45 | "@types/argparse": "^1.0.34", 46 | "@types/node": "^10.9.4", 47 | "coveralls": "^3.0.2", 48 | "istanbul": "^0.4.5", 49 | "mocha": "^5.2.0", 50 | "mocha-lcov-reporter": "^1.3.0", 51 | "pkg": "^4.3.4", 52 | "typescript": "^3.0.3" 53 | }, 54 | "pkg": { 55 | "scripts": [ 56 | "build/**/*.js", 57 | "node_modules/ax25/**/*.js", 58 | "node_modules/terminal-kit/**/*.js" 59 | ] 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/subcommands/send.ts: -------------------------------------------------------------------------------- 1 | import { Config } from '../config' 2 | import { Keystore } from '../Keystore' 3 | import { Messenger } from '../Messenger' 4 | import { isCallsign, isCallsignSSID } from '../utils' 5 | import * as readline from 'readline' 6 | 7 | export async function main(args: any, conf: Config, ks: Keystore): Promise { 8 | 9 | const messenger = new Messenger(conf) 10 | 11 | messenger.on('close', () => { 12 | console.error(`The connection to KISS TNC at ${conf.kissPort} is now closed. Exiting.`) 13 | process.exit(1) 14 | }) 15 | 16 | messenger.on('tnc-error', (err) => { 17 | console.error(`The connection to KISS TNC ${conf.kissPort} experienced the following error:`) 18 | console.error(err) 19 | }) 20 | 21 | try { 22 | await messenger.openTNC() 23 | } catch (err) { 24 | console.error(`Error opening a connection to the KISS TNC that should be listening at ${conf.kissPort}. Are you sure your TNC is running?`) 25 | console.error(`If you have Direwolf installed you can start it in another window with "direwolf -p -q d -t 0"`) 26 | return 1 27 | } 28 | 29 | if (!isCallsign(args.to) && !isCallsignSSID(args.to)) { 30 | console.error(`--to must be a valid callsign, callsign-ssid pair (e.g. "CALL-1"), or chatroom.`) 31 | return 1 32 | } 33 | 34 | // only sign if the user's config has a signing key 35 | const sign: boolean = (typeof conf.signingKey === 'string' && args.dontSign !== true) 36 | if (args.message != null && args.message.length > 0) { 37 | await messenger.send(args.to.toUpperCase(), args.message, sign) 38 | } else { 39 | await new Promise((resolve, reject) => { 40 | const rl: readline.ReadLine = readline.createInterface({ 41 | input: process.stdin, 42 | terminal: false, 43 | crlfDelay: Infinity 44 | }) 45 | 46 | const promises: Promise[] = [] 47 | rl.on('line', (line) => { 48 | promises.push(messenger.send(args.to.toUpperCase(), line, sign)) 49 | }) 50 | 51 | rl.on('close', () => { 52 | Promise.all(promises).then(resolve).catch(reject) 53 | }) 54 | }) 55 | } 56 | 57 | return 0 58 | } 59 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | import { Station } from './Packet' 2 | import { createHash } from 'crypto' 3 | 4 | export function timeout(millis: number): Promise { 5 | return new Promise((resolve) => { 6 | setTimeout(resolve, millis) 7 | }) 8 | } 9 | 10 | // MD5 is weak as hell. Don't use this for anything cryptographic. 11 | export function md5(buffer: string | Buffer): string { 12 | return createHash('md5').update(buffer).digest('hex') 13 | } 14 | 15 | export function stationToCallsignSSID(station: Station): string { 16 | return typeof station.ssid === 'number' && station.ssid !== 0 ? 17 | `${station.callsign}-${station.ssid}` : station.callsign 18 | } 19 | 20 | /** 21 | * @function callsignSSIDToStation 22 | * @param {string} callsignSSID 23 | * @throws {TypeError} If callsignSSID is invalid 24 | * @returns Station 25 | */ 26 | export function callsignSSIDToStation(callsignSSID: string): Station { 27 | if (isCallsignSSID(callsignSSID)) { 28 | const [callsign, ssidStr] = callsignSSID.split('-') 29 | const ssid = parseInt(ssidStr) 30 | return { callsign: callsign, ssid: ssid } 31 | } else if(isCallsign(callsignSSID)) { 32 | return { callsign: callsignSSID, ssid: 0 } 33 | } else { 34 | throw TypeError(`Invalid callsignSSID: ${callsignSSID}`) 35 | } 36 | } 37 | 38 | // mainly lifted from node-ax25 utils.testCallsign 39 | // callsign must be max 6 characters alphanumeric (no "-") 40 | export function isCallsign(callsign: string): boolean { 41 | if (typeof callsign !== 'string' || callsign.length > 6) return false 42 | callsign = callsign.toUpperCase().replace(/\s*$/g, "") 43 | // AX.25 has a built-in hard limit of six characters, which means a 44 | // seven-character callsign cannot be used in an AX.25 network. 45 | if (callsign.length < 1 || callsign.length > 6) return false 46 | for(let c = 0; c < callsign.length; c++) { 47 | let a: number = callsign[c].charCodeAt(0) 48 | if((a >= 48 && a <= 57) || (a >= 65 && a <= 90)) continue 49 | return false 50 | } 51 | return true 52 | } 53 | 54 | export function isCallsignSSID(callsignSSID: string): boolean { 55 | if ((callsignSSID.match(/-/g) || []).length !== 1) return false 56 | const [callsign, ssid] = callsignSSID.split('-') 57 | return isCallsign(callsign) && isSSID(parseInt(ssid)) 58 | } 59 | 60 | export function isSSID(ssid: number) { 61 | if (typeof ssid !== 'number') 62 | throw TypeError('ssid must be a number type') 63 | return ssid >= 0 && ssid <= 15 64 | } 65 | 66 | export function isBrokenPipeError(err: { code: string }): boolean { 67 | return err.code == 'EPIPE' || err.code == 'EIO' 68 | } 69 | -------------------------------------------------------------------------------- /src/subcommands/tty.ts: -------------------------------------------------------------------------------- 1 | import { Config } from '../config' 2 | import { Keystore } from '../Keystore' 3 | import { Station } from '../Packet' 4 | import { Messenger, MessageEvent, Verification } from '../Messenger' 5 | import { isCallsign, isCallsignSSID, callsignSSIDToStation } from '../utils' 6 | import * as readline from 'readline' 7 | 8 | export async function main(args: any, conf: Config, ks: Keystore): Promise { 9 | 10 | const messenger = new Messenger(conf) 11 | 12 | messenger.on('close', () => { 13 | console.error(`The connection to KISS TNC at ${conf.kissPort} is now closed. Exiting.`) 14 | process.exit(1) 15 | }) 16 | 17 | messenger.on('tnc-error', (err) => { 18 | console.error(`The connection to KISS TNC ${conf.kissPort} experienced the following error:`) 19 | console.error(err) 20 | }) 21 | 22 | messenger.on('message', (message: MessageEvent) => { 23 | const to: Station = callsignSSIDToStation(args.to) 24 | if (args.allowAll) console.log(message.message) 25 | else if (args.allRecipients || 26 | (message.to.callsign === to.callsign && message.to.ssid == to.ssid)) { 27 | if (message.verification === Verification.Valid) { 28 | console.log(message.message) 29 | } else if (args.allowUnsigned && message.verification === Verification.NotSigned) { 30 | console.log(message.message) 31 | } else if (args.allowUntrusted && message.verification === Verification.KeyNotFound) { 32 | console.log(message.message) 33 | } else if (args.allowInvalid && message.verification === Verification.Invalid) { 34 | console.log(message.message) 35 | } 36 | } 37 | }) 38 | 39 | try { 40 | await messenger.openTNC() 41 | } catch (err) { 42 | console.error(`Error opening a connection to the KISS TNC that should be listening at ${conf.kissPort}. Are you sure your TNC is running?`) 43 | console.error(`If you have Direwolf installed you can start it in another window with "direwolf -p -q d -t 0"`) 44 | return 1 45 | } 46 | 47 | if (!isCallsign(args.to) && !isCallsignSSID(args.to)) { 48 | console.error(`--to must be a valid callsign, callsign-ssid pair (e.g. "CALL-1"), or chatroom.`) 49 | return 1 50 | } 51 | 52 | // only sign if the user's config has a signing key 53 | const sign: boolean = (typeof conf.signingKey === 'string' && args.dontSign !== true) 54 | await new Promise((resolve, reject) => { 55 | const rl: readline.ReadLine = readline.createInterface({ 56 | input: process.stdin, 57 | terminal: false, 58 | crlfDelay: Infinity 59 | }) 60 | 61 | const promises: Promise[] = [] 62 | rl.on('line', (line) => { 63 | promises.push(messenger.send(args.to.toUpperCase(), line, sign)) 64 | }) 65 | 66 | rl.on('close', () => { 67 | Promise.all(promises).then(resolve).catch(reject) 68 | }) 69 | }) 70 | 71 | return 0 72 | } 73 | -------------------------------------------------------------------------------- /src/subcommands/receive.ts: -------------------------------------------------------------------------------- 1 | import { Config } from '../config' 2 | import { Keystore } from '../Keystore' 3 | import { Messenger, MessageEvent, Verification } from '../Messenger' 4 | import { stationToCallsignSSID, callsignSSIDToStation } from '../utils' 5 | import { Station } from '../Packet' 6 | 7 | function printVerbose(message: MessageEvent, raw: boolean): void { 8 | let msg = `[verbose] received a packet with ` 9 | if (message.verification === Verification.Valid) msg += `VALID_SIGNATURE ` 10 | else if (message.verification === Verification.NotSigned) msg += `NO_SIGNATURE ` 11 | else if (message.verification === Verification.Invalid) msg += `INVALID_SIGNATURE ` 12 | else if (message.verification === Verification.KeyNotFound) msg += `UNKNOWN_SIGNATURE ` 13 | msg += `from ${stationToCallsignSSID(message.from)} ` 14 | msg += `to ${stationToCallsignSSID(message.to)}: ` 15 | if (raw && message.ax25Buffer != null) msg += `${message.ax25Buffer.toString('utf8')}` 16 | else msg += `"${message.message}"` 17 | console.error(msg) 18 | } 19 | 20 | function printPacket(message: MessageEvent, raw: boolean): void { 21 | let msg: string = message.message 22 | if (raw && message.ax25Buffer != null) msg = message.ax25Buffer.toString('utf8') 23 | console.log(msg) 24 | } 25 | 26 | export async function main(args: any, conf: Config, ks: Keystore): Promise { 27 | 28 | const messenger = new Messenger(conf) 29 | 30 | messenger.on('close', () => { 31 | console.error(`The connection to KISS TNC at ${conf.kissPort} is now closed. Exiting.`) 32 | process.exit(1) 33 | }) 34 | 35 | messenger.on('tnc-error', (err) => { 36 | console.error(`The connection to KISS TNC ${conf.kissPort} experienced the following error:`) 37 | console.error(err) 38 | process.exit(1) 39 | }) 40 | 41 | messenger.on('message', (message: MessageEvent) => { 42 | const to: Station = callsignSSIDToStation(args.to) 43 | if (args.verbose) printVerbose(message, args.raw) 44 | if (args.allowAll) printPacket(message, args.raw) 45 | else if (args.allRecipients || 46 | (message.to.callsign === to.callsign && message.to.ssid == to.ssid)) { 47 | if (message.verification === Verification.Valid) { 48 | printPacket(message, args.raw) 49 | } else if (args.allowUnsigned && message.verification === Verification.NotSigned) { 50 | printPacket(message, args.raw) 51 | } else if (args.allowUntrusted && message.verification === Verification.KeyNotFound) { 52 | printPacket(message, args.raw) 53 | } else if (args.allowInvalid && message.verification === Verification.Invalid) { 54 | printPacket(message, args.raw) 55 | } 56 | } 57 | }) 58 | 59 | try { 60 | await messenger.openTNC() 61 | } catch (err) { 62 | console.error(`Error opening a connection to the KISS TNC that should be listening at ${conf.kissPort}. Are you sure your TNC is running?`) 63 | console.error(`If you have Direwolf installed you can start it in another window with "direwolf -p -q d -t 0"`) 64 | return 1 65 | } 66 | 67 | // await an unending promise to hang indefinitely 68 | await new Promise(()=>{}) 69 | return 0 // this will never be reached. 70 | } 71 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Pre-releases 2 | 3 | ## v0.7.0 4 | 5 | - Add KISS support over TCP ([#7](https://github.com/brannondorsey/chattervox/issues/7)). 6 | - Make TCP default KISS connection type. The default `config.kissPort` value is now `kiss://localhost:8001` instead of `/tmp/kisstnc`. 7 | - Add MacOS packaging support via `npm run pkg` (`pkg.sh`). 8 | - Fix tsc type complaint for `Promise`, replaced with `Promise`. 9 | 10 | ## v0.6.1 11 | 12 | - Fix unhandled exception when receiving non-chattervox AX.25 packets ([#24](https://github.com/brannondorsey/chattervox/issues/24)) 13 | - Update README to include instructions for installing Direwolf on Linux and MacOS. Shout out to @danc256 for some additions to the MacOS instructions. 14 | 15 | ## v0.6.0 16 | 17 | - Add feedback debounce feature and config item to filter out received messages if they are exact copies of messages recently sent. The Direwolf TNC can frequently "hear" a message right after its transmitted depending on the hardware setup. This feature protects against this annoying behavior and is now enabled by default. 18 | - Improved cleanup process during shutdown, especially when using the `exec` subcommand. 19 | 20 | ## v0.5.0 21 | 22 | - Add `exec` and `tty` subcommands. 23 | 24 | ## v0.4.0 25 | 26 | - Add `send` and `receive` subcommands ([#16](https://github.com/brannondorsey/chattervox/issues/16)). 27 | - `showkey` now indicates if a key is the signing key (e.g. `Public Key (your signing key): 043da...`). This indication is shown on the Public key only, even though the private key is technically the key used for signing. 28 | - Fix bug where keys wouldn't show up in `showkey` unless both private and public keys were in the store. Now `showkey` shows keys even if only public key is in the store. 29 | - Update README to explain path relationship between `chattervox` binary and `serialport.node` native addon ([#13](https://github.com/brannondorsey/chattervox/issues/13)). 30 | 31 | ## v0.3.2 32 | 33 | - Validate that if `conf.signingkey` exists it has a matching private key before executing `chat` subcommand. 34 | 35 | ## v0.3.1 36 | 37 | - Add details about the TypeScript implementation of the protocol 38 | - Fix off-by-one error in protocol documentation ([#8](https://github.com/brannondorsey/chattervox/issues/8)) 39 | - Add [FAQ](FAQ.md) ([#5](https://github.com/brannondorsey/chattervox/issues/5)) 40 | - Only supporting linux for now (this was always true, but now we are making it explicit) 41 | - Add `pkg.sh` script, run by `npm run pkg` 42 | - Add test coverage with istanbul/nyc and coveralls 43 | - Add continuous integration with Travis CI 44 | 45 | ## v0.3.0 46 | 47 | - Add `config.validate()`. 48 | - Add appropriate `--config` handling ([#4](https://github.com/brannondorsey/chattervox/issues/4)). 49 | - Fix several bugs dealing with loading config files. 50 | - Add `utils.isSSID()`. 51 | - Modify `utils.isCallsign()` to check if callsign is between 1 and 6 characters. 52 | - Add utils and config tests. 53 | 54 | ## v0.2.2 55 | 56 | - Fix `showkey` bug that caused crash if the optional callsign parameter wasn't provided. 57 | 58 | ## v0.2.1 59 | 60 | - Add GPLv3.txt 61 | 62 | ## v0.2.0 63 | 64 | - Add direct message support with `@KC3LZO` ([#2](https://github.com/brannondorsey/chattervox/issues/2)) 65 | - Remove `test/Messenger.test.js` 66 | 67 | ## v0.1.0 68 | 69 | - Add ssid support. 70 | - Add limited callsign validation. 71 | - Add callsign related utility functions in `src/utils.ts` 72 | - Several methods now accept callsigns as `strings` or `Packet.Station` objects. 73 | - Add `Packet.Station` interface. 74 | - Remove `nick` from config. 75 | - Add `ssid` to config (`0` by default). 76 | - Config version bump to 2. 77 | - Relicense under GPL v3 (previously MIT). 78 | - Add `.npmignore`. 79 | - Add `CHANGELOG.md`. 80 | 81 | ## v0.0.2 82 | 83 | - Add `#!/usr/bin/env node` shebang to `src/main.ts` so that `chattervox` installed by npm would run properly. 84 | 85 | ## v0.0.1 86 | 87 | - Initial release. Probably buggy as all get out. 88 | -------------------------------------------------------------------------------- /test/utils.test.js: -------------------------------------------------------------------------------- 1 | const utils = require('../build/utils.js') 2 | const fs = require('fs') 3 | const assert = require('assert') 4 | 5 | describe('utils', () => { 6 | 7 | describe('stationToCallsignSSID()', () => { 8 | 9 | it('should convert a station with an SSID to string', () => { 10 | const station = { callsign: 'KC3LZO', ssid: 1 } 11 | assert.equal('KC3LZO-1', utils.stationToCallsignSSID(station)) 12 | }) 13 | 14 | it('should convert a station with a zero SSID to a basic callsign string', () => { 15 | const station = { callsign: 'KC3LZO', ssid: 0 } 16 | assert.equal('KC3LZO', utils.stationToCallsignSSID(station)) 17 | }) 18 | }) 19 | 20 | describe('callsignSSIDToStation()', () => { 21 | 22 | it('should convert a basic callsign to a station', () => { 23 | const result = utils.callsignSSIDToStation('KC3LZO') 24 | const shouldBe = { callsign: 'KC3LZO', ssid: 0 } 25 | assert.deepEqual(result, shouldBe) 26 | }) 27 | 28 | it('should convert a callsign with an SSID to a station', () => { 29 | const result = utils.callsignSSIDToStation('KC3LZO-14') 30 | const shouldBe = { callsign: 'KC3LZO', ssid: 14 } 31 | assert.deepEqual(result, shouldBe) 32 | }) 33 | 34 | it('should throw an error if the callsign is invalid', () => { 35 | const callsignSSID = 'TESTTEST-10' 36 | assert.throws(() => utils.callsignSSIDToStation(callsignSSID), TypeError) 37 | }) 38 | 39 | it('should throw an error if the ssid is invalid', () => { 40 | const callsignSSID = 'KC3LZO-100' 41 | assert.throws(() => utils.callsignSSIDToStation(callsignSSID), TypeError) 42 | }) 43 | }) 44 | 45 | describe('isCallsign()', () => { 46 | 47 | it('should report that KC3LZO is a callsign', () => { 48 | assert.ok(utils.isCallsign('KC3LZO')) 49 | }) 50 | 51 | it('should report that KC3LZO-1 is not a callsign', () => { 52 | assert.equal(false, utils.isCallsign('KC3LZO-1')) 53 | }) 54 | 55 | it('should report that an empty string is not a callsign', () => { 56 | assert.equal(false, utils.isCallsign('')) 57 | }) 58 | 59 | it('should report #?!~/. is not a callsign', () => { 60 | assert.equal(false, utils.isCallsign('#?!~/.')) 61 | }) 62 | 63 | it('should report that a seven letter callsign is not a callsign. This is an AX25 limitation.', () => { 64 | assert.equal(false, utils.isCallsign('SEVENCH')) 65 | }) 66 | }) 67 | 68 | describe('isCallsignSSID()', () => { 69 | 70 | it('should report that KC3LZO-1 is a callsign with an SSID', () => { 71 | assert.ok(utils.isCallsignSSID('KC3LZO-1')) 72 | }) 73 | 74 | it('should report that KC3LZO is not a callsign with an SSID', () => { 75 | assert.equal(false, utils.isCallsignSSID('KC3LZO')) 76 | }) 77 | }) 78 | 79 | describe('isSSID()', () => { 80 | 81 | it('should report that 0 is a valid SSID', () => { 82 | assert.ok(utils.isSSID(0)) 83 | }) 84 | 85 | it('should report that 1 is a valid SSID', () => { 86 | assert.ok(utils.isSSID(1)) 87 | }) 88 | 89 | it('should report that 15 is a valid SSID', () => { 90 | assert.ok(utils.isSSID(15)) 91 | }) 92 | 93 | it('should report that 16 is not a valid SSID', () => { 94 | assert.equal(false, utils.isSSID(16)) 95 | }) 96 | 97 | it('should report that -1 is not a valid SSID', () => { 98 | assert.equal(false, utils.isSSID(-1)) 99 | }) 100 | 101 | it('should error if passed an empty string', () => { 102 | assert.throws(() => utils.isSSID(''), TypeError) 103 | }) 104 | 105 | it('should error if passed undefined', () => { 106 | assert.throws(() => utils.isSSID(undefined), TypeError) 107 | }) 108 | 109 | it('should error if passed null', () => { 110 | assert.throws(() => utils.isSSID(null), TypeError) 111 | }) 112 | }) 113 | }) 114 | -------------------------------------------------------------------------------- /src/ui/chat.ts: -------------------------------------------------------------------------------- 1 | 2 | import { terminal as term } from 'terminal-kit' 3 | import { Messenger, MessageEvent, Verification } from '../Messenger'; 4 | import { stationToCallsignSSID, isCallsign, isCallsignSSID } from '../utils' 5 | 6 | term.on('key', (name: string , matches: string[], data: any): void => { 7 | if ( matches.includes('CTRL_C') || matches.includes('CTRL_D')) { 8 | exit(0) 9 | } 10 | }) 11 | 12 | type TerminalFunction = (buffer: string) => TerminalFunction // function 13 | const colorMap: { [callsign: string]: TerminalFunction } = {} 14 | const myColorFunction: TerminalFunction = term.cyan 15 | 16 | function getColorFunction(callsign: string): TerminalFunction { 17 | 18 | const choices = [ 19 | term.red, 20 | term.green, 21 | term.yellow, 22 | term.blue, 23 | term.magenta, 24 | term.brightRed, 25 | term.brightGreen, 26 | term.brightYellow, 27 | term.brightBlue, 28 | term.brightMagenta 29 | ] 30 | 31 | if (!colorMap.hasOwnProperty(callsign)) { 32 | colorMap[callsign] = choices[Math.floor(Math.random() * choices.length)] 33 | } 34 | 35 | return colorMap[callsign] 36 | } 37 | 38 | export function enter(): void { 39 | term.fullscreen() 40 | } 41 | 42 | export function exit(code: number): void { 43 | term.processExit(code) 44 | } 45 | 46 | export async function printReceivedMessage(message: MessageEvent, callsign: string): Promise { 47 | 48 | const pos: { x: number, y: number } = await term.getCursorLocation() 49 | if (pos) { 50 | term.moveTo(0, pos.y) 51 | term.insertLine(1) 52 | printStyledText(message) 53 | term.move(pos.x - 1, 0) 54 | 55 | if (term.height === pos.y) { 56 | if (input) { 57 | // term.moveTo(0, term.height) 58 | term.moveTo(0, term.height) 59 | myColorFunction(`${callsign}`)(': ') 60 | input.redraw() 61 | } 62 | } 63 | } 64 | } 65 | 66 | export async function inputLoop(callsign: string, messenger: Messenger, sign: boolean): Promise { 67 | while (true) { 68 | const text = (await prompt(callsign)).trim() 69 | if (text !== '') { 70 | let to = 'CQ' 71 | if (text.startsWith('@')) { 72 | const space = text.indexOf(' ') 73 | const callsign = space === -1 ? text.slice(1) : text.slice(1, space) 74 | if (isCallsign(callsign) || isCallsignSSID(callsign)) 75 | to = callsign.toUpperCase() 76 | } 77 | await messenger.send(to, text, sign) 78 | } 79 | term.eraseLine() 80 | const pos: { x: number, y: number } = await term.getCursorLocation() 81 | term.moveTo(0, pos.y) 82 | myColorFunction(`${callsign}`)(`: ${text}`) 83 | } 84 | } 85 | 86 | let input: any 87 | async function prompt(callsign: string): Promise { 88 | myColorFunction(`\n${callsign}`)(': ') 89 | input = term.inputField({ cancelable: true }) 90 | const message = await input.promise 91 | return message 92 | } 93 | 94 | function printStyledText(message: MessageEvent): void { 95 | 96 | 97 | //// For testing only... 98 | // const rand = Math.random() 99 | // if (rand < 0.25) message.verification = Verification.NotSigned 100 | // else if (rand < 0.50) message.verification = Verification.Valid 101 | // else if (rand < 0.75) message.verification = Verification.Invalid 102 | // else message.verification = Verification.KeyNotFound 103 | 104 | const from: string = stationToCallsignSSID(message.from) 105 | getColorFunction(from)(`${from}`) 106 | switch (message.verification) { 107 | 108 | case Verification.NotSigned: 109 | term(' (UNSIGNED): ').dim(`${message.message}`) 110 | break; 111 | 112 | case Verification.Valid: 113 | term(`: ${message.message}`) 114 | break; 115 | 116 | case Verification.Invalid: 117 | term(' (INVALID SIGNATURE): ').strike(`${message.message}`) 118 | break; 119 | 120 | case Verification.KeyNotFound: 121 | term(' (KEY NOT FOUND): ').underline(`${message.message}`) 122 | break; 123 | } 124 | 125 | term('\n') 126 | } 127 | -------------------------------------------------------------------------------- /src/ui/init.ts: -------------------------------------------------------------------------------- 1 | import { timeout, isCallsign } from '../utils' 2 | import { Config, defaultConfig, save, init, defaultConfigPath } from '../config' 3 | import { Keystore, Key } from '../Keystore' 4 | import { terminal as term } from 'terminal-kit' 5 | 6 | export async function interactiveInit() { 7 | 8 | term(`Welcome! It looks like you are using chattervox for the first time.\n`) 9 | term(`We'll ask you some questions to create an initial settings configuration.\n\n`) 10 | 11 | let conf: Config 12 | while (true) { 13 | conf = await askUser() 14 | term.yellow(`\n${JSON.stringify(conf, null, 2)}`) 15 | term(`\nIs this correct [Y/n]? `) 16 | const correct = (await term.inputField().promise).trim().toLowerCase() 17 | if (correct === '' || correct === 'yes' || correct === 'y') break 18 | } 19 | 20 | // create the ~/.chattervox dir, config.json, and keystore.json 21 | init() 22 | 23 | const ks: Keystore = new Keystore(conf.keystoreFile) 24 | term(`\nGenerating ECDSA keypair...`) 25 | const key: Key = ks.genKeyPair(conf.callsign) 26 | await timeout(2000) // delay for dramatic effect, lol 27 | term(`\nPublic Key: ^c${key.public}^\n`) 28 | 29 | // signatures are created using a private key, but we don't want to include 30 | // the private key in the config file, so instead we use the public key 31 | // as the identifier, and then actually sign with the private key. 32 | conf.signingKey = key.public 33 | 34 | try { 35 | save(conf) 36 | term(`\nSettings saved to ${defaultConfigPath}\n`) 37 | } catch (err) { 38 | term(`\nError saving settings to ${defaultConfigPath}\n`) 39 | term.processExit() 40 | } 41 | } 42 | 43 | async function askUser(): Promise { 44 | 45 | let callsign: string = await promptCallsign() 46 | let ssid: number = await promptSSID() 47 | 48 | term(`\nDo you have a dedicated hardware TNC that you would like to use instead of Direwolf (default: no)? `) 49 | let hasDedicatedTNC: string = (await term.inputField().promise).trim().toLowerCase() 50 | let dedicatedTNC: boolean = (hasDedicatedTNC === 'yes' || hasDedicatedTNC === 'y') 51 | 52 | let kissPort: string 53 | let kissBaud: number 54 | if (dedicatedTNC) { 55 | term(`\nWhat is the serial port device name of this TNC (e.g. /dev/ttyS0)? `) 56 | kissPort = (await term.inputField().promise).trim() 57 | 58 | term(`\nWhat is the baud rate for this serial device (default ${defaultConfig.kissBaud})? `) 59 | const baud = (await term.inputField().promise).trim() 60 | kissBaud = baud === '' ? defaultConfig.kissBaud : parseInt(baud) 61 | } else { 62 | term(`\nWould you like to connect to Direwolf over serial instead of the default TCP connection (default: no)? `) 63 | let prefersSerialRaw: string = (await term.inputField().promise).trim().toLowerCase() 64 | let prefersSerial: boolean = (prefersSerialRaw === 'yes' || prefersSerialRaw === 'y') 65 | if (prefersSerial) { 66 | kissPort = '/tmp/kisstnc' 67 | } 68 | } 69 | 70 | const conf: Config = JSON.parse(JSON.stringify(defaultConfig)) 71 | conf.callsign = callsign 72 | conf.ssid = ssid 73 | if (kissPort) conf.kissPort = kissPort 74 | if (kissBaud) conf.kissBaud = kissBaud 75 | return conf 76 | } 77 | 78 | async function promptCallsign(): Promise { 79 | term(`\nWhat is your call sign (default: ${defaultConfig.callsign})? `) 80 | let callsign: string = (await term.inputField().promise).trim().toUpperCase() 81 | if (callsign === '') return defaultConfig.callsign 82 | else if (isCallsign(callsign)) return callsign 83 | else { 84 | term('\nCallsign must be between 1 and 6 alphanumeric characters.') 85 | return promptCallsign() 86 | } 87 | } 88 | 89 | async function promptSSID(): Promise { 90 | term(`\nWhat SSID would you like to associate with this station (press ENTER to skip)? `) 91 | let ssid: string = await term.inputField().promise 92 | if (ssid.trim() === '') return 0 93 | else if (!isNaN(parseInt(ssid))) { 94 | let num = parseInt(ssid) 95 | if (num >= 0 && num <= 15) return num 96 | } 97 | term('\nSSID must be a number between 0 and 15.') 98 | return promptSSID() 99 | } 100 | -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs' 2 | import * as path from 'path' 3 | import * as os from 'os' 4 | import { isCallsignSSID, isCallsign, isSSID } from './utils' 5 | import { Keystore } from './Keystore' 6 | 7 | export interface Config { 8 | readonly version: number, 9 | callsign: string, 10 | ssid: number, 11 | keystoreFile: string, 12 | kissPort: string, 13 | kissBaud: number, 14 | feedbackDebounce: number, 15 | signingKey?: string, 16 | } 17 | 18 | export const defaultChattervoxDir = path.join(os.homedir(), '.chattervox') 19 | export const defaultConfigPath = path.join(defaultChattervoxDir, 'config.json') 20 | export const defaultKeystorePath = path.join(defaultChattervoxDir, 'keystore.json') 21 | 22 | export const defaultConfig: Config = { 23 | version: 3, 24 | callsign: 'N0CALL', 25 | ssid: 0, 26 | keystoreFile: defaultKeystorePath, 27 | kissPort: 'kiss://localhost:8001', 28 | kissBaud: 9600, 29 | feedbackDebounce: 20 * 1000, 30 | } 31 | 32 | /** Save a config file as JSON 33 | * @function save 34 | * @param {Config} config 35 | * @param {string} configPath? 36 | * @returns void 37 | */ 38 | export function save(config: Config, configPath?: string): void { 39 | validate(config) 40 | const path = typeof configPath === 'string' ? configPath : defaultConfigPath 41 | fs.writeFileSync(path, JSON.stringify(config, null, 4)) 42 | } 43 | 44 | /** Load a config file 45 | * @function load 46 | * @param {string} configPath? 47 | * @returns Config 48 | */ 49 | export function load(configPath?: string): Config { 50 | const path = typeof configPath === 'string' ? configPath : defaultConfigPath 51 | const conf: Config = JSON.parse(fs.readFileSync(path).toString('utf8')) 52 | if (migrate(conf)) save(conf, configPath) 53 | validate(conf) 54 | return conf 55 | } 56 | 57 | /** 58 | * Update an older config to a newer one. Transforms the config object in place. 59 | * @function migrate 60 | * @param {Config} config 61 | * @returns boolean True if the config was changed 62 | */ 63 | export function migrate(config: Config): boolean { 64 | let changed = false 65 | // this change was made in config v3 66 | if (typeof config.feedbackDebounce === 'undefined') { 67 | config.feedbackDebounce = defaultConfig.feedbackDebounce 68 | changed = true 69 | } 70 | return changed 71 | } 72 | 73 | /** Check if the config file (or any file) exists 74 | * @function exists 75 | * @param {string} configPath? 76 | * @returns boolean 77 | */ 78 | export function exists(configPath?: string): boolean { 79 | const path = typeof configPath === 'string' ? configPath : defaultConfigPath 80 | return fs.existsSync(path) 81 | } 82 | 83 | /** 84 | * @function validate 85 | * @param config 86 | * @throws TypeError 87 | */ 88 | export function validate(config: Config): void { 89 | 90 | if (typeof config !== 'object') { 91 | throw TypeError('config is not an object') 92 | } else if (typeof config.version !== 'number') { 93 | throw TypeError('version must be a number type') 94 | } else if (typeof config.callsign !== 'string') { 95 | throw TypeError('callsign must be a string type') 96 | } else if (isCallsignSSID(config.callsign)) { 97 | throw TypeError('callsign must be a valid callsign excluding an SSID') 98 | } else if (!isCallsign(config.callsign)) { 99 | throw TypeError('callsign must be a valid callsign') 100 | } else if (!isSSID(config.ssid)) { 101 | throw TypeError('ssid must be a number between 0 and 15') 102 | } else if (typeof config.kissPort !== 'string') { 103 | throw TypeError('kissPort must be a string type') 104 | } else if (typeof config.kissBaud !== 'number') { 105 | throw TypeError('kissBaud must be a number type') 106 | } else if (typeof config.keystoreFile !== 'string') { 107 | throw TypeError('keystoreFile must be a string type') 108 | } else if (typeof config.signingKey !== 'undefined' 109 | && config.signingKey !== null 110 | && typeof config.signingKey !== 'string') { 111 | throw TypeError('signingKey must be a string or null if it is defined') 112 | } else if (config.feedbackDebounce !== null 113 | && typeof config.feedbackDebounce !== 'number') { 114 | throw TypeError('feedbackDebounce must be a number or null') 115 | } 116 | } 117 | 118 | /** 119 | * Create new chattervox directory, config file, and keystore ONLY if they do 120 | * not already exist. 121 | * @function init 122 | */ 123 | export function init(): void { 124 | 125 | if (!fs.existsSync(defaultChattervoxDir)) { 126 | fs.mkdirSync(defaultChattervoxDir) 127 | } 128 | 129 | if (!exists(defaultConfigPath)) { 130 | save(defaultConfig) 131 | } 132 | 133 | if (!exists(defaultKeystorePath)) { 134 | // simply creating a new keystore object with save the store 135 | new Keystore(defaultKeystorePath) 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ 5 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ 6 | "lib": ["es5", "es2015", "es2016", "es2017"], /* Specify library files to be included in the compilation. */ 7 | // "allowJs": true, /* Allow javascript files to be compiled. */ 8 | // "checkJs": true, /* Report errors in .js files. */ 9 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 10 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 11 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 12 | "sourceMap": true, /* Generates corresponding '.map' file. */ 13 | // "outFile": "./", /* Concatenate and emit output to single file. */ 14 | "outDir": "./build/", /* Redirect output structure to the directory. */ 15 | // "rootDir": "./src/", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 16 | // "composite": true, /* Enable project compilation */ 17 | // "removeComments": true, /* Do not emit comments to output. */ 18 | // "noEmit": true, /* Do not emit outputs. */ 19 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 20 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 21 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 22 | 23 | /* Strict Type-Checking Options */ 24 | "strict": true, /* Enable all strict type-checking options. */ 25 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 26 | "strictNullChecks": false, /* Enable strict null checks. */ 27 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 28 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 29 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 30 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 31 | 32 | /* Additional Checks */ 33 | "noUnusedLocals": true, /* Report errors on unused locals. */ 34 | "noUnusedParameters": false, /* Report errors on unused parameters. */ 35 | "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 36 | "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 37 | 38 | /* Module Resolution Options */ 39 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 40 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 41 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 42 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 43 | // "typeRoots": [], /* List of folders to include type definitions from. */ 44 | // "types": [], /* Type declaration files to be included in compilation. */ 45 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 46 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 47 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 48 | 49 | /* Source Map Options */ 50 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 51 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 52 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 53 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 54 | 55 | /* Experimental Options */ 56 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 57 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 58 | }, 59 | "include": [ 60 | "./src/**/*" 61 | ], 62 | "exclude": [ 63 | "node_modules" 64 | ], 65 | "compileOnSave": true 66 | } -------------------------------------------------------------------------------- /test/Keystore.test.js: -------------------------------------------------------------------------------- 1 | const { Keystore } = require('../build/Keystore.js') 2 | const assert = require('assert') 3 | const fs = require('fs') 4 | 5 | describe('Keystore', function() { 6 | 7 | let ks = null 8 | const call = 'N0CALL' 9 | const path = './test/tmp-keystore.json' 10 | 11 | before(() => { 12 | if (fs.existsSync(path)) fs.unlinkSync(path) 13 | }) 14 | 15 | after(() => { 16 | fs.unlinkSync(path) 17 | }) 18 | 19 | it('should fail on construction with no path parameter', () => { 20 | assert.throws(() => new Keystore(), TypeError) 21 | }) 22 | 23 | it('should should create a new keystore json file if none exists', () => { 24 | assert.ok(!fs.existsSync(path)) 25 | ks = new Keystore(path) 26 | assert.ok(fs.existsSync(path)) 27 | }) 28 | 29 | it('should generate a new key pair', () => { 30 | const { public, private } = ks.genKeyPair(call) 31 | assert.ok(public && private) 32 | }) 33 | 34 | it('should update the keystore JSON file when a new key is generated', () => { 35 | const keystore = JSON.parse(fs.readFileSync(path)) 36 | assert.ok(keystore[call].length == 1) 37 | }) 38 | 39 | it('should return an array of public keys for a callsign in the store', () => { 40 | const keys = ks.getPublicKeys(call) 41 | assert.ok(typeof keys[0] === 'string') 42 | }) 43 | 44 | it('should return an empty array for a callsign that is not in the store', () => { 45 | const keys = ks.getPublicKeys('DEADBEEF') 46 | assert.ok(keys && keys.constructor === Array && keys.length === 0) 47 | }) 48 | 49 | it(`should generate a valid signature from call "${call}"`, () => { 50 | 51 | let message = 'This is a test message.' 52 | const private = ks.getKeyPairs(call)[0].private 53 | const signature = ks.sign(message, private) 54 | const valid = ks.verify(call, message, signature) 55 | assert.ok(valid) 56 | }) 57 | 58 | it(`should not generate a valid signature signed by call "${call}" but verified with "DEADBEEF"`, () => { 59 | 60 | ks.genKeyPair('DEADBEEF') 61 | 62 | let message = 'This is a test message.' 63 | const private = ks.getKeyPairs(call)[0].private 64 | const signature = ks.sign(message, private) 65 | const valid = ks.verify('DEADBEEF', message, signature) 66 | assert.ok(valid === false) 67 | }) 68 | 69 | it(`should remove revoked public keys from the keystore`, () => { 70 | const pubs = ks.getPublicKeys('DEADBEEF') 71 | assert.ok(pubs.length === 1) 72 | const revoked = ks.revoke('DEADBEEF', pubs[0]) 73 | assert.ok(revoked) 74 | assert.ok(ks.getPublicKeys('DEADBEEF').length === 0) 75 | }) 76 | 77 | it(`should not revoked public keys where callsign isn't in the keystore`, () => { 78 | const pubs = ks.getPublicKeys(call) 79 | const revoked = ks.revoke('TEST', pubs[0]) 80 | assert.equal(false, revoked) 81 | assert.ok(ks.getPublicKeys('TEST').length === 0) 82 | }) 83 | 84 | it(`should not revoked public keys that don't exist in the keystore`, () => { 85 | const revoked = ks.revoke(call, '04c89d36628646335c3764bf33072a69e2787d1277639fb007625d7ee9df2139f01dbba76072eac810ff19b2893bb407ca') 86 | const numBefore = ks.getPublicKeys(call).length 87 | assert.ok(revoked === false) 88 | assert.equal(numBefore, ks.getPublicKeys(call).length) 89 | }) 90 | 91 | it(`should return an empty array of keypairs if callsign is not in the keystore`, () => { 92 | assert.deepEqual([], ks.getKeyPairs('UNSEEN')) 93 | }) 94 | 95 | it(`should add a new public key`, () => { 96 | ks.addPublicKey('KC3LZO', '04c89d36628646335c3764bf33072a69e2787d1277639fb007625d7ee9df2139f01dbba76072eac810ff19b2893bb407ca') 97 | }) 98 | 99 | it(`should add a second public key`, () => { 100 | ks.addPublicKey('PUBONLY', '0470326b0d79c816ec4b0b2cc44c76973b3361e53b0929127da7d16c9da8be8cf2eb934894cec50a48e22fd39f8ef3892f') 101 | }) 102 | 103 | it(`the public keys we just added for PUBONLY shouldn't show up in getKeyPairs()`, () => { 104 | assert.deepEqual([], ks.getKeyPairs('PUBONLY')) 105 | }) 106 | 107 | it(`the public keys we just added for PUBONLY should show up in getKeys()`, () => { 108 | assert.equal(ks.getKeys('PUBONLY').length, 1) 109 | }) 110 | 111 | it(`should error if callsign is undefined`, () => { 112 | assert.throws(() => { 113 | ks.addPublicKey(undefined, '04c89d36628646335c3764bf33072a69e2787d1277639fb007625d7ee9df2139f01dbba76072eac810ff19b2893bb407ca') 114 | }) 115 | }) 116 | 117 | it(`should error if publickey is undefined`, () => { 118 | assert.throws(() => { 119 | ks.addPublicKey('KC3LZO', undefined) 120 | }) 121 | }) 122 | 123 | it(`_addKey() should error if privatekey is not undefined and not a string`, () => { 124 | assert.throws(() => { 125 | ks._addKey('KC3LZO', '04c89d36628646335c3764bf33072a69e2787d1277639fb007625d7ee9df2139f01dbba76072eac810ff19b2893bb407ca', true) 126 | }) 127 | }) 128 | 129 | it(`should have three callsigns stored`, () => { 130 | assert.deepEqual([ 'N0CALL', 'DEADBEEF', 'KC3LZO', 'PUBONLY' ], ks.getCallsigns()) 131 | }) 132 | 133 | it(`should load an existing keystore from disk on construction`, () => { 134 | const ks = new Keystore(path) 135 | }) 136 | 137 | }) -------------------------------------------------------------------------------- /src/subcommands/exec.ts: -------------------------------------------------------------------------------- 1 | import { Config } from '../config' 2 | import { Keystore } from '../Keystore' 3 | import { Station } from '../Packet' 4 | import { Messenger, MessageEvent, Verification } from '../Messenger' 5 | import { isCallsign, isCallsignSSID, callsignSSIDToStation, timeout } from '../utils' 6 | import * as readline from 'readline' 7 | import { spawn, ChildProcess } from 'child_process' 8 | 9 | let proc: ChildProcess 10 | 11 | export async function main(args: any, conf: Config, ks: Keystore): Promise { 12 | 13 | const promises: Promise[] = [] 14 | const messenger = new Messenger(conf) 15 | 16 | messenger.on('close', () => { 17 | console.error(`The connection to KISS TNC at ${conf.kissPort} is now closed. Exiting.`) 18 | process.exit(1) 19 | }) 20 | 21 | messenger.on('tnc-error', (err) => { 22 | console.error(`The connection to KISS TNC ${conf.kissPort} experienced the following error:`) 23 | console.error(err) 24 | }) 25 | 26 | messenger.on('message', (message: MessageEvent) => { 27 | let receive = false 28 | const to: Station = callsignSSIDToStation(args.to) 29 | if (args.allowAll) receive = true 30 | else if (args.allRecipients || 31 | (message.to.callsign === to.callsign && message.to.ssid == to.ssid)) { 32 | if (message.verification === Verification.Valid) { 33 | receive = true 34 | } else if (args.allowUnsigned && message.verification === Verification.NotSigned) { 35 | receive = true 36 | } else if (args.allowUntrusted && message.verification === Verification.KeyNotFound) { 37 | receive = true 38 | } else if (args.allowInvalid && message.verification === Verification.Invalid) { 39 | receive = true 40 | } 41 | } 42 | 43 | if (receive) { 44 | promises.push(timeout(args.delay).then(() => writeToProc(proc, message.message))) 45 | } 46 | 47 | }) 48 | 49 | try { 50 | await messenger.openTNC() 51 | } catch (err) { 52 | console.error(`Error opening a connection to the KISS TNC that should be listening at ${conf.kissPort}. Are you sure your TNC is running?`) 53 | console.error(`If you have Direwolf installed you can start it in another window with "direwolf -p -q d -t 0"`) 54 | return 1 55 | } 56 | 57 | if (!isCallsign(args.to) && !isCallsignSSID(args.to)) { 58 | console.error(`--to must be a valid callsign, callsign-ssid pair (e.g. "CALL-1"), or chatroom.`) 59 | return 1 60 | } 61 | 62 | await new Promise((resolve, reject) => { 63 | 64 | const commandArgs: Array = args.command.split(' ') 65 | const command = commandArgs.shift() 66 | 67 | proc = spawn(command, commandArgs) 68 | 69 | proc.stdout.on('data', (data) => { 70 | const text: string = data.toString('utf8') 71 | console.log(text) 72 | promises.push(messenger.send(args.to.toUpperCase(), text, true)) 73 | }) 74 | 75 | if (args.stderr) { 76 | proc.stderr.on('data', (data) => { 77 | const text: string = data.toString('utf8') 78 | console.error(text) 79 | promises.push(messenger.send(args.to.toUpperCase(), text, true)) 80 | }) 81 | } 82 | 83 | proc.on('exit', (code: number) => { 84 | resolve(code) 85 | }) 86 | 87 | proc.on('error', (err: any) => { 88 | if (err.code == 'ENOENT') { 89 | console.error(`"${command}" does not exist.`) 90 | } 91 | reject(err) 92 | }) 93 | 94 | const rl: readline.ReadLine = readline.createInterface({ 95 | input: process.stdin, 96 | terminal: false, 97 | crlfDelay: Infinity 98 | }) 99 | 100 | rl.on('line', (line) => { 101 | proc.stdin.write(line) 102 | proc.stdin.write('\n') 103 | }) 104 | 105 | }) 106 | 107 | await Promise.all(promises) 108 | 109 | return 0 110 | } 111 | 112 | // If we have spawned a child process send it a SIGTERM signal. 113 | // If it doesn't die send it a SIGKILL in 7 seconds. 114 | // Reject the promise if it still isn't dead 3 seconds after that. 115 | export function cleanup(): Promise { 116 | return new Promise((resolve, reject) => { 117 | if (proc) { 118 | proc.on('close', resolve) 119 | proc.on('exit', resolve) 120 | proc.on('error', reject) 121 | 122 | proc.kill('SIGTERM') 123 | // note that these timeouts can still run even after resolve and 124 | // reject, so be careful what's put in here. 125 | setTimeout(() => { 126 | if (proc.pid) { 127 | proc.kill('SIGKILL') 128 | let message = 'Sent SIGKILL signal after child process didn\'t' 129 | message += ' exit from SIGTERM. There may be a zombie process' 130 | message += ' left over as a result.' 131 | console.error(message) 132 | } 133 | }, 7000) 134 | 135 | // give up and reject the promise 136 | setTimeout(reject, 10000) 137 | } else { 138 | resolve() 139 | } 140 | }) 141 | } 142 | 143 | function writeToProc(proc: ChildProcess, text: string): void { 144 | if (proc) { 145 | proc.stdin.write(text) 146 | proc.stdin.write('\n') 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /FAQ.md: -------------------------------------------------------------------------------- 1 | # Frequently Asked Questions 2 | 3 | ## What is Packet Radio? 4 | 5 | Packet radio is a form of packet switching technology used to transmit digital data via wireless communications. It uses a modem to encoded data as audio before it is mixed with a high-frequency carrier wave and transmitted over frequency modulated (FM) radio. 6 | 7 | ## Where can I learn more about packet radio? 8 | 9 | In 2015, I participated in a fantastic packet radio workshop at the first Radical Networks conference in Brooklyn, NY. The workshop was lead by artists Dennis de Bel and Roel Roscam Abbing who created a small zine called [**Messing Around with Packet Radio**](https://books.vvvvvvaria.org/book/41) ([PDF](https://books.vvvvvvaria.org/download/41/pdf/41.PDF)). I can't recommend that text enough as a fun and non-standard introduction to the subject. 10 | 11 | ## What's the point of chattervox? 12 | 13 | Chattervox adds cryptographic verifiability to text-based amateur radio communication. We've added built-in support for DEFLATE compression as a secondary goal for efficiency. 14 | 15 | ## What's a terminal node controller (TNC)? 16 | 17 | A terminal node controller is a mechanism used to receive and transmit AX.25 amateur radio packets. Historically, they've been hardware devices that attach to and communicate with a host computer via a serial connection. These days, their functionality can be entirely implemented in software. [Direwolf](https://github.com/wb2osz/direwolf) is an example of a modern software TNC. TNCs have the capability to: 18 | 19 | - Receive AX.25 packets and forward them over serial connections to applications that are listening for them 20 | - Transmit AX.25 packets on behalf of client applications that request them via a serial connection 21 | - Attempt to correct transmission errors in the AX.25 packets it receives 22 | - Automatically manage interaction with a transmission channel, buffering the transmission of packets until the channel appears clear 23 | - Be configured as a digipeater to automatically rebroadcast the AX.25 packets they receive and extend the range of the original sender's radio footprint 24 | - Be configured as internet gateway devices, uploading packets they receive over the air to the internet 25 | 26 | ## How far can I communicate with chattervox? 27 | 28 | The distance you can communicate depends on the transmission medium you are using. Messages are encoded and decoded using audio, so anything that can produce or receive audio is capable of sending or receiving chattervox messages. The trick is carrying that audio signal a great distance, and for that the solution is radio. VHF (30-300Mhz) and UHF (300Mhz-3Ghz) radio frequencies can carry signals 2-10+ miles depending on your location, antenna, output power, and propagation characteristics. HF frequencies (3-30Mhz) are capable of reaching several thousand miles, or across oceans. Hell, you could tunnel the audio connection over the internet if you really wanted. 29 | 30 | ## Is this legal? 31 | 32 | Yes! Well, it depends. If you broadcast digital data on the airwaves you have to make sure that you are allowed to do so. The legality general depends on: 33 | 34 | - Where you are? 35 | - Who you are? 36 | - What frequencies you are using? 37 | 38 | ## What if I'm not a licensed amateur? 39 | 40 | If you're not a licensed amateur you can still play around with chattervox! Chattervox uses audio to transmit messages, so you can use it independent of radio if you'd like. For instance, if you have a speaker and microphone, you can use it in a small room. Otherwise, you can probably use it over the internet as well by live streaming audio from your computer. If you are interested in using "on the air", there isn't a ton of unlicensed radio spectrum, at least in the US. You could probably get away with broadcasting on low power on FMRS (walky-talky) and MURS (Multi-use radio service) frequency bands without getting caught 😉, but technically digital modes are prohibited on those frequencies as well. Depending on where you are located, you may also be able to find equipment that operates in the unlicensed [industrial, scientific, and medical (ISM)](https://en.wikipedia.org/wiki/ISM_band) radio bands. 41 | 42 | All that said, obtaining a ham license is pretty easy if you devote a few nights to [studying](https://hamstudy.org/). Once you've got a license you can legally use this protocol on tons of spectrum at high-power levels. 43 | 44 | ## What does chattervox use for digital signatures? 45 | 46 | Chattervox uses elliptic curve cryptography to manage key signatures and verifications. Specifically, v1 of the packet protocol supports ECDSA using the NIST p192 curve implemented in [`elliptic`](https://github.com/indutny/elliptic/), a fast elliptic curve cryptography library for JavaScript. Signatures are created using a SHA-256 hash of a message's contents as well as the sender's private key. The receiver can then verify that the message was received without alteration and sent by the expected party using the received message and the sender's public key. All of this happens automatically by the `chattervox chat` application and the user is alerted if key signatures are not present or fail a verification check. The source code that manages digital signatures can be found in the [`src/Keystore.ts`](src/Keystore.ts) file. 47 | 48 | ## Is there receipt confirmation built into the protocol? 49 | 50 | No. Chattervox is a connectionless protocol (at least as of packet version 1). This means that there is no acknowledgement process built into the protocol. Think of the chattervox protocol like UDP, instead of TCP in this way. This decision was made deliberately for simplicity, as the goal of the chattervox protocol is to **add cryptographic verifiability to text-based radio communication**. 51 | 52 | ## Why is it called "chattervox"? 53 | 54 | VOX, or voice operated transmission, is a popular feature in some radios which allows for automatic TX when audio is detected using the microphone. This feature allows a radio tethered to a computer to automatically transmit data directly from a computer's audio output. Modem software running on the computer uses VOX to transmit without human involvement as is common with PTT (push-to-talk) TX. The combination of the words chatter and vox is a play on the words chatterbox (I'm sorry). -------------------------------------------------------------------------------- /src/Packet.ts: -------------------------------------------------------------------------------- 1 | import * as AX25 from 'ax25' // https://github.com/echicken/node-ax25/tree/es6rewrite 2 | import { compress, decompress } from './compression.js' 3 | import { callsignSSIDToStation } from './utils.js'; 4 | 5 | export enum HeaderFlags { 6 | Compressed = 0x01, 7 | Signed = 0x2 8 | } 9 | 10 | export interface Station { 11 | callsign: string, 12 | ssid: number 13 | } 14 | 15 | export const MagicBytes = [0x7a, 0x39] 16 | 17 | export interface Header { 18 | version: number, 19 | compressed: boolean, 20 | signed: boolean, 21 | signatureLength: number 22 | } 23 | 24 | export class Packet { 25 | 26 | header: Header 27 | from: Station 28 | to: Station 29 | message: string 30 | signature: Buffer 31 | data: Buffer 32 | 33 | constructor() { 34 | 35 | this.header = { 36 | version: 0x01, 37 | compressed: null, 38 | signed: null, 39 | signatureLength: null 40 | } 41 | 42 | this.from = null 43 | this.to = null 44 | this.message = null 45 | this.signature = null 46 | this.data = null 47 | } 48 | 49 | async toAX25Packet(): Promise { 50 | const packet = new AX25.Packet() 51 | packet.type = AX25.Masks.control.frame_types.u_frame.subtypes.ui 52 | packet.source = this.from 53 | packet.destination = this.to 54 | packet.payload = await this.assemble() 55 | return packet.assemble() 56 | } 57 | 58 | async assemble(): Promise { 59 | 60 | if (Buffer.isBuffer(this.signature)) { 61 | this.header.signed = true 62 | this.header.signatureLength = this.signature.length 63 | } 64 | 65 | // compress signature + message 66 | let payload: Buffer = this.header.signed ? this.signature : Buffer.from([]) 67 | let message: Buffer = Buffer.from(this.message, 'utf8') 68 | const compressed = await compress(message) 69 | if (compressed.length < message.length) { 70 | this.header.compressed = true 71 | payload = Buffer.concat([payload, compressed]) 72 | } else { 73 | this.header.compressed = false 74 | payload = Buffer.concat([payload, message]) 75 | } 76 | 77 | // flags 78 | let flags = 0x00 79 | if (this.header.signed) flags = flags | HeaderFlags.Signed 80 | if (this.header.compressed) flags = flags | HeaderFlags.Compressed 81 | 82 | // header buffer 83 | const headerArray = [...MagicBytes, this.header.version, flags] 84 | if (this.signature !== null) { 85 | if (this.signature.length > 256) throw Error('signature is larger than 256 bytes') 86 | headerArray.push(this.signature.length) 87 | } 88 | 89 | const header = Buffer.from(new Uint8Array(headerArray)) 90 | this.data = Buffer.concat([header, payload]) 91 | return this.data 92 | } 93 | 94 | async disassemble(data: Buffer): Promise { 95 | 96 | if (!Buffer.isBuffer(data)) throw TypeError('Invalid data must be a Buffer') 97 | 98 | if (data.length < 4) { 99 | throw TypeError('Invalid packet, too few bytes.') 100 | } 101 | 102 | const magic = data.slice(0, 2) 103 | if (magic[0] !== MagicBytes[0] || magic[1] !== MagicBytes[1]) { 104 | throw TypeError(`Invalid magic bytes in packet header. This is not a CV Packet.`) 105 | } 106 | 107 | const version = data[2] 108 | if (version !== 1) { 109 | throw TypeError(`Invalid packet version: ${version}`) 110 | } 111 | 112 | const flags = data[3] 113 | this.header.compressed = (flags & HeaderFlags.Compressed) == HeaderFlags.Compressed 114 | this.header.signed = (flags & HeaderFlags.Signed) == HeaderFlags.Signed 115 | 116 | // console.log(`compressed: ${this.header.compressed}`) 117 | // console.log(`signed: ${this.header.signed}`) 118 | 119 | let payloadIndex = 4 120 | if (this.header.signed) { 121 | this.header.signatureLength = data[4] 122 | payloadIndex = 5 123 | } 124 | 125 | let payload: Buffer = data.slice(payloadIndex) 126 | let messageIndex = 0 127 | if (this.header.signed) { 128 | this.signature = payload.slice(0, this.header.signatureLength) 129 | messageIndex = this.header.signatureLength 130 | } 131 | 132 | if (this.header.compressed) { 133 | this.message = (await decompress(payload.slice(messageIndex))).toString('utf8') 134 | } else { 135 | this.message = payload.slice(messageIndex).toString('utf8') 136 | } 137 | 138 | } 139 | 140 | static async ToAX25Packet(from: string | Station, 141 | to: string | Station, 142 | utf8Text: string, 143 | signature?: Buffer): Promise { 144 | 145 | if (typeof from === 'string') from = callsignSSIDToStation(from) 146 | if (typeof to === 'string') to = callsignSSIDToStation(to) 147 | 148 | const packet = new Packet() 149 | packet.from = from 150 | packet.to = to 151 | packet.message = utf8Text 152 | 153 | if (signature) { 154 | if (Buffer.isBuffer(signature)) packet.signature = signature 155 | else throw TypeError(`signature must be a Buffer type, not ${typeof signature}`) 156 | } 157 | 158 | if (packet.signature) { 159 | packet.header.signatureLength = packet.signature.length 160 | } 161 | 162 | return await packet.toAX25Packet() 163 | } 164 | 165 | static async FromAX25Packet(ax25Buffer: Buffer): Promise { 166 | 167 | const ax25Packet = new AX25.Packet() 168 | try { 169 | ax25Packet.disassemble(ax25Buffer) 170 | } catch (err) { 171 | throwInvalidPacketError(err) 172 | } 173 | 174 | const packet = new Packet() 175 | packet.from = ax25Packet.source 176 | packet.to = ax25Packet.destination 177 | try { 178 | await packet.disassemble(ax25Packet.payload) 179 | } catch (err) { 180 | throwInvalidPacketError(err) 181 | } 182 | 183 | return packet 184 | } 185 | } 186 | 187 | function throwInvalidPacketError(err: Error): TypeError { 188 | const error = TypeError(err.message) 189 | error.name = 'InvalidPacket' 190 | throw error 191 | } 192 | -------------------------------------------------------------------------------- /src/Keystore.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs' 2 | import { createHash } from 'crypto' 3 | import { ec as EC } from 'elliptic' 4 | const ec = new EC('p192') 5 | 6 | type Curve = 'p192' 7 | 8 | export interface Key { 9 | curve: Curve, 10 | public: string 11 | private?: string 12 | } 13 | 14 | type keystore = { [callsign: string]: Key[] } 15 | 16 | /** 17 | * @class Keystore 18 | * A class for managing keys, signatures, and signature verification 19 | */ 20 | export class Keystore { 21 | 22 | readonly path: string 23 | private _keystore: keystore 24 | 25 | /**@constructor 26 | * @param {string} path The path to a JSON keystore file. If path does not exist it is created. 27 | */ 28 | constructor(path: string) { 29 | 30 | this.path = path 31 | this._keystore = {} 32 | 33 | if (!this._exists()) { 34 | this._save() 35 | } else { 36 | this._keystore = this._load() 37 | } 38 | } 39 | 40 | /** 41 | * @method addPublicKey 42 | * @param {string} callsign 43 | * @param {string} pubkeyHex 44 | */ 45 | addPublicKey(callsign: string, pubkeyHex: string): void { 46 | this._addKey(callsign, pubkeyHex, undefined) 47 | } 48 | 49 | // only used for you 50 | /** 51 | * @param {string} callsign 52 | * @returns {object} keypair object 53 | */ 54 | genKeyPair(callsign: string): Key { 55 | const key = ec.genKeyPair() 56 | const pub = key.getPublic('hex') 57 | const priv = key.getPrivate('hex') 58 | this._addKey(callsign, pub, priv) 59 | return { public: pub, private: priv, curve: 'p192' } 60 | } 61 | /** 62 | * Remove a Key object from the keystore, using the public key. 63 | * @param {string} callsign 64 | * @param {string} pubkeyHex 65 | * @returns {boolean} True if a key was removed from the keystore. 66 | */ 67 | revoke(callsign: string, pubkeyHex: string): boolean { 68 | 69 | // callsign not in keystore, no key is revoked 70 | if (!this._keystore.hasOwnProperty(callsign)) return false 71 | 72 | // number of keys before the filter 73 | const length = this._keystore[callsign].length 74 | this._keystore[callsign] = this._keystore[callsign].filter((key: Key) => { 75 | return key.public !== pubkeyHex 76 | }) 77 | 78 | if (this._keystore[callsign].length !== length) { 79 | this._save() 80 | return true 81 | } 82 | 83 | return false 84 | } 85 | 86 | /** Get a list of callsigns. 87 | * @method getCallsigns 88 | * @returns {string[]} 89 | */ 90 | getCallsigns(): string[] { 91 | return Object.keys(this._keystore) 92 | } 93 | 94 | /** 95 | * @method getPublicKeys 96 | * @param {string} callsign 97 | * @returns {string[]} An array of public keys associated with a call sign. 98 | */ 99 | getPublicKeys(callsign: string): string[] { 100 | if (!this._keystore.hasOwnProperty(callsign)) return [] 101 | return this._keystore[callsign].map(key => key.public) 102 | } 103 | 104 | /** 105 | * Get Key objects that have both public and private keys 106 | * @method getKeyPairs 107 | * @param {string} callsign 108 | * @returns {Key[]} An array of keypair objects that have both { public: 'hex', private: 'hex' } 109 | */ 110 | getKeyPairs(callsign: string): Key[] { 111 | return this.getKeys(callsign).filter(key => { 112 | return typeof key.public === 'string' && typeof key.private === 'string' 113 | }) 114 | } 115 | 116 | /** Get Key objects that have at least a public key 117 | * @method getKeys 118 | * @param {string} callsign 119 | * @returns {Key[]} An array of key objects that have at least a public key 120 | */ 121 | getKeys(callsign: string): Key[] { 122 | if (!this._keystore.hasOwnProperty(callsign)) return [] 123 | return this._keystore[callsign] 124 | } 125 | 126 | 127 | /**@method sign 128 | * @param {string} message A string containing a message to sign. 129 | * @param {string} privateHex A private key as a string of hex characters. 130 | * @returns {Buffer} A message signature. 131 | */ 132 | sign(message: string, privateHex: string): Buffer { 133 | const key = ec.keyFromPrivate(privateHex) 134 | const hash: Buffer = this.sha256(message) 135 | const signature = key.sign(hash).toDER() 136 | return Buffer.from(signature) 137 | } 138 | 139 | 140 | /**@method verify 141 | * @param {string} callsign 142 | * @param {string} message 143 | * @param {Buffer} signature 144 | * @returns {boolean} True if the message signature is valid 145 | */ 146 | verify(callsign: string, message: string, signature: Buffer): boolean { 147 | const hash = this.sha256(message) 148 | for (let publicKey of this.getPublicKeys(callsign)) { 149 | const key = ec.keyFromPublic(publicKey, 'hex') 150 | if (key.verify(hash, signature)) return true 151 | } 152 | return false 153 | } 154 | 155 | /** 156 | * @method sha256 157 | * @param {string} message 158 | * @return {Buffer} The SHA 256 message digest 159 | */ 160 | sha256(message: string): Buffer { 161 | return createHash('sha256') 162 | .update(message, 'utf8') 163 | .digest() 164 | } 165 | 166 | private _addKey(callsign: string, publicHex: string, privateHex?: string): void { 167 | 168 | if (typeof callsign !== 'string') throw TypeError('callsign must be a string type') 169 | if (typeof publicHex !== 'string') throw TypeError('publicHex must be a string type') 170 | if (typeof privateHex !== 'undefined' && typeof privateHex !== 'string') throw TypeError('if privateHex is not undefined it must be a string type') 171 | 172 | if (!this._keystore.hasOwnProperty(callsign)) { 173 | this._keystore[callsign] = [] 174 | } 175 | 176 | const key: Key = { public: publicHex, curve: 'p192' } 177 | if (privateHex) key.private = privateHex 178 | this._keystore[callsign].push(key) 179 | this._save() 180 | } 181 | 182 | private _save(): void { 183 | fs.writeFileSync(this.path, JSON.stringify(this._keystore, null, '\t')) 184 | } 185 | 186 | private _load(): keystore { 187 | return JSON.parse(fs.readFileSync(this.path).toString('utf8')) 188 | } 189 | 190 | private _exists(): boolean { 191 | return fs.existsSync(this.path) 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/Messenger.ts: -------------------------------------------------------------------------------- 1 | import KISS_TNC from 'kiss-tnc' 2 | import { EventEmitter } from 'events' 3 | import { Keystore } from './Keystore.js' 4 | import { Packet, Station } from './Packet.js' 5 | import { Config } from './config.js' 6 | import { callsignSSIDToStation, timeout, md5 } from './utils.js' 7 | 8 | export interface MessageEvent { 9 | to: Station 10 | from: Station 11 | message: string 12 | verification: Verification, 13 | ax25Buffer?: Buffer 14 | } 15 | 16 | export enum Verification { 17 | NotSigned, 18 | KeyNotFound, 19 | Valid, 20 | Invalid 21 | } 22 | 23 | export class Messenger extends EventEmitter { 24 | 25 | private ks: Keystore 26 | private tnc: any 27 | private config: Config 28 | private recentlySent = new Map() 29 | 30 | constructor(config: Config) { 31 | super() 32 | this.config = config 33 | this.ks = new Keystore(this.config.keystoreFile) 34 | if (this.ks.getKeyPairs(config.callsign).length === 0) { 35 | this.ks.genKeyPair(config.callsign) 36 | } 37 | 38 | // device, baud_rate 39 | this.tnc = this._createTNC(config.kissPort, config.kissBaud) 40 | } 41 | 42 | openTNC(): Promise { 43 | return new Promise((resolve, reject) => { 44 | if (this.tnc == null) { 45 | this.tnc = this._createTNC(this.config.kissPort, this.config.kissBaud) 46 | } 47 | 48 | this.tnc.open((err: any) => { 49 | this.emit('open', err) 50 | if (err) reject(err) 51 | else resolve() 52 | }) 53 | }) 54 | } 55 | 56 | closeTNC(): void { 57 | this.tnc.close() 58 | this.tnc = null 59 | this.emit('close') 60 | } 61 | 62 | async send(to: string | Station, message: string, sign: boolean) { 63 | if (typeof to === 'string') to = callsignSSIDToStation(to) 64 | const from: Station = { callsign: this.config.callsign, ssid: this.config.ssid } 65 | 66 | let signature: Buffer = null 67 | if (sign) { 68 | if (this.config.signingKey) { 69 | const privates = this.ks.getKeyPairs(this.config.callsign) 70 | .filter(key => key.public === this.config.signingKey) 71 | .map(key => key.private) 72 | if (privates.length > 0) { 73 | signature = this.ks.sign(message, privates[0]) 74 | } else { 75 | throw Error('No signing key was found in the keystore. Make sure your config.signingKey is in your keystore.') 76 | } 77 | } else { 78 | throw Error(`sign is ${sign} but config.signingKey "${this.config.signingKey}" is not in keystore.`) 79 | } 80 | } 81 | 82 | const packet: Buffer = await Packet.ToAX25Packet(from, to, message, signature) 83 | if (this.tnc == null) throw Error('Error sending message with send(). The Messenger\'s TNC object is null. Are you sure it is connected?') 84 | return new Promise((resolve, reject) => { 85 | this.tnc.send_data(packet, (err: Error) => { 86 | if (err) reject(err) 87 | if (this.config.feedbackDebounce) { 88 | this._addToRecentlySent(packet, this.config.feedbackDebounce) 89 | } 90 | resolve() 91 | }) 92 | }) 93 | } 94 | 95 | private async _onAX25DataRecieved(data: any): Promise { 96 | 97 | let packet: Packet 98 | try { 99 | packet = await Packet.FromAX25Packet(data.data) 100 | } catch (err) { 101 | if (err.name == 'InvalidPacket') { 102 | // console.log('Received invalid packet, skipping') 103 | return 104 | } else throw err 105 | } 106 | 107 | if (this.config.feedbackDebounce && this._wasRecentlySent(data.data)) { 108 | // console.error('[verbose] received recently sent message, aborting received event.') 109 | return 110 | } 111 | 112 | let verification = Verification.NotSigned 113 | if (packet.signature) { 114 | // if we don't have a public key from that callsign 115 | if (this.ks.getPublicKeys(packet.from.callsign).length === 0) { 116 | verification = Verification.KeyNotFound 117 | } else { 118 | const verified = this.ks.verify(packet.from.callsign, packet.message, packet.signature) 119 | if (verified) verification = Verification.Valid 120 | else verification = Verification.Invalid 121 | } 122 | } 123 | 124 | const event: MessageEvent = { 125 | to: { callsign: packet.to.callsign.trim(), ssid: packet.to.ssid }, 126 | from: { callsign: packet.from.callsign.trim(), ssid: packet.from.ssid }, 127 | message: packet.message, 128 | verification, 129 | ax25Buffer: data.data 130 | } 131 | 132 | this.emit('message', event) 133 | } 134 | 135 | private _createTNC(port: string, baudrate: number): any { 136 | const tnc = new KISS_TNC(port, baudrate) 137 | // process.on('SIGTERM', tnc.close) 138 | tnc.on('error', (error: any) => this.emit('tnc-error', error)) 139 | tnc.on('data', (data: any) => this._onAX25DataRecieved(data)) 140 | return tnc 141 | } 142 | 143 | private _addToRecentlySent(buffer: Buffer, expiresIn: number): void { 144 | // MD5 is weak, but it doesn't matter here because we aren't using it 145 | // for anything sensitive. Here we like speed ;) 146 | const fingerprint = md5(buffer) 147 | if (!this.recentlySent.has(fingerprint)) { 148 | this.recentlySent.set(fingerprint, 1) 149 | } else { 150 | let count = this.recentlySent.get(fingerprint) 151 | this.recentlySent.set(fingerprint, count + 1) 152 | } 153 | timeout(expiresIn).then(() => { 154 | const count = this.recentlySent.get(fingerprint) 155 | if (count == 1) this.recentlySent.delete(fingerprint) 156 | else this.recentlySent.set(fingerprint, count - 1) 157 | }) 158 | } 159 | 160 | private _wasRecentlySent(buffer: Buffer): boolean { 161 | // MD5 is weak, but it doesn't matter here because we aren't using it 162 | // for anything sensitive. Here we like speed ;) 163 | const fingerprint = md5(buffer) 164 | return this.recentlySent.has(fingerprint) 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /test/config.test.js: -------------------------------------------------------------------------------- 1 | const config = require('../build/config.js') 2 | const fs = require('fs') 3 | const assert = require('assert') 4 | 5 | describe('config', () => { 6 | 7 | const tmpConfig = 'tmp-config.json' 8 | let conf = { 9 | version: 3, 10 | callsign: 'N0CALL', 11 | ssid: 0, 12 | keystoreFile: './tmp-keystore.json', 13 | kissPort: '/tmp/kisstnc', 14 | kissBaud: 9600, 15 | feedbackDebounce: 20 * 1000, 16 | } 17 | 18 | const tmpConfigV2 = 'tmp-config-v2.json' 19 | let confV2 = { 20 | version: 2, 21 | callsign: 'N0CALL', 22 | ssid: 0, 23 | keystoreFile: './tmp-keystore.json', 24 | kissPort: '/tmp/kisstnc', 25 | kissBaud: 9600, 26 | } 27 | 28 | before(() => { 29 | fs.writeFileSync(conf.keystoreFile, '{}') 30 | fs.writeFileSync(tmpConfigV2, JSON.stringify(confV2)) 31 | }) 32 | 33 | after(() => { 34 | fs.unlinkSync(conf.keystoreFile) 35 | fs.unlinkSync(tmpConfig) 36 | fs.unlinkSync(tmpConfigV2) 37 | }) 38 | 39 | describe('save', () => { 40 | 41 | it ('should save a valid config file', () => { 42 | config.save(conf, tmpConfig) 43 | }) 44 | 45 | it ('should not save an invalid config file', () => { 46 | const c = copy(conf) 47 | delete c.callsign 48 | assert.throws(() => config.save(c, tmpConfig), TypeError) 49 | }) 50 | }) 51 | 52 | describe('exists', () => { 53 | 54 | it ('should find that a valid file exists', () => { 55 | assert.ok(config.exists(tmpConfig)) 56 | }) 57 | 58 | it ('should find that an invalid file doesn\'t exist', () => { 59 | assert.equal(false, config.exists('/some/file/that/doesn\'t/exist')) 60 | }) 61 | }) 62 | 63 | describe('load', () => { 64 | 65 | it ('should load an existing config file', () => { 66 | conf = config.load(tmpConfig) 67 | }) 68 | 69 | it ('should error when loading a non existing config file', () => { 70 | assert.throws(() => config.load('/non/existing/path.json'), Error) 71 | }) 72 | 73 | it ('should error when loading an invalid config file', () => { 74 | const path = './tmp-invalid-config.json' 75 | const c = copy(conf) 76 | delete c.callsign 77 | fs.writeFileSync(path, JSON.stringify(c)) 78 | assert.throws(() => config.load(path), TypeError) 79 | fs.unlinkSync(path) 80 | }) 81 | }) 82 | 83 | describe('migrate', () => { 84 | 85 | it ('should migrate a v2 config file', () => { 86 | assert.equal(confV2.feedbackDebounce, undefined) 87 | const changed = config.migrate(confV2) 88 | assert.equal(changed, true) 89 | assert.equal(confV2.feedbackDebounce, config.defaultConfig.feedbackDebounce) 90 | }) 91 | 92 | it ('should load a config v2 file', () => { 93 | config.load(tmpConfigV2) 94 | }) 95 | 96 | it ('should save a migrated v2 -> v3 config file on load()', () => { 97 | const migratedConf = JSON.parse(fs.readFileSync(tmpConfigV2).toString('utf8')) 98 | assert.equal(migratedConf.feedbackDebounce, config.defaultConfig.feedbackDebounce) 99 | }) 100 | }) 101 | 102 | describe('validate', () => { 103 | 104 | it ('should validate a valid config JSON object', () => { 105 | config.validate(conf) 106 | }) 107 | 108 | it ('should error if no config object is passed into it', () => { 109 | assert.throws(() => config.validate(), TypeError) 110 | }) 111 | 112 | // -------------------------------------------------------------------- 113 | 114 | it ('should error if version doesn\'t exist', () => { 115 | const c = copy(conf) 116 | delete c.version 117 | assert.throws(() => config.validate(c), TypeError) 118 | }) 119 | 120 | it ('should error if callsign doesn\'t exist', () => { 121 | const c = copy(conf) 122 | delete c.callsign 123 | assert.throws(() => config.validate(c), TypeError) 124 | }) 125 | 126 | it ('should error if ssid doesn\'t exist', () => { 127 | const c = copy(conf) 128 | delete c.ssid 129 | assert.throws(() => config.validate(c), TypeError) 130 | }) 131 | 132 | it ('should error if kissPort doesn\'t exist', () => { 133 | const c = copy(conf) 134 | delete c.kissPort 135 | assert.throws(() => config.validate(c), TypeError) 136 | }) 137 | 138 | it ('should error if kissBaud doesn\'t exist', () => { 139 | const c = copy(conf) 140 | delete c.kissBaud 141 | assert.throws(() => config.validate(c), TypeError) 142 | }) 143 | 144 | it ('should error if keystoreFile doesn\'t exist', () => { 145 | const c = copy(conf) 146 | delete c.keystoreFile 147 | assert.throws(() => config.validate(c), TypeError) 148 | }) 149 | 150 | it ('should error if feedbackDebounce doesn\'t exist', () => { 151 | const c = copy(conf) 152 | delete c.feedbackDebounce 153 | assert.throws(() => config.validate(c), TypeError) 154 | }) 155 | 156 | // -------------------------------------------------------------------- 157 | 158 | it ('should error if version isn\'t a number', () => { 159 | const c = copy(conf) 160 | c.version = '4' 161 | assert.throws(() => config.validate(c), TypeError) 162 | }) 163 | 164 | it ('should error if callsign is invalid', () => { 165 | const c = copy(conf) 166 | c.callsign = '' 167 | assert.throws(() => config.validate(c), TypeError) 168 | c.callsign = 'LONGCALL' 169 | assert.throws(() => config.validate(c), TypeError) 170 | }) 171 | 172 | it ('should error if callsign includes SSID', () => { 173 | const c = copy(conf) 174 | c.callsign = 'KC3LZO-1' 175 | assert.throws(() => config.validate(c), TypeError) 176 | }) 177 | 178 | it ('should error if ssid is invalid', () => { 179 | const c = copy(conf) 180 | c.ssid = -1 181 | assert.throws(() => config.validate(c), TypeError) 182 | c.ssid = 16 183 | assert.throws(() => config.validate(c), TypeError) 184 | 185 | c.ssid = 15 186 | config.validate(c) 187 | }) 188 | 189 | it ('should error if kissPort is not a string', () => { 190 | const c = copy(conf) 191 | c.kissPort = 8 192 | assert.throws(() => config.validate(c), TypeError) 193 | }) 194 | 195 | it ('should error if kissBaud is not a string', () => { 196 | const c = copy(conf) 197 | c.kissBaud = '9600' 198 | assert.throws(() => config.validate(c), TypeError) 199 | }) 200 | 201 | it ('should error if keystoreFile isn\'t a string', () => { 202 | const c = copy(conf) 203 | c.keystoreFile = true 204 | assert.throws(() => config.validate(c), TypeError) 205 | }) 206 | 207 | it ('should error if signingKey is included but not a string', () => { 208 | const c = copy(conf) 209 | c.signingKey = 5 210 | assert.throws(() => config.validate(c), TypeError) 211 | }) 212 | 213 | it ('should error if feedbackDebounce isn\'t null or a number', () => { 214 | const c = copy(conf) 215 | c.feedbackDebounce = '4000' 216 | assert.throws(() => config.validate(c), TypeError) 217 | 218 | }) 219 | }) 220 | }) 221 | 222 | function copy(obj) { 223 | return JSON.parse(JSON.stringify(obj)) 224 | } 225 | -------------------------------------------------------------------------------- /test/Packet.test.js: -------------------------------------------------------------------------------- 1 | const { Packet } = require('../build/Packet.js') 2 | const { Keystore } = require('../build/Keystore.js') 3 | const assert = require('assert') 4 | const fs = require('fs') 5 | 6 | describe('Packet', () => { 7 | 8 | const ks = new Keystore('tmp-keystore.json') 9 | const { public, private } = ks.genKeyPair('N0CALL') 10 | 11 | const shortMessage = 'this is a message 🤑' 12 | let shortUnsignedAX25Packet = null 13 | let shortSignedAX25Packet = null 14 | 15 | const longMessage = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz' 16 | let longUnsignedAX25Packet = null 17 | let longSignedAX25Packet = null 18 | 19 | describe('ToAX25Packet()', () => { 20 | it('should construct an AX25 Packet with a short message and no signature', async () => { 21 | shortUnsignedAX25Packet = await Packet.ToAX25Packet('N0CALL', 'CQ', shortMessage) 22 | }) 23 | 24 | it('should construct an AX25 Packet with a short message and a signature', async () => { 25 | const signature = ks.sign(shortMessage, private) 26 | shortSignedAX25Packet = await Packet.ToAX25Packet('N0CALL-1', 'KC3LZO', shortMessage, signature) 27 | }) 28 | 29 | it('should construct an AX25 Packet with a long message and no signature', async () => { 30 | longUnsignedAX25Packet = await Packet.ToAX25Packet('N0CALL', 'KC3LZO-2', longMessage) 31 | }) 32 | 33 | it('should construct an AX25 Packet with a long message and a signature', async () => { 34 | const signature = ks.sign(longMessage, private) 35 | longSignedAX25Packet = await Packet.ToAX25Packet('N0CALL-3', 'KC3LZO-3', longMessage, signature) 36 | }) 37 | 38 | it('should error constructing an AX25 Packet with a signature that is greater than 256 bytes', async () => { 39 | const buff = Buffer.alloc(512) 40 | try { 41 | await Packet.ToAX25Packet('N0CALL', 'CQ', shortMessage, buff) 42 | assert.fail('No error creating packet with signature length 512') 43 | } catch (err) { 44 | assert.equal('signature is larger than 256 bytes', err.message) 45 | } 46 | }) 47 | }) 48 | 49 | describe('FromAX25Packet()', () => { 50 | 51 | describe('should error when creating invalid packets', () => { 52 | 53 | it ('should error if packet contains less than four bytes', async () => { 54 | try { 55 | await Packet.FromAX25Packet(Buffer.from([0x10, 0x11, 0x12])) 56 | assert.fail('Invalid packet must throw an error') 57 | } catch (err) { 58 | assert.equal('InvalidPacket', err.name) 59 | } 60 | }) 61 | 62 | }) 63 | 64 | describe('short packet no signature', () => { 65 | let packet 66 | 67 | it ('should create a packet object from the raw ax25 packet buffer', async () => { 68 | packet = await Packet.FromAX25Packet(shortUnsignedAX25Packet) 69 | }) 70 | 71 | it('should correctly extract the original message', () => { 72 | assert.equal(shortMessage, packet.message) 73 | }) 74 | 75 | it('signature property should be null', () => { 76 | assert.equal(packet.signature, null) 77 | }) 78 | 79 | it('should have a from callsign', () => { 80 | assert.ok(typeof packet.from.callsign === 'string') 81 | }) 82 | 83 | it('should have a to callsign', () => { 84 | assert.ok(typeof packet.to.callsign === 'string') 85 | }) 86 | 87 | it('should have a from ssid', () => { 88 | assert.ok(typeof packet.from.ssid === 'number') 89 | }) 90 | 91 | it('should have a to ssid', () => { 92 | assert.ok(typeof packet.to.ssid === 'number') 93 | }) 94 | 95 | it('header.compressed should be false', () => { 96 | assert.equal(packet.header.compressed, false) 97 | }) 98 | 99 | it('header.signed should be false', () => { 100 | assert.equal(packet.header.signed, false) 101 | }) 102 | 103 | it('header.signatureLength should be null', () => { 104 | assert.equal(packet.header.signatureLength, null) 105 | }) 106 | }) 107 | 108 | describe('short packet with signature', () => { 109 | let packet 110 | 111 | it ('should create a packet object from the raw ax25 packet buffer', async () => { 112 | packet = await Packet.FromAX25Packet(shortSignedAX25Packet) 113 | }) 114 | 115 | it('should correctly extract the original message', () => { 116 | assert.equal(shortMessage, packet.message) 117 | }) 118 | 119 | it('signature property should be a buffer', () => { 120 | assert.ok(packet.signature instanceof Buffer) 121 | }) 122 | 123 | it('the signature should be valid', () => { 124 | assert.ok(ks.verify('N0CALL', shortMessage, packet.signature)) 125 | }) 126 | 127 | it('should have a from callsign', () => { 128 | assert.ok(typeof packet.from.callsign === 'string') 129 | }) 130 | 131 | it('should have a to callsign', () => { 132 | assert.ok(typeof packet.to.callsign === 'string') 133 | }) 134 | 135 | it('should have a from ssid', () => { 136 | assert.ok(typeof packet.from.ssid === 'number') 137 | }) 138 | 139 | it('should have a to ssid', () => { 140 | assert.ok(typeof packet.to.ssid === 'number') 141 | }) 142 | 143 | it('header.compressed should be false', () => { 144 | assert.equal(packet.header.compressed, false) 145 | }) 146 | 147 | it('header.signed should be true', () => { 148 | assert.equal(packet.header.signed, true) 149 | }) 150 | 151 | it('header.signatureLength should be greater than zero', () => { 152 | assert.ok(packet.header.signatureLength > 0) 153 | }) 154 | }) 155 | 156 | describe('long packet no signature', () => { 157 | let packet 158 | 159 | it ('should create a packet object from the raw ax25 packet buffer', async () => { 160 | packet = await Packet.FromAX25Packet(longUnsignedAX25Packet) 161 | }) 162 | 163 | it('should correctly extract the original message', () => { 164 | assert.equal(longMessage, packet.message) 165 | }) 166 | 167 | it('signature property should be null', () => { 168 | assert.equal(packet.signature, null) 169 | }) 170 | 171 | it('should have a from callsign', () => { 172 | assert.ok(typeof packet.from.callsign === 'string') 173 | }) 174 | 175 | it('should have a to callsign', () => { 176 | assert.ok(typeof packet.to.callsign === 'string') 177 | }) 178 | 179 | it('should have a from ssid', () => { 180 | assert.ok(typeof packet.from.ssid === 'number') 181 | }) 182 | 183 | it('should have a to ssid', () => { 184 | assert.ok(typeof packet.to.ssid === 'number') 185 | }) 186 | 187 | it('header.compressed should be true', () => { 188 | assert.equal(packet.header.compressed, true) 189 | }) 190 | 191 | it('header.signed should be false', () => { 192 | assert.equal(packet.header.signed, false) 193 | }) 194 | 195 | it('header.signatureLength should be null', () => { 196 | assert.equal(packet.header.signatureLength, null) 197 | }) 198 | }) 199 | 200 | describe('long packet with signature', () => { 201 | let packet 202 | 203 | it ('should create a packet object from the raw ax25 packet buffer', async () => { 204 | packet = await Packet.FromAX25Packet(longSignedAX25Packet) 205 | }) 206 | 207 | it('should correctly extract the original message', () => { 208 | assert.equal(longMessage, packet.message) 209 | }) 210 | 211 | it('signature property should be a buffer', () => { 212 | assert.ok(packet.signature instanceof Buffer) 213 | }) 214 | 215 | it('the signature should be valid', () => { 216 | assert.ok(ks.verify('N0CALL', longMessage, packet.signature)) 217 | }) 218 | 219 | it('should have a from callsign', () => { 220 | assert.ok(typeof packet.from.callsign === 'string') 221 | }) 222 | 223 | it('should have a to callsign', () => { 224 | assert.ok(typeof packet.to.callsign === 'string') 225 | }) 226 | 227 | it('should have a from ssid', () => { 228 | assert.ok(typeof packet.from.ssid === 'number') 229 | }) 230 | 231 | it('should have a to ssid', () => { 232 | assert.ok(typeof packet.to.ssid === 'number') 233 | }) 234 | 235 | it('header.compressed should be true', () => { 236 | assert.equal(packet.header.compressed, true) 237 | }) 238 | 239 | it('header.signed should be true', () => { 240 | assert.equal(packet.header.signed, true) 241 | }) 242 | 243 | it('header.signatureLength should be greater than zero', () => { 244 | assert.ok(packet.header.signatureLength > 0) 245 | }) 246 | }) 247 | }) 248 | 249 | it('should remove the temporary keystore file', () => { 250 | fs.unlinkSync('tmp-keystore.json') 251 | }) 252 | }) 253 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Chattervox 2 | 3 | [![Travis CI Build Image](https://travis-ci.com/brannondorsey/chattervox.svg?branch=master)](https://travis-ci.com/brannondorsey/chattervox) [![Coverage Status](https://coveralls.io/repos/github/brannondorsey/chattervox/badge.svg?branch=master)](https://coveralls.io/github/brannondorsey/chattervox?branch=master) 4 | 5 | An AX.25 packet radio chat protocol with support for digital signatures and binary compression. Like IRC over radio waves 📡. 6 | 7 | Chattervox implements a minimal [packet radio protocol](#the-protocol) on top of AX.25 that can be used with a terminal node controller (TNC) like [Direwolf](https://github.com/wb2osz/direwolf) to transmit and receive digitally signed messages using audio frequency shift keying modulation (AFSK). In the United States, it's illegal to broadcast encrypted messages on amateur radio frequencies. Chattervox respects this law, while using elliptic curve cryptography and digital signatures to protect against message spoofing. 8 | 9 | With amateur packet radio anyone can pretend to be anyone else. With Chattervox, you can be sure you're chatting with the person you intend to. For more information, check out the [FAQ](FAQ.md) or the discussion about chattervox on [hackernews](https://news.ycombinator.com/item?id=18058031). 10 | 11 | > **UPDATE** (March 6, 2019): Check out [my slides](https://brannon.online/wopr.pdf) from the Chattervox workshop at WOPR Summit. 12 | 13 | > **UPDATE** (February 25, 2019): I've created a collection of example applications and use cases for the Chattervox protocol [here](https://github.com/brannondorsey/chattervox-examples). One example uses Chattervox to access a remote BASH shell on another machine and another shows how you can play Zork I over packet radio. PRs welcome! 14 | 15 | > **UPDATE** (October 11, 2018): We've setup a public key registry at [`chattervox-keys`](https://github.com/brannondorsey/chattervox-keys). Once you've generated your public key you can post it there! 16 | 17 | ![Baofeng UV-5R Linux setup](.images/baofeng.jpg) 18 | 19 | ## Prerequisites 20 | 21 | Chattervox requires a linux computer and a network or serial connection to a TNC to send and receive AX.25 packets. I recommend using [Direwolf](https://github.com/wb2osz/direwolf), a popular software TNC which can be run on the same computer hosting the `chattervox` application. 22 | 23 | You'll also need a radio and a cable to connect the microphone and speaker from the radio to your linux machine. I recommend the following equipment, especially if you're on a budget: 24 | 25 | - $24 Baofeng UV-5R 4-watt radio. This is the absolute best radio you can buy for that price. 26 | - $18 [BTech APRS cable](https://baofengtech.com/aprs-k2-trrs-cable) (3.5mm TRRS to 3.5mm and 2.5mm audio cable, usually for sale on Amazon) 27 | 28 | You can also make the cable yourself if you prefer. Check out [this zine](https://archive.org/details/oreally-packet-radio) for instructions. 29 | 30 | Finally, to operate legally on amateur radio frequencies, you'll need an amateur radio license. 31 | 32 | ### Install Direwolf 33 | 34 | #### Linux 35 | 36 | Installing Direwolf on a Linux machine is easy! Just clone the repo, build the software, and install it on your system. 37 | 38 | ```bash 39 | # clone, build, and install the Direwolf TNC 40 | git clone https://github.com/wb2osz/direwolf 41 | cd direwolf 42 | make 43 | sudo make install 44 | make install-conf 45 | ``` 46 | 47 | #### MacOS 48 | 49 | If you are using MacOS, you can install Direwolf with Homebrew by following the instructions in [this Gist](https://gist.github.com/danc256/9eca3317e5eaea7fb7e642e5f3a1f3f0) (thanks for the edits [@danc256](https://github.com/danc256/)). 50 | 51 | #### Windows 52 | 53 | Windows isn't currently supported, but will be soon! 54 | 55 | ## Download 56 | 57 | Binary downloads are available for Linux x64 and x86 architectures on the [releases page](https://github.com/brannondorsey/chattervox/releases). 58 | 59 | If you have `npm`, that is the preferred method of install as it allows for the easiest upgrade to the latest version. If you prefer to "build" it from Typescript source and run it as a Node.js app, you can do that as well. 60 | 61 | ### NPM 62 | 63 | ```bash 64 | npm install --cli -g chattervox@latest 65 | ``` 66 | 67 | Installing a node package globally may require `sudo`. If you get a permission denied error, try running the install command again with `sudo npm ...`. 68 | 69 | ### Source 70 | 71 | ```bash 72 | # clone the repo 73 | git clone https://github.com/brannondorsey/chattervox 74 | cd chattervox 75 | 76 | # download dependencies 77 | npm install 78 | 79 | # transpile the src/*.ts typescript files to build/*.js 80 | npm run build 81 | 82 | # run chattervox from source to opening the chat room 83 | node build/main.js chat 84 | ``` 85 | 86 | ### Binary Downloads 87 | 88 | [Binary downloads](https://github.com/brannondorsey/chattervox/releases) are packaged via [Pkg](https://github.com/zeit/pkg). Chattervox uses a native Node.js addon for serial port communication but Pkg [does not yet support](https://github.com/zeit/pkg#native-addons) bundling `.node` bindings in their binaries. Therefore, the `serialport.node` file that comes with the download must live in the same folder as the `chattervox` binary. If you want to install chattervox globally on your machine you can maintain this relationship by placing `chattervox` in your PATH using a symlink, or copying both `chattervox` and `serialport.node` to `/usr/local/bin` or wherever your OS looks for programs. 89 | 90 | ## Usage 91 | 92 | ```bash 93 | # open the chat room 94 | chattervox chat 95 | 96 | # send a packet from the command-line 97 | chattervox send "this is a chattervox packet sent from the command-line." 98 | 99 | # receive *all* packets and print them to stdout 100 | chattervox receive --allow-all 101 | 102 | # generate a new public/private key pair, and use it as your default signing key 103 | chattervox genkey --make-signing 104 | 105 | # add a friend's public key to your keyring, so that chattervox can verify their messages 106 | chattervox addkey KC3LZO 0489a1d94d700d6e45508d12a4eb9be93386b5b30feb2b4aa07836398781e3d444e04b54a6e01cf752e54ef423770c00a6 107 | 108 | # remove a friend's public key if it has become compromised 109 | chattervox removekey KC3LZO 0489a1d94d700d6e45508d12a4eb9be93386b5b30feb2b4aa07836398781e3d444e04b54a6e01cf752e54ef423770c00a6 110 | 111 | # print all keys in your keyring 112 | chattervox showkey 113 | ``` 114 | 115 | ``` 116 | usage: chattervox [-h] [-v] [--config CONFIG] 117 | {chat,send,receive,showkey,addkey,removekey,genkey} ... 118 | 119 | An AX.25 packet radio chat protocol with support for digital signatures and 120 | binary compression. Like IRC over radio waves 📡〰. 121 | 122 | Optional arguments: 123 | -h, --help Show this help message and exit. 124 | -v, --version Show program's version number and exit. 125 | --config CONFIG, -c CONFIG 126 | Path to config file (default: /home/braxxox/. 127 | chattervox/config.json) 128 | 129 | subcommands: 130 | {chat,send,receive,showkey,addkey,removekey,genkey} 131 | ``` 132 | 133 | ## The Protocol 134 | 135 | The chattervox packet is primitive and straightforward. It contains a simple header, an optional ECDSA digital signature, and a message payload that can be in plaintext or compressed. As of packet version 1, the protocol is connectionless. There is only one type of packet and there is no mechanism for delivery confirmation (think of it like UDP). It is expected to be transported via AX.25 Unnumbered Information (UI) packets, which the chattervox program relies on for sender and recipient information, as no such fields exists in the packet itself to conserve space. 136 | 137 | The protocol may be amended in the future to add new features, however, its simplicity should not be seen as a weakness. The goal of chattervox is singular: **Add cryptographic verifiability to text-based radio communication.** 138 | 139 | For proposed changes to the protocol [view the open RFCs](https://github.com/brannondorsey/chattervox/issues?q=is%3Aissue+is%3Aopen+label%3ARFC). 140 | 141 | ### Chattervox Protocol v1 Packet 142 | 143 | 144 | | Byte Offset | # of Bits | Name | Value | Description 145 | | ----------------- | ------------- | ----------------------------------- | ------------------ | ----------- 146 | | 0x0000 | 16 | Magic Header | 0x7a39 | A constant two-byte value used to identify chattervox packets. 147 | | 0x0002 | 8 | Version Byte | Number | A protocol version number between 1-255. 148 | | 0x0003 | 6 | Unused Flag Bits | Null | Reserved for future use. 149 | | 0x0003 | 1 | Digital Signature Flag | Bit | A value of 1 indicates that the message contains a ECDSA digital signature. 150 | | 0x0003 | 1 | Compression Flag | Bit | A value of 1 indicates that the message payload is compressed. 151 | | [0x0004] | [8] | [Signature Length] | Number | The length in bytes of the digital signature. This field is only included if the Digital Signature Flag is set. 152 | | [0x0004 or 0x0005]| [0-2048] | [Digital Signature] | Bytes | The ECDSA digital signature created using a SHA256 hash of the message contents and the sender's private key. 153 | | 0x0004-0x104 | 0-∞ | Message | Bytes | The packet's UTF-8 message payload. If the Compression Flag is set the contents of this buffer is a [raw DEFLATE buffer](https://nodejs.org/api/zlib.html#zlib_zlib_deflateraw_buffer_options_callback) containing the UTF-8 message. 154 | 155 | [] indicates an optional field. 156 | 157 | ### TypeScript chattervox client 158 | 159 | This repository serves as the first implementation of the protocol. The `chattervox` command-line tool acts as a client to send and receive chattervox packets in combination with a TNC. This implementation creates a new ECDSA keypair the first time it's run and includes a digital signature for each message (so long as there remains a `signingKey` in `~/.chattervox/config.json`). Each message is temporarily compressed by the client before it's sent in an attempt to measure the efficiency of the DEFLATE compression algorithm. If the compressed version is smaller than the uncompressed version, the compressed buffer is used as the message payload and the compression bit is set in the chattervox packet. If the plaintext version is smaller, no compression is used and the original message text is used as the payload. 160 | 161 | ## Beta Software 162 | 163 | Please understand that this software is in **beta** and I ask for your patience until development stabilizes. While I'm very excited to see that interest in the project is high, It's quite unexpected and I have spent very little time testing the software (aside from automated tests). If you have a problem, [please submit a detailed issue](https://github.com/brannondorsey/chattervox/issues) and I'll have a look. I'll be writing a tutorial explaining how to get up and running with chattervox very soon. 164 | 165 | The protocol is subject to change, and there are several [RFCs](https://github.com/brannondorsey/chattervox/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3ARFC+) that indicate the direction it may take in the near future. Currently, there is no protection from replay attacks, so that's something we hope to fix soon! 166 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import { ArgumentParser, SubParser } from 'argparse' 4 | import * as fs from 'fs' 5 | import * as path from 'path' 6 | import * as config from './config' 7 | import { Keystore, Key } from './Keystore' 8 | import * as chat from './subcommands/chat' 9 | import * as addkey from './subcommands/addkey' 10 | import * as removekey from './subcommands/removekey' 11 | import * as showkey from './subcommands/showkey' 12 | import * as genkey from './subcommands/genkey' 13 | import * as send from './subcommands/send' 14 | import * as receive from './subcommands/receive' 15 | import * as exec from './subcommands/exec' 16 | import * as tty from './subcommands/tty' 17 | import { interactiveInit } from './ui/init' 18 | import { isCallsign, isCallsignSSID, isBrokenPipeError } from './utils' 19 | 20 | function parseArgs(): any { 21 | 22 | const pkgBuff = fs.readFileSync(path.resolve(__dirname, '..', 'package.json')) 23 | const pkgJSON: any = JSON.parse(pkgBuff.toString('utf8')) 24 | 25 | const parser = new ArgumentParser({ 26 | prog: pkgJSON.name, 27 | version: pkgJSON.version, 28 | description: pkgJSON.description 29 | }) 30 | 31 | parser.addArgument(['--config', '-c'], { 32 | help: `Path to config file (default: ${config.defaultConfigPath})`, 33 | defaultValue: config.defaultConfigPath 34 | }) 35 | 36 | const subs: SubParser = parser.addSubparsers({ 37 | title: 'subcommands', 38 | dest: 'subcommand' 39 | }) 40 | 41 | const chat: ArgumentParser = subs.addParser('chat', { 42 | addHelp: true, 43 | description: 'Enter the chat room.' 44 | }) 45 | 46 | chat; // intentionally unused 47 | 48 | const send: ArgumentParser = subs.addParser('send', { 49 | addHelp: true, 50 | description: 'Send chattervox packets.' 51 | }) 52 | 53 | send.addArgument(['--to', '-t'], { 54 | type: 'string', 55 | help: 'The recipient\'s callsign, callsign-ssid pair, or chatroom name (default: "CQ").', 56 | defaultValue: 'CQ', 57 | required: false 58 | }) 59 | 60 | send.addArgument(['--dont-sign', '-d'], { 61 | action: 'storeTrue', 62 | dest: 'dontSign', 63 | help: 'Don\'t sign messages.', 64 | required: false 65 | }) 66 | 67 | send.addArgument('message', { 68 | type: 'string', 69 | help: 'A UTF-8 message to be sent.', 70 | nargs: '?', 71 | required: false 72 | }) 73 | 74 | const receive: ArgumentParser = subs.addParser('receive', { 75 | addHelp: true, 76 | description: 'Write chattervox packets to stdout.' 77 | }) 78 | 79 | receive.addArgument(['--allow-unsigned', '-u'], { 80 | action: 'storeTrue', 81 | dest: 'allowUnsigned', 82 | help: 'Receive unsigned messages.', 83 | }) 84 | 85 | receive.addArgument(['--allow-untrusted', '-e'], { 86 | action: 'storeTrue', 87 | dest: 'allowUntrusted', 88 | help: 'Receive messages signed by senders not in keyring.', 89 | }) 90 | 91 | receive.addArgument(['--allow-invalid', '-i'], { 92 | action: 'storeTrue', 93 | dest: 'allowInvalid', 94 | help: 'Receive messages with invalid signatures.', 95 | }) 96 | 97 | receive.addArgument(['--all-recipients', '-g'], { 98 | action: 'storeTrue', 99 | dest: 'allRecipients', 100 | help: 'Receive messages to all callsigns and chat rooms.', 101 | }) 102 | 103 | receive.addArgument(['--allow-all', '-a'], { 104 | action: 'storeTrue', 105 | dest: 'allowAll', 106 | help: 'Receive all messages, independent of signatures and destinations.', 107 | }) 108 | 109 | receive.addArgument(['--raw', '-r'], { 110 | action: 'storeTrue', 111 | dest: 'raw', 112 | help: 'Print raw ax25 packets instead of parsed chattervox messages.', 113 | }) 114 | 115 | receive.addArgument('--to', { 116 | type: 'string', 117 | help: 'The recipient\'s callsign, callsign-ssid pair, or chatroom name (default: "CQ").', 118 | defaultValue: 'CQ', 119 | required: false 120 | }) 121 | 122 | receive.addArgument(['--verbose', '-v'], { 123 | action: 'storeTrue', 124 | help: 'Print verbose output from any chattervox packet received to stderr.', 125 | }) 126 | 127 | const showKey: ArgumentParser = subs.addParser('showkey', { 128 | addHelp: true, 129 | description: 'List keys.' 130 | }) 131 | 132 | showKey.addArgument('callsign', { type: 'string', nargs: '?' }) 133 | 134 | const addKey: ArgumentParser = subs.addParser('addkey', { 135 | addHelp: true, 136 | description: 'Add a new public key to the keystore associated with a callsign.' 137 | }) 138 | 139 | addKey.addArgument('callsign', { type: 'string' }) 140 | addKey.addArgument('publickey', { type: 'string' }) 141 | 142 | const removeKey: ArgumentParser = subs.addParser('removekey', { 143 | addHelp: true, 144 | description: 'Remove a public key from the keystore.' 145 | }) 146 | 147 | removeKey.addArgument('callsign', { type: 'string' }) 148 | removeKey.addArgument('publickey', { type: 'string' }) 149 | 150 | const genKey: ArgumentParser = subs.addParser('genkey', { 151 | addHelp: true, 152 | description: 'Generate a new keypair for your callsign.' 153 | }) 154 | 155 | genKey.addArgument('--make-signing', { 156 | action: 'storeTrue', 157 | dest: 'makeSigning', 158 | help: 'Make the generated key your default signing key.' 159 | }) 160 | 161 | const exec: ArgumentParser = subs.addParser('exec', { 162 | addHelp: true, 163 | description: 'Execute a command using chattervox as the stdin and stdout interface.' 164 | }) 165 | 166 | exec.addArgument(['--delay', '-s'], { 167 | type: 'int', 168 | help: 'Milliseconds after receiving stdin to wait before transmitting stdout (default: 3000).', 169 | defaultValue: 3000, 170 | required: false 171 | }) 172 | 173 | exec.addArgument(['--to', '-t'], { 174 | type: 'string', 175 | help: 'The recipient\'s callsign, callsign-ssid pair, or chatroom name (default: "CQ").', 176 | defaultValue: 'CQ', 177 | required: false 178 | }) 179 | 180 | exec.addArgument(['--dont-sign', '-d'], { 181 | action: 'storeTrue', 182 | dest: 'dontSign', 183 | help: 'Don\'t sign messages.', 184 | required: false 185 | }) 186 | 187 | exec.addArgument(['--stderr', '-f'], { 188 | action: 'storeTrue', 189 | help: 'Also transmit stderr.', 190 | defaultValue: false, 191 | required: false 192 | }) 193 | 194 | exec.addArgument(['--allow-unsigned', '-u'], { 195 | action: 'storeTrue', 196 | dest: 'allowUnsigned', 197 | help: 'Receive unsigned messages.', 198 | }) 199 | 200 | exec.addArgument(['--allow-untrusted', '-e'], { 201 | action: 'storeTrue', 202 | dest: 'allowUntrusted', 203 | help: 'Receive messages signed by senders not in keyring.', 204 | }) 205 | 206 | exec.addArgument(['--allow-invalid', '-i'], { 207 | action: 'storeTrue', 208 | dest: 'allowInvalid', 209 | help: 'Receive messages with invalid signatures.', 210 | }) 211 | 212 | exec.addArgument(['--all-recipients', '-g'], { 213 | action: 'storeTrue', 214 | dest: 'allRecipients', 215 | help: 'Receive messages to all callsigns and chat rooms.', 216 | }) 217 | 218 | exec.addArgument(['--allow-all', '-a'], { 219 | action: 'storeTrue', 220 | dest: 'allowAll', 221 | help: 'Receive all messages, independent of signatures and destinations.', 222 | }) 223 | 224 | exec.addArgument('command', { 225 | type: 'string', 226 | help: 'A command to be run' 227 | }) 228 | 229 | const tty: ArgumentParser = subs.addParser('tty', { 230 | addHelp: true, 231 | description: 'A dumb tty interface. Sends what\'s typed, prints what\'s received.' 232 | }) 233 | 234 | tty.addArgument(['--to', '-t'], { 235 | type: 'string', 236 | help: 'The recipient\'s callsign, callsign-ssid pair, or chatroom name (default: "CQ").', 237 | defaultValue: 'CQ', 238 | required: false 239 | }) 240 | 241 | tty.addArgument(['--dont-sign', '-d'], { 242 | action: 'storeTrue', 243 | dest: 'dontSign', 244 | help: 'Don\'t sign messages.', 245 | required: false 246 | }) 247 | 248 | tty.addArgument(['--allow-unsigned', '-u'], { 249 | action: 'storeTrue', 250 | dest: 'allowUnsigned', 251 | help: 'Receive unsigned messages.', 252 | }) 253 | 254 | tty.addArgument(['--allow-untrusted', '-e'], { 255 | action: 'storeTrue', 256 | dest: 'allowUntrusted', 257 | help: 'Receive messages signed by senders not in keyring.', 258 | }) 259 | 260 | tty.addArgument(['--allow-invalid', '-i'], { 261 | action: 'storeTrue', 262 | dest: 'allowInvalid', 263 | help: 'Receive messages with invalid signatures.', 264 | }) 265 | 266 | tty.addArgument(['--all-recipients', '-g'], { 267 | action: 'storeTrue', 268 | dest: 'allRecipients', 269 | help: 'Receive messages to all callsigns and chat rooms.', 270 | }) 271 | 272 | tty.addArgument(['--allow-all', '-a'], { 273 | action: 'storeTrue', 274 | dest: 'allowAll', 275 | help: 'Receive all messages, independent of signatures and destinations.', 276 | }) 277 | 278 | 279 | return parser.parseArgs() 280 | } 281 | 282 | function validateArgs(args: any): void { 283 | if (args.callsign != null && !isCallsign(args.callsign)) { 284 | console.error(`${args.callsign} is not a valid callsign.`) 285 | if (isCallsignSSID(args.callsign)) { 286 | console.error(`callsign should not include an SSID for key management subcommands.`) 287 | } 288 | process.exit(1) 289 | } 290 | 291 | if (args.to != null && args.to !== 'CQ' && !(isCallsign(args.to) || isCallsignSSID(args.to))) { 292 | console.error('--to must be a callsign, callsign-ssid pair, or chatroom name with less than 7 alphanumeric characters.') 293 | process.exit(1) 294 | } 295 | } 296 | 297 | // not sure if we should add this here... 298 | // function validateKeystoreFile(conf: config.Config): void { 299 | 300 | // if (!fs.existsSync(conf.keystoreFile)) { 301 | // console.error(`No keystoreFile exists at location "${conf.keystoreFile}".`) 302 | // process.exit(1) 303 | // } else { 304 | // try { 305 | // JSON.parse(fs.readFileSync(conf.keystoreFile).toString('utf8')) 306 | // } catch (err) { 307 | // console.error(`Error loading keystoreFile file from "${conf.keystoreFile}".`) 308 | // console.error(err.message) 309 | // process.exit(1) 310 | // } 311 | // } 312 | // } 313 | 314 | function validateSigningKeyExists(conf: config.Config, ks: Keystore): void { 315 | // if there is a signing in the config but it doesn't exist in the keystore 316 | if (conf.signingKey != null) { 317 | const signing = ks.getKeyPairs(conf.callsign).filter((key: Key) => { 318 | return key.public === conf.signingKey 319 | }) 320 | 321 | if (signing.length < 1) { 322 | console.error(`Default signing key has no matching private key found in the keystore.`) 323 | process.exit(1) 324 | } 325 | } 326 | } 327 | 328 | async function cleanup(): Promise { 329 | return await exec.cleanup() 330 | } 331 | 332 | function onSignal(): void { 333 | cleanup() 334 | .then(() => process.exit(0)) 335 | .catch(err => { 336 | console.error(err) 337 | process.exit(1) 338 | }) 339 | } 340 | 341 | async function main() { 342 | 343 | process.on('SIGINT', onSignal) // catch ctrl-c 344 | process.on('SIGTERM', onSignal) // catch kill 345 | 346 | const args = parseArgs() 347 | validateArgs(args) 348 | 349 | // initialize a new config 350 | if (!config.exists(args.config)) { 351 | // if the default config doesn't exist, let's run the interactive init 352 | if (args.config === config.defaultConfigPath) { 353 | await interactiveInit() 354 | } else { 355 | console.error(`No config file exists at "${args.config}".`) 356 | process.exit(1) 357 | } 358 | } 359 | 360 | let conf: config.Config = null 361 | try { 362 | conf = config.load(args.config) 363 | } catch(err) { 364 | console.error(`Error loading config file from "${args.config}".`) 365 | console.error(err.message) 366 | process.exit(1) 367 | } 368 | 369 | // validate that keystore file exists 370 | // validateKeystoreFile(conf) 371 | const ks: Keystore = new Keystore(conf.keystoreFile) 372 | 373 | // if this subcommand is any of the commands that signs something 374 | if (['chat', 'send', 'receive'].includes(args.subcommand)) { 375 | validateSigningKeyExists(conf, ks) 376 | } 377 | 378 | let code = null 379 | 380 | try { 381 | switch (args.subcommand) { 382 | case 'chat': code = await chat.main(args, conf, ks); break 383 | case 'send': code = await send.main(args, conf, ks); break 384 | case 'receive': code = await receive.main(args, conf, ks); break 385 | case 'showkey': code = await showkey.main(args, conf, ks); break 386 | case 'addkey': code = await addkey.main(args, conf, ks); break 387 | case 'removekey': code = await removekey.main(args, conf, ks); break 388 | case 'genkey': code = await genkey.main(args, conf, ks); break 389 | case 'exec': code = await exec.main(args, conf, ks); break 390 | case 'tty': code = await tty.main(args, conf, ks); break 391 | } 392 | } catch (err) { 393 | if (isBrokenPipeError(err)) { 394 | console.error(`\nThe connection to KISS TNC ${conf.kissPort} has been closed with a broken pipe.`) 395 | code = 1 396 | } else throw err 397 | } 398 | 399 | process.exit(code) 400 | } 401 | 402 | main() 403 | .catch(async (err) => { 404 | console.error(err) 405 | await cleanup() 406 | process.exit(1) 407 | }) 408 | -------------------------------------------------------------------------------- /GPLv3.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------