Authenticate servers to your backend
Code outside your servers, such as friends, parties, matchmaking or a shop, runs best as your own backend, for example a Cloudflare Worker with Durable Objects. When a server calls it, the backend has to know who calls. Every server in a network has an instance key, and 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). - 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
Section titled “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, or
mk server --networkfor the local dev networkdev. - 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 ishttp://. Its discovery document is atlocalhost:4776/ n/ dev <issuer>/, its keys at.well-known/ openid-configuration <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://, 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
Section titled “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:
import { Instance } from "@minekube/paper";import { Effect } from "effect";
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.NoNetworkon a server in no network: it has noconnector.json, waits to be claimed, or its connector reads a file instead of a Minekube API.Instance.TokenFailedwhen the connector gives none, with its reason: the audience is blank, names the Minekube API itself or one of its networks (also aslocalhostfor127.0.0.1), or isminekube, 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 audienceminekubeunless the other network’s bundles should join with their own tokens.
Verify it in your backend
Section titled “Verify it in your backend”The backend trusts one issuer per network and one audience, its own. With jose in a Worker:
import { Effect } from "effect";import { createRemoteJWKSet, jwtVerify } from "jose";
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
Section titled “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:
createRemoteJWKSetkeeps the key set forcacheMaxAge(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 (
iatplus 5 minutes, orexpif 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 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
Section titled “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:
// 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
Section titled “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.
Was this helpful?
Thanks for the feedback.