# Private topics and member lists

URL: https://docs.folkways.io/docs/js-sdk/private-topics

Keep a topic to a list of members that your backend manages, and remove someone at once, whatever token they hold.

A private topic is one whose rule is **Members only**. Besides a token that allows it, each user needs an entry on
the topic's **member list**, which your backend keeps. Use it for project rooms, group chats and DMs, where who is
in the room changes over time.

| | Token access (the default) | Members only |
| --- | --- | --- |
| Who decides | The token lists the topics a user may use | The topic's member list, kept by your backend |
| Tokens | Grow with every room the user joins | One ceiling for all rooms, e.g. `private/*` |
| Removing someone | Takes effect when their token expires (at most 15 minutes) | At once: their subscriptions end and the next action is refused |
| A new token | Can grant access again | Can't undo a removal |

What a user may do in a private topic is what **all three** allow: their token, the rule's operations and their
member entry. Service tokens need no entry.

## Set up the rule [#set-up-the-rule]

On the segment's **Topic rules** tab, add a rule for the topics, for example pattern `private/*`, and set **Who may
use it** to **Members only**.

Give users a token that sets the ceiling for all those topics, and let the member lists decide which ones they get:

```ts
capabilities: [{ topics: 'private/*', ops: ['subscribe', 'publish'] }]
```

## Manage members from your backend [#manage-members-from-your-backend]

Your backend changes a list with `POST /v1/members/{action}` on the node's HTTP address, using a **service** token
with `publish` on the topic:

| Endpoint | Body | Does |
| --- | --- | --- |
| `/v1/members/add` | `{ topic, identities, ops }` | Each identity gets exactly `ops`, whether or not it was a member |
| `/v1/members/set` | `{ topic, identity, ops }` | The same for one identity. Narrow it to block someone: `["subscribe"]` can read but not send |
| `/v1/members/remove` | `{ topic, identities }` | The identities lose every right in the topic |
| `/v1/members/clear` | `{ topic }` | Everyone does: the room is closed |
| `/v1/members/list` | `{ topic }` | Answers `{ topic, members: [{ identity, ops }] }` |

`ops` is any of `subscribe`, `publish`, `set`, `signal`, `history` and `presence`. Changes answer `204` once they are
stored. Full details and errors are in the [REST reference](/docs/js-sdk/reference/rest#post-v1members).

```ts
const { token } = await rte.createToken({
  identity: 'backend',
  kind: 'service',
  capabilities: [{ topics: 'private/*', ops: ['publish'] }],
});

await fetch(`${process.env.RTE_URL}/v1/members/add`, {
  method: 'POST',
  headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
  body: JSON.stringify({ topic: 'private/project-7', identities: ['user:42'], ops: ['subscribe', 'publish'] }),
});
```

The SDK has no helper for these endpoints yet, so call them with `fetch` as above.
[Direct messages](/docs/js-sdk/direct-messages) on a members-only rule fill the list for you.

## What a removed member sees [#what-a-removed-member-sees]

Removing a member, or narrowing their entry so it loses `subscribe`, ends their subscriptions to the topic at once.
In the SDK the subscription fires `ended` with `Forbidden`, and any publish or subscribe there afterwards fails with
`Forbidden`, even with a fresh token. Someone who was never on the list gets `Forbidden` when they subscribe.

```ts
const sub = client.topic('private/project-7').subscribe(onMessage);
sub.on('ended', (err) => showRemovedFromRoom(err));  // err.codeName === 'Forbidden'
```

## Full example [#full-example]

The backend adds Alice and Bob to a private topic. Carol's token allows `private/*`, but she isn't on the list. Then
the backend removes Bob. Run it with Node.js 22 or later and the same variables as
[Issue tokens from your backend](/docs/js-sdk/server-tokens), on a segment with a **Members only** rule for
`private/*`.

```js title="private.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 },
});
const room = 'private/project-7';

// ---- backend ----

// POST /v1/members/{add,set,remove,clear,list} with a service token that may publish on the topic.
async function members(action, body) {
  const { token } = await rte.createToken({
    identity: 'backend',
    kind: 'service',
    capabilities: [{ topics: 'private/*', ops: ['publish'] }],
    ttlMs: 60_000,
  });
  const res = await fetch(`${url}/v1/members/${action}`, {
    method: 'POST',
    headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`members/${action}: HTTP ${res.status} ${await res.text()}`);
  return res.status === 200 ? res.json() : undefined;
}

// Every user's token: the same ceiling for all private topics. The member list decides which ones.
const tokenFor = (identity) => async () =>
  (await rte.createToken({ identity, capabilities: [{ topics: 'private/*', ops: ['subscribe', 'publish'] }] })).token;

await members('add', { topic: room, identities: ['user:alice', 'user:bob'], ops: ['subscribe', 'publish'] });
console.log('members:', JSON.stringify(await members('list', { topic: room })));

// ---- the apps ----

async function join(identity) {
  const client = await Folkways.connect({ url, token: tokenFor(identity) });
  const topic = client.topic(room);
  const sub = topic.subscribe((msg) => console.log(`  ${identity} got: ${msg.data.text}`));
  sub.on('error', (e) => console.log(`  ${identity}: subscription error ${e.codeName}`));
  sub.on('ended', (e) => console.log(`  ${identity}: subscription ended (${e?.codeName ?? e})`));
  await sub.ready.catch(() => {});
  return { client, topic };
}

const alice = await join('user:alice');
const bob = await join('user:bob');
const carol = await join('user:carol'); // her token allows private/*, but she isn't on the list

await alice.topic.publish('message', { text: 'hello members' });
await carol.topic.publish('message', { text: 'let me in' }).catch((e) => console.log('  carol publish:', e.codeName));
await new Promise((r) => setTimeout(r, 300));

console.log('-- the backend removes Bob');
await members('remove', { topic: room, identities: ['user:bob'] });
await new Promise((r) => setTimeout(r, 300));
await alice.topic.publish('message', { text: 'bob is gone' });
await bob.topic.publish('message', { text: 'still here?' }).catch((e) => console.log('  bob publish:', e.codeName));
await new Promise((r) => setTimeout(r, 300));

await Promise.all([alice.client.close(), bob.client.close(), carol.client.close()]);
```

It prints, among the updates:

```text
members: {"topic":"private/project-7","members":[{"identity":"user:alice","ops":["subscribe","publish"]},{"identity":"user:bob","ops":["subscribe","publish"]}]}
  user:carol: subscription error Forbidden
  user:alice got: hello members
  user:bob got: hello members
  carol publish: Forbidden
-- the backend removes Bob
  user:bob: subscription ended (Forbidden)
  user:alice got: bob is gone
  bob publish: Forbidden
```

## Good to know [#good-to-know]

- **A list belongs to one topic name**, not a pattern: `private/project-7` and `private/project-8` have separate
  lists. A topic holds at most 10,000 members, and one request changes at most 1,000.
- **Rules with token access have no list.** `/v1/members/*` on such a topic answers `400 InvalidArgument`.
- **Presence in private topics is for service tokens only.** `$presence/{topic}` stays closed to client tokens
  wherever a members-only rule could match, so it never shows who is in a private room. See
  [Presence](/docs/js-sdk/presence).
- **Changes apply on the node that receives them** and are stored before the answer, so they survive a restart. If
  the node can't store a change, the request fails with `503 Unavailable` and can be sent again; a removal still holds
  on that node meanwhile.
