# Firmas y vectores de prueba

> **Respuesta.** KRIN firma cada mensaje entre tu servidor y KRIN con HMAC-SHA256: el enlace de muro que tu servidor crea para un usuario y el postback de recompensa que KRIN envía a tu servidor. Cada uno firma una cadena canónica fija con una marca de tiempo, y cada uno tiene un vector de prueba para comprobar tu código antes de salir a producción.

Estos son los formatos que usa el código de KRIN. Cada firma de esta página se comprueba con los vectores de prueba de la especificación de la API de KRIN cada vez que se compila la documentación, y el código de abajo los supera todos.

| Mensaje | Quién firma | Quién comprueba | Secreto | Ventana de tiempo |
|---|---|---|---|---|
| [Enlace de muro firmado](#enlace-de-muro-firmado) | tu servidor | KRIN | secreto de lanzamiento de la ubicación | 5 minutos, nonce de un solo uso |
| [Postback de recompensa](#postback-de-recompensa) | KRIN | tu servidor | secreto de postback de la ubicación | 300 segundos |

Reglas para cada mensaje firmado:

- La firma es el hex en minúsculas de HMAC-SHA256 sobre una cadena canónica. Las líneas se unen con `\n` (un salto de línea), sin salto de línea al final.
- Compara las firmas en tiempo constante.
- Los secretos se quedan en tu servidor. Nunca incluyas uno en un navegador, una app o una URL compartida.
- Durante una rotación, el secreto antiguo y el nuevo funcionan durante el periodo de gracia que elegiste; después, solo el nuevo.

## Enlace de muro firmado

Tu servidor crea el enlace que un usuario abre para llegar al offerwall: `https://wall.krin.io/w` con `placement`, `user_id`, `ts` (segundos Unix), un `nonce` de un solo uso (de 16 a 128 caracteres) y `sig`.

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

`{sub_ids}` está vacío si no pasas sub-ids de tracking (hasta 5). Si los pasas, son las claves ordenadas, `key=value` unidos con `&`, codificados en porcentaje según RFC 3986 (solo `A-Z a-z 0-9 - . _ ~` se quedan como están).

**Vector de prueba.** Secreto de lanzamiento `kls_test_1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d`, ubicación `plc_01kbmz6v7r1s0e5d4c3b2a1z0y`, usuario `player-1042`, ts `1764867600`, nonce `n0nce-7f3a9c2e1b4d`, sub-ids `s1=spring` y `s2=tiktok`:

```text
sig = 2b9e27a873a2d1da412af2d1d4a794ebc3f7e07f5a511117cc6cf494bf7b3800
```

## Postback de recompensa

KRIN le indica a tu servidor que acredite o revierta la recompensa de un usuario. Envía uno de dos formatos, ambos firmados con el secreto de postback de la ubicación.

**POST JSON.** La cabecera es `X-Krin-Signature: t=<unix>,v1=<hex>`, y

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

Usa los bytes sin procesar que recibiste, antes de analizar el JSON. Durante una rotación de secreto, la cabecera lleva dos valores `v1` (`t=...,v1=<new>,v1=<old>`), y cualquiera de los dos puede coincidir.

**Plantilla de URL GET.** `sig` cubre estos valores exactamente como quedan tras decodificar la URL:

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

`{test}` es `0` o `1`, y KRIN rechaza una plantilla que no lo incluya. Un mensaje con `test` = `1` es una prueba: responde 2xx y nunca lo acredites.

Rechaza cualquiera de los dos formatos cuando `t` o `ts` se aleje más de 300 segundos de tu reloj.

**Vectores de prueba.** Secreto de postback `kps_test_5f2b9c1d8e7a4b3c2d1e0f9a8b7c6d5e`, `t = ts = 1764867600`. Cuerpo del POST (bytes exactos, una línea):

```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}
```

| Comprobación | Resultado esperado |
|---|---|
| POST `v1` | `d2ac88178d4693b9a2a0382a66aada97a4ec9711ba44e6cd2961c34a0fb525cc` |
| GET `sig` para la misma conversión | `53493e91b788502054cef2f461a753cbb08ced30af9972e3dcd5a4c56d85a555` |
| GET `sig`, la misma conversión con `test` = `1` | `84e8afb4c9eb9c8afb186a0b9a146c85ad9170ef131d89c4637b2572719f04b6` |
| el mismo cuerpo con un byte cambiado | debe fallar |
| el mismo mensaje comprobado 301 segundos después de `t` | debe fallar |

## El código

Un archivo por lenguaje con las funciones que describe esta página: firmar un enlace de muro, comprobar un postback POST y comprobar un postback GET. Copia el que necesites o descárgalo.

```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}"
```

Descargas: [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

**¿Por qué falla mi comprobación POST si la comprobación GET funciona?**
Probablemente estás calculando el HMAC sobre el JSON ya analizado y vuelto a serializar. Calcúlalo sobre los bytes sin procesar, exactamente como llegaron; cualquier cambio en los espacios o en el orden de las claves cambia el resultado.

**Mi firma coincide con el vector, pero KRIN sigue rechazando mi enlace de muro. ¿Por qué?**
Revisa la hora y el nonce. `ts` debe estar a menos de 5 minutos del reloj de KRIN, y cada nonce funciona una sola vez, así que firma un enlace nuevo cada vez que un usuario abra el muro.

**¿Qué caracteres quedan sin codificar en los sub-ids?**
Solo `A-Z a-z 0-9 - . _ ~` (RFC 3986). Codifica todo lo demás como `%XX` con hex en mayúsculas. En JavaScript, `encodeURIComponent` deja `! ' ( ) *` sin codificar, por eso el código de arriba también los codifica.

**¿Puedo usar un solo secreto para el enlace de muro y el postback?**
No. Cada ubicación tiene su propio secreto de lanzamiento y su propio secreto de postback, y una oferta tiene su propio secreto de entrada. Mantenlos separados para que rotar uno nunca rompa los demás.

