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.
- package/README.md +8 -5
- package/dist/auth.js +137 -19
- package/dist/catalogue.js +53 -9
- package/dist/commands/billing.js +25 -3
- package/dist/commands/doctor.js +37 -0
- package/dist/commands/findings.js +38 -0
- package/dist/commands/init.js +20 -9
- package/dist/commands/login.js +2 -2
- package/dist/commands/pay.js +5 -2
- package/dist/commands/plans.js +263 -0
- package/dist/commands/report.js +33 -0
- package/dist/commands/repos.js +55 -0
- package/dist/commands/scan.js +100 -0
- package/dist/commands/scans.js +32 -0
- package/dist/commands/shared.js +236 -0
- package/dist/commands/status.js +14 -2
- package/dist/commands/terms.js +78 -0
- package/dist/commands/uninstall.js +38 -12
- package/dist/device.js +6 -6
- package/dist/errors.js +17 -0
- package/dist/exit.js +46 -0
- package/dist/flow.js +218 -0
- package/dist/guide.js +26 -11
- package/dist/open.js +68 -0
- package/dist/origin.js +66 -0
- package/dist/payment.js +32 -0
- package/dist/plan.js +15 -0
- package/dist/session.js +182 -0
- package/dist/state.js +72 -0
- package/dist/steps.js +330 -0
- package/dist/terms.js +81 -0
- package/dist/verify.js +5 -1
- package/dist/writers.js +76 -10
- package/package.json +2 -2
- package/skills/sekura/SKILL.md +33 -21
package/dist/session.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { ISSUER, adoptSavedKey, credentialsPath, forgetKey, keyName, readKey, readSavedKey, readToolKey, redact, revokeKey, saveKey, saveToolKey, savedCredentials, } from './auth.js';
|
|
2
|
+
import { cliApi, getAccount, isMissingRoute, isToolError, SignedOut } from './api.js';
|
|
3
|
+
import { ENDPOINT, HOST } from './catalogue.js';
|
|
4
|
+
import { DEVICE_GRANT, TokenRouteMissing, form, pollForToken } from './device.js';
|
|
5
|
+
import { reach, refusal } from './errors.js';
|
|
6
|
+
import { signInHere as legacySignInHere } from './guide.js';
|
|
7
|
+
import { copyToClipboard, openLink } from './open.js';
|
|
8
|
+
import { cross, dot, say, spinner, tick } from './ui.js';
|
|
9
|
+
export const GITHUB_DEVICE_PAGE = 'https://github.com/login/device';
|
|
10
|
+
export class LegacyServer extends Error {
|
|
11
|
+
constructor() { super(`${HOST} does not offer the GitHub code sign-in yet`); this.name = 'LegacyServer'; }
|
|
12
|
+
}
|
|
13
|
+
export async function startGithubSignIn() {
|
|
14
|
+
const r = await reach(`${ISSUER}/oauth/github/device`, form({ client_name: keyName(), resource: ENDPOINT }));
|
|
15
|
+
if (r.status === 404)
|
|
16
|
+
throw new LegacyServer();
|
|
17
|
+
const data = (await r.json().catch(() => ({})));
|
|
18
|
+
if (!r.ok)
|
|
19
|
+
throw new Error(refusal(data, r.status));
|
|
20
|
+
if (typeof data.device_code !== 'string' || typeof data.user_code !== 'string')
|
|
21
|
+
throw new Error(`${HOST} answered the sign-in without a code`);
|
|
22
|
+
return {
|
|
23
|
+
device_code: data.device_code,
|
|
24
|
+
user_code: data.user_code,
|
|
25
|
+
verification_uri: typeof data.verification_uri === 'string' && data.verification_uri.startsWith('https://github.com/') ? data.verification_uri : GITHUB_DEVICE_PAGE,
|
|
26
|
+
expires_in: Number(data.expires_in) > 0 ? Number(data.expires_in) : 900,
|
|
27
|
+
interval: Number(data.interval) > 0 ? Number(data.interval) : undefined,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export async function pollGithubSignIn(code, opts = {}) {
|
|
31
|
+
let data;
|
|
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' });
|
|
34
|
+
}
|
|
35
|
+
catch (e) {
|
|
36
|
+
if (e instanceof TokenRouteMissing)
|
|
37
|
+
throw new LegacyServer();
|
|
38
|
+
throw e;
|
|
39
|
+
}
|
|
40
|
+
const account = data.account && typeof data.account === 'object' ? data.account : null;
|
|
41
|
+
return { key: String(data.access_token), scope: typeof data.scope === 'string' ? data.scope : '', account };
|
|
42
|
+
}
|
|
43
|
+
export async function signInWithGithub(opts = {}) {
|
|
44
|
+
const code = await startGithubSignIn();
|
|
45
|
+
const copied = copyToClipboard(code.user_code);
|
|
46
|
+
const opened = openLink(code.verification_uri, { browser: opts.browser });
|
|
47
|
+
opts.onCode?.({ userCode: code.user_code, uri: code.verification_uri, expiresIn: code.expires_in, copied, opened });
|
|
48
|
+
return pollGithubSignIn(code, opts);
|
|
49
|
+
}
|
|
50
|
+
const who = (account, key) => account?.email ?? account?.name ?? redact(key);
|
|
51
|
+
export async function currentSession(opts = {}) {
|
|
52
|
+
const tell = opts.quiet ? () => { } : say;
|
|
53
|
+
const fromEnv = !!process.env.SEKURA_API_KEY?.trim();
|
|
54
|
+
const existing = readKey();
|
|
55
|
+
if (!existing)
|
|
56
|
+
return null;
|
|
57
|
+
const kind = fromEnv ? 'env' : savedCredentials()?.kind ?? 'legacy';
|
|
58
|
+
try {
|
|
59
|
+
const account = await getAccount(existing);
|
|
60
|
+
if (!fromEnv)
|
|
61
|
+
adoptSavedKey();
|
|
62
|
+
tell(`${tick} Signed in to Sekura as ${who(account, existing)}${fromEnv ? ' (SEKURA_API_KEY)' : ''}`);
|
|
63
|
+
return { key: existing, account, kind, fresh: false };
|
|
64
|
+
}
|
|
65
|
+
catch (e) {
|
|
66
|
+
if (!(e instanceof SignedOut)) {
|
|
67
|
+
tell(`${dot} Using ${fromEnv ? 'the key in SEKURA_API_KEY' : `your saved Sekura key (${credentialsPath()})`}, ${redact(existing)}; Sekura could not confirm it: ${e.message}`);
|
|
68
|
+
return { key: existing, account: null, kind, fresh: false };
|
|
69
|
+
}
|
|
70
|
+
if (fromEnv) {
|
|
71
|
+
tell(`${cross} SEKURA_API_KEY is not a valid Sekura key (${e.message}); it was not used.`);
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
forgetKey();
|
|
75
|
+
tell(`${dot} Your saved Sekura key no longer works (${e.message}); sign in again.`);
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async function legacySession(flags) {
|
|
80
|
+
const s = await legacySignInHere({ device: flags.device || flags.browser === false });
|
|
81
|
+
if (!s)
|
|
82
|
+
return null;
|
|
83
|
+
saveKey(s.key, s.account?.email, 'legacy');
|
|
84
|
+
return { key: s.key, account: s.account, kind: 'legacy', fresh: true };
|
|
85
|
+
}
|
|
86
|
+
export async function signInFresh(flags = {}) {
|
|
87
|
+
if (flags.legacy)
|
|
88
|
+
return legacySession(flags);
|
|
89
|
+
say();
|
|
90
|
+
let stop = () => { };
|
|
91
|
+
try {
|
|
92
|
+
const signed = await signInWithGithub({
|
|
93
|
+
browser: flags.browser,
|
|
94
|
+
onCode: (c) => {
|
|
95
|
+
say(' Sign in to Sekura with GitHub. Your code:');
|
|
96
|
+
say();
|
|
97
|
+
say(` ${c.userCode}${c.copied ? ' (copied to your clipboard)' : ''}`);
|
|
98
|
+
say();
|
|
99
|
+
say(c.opened.opened
|
|
100
|
+
? ` Opening ${c.uri} in your browser. Enter the code there and approve.`
|
|
101
|
+
: ` On any device, open ${c.uri}, enter the code and approve.`);
|
|
102
|
+
say();
|
|
103
|
+
const minutes = Math.max(1, Math.round(c.expiresIn / 60));
|
|
104
|
+
stop = spinner(`Waiting for you to approve on github.com… the code expires in ${minutes} min; Ctrl-C to stop`);
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
stop();
|
|
108
|
+
let account = null;
|
|
109
|
+
try {
|
|
110
|
+
account = await getAccount(signed.key);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
account = null;
|
|
114
|
+
}
|
|
115
|
+
const where = saveKey(signed.key, account?.email ?? signed.account?.email, 'cli');
|
|
116
|
+
say(`${tick} Signed in to Sekura as ${who(account ?? signed.account, signed.key)}${signed.account?.created ? ' (new Sekura account)' : ''}; the key (${redact(signed.key)}) is kept in ${where}`);
|
|
117
|
+
return { key: signed.key, account, kind: 'cli', fresh: true };
|
|
118
|
+
}
|
|
119
|
+
catch (e) {
|
|
120
|
+
stop();
|
|
121
|
+
if (e instanceof LegacyServer)
|
|
122
|
+
return legacySession(flags);
|
|
123
|
+
say(`${cross} ${e.message}`);
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
export async function obtainSession(opts) {
|
|
128
|
+
const s = await currentSession({ quiet: opts.quiet });
|
|
129
|
+
if (s || !opts.interactive)
|
|
130
|
+
return s;
|
|
131
|
+
return signInFresh(opts);
|
|
132
|
+
}
|
|
133
|
+
const mintedKeyOf = (data) => {
|
|
134
|
+
for (const field of ['key', 'access_token', 'token', 'apiKey']) {
|
|
135
|
+
const v = data[field];
|
|
136
|
+
if (typeof v === 'string' && v)
|
|
137
|
+
return v;
|
|
138
|
+
}
|
|
139
|
+
return '';
|
|
140
|
+
};
|
|
141
|
+
export const toolKeyName = () => `${keyName()} tools`;
|
|
142
|
+
export async function toolKeyFor(session) {
|
|
143
|
+
if (session.kind !== 'cli')
|
|
144
|
+
return { key: session.key, separate: false, minted: false };
|
|
145
|
+
const saved = readSavedKey() === session.key ? readToolKey() : null;
|
|
146
|
+
if (saved) {
|
|
147
|
+
try {
|
|
148
|
+
await getAccount(saved);
|
|
149
|
+
return { key: saved, separate: true, minted: false };
|
|
150
|
+
}
|
|
151
|
+
catch (e) {
|
|
152
|
+
if (!(e instanceof SignedOut))
|
|
153
|
+
return { key: saved, separate: true, minted: false };
|
|
154
|
+
saveToolKey(null);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
const made = mintedKeyOf(await cliApi(session.key, 'POST', '/keys', { name: toolKeyName() }));
|
|
159
|
+
if (!made)
|
|
160
|
+
throw new Error(`${HOST} answered without a key for your tools`);
|
|
161
|
+
saveToolKey(made);
|
|
162
|
+
return { key: made, separate: true, minted: true };
|
|
163
|
+
}
|
|
164
|
+
catch (e) {
|
|
165
|
+
if (isMissingRoute(e) || (isToolError(e) && e.status === 403))
|
|
166
|
+
return { key: session.key, separate: false, minted: false };
|
|
167
|
+
throw e;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
export async function revokeSessionKey(key, endpoint = ENDPOINT, kind) {
|
|
171
|
+
if (kind !== 'legacy' && endpoint === ENDPOINT) {
|
|
172
|
+
try {
|
|
173
|
+
await cliApi(key, 'POST', '/logout');
|
|
174
|
+
return 'revoked';
|
|
175
|
+
}
|
|
176
|
+
catch (e) {
|
|
177
|
+
if (e instanceof SignedOut)
|
|
178
|
+
return 'revoked';
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return revokeKey(key, endpoint);
|
|
182
|
+
}
|
package/dist/state.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { ENDPOINT, credentialsPath } from './catalogue.js';
|
|
4
|
+
import { writeConfig } from './writers.js';
|
|
5
|
+
export const QUOTE_TTL_MS = 15 * 60_000;
|
|
6
|
+
export const statePath = () => join(dirname(credentialsPath()), 'state.json');
|
|
7
|
+
function readFile() {
|
|
8
|
+
try {
|
|
9
|
+
const raw = JSON.parse(readFileSync(statePath(), 'utf8'));
|
|
10
|
+
const servers = raw?.servers && typeof raw.servers === 'object' && !Array.isArray(raw.servers) ? raw.servers : {};
|
|
11
|
+
return { servers };
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return { servers: {} };
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function writeFile(s) {
|
|
18
|
+
const p = statePath();
|
|
19
|
+
mkdirSync(dirname(p), { recursive: true, mode: 0o700 });
|
|
20
|
+
try {
|
|
21
|
+
chmodSync(dirname(p), 0o700);
|
|
22
|
+
}
|
|
23
|
+
catch { }
|
|
24
|
+
writeConfig(p, JSON.stringify(s, null, 2) + '\n', true);
|
|
25
|
+
}
|
|
26
|
+
const live = (quotes, now) => Object.fromEntries(Object.entries(quotes ?? {}).filter(([, q]) => q && Date.parse(q.expiresAt) > now));
|
|
27
|
+
export function readState(endpoint = ENDPOINT) {
|
|
28
|
+
const s = readFile().servers[endpoint];
|
|
29
|
+
return s && typeof s === 'object' ? s : {};
|
|
30
|
+
}
|
|
31
|
+
export function updateState(change, endpoint = ENDPOINT) {
|
|
32
|
+
const file = readFile();
|
|
33
|
+
const current = file.servers[endpoint] && typeof file.servers[endpoint] === 'object' ? { ...file.servers[endpoint] } : {};
|
|
34
|
+
const next = change(current) ?? current;
|
|
35
|
+
next.quotes = live(next.quotes, Date.now());
|
|
36
|
+
if (!Object.keys(next.quotes).length)
|
|
37
|
+
delete next.quotes;
|
|
38
|
+
if (Object.keys(next).length)
|
|
39
|
+
file.servers[endpoint] = next;
|
|
40
|
+
else
|
|
41
|
+
delete file.servers[endpoint];
|
|
42
|
+
writeFile(file);
|
|
43
|
+
return next;
|
|
44
|
+
}
|
|
45
|
+
export const defaultRepository = (endpoint = ENDPOINT) => {
|
|
46
|
+
const r = readState(endpoint).repository;
|
|
47
|
+
return typeof r === 'string' && r ? r : null;
|
|
48
|
+
};
|
|
49
|
+
export function setDefaultRepository(repository, endpoint = ENDPOINT) {
|
|
50
|
+
updateState((s) => { if (repository)
|
|
51
|
+
s.repository = repository;
|
|
52
|
+
else
|
|
53
|
+
delete s.repository; }, endpoint);
|
|
54
|
+
}
|
|
55
|
+
export function saveQuote(q, endpoint = ENDPOINT) {
|
|
56
|
+
const now = Date.now();
|
|
57
|
+
const saved = { ...q, savedAt: new Date(now).toISOString(), expiresAt: q.expiresAt ?? new Date(now + QUOTE_TTL_MS).toISOString() };
|
|
58
|
+
updateState((s) => { s.quotes = { ...(s.quotes ?? {}), [saved.quoteId]: saved }; }, endpoint);
|
|
59
|
+
return saved;
|
|
60
|
+
}
|
|
61
|
+
export function findQuote(quoteId, endpoint = ENDPOINT) {
|
|
62
|
+
const q = readState(endpoint).quotes?.[quoteId];
|
|
63
|
+
if (!q)
|
|
64
|
+
return { status: 'unknown' };
|
|
65
|
+
return Date.parse(q.expiresAt) > Date.now() ? { status: 'found', quote: q } : { status: 'expired', quote: q };
|
|
66
|
+
}
|
|
67
|
+
export function dropQuote(quoteId, endpoint = ENDPOINT) {
|
|
68
|
+
if (!readState(endpoint).quotes?.[quoteId])
|
|
69
|
+
return;
|
|
70
|
+
updateState((s) => { if (s.quotes)
|
|
71
|
+
delete s.quotes[quoteId]; }, endpoint);
|
|
72
|
+
}
|
package/dist/steps.js
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { confirm, select } from '@inquirer/prompts';
|
|
2
|
+
import { readKey, readToolKey, redact } from './auth.js';
|
|
3
|
+
import { getAccount, getBilling, getPlans, isMissingRoute, isToolError, listRepositories, SignedOut } from './api.js';
|
|
4
|
+
import { ENDPOINT, HOST, carriesKey, link } from './catalogue.js';
|
|
5
|
+
import { EXIT, Exit, SIGN_IN_HINT } from './exit.js';
|
|
6
|
+
import { openLink } from './open.js';
|
|
7
|
+
import { cardLines, planLines } from './payment.js';
|
|
8
|
+
import { buildPlan, detectTools, stepPresent } from './plan.js';
|
|
9
|
+
import { currentGithubRepo } from './repo.js';
|
|
10
|
+
import { obtainSession } from './session.js';
|
|
11
|
+
import { defaultRepository, setDefaultRepository } from './state.js';
|
|
12
|
+
import { termsFlow } from './terms.js';
|
|
13
|
+
import { cross, dot, say, tick, waitFor } from './ui.js';
|
|
14
|
+
const isInteractive = (f) => f.interactive ?? (!f.yes && !f.json && !!process.stdin.isTTY && !!process.stderr.isTTY);
|
|
15
|
+
const same = (a, b) => a.toLowerCase() === b.toLowerCase();
|
|
16
|
+
export function localConnections(opts = {}) {
|
|
17
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
18
|
+
const scope = opts.scope ?? 'user';
|
|
19
|
+
const detected = detectTools(cwd);
|
|
20
|
+
const key = opts.key === undefined ? readToolKey() ?? readKey() : opts.key;
|
|
21
|
+
const ids = detected.map((t) => t.id);
|
|
22
|
+
const plan = buildPlan({ tools: ids, scope, skill: true, cwd, key });
|
|
23
|
+
const plain = key ? buildPlan({ tools: ids, scope, skill: true, cwd }) : plan;
|
|
24
|
+
const rows = [];
|
|
25
|
+
const connected = [];
|
|
26
|
+
plan.steps.forEach((s, i) => {
|
|
27
|
+
let p = stepPresent(s);
|
|
28
|
+
// An entry without the key is still connected; its tool signs in itself.
|
|
29
|
+
let how = s.kind === 'tool' && p === true && carriesKey(s.target) ? ' (with your key)' : '';
|
|
30
|
+
if (s.kind === 'tool' && p !== true && plain !== plan && stepPresent(plain.steps[i]) === true) {
|
|
31
|
+
p = true;
|
|
32
|
+
how = ' (signs in in the tool)';
|
|
33
|
+
}
|
|
34
|
+
const noun = s.kind === 'tool' ? 'connected' : 'installed';
|
|
35
|
+
// A command target is 'unknown' only when the tool has no list to ask,
|
|
36
|
+
// or its binary did not answer; a link means its binary is not here.
|
|
37
|
+
const unknown = s.kind !== 'tool' ? '' : s.target.kind === 'command' ? 'kept by the tool itself; ask it'
|
|
38
|
+
: s.target.kind === 'link' ? 'cannot be checked here, because its command is not on PATH' : 'its file has comments; look by hand';
|
|
39
|
+
const word = p === true ? noun + how : p === 'unknown' ? unknown : `not ${noun}`;
|
|
40
|
+
const label = s.kind === 'tool' ? s.tool.name : s.kind === 'skill' ? `skill ${s.path}` : `guidance ${s.path}`;
|
|
41
|
+
if (s.kind === 'tool' && p === true)
|
|
42
|
+
connected.push(s.tool.name);
|
|
43
|
+
rows.push({ kind: s.kind, label, state: p, word });
|
|
44
|
+
});
|
|
45
|
+
return { detected: detected.length, rows, skipped: plan.skipped.map((s) => ({ name: s.tool.name, why: s.why })), connected };
|
|
46
|
+
}
|
|
47
|
+
const settled = async (p) => {
|
|
48
|
+
try {
|
|
49
|
+
return { ok: true, value: await p };
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
return { ok: false, error };
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
const why = (e) => (e instanceof Error ? e.message : String(e));
|
|
56
|
+
export async function readiness(key, opts = {}) {
|
|
57
|
+
const tools = localConnections({ cwd: opts.cwd, scope: opts.scope });
|
|
58
|
+
const toolsCheck = {
|
|
59
|
+
id: 'tools', label: 'Coding tools', required: false,
|
|
60
|
+
state: tools.connected.length ? 'ready' : tools.detected ? 'todo' : 'info',
|
|
61
|
+
detail: tools.connected.length ? `connected: ${tools.connected.join(', ')}` : tools.detected ? 'none of the tools on this machine is connected' : 'no supported coding tool found on this machine',
|
|
62
|
+
...(tools.connected.length ? {} : { fix: tools.detected ? 'npx sekura@latest init' : 'npx sekura@latest init --tools <tool>' }),
|
|
63
|
+
};
|
|
64
|
+
const base = { server: ENDPOINT, repositories: [], defaultRepository: defaultRepository(), plans: [], billing: null, tools };
|
|
65
|
+
if (!key) {
|
|
66
|
+
return {
|
|
67
|
+
...base, signedIn: false, ready: false, account: null,
|
|
68
|
+
checks: [{ id: 'signIn', label: 'Signed in', state: 'todo', detail: 'not signed in here', fix: 'npx sekura@latest login', required: true }, toolsCheck],
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
const got = await settled(getAccount(key));
|
|
72
|
+
if (!got.ok) {
|
|
73
|
+
const out = got.error instanceof SignedOut;
|
|
74
|
+
return {
|
|
75
|
+
...base, signedIn: false, ready: false, account: null,
|
|
76
|
+
checks: [{
|
|
77
|
+
id: 'signIn', label: 'Signed in', required: true, state: out ? 'todo' : 'unknown',
|
|
78
|
+
detail: out ? `the key ${redact(key)} no longer works` : `the key ${redact(key)} could not be checked: ${why(got.error)}`,
|
|
79
|
+
fix: out ? 'npx sekura@latest login' : undefined,
|
|
80
|
+
}, toolsCheck],
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
const account = got.value;
|
|
84
|
+
const [repos, plans, billing] = await Promise.all([settled(listRepositories(key)), settled(getPlans(key)), settled(getBilling(key))]);
|
|
85
|
+
const checks = [{ id: 'signIn', label: 'Signed in', state: 'ready', detail: `as ${account.email ?? account.name ?? redact(key)}`, required: true }];
|
|
86
|
+
const outdated = account.termsUpdated === true;
|
|
87
|
+
checks.push(account.termsAccepted === false || outdated
|
|
88
|
+
? { id: 'terms', label: 'Terms', state: 'todo', detail: outdated ? 'the Terms changed since you accepted them' : 'not accepted yet', fix: 'npx sekura@latest terms', required: true }
|
|
89
|
+
: { id: 'terms', label: 'Terms', state: account.termsAccepted === true ? 'ready' : 'unknown', detail: account.termsAccepted === true ? 'accepted' : 'Sekura did not say', required: true });
|
|
90
|
+
checks.push(account.emailVerified === false
|
|
91
|
+
? { id: 'email', label: 'Email', state: 'todo', detail: 'not verified; reports are only sent to a verified address', fix: `verify it at ${account.links?.dashboard ?? link('/app')}`, required: true }
|
|
92
|
+
: { id: 'email', label: 'Email', state: account.emailVerified === true ? 'ready' : 'unknown', detail: account.emailVerified === true ? 'verified' : 'Sekura did not say', required: true });
|
|
93
|
+
let names = [];
|
|
94
|
+
if (repos.ok) {
|
|
95
|
+
const installs = repos.value.installations ?? [];
|
|
96
|
+
names = installs.flatMap((i) => i.repositories).filter((r) => !r.empty).map((r) => r.fullName);
|
|
97
|
+
const accounts = installs.map((i) => i.account).filter((a) => !!a);
|
|
98
|
+
const broken = installs.filter((i) => i.error && i.error !== 'partial').map((i) => `${i.account}: ${i.error}`);
|
|
99
|
+
checks.push(installs.length
|
|
100
|
+
? { id: 'app', label: 'GitHub App', state: broken.length ? 'todo' : 'ready', detail: broken.length ? broken.join('; ') : `installed on ${accounts.join(', ') || `${installs.length} account${installs.length > 1 ? 's' : ''}`}`, ...(broken.length ? { fix: 'npx sekura@latest repos --add' } : {}), required: true }
|
|
101
|
+
: { id: 'app', label: 'GitHub App', state: 'todo', detail: 'not installed on any GitHub account', fix: 'npx sekura@latest repos --add', required: true });
|
|
102
|
+
checks.push(names.length
|
|
103
|
+
? { id: 'repositories', label: 'Repositories', state: 'ready', detail: `${names.length} Sekura can scan${base.defaultRepository ? `; default ${base.defaultRepository}` : ''}`, required: true }
|
|
104
|
+
: { id: 'repositories', label: 'Repositories', state: 'todo', detail: 'none Sekura can scan yet', fix: 'npx sekura@latest repos --add', required: true });
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
checks.push({ id: 'app', label: 'GitHub App', state: 'unknown', detail: why(repos.error), required: true });
|
|
108
|
+
checks.push({ id: 'repositories', label: 'Repositories', state: 'unknown', detail: 'could not be listed', required: true });
|
|
109
|
+
}
|
|
110
|
+
const active = plans.ok ? planLines(plans.value.plans ?? []) : [];
|
|
111
|
+
checks.push(plans.ok
|
|
112
|
+
? { id: 'plans', label: 'Plans', state: 'info', detail: active.length ? active.join('; ') : 'none active', required: false }
|
|
113
|
+
: { id: 'plans', label: 'Plans', state: 'unknown', detail: why(plans.error), required: false });
|
|
114
|
+
const cards = billing.ok ? cardLines(billing.value) : [];
|
|
115
|
+
checks.push(billing.ok
|
|
116
|
+
? { id: 'cards', label: 'Cards', state: 'info', detail: cards.length ? cards.join('; ') : 'none saved; a paid scan opens Stripe Checkout', required: false }
|
|
117
|
+
: { id: 'cards', label: 'Cards', state: 'unknown', detail: why(billing.error), required: false });
|
|
118
|
+
checks.push(toolsCheck);
|
|
119
|
+
return {
|
|
120
|
+
...base, signedIn: true, account, repositories: names,
|
|
121
|
+
plans: plans.ok ? plans.value.plans ?? [] : [], billing: billing.ok ? billing.value : null,
|
|
122
|
+
ready: checks.every((c) => !c.required || c.state === 'ready'),
|
|
123
|
+
checks,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
export const checkMark = (c) => (c.state === 'ready' ? tick : c.state === 'todo' ? cross : dot);
|
|
127
|
+
export function sayChecks(r, opts = {}) {
|
|
128
|
+
for (const c of r.checks) {
|
|
129
|
+
if (opts.skip?.includes(c.id))
|
|
130
|
+
continue;
|
|
131
|
+
say(`${checkMark(c)} ${c.label}: ${c.detail}`);
|
|
132
|
+
if (opts.fixes && c.fix && c.state !== 'ready')
|
|
133
|
+
say(` ${c.fix.startsWith('npx ') ? `run ${c.fix}` : c.fix}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
export const readinessJson = (r) => ({
|
|
137
|
+
server: r.server,
|
|
138
|
+
signedIn: r.signedIn,
|
|
139
|
+
ready: r.ready,
|
|
140
|
+
account: r.account ? { email: r.account.email ?? null, name: r.account.name ?? null, termsAccepted: r.account.termsAccepted ?? null, emailVerified: r.account.emailVerified ?? null, freeScanAvailable: r.account.freeScanAvailable ?? null } : null,
|
|
141
|
+
repositories: r.repositories,
|
|
142
|
+
defaultRepository: r.defaultRepository,
|
|
143
|
+
checks: r.checks,
|
|
144
|
+
tools: r.tools,
|
|
145
|
+
});
|
|
146
|
+
export async function ensureSignedIn(flags = {}) {
|
|
147
|
+
const s = await obtainSession({ interactive: isInteractive(flags), legacy: flags.legacy, device: flags.device, browser: flags.browser, quiet: flags.json });
|
|
148
|
+
if (!s) {
|
|
149
|
+
throw new Exit(EXIT.notSignedIn, isInteractive(flags)
|
|
150
|
+
? 'Not signed in; nothing was changed. Run npx sekura@latest login to try again.'
|
|
151
|
+
: `Not signed in here, and there is no terminal to sign in from: ${SIGN_IN_HINT} in a terminal, or set SEKURA_API_KEY.`);
|
|
152
|
+
}
|
|
153
|
+
return s;
|
|
154
|
+
}
|
|
155
|
+
async function refreshAccount(s) {
|
|
156
|
+
try {
|
|
157
|
+
s.account = await getAccount(s.key);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return s.account;
|
|
161
|
+
}
|
|
162
|
+
return s.account;
|
|
163
|
+
}
|
|
164
|
+
export async function ensureTerms(s, flags = {}) {
|
|
165
|
+
const interactive = isInteractive(flags);
|
|
166
|
+
const a = s.account ?? await refreshAccount(s);
|
|
167
|
+
if (a && a.termsAccepted === true && a.termsUpdated !== true)
|
|
168
|
+
return 'current';
|
|
169
|
+
try {
|
|
170
|
+
const outcome = await termsFlow(s.key, { interactive, accept: flags.accept, marketing: flags.marketing });
|
|
171
|
+
if (outcome === 'accepted')
|
|
172
|
+
await refreshAccount(s);
|
|
173
|
+
if (outcome === 'declined') {
|
|
174
|
+
if (flags.soft) {
|
|
175
|
+
say(`${dot} Terms not accepted yet. A scan cannot start before that: run npx sekura@latest terms when you are ready.`);
|
|
176
|
+
return 'declined';
|
|
177
|
+
}
|
|
178
|
+
throw new Exit(EXIT.declined, 'Terms not accepted; nothing was started. Run npx sekura@latest terms when you are ready.');
|
|
179
|
+
}
|
|
180
|
+
return outcome;
|
|
181
|
+
}
|
|
182
|
+
catch (e) {
|
|
183
|
+
if (e instanceof Exit && e.code === EXIT.agreementRequired && flags.soft) {
|
|
184
|
+
say(`${dot} ${e.message}`);
|
|
185
|
+
return 'needed';
|
|
186
|
+
}
|
|
187
|
+
if (!isMissingRoute(e) && !(isToolError(e) && e.status === 403))
|
|
188
|
+
throw e;
|
|
189
|
+
}
|
|
190
|
+
const page = a?.links?.dashboard ?? link('/app');
|
|
191
|
+
say(`${dot} Before a scan can start, accept the Terms on ${HOST}: ${page}`);
|
|
192
|
+
if (interactive && await confirm({ message: `Open ${HOST} to do that now?`, default: true })) {
|
|
193
|
+
const o = openLink(page, { browser: flags.browser });
|
|
194
|
+
if (!o.opened)
|
|
195
|
+
say(` Open ${page}`);
|
|
196
|
+
const r = await waitFor(`Waiting for the Terms on ${HOST}… press Enter to skip`, async () => {
|
|
197
|
+
const now = await getAccount(s.key);
|
|
198
|
+
s.account = now;
|
|
199
|
+
return now.termsAccepted !== false;
|
|
200
|
+
}, flags.wait);
|
|
201
|
+
if (r === 'done') {
|
|
202
|
+
say(`${tick} Terms accepted`);
|
|
203
|
+
return 'accepted';
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (flags.soft)
|
|
207
|
+
return 'needed';
|
|
208
|
+
throw new Exit(EXIT.accountNotReady, `The Terms are not accepted yet; finish at ${page}, then run the command again.`);
|
|
209
|
+
}
|
|
210
|
+
const INSTALL_WARNINGS = {
|
|
211
|
+
github_sign_in_expired: (a) => `${a}: GitHub access has expired; run npx sekura@latest login to refresh it.`,
|
|
212
|
+
installation_gone: (a) => `${a}: the Sekura GitHub App is no longer installed there.`,
|
|
213
|
+
github_unavailable: (a) => `${a}: GitHub did not answer just now; try again in a minute.`,
|
|
214
|
+
partial: (a) => `${a}: GitHub stopped answering part-way, so this list may be incomplete; try again in a minute.`,
|
|
215
|
+
};
|
|
216
|
+
export function sayInstallWarnings(list) {
|
|
217
|
+
for (const i of list.installations ?? []) {
|
|
218
|
+
const warn = i.error ? INSTALL_WARNINGS[i.error] : undefined;
|
|
219
|
+
if (warn)
|
|
220
|
+
say(`${dot} ${warn(i.account ?? 'A GitHub account')}`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
export const repositoriesOf = (list) => (list.installations ?? []).flatMap((i) => i.repositories);
|
|
224
|
+
export const installLink = (s, list) => s.account?.links?.installGithubApp ?? list?.installUrl ?? s.account?.links?.start ?? link('/app/start');
|
|
225
|
+
export async function ensureApp(s, flags = {}) {
|
|
226
|
+
const interactive = isInteractive(flags);
|
|
227
|
+
const want = flags.want ?? null;
|
|
228
|
+
if (!s.account)
|
|
229
|
+
await refreshAccount(s);
|
|
230
|
+
let list = await listRepositories(s.key, { refresh: flags.add === true });
|
|
231
|
+
if (!flags.json)
|
|
232
|
+
sayInstallWarnings(list);
|
|
233
|
+
let repos = repositoriesOf(list);
|
|
234
|
+
const covered = () => (want ? repos.some((r) => same(r.fullName, want)) : repos.length > 0);
|
|
235
|
+
const url = installLink(s, list);
|
|
236
|
+
if (covered() && !flags.add)
|
|
237
|
+
return { installed: true, found: true, repositories: repos, link: url };
|
|
238
|
+
const onGithub = /^https:\/\/github\.com\//.test(url);
|
|
239
|
+
say(repos.length
|
|
240
|
+
? want && !covered() ? `${dot} ${want} is not one Sekura can scan yet: the Sekura GitHub App needs access to it.` : `${dot} To give Sekura more repositories, change the Sekura GitHub App's access.`
|
|
241
|
+
: `${dot} The Sekura GitHub App is not installed on any of your GitHub accounts yet, so there is nothing to scan.`);
|
|
242
|
+
if (!interactive) {
|
|
243
|
+
say(` Install it and choose repositories at ${url}`);
|
|
244
|
+
if (flags.soft || covered())
|
|
245
|
+
return { installed: repos.length > 0, found: covered(), repositories: repos, link: url };
|
|
246
|
+
throw new Exit(EXIT.accountNotReady, `Sekura cannot scan ${want ?? 'any repository'} yet. Install the Sekura GitHub App at the link above, then run the command again.`, { installUrl: url });
|
|
247
|
+
}
|
|
248
|
+
if (!flags.add) {
|
|
249
|
+
const go = await select({
|
|
250
|
+
message: repos.length ? `Give Sekura access to ${want}?` : 'Install the Sekura GitHub App?',
|
|
251
|
+
choices: [
|
|
252
|
+
{ name: `Yes, open ${onGithub ? 'github.com' : HOST} (GitHub asks which repositories)`, value: true },
|
|
253
|
+
{ name: repos.length ? 'No, pick from the repositories Sekura can already scan' : 'Not now', value: false },
|
|
254
|
+
],
|
|
255
|
+
});
|
|
256
|
+
if (!go)
|
|
257
|
+
return { installed: repos.length > 0, found: false, repositories: repos, link: url };
|
|
258
|
+
}
|
|
259
|
+
const opened = openLink(url, { browser: flags.browser });
|
|
260
|
+
say(opened.opened ? ` Opened ${url}` : ` Open ${url}`);
|
|
261
|
+
const before = new Set(repos.map((r) => r.fullName.toLowerCase()));
|
|
262
|
+
const r = await waitFor('Waiting for the GitHub App install… press Enter to skip', async () => {
|
|
263
|
+
list = await listRepositories(s.key, { refresh: true });
|
|
264
|
+
repos = repositoriesOf(list);
|
|
265
|
+
if (want)
|
|
266
|
+
return repos.some((x) => same(x.fullName, want));
|
|
267
|
+
return flags.add && before.size ? repos.some((x) => !before.has(x.fullName.toLowerCase())) : repos.length > 0;
|
|
268
|
+
}, flags.wait);
|
|
269
|
+
const found = r === 'done';
|
|
270
|
+
say(found
|
|
271
|
+
? `${tick} ${want ? `Sekura can scan ${want}` : before.size ? 'Sekura can scan more repositories now' : 'The Sekura GitHub App is installed'}`
|
|
272
|
+
: `${dot} Not there yet; you can finish the install later with npx sekura@latest repos --add`);
|
|
273
|
+
return { installed: repos.length > 0, found, repositories: repos, link: url };
|
|
274
|
+
}
|
|
275
|
+
export async function ensureRepository(s, flags = {}) {
|
|
276
|
+
const interactive = isInteractive(flags);
|
|
277
|
+
const cwd = flags.cwd ?? process.cwd();
|
|
278
|
+
const here = currentGithubRepo(cwd);
|
|
279
|
+
const asked = flags.repo?.trim() || null;
|
|
280
|
+
const want = asked ?? here;
|
|
281
|
+
const keep = (name) => { if (flags.save !== false)
|
|
282
|
+
setDefaultRepository(name); return name; };
|
|
283
|
+
const app = await ensureApp(s, { ...flags, want, soft: asked ? flags.soft : true });
|
|
284
|
+
const scannable = app.repositories.filter((r) => !r.empty);
|
|
285
|
+
const find = (name) => (name ? scannable.find((r) => same(r.fullName, name)) : undefined);
|
|
286
|
+
if (asked) {
|
|
287
|
+
const hit = find(asked);
|
|
288
|
+
if (hit)
|
|
289
|
+
return keep(hit.fullName);
|
|
290
|
+
if (app.repositories.some((r) => same(r.fullName, asked)))
|
|
291
|
+
throw new Exit(EXIT.accountNotReady, `${asked} is empty, so there is nothing to scan.`);
|
|
292
|
+
if (flags.soft)
|
|
293
|
+
return null;
|
|
294
|
+
throw new Exit(EXIT.accountNotReady, `Sekura cannot scan ${asked} yet. Give the Sekura GitHub App access with npx sekura@latest repos --add.`, { installUrl: app.link });
|
|
295
|
+
}
|
|
296
|
+
if (!scannable.length) {
|
|
297
|
+
if (flags.soft)
|
|
298
|
+
return null;
|
|
299
|
+
throw new Exit(EXIT.accountNotReady, 'There is no repository Sekura can scan yet. Run npx sekura@latest repos --add.', { installUrl: app.link });
|
|
300
|
+
}
|
|
301
|
+
const hereRepo = find(here);
|
|
302
|
+
const saved = find(defaultRepository());
|
|
303
|
+
if (!interactive) {
|
|
304
|
+
const pick = hereRepo ?? saved ?? (scannable.length === 1 ? scannable[0] : undefined);
|
|
305
|
+
if (pick)
|
|
306
|
+
return keep(pick.fullName);
|
|
307
|
+
if (flags.soft)
|
|
308
|
+
return null;
|
|
309
|
+
throw new Exit(EXIT.error, `Name the repository: Sekura can scan ${scannable.length}, and this folder is not one of them. Run npx sekura@latest repos to list them.`);
|
|
310
|
+
}
|
|
311
|
+
if (scannable.length === 1) {
|
|
312
|
+
say(`${tick} Repository: ${scannable[0].fullName}`);
|
|
313
|
+
return keep(scannable[0].fullName);
|
|
314
|
+
}
|
|
315
|
+
const first = hereRepo ?? saved;
|
|
316
|
+
const ordered = first ? [first, ...app.repositories.filter((r) => r !== first)] : app.repositories;
|
|
317
|
+
const picked = await select({
|
|
318
|
+
message: 'Which repository?',
|
|
319
|
+
pageSize: 12,
|
|
320
|
+
choices: [
|
|
321
|
+
...ordered.map((r) => ({
|
|
322
|
+
name: `${r.fullName}${r === hereRepo ? ' (this folder)' : r === saved ? ' (your default)' : ''}${r.private ? ' (private)' : ''}`,
|
|
323
|
+
value: r.fullName,
|
|
324
|
+
disabled: r.empty ? '(empty, nothing to scan)' : false,
|
|
325
|
+
})),
|
|
326
|
+
{ name: 'Skip for now', value: '' },
|
|
327
|
+
],
|
|
328
|
+
});
|
|
329
|
+
return picked ? keep(picked) : null;
|
|
330
|
+
}
|
package/dist/terms.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { confirm, select } from '@inquirer/prompts';
|
|
2
|
+
import { cliApi, isToolError } from './api.js';
|
|
3
|
+
import { EXIT, Exit } from './exit.js';
|
|
4
|
+
import { dot, say, tick } from './ui.js';
|
|
5
|
+
export const termsCurrent = (t) => t.state === 'current';
|
|
6
|
+
export async function getTerms(key) {
|
|
7
|
+
const t = await cliApi(key, 'GET', '/terms');
|
|
8
|
+
if (typeof t.version !== 'string' || typeof t.textHash !== 'string' || typeof t.text !== 'string') {
|
|
9
|
+
throw new Error('Sekura answered the Terms without their text; try again in a minute');
|
|
10
|
+
}
|
|
11
|
+
return t;
|
|
12
|
+
}
|
|
13
|
+
export const acceptTerms = (key, accept, marketing) => cliApi(key, 'POST', '/terms', { version: accept.version, textHash: accept.textHash, accept: true, marketing });
|
|
14
|
+
export function showTerms(t) {
|
|
15
|
+
say();
|
|
16
|
+
for (const line of t.text.split('\n'))
|
|
17
|
+
say(` ${line}`);
|
|
18
|
+
const documents = (t.documents ?? []).filter((d) => d.url);
|
|
19
|
+
if (documents.length) {
|
|
20
|
+
say();
|
|
21
|
+
for (const d of documents)
|
|
22
|
+
say(`${dot} ${d.title ?? 'Document'}: ${d.url}`);
|
|
23
|
+
}
|
|
24
|
+
say();
|
|
25
|
+
say(` Version ${t.version}`);
|
|
26
|
+
say();
|
|
27
|
+
}
|
|
28
|
+
const changed = (e) => isToolError(e, 'terms_changed') || (isToolError(e) && e.status === 409);
|
|
29
|
+
export async function termsFlow(key, opts) {
|
|
30
|
+
const command = opts.command ?? 'sekura terms';
|
|
31
|
+
let terms = await getTerms(key);
|
|
32
|
+
if (termsCurrent(terms))
|
|
33
|
+
return 'current';
|
|
34
|
+
if (opts.accept) {
|
|
35
|
+
try {
|
|
36
|
+
await acceptTerms(key, opts.accept, opts.marketing === true);
|
|
37
|
+
}
|
|
38
|
+
catch (e) {
|
|
39
|
+
if (changed(e))
|
|
40
|
+
throw new Exit(EXIT.agreementRequired, `The Terms are not the ones you named (they are now version ${terms.version}). Run ${command} --json to read them, then accept that version and textHash.`, { version: terms.version, textHash: terms.textHash });
|
|
41
|
+
throw e;
|
|
42
|
+
}
|
|
43
|
+
say(`${tick} Terms accepted (version ${opts.accept.version})`);
|
|
44
|
+
return 'accepted';
|
|
45
|
+
}
|
|
46
|
+
if (!opts.interactive) {
|
|
47
|
+
throw new Exit(EXIT.agreementRequired, `The Sekura Terms have to be accepted before a scan can start, and there is no terminal to ask in. Run ${command} in a terminal, or read them with ${command} --json and accept with ${command} --accept --terms-version ${terms.version} --text-hash ${terms.textHash}.`, { version: terms.version, textHash: terms.textHash });
|
|
48
|
+
}
|
|
49
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
50
|
+
if (terms.state === 'outdated')
|
|
51
|
+
say(`${dot} The Sekura Terms have changed since you accepted them.`);
|
|
52
|
+
showTerms(terms);
|
|
53
|
+
const answer = await select({
|
|
54
|
+
message: 'Do you accept?',
|
|
55
|
+
choices: [
|
|
56
|
+
{ name: 'I accept', value: true },
|
|
57
|
+
{ name: 'Not now', value: false },
|
|
58
|
+
],
|
|
59
|
+
default: false,
|
|
60
|
+
});
|
|
61
|
+
if (!answer)
|
|
62
|
+
return 'declined';
|
|
63
|
+
let marketing = opts.marketing === true;
|
|
64
|
+
if (opts.marketing === undefined && terms.marketingText)
|
|
65
|
+
marketing = await confirm({ message: terms.marketingText, default: false });
|
|
66
|
+
try {
|
|
67
|
+
await acceptTerms(key, { version: terms.version, textHash: terms.textHash }, marketing);
|
|
68
|
+
say(`${tick} Terms accepted (version ${terms.version})`);
|
|
69
|
+
return 'accepted';
|
|
70
|
+
}
|
|
71
|
+
catch (e) {
|
|
72
|
+
if (!changed(e))
|
|
73
|
+
throw e;
|
|
74
|
+
say(`${dot} The Terms changed while you were reading. Here they are again.`);
|
|
75
|
+
terms = await getTerms(key);
|
|
76
|
+
if (termsCurrent(terms))
|
|
77
|
+
return 'current';
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
throw new Exit(EXIT.error, `The Terms kept changing; run ${command} again in a minute.`);
|
|
81
|
+
}
|