@theokit/gateway 0.20.0 → 0.22.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 CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.22.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 963a0ff: `@theokit/gateway` exports `channelConfigReaders(prefix)`, the config readers (`invalid`, `isAbsent`, `readString`, `requiredString`, `readBoolean`, `readFunction`) that channel packages each copied. `@theokit/gateway-line` uses them and raises its `@theokit/gateway` peer floor to `>=0.21.0`.
8
+ - 4e7c21b: Add `CredentialStore` and `createFileCredentialStore` to `@theokit/gateway`, and `credentialStore` / `credentialKey` to `XAdapterOptions` so a rotated X refresh token survives a restart.
9
+ - a12e04c: Raise the `@theokit/gateway` peer floor of `@theokit/gateway-x` to 0.20.0 and bump the workspace `@theokit/gateway` version to match.
10
+
11
+ ### Patch Changes
12
+
13
+ - 6c60bb6: Tidy the `configFromEnv` internals and cover more edge cases in its tests. No behaviour change.
14
+ - 2c0f560: `createChannels` now builds the environment variable names in its missing-config rejections with the same internal `envVarName` helper as `configFromEnv`, so both report the same full names.
15
+ - 8b46fb4: `createChannels` names the missing environment variable (with the optional `ChannelEntry.envPrefix`) instead of the config key in `missing_required_config` rejections.
16
+
17
+ ## 0.21.0
18
+
19
+ ### Minor Changes
20
+
21
+ - 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.
22
+
23
+ ### Patch Changes
24
+
25
+ - 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`.
26
+
3
27
  ## 0.20.0
4
28
 
5
29
  ### Minor Changes
package/README.md CHANGED
@@ -325,6 +325,37 @@ const router = new SessionRouter(bindingStrategy(bindings, defaultStrategy));
325
325
 
326
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
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
+
351
+ ## Keeping a credential across restarts
352
+
353
+ `CredentialStore` is a `get(key)` / `set(key, value)` interface. `createFileCredentialStore(dir)`
354
+ keeps one file per key under `dir` (mode 0600, written to a temp file and renamed). Keys match
355
+ `[A-Za-z0-9._:-]+`, otherwise `set` and `get` throw `GatewayConfigurationError` with code
356
+ `invalid_credential_key`. `get` returns `undefined` for a missing key; any other read error throws
357
+ code `credential_store_unreadable`. `@theokit/gateway-x` uses it to keep a rotated refresh token.
358
+
328
359
  ## Architecture (5 pieces)
329
360
 
330
361
  | Module | Responsibility |
@@ -386,6 +417,8 @@ const { adapters, rejected } = createChannels([
386
417
  },
387
418
  ]);
388
419
  for (const { platform, error } of rejected) console.error(`${platform}: ${error.message}`);
420
+ // A rejection names each missing field's environment variable when the descriptor declares `env`.
421
+ // Pass `envPrefix` (the prefix you give `configFromEnv`) on an entry for the full variable name.
389
422
 
390
423
  const runner = new GatewayRunner({
391
424
  adapters,
@@ -412,13 +445,13 @@ const descriptor = selectVariant(whatsappChannel, process.env.APP_WHATSAPP_BACKE
412
445
  const { config, missing, secrets } = configFromEnv(descriptor, process.env, "APP_");
413
446
  if (missing.length > 0) console.error(`skipped: set ${missing.join(", ")}`);
414
447
  else {
415
- const { adapters } = createChannels([{ descriptor, config }]);
448
+ const { adapters } = createChannels([{ descriptor, config, envPrefix: "APP_" }]);
416
449
  // pass `secrets` to your log mask
417
450
  }
418
451
  ```
419
452
 
420
453
  - `createChannels` rejects an entry whose required field is absent, `null` or `""` with a
421
- `GatewayConfigurationError` coded `missing_required_config` that names the keys, and reports a
454
+ `GatewayConfigurationError` coded `missing_required_config` that names the missing variables (`envPrefix` + the field's `env`, or the config key when the field has no `env`), and reports a
422
455
  configuration error thrown by `create` the same way. Any other error propagates. It performs no
423
456
  network call.
424
457
  - `createChannels` also returns `channels`: each built adapter paired with the descriptor that built it, in the order of `adapters`.
package/dist/index.cjs CHANGED
@@ -4,6 +4,7 @@ var sdk = require('@theokit/sdk');
4
4
  var crypto = require('crypto');
5
5
  var fs = require('fs');
6
6
  var path = require('path');
7
+ var promises = require('fs/promises');
7
8
 
8
9
  // src/text/fence.ts
9
10
  var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
@@ -557,11 +558,6 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
557
558
  }
558
559
  };
559
560
 
560
- // src/channel/channel-descriptor.ts
561
- function isAuthenticatedSender(descriptor) {
562
- return descriptor.senderIdentity === "authenticated";
563
- }
564
-
565
561
  // src/errors/config-error.ts
566
562
  var GatewayConfigurationError = class extends Error {
567
563
  name = "GatewayConfigurationError";
@@ -578,18 +574,63 @@ var GatewayConfigurationError = class extends Error {
578
574
  }
579
575
  };
580
576
 
577
+ // src/channel/channel-config-readers.ts
578
+ function channelConfigReaders(prefix, createError = (options) => new GatewayConfigurationError(prefix, options)) {
579
+ const invalid2 = (key, expected) => createError({
580
+ code: "invalid_config",
581
+ message: `${prefix}: config.${key} must be ${expected}`,
582
+ detail: key
583
+ });
584
+ const isAbsent2 = (value) => value === void 0 || value === null || value === "";
585
+ const readString = (config, key) => {
586
+ const value = config[key];
587
+ if (isAbsent2(value)) return void 0;
588
+ if (typeof value !== "string") throw invalid2(key, "a string");
589
+ return value;
590
+ };
591
+ return {
592
+ invalid: invalid2,
593
+ isAbsent: isAbsent2,
594
+ readString,
595
+ requiredString(config, key) {
596
+ const value = config[key];
597
+ if (typeof value !== "string" || value === "") throw invalid2(key, "a non-empty string");
598
+ return value;
599
+ },
600
+ readBoolean(config, key) {
601
+ const value = config[key];
602
+ if (isAbsent2(value)) return void 0;
603
+ if (typeof value !== "boolean") throw invalid2(key, "a boolean");
604
+ return value;
605
+ },
606
+ readFunction(config, key) {
607
+ const value = config[key];
608
+ if (isAbsent2(value)) return void 0;
609
+ if (typeof value !== "function") throw invalid2(key, "a function");
610
+ return value;
611
+ }
612
+ };
613
+ }
614
+
615
+ // src/channel/channel-descriptor.ts
616
+ function isAuthenticatedSender(descriptor) {
617
+ return descriptor.senderIdentity === "authenticated";
618
+ }
619
+
581
620
  // src/channel/config-from-env.ts
621
+ function envVarName(field, prefix = "") {
622
+ return field.env === void 0 ? void 0 : prefix + field.env;
623
+ }
582
624
  function readValue(env, name) {
583
- const value = env[name]?.trim();
584
- return value ? value : void 0;
625
+ return env[name]?.trim() || void 0;
585
626
  }
586
627
  function configFromEnv(descriptor, env, prefix = "") {
587
628
  const config = {};
588
629
  const missing = [];
589
630
  const secrets = [];
590
631
  for (const field of descriptor.config) {
591
- if (field.env === void 0) continue;
592
- const name = prefix + field.env;
632
+ const name = envVarName(field, prefix);
633
+ if (name === void 0) continue;
593
634
  const value = readValue(env, name);
594
635
  if (value === void 0) {
595
636
  if (field.required) missing.push(name);
@@ -631,7 +672,10 @@ function isAbsent(value) {
631
672
  return value === void 0 || value === null || value === "";
632
673
  }
633
674
  function missingRequiredKeys(entry, values) {
634
- return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => field.key);
675
+ return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => {
676
+ const name = envVarName(field, entry.envPrefix);
677
+ return name === void 0 ? field.key : `${field.key} (env ${name})`;
678
+ });
635
679
  }
636
680
  function refused(platform, code, reason) {
637
681
  return {
@@ -1697,6 +1741,46 @@ function withMediaUnderstanding(handler, options) {
1697
1741
  return handler(wrapped, ctx);
1698
1742
  };
1699
1743
  }
1744
+ var KEY_PATTERN = /^[A-Za-z0-9._:-]+$(?![\s\S])/;
1745
+ function fileFor(dir, key) {
1746
+ if (!KEY_PATTERN.test(key) || key === "." || key === "..") {
1747
+ throw new GatewayConfigurationError("gateway", {
1748
+ code: "invalid_credential_key",
1749
+ message: `gateway: invalid_credential_key (keys match [A-Za-z0-9._:-]+): ${JSON.stringify(key)}`
1750
+ });
1751
+ }
1752
+ return path.join(dir, key.replaceAll(":", "%3A"));
1753
+ }
1754
+ function createFileCredentialStore(dir) {
1755
+ return {
1756
+ async get(key) {
1757
+ const path = fileFor(dir, key);
1758
+ try {
1759
+ return await promises.readFile(path, "utf8");
1760
+ } catch (err) {
1761
+ if (err.code === "ENOENT") return void 0;
1762
+ throw new GatewayConfigurationError("gateway", {
1763
+ code: "credential_store_unreadable",
1764
+ message: `gateway: credential_store_unreadable: ${path}`,
1765
+ detail: err instanceof Error ? err.message : String(err)
1766
+ });
1767
+ }
1768
+ },
1769
+ async set(key, value) {
1770
+ const path = fileFor(dir, key);
1771
+ await promises.mkdir(dir, { recursive: true });
1772
+ const tmp = `${path}.${crypto.randomBytes(6).toString("hex")}.tmp`;
1773
+ try {
1774
+ await promises.writeFile(tmp, value, { mode: 384 });
1775
+ await promises.chmod(tmp, 384);
1776
+ await promises.rename(tmp, path);
1777
+ } catch (err) {
1778
+ await promises.unlink(tmp).catch(() => void 0);
1779
+ throw err;
1780
+ }
1781
+ }
1782
+ };
1783
+ }
1700
1784
 
1701
1785
  // src/session/router.ts
1702
1786
  function defaultStrategy(event) {
@@ -1789,6 +1873,49 @@ function bindingStrategy(bindings, inner) {
1789
1873
  return (event) => `${sanitize(bindings.agentFor(event))}-${inner(event)}`;
1790
1874
  }
1791
1875
 
1876
+ // src/session/scoped-strategy.ts
1877
+ var join3 = (...segments) => segments.map(sanitize).join("-");
1878
+ function invalid(message, detail) {
1879
+ return new GatewayConfigurationError("gateway", {
1880
+ code: "invalid_session_scope",
1881
+ message: `gateway: invalid_session_scope: ${message}`,
1882
+ ...detail === void 0 ? {} : { detail }
1883
+ });
1884
+ }
1885
+ function scopedStrategy(options) {
1886
+ const { dmScope, peerLinks, accountLabel, groupScope = "channel" } = options;
1887
+ if (dmScope === "per-account-channel-peer" && (accountLabel === void 0 || accountLabel === "")) {
1888
+ throw invalid("per-account-channel-peer requires a non-empty accountLabel", "accountLabel");
1889
+ }
1890
+ if (peerLinks !== void 0) {
1891
+ for (const [from, peer] of peerLinks) {
1892
+ if (peer === "") throw invalid(`empty peer name for ${from}`, from);
1893
+ }
1894
+ }
1895
+ const dmKey = (platform, senderId) => {
1896
+ switch (dmScope) {
1897
+ case "main":
1898
+ return "_m-dm";
1899
+ case "per-peer": {
1900
+ const peer = peerLinks?.get(`${platform}:${senderId}`);
1901
+ return peer === void 0 ? join3(platform, "dm", senderId) : `_p-dm-${sanitize(peer)}`;
1902
+ }
1903
+ case "per-channel-peer":
1904
+ return join3(platform, "dm", senderId);
1905
+ case "per-account-channel-peer":
1906
+ return join3(platform, "dm", accountLabel ?? "", senderId);
1907
+ }
1908
+ };
1909
+ return (event) => {
1910
+ const { platform, channel, sender } = event;
1911
+ if (channel.type === "dm") return dmKey(platform, sender.id);
1912
+ if (channel.type === "thread" && channel.topicId !== void 0) {
1913
+ return join3(platform, "tpc", channel.id, channel.topicId);
1914
+ }
1915
+ return groupScope === "channel-sender" ? join3(platform, "grp", channel.id, sender.id) : join3(platform, "grp", channel.id);
1916
+ };
1917
+ }
1918
+
1792
1919
  // src/text/chunk.ts
1793
1920
  function searchBoundary(remaining, window, boundaries) {
1794
1921
  let cut = window;
@@ -2280,6 +2407,7 @@ exports.SeenIds = SeenIds;
2280
2407
  exports.SessionRouter = SessionRouter;
2281
2408
  exports.WeixinAdapterBase = WeixinAdapterBase;
2282
2409
  exports.bindingStrategy = bindingStrategy;
2410
+ exports.channelConfigReaders = channelConfigReaders;
2283
2411
  exports.channelRendering = channelRendering;
2284
2412
  exports.chunkByGrapheme = chunkByGrapheme;
2285
2413
  exports.chunkText = chunkText;
@@ -2288,6 +2416,7 @@ exports.configFromEnv = configFromEnv;
2288
2416
  exports.createAccessPolicyHook = createAccessPolicyHook;
2289
2417
  exports.createAgentBindings = createAgentBindings;
2290
2418
  exports.createChannels = createChannels;
2419
+ exports.createFileCredentialStore = createFileCredentialStore;
2291
2420
  exports.createFilePairingStore = createFilePairingStore;
2292
2421
  exports.createWebhookHandler = createWebhookHandler;
2293
2422
  exports.defaultStrategy = defaultStrategy;
@@ -2302,6 +2431,7 @@ exports.parseFlatXml = parseFlatXml;
2302
2431
  exports.rawBodyCapture = rawBodyCapture;
2303
2432
  exports.redactSecrets = redactSecrets;
2304
2433
  exports.scanFences = scanFences;
2434
+ exports.scopedStrategy = scopedStrategy;
2305
2435
  exports.selectVariant = selectVariant;
2306
2436
  exports.senderKey = senderKey;
2307
2437
  exports.splitKeepingRows = splitKeepingRows;