# Firme e vettori di test

> **Risposta.** KRIN firma ogni messaggio tra il tuo server e KRIN con HMAC-SHA256: il link della bacheca che il tuo server crea per un utente e il postback di ricompensa che KRIN invia al tuo server. Ognuno firma una stringa canonica fissa con un timestamp, e ognuno ha un vettore di test per verificare il tuo codice prima di andare in produzione.

Questi sono i formati che usa il codice di KRIN. Ogni firma di questa pagina viene verificata con i vettori di test della specifica API di KRIN a ogni build della documentazione, e il codice qui sotto li supera tutti.

| Messaggio | Chi firma | Chi verifica | Segreto | Finestra temporale |
|---|---|---|---|---|
| [Link firmato della bacheca](#link-firmato-della-bacheca) | il tuo server | KRIN | segreto di lancio del posizionamento | 5 minuti, nonce monouso |
| [Postback di ricompensa](#postback-di-ricompensa) | KRIN | il tuo server | segreto di postback del posizionamento | 300 secondi |

Regole per ogni messaggio firmato:

- La firma è l'hex minuscolo di HMAC-SHA256 su una stringa canonica. Le righe sono unite da `\n` (un a capo), senza a capo finale.
- Confronta le firme in tempo costante.
- I segreti restano sul tuo server. Non inserirne mai uno in un browser, in un'app o in un URL condiviso.
- Durante una rotazione, il segreto vecchio e quello nuovo funzionano entrambi per il periodo di tolleranza che hai scelto, poi solo quello nuovo.

## Link firmato della bacheca

Il tuo server crea il link che un utente apre per arrivare all'offerwall: `https://wall.krin.io/w` con `placement`, `user_id`, `ts` (secondi Unix), un `nonce` monouso (da 16 a 128 caratteri) e `sig`.

```text
krin-launch-v1
{placement}
{user_id}
{ts}
{nonce}
{sub_ids}
```

`{sub_ids}` è vuoto se non passi sub-id di tracciamento (fino a 5). Altrimenti contiene le chiavi ordinate, `key=value` unite da `&`, con percent-encoding secondo RFC 3986 (solo `A-Z a-z 0-9 - . _ ~` restano invariati).

**Vettore di test.** Segreto di lancio `kls_test_1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d`, posizionamento `plc_01kbmz6v7r1s0e5d4c3b2a1z0y`, utente `player-1042`, ts `1764867600`, nonce `n0nce-7f3a9c2e1b4d`, sub-id `s1=spring` e `s2=tiktok`:

```text
sig = 2b9e27a873a2d1da412af2d1d4a794ebc3f7e07f5a511117cc6cf494bf7b3800
```

## Postback di ricompensa

KRIN comunica al tuo server di accreditare o stornare la ricompensa di un utente. Invia uno di due formati, entrambi firmati con il segreto di postback del posizionamento.

**POST JSON.** L'header è `X-Krin-Signature: t=<unix>,v1=<hex>`, e

```text
v1 = hex(HMAC-SHA256(postback_secret, "<t>.<raw body>"))
```

Usa i byte grezzi ricevuti, prima di analizzare il JSON. Durante una rotazione del segreto l'header contiene due valori `v1` (`t=...,v1=<new>,v1=<old>`), e può corrispondere l'uno o l'altro.

**Modello di URL GET.** `sig` copre questi valori esattamente come risultano dopo la decodifica dell'URL:

```text
krin-pb-v2
{ts}
{conversion_id}
{kind}
{user_id}
{reward}
{payout_micros}
{test}
```

`{test}` è `0` o `1`, e KRIN rifiuta un modello che non lo contenga. Un messaggio con `test` = `1` è un test: rispondi 2xx e non accreditarlo mai.

Rifiuta entrambi i formati quando `t` o `ts` si discosta di oltre 300 secondi dal tuo orologio.

**Vettori di test.** Segreto di postback `kps_test_5f2b9c1d8e7a4b3c2d1e0f9a8b7c6d5e`, `t = ts = 1764867600`. Corpo del POST (byte esatti, una riga):

```json
{"kind":"credit","conversion_id":"cnv_01kbnkrpg0fgz9y6hb7h6nwvvg","click_id":"clk_01kbnkrnzv2c4t3bq8xyn9w7fe","user_id":"player-1042","placement_id":"plc_01kbmz6v7r1s0e5d4c3b2a1z0y","offer_id":"ofr_01kbmy9x8w7v6t5s4r3q2p1n0m","event_key":"level_10","event_name":"Reach level 10","payout_micros":412500,"payout_usd":"0.4125","reward":"412","currency":"Gems","status":"approved","reason_code":null,"ip":null,"country":"US","ts":1764867600,"test":false}
```

| Verifica | Risultato atteso |
|---|---|
| POST `v1` | `d2ac88178d4693b9a2a0382a66aada97a4ec9711ba44e6cd2961c34a0fb525cc` |
| GET `sig` per la stessa conversione | `53493e91b788502054cef2f461a753cbb08ced30af9972e3dcd5a4c56d85a555` |
| GET `sig`, stessa conversione con `test` = `1` | `84e8afb4c9eb9c8afb186a0b9a146c85ad9170ef131d89c4637b2572719f04b6` |
| lo stesso corpo con un byte modificato | deve fallire |
| lo stesso messaggio verificato 301 secondi dopo `t` | deve fallire |

## Il codice

Un file per linguaggio con le funzioni descritte in questa pagina: firmare un link della bacheca, verificare un postback POST e verificare un postback GET. Copia quello che ti serve oppure scaricalo.

```js
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";

// RFC 3986: only A-Z a-z 0-9 - . _ ~ stay as they are.
const enc = (s) =>
  encodeURIComponent(s).replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());

export function signLaunchUrl(secret, { placement, userId, subIds = {} },
    ts = Math.floor(Date.now() / 1000), nonce = randomBytes(16).toString("hex")) {
  const keys = Object.keys(subIds).sort();
  const sub = keys.map((k) => `${enc(k)}=${enc(subIds[k])}`).join("&");
  const message = ["krin-launch-v1", placement, userId, String(ts), nonce, sub].join("\n");
  const sig = createHmac("sha256", secret).update(message).digest("hex");
  const query = new URLSearchParams({ placement, user_id: userId, ts: String(ts), nonce, sig });
  for (const k of keys) query.append(`sub_ids[${k}]`, subIds[k]);
  return { url: `https://wall.krin.io/w?${query}`, sig };
}

const same = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));

// POST: header "t=<unix>,v1=<hex>" (two v1 values during a secret rotation).
// rawBody: the exact bytes KRIN sent. secrets: [current] or [new, old] while you rotate.
export function verifyPostbackPost(rawBody, header, secrets, now = Math.floor(Date.now() / 1000)) {
  let t = null;
  const sigs = [];
  for (const part of header.split(",")) {
    const [k, v = ""] = part.trim().split("=", 2);
    if (k === "t") t = v;
    else if (k === "v1") sigs.push(v);
  }
  if (!/^\d+$/.test(t ?? "") || Math.abs(now - Number(t)) > 300) return false;
  return secrets.some((secret) => {
    const expected = createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest("hex");
    return sigs.some((v) => same(v, expected));
  });
}

// GET: the decoded query values of the signed macros (krin-pb-v2; test is "0" or "1").
// A true result with q.test === "1" is a test postback: never credit it.
export function verifyPostbackGet(q, secrets, now = Math.floor(Date.now() / 1000)) {
  if (!/^\d+$/.test(q.ts ?? "") || Math.abs(now - Number(q.ts)) > 300) return false;
  if (q.test !== "0" && q.test !== "1") return false;
  const message = ["krin-pb-v2", q.ts, q.conversion_id, q.kind, q.user_id, q.reward, q.payout_micros, q.test].join("\n");
  return secrets.some((secret) =>
    same(String(q.sig ?? ""), createHmac("sha256", secret).update(message).digest("hex")));
}

// Advertiser S2S: sign the conversion you send to t.krin.io (postbacks.md 4.1, signature v2).
// The signature covers the request exactly as sent: method, host, path and the query without sig.
export function signInbound(secret, { offerKey, clickId, event, txnId = "" }, ts = Math.floor(Date.now() / 1000)) {
  const host = "t.krin.io";
  const path = `/pb/${encodeURIComponent(offerKey)}`;
  const params = new URLSearchParams({ click_id: clickId, event });
  if (txnId) params.set("txn_id", txnId);
  params.set("ts", String(ts));
  const query = params.toString();
  const sig = createHmac("sha256", secret).update(["krin-in-v2", "GET", host, path, query].join("\n")).digest("hex");
  return { url: `https://${host}${path}?${query}&sig=${sig}`, sig };
}
```

```php
<?php
// Sign a wall launch URL (sdk.md 2.1).
function krin_sign_launch_url(string $secret, string $placement, string $userId, array $subIds = [],
                              ?int $ts = null, ?string $nonce = null): string {
    ksort($subIds, SORT_STRING);
    $sub = implode('&', array_map(
        fn ($k) => rawurlencode((string) $k) . '=' . rawurlencode((string) $subIds[$k]),
        array_keys($subIds)
    ));
    $ts = (string) ($ts ?? time());
    $nonce ??= bin2hex(random_bytes(16));
    $sig = hash_hmac('sha256', implode("\n", ['krin-launch-v1', $placement, $userId, $ts, $nonce, $sub]), $secret);
    $query = ['placement' => $placement, 'user_id' => $userId, 'ts' => $ts, 'nonce' => $nonce, 'sig' => $sig];
    foreach ($subIds as $k => $v) {
        $query["sub_ids[$k]"] = $v;
    }
    return 'https://wall.krin.io/w?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986);
}

// Verify a POST reward postback. $rawBody = file_get_contents('php://input').
function krin_verify_postback_post(string $rawBody, string $header, array $secrets, ?int $now = null): bool {
    $now ??= time();
    $t = null;
    $sigs = [];
    foreach (explode(',', $header) as $part) {
        [$k, $v] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($k === 't') { $t = $v; } elseif ($k === 'v1') { $sigs[] = $v; }
    }
    if ($t === null || !ctype_digit($t) || abs($now - (int) $t) > 300) {
        return false;
    }
    foreach ($secrets as $secret) {
        $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
        foreach ($sigs as $v) {
            if (hash_equals($expected, $v)) {
                return true;
            }
        }
    }
    return false;
}

// Verify a GET reward postback (krin-pb-v2). $q = $_GET (already decoded).
// A true result with $q['test'] === '1' is a test postback: never credit it.
function krin_verify_postback_get(array $q, array $secrets, ?int $now = null): bool {
    $now ??= time();
    $ts = (string) ($q['ts'] ?? '');
    if (!ctype_digit($ts) || abs($now - (int) $ts) > 300) {
        return false;
    }
    $test = (string) ($q['test'] ?? '');
    if ($test !== '0' && $test !== '1') {
        return false;
    }
    $message = implode("\n", ['krin-pb-v2', $ts, $q['conversion_id'] ?? '', $q['kind'] ?? '',
        $q['user_id'] ?? '', $q['reward'] ?? '', $q['payout_micros'] ?? '', $test]);
    foreach ($secrets as $secret) {
        if (hash_equals(hash_hmac('sha256', $message, $secret), (string) ($q['sig'] ?? ''))) {
            return true;
        }
    }
    return false;
}

// Advertiser S2S: sign the conversion you send to t.krin.io (postbacks.md 4.1, signature v2).
// The signature covers the request exactly as sent: method, host, path and the query without sig.
function krin_sign_inbound(string $secret, string $offerKey, string $clickId, string $event,
                           string $txnId = '', ?int $ts = null): string {
    $host = 't.krin.io';
    $path = '/pb/' . rawurlencode($offerKey);
    $params = ['click_id' => $clickId, 'event' => $event];
    if ($txnId !== '') {
        $params['txn_id'] = $txnId;
    }
    $params['ts'] = (string) ($ts ?? time());
    $query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
    $sig = hash_hmac('sha256', implode("\n", ['krin-in-v2', 'GET', $host, $path, $query]), $secret);
    return "https://{$host}{$path}?{$query}&sig={$sig}";
}
```

```python
import hashlib
import hmac
import secrets as _secrets
import time
from urllib.parse import quote, urlencode

def _hex(secret: str, message: bytes) -> str:
    return hmac.new(secret.encode(), message, hashlib.sha256).hexdigest()

def sign_launch_url(secret, placement, user_id, sub_ids=None, ts=None, nonce=None):
    """Signed wall launch URL (sdk.md 2.1)."""
    sub_ids = sub_ids or {}
    keys = sorted(sub_ids)
    sub = "&".join(f"{quote(k, safe='')}={quote(sub_ids[k], safe='')}" for k in keys)
    ts = str(int(time.time()) if ts is None else ts)
    nonce = nonce or _secrets.token_hex(16)
    message = "\n".join(["krin-launch-v1", placement, user_id, ts, nonce, sub])
    sig = _hex(secret, message.encode())
    params = [("placement", placement), ("user_id", user_id), ("ts", ts), ("nonce", nonce), ("sig", sig)]
    params += [(f"sub_ids[{k}]", sub_ids[k]) for k in keys]
    return "https://wall.krin.io/w?" + urlencode(params, quote_via=quote)

def verify_postback_post(raw_body: bytes, header: str, secrets: list, now=None) -> bool:
    """POST reward postback: raw_body is the exact bytes KRIN sent."""
    now = int(time.time()) if now is None else now
    t, sigs = None, []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t":
            t = value
        elif key == "v1":
            sigs.append(value)
    if not t or not t.isdigit() or abs(now - int(t)) > 300:
        return False
    for secret in secrets:
        expected = _hex(secret, t.encode() + b"." + raw_body)
        if any(hmac.compare_digest(expected, v) for v in sigs):
            return True
    return False

def verify_postback_get(q: dict, secrets: list, now=None) -> bool:
    """GET reward postback (krin-pb-v2): q holds the decoded query values.
    A True result with q["test"] == "1" is a test postback: never credit it."""
    now = int(time.time()) if now is None else now
    ts = str(q.get("ts", ""))
    if not ts.isdigit() or abs(now - int(ts)) > 300:
        return False
    test = str(q.get("test", ""))
    if test not in ("0", "1"):
        return False
    message = "\n".join(["krin-pb-v2", ts] + [str(q.get(k, "")) for k in
                         ("conversion_id", "kind", "user_id", "reward", "payout_micros")] + [test])
    return any(hmac.compare_digest(_hex(s, message.encode()), str(q.get("sig", ""))) for s in secrets)

def sign_inbound(secret, offer_key, click_id, event, txn_id="", ts=None):
    """Advertiser S2S conversion to t.krin.io (postbacks.md 4.1, signature v2).
    The signature covers the request exactly as sent: method, host, path and the query without sig."""
    host = "t.krin.io"
    path = "/pb/" + quote(offer_key, safe="")
    params = [("click_id", click_id), ("event", event)]
    if txn_id:
        params.append(("txn_id", txn_id))
    params.append(("ts", str(int(time.time()) if ts is None else ts)))
    query = urlencode(params, quote_via=quote)
    sig = _hex(secret, "\n".join(["krin-in-v2", "GET", host, path, query]).encode())
    return f"https://{host}{path}?{query}&sig={sig}"
```

Download: [krin.mjs](https://docs.krin.io/code/krin.mjs) · [krin.php](https://docs.krin.io/code/krin.php) · [krin.py](https://docs.krin.io/code/krin.py) · [test-vectors.json](https://docs.krin.io/postbacks/test-vectors.json)

## FAQ

**Perché la mia verifica POST fallisce mentre quella GET passa?**
Probabilmente stai calcolando l'HMAC sul JSON già analizzato e riserializzato. Calcolalo sui byte grezzi, esattamente come sono arrivati; qualsiasi modifica agli spazi o all'ordine delle chiavi cambia il risultato.

**La mia firma corrisponde al vettore, ma KRIN rifiuta comunque il mio link della bacheca. Perché?**
Controlla l'orario e il nonce. `ts` deve discostarsi al massimo di 5 minuti dall'orologio di KRIN e ogni nonce funziona una sola volta, quindi firma un link nuovo ogni volta che un utente apre la bacheca.

**Quali caratteri restano non codificati nei sub-id?**
Solo `A-Z a-z 0-9 - . _ ~` (RFC 3986). Codifica tutto il resto come `%XX` con hex maiuscolo. In JavaScript, `encodeURIComponent` lascia invariati `! ' ( ) *`, per questo il codice qui sopra codifica anche quelli.

**Posso usare un solo segreto sia per il link della bacheca sia per il postback?**
No. Ogni posizionamento ha il proprio segreto di lancio e il proprio segreto di postback, e un'offerta ha il proprio segreto in entrata. Tienili separati, così la rotazione di uno non rompe mai gli altri.

