sekura 0.4.0 → 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,236 @@
1
+ import { confirm } from '@inquirer/prompts';
2
+ import { writeFileSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { CLI_API, ToolError, cliApi, cliFetch, isMissingRoute, isToolError, tools } from '../api.js';
5
+ import { EXIT, Exit, exitCodeFor, messageFor } from '../exit.js';
6
+ import { exitCodeOfStart, scanFinished, watchScan } from '../flow.js';
7
+ import { scanLink } from '../payment.js';
8
+ import { currentGithubRepo } from '../repo.js';
9
+ import { defaultRepository } from '../state.js';
10
+ import { cross, dot, interactive, say, tick } from '../ui.js';
11
+ export const DOCTOR_HINT = 'Run npx sekura@latest doctor to see what is left to set up.';
12
+ export function withQuoteOptions(cmd) {
13
+ return cmd
14
+ .option('--quote', 'print the quote, save it here and start nothing')
15
+ .option('--confirm <quoteId>', 'start exactly the quote that --quote printed')
16
+ .option('--yes', 'do not ask; needs --max-price for anything paid or authorized')
17
+ .option('--max-price <usd>', 'with --yes or --confirm, the most this may cost in US dollars')
18
+ .option('--card <card>', 'the saved card to charge: default, its last four digits, or its pm_ id')
19
+ .option('--json', 'print data as JSON on stdout')
20
+ .option('--no-browser', 'print links instead of opening them');
21
+ }
22
+ export function merged(cmd) {
23
+ const out = { ...(cmd.parent?.opts() ?? {}) };
24
+ for (const [k, v] of Object.entries(cmd.opts()))
25
+ if (v !== undefined)
26
+ out[k] = v;
27
+ return out;
28
+ }
29
+ export async function ready(fn) {
30
+ try {
31
+ return await fn();
32
+ }
33
+ catch (e) {
34
+ if (e instanceof ToolError && exitCodeFor(e) === EXIT.accountNotReady) {
35
+ throw new Exit(EXIT.accountNotReady, `${messageFor(e)}\n ${DOCTOR_HINT}`, { code: e.code, ...e.data });
36
+ }
37
+ throw e;
38
+ }
39
+ }
40
+ const REPO = /^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9._-]+$/;
41
+ export function resolveRepository(given, cwd = process.cwd()) {
42
+ if (given) {
43
+ const name = given.trim().replace(/^https?:\/\/github\.com\//i, '').replace(/\.git$/i, '').replace(/\/$/, '');
44
+ if (!REPO.test(name))
45
+ throw new Exit(EXIT.error, `${given} is not a GitHub repository name. Give it as owner/repo.`);
46
+ return name;
47
+ }
48
+ const saved = defaultRepository();
49
+ if (saved)
50
+ return saved;
51
+ const here = currentGithubRepo(cwd);
52
+ if (here)
53
+ return here;
54
+ throw new Exit(EXIT.error, 'No repository was named, none is saved as your default, and this folder has no GitHub remote. Give it as owner/repo, or run npx sekura@latest repos to see the ones Sekura can scan.');
55
+ }
56
+ const AGENT_LINE = /^If the person agrees, call |payment: \{ sharedPaymentToken|^nextStep:/;
57
+ const CONFIRM_WITH = /; confirm with payment: \{ savedCard: (?:true|\{ card: "[^"]*" \}) \}/g;
58
+ const CHECKOUT_HOW = /: leave payment out; the answer is 402 with a Stripe Checkout link to open in the person's browser/;
59
+ export function personText(text) {
60
+ const out = [];
61
+ for (const raw of text.split('\n')) {
62
+ if (AGENT_LINE.test(raw.replace(/^- /, '')))
63
+ continue;
64
+ out.push(raw.replace(CONFIRM_WITH, '').replace(CHECKOUT_HOW, ': a Stripe Checkout page in your browser'));
65
+ }
66
+ while (out.length && !out[out.length - 1].trim())
67
+ out.pop();
68
+ return out.join('\n');
69
+ }
70
+ export function sayText(text) {
71
+ say();
72
+ for (const l of personText(text).split('\n'))
73
+ say(` ${l}`);
74
+ say();
75
+ }
76
+ export const withoutConfirm = (args) => {
77
+ const { confirm: _dropped, ...rest } = args;
78
+ return rest;
79
+ };
80
+ const cliOnly = (e) => isMissingRoute(e) || isToolError(e, 'cli_sign_in_required');
81
+ export async function abandonPayment(key, planId) {
82
+ try {
83
+ const r = await cliApi(key, 'POST', '/payments/abandon', { planId });
84
+ return r.abandoned ? 'abandoned' : 'not-pending';
85
+ }
86
+ catch (e) {
87
+ if (cliOnly(e))
88
+ return 'unsupported';
89
+ if (isToolError(e, 'paid'))
90
+ return 'paid';
91
+ return 'failed';
92
+ }
93
+ }
94
+ export function sayAbandoned(result) {
95
+ if (result === 'abandoned')
96
+ say(`${tick} The payment was cancelled. Nothing was charged, and you can ask again whenever you like.`);
97
+ else if (result === 'paid')
98
+ say(`${tick} That payment went through, so there was nothing to cancel.`);
99
+ else if (result === 'not-pending')
100
+ say(`${dot} Nothing was waiting on a payment, so nothing was changed.`);
101
+ else if (result === 'unsupported')
102
+ say(`${dot} This Sekura server cannot cancel a payment from here. The Checkout link stops working by itself after 24 hours.`);
103
+ else
104
+ say(`${cross} The payment could not be cancelled just now. The Checkout link stops working by itself after 24 hours.`);
105
+ }
106
+ export async function offerAbandon(key, planId) {
107
+ if (!planId || !interactive())
108
+ return null;
109
+ const yes = await confirm({ message: 'Cancel this payment? Nothing is charged, and the Checkout link stops working.', default: false });
110
+ if (!yes)
111
+ return null;
112
+ const result = await abandonPayment(key, planId);
113
+ sayAbandoned(result);
114
+ return result;
115
+ }
116
+ const REPORT_REFUSALS = {
117
+ email_not_verified: () => `Verify the email address on your Sekura account before reading a report. ${DOCTOR_HINT}`,
118
+ not_found: (id) => `There is no scan ${id} on this account. npx sekura@latest scans lists yours.`,
119
+ report_missing: (id) => `Scan ${id} has no report to download.`,
120
+ 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`,
121
+ report_expired: (id) => `The report for scan ${id} is no longer kept, so it cannot be downloaded.`,
122
+ };
123
+ export const defaultReportPath = (scanId, cwd = process.cwd()) => resolve(cwd, `sekura-report-${scanId.replace(/[^A-Za-z0-9._-]/g, '_')}.html`);
124
+ export async function fetchReport(key, scanId, output) {
125
+ const path = `/scans/${encodeURIComponent(scanId)}/report`;
126
+ const r = await cliFetch(key, 'GET', path, undefined, { timeoutMs: 120_000 });
127
+ if (r.ok) {
128
+ const body = Buffer.from(await r.arrayBuffer());
129
+ const to = output ? resolve(output) : defaultReportPath(scanId);
130
+ writeFileSync(to, body);
131
+ return { kind: 'saved', path: to, bytes: body.length };
132
+ }
133
+ const data = (await r.json().catch(() => null));
134
+ const code = typeof data?.code === 'string' ? data.code : null;
135
+ const oldServer = r.status === 404 && !code;
136
+ if (!oldServer && code !== 'cli_sign_in_required') {
137
+ if (r.status === 401)
138
+ throw new Exit(EXIT.notSignedIn, 'Your Sekura key no longer works; run npx sekura@latest login.');
139
+ const said = typeof data?.error === 'string' ? data.error : typeof data?.message === 'string' ? data.message : `Sekura answered HTTP ${r.status}`;
140
+ throw new ToolError({ op: `GET ${CLI_API}${path}`, status: r.status, code: code ?? 'refused', message: REPORT_REFUSALS[code ?? '']?.(scanId, data ?? {}) ?? said, data: data ?? {} });
141
+ }
142
+ const link = (await tools.getReportLink(key, { scanId })).data;
143
+ return { kind: 'link', link: link.link, expiresAt: link.expiresAt ?? null, requiresSignIn: !!link.requiresSignIn };
144
+ }
145
+ export function saySaved(s) {
146
+ if (s.kind === 'saved')
147
+ say(`${tick} Report saved to ${s.path}`);
148
+ else
149
+ say(`${dot} This Sekura server does not hand the report to the CLI. Open it in a browser${s.requiresSignIn ? ' (it asks you to sign in)' : ''}: ${s.link}`);
150
+ }
151
+ const SEVERITY_ORDER = ['critical', 'high', 'medium', 'low', 'info', 'informational', 'unrated'];
152
+ export function severityWords(counts) {
153
+ const names = Object.keys(counts).sort((a, b) => {
154
+ const [x, y] = [SEVERITY_ORDER.indexOf(a), SEVERITY_ORDER.indexOf(b)];
155
+ return (x < 0 ? 99 : x) - (y < 0 ? 99 : y);
156
+ });
157
+ return names.filter((n) => counts[n] > 0).map((n) => `${counts[n]} ${n}`).join(', ');
158
+ }
159
+ export function sayFindings(f, shown = f.findings.length) {
160
+ if (!f.total) {
161
+ say(`${tick} No findings.`);
162
+ return;
163
+ }
164
+ say(`${tick} ${f.total} ${f.total === 1 ? 'finding' : 'findings'}: ${severityWords(f.counts)}`);
165
+ f.findings.slice(0, shown).forEach((x, i) => {
166
+ say(` ${i + 1}. [${x.severity}] ${x.title}${x.location ? ` — ${x.location}` : ''}`);
167
+ });
168
+ if (f.total > shown)
169
+ say(` … and ${f.total - shown} more: npx sekura@latest findings ${f.scanId}`);
170
+ }
171
+ export function sayScan(d) {
172
+ const s = d.scan;
173
+ const repo = s.target_owner && s.target_repo ? `${s.target_owner}/${s.target_repo}` : 'the repository';
174
+ const count = typeof s.findings_count === 'number' ? `, ${s.findings_count} ${s.findings_count === 1 ? 'finding' : 'findings'}` : '';
175
+ say(`${s.status === 'failed' ? cross : scanFinished(s.status) ? tick : dot} Scan ${s.id} of ${repo}: ${s.status}${s.status === 'done' ? count : ''}`);
176
+ say(` ${d.link ?? scanLink(s.id)}`);
177
+ }
178
+ export async function followScan(key, scanId, opts = {}) {
179
+ const watching = opts.watch ?? (interactive() && !opts.json);
180
+ if (!watching) {
181
+ say(`${dot} To follow it: npx sekura@latest scan show ${scanId} --watch`);
182
+ return;
183
+ }
184
+ const w = await watchScan(key, scanId, {
185
+ ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}),
186
+ ...(opts.intervalMs ? { intervalMs: opts.intervalMs } : {}),
187
+ onStatus: (status) => { if (!scanFinished(status))
188
+ say(`${dot} ${status}`); },
189
+ });
190
+ if (w.result !== 'done') {
191
+ 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 });
192
+ }
193
+ if (w.detail)
194
+ sayScan(w.detail);
195
+ if (w.status !== 'done')
196
+ throw new Exit(EXIT.error, `The scan ended as ${w.status}, so there is no report.`, { scanId, status: w.status });
197
+ try {
198
+ sayFindings((await tools.getScanFindings(key, { scanId, limit: 10 })).data, 10);
199
+ }
200
+ catch (e) {
201
+ say(`${cross} The findings could not be read: ${messageFor(e)}`);
202
+ }
203
+ if (opts.report === false)
204
+ return;
205
+ try {
206
+ saySaved(await fetchReport(key, scanId, opts.output));
207
+ }
208
+ catch (e) {
209
+ say(`${cross} The report could not be saved: ${messageFor(e)}. Try npx sekura@latest report ${scanId}`);
210
+ }
211
+ }
212
+ export async function afterStart(key, o, opts) {
213
+ if (o.kind === 'started') {
214
+ if (o.text)
215
+ sayText(o.text);
216
+ say(`${tick} ${opts.what} started.${o.scanId ? ` Scan id ${o.scanId}.` : ''}`);
217
+ if (o.scanId)
218
+ await followScan(key, o.scanId, opts);
219
+ return;
220
+ }
221
+ if (o.kind === 'paid-started') {
222
+ say(`${tick} Payment received. ${opts.what} started: scan id ${o.scanId} (${o.scanStatus}).`);
223
+ await followScan(key, o.scanId, opts);
224
+ return;
225
+ }
226
+ if (o.kind === 'paid') {
227
+ say(`${tick} Payment received. The scan starts within a few minutes: npx sekura@latest scans`);
228
+ return;
229
+ }
230
+ if (o.kind === 'payment-cancelled') {
231
+ throw new Exit(EXIT.declined, 'Checkout was closed without paying, so nothing was charged and nothing was started.', { planId: o.planId });
232
+ }
233
+ if (o.why === 'skipped')
234
+ await offerAbandon(key, o.planId);
235
+ throw new Exit(exitCodeOfStart(o), `No payment yet. The Checkout link stays valid for 24 hours, and the scan starts as soon as it is paid: ${o.checkoutUrl}${o.planId ? `\n To wait for it again: npx sekura@latest pay ${o.checkoutUrl} --plan ${o.planId} --no-open` : ''}`, { planId: o.planId, checkoutUrl: o.checkoutUrl });
236
+ }
@@ -1,7 +1,7 @@
1
1
  // `sekura status`: which tools are here, which carry Sekura, and whether the
2
2
  // server answers. Reads only.
3
3
  import { Command } from 'commander';
4
- import { ENDPOINT, carriesKey } from '../catalogue.js';
4
+ import { ENDPOINT, carriesKey, serverNote } from '../catalogue.js';
5
5
  import { buildPlan, detectTools, stepPresent } from '../plan.js';
6
6
  import { readKey, redact } from '../auth.js';
7
7
  import { getAccount, SignedOut } from '../api.js';
@@ -12,11 +12,15 @@ export async function runStatus(opts) {
12
12
  const scope = opts.scope ?? 'user';
13
13
  const detected = detectTools(cwd);
14
14
  say();
15
+ const note = serverNote();
16
+ if (note)
17
+ say(` ${note}`);
15
18
  if (!detected.length)
16
19
  say(' No supported coding tool found on this machine.');
17
20
  const key = readKey();
18
21
  const plan = buildPlan({ tools: detected.map((t) => t.id), scope, skill: true, cwd, key });
19
22
  const plain = key ? buildPlan({ tools: detected.map((t) => t.id), scope, skill: true, cwd }) : plan;
23
+ const seen = [];
20
24
  plan.steps.forEach((s, i) => {
21
25
  let p = stepPresent(s);
22
26
  // An entry without the key is still connected; its tool signs in itself.
@@ -25,14 +29,22 @@ export async function runStatus(opts) {
25
29
  p = true;
26
30
  how = ' (signs in in the tool)';
27
31
  }
32
+ if (s.kind === 'tool')
33
+ seen.push(p);
28
34
  const mark = p === true ? tick : p === 'unknown' ? dot : cross;
29
35
  const noun = s.kind === 'tool' ? 'connected' : 'installed';
30
- const word = p === true ? noun + how : p === 'unknown' ? (s.kind === 'tool' && s.target.kind === 'command' ? 'kept by the tool itself; ask it' : 'its file has comments; look by hand') : `not ${noun}`;
36
+ // A command target is 'unknown' only when the tool has no list to ask,
37
+ // or its binary did not answer; a link means its binary is not here.
38
+ const unknown = s.kind !== 'tool' ? '' : s.target.kind === 'command' ? 'kept by the tool itself; ask it'
39
+ : s.target.kind === 'link' ? 'cannot be checked here, because its command is not on PATH' : 'its file has comments; look by hand';
40
+ const word = p === true ? noun + how : p === 'unknown' ? unknown : `not ${noun}`;
31
41
  const label = s.kind === 'tool' ? s.tool.name : s.kind === 'skill' ? `skill ${s.path}` : `guidance ${s.path}`;
32
42
  say(`${mark} ${label}: ${word}`);
33
43
  });
34
44
  for (const s of plan.skipped)
35
45
  say(`${dot} ${s.tool.name}: ${s.why}`);
46
+ if (seen.length && !plan.skipped.length && seen.every((p) => p === false))
47
+ say(`${dot} Nothing on this machine is connected to Sekura.`);
36
48
  if (opts.verify !== false) {
37
49
  const v = await verifyEndpoint(ENDPOINT);
38
50
  say(`${v.ok ? tick : cross} ${v.detail}`);
@@ -0,0 +1,78 @@
1
+ import { Command } from 'commander';
2
+ import { EXIT, Exit } from '../exit.js';
3
+ import { requireKey } from '../flow.js';
4
+ import { isMissingRoute, isToolError } from '../api.js';
5
+ import { link } from '../catalogue.js';
6
+ import { getTerms, showTerms, termsCurrent, termsFlow } from '../terms.js';
7
+ import { dot, interactive, print, printJson, say, tick } from '../ui.js';
8
+ async function read(key) {
9
+ try {
10
+ return await getTerms(key);
11
+ }
12
+ catch (e) {
13
+ if (isMissingRoute(e))
14
+ throw new Exit(EXIT.accountNotReady, `This Sekura server does not show the Terms in the terminal yet. Read and accept them at ${link('/app')}.`);
15
+ if (isToolError(e, 'cli_sign_in_required') || (isToolError(e) && e.status === 403))
16
+ throw new Exit(EXIT.notSignedIn, 'This key cannot accept the Terms. Run npx sekura@latest login to sign in with GitHub, then try again.');
17
+ throw e;
18
+ }
19
+ }
20
+ export async function runTerms(opts = {}) {
21
+ const key = requireKey();
22
+ const terms = await read(key);
23
+ if (opts.json && !opts.accept) {
24
+ printJson(opts.full ? terms : { ...terms, documents: (terms.documents ?? []).map(({ text: _text, ...d }) => d) });
25
+ return EXIT.done;
26
+ }
27
+ if (opts.full && !opts.accept) {
28
+ for (const d of terms.documents ?? []) {
29
+ if (d.text) {
30
+ print(d.text);
31
+ print();
32
+ }
33
+ }
34
+ return EXIT.done;
35
+ }
36
+ if (termsCurrent(terms)) {
37
+ if (opts.json)
38
+ printJson({ state: terms.state, version: terms.version });
39
+ else {
40
+ showTerms(terms);
41
+ say(`${tick} You have accepted these Terms.`);
42
+ say();
43
+ }
44
+ return EXIT.done;
45
+ }
46
+ const named = opts.accept;
47
+ if (named && (!opts.termsVersion || !opts.textHash)) {
48
+ throw new Exit(EXIT.agreementRequired, `--accept needs the version and text hash you read: npx sekura@latest terms --accept --terms-version ${terms.version} --text-hash ${terms.textHash}`, { version: terms.version, textHash: terms.textHash });
49
+ }
50
+ if (!named && !interactive()) {
51
+ showTerms(terms);
52
+ throw new Exit(EXIT.agreementRequired, `Not accepted yet. To accept without a terminal: npx sekura@latest terms --accept --terms-version ${terms.version} --text-hash ${terms.textHash}`, { version: terms.version, textHash: terms.textHash });
53
+ }
54
+ const outcome = await termsFlow(key, {
55
+ interactive: !named && interactive(),
56
+ accept: named ? { version: opts.termsVersion, textHash: opts.textHash } : undefined,
57
+ marketing: opts.marketing,
58
+ });
59
+ if (opts.json)
60
+ printJson({ state: outcome === 'declined' ? terms.state : 'current', version: terms.version, outcome });
61
+ if (outcome === 'declined') {
62
+ say(`${dot} Not accepted. A scan cannot start before that.`);
63
+ say();
64
+ return EXIT.declined;
65
+ }
66
+ say();
67
+ return EXIT.done;
68
+ }
69
+ export const termsCommand = new Command('terms')
70
+ .description('Show the Sekura Terms and accept them here.')
71
+ .option('--json', 'print the Terms, their version and text hash as JSON on stdout')
72
+ .option('--full', 'print the full text of each document')
73
+ .option('--accept', 'accept without being asked; needs --terms-version and --text-hash from --json')
74
+ .option('--terms-version <version>', 'the version you read')
75
+ .option('--text-hash <hash>', 'the text hash you read')
76
+ .option('--marketing', 'also agree to product emails')
77
+ .option('--no-marketing', 'do not agree to product emails')
78
+ .action(async (opts) => { process.exitCode = await runTerms(opts); });
@@ -1,24 +1,33 @@
1
1
  // `sekura uninstall`: take the sekura entry out of every tool it was written
2
2
  // to, and the skill and guidance with it unless asked to keep them. Nothing
3
- // else in any file is touched. Sign-ins the tool keeps in its own store (a
4
- // keychain entry, a token) are the tool's to forget; the connection can also
5
- // be revoked on sekura.ai under Settings → Agents and API keys.
3
+ // else in any file is touched. The key the CLI saved is revoked on the
4
+ // server that made it before the copy is forgotten: until 0.4.2 it was only
5
+ // deleted here, and stayed live on Sekura with nobody holding it. Sign-ins
6
+ // a tool keeps in its own store (Codex, Devin) are keys the CLI never sees;
7
+ // the person is pointed at Settings → Agents and API keys for those.
6
8
  import { Command } from 'commander';
7
9
  import { confirm } from '@inquirer/prompts';
8
- import { buildPlan, describeStep, detectTools, removeStep } from '../plan.js';
9
- import { credentialsPath, forgetKey } from '../auth.js';
10
+ import { buildPlan, detectTools, removalLabel, removeStep } from '../plan.js';
11
+ import { credentialsPath, forgetAllKeys, hostOf, keyName, revokeKey, savedKeys } from '../auth.js';
12
+ import { KEYS_PAGE, serverNote } from '../catalogue.js';
10
13
  import { cross, dot, say, tick } from '../ui.js';
14
+ /** The Settings page on the server a key belongs to. */
15
+ const keysPageOf = (endpoint) => `${new URL(endpoint).origin}/app/settings → Agents and API keys`;
11
16
  export async function runUninstall(opts) {
12
17
  const cwd = opts.cwd ?? process.cwd();
13
18
  const scope = opts.scope ?? 'user';
14
19
  const interactive = !opts.yes && process.stdin.isTTY && process.stderr.isTTY;
15
20
  const plan = buildPlan({ tools: detectTools(cwd).map((t) => t.id), scope, skill: !opts.keepSkill, cwd });
21
+ const saved = opts.keepLogin ? [] : savedKeys();
16
22
  say();
23
+ const note = serverNote();
24
+ if (note)
25
+ say(` ${note}`);
17
26
  say(' This will remove Sekura from:');
18
27
  for (const s of plan.steps)
19
- say(`${dot} ${describeStep(s).split(':')[0]}`);
20
- if (!opts.keepLogin)
21
- say(`${dot} the saved key, ${credentialsPath()}`);
28
+ say(`${dot} ${removalLabel(s)}`);
29
+ for (const k of saved)
30
+ say(`${dot} the key saved for ${hostOf(k.endpoint)}: revoked on Sekura, then deleted from ${credentialsPath()}`);
22
31
  say(' and change nothing else.');
23
32
  say();
24
33
  if (interactive && !(await confirm({ message: 'Remove?', default: false }))) {
@@ -41,18 +50,35 @@ export async function runUninstall(opts) {
41
50
  say(`${cross} ${r.where}: ${'why' in r ? r.why : r.status}`);
42
51
  }
43
52
  }
44
- if (!opts.keepLogin && forgetKey())
53
+ // Revoked before the copy is deleted: once deleted, nothing here could
54
+ // revoke it. A server that cannot revoke from here is not a failure of
55
+ // the uninstall; the person is told which key to revoke, and where.
56
+ for (const k of saved) {
57
+ const r = await revokeKey(k.key, k.endpoint);
58
+ if (r === 'revoked')
59
+ say(`${tick} Revoked the saved key on ${hostOf(k.endpoint)}`);
60
+ else
61
+ say(`${dot} ${hostOf(k.endpoint)} did not revoke the saved key from here. Revoke "${keyName()}" at ${keysPageOf(k.endpoint)}.`);
62
+ }
63
+ if (saved.length && forgetAllKeys())
45
64
  say(`${tick} ${credentialsPath()}`);
65
+ if (!opts.keepLogin && process.env.SEKURA_API_KEY?.trim())
66
+ say(`${dot} SEKURA_API_KEY is set. That key is yours, so it was not revoked.`);
46
67
  say();
47
- say(' To end the connection on Sekura\'s side too: https://sekura.ai/app/settings → Agents and API keys.');
68
+ const ownLogins = plan.steps.flatMap((s) => (s.kind === 'tool' && s.tool.login ? [s.tool.name] : []));
69
+ say(` To end the connection on Sekura's side too: ${KEYS_PAGE}.`);
70
+ if (ownLogins.length) {
71
+ const many = ownLogins.length > 1;
72
+ say(` ${ownLogins.join(' and ')} ${many ? 'sign' : 'signs'} in to Sekura with ${many ? 'keys of their own' : 'a key of its own'}. Revoke ${many ? 'those' : 'it'} there too.`);
73
+ }
48
74
  say();
49
75
  return failed;
50
76
  }
51
77
  export const uninstallCommand = new Command('uninstall')
52
- .description('Remove Sekura from every tool on this machine, and the skill.')
78
+ .description('Remove Sekura from every tool on this machine, and the skill; revoke the key it saved.')
53
79
  .option('-y, --yes', 'remove without asking')
54
80
  .option('--keep-skill', 'leave the skill and the guidance block in place')
55
- .option('--keep-login', 'leave the saved Sekura key in place')
81
+ .option('--keep-login', 'leave the saved Sekura key in place, and do not revoke it')
56
82
  .option('--scope <scope>', 'user or project', 'user')
57
83
  .action(async (opts) => {
58
84
  process.exitCode = (await runUninstall(opts)) ? 1 : 0;
package/dist/device.js CHANGED
@@ -10,7 +10,7 @@
10
10
  // sees one "Sekura CLI" client whichever way they signed in. The
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
- import { ENDPOINT } from './catalogue.js';
13
+ import { ENDPOINT, HOST } from './catalogue.js';
14
14
  export const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
15
15
  const ISSUER = new URL(ENDPOINT).origin;
16
16
  /** The variables that say this terminal is not on the machine with the
@@ -31,9 +31,9 @@ export async function startDeviceAuthorization(clientId) {
31
31
  const r = await fetch(`${ISSUER}/oauth/device_authorization`, form({ client_id: clientId, scope: 'read write', resource: ENDPOINT }));
32
32
  const data = (await r.json().catch(() => ({})));
33
33
  if (!r.ok)
34
- throw new Error(`sekura.ai refused the sign-in (/oauth/device_authorization): ${data.error_description || data.error || r.status}`);
34
+ throw new Error(`${HOST} refused the sign-in (/oauth/device_authorization): ${data.error_description || data.error || r.status}`);
35
35
  if (typeof data.device_code !== 'string' || typeof data.user_code !== 'string' || typeof data.verification_uri !== 'string') {
36
- throw new Error('sekura.ai answered the device sign-in without a code');
36
+ throw new Error(`${HOST} answered the device sign-in without a code`);
37
37
  }
38
38
  return data;
39
39
  }
@@ -64,7 +64,7 @@ export async function pollDeviceToken(clientId, code, opts = {}) {
64
64
  if (r.ok) {
65
65
  const key = String(data.access_token ?? '');
66
66
  if (!key)
67
- throw new Error('sekura.ai answered without a key');
67
+ throw new Error(`${HOST} answered without a key`);
68
68
  return key;
69
69
  }
70
70
  if (r.status >= 500)
@@ -74,9 +74,9 @@ export async function pollDeviceToken(clientId, code, opts = {}) {
74
74
  case 'slow_down':
75
75
  interval += 5000;
76
76
  continue;
77
- case 'access_denied': throw new Error('the sign-in was declined on sekura.ai');
77
+ case 'access_denied': throw new Error(`the sign-in was declined on ${HOST}`);
78
78
  case 'expired_token': throw new Error('the code expired before it was approved; run the command again for a new one');
79
- default: throw new Error(`sekura.ai refused the sign-in (/oauth/token): ${data.error_description || data.error || r.status}`);
79
+ default: throw new Error(`${HOST} refused the sign-in (/oauth/token): ${data.error_description || data.error || r.status}`);
80
80
  }
81
81
  }
82
82
  }
package/dist/errors.js ADDED
@@ -0,0 +1,17 @@
1
+ import { HOST, SUPPORT } from './catalogue.js';
2
+ export const unreachable = () => `${HOST} could not be reached. Check your internet connection and try again.`;
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 async function reach(url, init) {
5
+ try {
6
+ return await fetch(url, init);
7
+ }
8
+ catch {
9
+ throw new Error(unreachable());
10
+ }
11
+ }
12
+ export function refusal(data, status) {
13
+ if (status >= 500)
14
+ return serverTrouble(status);
15
+ const why = typeof data.error_description === 'string' ? data.error_description : typeof data.error === 'string' ? data.error : `HTTP ${status}`;
16
+ return `${HOST} refused the sign-in: ${why}. Run the command again; if it keeps happening, write to ${SUPPORT}.`;
17
+ }
package/dist/exit.js ADDED
@@ -0,0 +1,46 @@
1
+ import { SignedOut, ToolError } from './api.js';
2
+ export const EXIT = {
3
+ done: 0,
4
+ error: 1,
5
+ stoppedWaiting: 2,
6
+ declined: 3,
7
+ notSignedIn: 4,
8
+ accountNotReady: 5,
9
+ agreementRequired: 6,
10
+ paymentNeedsBrowser: 7,
11
+ };
12
+ export class Exit extends Error {
13
+ code;
14
+ data;
15
+ constructor(code, message = '', data) {
16
+ super(message);
17
+ this.name = 'Exit';
18
+ this.code = code;
19
+ this.data = data;
20
+ }
21
+ }
22
+ export const SIGN_IN_HINT = 'run npx sekura@latest login';
23
+ const NOT_READY = new Set(['account_not_ready', 'consent_required', 'signature_required', 'no_repositories', 'not_granted', 'github_sign_in_expired', 'email_not_verified']);
24
+ export function exitCodeFor(e) {
25
+ if (e instanceof Exit)
26
+ return e.code;
27
+ if (e instanceof SignedOut)
28
+ return EXIT.notSignedIn;
29
+ if (e instanceof ToolError) {
30
+ if (e.code === 'invalid_token' || e.status === 401)
31
+ return EXIT.notSignedIn;
32
+ if (NOT_READY.has(e.code))
33
+ return EXIT.accountNotReady;
34
+ if (e.code === 'payment_required')
35
+ return EXIT.paymentNeedsBrowser;
36
+ }
37
+ return EXIT.error;
38
+ }
39
+ export function messageFor(e) {
40
+ if (e instanceof SignedOut)
41
+ return `Your Sekura key no longer works (${e.message}); ${SIGN_IN_HINT}.`;
42
+ if (e instanceof ToolError)
43
+ return e.link ? `${e.message} ${e.link}` : e.message;
44
+ return e instanceof Error ? e.message : String(e);
45
+ }
46
+ export const toExit = (e) => e instanceof Exit ? e : new Exit(exitCodeFor(e), messageFor(e), e instanceof ToolError ? { code: e.code, ...e.data } : undefined);