# Signed user tokens

> **In short.** Optional. If your users sign in, your server signs a short JWT for each one with an
> Ed25519 private key (`alg: "EdDSA"`) and claims `sub` (your user id), `name` (optional), `aud`
> (the product's `jk_...` key) and `exp` (at most 7 days ahead). The widget sends it as
> `Authorization: Bearer <token>`. Their tickets then follow their account to any device. The
> private key stays on your server; Junco only has the public half.

Without tokens, Junco recognises users by a random id kept in their browser or app, which is
fine for many products. Use tokens when users sign in and switch devices, or when you want only
signed-in users to reach support.

## 1. Make a key pair

On the product's page in Junco: **How users are recognised → Make a key**. Your browser makes an
Ed25519 key pair and downloads the private half as `<product>-junco-signing-key.pem` (PKCS#8,
`-----BEGIN PRIVATE KEY-----`). Junco keeps only the public half and can't show the private half
again.

Keep the `.pem` **on your server only**, in a secret or environment variable
(`JUNCO_SIGNING_KEY`, with its line breaks). Never put it in your app, your website's code or
your repo. Making a new key stops tokens signed with the old one at once.

On the same page, **Without an account** says whether users without a token may still send
tickets (by their random id). Turn it off to take tickets from signed-in users only.

## 2. Sign a token on your server

The token is a compact JWT:

| Part | Value |
|---|---|
| Header | `{"alg": "EdDSA", "typ": "JWT"}` |
| `sub` | Your id for the user: any string, 1 to 200 characters. Use something stable, not an email. |
| `name` | Their display name, shown to your team (optional; cut to 40 characters). |
| `aud` | The product's public key, `jk_...`. A token for one product doesn't work for another. |
| `exp` | When it expires, in seconds since 1970: in the future, and at most 7 days ahead. |
| `iat` | Optional, ignored. |

Junco rejects a token with another `alg`, a bad signature, the wrong `aud`, or an `exp` in the
past or more than 7 days ahead. A day (`86400` seconds) is a good lifetime; the widget asks for a
fresh one before each request.

### Node.js (no packages)

```js
import { createPrivateKey, sign } from "node:crypto";

const key = createPrivateKey(process.env.JUNCO_SIGNING_KEY);
const b64 = (v) => Buffer.from(typeof v === "string" ? v : JSON.stringify(v)).toString("base64url");

export function juncoToken(user) {
  const head = b64({ alg: "EdDSA", typ: "JWT" });
  const body = b64({ sub: String(user.id), name: user.displayName, aud: "jk_...", exp: Math.floor(Date.now() / 1000) + 86400 });
  return `${head}.${body}.${sign(null, Buffer.from(`${head}.${body}`), key).toString("base64url")}`;
}

// Express: app.get("/api/junco-token", requireLogin, (req, res) => res.type("text").send(juncoToken(req.user)));
```

With `jose`: `await new SignJWT({ name }).setProtectedHeader({ alg: "EdDSA" }).setSubject(id).setAudience("jk_...").setExpirationTime("1d").sign(await importPKCS8(pem, "EdDSA"))`.

### Python (PyJWT)

```python
# pip install "pyjwt[crypto]"
import os, time, jwt

KEY = os.environ["JUNCO_SIGNING_KEY"]

def junco_token(user) -> str:
    claims = {"sub": str(user.id), "name": user.display_name, "aud": "jk_...", "exp": int(time.time()) + 86400}
    return jwt.encode(claims, KEY, algorithm="EdDSA")

# Flask:  @app.get("/api/junco-token") -> return junco_token(current_user), 200, {"Content-Type": "text/plain"}
# Django: return HttpResponse(junco_token(request.user), content_type="text/plain")
```

### Go (standard library only)

```go
package junco

import (
	"crypto/ed25519"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"encoding/pem"
	"os"
	"time"
)

var key = func() ed25519.PrivateKey {
	block, _ := pem.Decode([]byte(os.Getenv("JUNCO_SIGNING_KEY")))
	if block == nil {
		panic("JUNCO_SIGNING_KEY isn't a PEM key")
	}
	k, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		panic(err)
	}
	return k.(ed25519.PrivateKey)
}()

func b64(v any) string {
	b, _ := json.Marshal(v)
	return base64.RawURLEncoding.EncodeToString(b)
}

func Token(userID, name string) string {
	head := b64(map[string]string{"alg": "EdDSA", "typ": "JWT"})
	body := b64(map[string]any{"sub": userID, "name": name, "aud": "jk_...", "exp": time.Now().Add(24 * time.Hour).Unix()})
	sig := ed25519.Sign(key, []byte(head+"."+body))
	return head + "." + body + "." + base64.RawURLEncoding.EncodeToString(sig)
}
```

### PHP (sodium, built in since PHP 7.2)

```php
<?php
function junco_token(string $userId, string $name): string {
    // The PEM holds a PKCS#8 wrapper whose last 32 bytes are the Ed25519 seed.
    $der = base64_decode(preg_replace('/-----[^-]+-----|\s/', '', getenv('JUNCO_SIGNING_KEY')));
    $secret = sodium_crypto_sign_secretkey(sodium_crypto_sign_seed_keypair(substr($der, -32)));
    $b64 = fn(string $v) => rtrim(strtr(base64_encode($v), '+/', '-_'), '=');
    $head = $b64(json_encode(['alg' => 'EdDSA', 'typ' => 'JWT']));
    $body = $b64(json_encode(['sub' => $userId, 'name' => $name, 'aud' => 'jk_...', 'exp' => time() + 86400]));
    return "$head.$body." . $b64(sodium_crypto_sign_detached("$head.$body", $secret));
}
```

### Anything else

Any JWT library that supports **EdDSA with Ed25519** works: `jose` (JavaScript), `PyJWT` with
`cryptography` (Python), `golang-jwt` (Go), `jwt` with `ed25519` (Ruby), `NSec` or BouncyCastle
(.NET), `jjwt` or Nimbus (Java and Kotlin), `jsonwebtoken` (Rust). If yours wants a raw key
rather than PEM, the 32-byte seed is the last 32 bytes of the PEM's decoded contents.

## 3. Hand it to the form

**The widget:** add an endpoint that returns the token as plain text for the signed-in user (and
an error, or nothing, for everyone else), and pass a function:

```js
Junco.init({
  game: "jk_...",
  server: "https://desk.juncodesk.app",
  playerToken: () => fetch("/api/junco-token", { credentials: "include" }).then((r) => (r.ok ? r.text() : null)),
});
```

The widget calls it before each request, so keep it quick (cache the token in memory until
shortly before `exp` if your endpoint is slow). Returning `null` falls back to the random id, if
**Without an account** is on.

**Your own form (the API):** send `Authorization: Bearer <token>` instead of `X-Junco-Player`.
Native apps get the token from your backend the same way.

## Check a token

Paste it into any JWT decoder: the header must say `EdDSA`, `aud` must be the product's key, and
`exp` must be within 7 days. Then:

```sh
curl -s https://desk.juncodesk.app/v1/games/jk_.../unread -H "Authorization: Bearer $TOKEN"
# {"count":0}  good
# {"error":"Player token isn't valid"}  wrong key, aud or exp
# {"error":"This game doesn't use player tokens"}  no key made on the product yet
```
