Server integration
Your backend has two jobs: sign user tokens, and manage rooms, messages and users over REST.
TypeScript has @kispi/chat/server, which wraps both; every other language does the same work directly.
Pick your language in the tabs below.
Both jobs use a single sk_.
User token spec
| Format | A standard JWT. The signing algorithm is fixed to HS256; any other algorithm and none are refused |
| Signing key | The entire sk_ string as UTF-8 bytes. Don't strip the prefix or decode it |
| Header | {"alg":"HS256","typ":"JWT","kid":"…"} — kid is optional. Set it only when the second segment of sk_<key id>_<token> is 13 Crockford Base32 characters ([0-9A-HJKMNP-TV-Z]{13}); otherwise leave it out. Without a kid, the engine tries every live sk_ of the app |
Claims:
| Claim | ||
|---|---|---|
sub |
required | The user id in your service. At most 128 UTF-8 bytes. Refused if it starts with anon: |
iat |
required | Issued at, in whole seconds. Refused if later than now + 60s. Don't round it or cache it |
exp |
required | Expiry, in whole seconds. If exp - iat exceeds 86400 (24 hours) it is refused, not clamped |
name |
recommended | Overwrites the stored name on every connect. Truncated to 256 bytes when stored |
avatar |
optional | Truncated to 2048 bytes when stored |
meta |
optional | A JSON object. It replaces the user's meta.provider block wholesale (it is not a deep merge). Other meta keys the user wrote themselves are left alone. If the claim's JSON is over 2048 bytes it is ignored and the previous provider block stays. Leave the claim out and the previous block stays too |
aud, iss and nbf are not required. Which app you are is decided by the pk_ the browser sends on
connect, not by the token. When verification fails the answer is a single 401 unauthorized whatever
the reason — it won't tell you whether the signature was wrong or the token expired.
Go uses github.com/golang-jwt/jwt/v5 and Kotlin uses com.auth0:java-jwt. The rest needs nothing
beyond the standard library.
import { createChatServer } from '@kispi/chat/server'
const chat = createChatServer({ secretKey: process.env.CHAT_SECRET_KEY! })
const token = chat.token({ userId: 'u_42', name: 'Hanna', ttlSeconds: 3600 })import base64, hmac, hashlib, json, re, time
KID = re.compile(r"[0-9A-HJKMNP-TV-Z]{13}") # 13 Crockford Base32 characters
def b64u(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
def chat_token(sk, user_id, name, ttl=3600, avatar=None, meta=None):
parts = sk.split("_")
header = {"alg": "HS256", "typ": "JWT"}
if len(parts) >= 3 and KID.fullmatch(parts[1]): header["kid"] = parts[1]
iat = int(time.time())
claims = {"sub": user_id, "name": name, "iat": iat, "exp": iat + ttl}
if avatar: claims["avatar"] = avatar
if meta: claims["meta"] = meta
enc = lambda o: b64u(json.dumps(o, separators=(",", ":")).encode())
signing_input = f"{enc(header)}.{enc(claims)}"
sig = hmac.new(sk.encode(), signing_input.encode(), hashlib.sha256).digest()
return f"{signing_input}.{b64u(sig)}"var kidPattern = regexp.MustCompile(`^[0-9A-HJKMNP-TV-Z]{13}$`) // 13 Crockford Base32 characters
func chatToken(sk, userID, name string, ttl time.Duration) (string, error) {
now := time.Now()
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": userID,
"name": name,
"iat": now.Unix(),
"exp": now.Add(ttl).Unix(),
})
if parts := strings.Split(sk, "_"); len(parts) >= 3 && kidPattern.MatchString(parts[1]) {
token.Header["kid"] = parts[1]
}
return token.SignedString([]byte(sk))
}private val KID = Regex("^[0-9A-HJKMNP-TV-Z]{13}$") // 13 Crockford Base32 characters
fun chatToken(sk: String, userId: String, name: String, ttlSeconds: Long = 3600): String {
val now = Instant.now()
val builder = JWT.create()
.withSubject(userId)
.withClaim("name", name)
.withIssuedAt(now)
.withExpiresAt(now.plusSeconds(ttlSeconds))
sk.split("_").let { if (it.size >= 3 && KID.matches(it[1])) builder.withKeyId(it[1]) }
return builder.sign(Algorithm.HMAC256(sk))
}Server API
There is one way in: REST. The TypeScript SDK wraps it, so the three tabs below are three ways of calling the same endpoints. Every route's request, response and errors are in the REST API reference.
The whole surface of @kispi/chat/server. Editing messages, search (q), user-list filters, and permanently deleting a user (purge) have no SDK method, so call REST directly. Permanently deleting a room is rooms.delete(roomId, {purge: true}).
| Group | Methods |
|---|---|
| Top level | token({userId, name, avatar?, meta?, ttlSeconds?}), guest({credential?, name, avatar?, meta?, ttlSeconds?}) — both sign locally |
rooms |
list({type?, cursor?, limit?}), ensure({key?, type, name?, meta?, members?}), ensureDM([a, b]), get, update, delete(roomId, {purge?}), custom(roomId, payload), presence(roomId, {full?}), members.list/add/remove |
messages |
send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?}), list(roomId, {before?, after?, limit?}), delete |
users |
list({cursor?, limit?}), update(userId, {name?, avatar?, meta?}), withdraw(userId, {purgeMessages?}), purgeMessages(userId), ban(userId, {until, reason?}), unban(userId), revokeTokens(userId), disconnect(userId, {connectionId?, reason?}) |
events |
list({after?, limit?}) — catch up on missed webhooks |
webhooks |
verify(headers, rawBody, {now?, tolerance?}) |
const chat = createChatServer({ secretKey: process.env.CHAT_SECRET_KEY! })
const room = await chat.rooms.ensure({ key: 'lobby', type: 'public' })
await chat.messages.send(room.id, {
sender: { id: 'system', name: 'Notice' },
text: 'Maintenance in 10 minutes'
})The address is https://api.chat.gravex.app. Authenticate with Authorization: Bearer sk_…, and send
Content-Type: application/json when there's a body.
| Purpose | Route |
|---|---|
| Room get-or-create | PUT /v1/rooms {key?, type, name?, meta?, members?} — 201 created, 200 existing |
| DM | PUT /v1/rooms {type: "dm", members: [a, b]} |
| List rooms | GET /v1/rooms?type=&cursor=&limit= — without type you get public and channel; an sk_ can also pass private and dm, comma-separated (type=private,dm). Newest first, limit defaults to 50, max 100 |
| Get, update, delete a room | GET, PATCH, DELETE /v1/rooms/{roomId}, GET /v1/rooms/by-key/{key} |
| Permanently delete a room | DELETE /v1/rooms/{roomId}?purge=true — 202 |
| Send a message | POST /v1/rooms/{roomId}/messages {clientMessageId, sender: {id, name, avatar?}, kind?, body: {text?, attachments?}, appMeta?, replyTo?, threadId?} |
| History and search | GET /v1/rooms/{roomId}/messages?before=&after=&limit=&view=&q= |
| Edit a message | PATCH /v1/rooms/{roomId}/messages/{messageId} {body: {text?, attachments?}} — 200 + the message object |
| Delete a message | DELETE /v1/rooms/{roomId}/messages/{messageId} — 204 |
| Control signal (not stored) | POST /v1/rooms/{roomId}/custom {payload} |
| Members | GET /v1/rooms/{roomId}/members, PUT, DELETE /v1/rooms/{roomId}/members/{userId} {role?} |
| presence | GET /v1/rooms/{roomId}/presence?full=true — an empty room is {count: 0} |
| User profile | PUT /v1/users/{userId} {name?, avatar?, meta?} |
| Ban and unban | PUT /v1/users/{userId}/ban {until, reason?} (until is unix milliseconds and required), DELETE …/ban |
| Take down their messages | DELETE /v1/users/{userId}/messages |
| Withdraw (anonymize) | DELETE /v1/users/{userId}, add ?purge_messages=true to take their messages down too |
| Permanently delete a user | DELETE /v1/users/{userId}?purge=true — withdrawn users only, 202 |
| Invalidate tokens | POST /v1/users/{userId}/revoke-tokens |
| Force disconnect | POST /v1/users/{userId}/disconnect |
| List users | GET /v1/users?cursor=&limit=&q=&status=&last_seen_after=&last_seen_before=&created_after=&created_before=&bots= |
| Missed events | GET /v1/events?after=&limit= |
| Download the whole app | GET /v1/export — an NDJSON stream with users, rooms, members, messages, reactions and read positions; attachment files are not included. A file whose last line is not {"type":"end",…} is incomplete. One at a time per app (409), 429 when the server is busy. sk_ only |
# Room get-or-create: 200 if it existed, 201 if it was created, same body either way
curl -X PUT https://api.chat.gravex.app/v1/rooms \
-H "Authorization: Bearer $CHAT_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"key": "lobby", "type": "public"}'
# Send a system message. sender and clientMessageId are required
curl -X POST https://api.chat.gravex.app/v1/rooms/$ROOM_ID/messages \
-H "Authorization: Bearer $CHAT_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"clientMessageId": "c_1",
"sender": {"id": "system", "name": "Notice"},
"body": {"text": "Maintenance in 10 minutes"}}'sender and clientMessageId are required when you send a message from the server. Query parameters are
snake_case (purge_messages); JSON fields are camelCase.
users.* works only after that person has connected at least once; users come into being by connecting.
Reading and searching history
- The response is in ascending seq order and
limitis at most 100.beforeandafterare seq values. - Without
viewyou get the whole room including thread replies;maingives the main timeline only, andthread:<root message id>gives that thread only. Any other value is a 400. qsearches message text (body.text) inside that room. It's a substring match, case-insensitive, and deleted messages don't match. Onlysk_may passq(a user token gets 403), and aqof only whitespace is a 400. Theseqvalues in search results are not contiguous — messages that didn't match are simply missing, so don't use them for gap detection.
Editing and deleting messages
PATCH replaces a message's whole body and stamps editedAt. seq doesn't move and the room receives
message.updated. A missing body is a 400, and an already-deleted message is a 404.
- Called with an
sk_, it edits any message (system messages included) and the edit window doesn't apply. - Called with a user token, it edits only the caller's own messages, and only inside the app's edit window
(
editWindowMs, unlimited by default). A room owner or admin can't edit someone else's message, only delete it. A banned user getsbanned. - The rate is 2 per second per user (
editPerSecond).sk_calls aren't counted.
The browser SDK's Room has no edit or delete methods, and the server SDK has only messages.delete. Call REST
directly to edit. Do system-message and moderation edits from your backend with an sk_; for a screen where
users edit their own messages, the browser can call the route with the user token (send
Authorization: Bearer <user token> and X-Chat-Key: pk_…). The engine checks the author and the edit window.
DELETE is a tombstone: the row stays and the text is emptied. seq is unchanged and the room receives
message.deleted. Deleting an already-deleted message is 204 again. A user token can delete the caller's own
messages, and a room owner or admin can delete others' as moderation.
Kinds of deletion
| What you want | Call | What remains |
|---|---|---|
| Delete one message | DELETE /v1/rooms/{roomId}/messages/{messageId} |
The row, its seq, and the sender's name. Only the text is emptied |
| Take down everything one person sent | DELETE /v1/users/{userId}/messages |
Same as above. The account stays |
| Withdraw | DELETE /v1/users/{userId} |
The name becomes "탈퇴한 사용자" (withdrawn user) and the avatar and meta are cleared. The user row and external id remain, and so do the messages |
| Withdraw + take down messages | DELETE /v1/users/{userId}?purge_messages=true |
The account stays withdrawn; message text and the name stamped on each message are removed |
| Permanently delete a user | DELETE /v1/users/{userId}?purge=true |
The user row, reactions, read cursors, memberships, and bans are gone, and the names on messages are blanked. Message rows and sender.id remain |
| Delete a room | DELETE /v1/rooms/{roomId} |
The room is no longer visible and its key is freed, so you can create a room with the same key again. Message rows remain |
| Permanently delete a room | DELETE /v1/rooms/{roomId}?purge=true |
The room and every message in it are gone |
- Withdrawing (
withdraw) only anonymizes; it doesn't delete. The user row stays, and on its own a withdrawal leaves message text and the name stamped on each message. This is the SDK'susers.withdraw(userId, {purgeMessages}). - A personal-data deletion request goes all the way to
purge. First callDELETE /v1/users/{userId}?purge_messages=trueuntil the response'spurgeCappedisfalse, then callDELETE /v1/users/{userId}?purge=true. The second call returns 409 for a user who hasn't withdrawn. - A
purgecannot be undone. The request is accepted with 202 and the engine deletes in batches. It needs ansk_; a user token gets 403. If a job for the same target is already in progress you get that job back. After a userpurgethe external id can be used again, and old messages still carry the samesender.idstring, so don't reuse an old id for a new person. - A room
purgeis the SDK'srooms.delete(roomId, {purge: true}), which returns the 202job(since 0.8.2). A userpurgehas no SDK method, so call REST directly. - A
purgevalue other thantrueorfalseis a 400.
User list filters
GET /v1/users accepts these optional conditions. A value that can't be parsed is a 400, and when you change a
filter, drop the cursor and start from the first page again.
| Parameter | Value |
|---|---|
q |
Prefix match on externalId, or substring match on name. Case-insensitive |
status |
live, withdrawn, all (default) |
last_seen_after, last_seen_before |
RFC3339. A range on the last-seen time |
created_after, created_before |
RFC3339. A range on the sign-up time |
bots |
include (default), exclude, only |
*_after is inclusive and *_before is exclusive. Withdrawn users appear in the list, marked by deletedAt.
The type you pick when creating a room:
| Type | Who can read | Who can write | How to find it |
|---|---|---|---|
public |
Anyone | Anyone | Key or id. Shows up in discovery |
private |
Members only | Members only | Key or id |
channel |
Anyone | owner and admin only | Key or id. Shows up in discovery |
dm |
The two participants only | The two participants only | The pair of users. Has no key |
A room's canonical identifier is its id. key is a human-assigned alias (lobby, order-1234) that the
browser opens with chat.roomByKey(key). A key must be 1 to 128 characters of ASCII letters, digits, and
_ . : - (^[A-Za-z0-9_.:-]{1,128}$). Korean text or a space makes PUT /v1/rooms and PATCH answer
400, so put the human-readable title in name. A dm room has no key. A channel created from the server has no owner, so if someone
needs to post announcements with a user token, assign an owner or admin with the members API afterwards.
Rotating keys
Rotate an sk_ in this order: issue new → deploy backend → verify → revoke old.
- In the console's Keys screen, press New secret key. The full value appears only in that dialog.
- Replace the
sk_on your backend and deploy. Both keys are live at this point. - Check that a token signed with the new key connects, and that your server API calls go through.
- Revoke the old key in the console.
Do not revoke first. Turning off the old key stops the backend that signs with it, right then.
After you deploy, browsers still hold tokens signed with the old key. The engine checks the key that a
token's kid points at, so those tokens keep working as long as the old key isn't revoked. Once one
token lifetime has passed (one hour by default), everything in circulation has been re-signed with the new
key — revoke then and nobody is dropped. Revoking sooner is safe too: an old token is replaced on the next call.
Rotating a pk_ has the same shape, plus one thing: allowed origins live on the key, not on the app.
A pk_ with an empty list admits no browser page, so a new key has to carry the origins the current one
has. If only the origins change, don't rotate the key — edit the list on the same key by clicking its allowed origins
on the Keys screen.
Revocation takes effect immediately and cannot be undone. Losing a key doesn't lose data: users, rooms and messages belong to the app.
Separate production and development with apps, not keys. The app is the tenant, so the app is the data boundary. Create two apps and label them Production and Development in the console.