Skip to content

Commit d98b0e1

Browse files
TMHSDigitalclaude
andcommitted
fix(tui): write the same files as the CLI; prefill from env and config
- A TUI CSV gets the takeover_candidate column when CNAME records are requested, and a JSONL file ends with the run-quality summary. - The summary builder moves to internal/report, shared by the CLI and the TUI, so both produce the same report. - tui.Start takes Options: the version for the report, and SUBENUM_* / config-file values that pre-fill the form over the last session's. Fixes #118 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent da30a54 commit d98b0e1

10 files changed

Lines changed: 343 additions & 91 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
3030
- The minimum Go version is now 1.26 (`go 1.26.0` in go.mod), required by current `golang.org/x/sys` and `golang.org/x/text`; both were bumped and `govulncheck -show verbose` now reports no vulnerable modules. Dependabot also updates indirect modules, and CI lints with errorlint, nilerr, contextcheck, noctx, copyloopvar, usestdlibvars and revive, with errcheck exemptions narrowed to stdout prints (#83).
3131

3232
### Fixed
33+
- The TUI writes the same files as the CLI: a CSV gets the `takeover_candidate` column when CNAME records are requested, and a JSONL file ends with the run-quality summary line. Its form starts from `SUBENUM_*` and config-file values, over the values remembered from the last session. The report is built by a new `internal/report` package that both front ends share (#118).
3334
- Shell completions: `-simulate-zone`, `-seeds`, `-resume` and `-state` complete file names in every shell (fish previously disabled file completion for them), bash and fish complete the shell name after `completion`, and the PowerShell completer reads the previous word, so file flags fall back to path completion and `-format`/`-type` offer their values. A test fails when a flag that takes a file is missing from the list, and CI checks that every generated script parses in its shell (#117).
3435
- New `-o` and `-stats` files get 0666 less the umask, as `os.Create` would, instead of a fixed 0644, so results stay private under `umask 077`; an `-o` path that is a symlink keeps the link and replaces the file it points at, instead of turning into a regular file (#119).
3536
- Takeover hints resolve each CNAME target once per scan instead of once per result, so hundreds of names aliased to the same CDN or SaaS host no longer spend a query and a `-rate` slot each; concurrent results for one target share the lookup, and an inconclusive one is retried by the next name (#121).

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,7 @@ Settings you repeat on every run can live in a config file or the environment. P
394394

395395
- The config file is `config.json` in your user config directory (`~/.config/subenum/` on Linux, `~/Library/Application Support/subenum/` on macOS, `%AppData%\subenum\` on Windows), or the path in `SUBENUM_CONFIG`. Keys are flag names; values are strings, numbers or booleans, and `exclude` and `type` also take a list of strings.
396396
- Each flag also reads `SUBENUM_<FLAG>`, upper-cased with dashes as underscores: `SUBENUM_DNS_SERVER`, `SUBENUM_RATE`, `SUBENUM_T`.
397+
- The TUI (`-tui`) starts its form from these values too, over the values it remembers from its last session.
397398
- `subenum -print-config` shows every effective setting and where it came from (`flag`, `env`, `config` or `default`). It, `-h` and `-version` still work when a value is bad, so you can find it; a scan refuses to start and names every bad value.
398399

399400
Shell completions and a man page are generated from the same flags, and release archives include them under `completions/` and `man/`:

‎docs/cli.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ Settings you repeat on every run can live in the environment or a config file. P
3535

3636
- Each flag reads `SUBENUM_<FLAG>`, upper-cased with dashes as underscores: `SUBENUM_DNS_SERVER`, `SUBENUM_RATE`, `SUBENUM_T`.
3737
- The config file is `config.json` in your user config directory (`~/.config/subenum/` on Linux, `~/Library/Application Support/subenum/` on macOS, `%AppData%\subenum\` on Windows), or the path in `SUBENUM_CONFIG`. Keys are flag names; values are strings, numbers or booleans, and `exclude` and `type` also take a list of strings. Mode flags (`tui`, `version`, `print-config`, `resume`) are command-line only.
38+
- The TUI (`-tui`) starts its form from these values too, over the values it remembers from its last session.
3839
- `subenum -print-config` prints every effective setting and where it came from: `flag`, `env`, `config` or `default`. With a bad value, `-h`, `-version` and `-print-config` still run and warn; a scan refuses to start and names every bad value.
3940
- When `-attempts` and the deprecated `-retries` both have a value, the one from the higher-precedence source wins; both on the command line (or both from the same file) is an error.
4041

‎internal/report/report.go‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
// Package report builds the run-quality report (#70) from finished scans.
2+
// The CLI and the TUI share it, so a -format jsonl file ends with the same
3+
// summary line whichever front end wrote it (#118).
4+
package report
5+
6+
import (
7+
"fmt"
8+
"time"
9+
10+
"github.com/TMHSDigital/subenum/internal/dns"
11+
"github.com/TMHSDigital/subenum/internal/output"
12+
"github.com/TMHSDigital/subenum/internal/scan"
13+
)
14+
15+
// Run describes a run for New.
16+
type Run struct {
17+
Version string // the tool version
18+
Started time.Time
19+
Simulated bool
20+
Seed uint64 // reported for simulated runs
21+
Resolver string // -dns-server, reported for real runs
22+
Zone string // -simulate-zone, if any
23+
RateLimit int
24+
}
25+
26+
// New starts a summary for a run; add targets with Finish.
27+
func New(r Run) output.Summary {
28+
s := output.Summary{
29+
Type: "summary",
30+
Schema: output.SummarySchema,
31+
Tool: "subenum",
32+
Version: r.Version,
33+
Started: r.Started.UTC().Truncate(time.Millisecond),
34+
Simulated: r.Simulated,
35+
RateLimit: r.RateLimit,
36+
Verdict: scan.VerdictComplete,
37+
}
38+
if r.Simulated {
39+
s.Seed = r.Seed
40+
} else {
41+
s.Resolver = r.Resolver
42+
s.Transport = dns.Transport(r.Resolver)
43+
s.Zone = r.Zone
44+
}
45+
return s
46+
}
47+
48+
// Target summarizes one domain's scan. status is "ok", "failed",
49+
// "interrupted", "skipped" or "" (never run); done reports whether the scan
50+
// sent its final event, final.
51+
func Target(domain, status, errMsg string, done bool, final scan.Event) output.TargetSummary {
52+
t := output.TargetSummary{Domain: domain, Status: status, Error: errMsg}
53+
switch {
54+
case status == "" || status == "skipped":
55+
if t.Status == "" {
56+
t.Status = "not_run"
57+
}
58+
t.Verdict, t.Reason = scan.VerdictUnreliable, "not scanned"
59+
if status == "skipped" {
60+
t.Reason = "not scanned: an earlier target's resolver looked overloaded"
61+
}
62+
return t
63+
case !done:
64+
reason := errMsg
65+
if reason == "" {
66+
reason = "the scan did not run to completion"
67+
}
68+
t.Verdict, t.Reason = scan.VerdictUnreliable, reason
69+
return t
70+
}
71+
st := final.Stats
72+
t.Processed, t.Total, t.Found = final.Processed, final.Total, final.Found
73+
t.Outcomes = output.Outcomes{
74+
Resolved: st.Found,
75+
NXDomain: st.NXDomain,
76+
Timeout: st.Timeout,
77+
Refused: st.Refused,
78+
Other: st.Other,
79+
WildcardFiltered: st.WildcardFiltered,
80+
Excluded: st.Excluded,
81+
}
82+
t.QueriesSent = st.QueriesSent
83+
t.SkippedCap = st.Skipped
84+
t.Takeover = st.Takeover
85+
t.PoolHits, t.Confirmed, t.Unconfirmed = st.PoolHits, st.Confirmed, st.Unconfirmed
86+
t.Wildcard = st.Wildcard
87+
if st.Wildcard {
88+
t.Fingerprint = st.Fingerprint
89+
}
90+
t.Verdict, t.Reason = st.Verdict(status == "interrupted")
91+
if st.Wildcard && t.Verdict == scan.VerdictComplete {
92+
t.Reason += fmt.Sprintf("; wildcard zone, %d answers filtered by fingerprint", st.WildcardFiltered)
93+
}
94+
return t
95+
}
96+
97+
// Finish adds the targets to s, sets the overall verdict (the worst
98+
// target's) and the achieved query rate over elapsed.
99+
func Finish(s *output.Summary, targets []output.TargetSummary, elapsed time.Duration) {
100+
s.DurationMs = elapsed.Milliseconds()
101+
s.Targets = make([]output.TargetSummary, 0, len(targets))
102+
worst := -1
103+
for i, t := range targets {
104+
s.QueriesSent += t.QueriesSent
105+
if worst < 0 || scan.VerdictRank(t.Verdict) > scan.VerdictRank(targets[worst].Verdict) {
106+
worst = i
107+
}
108+
s.Targets = append(s.Targets, t)
109+
}
110+
if worst >= 0 {
111+
w := targets[worst]
112+
s.Verdict, s.Reason = w.Verdict, w.Reason
113+
if len(targets) > 1 {
114+
s.Reason = w.Domain + ": " + w.Reason
115+
}
116+
}
117+
if secs := elapsed.Seconds(); secs > 0 {
118+
s.AchievedQPS = float64(int(float64(s.QueriesSent)/secs*10)) / 10
119+
}
120+
}

‎internal/tui/config.go‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/json"
55
"os"
66
"path/filepath"
7+
"strconv"
78
"strings"
89
)
910

@@ -103,3 +104,49 @@ func saveConfig(fv formValues) error {
103104
}
104105
return cerr
105106
}
107+
108+
// withSettings overlays flag values from SUBENUM_* variables or the config
109+
// file (keyed by flag name) on the remembered form values (#118).
110+
func withSettings(sc savedConfig, settings map[string]string) savedConfig {
111+
for name, v := range settings {
112+
n, _ := strconv.Atoi(v)
113+
b, _ := strconv.ParseBool(v)
114+
switch name {
115+
case "w":
116+
sc.Wordlist = v
117+
case "dns-server":
118+
sc.DNSServer = v
119+
case "t":
120+
sc.Concurrency = n
121+
case "timeout":
122+
sc.TimeoutMs = n
123+
case "attempts":
124+
sc.Attempts = n
125+
case "hit-rate":
126+
sc.HitRate = n
127+
case "type":
128+
sc.Types = v
129+
case "depth":
130+
sc.Depth = n
131+
case "rate":
132+
sc.Rate = n
133+
case "max-queries":
134+
sc.MaxQueries = n
135+
case "exclude":
136+
sc.Exclude = v
137+
case "o":
138+
sc.Output = v
139+
case "format":
140+
sc.Format = v
141+
case "simulate":
142+
sc.Simulate = b
143+
case "force":
144+
sc.Force = b
145+
case "recursive":
146+
sc.Recursive = b
147+
case "no-abort":
148+
sc.NoAbort = b
149+
}
150+
}
151+
return sc
152+
}

‎internal/tui/model.go‎

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,13 @@ import (
55
"context"
66
"fmt"
77
"math/rand/v2"
8+
"slices"
9+
"time"
810

911
tea "github.com/charmbracelet/bubbletea"
1012

1113
"github.com/TMHSDigital/subenum/internal/output"
14+
"github.com/TMHSDigital/subenum/internal/report"
1215
"github.com/TMHSDigital/subenum/internal/scan"
1316
"github.com/TMHSDigital/subenum/internal/wordlist"
1417
)
@@ -35,21 +38,37 @@ type Model struct {
3538
// is configured on the form.
3639
out *output.Writer
3740
outFile *output.File
41+
42+
opts Options
43+
vals formValues // the running scan's settings, for its report
44+
seed uint64
45+
started time.Time
46+
}
47+
48+
// Options configure the TUI.
49+
type Options struct {
50+
// Version is reported in the run-quality summary.
51+
Version string
52+
// Settings are flag values from SUBENUM_* variables or the config file,
53+
// keyed by flag name. They pre-fill the form over its remembered values,
54+
// as they override built-in defaults on the command line (#118).
55+
Settings map[string]string
3856
}
3957

4058
// New creates the root model starting on the form screen.
41-
func New() Model {
59+
func New(opts Options) Model {
4260
saved, _ := loadSavedConfig()
4361
return Model{
4462
state: stateForm,
45-
form: newFormModel(saved),
63+
form: newFormModel(withSettings(saved, opts.Settings)),
64+
opts: opts,
4665
}
4766
}
4867

4968
// Start runs the TUI and returns an exit code: 1 if the TUI itself failed or
5069
// the last scan failed (#55), else 0.
51-
func Start() int {
52-
p := tea.NewProgram(New(), tea.WithAltScreen())
70+
func Start(opts Options) int {
71+
p := tea.NewProgram(New(opts), tea.WithAltScreen())
5372
final, err := p.Run()
5473
if err != nil {
5574
return 1
@@ -156,7 +175,11 @@ func (m Model) beginScan(vals formValues, entries []string, skipped int) (tea.Mo
156175
m.outFile = f
157176
m.out = output.NewFile(f.Writer, vals.simulate, vals.format)
158177
m.out.SetSeed(seed)
178+
// Same file shape as the CLI's: a takeover column when CNAME
179+
// records are requested (#118).
180+
m.out.SetTakeoverColumn(slices.Contains(vals.recordTypes, "CNAME"))
159181
}
182+
m.vals, m.seed, m.started = vals, seed, time.Now()
160183

161184
m.state = stateScan
162185
m.scanView = newScanViewModel(m.width, m.height, vals.simulate)
@@ -213,7 +236,7 @@ func (m Model) updateScan(msg tea.Msg) (tea.Model, tea.Cmd) {
213236
// Restore last-used values so the user doesn't re-type everything.
214237
saved, _ := loadSavedConfig()
215238
m.state = stateForm
216-
m.form = newFormModel(saved)
239+
m.form = newFormModel(withSettings(saved, m.opts.Settings))
217240
m.events = nil
218241
return m, m.form.initCmd()
219242
}
@@ -240,7 +263,11 @@ func (m Model) updateScan(msg tea.Msg) (tea.Model, tea.Cmd) {
240263
case doneMsg:
241264
// Successful completion (including user abort, which still drains and
242265
// emits EventDone): finalize structured output so buffered JSON/CSV is
243-
// written and partial results are flushed.
266+
// written and partial results are flushed. A JSONL file ends with the
267+
// run-quality summary, as the CLI's does (#118).
268+
if m.out != nil {
269+
m.out.Summary(m.summary(msg))
270+
}
244271
m.reportOutputErr(m.finalizeOutput(true))
245272
return m, svCmd
246273
case abortedMsg:
@@ -282,6 +309,28 @@ func (m *Model) finalizeOutput(finish bool) error {
282309
return firstErr
283310
}
284311

312+
// summary builds the run-quality report for the finished scan.
313+
func (m *Model) summary(done doneMsg) output.Summary {
314+
s := report.New(report.Run{
315+
Version: m.opts.Version,
316+
Started: m.started,
317+
Simulated: m.vals.simulate,
318+
Seed: m.seed,
319+
Resolver: m.vals.dnsServer,
320+
RateLimit: m.vals.rate,
321+
})
322+
status := "ok"
323+
switch {
324+
case m.scanView.failed():
325+
status = "failed"
326+
case m.scanView.aborted:
327+
status = "interrupted"
328+
}
329+
final := scan.Event{Kind: scan.EventDone, Processed: done.processed, Total: done.total, Found: done.found, Stats: done.stats}
330+
report.Finish(&s, []output.TargetSummary{report.Target(m.vals.domain, status, "", true, final)}, time.Since(m.started))
331+
return s
332+
}
333+
285334
// reportOutputErr surfaces an output-file failure in the scan view.
286335
func (m *Model) reportOutputErr(err error) {
287336
if err != nil {

0 commit comments

Comments
 (0)