@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/CHANGELOG.md +17 -0
- package/README.md +70 -0
- package/dist/index.cjs +360 -74
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +135 -1
- package/dist/index.d.ts +135 -1
- package/dist/index.js +355 -75
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.21.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 6cad27f: Add `scopedStrategy` with four DM scopes (`main`, `per-peer`, `per-channel-peer`, `per-account-channel-peer`), peer links, an account label and a group scope.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- 9b4ca9f: `createChannels` rejections for missing required config now name each field's environment variable; pass `envPrefix` on a `ChannelEntry` to match the prefix given to `configFromEnv`.
|
|
12
|
+
|
|
13
|
+
## 0.20.0
|
|
14
|
+
|
|
15
|
+
### Minor Changes
|
|
16
|
+
|
|
17
|
+
- 80bbb11: Add `createAccessPolicyHook`, `createFilePairingStore` and `senderKey`: a `pre_inbound` hook that lets owners, paired and allowlisted senders through on platforms that authenticate the sender, applies a DM policy (`pairing`, `allowlist`, `open`, `disabled`) to strangers, and rate limits refusals.
|
|
18
|
+
- 295d6fa: Add `configFromEnv` and `selectVariant`: bind channel config fields to environment variables (`ChannelConfigField.env`), collect secret values for log masking, and pick a descriptor variant.
|
|
19
|
+
|
|
3
20
|
## 0.19.0
|
|
4
21
|
|
|
5
22
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -280,6 +280,34 @@ const hook = commandHook([
|
|
|
280
280
|
|
|
281
281
|
A command declared `arg: "none"` given an argument (or `"required"` given none) replies with its usage line instead of running. Two commands with the same name throw `GatewayConfigurationError` with code `duplicate_command`. `parseChatCommand(text, { prefixes })` is exported for apps that parse on their own.
|
|
282
282
|
|
|
283
|
+
## Access policy and pairing
|
|
284
|
+
|
|
285
|
+
`createAccessPolicyHook` decides who may talk to the agent. Owners (`<platform>:<senderId>` keys),
|
|
286
|
+
allowlisted and paired senders pass, only on platforms where `isAuthenticated` is true; an owner or
|
|
287
|
+
allowlist key on any other platform makes the constructor throw `unauthenticated_owner`. A DM from
|
|
288
|
+
anyone else follows `dm`: `open` passes, `disabled` is silent, `allowlist` answers `refusalText`,
|
|
289
|
+
`pairing` answers a 6-digit code and tells the sender to ask the owner for `/approve <code>`. A
|
|
290
|
+
refused sender is answered at most once per `refusalIntervalMs` (default one hour). An
|
|
291
|
+
unauthenticated sender is never answered. In a group a stranger gets no reply unless `groups: "open"`.
|
|
292
|
+
The owner's `/approve <code>` is answered "Paired." and never reaches the agent. A failure inside
|
|
293
|
+
the hook is logged (redacted) and becomes a silent block.
|
|
294
|
+
|
|
295
|
+
```typescript
|
|
296
|
+
import { createAccessPolicyHook, createFilePairingStore } from "@theokit/gateway";
|
|
297
|
+
|
|
298
|
+
const hook = createAccessPolicyHook({
|
|
299
|
+
owners: new Set(["telegram:12345"]),
|
|
300
|
+
dm: "pairing",
|
|
301
|
+
isAuthenticated: (p) => p === "telegram",
|
|
302
|
+
pairing: createFilePairingStore({ dir: "./state" }),
|
|
303
|
+
});
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
`createFilePairingStore` keeps paired senders in `pairing.json` (mode 0600, written through a temp
|
|
307
|
+
file and a rename) and pending codes in memory for one hour. A missing file is an empty store; an
|
|
308
|
+
unreadable or malformed one throws `pairing_store_unreadable`. `senderKey(platform, id)` builds the
|
|
309
|
+
key; email ids compare case-insensitively.
|
|
310
|
+
|
|
283
311
|
## Agent bindings
|
|
284
312
|
|
|
285
313
|
When one gateway serves several agents, `createAgentBindings` picks the agent per message. A rule names an `agent` and any of `platform`, `account` and `peer` (the sender id in a DM, the channel id otherwise). A rule matches when every field it sets equals the message's. The most specific match wins (peer 4, account 2, platform 1), ties go to the earlier rule, and no match gives `defaultAgent`.
|
|
@@ -297,6 +325,29 @@ const router = new SessionRouter(bindingStrategy(bindings, defaultStrategy));
|
|
|
297
325
|
|
|
298
326
|
`accountOf(event)` says which bot account received the event when the app runs several. Creation throws `GatewayConfigurationError` with code `unknown_agent` for a default or rule naming an agent not in `agents`, and `empty_binding_rule` for a rule with no `platform`, `account` or `peer`. `bindingStrategy` prefixes the inner key with the escaped agent name, so two agents never share a session.
|
|
299
327
|
|
|
328
|
+
## Session scopes
|
|
329
|
+
|
|
330
|
+
`scopedStrategy` builds a `SessionRouter` strategy with a DM scope. Every segment is escaped with the shared injective `sanitize` (`_` to `__`, `-` to `_d`) and joined with `-`, so distinct inputs never share a key. `dm` is always the second key segment, so a DM key never equals a group or thread key.
|
|
331
|
+
|
|
332
|
+
| `dmScope` | DM key |
|
|
333
|
+
| --- | --- |
|
|
334
|
+
| `main` | `_m-dm` (every DM is one conversation) |
|
|
335
|
+
| `per-peer` | `_p-dm-<peer>` for a sender in `peerLinks` (`"<platform>:<senderId>"` to a peer name, shared across platforms); an unlinked sender gets the `per-channel-peer` key |
|
|
336
|
+
| `per-channel-peer` | `<platform>-dm-<sender>` |
|
|
337
|
+
| `per-account-channel-peer` | `<platform>-dm-<accountLabel>-<sender>` (needs `accountLabel`) |
|
|
338
|
+
|
|
339
|
+
Groups ignore `dmScope`: `<platform>-grp-<channel>`, or `<platform>-grp-<channel>-<sender>` with `groupScope: "channel-sender"`. A thread with a topic is `<platform>-tpc-<channel>-<topic>`.
|
|
340
|
+
|
|
341
|
+
```ts
|
|
342
|
+
import { scopedStrategy, SessionRouter } from "@theokit/gateway";
|
|
343
|
+
|
|
344
|
+
const router = new SessionRouter(
|
|
345
|
+
scopedStrategy({ dmScope: "per-peer", peerLinks: new Map([["telegram:42", "ana"], ["slack:U1", "ana"]]) }),
|
|
346
|
+
);
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
Creation throws `GatewayConfigurationError` with code `invalid_session_scope` for `per-account-channel-peer` without a non-empty `accountLabel`, or for an empty peer name. It never throws per event.
|
|
350
|
+
|
|
300
351
|
## Architecture (5 pieces)
|
|
301
352
|
|
|
302
353
|
| Module | Responsibility |
|
|
@@ -358,6 +409,8 @@ const { adapters, rejected } = createChannels([
|
|
|
358
409
|
},
|
|
359
410
|
]);
|
|
360
411
|
for (const { platform, error } of rejected) console.error(`${platform}: ${error.message}`);
|
|
412
|
+
// A rejection names each missing field's environment variable when the descriptor declares `env`.
|
|
413
|
+
// Pass `envPrefix` (the prefix you give `configFromEnv`) on an entry for the full variable name.
|
|
361
414
|
|
|
362
415
|
const runner = new GatewayRunner({
|
|
363
416
|
adapters,
|
|
@@ -372,6 +425,23 @@ if (connected.length === 0) throw new Error("no channel connected");
|
|
|
372
425
|
for (const { platform, reason } of failed) console.error(`${platform} did not connect: ${reason}`);
|
|
373
426
|
```
|
|
374
427
|
|
|
428
|
+
To build channels from environment variables, give each descriptor field an `env` name and read it
|
|
429
|
+
with `configFromEnv`. It trims values, treats empty or whitespace as unset, lists unset required
|
|
430
|
+
variables by full name in `missing`, and returns secret values in `secrets` for a log mask.
|
|
431
|
+
`selectVariant` picks one of a descriptor's `variants` (for example a WhatsApp backend).
|
|
432
|
+
|
|
433
|
+
```typescript
|
|
434
|
+
import { configFromEnv, createChannels, selectVariant } from "@theokit/gateway";
|
|
435
|
+
|
|
436
|
+
const descriptor = selectVariant(whatsappChannel, process.env.APP_WHATSAPP_BACKEND);
|
|
437
|
+
const { config, missing, secrets } = configFromEnv(descriptor, process.env, "APP_");
|
|
438
|
+
if (missing.length > 0) console.error(`skipped: set ${missing.join(", ")}`);
|
|
439
|
+
else {
|
|
440
|
+
const { adapters } = createChannels([{ descriptor, config }]);
|
|
441
|
+
// pass `secrets` to your log mask
|
|
442
|
+
}
|
|
443
|
+
```
|
|
444
|
+
|
|
375
445
|
- `createChannels` rejects an entry whose required field is absent, `null` or `""` with a
|
|
376
446
|
`GatewayConfigurationError` coded `missing_required_config` that names the keys, and reports a
|
|
377
447
|
configuration error thrown by `create` the same way. Any other error propagates. It performs no
|
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;
|
|
@@ -277,17 +280,17 @@ var BasePlatformAdapter = class _BasePlatformAdapter {
|
|
|
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
|
}
|
|
@@ -575,12 +578,62 @@ var GatewayConfigurationError = class extends Error {
|
|
|
575
578
|
}
|
|
576
579
|
};
|
|
577
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
|
+
|
|
578
629
|
// src/channel/create-channels.ts
|
|
579
630
|
function isAbsent(value) {
|
|
580
631
|
return value === void 0 || value === null || value === "";
|
|
581
632
|
}
|
|
582
633
|
function missingRequiredKeys(entry, values) {
|
|
583
|
-
return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map(
|
|
634
|
+
return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map(
|
|
635
|
+
(field) => field.env === void 0 ? field.key : `${field.key} (env ${(entry.envPrefix ?? "") + field.env})`
|
|
636
|
+
);
|
|
584
637
|
}
|
|
585
638
|
function refused(platform, code, reason) {
|
|
586
639
|
return {
|
|
@@ -698,72 +751,6 @@ var GatewayLifecycleError = class extends Error {
|
|
|
698
751
|
this.code = opts.code;
|
|
699
752
|
}
|
|
700
753
|
};
|
|
701
|
-
|
|
702
|
-
// src/hooks/chat-command.ts
|
|
703
|
-
var LEADING_MENTION = /^(?:<@[^>]+>|@\S+)\s+/;
|
|
704
|
-
var DEFAULT_PREFIXES = ["/"];
|
|
705
|
-
function matchPrefix(text, prefixes) {
|
|
706
|
-
let best;
|
|
707
|
-
for (const p of prefixes) {
|
|
708
|
-
if (p.length > 0 && text.startsWith(p) && (best === void 0 || p.length > best.length)) {
|
|
709
|
-
best = p;
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
return best;
|
|
713
|
-
}
|
|
714
|
-
function parseChatCommand(text, options) {
|
|
715
|
-
const body = text.trim().replace(LEADING_MENTION, "");
|
|
716
|
-
const prefix = matchPrefix(body, options?.prefixes ?? DEFAULT_PREFIXES);
|
|
717
|
-
if (prefix === void 0) return void 0;
|
|
718
|
-
const rest = body.slice(prefix.length);
|
|
719
|
-
const m = /^([^\s@]+)(?:@\S+)?(?:\s+([\s\S]*))?$/.exec(rest);
|
|
720
|
-
if (!m?.[1]) return void 0;
|
|
721
|
-
return { name: m[1].toLowerCase(), arg: (m[2] ?? "").trim() };
|
|
722
|
-
}
|
|
723
|
-
function usageOf(c) {
|
|
724
|
-
return c.usage ?? `/${c.name}`;
|
|
725
|
-
}
|
|
726
|
-
function helpText(commands) {
|
|
727
|
-
return commands.map((c) => `${usageOf(c)} - ${c.description}`).join("\n");
|
|
728
|
-
}
|
|
729
|
-
function assertUnique(names) {
|
|
730
|
-
const seen = /* @__PURE__ */ new Set();
|
|
731
|
-
for (const raw of names) {
|
|
732
|
-
const name = raw.toLowerCase();
|
|
733
|
-
if (seen.has(name)) {
|
|
734
|
-
throw new GatewayConfigurationError("gateway", {
|
|
735
|
-
code: "duplicate_command",
|
|
736
|
-
message: `gateway: duplicate_command: ${raw}`,
|
|
737
|
-
detail: raw
|
|
738
|
-
});
|
|
739
|
-
}
|
|
740
|
-
seen.add(name);
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
function badArity(c, arg) {
|
|
744
|
-
const mode = c.arg ?? "optional";
|
|
745
|
-
return mode === "none" && arg !== "" || mode === "required" && arg === "";
|
|
746
|
-
}
|
|
747
|
-
function commandHook(commands, options) {
|
|
748
|
-
const helpName = options?.helpCommand === void 0 ? "help" : options.helpCommand;
|
|
749
|
-
assertUnique([...commands.map((c) => c.name), ...helpName === false ? [] : [helpName]]);
|
|
750
|
-
const byName = new Map(commands.map((c) => [c.name.toLowerCase(), c]));
|
|
751
|
-
const help = helpText(commands);
|
|
752
|
-
return {
|
|
753
|
-
name: options?.name ?? "chat-commands",
|
|
754
|
-
async pre_inbound({ event }) {
|
|
755
|
-
const parsed = parseChatCommand(event.text);
|
|
756
|
-
if (!parsed) return void 0;
|
|
757
|
-
if (helpName !== false && parsed.name === helpName.toLowerCase()) {
|
|
758
|
-
return { block: true, message: help };
|
|
759
|
-
}
|
|
760
|
-
const command = byName.get(parsed.name);
|
|
761
|
-
if (!command) return void 0;
|
|
762
|
-
if (badArity(command, parsed.arg)) return { block: true, message: usageOf(command) };
|
|
763
|
-
return command.run(event, parsed.arg);
|
|
764
|
-
}
|
|
765
|
-
};
|
|
766
|
-
}
|
|
767
754
|
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.
|
|
768
755
|
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.
|
|
769
756
|
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.
|
|
@@ -847,6 +834,256 @@ function maskSecrets(text, secrets) {
|
|
|
847
834
|
for (const secret of ordered) out = out.split(secret).join("[redacted]");
|
|
848
835
|
return out;
|
|
849
836
|
}
|
|
837
|
+
function senderKey(platform, senderId) {
|
|
838
|
+
return `${platform}:${platform === "email" ? senderId.toLowerCase() : senderId}`;
|
|
839
|
+
}
|
|
840
|
+
var TTL_MS = 36e5;
|
|
841
|
+
var FILE = "pairing.json";
|
|
842
|
+
function unreadable() {
|
|
843
|
+
return new GatewayConfigurationError("gateway", {
|
|
844
|
+
code: "pairing_store_unreadable",
|
|
845
|
+
message: "gateway: pairing_store_unreadable"
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
function load(path) {
|
|
849
|
+
let raw;
|
|
850
|
+
try {
|
|
851
|
+
raw = fs.readFileSync(path, "utf8");
|
|
852
|
+
} catch (e) {
|
|
853
|
+
if (e.code === "ENOENT") return /* @__PURE__ */ new Set();
|
|
854
|
+
throw unreadable();
|
|
855
|
+
}
|
|
856
|
+
let parsed;
|
|
857
|
+
try {
|
|
858
|
+
parsed = JSON.parse(raw);
|
|
859
|
+
} catch {
|
|
860
|
+
throw unreadable();
|
|
861
|
+
}
|
|
862
|
+
const list = parsed?.paired;
|
|
863
|
+
if (!Array.isArray(list) || !list.every((x) => typeof x === "string")) throw unreadable();
|
|
864
|
+
return new Set(list);
|
|
865
|
+
}
|
|
866
|
+
function createFilePairingStore(options) {
|
|
867
|
+
const clock = options.clock ?? Date.now;
|
|
868
|
+
const random = options.random ?? crypto.randomInt;
|
|
869
|
+
const path$1 = path.join(options.dir, FILE);
|
|
870
|
+
const paired = load(path$1);
|
|
871
|
+
const pending = /* @__PURE__ */ new Map();
|
|
872
|
+
let chain = Promise.resolve();
|
|
873
|
+
const prune = () => {
|
|
874
|
+
const now = clock();
|
|
875
|
+
for (const [code, p] of pending) if (p.expires <= now) pending.delete(code);
|
|
876
|
+
};
|
|
877
|
+
function persist(next) {
|
|
878
|
+
fs.mkdirSync(options.dir, { recursive: true });
|
|
879
|
+
const tmp = `${path$1}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
880
|
+
fs.writeFileSync(tmp, JSON.stringify({ paired: [...next].sort((a, b) => a.localeCompare(b)) }), {
|
|
881
|
+
mode: 384,
|
|
882
|
+
flag: "wx"
|
|
883
|
+
});
|
|
884
|
+
fs.renameSync(tmp, path$1);
|
|
885
|
+
}
|
|
886
|
+
return {
|
|
887
|
+
issue(platform, senderId) {
|
|
888
|
+
prune();
|
|
889
|
+
for (const [code2, p] of pending) {
|
|
890
|
+
if (senderKey(p.platform, p.senderId) === senderKey(platform, senderId)) return code2;
|
|
891
|
+
}
|
|
892
|
+
let code;
|
|
893
|
+
do {
|
|
894
|
+
code = String(random(1e5, 1e6));
|
|
895
|
+
} while (pending.has(code));
|
|
896
|
+
pending.set(code, { platform, senderId, expires: clock() + TTL_MS });
|
|
897
|
+
return code;
|
|
898
|
+
},
|
|
899
|
+
approve(code) {
|
|
900
|
+
const run = async () => {
|
|
901
|
+
prune();
|
|
902
|
+
const p = pending.get(code);
|
|
903
|
+
if (!p) return { ok: false, reason: "unknown_or_expired" };
|
|
904
|
+
const next = new Set(paired);
|
|
905
|
+
next.add(senderKey(p.platform, p.senderId));
|
|
906
|
+
try {
|
|
907
|
+
persist(next);
|
|
908
|
+
} catch {
|
|
909
|
+
return { ok: false, reason: "write_failed" };
|
|
910
|
+
}
|
|
911
|
+
paired.add(senderKey(p.platform, p.senderId));
|
|
912
|
+
pending.delete(code);
|
|
913
|
+
return { ok: true, platform: p.platform, senderId: p.senderId };
|
|
914
|
+
};
|
|
915
|
+
const result = chain.then(run, run);
|
|
916
|
+
chain = result.catch(() => void 0);
|
|
917
|
+
return result;
|
|
918
|
+
},
|
|
919
|
+
isPaired(platform, senderId) {
|
|
920
|
+
return paired.has(senderKey(platform, senderId));
|
|
921
|
+
}
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
// src/hooks/access-policy.ts
|
|
926
|
+
var SILENT = { block: true };
|
|
927
|
+
var DEFAULT_REFUSAL = "Sorry, you are not authorized to use this assistant.";
|
|
928
|
+
function normalize(key) {
|
|
929
|
+
const i = key.indexOf(":");
|
|
930
|
+
return i < 0 ? key : senderKey(key.slice(0, i), key.slice(i + 1));
|
|
931
|
+
}
|
|
932
|
+
function check(keys, isAuth) {
|
|
933
|
+
const out = /* @__PURE__ */ new Set();
|
|
934
|
+
for (const key of keys) {
|
|
935
|
+
const i = key.indexOf(":");
|
|
936
|
+
const platform = i < 0 ? key : key.slice(0, i);
|
|
937
|
+
if (!isAuth(platform)) {
|
|
938
|
+
throw new GatewayConfigurationError("gateway", {
|
|
939
|
+
code: "unauthenticated_owner",
|
|
940
|
+
message: `gateway: unauthenticated_owner: platform ${platform} does not authenticate the sender`,
|
|
941
|
+
detail: platform
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
out.add(normalize(key));
|
|
945
|
+
}
|
|
946
|
+
return out;
|
|
947
|
+
}
|
|
948
|
+
function createAccessPolicyHook(options) {
|
|
949
|
+
if (options.dm === "pairing" && !options.pairing) {
|
|
950
|
+
throw new GatewayConfigurationError("gateway", {
|
|
951
|
+
code: "pairing_store_required",
|
|
952
|
+
message: "gateway: pairing_store_required"
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
const owners = check(options.owners, options.isAuthenticated);
|
|
956
|
+
const allowed = check(options.allowed ?? /* @__PURE__ */ new Set(), options.isAuthenticated);
|
|
957
|
+
const clock = options.clock ?? Date.now;
|
|
958
|
+
const interval = options.refusalIntervalMs ?? 36e5;
|
|
959
|
+
const write = options.write ?? ((line) => process.stderr.write(`${line}
|
|
960
|
+
`));
|
|
961
|
+
const refusal = options.refusalText ?? DEFAULT_REFUSAL;
|
|
962
|
+
const store = options.pairing;
|
|
963
|
+
const refused2 = /* @__PURE__ */ new Map();
|
|
964
|
+
const mayRefuse = (key) => {
|
|
965
|
+
const now = clock();
|
|
966
|
+
for (const [k, t] of refused2) if (now - t >= interval) refused2.delete(k);
|
|
967
|
+
if (refused2.has(key)) return false;
|
|
968
|
+
refused2.set(key, now);
|
|
969
|
+
return true;
|
|
970
|
+
};
|
|
971
|
+
const pairingReply = (event) => {
|
|
972
|
+
const code = store.issue(event.platform, event.sender.id);
|
|
973
|
+
return {
|
|
974
|
+
block: true,
|
|
975
|
+
message: `Your pairing code is ${code}. Ask the owner to send /approve ${code}.`
|
|
976
|
+
};
|
|
977
|
+
};
|
|
978
|
+
const groupDecision = () => options.groups === "open" ? void 0 : SILENT;
|
|
979
|
+
const stranger = (event, key) => {
|
|
980
|
+
if (event.channel.type !== "dm") return groupDecision();
|
|
981
|
+
if (options.dm === "open") return void 0;
|
|
982
|
+
if (options.dm === "disabled" || !mayRefuse(key)) return SILENT;
|
|
983
|
+
if (options.dm === "allowlist") return { block: true, message: refusal };
|
|
984
|
+
return pairingReply(event);
|
|
985
|
+
};
|
|
986
|
+
const ownerMessage = async (text) => {
|
|
987
|
+
const m = /^\/approve\s+(\d{6})\s*$/.exec(text.trim());
|
|
988
|
+
if (!m?.[1]) return void 0;
|
|
989
|
+
if (!store) return { block: true, message: "Pairing is not enabled." };
|
|
990
|
+
const r = await store.approve(m[1]);
|
|
991
|
+
if (r.ok) return { block: true, message: "Paired." };
|
|
992
|
+
return {
|
|
993
|
+
block: true,
|
|
994
|
+
message: r.reason === "write_failed" ? "Saving the pairing failed. Check the storage and send the code again." : "Unknown or expired code."
|
|
995
|
+
};
|
|
996
|
+
};
|
|
997
|
+
const isPaired = (event) => store?.isPaired(event.platform, event.sender.id) === true;
|
|
998
|
+
const decide = async (event) => {
|
|
999
|
+
if (options.passThrough?.(event)) return void 0;
|
|
1000
|
+
if (!options.isAuthenticated(event.platform)) return SILENT;
|
|
1001
|
+
const key = senderKey(event.platform, event.sender.id);
|
|
1002
|
+
if (owners.has(key)) return ownerMessage(event.text);
|
|
1003
|
+
if (allowed.has(key) || isPaired(event)) return void 0;
|
|
1004
|
+
return stranger(event, key);
|
|
1005
|
+
};
|
|
1006
|
+
return {
|
|
1007
|
+
name: "access-policy",
|
|
1008
|
+
async pre_inbound({ event }) {
|
|
1009
|
+
try {
|
|
1010
|
+
return await decide(event);
|
|
1011
|
+
} catch (e) {
|
|
1012
|
+
try {
|
|
1013
|
+
write(`access-policy: hook failed: ${redactSecrets(e)}`);
|
|
1014
|
+
} catch {
|
|
1015
|
+
}
|
|
1016
|
+
return SILENT;
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
// src/hooks/chat-command.ts
|
|
1023
|
+
var LEADING_MENTION = /^(?:<@[^>]+>|@\S+)\s+/;
|
|
1024
|
+
var DEFAULT_PREFIXES = ["/"];
|
|
1025
|
+
function matchPrefix(text, prefixes) {
|
|
1026
|
+
let best;
|
|
1027
|
+
for (const p of prefixes) {
|
|
1028
|
+
if (p.length > 0 && text.startsWith(p) && (best === void 0 || p.length > best.length)) {
|
|
1029
|
+
best = p;
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
return best;
|
|
1033
|
+
}
|
|
1034
|
+
function parseChatCommand(text, options) {
|
|
1035
|
+
const body = text.trim().replace(LEADING_MENTION, "");
|
|
1036
|
+
const prefix = matchPrefix(body, options?.prefixes ?? DEFAULT_PREFIXES);
|
|
1037
|
+
if (prefix === void 0) return void 0;
|
|
1038
|
+
const rest = body.slice(prefix.length);
|
|
1039
|
+
const m = /^([^\s@]+)(?:@\S+)?(?:\s+([\s\S]*))?$/.exec(rest);
|
|
1040
|
+
if (!m?.[1]) return void 0;
|
|
1041
|
+
return { name: m[1].toLowerCase(), arg: (m[2] ?? "").trim() };
|
|
1042
|
+
}
|
|
1043
|
+
function usageOf(c) {
|
|
1044
|
+
return c.usage ?? `/${c.name}`;
|
|
1045
|
+
}
|
|
1046
|
+
function helpText(commands) {
|
|
1047
|
+
return commands.map((c) => `${usageOf(c)} - ${c.description}`).join("\n");
|
|
1048
|
+
}
|
|
1049
|
+
function assertUnique(names) {
|
|
1050
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1051
|
+
for (const raw of names) {
|
|
1052
|
+
const name = raw.toLowerCase();
|
|
1053
|
+
if (seen.has(name)) {
|
|
1054
|
+
throw new GatewayConfigurationError("gateway", {
|
|
1055
|
+
code: "duplicate_command",
|
|
1056
|
+
message: `gateway: duplicate_command: ${raw}`,
|
|
1057
|
+
detail: raw
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
seen.add(name);
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
function badArity(c, arg) {
|
|
1064
|
+
const mode = c.arg ?? "optional";
|
|
1065
|
+
return mode === "none" && arg !== "" || mode === "required" && arg === "";
|
|
1066
|
+
}
|
|
1067
|
+
function commandHook(commands, options) {
|
|
1068
|
+
const helpName = options?.helpCommand === void 0 ? "help" : options.helpCommand;
|
|
1069
|
+
assertUnique([...commands.map((c) => c.name), ...helpName === false ? [] : [helpName]]);
|
|
1070
|
+
const byName = new Map(commands.map((c) => [c.name.toLowerCase(), c]));
|
|
1071
|
+
const help = helpText(commands);
|
|
1072
|
+
return {
|
|
1073
|
+
name: options?.name ?? "chat-commands",
|
|
1074
|
+
async pre_inbound({ event }) {
|
|
1075
|
+
const parsed = parseChatCommand(event.text);
|
|
1076
|
+
if (!parsed) return void 0;
|
|
1077
|
+
if (helpName !== false && parsed.name === helpName.toLowerCase()) {
|
|
1078
|
+
return { block: true, message: help };
|
|
1079
|
+
}
|
|
1080
|
+
const command = byName.get(parsed.name);
|
|
1081
|
+
if (!command) return void 0;
|
|
1082
|
+
if (badArity(command, parsed.arg)) return { block: true, message: usageOf(command) };
|
|
1083
|
+
return command.run(event, parsed.arg);
|
|
1084
|
+
}
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
850
1087
|
|
|
851
1088
|
// src/hooks/executor.ts
|
|
852
1089
|
var HOOK_PHASES = ["pre_inbound", "post_outbound", "on_error"];
|
|
@@ -1554,6 +1791,49 @@ function bindingStrategy(bindings, inner) {
|
|
|
1554
1791
|
return (event) => `${sanitize(bindings.agentFor(event))}-${inner(event)}`;
|
|
1555
1792
|
}
|
|
1556
1793
|
|
|
1794
|
+
// src/session/scoped-strategy.ts
|
|
1795
|
+
var join2 = (...segments) => segments.map(sanitize).join("-");
|
|
1796
|
+
function invalid(message, detail) {
|
|
1797
|
+
return new GatewayConfigurationError("gateway", {
|
|
1798
|
+
code: "invalid_session_scope",
|
|
1799
|
+
message: `gateway: invalid_session_scope: ${message}`,
|
|
1800
|
+
...detail === void 0 ? {} : { detail }
|
|
1801
|
+
});
|
|
1802
|
+
}
|
|
1803
|
+
function scopedStrategy(options) {
|
|
1804
|
+
const { dmScope, peerLinks, accountLabel, groupScope = "channel" } = options;
|
|
1805
|
+
if (dmScope === "per-account-channel-peer" && (accountLabel === void 0 || accountLabel === "")) {
|
|
1806
|
+
throw invalid("per-account-channel-peer requires a non-empty accountLabel", "accountLabel");
|
|
1807
|
+
}
|
|
1808
|
+
if (peerLinks !== void 0) {
|
|
1809
|
+
for (const [from, peer] of peerLinks) {
|
|
1810
|
+
if (peer === "") throw invalid(`empty peer name for ${from}`, from);
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
const dmKey = (platform, senderId) => {
|
|
1814
|
+
switch (dmScope) {
|
|
1815
|
+
case "main":
|
|
1816
|
+
return "_m-dm";
|
|
1817
|
+
case "per-peer": {
|
|
1818
|
+
const peer = peerLinks?.get(`${platform}:${senderId}`);
|
|
1819
|
+
return peer === void 0 ? join2(platform, "dm", senderId) : `_p-dm-${sanitize(peer)}`;
|
|
1820
|
+
}
|
|
1821
|
+
case "per-channel-peer":
|
|
1822
|
+
return join2(platform, "dm", senderId);
|
|
1823
|
+
case "per-account-channel-peer":
|
|
1824
|
+
return join2(platform, "dm", accountLabel ?? "", senderId);
|
|
1825
|
+
}
|
|
1826
|
+
};
|
|
1827
|
+
return (event) => {
|
|
1828
|
+
const { platform, channel, sender } = event;
|
|
1829
|
+
if (channel.type === "dm") return dmKey(platform, sender.id);
|
|
1830
|
+
if (channel.type === "thread" && channel.topicId !== void 0) {
|
|
1831
|
+
return join2(platform, "tpc", channel.id, channel.topicId);
|
|
1832
|
+
}
|
|
1833
|
+
return groupScope === "channel-sender" ? join2(platform, "grp", channel.id, sender.id) : join2(platform, "grp", channel.id);
|
|
1834
|
+
};
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1557
1837
|
// src/text/chunk.ts
|
|
1558
1838
|
function searchBoundary(remaining, window, boundaries) {
|
|
1559
1839
|
let cut = window;
|
|
@@ -1804,9 +2084,9 @@ function statusForDeliver(outcomes) {
|
|
|
1804
2084
|
}
|
|
1805
2085
|
|
|
1806
2086
|
// src/webhook/express-server.ts
|
|
1807
|
-
async function loadPeer(
|
|
2087
|
+
async function loadPeer(load2, onMissing) {
|
|
1808
2088
|
try {
|
|
1809
|
-
const mod = await
|
|
2089
|
+
const mod = await load2();
|
|
1810
2090
|
return mod.default ?? mod;
|
|
1811
2091
|
} catch {
|
|
1812
2092
|
onMissing();
|
|
@@ -2049,8 +2329,11 @@ exports.channelRendering = channelRendering;
|
|
|
2049
2329
|
exports.chunkByGrapheme = chunkByGrapheme;
|
|
2050
2330
|
exports.chunkText = chunkText;
|
|
2051
2331
|
exports.commandHook = commandHook;
|
|
2332
|
+
exports.configFromEnv = configFromEnv;
|
|
2333
|
+
exports.createAccessPolicyHook = createAccessPolicyHook;
|
|
2052
2334
|
exports.createAgentBindings = createAgentBindings;
|
|
2053
2335
|
exports.createChannels = createChannels;
|
|
2336
|
+
exports.createFilePairingStore = createFilePairingStore;
|
|
2054
2337
|
exports.createWebhookHandler = createWebhookHandler;
|
|
2055
2338
|
exports.defaultStrategy = defaultStrategy;
|
|
2056
2339
|
exports.helpText = helpText;
|
|
@@ -2064,6 +2347,9 @@ exports.parseFlatXml = parseFlatXml;
|
|
|
2064
2347
|
exports.rawBodyCapture = rawBodyCapture;
|
|
2065
2348
|
exports.redactSecrets = redactSecrets;
|
|
2066
2349
|
exports.scanFences = scanFences;
|
|
2350
|
+
exports.scopedStrategy = scopedStrategy;
|
|
2351
|
+
exports.selectVariant = selectVariant;
|
|
2352
|
+
exports.senderKey = senderKey;
|
|
2067
2353
|
exports.splitKeepingRows = splitKeepingRows;
|
|
2068
2354
|
exports.statusForDeliver = statusForDeliver;
|
|
2069
2355
|
exports.toDialect = toDialect;
|