sekura 0.5.17 → 0.5.21

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.
@@ -1,9 +1,9 @@
1
1
  import { Command } from 'commander';
2
- import { call, tools } from '../api.js';
2
+ import { bareScanId, call, tools } from '../api.js';
3
3
  import { confirmQuote, requireKey, scanFinished, startWithPayment, watchScan } from '../flow.js';
4
4
  import { EXIT, Exit } from '../exit.js';
5
5
  import { dot, printJson, say } from '../ui.js';
6
- import { afterStart, merged, ready, resolveRepository, sayFindings, sayScan, sayText, withQuoteOptions, withoutConfirm } from './shared.js';
6
+ import { afterStart, merged, ready, stoppedWatching, resolveRepository, sayFindings, sayScan, sayText, withQuoteOptions, withoutConfirm } from './shared.js';
7
7
  export async function runScan(repo, opts = {}) {
8
8
  const key = requireKey();
9
9
  const repository = resolveRepository(repo, opts.cwd);
@@ -18,14 +18,15 @@ export async function runScan(repo, opts = {}) {
18
18
  question: `Do you agree, and start the scan of ${repository}?`,
19
19
  sayQuote: (text) => sayText(text, repository),
20
20
  });
21
- if (agreed.kind === 'quoted')
21
+ if (agreed.kind !== 'agreed')
22
22
  return;
23
23
  const outcome = await startWithPayment(key, agreed.confirmOperation, agreed.confirmArguments, { quoteId: agreed.quoteId, browser: opts.browser });
24
24
  await afterStart(key, outcome, { what: `The scan of ${repository}`, repository, watch: opts.watch, report: opts.report, output: opts.output, json: opts.json, intervalMs: opts.intervalMs, timeoutMs: opts.timeoutMs });
25
- });
25
+ }, { repository });
26
26
  }
27
- export async function runScanShow(scanId, opts = {}) {
27
+ export async function runScanShow(given, opts = {}) {
28
28
  const key = requireKey();
29
+ const scanId = bareScanId(given);
29
30
  let detail = (await ready(() => tools.getScan(key, { scanId }))).data;
30
31
  if (opts.watch && !scanFinished(detail.scan.status)) {
31
32
  const w = await watchScan(key, scanId, {
@@ -39,7 +40,7 @@ export async function runScanShow(scanId, opts = {}) {
39
40
  if (w.result !== 'done') {
40
41
  if (opts.json)
41
42
  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
+ throw new Exit(EXIT.stoppedWaiting, stoppedWatching(w.result, scanId), { scanId, status: w.status });
43
44
  }
44
45
  }
45
46
  if (opts.json) {
@@ -52,8 +53,9 @@ export async function runScanShow(scanId, opts = {}) {
52
53
  say(`${dot} The full report: npx sekura@latest report ${scanId}`);
53
54
  }
54
55
  }
55
- export async function runScanCancel(scanId, opts = {}) {
56
+ export async function runScanCancel(given, opts = {}) {
56
57
  const key = requireKey();
58
+ const scanId = bareScanId(given);
57
59
  const args = { scanId };
58
60
  await ready(async () => {
59
61
  const agreed = await confirmQuote({
@@ -63,9 +65,10 @@ export async function runScanCancel(scanId, opts = {}) {
63
65
  flags: opts,
64
66
  command: `npx sekura@latest scan cancel ${scanId}`,
65
67
  question: 'Cancel this scan?',
66
- sayQuote: sayText,
68
+ sayQuote: (text) => sayText(text),
69
+ nothing: 'Nothing was cancelled.',
67
70
  });
68
- if (agreed.kind === 'quoted')
71
+ if (agreed.kind !== 'agreed')
69
72
  return;
70
73
  const reply = await call(key, agreed.confirmOperation, withoutConfirm(agreed.confirmArguments));
71
74
  if (opts.json)
@@ -1,12 +1,12 @@
1
1
  import { Command } from 'commander';
2
- import { tools } from '../api.js';
2
+ import { bareScanId, tools } from '../api.js';
3
3
  import { Exit, EXIT } from '../exit.js';
4
4
  import { requireKey } from '../flow.js';
5
5
  import { dot, printTable, say } from '../ui.js';
6
6
  import { ready } from './shared.js';
7
7
  const day = (iso) => (iso ? iso.replace('T', ' ').slice(0, 16) : '');
8
8
  const COLUMNS = [
9
- { header: 'SCAN ID', value: (s) => s.id },
9
+ { header: 'SCAN ID', value: (s) => bareScanId(s.id) },
10
10
  { header: 'REPOSITORY', value: (s) => (s.target_owner && s.target_repo ? `${s.target_owner}/${s.target_repo}` : '') },
11
11
  { header: 'STATUS', value: (s) => s.status },
12
12
  { header: 'FINDINGS', value: (s) => (s.status === 'done' ? s.findings_count ?? 0 : ''), align: 'right' },
@@ -1,9 +1,9 @@
1
1
  import { writeFileSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
- import { CLI_API, ToolError, cliApi, cliFetch, isMissingRoute, isToolError, tools } from '../api.js';
3
+ import { CLI_API, ToolError, bareScanId, cliApi, cliFetch, isMissingRoute, isToolError, tools } from '../api.js';
4
4
  import { EXIT, Exit, exitCodeFor, messageFor } from '../exit.js';
5
5
  import { exitCodeOfStart, scanFinished, watchScan } from '../flow.js';
6
- import { scanLink } from '../payment.js';
6
+ import { openableLink, scanLink } from '../payment.js';
7
7
  import { currentGithubRepo } from '../repo.js';
8
8
  import { defaultRepository } from '../state.js';
9
9
  import { ask, c, cross, dot, interactive, say, tick } from '../ui.js';
@@ -25,17 +25,70 @@ export function merged(cmd) {
25
25
  out[k] = v;
26
26
  return out;
27
27
  }
28
- export async function ready(fn) {
28
+ /**
29
+ * Every refusal from Sekura, as the person at the terminal reads it. A
30
+ * refusal was printed as the server wrote it, for an agent: "updateSchedule
31
+ * changes when it runs; cancelPlan ends it" reached the terminal, and the
32
+ * reader was given no command to run (Varsha's 0.5.20 test, 1 December 2026,
33
+ * bugs 13 to 15). The repository is the command's own, for a refusal whose
34
+ * data does not name one.
35
+ */
36
+ export async function ready(fn, ctx = {}) {
29
37
  try {
30
38
  return await fn();
31
39
  }
32
40
  catch (e) {
33
- if (e instanceof ToolError && exitCodeFor(e) === EXIT.accountNotReady) {
34
- throw new Exit(EXIT.accountNotReady, `${messageFor(e)}\n ${DOCTOR_HINT}`, { code: e.code, ...e.data });
41
+ if (e instanceof ToolError) {
42
+ const code = exitCodeFor(e);
43
+ throw new Exit(code, `${refusalText(e, ctx.repository)}${code === EXIT.accountNotReady ? `\n ${DOCTOR_HINT}` : ''}`, { code: e.code, ...e.data });
35
44
  }
36
45
  throw e;
37
46
  }
38
47
  }
48
+ const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
49
+ /** What to run about a monthly plan that is already there. */
50
+ export const alreadyHints = (repo) => `To change when it runs: npx sekura@latest plan schedule ${repo}. To end it: npx sekura@latest plan cancel ${repo}`;
51
+ /**
52
+ * The terminal commands for a refusal, by its code. The server's sentence
53
+ * says what happened, to "you", with no tool names; the commands are the
54
+ * CLI's to add, because only the CLI knows it is in a terminal. Each line
55
+ * goes through say(), which adds --endpoint off production.
56
+ */
57
+ export function refusalHints(e, repository) {
58
+ const repo = str(e.data.repository) ?? repository ?? 'owner/repo';
59
+ switch (e.code) {
60
+ // A one-time scan after the first: Sekura sells only monthly plans then.
61
+ case 'once_not_sold': return [`Put it on a plan: npx sekura@latest plan start ${repo}`];
62
+ case 'already_always': return [alreadyHints(repo)];
63
+ // A payment is waiting. data.checkoutUrl is there while Stripe's page is
64
+ // still open; only a Stripe or Sekura link is printed to be opened.
65
+ case 'pending': {
66
+ const planId = str(e.data.planId);
67
+ const raw = str(e.data.checkoutUrl);
68
+ const url = raw ? openableLink(raw)?.href ?? null : null;
69
+ return [
70
+ ...(url ? [`To pay: open ${url}`] : []),
71
+ ...(planId ? [`To wait for it: npx sekura@latest pay --plan ${planId}`, `To cancel it: npx sekura@latest pay --plan ${planId} --abandon`] : []),
72
+ ];
73
+ }
74
+ default: return [];
75
+ }
76
+ }
77
+ /** A refusal's words for the person, then its commands. The words go
78
+ * through the same rewrites as a quote, as a safety net: a server that
79
+ * still writes for an agent ("the person", "connector", a tool name) has
80
+ * those sentences rewritten or left out. A hint the words already carry is
81
+ * not said twice. */
82
+ export function refusalText(e, repository) {
83
+ const said = personText(messageFor(e), repository);
84
+ if (!(e instanceof ToolError))
85
+ return said;
86
+ const fresh = refusalHints(e, repository).filter((h) => {
87
+ const parts = h.match(/npx sekura@latest [^.]+?(?=\.\s|\.?$)|https?:\/\/\S+/g) ?? [];
88
+ return !parts.length || !parts.every((p) => said.includes(p));
89
+ });
90
+ return [said, ...fresh].filter(Boolean).join('\n ');
91
+ }
39
92
  const REPO = /^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9._-]+$/;
40
93
  export function resolveRepository(given, cwd = process.cwd()) {
41
94
  if (given) {
@@ -108,7 +161,10 @@ const PERSON_REWRITES = [
108
161
  // After the first scan there is no one-time scan (Sudhir, 30 November 2026):
109
162
  // the server's refusal names the plan tool, the reader gets the command.
110
163
  [/To scan (\S+?), put it on a monthly plan: (.+?)\. Call \w+ with the repository and a schedule\./g,
111
- (_m, repo, plans) => `To scan ${repo}, put it on a monthly plan: ${plans}. Start one with: npx sekura@latest plan start ${repo}`],
164
+ // The command itself is the once_not_sold hint, on a line of its own:
165
+ // inside the sentence it ran on into "Nothing was started or charged."
166
+ // (Varsha's 0.5.20 test, 1 December 2026).
167
+ (_m, repo, plans) => `To scan ${repo}, put it on a monthly plan: ${plans}.`],
112
168
  [/this is the account's first scan\./g, 'this is your first scan.'],
113
169
  [/in the person's browser/g, 'in your browser'],
114
170
  [/the person's name/g, 'your name'],
@@ -116,7 +172,12 @@ const PERSON_REWRITES = [
116
172
  ];
117
173
  /** One sentence at a time, for the last check: a period that ends a sentence
118
174
  * is followed by a space and a capital; one inside a URL or "e.g." is not. */
119
- const sentences = (line) => line.split(/(?<=[.!?])\s+(?=[A-Z])/);
175
+ const sentences = (line) => line.split(SENTENCE_BREAK);
176
+ /** A sentence may also open with a tool name, in lower case: "… on this
177
+ * account. updateSchedule changes when it runs" was one sentence to the
178
+ * split above, and the repository's half was left out with the tool's
179
+ * (Varsha's 0.5.20 test, 1 December 2026, bug 13). */
180
+ const SENTENCE_BREAK = new RegExp(`(?<=[.!?])\\s+(?=[A-Z]|(?:${TOOL_NAMES.join('|')})\\b)`);
120
181
  /** The repository as the person typed it, where the server answered with its
121
182
  * lower-cased canonical name ("varsha311002/navidrome", Varsha's test, F10). */
122
183
  export function namedAs(text, repo) {
@@ -345,6 +406,11 @@ const REPORT_REFUSALS = {
345
406
  no_report_yet: (id, d) => `Scan ${id} has no report yet${typeof d.status === 'string' ? `: it is ${d.status}` : ''}. To wait for it: npx sekura@latest scan show ${id} --watch`,
346
407
  report_expired: (id) => `The report for scan ${id} is no longer kept, so it cannot be downloaded.`,
347
408
  };
409
+ /** What a watch that ended early says: the scan carries on, and the one
410
+ * command that saves its report once it is done. It said only "To look
411
+ * again: scan show --watch", and the report that the first-scan watch was
412
+ * to save was left behind (Varsha's 0.5.20 test, 1 December 2026, bug 6). */
413
+ export const stoppedWatching = (result, scanId) => `${result === 'skipped' ? 'Stopped watching' : 'Still running after the wait'}; the scan carries on. When it finishes, this saves the report: npx sekura@latest report ${bareScanId(scanId)}`;
348
414
  export const defaultReportPath = (scanId, cwd = process.cwd()) => resolve(cwd, `sekura-report-${scanId.replace(/[^A-Za-z0-9._-]/g, '_')}.html`);
349
415
  export async function fetchReport(key, scanId, output) {
350
416
  const path = `/scans/${encodeURIComponent(scanId)}/report`;
@@ -391,16 +457,17 @@ export function sayFindings(f, shown = f.findings.length) {
391
457
  say(` ${i + 1}. [${x.severity}] ${x.title}${x.location ? ` — ${x.location}` : ''}`);
392
458
  });
393
459
  if (f.total > shown)
394
- say(` … and ${f.total - shown} more: npx sekura@latest findings ${f.scanId}`);
460
+ say(` … and ${f.total - shown} more: npx sekura@latest findings ${bareScanId(f.scanId)}`);
395
461
  }
396
462
  export function sayScan(d) {
397
463
  const s = d.scan;
398
464
  const repo = s.target_owner && s.target_repo ? `${s.target_owner}/${s.target_repo}` : 'the repository';
399
465
  const count = typeof s.findings_count === 'number' ? `, ${s.findings_count} ${s.findings_count === 1 ? 'finding' : 'findings'}` : '';
400
- say(`${s.status === 'failed' ? cross : scanFinished(s.status) ? tick : dot} Scan ${s.id} of ${repo}: ${s.status}${s.status === 'done' ? count : ''}`);
466
+ say(`${s.status === 'failed' ? cross : scanFinished(s.status) ? tick : dot} Scan ${bareScanId(s.id)} of ${repo}: ${s.status}${s.status === 'done' ? count : ''}`);
401
467
  say(` ${d.link ?? scanLink(s.id)}`);
402
468
  }
403
- export async function followScan(key, scanId, opts = {}) {
469
+ export async function followScan(key, given, opts = {}) {
470
+ const scanId = bareScanId(given);
404
471
  const watching = opts.watch ?? (interactive() && !opts.json);
405
472
  if (!watching) {
406
473
  say(`${dot} To follow it: npx sekura@latest scan show ${scanId} --watch`);
@@ -415,7 +482,7 @@ export async function followScan(key, scanId, opts = {}) {
415
482
  say(`${dot} ${status}`); },
416
483
  });
417
484
  if (w.result !== 'done') {
418
- throw new Exit(EXIT.stoppedWaiting, `${w.result === 'skipped' ? 'Stopped watching' : 'Still running after the wait'}; the scan carries on. To look again: npx sekura@latest scan show ${scanId} --watch`, { scanId, status: w.status });
485
+ throw new Exit(EXIT.stoppedWaiting, stoppedWatching(w.result, scanId), { scanId, status: w.status });
419
486
  }
420
487
  if (w.detail)
421
488
  sayScan(w.detail);
@@ -24,16 +24,27 @@ export async function runStatus(opts) {
24
24
  const local = localConnections({ cwd, scope });
25
25
  if (!local.detected)
26
26
  say(' No supported coding tool found on this machine.');
27
+ // The tools that are connected (or cannot be checked) by name, and the
28
+ // others found here in one line. Every tool on the machine was listed,
29
+ // twelve of them "not connected" (Varsha's 0.5.20 test, 1 December 2026).
27
30
  const seen = [];
31
+ let others = 0;
28
32
  for (const row of local.rows) {
29
- if (row.kind === 'tool')
33
+ if (row.kind === 'tool') {
30
34
  seen.push(row.state);
35
+ if (row.state === false) {
36
+ others++;
37
+ continue;
38
+ }
39
+ }
31
40
  say(`${row.state === true ? tick : row.state === 'unknown' ? dot : cross} ${row.label}: ${row.word}`);
32
41
  }
33
42
  for (const s of local.skipped)
34
43
  say(`${dot} ${s.name}: ${s.why}`);
35
44
  if (seen.length && !local.skipped.length && seen.every((p) => p === false))
36
45
  say(`${dot} Nothing on this machine is connected to Sekura.`);
46
+ if (others)
47
+ say(`${dot} ${others}${seen.some((p) => p !== false) ? ' other' : ''} supported ${others === 1 ? 'tool' : 'tools'} found, not connected: npx sekura@latest init connects them`);
37
48
  let result = { readiness: null, server: null };
38
49
  if (opts.verify !== false) {
39
50
  const server = await verifyEndpoint(ENDPOINT, 8000, key);
package/dist/device.js CHANGED
@@ -11,7 +11,7 @@
11
11
  // device_code is the secret half of the pair and is never printed; only the
12
12
  // user_code is meant for eyes.
13
13
  import { ENDPOINT, HOST } from './catalogue.js';
14
- import { reach, refusal } from './errors.js';
14
+ import { reach, refusal, timed } from './errors.js';
15
15
  export const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
16
16
  const ISSUER = new URL(ENDPOINT).origin;
17
17
  /** The variables that say this terminal is not on the machine with the
@@ -91,7 +91,7 @@ export async function pollForToken(request, code, opts = {}) {
91
91
  * the key.
92
92
  */
93
93
  export async function pollDeviceToken(clientId, code, opts = {}) {
94
- const data = await pollForToken(() => fetch(`${ISSUER}/oauth/token`, form({ grant_type: DEVICE_GRANT, device_code: code.device_code, client_id: clientId, resource: ENDPOINT })), code, opts);
94
+ const data = await pollForToken(() => fetch(`${ISSUER}/oauth/token`, timed(form({ grant_type: DEVICE_GRANT, device_code: code.device_code, client_id: clientId, resource: ENDPOINT }))), code, opts);
95
95
  return String(data.access_token);
96
96
  }
97
97
  export async function deviceSignIn(clientId, opts = {}) {
package/dist/errors.js CHANGED
@@ -1,9 +1,31 @@
1
+ import { createRequire } from 'node:module';
1
2
  import { HOST, SUPPORT } from './catalogue.js';
3
+ /** The CLI by name and version, on every request it sends to Sekura. The
4
+ * server marks a refusal as isError only for a client it knows is this CLI;
5
+ * without the header a 409 came back as an ordinary answer with ok: false,
6
+ * and a CLI that looked only at isError read a refusal as a quote (the
7
+ * coordinator's note on Varsha's 0.5.20 test, 1 December 2026). */
8
+ export const USER_AGENT = `sekura-cli/${createRequire(import.meta.url)('../package.json').version}`;
9
+ /** The headers of a request with the user-agent added; a plain object stays
10
+ * a plain object, so a caller that reads init.headers still can. */
11
+ export function withAgent(init) {
12
+ const h = init.headers;
13
+ if (h instanceof Headers) {
14
+ const copy = new Headers(h);
15
+ copy.set('user-agent', USER_AGENT);
16
+ return { ...init, headers: copy };
17
+ }
18
+ if (Array.isArray(h))
19
+ return { ...init, headers: [...h.filter(([k]) => k.toLowerCase() !== 'user-agent'), ['user-agent', USER_AGENT]] };
20
+ return { ...init, headers: { ...(h ?? {}), 'user-agent': USER_AGENT } };
21
+ }
2
22
  export const unreachable = () => `${HOST} could not be reached. Check your internet connection and try again.`;
3
23
  export const serverTrouble = (status) => `${HOST} had a problem answering (HTTP ${status}). Try again in a minute; if it keeps happening, write to ${SUPPORT}.`;
24
+ export const REQUEST_TIMEOUT_MS = 25_000;
25
+ export const timed = (init, timeoutMs = REQUEST_TIMEOUT_MS) => withAgent(init.signal ? init : { ...init, signal: AbortSignal.timeout(timeoutMs) });
4
26
  export async function reach(url, init) {
5
27
  try {
6
- return await fetch(url, init);
28
+ return await fetch(url, timed(init));
7
29
  }
8
30
  catch {
9
31
  throw new Error(unreachable());
package/dist/flow.js CHANGED
@@ -3,8 +3,8 @@ import { readKey } from './auth.js';
3
3
  import { call, getPlans, paymentRequiredOf, tools } from './api.js';
4
4
  import { EXIT, Exit, SIGN_IN_HINT } from './exit.js';
5
5
  import { openLink } from './open.js';
6
- import { openableLink, paymentState } from './payment.js';
7
- import { dropQuote, findQuote, saveQuote } from './state.js';
6
+ import { checkoutCodeLine, checkoutCodeOf, openableLink, paymentState } from './payment.js';
7
+ import { dropCheckoutCode, dropQuote, findQuote, saveCheckoutCode, saveQuote } from './state.js';
8
8
  import { select, ask, dot, interactive, printJson, say, tick, waitFor } from './ui.js';
9
9
  export function requireKey() {
10
10
  const key = readKey();
@@ -12,6 +12,12 @@ export function requireKey() {
12
12
  throw new Exit(EXIT.notSignedIn, `Not signed in here: ${SIGN_IN_HINT} first.`);
13
13
  return key;
14
14
  }
15
+ /** True when the answer has a step to confirm. A preview of a plan already
16
+ * cancelled carries none (data.alreadyCancelled, no confirmOperation), and
17
+ * asking "Cancel the plan?" over it ended, on Yes, in "Cannot destructure
18
+ * property 'confirm' of 'args' as it is undefined" (Varsha's 0.5.20 test,
19
+ * 1 December 2026, bug 15). */
20
+ export const hasConfirmStep = (q) => !!q && typeof q.confirmOperation === 'string' && !!q.confirmOperation && !!q.confirmArguments && typeof q.confirmArguments === 'object';
15
21
  const usd = (cents) => `$${(cents / 100).toFixed(cents % 100 ? 2 : 0)}`;
16
22
  export const amountOf = (q) => typeof q.amountCents === 'number' && Number.isFinite(q.amountCents) ? q.amountCents : null;
17
23
  export const needsAgreement = (q) => !!q.disclosure || (amountOf(q) ?? 0) > 0;
@@ -76,6 +82,11 @@ export async function confirmQuote(req) {
76
82
  const flags = req.flags ?? {};
77
83
  const again = req.command ? `${req.command} --quote` : 'the same command with --quote';
78
84
  if (flags.confirm) {
85
+ // The payment is part of the quote: --card given here was ignored, and the
86
+ // confirm went to Checkout with no word (Claude's run of the customer flow,
87
+ // 1 December 2026). Refused, so the person knows where it goes.
88
+ if (flags.card)
89
+ throw new Exit(EXIT.error, `--card goes with --quote: the payment is part of the quote. Run ${again} --card ${flags.card}, then --confirm the new quote. Nothing was started.`);
79
90
  const found = findQuote(flags.confirm);
80
91
  if (found.status === 'unknown')
81
92
  throw new Exit(EXIT.error, `There is no quote ${flags.confirm} saved here. Run ${again} to get one.`);
@@ -92,6 +103,18 @@ export async function confirmQuote(req) {
92
103
  const amount = amountOf(q);
93
104
  const show = req.sayQuote ?? ((text) => { say(); for (const l of text.split('\n'))
94
105
  say(` ${l}`); say(); });
106
+ // No step to confirm: the answer is the whole of it, and there is no
107
+ // question to ask (bug 15).
108
+ if (!hasConfirmStep(q)) {
109
+ if (flags.json)
110
+ printJson(q);
111
+ else
112
+ show(q.text);
113
+ return { kind: 'answered', quote: q };
114
+ }
115
+ // A No to a cancel said "Nothing was started or charged." (Varsha's 0.5.20
116
+ // test, bug 16): the command names what it leaves as it was.
117
+ const nothing = req.nothing ?? 'Nothing was started or charged.';
95
118
  if (flags.quote) {
96
119
  const payment = paymentFromFlag(q, flags.card);
97
120
  const cached = cacheQuote(req, { ...q, confirmArguments: withPayment(q.confirmArguments, payment) });
@@ -99,7 +122,7 @@ export async function confirmQuote(req) {
99
122
  printJson({ quoteId: cached.quoteId, op: cached.op, confirmOperation: cached.confirmOperation, confirmArguments: cached.confirmArguments, amountCents: cached.amountCents, price: cached.price, expiresAt: cached.expiresAt, text: cached.text });
100
123
  else {
101
124
  show(q.text);
102
- say(`${dot} Quote ${cached.quoteId}, good until ${cached.expiresAt}. Nothing was started or charged.`);
125
+ say(`${dot} Quote ${cached.quoteId}, good until ${cached.expiresAt}. ${nothing}`);
103
126
  say(` To start exactly this: ${req.command ?? 'the same command'} --confirm ${cached.quoteId}`);
104
127
  }
105
128
  return { kind: 'quoted', cached };
@@ -120,7 +143,7 @@ export async function confirmQuote(req) {
120
143
  const payment = await askPayment(q, flags.card);
121
144
  const agreed = await ask(req.question ?? 'Do you agree?', { default: false, short: 'Do you agree?' });
122
145
  if (!agreed)
123
- throw new Exit(EXIT.declined, 'Nothing was started or charged.');
146
+ throw new Exit(EXIT.declined, nothing);
124
147
  return { kind: 'agreed', how: 'asked', confirmOperation: q.confirmOperation, confirmArguments: withPayment(q.confirmArguments, payment), amountCents: amount, quoteId: null, quote: q };
125
148
  }
126
149
  export async function planById(key, planId) {
@@ -136,9 +159,9 @@ export async function waitForPayment(key, planId, start, opts = {}) {
136
159
  let state = { kind: 'waiting' };
137
160
  let cancelledSeen = 0;
138
161
  let paidAt = null;
139
- const m = opts.message ?? 'Waiting for the payment to complete in your browser (Enter to stop waiting)';
162
+ const m = opts.message ?? 'Complete the payment in your browser; this continues by itself (Enter stops waiting)';
140
163
  const waiting = typeof m === 'function' ? m : () => m;
141
- const result = await waitFor(() => (paidAt ? 'Payment received. Waiting for the scan to start (Enter to stop waiting)' : waiting()), async () => {
164
+ const result = await waitFor(() => (paidAt ? 'Payment received. Starting the scan…' : waiting()), async () => {
142
165
  last = await planById(key, planId);
143
166
  state = paymentState(start, last);
144
167
  if (state.kind === 'cancelled')
@@ -155,14 +178,34 @@ export async function waitForPayment(key, planId, start, opts = {}) {
155
178
  /** A Checkout link is long, and wrapped by the terminal it ran back to the
156
179
  * left edge (Varsha's test, R3). Opened, it is not printed; otherwise it
157
180
  * gets a line of its own, never broken. */
158
- const sayCheckout = (opened, url) => {
181
+ export const sayCheckout = (opened, url, code = null) => {
159
182
  if (opened.opened)
160
183
  say(`${tick} Opened Stripe Checkout in your browser.`);
161
184
  else {
162
185
  say(`${dot} Open this link in a browser to pay:`);
163
186
  say(` ${url.href}`);
164
187
  }
188
+ if (code)
189
+ say(`${dot} ${checkoutCodeLine(code)}`);
165
190
  };
191
+ const settled = (o) => o.kind === 'paid-started' || o.kind === 'paid' || o.kind === 'payment-cancelled';
192
+ async function waitedOutcome(key, planId, checkoutUrl, opts) {
193
+ let start;
194
+ try {
195
+ start = await planById(key, planId);
196
+ }
197
+ catch {
198
+ start = undefined;
199
+ }
200
+ const w = await waitForPayment(key, planId, start, opts);
201
+ if (w.state.kind === 'started')
202
+ return { kind: 'paid-started', scanId: w.state.scanId, scanStatus: w.state.scanStatus, plan: w.plan, planId, checkoutUrl };
203
+ if (w.result === 'done' && w.state.kind === 'cancelled')
204
+ return { kind: 'payment-cancelled', plan: w.plan, planId, checkoutUrl };
205
+ if (w.state.kind === 'paid')
206
+ return { kind: 'paid', plan: w.plan, planId, checkoutUrl };
207
+ return { kind: 'payment-pending', why: w.result === 'skipped' ? 'skipped' : 'timeout', planId, checkoutUrl };
208
+ }
166
209
  export async function startWithPayment(key, op, args, opts = {}) {
167
210
  let reply;
168
211
  try {
@@ -178,34 +221,26 @@ export async function startWithPayment(key, op, args, opts = {}) {
178
221
  if (!url)
179
222
  throw new Exit(EXIT.error, `Sekura answered with a payment link this CLI does not open: ${due.checkoutUrl}`);
180
223
  const planId = typeof due.planId === 'string' && due.planId ? due.planId : null;
224
+ const code = checkoutCodeOf(due, e instanceof Error ? e.message : '');
225
+ if (code && planId)
226
+ saveCheckoutCode(planId, code);
181
227
  const opened = openLink(url.href, { browser: opts.browser });
182
228
  if (!opened.opened && !interactive()) {
183
- throw new Exit(EXIT.paymentNeedsBrowser, `Payment needs a browser. Open this link to pay; the scan starts once it is paid: ${url.href}${planId ? `\n To wait for it here: npx sekura@latest pay --plan ${planId}` : ''}`, { checkoutUrl: url.href, planId });
229
+ throw new Exit(EXIT.paymentNeedsBrowser, `Payment needs a browser. Open this link to pay; the scan starts once it is paid: ${url.href}${code ? `\n ${checkoutCodeLine(code)}` : ''}${planId ? `\n To wait for it here: npx sekura@latest pay --plan ${planId}` : ''}`, { checkoutUrl: url.href, planId, ...(code ? { promoCode: code.code } : {}) });
184
230
  }
185
231
  ;
186
- (opts.sayLink ?? sayCheckout)(opened, url);
232
+ (opts.sayLink ?? sayCheckout)(opened, url, code);
187
233
  if (!planId)
188
234
  return { kind: 'payment-pending', why: 'no-plan', planId: null, checkoutUrl: url.href };
189
- let start;
190
- try {
191
- start = await planById(key, planId);
192
- }
193
- catch {
194
- start = undefined;
195
- }
196
- const w = await waitForPayment(key, planId, start, opts);
197
- if (w.state.kind === 'started')
198
- return { kind: 'paid-started', scanId: w.state.scanId, scanStatus: w.state.scanStatus, plan: w.plan, planId, checkoutUrl: url.href };
199
- if (w.result === 'done' && w.state.kind === 'cancelled')
200
- return { kind: 'payment-cancelled', plan: w.plan, planId, checkoutUrl: url.href };
201
- if (w.state.kind === 'paid')
202
- return { kind: 'paid', plan: w.plan, planId, checkoutUrl: url.href };
203
- return { kind: 'payment-pending', why: w.result === 'skipped' ? 'skipped' : 'timeout', planId, checkoutUrl: url.href };
235
+ const outcome = await waitedOutcome(key, planId, url.href, opts);
236
+ if (code && settled(outcome))
237
+ dropCheckoutCode(planId);
238
+ return outcome;
204
239
  }
205
240
  if (opts.quoteId)
206
241
  dropQuote(opts.quoteId);
207
242
  const { data } = reply;
208
- return { kind: 'started', text: reply.text, data, scanId: typeof data.scanId === 'string' ? data.scanId : null, planId: typeof data.planId === 'string' ? data.planId : null };
243
+ return { kind: 'started', text: reply.text, data, scanId: typeof data.scanId === 'string' ? data.scanId.replace(/^ss-/i, '') : null, planId: typeof data.planId === 'string' ? data.planId : null };
209
244
  }
210
245
  export function exitCodeOfStart(o) {
211
246
  switch (o.kind) {
@@ -218,6 +253,12 @@ export function exitCodeOfStart(o) {
218
253
  }
219
254
  export const SCAN_TERMINAL = new Set(['done', 'failed', 'cancelled', 'expired']);
220
255
  export const scanFinished = (status) => !!status && SCAN_TERMINAL.has(status);
256
+ /** How long a scan is watched. A typical scan takes 35 to 40 minutes, and a
257
+ * long one more than an hour; an hour's watch, and a stray Enter, ended the
258
+ * first-scan watch before the scan did, and the report was never saved
259
+ * (Varsha's 0.5.20 test, 1 December 2026, bug 6). Two hours covers the
260
+ * longest scan seen so far with room to spare. */
261
+ export const SCAN_WATCH_MS = 120 * 60_000;
221
262
  export async function watchScan(key, scanId, opts = {}) {
222
263
  let detail = null;
223
264
  let seen = null;
@@ -231,6 +272,6 @@ export async function watchScan(key, scanId, opts = {}) {
231
272
  opts.onStatus?.(status, detail);
232
273
  }
233
274
  return scanFinished(status);
234
- }, { timeoutMs: opts.timeoutMs ?? 60 * 60_000, intervalMs: opts.intervalMs ?? 5000 });
275
+ }, { timeoutMs: opts.timeoutMs ?? SCAN_WATCH_MS, intervalMs: opts.intervalMs ?? 5000 });
235
276
  return { result, detail: detail, status: seen };
236
277
  }
package/dist/open.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { spawn, spawnSync } from 'node:child_process';
2
2
  import { platform } from 'node:os';
3
- import { onPath } from './catalogue.js';
3
+ import { join } from 'node:path';
4
+ import { HOST, onPath } from './catalogue.js';
4
5
  import { remoteSession } from './device.js';
5
6
  /** Whether this machine has a browser to open. On Linux that takes a
6
7
  * display and xdg-open; a bare server or container has neither, and the
@@ -10,15 +11,36 @@ export function hasBrowser(env = process.env) {
10
11
  return true;
11
12
  return !!(env.DISPLAY || env.WAYLAND_DISPLAY) && onPath('xdg-open');
12
13
  }
14
+ const BROWSER_PROTOCOLS = new Set(['https:', 'http:', 'file:']);
15
+ export function browserAddress(raw) {
16
+ let url;
17
+ try {
18
+ url = new URL(raw);
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ if (!BROWSER_PROTOCOLS.has(url.protocol))
24
+ return null;
25
+ return /[\s"]/.test(url.href) ? null : url.href;
26
+ }
27
+ export function windowsUrlOpener(env = process.env) {
28
+ const root = env.SystemRoot || env.windir;
29
+ return root ? join(root, 'System32', 'rundll32.exe') : 'rundll32.exe';
30
+ }
13
31
  /** Opens a URL in the default browser; false when there is none to ask. */
14
32
  export function openBrowser(url) {
15
33
  if (!hasBrowser())
16
34
  return false;
17
- const [cmd, args] = platform() === 'darwin' ? ['open', [url]]
18
- : platform() === 'win32' ? ['cmd', ['/c', 'start', '""', url.replace(/&/g, '^&')]]
19
- : ['xdg-open', [url]];
35
+ const href = browserAddress(url);
36
+ if (!href)
37
+ return false;
38
+ const windows = platform() === 'win32';
39
+ const [cmd, args] = platform() === 'darwin' ? ['open', [href]]
40
+ : windows ? [windowsUrlOpener(), ['url.dll,FileProtocolHandler', href]]
41
+ : ['xdg-open', [href]];
20
42
  try {
21
- const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
43
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true, ...(windows ? { windowsVerbatimArguments: true, windowsHide: true } : {}) });
22
44
  child.on('error', () => { });
23
45
  child.unref();
24
46
  return true;
@@ -46,6 +68,28 @@ export function openLink(url, opts = {}) {
46
68
  return { opened: false, url, why: 'no-browser' };
47
69
  return openBrowser(url) ? { opened: true, url } : { opened: false, url, why: 'failed' };
48
70
  }
71
+ export function trustedLink(raw, hosts) {
72
+ let url;
73
+ try {
74
+ url = new URL(raw);
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ const local = url.hostname === '127.0.0.1' || url.hostname === 'localhost';
80
+ if (url.protocol !== 'https:' && !(local && url.protocol === 'http:'))
81
+ return null;
82
+ if (url.username || url.password)
83
+ return null;
84
+ return hosts.has(url.host) ? url : null;
85
+ }
86
+ export const SEKURA_HOSTS = new Set([HOST]);
87
+ export const GITHUB_APP_HOSTS = new Set([HOST, 'github.com']);
88
+ export const NOT_OPENED = 'This link is not on a site this CLI opens, so it was not opened:';
89
+ export function openTrusted(raw, hosts, opts = {}) {
90
+ const url = trustedLink(raw, hosts);
91
+ return url ? openLink(url.href, opts) : { opened: false, url: raw, why: 'untrusted' };
92
+ }
49
93
  export function copyToClipboard(text, env = process.env) {
50
94
  if (remoteSession(env))
51
95
  return false;
package/dist/payment.js CHANGED
@@ -1,29 +1,45 @@
1
1
  import { ENDPOINT } from './catalogue.js';
2
+ import { trustedLink } from './open.js';
2
3
  export const SEKURA_ORIGIN = new URL(ENDPOINT).origin;
3
4
  const OPENABLE_HOSTS = new Set(['checkout.stripe.com', 'billing.stripe.com', new URL(ENDPOINT).host]);
4
- export function openableLink(raw) {
5
- let url;
6
- try {
7
- url = new URL(raw);
8
- }
9
- catch {
10
- return null;
11
- }
12
- const local = url.hostname === '127.0.0.1' || url.hostname === 'localhost';
13
- if (url.protocol !== 'https:' && !(local && url.protocol === 'http:'))
5
+ export const openableLink = (raw) => trustedLink(raw, OPENABLE_HOSTS);
6
+ const CODE_SHAPE = /^[A-Z0-9]{3,24}$/;
7
+ const CODE_IN_TEXT = /\benter the code ([A-Z0-9]{3,24})(?![A-Za-z0-9])/;
8
+ const SAVING_IN_TEXT = /\bthe (\$\d+(?:\.\d{2})?) becomes (\$\d+(?:\.\d{2})?)(?![\d.]*\d)/;
9
+ export function checkoutCodeOf(data, text) {
10
+ const named = CODE_IN_TEXT.exec(text)?.[1];
11
+ const sent = typeof data.promoCode === 'string' && CODE_SHAPE.test(data.promoCode) ? data.promoCode : null;
12
+ const code = named ?? sent;
13
+ if (!code)
14
14
  return null;
15
- return OPENABLE_HOSTS.has(url.host) ? url : null;
15
+ const saving = SAVING_IN_TEXT.exec(text);
16
+ return { code, saving: saving ? `the ${saving[1]} becomes ${saving[2]}` : null };
16
17
  }
18
+ export const checkoutCodeLine = (c) => `Enter the code ${c.code} on the Stripe page${c.saving ? `: ${c.saving}` : ''}.`;
17
19
  export const paymentMethodsLink = () => `${SEKURA_ORIGIN}/app/payment-methods`;
18
20
  export const scanLink = (scanId) => `${SEKURA_ORIGIN}/app/scans/${encodeURIComponent(scanId.startsWith('ss-') ? scanId : `ss-${scanId}`)}`;
19
- const newScanOf = (start, now) => now.lastScan && now.lastScan.id !== start?.lastScan?.id ? now.lastScan : null;
21
+ const IN_FLIGHT = new Set(['pending_authorization', 'queued', 'running']);
22
+ /** The scan this payment started. A new scan since the wait began; or, when
23
+ * the payment had already landed before the wait began (`pay --plan` run
24
+ * after paying, the "To wait for it again" command), the scan in flight on
25
+ * it. That case read "The scan starts within a few minutes" while the scan
26
+ * was already running (Claude's run of the customer flow, 1 December 2026:
27
+ * queued 09:32:17, claimed 09:32:35, the CLI said "within a few minutes"
28
+ * at 09:32:36). */
29
+ const newScanOf = (start, now) => {
30
+ if (!now.lastScan)
31
+ return null;
32
+ if (now.lastScan.id !== start?.lastScan?.id)
33
+ return now.lastScan;
34
+ return start?.status === 'active' && IN_FLIGHT.has(now.lastScan.status) ? now.lastScan : null;
35
+ };
20
36
  export function paymentState(start, now) {
21
37
  if (!now)
22
38
  return start ? { kind: 'cancelled' } : { kind: 'waiting' };
23
39
  if (now.status === 'active') {
24
40
  const scan = newScanOf(start, now);
25
41
  if (scan)
26
- return { kind: 'started', scanId: scan.id, scanStatus: scan.status };
42
+ return { kind: 'started', scanId: scan.id.replace(/^ss-/i, ''), scanStatus: scan.status };
27
43
  const backAsItWas = start?.status === 'pending' && (start.pendingFrom === 'rerun' || start.pendingFrom === 'upgrade') && !now.nextRunAt && !now.pendingFrom;
28
44
  return backAsItWas && start.plan === now.plan ? { kind: 'cancelled' } : { kind: 'paid' };
29
45
  }