Skip to help content
RightMessage
DevelopersReference

Build a custom connection with an AI agent

Give this page to your AI coding agent and it has everything it needs to build and deploy a RightMessage custom connection on Cloudflare Workers.

Updated

View as Markdown

This page is written for an AI coding agent, such as Claude Code, Codex, Cursor or Amp. Paste its URL, or its Markdown at /help/build-a-custom-connection-with-an-ai-agent.md, into your agent along with a short brief, and it can build a working custom connection on Cloudflare Workers. People should start with Connect your own backend with a custom connection.

A brief you can copy:

Prompt
Read https://rightmessage.com/help/build-a-custom-connection-with-an-ai-agent.md and follow it.
Build me a RightMessage custom connection on Cloudflare Workers for <my system, e.g. FluentCRM on https://crm.example.com>.
My RightMessage project ID is <pid>. The connection ID is <connection-id>.
Segments to read: <segment IDs and the tags/fields that mean them>.
Segments visitors may write: <only interest/preference segments, or none>.
Fields to pass through: <RightMessage key → my field>.
Don't deploy until I've reviewed the code. Ask me for every secret; never put one in code or chat.

Instructions for the agent

You're building the backend half of a RightMessage custom connection: an HTTPS endpoint that answers two signed requests, POST /resolve and POST /changes, under contract v1. The rest of this page is the complete contract and a complete, tested Cloudflare Worker that implements it. Start from that Worker; change only the adapter (the part that talks to the user's system) unless the user asks for more.

Rules:

  1. Secrets. The RightMessage signing secret and the user's system credentials are Worker secrets (npx wrangler secret put …). Never write them into code, wrangler.toml, logs, test fixtures, or your replies. Ask the user to run wrangler secret put themselves, or to paste the value straight into that prompt.
  2. Verify before anything else. Check the timestamp, nonce, body hash and signature before the adapter runs or any database connection opens. The template's handler already does this; keep that order.
  3. Writes are allow-listed. Visitors decide what /changes asks for. Accept segment.add and segment.remove only for segments the user named as writable, and answer rejected for everything else. Never write anything that grants access, records a purchase, or changes a plan.
  4. Fast reads. RightMessage waits at most 800 ms for /resolve. Keep your upstream timeout around 600 ms and make one lookup, not several.
  5. Don't leak. Never echo upstream errors or bodies. An adapter failure is 502 {"error":"upstream"}. Don't log request bodies, clues, emails or IDs.
  6. One tenant. A deployment serves one project ID and one connection ID, and refuses requests for any other.
  7. Test before deploy. Run the tests below and npx wrangler dev --local. Deploy only when the user says so, to the user's Cloudflare account.

What the user does in RightMessage

Order matters: the dashboard sets the Backend URL only when the connection is created, so deploy the Worker first (see Deploy). Until it has the secret it answers 500 {"error":"not_configured"}.

  1. Settings › Integrations › Custom connections › New connection. Name it, set the Connection ID (lowercase letters, numbers, dashes; it can't change later), set Backend URL to the deployed Worker URL (https://<name>.<account>.workers.dev), and optionally a Link token parameter such as fc_hash.
  2. Copy the signing secret shown once, and store it as the Worker secret RM_CONNECTION_SECRET.
  3. Put the link token parameter in email links, filled by the email tool's per-subscriber token merge tag (for FluentCRM, ?fc_hash={{contact.hash}}, which needs the SQL entry point because FluentCRM's REST API can't look up the hash). Have the user check the merge tag in a test email.

In wrangler.toml, set RM_PID to the user's project ID and RM_CONNECTION to the Connection ID. The template's values are examples; left unchanged, every request fails with 401 bad_signature, because both are part of the signed message.

The backend URL must be https://, port 443 or 8443, a public hostname (not an IP address, localhost, .local, .internal, .lan, .corp or home.arpa), with no credentials, query or fragment.

Contract v1

POST /resolve

Request body:

JSON
{ "pid": "1213277114", "connection": "fluentcrm", "clues": { "externalId": "48213" } }

clues has either externalId (the subscriber's ID in the user's system, a string), with email too when RightMessage knows it, or token (the link token from the URL). Look up by externalId when it's present; don't refuse a request that has both. Response, status 200:

JSON
{ "found": true, "contact": { "externalId": "48213", "email": "pat@example.com", "segments": ["seg_pro"], "fields": { "plan": "pro" } } }

or { "found": false }. Contact rules:

  • externalId is a string and must be the subscriber the request asked about (for a token or email clue, the subscriber it resolved to).
  • segments are RightMessage segment IDs (seg_…) from the user's mapping.
  • fields: at most 50; keys match [A-Za-z_][A-Za-z0-9_.-]{0,63}; values are strings, safe integers, booleans or null. No floats, arrays or objects.

Anything else makes RightMessage discard the answer.

RightMessage connects with a 300 ms timeout and waits 800 ms in all. It caches each answer for 5 minutes, serves a cached answer for up to 24 hours while the backend fails, and stops calling for 60 seconds after 5 failures in a row.

POST /changes

Request body:

JSON
{
  "pid": "1213277114",
  "connection": "fluentcrm",
  "changes": [
    { "id": "chg_3f1c0a9b", "externalId": "48213", "op": "segment.add", "segmentId": "seg_topic_seo", "cause": "answer", "at": 1764700000 }
  ]
}

op is segment.add or segment.remove. cause is answer (the visitor answered a question) or api (a script called addSegment/removeSegment). at is Unix seconds. Batches hold at most 10 changes. Response, status 200:

JSON
{ "results": [ { "id": "chg_3f1c0a9b", "status": "applied" } ] }
  • applied: done.
  • rejected: won't be applied; RightMessage never resends it. Use it for any segmentId that isn't writable.
  • retry: RightMessage tries again with backoff, up to 5 attempts within 24 hours. A change missing from results counts as retry.

id is an idempotency key: apply each id at most once. Attaching a tag that's already attached is fine to repeat; an operation that isn't idempotent must record ids it applied. RightMessage waits up to 5 seconds (2 s to connect), so stop calling upstream around 3.5 s and answer retry for the rest.

Request signing (RightMessage → you)

HeaderValue
RM-Key-Idkey ID of the secret that signed it (k_…)
RM-TimestampUnix seconds
RM-Nonce32 lowercase hex characters
RM-Content-SHA256lowercase hex SHA-256 of the raw body bytes
RM-Signaturev1= + lowercase hex HMAC-SHA256

Signed message, lines joined with \n and no trailing newline:

Text
rm-request.v1
POST
<URL path, e.g. /resolve; no host, no query>
<project ID>
<connection ID>
<RM-Timestamp>
<RM-Nonce>
<RM-Content-SHA256>

Reject with 401 when the timestamp is more than 300 s from your clock, the nonce was seen in the last 10 minutes, the body hash differs, or the signature doesn't match (compare in constant time). Reject with 403 when the body's pid or connection isn't yours. During a rotation, accept a signature from either RM_CONNECTION_SECRET or RM_CONNECTION_SECRET_PREVIOUS, and sign the response with the one that matched.

Response signing (you → RightMessage)

Every response, errors included, has RM-Signature: v1=<hex>: HMAC-SHA256 with the secret over

Text
rm-response.v1
<request RM-Nonce>
<HTTP status, e.g. 200>
<lowercase hex SHA-256 of your response body>

Also: Content-Type: application/json, body under 64 KB, no redirects (RightMessage treats a 3xx as an error). Unsigned or mis-signed responses are thrown away.

Signed identify (optional, for signed-in pages)

If the user's site has signed-in subscribers, the server can print a signed claim instead of relying on links:

JavaScript
RM.push(['identify', { connection: 'fluentcrm', externalId: '48213', segments: ['seg_pro'], fields: { plan: 'pro' }, ts: 1764700000, signature: '…' }])

Signature: lowercase hex HMAC-SHA256 over rm-claim.v1\n followed by the canonical JSON of {connection, externalId, email?, segments?, fields?, pid, ts}: keys sorted at every level, no whitespace, JSON.stringify string escaping, optional keys left out when not sent or when null or empty ([], {}), externalId and pid as JSON strings even when they're numeric (WordPress user IDs are integers: cast them). Render it per request (a claim lasts 5 minutes), never into cached HTML.

Test vectors

Secret rm-test-secret-0123456789abcdefghijklmnopqrstuv, project ID 1213277114. Your implementation must reproduce these exactly.

Request to /resolve for connection roost:

  • Body: {"pid":"1213277114","connection":"roost","clues":{"externalId":"48213"}}
  • RM-Timestamp 1764700000, RM-Nonce 0123456789abcdef0123456789abcdef
  • Body SHA-256: 96447e12fc3b96ed72b2bf39afad824269bedaaea828446209322bcf3a217efd
  • Signature: bf592b906548191afe8098e6075db7bb8fe4b721c12e930dfcddee9fcac3ede9

Response, status 200, same nonce:

  • Body: {"found":true,"contact":{"externalId":"48213","email":"pat@example.com","segments":["seg_pro"],"fields":{"plan":"pro"}}}
  • Body SHA-256: 154e94775585c93bd60062a44cf40c6567de770634e7acbde884e71c1779e202
  • Signature: c5c78dec705045490ac8693f238ed7746bd0bde82d664dadd2e4ff196185c5be

Claim {"connection":"roost","externalId":"48213","ts":1764700000}:

  • Canonical JSON: {"connection":"roost","externalId":"48213","pid":"1213277114","ts":1764700000}
  • Signature: 8eed1ad09fdd409498a30c6c8cae33d7db51bc033f23be8612a86bbe8412f26d

The Worker template

Create these files in a new directory. src/signing.js and src/handler.js implement the contract and shouldn't need changes. Write or adapt an adapter in src/adapters/ for the user's system: it exports an object with resolve(clues) returning a contact or null, and changes(changes) returning one {id, status} per change.

package.json

JSON
{
  "name": "rightmessage-custom-connection-worker",
  "private": true,
  "type": "module",
  "description": "RightMessage custom connection (contract v1) on Cloudflare Workers: /resolve and /changes, with FluentCRM, Hyperdrive SQL and Roost-shaped adapters.",
  "scripts": {
    "dev": "wrangler dev --local",
    "deploy": "wrangler deploy",
    "deploy:sql": "wrangler deploy --env sql"
  },
  "devDependencies": {
    "wrangler": "^4.131.1"
  },
  "optionalDependencies": {
    "mysql2": "^3.11.0"
  }
}

wrangler.toml

Toml
# RightMessage custom connection Worker (contract v1). Deploy to YOUR Cloudflare account:
#   npx wrangler secret put RM_CONNECTION_SECRET        # the secret RightMessage showed once
#   npx wrangler secret put FLUENTCRM_USER              # FluentCRM adapter only
#   npx wrangler secret put FLUENTCRM_APP_PASSWORD      # FluentCRM adapter only
#   npx wrangler deploy
# During a secret rotation, also set RM_CONNECTION_SECRET_PREVIOUS until the old key expires.
name = "rightmessage-custom-connection"
main = "src/index.js"
compatibility_date = "2026-09-01"
workers_dev = true

[vars]
RM_PID = "1213277114" # your RightMessage project ID
RM_CONNECTION = "fluentcrm" # the connection ID in RightMessage › Integrations
ADAPTER = "fluentcrm" # fluentcrm | sql | roost
FLUENTCRM_URL = "https://crm.example.com"
# A visitor can put themselves in any segment, so only mark interest tags writable, never plan or access tags.
SEGMENT_TAGS = '[{"segment":"seg_pro","tagId":3,"tagSlug":"pro"},{"segment":"seg_topic_seo","tagId":5,"tagSlug":"topic-seo","write":true}]'
FIELD_MAP = '{"plan":"plan"}'
UPSTREAM_TIMEOUT_MS = "600" # RightMessage waits at most 800 ms in all

# Hyperdrive SQL lookup: `npm install mysql2`, create a Hyperdrive config, uncomment, then `wrangler deploy --env sql`.
# [env.sql]
# main = "src/index-sql.js"
# compatibility_flags = ["nodejs_compat"]
# vars = { RM_PID = "1213277114", RM_CONNECTION = "fluentcrm", TABLE_PREFIX = "wp_", SEGMENT_TAGS = '[{"segment":"seg_pro","tagSlug":"pro"}]' }
# [[env.sql.hyperdrive]]
# binding = "HYPERDRIVE"
# id = "<your hyperdrive id>"

src/signing.js

JavaScript
// Contract v1 signing (RightMessage custom connections). Same bytes as App\Services\CustomConnections\RequestSigning;
// vectors in tests/Fixtures/custom-connections/contract-v1.json of the RightMessage repository.
const encoder = new TextEncoder()

const hex = (buffer) => Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, '0')).join('')

export const sha256 = async (text) => hex(await crypto.subtle.digest('SHA-256', encoder.encode(text)))

export const hmac = async (secret, message) => {
  const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, [
    'sign'
  ])
  return hex(await crypto.subtle.sign('HMAC', key, encoder.encode(message)))
}

/** Compares two hex strings in time that depends only on their length. */
export const safeEqual = (a, b) => {
  if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) {
    return false
  }
  let diff = 0
  for (let index = 0; index < a.length; index++) {
    diff |= a.charCodeAt(index) ^ b.charCodeAt(index)
  }
  return diff === 0
}

export const requestMessage = ({ method, path, pid, slug, ts, nonce, bodySha256 }) =>
  ['rm-request.v1', method.toUpperCase(), path, pid, slug, String(ts), nonce, bodySha256].join('\n')

export const responseMessage = ({ nonce, status, bodySha256 }) =>
  ['rm-response.v1', nonce, String(status), bodySha256].join('\n')

/** `RM-Signature: v1=<hex>`; any other version is refused. */
export const fromHeader = (header) => /^v1=([0-9a-f]{64})$/.exec((header || '').trim())?.[1] || null

src/handler.js

JavaScript
import { fromHeader, hmac, requestMessage, responseMessage, safeEqual, sha256 } from './signing.js'

export const WINDOW_SECONDS = 300
export const MAX_BODY_BYTES = 65536
const MAX_NONCES = 10000

/**
 * The RightMessage side of a custom connection: `POST /resolve` and `POST /changes`, contract v1.
 *
 * Every request must carry a fresh timestamp (±300 s), a nonce never seen in this isolate, a body hash that matches,
 * and an HMAC-SHA256 signature made with the connection's secret; and its `pid` and `connection` must be this
 * deployment's own. Every response, errors included, is signed and bound to the request's nonce. Nothing from the
 * adapter's backend is echoed: an adapter failure is `502 {"error":"upstream"}`. Nothing is logged.
 *
 * Replay: nonces are remembered per isolate only. Cloudflare can run several isolates, so a replay inside the 5-minute
 * window can land on another one; for strict single use, swap `nonces` for a Durable Object or KV.
 *
 * @param {{ adapter: { resolve(clues: object): Promise<object|null>, changes(changes: object[]): Promise<object[]> },
 *   nonces?: Map<string, number>, now?: () => number }} options The backend adapter, the nonce cache and a clock.
 */
export const createHandler = ({ adapter, nonces = new Map(), now = () => Date.now() }) => {
  const remember = (nonce) => {
    const time = now()
    if (nonces.size >= MAX_NONCES) {
      for (const [key, expires] of nonces) {
        if (expires <= time) {
          nonces.delete(key)
        }
      }
    }
    if (nonces.has(nonce) && nonces.get(nonce) > time) {
      return false
    }
    if (nonces.size >= MAX_NONCES) {
      // Full of live nonces: refuse rather than forget one (fails closed).
      return false
    }
    nonces.set(nonce, time + WINDOW_SECONDS * 2 * 1000)
    return true
  }

  return async (request, env) => {
    const secrets = [env.RM_CONNECTION_SECRET, env.RM_CONNECTION_SECRET_PREVIOUS].filter(Boolean)
    const nonce = request.headers.get('RM-Nonce') || ''
    let signingSecret = secrets[0]
    const respond = async (status, body) => {
      const text = JSON.stringify(body)
      const signature = signingSecret
        ? await hmac(signingSecret, responseMessage({ nonce, status, bodySha256: await sha256(text) }))
        : ''
      return new Response(text, {
        status,
        headers: { 'Content-Type': 'application/json', 'RM-Signature': `v1=${signature}`, 'Cache-Control': 'no-store' }
      })
    }

    const url = new URL(request.url)
    const operation = url.pathname.split('/').pop()
    if (request.method !== 'POST' || !['resolve', 'changes'].includes(operation)) {
      return respond(404, { error: 'not_found' })
    }
    if (!secrets.length || !env.RM_PID || !env.RM_CONNECTION) {
      return respond(500, { error: 'not_configured' })
    }

    const ts = Number(request.headers.get('RM-Timestamp'))
    const given = fromHeader(request.headers.get('RM-Signature'))
    if (!/^[0-9a-f]{32}$/.test(nonce) || !Number.isSafeInteger(ts) || !given) {
      return respond(401, { error: 'bad_signature' })
    }
    if (Math.abs(now() / 1000 - ts) > WINDOW_SECONDS) {
      return respond(401, { error: 'expired' })
    }
    const declaredLength = Number(request.headers.get('Content-Length') || 0)
    if (declaredLength > MAX_BODY_BYTES) {
      return respond(413, { error: 'too_large' })
    }
    const raw = await request.text()
    if (raw.length > MAX_BODY_BYTES) {
      return respond(413, { error: 'too_large' })
    }
    const bodySha256 = await sha256(raw)
    if (request.headers.get('RM-Content-SHA256') !== bodySha256) {
      return respond(401, { error: 'bad_signature' })
    }
    const message = requestMessage({
      method: request.method,
      path: url.pathname,
      pid: env.RM_PID,
      slug: env.RM_CONNECTION,
      ts,
      nonce,
      bodySha256
    })
    // Two secrets during a rotation's overlap. Every candidate is computed, so timing doesn't say which matched.
    let matched = null
    for (const secret of secrets) {
      if (safeEqual(await hmac(secret, message), given) && matched === null) {
        matched = secret
      }
    }
    if (!matched) {
      return respond(401, { error: 'bad_signature' })
    }
    signingSecret = matched
    if (!remember(nonce)) {
      return respond(401, { error: 'replayed' })
    }

    let body
    try {
      body = JSON.parse(raw)
    } catch {
      return respond(400, { error: 'bad_request' })
    }
    // One deployment serves one project's one connection; a request for another tenant is refused.
    if (body?.pid !== env.RM_PID || body?.connection !== env.RM_CONNECTION) {
      return respond(403, { error: 'wrong_tenant' })
    }

    try {
      if (operation === 'resolve') {
        const clues = body.clues && typeof body.clues === 'object' ? body.clues : {}
        const contact = await adapter.resolve(clues)
        return respond(200, contact ? { found: true, contact } : { found: false })
      }
      const changes = Array.isArray(body.changes) ? body.changes.slice(0, 100) : []
      return respond(200, { results: await adapter.changes(changes) })
    } catch {
      return respond(502, { error: 'upstream' })
    }
  }
}

src/index.js

JavaScript
import { createFluentCrmAdapter } from './adapters/fluentcrm.js'
import { createRoostAdapter } from './adapters/roost.js'
import { createHandler } from './handler.js'

// One nonce cache per isolate (see handler.js about strict single use).
const nonces = new Map()

// ADAPTER = fluentcrm (default) or roost. The Hyperdrive SQL adapter has its own entry, src/index-sql.js.
export default {
  async fetch(request, env) {
    const adapter = env.ADAPTER === 'roost' ? createRoostAdapter(env) : createFluentCrmAdapter(env)
    return createHandler({ adapter, nonces })(request, env)
  }
}

src/adapters/fluentcrm.js

JavaScript
/**
 * FluentCRM (WordPress) over its REST API, the first proof of the custom connection contract.
 *
 * Auth: a WordPress Application Password for a dedicated FluentCRM manager (Contacts Read and Contacts
 * Add/Update; never an Administrator), stored only as Worker secrets FLUENTCRM_USER and FLUENTCRM_APP_PASSWORD.
 * RightMessage never sees it.
 *
 * Mapping (Worker vars, JSON):
 * - SEGMENT_TAGS: [{ "segment": "seg_topic_seo", "tagId": 5, "tagSlug": "topic-seo", "write": true }]. A contact with
 *   the tag is in the segment. Only a mapping with `"write": true` accepts changes: `segment.add` attaches the tag and
 *   `segment.remove` detaches it; anything else is `rejected`. A visitor can put themselves in any segment (an answer,
 *   `RM.push(['addSegment', …])`), so never mark a tag that grants access or reflects payment (a plan, a course) as
 *   writable.
 * - CHANGES_BUDGET_MS: stop calling WordPress after this long and answer `retry` for the rest (default 3500, under
 *   RightMessage's 5 s wait).
 * - FIELD_MAP: { "plan": "plan" }: RightMessage field key → FluentCRM custom field slug, read from custom_values.
 *
 * Clues: `externalId` (the FluentCRM subscriber ID) or `email`. A link `token` (FluentCRM's subscriber `hash`) can't
 * be looked up over REST; use the SQL adapter for tokens.
 */
const json = (value, fallback) => {
  try {
    return value ? JSON.parse(value) : fallback
  } catch {
    return fallback
  }
}

export const createFluentCrmAdapter = (env, fetchImpl = fetch) => {
  const base = `${String(env.FLUENTCRM_URL || '').replace(/\/+$/, '')}/wp-json/fluent-crm/v2`
  const auth = `Basic ${btoa(`${env.FLUENTCRM_USER}:${env.FLUENTCRM_APP_PASSWORD}`)}`
  const segmentTags = json(env.SEGMENT_TAGS, [])
  const fieldMap = json(env.FIELD_MAP, {})
  const timeoutMs = Number(env.UPSTREAM_TIMEOUT_MS || 600)
  const budgetMs = Number(env.CHANGES_BUDGET_MS || 3500)

  const call = async (method, path, body) => {
    const response = await fetchImpl(`${base}${path}`, {
      method,
      headers: {
        Authorization: auth,
        Accept: 'application/json',
        ...(body ? { 'Content-Type': 'application/json' } : {})
      },
      body: body ? JSON.stringify(body) : undefined,
      redirect: 'manual',
      signal: AbortSignal.timeout(timeoutMs)
    })
    if (response.status === 404) {
      return null
    }
    if (!response.ok) {
      throw new Error(`fluentcrm_${response.status}`)
    }
    return response.json()
  }

  const toContact = (subscriber) => {
    if (!subscriber?.id) {
      return null
    }
    const slugs = new Set((subscriber.tags || []).map((tag) => tag.slug))
    const values = subscriber.custom_values || {}
    const fields = {}
    for (const [key, slug] of Object.entries(fieldMap)) {
      const value = values[slug]
      if (typeof value === 'string' || typeof value === 'boolean' || value === null) {
        fields[key] = value
      } else if (Number.isSafeInteger(value)) {
        fields[key] = value
      }
    }
    return {
      externalId: String(subscriber.id),
      email: subscriber.email || null,
      segments: segmentTags.filter((entry) => slugs.has(entry.tagSlug)).map((entry) => entry.segment),
      fields
    }
  }

  return {
    async resolve(clues) {
      const query = 'with%5B%5D=subscriber.custom_values'
      if (typeof clues.externalId === 'string' && /^\d{1,18}$/.test(clues.externalId)) {
        return toContact((await call('GET', `/subscribers/${clues.externalId}?${query}`))?.subscriber)
      }
      if (typeof clues.email === 'string' && clues.email.includes('@')) {
        const email = encodeURIComponent(clues.email)
        return toContact((await call('GET', `/subscribers/0?get_by_email=${email}&${query}`))?.subscriber)
      }
      return null
    },

    async changes(changes) {
      const results = []
      const deadline = Date.now() + budgetMs
      for (const change of changes) {
        if (Date.now() + timeoutMs > deadline) {
          results.push({ id: change.id, status: 'retry' })
          continue
        }
        // Only mappings marked `write: true`: every writable segment is one a visitor can set on themselves.
        const tag = segmentTags.find((entry) => entry.segment === change.segmentId && entry.write === true)
        if (
          !tag ||
          !/^\d{1,18}$/.test(String(change.externalId)) ||
          !['segment.add', 'segment.remove'].includes(change.op)
        ) {
          results.push({ id: change.id, status: 'rejected' })
          continue
        }
        try {
          const key = change.op === 'segment.add' ? 'attach_tags' : 'detach_tags'
          const updated = await call('PUT', `/subscribers/${change.externalId}`, { subscriber: { [key]: [tag.tagId] } })
          results.push({ id: change.id, status: updated ? 'applied' : 'rejected' })
        } catch {
          // Attaching or detaching a tag twice changes nothing, so a retry is safe.
          results.push({ id: change.id, status: 'retry' })
        }
      }
      return results
    }
  }
}

src/adapters/roost.js

JavaScript
/**
 * A Roost-shaped example: a subscriber API with numeric subscriber IDs, tags and custom fields, reached with a bearer
 * token. The paths and response shape are assumptions for illustration, not a real API. Replace the two calls with
 * your system's real ones.
 *
 * Vars: ROOST_API_URL; secret: ROOST_API_TOKEN; SEGMENT_TAGS: [{ "segment": "seg_topic_seo", "tagSlug": "topic-seo",
 * "write": true }]. Only mappings with `"write": true` accept changes; see the FluentCRM adapter about which tags
 * must stay read-only. CHANGES_BUDGET_MS (default 3500) stops calling Roost and answers `retry` for the rest.
 */
export const createRoostAdapter = (env, fetchImpl = fetch) => {
  const base = String(env.ROOST_API_URL || '').replace(/\/+$/, '')
  const segmentTags = (() => {
    try {
      return JSON.parse(env.SEGMENT_TAGS || '[]')
    } catch {
      return []
    }
  })()
  const timeoutMs = Number(env.UPSTREAM_TIMEOUT_MS || 600)
  const budgetMs = Number(env.CHANGES_BUDGET_MS || 3500)
  const call = (method, path, body) =>
    fetchImpl(`${base}${path}`, {
      method,
      headers: {
        Authorization: `Bearer ${env.ROOST_API_TOKEN}`,
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: body ? JSON.stringify(body) : undefined,
      redirect: 'manual',
      signal: AbortSignal.timeout(timeoutMs)
    })

  return {
    async resolve(clues) {
      if (typeof clues.externalId !== 'string' || !/^\d{1,18}$/.test(clues.externalId)) {
        return null
      }
      const response = await call('GET', `/subscribers/${clues.externalId}`)
      if (response.status === 404) {
        return null
      }
      if (!response.ok) {
        throw new Error(`roost_${response.status}`)
      }
      const subscriber = await response.json()
      const tags = new Set(subscriber.tags || [])
      return {
        externalId: String(subscriber.id),
        email: subscriber.email || null,
        segments: segmentTags.filter((entry) => tags.has(entry.tagSlug)).map((entry) => entry.segment),
        fields: {}
      }
    },

    async changes(changes) {
      const results = []
      const deadline = Date.now() + budgetMs
      for (const change of changes) {
        if (Date.now() + timeoutMs > deadline) {
          results.push({ id: change.id, status: 'retry' })
          continue
        }
        // Only mappings marked `write: true`: every writable segment is one a visitor can set on themselves.
        const tag = segmentTags.find((entry) => entry.segment === change.segmentId && entry.write === true)
        if (!tag) {
          results.push({ id: change.id, status: 'rejected' })
          continue
        }
        const response = await call(
          change.op === 'segment.add' ? 'POST' : 'DELETE',
          `/subscribers/${change.externalId}/tags`,
          {
            tag: tag.tagSlug,
            idempotencyKey: change.id
          }
        ).catch(() => null)
        results.push({
          id: change.id,
          status: response?.ok ? 'applied' : response && response.status < 500 ? 'rejected' : 'retry'
        })
      }
      return results
    }
  }
}

src/adapters/sql.js

JavaScript
/**
 * A short SQL lookup through Cloudflare Hyperdrive, for backends whose database the Worker can reach. The example
 * queries FluentCRM's own tables (`wp_fc_subscribers`, `wp_fc_subscriber_pivot`, `wp_fc_tags`); change the SQL for
 * your schema. Read-only: `/changes` answers `rejected` (never retried) so writes go through an adapter that owns them (combine with the
 * REST adapter in src/index.js if you need both).
 *
 * `query(sql, params)` runs one parameterised statement and resolves to rows. src/index.js builds it from mysql2 and
 * the HYPERDRIVE binding. Never interpolate clues into SQL.
 */
const PREFIX = /^[A-Za-z0-9_]{1,32}$/

/**
 * A `query` that opens its database connection on first use, so a request that fails the signature check (the
 * handler runs the adapter only after it) never reaches the database. `close()` ends a connection if one opened.
 */
export const lazyQuery = (connect) => {
  let opened = null
  return {
    query: async (sql, params) => {
      opened ||= connect()
      return (await (await opened).execute(sql, params))[0]
    },
    close: async () => {
      const connection = opened ? await opened.catch(() => null) : null
      await connection?.end()
    }
  }
}

export const createSqlAdapter = (env, query) => {
  const prefix = PREFIX.test(env.TABLE_PREFIX || '') ? env.TABLE_PREFIX : 'wp_'
  const segmentTags = (() => {
    try {
      return JSON.parse(env.SEGMENT_TAGS || '[]')
    } catch {
      return []
    }
  })()

  return {
    async resolve(clues) {
      let where
      let value
      if (typeof clues.externalId === 'string' && /^\d{1,18}$/.test(clues.externalId)) {
        ;[where, value] = ['s.id = ?', clues.externalId]
      } else if (typeof clues.email === 'string' && clues.email.includes('@')) {
        ;[where, value] = ['s.email = ?', clues.email]
      } else if (typeof clues.token === 'string' && /^[A-Za-z0-9]{16,64}$/.test(clues.token)) {
        ;[where, value] = ['s.hash = ?', clues.token]
      } else {
        return null
      }
      const rows = await query(
        `SELECT s.id, s.email, t.slug AS tag_slug FROM ${prefix}fc_subscribers s ` +
          `LEFT JOIN ${prefix}fc_subscriber_pivot p ON p.subscriber_id = s.id AND p.object_type = 'FluentCrm\\\\App\\\\Models\\\\Tag' ` +
          `LEFT JOIN ${prefix}fc_tags t ON t.id = p.object_id WHERE ${where} LIMIT 200`,
        [value]
      )
      if (!rows.length) {
        return null
      }
      const slugs = new Set(rows.map((row) => row.tag_slug).filter(Boolean))
      return {
        externalId: String(rows[0].id),
        email: rows[0].email || null,
        segments: segmentTags.filter((entry) => slugs.has(entry.tagSlug)).map((entry) => entry.segment),
        fields: {}
      }
    },

    async changes(changes) {
      return changes.map((change) => ({ id: change.id, status: 'rejected' }))
    }
  }
}

src/index-sql.js

JavaScript
import { createConnection } from 'mysql2/promise'
import { createSqlAdapter, lazyQuery } from './adapters/sql.js'
import { createHandler } from './handler.js'

const nonces = new Map()

// `wrangler deploy --env sql`, after `npm install mysql2` and a Hyperdrive config for your MySQL database.
// The database connection opens only once a request has passed the signature check (lazyQuery).
export default {
  async fetch(request, env) {
    const { query, close } = lazyQuery(() =>
      createConnection({
        host: env.HYPERDRIVE.host,
        user: env.HYPERDRIVE.user,
        password: env.HYPERDRIVE.password,
        database: env.HYPERDRIVE.database,
        port: env.HYPERDRIVE.port,
        disableEval: true
      })
    )
    try {
      return await createHandler({ adapter: createSqlAdapter(env, query), nonces })(request, env)
    } finally {
      await close()
    }
  }
}

Test it

A minimal test with the vectors above, saved as test/signing.test.js and run with Vitest (npx vitest run):

JavaScript
import { describe, expect, it } from 'vitest'
import { createHandler } from '../src/handler.js'
import { hmac, requestMessage, sha256 } from '../src/signing.js'

const env = { RM_PID: '1213277114', RM_CONNECTION: 'roost', RM_CONNECTION_SECRET: 'rm-test-secret-0123456789abcdefghijklmnopqrstuv' }
const body = '{"pid":"1213277114","connection":"roost","clues":{"externalId":"48213"}}'
const nonce = '0123456789abcdef0123456789abcdef'

describe('contract v1', () => {
  it('reproduces the request vector', async () => {
    const bodySha256 = await sha256(body)
    expect(bodySha256).toBe('96447e12fc3b96ed72b2bf39afad824269bedaaea828446209322bcf3a217efd')
    const message = requestMessage({ method: 'POST', path: '/resolve', pid: env.RM_PID, slug: 'roost', ts: 1764700000, nonce, bodySha256 })
    expect(await hmac(env.RM_CONNECTION_SECRET, message)).toBe('bf592b906548191afe8098e6075db7bb8fe4b721c12e930dfcddee9fcac3ede9')
  })

  it('answers a signed request and refuses a tampered one', async () => {
    const adapter = { resolve: async () => ({ externalId: '48213', segments: [], fields: {} }), changes: async () => [] }
    const now = () => 1764700000 * 1000
    const bodySha256 = await sha256(body)
    const signature = await hmac(env.RM_CONNECTION_SECRET, requestMessage({ method: 'POST', path: '/resolve', pid: env.RM_PID, slug: 'roost', ts: 1764700000, nonce, bodySha256 }))
    const request = (text) => new Request('https://worker.example/resolve', {
      method: 'POST',
      body: text,
      headers: { 'RM-Timestamp': '1764700000', 'RM-Nonce': nonce, 'RM-Content-SHA256': bodySha256, 'RM-Signature': `v1=${signature}` }
    })
    const ok = await createHandler({ adapter, now })(request(body), env)
    expect(ok.status).toBe(200)
    expect(await ok.json()).toEqual({ found: true, contact: { externalId: '48213', segments: [], fields: {} } })
    const tampered = await createHandler({ adapter, now })(request(body.replace('48213', '48214')), env)
    expect(tampered.status).toBe(401)
  })
})

Then run it locally against a stub of the user's system. No Cloudflare account is needed:

Shell
npm install
npx vitest run
npx wrangler dev --local

Deploy

Only after the user has reviewed the code:

Shell
npx wrangler login                       # the user's own Cloudflare account
npx wrangler deploy                      # answers not_configured until the secret is set
# the user now creates the connection with this Worker URL as its Backend URL, then:
npx wrangler secret put RM_CONNECTION_SECRET
# plus the adapter's credentials, e.g. for FluentCRM over REST:
npx wrangler secret put FLUENTCRM_USER
npx wrangler secret put FLUENTCRM_APP_PASSWORD

For the SQL entry point (src/index-sql.js), uncomment the [env.sql] block in wrangler.toml, add --env sql to wrangler deploy and wrangler secret put, and skip the FluentCRM credentials: Hyperdrive holds the database credentials.

Then the user checks a link with ?debug=true: the debugger should show the subscriber from their system as signed.

Adapting to other systems

  • REST API with a key (Kit-like, ConvertKit-like, a membership plugin): start from src/adapters/roost.js. Replace its paths with the real API. Map the system's tags or groups to RightMessage segment IDs with a SEGMENT_TAGS variable, and mark only interest segments writable.
  • Direct database access: start from src/adapters/sql.js and src/index-sql.js with Cloudflare Hyperdrive. Use one parameterized query; never interpolate clues into SQL. Keep it read-only unless the user asks for writes.
  • Link tokens: the system needs a per-subscriber value nobody can guess (a hash or random token), available as an email merge tag. Never use a plain email address or a sequential ID as the token. A token must be 16 to 256 characters of letters, digits, ., _, ~ and -; RightMessage refuses anything else before asking the Worker.
  • Nonces: the template remembers nonces per Worker isolate. For strict single use across isolates, store them in a Durable Object or KV with a 10-minute expiry.

Rotating the secret

When the user clicks Rotate secret in RightMessage, RightMessage signs its requests with the new secret immediately, so update the Worker right away: set the new secret as RM_CONNECTION_SECRET and the old one as RM_CONNECTION_SECRET_PREVIOUS. Until then, /resolve and /changes fail. The old secret keeps verifying identify claims the user's own server signs for 7 days; remove RM_CONNECTION_SECRET_PREVIOUS once they're over.

Still need a hand?

Tell us what you’re trying to do and where you’re getting stuck.

support@rightmessage.com