@theokit/gateway 0.21.0 → 0.22.1

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,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.22.1
4
+
5
+ ### Patch Changes
6
+
7
+ - b28c508: Raise the `@theokit/sdk` peer floor from `2.18.0` to `4.62.0`: `@theokit/sdk@2.18.0` publishes declarations that reference names it never defines, so a consumer at the old floor failed declaration checking (#584).
8
+
9
+ ## 0.22.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 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`.
14
+ - 4e7c21b: Add `CredentialStore` and `createFileCredentialStore` to `@theokit/gateway`, and `credentialStore` / `credentialKey` to `XAdapterOptions` so a rotated X refresh token survives a restart.
15
+ - a12e04c: Raise the `@theokit/gateway` peer floor of `@theokit/gateway-x` to 0.20.0 and bump the workspace `@theokit/gateway` version to match.
16
+
17
+ ### Patch Changes
18
+
19
+ - 6c60bb6: Tidy the `configFromEnv` internals and cover more edge cases in its tests. No behaviour change.
20
+ - 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.
21
+ - 8b46fb4: `createChannels` names the missing environment variable (with the optional `ChannelEntry.envPrefix`) instead of the config key in `missing_required_config` rejections.
22
+
3
23
  ## 0.21.0
4
24
 
5
25
  ### Minor Changes
package/README.md CHANGED
@@ -348,6 +348,14 @@ const router = new SessionRouter(
348
348
 
349
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
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
+
351
359
  ## Architecture (5 pieces)
352
360
 
353
361
  | Module | Responsibility |
@@ -437,13 +445,13 @@ const descriptor = selectVariant(whatsappChannel, process.env.APP_WHATSAPP_BACKE
437
445
  const { config, missing, secrets } = configFromEnv(descriptor, process.env, "APP_");
438
446
  if (missing.length > 0) console.error(`skipped: set ${missing.join(", ")}`);
439
447
  else {
440
- const { adapters } = createChannels([{ descriptor, config }]);
448
+ const { adapters } = createChannels([{ descriptor, config, envPrefix: "APP_" }]);
441
449
  // pass `secrets` to your log mask
442
450
  }
443
451
  ```
444
452
 
445
453
  - `createChannels` rejects an entry whose required field is absent, `null` or `""` with a
446
- `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
447
455
  configuration error thrown by `create` the same way. Any other error propagates. It performs no
448
456
  network call.
449
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,9 +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(
635
- (field) => field.env === void 0 ? field.key : `${field.key} (env ${(entry.envPrefix ?? "") + field.env})`
636
- );
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
+ });
637
679
  }
638
680
  function refused(platform, code, reason) {
639
681
  return {
@@ -1699,6 +1741,46 @@ function withMediaUnderstanding(handler, options) {
1699
1741
  return handler(wrapped, ctx);
1700
1742
  };
1701
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
+ }
1702
1784
 
1703
1785
  // src/session/router.ts
1704
1786
  function defaultStrategy(event) {
@@ -1792,7 +1874,7 @@ function bindingStrategy(bindings, inner) {
1792
1874
  }
1793
1875
 
1794
1876
  // src/session/scoped-strategy.ts
1795
- var join2 = (...segments) => segments.map(sanitize).join("-");
1877
+ var join3 = (...segments) => segments.map(sanitize).join("-");
1796
1878
  function invalid(message, detail) {
1797
1879
  return new GatewayConfigurationError("gateway", {
1798
1880
  code: "invalid_session_scope",
@@ -1816,21 +1898,21 @@ function scopedStrategy(options) {
1816
1898
  return "_m-dm";
1817
1899
  case "per-peer": {
1818
1900
  const peer = peerLinks?.get(`${platform}:${senderId}`);
1819
- return peer === void 0 ? join2(platform, "dm", senderId) : `_p-dm-${sanitize(peer)}`;
1901
+ return peer === void 0 ? join3(platform, "dm", senderId) : `_p-dm-${sanitize(peer)}`;
1820
1902
  }
1821
1903
  case "per-channel-peer":
1822
- return join2(platform, "dm", senderId);
1904
+ return join3(platform, "dm", senderId);
1823
1905
  case "per-account-channel-peer":
1824
- return join2(platform, "dm", accountLabel ?? "", senderId);
1906
+ return join3(platform, "dm", accountLabel ?? "", senderId);
1825
1907
  }
1826
1908
  };
1827
1909
  return (event) => {
1828
1910
  const { platform, channel, sender } = event;
1829
1911
  if (channel.type === "dm") return dmKey(platform, sender.id);
1830
1912
  if (channel.type === "thread" && channel.topicId !== void 0) {
1831
- return join2(platform, "tpc", channel.id, channel.topicId);
1913
+ return join3(platform, "tpc", channel.id, channel.topicId);
1832
1914
  }
1833
- return groupScope === "channel-sender" ? join2(platform, "grp", channel.id, sender.id) : join2(platform, "grp", channel.id);
1915
+ return groupScope === "channel-sender" ? join3(platform, "grp", channel.id, sender.id) : join3(platform, "grp", channel.id);
1834
1916
  };
1835
1917
  }
1836
1918
 
@@ -2325,6 +2407,7 @@ exports.SeenIds = SeenIds;
2325
2407
  exports.SessionRouter = SessionRouter;
2326
2408
  exports.WeixinAdapterBase = WeixinAdapterBase;
2327
2409
  exports.bindingStrategy = bindingStrategy;
2410
+ exports.channelConfigReaders = channelConfigReaders;
2328
2411
  exports.channelRendering = channelRendering;
2329
2412
  exports.chunkByGrapheme = chunkByGrapheme;
2330
2413
  exports.chunkText = chunkText;
@@ -2333,6 +2416,7 @@ exports.configFromEnv = configFromEnv;
2333
2416
  exports.createAccessPolicyHook = createAccessPolicyHook;
2334
2417
  exports.createAgentBindings = createAgentBindings;
2335
2418
  exports.createChannels = createChannels;
2419
+ exports.createFileCredentialStore = createFileCredentialStore;
2336
2420
  exports.createFilePairingStore = createFilePairingStore;
2337
2421
  exports.createWebhookHandler = createWebhookHandler;
2338
2422
  exports.defaultStrategy = defaultStrategy;