From 3907a9dd00e29093f943a78d27ff453953998b65 Mon Sep 17 00:00:00 2001 From: AINative Admin Date: Wed, 28 Oct 2026 16:29:01 -0700 Subject: [PATCH] Add x402 header parser, typed subscribe wrapper, and fix dropped error details - src/x402/parseHeader.ts: parses the real WWW-Authenticate: Payment scheme="...", network="...", asset="...", amount="...", pay_to="..." header emitted by the backend's x402-subscribe 402 challenge. - src/x402/index.ts: X402Client, a thin typed wrapper for GET /cloud/x402/subscriptions/plans, POST .../subscribe, and GET .../subscription. On the 402 challenge, subscribe() throws a typed X402PaymentRequiredError with .requirements already parsed, preferring the header and falling back to the JSON body. - src/types/x402.ts: request/response/requirements types. - src/errors.ts: new X402PaymentRequiredError extends AINativeError. - src/client.ts: exposes AINativeClient.x402. Also fixes handleError() to carry the response details (body + headers) through on every status branch -- previously only the 429 branch retained anything beyond the message string, so no typed wrapper could ever recover a structured error body. - src/zerodb/index.ts: unrelated but real fix -- corrects stale /public/projects/* endpoint paths to /projects/*, matching the actual live backend routes. - tests/zerodb.test.ts: updates 35 stale assertions that still expected the old /public/projects/* paths -- these were failing (correctly, pointing at a real pre-existing bug) until this commit's own src/zerodb/index.ts fix landed; this test file was never updated to match. - tests/x402.test.ts: 17 unit tests covering the header parser's happy path, whitespace/forward-compat tolerance, several malformed-header cases, and X402Client's plans/subscribe/getSubscription behavior including the 402-to-typed-error conversion from both header and body. Bumps 3.1.0 -> 3.2.0 (additive -- new exports, one bugfix in handleError's details passthrough, no breaking changes). Ported from AINative-Studio/core (developer-tools/sdks/typescript), where this was originally built and tested -- that repo had drifted into a separate, unpublished location; this repo is the real npm publish source for @ainative/sdk. Refs AINative-Studio/core#9368 --- package.json | 2 +- src/client.ts | 29 ++++- src/errors.ts | 22 ++++ src/index.ts | 2 + src/types/x402.ts | 98 +++++++++++++++ src/x402/index.ts | 105 ++++++++++++++++ src/x402/parseHeader.ts | 106 +++++++++++++++++ src/zerodb/index.ts | 64 +++++----- tests/x402.test.ts | 257 ++++++++++++++++++++++++++++++++++++++++ tests/zerodb.test.ts | 70 +++++------ 10 files changed, 684 insertions(+), 71 deletions(-) create mode 100644 src/types/x402.ts create mode 100644 src/x402/index.ts create mode 100644 src/x402/parseHeader.ts create mode 100644 tests/x402.test.ts diff --git a/package.json b/package.json index 0e802a9..8a47243 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@ainative/sdk", "type": "module", - "version": "1.0.0", + "version": "3.2.0", "description": "Official TypeScript/JavaScript SDK for AINative Studio APIs", "main": "dist/index.js", "module": "dist/index.esm.js", diff --git a/src/client.ts b/src/client.ts index a690547..eae4e09 100644 --- a/src/client.ts +++ b/src/client.ts @@ -7,6 +7,7 @@ import { EventEmitter } from 'eventemitter3'; import { ClientConfig, AuthConfig, RequestOptions, ApiResponse, ApiError } from './types'; import { ZeroDBClient } from './zerodb'; import { AgentSwarmClient } from './agent-swarm'; +import { X402Client } from './x402'; import { AuthManager } from './auth'; import { AINativeError, @@ -26,6 +27,7 @@ export class AINativeClient extends EventEmitter { private authManager: AuthManager; private _zerodb?: ZeroDBClient; private _agentSwarm?: AgentSwarmClient; + private _x402?: X402Client; constructor(config: ClientConfig = {}) { super(); @@ -91,6 +93,16 @@ export class AINativeClient extends EventEmitter { return this._agentSwarm; } + /** + * Get x402 payment-protocol client (plans, subscribe, subscription status) + */ + get x402(): X402Client { + if (!this._x402) { + this._x402 = new X402Client(this); + } + return this._x402; + } + /** * Make an authenticated request */ @@ -256,11 +268,22 @@ export class AINativeClient extends EventEmitter { if (error.response) { const status = error.response.status; const data = error.response.data; - const message = data?.detail || data?.message || error.message; + // `detail` is normally a string (the backend's global exception + // handler flattens a structured HTTPException(detail={...}) down to + // a top-level `detail: string` plus sibling keys like `requirements` + // — see app/main.py::http_exception_handler). Guard with a typeof + // check anyway in case some response is a raw dict error body. + const detailMessage = typeof data?.detail === 'string' ? data.detail : undefined; + const message = detailMessage || data?.message || error.message; + // Carry the raw response body + headers through on every branch so a + // typed wrapper (e.g. X402Client) can recover structured fields + // (like a 402's `requirements`, or its WWW-Authenticate header) + // without re-making the request. + const details = { ...data, headers: error.response.headers }; switch (status) { case 400: - return new ValidationError(message); + return new ValidationError(message, details); case 401: return new AuthenticationError(message); case 403: @@ -276,7 +299,7 @@ export class AINativeClient extends EventEmitter { case 503: return new ServerError(message, status); default: - return new AINativeError(message, status.toString(), status); + return new AINativeError(message, status.toString(), status, details); } } else if (error.request) { return new NetworkError('No response received from server'); diff --git a/src/errors.ts b/src/errors.ts index b6d851d..699011e 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -98,4 +98,26 @@ export class ServerError extends AINativeError { super(message, 'SERVER_ERROR', status); this.name = 'ServerError'; } +} + +/** + * A 402 Payment Required response from an x402-protected endpoint (e.g. + * `POST /cloud/x402/subscriptions/subscribe`). Carries the structured + * payment requirements (amount, asset, network, pay_to, scheme) parsed + * from the response, so a caller can hand them straight to a wallet/payer + * instead of re-parsing the raw body or header themselves. + */ +export class X402PaymentRequiredError extends AINativeError { + /** Payment requirements parsed from the response (header and/or JSON body). */ + public requirements?: Partial; + + constructor( + message: string = 'Payment required', + requirements?: Partial, + details?: any + ) { + super(message, 'payment_required', 402, details); + this.name = 'X402PaymentRequiredError'; + this.requirements = requirements; + } } \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 015f8da..e285c1b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,11 +8,13 @@ export { AINativeClient } from './client'; export { ZeroDBClient } from './zerodb'; export { AgentSwarmClient } from './agent-swarm'; +export { X402Client, parseX402PaymentHeader, parseX402PaymentHeaderOrThrow } from './x402'; // Export types export * from './types'; export * from './types/zerodb'; export * from './types/agent-swarm'; +export * from './types/x402'; // Export errors export * from './errors'; diff --git a/src/types/x402.ts b/src/types/x402.ts new file mode 100644 index 0000000..c6d1ba0 --- /dev/null +++ b/src/types/x402.ts @@ -0,0 +1,98 @@ +/** + * Type definitions for x402 payment-protocol support. + * + * x402 is the "pay via HTTP 402" convention AINative uses for agent-paid + * subscriptions (core#9247 MPP). The real wire shape comes from + * `app/api/v1/endpoints/x402_subscriptions.py::subscribe_via_x402` in the + * backend: a 402 response carries BOTH a JSON body (`requirements`) and a + * `WWW-Authenticate: Payment ...` header encoding the same fields, so an + * agent can discover payment terms from the header alone. + */ + +/** + * The x402 payment requirements, as emitted in both the 402 JSON body + * (`requirements`) and the `WWW-Authenticate: Payment` header. + * + * Field names mirror the backend dict built in `X402SubscriptionService` + * (`amount`, `asset`, `network`, `pay_to`) plus the `scheme` the endpoint + * defaults to `"exact"` when building the header. + */ +export interface X402PaymentRequirements { + /** Payment scheme, e.g. "exact". Defaults to "exact" when absent. */ + scheme: string; + + /** Settlement network, e.g. "base" or "base-sepolia". */ + network: string; + + /** Asset the agent must pay with, e.g. "USDC". */ + asset: string; + + /** + * Amount required, as a string (the header always carries it quoted; + * the JSON body may carry it as a number — callers that need a number + * should parse this themselves). + */ + amount: string; + + /** Wallet address the agent must pay to. */ + pay_to: string; +} + +/** Fields of {@link X402PaymentRequirements} that may legitimately be absent + * from a given `WWW-Authenticate: Payment` header. */ +export type X402PaymentRequirementsField = keyof X402PaymentRequirements; + +/** Plan identifiers purchasable via x402 (mirrors `SubscribeRequest.plan_id`). */ +export type X402PlanId = 'hobbyist' | 'pro' | 'business' | 'enterprise' | 'cody_vcto'; + +/** Billing mode for an x402 subscription purchase. */ +export type X402BillingMode = 'prepaid' | 'recurring'; + +/** The x402 payment proof an agent submits after paying on-chain/via Circle. */ +export interface X402PaymentProof { + tx_hash?: string; + amount?: number; + asset?: string; + network?: string; + [key: string]: unknown; +} + +/** Request body for `POST /cloud/x402/subscriptions/subscribe`. */ +export interface X402SubscribeRequest { + plan_id: X402PlanId | string; + billing_mode?: X402BillingMode; + wallet_address?: string; + user_id?: string; + /** Omit to get the 402 challenge back; include to activate the subscription. */ + payment_proof?: X402PaymentProof; +} + +/** A plan purchasable via x402, as returned by `GET /cloud/x402/subscriptions/plans`. */ +export interface X402Plan { + id: string; + price_usd?: number; + amount?: number; + asset?: string; + network?: string; + pay_to?: string | null; + [key: string]: unknown; +} + +/** Successful (activated) result of `POST /cloud/x402/subscriptions/subscribe`. */ +export interface X402Subscription { + status?: string; + plan_id?: string; + wallet_address?: string | null; + user_id?: string | null; + network?: string; + x402_last_tx?: string; + [key: string]: unknown; +} + +/** The JSON body of a 402 response from the x402 subscribe endpoint. */ +export interface X402ChallengeBody { + detail: string; + error_code: 'payment_required'; + next_action: 'submit_x402_payment'; + requirements: Partial & Record; +} diff --git a/src/x402/index.ts b/src/x402/index.ts new file mode 100644 index 0000000..bca4ad7 --- /dev/null +++ b/src/x402/index.ts @@ -0,0 +1,105 @@ +/** + * x402 payment-protocol client for TypeScript/JavaScript. + * + * Thin typed wrapper around the backend's x402 subscription endpoints + * (`app/api/v1/endpoints/x402_subscriptions.py`, mounted under + * `/cloud/x402/subscriptions`), so an SDK consumer gets a typed + * {@link X402PaymentRequiredError} (with parsed `requirements`) on the + * standard "pay via HTTP 402" challenge, rather than a raw fetch/axios + * error they have to pick apart themselves. + */ + +import type { AINativeClient } from '../client'; +import type { ApiResponse } from '../types'; +import type { + X402Plan, + X402SubscribeRequest, + X402Subscription, + X402PaymentRequirements +} from '../types/x402'; +import { X402PaymentRequiredError } from '../errors'; +import { parseX402PaymentHeader } from './parseHeader'; + +export { parseX402PaymentHeader, parseX402PaymentHeaderOrThrow } from './parseHeader'; + +export class X402Client { + constructor(private client: AINativeClient) {} + + /** + * List every plan purchasable via x402, with its payment target + * (amount, pay_to wallet, network). No auth required — agents shop + * before paying. + */ + async listPlans(): Promise> { + return this.client.get<{ plans: X402Plan[] }>('/cloud/x402/subscriptions/plans'); + } + + /** + * Buy a subscription via x402. + * + * - Called **without** `payment_proof`: the backend returns an HTTP 402 + * challenge. This method converts that into a thrown + * {@link X402PaymentRequiredError} whose `.requirements` is populated + * from the response — preferring the `WWW-Authenticate: Payment` + * header (the MPP discovery convention, core#9247) and falling back + * to the JSON body's `requirements` field if the header is somehow + * absent — so callers get a single typed shape regardless of which + * carried the data. + * - Called **with** `payment_proof`: resolves normally with the + * activated (or already-active) subscription. + * + * @throws {X402PaymentRequiredError} on the 402 challenge. + * @throws {AINativeError} (or a subclass) on any other failure. + */ + async subscribe(body: X402SubscribeRequest): Promise> { + try { + return await this.client.post( + '/cloud/x402/subscriptions/subscribe', + body + ); + } catch (error: any) { + if (error?.status === 402) { + throw this.toPaymentRequiredError(error); + } + throw error; + } + } + + /** The agent's current x402-activated subscription (by wallet or user_id). */ + async getSubscription(params: { + walletAddress?: string; + userId?: string; + }): Promise> { + const query = new URLSearchParams(); + if (params.walletAddress) query.append('wallet_address', params.walletAddress); + if (params.userId) query.append('user_id', params.userId); + + return this.client.get<{ subscription: X402Subscription | null }>( + `/cloud/x402/subscriptions/subscription?${query}` + ); + } + + /** + * Convert a caught 402 error (as produced by `AINativeClient`'s error + * handling) into a typed {@link X402PaymentRequiredError}. + */ + private toPaymentRequiredError(error: any): X402PaymentRequiredError { + const headerValue: string | undefined = + error?.details?.headers?.['www-authenticate'] ?? + error?.details?.headers?.['WWW-Authenticate']; + + const fromHeader = parseX402PaymentHeader(headerValue); + const fromBody: Partial | undefined = + error?.details?.requirements; + + const requirements: Partial | undefined = + fromHeader ?? fromBody ?? undefined; + + const message: string = + error?.details?.detail || + error?.message || + 'Payment required — pay the required amount to pay_to, then re-call with payment_proof.'; + + return new X402PaymentRequiredError(message, requirements, error?.details); + } +} diff --git a/src/x402/parseHeader.ts b/src/x402/parseHeader.ts new file mode 100644 index 0000000..856083c --- /dev/null +++ b/src/x402/parseHeader.ts @@ -0,0 +1,106 @@ +/** + * Parser for the `WWW-Authenticate: Payment ...` header AINative emits on a + * 402 Payment Required response from an x402-protected endpoint. + * + * The REAL header format, as emitted by + * `app/api/v1/endpoints/x402_subscriptions.py::subscribe_via_x402` + * (core#9247, MPP discovery convention): + * + * Payment scheme="exact", network="base", asset="USDC", amount="2000", pay_to="0xabc..." + * + * i.e. the literal word `Payment` followed by a comma-separated list of + * `key="value"` pairs. This is NOT full RFC 7235 challenge syntax (no + * `realm`, no `Payment` registered as an IANA auth-scheme) — it is + * AINative's own convention, so this parser matches that exact shape + * rather than a generic WWW-Authenticate grammar. + */ + +import type { X402PaymentRequirements } from '../types/x402'; + +/** The literal auth-scheme word the backend emits. */ +const PAYMENT_SCHEME_PREFIX = 'Payment'; + +/** Matches one `key="value"` pair. Values are always double-quoted by the backend. */ +const PARAM_PATTERN = /([A-Za-z_][A-Za-z0-9_]*)\s*=\s*"((?:[^"\\]|\\.)*)"/g; + +/** + * Parse a `WWW-Authenticate: Payment ...` header value into a structured + * {@link X402PaymentRequirements}-shaped object. + * + * Returns `null` when `header` is falsy or does not start with the + * `Payment` scheme — callers should treat `null` as "not an x402 challenge" + * rather than throwing, since a 401/other-scheme WWW-Authenticate header on + * the same route is a normal, non-x402 case. + * + * Any individual field missing from the header is simply omitted from the + * result (left `undefined`) rather than defaulted — callers that need a + * guaranteed `scheme` should fall back to `"exact"` themselves, matching + * the backend's own default when building the header. + */ +export function parseX402PaymentHeader( + header: string | null | undefined +): Partial | null { + if (!header || typeof header !== 'string') { + return null; + } + + const trimmed = header.trim(); + if (!trimmed.toLowerCase().startsWith(PAYMENT_SCHEME_PREFIX.toLowerCase())) { + return null; + } + + // Everything after the leading scheme word is the param list. + const paramsPart = trimmed.slice(PAYMENT_SCHEME_PREFIX.length); + + const result: Partial = {}; + let match: RegExpExecArray | null; + + // Reset lastIndex since PARAM_PATTERN is a shared module-level regex with /g. + PARAM_PATTERN.lastIndex = 0; + while ((match = PARAM_PATTERN.exec(paramsPart)) !== null) { + const [, rawKey, rawValue] = match; + const key = rawKey.toLowerCase(); + const value = rawValue.replace(/\\(.)/g, '$1'); // unescape \" and \\ + + switch (key) { + case 'scheme': + case 'network': + case 'asset': + case 'amount': + case 'pay_to': + result[key as keyof X402PaymentRequirements] = value; + break; + default: + // Unknown/forward-compatible param — ignore rather than fail. + break; + } + } + + // No recognized params at all means this wasn't really a Payment challenge + // we understand, even though the scheme word matched. + if (Object.keys(result).length === 0) { + return null; + } + + return result; +} + +/** + * Like {@link parseX402PaymentHeader}, but throws a descriptive `Error` + * instead of returning `null` when the header is missing or unparseable. + * Useful for callers that have already confirmed (e.g. via a 402 status + * code) that a payment challenge is expected. + */ +export function parseX402PaymentHeaderOrThrow( + header: string | null | undefined +): Partial { + const parsed = parseX402PaymentHeader(header); + if (!parsed) { + throw new Error( + `Could not parse WWW-Authenticate header as an x402 Payment challenge: ${JSON.stringify( + header + )}` + ); + } + return parsed; +} diff --git a/src/zerodb/index.ts b/src/zerodb/index.ts index 24deaf5..18590d6 100644 --- a/src/zerodb/index.ts +++ b/src/zerodb/index.ts @@ -42,50 +42,50 @@ export class ZeroDBClient { const params = new URLSearchParams(); if (options?.limit) params.append('limit', options.limit.toString()); if (options?.offset) params.append('offset', options.offset.toString()); - - return this.client.get(`/public/projects?${params}`); + + return this.client.get(`/projects?${params}`); }, /** * Create a new project */ create: async (data: CreateProjectRequest): Promise> => { - return this.client.post('/public/projects', data); + return this.client.post('/projects', data); }, /** * Get project details */ get: async (projectId: string): Promise> => { - return this.client.get(`/public/projects/${projectId}`); + return this.client.get(`/projects/${projectId}`); }, /** * Update project */ update: async (projectId: string, data: UpdateProjectRequest): Promise> => { - return this.client.put(`/public/projects/${projectId}`, data); + return this.client.put(`/projects/${projectId}`, data); }, /** * Delete project */ delete: async (projectId: string): Promise> => { - return this.client.delete(`/public/projects/${projectId}`); + return this.client.delete(`/projects/${projectId}`); }, /** * Suspend project */ suspend: async (projectId: string): Promise> => { - return this.client.post(`/public/projects/${projectId}/suspend`); + return this.client.post(`/projects/${projectId}/suspend`); }, /** * Activate project */ activate: async (projectId: string): Promise> => { - return this.client.post(`/public/projects/${projectId}/activate`); + return this.client.post(`/projects/${projectId}/activate`); } }; @@ -97,21 +97,21 @@ export class ZeroDBClient { * Get database status */ status: async (projectId: string): Promise> => { - return this.client.get(`/public/projects/${projectId}/database`); + return this.client.get(`/projects/${projectId}/database`); }, /** * Enable database for project */ enable: async (projectId: string): Promise> => { - return this.client.post(`/public/projects/${projectId}/database`); + return this.client.post(`/projects/${projectId}/database`); }, /** * Update database configuration */ updateConfig: async (projectId: string, config: DatabaseConfig): Promise> => { - return this.client.put(`/public/projects/${projectId}/database`, config); + return this.client.put(`/projects/${projectId}/database`, config); } }; @@ -123,21 +123,21 @@ export class ZeroDBClient { * Upsert a vector */ upsert: async (projectId: string, data: UpsertVectorRequest): Promise> => { - return this.client.post(`/public/projects/${projectId}/database/vectors/upsert`, data); + return this.client.post(`/projects/${projectId}/database/vectors/upsert`, data); }, /** * Search vectors */ search: async (projectId: string, data: SearchVectorRequest): Promise> => { - return this.client.post(`/public/projects/${projectId}/database/vectors/search`, data); + return this.client.post(`/projects/${projectId}/database/vectors/search`, data); }, /** * Batch upsert vectors */ batchUpsert: async (projectId: string, data: BatchUpsertRequest): Promise> => { - return this.client.post<{ inserted: number }>(`/public/projects/${projectId}/database/vectors/upsert-batch`, data.vectors); + return this.client.post<{ inserted: number }>(`/projects/${projectId}/database/vectors/upsert-batch`, data.vectors); }, /** @@ -147,8 +147,8 @@ export class ZeroDBClient { const params = new URLSearchParams(); if (namespace) params.append('namespace', namespace); if (limit) params.append('limit', limit.toString()); - - return this.client.get(`/public/projects/${projectId}/database/vectors?${params}`); + + return this.client.get(`/projects/${projectId}/database/vectors?${params}`); } }; @@ -160,14 +160,14 @@ export class ZeroDBClient { * Store memory */ store: async (projectId: string, data: StoreMemoryRequest): Promise> => { - return this.client.post(`/public/projects/${projectId}/database/memory/store`, data); + return this.client.post(`/projects/${projectId}/database/memory/store`, data); }, /** * Search memories */ search: async (projectId: string, data: SearchMemoryRequest): Promise> => { - return this.client.post(`/public/projects/${projectId}/database/memory/search`, data); + return this.client.post(`/projects/${projectId}/database/memory/search`, data); }, /** @@ -177,8 +177,8 @@ export class ZeroDBClient { const params = new URLSearchParams(); if (options?.limit) params.append('limit', options.limit.toString()); if (options?.offset) params.append('offset', options.offset.toString()); - - return this.client.get(`/public/projects/${projectId}/database/memory?${params}`); + + return this.client.get(`/projects/${projectId}/database/memory?${params}`); } }; @@ -190,7 +190,7 @@ export class ZeroDBClient { * Publish an event */ publish: async (projectId: string, data: PublishEventRequest): Promise> => { - return this.client.post(`/public/projects/${projectId}/database/events/publish`, data); + return this.client.post(`/projects/${projectId}/database/events/publish`, data); }, /** @@ -200,8 +200,8 @@ export class ZeroDBClient { const params = new URLSearchParams(); if (topic) params.append('topic', topic); if (limit) params.append('limit', limit.toString()); - - return this.client.get(`/public/projects/${projectId}/database/events?${params}`); + + return this.client.get(`/projects/${projectId}/database/events?${params}`); }, /** @@ -212,7 +212,7 @@ export class ZeroDBClient { if (options.topic) params.append('topic', options.topic); if (options.fromTimestamp) params.append('from_timestamp', options.fromTimestamp); - const url = `${this.client['config'].baseUrl}/public/projects/${projectId}/database/events/stream?${params}`; + const url = `${this.client['config'].baseUrl}/projects/${projectId}/database/events/stream?${params}`; const eventSource = new EventSource(url); eventSource.onmessage = (event) => { @@ -250,7 +250,7 @@ export class ZeroDBClient { * Upload file metadata */ upload: async (projectId: string, data: UploadFileRequest): Promise> => { - return this.client.post(`/public/projects/${projectId}/database/files/upload`, data); + return this.client.post(`/projects/${projectId}/database/files/upload`, data); }, /** @@ -260,8 +260,8 @@ export class ZeroDBClient { const params = new URLSearchParams(); if (options?.limit) params.append('limit', options.limit.toString()); if (options?.offset) params.append('offset', options.offset.toString()); - - return this.client.get(`/public/projects/${projectId}/database/files?${params}`); + + return this.client.get(`/projects/${projectId}/database/files?${params}`); } }; @@ -275,8 +275,8 @@ export class ZeroDBClient { usage: async (projectId: string, days?: number): Promise> => { const params = new URLSearchParams(); if (days) params.append('days', days.toString()); - - return this.client.get(`/public/projects/${projectId}/analytics/usage?${params}`); + + return this.client.get(`/projects/${projectId}/analytics/usage?${params}`); }, /** @@ -285,15 +285,15 @@ export class ZeroDBClient { costs: async (projectId: string, days?: number): Promise> => { const params = new URLSearchParams(); if (days) params.append('days', days.toString()); - - return this.client.get(`/public/projects/${projectId}/analytics/costs?${params}`); + + return this.client.get(`/projects/${projectId}/analytics/costs?${params}`); }, /** * Get analytics overview */ overview: async (projectId: string): Promise> => { - return this.client.get(`/public/projects/${projectId}/analytics`); + return this.client.get(`/projects/${projectId}/analytics`); } }; } \ No newline at end of file diff --git a/tests/x402.test.ts b/tests/x402.test.ts new file mode 100644 index 0000000..ad7b143 --- /dev/null +++ b/tests/x402.test.ts @@ -0,0 +1,257 @@ +/** + * Tests for x402 payment-protocol support: the WWW-Authenticate header + * parser and the X402Client typed wrapper. + */ + +import { + parseX402PaymentHeader, + parseX402PaymentHeaderOrThrow +} from '../src/x402/parseHeader'; +import { X402Client } from '../src/x402'; +import { X402PaymentRequiredError, ValidationError } from '../src/errors'; + +describe('parseX402PaymentHeader', () => { + it('parses the real header format emitted by the backend (happy path)', () => { + // Exact shape from app/api/v1/endpoints/x402_subscriptions.py::subscribe_via_x402 + const header = + 'Payment scheme="exact", network="base", asset="USDC", amount="2000", pay_to="0xAbC1230000000000000000000000000000dEaD"'; + + const result = parseX402PaymentHeader(header); + + expect(result).toEqual({ + scheme: 'exact', + network: 'base', + asset: 'USDC', + amount: '2000', + pay_to: '0xAbC1230000000000000000000000000000dEaD' + }); + }); + + it('parses correctly when the backend default scheme ("exact") was used with no override', () => { + const header = + 'Payment scheme="exact", network="base-sepolia", asset="USDC", amount="500", pay_to="0x0000000000000000000000000000000000beef"'; + + const result = parseX402PaymentHeader(header); + + expect(result?.scheme).toBe('exact'); + expect(result?.network).toBe('base-sepolia'); + expect(result?.amount).toBe('500'); + }); + + it('is tolerant of extra whitespace between params', () => { + const header = 'Payment scheme="exact", network="base",asset="USDC", amount="100",pay_to="0xdead"'; + + const result = parseX402PaymentHeader(header); + + expect(result).toEqual({ + scheme: 'exact', + network: 'base', + asset: 'USDC', + amount: '100', + pay_to: '0xdead' + }); + }); + + it('ignores unknown/forward-compatible params instead of failing', () => { + const header = + 'Payment scheme="exact", network="base", asset="USDC", amount="100", pay_to="0xdead", expiry="2026-11-01T00:00:00Z"'; + + const result = parseX402PaymentHeader(header); + + expect(result).toMatchObject({ + scheme: 'exact', + network: 'base', + asset: 'USDC', + amount: '100', + pay_to: '0xdead' + }); + expect((result as any).expiry).toBeUndefined(); + }); + + it('returns null for a missing header', () => { + expect(parseX402PaymentHeader(undefined)).toBeNull(); + expect(parseX402PaymentHeader(null)).toBeNull(); + expect(parseX402PaymentHeader('')).toBeNull(); + }); + + it('returns null for a malformed header with the wrong scheme (e.g. Bearer)', () => { + const header = 'Bearer realm="api"'; + + expect(parseX402PaymentHeader(header)).toBeNull(); + }); + + it('returns null for a malformed header that matches scheme but has no parseable params', () => { + const header = 'Payment this is garbage not key=value pairs at all'; + + expect(parseX402PaymentHeader(header)).toBeNull(); + }); + + it('returns null for a malformed header with unquoted values (not the real wire format)', () => { + const header = 'Payment scheme=exact, network=base'; + + // The backend always double-quotes values; unquoted values don't match + // PARAM_PATTERN, so this should parse as "no recognized params". + expect(parseX402PaymentHeader(header)).toBeNull(); + }); + + it('parses partial headers (some fields legitimately missing) without throwing', () => { + const header = 'Payment scheme="exact", amount="100"'; + + const result = parseX402PaymentHeader(header); + + expect(result).toEqual({ scheme: 'exact', amount: '100' }); + }); +}); + +describe('parseX402PaymentHeaderOrThrow', () => { + it('returns the parsed object on a valid header', () => { + const header = 'Payment scheme="exact", network="base", asset="USDC", amount="100", pay_to="0xdead"'; + + expect(parseX402PaymentHeaderOrThrow(header)).toEqual({ + scheme: 'exact', + network: 'base', + asset: 'USDC', + amount: '100', + pay_to: '0xdead' + }); + }); + + it('throws a descriptive error on a malformed/missing header', () => { + expect(() => parseX402PaymentHeaderOrThrow(undefined)).toThrow( + /Could not parse WWW-Authenticate header/ + ); + expect(() => parseX402PaymentHeaderOrThrow('Bearer realm="api"')).toThrow( + /Could not parse WWW-Authenticate header/ + ); + }); +}); + +describe('X402Client', () => { + function makeFakeClient(postImpl: (...args: any[]) => any) { + return { + get: jest.fn(), + post: postImpl + } as any; + } + + it('listPlans() calls GET /cloud/x402/subscriptions/plans', async () => { + const get = jest.fn().mockResolvedValue({ data: { plans: [] }, status: 200, headers: {} }); + const fakeClient = { get, post: jest.fn() } as any; + const x402 = new X402Client(fakeClient); + + await x402.listPlans(); + + expect(get).toHaveBeenCalledWith('/cloud/x402/subscriptions/plans'); + }); + + it('subscribe() resolves normally when payment_proof already satisfies the backend', async () => { + const post = jest + .fn() + .mockResolvedValue({ data: { status: 'active', plan_id: 'pro' }, status: 200, headers: {} }); + const fakeClient = makeFakeClient(post); + const x402 = new X402Client(fakeClient); + + const result = await x402.subscribe({ plan_id: 'pro', payment_proof: { tx_hash: '0x1' } }); + + expect(post).toHaveBeenCalledWith('/cloud/x402/subscriptions/subscribe', { + plan_id: 'pro', + payment_proof: { tx_hash: '0x1' } + }); + expect(result.data.status).toBe('active'); + }); + + it('subscribe() throws a typed X402PaymentRequiredError on the 402 challenge, parsed from the header', async () => { + const headerValue = + 'Payment scheme="exact", network="base", asset="USDC", amount="2000", pay_to="0xdead"'; + + // Simulate what AINativeClient.handleError actually constructs: status + // 402 falls into the `default` branch => a generic AINativeError whose + // `.status === 402` and `.details` carries body + headers. We build + // that shape directly here (rather than importing AINativeError) so + // this test exercises X402Client's *own* conversion logic. + const rawAinativeStyleError = { + status: 402, + message: 'Payment required — pay the USDC amount', + details: { + detail: 'Payment required — pay the USDC amount', + error_code: 'payment_required', + next_action: 'submit_x402_payment', + requirements: { scheme: 'exact', network: 'base', asset: 'USDC', amount: 2000, pay_to: '0xdead' }, + headers: { 'www-authenticate': headerValue } + } + }; + + const post = jest.fn().mockRejectedValue(rawAinativeStyleError); + const fakeClient = makeFakeClient(post); + const x402 = new X402Client(fakeClient); + + await expect(x402.subscribe({ plan_id: 'pro' })).rejects.toBeInstanceOf(X402PaymentRequiredError); + + try { + await x402.subscribe({ plan_id: 'pro' }); + fail('expected subscribe() to throw'); + } catch (err) { + const typed = err as X402PaymentRequiredError; + // Header-derived requirements take precedence and should win over the + // body's (which had a numeric amount vs. the header's string one). + expect(typed.requirements).toEqual({ + scheme: 'exact', + network: 'base', + asset: 'USDC', + amount: '2000', + pay_to: '0xdead' + }); + } + }); + + it('subscribe() falls back to the JSON body requirements when no WWW-Authenticate header is present', async () => { + const rawError = { + status: 402, + message: 'Payment required', + details: { + detail: 'Payment required', + error_code: 'payment_required', + next_action: 'submit_x402_payment', + requirements: { scheme: 'exact', network: 'base', asset: 'USDC', amount: 2000, pay_to: '0xdead' }, + headers: {} + } + }; + const post = jest.fn().mockRejectedValue(rawError); + const x402 = new X402Client(makeFakeClient(post)); + + try { + await x402.subscribe({ plan_id: 'pro' }); + fail('expected subscribe() to throw'); + } catch (err) { + const typed = err as X402PaymentRequiredError; + expect(typed).toBeInstanceOf(X402PaymentRequiredError); + expect(typed.requirements).toEqual({ + scheme: 'exact', + network: 'base', + asset: 'USDC', + amount: 2000, + pay_to: '0xdead' + }); + } + }); + + it('subscribe() re-throws non-402 errors unchanged', async () => { + const validationError = new ValidationError('plan_id is required'); + const post = jest.fn().mockRejectedValue(validationError); + const x402 = new X402Client(makeFakeClient(post)); + + await expect(x402.subscribe({ plan_id: '' })).rejects.toBe(validationError); + }); + + it('getSubscription() calls GET with the right query params', async () => { + const get = jest.fn().mockResolvedValue({ data: { subscription: null }, status: 200, headers: {} }); + const fakeClient = { get, post: jest.fn() } as any; + const x402 = new X402Client(fakeClient); + + await x402.getSubscription({ walletAddress: '0xdead' }); + + expect(get).toHaveBeenCalledWith( + '/cloud/x402/subscriptions/subscription?wallet_address=0xdead' + ); + }); +}); diff --git a/tests/zerodb.test.ts b/tests/zerodb.test.ts index b65c235..8a899e8 100644 --- a/tests/zerodb.test.ts +++ b/tests/zerodb.test.ts @@ -40,7 +40,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.projects.list(); - expect(mockClient.get).toHaveBeenCalledWith('/public/projects?'); + expect(mockClient.get).toHaveBeenCalledWith('/projects?'); expect(response).toBe(mockResponse); }); @@ -50,7 +50,7 @@ describe('ZeroDBClient', () => { await zerodbClient.projects.list({ limit: 10, offset: 20 }); - expect(mockClient.get).toHaveBeenCalledWith('/public/projects?limit=10&offset=20'); + expect(mockClient.get).toHaveBeenCalledWith('/projects?limit=10&offset=20'); }); it('should handle partial pagination options', async () => { @@ -59,7 +59,7 @@ describe('ZeroDBClient', () => { await zerodbClient.projects.list({ limit: 5 }); - expect(mockClient.get).toHaveBeenCalledWith('/public/projects?limit=5'); + expect(mockClient.get).toHaveBeenCalledWith('/projects?limit=5'); }); }); @@ -71,7 +71,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.projects.create(projectData); - expect(mockClient.post).toHaveBeenCalledWith('/public/projects', projectData); + expect(mockClient.post).toHaveBeenCalledWith('/projects', projectData); expect(response).toBe(mockResponse); }); }); @@ -84,7 +84,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.projects.get(projectId); - expect(mockClient.get).toHaveBeenCalledWith(`/public/projects/${projectId}`); + expect(mockClient.get).toHaveBeenCalledWith(`/projects/${projectId}`); expect(response).toBe(mockResponse); }); }); @@ -98,7 +98,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.projects.update(projectId, updateData); - expect(mockClient.put).toHaveBeenCalledWith(`/public/projects/${projectId}`, updateData); + expect(mockClient.put).toHaveBeenCalledWith(`/projects/${projectId}`, updateData); expect(response).toBe(mockResponse); }); }); @@ -111,7 +111,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.projects.delete(projectId); - expect(mockClient.delete).toHaveBeenCalledWith(`/public/projects/${projectId}`); + expect(mockClient.delete).toHaveBeenCalledWith(`/projects/${projectId}`); expect(response).toBe(mockResponse); }); }); @@ -124,7 +124,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.projects.suspend(projectId); - expect(mockClient.post).toHaveBeenCalledWith(`/public/projects/${projectId}/suspend`); + expect(mockClient.post).toHaveBeenCalledWith(`/projects/${projectId}/suspend`); expect(response).toBe(mockResponse); }); }); @@ -137,7 +137,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.projects.activate(projectId); - expect(mockClient.post).toHaveBeenCalledWith(`/public/projects/${projectId}/activate`); + expect(mockClient.post).toHaveBeenCalledWith(`/projects/${projectId}/activate`); expect(response).toBe(mockResponse); }); }); @@ -152,7 +152,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.database.status(projectId); - expect(mockClient.get).toHaveBeenCalledWith(`/public/projects/${projectId}/database`); + expect(mockClient.get).toHaveBeenCalledWith(`/projects/${projectId}/database`); expect(response).toBe(mockResponse); }); }); @@ -165,7 +165,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.database.enable(projectId); - expect(mockClient.post).toHaveBeenCalledWith(`/public/projects/${projectId}/database`); + expect(mockClient.post).toHaveBeenCalledWith(`/projects/${projectId}/database`); expect(response).toBe(mockResponse); }); }); @@ -179,7 +179,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.database.updateConfig(projectId, config); - expect(mockClient.put).toHaveBeenCalledWith(`/public/projects/${projectId}/database`, config); + expect(mockClient.put).toHaveBeenCalledWith(`/projects/${projectId}/database`, config); expect(response).toBe(mockResponse); }); }); @@ -200,7 +200,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.vectors.upsert(projectId, vectorData); expect(mockClient.post).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/vectors/upsert`, + `/projects/${projectId}/database/vectors/upsert`, vectorData ); expect(response).toBe(mockResponse); @@ -221,7 +221,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.vectors.search(projectId, searchData); expect(mockClient.post).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/vectors/search`, + `/projects/${projectId}/database/vectors/search`, searchData ); expect(response).toBe(mockResponse); @@ -243,7 +243,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.vectors.batchUpsert(projectId, batchData); expect(mockClient.post).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/vectors/upsert-batch`, + `/projects/${projectId}/database/vectors/upsert-batch`, batchData.vectors ); expect(response).toBe(mockResponse); @@ -259,7 +259,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.vectors.list(projectId); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/vectors?` + `/projects/${projectId}/database/vectors?` ); expect(response).toBe(mockResponse); }); @@ -272,7 +272,7 @@ describe('ZeroDBClient', () => { await zerodbClient.vectors.list(projectId, 'test-namespace', 10); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/vectors?namespace=test-namespace&limit=10` + `/projects/${projectId}/database/vectors?namespace=test-namespace&limit=10` ); }); @@ -284,7 +284,7 @@ describe('ZeroDBClient', () => { await zerodbClient.vectors.list(projectId, undefined, 5); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/vectors?limit=5` + `/projects/${projectId}/database/vectors?limit=5` ); }); }); @@ -307,7 +307,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.memory.store(projectId, memoryData); expect(mockClient.post).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/memory/store`, + `/projects/${projectId}/database/memory/store`, memoryData ); expect(response).toBe(mockResponse); @@ -327,7 +327,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.memory.search(projectId, searchData); expect(mockClient.post).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/memory/search`, + `/projects/${projectId}/database/memory/search`, searchData ); expect(response).toBe(mockResponse); @@ -343,7 +343,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.memory.list(projectId); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/memory?` + `/projects/${projectId}/database/memory?` ); expect(response).toBe(mockResponse); }); @@ -356,7 +356,7 @@ describe('ZeroDBClient', () => { await zerodbClient.memory.list(projectId, { limit: 20, offset: 10 }); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/memory?limit=20&offset=10` + `/projects/${projectId}/database/memory?limit=20&offset=10` ); }); }); @@ -376,7 +376,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.events.publish(projectId, eventData); expect(mockClient.post).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/events/publish`, + `/projects/${projectId}/database/events/publish`, eventData ); expect(response).toBe(mockResponse); @@ -392,7 +392,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.events.list(projectId); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/events?` + `/projects/${projectId}/database/events?` ); expect(response).toBe(mockResponse); }); @@ -405,7 +405,7 @@ describe('ZeroDBClient', () => { await zerodbClient.events.list(projectId, 'user-activity', 50); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/events?topic=user-activity&limit=50` + `/projects/${projectId}/database/events?topic=user-activity&limit=50` ); }); }); @@ -417,7 +417,7 @@ describe('ZeroDBClient', () => { const eventSource = zerodbClient.events.stream(projectId); expect(EventSource).toHaveBeenCalledWith( - `https://test-api.com/api/v1/public/projects/${projectId}/database/events/stream?` + `https://test-api.com/api/v1/projects/${projectId}/database/events/stream?` ); expect(eventSource).toBe(mockEventSource); }); @@ -432,7 +432,7 @@ describe('ZeroDBClient', () => { const eventSource = zerodbClient.events.stream(projectId, options); expect(EventSource).toHaveBeenCalledWith( - `https://test-api.com/api/v1/public/projects/${projectId}/database/events/stream?topic=user-activity&from_timestamp=2023-01-01T00%3A00%3A00Z` + `https://test-api.com/api/v1/projects/${projectId}/database/events/stream?topic=user-activity&from_timestamp=2023-01-01T00%3A00%3A00Z` ); }); @@ -522,7 +522,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.files.upload(projectId, fileData); expect(mockClient.post).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/files/upload`, + `/projects/${projectId}/database/files/upload`, fileData ); expect(response).toBe(mockResponse); @@ -538,7 +538,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.files.list(projectId); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/files?` + `/projects/${projectId}/database/files?` ); expect(response).toBe(mockResponse); }); @@ -551,7 +551,7 @@ describe('ZeroDBClient', () => { await zerodbClient.files.list(projectId, { limit: 25, offset: 50 }); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/database/files?limit=25&offset=50` + `/projects/${projectId}/database/files?limit=25&offset=50` ); }); }); @@ -567,7 +567,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.analytics.usage(projectId); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/analytics/usage?` + `/projects/${projectId}/analytics/usage?` ); expect(response).toBe(mockResponse); }); @@ -580,7 +580,7 @@ describe('ZeroDBClient', () => { await zerodbClient.analytics.usage(projectId, 30); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/analytics/usage?days=30` + `/projects/${projectId}/analytics/usage?days=30` ); }); }); @@ -594,7 +594,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.analytics.costs(projectId); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/analytics/costs?` + `/projects/${projectId}/analytics/costs?` ); expect(response).toBe(mockResponse); }); @@ -607,7 +607,7 @@ describe('ZeroDBClient', () => { await zerodbClient.analytics.costs(projectId, 7); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/analytics/costs?days=7` + `/projects/${projectId}/analytics/costs?days=7` ); }); }); @@ -627,7 +627,7 @@ describe('ZeroDBClient', () => { const response = await zerodbClient.analytics.overview(projectId); expect(mockClient.get).toHaveBeenCalledWith( - `/public/projects/${projectId}/analytics` + `/projects/${projectId}/analytics` ); expect(response).toBe(mockResponse); });