-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathagents.test.js
More file actions
289 lines (256 loc) · 9 KB
/
agents.test.js
File metadata and controls
289 lines (256 loc) · 9 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { Readable } from 'node:stream';
// ── Mocks ─────────────────────────────────────────────────────────────────
// All external deps are mocked so the handler is exercised in pure-unit mode.
const authState = {
session: null,
bearer: null,
};
vi.mock('../../api/_lib/auth.js', () => ({
getSessionUser: vi.fn(async () => authState.session),
authenticateBearer: vi.fn(async () => authState.bearer),
extractBearer: vi.fn(() => null),
}));
// `sql` is a tagged-template function. The mock returns whatever
// `sqlState.nextResult` is set to (or the next in a queue).
const sqlState = {
queue: [],
calls: [],
};
vi.mock('../../api/_lib/db.js', () => ({
sql: vi.fn(async (strings, ...values) => {
// Supports both `sql\`...\`` tagged-template form and `sql(text, params)` form.
if (typeof strings === 'string') {
sqlState.calls.push({ query: strings, values: values[0] ?? [] });
} else {
sqlState.calls.push({ query: strings.join('?'), values });
}
if (sqlState.queue.length === 0) return [];
return sqlState.queue.shift();
}),
}));
vi.mock('../../api/_lib/agent-wallet.js', () => ({
generateAgentWallet: vi.fn(async () => ({
address: '0xabc0000000000000000000000000000000000001',
encrypted_key: 'enc-key-stub',
})),
generateSolanaAgentWallet: vi.fn(async () => ({
address: 'SolAddr111111111111111111111111111111111111',
encrypted_secret: 'enc-sol-secret-stub',
})),
recoverSolanaAgentKeypair: vi.fn(async () => ({
publicKey: { toBase58: () => 'SolAddr111111111111111111111111111111111111' },
secretKey: new Uint8Array(64),
})),
}));
// Import the handler AFTER mocks are declared.
const { default: handler } = await import('../../api/agents.js');
// ── Test helpers ──────────────────────────────────────────────────────────
function makeReq({ method = 'GET', url = '/api/agents', headers = {}, body = null } = {}) {
const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
base.method = method;
base.url = url;
base.headers = {
host: 'localhost',
...(body ? { 'content-type': 'application/json' } : {}),
...headers,
};
return base;
}
function makeRes() {
const res = {
statusCode: 200,
headers: {},
body: '',
writableEnded: false,
setHeader(k, v) {
this.headers[k.toLowerCase()] = v;
},
end(chunk) {
if (chunk !== undefined) this.body += chunk;
this.writableEnded = true;
},
};
return res;
}
async function invoke(reqOpts) {
const req = makeReq(reqOpts);
const res = makeRes();
await handler(req, res);
const payload = res.body ? JSON.parse(res.body) : null;
return { res, status: res.statusCode, body: payload };
}
// ── Reset between tests ───────────────────────────────────────────────────
beforeEach(() => {
authState.session = null;
authState.bearer = null;
sqlState.queue = [];
sqlState.calls = [];
});
// ── Tests ─────────────────────────────────────────────────────────────────
describe('GET /api/agents — list', () => {
it('returns 401 when unauthenticated', async () => {
const { status, body } = await invoke({ method: 'GET', url: '/api/agents' });
expect(status).toBe(401);
expect(body.error).toBe('unauthorized');
});
it('returns caller agents when authenticated via session', async () => {
authState.session = { id: 'user-1' };
sqlState.queue.push([
{
id: 'agent-1',
user_id: 'user-1',
name: 'Alpha',
description: 'first',
avatar_id: null,
home_url: null,
skills: ['greet'],
meta: { encrypted_wallet_key: 'SECRET' },
wallet_address: '0xabc',
chain_id: 1,
erc8004_agent_id: null,
erc8004_registry: null,
registration_cid: null,
created_at: '2024-01-01T00:00:00Z',
},
]);
const { status, body } = await invoke({ method: 'GET', url: '/api/agents' });
expect(status).toBe(200);
expect(body.agents).toHaveLength(1);
expect(body.agents[0].id).toBe('agent-1');
expect(body.agents[0].name).toBe('Alpha');
expect(body.agents[0].home_url).toBe('/agent/agent-1');
// decorate() must strip encrypted_wallet_key from meta
expect(body.agents[0].meta.encrypted_wallet_key).toBeUndefined();
// Owner sees their own wallet_address
expect(body.agents[0].wallet_address).toBe('0xabc');
});
it('accepts bearer token as auth source', async () => {
authState.bearer = { userId: 'user-2' };
sqlState.queue.push([]);
const { status, body } = await invoke({ method: 'GET', url: '/api/agents' });
expect(status).toBe(200);
expect(body.agents).toEqual([]);
});
});
describe('GET /api/agents/me — identity bootstrap', () => {
it('returns agent: null (200) for anonymous callers instead of 401', async () => {
const { status, body } = await invoke({ method: 'GET', url: '/api/agents/me' });
expect(status).toBe(200);
expect(body).toEqual({ agent: null });
});
it('returns existing default agent for authenticated caller', async () => {
authState.session = { id: 'user-3' };
sqlState.queue.push([
{
id: 'agent-3',
user_id: 'user-3',
name: 'Agent',
skills: [],
meta: {},
created_at: '2024-01-01T00:00:00Z',
},
]);
const { status, body } = await invoke({ method: 'GET', url: '/api/agents/me' });
expect(status).toBe(200);
expect(body.agent.id).toBe('agent-3');
});
it('auto-creates a default agent when none exists', async () => {
authState.session = { id: 'user-4' };
// First SELECT → empty; INSERT → empty; Re-SELECT → the new row.
sqlState.queue.push([]); // first lookup
sqlState.queue.push([]); // insert result
sqlState.queue.push([
{
id: 'agent-4',
user_id: 'user-4',
name: 'Agent',
skills: ['greet'],
meta: {},
wallet_address: '0xabc0000000000000000000000000000000000001',
created_at: '2024-01-01T00:00:00Z',
},
]);
const { status, body } = await invoke({ method: 'GET', url: '/api/agents/me' });
expect(status).toBe(200);
expect(body.agent.id).toBe('agent-4');
expect(body.agent.wallet_address).toBe('0xabc0000000000000000000000000000000000001');
// Three sql calls: select, insert, select
expect(sqlState.calls).toHaveLength(3);
});
it('returns { agent: null, warning } when the agents table is missing', async () => {
authState.session = { id: 'user-5' };
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const dbErr = Object.assign(new Error('relation "agent_identities" does not exist'), {
code: '42P01',
});
sqlState.queue.push(Promise.reject(dbErr));
const { status, body } = await invoke({ method: 'GET', url: '/api/agents/me' });
expect(status).toBe(200);
expect(body.agent).toBeNull();
expect(body.warning).toBe('agents_table_missing');
errSpy.mockRestore();
});
});
describe('POST /api/agents — create', () => {
it('returns 401 when unauthenticated', async () => {
const { status, body } = await invoke({
method: 'POST',
url: '/api/agents',
body: { name: 'New' },
});
expect(status).toBe(401);
expect(body.error).toBe('unauthorized');
});
it('returns 400 when name trims to empty', async () => {
authState.session = { id: 'user-6' };
const { status, body } = await invoke({
method: 'POST',
url: '/api/agents',
body: { name: ' ' },
});
expect(status).toBe(400);
expect(body.error).toBe('validation_error');
});
it('creates and returns a new agent on happy path', async () => {
authState.session = { id: 'user-7' };
sqlState.queue.push([
{
id: 'agent-7',
user_id: 'user-7',
name: 'Scout',
description: 'desc',
skills: ['greet'],
wallet_address: '0xabc0000000000000000000000000000000000001',
meta: { encrypted_wallet_key: 'SECRET', foo: 'bar' },
created_at: '2024-01-01T00:00:00Z',
},
]);
const { status, body } = await invoke({
method: 'POST',
url: '/api/agents',
body: { name: 'Scout', description: 'desc', meta: { foo: 'bar' } },
});
expect(status).toBe(201);
expect(body.agent.id).toBe('agent-7');
expect(body.agent.name).toBe('Scout');
// encrypted_wallet_key must never leak to the client
expect(body.agent.meta.encrypted_wallet_key).toBeUndefined();
expect(body.agent.meta.foo).toBe('bar');
});
});
describe('method routing', () => {
it('rejects PUT on /api/agents with 405', async () => {
const { status, body } = await invoke({ method: 'PUT', url: '/api/agents' });
expect(status).toBe(405);
expect(body.error).toBe('method_not_allowed');
});
it('short-circuits OPTIONS (CORS preflight) with 204', async () => {
const { status } = await invoke({
method: 'OPTIONS',
url: '/api/agents',
headers: { origin: 'http://localhost:3000' },
});
expect(status).toBe(204);
});
});