@theokit/gateway 0.25.0 → 0.27.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,5 +1,5 @@
1
+ import { verify, randomInt, randomBytes, randomUUID, createPublicKey } from 'crypto';
1
2
  import { Security } from '@theokit/sdk';
2
- import { randomInt, randomBytes, randomUUID } from 'crypto';
3
3
  import { readFileSync, mkdirSync, writeFileSync, renameSync } from 'fs';
4
4
  import { join } from 'path';
5
5
  import { mkdir, writeFile, chmod, rename, unlink, readFile } from 'fs/promises';
@@ -378,6 +378,81 @@ var BasePlatformAdapter = class _BasePlatformAdapter {
378
378
  }
379
379
  };
380
380
 
381
+ // src/adapter/send-error.ts
382
+ function parseRetryAfter(value, now) {
383
+ if (value == null) return void 0;
384
+ const v = value.trim();
385
+ if (/^\d+$/.test(v)) return Number(v) * 1e3;
386
+ if (!/[A-Za-z]/.test(v)) return void 0;
387
+ const at = Date.parse(v);
388
+ if (Number.isNaN(at)) return void 0;
389
+ return Math.max(0, at - now);
390
+ }
391
+ var STATUS_CODES = {
392
+ 429: "rate_limit",
393
+ 401: "auth_failed",
394
+ 403: "permission_denied",
395
+ 408: "timeout"
396
+ };
397
+ function codeForStatus(status) {
398
+ return STATUS_CODES[status] ?? (status >= 500 ? "server_error" : "platform_error");
399
+ }
400
+ function sendErrorFromHttp(status, message, options) {
401
+ if (!Number.isInteger(status) || status < 100 || status > 599) {
402
+ throw new RangeError(`status must be an integer in 100..599, got ${String(status)}`);
403
+ }
404
+ const code = codeForStatus(status);
405
+ const retryAfterMs = status === 429 ? parseRetryAfter(options?.retryAfter, (options?.now ?? Date.now)()) : void 0;
406
+ return {
407
+ ok: false,
408
+ error: {
409
+ code,
410
+ message,
411
+ ...retryAfterMs !== void 0 ? { retryAfterMs } : {},
412
+ ...options?.platformCode !== void 0 ? { platformCode: options.platformCode } : {}
413
+ }
414
+ };
415
+ }
416
+
417
+ // src/auth/token-cache.ts
418
+ function createTokenCache(options) {
419
+ const marginMs = options.marginMs ?? 6e4;
420
+ const defaultTtlS = options.defaultTtlS ?? 7200;
421
+ const now = options.now ?? Date.now;
422
+ let cached;
423
+ let pending;
424
+ let generation = 0;
425
+ const refresh = (signal) => {
426
+ const started = generation;
427
+ const run = (async () => {
428
+ const fetched = await options.fetchToken(signal);
429
+ const ttl = fetched.expiresInS !== void 0 && fetched.expiresInS > 0 ? fetched.expiresInS : defaultTtlS;
430
+ if (started === generation) {
431
+ cached = { value: fetched.value, expiresAt: now() + ttl * 1e3 };
432
+ }
433
+ return fetched.value;
434
+ })();
435
+ const tracked = run.finally(() => {
436
+ if (pending === tracked) pending = void 0;
437
+ });
438
+ pending = tracked;
439
+ return tracked;
440
+ };
441
+ return {
442
+ get(opts) {
443
+ if (opts?.force !== true && cached !== void 0 && cached.expiresAt - marginMs > now()) {
444
+ return Promise.resolve(cached.value);
445
+ }
446
+ return pending ?? refresh(opts?.signal);
447
+ },
448
+ clear() {
449
+ generation += 1;
450
+ cached = void 0;
451
+ pending = void 0;
452
+ }
453
+ };
454
+ }
455
+
381
456
  // src/text/seen-ids.ts
382
457
  var DEFAULT_LIMIT = 1e3;
383
458
  var SeenIds = class {
@@ -427,7 +502,6 @@ function decodeEntities(s) {
427
502
 
428
503
  // src/adapter/weixin-base.ts
429
504
  var REQUEST_TIMEOUT_MS = 3e4;
430
- var TOKEN_MARGIN_MS = 6e4;
431
505
  var defaultFetch = async (url, init) => {
432
506
  const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
433
507
  return { status: res.status, text: () => res.text() };
@@ -442,12 +516,13 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
442
516
  cfg;
443
517
  doFetch;
444
518
  connected = false;
445
- accessToken;
519
+ tokens;
446
520
  seen = new SeenIds();
447
521
  constructor(cfg) {
448
522
  super();
449
523
  this.cfg = cfg;
450
524
  this.doFetch = cfg.fetch ?? defaultFetch;
525
+ this.tokens = createTokenCache({ fetchToken: () => this.requestToken() });
451
526
  }
452
527
  async connect() {
453
528
  if (this.connected) return true;
@@ -463,7 +538,7 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
463
538
  }
464
539
  async disconnect() {
465
540
  this.connected = false;
466
- this.accessToken = void 0;
541
+ this.tokens.clear();
467
542
  }
468
543
  /** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */
469
544
  async sendText(out) {
@@ -525,21 +600,19 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
525
600
  if (outcome === "no_handler") return { status: 503, body: "", reason: "no handler subscribed" };
526
601
  return weixinAck(outcome);
527
602
  }
528
- async token(force) {
529
- const cached = this.accessToken;
530
- if (!force && cached !== void 0 && cached.expiresAt - TOKEN_MARGIN_MS > Date.now()) {
531
- return cached.value;
532
- }
603
+ token(force) {
604
+ return this.tokens.get({ force });
605
+ }
606
+ async requestToken() {
533
607
  const body = await this.call("GET", this.tokenPath());
534
608
  if (body.errcode !== void 0 && body.errcode !== 0) {
535
609
  throw new Error(`token answered error ${String(body.errcode)}: ${String(body.errmsg)}`);
536
610
  }
537
611
  if (!body.access_token) throw new Error("token answer has no access_token");
538
- this.accessToken = {
612
+ return {
539
613
  value: body.access_token,
540
- expiresAt: Date.now() + (body.expires_in ?? 7200) * 1e3
614
+ ...body.expires_in === void 0 ? {} : { expiresInS: body.expires_in }
541
615
  };
542
- return body.access_token;
543
616
  }
544
617
  async call(method, path, payload) {
545
618
  const res = await this.doFetch((this.cfg.apiBase ?? this.cfg.defaultBase) + path, {
@@ -555,6 +628,125 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
555
628
  }
556
629
  }
557
630
  };
631
+ var DEFAULT_REFETCH_FLOOR_MS = 6e4;
632
+ var READ_TIMEOUT_MS = 1e4;
633
+ function jwksKeySet(options) {
634
+ const doFetch = options.fetch ?? ((url, init) => fetch(url, init));
635
+ const now = options.now ?? Date.now;
636
+ const floor = options.unknownKidRefetchFloorMs ?? DEFAULT_REFETCH_FLOOR_MS;
637
+ const swr = options.staleWhileRevalidate ?? true;
638
+ let held;
639
+ let lastReadStartedAt = Number.NEGATIVE_INFINITY;
640
+ let reading;
641
+ let lastFailure = "no read has completed";
642
+ async function fetchKeys() {
643
+ const response = await doFetch(options.url, { signal: AbortSignal.timeout(READ_TIMEOUT_MS) });
644
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
645
+ const keys = parseKeys(await response.json());
646
+ return { keys, freshUntil: now() + maxAgeMs(response.headers.get("cache-control")) };
647
+ }
648
+ function read() {
649
+ if (reading) return reading;
650
+ lastReadStartedAt = now();
651
+ const current = fetchKeys().then(
652
+ (next) => {
653
+ held = next;
654
+ reading = void 0;
655
+ return void 0;
656
+ },
657
+ (error) => {
658
+ lastFailure = error instanceof Error ? error.message : String(error);
659
+ reading = void 0;
660
+ return lastFailure;
661
+ }
662
+ );
663
+ reading = current;
664
+ return current;
665
+ }
666
+ const mayRead = () => !reading && now() - lastReadStartedAt >= floor;
667
+ function answer(kid) {
668
+ const key = held?.keys.get(kid);
669
+ if (key) return key;
670
+ return held ? "unlisted" : { unavailable: lastFailure };
671
+ }
672
+ async function refreshListed(kid) {
673
+ const refresh = reading ?? (mayRead() ? read() : void 0);
674
+ if (refresh && !swr) await refresh;
675
+ return answer(kid);
676
+ }
677
+ async function refreshUnknown(kid) {
678
+ const refresh = reading ?? (mayRead() ? read() : void 0);
679
+ const failure = refresh ? await refresh : void 0;
680
+ if (failure && !held?.keys.has(kid)) return { unavailable: failure };
681
+ return answer(kid);
682
+ }
683
+ return {
684
+ async lookup(kid) {
685
+ const listed = held?.keys.get(kid);
686
+ if (!held || !listed) return refreshUnknown(kid);
687
+ if (now() < held.freshUntil) return listed;
688
+ return refreshListed(kid);
689
+ }
690
+ };
691
+ }
692
+ function parseKey(jwk) {
693
+ if (typeof jwk !== "object" || jwk === null) return void 0;
694
+ const { kid, kty, use } = jwk;
695
+ if (typeof kid !== "string" || kty !== "RSA" || use !== void 0 && use !== "sig") {
696
+ return void 0;
697
+ }
698
+ try {
699
+ return [kid, createPublicKey({ key: jwk, format: "jwk" })];
700
+ } catch {
701
+ return void 0;
702
+ }
703
+ }
704
+ function parseKeys(body) {
705
+ const list = body?.keys;
706
+ if (!Array.isArray(list)) throw new Error("the key set has no `keys` array");
707
+ const entries = list.map(parseKey).filter((e) => e !== void 0);
708
+ return new Map(entries);
709
+ }
710
+ function maxAgeMs(cacheControl) {
711
+ const match = /(?:^|,)\s*max-age=(\d+)/i.exec(cacheControl ?? "");
712
+ return match?.[1] ? Number(match[1]) * 1e3 : 0;
713
+ }
714
+ var BASE64URL = /^[A-Za-z0-9_-]+$/;
715
+ function decodeJwt(token) {
716
+ const parts = token.split(".");
717
+ if (parts.length !== 3) return void 0;
718
+ const [h, p, s] = parts;
719
+ if (![h, p, s].every((part) => BASE64URL.test(part))) return void 0;
720
+ const header = jsonObject(h);
721
+ const payload = jsonObject(p);
722
+ if (!header || !payload) return void 0;
723
+ return { header, payload, signingInput: `${h}.${p}`, signature: Buffer.from(s, "base64url") };
724
+ }
725
+ function jsonObject(segment) {
726
+ try {
727
+ const value = JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
728
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
729
+ } catch {
730
+ return void 0;
731
+ }
732
+ }
733
+ async function verifyRs256Jwt(token, keys) {
734
+ const jwt = decodeJwt(token);
735
+ if (!jwt) return { ok: false, reason: "malformed" };
736
+ if (jwt.header.alg !== "RS256") return { ok: false, reason: "unsupported_alg" };
737
+ const kid = jwt.header.kid;
738
+ if (typeof kid !== "string" || kid === "") return { ok: false, reason: "malformed" };
739
+ const found = await keys.lookup(kid);
740
+ if (found === "unlisted") return { ok: false, reason: "unknown_kid" };
741
+ if ("unavailable" in found) return { ok: false, reason: "keys_unavailable" };
742
+ let valid = false;
743
+ try {
744
+ valid = verify("RSA-SHA256", Buffer.from(jwt.signingInput), found, jwt.signature);
745
+ } catch {
746
+ valid = false;
747
+ }
748
+ return valid ? { ok: true, header: jwt.header, payload: jwt.payload } : { ok: false, reason: "bad_signature" };
749
+ }
558
750
 
559
751
  // src/errors/config-error.ts
560
752
  var GatewayConfigurationError = class extends Error {
@@ -1248,6 +1440,56 @@ var HookExecutor = class {
1248
1440
  }
1249
1441
  };
1250
1442
 
1443
+ // src/runner/reconnect-backoff.ts
1444
+ function checkNonNegativeFinite(name, value) {
1445
+ if (!Number.isFinite(value) || value < 0) {
1446
+ throw new RangeError(`${name} must be a finite number >= 0, got ${value}`);
1447
+ }
1448
+ }
1449
+ var ReconnectBackoff = class {
1450
+ initialDelayMs;
1451
+ maxDelayMs;
1452
+ factor;
1453
+ maxAttempts;
1454
+ stableAfterMs;
1455
+ now;
1456
+ attempts = 0;
1457
+ openedAt;
1458
+ constructor(options = {}) {
1459
+ this.initialDelayMs = options.initialDelayMs ?? 1e3;
1460
+ this.maxDelayMs = options.maxDelayMs ?? 6e4;
1461
+ this.factor = options.factor ?? 2;
1462
+ this.maxAttempts = options.maxAttempts;
1463
+ this.stableAfterMs = options.stableAfterMs ?? 6e4;
1464
+ this.now = options.now ?? Date.now;
1465
+ checkNonNegativeFinite("initialDelayMs", this.initialDelayMs);
1466
+ checkNonNegativeFinite("maxDelayMs", this.maxDelayMs);
1467
+ if (!(this.factor >= 1) || !Number.isFinite(this.factor)) {
1468
+ throw new RangeError(`factor must be a finite number >= 1, got ${this.factor}`);
1469
+ }
1470
+ }
1471
+ /** Call when the connection opens. */
1472
+ opened() {
1473
+ this.openedAt = this.now();
1474
+ }
1475
+ /** Delay before the next attempt; `undefined` once `maxAttempts` is spent. Resets first if the last connection was stable. */
1476
+ nextDelayMs() {
1477
+ if (this.openedAt !== void 0) {
1478
+ if (this.now() - this.openedAt >= this.stableAfterMs) this.attempts = 0;
1479
+ this.openedAt = void 0;
1480
+ }
1481
+ if (this.maxAttempts !== void 0 && this.attempts >= this.maxAttempts) return void 0;
1482
+ const delay = Math.min(this.initialDelayMs * this.factor ** this.attempts, this.maxDelayMs);
1483
+ this.attempts += 1;
1484
+ return delay;
1485
+ }
1486
+ /** Back to the initial delay. */
1487
+ reset() {
1488
+ this.attempts = 0;
1489
+ this.openedAt = void 0;
1490
+ }
1491
+ };
1492
+
1251
1493
  // src/runner/gateway-runner.ts
1252
1494
  var DEFAULT_DRAIN_MS = 1e4;
1253
1495
  var TYPING_RENEW_MS = 4e3;
@@ -1399,27 +1641,28 @@ var GatewayRunner = class {
1399
1641
  connected: result.connected.map((a) => a.platform),
1400
1642
  failed: result.failed
1401
1643
  };
1402
- for (const adapter of result.retryable) this.scheduleReconnect(adapter, 1);
1644
+ for (const adapter of result.retryable) {
1645
+ const policy = this.opts.reconnect;
1646
+ if (policy === void 0) break;
1647
+ this.scheduleReconnect(adapter, 1, new ReconnectBackoff(policy));
1648
+ }
1403
1649
  return this.startResult;
1404
1650
  }
1405
1651
  /** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
1406
- scheduleReconnect(adapter, attempt) {
1652
+ scheduleReconnect(adapter, attempt, backoff) {
1407
1653
  const policy = this.opts.reconnect;
1408
1654
  if (policy === void 0 || this.stopped) return;
1409
- if (policy.maxAttempts !== void 0 && attempt > policy.maxAttempts) {
1655
+ const delay = backoff.nextDelayMs();
1656
+ if (delay === void 0) {
1410
1657
  process.stderr.write(
1411
1658
  `[gateway] adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts
1412
1659
  `
1413
1660
  );
1414
1661
  return;
1415
1662
  }
1416
- const delay = Math.min(
1417
- (policy.initialDelayMs ?? 1e3) * (policy.factor ?? 2) ** (attempt - 1),
1418
- policy.maxDelayMs ?? 6e4
1419
- );
1420
1663
  const timer = setTimeout(() => {
1421
1664
  this.retryTimers.delete(timer);
1422
- void this.reconnectOnce(adapter, attempt);
1665
+ void this.reconnectOnce(adapter, attempt, backoff);
1423
1666
  }, delay);
1424
1667
  timer.unref();
1425
1668
  this.retryTimers.add(timer);
@@ -1429,7 +1672,7 @@ var GatewayRunner = class {
1429
1672
  );
1430
1673
  this.emitState(adapter.platform, "retrying", `reconnect attempt ${attempt} in ${delay}ms`);
1431
1674
  }
1432
- async reconnectOnce(adapter, attempt) {
1675
+ async reconnectOnce(adapter, attempt, backoff) {
1433
1676
  if (this.stopped) return;
1434
1677
  try {
1435
1678
  if (await adapter.connect()) {
@@ -1475,7 +1718,7 @@ var GatewayRunner = class {
1475
1718
  `
1476
1719
  );
1477
1720
  }
1478
- this.scheduleReconnect(adapter, attempt + 1);
1721
+ this.scheduleReconnect(adapter, attempt + 1, backoff);
1479
1722
  }
1480
1723
  /**
1481
1724
  * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
@@ -2145,30 +2388,60 @@ function lineEndFrom(text, cut, bound) {
2145
2388
  while (at < text.length && at <= bound && !isLineEnd2(text[at])) at += 1;
2146
2389
  return at;
2147
2390
  }
2148
- function rowSafeCut2(text, partStart, cut, partLimit) {
2391
+ function advance(text, from, count, codepoint) {
2392
+ if (!codepoint) return Math.min(from + count, text.length);
2393
+ let at = from;
2394
+ for (let left = count; left > 0 && at < text.length; left -= 1) {
2395
+ at += (text.codePointAt(at) ?? 0) > 65535 ? 2 : 1;
2396
+ }
2397
+ return at;
2398
+ }
2399
+ function rowSafeCut2(text, partStart, cut, partLimit, codepoint) {
2149
2400
  const lineStart = lineStartBefore(text, cut, partStart);
2150
2401
  if (lineStart <= partStart || lineStart === cut) return cut;
2151
2402
  if (isLineEnd2(text[cut]) || !startsTableRow2(text, lineStart)) return cut;
2152
- const lineEnd = lineEndFrom(text, cut, lineStart + partLimit);
2153
- return lineEnd - lineStart <= partLimit ? lineStart : cut;
2403
+ const bound = advance(text, lineStart, partLimit, codepoint);
2404
+ return lineEndFrom(text, cut, bound) <= bound ? lineStart : cut;
2154
2405
  }
2155
- function graphemeCut(segments, start, partLimit) {
2156
- const cut = start + partLimit;
2157
- const segment = segments.containing(cut);
2158
- if (segment === void 0 || segment.index >= cut) return cut;
2406
+ function graphemeCut(segments, start, limitCut) {
2407
+ const segment = segments.containing(limitCut);
2408
+ if (segment === void 0 || segment.index >= limitCut) return limitCut;
2159
2409
  return segment.index > start ? segment.index : segment.index + segment.segment.length;
2160
2410
  }
2161
- function splitKeepingRows(text, partLimit) {
2411
+ function readUnit(partLimit, options) {
2412
+ const unit = options.unit ?? "utf16";
2413
+ if (unit !== "utf16" && unit !== "codepoint") {
2414
+ throw new RangeError(
2415
+ `splitKeepingRows: unit must be "utf16" or "codepoint", got ${String(unit)}`
2416
+ );
2417
+ }
2418
+ if (unit === "codepoint" && !(Number.isInteger(partLimit) && partLimit > 0)) {
2419
+ throw new RangeError(
2420
+ `splitKeepingRows: partLimit must be a positive integer, got ${partLimit}`
2421
+ );
2422
+ }
2423
+ return unit === "codepoint";
2424
+ }
2425
+ function splitKeepingRows(text, partLimit, options = {}) {
2426
+ const codepoint = readUnit(partLimit, options);
2162
2427
  const segments = new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(text);
2163
2428
  const parts = [];
2164
2429
  let start = 0;
2165
- while (text.length - start > partLimit) {
2166
- const cut = rowSafeCut2(text, start, graphemeCut(segments, start, partLimit), partLimit);
2430
+ let limitCut = advance(text, start, partLimit, codepoint);
2431
+ while (limitCut < text.length) {
2432
+ const grapheme = graphemeCut(segments, start, limitCut);
2433
+ if (codepoint && grapheme > limitCut) {
2434
+ throw new RangeError(
2435
+ `splitKeepingRows: a grapheme at offset ${start} is longer than ${partLimit} code points`
2436
+ );
2437
+ }
2438
+ const cut = rowSafeCut2(text, start, grapheme, partLimit, codepoint);
2167
2439
  if (cut <= start) {
2168
2440
  throw new RangeError(`splitKeepingRows: no progress at offset ${start} of ${text.length}`);
2169
2441
  }
2170
2442
  parts.push(text.slice(start, cut));
2171
2443
  start = cut;
2444
+ limitCut = advance(text, start, partLimit, codepoint);
2172
2445
  }
2173
2446
  if (start < text.length) parts.push(text.slice(start));
2174
2447
  return parts;
@@ -2431,6 +2704,6 @@ async function dispatch(webhook, adapter, request) {
2431
2704
  return runDefault(webhook, adapter, request);
2432
2705
  }
2433
2706
 
2434
- export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
2707
+ export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, ReconnectBackoff, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createTokenCache, createWebhookHandler, decodeJwt, defaultStrategy, helpText, isAuthenticatedSender, jwksKeySet, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, sendErrorFromHttp, senderKey, splitKeepingRows, statusForDeliver, toDialect, verifyRs256Jwt, withMediaUnderstanding };
2435
2708
  //# sourceMappingURL=index.js.map
2436
2709
  //# sourceMappingURL=index.js.map