@rohan-protocol/mcp 0.8.1 → 0.8.2
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/README.md +49 -74
- package/dist/cli.d.ts +6 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +304 -0
- package/dist/cli.js.map +1 -0
- package/dist/mcp-app.d.ts +136 -0
- package/dist/mcp-app.d.ts.map +1 -0
- package/dist/mcp-app.js +401 -0
- package/dist/mcp-app.js.map +1 -0
- package/dist/server.d.ts +35 -34
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +49 -255
- package/dist/server.js.map +1 -1
- package/package.json +6 -2
- package/server.json +0 -46
- package/smithery.yaml +0 -23
- package/src/firewall.ts +0 -37
- package/src/gateway.ts +0 -59
- package/src/identity/handshake.ts +0 -82
- package/src/identity/keystore.ts +0 -385
- package/src/index.ts +0 -2
- package/src/server.ts +0 -310
- package/tests/firewall.test.js +0 -75
- package/tests/gateway.test.js +0 -27
- package/tests/identity.test.js +0 -170
- package/tsconfig.json +0 -17
package/src/identity/keystore.ts
DELETED
|
@@ -1,385 +0,0 @@
|
|
|
1
|
-
import fs, { constants as fsConstants } from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import os from 'node:os';
|
|
4
|
-
import { createPrivateKey, createPublicKey, randomBytes } from 'node:crypto';
|
|
5
|
-
import {
|
|
6
|
-
createDidKey,
|
|
7
|
-
generateEd25519KeyPair,
|
|
8
|
-
InMemoryEd25519Signer,
|
|
9
|
-
type AgentSigner,
|
|
10
|
-
} from '@rohan-protocol/sdk';
|
|
11
|
-
|
|
12
|
-
const ED25519_PKCS8_PREFIX = new Uint8Array([
|
|
13
|
-
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
|
|
14
|
-
]);
|
|
15
|
-
const ED25519_SPKI_PREFIX = new Uint8Array([
|
|
16
|
-
0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
|
|
17
|
-
]);
|
|
18
|
-
const MAX_KEYSTORE_SIZE = 4096;
|
|
19
|
-
|
|
20
|
-
export interface AgentKeystoreData {
|
|
21
|
-
did: string;
|
|
22
|
-
privateKeyHex: string;
|
|
23
|
-
createdAt: number;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export interface LoadedAgentIdentity {
|
|
27
|
-
signer: AgentSigner;
|
|
28
|
-
did: string;
|
|
29
|
-
source: 'env' | 'filesystem' | 'auto-provisioned';
|
|
30
|
-
filePath?: string;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export class KeystoreResolutionError extends Error {
|
|
34
|
-
readonly code?: string;
|
|
35
|
-
|
|
36
|
-
constructor(message: string, options?: { cause?: unknown; code?: string }) {
|
|
37
|
-
super(message, { cause: options?.cause });
|
|
38
|
-
this.name = 'KeystoreResolutionError';
|
|
39
|
-
this.code = options?.code;
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function isErrno(error: unknown, code: string): boolean {
|
|
44
|
-
return typeof error === 'object' && error !== null && 'code' in error &&
|
|
45
|
-
(error as NodeJS.ErrnoException).code === code;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function currentUid(): number | undefined {
|
|
49
|
-
return typeof process.getuid === 'function' ? process.getuid() : undefined;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function ensurePrivateDirectory(directoryPath: string): void {
|
|
53
|
-
try {
|
|
54
|
-
fs.mkdirSync(directoryPath, { recursive: true, mode: 0o700 });
|
|
55
|
-
} catch (error) {
|
|
56
|
-
throw new KeystoreResolutionError(
|
|
57
|
-
`Could not create keystore directory "${directoryPath}".`,
|
|
58
|
-
{ cause: error }
|
|
59
|
-
);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
let directoryStat: fs.Stats;
|
|
63
|
-
try {
|
|
64
|
-
directoryStat = fs.lstatSync(directoryPath);
|
|
65
|
-
} catch (error) {
|
|
66
|
-
throw new KeystoreResolutionError(
|
|
67
|
-
`Could not inspect keystore directory "${directoryPath}".`,
|
|
68
|
-
{ cause: error }
|
|
69
|
-
);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
if (directoryStat.isSymbolicLink() || !directoryStat.isDirectory()) {
|
|
73
|
-
throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore parent must be a real directory, not a symlink.');
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const uid = currentUid();
|
|
77
|
-
if (uid !== undefined && directoryStat.uid !== uid) {
|
|
78
|
-
throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore directory is not owned by the current user.');
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
if (process.platform !== 'win32') {
|
|
82
|
-
try {
|
|
83
|
-
fs.chmodSync(directoryPath, 0o700);
|
|
84
|
-
directoryStat = fs.lstatSync(directoryPath);
|
|
85
|
-
} catch (error) {
|
|
86
|
-
throw new KeystoreResolutionError('SECURITY_VIOLATION: Could not secure keystore directory permissions.', { cause: error });
|
|
87
|
-
}
|
|
88
|
-
if ((directoryStat.mode & 0o777) !== 0o700) {
|
|
89
|
-
throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore directory must have mode 0700.');
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
async function derivePublicKey(privateKey: Uint8Array): Promise<Uint8Array> {
|
|
95
|
-
if (privateKey.length !== 32) {
|
|
96
|
-
throw new KeystoreResolutionError('Ed25519 private seed must be exactly 32 bytes.');
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
const pkcs8 = new Uint8Array(ED25519_PKCS8_PREFIX.length + privateKey.length);
|
|
100
|
-
pkcs8.set(ED25519_PKCS8_PREFIX);
|
|
101
|
-
pkcs8.set(privateKey, ED25519_PKCS8_PREFIX.length);
|
|
102
|
-
try {
|
|
103
|
-
const privateKeyObject = createPrivateKey({
|
|
104
|
-
key: Buffer.from(pkcs8.buffer, pkcs8.byteOffset, pkcs8.byteLength),
|
|
105
|
-
format: 'der',
|
|
106
|
-
type: 'pkcs8',
|
|
107
|
-
});
|
|
108
|
-
const publicDer = createPublicKey(privateKeyObject).export({ format: 'der', type: 'spki' });
|
|
109
|
-
const publicBytes = Buffer.isBuffer(publicDer) ? publicDer : Buffer.from(publicDer);
|
|
110
|
-
if (
|
|
111
|
-
publicBytes.length !== ED25519_SPKI_PREFIX.length + 32 ||
|
|
112
|
-
!ED25519_SPKI_PREFIX.every((byte, index) => publicBytes[index] === byte)
|
|
113
|
-
) {
|
|
114
|
-
throw new KeystoreResolutionError('Derived Ed25519 public key has an invalid encoding.');
|
|
115
|
-
}
|
|
116
|
-
return new Uint8Array(publicBytes.subarray(ED25519_SPKI_PREFIX.length));
|
|
117
|
-
} finally {
|
|
118
|
-
pkcs8.fill(0);
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function createSigner(publicKey: Uint8Array, privateKey: Uint8Array): InMemoryEd25519Signer {
|
|
123
|
-
try {
|
|
124
|
-
return new InMemoryEd25519Signer(publicKey, privateKey);
|
|
125
|
-
} finally {
|
|
126
|
-
publicKey.fill(0);
|
|
127
|
-
privateKey.fill(0);
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
function readKeystoreContents(filePath: string): string {
|
|
132
|
-
let pathStat: fs.Stats;
|
|
133
|
-
try {
|
|
134
|
-
pathStat = fs.lstatSync(filePath);
|
|
135
|
-
} catch (error) {
|
|
136
|
-
if (isErrno(error, 'ENOENT')) {
|
|
137
|
-
throw new KeystoreResolutionError(`Keystore file not found: ${filePath}`, { cause: error, code: 'ENOENT' });
|
|
138
|
-
}
|
|
139
|
-
throw new KeystoreResolutionError(`Could not inspect keystore file "${filePath}".`, { cause: error });
|
|
140
|
-
}
|
|
141
|
-
if (pathStat.isSymbolicLink()) {
|
|
142
|
-
throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore file must not be a symbolic link.');
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
let fd: number;
|
|
146
|
-
try {
|
|
147
|
-
const noFollow = fsConstants.O_NOFOLLOW ?? 0;
|
|
148
|
-
fd = fs.openSync(filePath, fsConstants.O_RDONLY | noFollow);
|
|
149
|
-
} catch (error) {
|
|
150
|
-
if (isErrno(error, 'ENOENT')) {
|
|
151
|
-
throw new KeystoreResolutionError(`Keystore file not found: ${filePath}`, { cause: error, code: 'ENOENT' });
|
|
152
|
-
}
|
|
153
|
-
if (isErrno(error, 'ELOOP')) {
|
|
154
|
-
throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore file must not be a symbolic link.', { cause: error });
|
|
155
|
-
}
|
|
156
|
-
throw new KeystoreResolutionError(`Could not open keystore file "${filePath}".`, { cause: error });
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
try {
|
|
160
|
-
const stat = fs.fstatSync(fd);
|
|
161
|
-
const currentPathStat = fs.lstatSync(filePath);
|
|
162
|
-
if (
|
|
163
|
-
currentPathStat.isSymbolicLink() ||
|
|
164
|
-
currentPathStat.dev !== stat.dev ||
|
|
165
|
-
currentPathStat.ino !== stat.ino ||
|
|
166
|
-
!stat.isFile() ||
|
|
167
|
-
stat.nlink !== 1
|
|
168
|
-
) {
|
|
169
|
-
throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore must be a regular file with one link.');
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
const uid = currentUid();
|
|
173
|
-
if (uid !== undefined && stat.uid !== uid) {
|
|
174
|
-
throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore file is not owned by the current user.');
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
if (stat.size > MAX_KEYSTORE_SIZE) {
|
|
178
|
-
throw new KeystoreResolutionError('CORRUPTED_KEYSTORE: Keystore file exceeds the maximum supported size.');
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
if (process.platform !== 'win32') {
|
|
182
|
-
if ((stat.mode & 0o777) !== 0o600) {
|
|
183
|
-
try {
|
|
184
|
-
fs.fchmodSync(fd, 0o600);
|
|
185
|
-
} catch (error) {
|
|
186
|
-
throw new KeystoreResolutionError('SECURITY_VIOLATION: Could not secure keystore permissions (expected 0600).', { cause: error });
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
const securedStat = fs.fstatSync(fd);
|
|
190
|
-
if ((securedStat.mode & 0o777) !== 0o600) {
|
|
191
|
-
throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore file must have mode 0600.');
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
return fs.readFileSync(fd, 'utf8');
|
|
196
|
-
} finally {
|
|
197
|
-
fs.closeSync(fd);
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
export async function loadKeystoreFile(filePath: string): Promise<InMemoryEd25519Signer> {
|
|
202
|
-
ensurePrivateDirectory(path.dirname(filePath));
|
|
203
|
-
const contents = readKeystoreContents(filePath);
|
|
204
|
-
|
|
205
|
-
let parsed: unknown;
|
|
206
|
-
try {
|
|
207
|
-
parsed = JSON.parse(contents);
|
|
208
|
-
} catch (error) {
|
|
209
|
-
throw new KeystoreResolutionError('CORRUPTED_KEYSTORE: Keystore JSON is invalid; refusing to replace the existing identity.', { cause: error });
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
213
|
-
throw new KeystoreResolutionError('CORRUPTED_KEYSTORE: Keystore must contain a JSON object.');
|
|
214
|
-
}
|
|
215
|
-
const data = parsed as Record<string, unknown>;
|
|
216
|
-
const keys = Object.keys(data).sort();
|
|
217
|
-
if (
|
|
218
|
-
keys.length !== 3 ||
|
|
219
|
-
keys[0] !== 'createdAt' ||
|
|
220
|
-
keys[1] !== 'did' ||
|
|
221
|
-
keys[2] !== 'privateKeyHex' ||
|
|
222
|
-
typeof data.did !== 'string' ||
|
|
223
|
-
typeof data.privateKeyHex !== 'string' ||
|
|
224
|
-
!/^[0-9a-f]{64}$/.test(data.privateKeyHex) ||
|
|
225
|
-
!Number.isSafeInteger(data.createdAt) ||
|
|
226
|
-
(data.createdAt as number) <= 0
|
|
227
|
-
) {
|
|
228
|
-
throw new KeystoreResolutionError('CORRUPTED_KEYSTORE: Keystore fields or values are invalid.');
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
const privateKey = new Uint8Array(Buffer.from(data.privateKeyHex, 'hex'));
|
|
232
|
-
let publicKey: Uint8Array | undefined;
|
|
233
|
-
try {
|
|
234
|
-
publicKey = await derivePublicKey(privateKey);
|
|
235
|
-
const derivedDid = createDidKey(publicKey);
|
|
236
|
-
if (data.did !== derivedDid) {
|
|
237
|
-
throw new KeystoreResolutionError('CORRUPTED_KEYSTORE: Stored DID does not match the DID derived from the private seed.');
|
|
238
|
-
}
|
|
239
|
-
return createSigner(publicKey, privateKey);
|
|
240
|
-
} catch (error) {
|
|
241
|
-
privateKey.fill(0);
|
|
242
|
-
publicKey?.fill(0);
|
|
243
|
-
if (error instanceof KeystoreResolutionError) throw error;
|
|
244
|
-
throw new KeystoreResolutionError('CORRUPTED_KEYSTORE: Could not validate the stored identity.', { cause: error });
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
export async function saveKeystoreFile(filePath: string, keystore: AgentKeystoreData): Promise<void> {
|
|
249
|
-
const directoryPath = path.dirname(filePath);
|
|
250
|
-
ensurePrivateDirectory(directoryPath);
|
|
251
|
-
|
|
252
|
-
if (
|
|
253
|
-
!keystore ||
|
|
254
|
-
typeof keystore.did !== 'string' ||
|
|
255
|
-
typeof keystore.privateKeyHex !== 'string' ||
|
|
256
|
-
!/^[0-9a-f]{64}$/.test(keystore.privateKeyHex) ||
|
|
257
|
-
!Number.isSafeInteger(keystore.createdAt) ||
|
|
258
|
-
keystore.createdAt <= 0
|
|
259
|
-
) {
|
|
260
|
-
throw new KeystoreResolutionError('Invalid keystore data.');
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
const privateKey = new Uint8Array(Buffer.from(keystore.privateKeyHex, 'hex'));
|
|
264
|
-
let publicKey: Uint8Array | undefined;
|
|
265
|
-
try {
|
|
266
|
-
publicKey = await derivePublicKey(privateKey);
|
|
267
|
-
if (createDidKey(publicKey) !== keystore.did) {
|
|
268
|
-
throw new KeystoreResolutionError('Keystore DID does not match the DID derived from the private seed.');
|
|
269
|
-
}
|
|
270
|
-
} finally {
|
|
271
|
-
privateKey.fill(0);
|
|
272
|
-
publicKey?.fill(0);
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
const temporaryPath = `${filePath}.tmp-${process.pid}-${randomBytes(16).toString('hex')}`;
|
|
276
|
-
const serialized = `${JSON.stringify(keystore, null, 2)}\n`;
|
|
277
|
-
let fd: number | undefined;
|
|
278
|
-
let tempCreated = false;
|
|
279
|
-
try {
|
|
280
|
-
fd = fs.openSync(temporaryPath, 'wx', 0o600);
|
|
281
|
-
tempCreated = true;
|
|
282
|
-
if (process.platform !== 'win32') {
|
|
283
|
-
fs.fchmodSync(fd, 0o600);
|
|
284
|
-
}
|
|
285
|
-
fs.writeFileSync(fd, serialized, 'utf8');
|
|
286
|
-
fs.fsyncSync(fd);
|
|
287
|
-
fs.closeSync(fd);
|
|
288
|
-
fd = undefined;
|
|
289
|
-
|
|
290
|
-
fs.linkSync(temporaryPath, filePath);
|
|
291
|
-
fs.unlinkSync(temporaryPath);
|
|
292
|
-
tempCreated = false;
|
|
293
|
-
|
|
294
|
-
if (process.platform !== 'win32') {
|
|
295
|
-
const dirFd = fs.openSync(directoryPath, fsConstants.O_RDONLY);
|
|
296
|
-
try {
|
|
297
|
-
fs.fsyncSync(dirFd);
|
|
298
|
-
} finally {
|
|
299
|
-
fs.closeSync(dirFd);
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
} catch (error) {
|
|
303
|
-
if (fd !== undefined) fs.closeSync(fd);
|
|
304
|
-
if (tempCreated) {
|
|
305
|
-
try {
|
|
306
|
-
fs.unlinkSync(temporaryPath);
|
|
307
|
-
} catch (cleanupError) {
|
|
308
|
-
if (!isErrno(cleanupError, 'ENOENT')) {
|
|
309
|
-
throw new KeystoreResolutionError('Keystore write failed and temporary-file cleanup also failed.', { cause: cleanupError });
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
if (isErrno(error, 'EEXIST')) {
|
|
314
|
-
throw new KeystoreResolutionError(`Keystore already exists: ${filePath}`, { cause: error, code: 'EEXIST' });
|
|
315
|
-
}
|
|
316
|
-
if (error instanceof KeystoreResolutionError) throw error;
|
|
317
|
-
throw new KeystoreResolutionError(`Could not atomically save keystore "${filePath}".`, { cause: error });
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
export async function createNewKeystoreFile(filePath: string): Promise<InMemoryEd25519Signer> {
|
|
322
|
-
const keyPair = await generateEd25519KeyPair();
|
|
323
|
-
try {
|
|
324
|
-
const keystore: AgentKeystoreData = {
|
|
325
|
-
did: createDidKey(keyPair.publicKey),
|
|
326
|
-
privateKeyHex: Buffer.from(keyPair.privateKey).toString('hex'),
|
|
327
|
-
createdAt: Date.now(),
|
|
328
|
-
};
|
|
329
|
-
|
|
330
|
-
try {
|
|
331
|
-
await saveKeystoreFile(filePath, keystore);
|
|
332
|
-
} catch (error) {
|
|
333
|
-
if (error instanceof KeystoreResolutionError && error.code === 'EEXIST') {
|
|
334
|
-
return await loadKeystoreFile(filePath);
|
|
335
|
-
}
|
|
336
|
-
throw error;
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
return new InMemoryEd25519Signer(keyPair.publicKey, keyPair.privateKey);
|
|
340
|
-
} finally {
|
|
341
|
-
keyPair.privateKey.fill(0);
|
|
342
|
-
keyPair.publicKey.fill(0);
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
export async function resolveAgentIdentity(options: {
|
|
347
|
-
privateKeyHex?: string;
|
|
348
|
-
filePath?: string;
|
|
349
|
-
} = {}): Promise<LoadedAgentIdentity> {
|
|
350
|
-
const envHex = options.privateKeyHex ?? process.env.ROHAN_AGENT_PRIVATE_KEY;
|
|
351
|
-
if (envHex !== undefined && envHex.trim() !== '') {
|
|
352
|
-
const normalized = envHex.trim().replace(/^0x/i, '');
|
|
353
|
-
if (!/^[0-9a-f]{64}$/i.test(normalized)) {
|
|
354
|
-
throw new KeystoreResolutionError('ROHAN_AGENT_PRIVATE_KEY is set but is not a valid 32-byte hexadecimal seed.');
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
const privateKey = new Uint8Array(Buffer.from(normalized, 'hex'));
|
|
358
|
-
let publicKey: Uint8Array | undefined;
|
|
359
|
-
try {
|
|
360
|
-
publicKey = await derivePublicKey(privateKey);
|
|
361
|
-
const signer = createSigner(publicKey, privateKey);
|
|
362
|
-
return { signer, did: signer.did, source: 'env' };
|
|
363
|
-
} catch (error) {
|
|
364
|
-
privateKey.fill(0);
|
|
365
|
-
publicKey?.fill(0);
|
|
366
|
-
if (error instanceof KeystoreResolutionError) throw error;
|
|
367
|
-
throw new KeystoreResolutionError('Could not initialize signer from ROHAN_AGENT_PRIVATE_KEY.', { cause: error });
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
const filePath = options.filePath ?? path.join(os.homedir(), '.rohan', 'agent-identity.json');
|
|
372
|
-
ensurePrivateDirectory(path.dirname(filePath));
|
|
373
|
-
|
|
374
|
-
try {
|
|
375
|
-
const signer = await loadKeystoreFile(filePath);
|
|
376
|
-
return { signer, did: signer.did, source: 'filesystem', filePath };
|
|
377
|
-
} catch (error) {
|
|
378
|
-
if (!(error instanceof KeystoreResolutionError) || error.code !== 'ENOENT') {
|
|
379
|
-
throw error;
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
const signer = await createNewKeystoreFile(filePath);
|
|
384
|
-
return { signer, did: signer.did, source: 'auto-provisioned', filePath };
|
|
385
|
-
}
|
package/src/index.ts
DELETED
package/src/server.ts
DELETED
|
@@ -1,310 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
declare const process: any;
|
|
3
|
-
|
|
4
|
-
import crypto from 'node:crypto';
|
|
5
|
-
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
6
|
-
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
7
|
-
import {
|
|
8
|
-
CallToolRequestSchema,
|
|
9
|
-
ListToolsRequestSchema,
|
|
10
|
-
} from '@modelcontextprotocol/sdk/types.js';
|
|
11
|
-
|
|
12
|
-
import { SemanticFirewall } from './firewall.js';
|
|
13
|
-
import { RohanClient, sealActionIntent, canonicalizeJson, type AgentSigner } from '@rohan-protocol/sdk';
|
|
14
|
-
import { resolveAgentIdentity } from './identity/keystore.js';
|
|
15
|
-
import {
|
|
16
|
-
resolveHandshakeAgentId,
|
|
17
|
-
ROHAN_HANDSHAKE_TOOL_SCHEMA,
|
|
18
|
-
validateHandshakeArguments,
|
|
19
|
-
} from './identity/handshake.js';
|
|
20
|
-
export { ROHAN_HANDSHAKE_TOOL_SCHEMA };
|
|
21
|
-
|
|
22
|
-
const CONTRACT_ADDRESS = process.env.ROHAN_CONTRACT_ADDRESS || '585ac0c4448257507d8ffa2a89e2aa00abd86ec9e94bdb6f553bc83e05f4dd0e';
|
|
23
|
-
const RELAYER_URL = process.env.ROHAN_RELAYER_URL || 'https://api.rohanprotocol.network/api/v1/handshake';
|
|
24
|
-
const API_KEY = process.env.ROHAN_API_KEY || '';
|
|
25
|
-
const loadedIdentity = await resolveAgentIdentity();
|
|
26
|
-
const configuredSigner: AgentSigner = loadedIdentity.signer;
|
|
27
|
-
console.error(`🛡️ [MCP V-08] Agent identity active (${loadedIdentity.source}): ${loadedIdentity.did}`);
|
|
28
|
-
if (loadedIdentity.filePath) {
|
|
29
|
-
console.error(`🛡️ [MCP V-08] Keystore path: ${loadedIdentity.filePath}`);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const rohanClient = new RohanClient({
|
|
33
|
-
contractAddress: CONTRACT_ADDRESS,
|
|
34
|
-
relayerUrl: RELAYER_URL,
|
|
35
|
-
apiKey: API_KEY,
|
|
36
|
-
signer: configuredSigner,
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
const server = new Server(
|
|
40
|
-
{
|
|
41
|
-
name: 'rohan-protocol-mcp',
|
|
42
|
-
version: '0.8.1',
|
|
43
|
-
},
|
|
44
|
-
{
|
|
45
|
-
capabilities: {
|
|
46
|
-
tools: {},
|
|
47
|
-
},
|
|
48
|
-
}
|
|
49
|
-
);
|
|
50
|
-
|
|
51
|
-
// ── Tool 2 Schema: Audit / In-Memory Verification ───────────────────────────
|
|
52
|
-
export const ROHAN_VERIFY_TOOL_SCHEMA = {
|
|
53
|
-
name: 'rohan_verify_commitment',
|
|
54
|
-
description:
|
|
55
|
-
'Verifies a plaintext confidential payload against its SHA-256 digest using RFC 8785 JSON Canonicalization. Supply the inner payload digest, not the outer on-chain intentHash. Zero gas cost; runs in local memory.',
|
|
56
|
-
inputSchema: {
|
|
57
|
-
type: 'object',
|
|
58
|
-
properties: {
|
|
59
|
-
payload: {
|
|
60
|
-
type: 'object',
|
|
61
|
-
description: 'The plaintext contract, agreement, or intent data to be verified.',
|
|
62
|
-
},
|
|
63
|
-
expectedDigest: {
|
|
64
|
-
type: 'string',
|
|
65
|
-
pattern: '^(?:sha256:|0x)?[0-9a-fA-F]{64}$',
|
|
66
|
-
description: 'The expected SHA-256 digest of the canonicalized confidential payload (the inner payload digest referenced as digest: sha256:<hash> in actionSummary), not the outer timestamp-salted on-chain intentHash. Accepts raw hex, 0x, or sha256: prefixes.',
|
|
67
|
-
},
|
|
68
|
-
},
|
|
69
|
-
required: ['payload', 'expectedDigest'],
|
|
70
|
-
},
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
// ── Tool 3 Schema: Read / Ledger State Inspection ───────────────────────────
|
|
74
|
-
export const ROHAN_LEDGER_STATE_TOOL_SCHEMA = {
|
|
75
|
-
name: 'rohan_get_ledger_state',
|
|
76
|
-
description:
|
|
77
|
-
'Reads the current anchored state of the Rohan Protocol smart contract on Midnight Preprod L1. Returns the state root, block height, and last mined transaction hash from memory cache.',
|
|
78
|
-
inputSchema: {
|
|
79
|
-
type: 'object',
|
|
80
|
-
properties: {},
|
|
81
|
-
},
|
|
82
|
-
};
|
|
83
|
-
|
|
84
|
-
export const ROHAN_HISTORY_TOOL_SCHEMA = {
|
|
85
|
-
name: 'rohan_get_transaction_history',
|
|
86
|
-
description:
|
|
87
|
-
'Lists historical settlement transactions and receipts anchored on Midnight Preprod L1.',
|
|
88
|
-
inputSchema: {
|
|
89
|
-
type: 'object',
|
|
90
|
-
properties: {
|
|
91
|
-
limit: {
|
|
92
|
-
type: 'integer',
|
|
93
|
-
description: 'Maximum number of historical transactions to return (default: 10, max: 50).',
|
|
94
|
-
},
|
|
95
|
-
},
|
|
96
|
-
},
|
|
97
|
-
};
|
|
98
|
-
|
|
99
|
-
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
100
|
-
return {
|
|
101
|
-
tools: [
|
|
102
|
-
ROHAN_HANDSHAKE_TOOL_SCHEMA,
|
|
103
|
-
ROHAN_LEDGER_STATE_TOOL_SCHEMA,
|
|
104
|
-
ROHAN_HISTORY_TOOL_SCHEMA,
|
|
105
|
-
ROHAN_VERIFY_TOOL_SCHEMA,
|
|
106
|
-
],
|
|
107
|
-
};
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
111
|
-
const toolName = request.params.name;
|
|
112
|
-
|
|
113
|
-
const rawArgs = request.params?.arguments;
|
|
114
|
-
if (!rawArgs || typeof rawArgs !== 'object' || Array.isArray(rawArgs)) {
|
|
115
|
-
return {
|
|
116
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: 'INVALID_ARGUMENTS: Expected a valid arguments object.' }) }],
|
|
117
|
-
isError: true,
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
const args = rawArgs as Record<string, any>;
|
|
121
|
-
|
|
122
|
-
// ── Tool 1: rohan_zk_handshake ────────────────────────────────────────────
|
|
123
|
-
if (toolName === 'rohan_execute_handshake' || toolName === 'rohan_zk_handshake') {
|
|
124
|
-
const argumentsError = validateHandshakeArguments(args);
|
|
125
|
-
if (argumentsError) {
|
|
126
|
-
return {
|
|
127
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: argumentsError }) }],
|
|
128
|
-
isError: true,
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
const identity = resolveHandshakeAgentId(args.agentId, configuredSigner);
|
|
133
|
-
if ('error' in identity) {
|
|
134
|
-
return {
|
|
135
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: identity.error }) }],
|
|
136
|
-
isError: true,
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
const effectiveAgentId = identity.agentId;
|
|
140
|
-
const actionLabel = args.actionSummary;
|
|
141
|
-
|
|
142
|
-
const isValid = SemanticFirewall.validate({
|
|
143
|
-
agentId: effectiveAgentId,
|
|
144
|
-
action: 'rohan_execute_handshake',
|
|
145
|
-
payload: args,
|
|
146
|
-
});
|
|
147
|
-
|
|
148
|
-
if (!isValid) {
|
|
149
|
-
return {
|
|
150
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: 'Security Violation: Intent rejected by Semantic Firewall (V-01)' }) }],
|
|
151
|
-
isError: true,
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
try {
|
|
156
|
-
const finalIntent = sealActionIntent(actionLabel, args.confidentialPayload);
|
|
157
|
-
|
|
158
|
-
const receipt = await rohanClient.submitHandshake({
|
|
159
|
-
agentId: effectiveAgentId,
|
|
160
|
-
intent: finalIntent,
|
|
161
|
-
counterpartyId: args.counterpartyId,
|
|
162
|
-
});
|
|
163
|
-
|
|
164
|
-
return {
|
|
165
|
-
content: [{
|
|
166
|
-
type: 'text',
|
|
167
|
-
text: JSON.stringify({
|
|
168
|
-
status: 'success',
|
|
169
|
-
message: 'Zero-Knowledge Handshake successfully settled on Midnight Blockchain with Sovereign Identity (V-08).',
|
|
170
|
-
agentDid: effectiveAgentId,
|
|
171
|
-
receipt,
|
|
172
|
-
}, null, 2),
|
|
173
|
-
}],
|
|
174
|
-
};
|
|
175
|
-
} catch (err: any) {
|
|
176
|
-
return {
|
|
177
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: err.message || 'Handshake execution failed' }) }],
|
|
178
|
-
isError: true,
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
// ── Tool 2: rohan_verify_commitment ───────────────────────────────────────
|
|
184
|
-
if (toolName === 'rohan_verify_commitment') {
|
|
185
|
-
// Payload-Size-Guard (Max 256 KB im RAM)
|
|
186
|
-
const payloadString = JSON.stringify(args.payload);
|
|
187
|
-
if (payloadString.length > 256 * 1024) {
|
|
188
|
-
return {
|
|
189
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: 'PAYLOAD_TOO_LARGE: Plaintext exceeds maximum allowed size of 256 KB.' }) }],
|
|
190
|
-
isError: true,
|
|
191
|
-
};
|
|
192
|
-
}
|
|
193
|
-
if (!args.payload || typeof args.payload !== 'object' || Array.isArray(args.payload)) {
|
|
194
|
-
return {
|
|
195
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: 'Invalid argument: payload must be a non-null object.' }) }],
|
|
196
|
-
isError: true,
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
if (!args.expectedDigest || typeof args.expectedDigest !== 'string') {
|
|
201
|
-
return {
|
|
202
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: 'Invalid argument: expectedDigest must be a string.' }) }],
|
|
203
|
-
isError: true,
|
|
204
|
-
};
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
try {
|
|
208
|
-
// LLM Prefix Tolerance: Strips 'sha256:' or '0x'
|
|
209
|
-
const normalizedExpected = args.expectedDigest.replace(/^(?:sha256:|0x)/i, '').toLowerCase();
|
|
210
|
-
|
|
211
|
-
if (!/^[0-9a-f]{64}$/.test(normalizedExpected)) {
|
|
212
|
-
return {
|
|
213
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: 'Invalid expectedDigest: must resolve to a 64-character hexadecimal SHA-256 hash.' }) }],
|
|
214
|
-
isError: true,
|
|
215
|
-
};
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
// Single Source of Truth: Canonicalization via @rohan-protocol/sdk
|
|
219
|
-
const canonicalPayload = canonicalizeJson(args.payload);
|
|
220
|
-
const computedDigest = crypto.createHash('sha256').update(canonicalPayload, 'utf8').digest('hex').toLowerCase();
|
|
221
|
-
const match = crypto.timingSafeEqual(
|
|
222
|
-
Buffer.from(computedDigest, 'hex'),
|
|
223
|
-
Buffer.from(normalizedExpected, 'hex')
|
|
224
|
-
);
|
|
225
|
-
|
|
226
|
-
return {
|
|
227
|
-
content: [{
|
|
228
|
-
type: 'text',
|
|
229
|
-
text: JSON.stringify({
|
|
230
|
-
status: 'success',
|
|
231
|
-
valid: match,
|
|
232
|
-
match,
|
|
233
|
-
expectedDigest: normalizedExpected,
|
|
234
|
-
computedDigest,
|
|
235
|
-
algorithm: 'SHA-256 (RFC 8785 JCS)',
|
|
236
|
-
verifiedAt: Date.now(),
|
|
237
|
-
}, null, 2),
|
|
238
|
-
}],
|
|
239
|
-
};
|
|
240
|
-
} catch (err: any) {
|
|
241
|
-
return {
|
|
242
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: err.message || 'Verification execution failed' }) }],
|
|
243
|
-
isError: true,
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
// ── Tool 3: rohan_get_ledger_state ────────────────────────────────────────
|
|
249
|
-
if (toolName === 'rohan_get_ledger_state') {
|
|
250
|
-
try {
|
|
251
|
-
const ledgerState = await rohanClient.getLedgerState();
|
|
252
|
-
const cacheAgeMs = Date.now() - (ledgerState.fetchedAt || Date.now());
|
|
253
|
-
|
|
254
|
-
return {
|
|
255
|
-
content: [{
|
|
256
|
-
type: 'text',
|
|
257
|
-
text: JSON.stringify({
|
|
258
|
-
status: 'success',
|
|
259
|
-
contractAddress: ledgerState.contractAddress,
|
|
260
|
-
currentStateRoot: ledgerState.currentStateRoot,
|
|
261
|
-
blockHeight: ledgerState.blockHeight ?? null,
|
|
262
|
-
lastTxHash: ledgerState.lastTxHash ?? null,
|
|
263
|
-
network: ledgerState.network || 'midnight-preprod',
|
|
264
|
-
isMinedOnChain: ledgerState.isMinedOnChain ?? true,
|
|
265
|
-
cacheAgeMs: (ledgerState as any).cacheAgeMs ?? cacheAgeMs,
|
|
266
|
-
cacheTtlMs: (ledgerState as any).cacheTtlMs ?? 15000,
|
|
267
|
-
fetchedAt: ledgerState.fetchedAt,
|
|
268
|
-
}, null, 2),
|
|
269
|
-
}],
|
|
270
|
-
};
|
|
271
|
-
} catch (err: any) {
|
|
272
|
-
return {
|
|
273
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: err.message || 'Failed to fetch ledger state' }) }],
|
|
274
|
-
isError: true,
|
|
275
|
-
};
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
if (toolName === 'rohan_get_transaction_history') {
|
|
280
|
-
try {
|
|
281
|
-
const rawLimit = Number(args.limit) || 10;
|
|
282
|
-
const history = await rohanClient.getTransactionHistory(rawLimit);
|
|
283
|
-
|
|
284
|
-
return {
|
|
285
|
-
content: [{
|
|
286
|
-
type: 'text',
|
|
287
|
-
text: JSON.stringify({ status: 'success', ...history }, null, 2),
|
|
288
|
-
}],
|
|
289
|
-
};
|
|
290
|
-
} catch (err: any) {
|
|
291
|
-
return {
|
|
292
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: err.message || 'Failed to fetch transaction history' }) }],
|
|
293
|
-
isError: true,
|
|
294
|
-
};
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
throw new Error(`Unknown tool: ${toolName}`);
|
|
299
|
-
});
|
|
300
|
-
|
|
301
|
-
async function run() {
|
|
302
|
-
const transport = new StdioServerTransport();
|
|
303
|
-
await server.connect(transport);
|
|
304
|
-
console.error('🛡️ Rohan Protocol MCP Server running via stdio (v0.8.1)...');
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
run().catch((error) => {
|
|
308
|
-
console.error('Fatal MCP server error:', error);
|
|
309
|
-
process.exit(1);
|
|
310
|
-
});
|