irida 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +60 -2
- package/bin/irida.js +355 -0
- package/package.json +45 -4
- package/src/auth.js +35 -0
- package/src/cloud.js +90 -0
- package/src/index.js +139 -0
- package/src/mcp.js +377 -0
- package/src/probe.js +78 -0
- package/src/proof.js +43 -0
- package/src/prove.js +77 -0
- package/src/receipt.js +52 -0
- package/src/secrets.js +50 -0
package/src/proof.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Checks a receipt against the anchor proof a node serves at /v1/receipts/:id/proof, and that proof against the chain.
|
|
2
|
+
// Same maths as server/anchor.js: leaf = sha256(0x00 || canonical receipt), node = sha256(0x01 || left || right),
|
|
3
|
+
// head = sha256(prev || root).
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { canonical } from "./receipt.js";
|
|
6
|
+
const H = (...p) => createHash("sha256").update(Buffer.concat(p.map((x) => Buffer.from(x, "hex")))).digest("hex");
|
|
7
|
+
const N = (a, b) => H("01", a, b);
|
|
8
|
+
export const SCHEME = "irida-merkle-2";
|
|
9
|
+
export const leafOf = (r) => { const { file, ...body } = r; return createHash("sha256").update(Buffer.concat([Buffer.from([0]), Buffer.from(canonical(body))])).digest("hex"); };
|
|
10
|
+
export function checkProof(receipt, p) {
|
|
11
|
+
if (p.scheme && p.scheme !== SCHEME) return { ok: false, reason: `unknown proof scheme ${p.scheme}` };
|
|
12
|
+
const leaf = leafOf(receipt);
|
|
13
|
+
if (leaf !== p.leaf) return { ok: false, reason: "the receipt does not hash to the proof's leaf" };
|
|
14
|
+
const root = p.path.reduce((h, s) => (s.side === "l" ? N(s.hash, h) : N(h, s.hash)), leaf);
|
|
15
|
+
if (root !== p.root) return { ok: false, reason: "the merkle path does not lead to the batch root" };
|
|
16
|
+
if (H(p.prev, p.root) !== p.head) return { ok: false, reason: "the batch head does not follow from prev and root" };
|
|
17
|
+
return { ok: true };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// keccak256("Anchored(uint64,bytes32,bytes32,uint32)")
|
|
21
|
+
export const ANCHORED_TOPIC = "0xe55e7e5b5898e4cc04193061e9bcc56b76c7acc89835be8221f952f25763873b";
|
|
22
|
+
export const DEFAULT_RPC = "https://rpc.mainnet.chain.robinhood.com";
|
|
23
|
+
|
|
24
|
+
/** Reads the transaction the proof names straight from a chain RPC and checks its Anchored event carries this batch's
|
|
25
|
+
* number, head and root, from the contract the receipt was signed against. Trusts the RPC, not the node. */
|
|
26
|
+
export async function checkChain(receipt, p, { rpc = DEFAULT_RPC, fetch: f = fetch } = {}) {
|
|
27
|
+
if (!p.tx) return { ok: false, pending: true, reason: "the batch head has not been posted on chain yet" };
|
|
28
|
+
const contract = String(receipt.anchor?.contract ?? p.contract ?? "").toLowerCase();
|
|
29
|
+
if (!/^0x[0-9a-f]{40}$/.test(contract)) return { ok: false, reason: "no anchor contract to check against" };
|
|
30
|
+
if (receipt.anchor?.chain && p.chain && Number(receipt.anchor.chain) !== Number(p.chain)) return { ok: false, reason: `the proof points at chain ${p.chain}, the receipt at chain ${receipt.anchor.chain}` };
|
|
31
|
+
const res = await f(rpc, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_getTransactionReceipt", params: [p.tx] }), signal: AbortSignal.timeout(20_000) });
|
|
32
|
+
const j = await res.json();
|
|
33
|
+
if (j.error) throw new Error(j.error.message);
|
|
34
|
+
const tx = j.result;
|
|
35
|
+
if (!tx) return { ok: false, reason: `transaction ${p.tx} is not on this chain` };
|
|
36
|
+
if (tx.status !== "0x1") return { ok: false, reason: "the anchoring transaction failed" };
|
|
37
|
+
const n = "0x" + BigInt(p.batch).toString(16).padStart(64, "0");
|
|
38
|
+
const ev = tx.logs.find((l) => l.address.toLowerCase() === contract && l.topics[0] === ANCHORED_TOPIC && l.topics[1] === n);
|
|
39
|
+
if (!ev) return { ok: false, reason: `transaction ${p.tx} has no Anchored event for batch #${p.batch} from ${contract}` };
|
|
40
|
+
const d = ev.data.slice(2);
|
|
41
|
+
if (d.slice(0, 64) !== p.head || d.slice(64, 128) !== p.root) return { ok: false, reason: "the head on chain is not the head in the proof" };
|
|
42
|
+
return { ok: true, block: parseInt(tx.blockNumber, 16), contract };
|
|
43
|
+
}
|
package/src/prove.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// `irida prove`: checks a node end to end from the outside, with no key, no wallet and no trust in the node.
|
|
2
|
+
// It runs a real probe through the node's keyless try endpoint and judges it from the signed receipt, compares the public
|
|
3
|
+
// copy of that receipt, reads the node's own canary record, checks the signed manifest, and walks one anchored receipt
|
|
4
|
+
// from its merkle leaf to the transaction on chain. Every check says what it looked at.
|
|
5
|
+
import { verifyReceipt } from "./receipt.js";
|
|
6
|
+
import { probeCommand, judge, verdict } from "./probe.js";
|
|
7
|
+
import { checkProof, checkChain, DEFAULT_RPC } from "./proof.js";
|
|
8
|
+
|
|
9
|
+
export async function prove(base, { fetch: f = fetch, rpc = DEFAULT_RPC, chain = true, onCheck = () => {} } = {}) {
|
|
10
|
+
base = String(base).replace(/\/$/, "");
|
|
11
|
+
const checks = [];
|
|
12
|
+
const add = (group, c) => { const row = { group, ...c }; checks.push(row); onCheck(row); return row; };
|
|
13
|
+
const get = async (path, opt) => {
|
|
14
|
+
const r = await f(base + path, { ...opt, signal: AbortSignal.timeout(60_000) });
|
|
15
|
+
const j = await r.json().catch(() => ({}));
|
|
16
|
+
if (!r.ok) throw Object.assign(new Error(j.error || `HTTP ${r.status}`), { status: r.status });
|
|
17
|
+
return j;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// 1. the node and who it says it is
|
|
21
|
+
let node;
|
|
22
|
+
try { node = await get("/v1/node"); }
|
|
23
|
+
catch (e) { add("node", { id: "reach", ok: false, label: "Node answers", detail: e.message }); return { node: null, checks, ...verdict(checks) }; }
|
|
24
|
+
add("node", { id: "reach", ok: true, label: "Node answers", detail: `${base} · node ${node.node.id} · ${node.sandbox ?? node.runner} sandbox` });
|
|
25
|
+
try {
|
|
26
|
+
const m = await get("/v1/manifest");
|
|
27
|
+
const v = verifyReceipt(m), same = m.node?.id === node.node.id;
|
|
28
|
+
const links = Object.entries(m.links ?? {}).map(([k, u]) => `${k} ${u}`).join(" · ");
|
|
29
|
+
add("node", { id: "manifest", ok: v.ok && same, label: "Manifest signed by the same key", detail: !v.ok ? v.reason : !same ? "manifest is signed by a different node" : links || "signed, no links listed" });
|
|
30
|
+
} catch (e) { add("node", { id: "manifest", ok: e.status === 404 ? null : false, label: "Manifest signed by the same key", detail: e.message }); }
|
|
31
|
+
|
|
32
|
+
// 2. a real run, judged from its receipt
|
|
33
|
+
if (!node.try) add("run", { id: "try", ok: false, label: "Keyless run", detail: "this node has keyless runs turned off, so it cannot be checked without an account" });
|
|
34
|
+
else {
|
|
35
|
+
const allowed = node.try.allow?.find((h) => !h.startsWith("*.")) ?? "pypi.org";
|
|
36
|
+
const worker = node.workers?.includes("python") ? "python" : "shell";
|
|
37
|
+
try {
|
|
38
|
+
const t0 = Date.now();
|
|
39
|
+
const r = await get("/v1/try", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ worker, cmd: probeCommand(allowed) }) });
|
|
40
|
+
add("run", { id: "try", ok: true, label: "Real sandbox run, no key", detail: `session ${r.session} · ${worker} · ${r.receipt.seconds}s · ${Date.now() - t0} ms round trip` });
|
|
41
|
+
for (const c of judge({ receipt: r.receipt, out: r.stdout, allowed, nodeId: node.node.id })) add("run", c);
|
|
42
|
+
try {
|
|
43
|
+
const pub = await get(`/v1/receipts/${r.session}`);
|
|
44
|
+
add("run", { id: "public", ok: pub.sig === r.receipt.sig, label: "Same receipt is public", detail: pub.sig === r.receipt.sig ? `${base}/v1/receipts/${r.session.slice(0, 10)}…` : "the public copy differs from the one returned" });
|
|
45
|
+
} catch (e) { add("run", { id: "public", ok: false, label: "Same receipt is public", detail: e.message }); }
|
|
46
|
+
} catch (e) { add("run", { id: "try", ok: false, label: "Real sandbox run, no key", detail: e.message }); }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 3. the node's own record of checking itself
|
|
50
|
+
try {
|
|
51
|
+
const c = await get("/v1/canary");
|
|
52
|
+
const last = c.last, age = last ? Math.round((Date.now() - Date.parse(new Date(last.at).toISOString())) / 60000) : null;
|
|
53
|
+
const fresh = last && age <= Math.ceil((c.every * 2.5) / 60);
|
|
54
|
+
add("canary", { id: "canary", ok: !last ? null : last.ok && fresh, label: "Node's own self-check is passing",
|
|
55
|
+
detail: !last ? "no self-check has run yet" : `${last.ok ? "passed" : "FAILED"} ${age} min ago · ${c.streak} in a row · every ${Math.round(c.every / 60)} min` });
|
|
56
|
+
} catch (e) { add("canary", { id: "canary", ok: e.status === 404 ? null : false, label: "Node's own self-check is passing", detail: e.status === 404 ? "this node does not publish a self-check" : e.message }); }
|
|
57
|
+
|
|
58
|
+
// 4. one receipt from the feed, walked to the chain
|
|
59
|
+
try {
|
|
60
|
+
const feed = await get("/v1/feed?limit=50");
|
|
61
|
+
const item = feed.items.find((x) => x.anchored) ?? feed.items.find((x) => x.batch != null);
|
|
62
|
+
if (!item) add("anchor", { id: "proof", ok: null, label: "Receipt sits in an anchored batch", detail: "no batch sealed yet (batches close every hour)" });
|
|
63
|
+
else {
|
|
64
|
+
const rc = await get(`/v1/receipts/${item.session}`), p = await get(`/v1/receipts/${item.session}/proof`);
|
|
65
|
+
const sig = verifyReceipt(rc), pr = checkProof(rc, p);
|
|
66
|
+
add("anchor", { id: "proof", ok: sig.ok && pr.ok, label: "Receipt sits in an anchored batch", detail: !sig.ok ? sig.reason : pr.ok ? `batch #${p.batch} · merkle path of ${p.path.length} checked locally` : pr.reason });
|
|
67
|
+
if (!chain) add("anchor", { id: "chain", ok: null, label: "Batch head is on chain", detail: "skipped (--no-chain)" });
|
|
68
|
+
else if (!p.tx) add("anchor", { id: "chain", ok: null, label: "Batch head is on chain", detail: "sealed, not posted yet" });
|
|
69
|
+
else {
|
|
70
|
+
const c = await checkChain(rc, p, { rpc, fetch: f });
|
|
71
|
+
add("anchor", { id: "chain", ok: c.ok, label: "Batch head is on chain", detail: c.ok ? `tx ${p.tx} · block ${c.block} · read from ${new URL(rpc).host}, not from the node` : c.reason });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
} catch (e) { add("anchor", { id: "proof", ok: e.status === 404 ? null : false, label: "Receipt sits in an anchored batch", detail: e.message }); }
|
|
75
|
+
|
|
76
|
+
return { node: node.node.id, checks, ...verdict(checks) };
|
|
77
|
+
}
|
package/src/receipt.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Receipts: canonical JSON, signed with the node's ed25519 key.
|
|
2
|
+
import { createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify, createHash } from "node:crypto";
|
|
3
|
+
import { mkdirSync, readFileSync, writeFileSync, existsSync, chmodSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
|
|
7
|
+
export const home = () => process.env.IRIDA_HOME || join(homedir(), ".irida");
|
|
8
|
+
|
|
9
|
+
// Canonical form: keys sorted at every level, no whitespace. The signature covers everything except `sig`.
|
|
10
|
+
export function canonical(v) {
|
|
11
|
+
if (Array.isArray(v)) return "[" + v.map(canonical).join(",") + "]";
|
|
12
|
+
if (v && typeof v === "object")
|
|
13
|
+
return "{" + Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + canonical(v[k])).join(",") + "}";
|
|
14
|
+
return JSON.stringify(v);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// The node key lives in IRIDA_HOME/node.key (0600). It is created on first use and never printed.
|
|
18
|
+
export function nodeKey(dir = home()) {
|
|
19
|
+
const file = join(dir, "node.key");
|
|
20
|
+
if (!existsSync(file)) {
|
|
21
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
22
|
+
const { privateKey } = generateKeyPairSync("ed25519");
|
|
23
|
+
writeFileSync(file, privateKey.export({ type: "pkcs8", format: "pem" }), { mode: 0o600 });
|
|
24
|
+
chmodSync(file, 0o600);
|
|
25
|
+
}
|
|
26
|
+
const priv = createPrivateKey(readFileSync(file));
|
|
27
|
+
const pub = createPublicKey(priv).export({ type: "spki", format: "der" }).toString("base64");
|
|
28
|
+
return { priv, pub, id: nodeId(pub) };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const nodeId = (pub) => "0x" + createHash("sha256").update(Buffer.from(pub, "base64")).digest("hex").slice(0, 40);
|
|
32
|
+
|
|
33
|
+
export function signReceipt(body, key) {
|
|
34
|
+
const r = { ...body, node: { id: key.id, pub: key.pub } };
|
|
35
|
+
delete r.sig;
|
|
36
|
+
r.sig = sign(null, Buffer.from(canonical(r)), key.priv).toString("base64");
|
|
37
|
+
return r;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Returns { ok, reason }. Checks the signature against the public key in the receipt and that the key matches the node id.
|
|
41
|
+
export function verifyReceipt(r) {
|
|
42
|
+
if (!r || typeof r !== "object" || !r.sig || !r.node?.pub) return { ok: false, reason: "not a receipt" };
|
|
43
|
+
if (nodeId(r.node.pub) !== r.node.id) return { ok: false, reason: "node id does not match its public key" };
|
|
44
|
+
const { sig, file, ...body } = r; // `file` is where this machine saved it, not part of what was signed
|
|
45
|
+
try {
|
|
46
|
+
const pub = createPublicKey({ key: Buffer.from(r.node.pub, "base64"), format: "der", type: "spki" });
|
|
47
|
+
const ok = verify(null, Buffer.from(canonical(body)), pub, Buffer.from(sig, "base64"));
|
|
48
|
+
return ok ? { ok: true } : { ok: false, reason: "signature does not match the receipt" };
|
|
49
|
+
} catch (e) {
|
|
50
|
+
return { ok: false, reason: "bad key or signature: " + e.message };
|
|
51
|
+
}
|
|
52
|
+
}
|
package/src/secrets.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Local keychain for the broker. Keys live in ~/.irida/secrets.json (0600) on your machine and are sent, over HTTPS,
|
|
2
|
+
// only to the node a session runs on, which keeps them in memory for that session and adds them to requests to their
|
|
3
|
+
// pinned origin. The sandbox, and so any agent or code running in it, never sees them.
|
|
4
|
+
import { readFileSync, writeFileSync, mkdirSync, chmodSync, existsSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { home } from "./receipt.js";
|
|
7
|
+
|
|
8
|
+
const file = (dir = home()) => join(dir, "secrets.json");
|
|
9
|
+
export function loadSecrets(dir) {
|
|
10
|
+
const f = file(dir);
|
|
11
|
+
if (!existsSync(f)) return {};
|
|
12
|
+
try { return JSON.parse(readFileSync(f, "utf8")); } catch { throw new Error(`${f} is not valid JSON`); }
|
|
13
|
+
}
|
|
14
|
+
function save(all, dir = home()) {
|
|
15
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
16
|
+
writeFileSync(file(dir), JSON.stringify(all, null, 2) + "\n", { mode: 0o600 });
|
|
17
|
+
chmodSync(file(dir), 0o600);
|
|
18
|
+
}
|
|
19
|
+
// rules: ["GET /repos/*", "POST /v1/chat/completions"] limit what the key may be used for (* one path segment, ** any);
|
|
20
|
+
// max: how many requests one session may make with it. Both are enforced at the gate, outside the sandbox.
|
|
21
|
+
const RULE_RE = /^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|\*) (\/[A-Za-z0-9._~!$&'()+,;=:@%*\/-]*)$/;
|
|
22
|
+
export function addSecret(name, origin, value, { header = "authorization", dir, rules = [], max = null } = {}) {
|
|
23
|
+
name = String(name).toLowerCase();
|
|
24
|
+
if (!/^[a-z][a-z0-9_-]{0,31}$/.test(name)) throw new Error("name: lowercase letters, digits, - or _ (up to 32), e.g. openai");
|
|
25
|
+
const u = new URL(origin);
|
|
26
|
+
if (u.protocol !== "https:") throw new Error("origin must be https://…");
|
|
27
|
+
value = String(value).trim();
|
|
28
|
+
if (!value) throw new Error("empty value");
|
|
29
|
+
header = header.toLowerCase();
|
|
30
|
+
// a bare token for the authorization header is sent as a bearer token
|
|
31
|
+
if (header === "authorization" && !/^(bearer|basic|token|bot)\s/i.test(value)) value = "Bearer " + value;
|
|
32
|
+
rules = rules.map((r) => String(r).trim().replace(/\s+/, " ")).filter(Boolean).map((r) => (/^\//.test(r) ? "* " + r : r.replace(/^\w+/, (m) => m.toUpperCase())));
|
|
33
|
+
for (const r of rules) if (!RULE_RE.test(r)) throw new Error(`rule "${r}" must look like "GET /repos/*" (method or *, then a path)`);
|
|
34
|
+
if (max != null && !(Number.isInteger(Number(max)) && Number(max) >= 1)) throw new Error("max must be a whole number of requests");
|
|
35
|
+
const all = loadSecrets(dir);
|
|
36
|
+
all[name] = { origin: u.origin, header, value, ...(rules.length ? { rules } : {}), ...(max != null ? { max: Number(max) } : {}) };
|
|
37
|
+
save(all, dir);
|
|
38
|
+
return { name, origin: u.origin, header, rules, max: max == null ? null : Number(max) };
|
|
39
|
+
}
|
|
40
|
+
export function removeSecret(name, dir) { const all = loadSecrets(dir); const had = name in all; delete all[name]; save(all, dir); return had; }
|
|
41
|
+
export const listSecrets = (dir) => Object.entries(loadSecrets(dir)).map(([name, s]) => ({ name, origin: s.origin, header: s.header, rules: s.rules ?? [], max: s.max ?? null }));
|
|
42
|
+
/** Turns names into what the node needs. Unknown names are an error, never silently skipped. */
|
|
43
|
+
export function resolveSecrets(names = [], dir) {
|
|
44
|
+
const all = loadSecrets(dir);
|
|
45
|
+
return names.map((n) => {
|
|
46
|
+
const s = all[String(n).toLowerCase()];
|
|
47
|
+
if (!s) throw new Error(`no secret named "${n}" on this machine. Add it: irida secret add ${n} <https origin>`);
|
|
48
|
+
return { name: String(n).toLowerCase(), origin: s.origin, header: s.header, value: s.value, ...(s.rules?.length ? { rules: s.rules } : {}), ...(s.max ? { max: s.max } : {}) };
|
|
49
|
+
});
|
|
50
|
+
}
|