> ## Documentation Index
> Fetch the complete documentation index at: https://rollout.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Verify the context

> Check that each launch came from Rollout, hasn't expired and hasn't been used before.

Every time Rollout loads your app, it adds two query parameters to your app URL:

```
https://app.example.com/crm-panel?context=eyJjb250ZXh0Ijoi…&signature=5f2c…
```

| Parameter | What it is |
| - | - |
| `context` | The [context](https://rollout.com/docs/embedded-apps/context-fields.md) as JSON, encoded as URL-safe base64 **without padding** (RFC 4648 §5, as in JWTs). |
| `signature` | HMAC-SHA256 of the `context` string, exactly as it appears in the URL, keyed with your client secret, as lowercase hex. |

Anyone can put a `context` in your URL. Trust nothing in it until your server
has checked it:

1. **Signature.** Compute HMAC-SHA256 of the `context` parameter with your
   client secret, and compare it to `signature` in constant time.
2. **Decode.** Decode `context` from base64url, and parse the JSON.
3. **Expiry.** Refuse it once `x.exp`, in seconds since the epoch, has passed.
   Contexts are good for five minutes.
4. **Replay.** Refuse an `x.jti` you've already accepted, so a copied URL can't
   be opened again. Remember each one until its `x.exp`.

Do this on your server, never in the browser: the check needs your client
secret.

```ts Node theme={null}
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyContext(
  context: string | null,
  signature: string | null,
  secret: string,
) {
  if (!context || !signature) return null;

  // 1. Signature
  const expected = createHmac("sha256", secret).update(context).digest();
  const actual = Buffer.from(signature, "hex");
  if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
    return null;
  }

  // 2. Decode
  const decoded = JSON.parse(Buffer.from(context, "base64url").toString("utf8"));

  // 3. Expiry
  if (decoded.x.exp < Math.floor(Date.now() / 1000)) return null;

  // 4. Replay: store jti until exp, and fail if it's already there
  if (!rememberJti(decoded.x.jti, decoded.x.exp)) return null;

  return decoded;
}
```

```python Python theme={null}
import base64, hashlib, hmac, json, time

def verify_context(context: str | None, signature: str | None, secret: str):
    if not context or not signature:
        return None

    # 1. Signature
    expected = hmac.new(secret.encode(), context.encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected.encode(), signature.encode()):
        return None

    # 2. Decode (add back the padding Python's decoder needs)
    padded = context + "=" * (-len(context) % 4)
    decoded = json.loads(base64.urlsafe_b64decode(padded))

    # 3. Expiry
    if decoded["x"]["exp"] < time.time():
        return None

    # 4. Replay: store jti until exp, and fail if it's already there
    if not remember_jti(decoded["x"]["jti"], decoded["x"]["exp"]):
        return None

    return decoded
```

```ruby Ruby theme={null}
require "base64"
require "json"
require "openssl"

def verify_context(context, signature, secret)
  return nil if context.to_s.empty? || signature.to_s.empty?

  # 1. Signature
  expected = OpenSSL::HMAC.hexdigest("SHA256", secret, context)
  return nil unless OpenSSL.secure_compare(expected, signature)

  # 2. Decode
  decoded = JSON.parse(Base64.urlsafe_decode64(context))

  # 3. Expiry
  return nil if decoded["x"]["exp"] < Time.now.to_i

  # 4. Replay: store jti until exp, and fail if it's already there
  return nil unless remember_jti(decoded["x"]["jti"], decoded["x"]["exp"])

  decoded
end
```

```php PHP theme={null}
function verifyContext(?string $context, ?string $signature, string $secret): ?array
{
    if (!$context || !$signature) {
        return null;
    }

    // 1. Signature
    if (!hash_equals(hash_hmac('sha256', $context, $secret), $signature)) {
        return null;
    }

    // 2. Decode
    $decoded = json_decode(base64_decode(strtr($context, '-_', '+/')), true);

    // 3. Expiry
    if ($decoded['x']['exp'] < time()) {
        return null;
    }

    // 4. Replay: store jti until exp, and fail if it's already there
    if (!rememberJti($decoded['x']['jti'], $decoded['x']['exp'])) {
        return null;
    }

    return $decoded;
}
```

```go Go theme={null}
import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"time"
)

type Context struct {
	User struct {
		ID string `json:"id"`
	} `json:"user"`
	Crm struct {
		PersonID string `json:"personId"`
	} `json:"crm"`
	X struct {
		MarketplaceID string `json:"marketplaceId"`
		Exp           int64  `json:"exp"`
		Jti           string `json:"jti"`
		Preview       bool   `json:"preview"`
	} `json:"x"`
}

func verifyContext(context, signature, secret string) *Context {
	if context == "" || signature == "" {
		return nil
	}

	// 1. Signature
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(context))
	actual, err := hex.DecodeString(signature)
	if err != nil || !hmac.Equal(actual, mac.Sum(nil)) {
		return nil
	}

	// 2. Decode
	raw, err := base64.RawURLEncoding.DecodeString(context)
	if err != nil {
		return nil
	}
	var decoded Context
	if json.Unmarshal(raw, &decoded) != nil {
		return nil
	}

	// 3. Expiry
	if decoded.X.Exp < time.Now().Unix() {
		return nil
	}

	// 4. Replay: store jti until exp, and fail if it's already there
	if !rememberJti(decoded.X.Jti, decoded.X.Exp) {
		return nil
	}

	return &decoded
}
```

```java Java theme={null}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.Base64;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class ContextVerifier {
  private static final ObjectMapper JSON = new ObjectMapper();

  public static JsonNode verifyContext(String context, String signature, String secret)
      throws Exception {
    if (context == null || context.isEmpty() || signature == null || signature.isEmpty()) {
      return null;
    }

    // 1. Signature
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    byte[] expected = mac.doFinal(context.getBytes(StandardCharsets.UTF_8));
    byte[] actual;
    try {
      actual = HexFormat.of().parseHex(signature);
    } catch (IllegalArgumentException e) {
      return null;
    }
    if (!MessageDigest.isEqual(expected, actual)) {
      return null;
    }

    // 2. Decode
    JsonNode decoded = JSON.readTree(Base64.getUrlDecoder().decode(context));

    // 3. Expiry
    long exp = decoded.path("x").path("exp").asLong();
    if (exp < Instant.now().getEpochSecond()) {
      return null;
    }

    // 4. Replay: store jti until exp, and fail if it's already there
    if (!rememberJti(decoded.path("x").path("jti").asText(), exp)) {
      return null;
    }

    return decoded;
  }
}
```

```csharp C# theme={null}
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

public static class ContextVerifier
{
    public static JsonElement? VerifyContext(string? context, string? signature, string secret)
    {
        if (string.IsNullOrEmpty(context) || string.IsNullOrEmpty(signature)) return null;

        // 1. Signature
        var expected = HMACSHA256.HashData(
            Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes(context));
        byte[] actual;
        try { actual = Convert.FromHexString(signature); }
        catch (FormatException) { return null; }
        if (!CryptographicOperations.FixedTimeEquals(expected, actual)) return null;

        // 2. Decode (add back the padding .NET's decoder needs)
        var base64 = context.Replace('-', '+').Replace('_', '/');
        base64 = base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=');
        var decoded = JsonDocument.Parse(Convert.FromBase64String(base64)).RootElement;

        // 3. Expiry
        var x = decoded.GetProperty("x");
        var exp = x.GetProperty("exp").GetInt64();
        if (exp < DateTimeOffset.UtcNow.ToUnixTimeSeconds()) return null;

        // 4. Replay: store jti until exp, and fail if it's already there
        if (!RememberJti(x.GetProperty("jti").GetString()!, exp)) return null;

        return decoded;
    }
}
```

`rememberJti` is yours to write: a set in Redis with a time to live, or a
database table with a unique key, works. It returns `false` when the id is
already stored. In Java and C#, it's a static method on the same class.

> [!NOTE]
>
> The signature and the encoding are the same as Follow Up Boss's embedded apps.
> A check written for FUB works once it uses your Rollout secret. The expiry and
> replay checks are new, and recommended.

## Rotating your client secret

Contexts are signed only with your **Current secret**. When you rotate it from
the dashboard's **API** page, the new secret signs nothing until the rotation
completes: when you choose **Complete rotation**, or when the old secret is
retired.

To rotate without failing any launch:

1. Start the rotation, and deploy a check that accepts a signature from either
   the old secret or the new one.
2. Complete the rotation. New contexts are signed with the new secret.
3. Wait five minutes, for the last contexts signed with the old secret to
   expire, then remove the old secret from your check.

## Previews

When a CRM reviews your listing, it sees your app in a preview. The signed
sample in your dashboard is a preview too. A preview is signed exactly like a
real launch, with your secret, so your check accepts it. But:

* `x.preview` is `true`.
* The agent, contact and org are made up: `user.id` is always
  `rollout-preview-user`, `crm.personId` is `rollout-preview-person`, and
  `crm.accountId` and `org.id` are `rollout-preview-account`.
* There is no `account`.
* `x.marketplaceId`, `x.platform` and `x.appId` are real. When you're not
  listed in any marketplace yet, a sample names a placeholder, `mkt_sample` on
  platform `sample`.

When `x.preview` is `true`, show your app as a signed-in agent would see it,
with sample data, so the reviewer can judge it. Don't link the preview's
`user.id` to any of your users, and don't write anything to a CRM.


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