All files / lib/executor code-policy.ts

100% Statements 199/199
97.36% Branches 37/38
100% Functions 7/7
100% Lines 199/199

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 2001x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 69x 69x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 21x 1x 1x 1x 1x 1x 1x 1x 21x 20x 20x 20x 20x 20x 20x 20x 21x 1x 1x 1x 1x 1x 560x 4x 1x 1x 1x 1x 558x 1x 1x 1x 1x 557x 2x 1x 1x 1x 1x 1x 556x 554x 553x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 560x 560x 8x 8x 8x 8x 8x 8x 560x 560x 35x 35x 35x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 35x 35x 35x 35x 35x 2x 2x 2x 2x 2x 2x 2x 2x 2x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 2x 2x 2x 2x 2x 2x 2x 2x 2x 35x 35x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 35x 29x 29x 29x 29x 35x  
"use strict";
/**
 * Static checks and transpilation of agent-submitted code.
 *
 * Agent code is the body of an async function receiving `sdk` and
 * `console`. Module syntax and dynamic `import()` are rejected before
 * execution; the Deno sandbox additionally disables string code generation
 * so imports cannot be smuggled through eval. These checks are defence in
 * depth, not the security boundary: the separate, permissionless Deno
 * process is.
 *
 * @module executor/code-policy
 */
import ts from "typescript";
 
import type { Diagnostic, ExecutionError } from "./types.js";
 
/** Number of wrapper lines that precede agent code. */
export const WRAPPER_HEADER_LINES = 1;
 
/** Result of preparing code. */
export type PreparedCode =
  | { ok: true; moduleBase64: string; js: string }
  | { ok: false; error: ExecutionError; violations?: string[] };
 
/**
 * Wrap agent code for transpilation and execution.
 *
 * @param {String} code - agent code
 * @return {String} module source
 */
export function wrapForExecution(code: string): string {
  return `export default async function __oagMcpMain(sdk, console) {\n${code}\n}\n`;
}
 
/**
 * Wrap agent code for type checking against the global `sdk` declaration.
 *
 * @param {String} code - agent code
 * @return {String} TypeScript source
 */
export function wrapForTypecheck(code: string): string {
  return `export {}; async function __oagMcpMain() {\n${code}\n}\n`;
}
 
/**
 * Convert a TypeScript diagnostic to agent coordinates.
 *
 * @param {Object} d - diagnostic
 * @return {Object|undefined} mapped diagnostic
 */
export function mapDiagnostic(d: ts.Diagnostic): Diagnostic | undefined {
  if (!d.file || d.start === undefined) {
    return {
      line: 0,
      column: 0,
      code: d.code,
      message: ts.flattenDiagnosticMessageText(d.messageText, "\n"),
    };
  }
  const pos = d.file.getLineAndCharacterOfPosition(d.start);
  const line = pos.line + 1 - WRAPPER_HEADER_LINES;
  return {
    line: Math.max(line, 1),
    column: pos.character + 1,
    code: d.code,
    message: ts.flattenDiagnosticMessageText(d.messageText, "\n"),
  };
}
 
/** Module-loading constructs agent code may not use, and how to name them. */
const MODULE_LOADERS: ReadonlyArray<[(n: ts.Node) => boolean, string]> = [
  [
    (n) =>
      ts.isCallExpression(n) &&
      n.expression.kind === ts.SyntaxKind.ImportKeyword,
    "dynamic import()",
  ],
  [
    (n) =>
      ts.isMetaProperty(n) && n.keywordToken === ts.SyntaxKind.ImportKeyword,
    "import.meta",
  ],
  [
    (n) =>
      ts.isCallExpression(n) &&
      ts.isIdentifier(n.expression) &&
      n.expression.text === "require",
    "require()",
  ],
  [
    (n) =>
      ts.isImportDeclaration(n) ||
      ts.isImportEqualsDeclaration(n) ||
      (ts.isExportDeclaration(n) && Boolean(n.moduleSpecifier)),
    "module import",
  ],
];
 
/**
 * Find module-loading constructs in agent code.
 *
 * @param {String} code - agent code
 * @param {String} language - "typescript" or "javascript"
 * @return {Array} violation descriptions with line numbers
 */
export function findViolations(
  code: string,
  language: "typescript" | "javascript",
): string[] {
  const sf = ts.createSourceFile(
    language === "typescript" ? "agent.ts" : "agent.js",
    wrapForExecution(code),
    ts.ScriptTarget.ES2022,
    true,
    language === "typescript" ? ts.ScriptKind.TS : ts.ScriptKind.JS,
  );
  const out: string[] = [];
  const visit = (n: ts.Node) => {
    const loader = MODULE_LOADERS.find(([matches]) => matches(n));
    if (loader) {
      const line =
        sf.getLineAndCharacterOfPosition(n.getStart(sf)).line +
        1 -
        WRAPPER_HEADER_LINES;
      out.push(`${loader[1]} at line ${line}`);
    }
    ts.forEachChild(n, visit);
  };
  visit(sf);
  return out;
}
 
/**
 * Validate and transpile agent code into a base64 ES module.
 *
 * @param {String} code - agent code
 * @param {String} language - "typescript" or "javascript"
 * @param {Number} maxBytes - maximum accepted code size
 * @return {Object} prepared code or error
 */
export function prepareCode(
  code: string,
  language: "typescript" | "javascript",
  maxBytes: number,
): PreparedCode {
  if (Buffer.byteLength(code) > maxBytes) {
    return {
      ok: false,
      error: {
        type: "resource_limit",
        reason: "code_too_large",
        message: `Code is ${Buffer.byteLength(code)} bytes; the limit is ${maxBytes}`,
      },
    };
  }
  const result = ts.transpileModule(wrapForExecution(code), {
    fileName: language === "typescript" ? "agent.ts" : "agent.js",
    reportDiagnostics: true,
    compilerOptions: {
      target: ts.ScriptTarget.ES2022,
      module: ts.ModuleKind.ESNext,
      allowJs: true,
      sourceMap: false,
      removeComments: false,
    },
  });
  const syntax = (result.diagnostics ?? [])
    .filter((d) => d.category === ts.DiagnosticCategory.Error)
    .map(mapDiagnostic)
    .filter((d): d is Diagnostic => Boolean(d));
  if (syntax.length > 0) {
    return {
      ok: false,
      error: {
        type: "syntax_error",
        message: `Code has ${syntax.length} syntax error(s): ${syntax[0].message} (line ${syntax[0].line})`,
        diagnostics: syntax.slice(0, 10),
      },
    };
  }
  const violations = findViolations(code, language);
  if (violations.length > 0) {
    return {
      ok: false,
      violations,
      error: {
        type: "permission_denied",
        reason: "import_not_allowed",
        message: `Imports are not allowed; use the provided \`sdk\` binding instead (${violations.slice(0, 3).join("; ")})`,
      },
    };
  }
  return {
    ok: true,
    js: result.outputText,
    moduleBase64: Buffer.from(result.outputText).toString("base64"),
  };
}