@strixgov/mcp-proxy 0.2.4 → 0.2.5
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/CHANGELOG.md +24 -1
- package/README.md +75 -25
- package/examples/controlled-launcher/README.md +33 -0
- package/examples/controlled-launcher/acceptance.mjs +337 -0
- package/examples/controlled-launcher/agent-client.mjs +18 -0
- package/examples/controlled-launcher/approval-relay.mjs +19 -0
- package/examples/controlled-launcher/approver.mjs +27 -0
- package/examples/controlled-launcher/authorizer.mjs +73 -0
- package/examples/controlled-launcher/bridge-client.mjs +8 -0
- package/examples/controlled-launcher/destination.mjs +18 -0
- package/examples/controlled-launcher/executor.mjs +74 -0
- package/examples/controlled-launcher/kernel-authority/acceptance.mjs +627 -0
- package/examples/controlled-launcher/kernel-authority/broker.mjs +83 -0
- package/examples/controlled-launcher/kernel-authority/derive.mjs +12 -0
- package/examples/controlled-launcher/kernel-authority/executor.mjs +105 -0
- package/examples/controlled-launcher/kernel-authority/reconcile.mjs +43 -0
- package/examples/controlled-launcher/kernel-authority/shim.mjs +38 -0
- package/examples/controlled-launcher/kernel-authority/signing-provider.mjs +137 -0
- package/examples/controlled-launcher/kernel-authority/strix-approver.mjs +73 -0
- package/examples/controlled-launcher/lib.mjs +63 -0
- package/examples/controlled-launcher/make-config.mjs +16 -0
- package/examples/controlled-launcher/proxy-host.mjs +19 -0
- package/examples/controlled-launcher/reconcile.mjs +30 -0
- package/examples/controlled-launcher/shim.mjs +32 -0
- package/examples/github-reference/README.md +1 -1
- package/examples/github-reference/acceptance.mjs +10 -3
- package/examples/github-reference/claims-matrix.md +3 -3
- package/examples/github-reference/package-lock.json +48 -44
- package/examples/github-reference/package.json +4 -4
- package/examples/github-reference/reuse-inventory.md +4 -4
- package/examples/synthetic-server/proxy-config.json +16 -0
- package/examples/synthetic-server/quickstart.mjs +98 -0
- package/examples/synthetic-server/server.mjs +54 -0
- package/package.json +5 -4
- package/test/synthetic-quickstart.test.mjs +44 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// STRIX AUTHORITY BROKER. Replaces the test-key authorizer. It mints NOTHING and holds NO signing key.
|
|
3
|
+
// It (1) verifies that a person's Guard-signed approval covers the exact request, then (2) asks the real
|
|
4
|
+
// Strix kernel for execution authority for that one action through @strixgov/execution-authority, and
|
|
5
|
+
// (3) holds the kernel-signed grant for the shim to claim. Authority is the kernel's: this process cannot
|
|
6
|
+
// widen, extend, or re-bind a grant, and the executor redeems it centrally, not here.
|
|
7
|
+
//
|
|
8
|
+
// The kernel's own approvers (distinct people, each signing SE v2 events with their OWN key) are NOT performed
|
|
9
|
+
// here: when the kernel answers APPROVAL_REQUIRED this process only WAITS (bounded) and asks again. It holds no
|
|
10
|
+
// approver secret, no approver key, and no way to approve. (Phase 4B-1.)
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import crypto from "node:crypto";
|
|
14
|
+
import { StrixExecutionAuthorityClient, buildProposal, canonicalSha256 } from "@strixgov/execution-authority";
|
|
15
|
+
import { serve, payloadHash, sha256hex, pubFromX } from "../lib.mjs";
|
|
16
|
+
|
|
17
|
+
const [registerSock, claimSock, stateDir, approverPubFile, readyFile] = process.argv.slice(2);
|
|
18
|
+
const SERVICE_TOKEN = process.env.STRIX_SERVICE_TOKEN;
|
|
19
|
+
if (!SERVICE_TOKEN) { console.error("broker: STRIX_SERVICE_TOKEN required"); process.exit(2); }
|
|
20
|
+
delete process.env.STRIX_SERVICE_TOKEN;
|
|
21
|
+
const WAIT_MS = Number(process.env.BROKER_APPROVAL_WAIT_MS ?? 25000);
|
|
22
|
+
const ready = JSON.parse(fs.readFileSync(readyFile, "utf8"));
|
|
23
|
+
const client = new StrixExecutionAuthorityClient({ baseUrl: ready.baseUrl, token: SERVICE_TOKEN, strixTenantId: ready.strixTenantId, issuer: ready.issuer });
|
|
24
|
+
for (const d of ["unclaimed", "claimed", "registered"]) fs.mkdirSync(path.join(stateDir, d), { recursive: true, mode: 0o700 });
|
|
25
|
+
const approver = JSON.parse(fs.readFileSync(approverPubFile, "utf8"));
|
|
26
|
+
const approverKey = pubFromX(approver.publicKey);
|
|
27
|
+
const log = (o) => fs.appendFileSync(path.join(stateDir, "broker-log.jsonl"), JSON.stringify({ t: new Date().toISOString(), ...o }) + "\n");
|
|
28
|
+
const preimage = ({ requestId, requestSha256, approved, decidedAt, kid }) =>
|
|
29
|
+
["strix-guard-approval/v1", `request:${requestId}`, `requestSha256:${requestSha256}`, `approved:${approved === true ? "true" : "false"}`, `decidedAt:${decidedAt}`, `kid:${kid}`].join("\n");
|
|
30
|
+
|
|
31
|
+
import { CAPABILITY, ROUTE, STANDING, consequenceIdFor } from "./derive.mjs";
|
|
32
|
+
export const proposalFor = (requestId, args, tenant) => buildProposal({
|
|
33
|
+
proposalId: "xp:" + requestId.replace(/[^A-Za-z0-9._:-]/g, "-").slice(0, 100),
|
|
34
|
+
tenantId: tenant, principalId: "agent:controlled-launcher-demo", action: CAPABILITY,
|
|
35
|
+
consequenceId: consequenceIdFor(args), executionRoute: ROUTE,
|
|
36
|
+
payloadCommitment: canonicalSha256(args), currentStateCommitment: canonicalSha256(STANDING),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
serve(registerSock, async (m) => {
|
|
40
|
+
if (m.op !== "register") return { ok: false, error: "UNKNOWN_OP" };
|
|
41
|
+
const { requestText, response } = m;
|
|
42
|
+
let req; try { req = JSON.parse(requestText); } catch { return { ok: false, error: "REQUEST_NOT_JSON" }; }
|
|
43
|
+
if (!response || response.approved !== true) return { ok: false, error: "NOT_APPROVED" };
|
|
44
|
+
if (response.kid !== approver.kid) return { ok: false, error: "UNKNOWN_APPROVER_KEY" };
|
|
45
|
+
if (response.requestSha256 !== sha256hex(requestText)) return { ok: false, error: "REQUEST_HASH_MISMATCH" };
|
|
46
|
+
const ok = crypto.verify(null, Buffer.from(preimage({ requestId: req.requestId, requestSha256: response.requestSha256, approved: true, decidedAt: response.decidedAt, kid: response.kid }), "utf8"), approverKey, Buffer.from(response.signature ?? "", "base64url"));
|
|
47
|
+
if (!ok) { log({ ev: "register-refused", reason: "BAD_SIGNATURE", requestId: req.requestId }); return { ok: false, error: "BAD_SIGNATURE" }; }
|
|
48
|
+
if (Date.now() - Date.parse(response.decidedAt) > 5 * 60_000) return { ok: false, error: "APPROVAL_STALE" };
|
|
49
|
+
try { fs.writeFileSync(path.join(stateDir, "registered", req.requestId), "", { flag: "wx" }); }
|
|
50
|
+
catch { log({ ev: "register-refused", reason: "APPROVAL_ALREADY_USED", requestId: req.requestId }); return { ok: false, error: "APPROVAL_ALREADY_USED" }; }
|
|
51
|
+
const args = req.invocation?.args ?? {};
|
|
52
|
+
if (req.capability?.id !== CAPABILITY) return { ok: false, error: "CAPABILITY_NOT_BROKERED" };
|
|
53
|
+
const proposal = proposalFor(req.requestId, args, ready.consumerTenantId);
|
|
54
|
+
let ev;
|
|
55
|
+
try {
|
|
56
|
+
ev = await client.evaluate(proposal, { minimumApprovals: 1 });
|
|
57
|
+
if (ev.status === "APPROVAL_REQUIRED") {
|
|
58
|
+
log({ ev: "approval-required", requestId: req.requestId, strixDecisionId: ev.strixDecisionId, approvalsRequired: ev.approvalsRequired, approvalsGranted: ev.approvalsGranted });
|
|
59
|
+
const until = Date.now() + WAIT_MS;
|
|
60
|
+
while (ev.status === "APPROVAL_REQUIRED" && Date.now() < until) { await new Promise((r) => setTimeout(r, 400)); ev = await client.evaluate(proposal, { minimumApprovals: 1 }); }
|
|
61
|
+
}
|
|
62
|
+
} catch (e) { log({ ev: "kernel-unavailable", requestId: req.requestId, code: e.code }); return { ok: false, error: "KERNEL_UNAVAILABLE", detail: e.code ?? e.message }; }
|
|
63
|
+
if (ev.status !== "GRANTED") { log({ ev: "not-granted", requestId: req.requestId, status: ev.status, reason: ev.reasonCode }); return { ok: false, error: "NOT_GRANTED", detail: ev.status + (ev.reasonCode ? ":" + ev.reasonCode : "") }; }
|
|
64
|
+
const g = ev.grant.payload;
|
|
65
|
+
fs.writeFileSync(path.join(stateDir, "unclaimed", `${payloadHash(args).slice(7)}.${g.grantId.replace(/[^A-Za-z0-9]/g, "")}.json`), JSON.stringify({ grant: ev.grant, proposal }), { mode: 0o600 });
|
|
66
|
+
log({ ev: "granted", requestId: req.requestId, grantId: g.grantId, strixDecisionId: ev.strixDecisionId, payloadCommitment: g.payloadCommitment, expiresAt: g.expiresAt });
|
|
67
|
+
return { ok: true, grantId: g.grantId, strixDecisionId: ev.strixDecisionId, payloadCommitment: g.payloadCommitment };
|
|
68
|
+
}, 0o660);
|
|
69
|
+
|
|
70
|
+
// Hand-off only (not enforcement): the shim claims the grant it will carry to the executor. The executor
|
|
71
|
+
// redeems it at the kernel; this claim being single-use is hygiene, the kernel's consume is the authority.
|
|
72
|
+
serve(claimSock, async (m) => {
|
|
73
|
+
if (m.op !== "claim" || typeof m.payloadHash !== "string" || !/^sha256:[0-9a-f]{64}$/.test(m.payloadHash)) return { ok: false, error: "BAD_CLAIM" };
|
|
74
|
+
const prefix = m.payloadHash.slice(7) + ".";
|
|
75
|
+
for (const name of fs.readdirSync(path.join(stateDir, "unclaimed")).filter((n) => n.startsWith(prefix))) {
|
|
76
|
+
try { fs.renameSync(path.join(stateDir, "unclaimed", name), path.join(stateDir, "claimed", name)); } catch { continue; }
|
|
77
|
+
const h = JSON.parse(fs.readFileSync(path.join(stateDir, "claimed", name), "utf8"));
|
|
78
|
+
log({ ev: "claimed", grantId: h.grant.payload.grantId, payloadHash: m.payloadHash });
|
|
79
|
+
return { ok: true, grant: h.grant, proposal: h.proposal };
|
|
80
|
+
}
|
|
81
|
+
log({ ev: "claim-none", payloadHash: m.payloadHash });
|
|
82
|
+
return { ok: false, error: "NO_AUTHORIZATION" };
|
|
83
|
+
}, 0o660);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// The execution identity for a create_branch call, derived ONLY from the arguments about to run.
|
|
2
|
+
// The broker uses it to build the proposal; the executor uses it again, independently, from the bytes it will
|
|
3
|
+
// actually execute, so a grant is spendable only on that exact consequence.
|
|
4
|
+
import { canonicalSha256 } from "@strixgov/execution-authority";
|
|
5
|
+
export const CAPABILITY = "mcp.github.create_branch";
|
|
6
|
+
export const ROUTE = "mcp:github.create_branch@controlled-executor";
|
|
7
|
+
export const STANDING = { estate: "synthetic/fixture", executor: "controlled-launcher-reference", policy: "v1" };
|
|
8
|
+
export const consequenceIdFor = (a) => `repo:${a.owner}.${a.repo}:branch:${a.branch}`.replace(/[^A-Za-z0-9._:-]/g, "-");
|
|
9
|
+
export const executionFor = (args, { tenantId, principalId, proposalId }) => ({
|
|
10
|
+
tenantId, principalId, proposalId, action: CAPABILITY, consequenceId: consequenceIdFor(args), executionRoute: ROUTE,
|
|
11
|
+
payloadCommitment: canonicalSha256(args), currentStateCommitment: canonicalSha256(STANDING),
|
|
12
|
+
});
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Credential-holding destination executor (separate OS identity), kernel-authority edition.
|
|
3
|
+
// It accepts reads (own credential) and ONE write, create_branch, only under a real Strix-issued grant:
|
|
4
|
+
// 1 INTENT is fsynced before anything is presented to the kernel;
|
|
5
|
+
// 2 trust is the kernel's published key set + signed revocation document, PINNED to the key/issuer/tenant
|
|
6
|
+
// this executor was provisioned with (a fetched document alone is never trusted);
|
|
7
|
+
// 3 the grant is verified locally (issuer, key identity, lifecycle, signature, window, lifetime) and then
|
|
8
|
+
// REDEEMED at the kernel for the exact execution derived here from the bytes about to run: the kernel
|
|
9
|
+
// consumes it atomically, once, and refuses any difference. A locally valid signature never permits execution;
|
|
10
|
+
// 4 CONSUMED and STARTED are fsynced before the destination call; the outcome is signed and reported to the kernel.
|
|
11
|
+
// An indeterminate consume, an unavailable kernel, or a crash never triggers a retry: the attempt stays
|
|
12
|
+
// UNKNOWN until read-back (reconcileRedemption) and the independent observer resolve it.
|
|
13
|
+
import fs from "node:fs";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import crypto from "node:crypto";
|
|
16
|
+
import { StrixExecutionAuthorityClient } from "@strixgov/execution-authority";
|
|
17
|
+
import { serve, appendDurable, signCanonical, jwkPublic } from "../lib.mjs";
|
|
18
|
+
import { CAPABILITY, executionFor } from "./derive.mjs";
|
|
19
|
+
|
|
20
|
+
const [sock, stateDir, pinnedFile, destUrl] = process.argv.slice(2);
|
|
21
|
+
const credential = process.env.EXECUTOR_TOKEN, serviceToken = process.env.STRIX_SERVICE_TOKEN;
|
|
22
|
+
if (!credential) { console.error("executor: EXECUTOR_TOKEN missing"); process.exit(2); }
|
|
23
|
+
delete process.env.EXECUTOR_TOKEN; delete process.env.STRIX_SERVICE_TOKEN;
|
|
24
|
+
const pinned = JSON.parse(fs.readFileSync(pinnedFile, "utf8")); // provisioning record, root-owned
|
|
25
|
+
const client = new StrixExecutionAuthorityClient({ baseUrl: pinned.baseUrl, token: serviceToken ?? "unset", strixTenantId: pinned.strixTenantId, issuer: pinned.issuer });
|
|
26
|
+
const attemptsFile = path.join(stateDir, "attempts.jsonl"), outcomesFile = path.join(stateDir, "outcomes.jsonl");
|
|
27
|
+
const keyFile = path.join(stateDir, "outcome-key.pem");
|
|
28
|
+
let priv;
|
|
29
|
+
if (fs.existsSync(keyFile)) priv = crypto.createPrivateKey(fs.readFileSync(keyFile));
|
|
30
|
+
else { const kp = crypto.generateKeyPairSync("ed25519"); fs.writeFileSync(keyFile, kp.privateKey.export({ format: "pem", type: "pkcs8" }), { mode: 0o400 }); priv = kp.privateKey; }
|
|
31
|
+
const OUT_KID = "executor-outcome-test-1";
|
|
32
|
+
fs.writeFileSync(path.join(stateDir, "outcome-jwks.json"), JSON.stringify({ keys: [jwkPublic(crypto.createPublicKey(priv), OUT_KID)] }, null, 2), { mode: 0o644 });
|
|
33
|
+
const readJsonl = (f) => (fs.existsSync(f) ? fs.readFileSync(f, "utf8").trim().split("\n").filter(Boolean).map(JSON.parse) : []);
|
|
34
|
+
const at = () => new Date().toISOString();
|
|
35
|
+
const rec = (o) => appendDurable(attemptsFile, { ...o, at: at() });
|
|
36
|
+
function writeOutcome(o) {
|
|
37
|
+
const payload = { schemaVersion: 1, outcomeId: "out_" + crypto.randomBytes(8).toString("hex"), ...o, at: at() };
|
|
38
|
+
appendDurable(outcomesFile, { ...payload, signingKeyId: OUT_KID, signature: signCanonical(payload, priv) });
|
|
39
|
+
return payload;
|
|
40
|
+
}
|
|
41
|
+
const TERMINAL = /^(COMPLETED_|REFUSED|RECOVERED_)/;
|
|
42
|
+
|
|
43
|
+
// Crash recovery: an INTENT with no terminal record is reconciled against the KERNEL's own store. It is never retried.
|
|
44
|
+
{
|
|
45
|
+
const all = readJsonl(attemptsFile);
|
|
46
|
+
for (const a of all.filter((x) => x.state === "INTENT")) {
|
|
47
|
+
if (all.some((x) => x.attemptId === a.attemptId && TERMINAL.test(x.state))) continue;
|
|
48
|
+
const started = all.some((x) => x.attemptId === a.attemptId && x.state === "STARTED");
|
|
49
|
+
const r = await client.reconcileRedemption(a.grantId).catch((e) => ({ status: "UNKNOWN", code: e.code ?? "ERR" }));
|
|
50
|
+
if (r.status === "CONSUMED") {
|
|
51
|
+
rec({ attemptId: a.attemptId, state: "RECOVERED_UNKNOWN", grantId: a.grantId, note: "kernel recorded consumption; destination effect unknown; reconcile by observation; never retried" });
|
|
52
|
+
writeOutcome({ attemptId: a.attemptId, grantId: a.grantId, payloadCommitment: a.payloadCommitment, status: "UNKNOWN", destinationStatus: null });
|
|
53
|
+
await client.reportOutcome(a.grantId, { outcome: "UNKNOWN", handlerEntered: started, reportedBy: "executor:recovery", detail: "executor restarted before an outcome was recorded" }).catch(() => {});
|
|
54
|
+
} else if (r.status === "NOT_CONSUMED") rec({ attemptId: a.attemptId, state: "RECOVERED_NOT_CONSUMED", grantId: a.grantId, note: "kernel shows the grant unspent; nothing executed" });
|
|
55
|
+
else rec({ attemptId: a.attemptId, state: "RECOVERED_UNRESOLVED", grantId: a.grantId, note: `kernel state not established (${r.status}); stays unknown` });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const refuse = (error, detail) => ({ ok: false, error, ...(detail ? { detail } : {}) });
|
|
60
|
+
const result = (text, isError = false) => ({ ok: true, content: [{ type: "text", text }], ...(isError ? { isError } : {}) });
|
|
61
|
+
const dest = (method, url, body) => fetch(destUrl + url, { method, headers: { authorization: "Bearer " + credential }, body: body ? JSON.stringify(body) : undefined });
|
|
62
|
+
|
|
63
|
+
// Trust is pinned: the kernel's published set must contain exactly the provisioned key, active, for the provisioned issuer.
|
|
64
|
+
async function pinnedTrust(grant) {
|
|
65
|
+
const trust = await client.loadTrust(); // throws StrixUnavailableError: key status / revocation not established => fail closed
|
|
66
|
+
const k = trust.keys.find((x) => x.kid === pinned.pinnedAuthorityKey.kid);
|
|
67
|
+
const spki = Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), Buffer.from(pinned.pinnedAuthorityKey.x, "base64url")]).toString("base64");
|
|
68
|
+
if (trust.issuer !== pinned.issuer) return "PINNED_ISSUER_MISMATCH";
|
|
69
|
+
if (!k || k.publicKeySpkiBase64 !== spki) return "PINNED_KEY_ABSENT_OR_CHANGED";
|
|
70
|
+
if (k.status !== "active") return "PINNED_KEY_NOT_ACTIVE:" + k.status;
|
|
71
|
+
if (grant?.payload?.signingKeyId !== pinned.pinnedAuthorityKey.kid) return "GRANT_KEY_NOT_PINNED";
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
serve(sock, async (m) => {
|
|
76
|
+
const { tool, args = {}, grant } = m;
|
|
77
|
+
if (tool === "get_file_contents" || tool === "list_branches") { const r = await dest("GET", "/repos/synthetic/fixture/branches"); return result(JSON.stringify(await r.json())); }
|
|
78
|
+
if (tool !== "create_branch") return refuse("TOOL_NOT_PERMITTED_BY_EXECUTOR", tool);
|
|
79
|
+
if (!grant?.payload) return refuse("AUTHORIZATION_REQUIRED");
|
|
80
|
+
if (args.owner !== "synthetic" || args.repo !== "fixture") return refuse("SCOPE_REFUSED", "owner/repo outside declared estate");
|
|
81
|
+
const gp = grant.payload;
|
|
82
|
+
const attemptId = "att_" + crypto.randomBytes(8).toString("hex");
|
|
83
|
+
const execution = executionFor(args, { tenantId: pinned.consumerTenantId, principalId: gp.principalId, proposalId: gp.proposalId });
|
|
84
|
+
const ref = "refs/heads/" + args.branch;
|
|
85
|
+
rec({ attemptId, state: "INTENT", grantId: gp.grantId, payloadCommitment: execution.payloadCommitment, ref, tool });
|
|
86
|
+
let pin;
|
|
87
|
+
try { pin = await pinnedTrust(grant); } catch (e) { rec({ attemptId, state: "REFUSED_TRUST_UNAVAILABLE", grantId: gp.grantId, code: e.code ?? "TRUST" }); return refuse("TRUST_NOT_ESTABLISHED", e.code ?? e.message); }
|
|
88
|
+
if (pin) { rec({ attemptId, state: "REFUSED_PINNING", grantId: gp.grantId, reason: pin }); return refuse("TRUST_PIN_REFUSED", pin); }
|
|
89
|
+
const red = await client.redeem(grant, execution, "executor:" + attemptId);
|
|
90
|
+
if (red.status === "REFUSE") { rec({ attemptId, state: "REFUSED_BY_" + red.refusedBy.toUpperCase(), grantId: gp.grantId, reasonCode: red.reasonCode, mismatched: red.mismatchedFields }); return refuse("AUTHORIZATION_REFUSED", `${red.refusedBy}:${red.reasonCode}`); }
|
|
91
|
+
if (red.status === "UNAVAILABLE") { rec({ attemptId, state: "REFUSED_KERNEL_UNAVAILABLE", grantId: gp.grantId, code: red.code }); return refuse("KERNEL_UNAVAILABLE", red.code); }
|
|
92
|
+
if (red.status === "REDEMPTION_INDETERMINATE") { rec({ attemptId, state: "REDEMPTION_INDETERMINATE", grantId: gp.grantId, code: red.code, note: "kernel may have consumed; NOT executed; NOT retried; reconcile" }); return refuse("REDEMPTION_INDETERMINATE", red.code); }
|
|
93
|
+
if (red.status !== "PERMIT") return refuse("UNEXPECTED_REDEMPTION_RESULT");
|
|
94
|
+
rec({ attemptId, state: "CONSUMED", grantId: gp.grantId, strixDecisionId: red.strixDecisionId, consumedAt: red.consumedAt });
|
|
95
|
+
if (process.env.EXECUTOR_TEST_CRASH_AFTER_CONSUME === "1") process.exit(98);
|
|
96
|
+
rec({ attemptId, state: "STARTED", grantId: gp.grantId, payloadCommitment: execution.payloadCommitment, ref, tool });
|
|
97
|
+
if (process.env.EXECUTOR_TEST_CRASH_AFTER_STARTED === "1") process.exit(99);
|
|
98
|
+
let status = null, st = "FAILED";
|
|
99
|
+
try { const r = await dest("POST", "/repos/synthetic/fixture/git/refs", { ref }); status = r.status; st = r.status === 201 ? "SUCCEEDED" : "REJECTED"; } catch { st = "UNKNOWN"; }
|
|
100
|
+
const o = writeOutcome({ attemptId, grantId: gp.grantId, strixDecisionId: red.strixDecisionId, payloadCommitment: execution.payloadCommitment, status: st, destinationStatus: status });
|
|
101
|
+
rec({ attemptId, state: "COMPLETED_" + st });
|
|
102
|
+
const kernelReport = await client.reportOutcome(gp.grantId, { outcome: st === "SUCCEEDED" ? "EXECUTED" : st === "UNKNOWN" ? "UNKNOWN" : "FAILED", handlerEntered: true, observedConsequence: { destinationStatus: status, ref }, reportedBy: "executor:" + attemptId }).catch((e) => ({ status: "UNREPORTED", error: e.code ?? e.message }));
|
|
103
|
+
rec({ attemptId, state: "KERNEL_OUTCOME_" + kernelReport.status, evidenceId: kernelReport.evidenceId ?? null });
|
|
104
|
+
return result(JSON.stringify({ status: st, destinationStatus: status, attemptId, kernelOutcome: kernelReport.status }), st !== "SUCCEEDED");
|
|
105
|
+
}, 0o660);
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Independent observer (separate OS identity, read-only destination credential), kernel-authority edition.
|
|
3
|
+
// Three evidence classes stay SEPARATE in every row:
|
|
4
|
+
// authorization - the kernel's consumption fact (CONSUMED record; never evidence the branch exists)
|
|
5
|
+
// executorReport - the executor's signed outcome (self-report)
|
|
6
|
+
// observation - the destination state this process read itself
|
|
7
|
+
// Every attempt that reached CONSUMED gets a row; attempts refused before consumption are counted, not judged.
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import crypto from "node:crypto";
|
|
11
|
+
import { canonicalizeJSON } from "../lib.mjs";
|
|
12
|
+
const [stateDir, destUrl, out] = process.argv.slice(2);
|
|
13
|
+
const jl = (f) => (fs.existsSync(f) ? fs.readFileSync(f, "utf8").trim().split("\n").filter(Boolean).map(JSON.parse) : []);
|
|
14
|
+
const pub = crypto.createPublicKey({ key: JSON.parse(fs.readFileSync(path.join(stateDir, "outcome-jwks.json"), "utf8")).keys[0], format: "jwk" });
|
|
15
|
+
const attempts = jl(path.join(stateDir, "attempts.jsonl")), outcomes = jl(path.join(stateDir, "outcomes.jsonl"));
|
|
16
|
+
let observed = null, observationError = null;
|
|
17
|
+
try {
|
|
18
|
+
const r = await fetch(destUrl + "/repos/synthetic/fixture/branches", { headers: { authorization: "Bearer " + process.env.OBSERVER_TOKEN } });
|
|
19
|
+
observed = r.ok ? (await r.json()).branches ?? [] : null; if (!r.ok) observationError = "HTTP " + r.status;
|
|
20
|
+
} catch (e) { observationError = String(e.message ?? e); }
|
|
21
|
+
const rows = [];
|
|
22
|
+
for (const c of attempts.filter((x) => x.state === "CONSUMED")) {
|
|
23
|
+
const intent = attempts.find((x) => x.attemptId === c.attemptId && x.state === "INTENT");
|
|
24
|
+
const o = outcomes.filter((x) => x.attemptId === c.attemptId).at(-1);
|
|
25
|
+
let sigOk = null;
|
|
26
|
+
if (o) { const { signingKeyId, signature, ...payload } = o; sigOk = crypto.verify(null, Buffer.from(canonicalizeJSON(payload), "utf8"), pub, Buffer.from(signature, "base64url")); }
|
|
27
|
+
const reported = o?.status ?? "NO_OUTCOME_RECORDED";
|
|
28
|
+
let verdict;
|
|
29
|
+
if (observed === null) verdict = "OUTCOME_REMAINS_UNKNOWN_NO_OBSERVATION"; // missing destination observation => never resolved
|
|
30
|
+
else {
|
|
31
|
+
const present = observed.includes(intent.ref);
|
|
32
|
+
if (reported === "SUCCEEDED") verdict = present ? "RECONCILED_CONSISTENT" : "INCONSISTENT_REPORTED_SUCCESS_NOT_OBSERVED";
|
|
33
|
+
else if (reported === "UNKNOWN" || reported === "NO_OUTCOME_RECORDED") verdict = present ? "RESOLVED_BY_OBSERVATION_EXECUTED" : "RESOLVED_BY_OBSERVATION_NOT_EXECUTED";
|
|
34
|
+
else verdict = present ? "INCONSISTENT_REPORTED_FAILURE_BUT_OBSERVED" : "RECONCILED_CONSISTENT";
|
|
35
|
+
}
|
|
36
|
+
rows.push({ attemptId: c.attemptId, grantId: c.grantId, ref: intent.ref, authorization: { kernelConsumed: true, consumedAt: c.consumedAt }, executorReported: reported, outcomeSignatureValid: sigOk, destinationObservedRefPresent: observed === null ? null : observed.includes(intent.ref), verdict });
|
|
37
|
+
}
|
|
38
|
+
const consumedIds = new Set(attempts.filter((x) => x.state === "CONSUMED").map((x) => x.attemptId));
|
|
39
|
+
const consumedRefs = new Set(attempts.filter((x) => x.state === "INTENT" && consumedIds.has(x.attemptId)).map((x) => x.ref));
|
|
40
|
+
const unattributed = (observed ?? []).filter((b) => b !== "main" && !consumedRefs.has(b));
|
|
41
|
+
const refused = attempts.filter((x) => /^REFUSED|^REDEMPTION_INDETERMINATE/.test(x.state));
|
|
42
|
+
fs.writeFileSync(out, JSON.stringify({ observedAt: new Date().toISOString(), observationError, observedBranches: observed, attempts: rows, refusedBeforeConsumption: refused.map((r) => ({ attemptId: r.attemptId, state: r.state, reason: r.reasonCode ?? r.reason ?? r.code ?? null })), destinationBranchesWithNoConsumedAttempt: unattributed }, null, 1));
|
|
43
|
+
console.log(JSON.stringify({ attempts: rows.length, inconsistent: rows.filter((x) => x.verdict.startsWith("INCONSISTENT")).length, unattributed, observationError }));
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Credential-free MCP upstream used by the published proxy. Holds NO downstream credential and NO signing key.
|
|
3
|
+
// For writes it claims the kernel-issued grant for the exact payload from the broker and forwards to the executor.
|
|
4
|
+
// If it is subverted it can only ask the executor, which still requires a valid exact-payload token.
|
|
5
|
+
import readline from "node:readline";
|
|
6
|
+
import { call, payloadHash } from "../lib.mjs";
|
|
7
|
+
const [execSock, claimSock] = process.argv.slice(2);
|
|
8
|
+
const tools = [
|
|
9
|
+
{ name: "get_file_contents", description: "Read repository contents (synthetic).", inputSchema: { type: "object", properties: {} } },
|
|
10
|
+
{ name: "list_branches", description: "List branches.", inputSchema: { type: "object", properties: {} } },
|
|
11
|
+
{ name: "create_branch", description: "Create a branch.", inputSchema: { type: "object", properties: { owner: { type: "string" }, repo: { type: "string" }, branch: { type: "string" }, from_branch: { type: "string" } }, required: ["owner", "repo", "branch"] } },
|
|
12
|
+
{ name: "merge_pull_request", description: "Merge a pull request.", inputSchema: { type: "object", properties: { owner: { type: "string" }, repo: { type: "string" }, pull_number: { type: "number" } }, required: ["owner", "repo", "pull_number"] } },
|
|
13
|
+
];
|
|
14
|
+
const send = (m) => process.stdout.write(JSON.stringify(m) + "\n");
|
|
15
|
+
const text = (t, isError = false) => ({ content: [{ type: "text", text: t }], ...(isError ? { isError } : {}) });
|
|
16
|
+
async function toolCall(name, args = {}) {
|
|
17
|
+
let grant;
|
|
18
|
+
if (name === "create_branch") {
|
|
19
|
+
// The proxy releases the call as soon as the person's signed response exists; the broker is still obtaining the
|
|
20
|
+
// kernel grant, so poll briefly. No grant within the window means no authority: the executor refuses.
|
|
21
|
+
let c = { ok: false };
|
|
22
|
+
for (let i = 0; i < 40 && !c.ok; i++) {
|
|
23
|
+
c = await call(claimSock, { op: "claim", payloadHash: payloadHash(args), capabilityId: "mcp.github.create_branch" }).catch((e) => ({ ok: false, error: String(e.message) }));
|
|
24
|
+
if (!c.ok) await new Promise((r) => setTimeout(r, 250));
|
|
25
|
+
}
|
|
26
|
+
grant = c.ok ? c.grant : undefined;
|
|
27
|
+
}
|
|
28
|
+
const r = await call(execSock, { tool: name, args, grant }).catch((e) => ({ ok: false, error: "EXECUTOR_UNREACHABLE", detail: e.message }));
|
|
29
|
+
return r.ok ? { content: r.content, ...(r.isError ? { isError: true } : {}) } : text(`refused: ${r.error}${r.detail ? " (" + r.detail + ")" : ""}`, true);
|
|
30
|
+
}
|
|
31
|
+
readline.createInterface({ input: process.stdin }).on("line", async (line) => {
|
|
32
|
+
let m; try { m = JSON.parse(line); } catch { return; }
|
|
33
|
+
if (m.id === undefined) return;
|
|
34
|
+
if (m.method === "initialize") return send({ jsonrpc: "2.0", id: m.id, result: { protocolVersion: m.params?.protocolVersion ?? "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "controlled-launcher-shim", version: "0.0.1" } } });
|
|
35
|
+
if (m.method === "tools/list") return send({ jsonrpc: "2.0", id: m.id, result: { tools } });
|
|
36
|
+
if (m.method === "tools/call") return send({ jsonrpc: "2.0", id: m.id, result: await toolCall(m.params?.name, m.params?.arguments) });
|
|
37
|
+
send({ jsonrpc: "2.0", id: m.id, error: { code: -32601, message: "method not found" } });
|
|
38
|
+
});
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* DEVELOPMENT signing provider for Strix authority grants (Phase 4B-2).
|
|
4
|
+
*
|
|
5
|
+
* A separate process, run as its own OS user, that holds the authority private
|
|
6
|
+
* key(s) in a 0700 keystore and exposes exactly two operations on a unix
|
|
7
|
+
* socket: public-keys and sign. There is NO export, NO get-private-key, NO
|
|
8
|
+
* generate-over-socket operation: key lifecycle (init / rotate / revoke) is an
|
|
9
|
+
* operator CLI acting on the keystore directly, not something the kernel can
|
|
10
|
+
* ask for.
|
|
11
|
+
*
|
|
12
|
+
* It is NOT a generic Ed25519 oracle. `sign` refuses unless the message is the
|
|
13
|
+
* canonical JSON of a Strix authority artifact whose schemaVersion is on the
|
|
14
|
+
* allow-list, whose issuer is this provider's configured issuer, and whose
|
|
15
|
+
* signingKeyId equals the key being asked for. It refuses revoked keys and keys
|
|
16
|
+
* outside their validity window.
|
|
17
|
+
*
|
|
18
|
+
* DEV ONLY: file-held keys, no HSM/KMS, no audit-grade logging. See the 4B-2
|
|
19
|
+
* evidence note for the exact limitations.
|
|
20
|
+
*
|
|
21
|
+
* signing-provider.mjs init --dir D --issuer URL --kid K [--days N]
|
|
22
|
+
* signing-provider.mjs rotate --dir D --kid K2 [--days N] (old key -> retired)
|
|
23
|
+
* signing-provider.mjs revoke --dir D --kid K
|
|
24
|
+
* signing-provider.mjs serve --dir D --socket S [--group G] [--delay-ms N]
|
|
25
|
+
*/
|
|
26
|
+
import crypto from 'node:crypto';
|
|
27
|
+
import fs from 'node:fs';
|
|
28
|
+
import net from 'node:net';
|
|
29
|
+
import path from 'node:path';
|
|
30
|
+
|
|
31
|
+
const ALLOWED_SCHEMAS = new Set([
|
|
32
|
+
'strix-execution-authority-v1',
|
|
33
|
+
'strix-rcm-authority-grant-v1',
|
|
34
|
+
'strix-rcm-authority-grant-v2',
|
|
35
|
+
'strix-authority-revocation-v1',
|
|
36
|
+
'strix-authority-revocation-v2',
|
|
37
|
+
]);
|
|
38
|
+
const MAX_REQUEST_BYTES = 64 * 1024;
|
|
39
|
+
|
|
40
|
+
const args = (() => { const o = {}; const a = process.argv.slice(3); for (let i = 0; i < a.length; i += 2) o[a[i].replace(/^--/, '')] = a[i + 1]; return o; })();
|
|
41
|
+
const cmd = process.argv[2];
|
|
42
|
+
|
|
43
|
+
function keystore(dir) { return path.join(dir, 'keys'); }
|
|
44
|
+
function readKeys(dir) {
|
|
45
|
+
const d = keystore(dir);
|
|
46
|
+
if (!fs.existsSync(d)) return [];
|
|
47
|
+
return fs.readdirSync(d).filter((f) => f.endsWith('.json')).map((f) => JSON.parse(fs.readFileSync(path.join(d, f), 'utf8')));
|
|
48
|
+
}
|
|
49
|
+
function writeKey(dir, rec) {
|
|
50
|
+
fs.mkdirSync(keystore(dir), { recursive: true, mode: 0o700 });
|
|
51
|
+
const f = path.join(keystore(dir), `${rec.kid}.json`);
|
|
52
|
+
const tmp = `${f}.tmp`;
|
|
53
|
+
fs.writeFileSync(tmp, JSON.stringify(rec), { mode: 0o600 });
|
|
54
|
+
fs.renameSync(tmp, f);
|
|
55
|
+
}
|
|
56
|
+
function meta(dir) { return JSON.parse(fs.readFileSync(path.join(dir, 'meta.json'), 'utf8')); }
|
|
57
|
+
function publicX(rec) {
|
|
58
|
+
const pub = crypto.createPublicKey(crypto.createPrivateKey({ key: Buffer.from(rec.pkcs8, 'base64'), format: 'der', type: 'pkcs8' }));
|
|
59
|
+
return pub.export({ format: 'jwk' }).x;
|
|
60
|
+
}
|
|
61
|
+
function newKey(kid, days) {
|
|
62
|
+
const { privateKey } = crypto.generateKeyPairSync('ed25519');
|
|
63
|
+
const now = new Date();
|
|
64
|
+
return {
|
|
65
|
+
kid, status: 'active',
|
|
66
|
+
pkcs8: privateKey.export({ format: 'der', type: 'pkcs8' }).toString('base64'),
|
|
67
|
+
notBefore: new Date(now.getTime() - 60_000).toISOString(),
|
|
68
|
+
notAfter: new Date(now.getTime() + Number(days ?? 30) * 86400_000).toISOString(),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (cmd === 'init') {
|
|
73
|
+
fs.mkdirSync(args.dir, { recursive: true, mode: 0o700 });
|
|
74
|
+
fs.writeFileSync(path.join(args.dir, 'meta.json'), JSON.stringify({ issuer: args.issuer }), { mode: 0o600 });
|
|
75
|
+
const rec = newKey(args.kid, args.days);
|
|
76
|
+
writeKey(args.dir, rec);
|
|
77
|
+
console.log(JSON.stringify({ kid: rec.kid, x: publicX(rec), notBefore: rec.notBefore, notAfter: rec.notAfter }));
|
|
78
|
+
} else if (cmd === 'rotate') {
|
|
79
|
+
for (const k of readKeys(args.dir)) if (k.status === 'active') writeKey(args.dir, { ...k, status: 'retired' });
|
|
80
|
+
const rec = newKey(args.kid, args.days);
|
|
81
|
+
writeKey(args.dir, rec);
|
|
82
|
+
console.log(JSON.stringify({ kid: rec.kid, x: publicX(rec), notBefore: rec.notBefore, notAfter: rec.notAfter }));
|
|
83
|
+
} else if (cmd === 'revoke') {
|
|
84
|
+
const k = readKeys(args.dir).find((x) => x.kid === args.kid);
|
|
85
|
+
if (!k) { console.error('unknown kid'); process.exit(1); }
|
|
86
|
+
writeKey(args.dir, { ...k, status: 'revoked', revokedAt: new Date().toISOString() });
|
|
87
|
+
console.log(JSON.stringify({ kid: k.kid, status: 'revoked' }));
|
|
88
|
+
} else if (cmd === 'serve') {
|
|
89
|
+
const delay = Number(args['delay-ms'] ?? 0);
|
|
90
|
+
try { fs.unlinkSync(args.socket); } catch { /* none */ }
|
|
91
|
+
const server = net.createServer((sock) => {
|
|
92
|
+
let buf = '';
|
|
93
|
+
sock.setTimeout(5000, () => sock.destroy());
|
|
94
|
+
sock.on('error', () => sock.destroy());
|
|
95
|
+
sock.on('data', (d) => {
|
|
96
|
+
buf += d.toString('utf8');
|
|
97
|
+
if (buf.length > MAX_REQUEST_BYTES) { reply(sock, { ok: false, error: 'request too large' }); return; }
|
|
98
|
+
const nl = buf.indexOf('\n');
|
|
99
|
+
if (nl === -1) return;
|
|
100
|
+
let req;
|
|
101
|
+
try { req = JSON.parse(buf.slice(0, nl)); } catch { reply(sock, { ok: false, error: 'malformed request' }); return; }
|
|
102
|
+
setTimeout(() => reply(sock, handle(req)), delay);
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
server.listen(args.socket, () => {
|
|
106
|
+
fs.chmodSync(args.socket, 0o660);
|
|
107
|
+
if (args.group) { try { fs.chownSync(args.socket, process.getuid(), Number(args.group)); } catch { /* best effort */ } }
|
|
108
|
+
console.log(JSON.stringify({ listening: args.socket }));
|
|
109
|
+
});
|
|
110
|
+
function handle(req) {
|
|
111
|
+
if (!req || typeof req !== 'object') return { ok: false, error: 'malformed request' };
|
|
112
|
+
const keys = readKeys(args.dir);
|
|
113
|
+
if (req.op === 'public-keys') {
|
|
114
|
+
return { ok: true, issuer: meta(args.dir).issuer, keys: keys.map((k) => ({ kid: k.kid, x: publicX(k), status: k.status, notBefore: k.notBefore, notAfter: k.notAfter })) };
|
|
115
|
+
}
|
|
116
|
+
if (req.op !== 'sign') return { ok: false, error: 'unknown operation' };
|
|
117
|
+
const rec = keys.find((k) => k.kid === req.kid);
|
|
118
|
+
if (!rec) return { ok: false, error: 'unknown key' };
|
|
119
|
+
if (rec.status === 'revoked') return { ok: false, error: 'key revoked' };
|
|
120
|
+
if (rec.status !== 'active') return { ok: false, error: 'key not active (retired keys never sign new artifacts)' };
|
|
121
|
+
const now = Date.now();
|
|
122
|
+
if (now < Date.parse(rec.notBefore) || now >= Date.parse(rec.notAfter)) return { ok: false, error: 'key outside validity window' };
|
|
123
|
+
if (typeof req.message !== 'string') return { ok: false, error: 'no message' };
|
|
124
|
+
const bytes = Buffer.from(req.message, 'base64');
|
|
125
|
+
let doc;
|
|
126
|
+
try { doc = JSON.parse(bytes.toString('utf8')); } catch { return { ok: false, error: 'message is not an authority artifact' }; }
|
|
127
|
+
if (!doc || typeof doc !== 'object' || !ALLOWED_SCHEMAS.has(doc.schemaVersion)) return { ok: false, error: 'schemaVersion not permitted' };
|
|
128
|
+
if (doc.issuer !== meta(args.dir).issuer) return { ok: false, error: 'issuer not permitted' };
|
|
129
|
+
if (doc.signingKeyId !== rec.kid) return { ok: false, error: 'signingKeyId does not match requested key' };
|
|
130
|
+
const key = crypto.createPrivateKey({ key: Buffer.from(rec.pkcs8, 'base64'), format: 'der', type: 'pkcs8' });
|
|
131
|
+
return { ok: true, kid: rec.kid, signature: crypto.sign(null, bytes, key).toString('base64url') };
|
|
132
|
+
}
|
|
133
|
+
function reply(sock, obj) { sock.end(JSON.stringify(obj) + '\n'); }
|
|
134
|
+
} else {
|
|
135
|
+
console.error('usage: signing-provider.mjs init|rotate|revoke|serve ...');
|
|
136
|
+
process.exit(2);
|
|
137
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// STRIX APPROVER TOOL (scratch identity). One OS user runs this per approver; the private key is generated HERE
|
|
3
|
+
// and never leaves this user's directory. It does exactly what an approver's own client does:
|
|
4
|
+
// 1. keygen - make an Ed25519 key; publish only the PUBLIC JWK (the operator registers it).
|
|
5
|
+
// 2. info - read what is being approved (decision, frozen params, hash the signature will cover).
|
|
6
|
+
// 3. approve - the console-approval act (DEV STAND-IN for a console session, per-approver secret).
|
|
7
|
+
// 4. sign - sign an SE v2 approval event over the decision AS IT NOW STANDS with the OWN key and submit it
|
|
8
|
+
// to the real ingest endpoint (HMAC with the service secret, as the route requires).
|
|
9
|
+
// The canonical payload below is a SECOND implementation of buildApprovalCanonicalPayload (13 ordered fields,
|
|
10
|
+
// JSON.stringify). tests/authority/strix-approver-parity.test.ts pins byte equality with the real builder, and the
|
|
11
|
+
// kernel's ingest re-derives and verifies every signature, so divergence is a refusal, never a silent accept.
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import crypto from "node:crypto";
|
|
15
|
+
|
|
16
|
+
const [cmd, dir, ...rest] = process.argv.slice(2);
|
|
17
|
+
const flag = (n) => { const i = rest.indexOf("--" + n); return i === -1 ? undefined : rest[i + 1]; };
|
|
18
|
+
const out = (o) => console.log(JSON.stringify(o));
|
|
19
|
+
|
|
20
|
+
if (cmd === "keygen") {
|
|
21
|
+
const principal = flag("principal");
|
|
22
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._@-]{0,127}$/.test(principal ?? "")) { out({ ok: false, error: "BAD_PRINCIPAL" }); process.exit(2); }
|
|
23
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
24
|
+
const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519");
|
|
25
|
+
const spki = publicKey.export({ type: "spki", format: "der" });
|
|
26
|
+
const kid = `${principal}-key-${crypto.randomUUID()}`;
|
|
27
|
+
const jwk = { kty: "OKP", crv: "Ed25519", x: spki.subarray(spki.length - 32).toString("base64url"), kid };
|
|
28
|
+
fs.writeFileSync(path.join(dir, "private.key"), privateKey.export({ type: "pkcs8", format: "der" }).toString("base64"), { mode: 0o400 });
|
|
29
|
+
fs.writeFileSync(path.join(dir, "identity.json"), JSON.stringify({ principal, kid }), { mode: 0o644 });
|
|
30
|
+
fs.writeFileSync(path.join(dir, "public.jwk.json"), JSON.stringify({ principal, jwk }), { mode: 0o644 });
|
|
31
|
+
out({ ok: true, principal, kid });
|
|
32
|
+
process.exit(0);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const SECRET = process.env.STRIX_APPROVER_SECRET, HMAC_KEY = process.env.STRIX_INGEST_HMAC_KEY;
|
|
36
|
+
delete process.env.STRIX_APPROVER_SECRET; delete process.env.STRIX_INGEST_HMAC_KEY;
|
|
37
|
+
const id = JSON.parse(fs.readFileSync(path.join(dir, "identity.json"), "utf8"));
|
|
38
|
+
const baseUrl = flag("base"), tenant = flag("tenant"), decisionId = flag("decision");
|
|
39
|
+
const H = { "x-dev-approver-id": id.principal, "x-dev-approver-secret": SECRET ?? "" };
|
|
40
|
+
const info = async () => { const r = await fetch(`${baseUrl}/dev/decision/${encodeURIComponent(decisionId)}`, { headers: H }); return { status: r.status, body: await r.json().catch(() => ({})) }; };
|
|
41
|
+
|
|
42
|
+
if (cmd === "info") { const i = await info(); out({ ok: i.status === 200, ...i.body }); process.exit(i.status === 200 ? 0 : 1); }
|
|
43
|
+
|
|
44
|
+
if (cmd === "approve") {
|
|
45
|
+
const expect = flag("expect-payload"); const i = await info();
|
|
46
|
+
if (i.status !== 200) { out({ ok: false, error: "NO_DECISION" }); process.exit(1); }
|
|
47
|
+
if (expect && !JSON.stringify(i.body.actionParams).includes(expect)) { out({ ok: false, error: "REFUSED_NOT_WHAT_I_WAS_ASKED_TO_APPROVE" }); process.exit(1); }
|
|
48
|
+
const r = await fetch(`${baseUrl}/dev/console-approve/${encodeURIComponent(decisionId)}`, { method: "POST", headers: H });
|
|
49
|
+
out({ ok: r.status === 200, http: r.status, principal: id.principal }); process.exit(r.status === 200 ? 0 : 1);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (cmd === "sign") {
|
|
53
|
+
const expect = flag("expect-payload"); const i = await info();
|
|
54
|
+
if (i.status !== 200) { out({ ok: false, error: "NO_DECISION" }); process.exit(1); }
|
|
55
|
+
if (expect && !JSON.stringify(i.body.actionParams).includes(expect)) { out({ ok: false, error: "REFUSED_NOT_WHAT_I_WAS_ASKED_TO_APPROVE" }); process.exit(1); }
|
|
56
|
+
const seq = flag("seq") !== undefined ? Number(flag("seq")) : i.body.nextSequence;
|
|
57
|
+
const prev = seq === 0 ? null : (flag("prev") ?? i.body.previousPayloadHash);
|
|
58
|
+
const kid = flag("use-kid") ?? id.kid; // `use-kid` exists only so a test can present a forged identity
|
|
59
|
+
const evidenceHash = flag("evidence-hash") ?? i.body.evidenceHash;
|
|
60
|
+
const approvalRequestId = flag("request-id") ?? i.body.approvalRequestId;
|
|
61
|
+
const chain = crypto.createHash("sha256").update(prev === null ? `origin:${approvalRequestId}` : prev).digest("hex");
|
|
62
|
+
const f = { approvalSchemaVersion: "2", approvalRequestId, evidenceHash, sequenceNumber: seq, approverPrincipalId: flag("as-principal") ?? id.principal, approverPrincipalType: "OPERATOR", keyType: "SESSION", keyId: kid, channel: "IN_BAND", stepUpPerformedAt: null, occurredAt: new Date().toISOString(), approvalChainHash: chain, tenantId: tenant };
|
|
63
|
+
const canonical = JSON.stringify({ approvalSchemaVersion: f.approvalSchemaVersion, approvalRequestId: f.approvalRequestId, evidenceHash: f.evidenceHash, sequenceNumber: f.sequenceNumber, approverPrincipalId: f.approverPrincipalId, approverPrincipalType: f.approverPrincipalType, keyType: f.keyType, keyId: f.keyId, channel: f.channel, stepUpPerformedAt: f.stepUpPerformedAt, occurredAt: f.occurredAt, approvalChainHash: f.approvalChainHash, tenantId: f.tenantId });
|
|
64
|
+
const key = crypto.createPrivateKey({ key: Buffer.from(fs.readFileSync(flag("key-file") ?? path.join(dir, "private.key"), "utf8").trim(), "base64"), format: "der", type: "pkcs8" });
|
|
65
|
+
const signature = crypto.sign(null, Buffer.from(canonical, "utf8"), key).toString("base64url");
|
|
66
|
+
const payloadHash = crypto.createHash("sha256").update(Buffer.from(canonical, "utf8")).digest("hex");
|
|
67
|
+
const body = JSON.stringify({ records: [{ ...f, approvalSignature: signature }] });
|
|
68
|
+
const r = await fetch(`${baseUrl}/api/v1/approval-events/ingest`, { method: "POST", headers: { "content-type": "application/json", "x-strix-signature": crypto.createHmac("sha256", HMAC_KEY ?? "").update(body).digest("hex") }, body });
|
|
69
|
+
const j = await r.json().catch(() => ({}));
|
|
70
|
+
out({ ok: r.status === 200 && j.inserted === 1, http: r.status, outcome: j.results?.[0]?.ingest_outcome, payloadHash, seq, principal: id.principal });
|
|
71
|
+
process.exit(0);
|
|
72
|
+
}
|
|
73
|
+
out({ ok: false, error: "UNKNOWN_COMMAND" }); process.exit(2);
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Shared helpers for the controlled-launcher reference. Reference code: small, dependency-light, reviewable.
|
|
2
|
+
import net from "node:net";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import crypto from "node:crypto";
|
|
6
|
+
import { canonicalizeJSON } from "@strixgov/mcp-token-validator";
|
|
7
|
+
|
|
8
|
+
export { canonicalizeJSON };
|
|
9
|
+
export const sha256hex = (s) => crypto.createHash("sha256").update(s, "utf8").digest("hex");
|
|
10
|
+
// payloadHash per mcp-mode-3-enforcement-v1 §4: "sha256:" + SHA-256(SCJ v1(args))
|
|
11
|
+
export const payloadHash = (args) => "sha256:" + sha256hex(canonicalizeJSON(args ?? {}));
|
|
12
|
+
|
|
13
|
+
/** One-request-per-connection JSON-line RPC over a unix socket. */
|
|
14
|
+
export function serve(sockPath, handler, mode = 0o660) {
|
|
15
|
+
try { fs.unlinkSync(sockPath); } catch {}
|
|
16
|
+
const srv = net.createServer((c) => {
|
|
17
|
+
let buf = "";
|
|
18
|
+
c.on("error", () => {});
|
|
19
|
+
c.on("data", async (d) => {
|
|
20
|
+
buf += d;
|
|
21
|
+
if (!buf.includes("\n")) return;
|
|
22
|
+
let out;
|
|
23
|
+
try { out = await handler(JSON.parse(buf.split("\n")[0])); }
|
|
24
|
+
catch (e) { out = { ok: false, error: "HANDLER_ERROR", detail: String(e?.message ?? e) }; }
|
|
25
|
+
c.end(JSON.stringify(out) + "\n");
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
srv.listen(sockPath, () => { try { fs.chmodSync(sockPath, mode); } catch {} });
|
|
29
|
+
return srv;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function call(sockPath, msg, timeoutMs = 15000) {
|
|
33
|
+
return new Promise((resolve, reject) => {
|
|
34
|
+
const c = net.connect(sockPath);
|
|
35
|
+
let buf = "";
|
|
36
|
+
const t = setTimeout(() => { c.destroy(); reject(new Error("TIMEOUT")); }, timeoutMs);
|
|
37
|
+
c.on("error", (e) => { clearTimeout(t); reject(e); });
|
|
38
|
+
c.on("connect", () => c.write(JSON.stringify(msg) + "\n"));
|
|
39
|
+
c.on("data", (d) => { buf += d; });
|
|
40
|
+
c.on("end", () => { clearTimeout(t); try { resolve(JSON.parse(buf.trim())); } catch { reject(new Error("BAD_REPLY")); } });
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Append a JSON line and fsync before returning (write-ahead accounting). */
|
|
45
|
+
export function appendDurable(file, obj) {
|
|
46
|
+
const fd = fs.openSync(file, "a", 0o644);
|
|
47
|
+
try { fs.writeSync(fd, JSON.stringify(obj) + "\n"); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Atomic single-use marker: O_EXCL create + fsync file and directory. true = first use; false = already used. */
|
|
51
|
+
export function burnOnce(dir, name) {
|
|
52
|
+
if (!/^[A-Za-z0-9._-]{8,128}$/.test(name)) throw new Error("bad marker name");
|
|
53
|
+
let fd;
|
|
54
|
+
try { fd = fs.openSync(path.join(dir, name), "wx", 0o644); }
|
|
55
|
+
catch (e) { if (e.code === "EEXIST") return false; throw e; }
|
|
56
|
+
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
57
|
+
const dfd = fs.openSync(dir, "r"); try { fs.fsyncSync(dfd); } finally { fs.closeSync(dfd); }
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const signCanonical = (obj, privateKey) => crypto.sign(null, Buffer.from(canonicalizeJSON(obj), "utf8"), privateKey).toString("base64url");
|
|
62
|
+
export const jwkPublic = (publicKeyObj, kid) => ({ kid, ...publicKeyObj.export({ format: "jwk" }) });
|
|
63
|
+
export const pubFromX = (x) => crypto.createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x }, format: "jwk" });
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Builds the trusted proxy config with @strixgov/guard's own buildProxyConfig (signed approvals), then points the
|
|
2
|
+
// upstream at the credential-free shim. Run at setup time by the launcher (root); the result is root-owned, read-only.
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import { buildProxyConfig } from "@strixgov/guard";
|
|
5
|
+
const [out, approverPubFile, proxyApprovalsDir, storePath, shimPath, execSock, claimSock, timeoutMs] = process.argv.slice(2);
|
|
6
|
+
const approver = JSON.parse(fs.readFileSync(approverPubFile, "utf8"));
|
|
7
|
+
const cfg = buildProxyConfig({
|
|
8
|
+
serverId: "github", entry: { command: "@modelcontextprotocol/server-github", args: [] },
|
|
9
|
+
paths: { approvalsDir: proxyApprovalsDir, receiptsDir: storePath }, approver,
|
|
10
|
+
});
|
|
11
|
+
cfg.upstream = { command: process.execPath, args: [shimPath, execSock, claimSock] };
|
|
12
|
+
cfg.storagePath = storePath;
|
|
13
|
+
cfg.approval.timeoutMs = Number(timeoutMs);
|
|
14
|
+
cfg.approval.pollIntervalMs = 100;
|
|
15
|
+
fs.writeFileSync(out, JSON.stringify(cfg, null, 2), { mode: 0o644 });
|
|
16
|
+
console.log(JSON.stringify({ capabilities: cfg.capabilities, policy: cfg.policy, requireSignedResponse: cfg.approval.requireSignedResponse }));
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Trusted proxy service (separate OS identity). Accepts MCP connections on a unix socket and, per connection,
|
|
3
|
+
// runs the PUBLISHED @strixgov/mcp-proxy with a root-owned config. The client controls only the bytes it sends:
|
|
4
|
+
// not the executable, the config, the environment, or the upstream command.
|
|
5
|
+
import net from "node:net";
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
const [sock, proxyBin, configFile] = process.argv.slice(2);
|
|
9
|
+
try { fs.unlinkSync(sock); } catch {}
|
|
10
|
+
const srv = net.createServer((c) => {
|
|
11
|
+
const child = spawn(process.execPath, [proxyBin, "--config", configFile], {
|
|
12
|
+
stdio: ["pipe", "pipe", "inherit"],
|
|
13
|
+
env: { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: process.env.HOME ?? "/nonexistent", NODE_ENV: "production" }, // scrubbed: nothing from the client or host env
|
|
14
|
+
});
|
|
15
|
+
c.pipe(child.stdin); child.stdout.pipe(c);
|
|
16
|
+
c.on("close", () => child.kill()); child.on("exit", () => c.destroy());
|
|
17
|
+
c.on("error", () => child.kill()); child.stdin.on("error", () => {});
|
|
18
|
+
});
|
|
19
|
+
srv.listen(sock, () => fs.chmodSync(sock, 0o660));
|