-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcapability-proxy.js
More file actions
199 lines (172 loc) · 6.77 KB
/
capability-proxy.js
File metadata and controls
199 lines (172 loc) · 6.77 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
// ============================================================
// 0nMCP — Capability Proxy
// ============================================================
// Zero-knowledge API execution layer. Tools call capabilities,
// not accounts. Credentials are borrowed from vault/connections,
// held in memory only for the duration of the call, then wiped.
//
// Wires in rate limiting (ratelimit.js) and audit logging.
// Credentials NEVER appear in logs, errors, or tool responses.
// ============================================================
import { appendFileSync, existsSync, mkdirSync } from "fs";
import { join } from "path";
import { homedir } from "os";
import { getLimiter, retryWithBackoff } from "./ratelimit.js";
const AUDIT_DIR = join(homedir(), ".0n", "history");
const AUDIT_FILE = join(AUDIT_DIR, "audit.jsonl");
export class CapabilityProxy {
/**
* @param {import("./connections.js").ConnectionManager} connectionManager
* @param {Record<string, any>} catalog - SERVICE_CATALOG from catalog.js
*/
constructor(connectionManager, catalog) {
this.connections = connectionManager;
this.catalog = catalog;
// Ensure audit directory exists
if (!existsSync(AUDIT_DIR)) {
mkdirSync(AUDIT_DIR, { recursive: true });
}
}
// ── Primary method — tools call this instead of fetch() ──────
/**
* Execute an API call through the proxy.
* Borrows credentials, enforces rate limits, executes, wipes credentials, logs audit.
*
* @param {string} service - Service key (e.g., "stripe", "sendgrid")
* @param {string} endpoint - Endpoint name from service catalog
* @param {Object} params - Request parameters
* @returns {Promise<{response: Response, data: any}>}
*/
async call(service, endpoint, params = {}) {
const start = Date.now();
let creds = null;
let status = 0;
try {
// 1. Borrow credentials (in-memory only)
creds = this._borrowCredentials(service);
if (!creds) {
throw new Error(`Service ${service} not connected`);
}
// 2. Resolve catalog entry
const svc = this.catalog[service];
if (!svc) throw new Error(`Unknown service: ${service}`);
const ep = svc.endpoints?.[endpoint];
if (!ep) throw new Error(`Unknown endpoint: ${service}.${endpoint}`);
// 3. Build request from catalog
const { url, method, headers, body } = this._buildRequest(svc, ep, params, creds);
// 4. Enforce rate limit
await this._enforceRateLimit(service);
// 5. Execute with retry on 429/5xx
const response = await retryWithBackoff(
() => fetch(url, { method, headers, body }),
{ maxRetries: 2, initialDelayMs: 500 }
);
status = response.status;
const data = await response.json().catch(() => ({
status: response.status,
statusText: response.statusText,
}));
return { response, data };
} finally {
// 6. Wipe credentials from local scope
creds = null;
// 7. Log audit entry (NO credentials)
this._logAudit(service, endpoint, status, Date.now() - start);
}
}
// ── CRM variant — credentials provided per-call ──────────────
/**
* Execute with externally-provided credentials (CRM pattern).
* Used when access_token comes from the MCP tool argument, not ConnectionManager.
* Still provides rate limiting and audit logging.
*
* @param {string} service - Service key (typically "crm")
* @param {string} endpoint - Endpoint/tool name
* @param {string} url - Pre-built URL
* @param {Object} options - Fetch options (method, headers, body)
* @returns {Promise<{response: Response, data: any}>}
*/
async callWithCredentials(service, endpoint, url, options) {
const start = Date.now();
let status = 0;
try {
// Enforce rate limit
await this._enforceRateLimit(service);
// Execute with retry
const response = await retryWithBackoff(
() => fetch(url, options),
{ maxRetries: 2, initialDelayMs: 500 }
);
status = response.status;
const data = await response.json().catch(() => ({
status: response.status,
statusText: response.statusText,
}));
return { response, data };
} finally {
this._logAudit(service, endpoint, status, Date.now() - start);
}
}
// ── Internal: borrow credentials ─────────────────────────────
_borrowCredentials(service) {
const creds = this.connections.getCredentials(service);
// Return a shallow copy; original ref released after call
return creds ? { ...creds } : null;
}
// ── Internal: enforce rate limit ─────────────────────────────
async _enforceRateLimit(service) {
const limiter = getLimiter(service);
await limiter.acquire();
}
// ── Internal: build request from catalog entry ───────────────
_buildRequest(svc, ep, params, creds) {
// URL with path param substitution
const allParams = { ...creds, ...params };
let url = svc.baseUrl + ep.path;
url = url.replace(/\{(\w+)\}/g, (_, key) => allParams[key] || `{${key}}`);
// Headers from catalog auth
const headers = svc.authHeader(creds);
const method = ep.method;
let body = undefined;
// Body for non-GET
if (method !== "GET" && params && Object.keys(params).length > 0) {
const contentType = ep.contentType || "application/json";
if (contentType === "application/x-www-form-urlencoded") {
headers["Content-Type"] = "application/x-www-form-urlencoded";
const flat = {};
for (const [k, v] of Object.entries(params)) {
if (typeof v !== "object") flat[k] = String(v);
}
body = new URLSearchParams(flat).toString();
} else {
headers["Content-Type"] = "application/json";
body = JSON.stringify(params);
}
}
// Query string for GET
if (method === "GET" && params && Object.keys(params).length > 0) {
const flat = {};
for (const [k, v] of Object.entries(params)) {
if (typeof v !== "object") flat[k] = String(v);
}
const qs = new URLSearchParams(flat).toString();
if (qs) url += (url.includes("?") ? "&" : "?") + qs;
}
return { url, method, headers, body };
}
// ── Internal: audit log (NEVER contains credentials) ─────────
_logAudit(service, endpoint, status, durationMs) {
try {
const entry = {
ts: new Date().toISOString(),
service,
endpoint,
status,
durationMs,
};
appendFileSync(AUDIT_FILE, JSON.stringify(entry) + "\n");
} catch {
// Audit logging should never break execution
}
}
}