@theokit/gateway 0.11.0 → 0.12.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/CHANGELOG.md +133 -0
- package/README.md +63 -3
- package/dist/index.cjs +231 -42
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +199 -17
- package/dist/index.d.ts +199 -17
- package/dist/index.js +231 -42
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -26,6 +26,35 @@ var BasePlatformAdapter = class {
|
|
|
26
26
|
}
|
|
27
27
|
return "ok";
|
|
28
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Whether {@link editMessage} can replace the text of a message this adapter sent.
|
|
31
|
+
*
|
|
32
|
+
* Read it before starting a preview: on `false`, send the final text instead. An adapter sets
|
|
33
|
+
* it at construction and MUST NOT change it with `connect()`. Annotated as `boolean` so that an
|
|
34
|
+
* edit-capable adapter can override it with `true`.
|
|
35
|
+
*/
|
|
36
|
+
supportsEdit = false;
|
|
37
|
+
/**
|
|
38
|
+
* Replace the text of a message this adapter sent, keeping its id.
|
|
39
|
+
*
|
|
40
|
+
* Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
|
|
41
|
+
* throws on platform errors. An edit-capable adapter applies, with no request, the same local
|
|
42
|
+
* checks its `sendMessage` applies (such as `empty_text`, and `not_connected` where the send
|
|
43
|
+
* checks the connection), plus `invalid_message_id`, and `edit_too_long` where the adapter
|
|
44
|
+
* splits text: an edit that would need more than one platform message is refused, never split.
|
|
45
|
+
*
|
|
46
|
+
* Default: refuses with `edit_unsupported`, makes no platform call, and checks nothing else
|
|
47
|
+
* first, so capability is answered before input.
|
|
48
|
+
*/
|
|
49
|
+
async editMessage(_messageId, _out) {
|
|
50
|
+
return {
|
|
51
|
+
ok: false,
|
|
52
|
+
error: {
|
|
53
|
+
code: "edit_unsupported",
|
|
54
|
+
message: `${this.platform} adapter cannot edit a sent message`
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
29
58
|
/** Lifecycle: emit a typing indicator. Default: noop. */
|
|
30
59
|
async startTyping(_channelId) {
|
|
31
60
|
}
|
|
@@ -57,29 +86,63 @@ function isAbsent(value) {
|
|
|
57
86
|
function missingRequiredKeys(entry, values) {
|
|
58
87
|
return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => field.key);
|
|
59
88
|
}
|
|
89
|
+
function refused(platform, code, reason) {
|
|
90
|
+
return {
|
|
91
|
+
refusal: {
|
|
92
|
+
platform,
|
|
93
|
+
error: new GatewayConfigurationError("gateway", {
|
|
94
|
+
code,
|
|
95
|
+
message: `channel ${platform}: ${reason}`
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function refuseBeforeCreate(entry, values, builtPlatforms) {
|
|
101
|
+
const platform = entry.descriptor.platform;
|
|
102
|
+
if (builtPlatforms.has(platform)) {
|
|
103
|
+
return refused(platform, "duplicate_channel", "a channel for this platform was already built");
|
|
104
|
+
}
|
|
105
|
+
const missing = missingRequiredKeys(entry, values);
|
|
106
|
+
if (missing.length > 0) {
|
|
107
|
+
return refused(
|
|
108
|
+
platform,
|
|
109
|
+
"missing_required_config",
|
|
110
|
+
`missing required config ${missing.join(", ")}`
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
return void 0;
|
|
114
|
+
}
|
|
115
|
+
function createAdapter(entry, values) {
|
|
116
|
+
const platform = entry.descriptor.platform;
|
|
117
|
+
let adapter;
|
|
118
|
+
try {
|
|
119
|
+
adapter = entry.descriptor.create(values);
|
|
120
|
+
} catch (err) {
|
|
121
|
+
if (!(err instanceof GatewayConfigurationError)) throw err;
|
|
122
|
+
return { refusal: { platform, error: err } };
|
|
123
|
+
}
|
|
124
|
+
if (adapter.platform !== platform) {
|
|
125
|
+
return refused(
|
|
126
|
+
platform,
|
|
127
|
+
"platform_mismatch",
|
|
128
|
+
`create returned an adapter reporting platform ${adapter.platform}`
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
return { adapter };
|
|
132
|
+
}
|
|
60
133
|
function createChannels(entries) {
|
|
61
134
|
const adapters = [];
|
|
62
135
|
const rejected = [];
|
|
136
|
+
const builtPlatforms = /* @__PURE__ */ new Set();
|
|
63
137
|
for (const entry of entries) {
|
|
64
138
|
const values = entry.config ?? {};
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
rejected.push({
|
|
69
|
-
platform,
|
|
70
|
-
error: new GatewayConfigurationError("gateway", {
|
|
71
|
-
code: "missing_required_config",
|
|
72
|
-
message: `channel ${platform}: missing required config ${missing.join(", ")}`
|
|
73
|
-
})
|
|
74
|
-
});
|
|
139
|
+
const outcome = refuseBeforeCreate(entry, values, builtPlatforms) ?? createAdapter(entry, values);
|
|
140
|
+
if (outcome.refusal !== void 0) {
|
|
141
|
+
rejected.push(outcome.refusal);
|
|
75
142
|
continue;
|
|
76
143
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
} catch (err) {
|
|
80
|
-
if (!(err instanceof GatewayConfigurationError)) throw err;
|
|
81
|
-
rejected.push({ platform, error: err });
|
|
82
|
-
}
|
|
144
|
+
adapters.push(outcome.adapter);
|
|
145
|
+
builtPlatforms.add(entry.descriptor.platform);
|
|
83
146
|
}
|
|
84
147
|
return { adapters, rejected };
|
|
85
148
|
}
|
|
@@ -171,6 +234,18 @@ var CREDENTIAL_SHAPES = {
|
|
|
171
234
|
field: "gateway-whatsapp `appSecret`",
|
|
172
235
|
why: "32 lowercase hex, the same shape as the Twilio auth token above and as every md5 and dashless UUID. Masking it would eat the correlation ids in a log."
|
|
173
236
|
},
|
|
237
|
+
{
|
|
238
|
+
field: "gateway-nextcloud-talk `secret`",
|
|
239
|
+
why: "a Talk bot secret is a string of 40 to 128 characters the administrator chose for `occ talk:bot:install`, with no prefix or format to recognise. It never travels: both sides send only an HMAC made with it, and the adapter never logs it."
|
|
240
|
+
},
|
|
241
|
+
{
|
|
242
|
+
field: "gateway-irc `password` and `saslPassword`",
|
|
243
|
+
why: "a server password and a NickServ password are passphrases the operator chose, with no format to recognise. The SDK's `key=value` rule masks them as fields wherever they appear as `password=...`; the SASL payload on the wire is their base64, which the adapter never logs."
|
|
244
|
+
},
|
|
245
|
+
{
|
|
246
|
+
field: "gateway-google-chat `privateKey`",
|
|
247
|
+
why: "a PEM block spans lines, and in a log it usually arrives inside a JSON string with its line breaks escaped as \\n, which no single-line shape can claim whole. The SDK's `key=value` rule masks it as a field wherever it appears as `private_key=...` or `privateKey=...`."
|
|
248
|
+
},
|
|
174
249
|
{
|
|
175
250
|
field: "gateway-line `channelAccessToken`, gateway-sms `authToken` (Plivo)",
|
|
176
251
|
why: "long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message."
|
|
@@ -291,6 +366,21 @@ function connectFailureReason(outcome) {
|
|
|
291
366
|
const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
|
|
292
367
|
return redactSecrets(message);
|
|
293
368
|
}
|
|
369
|
+
async function releaseAdapters(adapters, during) {
|
|
370
|
+
await Promise.all(
|
|
371
|
+
adapters.map(async (a) => {
|
|
372
|
+
try {
|
|
373
|
+
await a.disconnect();
|
|
374
|
+
} catch (err) {
|
|
375
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
376
|
+
process.stderr.write(
|
|
377
|
+
`[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${redactSecrets(message)}
|
|
378
|
+
`
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
})
|
|
382
|
+
);
|
|
383
|
+
}
|
|
294
384
|
var GatewayRunner = class {
|
|
295
385
|
constructor(opts) {
|
|
296
386
|
this.opts = opts;
|
|
@@ -305,6 +395,8 @@ var GatewayRunner = class {
|
|
|
305
395
|
/** Slash command registry: name → handler (word-boundary match, EC-A). */
|
|
306
396
|
commands = /* @__PURE__ */ new Map();
|
|
307
397
|
startResult;
|
|
398
|
+
/** The start that has not settled yet, shared by every overlapping `start()` call. */
|
|
399
|
+
startInFlight;
|
|
308
400
|
stopped = false;
|
|
309
401
|
/**
|
|
310
402
|
* Register a slash command. Match rule (EC-A): text === "/" + name
|
|
@@ -321,10 +413,24 @@ var GatewayRunner = class {
|
|
|
321
413
|
* Resolves with what connected. A second call after the first resolved returns the same result
|
|
322
414
|
* without connecting again.
|
|
323
415
|
*
|
|
416
|
+
* Overlapping calls share one start; a start overtaken by stop resolves with no adapter connected.
|
|
417
|
+
* A call made before `stop()` while another is still connecting connects nothing and settles
|
|
418
|
+
* with it; a call made after `stop()` throws `runner_stopped`. When `stop()` runs before the
|
|
419
|
+
* connect settles, the adapters that connected are disconnected, no inbound dispatch is wired,
|
|
420
|
+
* and the start resolves `{ connected: [], failed }`, keeping the `"isolate"` failures. Under
|
|
421
|
+
* `"rollback"`, a connect that fails still rejects the start.
|
|
422
|
+
*
|
|
423
|
+
* Under `connectFailure: "rollback"`, every connect settles before the rollback, so a failing
|
|
424
|
+
* start rejects only once its slowest connect settles, as a successful one resolves only then.
|
|
425
|
+
*
|
|
426
|
+
* An adapter whose `disconnect()` fails while a start rolls back, or while a start that `stop()`
|
|
427
|
+
* overtook gives its adapters back, is named on stderr with the error redacted; how the start
|
|
428
|
+
* settles does not change.
|
|
429
|
+
*
|
|
324
430
|
* @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
|
|
325
431
|
* stopped. A stopped runner is spent; construct a new one.
|
|
326
|
-
* @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after
|
|
327
|
-
* adapters that did connect were disconnected.
|
|
432
|
+
* @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after
|
|
433
|
+
* every connect settled and the adapters that did connect were disconnected.
|
|
328
434
|
*/
|
|
329
435
|
async start() {
|
|
330
436
|
if (this.stopped) {
|
|
@@ -334,7 +440,22 @@ var GatewayRunner = class {
|
|
|
334
440
|
});
|
|
335
441
|
}
|
|
336
442
|
if (this.startResult !== void 0) return this.startResult;
|
|
443
|
+
if (this.startInFlight === void 0) {
|
|
444
|
+
const pending = this.runStart();
|
|
445
|
+
this.startInFlight = pending;
|
|
446
|
+
pending.catch(() => {
|
|
447
|
+
if (this.startInFlight === pending) this.startInFlight = void 0;
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
return this.startInFlight;
|
|
451
|
+
}
|
|
452
|
+
async runStart() {
|
|
337
453
|
const result = (this.opts.connectFailure ?? "rollback") === "isolate" ? await this.connectIsolated() : await this.connectAllOrRollback();
|
|
454
|
+
if (this.stopped) {
|
|
455
|
+
await releaseAdapters(result.connected, "releasing a start that stop() overtook");
|
|
456
|
+
this.startResult = { connected: [], failed: result.failed };
|
|
457
|
+
return this.startResult;
|
|
458
|
+
}
|
|
338
459
|
this.wireInbound(result.connected);
|
|
339
460
|
this.startResult = {
|
|
340
461
|
connected: result.connected.map((a) => a.platform),
|
|
@@ -342,22 +463,36 @@ var GatewayRunner = class {
|
|
|
342
463
|
};
|
|
343
464
|
return this.startResult;
|
|
344
465
|
}
|
|
345
|
-
/**
|
|
466
|
+
/**
|
|
467
|
+
* All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
|
|
468
|
+
* the first failure. Every connect settles before the rollback: rolling back while one is still
|
|
469
|
+
* pending left that adapter live once it connected.
|
|
470
|
+
*/
|
|
346
471
|
async connectAllOrRollback() {
|
|
347
|
-
const
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
})
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
472
|
+
const adapters = this.opts.adapters;
|
|
473
|
+
const failures = [];
|
|
474
|
+
const settled = await Promise.allSettled(
|
|
475
|
+
adapters.map(async (a) => {
|
|
476
|
+
let ok;
|
|
477
|
+
try {
|
|
478
|
+
ok = await a.connect();
|
|
479
|
+
} catch (err) {
|
|
480
|
+
failures.push(err);
|
|
481
|
+
throw err;
|
|
482
|
+
}
|
|
483
|
+
if (!ok) {
|
|
484
|
+
const refusal = new Error(`adapter "${a.platform}" connect returned false`);
|
|
485
|
+
failures.push(refusal);
|
|
486
|
+
throw refusal;
|
|
487
|
+
}
|
|
488
|
+
})
|
|
489
|
+
);
|
|
490
|
+
if (failures.length > 0) {
|
|
491
|
+
const connected = adapters.filter((_, i) => settled[i]?.status === "fulfilled");
|
|
492
|
+
await releaseAdapters(connected, "rolling back a failed start");
|
|
493
|
+
throw failures[0];
|
|
359
494
|
}
|
|
360
|
-
return { connected: [...
|
|
495
|
+
return { connected: [...adapters], failed: [] };
|
|
361
496
|
}
|
|
362
497
|
/**
|
|
363
498
|
* Connect every adapter and keep the ones that connected. The `async` wrapper turns a
|
|
@@ -388,7 +523,12 @@ var GatewayRunner = class {
|
|
|
388
523
|
}
|
|
389
524
|
/**
|
|
390
525
|
* Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
|
|
391
|
-
* then disconnects adapters. Idempotent (EC-E).
|
|
526
|
+
* then disconnects adapters. Idempotent (EC-E). A disconnect that fails does not make `stop()`
|
|
527
|
+
* reject and does not stop the other disconnects; it is written to stderr, redacted, naming the
|
|
528
|
+
* platform.
|
|
529
|
+
*
|
|
530
|
+
* An adapter still connecting under an in-flight start is released when that start settles;
|
|
531
|
+
* `stop()` does not wait for it.
|
|
392
532
|
*/
|
|
393
533
|
async stop() {
|
|
394
534
|
if (this.stopped) return;
|
|
@@ -414,9 +554,7 @@ var GatewayRunner = class {
|
|
|
414
554
|
if (timer !== void 0) clearTimeout(timer);
|
|
415
555
|
}
|
|
416
556
|
}
|
|
417
|
-
await
|
|
418
|
-
[...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => void 0))
|
|
419
|
-
);
|
|
557
|
+
await releaseAdapters([...this.adaptersByPlatform.values()], "stopping the runner");
|
|
420
558
|
}
|
|
421
559
|
/**
|
|
422
560
|
* @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
|
|
@@ -588,11 +726,16 @@ var RENDERINGS = {
|
|
|
588
726
|
discord: { format: "markdown", translate: identity },
|
|
589
727
|
mattermost: { format: "markdown", translate: identity },
|
|
590
728
|
teams: { format: "markdown", translate: identity },
|
|
729
|
+
signal: { format: "markdown", translate: identity },
|
|
591
730
|
line: { format: "plain", translate: translateWith(DIALECTS.line) },
|
|
592
731
|
sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
|
|
593
732
|
telegram: { format: "plain", translate: translateWith(STRIP) },
|
|
594
733
|
matrix: { format: "plain", translate: translateWith(STRIP) },
|
|
595
|
-
email: { format: "plain", translate: translateWith(STRIP) }
|
|
734
|
+
email: { format: "plain", translate: translateWith(STRIP) },
|
|
735
|
+
imessage: { format: "plain", translate: translateWith(STRIP) },
|
|
736
|
+
google_chat: { format: "plain", translate: translateWith(STRIP) },
|
|
737
|
+
irc: { format: "plain", translate: translateWith(STRIP) },
|
|
738
|
+
nextcloud_talk: { format: "markdown", translate: identity }
|
|
596
739
|
};
|
|
597
740
|
function channelRendering(platform) {
|
|
598
741
|
const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
|
|
@@ -689,8 +832,14 @@ async function loadPeer(load, onMissing) {
|
|
|
689
832
|
onMissing();
|
|
690
833
|
}
|
|
691
834
|
}
|
|
692
|
-
function rawBodyCapture(tag) {
|
|
693
|
-
|
|
835
|
+
function rawBodyCapture(tag, options = {}) {
|
|
836
|
+
const { maxBytes } = options;
|
|
837
|
+
if (maxBytes !== void 0 && !(Number.isFinite(maxBytes) && maxBytes >= 0)) {
|
|
838
|
+
throw new RangeError(
|
|
839
|
+
`[${tag}] rawBodyCapture: maxBytes must be a finite number of zero or more, got ${maxBytes}`
|
|
840
|
+
);
|
|
841
|
+
}
|
|
842
|
+
return (rawReq, rawRes, next) => {
|
|
694
843
|
const req = rawReq;
|
|
695
844
|
if (req.readableEnded === true || req.complete === true) {
|
|
696
845
|
process.stderr.write(
|
|
@@ -702,17 +851,48 @@ function rawBodyCapture(tag) {
|
|
|
702
851
|
return;
|
|
703
852
|
}
|
|
704
853
|
let buf = "";
|
|
854
|
+
let bytes = 0;
|
|
855
|
+
let refused2 = maxBytes !== void 0 && declaredLength(req) > maxBytes;
|
|
856
|
+
let settled = false;
|
|
705
857
|
req.setEncoding("utf8");
|
|
706
858
|
req.on("data", (chunk) => {
|
|
859
|
+
if (refused2 || settled) return;
|
|
860
|
+
bytes += Buffer.byteLength(chunk);
|
|
861
|
+
if (maxBytes !== void 0 && bytes > maxBytes) {
|
|
862
|
+
refused2 = true;
|
|
863
|
+
buf = "";
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
707
866
|
buf += chunk;
|
|
708
867
|
});
|
|
709
868
|
req.on("end", () => {
|
|
869
|
+
if (settled) return;
|
|
870
|
+
settled = true;
|
|
871
|
+
if (refused2) {
|
|
872
|
+
answerTooLarge(rawRes, tag, maxBytes ?? 0);
|
|
873
|
+
return;
|
|
874
|
+
}
|
|
710
875
|
req.rawBody = buf;
|
|
711
876
|
next();
|
|
712
877
|
});
|
|
713
|
-
req.on("error", (err) =>
|
|
878
|
+
req.on("error", (err) => {
|
|
879
|
+
if (settled) return;
|
|
880
|
+
settled = true;
|
|
881
|
+
if (refused2) return;
|
|
882
|
+
next(err);
|
|
883
|
+
});
|
|
714
884
|
};
|
|
715
885
|
}
|
|
886
|
+
function declaredLength(req) {
|
|
887
|
+
const value = req.headers?.["content-length"];
|
|
888
|
+
const declared = Number(Array.isArray(value) ? value[0] : value);
|
|
889
|
+
return Number.isFinite(declared) ? declared : 0;
|
|
890
|
+
}
|
|
891
|
+
function answerTooLarge(res, tag, maxBytes) {
|
|
892
|
+
process.stderr.write(`[${tag}] refused a request (413): body larger than ${maxBytes} bytes
|
|
893
|
+
`);
|
|
894
|
+
res.status(413).json({ error: "request body too large" });
|
|
895
|
+
}
|
|
716
896
|
function listenerLifecycle(opts) {
|
|
717
897
|
let started = false;
|
|
718
898
|
let stopped = false;
|
|
@@ -724,8 +904,17 @@ function listenerLifecycle(opts) {
|
|
|
724
904
|
return;
|
|
725
905
|
}
|
|
726
906
|
stopped = false;
|
|
727
|
-
await new Promise((resolve) => {
|
|
728
|
-
|
|
907
|
+
await new Promise((resolve, reject) => {
|
|
908
|
+
const settle = (err) => {
|
|
909
|
+
if (err === void 0) resolve();
|
|
910
|
+
else reject(err);
|
|
911
|
+
};
|
|
912
|
+
const current = opts.app.listen(opts.port, settle);
|
|
913
|
+
listener = current;
|
|
914
|
+
current.once?.("error", settle);
|
|
915
|
+
}).catch((err) => {
|
|
916
|
+
listener = void 0;
|
|
917
|
+
throw err;
|
|
729
918
|
});
|
|
730
919
|
started = true;
|
|
731
920
|
},
|