opc-agent 0.9.0 → 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,148 @@
1
+ /**
2
+ * OPC Agent Error Hierarchy - v1.0.0
3
+ * Custom error classes with user-friendly messages and recovery hints.
4
+ */
5
+
6
+ export class OPCError extends Error {
7
+ public readonly code: string;
8
+ public readonly hint?: string;
9
+ public readonly context?: Record<string, unknown>;
10
+ public readonly timestamp = Date.now();
11
+
12
+ constructor(message: string, opts?: { code?: string; hint?: string; context?: Record<string, unknown>; cause?: Error }) {
13
+ super(message);
14
+ this.name = 'OPCError';
15
+ this.code = opts?.code ?? 'OPC_UNKNOWN';
16
+ this.hint = opts?.hint;
17
+ this.context = opts?.context;
18
+ if (opts?.cause) this.cause = opts.cause;
19
+ }
20
+
21
+ toJSON(): Record<string, unknown> {
22
+ return { name: this.name, code: this.code, message: this.message, hint: this.hint, context: this.context, timestamp: this.timestamp };
23
+ }
24
+
25
+ toUserMessage(): string {
26
+ return this.hint ? `${this.message}\nšŸ’” ${this.hint}` : this.message;
27
+ }
28
+ }
29
+
30
+ export class ProviderError extends OPCError {
31
+ public readonly provider: string;
32
+ public readonly statusCode?: number;
33
+
34
+ constructor(provider: string, message: string, opts?: { statusCode?: number; hint?: string; cause?: Error }) {
35
+ super(message, {
36
+ code: 'OPC_PROVIDER_ERROR',
37
+ hint: opts?.hint ?? `Check your API key and network connection for ${provider}.`,
38
+ context: { provider, statusCode: opts?.statusCode },
39
+ cause: opts?.cause,
40
+ });
41
+ this.name = 'ProviderError';
42
+ this.provider = provider;
43
+ this.statusCode = opts?.statusCode;
44
+ }
45
+ }
46
+
47
+ export class ValidationError extends OPCError {
48
+ public readonly field?: string;
49
+ public readonly errors: string[];
50
+
51
+ constructor(message: string, errors: string[] = [], field?: string) {
52
+ super(message, {
53
+ code: 'OPC_VALIDATION_ERROR',
54
+ hint: 'Check your OAD configuration file for missing or invalid fields.',
55
+ context: { field, errors },
56
+ });
57
+ this.name = 'ValidationError';
58
+ this.field = field;
59
+ this.errors = errors;
60
+ }
61
+ }
62
+
63
+ export class ConfigError extends OPCError {
64
+ constructor(message: string, hint?: string) {
65
+ super(message, { code: 'OPC_CONFIG_ERROR', hint: hint ?? 'Check your oad.yaml and .env files.' });
66
+ this.name = 'ConfigError';
67
+ }
68
+ }
69
+
70
+ export class ChannelError extends OPCError {
71
+ public readonly channelType: string;
72
+
73
+ constructor(channelType: string, message: string, opts?: { hint?: string; cause?: Error }) {
74
+ super(message, {
75
+ code: 'OPC_CHANNEL_ERROR',
76
+ hint: opts?.hint ?? `Check configuration for the ${channelType} channel.`,
77
+ context: { channelType },
78
+ cause: opts?.cause,
79
+ });
80
+ this.name = 'ChannelError';
81
+ this.channelType = channelType;
82
+ }
83
+ }
84
+
85
+ export class PluginError extends OPCError {
86
+ public readonly pluginName: string;
87
+
88
+ constructor(pluginName: string, message: string, opts?: { hint?: string; cause?: Error }) {
89
+ super(message, {
90
+ code: 'OPC_PLUGIN_ERROR',
91
+ hint: opts?.hint ?? `Check plugin "${pluginName}" configuration.`,
92
+ context: { pluginName },
93
+ cause: opts?.cause,
94
+ });
95
+ this.name = 'PluginError';
96
+ this.pluginName = pluginName;
97
+ }
98
+ }
99
+
100
+ export class RateLimitError extends OPCError {
101
+ public readonly retryAfterMs?: number;
102
+
103
+ constructor(message?: string, retryAfterMs?: number) {
104
+ super(message ?? 'Rate limit exceeded. Please slow down.', {
105
+ code: 'OPC_RATE_LIMIT',
106
+ hint: retryAfterMs ? `Try again in ${Math.ceil(retryAfterMs / 1000)} seconds.` : 'Please wait before sending more messages.',
107
+ context: { retryAfterMs },
108
+ });
109
+ this.name = 'RateLimitError';
110
+ this.retryAfterMs = retryAfterMs;
111
+ }
112
+ }
113
+
114
+ export class SecurityError extends OPCError {
115
+ constructor(message: string, hint?: string) {
116
+ super(message, { code: 'OPC_SECURITY_ERROR', hint: hint ?? 'This request was blocked for security reasons.' });
117
+ this.name = 'SecurityError';
118
+ }
119
+ }
120
+
121
+ export class TimeoutError extends OPCError {
122
+ constructor(operation: string, timeoutMs: number) {
123
+ super(`Operation "${operation}" timed out after ${timeoutMs}ms`, {
124
+ code: 'OPC_TIMEOUT',
125
+ hint: 'The operation took too long. Try again or increase the timeout.',
126
+ context: { operation, timeoutMs },
127
+ });
128
+ this.name = 'TimeoutError';
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Wrap an unknown thrown value into an OPCError.
134
+ */
135
+ export function wrapError(err: unknown, fallbackMessage = 'An unexpected error occurred'): OPCError {
136
+ if (err instanceof OPCError) return err;
137
+ if (err instanceof Error) return new OPCError(err.message, { cause: err });
138
+ return new OPCError(typeof err === 'string' ? err : fallbackMessage);
139
+ }
140
+
141
+ /**
142
+ * Format error for user display (no stack traces).
143
+ */
144
+ export function formatErrorForUser(err: unknown): string {
145
+ if (err instanceof OPCError) return err.toUserMessage();
146
+ if (err instanceof Error) return err.message;
147
+ return String(err);
148
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Security Hardening Module - v1.0.0
3
+ * Input sanitization, CORS, security headers, API key rotation.
4
+ */
5
+
6
+ import type { Request, Response, NextFunction } from 'express';
7
+
8
+ // ── Input Sanitization ──────────────────────────────────────
9
+
10
+ const XSS_PATTERNS = [
11
+ /<script\b[^>]*>[\s\S]*?<\/script>/gi,
12
+ /javascript:/gi,
13
+ /on\w+\s*=/gi,
14
+ /<iframe\b/gi,
15
+ /<object\b/gi,
16
+ /<embed\b/gi,
17
+ /<form\b/gi,
18
+ ];
19
+
20
+ const SQL_PATTERNS = [
21
+ /(\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER|CREATE|EXEC)\b.*\b(FROM|INTO|TABLE|SET|WHERE|ALL)\b)/gi,
22
+ /(--|;)\s*(DROP|ALTER|DELETE)/gi,
23
+ ];
24
+
25
+ export function sanitizeInput(input: string): string {
26
+ let clean = input;
27
+ for (const pattern of XSS_PATTERNS) {
28
+ clean = clean.replace(pattern, '');
29
+ }
30
+ // Encode dangerous HTML entities
31
+ clean = clean.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
32
+ return clean;
33
+ }
34
+
35
+ export function detectInjection(input: string): { safe: boolean; threats: string[] } {
36
+ const threats: string[] = [];
37
+ for (const pattern of XSS_PATTERNS) {
38
+ if (pattern.test(input)) threats.push('xss');
39
+ pattern.lastIndex = 0;
40
+ }
41
+ for (const pattern of SQL_PATTERNS) {
42
+ if (pattern.test(input)) threats.push('sql_injection');
43
+ pattern.lastIndex = 0;
44
+ }
45
+ return { safe: threats.length === 0, threats: [...new Set(threats)] };
46
+ }
47
+
48
+ // ── Security Headers (Helmet-style) ────────────────────────
49
+
50
+ export interface SecurityHeadersConfig {
51
+ contentSecurityPolicy?: string;
52
+ enableHSTS?: boolean;
53
+ frameDeny?: boolean;
54
+ xssProtection?: boolean;
55
+ noSniff?: boolean;
56
+ referrerPolicy?: string;
57
+ }
58
+
59
+ export function securityHeaders(config?: SecurityHeadersConfig) {
60
+ const csp = config?.contentSecurityPolicy ?? "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'";
61
+ return (_req: Request, res: Response, next: NextFunction): void => {
62
+ res.setHeader('Content-Security-Policy', csp);
63
+ res.setHeader('X-Content-Type-Options', 'nosniff');
64
+ res.setHeader('X-Frame-Options', config?.frameDeny !== false ? 'DENY' : 'SAMEORIGIN');
65
+ res.setHeader('X-XSS-Protection', '1; mode=block');
66
+ res.setHeader('Referrer-Policy', config?.referrerPolicy ?? 'strict-origin-when-cross-origin');
67
+ if (config?.enableHSTS !== false) {
68
+ res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
69
+ }
70
+ res.removeHeader('X-Powered-By');
71
+ next();
72
+ };
73
+ }
74
+
75
+ // ── CORS Configuration ──────────────────────────────────────
76
+
77
+ export interface CORSConfig {
78
+ origins?: string[];
79
+ methods?: string[];
80
+ allowHeaders?: string[];
81
+ credentials?: boolean;
82
+ maxAge?: number;
83
+ }
84
+
85
+ export function corsMiddleware(config?: CORSConfig) {
86
+ const origins = config?.origins ?? ['*'];
87
+ const methods = config?.methods ?? ['GET', 'POST', 'OPTIONS'];
88
+ const headers = config?.allowHeaders ?? ['Content-Type', 'Authorization'];
89
+
90
+ return (req: Request, res: Response, next: NextFunction): void => {
91
+ const origin = req.headers.origin ?? '';
92
+ if (origins.includes('*') || origins.includes(origin)) {
93
+ res.setHeader('Access-Control-Allow-Origin', origins.includes('*') ? '*' : origin);
94
+ }
95
+ res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
96
+ res.setHeader('Access-Control-Allow-Headers', headers.join(', '));
97
+ if (config?.credentials) res.setHeader('Access-Control-Allow-Credentials', 'true');
98
+ if (config?.maxAge) res.setHeader('Access-Control-Max-Age', String(config.maxAge));
99
+ if (req.method === 'OPTIONS') { res.status(204).end(); return; }
100
+ next();
101
+ };
102
+ }
103
+
104
+ // ── API Key Rotation ────────────────────────────────────────
105
+
106
+ export interface APIKeyEntry {
107
+ key: string;
108
+ label?: string;
109
+ createdAt: number;
110
+ expiresAt?: number;
111
+ active: boolean;
112
+ }
113
+
114
+ export class APIKeyManager {
115
+ private keys: APIKeyEntry[] = [];
116
+
117
+ addKey(key: string, opts?: { label?: string; expiresAt?: number }): void {
118
+ this.keys.push({ key, label: opts?.label, createdAt: Date.now(), expiresAt: opts?.expiresAt, active: true });
119
+ }
120
+
121
+ revokeKey(key: string): boolean {
122
+ const entry = this.keys.find(k => k.key === key);
123
+ if (entry) { entry.active = false; return true; }
124
+ return false;
125
+ }
126
+
127
+ isValid(key: string): boolean {
128
+ const entry = this.keys.find(k => k.key === key);
129
+ if (!entry || !entry.active) return false;
130
+ if (entry.expiresAt && Date.now() > entry.expiresAt) { entry.active = false; return false; }
131
+ return true;
132
+ }
133
+
134
+ rotateKey(oldKey: string, newKey: string): boolean {
135
+ const entry = this.keys.find(k => k.key === oldKey && k.active);
136
+ if (!entry) return false;
137
+ entry.active = false;
138
+ this.addKey(newKey, { label: entry.label });
139
+ return true;
140
+ }
141
+
142
+ listActive(): APIKeyEntry[] {
143
+ return this.keys.filter(k => k.active && (!k.expiresAt || Date.now() <= k.expiresAt));
144
+ }
145
+
146
+ cleanup(): number {
147
+ const before = this.keys.length;
148
+ this.keys = this.keys.filter(k => k.active && (!k.expiresAt || Date.now() <= k.expiresAt));
149
+ return before - this.keys.length;
150
+ }
151
+ }
152
+
153
+ // ── Input Validation Middleware ──────────────────────────────
154
+
155
+ export function inputValidation() {
156
+ return (req: Request, res: Response, next: NextFunction): void => {
157
+ if (req.body?.message && typeof req.body.message === 'string') {
158
+ const check = detectInjection(req.body.message);
159
+ if (!check.safe) {
160
+ res.status(400).json({ error: 'Input contains potentially unsafe content', threats: check.threats });
161
+ return;
162
+ }
163
+ // Limit message size
164
+ if (req.body.message.length > 100_000) {
165
+ res.status(413).json({ error: 'Message too large (max 100KB)' });
166
+ return;
167
+ }
168
+ }
169
+ next();
170
+ };
171
+ }
package/src/index.ts CHANGED
@@ -93,3 +93,10 @@ export type { CacheConfig, CacheEntry } from './core/cache';
93
93
  export { getSupportedLocales } from './i18n';
94
94
  export { createDataAnalystConfig } from './templates/data-analyst';
95
95
  export { createTeacherConfig } from './templates/teacher';
96
+
97
+ // v1.0.0 modules
98
+ export { OPCError, ProviderError, ValidationError, ConfigError, ChannelError, PluginError, RateLimitError, SecurityError, TimeoutError, wrapError, formatErrorForUser } from './core/errors';
99
+ export { sanitizeInput, detectInjection, securityHeaders, corsMiddleware, APIKeyManager, inputValidation } from './core/security';
100
+ export type { SecurityHeadersConfig, CORSConfig, APIKeyEntry } from './core/security';
101
+ export { createLoggingPlugin, createAnalyticsPlugin, createRateLimitPlugin } from './plugins';
102
+ export type { PluginManifest } from './plugins';
@@ -1,10 +1,17 @@
1
- import type { ISkill, IChannel } from '../core/types';
1
+ import type { ISkill, IChannel, Message } from '../core/types';
2
2
  import type { MCPTool } from '../tools/mcp';
3
+ import { Logger } from '../core/logger';
3
4
 
4
5
  /**
5
- * Plugin lifecycle hooks.
6
+ * Plugin lifecycle hooks - v1.0.0
6
7
  */
7
8
  export interface PluginHooks {
9
+ onInit?: () => Promise<void>;
10
+ onMessage?: (message: Message) => Promise<Message | void>;
11
+ onResponse?: (message: Message, response: Message) => Promise<Message | void>;
12
+ onError?: (error: Error, context?: Record<string, unknown>) => Promise<void>;
13
+ onShutdown?: () => Promise<void>;
14
+ // Legacy aliases
8
15
  beforeInit?: () => Promise<void>;
9
16
  afterInit?: () => Promise<void>;
10
17
  beforeMessage?: (message: { content: string }) => Promise<void>;
@@ -13,7 +20,15 @@ export interface PluginHooks {
13
20
  }
14
21
 
15
22
  /**
16
- * Plugin interface — extend agent with skills, tools, channels, and lifecycle hooks.
23
+ * Plugin manifest in OAD: plugins: [{ name, config }]
24
+ */
25
+ export interface PluginManifest {
26
+ name: string;
27
+ config?: Record<string, unknown>;
28
+ }
29
+
30
+ /**
31
+ * Plugin interface - extend agent with skills, tools, channels, and lifecycle hooks.
17
32
  */
18
33
  export interface IPlugin {
19
34
  name: string;
@@ -27,9 +42,14 @@ export interface IPlugin {
27
42
 
28
43
  export class PluginManager {
29
44
  private plugins: Map<string, IPlugin> = new Map();
45
+ private logger = new Logger('plugins');
30
46
 
31
47
  register(plugin: IPlugin): void {
48
+ if (this.plugins.has(plugin.name)) {
49
+ this.logger.warn(`Plugin "${plugin.name}" already registered, replacing`);
50
+ }
32
51
  this.plugins.set(plugin.name, plugin);
52
+ this.logger.info(`Plugin registered: ${plugin.name}@${plugin.version}`);
33
53
  }
34
54
 
35
55
  unregister(name: string): void {
@@ -42,9 +62,7 @@ export class PluginManager {
42
62
 
43
63
  list(): { name: string; version: string; description?: string }[] {
44
64
  return Array.from(this.plugins.values()).map(({ name, version, description }) => ({
45
- name,
46
- version,
47
- description,
65
+ name, version, description,
48
66
  }));
49
67
  }
50
68
 
@@ -56,9 +74,59 @@ export class PluginManager {
56
74
  for (const plugin of this.plugins.values()) {
57
75
  const hook = plugin.hooks?.[hookName];
58
76
  if (hook) {
59
- await (hook as (...a: unknown[]) => Promise<void>)(...args);
77
+ try {
78
+ await (hook as (...a: unknown[]) => Promise<void>)(...args);
79
+ } catch (err) {
80
+ this.logger.error(`Plugin "${plugin.name}" hook "${hookName}" failed`, {
81
+ error: err instanceof Error ? err.message : String(err),
82
+ });
83
+ // Don't let one plugin break others
84
+ }
85
+ }
86
+ }
87
+ }
88
+
89
+ async runOnInit(): Promise<void> {
90
+ await this.runHook('onInit');
91
+ await this.runHook('beforeInit');
92
+ await this.runHook('afterInit');
93
+ }
94
+
95
+ async runOnMessage(message: Message): Promise<Message> {
96
+ let msg = message;
97
+ for (const plugin of this.plugins.values()) {
98
+ if (plugin.hooks?.onMessage) {
99
+ const result = await plugin.hooks.onMessage(msg);
100
+ if (result) msg = result;
101
+ }
102
+ if (plugin.hooks?.beforeMessage) {
103
+ await plugin.hooks.beforeMessage({ content: msg.content });
60
104
  }
61
105
  }
106
+ return msg;
107
+ }
108
+
109
+ async runOnResponse(message: Message, response: Message): Promise<Message> {
110
+ let resp = response;
111
+ for (const plugin of this.plugins.values()) {
112
+ if (plugin.hooks?.onResponse) {
113
+ const result = await plugin.hooks.onResponse(message, resp);
114
+ if (result) resp = result;
115
+ }
116
+ if (plugin.hooks?.afterMessage) {
117
+ await plugin.hooks.afterMessage({ content: message.content }, { content: resp.content });
118
+ }
119
+ }
120
+ return resp;
121
+ }
122
+
123
+ async runOnError(error: Error, context?: Record<string, unknown>): Promise<void> {
124
+ await this.runHook('onError', error, context);
125
+ }
126
+
127
+ async runOnShutdown(): Promise<void> {
128
+ await this.runHook('onShutdown');
129
+ await this.runHook('beforeShutdown');
62
130
  }
63
131
 
64
132
  getAllSkills(): ISkill[] {
@@ -85,3 +153,56 @@ export class PluginManager {
85
153
  return channels;
86
154
  }
87
155
  }
156
+
157
+ // ── Built-in Plugins ────────────────────────────────────────
158
+
159
+ export function createLoggingPlugin(): IPlugin {
160
+ const logger = new Logger('agent:messages');
161
+ return {
162
+ name: 'logging',
163
+ version: '1.0.0',
164
+ description: 'Logs all messages and responses',
165
+ hooks: {
166
+ onInit: async () => { logger.info('Agent initialized'); },
167
+ onMessage: async (msg: Message) => { logger.info(`← ${msg.role}: ${msg.content.slice(0, 100)}`); return undefined as any; },
168
+ onResponse: async (_msg: Message, resp: Message) => { logger.info(`→ ${resp.role}: ${resp.content.slice(0, 100)}`); return undefined as any; },
169
+ onError: async (err: Error) => { logger.error(`Error: ${err.message}`); },
170
+ onShutdown: async () => { logger.info('Agent shutting down'); },
171
+ },
172
+ };
173
+ }
174
+
175
+ export function createAnalyticsPlugin(): IPlugin {
176
+ const stats = { messages: 0, errors: 0, startedAt: 0 };
177
+ return {
178
+ name: 'analytics',
179
+ version: '1.0.0',
180
+ description: 'Tracks message counts and error rates',
181
+ hooks: {
182
+ onInit: async () => { stats.startedAt = Date.now(); },
183
+ onMessage: async () => { stats.messages++; return undefined as any; },
184
+ onError: async () => { stats.errors++; },
185
+ },
186
+ };
187
+ }
188
+
189
+ export function createRateLimitPlugin(maxPerMinute = 60): IPlugin {
190
+ const timestamps: number[] = [];
191
+ return {
192
+ name: 'rate-limit',
193
+ version: '1.0.0',
194
+ description: `Rate limits to ${maxPerMinute} messages/minute`,
195
+ hooks: {
196
+ onMessage: async () => {
197
+ const now = Date.now();
198
+ const windowStart = now - 60_000;
199
+ while (timestamps.length > 0 && timestamps[0] < windowStart) timestamps.shift();
200
+ if (timestamps.length >= maxPerMinute) {
201
+ throw new Error('Rate limit exceeded. Please slow down.');
202
+ }
203
+ timestamps.push(now);
204
+ return undefined as any;
205
+ },
206
+ },
207
+ };
208
+ }
package/src/schema/oad.ts CHANGED
@@ -48,6 +48,11 @@ export const HITLSchema = z.object({
48
48
  defaultAction: z.enum(['approve', 'deny']).default('deny'),
49
49
  });
50
50
 
51
+ export const PluginRefSchema = z.object({
52
+ name: z.string(),
53
+ config: z.record(z.unknown()).optional(),
54
+ });
55
+
51
56
  export const AuthSchema = z.object({
52
57
  enabled: z.boolean().default(false),
53
58
  apiKeys: z.array(z.string()).default([]),
@@ -131,6 +136,7 @@ export const SpecSchema = z.object({
131
136
  webhook: WebhookSchema.optional(),
132
137
  hitl: HITLSchema.optional(),
133
138
  auth: AuthSchema.optional(),
139
+ plugins: z.array(PluginRefSchema).optional(),
134
140
  });
135
141
 
136
142
  export const OADSchema = z.object({
@@ -0,0 +1,83 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { OPCError, ProviderError, ValidationError, ConfigError, ChannelError, PluginError, RateLimitError, SecurityError, TimeoutError, wrapError, formatErrorForUser } from '../src/core/errors';
3
+
4
+ describe('Error Hierarchy', () => {
5
+ it('OPCError has code, hint, timestamp', () => {
6
+ const err = new OPCError('boom', { code: 'TEST', hint: 'try again' });
7
+ expect(err.message).toBe('boom');
8
+ expect(err.code).toBe('TEST');
9
+ expect(err.hint).toBe('try again');
10
+ expect(err.timestamp).toBeGreaterThan(0);
11
+ expect(err.toUserMessage()).toContain('try again');
12
+ });
13
+
14
+ it('toJSON serializes correctly', () => {
15
+ const err = new OPCError('test', { code: 'T1' });
16
+ const json = err.toJSON();
17
+ expect(json.name).toBe('OPCError');
18
+ expect(json.code).toBe('T1');
19
+ });
20
+
21
+ it('ProviderError includes provider', () => {
22
+ const err = new ProviderError('openai', 'API key invalid', { statusCode: 401 });
23
+ expect(err.provider).toBe('openai');
24
+ expect(err.statusCode).toBe(401);
25
+ expect(err.code).toBe('OPC_PROVIDER_ERROR');
26
+ expect(err instanceof OPCError).toBe(true);
27
+ });
28
+
29
+ it('ValidationError includes errors array', () => {
30
+ const err = new ValidationError('Invalid config', ['missing name', 'bad version'], 'metadata');
31
+ expect(err.errors).toEqual(['missing name', 'bad version']);
32
+ expect(err.field).toBe('metadata');
33
+ });
34
+
35
+ it('ConfigError', () => {
36
+ const err = new ConfigError('Missing oad.yaml');
37
+ expect(err.code).toBe('OPC_CONFIG_ERROR');
38
+ });
39
+
40
+ it('ChannelError', () => {
41
+ const err = new ChannelError('web', 'Port in use');
42
+ expect(err.channelType).toBe('web');
43
+ });
44
+
45
+ it('PluginError', () => {
46
+ const err = new PluginError('my-plugin', 'Init failed');
47
+ expect(err.pluginName).toBe('my-plugin');
48
+ });
49
+
50
+ it('RateLimitError', () => {
51
+ const err = new RateLimitError(undefined, 5000);
52
+ expect(err.retryAfterMs).toBe(5000);
53
+ expect(err.toUserMessage()).toContain('5 seconds');
54
+ });
55
+
56
+ it('SecurityError', () => {
57
+ const err = new SecurityError('Blocked');
58
+ expect(err.code).toBe('OPC_SECURITY_ERROR');
59
+ });
60
+
61
+ it('TimeoutError', () => {
62
+ const err = new TimeoutError('llm-call', 30000);
63
+ expect(err.message).toContain('30000ms');
64
+ });
65
+
66
+ it('wrapError wraps unknown errors', () => {
67
+ const wrapped = wrapError('string error');
68
+ expect(wrapped instanceof OPCError).toBe(true);
69
+ expect(wrapped.message).toBe('string error');
70
+
71
+ const native = wrapError(new Error('native'));
72
+ expect(native.message).toBe('native');
73
+
74
+ const existing = new ProviderError('x', 'y');
75
+ expect(wrapError(existing)).toBe(existing);
76
+ });
77
+
78
+ it('formatErrorForUser returns clean message', () => {
79
+ expect(formatErrorForUser(new RateLimitError())).toContain('Rate limit');
80
+ expect(formatErrorForUser(new Error('raw'))).toBe('raw');
81
+ expect(formatErrorForUser('string')).toBe('string');
82
+ });
83
+ });
@@ -0,0 +1,60 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { sanitizeInput, detectInjection, APIKeyManager } from '../src/core/security';
3
+
4
+ describe('Security', () => {
5
+ describe('sanitizeInput', () => {
6
+ it('strips script tags', () => {
7
+ expect(sanitizeInput('<script>alert(1)</script>hello')).not.toContain('<script');
8
+ });
9
+ it('encodes HTML entities', () => {
10
+ const result = sanitizeInput('a < b & c > d');
11
+ expect(result).toContain('&lt;');
12
+ expect(result).toContain('&amp;');
13
+ expect(result).toContain('&gt;');
14
+ });
15
+ });
16
+
17
+ describe('detectInjection', () => {
18
+ it('detects XSS', () => {
19
+ const r = detectInjection('<script>alert(1)</script>');
20
+ expect(r.safe).toBe(false);
21
+ expect(r.threats).toContain('xss');
22
+ });
23
+ it('passes clean input', () => {
24
+ expect(detectInjection('Hello world')).toEqual({ safe: true, threats: [] });
25
+ });
26
+ });
27
+
28
+ describe('APIKeyManager', () => {
29
+ it('add, validate, revoke', () => {
30
+ const mgr = new APIKeyManager();
31
+ mgr.addKey('key1', { label: 'test' });
32
+ expect(mgr.isValid('key1')).toBe(true);
33
+ expect(mgr.isValid('key2')).toBe(false);
34
+ mgr.revokeKey('key1');
35
+ expect(mgr.isValid('key1')).toBe(false);
36
+ });
37
+
38
+ it('rotate key', () => {
39
+ const mgr = new APIKeyManager();
40
+ mgr.addKey('old');
41
+ expect(mgr.rotateKey('old', 'new')).toBe(true);
42
+ expect(mgr.isValid('old')).toBe(false);
43
+ expect(mgr.isValid('new')).toBe(true);
44
+ });
45
+
46
+ it('expires keys', () => {
47
+ const mgr = new APIKeyManager();
48
+ mgr.addKey('expired', { expiresAt: Date.now() - 1000 });
49
+ expect(mgr.isValid('expired')).toBe(false);
50
+ });
51
+
52
+ it('listActive filters', () => {
53
+ const mgr = new APIKeyManager();
54
+ mgr.addKey('a');
55
+ mgr.addKey('b');
56
+ mgr.revokeKey('b');
57
+ expect(mgr.listActive().length).toBe(1);
58
+ });
59
+ });
60
+ });