diff --git a/src/agent/tools/ton/__tests__/jetton-decimals.test.ts b/src/agent/tools/ton/__tests__/jetton-decimals.test.ts new file mode 100644 index 00000000..ea558c29 --- /dev/null +++ b/src/agent/tools/ton/__tests__/jetton-decimals.test.ts @@ -0,0 +1,107 @@ +import { Address, type MessageRelaxed } from "@ton/core"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + loadWallet: vi.fn(), + getCachedTonClient: vi.fn(), + openWallet: vi.fn(), + tonapiFetch: vi.fn(), + sendWalletTx: vi.fn(), +})); + +vi.mock("../../../../ton/wallet-service.js", () => ({ + loadWallet: mocks.loadWallet, + getCachedTonClient: mocks.getCachedTonClient, +})); +vi.mock("../../../../ton/wallet-open.js", () => ({ openWallet: mocks.openWallet })); +vi.mock("../../../../constants/api-endpoints.js", () => ({ tonapiFetch: mocks.tonapiFetch })); +vi.mock("../../../../ton/confirm.js", () => ({ + sendWalletTx: mocks.sendWalletTx, + tonExplorerTxUrl: () => "https://example.invalid/transaction", +})); + +import { jettonSendExecutor } from "../jetton-send.js"; +import { jettonBalancesExecutor } from "../jetton-balances.js"; + +const owner = Address.parseRaw(`0:${"11".repeat(32)}`); +const master = Address.parseRaw(`0:${"22".repeat(32)}`); +const recipient = Address.parseRaw(`0:${"33".repeat(32)}`); +const jettonWallet = Address.parseRaw(`0:${"44".repeat(32)}`); +const context = {} as never; + +function respondWithBalance(decimals: number | null | undefined, balance = "2000000000") { + mocks.tonapiFetch.mockResolvedValue( + new Response( + JSON.stringify({ + balances: [ + { + balance, + wallet_address: { address: jettonWallet.toString() }, + jetton: { address: master.toString(), decimals, symbol: "TEST", name: "Test" }, + }, + ], + }) + ) + ); +} + +beforeEach(() => { + vi.clearAllMocks(); + mocks.loadWallet.mockReturnValue({ address: owner.toString() }); + mocks.getCachedTonClient.mockResolvedValue({}); + mocks.openWallet.mockResolvedValue({ keyPair: { secretKey: Buffer.alloc(64) }, contract: {} }); + mocks.sendWalletTx.mockResolvedValue({ hash: "test-hash" }); +}); + +describe("jetton decimal conversion", () => { + it.each([ + { decimals: 0, amount: 1, expected: 1n }, + { decimals: 9, amount: 1.25, expected: 1250000000n }, + { decimals: 6, amount: 1, expected: 1000000n }, + { decimals: undefined, amount: 1, expected: 1000000000n }, + { decimals: null, amount: 1, expected: 1000000000n }, + ])("encodes $amount tokens with decimals=$decimals as $expected units", async (test) => { + respondWithBalance(test.decimals); + const result = await jettonSendExecutor( + { jetton_address: master.toString(), to: recipient.toString(), amount: test.amount }, + context + ); + expect(result.success).toBe(true); + expect(mocks.sendWalletTx).toHaveBeenCalledOnce(); + const { messages } = mocks.sendWalletTx.mock.calls[0][2] as { messages: MessageRelaxed[] }; + expect(messages[0].info.type).toBe("internal"); + if (messages[0].info.type === "internal") { + expect(messages[0].info.dest.equals(jettonWallet)).toBe(true); + } + const body = messages[0].body.beginParse(); + expect(body.loadUint(32)).toBe(0xf8a7ea5); + expect(body.loadUintBig(64)).toBe(0n); + expect(body.loadCoins()).toBe(test.expected); + expect(body.loadAddress().equals(recipient)).toBe(true); + }); + + it("rejects insufficient zero-decimal balance before reaching the send boundary", async () => { + respondWithBalance(0, "2"); + expect( + await jettonSendExecutor( + { jetton_address: master.toString(), to: recipient.toString(), amount: 3 }, + context + ) + ).toMatchObject({ success: false }); + expect(mocks.sendWalletTx).not.toHaveBeenCalled(); + }); + + it.each([ + { decimals: 0, raw: "1234567890", expected: "1234567890", scale: 0 }, + { decimals: 9, raw: "1234000000", expected: "1.234", scale: 9 }, + { decimals: undefined, raw: "1234000000", expected: "1.234", scale: 9 }, + { decimals: null, raw: "1234000000", expected: "1.234", scale: 9 }, + ])("displays a balance with decimals=$decimals at its actual scale", async (test) => { + respondWithBalance(test.decimals, test.raw); + const result = await jettonBalancesExecutor({}, context); + expect(result).toMatchObject({ + success: true, + data: { balances: [{ balance: test.expected, rawBalance: test.raw, decimals: test.scale }] }, + }); + }); +}); diff --git a/src/agent/tools/ton/jetton-balances.ts b/src/agent/tools/ton/jetton-balances.ts index 5854d970..9b254784 100644 --- a/src/agent/tools/ton/jetton-balances.ts +++ b/src/agent/tools/ton/jetton-balances.ts @@ -68,7 +68,7 @@ export const jettonBalancesExecutor: ToolExecutor = async } // Convert balance from blockchain units to human-readable - const decimals = jetton.decimals || 9; + const decimals = jetton.decimals ?? 9; const rawBalance = BigInt(balance); const divisor = BigInt(10 ** decimals); const wholePart = rawBalance / divisor; diff --git a/src/agent/tools/ton/jetton-send.ts b/src/agent/tools/ton/jetton-send.ts index 51d21d76..fd50f436 100644 --- a/src/agent/tools/ton/jetton-send.ts +++ b/src/agent/tools/ton/jetton-send.ts @@ -101,7 +101,7 @@ export const jettonSendExecutor: ToolExecutor = async ( } const senderJettonWallet = jettonBalance.wallet_address.address; - const decimals = jettonBalance.jetton.decimals || 9; + const decimals = jettonBalance.jetton.decimals ?? 9; const symbol = jettonBalance.jetton.symbol || "JETTON"; const currentBalance = BigInt(jettonBalance.balance); diff --git a/src/agent/tools/workspace/__tests__/mutations.test.ts b/src/agent/tools/workspace/__tests__/mutations.test.ts new file mode 100644 index 00000000..3dfbde8d --- /dev/null +++ b/src/agent/tools/workspace/__tests__/mutations.test.ts @@ -0,0 +1,156 @@ +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("../../../../workspace/paths.js", async (importOriginal) => { + const original = await importOriginal(); + return { + ...original, + WORKSPACE_ROOT: mkdtempSync(join(tmpdir(), "teleton-mutations-")), + }; +}); + +import { PROTECTED_WORKSPACE_FILES, WORKSPACE_ROOT } from "../../../../workspace/paths.js"; +import { validateWritePath } from "../../../../workspace/validator.js"; +import { workspaceDeleteExecutor } from "../delete.js"; +import { workspaceRenameExecutor } from "../rename.js"; + +const context = {} as never; +const policyFiles = ["SOUL.md", "STRATEGY.md", "SECURITY.md"]; + +beforeEach(() => { + rmSync(WORKSPACE_ROOT, { recursive: true, force: true }); + mkdirSync(WORKSPACE_ROOT); + for (const filename of PROTECTED_WORKSPACE_FILES) { + writeFileSync(join(WORKSPACE_ROOT, filename), `original ${filename}`); + } + writeFileSync(join(WORKSPACE_ROOT, "replacement.txt"), "replacement"); +}); + +afterAll(() => rmSync(WORKSPACE_ROOT, { recursive: true, force: true })); + +describe("workspace policy-file mutations", () => { + it.each(policyFiles)("rejects renaming %s away without changing files", async (filename) => { + await expect( + workspaceRenameExecutor({ from: filename, to: "moved.txt" }, context) + ).rejects.toThrow("Cannot rename"); + expect(readFileSync(join(WORKSPACE_ROOT, filename), "utf8")).toBe(`original ${filename}`); + expect(existsSync(join(WORKSPACE_ROOT, "moved.txt"))).toBe(false); + }); + + it.each(policyFiles)("rejects replacing %s without changing either file", async (filename) => { + await expect( + workspaceRenameExecutor({ from: "replacement.txt", to: filename, overwrite: true }, context) + ).rejects.toThrow("Cannot rename"); + expect(readFileSync(join(WORKSPACE_ROOT, filename), "utf8")).toBe(`original ${filename}`); + expect(readFileSync(join(WORKSPACE_ROOT, "replacement.txt"), "utf8")).toBe("replacement"); + }); + + it.each(["./SECURITY.md", "folder/../SECURITY.md", "%2553ECURITY.md", "security.md"])( + "rejects normalized or case aliases: %s", + async (filename) => { + expect(() => validateWritePath(filename)).toThrow("Cannot write"); + await expect( + workspaceRenameExecutor({ from: "replacement.txt", to: filename, overwrite: true }, context) + ).rejects.toThrow("Cannot rename"); + expect(readFileSync(join(WORKSPACE_ROOT, "SECURITY.md"), "utf8")).toBe( + "original SECURITY.md" + ); + } + ); + + it("rejects creating an immutable destination before creating its parents", async () => { + await expect( + workspaceRenameExecutor({ from: "replacement.txt", to: "new/SOUL.md" }, context) + ).rejects.toThrow("Cannot rename"); + expect(existsSync(join(WORKSPACE_ROOT, "new"))).toBe(false); + expect(existsSync(join(WORKSPACE_ROOT, "replacement.txt"))).toBe(true); + }); + + it("preserves ordinary move, parent creation and overwrite behavior", async () => { + expect( + await workspaceRenameExecutor({ from: "replacement.txt", to: "new/file.txt" }, context) + ).toMatchObject({ success: true }); + writeFileSync(join(WORKSPACE_ROOT, "second.txt"), "second"); + expect( + await workspaceRenameExecutor({ from: "second.txt", to: "new/file.txt" }, context) + ).toMatchObject({ success: false }); + expect( + await workspaceRenameExecutor( + { from: "second.txt", to: "new/file.txt", overwrite: true }, + context + ) + ).toMatchObject({ success: true }); + expect(readFileSync(join(WORKSPACE_ROOT, "new/file.txt"), "utf8")).toBe("second"); + }); + + it.each(PROTECTED_WORKSPACE_FILES)( + "preserves direct delete protection for %s", + async (filename) => { + expect(await workspaceDeleteExecutor({ path: filename }, context)).toMatchObject({ + success: false, + }); + expect(readFileSync(join(WORKSPACE_ROOT, filename), "utf8")).toBe(`original ${filename}`); + } + ); + + it.each([".", "folder/..", "%2e", WORKSPACE_ROOT])( + "rejects deleting the workspace root via %s", + async (path) => { + expect(await workspaceDeleteExecutor({ path, recursive: true }, context)).toMatchObject({ + success: false, + }); + expect(readFileSync(join(WORKSPACE_ROOT, "SECURITY.md"), "utf8")).toBe( + "original SECURITY.md" + ); + expect(existsSync(join(WORKSPACE_ROOT, "replacement.txt"))).toBe(true); + } + ); + + it.each(["SECURITY.md", "soul.md", "MEMORY.md"])( + "rejects recursive deletion of a tree containing %s before removing ordinary files", + async (filename) => { + mkdirSync(join(WORKSPACE_ROOT, "nested/deep"), { recursive: true }); + writeFileSync(join(WORKSPACE_ROOT, "nested/ordinary.txt"), "keep"); + writeFileSync(join(WORKSPACE_ROOT, "nested/deep", filename), "protected"); + expect( + await workspaceDeleteExecutor({ path: "nested", recursive: true }, context) + ).toMatchObject({ success: false }); + expect(readFileSync(join(WORKSPACE_ROOT, "nested/ordinary.txt"), "utf8")).toBe("keep"); + expect(readFileSync(join(WORKSPACE_ROOT, "nested/deep", filename), "utf8")).toBe("protected"); + } + ); + + it("deletes ordinary files and directories without following descendant symlinks", async () => { + const outside = mkdtempSync(join(tmpdir(), "teleton-mutations-outside-")); + try { + writeFileSync(join(outside, "SECURITY.md"), "outside"); + mkdirSync(join(WORKSPACE_ROOT, "ordinary/deep"), { recursive: true }); + writeFileSync(join(WORKSPACE_ROOT, "ordinary/deep/file.txt"), "remove"); + symlinkSync(outside, join(WORKSPACE_ROOT, "ordinary/link")); + expect( + await workspaceDeleteExecutor({ path: "ordinary", recursive: true }, context) + ).toMatchObject({ success: true }); + expect(existsSync(join(WORKSPACE_ROOT, "ordinary"))).toBe(false); + expect(readFileSync(join(outside, "SECURITY.md"), "utf8")).toBe("outside"); + expect(await workspaceDeleteExecutor({ path: "replacement.txt" }, context)).toMatchObject({ + success: true, + }); + mkdirSync(join(WORKSPACE_ROOT, "empty")); + expect(await workspaceDeleteExecutor({ path: "empty" }, context)).toMatchObject({ + success: true, + }); + } finally { + rmSync(outside, { recursive: true, force: true }); + } + }); +}); diff --git a/src/agent/tools/workspace/delete.ts b/src/agent/tools/workspace/delete.ts index 7eb0d11a..9879d3f1 100644 --- a/src/agent/tools/workspace/delete.ts +++ b/src/agent/tools/workspace/delete.ts @@ -3,7 +3,11 @@ import { Type } from "@sinclair/typebox"; import { unlinkSync, rmdirSync, readdirSync, rmSync } from "fs"; import type { Tool, ToolExecutor } from "../types.js"; -import { validatePath, PROTECTED_WORKSPACE_FILES } from "../../../workspace/index.js"; +import { + assertDeletablePath, + validatePath, + WorkspaceSecurityError, +} from "../../../workspace/index.js"; interface WorkspaceDeleteParams { path: string; @@ -33,14 +37,14 @@ export const workspaceDeleteExecutor: ToolExecutor = asyn // Validate the path const validated = validatePath(path, false); - // Check if it's a protected file - if (PROTECTED_WORKSPACE_FILES.includes(validated.filename)) { - return { - success: false, - error: - `Cannot delete protected file: ${validated.filename}. ` + - `This file is essential for the agent's operation.`, - }; + // Check the entire target before removing any part of a directory tree. + try { + assertDeletablePath(validated, path, recursive); + } catch (error) { + if (error instanceof WorkspaceSecurityError) { + return { success: false, error: error.message }; + } + throw error; } if (validated.isDirectory) { diff --git a/src/agent/tools/workspace/rename.ts b/src/agent/tools/workspace/rename.ts index 85b46d1a..9121ebc6 100644 --- a/src/agent/tools/workspace/rename.ts +++ b/src/agent/tools/workspace/rename.ts @@ -5,7 +5,7 @@ import { renameSync, existsSync } from "fs"; import { dirname } from "path"; import { mkdirSync } from "fs"; import type { Tool, ToolExecutor } from "../types.js"; -import { validatePath } from "../../../workspace/index.js"; +import { assertMutablePath, validatePath } from "../../../workspace/index.js"; interface WorkspaceRenameParams { from: string; @@ -38,6 +38,7 @@ export const workspaceRenameExecutor: ToolExecutor = asyn // Validate source path (must exist) const validatedFrom = validatePath(from, false); + assertMutablePath(validatedFrom, from, "rename"); if (validatedFrom.isDirectory) { return { @@ -48,6 +49,7 @@ export const workspaceRenameExecutor: ToolExecutor = asyn // Validate destination path (may not exist yet) const validatedTo = validatePath(to, true); + assertMutablePath(validatedTo, to, "rename"); // Check if destination already exists if (validatedTo.exists && !overwrite) { diff --git a/src/workspace/__tests__/validator.test.ts b/src/workspace/__tests__/validator.test.ts index 055e516d..0192f812 100644 --- a/src/workspace/__tests__/validator.test.ts +++ b/src/workspace/__tests__/validator.test.ts @@ -23,6 +23,14 @@ vi.mock("../paths.js", async () => { WORKSPACE_ROOT: tempWorkspace, TELETON_ROOT: join(tempWorkspace, ".."), WORKSPACE_PATHS: {}, + PROTECTED_WORKSPACE_FILES: [ + "SOUL.md", + "STRATEGY.md", + "SECURITY.md", + "MEMORY.md", + "IDENTITY.md", + "USER.md", + ], ALLOWED_EXTENSIONS: { images: [".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp"], audio: [".mp3", ".ogg", ".wav", ".m4a", ".opus"], diff --git a/src/workspace/index.ts b/src/workspace/index.ts index 28ffbd4e..ff5778df 100644 --- a/src/workspace/index.ts +++ b/src/workspace/index.ts @@ -14,6 +14,8 @@ export { validatePath, validateReadPath, validateWritePath, + assertMutablePath, + assertDeletablePath, validateDirectory, isWithinWorkspace, sanitizeFilename, diff --git a/src/workspace/validator.ts b/src/workspace/validator.ts index 6db5e526..d9258b50 100644 --- a/src/workspace/validator.ts +++ b/src/workspace/validator.ts @@ -3,7 +3,12 @@ import { existsSync, lstatSync, readdirSync } from "fs"; import { resolve, normalize, relative, extname, basename, join, sep } from "path"; import { homedir } from "os"; -import { WORKSPACE_ROOT, ALLOWED_EXTENSIONS, MAX_FILE_SIZES } from "./paths.js"; +import { + WORKSPACE_ROOT, + ALLOWED_EXTENSIONS, + MAX_FILE_SIZES, + PROTECTED_WORKSPACE_FILES, +} from "./paths.js"; import { MAX_FILENAME_LENGTH } from "../constants/limits.js"; /** @@ -184,6 +189,57 @@ export function validateReadPath(inputPath: string): ValidatedPath { // Owner configuration files that cannot be overwritten by the agent const IMMUTABLE_FILES = ["SOUL.md", "STRATEGY.md", "SECURITY.md"]; +function matchesProtectedFile(filename: string, names: readonly string[]): boolean { + // Reserve case aliases too, including on case-insensitive filesystems. + return names.some((name) => name.toLowerCase() === filename.toLowerCase()); +} + +export function assertMutablePath( + validated: ValidatedPath, + inputPath: string, + operation: "write" | "rename" = "write" +): void { + if (matchesProtectedFile(validated.filename, IMMUTABLE_FILES)) { + throw new WorkspaceSecurityError( + `Cannot ${operation === "write" ? "write to" : operation} ${validated.filename}. This file is configured by the owner. Use memory_write instead.`, + inputPath + ); + } +} + +export function assertDeletablePath( + validated: ValidatedPath, + inputPath: string, + recursive: boolean +): void { + if (validated.relativePath === "") { + throw new WorkspaceSecurityError("Cannot delete the workspace root.", inputPath); + } + + const checkName = (filename: string): void => { + if (matchesProtectedFile(filename, PROTECTED_WORKSPACE_FILES)) { + throw new WorkspaceSecurityError( + `Cannot delete protected file: ${filename}. This file is essential for the agent's operation.`, + inputPath + ); + } + }; + checkName(validated.filename); + + if (recursive && validated.isDirectory) { + const pending = [validated.absolutePath]; + while (pending.length > 0) { + const directory = pending.pop(); + if (directory === undefined) break; + for (const entry of readdirSync(directory, { withFileTypes: true })) { + checkName(entry.name); + // Directory entries do not follow symlinks into other trees. + if (entry.isDirectory()) pending.push(join(directory, entry.name)); + } + } + } +} + export function validateWritePath( inputPath: string, fileType?: keyof typeof ALLOWED_EXTENSIONS @@ -191,12 +247,7 @@ export function validateWritePath( const validated = validatePath(inputPath, true); // SECURITY: Block writes to owner-only configuration files - if (IMMUTABLE_FILES.includes(validated.filename)) { - throw new WorkspaceSecurityError( - `Cannot write to ${validated.filename}. This file is configured by the owner. Use memory_write instead.`, - inputPath - ); - } + assertMutablePath(validated, inputPath); // Check extension if type specified (OPTIONAL - not enforced by default) if (fileType && ALLOWED_EXTENSIONS[fileType]) {