@rohan-protocol/mcp 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -12
- package/dist/firewall.d.ts.map +1 -1
- package/dist/firewall.js +3 -1
- package/dist/firewall.js.map +1 -1
- package/dist/gateway.d.ts +26 -0
- package/dist/gateway.d.ts.map +1 -1
- package/dist/gateway.js +10 -1
- package/dist/gateway.js.map +1 -1
- package/dist/identity/handshake.d.ts +42 -0
- package/dist/identity/handshake.d.ts.map +1 -0
- package/dist/identity/handshake.js +74 -0
- package/dist/identity/handshake.js.map +1 -0
- package/dist/identity/keystore.d.ts +27 -0
- package/dist/identity/keystore.d.ts.map +1 -0
- package/dist/identity/keystore.js +336 -0
- package/dist/identity/keystore.js.map +1 -0
- package/dist/identity.d.ts +3 -0
- package/dist/identity.d.ts.map +1 -0
- package/dist/identity.js +38 -0
- package/dist/identity.js.map +1 -0
- package/dist/server.d.ts +15 -30
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +69 -45
- package/dist/server.js.map +1 -1
- package/package.json +8 -4
- package/server.json +41 -25
- package/src/firewall.ts +5 -1
- package/src/gateway.ts +11 -1
- package/src/identity/handshake.ts +82 -0
- package/src/identity/keystore.ts +385 -0
- package/src/server.ts +81 -48
- package/tests/firewall.test.js +9 -0
- package/tests/gateway.test.js +27 -0
- package/tests/identity.test.js +170 -0
|
@@ -0,0 +1,385 @@
|
|
|
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/server.ts
CHANGED
|
@@ -10,22 +10,36 @@ import {
|
|
|
10
10
|
} from '@modelcontextprotocol/sdk/types.js';
|
|
11
11
|
|
|
12
12
|
import { SemanticFirewall } from './firewall.js';
|
|
13
|
-
import { RohanClient, sealActionIntent, canonicalizeJson } from '@rohan-protocol/sdk';
|
|
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 };
|
|
14
21
|
|
|
15
22
|
const CONTRACT_ADDRESS = process.env.ROHAN_CONTRACT_ADDRESS || '585ac0c4448257507d8ffa2a89e2aa00abd86ec9e94bdb6f553bc83e05f4dd0e';
|
|
16
23
|
const RELAYER_URL = process.env.ROHAN_RELAYER_URL || 'https://api.rohanprotocol.network/api/v1/handshake';
|
|
17
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
|
+
}
|
|
18
31
|
|
|
19
32
|
const rohanClient = new RohanClient({
|
|
20
33
|
contractAddress: CONTRACT_ADDRESS,
|
|
21
34
|
relayerUrl: RELAYER_URL,
|
|
22
35
|
apiKey: API_KEY,
|
|
36
|
+
signer: configuredSigner,
|
|
23
37
|
});
|
|
24
38
|
|
|
25
39
|
const server = new Server(
|
|
26
40
|
{
|
|
27
41
|
name: 'rohan-protocol-mcp',
|
|
28
|
-
version: '0.
|
|
42
|
+
version: '0.8.1',
|
|
29
43
|
},
|
|
30
44
|
{
|
|
31
45
|
capabilities: {
|
|
@@ -34,44 +48,11 @@ const server = new Server(
|
|
|
34
48
|
}
|
|
35
49
|
);
|
|
36
50
|
|
|
37
|
-
// ── Tool 1 Schema: Write / Settlement ───────────────────────────────────────
|
|
38
|
-
export const ROHAN_HANDSHAKE_TOOL_SCHEMA = {
|
|
39
|
-
name: 'rohan_zk_handshake',
|
|
40
|
-
description:
|
|
41
|
-
'Executes a confidential zero-knowledge state transition on Midnight Blockchain. Confidential parameters are automatically canonicalized (RFC 8785) and hashed in client RAM—never exposed on-chain or in model logs.',
|
|
42
|
-
inputSchema: {
|
|
43
|
-
type: 'object',
|
|
44
|
-
properties: {
|
|
45
|
-
agentId: {
|
|
46
|
-
type: 'string',
|
|
47
|
-
description: 'Decentralized Identifier (DID) of the initiating agent',
|
|
48
|
-
},
|
|
49
|
-
actionSummary: {
|
|
50
|
-
type: 'string',
|
|
51
|
-
description: "Public high-level action label (e.g. 'Vendor Agreement Execution', 'Database Audit Anchor')",
|
|
52
|
-
},
|
|
53
|
-
confidentialPayload: {
|
|
54
|
-
type: 'object',
|
|
55
|
-
description: 'OPTIONAL confidential parameters (budgets, deals, PII). Automatically canonicalized via RFC 8785 and hashed in local memory.',
|
|
56
|
-
},
|
|
57
|
-
counterpartyId: {
|
|
58
|
-
type: 'string',
|
|
59
|
-
description: 'Optional counterparty agent identifier',
|
|
60
|
-
},
|
|
61
|
-
intent: {
|
|
62
|
-
type: 'string',
|
|
63
|
-
description: 'Legacy fallback for actionSummary',
|
|
64
|
-
},
|
|
65
|
-
},
|
|
66
|
-
required: ['agentId'],
|
|
67
|
-
},
|
|
68
|
-
};
|
|
69
|
-
|
|
70
51
|
// ── Tool 2 Schema: Audit / In-Memory Verification ───────────────────────────
|
|
71
52
|
export const ROHAN_VERIFY_TOOL_SCHEMA = {
|
|
72
53
|
name: 'rohan_verify_commitment',
|
|
73
54
|
description:
|
|
74
|
-
'
|
|
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.',
|
|
75
56
|
inputSchema: {
|
|
76
57
|
type: 'object',
|
|
77
58
|
properties: {
|
|
@@ -82,7 +63,7 @@ export const ROHAN_VERIFY_TOOL_SCHEMA = {
|
|
|
82
63
|
expectedDigest: {
|
|
83
64
|
type: 'string',
|
|
84
65
|
pattern: '^(?:sha256:|0x)?[0-9a-fA-F]{64}$',
|
|
85
|
-
description: 'The
|
|
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.',
|
|
86
67
|
},
|
|
87
68
|
},
|
|
88
69
|
required: ['payload', 'expectedDigest'],
|
|
@@ -100,12 +81,28 @@ export const ROHAN_LEDGER_STATE_TOOL_SCHEMA = {
|
|
|
100
81
|
},
|
|
101
82
|
};
|
|
102
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
|
+
|
|
103
99
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
104
100
|
return {
|
|
105
101
|
tools: [
|
|
106
102
|
ROHAN_HANDSHAKE_TOOL_SCHEMA,
|
|
107
|
-
ROHAN_VERIFY_TOOL_SCHEMA,
|
|
108
103
|
ROHAN_LEDGER_STATE_TOOL_SCHEMA,
|
|
104
|
+
ROHAN_HISTORY_TOOL_SCHEMA,
|
|
105
|
+
ROHAN_VERIFY_TOOL_SCHEMA,
|
|
109
106
|
],
|
|
110
107
|
};
|
|
111
108
|
});
|
|
@@ -123,15 +120,28 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
123
120
|
const args = rawArgs as Record<string, any>;
|
|
124
121
|
|
|
125
122
|
// ── Tool 1: rohan_zk_handshake ────────────────────────────────────────────
|
|
126
|
-
if (toolName === 'rohan_zk_handshake') {
|
|
127
|
-
const
|
|
128
|
-
if (
|
|
129
|
-
|
|
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
130
|
}
|
|
131
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
|
+
|
|
132
142
|
const isValid = SemanticFirewall.validate({
|
|
133
|
-
agentId:
|
|
134
|
-
action: '
|
|
143
|
+
agentId: effectiveAgentId,
|
|
144
|
+
action: 'rohan_execute_handshake',
|
|
135
145
|
payload: args,
|
|
136
146
|
});
|
|
137
147
|
|
|
@@ -146,7 +156,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
146
156
|
const finalIntent = sealActionIntent(actionLabel, args.confidentialPayload);
|
|
147
157
|
|
|
148
158
|
const receipt = await rohanClient.submitHandshake({
|
|
149
|
-
agentId:
|
|
159
|
+
agentId: effectiveAgentId,
|
|
150
160
|
intent: finalIntent,
|
|
151
161
|
counterpartyId: args.counterpartyId,
|
|
152
162
|
});
|
|
@@ -156,7 +166,8 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
156
166
|
type: 'text',
|
|
157
167
|
text: JSON.stringify({
|
|
158
168
|
status: 'success',
|
|
159
|
-
message: 'Zero-Knowledge Handshake successfully settled on Midnight Blockchain.',
|
|
169
|
+
message: 'Zero-Knowledge Handshake successfully settled on Midnight Blockchain with Sovereign Identity (V-08).',
|
|
170
|
+
agentDid: effectiveAgentId,
|
|
160
171
|
receipt,
|
|
161
172
|
}, null, 2),
|
|
162
173
|
}],
|
|
@@ -207,7 +218,10 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
207
218
|
// Single Source of Truth: Canonicalization via @rohan-protocol/sdk
|
|
208
219
|
const canonicalPayload = canonicalizeJson(args.payload);
|
|
209
220
|
const computedDigest = crypto.createHash('sha256').update(canonicalPayload, 'utf8').digest('hex').toLowerCase();
|
|
210
|
-
const match =
|
|
221
|
+
const match = crypto.timingSafeEqual(
|
|
222
|
+
Buffer.from(computedDigest, 'hex'),
|
|
223
|
+
Buffer.from(normalizedExpected, 'hex')
|
|
224
|
+
);
|
|
211
225
|
|
|
212
226
|
return {
|
|
213
227
|
content: [{
|
|
@@ -262,13 +276,32 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
262
276
|
}
|
|
263
277
|
}
|
|
264
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
|
+
|
|
265
298
|
throw new Error(`Unknown tool: ${toolName}`);
|
|
266
299
|
});
|
|
267
300
|
|
|
268
301
|
async function run() {
|
|
269
302
|
const transport = new StdioServerTransport();
|
|
270
303
|
await server.connect(transport);
|
|
271
|
-
console.error('🛡️ Rohan Protocol MCP Server running via stdio (v0.
|
|
304
|
+
console.error('🛡️ Rohan Protocol MCP Server running via stdio (v0.8.1)...');
|
|
272
305
|
}
|
|
273
306
|
|
|
274
307
|
run().catch((error) => {
|
package/tests/firewall.test.js
CHANGED
|
@@ -11,6 +11,15 @@ test('SemanticFirewall: valid intent passes validation', () => {
|
|
|
11
11
|
assert.equal(SemanticFirewall.validate(intent), true);
|
|
12
12
|
});
|
|
13
13
|
|
|
14
|
+
test('SemanticFirewall: standardized execute handshake action passes validation', () => {
|
|
15
|
+
const intent = {
|
|
16
|
+
agentId: 'agent-12345',
|
|
17
|
+
action: 'rohan_execute_handshake',
|
|
18
|
+
payload: { state: 'ready', amount: 100 }
|
|
19
|
+
};
|
|
20
|
+
assert.equal(SemanticFirewall.validate(intent), true);
|
|
21
|
+
});
|
|
22
|
+
|
|
14
23
|
test('SemanticFirewall: verify_batched_handshakes passes validation', () => {
|
|
15
24
|
const intent = {
|
|
16
25
|
agentId: 'agent-batcher',
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { RohanMcpGateway } from '../dist/gateway.js';
|
|
4
|
+
|
|
5
|
+
test('ADK tool defaults to the standardized execute-handshake name', () => {
|
|
6
|
+
const gateway = new RohanMcpGateway();
|
|
7
|
+
|
|
8
|
+
assert.equal(gateway.asAdkTool().name, 'rohan_execute_handshake');
|
|
9
|
+
assert.equal(gateway.asLegacyAdkTool().name, 'rohan_zk_handshake');
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
test('standard and legacy ADK tool names share the same execution behavior', async () => {
|
|
13
|
+
const gateway = new RohanMcpGateway();
|
|
14
|
+
let submittedPayload;
|
|
15
|
+
gateway.relayerClient.submitHandshake = async (payload) => {
|
|
16
|
+
submittedPayload = payload;
|
|
17
|
+
return { status: 'confirmed' };
|
|
18
|
+
};
|
|
19
|
+
const params = { agentId: 'agent-1', intent: 'test intent' };
|
|
20
|
+
|
|
21
|
+
const standardResult = await gateway.asAdkTool().execute(params);
|
|
22
|
+
const legacyResult = await gateway.asLegacyAdkTool().execute(params);
|
|
23
|
+
|
|
24
|
+
assert.deepEqual(submittedPayload, params);
|
|
25
|
+
assert.deepEqual(standardResult, { status: 'confirmed' });
|
|
26
|
+
assert.deepEqual(legacyResult, { status: 'confirmed' });
|
|
27
|
+
});
|