Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/cli-info-escape-terminal-controls.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'nostream': patch
---

fix(cli): show control characters in `nostream info` output as escapes

`nostream info` printed the relay name, URL and other settings values as they are. These can be changed through the admin settings, so a value containing a newline or terminal escape sequence could add forged lines to the output or send commands to the operator's terminal, such as replacing the clipboard where the terminal allows it. The text output now shows control characters as visible escapes (for example `\x0a`). `nostream info --json` is unchanged.
20 changes: 12 additions & 8 deletions src/cli/commands/info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Client } from 'pg'
import packageJson from '../../../package.json'
import { loadMergedSettings } from '../utils/config'
import { tryGetRelayNip43Pubkey } from '../../utils/nip43'
import { logError, logInfo } from '../utils/output'
import { escapeForTerminal, logError, logInfo } from '../utils/output'
import { getOnionKeyPath, getTorHostnamePath } from '../utils/bootstrap'
import { getProjectPath } from '../utils/paths'
import { runCommandWithOutput } from '../utils/process'
Expand Down Expand Up @@ -161,7 +161,7 @@ export const runInfo = async (options: InfoOptions): Promise<number> => {
return 0
}

logInfo(payload.tor.hostname)
logInfo(escapeForTerminal(payload.tor.hostname))
return 0
}

Expand Down Expand Up @@ -244,12 +244,16 @@ export const runInfo = async (options: InfoOptions): Promise<number> => {
}

logInfo(`Nostream v${payload.version}`)
logInfo(`Relay: ${payload.relay.name ?? 'n/a'} (${payload.relay.url ?? 'n/a'})`)
logInfo(`Pubkey: ${payload.relay.pubkey ?? 'n/a'}`)
logInfo(`Signing pubkey (NIP-11 self): ${payload.relay.signingPubkey ?? 'unavailable (SECRET not set)'}`)
logInfo(`Payments: ${payload.relay.paymentsEnabled ? `enabled (${payload.relay.paymentProcessor})` : 'disabled'}`)
logInfo(`Tor hostname: ${payload.tor.hostname ?? 'not found'}`)
logInfo(`Onion key path: ${payload.tor.onionPrivateKeyPath}`)
const text = (value: unknown, fallback: string): string => escapeForTerminal(value ?? fallback)

logInfo(`Relay: ${text(payload.relay.name, 'n/a')} (${text(payload.relay.url, 'n/a')})`)
logInfo(`Pubkey: ${text(payload.relay.pubkey, 'n/a')}`)
logInfo(`Signing pubkey (NIP-11 self): ${text(payload.relay.signingPubkey, 'unavailable (SECRET not set)')}`)
logInfo(
`Payments: ${payload.relay.paymentsEnabled ? `enabled (${text(payload.relay.paymentProcessor, 'n/a')})` : 'disabled'}`,
)
logInfo(`Tor hostname: ${text(payload.tor.hostname, 'not found')}`)
logInfo(`Onion key path: ${escapeForTerminal(payload.tor.onionPrivateKeyPath)}`)
logInfo(`Events: ${payload.runtime.eventCount ?? 'unavailable'}`)
logInfo(`Uptime: ${formatUptime(payload.runtime.uptimeSeconds)}`)

Expand Down
15 changes: 15 additions & 0 deletions src/cli/utils/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,18 @@ export const logError = (message: string): void => {
}

export const title = (label: string): string => bold(label)

// C0 controls (including newline, carriage return and ESC), DEL and the C1 controls, which some terminals treat as
// escape introducers.
const TERMINAL_CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/g

/**
* Makes a value that someone else can set, such as the relay name in the settings, safe to print on a terminal:
* control characters are shown as visible escapes instead of being interpreted, so that the value cannot start new
* lines, forge other output or send escape sequences. Not for machine-readable output, which is serialized instead.
*/
export const escapeForTerminal = (value: unknown): string =>
String(value).replace(
TERMINAL_CONTROL_CHARACTERS,
(character) => `\\x${character.charCodeAt(0).toString(16).padStart(2, '0')}`,
)
50 changes: 48 additions & 2 deletions test/unit/cli/info.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@ import path from 'path'
import sinon from 'sinon'

const infoCommand = require('../../../dist/src/cli/commands/info.js')
const configUtils = require('../../../dist/src/cli/utils/config.js')
const settingsConfig = require('../../../dist/src/utils/settings-config.js')
const processUtils = require('../../../dist/src/cli/utils/process.js')

describe('runInfo', () => {
const keysFile = path.join(process.cwd(), '.nostr', 'i2p', 'data', 'nostream.dat')

let stdout = ''
let stderr = ''
let settings: sinon.SinonStub

beforeEach(() => {
sinon.stub(configUtils, 'loadMergedSettings').returns({})
settings = sinon.stub(settingsConfig, 'loadMergedSettings').returns({})
sinon.stub(process.stdout, 'write').callsFake(((chunk: string | Uint8Array) => {
stdout += String(chunk)
return true
Expand Down Expand Up @@ -127,4 +128,49 @@ describe('runInfo', () => {
expect(stdout).to.include('To find your nostream .b32.i2p address, use one of these methods:')
expect(stderr).to.equal('')
})

describe('relay metadata that someone else can set', () => {
const hostileName = 'Nice relay\nPayments: disabled\r\u001b]52;c;ZXZpbA==\u0007\u009b31m'

beforeEach(() => {
settings.returns({
info: { name: hostileName, relay_url: 'wss://relay.example/\u001b[2J' },
})
sinon.stub(fs, 'existsSync').returns(false)
sinon
.stub(processUtils, 'runCommandWithOutput')
.resolves({ ok: false, reason: 'not-found', stdout: '', stderr: '' })
})

it('shows control characters in the relay name and url as visible escapes', async () => {
const code = await infoCommand.runInfo({})

expect(code).to.equal(0)
expect(stdout).to.include(
'Relay: Nice relay\\x0aPayments: disabled\\x0d\\x1b]52;c;ZXZpbA==\\x07\\x9b31m (wss://relay.example/\\x1b[2J)',
)
})

it('cannot add lines or send escape sequences to the terminal', async () => {
await infoCommand.runInfo({})

expect(stdout).to.not.match(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/)
expect(stdout.split('\n').filter((line) => line.startsWith('Payments:'))).to.have.length(1)
expect(stdout.split('\n').filter((line) => line.startsWith('Relay:'))).to.have.length(1)
})

it('leaves ordinary names, including non-ASCII ones, as they are', async () => {
settings.returns({ info: { name: 'Café relay 🚀', relay_url: 'wss://relay.example' } })

await infoCommand.runInfo({})

expect(stdout).to.include('Relay: Café relay 🚀 (wss://relay.example)')
})

it('keeps the JSON output exact', async () => {
await infoCommand.runInfo({ json: true })

expect(JSON.parse(stdout).relay.name).to.equal(hostileName)
})
})
})
Loading