@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,237 @@
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
+ import { timingSafeEqual } from 'node:crypto';
14
+ import { routePath } from "./config.js";
15
+ /** The prefixes a transaction push uses: the current Application Service path and the legacy one. */
16
+ const TRANSACTION_PREFIXES = ['/_matrix/app/v1/transactions/', '/transactions/'];
17
+ /** The route families whose methods are fixed. */
18
+ const PING_PATH = '/_matrix/app/v1/ping';
19
+ const USERS_PREFIX = '/_matrix/app/v1/users/';
20
+ const ROOMS_PREFIX = '/_matrix/app/v1/rooms/';
21
+ /** Compare two secrets without leaking where they differ. */
22
+ function secretMatches(expected, received) {
23
+ const left = Buffer.from(expected, 'utf8');
24
+ const right = Buffer.from(received, 'utf8');
25
+ if (left.length !== right.length)
26
+ return false;
27
+ return timingSafeEqual(left, right);
28
+ }
29
+ /** The Bearer token of a request, when it used the current scheme. */
30
+ function bearerOf(request) {
31
+ const header = request.headers.authorization;
32
+ if (typeof header !== 'string')
33
+ return undefined;
34
+ const match = /^Bearer\s+(.+)$/i.exec(header);
35
+ return match?.[1];
36
+ }
37
+ /** Read a request body to its end. The adapter imposes no size limit of its own. */
38
+ async function readBody(request) {
39
+ const chunks = [];
40
+ for await (const chunk of request) {
41
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
42
+ }
43
+ return Buffer.concat(chunks).toString('utf8');
44
+ }
45
+ /** Write one bodiless answer. */
46
+ function writeStatus(response, status, headers = {}) {
47
+ if (response.headersSent) {
48
+ response.end();
49
+ return;
50
+ }
51
+ response.writeHead(status, headers);
52
+ response.end();
53
+ }
54
+ /** Write one JSON answer. */
55
+ function writeJson(response, status, body) {
56
+ if (response.headersSent) {
57
+ response.end();
58
+ return;
59
+ }
60
+ response.writeHead(status, { 'content-type': 'application/json' });
61
+ response.end(JSON.stringify(body));
62
+ }
63
+ /** The `M_UNRECOGNIZED` answer the specification asks unknown routes to use. */
64
+ function writeUnrecognized(response) {
65
+ writeJson(response, 404, {
66
+ errcode: 'M_UNRECOGNIZED',
67
+ error: 'Unrecognized request',
68
+ });
69
+ }
70
+ /** Message of any caught value, for a log line. */
71
+ function messageOf(error) {
72
+ return error instanceof Error ? error.message : String(error);
73
+ }
74
+ /** The transaction id of one subpath, when the subpath is a transaction route. */
75
+ function transactionIdOf(sub) {
76
+ for (const prefix of TRANSACTION_PREFIXES) {
77
+ if (!sub.startsWith(prefix))
78
+ continue;
79
+ const id = sub.slice(prefix.length);
80
+ return id === '' ? undefined : id;
81
+ }
82
+ return undefined;
83
+ }
84
+ /** The Application Service transport of one bot. */
85
+ export class MatrixAppService {
86
+ bot;
87
+ dispose;
88
+ constructor(bot) {
89
+ this.bot = bot;
90
+ }
91
+ /** Register the prefix route; a profile without a web server fails with an actionable message. */
92
+ async start() {
93
+ const webServer = this.bot.ctx.get('webServer');
94
+ if (webServer === undefined) {
95
+ throw this.fail('matrix: the Application Service needs a profile-provided webServer; ' +
96
+ "the homeserver must reach the route named by the registration's url");
97
+ }
98
+ this.dispose = webServer.register({
99
+ kind: 'prefix',
100
+ path: routePath(this.bot.config.path),
101
+ auth: 'anonymous',
102
+ handler: (request, response) => this.handle(request, response),
103
+ });
104
+ }
105
+ /** Release the route. */
106
+ async stop() {
107
+ this.dispose?.();
108
+ this.dispose = undefined;
109
+ }
110
+ /** Log a fatal start failure before the caller throws it (`Bot.start` only stores a connect failure). */
111
+ fail(message) {
112
+ this.bot.ctx.logger.error(message);
113
+ return new Error(message);
114
+ }
115
+ async handle(request, response) {
116
+ try {
117
+ const base = routePath(this.bot.config.path);
118
+ const url = new URL(request.url ?? '/', 'http://matrix.invalid');
119
+ const inside = base === '/' ||
120
+ url.pathname === base ||
121
+ url.pathname.startsWith(`${base}/`);
122
+ if (!inside) {
123
+ writeUnrecognized(response);
124
+ return;
125
+ }
126
+ if (!this.authorized(request, url.searchParams)) {
127
+ writeStatus(response, 403);
128
+ return;
129
+ }
130
+ const sub = base === '/' ? url.pathname : url.pathname.slice(base.length);
131
+ const txnId = transactionIdOf(sub);
132
+ if (txnId !== undefined) {
133
+ if (request.method !== 'PUT') {
134
+ writeStatus(response, 405, { allow: 'PUT' });
135
+ return;
136
+ }
137
+ await this.transaction(request, response, txnId);
138
+ return;
139
+ }
140
+ if (sub === PING_PATH) {
141
+ if (request.method !== 'POST') {
142
+ writeStatus(response, 405, { allow: 'POST' });
143
+ return;
144
+ }
145
+ writeJson(response, 200, {});
146
+ return;
147
+ }
148
+ if (sub.startsWith(USERS_PREFIX)) {
149
+ if (request.method !== 'GET') {
150
+ writeStatus(response, 405, { allow: 'GET' });
151
+ return;
152
+ }
153
+ this.users(response, sub.slice(USERS_PREFIX.length));
154
+ return;
155
+ }
156
+ if (sub.startsWith(ROOMS_PREFIX)) {
157
+ if (request.method !== 'GET') {
158
+ writeStatus(response, 405, { allow: 'GET' });
159
+ return;
160
+ }
161
+ writeUnrecognized(response);
162
+ return;
163
+ }
164
+ writeUnrecognized(response);
165
+ }
166
+ catch (error) {
167
+ // A route must never leave the listener without an answer.
168
+ this.bot.ctx.logger.warn('matrix: Application Service request failed: %s', messageOf(error));
169
+ writeStatus(response, 500);
170
+ }
171
+ }
172
+ /** Whether one request carries the registration's `hs_token` in exactly one consistent form. */
173
+ authorized(request, query) {
174
+ const bearer = bearerOf(request);
175
+ const legacy = query.get('access_token') ?? undefined;
176
+ if (bearer !== undefined && legacy !== undefined && bearer !== legacy)
177
+ return false;
178
+ const token = bearer ?? legacy;
179
+ if (token === undefined)
180
+ return false;
181
+ return secretMatches(this.bot.config.hsToken, token);
182
+ }
183
+ /** Read and process one transaction; the answer is `200 {}` only after every event reached intake. */
184
+ async transaction(request, response, txnId) {
185
+ const body = await readBody(request);
186
+ let parsed;
187
+ try {
188
+ parsed = JSON.parse(body);
189
+ }
190
+ catch (error) {
191
+ this.bot.ctx.logger.warn('matrix: cannot parse transaction %s: %s', txnId, messageOf(error));
192
+ writeStatus(response, 400);
193
+ return;
194
+ }
195
+ if (typeof parsed !== 'object' || parsed === null) {
196
+ writeStatus(response, 400);
197
+ return;
198
+ }
199
+ const events = parsed.events;
200
+ if (!Array.isArray(events)) {
201
+ writeStatus(response, 400);
202
+ return;
203
+ }
204
+ try {
205
+ for (const raw of events) {
206
+ if (typeof raw !== 'object' || raw === null)
207
+ continue;
208
+ const session = await this.bot.decode(raw);
209
+ if (session !== undefined)
210
+ await this.bot.receive(session);
211
+ }
212
+ }
213
+ catch (error) {
214
+ this.bot.noteRuntimeError(error);
215
+ this.bot.ctx.logger.warn('matrix: transaction %s failed; the homeserver redelivers it: %s', txnId, messageOf(error));
216
+ writeStatus(response, 500);
217
+ return;
218
+ }
219
+ writeJson(response, 200, {});
220
+ }
221
+ /** Answer the `users` query: only the AS virtual user exists. */
222
+ users(response, encoded) {
223
+ let userId = encoded;
224
+ try {
225
+ userId = decodeURIComponent(encoded);
226
+ }
227
+ catch {
228
+ // A malformed escape is simply not a user this service owns.
229
+ }
230
+ if (userId !== this.bot.selfId) {
231
+ writeUnrecognized(response);
232
+ return;
233
+ }
234
+ writeJson(response, 200, {});
235
+ }
236
+ }
237
+ //# sourceMappingURL=as.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"as.js","sourceRoot":"","sources":["../../src/as.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAG7C,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAgBvC,qGAAqG;AACrG,MAAM,oBAAoB,GAAG,CAAC,+BAA+B,EAAE,gBAAgB,CAAC,CAAA;AAEhF,kDAAkD;AAClD,MAAM,SAAS,GAAG,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AAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI;oBAAE,SAAQ;gBACrD,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAkB,CAAC,CAAA;gBACzD,IAAI,OAAO,KAAK,SAAS;oBAAE,MAAM,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;YAC5D,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAA;YAChC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CACtB,iEAAiE,EACjE,KAAK,EACL,SAAS,CAAC,KAAK,CAAC,CACjB,CAAA;YACD,WAAW,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;YAC1B,OAAM;QACR,CAAC;QACD,SAAS,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,CAAC,CAAA;IAC9B,CAAC;IAED,iEAAiE;IACzD,KAAK,CAAC,QAAwB,EAAE,OAAe;QACrD,IAAI,MAAM,GAAG,OAAO,CAAA;QACpB,IAAI,CAAC;YACH,MAAM,GAAG,kBAAkB,CAAC,OAAO,CAAC,CAAA;QACtC,CAAC;QAAC,MAAM,CAAC;YACP,6DAA6D;QAC/D,CAAC;QACD,IAAI,MAAM,KAAK,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC;YAC/B,iBAAiB,CAAC,QAAQ,CAAC,CAAA;YAC3B,OAAM;QACR,CAAC;QACD,SAAS,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,CAAC,CAAA;IAC9B,CAAC;CACF"}
@@ -0,0 +1,109 @@
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
+ import type { Context } from '@deepseek-ai/cordis';
14
+ import { Adapter } from '@deepseek-ai/cordis-plugin-im-core';
15
+ import type { ChatRef, InboundMessage, MembersPage, MessageHandle, MessageRef, Mode, PrepareContext, ResolvedResource, ResourceKind, ResourceRef, SendContext, SentPart, Target } from '@deepseek-ai/cordis-plugin-im-core';
16
+ import { Config } from './config.ts';
17
+ import type { Config as MatrixConfig } from './config.ts';
18
+ import { decodeEvent } from './decode.ts';
19
+ import type { MatrixDecoderHost } from './decode.ts';
20
+ import { MatrixClient } from './request.ts';
21
+ import { RoomCache } from './rooms.ts';
22
+ import type { MatrixModeTypes } from './modes/shared.ts';
23
+ import { Internal } from './types.ts';
24
+ /** The one mode this adapter implements. */
25
+ export interface MatrixModes {
26
+ [mode: string]: Mode<MatrixModeTypes>;
27
+ html: Mode<MatrixModeTypes>;
28
+ }
29
+ /**
30
+ * Matrix Application Service adapter.
31
+ *
32
+ * Identity is the configured virtual user (`@<id>:<host>`), registered or logged in on connect; the inbound route is
33
+ * the Application Service API below `path`; the room cache is filled by the one-shot full-state sync.
34
+ */
35
+ export declare class MatrixBot extends Adapter<MatrixConfig, MatrixModes> implements MatrixDecoderHost {
36
+ /** The adapter needs the Satori service and the isolated `http` service. */
37
+ static inject: string[];
38
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
39
+ static readonly Config: import("@deepseek-ai/schemastery").default<{
40
+ endpoint?: string | null;
41
+ host?: string | null;
42
+ id?: string | null;
43
+ asToken?: string | null;
44
+ hsToken?: string | null;
45
+ path?: string | null;
46
+ name?: string | null;
47
+ avatar?: string | null;
48
+ autoJoin?: boolean | null;
49
+ } & import("@deepseek-ai/cordis-plugin-im-core").Dict, Config, "plain">;
50
+ readonly modes: MatrixModes;
51
+ readonly modeOrder: readonly ["html"];
52
+ /** Homeserver root plus `/_matrix`, without a trailing slash. */
53
+ readonly endpoint: string;
54
+ /** Client-Server transport shared by `Internal` and the adapter's own calls. */
55
+ readonly request: MatrixClient;
56
+ /** The same client under the name the migrated upstream `Internal` uses (`bot.http`). */
57
+ readonly http: MatrixClient;
58
+ /** Full typed Client-Server / Application Service surface (the migrated upstream client). */
59
+ readonly internal: Internal;
60
+ /** Names, members, summaries, direct markers and encryption markers per room. */
61
+ readonly rooms: RoomCache;
62
+ /** Random process base of transaction ids, so a restart cannot collide with an old id. */
63
+ txnBase: number;
64
+ /** Monotonic transaction id counter. */
65
+ txnCounter: number;
66
+ private appService;
67
+ /** Whether an invitation of the bot itself is joined automatically. */
68
+ get autoJoin(): boolean;
69
+ constructor(ctx: Context, config: MatrixConfig);
70
+ connect(): Promise<void>;
71
+ disconnect(): Promise<void>;
72
+ upload(ref: ResourceRef, _scope: string, ctx: PrepareContext): Promise<ResolvedResource>;
73
+ resourceScope(_target: Target, _kind: ResourceKind): string;
74
+ sendPayload(payload: unknown, target: Target, ctx: SendContext): Promise<SentPart>;
75
+ idempotentSend(target: Target, ctx: SendContext): boolean;
76
+ deletePart(part: SentPart, handle: MessageHandle): Promise<void>;
77
+ createReaction(message: MessageRef, emoji: string): Promise<void>;
78
+ members(chat: ChatRef, cursor?: string, limit?: number): Promise<MembersPage>;
79
+ getMessage(chat: ChatRef, id: string): Promise<InboundMessage>;
80
+ classify(error: unknown): import("@deepseek-ai/cordis-plugin-im-core").PlatformError;
81
+ /** Decode one Application Service event into the session the transport publishes. */
82
+ decode(event: Parameters<typeof decodeEvent>[1]): Promise<import("@deepseek-ai/cordis-plugin-im-core").Session | undefined>;
83
+ /** Debug log of one dropped inbound event. */
84
+ log(message: string): void;
85
+ /** Warning log of an unreadable room or a failed state refresh. */
86
+ warn(message: string): void;
87
+ /** Join one room without refreshing; the self-join event triggers the refresh. */
88
+ joinRoom(roomId: string): Promise<void>;
89
+ /**
90
+ * Run the one-shot full-state sync and apply it, joining the rooms the bot was invited into when `autoJoin` is on.
91
+ *
92
+ * The sync's timeline is history the host store already owns, so it is only read for state. A successful join runs
93
+ * the same query once more, which is what puts the new room's name, members and summary in the cache.
94
+ */
95
+ refreshRooms(): Promise<void>;
96
+ /**
97
+ * Take the bot offline when a Client-Server call reports that its token is gone.
98
+ * @param error - the caught failure of an outbound call or an inbound event handler.
99
+ */
100
+ noteRuntimeError(error: unknown): void;
101
+ /** Adapt one authenticated media download into the host's response. */
102
+ private serveMedia;
103
+ /** Run one outbound call, marking the bot offline when the failure is a dead token. */
104
+ private withApi;
105
+ private sendDeps;
106
+ }
107
+ export { Config };
108
+ export default MatrixBot;
109
+ //# sourceMappingURL=bot.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bot.d.ts","sourceRoot":"","sources":["../../src/bot.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,OAAO,EAAE,MAAM,oCAAoC,CAAA;AAC5D,OAAO,KAAK,EACV,OAAO,EACP,cAAc,EACd,WAAW,EACX,aAAa,EACb,UAAU,EACV,IAAI,EACJ,cAAc,EACd,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,WAAW,EACX,QAAQ,EACR,MAAM,EACP,MAAM,oCAAoC,CAAA;AAE3C,OAAO,EAAE,MAAM,EAAe,MAAM,aAAa,CAAA;AACjD,OAAO,KAAK,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,aAAa,CAAA;AACzD,OAAO,EAAE,WAAW,EAAiB,MAAM,aAAa,CAAA;AACxD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAIpD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;A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E,OAAO;IASrB,OAAO,CAAC,QAAQ;CAajB;AAED,OAAO,EAAE,MAAM,EAAE,CAAA;AAEjB,eAAe,SAAS,CAAA"}
@@ -0,0 +1,234 @@
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
+ import { Adapter } from '@deepseek-ai/cordis-plugin-im-core';
14
+ import { MatrixAppService } from "./as.js";
15
+ import { Config, configError } from "./config.js";
16
+ import { decodeEvent, decodeMessage } from "./decode.js";
17
+ import { classifyMatrixError, isTokenFailure } from "./errors.js";
18
+ import { establishIdentity, matrixUserId } from "./identity.js";
19
+ import { mediaResponse, parseMxc, uploadResource } from "./media.js";
20
+ import { MatrixClient } from "./request.js";
21
+ import { enumerateRooms, RoomCache } from "./rooms.js";
22
+ import { createReaction, deletePart, getMessage, idempotentSend, members, sendPayload, } from "./send.js";
23
+ import { createHtmlMode } from "./modes/html.js";
24
+ import { Internal } from "./types.js";
25
+ /** Message of any caught value, for a log line. */
26
+ function messageOf(error) {
27
+ return error instanceof Error ? error.message : String(error);
28
+ }
29
+ /**
30
+ * Matrix Application Service adapter.
31
+ *
32
+ * Identity is the configured virtual user (`@<id>:<host>`), registered or logged in on connect; the inbound route is
33
+ * the Application Service API below `path`; the room cache is filled by the one-shot full-state sync.
34
+ */
35
+ export class MatrixBot extends Adapter {
36
+ /** The adapter needs the Satori service and the isolated `http` service. */
37
+ static inject = ['satori', 'http'];
38
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
39
+ static Config = Config;
40
+ modes = { html: createHtmlMode() };
41
+ modeOrder = ['html'];
42
+ /** Homeserver root plus `/_matrix`, without a trailing slash. */
43
+ endpoint;
44
+ /** Client-Server transport shared by `Internal` and the adapter's own calls. */
45
+ request;
46
+ /** The same client under the name the migrated upstream `Internal` uses (`bot.http`). */
47
+ http;
48
+ /** Full typed Client-Server / Application Service surface (the migrated upstream client). */
49
+ internal;
50
+ /** Names, members, summaries, direct markers and encryption markers per room. */
51
+ rooms = new RoomCache();
52
+ /** Random process base of transaction ids, so a restart cannot collide with an old id. */
53
+ txnBase = Math.round(Math.random() * 1_000);
54
+ /** Monotonic transaction id counter. */
55
+ txnCounter = 0;
56
+ appService;
57
+ /** Whether an invitation of the bot itself is joined automatically. */
58
+ get autoJoin() {
59
+ return this.config.autoJoin;
60
+ }
61
+ constructor(ctx, config) {
62
+ const invalid = configError(config);
63
+ if (invalid !== undefined)
64
+ throw invalid;
65
+ const selfId = matrixUserId(config);
66
+ super(ctx, config, {
67
+ id: `matrix:${selfId}`,
68
+ platform: 'matrix',
69
+ adapter: 'matrix',
70
+ });
71
+ this.selfId = selfId;
72
+ this.user = { id: selfId, name: config.name ?? config.id, isBot: true };
73
+ this.endpoint = `${config.endpoint}/_matrix`;
74
+ this.request = new MatrixClient(ctx, this.endpoint);
75
+ this.http = this.request;
76
+ this.internal = new Internal(this);
77
+ this.defineInternalRoute('/media', (request) => this.serveMedia(request));
78
+ }
79
+ async connect() {
80
+ try {
81
+ await establishIdentity(this);
82
+ await this.refreshRooms();
83
+ const appService = new MatrixAppService(this);
84
+ await appService.start();
85
+ this.appService = appService;
86
+ this.online();
87
+ }
88
+ catch (error) {
89
+ // `Bot.start` only stores a connect failure on `bot.error`; the log line names the failure for the operator.
90
+ this.ctx.logger.error('matrix: connect failed: %s', messageOf(error));
91
+ await this.appService?.stop();
92
+ this.appService = undefined;
93
+ throw error;
94
+ }
95
+ }
96
+ async disconnect() {
97
+ const appService = this.appService;
98
+ this.appService = undefined;
99
+ await appService?.stop();
100
+ }
101
+ async upload(ref, _scope, ctx) {
102
+ return await this.withApi(() => uploadResource(this.request, ref, ctx));
103
+ }
104
+ resourceScope(_target, _kind) {
105
+ // An uploaded media item belongs to the bot user and is valid in every room it sends to.
106
+ return this.id;
107
+ }
108
+ async sendPayload(payload, target, ctx) {
109
+ try {
110
+ return await this.withApi(() => sendPayload(this.sendDeps(), payload, target, ctx));
111
+ }
112
+ catch (error) {
113
+ // The upload already succeeded; a later failure leaves the media in the repository with no event referencing it.
114
+ const value = payload;
115
+ if (value.kind === 'media') {
116
+ this.ctx.logger.warn('matrix: a send attempt for uploaded media %s failed: %s', value.url, messageOf(error));
117
+ }
118
+ throw error;
119
+ }
120
+ }
121
+ idempotentSend(target, ctx) {
122
+ return idempotentSend(target, ctx);
123
+ }
124
+ async deletePart(part, handle) {
125
+ await this.withApi(() => deletePart(this.sendDeps(), part, handle));
126
+ }
127
+ async createReaction(message, emoji) {
128
+ await this.withApi(() => createReaction(this.sendDeps(), message, emoji));
129
+ }
130
+ async members(chat, cursor, limit) {
131
+ return await this.withApi(() => members(this.sendDeps(), chat, cursor, limit));
132
+ }
133
+ async getMessage(chat, id) {
134
+ return await this.withApi(() => getMessage(this.sendDeps(), chat, id));
135
+ }
136
+ classify(error) {
137
+ return classifyMatrixError(error);
138
+ }
139
+ /** Decode one Application Service event into the session the transport publishes. */
140
+ async decode(event) {
141
+ return await decodeEvent(this, event);
142
+ }
143
+ /** Debug log of one dropped inbound event. */
144
+ log(message) {
145
+ this.ctx.logger.debug(message);
146
+ }
147
+ /** Warning log of an unreadable room or a failed state refresh. */
148
+ warn(message) {
149
+ this.ctx.logger.warn(message);
150
+ }
151
+ /** Join one room without refreshing; the self-join event triggers the refresh. */
152
+ async joinRoom(roomId) {
153
+ await this.internal.joinRoom(roomId);
154
+ }
155
+ /**
156
+ * Run the one-shot full-state sync and apply it, joining the rooms the bot was invited into when `autoJoin` is on.
157
+ *
158
+ * The sync's timeline is history the host store already owns, so it is only read for state. A successful join runs
159
+ * the same query once more, which is what puts the new room's name, members and summary in the cache.
160
+ */
161
+ async refreshRooms() {
162
+ const invites = await enumerateRooms(this.internal, this.rooms, this.selfId);
163
+ if (invites.length === 0)
164
+ return;
165
+ if (!this.config.autoJoin) {
166
+ for (const roomId of invites)
167
+ this.ctx.logger.info(`matrix: invited to ${roomId}; autoJoin is off, so it is not joined`);
168
+ return;
169
+ }
170
+ let joined = false;
171
+ for (const roomId of invites) {
172
+ try {
173
+ await this.internal.joinRoom(roomId);
174
+ joined = true;
175
+ }
176
+ catch (error) {
177
+ // The invitation stays in force, so a later connect retries it; one unjoinable room must not fail the rest.
178
+ this.ctx.logger.warn(`matrix: could not join invited room ${roomId}: ${messageOf(error)}`);
179
+ }
180
+ }
181
+ if (joined)
182
+ await enumerateRooms(this.internal, this.rooms, this.selfId);
183
+ }
184
+ /**
185
+ * Take the bot offline when a Client-Server call reports that its token is gone.
186
+ * @param error - the caught failure of an outbound call or an inbound event handler.
187
+ */
188
+ noteRuntimeError(error) {
189
+ if (!isTokenFailure(error))
190
+ return;
191
+ this.ctx.logger.error('matrix: the user access token was rejected (%s); replace the registration credentials and restart', messageOf(error));
192
+ this.offline(error);
193
+ }
194
+ /** Adapt one authenticated media download into the host's response. */
195
+ async serveMedia(request) {
196
+ const value = request.query.get('mxc');
197
+ if (value === null)
198
+ return new Response(null, { status: 400 });
199
+ const parsed = parseMxc(value.startsWith('mxc://') ? value : `mxc://${value}`);
200
+ if (parsed === undefined)
201
+ return new Response(null, { status: 400 });
202
+ try {
203
+ return mediaResponse(await this.request.download(parsed.serverName, parsed.mediaId));
204
+ }
205
+ catch (error) {
206
+ this.noteRuntimeError(error);
207
+ this.ctx.logger.warn('matrix: media %s/%s could not be served: %s', parsed.serverName, parsed.mediaId, messageOf(error));
208
+ return new Response(null, { status: 502 });
209
+ }
210
+ }
211
+ /** Run one outbound call, marking the bot offline when the failure is a dead token. */
212
+ async withApi(run) {
213
+ try {
214
+ return await run();
215
+ }
216
+ catch (error) {
217
+ this.noteRuntimeError(error);
218
+ throw error;
219
+ }
220
+ }
221
+ sendDeps() {
222
+ return {
223
+ client: this.request,
224
+ selfId: this.selfId,
225
+ nextTxn: () => this.txnBase + this.txnCounter++,
226
+ rooms: this.rooms,
227
+ isBot: (userId) => this.ctx.bots.some((bot) => bot.platform === 'matrix' && bot.selfId === userId),
228
+ decode: (chat, event) => decodeMessage(this, event, chat),
229
+ };
230
+ }
231
+ }
232
+ export { Config };
233
+ export default MatrixBot;
234
+ //# sourceMappingURL=bot.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bot.js","sourceRoot":"","sources":["../../src/bot.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,EAAE,OAAO,EAAE,MAAM,oCAAoC,CAAA;AAgB5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAC1C,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAEjD,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAExD,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AACjE,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAC/D,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AACtD,OAAO,EACL,cAAc,EACd,UAAU,EACV,UAAU,EACV,cAAc,EACd,OAAO,EACP,WAAW,GACZ,MAAM,WAAW,CAAA;AAElB,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAEhD,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAQ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