@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
@@ -0,0 +1,134 @@
1
+ import imageSize from 'image-size';
2
+ export class Internal {
3
+ bot;
4
+ txnId = Math.round(Math.random() * 1000);
5
+ constructor(bot) {
6
+ this.bot = bot;
7
+ }
8
+ async uploadFile(filename, buffer, mimetype) {
9
+ const headers = {};
10
+ if (mimetype)
11
+ headers['content-type'] = mimetype;
12
+ return (await this.bot.http.post(`/media/v3/upload?filename=${filename}`, buffer, { headers })).content_uri;
13
+ }
14
+ async sendTextMessage(roomId, content, reply) {
15
+ const eventContent = {
16
+ msgtype: 'm.text',
17
+ body: content,
18
+ };
19
+ if (reply)
20
+ eventContent['m.relates_to'] = { 'm.in_reply_to': { 'event_id': reply } };
21
+ const response = await this.bot.http.put(`/client/v3/rooms/${roomId}/send/m.room.message/${this.txnId++}`, eventContent);
22
+ return response.event_id;
23
+ }
24
+ async sendMediaMessage(roomId, type, buffer, reply, mimetype, filename = 'file') {
25
+ const uri = await this.uploadFile(filename, buffer, mimetype);
26
+ let info;
27
+ if (type === 'image') {
28
+ const { width, height } = imageSize(buffer);
29
+ info = {
30
+ size: buffer.byteLength,
31
+ h: height,
32
+ w: width,
33
+ ...(mimetype === undefined ? {} : { mimetype }),
34
+ };
35
+ }
36
+ const eventContent = {
37
+ msgtype: `m.${type}`,
38
+ body: filename,
39
+ url: uri,
40
+ ...(info === undefined ? {} : { info }),
41
+ };
42
+ if (reply)
43
+ eventContent['m.relates_to'] = { 'm.in_reply_to': { 'event_id': reply } };
44
+ const response = await this.bot.http.put(`/client/v3/rooms/${roomId}/send/m.room.message/${this.txnId++}`, eventContent);
45
+ return response.event_id;
46
+ }
47
+ async sendReaction(roomId, messageId, key) {
48
+ const eventContent = {
49
+ 'm.relates_to': {
50
+ rel_type: 'm.annotation',
51
+ event_id: messageId,
52
+ key,
53
+ },
54
+ };
55
+ const response = await this.bot.http.put(`/client/v3/rooms/${roomId}/send/m.reaction/${this.txnId++}`, eventContent);
56
+ return response.event_id;
57
+ }
58
+ async getEvent(roomId, eventId) {
59
+ return await this.bot.http.get(`/client/v3/rooms/${roomId}/event/${eventId}`);
60
+ }
61
+ async redactEvent(roomId, eventId, reason) {
62
+ const event = await this.bot.http.put(`/client/v3/rooms/${roomId}/redact/${eventId}/${this.txnId++}`, { reason });
63
+ return event.event_id;
64
+ }
65
+ async getProfile(userId) {
66
+ return await this.bot.http.get(`/client/v3/profile/${userId}`);
67
+ }
68
+ async setDisplayName(userId, displayname) {
69
+ await this.bot.http.put(`/client/v3/profile/${userId}/displayname`, { displayname });
70
+ }
71
+ async setAvatar(userId, buffer, mimetype) {
72
+ const uri = await this.uploadFile('avatar', buffer, mimetype);
73
+ await this.bot.http.put(`/client/v3/profile/${userId}/avatar_url`, { avatar_url: uri });
74
+ }
75
+ async createRoom(creation) {
76
+ const response = await this.bot.http.post('/client/v3/createRoom', creation);
77
+ return response.room_id;
78
+ }
79
+ async joinRoom(roomId, reason) {
80
+ const response = await this.bot.http.post(`/client/v3/join/${roomId}`, { reason });
81
+ return response.room_id;
82
+ }
83
+ async leaveRoom(roomId, reason) {
84
+ const response = await this.bot.http.post(`/client/v3/rooms/${roomId}/leave`, { reason });
85
+ return response.room_id;
86
+ }
87
+ async invite(roomId, userId, reason) {
88
+ await this.bot.http.post(`/client/v3/rooms/${roomId}/invite`, { user_id: userId, reason });
89
+ }
90
+ async sync(fullSstate = false) {
91
+ return await this.bot.http.get('/client/v3/sync', {
92
+ params: { full_state: fullSstate },
93
+ });
94
+ }
95
+ async getState(roomId) {
96
+ return await this.bot.http.get(`/client/v3/rooms/${roomId}/state`);
97
+ }
98
+ async setState(roomId, eventType, event, state) {
99
+ const statePath = state ? `/${state}` : '';
100
+ const response = await this.bot.http.put(`/client/v3/rooms/${roomId}/state/${eventType}${statePath}`, event);
101
+ return response.event_id;
102
+ }
103
+ async getJoinedRooms() {
104
+ return await this.bot.http.get('/client/v3/joined_rooms');
105
+ }
106
+ async register(username, asToken) {
107
+ return await this.bot.ctx.http.post(this.bot.endpoint + '/client/v3/register', {
108
+ type: 'm.login.application_service',
109
+ username,
110
+ }, {
111
+ headers: {
112
+ 'Authorization': `Bearer ${asToken}`,
113
+ },
114
+ });
115
+ }
116
+ async login(username, asToken) {
117
+ return await this.bot.ctx.http.post(this.bot.endpoint + '/client/v3/login', {
118
+ type: 'm.login.application_service',
119
+ identifier: {
120
+ type: 'm.id.user',
121
+ user: username,
122
+ },
123
+ }, {
124
+ headers: {
125
+ 'Authorization': `Bearer ${asToken}`,
126
+ },
127
+ });
128
+ }
129
+ getAssetUrl(mxc) {
130
+ // mxc://
131
+ return `${this.bot.endpoint}/client/v1/media/download/${mxc.substring(6)}`;
132
+ }
133
+ }
134
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,YAAY,CAAA;AAgelC,MAAM,OAAO,QAAQ;IAGA;IAFX,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CAAA;IAEhD,YAAmB,GAAc;QAAd,QAAG,GAAH,GAAG,CAAW;IAAG,CAAC;IAErC,KAAK,CAAC,UAAU,CAAC,QAAgB,EAAE,MAAc,EAAE,QAAiB;QAClE,MAAM,OAAO,GAA2B,EAAE,CAAA;QAC1C,IAAI,QAAQ;YAAE,OAAO,CAAC,cAAc,CAAC,GAAG,QAAQ,CAAA;QAChD,OAAO,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,6BAA6B,QAAQ,EAAE,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,WAAW,CAAA;IAC7G,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,MAAc,EAAE,OAAe,EAAE,KAAc;QACnE,MAAM,YAAY,GAAW;YAC3B,OAAO,EAAE,QAAQ;YACjB,IAAI,EAAE,OAAO;SACd,CAAA;QACD,IAAI,KAAK;YAAE,YAAY,CAAC,cAAc,CAAC,GAAG,EAAE,eAAe,EAAE,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE,CAAA;QACpF,MAAM,QAAQ,GAAG,MAAM,IAAI,CAA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C,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,GAAG,kBAAkB,EAAE;YAC1E,IAAI,EAAE,6BAA6B;YACnC,UAAU,EAAE;gBACV,IAAI,EAAE,WAAW;gBACjB,IAAI,EAAE,QAAQ;aACf;SACF,EAAE;YACD,OAAO,EAAE;gBACP,eAAe,EAAE,UAAU,OAAO,EAAE;aACrC;SACF,CAAC,CAAA;IACJ,CAAC;IAED,WAAW,CAAC,GAAW;QACrB,SAAS;QACT,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,6BAA6B,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAA;IAC5E,CAAC;CACF"}
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "@im-more/dsh-matrix",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Matrix adapter for official dsh-im of DeepSeek Harness",
5
+ "homepage": "https://github.com/ilharp/dsh-im-more",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/ilharp/dsh-im-more.git",
9
+ "directory": "packages/matrix"
10
+ },
11
+ "author": {
12
+ "name": "Il Harper",
13
+ "email": "hi@ilharper.com",
14
+ "url": "https://ilharper.com"
15
+ },
16
+ "license": "MIT",
17
+ "type": "module",
18
+ "main": "lib/index.js",
19
+ "types": "lib/types/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./lib/types/index.d.ts",
23
+ "default": "./lib/index.js"
24
+ },
25
+ "./package.json": "./package.json",
26
+ "./cordis.patch.yml": "./cordis.patch.yml"
27
+ },
28
+ "files": [
29
+ "lib",
30
+ "src",
31
+ "cordis.patch.yml"
32
+ ],
33
+ "engines": {
34
+ "dsh": ">=0.2.3-alpha.3"
35
+ },
36
+ "peerDependencies": {
37
+ "@deepseek-ai/cordis": ">=4.2.0-alpha.2",
38
+ "@deepseek-ai/cordis-plugin-http": ">=1.6.1-alpha.2",
39
+ "@deepseek-ai/cordis-plugin-im-core": ">=5.0.1-alpha.2",
40
+ "@deepseek-ai/satori-element": ">=4.0.1-alpha.2",
41
+ "@deepseek-ai/schemastery": ">=3.20.0-alpha.2"
42
+ },
43
+ "dependencies": {
44
+ "html5parser": "^2.0.2",
45
+ "image-size": "^2.0.2"
46
+ },
47
+ "devDependencies": {
48
+ "@deepseek-ai/cordis": ">=4.2.0-alpha.2",
49
+ "@deepseek-ai/cordis-plugin-http": ">=1.6.1-alpha.2",
50
+ "@deepseek-ai/cordis-plugin-im-core": ">=5.0.1-alpha.2",
51
+ "@deepseek-ai/satori-element": ">=4.0.1-alpha.2",
52
+ "@deepseek-ai/schemastery": ">=3.20.0-alpha.2",
53
+ "@types/node": "^22.20.1",
54
+ "tsdown": "^0.22.2",
55
+ "typescript": "^6.0.3",
56
+ "vitest": "^4.1.11"
57
+ },
58
+ "dsh": {
59
+ "bundle": {
60
+ "patch": "./cordis.patch.yml"
61
+ }
62
+ },
63
+ "scripts": {
64
+ "build": "tsc -p tsconfig.json && tsdown",
65
+ "typecheck": "tsc -p tsconfig.test.json",
66
+ "test": "vitest run"
67
+ }
6
68
  }
package/src/as.ts ADDED
@@ -0,0 +1,293 @@
1
+ /**
2
+ * The Application Service inbound transport.
3
+ *
4
+ * The profile's `webServer` owns the listener, so this transport registers one anonymous prefix route at the configured
5
+ * path and implements the Application Service API under it: transaction pushes (current and legacy path forms), the
6
+ * `users` query, the `rooms` query (always unknown) and the v1.7 `ping`. Every request is authenticated by `hs_token`,
7
+ * with the legacy `?access_token=` form accepted and refused when it contradicts a Bearer header.
8
+ *
9
+ * A transaction is confirmed only after every event reached intake: a failed event answers `500`, so the homeserver
10
+ * redelivers the batch with the same transaction id and the host's event-id deduplication removes the copies it already
11
+ * stored. That is the opposite of the upstream adapter's confirm-first order, which loses an event whose store failed.
12
+ */
13
+
14
+ import { timingSafeEqual } from 'node:crypto'
15
+ import type { IncomingMessage, ServerResponse } from 'node:http'
16
+ import type { MatrixBot } from './bot.ts'
17
+ import { routePath } from './config.ts'
18
+ import type { ClientEvent } from './types.ts'
19
+
20
+ /** The part of `ctx.webServer` this adapter uses. */
21
+ interface WebServerLike {
22
+ register(route: {
23
+ kind: 'prefix'
24
+ path: string
25
+ auth: 'anonymous'
26
+ handler: (
27
+ request: IncomingMessage,
28
+ response: ServerResponse,
29
+ ) => void | Promise<void>
30
+ }): () => void
31
+ }
32
+
33
+ /** The prefixes a transaction push uses: the current Application Service path and the legacy one. */
34
+ const TRANSACTION_PREFIXES = ['/_matrix/app/v1/transactions/', '/transactions/']
35
+
36
+ /** The route families whose methods are fixed. */
37
+ const PING_PATH = '/_matrix/app/v1/ping'
38
+ const USERS_PREFIX = '/_matrix/app/v1/users/'
39
+ const ROOMS_PREFIX = '/_matrix/app/v1/rooms/'
40
+
41
+ /** Compare two secrets without leaking where they differ. */
42
+ function secretMatches(expected: string, received: string): boolean {
43
+ const left = Buffer.from(expected, 'utf8')
44
+ const right = Buffer.from(received, 'utf8')
45
+ if (left.length !== right.length) return false
46
+ return timingSafeEqual(left, right)
47
+ }
48
+
49
+ /** The Bearer token of a request, when it used the current scheme. */
50
+ function bearerOf(request: IncomingMessage): string | undefined {
51
+ const header = request.headers.authorization
52
+ if (typeof header !== 'string') return undefined
53
+ const match = /^Bearer\s+(.+)$/i.exec(header)
54
+ return match?.[1]
55
+ }
56
+
57
+ /** Read a request body to its end. The adapter imposes no size limit of its own. */
58
+ async function readBody(request: IncomingMessage): Promise<string> {
59
+ const chunks: Buffer[] = []
60
+ for await (const chunk of request) {
61
+ chunks.push(
62
+ Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array),
63
+ )
64
+ }
65
+ return Buffer.concat(chunks).toString('utf8')
66
+ }
67
+
68
+ /** Write one bodiless answer. */
69
+ function writeStatus(
70
+ response: ServerResponse,
71
+ status: number,
72
+ headers: Record<string, string> = {},
73
+ ): void {
74
+ if (response.headersSent) {
75
+ response.end()
76
+ return
77
+ }
78
+ response.writeHead(status, headers)
79
+ response.end()
80
+ }
81
+
82
+ /** Write one JSON answer. */
83
+ function writeJson(
84
+ response: ServerResponse,
85
+ status: number,
86
+ body: unknown,
87
+ ): void {
88
+ if (response.headersSent) {
89
+ response.end()
90
+ return
91
+ }
92
+ response.writeHead(status, { 'content-type': 'application/json' })
93
+ response.end(JSON.stringify(body))
94
+ }
95
+
96
+ /** The `M_UNRECOGNIZED` answer the specification asks unknown routes to use. */
97
+ function writeUnrecognized(response: ServerResponse): void {
98
+ writeJson(response, 404, {
99
+ errcode: 'M_UNRECOGNIZED',
100
+ error: 'Unrecognized request',
101
+ })
102
+ }
103
+
104
+ /** Message of any caught value, for a log line. */
105
+ function messageOf(error: unknown): string {
106
+ return error instanceof Error ? error.message : String(error)
107
+ }
108
+
109
+ /** The transaction id of one subpath, when the subpath is a transaction route. */
110
+ function transactionIdOf(sub: string): string | undefined {
111
+ for (const prefix of TRANSACTION_PREFIXES) {
112
+ if (!sub.startsWith(prefix)) continue
113
+ const id = sub.slice(prefix.length)
114
+ return id === '' ? undefined : id
115
+ }
116
+ return undefined
117
+ }
118
+
119
+ /** The Application Service transport of one bot. */
120
+ export class MatrixAppService {
121
+ private dispose: (() => void) | undefined
122
+
123
+ constructor(private readonly bot: MatrixBot) {}
124
+
125
+ /** Register the prefix route; a profile without a web server fails with an actionable message. */
126
+ async start(): Promise<void> {
127
+ const webServer = this.bot.ctx.get('webServer') as WebServerLike | undefined
128
+ if (webServer === undefined) {
129
+ throw this.fail(
130
+ 'matrix: the Application Service needs a profile-provided webServer; ' +
131
+ "the homeserver must reach the route named by the registration's url",
132
+ )
133
+ }
134
+ this.dispose = webServer.register({
135
+ kind: 'prefix',
136
+ path: routePath(this.bot.config.path),
137
+ auth: 'anonymous',
138
+ handler: (request, response) => this.handle(request, response),
139
+ })
140
+ }
141
+
142
+ /** Release the route. */
143
+ async stop(): Promise<void> {
144
+ this.dispose?.()
145
+ this.dispose = undefined
146
+ }
147
+
148
+ /** Log a fatal start failure before the caller throws it (`Bot.start` only stores a connect failure). */
149
+ private fail(message: string): Error {
150
+ this.bot.ctx.logger.error(message)
151
+ return new Error(message)
152
+ }
153
+
154
+ private async handle(
155
+ request: IncomingMessage,
156
+ response: ServerResponse,
157
+ ): Promise<void> {
158
+ try {
159
+ const base = routePath(this.bot.config.path)
160
+ const url = new URL(request.url ?? '/', 'http://matrix.invalid')
161
+ const inside =
162
+ base === '/' ||
163
+ url.pathname === base ||
164
+ url.pathname.startsWith(`${base}/`)
165
+ if (!inside) {
166
+ writeUnrecognized(response)
167
+ return
168
+ }
169
+ if (!this.authorized(request, url.searchParams)) {
170
+ writeStatus(response, 403)
171
+ return
172
+ }
173
+ const sub = base === '/' ? url.pathname : url.pathname.slice(base.length)
174
+ const txnId = transactionIdOf(sub)
175
+ if (txnId !== undefined) {
176
+ if (request.method !== 'PUT') {
177
+ writeStatus(response, 405, { allow: 'PUT' })
178
+ return
179
+ }
180
+ await this.transaction(request, response, txnId)
181
+ return
182
+ }
183
+ if (sub === PING_PATH) {
184
+ if (request.method !== 'POST') {
185
+ writeStatus(response, 405, { allow: 'POST' })
186
+ return
187
+ }
188
+ writeJson(response, 200, {})
189
+ return
190
+ }
191
+ if (sub.startsWith(USERS_PREFIX)) {
192
+ if (request.method !== 'GET') {
193
+ writeStatus(response, 405, { allow: 'GET' })
194
+ return
195
+ }
196
+ this.users(response, sub.slice(USERS_PREFIX.length))
197
+ return
198
+ }
199
+ if (sub.startsWith(ROOMS_PREFIX)) {
200
+ if (request.method !== 'GET') {
201
+ writeStatus(response, 405, { allow: 'GET' })
202
+ return
203
+ }
204
+ writeUnrecognized(response)
205
+ return
206
+ }
207
+ writeUnrecognized(response)
208
+ } catch (error) {
209
+ // A route must never leave the listener without an answer.
210
+ this.bot.ctx.logger.warn(
211
+ 'matrix: Application Service request failed: %s',
212
+ messageOf(error),
213
+ )
214
+ writeStatus(response, 500)
215
+ }
216
+ }
217
+
218
+ /** Whether one request carries the registration's `hs_token` in exactly one consistent form. */
219
+ private authorized(
220
+ request: IncomingMessage,
221
+ query: URLSearchParams,
222
+ ): boolean {
223
+ const bearer = bearerOf(request)
224
+ const legacy = query.get('access_token') ?? undefined
225
+ if (bearer !== undefined && legacy !== undefined && bearer !== legacy)
226
+ return false
227
+ const token = bearer ?? legacy
228
+ if (token === undefined) return false
229
+ return secretMatches(this.bot.config.hsToken, token)
230
+ }
231
+
232
+ /** Read and process one transaction; the answer is `200 {}` only after every event reached intake. */
233
+ private async transaction(
234
+ request: IncomingMessage,
235
+ response: ServerResponse,
236
+ txnId: string,
237
+ ): Promise<void> {
238
+ const body = await readBody(request)
239
+ let parsed: unknown
240
+ try {
241
+ parsed = JSON.parse(body)
242
+ } catch (error) {
243
+ this.bot.ctx.logger.warn(
244
+ 'matrix: cannot parse transaction %s: %s',
245
+ txnId,
246
+ messageOf(error),
247
+ )
248
+ writeStatus(response, 400)
249
+ return
250
+ }
251
+ if (typeof parsed !== 'object' || parsed === null) {
252
+ writeStatus(response, 400)
253
+ return
254
+ }
255
+ const events = (parsed as { events?: unknown }).events
256
+ if (!Array.isArray(events)) {
257
+ writeStatus(response, 400)
258
+ return
259
+ }
260
+ try {
261
+ for (const raw of events) {
262
+ if (typeof raw !== 'object' || raw === null) continue
263
+ const session = await this.bot.decode(raw as ClientEvent)
264
+ if (session !== undefined) await this.bot.receive(session)
265
+ }
266
+ } catch (error) {
267
+ this.bot.noteRuntimeError(error)
268
+ this.bot.ctx.logger.warn(
269
+ 'matrix: transaction %s failed; the homeserver redelivers it: %s',
270
+ txnId,
271
+ messageOf(error),
272
+ )
273
+ writeStatus(response, 500)
274
+ return
275
+ }
276
+ writeJson(response, 200, {})
277
+ }
278
+
279
+ /** Answer the `users` query: only the AS virtual user exists. */
280
+ private users(response: ServerResponse, encoded: string): void {
281
+ let userId = encoded
282
+ try {
283
+ userId = decodeURIComponent(encoded)
284
+ } catch {
285
+ // A malformed escape is simply not a user this service owns.
286
+ }
287
+ if (userId !== this.bot.selfId) {
288
+ writeUnrecognized(response)
289
+ return
290
+ }
291
+ writeJson(response, 200, {})
292
+ }
293
+ }