> ## 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) con SCRAM

> Publica con la credencial de productor del topic usando autenticación HTTP SCRAM-SHA-256.

La entrada HTTP y HTTPS admite autenticación HTTP SCRAM ([RFC 7804](https://www.rfc-editor.org/rfc/rfc7804)) con SCRAM-SHA-256 ([RFC 5802](https://www.rfc-editor.org/rfc/rfc5802), [RFC 7677](https://www.rfc-editor.org/rfc/rfc7677)). La contraseña nunca cruza la red y tu cliente verifica la firma del servidor.

## Antes de empezar

Muestra la credencial de **productor** para HTTPS o HTTP en la tarjeta del topic y define:

| Variable | Valor |
| - | - |
| `LINK4SYNC_URL` | URL HTTPS o HTTP de la tarjeta del topic |
| `LINK4SYNC_USERNAME` | Usuario SCRAM de productor |
| `LINK4SYNC_PASSWORD` | Contraseña SCRAM de productor |

## El intercambio

Envía el mismo cuerpo JSON en ambas peticiones.

**1. Petición client-first**

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

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

**2. Petición client-final**

Calcula el mensaje client-final (`c=biws,r=<server-nonce>,p=<proof>`) y haz POST con `Authorization: SCRAM-SHA-256 sid=<sid>,data=<base64 client-final>`.

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

**3. Verifica el servidor**

Compara la firma del servidor con la que calculas tú. Rechaza la respuesta si no coinciden.

## Implementación de referencia (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');
  }
}
```

Llámala con cualquier valor JSON:

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

> [!WARNING]
>
> Tras rotar la credencial de productor, la contraseña anterior deja de funcionar. Actualiza
> `LINK4SYNC_PASSWORD`.


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