# RUO compliance feed

Stores in OnCharge's research-use-only (RUO) programme are reviewed against the programme rules before payments are enabled, and again every day afterwards. A compliant RUO store keeps its catalogue behind a research-access gate, so OnCharge cannot read it as an anonymous visitor. The **compliance feed** is a small, read-only, signed API that your store serves so OnCharge can read the catalogue as a verified buyer would see it.

This page is only for RUO merchants. Other stores can skip it.

| Platform | How to serve the feed |
|---|---|
| WooCommerce | Install the **OnCharge Compliance Scanner** plugin. See [WooCommerce](https://oncharge.io/docs/woocommerce#ruo-compliance-scanner). |
| Next.js | `createComplianceFeedRoute` from `@oncharge/node/next`. See [below](#nextjs). |
| Magento 2 (beta) | Built into the [Magento module](https://oncharge.io/docs/magento): base path `/oncharge/compliance`. |
| Wix (beta) | Built into the [Wix integration](https://oncharge.io/docs/wix): base path `/_functions/onchargeCompliance`. |
| Anything else | Implement the three endpoints below, or use `createComplianceFeed` from `@oncharge/node`. |

## How it works

1. In the merchant portal, start a store connection for your store's host (for example `shop.example.com`), choose its platform and, for anything but WordPress, the feed's base path. The default is `/.well-known/oncharge-compliance`.
2. OnCharge shows a one-time **connection code** `occs_<connection-id>.<secret>`. Save it as a server secret (for example `ONCHARGE_COMPLIANCE_CODE`); it is not shown again.
3. Your store serves three `GET` endpoints on that host:
   - `<base>/proof`: proves your server holds the code (ownership check).
   - `<base>/content`: one page of published products and pages (signed requests only).
   - `<base>/reviewer-access`: whether a reviewer login is ready (signed requests only).
4. In the portal, select **Verify connection**, then run a scan.

The endpoints must be served from the connected host itself (`https://<host><base>/…`), not a separate API domain, because answering from that host is what proves you control it. If your research gate or firewall blocks unknown visitors, allow these paths.

A base path is only a path on that host: one or more `/segment` parts made of `A-Z a-z 0-9 . _ ~ -`, with no `.` or `..` segment, no query, fragment, `%`, `\`, `@`, `:` or whitespace, no trailing slash, and at most 200 characters. WordPress stores use the plugin's REST routes instead (`https://<host>/?rest_route=/oncharge-compliance-scanner/v1/<endpoint>`).

## Keys

From the code `occs_<connection-id>.<secret>`:

- `connection_id` is the UUID.
- `signing_key` is the lower-case hex SHA-256 of the UTF-8 `<secret>` (64 characters). Every HMAC below is HMAC-SHA256 **keyed with this 64-character string as ASCII bytes**, output in lower-case hex.

The strings that are signed always use the canonical routes `/oncharge-compliance-scanner/v1/content` and `/oncharge-compliance-scanner/v1/reviewer-access`, whatever URL you serve them at.

## `GET <base>/proof?challenge=<hex64>&ts=<unix seconds>`

Not authenticated. Respond `200` with JSON and `Cache-Control: no-store`:

```json
{ "connection_id": "<uuid>", "host": "shop.example.com", "proof": "<hex>", "plugin_version": "1.0.0" }
```

`proof = HMAC(signing_key, "oncharge-compliance-scanner.proof.v1|" + host + "|" + challenge + "|" + ts)`, where `host` is the host as configured in the portal. Respond `409` if no connection code is configured.

## `GET <base>/content?cursor=<int>&limit=<int>`

Signed by OnCharge with these headers:

| Header | Value |
|---|---|
| `X-OnCharge-Scanner-Connection` | The connection UUID. |
| `X-OnCharge-Scanner-Timestamp` | Unix seconds. |
| `X-OnCharge-Scanner-Nonce` | 32 hex characters, single use. |
| `X-OnCharge-Scanner-Signature` | Hex HMAC below. |

Accept the request only if the connection ID matches, `|now - ts| <= 300`, the nonce was not seen in the last 10 minutes, and the signature equals (constant-time compare):

```text
HMAC(signing_key, "oncharge-compliance-scanner.content.v1|GET|/oncharge-compliance-scanner/v1/content|cursor=<cursor>&limit=<limit>|<ts>|<nonce>")
```

Otherwise respond `401` (bad signature, clock skew, replay) or `409` (not connected). `cursor` starts at `0`; `limit` is at most `50`.

```json title="200 OK"
{
  "plugin_version": "1.0.0",
  "site": {
    "name": "Example Research Supply",
    "tagline": "Reference materials for laboratory research",
    "home_url": "https://shop.example.com/",
    "wc_active": false,
    "terms_page_url": "https://shop.example.com/terms",
    "privacy_policy_url": "https://shop.example.com/privacy",
    "refund_page_url": "https://shop.example.com/refunds",
    "shipping_page_url": "https://shop.example.com/shipping",
    "contact_page_url": "https://shop.example.com/contact"
  },
  "items": [
    {
      "type": "product",
      "id": 123,
      "url": "https://shop.example.com/products/example-compound",
      "title": "Example compound, 10 mg",
      "content_html": "<p>For laboratory research use only. Not for human or veterinary use.</p>",
      "short_description_html": "",
      "price_html": "$49.00",
      "sku": "EX-10",
      "meta_description": "",
      "image_alts": ["Example compound vial"],
      "categories": [{ "name": "Reference materials", "url": "https://shop.example.com/c/reference" }],
      "tags": [],
      "attributes": [{ "name": "Purity", "value": "≥99%" }],
      "attachments": [{ "url": "https://shop.example.com/coa/ex-10-lot-123.pdf", "title": "COA lot 123", "mime": "application/pdf" }]
    }
  ],
  "next_cursor": 50,
  "truncated": false
}
```

- `type` is `product`, `page` or `post`; `id` is a non-negative integer, unique per type.
- Serve every published product, **including products behind an age or research gate**, plus the pages with your terms, privacy policy, refunds, shipping, contact details and research-use statements. Never include drafts, private content, orders or customers.
- `next_cursor` is `null` on the last page. Serve at most 5,000 items in total and set `truncated: true` if there are more.
- Limits: titles 2,000 characters; HTML fields 250,000; at most 200 image alts; 100 categories, tags or attributes; 40 attachments per item.

## `GET <base>/reviewer-access`

Signed like `content`, with the message:

```text
"oncharge-compliance-scanner.reviewer-access.v1|GET|/oncharge-compliance-scanner/v1/reviewer-access||<ts>|<nonce>"
```

Card-network and payment reviewers must be able to see a gated catalogue. Create a dedicated, non-administrator reviewer account on your store with the same research access a verified buyer has, sign in as it once to confirm it sees products and prices, and give the login to OnCharge yourself (never through this endpoint). The endpoint only reports the status:

```json
{
  "host": "shop.example.com",
  "ready": true,
  "account_exists": true,
  "can_view_catalog": true,
  "owner_confirmed": true,
  "checked_at": 1700000000,
  "nonce": "<the request's nonce>",
  "signature": "<hex>"
}
```

`signature = HMAC(signing_key, "oncharge-compliance-scanner.reviewer-status.v1|" + host + "|" + b(ready) + "|" + b(account_exists) + "|" + b(can_view_catalog) + "|" + b(owner_confirmed) + "|" + checked_at + "|" + nonce)`, where `b(x)` is `1` or `0`. `ready` is true only when the other three are.

## Test vectors

`secret = "test-secret"`, so `signing_key = 9caf06bb4436cdbfa20af9121a626bc1093c4f54b31c0fa937957856135345b6`. With host `shop.example.com`, timestamp `1700000000` and nonce `0123456789abcdef0123456789abcdef`:

| Message | Expected HMAC |
|---|---|
| proof, challenge = 64 zeros | `ce6be291c7332d8c03841e376170ce56e1b8b3948b25e82fcfd74ab9ac60be80` |
| content, `cursor=0&limit=50` | `2d8b01d1ec2bb18d290360e8273dbaa3f668feb173f4febf1f37147e11ceaff3` |
| reviewer-access request | `e1c441bfc451e4d96111660dbacae2d6e2edae506cafa41d2e0c58bbc723f85c` |
| reviewer status, all `1`, `checked_at=1700000000` | `6f18051e96fbb2085ad6f859bfce11ca039ffee5c2ba0bc661e63bcea55bec9f` |

Add these to your unit tests.

## Reference implementation (any JavaScript runtime)

A dependency-free handler using the standard `Request`/`Response` API (Node 18+, Next.js, Remix, Hono, Cloudflare Workers, Bun, Deno). Route every request under your base path to it.

```js title="compliance-feed.mjs" test="ruo-node"
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';

const CONTENT_ROUTE = '/oncharge-compliance-scanner/v1/content';
const REVIEWER_ROUTE = '/oncharge-compliance-scanner/v1/reviewer-access';
const VERSION = '1.0.0';

const hmac = (key, message) => createHmac('sha256', key).update(message, 'utf8').digest('hex');
const sameHex = (a, b) => typeof b === 'string' && /^[0-9a-f]{64}$/.test(b) && timingSafeEqual(Buffer.from(a), Buffer.from(b));
const json = (status, body) =>
  new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' } });

export function parseConnectionCode(code) {
  const m = /^occs_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.([A-Za-z0-9_-]{43})$/.exec(String(code ?? '').trim());
  if (!m) return null;
  return { connectionId: m[1], signingKey: createHash('sha256').update(m[2], 'utf8').digest('hex') };
}

export const proofSignature = (key, host, challenge, ts) => hmac(key, `oncharge-compliance-scanner.proof.v1|${host}|${challenge}|${ts}`);

export const reviewerStatusSignature = (key, s) =>
  hmac(key, ['oncharge-compliance-scanner.reviewer-status.v1', s.host, +s.ready, +s.account_exists, +s.can_view_catalog, +s.owner_confirmed, s.checked_at, s.nonce].join('|'));

/**
 * options.connectionCode  the occs_… code (server secret)
 * options.host            the host exactly as connected, e.g. "shop.example.com"
 * options.site            { name, tagline, home_url, terms_page_url, … }
 * options.listItems       async ({ cursor, limit }) => ({ items, nextCursor, truncated? })
 * options.reviewerAccess  async () => ({ accountExists, canViewCatalog, ownerConfirmed })
 * options.nonceStore      { claim(nonce, ttlSeconds) } → false if already seen; use a shared store (Redis, database) when you run several instances
 */
export function createFeedHandler(options) {
  const seen = new Map();
  const nonces = options.nonceStore ?? {
    claim(nonce, ttlSeconds) {
      if ((seen.get(nonce) ?? 0) > Date.now()) return false;
      seen.set(nonce, Date.now() + ttlSeconds * 1000);
      return true;
    },
  };

  return async function handle(request) {
    const conn = parseConnectionCode(options.connectionCode);
    if (!conn) return json(409, { error: 'not_connected' });
    const url = new URL(request.url);
    const endpoint = url.pathname.replace(/\/+$/, '').split('/').pop();

    if (endpoint === 'proof') {
      const challenge = url.searchParams.get('challenge') ?? '';
      const ts = url.searchParams.get('ts') ?? '';
      if (!/^[0-9a-f]{64}$/.test(challenge) || !/^\d+$/.test(ts)) return json(400, { error: 'bad_request' });
      return json(200, { connection_id: conn.connectionId, host: options.host, proof: proofSignature(conn.signingKey, options.host, challenge, ts), plugin_version: VERSION });
    }

    // Signed endpoints
    const h = (name) => request.headers.get(name) ?? '';
    const ts = h('X-OnCharge-Scanner-Timestamp');
    const nonce = h('X-OnCharge-Scanner-Nonce');
    if (h('X-OnCharge-Scanner-Connection') !== conn.connectionId) return json(401, { error: 'unauthorized' });
    if (!/^\d+$/.test(ts) || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return json(401, { error: 'unauthorized' });
    if (!/^[0-9a-f]{32}$/.test(nonce)) return json(401, { error: 'unauthorized' });

    let message;
    if (endpoint === 'content') {
      const cursor = url.searchParams.get('cursor') ?? '';
      const limit = url.searchParams.get('limit') ?? '';
      message = `oncharge-compliance-scanner.content.v1|GET|${CONTENT_ROUTE}|cursor=${cursor}&limit=${limit}|${ts}|${nonce}`;
    } else if (endpoint === 'reviewer-access') {
      message = `oncharge-compliance-scanner.reviewer-access.v1|GET|${REVIEWER_ROUTE}||${ts}|${nonce}`;
    } else {
      return json(404, { error: 'not_found' });
    }
    if (!sameHex(hmac(conn.signingKey, message), h('X-OnCharge-Scanner-Signature'))) return json(401, { error: 'unauthorized' });
    if (!(await nonces.claim(nonce, 600))) return json(401, { error: 'unauthorized' }); // replay

    if (endpoint === 'content') {
      const cursor = Math.max(0, parseInt(url.searchParams.get('cursor') ?? '0', 10) || 0);
      const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit') ?? '50', 10) || 50));
      const page = await options.listItems({ cursor, limit });
      return json(200, { plugin_version: VERSION, site: options.site, items: page.items, next_cursor: page.nextCursor ?? null, truncated: Boolean(page.truncated) });
    }

    const r = options.reviewerAccess ? await options.reviewerAccess() : {};
    const status = {
      host: options.host,
      ready: Boolean(r.accountExists && r.canViewCatalog && r.ownerConfirmed),
      account_exists: Boolean(r.accountExists),
      can_view_catalog: Boolean(r.canViewCatalog),
      owner_confirmed: Boolean(r.ownerConfirmed),
      checked_at: Math.floor(Date.now() / 1000),
      nonce,
    };
    return json(200, { ...status, signature: reviewerStatusSignature(conn.signingKey, status) });
  };
}
```

## With the Node SDK

```ts title="Any framework"
import { createComplianceFeed } from '@oncharge/node';

const feed = createComplianceFeed({
  connectionCode: process.env.ONCHARGE_COMPLIANCE_CODE,
  host: 'shop.example.com',
  site: { name: 'Example Research Supply', home_url: 'https://shop.example.com/', terms_page_url: 'https://shop.example.com/terms' },
  listItems: async ({ cursor, limit }) => loadPublishedCatalog(cursor, limit), // → { items, nextCursor, truncated? }
  reviewerAccess: async () => ({ accountExists: true, canViewCatalog: true, ownerConfirmed: true }),
});

// feed.handle(request: Request): Promise<Response>
```

### Next.js

```ts title="app/.well-known/oncharge-compliance/[route]/route.ts"
import { createComplianceFeedRoute } from '@oncharge/node/next';

export const dynamic = 'force-dynamic';

export const { GET } = createComplianceFeedRoute({
  connectionCode: process.env.ONCHARGE_COMPLIANCE_CODE,
  host: 'shop.example.com',
  site: { name: 'Example Research Supply', home_url: 'https://shop.example.com/' },
  listItems: async ({ cursor, limit }) => loadPublishedCatalog(cursor, limit), // → { items, nextCursor, truncated? }
});
```

> **Coming soon.** `@oncharge/node` is not yet on npm. Until it is, use the reference implementation above: in Next.js, `export async function GET(request) { return handle(request); }` in the same route file.

## Content rules

The feed exists so OnCharge sees exactly what your buyers see. It must be read-only and must not hide, rewrite or add content for OnCharge. The scan checks your product pages, documents and policies against the RUO programme rules, for example: only approved products, original and accurate certificates of analysis (COAs), and product descriptions without human-use or health-benefit claims. Your onboarding contact can share the full rule list.
