shiplock 0.0.0-stage → 0.4.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.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/cli.mjs +269 -0
  3. package/index.mjs +152 -0
  4. package/package.json +35 -4
  5. package/README.md +0 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Felipe Alves de Medeiros
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/cli.mjs ADDED
@@ -0,0 +1,269 @@
1
+ #!/usr/bin/env node
2
+ // shiplock: the terminal entrance (Felipe 2026-12-02, onboarding happens in
3
+ // the terminal). `shiplock init` signs this terminal in the way Claude Code
4
+ // does (browser, Authorize, back to the terminal), checks the GitHub
5
+ // repository is connected, and adds ShipLock to the repository's .mcp.json
6
+ // so the coding agent can use it. The token is stored in the user's config
7
+ // directory with mode 600, never in the repository. ShipLock writes no code.
8
+ import { execFileSync, spawn } from "node:child_process";
9
+ import { createHash, randomBytes } from "node:crypto";
10
+ import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
11
+ import { createServer } from "node:http";
12
+ import { createInterface } from "node:readline";
13
+ import { homedir, hostname } from "node:os";
14
+ import { join } from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+
17
+ export const DEFAULT_BASE = "https://shiplock.dev";
18
+ const trim = (url) => url.replace(/\/+$/, "");
19
+ const configDir = () => process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
20
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
21
+
22
+ // ShipLock's look in the terminal: v3 bronze for the accent, dim for the
23
+ // quiet parts. Plain text when piped or when NO_COLOR is set.
24
+ const tty = process.stdout.isTTY && !process.env.NO_COLOR;
25
+ const paint = (open) => (s) => (tty ? `\x1b[${open}m${s}\x1b[0m` : s);
26
+ const bronze = paint("38;2;201;169;97");
27
+ const dim = paint("2");
28
+ const bold = paint("1");
29
+ const ok = (s) => `${bronze("✓")} ${s}`;
30
+
31
+ function banner() {
32
+ const lines = [`${bronze("◆")} ${bold("Welcome to ShipLock")}`, "", dim(" Security checks your coding agent works"), dim(" through. ShipLock writes no code.")];
33
+ const width = 44;
34
+ // eslint-disable-next-line no-control-regex
35
+ const pad = (s) => s + " ".repeat(Math.max(0, width - s.replace(/\x1b\[[0-9;]*m/g, "").length));
36
+ return [bronze(`╭${"─".repeat(width + 2)}╮`), ...lines.map((l) => `${bronze("│")} ${pad(l)} ${bronze("│")}`), bronze(`╰${"─".repeat(width + 2)}╯`)].join("\n");
37
+ }
38
+
39
+ /** owner/name from a GitHub remote URL, or null for any other host. */
40
+ export function githubRepository(remote) {
41
+ const m = /^(?:git@github\.com:|(?:https|ssh):\/\/(?:[^@/]+@)?github\.com\/)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(String(remote).trim());
42
+ return m ? `${m[1]}/${m[2]}` : null;
43
+ }
44
+
45
+ function credentialsFile(dir) { return join(dir ?? configDir(), "shiplock", "credentials.json"); }
46
+
47
+ function readCredentials(dir) {
48
+ try { return JSON.parse(readFileSync(credentialsFile(dir), "utf8")); } catch { return {}; }
49
+ }
50
+
51
+ export function readToken(base, dir) {
52
+ const token = readCredentials(dir)[trim(base)]?.token;
53
+ return typeof token === "string" ? token : null;
54
+ }
55
+
56
+ export function saveToken(base, token, dir) {
57
+ const file = credentialsFile(dir);
58
+ mkdirSync(join(file, ".."), { recursive: true, mode: 0o700 });
59
+ const all = readCredentials(dir);
60
+ all[trim(base)] = { token, savedAt: new Date().toISOString() };
61
+ writeFileSync(file, JSON.stringify(all, null, 2) + "\n", { mode: 0o600 });
62
+ chmodSync(file, 0o600);
63
+ }
64
+
65
+ export function forgetToken(base, dir) {
66
+ const all = readCredentials(dir);
67
+ if (!(trim(base) in all)) return false;
68
+ delete all[trim(base)];
69
+ writeFileSync(credentialsFile(dir), JSON.stringify(all, null, 2) + "\n", { mode: 0o600 });
70
+ return true;
71
+ }
72
+
73
+ /** The repository's .mcp.json with ShipLock added. No token: the server reads it from the user's config. */
74
+ export function mergeMcpConfig(existing) {
75
+ let config = {};
76
+ if (existing != null) {
77
+ try { config = JSON.parse(existing); } catch { throw new Error(".mcp.json is not valid JSON. Fix it, then run shiplock init again."); }
78
+ }
79
+ return { ...config, mcpServers: { ...(config.mcpServers ?? {}), shiplock: { command: "npx", args: ["-y", "shiplock", "mcp"] } } };
80
+ }
81
+
82
+ async function post(fetchImpl, url, body) {
83
+ const res = await fetchImpl(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
84
+ return { status: res.status, body: await res.json().catch(() => ({})) };
85
+ }
86
+
87
+ const CODE = /^[A-Za-z0-9_-]{43}$/;
88
+ const SIGN_IN_MS = 10 * 60 * 1000;
89
+
90
+ const DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>ShipLock</title>
91
+ <body style="margin:0;min-height:100vh;display:grid;place-items:center;background:#0f1b2d;color:#dbe3ee;font:16px system-ui,sans-serif">
92
+ <p><span style="color:#c9a961">&#9670;</span> Signed in to ShipLock. You can close this tab and return to your terminal.</p></body>`;
93
+
94
+ /** The loopback listener the browser returns to (RFC 8252): 127.0.0.1, a
95
+ * free port, one path, and only a callback carrying this sign-in's state. */
96
+ function listen(state) {
97
+ return new Promise((ready, failed) => {
98
+ let settle;
99
+ const code = new Promise((resolve, reject) => { settle = { resolve, reject }; });
100
+ code.catch(() => {});
101
+ const server = createServer((req, res) => {
102
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
103
+ if (url.pathname !== "/callback" || url.searchParams.get("state") !== state) {
104
+ res.writeHead(400, { "content-type": "text/plain" }).end("Not this sign-in.");
105
+ return;
106
+ }
107
+ if (url.searchParams.get("error")) {
108
+ res.writeHead(200, { "content-type": "text/plain" }).end("Cancelled. Nothing was authorized.");
109
+ settle.reject(new Error("Sign-in was cancelled in the browser."));
110
+ return;
111
+ }
112
+ const value = url.searchParams.get("code") ?? "";
113
+ if (!CODE.test(value)) { res.writeHead(400, { "content-type": "text/plain" }).end("Invalid code."); return; }
114
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(DONE_PAGE);
115
+ settle.resolve(value);
116
+ });
117
+ server.on("error", failed);
118
+ server.listen(0, "127.0.0.1", () => ready({ port: server.address().port, code, close: () => server.close() }));
119
+ });
120
+ }
121
+
122
+ /** "Paste code here if prompted >", as Claude Code asks: the fallback when the
123
+ * browser runs on another machine. Cancelled once the callback wins. */
124
+ export function askForCode() {
125
+ if (!process.stdin.isTTY) return { promise: new Promise(() => {}), cancel: () => {} };
126
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
127
+ const promise = new Promise((resolve) => {
128
+ const prompt = () => rl.question(`${dim("Paste code here if prompted")} ${bronze(">")} `, (answer) => {
129
+ const value = answer.trim();
130
+ if (CODE.test(value)) resolve(value);
131
+ else { if (value) console.log("That code is not complete. Copy it again from the browser."); prompt(); }
132
+ });
133
+ prompt();
134
+ });
135
+ return { promise, cancel: () => rl.close() };
136
+ }
137
+
138
+ /** A terminal over SSH cannot receive the browser's callback. */
139
+ function isRemote() { return Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY); }
140
+
141
+ /** Browser sign-in, the way Claude Code does it: OAuth's authorization code
142
+ * with PKCE. The link carries only the S256 challenge; the code comes back to
143
+ * a 127.0.0.1 listener, or is pasted; the verifier redeems it once. */
144
+ export async function login({ base, client, fetch: fetchImpl = fetch, say = console.log, open = openBrowser, ask = askForCode, remote = isRemote() }) {
145
+ const verifier = randomBytes(32).toString("base64url");
146
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
147
+ const state = randomBytes(16).toString("base64url");
148
+ const loopback = remote ? null : await listen(state).catch(() => null);
149
+ const url = `${trim(base)}/cli?${new URLSearchParams({ challenge, state, client, ...(loopback ? { port: String(loopback.port) } : {}) })}`;
150
+ if (loopback) {
151
+ say(`${dim("Opening your browser to sign in...")}\n${dim("Browser didn't open? Use the URL below to sign in:")}\n\n${url}\n`);
152
+ open(url);
153
+ } else {
154
+ say(`${dim("Open this URL in a browser to sign in, then paste the code it shows:")}\n\n${url}\n`);
155
+ }
156
+ const pasted = ask();
157
+ let timer;
158
+ try {
159
+ const code = await Promise.race([
160
+ ...(loopback ? [loopback.code] : []),
161
+ pasted.promise,
162
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("The sign-in expired. Run the command again.")), SIGN_IN_MS); }),
163
+ ]);
164
+ const res = await fetchImpl(`${trim(base)}/api/cli/token`, {
165
+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code, verifier }),
166
+ });
167
+ const body = await res.json().catch(() => ({}));
168
+ if (res.status !== 200 || typeof body.token !== "string") throw new Error(body.error || `Sign-in failed (${res.status}).`);
169
+ return body.token;
170
+ } finally {
171
+ clearTimeout(timer);
172
+ pasted.cancel();
173
+ loopback?.close();
174
+ }
175
+ }
176
+
177
+ /** Whether ShipLock reads this repository, from the same context the agent gets. */
178
+ export async function repositoryStatus({ base, token, repository, fetch: fetchImpl = fetch }) {
179
+ const res = await fetchImpl(`${trim(base)}/api/mcp/context?repository=${encodeURIComponent(repository)}`, {
180
+ headers: { Authorization: `Bearer ${token}` },
181
+ });
182
+ const body = await res.json().catch(() => ({}));
183
+ if (res.status === 200) return { state: "selected", context: body };
184
+ if (res.status === 401) return { state: "signed_out" };
185
+ if (res.status === 404 || res.status === 400) return { state: "not_selected" };
186
+ throw new Error(body.error || `ShipLock could not read the repository (${res.status}).`);
187
+ }
188
+
189
+ export function openBrowser(url) {
190
+ if (process.env.SHIPLOCK_NO_BROWSER) return;
191
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]]
192
+ : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
193
+ try { spawn(cmd, args, { stdio: "ignore", detached: true }).on("error", () => {}).unref(); } catch { /* the URL is printed */ }
194
+ }
195
+
196
+ function git(args) {
197
+ try { return execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch { return null; }
198
+ }
199
+
200
+ async function signIn(base) {
201
+ const token = await login({ base, client: hostname().slice(0, 60) || "A terminal" });
202
+ saveToken(base, token);
203
+ console.log(`\n${ok("Signed in")} ${dim("(token saved in your config directory, never in the repository)")}`);
204
+ return token;
205
+ }
206
+
207
+ async function init(base) {
208
+ const root = git(["rev-parse", "--show-toplevel"]);
209
+ if (!root) throw new Error("Run shiplock init inside a git repository.");
210
+ const repository = githubRepository(git(["remote", "get-url", "origin"]) ?? "");
211
+ if (!repository) throw new Error("This repository has no GitHub remote named origin. ShipLock reads repositories through GitHub.");
212
+ console.log(`${banner()}\n\n ${dim("Repository")} ${bold(repository)}\n`);
213
+
214
+ let token = readToken(base);
215
+ let status = token ? await repositoryStatus({ base, token, repository }) : { state: "signed_out" };
216
+ if (status.state === "signed_out") {
217
+ token = await signIn(base);
218
+ status = await repositoryStatus({ base, token, repository });
219
+ } else console.log(ok("Signed in"));
220
+
221
+ if (status.state === "not_selected") {
222
+ console.log(`\n${bronze("◆")} Connect ${repository}: install the ShipLock GitHub App on it and select it.`);
223
+ console.log(dim("Opening ShipLock in your browser. Waiting..."));
224
+ openBrowser(`${trim(base)}/onboarding`);
225
+ const deadline = Date.now() + 15 * 60 * 1000;
226
+ while (status.state === "not_selected" && Date.now() < deadline) {
227
+ await sleep(5000);
228
+ status = await repositoryStatus({ base, token, repository });
229
+ }
230
+ if (status.state !== "selected") throw new Error(`${repository} is not selected yet. Finish in the browser, then run shiplock init again.`);
231
+ }
232
+ console.log(ok(`${repository} connected`));
233
+
234
+ const file = join(root, ".mcp.json");
235
+ const merged = mergeMcpConfig(existsSync(file) ? readFileSync(file, "utf8") : null);
236
+ writeFileSync(file, JSON.stringify(merged, null, 2) + "\n");
237
+ console.log(`${ok("Added ShipLock to .mcp.json")} ${dim("(no token in it, safe to commit)")}`);
238
+
239
+ const loop = status.context?.loop ?? [];
240
+ if (loop.length) {
241
+ console.log("");
242
+ const wide = Math.max(...loop.map((stage) => stage.stage.length));
243
+ for (const stage of loop) console.log(` ${dim(stage.stage.padEnd(wide))} ${stage.headline ?? stage.state}`);
244
+ }
245
+ console.log(`\n${bronze("◆")} Open your coding agent here and ask it to check ShipLock's findings.\n ${dim("ShipLock checks every pull request.")}`);
246
+ }
247
+
248
+ const HELP = `shiplock: security checks your coding agent works through
249
+
250
+ shiplock init sign in, connect this repository, add ShipLock to .mcp.json
251
+ shiplock login sign this terminal in
252
+ shiplock logout forget this terminal's token
253
+ shiplock mcp run the MCP server for your agent (used by .mcp.json)
254
+
255
+ SHIPLOCK_URL changes the address (default ${DEFAULT_BASE}).`;
256
+
257
+ export async function main(argv) {
258
+ const base = trim(process.env.SHIPLOCK_URL || DEFAULT_BASE);
259
+ const command = argv[0] ?? "help";
260
+ if (command === "init") return init(base);
261
+ if (command === "login") { await signIn(base); return; }
262
+ if (command === "logout") { console.log(forgetToken(base) ? "Signed out. Revoke the token in Settings to end it everywhere." : "Not signed in."); return; }
263
+ if (command === "mcp") { await import("./index.mjs"); return; }
264
+ console.log(HELP);
265
+ if (command !== "help" && command !== "--help" && command !== "-h") process.exitCode = 1;
266
+ }
267
+
268
+ const invoked = process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
269
+ if (invoked) main(process.argv.slice(2)).catch((err) => { console.error(`\n${err instanceof Error ? err.message : err}`); process.exitCode = 1; });
package/index.mjs ADDED
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ // ShipLock MCP server (stdio). Runs on the developer's machine and exposes their
3
+ // ShipLock security findings and fix guidance to their coding agent (Claude
4
+ // Code, Cursor, Codex). Thin wrapper over /api/mcp/*, authenticated with a
5
+ // ShipLock token: SHIPLOCK_TOKEN, or the one `shiplock init` saved in the
6
+ // user's config directory. Read tools, polling ShipLock intelligence tasks and
7
+ // submitting a proposal for one; ShipLock verifies every proposal against
8
+ // GitHub and only stores it. This server cannot start a scan, write a file,
9
+ // open a pull request or merge: ShipLock writes no code (2026-12-02).
10
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
11
+ import { readToken } from "./cli.mjs";
12
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
+ import {
14
+ CallToolRequestSchema,
15
+ ListToolsRequestSchema,
16
+ ListResourcesRequestSchema,
17
+ ReadResourceRequestSchema,
18
+ } from "@modelcontextprotocol/sdk/types.js";
19
+
20
+ const BASE = (process.env.SHIPLOCK_URL || "https://shiplock.dev").replace(/\/+$/, "");
21
+ const TOKEN = process.env.SHIPLOCK_TOKEN || readToken(BASE);
22
+
23
+ async function api(path, init = {}) {
24
+ if (!TOKEN) throw new Error("Not signed in. Run `npx shiplock init` in this repository, or set SHIPLOCK_TOKEN.");
25
+ const res = await fetch(`${BASE}${path}`, {
26
+ ...init,
27
+ headers: { Authorization: `Bearer ${TOKEN}`, "content-type": "application/json", ...(init.headers || {}) },
28
+ });
29
+ const data = await res.json().catch(() => ({}));
30
+ if (!res.ok) throw new Error(data.error || `ShipLock request failed (${res.status})`);
31
+ return data;
32
+ }
33
+
34
+ const TOOLS = [
35
+ {
36
+ name: "list_findings",
37
+ description:
38
+ "List the open security findings for the connected ShipLock account (scan + deep). Returns id, title, severity, source, fix method, and a summary. Use get_fix for the full fix.",
39
+ inputSchema: { type: "object", properties: {} },
40
+ },
41
+ {
42
+ name: "get_fix",
43
+ description:
44
+ "Get the full fix for one finding by id. Returns the fix method and, for code/DB fixes, the exact file content + target path to write into the working tree (the developer reviews the git diff and commits). DB/RLS fixes are migration files applied by the developer's own deploy — never write them to production directly. Some fixes return a deep-link URL instead.",
45
+ inputSchema: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
46
+ },
47
+ {
48
+ name: "get_security_context",
49
+ description:
50
+ "Start here before editing a repository selected in ShipLock. Returns, as JSON: the last finished audit's time and status, auditInProgress (status and current step when one is queued or running), loop (the read, attack, map, fix, watch stages the dashboard shows, each with its state), the detected stack, the guardrails (security controls the code has today, which ShipLock's pull request check will not let a change remove), open findings with route, file and consequence, production (which commit production runs and how many commits are not live yet), liveSite (backend addresses the live site requests that the repository has no route for, and any the code removed that are still live), notRead (what the audit could not check), and howToUse. Built from ShipLock's stored facts: no source code, no model call. Pass repository as owner/name; it may be omitted when one repository is selected. Anything in notRead, and any route without a rule, is not known to be safe.",
51
+ inputSchema: { type: "object", properties: { repository: { type: "string", description: "owner/name of a repository selected in ShipLock" } }, additionalProperties: false },
52
+ },
53
+ {
54
+ name: "get_guardrails",
55
+ description:
56
+ "Read the security rules a selected repository must keep, as JSON: for each route that reaches data, which controls ShipLock observed today (signed-in caller required, rows scoped to the caller, machine secret required), the tables involved, and what to keep when editing. Read this before changing a route or its helpers; ShipLock's pull request check blocks a change that removes one of these controls. A route with no rule is not known to be safe: controls ShipLock could not read are never rules. Pass repository as owner/name; it may be omitted when the account has one selected repository. Returns guardrails null when no audit facts exist yet.",
57
+ inputSchema: { type: "object", properties: { repository: { type: "string", description: "owner/name of a repository selected in ShipLock" } }, additionalProperties: false },
58
+ },
59
+ {
60
+ name: "list_intelligence_tasks",
61
+ description:
62
+ "List ShipLock intelligence tasks waiting for this account's coding agent: task id, kind, repository, commit, and instruction. Kinds: review (a deep or pull request scan), attack_reasoning (reason over an audit's route inventory), attack_verification (prove or refute attack claims with quoted lines). Run on your own schedule; tasks expire, and an unanswered task stays 'AI check pending' in ShipLock.",
63
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
64
+ },
65
+ {
66
+ name: "get_intelligence_task",
67
+ description:
68
+ "Read one intelligence task: kind, repository, commit, instruction, the file paths and SHA-256 hashes it covers, limits, and the exact JSON schema a result must match. An attack_reasoning task adds system and prompt (the audit's route inventory); an attack_verification task adds system and claims. ShipLock never sends source; read the files from your own checkout at that commit.",
69
+ inputSchema: { type: "object", properties: { taskId: { type: "string" } }, required: ["taskId"], additionalProperties: false },
70
+ },
71
+ {
72
+ name: "submit_intelligence_result",
73
+ description:
74
+ "Submit one result for a task, matching the task's resultSchema. Quote cited lines exactly; propose edits only for mechanical changes, and use status needs_human for anything that depends on ownership, authorization, or business policy. ShipLock checks every attack hypothesis against the audit's facts and re-reads cited files from GitHub before accepting; only a claim proved by quoted lines becomes a finding. It never applies an edit or opens a PR.",
75
+ inputSchema: {
76
+ type: "object",
77
+ properties: { taskId: { type: "string" }, result: { type: "object" } },
78
+ required: ["taskId", "result"],
79
+ additionalProperties: false,
80
+ },
81
+ },
82
+ {
83
+ name: "report_self_check",
84
+ description:
85
+ "Report what one self-check showed. get_security_context gives some findings a selfCheck: one harmless curl with an id that cannot exist, so it reads and changes nothing. Run it yourself against the customer's local or preview app, never production, then send the finding id, the HTTP status you got, and the host you ran it against (for example localhost:3000). ShipLock records its own method and path for that finding, refuses the production address, and shows your report on the finding as a test your agent ran, never as proof; it changes no status. Pass repository as owner/name when the id is open in more than one repository.",
86
+ inputSchema: { type: "object", properties: { findingId: { type: "string" }, status: { type: "integer", minimum: 100, maximum: 599 },
87
+ host: { type: "string", description: "host:port you ran it against, never production" }, repository: { type: "string", description: "owner/name, when the id is ambiguous" } },
88
+ required: ["findingId", "status", "host"], additionalProperties: false },
89
+ },
90
+ ];
91
+
92
+ // Task ids are UUIDs. Refuse anything else before building a request path.
93
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
94
+ function taskPath(taskId) {
95
+ if (typeof taskId !== "string" || !UUID.test(taskId)) throw new Error("taskId must be a task UUID");
96
+ return `/api/mcp/intelligence/tasks/${taskId}`;
97
+ }
98
+
99
+ const RESOURCES = [
100
+ { uri: "shiplock://brief", name: "ShipLock security brief", description: "Every open finding with its fix, formatted for the agent.", mimeType: "text/markdown" },
101
+ { uri: "shiplock://posture", name: "ShipLock posture", description: "Current security posture summary (counts, last scan).", mimeType: "application/json" },
102
+ ];
103
+
104
+ const server = new Server({ name: "shiplock", version: "0.3.0" }, { capabilities: { tools: {}, resources: {} } });
105
+
106
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
107
+
108
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources: RESOURCES }));
109
+
110
+ server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
111
+ const { uri } = req.params;
112
+ if (uri === "shiplock://brief") {
113
+ const { markdown } = await api("/api/mcp/brief");
114
+ return { contents: [{ uri, mimeType: "text/markdown", text: markdown }] };
115
+ }
116
+ if (uri === "shiplock://posture") {
117
+ const posture = await api("/api/mcp/posture");
118
+ return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(posture, null, 2) }] };
119
+ }
120
+ throw new Error(`Unknown resource: ${uri}`);
121
+ });
122
+
123
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
124
+ const { name, arguments: args = {} } = req.params;
125
+ try {
126
+ let result;
127
+ if (name === "list_findings") {
128
+ result = await api("/api/mcp/findings");
129
+ } else if (name === "get_fix") {
130
+ result = await api(`/api/mcp/fix?id=${encodeURIComponent(args.id)}`);
131
+ } else if (name === "get_security_context") {
132
+ result = await api(`/api/mcp/context${args.repository ? `?repository=${encodeURIComponent(args.repository)}` : ""}`);
133
+ } else if (name === "get_guardrails") {
134
+ result = await api(`/api/mcp/guardrails${args.repository ? `?repository=${encodeURIComponent(args.repository)}` : ""}`);
135
+ } else if (name === "list_intelligence_tasks") {
136
+ result = await api("/api/mcp/intelligence/tasks");
137
+ } else if (name === "get_intelligence_task") {
138
+ result = await api(taskPath(args.taskId));
139
+ } else if (name === "submit_intelligence_result") {
140
+ result = await api(`${taskPath(args.taskId)}/result`, { method: "POST", body: JSON.stringify({ result: args.result }) });
141
+ } else if (name === "report_self_check") {
142
+ result = await api("/api/mcp/self-check", { method: "POST", body: JSON.stringify({ findingId: args.findingId, status: args.status, host: args.host, repository: args.repository }) });
143
+ } else {
144
+ throw new Error(`Unknown tool: ${name}`);
145
+ }
146
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
147
+ } catch (err) {
148
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
149
+ }
150
+ });
151
+
152
+ await server.connect(new StdioServerTransport());
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "shiplock",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "description": "ShipLock in your terminal: sign in, add ShipLock to your repository's .mcp.json, and give your coding agent its security findings over MCP. ShipLock writes no code.",
5
+ "license": "MIT",
6
+ "homepage": "https://shiplock.dev",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Pipemedeiros/Shiplock-OS.git",
10
+ "directory": "mcp"
11
+ },
12
+ "keywords": [
13
+ "security",
14
+ "mcp",
15
+ "claude-code",
16
+ "cursor",
17
+ "codex",
18
+ "nextjs",
19
+ "supabase",
20
+ "cli"
21
+ ],
22
+ "type": "module",
23
+ "bin": {
24
+ "shiplock": "cli.mjs",
25
+ "shiplock-mcp": "index.mjs"
26
+ },
27
+ "files": [
28
+ "cli.mjs",
29
+ "index.mjs"
30
+ ],
31
+ "engines": {
32
+ "node": ">=18"
33
+ },
34
+ "dependencies": {
35
+ "@modelcontextprotocol/sdk": "^1.0.0"
36
+ }
37
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.