Class: X402::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/x402/middleware.rb

Overview

Pure Rack dispatcher for payment-gated HTTP.

The middleware has no blockchain knowledge — it matches routes, issues payment challenges by polling configured gateways, and dispatches proofs to the matching gateway for settlement.

Examples:

config.ru

X402.configure { |c| c.operator_wallet_url = "https://..." }
use X402::Middleware

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.

Parameters:

  • app (#call)

    next Rack app in the middleware stack



21
22
23
# File 'lib/x402/middleware.rb', line 21

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Array(Integer, Hash, Array)

Returns Rack response triple.

Parameters:

  • env (Hash)

    Rack environment

Returns:

  • (Array(Integer, Hash, Array))

    Rack response triple



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/x402/middleware.rb', line 27

def call(env)
  request = Rack::Request.new(env)
  config = X402.configuration

  if config.status_endpoint_enabled? && request.path_info == config.status_endpoint_path
    return X402::StatusEndpoint.new(config).call(env)
  end

  route = config.find_route(request.request_method, request.path_info)

  # Unprotected route — pass through
  return @app.call(env) unless route

  log = config.logger
  log.info "[x402] #{request.request_method} #{request.path_info} " \
           "— protected route, #{route.resolve_amount_sats} sats"

  # BRC-104 §6.2: extract client identity key from x-bsv-auth-identity-key
  extract_brc103_identity_key!(env, log)

  # Check for a proof/payment header from any gateway
  gateway, header_name, proof_payload = detect_proof(env, config)

  if gateway
    log.info "[x402] Proof header #{header_name} detected — dispatching to #{gateway.class.name}"
    settle_and_forward(env, gateway, header_name, proof_payload, request, route, log)
  else
    log.info "[x402] No proof header — issuing 402 challenge"
    issue_challenge(request, route, config)
  end
end