# Recipe: custom domains in a Ruby on Rails app

Let the users of a Rails app connect their own domain with Cnamio: a session endpoint, the connect window in a view, and a webhook endpoint. There is no Ruby SDK: this recipe calls the REST API with the standard library (`net/http`, `openssl`), exactly what the Node.js and Python SDKs do. The full guide is https://cnamio.com/agent-onboarding/SKILL.md; every route is in https://cnamio.com/openapi.json.

## 1. Configure

```bash
CNAMIO_APPLICATION_ID=app_…
CNAMIO_SECRET=cnm_sk_…        # server only, never committed
CNAMIO_OWNERSHIP_KEY=…        # any long random secret of yours
CNAMIO_WEBHOOK_SECRET=…
```

No account yet? A coding agent can call the MCP tool `start_signup` (or `POST https://api.cnamio.com/v1/agent/signup`) with your email, and work in the sandbox until you open the verification link.

## 2. A small client: `app/services/cnamio.rb`

```ruby
require "json"
require "net/http"
require "openssl"

module Cnamio
  API = URI("https://api.cnamio.com")

  # A CNAME to your hosting plus a TXT only this user can satisfy (same values as recordsForUser in the SDKs).
  def self.records_for(user_id, target: "customers.yourapp.com", prefix: "cnamio-verify")
    value = OpenSSL::HMAC.hexdigest("SHA256", ENV.fetch("CNAMIO_OWNERSHIP_KEY"), user_id.to_s)[0, 32]
    [
      { type: "CNAME", host: "{SUBDOMAIN}", value: target, ttl: 300 },
      { type: "TXT", host: "_#{prefix}.{SUBDOMAIN}", value: "#{prefix}=#{value}", ttl: 300 },
    ]
  end

  # POST /token: a 60-minute session bound to this user's records. Returns what the connect window needs.
  def self.create_session(user_id:, dns_records:)
    body = { applicationId: ENV.fetch("CNAMIO_APPLICATION_ID"), secret: ENV.fetch("CNAMIO_SECRET"), userId: user_id.to_s, dnsRecords: dns_records }
    response = Net::HTTP.post(URI.join(API, "/token"), body.to_json, "Content-Type" => "application/json")
    raise "cnamio #{response.code}" unless response.is_a?(Net::HTTPSuccess)
    { token: JSON.parse(response.body).fetch("auth_token"), applicationId: ENV.fetch("CNAMIO_APPLICATION_ID"), dnsRecords: dns_records }
  end

  # Cnamio-Signature: sha256=<hex> of "{Cnamio-Timestamp}.{raw body}", timestamp within 5 minutes.
  def self.verify_webhook(raw_body, headers, secret = ENV["CNAMIO_WEBHOOK_SECRET"])
    timestamp = headers["Cnamio-Timestamp"].to_s
    return false if secret.blank? || timestamp !~ /\A\d{1,12}\z/ || (Time.now.to_i - timestamp.to_i).abs > 300
    expected = "sha256=" + OpenSSL::HMAC.hexdigest("SHA256", secret, "#{timestamp}.#{raw_body}")
    ActiveSupport::SecurityUtils.secure_compare(expected, headers["Cnamio-Signature"].to_s)
  end
end
```

## 3. Controllers

```ruby
# app/controllers/cnamio_sessions_controller.rb
class CnamioSessionsController < ApplicationController
  before_action :authenticate_user!   # your own auth

  def create
    render json: Cnamio.create_session(user_id: current_user.id, dns_records: Cnamio.records_for(current_user.id))
  rescue StandardError
    render json: { error: "cnamio_unavailable" }, status: :bad_gateway
  end
end

# app/controllers/cnamio_webhooks_controller.rb
class CnamioWebhooksController < ActionController::API
  def create
    raw = request.raw_post   # the raw body: the signature is over these bytes
    return head :unauthorized unless Cnamio.verify_webhook(raw, request.headers)
    event = JSON.parse(raw)
    # Idempotent by event["id"]: the same event may arrive again.
    case event["type"]
    when "domain.added" then mark_domain_connected(event["user_id"], event["domain"])   # your code
    when "domain.propagation.timeout" then mark_domain_failed(event["user_id"], event["domain"])
    end
    head :ok
  end
end
```

```ruby
# config/routes.rb
post "/api/cnamio/session", to: "cnamio_sessions#create"
post "/webhooks/cnamio", to: "cnamio_webhooks#create"
```

## 4. Connect button: in a view

```erb
<script src="https://connect.cnamio.com/sdk/v1.js"></script>
<button id="connect-domain">Connect your domain</button>
<script>
  document.getElementById('connect-domain').addEventListener('click', async () => {
    const r = await fetch('/api/cnamio/session', { method: 'POST', headers: { 'X-CSRF-Token': '<%= form_authenticity_token %>' } });
    if (!r.ok) return alert('Custom domains are unavailable right now.');
    window.cnamio.connectDomain({ ...(await r.json()), applicationName: 'Your App', locale: 'en' });
  });
</script>
```

## 5. Register the webhook and check it

```bash
curl -s -X PUT https://api.cnamio.com/v1/manage/webhook -u "$CNAMIO_APPLICATION_ID:$CNAMIO_SECRET" \
  -H 'Content-Type: application/json' -d '{"url":"https://yourapp.com/webhooks/cnamio"}'
curl -s -X POST https://api.cnamio.com/v1/manage/webhook-test -u "$CNAMIO_APPLICATION_ID:$CNAMIO_SECRET"   # → {"delivered":true}
```

With the test application's credentials every domain goes to the sandbox provider: `shop.example.com` connects at once, `conflict.example.com` shows a conflict, `pending.example.com` never propagates.
