Retry Challenge after a failed verify reflects pre-verify state, so clients pay a spent single-use recipient again

Abierto
#1,365 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
54/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
typescript
Área
payments

Línea de trabajo

Start by tracing resolveRouteChallenge and the method request and verify hooks described in the issue, then inspect how identityRejection handles 402 responses without a retry Challenge. Reproduce the flow with the supplied example and identify where the pre-verify Challenge is reused after verification fails. Done means a failing case proves the retry cannot pay the retired recipient, with coverage for both a terminal payment failure and a retryable backend error.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

friction
Expected Behavior

When a method's verify throws, the 402 that mppx returns should not offer a Challenge the method has just invalidated. Methods whose request hook depends on state that verify changes (single-use deposit addresses, quotes, invoices) need either a retry Challenge built after verify, or a way to reject without one.

Current Behavior

On a Credential-bearing request, resolveRouteChallenge runs the method's request hook with the Credential and builds the route Challenge before verify. A stateful method has to return what the Credential paid for, or the binding check fails. If verify then throws (for example the payment was refunded and the method retires that address), mppx emits that same pre-verify Challenge as the retry Challenge. The mppx client pays it, sending a second payment to a recipient the server has already retired. Reproduced on 0.22.0.

Possible Solution
  • Preferred: an opt-in way for a method to rebuild the retry Challenge after verify throws, for example a hook that receives the error and returns the request for the retry Challenge (or runs the request hook again without the Credential). The method can then return a fresh request after a terminal failure, and keep the original Challenge for errors where the Credential stays valid (such as a 503 from a backend outage).
  • Minimum: let a PaymentError thrown from verify opt out of the retry Challenge, the way identity rejections already return a 402 without one (identityRejection).
Minimal Reproducible Example
import { Credential, Errors, Method, z } from 'mppx'
import { Mppx as ClientMppx } from 'mppx/client'
import { Mppx as ServerMppx } from 'mppx/server'

const deposit = Method.from({
  name: 'deposit',
  intent: 'charge',
  schema: {
    credential: { payload: z.object({ hash: z.string() }) },
    request: z.object({ amount: z.string(), currency: z.string(), recipient: z.string() }),
  },
})

let next = 1
let current = `addr-${next}`
const spent = new Set<string>()

const route = ServerMppx.create({
  secretKey: 'repro-secret-key-of-at-least-32-bytes!!',
  methods: [
    Method.toServer(deposit, {
      defaults: { amount: '1', currency: 'usd', recipient: current },
      stableBinding: ({ amount, currency, recipient }) => ({ amount, currency, recipient }),
      async request({ credential, request }) {
        const paid = (credential?.challenge.request as { recipient?: string } | undefined)?.recipient
        return { ...request, recipient: paid && !spent.has(paid) ? paid : current }
      },
      async verify({ credential }) {
        const paid = (credential.challenge.request as { recipient: string }).recipient
        spent.add(paid) // e.g. the payment was refunded; this address is single-use
        current = `addr-${++next}`
        throw new Errors.VerificationFailedError({ reason: `payment to ${paid} was refunded` })
      },
    }),
  ],
}).charge({})

const payments: string[] = []
const client = ClientMppx.create({
  polyfill: false,
  fetch: (async (input: RequestInfo | URL, init?: RequestInit) => {
    const result = await route(new Request(input, init))
    return result.status === 402 ? result.challenge : result.withReceipt(Response.json({}))
  }) as typeof globalThis.fetch,
  methods: [
    Method.toClient(deposit, {
      async createCredential({ challenge }) {
        payments.push((challenge.request as { recipient: string }).recipient)
        return Credential.serialize(Credential.from({ challenge, payload: { hash: `tx-${payments.length}` } }))
      },
    }),
  ],
})

await client.fetch('https://example.com/resource')
console.log(payments) // ['addr-1', 'addr-1']: the second payment goes to the address verify already retired
Context

We maintain the nearintents payment method (@defuse-protocol/nearintents-mpp-sdk), where each Challenge carries a single-use cross-chain deposit address. After a refunded settlement, mppx's client sent a second real deposit to the spent address. We worked around it in our client method (it never pays the same deposit address twice for the same payer), but that only protects our client. A server-side fix would protect every client, and would let our server return the fresh Challenge our spec requires after settlement-failed.

Lenguaje dominante
TypeScript
Estrellas
196
Forks
79
Merge medio
15 h 20 min
PR fusionados (30 d)
156

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de wevm/mppx

Todos los issues de wevm/mppx

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.