@quillaudits/cli 0.2.2 → 0.2.3

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 (3) hide show
  1. package/README.md +3 -3
  2. package/dist/qs.js +314 -174
  3. package/package.json +5 -2
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # QuillAudits CLI
1
+ # QuillShield CLI
2
2
 
3
- Paid audits from the terminal. Same path as the web app: **quote → order → pay → start**.
3
+ Run QuillShield from the terminal. QuillShield is the AI security auditor for Solidity smart contracts from the audit firm QuillAudits: it runs a full audit with proofs of concept, then checks every pull request against it. The CLI takes the same path as the web app at https://shield.quillaudits.com: **quote, order, pay, start**.
4
4
 
5
5
  Prefer **Cursor / Claude**? Use [`@quillaudits/mcp`](../mcp) instead — [MCP guide](../../docs/MCP.md).
6
6
 
@@ -48,7 +48,7 @@ qs report <job-id> --out ./report.pdf
48
48
  ## Environment
49
49
 
50
50
  ```bash
51
- export QUILLSHIELD_API_URL=https://api.quillaudits.ai
51
+ export QUILLSHIELD_API_URL=https://api-production-7027.up.railway.app
52
52
  export QUILLSHIELD_API_KEY=qs_live_xxxxxxxxxxxx
53
53
  export QUILLSHIELD_ORG_ID=01… # optional
54
54
  ```
package/dist/qs.js CHANGED
@@ -51,14 +51,30 @@ var __require = /* @__PURE__ */ createRequire(import.meta.url);
51
51
  import { homedir } from "node:os";
52
52
  import { join } from "node:path";
53
53
  import { mkdir, readFile, writeFile, unlink } from "node:fs/promises";
54
- async function loadConfig() {
54
+ function assertSafeApiUrl(apiUrl) {
55
+ let url;
56
+ try {
57
+ url = new URL(apiUrl);
58
+ } catch {
59
+ throw new Error(`Invalid API URL: ${apiUrl}`);
60
+ }
61
+ if (url.protocol === "https:")
62
+ return;
63
+ const host = url.hostname.toLowerCase();
64
+ const loopback = host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
65
+ if (url.protocol === "http:" && (loopback || process.env.QUILLSHIELD_ALLOW_INSECURE_API_URL === "1"))
66
+ return;
67
+ throw new Error(`Refusing to send the API key over plain HTTP to ${url.host}. Use an https:// API URL (set QUILLSHIELD_ALLOW_INSECURE_API_URL=1 for a trusted private network).`);
68
+ }
69
+ async function loadConfigUnchecked() {
55
70
  const envKey = process.env.QUILLSHIELD_API_KEY;
56
71
  const envUrl = process.env.QUILLSHIELD_API_URL;
72
+ const envOrg = process.env.QUILLSHIELD_ORG_ID;
57
73
  if (envKey && envUrl) {
58
74
  return {
59
75
  api_url: envUrl,
60
76
  api_key: envKey,
61
- org_id: process.env.QUILLSHIELD_ORG_ID
77
+ org_id: envOrg
62
78
  };
63
79
  }
64
80
  try {
@@ -68,6 +84,8 @@ async function loadConfig() {
68
84
  cfg.api_key = envKey;
69
85
  if (envUrl)
70
86
  cfg.api_url = envUrl;
87
+ if (envOrg)
88
+ cfg.org_id = envOrg;
71
89
  if (!cfg.api_key || !cfg.api_url)
72
90
  return null;
73
91
  return cfg;
@@ -76,9 +94,9 @@ async function loadConfig() {
76
94
  }
77
95
  }
78
96
  async function saveConfig(cfg) {
79
- await mkdir(CONFIG_DIR, { recursive: true });
97
+ await mkdir(CONFIG_DIR, { recursive: true, mode: 448 });
80
98
  await writeFile(CONFIG_FILE, JSON.stringify(cfg, null, 2) + `
81
- `, "utf8");
99
+ `, { encoding: "utf8", mode: 384 });
82
100
  try {
83
101
  const { chmod } = await import("node:fs/promises");
84
102
  await chmod(CONFIG_FILE, 384);
@@ -97,7 +115,13 @@ async function requireConfig() {
97
115
  }
98
116
  return cfg;
99
117
  }
100
- var CONFIG_DIR, CONFIG_FILE, DEFAULT_API_URL = "http://localhost:3001";
118
+ async function loadConfig() {
119
+ const cfg = await loadConfigUnchecked();
120
+ if (cfg)
121
+ assertSafeApiUrl(cfg.api_url);
122
+ return cfg;
123
+ }
124
+ var CONFIG_DIR, CONFIG_FILE, DEFAULT_API_URL = "https://api-production-7027.up.railway.app";
101
125
  var init_config = __esm(() => {
102
126
  CONFIG_DIR = join(homedir(), ".quillshield");
103
127
  CONFIG_FILE = join(CONFIG_DIR, "config.json");
@@ -110,15 +134,21 @@ function isPaymentRequiredDetails(d) {
110
134
  const o = d;
111
135
  return typeof o.quote_id === "string" && typeof o.project_id === "string" && typeof o.project_version_id === "string" && o.quote != null && typeof o.quote === "object" && o.project != null && typeof o.project === "object" && o.version != null && typeof o.version === "object";
112
136
  }
137
+ function seg(value) {
138
+ return encodeURIComponent(String(value));
139
+ }
113
140
 
114
141
  class QuillShieldApi {
115
142
  cfg;
116
- constructor(cfg) {
143
+ client;
144
+ constructor(cfg, client = "cli") {
117
145
  this.cfg = cfg;
146
+ this.client = client;
118
147
  }
119
148
  headers(extra) {
120
149
  const h = {
121
150
  Authorization: `Bearer ${this.cfg.api_key}`,
151
+ "X-QuillShield-Client": this.client,
122
152
  ...extra
123
153
  };
124
154
  if (this.cfg.org_id)
@@ -126,7 +156,12 @@ class QuillShieldApi {
126
156
  return h;
127
157
  }
128
158
  async request(method, path, opts = {}) {
129
- const url = `${this.cfg.api_url}${path}`;
159
+ const base = this.cfg.api_url.replace(/\/+$/, "");
160
+ const url = `${base}${path}`;
161
+ const resolved = new URL(url);
162
+ const expected = new URL(base).pathname.replace(/\/+$/, "") + path.split("?")[0];
163
+ if (resolved.pathname !== expected)
164
+ throw new Error("Invalid API path");
130
165
  const isJson = opts.body !== undefined && !(opts.body instanceof FormData);
131
166
  const res = await fetch(url, {
132
167
  method,
@@ -159,10 +194,13 @@ class QuillShieldApi {
159
194
  return this.request("GET", "/v1/projects");
160
195
  }
161
196
  async getProject(id) {
162
- return this.request("GET", `/v1/projects/${id}`);
197
+ return this.request("GET", `/v1/projects/${seg(id)}`);
163
198
  }
164
199
  async listVersions(projectId) {
165
- return this.request("GET", `/v1/projects/${projectId}/versions`);
200
+ return this.request("GET", `/v1/projects/${seg(projectId)}/versions`);
201
+ }
202
+ async listWorkflows() {
203
+ return (await this.request("GET", "/v1/workflows")).items;
166
204
  }
167
205
  async submitForCheckout(args) {
168
206
  try {
@@ -208,76 +246,69 @@ class QuillShieldApi {
208
246
  });
209
247
  }
210
248
  async getQuote(quoteId) {
211
- return this.request("GET", `/v1/quotes/${quoteId}`);
249
+ return this.request("GET", `/v1/quotes/${seg(quoteId)}`);
250
+ }
251
+ async refreshQuoteWallet(quoteId) {
252
+ return this.request("POST", `/v1/quotes/${seg(quoteId)}/refresh-wallet`, { body: {} });
212
253
  }
213
254
  async applyCoupon(quoteId, couponCode) {
214
- return this.request("POST", `/v1/quotes/${quoteId}/apply-coupon`, {
255
+ return this.request("POST", `/v1/quotes/${seg(quoteId)}/apply-coupon`, {
215
256
  body: { coupon_code: couponCode }
216
257
  });
217
258
  }
218
259
  async removeCoupon(quoteId) {
219
- return this.request("POST", `/v1/quotes/${quoteId}/remove-coupon`, {
260
+ return this.request("POST", `/v1/quotes/${seg(quoteId)}/remove-coupon`, {
220
261
  body: {}
221
262
  });
222
263
  }
223
- async createOrder(quoteId, paymentMethod) {
224
- return this.request("POST", `/v1/quotes/${quoteId}/orders`, {
225
- body: { payment_method: paymentMethod }
264
+ async createOrder(quoteId, paymentMethod, walletOnly = false) {
265
+ return this.request("POST", `/v1/quotes/${seg(quoteId)}/orders`, {
266
+ body: { payment_method: paymentMethod, ...walletOnly ? { wallet_only: true } : {} }
226
267
  });
227
268
  }
228
269
  async getOrder(orderId) {
229
- return this.request("GET", `/v1/orders/${orderId}`);
270
+ return this.request("GET", `/v1/orders/${seg(orderId)}`);
230
271
  }
231
272
  async listOrders() {
232
273
  return this.request("GET", "/v1/orders");
233
274
  }
234
275
  async confirmStripePayment(orderId) {
235
- return this.request("POST", `/v1/orders/${orderId}/confirm-stripe-payment`, {
276
+ return this.request("POST", `/v1/orders/${seg(orderId)}/confirm-stripe-payment`, {
236
277
  body: {}
237
278
  });
238
279
  }
239
280
  async refreshCheckoutSession(orderId) {
240
- return this.request("POST", `/v1/orders/${orderId}/refresh-checkout-session`, {
281
+ return this.request("POST", `/v1/orders/${seg(orderId)}/refresh-checkout-session`, {
241
282
  body: {}
242
283
  });
243
284
  }
244
285
  async startAudit(orderId) {
245
- return this.request("POST", `/v1/orders/${orderId}/start-audit`, {
286
+ return this.request("POST", `/v1/orders/${seg(orderId)}/start-audit`, {
246
287
  body: {}
247
288
  });
248
289
  }
249
- async mockConfirmPayment(orderId) {
250
- return this.request("POST", "/v1/webhooks/mock-confirm", {
251
- body: { order_id: orderId }
252
- });
253
- }
254
- async mockConfirmTopup(topupOrderId) {
255
- return this.request("POST", "/v1/webhooks/mock-confirm-topup", {
256
- body: { topup_order_id: topupOrderId }
257
- });
258
- }
259
290
  async getWallet() {
260
291
  return this.request("GET", "/v1/wallet");
261
292
  }
262
293
  async getWalletTransactions() {
263
294
  return this.request("GET", "/v1/wallet/transactions");
264
295
  }
265
- async createWalletTopup(amountCents) {
296
+ async createWalletTopup(amountCents, paymentMethod = "stripe") {
266
297
  return this.request("POST", "/v1/wallet/topups", {
267
- body: { amount_cents: amountCents }
298
+ body: { amount_cents: amountCents, payment_method: paymentMethod }
268
299
  });
269
300
  }
270
301
  async getWalletTopup(topupOrderId) {
271
- return this.request("GET", `/v1/wallet/topups/${topupOrderId}`);
302
+ return this.request("GET", `/v1/wallet/topups/${seg(topupOrderId)}`);
272
303
  }
273
304
  async confirmWalletTopupPayment(topupOrderId) {
274
- return this.request("POST", `/v1/wallet/topups/${topupOrderId}/confirm-stripe-payment`, { body: {} });
305
+ return this.request("POST", `/v1/wallet/topups/${seg(topupOrderId)}/confirm-stripe-payment`, { body: {} });
275
306
  }
276
307
  async refreshWalletTopupCheckoutSession(topupOrderId) {
277
- return this.request("POST", `/v1/wallet/topups/${topupOrderId}/refresh-checkout-session`, { body: {} });
308
+ return this.request("POST", `/v1/wallet/topups/${seg(topupOrderId)}/refresh-checkout-session`, { body: {} });
278
309
  }
279
310
  async getAudit(jobId) {
280
- return this.request("GET", `/v1/audits/${jobId}`);
311
+ return this.request("GET", `/v1/audits/${seg(jobId)}`);
281
312
  }
282
313
  async listAudits(opts) {
283
314
  const params = new URLSearchParams;
@@ -289,13 +320,13 @@ class QuillShieldApi {
289
320
  return this.request("GET", `/v1/audits${q ? `?${q}` : ""}`);
290
321
  }
291
322
  async cancelAudit(jobId) {
292
- await this.request("POST", `/v1/audits/${jobId}/cancel`);
323
+ await this.request("POST", `/v1/audits/${seg(jobId)}/cancel`);
293
324
  }
294
325
  async getFindings(jobId) {
295
- return this.request("GET", `/v1/audits/${jobId}/findings`);
326
+ return this.request("GET", `/v1/audits/${seg(jobId)}/findings`);
296
327
  }
297
328
  async getReportUrl(jobId, format = "pdf") {
298
- const res = await this.request("GET", `/v1/audits/${jobId}/report?format=${format}`);
329
+ const res = await this.request("GET", `/v1/audits/${seg(jobId)}/report?format=${seg(format)}`);
299
330
  if (typeof res === "string")
300
331
  return res;
301
332
  return res.url ?? JSON.stringify(res);
@@ -308,9 +339,10 @@ class QuillShieldApi {
308
339
  throw new ApiClientError(res.status, "http_error", text.slice(0, 200) || `Report download failed (${res.status})`);
309
340
  }
310
341
  const contentType = res.headers.get("content-type") ?? "application/octet-stream";
342
+ const bytes = Buffer.from(await res.arrayBuffer());
311
343
  if (contentType.includes("application/json")) {
312
- const body = await res.json();
313
- if (body.url) {
344
+ const body = JSON.parse(bytes.toString("utf8"));
345
+ if (body && typeof body === "object" && Object.keys(body).length === 1 && "url" in body && typeof body.url === "string" && /^https?:\/\//i.test(body.url)) {
314
346
  const fileRes = await fetch(body.url);
315
347
  if (!fileRes.ok)
316
348
  throw new Error(`Failed to download report from URL (${fileRes.status})`);
@@ -318,18 +350,17 @@ class QuillShieldApi {
318
350
  return { bytes: bytes2, contentType: fileRes.headers.get("content-type") ?? contentType, filename: `report-${jobId}.${format}` };
319
351
  }
320
352
  }
321
- const bytes = Buffer.from(await res.arrayBuffer());
322
353
  return { bytes, contentType, filename: `report-${jobId}.${format}` };
323
354
  }
324
355
  streamEvents(jobId, onEvent, onError) {
325
- const url = `${this.cfg.api_url}/v1/audits/${jobId}/events?api_key=${encodeURIComponent(this.cfg.api_key)}`;
356
+ const url = `${this.cfg.api_url}/v1/audits/${jobId}/events`;
326
357
  const controller = new AbortController;
327
358
  let closed = false;
328
359
  (async () => {
329
360
  try {
330
361
  const res = await fetch(url, {
331
362
  method: "GET",
332
- headers: { Accept: "text/event-stream", Authorization: `Bearer ${this.cfg.api_key}` },
363
+ headers: this.headers({ Accept: "text/event-stream" }),
333
364
  signal: controller.signal
334
365
  });
335
366
  if (!res.ok || !res.body) {
@@ -1019,7 +1050,7 @@ var init_esm = __esm(() => {
1019
1050
  });
1020
1051
 
1021
1052
  // src/folder-zip.ts
1022
- import { readdirSync, readFileSync, statSync } from "node:fs";
1053
+ import { readdirSync, readFileSync, lstatSync } from "node:fs";
1023
1054
  import { join as join2, relative, basename, sep } from "node:path";
1024
1055
  function walkDir(dir, base = dir) {
1025
1056
  const results = [];
@@ -1034,7 +1065,7 @@ function walkDir(dir, base = dir) {
1034
1065
  const relPath = relative(base, fullPath).split(sep).join("/");
1035
1066
  let st;
1036
1067
  try {
1037
- st = statSync(fullPath);
1068
+ st = lstatSync(fullPath);
1038
1069
  } catch {
1039
1070
  continue;
1040
1071
  }
@@ -1051,8 +1082,20 @@ function walkDir(dir, base = dir) {
1051
1082
  function zipFolder(folderPath) {
1052
1083
  const files = walkDir(folderPath);
1053
1084
  const zippable = {};
1085
+ let totalBytes = 0;
1054
1086
  for (const [relPath, absPath] of files) {
1055
- zippable[relPath] = new Uint8Array(readFileSync(absPath));
1087
+ const st = lstatSync(absPath);
1088
+ if (!st.isFile())
1089
+ continue;
1090
+ if (totalBytes + st.size > MAX_TOTAL_BYTES) {
1091
+ throw new Error("Folder is too large. The total upload limit is 50 MiB. Remove large files or upload a zip directly.");
1092
+ }
1093
+ const bytes = new Uint8Array(readFileSync(absPath));
1094
+ totalBytes += bytes.length;
1095
+ if (totalBytes > MAX_TOTAL_BYTES) {
1096
+ throw new Error("Folder is too large. The total upload limit is 50 MiB.");
1097
+ }
1098
+ zippable[relPath] = bytes;
1056
1099
  }
1057
1100
  if (Object.keys(zippable).length === 0) {
1058
1101
  throw new Error(`No files found in folder: ${folderPath}`);
@@ -1062,7 +1105,7 @@ function zipFolder(folderPath) {
1062
1105
  function folderName(folderPath) {
1063
1106
  return basename(folderPath);
1064
1107
  }
1065
- var SKIP_DIRS;
1108
+ var SKIP_DIRS, MAX_TOTAL_BYTES;
1066
1109
  var init_folder_zip = __esm(() => {
1067
1110
  init_esm();
1068
1111
  SKIP_DIRS = new Set([
@@ -1084,6 +1127,7 @@ var init_folder_zip = __esm(() => {
1084
1127
  "mock",
1085
1128
  "mocks"
1086
1129
  ]);
1130
+ MAX_TOTAL_BYTES = 50 * 1024 * 1024;
1087
1131
  });
1088
1132
 
1089
1133
  // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v4/core/core.js
@@ -10759,14 +10803,14 @@ function getDotPath(path) {
10759
10803
  if (path.length === 0) {
10760
10804
  return "object root";
10761
10805
  }
10762
- return path.reduce((acc, seg, index) => {
10806
+ return path.reduce((acc, seg2, index) => {
10763
10807
  if (index === 0) {
10764
- return String(seg);
10808
+ return String(seg2);
10765
10809
  }
10766
- if (typeof seg === "number") {
10767
- return `${acc}[${seg}]`;
10810
+ if (typeof seg2 === "number") {
10811
+ return `${acc}[${seg2}]`;
10768
10812
  }
10769
- return `${acc}.${seg}`;
10813
+ return `${acc}.${seg2}`;
10770
10814
  }, "");
10771
10815
  }
10772
10816
  function getParseErrorMessage(error2) {
@@ -17321,8 +17365,8 @@ var require_core = __commonJS((exports) => {
17321
17365
  for (const jsonPointer of keywordsJsonPointers) {
17322
17366
  const segments = jsonPointer.split("/").slice(1);
17323
17367
  let keywords = metaSchema;
17324
- for (const seg of segments)
17325
- keywords = keywords[seg];
17368
+ for (const seg2 of segments)
17369
+ keywords = keywords[seg2];
17326
17370
  for (const key in rules) {
17327
17371
  const rule = rules[key];
17328
17372
  if (typeof rule != "object")
@@ -21047,23 +21091,19 @@ async function requireMcpConfig() {
21047
21091
  const envUrl = process.env.QUILLSHIELD_API_URL;
21048
21092
  const envOrg = process.env.QUILLSHIELD_ORG_ID;
21049
21093
  if (envKey) {
21050
- return {
21051
- api_url: (envUrl || DEFAULT_MCP_API_URL).replace(/\/$/, ""),
21052
- api_key: envKey,
21053
- org_id: envOrg || undefined
21054
- };
21094
+ const api_url = (envUrl || DEFAULT_MCP_API_URL).replace(/\/$/, "");
21095
+ assertSafeApiUrl(api_url);
21096
+ return { api_url, api_key: envKey, org_id: envOrg || undefined };
21055
21097
  }
21056
21098
  const fileCfg = await loadConfig();
21057
21099
  if (fileCfg?.api_key) {
21058
- return {
21059
- api_url: (envUrl || fileCfg.api_url || DEFAULT_MCP_API_URL).replace(/\/$/, ""),
21060
- api_key: fileCfg.api_key,
21061
- org_id: envOrg || fileCfg.org_id
21062
- };
21100
+ const api_url = (envUrl || fileCfg.api_url || DEFAULT_MCP_API_URL).replace(/\/$/, "");
21101
+ assertSafeApiUrl(api_url);
21102
+ return { api_url, api_key: fileCfg.api_key, org_id: envOrg || fileCfg.org_id };
21063
21103
  }
21064
21104
  throw new Error("Not configured. Set QUILLSHIELD_API_KEY (and optional QUILLSHIELD_API_URL) " + "or run `npx @quillaudits/cli init` to save ~/.quillshield/config.json.");
21065
21105
  }
21066
- var DEFAULT_MCP_API_URL = "https://api.quillaudits.ai", TOPUP_URL = "https://shield.quillaudits.com/topup";
21106
+ var DEFAULT_MCP_API_URL = "https://api-production-7027.up.railway.app", TOPUP_URL = "https://shield.quillaudits.com/topup";
21067
21107
  var init_config2 = __esm(() => {
21068
21108
  init_config();
21069
21109
  });
@@ -21098,7 +21138,13 @@ function stderrLog() {
21098
21138
  async function payQuoteWithWalletOnly(api2, quoteId, opts = {}) {
21099
21139
  const log = opts.log ?? stderrLog();
21100
21140
  let quote = await api2.getQuote(quoteId);
21101
- if (opts.coupon) {
21141
+ if (quote.reused_audit_job_id) {
21142
+ log.success(`Existing report reused at no charge: ${quote.reused_audit_job_id}`);
21143
+ return { ok: true, quote, order: null, audit_job_id: quote.reused_audit_job_id };
21144
+ }
21145
+ if (quote.status === "draft")
21146
+ quote = await api2.refreshQuoteWallet(quoteId);
21147
+ if (opts.coupon && quote.status !== "accepted") {
21102
21148
  log.info(`Applying coupon ${opts.coupon}...`);
21103
21149
  quote = await api2.applyCoupon(quoteId, opts.coupon);
21104
21150
  }
@@ -21109,7 +21155,15 @@ async function payQuoteWithWalletOnly(api2, quoteId, opts = {}) {
21109
21155
  return { ok: false, error: confirmRequired(quote) };
21110
21156
  }
21111
21157
  log.info("Creating order (wallet-covered)...");
21112
- let order = await api2.createOrder(quoteId, "stripe");
21158
+ let order;
21159
+ try {
21160
+ order = await api2.createOrder(quoteId, "stripe", true);
21161
+ } catch (err2) {
21162
+ if (!(err2 instanceof ApiClientError) || err2.status !== 402)
21163
+ throw err2;
21164
+ const details = err2.details;
21165
+ return { ok: false, error: walletTopupRequired({ ...quote, final_price_cents: details?.final_price_cents ?? quote.final_price_cents }) };
21166
+ }
21113
21167
  log.success(`Order ${order.id} — ${order.payment_status}`);
21114
21168
  if (order.payment_status !== "paid") {
21115
21169
  order = await api2.getOrder(order.id);
@@ -21175,7 +21229,7 @@ function truncateText(text, max = MD_TRUNCATE) {
21175
21229
  var MD_TRUNCATE = 1e5;
21176
21230
 
21177
21231
  // ../mcp/src/server.ts
21178
- import { readFileSync as readFileSync2, writeFileSync, existsSync, statSync as statSync2 } from "node:fs";
21232
+ import { readFileSync as readFileSync2, writeFileSync, existsSync, statSync } from "node:fs";
21179
21233
  import { basename as basename2, extname, resolve } from "node:path";
21180
21234
  function stderrLog2() {
21181
21235
  return {
@@ -21185,7 +21239,7 @@ function stderrLog2() {
21185
21239
  };
21186
21240
  }
21187
21241
  async function getApi(cfg) {
21188
- return new QuillShieldApi(cfg ?? await requireMcpConfig());
21242
+ return new QuillShieldApi(cfg ?? await requireMcpConfig(), "mcp");
21189
21243
  }
21190
21244
  function toolErr(err2) {
21191
21245
  if (err2 instanceof ApiClientError) {
@@ -21212,7 +21266,7 @@ function createQuillShieldMcpServer(opts) {
21212
21266
  server.registerTool("list_versions", {
21213
21267
  description: "List versions for a project.",
21214
21268
  inputSchema: {
21215
- project_id: exports_external.string().describe("Project id")
21269
+ project_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Project id")
21216
21270
  }
21217
21271
  }, async ({ project_id }) => {
21218
21272
  try {
@@ -21225,7 +21279,7 @@ function createQuillShieldMcpServer(opts) {
21225
21279
  server.registerTool("list_audits", {
21226
21280
  description: "List audit jobs. Optional filters: project_id, status.",
21227
21281
  inputSchema: {
21228
- project_id: exports_external.string().optional().describe("Filter by project id"),
21282
+ project_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").optional().describe("Filter by project id"),
21229
21283
  status: exports_external.string().optional().describe("Filter by job status")
21230
21284
  }
21231
21285
  }, async ({ project_id, status }) => {
@@ -21239,7 +21293,7 @@ function createQuillShieldMcpServer(opts) {
21239
21293
  server.registerTool("get_audit", {
21240
21294
  description: "Get a single audit job by id.",
21241
21295
  inputSchema: {
21242
- job_id: exports_external.string().describe("Audit job id")
21296
+ job_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Audit job id")
21243
21297
  }
21244
21298
  }, async ({ job_id }) => {
21245
21299
  try {
@@ -21252,7 +21306,7 @@ function createQuillShieldMcpServer(opts) {
21252
21306
  server.registerTool("list_findings", {
21253
21307
  description: "List findings for an audit job.",
21254
21308
  inputSchema: {
21255
- job_id: exports_external.string().describe("Audit job id")
21309
+ job_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Audit job id")
21256
21310
  }
21257
21311
  }, async ({ job_id }) => {
21258
21312
  try {
@@ -21263,20 +21317,16 @@ function createQuillShieldMcpServer(opts) {
21263
21317
  }
21264
21318
  });
21265
21319
  server.registerTool("get_report", {
21266
- description: "Fetch the audit report. md/json returned inline (md truncated if huge). pdf returns a URL or writes to out_path.",
21320
+ description: "Fetch the audit report. md/json returned inline (md truncated if huge). pdf returns an embedded PDF resource or writes to out_path.",
21267
21321
  inputSchema: {
21268
- job_id: exports_external.string().describe("Audit job id"),
21322
+ job_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Audit job id"),
21269
21323
  format: exports_external.enum(["md", "json", "pdf"]).optional().describe("Report format (default md)"),
21270
- out_path: exports_external.string().optional().describe("Local path to write the file (useful for pdf)")
21324
+ out_path: exports_external.string().optional().describe("New filename in the current directory (existing files are not overwritten)")
21271
21325
  }
21272
21326
  }, async ({ job_id, format, out_path }) => {
21273
21327
  try {
21274
21328
  const api2 = await resolveApi();
21275
21329
  const fmt = format ?? "md";
21276
- if (fmt === "pdf" && !out_path) {
21277
- const url = await api2.getReportUrl(job_id, "pdf");
21278
- return okJson({ format: "pdf", url });
21279
- }
21280
21330
  const { bytes, contentType, filename } = await api2.downloadReport(job_id, fmt);
21281
21331
  if (out_path) {
21282
21332
  if (out_path !== basename2(out_path)) {
@@ -21286,9 +21336,21 @@ function createQuillShieldMcpServer(opts) {
21286
21336
  });
21287
21337
  }
21288
21338
  const safePath = resolve(process.cwd(), basename2(out_path));
21289
- writeFileSync(safePath, bytes);
21339
+ writeFileSync(safePath, bytes, { flag: "wx", mode: 384 });
21290
21340
  return okJson({ format: fmt, saved_to: safePath, bytes: bytes.length, content_type: contentType });
21291
21341
  }
21342
+ if (fmt === "pdf") {
21343
+ return {
21344
+ content: [{
21345
+ type: "resource",
21346
+ resource: {
21347
+ uri: `quillshield://audits/${encodeURIComponent(job_id)}/report.pdf`,
21348
+ mimeType: "application/pdf",
21349
+ blob: bytes.toString("base64")
21350
+ }
21351
+ }]
21352
+ };
21353
+ }
21292
21354
  if (fmt === "json") {
21293
21355
  return okJson({ format: "json", report: JSON.parse(bytes.toString("utf8")) });
21294
21356
  }
@@ -21321,7 +21383,7 @@ function createQuillShieldMcpServer(opts) {
21321
21383
  server.registerTool("get_order", {
21322
21384
  description: "Get a single order by id.",
21323
21385
  inputSchema: {
21324
- order_id: exports_external.string().describe("Order id")
21386
+ order_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Order id")
21325
21387
  }
21326
21388
  }, async ({ order_id }) => {
21327
21389
  try {
@@ -21334,7 +21396,7 @@ function createQuillShieldMcpServer(opts) {
21334
21396
  server.registerTool("get_quote", {
21335
21397
  description: "Get a price quote by id (full breakdown: base, coupon, wallet applied, due).",
21336
21398
  inputSchema: {
21337
- quote_id: exports_external.string().describe("Quote id")
21399
+ quote_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Quote id")
21338
21400
  }
21339
21401
  }, async ({ quote_id }) => {
21340
21402
  try {
@@ -21347,7 +21409,7 @@ function createQuillShieldMcpServer(opts) {
21347
21409
  server.registerTool("create_quote", {
21348
21410
  description: "Create a full-audit price quote for a project version (same as dashboard checkout).",
21349
21411
  inputSchema: {
21350
- project_version_id: exports_external.string().describe("Project version id")
21412
+ project_version_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Project version id")
21351
21413
  }
21352
21414
  }, async ({ project_version_id }) => {
21353
21415
  try {
@@ -21360,7 +21422,7 @@ function createQuillShieldMcpServer(opts) {
21360
21422
  server.registerTool("apply_coupon", {
21361
21423
  description: "Apply a coupon code to a quote (same as frontend checkout).",
21362
21424
  inputSchema: {
21363
- quote_id: exports_external.string().describe("Quote id"),
21425
+ quote_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Quote id"),
21364
21426
  coupon_code: exports_external.string().describe("Coupon code")
21365
21427
  }
21366
21428
  }, async ({ quote_id, coupon_code }) => {
@@ -21374,7 +21436,7 @@ function createQuillShieldMcpServer(opts) {
21374
21436
  server.registerTool("remove_coupon", {
21375
21437
  description: "Remove the coupon from a quote.",
21376
21438
  inputSchema: {
21377
- quote_id: exports_external.string().describe("Quote id")
21439
+ quote_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Quote id")
21378
21440
  }
21379
21441
  }, async ({ quote_id }) => {
21380
21442
  try {
@@ -21420,7 +21482,7 @@ function createQuillShieldMcpServer(opts) {
21420
21482
  });
21421
21483
  } else if (args.dir_path) {
21422
21484
  const dir = resolve(args.dir_path);
21423
- if (!existsSync(dir) || !statSync2(dir).isDirectory()) {
21485
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) {
21424
21486
  return errJson({ code: "invalid_input", message: `Not a directory: ${dir}` });
21425
21487
  }
21426
21488
  log.info(`Zipping ${dir}...`);
@@ -21445,7 +21507,7 @@ function createQuillShieldMcpServer(opts) {
21445
21507
  message: `zip_path must be a .zip or .sol file, got "${ext || "no extension"}"`
21446
21508
  });
21447
21509
  }
21448
- const st = statSync2(path);
21510
+ const st = statSync(path);
21449
21511
  const MAX_UPLOAD_BYTES = 50 * 1024 * 1024;
21450
21512
  if (st.size > MAX_UPLOAD_BYTES) {
21451
21513
  return errJson({
@@ -21505,7 +21567,7 @@ function createQuillShieldMcpServer(opts) {
21505
21567
  server.registerTool("pay_quote", {
21506
21568
  description: "Pay a quote and start the audit using wallet credits only (same finalizeCheckout as the frontend). " + "If anything is still due after coupons/wallet, returns wallet_topup_required — top up in the dashboard, do not Stripe from MCP. " + "Requires confirm:true when the quote is $0 due (spends prepaid/refund/bonus).",
21507
21569
  inputSchema: {
21508
- quote_id: exports_external.string().describe("Quote id"),
21570
+ quote_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Quote id"),
21509
21571
  coupon: exports_external.string().optional().describe("Optional coupon to apply first"),
21510
21572
  confirm: exports_external.boolean().optional().describe("Must be true to create the order and spend wallet credits")
21511
21573
  }
@@ -21532,7 +21594,7 @@ function createQuillShieldMcpServer(opts) {
21532
21594
  server.registerTool("start_audit", {
21533
21595
  description: "Retry starting an audit for an order that is already paid (idempotent start-audit).",
21534
21596
  inputSchema: {
21535
- order_id: exports_external.string().describe("Paid order id")
21597
+ order_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Paid order id")
21536
21598
  }
21537
21599
  }, async ({ order_id }) => {
21538
21600
  try {
@@ -21558,7 +21620,7 @@ function createQuillShieldMcpServer(opts) {
21558
21620
  server.registerTool("cancel_audit", {
21559
21621
  description: "Cancel a running audit job.",
21560
21622
  inputSchema: {
21561
- job_id: exports_external.string().describe("Audit job id")
21623
+ job_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Audit job id")
21562
21624
  }
21563
21625
  }, async ({ job_id }) => {
21564
21626
  try {
@@ -21572,7 +21634,7 @@ function createQuillShieldMcpServer(opts) {
21572
21634
  server.registerTool("watch_audit", {
21573
21635
  description: "Poll audit status for up to ~20 seconds. Call again to continue watching; does not hang the MCP session.",
21574
21636
  inputSchema: {
21575
- job_id: exports_external.string().describe("Audit job id"),
21637
+ job_id: exports_external.string().regex(ULID_RE, "must be an id as returned by the API").describe("Audit job id"),
21576
21638
  timeout_ms: exports_external.number().optional().describe(`Max wait in ms (capped at ${WATCH_CAP_MS})`)
21577
21639
  }
21578
21640
  }, async ({ job_id, timeout_ms }) => {
@@ -21583,14 +21645,15 @@ function createQuillShieldMcpServer(opts) {
21583
21645
  const deadline = Date.now() + cap;
21584
21646
  let job = await api2.getAudit(job_id);
21585
21647
  const terminal = new Set(["completed", "failed", "cancelled", "canceled"]);
21586
- while (Date.now() < deadline && !terminal.has(String(job.status))) {
21648
+ const settled = (status) => terminal.has(String(status)) || status === "paused";
21649
+ while (Date.now() < deadline && !settled(job.status)) {
21587
21650
  await sleep2(2000);
21588
21651
  job = await api2.getAudit(job_id);
21589
21652
  }
21590
21653
  return okJson({
21591
21654
  job,
21592
- timed_out: !terminal.has(String(job.status)),
21593
- hint: terminal.has(String(job.status)) ? undefined : "Still running — call watch_audit again to continue."
21655
+ timed_out: !settled(job.status),
21656
+ hint: job.status === "paused" ? "Paused: the AI this audit runs on stopped (see job.pause). Finished work is saved; resume it from the dashboard." : terminal.has(String(job.status)) ? undefined : "Still running — call watch_audit again to continue."
21594
21657
  });
21595
21658
  } catch (err2) {
21596
21659
  return toolErr(err2);
@@ -21601,7 +21664,7 @@ function createQuillShieldMcpServer(opts) {
21601
21664
  function sleep2(ms) {
21602
21665
  return new Promise((r) => setTimeout(r, ms));
21603
21666
  }
21604
- var WATCH_CAP_MS = 20000;
21667
+ var ULID_RE, WATCH_CAP_MS = 20000;
21605
21668
  var init_server3 = __esm(() => {
21606
21669
  init_mcp();
21607
21670
  init_zod();
@@ -21610,6 +21673,7 @@ var init_server3 = __esm(() => {
21610
21673
  init_esm();
21611
21674
  init_config2();
21612
21675
  init_wallet_pay();
21676
+ ULID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
21613
21677
  });
21614
21678
 
21615
21679
  // ../mcp/src/run.ts
@@ -21637,7 +21701,7 @@ var init_mcp2 = __esm(() => {
21637
21701
  init_config();
21638
21702
  init_api();
21639
21703
  import { parseArgs } from "node:util";
21640
- import { readFileSync as readFileSync3, existsSync as existsSync2, statSync as statSync3, writeFileSync as writeFileSync2 } from "node:fs";
21704
+ import { readFileSync as readFileSync3, existsSync as existsSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
21641
21705
  import { basename as basename3, resolve as resolve2 } from "node:path";
21642
21706
  import { createInterface } from "node:readline";
21643
21707
 
@@ -21655,7 +21719,7 @@ function defaultLog() {
21655
21719
  function printQuote(quote) {
21656
21720
  console.log();
21657
21721
  console.log(` Quote ${quote.id}`);
21658
- console.log(` Tier ${quote.tier_label} (${quote.bloc_total} BLOC)`);
21722
+ console.log(` Tier ${quote.tier_label} (${quote.bloc_total} BLoC)`);
21659
21723
  console.log(` Base ${formatUsd(quote.base_price_cents)}`);
21660
21724
  if (quote.coupon_discount_cents > 0) {
21661
21725
  console.log(` Coupon -${formatUsd(quote.coupon_discount_cents)}${quote.coupon_code ? ` (${quote.coupon_code})` : ""}`);
@@ -21699,7 +21763,11 @@ async function payQuoteAndStartAudit(api, quoteId, opts = {}) {
21699
21763
  const method = opts.method ?? "stripe";
21700
21764
  const timeoutMs = opts.timeoutMs ?? 10 * 60 * 1000;
21701
21765
  let quote = await api.getQuote(quoteId);
21702
- if (opts.coupon) {
21766
+ if (quote.reused_audit_job_id) {
21767
+ log.success(`Unchanged audit inputs — report ${quote.reused_audit_job_id} reused at no charge.`);
21768
+ return { quote, order: null, audit_job_id: quote.reused_audit_job_id };
21769
+ }
21770
+ if (opts.coupon && quote.status !== "accepted") {
21703
21771
  log.info(`Applying coupon ${opts.coupon}...`);
21704
21772
  quote = await api.applyCoupon(quoteId, opts.coupon);
21705
21773
  }
@@ -21719,48 +21787,49 @@ async function payQuoteAndStartAudit(api, quoteId, opts = {}) {
21719
21787
  log.success("Order already paid (covered by credits / $0).");
21720
21788
  } else if (isMock) {
21721
21789
  log.info("Mock payments enabled — confirming payment...");
21722
- const mock = await api.mockConfirmPayment(order.id);
21723
- order = await api.getOrder(order.id);
21724
- log.success(`Mock payment ${mock.order.payment_status}`);
21790
+ order = await api.confirmStripePayment(order.id);
21791
+ log.success(`Mock payment ${order.payment_status}`);
21725
21792
  } else {
21726
21793
  if (!order.stripe_checkout_url) {
21727
21794
  log.info("Refreshing checkout session...");
21728
21795
  order = await api.refreshCheckoutSession(order.id);
21729
21796
  }
21730
- const url = selectCheckoutUrl(order);
21731
- if (!url) {
21732
- throw new Error("No Stripe checkout URL available for this order");
21733
- }
21734
- if (url.startsWith("mock://")) {
21735
- throw new Error("Received mock checkout URL but stripe_mock is false — check API config");
21736
- }
21737
- console.log(` Checkout URL: ${url}`);
21738
- const doOpen = opts.open === true || opts.open !== false && !opts.noOpen && process.stdin.isTTY;
21739
- if (doOpen) {
21740
- log.info("Opening browser for payment...");
21741
- await openBrowser(url);
21742
- } else {
21743
- log.warn("Open the checkout URL in a browser to complete payment.");
21744
- }
21745
- log.info("Waiting for payment...");
21746
- const deadline = Date.now() + timeoutMs;
21747
- while (Date.now() < deadline) {
21748
- try {
21749
- order = await api.confirmStripePayment(order.id);
21750
- } catch {
21751
- order = await api.getOrder(order.id);
21797
+ if (order.payment_status !== "paid") {
21798
+ const url = selectCheckoutUrl(order);
21799
+ if (!url) {
21800
+ throw new Error("No Stripe checkout URL available for this order");
21801
+ }
21802
+ if (!url.startsWith("https://")) {
21803
+ throw new Error("Invalid Stripe checkout URL");
21804
+ }
21805
+ console.log(` Checkout URL: ${url}`);
21806
+ const doOpen = opts.open === true || opts.open !== false && !opts.noOpen && process.stdin.isTTY;
21807
+ if (doOpen) {
21808
+ log.info("Opening browser for payment...");
21809
+ await openBrowser(url);
21810
+ } else {
21811
+ log.warn("Open the checkout URL in a browser to complete payment.");
21752
21812
  }
21753
- if (order.payment_status === "paid")
21754
- break;
21755
- if (order.payment_status === "failed" || order.payment_status === "cancelled") {
21756
- throw new Error(`Payment ${order.payment_status}`);
21813
+ log.info("Waiting for payment...");
21814
+ const deadline = Date.now() + timeoutMs;
21815
+ while (Date.now() < deadline) {
21816
+ try {
21817
+ order = await api.confirmStripePayment(order.id);
21818
+ } catch {
21819
+ order = await api.getOrder(order.id);
21820
+ }
21821
+ if (order.payment_status === "paid")
21822
+ break;
21823
+ if (order.payment_status === "failed" || order.payment_status === "cancelled" || order.payment_status === "refunded") {
21824
+ throw new Error(`Payment ${order.payment_status}`);
21825
+ }
21826
+ await sleep(3000);
21757
21827
  }
21758
- await sleep(3000);
21759
- }
21760
- if (order.payment_status !== "paid") {
21761
- throw new Error(`Timed out waiting for payment (status: ${order.payment_status})`);
21828
+ if (order.payment_status !== "paid") {
21829
+ throw new Error(`Timed out waiting for payment (status: ${order.payment_status})`);
21830
+ }
21831
+ log.success("Payment confirmed");
21762
21832
  }
21763
- log.success("Payment confirmed");
21764
21833
  }
21765
21834
  order = await api.getOrder(order.id);
21766
21835
  let jobId = order.audit_job_id;
@@ -21778,41 +21847,46 @@ async function payQuoteAndStartAudit(api, quoteId, opts = {}) {
21778
21847
  async function payWalletTopup(api, amountCents, opts = {}) {
21779
21848
  const log = opts.log ?? defaultLog();
21780
21849
  const timeoutMs = opts.timeoutMs ?? 10 * 60 * 1000;
21781
- log.info(`Creating top-up for ${formatUsd(amountCents)}...`);
21782
- let topup = await api.createWalletTopup(amountCents);
21850
+ const method = opts.method === "crypto" ? "crypto" : "stripe";
21783
21851
  const cfg = await api.getConfig().catch(() => ({ stripe_mock: false, crypto_enabled: false }));
21852
+ if (method === "crypto" && !cfg.crypto_enabled) {
21853
+ throw new Error("Crypto payments are not configured.");
21854
+ }
21855
+ log.info(`Creating ${method} top-up for ${formatUsd(amountCents)}...`);
21856
+ let topup = await api.createWalletTopup(amountCents, method);
21784
21857
  if (cfg.stripe_mock) {
21785
21858
  log.info("Mock payments enabled — confirming top-up...");
21786
- await api.mockConfirmTopup(topup.id);
21787
- topup = await api.getWalletTopup(topup.id);
21859
+ topup = await api.confirmWalletTopupPayment(topup.id);
21788
21860
  } else {
21789
21861
  if (!topup.stripe_checkout_url) {
21790
21862
  topup = await api.refreshWalletTopupCheckoutSession(topup.id);
21791
21863
  }
21792
- const url = topup.stripe_checkout_url;
21793
- if (!url)
21794
- throw new Error("No Stripe checkout URL for top-up");
21795
- console.log(` Checkout URL: ${url}`);
21796
- const doOpen = opts.open === true || opts.open !== false && !opts.noOpen && process.stdin.isTTY;
21797
- if (doOpen)
21798
- await openBrowser(url);
21799
- log.info("Waiting for top-up payment...");
21800
- const deadline = Date.now() + timeoutMs;
21801
- while (Date.now() < deadline) {
21802
- try {
21803
- topup = await api.confirmWalletTopupPayment(topup.id);
21804
- } catch {
21805
- topup = await api.getWalletTopup(topup.id);
21864
+ if (topup.payment_status !== "paid") {
21865
+ const url = topup.stripe_checkout_url;
21866
+ if (!url || !url.startsWith("https://"))
21867
+ throw new Error("No valid Stripe checkout URL for top-up");
21868
+ console.log(` Checkout URL: ${url}`);
21869
+ const doOpen = opts.open === true || opts.open !== false && !opts.noOpen && process.stdin.isTTY;
21870
+ if (doOpen)
21871
+ await openBrowser(url);
21872
+ log.info("Waiting for top-up payment...");
21873
+ const deadline = Date.now() + timeoutMs;
21874
+ while (Date.now() < deadline) {
21875
+ try {
21876
+ topup = await api.confirmWalletTopupPayment(topup.id);
21877
+ } catch {
21878
+ topup = await api.getWalletTopup(topup.id);
21879
+ }
21880
+ if (topup.payment_status === "paid")
21881
+ break;
21882
+ if (topup.payment_status === "failed" || topup.payment_status === "cancelled" || topup.payment_status === "refunded") {
21883
+ throw new Error(`Top-up ${topup.payment_status}`);
21884
+ }
21885
+ await sleep(3000);
21806
21886
  }
21807
- if (topup.payment_status === "paid")
21808
- break;
21809
- if (topup.payment_status === "failed" || topup.payment_status === "cancelled") {
21810
- throw new Error(`Top-up ${topup.payment_status}`);
21887
+ if (topup.payment_status !== "paid") {
21888
+ throw new Error(`Timed out waiting for top-up (status: ${topup.payment_status})`);
21811
21889
  }
21812
- await sleep(3000);
21813
- }
21814
- if (topup.payment_status !== "paid") {
21815
- throw new Error(`Timed out waiting for top-up (status: ${topup.payment_status})`);
21816
21890
  }
21817
21891
  }
21818
21892
  log.success(`Top-up ${topup.id} paid`);
@@ -21833,17 +21907,20 @@ var CYAN = "\x1B[36m";
21833
21907
  var BRAND2 = "\x1B[38;2;16;61;211m";
21834
21908
  var SKY = "\x1B[38;2;40;198;255m";
21835
21909
  var RESET = "\x1B[0m";
21910
+ function term(value) {
21911
+ return String(value ?? "").replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, (c) => `\\x${c.charCodeAt(0).toString(16).padStart(2, "0")}`);
21912
+ }
21836
21913
  function info(msg) {
21837
- console.log(`${BRAND2}●${RESET} ${msg}`);
21914
+ console.log(`${BRAND2}●${RESET} ${term(msg)}`);
21838
21915
  }
21839
21916
  function success(msg) {
21840
- console.log(`${GREEN}✓${RESET} ${msg}`);
21917
+ console.log(`${GREEN}✓${RESET} ${term(msg)}`);
21841
21918
  }
21842
21919
  function warn(msg) {
21843
- console.log(`${YELLOW}⚠${RESET} ${msg}`);
21920
+ console.log(`${YELLOW}⚠${RESET} ${term(msg)}`);
21844
21921
  }
21845
21922
  function fail(msg) {
21846
- console.error(`${RED}✗${RESET} ${msg}`);
21923
+ console.error(`${RED}✗${RESET} ${term(msg)}`);
21847
21924
  }
21848
21925
  var cliLog = { info, success, warn };
21849
21926
  function printHelp() {
@@ -21874,6 +21951,7 @@ ${BOLD}COMMANDS${RESET}
21874
21951
 
21875
21952
  ${BOLD}wallet${RESET} Show wallet balances
21876
21953
  ${BOLD}topup${RESET} <amount> Top up wallet (dollars, e.g. 50 or 50.00)
21954
+ --method <stripe|crypto> Payment method (default: stripe)
21877
21955
  --yes --no-open --open
21878
21956
  ${BOLD}orders${RESET} List recent orders
21879
21957
  ${BOLD}order${RESET} <order-id> Show an order
@@ -21887,6 +21965,7 @@ ${BOLD}COMMANDS${RESET}
21887
21965
 
21888
21966
  ${BOLD}projects${RESET} List projects
21889
21967
  ${BOLD}versions${RESET} <project-id> List versions
21968
+ ${BOLD}workflows${RESET} List workflows (audits use your org default)
21890
21969
  ${BOLD}mcp${RESET} Start Cursor/Claude MCP server (stdio)
21891
21970
  ${BOLD}cancel${RESET} <job-id> Cancel a running audit
21892
21971
  ${BOLD}logout${RESET} Clear stored credentials
@@ -21899,6 +21978,7 @@ ${BOLD}EXAMPLES${RESET}
21899
21978
  qs quote 01KXK... && qs pay 01KXK... --yes --watch
21900
21979
  qs wallet
21901
21980
  qs topup 50 --yes
21981
+ qs topup 50 --method crypto --yes
21902
21982
  `);
21903
21983
  }
21904
21984
  async function promptConfirm(message) {
@@ -21926,6 +22006,12 @@ async function cmdInit() {
21926
22006
  process.stdout.write(`API URL [${DEFAULT_API_URL}]: `);
21927
22007
  const apiUrl = await readLine();
21928
22008
  const finalUrl = apiUrl.trim() || DEFAULT_API_URL;
22009
+ try {
22010
+ assertSafeApiUrl(finalUrl);
22011
+ } catch (err2) {
22012
+ fail(err2.message);
22013
+ process.exit(1);
22014
+ }
21929
22015
  process.stdout.write("API Key (qs_live_...): ");
21930
22016
  const apiKey = await readLine();
21931
22017
  if (!apiKey.trim()) {
@@ -22009,7 +22095,7 @@ async function cmdAudit(args) {
22009
22095
  fail(`Folder not found: ${dirPath}`);
22010
22096
  process.exit(1);
22011
22097
  }
22012
- if (!statSync3(dirPath).isDirectory()) {
22098
+ if (!statSync2(dirPath).isDirectory()) {
22013
22099
  fail(`Path is not a directory: ${dirPath}`);
22014
22100
  process.exit(1);
22015
22101
  }
@@ -22042,13 +22128,13 @@ async function cmdAudit(args) {
22042
22128
  console.log();
22043
22129
  success("Project prepared — payment required to start audit");
22044
22130
  console.log();
22045
- console.log(` ${BOLD}Project${RESET} ${handoff.project.name} (${handoff.project.id})`);
22131
+ console.log(` ${BOLD}Project${RESET} ${term(handoff.project.name)} (${term(handoff.project.id)})`);
22046
22132
  console.log(` ${BOLD}Version${RESET} ${handoff.version.id}`);
22047
- console.log(` ${BOLD}SLOC${RESET} ${handoff.version.sloc ?? "?"}`);
22133
+ console.log(` ${BOLD}BLoC${RESET} ${handoff.version.sloc ?? "?"}`);
22048
22134
  console.log(` ${BOLD}Scope${RESET} ${handoff.scope.file_count} file(s)`);
22049
22135
  if (handoff.scope.files?.length) {
22050
22136
  for (const f of handoff.scope.files.slice(0, 20)) {
22051
- console.log(` ${DIM}${f}${RESET}`);
22137
+ console.log(` ${DIM}${term(f)}${RESET}`);
22052
22138
  }
22053
22139
  if (handoff.scope.total_files > handoff.scope.files.length) {
22054
22140
  console.log(` ${DIM}... and ${handoff.scope.total_files - handoff.scope.files.length} more${RESET}`);
@@ -22090,6 +22176,10 @@ async function cmdQuote(args) {
22090
22176
  const quote = await api2.createQuote(versionId);
22091
22177
  success(`Quote ${quote.id}`);
22092
22178
  printQuote(quote);
22179
+ if (quote.reused_audit_job_id) {
22180
+ success(`Existing report reused at no charge: ${quote.reused_audit_job_id}`);
22181
+ return;
22182
+ }
22093
22183
  console.log(` Pay with: ${DIM}qs pay ${quote.id} --yes${RESET}`);
22094
22184
  }
22095
22185
  async function cmdPay(args) {
@@ -22144,7 +22234,8 @@ async function cmdTopup(args) {
22144
22234
  options: {
22145
22235
  yes: { type: "boolean", default: false },
22146
22236
  "no-open": { type: "boolean", default: false },
22147
- open: { type: "boolean", default: false }
22237
+ open: { type: "boolean", default: false },
22238
+ method: { type: "string", default: "stripe" }
22148
22239
  },
22149
22240
  allowPositionals: true
22150
22241
  });
@@ -22159,6 +22250,7 @@ async function cmdTopup(args) {
22159
22250
  process.exit(1);
22160
22251
  }
22161
22252
  const amountCents = Math.round(dollars * 100);
22253
+ const method = values.method === "crypto" ? "crypto" : "stripe";
22162
22254
  if (!values.yes) {
22163
22255
  const ok = await confirmChargeIfNeeded({ final_price_cents: amountCents }, false);
22164
22256
  if (!ok)
@@ -22168,6 +22260,7 @@ async function cmdTopup(args) {
22168
22260
  yes: values.yes,
22169
22261
  noOpen: values["no-open"],
22170
22262
  open: values.open,
22263
+ method,
22171
22264
  log: cliLog
22172
22265
  });
22173
22266
  await cmdWallet();
@@ -22256,6 +22349,10 @@ Job already ${colorStatus(job.status)}.`);
22256
22349
  }
22257
22350
  return;
22258
22351
  }
22352
+ if (job.status === "paused") {
22353
+ printPaused(job);
22354
+ return;
22355
+ }
22259
22356
  info("Connecting to live stream...");
22260
22357
  const done = new Promise((resolveDone) => {
22261
22358
  let stream = api2.streamEvents(jobId, (event, data) => {
@@ -22266,13 +22363,17 @@ Job already ${colorStatus(job.status)}.`);
22266
22363
  stream.close();
22267
22364
  resolveDone();
22268
22365
  }
22366
+ if (data.status === "paused") {
22367
+ stream.close();
22368
+ api2.getAudit(jobId).then(printPaused, () => printPaused({})).finally(resolveDone);
22369
+ }
22269
22370
  break;
22270
22371
  case "phase":
22271
- console.log(` [phase] ${data.phase} (${data.pct}%)`);
22372
+ console.log(` [phase] ${term(data.phase)} (${Number(data.pct)}%)`);
22272
22373
  break;
22273
22374
  case "log": {
22274
22375
  const prefix = data.level === "error" ? RED : data.level === "warn" ? YELLOW : DIM;
22275
- console.log(` [log] ${prefix}${data.message}${RESET}`);
22376
+ console.log(` [log] ${prefix}${term(data.message)}${RESET}`);
22276
22377
  break;
22277
22378
  }
22278
22379
  case "finding": {
@@ -22311,6 +22412,11 @@ ${BOLD}Job ${job.status}.${RESET}`);
22311
22412
  resolveDone();
22312
22413
  return;
22313
22414
  }
22415
+ if (job.status === "paused") {
22416
+ printPaused(job);
22417
+ resolveDone();
22418
+ return;
22419
+ }
22314
22420
  if (job.progress) {
22315
22421
  console.log(` [poll] ${job.progress.phase} (${job.progress.pct}%)`);
22316
22422
  }
@@ -22341,14 +22447,14 @@ async function cmdFindings(args) {
22341
22447
  const sev = (f.severity ?? "info").toUpperCase();
22342
22448
  const sevColor = sev === "CRITICAL" ? RED : sev === "HIGH" ? YELLOW : sev === "MEDIUM" ? CYAN : DIM;
22343
22449
  const status = f.status ? ` ${DIM}[${f.status}]${RESET}` : "";
22344
- console.log(` ${sevColor}[${sev}]${RESET} ${BOLD}${f.title}${RESET}${status}`);
22450
+ console.log(` ${sevColor}[${term(sev)}]${RESET} ${BOLD}${term(f.title)}${RESET}${term(status)}`);
22345
22451
  if (f.file) {
22346
22452
  const loc = f.line ? `${f.file}:${f.line}` : f.file;
22347
- console.log(` ${DIM}${loc}${RESET}`);
22453
+ console.log(` ${DIM}${term(loc)}${RESET}`);
22348
22454
  }
22349
22455
  if (f.description) {
22350
22456
  const desc = f.description.length > 120 ? f.description.slice(0, 117) + "..." : f.description;
22351
- console.log(` ${desc}`);
22457
+ console.log(` ${term(desc)}`);
22352
22458
  }
22353
22459
  console.log();
22354
22460
  }
@@ -22391,6 +22497,29 @@ async function cmdProjects() {
22391
22497
  console.log(` ${DIM}${p.source_type} · ${p.repo_url ?? "upload"} · ${p.created_at}${RESET}`);
22392
22498
  }
22393
22499
  }
22500
+ async function cmdWorkflows() {
22501
+ const cfg = await requireConfig();
22502
+ const api2 = new QuillShieldApi(cfg);
22503
+ const workflows = await api2.listWorkflows().catch((err2) => {
22504
+ if (err2 instanceof ApiClientError && err2.status === 404) {
22505
+ console.log("Workflow Studio is not enabled on this QuillShield deployment.");
22506
+ return null;
22507
+ }
22508
+ throw err2;
22509
+ });
22510
+ if (!workflows)
22511
+ return;
22512
+ console.log(`${BOLD}Workflows (${workflows.length})${RESET}
22513
+ `);
22514
+ for (const w of workflows) {
22515
+ const marks = [w.is_default ? "default" : null, w.official ? "official" : null, w.is_owner ? "yours" : w.installed ? "installed" : null].filter(Boolean).join(", ");
22516
+ console.log(` ${SKY}${w.id}${RESET} ${w.name}${marks ? ` ${DIM}(${marks})${RESET}` : ""}`);
22517
+ if (w.summary)
22518
+ console.log(` ${DIM}${w.summary}${RESET}`);
22519
+ }
22520
+ console.log(`
22521
+ ${DIM}Audits started from the CLI run your organization's default workflow. Change it in the dashboard (Workflows → Make default).${RESET}`);
22522
+ }
22394
22523
  async function cmdVersions(args) {
22395
22524
  const cfg = await requireConfig();
22396
22525
  const api2 = new QuillShieldApi(cfg);
@@ -22407,7 +22536,7 @@ async function cmdVersions(args) {
22407
22536
  console.log(`${BOLD}Versions (${versions2.length})${RESET}
22408
22537
  `);
22409
22538
  for (const v of versions2) {
22410
- console.log(` ${SKY}${v.id}${RESET} SLOC: ${v.sloc ?? "?"} deps: ${v.dependency_count ?? 0}`);
22539
+ console.log(` ${SKY}${v.id}${RESET} BLoC: ${v.sloc ?? "?"} deps: ${v.dependency_count ?? 0}`);
22411
22540
  if (v.commit_sha)
22412
22541
  console.log(` ${DIM}commit: ${v.commit_sha.slice(0, 7)}${RESET}`);
22413
22542
  console.log(` ${DIM}${v.created_at}${RESET}`);
@@ -22459,11 +22588,19 @@ async function readLine() {
22459
22588
  process.stdin.on("end", onEnd);
22460
22589
  });
22461
22590
  }
22591
+ function printPaused(job) {
22592
+ console.log(`
22593
+ ${BOLD}Job ${colorStatus("paused")}${BOLD}.${RESET} ${job.pause?.message ?? "The AI it runs on stopped."}`);
22594
+ if (job.pause?.completed_tasks != null)
22595
+ console.log(` ${job.pause.completed_tasks} finished tasks are saved.`);
22596
+ console.log(` Resume it from the dashboard${job.pause?.expires_at ? ` before ${job.pause.expires_at}` : ""}; otherwise it is stopped and refunded.`);
22597
+ }
22462
22598
  function colorStatus(status) {
22463
22599
  const colors = {
22464
22600
  queued: SKY,
22465
22601
  building: YELLOW,
22466
22602
  running: YELLOW,
22603
+ paused: YELLOW,
22467
22604
  completed: GREEN,
22468
22605
  failed: RED,
22469
22606
  cancelled: DIM
@@ -22523,6 +22660,9 @@ async function main() {
22523
22660
  case "versions":
22524
22661
  await cmdVersions(rest);
22525
22662
  break;
22663
+ case "workflows":
22664
+ await cmdWorkflows();
22665
+ break;
22526
22666
  case "mcp": {
22527
22667
  const { runMcpStdio: runMcpStdio2 } = await Promise.resolve().then(() => (init_mcp2(), exports_mcp));
22528
22668
  await runMcpStdio2();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@quillaudits/cli",
3
- "version": "0.2.2",
4
- "description": "QuillAudits CLI — paid audit workflow from the command line",
3
+ "version": "0.2.3",
4
+ "description": "QuillShield CLI: run AI smart contract audits of Solidity projects from the terminal, follow findings and download reports",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -15,8 +15,11 @@
15
15
  "quillshield",
16
16
  "solidity",
17
17
  "smart-contract",
18
+ "smart-contract-security",
18
19
  "audit",
20
+ "ai-audit",
19
21
  "security",
22
+ "foundry",
20
23
  "cli"
21
24
  ],
22
25
  "bin": {