# Diner identity: sign diner tokens for the Tamr SDK

> Sign a short EdDSA JWT on your backend to tell Tamr's AI waiter which of your users is chatting, in Node, Kotlin, Dart or Swift, or mint a one-time launch code instead.

Source: https://tamr.link/docs/guides/diner-identity

Your app tells the waiter who the diner is by asking your backend for a short signed token, each time the waiter page needs one. Your backend checks its own user is logged in, then signs a JWT with an Ed25519 key. If your backend can't sign tokens, it can mint a one-time [launch code](#launch-codes) instead.

## The identity provider

The controller calls your identity provider whenever the page needs a fresh token, with a reason (`first_open`, `expired` or `refused`), and expects an answer within 15 seconds:

| Platform | A signed-in diner | A launch code | No one |
| --- | --- | --- | --- |
| Web, React Native | `{ token }` | `{ code }` | `null` |
| Flutter | `TamrToken(token)` | `TamrLaunchCode(code)` | `null` |
| iOS | `.token(token)` | `.code(code)` | `nil` |
| Android | `TamrIdentity.token(token)` | `TamrIdentity.code(code)` | `null` |

Ask your backend for a fresh token every time: a token works once. The page handles renewal, retries and expiry itself.

## 1. Make a key pair, once

Generate an Ed25519 key pair with your platform's crypto library (in Node, `generateKeyPairSync("ed25519")` from `node:crypto`) and keep the private key on your server, as a secret.

## 2. Register the public half

In **Settings > App keys**, open the app key, and under **Diner token signing keys** add the public key as a JWK (`{"kty":"OKP","crv":"Ed25519","x":"…"}`) with a name and a `kid` you choose: letters, digits, dots, dashes and underscores. The dashboard refuses a private key. The same section shows the exact `iss` and `aud` values to sign with.

## 3. Sign each token

| Claim | Value |
| --- | --- |
| header `alg` | `EdDSA` |
| header `kid` | The `kid` you registered |
| `iss` | The app key's id, as shown under Diner token signing keys (not the `tamr_pk_…` key itself). It stays the same when the key is rotated. |
| `aud` | `tamr:` and the restaurant address, for example `tamr:your-restaurant` |
| `sub` | Your own id for the user. Never a name, email or phone number. |
| `iat`, `exp` | Issued and expiry times in seconds, at most 5 minutes apart. Tamr allows 60 seconds of clock difference. |
| `jti` | A random id. Each token is accepted once. |
| `branch` | Optional: a branch address, as a hint |
| `locale` | Optional: a language tag, as a hint |

The same function in the four languages backends behind these apps are written in. The Node one runs in Tamr's tests against Tamr's own token check.

Node:

```js
// Signs a diner token for Tamr's waiter on your backend (Node 18+, no packages).
// Your app asks your backend for one whenever the waiter needs it (setIdentityProvider).
import { createPrivateKey, randomUUID, sign } from "node:crypto";

export function signTamrDinerToken({
	privateKeyPem,
	kid,
	appKeyId,
	restaurant,
	userId,
}) {
	const now = Math.floor(Date.now() / 1000);
	const header = { alg: "EdDSA", typ: "JWT", kid };
	const claims = {
		iss: appKeyId, // the app key's id (Settings, App keys)
		aud: `tamr:${restaurant}`,
		sub: userId, // your own id for this diner: never a name, email or phone
		iat: now,
		exp: now + 120, // at most 5 minutes
		jti: randomUUID(), // used once
	};
	const encode = (part) =>
		Buffer.from(JSON.stringify(part)).toString("base64url");
	const input = `${encode(header)}.${encode(claims)}`;
	const signature = sign(
		null,
		Buffer.from(input),
		createPrivateKey(privateKeyPem),
	);
	return `${input}.${signature.toString("base64url")}`;
}
```

Kotlin:

```kotlin
// Signs a diner token for Tamr's waiter on your backend (JDK 15+, no libraries).
// Your app asks your backend for one whenever the waiter needs it (setIdentityProvider).
import java.security.KeyFactory
import java.security.Signature
import java.security.spec.PKCS8EncodedKeySpec
import java.util.Base64
import java.util.UUID

fun signTamrDinerToken(
    privateKeyPkcs8: ByteArray,
    kid: String,
    appKeyId: String,
    restaurant: String,
    userId: String,
): String {
    val now = System.currentTimeMillis() / 1000
    fun json(value: String) = "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
    val header = """{"alg":"EdDSA","typ":"JWT","kid":${json(kid)}}"""
    val claims = """{"iss":${json(appKeyId)},"aud":${json("tamr:$restaurant")},""" +
        """"sub":${json(userId)},"iat":$now,"exp":${now + 120},"jti":${json(UUID.randomUUID().toString())}}"""
    val encoder = Base64.getUrlEncoder().withoutPadding()
    val input = encoder.encodeToString(header.toByteArray()) + "." + encoder.encodeToString(claims.toByteArray())
    val key = KeyFactory.getInstance("Ed25519").generatePrivate(PKCS8EncodedKeySpec(privateKeyPkcs8))
    val signature = Signature.getInstance("Ed25519").run {
        initSign(key)
        update(input.toByteArray())
        sign()
    }
    return input + "." + encoder.encodeToString(signature)
}
```

Dart:

```dart
// Signs a diner token for Tamr's waiter on your backend (package:cryptography).
// Your app asks your backend for one whenever the waiter needs it (setIdentityProvider).
import 'dart:convert';
import 'dart:math';

import 'package:cryptography/cryptography.dart';

Future<String> signTamrDinerToken({
  required SimpleKeyPair keyPair, // an Ed25519 key pair
  required String kid,
  required String appKeyId,
  required String restaurant,
  required String userId,
}) async {
  final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
  String encode(Object part) =>
      base64Url.encode(utf8.encode(jsonEncode(part))).replaceAll('=', '');
  final random = Random.secure();
  final jti = List.generate(16, (_) => random.nextInt(256))
      .map((b) => b.toRadixString(16).padLeft(2, '0'))
      .join();
  final header = {'alg': 'EdDSA', 'typ': 'JWT', 'kid': kid};
  final claims = {
    'iss': appKeyId, // the app key's id (Settings, App keys)
    'aud': 'tamr:$restaurant',
    'sub': userId, // your own id for this diner: never a name, email or phone
    'iat': now,
    'exp': now + 120, // at most 5 minutes
    'jti': jti, // used once
  };
  final input = '${encode(header)}.${encode(claims)}';
  final signature = await Ed25519().sign(utf8.encode(input), keyPair: keyPair);
  return '$input.${base64Url.encode(signature.bytes).replaceAll('=', '')}';
}
```

Swift:

```swift
// Signs a diner token for Tamr's waiter on your backend (CryptoKit, or swift-crypto on Linux).
// Your app asks your backend for one whenever the waiter needs it (setIdentityProvider).
#if canImport(CryptoKit)
import CryptoKit
#else
import Crypto
#endif
import Foundation

func signTamrDinerToken(
    privateKey: Curve25519.Signing.PrivateKey,
    kid: String,
    appKeyId: String,
    restaurant: String,
    userId: String
) throws -> String {
    let now = Int(Date().timeIntervalSince1970)
    func encode(_ part: [String: Any]) throws -> String {
        try JSONSerialization.data(withJSONObject: part, options: [.sortedKeys]).base64URL
    }
    let header: [String: Any] = ["alg": "EdDSA", "typ": "JWT", "kid": kid]
    let claims: [String: Any] = [
        "iss": appKeyId, // the app key's id (Settings, App keys)
        "aud": "tamr:\(restaurant)",
        "sub": userId, // your own id for this diner: never a name, email or phone
        "iat": now,
        "exp": now + 120, // at most 5 minutes
        "jti": UUID().uuidString, // used once
    ]
    let input = try encode(header) + "." + encode(claims)
    let signature = try privateKey.signature(for: Data(input.utf8))
    return input + "." + signature.base64URL
}

extension Data {
    var base64URL: String {
        base64EncodedString()
            .replacingOccurrences(of: "+", with: "-")
            .replacingOccurrences(of: "/", with: "_")
            .replacingOccurrences(of: "=", with: "")
    }
}
```

A token is spent when the page uses it, so sign a new one on every request from the app. The errors you may see are `token_invalid` (signature, `iss`, `aud`, `kid` or times wrong; the message says which) and `token_replayed` (the token was used before).

## Launch codes

If your backend can't sign tokens, mint a one-time code with a secret API key that has the `diner:sdk` permission: [Create a launch code](https://tamr.link/docs/api/create-launch-code). A code lasts 5 minutes and works once; your app returns it from the identity provider as a code. `branch` and `locale` are optional in the request, and an unknown branch is refused.

## Rotating keys

Add a second signing key, move your backend to it, then revoke the old one. Rotating the app key itself, with 0, 7 or 30 days' grace, doesn't change what you sign.

## One restaurant, one set of users

Tamr knows a diner by the restaurant and your user id, not by the app key: every app key of a restaurant shares the same users, so user `123` from its iOS app and its website is one diner with one history. A restaurant whose apps keep separate user lists must give its ids distinct prefixes (for example `ios:123` and `web:123`).

## When the diner signs out

Call `clearIdentity()` and dispose of the controller, then make a new one for the next diner. With a key in guest mode, `clearIdentity()` also ends the guest and starts a new one at once, on a new device id, so the next person on a shared phone never sees the last one's conversation. An app that draws its own chat calls [End a session](https://tamr.link/docs/api/end-session), which also ends the diner's current conversation, so their next sign-in starts afresh on every device.
