vix11 1.0.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.
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Vix11 SDK Type Definitions
3
+ *
4
+ * SDK-specific types for requests and responses when interacting
5
+ * with the Vix11 AI agent security platform API.
6
+ */
7
+ /** Error thrown by the Vix11 SDK on non-2xx responses. */
8
+ export declare class Vix11Error extends Error {
9
+ /** HTTP status code returned by the API. */
10
+ readonly status: number;
11
+ /** Raw response body (if available). */
12
+ readonly body: unknown;
13
+ constructor(message: string, status: number, body?: unknown);
14
+ }
15
+ /** Layer-level score returned by the detection pipeline. */
16
+ export interface LayerScore {
17
+ id: string;
18
+ score: number;
19
+ reason: string;
20
+ durationMs: number;
21
+ }
22
+ /** Detection metadata returned by detect/shield endpoints. */
23
+ export interface DetectionMeta {
24
+ action: 'allow' | 'throttle' | 'shadow-ban' | 'block';
25
+ score: number;
26
+ totalDurationMs: number;
27
+ trustScore?: number;
28
+ trustTier?: TrustTier;
29
+ }
30
+ /** Body sent to POST /v1/detect. */
31
+ export interface DetectRequest {
32
+ agentId: string;
33
+ endpoint?: string;
34
+ payload?: string;
35
+ parameters?: Record<string, string>;
36
+ [key: string]: unknown;
37
+ }
38
+ /** Response from POST /v1/detect. */
39
+ export interface DetectResponse {
40
+ detection: {
41
+ action: 'allow' | 'throttle' | 'shadow-ban' | 'block';
42
+ score: number;
43
+ layers: LayerScore[];
44
+ totalDurationMs: number;
45
+ trustScore?: number;
46
+ trustTier?: TrustTier;
47
+ };
48
+ }
49
+ /** Body sent to POST /v1/shield. */
50
+ export interface ShieldRequest {
51
+ agentId: string;
52
+ passport?: SignedPassport;
53
+ endpoint?: string;
54
+ payload?: string;
55
+ parameters?: Record<string, string>;
56
+ [key: string]: unknown;
57
+ }
58
+ /** Response from POST /v1/shield. */
59
+ export interface ShieldResponse {
60
+ status: 'allowed' | 'throttled' | 'blocked';
61
+ retryAfterMs?: number;
62
+ error?: string;
63
+ data?: Record<string, unknown>;
64
+ meta: DetectionMeta;
65
+ }
66
+ export interface PassportCapabilities {
67
+ maxTokensPerDay: number;
68
+ allowedEndpoints: string[];
69
+ maxRequestsPerMinute: number;
70
+ }
71
+ export interface PassportPayload {
72
+ passportId: string;
73
+ agentId: string;
74
+ ownerHash: string;
75
+ capabilities: PassportCapabilities;
76
+ issuedAt: number;
77
+ expiresAt: number;
78
+ version: 1;
79
+ }
80
+ export interface SignedPassport {
81
+ payload: PassportPayload;
82
+ signature: string;
83
+ publicKey: string;
84
+ }
85
+ /** Response from GET /v1/analytics/summary. */
86
+ export interface AnalyticsSummary {
87
+ from: number;
88
+ to: number;
89
+ totalRequests: number;
90
+ blockedRequests: number;
91
+ shadowBannedRequests: number;
92
+ distillationAttempts: number;
93
+ estimatedTokensSaved: number;
94
+ estimatedValueSaved: number;
95
+ topAgents: {
96
+ agentId: string;
97
+ attempts: number;
98
+ }[];
99
+ layerBreakdown: {
100
+ layerId: string;
101
+ avgScore: number;
102
+ triggerCount: number;
103
+ }[];
104
+ }
105
+ /** Response from GET /v1/analytics/events. */
106
+ export interface PaginatedEvents {
107
+ events: DistillationEvent[];
108
+ page: number;
109
+ limit: number;
110
+ total: number;
111
+ }
112
+ export interface DistillationEvent {
113
+ id: string;
114
+ timestamp: number;
115
+ agentId: string;
116
+ action: 'block' | 'shadow-ban' | 'throttle';
117
+ score: number;
118
+ semanticScore: number;
119
+ intentScore: number;
120
+ estimatedTokens: number;
121
+ estimatedValue: number;
122
+ }
123
+ /** Response from GET /v1/compliance/report. */
124
+ export interface ComplianceReport {
125
+ status: string;
126
+ generatedAt: string;
127
+ [key: string]: unknown;
128
+ }
129
+ /** Trust tier for an AI agent. */
130
+ export type TrustTier = 'untrusted' | 'low' | 'medium' | 'high' | 'verified';
131
+ /** Response from GET /v1/trust/:agentId. */
132
+ export interface TrustScore {
133
+ agentId: string;
134
+ trustScore: number;
135
+ trustTier: TrustTier;
136
+ totalRequests: number;
137
+ decisions: {
138
+ allow: number;
139
+ throttle: number;
140
+ shadowBan: number;
141
+ block: number;
142
+ };
143
+ lastAction: string;
144
+ lastDetectionScore: number;
145
+ lastUpdated: string;
146
+ createdAt: string;
147
+ }
148
+ /** KV probe result from health check. */
149
+ export interface HealthCheck {
150
+ name: string;
151
+ status: 'pass' | 'fail';
152
+ durationMs: number;
153
+ }
154
+ /** Response from GET /v1/health. */
155
+ export interface HealthResponse {
156
+ status: 'ok' | 'degraded';
157
+ service: string;
158
+ version: string;
159
+ timestamp: string;
160
+ environment: string;
161
+ pipeline: {
162
+ mode: string;
163
+ layers: number;
164
+ };
165
+ thresholds: {
166
+ throttle: number;
167
+ shadowBan: number;
168
+ block: number;
169
+ };
170
+ checks: Record<string, HealthCheck>;
171
+ totalDurationMs: number;
172
+ }
173
+ /** Response from GET /v1/detection/stats. */
174
+ export interface DetectionStats {
175
+ status: string;
176
+ layers: {
177
+ id: string;
178
+ status: string;
179
+ version: string;
180
+ }[];
181
+ thresholds: {
182
+ throttle: number;
183
+ shadowBan: number;
184
+ block: number;
185
+ };
186
+ }
package/dist/types.js ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Vix11 SDK Type Definitions
3
+ *
4
+ * SDK-specific types for requests and responses when interacting
5
+ * with the Vix11 AI agent security platform API.
6
+ */
7
+ // ---------------------------------------------------------------------------
8
+ // Error
9
+ // ---------------------------------------------------------------------------
10
+ /** Error thrown by the Vix11 SDK on non-2xx responses. */
11
+ export class Vix11Error extends Error {
12
+ /** HTTP status code returned by the API. */
13
+ status;
14
+ /** Raw response body (if available). */
15
+ body;
16
+ constructor(message, status, body) {
17
+ super(message);
18
+ this.name = 'Vix11Error';
19
+ this.status = status;
20
+ this.body = body;
21
+ }
22
+ }
package/package.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "vix11",
3
+ "version": "1.0.0",
4
+ "description": "Vix11 SDK - AI Agent Security",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "test": "vitest run"
10
+ },
11
+ "dependencies": {},
12
+ "devDependencies": {
13
+ "typescript": "^5.4.0",
14
+ "vitest": "^4.1.0"
15
+ }
16
+ }
package/src/client.ts ADDED
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Vix11 SDK Client
3
+ *
4
+ * Provides a typed interface for interacting with the Vix11 API.
5
+ * Uses native fetch (no external dependencies).
6
+ */
7
+
8
+ import type {
9
+ DetectRequest,
10
+ DetectResponse,
11
+ ShieldRequest,
12
+ ShieldResponse,
13
+ AnalyticsSummary,
14
+ PaginatedEvents,
15
+ ComplianceReport,
16
+ DetectionStats,
17
+ TrustScore,
18
+ HealthResponse,
19
+ SignedPassport,
20
+ PassportCapabilities,
21
+ } from './types';
22
+ import { Vix11Error } from './types';
23
+
24
+ /** Configuration for the Vix11 client. */
25
+ export interface Vix11Config {
26
+ /** Base URL of the Vix11 API (e.g. "https://vix11.example.com"). */
27
+ baseUrl: string;
28
+ /** Agent identifier sent with every request. */
29
+ agentId: string;
30
+ /** Optional API key for authenticated requests. */
31
+ apiKey?: string;
32
+ /** Request timeout in milliseconds (default: 5000). */
33
+ timeout?: number;
34
+ }
35
+
36
+ export class Vix11Client {
37
+ private readonly baseUrl: string;
38
+ private readonly agentId: string;
39
+ private readonly apiKey?: string;
40
+ private readonly timeout: number;
41
+
42
+ constructor(config: Vix11Config) {
43
+ // Strip trailing slash for consistent URL building.
44
+ this.baseUrl = config.baseUrl.replace(/\/+$/, '');
45
+ this.agentId = config.agentId;
46
+ this.apiKey = config.apiKey;
47
+ this.timeout = config.timeout ?? 5000;
48
+ }
49
+
50
+ // -----------------------------------------------------------------------
51
+ // Detection
52
+ // -----------------------------------------------------------------------
53
+
54
+ /** Run the detection pipeline against a request payload. */
55
+ async detect(payload: DetectRequest): Promise<DetectResponse> {
56
+ return this.post<DetectResponse>('/v1/detect', payload);
57
+ }
58
+
59
+ /** Run the shielded-request flow (passport verification + detection). */
60
+ async shield(payload: ShieldRequest): Promise<ShieldResponse> {
61
+ return this.post<ShieldResponse>('/v1/shield', payload);
62
+ }
63
+
64
+ // -----------------------------------------------------------------------
65
+ // Analytics
66
+ // -----------------------------------------------------------------------
67
+
68
+ /** Retrieve the analytics summary for a time range. */
69
+ async getAnalyticsSummary(from?: number, to?: number): Promise<AnalyticsSummary> {
70
+ const params = new URLSearchParams();
71
+ if (from !== undefined) params.set('from', String(from));
72
+ if (to !== undefined) params.set('to', String(to));
73
+ const qs = params.toString();
74
+ return this.get<AnalyticsSummary>(`/v1/analytics/summary${qs ? `?${qs}` : ''}`);
75
+ }
76
+
77
+ /** Retrieve paginated analytics events. */
78
+ async getAnalyticsEvents(page?: number, limit?: number): Promise<PaginatedEvents> {
79
+ const params = new URLSearchParams();
80
+ if (page !== undefined) params.set('page', String(page));
81
+ if (limit !== undefined) params.set('limit', String(limit));
82
+ const qs = params.toString();
83
+ return this.get<PaginatedEvents>(`/v1/analytics/events${qs ? `?${qs}` : ''}`);
84
+ }
85
+
86
+ // -----------------------------------------------------------------------
87
+ // Compliance
88
+ // -----------------------------------------------------------------------
89
+
90
+ /** Retrieve the current compliance report. */
91
+ async getComplianceReport(): Promise<ComplianceReport> {
92
+ return this.get<ComplianceReport>('/v1/compliance/report');
93
+ }
94
+
95
+ // -----------------------------------------------------------------------
96
+ // Stats
97
+ // -----------------------------------------------------------------------
98
+
99
+ /** Retrieve detection pipeline stats (layers, thresholds). */
100
+ async getDetectionStats(): Promise<DetectionStats> {
101
+ return this.get<DetectionStats>('/v1/detection/stats');
102
+ }
103
+
104
+ // -----------------------------------------------------------------------
105
+ // Trust
106
+ // -----------------------------------------------------------------------
107
+
108
+ /** Get the Agent Trust Score for a specific agent. */
109
+ async getTrustScore(agentId: string): Promise<TrustScore> {
110
+ return this.get<TrustScore>(`/v1/trust/${encodeURIComponent(agentId)}`);
111
+ }
112
+
113
+ // -----------------------------------------------------------------------
114
+ // Passport
115
+ // -----------------------------------------------------------------------
116
+
117
+ /** Issue a new KYA passport for an agent. */
118
+ async issuePassport(params: {
119
+ agentId: string;
120
+ ownerId: string;
121
+ capabilities: PassportCapabilities;
122
+ ttlSeconds?: number;
123
+ }): Promise<{ passport: SignedPassport; meta: { latencyMs: number } }> {
124
+ return this.post('/v1/passport/issue', params);
125
+ }
126
+
127
+ /** Verify a signed passport. */
128
+ async verifyPassport(passport: SignedPassport): Promise<{
129
+ valid: boolean;
130
+ reason: string;
131
+ payload?: SignedPassport['payload'];
132
+ meta: { latencyMs: number };
133
+ }> {
134
+ return this.post('/v1/passport/verify', passport);
135
+ }
136
+
137
+ /** Revoke a passport by ID. */
138
+ async revokePassport(passportId: string, reason: string): Promise<{
139
+ revoked: boolean;
140
+ passportId: string;
141
+ }> {
142
+ return this.post('/v1/passport/revoke', { passportId, reason });
143
+ }
144
+
145
+ // -----------------------------------------------------------------------
146
+ // Health
147
+ // -----------------------------------------------------------------------
148
+
149
+ /** Check API health with KV connectivity probes. */
150
+ async health(): Promise<HealthResponse> {
151
+ return this.get<HealthResponse>('/v1/health');
152
+ }
153
+
154
+ // -----------------------------------------------------------------------
155
+ // Internal helpers
156
+ // -----------------------------------------------------------------------
157
+
158
+ private buildHeaders(): Record<string, string> {
159
+ const headers: Record<string, string> = {
160
+ 'Content-Type': 'application/json',
161
+ 'X-Vix11-Agent-Id': this.agentId,
162
+ };
163
+ if (this.apiKey) {
164
+ headers['Authorization'] = `Bearer ${this.apiKey}`;
165
+ }
166
+ return headers;
167
+ }
168
+
169
+ private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
170
+ const url = `${this.baseUrl}${path}`;
171
+ const controller = new AbortController();
172
+ const timer = setTimeout(() => controller.abort(), this.timeout);
173
+
174
+ try {
175
+ const response = await fetch(url, {
176
+ method,
177
+ headers: this.buildHeaders(),
178
+ body: body !== undefined ? JSON.stringify(body) : undefined,
179
+ signal: controller.signal,
180
+ });
181
+
182
+ const responseBody: unknown = await response.json().catch(() => null);
183
+
184
+ if (!response.ok) {
185
+ const message =
186
+ (responseBody && typeof responseBody === 'object' && 'error' in responseBody
187
+ ? String((responseBody as Record<string, unknown>).error)
188
+ : undefined) ?? `Request failed with status ${response.status}`;
189
+ throw new Vix11Error(message, response.status, responseBody);
190
+ }
191
+
192
+ return responseBody as T;
193
+ } catch (err) {
194
+ if (err instanceof Vix11Error) throw err;
195
+ if (err instanceof DOMException && err.name === 'AbortError') {
196
+ throw new Vix11Error(`Request timed out after ${this.timeout}ms`, 0);
197
+ }
198
+ throw err;
199
+ } finally {
200
+ clearTimeout(timer);
201
+ }
202
+ }
203
+
204
+ private get<T>(path: string): Promise<T> {
205
+ return this.request<T>('GET', path);
206
+ }
207
+
208
+ private post<T>(path: string, body: unknown): Promise<T> {
209
+ return this.request<T>('POST', path, body);
210
+ }
211
+ }
package/src/index.ts ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Vix11 SDK — AI Agent Security
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+
7
+ export { Vix11Client } from './client';
8
+ export type { Vix11Config } from './client';
9
+ export { vix11Middleware } from './middleware';
10
+ export type { RequestHandler } from './middleware';
11
+
12
+ export {
13
+ Vix11Error,
14
+ type LayerScore,
15
+ type DetectionMeta,
16
+ type DetectRequest,
17
+ type DetectResponse,
18
+ type ShieldRequest,
19
+ type ShieldResponse,
20
+ type PassportCapabilities,
21
+ type PassportPayload,
22
+ type SignedPassport,
23
+ type AnalyticsSummary,
24
+ type PaginatedEvents,
25
+ type DistillationEvent,
26
+ type ComplianceReport,
27
+ type DetectionStats,
28
+ type TrustTier,
29
+ type TrustScore,
30
+ type HealthCheck,
31
+ type HealthResponse,
32
+ } from './types';
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Vix11 Express Middleware
3
+ *
4
+ * Drop-in Express middleware that intercepts incoming requests,
5
+ * runs them through the Vix11 detection pipeline, and blocks or
6
+ * throttles suspicious traffic automatically.
7
+ */
8
+
9
+ import { Vix11Client } from './client';
10
+ import type { Vix11Config } from './client';
11
+ import type { DetectResponse } from './types';
12
+
13
+ /** Minimal Express-compatible types so we avoid a dependency on @types/express. */
14
+ interface Request {
15
+ ip?: string;
16
+ path?: string;
17
+ method?: string;
18
+ body?: unknown;
19
+ headers: Record<string, string | string[] | undefined>;
20
+ vix11?: DetectResponse['detection'];
21
+ [key: string]: unknown;
22
+ }
23
+
24
+ interface Response {
25
+ status(code: number): Response;
26
+ json(body: unknown): void;
27
+ }
28
+
29
+ type NextFunction = (err?: unknown) => void;
30
+
31
+ /** Express-compatible RequestHandler signature. */
32
+ export type RequestHandler = (req: Request, res: Response, next: NextFunction) => void;
33
+
34
+ /**
35
+ * Create Express middleware that runs every incoming request through
36
+ * Vix11 detection.
37
+ *
38
+ * - If the action is `block`, responds with 403.
39
+ * - If the action is `throttle`, responds with 429.
40
+ * - Otherwise calls `next()` and attaches the detection result to `req.vix11`.
41
+ */
42
+ export function vix11Middleware(config: Vix11Config): RequestHandler {
43
+ const client = new Vix11Client(config);
44
+
45
+ return (req: Request, res: Response, next: NextFunction): void => {
46
+ const agentIdHeader = req.headers['x-vix11-agent-id'];
47
+ const agentId = (typeof agentIdHeader === 'string' ? agentIdHeader : undefined) ?? config.agentId;
48
+
49
+ const ip =
50
+ (typeof req.headers['x-forwarded-for'] === 'string'
51
+ ? req.headers['x-forwarded-for'].split(',')[0]?.trim()
52
+ : undefined) ?? req.ip ?? '0.0.0.0';
53
+
54
+ client
55
+ .detect({
56
+ agentId,
57
+ endpoint: req.path ?? '/',
58
+ payload: req.body ? JSON.stringify(req.body) : undefined,
59
+ ip,
60
+ })
61
+ .then((result) => {
62
+ // Attach to request for downstream handlers.
63
+ req.vix11 = result.detection;
64
+
65
+ switch (result.detection.action) {
66
+ case 'block':
67
+ res.status(403).json({
68
+ error: 'Request blocked by Vix11 security policy',
69
+ action: 'block',
70
+ });
71
+ return;
72
+ case 'throttle':
73
+ res.status(429).json({
74
+ error: 'Request throttled by Vix11 security policy',
75
+ action: 'throttle',
76
+ retryAfterMs: 5000,
77
+ });
78
+ return;
79
+ default:
80
+ next();
81
+ }
82
+ })
83
+ .catch((err: unknown) => {
84
+ // On detection failure, fail open (let request through) and forward the error.
85
+ next(err);
86
+ });
87
+ };
88
+ }