Kroos Developers
Kroos Developers › Website chatbot

End-user tokens

Sign short-lived HS256 tokens on your server so the chatbot can give signed-in customers their own segment, limits and features.

Without a token, every visitor is in the anonymous segment. A token tells Kroos that this is a known customer and which segment they belong to.

1. Get the signing secret#

bash
curl -s -X POST https://kroos.ai/api/tenant/enduser-secret -H "authorization: Bearer kroos_sk_..."

The secret is returned once. Calling it again rotates the secret (existing tokens stop working). Store it with your other server secrets.

2. Token format#

A standard JWT signed with HS256 only.

ClaimRequiredRules
subyesA stable, pseudonymous ID for the customer (for example a hash of your user ID). Never an email. Up to 128 characters.
segmentnoA segment defined in your usage policy (default customer).
audyesYour organization ID (shown in the console and in GET /api/tenant).
expyesExpiry in Unix seconds, at most one hour from now.
ctxnoA small JSON object (at most 2 KB) about this person that the chatbot may use to guide them: first name, plan, role, renewal date. One level of nesting; arrays become lists. For larger or live data, use a context provider.

3. Sign it#

jsNode.js
import { createHmac, createHash } from "node:crypto";

const b64 = (s) => Buffer.from(s).toString("base64url");
export function kroosToken(userId, segment = "customer") {
  const header = b64(JSON.stringify({ alg: "HS256", typ: "JWT" }));
  const payload = b64(JSON.stringify({
    sub: createHash("sha256").update(`my-site:${userId}`).digest("hex").slice(0, 32),
    segment,
    aud: process.env.KROOS_ORG_ID,
    exp: Math.floor(Date.now() / 1000) + 3600,
  }));
  const sig = createHmac("sha256", process.env.KROOS_ENDUSER_SECRET).update(`${header}.${payload}`).digest("base64url");
  return `${header}.${payload}.${sig}`;
}
pythonPython
import base64, hashlib, hmac, json, os, time

def b64(b: bytes) -> str:
    return base64.urlsafe_b64encode(b).rstrip(b"=").decode()

def kroos_token(user_id: str, segment: str = "customer") -> str:
    header = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
    payload = b64(json.dumps({
        "sub": hashlib.sha256(f"my-site:{user_id}".encode()).hexdigest()[:32],
        "segment": segment,
        "aud": os.environ["KROOS_ORG_ID"],
        "exp": int(time.time()) + 3600,
    }).encode())
    sig = hmac.new(os.environ["KROOS_ENDUSER_SECRET"].encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest()
    return f"{header}.{payload}.{b64(sig)}"
phpPHP
function kroos_token(string $userId, string $segment = 'customer'): string {
  $b64 = fn($s) => rtrim(strtr(base64_encode($s), '+/', '-_'), '=');
  $h = $b64(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
  $p = $b64(json_encode([
    'sub' => substr(hash('sha256', 'my-site:' . $userId), 0, 32),
    'segment' => $segment,
    'aud' => getenv('KROOS_ORG_ID'),
    'exp' => time() + 3600,
  ]));
  $s = $b64(hash_hmac('sha256', "$h.$p", getenv('KROOS_ENDUSER_SECRET'), true));
  return "$h.$p.$s";
}

4. Use it#

  • In the widget: data-kroos-user-token="…".
  • In API calls: add "userToken": "…" to the body of any /api/public/v1/* request.

Live context for signed-in users#

For answers from your own database (a customer's orders, a member's bookings, an admin's numbers for the week), connect a context provider: an https endpoint you run. For every message from a signed-in user, Kroos sends it a signed request, and you reply with what this person may see.

bash
curl -s -X PUT https://kroos.ai/api/tenant/context-provider -H "authorization: Bearer kroos_sk_..." \
  -H "content-type: application/json" -d '{"url":"https://example.com/api/kroos/context"}'

The response holds a signing secret, shown once. Connecting or removing a provider needs a verified owner. GET /api/tenant/context-provider shows the current host; DELETE /api/tenant/context-provider disconnects it.

Kroos sends:

json
{ "type": "context.request", "tenant": "org_…", "user": { "sub": "…", "segment": "admin" }, "surface": "web", "question": "How many orders this week?", "at": "2026-12-02T15:04:05.000Z" }

with the header Kroos-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "t.body">, the same scheme as webhooks. Verify it, look the user up by sub, and reply within 1.5 seconds:

json
{ "facts": [{ "label": "Orders this week", "value": "128" }, { "label": "Open tickets", "value": "3" }], "text": "Optional short notes, up to 6,000 characters." }
  • Scope it in your code: a customer gets their own records; an admin segment gets business figures. Kroos holds no database credentials.
  • Up to 40 facts. A slow, failing or empty provider never blocks the answer: the chatbot answers from your published knowledge instead.
  • Context is private to that person's turn: never cached, never added to your knowledge, never used for learning, never shown to anyone else.
  • Anonymous visitors never trigger a provider call.

Errors#

A bad token is rejected with 401 auth.enduser_token_invalid and a reason: malformed, only HS256 is accepted, bad signature, wrong audience, expired, lifetime longer than 1 hour, missing sub, ctx must be an object, ctx is larger than 2048 bytes, or this business hasn't enabled end-user tokens. A rejected token never falls back to anonymous silently.

Warning

Never sign tokens in the browser, and never put the signing secret in front-end code or Liquid templates. The CMS plugins sign on the server for you.

Last updated 2026-12-03