@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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.20.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
- 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.
|
|
9
|
+
|
|
10
|
+
## 0.19.0
|
|
11
|
+
|
|
12
|
+
### Minor Changes
|
|
13
|
+
|
|
14
|
+
- 9c832b2: Add `AdapterCapabilities` and `BasePlatformAdapter.capabilities` (edit, attachment kinds, typing, reactions, threads, max length), derived by default. Telegram reports `image` and `audio` attachments.
|
|
15
|
+
- 6a80cc5: Add `createAgentBindings` and `bindingStrategy`: rule-based choice of agent by platform, account and peer, with session keys prefixed by the bound agent.
|
|
16
|
+
- 8e54100: Add `parseChatCommand`, `commandHook` and `helpText`: one `pre_inbound` hook that strips a leading mention and `@bot` suffix, matches commands exactly and answers `/help`.
|
|
17
|
+
- 362e4ef: Add `createWebhookHandler`, a Fetch handler that routes every webhook channel, and `statusForDeliver`. `ChannelWebhook` gains optional `methods` and `handle`, and `WebhookRequest` gains `method` and `url`.
|
|
18
|
+
- 9f21ff7: `GatewayRunner` gains `connectTimeoutMs`, `onAdapterState` and `secrets` options (under `connectFailure: "isolate"`), an `adapter(platform)` lookup, a live `connected` set, and an exported `maskSecrets` helper and `AdapterState` type.
|
|
19
|
+
- 56bb1d8: Declare whether a channel's sender id is authenticated with `senderIdentity`.
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- e2a6da8: The cross-adapter lint tests no longer count `gateway-agent`, which bridges an agent to adapters and is not a platform adapter.
|
|
24
|
+
|
|
3
25
|
## 0.18.0
|
|
4
26
|
|
|
5
27
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -246,6 +246,85 @@ reach the platform in either order, and the one that lands last stays on screen;
|
|
|
246
246
|
edit is a separate event and clients show the newest. Await each edit before sending the next,
|
|
247
247
|
or keep one in flight and send only the latest text when it settles.
|
|
248
248
|
|
|
249
|
+
## Adapter capabilities
|
|
250
|
+
|
|
251
|
+
Every adapter has a `capabilities` getter, so an app reads what a channel can do instead of
|
|
252
|
+
keeping a table of platform names:
|
|
253
|
+
|
|
254
|
+
```ts
|
|
255
|
+
const { edit, attachments, typing, reactions, threads, maxMessageChars } = adapter.capabilities;
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
- `edit` is `supportsEdit`.
|
|
259
|
+
- `attachments` lists the kinds the adapter sends (`"image"`, `"audio"`); `[]` when none. An
|
|
260
|
+
adapter that sets only `supportsAttachments = true` reports `["image"]`; one that sends more
|
|
261
|
+
sets the protected `attachmentKinds`.
|
|
262
|
+
- `typing` and `reactions` are `true` when the adapter overrides `startTyping` and `react`.
|
|
263
|
+
- `threads` is `false` and `maxMessageChars` is `undefined` unless an adapter overrides the
|
|
264
|
+
getter; no adapter sets them yet.
|
|
265
|
+
|
|
266
|
+
The type is exported as `AdapterCapabilities`.
|
|
267
|
+
|
|
268
|
+
## Chat commands
|
|
269
|
+
|
|
270
|
+
`commandHook` is one `pre_inbound` hook for many commands. It recognises a command behind one leading mention (`<@U123> /help`, `@bot /help`) and with Telegram's `@bot` suffix (`/help@my_bot`), matches the name exactly (`/new chat` is `/new` with arg `chat`; `/newer` passes through), and answers `/help` with `helpText(commands)`.
|
|
271
|
+
|
|
272
|
+
```ts
|
|
273
|
+
import { commandHook } from "@theokit/gateway";
|
|
274
|
+
|
|
275
|
+
const hook = commandHook([
|
|
276
|
+
{ name: "new", description: "Start a new chat", arg: "none", run: () => ({ block: true, message: "Reset." }) },
|
|
277
|
+
{ name: "think", description: "Set thinking", usage: "/think off|low|medium|high", run: (_e, arg) => ({ block: true, message: `think=${arg}` }) },
|
|
278
|
+
]);
|
|
279
|
+
```
|
|
280
|
+
|
|
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
|
+
|
|
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
|
+
|
|
311
|
+
## Agent bindings
|
|
312
|
+
|
|
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`.
|
|
314
|
+
|
|
315
|
+
```ts
|
|
316
|
+
import { bindingStrategy, createAgentBindings, defaultStrategy, SessionRouter } from "@theokit/gateway";
|
|
317
|
+
|
|
318
|
+
const bindings = createAgentBindings({
|
|
319
|
+
defaultAgent: "personal",
|
|
320
|
+
agents: ["personal", "support"],
|
|
321
|
+
rules: [{ agent: "support", platform: "slack" }],
|
|
322
|
+
});
|
|
323
|
+
const router = new SessionRouter(bindingStrategy(bindings, defaultStrategy));
|
|
324
|
+
```
|
|
325
|
+
|
|
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.
|
|
327
|
+
|
|
249
328
|
## Architecture (5 pieces)
|
|
250
329
|
|
|
251
330
|
| Module | Responsibility |
|
|
@@ -321,6 +400,23 @@ if (connected.length === 0) throw new Error("no channel connected");
|
|
|
321
400
|
for (const { platform, reason } of failed) console.error(`${platform} did not connect: ${reason}`);
|
|
322
401
|
```
|
|
323
402
|
|
|
403
|
+
To build channels from environment variables, give each descriptor field an `env` name and read it
|
|
404
|
+
with `configFromEnv`. It trims values, treats empty or whitespace as unset, lists unset required
|
|
405
|
+
variables by full name in `missing`, and returns secret values in `secrets` for a log mask.
|
|
406
|
+
`selectVariant` picks one of a descriptor's `variants` (for example a WhatsApp backend).
|
|
407
|
+
|
|
408
|
+
```typescript
|
|
409
|
+
import { configFromEnv, createChannels, selectVariant } from "@theokit/gateway";
|
|
410
|
+
|
|
411
|
+
const descriptor = selectVariant(whatsappChannel, process.env.APP_WHATSAPP_BACKEND);
|
|
412
|
+
const { config, missing, secrets } = configFromEnv(descriptor, process.env, "APP_");
|
|
413
|
+
if (missing.length > 0) console.error(`skipped: set ${missing.join(", ")}`);
|
|
414
|
+
else {
|
|
415
|
+
const { adapters } = createChannels([{ descriptor, config }]);
|
|
416
|
+
// pass `secrets` to your log mask
|
|
417
|
+
}
|
|
418
|
+
```
|
|
419
|
+
|
|
324
420
|
- `createChannels` rejects an entry whose required field is absent, `null` or `""` with a
|
|
325
421
|
`GatewayConfigurationError` coded `missing_required_config` that names the keys, and reports a
|
|
326
422
|
configuration error thrown by `create` the same way. Any other error propagates. It performs no
|
|
@@ -332,6 +428,15 @@ for (const { platform, reason } of failed) console.error(`${platform} did not co
|
|
|
332
428
|
`connectFailure: "isolate"` (under `"rollback"` the start still rejects). A `connect()` that
|
|
333
429
|
returns `false`, or throws a 401/403 credential error, is reported once and never retried.
|
|
334
430
|
`start()` called again afterwards returns the updated `connected` and `failed`.
|
|
431
|
+
- `connectTimeoutMs` (under `"isolate"`) gives up on one adapter's `connect()` after that many ms:
|
|
432
|
+
it is reported `timed_out` in `StartResult.failed`, never wired for inbound, and disconnected if
|
|
433
|
+
its `connect()` resolves `true` later. With `reconnect` it is retried like a transient failure.
|
|
434
|
+
`onAdapterState(platform, state, reason?)` fires as each adapter becomes `connected`, `failed`,
|
|
435
|
+
`retrying` or `timed_out`, while `start()` may still be pending; `reason` is redacted. Both are
|
|
436
|
+
ignored under `"rollback"`. `secrets: [...]` masks those exact values (longest first) with
|
|
437
|
+
`[redacted]` in every reason and log line before `redactSecrets` runs (`maskSecrets` is exported).
|
|
438
|
+
- `runner.adapter(platform)` returns the registered adapter, connected or not, or `undefined`;
|
|
439
|
+
`runner.connected` is the live set of connected platforms, updated by retries and `stop()`.
|
|
335
440
|
- `connectFailure` defaults to `"rollback"`: one failed connect disconnects the adapters that did
|
|
336
441
|
connect and rejects `start()`, as before. Under `"isolate"`, `start()` resolves even when every
|
|
337
442
|
adapter failed, so check `connected` before you rely on the runner.
|
|
@@ -361,6 +466,45 @@ for (const { platform, reason } of failed) console.error(`${platform} did not co
|
|
|
361
466
|
`failed` under `"isolate"`. Acknowledging it loses the message, since the platform does not
|
|
362
467
|
redeliver an acknowledged request.
|
|
363
468
|
|
|
469
|
+
### Mounting webhooks in a Fetch server
|
|
470
|
+
|
|
471
|
+
`createWebhookHandler` routes `/webhooks/<platform>` for every `transport: "webhook"` channel. It
|
|
472
|
+
answers 404 for an unknown platform, 503 while the platform has not started, 405 for a method the
|
|
473
|
+
route does not take, 413 (with `connection: close`) past `maxBodyBytes` (default 1 MiB), 401 when
|
|
474
|
+
`verify` fails, 400 for a body that is not JSON or is `"malformed"`, and 503 for `"no_handler"`. A
|
|
475
|
+
descriptor with `webhook.handle` answers the request itself (method, URL and query included).
|
|
476
|
+
A throw gives 500 with no body and calls `onError(platform, error)`. `statusForDeliver(outcomes)`
|
|
477
|
+
maps `deliver()` outcomes to a status, worst wins.
|
|
478
|
+
|
|
479
|
+
```ts
|
|
480
|
+
import { createChannels, createWebhookHandler } from "@theokit/gateway";
|
|
481
|
+
|
|
482
|
+
const { channels } = createChannels(entries);
|
|
483
|
+
const handler = createWebhookHandler({
|
|
484
|
+
channels,
|
|
485
|
+
isStarted: (platform) => runnerStarted.has(platform),
|
|
486
|
+
onError: (platform, error) => log.error({ platform, error }),
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
Bun.serve({ port: 3000, fetch: handler });
|
|
490
|
+
```
|
|
491
|
+
|
|
492
|
+
### Is the sender id authenticated?
|
|
493
|
+
|
|
494
|
+
A descriptor can say whether `sender.id` is proven by the platform with `senderIdentity`:
|
|
495
|
+
`"authenticated"`, or `{ unauthenticated: "why it can be forged" }` for a channel such as email (the
|
|
496
|
+
From header) or SMS (the caller id), where the sender writes the id (CWE-290).
|
|
497
|
+
`isAuthenticatedSender(descriptor)` is true only for `"authenticated"`. A descriptor that does not
|
|
498
|
+
set the field is unknown, and unknown is treated as not authenticated (fail closed), so an app
|
|
499
|
+
that lets owners control an agent should refuse owner entries on such a channel.
|
|
500
|
+
|
|
501
|
+
```typescript
|
|
502
|
+
import { isAuthenticatedSender } from "@theokit/gateway";
|
|
503
|
+
import { telegramChannel } from "@theokit/gateway-telegram";
|
|
504
|
+
|
|
505
|
+
isAuthenticatedSender(telegramChannel); // true
|
|
506
|
+
```
|
|
507
|
+
|
|
364
508
|
## Receiving from a TheoKit app
|
|
365
509
|
|
|
366
510
|
Three repositories share this path. `theokit` owns the HTTP route and the signature check —
|