From 5ef5ced954036c76b47bb93a9e62949bb6da184c Mon Sep 17 00:00:00 2001 From: Jose Ramon Palanco Date: Fri, 31 Jul 2026 22:59:06 +0200 Subject: [PATCH 1/3] chore: remove dead code, unused exports, and unused dependencies Delete unused command modules (login/repos/filter/theme), an unused ThemedBox component, and an unused useFuzzy hook, found via automated dead-code analysis and cross-verified by hand. Un-export types/consts that are only used within their own module and drop the now-unused figures/ink-text-input/react-dom deps. --- bun.lock | 17 ------- package.json | 5 -- src/commands.ts | 32 +++---------- src/commands/filter/index.ts | 55 ---------------------- src/commands/login.ts | 7 --- src/commands/repos.ts | 3 -- src/commands/theme/index.ts | 17 ------- src/components/design-system/ThemedBox.tsx | 27 ----------- src/hooks/useFuzzy.ts | 13 ----- src/utils/diff.ts | 2 +- src/utils/replCommands.ts | 15 +----- tests/commands/registry.test.ts | 9 ---- 12 files changed, 8 insertions(+), 194 deletions(-) delete mode 100644 src/commands/filter/index.ts delete mode 100644 src/commands/login.ts delete mode 100644 src/commands/repos.ts delete mode 100644 src/commands/theme/index.ts delete mode 100644 src/components/design-system/ThemedBox.tsx delete mode 100644 src/hooks/useFuzzy.ts diff --git a/bun.lock b/bun.lock index 47d889a..c7d2fda 100644 --- a/bun.lock +++ b/bun.lock @@ -7,20 +7,15 @@ "dependencies": { "@commander-js/extra-typings": "^14.0.0", "chalk": "^5.6.2", - "figures": "^6.1.0", "ink": "5", - "ink-text-input": "^6.0.0", "lodash-es": "^4.18.1", "react": "18", - "react-dom": "18", "zod": "^4.3.6", }, "devDependencies": { "@types/bun": "latest", "@types/lodash-es": "^4.17.12", "@types/react": "18", - "@types/react-dom": "18", - "ink-testing-library": "^4.0.0", "react-devtools-core": "^7.0.1", "typescript": "^6.0.3", }, @@ -43,8 +38,6 @@ "@types/react": ["@types/react@18.3.28", "", { "dependencies": { "@types/prop-types": "*", "csstype": "^3.2.2" } }, "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw=="], - "@types/react-dom": ["@types/react-dom@18.3.7", "", { "peerDependencies": { "@types/react": "^18.0.0" } }, "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ=="], - "ansi-escapes": ["ansi-escapes@7.3.0", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg=="], "ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], @@ -79,24 +72,16 @@ "escape-string-regexp": ["escape-string-regexp@2.0.0", "", {}, "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w=="], - "figures": ["figures@6.1.0", "", { "dependencies": { "is-unicode-supported": "^2.0.0" } }, "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg=="], - "get-east-asian-width": ["get-east-asian-width@1.5.0", "", {}, "sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA=="], "indent-string": ["indent-string@5.0.0", "", {}, "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg=="], "ink": ["ink@5.2.1", "", { "dependencies": { "@alcalzone/ansi-tokenize": "^0.1.3", "ansi-escapes": "^7.0.0", "ansi-styles": "^6.2.1", "auto-bind": "^5.0.1", "chalk": "^5.3.0", "cli-boxes": "^3.0.0", "cli-cursor": "^4.0.0", "cli-truncate": "^4.0.0", "code-excerpt": "^4.0.0", "es-toolkit": "^1.22.0", "indent-string": "^5.0.0", "is-in-ci": "^1.0.0", "patch-console": "^2.0.0", "react-reconciler": "^0.29.0", "scheduler": "^0.23.0", "signal-exit": "^3.0.7", "slice-ansi": "^7.1.0", "stack-utils": "^2.0.6", "string-width": "^7.2.0", "type-fest": "^4.27.0", "widest-line": "^5.0.0", "wrap-ansi": "^9.0.0", "ws": "^8.18.0", "yoga-layout": "~3.2.1" }, "peerDependencies": { "@types/react": ">=18.0.0", "react": ">=18.0.0", "react-devtools-core": "^4.19.1" }, "optionalPeers": ["@types/react", "react-devtools-core"] }, "sha512-BqcUyWrG9zq5HIwW6JcfFHsIYebJkWWb4fczNah1goUO0vv5vneIlfwuS85twyJ5hYR/y18FlAYUxrO9ChIWVg=="], - "ink-testing-library": ["ink-testing-library@4.0.0", "", { "peerDependencies": { "@types/react": ">=18.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-yF92kj3pmBvk7oKbSq5vEALO//o7Z9Ck/OaLNlkzXNeYdwfpxMQkSowGTFUCS5MSu9bWfSZMewGpp7bFc66D7Q=="], - - "ink-text-input": ["ink-text-input@6.0.0", "", { "dependencies": { "chalk": "^5.3.0", "type-fest": "^4.18.2" }, "peerDependencies": { "ink": ">=5", "react": ">=18" } }, "sha512-Fw64n7Yha5deb1rHY137zHTAbSTNelUKuB5Kkk2HACXEtwIHBCf9OH2tP/LQ9fRYTl1F0dZgbW0zPnZk6FA9Lw=="], - "is-fullwidth-code-point": ["is-fullwidth-code-point@4.0.0", "", {}, "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ=="], "is-in-ci": ["is-in-ci@1.0.0", "", { "bin": { "is-in-ci": "cli.js" } }, "sha512-eUuAjybVTHMYWm/U+vBO1sY/JOCgoPCXRxzdju0K+K0BiGW0SChEL1MLC0PoCIR1OlPo5YAp8HuQoUlsWEICwg=="], - "is-unicode-supported": ["is-unicode-supported@2.1.0", "", {}, "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ=="], - "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], "lodash-es": ["lodash-es@4.18.1", "", {}, "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A=="], @@ -113,8 +98,6 @@ "react-devtools-core": ["react-devtools-core@7.0.1", "", { "dependencies": { "shell-quote": "^1.6.1", "ws": "^7" } }, "sha512-C3yNvRHaizlpiASzy7b9vbnBGLrhvdhl1CbdU6EnZgxPNbai60szdLtl+VL76UNOt5bOoVTOz5rNWZxgGt+Gsw=="], - "react-dom": ["react-dom@18.3.1", "", { "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" }, "peerDependencies": { "react": "^18.3.1" } }, "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw=="], - "react-reconciler": ["react-reconciler@0.29.2", "", { "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" }, "peerDependencies": { "react": "^18.3.1" } }, "sha512-zZQqIiYgDCTP/f1N/mAR10nJGrPD2ZR+jDSEsKWJHYC7Cm2wodlwbR3upZRdC3cjIjSlTLNVyO7Iu0Yy7t2AYg=="], "restore-cursor": ["restore-cursor@4.0.0", "", { "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" } }, "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg=="], diff --git a/package.json b/package.json index cb6d8de..21f467d 100644 --- a/package.json +++ b/package.json @@ -16,20 +16,15 @@ "@types/bun": "latest", "@types/lodash-es": "^4.17.12", "@types/react": "18", - "@types/react-dom": "18", - "ink-testing-library": "^4.0.0", "react-devtools-core": "^7.0.1", "typescript": "^6.0.3" }, "dependencies": { "@commander-js/extra-typings": "^14.0.0", "chalk": "^5.6.2", - "figures": "^6.1.0", "ink": "5", - "ink-text-input": "^6.0.0", "lodash-es": "^4.18.1", "react": "18", - "react-dom": "18", "zod": "^4.3.6" } } diff --git a/src/commands.ts b/src/commands.ts index ddda382..8170242 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -1,55 +1,35 @@ import { memoize } from 'lodash-es' -import type { ReactElement } from 'react' import type { AppState } from './state/AppState.js' import type { Action } from './state/actions.js' -export interface CommandCtx { +interface CommandCtx { state: AppState dispatch: React.Dispatch } -interface CommandBase { +export interface LocalCommand { name: string description: string aliases?: string[] -} - -export interface PromptCommand extends CommandBase { - type: 'prompt' - getPrompt: (args: string[]) => string -} - -export interface LocalCommand extends CommandBase { type: 'local' call: (args: string[], ctx: CommandCtx) => Promise } -export interface LocalJSXCommand extends CommandBase { - type: 'local-jsx' - render: (args: string[], ctx: CommandCtx) => ReactElement -} - -export type Command = PromptCommand | LocalCommand | LocalJSXCommand - // Memoized command registry — lazy loads modules -const loadCommands = memoize(async (): Promise => { - const [themeMod, filterMod, configMod] = await Promise.all([ - import('./commands/theme/index.js'), - import('./commands/filter/index.js'), +const loadCommands = memoize(async (): Promise => { + const [configMod] = await Promise.all([ import('./commands/config/index.js'), ]) return [ - themeMod.default, - filterMod.default, configMod.default, ] }) -export async function findCommand(name: string): Promise { +export async function findCommand(name: string): Promise { const commands = await loadCommands() return commands.find(c => c.name === name || c.aliases?.includes(name)) } -export async function getAllCommands(): Promise { +export async function getAllCommands(): Promise { return loadCommands() } diff --git a/src/commands/filter/index.ts b/src/commands/filter/index.ts deleted file mode 100644 index 0bda56a..0000000 --- a/src/commands/filter/index.ts +++ /dev/null @@ -1,55 +0,0 @@ -import type { LocalCommand } from '../../commands.js' -import type { FindingSeverity, FindingStatus, FindingType } from '../../types.js' -import type { FindingsFilter } from '../../state/actions.js' - -const VALID_SEVERITIES = new Set(['critical', 'high', 'medium', 'low', 'informational']) -const VALID_STATUSES = new Set(['open', 'mitigated', 'enriched']) -const VALID_TYPES = new Set(['SAST', 'SCA', 'DAST']) - -const filterCommand: LocalCommand = { - name: 'filter', - type: 'local', - description: 'Filter findings (/filter severity:critical,high repo:myapp status:open)', - call: async (args, ctx) => { - const filter: FindingsFilter = {} - for (const arg of args) { - const colonIdx = arg.indexOf(':') - if (colonIdx === -1) continue - const k = arg.slice(0, colonIdx) - const v = arg.slice(colonIdx + 1) - if (!v) continue - - if (k === 'severity' || k === 'severities') { - const severities = v.split(',').filter((s): s is FindingSeverity => VALID_SEVERITIES.has(s as FindingSeverity)) - if (severities.length) filter.severities = severities - } - if (k === 'repo' || k === 'repository') { - // Look up repo id from state.repos by nickname - const repos = ctx.state.repos - const match = repos.find(r => r.nickname === v || r.id === v) - if (match) { - filter.repository_ids = [match.id] - } - } - if (k === 'status') { - const statuses = v.split(',').filter((s): s is FindingStatus => VALID_STATUSES.has(s as FindingStatus)) - if (statuses.length) filter.statuses = statuses - } - if (k === 'type') { - const types = v.split(',').filter((t): t is FindingType => VALID_TYPES.has(t as FindingType)) - if (types.length) filter.types = types - } - if (k === 'language') filter.languages = [v] - if (k === 'category') filter.categories = [v] - } - ctx.dispatch({ type: 'findings/filter', payload: filter }) - const desc = [ - filter.severities ? `severity: ${filter.severities.join(', ')}` : '', - filter.repository_ids ? `repo ids: ${filter.repository_ids.join(', ')}` : '', - filter.statuses ? `status: ${filter.statuses.join(', ')}` : '', - ].filter(Boolean).join(', ') - return `Filter applied${desc ? ': ' + desc : ''}` - }, -} - -export default filterCommand diff --git a/src/commands/login.ts b/src/commands/login.ts deleted file mode 100644 index 69cf4d5..0000000 --- a/src/commands/login.ts +++ /dev/null @@ -1,7 +0,0 @@ -interface LoginOptions { - token?: string -} - -export default async function LoginCommand(_options: LoginOptions): Promise { - // stub: login is handled by the TUI LoginForm -} diff --git a/src/commands/repos.ts b/src/commands/repos.ts deleted file mode 100644 index cc78584..0000000 --- a/src/commands/repos.ts +++ /dev/null @@ -1,3 +0,0 @@ -export default async function ReposCommand(): Promise { - // stub: repos are displayed in the TUI ReposPanel -} diff --git a/src/commands/theme/index.ts b/src/commands/theme/index.ts deleted file mode 100644 index 1521bd2..0000000 --- a/src/commands/theme/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { LocalCommand } from '../../commands.js' - -const themeCommand: LocalCommand = { - name: 'theme', - type: 'local', - description: 'Switch theme (/theme )', - call: async (args, ctx) => { - const theme = args[0] - if (theme !== 'dark' && theme !== 'light' && theme !== 'plexicus') { - return 'Usage: /theme ' - } - ctx.dispatch({ type: 'ui/setTheme', payload: theme }) - return `Theme set to ${theme}` - }, -} - -export default themeCommand diff --git a/src/components/design-system/ThemedBox.tsx b/src/components/design-system/ThemedBox.tsx deleted file mode 100644 index 3bbd28f..0000000 --- a/src/components/design-system/ThemedBox.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import React from 'react' -import { Box, type BoxProps } from 'ink' -import type { Theme } from '../../utils/theme.js' - -type Variant = 'primary' | 'secondary' | 'danger' - -const BORDER_COLORS: Record> = { - plexicus: { primary: '#9241ff', secondary: 'gray', danger: 'red' }, - dark: { primary: 'cyan', secondary: 'gray', danger: 'red' }, - light: { primary: 'blue', secondary: 'gray', danger: 'red' }, -} - -interface ThemedBoxProps extends BoxProps { - theme?: Theme - variant?: Variant -} - -export function ThemedBox({ theme = 'plexicus', variant = 'primary', borderStyle, ...props }: ThemedBoxProps) { - const borderColor = BORDER_COLORS[theme][variant] - return ( - - ) -} diff --git a/src/hooks/useFuzzy.ts b/src/hooks/useFuzzy.ts deleted file mode 100644 index 87c9702..0000000 --- a/src/hooks/useFuzzy.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { useState, useMemo } from 'react' - -export function useFuzzy(items: T[], getKey: (item: T) => string) { - const [query, setQuery] = useState('') - - const filtered = useMemo(() => { - if (!query) return items - const lower = query.toLowerCase() - return items.filter(item => getKey(item).toLowerCase().includes(lower)) - }, [items, query, getKey]) - - return { query, setQuery, filtered } -} diff --git a/src/utils/diff.ts b/src/utils/diff.ts index a073505..30b2a93 100644 --- a/src/utils/diff.ts +++ b/src/utils/diff.ts @@ -1,4 +1,4 @@ -export type DiffLineType = 'add' | 'remove' | 'context' | 'header' +type DiffLineType = 'add' | 'remove' | 'context' | 'header' export interface DiffLine { type: DiffLineType diff --git a/src/utils/replCommands.ts b/src/utils/replCommands.ts index ff9b93c..f0fc4a8 100644 --- a/src/utils/replCommands.ts +++ b/src/utils/replCommands.ts @@ -5,7 +5,7 @@ export interface ReplCommand { description: string } -export const REPL_COMMANDS: ReplCommand[] = [ +const REPL_COMMANDS: ReplCommand[] = [ { name: 'filter', template: 'filter', description: 'Open filter modal' }, { name: 'scan', template: 'scan', description: 'Request scan for selected repo' }, { name: 'theme', template: 'theme ', description: 'Switch UI theme' }, @@ -13,19 +13,6 @@ export const REPL_COMMANDS: ReplCommand[] = [ { name: 'help', aliases: ['?'], template: 'help', description: 'Show keybindings help' }, ] -export function matchCommand(input: string): ReplCommand | null { - const normalized = input.startsWith('/') ? input.slice(1) : input - if (!normalized.trim()) return null - const cmd = normalized.split(/\s+/)[0]?.toLowerCase() ?? '' - return ( - REPL_COMMANDS.find(c => c.name === cmd) ?? - REPL_COMMANDS.find(c => c.aliases?.includes(cmd)) ?? - REPL_COMMANDS.find(c => c.name.startsWith(cmd)) ?? - REPL_COMMANDS.find(c => c.aliases?.some(a => a.startsWith(cmd))) ?? - null - ) -} - export function filterCommands(input: string): ReplCommand[] { const normalized = (input.startsWith('/') ? input.slice(1) : input).toLowerCase().trim() if (!normalized) return REPL_COMMANDS diff --git a/tests/commands/registry.test.ts b/tests/commands/registry.test.ts index c0dc2f6..1d66abf 100644 --- a/tests/commands/registry.test.ts +++ b/tests/commands/registry.test.ts @@ -2,12 +2,6 @@ import { describe, it, expect } from 'bun:test' import { findCommand, getAllCommands } from '../../src/commands.js' describe('command registry', () => { - it('finds theme command by name', async () => { - const cmd = await findCommand('theme') - expect(cmd).toBeDefined() - expect(cmd?.name).toBe('theme') - }) - it('finds config command by name', async () => { const cmd = await findCommand('config') expect(cmd).toBeDefined() @@ -22,10 +16,7 @@ describe('command registry', () => { it('getAllCommands returns all registered commands', async () => { const cmds = await getAllCommands() expect(Array.isArray(cmds)).toBe(true) - expect(cmds.length).toBeGreaterThanOrEqual(3) const names = cmds.map(c => c.name) - expect(names).toContain('theme') - expect(names).toContain('filter') expect(names).toContain('config') }) From f67a4e19e0e3551e1e010d42518e1f2f92122cfa Mon Sep 17 00:00:00 2001 From: Jose Ramon Palanco Date: Fri, 31 Jul 2026 22:59:28 +0200 Subject: [PATCH 2/3] fix: apply confirmed multi-agent audit findings across API compliance, UI, and security MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 25 findings confirmed by a consensus-critic pass (3 skeptical reviewers per finding) over a prior deep multi-agent analysis, all fixed: API compliance: - Send the sort query param to the backend (Zalando-style +/-field, mapped to real Mongo field names) — sort_by/sort_dir were computed client-side but never reached the API. - Stop flooring CVSS filter bounds to integers. - Tolerate null nickname/uri/title/date/repo_id in API responses instead of throwing on parse. - Null-guard getScmRepos' per-provider response mapping and fix its pagination to check the raw (not null-filtered) page size. - Document why WS auth token and language/category filter casing can't be fixed client-side (backend-only query-param support / no stable casing convention across scanner tools). UI/input handling: - Gate StatusModal's Escape handler by inputMode, matching the isActive pattern used elsewhere (it was firing unconditionally). - Stop SCMConnectFlow's repo-search textbox from racing with its own j/k/space navigation handler; add scroll windowing past 12 repos. - Wire up the gg/G jump-to-top/bottom shortcuts in the repo and findings lists (handlers existed in useKeymap but nothing called them). - Add the missing "ready" status to the filter modal's checklist. - Fix Tab not submitting SmartTextInput fields. - Use the theme accent color in DiffModal instead of a hardcoded yellow. - Remove KeybindingsHelp's redundant any-key dismiss handler now that App's inputMode==='help' gate already owns it. - Remove dead activePanel/Panel/helpOpen state that mirrored inputMode. Security: - Warn when --token is passed on argv (CWE-214: visible via ps/procfs) and point users at PLEXICUS_TOKEN instead. - Make the login-redirect CSRF nonce single-use. Consistency/maintainability: - Apply friendlyError() at all 16 user-facing error sites instead of 1. - Extract createApiClient()/useFindingActions() to remove the loadConfig+PlexicusApi construction and suppress/false-positive logic duplicated across 8+ call sites. --- src/commands/config/index.ts | 13 +++- src/commands/configSet.ts | 3 +- src/components/App.tsx | 25 +++--- src/components/DiffModal.tsx | 17 +++-- src/components/FilterModal.tsx | 4 +- src/components/FindingDetailScreen.tsx | 41 +++------- src/components/FindingsPanel.tsx | 47 +++++------- src/components/FirstRunWizard.tsx | 3 +- src/components/LoginForm.tsx | 7 +- src/components/ReposPanel.tsx | 10 ++- src/components/SCMConnectFlow.tsx | 47 +++++++----- src/components/StatusModal.tsx | 3 +- .../design-system/KeybindingsHelp.tsx | 11 +-- .../design-system/SmartTextInput.tsx | 5 +- src/hooks/useFindingActions.ts | 31 ++++++++ src/hooks/useFindings.ts | 9 +-- src/hooks/useKeymap.ts | 10 +-- src/hooks/useRemediation.ts | 9 +-- src/hooks/useRepos.ts | 9 +-- src/main.tsx | 12 ++- src/services/apiClient.ts | 7 ++ src/services/apiSchemas.ts | 27 +++---- src/services/auth/webRedirect.ts | 8 +- src/services/plexicusApi.ts | 76 +++++++++++++------ src/services/websocket.ts | 5 +- src/state/AppState.tsx | 21 +++-- src/state/actions.ts | 5 +- src/types.ts | 10 +-- src/utils/text.ts | 18 +++++ 29 files changed, 288 insertions(+), 205 deletions(-) create mode 100644 src/hooks/useFindingActions.ts create mode 100644 src/services/apiClient.ts create mode 100644 src/utils/text.ts diff --git a/src/commands/config/index.ts b/src/commands/config/index.ts index 4891fa7..fddd1a1 100644 --- a/src/commands/config/index.ts +++ b/src/commands/config/index.ts @@ -1,17 +1,24 @@ import type { LocalCommand } from '../../commands.js' import { setConfigValue } from '../../services/config.js' +const THEMES = new Set(['dark', 'light', 'plexicus']) + const configCommand: LocalCommand = { name: 'config', type: 'local', - description: 'Manage configuration (/config set )', - call: async (args, _ctx) => { + description: 'Manage configuration (:config set )', + call: async (args, ctx) => { const [subcommand, key, ...valueParts] = args if (subcommand !== 'set' || !key || valueParts.length === 0) { - return 'Usage: /config set ' + return 'Usage: :config set ' } const value = valueParts.join(' ') await setConfigValue(key, value) + // Persisting the theme without also applying it live would leave the running + // session showing the old theme until restart, looking like the command no-op'd. + if (key === 'theme' && THEMES.has(value)) { + ctx.dispatch({ type: 'ui/setTheme', payload: value as 'dark' | 'light' | 'plexicus' }) + } return `Config updated: ${key} = ${value}` }, } diff --git a/src/commands/configSet.ts b/src/commands/configSet.ts index f4bfb66..fd0c843 100644 --- a/src/commands/configSet.ts +++ b/src/commands/configSet.ts @@ -1,4 +1,5 @@ import { setConfigValue } from '../services/config.js' +import { friendlyError } from '../utils/errors.js' export default async function ConfigSetCommand(key: string, value: string): Promise { try { @@ -6,7 +7,7 @@ export default async function ConfigSetCommand(key: string, value: string): Prom const isSensitive = key === 'token' console.log(`✓ Set ${key} = ${isSensitive ? '***' : value}`) } catch (err) { - console.error(`✗ Failed to set ${key}: ${err instanceof Error ? err.message : String(err)}`) + console.error(`✗ Failed to set ${key}: ${friendlyError(err, 'Unknown error')}`) process.exit(1) } } diff --git a/src/components/App.tsx b/src/components/App.tsx index 3663630..e895593 100644 --- a/src/components/App.tsx +++ b/src/components/App.tsx @@ -13,6 +13,8 @@ import { FirstRunWizard } from './FirstRunWizard.js' import { findCommand } from '../commands.js' import { useWebSocket } from '../hooks/useWebSocket.js' import { filterCommands } from '../utils/replCommands.js' +import { friendlyError } from '../utils/errors.js' +import { createApiClient } from '../services/apiClient.js' import type { Config } from '../services/config.js' interface AppProps { @@ -53,7 +55,6 @@ function AppShell(props: AppProps) { const { exit } = useApp() const [replInput, setReplInput] = useState('') const [replOutput, setReplOutput] = useState(null) - const [showHelp, setShowHelp] = useState(false) const commandHistory = useRef([]) const historyIndex = useRef(-1) const replInputRef = useRef('') @@ -89,8 +90,8 @@ function AppShell(props: AppProps) { const ac = accent(state.theme) useInput((input, key) => { - if (showHelp) { - setShowHelp(false) + if (state.inputMode === 'help') { + dispatch({ type: 'help/close' }) return } @@ -98,7 +99,7 @@ function AppShell(props: AppProps) { if (state.inputMode === 'scm') return if (input === '?' && state.inputMode === 'navigation') { - setShowHelp(true) + dispatch({ type: 'help/open' }) return } @@ -253,10 +254,7 @@ function AppShell(props: AppProps) { return } try { - const { loadConfig } = await import('../services/config.js') - const { PlexicusApi } = await import('../services/plexicusApi.js') - const config = await loadConfig() - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: stateRef.current.token ?? config.token }) + const api = await createApiClient(stateRef.current.token) const repo = stateRef.current.repos.find(r => r.id === repoId) await api.requestScan(repoId) dispatch({ @@ -264,15 +262,14 @@ function AppShell(props: AppProps) { payload: { type: 'repo', id: repoId, name: repo?.nickname ?? repoId, status: 'pending', progress: 0, logs: [] }, }) } catch (err) { - setReplOutput(err instanceof Error ? err.message : 'Scan request failed') + setReplOutput(friendlyError(err, 'Scan request failed')) } dispatch({ type: 'ui/setInputMode', payload: 'navigation' }) return } if (cmdName === '?' || cmdName === 'help') { - dispatch({ type: 'ui/setInputMode', payload: 'navigation' }) - setShowHelp(true) + dispatch({ type: 'help/open' }) return } @@ -288,11 +285,11 @@ function AppShell(props: AppProps) { setReplOutput(`Unknown command: ${cmdName} — type :help for available commands`) dispatch({ type: 'ui/setInputMode', payload: 'navigation' }) } catch (err) { - setReplOutput(err instanceof Error ? err.message : 'Command failed') + setReplOutput(friendlyError(err, 'Command failed')) dispatch({ type: 'ui/setInputMode', payload: 'navigation' }) } }, - [dispatch, setShowHelp], + [dispatch], ) const { sort_by: _sb, sort_dir: _sd, ...filterRest } = state.findingsFilter @@ -396,7 +393,7 @@ function AppShell(props: AppProps) { )} - {showHelp && setShowHelp(false)} accentColor={ac} />} + {state.inputMode === 'help' && } ) } diff --git a/src/components/DiffModal.tsx b/src/components/DiffModal.tsx index a6ac6e3..4135a5d 100644 --- a/src/components/DiffModal.tsx +++ b/src/components/DiffModal.tsx @@ -4,6 +4,7 @@ import { useAppState } from '../state/AppState.js' import { accent } from '../utils/theme.js' import { useRemediation } from '../hooks/useRemediation.js' import { parseDiff } from '../utils/diff.js' +import { expandTabs } from '../utils/text.js' import { Spinner } from './design-system/Spinner.js' import type { Finding } from '../types.js' @@ -51,7 +52,6 @@ export function DiffModal({ finding, onClose }: DiffModalProps) { const visibleLines = diffLines.slice(scrollOffset, scrollOffset + VISIBLE_LINES) useInput((input, key) => { - if (state.inputMode !== 'navigation') return if (key.escape) { onClose(); return } if (isReady && diffLines.length > 0) { @@ -69,13 +69,13 @@ export function DiffModal({ finding, onClose }: DiffModalProps) { applyPR() return } - }) + }, { isActive: state.inputMode === 'navigation' }) return ( - + - AI Remediation + AI Remediation — {finding.title} {isReady && diffLines.length > 0 && ( @@ -105,15 +105,16 @@ export function DiffModal({ finding, onClose }: DiffModalProps) { {isReady && diffLines.length > 0 && ( {visibleLines.map((line, i) => { + const content = expandTabs(line.content) switch (line.type) { case 'add': - return +{line.content} + return +{content} case 'remove': - return -{line.content} + return -{content} case 'header': - return {line.content} + return {content} case 'context': - return {line.content} + return {content} } })} diff --git a/src/components/FilterModal.tsx b/src/components/FilterModal.tsx index 5c2031e..2bb9c3a 100644 --- a/src/components/FilterModal.tsx +++ b/src/components/FilterModal.tsx @@ -6,7 +6,7 @@ import type { FindingSeverity, FindingStatus, FindingType } from '../types.js' import type { FindingsFilter } from '../state/actions.js' const SEVERITIES: FindingSeverity[] = ['critical', 'high', 'medium', 'low', 'informational'] -const STATUSES: FindingStatus[] = ['open', 'mitigated', 'enriched'] +const STATUSES: FindingStatus[] = ['open', 'enriched', 'ready', 'mitigated'] const TYPES: FindingType[] = ['SAST', 'SCA', 'DAST'] // Section indices @@ -513,12 +513,14 @@ export function FilterModal() { {sectionLabel(S_LANGUAGE, 'Language')} {textField(S_LANGUAGE, draft.language)} + {section === S_LANGUAGE && case-sensitive exact match — use the casing shown on a finding} {/* Category */} {sectionLabel(S_CATEGORY, 'Category')} {textField(S_CATEGORY, draft.category)} + {section === S_CATEGORY && case-sensitive exact match — use the casing shown on a finding} {/* CWE IDs */} diff --git a/src/components/FindingDetailScreen.tsx b/src/components/FindingDetailScreen.tsx index f9abb53..42fb20c 100644 --- a/src/components/FindingDetailScreen.tsx +++ b/src/components/FindingDetailScreen.tsx @@ -5,6 +5,8 @@ import { accent } from '../utils/theme.js' import { severityBadge, severityColor, cvssColor } from '../utils/severity.js' import { scmLabel, scmUrl, openScmLink } from '../utils/scm.js' import { DiffModal } from './DiffModal.js' +import { expandTabs } from '../utils/text.js' +import { useFindingActions } from '../hooks/useFindingActions.js' import type { Finding } from '../types.js' function statusLabel(finding: Finding): string { @@ -57,7 +59,7 @@ function CodeBlock({ code, scrollOffset, highlightLine }: { code: string; scroll const isHot = highlightLine !== null && highlightLine !== undefined && lineNum === highlightLine return ( - {line} + {expandTabs(line)} ) })} @@ -81,33 +83,15 @@ export function FindingDetailScreen() { ? state.repos.find(r => r.id === finding.repo_id) ?? null : null - const handleSuppress = useCallback(async () => { - if (!finding) return - try { - const { loadConfig } = await import('../services/config.js') - const { PlexicusApi } = await import('../services/plexicusApi.js') - const config = await loadConfig() - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: state.token ?? config.token }) - await api.markMitigated(finding.id) - dispatch({ type: 'findings/update', payload: { ...finding, status: 'mitigated' as const } }) - } catch (err) { - dispatch({ type: 'ui/setError', payload: err instanceof Error ? err.message : 'Failed to suppress' }) - } - }, [finding, state.token, dispatch]) + const { suppress, toggleFalsePositive } = useFindingActions() - const handleFalsePositive = useCallback(async () => { - if (!finding) return - try { - const { loadConfig } = await import('../services/config.js') - const { PlexicusApi } = await import('../services/plexicusApi.js') - const config = await loadConfig() - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: state.token ?? config.token }) - await api.toggleFalsePositive(finding.id) - dispatch({ type: 'findings/update', payload: { ...finding, is_false_positive: !finding.is_false_positive } }) - } catch (err) { - dispatch({ type: 'ui/setError', payload: err instanceof Error ? err.message : 'Failed to toggle false positive' }) - } - }, [finding, state.token, dispatch]) + const handleSuppress = useCallback(() => { + if (finding) suppress(finding) + }, [finding, suppress]) + + const handleFalsePositive = useCallback(() => { + if (finding) toggleFalsePositive(finding) + }, [finding, toggleFalsePositive]) const handleOpenLink = useCallback(async () => { if (!finding || !repo) return @@ -132,7 +116,6 @@ export function FindingDetailScreen() { useInput((input, key) => { if (!finding) return - if (state.inputMode !== 'navigation') return if (key.escape) { dispatch({ type: 'nav/popScreen' }); return } if (input === 'r') { setShowDiff(true); return } if (input === 's') { handleSuppress(); return } @@ -146,7 +129,7 @@ export function FindingDetailScreen() { setCodeScroll(s => Math.min(s + 1, Math.max(0, codeLineCount - CODE_VISIBLE))) return } - }) + }, { isActive: !showDiff && state.inputMode === 'navigation' }) if (!finding) return null if (showDiff) return setShowDiff(false)} /> diff --git a/src/components/FindingsPanel.tsx b/src/components/FindingsPanel.tsx index 9b3b266..118dc7c 100644 --- a/src/components/FindingsPanel.tsx +++ b/src/components/FindingsPanel.tsx @@ -7,6 +7,7 @@ import { useFindings } from '../hooks/useFindings.js' import { Spinner } from './design-system/Spinner.js' import { FuzzyPicker } from './design-system/FuzzyPicker.js' import { severityColor } from '../utils/severity.js' +import { useFindingActions } from '../hooks/useFindingActions.js' import type { Finding } from '../types.js' import type { FindingsFilter } from '../state/actions.js' @@ -47,6 +48,14 @@ export function FindingsPanel({ repo, cve }: FindingsPanelProps) { setCursorIndex(i => Math.max(i - 1, 0)) }, []) + const handleGG = useCallback(() => { + setCursorIndex(0) + }, []) + + const handleShiftG = useCallback(() => { + setCursorIndex(Math.max(0, findings.length - 1)) + }, [findings.length]) + const handleSelect = useCallback(() => { const finding = findings[cursorIndex] if (!finding) return @@ -58,40 +67,24 @@ export function FindingsPanel({ repo, cve }: FindingsPanelProps) { dispatch({ type: 'nav/popScreen' }) }, [dispatch]) - const handleSuppress = useCallback(async () => { + const { suppress, toggleFalsePositive } = useFindingActions() + + const handleSuppress = useCallback(() => { const finding = findings[cursorIndex] - if (!finding) return - try { - const { loadConfig } = await import('../services/config.js') - const { PlexicusApi } = await import('../services/plexicusApi.js') - const config = await loadConfig() - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: state.token ?? config.token }) - await api.markMitigated(finding.id) - dispatch({ type: 'findings/update', payload: { ...finding, status: 'mitigated' as const } }) - } catch (err) { - dispatch({ type: 'ui/setError', payload: err instanceof Error ? err.message : 'Failed to suppress finding' }) - } - }, [findings, cursorIndex, dispatch, state.token]) - - const handleFalsePositive = useCallback(async () => { + if (finding) suppress(finding) + }, [findings, cursorIndex, suppress]) + + const handleFalsePositive = useCallback(() => { const finding = findings[cursorIndex] - if (!finding) return - try { - const { loadConfig } = await import('../services/config.js') - const { PlexicusApi } = await import('../services/plexicusApi.js') - const config = await loadConfig() - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: state.token ?? config.token }) - await api.toggleFalsePositive(finding.id) - dispatch({ type: 'findings/update', payload: { ...finding, is_false_positive: !finding.is_false_positive } }) - } catch (err) { - dispatch({ type: 'ui/setError', payload: err instanceof Error ? err.message : 'Failed to toggle false positive' }) - } - }, [findings, cursorIndex, dispatch, state.token]) + if (finding) toggleFalsePositive(finding) + }, [findings, cursorIndex, toggleFalsePositive]) useKeymap( { onDown: handleDown, onUp: handleUp, + onGG: handleGG, + onShiftG: handleShiftG, onSelect: handleSelect, onEscape: handleEscape, onSuppress: handleSuppress, diff --git a/src/components/FirstRunWizard.tsx b/src/components/FirstRunWizard.tsx index 1675faa..c4b442b 100644 --- a/src/components/FirstRunWizard.tsx +++ b/src/components/FirstRunWizard.tsx @@ -2,6 +2,7 @@ import React, { useState } from 'react' import { Box, Text } from 'ink' import { SmartTextInput as TextInput } from './design-system/SmartTextInput.js' import { saveConfig, loadConfig } from '../services/config.js' +import { friendlyError } from '../utils/errors.js' interface FirstRunWizardProps { onComplete: () => void @@ -21,7 +22,7 @@ export function FirstRunWizard({ onComplete }: FirstRunWizardProps) { await saveConfig({ ...config, serverUrl: url }) onComplete() } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to save config') + setError(friendlyError(err, 'Failed to save config')) setSaving(false) } } diff --git a/src/components/LoginForm.tsx b/src/components/LoginForm.tsx index d271850..fd20826 100644 --- a/src/components/LoginForm.tsx +++ b/src/components/LoginForm.tsx @@ -4,6 +4,7 @@ import { SmartTextInput as TextInput } from './design-system/SmartTextInput.js' import { useAppState } from '../state/AppState.js' import { PlexicusApi } from '../services/plexicusApi.js' import { loadConfig, saveConfig } from '../services/config.js' +import { friendlyError } from '../utils/errors.js' type LoginStep = 'email' | 'password' | 'otp' | 'loading' | 'done' @@ -56,7 +57,7 @@ export function LoginForm({ prefilledToken, onDone }: LoginFormProps) { setStep('done') onDone?.(user.email) } catch (err) { - setError(err instanceof Error ? err.message : 'Invalid token') + setError(friendlyError(err, 'Invalid token')) setStep('email') } } @@ -92,7 +93,7 @@ export function LoginForm({ prefilledToken, onDone }: LoginFormProps) { setStep('done') onDone?.(sessionUser.email) } catch (err) { - setError(err instanceof Error ? err.message : 'Login failed') + setError(friendlyError(err, 'Login failed')) setStep('password') } }, [email, dispatch]) @@ -113,7 +114,7 @@ export function LoginForm({ prefilledToken, onDone }: LoginFormProps) { setStep('done') onDone?.(sessionUser.email) } catch (err) { - setError(err instanceof Error ? err.message : '2FA verification failed') + setError(friendlyError(err, '2FA verification failed')) setStep('otp') } }, [email, dispatch]) diff --git a/src/components/ReposPanel.tsx b/src/components/ReposPanel.tsx index 9ab4e03..6326628 100644 --- a/src/components/ReposPanel.tsx +++ b/src/components/ReposPanel.tsx @@ -52,6 +52,14 @@ export function ReposPanel() { setCursorIndex(i => Math.max(i - 1, 0)) }, []) + const handleGG = useCallback(() => { + setCursorIndex(0) + }, []) + + const handleShiftG = useCallback(() => { + setCursorIndex(totalItems - 1) + }, [totalItems]) + const handleSelect = useCallback(() => { const repoId = cursorIndex === 0 ? null : (repos[cursorIndex - 1]?.id ?? null) dispatch({ type: 'repo/select', payload: repoId }) @@ -67,7 +75,7 @@ export function ReposPanel() { }, [dispatch]) useKeymap( - { onDown: handleDown, onUp: handleUp, onSelect: handleSelect, onAdd: handleAdd }, + { onDown: handleDown, onUp: handleUp, onGG: handleGG, onShiftG: handleShiftG, onSelect: handleSelect, onAdd: handleAdd }, { inputMode: state.inputMode, isActive: state.screen === 'repos' }, ) diff --git a/src/components/SCMConnectFlow.tsx b/src/components/SCMConnectFlow.tsx index d108148..bddfc87 100644 --- a/src/components/SCMConnectFlow.tsx +++ b/src/components/SCMConnectFlow.tsx @@ -3,8 +3,9 @@ import { Box, Text, useInput } from 'ink' import { SmartTextInput as TextInput } from './design-system/SmartTextInput.js' import { useAppState } from '../state/AppState.js' import { accent } from '../utils/theme.js' -import { PlexicusApi } from '../services/plexicusApi.js' +import { createApiClient } from '../services/apiClient.js' import { loadConfig } from '../services/config.js' +import { friendlyError } from '../utils/errors.js' import { Spinner } from './design-system/Spinner.js' import type { ScmProvider, ScmRepo } from '../types.js' @@ -43,7 +44,7 @@ export function SCMConnectFlow({ onClose }: { onClose: () => void }) { try { const config = await loadConfig() setWebUrl(config.webUrl ?? null) - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: state.token ?? undefined }) + const api = await createApiClient(state.token) const v = await api.checkScmValidity() if (!cancelled) setValidity(v) } catch { @@ -76,14 +77,13 @@ export function SCMConnectFlow({ onClose }: { onClose: () => void }) { const fetchRepos = useCallback(async (prov: ScmProvider) => { setStep('loading-repos') try { - const config = await loadConfig() - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: state.token ?? undefined }) + const api = await createApiClient(state.token) const scmRepos = await api.getScmRepos(prov) setRepos(scmRepos) setCursor(0) setStep('pick-repos') } catch (err) { - setErrorMsg(err instanceof Error ? err.message : 'Failed to load repositories') + setErrorMsg(friendlyError(err, 'Failed to load repositories')) setStep('error') } }, [state.token]) @@ -100,14 +100,13 @@ export function SCMConnectFlow({ onClose }: { onClose: () => void }) { } setStep('importing') try { - const config = await loadConfig() - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: state.token ?? undefined }) + const api = await createApiClient(state.token) const repo = { id: nickname, name: nickname, full_name: nickname, html_url: url } await api.importRepositories([repo], guessProvider(url)) setImportedCount(1) setStep('done') } catch (err) { - setErrorMsg(err instanceof Error ? err.message : 'Import failed') + setErrorMsg(friendlyError(err, 'Import failed')) setStep('error') } }, [manualRepoUrl, manualNickname, state.token]) @@ -117,13 +116,12 @@ export function SCMConnectFlow({ onClose }: { onClose: () => void }) { if (toImport.length === 0) return setStep('importing') try { - const config = await loadConfig() - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: state.token ?? undefined }) + const api = await createApiClient(state.token) await api.importRepositories(toImport, provider) setImportedCount(toImport.length) setStep('done') } catch (err) { - setErrorMsg(err instanceof Error ? err.message : 'Import failed') + setErrorMsg(friendlyError(err, 'Import failed')) setStep('error') } }, [repos, selectedRepoIds, provider, state.token]) @@ -131,7 +129,9 @@ export function SCMConnectFlow({ onClose }: { onClose: () => void }) { const filteredRepos = repoQuery ? repos.filter(r => r.full_name.toLowerCase().includes(repoQuery.toLowerCase())) : repos - const visibleRepos = filteredRepos.slice(0, 12) + const REPO_VISIBLE = 12 + const repoWindowStart = Math.max(0, cursor - Math.floor(REPO_VISIBLE / 2)) + const visibleRepos = filteredRepos.slice(repoWindowStart, repoWindowStart + REPO_VISIBLE) const selectedProvider = PROVIDERS[cursor] const selectedConnected = selectedProvider ? !!validity[selectedProvider.id] : false @@ -169,10 +169,15 @@ export function SCMConnectFlow({ onClose }: { onClose: () => void }) { } if (step === 'pick-repos') { - if (input === 'j' || key.downArrow) { setCursor(c => Math.min(c + 1, visibleRepos.length - 1)); return } + if (key.backspace || key.delete) { + setRepoQuery(q => q.slice(0, -1)) + setCursor(0) + return + } + if (input === 'j' || key.downArrow) { setCursor(c => Math.min(c + 1, filteredRepos.length - 1)); return } if (input === 'k' || key.upArrow) { setCursor(c => Math.max(c - 1, 0)); return } if (input === ' ') { - const repo = visibleRepos[cursor] + const repo = filteredRepos[cursor] if (repo) { setSelectedRepoIds(prev => { const next = new Set(prev) @@ -183,6 +188,11 @@ export function SCMConnectFlow({ onClose }: { onClose: () => void }) { return } if (key.return) { importSelected(); return } + if (!key.ctrl && !key.meta && input && input.length === 1) { + setRepoQuery(q => q + input) + setCursor(0) + return + } } if (step === 'error') { @@ -253,20 +263,21 @@ export function SCMConnectFlow({ onClose }: { onClose: () => void }) { Select repositories to import ({selectedRepoIds.size} selected): / - { setRepoQuery(v); setCursor(0) }} placeholder="filter repos..." /> + {repoQuery} {!repoQuery && filter repos...} {visibleRepos.map((repo, i) => { + const absIdx = repoWindowStart + i const selected = selectedRepoIds.has(repo.id) return ( - - {i === cursor ? '▶ ' : ' '} + + {absIdx === cursor ? '▶ ' : ' '} {selected ? '✓ ' : ' '} {repo.full_name} {repo.private && (private)} ) })} - {visibleRepos.length}/{repos.length} repos + {filteredRepos.length}/{repos.length} repos ↑↓=navigate Space=toggle Enter=import selected Esc=back )} diff --git a/src/components/StatusModal.tsx b/src/components/StatusModal.tsx index 0ff1779..bc3b1bf 100644 --- a/src/components/StatusModal.tsx +++ b/src/components/StatusModal.tsx @@ -21,11 +21,10 @@ export function StatusModal() { const job = state.activeStatusJob useInput((_, key) => { - if (!job) return if (key.escape) { dispatch({ type: 'status/close' }) } - }) + }, { isActive: !!job && state.inputMode === 'navigation' }) if (!job) return null diff --git a/src/components/design-system/KeybindingsHelp.tsx b/src/components/design-system/KeybindingsHelp.tsx index 1e482b8..a5ebd26 100644 --- a/src/components/design-system/KeybindingsHelp.tsx +++ b/src/components/design-system/KeybindingsHelp.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { Box, Text, useInput } from 'ink' +import { Box, Text } from 'ink' import { Dialog } from './Dialog.js' const KEYBINDINGS = [ @@ -15,25 +15,20 @@ const KEYBINDINGS = [ ['] / [', 'Next / prev page'], ['/', 'Fuzzy search (findings only)'], [':', 'Open command REPL'], - ['c', 'Toggle AI chat sidebar'], - ['Tab / 1 / 2', 'Switch panels'], ['?', 'Show this help'], ['── REPL ──', ''], - [':ask / :a', 'Ask AI a question'], [':filter', 'Open filter modal'], + [':scan', 'Trigger a repository scan'], [':theme dark|light|plexicus', 'Switch UI theme'], [':config set ', 'Set a config value'], [':help / :?', 'Show keybindings help'], ] interface KeybindingsHelpProps { - onDismiss: () => void accentColor?: string } -export function KeybindingsHelp({ onDismiss, accentColor = '#9241ff' }: KeybindingsHelpProps) { - useInput(() => onDismiss()) - +export function KeybindingsHelp({ accentColor = '#9241ff' }: KeybindingsHelpProps) { return ( {KEYBINDINGS.map(([key, desc]) => diff --git a/src/components/design-system/SmartTextInput.tsx b/src/components/design-system/SmartTextInput.tsx index 04c351b..5e102f1 100644 --- a/src/components/design-system/SmartTextInput.tsx +++ b/src/components/design-system/SmartTextInput.tsx @@ -73,7 +73,10 @@ export function SmartTextInput({ } return } - if (key.return) { + if (key.return || key.tab) { + // Tab is unbound everywhere else in the app; users reflexively press it to + // advance fields, and without this it silently no-ops and their next + // keystrokes append into the still-focused field instead. onSubmit?.(latestValue.current) return } diff --git a/src/hooks/useFindingActions.ts b/src/hooks/useFindingActions.ts new file mode 100644 index 0000000..9d6ec45 --- /dev/null +++ b/src/hooks/useFindingActions.ts @@ -0,0 +1,31 @@ +import { useCallback } from 'react' +import { useAppState } from '../state/AppState.js' +import { createApiClient } from '../services/apiClient.js' +import { friendlyError } from '../utils/errors.js' +import type { Finding } from '../types.js' + +export function useFindingActions() { + const { state, dispatch } = useAppState() + + const suppress = useCallback(async (finding: Finding) => { + try { + const api = await createApiClient(state.token) + await api.markMitigated(finding.id) + dispatch({ type: 'findings/update', payload: { ...finding, status: 'mitigated' as const } }) + } catch (err) { + dispatch({ type: 'ui/setError', payload: friendlyError(err, 'Failed to suppress finding') }) + } + }, [state.token, dispatch]) + + const toggleFalsePositive = useCallback(async (finding: Finding) => { + try { + const api = await createApiClient(state.token) + await api.toggleFalsePositive(finding.id) + dispatch({ type: 'findings/update', payload: { ...finding, is_false_positive: !finding.is_false_positive } }) + } catch (err) { + dispatch({ type: 'ui/setError', payload: friendlyError(err, 'Failed to toggle false positive') }) + } + }, [state.token, dispatch]) + + return { suppress, toggleFalsePositive } +} diff --git a/src/hooks/useFindings.ts b/src/hooks/useFindings.ts index a30525f..c1dcbc3 100644 --- a/src/hooks/useFindings.ts +++ b/src/hooks/useFindings.ts @@ -1,8 +1,8 @@ import { useEffect, useRef, useMemo } from 'react' import { useAppState } from '../state/AppState.js' -import { PlexicusApi } from '../services/plexicusApi.js' -import { loadConfig } from '../services/config.js' +import { createApiClient } from '../services/apiClient.js' import { severityRank } from '../utils/severity.js' +import { friendlyError } from '../utils/errors.js' import type { Finding } from '../types.js' function sortFindings(findings: Finding[], sortBy: string | undefined, sortDir: string | undefined): Finding[] { @@ -49,8 +49,7 @@ export function useFindings(opts?: { cve?: string }) { async function fetchFindings() { dispatch({ type: 'findings/loading', payload: true }) try { - const config = await loadConfig() - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: state.token ?? config.token }) + const api = await createApiClient(state.token) const { findings, total, pageCount } = await api.getFindings( state.findingsFilter, @@ -75,7 +74,7 @@ export function useFindings(opts?: { cve?: string }) { } catch (err) { if (controller.signal.aborted) return dispatch({ type: 'findings/loading', payload: false }) - dispatch({ type: 'ui/setError', payload: err instanceof Error ? err.message : 'Failed to load findings' }) + dispatch({ type: 'ui/setError', payload: friendlyError(err, 'Failed to load findings') }) } } diff --git a/src/hooks/useKeymap.ts b/src/hooks/useKeymap.ts index 631763b..e33e913 100644 --- a/src/hooks/useKeymap.ts +++ b/src/hooks/useKeymap.ts @@ -29,11 +29,11 @@ const GG_TIMEOUT_MS = 500 export function useKeymap(handlers: KeymapHandlers, { inputMode, isActive = true }: UseKeymapOptions) { const gPressedAt = useRef(null) + // Gate via Ink's own isActive option (not a manual check inside the callback) so Ink + // detaches the stdin listener entirely when inactive — a manual in-callback check still + // leaves the listener attached, which races other active useInput hooks (e.g. modals) + // for the same keystroke depending on closure/render timing. useInput((input, key) => { - if (!isActive) return - // Only process navigation keys when in navigation mode - if (inputMode !== 'navigation') return - if (input === 'j' || key.downArrow) { gPressedAt.current = null handlers.onDown?.() @@ -116,5 +116,5 @@ export function useKeymap(handlers: KeymapHandlers, { inputMode, isActive = true handlers.onOpenLink?.() return } - }) + }, { isActive: isActive && inputMode === 'navigation' }) } diff --git a/src/hooks/useRemediation.ts b/src/hooks/useRemediation.ts index f0b557f..820cd15 100644 --- a/src/hooks/useRemediation.ts +++ b/src/hooks/useRemediation.ts @@ -1,7 +1,6 @@ import React, { useCallback, useRef, useState } from 'react' import { useAppState } from '../state/AppState.js' -import { PlexicusApi } from '../services/plexicusApi.js' -import { loadConfig } from '../services/config.js' +import { createApiClient } from '../services/apiClient.js' import { friendlyError } from '../utils/errors.js' import { plexicusWs } from '../services/websocket.js' @@ -82,8 +81,7 @@ export function useRemediation(findingId: string | null) { setLocalError(null) try { - const config = await loadConfig() - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: state.token ?? config.token }) + const api = await createApiClient(state.token) const existing = await api.getRemediations(findingId) const ready = existing.find(r => r.finding_id === findingId && r.status === 'ready') @@ -161,8 +159,7 @@ export function useRemediation(findingId: string | null) { } try { - const config = await loadConfig() - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: state.token ?? config.token }) + const api = await createApiClient(state.token) await api.createPR(remediation.id) dispatch({ type: 'ui/setNotification', payload: 'PR creation triggered — check your repository' }) } catch (err) { diff --git a/src/hooks/useRepos.ts b/src/hooks/useRepos.ts index 95bc512..9d83c5b 100644 --- a/src/hooks/useRepos.ts +++ b/src/hooks/useRepos.ts @@ -1,7 +1,7 @@ import { useEffect, useRef } from 'react' import { useAppState } from '../state/AppState.js' -import { PlexicusApi } from '../services/plexicusApi.js' -import { loadConfig } from '../services/config.js' +import { createApiClient } from '../services/apiClient.js' +import { friendlyError } from '../utils/errors.js' export function useRepos() { const { state, dispatch } = useAppState() @@ -15,13 +15,12 @@ export function useRepos() { async function fetchRepos() { dispatch({ type: 'repos/loading', payload: true }) try { - const config = await loadConfig() - const api = new PlexicusApi({ baseUrl: config.serverUrl, token: state.token ?? config.token }) + const api = await createApiClient(state.token) const { repos } = await api.getRepositories() dispatch({ type: 'repos/set', payload: repos }) } catch (err) { dispatch({ type: 'repos/loading', payload: false }) - dispatch({ type: 'ui/setError', payload: err instanceof Error ? err.message : 'Failed to load repos' }) + dispatch({ type: 'ui/setError', payload: friendlyError(err, 'Failed to load repos') }) } } diff --git a/src/main.tsx b/src/main.tsx index fa82f83..41a4caa 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -3,6 +3,7 @@ import { program } from '@commander-js/extra-typings' import React from 'react' import { render } from 'ink' import chalk from 'chalk' +import { friendlyError } from './utils/errors.js' // Force true-color (24-bit) rendering — some terminals report lower capability chalk.level = 3 @@ -15,7 +16,7 @@ program .version(version) .option('--repo ', 'filter findings to a specific repository') .option('--cve ', 'jump directly to a finding by CVE ID') - .option('--token ', 'authenticate with a Bearer token') + .option('--token ', 'authenticate with a Bearer token (prefer PLEXICUS_TOKEN env var — argv is visible to other users via ps/procfs)') .action(async (options) => { const { loadConfig } = await import('./services/config.js') const { printSplash } = await import('./assets/splash.js') @@ -23,6 +24,10 @@ program printSplash(version, config.serverUrl) + if (options.token) { + console.warn(chalk.yellow('Warning: --token exposes your token in the process list (ps, /proc). Prefer PLEXICUS_TOKEN.')) + } + const token = options.token ?? process.env.PLEXICUS_TOKEN ?? config.token const { default: App } = await import('./components/App.js') @@ -32,7 +37,7 @@ program program .command('login') .description('Authenticate with the Plexicus API') - .option('--token ', 'skip interactive login, store this token directly') + .option('--token ', 'skip interactive login, store this token directly (prefer PLEXICUS_TOKEN env var — argv is visible to other users via ps/procfs)') .option('--headless', 'use email/password instead of browser redirect') .action(async (options) => { const { loadConfig, saveConfig } = await import('./services/config.js') @@ -49,6 +54,7 @@ program } if (options.token) { + console.warn(chalk.yellow('Warning: --token exposes your token in the process list (ps, /proc). Prefer PLEXICUS_TOKEN.')) const loginEl = React.createElement(LoginForm, { prefilledToken: options.token, onDone }) render(React.createElement(AppStateProvider, { initialTheme: config.theme, children: loginEl })) return @@ -68,7 +74,7 @@ program console.log(chalk.green(`✓ Authenticated as ${email}`)) process.exit(0) } catch (err: unknown) { - const msg = err instanceof Error ? err.message : String(err) + const msg = friendlyError(err, 'Browser auth failed') console.warn(chalk.yellow(`Browser auth failed (${msg}), falling back to password login.`)) } } else if (!options.headless && !webUrl) { diff --git a/src/services/apiClient.ts b/src/services/apiClient.ts new file mode 100644 index 0000000..c36d980 --- /dev/null +++ b/src/services/apiClient.ts @@ -0,0 +1,7 @@ +import { PlexicusApi } from './plexicusApi.js' +import { loadConfig } from './config.js' + +export async function createApiClient(token: string | null | undefined): Promise { + const config = await loadConfig() + return new PlexicusApi({ baseUrl: config.serverUrl, token: token ?? config.token }) +} diff --git a/src/services/apiSchemas.ts b/src/services/apiSchemas.ts index d2eb3fc..b622878 100644 --- a/src/services/apiSchemas.ts +++ b/src/services/apiSchemas.ts @@ -18,7 +18,7 @@ const STATUS_MAP: Record = { } const FindingAttributesSchema = z.object({ - title: z.string(), + title: z.string().nullish().transform(v => v ?? 'Untitled finding'), severity: z.string().transform(s => (SEVERITY_MAP[s.toLowerCase()] ?? 'low') as 'critical' | 'high' | 'medium' | 'low' | 'informational'), severity_numerical: z.number().nullable().default(null), status: z.string().transform(s => (STATUS_MAP[s.toLowerCase()] ?? 'open') as 'open' | 'mitigated' | 'enriched' | 'ready'), @@ -38,8 +38,8 @@ const FindingAttributesSchema = z.object({ impact: z.number().nullable().default(null), confidence: z.number().nullable().default(null), estimated_epss: z.number().nullable().default(null), - repo_id: z.string(), - date: z.string(), + repo_id: z.string().nullish().transform(v => v ?? ''), + date: z.string().nullish().transform(v => v ?? ''), is_false_positive: z.boolean().default(false), duplicate: z.boolean().optional(), is_duplicate: z.boolean().optional(), @@ -64,7 +64,7 @@ const FindingAttributesSchema = z.object({ is_duplicate: a.is_duplicate ?? a.duplicate ?? false, })) -export const FindingItemSchema = z.object({ +const FindingItemSchema = z.object({ id: z.string(), attributes: FindingAttributesSchema, }) @@ -82,8 +82,8 @@ export const SingleFindingResponseSchema = z.object({ }) const RepoAttributesSchema = z.object({ - nickname: z.string(), - uri: z.string(), + nickname: z.string().nullish().transform(v => v ?? 'unknown-repo'), + uri: z.string().nullish().transform(v => v ?? ''), active: z.boolean().nullish().transform(v => v ?? true), repo_type: z.string().nullish().transform(v => v ?? 'github'), status: z.string().nullish().transform(v => v ?? 'active'), @@ -103,7 +103,7 @@ const RepoAttributesSchema = z.object({ }).nullable().optional(), }) -export const RepoItemSchema = z.object({ +const RepoItemSchema = z.object({ id: z.string(), attributes: RepoAttributesSchema, }) @@ -169,13 +169,7 @@ export const RemediationsCollectionSchema = z.object({ prev: z.string().nullable().optional(), }) -export const PRSchema = z.object({ - remediation_id: z.string(), - url: z.string(), - status: z.string(), -}) - -export const ApiTokenListItemSchema = z.object({ +const ApiTokenListItemSchema = z.object({ name: z.string(), created_at: z.string(), expires_at: z.string().nullable().optional(), @@ -196,7 +190,6 @@ export const ApiTokenCreatedSchema = z.object({ })) export const ApiTokensListSchema = z.array(ApiTokenListItemSchema) -export const RemediationsListSchema = z.array(RemediationSchema) export const SessionUserSchema = z.object({ user_id: z.string(), @@ -209,7 +202,7 @@ export const LoginResponseFlatSchema = z.object({ token_type: z.string().default('Bearer'), }) -export const LoginResponse2FASchema = z.object({ +const LoginResponse2FASchema = z.object({ otp_data: z.object({ secret: z.string() }), requires_2fa: z.literal(true), message: z.string(), @@ -222,5 +215,3 @@ export const Verify2FAResponseSchema = z.object({ access_token: z.string().optional(), token_type: z.string().optional(), }) - -export const LoginResponseSchema = LoginResponseFlatSchema diff --git a/src/services/auth/webRedirect.ts b/src/services/auth/webRedirect.ts index 85801b1..52d5ce1 100644 --- a/src/services/auth/webRedirect.ts +++ b/src/services/auth/webRedirect.ts @@ -71,6 +71,8 @@ export async function loginViaWebRedirect( let server: ReturnType | null = null let port = 0 + let handled = false + for (let p = PORT_MIN; p <= PORT_MAX; p++) { try { server = Bun.serve({ @@ -90,13 +92,17 @@ export async function loginViaWebRedirect( { status: 400, headers: htmlHeaders }, ) } - if (echoState !== nonce) { + // Single-use: the state nonce briefly appears in this process's argv (passed to + // open/xdg-open below), so a co-resident process on a shared host could in theory + // race to replay it — reject anything past the first valid callback. + if (echoState !== nonce || handled) { return new Response( authPage({ ok: false, title: 'Authentication failed', message: 'Security check failed (state mismatch). Run plexicus login again.' }), { status: 400, headers: htmlHeaders }, ) } + handled = true queueMicrotask(() => resolveResult({ token, email })) return new Response( authPage({ ok: true, title: "You're authenticated", message: `Signed in as ${escapeHtml(email)}.` }), diff --git a/src/services/plexicusApi.ts b/src/services/plexicusApi.ts index ba49a72..13eff11 100644 --- a/src/services/plexicusApi.ts +++ b/src/services/plexicusApi.ts @@ -66,26 +66,56 @@ function encodeCursor(offset: number): string { .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') } +// The backend stores severity Title-Cased ("Critical", "High", ...) and matches +// filters[severity] case-sensitively, but the client's internal Finding.severity is +// lowercased for display — convert back before sending. +function toBackendSeverity(severity: string): string { + return severity.charAt(0).toUpperCase() + severity.slice(1) +} + +// The client aggregates several raw backend statuses into user-facing categories +// (see STATUS_MAP in apiSchemas.ts); filters[status] matches raw values only, so +// expand each selected category back to the raw values that map to it. +const STATUS_FILTER_RAW_VALUES: Record = { + open: ['pending_input'], + enriched: ['enriched', 'issued'], + ready: ['ready'], + mitigated: ['completed', 'pr_submitted', 'solved'], +} + +// FilterModal's sort options map to raw MongoDB field names on the Finding document +// (see FindingAttributesSchema in apiSchemas.ts); the backend's `sort` query param +// follows the Zalando R137 convention (+/- prefix, single field only — see +// fastapi/config/pagination.py:parse_sort_to_db in the platform repo). +const SORT_FIELD_MAP: Record = { + priority: 'prioritization_value', + severity: 'severity_numerical', + cvss: 'cvssv3_score', + date: 'date', + epss: 'estimated_epss', +} + function buildFilterQuery(filter: FindingsFilter): URLSearchParams { const qs = new URLSearchParams() if (filter.severities?.length) { - qs.set('filters[severity]', filter.severities.join(',')) + qs.set('filters[severity]', filter.severities.map(toBackendSeverity).join(',')) } if (filter.repository_ids?.length) { qs.set('filters[repository]', filter.repository_ids.join(',')) } if (filter.statuses?.length) { - qs.set('filters[status]', filter.statuses.join(',')) + const rawStatuses = filter.statuses.flatMap(s => STATUS_FILTER_RAW_VALUES[s] ?? [s]) + qs.set('filters[status]', rawStatuses.join(',')) } if (filter.types?.length) { qs.set('filters[type]', filter.types.join(',')) } if (filter.cvss_gt !== undefined) { - qs.set('filters[cvssv3_score_gt]', String(Math.floor(filter.cvss_gt))) + qs.set('filters[cvssv3_score_gt]', String(filter.cvss_gt)) } if (filter.cvss_lt !== undefined) { - qs.set('filters[cvssv3_score_lt]', String(Math.floor(filter.cvss_lt))) + qs.set('filters[cvssv3_score_lt]', String(filter.cvss_lt)) } if (filter.priority_gt !== undefined) { qs.set('filters[priority_gt]', String(filter.priority_gt)) @@ -99,6 +129,9 @@ function buildFilterQuery(filter: FindingsFilter): URLSearchParams { if (filter.policy_names?.length) { qs.set('filters[policy_name]', filter.policy_names.join(',')) } + // filters[language]/[category] are case-sensitive exact matches server-side + // (fastapi/utils/finding.py), and unlike severity there's no fixed casing convention — + // stored values are whatever each scanner tool emits, so no client-side transform is safe here. if (filter.languages?.length) { qs.set('filters[language]', filter.languages.join(',')) } @@ -111,6 +144,10 @@ function buildFilterQuery(filter: FindingsFilter): URLSearchParams { if (filter.finding_type) { qs.set('finding_type', filter.finding_type) } + if (filter.sort_by) { + const field = SORT_FIELD_MAP[filter.sort_by] ?? filter.sort_by + qs.set('sort', `${filter.sort_dir === 'asc' ? '+' : '-'}${field}`) + } return qs } @@ -367,12 +404,10 @@ export class PlexicusApi { return this.fetch('POST', '/users/me/api-tokens', { name }, ApiTokenCreatedSchema) } - // FIXME-11: GitLab and Bitbucket OAuth endpoints don't exist in backend yet. - // Only 'github' is valid until the backend exposes equivalent routes. - async getOAuthUrl(provider: 'github'): Promise { + async getOAuthUrl(provider: string): Promise { if (MOCK_MODE) return `https://github.com/login/oauth/authorize?mock=1` - const data = await this.fetch<{ oauth_url: string }>('GET', '/oauth/github/authorization', undefined, undefined, 'raw') - return data.oauth_url + const data = await this.fetch<{ authorization_url: string }>('GET', `/vulnerability-tool/auth/${provider}`, undefined, undefined, 'raw') + return data.authorization_url } async checkScmValidity(): Promise> { @@ -401,9 +436,12 @@ export class PlexicusApi { // fetch() auto-unwraps { success, data: {...} } → raw IS { repositories: [...], total_count, ... } const raw = await this.fetch('GET', `/vulnerability-tool/repositories/${provider}?${qs}`) const envelope = raw as Record - const repos: any[] = Array.isArray(envelope?.repositories) + const rawRepos: any[] = Array.isArray(envelope?.repositories) ? envelope.repositories : (Array.isArray(raw) ? raw : []) + // Third-party SCM responses aren't Zod-validated here (shape varies per provider) — + // guard against null/non-object entries so one bad row doesn't crash the whole page. + const repos = rawRepos.filter((r): r is Record => r != null && typeof r === 'object') allRepos.push(...repos.map(r => ({ id: String(r.uuid ?? r.id ?? ''), name: String(r.slug ?? r.name ?? ''), @@ -412,7 +450,7 @@ export class PlexicusApi { clone_url: r.clone_url ?? r.http_url_to_repo ?? undefined, private: r.private ?? r.is_private ?? r.visibility === 'private', } as ScmRepo))) - if (repos.length < PER_PAGE) break + if (rawRepos.length < PER_PAGE) break page++ } return allRepos @@ -420,32 +458,27 @@ export class PlexicusApi { async connectWithToken(provider: string, token: string, baseUrl?: string): Promise { if (MOCK_MODE) return - // Use PUT /client/plugin/{provider} — same path the web frontend uses + // PUT /clients/self/plugins/{plugin_name} per the documented Platform API if (provider === 'gitea') { const url = new URL(baseUrl ?? 'http://localhost:3000') const port = url.port || (url.protocol === 'https:' ? '443' : '80') - await this.fetch('PUT', '/client/plugin/gitea', { + await this.fetch('PUT', '/clients/self/plugins/gitea', { protocol: url.protocol.replace(':', ''), oauth_token: token, hosted_domain: url.hostname, port, }, undefined, 'raw') - // save_token registers the encoded token in the auth system - await this.fetch('POST', '/scm-tokens', { - token: `${url.protocol.replace(':', '')}:${token}:${url.hostname}:${port}`, - source_control: 'gitea', - }, undefined, 'raw') } else if (provider === 'gitlab') { - await this.fetch('PUT', '/client/plugin/gitlab', { + await this.fetch('PUT', '/clients/self/plugins/gitlab', { oauth_token: token, hosted_url: baseUrl ?? 'https://gitlab.com', }, undefined, 'raw') } else if (provider === 'bitbucket') { - await this.fetch('PUT', '/client/plugin/bitbucket_cloud', { + await this.fetch('PUT', '/clients/self/plugins/bitbucket_cloud', { oauth_token: token, }, undefined, 'raw') } else { - await this.fetch('PUT', `/client/plugin/${provider}`, { + await this.fetch('PUT', `/clients/self/plugins/${provider}`, { oauth_token: token, }, undefined, 'raw') } @@ -459,7 +492,6 @@ export class PlexicusApi { async importRepositories(repos: ScmRepo[], sourceControl: string): Promise { if (MOCK_MODE) return - // FIXME-16: body shape changed -- backend expects {data: [...], source_control} const data = repos.map(r => ({ nickname: r.name, uri: r.html_url ?? r.clone_url ?? '', diff --git a/src/services/websocket.ts b/src/services/websocket.ts index 1a76c78..eb54e34 100644 --- a/src/services/websocket.ts +++ b/src/services/websocket.ts @@ -1,4 +1,4 @@ -export interface WsMessage { +interface WsMessage { client_id?: string finding_id?: string message?: string @@ -42,6 +42,9 @@ class PlexicusWebSocket { private _connect(): void { if (!this.shouldReconnect) return try { + // Token must go in the query string: the backend's WS route (fastapi/routes/socket.py) + // declares `token: str = Query(...)` and calls decode_and_validate_scopes directly — + // it never reads websocket.headers, so a header-based alternative isn't available server-side. const url = `${this.wsUrl}/ws/${this.clientId}?token=${this.token}` this.ws = new WebSocket(url) diff --git a/src/state/AppState.tsx b/src/state/AppState.tsx index 2c1f160..98a8966 100644 --- a/src/state/AppState.tsx +++ b/src/state/AppState.tsx @@ -1,5 +1,5 @@ import React, { createContext, useContext, useReducer, type ReactNode } from 'react' -import type { Finding, Repository, Remediation, Panel, InputMode, SessionUser, StatusJob, Screen } from '../types.js' +import type { Finding, Repository, Remediation, InputMode, SessionUser, StatusJob, Screen } from '../types.js' import type { Action, FindingsFilter } from './actions.js' export interface AppState { @@ -16,7 +16,6 @@ export interface AppState { repos: Repository[] reposLoading: boolean remediations: Record - activePanel: Panel inputMode: InputMode fuzzyOpen: boolean filterOpen: boolean @@ -45,7 +44,6 @@ const initialState: AppState = { repos: [], reposLoading: false, remediations: {}, - activePanel: 'repos', inputMode: 'navigation', fuzzyOpen: false, filterOpen: false, @@ -103,9 +101,6 @@ function reducer(state: AppState, action: Action): AppState { remediations: { ...state.remediations, [action.payload.finding_id]: action.payload }, } - case 'ui/setPanel': - return { ...state, activePanel: action.payload } - case 'ui/setTheme': return { ...state, theme: action.payload } @@ -133,6 +128,12 @@ function reducer(state: AppState, action: Action): AppState { case 'scm/close': return { ...state, scmFlowOpen: false, inputMode: 'navigation' } + case 'help/open': + return { ...state, inputMode: 'help' } + + case 'help/close': + return { ...state, inputMode: 'navigation' } + case 'status/open': return { ...state, activeStatusJob: action.payload } @@ -153,16 +154,14 @@ function reducer(state: AppState, action: Action): AppState { case 'nav/pushScreen': { const newStack = [...state.screenStack, action.payload] - const panel: Panel = action.payload === 'repos' ? 'repos' : 'findings' - return { ...state, screen: action.payload, screenStack: newStack, activePanel: panel } + return { ...state, screen: action.payload, screenStack: newStack } } case 'nav/popScreen': { if (state.screenStack.length <= 1) return state const newStack = state.screenStack.slice(0, -1) - const prev = newStack[newStack.length - 1] - const panel: Panel = prev === 'repos' ? 'repos' : 'findings' - return { ...state, screen: prev, screenStack: newStack, activePanel: panel } + const prev = newStack[newStack.length - 1]! + return { ...state, screen: prev, screenStack: newStack } } case 'repo/select': diff --git a/src/state/actions.ts b/src/state/actions.ts index b3bd269..194a8a5 100644 --- a/src/state/actions.ts +++ b/src/state/actions.ts @@ -1,4 +1,4 @@ -import type { Finding, FindingSeverity, FindingStatus, FindingType, Repository, Remediation, Panel, InputMode, SessionUser, StatusJob, Screen } from '../types.js' +import type { Finding, FindingSeverity, FindingStatus, FindingType, Repository, Remediation, InputMode, SessionUser, StatusJob, Screen } from '../types.js' export interface FindingsFilter { severities?: FindingSeverity[] @@ -32,7 +32,6 @@ export type Action = | { type: 'repos/set'; payload: Repository[] } | { type: 'repos/loading'; payload: boolean } | { type: 'remediation/set'; payload: Remediation } - | { type: 'ui/setPanel'; payload: Panel } | { type: 'ui/setTheme'; payload: 'dark' | 'light' | 'plexicus' } | { type: 'ui/setError'; payload: string | null } | { type: 'ui/setNotification'; payload: string | null } @@ -42,6 +41,8 @@ export type Action = | { type: 'filter/close' } | { type: 'scm/open' } | { type: 'scm/close' } + | { type: 'help/open' } + | { type: 'help/close' } | { type: 'status/open'; payload: StatusJob } | { type: 'status/update'; payload: Partial & { id: string } } | { type: 'status/close' } diff --git a/src/types.ts b/src/types.ts index 72244dc..a970d8b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -72,12 +72,6 @@ export interface Remediation { error_message?: string | null } -export interface PR { - remediation_id: string - url: string - status: string -} - export interface ApiToken { id: string name: string @@ -98,9 +92,7 @@ export interface SessionUser { email: string } -export type Panel = 'findings' | 'repos' - -export type InputMode = 'navigation' | 'repl' | 'login' | 'filter' | 'scm' +export type InputMode = 'navigation' | 'repl' | 'login' | 'filter' | 'scm' | 'help' export type ScmProvider = 'github' | 'gitlab' | 'bitbucket' | 'gitea' diff --git a/src/utils/text.ts b/src/utils/text.ts new file mode 100644 index 0000000..7ae60fb --- /dev/null +++ b/src/utils/text.ts @@ -0,0 +1,18 @@ +const TAB_WIDTH = 4 + +// Ink measures text width per-character and doesn't special-case '\t', so a raw tab +// desyncs Ink's wrap/border layout from how terminals actually render tab stops. +// Expand tabs to spaces before handing code/diff lines to so measured width +// matches rendered width. +export function expandTabs(line: string, tabWidth = TAB_WIDTH): string { + let result = '' + for (const ch of line) { + if (ch === '\t') { + const pad = tabWidth - (result.length % tabWidth) + result += ' '.repeat(pad) + } else { + result += ch + } + } + return result +} From a90982b3a555d57301a1cd2d6be473cf0ceb60fe Mon Sep 17 00:00:00 2001 From: Jose Ramon Palanco Date: Fri, 31 Jul 2026 22:59:35 +0200 Subject: [PATCH 3/3] test: cover plexicusApi's real fetch, sort/filter query building, and remediation-shape normalization The existing plexicusApi.test.ts only exercises MOCK_PLEXICUS=1 fixture paths, so fetch()'s error handling, buildFilterQuery()'s query-param construction, and getRemediations()'s several response- shape normalizations had zero coverage. Mock global fetch directly (bypassing MOCK_MODE via a cache-busting dynamic import) to test the real code paths: 401/error/network-failure handling, severity/status/ CVSS/sort query serialization, remediation envelope normalization, the 2FA login branch, getScmRepos' per-provider field mapping and null-guarding, and the new nullable-field schema fallbacks. --- tests/services/plexicusApi.live.test.ts | 263 ++++++++++++++++++++++++ 1 file changed, 263 insertions(+) create mode 100644 tests/services/plexicusApi.live.test.ts diff --git a/tests/services/plexicusApi.live.test.ts b/tests/services/plexicusApi.live.test.ts new file mode 100644 index 0000000..8116aca --- /dev/null +++ b/tests/services/plexicusApi.live.test.ts @@ -0,0 +1,263 @@ +import { describe, it, expect, beforeAll, beforeEach, afterEach, mock } from 'bun:test' +import type { PlexicusApi as PlexicusApiType } from '../../src/services/plexicusApi.js' + +// Ensure the module's MOCK_MODE constant (captured at import time) is false, so +// these tests exercise the real fetch()/buildFilterQuery()/getRemediations() code +// paths instead of the fixture short-circuits covered by plexicusApi.test.ts. +delete process.env.MOCK_PLEXICUS + +let PlexicusApi: typeof PlexicusApiType +let PlexicusApiError: new (...args: any[]) => Error & { statusCode: number; endpoint: string } +let PlexicusAuthError: new (...args: any[]) => Error + +beforeAll(async () => { + // Cache-busting query string: plexicusApi.test.ts also imports this module (with + // MOCK_PLEXICUS='1') in the same test run, and dynamic import() caches by resolved + // specifier — without this we'd get that file's already-evaluated MOCK_MODE=true instance. + // @ts-expect-error — query string is a runtime-only cache-busting trick; tsc can't resolve it + ;({ PlexicusApi } = await import('../../src/services/plexicusApi.js?live-fetch-test')) + ;({ PlexicusApiError, PlexicusAuthError } = await import('../../src/utils/errors.js')) +}) + +describe('PlexicusApi (live fetch path)', () => { + let originalFetch: typeof fetch + let calls: { url: string }[] + let api: PlexicusApiType + + beforeEach(() => { + originalFetch = globalThis.fetch + calls = [] + api = new PlexicusApi({ baseUrl: 'https://api.example.com', token: 'tok' }) + }) + + afterEach(() => { + globalThis.fetch = originalFetch + }) + + function mockFetchOnce(response: Response) { + globalThis.fetch = mock(async (url: string | URL | Request) => { + calls.push({ url: String(url) }) + return response + }) as unknown as typeof fetch + } + + describe('buildFilterQuery via getFindings', () => { + it('title-cases severities to match the backend', async () => { + mockFetchOnce(new Response(JSON.stringify({ items: [], total: 0 }), { status: 200 })) + await api.getFindings({ severities: ['critical', 'high'] }) + const url = new URL(calls[0]!.url) + expect(url.searchParams.get('filters[severity]')).toBe('Critical,High') + }) + + it('expands aggregated statuses to raw backend values', async () => { + mockFetchOnce(new Response(JSON.stringify({ items: [], total: 0 }), { status: 200 })) + await api.getFindings({ statuses: ['open', 'mitigated'] }) + const url = new URL(calls[0]!.url) + expect(url.searchParams.get('filters[status]')).toBe('pending_input,completed,pr_submitted,solved') + }) + + it('preserves CVSS decimal precision instead of flooring', async () => { + mockFetchOnce(new Response(JSON.stringify({ items: [], total: 0 }), { status: 200 })) + await api.getFindings({ cvss_gt: 7.5, cvss_lt: 9.2 }) + const url = new URL(calls[0]!.url) + expect(url.searchParams.get('filters[cvssv3_score_gt]')).toBe('7.5') + expect(url.searchParams.get('filters[cvssv3_score_lt]')).toBe('9.2') + }) + + it('maps sort_by to the backend field name with a direction prefix', async () => { + mockFetchOnce(new Response(JSON.stringify({ items: [], total: 0 }), { status: 200 })) + await api.getFindings({ sort_by: 'cvss', sort_dir: 'asc' }) + const url = new URL(calls[0]!.url) + expect(url.searchParams.get('sort')).toBe('+cvssv3_score') + }) + + it('defaults sort direction to descending', async () => { + mockFetchOnce(new Response(JSON.stringify({ items: [], total: 0 }), { status: 200 })) + await api.getFindings({ sort_by: 'priority' }) + const url = new URL(calls[0]!.url) + expect(url.searchParams.get('sort')).toBe('-prioritization_value') + }) + + it('omits the sort param entirely when no sort_by is given', async () => { + mockFetchOnce(new Response(JSON.stringify({ items: [], total: 0 }), { status: 200 })) + await api.getFindings({}) + const url = new URL(calls[0]!.url) + expect(url.searchParams.has('sort')).toBe(false) + }) + }) + + describe('fetch() error handling', () => { + it('throws PlexicusAuthError on a 401 response', async () => { + mockFetchOnce(new Response(JSON.stringify({ detail: 'Token expired' }), { status: 401 })) + await expect(api.getFinding('f-1')).rejects.toBeInstanceOf(PlexicusAuthError) + }) + + it('throws PlexicusApiError with the status code on a non-ok response', async () => { + mockFetchOnce(new Response('Internal error', { status: 500 })) + await expect(api.getFinding('f-1')).rejects.toMatchObject({ statusCode: 500 }) + }) + + it('wraps network-level fetch failures in PlexicusApiError', async () => { + globalThis.fetch = mock(async () => { throw new TypeError('fetch failed') }) as unknown as typeof fetch + await expect(api.getFinding('f-1')).rejects.toBeInstanceOf(PlexicusApiError) + }) + + it('returns undefined for empty response bodies', async () => { + mockFetchOnce(new Response('', { status: 204 })) + const result = await api.markMitigated('f-1') + expect(result).toBeUndefined() + }) + }) + + describe('getRemediations response-shape normalization', () => { + it('returns [] on 404 (no remediation created yet)', async () => { + mockFetchOnce(new Response('Not found', { status: 404 })) + const result = await api.getRemediations('f-1') + expect(result).toEqual([]) + }) + + it('normalizes a bare array response', async () => { + mockFetchOnce(new Response(JSON.stringify([{ _id: 'r1', finding_id: 'f-1', status: 'ready' }]), { status: 200 })) + const result = await api.getRemediations('f-1') + expect(result).toHaveLength(1) + expect(result[0]!.id).toBe('r1') + }) + + it('normalizes a {code, result} envelope', async () => { + mockFetchOnce(new Response(JSON.stringify({ code: 200, result: { _id: 'r2', finding_id: 'f-1', status: 'pending' } }), { status: 200 })) + const result = await api.getRemediations('f-1') + expect(result).toHaveLength(1) + expect(result[0]!.id).toBe('r2') + }) + + it('normalizes a {data: [...]} envelope', async () => { + mockFetchOnce(new Response(JSON.stringify({ data: [{ _id: 'r3', finding_id: 'f-1' }] }), { status: 200 })) + const result = await api.getRemediations('f-1') + expect(result).toHaveLength(1) + expect(result[0]!.id).toBe('r3') + }) + + it('normalizes a single object keyed by _id', async () => { + mockFetchOnce(new Response(JSON.stringify({ _id: 'r4', finding_id: 'f-1', status: 'error' }), { status: 200 })) + const result = await api.getRemediations('f-1') + expect(result).toHaveLength(1) + expect(result[0]!.id).toBe('r4') + }) + + it('returns [] when the response shape cannot be normalized', async () => { + mockFetchOnce(new Response(JSON.stringify({ totally: 'unrecognized' }), { status: 200 })) + const result = await api.getRemediations('f-1') + expect(result).toEqual([]) + }) + }) + + describe('login() / verify2FA() 2FA flow', () => { + it('returns kind=ok for a flat access_token response', async () => { + mockFetchOnce(new Response(JSON.stringify({ access_token: 'tok-1', token_type: 'Bearer' }), { status: 200 })) + const result = await api.login('a@b.com', 'pw') + expect(result).toEqual({ kind: 'ok', access_token: 'tok-1', token_type: 'Bearer' }) + }) + + it('returns kind=2fa with the OTP secret when the backend requires it', async () => { + mockFetchOnce(new Response(JSON.stringify({ + requires_2fa: true, + message: 'OTP required', + otp_data: { secret: 'JBSWY3DPEHPK3PXP' }, + }), { status: 200 })) + const result = await api.login('a@b.com', 'pw') + expect(result).toEqual({ kind: '2fa', secret: 'JBSWY3DPEHPK3PXP' }) + }) + + it('verify2FA returns the access token on success', async () => { + mockFetchOnce(new Response(JSON.stringify({ verify_otp: true, access_token: 'tok-2' }), { status: 200 })) + const token = await api.verify2FA('a@b.com', '123456') + expect(token).toBe('tok-2') + }) + + it('verify2FA throws PlexicusAuthError when the OTP is rejected', async () => { + mockFetchOnce(new Response(JSON.stringify({ verify_otp: false }), { status: 200 })) + await expect(api.verify2FA('a@b.com', '000000')).rejects.toBeInstanceOf(PlexicusAuthError) + }) + + it('verify2FA throws PlexicusAuthError when verified but no token is returned', async () => { + mockFetchOnce(new Response(JSON.stringify({ verify_otp: true }), { status: 200 })) + await expect(api.verify2FA('a@b.com', '123456')).rejects.toBeInstanceOf(PlexicusAuthError) + }) + }) + + describe('getScmRepos()', () => { + it('maps a GitHub-shaped repo (id/full_name/html_url/clone_url/private)', async () => { + mockFetchOnce(new Response(JSON.stringify({ + repositories: [{ id: 42, full_name: 'org/repo', html_url: 'https://github.com/org/repo', clone_url: 'https://github.com/org/repo.git', private: true }], + }), { status: 200 })) + const repos = await api.getScmRepos('github') + expect(repos).toEqual([{ + id: '42', name: '', full_name: 'org/repo', + html_url: 'https://github.com/org/repo', clone_url: 'https://github.com/org/repo.git', private: true, + }]) + }) + + it('maps a GitLab-shaped repo (web_url/http_url_to_repo/name_with_namespace/is_private)', async () => { + mockFetchOnce(new Response(JSON.stringify({ + repositories: [{ id: 7, name: 'repo', name_with_namespace: 'group/repo', web_url: 'https://gitlab.com/group/repo', http_url_to_repo: 'https://gitlab.com/group/repo.git', is_private: true }], + }), { status: 200 })) + const repos = await api.getScmRepos('gitlab') + expect(repos).toEqual([{ + id: '7', name: 'repo', full_name: 'group/repo', + html_url: 'https://gitlab.com/group/repo', clone_url: 'https://gitlab.com/group/repo.git', private: true, + }]) + }) + + it('filters out null/non-object entries without crashing', async () => { + mockFetchOnce(new Response(JSON.stringify({ + repositories: [null, { id: 1, name: 'ok-repo' }, undefined], + }), { status: 200 })) + const repos = await api.getScmRepos('gitea') + expect(repos).toHaveLength(1) + expect(repos[0]!.name).toBe('ok-repo') + }) + + it('paginates using the raw page size, not the null-filtered count', async () => { + let requestCount = 0 + globalThis.fetch = mock(async (url: string | URL | Request) => { + requestCount++ + const page = new URL(String(url)).searchParams.get('page') + if (page === '1') { + // 100 raw items (including a null), matching PER_PAGE — must trigger page 2 + const items = Array.from({ length: 99 }, (_, i) => ({ id: i, name: `repo-${i}` })) + return new Response(JSON.stringify({ repositories: [null, ...items] }), { status: 200 }) + } + return new Response(JSON.stringify({ repositories: [{ id: 100, name: 'repo-100' }] }), { status: 200 }) + }) as unknown as typeof fetch + + const repos = await api.getScmRepos('github') + expect(requestCount).toBe(2) + expect(repos).toHaveLength(100) + expect(repos.at(-1)!.name).toBe('repo-100') + }) + }) + + describe('schema-fallback defaults for null/missing fields', () => { + it('getRepositories falls back nickname/uri/active/repo_type/status when null', async () => { + mockFetchOnce(new Response(JSON.stringify({ + items: [{ id: 'r1', attributes: { nickname: null, uri: null, active: null, repo_type: null, status: null } }], + total: 1, + }), { status: 200 })) + const { repos } = await api.getRepositories() + expect(repos[0]).toMatchObject({ + id: 'r1', nickname: 'unknown-repo', uri: '', active: true, repo_type: 'github', status: 'active', + }) + }) + + it('getFindings falls back title/date/repo_id when null', async () => { + mockFetchOnce(new Response(JSON.stringify({ + items: [{ id: 'f1', attributes: { + title: null, severity: 'high', status: 'open', repo_id: null, date: null, + } }], + total: 1, + }), { status: 200 })) + const { findings } = await api.getFindings() + expect(findings[0]).toMatchObject({ id: 'f1', title: 'Untitled finding', date: '', repo_id: '' }) + }) + }) +})