@wtfalch/chat 0.1.0

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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +293 -0
  3. package/dist/chat/admin/admin.css +78 -0
  4. package/dist/chat/admin/index.d.ts +92 -0
  5. package/dist/chat/admin/index.js +124 -0
  6. package/dist/chat/admin/react.d.ts +40 -0
  7. package/dist/chat/admin/react.js +169 -0
  8. package/dist/chat/chat.css +1003 -0
  9. package/dist/chat/client.d.ts +30 -0
  10. package/dist/chat/client.js +1300 -0
  11. package/dist/chat/exchange.d.ts +9 -0
  12. package/dist/chat/exchange.js +31 -0
  13. package/dist/chat/fake/index.d.ts +27 -0
  14. package/dist/chat/fake/index.js +48 -0
  15. package/dist/chat/fake/intercept.d.ts +21 -0
  16. package/dist/chat/fake/intercept.js +57 -0
  17. package/dist/chat/fake/sample.d.ts +4 -0
  18. package/dist/chat/fake/sample.js +6 -0
  19. package/dist/chat/fake/server.d.ts +168 -0
  20. package/dist/chat/fake/server.js +811 -0
  21. package/dist/chat/fake/xhr.d.ts +3 -0
  22. package/dist/chat/fake/xhr.js +104 -0
  23. package/dist/chat/index.d.ts +10 -0
  24. package/dist/chat/index.js +9 -0
  25. package/dist/chat/markdown.d.ts +29 -0
  26. package/dist/chat/markdown.js +161 -0
  27. package/dist/chat/react/Attachment.d.ts +39 -0
  28. package/dist/chat/react/Attachment.js +113 -0
  29. package/dist/chat/react/Chat.d.ts +48 -0
  30. package/dist/chat/react/Chat.js +139 -0
  31. package/dist/chat/react/Composer.d.ts +25 -0
  32. package/dist/chat/react/Composer.js +157 -0
  33. package/dist/chat/react/MessageRow.d.ts +21 -0
  34. package/dist/chat/react/MessageRow.js +114 -0
  35. package/dist/chat/react/NewDirectMessage.d.ts +23 -0
  36. package/dist/chat/react/NewDirectMessage.js +47 -0
  37. package/dist/chat/react/ThreadPanel.d.ts +25 -0
  38. package/dist/chat/react/ThreadPanel.js +17 -0
  39. package/dist/chat/react/Timeline.d.ts +27 -0
  40. package/dist/chat/react/Timeline.js +120 -0
  41. package/dist/chat/react/index.d.ts +7 -0
  42. package/dist/chat/react/index.js +6 -0
  43. package/dist/chat/react/mentions.d.ts +34 -0
  44. package/dist/chat/react/mentions.js +70 -0
  45. package/dist/chat/react/scroll.d.ts +26 -0
  46. package/dist/chat/react/scroll.js +27 -0
  47. package/dist/chat/react/timelineLayout.d.ts +26 -0
  48. package/dist/chat/react/timelineLayout.js +47 -0
  49. package/dist/chat/sanitize.d.ts +49 -0
  50. package/dist/chat/sanitize.js +264 -0
  51. package/dist/chat/store.d.ts +16 -0
  52. package/dist/chat/store.js +25 -0
  53. package/dist/chat/types.d.ts +340 -0
  54. package/dist/chat/types.js +1 -0
  55. package/package.json +88 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 William Tallis Falch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,293 @@
1
+ # @wtfalch/chat
2
+
3
+ Team chat, on Matrix. Mirrors [`@wtfalch/email`](https://github.com/wtfalch/email)'s
4
+ shape: a client the agora gives a way to get a token, a React section built on
5
+ it, and a fake of both for stories and tests.
6
+
7
+ ## Exports
8
+
9
+ | Export | What it holds |
10
+ | --- | --- |
11
+ | `@wtfalch/chat` | `createChatClient`: a matrix-js-sdk `MatrixClient` behind the token exchange, refreshed on its own, exposing a small typed API |
12
+ | `@wtfalch/chat/react` | The `Chat` component: rooms, a timeline, a composer, direct messages, threads, reactions and mentions |
13
+ | `@wtfalch/chat/fake` | A real `createChatClient`, wired to a fake exchange and a fake homeserver instead of the network |
14
+ | `@wtfalch/chat/chat.css` | Styles, on `@wtfalch/design` tokens |
15
+
16
+ ## The client
17
+
18
+ ```ts
19
+ import { createChatClient } from '@wtfalch/chat';
20
+
21
+ const chat = createChatClient({
22
+ exchangeUrl: 'https://chat.example.com/_chat/exchange',
23
+ getAccessToken: () => agora.currentZitadelToken(),
24
+ deviceId: agora.deviceId(),
25
+ storeName: agora.companyId(),
26
+ });
27
+
28
+ await chat.start();
29
+ chat.onRoomsChanged((rooms) => render(rooms));
30
+ ```
31
+
32
+ `createChatClient` takes only a way to get a current ZITADEL access token
33
+ (`getAccessToken`) -- it knows nothing else about the agora, and never imports
34
+ an Agora type. On `start()`, it `POST`s `exchangeUrl` with that token and a
35
+ device id, and gets back a Matrix homeserver, user id and access token (the
36
+ exact contract is `apps/chat-service/README.md` and
37
+ `apps/chat-service/src/exchange.ts`). `storeName` names its local IndexedDB
38
+ store, so two companies open in the same browser never share one.
39
+
40
+ There is no Matrix refresh token, so this refreshes itself two ways: a timer
41
+ ahead of `expires_at`, and a listener for Synapse's `M_UNKNOWN_TOKEN`. Both
42
+ re-run the exchange and carry on without the caller doing anything.
43
+
44
+ Crypto stays off: encryption is not in the first ship, so this never calls
45
+ `initRustCrypto()`. matrix-js-sdk only downloads its Rust crypto WASM when
46
+ that is called, so skipping it means the WASM module is never loaded, in a
47
+ browser or under vitest -- no shim or polyfill needed either way.
48
+
49
+ **Sync, reconnect and unread counts** ([#14](https://github.com/wtfalch/messaging/issues/14)).
50
+ The room list follows matrix-js-sdk's own `/sync` loop: a new room, a rename,
51
+ or the account joining or leaving one all land through `onRoomsChanged`,
52
+ never a poll. If Synapse ever refuses the client's stored sync position (seen
53
+ after a long enough time offline), this wipes the local store and starts a
54
+ full sync on its own -- no duplicated or missing events either way. Each room
55
+ summary carries `unreadCount`, Matrix's own notification count; `chat.
56
+ totalUnreadCount()` sums it across every room, for the agora's badge.
57
+ `chat.markRoomRead(roomId)` sends `m.read` for the newest event and clears
58
+ that room's count right away -- call it when a room is opened and again when
59
+ the person reaches the newest message. `chat.connectionStatus()` (and
60
+ `onConnectionStatusChanged`) is `'connected'`, `'catching-up'` or
61
+ `'offline'`, for a status the UI can render.
62
+
63
+ **Direct messages** ([#16](https://github.com/wtfalch/messaging/issues/16)).
64
+ `chat.people()` is everyone in the company space but the signed-in person --
65
+ the space is where a company's membership lives, and a guest is never in it,
66
+ so a guest can never be offered. `chat.startDirectMessage(userIds)` opens the
67
+ direct room with exactly those people and resolves with its id: an existing
68
+ one is found through the account's own `m.direct` data and reopened, and only
69
+ a set of people with no room yet creates one. A different set of people is a
70
+ different room, which is why changing a group's people starts a new direct
71
+ message rather than editing the old one.
72
+
73
+ The room it creates carries `is_direct` and an invite list and nothing else.
74
+ That is not a style choice: Synapse's `wtfalch_chat_gate` module refuses a
75
+ member-created room that also carries a name, a topic, `initial_state` or
76
+ `creation_content`, because a room dressed as a channel is the manage app's
77
+ to make (chat plan section 5).
78
+
79
+ `chat.hideDirectMessage(roomId)` takes a direct room out of `rooms()` with a
80
+ `com.wtfalch.hidden` room tag rather than a leave, so its history is exactly
81
+ where it was and the next `startDirectMessage` with the same people brings it
82
+ straight back.
83
+
84
+ **Threads** ([#17](https://github.com/wtfalch/messaging/issues/17)). A thread
85
+ is named by the message that started it -- Matrix threads are one level, so a
86
+ thread has no id of its own, and a reply always relates to the root rather
87
+ than to the reply above it. `chat.timeline(roomId, threadId)` is that
88
+ thread's own timeline, root first;
89
+ `chat.sendMessage(roomId, text, { threadId })` replies into it;
90
+ `chat.paginate(roomId, threadId)` walks its history. A
91
+ reply is never in the room's own timeline: what the room shows is the count
92
+ and the people on the root, through `event.thread`.
93
+
94
+ `onTimelineChanged(roomId, listener)` takes no thread id, deliberately. A
95
+ reply changes both the thread it is in and the count on its root, so a caller
96
+ reading either has to hear about it; one subscription per room says that
97
+ once.
98
+
99
+ **Reactions and mentions** ([#18](https://github.com/wtfalch/messaging/issues/18)).
100
+ `event.reactions` is what people have reacted with, most-reacted first and
101
+ then by key, so everyone sees the same row in the same order.
102
+ `chat.toggleReaction(roomId, eventId, key)` adds the signed-in person's
103
+ reaction or takes it away -- one call, because that is the one thing anybody
104
+ means by pressing a reaction. Taking one back is a redaction of the event
105
+ that was sent, which is the only way Matrix has. Concurrent toggles converge
106
+ because Matrix does the converging: two people pressing at once end up with
107
+ both events or neither, never with a count nobody can explain.
108
+
109
+ `chat.roomMembers(roomId)` is who a message here can mention -- the room's
110
+ own membership, not the company's, because mentioning somebody who is not
111
+ here would notify nobody. `sendMessage(roomId, text, { mentions })` writes
112
+ `m.mentions.user_ids`, and `event.mentionsMe` reads it back. The text alone
113
+ never decides: two people can share a display name.
114
+
115
+ **Edit and delete** ([#19](https://github.com/wtfalch/messaging/issues/19)).
116
+ `chat.editMessage(roomId, eventId, text)` replaces the text of the signed-in
117
+ person's own message, as Matrix's `m.replace`: a new event carrying
118
+ `m.new_content`, related to the original. The original keeps its place in the
119
+ timeline and keeps its id, so an edit never reorders a conversation and never
120
+ breaks a thread hanging off the message. `event.edited` says the reader is
121
+ not looking at what was first written; `event.body` is already the new text.
122
+ The `m.replace` event itself is never drawn as a second message.
123
+
124
+ `chat.deleteMessage(roomId, eventId)` redacts. The event stays in the
125
+ timeline and `event.deleted` says so, with `body` empty: a renderer draws a
126
+ tombstone in its place rather than dropping the row, which would move
127
+ everything under a reader mid-scroll, and a thread whose root was deleted
128
+ keeps every reply.
129
+
130
+ A thread whose root was deleted keeps every reply, and the root still holds
131
+ them up as a tombstone. That needs saying because matrix-js-sdk does not do
132
+ it on its own: it rebuilds a thread's reply count from the root's bundled
133
+ summary, which Synapse stops sending once the root is redacted, so the client
134
+ that *wrote* the replies can watch its own `Thread` object be torn down while
135
+ the person who wrote the root keeps theirs. The replies are untouched in the
136
+ room's relations either way -- a redaction takes one event's content, never
137
+ anything relating to it -- so that is what this package reads when the thread
138
+ is gone. On a client that lost its thread that way, a reply that had been
139
+ edited before the root was deleted can read as its original text until the
140
+ next reload; the reply itself is never lost.
141
+
142
+ Both refuse a message somebody else sent, and `event.mine` is what a UI draws
143
+ that rule from. Ownership is the whole rule: Matrix ignores an `m.replace`
144
+ from anybody but the original sender, and the default power levels let a
145
+ member redact their own event and nobody else's. Moderating other people's
146
+ messages is the manage app's, later.
147
+
148
+ **Redacted text does leave the database, but not at once.** A redaction
149
+ empties the event for every client immediately; Synapse replaces its own
150
+ stored copy with the redacted form after `redaction_retention_period`, which
151
+ is 7 days by default. Until then the original text is still in Synapse's
152
+ Postgres, where a server administrator could read it. Anything that has to be
153
+ gone *now* is not a redaction (chat plan section 8).
154
+
155
+ **Safe rendering.** `formatted_body` is a stranger's HTML and is never drawn
156
+ without `sanitizeHtml` first -- an allow-list walked in a document with no
157
+ browsing context, unknown tags unwrapped, scripts and forms dropped with
158
+ their contents, a link's scheme parsed rather than pattern-matched, an image
159
+ only ever this homeserver's own media, and caps on depth and node count. Its
160
+ tests carry the payloads: `javascript:` behind case, whitespace and HTML
161
+ entities, `svg onload`, `object`/`embed`/`form`/`base`/`meta`, every `on*`
162
+ handler, the `<scr<script>ipt>` trick, foreign image sources, and messages
163
+ built out of nothing but depth or siblings.
164
+
165
+ ## The fake
166
+
167
+ ```ts
168
+ import { fakeChat } from '@wtfalch/chat/fake';
169
+
170
+ const { client, server, dispose } = fakeChat();
171
+ await client.start();
172
+ client.rooms(); // the sample rooms, joined
173
+ dispose();
174
+ ```
175
+
176
+ Like `@wtfalch/email`'s `fakeMail`, this is a fake transport, not a fake
177
+ client: `createChatClient` and matrix-js-sdk run unchanged, against a fake
178
+ exchange and homeserver answered by intercepting `fetch`. `FakeChatServer`
179
+ (also exported) gives a test finer control -- seeding rooms (with a starting
180
+ `notificationCount`), seeding the company space (`isSpace`) and who is in it
181
+ (`members`, `invited`), adding, renaming or delivering someone leaving a room
182
+ mid-test, sending a message into one, invalidating the current token to
183
+ prove a token recovery, or refusing the next poll's position to prove a
184
+ full-sync recovery. It answers `/createRoom`, `m.direct` account data and
185
+ room tags too, so a direct message can be started, reopened and hidden
186
+ against it -- and it refuses a `createRoom` carrying a `name`, the same way
187
+ the Synapse gate does, so a client that started sending one would fail here
188
+ rather than in production. It also takes sends (`server.sent` is what went
189
+ out, relation and all), seeds a room with messages, delivers a threaded
190
+ reply, and answers `/event` and `/relations`, which is what matrix-js-sdk
191
+ asks for while it builds a thread. It echoes every accepted send back
192
+ through sync carrying its transaction id, so a reaction shows up the way it
193
+ does against a homeserver, and it answers redactions -- which is how a
194
+ reaction is taken back.
195
+
196
+ ## Integration tests
197
+
198
+ `test/integration/` runs `createChatClient` against the real stack
199
+ `apps/chat-service/test/stack` brings up -- a real chat-service, Synapse and
200
+ MAS, through the same helpers chat-service's own integration suite uses.
201
+ Bring the stack up first (`bash apps/chat-service/test/stack/up.sh`), then
202
+ `pnpm test:integration`; `bash apps/chat-service/test/stack/down.sh` when
203
+ done.
204
+
205
+ ## Plan
206
+
207
+ [`.plans/2026-09-17-chat.md`](../../.plans/2026-09-17-chat.md), section 9.
208
+ Tickets [#11](https://github.com/wtfalch/messaging/issues/11),
209
+ [#14](https://github.com/wtfalch/messaging/issues/14),
210
+ [#15](https://github.com/wtfalch/messaging/issues/15),
211
+ [#16](https://github.com/wtfalch/messaging/issues/16),
212
+ [#17](https://github.com/wtfalch/messaging/issues/17) and
213
+ [#18](https://github.com/wtfalch/messaging/issues/18).
214
+
215
+ ## Files
216
+
217
+ Pick files in the composer, paste them, or drop them onto it. Each file can be
218
+ up to 50 MiB (52,428,800 bytes, displayed as 50 MB), matching Synapse's `50M`
219
+ limit. Larger files are refused before any upload starts. Uploads show progress
220
+ and can be cancelled; failures keep the file for Retry. After upload, the normal
221
+ message retry sends the existing media reference without uploading the bytes again.
222
+ Stopping the client aborts unfinished uploads.
223
+
224
+ `client.sendFile(roomId, file, { threadId })` returns a temporary upload row id.
225
+ After upload it becomes a Matrix message with its own event id. Read the current
226
+ id from `timeline()` before calling `retryMessage` or `cancelMessage`.
227
+ `event.attachment` describes an image or file; `event.upload` carries byte progress
228
+ until the upload completes. Images preview inline and all files have a named
229
+ Download link. A failed download offers Retry download.
230
+
231
+ Media bytes are fetched with the session bearer token from
232
+ `/_matrix/client/v1/media/download/*`, including images inside formatted messages.
233
+ There is no legacy unauthenticated download fallback. `loadMedia(mxcUri)` returns
234
+ a blob URL or null; callers must revoke returned URLs. The React views revoke
235
+ theirs on replacement and unmount, including downloads that finish after unmount.
236
+ Uploads use Matrix's separate authenticated `/_matrix/media/v3/upload` endpoint.
237
+ Only references on the session's own homeserver are accepted.
238
+
239
+ **Known limit: files are not locked to their channels.** A person with a valid
240
+ homeserver token and a media id may retrieve that file without membership in the
241
+ room where it was posted. Deleting the message removes its visible reference;
242
+ it does not delete the stored media. No malware scanning or file search is included.
243
+
244
+ ## First-ship local proof
245
+
246
+ See [the browser/Electron fixture](test/acceptance/README.md) for the repeatable
247
+ local preflight. It uses the real Synapse/MAS stack and a fake issuer, and records
248
+ outstanding UI and deployment acceptance separately. The first ship has no push
249
+ notifications or message/file search.
250
+
251
+ ## Invitations and read receipts
252
+
253
+ `rooms()` includes `membership: 'invite'` entries as well as joined rooms.
254
+ Invitations appear in their own section and contribute one to the attention
255
+ count until answered or withdrawn. `acceptInvitation(roomId)` joins the room;
256
+ `declineInvitation(roomId)` leaves it. Accepting a DM records the recipient's
257
+ `m.direct` account data so it stays a direct message across devices and reloads.
258
+
259
+ The React timeline calls `markRoomRead` when the visible room is at the bottom.
260
+ Reading a thread, viewing older history, or leaving a tab in the background does
261
+ not clear unread room messages.
262
+
263
+ ## Administration in Manage
264
+
265
+ `@wtfalch/chat/admin` exports `createChatAdmin`, the typed management
266
+ client, and `hasChatAdminRole` for already-verified identity claims. The admin
267
+ entry imports neither React nor Matrix. Configure a canonical agora origin and
268
+ supply the signed-in administrator's fresh ZITADEL access token per request:
269
+
270
+ ```ts
271
+ import { createChatAdmin } from '@wtfalch/chat/admin';
272
+ const admin = createChatAdmin({ agoraUrl: 'https://agora.example.test', getAccessToken });
273
+ const page = await admin.listChannels({ limit: 25 });
274
+ ```
275
+
276
+ It exposes channel list/details/create/update/archive/delete, private-channel
277
+ invitations/removals, Chat-user deactivation and audit pagination. Redirects are
278
+ refused; tokens never appear in URLs or rendered errors. Service authorization
279
+ still verifies the token, organisation and Chat project's admin role on every
280
+ request. Request the Chat project audience and qualified project-role claims
281
+ when Manage signs in; a same-named role from another project is insufficient.
282
+
283
+ `@wtfalch/chat/admin/react` exports `ChatAdminPanel` plus its action
284
+ contracts. Import `@wtfalch/chat/admin/admin.css` after design styles.
285
+ The SDK owns the controls; Manage supplies an organisation-scoped `load` and
286
+ `run` action, its verified gates, and a roster mapping issuer subjects to names.
287
+ Keep access tokens in server actions. Every action must check both host tenant
288
+ membership and the Chat project role itself; hiding a menu entry is not a gate.
289
+ Mail follows the same separation through `@wtfalch/email/postmaster`.
290
+
291
+ The agora is the sole user-facing app and HTTP origin for Mail and Chat. Admin
292
+ panels live in Manage; no separate Chat web host is inferred or provisioned.
293
+ Deployment and real-identity acceptance remain separate from local checks.
@@ -0,0 +1,78 @@
1
+ .chat-admin {
2
+ color: var(--text);
3
+ font-size: var(--text-sm);
4
+ }
5
+ .chat-admin-fields {
6
+ border: 0;
7
+ padding: 0;
8
+ margin: 0;
9
+ min-width: 0;
10
+ }
11
+ .chat-admin-toolbar {
12
+ display: flex;
13
+ align-items: center;
14
+ flex-wrap: wrap;
15
+ gap: var(--space-3);
16
+ margin-block: var(--space-4);
17
+ }
18
+ .chat-admin-form {
19
+ display: grid;
20
+ gap: var(--space-3);
21
+ max-width: 42rem;
22
+ margin-block: var(--space-4);
23
+ }
24
+ .chat-admin-form > button {
25
+ justify-self: start;
26
+ }
27
+ .chat-admin details,
28
+ .chat-admin-section {
29
+ border-top: var(--border-width) solid var(--border);
30
+ padding-block: var(--space-4);
31
+ }
32
+ .chat-admin summary {
33
+ cursor: pointer;
34
+ font-weight: var(--weight-strong);
35
+ padding-block: var(--space-2);
36
+ }
37
+ .chat-admin summary:focus-visible {
38
+ outline: var(--border-width) solid var(--text);
39
+ outline-offset: var(--space-1);
40
+ }
41
+ .chat-admin h2,
42
+ .chat-admin h3 {
43
+ margin-block: var(--space-2);
44
+ }
45
+ .chat-admin-people {
46
+ list-style: none;
47
+ padding: 0;
48
+ margin: 0;
49
+ }
50
+ .chat-admin-people li {
51
+ display: flex;
52
+ flex-wrap: wrap;
53
+ align-items: center;
54
+ justify-content: space-between;
55
+ gap: var(--space-3);
56
+ padding-block: var(--space-2);
57
+ border-bottom: var(--border-width) solid var(--border);
58
+ }
59
+ .chat-admin-confirm {
60
+ border: 0;
61
+ padding: 0;
62
+ margin: 0;
63
+ min-width: 0;
64
+ display: flex;
65
+ flex-wrap: wrap;
66
+ align-items: center;
67
+ gap: var(--space-2);
68
+ }
69
+ .chat-admin-confirm p {
70
+ flex-basis: 100%;
71
+ }
72
+ .chat-admin p,
73
+ .chat-admin-people span {
74
+ overflow-wrap: anywhere;
75
+ }
76
+ .chat-admin [role="alert"] {
77
+ color: var(--bad);
78
+ }
@@ -0,0 +1,92 @@
1
+ /** Chat administration for hosts such as Manage. The caller supplies its
2
+ * signed-in administrator's ZITADEL token; never a MAS or Synapse secret.
3
+ * Importing this entry does not load Matrix, React or the chat sync client. */
4
+ export type ChatAdminOptions = {
5
+ agoraUrl: string;
6
+ getAccessToken: () => Promise<string>;
7
+ fetch?: typeof fetch;
8
+ };
9
+ export type ChannelPerson = {
10
+ subject: string;
11
+ display_name: string | null;
12
+ membership: 'join' | 'invite';
13
+ };
14
+ export type AdminChannel = {
15
+ room_id: string;
16
+ name: string;
17
+ topic: string;
18
+ visibility: 'public' | 'private';
19
+ archived: boolean;
20
+ people: ChannelPerson[];
21
+ };
22
+ export type ChannelPage = {
23
+ channels: AdminChannel[];
24
+ next_cursor: string | null;
25
+ };
26
+ export type ChannelInput = {
27
+ name: string;
28
+ topic?: string;
29
+ visibility: 'public' | 'private';
30
+ };
31
+ export type AuditRow = {
32
+ id: string;
33
+ at: string;
34
+ actor: string | null;
35
+ organisation_id: string;
36
+ operation: string;
37
+ target: string | null;
38
+ result: 'ok' | 'refused' | 'error';
39
+ reason: string | null;
40
+ };
41
+ export type AuditPage = {
42
+ rows: AuditRow[];
43
+ next_cursor: string | null;
44
+ };
45
+ export type PageInput = {
46
+ limit?: number;
47
+ cursor?: string;
48
+ };
49
+ /** Safe to render: no upstream text, URL, body or credential in the message. */
50
+ export declare class ChatAdminError extends Error {
51
+ readonly status: number;
52
+ readonly code: string;
53
+ constructor(status: number, code: string);
54
+ }
55
+ export declare function createChatAdmin(options: ChatAdminOptions): {
56
+ listChannels: (input?: PageInput) => Promise<ChannelPage>;
57
+ getChannel: (roomId: string) => Promise<AdminChannel>;
58
+ createChannel: (input: ChannelInput) => Promise<{
59
+ room_id: string;
60
+ }>;
61
+ updateChannel: (roomId: string, input: {
62
+ name?: string;
63
+ topic?: string;
64
+ }) => Promise<{
65
+ room_id: string;
66
+ }>;
67
+ invitePerson: (roomId: string, subject: string) => Promise<{
68
+ room_id: string;
69
+ user_id: string;
70
+ }>;
71
+ removePerson: (roomId: string, subject: string) => Promise<{
72
+ room_id: string;
73
+ user_id: string;
74
+ }>;
75
+ archiveChannel: (roomId: string) => Promise<{
76
+ room_id: string;
77
+ archived: true;
78
+ }>;
79
+ deleteChannel: (roomId: string) => Promise<{
80
+ room_id: string;
81
+ deleted: true;
82
+ }>;
83
+ deactivatePerson: (subject: string) => Promise<{
84
+ user_id: string;
85
+ deactivated: true;
86
+ }>;
87
+ audit: (input?: PageInput) => Promise<AuditPage>;
88
+ };
89
+ export type ChatAdmin = ReturnType<typeof createChatAdmin>;
90
+ /** For a host's visibility gate, using claims ALREADY verified by its auth
91
+ * SDK. This does not verify a JWT; the service authorizes every request. */
92
+ export declare function hasChatAdminRole(claims: Record<string, unknown>, projectId: string, organisationId: string, role?: string): boolean;
@@ -0,0 +1,124 @@
1
+ /** Safe to render: no upstream text, URL, body or credential in the message. */
2
+ export class ChatAdminError extends Error {
3
+ status;
4
+ code;
5
+ constructor(status, code) {
6
+ super(`Chat administration refused the request (${status}, ${code}).`);
7
+ this.status = status;
8
+ this.code = code;
9
+ this.name = 'ChatAdminError';
10
+ }
11
+ }
12
+ function origin(input) {
13
+ const url = new URL(input);
14
+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
15
+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) ||
16
+ url.username ||
17
+ url.password ||
18
+ url.pathname !== '/' ||
19
+ url.search ||
20
+ url.hash) {
21
+ throw new Error('Chat administration needs an HTTPS agora origin (HTTP is allowed on loopback).');
22
+ }
23
+ return url.origin;
24
+ }
25
+ const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
26
+ const nullableString = (value) => value === null || typeof value === 'string';
27
+ function channel(value) {
28
+ return (record(value) &&
29
+ typeof value.room_id === 'string' &&
30
+ typeof value.name === 'string' &&
31
+ typeof value.topic === 'string' &&
32
+ ['public', 'private'].includes(String(value.visibility)) &&
33
+ typeof value.archived === 'boolean' &&
34
+ Array.isArray(value.people) &&
35
+ value.people.every((person) => record(person) &&
36
+ typeof person.subject === 'string' &&
37
+ nullableString(person.display_name) &&
38
+ ['join', 'invite'].includes(String(person.membership))));
39
+ }
40
+ function auditRow(value) {
41
+ return (record(value) &&
42
+ ['id', 'at', 'organisation_id', 'operation'].every((key) => typeof value[key] === 'string') &&
43
+ nullableString(value.actor) &&
44
+ nullableString(value.target) &&
45
+ nullableString(value.reason) &&
46
+ ['ok', 'refused', 'error'].includes(String(value.result)));
47
+ }
48
+ function identifier(value) {
49
+ if (!value || value.length > 1024)
50
+ throw new Error('A target identifier is required.');
51
+ return encodeURIComponent(value);
52
+ }
53
+ function pageQuery(max, input = {}) {
54
+ const query = new URLSearchParams();
55
+ if (input.limit !== undefined) {
56
+ if (!Number.isInteger(input.limit) || input.limit < 1 || input.limit > max)
57
+ throw new Error(`limit must be between 1 and ${max}.`);
58
+ query.set('limit', String(input.limit));
59
+ }
60
+ if (input.cursor !== undefined)
61
+ query.set('cursor', input.cursor);
62
+ return query.size ? `?${query}` : '';
63
+ }
64
+ export function createChatAdmin(options) {
65
+ const base = `${origin(options.agoraUrl)}/_chat/manage`;
66
+ const fetchImpl = options.fetch ?? globalThis.fetch;
67
+ async function request(method, path, valid, body) {
68
+ const token = await options.getAccessToken();
69
+ if (!token)
70
+ throw new ChatAdminError(401, 'no_session');
71
+ const response = await fetchImpl(`${base}${path}`, {
72
+ method,
73
+ credentials: 'omit',
74
+ cache: 'no-store',
75
+ redirect: 'error',
76
+ signal: AbortSignal.timeout(30_000),
77
+ headers: {
78
+ authorization: `Bearer ${token}`,
79
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
80
+ },
81
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
82
+ });
83
+ const data = await response.json().catch(() => null);
84
+ if (!response.ok) {
85
+ const code = record(data) && typeof data.error === 'string' && /^[a-z_]{1,64}$/.test(data.error)
86
+ ? data.error
87
+ : 'request_failed';
88
+ throw new ChatAdminError(response.status, code);
89
+ }
90
+ if (!valid(data))
91
+ throw new ChatAdminError(502, 'invalid_response');
92
+ return data;
93
+ }
94
+ const roomResult = (data) => record(data) && typeof data.room_id === 'string';
95
+ const personResult = (data) => roomResult(data) && 'user_id' in data && typeof data.user_id === 'string';
96
+ const roomPath = (roomId) => `/channels/${identifier(roomId)}`;
97
+ return {
98
+ listChannels: (input) => request('GET', `/channels${pageQuery(100, input)}`, (data) => record(data) &&
99
+ Array.isArray(data.channels) &&
100
+ data.channels.every(channel) &&
101
+ nullableString(data.next_cursor)),
102
+ getChannel: (roomId) => request('GET', roomPath(roomId), channel),
103
+ createChannel: (input) => request('POST', '/channels', roomResult, input),
104
+ updateChannel: (roomId, input) => request('PATCH', roomPath(roomId), roomResult, input),
105
+ invitePerson: (roomId, subject) => request('POST', `${roomPath(roomId)}/people`, personResult, { subject }),
106
+ removePerson: (roomId, subject) => request('DELETE', `${roomPath(roomId)}/people/${identifier(subject)}`, personResult),
107
+ archiveChannel: (roomId) => request('POST', `${roomPath(roomId)}/archive`, (data) => roomResult(data) && 'archived' in data && data.archived === true),
108
+ deleteChannel: (roomId) => request('DELETE', roomPath(roomId), (data) => roomResult(data) && 'deleted' in data && data.deleted === true),
109
+ deactivatePerson: (subject) => request('DELETE', `/people/${identifier(subject)}`, (data) => record(data) && typeof data.user_id === 'string' && data.deactivated === true),
110
+ audit: (input) => request('GET', `/audit${pageQuery(200, input)}`, (data) => record(data) &&
111
+ Array.isArray(data.rows) &&
112
+ data.rows.every(auditRow) &&
113
+ nullableString(data.next_cursor)),
114
+ };
115
+ }
116
+ /** For a host's visibility gate, using claims ALREADY verified by its auth
117
+ * SDK. This does not verify a JWT; the service authorizes every request. */
118
+ export function hasChatAdminRole(claims, projectId, organisationId, role = 'chat.admin') {
119
+ const roles = claims[`urn:zitadel:iam:org:project:${projectId}:roles`];
120
+ if (!record(roles) || !Object.hasOwn(roles, role))
121
+ return false;
122
+ const grants = roles[role];
123
+ return record(grants) && Object.hasOwn(grants, organisationId);
124
+ }
@@ -0,0 +1,40 @@
1
+ import type { ChannelInput, ChannelPage } from './index.ts';
2
+ export type AdminPerson = {
3
+ subject: string;
4
+ name: string;
5
+ };
6
+ export type AdminCommand = {
7
+ operation: 'create';
8
+ input: ChannelInput;
9
+ } | {
10
+ operation: 'update';
11
+ roomId: string;
12
+ name: string;
13
+ topic: string;
14
+ } | {
15
+ operation: 'invite' | 'remove';
16
+ roomId: string;
17
+ subject: string;
18
+ } | {
19
+ operation: 'archive' | 'delete';
20
+ roomId: string;
21
+ } | {
22
+ operation: 'deactivate';
23
+ subject: string;
24
+ };
25
+ export type AdminOutcome = {
26
+ ok: boolean;
27
+ message: string;
28
+ };
29
+ export type AdminOverview = ChannelPage & {
30
+ people: AdminPerson[];
31
+ };
32
+ export type ChatAdminActions = {
33
+ load: (cursor?: string) => Promise<AdminOverview>;
34
+ run: (command: AdminCommand) => Promise<AdminOutcome>;
35
+ };
36
+ /** The SDK owns the controls. Hosts pass authenticated actions, not tokens;
37
+ * every action must authorize its own caller before reaching the service. */
38
+ export declare function ChatAdminPanel({ actions }: {
39
+ actions: ChatAdminActions;
40
+ }): import("react").JSX.Element;