Skip to content
Merged
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
49 changes: 49 additions & 0 deletions convex/devTemplateAuditFixtures.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { parseTemplateDocument } from "../src/lib/templateDetail";
import { seed } from "./devTemplateAuditFixtures";

afterEach(() => vi.unstubAllEnvs());
describe("local Template audit fixture", () => {
it.each(["prod:production", "dev:cloud", ""])(
"refuses %s before any storage or database writes",
async (deployment) => {
vi.stubEnv("DEV_AUTH_ENABLED", "1");
vi.stubEnv("CONVEX_DEPLOYMENT", deployment);
vi.stubEnv("DEV_AUTH_CONVEX_DEPLOYMENT", "");
vi.stubEnv("CONVEX_SITE_URL", "http://127.0.0.1:3661");
const storage = { store: vi.fn() };
await expect(
(seed as unknown as { _handler: (ctx: unknown, args: {}) => Promise<unknown> })._handler(
{ storage } as never,
{},
),
).rejects.toThrow("Local Template audit fixture only");
expect(storage.store).not.toHaveBeenCalled();
},
);
it("uses the real unified manifest and stores realistic inert files", async () => {
vi.stubEnv("DEV_AUTH_ENABLED", "1");
vi.stubEnv("CONVEX_DEPLOYMENT", "local:template-audit-test");
vi.stubEnv("CONVEX_SITE_URL", "http://127.0.0.1:3661");
const blobs: Blob[] = [];
const runMutation = vi
.fn()
.mockResolvedValue({ name: "openclaw-music-manager", simulated: true });
await (seed as unknown as { _handler: (ctx: unknown, args: {}) => Promise<unknown> })._handler(
{
storage: {
store: vi.fn(async (blob: Blob) => {
blobs.push(blob);
return "storage:test";
}),
},
runMutation,
} as never,
{},
);
const text = await blobs[0].text();
expect(parseTemplateDocument(text).manifest?.agent.id).toBe("music-manager");
expect(blobs).toHaveLength(5);
expect(runMutation.mock.calls[0][1].files[0].path).toBe("CLAW.md");
});
});
196 changes: 196 additions & 0 deletions convex/devTemplateAuditFixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/** Reusable, explicitly simulated browser fixtures. Never usable against cloud deployments. */
import { makeFunctionReference } from "convex/server";
import { v } from "convex/values";
import { internalAction, internalMutation } from "./functions";
import { isLocalDevAuthEnabled } from "./lib/devAuth";
import { hashSkillFiles } from "./lib/skills/fileHash";

const name = "openclaw-music-manager";
const manifest = {
schemaVersion: 1,
agent: {
id: "music-manager",
name: "Music Manager",
description:
"Organize a personal music library, curate playlists, and prepare weekly listening recommendations.",
},
skills: [{ path: "skills/library" }],
plugins: [{ path: "plugins/player" }],
workspace: { bootstrapFiles: { "AGENTS.md": { source: "workspace/AGENTS.md" } } },
automations: [
{
id: "weekly-discovery",
name: "Weekly listening discoveries",
enabled: false,
schedule: { cron: "0 18 * * 5", timezone: "UTC" },
session: "isolated",
message: "Prepare five listening recommendations from the approved library.",
delivery: { mode: "none" },
},
],
};
const contents =
"---\n" +
JSON.stringify(manifest) +
"\n---\n# Your music, thoughtfully organized\n\nKeep playlists coherent, discover overlooked favorites, and make room for something new.\n\n## Library workflow\n\n- Work only within the music folder the user approves.\n- Ask before moving or deleting tracks.\n- Preview playlist edits before saving them.\n\n## Weekly discoveries\n\nSuggest five tracks and explain what connects them. The included automation starts paused.\n";
export const seed = internalAction({
args: {},
handler: async (ctx) => {
if (!isLocalDevAuthEnabled()) throw new Error("Local Template audit fixture only");
const files = [];
for (const [path, content] of Object.entries({
"CLAW.md": contents,
"package.json": JSON.stringify({ name, version: "1.2.0", openclaw: { template: "CLAW.md" } }),
"workspace/AGENTS.md": "# Music Manager\nAsk before accessing private library folders.\n",
"skills/library/SKILL.md": "# Library\nRead only the user-approved music directory.\n",
"plugins/player/package.json": JSON.stringify({ name: "local-player", version: "1.0.0" }),
})) {
const bytes = new TextEncoder().encode(content);
const sha256 = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)))
.map((x) => x.toString(16).padStart(2, "0"))
.join("");
files.push({
path,
size: bytes.length,
sha256,
storageId: await ctx.storage.store(new Blob([content], { type: "text/plain" })),
contentType: "text/plain",
});
}
return ctx.runMutation(makeFunctionReference<"mutation">("devTemplateAuditFixtures:insert"), {
files,
});
},
});
export const insert = internalMutation({
args: {
files: v.array(
v.object({
path: v.string(),
size: v.number(),
sha256: v.string(),
storageId: v.id("_storage"),
contentType: v.string(),
}),
),
},
handler: async (ctx, { files }) => {
if (!isLocalDevAuthEnabled()) throw new Error("Local Template audit fixture only");
const now = 1794513600000;
const existing = await ctx.db
.query("packages")
.withIndex("by_name", (q) => q.eq("normalizedName", name))
.unique();
if (existing) {
for (const file of files) await ctx.storage.delete(file.storageId);
return { name, simulated: true, existing: true };
}
const userId = await ctx.db.insert("users", {
handle: "ameliomansour",
name: "Amelio Mansour (local fixture)",
createdAt: now,
updatedAt: now,
});
const verification = {
tier: "structural" as const,
scope: "artifact-only" as const,
scanStatus: "clean" as const,
};
const packageId = await ctx.db.insert("packages", {
name,
normalizedName: name,
displayName: "Music Manager",
summary: manifest.agent.description,
ownerUserId: userId,
family: "claw",
channel: "community",
isOfficial: false,
tags: {},
verification,
scanStatus: "clean",
stats: { downloads: 128, installs: 34, stars: 7, versions: 2 },
createdAt: now,
updatedAt: now,
});
let latestReleaseId;
for (const [version, findings] of [
["1.1.0", true],
["1.2.0", false],
] as const) {
const releaseId = await ctx.db.insert("packageReleases", {
packageId,
version,
publicationStatus: "published",
changelog: "Simulated local UI fixture; not a live scanner run.",
distTags: findings ? [] : ["latest"],
files,
integritySha256: await hashSkillFiles(files),
extractedPackageJson: { name, version, openclaw: { template: "CLAW.md" } },
templateInventory: [
{ kind: "skill", source: "bundled", path: "skills/library", name: "Library organizer" },
{ kind: "plugin", source: "bundled", path: "plugins/player", name: "Local player" },
],
verification,
aigAnalysis: {
status: findings ? "suspicious" : "clean",
scannerVersion: "0.2.0",
issueCount: findings ? 2 : 0,
findings: findings
? [
{
ruleId: "MCP-004",
level: "warning",
title: "Library access boundary needs review",
message: "Evidence: Read only the user-approved music directory.",
description:
"Confirm the selected library directory before granting filesystem access.",
file: "skills/library/SKILL.md",
startLine: 1,
endLine: 2,
remediation: "Limit access to the chosen music folder.",
},
{
ruleId: "supplemental.dynamic.workspace-boundary",
level: "note",
message:
"The bundled workspace instructions require confirmation before private folder access.",
file: "workspace/AGENTS.md",
startLine: 2,
},
]
: [],
summary: findings
? "Simulated A.I.G MCP fixture: two findings retained for review."
: "Simulated A.I.G MCP fixture: no findings reported.",
checkedAt: now,
},
llmAnalysis: {
status: "completed",
verdict: findings ? "suspicious" : "benign",
confidence: "high",
summary: findings
? "Review the library access boundary before granting permissions."
: "The stored fixture evidence is consistent with the declared library workflow.",
model: "simulated-local-evidence-judge-not-live",
checkedAt: now,
},
createdBy: userId,
publishActor: { kind: "user", userId },
createdAt: now,
});
if (!findings) latestReleaseId = releaseId;
}
if (latestReleaseId)
await ctx.db.patch(packageId, {
latestReleaseId,
tags: { latest: latestReleaseId },
latestVersionSummary: {
version: "1.2.0",
createdAt: now,
changelog: "Simulated local browser fixture",
verification,
},
});
return { name, packageId, simulated: true };
},
});
37 changes: 37 additions & 0 deletions specs/template-security-audit.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,40 @@ Record the workflow URL, run SHA and receipt with the exact-SHA Deploy Test resu
Do not describe this mechanical proof as full-registry finalization or broad
scanner accuracy. Unit tests use explicitly synthetic responses and are not the
live qualification run. Production rollout remains a separate authorized action.

## Public audit UI identity

Template details link to the canonical publisher Template security-audit subpage,
with the displayed release pinned in the optional version query. Detail and audit
share scoped-first/unscoped-owner-matched lookup, reject other families/owners,
and never substitute a different release for an exact-version read. Anonymous
reads need no manage context. Missing packages/releases, no published release,
rate limiting and registry errors remain distinct. Exact-release reads opt into
error propagation in the shared package API helper: only a genuine HTTP 404 is
missing; HTTP 429 retains rate-limit metadata, and server/network/parse failures
reach the existing retry UI. Legacy best-effort callers keep their null fallback.
The audit route opts out of parent nesting so it neither renders nor loads the
latest detail view during historical navigation, reload or deep links.

The sidebar no longer repeats the Declared contents metadata block. Current
version, install readiness, manifest warnings and provenance-aware inventory
remain intact; artifact identity belongs on the audit detail.

Reuse the shared audit summary/page/findings. Only show stored Template scanner
reports, never a synthetic absent SkillSpector card or skill-only T01–T09 clean
checklist. Current Template scans use native AIG MCP plus an evidence-only judge;
legacy stored AIG/SkillSpector reports remain visible as recorded. The public
projection currently records scanner version but not driver/profile identity:
do not infer MCP from the Template family or version number. Show that limitation
rather than relabel historical evidence. Preserve raw rule IDs (including dynamic
and supplemental IDs), severity, location/range, message, remediation and stored
scanner provenance separately from the final judge verdict. Missing, pending or
failed evidence is not a clean scan. This read-only route grants no new rescan or
export permission.

Local browser evidence can use the guarded internal
`devTemplateAuditFixtures:seed` action. It creates an unscoped Music Manager
fixture under ameliomansour with a clean latest release and a historical release
with MCP/supplemental findings. Both scanner reports and judge verdicts are
explicitly simulated; the fixture is not live scanner-quality evidence. The
fixture refuses non-local dev-auth contexts and is not part of ordinary seeding.
17 changes: 16 additions & 1 deletion src/components/DetailSecuritySummary.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Info } from "lucide-react";
import { useId } from "react";
import { aggregateAuditVerdict, SECURITY_AUDIT_SUBTEXT } from "./securityAuditModel";
import { getScanStatusInfo, type LlmAnalysis } from "./SkillSecurityScanResults";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./ui/tooltip";
Expand All @@ -7,6 +8,7 @@ type DetailSecuritySummaryProps = {
auditHref: string;
llmAnalysis?: LlmAnalysis | null;
githubScanStatus?: string | null;
description?: string;
};

export function auditVerdictMeterLevel(status: string) {
Expand All @@ -30,14 +32,22 @@ export function DetailSecuritySummary({
auditHref,
llmAnalysis,
githubScanStatus,
description,
}: DetailSecuritySummaryProps) {
const descriptionId = useId();
const auditVerdict = llmAnalysis
? aggregateAuditVerdict({ llmAnalysis })
: (githubScanStatus ?? "pending");
const auditVerdictInfo = getScanStatusInfo(auditVerdict);
const meterLevel = auditVerdictMeterLevel(auditVerdict);
return (
<a href={auditHref} className="security-audit-sidebar-value" aria-label="View Security Audit">
<a
href={auditHref}
className="security-audit-sidebar-value"
aria-label="View Security Audit"
aria-describedby={description ? descriptionId : undefined}
title={description}
>
<div className="security-audit-sidebar-value-row">
<span className="security-audit-sidebar-verdict" data-status={auditVerdict}>
{auditVerdictInfo.label}
Expand All @@ -48,6 +58,11 @@ export function DetailSecuritySummary({
<span />
</div>
</div>
{description ? (
<span id={descriptionId} className="sr-only">
{description}
</span>
) : null}
</a>
);
}
Expand Down
Loading
Loading