@theokit/gateway 0.27.0 → 0.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,11 +1,122 @@
1
1
  'use strict';
2
2
 
3
- var crypto = require('crypto');
4
3
  var sdk = require('@theokit/sdk');
4
+ var readline = require('readline');
5
+ var crypto = require('crypto');
5
6
  var fs = require('fs');
6
7
  var path = require('path');
7
8
  var promises = require('fs/promises');
8
9
 
10
+ // src/delivery/attachments.ts
11
+ function attachmentsOf(attachments) {
12
+ return attachments != null && attachments.length !== 0 ? { attachments } : {};
13
+ }
14
+ function refuseUnsupportedAttachments(adapter, outbound) {
15
+ const { attachments } = outbound;
16
+ if (adapter.supportsAttachments || attachments == null || attachments.length === 0) {
17
+ return void 0;
18
+ }
19
+ return {
20
+ ok: false,
21
+ error: {
22
+ code: "attachments_unsupported",
23
+ message: `${adapter.platform} adapter cannot send attachments`
24
+ }
25
+ };
26
+ }
27
+ var UNCOVERED_TABLE = `gateway-qq \`appSecret\` :: a QQ Bot AppSecret, an opaque 32-character string with no prefix or fixed shape. It travels only to the access-token endpoint and into the webhook signature derivation; the adapter never logs it.
28
+ gateway-x \`clientSecret\`, \`refreshToken\`, \`bearerToken\` :: an X OAuth 2.0 client secret, a rotating refresh token and an app bearer token, opaque strings with no fixed prefix. They travel only to the X API in Authorization headers and the token request body, which the adapter never logs.
29
+ gateway-buzz \`token\` :: a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs.
30
+ gateway-clickclack \`token\` :: a ClickClack bot token (\`ccb_\` prefix) or session token with no fixed shape for the latter. It travels only in Authorization headers, which the adapter never logs.
31
+ gateway-zalo \`accessToken\`, \`oaSecretKey\` :: a Zalo Official Account access token and OA secret key: opaque strings with no prefix or fixed shape to recognise. The token travels only in an \`access_token\` header and the key only into the signature check, and the adapter never logs either.
32
+ gateway-wechat \`appSecret\`, \`token\` :: a WeChat Official Account AppSecret (32 hex characters, indistinguishable from any other hex string) and the server-URL verification token (a string the operator chooses). The secret travels only to the access-token endpoint and the token only into the signature check; the adapter never logs either.
33
+ gateway-wecom \`corpSecret\`, \`token\`, \`encodingAesKey\` :: a WeCom application Secret (43 URL-safe base64 characters, indistinguishable from other opaque strings), the callback Token (a string the operator chooses) and the EncodingAESKey (43 base64 characters). The secret travels only to the access-token endpoint, the token into the signature check and the key into the decryption; the adapter never logs any of them.
34
+ gateway-yuanbao \`appSecret\`, \`callbackSecret\` :: a Yuanbao bot AppSecret and the callback signing secret, both opaque strings with no prefix or fixed shape. The app secret travels only to the access-token endpoint and the callback secret only into the signature check; the adapter never logs either.
35
+ gateway-zalo-personal \`credentials\` :: a Zalo web session: a cookie jar, an IMEI-like device id and a user agent. The cookie has no prefix or fixed shape to recognise. It travels only to the Zalo library, which the adapter never logs.
36
+ gateway-twitch \`accessToken\` :: 30 lowercase alphanumerics with no prefix, the shape of many ids and hashes in a log. It travels only in Authorization headers, which the adapter never logs.
37
+ gateway-tlon-urbit \`code\` :: a +code is four dash-joined phonemic syllable words, the same shape as an Urbit ship name such as ~sampel-palnet-sampel-palnet, which the logs exist to show. It travels only in the /~/login body, which the adapter never logs.
38
+ gateway-synology-chat \`botToken\` and \`incomingUrl\` :: a bot token is a random string the NAS generates with no prefix, and the Incoming URL carries its own token as a query parameter of an ordinary entry.cgi URL. Neither has a shape to claim without eating ordinary ids and URLs; the adapter never logs the URL, and refuses a callback token before reading it.
39
+ gateway-feishu-lark \`appSecret\` :: 32 alphanumerics with no prefix, the shape of many tokens and hashes; it travels only in the body of the tenant-token request, which the adapter never logs.
40
+ gateway-nostr \`secretKey\` (64-hex form) :: 64 hex characters is also every Nostr public key and event id, which the logs exist to show, and a sha256 digest. The nsec1 spelling of the same key is masked above.
41
+ gateway-sms \`authToken\` (Twilio), gateway-line \`channelSecret\` :: 32 lowercase hex characters, which is also an md5 digest, a dashless UUID and half a git tree hash. Masking it would eat the correlation id a developer reads the log to find.
42
+ gateway-mattermost \`accessToken\` :: 26 lowercase alphanumerics, which is exactly a lowercase ULID \u2014 the shape of most trace ids.
43
+ gateway-email \`password\`, gateway-sms \`apiSecret\` and \`signatureSecret\` (Vonage) :: no format of their own; a passphrase is indistinguishable from prose. The SDK's own \`key=value\` rule already masks these fully wherever they appear as \`field=value\`, and adding a pattern here made that WORSE by claiming the value first \u2014 it was masked as first6\u2026last4 instead of removed.
44
+ gateway-slack \`botToken\` :: already masked by one of the SDK's own twelve built-in patterns \u2014 \`xoxb-\` is Slack's and the SDK knows it. A pattern here would be a second one doing the first's work, and the field-level gate flagged its absence, which is the gate working.
45
+ gateway-whatsapp \`appSecret\` :: 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.
46
+ gateway-nextcloud-talk \`secret\` :: 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.
47
+ gateway-irc \`password\` and \`saslPassword\` :: 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.
48
+ gateway-google-chat \`privateKey\` :: 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=...\`.
49
+ gateway-line \`channelAccessToken\`, gateway-sms \`authToken\` (Plivo) :: long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message.`;
50
+ function parseUncovered(table) {
51
+ return table.split("\n").map((row) => {
52
+ const [field = "", why = ""] = row.split(" :: ");
53
+ return { field, why };
54
+ });
55
+ }
56
+ var CREDENTIAL_SHAPES = {
57
+ covered: [
58
+ {
59
+ field: "gateway-telegram `token`",
60
+ pattern: /(?<![A-Za-z0-9])\d{8,10}:[A-Za-z0-9_-]{35}(?![A-Za-z0-9_-])/g,
61
+ alsoMatches: "an 8-10 digit number joined by a colon to exactly 35 url-safe characters \u2014 a timestamped identifier of that exact width would be masked"
62
+ },
63
+ {
64
+ field: "gateway-discord `token`",
65
+ pattern: /(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{23,28}\.[A-Za-z0-9_-]{6,7}\.[A-Za-z0-9_-]{27,}(?![A-Za-z0-9_-])/g,
66
+ alsoMatches: "a three-part dotted identifier of those widths; a JWT's middle part is longer"
67
+ },
68
+ {
69
+ field: "gateway-slack `appToken`",
70
+ pattern: /(?<![A-Za-z0-9-])xapp-\d-[A-Z0-9]+-\d+-[a-f0-9]{32,}(?![a-f0-9])/g,
71
+ alsoMatches: "nothing plausible \u2014 the `xapp-` prefix and the shape are Slack's"
72
+ },
73
+ {
74
+ field: "gateway-matrix `accessToken`",
75
+ pattern: /(?<![A-Za-z0-9_])syt_[A-Za-z0-9_-]+_[A-Za-z0-9_-]+_[A-Za-z0-9]+(?![A-Za-z0-9_-])/g,
76
+ alsoMatches: "nothing plausible \u2014 `syt_` is Matrix's own prefix"
77
+ },
78
+ {
79
+ field: "gateway-whatsapp `accessToken`",
80
+ pattern: /(?<![A-Za-z0-9])EAA[A-Za-z0-9]{20,}(?![A-Za-z0-9])/g,
81
+ alsoMatches: "any identifier beginning EAA followed by 20 or more alphanumerics"
82
+ },
83
+ {
84
+ field: "gateway-teams `clientSecret`",
85
+ pattern: /(?<![A-Za-z0-9~])[A-Za-z0-9]{3}\d[A-Za-z0-9]?~[A-Za-z0-9._~-]{30,}(?![A-Za-z0-9._~-])/g,
86
+ alsoMatches: "an Entra-style secret is the only common value with a tilde in that position"
87
+ },
88
+ {
89
+ field: "gateway-nostr `secretKey` (nsec1 form)",
90
+ pattern: /(?<![a-z0-9])nsec1[02-9ac-hj-np-z]{58}(?![a-z0-9])/g,
91
+ alsoMatches: "nothing plausible \u2014 `nsec1` is NIP-19's prefix for a secret key"
92
+ }
93
+ ],
94
+ uncovered: parseUncovered(UNCOVERED_TABLE)
95
+ };
96
+ function maskShapes(text) {
97
+ let out = text;
98
+ for (const { pattern } of CREDENTIAL_SHAPES.covered) out = out.replace(pattern, "***");
99
+ return out;
100
+ }
101
+ function redactSecrets(value) {
102
+ return sdk.Security.redact(maskShapes(typeof value === "string" ? value : String(value)));
103
+ }
104
+ function maskSecrets(text, secrets) {
105
+ const ordered = [...new Set(secrets)].filter((s) => s.length > 0).sort((a, b) => b.length - a.length);
106
+ let out = text;
107
+ for (const secret of ordered) out = out.split(secret).join("[redacted]");
108
+ return out;
109
+ }
110
+
111
+ // src/diagnostics.ts
112
+ function reportDiagnostic(tag, message, _options = {}) {
113
+ reportDiagnosticLine(`[${tag}] ${message}`);
114
+ }
115
+ function reportDiagnosticLine(line) {
116
+ process.stderr.write(`${redactSecrets(line)}
117
+ `);
118
+ }
119
+
9
120
  // src/text/fence.ts
10
121
  var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
11
122
  var OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;
@@ -239,8 +350,7 @@ var BasePlatformAdapter = class _BasePlatformAdapter {
239
350
  await handler(event);
240
351
  } catch (err) {
241
352
  const message = err instanceof Error ? err.message : String(err);
242
- process.stderr.write(`[${this.platform}] handler threw: ${message}
243
- `);
353
+ reportDiagnostic(this.platform, `handler threw: ${message}`, { });
244
354
  return "handler_threw";
245
355
  }
246
356
  return "ok";
@@ -268,14 +378,20 @@ var BasePlatformAdapter = class _BasePlatformAdapter {
268
378
  if (this.subscribedHandler === void 0) return "no_handler";
269
379
  seen.add(event.id);
270
380
  const outcome = await this.runHandler(this.subscribedHandler, event);
271
- if (outcome === "handler_threw") process.stderr.write(`[${label}] handler threw
272
- `);
381
+ if (outcome === "handler_threw") reportDiagnostic(label, "handler threw", { });
273
382
  return outcome;
274
383
  }
275
384
  /** `out.text`, translated to the platform's markup when `out.format` is `markdown`. */
276
385
  outboundText(out) {
277
386
  return out.format === "markdown" ? channelRendering(this.platform).translate(out.text) : out.text;
278
387
  }
388
+ /**
389
+ * `attachments_unsupported` when `out` carries attachments and this adapter does not declare
390
+ * `supportsAttachments`, otherwise `undefined`. Call it first in `sendMessage`.
391
+ */
392
+ refuseAttachments(out) {
393
+ return refuseUnsupportedAttachments(this, out);
394
+ }
279
395
  /**
280
396
  * The local checks every text-only `sendMessage` makes before a request, in this order:
281
397
  * `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
@@ -379,6 +495,98 @@ var BasePlatformAdapter = class _BasePlatformAdapter {
379
495
  async stopTyping(_channelId) {
380
496
  }
381
497
  };
498
+ function parseMessage(line, onSkip) {
499
+ if (line.trim() === "") return void 0;
500
+ let value;
501
+ try {
502
+ value = JSON.parse(line);
503
+ } catch {
504
+ onSkip(line.slice(0, 120));
505
+ return void 0;
506
+ }
507
+ const isObject = typeof value === "object" && value !== null && !Array.isArray(value);
508
+ return isObject ? value : void 0;
509
+ }
510
+ function outcomeOf(message) {
511
+ const { error } = message;
512
+ if (error === void 0) return { kind: "result", result: message.result };
513
+ return {
514
+ kind: "error",
515
+ code: error.code ?? 0,
516
+ message: error.message ?? "unknown JSON-RPC error",
517
+ ...error.data === void 0 ? {} : { data: error.data }
518
+ };
519
+ }
520
+ var JsonRpcLineClient = class {
521
+ /**
522
+ * @param child - the running child; the client attaches to its pipes and events
523
+ * @param label - the stderr tag, e.g. `gateway-signal`
524
+ * @param onNotification - called for every message that carries a method and no id
525
+ * @param onClosed - called once, when the child exits or fails
526
+ */
527
+ constructor(child, label, onNotification, onClosed) {
528
+ this.child = child;
529
+ this.label = label;
530
+ this.onNotification = onNotification;
531
+ this.onClosed = onClosed;
532
+ const lines = readline.createInterface({ input: child.stdout, crlfDelay: Number.POSITIVE_INFINITY });
533
+ lines.on("line", (line) => this.handleLine(line));
534
+ child.stderr.resume();
535
+ child.stdin.on("error", (err) => this.close(`stdin: ${err.message}`));
536
+ child.on("error", (err) => this.close(err.message));
537
+ child.on("close", (code, signal) => this.close(`exited with ${signal ?? `code ${code}`}`));
538
+ }
539
+ child;
540
+ label;
541
+ onNotification;
542
+ onClosed;
543
+ counter = 0;
544
+ pending = /* @__PURE__ */ new Map();
545
+ alive = true;
546
+ /** Send `method` and wait for its answer, at most `timeoutMs`. */
547
+ request(method, params, timeoutMs) {
548
+ if (!this.alive || !this.child.stdin.writable) return Promise.resolve({ kind: "disconnected" });
549
+ this.counter += 1;
550
+ const id = this.counter;
551
+ const frame = `${JSON.stringify({ jsonrpc: "2.0", method, params, id })}
552
+ `;
553
+ return new Promise((resolve) => {
554
+ const timer = setTimeout(() => this.settle(id, { kind: "timeout" }), timeoutMs);
555
+ this.pending.set(id, { settle: resolve, timer });
556
+ this.child.stdin.write(frame, (err) => {
557
+ if (err) this.close(`stdin: ${err.message}`);
558
+ });
559
+ });
560
+ }
561
+ /** Settle every pending request as `disconnected` and stop accepting new ones. Idempotent. */
562
+ close(reason) {
563
+ if (!this.alive) return;
564
+ this.alive = false;
565
+ for (const id of Array.from(this.pending.keys())) this.settle(id, { kind: "disconnected" });
566
+ this.onClosed(reason);
567
+ }
568
+ settle(id, outcome) {
569
+ const entry = this.pending.get(id);
570
+ if (entry === void 0) return;
571
+ clearTimeout(entry.timer);
572
+ this.pending.delete(id);
573
+ entry.settle(outcome);
574
+ }
575
+ handleLine(line) {
576
+ if (!this.alive) return;
577
+ const message = parseMessage(line, (excerpt) => {
578
+ process.stderr.write(`[${this.label}] skipped a stdout line that is not JSON: ${excerpt}
579
+ `);
580
+ });
581
+ if (message === void 0) return;
582
+ const { id, method } = message;
583
+ if (typeof method === "string" && (id === void 0 || id === null)) {
584
+ this.onNotification({ method, params: message.params });
585
+ } else if (typeof id === "number") {
586
+ this.settle(id, outcomeOf(message));
587
+ }
588
+ }
589
+ };
382
590
 
383
591
  // src/adapter/send-error.ts
384
592
  function parseRetryAfter(value, now) {
@@ -533,8 +741,8 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
533
741
  this.connected = true;
534
742
  return true;
535
743
  } catch (err) {
536
- process.stderr.write(`[${this.cfg.label}] connect failed: ${weixinMessageOf(err)}
537
- `);
744
+ reportDiagnostic(this.cfg.label, `connect failed: ${weixinMessageOf(err)}`, {
745
+ });
538
746
  return false;
539
747
  }
540
748
  }
@@ -958,24 +1166,6 @@ function createChannels(entries) {
958
1166
  return { adapters, channels, rejected };
959
1167
  }
960
1168
 
961
- // src/delivery/attachments.ts
962
- function attachmentsOf(attachments) {
963
- return attachments != null && attachments.length !== 0 ? { attachments } : {};
964
- }
965
- function refuseUnsupportedAttachments(adapter, outbound) {
966
- const { attachments } = outbound;
967
- if (adapter.supportsAttachments || attachments == null || attachments.length === 0) {
968
- return void 0;
969
- }
970
- return {
971
- ok: false,
972
- error: {
973
- code: "attachments_unsupported",
974
- message: `${adapter.platform} adapter cannot send attachments`
975
- }
976
- };
977
- }
978
-
979
1169
  // src/delivery/router.ts
980
1170
  var DeliveryRouter = class {
981
1171
  adapters = /* @__PURE__ */ new Map();
@@ -1011,89 +1201,6 @@ var GatewayLifecycleError = class extends Error {
1011
1201
  this.code = opts.code;
1012
1202
  }
1013
1203
  };
1014
- var UNCOVERED_TABLE = `gateway-qq \`appSecret\` :: a QQ Bot AppSecret, an opaque 32-character string with no prefix or fixed shape. It travels only to the access-token endpoint and into the webhook signature derivation; the adapter never logs it.
1015
- gateway-x \`clientSecret\`, \`refreshToken\`, \`bearerToken\` :: an X OAuth 2.0 client secret, a rotating refresh token and an app bearer token, opaque strings with no fixed prefix. They travel only to the X API in Authorization headers and the token request body, which the adapter never logs.
1016
- gateway-buzz \`token\` :: a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs.
1017
- gateway-clickclack \`token\` :: a ClickClack bot token (\`ccb_\` prefix) or session token with no fixed shape for the latter. It travels only in Authorization headers, which the adapter never logs.
1018
- gateway-zalo \`accessToken\`, \`oaSecretKey\` :: a Zalo Official Account access token and OA secret key: opaque strings with no prefix or fixed shape to recognise. The token travels only in an \`access_token\` header and the key only into the signature check, and the adapter never logs either.
1019
- gateway-wechat \`appSecret\`, \`token\` :: a WeChat Official Account AppSecret (32 hex characters, indistinguishable from any other hex string) and the server-URL verification token (a string the operator chooses). The secret travels only to the access-token endpoint and the token only into the signature check; the adapter never logs either.
1020
- gateway-wecom \`corpSecret\`, \`token\`, \`encodingAesKey\` :: a WeCom application Secret (43 URL-safe base64 characters, indistinguishable from other opaque strings), the callback Token (a string the operator chooses) and the EncodingAESKey (43 base64 characters). The secret travels only to the access-token endpoint, the token into the signature check and the key into the decryption; the adapter never logs any of them.
1021
- gateway-yuanbao \`appSecret\`, \`callbackSecret\` :: a Yuanbao bot AppSecret and the callback signing secret, both opaque strings with no prefix or fixed shape. The app secret travels only to the access-token endpoint and the callback secret only into the signature check; the adapter never logs either.
1022
- gateway-zalo-personal \`credentials\` :: a Zalo web session: a cookie jar, an IMEI-like device id and a user agent. The cookie has no prefix or fixed shape to recognise. It travels only to the Zalo library, which the adapter never logs.
1023
- gateway-twitch \`accessToken\` :: 30 lowercase alphanumerics with no prefix, the shape of many ids and hashes in a log. It travels only in Authorization headers, which the adapter never logs.
1024
- gateway-tlon-urbit \`code\` :: a +code is four dash-joined phonemic syllable words, the same shape as an Urbit ship name such as ~sampel-palnet-sampel-palnet, which the logs exist to show. It travels only in the /~/login body, which the adapter never logs.
1025
- gateway-synology-chat \`botToken\` and \`incomingUrl\` :: a bot token is a random string the NAS generates with no prefix, and the Incoming URL carries its own token as a query parameter of an ordinary entry.cgi URL. Neither has a shape to claim without eating ordinary ids and URLs; the adapter never logs the URL, and refuses a callback token before reading it.
1026
- gateway-feishu-lark \`appSecret\` :: 32 alphanumerics with no prefix, the shape of many tokens and hashes; it travels only in the body of the tenant-token request, which the adapter never logs.
1027
- gateway-nostr \`secretKey\` (64-hex form) :: 64 hex characters is also every Nostr public key and event id, which the logs exist to show, and a sha256 digest. The nsec1 spelling of the same key is masked above.
1028
- gateway-sms \`authToken\` (Twilio), gateway-line \`channelSecret\` :: 32 lowercase hex characters, which is also an md5 digest, a dashless UUID and half a git tree hash. Masking it would eat the correlation id a developer reads the log to find.
1029
- gateway-mattermost \`accessToken\` :: 26 lowercase alphanumerics, which is exactly a lowercase ULID \u2014 the shape of most trace ids.
1030
- gateway-email \`password\`, gateway-sms \`apiSecret\` and \`signatureSecret\` (Vonage) :: no format of their own; a passphrase is indistinguishable from prose. The SDK's own \`key=value\` rule already masks these fully wherever they appear as \`field=value\`, and adding a pattern here made that WORSE by claiming the value first \u2014 it was masked as first6\u2026last4 instead of removed.
1031
- gateway-slack \`botToken\` :: already masked by one of the SDK's own twelve built-in patterns \u2014 \`xoxb-\` is Slack's and the SDK knows it. A pattern here would be a second one doing the first's work, and the field-level gate flagged its absence, which is the gate working.
1032
- gateway-whatsapp \`appSecret\` :: 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.
1033
- gateway-nextcloud-talk \`secret\` :: 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.
1034
- gateway-irc \`password\` and \`saslPassword\` :: 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.
1035
- gateway-google-chat \`privateKey\` :: 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=...\`.
1036
- gateway-line \`channelAccessToken\`, gateway-sms \`authToken\` (Plivo) :: long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message.`;
1037
- function parseUncovered(table) {
1038
- return table.split("\n").map((row) => {
1039
- const [field = "", why = ""] = row.split(" :: ");
1040
- return { field, why };
1041
- });
1042
- }
1043
- var CREDENTIAL_SHAPES = {
1044
- covered: [
1045
- {
1046
- field: "gateway-telegram `token`",
1047
- pattern: /(?<![A-Za-z0-9])\d{8,10}:[A-Za-z0-9_-]{35}(?![A-Za-z0-9_-])/g,
1048
- alsoMatches: "an 8-10 digit number joined by a colon to exactly 35 url-safe characters \u2014 a timestamped identifier of that exact width would be masked"
1049
- },
1050
- {
1051
- field: "gateway-discord `token`",
1052
- pattern: /(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{23,28}\.[A-Za-z0-9_-]{6,7}\.[A-Za-z0-9_-]{27,}(?![A-Za-z0-9_-])/g,
1053
- alsoMatches: "a three-part dotted identifier of those widths; a JWT's middle part is longer"
1054
- },
1055
- {
1056
- field: "gateway-slack `appToken`",
1057
- pattern: /(?<![A-Za-z0-9-])xapp-\d-[A-Z0-9]+-\d+-[a-f0-9]{32,}(?![a-f0-9])/g,
1058
- alsoMatches: "nothing plausible \u2014 the `xapp-` prefix and the shape are Slack's"
1059
- },
1060
- {
1061
- field: "gateway-matrix `accessToken`",
1062
- pattern: /(?<![A-Za-z0-9_])syt_[A-Za-z0-9_-]+_[A-Za-z0-9_-]+_[A-Za-z0-9]+(?![A-Za-z0-9_-])/g,
1063
- alsoMatches: "nothing plausible \u2014 `syt_` is Matrix's own prefix"
1064
- },
1065
- {
1066
- field: "gateway-whatsapp `accessToken`",
1067
- pattern: /(?<![A-Za-z0-9])EAA[A-Za-z0-9]{20,}(?![A-Za-z0-9])/g,
1068
- alsoMatches: "any identifier beginning EAA followed by 20 or more alphanumerics"
1069
- },
1070
- {
1071
- field: "gateway-teams `clientSecret`",
1072
- pattern: /(?<![A-Za-z0-9~])[A-Za-z0-9]{3}\d[A-Za-z0-9]?~[A-Za-z0-9._~-]{30,}(?![A-Za-z0-9._~-])/g,
1073
- alsoMatches: "an Entra-style secret is the only common value with a tilde in that position"
1074
- },
1075
- {
1076
- field: "gateway-nostr `secretKey` (nsec1 form)",
1077
- pattern: /(?<![a-z0-9])nsec1[02-9ac-hj-np-z]{58}(?![a-z0-9])/g,
1078
- alsoMatches: "nothing plausible \u2014 `nsec1` is NIP-19's prefix for a secret key"
1079
- }
1080
- ],
1081
- uncovered: parseUncovered(UNCOVERED_TABLE)
1082
- };
1083
- function maskShapes(text) {
1084
- let out = text;
1085
- for (const { pattern } of CREDENTIAL_SHAPES.covered) out = out.replace(pattern, "***");
1086
- return out;
1087
- }
1088
- function redactSecrets(value) {
1089
- return sdk.Security.redact(maskShapes(typeof value === "string" ? value : String(value)));
1090
- }
1091
- function maskSecrets(text, secrets) {
1092
- const ordered = [...new Set(secrets)].filter((s) => s.length > 0).sort((a, b) => b.length - a.length);
1093
- let out = text;
1094
- for (const secret of ordered) out = out.split(secret).join("[redacted]");
1095
- return out;
1096
- }
1097
1204
  function senderKey(platform, senderId) {
1098
1205
  return `${platform}:${platform === "email" ? senderId.toLowerCase() : senderId}`;
1099
1206
  }
@@ -1216,8 +1323,7 @@ function createAccessPolicyHook(options) {
1216
1323
  const allowed = check(options.allowed ?? /* @__PURE__ */ new Set(), options.isAuthenticated);
1217
1324
  const clock = options.clock ?? Date.now;
1218
1325
  const interval = options.refusalIntervalMs ?? 36e5;
1219
- const write = options.write ?? ((line) => process.stderr.write(`${line}
1220
- `));
1326
+ const write = options.write ?? reportDiagnosticLine;
1221
1327
  const refusal = options.refusalText ?? DEFAULT_REFUSAL;
1222
1328
  const store = options.pairing;
1223
1329
  const refused2 = /* @__PURE__ */ new Map();
@@ -1397,9 +1503,10 @@ var HookExecutor = class {
1397
1503
  try {
1398
1504
  decision = await h.pre_inbound(ctx);
1399
1505
  } catch (err) {
1400
- process.stderr.write(
1401
- `[gateway] pre_inbound hook "${h.name}" threw: ${redactSecrets(err.message)}
1402
- `
1506
+ reportDiagnostic(
1507
+ "gateway",
1508
+ `pre_inbound hook "${h.name}" threw: ${err.message}`,
1509
+ { }
1403
1510
  );
1404
1511
  return {
1405
1512
  block: true,
@@ -1419,9 +1526,10 @@ var HookExecutor = class {
1419
1526
  try {
1420
1527
  await h.post_outbound(ctx);
1421
1528
  } catch (err) {
1422
- process.stderr.write(
1423
- `[gateway] post_outbound hook "${h.name}" threw: ${err.message}
1424
- `
1529
+ reportDiagnostic(
1530
+ "gateway",
1531
+ `post_outbound hook "${h.name}" threw: ${err.message}`,
1532
+ { }
1425
1533
  );
1426
1534
  }
1427
1535
  }
@@ -1433,10 +1541,8 @@ var HookExecutor = class {
1433
1541
  try {
1434
1542
  await h.on_error(ctx);
1435
1543
  } catch (err) {
1436
- process.stderr.write(
1437
- `[gateway] on_error hook "${h.name}" threw: ${err.message}
1438
- `
1439
- );
1544
+ reportDiagnostic("gateway", `on_error hook "${h.name}" threw: ${err.message}`, {
1545
+ });
1440
1546
  }
1441
1547
  }
1442
1548
  }
@@ -1531,9 +1637,9 @@ async function releaseAdapters(adapters, during, redact = redactSecrets) {
1531
1637
  await a.disconnect();
1532
1638
  } catch (err) {
1533
1639
  const message = err instanceof Error ? err.message : String(err);
1534
- process.stderr.write(
1535
- `[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${redact(message)}
1536
- `
1640
+ reportDiagnostic(
1641
+ "gateway",
1642
+ `adapter "${a.platform}" disconnect failed while ${during}: ${redact(message)}`
1537
1643
  );
1538
1644
  }
1539
1645
  })
@@ -1656,9 +1762,9 @@ var GatewayRunner = class {
1656
1762
  if (policy === void 0 || this.stopped) return;
1657
1763
  const delay = backoff.nextDelayMs();
1658
1764
  if (delay === void 0) {
1659
- process.stderr.write(
1660
- `[gateway] adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts
1661
- `
1765
+ reportDiagnostic(
1766
+ "gateway",
1767
+ `adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts`
1662
1768
  );
1663
1769
  return;
1664
1770
  }
@@ -1668,9 +1774,9 @@ var GatewayRunner = class {
1668
1774
  }, delay);
1669
1775
  timer.unref();
1670
1776
  this.retryTimers.add(timer);
1671
- process.stderr.write(
1672
- `[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms
1673
- `
1777
+ reportDiagnostic(
1778
+ "gateway",
1779
+ `adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms`
1674
1780
  );
1675
1781
  this.emitState(adapter.platform, "retrying", `reconnect attempt ${attempt} in ${delay}ms`);
1676
1782
  }
@@ -1694,30 +1800,27 @@ var GatewayRunner = class {
1694
1800
  connected: [...prev.connected, adapter.platform],
1695
1801
  failed: prev.failed.filter((f) => f.platform !== adapter.platform)
1696
1802
  };
1697
- process.stderr.write(
1698
- `[gateway] adapter "${adapter.platform}" connected on attempt ${attempt}
1699
- `
1803
+ reportDiagnostic(
1804
+ "gateway",
1805
+ `adapter "${adapter.platform}" connected on attempt ${attempt}`
1700
1806
  );
1701
1807
  return;
1702
1808
  }
1703
- process.stderr.write(
1704
- `[gateway] adapter "${adapter.platform}" refused to connect; not retrying
1705
- `
1706
- );
1809
+ reportDiagnostic("gateway", `adapter "${adapter.platform}" refused to connect; not retrying`);
1707
1810
  return;
1708
1811
  } catch (err) {
1709
1812
  const reason = connectFailureReason({ status: "rejected", reason: err }, this.redact);
1710
1813
  if (isTerminalConnectError(err)) {
1711
1814
  this.emitState(adapter.platform, "failed", reason);
1712
- process.stderr.write(
1713
- `[gateway] adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying
1714
- `
1815
+ reportDiagnostic(
1816
+ "gateway",
1817
+ `adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying`
1715
1818
  );
1716
1819
  return;
1717
1820
  }
1718
- process.stderr.write(
1719
- `[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} failed: ${reason}
1720
- `
1821
+ reportDiagnostic(
1822
+ "gateway",
1823
+ `adapter "${adapter.platform}" reconnect attempt ${attempt} failed: ${reason}`
1721
1824
  );
1722
1825
  }
1723
1826
  this.scheduleReconnect(adapter, attempt + 1, backoff);
@@ -1875,8 +1978,7 @@ var GatewayRunner = class {
1875
1978
  await ctx.reply(decision.message).catch(async (err) => {
1876
1979
  const error = err;
1877
1980
  await this.hookExecutor.fireOnError({ event, error });
1878
- process.stderr.write(`[gateway] auto-reply error: ${this.redact(error.message)}
1879
- `);
1981
+ reportDiagnostic("gateway", `auto-reply error: ${this.redact(error.message)}`);
1880
1982
  });
1881
1983
  }
1882
1984
  return;
@@ -1889,8 +1991,7 @@ var GatewayRunner = class {
1889
1991
  await handler(event, ctx);
1890
1992
  } catch (err) {
1891
1993
  await this.hookExecutor.fireOnError({ event, error: err });
1892
- process.stderr.write(`[gateway] handler error: ${this.redact(err.message)}
1893
- `);
1994
+ reportDiagnostic("gateway", `handler error: ${this.redact(err.message)}`);
1894
1995
  } finally {
1895
1996
  await stopTyping();
1896
1997
  }
@@ -1973,8 +2074,7 @@ function errorName(error) {
1973
2074
  }
1974
2075
  function withMediaUnderstanding(handler, options) {
1975
2076
  const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
1976
- const write = options.write ?? ((line) => void process.stderr.write(`${line}
1977
- `));
2077
+ const write = options.write ?? reportDiagnosticLine;
1978
2078
  const understand = async (kind, media, fn) => {
1979
2079
  const type = sanitizeType(media.mediaType);
1980
2080
  if (fn === void 0) return `[Attachment of type ${type} not understood]`;
@@ -2402,8 +2502,19 @@ function rowSafeCut2(text, partStart, cut, partLimit, codepoint) {
2402
2502
  const lineStart = lineStartBefore(text, cut, partStart);
2403
2503
  if (lineStart <= partStart || lineStart === cut) return cut;
2404
2504
  if (isLineEnd2(text[cut]) || !startsTableRow2(text, lineStart)) return cut;
2405
- const bound = advance(text, lineStart, partLimit, codepoint);
2406
- return lineEndFrom(text, cut, bound) <= bound ? lineStart : cut;
2505
+ return rowFits(text, lineStart, cut, partLimit, codepoint) ? lineStart : cut;
2506
+ }
2507
+ function rowFits(text, lineStart, cut, partLimit, codepoint) {
2508
+ const window = lineStart + (codepoint ? 2 * partLimit : partLimit);
2509
+ const end = lineEndFrom(text, cut, window);
2510
+ if (end > window) return false;
2511
+ if (!codepoint) return true;
2512
+ let units = 0;
2513
+ for (let at = lineStart; at < end; units += 1) {
2514
+ if (units >= partLimit) return false;
2515
+ at += (text.codePointAt(at) ?? 0) > 65535 ? 2 : 1;
2516
+ }
2517
+ return true;
2407
2518
  }
2408
2519
  function graphemeCut(segments, start, limitCut) {
2409
2520
  const segment = segments.containing(limitCut);
@@ -2483,9 +2594,9 @@ function rawBodyCapture(tag, options = {}) {
2483
2594
  return (rawReq, rawRes, next) => {
2484
2595
  const req = rawReq;
2485
2596
  if (req.readableEnded === true || req.complete === true) {
2486
- process.stderr.write(
2487
- `[${tag}] raw body already consumed before signature capture \u2014 mount this router BEFORE any global body parser, or signature verification cannot see the bytes it must hash
2488
- `
2597
+ reportDiagnostic(
2598
+ tag,
2599
+ "raw body already consumed before signature capture \u2014 mount this router BEFORE any global body parser, or signature verification cannot see the bytes it must hash"
2489
2600
  );
2490
2601
  req.rawBody = "";
2491
2602
  next();
@@ -2531,8 +2642,7 @@ function declaredLength(req) {
2531
2642
  return Number.isFinite(declared) ? declared : 0;
2532
2643
  }
2533
2644
  function answerTooLarge(res, tag, maxBytes) {
2534
- process.stderr.write(`[${tag}] refused a request (413): body larger than ${maxBytes} bytes
2535
- `);
2645
+ reportDiagnostic(tag, `refused a request (413): body larger than ${maxBytes} bytes`);
2536
2646
  res.status(413).json({ error: "request body too large" });
2537
2647
  }
2538
2648
  function listenerLifecycle(opts) {
@@ -2705,6 +2815,48 @@ async function dispatch(webhook, adapter, request) {
2705
2815
  if (webhook.handle !== void 0) return answerResponse(await webhook.handle(adapter, request));
2706
2816
  return runDefault(webhook, adapter, request);
2707
2817
  }
2818
+ function safeEqualString(expected, received) {
2819
+ if (typeof expected !== "string" || typeof received !== "string") return false;
2820
+ if (expected.length === 0 || received.length === 0) return false;
2821
+ const a = Buffer.from(expected, "utf8");
2822
+ const b = Buffer.from(received, "utf8");
2823
+ if (a.length !== b.length) return false;
2824
+ return crypto.timingSafeEqual(a, b);
2825
+ }
2826
+ function stripPrefix(signature, prefix) {
2827
+ if (typeof signature !== "string" || signature.length === 0) return null;
2828
+ if (!prefix) return signature;
2829
+ if (!signature.startsWith(prefix)) return null;
2830
+ const rest = signature.slice(prefix.length);
2831
+ return rest.length === 0 ? null : rest;
2832
+ }
2833
+ function normalize2(value, encoding, caseInsensitive) {
2834
+ return encoding === "hex" && caseInsensitive ? value.toLowerCase() : value;
2835
+ }
2836
+ function verifyHmac(opts) {
2837
+ const secrets = typeof opts.secrets === "string" ? [opts.secrets] : [...opts.secrets];
2838
+ if (secrets.length === 0 || secrets.some((s) => typeof s !== "string" || s.length === 0)) {
2839
+ throw new RangeError(
2840
+ "verifyHmac: `secrets` must be a non-empty string or a non-empty list of non-empty strings"
2841
+ );
2842
+ }
2843
+ const received = stripPrefix(opts.signature, opts.prefix);
2844
+ if (received === null) return false;
2845
+ const ci = opts.caseInsensitive === true;
2846
+ const got = normalize2(received, opts.encoding, ci);
2847
+ let ok = false;
2848
+ for (const secret of secrets) {
2849
+ const expected = crypto.createHmac(opts.algorithm, secret).update(opts.message).digest(opts.encoding);
2850
+ if (safeEqualString(normalize2(expected, opts.encoding, ci), got)) ok = true;
2851
+ }
2852
+ return ok;
2853
+ }
2854
+ function verifyDigest(opts) {
2855
+ const received = stripPrefix(opts.signature, opts.prefix);
2856
+ if (received === null) return false;
2857
+ const expected = crypto.createHash(opts.algorithm).update(opts.message).digest(opts.encoding);
2858
+ return safeEqualString(expected, received);
2859
+ }
2708
2860
 
2709
2861
  exports.BasePlatformAdapter = BasePlatformAdapter;
2710
2862
  exports.CREDENTIAL_SHAPES = CREDENTIAL_SHAPES;
@@ -2714,6 +2866,7 @@ exports.GatewayConfigurationError = GatewayConfigurationError;
2714
2866
  exports.GatewayLifecycleError = GatewayLifecycleError;
2715
2867
  exports.GatewayRunner = GatewayRunner;
2716
2868
  exports.HookExecutor = HookExecutor;
2869
+ exports.JsonRpcLineClient = JsonRpcLineClient;
2717
2870
  exports.ReconnectBackoff = ReconnectBackoff;
2718
2871
  exports.SeenIds = SeenIds;
2719
2872
  exports.SessionRouter = SessionRouter;
@@ -2745,6 +2898,9 @@ exports.parseChatCommand = parseChatCommand;
2745
2898
  exports.parseFlatXml = parseFlatXml;
2746
2899
  exports.rawBodyCapture = rawBodyCapture;
2747
2900
  exports.redactSecrets = redactSecrets;
2901
+ exports.refuseUnsupportedAttachments = refuseUnsupportedAttachments;
2902
+ exports.reportDiagnostic = reportDiagnostic;
2903
+ exports.safeEqualString = safeEqualString;
2748
2904
  exports.scanFences = scanFences;
2749
2905
  exports.scopedStrategy = scopedStrategy;
2750
2906
  exports.selectVariant = selectVariant;
@@ -2753,6 +2909,8 @@ exports.senderKey = senderKey;
2753
2909
  exports.splitKeepingRows = splitKeepingRows;
2754
2910
  exports.statusForDeliver = statusForDeliver;
2755
2911
  exports.toDialect = toDialect;
2912
+ exports.verifyDigest = verifyDigest;
2913
+ exports.verifyHmac = verifyHmac;
2756
2914
  exports.verifyRs256Jwt = verifyRs256Jwt;
2757
2915
  exports.withMediaUnderstanding = withMediaUnderstanding;
2758
2916
  //# sourceMappingURL=index.cjs.map