@kispi/chat 0.3.0 → 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.
Files changed (3) hide show
  1. package/README.en.md +56 -229
  2. package/README.md +45 -218
  3. package/package.json +1 -1
package/README.en.md CHANGED
@@ -11,7 +11,7 @@ npm install @kispi/chat
11
11
  ```
12
12
 
13
13
  This document covers **the entire surface**. Anything not here is internal and
14
- changes without notice. How to get started is here too.
14
+ changes without notice.
15
15
 
16
16
  ---
17
17
 
@@ -29,12 +29,6 @@ changes without notice. How to get started is here too.
29
29
  Do not create `token` in the browser. Signing requires the `sk_`, and if the `sk_`
30
30
  is in the browser, the whole app is open.
31
31
 
32
- **You do not configure the address.** There is one engine, `wss://api.chat.gravex.app`,
33
- and the SDK holds it as a constant (readable as `ChatEndpoint`). REST is the same
34
- place with the scheme swapped. To separate development from production, **create a
35
- separate app in the console**: different apps have different `pk_`/`sk_`, rooms and
36
- users, which is the separation you actually want.
37
-
38
32
  ### `ChatClient`
39
33
 
40
34
  | Property | |
@@ -50,7 +44,7 @@ users, which is the separation you actually want.
50
44
  | `close()` | Disconnects. This one does not reconnect. Call `connect()` to come back |
51
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) |
52
46
  | `room(roomId)` | Room handle. Same id, same object |
53
- | `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` (see below) |
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()` |
54
48
  | `rooms.list({cursor?, limit?})` | Rooms I'm a member of + unread + last message |
55
49
  | `rooms.discover({type?, cursor?, limit?})` | Browse public rooms |
56
50
  | `rooms.members(roomId).list/add/remove` | Member management |
@@ -80,7 +74,7 @@ off()
80
74
  | `id` / `key` | Room identifiers. If opened by key, `id` is absent until you subscribe |
81
75
  | `lastSeq` | The room's last seq as reported by the server |
82
76
  | `presence` | `{count, users?, capped?}` |
83
- | `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` (the first row is above the room's retention floor); `false` while the list is empty. Re-read it on `messages` |
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` |
84
78
 
85
79
  | Method | |
86
80
  |---|---|
@@ -97,8 +91,7 @@ off()
97
91
  | `join()` / `leave()` | Membership |
98
92
  | `presenceList()` | Who is in this room right now |
99
93
 
100
- Event names are **exactly the wire names**, and the payloads are typed after the
101
- shapes in `docs/protocol.md`.
94
+ Event names are **exactly the wire names**, and the payloads are in the type declarations.
102
95
 
103
96
  | Event | Payload |
104
97
  |---|---|
@@ -119,18 +112,13 @@ The SDK emits three more that have no wire counterpart.
119
112
  | Event | When |
120
113
  |---|---|
121
114
  | `messages` | Every time the list changes. **A new array each time; an emitted array is never touched again** |
122
- | `error` | Reading history or filling a gap failed. **The room resubscribes itself** (from 1 s, doubling, 5 tries while connected, again on every reconnect). The retry button for a person is `subscribe()` |
115
+ | `error` | Reading history or filling a gap failed. **The room resubscribes itself.** The retry button for a person is `subscribe()` |
123
116
  | `reset` | The cursor was older than the retention period, so the list was discarded and refilled. **You must discard what you rendered** |
124
117
 
125
118
  ### Things to know
126
119
 
127
- **`messages` changes reference.** Every time the list changes a new array comes out, and
128
- an array once emitted, along with the row objects in it, is never modified afterward. So you
129
- can put it straight into state that compares by reference. Rows follow the same rule: only a
130
- row an event changed (edit, delete, reaction, thread) is a new object, and the others keep
131
- their reference — **same reference means unchanged**, so row-level memoization is safe. The
132
- converse is not promised: `reload()` and reconnect catch-up fetch rows from the server again,
133
- 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.
134
122
 
135
123
  ```ts
136
124
  // Svelte 5
@@ -146,173 +134,33 @@ const messages = shallowRef<Message[]>([])
146
134
  room.on('messages', m => (messages.value = m))
147
135
  ```
148
136
 
149
- Wrapping it in `$state` (a deep proxy) or `ref` works, but does unnecessary work.
150
-
151
- **Reactions: `reactions` is everyone's counts, `myReactions` is the emoji you pressed.**
152
- The SDK keeps both live — counts from the `count` on `reaction.*` events, `myReactions` from
153
- those events when their `userId` is `chat.user.id` (including presses from your other tabs and
154
- devices) and from your own `react()`/`unreact()`. Both are overwrites, not
155
- increments, so getting the event and the ack never counts twice. Only the changed row is a new
156
- object.
157
-
158
- **`myReactions` moves the moment you press.** `react()`/`unreact()` update that row's
159
- `myReactions` and emit `messages` **before** the frame goes out, so the press does not feel a
160
- round trip late — the value is already determined by (you, emoji) and the server is idempotent,
161
- so the ack has nothing new to say. If the server refuses (a limit, permissions) or the ack never
162
- arrives (timeout, a dropped connection), the SDK rolls it back — unless something newer has
163
- taken that spot in the meantime. A later press, a `reaction.*` event carrying your own `userId`,
164
- and a page from `reload()` or a reconnect all beat a pending optimistic value, and a refusal
165
- never resurrects a stale one. **The SDK owns this field**: an optimistic layer of your own on
166
- top of it would give it two owners.
167
-
168
- **The count (`reactions[].count`) is always the server's.** It is never moved locally. If
169
- somebody else presses the same emoji while your ack is in flight, a local ±1 disagrees with the
170
- number the server sends, and the event that would have corrected it has already gone by. Counts
171
- move on `reaction.*` events only.
172
-
173
- **Publishing (`send()`) is deliberately not optimistic.** A `before_publish` hook may rewrite
174
- the body (an emoji filter, a link rewrite), so there is no value on the client to draw ahead of
175
- time. A message joins the list when its `message.created` arrives. A "sending…" indicator is
176
- your own view state, and unlike a reaction the SDK cannot decide it for you.
177
-
178
- **Attach the past to the same list with `loadOlder()`.** `history()` is a direct read that
179
- doesn't touch the list, so merging its results with the live list, filtering duplicates, and
180
- handling `reset` and reconnects all fall to the consumer. `loadOlder()` puts those rows into
181
- `messages`, so ordering, deduplication, deletion, reactions, and reconnects apply to them just
182
- like any other row. Calling it several times concurrently still makes one request, and if
183
- `hasMore` is `false` you're at the start of the room (or of the retention period).
184
- `reset` or `reload()` discards the attached past as well.
185
-
186
- **`hasOlder` and `loadOlder()` describe the SDK's list, not your window.** The SDK never trims
187
- `room.messages` — if it holds 500 rows, all 500 are there. So if you render a 100-row slice of
188
- the array you were handed, the other 400 are in `room.messages`, not on the server, and
189
- `hasOlder === false` is the right answer (it means you are at the start of the room). Widening
190
- the window is a re-read of `room.messages`; asking the server comes after that.
191
-
192
- ```ts
193
- showLoadMore(room.hasOlder)
194
- const { hasMore } = await room.loadOlder()
195
- ```
196
-
197
- **It's safe to send once `await room.subscribe()` has finished.** That said, you may
198
- `send` without waiting — if a subscription is in progress, `send` (and `react`, `markRead`,
199
- `loadOlder`, etc.) waits for it before going out. If the subscription fails, it rejects with
200
- that error. A `roomByKey` room that was never subscribed doesn't know its id, so it rejects
201
- immediately with `closed`. Publishing while `chat.state` is `reconnecting` also rejects with
202
- `closed` — the SDK does not queue things to send.
203
-
204
- **Opening by key does not create a room.** `roomByKey(key).subscribe()` only looks up an
205
- existing room, and if there is none it's `not_found`. Rooms are created by the backend with
206
- the `sk_` (`rooms.ensure({key, type})` in `@kispi/chat/server` — it's get-or-create, returning
207
- the room as-is if it exists, so it's fine to call on every page load). There is an app setting
208
- that lets user tokens create rooms, but it is off by default and can't be turned on from the
209
- console — since the `pk_` is public, turning it on opens a door through which anyone can stamp
210
- out rooms.
211
-
212
- **The connection comes back on its own.** If the socket drops or `token()` throws, it
213
- reconnects with exponential backoff (0.5 s up to 30 s, with jitter). **The first `connect()`
214
- is the same** — on failure the `await` rejects so the caller knows, and retries continue in
215
- the background (`state` is `reconnecting`, then `open` once it connects). The server's
216
- connection limit (`rate_limited`) and server failures (`internal`) take the same path (a
217
- limit waits as long as the server says). So there's no need to write your own retry loop.
218
-
219
- **Subscribe rooms first; don't wait for the connection.** `subscribe()` waits until the
220
- client is connected and then goes out, so even if the first `connect()` fails, the room fills
221
- the moment a background retry connects. Putting `subscribe()` after `await chat.connect()`
222
- means a rejected connect never reaches the subscribe line.
223
-
224
- ```ts
225
- const room = chat.roomByKey('lobby')
226
- room.on('messages', render)
227
- chat.connect().catch(showOffline) // retries continue even on failure
228
- await room.subscribe() // settles once connected
229
- ```
230
-
231
- Three things stop it: `close()`, the server refusing authentication (`unauthorized`,
232
- `forbidden` — repeating the same token would just be hammering the server), and **`token()`
233
- throwing a `ChatError`**. That is how you say a failure is not worth retrying, like a ban or
234
- an ended session:
235
-
236
- ```ts
237
- token: async () => {
238
- const res = await fetch('/api/chat-token')
239
- if (res.status === 403) throw new ChatError('forbidden', 'banned') // not retried
240
- if (!res.ok) throw new Error(`token ${res.status}`) // retried with backoff
241
- return (await res.json()).token
242
- }
243
- ```
244
-
245
- The last two leave `state` at `closed` and report why on `chat.on('error')` — even mid-reconnect
246
- or during a REST token refresh, where there is no caller to reject. Call `connect()` to come
247
- back.
248
-
249
- **After a nickname change, `reconnect()`.** The server reads the name and avatar from the
250
- token's claims once, when the socket authenticates. So after your backend changes the name,
251
- the next message on this connection still carries the old one. `reconnect()` calls `token()`
252
- again, re-authenticates with the new claims, and the rooms carry on from what they hold.
253
- `close()` + `connect()` works too, but passes through `closed` (your offline screen flashes)
254
- and removes the page listeners. Frames still awaiting an ack on the old socket reject with
255
- `closed`. When it resolves, `chat.user` is the new identity.
256
-
257
- ```ts
258
- await api.updateNickname(name) // so your backend puts the new name in the next token()
259
- await chat.reconnect()
260
- chat.user?.name // the new name
261
- ```
262
-
263
- **The SDK handles token expiry.** The socket authenticates only once on connect, so it stays
264
- fine even when the token expires, but REST checks the token on every request. When REST gets a
265
- 401, the SDK calls `token()` again and retries **once**. A second 401 (origin, revoked token,
266
- ban) is thrown as-is. There's no need to reconnect periodically.
267
-
268
- The SDK neither caches the token nor hands it out. Cache inside `token()` (there's no need to
269
- hit your backend on every call). **Don't reuse this token as the credential for your own
270
- backend's API** — it is made to be presented to the chat engine, and mixing the two turns a
271
- token leaked on one side into a key for the other. Use your own session for your own API.
272
-
273
- **The SDK handles ordering and gap filling.** If frames arrive out of order or a reconnect
274
- misses a range, it fills them in via REST. Gaps larger than one page (100) are filled
275
- completely too.
276
-
277
- **Reconnecting only recovers messages.** Because the history route covers messages only,
278
- reactions on **older messages** or room renames that happened while disconnected are not
279
- reflected. In that case, `await room.reload()`.
280
-
281
- **`typing` is also delivered to the sender.** If you render "X is typing", skip your own
282
- `userId`.
283
-
284
- **Don't ignore `reset`.** If you keep appending to the old list, you're left with a gap that
285
- 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.
286
150
 
287
151
  ### Using it in the browser
288
152
 
289
- You **must add the page's origin** to the `pk_`'s `allowed_origins`. That's the only thing.
290
- The server emits CORS headers itself, so there's no need to touch nginx or any other proxy.
291
-
292
- ```sh
293
- chat-server app create my-app --origins https://example.com
294
- chat-server key create <app-id> pk --origins https://staging.example.com
295
- ```
296
-
297
- Scheme, host, and port must match **exactly**. `https://example.com` and
298
- `https://www.example.com` are different origins, and so are `http://localhost:3000` and
299
- `http://127.0.0.1:3000`. Add development origins separately.
300
-
301
- **In Node it works without this setting.** WHATWG `fetch` and `WebSocket` don't send
302
- `Origin` outside the browser, and the engine lets requests without an `Origin` through. That's
303
- how code that's green in Node can return 401 only in the browser — this section is the reason.
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.
304
156
 
305
- If the origin isn't on the list, REST rejects with 401, and the message states the cause:
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.
306
160
 
307
- ```
308
- origin not allowed for this publishable key: add it to the key's allowed_origins
309
- ```
310
-
311
- **The connection consults the same list.** WebSocket isn't subject to browser CORS, but the
312
- engine checks the `pk_`'s `allowed_origins` itself during the handshake. So from an origin
313
- that isn't on the list, it isn't just REST that fails — the connection is refused too, and an
314
- authentication refusal is a failure the SDK doesn't retry, so the client stops at `closed`.
315
- The reason arrives on `chat.on('error')`.
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')`.
316
164
 
317
165
  ### Errors
318
166
 
@@ -351,10 +199,6 @@ const chat = createChatServer({
351
199
  })
352
200
  ```
353
201
 
354
- One key is all it takes. The value that tells the server which key signed a token
355
- (`kid`) lives inside the `sk_`, so the SDK reads it from there — you do not pass
356
- the console's key ID separately. The address is a constant here too.
357
-
358
202
  ### `chat.token(input): string`
359
203
 
360
204
  A local signature that doesn't touch the network.
@@ -380,23 +224,15 @@ app.post('/api/chat-token', (req, res) => {
380
224
  })
381
225
  ```
382
226
 
383
- **Never sign a `userId` handed back by the browser as-is.** A guest id is not a secret — it
384
- goes out as `sender.id` on every message in the room. A token endpoint that "re-signs the id
385
- the browser kept" gives that guest's identity to anyone who copied the id from someone's
386
- message. A format check (`g_` + UUID regex) doesn't prevent this. A UUID being hard to guess
387
- means nothing once the value is public.
388
-
389
- `guest()` has the browser hold a **credential** instead of the id. It is
390
- `g1.<userId>.<MAC>`, with the MAC made from `guestSecret`. If the returned credential
391
- verifies, it signs with the id inside it; if it's missing or invalid, it signs a new guest
392
- (`g_` + 22 random characters, `created: true`). Where possible, keep it in an `httpOnly`
393
- 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.
394
231
 
395
232
  | | |
396
233
  |---|---|
397
- | `guestSecret` | At least 32 characters. Keep it on the backend only. **Don't derive it from the `sk_`** — the `sk_` is a key you rotate if it leaks, and rotating it must not turn every guest into a new person |
234
+ | `guestSecret` | At least 32 characters. Keep it on the backend only. **Don't derive it from the `sk_`** |
398
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 |
399
- | 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 |
400
236
 
401
237
  Guest ids start with `g_`. As long as logged-in users' ids don't start with `g_`, the two
402
238
  spaces don't overlap.
@@ -408,40 +244,35 @@ spaces don't overlap.
408
244
  | `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
409
245
  | `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
410
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?})` |
411
- | `events` | `list({after?, limit?})` — the outbox. Catches up on missed webhooks |
247
+ | `events` | `list({after?, limit?})` — catches up on missed webhook events |
412
248
  | `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` — `tolerance` is in milliseconds |
413
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.
252
+
414
253
  `rooms.presence(roomId)` is `{count}`; with `{full: true}` it adds `users` (at most 1000,
415
254
  `capped: true` when cut). An empty room is `{count: 0}`, not a 404.
416
255
 
417
- **`users.purgeMessages(userId)` is moderation** — it deletes every message the user sent in the
418
- app (tombstones: seq is untouched, and watching clients get `message.deleted`) **without
419
- withdrawing them.** The name stays. For spam, **ban first**, then call it — a message posted
420
- while it runs is not in its listing. It does a bounded amount per call, so call again while
421
- `purgeCapped` is `true`. A withdrawn user is a 404 (use `withdraw(userId, {purgeMessages: true})`).
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**.
422
266
 
423
267
  ```ts
424
268
  await chat.users.ban(userId, { until: Date.now() + 7 * 86_400_000, reason: 'spam' })
425
269
  while ((await chat.users.purgeMessages(userId)).purgeCapped) {}
426
270
  ```
427
271
 
428
- `users.ban`'s `until` is **unix milliseconds and required.** For an indefinite ban, pick a
429
- far-future time yourself — it goes into the audit log as a decision, not an accident.
430
-
431
- `users.*` works only **after the person has connected at least once**. Users come into
432
- existence by connecting.
433
-
434
- `users.list` is for the console. Reverse uid order, `limit` defaults to 50, max 100, `cursor`
435
- is an opaque string and an empty string marks the last page. **Deleted users are included too,
436
- and `deletedAt` marks them** — filter on it if you only want live users. This is the opposite of
437
- the in-room lists (members, reactions, reads) hiding deleted users' ids, because those are lists
438
- read by **other users**, whereas this one requires the `sk_`, so the reader is the very backend
439
- that issued those ids.
440
-
441
- `rooms.custom(roomId, payload)` is a **control signal that is not stored**. `payload` is a JSON
442
- object and arrives as-is at `room.on('custom', ...)`. It leaves no history, no unread, and no
443
- webhook, so anyone not connected at that moment never learns of it — for a signal that must be
444
- 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.
445
276
 
446
277
  ### Webhooks
447
278
 
@@ -454,15 +285,11 @@ app.post('/chat-hook', express.raw({ type: 'application/json' }), (req, res) =>
454
285
  })
455
286
  ```
456
287
 
457
- **It must be the raw body.** The MAC is over the bytes the server sent, and something parsed
458
- and re-serialized is a different string.
459
-
460
- **The signature covers the headers too.** The canonical string is
461
- `` `${t}\n${event}\n${delivery}\n${rawBody}` `` and the order is fixed. So
462
- `verify` reads `X-Chat-Event` and `X-Chat-Delivery` **before verifying**, and a replay with only
463
- the headers swapped won't pass — `X-Chat-Delivery` is the deduplication key, so if it were
464
- 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.
465
290
 
466
291
  Keep three things. `verify` checks the signature and the timestamp (default 5 minutes),
467
292
  **deduplication is on you** (by `delivery`), and you must respond with a 2xx within 10 seconds.
468
293
  Going over counts as a failure and backoff begins.
294
+
295
+ The signature spec for other languages is in the [webhooks guide](https://chat.gravex.app/docs/webhooks).
package/README.md CHANGED
@@ -11,7 +11,7 @@ npm install @kispi/chat
11
11
  ```
12
12
 
13
13
  이 문서가 **표면 전체**를 적는다. 여기 없는 것은 내부 구현이고, 다음 버전에
14
- 말 없이 바뀐다. 시작하는 법도 여기 있다.
14
+ 말 없이 바뀐다.
15
15
 
16
16
  ---
17
17
 
@@ -29,11 +29,6 @@ npm install @kispi/chat
29
29
  `token`을 브라우저에서 만들지 않는다. 서명에 `sk_`가 필요하고, `sk_`가
30
30
  브라우저에 있으면 그 앱 전체가 열린다.
31
31
 
32
- **주소는 설정하지 않는다.** 엔진은 `wss://api.chat.gravex.app` 하나이고
33
- SDK가 상수로 들고 있다(`ChatEndpoint`로 읽을 수 있다). REST도 같은 곳이다 —
34
- 스킴만 바뀐다. 개발용과 운영용을 나누려면 **콘솔에서 앱을 따로 만든다**:
35
- 앱이 다르면 `pk_`·`sk_`·방·유저가 전부 다르고, 그것이 실제로 원하는 분리다.
36
-
37
32
  ### `ChatClient`
38
33
 
39
34
  | 프로퍼티 | |
@@ -49,7 +44,7 @@ SDK가 상수로 들고 있다(`ChatEndpoint`로 읽을 수 있다). REST도 같
49
44
  | `close()` | 끊는다. 이건 재접속하지 않는다. 다시 붙으려면 `connect()` |
50
45
  | `reconnect()` | **다시 인증한다**: `token()`을 다시 불러 소켓을 바꾼다. 방 핸들과 구독, `messages`는 그대로이고 상태는 `open → reconnecting → open`이다(`closed`를 거치지 않는다). 닉네임·아바타를 바꾼 뒤에 쓴다(아래) |
51
46
  | `room(roomId)` | 방 핸들. 같은 id면 같은 객체 |
52
- | `roomByKey(key)` | 키로 여는 방 핸들. 구독할 때 서버가 id를 알려 준다. **방을 만들지 않는다** — 없는 키면 `subscribe()`가 `not_found`로 거절한다(아래) |
47
+ | `roomByKey(key)` | 키로 여는 방 핸들. 구독할 때 서버가 id를 알려 준다. **방을 만들지 않는다** — 없는 키면 `subscribe()`가 `not_found`로 거절한다. 방은 백엔드가 `rooms.ensure()`로 만든다 |
53
48
  | `rooms.list({cursor?, limit?})` | 내가 멤버인 방 + unread + 마지막 메시지 |
54
49
  | `rooms.discover({type?, cursor?, limit?})` | 공개 방 탐색 |
55
50
  | `rooms.members(roomId).list/add/remove` | 멤버 관리 |
@@ -79,7 +74,7 @@ off()
79
74
  | `id` / `key` | 방 식별자. 키로 열었으면 구독 전까지 `id`가 없다 |
80
75
  | `lastSeq` | 서버가 알려 준 방의 마지막 seq |
81
76
  | `presence` | `{count, users?, capped?}` |
82
- | `hasOlder` | `loadOlder()`로 더 읽을 과거가 있는지. 첫 `loadOlder()` 전에 "이전 메시지" 버튼을 그릴지 정할 때 쓴다. `loadOlder()`의 `hasMore`와 같은 판정(맨 위 행이 방의 보존 하한 위에 있는지)이고, 목록이 비었으면 `false`. `messages` 이벤트 때 다시 읽는다 |
77
+ | `hasOlder` | `loadOlder()`로 더 읽을 과거가 있는지. 첫 `loadOlder()` 전에 "이전 메시지" 버튼을 그릴지 정할 때 쓴다. `loadOlder()`의 `hasMore`와 같은 판정이고, 목록이 비었으면 `false`. `messages` 이벤트 때 다시 읽는다 |
83
78
 
84
79
  | 메서드 | |
85
80
  |---|---|
@@ -96,8 +91,7 @@ off()
96
91
  | `join()` / `leave()` | 멤버십 |
97
92
  | `presenceList()` | 지금 이 방에 있는 사람 |
98
93
 
99
- 이벤트 이름은 **와이어의 이름 그대로**다. 페이로드는 `docs/protocol.md`의
100
- 모양대로 타입이 붙어 있다.
94
+ 이벤트 이름은 **와이어의 이름 그대로**이고, 페이로드는 타입 선언에 있다.
101
95
 
102
96
  | 이벤트 | 페이로드 |
103
97
  |---|---|
@@ -118,17 +112,12 @@ off()
118
112
  | 이벤트 | 언제 |
119
113
  |---|---|
120
114
  | `messages` | 목록이 바뀔 때마다. **매번 새 배열이고, 내보낸 배열은 다시 건드리지 않는다** |
121
- | `error` | 히스토리를 읽거나 구멍을 메우는 데 실패했다. **방이 스스로 다시 구독한다**(1초부터 두 배씩, 연결된 동안 5번, 재접속마다 다시). 사람이 누를 재시도 버튼은 `subscribe()` |
115
+ | `error` | 히스토리를 읽거나 구멍을 메우는 데 실패했다. **방이 스스로 다시 구독한다.** 사람이 누를 재시도 버튼은 `subscribe()` |
122
116
  | `reset` | 커서가 보존 기간보다 오래돼 목록을 버리고 다시 채웠다. **렌더한 것을 버려야 한다** |
123
117
 
124
118
  ### 알아 둘 것
125
119
 
126
- **`messages`는 참조가 바뀐다.** 목록이 바뀔 때마다 새 배열이 나오고, 한 번 내보낸
127
- 배열과 그 안의 행 객체는 이후에 고쳐지지 않는다. 그래서 참조로 비교하는 상태에 그대로
128
- 넣으면 된다. 행도 마찬가지로, 이벤트(수정, 삭제, 리액션, 스레드)가 바꾼 행만 새 객체이고
129
- 나머지 행은 참조가 그대로다 — **참조가 같으면 바뀌지 않은 것**이니 행 단위 memo에 써도
130
- 된다. 반대는 약속하지 않는다: `reload()`와 재접속 따라잡기는 같은 내용의 행을 서버에서
131
- 새로 받아 오므로, 참조가 달라도 내용은 같을 수 있다.
120
+ **`messages`는 매번 새 배열이고, 바뀐 행만 새 객체다.** 참조로 비교하는 상태에 그대로 넣는다.
132
121
 
133
122
  ```ts
134
123
  // Svelte 5
@@ -144,162 +133,27 @@ const messages = shallowRef<Message[]>([])
144
133
  room.on('messages', m => (messages.value = m))
145
134
  ```
146
135
 
147
- `$state`(깊은 프록시)나 `ref`로 감싸도 동작하지만 필요 없는 일을 한다.
148
-
149
- **리액션: `reactions`는 모두의 개수, `myReactions`는 내가 누른 이모지다.** 둘 다
150
- SDK가 라이브로 맞춘다 — 개수는 `reaction.*` 이벤트의 `count`로, `myReactions`는 그
151
- 이벤트의 `userId`가 `chat.user.id`일 때(다른 탭·기기에서 누른 것 포함)와 내
152
- `react()`/`unreact()`로. 둘 다 더하기가 아니라 덮어쓰기라 이벤트와 ack가 모두
153
- 와도 두 번 세지 않는다. 바뀐 행만 새 객체다.
154
-
155
- **`myReactions`는 누른 즉시 바뀐다.** `react()`/`unreact()`는 프레임을 보내기 **전에**
156
- 그 행의 `myReactions`를 고치고 `messages`를 내보낸다. 그래서 누른 느낌이 왕복만큼
157
- 늦지 않는다 — 누른 값은 (나, 이모지)로 이미 정해져 있고 서버는 멱등이라, ack가
158
- 새로 알려 줄 것이 없다. 서버가 거절하거나(한도, 권한) ack가 못 오면(타임아웃,
159
- 끊김) 되돌린다. 단, 그 사이 더 새로운 값이 자리를 차지했으면 그대로 둔다: 뒤에 누른
160
- 값, 내 `userId`가 실린 `reaction.*` 이벤트, `reload()`나 재접속이 가져온 페이지가
161
- 모두 대기 중인 낙관값을 이긴다. 거절이 낡은 값을 되살리는 일은 없다.
162
- **이 필드의 주인은 SDK다** — 위에 자기 낙관 계층을 덧대면 주인이 둘이 된다.
163
-
164
- **개수(`reactions[].count`)는 늘 서버 값이다.** 로컬에서 ±1하지 않는다. ack를
165
- 기다리는 사이 남이 같은 이모지를 누르면 로컬 계산은 서버가 보낼 수와 어긋나고,
166
- 그 차이를 고쳐 줄 이벤트는 이미 지나갔다. 개수는 `reaction.*` 이벤트가 옮긴다.
167
-
168
- **발행(`send()`)은 일부러 낙관적이지 않다.** `before_publish` 훅이 본문을 바꿀 수
169
- 있어서(이모지 필터, 링크 치환) 미리 그릴 값이 클라이언트에 없다. 메시지는
170
- `message.created`가 올 때 목록에 들어간다. 보내는 중 표시가 필요하면 그것은 소비자의
171
- 화면 상태이고, 리액션과 달리 SDK가 대신 정해 줄 수 없다.
172
-
173
- **과거는 `loadOlder()`로 같은 목록에 붙인다.** `history()`는 목록을 건드리지 않는
174
- 직접 읽기라, 그 결과를 라이브 목록과 합치고 중복을 거르고 `reset`과 재접속을
175
- 처리하는 일이 전부 소비자 몫이 된다. `loadOlder()`는 그 행들을 `messages`에 넣으므로
176
- 정렬·중복 제거·삭제·리액션·재접속이 다른 행과 똑같이 적용된다. 동시에 여러 번
177
- 불러도 요청은 하나이고, `hasMore`가 `false`면 방(또는 보존 기간)의 맨 앞이다.
178
- `reset`이나 `reload()`는 붙인 과거도 함께 버린다.
179
-
180
- **`hasOlder`와 `loadOlder()`는 SDK의 목록을 말한다, 당신의 창이 아니라.** SDK는
181
- `room.messages`를 줄이지 않는다 — 500건을 들고 있으면 500건이 다 거기 있다. 화면
182
- 성능 때문에 받은 배열을 100건으로 잘라 그리고 있다면, 더 보여 줄 400건은 서버가
183
- 아니라 `room.messages`에 있다. 그때 `hasOlder`가 `false`인 것은 맞는 답이다(방의
184
- 맨 앞이라는 뜻이다). 창을 넓히는 일은 `room.messages`를 다시 읽는 것이고, 서버에
185
- 묻는 것은 그 다음이다.
186
-
187
- ```ts
188
- showLoadMore(room.hasOlder)
189
- const { hasMore } = await room.loadOlder()
190
- ```
191
-
192
- **보내도 되는 때는 `await room.subscribe()`가 끝난 때다.** 다만 기다리지 않고
193
- `send`해도 된다 — 구독이 진행 중이면 `send`(와 `react`, `markRead`, `loadOlder` 등)가
194
- 그것을 기다렸다가 나간다. 구독이 실패하면 그 에러로 거절한다. 구독한 적도 없는
195
- `roomByKey` 방은 id를 모르므로 곧바로 `closed`로 거절한다. `chat.state`가
196
- `reconnecting`인 동안의 발행도 `closed`로 거절한다 — SDK는 보낼 것을 쌓아 두지 않는다.
197
-
198
- **키로 연다고 방이 생기지 않는다.** `roomByKey(key).subscribe()`는 있는 방을 찾기만
199
- 하고, 없으면 `not_found`다. 방은 백엔드가 `sk_`로 만든다
200
- (`@kispi/chat/server`의 `rooms.ensure({key, type})` — 있으면 그대로 돌려주는
201
- get-or-create라 페이지를 열 때마다 불러도 된다). 유저 토큰으로 방을 만들게 하는 앱 설정도
202
- 있지만 기본은 꺼져 있고 콘솔에서 켤 수 없다 — `pk_`는 공개값이라, 켜면 누구나 방을
203
- 찍어낼 수 있는 문이 된다.
204
-
205
- **연결은 알아서 돌아온다.** 소켓이 끊기거나 `token()`이 던지면 지수 백오프(0.5초에서
206
- 30초까지, 지터)로 다시 붙는다. **첫 `connect()`도 같다** — 실패하면 `await`는 거절해서
207
- 호출자가 알게 하고, 재시도는 백그라운드에서 이어진다(`state`가 `reconnecting`, 붙으면
208
- `open`). 서버의 접속 한도(`rate_limited`)와 서버 장애(`internal`)도 같은 길로 다시
209
- 붙는다(한도는 서버가 말한 만큼 기다린다). 그래서 재시도 루프를 직접 짤 필요가 없다.
210
-
211
- 방은 **연결을 기다리지 말고 먼저 구독해 둔다.** `subscribe()`는 붙을 때까지 기다렸다가
212
- 나가므로, 첫 `connect()`가 실패해도 백그라운드 재시도가 붙는 순간 방이 채워진다.
213
- `await chat.connect()` 뒤에 `subscribe()`를 두면 connect가 거절될 때 구독 줄에 닿지
214
- 않는다.
215
-
216
- ```ts
217
- const room = chat.roomByKey('lobby')
218
- room.on('messages', render)
219
- chat.connect().catch(showOffline) // 실패해도 재시도는 계속된다
220
- await room.subscribe() // 붙은 뒤 끝난다
221
- ```
222
-
223
- 멈추는 것은 셋이다. `close()`, 서버의 인증 거절(`unauthorized`, `forbidden` — 같은
224
- 토큰을 반복하는 것은 서버를 두드리는 일이다), 그리고 **`token()`이 `ChatError`를 던질
225
- 때**다. 밴이나 끝난 세션처럼 다시 해도 소용없는 실패는 그렇게 알린다:
226
-
227
- ```ts
228
- token: async () => {
229
- const res = await fetch('/api/chat-token')
230
- if (res.status === 403) throw new ChatError('forbidden', 'banned') // 다시 하지 않는다
231
- if (!res.ok) throw new Error(`token ${res.status}`) // 백오프로 다시 한다
232
- return (await res.json()).token
233
- }
234
- ```
235
-
236
- 뒤의 둘은 `state`를 `closed`로 두고 `chat.on('error')`로 이유를 낸다. 재접속 중이나
237
- REST의 토큰 갱신 중이라 거절을 받을 호출자가 없어도 그렇다. 다시 붙으려면 `connect()`.
238
-
239
- **닉네임을 바꾸면 `reconnect()`.** 서버는 이름·아바타를 접속할 때 토큰 claim에서
240
- 한 번 읽는다. 그래서 백엔드에서 이름을 바꿔도 이 접속의 다음 메시지는 옛 이름이다.
241
- `reconnect()`는 `token()`을 다시 불러 새 claim으로 다시 인증하고, 방은 가진 것에서
242
- 이어서 따라잡는다. `close()` + `connect()`도 되지만 `closed`를 거쳐(오프라인 화면이
243
- 깜빡인다) 페이지 리스너까지 떼어 낸다. 옛 소켓에서 ack를 기다리던 프레임은 `closed`로
244
- 거절된다. 끝나면 `chat.user`가 새 신원이다.
245
-
246
- ```ts
247
- await api.updateNickname(name) // 백엔드가 다음 token()에 새 이름을 싣게 한다
248
- await chat.reconnect()
249
- chat.user?.name // 새 이름
250
- ```
251
-
252
- **토큰 만료는 SDK가 처리한다.** 소켓은 접속할 때 한 번만 인증하므로 토큰이 만료돼도
253
- 멀쩡하지만, REST는 요청마다 토큰을 본다. REST가 401을 받으면 SDK가 `token()`을 다시
254
- 불러 **한 번** 재시도한다. 두 번째 401(오리진, 폐기된 토큰, 밴)은 그대로 던진다.
255
- 주기적으로 재접속할 필요가 없다.
256
-
257
- SDK는 토큰을 캐시하지도, 꺼내 주지도 않는다. 캐시는 `token()` 안에서 한다(부를
258
- 때마다 백엔드를 칠 필요는 없다). **이 토큰을 자기 백엔드 API의 인증으로 다시 쓰지
259
- 않는다** — 채팅 엔진에 내라고 만든 것이고, 둘을 섞으면 한쪽에 새어 나간 토큰이 다른
260
- 쪽의 열쇠가 된다. 자기 API에는 자기 세션을 쓴다.
261
-
262
- **정렬과 구멍 메우기는 SDK가 한다.** 프레임이 순서 없이 오거나 재접속으로 구간을
263
- 놓치면 REST로 채운다. 한 페이지(100)를 넘는 구멍도 전부 채운다.
264
-
265
- **재접속이 복구하는 것은 메시지뿐이다.** 히스토리 라우트가 메시지 하나라서,
266
- 끊긴 동안 **오래된 메시지**에 달린 리액션이나 바뀐 방 이름은 반영되지 않는다.
267
- 그럴 때는 `await room.reload()`.
268
-
269
- **`typing`은 보낸 사람에게도 온다.** "X가 입력 중"을 그린다면 자기 `userId`를
270
- 건너뛴다.
271
-
272
- **`reset`을 무시하면 안 된다.** 옛 목록에 이어 붙이면 아무도 메우지 않는 구멍이
273
- 남는다.
136
+ - **`reset`을 무시하면 안 된다.** 옛 목록에 이어 붙이면 아무도 메우지 않는 구멍이 남는다.
137
+ - **과거는 `loadOlder()`로 같은 목록에 붙인다.** `history()`는 목록을 건드리지 않는 직접
138
+ 읽기이므로 합치고 중복을 거르는 일이 소비자 몫이 된다.
139
+ - **`typing`은 보낸 사람에게도 온다.** "X가 입력 중"을 그린다면 자기 `userId`를 건너뛴다.
140
+ - **연결은 알아서 돌아온다.** 끊기면 지수 백오프로 다시 붙으니 재시도 루프를 짜지 않는다.
141
+ - **토큰 만료는 SDK가 처리한다.** REST가 401을 받으면 `token()`을 다시 불러 한 번
142
+ 재시도한다. 주기적으로 재접속할 필요가 없다.
143
+ - **`token()`이 `ChatError`를 던지면 멈춘다.** 밴처럼 다시 해도 소용없는 실패를 그렇게 알린다.
144
+ - **닉네임·아바타를 바꿨으면 `reconnect()`.** 서버는 그 값을 접속할 때 토큰 claim에서
145
+ 한 번 읽는다.
274
146
 
275
147
  ### 브라우저에서 쓸 때
276
148
 
277
- `pk_`의 `allowed_origins`에 **페이지의 오리진을 넣어야 한다.** 이것 하나다. 서버가
278
- CORS 헤더를 직접 내므로 nginx나 다른 프록시를 건드릴 일은 없다.
279
-
280
- ```sh
281
- chat-server app create my-app --origins https://example.com
282
- chat-server key create <app-id> pk --origins https://staging.example.com
283
- ```
284
-
285
- 스킴·호스트·포트가 **정확히** 맞아야 한다. `https://example.com`과
286
- `https://www.example.com`은 다른 오리진이고, `http://localhost:3000`과
287
- `http://127.0.0.1:3000`도 다른 오리진이다. 개발용 오리진은 따로 넣는다.
288
-
289
- **Node에서는 이 설정 없이도 된다.** WHATWG `fetch`와 `WebSocket`은 브라우저 밖에서
290
- `Origin`을 보내지 않고, 엔진은 `Origin`이 없는 요청을 통과시킨다. 그래서 Node에서
291
- 초록이던 코드가 브라우저에서만 401이 나는 일이 생긴다 — 이 절이 그 이유다.
292
-
293
- 목록에 없으면 REST가 401로 거절하고, 메시지가 원인을 말한다:
149
+ `pk_`의 허용 오리진에 **페이지의 오리진을 넣어야 한다.** 이것 하나다 — 서버가 CORS 헤더를
150
+ 직접 내므로 프록시를 건드릴 일은 없다. 오리진은 콘솔의 키 화면에서 편집한다.
294
151
 
295
- ```
296
- origin not allowed for this publishable key: add it to the key's allowed_origins
297
- ```
152
+ 스킴·호스트·포트가 **정확히** 맞아야 한다. `https://example.com`과 `https://www.example.com`,
153
+ `http://localhost:3000`과 `http://127.0.0.1:3000`이 서로 다른 오리진이다. 개발용은 따로 넣는다.
298
154
 
299
- **접속도 같은 목록을 본다.** WebSocket은 브라우저 CORS의 대상이 아니지만, 엔진이
300
- 핸드셰이크에서 `pk_`의 `allowed_origins`를 직접 검사한다. 그래서 목록에 없는
301
- 오리진에서는 REST만이 아니라 접속부터 막히고, 인증 거절은 SDK가 다시 시도하지 않는
302
- 실패라 클라이언트가 `closed`에서 멈춘다 — 이유는 `chat.on('error')`로 온다.
155
+ 목록에 없는 오리진에서는 REST만이 아니라 **접속부터 401이다.** 인증 거절은 SDK가 다시
156
+ 시도하지 않으므로 클라이언트가 `closed`에서 멈추고, 이유는 `chat.on('error')`로 온다.
303
157
 
304
158
  ### 에러
305
159
 
@@ -338,10 +192,6 @@ const chat = createChatServer({
338
192
  })
339
193
  ```
340
194
 
341
- 키 하나면 된다. 어느 키로 서명했는지를 서버에 알리는 값(`kid`)은 `sk_`
342
- 안에 들어 있어서 SDK가 거기서 읽는다 — 콘솔의 키 ID를 따로 넣지 않는다.
343
- 주소도 클라이언트와 같이 상수다.
344
-
345
195
  ### `chat.token(input): string`
346
196
 
347
197
  네트워크를 타지 않는 로컬 서명이다.
@@ -367,25 +217,16 @@ app.post('/api/chat-token', (req, res) => {
367
217
  })
368
218
  ```
369
219
 
370
- **브라우저가 돌려준 `userId`를 그대로 서명하면 안 된다.** 게스트 id는 비밀이 아니다 —
371
- 방의 모든 메시지에 `sender.id`로 실려 나간다. "브라우저가 보관한 id를 다시 서명"하는
372
- 토큰 엔드포인트는 남의 메시지에서 id를 복사한 누구에게나 그 게스트의 신원을 준다.
373
- 형식 검사(`g_` + UUID 정규식)는 이것을 막지 못한다. UUID가 추측하기 어려운 것은
374
- 공개된 값 앞에서는 아무 의미가 없다.
375
-
376
- `guest()`는 브라우저가 id 대신 **자격증명**을 들게 한다. `g1.<userId>.<MAC>`이고 MAC은
377
- `guestSecret`으로 만든다. 돌아온 자격증명이 검증되면 그 안의 id로, 없거나 틀리면
378
- 새 게스트(`g_` + 무작위 22자, `created: true`)로 서명한다. 가능하면 `httpOnly` 쿠키에
379
- 두어 페이지의 스크립트가 읽지 못하게 한다.
220
+ **브라우저가 돌려준 `userId`를 그대로 서명하지 않는다.** `guest()`는 브라우저가 id 대신
221
+ **자격증명**을 들게 한다 — 검증되면 그 안의 id로, 없거나 틀리면 새 게스트(`created: true`)로
222
+ 서명한다. 가능하면 `httpOnly` 쿠키에 둔다.
380
223
 
381
224
  | | |
382
225
  |---|---|
383
- | `guestSecret` | 32자 이상. 백엔드에만 둔다. **`sk_`에서 유도하지 않는다** — `sk_`는 유출되면 돌리는 키이고, 돌릴 때 모든 게스트가 새 사람이 되면 안 되기 때문이다 |
226
+ | `guestSecret` | 32자 이상. 백엔드에만 둔다. **`sk_`에서 유도하지 않는다** |
384
227
  | 교체 | 배열로 준다: `[새것, 옛것]`. 첫 번째로 서명하고 전부로 검증한다. 옛것으로 검증된 자격증명은 같은 `userId`로 새로 서명해 돌려주므로 다음 방문에 옮겨 간다 |
385
- | 유출 | 비밀이 새면 누구든 아무 게스트가 될 수 있다. 옛것을 목록에서 **빼면** 모든 게스트가 새 사람이 된다 — 신원을 잃는 것이 사칭보다 낫다 |
386
228
 
387
- 게스트 id는 `g_`로 시작한다. 로그인 유저의 id가 `g_`로 시작하지 않게 하면 두 공간이
388
- 겹치지 않는다.
229
+ 게스트 id는 `g_`로 시작한다. 로그인 유저의 id를 `g_`로 시작하지 않게 하면 겹치지 않는다.
389
230
 
390
231
  ### 나머지
391
232
 
@@ -394,39 +235,31 @@ app.post('/api/chat-token', (req, res) => {
394
235
  | `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
395
236
  | `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
396
237
  | `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?})` |
397
- | `events` | `list({after?, limit?})` — outbox. 놓친 웹훅을 따라잡는다 |
238
+ | `events` | `list({after?, limit?})` — 놓친 웹훅 이벤트를 따라잡는다 |
398
239
  | `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` — `tolerance`는 밀리초 |
399
240
 
241
+ `rooms.ensure`는 get-or-create다 — 있으면 그대로 돌려주므로 페이지를 열 때마다 불러도 된다.
242
+
400
243
  `rooms.presence(roomId)`는 `{count}`이고, `{full: true}`면 `users`(최대 1000명, 잘리면
401
244
  `capped: true`)가 붙는다. 빈 방은 404가 아니라 `{count: 0}`이다.
402
245
 
403
- **`users.purgeMessages(userId)`는 모더레이션이다** — 그 유저가 앱에서 보낸 메시지를
404
- 전부 지우되(tombstone: seq는 그대로, 보고 있는 클라이언트에는 `message.deleted`가
405
- 간다) **탈퇴시키지 않는다.** 이름도 남는다. 스팸이면 **밴을 먼저** 하고 부른다 — 도는
406
- 사이에 올라온 메시지는 목록에 없다. 한 번에 상한만큼만 하므로 `purgeCapped`가
407
- `true`인 동안 다시 부른다. 탈퇴한 유저는 404다(그때는 `withdraw(userId, {purgeMessages: true})`).
246
+ `rooms.custom(roomId, payload)`은 **저장되지 않는 제어 신호**다. `payload`는 JSON 객체이고
247
+ 그대로 `room.on('custom', ...)`에 도착한다. 히스토리도 unread도 웹훅도 남지 않으니, 재접속해도
248
+ 받아야 하는 신호는 `messages.send(roomId, {kind:'system', ...})`으로 보낸다.
249
+
250
+ `users.ban`의 `until`은 **unix 밀리초이고 필수다.** 무기한 밴은 먼 미래 시각을 직접 고른다.
251
+
252
+ `users.purgeMessages(userId)`는 그 유저의 메시지를 거두되 **탈퇴시키지 않는다.** 한 번에
253
+ 상한만큼만 하므로 `purgeCapped`가 `true`인 동안 다시 부르고, 스팸이면 **밴을 먼저** 한다.
408
254
 
409
255
  ```ts
410
256
  await chat.users.ban(userId, { until: Date.now() + 7 * 86_400_000, reason: 'spam' })
411
257
  while ((await chat.users.purgeMessages(userId)).purgeCapped) {}
412
258
  ```
413
259
 
414
- `users.ban`의 `until`은 **unix 밀리초이고 필수다.** 무기한 밴은 먼 미래 시각을
415
- 직접 고른다 — 감사 로그에 사고가 아니라 결정으로 남는다.
416
-
417
- `users.*`는 그 사람이 **한 번이라도 접속한 뒤에만** 통한다. 유저는 접속으로
418
- 생긴다.
419
-
420
- `users.list`는 콘솔용이다. uid 역순, `limit` 기본 50 최대 100, `cursor`는 불투명
421
- 문자열이고 빈 문자열이 마지막 페이지다. **탈퇴한 유저도 나오고 `deletedAt`이 그
422
- 표시다** — 살아 있는 유저만 원하면 그것으로 거른다. 방 안의 목록들(멤버·리액션·읽음)이
423
- 탈퇴자의 id를 감추는 것과 반대인데, 그쪽은 **다른 유저**가 읽는 목록이고 이쪽은
424
- `sk_`가 있어야 하므로 상대가 그 id를 발급한 백엔드 자신이기 때문이다.
425
-
426
- `rooms.custom(roomId, payload)`은 **저장되지 않는 제어 신호**다. `payload`는 JSON
427
- 객체이고 그대로 `room.on('custom', ...)`에 도착한다. 히스토리도 unread도 웹훅도
428
- 남지 않으니, 그 순간 접속해 있지 않은 사람은 영영 모른다 — 재접속해도 받아야 하는
429
- 신호라면 `messages.send(roomId, {kind:'system', ...})`이다.
260
+ `users.list`는 최신순이고 `limit` 기본 50 최대 100, `cursor`는 불투명 문자열이며 빈
261
+ 문자열이 마지막 페이지다. **탈퇴한 유저도 나오고 `deletedAt`이 그 표시다.**
262
+ `users.*`는 그 사람이 **한 번이라도 접속한 뒤에만** 통한다 — 유저는 접속으로 생긴다.
430
263
 
431
264
  ### 웹훅
432
265
 
@@ -439,15 +272,9 @@ app.post('/chat-hook', express.raw({ type: 'application/json' }), (req, res) =>
439
272
  })
440
273
  ```
441
274
 
442
- **raw 바디여야 한다.** MAC은 서버가 보낸 바이트에 대한 것이고, 파싱했다가 다시
443
- 직렬화한 것은 다른 문자열이다.
275
+ **raw 바디여야 한다.** 파싱했다가 다시 직렬화한 것은 다른 문자열이라 검증에 실패한다.
444
276
 
445
- **서명은 헤더도 덮는다.** 정규 문자열이
446
- `` `${t}\n${event}\n${delivery}\n${rawBody}` ``이고 순서가 고정이다. 그래서
447
- `verify`는 `X-Chat-Event`와 `X-Chat-Delivery`를 **검증 전에** 읽고, 헤더만
448
- 바꿔치기한 재전송은 통과하지 못한다 — `X-Chat-Delivery`가 중복 제거 키이므로
449
- 그것이 서명 밖에 있으면 캡처한 배달 하나가 얼마든지 새 이벤트로 셀 수 있다.
277
+ 세 가지를 지킨다. `verify`가 서명과 시각(기본 5분)을 보고, **중복 제거는 직접** 해야 하며
278
+ (`delivery`로), 10초 안에 2xx로 답해야 한다. 넘기면 실패로 치고 백오프가 시작된다.
450
279
 
451
- 세 가지를 지킨다. `verify`가 서명과 시각(기본 5분)을 보고, **중복 제거는 직접**
452
- 해야 하며(`delivery`로), 10초 안에 2xx로 답해야 한다. 넘기면 실패로 치고 백오프가
453
- 시작된다.
280
+ 다른 언어로 검증하는 규격은 [웹훅 문서](https://chat.gravex.app/docs/webhooks)에 있다.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kispi/chat",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Client SDK for the chat server: one WebSocket, many rooms, ordered history.",
5
5
  "license": "MIT",
6
6
  "type": "module",