@rohan-protocol/mcp 0.8.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 +31 -18
- 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/server.d.ts +2 -30
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +29 -43
- package/dist/server.js.map +1 -1
- package/package.json +2 -2
- package/server.json +3 -3
- package/src/identity/handshake.ts +82 -0
- package/src/identity/keystore.ts +385 -0
- package/src/server.ts +35 -46
- package/tests/identity.test.js +151 -13
- package/src/identity.ts +0 -56
package/dist/server.js
CHANGED
|
@@ -5,13 +5,17 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
|
|
5
5
|
import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
6
6
|
import { SemanticFirewall } from './firewall.js';
|
|
7
7
|
import { RohanClient, sealActionIntent, canonicalizeJson } from '@rohan-protocol/sdk';
|
|
8
|
-
import {
|
|
8
|
+
import { resolveAgentIdentity } from './identity/keystore.js';
|
|
9
|
+
import { resolveHandshakeAgentId, ROHAN_HANDSHAKE_TOOL_SCHEMA, validateHandshakeArguments, } from './identity/handshake.js';
|
|
10
|
+
export { ROHAN_HANDSHAKE_TOOL_SCHEMA };
|
|
9
11
|
const CONTRACT_ADDRESS = process.env.ROHAN_CONTRACT_ADDRESS || '585ac0c4448257507d8ffa2a89e2aa00abd86ec9e94bdb6f553bc83e05f4dd0e';
|
|
10
12
|
const RELAYER_URL = process.env.ROHAN_RELAYER_URL || 'https://api.rohanprotocol.network/api/v1/handshake';
|
|
11
13
|
const API_KEY = process.env.ROHAN_API_KEY || '';
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
14
|
+
const loadedIdentity = await resolveAgentIdentity();
|
|
15
|
+
const configuredSigner = loadedIdentity.signer;
|
|
16
|
+
console.error(`π‘οΈ [MCP V-08] Agent identity active (${loadedIdentity.source}): ${loadedIdentity.did}`);
|
|
17
|
+
if (loadedIdentity.filePath) {
|
|
18
|
+
console.error(`π‘οΈ [MCP V-08] Keystore path: ${loadedIdentity.filePath}`);
|
|
15
19
|
}
|
|
16
20
|
const rohanClient = new RohanClient({
|
|
17
21
|
contractAddress: CONTRACT_ADDRESS,
|
|
@@ -21,43 +25,12 @@ const rohanClient = new RohanClient({
|
|
|
21
25
|
});
|
|
22
26
|
const server = new Server({
|
|
23
27
|
name: 'rohan-protocol-mcp',
|
|
24
|
-
version: '0.8.
|
|
28
|
+
version: '0.8.1',
|
|
25
29
|
}, {
|
|
26
30
|
capabilities: {
|
|
27
31
|
tools: {},
|
|
28
32
|
},
|
|
29
33
|
});
|
|
30
|
-
// ββ Tool 1 Schema: Write / Settlement βββββββββββββββββββββββββββββββββββββββ
|
|
31
|
-
export const ROHAN_HANDSHAKE_TOOL_SCHEMA = {
|
|
32
|
-
name: 'rohan_execute_handshake',
|
|
33
|
-
description: '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.',
|
|
34
|
-
inputSchema: {
|
|
35
|
-
type: 'object',
|
|
36
|
-
properties: {
|
|
37
|
-
agentId: {
|
|
38
|
-
type: 'string',
|
|
39
|
-
description: 'Decentralized Identifier (DID) of the initiating agent',
|
|
40
|
-
},
|
|
41
|
-
actionSummary: {
|
|
42
|
-
type: 'string',
|
|
43
|
-
description: "Public high-level action label (e.g. 'Vendor Agreement Execution', 'Database Audit Anchor')",
|
|
44
|
-
},
|
|
45
|
-
confidentialPayload: {
|
|
46
|
-
type: 'object',
|
|
47
|
-
description: 'OPTIONAL confidential parameters (budgets, deals, PII). Automatically canonicalized via RFC 8785 and hashed in local memory.',
|
|
48
|
-
},
|
|
49
|
-
counterpartyId: {
|
|
50
|
-
type: 'string',
|
|
51
|
-
description: 'Optional counterparty agent identifier',
|
|
52
|
-
},
|
|
53
|
-
intent: {
|
|
54
|
-
type: 'string',
|
|
55
|
-
description: 'Legacy fallback for actionSummary',
|
|
56
|
-
},
|
|
57
|
-
},
|
|
58
|
-
required: ['agentId'],
|
|
59
|
-
},
|
|
60
|
-
};
|
|
61
34
|
// ββ Tool 2 Schema: Audit / In-Memory Verification βββββββββββββββββββββββββββ
|
|
62
35
|
export const ROHAN_VERIFY_TOOL_SCHEMA = {
|
|
63
36
|
name: 'rohan_verify_commitment',
|
|
@@ -122,12 +95,24 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
122
95
|
const args = rawArgs;
|
|
123
96
|
// ββ Tool 1: rohan_zk_handshake ββββββββββββββββββββββββββββββββββββββββββββ
|
|
124
97
|
if (toolName === 'rohan_execute_handshake' || toolName === 'rohan_zk_handshake') {
|
|
125
|
-
const
|
|
126
|
-
if (
|
|
127
|
-
|
|
98
|
+
const argumentsError = validateHandshakeArguments(args);
|
|
99
|
+
if (argumentsError) {
|
|
100
|
+
return {
|
|
101
|
+
content: [{ type: 'text', text: JSON.stringify({ success: false, error: argumentsError }) }],
|
|
102
|
+
isError: true,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const identity = resolveHandshakeAgentId(args.agentId, configuredSigner);
|
|
106
|
+
if ('error' in identity) {
|
|
107
|
+
return {
|
|
108
|
+
content: [{ type: 'text', text: JSON.stringify({ success: false, error: identity.error }) }],
|
|
109
|
+
isError: true,
|
|
110
|
+
};
|
|
128
111
|
}
|
|
112
|
+
const effectiveAgentId = identity.agentId;
|
|
113
|
+
const actionLabel = args.actionSummary;
|
|
129
114
|
const isValid = SemanticFirewall.validate({
|
|
130
|
-
agentId:
|
|
115
|
+
agentId: effectiveAgentId,
|
|
131
116
|
action: 'rohan_execute_handshake',
|
|
132
117
|
payload: args,
|
|
133
118
|
});
|
|
@@ -140,7 +125,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
140
125
|
try {
|
|
141
126
|
const finalIntent = sealActionIntent(actionLabel, args.confidentialPayload);
|
|
142
127
|
const receipt = await rohanClient.submitHandshake({
|
|
143
|
-
agentId:
|
|
128
|
+
agentId: effectiveAgentId,
|
|
144
129
|
intent: finalIntent,
|
|
145
130
|
counterpartyId: args.counterpartyId,
|
|
146
131
|
});
|
|
@@ -149,7 +134,8 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
149
134
|
type: 'text',
|
|
150
135
|
text: JSON.stringify({
|
|
151
136
|
status: 'success',
|
|
152
|
-
message: 'Zero-Knowledge Handshake successfully settled on Midnight Blockchain.',
|
|
137
|
+
message: 'Zero-Knowledge Handshake successfully settled on Midnight Blockchain with Sovereign Identity (V-08).',
|
|
138
|
+
agentDid: effectiveAgentId,
|
|
153
139
|
receipt,
|
|
154
140
|
}, null, 2),
|
|
155
141
|
}],
|
|
@@ -272,7 +258,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
272
258
|
async function run() {
|
|
273
259
|
const transport = new StdioServerTransport();
|
|
274
260
|
await server.connect(transport);
|
|
275
|
-
console.error('π‘οΈ Rohan Protocol MCP Server running via stdio (v0.8.
|
|
261
|
+
console.error('π‘οΈ Rohan Protocol MCP Server running via stdio (v0.8.1)...');
|
|
276
262
|
}
|
|
277
263
|
run().catch((error) => {
|
|
278
264
|
console.error('Fatal MCP server error:', error);
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":";AAGA,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,oBAAoB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;gBAClI,OAAO,EAAE,IAAI;aACd,CAAC;QACJ,CAAC;IACH,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,iBAAiB,QAAQ,EAAE,CAAC,CAAC;AAC/C,CAAC,CAAC,CAAC;AAEH,KAAK,UAAU,GAAG;IAChB,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;IAC7C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,CAAC,KAAK,CAAC,6DAA6D,CAAC,CAAC;AAC/E,CAAC;AAED,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACpB,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;IAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rohan-protocol/mcp",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"mcpName": "io.github.rohan-protocol/mcp",
|
|
5
5
|
"description": "Model Context Protocol (MCP) Gateway for Rohan Protocol ZK-Handshakes",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
26
|
-
"@rohan-protocol/sdk": "^0.8.
|
|
26
|
+
"@rohan-protocol/sdk": "^0.8.1"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@types/node": "^22.0.0",
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "io.github.rohan-protocol/mcp",
|
|
4
4
|
"title": "Rohan Protocol MCP",
|
|
5
5
|
"description": "Stateless zero-knowledge trust gateway and WebMCP shield for AI agents on Midnight.",
|
|
6
|
-
"version": "0.8.
|
|
6
|
+
"version": "0.8.1",
|
|
7
7
|
"websiteUrl": "https://rohanprotocol.network",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/rohan-protocol/sdk",
|
|
@@ -14,14 +14,14 @@
|
|
|
14
14
|
{
|
|
15
15
|
"registryType": "npm",
|
|
16
16
|
"identifier": "@rohan-protocol/mcp",
|
|
17
|
-
"version": "0.8.
|
|
17
|
+
"version": "0.8.1",
|
|
18
18
|
"transport": {
|
|
19
19
|
"type": "stdio"
|
|
20
20
|
},
|
|
21
21
|
"environmentVariables": [
|
|
22
22
|
{
|
|
23
23
|
"name": "ROHAN_AGENT_PRIVATE_KEY",
|
|
24
|
-
"description": "Optional 32-byte Ed25519 seed as 64 hex characters
|
|
24
|
+
"description": "Optional 32-byte Ed25519 seed as 64 hex characters to override the auto-provisioned local identity. Keep it in a secret store; never provide it as a tool argument.",
|
|
25
25
|
"default": "",
|
|
26
26
|
"isRequired": false,
|
|
27
27
|
"format": "string"
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { AgentSigner } from '@rohan-protocol/sdk';
|
|
2
|
+
|
|
3
|
+
export const ROHAN_HANDSHAKE_TOOL_SCHEMA = {
|
|
4
|
+
name: 'rohan_execute_handshake',
|
|
5
|
+
description:
|
|
6
|
+
'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.',
|
|
7
|
+
inputSchema: {
|
|
8
|
+
type: 'object',
|
|
9
|
+
properties: {
|
|
10
|
+
actionSummary: {
|
|
11
|
+
type: 'string',
|
|
12
|
+
minLength: 1,
|
|
13
|
+
description: 'Required public high-level action label.',
|
|
14
|
+
},
|
|
15
|
+
agentId: {
|
|
16
|
+
type: 'string',
|
|
17
|
+
description: "Optional Sovereign Agent DID. Defaults to the local signer's DID and must match it when provided.",
|
|
18
|
+
},
|
|
19
|
+
confidentialPayload: {
|
|
20
|
+
type: 'object',
|
|
21
|
+
description: 'Optional confidential parameters, canonicalized and hashed locally.',
|
|
22
|
+
},
|
|
23
|
+
counterpartyId: {
|
|
24
|
+
type: 'string',
|
|
25
|
+
description: 'Optional counterparty agent identifier.',
|
|
26
|
+
},
|
|
27
|
+
intent: {
|
|
28
|
+
type: 'string',
|
|
29
|
+
deprecated: true,
|
|
30
|
+
description: 'Deprecated alias. actionSummary remains required.',
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
required: ['actionSummary'],
|
|
34
|
+
additionalProperties: false,
|
|
35
|
+
},
|
|
36
|
+
} as const;
|
|
37
|
+
|
|
38
|
+
export function validateActionSummary(value: unknown): string | undefined {
|
|
39
|
+
if (typeof value !== 'string' || value.trim().length === 0) {
|
|
40
|
+
return 'INVALID_ARGUMENTS: actionSummary is required and cannot be empty.';
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function validateHandshakeArguments(args: Record<string, unknown>): string | undefined {
|
|
46
|
+
const allowedProperties = new Set([
|
|
47
|
+
'actionSummary',
|
|
48
|
+
'agentId',
|
|
49
|
+
'confidentialPayload',
|
|
50
|
+
'counterpartyId',
|
|
51
|
+
'intent',
|
|
52
|
+
]);
|
|
53
|
+
if (Object.keys(args).some((key) => !allowedProperties.has(key))) {
|
|
54
|
+
return 'INVALID_ARGUMENTS: Handshake arguments contain unsupported properties.';
|
|
55
|
+
}
|
|
56
|
+
if (args.intent !== undefined && typeof args.intent !== 'string') {
|
|
57
|
+
return 'INVALID_ARGUMENTS: Deprecated intent must be a string when provided.';
|
|
58
|
+
}
|
|
59
|
+
return validateActionSummary(args.actionSummary);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function resolveHandshakeAgentId(
|
|
63
|
+
requestedAgentId: unknown,
|
|
64
|
+
signer?: AgentSigner
|
|
65
|
+
): { agentId: string } | { error: string } {
|
|
66
|
+
if (signer) {
|
|
67
|
+
if (requestedAgentId === undefined) return { agentId: signer.did };
|
|
68
|
+
if (typeof requestedAgentId !== 'string' || requestedAgentId !== signer.did) {
|
|
69
|
+
return {
|
|
70
|
+
error: 'IDENTITY_MISMATCH: Declared agentId does not match the armed Sovereign Signer DID.',
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
return { agentId: signer.did };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (typeof requestedAgentId !== 'string' || requestedAgentId.trim().length === 0) {
|
|
77
|
+
return {
|
|
78
|
+
error: 'MISSING_AGENT_ID: An explicit agentId is required when no Sovereign Signer is armed.',
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
return { agentId: requestedAgentId };
|
|
82
|
+
}
|
|
@@ -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
|
+
}
|