-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpayment.spec.ts
More file actions
480 lines (419 loc) · 17.3 KB
/
Copy pathpayment.spec.ts
File metadata and controls
480 lines (419 loc) · 17.3 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'bun:test';
import 'reflect-metadata';
import { Test } from '@nestjs/testing';
import type { INestApplication } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { getDataSourceToken } from '@nestjs/typeorm';
import { decodePaymentRequiredHeader, decodePaymentResponseHeader } from '@x402/core/http';
import { safeBase64Encode } from '@x402/core/utils';
import { ChunkEntity } from '../database/chunk.entity';
import { DocumentEntity } from '../database/document.entity';
import { buildDataSourceOptions } from '../database/typeorm.config';
import { toVectorLiteral, type Embedder } from '../embed/embedder';
import { SearchController } from '../search/search.controller';
import { SearchService } from '../search/search.service';
import { IndexesService } from '../indexes/indexes.service';
import { INDEXES_CONFIG, buildIndexesConfig } from '../indexes/index.config';
import { globalIndexId, joinIndex, truncateWuzzyTables } from '../testing/database';
import { scenario } from '../testing/scenario';
import { buildPaymentConfig, PAYMENT_CONFIG, type PaymentConfig } from './payment.config';
import { PaymentService, resourceUrl } from './payment.service';
import { startMockFacilitator, type MockFacilitator } from './mock-facilitator';
import { PROTOCOL } from '../canonicalize/v1';
const DIMENSIONS = 1536;
const PAY_TO = '0x2222222222222222222222222222222222222222';
describe('facilitator selection', () => {
it('defaults to the facilitator that settles Base mainnet', () => {
// The public endpoint at x402.org answers /supported with base-sepolia and
// a list of other testnets, and no eip155:8453. It was this project's
// default, including in the live Nomad job, which would have produced a
// meter that 402s forever on mainnet.
const config = buildPaymentConfig({});
expect(config.facilitatorUrl).toBe('https://api.cdp.coinbase.com/platform/v2/x402');
expect(config.facilitatorUrl).not.toContain('x402.org');
});
it('refuses to talk to Coinbase without credentials', () => {
// Failing here is the point: the alternative is a running meter that
// cannot settle, discovered when a payer's first request is rejected.
const build = () =>
new PaymentService(buildPaymentConfig({ X402_PAY_TO: '0x1' }));
expect(build).toThrow(/X402_CDP_API_KEY_ID/);
});
it('leaves a self-hosted facilitator alone', () => {
// A fork rehearsal, the demo stack's mock and the tests all point at a
// local URL, and none of them should have credentials attached.
const config = buildPaymentConfig({
X402_FACILITATOR_URL: 'http://127.0.0.1:39601',
X402_PAY_TO: '0x1',
});
expect(() => new PaymentService(config)).not.toThrow();
});
});
/** Deterministic stand-in: no network, and similarity still behaves sensibly. */
const stubEmbedder = (): Embedder => ({
model: 'stub',
dimensions: DIMENSIONS,
embed: async (texts) =>
texts.map((text) => {
const vector = new Array<number>(DIMENSIONS).fill(0);
for (const [index, char] of [...text.toLowerCase()].entries()) {
const slot = (char.charCodeAt(0) * 7 + index) % DIMENSIONS;
vector[slot] = (vector[slot] ?? 0) + 1;
}
return vector;
}),
});
let dataSource: DataSource | undefined;
let unreachable: string | undefined;
let facilitator: MockFacilitator | undefined;
beforeAll(async () => {
const candidate = new DataSource(buildDataSourceOptions());
try {
dataSource = await candidate.initialize();
} catch (error) {
if (process.env.CI) throw error;
unreachable = (error as Error).message;
return;
}
await truncateWuzzyTables(dataSource);
facilitator = await startMockFacilitator();
});
afterAll(async () => {
await facilitator?.close();
await dataSource?.destroy();
});
afterEach(async () => {
await truncateWuzzyTables(dataSource);
facilitator?.reset();
});
const ready = (): DataSource | null => {
if (dataSource) return dataSource;
console.log(`skipped: database unreachable (${unreachable})`);
return null;
};
/** Boots the search endpoint with the meter configured as the scenario needs. */
async function boot(source: DataSource, overrides: Partial<PaymentConfig>) {
const config: PaymentConfig = {
enabled: true,
payTo: PAY_TO,
network: 'base',
price: '$0.01',
facilitatorUrl: facilitator!.url,
description: 'One Wuzzy search query with onchain provenance',
...overrides,
};
const moduleRef = await Test.createTestingModule({
controllers: [SearchController],
providers: [
{ provide: getDataSourceToken(), useValue: source },
{ provide: PAYMENT_CONFIG, useValue: config },
PaymentService,
{ provide: SearchService, useValue: new SearchService(source, stubEmbedder()) },
{ provide: IndexesService, useValue: new IndexesService(source, buildIndexesConfig({})) },
{ provide: INDEXES_CONFIG, useValue: buildIndexesConfig({}) },
],
}).compile();
const app = moduleRef.createNestApplication();
await app.init();
await app.listen(0);
const url = await app.getUrl();
return { app, url: url.replace('[::1]', '127.0.0.1') };
}
/** One indexed, embedded, attested document so results have provenance to carry. */
async function seedCorpus(source: DataSource, attestationUid: string | null) {
const text = 'Deploying a smart contract to Base requires a funded wallet and a configured RPC.';
const document = await source.getRepository(DocumentEntity).save({
url: 'https://docs.base.org/deploy',
title: 'Deploy a smart contract',
content: `# Deploy\n\n${text}\n`,
rawHash: 'a'.repeat(64),
contentHash: 'b'.repeat(64),
protocol: PROTOCOL,
protocolVersion: 1,
robotsStatus: 'allowed',
httpStatus: 200,
fetchedAt: new Date('2026-02-01T00:00:00Z'),
embeddedAt: new Date('2026-02-01T01:00:00Z'),
attestationUid,
attestedAt: attestationUid ? new Date('2026-02-01T02:00:00Z') : null,
});
// Search is always scoped, so a document nobody joined to an index is a
// document nothing can find.
await joinIndex(source, await globalIndexId(source), document.id);
const [vector] = await stubEmbedder().embed([text]);
await source.getRepository(ChunkEntity).insert({
documentId: document.id,
ordinal: 0,
text,
tokenCount: 20,
embedding: toVectorLiteral(vector!) as unknown as number[],
embeddedAt: new Date('2026-02-01T01:00:00Z'),
});
return document;
}
const post = (url: string, body: unknown, headers: Record<string, string> = {}) =>
fetch(`${url}/search`, {
method: 'POST',
headers: { 'content-type': 'application/json', ...headers },
body: JSON.stringify(body),
});
/** The signed authorization, which is the same in both protocol versions. */
const signed = () => ({
signature: `0x${'1'.repeat(130)}`,
authorization: {
from: '0x1111111111111111111111111111111111111111',
to: PAY_TO,
value: '10000',
validAfter: '0',
validBefore: String(Math.floor(Date.now() / 1000) + 3600),
nonce: `0x${'2'.repeat(64)}`,
},
});
/** A well-formed X-PAYMENT header; the mock facilitator decides if it is valid. */
const paymentHeader = (): string =>
safeBase64Encode(
JSON.stringify({ x402Version: 1, scheme: 'exact', network: 'base', payload: signed() }),
);
/** A version 2 payment for requirements a 402 offered, as PAYMENT-SIGNATURE carries it. */
const paymentSignature = (accepted: unknown): string =>
safeBase64Encode(JSON.stringify({ x402Version: 2, accepted, payload: signed() }));
/** What a v2 client reads from a 402: the header, not the body. */
const requiredV2 = (response: Response) => {
const header = response.headers.get('payment-required');
if (!header) throw new Error('402 carried no PAYMENT-REQUIRED header');
return decodePaymentRequiredHeader(header);
};
describe('x402-metered search', () => {
scenario('unpaid request receives payment requirements', async () => {
const source = ready();
if (!source) return;
await seedCorpus(source, `0x${'e'.repeat(64)}`);
const { app, url } = await boot(source, {});
try {
const response = await post(url, { query: 'deploy a contract' });
expect(response.status).toBe(402);
const body = (await response.json()) as Record<string, any>;
expect(body.x402Version).toBe(1);
expect(body.accepts).toBeArray();
expect(body.accepts[0].payTo).toBe(PAY_TO);
expect(body.accepts[0].maxAmountRequired).toBe('10000');
expect(body.accepts[0].network).toBe('base');
expect(body.results).toBeUndefined();
} finally {
await app.close();
}
});
scenario('paid request returns results with provenance', async () => {
const source = ready();
if (!source) return;
const uid = `0x${'e'.repeat(64)}`;
await seedCorpus(source, uid);
const { app, url } = await boot(source, {});
try {
const response = await post(url, { query: 'deploy a contract' }, { 'X-PAYMENT': paymentHeader() });
expect(response.status).toBe(200);
const body = (await response.json()) as Record<string, any>;
expect(body.results).toBeArray();
expect(body.results.length).toBeGreaterThan(0);
const [result] = body.results;
expect(result.url).toBe('https://docs.base.org/deploy');
expect(result.title).toBe('Deploy a smart contract');
expect(typeof result.snippet).toBe('string');
expect(typeof result.score).toBe('number');
expect(result.provenance.protocol).toBe(PROTOCOL);
expect(result.provenance.protocolVersion).toBe(1);
expect(result.provenance.contentHash).toBe('b'.repeat(64));
// The bytes as served, which is the only claim a buyer can check
// against their own fetch while a result is still unattested.
expect(result.provenance.rawHash).toBe('a'.repeat(64));
expect(result.provenance.fetchedAt).toBe('2026-02-01T00:00:00.000Z');
expect(result.provenance.attestationUid).toBe(uid);
expect(result.provenance.attestationUrl).toBe(
`https://base.easscan.org/attestation/view/${uid}`,
);
// Settled only after results existed, and reported back to the payer.
expect(facilitator!.settled).toHaveLength(1);
expect(response.headers.get('x-payment-response')).toBeTruthy();
} finally {
await app.close();
}
});
scenario('malformed or insufficient payment is rejected', async () => {
const source = ready();
if (!source) return;
await seedCorpus(source, null);
const { app, url } = await boot(source, {});
try {
// Malformed: not a decodable payment header at all.
const malformed = await post(url, { query: 'deploy' }, { 'X-PAYMENT': 'not-a-payment' });
expect(malformed.status).toBe(402);
expect((await malformed.json()).results).toBeUndefined();
// Insufficient: well-formed, but the facilitator refuses it.
facilitator!.valid = false;
const insufficient = await post(url, { query: 'deploy' }, { 'X-PAYMENT': paymentHeader() });
expect(insufficient.status).toBe(402);
const body = (await insufficient.json()) as Record<string, any>;
expect(body.error).toBe('insufficient_funds');
expect(body.results).toBeUndefined();
} finally {
await app.close();
}
});
scenario('unpaid request offers both protocol versions', async () => {
const source = ready();
if (!source) return;
await seedCorpus(source, null);
const { app, url } = await boot(source, {});
try {
const response = await post(url, { query: 'deploy a contract' });
expect(response.status).toBe(402);
const body = (await response.json()) as Record<string, any>;
expect(body.x402Version).toBe(1);
const [v1] = body.accepts;
const required = requiredV2(response);
expect(required.x402Version).toBe(2);
expect(required.resource.url).toBe(v1.resource);
const [v2] = required.accepts;
expect(v2!.network).toBe('eip155:8453');
expect(v2!.amount).toBe(v1.maxAmountRequired);
expect(v2!.asset).toBe(v1.asset);
expect(v2!.payTo).toBe(v1.payTo);
// A quote belongs to one request. A cached one would be replayed against
// the next request, which may be priced differently.
expect(response.headers.get('cache-control')).toBe('no-store');
} finally {
await app.close();
}
});
scenario('a version 2 payment is answered in version 2', async () => {
const source = ready();
if (!source) return;
await seedCorpus(source, `0x${'e'.repeat(64)}`);
const { app, url } = await boot(source, {});
try {
// As a v2 client does it: ask, read the header, sign exactly what it offered.
const quote = await post(url, { query: 'deploy a contract' });
const [accepted] = requiredV2(quote).accepts;
const response = await post(
url,
{ query: 'deploy a contract' },
{ 'PAYMENT-SIGNATURE': paymentSignature(accepted) },
);
expect(response.status).toBe(200);
expect((await response.json()).results.length).toBeGreaterThan(0);
const settlement = response.headers.get('payment-response');
expect(settlement).toBeTruthy();
expect(decodePaymentResponseHeader(settlement!).success).toBe(true);
expect(response.headers.get('x-payment-response')).toBeNull();
// Forwarded as v2, against the network's CAIP-2 id rather than its v1 name.
const [verified] = facilitator!.verified as Record<string, any>[];
expect(verified!.x402Version).toBe(2);
expect(verified!.paymentRequirements.network).toBe('eip155:8453');
expect(facilitator!.settled).toHaveLength(1);
} finally {
await app.close();
}
});
scenario('a payment is read in the version of the header that carries it', async () => {
const source = ready();
if (!source) return;
await seedCorpus(source, null);
const { app, url } = await boot(source, {});
try {
const [accepted] = requiredV2(await post(url, { query: 'deploy' })).accepts;
const v1InV2 = await post(url, { query: 'deploy' }, { 'PAYMENT-SIGNATURE': paymentHeader() });
expect(v1InV2.status).toBe(402);
expect((await v1InV2.json()).results).toBeUndefined();
const v2InV1 = await post(
url,
{ query: 'deploy' },
{ 'X-PAYMENT': paymentSignature(accepted) },
);
expect(v2InV1.status).toBe(402);
// Which one counts is not a choice to make on the payer's behalf.
const both = await post(
url,
{ query: 'deploy' },
{ 'X-PAYMENT': paymentHeader(), 'PAYMENT-SIGNATURE': paymentSignature(accepted) },
);
expect(both.status).toBe(402);
expect(facilitator!.verified).toHaveLength(0);
} finally {
await app.close();
}
});
it('refuses a version 2 payment signed for a different quote', async () => {
const source = ready();
if (!source) return;
await seedCorpus(source, null);
const { app, url } = await boot(source, {});
try {
const [accepted] = requiredV2(await post(url, { query: 'deploy' })).accepts;
const underpaid = { ...accepted, amount: '1' };
const response = await post(
url,
{ query: 'deploy' },
{ 'PAYMENT-SIGNATURE': paymentSignature(underpaid) },
);
expect(response.status).toBe(402);
expect(requiredV2(response).error).toBe('Unable to find matching payment requirements');
expect(facilitator!.verified).toHaveLength(0);
} finally {
await app.close();
}
});
scenario('dev mode serves openly and says so', async () => {
const source = ready();
if (!source) return;
await seedCorpus(source, null);
const { app, url } = await boot(source, { enabled: false });
try {
const response = await post(url, { query: 'deploy a contract' });
expect(response.status).toBe(200);
expect((await response.json()).results).toBeArray();
// Nothing was charged, because nothing was metered.
expect(facilitator!.settled).toHaveLength(0);
} finally {
await app.close();
}
});
scenario('queries are rejected when empty', async () => {
const source = ready();
if (!source) return;
await seedCorpus(source, null);
const { app, url } = await boot(source, { enabled: false });
try {
const response = await post(url, { query: ' ' });
expect(response.status).toBe(400);
} finally {
await app.close();
}
});
});
describe('the resource a 402 names', () => {
const request = (
headers: Record<string, string>,
host = 'api.wuzzy.io',
protocol = 'http',
) => ({
protocol,
path: '/search',
header: (name: string) => headers[name.toLowerCase()],
get: (name: string) => (name.toLowerCase() === 'host' ? host : undefined),
});
it('names the scheme the caller used, not the one the socket saw', () => {
// Traefik and Cloudflare terminate TLS, so the socket is plain HTTP and a
// 402 would otherwise advertise a URL nobody called.
expect(resourceUrl(request({ 'x-forwarded-proto': 'https' }))).toBe(
'https://api.wuzzy.io/search',
);
});
it('takes the first scheme when each proxy in the chain appends one', () => {
expect(resourceUrl(request({ 'x-forwarded-proto': 'https,https' }))).toBe(
'https://api.wuzzy.io/search',
);
});
it('falls back to the socket scheme with nothing in front', () => {
expect(resourceUrl(request({}, 'localhost:3000'))).toBe('http://localhost:3000/search');
});
});