-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
250 lines (219 loc) · 6.89 KB
/
index.js
File metadata and controls
250 lines (219 loc) · 6.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
const fetch = require('node-fetch');
const DEFAULT_BASE_URL = 'https://api.agenticterminal.ai';
const DEFAULT_FALLBACK = 'review';
/**
* Observer Protocol SDK for Node.js / Express
*
* Provides reputation checks and middleware for agent-to-agent payments
* Works with x402, Lightning, L402, and any payment rail
*/
class ObserverClient {
constructor(options = {}) {
this.apiKey = options.apiKey || null;
this.baseUrl = options.baseUrl || DEFAULT_BASE_URL;
this.cache = new Map();
}
/**
* Get reputation for an agent by ID
* @param {string} agentId - The Observer Protocol agent ID
* @returns {Promise<Object>} Reputation data
*/
async getReputation(agentId) {
const cacheKey = `agent:${agentId}`;
const cached = this.cache.get(cacheKey);
if (cached && cached.expires > Date.now()) {
return cached.data;
}
try {
const headers = {};
if (this.apiKey) {
headers['Authorization'] = `Bearer ${this.apiKey}`;
}
const response = await fetch(
`${this.baseUrl}/observer/reputation/${encodeURIComponent(agentId)}`,
{ headers }
);
if (response.status === 404) {
const fallback = {
agent_id: agentId,
verified: false,
reputation_score: 0,
trust_tier: 'unknown',
payment_history: null,
risk_signals: { known_bad: false },
suggested_action: 'review',
cache_ttl_seconds: 60
};
this._setCache(cacheKey, fallback, fallback.cache_ttl_seconds);
return fallback;
}
if (!response.ok) {
throw new Error(`OP API error: ${response.status}`);
}
const data = await response.json();
this._setCache(cacheKey, data, data.cache_ttl_seconds || 300);
return data;
} catch (error) {
// Network error - return review fallback
return {
agent_id: agentId,
verified: false,
reputation_score: 0,
trust_tier: 'unknown',
payment_history: null,
risk_signals: { known_bad: false },
suggested_action: 'review',
cache_ttl_seconds: 60,
_error: error.message
};
}
}
/**
* Get reputation for an agent by wallet address
* @param {string} address - EVM wallet address
* @returns {Promise<Object>} Reputation data
*/
async getReputationByWallet(address) {
const cacheKey = `wallet:${address.toLowerCase()}`;
const cached = this.cache.get(cacheKey);
if (cached && cached.expires > Date.now()) {
return cached.data;
}
try {
const headers = {};
if (this.apiKey) {
headers['Authorization'] = `Bearer ${this.apiKey}`;
}
const response = await fetch(
`${this.baseUrl}/observer/reputation/wallet/${encodeURIComponent(address)}`,
{ headers }
);
if (response.status === 404) {
const fallback = {
wallet_address: address,
verified: false,
reputation_score: 0,
trust_tier: 'unknown',
payment_history: null,
risk_signals: { known_bad: false },
suggested_action: 'review',
cache_ttl_seconds: 60
};
this._setCache(cacheKey, fallback, fallback.cache_ttl_seconds);
return fallback;
}
if (!response.ok) {
throw new Error(`OP API error: ${response.status}`);
}
const data = await response.json();
this._setCache(cacheKey, data, data.cache_ttl_seconds || 300);
return data;
} catch (error) {
return {
wallet_address: address,
verified: false,
reputation_score: 0,
trust_tier: 'unknown',
payment_history: null,
risk_signals: { known_bad: false },
suggested_action: 'review',
cache_ttl_seconds: 60,
_error: error.message
};
}
}
_setCache(key, data, ttlSeconds) {
this.cache.set(key, {
data,
expires: Date.now() + (ttlSeconds * 1000)
});
}
/**
* Express middleware for reputation checking
* @param {Object} options - Middleware options
* @param {string} options.fallback - Fallback action on error ('accept', 'review', 'reject')
* @param {string} options.policy - Policy mode ('lenient', 'strict')
* @returns {Function} Express middleware
*/
reputationMiddleware(options = {}) {
const fallback = options.fallback || DEFAULT_FALLBACK;
const policy = options.policy || 'lenient';
return async (req, res, next) => {
// Extract agent identity from request
const agentId = req.headers['x-observer-agent-id'];
const walletAddress = req.headers['x-agent-wallet'];
// For POST requests, check x402 payment proof body
let x402From = null;
if (req.method === 'POST' && req.body && typeof req.body === 'object') {
x402From = req.body.from || req.body.payment?.from;
}
let identity = null;
let identityType = null;
if (agentId) {
identity = agentId;
identityType = 'agent';
} else if (walletAddress) {
identity = walletAddress;
identityType = 'wallet';
} else if (x402From) {
identity = x402From;
identityType = 'wallet';
}
// No identity found - proceed without reputation
if (!identity) {
req.observerReputation = null;
return next();
}
// Fetch reputation
let reputation;
try {
if (identityType === 'agent') {
reputation = await this.getReputation(identity);
} else {
reputation = await this.getReputationByWallet(identity);
}
} catch (error) {
// On error, use fallback
reputation = {
suggested_action: fallback,
trust_tier: 'unknown',
_error: error.message
};
}
// Attach to request
req.observerReputation = reputation;
// Handle suggested actions
const action = reputation.suggested_action || fallback;
if (action === 'reject') {
return res.status(403).json({
error: 'Access denied',
reason: 'Agent reputation insufficient',
code: 'OP_REPUTATION_REJECT'
});
}
if (action === 'review' && policy === 'strict') {
return res.status(402).json({
error: 'Payment requires review',
reason: 'Agent not verified in Observer Protocol',
code: 'OP_REPUTATION_REVIEW',
registration_url: 'https://agenticterminal.ai/observer/register'
});
}
// accept or (review + lenient policy) - proceed
next();
};
}
}
/**
* Standalone middleware factory (for simple usage)
* @param {Object} options - Options
* @returns {Function} Express middleware
*/
function reputationMiddleware(options = {}) {
const client = new ObserverClient(options);
return client.reputationMiddleware(options);
}
module.exports = {
ObserverClient,
reputationMiddleware
};