@theokit/gateway 0.19.0 → 0.21.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/dist/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  import { Security } from '@theokit/sdk';
2
+ import { randomInt, randomUUID } from 'crypto';
3
+ import { readFileSync, mkdirSync, writeFileSync, renameSync } from 'fs';
4
+ import { join } from 'path';
2
5
 
3
6
  // src/text/fence.ts
4
7
  var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
@@ -275,17 +278,17 @@ var BasePlatformAdapter = class _BasePlatformAdapter {
275
278
  * `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
276
279
  * Returns the refusal, or `undefined` when the message may be sent.
277
280
  */
278
- refuseUnsendable(out, check) {
281
+ refuseUnsendable(out, check2) {
279
282
  const refuse = (code, message) => ({
280
283
  ok: false,
281
284
  error: { code, message }
282
285
  });
283
286
  if (out.text.length === 0) return refuse("empty_text", "outbound text is empty");
284
- if (!check.connected) {
285
- return refuse("not_connected", `${check.className}.connect() has not succeeded`);
287
+ if (!check2.connected) {
288
+ return refuse("not_connected", `${check2.className}.connect() has not succeeded`);
286
289
  }
287
- if (check.channel !== void 0 && !check.channel.valid(out.channel.id)) {
288
- return refuse("invalid_channel", check.channel.message);
290
+ if (check2.channel !== void 0 && !check2.channel.valid(out.channel.id)) {
291
+ return refuse("invalid_channel", check2.channel.message);
289
292
  }
290
293
  return void 0;
291
294
  }
@@ -573,12 +576,62 @@ var GatewayConfigurationError = class extends Error {
573
576
  }
574
577
  };
575
578
 
579
+ // src/channel/config-from-env.ts
580
+ function readValue(env, name) {
581
+ const value = env[name]?.trim();
582
+ return value ? value : void 0;
583
+ }
584
+ function configFromEnv(descriptor, env, prefix = "") {
585
+ const config = {};
586
+ const missing = [];
587
+ const secrets = [];
588
+ for (const field of descriptor.config) {
589
+ if (field.env === void 0) continue;
590
+ const name = prefix + field.env;
591
+ const value = readValue(env, name);
592
+ if (value === void 0) {
593
+ if (field.required) missing.push(name);
594
+ continue;
595
+ }
596
+ config[field.key] = value;
597
+ recordSecret(field, value, secrets);
598
+ }
599
+ return { config, missing, secrets };
600
+ }
601
+ function recordSecret(field, value, secrets) {
602
+ if (field.secret && !secrets.includes(value)) secrets.push(value);
603
+ }
604
+ function mismatch(parent, variant, name) {
605
+ throw new GatewayConfigurationError("gateway", {
606
+ code: "platform_mismatch",
607
+ message: `channel ${parent.platform}: variant "${name}" reports platform ${variant.platform}`
608
+ });
609
+ }
610
+ function unknownVariant(descriptor, name) {
611
+ const valid = Object.keys(descriptor.variants ?? {});
612
+ const given = name === void 0 ? "(none given)" : `"${name}"`;
613
+ throw new GatewayConfigurationError("gateway", {
614
+ code: "unknown_channel_variant",
615
+ message: `channel ${descriptor.platform}: unknown variant ${given}; valid variants: ${valid.length > 0 ? valid.join(", ") : "(none)"}`
616
+ });
617
+ }
618
+ function selectVariant(descriptor, name) {
619
+ const variants = descriptor.variants ?? {};
620
+ if (name === void 0 && Object.keys(variants).length === 0) return descriptor;
621
+ const variant = name !== void 0 && Object.hasOwn(variants, name) ? variants[name] : void 0;
622
+ if (variant === void 0) return unknownVariant(descriptor, name);
623
+ if (variant.platform !== descriptor.platform) mismatch(descriptor, variant, name ?? "");
624
+ return variant;
625
+ }
626
+
576
627
  // src/channel/create-channels.ts
577
628
  function isAbsent(value) {
578
629
  return value === void 0 || value === null || value === "";
579
630
  }
580
631
  function missingRequiredKeys(entry, values) {
581
- return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => field.key);
632
+ return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map(
633
+ (field) => field.env === void 0 ? field.key : `${field.key} (env ${(entry.envPrefix ?? "") + field.env})`
634
+ );
582
635
  }
583
636
  function refused(platform, code, reason) {
584
637
  return {
@@ -696,72 +749,6 @@ var GatewayLifecycleError = class extends Error {
696
749
  this.code = opts.code;
697
750
  }
698
751
  };
699
-
700
- // src/hooks/chat-command.ts
701
- var LEADING_MENTION = /^(?:<@[^>]+>|@\S+)\s+/;
702
- var DEFAULT_PREFIXES = ["/"];
703
- function matchPrefix(text, prefixes) {
704
- let best;
705
- for (const p of prefixes) {
706
- if (p.length > 0 && text.startsWith(p) && (best === void 0 || p.length > best.length)) {
707
- best = p;
708
- }
709
- }
710
- return best;
711
- }
712
- function parseChatCommand(text, options) {
713
- const body = text.trim().replace(LEADING_MENTION, "");
714
- const prefix = matchPrefix(body, options?.prefixes ?? DEFAULT_PREFIXES);
715
- if (prefix === void 0) return void 0;
716
- const rest = body.slice(prefix.length);
717
- const m = /^([^\s@]+)(?:@\S+)?(?:\s+([\s\S]*))?$/.exec(rest);
718
- if (!m?.[1]) return void 0;
719
- return { name: m[1].toLowerCase(), arg: (m[2] ?? "").trim() };
720
- }
721
- function usageOf(c) {
722
- return c.usage ?? `/${c.name}`;
723
- }
724
- function helpText(commands) {
725
- return commands.map((c) => `${usageOf(c)} - ${c.description}`).join("\n");
726
- }
727
- function assertUnique(names) {
728
- const seen = /* @__PURE__ */ new Set();
729
- for (const raw of names) {
730
- const name = raw.toLowerCase();
731
- if (seen.has(name)) {
732
- throw new GatewayConfigurationError("gateway", {
733
- code: "duplicate_command",
734
- message: `gateway: duplicate_command: ${raw}`,
735
- detail: raw
736
- });
737
- }
738
- seen.add(name);
739
- }
740
- }
741
- function badArity(c, arg) {
742
- const mode = c.arg ?? "optional";
743
- return mode === "none" && arg !== "" || mode === "required" && arg === "";
744
- }
745
- function commandHook(commands, options) {
746
- const helpName = options?.helpCommand === void 0 ? "help" : options.helpCommand;
747
- assertUnique([...commands.map((c) => c.name), ...helpName === false ? [] : [helpName]]);
748
- const byName = new Map(commands.map((c) => [c.name.toLowerCase(), c]));
749
- const help = helpText(commands);
750
- return {
751
- name: options?.name ?? "chat-commands",
752
- async pre_inbound({ event }) {
753
- const parsed = parseChatCommand(event.text);
754
- if (!parsed) return void 0;
755
- if (helpName !== false && parsed.name === helpName.toLowerCase()) {
756
- return { block: true, message: help };
757
- }
758
- const command = byName.get(parsed.name);
759
- if (!command) return void 0;
760
- if (badArity(command, parsed.arg)) return { block: true, message: usageOf(command) };
761
- return command.run(event, parsed.arg);
762
- }
763
- };
764
- }
765
752
  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.
766
753
  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.
767
754
  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.
@@ -845,6 +832,256 @@ function maskSecrets(text, secrets) {
845
832
  for (const secret of ordered) out = out.split(secret).join("[redacted]");
846
833
  return out;
847
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 = 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 ?? randomInt;
867
+ const path = join(options.dir, FILE);
868
+ const paired = load(path);
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
+ mkdirSync(options.dir, { recursive: true });
877
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
878
+ writeFileSync(tmp, JSON.stringify({ paired: [...next].sort((a, b) => a.localeCompare(b)) }), {
879
+ mode: 384,
880
+ flag: "wx"
881
+ });
882
+ renameSync(tmp, path);
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
+ }
848
1085
 
849
1086
  // src/hooks/executor.ts
850
1087
  var HOOK_PHASES = ["pre_inbound", "post_outbound", "on_error"];
@@ -1552,6 +1789,49 @@ function bindingStrategy(bindings, inner) {
1552
1789
  return (event) => `${sanitize(bindings.agentFor(event))}-${inner(event)}`;
1553
1790
  }
1554
1791
 
1792
+ // src/session/scoped-strategy.ts
1793
+ var join2 = (...segments) => segments.map(sanitize).join("-");
1794
+ function invalid(message, detail) {
1795
+ return new GatewayConfigurationError("gateway", {
1796
+ code: "invalid_session_scope",
1797
+ message: `gateway: invalid_session_scope: ${message}`,
1798
+ ...detail === void 0 ? {} : { detail }
1799
+ });
1800
+ }
1801
+ function scopedStrategy(options) {
1802
+ const { dmScope, peerLinks, accountLabel, groupScope = "channel" } = options;
1803
+ if (dmScope === "per-account-channel-peer" && (accountLabel === void 0 || accountLabel === "")) {
1804
+ throw invalid("per-account-channel-peer requires a non-empty accountLabel", "accountLabel");
1805
+ }
1806
+ if (peerLinks !== void 0) {
1807
+ for (const [from, peer] of peerLinks) {
1808
+ if (peer === "") throw invalid(`empty peer name for ${from}`, from);
1809
+ }
1810
+ }
1811
+ const dmKey = (platform, senderId) => {
1812
+ switch (dmScope) {
1813
+ case "main":
1814
+ return "_m-dm";
1815
+ case "per-peer": {
1816
+ const peer = peerLinks?.get(`${platform}:${senderId}`);
1817
+ return peer === void 0 ? join2(platform, "dm", senderId) : `_p-dm-${sanitize(peer)}`;
1818
+ }
1819
+ case "per-channel-peer":
1820
+ return join2(platform, "dm", senderId);
1821
+ case "per-account-channel-peer":
1822
+ return join2(platform, "dm", accountLabel ?? "", senderId);
1823
+ }
1824
+ };
1825
+ return (event) => {
1826
+ const { platform, channel, sender } = event;
1827
+ if (channel.type === "dm") return dmKey(platform, sender.id);
1828
+ if (channel.type === "thread" && channel.topicId !== void 0) {
1829
+ return join2(platform, "tpc", channel.id, channel.topicId);
1830
+ }
1831
+ return groupScope === "channel-sender" ? join2(platform, "grp", channel.id, sender.id) : join2(platform, "grp", channel.id);
1832
+ };
1833
+ }
1834
+
1555
1835
  // src/text/chunk.ts
1556
1836
  function searchBoundary(remaining, window, boundaries) {
1557
1837
  let cut = window;
@@ -1802,9 +2082,9 @@ function statusForDeliver(outcomes) {
1802
2082
  }
1803
2083
 
1804
2084
  // src/webhook/express-server.ts
1805
- async function loadPeer(load, onMissing) {
2085
+ async function loadPeer(load2, onMissing) {
1806
2086
  try {
1807
- const mod = await load();
2087
+ const mod = await load2();
1808
2088
  return mod.default ?? mod;
1809
2089
  } catch {
1810
2090
  onMissing();
@@ -2031,6 +2311,6 @@ async function dispatch(webhook, adapter, request) {
2031
2311
  return runDefault(webhook, adapter, request);
2032
2312
  }
2033
2313
 
2034
- export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelRendering, chunkByGrapheme, chunkText, commandHook, createAgentBindings, createChannels, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
2314
+ export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
2035
2315
  //# sourceMappingURL=index.js.map
2036
2316
  //# sourceMappingURL=index.js.map