π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(openapi): add Machine Payments Protocol middleware (HTTP 402) (#18518)
Arvin Xudc68e0a6eab6
diff --git a/packages/business-server/src/machine-payments/recordPayment.ts b/packages/business-server/src/machine-payments/recordPayment.tsnew file mode 100644index 00000000000..72810b4ef18--- /dev/null+++ b/packages/business-server/src/machine-payments/recordPayment.ts@@ -0,0 +1,9 @@+import type { MachinePaymentRecordParams } from './types';++/**+ * Records a settled machine payment.+ *+ * Open-source stub: no-op. Cloud overrides this to write the ledger row that+ * `/v1/usage` reads back.+ */+export async function recordPayment(_params: MachinePaymentRecordParams): Promise<void> {}diff --git a/packages/business-server/src/machine-payments/resolvePrice.ts b/packages/business-server/src/machine-payments/resolvePrice.tsnew file mode 100644index 00000000000..dad7ca05d96--- /dev/null+++ b/packages/business-server/src/machine-payments/resolvePrice.ts@@ -0,0 +1,20 @@+import type { MachinePaymentPrice, MachinePaymentPriceParams } from './types';++/**+ * Resolves the price for a machine-payable route.+ *+ * Open-source stub: returns `null`, meaning "this route is not for sale". The+ * middleware then issues no challenge and settles nothing, so a self-hosted+ * deployment keeps its current behaviour β every route stays behind normal+ * auth. Cloud overrides this with real pricing; self-hosters can override it+ * to sell their own instance.+ *+ * Returning an amount of `'0'` prices the route as a *metered free tier*: the+ * caller still has to answer the challenge with an identity proof, but no+ * money moves.+ */+export async function resolvePrice(+ _params: MachinePaymentPriceParams,+): Promise<MachinePaymentPrice | null> {+ return null;+}diff --git a/packages/business-server/src/machine-payments/types.ts b/packages/business-server/src/machine-payments/types.tsnew file mode 100644index 00000000000..0dd59128818--- /dev/null+++ b/packages/business-server/src/machine-payments/types.ts@@ -0,0 +1,40 @@+export interface MachinePaymentPriceParams {+ // No caller identity yet: the middleware verifies no request attestation+ // (Web Bot Auth / TAP), so pricing cannot depend on who is asking. Add an+ // attestation field here only together with the verifier that produces it.+ /**+ * Route scope, e.g. `GET /v1/search`. Bound into the challenge so a+ * credential minted for one route cannot be replayed against another.+ */+ route: string;+}++export interface MachinePaymentPrice {+ /** Amount in the currency's major unit as a decimal string, e.g. `'0.02'`. */+ amount: string;+ currency: string;+ /** Payment destination in the method's native format. */+ recipient?: string;+}++export interface MachinePaymentRecordParams {+ amount: string;+ /**+ * Payer identity as *claimed* by the credential's `source` field.+ *+ * Untrusted: the protocol does not authenticate `source`, so it is only as+ * trustworthy as the configured payment method's verification of it. A method+ * that verifies payment without binding `source` lets a valid payer attribute+ * usage to any identity. Do not treat it as an authenticated caller id.+ */+ claimedSource?: string;+ currency: string;+ /**+ * Method-native settlement reference taken from the receipt. Unique per+ * settlement, so it doubles as the idempotency key: the middleware calls+ * `recordPayment` exactly once and never retries, so an implementation that+ * needs durability must dedupe and re-drive on this value.+ */+ reference: string;+ route: string;+}diff --git a/packages/openapi/package.json b/packages/openapi/package.jsonindex 623692c37f0..d4fa6a9cf50 100644--- a/packages/openapi/package.json+++ b/packages/openapi/package.json@@ -23,6 +23,7 @@"hono-openapi": "^1.3.1","js-sha256": "^0.11.1","lodash": "^4.18.1",+ "mppx": "0.11.0","url-join": "^5.0.0","zod": "^4.4.3"},diff --git a/packages/openapi/src/middleware/machine-payment-rejections.test.ts b/packages/openapi/src/middleware/machine-payment-rejections.test.tsnew file mode 100644index 00000000000..a50fc7bf9fd--- /dev/null+++ b/packages/openapi/src/middleware/machine-payment-rejections.test.ts@@ -0,0 +1,91 @@+import { Hono } from 'hono';+import { Challenge, Credential } from 'mppx';+import { Mppx, stripe } from 'mppx/server';+import { describe, expect, it } from 'vitest';++import { machinePayment, requirePaymentOr } from './machine-payment';+import { withPaymentRejections } from './machine-payment-rejections';++// Drives the real `stripe.charge()` method from mppx. Only the Stripe SDK client+// is faked, so these tests break if upstream changes the errors it throws.++type PaymentIntentStatus = 'canceled' | 'processing' | 'requires_payment_method' | 'succeeded';++const createApp = (status: PaymentIntentStatus, { wrap = true } = {}) => {+ const client = {+ paymentIntents: { create: async () => ({ id: 'pi_test', status }) },+ };+ const method = stripe.charge({+ client: client as any,+ decimals: 2,+ networkId: 'internal',+ paymentMethodTypes: ['card'],+ } as any);++ const mppx = Mppx.create({+ methods: [wrap ? withPaymentRejections(method) : method],+ realm: 'lobehub.test',+ secretKey: 'machine-payment-test-secret-key-at-least-32-bytes',+ });++ const app = new Hono();+ app.get(+ '/search',+ machinePayment({+ methodKey: 'stripe/charge',+ mppx: mppx as any,+ resolvePrice: async () => ({ amount: '1.00', currency: 'usd' }),+ }),+ requirePaymentOr(async (c) => c.json({ error: 'unauthorized' }, 401)),+ (c) => c.json({ ok: true }),+ );+ return app;+};++const pay = async (app: Hono, payload: Record<string, unknown> = { spt: 'spt_test' }) => {+ const challenge = Challenge.fromResponse(await app.request('/search'));+ const credential = Credential.serialize(Credential.from({ challenge, payload }));+ return app.request('/search', { headers: { Authorization: credential } });+};++describe('withPaymentRejections (real stripe.charge)', () => {+ it('delivers a succeeded payment untouched', async () => {+ const res = await pay(createApp('succeeded'));++ expect(res.status).toBe(200);+ expect(res.headers.get('Payment-Receipt')).toBeTruthy();+ });++ it.each(['requires_payment_method', 'canceled'] as const)(+ 'answers a %s PaymentIntent with a fresh 402 challenge',+ async (status) => {+ const res = await pay(createApp(status));++ expect(res.status).toBe(402);+ expect(res.headers.get('WWW-Authenticate')).toMatch(/^Payment /);+ },+ );++ it('answers a malformed credential payload with a 402 challenge', async () => {+ // mppx core rejects this against the method schema before `verify` runs,+ // which is why the wrapper carries no pattern for it.+ const res = await pay(createApp('succeeded', { wrap: false }), { wrong: 'shape' });++ expect(res.status).toBe(402);+ expect(res.headers.get('WWW-Authenticate')).toMatch(/^Payment /);+ });++ it('keeps a still-processing charge a 500, since paying again could double-charge', async () => {+ const res = await pay(createApp('processing'));++ expect(res.status).toBe(500);+ });++ it('is what turns a declined card from a 500 into a 402', async () => {+ // Pins the upstream behaviour the wrapper exists for: without it, mppx maps+ // Stripe's plain Error to an InternalPaymentError.+ const res = await pay(createApp('requires_payment_method', { wrap: false }));++ expect(res.status).toBe(500);+ });+});diff --git a/packages/openapi/src/middleware/machine-payment-rejections.ts b/packages/openapi/src/middleware/machine-payment-rejections.tsnew file mode 100644index 00000000000..3383457eef0--- /dev/null+++ b/packages/openapi/src/middleware/machine-payment-rejections.ts@@ -0,0 +1,61 @@+import { Errors } from 'mppx';++/**+ * Plain `Error`s that official mppx methods throw from `verify` when the+ * *caller's* payment is at fault. mppx maps any non-`PaymentError` to a 500+ * `InternalPaymentError`, so without translation a declined card reads as our+ * outage instead of a payment the caller can retry.+ *+ * A malformed payload needs no entry: mppx core rejects it against the+ * method's schema with a 402 before `verify` runs.+ *+ * Matched on message because upstream gives them no type; `mppx` is pinned to+ * an exact version and the Stripe tests exercise the real method, so a changed+ * message fails CI rather than silently reverting to 500.+ *+ * Deliberately excluded: Stripe `processing`. The charge may still complete, so+ * answering with a fresh 402 challenge would invite the caller to pay twice. It+ * stays a 500 until it can be reported as pending.+ */+const CALLER_REJECTIONS: RegExp[] = [+ // stripe/server/Charge.js β the PaymentIntent ended in a terminal failure.+ /^Stripe PaymentIntent status: (?:requires_payment_method|canceled)$/,+];++/** Whether `error` is a known caller-caused payment failure (see above). */+export const isCallerPaymentRejection = (error: unknown): boolean =>+ error instanceof Error && CALLER_REJECTIONS.some((pattern) => pattern.test(error.message));++interface VerifyingMethod {+ verify: (parameters: any) => Promise<any>;+}++/**+ * Wraps a server payment method so a caller-caused rejection answers 402 with a+ * fresh challenge instead of a 500.+ *+ * Only errors `isRejection` recognises are translated. Everything else β a+ * misconfigured method, an unreachable payment network β keeps propagating as+ * a 500, because telling the caller to pay again when we cannot tell whether+ * the first payment landed risks charging them twice.+ *+ * Apply it where the method is constructed, before `Mppx.create()`:+ *+ * ```ts+ * Mppx.create({ methods: [withPaymentRejections(stripe.charge({ β¦ }))], β¦ })+ * ```+ */+export const withPaymentRejections = <M extends VerifyingMethod>(+ method: M,+ isRejection: (error: unknown) => boolean = isCallerPaymentRejection,+): M => ({+ ...method,+ verify: async (parameters: Parameters<M['verify']>[0]) => {+ try {+ return await method.verify(parameters);+ } catch (error) {+ if (error instanceof Errors.PaymentError || !isRejection(error)) throw error;+ throw new Errors.VerificationFailedError({ reason: (error as Error).message });+ }+ },+});diff --git a/packages/openapi/src/middleware/machine-payment.test.ts b/packages/openapi/src/middleware/machine-payment.test.tsnew file mode 100644index 00000000000..8fe048bec3a--- /dev/null+++ b/packages/openapi/src/middleware/machine-payment.test.ts@@ -0,0 +1,500 @@+import { createHmac } from 'node:crypto';++import { Hono, type MiddlewareHandler } from 'hono';+import { Challenge, Credential, Errors, Method, Store, z } from 'mppx';+import { Mppx } from 'mppx/server';+import { beforeEach, describe, expect, it } from 'vitest';++import type { MachinePaymentRecordParams } from '@/business/server/machine-payments/types';++import { machinePayment, type MachinePaymentConfig, requirePaymentOr } from './machine-payment';++// ---------------------------------------------------------------------------+// Fixture: a self-contained payment rail+//+// "Settlement" is an HMAC over the challenge id, which is obviously not a+// payment β it has the same *shape* as one, so the challenge / credential /+// receipt loop, route binding and replay rules are exercised for real without+// reaching a payment network. A deployment swaps this for `stripe.charge()` or+// `tempo.charge()` at the `Mppx.create()` call site; the middleware is+// method-agnostic and does not change.+// ---------------------------------------------------------------------------++const WALLET_SECRET = 'machine-payment-test-wallet-secret';+const METHOD_NAME = 'lobehub-test';+const METHOD_KEY = `${METHOD_NAME}/charge`;++const testCharge = Method.from({+ intent: 'charge',+ name: METHOD_NAME,+ schema: {+ credential: {+ payload: z.object({ signature: z.string(), type: z.enum(['payment', 'proof']) }),+ },+ request: z.object({ amount: z.string(), currency: z.string() }),+ },+});++const sign = (challengeId: string, type: 'payment' | 'proof') =>+ createHmac('sha256', WALLET_SECRET).update(`${challengeId}:${type}`).digest('base64url');++interface Settlement {+ amount: string;+ type: string;+}++const createTestMethod = (settlements: Settlement[]) => {+ const store = Store.memory();++ return {+ ...testCharge,+ verify: async ({ credential, request }: any) => {+ const payload = credential.payload as { signature: string; type: 'payment' | 'proof' };++ // A zero-amount challenge is the metered free tier: the caller proves who+ // it is, but no value moves. Anything else must carry a real payment.+ //+ // Rejections must be typed `PaymentError`s: mppx answers them with a fresh+ // 402 challenge, but maps any other throw to a 500 InternalPaymentError.+ const expectedType = request.amount === '0' ? 'proof' : 'payment';+ if (payload.type !== expectedType)+ throw new Errors.VerificationFailedError({+ reason: `expected a "${expectedType}" credential`,+ });+ if (payload.signature !== sign(credential.challenge.id, payload.type))+ throw new Errors.VerificationFailedError({ reason: 'invalid payment proof' });++ // Replay protection belongs to the method, not the protocol: mppx core+ // re-verifies a credential happily, and only the method knows what+ // "already spent" means for its rail. Card / stablecoin methods inherit+ // this from the network; a method without such a rail must claim the+ // challenge id itself.+ const expires = credential.challenge.expires+ ? Date.parse(credential.challenge.expires)+ : Date.now() + 60_000;+ if (!(await Store.tryClaim(store, `test:${credential.challenge.id}`, expires)))+ throw new Errors.VerificationFailedError({ reason: 'credential has already been used' });++ settlements.push({ amount: request.amount, type: payload.type });++ return {+ method: METHOD_NAME,+ reference: `ref_${credential.challenge.id.slice(0, 12)}`,+ status: 'success' as const,+ timestamp: new Date().toISOString(),+ };+ },+ };+};++// ---------------------------------------------------------------------------++/**+ * Stands in for the app-wide `userAuthMiddleware`, minus the database. Like the+ * real one it runs before route middleware and only *records* who the caller+ * is β including its development bypass, which authenticates a request that+ * carries no `Authorization` header at all.+ */+const fakeUserAuth: MiddlewareHandler = async (c, next) => {+ const isApiKey = c.req.header('Authorization')?.startsWith('Bearer sk-lh-');+ const isDevBypass = c.req.header('lobe-auth-dev-backend-api') === '1';+ if (isApiKey || isDevBypass) (c as any).set('userId', isDevBypass ? 'DEV_USER' : 'user-1');+ return next();+};++/** Stands in for `requireAuth`: the gate reads the resolved user, not headers. */+const fakeAuth: MiddlewareHandler = async (c, next) =>+ (c as any).get('userId') ? next() : c.json({ error: 'unauthorized' }, 401);++/**+ * Stands in for the cloud override of `resolvePrice`. The open-source stub+ * returns `null` for everything, which is the `/ping` row below.+ */+const PRICES: Record<string, { amount: string; currency: string } | null> = {+ 'GET /ping': null,+ 'GET /search': { amount: '0.02', currency: 'usd' },+ 'GET /search/boom': { amount: '0.05', currency: 'usd' },+ 'GET /search/free': { amount: '0', currency: 'usd' },+};++interface AppOptions {+ prices?: Record<string, { amount: string; currency: string } | null>;+ recorded?: MachinePaymentRecordParams[];+ recordPayment?: (params: MachinePaymentRecordParams) => Promise<void>;+ resolvePrice?: MachinePaymentConfig['resolvePrice'];+ settlements?: Settlement[];+}++const createApp = (options: AppOptions = {}) => {+ const {+ prices = PRICES,+ recorded = [],+ settlements = [],+ recordPayment = async (params: MachinePaymentRecordParams) => {+ recorded.push(params);+ },+ resolvePrice = async ({ route }: { route: string }) => prices[route] ?? null,+ } = options;++ const mppx = Mppx.create({+ methods: [createTestMethod(settlements)],+ realm: 'lobehub.test',+ secretKey: 'machine-payment-test-secret-key-at-least-32-bytes',+ });++ const pay = machinePayment({+ methodKey: METHOD_KEY,+ mppx: mppx as any,+ recordPayment,+ resolvePrice,+ });++ const app = new Hono();+ app.use('*', fakeUserAuth);+ const handler = (c: any) => c.json({ ok: true, tier: c.get('machinePaymentTier') });++ app.get('/ping', pay, requirePaymentOr(fakeAuth), handler);+ app.get('/search/free', pay, requirePaymentOr(fakeAuth), handler);+ app.get('/search', pay, requirePaymentOr(fakeAuth), handler);+ app.get('/search/boom', pay, requirePaymentOr(fakeAuth), () => {+ throw new Error('handler exploded after settlement');+ });++ return app;+};++describe('machinePayment', () => {+ let app: ReturnType<typeof createApp>;+ let settlements: Settlement[];+ let recorded: MachinePaymentRecordParams[];++ beforeEach(() => {+ settlements = [];+ recorded = [];+ app = createApp({ recorded, settlements });+ });++ /** Reads the 402 challenge for a route without answering it. */+ const challengeFor = async (path: string) => {+ const res = await app.request(path);+ expect(res.status).toBe(402);+ return Challenge.fromResponse(res);+ };++ /** Mints a credential, defaulting to the proof type the challenge requires. */+ const mint = (challenge: any, type?: 'payment' | 'proof') => {+ const t = type ?? (challenge.request.amount === '0' ? 'proof' : 'payment');+ return Credential.serialize(+ Credential.from({+ challenge,+ payload: { signature: sign(challenge.id, t), type: t },+ source: 'did:test:agent-001',+ }),+ );+ };++ const submit = (path: string, credential: string) =>+ app.request(path, { headers: { Authorization: credential } });++ describe('unpriced routes (open-source default)', () => {+ it('issues no challenge and keeps the route behind auth', async () => {+ const res = await app.request('/ping');++ expect(res.status).toBe(401);+ // An unpriced route must not advertise itself as purchasable, or a caller+ // would believe paying is a way around authentication.+ expect(res.headers.get('WWW-Authenticate')).toBeNull();+ });++ it('serves the route to an authenticated caller', async () => {+ const res = await app.request('/ping', { headers: { Authorization: 'Bearer sk-lh-test' } });++ expect(res.status).toBe(200);+ // Reported as `authenticated`, not `unpriced`: a non-Payment credential+ // short-circuits before `resolvePrice` is consulted at all.+ expect(await res.json()).toEqual({ ok: true, tier: 'authenticated' });+ });++ it('settles nothing', async () => {+ await app.request('/ping', { headers: { Authorization: 'Bearer sk-lh-test' } });++ expect(settlements).toHaveLength(0);+ });+ });++ describe('free tier (zero-amount challenge)', () => {+ it('challenges for zero value', async () => {+ expect((await challengeFor('/search/free')).request.amount).toBe('0');+ });++ it('serves the route after an identity proof, with no account', async () => {+ const challenge = await challengeFor('/search/free');+ const res = await submit('/search/free', mint(challenge));++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ ok: true, tier: 'free' });+ });++ it('records the call without charging', async () => {+ const challenge = await challengeFor('/search/free');+ await submit('/search/free', mint(challenge));++ expect(settlements).toEqual([{ amount: '0', type: 'proof' }]);+ });++ it('rejects a payment-typed credential where a proof is required', async () => {+ const challenge = await challengeFor('/search/free');+ const res = await submit('/search/free', mint(challenge, 'payment'));++ expect(res.status).toBe(402);+ expect(settlements).toHaveLength(0);+ });+ });++ describe('paid tier', () => {+ it('challenges for the resolved price', async () => {+ expect((await challengeFor('/search')).request).toMatchObject({+ amount: '0.02',+ currency: 'usd',+ });+ });++ it('serves the route and attaches a receipt after payment', async () => {+ const challenge = await challengeFor('/search');+ const res = await submit('/search', mint(challenge));++ expect(res.status).toBe(200);+ expect(await res.json()).toMatchObject({ tier: 'paid' });+ // The receipt is attached server-side after settlement, so it cannot be+ // forged into the response: a 200 carrying one is a paid 200.+ expect(res.headers.get('Payment-Receipt')).toBeTruthy();+ });++ it('rejects a free-tier proof presented against a priced challenge', async () => {+ const challenge = await challengeFor('/search');+ const res = await submit('/search', mint(challenge, 'proof'));++ expect(res.status).toBe(402);+ expect(settlements).toHaveLength(0);+ });++ it('rejects a forged proof', async () => {+ const challenge = await challengeFor('/search');+ const forged = Credential.serialize(+ Credential.from({ challenge, payload: { signature: 'not-a-signature', type: 'payment' } }),+ );++ const res = await submit('/search', forged);++ expect(res.status).toBe(402);+ expect(settlements).toHaveLength(0);+ });+ });++ describe('credential scoping', () => {+ it('does not accept a credential minted for another route', async () => {+ // Without route binding, a caller could answer the cheapest endpoint's+ // challenge and spend it on the most expensive one.+ const challenge = await challengeFor('/search/free');+ const res = await submit('/search', mint(challenge));++ expect(res.status).toBe(402);+ expect(settlements).toHaveLength(0);+ });++ it('binds the issuing route into the challenge', async () => {+ const challenge = await challengeFor('/search/free');+ const opaque = JSON.parse(Buffer.from(challenge.opaque!, 'base64url').toString('utf8'));++ expect(opaque).toMatchObject({ _mppx_scope: 'GET /search/free' });+ });+ });++ describe('replay', () => {+ it('does not settle the same credential twice', async () => {+ const challenge = await challengeFor('/search');+ const credential = mint(challenge);++ const first = await submit('/search', credential);+ const second = await submit('/search', credential);++ expect(first.status).toBe(200);+ expect(second.status).toBe(402);+ expect(settlements).toHaveLength(1);+ });+ });++ describe('authenticated callers on a priced route', () => {+ it('serves an API-key caller without demanding payment', async () => {+ // Pricing an existing route must not replace authentication: its current+ // authenticated clients would all start getting 402.+ const res = await app.request('/search', { headers: { Authorization: 'Bearer sk-lh-test' } });++ expect(res.status).toBe(200);+ expect(settlements).toHaveLength(0);+ });++ it('reports the request as authenticated rather than paid', async () => {+ const res = await app.request('/search', { headers: { Authorization: 'Bearer sk-lh-test' } });++ expect(await res.json()).toEqual({ ok: true, tier: 'authenticated' });+ });++ it('still rejects a bad Bearer token instead of letting it skip both gates', async () => {+ const res = await app.request('/search', { headers: { Authorization: 'Bearer nope' } });++ expect(res.status).toBe(401);+ expect(settlements).toHaveLength(0);+ });++ it('serves a caller authenticated without an Authorization header', async () => {+ // The development bypass resolves a user from a debug header alone, so a+ // header-only check would treat this authenticated caller as anonymous.+ const res = await app.request('/search', { headers: { 'lobe-auth-dev-backend-api': '1' } });++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ ok: true, tier: 'authenticated' });+ expect(settlements).toHaveLength(0);+ });++ it('challenges a caller that presents no credential at all', async () => {+ const res = await app.request('/search');++ expect(res.status).toBe(402);+ });+ });++ describe('ledger recording', () => {+ it('records a paid settlement with its route, price, reference and payer', async () => {+ const challenge = await challengeFor('/search');+ await submit('/search', mint(challenge));++ expect(recorded).toEqual([+ {+ amount: '0.02',+ currency: 'usd',+ reference: expect.stringContaining('ref_'),+ route: 'GET /search',+ claimedSource: 'did:test:agent-001',+ },+ ]);+ });++ it('records a zero-amount free-tier call so the tier stays metered', async () => {+ const challenge = await challengeFor('/search/free');+ await submit('/search/free', mint(challenge));++ expect(recorded).toEqual([+ expect.objectContaining({ amount: '0', route: 'GET /search/free' }),+ ]);+ });++ it('records nothing when no payment settled', async () => {+ await app.request('/ping', { headers: { Authorization: 'Bearer sk-lh-test' } });++ expect(recorded).toHaveLength(0);+ });+ });++ describe('settled requests that fail downstream', () => {+ it('still returns the receipt when the handler throws', async () => {+ const challenge = await challengeFor('/search/boom');+ const res = await submit('/search/boom', mint(challenge));++ // The credential already settled and cannot be replayed, so an+ // unreceipted error would leave the payer unable to prove the charge.+ expect(settlements).toHaveLength(1);+ expect(res.headers.get('Payment-Receipt')).toBeTruthy();+ });++ it('surfaces the failure rather than reporting success', async () => {+ const challenge = await challengeFor('/search/boom');+ const res = await submit('/search/boom', mint(challenge));++ expect(res.status).toBeGreaterThanOrEqual(500);+ });+ });++ describe('when ledger recording fails', () => {+ const brokenLedger = () => {+ const seen: Settlement[] = [];+ const app = createApp({+ recordPayment: async () => {+ throw new Error('ledger unavailable');+ },+ settlements: seen,+ });+ return { app, seen };+ };++ it('still delivers the resource the caller paid for', async () => {+ // The credential is spent either way, so withholding delivery would make+ // the caller pay a second time to get what they already bought.+ const { app: broken, seen } = brokenLedger();+ const challenge = Challenge.fromResponse(await broken.request('/search'));+ const res = await broken.request('/search', {+ headers: { Authorization: mint(challenge) },+ });++ expect(res.status).toBe(200);+ expect(seen).toHaveLength(1);+ });++ it('still returns the receipt so the settlement stays provable', async () => {+ const { app: broken } = brokenLedger();+ const challenge = Challenge.fromResponse(await broken.request('/search'));+ const res = await broken.request('/search', {+ headers: { Authorization: mint(challenge) },+ });++ expect(res.headers.get('Payment-Receipt')).toBeTruthy();+ });+ });++ describe('when the pricing backend is down', () => {+ const brokenPricing = () =>+ createApp({+ resolvePrice: async () => {+ throw new Error('pricing backend unavailable');+ },+ });++ it('still serves an authenticated caller', async () => {+ // Pricing a route must not make its existing authenticated clients+ // depend on the availability of a service they never pay.+ const res = await brokenPricing().request('/search', {+ headers: { Authorization: 'Bearer sk-lh-test' },+ });++ expect(res.status).toBe(200);+ });++ it('does not quietly serve an anonymous caller', async () => {+ const res = await brokenPricing().request('/search');++ expect(res.status).not.toBe(200);+ });+ });++ describe('a quote that is no longer current', () => {+ it('is refused rather than settled at either price', async () => {+ // mppx binds the amount into the challenge id, so a stale quote cannot be+ // spent. This pins that invariant: the ledger derives its amount from the+ // settled credential, and this is what keeps the two from ever diverging.+ const prices = { ...PRICES };+ const settlements: Settlement[] = [];+ const recorded: MachinePaymentRecordParams[] = [];+ const repriced = createApp({ prices, recorded, settlements });++ const challenge = Challenge.fromResponse(await repriced.request('/search'));+ prices['GET /search'] = { amount: '0.05', currency: 'usd' };+ const res = await repriced.request('/search', {+ headers: { Authorization: mint(challenge) },+ });++ expect(res.status).toBe(402);+ expect(settlements).toHaveLength(0);+ expect(recorded).toHaveLength(0);+ });+ });+});diff --git a/packages/openapi/src/middleware/machine-payment.ts b/packages/openapi/src/middleware/machine-payment.tsnew file mode 100644index 00000000000..ee41d930109--- /dev/null+++ b/packages/openapi/src/middleware/machine-payment.ts@@ -0,0 +1,235 @@+import debug from 'debug';+import type { MiddlewareHandler } from 'hono';+import { Credential, Receipt } from 'mppx';++import type {+ MachinePaymentPrice,+ MachinePaymentPriceParams,+ MachinePaymentRecordParams,+} from '@/business/server/machine-payments/types';++const log = debug('lobe-hono:machine-payment');++const RECEIPT_HEADER = 'Payment-Receipt';++/** Outcome of a composed mppx handler for one HTTP request. */+export type ComposedPaymentResult =+ | { challenge: Response; status: 402 }+ | { status: 200; withReceipt: (response: Response) => Response };++/**+ * Structural view of the mppx instance this middleware needs.+ *+ * Kept structural on purpose: which payment methods the instance carries+ * (Stripe SPT, Tempo stablecoin, β¦) is a deployment decision that belongs to+ * the layer that constructs it, not to the protocol plumbing here.+ */+export interface MachinePaymentMppx {+ compose: (+ ...entries: [string, Record<string, unknown>][]+ ) => (input: Request) => Promise<ComposedPaymentResult>;+}++export interface MachinePaymentConfig {+ /** Canonical `name/intent` key of the configured method, e.g. `stripe/charge`. */+ methodKey: string;+ /**+ * Must carry replay protection. mppx core never dedupes credentials β that is+ * the payment method's job (e.g. `tempo.charge()` only protects when given a+ * `store`). Without it, one credential settles on every request that repeats+ * it.+ *+ * A method's `verify` must reject with an mppx `PaymentError` (e.g.+ * `Errors.VerificationFailedError`) to answer 402; any other throw becomes a+ * 500 `InternalPaymentError`. Official methods do not always comply β Stripe+ * throws a plain `Error` for a declined card β so wrap each method with+ * `withPaymentRejections` (./machine-payment-rejections) before `Mppx.create()`.+ */+ mppx: MachinePaymentMppx;+ /**+ * Invoked once per settlement, before the handler runs.+ *+ * Called exactly once and never retried, and a rejection is logged rather+ * than propagated β a caller who paid still gets what they bought. Durability+ * is therefore the implementation's job: make it idempotent on `reference`+ * (unique per settlement) and write through an outbox if the ledger can be+ * unavailable.+ */+ recordPayment?: (params: MachinePaymentRecordParams) => Promise<void>;+ resolvePrice: (params: MachinePaymentPriceParams) => Promise<MachinePaymentPrice | null>;+}++declare module 'hono' {+ interface ContextVariableMap {+ /** True only after a challenge was answered and settled for this request. */+ machinePaymentSettled?: boolean;+ machinePaymentTier?: 'authenticated' | 'free' | 'paid' | 'unpriced';+ }+}++const routeOf = (method: string, url: string) => `${method} ${new URL(url).pathname}`;++/**+ * Gates a route behind the Machine Payments Protocol (HTTP 402).+ *+ * Four outcomes:+ *+ * - `resolvePrice` returns `null` β the route is not for sale. No challenge is+ * issued and nothing is settled; the request falls through untouched so the+ * normal auth chain still governs it. This is the open-source default.+ * - the caller presents a non-Payment credential β it is asking to be+ * authenticated, not to buy. See below.+ * - amount `'0'` β metered free tier. The caller must still answer the+ * challenge with an identity proof, but no money moves.+ * - any other amount β the caller pays before the handler runs.+ *+ * The middleware never grants access on its own. It only *records* that a+ * payment settled, via `machinePaymentSettled`. Pair it with+ * {@link requirePaymentOr} so an unpriced route stays behind authentication+ * instead of silently becoming public.+ */+export const machinePayment = (config: MachinePaymentConfig): MiddlewareHandler => {+ const { methodKey, mppx, recordPayment, resolvePrice } = config;++ return async (c, next) => {+ const route = routeOf(c.req.method, c.req.url);++ // A caller holding a non-Payment credential is asking to be authenticated,+ // not to buy. Challenging it would mean that pricing an existing route+ // silently *replaces* authentication: every current API-key client of that+ // route would start getting 402. Hand it to the auth chain instead β which+ // still rejects it if the credential is bad, since nothing settled.+ //+ // This runs before `resolvePrice` on purpose. Pricing is a separate backend+ // and it can be down; resolving first would make callers who never pay+ // depend on its availability to reach a route they already have access to.+ //+ // A resolved `userId` counts too: the app-wide `userAuthMiddleware` runs+ // first, and its development bypass authenticates a request that carries no+ // `Authorization` header at all. The header check still matters for a bad+ // token, which leaves `userId` unset and must reach the auth chain's 401.+ const authorization = c.req.header('Authorization');+ const alreadyAuthenticated = Boolean(c.get('userId'));+ if (+ alreadyAuthenticated ||+ (authorization && !Credential.extractPaymentScheme(authorization))+ ) {+ c.set('machinePaymentTier', 'authenticated');+ return next();+ }++ const price = await resolvePrice({ route });++ if (!price) {+ c.set('machinePaymentTier', 'unpriced');+ return next();+ }++ const result = await mppx.compose([+ methodKey,+ {+ amount: price.amount,+ currency: price.currency,+ // Binds the challenge to this route, so a credential minted for one+ // endpoint cannot be replayed against another.+ scope: route,+ ...(price.recipient ? { recipient: price.recipient } : {}),+ },+ ])(c.req.raw);++ if (result.status === 402) return result.challenge;++ c.set('machinePaymentTier', price.amount === '0' ? 'free' : 'paid');+ c.set('machinePaymentSettled', true);++ // Attach the receipt *before* the handler runs. Hono merges context headers+ // into the handler's response and into the error handler's alike, so a+ // request that settled always carries its proof of payment β even when+ // delivery fails afterwards. Assigning to `c.res` after `next()` would drop+ // the receipt on the throw path, leaving a charged caller unable to prove+ // the charge while the spent credential is refused as a replay on retry.+ const receiptHeader = result.withReceipt(new Response(null)).headers.get(RECEIPT_HEADER);+ if (receiptHeader) c.header(RECEIPT_HEADER, receiptHeader);++ // Amount and currency come from the settled credential rather than the+ // price just resolved: the ledger should record what was actually charged.+ // mppx binds the amount into the challenge id and refuses a stale quote, so+ // the two cannot currently diverge β reading the settled value keeps that+ // true without depending on the invariant holding.+ const settled = settlementOf(c.req.raw);++ // Recorded before delivery for the same reason as the receipt: the money+ // moved whether or not the handler succeeds, so the ledger has to see it+ // either way.+ //+ // But bookkeeping must never cost the caller what they just bought. If the+ // ledger is down, letting it reject here would charge them, withhold the+ // resource, and leave a spent credential that a retry refuses as a replay β+ // so they would have to pay twice. Delivery wins; reconciling a missed row+ // is our problem. Durability belongs to the `recordPayment` implementation,+ // which this middleware calls exactly once and never retries.+ try {+ await recordPayment?.({+ amount: settled.amount ?? price.amount,+ currency: settled.currency ?? price.currency,+ reference: receiptHeader ? Receipt.deserialize(receiptHeader).reference : '',+ route,+ ...(settled.claimedSource ? { claimedSource: settled.claimedSource } : {}),+ });+ } catch (error) {+ log(+ 'recordPayment failed for a settled request: route=%s receipt=%s %O',+ route,+ receiptHeader,+ error,+ );+ }++ return next();+ };+};++interface SettledCredential {+ amount?: string;+ claimedSource?: string;+ currency?: string;+}++/**+ * What the settled credential itself declares. The amount and currency are+ * authoritative β mppx binds them into the verified challenge. The payer is+ * not: `source` is caller-supplied and only as trustworthy as the payment+ * method's verification of it, so it is surfaced as a claim.+ *+ * Never throws: the credential already verified, so a parse failure here only+ * means those details are unknown. Failing a settled request over unreadable+ * bookkeeping fields would charge the caller and then deny them the resource.+ */+const settlementOf = (request: Request): SettledCredential => {+ try {+ const credential = Credential.fromRequest(request);+ const charged = credential.challenge?.request as Record<string, unknown> | undefined;++ return {+ ...(typeof charged?.amount === 'string' ? { amount: charged.amount } : {}),+ ...(typeof charged?.currency === 'string' ? { currency: charged.currency } : {}),+ ...(credential.source ? { claimedSource: credential.source } : {}),+ };+ } catch {+ return {};+ }+};++/**+ * Fail-closed bridge between payment and authentication.+ *+ * Skips `fallback` only when {@link machinePayment} actually settled a payment+ * for this request. When no price was configured β the open-source default β+ * nothing settles, so `fallback` runs and the route keeps exactly the+ * protection it has today. Getting this default backwards would turn every+ * self-hosted deployment's API into an open endpoint.+ */+export const requirePaymentOr =+ (fallback: MiddlewareHandler): MiddlewareHandler =>+ async (c, next) =>+ c.get('machinePaymentSettled') === true ? next() : fallback(c, next);