@theokit/gateway 0.26.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 +10 -0
- package/README.md +16 -1
- package/dist/index.cjs +123 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +55 -1
- package/dist/index.d.ts +55 -1
- package/dist/index.js +121 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { KeyObject } from 'node:crypto';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* A bounded set of ids, oldest evicted first, so a long-running process remembers what it delivered
|
|
3
5
|
* without growing for ever (NFR-003).
|
|
@@ -1136,6 +1138,58 @@ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
|
|
|
1136
1138
|
*/
|
|
1137
1139
|
declare function parseFlatXml(xml: string): Record<string, string>;
|
|
1138
1140
|
|
|
1141
|
+
/**
|
|
1142
|
+
* A JWKS key-set cache and RS256 JWT signature verification, for platforms that sign their
|
|
1143
|
+
* requests with a JWT. Signature only: issuer, audience and expiry stay with the caller.
|
|
1144
|
+
*/
|
|
1145
|
+
|
|
1146
|
+
/** A key for a `kid`, `"unlisted"` when the key set does not list it, or why no key set is readable. */
|
|
1147
|
+
type JwksLookup = KeyObject | "unlisted" | {
|
|
1148
|
+
readonly unavailable: string;
|
|
1149
|
+
};
|
|
1150
|
+
/** Where a JWKS is read from, and how its cache behaves. */
|
|
1151
|
+
interface JwksKeySetOptions {
|
|
1152
|
+
readonly url: string;
|
|
1153
|
+
readonly fetch?: (url: string, init?: {
|
|
1154
|
+
signal?: AbortSignal;
|
|
1155
|
+
}) => Promise<Response>;
|
|
1156
|
+
readonly now?: () => number;
|
|
1157
|
+
/** Minimum time between refetches triggered by an unknown kid. Default 60_000. */
|
|
1158
|
+
readonly unknownKidRefetchFloorMs?: number;
|
|
1159
|
+
/** Serve a stale key set while one refresh runs. Default true. */
|
|
1160
|
+
readonly staleWhileRevalidate?: boolean;
|
|
1161
|
+
}
|
|
1162
|
+
/** A cache of the keys a JWKS publishes, looked up by `kid`. */
|
|
1163
|
+
interface JwksKeySet {
|
|
1164
|
+
lookup(kid: string): Promise<JwksLookup>;
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* A JWKS key set cached for the `max-age` its response declares. Concurrent lookups share one
|
|
1168
|
+
* read; a read starts at most once per `unknownKidRefetchFloorMs`. A failed read keeps the last
|
|
1169
|
+
* good copy.
|
|
1170
|
+
*/
|
|
1171
|
+
declare function jwksKeySet(options: JwksKeySetOptions): JwksKeySet;
|
|
1172
|
+
/** A compact JWT split into its parts; nothing in it is verified yet. */
|
|
1173
|
+
interface DecodedJwt {
|
|
1174
|
+
readonly header: Readonly<Record<string, unknown>>;
|
|
1175
|
+
readonly payload: Readonly<Record<string, unknown>>;
|
|
1176
|
+
readonly signingInput: string;
|
|
1177
|
+
readonly signature: Buffer;
|
|
1178
|
+
}
|
|
1179
|
+
/** Split a compact JWT into its parts without checking anything; `undefined` when malformed. */
|
|
1180
|
+
declare function decodeJwt(token: string): DecodedJwt | undefined;
|
|
1181
|
+
/** The outcome of checking a token's signature: its claims, or why it was refused. */
|
|
1182
|
+
type VerifyJwtResult = {
|
|
1183
|
+
readonly ok: true;
|
|
1184
|
+
readonly header: DecodedJwt["header"];
|
|
1185
|
+
readonly payload: DecodedJwt["payload"];
|
|
1186
|
+
} | {
|
|
1187
|
+
readonly ok: false;
|
|
1188
|
+
readonly reason: "malformed" | "unsupported_alg" | "unknown_kid" | "keys_unavailable" | "bad_signature";
|
|
1189
|
+
};
|
|
1190
|
+
/** Signature only. Issuer, audience and expiry stay with the caller. */
|
|
1191
|
+
declare function verifyRs256Jwt(token: string, keys: JwksKeySet): Promise<VerifyJwtResult>;
|
|
1192
|
+
|
|
1139
1193
|
/**
|
|
1140
1194
|
* `createTokenCache` — holds one expiring access token and shares a single refresh between every
|
|
1141
1195
|
* concurrent caller.
|
|
@@ -2574,4 +2628,4 @@ interface WebhookHandlerOptions {
|
|
|
2574
2628
|
*/
|
|
2575
2629
|
declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
|
|
2576
2630
|
|
|
2577
|
-
export { type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelConfigInput, type ChannelConfigReaders, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type CredentialStore, DEFAULT_WEBHOOK_MAX_BYTES, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type FeishuLarkMessageEvent, type FenceRegion, type FetchedToken, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, ReconnectBackoff, type ReconnectBackoffOptions, type ReconnectPolicy, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendError, type SendErrorCode, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type SplitKeepingRowsOptions, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TokenCache, type TokenCacheOptions, type TwitchMessageEvent, type UncoveredShape, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createTokenCache, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, sendErrorFromHttp, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
|
|
2631
|
+
export { type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelConfigInput, type ChannelConfigReaders, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type CredentialStore, DEFAULT_WEBHOOK_MAX_BYTES, type DecodedJwt, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type FeishuLarkMessageEvent, type FenceRegion, type FetchedToken, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type JwksKeySet, type JwksKeySetOptions, type JwksLookup, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, ReconnectBackoff, type ReconnectBackoffOptions, type ReconnectPolicy, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendError, type SendErrorCode, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type SplitKeepingRowsOptions, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TokenCache, type TokenCacheOptions, type TwitchMessageEvent, type UncoveredShape, type VerifyJwtResult, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, 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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { KeyObject } from 'node:crypto';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* A bounded set of ids, oldest evicted first, so a long-running process remembers what it delivered
|
|
3
5
|
* without growing for ever (NFR-003).
|
|
@@ -1136,6 +1138,58 @@ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
|
|
|
1136
1138
|
*/
|
|
1137
1139
|
declare function parseFlatXml(xml: string): Record<string, string>;
|
|
1138
1140
|
|
|
1141
|
+
/**
|
|
1142
|
+
* A JWKS key-set cache and RS256 JWT signature verification, for platforms that sign their
|
|
1143
|
+
* requests with a JWT. Signature only: issuer, audience and expiry stay with the caller.
|
|
1144
|
+
*/
|
|
1145
|
+
|
|
1146
|
+
/** A key for a `kid`, `"unlisted"` when the key set does not list it, or why no key set is readable. */
|
|
1147
|
+
type JwksLookup = KeyObject | "unlisted" | {
|
|
1148
|
+
readonly unavailable: string;
|
|
1149
|
+
};
|
|
1150
|
+
/** Where a JWKS is read from, and how its cache behaves. */
|
|
1151
|
+
interface JwksKeySetOptions {
|
|
1152
|
+
readonly url: string;
|
|
1153
|
+
readonly fetch?: (url: string, init?: {
|
|
1154
|
+
signal?: AbortSignal;
|
|
1155
|
+
}) => Promise<Response>;
|
|
1156
|
+
readonly now?: () => number;
|
|
1157
|
+
/** Minimum time between refetches triggered by an unknown kid. Default 60_000. */
|
|
1158
|
+
readonly unknownKidRefetchFloorMs?: number;
|
|
1159
|
+
/** Serve a stale key set while one refresh runs. Default true. */
|
|
1160
|
+
readonly staleWhileRevalidate?: boolean;
|
|
1161
|
+
}
|
|
1162
|
+
/** A cache of the keys a JWKS publishes, looked up by `kid`. */
|
|
1163
|
+
interface JwksKeySet {
|
|
1164
|
+
lookup(kid: string): Promise<JwksLookup>;
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* A JWKS key set cached for the `max-age` its response declares. Concurrent lookups share one
|
|
1168
|
+
* read; a read starts at most once per `unknownKidRefetchFloorMs`. A failed read keeps the last
|
|
1169
|
+
* good copy.
|
|
1170
|
+
*/
|
|
1171
|
+
declare function jwksKeySet(options: JwksKeySetOptions): JwksKeySet;
|
|
1172
|
+
/** A compact JWT split into its parts; nothing in it is verified yet. */
|
|
1173
|
+
interface DecodedJwt {
|
|
1174
|
+
readonly header: Readonly<Record<string, unknown>>;
|
|
1175
|
+
readonly payload: Readonly<Record<string, unknown>>;
|
|
1176
|
+
readonly signingInput: string;
|
|
1177
|
+
readonly signature: Buffer;
|
|
1178
|
+
}
|
|
1179
|
+
/** Split a compact JWT into its parts without checking anything; `undefined` when malformed. */
|
|
1180
|
+
declare function decodeJwt(token: string): DecodedJwt | undefined;
|
|
1181
|
+
/** The outcome of checking a token's signature: its claims, or why it was refused. */
|
|
1182
|
+
type VerifyJwtResult = {
|
|
1183
|
+
readonly ok: true;
|
|
1184
|
+
readonly header: DecodedJwt["header"];
|
|
1185
|
+
readonly payload: DecodedJwt["payload"];
|
|
1186
|
+
} | {
|
|
1187
|
+
readonly ok: false;
|
|
1188
|
+
readonly reason: "malformed" | "unsupported_alg" | "unknown_kid" | "keys_unavailable" | "bad_signature";
|
|
1189
|
+
};
|
|
1190
|
+
/** Signature only. Issuer, audience and expiry stay with the caller. */
|
|
1191
|
+
declare function verifyRs256Jwt(token: string, keys: JwksKeySet): Promise<VerifyJwtResult>;
|
|
1192
|
+
|
|
1139
1193
|
/**
|
|
1140
1194
|
* `createTokenCache` — holds one expiring access token and shares a single refresh between every
|
|
1141
1195
|
* concurrent caller.
|
|
@@ -2574,4 +2628,4 @@ interface WebhookHandlerOptions {
|
|
|
2574
2628
|
*/
|
|
2575
2629
|
declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
|
|
2576
2630
|
|
|
2577
|
-
export { type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelConfigInput, type ChannelConfigReaders, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type CredentialStore, DEFAULT_WEBHOOK_MAX_BYTES, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type FeishuLarkMessageEvent, type FenceRegion, type FetchedToken, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, ReconnectBackoff, type ReconnectBackoffOptions, type ReconnectPolicy, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendError, type SendErrorCode, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type SplitKeepingRowsOptions, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TokenCache, type TokenCacheOptions, type TwitchMessageEvent, type UncoveredShape, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createTokenCache, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, sendErrorFromHttp, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
|
|
2631
|
+
export { type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelConfigInput, type ChannelConfigReaders, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type CredentialStore, DEFAULT_WEBHOOK_MAX_BYTES, type DecodedJwt, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type FeishuLarkMessageEvent, type FenceRegion, type FetchedToken, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type JwksKeySet, type JwksKeySetOptions, type JwksLookup, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, ReconnectBackoff, type ReconnectBackoffOptions, type ReconnectPolicy, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendError, type SendErrorCode, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type SplitKeepingRowsOptions, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TokenCache, type TokenCacheOptions, type TwitchMessageEvent, type UncoveredShape, type VerifyJwtResult, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, 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 };
|
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';
|
|
@@ -628,6 +628,125 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
|
|
|
628
628
|
}
|
|
629
629
|
}
|
|
630
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
|
+
}
|
|
631
750
|
|
|
632
751
|
// src/errors/config-error.ts
|
|
633
752
|
var GatewayConfigurationError = class extends Error {
|
|
@@ -2585,6 +2704,6 @@ async function dispatch(webhook, adapter, request) {
|
|
|
2585
2704
|
return runDefault(webhook, adapter, request);
|
|
2586
2705
|
}
|
|
2587
2706
|
|
|
2588
|
-
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, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, sendErrorFromHttp, 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 };
|
|
2589
2708
|
//# sourceMappingURL=index.js.map
|
|
2590
2709
|
//# sourceMappingURL=index.js.map
|