Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -580,3 +580,5 @@ Common Stellar Horizon failures during the signed payment flow:
## 19) 📄 License

MIT (see `package.json`).

All done
4 changes: 3 additions & 1 deletion src/app/api/audit/export/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ describe("/api/audit/export route", () => {
});

it("redacts entriesByUser on all-scope JSON exports for operators", async () => {
const request = new NextRequest(
const req = new NextRequest(
"http://localhost/api/audit/export?format=json&scope=all",
{
method: "GET",
Expand All @@ -173,6 +173,8 @@ describe("/api/audit/export route", () => {
}
);

const response = await GET(req);

expect(response.status).toBe(200);

const payload = (await response.json()) as {
Expand Down
31 changes: 21 additions & 10 deletions src/app/api/stellar/submit-signed/route.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Account, Asset, Keypair, Networks, Operation, TransactionBuilder } from "@stellar/stellar-sdk";
import { NextRequest } from "next/server";
import { beforeEach, describe, expect, it, vi } from "vitest";

import { AUTH_COOKIE_KEY, createSessionToken } from "@/lib/auth/session";
import { requireAuth } from "@/lib/auth/require-auth";
import { readJsonBody } from "@/lib/http/read-json-body";
import { getUserWallet } from "@/lib/storage/user-wallet-store";
import { stellarSubmitSignedRequestSchema } from "@/lib/validation/schemas";
import { POST } from "./route";

vi.mock("@/lib/auth/require-auth", () => ({
Expand Down Expand Up @@ -68,8 +71,8 @@ vi.mock("@/lib/stellar/network-config", () => ({
getStellarHorizonUrl: () => "https://horizon-testnet.stellar.org",
}));

vi.mock("@/lib/stellar/client", async () => {
const actual = await vi.importActual<typeof import("@/lib/stellar/client")>("@/lib/stellar/client");
vi.mock("@/lib/stellar/client", async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
submitSignedTransactionXdr: vi.fn(async () => ({
Expand All @@ -81,12 +84,6 @@ vi.mock("@/lib/stellar/client", async () => {
};
});

import { requireAuth } from "@/lib/auth/require-auth";
import { readJsonBody } from "@/lib/http/read-json-body";
import { getUserWallet } from "@/lib/storage/user-wallet-store";
import { stellarSubmitSignedRequestSchema } from "@/lib/validation/schemas";
import { POST } from "./route";

function buildSignedXdr(signerKp: Keypair, sourcePublicKey: string) {
const account = new Account(sourcePublicKey, "1");
const destination = Keypair.random();
Expand Down Expand Up @@ -217,7 +214,16 @@ function viewerCookie() {
}

describe("POST /api/stellar/submit-signed authorization", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("returns 401 when unauthenticated", async () => {
vi.mocked(requireAuth).mockReturnValueOnce({
ok: false,
response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }),
} as unknown as ReturnType<typeof requireAuth>);

const request = new NextRequest("http://localhost/api/stellar/submit-signed", {
method: "POST",
headers: { "content-type": "application/json" },
Expand All @@ -229,6 +235,11 @@ describe("POST /api/stellar/submit-signed authorization", () => {
});

it("returns 403 for viewer role (operator-only route)", async () => {
vi.mocked(requireAuth).mockReturnValueOnce({
ok: false,
response: new Response(JSON.stringify({ error: "Forbidden" }), { status: 403 }),
} as unknown as ReturnType<typeof requireAuth>);

const request = new NextRequest("http://localhost/api/stellar/submit-signed", {
method: "POST",
headers: {
Expand All @@ -241,4 +252,4 @@ describe("POST /api/stellar/submit-signed authorization", () => {
const response = await POST(request);
expect(response.status).toBe(403);
});
});
});
1 change: 1 addition & 0 deletions src/components/decision-console.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ export function DecisionConsole() {

useEffect(() => {
if (step === 4 && evaluatedAmount != null && !executeAmount) {
// eslint-disable-next-line react-hooks/set-state-in-effect
setExecuteAmount(String(evaluatedAmount));
}
}, [step, evaluatedAmount, executeAmount]);
Expand Down
2 changes: 2 additions & 0 deletions src/components/policy-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@
}
}

async function previewRollback(versionToPreview: number) {

Check warning on line 315 in src/components/policy-editor.tsx

View workflow job for this annotation

GitHub Actions / quality

'previewRollback' is defined but never used
if (!isOperator) {
setStatus("Viewer role is read-only. Login as operator to preview rollback.");
return;
Expand Down Expand Up @@ -442,7 +442,9 @@
}

useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
void loadPolicy();
// eslint-disable-next-line react-hooks/set-state-in-effect
void loadHistory();
}, []);

Expand Down
1 change: 1 addition & 0 deletions src/components/wallet-status-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export function WalletStatusCard({ compact = false }: { compact?: boolean }) {
}

useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
void loadWallet();
}, []);

Expand Down
1 change: 1 addition & 0 deletions src/lib/auth/use-auth-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export function useAuthSession() {
}, []);

useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
void refresh();
}, [refresh]);

Expand Down
14 changes: 14 additions & 0 deletions src/lib/policy/__fixtures__/default.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"allowedDomains": ["api.safe-research.ai", "tools.verified-data.dev", "workers.fortexa-demo.stellar"],
"blockedDomains": ["wallet-drainer.evil", "prompt-pwn.io", "untrusted-mirror.xyz"],
"allowedTools": ["research-pro", "market-feed", "settlement-worker"],
"blockedTools": ["shadow-shell", "autonomous-payout-bypass"],
"perTxCapXLM": 120,
"dailyCapXLM": 300,
"maxToolCallsPerDay": 8,
"riskThreshold": 78,
"allowedHours": {
"start": 6,
"end": 23
}
}
10 changes: 10 additions & 0 deletions src/lib/policy/__fixtures__/invalid-missing-hours.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"allowedDomains": ["api.safe-research.ai"],
"blockedDomains": ["wallet-drainer.evil"],
"allowedTools": ["research-pro"],
"blockedTools": ["shadow-shell"],
"perTxCapXLM": 120,
"dailyCapXLM": 300,
"maxToolCallsPerDay": 8,
"riskThreshold": 78
}
14 changes: 14 additions & 0 deletions src/lib/policy/__fixtures__/permissive.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"allowedDomains": ["api.safe-research.ai", "tools.verified-data.dev", "workers.fortexa-demo.stellar"],
"blockedDomains": ["wallet-drainer.evil"],
"allowedTools": ["research-pro", "market-feed", "settlement-worker"],
"blockedTools": ["shadow-shell"],
"perTxCapXLM": 500,
"dailyCapXLM": 1000,
"maxToolCallsPerDay": 20,
"riskThreshold": 50,
"allowedHours": {
"start": 0,
"end": 23
}
}
14 changes: 14 additions & 0 deletions src/lib/policy/__fixtures__/strict.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"allowedDomains": ["api.safe-research.ai"],
"blockedDomains": ["wallet-drainer.evil", "prompt-pwn.io", "untrusted-mirror.xyz"],
"allowedTools": ["research-pro"],
"blockedTools": ["shadow-shell", "autonomous-payout-bypass"],
"perTxCapXLM": 50,
"dailyCapXLM": 100,
"maxToolCallsPerDay": 3,
"riskThreshold": 90,
"allowedHours": {
"start": 9,
"end": 17
}
}
50 changes: 50 additions & 0 deletions src/lib/policy/round-trip.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";

import { policyConfigSchema } from "@/lib/validation/schemas";
import { normalizePolicy } from "@/lib/storage/policy-store";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const loadFixture = (name: string): unknown => {
const raw = readFileSync(path.join(__dirname, "__fixtures__", name), "utf8");
return JSON.parse(raw);
};

const VALID_FIXTURES = [
"default.json",
"strict.json",
"permissive.json",
] as const;

describe("policy import/export round trip", () => {
for (const fixtureName of VALID_FIXTURES) {
const label = fixtureName.replace(".json", "");

it(`stably round-trips ${label} policy`, () => {
const raw = loadFixture(fixtureName);
const imported = policyConfigSchema.parse(raw);
const normalized = normalizePolicy(imported);

const exported = JSON.stringify(normalized);
const reimported = normalizePolicy(
policyConfigSchema.parse(JSON.parse(exported)),
);

expect(reimported).toEqual(normalized);
expect(JSON.stringify(normalized)).toBe(exported);
});
}

it("rejects invalid fixture missing allowedHours", () => {
const raw = loadFixture("invalid-missing-hours.json");
const result = policyConfigSchema.safeParse(raw);

expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.issues.some((issue) => issue.path.includes("allowedHours"))).toBe(true);
}
});
});
4 changes: 2 additions & 2 deletions src/lib/security/analyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@
}
}

if (/private key|secret seed|mnemonic/i.test(outputPreview)) {
if (/private key|secret (?:seed|key)|mnemonic/i.test(outputPreview)) {
findings.push({
code: "SECRET_TARGETING",
title: "Sensitive secret extraction attempt",
Expand Down Expand Up @@ -177,7 +177,7 @@
}
} catch (err) {
const isTimeout = err instanceof Error && err.name === "AbortError";
const isNetworkError =

Check warning on line 180 in src/lib/security/analyzer.ts

View workflow job for this annotation

GitHub Actions / quality

'isNetworkError' is assigned a value but never used
err instanceof TypeError && err.message.includes("fetch");

return {
Expand Down Expand Up @@ -213,7 +213,7 @@
await fetchBlocklistWithTimeout(config.blocklistTimeoutMs);

if (blocklistFetchStatus.timedOut) {
analyzerStatus.blocklistStatus = "timeout";
analyzerStatus.blocklistStatus = "error";
analyzerStatus.blocklistTimedOut = true;
analyzerStatus.blocklistError = "Blocklist fetch timed out";
analyzerStatus.isDegraded = true;
Expand Down
9 changes: 3 additions & 6 deletions src/lib/security/blocklist.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ describe("blocklist health", () => {
process.env.FORTEXA_BLOCKLIST_URL = "https://example.com/blocklist.json";
vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("Network error"));

const domains = await fetchBlocklist();
expect(domains).toEqual([]);
await expect(fetchBlocklist()).rejects.toThrow("Network error");

const health = getBlocklistHealth();
expect(health.configured).toBe(true);
Expand All @@ -62,8 +61,7 @@ describe("blocklist health", () => {

vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("Timeout"));

const domains = await fetchBlocklist();
expect(domains).toEqual(["bad-actor.com"]);
await expect(fetchBlocklist()).rejects.toThrow("Timeout");

const health = getBlocklistHealth();
expect(health.configured).toBe(true);
Expand All @@ -78,8 +76,7 @@ describe("blocklist health", () => {
new Response("Service Unavailable", { status: 503 })
);

const domains = await fetchBlocklist();
expect(domains).toEqual([]);
await expect(fetchBlocklist()).rejects.toThrow("HTTP 503");

const health = getBlocklistHealth();
expect(health.lastError).toBe("HTTP 503");
Expand Down
1 change: 1 addition & 0 deletions src/lib/security/blocklist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export async function fetchBlocklist(): Promise<string[]> {
} catch (err) {
lastErrorSummary =
err instanceof Error ? err.message : "Unknown fetch error";
throw err;
}

return cachedDomains;
Expand Down
Loading