# Authenticate servers to your backend

> Let a Worker or any backend of yours know which server of which network calls it: a bundle asks for a short-lived token signed with its server's instance key, and the backend verifies it against the network's public keys with any JWT library. No secret in the bundle.

> **Preview: Connect in the Minekube plugin:**
> This page describes networks in the Minekube plugin, the next generation of Connect. Today's Connect plugin and its `<endpoint>.play.minekube.net` addresses are described in the [Connect docs](https://minekube.com/guide/) and keep working. [Networks in the Minekube plugin](https://minekube.com/guide/networks/) compares the two.

Code outside your servers, such as friends, parties, matchmaking or a shop, runs best as your own backend, for example a [Cloudflare Worker](https://developers.cloudflare.com/workers/) with Durable Objects. When a server calls it, the backend has to know who calls. Every server in a network has an [instance key](https://minekube.com/guide/networks/concepts/instance#the-key-is-the-identity), and every network is an [OpenID Connect issuer](https://minekube.com/guide/networks/connectivity#every-network-is-an-openid-connect-issuer) that publishes the keys of its members. So a bundle can show a token signed with its server's key, and your backend checks it with any JWT library:

- **No secret in the bundle.** The key stays in the connector, in the server's process; the bundle only gets a token that expires in 5 minutes.
- **Nothing to register.** The backend trusts the network's issuer, so a new server works as soon as it is in the network, and a server that left or that you removed (`mk instances remove`) stops working once the backend reads the key set again ([how soon](#when-a-server-leaves)).
- **The same locally.** Against your local Minekube API (`mk api`, `mk server --network`), the issuer is local too, and the backend verifies the same way.

## Before you start

- A Paper server or Velocity proxy with the Minekube plugin, its connector on and the server in a network: [Let servers in](https://minekube.com/guide/networks/let-servers-in), or `mk server --network` for the local dev network `dev`.
- The network's issuer: the origin of the Minekube API URL in the server's `connector.json`, then `/n/<network>`. For the local dev network that is `http://localhost:4776/n/dev`. Its discovery document is at `<issuer>/.well-known/openid-configuration`, its keys at `<issuer>/jwks`.

The issuer is built from the Minekube API's origin only, exactly as the server's connector writes it: an API you host yourself under a path prefix still issues `https://api.example.com/n/<network>`, without the prefix, so serve `/n/` at the origin's root. `http://localhost:4776` and `http://127.0.0.1:4776` are two issuers too: write the Minekube API URL the same way in `connector.json` and in the backend.

## Ask for a token in the bundle

`Instance.token` is in every platform package (`@minekube/paper`, `@minekube/velocity`). The audience names your backend, so a token made for one backend is useless at another:

```ts

const backend = "https://friends.example.workers.dev";

const connect = Effect.gen(function* () {
  const token = yield* Instance.token({ audience: backend });
  // Over HTTP as a bearer token. A WebSocket cannot send headers, so it offers the token as its second protocol,
  // which stays out of the URL and so out of access logs.
  const socket = new WebSocket(`${backend.replace(/^http/, "ws")}/servers`, ["friends", token]);
});
```

Ask for a new token for each connection: it is valid for 5 minutes, and the server's network or labels may have changed. `Instance.token` fails with:

- **`Instance.NoNetwork`** on a server in no network: it has no `connector.json`, waits to be claimed, or its connector reads a file instead of a Minekube API.
- **`Instance.TokenFailed`** when the connector gives none, with its reason: the audience is blank, names the Minekube API itself or one of its networks (also as `localhost` for `127.0.0.1`), or is `minekube`, the audience trust rules take by default. The connector signs its own calls to the registry. Any other audience a bundle may ask for, and a trust rule with that audience takes the token. What keeps another network safe is the signer binding: a rule for a network's tokens (`mk trust add --network-issuer`) lets in only the server whose key signed the token, so a bundle's token can move at most its own server, never bring in another. Keep such a rule on the default audience `minekube` unless the other network's bundles should join with their own tokens.

## Verify it in your backend

The backend trusts one issuer per network and one audience, its own. With [jose](https://github.com/panva/jose) in a Worker:

```ts

const issuer = "https://api.minekube.com/n/my-network";
const audience = "https://friends.example.workers.dev";
// Read again at most a minute later, so a removed server's key is gone within a minute.
const keys = createRemoteJWKSet(new URL(`${issuer}/jwks`), { cacheMaxAge: 60_000 });

const caller = (token: string) =>
  Effect.tryPromise({
    try: () =>
      jwtVerify(token, keys, {
        issuer,
        audience,
        algorithms: ["EdDSA"],
        // A connector's token lasts 5 minutes: refuse one made to last longer.
        maxTokenAge: "5m",
        clockTolerance: "30s",
        requiredClaims: ["sub", "exp", "iat"],
      }),
    catch: () => new Error("not a server of my-network"),
  }).pipe(
    Effect.filterOrFail(
      // Any member's key verifies a member's token: the key id says whose key signed, and it must be the subject.
      ({ payload, protectedHeader }) => protectedHeader.kid === payload.sub,
      () => new Error("the token's subject is not the key that signed it"),
    ),
    // When to close the connection: 5 minutes after the token was made at most, whatever `exp` it says.
    Effect.map(({ payload }) => ({ instance: payload.sub, expiresAt: Math.min(payload.exp ?? 0, (payload.iat ?? 0) + 300) * 1000 })),
  );
```

Keep the issuer, the audience and the algorithm fixed in the backend's configuration; never take them from the token. Check that `kid` is `sub`: the network's key set has a key for every member, so without it one server could sign a token that names another. For a WebSocket, read the token from `Sec-WebSocket-Protocol` (`friends, <token>`) and answer with `Sec-WebSocket-Protocol: friends`, then close the connection when the token expires, so a server that left does not stay connected. Take the earlier of `exp` and `iat` plus 5 minutes: `maxTokenAge` refuses an old token, but a server with a changed connector could sign a fresh one whose `exp` is years away.

## When a server leaves

A server is out of the network's key set as soon as it moves to another network, you remove it (`mk instances remove <id> --network <network>`), or you remove the trust rule that let it in (`mk trust remove`). Your backend notices when it reads the key set again:

- **New tokens:** `createRemoteJWKSet` keeps the key set for `cacheMaxAge` (10 minutes unless you set it; a minute above) and reads it again earlier only for a key it does not know, such as a server that just joined. Until then the removed server's tokens still verify.
- **Open connections:** a connection verified before stays open until you close it. Close it 5 minutes after the token was made at the latest (`iat` plus 5 minutes, or `exp` if that is earlier), and the server has to connect again with a new token.

So a removed server stops working after at most `cacheMaxAge` plus 5 minutes and the 30 seconds of clock tolerance: a token made just before your backend last read the key set still opens a connection, which lasts until 5 minutes after the token was made. That is six and a half minutes with the settings above. It needs a new claim code or invite to join again; a server that joined by a trust rule joins again with its environment's next token while the rule covers it, so narrow or remove the rule too.

The [friends example](https://minekube.com/games/examples/friends) does both: a lobby bundle that connects to a Worker with a token, and a Worker that verifies it before a Durable Object takes the connection.

## What the token says

| Claim | Value |
| --- | --- |
| `iss` | The network's issuer, `<api>/n/<network>` |
| `sub` | The instance ID: the server's Ed25519 public key in hex. The header's `kid` is the same, as the network's key set lists it |
| `aud` | The audience the bundle asked for |
| `iat`, `exp` | When it was made, and 5 minutes later |
| `labels` | The server's labels: its own from `connector.json`, over them those its invite or trust rule gave it, and `minekube.com/platform` and `minekube.com/version` |

The signature proves which server made the token, and the key set proves the server is in the network now. The labels are the server's own claim: its connector writes them into the token, so a server with a changed connector can claim any labels, also those an invite or trust rule gives (`minekube.com/region` is not in the token, since only the registry knows it). Use them to show a server or as a hint where to route it, never to decide what it may do.

Decide what a server may do by its instance ID, the `sub` the backend just verified. Keep the IDs of the servers that may do more in the backend's configuration, such as a Worker variable:

```ts
// ADMINS: the instance IDs of the servers that may moderate, comma-separated. A server's ID is the `sub` of its
// token, which the backend may log for you on its first connection; `mk instances` shows how each starts.
const admins = new Set(env.ADMINS.split(","));

const mayModerate = (caller: { readonly instance: string }) => admins.has(caller.instance);
```

A server you remove from the network loses those rights with its membership, as its tokens stop verifying.

## Surfaces

Tokens are made where the key is, so this capability is an API of the server, not of the Minekube API: the connector signs, the runtime passes the call through, and a bundle calls `Instance.token`. `mk` has no command for it and `vite.config.ts` no field, since neither holds a server's key. Verifying needs nothing from Minekube but the issuer's public URLs.
