chore(lint): replace ESLint with Oxlint and clear anti-slop findings

This commit is contained in:
Chris Scott committed 2026-11-13 01:13:34 -05:00
1 parent c6c13335e5
commit b625acfc0c
1083 files changed
+67089 -80136

No files matched your search

+178 -276
View File
@@ -1,290 +1,192 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import type { Database } from 'bun:sqlite'
import * as crypto from 'crypto'
import * as fs from 'fs/promises'
import * as path from 'path'
import * as fs from 'node:fs/promises'
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import type { TempWorkspace } from '../helpers/test-env'
import { applyTestEnv, createTempWorkspace } from '../helpers/test-env'
import { createTestDatabase } from '../helpers/test-database'
import { SSHHostKeyHandler } from '../../src/ipc/sshHostKeyHandler'
vi.mock('@opencode-manager/shared/config/env', () => ({
ENV: {
AUTH: {
SECRET: 'test-secret-for-encryption'
},
OPENCODE: {
PORT: 5551
},
SERVER: {
PORT: 5003
}
},
getWorkspacePath: vi.fn(() => '/tmp/test-workspace'),
getReposPath: vi.fn(() => '/tmp/test-repos'),
}))
const SSH_KEYSCAN_SCRIPT = `#!/usr/bin/env node
const fs = require('node:fs')
const keyFile = process.env.SSH_KEYSCAN_KEY_FILE
if (!fs.existsSync(keyFile)) {
process.stderr.write('ssh-keyscan: no keys found\\n')
process.exit(1)
}
process.stdout.write(fs.readFileSync(keyFile, 'utf8'))
`
let testWorkspacePath: string = '/tmp/test-workspace'
const RSA_KEY = 'github.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
const ED25519_KEY = 'github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test@example.com'
const ECDSA_KEY = 'github.com ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEM/test@test.com'
const mockPrepare = vi.fn()
const mockExec = vi.fn()
const mockDatabase = {
prepare: mockPrepare,
exec: mockExec,
} as unknown as Database
let workspace: TempWorkspace
let db: Database
let handler: SSHHostKeyHandler
let knownHostsPath: string
let keyScanKeyFile: string
let restoreEnv: () => void
vi.mock('bun:sqlite', () => ({
Database: vi.fn(() => mockDatabase),
}))
function insertTrustedHost(host: string, keyType: string, publicKey: string): void {
const now = Date.now()
db.prepare(
'INSERT INTO trusted_ssh_hosts (host, key_type, public_key, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
).run(host, keyType, publicKey, now, now)
}
import { SSHHostKeyHandler, createSSHHostKeyHandler } from '../../src/ipc/sshHostKeyHandler'
function keyScanReturns(publicKey: string): void {
writeFileSync(keyScanKeyFile, `${publicKey}\n`, 'utf-8')
}
describe('SSHHostKeyHandler', () => {
let handler: SSHHostKeyHandler
let knownHostsPath: string
beforeEach(async () => {
workspace = createTempWorkspace('ocm-ssh-hostkey-')
const binDir = join(workspace.path, 'bin')
mkdirSync(binDir, { recursive: true })
writeFileSync(join(binDir, 'ssh-keyscan'), SSH_KEYSCAN_SCRIPT, { mode: 0o755 })
keyScanKeyFile = join(workspace.path, 'keyscan-output')
restoreEnv = applyTestEnv({ PATH: `${binDir}:${process.env.PATH ?? ''}`, SSH_KEYSCAN_KEY_FILE: keyScanKeyFile })
beforeEach(async () => {
vi.clearAllMocks()
const uniqueId = crypto.randomUUID()
testWorkspacePath = `/tmp/test-workspace-${uniqueId}`
mockPrepare.mockReturnValue({
run: vi.fn(),
get: vi.fn().mockReturnValue(null),
all: vi.fn().mockReturnValue([]),
})
const configDir = `${testWorkspacePath}/config`
await fs.mkdir(configDir, { recursive: true })
const knownHostsFile = path.join(configDir, 'known_hosts')
await fs.writeFile(knownHostsFile, '', { mode: 0o600 })
handler = createSSHHostKeyHandler(mockDatabase, 5000)
await handler.initialize()
knownHostsPath = handler.getKnownHostsPath()
db = createTestDatabase()
knownHostsPath = join(workspace.path, 'config', 'known_hosts')
await fs.mkdir(join(workspace.path, 'config'), { recursive: true })
await fs.writeFile(knownHostsPath, '', { mode: 0o600 })
handler = new SSHHostKeyHandler(db, 5_000)
await handler.initialize()
})
afterEach(async () => {
try {
db.close()
} catch {}
restoreEnv()
workspace.restore()
})
describe('SSHHostKeyHandler initialization', () => {
it('points known_hosts at the workspace config directory', () => {
expect(handler.getKnownHostsPath()).toBe(knownHostsPath)
expect(handler.getEnv()).toEqual({ KNOWN_HOSTS_PATH: knownHostsPath })
})
afterEach(async () => {
vi.clearAllMocks()
await fs.rm(testWorkspacePath, { recursive: true, force: true }).catch(() => {})
})
it('loads every trusted host key from the database into known_hosts', async () => {
insertTrustedHost('github.com', 'ssh-rsa', RSA_KEY)
insertTrustedHost('gitlab.com:2222', 'ssh-ed25519', ED25519_KEY)
describe('Public Key Retrieval', () => {
it('should store public key instead of fingerprint', async () => {
const host = 'test.example.com'
const publicKey = `${host} ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test@example.com`
await handler['addToKnownHosts'](host, publicKey)
const content = await fs.readFile(knownHostsPath, 'utf-8')
expect(content).toContain(publicKey)
expect(content).not.toContain('SHA256:')
})
const reloaded = new SSHHostKeyHandler(db, 5_000)
await reloaded.initialize()
it('should store public key in database', () => {
const host = 'test.example.com'
const publicKey = `${host} ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test@example.com`
const mockRun = vi.fn()
mockPrepare.mockReturnValue({ run: mockRun })
handler['saveTrustedHost'](host, publicKey)
expect(mockPrepare).toHaveBeenCalled()
expect(mockRun).toHaveBeenCalled()
})
})
describe('Host:Port Handling', () => {
it('should handle hosts with non-standard ports', async () => {
const host = 'github.com:2222'
const publicKey = `[github.com]:2222 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host`
await handler['addToKnownHosts'](host, publicKey)
const content = await fs.readFile(knownHostsPath, 'utf-8')
expect(content).toContain('[github.com]:2222')
})
it('should handle hosts with standard port 22', async () => {
const host = 'github.com'
const publicKey = `${host} ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host`
await handler['addToKnownHosts'](host, publicKey)
const content = await fs.readFile(knownHostsPath, 'utf-8')
expect(content).toContain(`${host} ssh-rsa`)
expect(content).not.toContain(':22')
})
})
describe('Load from Database', () => {
it('should load public keys from database to known_hosts', async () => {
const host1 = 'github.com'
const host2 = 'gitlab.com:2222'
const publicKey1 = `${host1} ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host`
const publicKey2 = `[gitlab.com]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test@example.com`
mockPrepare.mockReturnValue({
all: vi.fn().mockReturnValue([
{ host: host1, public_key: publicKey1 },
{ host: host2, public_key: publicKey2 },
]),
})
await handler['loadFromDatabaseToKnownHosts']()
const content = await fs.readFile(knownHostsPath, 'utf-8')
expect(content).toContain(publicKey1)
expect(content).toContain(publicKey2)
})
})
describe('SSH Key Format Support', () => {
const keyFormats = [
{
type: 'RSA public',
key: 'github.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
},
{
type: 'ED25519 public',
key: 'github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test@example.com'
},
{
type: 'ECDSA public',
key: 'github.com ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEM/test@test.com'
}
]
keyFormats.forEach(({ type, key }) => {
it(`should support ${type}`, async () => {
await handler['addToKnownHosts']('testhost', key)
const content = await fs.readFile(knownHostsPath, 'utf-8')
const keyType = key.split(' ')[1]
if (keyType) {
expect(content).toContain(keyType)
}
})
})
})
describe('Known Hosts File Format', () => {
it('should write proper known_hosts format', async () => {
const host = 'github.com'
const keyType = 'ssh-rsa'
const keyData = 'AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw=='
const publicKey = `${host} ${keyType} ${keyData}`
await handler['addToKnownHosts'](host, publicKey)
const content = await fs.readFile(knownHostsPath, 'utf-8')
const lines = content.trim().split('\n')
expect(lines.length).toBe(1)
const firstLine = lines[0]
if (firstLine) {
const parts = firstLine.split(' ')
expect(parts.length).toBeGreaterThanOrEqual(3)
expect(parts[0]).toBe(host)
expect(parts[1]).toBe(keyType)
expect(parts[2]).toBe(keyData)
}
})
it('should handle bracketed host notation for non-standard ports', async () => {
const host = 'github.com:2222'
const publicKey = '[github.com]:2222 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
await handler['addToKnownHosts'](host, publicKey)
const content = await fs.readFile(knownHostsPath, 'utf-8')
expect(content).toContain('[github.com]:2222')
})
})
describe('getEnv', () => {
it('should return known hosts path in environment', () => {
const env = handler.getEnv()
expect(env.KNOWN_HOSTS_PATH).toBe(knownHostsPath)
})
})
describe('verifyHostKeyBeforeOperation', () => {
it('should return true immediately for trusted host in DB', async () => {
mockPrepare.mockReturnValue({
run: vi.fn(),
get: vi.fn().mockReturnValue({ key_type: 'ssh-rsa', public_key: 'github.com ssh-rsa AAAAB...' }),
all: vi.fn().mockReturnValue([])
})
const result = await handler.verifyHostKeyBeforeOperation('git@github.com:user/repo.git')
expect(result).toBe(true)
})
it('should return false on ssh-keyscan command failure', async () => {
mockPrepare.mockReturnValue({
run: vi.fn(),
get: vi.fn().mockReturnValue(null),
all: vi.fn().mockReturnValue([])
})
const result = await handler.verifyHostKeyBeforeOperation('git@invalid-host.example:user/repo.git')
expect(result).toBe(false)
})
})
describe('respond', () => {
it('should return error for non-existent request', async () => {
const result = await handler.respond({
requestId: 'non-existent-id',
response: 'accept'
})
expect(result.success).toBe(false)
expect(result.error).toBe('Request not found or expired')
})
})
describe('getPendingCount', () => {
it('should return 0 when no pending requests', () => {
const count = handler.getPendingCount()
expect(count).toBe(0)
})
})
describe('Error Scenarios', () => {
it('should handle database query failures gracefully in getTrustedHost', () => {
mockPrepare.mockImplementation(() => {
throw new Error('Database connection failed')
})
const result = handler['getTrustedHost']('github.com')
expect(result).toBeNull()
})
it('should handle database save failures gracefully', () => {
const mockRun = vi.fn().mockImplementation(() => {
throw new Error('Database write failed')
})
mockPrepare.mockReturnValue({
run: mockRun,
get: vi.fn().mockReturnValue(null),
all: vi.fn().mockReturnValue([])
})
expect(() => {
handler['saveTrustedHost']('github.com', 'github.com ssh-rsa AAAAB...')
}).not.toThrow()
})
it('should handle known_hosts file write failures gracefully', async () => {
const originalPath = handler['knownHostsPath']
handler['knownHostsPath'] = '/nonexistent/path/known_hosts'
await expect(handler['addToKnownHosts']('github.com', 'github.com ssh-rsa AAAAB...')).resolves.toBeUndefined()
handler['knownHostsPath'] = originalPath
})
const content = await fs.readFile(reloaded.getKnownHostsPath(), 'utf-8')
expect(content).toContain(RSA_KEY)
expect(content).toContain(ED25519_KEY)
})
})
describe('known_hosts entries', () => {
it.each([
['a non-standard port', 'github.com:2222', '[github.com]:2222 ssh-rsa AAAA test@host', '[github.com]:2222'],
['the standard port', 'github.com', 'github.com ssh-rsa AAAA test@host', 'github.com ssh-rsa'],
['an ED25519 key', 'github.com', ED25519_KEY, 'ssh-ed25519'],
['an ECDSA key', 'github.com', ECDSA_KEY, 'ecdsa-sha2-nistp256'],
])('writes %s as a known_hosts line', async (_label, host, publicKey, expectedFragment) => {
await handler['addToKnownHosts'](host, publicKey)
const content = await fs.readFile(knownHostsPath, 'utf-8')
expect(content).toContain(expectedFragment)
expect(content).not.toContain('SHA256:')
})
it('writes exactly one host key line with the host, key type and key data', async () => {
await handler['addToKnownHosts']('github.com', RSA_KEY)
const content = await fs.readFile(knownHostsPath, 'utf-8')
expect(content.trim().split('\n')).toEqual([RSA_KEY])
})
it('does not write a port suffix for the standard port', async () => {
await handler['addToKnownHosts']('github.com', RSA_KEY)
await expect(fs.readFile(knownHostsPath, 'utf-8')).resolves.not.toContain(':22')
})
it('resolves without throwing when known_hosts cannot be written', async () => {
handler['knownHostsPath'] = join(workspace.path, 'missing-dir', 'known_hosts')
await expect(handler['addToKnownHosts']('github.com', RSA_KEY)).resolves.toBeUndefined()
})
})
describe('trusted host persistence', () => {
it('inserts a new trusted host and reads it back', () => {
handler['saveTrustedHost']('github.com', RSA_KEY)
expect(handler['getTrustedHost']('github.com')).toEqual({ key_type: 'ssh-rsa', public_key: RSA_KEY })
})
it('updates the stored key when the same host reports a new one', () => {
handler['saveTrustedHost']('github.com', RSA_KEY)
handler['saveTrustedHost']('github.com', ED25519_KEY)
const rows = db.prepare('SELECT public_key FROM trusted_ssh_hosts WHERE host = ?').all('github.com')
expect(rows).toEqual([{ public_key: ED25519_KEY }])
})
it('returns null instead of throwing when the database query fails', () => {
db.close()
expect(handler['getTrustedHost']('github.com')).toBeNull()
})
it('swallows a database write failure', () => {
db.close()
expect(() => handler['saveTrustedHost']('github.com', RSA_KEY)).not.toThrow()
})
})
describe('verifyHostKeyBeforeOperation', () => {
it('trusts a host that is already stored', async () => {
insertTrustedHost('github.com', 'ssh-rsa', RSA_KEY)
await expect(handler.verifyHostKeyBeforeOperation('git@github.com:user/repo.git')).resolves.toBe(true)
})
it('rejects a host that ssh-keyscan cannot resolve', async () => {
await expect(handler.verifyHostKeyBeforeOperation('git@unknown.example:user/repo.git')).resolves.toBe(false)
})
it('stores the scanned key when the host is auto-accepted', async () => {
keyScanReturns(RSA_KEY)
await handler.autoAcceptHostKey('git@github.com:user/repo.git')
expect(handler['getTrustedHost']('github.com')).toEqual({ key_type: 'ssh-rsa', public_key: RSA_KEY })
await expect(fs.readFile(knownHostsPath, 'utf-8')).resolves.toContain(RSA_KEY)
await expect(handler.verifyHostKeyBeforeOperation('git@github.com:user/repo.git')).resolves.toBe(true)
})
})
describe('respond', () => {
it('reports an unknown request id', async () => {
await expect(handler.respond({ requestId: 'non-existent-id', response: 'accept' })).resolves.toEqual({
success: false,
error: 'Request not found or expired',
})
})
it('has no pending requests initially', () => {
expect(handler.getPendingCount()).toBe(0)
})
})
it('creates the known_hosts file when it does not exist yet', async () => {
const fresh = new SSHHostKeyHandler(db, 5_000)
const freshPath = fresh.getKnownHostsPath()
await fs.rm(freshPath, { force: true })
await fresh.initialize()
expect(existsSync(freshPath)).toBe(true)
})