# Link4Sync integration skill

Use this file to connect an application to Link4Sync, a hosted event endpoint service. A Link4Sync **topic** receives JSON events over HTTPS, HTTP, MQTT, or MQTTS.

Never hard-code credentials. Read them from environment variables and never print them in logs.

## 1. What the user sets up in the dashboard

Ask the user to do this in https://www.link4sync.com/dashboard/topics and send you the values. You cannot do it for them.

1. Turn on a connection under **Connection status**. On Basic, select the shared HTTP, HTTPS, or MQTT connection. On Premium, switch the owned endpoint on.
2. Create a topic with **Create topic**. Names use lowercase letters, digits, and hyphens.
3. On the topic card, choose a protocol and copy:
   - the **connection URL**;
   - the **topic ID** (for example `u0123456789abcdef-orders`), needed for MQTT.
4. Choose how to authenticate:
   - **OAuth** (HTTPS only, in this guide): the Link4Sync account email and password.
   - **SCRAM**: reveal the **Producer** credential on the topic card. Each protocol has its own producer and consumer credentials, and they can be rotated in the dashboard.

Use these environment variables:

| Variable                                   | Value                               |
| ------------------------------------------ | ----------------------------------- |
| `LINK4SYNC_URL`                            | Connection URL from the topic card  |
| `LINK4SYNC_TOPIC_ID`                       | Topic ID from the topic card (MQTT) |
| `LINK4SYNC_EMAIL`, `LINK4SYNC_PASSWORD`    | Account login (OAuth)               |
| `LINK4SYNC_USERNAME`, `LINK4SYNC_PASSWORD` | Producer SCRAM credential (SCRAM)   |

## 2. Endpoints

| Protocol            | Basic (shared)                                    | Premium (owned)                              |
| ------------------- | ------------------------------------------------- | -------------------------------------------- |
| HTTPS               | `https://<endpoint>.link4sync.com/<topic-id>`     | same pattern, own endpoint                   |
| HTTP (unencrypted)  | `http://<endpoint>-http.link4sync.com/<topic-id>` | same pattern, own endpoint                   |
| MQTT over WebSocket | `wss://mqtt.link4sync.com/mqtt`                   | `wss://<instance>-mqtt.link4sync.com/mqtt`   |
| MQTTS               | `mqtts://mqtt.link4sync.com:8883`                 | `mqtts://<instance>-mqtts.link4sync.com:443` |

Always use the exact URL from the topic card. Prefer HTTPS or MQTTS. The first request after a connection is switched on can take longer while it starts.

## 3. Publish over HTTPS with OAuth

Get a short-lived access token with the account login, then POST JSON with it. A successful publish returns **202 Accepted**.

```sh
TOKEN=$(curl -s https://auth.link4sync.com/realms/link4sync/protocol/openid-connect/token \
  -d grant_type=password -d client_id=kafka-connect-access \
  --data-urlencode "username=$LINK4SYNC_EMAIL" \
  --data-urlencode "password=$LINK4SYNC_PASSWORD" | jq -r .access_token)

curl -i -X POST "$LINK4SYNC_URL" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"temperature": 21.5}'
```

The token expires. Request a new one when you get `401`.

## 4. Publish over HTTPS with SCRAM-SHA-256

The ingress uses HTTP SCRAM authentication (RFC 7804) with SCRAM-SHA-256 (RFC 5802/7677). Send the same JSON body in both requests:

1. 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. 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>">`; verify the signature.

Reference implementation for Node.js 18+:

```js
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');
  }
}
```

## 5. Publish over MQTT 5 with SCRAM-SHA-512

MQTT uses MQTT 5 enhanced authentication. Use a client library that supports the MQTT 5 `AUTH` packet (for example MQTT.js `handleAuth`). Authentication data is the raw UTF-8 SCRAM message, not base64.

1. **CONNECT**: protocol version 5, a client ID that is unique for every session, username = producer SCRAM username, no password, property _Authentication Method_ = `SCRAM-SHA-512`, property _Authentication Data_ = `n,,n=<username>,r=<client-nonce>`.
2. The broker replies with **AUTH**, reason code `0x18` (continue), _Authentication Data_ = server-first (`r=…,s=…,i=…`).
3. Send **AUTH**, reason code `0x18`, _Authentication Method_ = `SCRAM-SHA-512`, _Authentication Data_ = client-final (`c=biws,r=<server-nonce>,p=<proof>`). Compute it as in section 4 with SHA-512 and a 64-byte PBKDF2 key.
4. The broker replies with **CONNACK** reason code `0x00`.
5. **PUBLISH** a JSON payload with QoS 1 to the MQTT topic ID from the topic card and wait for **PUBACK**.

## 6. Limits and behaviour

- Payloads are JSON values.
- Topics keep messages for seven days.
- Basic: one shared connection, up to 25 msg/s and 5 Mbit/s. Premium: own hostnames, up to 500 msg/s and 50 Mbit/s. The dashboard subscription page shows the current limits.
- After a credential rotation, the old producer password stops working. Update `LINK4SYNC_PASSWORD`.

## 7. Reading messages

The user can open the topic in the dashboard to see the latest messages, which is the quickest way to confirm a publish. A public API for reading messages is not documented here; for programmatic reads, contact support@link4sync.com.

## 8. Troubleshooting

| Result                                          | Meaning                                                          |
| ----------------------------------------------- | ---------------------------------------------------------------- |
| `202`                                           | Accepted.                                                        |
| `401` on the second SCRAM request               | Wrong username or password, or the credential was rotated.       |
| `401` with OAuth                                | The token expired or the account login is wrong.                 |
| `404`                                           | The URL or topic ID is wrong, or the connection is switched off. |
| MQTT CONNACK with a reason code ≥ `0x80`        | Authentication failed. Check the producer credential.            |
| MQTT session drops when another client connects | Two sessions share a client ID. Give each session its own.       |
