@highway1/core 0.1.46 → 0.1.48

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.d.ts CHANGED
@@ -622,6 +622,217 @@ interface MessageRouter {
622
622
  */
623
623
  declare function createMessageRouter(libp2p: Libp2p, verifyFn: (signature: Uint8Array, data: Uint8Array) => Promise<boolean>, dht?: DHTOperations, relayPeers?: string[]): MessageRouter;
624
624
 
625
+ /**
626
+ * Message Queue Types
627
+ *
628
+ * Types for message queue, storage, and filtering operations.
629
+ */
630
+
631
+ /**
632
+ * Message direction
633
+ */
634
+ type MessageDirection = 'inbound' | 'outbound';
635
+ /**
636
+ * Message status
637
+ */
638
+ type MessageStatus = 'pending' | 'delivered' | 'failed' | 'archived';
639
+ /**
640
+ * Stored message with metadata
641
+ */
642
+ interface StoredMessage {
643
+ envelope: MessageEnvelope;
644
+ direction: MessageDirection;
645
+ status: MessageStatus;
646
+ receivedAt?: number;
647
+ sentAt?: number;
648
+ readAt?: number;
649
+ trustScore?: number;
650
+ error?: string;
651
+ }
652
+ /**
653
+ * Message filter for queries
654
+ */
655
+ interface MessageFilter {
656
+ fromDid?: string | string[];
657
+ toDid?: string | string[];
658
+ protocol?: string | string[];
659
+ minTrustScore?: number;
660
+ maxAge?: number;
661
+ type?: 'request' | 'response' | 'notification';
662
+ unreadOnly?: boolean;
663
+ status?: MessageStatus | MessageStatus[];
664
+ }
665
+ /**
666
+ * Pagination options
667
+ */
668
+ interface PaginationOptions {
669
+ limit?: number;
670
+ offset?: number;
671
+ startKey?: string;
672
+ }
673
+ /**
674
+ * Paginated message results
675
+ */
676
+ interface MessagePage {
677
+ messages: StoredMessage[];
678
+ total: number;
679
+ hasMore: boolean;
680
+ nextKey?: string;
681
+ }
682
+ /**
683
+ * Blocklist entry
684
+ */
685
+ interface BlocklistEntry {
686
+ did: string;
687
+ reason: string;
688
+ blockedAt: number;
689
+ blockedBy: string;
690
+ }
691
+ /**
692
+ * Allowlist entry
693
+ */
694
+ interface AllowlistEntry {
695
+ did: string;
696
+ addedAt: number;
697
+ note?: string;
698
+ }
699
+ /**
700
+ * Seen cache entry (for deduplication)
701
+ */
702
+ interface SeenEntry {
703
+ messageId: string;
704
+ seenAt: number;
705
+ fromDid: string;
706
+ }
707
+ /**
708
+ * Rate limit state
709
+ */
710
+ interface RateLimitState {
711
+ did: string;
712
+ tokens: number;
713
+ lastRefill: number;
714
+ totalRequests: number;
715
+ firstSeen: number;
716
+ }
717
+ /**
718
+ * Defense check result
719
+ */
720
+ interface DefenseResult {
721
+ allowed: boolean;
722
+ reason?: 'blocked' | 'duplicate' | 'trust_too_low' | 'rate_limited' | 'invalid';
723
+ trustScore?: number;
724
+ remainingTokens?: number;
725
+ resetTime?: number;
726
+ }
727
+ /**
728
+ * Rate limit result
729
+ */
730
+ interface RateLimitResult {
731
+ allowed: boolean;
732
+ remaining: number;
733
+ resetTime: number;
734
+ limit: number;
735
+ }
736
+ /**
737
+ * Queue statistics
738
+ */
739
+ interface QueueStats {
740
+ inboxTotal: number;
741
+ inboxUnread: number;
742
+ outboxPending: number;
743
+ outboxFailed: number;
744
+ blockedAgents: number;
745
+ allowedAgents: number;
746
+ rateLimitedAgents: number;
747
+ }
748
+ /**
749
+ * Subscription callback
750
+ */
751
+ type MessageCallback = (message: StoredMessage) => void | Promise<void>;
752
+ /**
753
+ * Subscription filter
754
+ */
755
+ interface SubscriptionFilter extends MessageFilter {
756
+ webhookUrl?: string;
757
+ }
758
+
759
+ /**
760
+ * Message Storage - LevelDB operations for message queue
761
+ *
762
+ * Key schema:
763
+ * msg:inbound:{timestamp}:{id} → StoredMessage
764
+ * msg:outbound:{timestamp}:{id} → StoredMessage
765
+ * block:{did} → BlocklistEntry
766
+ * allow:{did} → AllowlistEntry
767
+ * seen:{messageId} → SeenEntry
768
+ * rate:{did} → RateLimitState
769
+ * idx:from:{did}:{timestamp}:{id} → '1'
770
+ */
771
+
772
+ declare class MessageStorage {
773
+ private db;
774
+ private ready;
775
+ constructor(dbPath: string);
776
+ open(): Promise<void>;
777
+ close(): Promise<void>;
778
+ putMessage(msg: StoredMessage): Promise<void>;
779
+ getMessage(id: string): Promise<StoredMessage | null>;
780
+ updateMessage(id: string, updates: Partial<StoredMessage>): Promise<void>;
781
+ deleteMessage(id: string): Promise<void>;
782
+ queryMessages(direction: 'inbound' | 'outbound', filter?: MessageFilter, pagination?: PaginationOptions): Promise<MessagePage>;
783
+ private matchesFilter;
784
+ countMessages(direction: 'inbound' | 'outbound', filter?: MessageFilter): Promise<number>;
785
+ putBlock(entry: BlocklistEntry): Promise<void>;
786
+ getBlock(did: string): Promise<BlocklistEntry | null>;
787
+ deleteBlock(did: string): Promise<void>;
788
+ listBlocked(): Promise<BlocklistEntry[]>;
789
+ putAllow(entry: AllowlistEntry): Promise<void>;
790
+ getAllow(did: string): Promise<AllowlistEntry | null>;
791
+ deleteAllow(did: string): Promise<void>;
792
+ listAllowed(): Promise<AllowlistEntry[]>;
793
+ putSeen(entry: SeenEntry): Promise<void>;
794
+ getSeen(messageId: string): Promise<SeenEntry | null>;
795
+ cleanupSeen(maxAgeMs: number): Promise<void>;
796
+ putRateLimit(state: RateLimitState): Promise<void>;
797
+ getRateLimit(did: string): Promise<RateLimitState | null>;
798
+ cleanupRateLimits(maxAgeMs: number): Promise<void>;
799
+ }
800
+
801
+ /**
802
+ * Message Queue
803
+ *
804
+ * Persistent inbox/outbox backed by LevelDB.
805
+ * Supports real-time subscriptions and pagination.
806
+ */
807
+
808
+ interface MessageQueueConfig {
809
+ dbPath: string;
810
+ }
811
+ declare class MessageQueue {
812
+ private storage;
813
+ private subscriptions;
814
+ private subCounter;
815
+ constructor(config: MessageQueueConfig);
816
+ get store(): MessageStorage;
817
+ start(): Promise<void>;
818
+ stop(): Promise<void>;
819
+ getInbox(filter?: MessageFilter, pagination?: PaginationOptions): Promise<MessagePage>;
820
+ getMessage(id: string): Promise<StoredMessage | null>;
821
+ markAsRead(id: string): Promise<void>;
822
+ deleteMessage(id: string): Promise<void>;
823
+ getOutbox(pagination?: PaginationOptions): Promise<MessagePage>;
824
+ retryMessage(id: string): Promise<void>;
825
+ enqueueInbound(envelope: MessageEnvelope, trustScore?: number): Promise<StoredMessage>;
826
+ enqueueOutbound(envelope: MessageEnvelope): Promise<StoredMessage>;
827
+ markOutboundDelivered(id: string): Promise<void>;
828
+ markOutboundFailed(id: string, error: string): Promise<void>;
829
+ subscribe(filter: SubscriptionFilter, callback: MessageCallback): string;
830
+ unsubscribe(subscriptionId: string): void;
831
+ private notifySubscribers;
832
+ private matchesSubscriptionFilter;
833
+ getStats(): Promise<QueueStats>;
834
+ }
835
+
625
836
  /**
626
837
  * Sybil Defense Mechanisms
627
838
  *
@@ -886,6 +1097,102 @@ declare class TrustSystem {
886
1097
  */
887
1098
  declare function createTrustSystem(config: TrustSystemConfig): TrustSystem;
888
1099
 
1100
+ /**
1101
+ * Token Bucket Rate Limiter
1102
+ *
1103
+ * Classic token bucket algorithm for per-sender rate limiting.
1104
+ * Tokens refill at a constant rate up to capacity.
1105
+ */
1106
+ interface TokenBucketConfig {
1107
+ capacity: number;
1108
+ refillRate: number;
1109
+ }
1110
+ declare class TokenBucket {
1111
+ private tokens;
1112
+ private lastRefill;
1113
+ private readonly capacity;
1114
+ private readonly refillRate;
1115
+ constructor(config: TokenBucketConfig, initialTokens?: number, lastRefill?: number);
1116
+ /** Attempt to consume one token. Returns true if allowed. */
1117
+ consume(): boolean;
1118
+ getRemaining(): number;
1119
+ /** Milliseconds until at least one token is available */
1120
+ getResetTime(): number;
1121
+ /** Serialize state for persistence */
1122
+ toState(): {
1123
+ tokens: number;
1124
+ lastRefill: number;
1125
+ };
1126
+ private refill;
1127
+ }
1128
+ /**
1129
+ * Rate limiter tiers based on trust score
1130
+ */
1131
+ interface RateLimitTiers {
1132
+ /** Trust < 0.3: new/unknown agents */
1133
+ newAgent: TokenBucketConfig;
1134
+ /** Trust 0.3–0.6: established agents */
1135
+ established: TokenBucketConfig;
1136
+ /** Trust > 0.6: trusted agents */
1137
+ trusted: TokenBucketConfig;
1138
+ }
1139
+ declare const DEFAULT_RATE_LIMIT_TIERS: RateLimitTiers;
1140
+ declare function getTierConfig(trustScore: number, tiers: RateLimitTiers): TokenBucketConfig;
1141
+
1142
+ /**
1143
+ * Defense Middleware
1144
+ *
1145
+ * Checks incoming messages against:
1146
+ * 1. Allowlist bypass
1147
+ * 2. Blocklist rejection
1148
+ * 3. Deduplication (seen cache)
1149
+ * 4. Trust score filtering
1150
+ * 5. Rate limiting (token bucket, tiered by trust)
1151
+ */
1152
+
1153
+ interface DefenseConfig {
1154
+ trustSystem: TrustSystem;
1155
+ storage: MessageStorage;
1156
+ /** Minimum trust score to accept messages (0 = accept all) */
1157
+ minTrustScore?: number;
1158
+ /** Auto-block agents below this score */
1159
+ autoBlockThreshold?: number;
1160
+ rateLimitTiers?: RateLimitTiers;
1161
+ /** TTL for seen-cache entries in ms (default: 1 hour) */
1162
+ seenTtlMs?: number;
1163
+ }
1164
+ declare class DefenseMiddleware {
1165
+ private readonly trust;
1166
+ private readonly storage;
1167
+ private readonly minTrustScore;
1168
+ private readonly autoBlockThreshold;
1169
+ private readonly tiers;
1170
+ private readonly seenTtlMs;
1171
+ private readonly seenCache;
1172
+ private readonly MAX_SEEN_CACHE;
1173
+ private readonly buckets;
1174
+ constructor(config: DefenseConfig);
1175
+ /**
1176
+ * Run all defense checks on an incoming message.
1177
+ * Returns { allowed: true } if the message should be processed,
1178
+ * or { allowed: false, reason } if it should be dropped.
1179
+ */
1180
+ checkMessage(envelope: MessageEnvelope): Promise<DefenseResult>;
1181
+ blockAgent(did: string, reason: string, blockedBy?: string): Promise<void>;
1182
+ unblockAgent(did: string): Promise<void>;
1183
+ isBlocked(did: string): Promise<boolean>;
1184
+ allowAgent(did: string, note?: string): Promise<void>;
1185
+ removeFromAllowlist(did: string): Promise<void>;
1186
+ isAllowed(did: string): Promise<boolean>;
1187
+ checkRateLimit(did: string, trustScore: number): Promise<RateLimitResult>;
1188
+ hasSeen(messageId: string): boolean;
1189
+ markAsSeen(messageId: string): void;
1190
+ /** Periodic cleanup of expired seen entries */
1191
+ cleanupSeen(): Promise<void>;
1192
+ /** Periodic cleanup of stale rate limit buckets (24h inactive) */
1193
+ cleanupRateLimits(): Promise<void>;
1194
+ }
1195
+
889
1196
  declare enum LogLevel {
890
1197
  DEBUG = 0,
891
1198
  INFO = 1,
@@ -922,4 +1229,4 @@ declare class MessagingError extends ClawiverseError {
922
1229
  constructor(message: string, details?: unknown);
923
1230
  }
924
1231
 
925
- export { type AgentCard, CLAWIVERSE_CONTEXT, type Capability, CapabilityMatcher, type CapabilityParameter, CapabilityTypes, type Challenge, type ChallengeSolution, ClawiverseError, type ClawiverseNode, type DHTOperations, DiscoveryError, type Endorsement, EndorsementManager, IdentityError, type Interaction, InteractionHistory, type InteractionStats, type KeyPair, type LegacyAgentCard, LogLevel, Logger, type MessageEnvelope, type MessageHandler, type MessageRouter, MessagingError, ParameterTypes, type PeerHint, type PeerTrustLevel, type ResolvedDID, SCHEMA_ORG_CONTEXT, SearchIndex, type SearchResult, type SemanticQuery, SemanticSearchEngine, type SignFunction, type SignedMessage, SybilDefense, type TransportConfig, TransportError, TrustMetrics, type TrustScore, TrustSystem, type TrustSystemConfig, type VerifyFunction, clawiverseContext, createAgentCard, createDHTOperations, createDefaultTrustScore, createEnvelope, createLegacyAgentCard, createLogger, createMessageRouter, createNode, createSemanticSearch, createTrustSystem, decodeAgentCard, decodeFromCBOR, decodeFromJSON, decodeMessage, decodeMessageJSON, deriveDID, downgradeToLegacyCard, encodeForDHT, encodeForWeb, encodeMessage, encodeMessageJSON, exportKeyPair, extractPublicKey, generateKeyPair, getAgentCardContext, getEncodedSize, importKeyPair, isLegacyCard, isValidContext, matchesCapability, sign, signAgentCard, signEnvelope, signMessage, upgradeLegacyCard, validateAgentCard, validateDID, validateEnvelope, verify, verifyAgentCard, verifyEnvelope, verifyMessage };
1232
+ export { type AgentCard, type AllowlistEntry, type BlocklistEntry, CLAWIVERSE_CONTEXT, type Capability, CapabilityMatcher, type CapabilityParameter, CapabilityTypes, type Challenge, type ChallengeSolution, ClawiverseError, type ClawiverseNode, DEFAULT_RATE_LIMIT_TIERS, type DHTOperations, type DefenseConfig, DefenseMiddleware, type DefenseResult, DiscoveryError, type Endorsement, EndorsementManager, IdentityError, type Interaction, InteractionHistory, type InteractionStats, type KeyPair, type LegacyAgentCard, LogLevel, Logger, type MessageCallback, type MessageDirection, type MessageEnvelope, type MessageFilter, type MessageHandler, type MessagePage, MessageQueue, type MessageQueueConfig, type MessageRouter, type MessageStatus, MessageStorage, MessagingError, type PaginationOptions, ParameterTypes, type PeerHint, type PeerTrustLevel, type QueueStats, type RateLimitResult, type RateLimitState, type RateLimitTiers, type ResolvedDID, SCHEMA_ORG_CONTEXT, SearchIndex, type SearchResult, type SeenEntry, type SemanticQuery, SemanticSearchEngine, type SignFunction, type SignedMessage, type StoredMessage, type SubscriptionFilter, SybilDefense, TokenBucket, type TokenBucketConfig, type TransportConfig, TransportError, TrustMetrics, type TrustScore, TrustSystem, type TrustSystemConfig, type VerifyFunction, clawiverseContext, createAgentCard, createDHTOperations, createDefaultTrustScore, createEnvelope, createLegacyAgentCard, createLogger, createMessageRouter, createNode, createSemanticSearch, createTrustSystem, decodeAgentCard, decodeFromCBOR, decodeFromJSON, decodeMessage, decodeMessageJSON, deriveDID, downgradeToLegacyCard, encodeForDHT, encodeForWeb, encodeMessage, encodeMessageJSON, exportKeyPair, extractPublicKey, generateKeyPair, getAgentCardContext, getEncodedSize, getTierConfig, importKeyPair, isLegacyCard, isValidContext, matchesCapability, sign, signAgentCard, signEnvelope, signMessage, upgradeLegacyCard, validateAgentCard, validateDID, validateEnvelope, verify, verifyAgentCard, verifyEnvelope, verifyMessage };