> ## Documentation Index
> Fetch the complete documentation index at: https://docs.link4sync.com/llms.txt
> Use this file to discover all available pages before exploring further.

# HTTP(S) with SCRAM

> Publish with the topic producer credential using HTTP SCRAM-SHA-256 authentication.

The HTTP and HTTPS ingress supports HTTP SCRAM authentication ([RFC 7804](https://www.rfc-editor.org/rfc/rfc7804)) with SCRAM-SHA-256 ([RFC 5802](https://www.rfc-editor.org/rfc/rfc5802), [RFC 7677](https://www.rfc-editor.org/rfc/rfc7677)). The password never crosses the network, and your client verifies the server's signature.

## Before you start

Reveal the **Producer** credential for HTTPS or HTTP on the topic card and set:

| Variable | Value |
| - | - |
| `LINK4SYNC_URL` | HTTPS or HTTP URL from the topic card |
| `LINK4SYNC_USERNAME` | Producer SCRAM username |
| `LINK4SYNC_PASSWORD` | Producer SCRAM password |

## The exchange

Send the same JSON body in both requests.

**1. Client-first request**

POST with `Authorization: SCRAM-SHA-256 data=<base64("n,,n=<username>,r=<client-nonce>")>`.

Expect `401` and `WWW-Authenticate: SCRAM-SHA-256 sid=<sid>, data=<base64 server-first>`.

**2. Client-final request**

Compute the client-final message (`c=biws,r=<server-nonce>,p=<proof>`) and POST with `Authorization: SCRAM-SHA-256 sid=<sid>,data=<base64 client-final>`.

Expect `202` and `Authentication-Info: sid=<sid>,data=<base64 "v=<server-signature>">`.

**3. Verify the server**

Compare the server signature with the one you compute. Reject the response if they differ.

## Reference implementation (Node.js 18+)

```js publish.mjs theme={null}
import { createHash, createHmac, pbkdf2Sync, randomBytes, timingSafeEqual } from 'node:crypto';

const url = process.env.LINK4SYNC_URL;
const username = process.env.LINK4SYNC_USERNAME;
const password = process.env.LINK4SYNC_PASSWORD;

const base64 = (text) => Buffer.from(text, 'utf8').toString('base64');
const fromBase64 = (text) => Buffer.from(text, 'base64').toString('utf8');
const scramAttributes = (text) =>
  Object.fromEntries(text.split(',').map((part) => [part[0], part.slice(2)]));
const authParams = (header) =>
  Object.fromEntries(
    header
      .replace(/^SCRAM-SHA-256\s+/i, '')
      .split(',')
      .map((part) => {
        const index = part.indexOf('=');
        return [
          part.slice(0, index).trim(),
          part
            .slice(index + 1)
            .trim()
            .replace(/^"|"$/g, ''),
        ];
      }),
  );

export async function publish(event) {
  const body = JSON.stringify(event);
  const headers = { 'Content-Type': 'application/json' };
  const nonce = randomBytes(18).toString('base64url');
  const user = username.replaceAll('=', '=3D').replaceAll(',', '=2C');
  const clientFirstBare = `n=${user},r=${nonce}`;

  const first = await fetch(url, {
    method: 'POST',
    redirect: 'manual',
    headers: { ...headers, Authorization: `SCRAM-SHA-256 data=${base64(`n,,${clientFirstBare}`)}` },
    body,
  });
  if (first.status !== 401) throw new Error(`Expected a SCRAM challenge, got ${first.status}`);
  const challenge = authParams(first.headers.get('www-authenticate') ?? '');
  const serverFirst = fromBase64(challenge.data);
  const { r, s, i } = scramAttributes(serverFirst);
  if (!r?.startsWith(nonce) || r.length <= nonce.length) throw new Error('Bad server nonce');

  const salted = pbkdf2Sync(password, Buffer.from(s, 'base64'), Number(i), 32, 'sha256');
  const clientKey = createHmac('sha256', salted).update('Client Key').digest();
  const storedKey = createHash('sha256').update(clientKey).digest();
  const withoutProof = `c=biws,r=${r}`;
  const authMessage = `${clientFirstBare},${serverFirst},${withoutProof}`;
  const signature = createHmac('sha256', storedKey).update(authMessage).digest();
  const proof = Buffer.from(clientKey.map((byte, index) => byte ^ signature[index]));

  const final = await fetch(url, {
    method: 'POST',
    redirect: 'manual',
    headers: {
      ...headers,
      Authorization: `SCRAM-SHA-256 sid=${challenge.sid},data=${base64(`${withoutProof},p=${proof.toString('base64')}`)}`,
    },
    body,
  });
  if (final.status !== 202) throw new Error(`Publish rejected with ${final.status}`);

  const serverKey = createHmac('sha256', salted).update('Server Key').digest();
  const expected = createHmac('sha256', serverKey).update(authMessage).digest();
  const info = authParams(final.headers.get('authentication-info') ?? '');
  const received = Buffer.from(scramAttributes(fromBase64(info.data ?? '')).v ?? '', 'base64');
  if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
    throw new Error('Server signature did not match');
  }
}
```

Call it with any JSON value:

```js theme={null}
await publish({ temperature: 21.5 });
```

> [!WARNING]
>
> After you rotate the producer credential, the old password stops working. Update
> `LINK4SYNC_PASSWORD`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.