@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/CHANGELOG.md +19 -0
- package/README.md +72 -1
- package/dist/index.cjs +311 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +181 -10
- package/dist/index.d.ts +181 -10
- package/dist/index.js +306 -33
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.27.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- e3bf8c9: Add `jwksKeySet`, `decodeJwt` and `verifyRs256Jwt`: a JWKS key-set cache (max-age, shared in-flight read, unknown-kid refetch floor, stale-while-revalidate) and RS256 JWT signature verification for adapters whose platform signs requests with a JWT.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- 8585427: README status lines say "0.x, pre-1.0" instead of a hard-coded version.
|
|
12
|
+
|
|
13
|
+
## 0.26.0
|
|
14
|
+
|
|
15
|
+
### Minor Changes
|
|
16
|
+
|
|
17
|
+
- f357dab: Export `ReconnectBackoff` and `ReconnectBackoffOptions` so adapters that hold a long-lived connection can share the runner's reconnect backoff, including a reset after a stable connection. `GatewayRunner` now uses it for its own retries.
|
|
18
|
+
- 770b67f: Type `SendResult.error` as `SendError` with shared `SendErrorCode` values, `retryAfterMs` and `platformCode`, and add `sendErrorFromHttp` to map an HTTP status to a `SendResult`.
|
|
19
|
+
- d7dbc27: `splitKeepingRows` takes an optional `{ unit: "utf16" | "codepoint" }` so `partLimit` can be measured in code points. `SplitKeepingRowsOptions` is exported.
|
|
20
|
+
- 28d3dd5: Add `createTokenCache` for expiring access tokens with one shared refresh, and use it in `WeixinAdapterBase`.
|
|
21
|
+
|
|
3
22
|
## 0.25.0
|
|
4
23
|
|
|
5
24
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Multi-platform messaging gateway for `@theokit/sdk`. Transport-agnostic primitives — adapters live in separate peer-dep packages.
|
|
4
4
|
|
|
5
|
-
> **Status: 0.1.0
|
|
5
|
+
> **Status: 0.x, pre-1.0.** Breaking changes allowed within the `0.x` line per semver.
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
@@ -88,6 +88,10 @@ presenter per turn; it keeps state between `present()` calls.
|
|
|
88
88
|
does with `format`; none was observed on a real client.
|
|
89
89
|
- The presenter never splits. Each adapter's `sendMessage` splits a long message at its own
|
|
90
90
|
platform's limit, as it always has.
|
|
91
|
+
- `splitKeepingRows(text, partLimit, { unit })` cuts at grapheme boundaries and keeps table rows
|
|
92
|
+
whole. `partLimit` counts UTF-16 units by default; `unit: "codepoint"` counts code points (it
|
|
93
|
+
needs a positive integer, and throws `RangeError` for a single grapheme longer than the limit).
|
|
94
|
+
Any other `unit` throws `RangeError`.
|
|
91
95
|
- `channelRendering` throws a `RangeError` for a platform it does not know, rather than letting
|
|
92
96
|
the presenter fall back to markdown.
|
|
93
97
|
- `@theokit/presenter` is your dependency, not this package's: `@theokit/gateway` does not depend
|
|
@@ -265,6 +269,31 @@ const { edit, attachments, typing, reactions, threads, maxMessageChars } = adapt
|
|
|
265
269
|
|
|
266
270
|
The type is exported as `AdapterCapabilities`.
|
|
267
271
|
|
|
272
|
+
## Send error codes
|
|
273
|
+
|
|
274
|
+
A failed `SendResult` carries `error: { code, message, retryAfterMs?, platformCode? }`. `code` is a
|
|
275
|
+
`SendErrorCode`, or a platform-specific string an adapter has not mapped yet.
|
|
276
|
+
|
|
277
|
+
| Code | Used when |
|
|
278
|
+
| --- | --- |
|
|
279
|
+
| `empty_text` | core: the message has no text |
|
|
280
|
+
| `not_connected` | core: the adapter is not connected |
|
|
281
|
+
| `invalid_channel` | core: the channel is not valid for the adapter |
|
|
282
|
+
| `attachments_unsupported` | core: attachments sent to an adapter that cannot send them |
|
|
283
|
+
| `rate_limit` | the platform throttled the send (HTTP 429); `retryAfterMs` holds the wait |
|
|
284
|
+
| `permission_denied` | the credential may not post here (HTTP 403) |
|
|
285
|
+
| `auth_failed` | the credential was rejected (HTTP 401) |
|
|
286
|
+
| `timeout` | the request timed out (HTTP 408) |
|
|
287
|
+
| `server_error` | the platform failed (HTTP 5xx) |
|
|
288
|
+
| `network_error` | the request got no answer |
|
|
289
|
+
| `platform_error` | any other platform refusal |
|
|
290
|
+
|
|
291
|
+
`sendErrorFromHttp(status, message, { retryAfter, platformCode, now })` builds the `SendResult`
|
|
292
|
+
for an HTTP status; `retryAfter` is a `Retry-After` value in seconds or an HTTP date. It throws
|
|
293
|
+
`RangeError` when `status` is not an integer in 100..599. Adapters still return their own codes
|
|
294
|
+
today (`rate_limited`, `no_permission`, `<platform>_http_error`); moving them onto the shared
|
|
295
|
+
codes is follow-up work.
|
|
296
|
+
|
|
268
297
|
## Chat commands
|
|
269
298
|
|
|
270
299
|
`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)`.
|
|
@@ -356,6 +385,17 @@ keeps one file per key under `dir` (mode 0600, written to a temp file and rename
|
|
|
356
385
|
`invalid_credential_key`. `get` returns `undefined` for a missing key; any other read error throws
|
|
357
386
|
code `credential_store_unreadable`. `@theokit/gateway-x` uses it to keep a rotated refresh token.
|
|
358
387
|
|
|
388
|
+
## Caching an expiring access token
|
|
389
|
+
|
|
390
|
+
`createTokenCache({ fetchToken })` holds one access token. `get()` returns the cached token, or
|
|
391
|
+
runs `fetchToken` once and gives the same result to every concurrent caller. A token is refreshed
|
|
392
|
+
`marginMs` (default 60 000) before it expires; its lifetime is `expiresInS` from `fetchToken`, or
|
|
393
|
+
`defaultTtlS` (default 7200) when that is absent or not positive. `get({ force: true })` skips the
|
|
394
|
+
cache but still joins a fetch already in flight. `clear()` forgets the token, and a fetch that was
|
|
395
|
+
running at that moment does not store its result. A failed fetch rejects every waiting caller and
|
|
396
|
+
is not cached. The signal passed to `get` reaches `fetchToken` only for the caller that starts the
|
|
397
|
+
fetch. `now` replaces the clock in tests.
|
|
398
|
+
|
|
359
399
|
## Architecture (5 pieces)
|
|
360
400
|
|
|
361
401
|
| Module | Responsibility |
|
|
@@ -644,6 +684,21 @@ assuming this one's.
|
|
|
644
684
|
Adapters whose transport is a long-lived connection rather than a webhook own that transport and do
|
|
645
685
|
not go through this seam.
|
|
646
686
|
|
|
687
|
+
## Verifying a JWT-signed request
|
|
688
|
+
|
|
689
|
+
Platforms that sign requests with an RS256 JWT can share one key-set cache and verifier:
|
|
690
|
+
|
|
691
|
+
```ts
|
|
692
|
+
import { jwksKeySet, verifyRs256Jwt } from "@theokit/gateway";
|
|
693
|
+
|
|
694
|
+
const keys = jwksKeySet({ url: "https://www.googleapis.com/oauth2/v3/certs" });
|
|
695
|
+
const result = await verifyRs256Jwt(bearerToken, keys);
|
|
696
|
+
if (!result.ok) throw new Error(result.reason);
|
|
697
|
+
// result.payload is signature-verified; check issuer, audience and expiry yourself.
|
|
698
|
+
```
|
|
699
|
+
|
|
700
|
+
The cache honours `Cache-Control: max-age`, shares one in-flight read, refetches for an unknown `kid` at most once per `unknownKidRefetchFloorMs` (default 60 s) and, by default, serves a stale key while one refresh runs (`staleWhileRevalidate`). `reason` is `malformed`, `unsupported_alg` (only `RS256` is accepted), `unknown_kid`, `keys_unavailable` or `bad_signature`. `decodeJwt` splits a token without verifying it.
|
|
701
|
+
|
|
647
702
|
## Design principles
|
|
648
703
|
|
|
649
704
|
- **Compose, don't reimplement.** The gateway never owns session persistence (SDK does), never owns scheduling (Cron does), never owns prompt resolution (SystemPromptResolver does).
|
|
@@ -655,3 +710,19 @@ See `.claude/knowledge-base/adrs/D170-D181-*.md` for the full design rationale.
|
|
|
655
710
|
## License
|
|
656
711
|
|
|
657
712
|
Apache-2.0
|
|
713
|
+
|
|
714
|
+
### `ReconnectBackoff`
|
|
715
|
+
|
|
716
|
+
Adapters that hold a long-lived socket or stream can reuse the runner's backoff:
|
|
717
|
+
|
|
718
|
+
```ts
|
|
719
|
+
import { ReconnectBackoff } from "@theokit/gateway";
|
|
720
|
+
|
|
721
|
+
const backoff = new ReconnectBackoff({ initialDelayMs: 1000, maxDelayMs: 30_000 });
|
|
722
|
+
// on open: backoff.opened();
|
|
723
|
+
// on close: const delay = backoff.nextDelayMs(); // undefined once maxAttempts is spent
|
|
724
|
+
```
|
|
725
|
+
|
|
726
|
+
Defaults match `ReconnectPolicy` (1 s initial, 60 s cap, factor 2). A connection open for at least
|
|
727
|
+
`stableAfterMs` (default 60 s) resets the delay. A negative or non-finite delay, or a `factor`
|
|
728
|
+
below 1, throws a `RangeError` naming the field.
|
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var sdk = require('@theokit/sdk');
|
|
4
3
|
var crypto = require('crypto');
|
|
4
|
+
var sdk = require('@theokit/sdk');
|
|
5
5
|
var fs = require('fs');
|
|
6
6
|
var path = require('path');
|
|
7
7
|
var promises = require('fs/promises');
|
|
@@ -380,6 +380,81 @@ var BasePlatformAdapter = class _BasePlatformAdapter {
|
|
|
380
380
|
}
|
|
381
381
|
};
|
|
382
382
|
|
|
383
|
+
// src/adapter/send-error.ts
|
|
384
|
+
function parseRetryAfter(value, now) {
|
|
385
|
+
if (value == null) return void 0;
|
|
386
|
+
const v = value.trim();
|
|
387
|
+
if (/^\d+$/.test(v)) return Number(v) * 1e3;
|
|
388
|
+
if (!/[A-Za-z]/.test(v)) return void 0;
|
|
389
|
+
const at = Date.parse(v);
|
|
390
|
+
if (Number.isNaN(at)) return void 0;
|
|
391
|
+
return Math.max(0, at - now);
|
|
392
|
+
}
|
|
393
|
+
var STATUS_CODES = {
|
|
394
|
+
429: "rate_limit",
|
|
395
|
+
401: "auth_failed",
|
|
396
|
+
403: "permission_denied",
|
|
397
|
+
408: "timeout"
|
|
398
|
+
};
|
|
399
|
+
function codeForStatus(status) {
|
|
400
|
+
return STATUS_CODES[status] ?? (status >= 500 ? "server_error" : "platform_error");
|
|
401
|
+
}
|
|
402
|
+
function sendErrorFromHttp(status, message, options) {
|
|
403
|
+
if (!Number.isInteger(status) || status < 100 || status > 599) {
|
|
404
|
+
throw new RangeError(`status must be an integer in 100..599, got ${String(status)}`);
|
|
405
|
+
}
|
|
406
|
+
const code = codeForStatus(status);
|
|
407
|
+
const retryAfterMs = status === 429 ? parseRetryAfter(options?.retryAfter, (options?.now ?? Date.now)()) : void 0;
|
|
408
|
+
return {
|
|
409
|
+
ok: false,
|
|
410
|
+
error: {
|
|
411
|
+
code,
|
|
412
|
+
message,
|
|
413
|
+
...retryAfterMs !== void 0 ? { retryAfterMs } : {},
|
|
414
|
+
...options?.platformCode !== void 0 ? { platformCode: options.platformCode } : {}
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// src/auth/token-cache.ts
|
|
420
|
+
function createTokenCache(options) {
|
|
421
|
+
const marginMs = options.marginMs ?? 6e4;
|
|
422
|
+
const defaultTtlS = options.defaultTtlS ?? 7200;
|
|
423
|
+
const now = options.now ?? Date.now;
|
|
424
|
+
let cached;
|
|
425
|
+
let pending;
|
|
426
|
+
let generation = 0;
|
|
427
|
+
const refresh = (signal) => {
|
|
428
|
+
const started = generation;
|
|
429
|
+
const run = (async () => {
|
|
430
|
+
const fetched = await options.fetchToken(signal);
|
|
431
|
+
const ttl = fetched.expiresInS !== void 0 && fetched.expiresInS > 0 ? fetched.expiresInS : defaultTtlS;
|
|
432
|
+
if (started === generation) {
|
|
433
|
+
cached = { value: fetched.value, expiresAt: now() + ttl * 1e3 };
|
|
434
|
+
}
|
|
435
|
+
return fetched.value;
|
|
436
|
+
})();
|
|
437
|
+
const tracked = run.finally(() => {
|
|
438
|
+
if (pending === tracked) pending = void 0;
|
|
439
|
+
});
|
|
440
|
+
pending = tracked;
|
|
441
|
+
return tracked;
|
|
442
|
+
};
|
|
443
|
+
return {
|
|
444
|
+
get(opts) {
|
|
445
|
+
if (opts?.force !== true && cached !== void 0 && cached.expiresAt - marginMs > now()) {
|
|
446
|
+
return Promise.resolve(cached.value);
|
|
447
|
+
}
|
|
448
|
+
return pending ?? refresh(opts?.signal);
|
|
449
|
+
},
|
|
450
|
+
clear() {
|
|
451
|
+
generation += 1;
|
|
452
|
+
cached = void 0;
|
|
453
|
+
pending = void 0;
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
|
|
383
458
|
// src/text/seen-ids.ts
|
|
384
459
|
var DEFAULT_LIMIT = 1e3;
|
|
385
460
|
var SeenIds = class {
|
|
@@ -429,7 +504,6 @@ function decodeEntities(s) {
|
|
|
429
504
|
|
|
430
505
|
// src/adapter/weixin-base.ts
|
|
431
506
|
var REQUEST_TIMEOUT_MS = 3e4;
|
|
432
|
-
var TOKEN_MARGIN_MS = 6e4;
|
|
433
507
|
var defaultFetch = async (url, init) => {
|
|
434
508
|
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
|
435
509
|
return { status: res.status, text: () => res.text() };
|
|
@@ -444,12 +518,13 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
|
|
|
444
518
|
cfg;
|
|
445
519
|
doFetch;
|
|
446
520
|
connected = false;
|
|
447
|
-
|
|
521
|
+
tokens;
|
|
448
522
|
seen = new SeenIds();
|
|
449
523
|
constructor(cfg) {
|
|
450
524
|
super();
|
|
451
525
|
this.cfg = cfg;
|
|
452
526
|
this.doFetch = cfg.fetch ?? defaultFetch;
|
|
527
|
+
this.tokens = createTokenCache({ fetchToken: () => this.requestToken() });
|
|
453
528
|
}
|
|
454
529
|
async connect() {
|
|
455
530
|
if (this.connected) return true;
|
|
@@ -465,7 +540,7 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
|
|
|
465
540
|
}
|
|
466
541
|
async disconnect() {
|
|
467
542
|
this.connected = false;
|
|
468
|
-
this.
|
|
543
|
+
this.tokens.clear();
|
|
469
544
|
}
|
|
470
545
|
/** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */
|
|
471
546
|
async sendText(out) {
|
|
@@ -527,21 +602,19 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
|
|
|
527
602
|
if (outcome === "no_handler") return { status: 503, body: "", reason: "no handler subscribed" };
|
|
528
603
|
return weixinAck(outcome);
|
|
529
604
|
}
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
}
|
|
605
|
+
token(force) {
|
|
606
|
+
return this.tokens.get({ force });
|
|
607
|
+
}
|
|
608
|
+
async requestToken() {
|
|
535
609
|
const body = await this.call("GET", this.tokenPath());
|
|
536
610
|
if (body.errcode !== void 0 && body.errcode !== 0) {
|
|
537
611
|
throw new Error(`token answered error ${String(body.errcode)}: ${String(body.errmsg)}`);
|
|
538
612
|
}
|
|
539
613
|
if (!body.access_token) throw new Error("token answer has no access_token");
|
|
540
|
-
|
|
614
|
+
return {
|
|
541
615
|
value: body.access_token,
|
|
542
|
-
|
|
616
|
+
...body.expires_in === void 0 ? {} : { expiresInS: body.expires_in }
|
|
543
617
|
};
|
|
544
|
-
return body.access_token;
|
|
545
618
|
}
|
|
546
619
|
async call(method, path, payload) {
|
|
547
620
|
const res = await this.doFetch((this.cfg.apiBase ?? this.cfg.defaultBase) + path, {
|
|
@@ -557,6 +630,125 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
|
|
|
557
630
|
}
|
|
558
631
|
}
|
|
559
632
|
};
|
|
633
|
+
var DEFAULT_REFETCH_FLOOR_MS = 6e4;
|
|
634
|
+
var READ_TIMEOUT_MS = 1e4;
|
|
635
|
+
function jwksKeySet(options) {
|
|
636
|
+
const doFetch = options.fetch ?? ((url, init) => fetch(url, init));
|
|
637
|
+
const now = options.now ?? Date.now;
|
|
638
|
+
const floor = options.unknownKidRefetchFloorMs ?? DEFAULT_REFETCH_FLOOR_MS;
|
|
639
|
+
const swr = options.staleWhileRevalidate ?? true;
|
|
640
|
+
let held;
|
|
641
|
+
let lastReadStartedAt = Number.NEGATIVE_INFINITY;
|
|
642
|
+
let reading;
|
|
643
|
+
let lastFailure = "no read has completed";
|
|
644
|
+
async function fetchKeys() {
|
|
645
|
+
const response = await doFetch(options.url, { signal: AbortSignal.timeout(READ_TIMEOUT_MS) });
|
|
646
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
647
|
+
const keys = parseKeys(await response.json());
|
|
648
|
+
return { keys, freshUntil: now() + maxAgeMs(response.headers.get("cache-control")) };
|
|
649
|
+
}
|
|
650
|
+
function read() {
|
|
651
|
+
if (reading) return reading;
|
|
652
|
+
lastReadStartedAt = now();
|
|
653
|
+
const current = fetchKeys().then(
|
|
654
|
+
(next) => {
|
|
655
|
+
held = next;
|
|
656
|
+
reading = void 0;
|
|
657
|
+
return void 0;
|
|
658
|
+
},
|
|
659
|
+
(error) => {
|
|
660
|
+
lastFailure = error instanceof Error ? error.message : String(error);
|
|
661
|
+
reading = void 0;
|
|
662
|
+
return lastFailure;
|
|
663
|
+
}
|
|
664
|
+
);
|
|
665
|
+
reading = current;
|
|
666
|
+
return current;
|
|
667
|
+
}
|
|
668
|
+
const mayRead = () => !reading && now() - lastReadStartedAt >= floor;
|
|
669
|
+
function answer(kid) {
|
|
670
|
+
const key = held?.keys.get(kid);
|
|
671
|
+
if (key) return key;
|
|
672
|
+
return held ? "unlisted" : { unavailable: lastFailure };
|
|
673
|
+
}
|
|
674
|
+
async function refreshListed(kid) {
|
|
675
|
+
const refresh = reading ?? (mayRead() ? read() : void 0);
|
|
676
|
+
if (refresh && !swr) await refresh;
|
|
677
|
+
return answer(kid);
|
|
678
|
+
}
|
|
679
|
+
async function refreshUnknown(kid) {
|
|
680
|
+
const refresh = reading ?? (mayRead() ? read() : void 0);
|
|
681
|
+
const failure = refresh ? await refresh : void 0;
|
|
682
|
+
if (failure && !held?.keys.has(kid)) return { unavailable: failure };
|
|
683
|
+
return answer(kid);
|
|
684
|
+
}
|
|
685
|
+
return {
|
|
686
|
+
async lookup(kid) {
|
|
687
|
+
const listed = held?.keys.get(kid);
|
|
688
|
+
if (!held || !listed) return refreshUnknown(kid);
|
|
689
|
+
if (now() < held.freshUntil) return listed;
|
|
690
|
+
return refreshListed(kid);
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
function parseKey(jwk) {
|
|
695
|
+
if (typeof jwk !== "object" || jwk === null) return void 0;
|
|
696
|
+
const { kid, kty, use } = jwk;
|
|
697
|
+
if (typeof kid !== "string" || kty !== "RSA" || use !== void 0 && use !== "sig") {
|
|
698
|
+
return void 0;
|
|
699
|
+
}
|
|
700
|
+
try {
|
|
701
|
+
return [kid, crypto.createPublicKey({ key: jwk, format: "jwk" })];
|
|
702
|
+
} catch {
|
|
703
|
+
return void 0;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
function parseKeys(body) {
|
|
707
|
+
const list = body?.keys;
|
|
708
|
+
if (!Array.isArray(list)) throw new Error("the key set has no `keys` array");
|
|
709
|
+
const entries = list.map(parseKey).filter((e) => e !== void 0);
|
|
710
|
+
return new Map(entries);
|
|
711
|
+
}
|
|
712
|
+
function maxAgeMs(cacheControl) {
|
|
713
|
+
const match = /(?:^|,)\s*max-age=(\d+)/i.exec(cacheControl ?? "");
|
|
714
|
+
return match?.[1] ? Number(match[1]) * 1e3 : 0;
|
|
715
|
+
}
|
|
716
|
+
var BASE64URL = /^[A-Za-z0-9_-]+$/;
|
|
717
|
+
function decodeJwt(token) {
|
|
718
|
+
const parts = token.split(".");
|
|
719
|
+
if (parts.length !== 3) return void 0;
|
|
720
|
+
const [h, p, s] = parts;
|
|
721
|
+
if (![h, p, s].every((part) => BASE64URL.test(part))) return void 0;
|
|
722
|
+
const header = jsonObject(h);
|
|
723
|
+
const payload = jsonObject(p);
|
|
724
|
+
if (!header || !payload) return void 0;
|
|
725
|
+
return { header, payload, signingInput: `${h}.${p}`, signature: Buffer.from(s, "base64url") };
|
|
726
|
+
}
|
|
727
|
+
function jsonObject(segment) {
|
|
728
|
+
try {
|
|
729
|
+
const value = JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
|
|
730
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
731
|
+
} catch {
|
|
732
|
+
return void 0;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
async function verifyRs256Jwt(token, keys) {
|
|
736
|
+
const jwt = decodeJwt(token);
|
|
737
|
+
if (!jwt) return { ok: false, reason: "malformed" };
|
|
738
|
+
if (jwt.header.alg !== "RS256") return { ok: false, reason: "unsupported_alg" };
|
|
739
|
+
const kid = jwt.header.kid;
|
|
740
|
+
if (typeof kid !== "string" || kid === "") return { ok: false, reason: "malformed" };
|
|
741
|
+
const found = await keys.lookup(kid);
|
|
742
|
+
if (found === "unlisted") return { ok: false, reason: "unknown_kid" };
|
|
743
|
+
if ("unavailable" in found) return { ok: false, reason: "keys_unavailable" };
|
|
744
|
+
let valid = false;
|
|
745
|
+
try {
|
|
746
|
+
valid = crypto.verify("RSA-SHA256", Buffer.from(jwt.signingInput), found, jwt.signature);
|
|
747
|
+
} catch {
|
|
748
|
+
valid = false;
|
|
749
|
+
}
|
|
750
|
+
return valid ? { ok: true, header: jwt.header, payload: jwt.payload } : { ok: false, reason: "bad_signature" };
|
|
751
|
+
}
|
|
560
752
|
|
|
561
753
|
// src/errors/config-error.ts
|
|
562
754
|
var GatewayConfigurationError = class extends Error {
|
|
@@ -1250,6 +1442,56 @@ var HookExecutor = class {
|
|
|
1250
1442
|
}
|
|
1251
1443
|
};
|
|
1252
1444
|
|
|
1445
|
+
// src/runner/reconnect-backoff.ts
|
|
1446
|
+
function checkNonNegativeFinite(name, value) {
|
|
1447
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
1448
|
+
throw new RangeError(`${name} must be a finite number >= 0, got ${value}`);
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
var ReconnectBackoff = class {
|
|
1452
|
+
initialDelayMs;
|
|
1453
|
+
maxDelayMs;
|
|
1454
|
+
factor;
|
|
1455
|
+
maxAttempts;
|
|
1456
|
+
stableAfterMs;
|
|
1457
|
+
now;
|
|
1458
|
+
attempts = 0;
|
|
1459
|
+
openedAt;
|
|
1460
|
+
constructor(options = {}) {
|
|
1461
|
+
this.initialDelayMs = options.initialDelayMs ?? 1e3;
|
|
1462
|
+
this.maxDelayMs = options.maxDelayMs ?? 6e4;
|
|
1463
|
+
this.factor = options.factor ?? 2;
|
|
1464
|
+
this.maxAttempts = options.maxAttempts;
|
|
1465
|
+
this.stableAfterMs = options.stableAfterMs ?? 6e4;
|
|
1466
|
+
this.now = options.now ?? Date.now;
|
|
1467
|
+
checkNonNegativeFinite("initialDelayMs", this.initialDelayMs);
|
|
1468
|
+
checkNonNegativeFinite("maxDelayMs", this.maxDelayMs);
|
|
1469
|
+
if (!(this.factor >= 1) || !Number.isFinite(this.factor)) {
|
|
1470
|
+
throw new RangeError(`factor must be a finite number >= 1, got ${this.factor}`);
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
/** Call when the connection opens. */
|
|
1474
|
+
opened() {
|
|
1475
|
+
this.openedAt = this.now();
|
|
1476
|
+
}
|
|
1477
|
+
/** Delay before the next attempt; `undefined` once `maxAttempts` is spent. Resets first if the last connection was stable. */
|
|
1478
|
+
nextDelayMs() {
|
|
1479
|
+
if (this.openedAt !== void 0) {
|
|
1480
|
+
if (this.now() - this.openedAt >= this.stableAfterMs) this.attempts = 0;
|
|
1481
|
+
this.openedAt = void 0;
|
|
1482
|
+
}
|
|
1483
|
+
if (this.maxAttempts !== void 0 && this.attempts >= this.maxAttempts) return void 0;
|
|
1484
|
+
const delay = Math.min(this.initialDelayMs * this.factor ** this.attempts, this.maxDelayMs);
|
|
1485
|
+
this.attempts += 1;
|
|
1486
|
+
return delay;
|
|
1487
|
+
}
|
|
1488
|
+
/** Back to the initial delay. */
|
|
1489
|
+
reset() {
|
|
1490
|
+
this.attempts = 0;
|
|
1491
|
+
this.openedAt = void 0;
|
|
1492
|
+
}
|
|
1493
|
+
};
|
|
1494
|
+
|
|
1253
1495
|
// src/runner/gateway-runner.ts
|
|
1254
1496
|
var DEFAULT_DRAIN_MS = 1e4;
|
|
1255
1497
|
var TYPING_RENEW_MS = 4e3;
|
|
@@ -1401,27 +1643,28 @@ var GatewayRunner = class {
|
|
|
1401
1643
|
connected: result.connected.map((a) => a.platform),
|
|
1402
1644
|
failed: result.failed
|
|
1403
1645
|
};
|
|
1404
|
-
for (const adapter of result.retryable)
|
|
1646
|
+
for (const adapter of result.retryable) {
|
|
1647
|
+
const policy = this.opts.reconnect;
|
|
1648
|
+
if (policy === void 0) break;
|
|
1649
|
+
this.scheduleReconnect(adapter, 1, new ReconnectBackoff(policy));
|
|
1650
|
+
}
|
|
1405
1651
|
return this.startResult;
|
|
1406
1652
|
}
|
|
1407
1653
|
/** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
|
|
1408
|
-
scheduleReconnect(adapter, attempt) {
|
|
1654
|
+
scheduleReconnect(adapter, attempt, backoff) {
|
|
1409
1655
|
const policy = this.opts.reconnect;
|
|
1410
1656
|
if (policy === void 0 || this.stopped) return;
|
|
1411
|
-
|
|
1657
|
+
const delay = backoff.nextDelayMs();
|
|
1658
|
+
if (delay === void 0) {
|
|
1412
1659
|
process.stderr.write(
|
|
1413
1660
|
`[gateway] adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts
|
|
1414
1661
|
`
|
|
1415
1662
|
);
|
|
1416
1663
|
return;
|
|
1417
1664
|
}
|
|
1418
|
-
const delay = Math.min(
|
|
1419
|
-
(policy.initialDelayMs ?? 1e3) * (policy.factor ?? 2) ** (attempt - 1),
|
|
1420
|
-
policy.maxDelayMs ?? 6e4
|
|
1421
|
-
);
|
|
1422
1665
|
const timer = setTimeout(() => {
|
|
1423
1666
|
this.retryTimers.delete(timer);
|
|
1424
|
-
void this.reconnectOnce(adapter, attempt);
|
|
1667
|
+
void this.reconnectOnce(adapter, attempt, backoff);
|
|
1425
1668
|
}, delay);
|
|
1426
1669
|
timer.unref();
|
|
1427
1670
|
this.retryTimers.add(timer);
|
|
@@ -1431,7 +1674,7 @@ var GatewayRunner = class {
|
|
|
1431
1674
|
);
|
|
1432
1675
|
this.emitState(adapter.platform, "retrying", `reconnect attempt ${attempt} in ${delay}ms`);
|
|
1433
1676
|
}
|
|
1434
|
-
async reconnectOnce(adapter, attempt) {
|
|
1677
|
+
async reconnectOnce(adapter, attempt, backoff) {
|
|
1435
1678
|
if (this.stopped) return;
|
|
1436
1679
|
try {
|
|
1437
1680
|
if (await adapter.connect()) {
|
|
@@ -1477,7 +1720,7 @@ var GatewayRunner = class {
|
|
|
1477
1720
|
`
|
|
1478
1721
|
);
|
|
1479
1722
|
}
|
|
1480
|
-
this.scheduleReconnect(adapter, attempt + 1);
|
|
1723
|
+
this.scheduleReconnect(adapter, attempt + 1, backoff);
|
|
1481
1724
|
}
|
|
1482
1725
|
/**
|
|
1483
1726
|
* All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
|
|
@@ -2147,30 +2390,60 @@ function lineEndFrom(text, cut, bound) {
|
|
|
2147
2390
|
while (at < text.length && at <= bound && !isLineEnd2(text[at])) at += 1;
|
|
2148
2391
|
return at;
|
|
2149
2392
|
}
|
|
2150
|
-
function
|
|
2393
|
+
function advance(text, from, count, codepoint) {
|
|
2394
|
+
if (!codepoint) return Math.min(from + count, text.length);
|
|
2395
|
+
let at = from;
|
|
2396
|
+
for (let left = count; left > 0 && at < text.length; left -= 1) {
|
|
2397
|
+
at += (text.codePointAt(at) ?? 0) > 65535 ? 2 : 1;
|
|
2398
|
+
}
|
|
2399
|
+
return at;
|
|
2400
|
+
}
|
|
2401
|
+
function rowSafeCut2(text, partStart, cut, partLimit, codepoint) {
|
|
2151
2402
|
const lineStart = lineStartBefore(text, cut, partStart);
|
|
2152
2403
|
if (lineStart <= partStart || lineStart === cut) return cut;
|
|
2153
2404
|
if (isLineEnd2(text[cut]) || !startsTableRow2(text, lineStart)) return cut;
|
|
2154
|
-
const
|
|
2155
|
-
return
|
|
2405
|
+
const bound = advance(text, lineStart, partLimit, codepoint);
|
|
2406
|
+
return lineEndFrom(text, cut, bound) <= bound ? lineStart : cut;
|
|
2156
2407
|
}
|
|
2157
|
-
function graphemeCut(segments, start,
|
|
2158
|
-
const
|
|
2159
|
-
|
|
2160
|
-
if (segment === void 0 || segment.index >= cut) return cut;
|
|
2408
|
+
function graphemeCut(segments, start, limitCut) {
|
|
2409
|
+
const segment = segments.containing(limitCut);
|
|
2410
|
+
if (segment === void 0 || segment.index >= limitCut) return limitCut;
|
|
2161
2411
|
return segment.index > start ? segment.index : segment.index + segment.segment.length;
|
|
2162
2412
|
}
|
|
2163
|
-
function
|
|
2413
|
+
function readUnit(partLimit, options) {
|
|
2414
|
+
const unit = options.unit ?? "utf16";
|
|
2415
|
+
if (unit !== "utf16" && unit !== "codepoint") {
|
|
2416
|
+
throw new RangeError(
|
|
2417
|
+
`splitKeepingRows: unit must be "utf16" or "codepoint", got ${String(unit)}`
|
|
2418
|
+
);
|
|
2419
|
+
}
|
|
2420
|
+
if (unit === "codepoint" && !(Number.isInteger(partLimit) && partLimit > 0)) {
|
|
2421
|
+
throw new RangeError(
|
|
2422
|
+
`splitKeepingRows: partLimit must be a positive integer, got ${partLimit}`
|
|
2423
|
+
);
|
|
2424
|
+
}
|
|
2425
|
+
return unit === "codepoint";
|
|
2426
|
+
}
|
|
2427
|
+
function splitKeepingRows(text, partLimit, options = {}) {
|
|
2428
|
+
const codepoint = readUnit(partLimit, options);
|
|
2164
2429
|
const segments = new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(text);
|
|
2165
2430
|
const parts = [];
|
|
2166
2431
|
let start = 0;
|
|
2167
|
-
|
|
2168
|
-
|
|
2432
|
+
let limitCut = advance(text, start, partLimit, codepoint);
|
|
2433
|
+
while (limitCut < text.length) {
|
|
2434
|
+
const grapheme = graphemeCut(segments, start, limitCut);
|
|
2435
|
+
if (codepoint && grapheme > limitCut) {
|
|
2436
|
+
throw new RangeError(
|
|
2437
|
+
`splitKeepingRows: a grapheme at offset ${start} is longer than ${partLimit} code points`
|
|
2438
|
+
);
|
|
2439
|
+
}
|
|
2440
|
+
const cut = rowSafeCut2(text, start, grapheme, partLimit, codepoint);
|
|
2169
2441
|
if (cut <= start) {
|
|
2170
2442
|
throw new RangeError(`splitKeepingRows: no progress at offset ${start} of ${text.length}`);
|
|
2171
2443
|
}
|
|
2172
2444
|
parts.push(text.slice(start, cut));
|
|
2173
2445
|
start = cut;
|
|
2446
|
+
limitCut = advance(text, start, partLimit, codepoint);
|
|
2174
2447
|
}
|
|
2175
2448
|
if (start < text.length) parts.push(text.slice(start));
|
|
2176
2449
|
return parts;
|
|
@@ -2441,6 +2714,7 @@ exports.GatewayConfigurationError = GatewayConfigurationError;
|
|
|
2441
2714
|
exports.GatewayLifecycleError = GatewayLifecycleError;
|
|
2442
2715
|
exports.GatewayRunner = GatewayRunner;
|
|
2443
2716
|
exports.HookExecutor = HookExecutor;
|
|
2717
|
+
exports.ReconnectBackoff = ReconnectBackoff;
|
|
2444
2718
|
exports.SeenIds = SeenIds;
|
|
2445
2719
|
exports.SessionRouter = SessionRouter;
|
|
2446
2720
|
exports.WeixinAdapterBase = WeixinAdapterBase;
|
|
@@ -2456,10 +2730,13 @@ exports.createAgentBindings = createAgentBindings;
|
|
|
2456
2730
|
exports.createChannels = createChannels;
|
|
2457
2731
|
exports.createFileCredentialStore = createFileCredentialStore;
|
|
2458
2732
|
exports.createFilePairingStore = createFilePairingStore;
|
|
2733
|
+
exports.createTokenCache = createTokenCache;
|
|
2459
2734
|
exports.createWebhookHandler = createWebhookHandler;
|
|
2735
|
+
exports.decodeJwt = decodeJwt;
|
|
2460
2736
|
exports.defaultStrategy = defaultStrategy;
|
|
2461
2737
|
exports.helpText = helpText;
|
|
2462
2738
|
exports.isAuthenticatedSender = isAuthenticatedSender;
|
|
2739
|
+
exports.jwksKeySet = jwksKeySet;
|
|
2463
2740
|
exports.listenerLifecycle = listenerLifecycle;
|
|
2464
2741
|
exports.loadPeer = loadPeer;
|
|
2465
2742
|
exports.maskSecrets = maskSecrets;
|
|
@@ -2471,10 +2748,12 @@ exports.redactSecrets = redactSecrets;
|
|
|
2471
2748
|
exports.scanFences = scanFences;
|
|
2472
2749
|
exports.scopedStrategy = scopedStrategy;
|
|
2473
2750
|
exports.selectVariant = selectVariant;
|
|
2751
|
+
exports.sendErrorFromHttp = sendErrorFromHttp;
|
|
2474
2752
|
exports.senderKey = senderKey;
|
|
2475
2753
|
exports.splitKeepingRows = splitKeepingRows;
|
|
2476
2754
|
exports.statusForDeliver = statusForDeliver;
|
|
2477
2755
|
exports.toDialect = toDialect;
|
|
2756
|
+
exports.verifyRs256Jwt = verifyRs256Jwt;
|
|
2478
2757
|
exports.withMediaUnderstanding = withMediaUnderstanding;
|
|
2479
2758
|
//# sourceMappingURL=index.cjs.map
|
|
2480
2759
|
//# sourceMappingURL=index.cjs.map
|