@theokit/gateway 0.18.0 → 0.20.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 +22 -0
- package/README.md +144 -0
- package/dist/index.cjs +646 -36
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +330 -1
- package/dist/index.d.ts +330 -1
- package/dist/index.js +633 -37
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var sdk = require('@theokit/sdk');
|
|
4
|
+
var crypto = require('crypto');
|
|
5
|
+
var fs = require('fs');
|
|
6
|
+
var path = require('path');
|
|
4
7
|
|
|
5
8
|
// src/text/fence.ts
|
|
6
9
|
var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
|
|
@@ -216,7 +219,7 @@ function channelRendering(platform) {
|
|
|
216
219
|
}
|
|
217
220
|
|
|
218
221
|
// src/adapter/base.ts
|
|
219
|
-
var BasePlatformAdapter = class {
|
|
222
|
+
var BasePlatformAdapter = class _BasePlatformAdapter {
|
|
220
223
|
/**
|
|
221
224
|
* Run a subscribed handler and contain its failure. The body of {@link deliver}, written once.
|
|
222
225
|
*
|
|
@@ -277,17 +280,17 @@ var BasePlatformAdapter = class {
|
|
|
277
280
|
* `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
|
|
278
281
|
* Returns the refusal, or `undefined` when the message may be sent.
|
|
279
282
|
*/
|
|
280
|
-
refuseUnsendable(out,
|
|
283
|
+
refuseUnsendable(out, check2) {
|
|
281
284
|
const refuse = (code, message) => ({
|
|
282
285
|
ok: false,
|
|
283
286
|
error: { code, message }
|
|
284
287
|
});
|
|
285
288
|
if (out.text.length === 0) return refuse("empty_text", "outbound text is empty");
|
|
286
|
-
if (!
|
|
287
|
-
return refuse("not_connected", `${
|
|
289
|
+
if (!check2.connected) {
|
|
290
|
+
return refuse("not_connected", `${check2.className}.connect() has not succeeded`);
|
|
288
291
|
}
|
|
289
|
-
if (
|
|
290
|
-
return refuse("invalid_channel",
|
|
292
|
+
if (check2.channel !== void 0 && !check2.channel.valid(out.channel.id)) {
|
|
293
|
+
return refuse("invalid_channel", check2.channel.message);
|
|
291
294
|
}
|
|
292
295
|
return void 0;
|
|
293
296
|
}
|
|
@@ -307,6 +310,27 @@ var BasePlatformAdapter = class {
|
|
|
307
310
|
* `boolean` so that an adapter that sends images can override it with `true`.
|
|
308
311
|
*/
|
|
309
312
|
supportsAttachments = false;
|
|
313
|
+
/**
|
|
314
|
+
* The attachment kinds {@link sendMessage} can send. `undefined` means "not declared": the
|
|
315
|
+
* `capabilities` getter then reports `["image"]` when `supportsAttachments` is `true`, else `[]`.
|
|
316
|
+
*/
|
|
317
|
+
attachmentKinds = void 0;
|
|
318
|
+
/**
|
|
319
|
+
* What this adapter can do, for an app that renders differently per channel.
|
|
320
|
+
*
|
|
321
|
+
* Derived from the members above and from which lifecycle methods the subclass overrides; an
|
|
322
|
+
* adapter overrides the getter only for what derivation cannot know. Read it at call time.
|
|
323
|
+
*/
|
|
324
|
+
get capabilities() {
|
|
325
|
+
const proto = _BasePlatformAdapter.prototype;
|
|
326
|
+
return {
|
|
327
|
+
edit: this.supportsEdit,
|
|
328
|
+
attachments: this.attachmentKinds ?? (this.supportsAttachments ? ["image"] : []),
|
|
329
|
+
typing: this.startTyping !== proto.startTyping,
|
|
330
|
+
reactions: this.react !== proto.react,
|
|
331
|
+
threads: false
|
|
332
|
+
};
|
|
333
|
+
}
|
|
310
334
|
/**
|
|
311
335
|
* Replace the text of a message this adapter sent, keeping its id.
|
|
312
336
|
*
|
|
@@ -533,6 +557,11 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
|
|
|
533
557
|
}
|
|
534
558
|
};
|
|
535
559
|
|
|
560
|
+
// src/channel/channel-descriptor.ts
|
|
561
|
+
function isAuthenticatedSender(descriptor) {
|
|
562
|
+
return descriptor.senderIdentity === "authenticated";
|
|
563
|
+
}
|
|
564
|
+
|
|
536
565
|
// src/errors/config-error.ts
|
|
537
566
|
var GatewayConfigurationError = class extends Error {
|
|
538
567
|
name = "GatewayConfigurationError";
|
|
@@ -549,6 +578,54 @@ var GatewayConfigurationError = class extends Error {
|
|
|
549
578
|
}
|
|
550
579
|
};
|
|
551
580
|
|
|
581
|
+
// src/channel/config-from-env.ts
|
|
582
|
+
function readValue(env, name) {
|
|
583
|
+
const value = env[name]?.trim();
|
|
584
|
+
return value ? value : void 0;
|
|
585
|
+
}
|
|
586
|
+
function configFromEnv(descriptor, env, prefix = "") {
|
|
587
|
+
const config = {};
|
|
588
|
+
const missing = [];
|
|
589
|
+
const secrets = [];
|
|
590
|
+
for (const field of descriptor.config) {
|
|
591
|
+
if (field.env === void 0) continue;
|
|
592
|
+
const name = prefix + field.env;
|
|
593
|
+
const value = readValue(env, name);
|
|
594
|
+
if (value === void 0) {
|
|
595
|
+
if (field.required) missing.push(name);
|
|
596
|
+
continue;
|
|
597
|
+
}
|
|
598
|
+
config[field.key] = value;
|
|
599
|
+
recordSecret(field, value, secrets);
|
|
600
|
+
}
|
|
601
|
+
return { config, missing, secrets };
|
|
602
|
+
}
|
|
603
|
+
function recordSecret(field, value, secrets) {
|
|
604
|
+
if (field.secret && !secrets.includes(value)) secrets.push(value);
|
|
605
|
+
}
|
|
606
|
+
function mismatch(parent, variant, name) {
|
|
607
|
+
throw new GatewayConfigurationError("gateway", {
|
|
608
|
+
code: "platform_mismatch",
|
|
609
|
+
message: `channel ${parent.platform}: variant "${name}" reports platform ${variant.platform}`
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
function unknownVariant(descriptor, name) {
|
|
613
|
+
const valid = Object.keys(descriptor.variants ?? {});
|
|
614
|
+
const given = name === void 0 ? "(none given)" : `"${name}"`;
|
|
615
|
+
throw new GatewayConfigurationError("gateway", {
|
|
616
|
+
code: "unknown_channel_variant",
|
|
617
|
+
message: `channel ${descriptor.platform}: unknown variant ${given}; valid variants: ${valid.length > 0 ? valid.join(", ") : "(none)"}`
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
function selectVariant(descriptor, name) {
|
|
621
|
+
const variants = descriptor.variants ?? {};
|
|
622
|
+
if (name === void 0 && Object.keys(variants).length === 0) return descriptor;
|
|
623
|
+
const variant = name !== void 0 && Object.hasOwn(variants, name) ? variants[name] : void 0;
|
|
624
|
+
if (variant === void 0) return unknownVariant(descriptor, name);
|
|
625
|
+
if (variant.platform !== descriptor.platform) mismatch(descriptor, variant, name ?? "");
|
|
626
|
+
return variant;
|
|
627
|
+
}
|
|
628
|
+
|
|
552
629
|
// src/channel/create-channels.ts
|
|
553
630
|
function isAbsent(value) {
|
|
554
631
|
return value === void 0 || value === null || value === "";
|
|
@@ -749,6 +826,262 @@ function maskShapes(text) {
|
|
|
749
826
|
function redactSecrets(value) {
|
|
750
827
|
return sdk.Security.redact(maskShapes(typeof value === "string" ? value : String(value)));
|
|
751
828
|
}
|
|
829
|
+
function maskSecrets(text, secrets) {
|
|
830
|
+
const ordered = [...new Set(secrets)].filter((s) => s.length > 0).sort((a, b) => b.length - a.length);
|
|
831
|
+
let out = text;
|
|
832
|
+
for (const secret of ordered) out = out.split(secret).join("[redacted]");
|
|
833
|
+
return out;
|
|
834
|
+
}
|
|
835
|
+
function senderKey(platform, senderId) {
|
|
836
|
+
return `${platform}:${platform === "email" ? senderId.toLowerCase() : senderId}`;
|
|
837
|
+
}
|
|
838
|
+
var TTL_MS = 36e5;
|
|
839
|
+
var FILE = "pairing.json";
|
|
840
|
+
function unreadable() {
|
|
841
|
+
return new GatewayConfigurationError("gateway", {
|
|
842
|
+
code: "pairing_store_unreadable",
|
|
843
|
+
message: "gateway: pairing_store_unreadable"
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
function load(path) {
|
|
847
|
+
let raw;
|
|
848
|
+
try {
|
|
849
|
+
raw = fs.readFileSync(path, "utf8");
|
|
850
|
+
} catch (e) {
|
|
851
|
+
if (e.code === "ENOENT") return /* @__PURE__ */ new Set();
|
|
852
|
+
throw unreadable();
|
|
853
|
+
}
|
|
854
|
+
let parsed;
|
|
855
|
+
try {
|
|
856
|
+
parsed = JSON.parse(raw);
|
|
857
|
+
} catch {
|
|
858
|
+
throw unreadable();
|
|
859
|
+
}
|
|
860
|
+
const list = parsed?.paired;
|
|
861
|
+
if (!Array.isArray(list) || !list.every((x) => typeof x === "string")) throw unreadable();
|
|
862
|
+
return new Set(list);
|
|
863
|
+
}
|
|
864
|
+
function createFilePairingStore(options) {
|
|
865
|
+
const clock = options.clock ?? Date.now;
|
|
866
|
+
const random = options.random ?? crypto.randomInt;
|
|
867
|
+
const path$1 = path.join(options.dir, FILE);
|
|
868
|
+
const paired = load(path$1);
|
|
869
|
+
const pending = /* @__PURE__ */ new Map();
|
|
870
|
+
let chain = Promise.resolve();
|
|
871
|
+
const prune = () => {
|
|
872
|
+
const now = clock();
|
|
873
|
+
for (const [code, p] of pending) if (p.expires <= now) pending.delete(code);
|
|
874
|
+
};
|
|
875
|
+
function persist(next) {
|
|
876
|
+
fs.mkdirSync(options.dir, { recursive: true });
|
|
877
|
+
const tmp = `${path$1}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
878
|
+
fs.writeFileSync(tmp, JSON.stringify({ paired: [...next].sort((a, b) => a.localeCompare(b)) }), {
|
|
879
|
+
mode: 384,
|
|
880
|
+
flag: "wx"
|
|
881
|
+
});
|
|
882
|
+
fs.renameSync(tmp, path$1);
|
|
883
|
+
}
|
|
884
|
+
return {
|
|
885
|
+
issue(platform, senderId) {
|
|
886
|
+
prune();
|
|
887
|
+
for (const [code2, p] of pending) {
|
|
888
|
+
if (senderKey(p.platform, p.senderId) === senderKey(platform, senderId)) return code2;
|
|
889
|
+
}
|
|
890
|
+
let code;
|
|
891
|
+
do {
|
|
892
|
+
code = String(random(1e5, 1e6));
|
|
893
|
+
} while (pending.has(code));
|
|
894
|
+
pending.set(code, { platform, senderId, expires: clock() + TTL_MS });
|
|
895
|
+
return code;
|
|
896
|
+
},
|
|
897
|
+
approve(code) {
|
|
898
|
+
const run = async () => {
|
|
899
|
+
prune();
|
|
900
|
+
const p = pending.get(code);
|
|
901
|
+
if (!p) return { ok: false, reason: "unknown_or_expired" };
|
|
902
|
+
const next = new Set(paired);
|
|
903
|
+
next.add(senderKey(p.platform, p.senderId));
|
|
904
|
+
try {
|
|
905
|
+
persist(next);
|
|
906
|
+
} catch {
|
|
907
|
+
return { ok: false, reason: "write_failed" };
|
|
908
|
+
}
|
|
909
|
+
paired.add(senderKey(p.platform, p.senderId));
|
|
910
|
+
pending.delete(code);
|
|
911
|
+
return { ok: true, platform: p.platform, senderId: p.senderId };
|
|
912
|
+
};
|
|
913
|
+
const result = chain.then(run, run);
|
|
914
|
+
chain = result.catch(() => void 0);
|
|
915
|
+
return result;
|
|
916
|
+
},
|
|
917
|
+
isPaired(platform, senderId) {
|
|
918
|
+
return paired.has(senderKey(platform, senderId));
|
|
919
|
+
}
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
// src/hooks/access-policy.ts
|
|
924
|
+
var SILENT = { block: true };
|
|
925
|
+
var DEFAULT_REFUSAL = "Sorry, you are not authorized to use this assistant.";
|
|
926
|
+
function normalize(key) {
|
|
927
|
+
const i = key.indexOf(":");
|
|
928
|
+
return i < 0 ? key : senderKey(key.slice(0, i), key.slice(i + 1));
|
|
929
|
+
}
|
|
930
|
+
function check(keys, isAuth) {
|
|
931
|
+
const out = /* @__PURE__ */ new Set();
|
|
932
|
+
for (const key of keys) {
|
|
933
|
+
const i = key.indexOf(":");
|
|
934
|
+
const platform = i < 0 ? key : key.slice(0, i);
|
|
935
|
+
if (!isAuth(platform)) {
|
|
936
|
+
throw new GatewayConfigurationError("gateway", {
|
|
937
|
+
code: "unauthenticated_owner",
|
|
938
|
+
message: `gateway: unauthenticated_owner: platform ${platform} does not authenticate the sender`,
|
|
939
|
+
detail: platform
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
out.add(normalize(key));
|
|
943
|
+
}
|
|
944
|
+
return out;
|
|
945
|
+
}
|
|
946
|
+
function createAccessPolicyHook(options) {
|
|
947
|
+
if (options.dm === "pairing" && !options.pairing) {
|
|
948
|
+
throw new GatewayConfigurationError("gateway", {
|
|
949
|
+
code: "pairing_store_required",
|
|
950
|
+
message: "gateway: pairing_store_required"
|
|
951
|
+
});
|
|
952
|
+
}
|
|
953
|
+
const owners = check(options.owners, options.isAuthenticated);
|
|
954
|
+
const allowed = check(options.allowed ?? /* @__PURE__ */ new Set(), options.isAuthenticated);
|
|
955
|
+
const clock = options.clock ?? Date.now;
|
|
956
|
+
const interval = options.refusalIntervalMs ?? 36e5;
|
|
957
|
+
const write = options.write ?? ((line) => process.stderr.write(`${line}
|
|
958
|
+
`));
|
|
959
|
+
const refusal = options.refusalText ?? DEFAULT_REFUSAL;
|
|
960
|
+
const store = options.pairing;
|
|
961
|
+
const refused2 = /* @__PURE__ */ new Map();
|
|
962
|
+
const mayRefuse = (key) => {
|
|
963
|
+
const now = clock();
|
|
964
|
+
for (const [k, t] of refused2) if (now - t >= interval) refused2.delete(k);
|
|
965
|
+
if (refused2.has(key)) return false;
|
|
966
|
+
refused2.set(key, now);
|
|
967
|
+
return true;
|
|
968
|
+
};
|
|
969
|
+
const pairingReply = (event) => {
|
|
970
|
+
const code = store.issue(event.platform, event.sender.id);
|
|
971
|
+
return {
|
|
972
|
+
block: true,
|
|
973
|
+
message: `Your pairing code is ${code}. Ask the owner to send /approve ${code}.`
|
|
974
|
+
};
|
|
975
|
+
};
|
|
976
|
+
const groupDecision = () => options.groups === "open" ? void 0 : SILENT;
|
|
977
|
+
const stranger = (event, key) => {
|
|
978
|
+
if (event.channel.type !== "dm") return groupDecision();
|
|
979
|
+
if (options.dm === "open") return void 0;
|
|
980
|
+
if (options.dm === "disabled" || !mayRefuse(key)) return SILENT;
|
|
981
|
+
if (options.dm === "allowlist") return { block: true, message: refusal };
|
|
982
|
+
return pairingReply(event);
|
|
983
|
+
};
|
|
984
|
+
const ownerMessage = async (text) => {
|
|
985
|
+
const m = /^\/approve\s+(\d{6})\s*$/.exec(text.trim());
|
|
986
|
+
if (!m?.[1]) return void 0;
|
|
987
|
+
if (!store) return { block: true, message: "Pairing is not enabled." };
|
|
988
|
+
const r = await store.approve(m[1]);
|
|
989
|
+
if (r.ok) return { block: true, message: "Paired." };
|
|
990
|
+
return {
|
|
991
|
+
block: true,
|
|
992
|
+
message: r.reason === "write_failed" ? "Saving the pairing failed. Check the storage and send the code again." : "Unknown or expired code."
|
|
993
|
+
};
|
|
994
|
+
};
|
|
995
|
+
const isPaired = (event) => store?.isPaired(event.platform, event.sender.id) === true;
|
|
996
|
+
const decide = async (event) => {
|
|
997
|
+
if (options.passThrough?.(event)) return void 0;
|
|
998
|
+
if (!options.isAuthenticated(event.platform)) return SILENT;
|
|
999
|
+
const key = senderKey(event.platform, event.sender.id);
|
|
1000
|
+
if (owners.has(key)) return ownerMessage(event.text);
|
|
1001
|
+
if (allowed.has(key) || isPaired(event)) return void 0;
|
|
1002
|
+
return stranger(event, key);
|
|
1003
|
+
};
|
|
1004
|
+
return {
|
|
1005
|
+
name: "access-policy",
|
|
1006
|
+
async pre_inbound({ event }) {
|
|
1007
|
+
try {
|
|
1008
|
+
return await decide(event);
|
|
1009
|
+
} catch (e) {
|
|
1010
|
+
try {
|
|
1011
|
+
write(`access-policy: hook failed: ${redactSecrets(e)}`);
|
|
1012
|
+
} catch {
|
|
1013
|
+
}
|
|
1014
|
+
return SILENT;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
// src/hooks/chat-command.ts
|
|
1021
|
+
var LEADING_MENTION = /^(?:<@[^>]+>|@\S+)\s+/;
|
|
1022
|
+
var DEFAULT_PREFIXES = ["/"];
|
|
1023
|
+
function matchPrefix(text, prefixes) {
|
|
1024
|
+
let best;
|
|
1025
|
+
for (const p of prefixes) {
|
|
1026
|
+
if (p.length > 0 && text.startsWith(p) && (best === void 0 || p.length > best.length)) {
|
|
1027
|
+
best = p;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
return best;
|
|
1031
|
+
}
|
|
1032
|
+
function parseChatCommand(text, options) {
|
|
1033
|
+
const body = text.trim().replace(LEADING_MENTION, "");
|
|
1034
|
+
const prefix = matchPrefix(body, options?.prefixes ?? DEFAULT_PREFIXES);
|
|
1035
|
+
if (prefix === void 0) return void 0;
|
|
1036
|
+
const rest = body.slice(prefix.length);
|
|
1037
|
+
const m = /^([^\s@]+)(?:@\S+)?(?:\s+([\s\S]*))?$/.exec(rest);
|
|
1038
|
+
if (!m?.[1]) return void 0;
|
|
1039
|
+
return { name: m[1].toLowerCase(), arg: (m[2] ?? "").trim() };
|
|
1040
|
+
}
|
|
1041
|
+
function usageOf(c) {
|
|
1042
|
+
return c.usage ?? `/${c.name}`;
|
|
1043
|
+
}
|
|
1044
|
+
function helpText(commands) {
|
|
1045
|
+
return commands.map((c) => `${usageOf(c)} - ${c.description}`).join("\n");
|
|
1046
|
+
}
|
|
1047
|
+
function assertUnique(names) {
|
|
1048
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1049
|
+
for (const raw of names) {
|
|
1050
|
+
const name = raw.toLowerCase();
|
|
1051
|
+
if (seen.has(name)) {
|
|
1052
|
+
throw new GatewayConfigurationError("gateway", {
|
|
1053
|
+
code: "duplicate_command",
|
|
1054
|
+
message: `gateway: duplicate_command: ${raw}`,
|
|
1055
|
+
detail: raw
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
seen.add(name);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
function badArity(c, arg) {
|
|
1062
|
+
const mode = c.arg ?? "optional";
|
|
1063
|
+
return mode === "none" && arg !== "" || mode === "required" && arg === "";
|
|
1064
|
+
}
|
|
1065
|
+
function commandHook(commands, options) {
|
|
1066
|
+
const helpName = options?.helpCommand === void 0 ? "help" : options.helpCommand;
|
|
1067
|
+
assertUnique([...commands.map((c) => c.name), ...helpName === false ? [] : [helpName]]);
|
|
1068
|
+
const byName = new Map(commands.map((c) => [c.name.toLowerCase(), c]));
|
|
1069
|
+
const help = helpText(commands);
|
|
1070
|
+
return {
|
|
1071
|
+
name: options?.name ?? "chat-commands",
|
|
1072
|
+
async pre_inbound({ event }) {
|
|
1073
|
+
const parsed = parseChatCommand(event.text);
|
|
1074
|
+
if (!parsed) return void 0;
|
|
1075
|
+
if (helpName !== false && parsed.name === helpName.toLowerCase()) {
|
|
1076
|
+
return { block: true, message: help };
|
|
1077
|
+
}
|
|
1078
|
+
const command = byName.get(parsed.name);
|
|
1079
|
+
if (!command) return void 0;
|
|
1080
|
+
if (badArity(command, parsed.arg)) return { block: true, message: usageOf(command) };
|
|
1081
|
+
return command.run(event, parsed.arg);
|
|
1082
|
+
}
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
752
1085
|
|
|
753
1086
|
// src/hooks/executor.ts
|
|
754
1087
|
var HOOK_PHASES = ["pre_inbound", "post_outbound", "on_error"];
|
|
@@ -862,10 +1195,10 @@ function keepTyping(adapter, channelId) {
|
|
|
862
1195
|
};
|
|
863
1196
|
}
|
|
864
1197
|
var DEFAULT_COMMAND_PREFIXES = ["/"];
|
|
865
|
-
function connectFailureReason(outcome) {
|
|
1198
|
+
function connectFailureReason(outcome, redact) {
|
|
866
1199
|
if (outcome.status === "fulfilled") return "connect returned false";
|
|
867
1200
|
const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
|
|
868
|
-
return
|
|
1201
|
+
return redact(message);
|
|
869
1202
|
}
|
|
870
1203
|
function isTerminalConnectError(err) {
|
|
871
1204
|
if (typeof err !== "object" || err === null) return false;
|
|
@@ -879,7 +1212,7 @@ function isTerminalConnectError(err) {
|
|
|
879
1212
|
message
|
|
880
1213
|
);
|
|
881
1214
|
}
|
|
882
|
-
async function releaseAdapters(adapters, during) {
|
|
1215
|
+
async function releaseAdapters(adapters, during, redact = redactSecrets) {
|
|
883
1216
|
await Promise.all(
|
|
884
1217
|
adapters.map(async (a) => {
|
|
885
1218
|
try {
|
|
@@ -887,7 +1220,7 @@ async function releaseAdapters(adapters, during) {
|
|
|
887
1220
|
} catch (err) {
|
|
888
1221
|
const message = err instanceof Error ? err.message : String(err);
|
|
889
1222
|
process.stderr.write(
|
|
890
|
-
`[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${
|
|
1223
|
+
`[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${redact(message)}
|
|
891
1224
|
`
|
|
892
1225
|
);
|
|
893
1226
|
}
|
|
@@ -898,6 +1231,8 @@ var GatewayRunner = class {
|
|
|
898
1231
|
constructor(opts) {
|
|
899
1232
|
this.opts = opts;
|
|
900
1233
|
this.hookExecutor = new HookExecutor(opts.hooks ?? []);
|
|
1234
|
+
const secrets = opts.secrets ?? [];
|
|
1235
|
+
this.redact = (text) => redactSecrets(maskSecrets(text, secrets));
|
|
901
1236
|
}
|
|
902
1237
|
opts;
|
|
903
1238
|
hookExecutor;
|
|
@@ -910,6 +1245,23 @@ var GatewayRunner = class {
|
|
|
910
1245
|
startInFlight;
|
|
911
1246
|
stopped = false;
|
|
912
1247
|
retryTimers = /* @__PURE__ */ new Set();
|
|
1248
|
+
connectedPlatforms = /* @__PURE__ */ new Set();
|
|
1249
|
+
redact;
|
|
1250
|
+
/** The registered adapter for a platform, connected or not. */
|
|
1251
|
+
adapter(platform) {
|
|
1252
|
+
return this.opts.adapters.find((a) => a.platform === platform);
|
|
1253
|
+
}
|
|
1254
|
+
/** Platforms whose adapter is connected now; updated by connects, retries and `stop()`. */
|
|
1255
|
+
get connected() {
|
|
1256
|
+
return this.connectedPlatforms;
|
|
1257
|
+
}
|
|
1258
|
+
emitState(platform, state, reason) {
|
|
1259
|
+
if ((this.opts.connectFailure ?? "rollback") !== "isolate") return;
|
|
1260
|
+
try {
|
|
1261
|
+
this.opts.onAdapterState?.(platform, state, reason);
|
|
1262
|
+
} catch {
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
913
1265
|
/**
|
|
914
1266
|
* Register a slash command. Match rule (EC-A): text === "/" + name
|
|
915
1267
|
* OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
|
|
@@ -964,11 +1316,17 @@ var GatewayRunner = class {
|
|
|
964
1316
|
async runStart() {
|
|
965
1317
|
const result = (this.opts.connectFailure ?? "rollback") === "isolate" ? await this.connectIsolated() : await this.connectAllOrRollback();
|
|
966
1318
|
if (this.stopped) {
|
|
967
|
-
await releaseAdapters(
|
|
1319
|
+
await releaseAdapters(
|
|
1320
|
+
result.connected,
|
|
1321
|
+
"releasing a start that stop() overtook",
|
|
1322
|
+
this.redact
|
|
1323
|
+
);
|
|
1324
|
+
this.connectedPlatforms.clear();
|
|
968
1325
|
this.startResult = { connected: [], failed: result.failed };
|
|
969
1326
|
return this.startResult;
|
|
970
1327
|
}
|
|
971
1328
|
this.wireInbound(result.connected);
|
|
1329
|
+
for (const a of result.connected) this.connectedPlatforms.add(a.platform);
|
|
972
1330
|
this.startResult = {
|
|
973
1331
|
connected: result.connected.map((a) => a.platform),
|
|
974
1332
|
failed: result.failed
|
|
@@ -1001,16 +1359,23 @@ var GatewayRunner = class {
|
|
|
1001
1359
|
`[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms
|
|
1002
1360
|
`
|
|
1003
1361
|
);
|
|
1362
|
+
this.emitState(adapter.platform, "retrying", `reconnect attempt ${attempt} in ${delay}ms`);
|
|
1004
1363
|
}
|
|
1005
1364
|
async reconnectOnce(adapter, attempt) {
|
|
1006
1365
|
if (this.stopped) return;
|
|
1007
1366
|
try {
|
|
1008
1367
|
if (await adapter.connect()) {
|
|
1009
1368
|
if (this.stopped) {
|
|
1010
|
-
await releaseAdapters(
|
|
1369
|
+
await releaseAdapters(
|
|
1370
|
+
[adapter],
|
|
1371
|
+
"releasing a reconnect that stop() overtook",
|
|
1372
|
+
this.redact
|
|
1373
|
+
);
|
|
1011
1374
|
return;
|
|
1012
1375
|
}
|
|
1013
1376
|
this.wireInbound([adapter]);
|
|
1377
|
+
this.connectedPlatforms.add(adapter.platform);
|
|
1378
|
+
this.emitState(adapter.platform, "connected");
|
|
1014
1379
|
const prev = this.startResult ?? { connected: [], failed: [] };
|
|
1015
1380
|
this.startResult = {
|
|
1016
1381
|
connected: [...prev.connected, adapter.platform],
|
|
@@ -1028,8 +1393,9 @@ var GatewayRunner = class {
|
|
|
1028
1393
|
);
|
|
1029
1394
|
return;
|
|
1030
1395
|
} catch (err) {
|
|
1031
|
-
const reason = connectFailureReason({ status: "rejected", reason: err });
|
|
1396
|
+
const reason = connectFailureReason({ status: "rejected", reason: err }, this.redact);
|
|
1032
1397
|
if (isTerminalConnectError(err)) {
|
|
1398
|
+
this.emitState(adapter.platform, "failed", reason);
|
|
1033
1399
|
process.stderr.write(
|
|
1034
1400
|
`[gateway] adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying
|
|
1035
1401
|
`
|
|
@@ -1069,7 +1435,7 @@ var GatewayRunner = class {
|
|
|
1069
1435
|
);
|
|
1070
1436
|
if (failures.length > 0) {
|
|
1071
1437
|
const connected = adapters.filter((_, i) => settled[i]?.status === "fulfilled");
|
|
1072
|
-
await releaseAdapters(connected, "rolling back a failed start");
|
|
1438
|
+
await releaseAdapters(connected, "rolling back a failed start", this.redact);
|
|
1073
1439
|
throw failures[0];
|
|
1074
1440
|
}
|
|
1075
1441
|
return { connected: [...adapters], failed: [], retryable: [] };
|
|
@@ -1081,22 +1447,55 @@ var GatewayRunner = class {
|
|
|
1081
1447
|
*/
|
|
1082
1448
|
async connectIsolated() {
|
|
1083
1449
|
const adapters = this.opts.adapters;
|
|
1084
|
-
const
|
|
1450
|
+
const results = await Promise.all(adapters.map((a) => this.connectOne(a)));
|
|
1085
1451
|
const connected = [];
|
|
1086
1452
|
const failed = [];
|
|
1087
1453
|
const retryable = [];
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
if (outcome.status === "rejected" && !isTerminalConnectError(outcome.reason)) {
|
|
1094
|
-
retryable.push(adapter);
|
|
1095
|
-
}
|
|
1096
|
-
}
|
|
1097
|
-
});
|
|
1454
|
+
for (const r of results) {
|
|
1455
|
+
if (r.failure === void 0) connected.push(r.adapter);
|
|
1456
|
+
else failed.push(r.failure);
|
|
1457
|
+
if (r.retry) retryable.push(r.adapter);
|
|
1458
|
+
}
|
|
1098
1459
|
return { connected, failed, retryable };
|
|
1099
1460
|
}
|
|
1461
|
+
/** Connect one adapter, bounded by `connectTimeoutMs`, and report its state as it settles. */
|
|
1462
|
+
async connectOne(adapter) {
|
|
1463
|
+
const attempt = Promise.allSettled([(async () => adapter.connect())()]).then(
|
|
1464
|
+
([r]) => r
|
|
1465
|
+
);
|
|
1466
|
+
const ms = this.opts.connectTimeoutMs;
|
|
1467
|
+
if (ms === void 0) return this.classify(adapter, await attempt);
|
|
1468
|
+
let timer;
|
|
1469
|
+
const first = await Promise.race([
|
|
1470
|
+
attempt,
|
|
1471
|
+
new Promise((resolve) => {
|
|
1472
|
+
timer = setTimeout(() => resolve("timeout"), ms);
|
|
1473
|
+
})
|
|
1474
|
+
]);
|
|
1475
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1476
|
+
if (first !== "timeout") return this.classify(adapter, first);
|
|
1477
|
+
void attempt.then((late) => this.releaseLateConnect(adapter, late));
|
|
1478
|
+
const reason = `connect timed out after ${ms}ms`;
|
|
1479
|
+
this.emitState(adapter.platform, "timed_out", reason);
|
|
1480
|
+
return { adapter, failure: { platform: adapter.platform, reason }, retry: true };
|
|
1481
|
+
}
|
|
1482
|
+
/** A connect that finished after the runner gave up on it must not stay connected unseen. */
|
|
1483
|
+
releaseLateConnect(adapter, late) {
|
|
1484
|
+
if (late.status !== "fulfilled" || !late.value) return;
|
|
1485
|
+
if (this.connectedPlatforms.has(adapter.platform)) return;
|
|
1486
|
+
void releaseAdapters([adapter], "releasing a connect that timed out", this.redact);
|
|
1487
|
+
}
|
|
1488
|
+
classify(adapter, outcome) {
|
|
1489
|
+
if (outcome.status === "fulfilled" && outcome.value) {
|
|
1490
|
+
this.connectedPlatforms.add(adapter.platform);
|
|
1491
|
+
this.emitState(adapter.platform, "connected");
|
|
1492
|
+
return { adapter, failure: void 0, retry: false };
|
|
1493
|
+
}
|
|
1494
|
+
const reason = connectFailureReason(outcome, this.redact);
|
|
1495
|
+
this.emitState(adapter.platform, "failed", reason);
|
|
1496
|
+
const retry = outcome.status === "rejected" && !isTerminalConnectError(outcome.reason);
|
|
1497
|
+
return { adapter, failure: { platform: adapter.platform, reason }, retry };
|
|
1498
|
+
}
|
|
1100
1499
|
wireInbound(adapters) {
|
|
1101
1500
|
for (const a of adapters) {
|
|
1102
1501
|
const unsub = a.onInbound(async (event) => {
|
|
@@ -1128,6 +1527,7 @@ var GatewayRunner = class {
|
|
|
1128
1527
|
this.unsubs.length = 0;
|
|
1129
1528
|
for (const t of this.retryTimers) clearTimeout(t);
|
|
1130
1529
|
this.retryTimers.clear();
|
|
1530
|
+
this.connectedPlatforms.clear();
|
|
1131
1531
|
const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
|
|
1132
1532
|
if (this.inflight.size > 0) {
|
|
1133
1533
|
let timer;
|
|
@@ -1142,7 +1542,7 @@ var GatewayRunner = class {
|
|
|
1142
1542
|
if (timer !== void 0) clearTimeout(timer);
|
|
1143
1543
|
}
|
|
1144
1544
|
}
|
|
1145
|
-
await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner");
|
|
1545
|
+
await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner", this.redact);
|
|
1146
1546
|
}
|
|
1147
1547
|
/**
|
|
1148
1548
|
* @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
|
|
@@ -1162,7 +1562,7 @@ var GatewayRunner = class {
|
|
|
1162
1562
|
await ctx.reply(decision.message).catch(async (err) => {
|
|
1163
1563
|
const error = err;
|
|
1164
1564
|
await this.hookExecutor.fireOnError({ event, error });
|
|
1165
|
-
process.stderr.write(`[gateway] auto-reply error: ${
|
|
1565
|
+
process.stderr.write(`[gateway] auto-reply error: ${this.redact(error.message)}
|
|
1166
1566
|
`);
|
|
1167
1567
|
});
|
|
1168
1568
|
}
|
|
@@ -1176,7 +1576,7 @@ var GatewayRunner = class {
|
|
|
1176
1576
|
await handler(event, ctx);
|
|
1177
1577
|
} catch (err) {
|
|
1178
1578
|
await this.hookExecutor.fireOnError({ event, error: err });
|
|
1179
|
-
process.stderr.write(`[gateway] handler error: ${
|
|
1579
|
+
process.stderr.write(`[gateway] handler error: ${this.redact(err.message)}
|
|
1180
1580
|
`);
|
|
1181
1581
|
} finally {
|
|
1182
1582
|
await stopTyping();
|
|
@@ -1328,6 +1728,67 @@ var SessionRouter = class {
|
|
|
1328
1728
|
}
|
|
1329
1729
|
};
|
|
1330
1730
|
|
|
1731
|
+
// src/session/bindings.ts
|
|
1732
|
+
function unknownAgent(agent) {
|
|
1733
|
+
return new GatewayConfigurationError("gateway", {
|
|
1734
|
+
code: "unknown_agent",
|
|
1735
|
+
message: `gateway: unknown_agent: ${agent}`,
|
|
1736
|
+
detail: agent
|
|
1737
|
+
});
|
|
1738
|
+
}
|
|
1739
|
+
function createAgentBindings(options) {
|
|
1740
|
+
const known = new Set(options.agents);
|
|
1741
|
+
if (!known.has(options.defaultAgent)) throw unknownAgent(options.defaultAgent);
|
|
1742
|
+
for (const rule of options.rules) {
|
|
1743
|
+
if (!known.has(rule.agent)) throw unknownAgent(rule.agent);
|
|
1744
|
+
if (rule.platform === void 0 && rule.account === void 0 && rule.peer === void 0) {
|
|
1745
|
+
throw new GatewayConfigurationError("gateway", {
|
|
1746
|
+
code: "empty_binding_rule",
|
|
1747
|
+
message: `gateway: empty_binding_rule: ${rule.agent}`,
|
|
1748
|
+
detail: rule.agent
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
const rules = [...options.rules];
|
|
1753
|
+
const { accountOf } = options;
|
|
1754
|
+
return {
|
|
1755
|
+
agentFor(event) {
|
|
1756
|
+
const ctx = {
|
|
1757
|
+
platform: event.platform,
|
|
1758
|
+
account: accountOf?.(event),
|
|
1759
|
+
peer: event.channel.type === "dm" ? event.sender.id : event.channel.id
|
|
1760
|
+
};
|
|
1761
|
+
let best = options.defaultAgent;
|
|
1762
|
+
let bestScore = 0;
|
|
1763
|
+
for (const rule of rules) {
|
|
1764
|
+
const score = scoreRule(rule, ctx);
|
|
1765
|
+
if (score > bestScore) {
|
|
1766
|
+
best = rule.agent;
|
|
1767
|
+
bestScore = score;
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
return best;
|
|
1771
|
+
}
|
|
1772
|
+
};
|
|
1773
|
+
}
|
|
1774
|
+
function scoreRule(rule, ctx) {
|
|
1775
|
+
const fields = [
|
|
1776
|
+
[rule.platform, ctx.platform, 1],
|
|
1777
|
+
[rule.account, ctx.account, 2],
|
|
1778
|
+
[rule.peer, ctx.peer, 4]
|
|
1779
|
+
];
|
|
1780
|
+
let score = 0;
|
|
1781
|
+
for (const [want, got, weight] of fields) {
|
|
1782
|
+
if (want === void 0) continue;
|
|
1783
|
+
if (want !== got) return 0;
|
|
1784
|
+
score += weight;
|
|
1785
|
+
}
|
|
1786
|
+
return score;
|
|
1787
|
+
}
|
|
1788
|
+
function bindingStrategy(bindings, inner) {
|
|
1789
|
+
return (event) => `${sanitize(bindings.agentFor(event))}-${inner(event)}`;
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1331
1792
|
// src/text/chunk.ts
|
|
1332
1793
|
function searchBoundary(remaining, window, boundaries) {
|
|
1333
1794
|
let cut = window;
|
|
@@ -1485,9 +1946,9 @@ function chunkFencedByGrapheme(text, partLimit, regions) {
|
|
|
1485
1946
|
let prefix = "";
|
|
1486
1947
|
while (prefix.length + (text.length - pos) > partLimit) {
|
|
1487
1948
|
const room = partLimit - prefix.length;
|
|
1488
|
-
const
|
|
1489
|
-
const region = fenceAt(regions,
|
|
1490
|
-
const next = region === void 0 ? { cut:
|
|
1949
|
+
const plain2 = boundaryUpTo(pos, pos + room);
|
|
1950
|
+
const region = fenceAt(regions, plain2);
|
|
1951
|
+
const next = region === void 0 ? { cut: plain2, suffix: "", reopen: "" } : fenceGraphemeCut(text, region, pos, plain2, room, boundaryUpTo);
|
|
1491
1952
|
parts.push(prefix + text.slice(pos, next.cut) + next.suffix);
|
|
1492
1953
|
pos = next.cut;
|
|
1493
1954
|
prefix = next.reopen;
|
|
@@ -1495,9 +1956,9 @@ function chunkFencedByGrapheme(text, partLimit, regions) {
|
|
|
1495
1956
|
parts.push(prefix + text.slice(pos));
|
|
1496
1957
|
return parts;
|
|
1497
1958
|
}
|
|
1498
|
-
function fenceGraphemeCut(text, region, pos,
|
|
1499
|
-
const none = { cut:
|
|
1500
|
-
if (
|
|
1959
|
+
function fenceGraphemeCut(text, region, pos, plain2, room, boundaryUpTo) {
|
|
1960
|
+
const none = { cut: plain2, suffix: "", reopen: "" };
|
|
1961
|
+
if (plain2 <= region.openerEnd) {
|
|
1501
1962
|
return region.start > pos ? { ...none, cut: region.start } : none;
|
|
1502
1963
|
}
|
|
1503
1964
|
const eol = openerEol(text, region);
|
|
@@ -1562,10 +2023,25 @@ function splitKeepingRows(text, partLimit) {
|
|
|
1562
2023
|
return parts;
|
|
1563
2024
|
}
|
|
1564
2025
|
|
|
2026
|
+
// src/webhook/deliver-status.ts
|
|
2027
|
+
function statusForDeliver(outcomes) {
|
|
2028
|
+
let status = 200;
|
|
2029
|
+
for (const outcome of outcomes) {
|
|
2030
|
+
if (outcome === "handler_threw") {
|
|
2031
|
+
status = 500;
|
|
2032
|
+
} else if (outcome === "no_handler") {
|
|
2033
|
+
if (status === 200) status = 503;
|
|
2034
|
+
} else if (outcome !== "ok") {
|
|
2035
|
+
throw new Error(`unknown deliver outcome: ${outcome}`);
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
return status;
|
|
2039
|
+
}
|
|
2040
|
+
|
|
1565
2041
|
// src/webhook/express-server.ts
|
|
1566
|
-
async function loadPeer(
|
|
2042
|
+
async function loadPeer(load2, onMissing) {
|
|
1567
2043
|
try {
|
|
1568
|
-
const mod = await
|
|
2044
|
+
const mod = await load2();
|
|
1569
2045
|
return mod.default ?? mod;
|
|
1570
2046
|
} catch {
|
|
1571
2047
|
onMissing();
|
|
@@ -1672,6 +2148,126 @@ function listenerLifecycle(opts) {
|
|
|
1672
2148
|
};
|
|
1673
2149
|
}
|
|
1674
2150
|
|
|
2151
|
+
// src/webhook/fetch-handler.ts
|
|
2152
|
+
var TOO_LARGE = /* @__PURE__ */ Symbol("too-large");
|
|
2153
|
+
function defaultPlatformFor(url) {
|
|
2154
|
+
const marker = "/webhooks/";
|
|
2155
|
+
const at = url.pathname.lastIndexOf(marker);
|
|
2156
|
+
if (at < 0) return void 0;
|
|
2157
|
+
const rest = url.pathname.slice(at + marker.length).replace(/\/+$/, "");
|
|
2158
|
+
const last = rest.split("/").pop();
|
|
2159
|
+
return last ? last : void 0;
|
|
2160
|
+
}
|
|
2161
|
+
function plain(status, extra) {
|
|
2162
|
+
return new Response(null, { status, headers: extra });
|
|
2163
|
+
}
|
|
2164
|
+
function tooLarge() {
|
|
2165
|
+
return plain(413, { connection: "close" });
|
|
2166
|
+
}
|
|
2167
|
+
async function readCapped(request, max) {
|
|
2168
|
+
const declared = request.headers.get("content-length");
|
|
2169
|
+
if (declared !== null && Number(declared) > max) return TOO_LARGE;
|
|
2170
|
+
if (request.body === null) return "";
|
|
2171
|
+
const reader = request.body.getReader();
|
|
2172
|
+
const chunks = [];
|
|
2173
|
+
let total = 0;
|
|
2174
|
+
for (; ; ) {
|
|
2175
|
+
const { done, value } = await reader.read();
|
|
2176
|
+
if (done) break;
|
|
2177
|
+
total += value.byteLength;
|
|
2178
|
+
if (total > max) {
|
|
2179
|
+
await reader.cancel().catch(() => void 0);
|
|
2180
|
+
return TOO_LARGE;
|
|
2181
|
+
}
|
|
2182
|
+
chunks.push(value);
|
|
2183
|
+
}
|
|
2184
|
+
const joined = new Uint8Array(total);
|
|
2185
|
+
let offset = 0;
|
|
2186
|
+
for (const chunk of chunks) {
|
|
2187
|
+
joined.set(chunk, offset);
|
|
2188
|
+
offset += chunk.byteLength;
|
|
2189
|
+
}
|
|
2190
|
+
return new TextDecoder().decode(joined);
|
|
2191
|
+
}
|
|
2192
|
+
function answerResponse(answer) {
|
|
2193
|
+
const headers = {};
|
|
2194
|
+
if (answer.contentType !== void 0) headers["content-type"] = answer.contentType;
|
|
2195
|
+
return new Response(answer.body ?? null, { status: answer.status, headers });
|
|
2196
|
+
}
|
|
2197
|
+
async function runDefault(webhook, adapter, request) {
|
|
2198
|
+
if (!webhook.verify(adapter, request)) return plain(401);
|
|
2199
|
+
let payload;
|
|
2200
|
+
try {
|
|
2201
|
+
payload = JSON.parse(request.rawBody);
|
|
2202
|
+
} catch {
|
|
2203
|
+
return plain(400);
|
|
2204
|
+
}
|
|
2205
|
+
const result = await webhook.ingest(adapter, payload);
|
|
2206
|
+
if (result === "delivered") return plain(200);
|
|
2207
|
+
return plain(result === "no_handler" ? 503 : 400);
|
|
2208
|
+
}
|
|
2209
|
+
function headersOf(request) {
|
|
2210
|
+
const out = {};
|
|
2211
|
+
request.headers.forEach((value, key) => {
|
|
2212
|
+
out[key] = value;
|
|
2213
|
+
});
|
|
2214
|
+
return out;
|
|
2215
|
+
}
|
|
2216
|
+
async function readBody(request, max) {
|
|
2217
|
+
let body;
|
|
2218
|
+
try {
|
|
2219
|
+
body = await readCapped(request, max);
|
|
2220
|
+
} catch {
|
|
2221
|
+
return plain(400);
|
|
2222
|
+
}
|
|
2223
|
+
return body === TOO_LARGE ? tooLarge() : body;
|
|
2224
|
+
}
|
|
2225
|
+
function createWebhookHandler(options) {
|
|
2226
|
+
const max = options.maxBodyBytes ?? DEFAULT_WEBHOOK_MAX_BYTES;
|
|
2227
|
+
const platformFor = options.platformFor ?? defaultPlatformFor;
|
|
2228
|
+
const routes = /* @__PURE__ */ new Map();
|
|
2229
|
+
for (const channel of options.channels) {
|
|
2230
|
+
if (channel.descriptor.transport === "webhook")
|
|
2231
|
+
routes.set(channel.descriptor.platform, channel);
|
|
2232
|
+
}
|
|
2233
|
+
const route = (url) => {
|
|
2234
|
+
const platform = platformFor(url);
|
|
2235
|
+
return platform === void 0 ? void 0 : routes.get(platform);
|
|
2236
|
+
};
|
|
2237
|
+
return async (request) => {
|
|
2238
|
+
const channel = route(new URL(request.url));
|
|
2239
|
+
if (channel === void 0) return plain(404);
|
|
2240
|
+
const platform = channel.descriptor.platform;
|
|
2241
|
+
if (!options.isStarted(platform)) return plain(503);
|
|
2242
|
+
const webhook = channel.descriptor.webhook;
|
|
2243
|
+
const refused2 = refuseMethod(webhook, request);
|
|
2244
|
+
if (refused2 !== void 0) return refused2;
|
|
2245
|
+
const rawBody = await readBody(request, max);
|
|
2246
|
+
if (typeof rawBody !== "string") return rawBody;
|
|
2247
|
+
try {
|
|
2248
|
+
return await dispatch(webhook, channel.adapter, {
|
|
2249
|
+
rawBody,
|
|
2250
|
+
headers: headersOf(request),
|
|
2251
|
+
method: request.method.toUpperCase(),
|
|
2252
|
+
url: request.url
|
|
2253
|
+
});
|
|
2254
|
+
} catch (error) {
|
|
2255
|
+
options.onError?.(platform, error);
|
|
2256
|
+
return plain(500);
|
|
2257
|
+
}
|
|
2258
|
+
};
|
|
2259
|
+
}
|
|
2260
|
+
function refuseMethod(webhook, request) {
|
|
2261
|
+
const methods = webhook.methods ?? ["POST"];
|
|
2262
|
+
const method = request.method.toUpperCase();
|
|
2263
|
+
if (methods.some((m) => m.toUpperCase() === method)) return void 0;
|
|
2264
|
+
return plain(405, { allow: methods.join(", ") });
|
|
2265
|
+
}
|
|
2266
|
+
async function dispatch(webhook, adapter, request) {
|
|
2267
|
+
if (webhook.handle !== void 0) return answerResponse(await webhook.handle(adapter, request));
|
|
2268
|
+
return runDefault(webhook, adapter, request);
|
|
2269
|
+
}
|
|
2270
|
+
|
|
1675
2271
|
exports.BasePlatformAdapter = BasePlatformAdapter;
|
|
1676
2272
|
exports.CREDENTIAL_SHAPES = CREDENTIAL_SHAPES;
|
|
1677
2273
|
exports.DEFAULT_WEBHOOK_MAX_BYTES = DEFAULT_WEBHOOK_MAX_BYTES;
|
|
@@ -1683,19 +2279,33 @@ exports.HookExecutor = HookExecutor;
|
|
|
1683
2279
|
exports.SeenIds = SeenIds;
|
|
1684
2280
|
exports.SessionRouter = SessionRouter;
|
|
1685
2281
|
exports.WeixinAdapterBase = WeixinAdapterBase;
|
|
2282
|
+
exports.bindingStrategy = bindingStrategy;
|
|
1686
2283
|
exports.channelRendering = channelRendering;
|
|
1687
2284
|
exports.chunkByGrapheme = chunkByGrapheme;
|
|
1688
2285
|
exports.chunkText = chunkText;
|
|
2286
|
+
exports.commandHook = commandHook;
|
|
2287
|
+
exports.configFromEnv = configFromEnv;
|
|
2288
|
+
exports.createAccessPolicyHook = createAccessPolicyHook;
|
|
2289
|
+
exports.createAgentBindings = createAgentBindings;
|
|
1689
2290
|
exports.createChannels = createChannels;
|
|
2291
|
+
exports.createFilePairingStore = createFilePairingStore;
|
|
2292
|
+
exports.createWebhookHandler = createWebhookHandler;
|
|
1690
2293
|
exports.defaultStrategy = defaultStrategy;
|
|
2294
|
+
exports.helpText = helpText;
|
|
2295
|
+
exports.isAuthenticatedSender = isAuthenticatedSender;
|
|
1691
2296
|
exports.listenerLifecycle = listenerLifecycle;
|
|
1692
2297
|
exports.loadPeer = loadPeer;
|
|
2298
|
+
exports.maskSecrets = maskSecrets;
|
|
1693
2299
|
exports.maskShapes = maskShapes;
|
|
2300
|
+
exports.parseChatCommand = parseChatCommand;
|
|
1694
2301
|
exports.parseFlatXml = parseFlatXml;
|
|
1695
2302
|
exports.rawBodyCapture = rawBodyCapture;
|
|
1696
2303
|
exports.redactSecrets = redactSecrets;
|
|
1697
2304
|
exports.scanFences = scanFences;
|
|
2305
|
+
exports.selectVariant = selectVariant;
|
|
2306
|
+
exports.senderKey = senderKey;
|
|
1698
2307
|
exports.splitKeepingRows = splitKeepingRows;
|
|
2308
|
+
exports.statusForDeliver = statusForDeliver;
|
|
1699
2309
|
exports.toDialect = toDialect;
|
|
1700
2310
|
exports.withMediaUnderstanding = withMediaUnderstanding;
|
|
1701
2311
|
//# sourceMappingURL=index.cjs.map
|