# Sign-in Source Reference

> The signed backend check request, Your keys claims, and the key-pair command.

Source: https://docs.gydr.ai/widget/visitor-token-reference

The exact contracts behind the three [sign-in sources](https://docs.gydr.ai/widget/signed-in-visitors): the signed check request Gydr sends to your backend, and the key and claims a *Your keys* source expects.

### Your backend: the check request

Gydr sends one `POST` with an empty body to your check URL. The URL must be `https` (no IP addresses, no redirects) and answer within 3 seconds.

Request headers:

```bash
POST https://api.example.com/gydr/check
Gydr-Source-Id: ids_AbC123xyz
Gydr-Visitor-Token: <the visitor's token>      (absent on the activation probe)
Gydr-Challenge: <random nonce>                 (activation probe only)
Gydr-Signature: t=1790000000,n=<nonce>,v1=<hex>[,v1=<hex>]
```

The signature proves the call is Gydr’s. Compute it with your secret exactly like this, and compare in constant time:

The signature:

```bash
v1 = hex( HMAC-SHA256( secret as UTF-8,
        "gydr-check-v1\n<t>\n<sourceId>\n<n>\n<subject>" ) )

subject = lowercase hex SHA-256 of the visitor token
          (for the activation probe: the Gydr-Challenge value)
```

-   Refuse a request when `|now − t|` is more than 300 seconds.
-   Accept any of the listed `v1` values: during a secret rotation Gydr sends both versions.
-   Answer with `Cache-Control: no-store`. A `200` that carries an `Age` header or a public cache directive is refused.

### What to answer

| Your answer | Meaning for Gydr |
| --- | --- |
| `200` with `{ "userId": "42", "name"?, "email"?, "expiresIn"? }` | Signed in. JSON of at most 4 KB with no other members; `userId` is a string of 1 to 255 printable characters. |
| `401` | Not signed in. Cached for 60 seconds; the visitor is a guest. |
| `403` | “I refuse your signature”. Reported as `bad_signature` with an operator alert — and never a sign-out. |
| Timeout, 5xx | `check_unavailable`. Gydr keeps the visitor signed in on the same token for a short grace period. |
| Anything else | `misconfigured`. |

### Verify and answer

Node.js:

```js
const crypto = require('node:crypto')
const SECRET = process.env.GYDR_CHECK_SECRET

const hmacHex = (key, text) =>
  crypto.createHmac('sha256', key).update(text).digest('hex')
const sha256Hex = (text) =>
  crypto.createHash('sha256').update(text).digest('hex')

function parseSignature(header) {
  const sig = { t: 0, n: '', v1: [] }
  for (const part of String(header || '').split(',')) {
    const [k, v] = part.split('=')
    if (k === 't') sig.t = Number(v)
    else if (k === 'n') sig.n = v
    else if (k === 'v1') sig.v1.push(v)
  }
  return sig.t && sig.n && sig.v1.length ? sig : null
}

function verifyGydrSignature(req, res, next) {
  const sig = parseSignature(req.get('Gydr-Signature'))
  if (!sig || Math.abs(Date.now() / 1000 - sig.t) > 300) return res.sendStatus(403)
  const subject =
    req.get('Gydr-Challenge') ?? sha256Hex(req.get('Gydr-Visitor-Token') ?? '')
  const base = ['gydr-check-v1', sig.t, req.get('Gydr-Source-Id'), sig.n, subject].join('\n')
  const expected = Buffer.from(hmacHex(SECRET, base), 'hex')
  const ok = sig.v1.some((v) => {
    const got = Buffer.from(v, 'hex')
    return got.length === expected.length && crypto.timingSafeEqual(got, expected)
  })
  return ok ? next() : res.sendStatus(403)
}

app.post('/gydr/check', verifyGydrSignature, async (req, res) => {
  res.set('Cache-Control', 'no-store')
  const challenge = req.get('Gydr-Challenge') // activation probe
  if (challenge) return res.json({ challenge: hmacHex(SECRET, challenge) })
  const user = await userForApiToken(req.get('Gydr-Visitor-Token'))
  if (!user) return res.sendStatus(401)
  res.json({ userId: String(user.id), name: user.name, email: user.email })
})
```

PHP:

```php
<?php
$secret = getenv('GYDR_CHECK_SECRET');
header('Cache-Control: no-store');

$sig = ['t' => 0, 'n' => '', 'v1' => []];
foreach (explode(',', $_SERVER['HTTP_GYDR_SIGNATURE'] ?? '') as $part) {
    [$k, $v] = array_pad(explode('=', $part, 2), 2, '');
    if ($k === 't') $sig['t'] = (int) $v;
    elseif ($k === 'n') $sig['n'] = $v;
    elseif ($k === 'v1') $sig['v1'][] = $v;
}
if (!$sig['t'] || abs(time() - $sig['t']) > 300) { http_response_code(403); exit; }

$challenge = $_SERVER['HTTP_GYDR_CHALLENGE'] ?? null;
$token = $_SERVER['HTTP_GYDR_VISITOR_TOKEN'] ?? '';
$subject = $challenge ?? hash('sha256', $token);
$base = implode("\n", ['gydr-check-v1', $sig['t'], $_SERVER['HTTP_GYDR_SOURCE_ID'], $sig['n'], $subject]);
$expected = hash_hmac('sha256', $base, $secret);

$ok = false;
foreach ($sig['v1'] as $v) { if (hash_equals($expected, $v)) $ok = true; }
if (!$ok) { http_response_code(403); exit; }

if ($challenge) { echo json_encode(['challenge' => hash_hmac('sha256', $challenge, $secret)]); exit; }

$user = user_for_api_token($token);
if (!$user) { http_response_code(401); exit; }
echo json_encode(['userId' => (string) $user->id, 'name' => $user->name, 'email' => $user->email]);
```

Python:

```python
import hashlib, hmac, os, time
from flask import Flask, request, jsonify

SECRET = os.environ['GYDR_CHECK_SECRET'].encode()
app = Flask(__name__)

def parse_signature(header):
    sig = {'t': 0, 'n': '', 'v1': []}
    for part in (header or '').split(','):
        k, _, v = part.partition('=')
        if k == 't': sig['t'] = int(v or 0)
        elif k == 'n': sig['n'] = v
        elif k == 'v1': sig['v1'].append(v)
    return sig if sig['t'] and sig['n'] and sig['v1'] else None

def hmac_hex(text):
    return hmac.new(SECRET, text.encode(), hashlib.sha256).hexdigest()

@app.post('/gydr/check')
def check():
    sig = parse_signature(request.headers.get('Gydr-Signature'))
    if not sig or abs(time.time() - sig['t']) > 300:
        return '', 403
    challenge = request.headers.get('Gydr-Challenge')
    token = request.headers.get('Gydr-Visitor-Token', '')
    subject = challenge or hashlib.sha256(token.encode()).hexdigest()
    base = '\n'.join(['gydr-check-v1', str(sig['t']), request.headers.get('Gydr-Source-Id', ''), sig['n'], subject])
    expected = hmac_hex(base)
    if not any(hmac.compare_digest(expected, v) for v in sig['v1']):
        return '', 403
    resp_headers = {'Cache-Control': 'no-store'}
    if challenge:
        return jsonify(challenge=hmac_hex(challenge)), 200, resp_headers
    user = user_for_api_token(token)
    if not user:
        return '', 401
    return jsonify(userId=str(user.id), name=user.name, email=user.email), 200, resp_headers
```

### Activate, rotate, retire

-   **Activate.** The Console sends a probe carrying `Gydr-Challenge`; your endpoint answers `{ "challenge": hex(HMAC(secret, challenge)) }`. The snippets above already do. A source works only after a probe passes, and **any edit of the check URL deactivates it** until a new probe passes.
-   **Rotate.** Rotating issues a new secret (shown once) and Gydr signs every request with both until you press **Retire the old secret**, so rotation signs nobody out.
-   **Egress.** Gydr calls from fixed addresses, listed in Console → Settings → Visitor sign-in, if you allow-list.

Keep the secret in server configuration. Anyone holding it can make your endpoint answer as Gydr, and the Console shows it only once.

### Your keys: claims and the key-pair command

A *Your keys* source accepts RS256, ES256 or EdDSA JWTs. The token must carry:

| Claim | Required | Notes |
| --- | --- | --- |
| `iss` | Yes | Must equal the issuer you registered. |
| `aud` / `azp` / `client_id` | Required for a JWKS URL; optional for a pasted key | One of them must equal the audience you registered. |
| `sub` | Yes | The User ID, unless you name another claim. 1 to 255 printable characters; it must never change for the same person. |
| `exp` | Yes | At most 24 hours after the token was issued; about 1 hour is typical. |
| `name`, `email`, `phone_number` | No | Used to fill the visitor's details where empty. Phone is read from phone\_number, or from phone when phone\_number is absent. |
| `is_anonymous`, `firebase.sign_in_provider` | No | A token for an anonymous session (is\_anonymous: true, or a Firebase anonymous sign-in) never signs a visitor in: the visitor stays a guest. |

Limits Gydr enforces

The whole token is at most 8 KB and each claim at most 256 characters. Tokens whose header carries `crit`, `jku`, `jwk`, `x5u` or `x5c` are refused, and up to 60 seconds of clock difference is allowed. The issuer, JWKS URL and any URL you register must be https.

### Sign your own token

For a site with cookie sessions and no identity provider. Create a key pair once, paste the **public** key in the Console, and keep the private key on your server:

Create an ES256 key pair:

```bash
openssl ecparam -name prime256v1 -genkey -noout -out gydr-ec.pem
openssl pkcs8 -topk8 -nocrypt -in gydr-ec.pem -out gydr-private.pem   # keep on your server
openssl ec -in gydr-ec.pem -pubout -out gydr-public.pem               # paste in the Console
```

Serve the token:

```js
import { SignJWT, importPKCS8 } from 'jose'
const key = await importPKCS8(process.env.GYDR_VISITOR_KEY, 'ES256')

app.get('/gydr/visitor-token', async (req, res) => {
  res.set('Cache-Control', 'no-store')
  const u = req.session.user
  if (!u) return res.json({ visitorToken: null })
  const visitorToken = await new SignJWT({ name: u.name, email: u.email })
    .setProtectedHeader({ alg: 'ES256' })
    .setSubject(String(u.id))
    .setIssuer('https://www.example.com')
    .setIssuedAt()
    .setExpirationTime('1h')
    .sign(key)
  res.json({ visitorToken })
})
```

Register the issuer (`https://www.example.com` above) and the public key; the audience is optional for a pasted key. This is the “recognise people only” setup: no plugin receives the token.
