@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.js CHANGED
@@ -1,9 +1,120 @@
1
- import { verify, randomInt, randomBytes, randomUUID, createPublicKey } from 'crypto';
2
1
  import { Security } from '@theokit/sdk';
2
+ import { createInterface } from 'readline';
3
+ import { verify, randomInt, randomBytes, timingSafeEqual, createHmac, createHash, randomUUID, createPublicKey } from 'crypto';
3
4
  import { readFileSync, mkdirSync, writeFileSync, renameSync } from 'fs';
4
5
  import { join } from 'path';
5
6
  import { mkdir, writeFile, chmod, rename, unlink, readFile } from 'fs/promises';
6
7
 
8
+ // src/delivery/attachments.ts
9
+ function attachmentsOf(attachments) {
10
+ return attachments != null && attachments.length !== 0 ? { attachments } : {};
11
+ }
12
+ function refuseUnsupportedAttachments(adapter, outbound) {
13
+ const { attachments } = outbound;
14
+ if (adapter.supportsAttachments || attachments == null || attachments.length === 0) {
15
+ return void 0;
16
+ }
17
+ return {
18
+ ok: false,
19
+ error: {
20
+ code: "attachments_unsupported",
21
+ message: `${adapter.platform} adapter cannot send attachments`
22
+ }
23
+ };
24
+ }
25
+ 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.
26
+ 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.
27
+ 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.
28
+ 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.
29
+ 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.
30
+ 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.
31
+ 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.
32
+ 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.
33
+ 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.
34
+ 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.
35
+ 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.
36
+ 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.
37
+ 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.
38
+ 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.
39
+ 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.
40
+ gateway-mattermost \`accessToken\` :: 26 lowercase alphanumerics, which is exactly a lowercase ULID \u2014 the shape of most trace ids.
41
+ 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.
42
+ 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.
43
+ 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.
44
+ 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.
45
+ 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.
46
+ 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=...\`.
47
+ 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.`;
48
+ function parseUncovered(table) {
49
+ return table.split("\n").map((row) => {
50
+ const [field = "", why = ""] = row.split(" :: ");
51
+ return { field, why };
52
+ });
53
+ }
54
+ var CREDENTIAL_SHAPES = {
55
+ covered: [
56
+ {
57
+ field: "gateway-telegram `token`",
58
+ pattern: /(?<![A-Za-z0-9])\d{8,10}:[A-Za-z0-9_-]{35}(?![A-Za-z0-9_-])/g,
59
+ 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"
60
+ },
61
+ {
62
+ field: "gateway-discord `token`",
63
+ 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,
64
+ alsoMatches: "a three-part dotted identifier of those widths; a JWT's middle part is longer"
65
+ },
66
+ {
67
+ field: "gateway-slack `appToken`",
68
+ pattern: /(?<![A-Za-z0-9-])xapp-\d-[A-Z0-9]+-\d+-[a-f0-9]{32,}(?![a-f0-9])/g,
69
+ alsoMatches: "nothing plausible \u2014 the `xapp-` prefix and the shape are Slack's"
70
+ },
71
+ {
72
+ field: "gateway-matrix `accessToken`",
73
+ pattern: /(?<![A-Za-z0-9_])syt_[A-Za-z0-9_-]+_[A-Za-z0-9_-]+_[A-Za-z0-9]+(?![A-Za-z0-9_-])/g,
74
+ alsoMatches: "nothing plausible \u2014 `syt_` is Matrix's own prefix"
75
+ },
76
+ {
77
+ field: "gateway-whatsapp `accessToken`",
78
+ pattern: /(?<![A-Za-z0-9])EAA[A-Za-z0-9]{20,}(?![A-Za-z0-9])/g,
79
+ alsoMatches: "any identifier beginning EAA followed by 20 or more alphanumerics"
80
+ },
81
+ {
82
+ field: "gateway-teams `clientSecret`",
83
+ 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,
84
+ alsoMatches: "an Entra-style secret is the only common value with a tilde in that position"
85
+ },
86
+ {
87
+ field: "gateway-nostr `secretKey` (nsec1 form)",
88
+ pattern: /(?<![a-z0-9])nsec1[02-9ac-hj-np-z]{58}(?![a-z0-9])/g,
89
+ alsoMatches: "nothing plausible \u2014 `nsec1` is NIP-19's prefix for a secret key"
90
+ }
91
+ ],
92
+ uncovered: parseUncovered(UNCOVERED_TABLE)
93
+ };
94
+ function maskShapes(text) {
95
+ let out = text;
96
+ for (const { pattern } of CREDENTIAL_SHAPES.covered) out = out.replace(pattern, "***");
97
+ return out;
98
+ }
99
+ function redactSecrets(value) {
100
+ return Security.redact(maskShapes(typeof value === "string" ? value : String(value)));
101
+ }
102
+ function maskSecrets(text, secrets) {
103
+ const ordered = [...new Set(secrets)].filter((s) => s.length > 0).sort((a, b) => b.length - a.length);
104
+ let out = text;
105
+ for (const secret of ordered) out = out.split(secret).join("[redacted]");
106
+ return out;
107
+ }
108
+
109
+ // src/diagnostics.ts
110
+ function reportDiagnostic(tag, message, _options = {}) {
111
+ reportDiagnosticLine(`[${tag}] ${message}`);
112
+ }
113
+ function reportDiagnosticLine(line) {
114
+ process.stderr.write(`${redactSecrets(line)}
115
+ `);
116
+ }
117
+
7
118
  // src/text/fence.ts
8
119
  var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
9
120
  var OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;
@@ -237,8 +348,7 @@ var BasePlatformAdapter = class _BasePlatformAdapter {
237
348
  await handler(event);
238
349
  } catch (err) {
239
350
  const message = err instanceof Error ? err.message : String(err);
240
- process.stderr.write(`[${this.platform}] handler threw: ${message}
241
- `);
351
+ reportDiagnostic(this.platform, `handler threw: ${message}`, { });
242
352
  return "handler_threw";
243
353
  }
244
354
  return "ok";
@@ -266,14 +376,20 @@ var BasePlatformAdapter = class _BasePlatformAdapter {
266
376
  if (this.subscribedHandler === void 0) return "no_handler";
267
377
  seen.add(event.id);
268
378
  const outcome = await this.runHandler(this.subscribedHandler, event);
269
- if (outcome === "handler_threw") process.stderr.write(`[${label}] handler threw
270
- `);
379
+ if (outcome === "handler_threw") reportDiagnostic(label, "handler threw", { });
271
380
  return outcome;
272
381
  }
273
382
  /** `out.text`, translated to the platform's markup when `out.format` is `markdown`. */
274
383
  outboundText(out) {
275
384
  return out.format === "markdown" ? channelRendering(this.platform).translate(out.text) : out.text;
276
385
  }
386
+ /**
387
+ * `attachments_unsupported` when `out` carries attachments and this adapter does not declare
388
+ * `supportsAttachments`, otherwise `undefined`. Call it first in `sendMessage`.
389
+ */
390
+ refuseAttachments(out) {
391
+ return refuseUnsupportedAttachments(this, out);
392
+ }
277
393
  /**
278
394
  * The local checks every text-only `sendMessage` makes before a request, in this order:
279
395
  * `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
@@ -377,6 +493,98 @@ var BasePlatformAdapter = class _BasePlatformAdapter {
377
493
  async stopTyping(_channelId) {
378
494
  }
379
495
  };
496
+ function parseMessage(line, onSkip) {
497
+ if (line.trim() === "") return void 0;
498
+ let value;
499
+ try {
500
+ value = JSON.parse(line);
501
+ } catch {
502
+ onSkip(line.slice(0, 120));
503
+ return void 0;
504
+ }
505
+ const isObject = typeof value === "object" && value !== null && !Array.isArray(value);
506
+ return isObject ? value : void 0;
507
+ }
508
+ function outcomeOf(message) {
509
+ const { error } = message;
510
+ if (error === void 0) return { kind: "result", result: message.result };
511
+ return {
512
+ kind: "error",
513
+ code: error.code ?? 0,
514
+ message: error.message ?? "unknown JSON-RPC error",
515
+ ...error.data === void 0 ? {} : { data: error.data }
516
+ };
517
+ }
518
+ var JsonRpcLineClient = class {
519
+ /**
520
+ * @param child - the running child; the client attaches to its pipes and events
521
+ * @param label - the stderr tag, e.g. `gateway-signal`
522
+ * @param onNotification - called for every message that carries a method and no id
523
+ * @param onClosed - called once, when the child exits or fails
524
+ */
525
+ constructor(child, label, onNotification, onClosed) {
526
+ this.child = child;
527
+ this.label = label;
528
+ this.onNotification = onNotification;
529
+ this.onClosed = onClosed;
530
+ const lines = createInterface({ input: child.stdout, crlfDelay: Number.POSITIVE_INFINITY });
531
+ lines.on("line", (line) => this.handleLine(line));
532
+ child.stderr.resume();
533
+ child.stdin.on("error", (err) => this.close(`stdin: ${err.message}`));
534
+ child.on("error", (err) => this.close(err.message));
535
+ child.on("close", (code, signal) => this.close(`exited with ${signal ?? `code ${code}`}`));
536
+ }
537
+ child;
538
+ label;
539
+ onNotification;
540
+ onClosed;
541
+ counter = 0;
542
+ pending = /* @__PURE__ */ new Map();
543
+ alive = true;
544
+ /** Send `method` and wait for its answer, at most `timeoutMs`. */
545
+ request(method, params, timeoutMs) {
546
+ if (!this.alive || !this.child.stdin.writable) return Promise.resolve({ kind: "disconnected" });
547
+ this.counter += 1;
548
+ const id = this.counter;
549
+ const frame = `${JSON.stringify({ jsonrpc: "2.0", method, params, id })}
550
+ `;
551
+ return new Promise((resolve) => {
552
+ const timer = setTimeout(() => this.settle(id, { kind: "timeout" }), timeoutMs);
553
+ this.pending.set(id, { settle: resolve, timer });
554
+ this.child.stdin.write(frame, (err) => {
555
+ if (err) this.close(`stdin: ${err.message}`);
556
+ });
557
+ });
558
+ }
559
+ /** Settle every pending request as `disconnected` and stop accepting new ones. Idempotent. */
560
+ close(reason) {
561
+ if (!this.alive) return;
562
+ this.alive = false;
563
+ for (const id of Array.from(this.pending.keys())) this.settle(id, { kind: "disconnected" });
564
+ this.onClosed(reason);
565
+ }
566
+ settle(id, outcome) {
567
+ const entry = this.pending.get(id);
568
+ if (entry === void 0) return;
569
+ clearTimeout(entry.timer);
570
+ this.pending.delete(id);
571
+ entry.settle(outcome);
572
+ }
573
+ handleLine(line) {
574
+ if (!this.alive) return;
575
+ const message = parseMessage(line, (excerpt) => {
576
+ process.stderr.write(`[${this.label}] skipped a stdout line that is not JSON: ${excerpt}
577
+ `);
578
+ });
579
+ if (message === void 0) return;
580
+ const { id, method } = message;
581
+ if (typeof method === "string" && (id === void 0 || id === null)) {
582
+ this.onNotification({ method, params: message.params });
583
+ } else if (typeof id === "number") {
584
+ this.settle(id, outcomeOf(message));
585
+ }
586
+ }
587
+ };
380
588
 
381
589
  // src/adapter/send-error.ts
382
590
  function parseRetryAfter(value, now) {
@@ -531,8 +739,8 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
531
739
  this.connected = true;
532
740
  return true;
533
741
  } catch (err) {
534
- process.stderr.write(`[${this.cfg.label}] connect failed: ${weixinMessageOf(err)}
535
- `);
742
+ reportDiagnostic(this.cfg.label, `connect failed: ${weixinMessageOf(err)}`, {
743
+ });
536
744
  return false;
537
745
  }
538
746
  }
@@ -956,24 +1164,6 @@ function createChannels(entries) {
956
1164
  return { adapters, channels, rejected };
957
1165
  }
958
1166
 
959
- // src/delivery/attachments.ts
960
- function attachmentsOf(attachments) {
961
- return attachments != null && attachments.length !== 0 ? { attachments } : {};
962
- }
963
- function refuseUnsupportedAttachments(adapter, outbound) {
964
- const { attachments } = outbound;
965
- if (adapter.supportsAttachments || attachments == null || attachments.length === 0) {
966
- return void 0;
967
- }
968
- return {
969
- ok: false,
970
- error: {
971
- code: "attachments_unsupported",
972
- message: `${adapter.platform} adapter cannot send attachments`
973
- }
974
- };
975
- }
976
-
977
1167
  // src/delivery/router.ts
978
1168
  var DeliveryRouter = class {
979
1169
  adapters = /* @__PURE__ */ new Map();
@@ -1009,89 +1199,6 @@ var GatewayLifecycleError = class extends Error {
1009
1199
  this.code = opts.code;
1010
1200
  }
1011
1201
  };
1012
- 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.
1013
- 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.
1014
- 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.
1015
- 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.
1016
- 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.
1017
- 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.
1018
- 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.
1019
- 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.
1020
- 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.
1021
- 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.
1022
- 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.
1023
- 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.
1024
- 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.
1025
- 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.
1026
- 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.
1027
- gateway-mattermost \`accessToken\` :: 26 lowercase alphanumerics, which is exactly a lowercase ULID \u2014 the shape of most trace ids.
1028
- 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.
1029
- 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.
1030
- 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.
1031
- 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.
1032
- 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.
1033
- 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=...\`.
1034
- 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.`;
1035
- function parseUncovered(table) {
1036
- return table.split("\n").map((row) => {
1037
- const [field = "", why = ""] = row.split(" :: ");
1038
- return { field, why };
1039
- });
1040
- }
1041
- var CREDENTIAL_SHAPES = {
1042
- covered: [
1043
- {
1044
- field: "gateway-telegram `token`",
1045
- pattern: /(?<![A-Za-z0-9])\d{8,10}:[A-Za-z0-9_-]{35}(?![A-Za-z0-9_-])/g,
1046
- 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"
1047
- },
1048
- {
1049
- field: "gateway-discord `token`",
1050
- 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,
1051
- alsoMatches: "a three-part dotted identifier of those widths; a JWT's middle part is longer"
1052
- },
1053
- {
1054
- field: "gateway-slack `appToken`",
1055
- pattern: /(?<![A-Za-z0-9-])xapp-\d-[A-Z0-9]+-\d+-[a-f0-9]{32,}(?![a-f0-9])/g,
1056
- alsoMatches: "nothing plausible \u2014 the `xapp-` prefix and the shape are Slack's"
1057
- },
1058
- {
1059
- field: "gateway-matrix `accessToken`",
1060
- pattern: /(?<![A-Za-z0-9_])syt_[A-Za-z0-9_-]+_[A-Za-z0-9_-]+_[A-Za-z0-9]+(?![A-Za-z0-9_-])/g,
1061
- alsoMatches: "nothing plausible \u2014 `syt_` is Matrix's own prefix"
1062
- },
1063
- {
1064
- field: "gateway-whatsapp `accessToken`",
1065
- pattern: /(?<![A-Za-z0-9])EAA[A-Za-z0-9]{20,}(?![A-Za-z0-9])/g,
1066
- alsoMatches: "any identifier beginning EAA followed by 20 or more alphanumerics"
1067
- },
1068
- {
1069
- field: "gateway-teams `clientSecret`",
1070
- 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,
1071
- alsoMatches: "an Entra-style secret is the only common value with a tilde in that position"
1072
- },
1073
- {
1074
- field: "gateway-nostr `secretKey` (nsec1 form)",
1075
- pattern: /(?<![a-z0-9])nsec1[02-9ac-hj-np-z]{58}(?![a-z0-9])/g,
1076
- alsoMatches: "nothing plausible \u2014 `nsec1` is NIP-19's prefix for a secret key"
1077
- }
1078
- ],
1079
- uncovered: parseUncovered(UNCOVERED_TABLE)
1080
- };
1081
- function maskShapes(text) {
1082
- let out = text;
1083
- for (const { pattern } of CREDENTIAL_SHAPES.covered) out = out.replace(pattern, "***");
1084
- return out;
1085
- }
1086
- function redactSecrets(value) {
1087
- return Security.redact(maskShapes(typeof value === "string" ? value : String(value)));
1088
- }
1089
- function maskSecrets(text, secrets) {
1090
- const ordered = [...new Set(secrets)].filter((s) => s.length > 0).sort((a, b) => b.length - a.length);
1091
- let out = text;
1092
- for (const secret of ordered) out = out.split(secret).join("[redacted]");
1093
- return out;
1094
- }
1095
1202
  function senderKey(platform, senderId) {
1096
1203
  return `${platform}:${platform === "email" ? senderId.toLowerCase() : senderId}`;
1097
1204
  }
@@ -1214,8 +1321,7 @@ function createAccessPolicyHook(options) {
1214
1321
  const allowed = check(options.allowed ?? /* @__PURE__ */ new Set(), options.isAuthenticated);
1215
1322
  const clock = options.clock ?? Date.now;
1216
1323
  const interval = options.refusalIntervalMs ?? 36e5;
1217
- const write = options.write ?? ((line) => process.stderr.write(`${line}
1218
- `));
1324
+ const write = options.write ?? reportDiagnosticLine;
1219
1325
  const refusal = options.refusalText ?? DEFAULT_REFUSAL;
1220
1326
  const store = options.pairing;
1221
1327
  const refused2 = /* @__PURE__ */ new Map();
@@ -1395,9 +1501,10 @@ var HookExecutor = class {
1395
1501
  try {
1396
1502
  decision = await h.pre_inbound(ctx);
1397
1503
  } catch (err) {
1398
- process.stderr.write(
1399
- `[gateway] pre_inbound hook "${h.name}" threw: ${redactSecrets(err.message)}
1400
- `
1504
+ reportDiagnostic(
1505
+ "gateway",
1506
+ `pre_inbound hook "${h.name}" threw: ${err.message}`,
1507
+ { }
1401
1508
  );
1402
1509
  return {
1403
1510
  block: true,
@@ -1417,9 +1524,10 @@ var HookExecutor = class {
1417
1524
  try {
1418
1525
  await h.post_outbound(ctx);
1419
1526
  } catch (err) {
1420
- process.stderr.write(
1421
- `[gateway] post_outbound hook "${h.name}" threw: ${err.message}
1422
- `
1527
+ reportDiagnostic(
1528
+ "gateway",
1529
+ `post_outbound hook "${h.name}" threw: ${err.message}`,
1530
+ { }
1423
1531
  );
1424
1532
  }
1425
1533
  }
@@ -1431,10 +1539,8 @@ var HookExecutor = class {
1431
1539
  try {
1432
1540
  await h.on_error(ctx);
1433
1541
  } catch (err) {
1434
- process.stderr.write(
1435
- `[gateway] on_error hook "${h.name}" threw: ${err.message}
1436
- `
1437
- );
1542
+ reportDiagnostic("gateway", `on_error hook "${h.name}" threw: ${err.message}`, {
1543
+ });
1438
1544
  }
1439
1545
  }
1440
1546
  }
@@ -1529,9 +1635,9 @@ async function releaseAdapters(adapters, during, redact = redactSecrets) {
1529
1635
  await a.disconnect();
1530
1636
  } catch (err) {
1531
1637
  const message = err instanceof Error ? err.message : String(err);
1532
- process.stderr.write(
1533
- `[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${redact(message)}
1534
- `
1638
+ reportDiagnostic(
1639
+ "gateway",
1640
+ `adapter "${a.platform}" disconnect failed while ${during}: ${redact(message)}`
1535
1641
  );
1536
1642
  }
1537
1643
  })
@@ -1654,9 +1760,9 @@ var GatewayRunner = class {
1654
1760
  if (policy === void 0 || this.stopped) return;
1655
1761
  const delay = backoff.nextDelayMs();
1656
1762
  if (delay === void 0) {
1657
- process.stderr.write(
1658
- `[gateway] adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts
1659
- `
1763
+ reportDiagnostic(
1764
+ "gateway",
1765
+ `adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts`
1660
1766
  );
1661
1767
  return;
1662
1768
  }
@@ -1666,9 +1772,9 @@ var GatewayRunner = class {
1666
1772
  }, delay);
1667
1773
  timer.unref();
1668
1774
  this.retryTimers.add(timer);
1669
- process.stderr.write(
1670
- `[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms
1671
- `
1775
+ reportDiagnostic(
1776
+ "gateway",
1777
+ `adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms`
1672
1778
  );
1673
1779
  this.emitState(adapter.platform, "retrying", `reconnect attempt ${attempt} in ${delay}ms`);
1674
1780
  }
@@ -1692,30 +1798,27 @@ var GatewayRunner = class {
1692
1798
  connected: [...prev.connected, adapter.platform],
1693
1799
  failed: prev.failed.filter((f) => f.platform !== adapter.platform)
1694
1800
  };
1695
- process.stderr.write(
1696
- `[gateway] adapter "${adapter.platform}" connected on attempt ${attempt}
1697
- `
1801
+ reportDiagnostic(
1802
+ "gateway",
1803
+ `adapter "${adapter.platform}" connected on attempt ${attempt}`
1698
1804
  );
1699
1805
  return;
1700
1806
  }
1701
- process.stderr.write(
1702
- `[gateway] adapter "${adapter.platform}" refused to connect; not retrying
1703
- `
1704
- );
1807
+ reportDiagnostic("gateway", `adapter "${adapter.platform}" refused to connect; not retrying`);
1705
1808
  return;
1706
1809
  } catch (err) {
1707
1810
  const reason = connectFailureReason({ status: "rejected", reason: err }, this.redact);
1708
1811
  if (isTerminalConnectError(err)) {
1709
1812
  this.emitState(adapter.platform, "failed", reason);
1710
- process.stderr.write(
1711
- `[gateway] adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying
1712
- `
1813
+ reportDiagnostic(
1814
+ "gateway",
1815
+ `adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying`
1713
1816
  );
1714
1817
  return;
1715
1818
  }
1716
- process.stderr.write(
1717
- `[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} failed: ${reason}
1718
- `
1819
+ reportDiagnostic(
1820
+ "gateway",
1821
+ `adapter "${adapter.platform}" reconnect attempt ${attempt} failed: ${reason}`
1719
1822
  );
1720
1823
  }
1721
1824
  this.scheduleReconnect(adapter, attempt + 1, backoff);
@@ -1873,8 +1976,7 @@ var GatewayRunner = class {
1873
1976
  await ctx.reply(decision.message).catch(async (err) => {
1874
1977
  const error = err;
1875
1978
  await this.hookExecutor.fireOnError({ event, error });
1876
- process.stderr.write(`[gateway] auto-reply error: ${this.redact(error.message)}
1877
- `);
1979
+ reportDiagnostic("gateway", `auto-reply error: ${this.redact(error.message)}`);
1878
1980
  });
1879
1981
  }
1880
1982
  return;
@@ -1887,8 +1989,7 @@ var GatewayRunner = class {
1887
1989
  await handler(event, ctx);
1888
1990
  } catch (err) {
1889
1991
  await this.hookExecutor.fireOnError({ event, error: err });
1890
- process.stderr.write(`[gateway] handler error: ${this.redact(err.message)}
1891
- `);
1992
+ reportDiagnostic("gateway", `handler error: ${this.redact(err.message)}`);
1892
1993
  } finally {
1893
1994
  await stopTyping();
1894
1995
  }
@@ -1971,8 +2072,7 @@ function errorName(error) {
1971
2072
  }
1972
2073
  function withMediaUnderstanding(handler, options) {
1973
2074
  const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
1974
- const write = options.write ?? ((line) => void process.stderr.write(`${line}
1975
- `));
2075
+ const write = options.write ?? reportDiagnosticLine;
1976
2076
  const understand = async (kind, media, fn) => {
1977
2077
  const type = sanitizeType(media.mediaType);
1978
2078
  if (fn === void 0) return `[Attachment of type ${type} not understood]`;
@@ -2400,8 +2500,19 @@ function rowSafeCut2(text, partStart, cut, partLimit, codepoint) {
2400
2500
  const lineStart = lineStartBefore(text, cut, partStart);
2401
2501
  if (lineStart <= partStart || lineStart === cut) return cut;
2402
2502
  if (isLineEnd2(text[cut]) || !startsTableRow2(text, lineStart)) return cut;
2403
- const bound = advance(text, lineStart, partLimit, codepoint);
2404
- return lineEndFrom(text, cut, bound) <= bound ? lineStart : cut;
2503
+ return rowFits(text, lineStart, cut, partLimit, codepoint) ? lineStart : cut;
2504
+ }
2505
+ function rowFits(text, lineStart, cut, partLimit, codepoint) {
2506
+ const window = lineStart + (codepoint ? 2 * partLimit : partLimit);
2507
+ const end = lineEndFrom(text, cut, window);
2508
+ if (end > window) return false;
2509
+ if (!codepoint) return true;
2510
+ let units = 0;
2511
+ for (let at = lineStart; at < end; units += 1) {
2512
+ if (units >= partLimit) return false;
2513
+ at += (text.codePointAt(at) ?? 0) > 65535 ? 2 : 1;
2514
+ }
2515
+ return true;
2405
2516
  }
2406
2517
  function graphemeCut(segments, start, limitCut) {
2407
2518
  const segment = segments.containing(limitCut);
@@ -2481,9 +2592,9 @@ function rawBodyCapture(tag, options = {}) {
2481
2592
  return (rawReq, rawRes, next) => {
2482
2593
  const req = rawReq;
2483
2594
  if (req.readableEnded === true || req.complete === true) {
2484
- process.stderr.write(
2485
- `[${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
2486
- `
2595
+ reportDiagnostic(
2596
+ tag,
2597
+ "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"
2487
2598
  );
2488
2599
  req.rawBody = "";
2489
2600
  next();
@@ -2529,8 +2640,7 @@ function declaredLength(req) {
2529
2640
  return Number.isFinite(declared) ? declared : 0;
2530
2641
  }
2531
2642
  function answerTooLarge(res, tag, maxBytes) {
2532
- process.stderr.write(`[${tag}] refused a request (413): body larger than ${maxBytes} bytes
2533
- `);
2643
+ reportDiagnostic(tag, `refused a request (413): body larger than ${maxBytes} bytes`);
2534
2644
  res.status(413).json({ error: "request body too large" });
2535
2645
  }
2536
2646
  function listenerLifecycle(opts) {
@@ -2703,7 +2813,49 @@ async function dispatch(webhook, adapter, request) {
2703
2813
  if (webhook.handle !== void 0) return answerResponse(await webhook.handle(adapter, request));
2704
2814
  return runDefault(webhook, adapter, request);
2705
2815
  }
2816
+ function safeEqualString(expected, received) {
2817
+ if (typeof expected !== "string" || typeof received !== "string") return false;
2818
+ if (expected.length === 0 || received.length === 0) return false;
2819
+ const a = Buffer.from(expected, "utf8");
2820
+ const b = Buffer.from(received, "utf8");
2821
+ if (a.length !== b.length) return false;
2822
+ return timingSafeEqual(a, b);
2823
+ }
2824
+ function stripPrefix(signature, prefix) {
2825
+ if (typeof signature !== "string" || signature.length === 0) return null;
2826
+ if (!prefix) return signature;
2827
+ if (!signature.startsWith(prefix)) return null;
2828
+ const rest = signature.slice(prefix.length);
2829
+ return rest.length === 0 ? null : rest;
2830
+ }
2831
+ function normalize2(value, encoding, caseInsensitive) {
2832
+ return encoding === "hex" && caseInsensitive ? value.toLowerCase() : value;
2833
+ }
2834
+ function verifyHmac(opts) {
2835
+ const secrets = typeof opts.secrets === "string" ? [opts.secrets] : [...opts.secrets];
2836
+ if (secrets.length === 0 || secrets.some((s) => typeof s !== "string" || s.length === 0)) {
2837
+ throw new RangeError(
2838
+ "verifyHmac: `secrets` must be a non-empty string or a non-empty list of non-empty strings"
2839
+ );
2840
+ }
2841
+ const received = stripPrefix(opts.signature, opts.prefix);
2842
+ if (received === null) return false;
2843
+ const ci = opts.caseInsensitive === true;
2844
+ const got = normalize2(received, opts.encoding, ci);
2845
+ let ok = false;
2846
+ for (const secret of secrets) {
2847
+ const expected = createHmac(opts.algorithm, secret).update(opts.message).digest(opts.encoding);
2848
+ if (safeEqualString(normalize2(expected, opts.encoding, ci), got)) ok = true;
2849
+ }
2850
+ return ok;
2851
+ }
2852
+ function verifyDigest(opts) {
2853
+ const received = stripPrefix(opts.signature, opts.prefix);
2854
+ if (received === null) return false;
2855
+ const expected = createHash(opts.algorithm).update(opts.message).digest(opts.encoding);
2856
+ return safeEqualString(expected, received);
2857
+ }
2706
2858
 
2707
- export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, ReconnectBackoff, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createTokenCache, createWebhookHandler, decodeJwt, defaultStrategy, helpText, isAuthenticatedSender, jwksKeySet, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, sendErrorFromHttp, senderKey, splitKeepingRows, statusForDeliver, toDialect, verifyRs256Jwt, withMediaUnderstanding };
2859
+ export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, JsonRpcLineClient, ReconnectBackoff, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createTokenCache, createWebhookHandler, decodeJwt, defaultStrategy, helpText, isAuthenticatedSender, jwksKeySet, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, refuseUnsupportedAttachments, reportDiagnostic, safeEqualString, scanFences, scopedStrategy, selectVariant, sendErrorFromHttp, senderKey, splitKeepingRows, statusForDeliver, toDialect, verifyDigest, verifyHmac, verifyRs256Jwt, withMediaUnderstanding };
2708
2860
  //# sourceMappingURL=index.js.map
2709
2861
  //# sourceMappingURL=index.js.map