Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions internal/x402/payer_context_test.go
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
package x402

import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)

func TestSplicePayerSystemMessage(t *testing.T) {
payer := "0x2447b86f22245fa1271978bF37907D07EDE06261"

t.Run("prepends system message and preserves the rest", func(t *testing.T) {
body := []byte(`{"model":"openrouter/auto","stream":true,"messages":[{"role":"user","content":"claim my airdrop"}]}`)
out, ok := splicePayerSystemMessage(body, payer)
if !ok {
t.Fatalf("expected ok")
}
var doc struct {
Model string `json:"model"`
Stream bool `json:"stream"`
Messages []struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"messages"`
}
if err := json.Unmarshal(out, &doc); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if doc.Model != "openrouter/auto" || !doc.Stream {
t.Fatalf("sibling fields not preserved: %+v", doc)
}
if len(doc.Messages) != 2 {
t.Fatalf("want 2 messages, got %d", len(doc.Messages))
}
if doc.Messages[0].Role != "system" || !strings.Contains(doc.Messages[0].Content, payer) {
t.Fatalf("system payer message not first: %+v", doc.Messages[0])
}
if doc.Messages[1].Content != "claim my airdrop" {
t.Fatalf("user message mangled: %+v", doc.Messages[1])
}
})

t.Run("non-JSON body passes through", func(t *testing.T) {
body := []byte("not json")
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != "not json" {
t.Fatalf("expected byte-identical passthrough, got ok=%v out=%q", ok, out)
}
})

t.Run("JSON without messages passes through", func(t *testing.T) {
body := []byte(`{"model":"x"}`)
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != `{"model":"x"}` {
t.Fatalf("expected passthrough, got ok=%v out=%q", ok, out)
}
})
}

// proxyBodySeen runs a request through buildUpstreamProxy for the given rule
// and returns the body + headers the upstream received.
func proxyBodySeen(t *testing.T, rule *RouteRule, reqPath, body string, hdr map[string]string) (string, http.Header) {
t.Helper()
var gotBody string
var gotHeader http.Header
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
gotHeader = r.Header.Clone()
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
rule.UpstreamURL = upstream.URL

proxy, err := buildUpstreamProxy(rule)
if err != nil {
t.Fatalf("buildUpstreamProxy: %v", err)
}
req := httptest.NewRequest(http.MethodPost, reqPath, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
for k, v := range hdr {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
proxy.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("proxy status = %d", rec.Code)
}
return gotBody, gotHeader
}

func TestBuildUpstreamProxy_InjectsPayerContextForAgentOffers(t *testing.T) {
payer := "0xD0391EeDc3268F3deeF1F05fff5D7aEf82F64cCF"
chatBody := `{"model":"openrouter/auto","messages":[{"role":"user","content":"claim mine"}]}`

t.Run("agent offer with verified payer gets the system message", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) || !strings.Contains(body, "x402 payment context") {
t.Fatalf("payer context not injected; upstream saw: %s", body)
}
if !strings.Contains(body, "claim mine") {
t.Fatalf("original user message lost: %s", body)
}
})

t.Run("falls back to SIWX verified wallet", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderVerifiedWallet: payer})
if !strings.Contains(body, payer) {
t.Fatalf("verified-wallet fallback not injected; upstream saw: %s", body)
}
})

t.Run("no identity header means untouched body", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody, nil)
if body != chatBody {
t.Fatalf("body modified without identity header: %s", body)
}
})

t.Run("non-agent offers are untouched", func(t *testing.T) {
rule := &RouteRule{OfferType: "http", StripPrefix: "/services/api"}
body, _ := proxyBodySeen(t, rule, "/services/api/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if body != chatBody {
t.Fatalf("http offer body modified: %s", body)
}
})

t.Run("normalized bare path also gets injection", func(t *testing.T) {
// Buyers frequently POST to the service base; normalizeChatCompletionsPath
// rewrites it to /v1/chat/completions, and injection must follow.
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) {
t.Fatalf("payer context not injected on normalized path; upstream saw: %s", body)
}
})

t.Run("content-length is recomputed", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, hdr := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if cl := hdr.Get("Content-Length"); cl != "" {
n, err := strconv.Atoi(cl)
if err != nil || n != len(body) {
t.Fatalf("content-length %q != body length %d", cl, len(body))
}
}
})
}
100 changes: 100 additions & 0 deletions internal/x402/verifier.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,18 @@ package x402

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
Expand DownExpand Up@@ -824,6 +828,7 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
} else if rule.UpstreamAuth != "" {
pr.Out.Header.Set("Authorization", rule.UpstreamAuth)
}
injectAgentPayerContext(pr, rule)
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("x402-verifier: upstream proxy error for %s/%s: %v", rule.OfferNamespace, rule.OfferName, err)
Expand All@@ -837,6 +842,101 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
// agent upstreams (LiteLLM, Hermes).
const chatCompletionsPath = "/v1/chat/completions"

// payerContextBodyLimit caps how much of a chat-completions request body the
// verifier buffers to splice in the payer-context system message. Larger
// bodies pass through byte-identical.
const payerContextBodyLimit = 4 << 20

// injectAgentPayerContext rewrites a paid agent-offer chat request so the
// verified payer wallet rides IN-BAND as a leading system message. The
// X-Payment-Payer header alone doesn't reach the model — agent runtimes drop
// HTTP headers before the LLM sees the conversation — so without this a buyer
// must repeat their own address in the prompt. Identity headers are
// verifier-set only (client copies are stripped at HandleProxy entry), so the
// injected value is an authenticated fact.
//
// Injection is strictly best-effort: any shape we don't fully understand
// (non-JSON, no messages array, oversized or unreadable body, compressed
// content) leaves the request byte-identical rather than risking a paid
// request.
func injectAgentPayerContext(pr *httputil.ProxyRequest, rule *RouteRule) {
if rule.OfferType != "agent" || pr.Out.Method != http.MethodPost ||
pr.Out.URL.Path != chatCompletionsPath || pr.Out.Body == nil {
return
}
if ce := pr.In.Header.Get("Content-Encoding"); ce != "" && !strings.EqualFold(ce, "identity") {
return
}
if ct := pr.In.Header.Get("Content-Type"); ct != "" && !strings.Contains(strings.ToLower(ct), "json") {
return
}
payer := pr.In.Header.Get(HeaderPaymentPayer)
if payer == "" {
payer = pr.In.Header.Get(HeaderVerifiedWallet)
}
if payer == "" {
return
}

orig := pr.Out.Body
body, err := io.ReadAll(io.LimitReader(orig, payerContextBodyLimit+1))
if err != nil || len(body) > payerContextBodyLimit {
// Splice the consumed bytes back in front of the unread remainder so
// the upstream still receives the full original body.
pr.Out.Body = struct {
io.Reader
io.Closer
}{io.MultiReader(bytes.NewReader(body), orig), orig}
return
}
orig.Close()

newBody, ok := splicePayerSystemMessage(body, payer)
if !ok {
newBody = body
}
pr.Out.Body = io.NopCloser(bytes.NewReader(newBody))
pr.Out.ContentLength = int64(len(newBody))
pr.Out.Header.Set("Content-Length", strconv.Itoa(len(newBody)))
}

// splicePayerSystemMessage prepends a system message carrying the verified
// payer wallet to an OpenAI chat-completions JSON body. Returns the original
// bytes and false when the body isn't the expected shape.
func splicePayerSystemMessage(body []byte, payer string) ([]byte, bool) {
var doc map[string]json.RawMessage
if err := json.Unmarshal(body, &doc); err != nil {
return body, false
}
rawMsgs, ok := doc["messages"]
if !ok {
return body, false
}
var messages []json.RawMessage
if err := json.Unmarshal(rawMsgs, &messages); err != nil {
return body, false
}
note, err := json.Marshal(map[string]string{
"role": "system",
"content": "x402 payment context: this request was paid by wallet " + payer +
" (payer identity verified on-chain by the payment gateway; buyers cannot spoof it). " +
"When the buyer refers to their own wallet or address without spelling it out, use this address.",
})
if err != nil {
return body, false
}
merged, err := json.Marshal(append([]json.RawMessage{note}, messages...))
if err != nil {
return body, false
}
doc["messages"] = merged
newBody, err := json.Marshal(doc)
if err != nil {
return body, false
}
return newBody, true
}

// normalizeChatCompletionsPath forgives the common wrong-path shapes buyers
// send to chat-completions offers. External x402 clients (and the prompts on
// older 402 pages) frequently POST to the bare service base or to
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat: inject paying address into agent message body by OisinKyne · Pull Request #654 · ObolNetwork/obol-stack · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions internal/x402/payer_context_test.go
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
package x402

import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)

func TestSplicePayerSystemMessage(t *testing.T) {
payer := "0x2447b86f22245fa1271978bF37907D07EDE06261"

t.Run("prepends system message and preserves the rest", func(t *testing.T) {
body := []byte(`{"model":"openrouter/auto","stream":true,"messages":[{"role":"user","content":"claim my airdrop"}]}`)
out, ok := splicePayerSystemMessage(body, payer)
if !ok {
t.Fatalf("expected ok")
}
var doc struct {
Model string `json:"model"`
Stream bool `json:"stream"`
Messages []struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"messages"`
}
if err := json.Unmarshal(out, &doc); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if doc.Model != "openrouter/auto" || !doc.Stream {
t.Fatalf("sibling fields not preserved: %+v", doc)
}
if len(doc.Messages) != 2 {
t.Fatalf("want 2 messages, got %d", len(doc.Messages))
}
if doc.Messages[0].Role != "system" || !strings.Contains(doc.Messages[0].Content, payer) {
t.Fatalf("system payer message not first: %+v", doc.Messages[0])
}
if doc.Messages[1].Content != "claim my airdrop" {
t.Fatalf("user message mangled: %+v", doc.Messages[1])
}
})

t.Run("non-JSON body passes through", func(t *testing.T) {
body := []byte("not json")
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != "not json" {
t.Fatalf("expected byte-identical passthrough, got ok=%v out=%q", ok, out)
}
})

t.Run("JSON without messages passes through", func(t *testing.T) {
body := []byte(`{"model":"x"}`)
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != `{"model":"x"}` {
t.Fatalf("expected passthrough, got ok=%v out=%q", ok, out)
}
})
}

// proxyBodySeen runs a request through buildUpstreamProxy for the given rule
// and returns the body + headers the upstream received.
func proxyBodySeen(t *testing.T, rule *RouteRule, reqPath, body string, hdr map[string]string) (string, http.Header) {
t.Helper()
var gotBody string
var gotHeader http.Header
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
gotHeader = r.Header.Clone()
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
rule.UpstreamURL = upstream.URL

proxy, err := buildUpstreamProxy(rule)
if err != nil {
t.Fatalf("buildUpstreamProxy: %v", err)
}
req := httptest.NewRequest(http.MethodPost, reqPath, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
for k, v := range hdr {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
proxy.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("proxy status = %d", rec.Code)
}
return gotBody, gotHeader
}

func TestBuildUpstreamProxy_InjectsPayerContextForAgentOffers(t *testing.T) {
payer := "0xD0391EeDc3268F3deeF1F05fff5D7aEf82F64cCF"
chatBody := `{"model":"openrouter/auto","messages":[{"role":"user","content":"claim mine"}]}`

t.Run("agent offer with verified payer gets the system message", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) || !strings.Contains(body, "x402 payment context") {
t.Fatalf("payer context not injected; upstream saw: %s", body)
}
if !strings.Contains(body, "claim mine") {
t.Fatalf("original user message lost: %s", body)
}
})

t.Run("falls back to SIWX verified wallet", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderVerifiedWallet: payer})
if !strings.Contains(body, payer) {
t.Fatalf("verified-wallet fallback not injected; upstream saw: %s", body)
}
})

t.Run("no identity header means untouched body", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody, nil)
if body != chatBody {
t.Fatalf("body modified without identity header: %s", body)
}
})

t.Run("non-agent offers are untouched", func(t *testing.T) {
rule := &RouteRule{OfferType: "http", StripPrefix: "/services/api"}
body, _ := proxyBodySeen(t, rule, "/services/api/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if body != chatBody {
t.Fatalf("http offer body modified: %s", body)
}
})

t.Run("normalized bare path also gets injection", func(t *testing.T) {
// Buyers frequently POST to the service base; normalizeChatCompletionsPath
// rewrites it to /v1/chat/completions, and injection must follow.
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) {
t.Fatalf("payer context not injected on normalized path; upstream saw: %s", body)
}
})

t.Run("content-length is recomputed", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, hdr := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if cl := hdr.Get("Content-Length"); cl != "" {
n, err := strconv.Atoi(cl)
if err != nil || n != len(body) {
t.Fatalf("content-length %q != body length %d", cl, len(body))
}
}
})
}
100 changes: 100 additions & 0 deletions internal/x402/verifier.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,18 @@ package x402

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
Expand DownExpand Up@@ -824,6 +828,7 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
} else if rule.UpstreamAuth != "" {
pr.Out.Header.Set("Authorization", rule.UpstreamAuth)
}
injectAgentPayerContext(pr, rule)
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("x402-verifier: upstream proxy error for %s/%s: %v", rule.OfferNamespace, rule.OfferName, err)
Expand All@@ -837,6 +842,101 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
// agent upstreams (LiteLLM, Hermes).
const chatCompletionsPath = "/v1/chat/completions"

// payerContextBodyLimit caps how much of a chat-completions request body the
// verifier buffers to splice in the payer-context system message. Larger
// bodies pass through byte-identical.
const payerContextBodyLimit = 4 << 20

// injectAgentPayerContext rewrites a paid agent-offer chat request so the
// verified payer wallet rides IN-BAND as a leading system message. The
// X-Payment-Payer header alone doesn't reach the model — agent runtimes drop
// HTTP headers before the LLM sees the conversation — so without this a buyer
// must repeat their own address in the prompt. Identity headers are
// verifier-set only (client copies are stripped at HandleProxy entry), so the
// injected value is an authenticated fact.
//
// Injection is strictly best-effort: any shape we don't fully understand
// (non-JSON, no messages array, oversized or unreadable body, compressed
// content) leaves the request byte-identical rather than risking a paid
// request.
func injectAgentPayerContext(pr *httputil.ProxyRequest, rule *RouteRule) {
if rule.OfferType != "agent" || pr.Out.Method != http.MethodPost ||
pr.Out.URL.Path != chatCompletionsPath || pr.Out.Body == nil {
return
}
if ce := pr.In.Header.Get("Content-Encoding"); ce != "" && !strings.EqualFold(ce, "identity") {
return
}
if ct := pr.In.Header.Get("Content-Type"); ct != "" && !strings.Contains(strings.ToLower(ct), "json") {
return
}
payer := pr.In.Header.Get(HeaderPaymentPayer)
if payer == "" {
payer = pr.In.Header.Get(HeaderVerifiedWallet)
}
if payer == "" {
return
}

orig := pr.Out.Body
body, err := io.ReadAll(io.LimitReader(orig, payerContextBodyLimit+1))
if err != nil || len(body) > payerContextBodyLimit {
// Splice the consumed bytes back in front of the unread remainder so
// the upstream still receives the full original body.
pr.Out.Body = struct {
io.Reader
io.Closer
}{io.MultiReader(bytes.NewReader(body), orig), orig}
return
}
orig.Close()

newBody, ok := splicePayerSystemMessage(body, payer)
if !ok {
newBody = body
}
pr.Out.Body = io.NopCloser(bytes.NewReader(newBody))
pr.Out.ContentLength = int64(len(newBody))
pr.Out.Header.Set("Content-Length", strconv.Itoa(len(newBody)))
}

// splicePayerSystemMessage prepends a system message carrying the verified
// payer wallet to an OpenAI chat-completions JSON body. Returns the original
// bytes and false when the body isn't the expected shape.
func splicePayerSystemMessage(body []byte, payer string) ([]byte, bool) {
var doc map[string]json.RawMessage
if err := json.Unmarshal(body, &doc); err != nil {
return body, false
}
rawMsgs, ok := doc["messages"]
if !ok {
return body, false
}
var messages []json.RawMessage
if err := json.Unmarshal(rawMsgs, &messages); err != nil {
return body, false
}
note, err := json.Marshal(map[string]string{
"role": "system",
"content": "x402 payment context: this request was paid by wallet " + payer +
" (payer identity verified on-chain by the payment gateway; buyers cannot spoof it). " +
"When the buyer refers to their own wallet or address without spelling it out, use this address.",
})
if err != nil {
return body, false
}
merged, err := json.Marshal(append([]json.RawMessage{note}, messages...))
if err != nil {
return body, false
}
doc["messages"] = merged
newBody, err := json.Marshal(doc)
if err != nil {
return body, false
}
return newBody, true
}

// normalizeChatCompletionsPath forgives the common wrong-path shapes buyers
// send to chat-completions offers. External x402 clients (and the prompts on
// older 402 pages) frequently POST to the bare service base or to
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat: inject paying address into agent message body by OisinKyne · Pull Request #654 · ObolNetwork/obol-stack · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions internal/x402/payer_context_test.go
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
package x402

import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)

func TestSplicePayerSystemMessage(t *testing.T) {
payer := "0x2447b86f22245fa1271978bF37907D07EDE06261"

t.Run("prepends system message and preserves the rest", func(t *testing.T) {
body := []byte(`{"model":"openrouter/auto","stream":true,"messages":[{"role":"user","content":"claim my airdrop"}]}`)
out, ok := splicePayerSystemMessage(body, payer)
if !ok {
t.Fatalf("expected ok")
}
var doc struct {
Model string `json:"model"`
Stream bool `json:"stream"`
Messages []struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"messages"`
}
if err := json.Unmarshal(out, &doc); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if doc.Model != "openrouter/auto" || !doc.Stream {
t.Fatalf("sibling fields not preserved: %+v", doc)
}
if len(doc.Messages) != 2 {
t.Fatalf("want 2 messages, got %d", len(doc.Messages))
}
if doc.Messages[0].Role != "system" || !strings.Contains(doc.Messages[0].Content, payer) {
t.Fatalf("system payer message not first: %+v", doc.Messages[0])
}
if doc.Messages[1].Content != "claim my airdrop" {
t.Fatalf("user message mangled: %+v", doc.Messages[1])
}
})

t.Run("non-JSON body passes through", func(t *testing.T) {
body := []byte("not json")
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != "not json" {
t.Fatalf("expected byte-identical passthrough, got ok=%v out=%q", ok, out)
}
})

t.Run("JSON without messages passes through", func(t *testing.T) {
body := []byte(`{"model":"x"}`)
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != `{"model":"x"}` {
t.Fatalf("expected passthrough, got ok=%v out=%q", ok, out)
}
})
}

// proxyBodySeen runs a request through buildUpstreamProxy for the given rule
// and returns the body + headers the upstream received.
func proxyBodySeen(t *testing.T, rule *RouteRule, reqPath, body string, hdr map[string]string) (string, http.Header) {
t.Helper()
var gotBody string
var gotHeader http.Header
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
gotHeader = r.Header.Clone()
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
rule.UpstreamURL = upstream.URL

proxy, err := buildUpstreamProxy(rule)
if err != nil {
t.Fatalf("buildUpstreamProxy: %v", err)
}
req := httptest.NewRequest(http.MethodPost, reqPath, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
for k, v := range hdr {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
proxy.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("proxy status = %d", rec.Code)
}
return gotBody, gotHeader
}

func TestBuildUpstreamProxy_InjectsPayerContextForAgentOffers(t *testing.T) {
payer := "0xD0391EeDc3268F3deeF1F05fff5D7aEf82F64cCF"
chatBody := `{"model":"openrouter/auto","messages":[{"role":"user","content":"claim mine"}]}`

t.Run("agent offer with verified payer gets the system message", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) || !strings.Contains(body, "x402 payment context") {
t.Fatalf("payer context not injected; upstream saw: %s", body)
}
if !strings.Contains(body, "claim mine") {
t.Fatalf("original user message lost: %s", body)
}
})

t.Run("falls back to SIWX verified wallet", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderVerifiedWallet: payer})
if !strings.Contains(body, payer) {
t.Fatalf("verified-wallet fallback not injected; upstream saw: %s", body)
}
})

t.Run("no identity header means untouched body", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody, nil)
if body != chatBody {
t.Fatalf("body modified without identity header: %s", body)
}
})

t.Run("non-agent offers are untouched", func(t *testing.T) {
rule := &RouteRule{OfferType: "http", StripPrefix: "/services/api"}
body, _ := proxyBodySeen(t, rule, "/services/api/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if body != chatBody {
t.Fatalf("http offer body modified: %s", body)
}
})

t.Run("normalized bare path also gets injection", func(t *testing.T) {
// Buyers frequently POST to the service base; normalizeChatCompletionsPath
// rewrites it to /v1/chat/completions, and injection must follow.
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) {
t.Fatalf("payer context not injected on normalized path; upstream saw: %s", body)
}
})

t.Run("content-length is recomputed", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, hdr := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if cl := hdr.Get("Content-Length"); cl != "" {
n, err := strconv.Atoi(cl)
if err != nil || n != len(body) {
t.Fatalf("content-length %q != body length %d", cl, len(body))
}
}
})
}
100 changes: 100 additions & 0 deletions internal/x402/verifier.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,18 @@ package x402

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
Expand DownExpand Up@@ -824,6 +828,7 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
} else if rule.UpstreamAuth != "" {
pr.Out.Header.Set("Authorization", rule.UpstreamAuth)
}
injectAgentPayerContext(pr, rule)
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("x402-verifier: upstream proxy error for %s/%s: %v", rule.OfferNamespace, rule.OfferName, err)
Expand All@@ -837,6 +842,101 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
// agent upstreams (LiteLLM, Hermes).
const chatCompletionsPath = "/v1/chat/completions"

// payerContextBodyLimit caps how much of a chat-completions request body the
// verifier buffers to splice in the payer-context system message. Larger
// bodies pass through byte-identical.
const payerContextBodyLimit = 4 << 20

// injectAgentPayerContext rewrites a paid agent-offer chat request so the
// verified payer wallet rides IN-BAND as a leading system message. The
// X-Payment-Payer header alone doesn't reach the model — agent runtimes drop
// HTTP headers before the LLM sees the conversation — so without this a buyer
// must repeat their own address in the prompt. Identity headers are
// verifier-set only (client copies are stripped at HandleProxy entry), so the
// injected value is an authenticated fact.
//
// Injection is strictly best-effort: any shape we don't fully understand
// (non-JSON, no messages array, oversized or unreadable body, compressed
// content) leaves the request byte-identical rather than risking a paid
// request.
func injectAgentPayerContext(pr *httputil.ProxyRequest, rule *RouteRule) {
if rule.OfferType != "agent" || pr.Out.Method != http.MethodPost ||
pr.Out.URL.Path != chatCompletionsPath || pr.Out.Body == nil {
return
}
if ce := pr.In.Header.Get("Content-Encoding"); ce != "" && !strings.EqualFold(ce, "identity") {
return
}
if ct := pr.In.Header.Get("Content-Type"); ct != "" && !strings.Contains(strings.ToLower(ct), "json") {
return
}
payer := pr.In.Header.Get(HeaderPaymentPayer)
if payer == "" {
payer = pr.In.Header.Get(HeaderVerifiedWallet)
}
if payer == "" {
return
}

orig := pr.Out.Body
body, err := io.ReadAll(io.LimitReader(orig, payerContextBodyLimit+1))
if err != nil || len(body) > payerContextBodyLimit {
// Splice the consumed bytes back in front of the unread remainder so
// the upstream still receives the full original body.
pr.Out.Body = struct {
io.Reader
io.Closer
}{io.MultiReader(bytes.NewReader(body), orig), orig}
return
}
orig.Close()

newBody, ok := splicePayerSystemMessage(body, payer)
if !ok {
newBody = body
}
pr.Out.Body = io.NopCloser(bytes.NewReader(newBody))
pr.Out.ContentLength = int64(len(newBody))
pr.Out.Header.Set("Content-Length", strconv.Itoa(len(newBody)))
}

// splicePayerSystemMessage prepends a system message carrying the verified
// payer wallet to an OpenAI chat-completions JSON body. Returns the original
// bytes and false when the body isn't the expected shape.
func splicePayerSystemMessage(body []byte, payer string) ([]byte, bool) {
var doc map[string]json.RawMessage
if err := json.Unmarshal(body, &doc); err != nil {
return body, false
}
rawMsgs, ok := doc["messages"]
if !ok {
return body, false
}
var messages []json.RawMessage
if err := json.Unmarshal(rawMsgs, &messages); err != nil {
return body, false
}
note, err := json.Marshal(map[string]string{
"role": "system",
"content": "x402 payment context: this request was paid by wallet " + payer +
" (payer identity verified on-chain by the payment gateway; buyers cannot spoof it). " +
"When the buyer refers to their own wallet or address without spelling it out, use this address.",
})
if err != nil {
return body, false
}
merged, err := json.Marshal(append([]json.RawMessage{note}, messages...))
if err != nil {
return body, false
}
doc["messages"] = merged
newBody, err := json.Marshal(doc)
if err != nil {
return body, false
}
return newBody, true
}

// normalizeChatCompletionsPath forgives the common wrong-path shapes buyers
// send to chat-completions offers. External x402 clients (and the prompts on
// older 402 pages) frequently POST to the bare service base or to
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat: inject paying address into agent message body by OisinKyne · Pull Request #654 · ObolNetwork/obol-stack · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions internal/x402/payer_context_test.go
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
package x402

import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)

func TestSplicePayerSystemMessage(t *testing.T) {
payer := "0x2447b86f22245fa1271978bF37907D07EDE06261"

t.Run("prepends system message and preserves the rest", func(t *testing.T) {
body := []byte(`{"model":"openrouter/auto","stream":true,"messages":[{"role":"user","content":"claim my airdrop"}]}`)
out, ok := splicePayerSystemMessage(body, payer)
if !ok {
t.Fatalf("expected ok")
}
var doc struct {
Model string `json:"model"`
Stream bool `json:"stream"`
Messages []struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"messages"`
}
if err := json.Unmarshal(out, &doc); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if doc.Model != "openrouter/auto" || !doc.Stream {
t.Fatalf("sibling fields not preserved: %+v", doc)
}
if len(doc.Messages) != 2 {
t.Fatalf("want 2 messages, got %d", len(doc.Messages))
}
if doc.Messages[0].Role != "system" || !strings.Contains(doc.Messages[0].Content, payer) {
t.Fatalf("system payer message not first: %+v", doc.Messages[0])
}
if doc.Messages[1].Content != "claim my airdrop" {
t.Fatalf("user message mangled: %+v", doc.Messages[1])
}
})

t.Run("non-JSON body passes through", func(t *testing.T) {
body := []byte("not json")
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != "not json" {
t.Fatalf("expected byte-identical passthrough, got ok=%v out=%q", ok, out)
}
})

t.Run("JSON without messages passes through", func(t *testing.T) {
body := []byte(`{"model":"x"}`)
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != `{"model":"x"}` {
t.Fatalf("expected passthrough, got ok=%v out=%q", ok, out)
}
})
}

// proxyBodySeen runs a request through buildUpstreamProxy for the given rule
// and returns the body + headers the upstream received.
func proxyBodySeen(t *testing.T, rule *RouteRule, reqPath, body string, hdr map[string]string) (string, http.Header) {
t.Helper()
var gotBody string
var gotHeader http.Header
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
gotHeader = r.Header.Clone()
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
rule.UpstreamURL = upstream.URL

proxy, err := buildUpstreamProxy(rule)
if err != nil {
t.Fatalf("buildUpstreamProxy: %v", err)
}
req := httptest.NewRequest(http.MethodPost, reqPath, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
for k, v := range hdr {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
proxy.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("proxy status = %d", rec.Code)
}
return gotBody, gotHeader
}

func TestBuildUpstreamProxy_InjectsPayerContextForAgentOffers(t *testing.T) {
payer := "0xD0391EeDc3268F3deeF1F05fff5D7aEf82F64cCF"
chatBody := `{"model":"openrouter/auto","messages":[{"role":"user","content":"claim mine"}]}`

t.Run("agent offer with verified payer gets the system message", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) || !strings.Contains(body, "x402 payment context") {
t.Fatalf("payer context not injected; upstream saw: %s", body)
}
if !strings.Contains(body, "claim mine") {
t.Fatalf("original user message lost: %s", body)
}
})

t.Run("falls back to SIWX verified wallet", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderVerifiedWallet: payer})
if !strings.Contains(body, payer) {
t.Fatalf("verified-wallet fallback not injected; upstream saw: %s", body)
}
})

t.Run("no identity header means untouched body", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody, nil)
if body != chatBody {
t.Fatalf("body modified without identity header: %s", body)
}
})

t.Run("non-agent offers are untouched", func(t *testing.T) {
rule := &RouteRule{OfferType: "http", StripPrefix: "/services/api"}
body, _ := proxyBodySeen(t, rule, "/services/api/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if body != chatBody {
t.Fatalf("http offer body modified: %s", body)
}
})

t.Run("normalized bare path also gets injection", func(t *testing.T) {
// Buyers frequently POST to the service base; normalizeChatCompletionsPath
// rewrites it to /v1/chat/completions, and injection must follow.
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) {
t.Fatalf("payer context not injected on normalized path; upstream saw: %s", body)
}
})

t.Run("content-length is recomputed", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, hdr := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if cl := hdr.Get("Content-Length"); cl != "" {
n, err := strconv.Atoi(cl)
if err != nil || n != len(body) {
t.Fatalf("content-length %q != body length %d", cl, len(body))
}
}
})
}
100 changes: 100 additions & 0 deletions internal/x402/verifier.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,18 @@ package x402

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
Expand DownExpand Up@@ -824,6 +828,7 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
} else if rule.UpstreamAuth != "" {
pr.Out.Header.Set("Authorization", rule.UpstreamAuth)
}
injectAgentPayerContext(pr, rule)
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("x402-verifier: upstream proxy error for %s/%s: %v", rule.OfferNamespace, rule.OfferName, err)
Expand All@@ -837,6 +842,101 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
// agent upstreams (LiteLLM, Hermes).
const chatCompletionsPath = "/v1/chat/completions"

// payerContextBodyLimit caps how much of a chat-completions request body the
// verifier buffers to splice in the payer-context system message. Larger
// bodies pass through byte-identical.
const payerContextBodyLimit = 4 << 20

// injectAgentPayerContext rewrites a paid agent-offer chat request so the
// verified payer wallet rides IN-BAND as a leading system message. The
// X-Payment-Payer header alone doesn't reach the model — agent runtimes drop
// HTTP headers before the LLM sees the conversation — so without this a buyer
// must repeat their own address in the prompt. Identity headers are
// verifier-set only (client copies are stripped at HandleProxy entry), so the
// injected value is an authenticated fact.
//
// Injection is strictly best-effort: any shape we don't fully understand
// (non-JSON, no messages array, oversized or unreadable body, compressed
// content) leaves the request byte-identical rather than risking a paid
// request.
func injectAgentPayerContext(pr *httputil.ProxyRequest, rule *RouteRule) {
if rule.OfferType != "agent" || pr.Out.Method != http.MethodPost ||
pr.Out.URL.Path != chatCompletionsPath || pr.Out.Body == nil {
return
}
if ce := pr.In.Header.Get("Content-Encoding"); ce != "" && !strings.EqualFold(ce, "identity") {
return
}
if ct := pr.In.Header.Get("Content-Type"); ct != "" && !strings.Contains(strings.ToLower(ct), "json") {
return
}
payer := pr.In.Header.Get(HeaderPaymentPayer)
if payer == "" {
payer = pr.In.Header.Get(HeaderVerifiedWallet)
}
if payer == "" {
return
}

orig := pr.Out.Body
body, err := io.ReadAll(io.LimitReader(orig, payerContextBodyLimit+1))
if err != nil || len(body) > payerContextBodyLimit {
// Splice the consumed bytes back in front of the unread remainder so
// the upstream still receives the full original body.
pr.Out.Body = struct {
io.Reader
io.Closer
}{io.MultiReader(bytes.NewReader(body), orig), orig}
return
}
orig.Close()

newBody, ok := splicePayerSystemMessage(body, payer)
if !ok {
newBody = body
}
pr.Out.Body = io.NopCloser(bytes.NewReader(newBody))
pr.Out.ContentLength = int64(len(newBody))
pr.Out.Header.Set("Content-Length", strconv.Itoa(len(newBody)))
}

// splicePayerSystemMessage prepends a system message carrying the verified
// payer wallet to an OpenAI chat-completions JSON body. Returns the original
// bytes and false when the body isn't the expected shape.
func splicePayerSystemMessage(body []byte, payer string) ([]byte, bool) {
var doc map[string]json.RawMessage
if err := json.Unmarshal(body, &doc); err != nil {
return body, false
}
rawMsgs, ok := doc["messages"]
if !ok {
return body, false
}
var messages []json.RawMessage
if err := json.Unmarshal(rawMsgs, &messages); err != nil {
return body, false
}
note, err := json.Marshal(map[string]string{
"role": "system",
"content": "x402 payment context: this request was paid by wallet " + payer +
" (payer identity verified on-chain by the payment gateway; buyers cannot spoof it). " +
"When the buyer refers to their own wallet or address without spelling it out, use this address.",
})
if err != nil {
return body, false
}
merged, err := json.Marshal(append([]json.RawMessage{note}, messages...))
if err != nil {
return body, false
}
doc["messages"] = merged
newBody, err := json.Marshal(doc)
if err != nil {
return body, false
}
return newBody, true
}

// normalizeChatCompletionsPath forgives the common wrong-path shapes buyers
// send to chat-completions offers. External x402 clients (and the prompts on
// older 402 pages) frequently POST to the bare service base or to
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat: inject paying address into agent message body by OisinKyne · Pull Request #654 · ObolNetwork/obol-stack · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions internal/x402/payer_context_test.go
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
package x402

import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)

func TestSplicePayerSystemMessage(t *testing.T) {
payer := "0x2447b86f22245fa1271978bF37907D07EDE06261"

t.Run("prepends system message and preserves the rest", func(t *testing.T) {
body := []byte(`{"model":"openrouter/auto","stream":true,"messages":[{"role":"user","content":"claim my airdrop"}]}`)
out, ok := splicePayerSystemMessage(body, payer)
if !ok {
t.Fatalf("expected ok")
}
var doc struct {
Model string `json:"model"`
Stream bool `json:"stream"`
Messages []struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"messages"`
}
if err := json.Unmarshal(out, &doc); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if doc.Model != "openrouter/auto" || !doc.Stream {
t.Fatalf("sibling fields not preserved: %+v", doc)
}
if len(doc.Messages) != 2 {
t.Fatalf("want 2 messages, got %d", len(doc.Messages))
}
if doc.Messages[0].Role != "system" || !strings.Contains(doc.Messages[0].Content, payer) {
t.Fatalf("system payer message not first: %+v", doc.Messages[0])
}
if doc.Messages[1].Content != "claim my airdrop" {
t.Fatalf("user message mangled: %+v", doc.Messages[1])
}
})

t.Run("non-JSON body passes through", func(t *testing.T) {
body := []byte("not json")
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != "not json" {
t.Fatalf("expected byte-identical passthrough, got ok=%v out=%q", ok, out)
}
})

t.Run("JSON without messages passes through", func(t *testing.T) {
body := []byte(`{"model":"x"}`)
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != `{"model":"x"}` {
t.Fatalf("expected passthrough, got ok=%v out=%q", ok, out)
}
})
}

// proxyBodySeen runs a request through buildUpstreamProxy for the given rule
// and returns the body + headers the upstream received.
func proxyBodySeen(t *testing.T, rule *RouteRule, reqPath, body string, hdr map[string]string) (string, http.Header) {
t.Helper()
var gotBody string
var gotHeader http.Header
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
gotHeader = r.Header.Clone()
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
rule.UpstreamURL = upstream.URL

proxy, err := buildUpstreamProxy(rule)
if err != nil {
t.Fatalf("buildUpstreamProxy: %v", err)
}
req := httptest.NewRequest(http.MethodPost, reqPath, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
for k, v := range hdr {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
proxy.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("proxy status = %d", rec.Code)
}
return gotBody, gotHeader
}

func TestBuildUpstreamProxy_InjectsPayerContextForAgentOffers(t *testing.T) {
payer := "0xD0391EeDc3268F3deeF1F05fff5D7aEf82F64cCF"
chatBody := `{"model":"openrouter/auto","messages":[{"role":"user","content":"claim mine"}]}`

t.Run("agent offer with verified payer gets the system message", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) || !strings.Contains(body, "x402 payment context") {
t.Fatalf("payer context not injected; upstream saw: %s", body)
}
if !strings.Contains(body, "claim mine") {
t.Fatalf("original user message lost: %s", body)
}
})

t.Run("falls back to SIWX verified wallet", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderVerifiedWallet: payer})
if !strings.Contains(body, payer) {
t.Fatalf("verified-wallet fallback not injected; upstream saw: %s", body)
}
})

t.Run("no identity header means untouched body", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody, nil)
if body != chatBody {
t.Fatalf("body modified without identity header: %s", body)
}
})

t.Run("non-agent offers are untouched", func(t *testing.T) {
rule := &RouteRule{OfferType: "http", StripPrefix: "/services/api"}
body, _ := proxyBodySeen(t, rule, "/services/api/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if body != chatBody {
t.Fatalf("http offer body modified: %s", body)
}
})

t.Run("normalized bare path also gets injection", func(t *testing.T) {
// Buyers frequently POST to the service base; normalizeChatCompletionsPath
// rewrites it to /v1/chat/completions, and injection must follow.
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) {
t.Fatalf("payer context not injected on normalized path; upstream saw: %s", body)
}
})

t.Run("content-length is recomputed", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, hdr := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if cl := hdr.Get("Content-Length"); cl != "" {
n, err := strconv.Atoi(cl)
if err != nil || n != len(body) {
t.Fatalf("content-length %q != body length %d", cl, len(body))
}
}
})
}
100 changes: 100 additions & 0 deletions internal/x402/verifier.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,18 @@ package x402

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
Expand DownExpand Up@@ -824,6 +828,7 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
} else if rule.UpstreamAuth != "" {
pr.Out.Header.Set("Authorization", rule.UpstreamAuth)
}
injectAgentPayerContext(pr, rule)
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("x402-verifier: upstream proxy error for %s/%s: %v", rule.OfferNamespace, rule.OfferName, err)
Expand All@@ -837,6 +842,101 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
// agent upstreams (LiteLLM, Hermes).
const chatCompletionsPath = "/v1/chat/completions"

// payerContextBodyLimit caps how much of a chat-completions request body the
// verifier buffers to splice in the payer-context system message. Larger
// bodies pass through byte-identical.
const payerContextBodyLimit = 4 << 20

// injectAgentPayerContext rewrites a paid agent-offer chat request so the
// verified payer wallet rides IN-BAND as a leading system message. The
// X-Payment-Payer header alone doesn't reach the model — agent runtimes drop
// HTTP headers before the LLM sees the conversation — so without this a buyer
// must repeat their own address in the prompt. Identity headers are
// verifier-set only (client copies are stripped at HandleProxy entry), so the
// injected value is an authenticated fact.
//
// Injection is strictly best-effort: any shape we don't fully understand
// (non-JSON, no messages array, oversized or unreadable body, compressed
// content) leaves the request byte-identical rather than risking a paid
// request.
func injectAgentPayerContext(pr *httputil.ProxyRequest, rule *RouteRule) {
if rule.OfferType != "agent" || pr.Out.Method != http.MethodPost ||
pr.Out.URL.Path != chatCompletionsPath || pr.Out.Body == nil {
return
}
if ce := pr.In.Header.Get("Content-Encoding"); ce != "" && !strings.EqualFold(ce, "identity") {
return
}
if ct := pr.In.Header.Get("Content-Type"); ct != "" && !strings.Contains(strings.ToLower(ct), "json") {
return
}
payer := pr.In.Header.Get(HeaderPaymentPayer)
if payer == "" {
payer = pr.In.Header.Get(HeaderVerifiedWallet)
}
if payer == "" {
return
}

orig := pr.Out.Body
body, err := io.ReadAll(io.LimitReader(orig, payerContextBodyLimit+1))
if err != nil || len(body) > payerContextBodyLimit {
// Splice the consumed bytes back in front of the unread remainder so
// the upstream still receives the full original body.
pr.Out.Body = struct {
io.Reader
io.Closer
}{io.MultiReader(bytes.NewReader(body), orig), orig}
return
}
orig.Close()

newBody, ok := splicePayerSystemMessage(body, payer)
if !ok {
newBody = body
}
pr.Out.Body = io.NopCloser(bytes.NewReader(newBody))
pr.Out.ContentLength = int64(len(newBody))
pr.Out.Header.Set("Content-Length", strconv.Itoa(len(newBody)))
}

// splicePayerSystemMessage prepends a system message carrying the verified
// payer wallet to an OpenAI chat-completions JSON body. Returns the original
// bytes and false when the body isn't the expected shape.
func splicePayerSystemMessage(body []byte, payer string) ([]byte, bool) {
var doc map[string]json.RawMessage
if err := json.Unmarshal(body, &doc); err != nil {
return body, false
}
rawMsgs, ok := doc["messages"]
if !ok {
return body, false
}
var messages []json.RawMessage
if err := json.Unmarshal(rawMsgs, &messages); err != nil {
return body, false
}
note, err := json.Marshal(map[string]string{
"role": "system",
"content": "x402 payment context: this request was paid by wallet " + payer +
" (payer identity verified on-chain by the payment gateway; buyers cannot spoof it). " +
"When the buyer refers to their own wallet or address without spelling it out, use this address.",
})
if err != nil {
return body, false
}
merged, err := json.Marshal(append([]json.RawMessage{note}, messages...))
if err != nil {
return body, false
}
doc["messages"] = merged
newBody, err := json.Marshal(doc)
if err != nil {
return body, false
}
return newBody, true
}

// normalizeChatCompletionsPath forgives the common wrong-path shapes buyers
// send to chat-completions offers. External x402 clients (and the prompts on
// older 402 pages) frequently POST to the bare service base or to
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat: inject paying address into agent message body by OisinKyne · Pull Request #654 · ObolNetwork/obol-stack · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions internal/x402/payer_context_test.go
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
package x402

import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)

func TestSplicePayerSystemMessage(t *testing.T) {
payer := "0x2447b86f22245fa1271978bF37907D07EDE06261"

t.Run("prepends system message and preserves the rest", func(t *testing.T) {
body := []byte(`{"model":"openrouter/auto","stream":true,"messages":[{"role":"user","content":"claim my airdrop"}]}`)
out, ok := splicePayerSystemMessage(body, payer)
if !ok {
t.Fatalf("expected ok")
}
var doc struct {
Model string `json:"model"`
Stream bool `json:"stream"`
Messages []struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"messages"`
}
if err := json.Unmarshal(out, &doc); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if doc.Model != "openrouter/auto" || !doc.Stream {
t.Fatalf("sibling fields not preserved: %+v", doc)
}
if len(doc.Messages) != 2 {
t.Fatalf("want 2 messages, got %d", len(doc.Messages))
}
if doc.Messages[0].Role != "system" || !strings.Contains(doc.Messages[0].Content, payer) {
t.Fatalf("system payer message not first: %+v", doc.Messages[0])
}
if doc.Messages[1].Content != "claim my airdrop" {
t.Fatalf("user message mangled: %+v", doc.Messages[1])
}
})

t.Run("non-JSON body passes through", func(t *testing.T) {
body := []byte("not json")
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != "not json" {
t.Fatalf("expected byte-identical passthrough, got ok=%v out=%q", ok, out)
}
})

t.Run("JSON without messages passes through", func(t *testing.T) {
body := []byte(`{"model":"x"}`)
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != `{"model":"x"}` {
t.Fatalf("expected passthrough, got ok=%v out=%q", ok, out)
}
})
}

// proxyBodySeen runs a request through buildUpstreamProxy for the given rule
// and returns the body + headers the upstream received.
func proxyBodySeen(t *testing.T, rule *RouteRule, reqPath, body string, hdr map[string]string) (string, http.Header) {
t.Helper()
var gotBody string
var gotHeader http.Header
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
gotHeader = r.Header.Clone()
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
rule.UpstreamURL = upstream.URL

proxy, err := buildUpstreamProxy(rule)
if err != nil {
t.Fatalf("buildUpstreamProxy: %v", err)
}
req := httptest.NewRequest(http.MethodPost, reqPath, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
for k, v := range hdr {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
proxy.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("proxy status = %d", rec.Code)
}
return gotBody, gotHeader
}

func TestBuildUpstreamProxy_InjectsPayerContextForAgentOffers(t *testing.T) {
payer := "0xD0391EeDc3268F3deeF1F05fff5D7aEf82F64cCF"
chatBody := `{"model":"openrouter/auto","messages":[{"role":"user","content":"claim mine"}]}`

t.Run("agent offer with verified payer gets the system message", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) || !strings.Contains(body, "x402 payment context") {
t.Fatalf("payer context not injected; upstream saw: %s", body)
}
if !strings.Contains(body, "claim mine") {
t.Fatalf("original user message lost: %s", body)
}
})

t.Run("falls back to SIWX verified wallet", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderVerifiedWallet: payer})
if !strings.Contains(body, payer) {
t.Fatalf("verified-wallet fallback not injected; upstream saw: %s", body)
}
})

t.Run("no identity header means untouched body", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody, nil)
if body != chatBody {
t.Fatalf("body modified without identity header: %s", body)
}
})

t.Run("non-agent offers are untouched", func(t *testing.T) {
rule := &RouteRule{OfferType: "http", StripPrefix: "/services/api"}
body, _ := proxyBodySeen(t, rule, "/services/api/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if body != chatBody {
t.Fatalf("http offer body modified: %s", body)
}
})

t.Run("normalized bare path also gets injection", func(t *testing.T) {
// Buyers frequently POST to the service base; normalizeChatCompletionsPath
// rewrites it to /v1/chat/completions, and injection must follow.
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) {
t.Fatalf("payer context not injected on normalized path; upstream saw: %s", body)
}
})

t.Run("content-length is recomputed", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, hdr := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if cl := hdr.Get("Content-Length"); cl != "" {
n, err := strconv.Atoi(cl)
if err != nil || n != len(body) {
t.Fatalf("content-length %q != body length %d", cl, len(body))
}
}
})
}
100 changes: 100 additions & 0 deletions internal/x402/verifier.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,18 @@ package x402

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
Expand DownExpand Up@@ -824,6 +828,7 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
} else if rule.UpstreamAuth != "" {
pr.Out.Header.Set("Authorization", rule.UpstreamAuth)
}
injectAgentPayerContext(pr, rule)
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("x402-verifier: upstream proxy error for %s/%s: %v", rule.OfferNamespace, rule.OfferName, err)
Expand All@@ -837,6 +842,101 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
// agent upstreams (LiteLLM, Hermes).
const chatCompletionsPath = "/v1/chat/completions"

// payerContextBodyLimit caps how much of a chat-completions request body the
// verifier buffers to splice in the payer-context system message. Larger
// bodies pass through byte-identical.
const payerContextBodyLimit = 4 << 20

// injectAgentPayerContext rewrites a paid agent-offer chat request so the
// verified payer wallet rides IN-BAND as a leading system message. The
// X-Payment-Payer header alone doesn't reach the model — agent runtimes drop
// HTTP headers before the LLM sees the conversation — so without this a buyer
// must repeat their own address in the prompt. Identity headers are
// verifier-set only (client copies are stripped at HandleProxy entry), so the
// injected value is an authenticated fact.
//
// Injection is strictly best-effort: any shape we don't fully understand
// (non-JSON, no messages array, oversized or unreadable body, compressed
// content) leaves the request byte-identical rather than risking a paid
// request.
func injectAgentPayerContext(pr *httputil.ProxyRequest, rule *RouteRule) {
if rule.OfferType != "agent" || pr.Out.Method != http.MethodPost ||
pr.Out.URL.Path != chatCompletionsPath || pr.Out.Body == nil {
return
}
if ce := pr.In.Header.Get("Content-Encoding"); ce != "" && !strings.EqualFold(ce, "identity") {
return
}
if ct := pr.In.Header.Get("Content-Type"); ct != "" && !strings.Contains(strings.ToLower(ct), "json") {
return
}
payer := pr.In.Header.Get(HeaderPaymentPayer)
if payer == "" {
payer = pr.In.Header.Get(HeaderVerifiedWallet)
}
if payer == "" {
return
}

orig := pr.Out.Body
body, err := io.ReadAll(io.LimitReader(orig, payerContextBodyLimit+1))
if err != nil || len(body) > payerContextBodyLimit {
// Splice the consumed bytes back in front of the unread remainder so
// the upstream still receives the full original body.
pr.Out.Body = struct {
io.Reader
io.Closer
}{io.MultiReader(bytes.NewReader(body), orig), orig}
return
}
orig.Close()

newBody, ok := splicePayerSystemMessage(body, payer)
if !ok {
newBody = body
}
pr.Out.Body = io.NopCloser(bytes.NewReader(newBody))
pr.Out.ContentLength = int64(len(newBody))
pr.Out.Header.Set("Content-Length", strconv.Itoa(len(newBody)))
}

// splicePayerSystemMessage prepends a system message carrying the verified
// payer wallet to an OpenAI chat-completions JSON body. Returns the original
// bytes and false when the body isn't the expected shape.
func splicePayerSystemMessage(body []byte, payer string) ([]byte, bool) {
var doc map[string]json.RawMessage
if err := json.Unmarshal(body, &doc); err != nil {
return body, false
}
rawMsgs, ok := doc["messages"]
if !ok {
return body, false
}
var messages []json.RawMessage
if err := json.Unmarshal(rawMsgs, &messages); err != nil {
return body, false
}
note, err := json.Marshal(map[string]string{
"role": "system",
"content": "x402 payment context: this request was paid by wallet " + payer +
" (payer identity verified on-chain by the payment gateway; buyers cannot spoof it). " +
"When the buyer refers to their own wallet or address without spelling it out, use this address.",
})
if err != nil {
return body, false
}
merged, err := json.Marshal(append([]json.RawMessage{note}, messages...))
if err != nil {
return body, false
}
doc["messages"] = merged
newBody, err := json.Marshal(doc)
if err != nil {
return body, false
}
return newBody, true
}

// normalizeChatCompletionsPath forgives the common wrong-path shapes buyers
// send to chat-completions offers. External x402 clients (and the prompts on
// older 402 pages) frequently POST to the bare service base or to
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat: inject paying address into agent message body by OisinKyne · Pull Request #654 · ObolNetwork/obol-stack · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions internal/x402/payer_context_test.go
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
package x402

import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)

func TestSplicePayerSystemMessage(t *testing.T) {
payer := "0x2447b86f22245fa1271978bF37907D07EDE06261"

t.Run("prepends system message and preserves the rest", func(t *testing.T) {
body := []byte(`{"model":"openrouter/auto","stream":true,"messages":[{"role":"user","content":"claim my airdrop"}]}`)
out, ok := splicePayerSystemMessage(body, payer)
if !ok {
t.Fatalf("expected ok")
}
var doc struct {
Model string `json:"model"`
Stream bool `json:"stream"`
Messages []struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"messages"`
}
if err := json.Unmarshal(out, &doc); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if doc.Model != "openrouter/auto" || !doc.Stream {
t.Fatalf("sibling fields not preserved: %+v", doc)
}
if len(doc.Messages) != 2 {
t.Fatalf("want 2 messages, got %d", len(doc.Messages))
}
if doc.Messages[0].Role != "system" || !strings.Contains(doc.Messages[0].Content, payer) {
t.Fatalf("system payer message not first: %+v", doc.Messages[0])
}
if doc.Messages[1].Content != "claim my airdrop" {
t.Fatalf("user message mangled: %+v", doc.Messages[1])
}
})

t.Run("non-JSON body passes through", func(t *testing.T) {
body := []byte("not json")
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != "not json" {
t.Fatalf("expected byte-identical passthrough, got ok=%v out=%q", ok, out)
}
})

t.Run("JSON without messages passes through", func(t *testing.T) {
body := []byte(`{"model":"x"}`)
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != `{"model":"x"}` {
t.Fatalf("expected passthrough, got ok=%v out=%q", ok, out)
}
})
}

// proxyBodySeen runs a request through buildUpstreamProxy for the given rule
// and returns the body + headers the upstream received.
func proxyBodySeen(t *testing.T, rule *RouteRule, reqPath, body string, hdr map[string]string) (string, http.Header) {
t.Helper()
var gotBody string
var gotHeader http.Header
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
gotHeader = r.Header.Clone()
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
rule.UpstreamURL = upstream.URL

proxy, err := buildUpstreamProxy(rule)
if err != nil {
t.Fatalf("buildUpstreamProxy: %v", err)
}
req := httptest.NewRequest(http.MethodPost, reqPath, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
for k, v := range hdr {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
proxy.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("proxy status = %d", rec.Code)
}
return gotBody, gotHeader
}

func TestBuildUpstreamProxy_InjectsPayerContextForAgentOffers(t *testing.T) {
payer := "0xD0391EeDc3268F3deeF1F05fff5D7aEf82F64cCF"
chatBody := `{"model":"openrouter/auto","messages":[{"role":"user","content":"claim mine"}]}`

t.Run("agent offer with verified payer gets the system message", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) || !strings.Contains(body, "x402 payment context") {
t.Fatalf("payer context not injected; upstream saw: %s", body)
}
if !strings.Contains(body, "claim mine") {
t.Fatalf("original user message lost: %s", body)
}
})

t.Run("falls back to SIWX verified wallet", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderVerifiedWallet: payer})
if !strings.Contains(body, payer) {
t.Fatalf("verified-wallet fallback not injected; upstream saw: %s", body)
}
})

t.Run("no identity header means untouched body", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody, nil)
if body != chatBody {
t.Fatalf("body modified without identity header: %s", body)
}
})

t.Run("non-agent offers are untouched", func(t *testing.T) {
rule := &RouteRule{OfferType: "http", StripPrefix: "/services/api"}
body, _ := proxyBodySeen(t, rule, "/services/api/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if body != chatBody {
t.Fatalf("http offer body modified: %s", body)
}
})

t.Run("normalized bare path also gets injection", func(t *testing.T) {
// Buyers frequently POST to the service base; normalizeChatCompletionsPath
// rewrites it to /v1/chat/completions, and injection must follow.
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) {
t.Fatalf("payer context not injected on normalized path; upstream saw: %s", body)
}
})

t.Run("content-length is recomputed", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, hdr := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if cl := hdr.Get("Content-Length"); cl != "" {
n, err := strconv.Atoi(cl)
if err != nil || n != len(body) {
t.Fatalf("content-length %q != body length %d", cl, len(body))
}
}
})
}
100 changes: 100 additions & 0 deletions internal/x402/verifier.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,18 @@ package x402

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
Expand DownExpand Up@@ -824,6 +828,7 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
} else if rule.UpstreamAuth != "" {
pr.Out.Header.Set("Authorization", rule.UpstreamAuth)
}
injectAgentPayerContext(pr, rule)
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("x402-verifier: upstream proxy error for %s/%s: %v", rule.OfferNamespace, rule.OfferName, err)
Expand All@@ -837,6 +842,101 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
// agent upstreams (LiteLLM, Hermes).
const chatCompletionsPath = "/v1/chat/completions"

// payerContextBodyLimit caps how much of a chat-completions request body the
// verifier buffers to splice in the payer-context system message. Larger
// bodies pass through byte-identical.
const payerContextBodyLimit = 4 << 20

// injectAgentPayerContext rewrites a paid agent-offer chat request so the
// verified payer wallet rides IN-BAND as a leading system message. The
// X-Payment-Payer header alone doesn't reach the model — agent runtimes drop
// HTTP headers before the LLM sees the conversation — so without this a buyer
// must repeat their own address in the prompt. Identity headers are
// verifier-set only (client copies are stripped at HandleProxy entry), so the
// injected value is an authenticated fact.
//
// Injection is strictly best-effort: any shape we don't fully understand
// (non-JSON, no messages array, oversized or unreadable body, compressed
// content) leaves the request byte-identical rather than risking a paid
// request.
func injectAgentPayerContext(pr *httputil.ProxyRequest, rule *RouteRule) {
if rule.OfferType != "agent" || pr.Out.Method != http.MethodPost ||
pr.Out.URL.Path != chatCompletionsPath || pr.Out.Body == nil {
return
}
if ce := pr.In.Header.Get("Content-Encoding"); ce != "" && !strings.EqualFold(ce, "identity") {
return
}
if ct := pr.In.Header.Get("Content-Type"); ct != "" && !strings.Contains(strings.ToLower(ct), "json") {
return
}
payer := pr.In.Header.Get(HeaderPaymentPayer)
if payer == "" {
payer = pr.In.Header.Get(HeaderVerifiedWallet)
}
if payer == "" {
return
}

orig := pr.Out.Body
body, err := io.ReadAll(io.LimitReader(orig, payerContextBodyLimit+1))
if err != nil || len(body) > payerContextBodyLimit {
// Splice the consumed bytes back in front of the unread remainder so
// the upstream still receives the full original body.
pr.Out.Body = struct {
io.Reader
io.Closer
}{io.MultiReader(bytes.NewReader(body), orig), orig}
return
}
orig.Close()

newBody, ok := splicePayerSystemMessage(body, payer)
if !ok {
newBody = body
}
pr.Out.Body = io.NopCloser(bytes.NewReader(newBody))
pr.Out.ContentLength = int64(len(newBody))
pr.Out.Header.Set("Content-Length", strconv.Itoa(len(newBody)))
}

// splicePayerSystemMessage prepends a system message carrying the verified
// payer wallet to an OpenAI chat-completions JSON body. Returns the original
// bytes and false when the body isn't the expected shape.
func splicePayerSystemMessage(body []byte, payer string) ([]byte, bool) {
var doc map[string]json.RawMessage
if err := json.Unmarshal(body, &doc); err != nil {
return body, false
}
rawMsgs, ok := doc["messages"]
if !ok {
return body, false
}
var messages []json.RawMessage
if err := json.Unmarshal(rawMsgs, &messages); err != nil {
return body, false
}
note, err := json.Marshal(map[string]string{
"role": "system",
"content": "x402 payment context: this request was paid by wallet " + payer +
" (payer identity verified on-chain by the payment gateway; buyers cannot spoof it). " +
"When the buyer refers to their own wallet or address without spelling it out, use this address.",
})
if err != nil {
return body, false
}
merged, err := json.Marshal(append([]json.RawMessage{note}, messages...))
if err != nil {
return body, false
}
doc["messages"] = merged
newBody, err := json.Marshal(doc)
if err != nil {
return body, false
}
return newBody, true
}

// normalizeChatCompletionsPath forgives the common wrong-path shapes buyers
// send to chat-completions offers. External x402 clients (and the prompts on
// older 402 pages) frequently POST to the bare service base or to
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); feat: inject paying address into agent message body by OisinKyne · Pull Request #654 · ObolNetwork/obol-stack · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions internal/x402/payer_context_test.go
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
package x402

import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)

func TestSplicePayerSystemMessage(t *testing.T) {
payer := "0x2447b86f22245fa1271978bF37907D07EDE06261"

t.Run("prepends system message and preserves the rest", func(t *testing.T) {
body := []byte(`{"model":"openrouter/auto","stream":true,"messages":[{"role":"user","content":"claim my airdrop"}]}`)
out, ok := splicePayerSystemMessage(body, payer)
if !ok {
t.Fatalf("expected ok")
}
var doc struct {
Model string `json:"model"`
Stream bool `json:"stream"`
Messages []struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"messages"`
}
if err := json.Unmarshal(out, &doc); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if doc.Model != "openrouter/auto" || !doc.Stream {
t.Fatalf("sibling fields not preserved: %+v", doc)
}
if len(doc.Messages) != 2 {
t.Fatalf("want 2 messages, got %d", len(doc.Messages))
}
if doc.Messages[0].Role != "system" || !strings.Contains(doc.Messages[0].Content, payer) {
t.Fatalf("system payer message not first: %+v", doc.Messages[0])
}
if doc.Messages[1].Content != "claim my airdrop" {
t.Fatalf("user message mangled: %+v", doc.Messages[1])
}
})

t.Run("non-JSON body passes through", func(t *testing.T) {
body := []byte("not json")
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != "not json" {
t.Fatalf("expected byte-identical passthrough, got ok=%v out=%q", ok, out)
}
})

t.Run("JSON without messages passes through", func(t *testing.T) {
body := []byte(`{"model":"x"}`)
out, ok := splicePayerSystemMessage(body, payer)
if ok || string(out) != `{"model":"x"}` {
t.Fatalf("expected passthrough, got ok=%v out=%q", ok, out)
}
})
}

// proxyBodySeen runs a request through buildUpstreamProxy for the given rule
// and returns the body + headers the upstream received.
func proxyBodySeen(t *testing.T, rule *RouteRule, reqPath, body string, hdr map[string]string) (string, http.Header) {
t.Helper()
var gotBody string
var gotHeader http.Header
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
gotHeader = r.Header.Clone()
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
rule.UpstreamURL = upstream.URL

proxy, err := buildUpstreamProxy(rule)
if err != nil {
t.Fatalf("buildUpstreamProxy: %v", err)
}
req := httptest.NewRequest(http.MethodPost, reqPath, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
for k, v := range hdr {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
proxy.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("proxy status = %d", rec.Code)
}
return gotBody, gotHeader
}

func TestBuildUpstreamProxy_InjectsPayerContextForAgentOffers(t *testing.T) {
payer := "0xD0391EeDc3268F3deeF1F05fff5D7aEf82F64cCF"
chatBody := `{"model":"openrouter/auto","messages":[{"role":"user","content":"claim mine"}]}`

t.Run("agent offer with verified payer gets the system message", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) || !strings.Contains(body, "x402 payment context") {
t.Fatalf("payer context not injected; upstream saw: %s", body)
}
if !strings.Contains(body, "claim mine") {
t.Fatalf("original user message lost: %s", body)
}
})

t.Run("falls back to SIWX verified wallet", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderVerifiedWallet: payer})
if !strings.Contains(body, payer) {
t.Fatalf("verified-wallet fallback not injected; upstream saw: %s", body)
}
})

t.Run("no identity header means untouched body", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody, nil)
if body != chatBody {
t.Fatalf("body modified without identity header: %s", body)
}
})

t.Run("non-agent offers are untouched", func(t *testing.T) {
rule := &RouteRule{OfferType: "http", StripPrefix: "/services/api"}
body, _ := proxyBodySeen(t, rule, "/services/api/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if body != chatBody {
t.Fatalf("http offer body modified: %s", body)
}
})

t.Run("normalized bare path also gets injection", func(t *testing.T) {
// Buyers frequently POST to the service base; normalizeChatCompletionsPath
// rewrites it to /v1/chat/completions, and injection must follow.
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, _ := proxyBodySeen(t, rule, "/services/claim-bot", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if !strings.Contains(body, payer) {
t.Fatalf("payer context not injected on normalized path; upstream saw: %s", body)
}
})

t.Run("content-length is recomputed", func(t *testing.T) {
rule := &RouteRule{OfferType: "agent", StripPrefix: "/services/claim-bot"}
body, hdr := proxyBodySeen(t, rule, "/services/claim-bot/v1/chat/completions", chatBody,
map[string]string{HeaderPaymentPayer: payer})
if cl := hdr.Get("Content-Length"); cl != "" {
n, err := strconv.Atoi(cl)
if err != nil || n != len(body) {
t.Fatalf("content-length %q != body length %d", cl, len(body))
}
}
})
}
100 changes: 100 additions & 0 deletions internal/x402/verifier.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,18 @@ package x402

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
Expand DownExpand Up@@ -824,6 +828,7 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
} else if rule.UpstreamAuth != "" {
pr.Out.Header.Set("Authorization", rule.UpstreamAuth)
}
injectAgentPayerContext(pr, rule)
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("x402-verifier: upstream proxy error for %s/%s: %v", rule.OfferNamespace, rule.OfferName, err)
Expand All@@ -837,6 +842,101 @@ func buildUpstreamProxy(rule *RouteRule) (http.Handler, error) {
// agent upstreams (LiteLLM, Hermes).
const chatCompletionsPath = "/v1/chat/completions"

// payerContextBodyLimit caps how much of a chat-completions request body the
// verifier buffers to splice in the payer-context system message. Larger
// bodies pass through byte-identical.
const payerContextBodyLimit = 4 << 20

// injectAgentPayerContext rewrites a paid agent-offer chat request so the
// verified payer wallet rides IN-BAND as a leading system message. The
// X-Payment-Payer header alone doesn't reach the model — agent runtimes drop
// HTTP headers before the LLM sees the conversation — so without this a buyer
// must repeat their own address in the prompt. Identity headers are
// verifier-set only (client copies are stripped at HandleProxy entry), so the
// injected value is an authenticated fact.
//
// Injection is strictly best-effort: any shape we don't fully understand
// (non-JSON, no messages array, oversized or unreadable body, compressed
// content) leaves the request byte-identical rather than risking a paid
// request.
func injectAgentPayerContext(pr *httputil.ProxyRequest, rule *RouteRule) {
if rule.OfferType != "agent" || pr.Out.Method != http.MethodPost ||
pr.Out.URL.Path != chatCompletionsPath || pr.Out.Body == nil {
return
}
if ce := pr.In.Header.Get("Content-Encoding"); ce != "" && !strings.EqualFold(ce, "identity") {
return
}
if ct := pr.In.Header.Get("Content-Type"); ct != "" && !strings.Contains(strings.ToLower(ct), "json") {
return
}
payer := pr.In.Header.Get(HeaderPaymentPayer)
if payer == "" {
payer = pr.In.Header.Get(HeaderVerifiedWallet)
}
if payer == "" {
return
}

orig := pr.Out.Body
body, err := io.ReadAll(io.LimitReader(orig, payerContextBodyLimit+1))
if err != nil || len(body) > payerContextBodyLimit {
// Splice the consumed bytes back in front of the unread remainder so
// the upstream still receives the full original body.
pr.Out.Body = struct {
io.Reader
io.Closer
}{io.MultiReader(bytes.NewReader(body), orig), orig}
return
}
orig.Close()

newBody, ok := splicePayerSystemMessage(body, payer)
if !ok {
newBody = body
}
pr.Out.Body = io.NopCloser(bytes.NewReader(newBody))
pr.Out.ContentLength = int64(len(newBody))
pr.Out.Header.Set("Content-Length", strconv.Itoa(len(newBody)))
}

// splicePayerSystemMessage prepends a system message carrying the verified
// payer wallet to an OpenAI chat-completions JSON body. Returns the original
// bytes and false when the body isn't the expected shape.
func splicePayerSystemMessage(body []byte, payer string) ([]byte, bool) {
var doc map[string]json.RawMessage
if err := json.Unmarshal(body, &doc); err != nil {
return body, false
}
rawMsgs, ok := doc["messages"]
if !ok {
return body, false
}
var messages []json.RawMessage
if err := json.Unmarshal(rawMsgs, &messages); err != nil {
return body, false
}
note, err := json.Marshal(map[string]string{
"role": "system",
"content": "x402 payment context: this request was paid by wallet " + payer +
" (payer identity verified on-chain by the payment gateway; buyers cannot spoof it). " +
"When the buyer refers to their own wallet or address without spelling it out, use this address.",
})
if err != nil {
return body, false
}
merged, err := json.Marshal(append([]json.RawMessage{note}, messages...))
if err != nil {
return body, false
}
doc["messages"] = merged
newBody, err := json.Marshal(doc)
if err != nil {
return body, false
}
return newBody, true
}

// normalizeChatCompletionsPath forgives the common wrong-path shapes buyers
// send to chat-completions offers. External x402 clients (and the prompts on
// older 402 pages) frequently POST to the bare service base or to
Expand Down
Loading