irida 0.0.0-stage → 0.1.1

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/src/index.js ADDED
@@ -0,0 +1,139 @@
1
+ // Irida SDK: open a metered session, exec commands in it, stop it to get a signed receipt.
2
+ //
3
+ // const session = await irida.open({ worker: "python", seconds: 600 });
4
+ // const out = await session.exec("python main.py");
5
+ // const receipt = await session.stop();
6
+ //
7
+ // This release runs in local mode: the worker is your own machine and the node key is a local ed25519 key.
8
+ // Seconds are metered and receipts are signed for real; no money moves (settlement is "local").
9
+ import { spawn } from "node:child_process";
10
+ import { randomBytes, createHash } from "node:crypto";
11
+ import { mkdirSync, writeFileSync, readdirSync, readFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { nodeKey, signReceipt, verifyReceipt, home } from "./receipt.js";
14
+
15
+ export { verifyReceipt, canonical } from "./receipt.js";
16
+ export { client as cloud, DEFAULT_CLOUD, SCAN, scanUrl } from "./cloud.js";
17
+ import { client as cloudClient } from "./cloud.js";
18
+
19
+ export const DEFAULT_RATE = "0.0004"; // USDG per second
20
+ const DEC = 6; // USDG has 6 decimals; all money maths is done in integer micro-units
21
+
22
+ export function toMicro(s) {
23
+ const str = String(s).trim();
24
+ if (!/^\d+(\.\d+)?$/.test(str)) throw new Error(`not an amount: ${s}`);
25
+ const [i, f = ""] = str.split(".");
26
+ if (f.length > DEC) throw new Error(`more than ${DEC} decimals: ${s}`);
27
+ return BigInt(i) * 10n ** BigInt(DEC) + BigInt(f.padEnd(DEC, "0"));
28
+ }
29
+ export function fromMicro(m, places = 4) {
30
+ const neg = m < 0n; if (neg) m = -m;
31
+ const s = (m / 10n ** BigInt(DEC)).toString() + "." + (m % 10n ** BigInt(DEC)).toString().padStart(DEC, "0");
32
+ return (neg ? "-" : "") + s.slice(0, s.indexOf(".") + 1 + places);
33
+ }
34
+
35
+ // Billing is per started second: 1.2 s of wall clock is 2 seconds.
36
+ export const billedSeconds = (ms) => Math.max(1, Math.ceil(ms / 1000));
37
+
38
+ export function quote(seconds, rate = DEFAULT_RATE) {
39
+ return fromMicro(BigInt(seconds) * toMicro(rate), 6);
40
+ }
41
+
42
+ // open({ cloud: "https://…" }) (or IRIDA_CLOUD set) runs in an Irida Cloud sandbox; otherwise local mode.
43
+ export async function open(opts = {}) {
44
+ const url = opts.cloud === true ? undefined : opts.cloud;
45
+ if (opts.cloud || (process.env.IRIDA_CLOUD && opts.cloud !== false)) return cloudClient(url, { dir: opts.dir }).open(opts);
46
+ return openLocal(opts);
47
+ }
48
+
49
+ async function openLocal({ worker = "local", seconds, budget, rate = DEFAULT_RATE, dir = home(), onTick } = {}) {
50
+ const rateM = toMicro(rate);
51
+ if (rateM <= 0n) throw new Error("rate must be above zero");
52
+ // A budget caps the session; `seconds` is the same cap expressed in time.
53
+ let budgetM = budget != null ? toMicro(budget) : seconds != null ? BigInt(seconds) * rateM : toMicro("2");
54
+ const maxSeconds = Number(budgetM / rateM);
55
+ if (maxSeconds < 1) throw new Error("budget does not cover a single second at this rate");
56
+
57
+ const key = nodeKey(dir);
58
+ const id = "0x" + randomBytes(32).toString("hex");
59
+ const opened = Date.now();
60
+ let usedMs = 0, running = null, stopped = null, exhausted = false;
61
+ const outHash = createHash("sha256");
62
+ const execs = [];
63
+
64
+ const left = () => maxSeconds * 1000 - usedMs;
65
+
66
+ const session = {
67
+ id, worker, rate: fromMicro(rateM, 6), budget: fromMicro(budgetM, 6), maxSeconds, node: key.id,
68
+ get seconds() { return usedMs ? billedSeconds(usedMs) : 0; },
69
+ get exhausted() { return exhausted; },
70
+ cost: (s) => fromMicro(BigInt(s) * rateM, 4),
71
+
72
+ // Runs a command (a shell string, or [cmd, ...args]) and resolves with { code, signal, stdout, stderr }.
73
+ // stdio: "pipe" collects output, "inherit-tee" streams it to this process too.
74
+ exec(cmd, { stdio = "pipe", onData } = {}) {
75
+ if (stopped) return Promise.reject(new Error("session is stopped"));
76
+ if (running) return Promise.reject(new Error("one command at a time per session"));
77
+ if (left() <= 0) return Promise.reject(new Error("budget exhausted"));
78
+ const [file, args, shell] = Array.isArray(cmd) ? [cmd[0], cmd.slice(1), false] : [cmd, [], true];
79
+ const child = spawn(file, args, { shell, stdio: ["inherit", "pipe", "pipe"] });
80
+ const t0 = Date.now(), bufs = { stdout: [], stderr: [] };
81
+ const tick = setInterval(() => {
82
+ const ms = usedMs + (Date.now() - t0);
83
+ onTick?.({ seconds: billedSeconds(ms), cost: fromMicro(BigInt(billedSeconds(ms)) * rateM, 4), max: maxSeconds });
84
+ if (ms >= maxSeconds * 1000 && !exhausted) { exhausted = true; child.kill("SIGTERM"); setTimeout(() => child.kill("SIGKILL"), 3000).unref(); }
85
+ }, 250);
86
+ for (const k of ["stdout", "stderr"]) child[k].on("data", (b) => {
87
+ outHash.update(b); if (stdio === "pipe") bufs[k].push(b); onData?.(k, b);
88
+ });
89
+ running = new Promise((resolve, reject) => {
90
+ child.on("error", (e) => { clearInterval(tick); running = null; reject(e); });
91
+ child.on("close", (code, signal) => {
92
+ clearInterval(tick);
93
+ usedMs = Math.min(usedMs + (Date.now() - t0), maxSeconds * 1000);
94
+ running = null;
95
+ const rec = { cmd: Array.isArray(cmd) ? cmd.join(" ") : cmd, code, signal, ms: Date.now() - t0 };
96
+ execs.push(rec);
97
+ resolve({ ...rec, stdout: Buffer.concat(bufs.stdout).toString(), stderr: Buffer.concat(bufs.stderr).toString() });
98
+ });
99
+ });
100
+ return running;
101
+ },
102
+
103
+ // Closes the session, signs the receipt and writes it to IRIDA_HOME/receipts/<id>.json.
104
+ async stop() {
105
+ if (stopped) return stopped;
106
+ if (running) await running.catch(() => {});
107
+ const s = usedMs ? billedSeconds(usedMs) : 0;
108
+ const paidM = BigInt(s) * rateM > budgetM ? budgetM : BigInt(s) * rateM;
109
+ const body = {
110
+ v: 1, mode: "local", session: id, worker, opened: new Date(opened).toISOString(), closed: new Date().toISOString(),
111
+ seconds: s, rate: fromMicro(rateM, 6) + " USDG/s", budget: fromMicro(budgetM, 6) + " USDG",
112
+ paid: fromMicro(paidM, 6) + " USDG", refund: fromMicro(budgetM - paidM, 6) + " USDG",
113
+ status: exhausted ? "budget_exhausted" : "completed", settlement: "local",
114
+ execs: execs.map(({ cmd, code, signal }) => ({ cmd, code, signal })),
115
+ output: "sha256:" + outHash.digest("hex"),
116
+ };
117
+ stopped = signReceipt(body, key);
118
+ const rdir = join(dir, "receipts");
119
+ mkdirSync(rdir, { recursive: true });
120
+ stopped.file = join(rdir, id + ".json");
121
+ const { file, ...out } = stopped;
122
+ writeFileSync(stopped.file, JSON.stringify(out, null, 2) + "\n");
123
+ return stopped;
124
+ },
125
+ };
126
+ return session;
127
+ }
128
+
129
+ export function receipts(dir = home()) {
130
+ const rdir = join(dir, "receipts");
131
+ let names = [];
132
+ try { names = readdirSync(rdir).filter((n) => n.endsWith(".json")); } catch {}
133
+ return names.map((n) => { try { return { file: join(rdir, n), ...JSON.parse(readFileSync(join(rdir, n), "utf8")) }; } catch { return null; } })
134
+ .filter(Boolean).sort((a, b) => (a.closed < b.closed ? 1 : -1));
135
+ }
136
+
137
+ export function whoami(dir = home()) { const k = nodeKey(dir); return { id: k.id, pub: k.pub, home: dir }; }
138
+
139
+ export default { open, quote, receipts, verifyReceipt, whoami, cloud: cloudClient };
package/src/mcp.js ADDED
@@ -0,0 +1,377 @@
1
+ // Irida as an MCP server: any MCP client (Claude Code, Claude Desktop, Cursor, ...) gets tools to rent a sealed
2
+ // sandbox by the second, run code in it, and get back the output with a signed, verified receipt.
3
+ // Transport: stdio, newline-delimited JSON-RPC 2.0. No dependencies. stdout carries protocol messages only.
4
+ //
5
+ // irida mcp [--cloud <url>] [--max-budget 0.10]
6
+ //
7
+ // The account is the local ed25519 key in IRIDA_HOME (~/.irida), the same one the CLI uses.
8
+ // --max-budget caps what a single tool call may hold, so an agent cannot spend more than you allow per run.
9
+ import { createInterface } from "node:readline";
10
+ import { readFileSync, writeFileSync, mkdirSync, statSync } from "node:fs";
11
+ import { join, dirname, resolve } from "node:path";
12
+ import { client, DEFAULT_CLOUD, scanUrl } from "./cloud.js";
13
+ import { verifyReceipt, home } from "./receipt.js";
14
+ import { receipts, quote, toMicro, fromMicro, DEFAULT_RATE } from "./index.js";
15
+ import { resolveSecrets, listSecrets } from "./secrets.js";
16
+ import { prove } from "./prove.js";
17
+
18
+ // Hosts an agent may open the gate to when the user has not set --allow: package registries and source downloads.
19
+ export const DEFAULT_CEILING = ["pypi.org", "files.pythonhosted.org", "registry.npmjs.org", "github.com", "codeload.github.com",
20
+ "objects.githubusercontent.com", "raw.githubusercontent.com", "api.github.com"];
21
+
22
+ const PROTOCOLS = ["2025-06-18", "2025-03-26", "2024-11-05"];
23
+ const OUT_LIMIT = 20_000; // characters of stdout/stderr returned per stream
24
+ const UP_LIMIT = 512 * 1024; // bytes uploaded per call, all files together
25
+ const DOWN_LIMIT = 2 * 1024 * 1024; // bytes per output file
26
+ const INLINE_TEXT = 64 * 1024; // output files up to this size come back inline when they are text
27
+ const CHUNK = 5700; // raw bytes per upload exec; base64 plus the command stays under the node's 8192-character limit
28
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
29
+
30
+ const INSTRUCTIONS = `Irida rents a sealed sandbox by the second and pays for it in USDG from this machine's Irida account.
31
+ By default the sandbox has no network. To reach the internet pass net.allow with the hosts you need (HTTPS only, within the hosts the user permits; irida_account lists them).
32
+ To call an API with a key, pass net.secrets with key names from irida_account: inside the sandbox call $IRIDA_GATE/<name>/<path> (for example $IRIDA_GATE/openai/v1/chat/completions) and the gate adds the key outside the sandbox. You never see or handle the key.
33
+ Every request through the gate is written into the signed receipt.
34
+ Use irida_run for a one-shot job: code or a command, optional input files, optional output files to bring back, one receipt.
35
+ For multi-step work (install, run, inspect, run again) use irida_session_open, then irida_exec as many times as needed (files in /work persist between calls), then irida_session_close. A session is billed for every second it is open, including time between calls, so close it as soon as you are done; the node closes it after 2 idle minutes.
36
+ Every run returns stdout, stderr, the exit code, the seconds billed, the amount paid and refunded, and a receipt that has already been verified.
37
+ Check irida_account first if a run fails for lack of balance. New accounts start with a small free trial.`;
38
+
39
+ const shq = (a) => "'" + String(a).replace(/'/g, "'\\''") + "'";
40
+ const cut = (s) => (s.length > OUT_LIMIT ? s.slice(0, OUT_LIMIT) + `\n[... ${s.length - OUT_LIMIT} more characters not shown]` : s);
41
+ const amt = (s) => String(s).split(" ")[0];
42
+
43
+ const FILES_IN = { type: "array", description: "Files to place in /work before running. Each item gives a relative path and either text content or a local_path on this machine. 512 KB in total.",
44
+ items: { type: "object", properties: { path: { type: "string", description: "Relative path inside /work, e.g. data/input.csv" }, content: { type: "string", description: "Text content of the file." }, local_path: { type: "string", description: "A file on this machine to upload instead of content." } }, required: ["path"], additionalProperties: false } };
45
+ const FILES_OUT = { type: "array", items: { type: "string" }, description: "Relative paths in /work to bring back after the run, e.g. [\"out/chart.png\"]. Saved under ~/.irida/files/<session>/; text files up to 64 KB are also returned inline. 2 MB per file." };
46
+ const CODE = { type: "string", description: "Source code to run. Runs with python3 for worker python, node for worker node, sh for worker shell. Long code is uploaded as a file first." };
47
+ const COMMAND = { type: "string", description: "A shell command line to run instead of code, run from /work, e.g. \"pip list\" or \"python3 main.py\"." };
48
+ const NET = { type: "object", description: "Open the gate for this run. Without it the sandbox has no network.",
49
+ properties: { allow: { type: "array", items: { type: "string" }, description: "Hosts HTTPS may reach, e.g. [\"pypi.org\", \"files.pythonhosted.org\"]. Must be within the hosts the user permits (see irida_account)." },
50
+ secrets: { type: "array", items: { type: "string" }, description: "Names of the user's stored keys to use through $IRIDA_GATE/<name>/<path>. The key is added outside the sandbox." } },
51
+ additionalProperties: false };
52
+ const BUDGET = { type: "string", description: "Most USDG this may spend, e.g. \"0.02\" (50 seconds at 0.0004/s). Unused budget is refunded. Defaults to 0.02." };
53
+
54
+ export const TOOLS = [
55
+ {
56
+ name: "irida_run",
57
+ title: "Run code in an Irida sandbox",
58
+ description: "Run a command or a snippet of code in a sealed Irida Cloud sandbox (no network access, empty working directory), billed per second in USDG. " +
59
+ "Returns stdout, stderr, exit code, seconds billed, amount paid and refunded, and a signed receipt that is verified before it is returned. " +
60
+ "Give either `code` (run with the worker's interpreter) or `command` (a shell command line).",
61
+ inputSchema: {
62
+ type: "object",
63
+ properties: {
64
+ code: CODE, command: COMMAND,
65
+ worker: { type: "string", enum: ["python", "node", "shell"], description: "Sandbox image. Defaults to python when code is given, shell otherwise." },
66
+ budget: BUDGET, files: FILES_IN, outputs: FILES_OUT, net: NET,
67
+ },
68
+ additionalProperties: false,
69
+ },
70
+ annotations: { title: "Run code in an Irida sandbox", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
71
+ },
72
+ {
73
+ name: "irida_session_open",
74
+ title: "Open a sandbox session",
75
+ description: "Open a sealed sandbox that stays up across several irida_exec calls, with /work kept between them. Billed per second while open, idle sessions close after 2 minutes. Returns the session id.",
76
+ inputSchema: { type: "object", properties: { worker: { type: "string", enum: ["python", "node", "shell"], description: "Sandbox image. Defaults to python." }, budget: BUDGET, net: NET }, additionalProperties: false },
77
+ annotations: { title: "Open a sandbox session", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
78
+ },
79
+ {
80
+ name: "irida_exec",
81
+ title: "Run in an open session",
82
+ description: "Run code or a command in a session opened with irida_session_open. Files written to /work stay for the next call. Can upload input files and bring output files back.",
83
+ inputSchema: { type: "object", properties: { session: { type: "string", description: "Session id from irida_session_open." }, code: CODE, command: COMMAND, files: FILES_IN, outputs: FILES_OUT }, required: ["session"], additionalProperties: false },
84
+ annotations: { title: "Run in an open session", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
85
+ },
86
+ {
87
+ name: "irida_session_close",
88
+ title: "Close a session",
89
+ description: "Close a session: pay the seconds it was open, refund the rest of the budget, and return the signed receipt after verifying it.",
90
+ inputSchema: { type: "object", properties: { session: { type: "string", description: "Session id to close." } }, required: ["session"], additionalProperties: false },
91
+ annotations: { title: "Close a session", readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
92
+ },
93
+ {
94
+ name: "irida_account",
95
+ title: "Irida account and balance",
96
+ description: "Show this machine's Irida account id, USDG balance, any free trial, the node's rate and workers, and how to fund the account.",
97
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
98
+ annotations: { title: "Irida account and balance", readOnlyHint: true, openWorldHint: true },
99
+ },
100
+ {
101
+ name: "irida_quote",
102
+ title: "Price a run",
103
+ description: "Price a run of a given number of seconds at the node's per-second rate, before spending anything.",
104
+ inputSchema: { type: "object", properties: { seconds: { type: "integer", minimum: 1, description: "Seconds to price." } }, required: ["seconds"], additionalProperties: false },
105
+ annotations: { title: "Price a run", readOnlyHint: true, openWorldHint: false },
106
+ },
107
+ {
108
+ name: "irida_verify",
109
+ title: "Verify a receipt",
110
+ description: "Check an Irida receipt's ed25519 signature over its canonical JSON. Accepts a full session id (0x + 64 hex), a receipt URL, or the receipt JSON itself. Any edited field makes it invalid.",
111
+ inputSchema: { type: "object", properties: { receipt: { type: "string", description: "Session id, receipt URL, or receipt JSON." } }, required: ["receipt"], additionalProperties: false },
112
+ annotations: { title: "Verify a receipt", readOnlyHint: true, openWorldHint: true },
113
+ },
114
+ {
115
+ name: "irida_prove",
116
+ title: "Prove the node",
117
+ description: "Check the Irida node end to end without trusting it: run a probe in a real sandbox with no key, then check the receipt signature, that the output matches its hash, that billing is per second, that the gate refused an unlisted host and the cloud metadata address and logged it, that the box has no network outside the gate, the node's own self-check, its signed manifest, and one anchored receipt down to the chain. Use it before trusting a node with keys or funds.",
118
+ inputSchema: { type: "object", properties: { chain: { type: "boolean", description: "Also read the anchor transaction from a chain RPC. Defaults to true." } }, additionalProperties: false },
119
+ annotations: { title: "Prove the node", readOnlyHint: true, openWorldHint: true },
120
+ },
121
+ {
122
+ name: "irida_receipts",
123
+ title: "Recent receipts",
124
+ description: "List the most recent receipts saved on this machine, newest first.",
125
+ inputSchema: { type: "object", properties: { limit: { type: "integer", minimum: 1, maximum: 100, description: "How many to list. Defaults to 10." } }, additionalProperties: false },
126
+ annotations: { title: "Recent receipts", readOnlyHint: true, openWorldHint: false },
127
+ },
128
+ ];
129
+
130
+ /** Tool implementations, separate from the transport so they can be tested directly. */
131
+ export function tools({ url = process.env.IRIDA_CLOUD || DEFAULT_CLOUD, dir, maxBudget = process.env.IRIDA_MAX_BUDGET || "0.10", ceiling = DEFAULT_CEILING } = {}) {
132
+ const c = client(url, dir ? { dir } : undefined);
133
+ const cap = toMicro(maxBudget);
134
+ const ok = (text, data) => ({ content: [{ type: "text", text }], structuredContent: data, isError: false });
135
+ const fail = (text) => ({ content: [{ type: "text", text }], isError: true });
136
+
137
+ const open = new Map(); // session id -> { s, worker }
138
+ const fileDir = (id) => join(dir || home(), "files", id);
139
+
140
+ function budgetOf(budget = "0.02") {
141
+ let b;
142
+ try { b = toMicro(String(budget)); } catch { throw new Error(`Budget "${budget}" is not an amount. Use a decimal string such as "0.02".`); }
143
+ if (b <= 0n) throw new Error("Budget must be above zero.");
144
+ if (b > cap) throw new Error(`Budget ${budget} USDG is above this server's per-run cap of ${fromMicro(cap, 6)} USDG. Ask the user to raise --max-budget, or use a smaller budget.`);
145
+ return fromMicro(b, 6);
146
+ }
147
+ const safePath = (p) => {
148
+ const x = String(p || "").replace(/^\/work\//, "").replace(/^\.\//, "");
149
+ if (!x || x.startsWith("/") || x.split("/").some((seg) => seg === ".." || seg === "") || /[\0\n]/.test(x)) throw new Error(`"${p}" must be a relative path inside /work, without .. segments.`);
150
+ return x;
151
+ };
152
+ // the agent can ask for less than the user permits, never more
153
+ const permitted = (h) => ceiling.includes("*") || ceiling.some((p) => (p.startsWith("*.") ? h.endsWith(p.slice(1)) : h === p));
154
+ function netOf(net) {
155
+ if (!net || (!net.allow?.length && !net.secrets?.length)) return undefined;
156
+ const allow = (net.allow ?? []).map((h) => String(h).toLowerCase());
157
+ const out = allow.filter((h) => !permitted(h));
158
+ if (out.length) throw new Error(`Not permitted: ${out.join(", ")}. The user allows: ${ceiling.join(", ")}. Ask the user to add hosts with irida mcp --allow.`);
159
+ return { allow, secrets: resolveSecrets(net.secrets ?? [], dir) };
160
+ }
161
+ async function openSession(worker, budget, net) {
162
+ try { return await c.open({ worker, budget: budgetOf(budget ?? "0.02"), fit: budget == null, net: netOf(net) }); }
163
+ catch (e) {
164
+ if (e.status === 402) throw new Error(`Not enough balance on ${c.url} for a ${budget ?? "0.02"} USDG budget. Account ${c.account}. Call irida_account to see the balance and how to fund it.`);
165
+ if (e.status === 429 || e.status === 409) throw new Error(`The node refused a new session: ${e.message}. Close any open session first (irida_session_close).`);
166
+ throw new Error(e.message);
167
+ }
168
+ }
169
+ async function upload(s, files = []) {
170
+ const items = files.map((f) => {
171
+ const path = safePath(f.path);
172
+ let buf;
173
+ if (f.local_path != null) {
174
+ const lp = resolve(String(f.local_path).replace(/^~(?=\/|$)/, process.env.HOME || ""));
175
+ if (statSync(lp).size > UP_LIMIT) throw new Error(`${f.local_path} is larger than ${UP_LIMIT / 1024} KB.`);
176
+ buf = readFileSync(lp);
177
+ } else if (f.content != null) buf = Buffer.from(String(f.content));
178
+ else throw new Error(`File ${f.path} needs content or local_path.`);
179
+ return { path, buf };
180
+ });
181
+ const total = items.reduce((n, x) => n + x.buf.length, 0);
182
+ if (total > UP_LIMIT) throw new Error(`Input files total ${Math.ceil(total / 1024)} KB, above the ${UP_LIMIT / 1024} KB limit per call.`);
183
+ for (const { path, buf } of items) {
184
+ const q = shq(path);
185
+ const first = await s.exec(`mkdir -p "$(dirname ${q})" && : > ${q}`);
186
+ if (first.code !== 0) throw new Error(`Could not create ${path}: ${first.stderr.trim()}`);
187
+ for (let i = 0; i < buf.length; i += CHUNK) {
188
+ const r = await s.exec(`printf %s '${buf.subarray(i, i + CHUNK).toString("base64")}' | base64 -d >> ${q}`);
189
+ if (r.code !== 0) throw new Error(`Upload of ${path} failed: ${r.stderr.trim()}`);
190
+ }
191
+ }
192
+ return items.map((x) => ({ path: x.path, bytes: x.buf.length }));
193
+ }
194
+ async function download(s, id, outputs = []) {
195
+ const out = [];
196
+ for (const p of outputs) {
197
+ const path = safePath(p), q = shq(path);
198
+ const size = await s.exec(`[ -f ${q} ] && wc -c < ${q}`);
199
+ if (size.code !== 0) { out.push({ path, error: "not found" }); continue; }
200
+ const n = Number(size.stdout.trim());
201
+ if (n > DOWN_LIMIT) { out.push({ path, bytes: n, error: `larger than ${DOWN_LIMIT / 1024 / 1024} MB, not downloaded` }); continue; }
202
+ const r = await s.exec(`base64 < ${q}`);
203
+ if (r.code !== 0) { out.push({ path, error: r.stderr.trim() || "could not read" }); continue; }
204
+ const buf = Buffer.from(r.stdout.replace(/\s+/g, ""), "base64");
205
+ const local = join(fileDir(id), path);
206
+ mkdirSync(dirname(local), { recursive: true });
207
+ writeFileSync(local, buf);
208
+ const text = buf.length <= INLINE_TEXT && !buf.includes(0) && Buffer.from(buf.toString("utf8")).equals(buf) ? buf.toString("utf8") : null;
209
+ out.push({ path, bytes: buf.length, saved_to: local, ...(text != null ? { content: text } : {}) });
210
+ }
211
+ return out;
212
+ }
213
+ async function execIn(s, worker, { code, command, files, outputs }) {
214
+ if (!code && !command) throw new Error("Give `code` or `command`.");
215
+ if (code && command) throw new Error("Give `code` or `command`, not both.");
216
+ const uploaded = files?.length ? await upload(s, files) : [];
217
+ let cmd = command;
218
+ if (code) {
219
+ const run = { python: "python3", node: "node", shell: "sh" }[worker];
220
+ if (code.length > 6000) { await upload(s, [{ path: `.irida/main.${{ python: "py", node: "js", shell: "sh" }[worker]}`, content: code }]); cmd = `${run} .irida/main.${{ python: "py", node: "js", shell: "sh" }[worker]}`; }
221
+ else cmd = `${{ python: "python3 -c", node: "node -e", shell: "sh -c" }[worker]} ${shq(code)}`;
222
+ }
223
+ const res = await s.exec(cmd);
224
+ const files_out = outputs?.length ? await download(s, s.id, outputs) : [];
225
+ return { exit_code: res.code ?? null, signal: res.signal ?? null, closed: !!res.closed, stdout: cut(res.stdout ?? ""), stderr: cut(res.stderr ?? ""), uploaded, files: files_out };
226
+ }
227
+ const outText = (d) => [
228
+ d.uploaded?.length ? `uploaded ${d.uploaded.map((f) => `${f.path} (${f.bytes} B)`).join(", ")}` : null,
229
+ d.stdout && `--- stdout\n${d.stdout}`, d.stderr && `--- stderr\n${d.stderr}`,
230
+ ...(d.files || []).map((f) => f.error ? `--- file ${f.path}: ${f.error}` : `--- file ${f.path} (${f.bytes} B) saved to ${f.saved_to}${f.content != null ? `\n${cut(f.content)}` : ""}`),
231
+ ].filter(Boolean).join("\n");
232
+ const receiptData0 = (r) => ({ status: r.status, seconds: r.seconds, rate: amt(r.rate), paid: amt(r.paid), refund: amt(r.refund), currency: "USDG",
233
+ session: r.session, node: r.node.id, receipt_url: `${c.url}/v1/receipts/${r.session}`, scan_url: scanUrl(c.url, r.session), receipt_file: r.file, receipt_verified: true });
234
+ const gateLine = (r) => r.net ? `\ngate: ${r.net.requests} requests, ${r.net.denied} refused${r.net.log.filter((e) => e.k === "deny").slice(0, 5).map((e) => `\n refused ${e.host}${e.path ?? ""} (${e.why})`).join("")}` : "";
235
+ const receiptData = (r) => ({ ...receiptData0(r), gate: r.net ? { allow: r.net.allow, secrets: r.net.secrets.map((x) => x.name), requests: r.net.requests, denied: r.net.denied, log: r.net.log.slice(-50) } : null });
236
+ const receiptLine = (d) => `${d.seconds}s billed · paid ${d.paid} USDG · refund ${d.refund} USDG${d.status === "budget_exhausted" ? " · stopped: budget ran out" : ""}\nreceipt ${d.session} (signature verified) ${d.receipt_url}${d.scan_url ? `\nanyone can check it: ${d.scan_url}` : ""}`;
237
+
238
+ async function run({ code, command, worker, budget, files, outputs, net } = {}) {
239
+ const w = worker || (code ? "python" : "shell");
240
+ if (!["python", "node", "shell"].includes(w)) return fail(`Unknown worker "${w}". Use python, node or shell.`);
241
+ if (!code && !command) return fail("Give `code` or `command`.");
242
+ if (code && command) return fail("Give `code` or `command`, not both.");
243
+ let s;
244
+ try { s = await openSession(w, budget, net); } catch (e) { return fail(e.message); }
245
+ let d, error = null;
246
+ try { d = await execIn(s, w, { code, command, files, outputs }); } catch (e) { error = e.message; }
247
+ const r = await s.stop();
248
+ const data = { ...(d || {}), worker: w, ...receiptData(r) };
249
+ const head = `exit ${data.exit_code ?? data.signal ?? "none"} · ${receiptLine(data)}${gateLine(r)}${error ? `\nerror: ${error}` : ""}`;
250
+ const body = d ? outText(d) : "";
251
+ return { ...ok(body ? `${head}\n${body}` : `${head}\n(no output)`, data), isError: !!error || r.status === "budget_exhausted" || (data.exit_code ?? 0) !== 0 };
252
+ }
253
+
254
+ async function sessionOpen({ worker = "python", budget, net } = {}) {
255
+ if (!["python", "node", "shell"].includes(worker)) return fail(`Unknown worker "${worker}". Use python, node or shell.`);
256
+ let s;
257
+ try { s = await openSession(worker, budget, net); } catch (e) { return fail(e.message); }
258
+ open.set(s.id, { s, worker });
259
+ const data = { session: s.id, worker, image: s.image, budget: amt(s.budget), rate: amt(s.rate), max_seconds: s.maxSeconds, node: s.node, net: s.net };
260
+ return ok(`session ${s.id} open · worker ${worker} · budget ${data.budget} USDG (up to ${s.maxSeconds}s) · ${s.net ? `gate open to ${s.net.allow.join(", ") || "no hosts"}${s.net.secrets.length ? `, keys ${s.net.secrets.join(", ")} via $IRIDA_GATE` : ""}` : "no network"} · billed while open, close it with irida_session_close`, data);
261
+ }
262
+ async function exec({ session, ...args } = {}) {
263
+ const o = open.get(String(session));
264
+ if (!o) return fail(`No open session ${session} from this server. Open one with irida_session_open.`);
265
+ try {
266
+ const d = await execIn(o.s, o.worker, args);
267
+ if (d.closed) { open.delete(o.s.id); }
268
+ const text = `exit ${d.exit_code ?? d.signal ?? "none"} · session ${o.s.id}${d.closed ? " · the session was closed by the node (budget or idle)" : ""}\n${outText(d) || "(no output)"}`;
269
+ return { ...ok(text, { session: o.s.id, ...d }), isError: (d.exit_code ?? 0) !== 0 };
270
+ } catch (e) { return fail(e.message); }
271
+ }
272
+ async function sessionClose({ session } = {}) {
273
+ const o = open.get(String(session));
274
+ if (!o) return fail(`No open session ${session} from this server.`);
275
+ open.delete(o.s.id);
276
+ try { const d = receiptData(await o.s.stop()); return ok(receiptLine(d), d); }
277
+ catch (e) { return fail(`Could not close ${session}: ${e.message}`); }
278
+ }
279
+
280
+ async function account() {
281
+ try {
282
+ const [a, n] = await Promise.all([c.balance(), c.node()]);
283
+ const data = { account: a.account, node: n.node.id, url: c.url, balance: a.balance, held: a.held, trial: a.trial ?? null, currency: a.currency || "USDG",
284
+ rate: n.rate, workers: n.workers, max_budget_per_run: fromMicro(cap, 6), deposit: n.deposit ?? null,
285
+ gate: { permitted_hosts: ceiling, keys: listSecrets(dir).map((x) => ({ name: x.name, origin: x.origin, ...(x.rules.length ? { only: x.rules } : {}), ...(x.max ? { max_requests: x.max } : {}) })) } };
286
+ const lines = [`account ${a.account}`, `balance ${a.balance} USDG${a.held !== "0.000000" ? ` (${a.held} held by open sessions)` : ""}`,
287
+ a.trial ? `free trial of ${a.trial} USDG added to this new account` : null,
288
+ `rate ${n.rate} USDG/s · workers ${n.workers.join(", ")} · cap per run ${fromMicro(cap, 6)} USDG`,
289
+ `gate: hosts you may allow ${ceiling.join(", ")}`, `keys: ${listSecrets(dir).map((x) => `${x.name} (${x.origin}${x.rules.length ? `, only ${x.rules.join(" | ")}` : ""}${x.max ? `, up to ${x.max} requests` : ""})`).join(", ") || "none stored (the user adds them with irida secret add)"}`,
290
+ n.deposit ? `fund: send USDG to vault ${n.deposit.vault} on chain ${n.deposit.chainId} (${n.deposit.method}) for account ${a.account}` : null].filter(Boolean);
291
+ return ok(lines.join("\n"), data);
292
+ } catch (e) { return fail(`Could not reach ${c.url}: ${e.message}`); }
293
+ }
294
+
295
+ async function proveIt({ chain = true } = {}) {
296
+ const r = await prove(c.url, { chain });
297
+ const lines = r.checks.map((x) => `${x.ok === true ? "pass" : x.ok === false ? "FAIL" : "n/a "} ${x.label}${x.detail ? " · " + x.detail : ""}`);
298
+ return ok(`${r.ok ? "Proven" : "Not proven"}: ${r.passed} passed, ${r.failed} failed, ${r.skipped} not applicable yet (node ${c.url})\n` + lines.join("\n"), r);
299
+ }
300
+ async function priceIt({ seconds }) {
301
+ const n = Number(seconds);
302
+ if (!Number.isInteger(n) || n < 1) return fail("seconds must be a whole number of at least 1.");
303
+ let rate = DEFAULT_RATE;
304
+ try { rate = (await c.node()).rate; } catch {}
305
+ const cost = quote(n, rate);
306
+ return ok(`${n}s at ${rate} USDG/s = ${cost} USDG`, { seconds: n, rate, cost, currency: "USDG" });
307
+ }
308
+
309
+ async function verify({ receipt }) {
310
+ const arg = String(receipt || "").trim();
311
+ let r;
312
+ try {
313
+ if (arg.startsWith("{")) r = JSON.parse(arg);
314
+ else {
315
+ const link = /^https?:\/\//.test(arg) ? arg : /^0x[0-9a-f]{64}$/i.test(arg) ? `${c.url}/v1/receipts/${arg.toLowerCase()}` : null;
316
+ if (!link) {
317
+ const local = receipts(dir).find((x) => x.session.startsWith(arg.split(/…|\.\.\./)[0]) && x.session.endsWith(arg.split(/…|\.\.\./)[1] || ""));
318
+ if (!local) return fail("Give a full session id (0x + 64 hex), a receipt URL, or the receipt JSON.");
319
+ r = local;
320
+ } else {
321
+ const res = await fetch(link);
322
+ if (!res.ok) return fail(`${link} answered ${res.status}.`);
323
+ r = await res.json();
324
+ }
325
+ }
326
+ } catch (e) { return fail(`Could not read the receipt: ${e.message}`); }
327
+ if (r && !r.sig && r.receipt) r = r.receipt;
328
+ const { file, ...clean } = r || {};
329
+ const v = verifyReceipt(clean);
330
+ const data = { valid: v.ok, reason: v.ok ? null : v.reason, session: clean.session ?? null, seconds: clean.seconds ?? null, paid: clean.paid ? amt(clean.paid) : null, node: clean.node?.id ?? null };
331
+ return { ...ok(v.ok ? `valid · session ${clean.session} · ${clean.seconds}s · paid ${clean.paid} · signed by node ${clean.node?.id}` : `invalid · ${v.reason}`, data), isError: false };
332
+ }
333
+
334
+ function list({ limit = 10 } = {}) {
335
+ const rs = receipts(dir).slice(-Math.min(100, Math.max(1, Number(limit) || 10))).reverse();
336
+ const rows = rs.map((r) => ({ session: r.session, closed: r.closed, seconds: r.seconds, paid: amt(r.paid), worker: r.worker, status: r.status, mode: r.mode ?? null }));
337
+ return ok(rows.length ? rows.map((r) => `${r.closed.slice(0, 19).replace("T", " ")} ${r.session} ${r.seconds}s ${r.paid} ${r.worker} ${r.status}`).join("\n") : "No receipts on this machine yet.", { receipts: rows });
338
+ }
339
+
340
+ const closeAll = () => Promise.allSettled([...open.values()].map((o) => o.s.stop()));
341
+ return { url: c.url, account: c.account, closeAll, call: { irida_run: run, irida_session_open: sessionOpen, irida_exec: exec, irida_session_close: sessionClose, irida_account: account, irida_quote: priceIt, irida_verify: verify, irida_receipts: list, irida_prove: proveIt } };
342
+ }
343
+
344
+ /** Serves the tools over stdio until stdin closes. */
345
+ export function serve(opts = {}, { input = process.stdin, output = process.stdout } = {}) {
346
+ const t = tools(opts);
347
+ const send = (m) => output.write(JSON.stringify(m) + "\n");
348
+ const reply = (id, result) => send({ jsonrpc: "2.0", id, result });
349
+ const error = (id, code, message) => send({ jsonrpc: "2.0", id, error: { code, message } });
350
+ const rl = createInterface({ input, crlfDelay: Infinity });
351
+ const pending = new Set();
352
+ rl.on("line", (line) => {
353
+ if (!line.trim()) return;
354
+ let m;
355
+ try { m = JSON.parse(line); } catch { return error(null, -32700, "parse error"); }
356
+ const { id, method, params = {} } = m;
357
+ if (id === undefined) return; // notifications (initialized, cancelled) need no answer
358
+ if (method === "initialize") {
359
+ const v = PROTOCOLS.includes(params.protocolVersion) ? params.protocolVersion : PROTOCOLS[0];
360
+ return reply(id, { protocolVersion: v, capabilities: { tools: { listChanged: false } }, serverInfo: { name: "irida", title: "Irida", version: pkg.version }, instructions: INSTRUCTIONS });
361
+ }
362
+ if (method === "ping") return reply(id, {});
363
+ if (method === "tools/list") return reply(id, { tools: TOOLS });
364
+ if (method === "tools/call") {
365
+ const fn = t.call[params.name];
366
+ if (!fn) return error(id, -32602, `unknown tool: ${params.name}`);
367
+ const p = Promise.resolve().then(() => fn(params.arguments || {}))
368
+ .then((r) => reply(id, r), (e) => reply(id, { content: [{ type: "text", text: `irida: ${e.message}` }], isError: true }))
369
+ .finally(() => pending.delete(p));
370
+ pending.add(p);
371
+ return;
372
+ }
373
+ error(id, -32601, `method not found: ${method}`);
374
+ });
375
+ // when the client goes away, open sessions are closed so their unused budget is refunded
376
+ return new Promise((done) => rl.on("close", () => Promise.allSettled([...pending]).then(() => t.closeAll()).then(() => done())));
377
+ }
package/src/probe.js ADDED
@@ -0,0 +1,85 @@
1
+ // The probe: a short script run inside a real gated sandbox, and the rules that judge it from the signed receipt.
2
+ // The node runs it on itself as a canary every half hour; `irida prove` runs it from anyone's machine. Same script,
3
+ // same rules, so a canary result and a prove result mean the same thing.
4
+ //
5
+ // What it asks the sandbox to do, and what must happen:
6
+ // direct open a socket to 1.1.1.1:443 without the gate -> must fail (the box has no network of its own)
7
+ // unlisted fetch https://example.com through the gate -> the gate must refuse it, and log the refusal
8
+ // metadata fetch http://169.254.169.254 (cloud credentials) -> the gate must refuse it, and log the refusal
9
+ // allowed fetch https://<first allowed host> through the gate -> the gate must let it through, and log it
10
+ // The receipt is the judge for the gate checks (its log is signed by the node); the box's own report is only used for
11
+ // the direct check, which the gate cannot see.
12
+ import { createHash } from "node:crypto";
13
+ import { verifyReceipt } from "./receipt.js";
14
+
15
+ export const UNLISTED = "example.com";
16
+ export const METADATA = "169.254.169.254";
17
+ const MARK = "irida-probe-v1";
18
+
19
+ /** The command to run. Python's urllib follows the HTTPS_PROXY the gate sets; stderr is folded into stdout so the
20
+ * output hash in the receipt can be checked against exactly what came back. */
21
+ export function probeCommand(allowed) {
22
+ if (!/^[a-z0-9.-]+$/.test(allowed)) throw new Error(`not a host name: ${allowed}`);
23
+ return `python3 - <<'PY' 2>&1
24
+ # ${MARK}
25
+ import json, socket, urllib.request, urllib.error
26
+ def get(u):
27
+ try:
28
+ return urllib.request.urlopen(u, timeout=8).status
29
+ except urllib.error.HTTPError as e:
30
+ return e.code
31
+ except Exception as e:
32
+ return "refused" if "403" in str(e) or "Tunnel" in str(e) else "error"
33
+ r = {}
34
+ try:
35
+ socket.create_connection(("1.1.1.1", 443), timeout=3).close(); r["direct"] = "open"
36
+ except Exception:
37
+ r["direct"] = "blocked"
38
+ r["unlisted"] = get("https://${UNLISTED}/")
39
+ r["metadata"] = get("http://${METADATA}/latest/meta-data/")
40
+ r["allowed"] = get("https://${allowed}/")
41
+ print(json.dumps(r, sort_keys=True))
42
+ PY`;
43
+ }
44
+
45
+ const lastJson = (s) => { for (const line of String(s).trim().split("\n").reverse()) { try { const o = JSON.parse(line); if (o && typeof o === "object") return o; } catch {} } return null; };
46
+
47
+ /**
48
+ * Judges one probe run. `out` is what the caller received (stdout), `receipt` is the node's signed receipt for it.
49
+ * Returns [{ id, ok, label, detail }]; `ok` is true, false, or null when the check could not apply.
50
+ */
51
+ export function judge({ receipt, out, allowed, nodeId = null }) {
52
+ const checks = [];
53
+ const add = (id, ok, label, detail) => checks.push({ id, ok, label, detail });
54
+ const sig = verifyReceipt(receipt);
55
+ add("signature", sig.ok, "Receipt is signed by the node", sig.ok ? `ed25519 · node ${receipt.node.id}` : sig.reason);
56
+ if (nodeId) add("node", receipt?.node?.id === nodeId, "Signed by the node you asked", receipt?.node?.id === nodeId ? nodeId : `receipt names ${receipt?.node?.id}, node says ${nodeId}`);
57
+ const hash = "sha256:" + createHash("sha256").update(String(out ?? "")).digest("hex");
58
+ add("output", receipt?.output === hash, "Output you got is the output that was signed", receipt?.output === hash ? hash.slice(0, 23) + "…" : "the receipt's output hash does not match what came back");
59
+ const rate = parseFloat(receipt?.rate), paid = parseFloat(receipt?.paid), budget = parseFloat(receipt?.budget);
60
+ const want = Math.min(budget, Math.round(receipt?.seconds * rate * 1e6) / 1e6);
61
+ const billOk = Number.isFinite(paid) && Math.abs(paid - want) < 1e-6 && Math.abs(paid + parseFloat(receipt?.refund) - budget) < 1e-6;
62
+ add("billing", billOk, "Billed by the second, rest refunded", billOk ? `${receipt.seconds}s × ${rate} = ${receipt.paid}, refund ${receipt.refund}` : `paid ${receipt?.paid} for ${receipt?.seconds}s at ${receipt?.rate}`);
63
+ const log = receipt?.net?.log ?? [];
64
+ if (!receipt?.net) {
65
+ add("gate", false, "Session ran behind the gate", "the receipt has no gate section: this node runs sandboxes without network");
66
+ return checks;
67
+ }
68
+ const denied = (h) => log.some((e) => e.k === "deny" && e.host === h);
69
+ const passed = (h) => log.some((e) => e.k !== "deny" && e.k !== "revoke" && e.host === h);
70
+ // reached means bytes came back through the gate, not just that it was let through
71
+ const reached = (h) => log.some((e) => e.k !== "deny" && e.k !== "revoke" && e.host === h && (e.down ?? 0) > 0);
72
+ const failedUp = (h) => log.find((e) => e.host === h && e.why && e.k !== "deny");
73
+ add("unlisted", denied(UNLISTED), `Unlisted host refused (${UNLISTED})`, denied(UNLISTED) ? "refusal is in the signed gate log" : "no refusal for it in the gate log");
74
+ add("metadata", denied(METADATA), "Cloud metadata address refused", denied(METADATA) ? "refusal is in the signed gate log" : "no refusal for it in the gate log");
75
+ const report = lastJson(out);
76
+ const up = failedUp(allowed);
77
+ add("allowed", reached(allowed) ? true : up ? false : null, `Allowlisted host reached (${allowed})`,
78
+ reached(allowed) ? `answered through the gate, ${log.find((e) => e.host === allowed && (e.down ?? 0) > 0).down} B back, in the signed gate log`
79
+ : up ? `let through, but the gate could not reach it (${up.why}); the box saw ${report?.allowed ?? "nothing"}`
80
+ : passed(allowed) ? `let through, no reply yet (box saw ${report?.allowed ?? "nothing"})` : `not reached (box saw ${report?.allowed ?? "nothing"}); the upstream may be down`);
81
+ add("direct", report ? report.direct === "blocked" : false, "No network outside the gate", report?.direct === "blocked" ? "a raw socket to 1.1.1.1:443 failed inside the box" : report ? "a raw socket got out: this sandbox is not isolated" : "the probe printed no report");
82
+ return checks;
83
+ }
84
+
85
+ export const verdict = (checks) => ({ ok: checks.every((c) => c.ok !== false), passed: checks.filter((c) => c.ok === true).length, failed: checks.filter((c) => c.ok === false).length, skipped: checks.filter((c) => c.ok === null).length });