@theokit/gateway-matrix 0.4.0 → 0.6.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.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,19 @@
1
1
  import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, MatrixMessageEvent } from '@theokit/gateway';
2
2
 
3
+ interface InviteEventLike {
4
+ getSender(): string | undefined;
5
+ }
6
+ interface InviteRoomLike {
7
+ readonly roomId: string;
8
+ getMyMembership?(): string;
9
+ /** The inviter is the sender of the bot's own member event. */
10
+ getMember?(userId: string): {
11
+ events?: {
12
+ member?: InviteEventLike;
13
+ };
14
+ } | null;
15
+ }
16
+
3
17
  /**
4
18
  * Public option types + minimal Matrix shape narrowing (kept local so
5
19
  * we don't force `matrix-js-sdk` types on consumers).
@@ -24,6 +38,22 @@ interface MatrixAdapterOptions {
24
38
  * initial sync are dropped. Default 60000 (60s).
25
39
  */
26
40
  readonly freshnessWindowMs?: number;
41
+ /**
42
+ * Deliver a room message only when it mentions the bot. Default `true`.
43
+ *
44
+ * A mention is the bot's `userId` in the event's `m.mentions.user_ids`. An event with no
45
+ * `m.mentions` (an older client) is read for the id in `body` or `formatted_body`, where a
46
+ * mention pill carries it. `m.mentions.room` alone is not a mention. A direct message (a room
47
+ * of two members) is always delivered. Pass `false` to deliver every message, as the adapter
48
+ * did before this option existed.
49
+ */
50
+ readonly requireMention?: boolean;
51
+ /**
52
+ * Decide whether to join a room the bot is invited to. Called with the inviter's user id and the
53
+ * room id; return `true` to join. Without it the bot joins nothing, and an invite stays pending,
54
+ * so a stranger cannot pull the bot into a room. A host applies its owner and allowlist rules here.
55
+ */
56
+ readonly acceptInvite?: (inviter: string, roomId: string) => boolean | Promise<boolean>;
27
57
  }
28
58
  /**
29
59
  * Minimal subset of `MatrixEvent` we read. Real events from
@@ -40,6 +70,11 @@ interface MatrixEventLike {
40
70
  getContent(): {
41
71
  body?: string;
42
72
  msgtype?: string;
73
+ formatted_body?: string;
74
+ "m.mentions"?: {
75
+ user_ids?: string[];
76
+ room?: boolean;
77
+ };
43
78
  };
44
79
  getTs(): number;
45
80
  }
@@ -102,10 +137,6 @@ interface MatrixClientLike {
102
137
  */
103
138
  declare function subscribeToTimeline(client: MatrixClientLike, handler: (event: MatrixEventLike, room: MatrixRoomLike) => void, opts: SyncFilterOpts): TimelineSubscription;
104
139
 
105
- /**
106
- * Lazy `matrix-js-sdk` loader.
107
- */
108
-
109
140
  interface MatrixSdkClient extends MatrixClientLike {
110
141
  startClient(opts: {
111
142
  initialSyncLimit: number;
@@ -125,9 +156,18 @@ interface MatrixSdkClient extends MatrixClientLike {
125
156
  sendMessage?(roomId: string, content: Record<string, unknown>): Promise<{
126
157
  event_id: string;
127
158
  }>;
159
+ /** Send a room event of `eventType` (used for `m.reaction`). */
160
+ sendEvent?(roomId: string, eventType: string, content: Record<string, unknown>): Promise<{
161
+ event_id: string;
162
+ }>;
163
+ /** `PUT /rooms/{roomId}/typing/{userId}`; present on matrix-js-sdk's client. */
164
+ sendTyping?(roomId: string, isTyping: boolean, timeoutMs: number): Promise<unknown>;
128
165
  getRoomIdForAlias(alias: string): Promise<{
129
166
  room_id: string;
130
167
  }>;
168
+ /** Join a room (used to accept an invite). */
169
+ joinRoom?(roomId: string): Promise<unknown>;
170
+ getRooms?(): InviteRoomLike[];
131
171
  getRoom(roomId: string): MatrixRoomLike | null;
132
172
  isRoomEncrypted?(roomId: string): boolean;
133
173
  /** Best-effort current user id; matrix-js-sdk returns `string | null`. */
@@ -155,6 +195,7 @@ declare class MatrixAdapter extends BasePlatformAdapter {
155
195
  private readonly opts;
156
196
  private client;
157
197
  private subscription;
198
+ private unsubscribeInvites;
158
199
  private inboundHandler;
159
200
  private readonly aliasCache;
160
201
  private connected;
@@ -178,6 +219,7 @@ declare class MatrixAdapter extends BasePlatformAdapter {
178
219
  connect(): Promise<boolean>;
179
220
  disconnect(): Promise<void>;
180
221
  sendMessage(out: OutboundMessage): Promise<SendResult>;
222
+ private sendText;
181
223
  /**
182
224
  * Matrix edits through an `m.replace` event, so the capability holds from construction: it does
183
225
  * not depend on a connection or on which client is injected later.
@@ -194,6 +236,12 @@ declare class MatrixAdapter extends BasePlatformAdapter {
194
236
  * Unlike `sendMessage`, a refused markup is not retried as plain text: one request, one answer.
195
237
  */
196
238
  editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
239
+ private editText;
240
+ /** Matrix expires a typing notice after its timeout; the runner renews it while the turn runs. */
241
+ startTyping(channelId: string): Promise<void>;
242
+ stopTyping(channelId: string): Promise<void>;
243
+ private setTyping;
244
+ react(channelId: string, messageId: string, emoji: string): Promise<SendResult>;
197
245
  /** Whether the "no markdown mode here" warning has already been emitted. */
198
246
  private warnedAboutFormat;
199
247
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
@@ -203,13 +251,20 @@ declare class MatrixAdapter extends BasePlatformAdapter {
203
251
  _installClient(client: MatrixSdkClient): void;
204
252
  private attachSync;
205
253
  private dispatchTimelineEvent;
254
+ /**
255
+ * Whether an event may reach the handler: always for a DM or with `requireMention` off,
256
+ * otherwise only when the content mentions the bot. Both `deliver()` and the sync path call it,
257
+ * so the two entries cannot disagree.
258
+ */
259
+ private passesMentionGate;
206
260
  private isEncrypted;
207
261
  private warnEncryptedOnce;
208
262
  /**
209
263
  * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
210
264
  *
211
- * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
212
- * named as the handler's failure rather than the platform's, and delivery continues.
265
+ * The mention gate runs first, as on the sync path: an event it drops answers `"ok"`, with or
266
+ * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its
267
+ * throw is named as the handler's failure rather than the platform's, and delivery continues.
213
268
  */
214
269
  deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
215
270
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,19 @@
1
1
  import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, MatrixMessageEvent } from '@theokit/gateway';
2
2
 
3
+ interface InviteEventLike {
4
+ getSender(): string | undefined;
5
+ }
6
+ interface InviteRoomLike {
7
+ readonly roomId: string;
8
+ getMyMembership?(): string;
9
+ /** The inviter is the sender of the bot's own member event. */
10
+ getMember?(userId: string): {
11
+ events?: {
12
+ member?: InviteEventLike;
13
+ };
14
+ } | null;
15
+ }
16
+
3
17
  /**
4
18
  * Public option types + minimal Matrix shape narrowing (kept local so
5
19
  * we don't force `matrix-js-sdk` types on consumers).
@@ -24,6 +38,22 @@ interface MatrixAdapterOptions {
24
38
  * initial sync are dropped. Default 60000 (60s).
25
39
  */
26
40
  readonly freshnessWindowMs?: number;
41
+ /**
42
+ * Deliver a room message only when it mentions the bot. Default `true`.
43
+ *
44
+ * A mention is the bot's `userId` in the event's `m.mentions.user_ids`. An event with no
45
+ * `m.mentions` (an older client) is read for the id in `body` or `formatted_body`, where a
46
+ * mention pill carries it. `m.mentions.room` alone is not a mention. A direct message (a room
47
+ * of two members) is always delivered. Pass `false` to deliver every message, as the adapter
48
+ * did before this option existed.
49
+ */
50
+ readonly requireMention?: boolean;
51
+ /**
52
+ * Decide whether to join a room the bot is invited to. Called with the inviter's user id and the
53
+ * room id; return `true` to join. Without it the bot joins nothing, and an invite stays pending,
54
+ * so a stranger cannot pull the bot into a room. A host applies its owner and allowlist rules here.
55
+ */
56
+ readonly acceptInvite?: (inviter: string, roomId: string) => boolean | Promise<boolean>;
27
57
  }
28
58
  /**
29
59
  * Minimal subset of `MatrixEvent` we read. Real events from
@@ -40,6 +70,11 @@ interface MatrixEventLike {
40
70
  getContent(): {
41
71
  body?: string;
42
72
  msgtype?: string;
73
+ formatted_body?: string;
74
+ "m.mentions"?: {
75
+ user_ids?: string[];
76
+ room?: boolean;
77
+ };
43
78
  };
44
79
  getTs(): number;
45
80
  }
@@ -102,10 +137,6 @@ interface MatrixClientLike {
102
137
  */
103
138
  declare function subscribeToTimeline(client: MatrixClientLike, handler: (event: MatrixEventLike, room: MatrixRoomLike) => void, opts: SyncFilterOpts): TimelineSubscription;
104
139
 
105
- /**
106
- * Lazy `matrix-js-sdk` loader.
107
- */
108
-
109
140
  interface MatrixSdkClient extends MatrixClientLike {
110
141
  startClient(opts: {
111
142
  initialSyncLimit: number;
@@ -125,9 +156,18 @@ interface MatrixSdkClient extends MatrixClientLike {
125
156
  sendMessage?(roomId: string, content: Record<string, unknown>): Promise<{
126
157
  event_id: string;
127
158
  }>;
159
+ /** Send a room event of `eventType` (used for `m.reaction`). */
160
+ sendEvent?(roomId: string, eventType: string, content: Record<string, unknown>): Promise<{
161
+ event_id: string;
162
+ }>;
163
+ /** `PUT /rooms/{roomId}/typing/{userId}`; present on matrix-js-sdk's client. */
164
+ sendTyping?(roomId: string, isTyping: boolean, timeoutMs: number): Promise<unknown>;
128
165
  getRoomIdForAlias(alias: string): Promise<{
129
166
  room_id: string;
130
167
  }>;
168
+ /** Join a room (used to accept an invite). */
169
+ joinRoom?(roomId: string): Promise<unknown>;
170
+ getRooms?(): InviteRoomLike[];
131
171
  getRoom(roomId: string): MatrixRoomLike | null;
132
172
  isRoomEncrypted?(roomId: string): boolean;
133
173
  /** Best-effort current user id; matrix-js-sdk returns `string | null`. */
@@ -155,6 +195,7 @@ declare class MatrixAdapter extends BasePlatformAdapter {
155
195
  private readonly opts;
156
196
  private client;
157
197
  private subscription;
198
+ private unsubscribeInvites;
158
199
  private inboundHandler;
159
200
  private readonly aliasCache;
160
201
  private connected;
@@ -178,6 +219,7 @@ declare class MatrixAdapter extends BasePlatformAdapter {
178
219
  connect(): Promise<boolean>;
179
220
  disconnect(): Promise<void>;
180
221
  sendMessage(out: OutboundMessage): Promise<SendResult>;
222
+ private sendText;
181
223
  /**
182
224
  * Matrix edits through an `m.replace` event, so the capability holds from construction: it does
183
225
  * not depend on a connection or on which client is injected later.
@@ -194,6 +236,12 @@ declare class MatrixAdapter extends BasePlatformAdapter {
194
236
  * Unlike `sendMessage`, a refused markup is not retried as plain text: one request, one answer.
195
237
  */
196
238
  editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
239
+ private editText;
240
+ /** Matrix expires a typing notice after its timeout; the runner renews it while the turn runs. */
241
+ startTyping(channelId: string): Promise<void>;
242
+ stopTyping(channelId: string): Promise<void>;
243
+ private setTyping;
244
+ react(channelId: string, messageId: string, emoji: string): Promise<SendResult>;
197
245
  /** Whether the "no markdown mode here" warning has already been emitted. */
198
246
  private warnedAboutFormat;
199
247
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
@@ -203,13 +251,20 @@ declare class MatrixAdapter extends BasePlatformAdapter {
203
251
  _installClient(client: MatrixSdkClient): void;
204
252
  private attachSync;
205
253
  private dispatchTimelineEvent;
254
+ /**
255
+ * Whether an event may reach the handler: always for a DM or with `requireMention` off,
256
+ * otherwise only when the content mentions the bot. Both `deliver()` and the sync path call it,
257
+ * so the two entries cannot disagree.
258
+ */
259
+ private passesMentionGate;
206
260
  private isEncrypted;
207
261
  private warnEncryptedOnce;
208
262
  /**
209
263
  * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
210
264
  *
211
- * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
212
- * named as the handler's failure rather than the platform's, and delivery continues.
265
+ * The mention gate runs first, as on the sync path: an event it drops answers `"ok"`, with or
266
+ * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its
267
+ * throw is named as the handler's failure rather than the platform's, and delivery continues.
213
268
  */
214
269
  deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
215
270
  }
package/dist/index.js CHANGED
@@ -63,6 +63,49 @@ async function loadMatrixSdk() {
63
63
  }
64
64
  }
65
65
 
66
+ // src/invite.ts
67
+ function warn(msg) {
68
+ process.stderr.write(`[gateway-matrix] ${msg}
69
+ `);
70
+ }
71
+ async function handleInvite(client, opts, inviter, roomId, seen) {
72
+ if (seen.has(roomId)) return;
73
+ seen.add(roomId);
74
+ try {
75
+ if (!await opts.acceptInvite(inviter, roomId)) return;
76
+ await client.joinRoom(roomId);
77
+ } catch (err) {
78
+ seen.delete(roomId);
79
+ warn(`join of ${roomId} failed: ${err instanceof Error ? err.message : String(err)}`);
80
+ }
81
+ }
82
+ function subscribeToInvites(client, opts) {
83
+ const seen = /* @__PURE__ */ new Set();
84
+ const run = (inviter, roomId) => {
85
+ void handleInvite(client, opts, inviter, roomId, seen).catch((err) => {
86
+ warn(`invite handling failed: ${err instanceof Error ? err.message : String(err)}`);
87
+ });
88
+ };
89
+ const onMember = (event, member) => {
90
+ if (member.userId !== opts.botUserId || member.membership !== "invite") return;
91
+ run(event.getSender() ?? "", member.roomId);
92
+ };
93
+ const scanPending = () => {
94
+ for (const room of client.getRooms?.() ?? []) {
95
+ if (room.getMyMembership?.() !== "invite") continue;
96
+ const inviter = room.getMember?.(opts.botUserId)?.events?.member?.getSender() ?? "";
97
+ run(inviter, room.roomId);
98
+ }
99
+ };
100
+ client.on("RoomMember.membership", onMember);
101
+ client.on("sync", scanPending);
102
+ scanPending();
103
+ return () => {
104
+ client.off("RoomMember.membership", onMember);
105
+ client.off("sync", scanPending);
106
+ };
107
+ }
108
+
66
109
  // src/room-state.ts
67
110
  function detectChannelType(room) {
68
111
  if (room === void 0) return "group";
@@ -96,6 +139,15 @@ function matrixEventToMessageEvent(event, room) {
96
139
  };
97
140
  }
98
141
 
142
+ // src/refuse-attachments.ts
143
+ function refuseAttachments(out) {
144
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
145
+ return {
146
+ ok: false,
147
+ error: { code: "attachments_unsupported", message: "matrix adapter cannot send attachments" }
148
+ };
149
+ }
150
+
99
151
  // src/replace-content.ts
100
152
  var HTML_FORMAT = "org.matrix.custom.html";
101
153
  function textContent(text, html) {
@@ -139,6 +191,7 @@ var MatrixAdapter = class extends BasePlatformAdapter {
139
191
  opts;
140
192
  client;
141
193
  subscription;
194
+ unsubscribeInvites;
142
195
  inboundHandler;
143
196
  aliasCache = new AliasCache();
144
197
  connected = false;
@@ -210,7 +263,11 @@ var MatrixAdapter = class extends BasePlatformAdapter {
210
263
  const msg = err instanceof Error ? err.message : String(err);
211
264
  process.stderr.write(`[gateway-matrix] connect failed: ${msg}
212
265
  `);
213
- return false;
266
+ const rest = err;
267
+ if (rest?.httpStatus === 401 || rest?.httpStatus === 403 || rest?.errcode === "M_UNKNOWN_TOKEN") {
268
+ return false;
269
+ }
270
+ throw err;
214
271
  }
215
272
  }
216
273
  async disconnect() {
@@ -218,6 +275,8 @@ var MatrixAdapter = class extends BasePlatformAdapter {
218
275
  this.tearingDown = true;
219
276
  this.subscription?.unsubscribe();
220
277
  this.subscription = void 0;
278
+ this.unsubscribeInvites?.();
279
+ this.unsubscribeInvites = void 0;
221
280
  this.client?.stopClient();
222
281
  this.client = void 0;
223
282
  this.connected = false;
@@ -225,6 +284,9 @@ var MatrixAdapter = class extends BasePlatformAdapter {
225
284
  this.aliasCache.clear();
226
285
  }
227
286
  async sendMessage(out) {
287
+ return refuseAttachments(out) ?? this.sendText(out);
288
+ }
289
+ async sendText(out) {
228
290
  if (out.text.length === 0) {
229
291
  return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
230
292
  }
@@ -268,6 +330,9 @@ var MatrixAdapter = class extends BasePlatformAdapter {
268
330
  * Unlike `sendMessage`, a refused markup is not retried as plain text: one request, one answer.
269
331
  */
270
332
  async editMessage(messageId, out) {
333
+ return refuseAttachments(out) ?? this.editText(messageId, out);
334
+ }
335
+ async editText(messageId, out) {
271
336
  if (out.text.length === 0) {
272
337
  return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
273
338
  }
@@ -309,6 +374,52 @@ var MatrixAdapter = class extends BasePlatformAdapter {
309
374
  }
310
375
  return { ok: true, messageId };
311
376
  }
377
+ /** Matrix expires a typing notice after its timeout; the runner renews it while the turn runs. */
378
+ async startTyping(channelId) {
379
+ await this.setTyping(channelId, true);
380
+ }
381
+ async stopTyping(channelId) {
382
+ await this.setTyping(channelId, false);
383
+ }
384
+ async setTyping(channelId, typing) {
385
+ const client = this.client;
386
+ if (channelId.length === 0 || client?.sendTyping === void 0) return;
387
+ try {
388
+ const roomId = await this.aliasCache.resolve(client, channelId);
389
+ await client.sendTyping(roomId, typing, 1e4);
390
+ } catch {
391
+ }
392
+ }
393
+ async react(channelId, messageId, emoji) {
394
+ if (channelId.length === 0 || messageId.length === 0 || emoji.length === 0) {
395
+ return {
396
+ ok: false,
397
+ error: { code: "invalid_reaction", message: "room, event id and emoji are required" }
398
+ };
399
+ }
400
+ const client = this.client;
401
+ if (client === void 0) {
402
+ return {
403
+ ok: false,
404
+ error: { code: "not_connected", message: "MatrixAdapter.connect() not called" }
405
+ };
406
+ }
407
+ if (client.sendEvent === void 0) {
408
+ return {
409
+ ok: false,
410
+ error: { code: "react_unsupported", message: "matrix client has no sendEvent" }
411
+ };
412
+ }
413
+ try {
414
+ const roomId = await this.aliasCache.resolve(client, channelId);
415
+ await client.sendEvent(roomId, "m.reaction", {
416
+ "m.relates_to": { rel_type: "m.annotation", event_id: messageId, key: emoji }
417
+ });
418
+ } catch (err) {
419
+ return mapMatrixError(err);
420
+ }
421
+ return { ok: true, messageId };
422
+ }
312
423
  /**
313
424
  * Send `out`, letting the caller's declared `format` decide the shape.
314
425
  *
@@ -395,6 +506,14 @@ var MatrixAdapter = class extends BasePlatformAdapter {
395
506
  botUserId: this.opts.userId,
396
507
  freshnessWindowMs: this.opts.freshnessWindowMs ?? DEFAULT_FRESHNESS_MS
397
508
  };
509
+ const acceptInvite = this.opts.acceptInvite;
510
+ if (acceptInvite !== void 0 && client.joinRoom !== void 0) {
511
+ this.unsubscribeInvites?.();
512
+ this.unsubscribeInvites = subscribeToInvites(
513
+ client,
514
+ { botUserId: this.opts.userId, acceptInvite }
515
+ );
516
+ }
398
517
  this.subscription = subscribeToTimeline(
399
518
  client,
400
519
  (ev, room) => {
@@ -414,6 +533,7 @@ var MatrixAdapter = class extends BasePlatformAdapter {
414
533
  }
415
534
  const normalized = matrixEventToMessageEvent(event, room);
416
535
  if (normalized === void 0) return;
536
+ if (!this.passesMentionGate(normalized)) return;
417
537
  if (this.inboundHandler === void 0) return;
418
538
  try {
419
539
  await this.inboundHandler(normalized);
@@ -423,6 +543,21 @@ var MatrixAdapter = class extends BasePlatformAdapter {
423
543
  `);
424
544
  }
425
545
  }
546
+ /**
547
+ * Whether an event may reach the handler: always for a DM or with `requireMention` off,
548
+ * otherwise only when the content mentions the bot. Both `deliver()` and the sync path call it,
549
+ * so the two entries cannot disagree.
550
+ */
551
+ passesMentionGate(event) {
552
+ if (event.channel.type === "dm" || !(this.opts.requireMention ?? true)) return true;
553
+ const botId = this.opts.userId;
554
+ const raw = event.platform === "matrix" ? event.matrix.raw : void 0;
555
+ const content = raw?.getContent?.();
556
+ if (content === void 0) return event.text.includes(botId);
557
+ const mentions = content["m.mentions"];
558
+ if (mentions !== void 0) return mentions.user_ids?.includes(botId) ?? false;
559
+ return (content.body ?? "").includes(botId) || (content.formatted_body ?? "").includes(botId);
560
+ }
426
561
  isEncrypted(roomId) {
427
562
  if (this.client === void 0) return false;
428
563
  if (this.client.isRoomEncrypted === void 0) return false;
@@ -443,10 +578,12 @@ var MatrixAdapter = class extends BasePlatformAdapter {
443
578
  /**
444
579
  * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
445
580
  *
446
- * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
447
- * named as the handler's failure rather than the platform's, and delivery continues.
581
+ * The mention gate runs first, as on the sync path: an event it drops answers `"ok"`, with or
582
+ * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its
583
+ * throw is named as the handler's failure rather than the platform's, and delivery continues.
448
584
  */
449
585
  async deliver(event) {
586
+ if (!this.passesMentionGate(event)) return "ok";
450
587
  return this.runHandler(this.inboundHandler, event);
451
588
  }
452
589
  };