@im-more/dsh-matrix 0.0.0-stage → 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 (86) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +14 -0
  3. package/lib/index.js +2401 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/as.d.ts +33 -0
  6. package/lib/types/as.d.ts.map +1 -0
  7. package/lib/types/as.js +237 -0
  8. package/lib/types/as.js.map +1 -0
  9. package/lib/types/bot.d.ts +109 -0
  10. package/lib/types/bot.d.ts.map +1 -0
  11. package/lib/types/bot.js +234 -0
  12. package/lib/types/bot.js.map +1 -0
  13. package/lib/types/config.d.ts +59 -0
  14. package/lib/types/config.d.ts.map +1 -0
  15. package/lib/types/config.js +67 -0
  16. package/lib/types/config.js.map +1 -0
  17. package/lib/types/decode.d.ts +56 -0
  18. package/lib/types/decode.d.ts.map +1 -0
  19. package/lib/types/decode.js +298 -0
  20. package/lib/types/decode.js.map +1 -0
  21. package/lib/types/errors.d.ts +45 -0
  22. package/lib/types/errors.d.ts.map +1 -0
  23. package/lib/types/errors.js +120 -0
  24. package/lib/types/errors.js.map +1 -0
  25. package/lib/types/html.d.ts +44 -0
  26. package/lib/types/html.d.ts.map +1 -0
  27. package/lib/types/html.js +286 -0
  28. package/lib/types/html.js.map +1 -0
  29. package/lib/types/identity.d.ts +20 -0
  30. package/lib/types/identity.d.ts.map +1 -0
  31. package/lib/types/identity.js +136 -0
  32. package/lib/types/identity.js.map +1 -0
  33. package/lib/types/index.d.ts +5 -0
  34. package/lib/types/index.d.ts.map +1 -0
  35. package/lib/types/index.js +5 -0
  36. package/lib/types/index.js.map +1 -0
  37. package/lib/types/media.d.ts +54 -0
  38. package/lib/types/media.d.ts.map +1 -0
  39. package/lib/types/media.js +94 -0
  40. package/lib/types/media.js.map +1 -0
  41. package/lib/types/mentions.d.ts +58 -0
  42. package/lib/types/mentions.d.ts.map +1 -0
  43. package/lib/types/mentions.js +94 -0
  44. package/lib/types/mentions.js.map +1 -0
  45. package/lib/types/modes/html.d.ts +13 -0
  46. package/lib/types/modes/html.d.ts.map +1 -0
  47. package/lib/types/modes/html.js +242 -0
  48. package/lib/types/modes/html.js.map +1 -0
  49. package/lib/types/modes/shared.d.ts +164 -0
  50. package/lib/types/modes/shared.d.ts.map +1 -0
  51. package/lib/types/modes/shared.js +312 -0
  52. package/lib/types/modes/shared.js.map +1 -0
  53. package/lib/types/request.d.ts +82 -0
  54. package/lib/types/request.d.ts.map +1 -0
  55. package/lib/types/request.js +206 -0
  56. package/lib/types/request.js.map +1 -0
  57. package/lib/types/rooms.d.ts +83 -0
  58. package/lib/types/rooms.d.ts.map +1 -0
  59. package/lib/types/rooms.js +177 -0
  60. package/lib/types/rooms.js.map +1 -0
  61. package/lib/types/send.d.ts +76 -0
  62. package/lib/types/send.d.ts.map +1 -0
  63. package/lib/types/send.js +172 -0
  64. package/lib/types/send.js.map +1 -0
  65. package/lib/types/types.d.ts +418 -0
  66. package/lib/types/types.d.ts.map +1 -0
  67. package/lib/types/types.js +134 -0
  68. package/lib/types/types.js.map +1 -0
  69. package/package.json +65 -3
  70. package/src/as.ts +293 -0
  71. package/src/bot.ts +338 -0
  72. package/src/config.ts +100 -0
  73. package/src/decode.ts +392 -0
  74. package/src/errors.ts +149 -0
  75. package/src/html.ts +325 -0
  76. package/src/identity.ts +165 -0
  77. package/src/index.ts +14 -0
  78. package/src/media.ts +132 -0
  79. package/src/mentions.ts +134 -0
  80. package/src/modes/html.ts +346 -0
  81. package/src/modes/shared.ts +485 -0
  82. package/src/request.ts +295 -0
  83. package/src/rooms.ts +232 -0
  84. package/src/send.ts +275 -0
  85. package/src/types.ts +633 -0
  86. package/README.md +0 -3
package/src/bot.ts ADDED
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Matrix Application Service adapter.
3
+ *
4
+ * The only transport is the homeserver's transaction push into a profile-provided `webServer`; the bot first registers
5
+ * its virtual user (`m.login.application_service`), then runs one full-state sync to learn its rooms, then registers
6
+ * the transaction route and goes online. There is no `/sync` message loop and no end-to-end encryption: encrypted
7
+ * rooms are unusable, and `m.room.encrypted` events are dropped.
8
+ *
9
+ * The mode is `html` only: Matrix's rich text is `org.matrix.custom.html` plus a plain `body`, and a plain-only mode
10
+ * would be the same payload without the two format fields. Media is uploaded to the media repository; inbound `mxc:`
11
+ * URIs are served through the authenticated download endpoint behind the bot's own `satori:` route.
12
+ */
13
+
14
+ import type { Context } from '@deepseek-ai/cordis'
15
+ import { Adapter } from '@deepseek-ai/cordis-plugin-im-core'
16
+ import type {
17
+ ChatRef,
18
+ InboundMessage,
19
+ MembersPage,
20
+ MessageHandle,
21
+ MessageRef,
22
+ Mode,
23
+ PrepareContext,
24
+ ResolvedResource,
25
+ ResourceKind,
26
+ ResourceRef,
27
+ SendContext,
28
+ SentPart,
29
+ Target,
30
+ } from '@deepseek-ai/cordis-plugin-im-core'
31
+ import { MatrixAppService } from './as.ts'
32
+ import { Config, configError } from './config.ts'
33
+ import type { Config as MatrixConfig } from './config.ts'
34
+ import { decodeEvent, decodeMessage } from './decode.ts'
35
+ import type { MatrixDecoderHost } from './decode.ts'
36
+ import { classifyMatrixError, isTokenFailure } from './errors.ts'
37
+ import { establishIdentity, matrixUserId } from './identity.ts'
38
+ import { mediaResponse, parseMxc, uploadResource } from './media.ts'
39
+ import { MatrixClient } from './request.ts'
40
+ import { enumerateRooms, RoomCache } from './rooms.ts'
41
+ import {
42
+ createReaction,
43
+ deletePart,
44
+ getMessage,
45
+ idempotentSend,
46
+ members,
47
+ sendPayload,
48
+ } from './send.ts'
49
+ import type { MatrixSendDeps } from './send.ts'
50
+ import { createHtmlMode } from './modes/html.ts'
51
+ import type { MatrixModeTypes, MatrixPayload } from './modes/shared.ts'
52
+ import { Internal } from './types.ts'
53
+
54
+ /** The one mode this adapter implements. */
55
+ export interface MatrixModes {
56
+ [mode: string]: Mode<MatrixModeTypes>
57
+ html: Mode<MatrixModeTypes>
58
+ }
59
+
60
+ /** Message of any caught value, for a log line. */
61
+ function messageOf(error: unknown): string {
62
+ return error instanceof Error ? error.message : String(error)
63
+ }
64
+
65
+ /**
66
+ * Matrix Application Service adapter.
67
+ *
68
+ * Identity is the configured virtual user (`@<id>:<host>`), registered or logged in on connect; the inbound route is
69
+ * the Application Service API below `path`; the room cache is filled by the one-shot full-state sync.
70
+ */
71
+ export class MatrixBot
72
+ extends Adapter<MatrixConfig, MatrixModes>
73
+ implements MatrixDecoderHost
74
+ {
75
+ /** The adapter needs the Satori service and the isolated `http` service. */
76
+ static override inject = ['satori', 'http']
77
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
78
+ static readonly Config = Config
79
+
80
+ readonly modes: MatrixModes = { html: createHtmlMode() }
81
+ readonly modeOrder = ['html'] as const
82
+
83
+ /** Homeserver root plus `/_matrix`, without a trailing slash. */
84
+ readonly endpoint: string
85
+ /** Client-Server transport shared by `Internal` and the adapter's own calls. */
86
+ readonly request: MatrixClient
87
+ /** The same client under the name the migrated upstream `Internal` uses (`bot.http`). */
88
+ readonly http: MatrixClient
89
+ /** Full typed Client-Server / Application Service surface (the migrated upstream client). */
90
+ override readonly internal: Internal
91
+ /** Names, members, summaries, direct markers and encryption markers per room. */
92
+ readonly rooms = new RoomCache()
93
+ /** Random process base of transaction ids, so a restart cannot collide with an old id. */
94
+ txnBase = Math.round(Math.random() * 1_000)
95
+ /** Monotonic transaction id counter. */
96
+ txnCounter = 0
97
+
98
+ private appService: MatrixAppService | undefined
99
+
100
+ /** Whether an invitation of the bot itself is joined automatically. */
101
+ get autoJoin(): boolean {
102
+ return this.config.autoJoin
103
+ }
104
+
105
+ constructor(ctx: Context, config: MatrixConfig) {
106
+ const invalid = configError(config)
107
+ if (invalid !== undefined) throw invalid
108
+ const selfId = matrixUserId(config)
109
+ super(ctx, config, {
110
+ id: `matrix:${selfId}`,
111
+ platform: 'matrix',
112
+ adapter: 'matrix',
113
+ })
114
+ this.selfId = selfId
115
+ this.user = { id: selfId, name: config.name ?? config.id, isBot: true }
116
+ this.endpoint = `${config.endpoint}/_matrix`
117
+ this.request = new MatrixClient(ctx, this.endpoint)
118
+ this.http = this.request
119
+ this.internal = new Internal(this)
120
+ this.defineInternalRoute('/media', (request) => this.serveMedia(request))
121
+ }
122
+
123
+ override async connect(): Promise<void> {
124
+ try {
125
+ await establishIdentity(this)
126
+ await this.refreshRooms()
127
+ const appService = new MatrixAppService(this)
128
+ await appService.start()
129
+ this.appService = appService
130
+ this.online()
131
+ } catch (error) {
132
+ // `Bot.start` only stores a connect failure on `bot.error`; the log line names the failure for the operator.
133
+ this.ctx.logger.error('matrix: connect failed: %s', messageOf(error))
134
+ await this.appService?.stop()
135
+ this.appService = undefined
136
+ throw error
137
+ }
138
+ }
139
+
140
+ override async disconnect(): Promise<void> {
141
+ const appService = this.appService
142
+ this.appService = undefined
143
+ await appService?.stop()
144
+ }
145
+
146
+ override async upload(
147
+ ref: ResourceRef,
148
+ _scope: string,
149
+ ctx: PrepareContext,
150
+ ): Promise<ResolvedResource> {
151
+ return await this.withApi(() => uploadResource(this.request, ref, ctx))
152
+ }
153
+
154
+ override resourceScope(_target: Target, _kind: ResourceKind): string {
155
+ // An uploaded media item belongs to the bot user and is valid in every room it sends to.
156
+ return this.id
157
+ }
158
+
159
+ override async sendPayload(
160
+ payload: unknown,
161
+ target: Target,
162
+ ctx: SendContext,
163
+ ): Promise<SentPart> {
164
+ try {
165
+ return await this.withApi(() =>
166
+ sendPayload(this.sendDeps(), payload as MatrixPayload, target, ctx),
167
+ )
168
+ } catch (error) {
169
+ // The upload already succeeded; a later failure leaves the media in the repository with no event referencing it.
170
+ const value = payload as MatrixPayload
171
+ if (value.kind === 'media') {
172
+ this.ctx.logger.warn(
173
+ 'matrix: a send attempt for uploaded media %s failed: %s',
174
+ value.url,
175
+ messageOf(error),
176
+ )
177
+ }
178
+ throw error
179
+ }
180
+ }
181
+
182
+ override idempotentSend(target: Target, ctx: SendContext): boolean {
183
+ return idempotentSend(target, ctx)
184
+ }
185
+
186
+ override async deletePart(
187
+ part: SentPart,
188
+ handle: MessageHandle,
189
+ ): Promise<void> {
190
+ await this.withApi(() => deletePart(this.sendDeps(), part, handle))
191
+ }
192
+
193
+ override async createReaction(
194
+ message: MessageRef,
195
+ emoji: string,
196
+ ): Promise<void> {
197
+ await this.withApi(() => createReaction(this.sendDeps(), message, emoji))
198
+ }
199
+
200
+ override async members(
201
+ chat: ChatRef,
202
+ cursor?: string,
203
+ limit?: number,
204
+ ): Promise<MembersPage> {
205
+ return await this.withApi(() =>
206
+ members(this.sendDeps(), chat, cursor, limit),
207
+ )
208
+ }
209
+
210
+ override async getMessage(
211
+ chat: ChatRef,
212
+ id: string,
213
+ ): Promise<InboundMessage> {
214
+ return await this.withApi(() => getMessage(this.sendDeps(), chat, id))
215
+ }
216
+
217
+ override classify(error: unknown) {
218
+ return classifyMatrixError(error)
219
+ }
220
+
221
+ /** Decode one Application Service event into the session the transport publishes. */
222
+ async decode(event: Parameters<typeof decodeEvent>[1]) {
223
+ return await decodeEvent(this, event)
224
+ }
225
+
226
+ /** Debug log of one dropped inbound event. */
227
+ log(message: string): void {
228
+ this.ctx.logger.debug(message)
229
+ }
230
+
231
+ /** Warning log of an unreadable room or a failed state refresh. */
232
+ warn(message: string): void {
233
+ this.ctx.logger.warn(message)
234
+ }
235
+
236
+ /** Join one room without refreshing; the self-join event triggers the refresh. */
237
+ async joinRoom(roomId: string): Promise<void> {
238
+ await this.internal.joinRoom(roomId)
239
+ }
240
+
241
+ /**
242
+ * Run the one-shot full-state sync and apply it, joining the rooms the bot was invited into when `autoJoin` is on.
243
+ *
244
+ * The sync's timeline is history the host store already owns, so it is only read for state. A successful join runs
245
+ * the same query once more, which is what puts the new room's name, members and summary in the cache.
246
+ */
247
+ async refreshRooms(): Promise<void> {
248
+ const invites = await enumerateRooms(this.internal, this.rooms, this.selfId)
249
+ if (invites.length === 0) return
250
+ if (!this.config.autoJoin) {
251
+ for (const roomId of invites)
252
+ this.ctx.logger.info(
253
+ `matrix: invited to ${roomId}; autoJoin is off, so it is not joined`,
254
+ )
255
+ return
256
+ }
257
+ let joined = false
258
+ for (const roomId of invites) {
259
+ try {
260
+ await this.internal.joinRoom(roomId)
261
+ joined = true
262
+ } catch (error) {
263
+ // The invitation stays in force, so a later connect retries it; one unjoinable room must not fail the rest.
264
+ this.ctx.logger.warn(
265
+ `matrix: could not join invited room ${roomId}: ${messageOf(error)}`,
266
+ )
267
+ }
268
+ }
269
+ if (joined) await enumerateRooms(this.internal, this.rooms, this.selfId)
270
+ }
271
+
272
+ /**
273
+ * Take the bot offline when a Client-Server call reports that its token is gone.
274
+ * @param error - the caught failure of an outbound call or an inbound event handler.
275
+ */
276
+ noteRuntimeError(error: unknown): void {
277
+ if (!isTokenFailure(error)) return
278
+ this.ctx.logger.error(
279
+ 'matrix: the user access token was rejected (%s); replace the registration credentials and restart',
280
+ messageOf(error),
281
+ )
282
+ this.offline(error)
283
+ }
284
+
285
+ /** Adapt one authenticated media download into the host's response. */
286
+ private async serveMedia(
287
+ request: Request & { query: URLSearchParams },
288
+ ): Promise<Response> {
289
+ const value = request.query.get('mxc')
290
+ if (value === null) return new Response(null, { status: 400 })
291
+ const parsed = parseMxc(
292
+ value.startsWith('mxc://') ? value : `mxc://${value}`,
293
+ )
294
+ if (parsed === undefined) return new Response(null, { status: 400 })
295
+ try {
296
+ return mediaResponse(
297
+ await this.request.download(parsed.serverName, parsed.mediaId),
298
+ )
299
+ } catch (error) {
300
+ this.noteRuntimeError(error)
301
+ this.ctx.logger.warn(
302
+ 'matrix: media %s/%s could not be served: %s',
303
+ parsed.serverName,
304
+ parsed.mediaId,
305
+ messageOf(error),
306
+ )
307
+ return new Response(null, { status: 502 })
308
+ }
309
+ }
310
+
311
+ /** Run one outbound call, marking the bot offline when the failure is a dead token. */
312
+ private async withApi<T>(run: () => Promise<T>): Promise<T> {
313
+ try {
314
+ return await run()
315
+ } catch (error) {
316
+ this.noteRuntimeError(error)
317
+ throw error
318
+ }
319
+ }
320
+
321
+ private sendDeps(): MatrixSendDeps {
322
+ return {
323
+ client: this.request,
324
+ selfId: this.selfId,
325
+ nextTxn: () => this.txnBase + this.txnCounter++,
326
+ rooms: this.rooms,
327
+ isBot: (userId) =>
328
+ this.ctx.bots.some(
329
+ (bot) => bot.platform === 'matrix' && bot.selfId === userId,
330
+ ),
331
+ decode: (chat, event) => decodeMessage(this, event, chat),
332
+ }
333
+ }
334
+ }
335
+
336
+ export { Config }
337
+
338
+ export default MatrixBot
package/src/config.ts ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The Application Service configuration: the registration credentials, the virtual user, the inbound route and the
3
+ * media request defaults. There is no transport switch — the homeserver's transaction push is the only intake.
4
+ *
5
+ * `endpoint` defaults to `https://<host>`; trailing slashes are removed so the client can append `/_matrix` once.
6
+ */
7
+
8
+ import z from '@deepseek-ai/schemastery'
9
+
10
+ /** A schema-required field, narrowed from the transform's nullable view of an object schema. */
11
+ function required(value: string | null | undefined, field: string): string {
12
+ if (value === undefined || value === null || value === '') {
13
+ throw new Error(`matrix: ${field} is required`)
14
+ }
15
+ return value
16
+ }
17
+
18
+ /** One Matrix Application Service bot. */
19
+ export interface Config {
20
+ /** Homeserver root (`https://<host>` unless the homeserver lives elsewhere); `/_matrix` is appended. */
21
+ endpoint: string
22
+ /** Homeserver server name; the virtual user is `@<id>:<host>`. */
23
+ host: string
24
+ /** Localpart of the AS virtual user; it must fall inside the registration's users namespace. */
25
+ id: string
26
+ /** The registration's `as_token` (`role('secret')`). */
27
+ asToken: string
28
+ /** The registration's `hs_token`, used to verify inbound transactions (`role('secret')`). */
29
+ hsToken: string
30
+ /** Prefix of the inbound Application Service route; the registration's `url` points at it. */
31
+ path: string
32
+ /** Display name written to the AS user when set. */
33
+ name?: string | null
34
+ /** Avatar URL downloaded and written to the AS user when set. */
35
+ avatar?: string | null
36
+ /** Join a room the bot is invited to (an AS virtual user has no second login entry). */
37
+ autoJoin: boolean
38
+ }
39
+
40
+ /** Validated Matrix adapter configuration; `endpoint` is always resolved. */
41
+ export const Config = z.transform(
42
+ z.object({
43
+ endpoint: z.string().role('url'),
44
+ host: z.string().required(),
45
+ id: z.string().required(),
46
+ asToken: z.string().role('secret').required(),
47
+ hsToken: z.string().role('secret').required(),
48
+ path: z.string().default('/matrix'),
49
+ name: z.string(),
50
+ avatar: z.string(),
51
+ autoJoin: z.boolean().default(true),
52
+ }),
53
+ (value): Config => ({
54
+ ...value,
55
+ endpoint: (
56
+ value.endpoint ?? `https://${required(value.host, 'host')}`
57
+ ).replace(/\/+$/, ''),
58
+ host: required(value.host, 'host'),
59
+ id: required(value.id, 'id'),
60
+ asToken: required(value.asToken, 'asToken'),
61
+ hsToken: required(value.hsToken, 'hsToken'),
62
+ path: value.path ?? '/matrix',
63
+ autoJoin: value.autoJoin ?? true,
64
+ }),
65
+ )
66
+
67
+ /** Validated Matrix adapter configuration, also exported as `MatrixConfig`. */
68
+ export type MatrixConfig = Config
69
+
70
+ /**
71
+ * The endpoint the adapter refuses to start with.
72
+ *
73
+ * The schema marks `endpoint` as a URL for profile renderers, but only this check makes a malformed root fail before
74
+ * the first request instead of on every call.
75
+ *
76
+ * @param config - the validated configuration.
77
+ * @returns the configuration error, or undefined when the endpoint is usable.
78
+ */
79
+ export function configError(config: Config): Error | undefined {
80
+ let url: URL
81
+ try {
82
+ url = new URL(config.endpoint)
83
+ } catch {
84
+ return new Error('matrix: endpoint must be an absolute http(s) URL')
85
+ }
86
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
87
+ return new Error('matrix: endpoint must be an absolute http(s) URL')
88
+ }
89
+ return undefined
90
+ }
91
+
92
+ /**
93
+ * Normalize an inbound route path: absolute, no trailing slash.
94
+ * @param path - the configured `path`.
95
+ * @returns the pathname to register.
96
+ */
97
+ export function routePath(path: string): string {
98
+ const withSlash = path.startsWith('/') ? path : `/${path}`
99
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, '') : withSlash
100
+ }