sekura 0.5.17 → 0.5.20

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.
package/README.md CHANGED
@@ -14,20 +14,20 @@ Every step is read from your account, so a second run carries on where the first
14
14
 
15
15
  ## Which Sekura servers do this today
16
16
 
17
- The GitHub-code sign-in, the Terms in the terminal, the report download and a free first scan started from the terminal need a Sekura server with CLI onboarding switched on. Today that is `dev.sekura.ai`. Against `sekura.ai` the CLI notices the server does not offer the new sign-in and uses the Sekura-page sign-in instead: you approve on a Sekura page, the Terms and the GitHub App are finished on Sekura pages the CLI opens and waits on, `report` and `billing --open` give you a link, and a first scan is quoted at its price. `--legacy-login` asks for that sign-in on any server. Every other command works the same on both.
17
+ The GitHub-code sign-in, the Terms in the terminal, the report download and a free first scan started from the terminal need a Sekura server with CLI onboarding switched on. Both `sekura.ai` and `dev.sekura.ai` have it. Against a server that does not offer the new sign-in, the CLI notices and uses the Sekura-page sign-in instead: you approve on a Sekura page, the Terms and the GitHub App are finished on Sekura pages the CLI opens and waits on, `report` and `billing --open` give you a link, and a first scan is quoted at its price. `--legacy-login` asks for that sign-in on any server. Every other command works the same either way.
18
18
 
19
19
  ## What a first run does
20
20
 
21
21
  1. **Detects** the tools on this machine: Claude Code, Cursor, GitHub Copilot in VS Code, OpenAI Codex, Kiro, Cline, Zed, Antigravity, OpenCode, JetBrains Junie, Factory Droid, Tabnine, Devin and Goose. With none found it says how to name one (`--tools`) and carries on with your account.
22
- 2. **Asks one question**, with every detected tool, your user configuration, the skill and the sign-in as the defaults: `Connect Claude Code, Cursor and OpenAI Codex for every project, with the skill, and sign in to Sekura?` Answer **Yes**, **No**, or **Choose** to pick the tools, where (every project, or this project only when run inside one), the skill and the sign-in. A flag answers its own question and skips it.
23
- 3. **Shows the plan** before anything happens: each file and the exact entry, or the tool's own command, with `Authorization: Bearer <your key, after sign-in>` where the key will go (a key you already have is shown as `sek_live_…abcd`). Then it asks **Apply?**
22
+ 2. **Asks one question**, with every detected tool, your user configuration, the skill and the sign-in as the defaults: `Connect Claude Code, Cursor and OpenAI Codex?`, under a line that reads `Every project · with skill · sign in with GitHub`. With more than three tools the question is `Connect these 5 tools?` and their names go on the line above. Answer **Yes**, **No**, or **Choose** to pick the tools, where (every project, or this project only when run inside one), the skill and the sign-in. A flag answers its own question and skips it.
23
+ 3. **Shows the plan** before anything happens, one line for each step: the file Sekura is added to, or the tool's own command, then the skill. Then it asks **Apply?** `--dry-run` prints the detail instead and stops there: each file and the exact entry, with `Authorization: Bearer <your key, after sign-in>` where the key will go (a key you already have is shown as `sek_live_…abcd`).
24
24
  4. **Signs you in.** It prints a code, copies it to your clipboard and opens `github.com/login/device`; you enter the code and approve. Over SSH, in a container, or with `--no-browser`, it prints the address instead of opening it. If the sign-in does not finish, nothing is written and the run stops with exit code 4.
25
25
  5. **Writes the tool entries and the skill**, one step at a time, saying what each did. Your tools get a key of their own (see Your keys). Files that are not plain JSON (Zed's `settings.json` with comments, for one) are never rewritten; you are shown the lines to add. Codex and Devin cannot take a key in their configuration, so the CLI prints the one command that signs each in (`codex mcp login sekura`, `devin mcp login sekura`).
26
26
  6. **Checks** that the Sekura server answers and takes your key.
27
27
  7. **The Terms.** It prints the consent sentence and links to the documents, then asks **I accept** or **Not now**, and whether you want product emails. Nothing is accepted for you: `--yes` skips this step.
28
28
  8. **The GitHub App.** If Sekura cannot scan anything yet, or not the repository in this folder, it opens the install page on github.com and carries on by itself once the repository shows up. Enter skips the wait.
29
29
  9. **A repository.** This folder's GitHub remote first, otherwise your pick. It is saved as the default for `scan` and `plan`.
30
- 10. **A first scan**, when the account has none yet. The quote is printed as Sekura gives it, with the authorization wording and the price, and nothing starts until you agree. It is the $10 one-time scan: Stripe Checkout opens, the code NPMSCAN entered there makes it $0, and the CLI waits for the payment. After the first scan, a repository is scanned on a monthly plan (`plan start`); Sekura sells no other one-time scan. Then it follows the scan (Enter stops watching; the scan carries on), prints the findings by severity and saves the report as `sekura-report-<scan-id>.html`.
30
+ 10. **A first scan**, when the account has none yet. The quote is printed as Sekura gives it, with the authorization wording and the price, and nothing starts until you agree. It is the $10 one-time scan: Stripe Checkout opens, the CLI prints the code to enter there (NPMSCAN, which makes it $0), and it waits for the payment. After the first scan, a repository is scanned on a monthly plan (`plan start`); Sekura sells no other one-time scan. Then it follows the scan (Enter stops watching; the scan carries on), prints the findings by severity and saves the report as `sekura-report-<scan-id>.html`.
31
31
  11. **Says what is next in each tool**, such as "Claude Code: start a new Claude Code session, then type /sekura", and how to scan again from the terminal.
32
32
 
33
33
  ## Commands
@@ -174,7 +174,7 @@ The keys are stored in plain text. Every file the CLI writes one into, its own a
174
174
  - **The server follows the key.** Without `SEKURA_ENDPOINT` or `--endpoint`, the CLI talks to the server your saved key is from, and every link it prints is on that server. It says so when that is not `sekura.ai`.
175
175
  - **Codex and Devin** sign in with keys of their own; the CLI prints the command and runs nothing.
176
176
  - **See or revoke a key** at [sekura.ai/app/settings](https://sekura.ai/app/settings) → Agents and API keys. Revoking one there ends it everywhere at once; run `sekura login` for a new one.
177
- - **`sekura logout`** revokes the CLI's own key on Sekura and removes it here. Your tools keep their key, which stays recorded so `uninstall` can revoke it. With a single Sekura-page key, `logout` only removes the saved copy, because your tools are using it.
177
+ - **`sekura logout`** revokes the CLI's own key on Sekura and removes it here. The key your tools use was made from that sign-in, so Sekura ends it too; run `npx sekura@latest` again to sign in and give them a new one. With a single Sekura-page key, `logout` only removes the saved copy, because your tools are using it.
178
178
  - **`sekura uninstall`** removes the entries (with their key), the skill and the guidance block. Then it revokes your tools' key and the CLI's key on the server that made them, and deletes the saved copies. If that server cannot revoke a key from the CLI, it tells you which key to revoke in Settings. `SEKURA_API_KEY` is never revoked: it is a key you made. `--keep-login` keeps the saved keys, and revokes nothing.
179
179
  - **`--no-login`** writes no key anywhere.
180
180
 
package/dist/catalogue.js CHANGED
@@ -11,7 +11,7 @@
11
11
  // person chooses, and a tool they did not choose is not touched.
12
12
  import { existsSync, readdirSync, readFileSync } from 'node:fs';
13
13
  import { homedir, platform } from 'node:os';
14
- import { join, delimiter } from 'node:path';
14
+ import { join, delimiter, isAbsolute } from 'node:path';
15
15
  import { setCommandOrigin } from './ui.js';
16
16
  /** The home directory, overridable for tests. */
17
17
  export const home = () => process.env.SEKURA_HOME || homedir();
@@ -113,15 +113,19 @@ export function devinFile(h, name) {
113
113
  }
114
114
  /** True when `bin` is an executable on PATH. */
115
115
  export function onPath(bin) {
116
+ return pathOf(bin) !== null;
117
+ }
118
+ export function pathOf(bin) {
116
119
  const exts = platform() === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
117
- for (const dir of (process.env.PATH || '').split(delimiter)) {
118
- if (!dir)
119
- continue;
120
- for (const ext of exts)
121
- if (existsSync(join(dir, bin + ext)))
122
- return true;
120
+ const dirs = isAbsolute(bin) || /[\\/]/.test(bin) ? [''] : (process.env.PATH || '').split(delimiter).filter(Boolean);
121
+ for (const dir of dirs) {
122
+ for (const ext of exts) {
123
+ const candidate = dir ? join(dir, bin + ext) : bin + ext;
124
+ if (existsSync(candidate))
125
+ return candidate;
126
+ }
123
127
  }
124
- return false;
128
+ return null;
125
129
  }
126
130
  /** Stands in for the key in the plan shown before the sign-in. Not a key
127
131
  * shape (no sek_ prefix), so it is never redacted into one, and writers.ts
@@ -1,5 +1,6 @@
1
1
  import { Command } from 'commander';
2
- import { openBrowser, readKey } from '../auth.js';
2
+ import { readKey } from '../auth.js';
3
+ import { openLink } from '../open.js';
3
4
  import { cliApi, getBilling, getPlans, isMissingRoute, isToolError, SignedOut } from '../api.js';
4
5
  import { cardLines, cardsFingerprint, openableLink, paymentMethodsLink, planLines } from '../payment.js';
5
6
  import { cross, dot, printJson, say, tick, waitFor } from '../ui.js';
@@ -98,7 +99,7 @@ export async function runBilling(opts = {}) {
98
99
  return 1;
99
100
  }
100
101
  const link = page.link;
101
- const opened = opts.browser === false ? false : openBrowser(link);
102
+ const opened = openLink(link, { browser: opts.browser }).opened;
102
103
  const where = page.what === 'card' ? 'Stripe\'s page for saving a card' : page.what === 'portal' ? 'your cards on Stripe' : 'your payment methods';
103
104
  if (opened)
104
105
  say(`${tick} Opened ${where} in the browser.`);
@@ -11,7 +11,7 @@ import { credentialsPath, forgetKey, hostOf, readSavedKey, savedCredentials } fr
11
11
  import { EXIT, Exit } from '../exit.js';
12
12
  import { howToScan, toolLogin } from '../guide.js';
13
13
  import { revokeSessionKey, toolKeyFor, toolKeyName } from '../session.js';
14
- import { ensureSignedIn } from '../steps.js';
14
+ import { ensureSignedIn, ensureTerms, TERMS_LATER } from '../steps.js';
15
15
  import { defaultRepository } from '../state.js';
16
16
  import { cross, dot, say, tick } from '../ui.js';
17
17
  /** A tool name that names two things ("Devin Desktop and the Devin CLI")
@@ -72,9 +72,16 @@ export async function runLogin(opts) {
72
72
  if (!names.length)
73
73
  say(`${dot} No tool on this machine has Sekura yet: run npx sekura@latest init.`);
74
74
  const a = session.account;
75
+ // Asked here, not reported as a fault with a command to go and run (Sudhir,
76
+ // 1 December 2026, on Tikka's run: "Terms not accepted yet. A scan cannot
77
+ // start before that" read as an error and was "not polished"). A person
78
+ // who says Not now hears what it is for, and how to come back to it.
75
79
  if (a?.termsAccepted === false || a?.termsUpdated === true) {
76
80
  say();
77
- say(`${dot} Terms not accepted yet. A scan cannot start before that: npx sekura@latest terms`);
81
+ if (interactive)
82
+ await ensureTerms(session, { interactive, soft: true });
83
+ else
84
+ say(`${dot} ${TERMS_LATER}`);
78
85
  }
79
86
  if (names.length) {
80
87
  say();
@@ -108,7 +115,7 @@ export async function runLogout() {
108
115
  }
109
116
  say(forgetKey() ? `${tick} Removed it from ${credentialsPath()}` : `${dot} No saved key at ${credentialsPath()}`);
110
117
  say(saved.kind === 'cli'
111
- ? ` Your coding tools keep their own key, which stays recorded here so that npx sekura@latest uninstall can revoke it. To end it now: ${KEYS_PAGE}.`
118
+ ? ` The key your coding tools use was made from this sign-in, so Sekura ends it too. Run npx sekura@latest to sign in again and give them a new one.`
112
119
  : ` Tools that were given the key keep it until you run npx sekura@latest uninstall. To end it everywhere: ${KEYS_PAGE}.`);
113
120
  say();
114
121
  }
@@ -1,8 +1,10 @@
1
1
  import { Command } from 'commander';
2
- import { openBrowser, readKey } from '../auth.js';
2
+ import { readKey } from '../auth.js';
3
3
  import { SignedOut } from '../api.js';
4
- import { planById, waitForPayment } from '../flow.js';
5
- import { monthlyName, openableLink, scanLink } from '../payment.js';
4
+ import { planById, sayCheckout, waitForPayment } from '../flow.js';
5
+ import { openLink } from '../open.js';
6
+ import { checkoutCodeLine, monthlyName, openableLink, scanLink } from '../payment.js';
7
+ import { checkoutCodeFor, dropCheckoutCode } from '../state.js';
6
8
  import { cross, dot, say, tick } from '../ui.js';
7
9
  import { abandonPayment, offerAbandon, sayAbandoned } from './shared.js';
8
10
  export const PAY_EXIT = { started: 0, paid: 0, notSignedIn: 4, cancelled: 3, timeout: 2, badLink: 1 };
@@ -11,14 +13,6 @@ const minutes = (raw, fallback) => {
11
13
  const n = Number(raw);
12
14
  return Number.isFinite(n) && n > 0 ? Math.min(n, 60) : fallback;
13
15
  };
14
- function sayOpened(link, opened) {
15
- if (opened)
16
- say(`${tick} Opened Stripe Checkout in your browser.`);
17
- else {
18
- say(`${dot} Open this link in a browser to pay:`);
19
- say(` ${link.href}`);
20
- }
21
- }
22
16
  function sayOutcome(state, plan) {
23
17
  const repo = planName(plan);
24
18
  if (state.kind === 'started') {
@@ -61,14 +55,17 @@ export async function runPay(link, opts = {}) {
61
55
  say(`${cross} Give the plan id Sekura answered with: npx sekura@latest pay --plan <id>`);
62
56
  return PAY_EXIT.badLink;
63
57
  }
58
+ const code = opts.plan ? checkoutCodeFor(opts.plan) : null;
64
59
  if (link) {
65
60
  const url = openableLink(link);
66
61
  if (!url) {
67
62
  say(`${cross} Not a Stripe Checkout or Sekura link, so it was not opened: ${link}`);
68
63
  return PAY_EXIT.badLink;
69
64
  }
70
- const opened = opts.open === false ? false : openBrowser(url.href);
71
- sayOpened(url, opened);
65
+ sayCheckout(openLink(url.href, { browser: opts.open !== false }), url, code);
66
+ }
67
+ else if (code) {
68
+ say(`${dot} ${checkoutCodeLine(code)}`);
72
69
  }
73
70
  const key = readKey();
74
71
  if (!opts.plan || !key) {
@@ -88,6 +85,7 @@ export async function runPay(link, opts = {}) {
88
85
  }
89
86
  const { result, state: final, plan: last } = await waitForPayment(key, planId, start, { timeoutMs: minutes(opts.timeout, 9) * 60_000, ...(opts.intervalMs ? { intervalMs: opts.intervalMs } : {}) });
90
87
  if (result === 'done' || final.kind === 'paid') {
88
+ dropCheckoutCode(planId);
91
89
  sayOutcome(final, last);
92
90
  return final.kind === 'cancelled' ? PAY_EXIT.cancelled : PAY_EXIT.started;
93
91
  }
@@ -1,6 +1,7 @@
1
1
  import { Command } from 'commander';
2
2
  import { requireKey } from '../flow.js';
3
- import { openLink } from '../open.js';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { NOT_OPENED, SEKURA_HOSTS, openLink, openTrusted } from '../open.js';
4
5
  import { dot, printJson, say, tick } from '../ui.js';
5
6
  import { fetchReport, ready, saySaved } from './shared.js';
6
7
  export async function runReport(scanId, opts = {}) {
@@ -11,15 +12,17 @@ export async function runReport(scanId, opts = {}) {
11
12
  else
12
13
  saySaved(saved);
13
14
  if (saved.kind === 'saved') {
14
- if (opts.open && openLink(`file://${saved.path}`, { browser: opts.browser }).opened && !opts.json)
15
+ if (opts.open && openLink(pathToFileURL(saved.path).href, { browser: opts.browser }).opened && !opts.json)
15
16
  say(`${tick} Opened it in your browser.`);
16
17
  return;
17
18
  }
18
19
  if (opts.json)
19
20
  return;
20
- const opened = openLink(saved.link, { browser: opts.browser });
21
+ const opened = openTrusted(saved.link, SEKURA_HOSTS, { browser: opts.browser });
21
22
  if (opened.opened)
22
23
  say(`${tick} Opened it in your browser.`);
24
+ else if (opened.why === 'untrusted')
25
+ say(`${dot} ${NOT_OPENED} ${saved.link}`);
23
26
  if (saved.expiresAt)
24
27
  say(`${dot} The report is kept until ${saved.expiresAt}.`);
25
28
  }
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,11 @@
1
1
  import { HOST, SUPPORT } from './catalogue.js';
2
2
  export const unreachable = () => `${HOST} could not be reached. Check your internet connection and try again.`;
3
3
  export const serverTrouble = (status) => `${HOST} had a problem answering (HTTP ${status}). Try again in a minute; if it keeps happening, write to ${SUPPORT}.`;
4
+ export const REQUEST_TIMEOUT_MS = 25_000;
5
+ export const timed = (init, timeoutMs = REQUEST_TIMEOUT_MS) => init.signal ? init : { ...init, signal: AbortSignal.timeout(timeoutMs) };
4
6
  export async function reach(url, init) {
5
7
  try {
6
- return await fetch(url, init);
8
+ return await fetch(url, timed(init));
7
9
  }
8
10
  catch {
9
11
  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();
@@ -136,9 +136,9 @@ export async function waitForPayment(key, planId, start, opts = {}) {
136
136
  let state = { kind: 'waiting' };
137
137
  let cancelledSeen = 0;
138
138
  let paidAt = null;
139
- const m = opts.message ?? 'Waiting for the payment to complete in your browser (Enter to stop waiting)';
139
+ const m = opts.message ?? 'Complete the payment in your browser; this continues by itself (Enter stops waiting)';
140
140
  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 () => {
141
+ const result = await waitFor(() => (paidAt ? 'Payment received. Starting the scan…' : waiting()), async () => {
142
142
  last = await planById(key, planId);
143
143
  state = paymentState(start, last);
144
144
  if (state.kind === 'cancelled')
@@ -155,14 +155,34 @@ export async function waitForPayment(key, planId, start, opts = {}) {
155
155
  /** A Checkout link is long, and wrapped by the terminal it ran back to the
156
156
  * left edge (Varsha's test, R3). Opened, it is not printed; otherwise it
157
157
  * gets a line of its own, never broken. */
158
- const sayCheckout = (opened, url) => {
158
+ export const sayCheckout = (opened, url, code = null) => {
159
159
  if (opened.opened)
160
160
  say(`${tick} Opened Stripe Checkout in your browser.`);
161
161
  else {
162
162
  say(`${dot} Open this link in a browser to pay:`);
163
163
  say(` ${url.href}`);
164
164
  }
165
+ if (code)
166
+ say(`${dot} ${checkoutCodeLine(code)}`);
165
167
  };
168
+ const settled = (o) => o.kind === 'paid-started' || o.kind === 'paid' || o.kind === 'payment-cancelled';
169
+ async function waitedOutcome(key, planId, checkoutUrl, opts) {
170
+ let start;
171
+ try {
172
+ start = await planById(key, planId);
173
+ }
174
+ catch {
175
+ start = undefined;
176
+ }
177
+ const w = await waitForPayment(key, planId, start, opts);
178
+ if (w.state.kind === 'started')
179
+ return { kind: 'paid-started', scanId: w.state.scanId, scanStatus: w.state.scanStatus, plan: w.plan, planId, checkoutUrl };
180
+ if (w.result === 'done' && w.state.kind === 'cancelled')
181
+ return { kind: 'payment-cancelled', plan: w.plan, planId, checkoutUrl };
182
+ if (w.state.kind === 'paid')
183
+ return { kind: 'paid', plan: w.plan, planId, checkoutUrl };
184
+ return { kind: 'payment-pending', why: w.result === 'skipped' ? 'skipped' : 'timeout', planId, checkoutUrl };
185
+ }
166
186
  export async function startWithPayment(key, op, args, opts = {}) {
167
187
  let reply;
168
188
  try {
@@ -178,29 +198,21 @@ export async function startWithPayment(key, op, args, opts = {}) {
178
198
  if (!url)
179
199
  throw new Exit(EXIT.error, `Sekura answered with a payment link this CLI does not open: ${due.checkoutUrl}`);
180
200
  const planId = typeof due.planId === 'string' && due.planId ? due.planId : null;
201
+ const code = checkoutCodeOf(due, e instanceof Error ? e.message : '');
202
+ if (code && planId)
203
+ saveCheckoutCode(planId, code);
181
204
  const opened = openLink(url.href, { browser: opts.browser });
182
205
  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 });
206
+ 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
207
  }
185
208
  ;
186
- (opts.sayLink ?? sayCheckout)(opened, url);
209
+ (opts.sayLink ?? sayCheckout)(opened, url, code);
187
210
  if (!planId)
188
211
  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 };
212
+ const outcome = await waitedOutcome(key, planId, url.href, opts);
213
+ if (code && settled(outcome))
214
+ dropCheckoutCode(planId);
215
+ return outcome;
204
216
  }
205
217
  if (opts.quoteId)
206
218
  dropQuote(opts.quoteId);
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,19 +1,21 @@
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
21
  const newScanOf = (start, now) => now.lastScan && now.lastScan.id !== start?.lastScan?.id ? now.lastScan : null;
package/dist/session.js CHANGED
@@ -2,7 +2,7 @@ import { ISSUER, adoptSavedKey, credentialsPath, forgetKey, keyName, readKey, re
2
2
  import { cliApi, getAccount, isMissingRoute, isToolError, SignedOut } from './api.js';
3
3
  import { ENDPOINT, HOST } from './catalogue.js';
4
4
  import { DEVICE_GRANT, TokenRouteMissing, form, pollForToken } from './device.js';
5
- import { reach, refusal } from './errors.js';
5
+ import { reach, refusal, timed } from './errors.js';
6
6
  import { signInHere as legacySignInHere } from './guide.js';
7
7
  import { copyToClipboard, openLink } from './open.js';
8
8
  import { cross, dot, say, spinner, tick } from './ui.js';
@@ -30,7 +30,7 @@ export async function startGithubSignIn() {
30
30
  export async function pollGithubSignIn(code, opts = {}) {
31
31
  let data;
32
32
  try {
33
- data = await pollForToken(() => fetch(`${ISSUER}/oauth/github/token`, form({ grant_type: DEVICE_GRANT, device_code: code.device_code, resource: ENDPOINT })), code, { ...opts, routeMayBeMissing: true, denied: 'the sign-in was cancelled on github.com' });
33
+ data = await pollForToken(() => fetch(`${ISSUER}/oauth/github/token`, timed(form({ grant_type: DEVICE_GRANT, device_code: code.device_code, resource: ENDPOINT }))), code, { ...opts, routeMayBeMissing: true, denied: 'the sign-in was cancelled on github.com' });
34
34
  }
35
35
  catch (e) {
36
36
  if (e instanceof TokenRouteMissing)
package/dist/state.js CHANGED
@@ -3,6 +3,7 @@ import { dirname, join } from 'node:path';
3
3
  import { ENDPOINT, credentialsPath } from './catalogue.js';
4
4
  import { writeConfig } from './writers.js';
5
5
  export const QUOTE_TTL_MS = 15 * 60_000;
6
+ export const CHECKOUT_LINK_TTL_MS = 24 * 60 * 60_000;
6
7
  export const statePath = () => join(dirname(credentialsPath()), 'state.json');
7
8
  function readFile() {
8
9
  try {
@@ -24,6 +25,7 @@ function writeFile(s) {
24
25
  writeConfig(p, JSON.stringify(s, null, 2) + '\n', true);
25
26
  }
26
27
  const live = (quotes, now) => Object.fromEntries(Object.entries(quotes ?? {}).filter(([, q]) => q && Date.parse(q.expiresAt) > now));
28
+ const payable = (codes, now) => Object.fromEntries(Object.entries(codes ?? {}).filter(([, c]) => c && typeof c.code === 'string' && Date.parse(c.savedAt) + CHECKOUT_LINK_TTL_MS > now));
27
29
  export function readState(endpoint = ENDPOINT) {
28
30
  const s = readFile().servers[endpoint];
29
31
  return s && typeof s === 'object' ? s : {};
@@ -35,6 +37,9 @@ export function updateState(change, endpoint = ENDPOINT) {
35
37
  next.quotes = live(next.quotes, Date.now());
36
38
  if (!Object.keys(next.quotes).length)
37
39
  delete next.quotes;
40
+ next.checkoutCodes = payable(next.checkoutCodes, Date.now());
41
+ if (!Object.keys(next.checkoutCodes).length)
42
+ delete next.checkoutCodes;
38
43
  if (Object.keys(next).length)
39
44
  file.servers[endpoint] = next;
40
45
  else
@@ -70,3 +75,16 @@ export function dropQuote(quoteId, endpoint = ENDPOINT) {
70
75
  updateState((s) => { if (s.quotes)
71
76
  delete s.quotes[quoteId]; }, endpoint);
72
77
  }
78
+ export function saveCheckoutCode(planId, c, endpoint = ENDPOINT) {
79
+ updateState((s) => { s.checkoutCodes = { ...(s.checkoutCodes ?? {}), [planId]: { code: c.code, saving: c.saving, savedAt: new Date().toISOString() } }; }, endpoint);
80
+ }
81
+ export function checkoutCodeFor(planId, endpoint = ENDPOINT) {
82
+ const c = payable(readState(endpoint).checkoutCodes, Date.now())[planId];
83
+ return c ? { code: c.code, saving: typeof c.saving === 'string' ? c.saving : null } : null;
84
+ }
85
+ export function dropCheckoutCode(planId, endpoint = ENDPOINT) {
86
+ if (!readState(endpoint).checkoutCodes?.[planId])
87
+ return;
88
+ updateState((s) => { if (s.checkoutCodes)
89
+ delete s.checkoutCodes[planId]; }, endpoint);
90
+ }
package/dist/steps.js CHANGED
@@ -2,7 +2,7 @@ import { readKey, readToolKey, redact } from './auth.js';
2
2
  import { getAccount, getBilling, getPlans, isMissingRoute, isToolError, listRepositories, SignedOut } from './api.js';
3
3
  import { ENDPOINT, HOST, carriesKey, link } from './catalogue.js';
4
4
  import { EXIT, Exit, SIGN_IN_HINT } from './exit.js';
5
- import { openLink } from './open.js';
5
+ import { GITHUB_APP_HOSTS, NOT_OPENED, SEKURA_HOSTS, openTrusted } from './open.js';
6
6
  import { cardLines, planLines } from './payment.js';
7
7
  import { buildPlan, detectTools, stepPresent } from './plan.js';
8
8
  import { currentGithubRepo } from './repo.js';
@@ -160,6 +160,9 @@ async function refreshAccount(s) {
160
160
  }
161
161
  return s.account;
162
162
  }
163
+ /** What a person who has not accepted the Terms reads: the one step left
164
+ * and how to take it, not a fault. */
165
+ export const TERMS_LATER = 'One step before your first scan: accept the Terms. When you are ready, run npx sekura@latest terms.';
163
166
  export async function ensureTerms(s, flags = {}) {
164
167
  const interactive = isInteractive(flags);
165
168
  const a = s.account ?? await refreshAccount(s);
@@ -171,7 +174,7 @@ export async function ensureTerms(s, flags = {}) {
171
174
  await refreshAccount(s);
172
175
  if (outcome === 'declined') {
173
176
  if (flags.soft) {
174
- say(`${dot} Terms not accepted yet. A scan cannot start before that: run npx sekura@latest terms when you are ready.`);
177
+ say(`${dot} ${TERMS_LATER}`);
175
178
  return 'declined';
176
179
  }
177
180
  throw new Exit(EXIT.declined, 'Terms not accepted; nothing was started. Run npx sekura@latest terms when you are ready.');
@@ -189,10 +192,10 @@ export async function ensureTerms(s, flags = {}) {
189
192
  const page = a?.links?.dashboard ?? link('/app');
190
193
  say(`${dot} Accept the Terms before your first scan: ${page}`);
191
194
  if (interactive && await ask(`Open ${HOST} to do that now?`, { default: true, short: 'Open it now?' })) {
192
- const o = openLink(page, { browser: flags.browser });
195
+ const o = openTrusted(page, SEKURA_HOSTS, { browser: flags.browser });
193
196
  if (!o.opened)
194
- say(` Open ${page}`);
195
- const r = await waitFor(`Waiting for the Terms on ${HOST}… press Enter to skip`, async () => {
197
+ say(o.why === 'untrusted' ? ` ${NOT_OPENED} ${page}` : ` Open ${page}`);
198
+ const r = await waitFor(`Accept the Terms on ${HOST}; this continues by itself (Enter skips)`, async () => {
196
199
  const now = await getAccount(s.key);
197
200
  s.account = now;
198
201
  return now.termsAccepted !== false;
@@ -271,27 +274,36 @@ export async function ensureApp(s, flags = {}) {
271
274
  // The install link carries a long state token: printed after "Opened" it
272
275
  // wrapped back to the left edge and was no use to anyone (Varsha's test,
273
276
  // F8). Opened, it is not printed; otherwise it gets a line of its own.
274
- const opened = openLink(url, { browser: flags.browser });
277
+ const opened = openTrusted(url, GITHUB_APP_HOSTS, { browser: flags.browser });
275
278
  if (opened.opened)
276
279
  say(` Opened ${onGithub ? 'github.com' : HOST} in your browser.`);
277
280
  else {
278
- say(' Open this link to install it:');
281
+ say(opened.why === 'untrusted' ? ` ${NOT_OPENED}` : ' Open this link to install it:');
279
282
  say(` ${url}`);
280
283
  }
281
284
  const before = new Set(repos.map((r) => r.fullName.toLowerCase()));
282
- const r = await waitFor('Waiting for the GitHub App install… press Enter to skip', async () => {
285
+ const r = await waitFor('Finish the install on github.com; this continues by itself (Enter skips)', async () => {
283
286
  list = await listRepositories(s.key, { refresh: true });
284
287
  repos = repositoriesOf(list);
285
- if (want)
286
- return repos.some((x) => same(x.fullName, want));
288
+ if (want && repos.some((x) => same(x.fullName, want)))
289
+ return true;
287
290
  if (ownMissing)
288
291
  return accountsOf(list).some((a) => same(a, own));
289
- return flags.add && before.size ? repos.some((x) => !before.has(x.fullName.toLowerCase())) : repos.length > 0;
292
+ // A first install is done when it lands, whatever was picked on GitHub.
293
+ // Waiting only for this folder's repository kept the terminal at "press
294
+ // Enter to skip" after the person had installed the App on another
295
+ // account without it (Tikka, 1 December 2026).
296
+ if (!before.size)
297
+ return repos.length > 0;
298
+ return repos.some((x) => !before.has(x.fullName.toLowerCase()));
290
299
  }, flags.wait);
291
300
  const found = r === 'done';
301
+ const hasWant = !!want && repos.some((x) => same(x.fullName, want));
292
302
  say(found
293
- ? `${tick} ${want ? `Sekura can scan ${want}` : ownMissing ? `The Sekura GitHub App is installed on ${own}` : before.size ? 'Sekura can scan more repositories now' : 'The Sekura GitHub App is installed'}`
303
+ ? `${tick} ${hasWant ? `Sekura can scan ${want}` : ownMissing ? `The Sekura GitHub App is installed on ${own}` : before.size ? 'Sekura can scan more repositories now' : 'The Sekura GitHub App is installed'}`
294
304
  : `${dot} Not there yet; you can finish the install later with npx sekura@latest repos --add`);
305
+ if (found && want && !hasWant)
306
+ say(` ${want} was not among the repositories you chose; pick one below, or add it later with npx sekura@latest repos --add`);
295
307
  return { installed: repos.length > 0, found, repositories: repos, link: url, accounts: accountsOf(list) };
296
308
  }
297
309
  export async function ensureRepository(s, flags = {}) {
package/dist/writers.js CHANGED
@@ -15,7 +15,8 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSyn
15
15
  import { randomBytes } from 'node:crypto';
16
16
  import { dirname } from 'node:path';
17
17
  import { spawnSync } from 'node:child_process';
18
- import { ENDPOINT, PENDING_KEY, SERVER_NAME } from './catalogue.js';
18
+ import { platform } from 'node:os';
19
+ import { ENDPOINT, PENDING_KEY, SERVER_NAME, pathOf } from './catalogue.js';
19
20
  import { redactAll } from './auth.js';
20
21
  export const SECRET_MODE = 0o600;
21
22
  export function writeConfig(path, text, secret) {
@@ -261,11 +262,28 @@ export function hasYaml(t) {
261
262
  const at = yamlLayout(lines, t.key);
262
263
  return 'entry' in at && !!at.entry && yamlOk(t, lines.slice(at.entry[0] + 1, at.entry[1]));
263
264
  }
264
- // ── commands ────────────────────────────────────────────────────────────────
265
- /** A read-only question (get, list) is given a time limit: a tool that
266
- * stopped to ask something on a closed stdin would hang `status` forever. */
267
265
  function spawn(bin, args, timeout) {
268
- return spawnSync(bin, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], ...(timeout ? { timeout } : {}) });
266
+ const options = { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], ...(timeout ? { timeout } : {}) };
267
+ const shim = platform() === 'win32' ? batchShimOf(bin) : null;
268
+ if (!shim)
269
+ return spawnSync(bin, args, options);
270
+ const line = batchCommandLine(shim, args);
271
+ if (line === null)
272
+ return { status: null, stdout: '', stderr: '', error: new Error(`${bin} cannot be run with these arguments on Windows`) };
273
+ return spawnSync(process.env.ComSpec || 'cmd.exe', ['/d', '/v:off', '/s', '/c', line], { ...options, windowsVerbatimArguments: true, windowsHide: true });
274
+ }
275
+ const BATCH_SHIM = /\.(cmd|bat)$/i;
276
+ export function batchShimOf(bin) {
277
+ const found = pathOf(bin);
278
+ return found && BATCH_SHIM.test(found) ? found : null;
279
+ }
280
+ const UNSAFE_IN_CMD = /["%\r\n\0]/;
281
+ const cmdQuoted = (word) => `"${word.replace(/(\\+)$/, '$1$1')}"`;
282
+ export function batchCommandLine(shim, args) {
283
+ const words = [shim, ...args];
284
+ if (words.some((w) => UNSAFE_IN_CMD.test(w)))
285
+ return null;
286
+ return `"${words.map(cmdQuoted).join(' ')}"`;
269
287
  }
270
288
  export function runCommand(bin, args) {
271
289
  const r = spawn(bin, args);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sekura",
3
- "version": "0.5.17",
3
+ "version": "0.5.20",
4
4
  "description": "Set up Sekura and scan your GitHub repositories from the terminal, and connect your coding tools: npx sekura@latest",
5
5
  "type": "module",
6
6
  "license": "MIT",