Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

8.3 KB
Raw Blame
/**
 * @cyble/aisoc-connector — TypeScript Connector SDK (t5-connector-sdk-ga).
 *
 * Authoring model in 30 seconds:
 *
 *     import { defineConnector, ConnectorKind } from '@cyble/aisoc-connector';
 *
 *     export default defineConnector({
 *       kind: ConnectorKind.SIEM,
 *       vendor: 'acme-siem',
 *       version: '0.1.0',
 *       configSchema: z.object({ baseUrl: z.string().url(), token: z.string().min(1) }),
 *       actions: {
 *         search_events: {
 *           description: 'Find events for an entity in the last 24h.',
 *           input: z.object({ entity: z.string(), entity_type: z.enum(['ip','host','user']) }),
 *           output: z.array(z.object({
 *             event_id: z.string(),
 *             timestamp: z.string(),
 *             title: z.string(),
 *           })),
 *           handler: async ({ input, ctx }) => {
 *             const r = await ctx.http.get(`/search?q=${input.entity}`);
 *             return r.events;
 *           },
 *         },
 *       },
 *     });
 *
 * The same definition object is what the dev server (`aisoc-connector dev`)
 * exposes over HTTP for the Python platform to call into. Hot reload is
 * file-watcher driven via chokidar — see `dev.ts`.
 *
 * The schema layer is Zod. We chose Zod (over Yup / TypeBox / Valibot)
 * for two reasons:
 *  1. It compiles to OpenAPI / JSON Schema for the marketplace listing
 *     with a single helper (`zod-to-json-schema`).
 *  2. The same schema is used at runtime to validate every action input
 *     before the handler runs, so a malformed agent call can never
 *     reach a connector handler.
 */

import { z, type ZodTypeAny, type ZodType } from 'zod/v3';

// ─── Types ─────────────────────────────────────────────────────────

export enum ConnectorKind {
  SIEM = 'siem',
  EDR = 'edr',
  IDP = 'idp',
  EMAIL = 'email',
  CTI = 'cti',
  TICKETING = 'ticketing',
  CHAT = 'chat',
  PAM = 'pam',
  CASB = 'casb',
  CMDB = 'cmdb',
  CLOUD = 'cloud',
  CUSTOM = 'custom',
}

export enum RiskClass {
  READ = 'READ',
  WRITE_REVERSIBLE = 'WRITE-REVERSIBLE',
  WRITE_SIGNIFICANT = 'WRITE-SIGNIFICANT',
  WRITE_IRREVERSIBLE = 'WRITE-IRREVERSIBLE',
}

/** Minimal HTTP client surface available to handlers. */
export interface ConnectorHttpClient {
  get<T = unknown>(path: string, init?: RequestInit): Promise<T>;
  post<T = unknown>(path: string, body?: unknown, init?: RequestInit): Promise<T>;
  put<T = unknown>(path: string, body?: unknown, init?: RequestInit): Promise<T>;
  delete<T = unknown>(path: string, init?: RequestInit): Promise<T>;
  /** Raw fetch escape hatch for streaming / multipart. */
  fetch(path: string, init?: RequestInit): Promise<Response>;
}

/** Per-call execution context handed to every action handler. */
export interface ActionContext<TConfig = unknown> {
  /** Validated, typed config for this tenant. */
  config: TConfig;
  /** HTTP client preconfigured with the vendor's base URL + auth. */
  http: ConnectorHttpClient;
  /** Tenant id the call is being made on behalf of. */
  tenantId: string;
  /** Idempotency key generated by the agent mesh; safe to forward. */
  idempotencyKey: string;
  /** Unique id for this invocation (for logs / traces). */
  invocationId: string;
  /** Per-tenant logger that ends up in the platform's audit log. */
  log: (level: 'debug' | 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
  /**
   * Abort signal that fires when the platform's tool-call timeout
   * elapses. Always pass this through to fetch() so a slow upstream
   * cannot hold an agent step indefinitely.
   */
  signal: AbortSignal;
}

export interface ActionDefinition<
  TConfig extends ZodTypeAny,
  TInput extends ZodTypeAny,
  TOutput extends ZodTypeAny,
> {
  /** Short imperative description, surfaced in agent-card metadata. */
  description: string;
  /** Risk class governs HITL gating and audit treatment. */
  risk?: RiskClass;
  /** Set true if calling twice with the same input is a no-op. */
  idempotent?: boolean;
  /** Set true if a previous successful call can be undone. */
  reversible?: boolean;
  input: TInput;
  output: TOutput;
  handler: (args: {
    input: z.infer<TInput>;
    ctx: ActionContext<z.infer<TConfig>>;
  }) => Promise<z.infer<TOutput>>;
}

export interface ConnectorDefinition<
  TConfig extends ZodTypeAny = ZodType<unknown>,
> {
  kind: ConnectorKind;
  vendor: string;
  version: string;
  /** Maintainer attribution; surfaced in the marketplace listing. */
  author?: string;
  /** Documentation URL for the contributor. */
  docsUrl?: string;
  /** Zod schema validating tenant-scoped config (creds, base URL, etc). */
  configSchema: TConfig;
  /** Map of action-name -> action definition. */
  actions: Record<
    string,
    ActionDefinition<TConfig, ZodTypeAny, ZodTypeAny>
  >;
  /**
   * Optional health check. Called periodically and on first activation
   * so the platform can mark a tenant connector as up/down.
   */
  health?: (ctx: ActionContext<z.infer<TConfig>>) => Promise<{ ok: boolean; reason?: string }>;
}

// ─── Public API ────────────────────────────────────────────────────

/**
 * Define a connector. The return value is what your module's
 * `default export` should be. The dev server picks this up and
 * publishes it to the Python bridge.
 *
 * The function exists purely for type-narrowing — at runtime it
 * returns its argument unchanged.
 */
export function defineConnector<TConfig extends ZodTypeAny>(
  def: ConnectorDefinition<TConfig>,
): ConnectorDefinition<TConfig> {
  // Sanity-check the manifest at module-load time so the developer
  // sees errors *before* they hit a hot-reload cycle.
  if (!def.kind) throw new Error('connector: kind is required');
  if (!def.vendor || !/^[a-z0-9][a-z0-9-]{1,40}$/.test(def.vendor)) {
    throw new Error(
      'connector.vendor must be 2-41 chars, lowercase letters/digits/hyphens, ' +
        'starting with a letter or digit',
    );
  }
  if (!def.version || !/^\d+\.\d+\.\d+/.test(def.version)) {
    throw new Error('connector.version must be semver-like (e.g. 0.1.0)');
  }
  if (!def.configSchema || typeof def.configSchema.parse !== 'function') {
    throw new Error('connector.configSchema must be a Zod schema');
  }
  for (const [name, action] of Object.entries(def.actions ?? {})) {
    if (!/^[a-z][a-z0-9_]{1,40}$/.test(name)) {
      throw new Error(
        `action name "${name}" is invalid — use snake_case, 2-41 chars`,
      );
    }
    if (typeof action.handler !== 'function') {
      throw new Error(`action "${name}" is missing handler`);
    }
    if (!action.input || typeof action.input.parse !== 'function') {
      throw new Error(`action "${name}" must declare a Zod input schema`);
    }
    if (!action.output || typeof action.output.parse !== 'function') {
      throw new Error(`action "${name}" must declare a Zod output schema`);
    }
  }
  return def;
}

/** Convenience re-export so users only need one import. */
export { z };

// ─── Manifest helpers ──────────────────────────────────────────────
//
// The Python platform consumes a JSON manifest describing the
// connector. We expose a helper here so the dev server, the build
// step, and the marketplace-publish flow all serialise it the same
// way — drift between them was the #1 source of bugs in the v0
// connector SDK.

import { zodToJsonSchema } from './_zodSchema.js';

export function manifestForConnector(
  def: ConnectorDefinition<ZodTypeAny>,
): Record<string, unknown> {
  return {
    sdk_version: '0.1.0-beta.1',
    kind: def.kind,
    vendor: def.vendor,
    version: def.version,
    author: def.author ?? null,
    docs_url: def.docsUrl ?? null,
    config_schema: zodToJsonSchema(def.configSchema),
    actions: Object.fromEntries(
      Object.entries(def.actions).map(([name, a]) => [
        name,
        {
          description: a.description,
          risk: a.risk ?? RiskClass.READ,
          idempotent: a.idempotent ?? true,
          reversible: a.reversible ?? false,
          input_schema: zodToJsonSchema(a.input),
          output_schema: zodToJsonSchema(a.output),
        },
      ]),
    ),
    health: Boolean(def.health),
  };
}