Programmatic interfaces for security management.
import {
// Types
type TrustLevel,
type Capability,
type InjectionSource,
type SecurityConfig,
type SecurityPolicy,
// Trust level utilities
compareTrustLevel,
meetsTrustLevel,
// Capability utilities
hasCapability,
expandCapabilities,
CAPABILITY_PROFILES,
// Source creation
createInjectionSource,
// Policy functions
initSecurity,
getSecurityConfig,
saveSecurityConfig,
resolvePolicy,
checkSessionAccess,
checkCapability,
checkToolAccess,
// Context functions
SecurityContext,
createSecurityContext,
createCliContext,
createDaemonContext,
createP2PContext,
// Sandbox functions
isDockerAvailable,
createSandbox,
execInSandbox,
destroySandbox,
// Gateway functions
isGateway,
canForwardTo,
forwardRequest,
routeThroughGateway,
} from "@wopr/core/security";type TrustLevel = "owner" | "trusted" | "semi-trusted" | "untrusted";Compare two trust levels.
function compareTrustLevel(a: TrustLevel, b: TrustLevel): number;
// Returns:
// -1 if a < b (a is less trusted)
// 0 if a === b
// 1 if a > b (a is more trusted)
// Examples
compareTrustLevel("owner", "trusted"); // 1
compareTrustLevel("untrusted", "trusted"); // -1
compareTrustLevel("trusted", "trusted"); // 0Check if a trust level meets a minimum requirement.
function meetsTrustLevel(actual: TrustLevel, required: TrustLevel): boolean;
// Examples
meetsTrustLevel("owner", "trusted"); // true
meetsTrustLevel("untrusted", "trusted"); // false
meetsTrustLevel("trusted", "trusted"); // truetype Capability =
| "inject"
| "inject.tools"
| "inject.network"
| "inject.exec"
| "session.spawn"
| "cross.inject"
| "config.write"
| "a2a.call"
| "*"; // Wildcard - all capabilitiesCheck if a capability set includes a specific capability.
function hasCapability(
capabilities: Capability[],
required: Capability
): boolean;
// Examples
hasCapability(["inject", "inject.tools"], "inject.tools"); // true
hasCapability(["inject", "inject.tools"], "inject.exec"); // false
hasCapability(["*"], "anything"); // trueExpand wildcard and nested capabilities.
function expandCapabilities(capabilities: Capability[]): Capability[];
// Example
expandCapabilities(["inject.*"]);
// Returns: ["inject", "inject.tools", "inject.network", "inject.exec"]Pre-defined capability sets.
const CAPABILITY_PROFILES: Record<string, Capability[]> = {
owner: ["*"],
trusted: ["inject", "inject.tools", "session.spawn", "a2a.call"],
"semi-trusted": ["inject", "inject.tools"],
untrusted: ["inject"],
readonly: ["inject"],
gateway: ["inject", "inject.tools", "cross.inject", "a2a.call"],
};interface InjectionSource {
type: InjectionSourceType;
trustLevel: TrustLevel;
identity?: {
publicKey?: string;
userId?: string;
gatewaySession?: string;
pluginName?: string;
};
sessionId?: string;
timestamp?: number;
}
type InjectionSourceType =
| "cli"
| "daemon"
| "p2p"
| "p2p-discovery"
| "plugin"
| "cron"
| "api"
| "gateway"
| "internal";Create an injection source with appropriate defaults.
function createInjectionSource(
type: InjectionSourceType,
overrides?: Partial<InjectionSource>
): InjectionSource;
// Examples
const cliSource = createInjectionSource("cli");
// { type: "cli", trustLevel: "owner", timestamp: ... }
const p2pSource = createInjectionSource("p2p", {
trustLevel: "trusted",
identity: { publicKey: "MCow..." }
});
const gatewaySource = createInjectionSource("gateway", {
trustLevel: "semi-trusted",
identity: { gatewaySession: "p2p-gateway" }
});class SecurityContext {
/** The injection source */
readonly source: InjectionSource;
/** Target session name */
readonly session: string;
/** Resolved trust level */
readonly trustLevel: TrustLevel;
/** Granted capabilities */
readonly capabilities: Capability[];
/** Check if a capability is granted */
hasCapability(cap: Capability): boolean;
/** Check if a tool is allowed */
isToolAllowed(toolName: string): boolean;
/** Check if can forward to another session */
canForward(): boolean;
/** Get the resolved policy */
getResolvedPolicy(): ResolvedPolicy;
}Create a security context for an injection.
function createSecurityContext(
source: InjectionSource,
session: string
): SecurityContext;
// Example
const source = createInjectionSource("p2p", {
trustLevel: "trusted",
identity: { publicKey: "MCow..." }
});
const ctx = createSecurityContext(source, "my-session");
if (ctx.hasCapability("inject.tools")) {
// Tools are allowed
}Pre-configured context creators for common sources.
// CLI context (owner)
function createCliContext(session: string): SecurityContext;
// Daemon context (owner)
function createDaemonContext(session: string): SecurityContext;
// Plugin context
function createPluginContext(
pluginName: string,
session: string,
trustLevel?: TrustLevel
): SecurityContext;
// P2P context
function createP2PContext(
session: string,
publicKey: string,
trustLevel: TrustLevel
): SecurityContext;
// P2P discovery context (untrusted)
function createP2PDiscoveryContext(
session: string,
publicKey: string
): SecurityContext;
// API context
function createApiContext(
session: string,
apiKey: string,
trustLevel?: TrustLevel
): SecurityContext;Store and retrieve contexts for sessions.
// Store context for later retrieval
function storeContext(ctx: SecurityContext): void;
// Get context for session
function getContext(session: string): SecurityContext | undefined;
// Clear context
function clearContext(session: string): void;
// Execute with context
async function withSecurityContext<T>(
ctx: SecurityContext,
fn: () => Promise<T>
): Promise<T>;Initialize the security system. Must be called at startup.
async function initSecurity(): Promise<void>;function getSecurityConfig(): SecurityConfig;
function saveSecurityConfig(config: SecurityConfig): void;Resolve the effective policy for a source and session.
function resolvePolicy(
source: InjectionSource,
session: string
): ResolvedPolicy;
interface ResolvedPolicy {
trustLevel: TrustLevel;
capabilities: Capability[];
sandbox: SandboxConfig;
tools: ToolPolicy;
}Check if a source can inject into a session.
function checkSessionAccess(
source: InjectionSource,
session: string
): PolicyCheckResult;
interface PolicyCheckResult {
allowed: boolean;
reason?: string;
requiredCapability?: Capability;
requiresGateway?: boolean;
suggestedGateway?: string;
}Check if a source has a capability.
function checkCapability(
source: InjectionSource,
session: string,
capability: Capability
): PolicyCheckResult;Check if a source can use a specific tool.
function checkToolAccess(
source: InjectionSource,
session: string,
toolName: string
): PolicyCheckResult;Filter available tools based on policy.
function filterToolsByPolicy(
tools: string[],
source: InjectionSource,
session: string
): string[];Check if Docker is available for sandboxing.
async function isDockerAvailable(): Promise<boolean>;Check if the sandbox image exists.
async function isSandboxImageAvailable(): Promise<boolean>;Build the sandbox Docker image.
async function buildSandboxImage(): Promise<void>;Create a new sandbox container.
async function createSandbox(
sessionName: string,
config?: SandboxConfig
): Promise<SandboxInstance>;
interface SandboxInstance {
containerId: string;
sessionName: string;
status: "created" | "running" | "stopped" | "destroyed";
config: SandboxConfig;
}Execute a command in a sandbox.
async function execInSandbox(
containerId: string,
command: string,
options?: {
timeout?: number;
cwd?: string;
env?: Record<string, string>;
}
): Promise<{
stdout: string;
stderr: string;
exitCode: number;
}>;Destroy a sandbox container.
async function destroySandbox(containerId: string): Promise<void>;Get status of a sandbox.
async function getSandboxStatus(
containerId: string
): Promise<SandboxInstance | null>;List all sandbox containers.
async function listSandboxes(): Promise<SandboxInstance[]>;Destroy all sandbox containers.
async function cleanupAllSandboxes(): Promise<void>;Check if a session is a gateway.
function isGateway(sessionName: string): boolean;Get forward rules for a gateway.
function getForwardRules(sessionName: string): GatewayForwardRules | null;Check if gateway can forward to target.
function canForwardTo(
gatewaySession: string,
targetSession: string
): boolean;Forward a request through a gateway.
async function forwardRequest(
gatewaySession: string,
targetSession: string,
message: string,
originalSource: InjectionSource,
options?: {
actionType?: string;
skipApproval?: boolean;
injectFn?: InjectFunction;
}
): Promise<ForwardResult>;
interface ForwardResult {
success: boolean;
response?: string;
error?: string;
requestId: string;
requiresApproval?: boolean;
}Automatically route untrusted request through gateway.
async function routeThroughGateway(
source: InjectionSource,
targetSession: string,
message: string,
injectFn?: InjectFunction
): Promise<ForwardResult | null>;
// Returns null if gateway not requiredCheck if a source must use gateway.
function requiresGateway(
source: InjectionSource,
targetSession: string
): boolean;Find appropriate gateway for a source.
function findGatewayForSource(
source: InjectionSource,
requestedSession: string
): string | null;// Queue request for approval
function queueForApproval(request: ForwardRequest): void;
// Approve request
function approveRequest(requestId: string): ForwardRequest | null;
// Reject request
function rejectRequest(
requestId: string,
reason: string
): ForwardRequest | null;
// Get pending requests
function getPendingRequests(gatewaySession?: string): ForwardRequest[];
// Approve and execute
async function approveAndExecute(
requestId: string,
injectFn?: InjectFunction
): Promise<ForwardResult>;Tools available to sessions for security introspection.
Returns the caller's security context.
Request: (no parameters)
Response:
{
"trustLevel": "trusted",
"capabilities": ["inject", "inject.tools", "session.spawn"],
"sandbox": {
"enabled": false
},
"source": {
"type": "p2p",
"trustLevel": "trusted",
"identity": {
"publicKey": "MCow..."
}
},
"session": "code-assistant",
"policy": {
"tools": {
"allow": ["Read", "Write", "Edit"],
"deny": ["config.write"]
}
}
}Check if a specific action is allowed.
Request:
{
"capability": "inject.network"
}Response (allowed):
{
"allowed": true,
"capability": "inject.network"
}Response (denied):
{
"allowed": false,
"capability": "inject.network",
"reason": "Capability inject.network not granted for trust level 'trusted'"
}Security events emitted for auditing.
type SecurityEventType =
| "access_granted"
| "access_denied"
| "capability_check"
| "tool_blocked"
| "sandbox_created"
| "sandbox_destroyed"
| "gateway_forward"
| "gateway_blocked"
| "policy_violation";
interface SecurityEvent {
type: SecurityEventType;
timestamp: number;
source: InjectionSource;
session: string;
details: Record<string, unknown>;
}
// Subscribe to events
import { events } from "@wopr/core";
events.on("security", (event: SecurityEvent) => {
console.log(`[${event.type}] ${event.session}:`, event.details);
});import { createP2PContext, checkToolAccess } from "@wopr/core/security";
async function handleP2PInject(
session: string,
message: string,
peerKey: string,
trustLevel: TrustLevel
) {
const ctx = createP2PContext(session, peerKey, trustLevel);
// Check if Bash is allowed
const bashCheck = checkToolAccess(ctx.source, session, "Bash");
if (!bashCheck.allowed) {
return { error: bashCheck.reason };
}
// Proceed with injection
return inject(session, message, { source: ctx.source });
}import {
requiresGateway,
routeThroughGateway,
createP2PDiscoveryContext
} from "@wopr/core/security";
async function handleDiscoveredPeer(
session: string,
message: string,
peerKey: string
) {
const ctx = createP2PDiscoveryContext(session, peerKey);
if (requiresGateway(ctx.source, session)) {
const result = await routeThroughGateway(
ctx.source,
session,
message,
inject
);
if (!result) {
return { error: "No gateway available" };
}
if (!result.success) {
return { error: result.error };
}
return { response: result.response };
}
// Direct injection allowed
return inject(session, message, { source: ctx.source });
}import {
checkSandboxRequired,
createSandbox,
execInSandbox,
destroySandbox
} from "@wopr/core/security";
async function runInSandboxIfRequired(
source: InjectionSource,
session: string,
code: string
) {
const policy = resolvePolicy(source, session);
if (policy.sandbox.enabled) {
const sandbox = await createSandbox(session, policy.sandbox);
try {
const result = await execInSandbox(sandbox.containerId, code);
return result;
} finally {
await destroySandbox(sandbox.containerId);
}
}
// Run directly
return exec(code);
}- SECURITY.md - Security model overview
- SECURITY_CONFIG.md - Configuration reference
- GATEWAY.md - Gateway details
- SANDBOX.md - Sandbox details