sekura 0.4.0 → 0.5.0

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
@@ -1,83 +1,144 @@
1
1
  # sekura
2
2
 
3
- Connect your coding tool to [Sekura](https://sekura.ai) in one command.
3
+ Set up [Sekura](https://sekura.ai) and scan your GitHub repositories from the terminal, and connect your coding tools in the same run.
4
4
 
5
5
  ```bash
6
- npx sekura@latest init
6
+ npx sekura@latest
7
7
  ```
8
8
 
9
- Sekura is an AI red team as a service: it scans a GitHub repository you have granted it, exploits what it finds to prove each finding, and delivers a report. Its MCP server is remote, at `https://sekura.ai/mcp`, so this package runs no server. It writes that address into the coding tools on your machine and installs a skill that teaches the agent the quote-then-confirm rule. Then it finishes getting started right in the terminal: it signs you in once, waits while you accept the Terms and install the GitHub App, and lets you pick a repository. When you open your coding tool, Sekura already works.
9
+ Sekura is an AI red team as a service: it scans a GitHub repository you have granted it, exploits what it finds to prove each finding, and delivers a report. One run of `npx sekura@latest` takes a new person from nothing to a finished first scan: it signs you in with a GitHub code, shows you the Terms to accept, opens the Sekura GitHub App install on github.com, lets you pick a repository, quotes the first scan, and, once you agree, starts it, follows it and saves the report. The only browser pages are github.com (approve the code, install the App) and Stripe (enter a card, when a scan is paid).
10
10
 
11
- `npx sekura@latest` on its own runs `init` too.
11
+ It also writes Sekura's remote MCP server (`https://sekura.ai/mcp`) into the coding tools on your machine and installs a skill that teaches the agent the quote-then-confirm rule, so the same account works from Claude Code, Cursor, Codex and the rest. This package runs no server.
12
12
 
13
- ## What `init` does
13
+ Every step is read from your account, so a second run carries on where the first one stopped.
14
14
 
15
- 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.
16
- 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 **Edit** to choose the tools, every project or this project only, the skill, and the sign-in one by one. A flag answers its own question and skips it.
17
- 3. **Shows the plan** before anything happens: each file and the exact entry, or the tool's own command. The key isn't there yet, so the plan shows `Authorization: Bearer <your key, after sign-in>` where it will go (a key you already have is shown as `sek_live_…abcd`). Then it asks **Apply?**
18
- 4. **Signs you in** once you've said yes. You sign in with GitHub on sekura.ai and approve, and the CLI receives a Sekura key. On a machine whose browser is somewhere else (over SSH, in a devcontainer or Codespace, with `--device`, or when no browser opens), it prints a code instead: open `https://sekura.ai/connect/device` on any device and enter it. If the sign-in doesn't finish, the same plan is applied without a key, and each tool signs in the first time it uses Sekura.
19
- 5. **Applies** the plan with the key in it, one step at a time, and says what each step did. Files that are not plain JSON (Zed's `settings.json` with comments, for one) are never rewritten; you are shown the lines to add instead. Codex and Devin can't take a key in their configuration, so the CLI runs their own `mcp login`; since your browser is already signed in, that's one click.
20
- 6. **Checks** that the Sekura server answers.
21
- 7. **Gets you to a first scan**:
22
- - If your account still needs the Terms or email verification, it opens sekura.ai and carries on by itself once they are done.
23
- - If nothing can be scanned yet, or the repository in the current folder isn't covered, it offers to open the GitHub App install and carries on by itself once the repository shows up.
24
- - It lets you pick a repository, with the current folder's first.
15
+ ## Which Sekura servers do this today
25
16
 
26
- Each wait shows a one-line spinner, stops after five minutes, and Enter skips it.
27
- 8. **Tells you the next step in each tool**, such as "Cursor: restart Cursor (or reload MCP servers in Settings → MCP)" or "Claude Code: start a new Claude Code session, then type /sekura", and what to type to scan, such as `/sekura scan owner/repo` (`/sekura help` lists every command).
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.
28
18
 
29
- Every scan you then ask for in your coding tool is quoted first, with the price and the authorization wording, and starts only after you agree.
19
+ ## What a first run does
30
20
 
31
- ## Paying from your coding tool
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 **Edit** to choose each one. 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?**
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
+ 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
+ 6. **Checks** that the Sekura server answers and takes your key.
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
+ 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
+ 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. On a server with CLI onboarding, a new account's free first scan is started here, in the terminal, at no charge; otherwise Stripe Checkout opens and the CLI waits for the payment. 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
+ 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
+
33
+ ## Commands
34
+
35
+ | Command | What it does |
36
+ |---|---|
37
+ | `sekura`, `sekura init` | The first run above. |
38
+ | `login`, `logout` | Sign in with a GitHub code and give your connected tools their key; `logout` revokes the sign-in key on Sekura and forgets it here. |
39
+ | `status` (alias `account`) | Your account (sign-in, Terms, email, GitHub App, repositories, plans, cards) and which tools here are connected. |
40
+ | `doctor` | The same checklist, with the command to run for each thing that is not ready. Exits 4 when signed out, 5 when the account is not ready. |
41
+ | `terms` | Show the Terms and accept them. `--json` prints the version and text hash. |
42
+ | `repos [--add]` | The repositories Sekura can scan; `--add` opens the GitHub App install and waits for the new ones. |
43
+ | `scan [repo]` | Quote, agree, start, follow, findings, report. `--no-watch` returns once it has started. |
44
+ | `scan show <id> [--watch]`, `scan cancel <id>` | One scan's status and findings; cancel inside its cancel window, shown first. |
45
+ | `scans` | Your scans and their status. |
46
+ | `findings <id>`, `report <id>` | A scan's findings; the report saved to a file (`-o` names it, `--open` opens it). |
47
+ | `plans` | Repositories on a monthly plan. |
48
+ | `plan start [repo]` | Start a monthly plan: `--tier weekly` (Weekly) or `--tier frequent` (More frequently), with `--weekday`, `--every`, `--time`, `--tz` or `--on-demand`. |
49
+ | `plan schedule [repo]`, `plan run [repo]`, `plan cancel [repo]` | Change when a plan runs, run its next scan now, end it. Each is shown first. |
50
+ | `billing [--open]` | Your saved cards, masked, and your active plans. `--open` opens Stripe to add or change a card and waits for the change. |
51
+ | `pay [link] --plan <id>` | Open a Checkout link from a quote and wait for the payment; `--abandon --plan <id>` cancels a pending one. |
52
+ | `uninstall` | Remove the entries, the skill and the guidance block, and revoke the saved keys. |
53
+
54
+ `[repo]` is `owner/repo`. Left out, it is your saved default, then this folder's GitHub remote.
55
+
56
+ ## Rules every command follows
57
+
58
+ - **Quote, shown, agree, start.** Anything that starts, changes or cancels something first prints what Sekura will do, with the authorization wording and the price exactly as the server gives them, and asks. No is exit code 3 and changes nothing.
59
+ - **Without a terminal** (an agent, a script, CI) there are two ways, and no third:
60
+ - `--quote` prints the quote, saves it for 15 minutes and starts nothing; `--confirm <quoteId>` then starts exactly that quote. This is how an agent starts something: quote, show the person, confirm after their yes.
61
+ - `--yes --max-price <usd>` agrees to a quote at or under that price. `--yes` alone never starts anything paid or authorized: it exits 6.
62
+ - **`--card`** picks the saved card to charge: `default`, its last four digits, or its id. Without a saved card, the payment is a Stripe Checkout page.
63
+ - **`--json`** on read commands and on `--quote` puts the data on stdout and nothing else there; everything said to a person goes to stderr.
64
+ - **`--no-browser`** prints links instead of opening them.
65
+
66
+ | Exit code | Meaning |
67
+ |---|---|
68
+ | 0 | Done. |
69
+ | 1 | An error. |
70
+ | 2 | Stopped waiting (you pressed Enter, or the wait ran out); what was started carries on. |
71
+ | 3 | Declined: you said no, closed Checkout unpaid, or the price was above `--max-price`. |
72
+ | 4 | Not signed in. |
73
+ | 5 | The account is not ready: the Terms, the email address or the GitHub App. `sekura doctor` says which. |
74
+ | 6 | Agreement is needed and there is no terminal to give it in. |
75
+ | 7 | A payment needs a browser and none can be opened here. |
76
+
77
+ ## Paying
32
78
 
33
79
  The quote lists how you can pay:
34
80
 
35
- - **A saved card**, shown only by brand and last four (`Visa •••• •••• •••• 4242`). Pick one and it is charged right there, with no browser: `Charged $199 to Visa ending 4242`, then the scan id and link.
36
- - **Pay with a Checkout link.** The agent runs `npx sekura@latest pay "<link>" --plan <id>`, which opens Stripe Checkout in your default browser and waits. When the payment lands, the same session shows the scan id and link. Your first payment is always made this way, and the card you use is saved for next time.
37
- - **Change payment method.** The agent runs `npx sekura@latest billing --open`, which opens the page where you add or change a card, then shows the updated list.
81
+ - **A saved card**, shown only by brand and last four (`Visa •••• •••• •••• 4242`). Pick one and it is charged right there, with no browser.
82
+ - **Stripe Checkout.** The CLI opens the page and waits; when the payment lands it shows the scan id and follows the scan. Your first payment is always made this way, and the card you use is saved for next time.
83
+ - **Change a card** with `sekura billing --open`.
38
84
 
39
- Nothing is charged without a quote and your yes, and only the card you pick is charged.
85
+ From a coding tool the agent does the same through the MCP tools, running `npx sekura@latest pay "<link>" --plan <id>` for a Checkout link. Nothing is charged without a quote and your yes, and only the card you pick is charged.
40
86
 
41
- ## Flags
87
+ ## Flags of `init`
42
88
 
43
89
  | Flag | What it does |
44
90
  |---|---|
45
- | `-y, --yes` | No questions: every detected tool, user scope, the skill, and the key in `SEKURA_API_KEY` or the one `sekura login` saved. Signs in nowhere. |
91
+ | `-y, --yes` | No questions: every detected tool, user scope, the skill, and the key in `SEKURA_API_KEY` or the one `sekura login` saved. Signs in nowhere, accepts no Terms and starts no scan. |
46
92
  | `--tools <ids>` | Only these, comma-separated: `claude`, `cursor`, `copilot`, `codex`, `kiro`, `cline`, `zed`, `antigravity`, `opencode`, `jetbrains`, `factory`, `tabnine`, `devin`, `goose`. |
47
93
  | `--scope <user\|project>` | `user` (every project, the default) or `project` (this directory). |
48
94
  | `--no-skill` | The MCP server only: no skill, no guidance block. |
49
- | `--no-login` | No sign-in here; each tool opens a sekura.ai sign-in page the first time it uses Sekura. This is how 0.1.x worked. |
50
- | `--device` | Sign in with a code on another device. The default over SSH (`SSH_CONNECTION`, `SSH_TTY`), in Codespaces, devcontainers (`REMOTE_CONTAINERS`) and Gitpod. `sekura login` takes it too. |
95
+ | `--no-login` | No sign-in and no account step here; each tool opens a Sekura sign-in the first time it uses Sekura. |
96
+ | `--no-scan` | Stop after the repository; no first scan is offered. |
97
+ | `--no-browser` | Print links instead of opening them. |
98
+ | `--legacy-login` | Sign in on a Sekura page instead of with a GitHub code. `--device` then uses a code on another device, the default over SSH (`SSH_CONNECTION`, `SSH_TTY`), in Codespaces, devcontainers (`REMOTE_CONTAINERS`) and Gitpod. |
51
99
  | `--dry-run` | Show the plan and change nothing. Never signs in and needs no key. |
52
- | `--no-verify` | Don't check that the Sekura server answers. |
100
+ | `--no-verify` | Do not check that the Sekura server answers. |
101
+ | `--endpoint <url>` | Use another Sekura server instead of `https://sekura.ai`, such as `https://dev.sekura.ai` or a local one at `http://127.0.0.1:8787`. The same as setting `SEKURA_ENDPOINT`. Works with every command. |
53
102
 
54
- Project scope never writes the key, because project files get committed.
103
+ Without a terminal and without `--yes`, `init` shows the plan and writes nothing. Project scope never writes a key, because project files get committed.
55
104
 
56
105
  ```bash
57
- npx sekura@latest # the same as init
106
+ npx sekura@latest # set up and scan; the same as init
58
107
  npx sekura@latest init --yes # every detected tool, user scope, with the skill, no questions
59
108
  npx sekura@latest init --dry-run # show the plan and change nothing
60
109
  npx sekura@latest init --scope project # this project only: .mcp.json, .cursor/mcp.json, AGENTS.md …
61
- npx sekura@latest init --tools claude,cursor --no-skill
62
- npx sekura@latest init --no-login # no sign-in here; each tool signs in on first use
63
- npx sekura@latest init --device # sign in with a code, for a terminal on another machine
64
- npx sekura@latest login # sign in again, give connected tools the key, pick a repository
65
- npx sekura@latest status # what is connected, and who is signed in
66
- npx sekura@latest billing # your saved cards, masked; --open to change them
67
- npx sekura@latest pay "<checkout link>" --plan <id> # open Checkout and wait for the payment
68
- npx sekura@latest logout # forget the saved key
69
- npx sekura@latest uninstall # remove the entries, the skill, the guidance block and the saved key
110
+ npx sekura@latest init --tools claude,cursor --no-skill --no-scan
111
+ npx sekura@latest doctor # what is still missing before a scan can start
112
+ npx sekura@latest scan owner/repo # quote, agree, start, follow, report
113
+ npx sekura@latest scan owner/repo --quote --json # for an agent: the quote and its id, nothing started
114
+ npx sekura@latest scan owner/repo --confirm q_abc123 # start exactly that quote
115
+ npx sekura@latest plan start owner/repo --tier weekly --weekday monday --time 09:00
116
+ npx sekura@latest report <scan-id> -o report.html
117
+ npx sekura@latest billing --open # add or change a card on Stripe
118
+ npx sekura@latest logout # revoke the sign-in key and forget it here
119
+ npx sekura@latest uninstall # remove the entries, the skill and the guidance block; revoke the saved keys
70
120
  SEKURA_API_KEY=sek_live_… npx sekura@latest init --yes # unattended, with a key from Settings
71
- SEKURA_ENDPOINT=https://dev.sekura.ai/mcp npx sekura@latest billing # against another Sekura server, for testing
121
+ npx sekura@latest --endpoint https://dev.sekura.ai # against another Sekura server
122
+ ```
123
+
124
+ ## Another Sekura server
125
+
126
+ `SEKURA_ENDPOINT` (or `--endpoint`) points the sign-in, the server check, the links and the address written into each tool at another Sekura server:
127
+
128
+ ```bash
129
+ SEKURA_ENDPOINT=https://dev.sekura.ai npx sekura@latest init
130
+ npx sekura@latest init --endpoint http://127.0.0.1:8787
72
131
  ```
73
132
 
133
+ The address must be `https://`, or `http://` for `127.0.0.1` or `localhost` only (use `127.0.0.1` for a local server), with or without `/mcp` at the end. The default is `https://sekura.ai`. Each server's key is kept under that server's address in `credentials.json`, and a key saved for one server is never sent to another. After a sign-in on another server, a run without the override stays on that server (see Your keys); run `sekura init --endpoint https://sekura.ai` to point your tools back at `https://sekura.ai`.
134
+
74
135
  ## What it writes
75
136
 
76
137
  | Tool | User scope | Project scope |
77
138
  |---|---|---|
78
- | Claude Code | `claude mcp add --transport http -s user sekura …`, or `~/.claude.json` → `mcpServers.sekura` | `.mcp.json` |
139
+ | Claude Code | `claude mcp add --transport http -s user sekura …`, or `~/.claude.json` → `mcpServers.sekura` (always the file when it carries your key) | `.mcp.json` |
79
140
  | Cursor | `~/.cursor/mcp.json` → `mcpServers.sekura` | `.cursor/mcp.json` |
80
- | GitHub Copilot (VS Code) | the VS Code user `mcp.json` → `servers.sekura` | `.mcp.json` |
141
+ | GitHub Copilot in VS Code | the VS Code user `mcp.json` → `servers.sekura` | `.mcp.json` |
81
142
  | OpenAI Codex | `codex mcp add sekura --url …`, or `~/.codex/config.toml` → `[mcp_servers.sekura]` | — |
82
143
  | Kiro | `~/.kiro/settings/mcp.json` | `.kiro/settings/mcp.json` |
83
144
  | Cline | `~/.cline/data/settings/cline_mcp_settings.json` (shared by the extension, v4 and later, and the Cline CLI) | — |
@@ -95,14 +156,24 @@ The skill goes to `~/.agents/skills/sekura/SKILL.md` and, when Claude Code is pr
95
156
  - Every other server, setting and file. The installer sets one key, `sekura`, and reads nothing else.
96
157
  - Your source code isn't read or uploaded by this installer.
97
158
 
98
- ## Your key
159
+ ## Your keys
160
+
161
+ Signing in with a GitHub code creates two Sekura keys:
99
162
 
100
- Signing in creates one Sekura key, named "Sekura CLI (your computer's name)", whichever way you signed in (browser or code). The CLI saves it in `~/.config/sekura/credentials.json` (under `$XDG_CONFIG_HOME` when that is set), readable by you only, and writes it as an `Authorization: Bearer` header into each tool's user configuration. `SEKURA_API_KEY` in the environment is used instead of the saved file when it is set. Nothing printed ever shows the whole key.
163
+ - **The CLI's own key**, named "Sekura CLI (your computer's name)". It carries the `cli` scope, which only this sign-in grants and which is what lets the terminal accept the Terms, download a report and manage cards. It stays in `~/.config/sekura/credentials.json` (under `$XDG_CONFIG_HOME` when that is set) and is never written into a coding tool.
164
+ - **Your tools' key**, named "Sekura CLI (your computer's name) tools", with read and write only. It is the one written as an `Authorization: Bearer` header into each tool's user configuration, and it is recorded beside the CLI's key so it can be revoked later.
101
165
 
102
- - **See or revoke it** at [sekura.ai/app/settings](https://sekura.ai/app/settings) → Agents and API keys. Revoking it there ends it everywhere at once; run `sekura login` for a new one.
103
- - **`sekura logout`** removes the saved copy. Tools that were given the key keep it.
104
- - **`sekura uninstall`** removes the entries (with their key), the skill, the guidance block and the saved copy.
105
- - **`--no-login`** writes no key anywhere, as 0.1.x did.
166
+ With the Sekura-page sign-in (`--legacy-login`, or a server without CLI onboarding) there is one key, used for both.
167
+
168
+ The keys are stored in plain text. Every file the CLI writes one into, its own and each tool's, is set to mode 0600 (readable by you only), and `~/.config/sekura` to 0700; a tool that later rewrites its own file may set its own mode. On Windows the files keep the permissions of your user folder. A key never appears on a command line: for Claude Code it is written into `~/.claude.json` rather than passed to `claude mcp add`. `SEKURA_API_KEY` in the environment is used instead of the saved key when it is set. Nothing printed ever shows a whole key. Any program running as you can read these files, a coding agent with a shell included; the `cli` scope keeps the account steps away from tools that only speak MCP, not from your own machine.
169
+
170
+ - **One sign-in per Sekura server.** A rerun of `init` or `login` uses the saved keys while Sekura still takes them, so it makes no new ones. Keys for `dev.sekura.ai` are kept beside the ones for `sekura.ai` in the same file, and neither replaces the other.
171
+ - **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`.
172
+ - **Codex and Devin** sign in with keys of their own; the CLI prints the command and runs nothing.
173
+ - **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.
174
+ - **`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.
175
+ - **`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.
176
+ - **`--no-login`** writes no key anywhere.
106
177
 
107
178
  Review before running: the source is this repository, the package is [`sekura` on npm](https://www.npmjs.com/package/sekura), and `--dry-run` prints every write the wizard would make.
108
179
 
@@ -110,6 +181,10 @@ Review before running: the source is this repository, the package is [`sekura` o
110
181
 
111
182
  The page at [sekura.ai/connect](https://sekura.ai/connect/) has the file or screen for every tool, including the ones this installer cannot reach (claude.ai, Replit, Lovable, Bolt, v0, and the rest).
112
183
 
184
+ ## Help
185
+
186
+ Write to [support@sekura.ai](mailto:support@sekura.ai).
187
+
113
188
  ## Licence
114
189
 
115
190
  MIT.
package/dist/api.js CHANGED
@@ -1,44 +1,150 @@
1
- // The few Sekura tools the CLI calls itself, over the same MCP endpoint the
1
+ // The Sekura tools the CLI calls itself, over the same MCP endpoint the
2
2
  // coding tools use. The server is stateless JSON-RPC over POST and answers
3
3
  // in plain JSON, so no session and no MCP library: one request per call.
4
- // Only tools that read are called here; every scan is quoted and agreed in
5
- // the coding tool.
6
- import { ENDPOINT } from './catalogue.js';
4
+ import { ENDPOINT, ORIGIN } from './catalogue.js';
5
+ import { reach, serverTrouble } from './errors.js';
7
6
  export class SignedOut extends Error {
8
7
  constructor(detail) { super(detail); this.name = 'SignedOut'; }
9
8
  }
9
+ export class ToolError extends Error {
10
+ op;
11
+ code;
12
+ data;
13
+ link;
14
+ status;
15
+ constructor(o) {
16
+ super(o.message);
17
+ this.name = 'ToolError';
18
+ this.op = o.op;
19
+ this.code = o.code;
20
+ this.data = o.data ?? {};
21
+ this.link = o.link;
22
+ this.status = o.status;
23
+ }
24
+ }
25
+ export const isToolError = (e, code) => e instanceof ToolError && (code === undefined || e.code === code);
10
26
  let nextId = 1;
11
- export async function callTool(key, name, args = {}) {
12
- const r = await fetch(ENDPOINT, {
27
+ const parsedBlock = (content) => {
28
+ for (const c of Array.isArray(content) ? content : []) {
29
+ if (c?.type !== 'text' || typeof c.text !== 'string')
30
+ continue;
31
+ try {
32
+ const v = JSON.parse(c.text);
33
+ if (v && typeof v === 'object' && !Array.isArray(v))
34
+ return v;
35
+ }
36
+ catch {
37
+ continue;
38
+ }
39
+ }
40
+ return null;
41
+ };
42
+ const firstText = (content) => {
43
+ const c = Array.isArray(content) ? content[0] : null;
44
+ return c?.type === 'text' && typeof c.text === 'string' ? c.text : '';
45
+ };
46
+ export async function call(key, op, args = {}, opts = {}) {
47
+ const r = await reach(ENDPOINT, {
13
48
  method: 'POST',
14
49
  headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
15
- body: JSON.stringify({ jsonrpc: '2.0', id: nextId++, method: 'tools/call', params: { name, arguments: args } }),
16
- signal: AbortSignal.timeout(30_000),
50
+ body: JSON.stringify({ jsonrpc: '2.0', id: nextId++, method: 'tools/call', params: { name: op, arguments: args } }),
51
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
17
52
  });
18
53
  const body = (await r.json().catch(() => null));
19
54
  if (r.status === 401)
20
55
  throw new SignedOut(body?.error_description || 'the key is no longer valid');
21
- if (!r.ok || !body)
22
- throw new Error(`Sekura answered ${r.status} to ${name}${body?.error_description ? `: ${body.error_description}` : ''}`);
23
- if (body.error)
24
- throw new Error(`Sekura ${name}: ${body.error.message ?? JSON.stringify(body.error)}`);
56
+ if (r.status >= 500 || (!r.ok && !body?.error_description))
57
+ throw new Error(serverTrouble(r.status));
58
+ if (!r.ok || !body) {
59
+ throw new ToolError({
60
+ op, status: r.status,
61
+ code: typeof body?.error === 'string' ? body.error : 'unavailable',
62
+ message: `Sekura did not answer ${op}${body?.error_description ? `: ${body.error_description}` : ''}`,
63
+ });
64
+ }
65
+ if (body.error) {
66
+ throw new ToolError({
67
+ op, code: 'rpc_error',
68
+ message: `Sekura could not answer ${op}${typeof body.error.message === 'string' ? `: ${body.error.message}` : ''}`,
69
+ data: { rpcCode: body.error.code },
70
+ });
71
+ }
25
72
  const result = body.result ?? {};
26
- if (result.isError)
27
- throw new Error(`Sekura ${name}: ${result.content?.[0]?.text ?? 'failed'}`);
28
- if (result.structuredContent)
29
- return result.structuredContent;
30
- // Older answers carry the data as JSON in the second text block.
31
- for (const c of result.content ?? []) {
32
- if (c?.type !== 'text')
33
- continue;
34
- try {
35
- return JSON.parse(c.text);
36
- }
37
- catch { /* the prose block */ }
73
+ const structured = result.structuredContent && typeof result.structuredContent === 'object' ? result.structuredContent : null;
74
+ const text = firstText(result.content);
75
+ if (result.isError) {
76
+ const data = structured ?? parsedBlock(result.content) ?? {};
77
+ const link = typeof data.link === 'string' ? data.link : undefined;
78
+ const sentence = link && text.endsWith(` ${link}`) ? text.slice(0, -link.length - 1) : text;
79
+ throw new ToolError({ op, code: typeof data.code === 'string' ? data.code : 'refused', message: sentence || `Sekura refused ${op}`, data, link });
38
80
  }
39
- throw new Error(`Sekura ${name}: no data in the answer`);
81
+ const data = structured ?? parsedBlock(result.content);
82
+ if (!data)
83
+ throw new Error(`Sekura ${op}: no data in the answer`);
84
+ return { text: typeof data.text === 'string' && data.text ? data.text : text, data: data };
85
+ }
86
+ export async function callTool(key, name, args = {}) {
87
+ return (await call(key, name, args)).data;
88
+ }
89
+ export const CLI_API = '/api/cli/v1';
90
+ export async function cliFetch(key, method, path, body, opts = {}) {
91
+ return reach(`${ORIGIN}${CLI_API}${path}`, {
92
+ method,
93
+ headers: { authorization: `Bearer ${key}`, accept: 'application/json', ...(body ? { 'content-type': 'application/json' } : {}) },
94
+ ...(body ? { body: JSON.stringify(body) } : {}),
95
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
96
+ });
40
97
  }
98
+ export async function cliApi(key, method, path, body, opts = {}) {
99
+ const r = await cliFetch(key, method, path, body, opts);
100
+ const data = (await r.json().catch(() => null));
101
+ if (r.ok)
102
+ return (data ?? {});
103
+ if (r.status === 401)
104
+ throw new SignedOut(typeof data?.error_description === 'string' ? data.error_description : 'the key is no longer valid');
105
+ const op = `${method} ${CLI_API}${path}`;
106
+ if (r.status >= 500)
107
+ throw new ToolError({ op, status: r.status, code: 'unavailable', message: serverTrouble(r.status), data: data ?? {} });
108
+ const code = typeof data?.code === 'string' ? data.code : typeof data?.error === 'string' && /^[a-z_]+$/.test(data.error) ? data.error : r.status === 404 ? 'not_found' : 'refused';
109
+ const said = typeof data?.error_description === 'string' ? data.error_description : typeof data?.message === 'string' ? data.message : typeof data?.error === 'string' && data.error !== code ? data.error : `Sekura answered HTTP ${r.status}`;
110
+ throw new ToolError({ op, status: r.status, code, message: said, data: data ?? {}, link: typeof data?.link === 'string' ? data.link : undefined });
111
+ }
112
+ export const isMissingRoute = (e) => e instanceof ToolError && e.status === 404 && typeof e.data.code !== 'string' && e.code === 'not_found';
113
+ export const paymentRequiredOf = (e) => isToolError(e, 'payment_required') && typeof e.data.checkoutUrl === 'string' ? e.data : null;
41
114
  export const getAccount = (key) => callTool(key, 'getAccount');
42
115
  export const getPlans = (key) => callTool(key, 'getPlans');
43
116
  export const getBilling = (key) => callTool(key, 'getBilling');
44
- export const listRepositories = (key) => callTool(key, 'listRepositories');
117
+ export async function listRepositories(key, opts = {}) {
118
+ if (!opts.refresh)
119
+ return callTool(key, 'listRepositories');
120
+ try {
121
+ return await callTool(key, 'listRepositories', { refresh: true });
122
+ }
123
+ catch (e) {
124
+ if (!isToolError(e, 'invalid_input'))
125
+ throw e;
126
+ return callTool(key, 'listRepositories');
127
+ }
128
+ }
129
+ export const tools = {
130
+ getAccount: (key) => call(key, 'getAccount'),
131
+ listRepositories: (key) => call(key, 'listRepositories'),
132
+ getPlans: (key) => call(key, 'getPlans'),
133
+ getBilling: (key) => call(key, 'getBilling'),
134
+ listScans: (key, args = {}) => call(key, 'listScans', args),
135
+ getScan: (key, args) => call(key, 'getScan', args),
136
+ getScanFindings: (key, args) => call(key, 'getScanFindings', args),
137
+ getReportLink: (key, args) => call(key, 'getReportLink', args),
138
+ quoteScan: (key, args) => call(key, 'quoteScan', args),
139
+ startScan: (key, args) => call(key, 'startScan', args),
140
+ previewCancelScan: (key, args) => call(key, 'previewCancelScan', args),
141
+ cancelScan: (key, args) => call(key, 'cancelScan', args),
142
+ quoteAlways: (key, args) => call(key, 'quoteAlways', args),
143
+ startAlways: (key, args) => call(key, 'startAlways', args),
144
+ quoteSchedule: (key, args) => call(key, 'quoteSchedule', args),
145
+ updateSchedule: (key, args) => call(key, 'updateSchedule', args),
146
+ quoteRunNow: (key, args) => call(key, 'quoteRunNow', args),
147
+ runNow: (key, args) => call(key, 'runNow', args),
148
+ previewCancelPlan: (key, args) => call(key, 'previewCancelPlan', args),
149
+ cancelPlan: (key, args) => call(key, 'cancelPlan', args),
150
+ };