@kispi/chat 0.2.3 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +77 -250
- package/README.md +67 -242
- package/dist/{chunk-5QQRM7BH.js → chunk-WSBOTTBM.js} +21 -3
- package/dist/index.cjs +63 -40
- package/dist/index.d.cts +141 -388
- package/dist/index.d.ts +141 -388
- package/dist/index.js +46 -36
- package/dist/server/index.cjs +37 -9
- package/dist/server/index.d.cts +20 -14
- package/dist/server/index.d.ts +20 -14
- package/dist/server/index.js +22 -8
- package/package.json +1 -1
package/README.en.md
CHANGED
|
@@ -10,7 +10,8 @@ There are two entry points. `@kispi/chat` is the client for the browser and Node
|
|
|
10
10
|
npm install @kispi/chat
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
This document covers **the entire surface**.
|
|
13
|
+
This document covers **the entire surface**. Anything not here is internal and
|
|
14
|
+
changes without notice.
|
|
14
15
|
|
|
15
16
|
---
|
|
16
17
|
|
|
@@ -20,12 +21,9 @@ This document covers **the entire surface**. How to get started is here too.
|
|
|
20
21
|
|
|
21
22
|
| Option | Type | |
|
|
22
23
|
|---|---|---|
|
|
23
|
-
| `url` | `string` | **Required.** Pass the origin only. The SDK appends `/v1/ws?v=1` |
|
|
24
24
|
| `key` | `string` | **Required.** A `pk_`. It is public, so it is fine to put in the browser |
|
|
25
25
|
| `token` | `() => string \| Promise<string>` | **Required.** A user token signed by your backend. Called again on every connect and whenever REST gets a 401, so an expired one is never reused. A throw is retried with backoff; **throwing a `ChatError` means do not retry** (see below) |
|
|
26
|
-
| `
|
|
27
|
-
| `externalToken` | `() => string \| Promise<string>` | External mode. If given, it **takes precedence over `token`** (same order the server checks in). **The server still rejects it, so there is no use for it today** |
|
|
28
|
-
| `WebSocket` | `new (url) => WebSocketLike` | Implementation to use instead of the global. Injected in tests |
|
|
26
|
+
| `WebSocket` | `new (url) => WebSocketLike` | Implementation to use instead of the global |
|
|
29
27
|
| `fetch` | `typeof fetch` | Same as above |
|
|
30
28
|
|
|
31
29
|
Do not create `token` in the browser. Signing requires the `sk_`, and if the `sk_`
|
|
@@ -38,7 +36,7 @@ is in the browser, the whole app is open.
|
|
|
38
36
|
| `state` | `'connecting' \| 'open' \| 'reconnecting' \| 'closed'` |
|
|
39
37
|
| `user` | The connected user. `{id, name, avatar?}` — **the identity the server accepted from the token** (what `hello` carried). Use this instead of parsing your token response. Set once `connect()`/`reconnect()` resolves |
|
|
40
38
|
| `connectionId` | Identifier used for support requests and forced disconnects |
|
|
41
|
-
| `hello` | Everything the server sent on connect (
|
|
39
|
+
| `hello` | Everything the server sent on connect: `limits` (effective), `unread` (`{total, mentions, roomsCapped?}` — **absent is not zero, it means the count could not be read**, so recover with `unread()`), `warnings`, `serverTime`, `heartbeatMs` |
|
|
42
40
|
|
|
43
41
|
| Method | |
|
|
44
42
|
|---|---|
|
|
@@ -46,13 +44,12 @@ is in the browser, the whole app is open.
|
|
|
46
44
|
| `close()` | Disconnects. This one does not reconnect. Call `connect()` to come back |
|
|
47
45
|
| `reconnect()` | **Re-authenticates**: calls `token()` again and replaces the socket. Room handles, subscriptions and `messages` are kept, and the state goes `open → reconnecting → open` (never `closed`). Use it after a nickname or avatar change (below) |
|
|
48
46
|
| `room(roomId)` | Room handle. Same id, same object |
|
|
49
|
-
| `roomByKey(key)` | Handle for a room opened by key. The server tells you the id when you subscribe. **Does not create the room** — for a key that doesn't exist, `subscribe()` rejects with `not_found`
|
|
47
|
+
| `roomByKey(key)` | Handle for a room opened by key. The server tells you the id when you subscribe. **Does not create the room** — for a key that doesn't exist, `subscribe()` rejects with `not_found`. Rooms are created by the backend with `rooms.ensure()` |
|
|
50
48
|
| `rooms.list({cursor?, limit?})` | Rooms I'm a member of + unread + last message |
|
|
51
49
|
| `rooms.discover({type?, cursor?, limit?})` | Browse public rooms |
|
|
52
50
|
| `rooms.members(roomId).list/add/remove` | Member management |
|
|
53
|
-
| `unread()` |
|
|
51
|
+
| `unread()` | `{total, mentions, roomsCapped?, rooms}` — the **same field names** as `chat.hello?.unread` |
|
|
54
52
|
| `updateMe(meta)` | My `meta`. **`name` and `avatar` come from the token claims** |
|
|
55
|
-
| `send(type, data?, timeoutMs?)` | Raw frame. Only for calling things not on the surface |
|
|
56
53
|
|
|
57
54
|
| Event | |
|
|
58
55
|
|---|---|
|
|
@@ -77,7 +74,7 @@ off()
|
|
|
77
74
|
| `id` / `key` | Room identifiers. If opened by key, `id` is absent until you subscribe |
|
|
78
75
|
| `lastSeq` | The room's last seq as reported by the server |
|
|
79
76
|
| `presence` | `{count, users?, capped?}` |
|
|
80
|
-
| `hasOlder` | Whether `loadOlder()` has more past to read. Lets you decide whether to draw "load earlier" before the first `loadOlder()`. The same test as `loadOlder()`'s `hasMore
|
|
77
|
+
| `hasOlder` | Whether `loadOlder()` has more past to read. Lets you decide whether to draw "load earlier" before the first `loadOlder()`. The same test as `loadOlder()`'s `hasMore`; `false` while the list is empty. Re-read it on `messages` |
|
|
81
78
|
|
|
82
79
|
| Method | |
|
|
83
80
|
|---|---|
|
|
@@ -93,30 +90,35 @@ off()
|
|
|
93
90
|
| `typing()` | Typing indicator. Does not throw |
|
|
94
91
|
| `join()` / `leave()` | Membership |
|
|
95
92
|
| `presenceList()` | Who is in this room right now |
|
|
96
|
-
| `resume()` | Resubscribes after reconnecting. The SDK calls it for you |
|
|
97
93
|
|
|
98
|
-
Event names are **exactly the wire names
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
94
|
+
Event names are **exactly the wire names**, and the payloads are in the type declarations.
|
|
95
|
+
|
|
96
|
+
| Event | Payload |
|
|
97
|
+
|---|---|
|
|
98
|
+
| `message.created` / `message.updated` | `Message`. On `created`, `thread` is absent and `reactions` is empty |
|
|
99
|
+
| `message.deleted` | `{id, seq}`. `seq` is the one the message got **when it was published** |
|
|
100
|
+
| `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}` |
|
|
101
|
+
| `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
|
|
102
|
+
| `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left` are incremental, `users` replaces |
|
|
103
|
+
| `typing` | `{userId}` |
|
|
104
|
+
| `read` | `{userId, seq, threadId?}` |
|
|
105
|
+
| `member.joined` / `member.left` | `{userId, role?}` |
|
|
106
|
+
| `room.updated` | The room object (`unknown` — the server's own representation) |
|
|
107
|
+
| `room.deleted` | `{roomId}` |
|
|
108
|
+
| `custom` | Exactly the object `rooms.custom(roomId, payload)` sent |
|
|
102
109
|
|
|
103
110
|
The SDK emits three more that have no wire counterpart.
|
|
104
111
|
|
|
105
112
|
| Event | When |
|
|
106
113
|
|---|---|
|
|
107
114
|
| `messages` | Every time the list changes. **A new array each time; an emitted array is never touched again** |
|
|
108
|
-
| `error` | Reading history or filling a gap failed. **The room resubscribes itself
|
|
115
|
+
| `error` | Reading history or filling a gap failed. **The room resubscribes itself.** The retry button for a person is `subscribe()` |
|
|
109
116
|
| `reset` | The cursor was older than the retention period, so the list was discarded and refilled. **You must discard what you rendered** |
|
|
110
117
|
|
|
111
118
|
### Things to know
|
|
112
119
|
|
|
113
|
-
**`messages`
|
|
114
|
-
|
|
115
|
-
can put it straight into state that compares by reference. Rows follow the same rule: only a
|
|
116
|
-
row an event changed (edit, delete, reaction, thread) is a new object, and the others keep
|
|
117
|
-
their reference — **same reference means unchanged**, so row-level memoization is safe. The
|
|
118
|
-
converse is not promised: `reload()` and reconnect catch-up fetch rows from the server again,
|
|
119
|
-
so a different reference can carry the same content.
|
|
120
|
+
**`messages` is a new array every time, and only changed rows are new objects.** Put it
|
|
121
|
+
straight into state that compares by reference.
|
|
120
122
|
|
|
121
123
|
```ts
|
|
122
124
|
// Svelte 5
|
|
@@ -132,174 +134,33 @@ const messages = shallowRef<Message[]>([])
|
|
|
132
134
|
room.on('messages', m => (messages.value = m))
|
|
133
135
|
```
|
|
134
136
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
the
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
The
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
round trip late — the value is already determined by (you, emoji) and the server is idempotent,
|
|
149
|
-
so the ack has nothing new to say. If the server refuses (a limit, permissions) or the ack never
|
|
150
|
-
arrives (timeout, a dropped connection), the SDK rolls it back — unless something newer has
|
|
151
|
-
taken that spot in the meantime. A later press, a `reaction.*` event carrying your own `userId`,
|
|
152
|
-
and a page from `reload()` or a reconnect all beat a pending optimistic value, and a refusal
|
|
153
|
-
never resurrects a stale one. **The SDK owns this field**: an optimistic layer of your own on
|
|
154
|
-
top of it would give it two owners.
|
|
155
|
-
|
|
156
|
-
**The count (`reactions[].count`) is always the server's.** It is never moved locally. If
|
|
157
|
-
somebody else presses the same emoji while your ack is in flight, a local ±1 disagrees with the
|
|
158
|
-
number the server sends, and the event that would have corrected it has already gone by. Counts
|
|
159
|
-
move on `reaction.*` events only.
|
|
160
|
-
|
|
161
|
-
**Publishing (`send()`) is deliberately not optimistic.** A `before_publish` hook may rewrite
|
|
162
|
-
the body (an emoji filter, a link rewrite), so there is no value on the client to draw ahead of
|
|
163
|
-
time. A message joins the list when its `message.created` arrives. A "sending…" indicator is
|
|
164
|
-
your own view state, and unlike a reaction the SDK cannot decide it for you.
|
|
165
|
-
|
|
166
|
-
**Attach the past to the same list with `loadOlder()`.** `history()` is a direct read that
|
|
167
|
-
doesn't touch the list, so merging its results with the live list, filtering duplicates, and
|
|
168
|
-
handling `reset` and reconnects all fall to the consumer. `loadOlder()` puts those rows into
|
|
169
|
-
`messages`, so ordering, deduplication, deletion, reactions, and reconnects apply to them just
|
|
170
|
-
like any other row. Calling it several times concurrently still makes one request, and if
|
|
171
|
-
`hasMore` is `false` you're at the start of the room (or of the retention period).
|
|
172
|
-
`reset` or `reload()` discards the attached past as well.
|
|
173
|
-
|
|
174
|
-
**`hasOlder` and `loadOlder()` describe the SDK's list, not your window.** The SDK never trims
|
|
175
|
-
`room.messages` — if it holds 500 rows, all 500 are there. So if you render a 100-row slice of
|
|
176
|
-
the array you were handed, the other 400 are in `room.messages`, not on the server, and
|
|
177
|
-
`hasOlder === false` is the right answer (it means you are at the start of the room). Widening
|
|
178
|
-
the window is a re-read of `room.messages`; asking the server comes after that.
|
|
179
|
-
|
|
180
|
-
```ts
|
|
181
|
-
showLoadMore(room.hasOlder)
|
|
182
|
-
const { hasMore } = await room.loadOlder()
|
|
183
|
-
```
|
|
184
|
-
|
|
185
|
-
**It's safe to send once `await room.subscribe()` has finished.** That said, you may
|
|
186
|
-
`send` without waiting — if a subscription is in progress, `send` (and `react`, `markRead`,
|
|
187
|
-
`loadOlder`, etc.) waits for it before going out. If the subscription fails, it rejects with
|
|
188
|
-
that error. A `roomByKey` room that was never subscribed doesn't know its id, so it rejects
|
|
189
|
-
immediately with `closed`. Publishing while `chat.state` is `reconnecting` also rejects with
|
|
190
|
-
`closed` — the SDK does not queue things to send.
|
|
191
|
-
|
|
192
|
-
**Opening by key does not create a room.** `roomByKey(key).subscribe()` only looks up an
|
|
193
|
-
existing room, and if there is none it's `not_found`. Rooms are created by the backend with
|
|
194
|
-
the `sk_` (`rooms.ensure({key, type})` in `@kispi/chat/server` — it's get-or-create, returning
|
|
195
|
-
the room as-is if it exists, so it's fine to call on every page load). If you turn on the app
|
|
196
|
-
setting `client_room_create`, user tokens can also call `PUT /v1/rooms` (allowed types, key
|
|
197
|
-
pattern, 50-per-day limit), but since the `pk_` is public, that becomes a door through which
|
|
198
|
-
anyone can stamp out rooms. It is off by default, and we recommend keeping it off.
|
|
199
|
-
|
|
200
|
-
**The connection comes back on its own.** If the socket drops or `token()` throws, it
|
|
201
|
-
reconnects with exponential backoff (0.5 s up to 30 s, with jitter). **The first `connect()`
|
|
202
|
-
is the same** — on failure the `await` rejects so the caller knows, and retries continue in
|
|
203
|
-
the background (`state` is `reconnecting`, then `open` once it connects). The server's
|
|
204
|
-
connection limit (`rate_limited`) and server failures (`internal`) take the same path (a
|
|
205
|
-
limit waits as long as the server says). So there's no need to write your own retry loop.
|
|
206
|
-
|
|
207
|
-
**Subscribe rooms first; don't wait for the connection.** `subscribe()` waits until the
|
|
208
|
-
client is connected and then goes out, so even if the first `connect()` fails, the room fills
|
|
209
|
-
the moment a background retry connects. Putting `subscribe()` after `await chat.connect()`
|
|
210
|
-
means a rejected connect never reaches the subscribe line.
|
|
211
|
-
|
|
212
|
-
```ts
|
|
213
|
-
const room = chat.roomByKey('lobby')
|
|
214
|
-
room.on('messages', render)
|
|
215
|
-
chat.connect().catch(showOffline) // retries continue even on failure
|
|
216
|
-
await room.subscribe() // settles once connected
|
|
217
|
-
```
|
|
218
|
-
|
|
219
|
-
Three things stop it: `close()`, the server refusing authentication (`unauthorized`,
|
|
220
|
-
`forbidden` — repeating the same token would just be hammering the server), and **`token()`
|
|
221
|
-
throwing a `ChatError`**. That is how you say a failure is not worth retrying, like a ban or
|
|
222
|
-
an ended session:
|
|
223
|
-
|
|
224
|
-
```ts
|
|
225
|
-
token: async () => {
|
|
226
|
-
const res = await fetch('/api/chat-token')
|
|
227
|
-
if (res.status === 403) throw new ChatError('forbidden', 'banned') // not retried
|
|
228
|
-
if (!res.ok) throw new Error(`token ${res.status}`) // retried with backoff
|
|
229
|
-
return (await res.json()).token
|
|
230
|
-
}
|
|
231
|
-
```
|
|
232
|
-
|
|
233
|
-
The last two leave `state` at `closed` and report why on `chat.on('error')` — even mid-reconnect
|
|
234
|
-
or during a REST token refresh, where there is no caller to reject. Call `connect()` to come
|
|
235
|
-
back.
|
|
236
|
-
|
|
237
|
-
**After a nickname change, `reconnect()`.** The server reads the name and avatar from the
|
|
238
|
-
token's claims once, when the socket authenticates. So after your backend changes the name,
|
|
239
|
-
the next message on this connection still carries the old one. `reconnect()` calls `token()`
|
|
240
|
-
again, re-authenticates with the new claims, and the rooms carry on from what they hold.
|
|
241
|
-
`close()` + `connect()` works too, but passes through `closed` (your offline screen flashes)
|
|
242
|
-
and removes the page listeners. Frames still awaiting an ack on the old socket reject with
|
|
243
|
-
`closed`. When it resolves, `chat.user` is the new identity.
|
|
244
|
-
|
|
245
|
-
```ts
|
|
246
|
-
await api.updateNickname(name) // so your backend puts the new name in the next token()
|
|
247
|
-
await chat.reconnect()
|
|
248
|
-
chat.user?.name // the new name
|
|
249
|
-
```
|
|
250
|
-
|
|
251
|
-
**The SDK handles token expiry.** The socket authenticates only once on connect, so it stays
|
|
252
|
-
fine even when the token expires, but REST checks the token on every request. When REST gets a
|
|
253
|
-
401, the SDK calls `token()` again and retries **once**. A second 401 (origin, revoked token,
|
|
254
|
-
ban) is thrown as-is. There's no need to reconnect periodically.
|
|
255
|
-
|
|
256
|
-
The SDK neither caches the token nor hands it out. Cache inside `token()` (there's no need to
|
|
257
|
-
hit your backend on every call). **Don't reuse this token as the credential for your own
|
|
258
|
-
backend's API** — it is made to be presented to the chat engine, and mixing the two turns a
|
|
259
|
-
token leaked on one side into a key for the other. Use your own session for your own API.
|
|
260
|
-
|
|
261
|
-
**The SDK handles ordering and gap filling.** If frames arrive out of order or a reconnect
|
|
262
|
-
misses a range, it fills them in via REST. Gaps larger than one page (100) are filled
|
|
263
|
-
completely too.
|
|
264
|
-
|
|
265
|
-
**Reconnecting only recovers messages.** Because the history route covers messages only,
|
|
266
|
-
reactions on **older messages** or room renames that happened while disconnected are not
|
|
267
|
-
reflected. In that case, `await room.reload()`.
|
|
268
|
-
|
|
269
|
-
**`typing` is also delivered to the sender.** If you render "X is typing", skip your own
|
|
270
|
-
`userId`.
|
|
271
|
-
|
|
272
|
-
**Don't ignore `reset`.** If you keep appending to the old list, you're left with a gap that
|
|
273
|
-
nobody fills.
|
|
137
|
+
- **Don't ignore `reset`.** If you keep appending to the old list, you're left with a gap
|
|
138
|
+
that nobody fills.
|
|
139
|
+
- **Attach the past to the same list with `loadOlder()`.** `history()` is a direct read that
|
|
140
|
+
doesn't touch the list, so merging and deduplicating fall to you.
|
|
141
|
+
- **`typing` is also delivered to the sender.** If you render "X is typing", skip your own `userId`.
|
|
142
|
+
- **The connection comes back on its own.** It reconnects with exponential backoff, so don't
|
|
143
|
+
write your own retry loop.
|
|
144
|
+
- **The SDK handles token expiry.** When REST gets a 401 it calls `token()` again and retries
|
|
145
|
+
once. There's no need to reconnect periodically.
|
|
146
|
+
- **Throwing a `ChatError` from `token()` stops the client.** That is how you say a failure,
|
|
147
|
+
like a ban, is not worth retrying.
|
|
148
|
+
- **After a nickname or avatar change, `reconnect()`.** The server reads those values from the
|
|
149
|
+
token claims once, when the socket authenticates.
|
|
274
150
|
|
|
275
151
|
### Using it in the browser
|
|
276
152
|
|
|
277
|
-
You **must add the page's origin** to the `pk_`'s
|
|
278
|
-
|
|
153
|
+
You **must add the page's origin** to the `pk_`'s allowed origins. That's the only thing —
|
|
154
|
+
the server emits CORS headers itself, so there's no proxy to touch. Origins are edited on the
|
|
155
|
+
key screen in the console.
|
|
279
156
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
```
|
|
284
|
-
|
|
285
|
-
Scheme, host, and port must match **exactly**. `https://example.com` and
|
|
286
|
-
`https://www.example.com` are different origins, and so are `http://localhost:3000` and
|
|
287
|
-
`http://127.0.0.1:3000`. Add development origins separately.
|
|
288
|
-
|
|
289
|
-
**In Node it works without this setting.** WHATWG `fetch` and `WebSocket` don't send
|
|
290
|
-
`Origin` outside the browser, and the engine lets requests without an `Origin` through. That's
|
|
291
|
-
how code that's green in Node can return 401 only in the browser — this section is the reason.
|
|
292
|
-
|
|
293
|
-
If the origin isn't on the list, REST rejects with 401, and the message states the cause:
|
|
294
|
-
|
|
295
|
-
```
|
|
296
|
-
origin not allowed for this publishable key: add it to the key's allowed_origins
|
|
297
|
-
```
|
|
157
|
+
Scheme, host and port must match **exactly**. `https://example.com` and
|
|
158
|
+
`https://www.example.com`, `http://localhost:3000` and `http://127.0.0.1:3000` are different
|
|
159
|
+
origins. Add development origins separately.
|
|
298
160
|
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
shows nothing".
|
|
161
|
+
From an origin that isn't on the list it isn't just REST that fails — **the connection itself
|
|
162
|
+
is a 401.** An authentication refusal is a failure the SDK doesn't retry, so the client stops
|
|
163
|
+
at `closed`, and the reason arrives on `chat.on('error')`.
|
|
303
164
|
|
|
304
165
|
### Errors
|
|
305
166
|
|
|
@@ -317,7 +178,7 @@ try {
|
|
|
317
178
|
|
|
318
179
|
| Field | |
|
|
319
180
|
|---|---|
|
|
320
|
-
| `code` | `unauthorized`, `
|
|
181
|
+
| `code` | A union of the known values (`ChatErrorCode`), so a typo fails to compile. From the server: `unauthorized`, `forbidden`, `not_found`, `invalid`, `too_large`, `rate_limited`, `banned`, `moderation_denied`, `cursor_too_old`, `internal`. From the SDK: `timeout`, `closed`. A code the server adds later still type-checks |
|
|
321
182
|
| `retryAfterMs` | Wait time reported by the server when you hit a limit |
|
|
322
183
|
| `appCode` | Consumer-side code attached by a `before_publish` webhook when rejecting |
|
|
323
184
|
| `status` | HTTP status, if the error came from a REST call |
|
|
@@ -332,9 +193,7 @@ Uses the `sk_`. **Never put it in the browser.**
|
|
|
332
193
|
import { createChatServer } from '@kispi/chat/server'
|
|
333
194
|
|
|
334
195
|
const chat = createChatServer({
|
|
335
|
-
|
|
336
|
-
secretKey: process.env.CHAT_SECRET_KEY!,
|
|
337
|
-
keyId: process.env.CHAT_KEY_ID!,
|
|
196
|
+
secretKey: process.env.CHAT_SECRET_KEY!, // sk_…
|
|
338
197
|
webhookSecret: process.env.CHAT_WEBHOOK_SECRET,
|
|
339
198
|
guestSecret: process.env.CHAT_GUEST_SECRET, // only if you use guest()
|
|
340
199
|
})
|
|
@@ -365,23 +224,15 @@ app.post('/api/chat-token', (req, res) => {
|
|
|
365
224
|
})
|
|
366
225
|
```
|
|
367
226
|
|
|
368
|
-
**Never sign a `userId` handed back by the browser as-is.**
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
means nothing once the value is public.
|
|
373
|
-
|
|
374
|
-
`guest()` has the browser hold a **credential** instead of the id. It is
|
|
375
|
-
`g1.<userId>.<MAC>`, with the MAC made from `guestSecret`. If the returned credential
|
|
376
|
-
verifies, it signs with the id inside it; if it's missing or invalid, it signs a new guest
|
|
377
|
-
(`g_` + 22 random characters, `created: true`). Where possible, keep it in an `httpOnly`
|
|
378
|
-
cookie so page scripts can't read it.
|
|
227
|
+
**Never sign a `userId` handed back by the browser as-is.** `guest()` has the browser hold a
|
|
228
|
+
**credential** instead of the id — if it verifies, it signs with the id inside it; if it's
|
|
229
|
+
missing or invalid, it signs a new guest (`created: true`). Keep it in an `httpOnly` cookie
|
|
230
|
+
where you can.
|
|
379
231
|
|
|
380
232
|
| | |
|
|
381
233
|
|---|---|
|
|
382
|
-
| `guestSecret` | At least 32 characters. Keep it on the backend only. **Don't derive it from the `sk_`**
|
|
234
|
+
| `guestSecret` | At least 32 characters. Keep it on the backend only. **Don't derive it from the `sk_`** |
|
|
383
235
|
| Rotation | Pass an array: `[new, old]`. Signs with the first and verifies with all. A credential verified with an old one is re-signed with the same `userId` and returned, so it migrates on the next visit |
|
|
384
|
-
| Leak | If the secret leaks, anyone can become any guest. **Removing** the old one from the list turns every guest into a new person — losing identity is better than impersonation |
|
|
385
236
|
|
|
386
237
|
Guest ids start with `g_`. As long as logged-in users' ids don't start with `g_`, the two
|
|
387
238
|
spaces don't overlap.
|
|
@@ -392,41 +243,36 @@ spaces don't overlap.
|
|
|
392
243
|
|---|---|
|
|
393
244
|
| `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
|
|
394
245
|
| `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
|
|
395
|
-
| `users` | `list({cursor?, limit?})`, `update`, `
|
|
396
|
-
| `events` | `list({after?, limit?})` —
|
|
397
|
-
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` |
|
|
246
|
+
| `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?})` |
|
|
247
|
+
| `events` | `list({after?, limit?})` — catches up on missed webhook events |
|
|
248
|
+
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` — `tolerance` is in milliseconds |
|
|
249
|
+
|
|
250
|
+
`rooms.ensure` is get-or-create — it returns the room as-is if it exists, so it's fine to call
|
|
251
|
+
on every page load.
|
|
398
252
|
|
|
399
253
|
`rooms.presence(roomId)` is `{count}`; with `{full: true}` it adds `users` (at most 1000,
|
|
400
254
|
`capped: true` when cut). An empty room is `{count: 0}`, not a 404.
|
|
401
255
|
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
256
|
+
`rooms.custom(roomId, payload)` is a **control signal that is not stored**. `payload` is a JSON
|
|
257
|
+
object and arrives as-is at `room.on('custom', ...)`. It leaves no history, no unread and no
|
|
258
|
+
webhook, so send a signal that must survive a reconnect with
|
|
259
|
+
`messages.send(roomId, {kind:'system', ...})` instead.
|
|
260
|
+
|
|
261
|
+
`users.ban`'s `until` is **unix milliseconds and required.** For an indefinite ban, pick a
|
|
262
|
+
far-future time yourself.
|
|
263
|
+
|
|
264
|
+
`users.purgeMessages(userId)` clears that user's messages **without withdrawing them.** It does
|
|
265
|
+
a bounded amount per call, so call again while `purgeCapped` is `true`, and for spam **ban first**.
|
|
407
266
|
|
|
408
267
|
```ts
|
|
409
268
|
await chat.users.ban(userId, { until: Date.now() + 7 * 86_400_000, reason: 'spam' })
|
|
410
269
|
while ((await chat.users.purgeMessages(userId)).purgeCapped) {}
|
|
411
270
|
```
|
|
412
271
|
|
|
413
|
-
`users.
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
existence by connecting.
|
|
418
|
-
|
|
419
|
-
`users.list` is for the console. Reverse uid order, `limit` defaults to 50, max 100, `cursor`
|
|
420
|
-
is an opaque string and an empty string marks the last page. **Deleted users are included too,
|
|
421
|
-
and `deletedAt` marks them** — filter on it if you only want live users. This is the opposite of
|
|
422
|
-
the in-room lists (members, reactions, reads) hiding deleted users' ids, because those are lists
|
|
423
|
-
read by **other users**, whereas this one requires the `sk_`, so the reader is the very backend
|
|
424
|
-
that issued those ids.
|
|
425
|
-
|
|
426
|
-
`rooms.custom(roomId, payload)` is a **control signal that is not stored**. `payload` is a JSON
|
|
427
|
-
object and arrives as-is at `room.on('custom', ...)`. It leaves no history, no unread, and no
|
|
428
|
-
webhook, so anyone not connected at that moment never learns of it — for a signal that must be
|
|
429
|
-
received even after reconnecting, use `messages.send(roomId, {kind:'system', ...})`.
|
|
272
|
+
`users.list` is newest first, `limit` defaults to 50 and maxes at 100, and `cursor` is
|
|
273
|
+
an opaque string where an empty string marks the last page. **Withdrawn users are included too,
|
|
274
|
+
and `deletedAt` marks them.** `users.*` works only **after the person has connected at least
|
|
275
|
+
once** — users come into existence by connecting.
|
|
430
276
|
|
|
431
277
|
### Webhooks
|
|
432
278
|
|
|
@@ -439,30 +285,11 @@ app.post('/chat-hook', express.raw({ type: 'application/json' }), (req, res) =>
|
|
|
439
285
|
})
|
|
440
286
|
```
|
|
441
287
|
|
|
442
|
-
**It must be the raw body.**
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
**The signature covers the headers too.** The canonical string is
|
|
446
|
-
`` `${t}\n${event}\n${delivery}\n${rawBody}` `` and the order is fixed. So
|
|
447
|
-
`verify` reads `X-Chat-Event` and `X-Chat-Delivery` **before verifying**, and a replay with only
|
|
448
|
-
the headers swapped won't pass — `X-Chat-Delivery` is the deduplication key, so if it were
|
|
449
|
-
outside the signature, a single captured delivery could be counted as any number of new events.
|
|
288
|
+
**It must be the raw body.** Something parsed and re-serialized is a different string and
|
|
289
|
+
fails verification.
|
|
450
290
|
|
|
451
291
|
Keep three things. `verify` checks the signature and the timestamp (default 5 minutes),
|
|
452
292
|
**deduplication is on you** (by `delivery`), and you must respond with a 2xx within 10 seconds.
|
|
453
293
|
Going over counts as a failure and backoff begins.
|
|
454
294
|
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
## Development
|
|
458
|
-
|
|
459
|
-
```sh
|
|
460
|
-
pnpm install
|
|
461
|
-
pnpm build # ESM + CJS + type declarations
|
|
462
|
-
pnpm exec vitest run
|
|
463
|
-
pnpm exec tsc --noEmit
|
|
464
|
-
```
|
|
465
|
-
|
|
466
|
-
Tests use **injection**, not mocks. Swapping in `WebSocket` and `fetch` means there's no need to
|
|
467
|
-
imitate the server, and the integration-style files connect to a **live server** outright.
|
|
468
|
-
Running them requires Postgres and Redis.
|
|
295
|
+
The signature spec for other languages is in the [webhooks guide](https://chat.gravex.app/docs/webhooks).
|