# Kick and revoke

URL: https://docs.folkways.io/docs/js-sdk/kick-and-revoke

Cut a user off before their token expires — close all their connections with POST /v1/kick, or cancel one token with POST /v1/revoke.

Tokens live at most 15 minutes. When you can't wait that long (a user is banned, signs out everywhere, or a token
leaks), your backend asks the node to cut them off:

| | `POST /v1/kick` | `POST /v1/revoke` |
| --- | --- | --- |
| Targets | One **identity**: every connection of that user in the segment | One **token**, by its `jti`: every connection using it, anonymous ones included |
| Afterwards | The user's tokens still work: a kick doesn't keep anyone out | The token is refused from then on, until it would have expired anyway |
| Use it for | "Sign out everywhere", moving a user to a new token now | A leaked or stolen token, a single device |

To ban someone, **stop issuing tokens for them** in your token endpoint, then kick them. Their current token runs
out within 15 minutes at most; revoke it too if they must not reconnect before then.

## Authenticate from your backend [#authenticate-from-your-backend]

Both endpoints are on the node's HTTP address and take a **service** token from your backend in
`Authorization: Bearer`. It needs the rights a client would need, and no more:

| Endpoint | Service token needs |
| --- | --- |
| `POST /v1/kick` | `publish` on that user's personal topic, `$user/{identity}` (or on `$user/>`) |
| `POST /v1/revoke` | `publish` on `$user/>`: the request doesn't say whose token it is |

```ts
const { token } = await rte.createToken({
  identity: 'backend',
  kind: 'service',
  capabilities: [{ topics: '$user/>', ops: ['publish'] }],
  ttlMs: 60_000,
});

await fetch(`${process.env.RTE_URL}/v1/kick`, {
  method: 'POST',
  headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
  body: JSON.stringify({ identity: 'user:42' }),
});
```

The body is `{ "identity": "user:42" }` for a kick and `{ "jti": "…" }` for a revoke. The answer is
`204 No Content`, whether or not the user was connected or the token was ever seen, so a request reveals nothing
about who exists. Errors are listed in the [REST reference](/docs/js-sdk/reference/rest#post-v1kick-and-post-v1revoke).

### Finding a token's `jti` [#finding-a-tokens-jti]

Only tokens with a `jti` claim can be revoked. `rte.createToken()` gives every token a random `jti`, but doesn't
return it separately; read it from the token when you issue it, and keep it with the user's session or device:

```ts
const jtiOf = (token: string) => JSON.parse(Buffer.from(token.split('.')[1], 'base64url')).jti as string;

const { token } = await rte.createToken({ identity: 'user:42', capabilities });
await db.devices.update(deviceId, { lastTokenJti: jtiOf(token) });
```

If you sign tokens with your own JWT library, set a unique `jti` yourself.

## What the client sees [#what-the-client-sees]

Each affected connection is closed with code **207, `AuthRevoked`** (within a second after a kick): reason
`kicked by the backend` after a kick, `token revoked` after a revoke. The node refuses a revoked token with `AuthRevoked` on every
later connection and HTTP request.

<Callout type="warn" title="Handle AuthRevoked in your app">
  The SDK doesn't treat `AuthRevoked` as final yet, and its `Code` table has no name for it (the error's `codeName`
  is `'Code207'`). Without handling, it reconnects: after a kick, at once with the same token, which still works;
  after a revoke, it keeps retrying the refused token until that expires. Close the client yourself, as below.
</Callout>

```ts
const AUTH_REVOKED = 207; // Code.AuthRevoked; not in the SDK's Code table yet

client.connection.on('change', ({ current, reason }) => {
  if (current === 'reconnecting' && reason?.code === AUTH_REVOKED) {
    void client.close({ clear: true }); // stop reconnecting and wipe local data
    showSignedOutScreen();               // reconnect only once your backend issues a new token
  }
});
```

The handler above sees connections that were open when the kick or revoke arrived. A client that starts with a token
that is already revoked gets no `change` with a reason: `connect()` keeps retrying the refused token, then rejects with
`Timeout` after `connectTimeoutMs`. So don't store tokens across sign-ins; ask your token endpoint for a fresh one,
which also lets your backend refuse a banned user.

Don't reconnect automatically after `AuthRevoked`. Tell the user they were signed out, and connect again only when
your app has a new token for them, which your backend may refuse to issue.

## Limits [#limits]

- **One node, in memory.** A kick or revoke applies only to the node that received it, and a revocation is kept in
  that node's memory. Another node, or the same node after a restart, doesn't know about it. If your segment's
  clients connect to more than one node, send the request to each of them.
- **Kept until the token would have expired.** The node holds each revocation for 16 minutes (a token's 15-minute
  maximum lifetime plus clock-skew leeway), and at most 10,000 per segment at a time. Beyond that, `/v1/revoke`
  answers `429 QuotaExceeded` until older ones expire.
- **Rate.** Each request takes one unit from the segment's service budget, shared with
  [`/v1/dm/open`](/docs/js-sdk/direct-messages) and [`/v1/members/*`](/docs/js-sdk/private-topics); over it, `429 RateLimited` with a `Retry-After` header.
- A connection that already moved to a new token with `client.updateToken()` is not affected by revoking its old
  token.
- Both endpoints are for backends only: they have no CORS, and browsers must never hold service tokens.

## Full example [#full-example]

The backend kicks Alice and revokes Bob's token; both apps sign out instead of reconnecting. Run it with Node.js 22
or later and the same variables as [Issue tokens from your backend](/docs/js-sdk/server-tokens).

```js title="kick.mjs"
import { Folkways } from '@folkwaysio/realtime';
import { Folkways as Server } from '@folkwaysio/realtime/server';

const url = process.env.RTE_URL;
const rte = new Server.Rest({
  url,
  segment: process.env.RTE_SEGMENT_ID,
  signingKey: { kid: process.env.RTE_KEY_ID, privateKey: process.env.RTE_PRIVATE_KEY },
});

// ---- backend ----

// createToken() gives every token a random jti. Read it from the token to revoke that token later.
const jtiOf = (token) => JSON.parse(Buffer.from(token.split('.')[1], 'base64url')).jti;

async function cutOff(path, body, capabilities) {
  const { token } = await rte.createToken({ identity: 'backend', kind: 'service', capabilities, ttlMs: 60_000 });
  const res = await fetch(`${url}${path}`, {
    method: 'POST',
    headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
    body: JSON.stringify(body),
  });
  if (res.status !== 204) throw new Error(`${path}: HTTP ${res.status} ${await res.text()}`);
}

// Close every connection of one user.
const kick = (identity) => cutOff('/v1/kick', { identity }, [{ topics: `$user/${identity}`, ops: ['publish'] }]);
// Close the connections holding one token, and refuse that token until it expires.
const revoke = (jti) => cutOff('/v1/revoke', { jti }, [{ topics: '$user/>', ops: ['publish'] }]);

// ---- the app ----

const AUTH_REVOKED = 207; // Code.AuthRevoked; not in the SDK's Code table yet

async function signIn(identity) {
  const tokens = [];
  const client = await Folkways.connect({
    url,
    token: async () => {
      const { token } = await rte.createToken({ identity }); // your token endpoint
      tokens.push(token);
      return token;
    },
  });
  client.connection.on('change', ({ current, reason }) => {
    if (current === 'reconnecting' && reason?.code === AUTH_REVOKED) {
      console.log(`${identity}: signed out by the backend (${reason.message})`);
      void client.close({ clear: true }); // stop reconnecting; show your signed-out screen
    }
  });
  return { client, tokens };
}

const alice = await signIn('user:alice');
const bob = await signIn('user:bob');

await kick('user:alice');
await revoke(jtiOf(bob.tokens.at(-1)));

await new Promise((r) => setTimeout(r, 1000));
console.log('alice:', alice.client.connection.state, '| bob:', bob.client.connection.state);
```

```text
user:alice: signed out by the backend (Code207: kicked by the backend)
user:bob: signed out by the backend (Code207: token revoked)
alice: closed | bob: closed
```
