-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
250 lines (227 loc) · 9.75 KB
/
Copy pathserver.js
File metadata and controls
250 lines (227 loc) · 9.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#!/usr/bin/env node
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import {
verifyArtifact,
canonicalHash,
bytesToHex,
base64urlToBytes,
} from '@veritasacta/artifacts';
const __dirname = dirname(fileURLToPath(import.meta.url));
function readJsonInput(path, raw) {
if (raw && raw.trim()) return JSON.parse(raw);
if (path && path.trim()) return JSON.parse(readFileSync(path, 'utf-8'));
throw new Error('Provide either raw JSON input or a file path.');
}
function isPassportEnvelope(obj) {
return obj && typeof obj === 'object'
&& obj.payload && typeof obj.payload === 'object'
&& obj.signature && typeof obj.signature === 'object'
&& typeof obj.signature.sig === 'string';
}
function convertPassportToV1(envelope) {
return {
artifact: { ...envelope.payload, signature: envelope.signature.sig },
kid: envelope.signature.kid || null,
format: 'passport',
};
}
function deriveEmbeddedKey(artifact) {
const payload = artifact?.payload || artifact;
if (payload?.public_key && typeof payload.public_key === 'string' && payload.public_key.length === 64) {
return payload.public_key;
}
return null;
}
function formatArtifact(artifact) {
if (isPassportEnvelope(artifact)) return 'passport';
if (artifact?.v === 2) return 'v2';
return 'v1';
}
function getArtifactCore(artifact) {
if (isPassportEnvelope(artifact)) {
return convertPassportToV1(artifact);
}
return {
artifact,
kid: artifact?.kid || null,
format: formatArtifact(artifact),
};
}
function resolveBundleKeyMap(bundle) {
const keys = bundle?.verification?.signing_keys || [];
const map = new Map();
for (const jwk of keys) {
if (jwk?.kid && jwk?.x) {
map.set(jwk.kid, bytesToHex(base64urlToBytes(jwk.x)));
}
}
return map;
}
function verifySingle(artifact, publicKeyHex) {
const core = getArtifactCore(artifact);
const key = publicKeyHex || deriveEmbeddedKey(artifact);
if (!key) {
return {
valid: false,
error: 'no_public_key',
type: artifact?.type || core.artifact?.type || 'unknown',
format: core.format,
kid: core.kid,
issuer: artifact?.issuer || null,
hash: null,
};
}
const result = verifyArtifact(core.artifact, key);
const unsigned = { ...core.artifact };
delete unsigned.signature;
return {
valid: !!result.valid,
error: result.valid ? null : (result.error || 'invalid_signature'),
type: artifact?.type || core.artifact?.type || 'unknown',
format: core.format,
kid: core.kid,
issuer: artifact?.issuer || null,
hash: canonicalHash(unsigned),
};
}
function verifyBundle(bundle) {
if (!bundle?.receipts || !Array.isArray(bundle.receipts)) {
throw new Error('Invalid bundle: missing receipts array');
}
const keyMap = resolveBundleKeyMap(bundle);
let passed = 0;
const receipts = bundle.receipts.map((receipt, index) => {
const key = receipt?.kid ? keyMap.get(receipt.kid) : deriveEmbeddedKey(receipt);
const result = verifySingle(receipt, key || null);
if (result.valid) passed += 1;
return {
index,
type: result.type,
kid: result.kid,
valid: result.valid,
error: result.error,
};
});
return {
valid: passed === bundle.receipts.length,
total: bundle.receipts.length,
passed,
failed: bundle.receipts.length - passed,
receipts,
};
}
function explainArtifact(artifact) {
const core = getArtifactCore(artifact);
const payload = artifact?.payload || core.artifact?.payload || core.artifact;
const payloadKeys = payload && typeof payload === 'object'
? Object.keys(payload).filter((k) => k !== 'signature').sort()
: [];
return {
type: artifact?.type || core.artifact?.type || 'unknown',
format: core.format,
issuer: artifact?.issuer || null,
kid: core.kid,
issued_at: artifact?.issued_at || artifact?.timestamp || payload?.issued_at || null,
payload_keys: payloadKeys,
};
}
function loadSelfTestArtifacts() {
return {
receipt: JSON.parse(readFileSync(join(__dirname, 'samples', 'sample-receipt.json'), 'utf-8')),
bundle: JSON.parse(readFileSync(join(__dirname, 'samples', 'sample-bundle.json'), 'utf-8')),
publicKeyHex: 'd75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a',
};
}
function textResult(value) {
return { content: [{ type: 'text', text: JSON.stringify(value, null, 2) }] };
}
const server = new McpServer({
name: 'scopeblind-verify',
version: '0.1.4',
description: 'Offline verification MCP server for ScopeBlind and Veritas Acta artifacts.',
});
server.tool(
'self_test',
"Run the packaged offline self-test: verifies a known-good sample receipt and sample audit bundle shipped with the server. Read-only and deterministic; no network calls and no ScopeBlind servers are contacted. Returns JSON { ok: boolean, receipt: { valid, type, format, kid, issuer, hash }, bundle: { valid, total, passed, failed }, note }. If the packaged samples cannot be read it returns { ok: false, error }. Call this first to prove the verifier works before verifying your own artifacts.",
{},
{ title: 'Offline self-test', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
async () => {
try {
const { receipt, bundle, publicKeyHex } = loadSelfTestArtifacts();
const receiptResult = verifySingle(receipt, publicKeyHex);
const bundleResult = verifyBundle(bundle);
return textResult({
ok: receiptResult.valid && bundleResult.valid,
receipt: receiptResult,
bundle: {
valid: bundleResult.valid,
total: bundleResult.total,
passed: bundleResult.passed,
failed: bundleResult.failed,
},
note: 'No ScopeBlind servers were contacted.',
});
} catch (error) {
return textResult({ ok: false, error: error.message });
}
}
);
server.tool(
'verify_receipt',
"Verify the Ed25519 signature of a single signed artifact (decision receipt, restraint receipt, passport envelope, or other Veritas Acta artifact; v1, v2, and passport formats are auto-detected). Read-only and fully offline. Provide the artifact as raw JSON (artifact_json) or a local file path (path); artifact_json wins if both are given. Verification uses public_key_hex when provided, otherwise a key embedded in the artifact payload; if neither exists it returns valid: false with error 'no_public_key' rather than guessing. Returns JSON { valid: boolean, error: string|null (e.g. 'invalid_signature', 'no_public_key'), type, format ('v1'|'v2'|'passport'), kid, issuer, hash (SHA-256 over the canonical unsigned bytes) }. Unparseable input returns { ok: false, error }.",
{
artifact_json: z.string().optional().describe('Raw JSON artifact string.'),
path: z.string().optional().describe('Path to a local JSON artifact file.'),
public_key_hex: z.string().optional().describe('Optional Ed25519 public key hex (64 bytes as hex).'),
},
{ title: 'Verify one signed artifact', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
async (args) => {
try {
const artifact = readJsonInput(args.path, args.artifact_json);
return textResult(verifySingle(artifact, args.public_key_hex || null));
} catch (error) {
return textResult({ ok: false, error: error.message });
}
}
);
server.tool(
'verify_bundle',
"Verify every receipt in a ScopeBlind audit bundle offline, using the bundle's embedded verification keys (the JWK set at verification.signing_keys, matched to each receipt by kid). Read-only; no network calls. Provide the bundle as raw JSON (bundle_json) or a local file path (path). Returns JSON { valid: boolean (true only if every receipt verifies), total, passed, failed, receipts: [{ index, type, kid, valid, error }] }. A document without a receipts array returns { ok: false, error }. For a single artifact, or to supply an external key, use verify_receipt instead.",
{
bundle_json: z.string().optional().describe('Raw JSON bundle string.'),
path: z.string().optional().describe('Path to a local JSON bundle file.'),
},
{ title: 'Verify an audit bundle', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
async (args) => {
try {
const bundle = readJsonInput(args.path, args.bundle_json);
return textResult(verifyBundle(bundle));
} catch (error) {
return textResult({ ok: false, error: error.message });
}
}
);
server.tool(
'explain_artifact',
"Inspect a signed artifact WITHOUT verifying it: reports what the artifact claims to be so you can choose the right verification tool and key. Requires no key; read-only and offline. Provide raw JSON (artifact_json) or a local file path (path). Returns JSON { type, format ('v1'|'v2'|'passport'), issuer, kid, issued_at, payload_keys (sorted, signature excluded) }. It performs no signature check, so a well-formed forgery will explain cleanly; use verify_receipt to check authenticity.",
{
artifact_json: z.string().optional().describe('Raw JSON artifact string.'),
path: z.string().optional().describe('Path to a local JSON artifact file.'),
},
{ title: 'Inspect an artifact without verifying', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
async (args) => {
try {
const artifact = readJsonInput(args.path, args.artifact_json);
return textResult(explainArtifact(artifact));
} catch (error) {
return textResult({ ok: false, error: error.message });
}
}
);
const transport = new StdioServerTransport();
await server.connect(transport);