sekura 0.4.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,263 @@
1
+ import { Command } from 'commander';
2
+ import { input, select } from '@inquirer/prompts';
3
+ import { call, getPlans, tools } from '../api.js';
4
+ import { EXIT, Exit } from '../exit.js';
5
+ import { confirmQuote, requireKey, startWithPayment } from '../flow.js';
6
+ import { monthlyName } from '../payment.js';
7
+ import { dot, interactive, printJson, printTable, say } from '../ui.js';
8
+ import { afterStart, ready, resolveRepository, sayText, withQuoteOptions, withoutConfirm } from './shared.js';
9
+ const when = (iso) => (iso ? iso.replace('T', ' ').slice(0, 16) : '');
10
+ const stateOf = (p) => p.status === 'pending' ? 'waiting on a payment'
11
+ : p.status === 'canceled' ? 'ended'
12
+ : p.canceledAt ? `cancelled${p.currentPeriodEnd ? `, ends ${p.currentPeriodEnd.slice(0, 10)}` : ''}`
13
+ : p.status;
14
+ const COLUMNS = [
15
+ { header: 'REPOSITORY', value: (p) => (p.owner && p.name ? `${p.owner}/${p.name}` : p.id) },
16
+ { header: 'PLAN', value: (p) => monthlyName(p) ?? 'One-time scan' },
17
+ { header: 'SCHEDULE', value: (p) => (monthlyName(p) ? p.schedule?.description ?? '' : '') },
18
+ { header: 'STATE', value: stateOf },
19
+ { header: 'NEXT RUN (UTC)', value: (p) => when(p.nextRunAt) },
20
+ { header: 'LAST SCAN', value: (p) => (p.lastScan ? `${p.lastScan.id} ${p.lastScan.status}` : '') },
21
+ ];
22
+ export async function runPlans(opts = {}) {
23
+ const key = requireKey();
24
+ const data = await ready(() => getPlans(key));
25
+ const plans = data.plans ?? [];
26
+ if (!plans.length && !opts.json) {
27
+ say(`${dot} No plans yet. A one-time scan: npx sekura@latest scan owner/repo. A monthly plan: npx sekura@latest plan start owner/repo`);
28
+ return;
29
+ }
30
+ printTable(plans, COLUMNS, { json: opts.json, data });
31
+ if (!opts.json && data.truncated)
32
+ say(`${dot} There are more on your dashboard${data.dashboard ? `: ${data.dashboard}` : '.'}`);
33
+ }
34
+ export const plansCommand = new Command('plans')
35
+ .description('List your plans by repository: the plan, its schedule, its state and its last scan.')
36
+ .option('--json', 'print the plans as JSON on stdout')
37
+ .action(async (opts) => { await runPlans(opts); });
38
+ const TIER_WORDS = { weekly: 'always', always: 'always', frequent: 'pro', frequently: 'pro', 'more-frequently': 'pro', pro: 'pro' };
39
+ export function tierOf(raw) {
40
+ const t = TIER_WORDS[(raw ?? 'weekly').trim().toLowerCase()];
41
+ if (!t)
42
+ throw new Exit(EXIT.error, `--tier takes weekly (Weekly) or frequent (More frequently); ${raw} is neither.`);
43
+ return t;
44
+ }
45
+ const cadenceOf = (tier) => (tier === 'pro' ? 'daily' : 'weekly');
46
+ const DAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
47
+ export function weekdayOf(raw) {
48
+ const v = raw.trim().toLowerCase();
49
+ if (/^[0-6]$/.test(v))
50
+ return Number(v);
51
+ const i = DAYS.findIndex((d) => d === v || d.slice(0, 3) === v);
52
+ if (i < 0)
53
+ throw new Exit(EXIT.error, `--weekday takes a day such as monday or mon, or 0 (Sunday) to 6 (Saturday); ${raw} is not one.`);
54
+ return i;
55
+ }
56
+ export function minuteOf(raw) {
57
+ const m = /^(\d{1,2}):(\d{2})$/.exec(raw.trim());
58
+ const [h, min] = m ? [Number(m[1]), Number(m[2])] : [NaN, NaN];
59
+ if (!m || h > 23 || min > 59)
60
+ throw new Exit(EXIT.error, `--time takes a 24-hour time such as 09:00 or 23:30; ${raw} is not one.`);
61
+ return h * 60 + min;
62
+ }
63
+ const localZone = () => {
64
+ try {
65
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
66
+ }
67
+ catch {
68
+ return 'UTC';
69
+ }
70
+ };
71
+ const flagged = (f) => !!f.onDemand || f.weekday !== undefined || f.time !== undefined || f.every !== undefined;
72
+ export function scheduleFromFlags(tier, f) {
73
+ const kind = cadenceOf(tier);
74
+ const tz = f.tz?.trim() || localZone();
75
+ const minute = f.time !== undefined ? minuteOf(f.time) : 540;
76
+ if (f.onDemand) {
77
+ if (f.weekday !== undefined || f.every !== undefined)
78
+ throw new Exit(EXIT.error, '--on-demand means no scheduled runs, so it does not go with --weekday or --every.');
79
+ return { kind, minute, tz, onDemand: true };
80
+ }
81
+ if (kind === 'weekly') {
82
+ if (f.every !== undefined)
83
+ throw new Exit(EXIT.error, '--every is for More frequently (--tier frequent). Weekly takes --weekday and --time.');
84
+ if (f.weekday === undefined)
85
+ throw new Exit(EXIT.error, 'Weekly runs on one day of the week: add --weekday, such as --weekday monday, or --on-demand for no scheduled runs.');
86
+ return { kind, weekday: weekdayOf(f.weekday), minute, tz };
87
+ }
88
+ if (f.weekday !== undefined)
89
+ throw new Exit(EXIT.error, '--weekday is for Weekly. More frequently takes --every 1, 2 or 3 (days) and --time.');
90
+ const every = f.every === undefined ? 1 : Number(f.every);
91
+ if (![1, 2, 3].includes(every))
92
+ throw new Exit(EXIT.error, `--every takes 1, 2 or 3 (every day, every second day, every third day); ${f.every} is not one.`);
93
+ return { kind, minute, tz, everyDays: every };
94
+ }
95
+ async function askSchedule(tier) {
96
+ const kind = cadenceOf(tier);
97
+ const tz = localZone();
98
+ const how = await select({
99
+ message: 'When should it scan?',
100
+ choices: [
101
+ { name: kind === 'weekly' ? 'On a day and time each week' : 'On a schedule, every one to three days', value: 'scheduled' },
102
+ { name: `On demand: you start each scan yourself with sekura plan run (${kind === 'weekly' ? 'at most once in seven days' : 'at most once a day'})`, value: 'on-demand' },
103
+ ],
104
+ });
105
+ if (how === 'on-demand')
106
+ return { kind, minute: 540, tz, onDemand: true };
107
+ const flags = { tz };
108
+ if (kind === 'weekly') {
109
+ flags.weekday = String(await select({ message: 'Which day?', choices: DAYS.map((d, i) => ({ name: d[0].toUpperCase() + d.slice(1), value: i })), default: 1 }));
110
+ }
111
+ else {
112
+ flags.every = await select({ message: 'How often?', choices: [{ name: 'Every day', value: 1 }, { name: 'Every second day', value: 2 }, { name: 'Every third day', value: 3 }] });
113
+ }
114
+ flags.time = await input({ message: `At what time (24-hour, ${tz})?`, default: '09:00', validate: (v) => /^([01]?\d|2[0-3]):[0-5]\d$/.test(v.trim()) || 'A time such as 09:00 or 23:30' });
115
+ return scheduleFromFlags(tier, flags);
116
+ }
117
+ async function scheduleFor(tier, f, command) {
118
+ if (flagged(f))
119
+ return scheduleFromFlags(tier, f);
120
+ if (interactive())
121
+ return askSchedule(tier);
122
+ throw new Exit(EXIT.error, `${command} needs a schedule when there is no terminal to ask in: ${cadenceOf(tier) === 'weekly' ? '--weekday <day> --time <HH:MM>' : '--every <1|2|3> --time <HH:MM>'}, or --on-demand. --tz names the time zone; the default is this machine's.`);
123
+ }
124
+ const withScheduleOptions = (cmd) => cmd
125
+ .option('--on-demand', 'no scheduled runs: you start each scan with sekura plan run')
126
+ .option('--weekday <day>', 'Weekly: the day it runs, such as monday')
127
+ .option('--every <days>', 'More frequently: every 1, 2 or 3 days')
128
+ .option('--time <HH:MM>', 'the time it runs, 24-hour; the default is 09:00')
129
+ .option('--tz <zone>', 'the IANA time zone the time is in, such as Europe/London; the default is this machine\'s');
130
+ const withFollowOptions = (cmd) => cmd
131
+ .option('--watch', 'watch the scan it starts until it finishes (the default in a terminal)')
132
+ .option('--no-watch', 'return as soon as it is started')
133
+ .option('--no-report', 'do not save the report when the scan finishes')
134
+ .option('-o, --output <file>', 'where to save the report');
135
+ export async function runPlanStart(repo, opts = {}) {
136
+ const key = requireKey();
137
+ const repository = resolveRepository(repo, opts.cwd);
138
+ const tier = tierOf(opts.tier);
139
+ const command = `npx sekura@latest plan start ${repository}`;
140
+ await ready(async () => {
141
+ const args = opts.confirm ? { repository } : { repository, tier, schedule: await scheduleFor(tier, opts, command) };
142
+ const agreed = await confirmQuote({
143
+ op: 'quoteAlways',
144
+ args,
145
+ fetch: () => tools.quoteAlways(key, args),
146
+ flags: opts,
147
+ command,
148
+ question: `Do you agree, and start ${tier === 'pro' ? 'More frequently' : 'Weekly'} for ${repository}?`,
149
+ sayQuote: sayText,
150
+ });
151
+ if (agreed.kind === 'quoted')
152
+ return;
153
+ const outcome = await startWithPayment(key, agreed.confirmOperation, agreed.confirmArguments, { quoteId: agreed.quoteId, browser: opts.browser });
154
+ await afterStart(key, outcome, { what: `The plan for ${repository}`, watch: opts.watch, report: opts.report, output: opts.output, json: opts.json });
155
+ });
156
+ }
157
+ async function planFor(key, repository) {
158
+ const [owner, name] = repository.toLowerCase().split('/');
159
+ const plans = (await getPlans(key)).plans ?? [];
160
+ const mine = plans.filter((p) => p.owner?.toLowerCase() === owner && p.name?.toLowerCase() === name);
161
+ return mine.find((p) => p.status === 'active' && monthlyName(p)) ?? mine.find((p) => monthlyName(p)) ?? mine[0];
162
+ }
163
+ export async function runPlanSchedule(repo, opts = {}) {
164
+ const key = requireKey();
165
+ const repository = resolveRepository(repo, opts.cwd);
166
+ const command = `npx sekura@latest plan schedule ${repository}`;
167
+ await ready(async () => {
168
+ let args = { repository };
169
+ if (!opts.confirm) {
170
+ const plan = await planFor(key, repository);
171
+ if (!plan || !monthlyName(plan))
172
+ throw new Exit(EXIT.error, `${repository} has no monthly plan to schedule. To start one: npx sekura@latest plan start ${repository}`);
173
+ args = { repository, schedule: await scheduleFor(plan.tier ?? plan.plan, opts, command) };
174
+ }
175
+ const agreed = await confirmQuote({
176
+ op: 'quoteSchedule',
177
+ args,
178
+ fetch: () => tools.quoteSchedule(key, args),
179
+ flags: opts,
180
+ command,
181
+ question: `Change the schedule for ${repository}?`,
182
+ sayQuote: sayText,
183
+ });
184
+ if (agreed.kind === 'quoted')
185
+ return;
186
+ const outcome = await startWithPayment(key, agreed.confirmOperation, agreed.confirmArguments, { quoteId: agreed.quoteId, browser: opts.browser });
187
+ if (outcome.kind === 'started') {
188
+ if (opts.json)
189
+ printJson(outcome.data);
190
+ else
191
+ sayText(outcome.text);
192
+ return;
193
+ }
194
+ await afterStart(key, outcome, { what: `The new schedule for ${repository}`, watch: false, json: opts.json });
195
+ });
196
+ }
197
+ export async function runPlanRun(repo, opts = {}) {
198
+ const key = requireKey();
199
+ const repository = resolveRepository(repo, opts.cwd);
200
+ const args = { repository };
201
+ await ready(async () => {
202
+ const agreed = await confirmQuote({
203
+ op: 'quoteRunNow',
204
+ args,
205
+ fetch: () => tools.quoteRunNow(key, args),
206
+ flags: opts,
207
+ command: `npx sekura@latest plan run ${repository}`,
208
+ question: `Start a scan of ${repository} now?`,
209
+ sayQuote: sayText,
210
+ });
211
+ if (agreed.kind === 'quoted')
212
+ return;
213
+ const outcome = await startWithPayment(key, agreed.confirmOperation, agreed.confirmArguments, { quoteId: agreed.quoteId, browser: opts.browser });
214
+ await afterStart(key, outcome, { what: `The scan of ${repository}`, watch: opts.watch, report: opts.report, output: opts.output, json: opts.json });
215
+ });
216
+ }
217
+ export async function runPlanCancel(repo, opts = {}) {
218
+ const key = requireKey();
219
+ const repository = resolveRepository(repo, opts.cwd);
220
+ const args = { repository };
221
+ await ready(async () => {
222
+ const agreed = await confirmQuote({
223
+ op: 'previewCancelPlan',
224
+ args,
225
+ fetch: () => tools.previewCancelPlan(key, args),
226
+ flags: opts,
227
+ command: `npx sekura@latest plan cancel ${repository}`,
228
+ question: `Cancel the plan for ${repository}?`,
229
+ sayQuote: sayText,
230
+ });
231
+ if (agreed.kind === 'quoted')
232
+ return;
233
+ const reply = await call(key, agreed.confirmOperation, withoutConfirm(agreed.confirmArguments));
234
+ if (opts.json)
235
+ printJson(reply.data);
236
+ else
237
+ sayText(reply.text);
238
+ });
239
+ }
240
+ const REPO_ARG = 'owner/repo; the default is your saved repository, then this folder\'s GitHub remote';
241
+ const start = withFollowOptions(withScheduleOptions(withQuoteOptions(new Command('start')
242
+ .description('Start a monthly plan for one repository: Weekly or More frequently. Shows the quote, asks, then starts the plan and its first scan.')
243
+ .argument('[repo]', REPO_ARG)
244
+ .option('--tier <tier>', 'weekly (Weekly) or frequent (More frequently)', 'weekly'))))
245
+ .action(async (repo, opts) => { await runPlanStart(repo, opts); });
246
+ const schedule = withScheduleOptions(withQuoteOptions(new Command('schedule')
247
+ .description('Change when a monthly plan scans: shows the change, asks, then applies it.')
248
+ .argument('[repo]', REPO_ARG)))
249
+ .action(async (repo, opts) => { await runPlanSchedule(repo, opts); });
250
+ const run = withFollowOptions(withQuoteOptions(new Command('run')
251
+ .description('Start a monthly plan\'s scan now, within the plan\'s run limit: shows what it does, asks, then starts.')
252
+ .argument('[repo]', REPO_ARG)))
253
+ .action(async (repo, opts) => { await runPlanRun(repo, opts); });
254
+ const cancel = withQuoteOptions(new Command('cancel')
255
+ .description('Cancel a monthly plan: shows what cancelling does and when it ends, then asks.')
256
+ .argument('[repo]', REPO_ARG))
257
+ .action(async (repo, opts) => { await runPlanCancel(repo, opts); });
258
+ export const planCommand = new Command('plan')
259
+ .description('Start, schedule, run or cancel a monthly plan for a repository. sekura plans lists them.')
260
+ .addCommand(start)
261
+ .addCommand(schedule)
262
+ .addCommand(run)
263
+ .addCommand(cancel);
@@ -0,0 +1,33 @@
1
+ import { Command } from 'commander';
2
+ import { requireKey } from '../flow.js';
3
+ import { openLink } from '../open.js';
4
+ import { dot, printJson, say, tick } from '../ui.js';
5
+ import { fetchReport, ready, saySaved } from './shared.js';
6
+ export async function runReport(scanId, opts = {}) {
7
+ const key = requireKey();
8
+ const saved = await ready(() => fetchReport(key, scanId, opts.output));
9
+ if (opts.json)
10
+ printJson(saved);
11
+ else
12
+ saySaved(saved);
13
+ if (saved.kind === 'saved') {
14
+ if (opts.open && openLink(`file://${saved.path}`, { browser: opts.browser }).opened && !opts.json)
15
+ say(`${tick} Opened it in your browser.`);
16
+ return;
17
+ }
18
+ if (opts.json)
19
+ return;
20
+ const opened = openLink(saved.link, { browser: opts.browser });
21
+ if (opened.opened)
22
+ say(`${tick} Opened it in your browser.`);
23
+ if (saved.expiresAt)
24
+ say(`${dot} The report is kept until ${saved.expiresAt}.`);
25
+ }
26
+ export const reportCommand = new Command('report')
27
+ .description('Save a finished scan\'s report, with the proof for each finding, to a file.')
28
+ .argument('<scan-id>', 'the scan id, from sekura scans')
29
+ .option('-o, --output <file>', 'where to save it; the default is sekura-report-<scan-id>.html in this folder')
30
+ .option('--open', 'open the saved report in your browser')
31
+ .option('--json', 'print where it was saved as JSON on stdout')
32
+ .option('--no-browser', 'print links instead of opening them')
33
+ .action(async (id, opts) => { await runReport(id, opts); });
@@ -0,0 +1,55 @@
1
+ import { Command } from 'commander';
2
+ import { listRepositories } from '../api.js';
3
+ import { EXIT } from '../exit.js';
4
+ import { requireKey } from '../flow.js';
5
+ import { currentGithubRepo } from '../repo.js';
6
+ import { defaultRepository } from '../state.js';
7
+ import { ensureApp, installLink, repositoriesOf, sayInstallWarnings } from '../steps.js';
8
+ import { dot, interactive, print, printJson, say, table } from '../ui.js';
9
+ export async function runRepos(opts = {}) {
10
+ const key = requireKey();
11
+ const session = { key, account: null, kind: 'legacy', fresh: false };
12
+ let repos;
13
+ let installUrl;
14
+ if (opts.add) {
15
+ const app = await ensureApp(session, { add: true, interactive: !opts.json && interactive(), browser: opts.browser, json: opts.json, soft: true });
16
+ repos = app.repositories;
17
+ installUrl = app.link;
18
+ }
19
+ else {
20
+ const list = await listRepositories(key);
21
+ if (!opts.json)
22
+ sayInstallWarnings(list);
23
+ repos = repositoriesOf(list);
24
+ installUrl = installLink(session, list);
25
+ }
26
+ const here = currentGithubRepo(opts.cwd ?? process.cwd());
27
+ const saved = defaultRepository();
28
+ const is = (a, b) => !!a && a.toLowerCase() === b.toLowerCase();
29
+ if (opts.json) {
30
+ printJson({ repositories: repos.map((r) => ({ fullName: r.fullName, private: !!r.private, empty: !!r.empty, thisFolder: is(here, r.fullName), default: is(saved, r.fullName) })), installUrl });
31
+ return EXIT.done;
32
+ }
33
+ if (!repos.length) {
34
+ say(`${dot} There is no repository Sekura can scan yet.${opts.add ? '' : ' Run npx sekura@latest repos --add to install the Sekura GitHub App.'}`);
35
+ say();
36
+ return EXIT.accountNotReady;
37
+ }
38
+ for (const l of table(repos, [
39
+ { header: 'Repository', value: (r) => r.fullName },
40
+ { header: 'Visibility', value: (r) => (r.private ? 'private' : 'public') },
41
+ { header: 'Note', value: (r) => [r.empty ? 'empty, nothing to scan' : '', is(here, r.fullName) ? 'this folder' : '', is(saved, r.fullName) ? 'default' : ''].filter(Boolean).join(', ') },
42
+ ]))
43
+ print(l);
44
+ if (!opts.add) {
45
+ say();
46
+ say(' To add repositories: npx sekura@latest repos --add');
47
+ }
48
+ return EXIT.done;
49
+ }
50
+ export const reposCommand = new Command('repos')
51
+ .description('List the repositories Sekura can scan; --add opens GitHub to give the Sekura GitHub App access to more.')
52
+ .option('--add', 'open the GitHub App install page and wait until the new repositories show up')
53
+ .option('--json', 'print the list as JSON on stdout')
54
+ .option('--no-browser', 'print the link instead of opening it')
55
+ .action(async (opts) => { process.exitCode = await runRepos(opts); });
@@ -0,0 +1,100 @@
1
+ import { Command } from 'commander';
2
+ import { call, tools } from '../api.js';
3
+ import { confirmQuote, requireKey, scanFinished, startWithPayment, watchScan } from '../flow.js';
4
+ import { EXIT, Exit } from '../exit.js';
5
+ import { dot, printJson, say } from '../ui.js';
6
+ import { afterStart, merged, ready, resolveRepository, sayFindings, sayScan, sayText, withQuoteOptions, withoutConfirm } from './shared.js';
7
+ export async function runScan(repo, opts = {}) {
8
+ const key = requireKey();
9
+ const repository = resolveRepository(repo, opts.cwd);
10
+ const args = { repository };
11
+ await ready(async () => {
12
+ const agreed = await confirmQuote({
13
+ op: 'quoteScan',
14
+ args,
15
+ fetch: () => tools.quoteScan(key, args),
16
+ flags: opts,
17
+ command: `npx sekura@latest scan ${repository}`,
18
+ question: `Do you agree, and start the scan of ${repository}?`,
19
+ sayQuote: sayText,
20
+ });
21
+ if (agreed.kind === 'quoted')
22
+ return;
23
+ const outcome = await startWithPayment(key, agreed.confirmOperation, agreed.confirmArguments, { quoteId: agreed.quoteId, browser: opts.browser });
24
+ await afterStart(key, outcome, { what: `The scan of ${repository}`, watch: opts.watch, report: opts.report, output: opts.output, json: opts.json, intervalMs: opts.intervalMs, timeoutMs: opts.timeoutMs });
25
+ });
26
+ }
27
+ export async function runScanShow(scanId, opts = {}) {
28
+ const key = requireKey();
29
+ let detail = (await ready(() => tools.getScan(key, { scanId }))).data;
30
+ if (opts.watch && !scanFinished(detail.scan.status)) {
31
+ const w = await watchScan(key, scanId, {
32
+ ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}),
33
+ ...(opts.intervalMs ? { intervalMs: opts.intervalMs } : {}),
34
+ onStatus: (status) => { if (!scanFinished(status) && !opts.json)
35
+ say(`${dot} ${status}`); },
36
+ });
37
+ if (w.detail)
38
+ detail = w.detail;
39
+ if (w.result !== 'done') {
40
+ if (opts.json)
41
+ printJson(detail);
42
+ throw new Exit(EXIT.stoppedWaiting, `${w.result === 'skipped' ? 'Stopped watching' : 'Still running after the wait'}; the scan carries on.`, { scanId, status: w.status });
43
+ }
44
+ }
45
+ if (opts.json) {
46
+ printJson(detail);
47
+ return;
48
+ }
49
+ sayScan(detail);
50
+ if (detail.scan.status === 'done' && opts.findings !== false) {
51
+ sayFindings((await tools.getScanFindings(key, { scanId, limit: 10 })).data, 10);
52
+ say(`${dot} The full report: npx sekura@latest report ${scanId}`);
53
+ }
54
+ }
55
+ export async function runScanCancel(scanId, opts = {}) {
56
+ const key = requireKey();
57
+ const args = { scanId };
58
+ await ready(async () => {
59
+ const agreed = await confirmQuote({
60
+ op: 'previewCancelScan',
61
+ args,
62
+ fetch: () => tools.previewCancelScan(key, args),
63
+ flags: opts,
64
+ command: `npx sekura@latest scan cancel ${scanId}`,
65
+ question: 'Cancel this scan?',
66
+ sayQuote: sayText,
67
+ });
68
+ if (agreed.kind === 'quoted')
69
+ return;
70
+ const reply = await call(key, agreed.confirmOperation, withoutConfirm(agreed.confirmArguments));
71
+ if (opts.json)
72
+ printJson(reply.data);
73
+ else
74
+ sayText(reply.text);
75
+ });
76
+ }
77
+ const show = new Command('show')
78
+ .description('Show one scan: its status and, when it is done, its findings by severity.')
79
+ .argument('<scan-id>', 'the scan id, from sekura scans')
80
+ .option('--watch', 'keep watching until the scan finishes (Enter stops watching; the scan carries on)')
81
+ .option('--no-findings', 'leave the findings out')
82
+ .option('--json', 'print the scan as JSON on stdout')
83
+ .action(async (id, _o, cmd) => {
84
+ const o = merged(cmd);
85
+ await runScanShow(id, { ...o, watch: cmd.opts().watch === true || cmd.parent?.opts().watch === true });
86
+ });
87
+ const cancel = withQuoteOptions(new Command('cancel')
88
+ .description('Cancel a scan inside its cancel window: shows what cancelling does, then asks.')
89
+ .argument('<scan-id>', 'the scan id, from sekura scans'))
90
+ .action(async (id, _o, cmd) => { await runScanCancel(id, merged(cmd)); });
91
+ export const scanCommand = withQuoteOptions(new Command('scan')
92
+ .description('Scan a repository: shows the quote with the authorization wording and the price, asks, starts, then watches the scan and saves the report.')
93
+ .argument('[repo]', 'owner/repo; the default is your saved repository, then this folder\'s GitHub remote'))
94
+ .option('--watch', 'watch the scan until it finishes (the default in a terminal)')
95
+ .option('--no-watch', 'start the scan and return at once')
96
+ .option('--no-report', 'do not save the report when the scan finishes')
97
+ .option('-o, --output <file>', 'where to save the report')
98
+ .addCommand(show)
99
+ .addCommand(cancel)
100
+ .action(async (repo, opts) => { await runScan(repo, opts); });
@@ -0,0 +1,32 @@
1
+ import { Command } from 'commander';
2
+ import { tools } from '../api.js';
3
+ import { Exit, EXIT } from '../exit.js';
4
+ import { requireKey } from '../flow.js';
5
+ import { dot, printTable, say } from '../ui.js';
6
+ import { ready } from './shared.js';
7
+ const day = (iso) => (iso ? iso.replace('T', ' ').slice(0, 16) : '');
8
+ const COLUMNS = [
9
+ { header: 'SCAN ID', value: (s) => s.id },
10
+ { header: 'REPOSITORY', value: (s) => (s.target_owner && s.target_repo ? `${s.target_owner}/${s.target_repo}` : '') },
11
+ { header: 'STATUS', value: (s) => s.status },
12
+ { header: 'FINDINGS', value: (s) => (s.status === 'done' ? s.findings_count ?? 0 : ''), align: 'right' },
13
+ { header: 'STARTED (UTC)', value: (s) => day(s.created_at) },
14
+ ];
15
+ export async function runScans(opts = {}) {
16
+ const key = requireKey();
17
+ const limit = opts.limit === undefined ? 10 : Number(opts.limit);
18
+ if (!Number.isInteger(limit) || limit < 1 || limit > 20)
19
+ throw new Exit(EXIT.error, '--limit takes a whole number from 1 to 20.');
20
+ const { data } = await ready(() => tools.listScans(key, { limit }));
21
+ const scans = data.scans ?? [];
22
+ if (!scans.length && !opts.json) {
23
+ say(`${dot} No scans yet. To start one: npx sekura@latest scan owner/repo`);
24
+ return;
25
+ }
26
+ printTable(scans, COLUMNS, { json: opts.json, data });
27
+ }
28
+ export const scansCommand = new Command('scans')
29
+ .description('List your most recent scans, newest first.')
30
+ .option('--limit <n>', 'how many, 1 to 20', '10')
31
+ .option('--json', 'print the list as JSON on stdout')
32
+ .action(async (opts) => { await runScans(opts); });