|
| 1 | +package client |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/base64" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "net/http" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +// Payer handles invoice payment for L402 flows. |
| 14 | +type Payer interface { |
| 15 | + PayInvoice(ctx context.Context, bolt11 string) (preimageHex string, err error) |
| 16 | +} |
| 17 | + |
| 18 | +// L402RoundTripper is an http.RoundTripper that handles L402 payment flows. |
| 19 | +// It transparently pays invoices, caches tokens, and adds Authorization headers. |
| 20 | +type L402RoundTripper struct { |
| 21 | + inner http.RoundTripper |
| 22 | + payer Payer |
| 23 | + store TokenStore |
| 24 | + ignoreExistingAuth bool |
| 25 | +} |
| 26 | + |
| 27 | +// Option is a functional option for configuring L402RoundTripper. |
| 28 | +type Option func(*L402RoundTripper) |
| 29 | + |
| 30 | +// WithTransport sets a custom inner http.RoundTripper (defaults to http.DefaultTransport). |
| 31 | +func WithTransport(t http.RoundTripper) Option { |
| 32 | + return func(r *L402RoundTripper) { |
| 33 | + r.inner = t |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +// WithStore sets a custom TokenStore for caching tokens. |
| 38 | +// If not provided, tokens are not cached (default behavior). |
| 39 | +// Cache keys are derived from the request's host and path (query params are ignored). |
| 40 | +// Tokens are evicted from the cache when they expire or rejected by the server. |
| 41 | +// Pass NewMemoryTokenStore() for in-memory caching, or implement TokenStore for custom backends. |
| 42 | +// Passing nil will disable caching. |
| 43 | +func WithStore(s TokenStore) Option { |
| 44 | + return func(r *L402RoundTripper) { |
| 45 | + r.store = s |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +// IgnoreExistingAuth causes L402RoundTripper to ignore any existing Authorization header |
| 50 | +// on the request and proceed with the L402 payment flow. Useful when you want to force |
| 51 | +// L402 authentication even if the request already carries other credentials. |
| 52 | +func IgnoreExistingAuth() Option { |
| 53 | + return func(r *L402RoundTripper) { |
| 54 | + r.ignoreExistingAuth = true |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// New creates an L402RoundTripper. |
| 59 | +// By default, tokens are not cached (uses internal no-op store). |
| 60 | +// Pass WithStore(NewMemoryTokenStore()) to enable caching. |
| 61 | +func New(payer Payer, opts ...Option) *L402RoundTripper { |
| 62 | + rt := &L402RoundTripper{ |
| 63 | + inner: http.DefaultTransport, |
| 64 | + payer: payer, |
| 65 | + ignoreExistingAuth: false, |
| 66 | + } |
| 67 | + for _, opt := range opts { |
| 68 | + opt(rt) |
| 69 | + } |
| 70 | + |
| 71 | + // This allow passing a WithStore(nil) for better ergonomics. |
| 72 | + if rt.store == nil { |
| 73 | + rt.store = &noopTokenStore{} |
| 74 | + } |
| 75 | + |
| 76 | + return rt |
| 77 | +} |
| 78 | + |
| 79 | +// RoundTrip implements http.RoundTripper, handling L402 flows transparently. |
| 80 | +func (r *L402RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { |
| 81 | + // Step 0: If the original request already has an Authorization header and we're not |
| 82 | + // ignoring it, bypass the L402 payment flow and forward the request as-is. |
| 83 | + // The server will validate whatever credentials are already present. |
| 84 | + // This allows reusing existing auth (e.g., from a previous L402 exchange or other scheme). |
| 85 | + if req.Header.Get("Authorization") != "" && !r.ignoreExistingAuth { |
| 86 | + return r.inner.RoundTrip(req) |
| 87 | + } |
| 88 | + |
| 89 | + cacheKey := r.cacheKey(req) |
| 90 | + cloned := req.Clone(req.Context()) |
| 91 | + |
| 92 | + // Step 1: Check if we have a cached token and set it as an Auth header. |
| 93 | + if token, preimage, ok := r.store.Get(cacheKey); ok { |
| 94 | + cloned.Header.Set("Authorization", fmt.Sprintf("L402 %s:%s", token, preimage)) |
| 95 | + } |
| 96 | + |
| 97 | + resp, err := r.inner.RoundTrip(cloned) |
| 98 | + if err != nil { |
| 99 | + return nil, err |
| 100 | + } |
| 101 | + |
| 102 | + if resp.StatusCode != http.StatusPaymentRequired { |
| 103 | + return resp, nil |
| 104 | + } |
| 105 | + |
| 106 | + // At this stage we've got a 402. We close the body as we are returning a new response. Also the |
| 107 | + // cache key is evicted. |
| 108 | + _ = resp.Body.Close() |
| 109 | + r.store.Delete(cacheKey) |
| 110 | + |
| 111 | + // Step 4: Parse WWW-Authenticate header |
| 112 | + wwwAuth := resp.Header.Get("WWW-Authenticate") |
| 113 | + token, invoice, err := parseChallenge(wwwAuth) |
| 114 | + if err != nil { |
| 115 | + return nil, fmt.Errorf("parsing L402 challenge: %w", err) |
| 116 | + } |
| 117 | + |
| 118 | + // Step 5: Call payer to pay the invoice |
| 119 | + preimage, err := r.payer.PayInvoice(req.Context(), invoice) |
| 120 | + if err != nil { |
| 121 | + return nil, fmt.Errorf("paying invoice: %w", err) |
| 122 | + } |
| 123 | + |
| 124 | + // Step 6: Decode token expiry and determine TTL |
| 125 | + expiresAt, err := decodeExpiry(token) |
| 126 | + if err != nil { |
| 127 | + // On decode error, use a default 24h TTL |
| 128 | + expiresAt = time.Now().Add(24 * time.Hour) |
| 129 | + } |
| 130 | + |
| 131 | + // Step 7: Cache the token (or no-op if using default store) |
| 132 | + r.store.Set(cacheKey, token, preimage, expiresAt) |
| 133 | + |
| 134 | + // Step 8: Clone original request and add Authorization header |
| 135 | + cloned.Header.Set("Authorization", fmt.Sprintf("L402 %s:%s", token, preimage)) |
| 136 | + |
| 137 | + // Step 9: Forward with payment credentials and return final response |
| 138 | + return r.inner.RoundTrip(cloned) |
| 139 | +} |
| 140 | + |
| 141 | +// cacheKey derives a cache key from the request (host + path, ignoring query params). |
| 142 | +func (r *L402RoundTripper) cacheKey(req *http.Request) string { |
| 143 | + return req.URL.Host + req.URL.Path |
| 144 | +} |
| 145 | + |
| 146 | +// tokenPayload represents the JSON payload embedded in an L402 token. |
| 147 | +type tokenPayload struct { |
| 148 | + ExpiresAt int64 `json:"expires_at"` |
| 149 | +} |
| 150 | + |
| 151 | +// decodeExpiry extracts the expires_at field from a token. |
| 152 | +// Token format: base64url(json_payload).hex(hmac_sha256) |
| 153 | +// On error, returns time.Now().Add(24h) as a fallback. |
| 154 | +func decodeExpiry(rawToken string) (time.Time, error) { |
| 155 | + // Split on the first dot |
| 156 | + parts := strings.SplitN(rawToken, ".", 2) |
| 157 | + if len(parts) != 2 { |
| 158 | + return time.Time{}, fmt.Errorf("invalid token format") |
| 159 | + } |
| 160 | + |
| 161 | + encoded := parts[0] |
| 162 | + |
| 163 | + // Base64url decode |
| 164 | + payload, err := base64.URLEncoding.DecodeString(encoded) |
| 165 | + if err != nil { |
| 166 | + return time.Time{}, fmt.Errorf("decoding token: %w", err) |
| 167 | + } |
| 168 | + |
| 169 | + // JSON unmarshal |
| 170 | + var tp tokenPayload |
| 171 | + if err := json.Unmarshal(payload, &tp); err != nil { |
| 172 | + return time.Time{}, fmt.Errorf("unmarshaling token payload: %w", err) |
| 173 | + } |
| 174 | + |
| 175 | + return time.Unix(tp.ExpiresAt, 0), nil |
| 176 | +} |
0 commit comments