An open-source, faster Devin alternative
TypeScript
feat: add hook exposure security alerts
Igor Zalutski3ad291c9e789
diff --git a/cloudflare-workers/api-edge/migrations/0003_agent_security_notifications.sql b/cloudflare-workers/api-edge/migrations/0003_agent_security_notifications.sqlnew file mode 100644index 00000000..46cd8ec6--- /dev/null+++ b/cloudflare-workers/api-edge/migrations/0003_agent_security_notifications.sql@@ -0,0 +1,39 @@+-- Durable owner/admin alerts for exposed Agent Hook credentials.+-- The security event is server-authored and deliberately carries no reported+-- token, repository/location metadata, request body, or arbitrary copy.++CREATE TABLE IF NOT EXISTS agent_security_notifications (+ id TEXT PRIMARY KEY,+ org_id TEXT NOT NULL,+ agent_id TEXT NOT NULL,+ hook_id TEXT NOT NULL,+ kind TEXT NOT NULL CHECK (kind = 'secret_exposure'),+ occurred_at INTEGER NOT NULL,+ received_at INTEGER NOT NULL,+ acknowledged_at INTEGER,+ acknowledged_by TEXT,+ CHECK (+ substr(id, 1, 4) = 'hse_' AND length(id) = 28 AND+ substr(id, 5) NOT GLOB '*[^0-9a-f]*'+ ),+ CHECK (+ substr(agent_id, 1, 4) = 'agt_' AND length(agent_id) = 28 AND+ substr(agent_id, 5) NOT GLOB '*[^0-9a-f]*'+ ),+ CHECK (+ substr(hook_id, 1, 3) = 'hk_' AND length(hook_id) = 27 AND+ substr(hook_id, 4) NOT GLOB '*[^0-9a-f]*'+ ),+ CHECK (+ (acknowledged_at IS NULL AND acknowledged_by IS NULL) OR+ (acknowledged_at IS NOT NULL AND acknowledged_by IS NOT NULL)+ )+);++CREATE INDEX IF NOT EXISTS idx_agent_security_notifications_org_ack+ ON agent_security_notifications (+ org_id,+ acknowledged_at,+ occurred_at DESC,+ id DESC+ );diff --git a/cloudflare-workers/api-edge/schema-snapshots/current_schema.sql b/cloudflare-workers/api-edge/schema-snapshots/current_schema.sqlindex 14078f57..05f6d7d8 100644--- a/cloudflare-workers/api-edge/schema-snapshots/current_schema.sql+++ b/cloudflare-workers/api-edge/schema-snapshots/current_schema.sql@@ -19,6 +19,34 @@ CREATE TABLE agent_subscriptions (cancelled_at INTEGER);+CREATE TABLE agent_security_notifications (+ id TEXT PRIMARY KEY,+ org_id TEXT NOT NULL,+ agent_id TEXT NOT NULL,+ hook_id TEXT NOT NULL,+ kind TEXT NOT NULL CHECK (kind = 'secret_exposure'),+ occurred_at INTEGER NOT NULL,+ received_at INTEGER NOT NULL,+ acknowledged_at INTEGER,+ acknowledged_by TEXT,+ CHECK (+ substr(id, 1, 4) = 'hse_' AND length(id) = 28 AND+ substr(id, 5) NOT GLOB '*[^0-9a-f]*'+ ),+ CHECK (+ substr(agent_id, 1, 4) = 'agt_' AND length(agent_id) = 28 AND+ substr(agent_id, 5) NOT GLOB '*[^0-9a-f]*'+ ),+ CHECK (+ substr(hook_id, 1, 3) = 'hk_' AND length(hook_id) = 27 AND+ substr(hook_id, 4) NOT GLOB '*[^0-9a-f]*'+ ),+ CHECK (+ (acknowledged_at IS NULL AND acknowledged_by IS NULL) OR+ (acknowledged_at IS NOT NULL AND acknowledged_by IS NOT NULL)+ )+);+CREATE TABLE api_keys (id TEXT PRIMARY KEY,org_id TEXT NOT NULL,@@ -262,6 +290,14 @@ CREATE TABLE webhook_idempotency (CREATE INDEX idx_agent_subs_org ON agent_subscriptions(org_id);+CREATE INDEX idx_agent_security_notifications_org_ack+ ON agent_security_notifications (+ org_id,+ acknowledged_at,+ occurred_at DESC,+ id DESC+ );+CREATE UNIQUE INDEX idx_agent_subs_unique ON agent_subscriptions(org_id, agent_id, feature);CREATE INDEX idx_api_keys_hash ON api_keys(key_hash);diff --git a/cloudflare-workers/api-edge/src/agent_security_notifications.test.ts b/cloudflare-workers/api-edge/src/agent_security_notifications.test.tsnew file mode 100644index 00000000..aaf93439--- /dev/null+++ b/cloudflare-workers/api-edge/src/agent_security_notifications.test.ts@@ -0,0 +1,320 @@+import { describe, expect, it } from "vitest";+import {+ acknowledgeAgentSecurityNotification,+ listAgentSecurityNotifications,+ receiveAgentSecurityNotification,+ type AgentSecurityCaller,+ type AgentSecurityNotificationsEnv,+} from "./agent_security_notifications";++const SECRET = "security-notification-secret";+const NOW = 1_783_526_400;+const ORG_A = "11111111-1111-4111-8111-111111111111";+const ORG_B = "22222222-2222-4222-8222-222222222222";+const OWNER: AgentSecurityCaller = { orgID: ORG_A, userID: "usr_owner" };+const ADMIN: AgentSecurityCaller = { orgID: ORG_A, userID: "usr_admin" };+const MEMBER: AgentSecurityCaller = { orgID: ORG_A, userID: "usr_member" };++interface Row {+ id: string;+ org_id: string;+ agent_id: string;+ hook_id: string;+ kind: "secret_exposure";+ occurred_at: number;+ received_at: number;+ acknowledged_at: number | null;+ acknowledged_by: string | null;+}++class MemoryD1 {+ readonly events = new Map<string, Row>();+ readonly roles = new Map<string, string>([+ [`${ORG_A}:usr_owner`, "owner"],+ [`${ORG_A}:usr_admin`, "admin"],+ [`${ORG_A}:usr_member`, "member"],+ [`${ORG_B}:usr_other_owner`, "owner"],+ ]);+ prepares = 0;++ prepare(sql: string) {+ this.prepares += 1;+ const db = this;+ let args: unknown[] = [];+ return {+ bind(...values: unknown[]) {+ args = values;+ return this;+ },+ async run() {+ if (sql.includes("INSERT OR IGNORE INTO agent_security_notifications")) {+ const id = String(args[0]);+ if (db.events.has(id)) return { meta: { changes: 0 } };+ db.events.set(id, {+ id,+ org_id: String(args[1]),+ agent_id: String(args[2]),+ hook_id: String(args[3]),+ kind: args[4] as "secret_exposure",+ occurred_at: Number(args[5]),+ received_at: Number(args[6]),+ acknowledged_at: null,+ acknowledged_by: null,+ });+ return { meta: { changes: 1 } };+ }+ if (sql.includes("UPDATE agent_security_notifications")) {+ const [acknowledgedAt, acknowledgedBy, id, orgID] = args;+ const row = db.events.get(String(id));+ if (!row || row.org_id !== orgID || row.acknowledged_at !== null) {+ return { meta: { changes: 0 } };+ }+ row.acknowledged_at = Number(acknowledgedAt);+ row.acknowledged_by = String(acknowledgedBy);+ return { meta: { changes: 1 } };+ }+ throw new Error(`unexpected run SQL: ${sql}`);+ },+ async first<T>() {+ if (sql.includes("SELECT role FROM org_memberships")) {+ const role = db.roles.get(`${args[0]}:${args[1]}`);+ return (role ? { role } : null) as T | null;+ }+ if (sql.includes("FROM agent_security_notifications WHERE id=?1 AND org_id=?2")) {+ const row = db.events.get(String(args[0]));+ return (row && row.org_id === args[1] ? { id: row.id } : null) as T | null;+ }+ if (sql.includes("FROM agent_security_notifications WHERE id=?1")) {+ return (db.events.get(String(args[0])) ?? null) as T | null;+ }+ throw new Error(`unexpected first SQL: ${sql}`);+ },+ async all<T>() {+ if (!sql.includes("FROM agent_security_notifications")) {+ throw new Error(`unexpected all SQL: ${sql}`);+ }+ const orgID = String(args[0]);+ const unacknowledgedOnly = sql.includes("acknowledged_at IS NULL");+ const hasCursor = sql.includes("occurred_at <");+ const cursorOccurredAt = hasCursor ? Number(args[1]) : null;+ const cursorID = hasCursor ? String(args[2]) : null;+ const limit = Number(args.at(-1));+ const results = [...db.events.values()]+ .filter((row) => row.org_id === orgID)+ .filter((row) => !unacknowledgedOnly || row.acknowledged_at === null)+ .filter((row) => !hasCursor+ || row.occurred_at < cursorOccurredAt!+ || (row.occurred_at === cursorOccurredAt && row.id < cursorID!))+ .sort((left, right) => right.occurred_at - left.occurred_at || right.id.localeCompare(left.id))+ .slice(0, limit);+ return { results: results as T[] };+ },+ };+ }+}++function env(db = new MemoryD1()): AgentSecurityNotificationsEnv {+ return {+ OPENCOMPUTER_DB: db as unknown as D1Database,+ OC_SECURITY_NOTIFICATION_SECRET: SECRET,+ };+}++function event(overrides: Partial<Record<keyof Row, unknown>> = {}) {+ return {+ id: "hse_aaaaaaaaaaaaaaaaaaaaaaaa",+ org_id: ORG_A,+ agent_id: "agt_bbbbbbbbbbbbbbbbbbbbbbbb",+ hook_id: "hk_cccccccccccccccccccccccc",+ kind: "secret_exposure",+ occurred_at: "2026-07-08T00:00:00.000Z",+ ...overrides,+ };+}++async function hmacHex(data: string): Promise<string> {+ const key = await crypto.subtle.importKey(+ "raw",+ new TextEncoder().encode(SECRET),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(data));+ return [...new Uint8Array(signature)]+ .map((byte) => byte.toString(16).padStart(2, "0"))+ .join("");+}++async function signedRequest(+ body: string,+ options: { timestamp?: string; signature?: string; contentType?: string } = {},+) {+ const timestamp = options.timestamp ?? String(NOW);+ const signature = options.signature ?? `v1=${await hmacHex(`${timestamp}.${body}`)}`;+ return new Request("https://app.opencomputer.dev/internal/agent-security-notifications", {+ method: "POST",+ headers: {+ "content-type": options.contentType ?? "application/json",+ "x-oc-security-timestamp": timestamp,+ "x-oc-security-signature": signature,+ },+ body,+ });+}++async function receive(+ db: MemoryD1,+ payload: unknown = event(),+ options: Parameters<typeof signedRequest>[1] = {},+) {+ const body = typeof payload === "string" ? payload : JSON.stringify(payload);+ return receiveAgentSecurityNotification(await signedRequest(body, options), env(db), NOW);+}++function seed(db: MemoryD1, row: Partial<Row> & Pick<Row, "id">) {+ db.events.set(row.id, {+ id: row.id,+ org_id: row.org_id ?? ORG_A,+ agent_id: row.agent_id ?? "agt_bbbbbbbbbbbbbbbbbbbbbbbb",+ hook_id: row.hook_id ?? "hk_cccccccccccccccccccccccc",+ kind: "secret_exposure",+ occurred_at: row.occurred_at ?? NOW,+ received_at: row.received_at ?? NOW,+ acknowledged_at: row.acknowledged_at ?? null,+ acknowledged_by: row.acknowledged_by ?? null,+ });+}++describe("Agent Hook security notification receiver", () => {+ it("commits a verified event, accepts an exact replay, and rejects an id conflict", async () => {+ const db = new MemoryD1();+ expect((await receive(db)).status).toBe(204);+ expect(db.events.size).toBe(1);+ expect((await receive(db)).status).toBe(204);+ expect(db.events.size).toBe(1);++ const conflict = await receive(db, event({ hook_id: "hk_dddddddddddddddddddddddd" }));+ expect(conflict.status).toBe(409);+ expect(await conflict.json()).toEqual({+ error: {+ type: "conflict",+ message: "Security notification id conflicts with an existing event",+ },+ });+ expect(db.events.get("hse_aaaaaaaaaaaaaaaaaaaaaaaa")?.hook_id)+ .toBe("hk_cccccccccccccccccccccccc");+ });++ it("authenticates the raw body before parsing or touching D1", async () => {+ const db = new MemoryD1();+ const response = await receive(db, "not-json", { signature: `v1=${"0".repeat(64)}` });+ expect(response.status).toBe(401);+ expect(db.prepares).toBe(0);+ });++ it("fails closed for stale, malformed, oversized, and unconfigured requests", async () => {+ const db = new MemoryD1();+ expect((await receive(db, event(), { timestamp: String(NOW - 301) })).status).toBe(401);+ expect((await receive(db, { ...event(), arbitrary: true })).status).toBe(400);+ expect((await receive(db, "x".repeat(4 * 1024 + 1))).status).toBe(413);+ expect((await receive(db, event(), { contentType: "text/plain" })).status).toBe(415);++ const body = JSON.stringify(event());+ const unconfigured = await receiveAgentSecurityNotification(+ await signedRequest(body),+ { OPENCOMPUTER_DB: db as unknown as D1Database },+ NOW,+ );+ expect(unconfigured.status).toBe(503);+ expect(db.events.size).toBe(0);+ });+});++describe("Agent Hook security notification dashboard API", () => {+ it("is owner/admin-only, org-scoped, paginated, and cursor-bound to the filter", async () => {+ const db = new MemoryD1();+ seed(db, { id: "hse_000000000000000000000003", occurred_at: NOW + 3 });+ seed(db, { id: "hse_000000000000000000000002", occurred_at: NOW + 2 });+ seed(db, {+ id: "hse_000000000000000000000001",+ occurred_at: NOW + 1,+ acknowledged_at: NOW + 10,+ acknowledged_by: "usr_owner",+ });+ seed(db, { id: "hse_ffffffffffffffffffffffff", org_id: ORG_B, occurred_at: NOW + 4 });++ const member = await listAgentSecurityNotifications(+ new Request("https://app.test/api/dashboard/agent-security-notifications"),+ env(db),+ MEMBER,+ );+ expect(member.status).toBe(403);++ const first = await listAgentSecurityNotifications(+ new Request("https://app.test/api/dashboard/agent-security-notifications?limit=1"),+ env(db),+ OWNER,+ );+ expect(first.status).toBe(200);+ const firstBody = await first.json() as { data: Array<{ id: string }>; next_cursor: string };+ expect(firstBody.data.map((item) => item.id)).toEqual(["hse_000000000000000000000003"]);+ expect(firstBody.next_cursor).toEqual(expect.any(String));++ const second = await listAgentSecurityNotifications(+ new Request(`https://app.test/api/dashboard/agent-security-notifications?limit=1&cursor=${firstBody.next_cursor}`),+ env(db),+ ADMIN,+ );+ const secondBody = await second.json() as { data: Array<{ id: string }>; next_cursor: string | null };+ expect(secondBody.data.map((item) => item.id)).toEqual(["hse_000000000000000000000002"]);+ expect(secondBody.next_cursor).toBeNull();++ const mismatchedFilter = await listAgentSecurityNotifications(+ new Request(`https://app.test/api/dashboard/agent-security-notifications?include_acknowledged=true&cursor=${firstBody.next_cursor}`),+ env(db),+ OWNER,+ );+ expect(mismatchedFilter.status).toBe(400);++ const all = await listAgentSecurityNotifications(+ new Request("https://app.test/api/dashboard/agent-security-notifications?include_acknowledged=true"),+ env(db),+ OWNER,+ );+ const allBody = await all.json() as { data: Array<{ id: string }> };+ expect(allBody.data.map((item) => item.id)).toEqual([+ "hse_000000000000000000000003",+ "hse_000000000000000000000002",+ "hse_000000000000000000000001",+ ]);+ });++ it("acknowledges once and keeps missing and cross-org ids indistinguishable", async () => {+ const db = new MemoryD1();+ const id = "hse_000000000000000000000001";+ seed(db, { id });++ expect((await acknowledgeAgentSecurityNotification(env(db), MEMBER, id, NOW + 1)).status)+ .toBe(403);+ expect((await acknowledgeAgentSecurityNotification(env(db), OWNER, id, NOW + 2)).status)+ .toBe(204);+ expect(db.events.get(id)).toMatchObject({+ acknowledged_at: NOW + 2,+ acknowledged_by: OWNER.userID,+ });+ expect((await acknowledgeAgentSecurityNotification(env(db), ADMIN, id, NOW + 3)).status)+ .toBe(204);+ expect(db.events.get(id)?.acknowledged_at).toBe(NOW + 2);++ const otherOrgCaller = { orgID: ORG_B, userID: "usr_other_owner" };+ expect((await acknowledgeAgentSecurityNotification(env(db), otherOrgCaller, id, NOW + 4)).status)+ .toBe(404);+ expect((await acknowledgeAgentSecurityNotification(+ env(db),+ OWNER,+ "hse_999999999999999999999999",+ NOW + 4,+ )).status).toBe(404);+ });+});diff --git a/cloudflare-workers/api-edge/src/agent_security_notifications.ts b/cloudflare-workers/api-edge/src/agent_security_notifications.tsnew file mode 100644index 00000000..08bc9e77--- /dev/null+++ b/cloudflare-workers/api-edge/src/agent_security_notifications.ts@@ -0,0 +1,369 @@+// Durable, owner/admin-visible alerts for exposed Agent Hook credentials.+//+// The internal receiver authenticates the exact raw body before parsing and+// stores only the frozen server-authored fields from design 017 §12.4. It never+// receives or persists GitHub Match Data or the exposed credential.++export interface AgentSecurityNotificationsEnv {+ OPENCOMPUTER_DB: D1Database;+ OC_SECURITY_NOTIFICATION_SECRET?: string;+}++export interface AgentSecurityCaller {+ orgID: string;+ userID: string;+}++export const AGENT_SECURITY_NOTIFICATION_PATH = "/internal/agent-security-notifications";++const MAX_BODY_BYTES = 4 * 1024;+const SIGNATURE_WINDOW_SECONDS = 5 * 60;+const DEFAULT_PAGE_SIZE = 50;+const MAX_PAGE_SIZE = 100;+const EVENT_ID_RE = /^hse_[0-9a-f]{24}$/;+const AGENT_ID_RE = /^agt_[0-9a-f]{24}$/;+const HOOK_ID_RE = /^hk_[0-9a-f]{24}$/;+const ORG_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;++interface SecurityEventInput {+ id: string;+ org_id: string;+ agent_id: string;+ hook_id: string;+ kind: "secret_exposure";+ occurred_at: string;+}++interface StoredSecurityEvent {+ id: string;+ org_id: string;+ agent_id: string;+ hook_id: string;+ kind: "secret_exposure";+ occurred_at: number;+ received_at: number;+ acknowledged_at: number | null;+ acknowledged_by: string | null;+}++interface CursorV1 {+ v: 1;+ include_acknowledged: boolean;+ occurred_at: number;+ id: string;+}++function json(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: {+ "content-type": "application/json",+ "cache-control": "no-store",+ "x-content-type-options": "nosniff",+ },+ });+}++function fixedError(type: string, message: string, status: number): Response {+ return json({ error: { type, message } }, status);+}++function hexBytes(value: string): Uint8Array | null {+ if (!/^[0-9a-f]{64}$/.test(value)) return null;+ return Uint8Array.from({ length: 32 }, (_, index) =>+ Number.parseInt(value.slice(index * 2, index * 2 + 2), 16),+ );+}++async function validSignature(+ secret: string,+ timestamp: string,+ rawBody: string,+ signature: string,+): Promise<boolean> {+ if (!signature.startsWith("v1=")) return false;+ const bytes = hexBytes(signature.slice(3));+ if (!bytes) return false;+ const key = await crypto.subtle.importKey(+ "raw",+ new TextEncoder().encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["verify"],+ );+ return crypto.subtle.verify(+ "HMAC",+ key,+ bytes,+ new TextEncoder().encode(`${timestamp}.${rawBody}`),+ );+}++function parseCanonicalTimestamp(value: unknown): number | null {+ if (+ typeof value !== "string"+ || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(value)+ ) return null;+ const millis = Date.parse(value);+ if (!Number.isFinite(millis)) return null;+ const canonical = new Date(millis).toISOString();+ if (value !== canonical && value !== canonical.replace(".000Z", "Z")) return null;+ return Math.floor(millis / 1_000);+}++function parseEvent(rawBody: string): { event: SecurityEventInput; occurredAt: number } | null {+ let value: unknown;+ try { value = JSON.parse(rawBody); }+ catch { return null; }+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const record = value as Record<string, unknown>;+ const keys = Object.keys(record).sort();+ if (keys.join(",") !== "agent_id,hook_id,id,kind,occurred_at,org_id") return null;+ const occurredAt = parseCanonicalTimestamp(record.occurred_at);+ if (+ typeof record.id !== "string"+ || typeof record.org_id !== "string"+ || typeof record.agent_id !== "string"+ || typeof record.hook_id !== "string"+ || !EVENT_ID_RE.test(record.id)+ || !ORG_ID_RE.test(record.org_id)+ || !AGENT_ID_RE.test(record.agent_id)+ || !HOOK_ID_RE.test(record.hook_id)+ || record.kind !== "secret_exposure"+ || occurredAt === null+ ) return null;+ return { event: record as unknown as SecurityEventInput, occurredAt };+}++function sameEvent(+ row: StoredSecurityEvent,+ event: SecurityEventInput,+ occurredAt: number,+): boolean {+ return row.id === event.id+ && row.org_id === event.org_id+ && row.agent_id === event.agent_id+ && row.hook_id === event.hook_id+ && row.kind === event.kind+ && row.occurred_at === occurredAt;+}++export async function receiveAgentSecurityNotification(+ req: Request,+ env: AgentSecurityNotificationsEnv,+ nowSeconds = Math.floor(Date.now() / 1_000),+): Promise<Response> {+ if (req.method !== "POST") return fixedError("method_not_allowed", "Method not allowed", 405);+ if (!env.OC_SECURITY_NOTIFICATION_SECRET) {+ return fixedError("unavailable", "Security notification receiver is unavailable", 503);+ }+ if ((req.headers.get("content-type") ?? "").trim().toLowerCase() !== "application/json") {+ return fixedError("unsupported_media", "Content type must be application/json", 415);+ }+ const contentLength = req.headers.get("content-length");+ const declared = contentLength === null ? null : Number(contentLength);+ if (declared !== null && (!Number.isSafeInteger(declared) || declared < 0)) {+ return fixedError("invalid", "Invalid content length", 400);+ }+ if (declared !== null && declared > MAX_BODY_BYTES) {+ return fixedError("payload_too_large", "Payload too large", 413);+ }+ const rawBody = await req.text();+ if (new TextEncoder().encode(rawBody).byteLength > MAX_BODY_BYTES) {+ return fixedError("payload_too_large", "Payload too large", 413);+ }+ const timestamp = req.headers.get("x-oc-security-timestamp") ?? "";+ const signature = req.headers.get("x-oc-security-signature") ?? "";+ const timestampNumber = Number(timestamp);+ if (+ !/^[1-9]\d{9}$/.test(timestamp)+ || !Number.isSafeInteger(timestampNumber)+ || Math.abs(nowSeconds - timestampNumber) > SIGNATURE_WINDOW_SECONDS+ ) {+ return fixedError("unauthorized", "Invalid security notification signature", 401);+ }+ if (!(await validSignature(env.OC_SECURITY_NOTIFICATION_SECRET, timestamp, rawBody, signature))) {+ return fixedError("unauthorized", "Invalid security notification signature", 401);+ }++ const parsed = parseEvent(rawBody);+ if (!parsed) return fixedError("invalid", "Invalid security notification", 400);+ const inserted = await env.OPENCOMPUTER_DB.prepare(+ `INSERT OR IGNORE INTO agent_security_notifications+ (id,org_id,agent_id,hook_id,kind,occurred_at,received_at)+ VALUES (?1,?2,?3,?4,?5,?6,?7)`,+ ).bind(+ parsed.event.id,+ parsed.event.org_id,+ parsed.event.agent_id,+ parsed.event.hook_id,+ parsed.event.kind,+ parsed.occurredAt,+ nowSeconds,+ ).run();+ if ((inserted.meta?.changes ?? 0) > 0) return new Response(null, { status: 204 });++ const existing = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id,org_id,agent_id,hook_id,kind,occurred_at,received_at,+ acknowledged_at,acknowledged_by+ FROM agent_security_notifications WHERE id=?1`,+ ).bind(parsed.event.id).first<StoredSecurityEvent>();+ if (!existing) return fixedError("unavailable", "Security notification storage is unavailable", 503);+ if (!sameEvent(existing, parsed.event, parsed.occurredAt)) {+ return fixedError("conflict", "Security notification id conflicts with an existing event", 409);+ }+ return new Response(null, { status: 204 });+}++function toBase64Url(value: string): string {+ const bytes = new TextEncoder().encode(value);+ let binary = "";+ for (const byte of bytes) binary += String.fromCharCode(byte);+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+}++function fromBase64Url(value: string): string | null {+ if (!/^[A-Za-z0-9_-]{1,512}$/.test(value)) return null;+ const padded = value.replace(/-/g, "+").replace(/_/g, "/")+ + "=".repeat((4 - value.length % 4) % 4);+ try {+ const binary = atob(padded);+ return new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));+ } catch {+ return null;+ }+}++function encodeCursor(cursor: CursorV1): string {+ return toBase64Url(JSON.stringify(cursor));+}++function decodeCursor(+ value: string | null,+ includeAcknowledged: boolean,+): CursorV1 | null | "invalid" {+ if (!value) return null;+ const decoded = fromBase64Url(value);+ if (!decoded) return "invalid";+ try {+ const parsed = JSON.parse(decoded) as Partial<CursorV1>;+ if (+ parsed.v !== 1+ || parsed.include_acknowledged !== includeAcknowledged+ || !Number.isSafeInteger(parsed.occurred_at)+ || Number(parsed.occurred_at) < 0+ || !EVENT_ID_RE.test(String(parsed.id ?? ""))+ ) return "invalid";+ return parsed as CursorV1;+ } catch {+ return "invalid";+ }+}++async function canManageSecurityAlerts(+ env: AgentSecurityNotificationsEnv,+ caller: AgentSecurityCaller,+): Promise<boolean> {+ const membership = await env.OPENCOMPUTER_DB.prepare(+ `SELECT role FROM org_memberships WHERE org_id=?1 AND user_id=?2`,+ ).bind(caller.orgID, caller.userID).first<{ role: string }>();+ return membership?.role === "owner" || membership?.role === "admin";+}++function serializeEvent(row: StoredSecurityEvent) {+ return {+ id: row.id,+ agentId: row.agent_id,+ hookId: row.hook_id,+ kind: row.kind,+ occurredAt: new Date(row.occurred_at * 1_000).toISOString(),+ acknowledgedAt: row.acknowledged_at === null+ ? null+ : new Date(row.acknowledged_at * 1_000).toISOString(),+ acknowledgedBy: row.acknowledged_by,+ };+}++export async function listAgentSecurityNotifications(+ req: Request,+ env: AgentSecurityNotificationsEnv,+ caller: AgentSecurityCaller,+): Promise<Response> {+ if (!(await canManageSecurityAlerts(env, caller))) {+ return fixedError("forbidden", "Organization owner or admin access is required", 403);+ }+ const url = new URL(req.url);+ const includeRaw = url.searchParams.get("include_acknowledged");+ if (includeRaw !== null && includeRaw !== "true" && includeRaw !== "false") {+ return fixedError("invalid", "include_acknowledged must be true or false", 400);+ }+ const includeAcknowledged = includeRaw === "true";+ const limitRaw = url.searchParams.get("limit");+ const requestedLimit = limitRaw === null ? DEFAULT_PAGE_SIZE : Number(limitRaw);+ if (!Number.isInteger(requestedLimit) || requestedLimit < 1) {+ return fixedError("invalid", "limit must be a positive integer", 400);+ }+ const limit = Math.min(requestedLimit, MAX_PAGE_SIZE);+ const cursor = decodeCursor(url.searchParams.get("cursor"), includeAcknowledged);+ if (cursor === "invalid") return fixedError("invalid", "Invalid cursor", 400);++ const clauses = ["org_id=?1"];+ const bindings: unknown[] = [caller.orgID];+ if (!includeAcknowledged) clauses.push("acknowledged_at IS NULL");+ if (cursor) {+ bindings.push(cursor.occurred_at, cursor.id);+ const occurredIndex = bindings.length - 1;+ const idIndex = bindings.length;+ clauses.push(+ `(occurred_at < ?${occurredIndex} OR (occurred_at = ?${occurredIndex} AND id < ?${idIndex}))`,+ );+ }+ bindings.push(limit + 1);+ const limitIndex = bindings.length;+ const result = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id,org_id,agent_id,hook_id,kind,occurred_at,received_at,+ acknowledged_at,acknowledged_by+ FROM agent_security_notifications+ WHERE ${clauses.join(" AND ")}+ ORDER BY occurred_at DESC,id DESC+ LIMIT ?${limitIndex}`,+ ).bind(...bindings).all<StoredSecurityEvent>();+ const rows = result.results ?? [];+ const page = rows.slice(0, limit);+ const last = page.at(-1);+ const nextCursor = rows.length > limit && last+ ? encodeCursor({+ v: 1,+ include_acknowledged: includeAcknowledged,+ occurred_at: last.occurred_at,+ id: last.id,+ })+ : null;+ return json({ data: page.map(serializeEvent), next_cursor: nextCursor });+}++export async function acknowledgeAgentSecurityNotification(+ env: AgentSecurityNotificationsEnv,+ caller: AgentSecurityCaller,+ eventId: string,+ nowSeconds = Math.floor(Date.now() / 1_000),+): Promise<Response> {+ if (!(await canManageSecurityAlerts(env, caller))) {+ return fixedError("forbidden", "Organization owner or admin access is required", 403);+ }+ if (!EVENT_ID_RE.test(eventId)) {+ return fixedError("not_found", "Security notification not found", 404);+ }+ const updated = await env.OPENCOMPUTER_DB.prepare(+ `UPDATE agent_security_notifications+ SET acknowledged_at=?1,acknowledged_by=?2+ WHERE id=?3 AND org_id=?4 AND acknowledged_at IS NULL`,+ ).bind(nowSeconds, caller.userID, eventId, caller.orgID).run();+ if ((updated.meta?.changes ?? 0) > 0) return new Response(null, { status: 204 });+ const existing = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id FROM agent_security_notifications WHERE id=?1 AND org_id=?2`,+ ).bind(eventId, caller.orgID).first<{ id: string }>();+ return existing+ ? new Response(null, { status: 204 })+ : fixedError("not_found", "Security notification not found", 404);+}diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex c72d3efb..6be85a8b 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -27,6 +27,10 @@ import {autumnOpenCustomerPortal,} from "./autumn_webhook";import { handleWebhooksAPI, type WebhookEnv } from "./webhooks";+import {+ acknowledgeAgentSecurityNotification,+ listAgentSecurityNotifications,+} from "./agent_security_notifications";export interface DashboardEnv {OPENCOMPUTER_DB: D1Database;@@ -973,6 +977,17 @@ export async function handleDashboard(if (sub === "/org/custom-domain" && method === "DELETE") return handleDeleteCustomDomain(req, env, caller);if (sub === "/org/custom-domain/refresh" && method === "POST") return handleRefreshCustomDomain(req, env, caller);+ // ── Agent Hook exposure alerts ──────────────────────────────────────────+ if (sub === "/agent-security-notifications" && method === "GET") {+ return listAgentSecurityNotifications(req, env, caller);+ }+ {+ const m = sub.match(/^\/agent-security-notifications\/(hse_[0-9a-f]{24})\/acknowledge$/);+ if (m && method === "POST") {+ return acknowledgeAgentSecurityNotification(env, caller, m[1]);+ }+ }+// ── api keys ───────────────────────────────────────────────────────────if (sub === "/api-keys" && method === "GET") return handleListAPIKeys(req, env, caller);if (sub === "/api-keys" && method === "POST") return handleCreateAPIKey(req, env, caller);diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex e0a90bae..c04c7eb5 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -18,6 +18,10 @@export { CreditAccount } from "../../shared/credit_account";import { handleDashboard, type DashboardEnv } from "./dashboard";+import {+ AGENT_SECURITY_NOTIFICATION_PATH,+ receiveAgentSecurityNotification,+} from "./agent_security_notifications";import {autumnWebhook,autumnProjectInternal,@@ -38,6 +42,9 @@ export interface Env extends DashboardEnv {CF_ADMIN_SECRET: string;STRIPE_WEBHOOK_SECRET: string;EVENT_SECRET: string;+ // Dedicated HMAC secret for the Sessions API's minimal Agent Hook exposure+ // alert. It is intentionally not shared with other internal routes.+ OC_SECURITY_NOTIFICATION_SECRET?: string;// Per-org cross-cell paused-sandbox cap (default 100). Set lower on dev to// exercise the promotion path without paused hundreds of boxes.PAUSED_CAP?: string;@@ -1849,6 +1856,9 @@ export default {if (req.method !== "POST") return json({ error: "method not allowed" }, 405);return browserUsageInternal(req, env);}+ if (path === AGENT_SECURITY_NOTIFICATION_PATH) {+ return receiveAgentSecurityNotification(req, env);+ }// Migrate tool: flip D1 billing_provider for one org (EVENT_SECRET HMAC).if (path === "/internal/autumn-set-provider") {diff --git a/cloudflare-workers/api-edge/wrangler.igor-dev.toml b/cloudflare-workers/api-edge/wrangler.igor-dev.tomlindex 10857698..e972d0f6 100644--- a/cloudflare-workers/api-edge/wrangler.igor-dev.toml+++ b/cloudflare-workers/api-edge/wrangler.igor-dev.toml@@ -20,6 +20,7 @@# SESSION_JWT_SECRET — signs oc_session; must == the box's# OPENSANDBOX_SESSION_JWT_SECRET to wire it as a cell# EVENT_SECRET, SVIX_API_TOKEN — webhooks e2e (PR #410), optional+# OC_SECURITY_NOTIFICATION_SECRET — Agent Hook exposure alerts, optional# WorkOS dashboard (staging env): allowlist https://<worker>.workers.dev/auth/callback# and set it as the Sign-out redirect.diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.tomlindex 61b62cd9..91c19ad4 100644--- a/cloudflare-workers/api-edge/wrangler.prod.toml+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -63,6 +63,8 @@ new_sqlite_classes = ["CreditAccount"]# OC_MANAGED_CRED_HMAC_SECRET — dedicated HMAC for handing a minted OR key to# sessions-api (shared only with sessions-api; NOT the# generic internal-auth — this route carries a live key)+# OC_SECURITY_NOTIFICATION_SECRET — dedicated HMAC for minimal Agent Hook+# exposure alerts from sessions-api# BROWSER_API_SECRET — shared with browser.opencomputer.dev for dashboard# browser-session proxy requests# Optional vars: OPENROUTER_BASE_URL (default https://openrouter.ai/api/v1),diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex a0b996bd..7a70ea3b 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -92,6 +92,8 @@ new_sqlite_classes = ["CreditAccount"]# until set. See .agents/work/token-billing.md.# OC_MANAGED_CRED_HMAC_SECRET — dedicated HMAC for the minted-OR-key hand-off to# sessions-api (shared only with sessions-api).+# OC_SECURITY_NOTIFICATION_SECRET — dedicated HMAC for minimal Agent Hook+# exposure alerts from sessions-api.# Optional vars: OPENROUTER_BASE_URL (default https://openrouter.ai/api/v1),# OPENROUTER_MARKUP_BPS (env-default markup; per-org orgs.model_markup_bps wins).diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 10617f5e..c6febcef 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -57,6 +57,7 @@ export type {SandboxWebhook,SandboxWebhookDelivery,Credential,+ AgentSecurityNotification,} from './schemas'const API_BASE = '/api/dashboard'@@ -380,6 +381,19 @@ export const switchOrg = (orgId: string) =>S.OrgSchema,)+export const listAgentSecurityNotifications = () =>+ apiFetch(+ '/agent-security-notifications?include_acknowledged=false&limit=100',+ {},+ S.AgentSecurityNotificationListSchema,+ )++export const acknowledgeAgentSecurityNotification = (id: string) =>+ apiFetch<void>(+ `/agent-security-notifications/${encodeURIComponent(id)}/acknowledge`,+ { method: 'POST' },+ )+// Creditsexport const getCredits = () => apiFetch('/org/credits', {}, S.CreditsSchema)diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.tsindex d24d3c7f..784f825f 100644--- a/web/src/api/schemas.ts+++ b/web/src/api/schemas.ts@@ -1005,6 +1005,20 @@ export const SessionResultSchema = z.object({result: SessionEventSchema.nullable(),})+export const AgentSecurityNotificationSchema = z.object({+ id: z.string(),+ agentId: z.string(),+ hookId: z.string(),+ kind: z.literal('secret_exposure'),+ occurredAt: z.string(),+ acknowledgedAt: z.string().nullable(),+ acknowledgedBy: z.string().nullable(),+})+export const AgentSecurityNotificationListSchema = z.object({+ data: z.array(AgentSecurityNotificationSchema),+ next_cursor: z.string().nullable(),+})+export const DestinationSchema = z.object({id: z.string(),url: z.string(),@@ -1071,6 +1085,9 @@ export type AgentSnapshot = z.infer<typeof AgentSnapshotSchema>export type SessionEvent = z.infer<typeof SessionEventSchema>export type Turn = z.infer<typeof TurnSchema>export type SessionResult = z.infer<typeof SessionResultSchema>+export type AgentSecurityNotification = z.infer<+ typeof AgentSecurityNotificationSchema+>export type Destination = z.infer<typeof DestinationSchema>export type Delivery = z.infer<typeof DeliverySchema>diff --git a/web/src/components/agent-security-alert.test.tsx b/web/src/components/agent-security-alert.test.tsxnew file mode 100644index 00000000..8385846a--- /dev/null+++ b/web/src/components/agent-security-alert.test.tsx@@ -0,0 +1,59 @@+import { renderToStaticMarkup } from 'react-dom/server'+import { MemoryRouter } from 'react-router-dom'+import { describe, expect, it, vi } from 'vitest'+import { AgentSecurityAlert } from './agent-security-alert'+import type { AgentSecurityNotification } from '@/api/client'++const alert: AgentSecurityNotification = {+ id: 'hse_aaaaaaaaaaaaaaaaaaaaaaaa',+ agentId: 'agt_bbbbbbbbbbbbbbbbbbbbbbbb',+ hookId: 'hk_cccccccccccccccccccccccc',+ kind: 'secret_exposure',+ occurredAt: '2026-07-08T00:00:00.000Z',+ acknowledgedAt: null,+ acknowledgedBy: null,+}++function render(+ alerts: AgentSecurityNotification[],+ options: { acknowledging?: boolean; acknowledgeFailed?: boolean } = {},+) {+ return renderToStaticMarkup(+ <MemoryRouter>+ <AgentSecurityAlert+ alerts={alerts}+ onAcknowledge={vi.fn()}+ {...options}+ />+ </MemoryRouter>,+ )+}++describe('AgentSecurityAlert', () => {+ it('renders persistent server-owned copy, an Agent link, and a keyboard button', () => {+ const markup = render([alert])++ expect(markup).toContain('role="alert"')+ expect(markup).toContain('An Agent Hook URL was exposed and revoked.')+ expect(markup).toContain(`href="/agents/${alert.agentId}#hooks"`)+ expect(markup).toContain('>Acknowledge</button>')+ expect(markup).toContain('sm:flex-row')+ expect(markup).not.toContain(alert.hookId)+ expect(markup).not.toContain('GitHub')+ })++ it('keeps the alert visible during acknowledgement and after a failed attempt', () => {+ expect(render([alert], { acknowledging: true })).toContain('Acknowledging…')+ expect(render([alert], { acknowledging: true })).toContain('disabled=""')+ expect(render([alert], { acknowledgeFailed: true })).toContain(+ 'Could not acknowledge the alert. Try again.',+ )+ })++ it('summarizes multiple alerts and renders nothing once all are acknowledged', () => {+ expect(+ render([alert, { ...alert, id: 'hse_dddddddddddddddddddddddd' }]),+ ).toContain('2 Agent Hook URLs were exposed and revoked.')+ expect(render([])).toBe('')+ })+})diff --git a/web/src/components/agent-security-alert.tsx b/web/src/components/agent-security-alert.tsxnew file mode 100644index 00000000..18a7e465--- /dev/null+++ b/web/src/components/agent-security-alert.tsx@@ -0,0 +1,93 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { ShieldAlert } from 'lucide-react'+import { Link } from 'react-router-dom'+import {+ acknowledgeAgentSecurityNotification,+ listAgentSecurityNotifications,+ type AgentSecurityNotification,+} from '@/api/client'+import { Button } from '@/components/ui/button'++export function AgentSecurityAlert({+ alerts,+ acknowledging = false,+ acknowledgeFailed = false,+ onAcknowledge,+}: {+ alerts: AgentSecurityNotification[]+ acknowledging?: boolean+ acknowledgeFailed?: boolean+ onAcknowledge: (id: string) => void+}) {+ const alert = alerts[0]+ if (!alert) return null++ return (+ <div+ className="border-destructive/40 bg-status-error-bg text-destructive flex flex-col gap-2 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:px-8"+ role="alert"+ >+ <div className="flex min-w-0 items-start gap-2.5">+ <ShieldAlert className="mt-0.5 size-4 shrink-0" aria-hidden />+ <div className="min-w-0 text-sm">+ <p className="font-semibold">+ {alerts.length === 1+ ? 'An Agent Hook URL was exposed and revoked.'+ : `${alerts.length} Agent Hook URLs were exposed and revoked.`}+ </p>+ <p className="text-destructive/80 mt-0.5">+ Review the affected Hook before reconnecting its sender.{' '}+ <Link+ to={`/agents/${encodeURIComponent(alert.agentId)}#hooks`}+ className="font-medium underline underline-offset-2"+ >+ Review agent+ </Link>+ </p>+ {acknowledgeFailed ? (+ <p className="mt-1 font-medium">+ Could not acknowledge the alert. Try again.+ </p>+ ) : null}+ </div>+ </div>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ className="self-start sm:self-center"+ disabled={acknowledging}+ onClick={() => onAcknowledge(alert.id)}+ >+ {acknowledging ? 'Acknowledging…' : 'Acknowledge'}+ </Button>+ </div>+ )+}++export function AgentSecurityAlertBanner() {+ const queryClient = useQueryClient()+ const { data } = useQuery({+ queryKey: ['agent-security-notifications'],+ queryFn: listAgentSecurityNotifications,+ retry: false,+ refetchInterval: (query) => (query.state.error ? false : 30_000),+ })+ const acknowledge = useMutation({+ mutationFn: acknowledgeAgentSecurityNotification,+ onSuccess: () => {+ void queryClient.invalidateQueries({+ queryKey: ['agent-security-notifications'],+ })+ },+ })++ return (+ <AgentSecurityAlert+ alerts={data?.data ?? []}+ acknowledging={acknowledge.isPending}+ acknowledgeFailed={acknowledge.isError}+ onAcknowledge={(id) => acknowledge.mutate(id)}+ />+ )+}diff --git a/web/src/components/app-shell.tsx b/web/src/components/app-shell.tsxindex f28f7610..9d3e79e7 100644--- a/web/src/components/app-shell.tsx+++ b/web/src/components/app-shell.tsx@@ -24,7 +24,7 @@ import {type LucideIcon,} from 'lucide-react'import { useAuth } from '@/hooks/useAuth'-import { logout, getAutumnBilling } from '@/api/client'+import { getAutumnBilling, logout } from '@/api/client'import { Button } from '@/components/ui/button'import {Sheet,@@ -41,6 +41,7 @@ import {DropdownMenuTrigger,} from '@/components/ui/dropdown-menu'import { ErrorBoundary } from '@/components/error-boundary'+import { AgentSecurityAlertBanner } from '@/components/agent-security-alert'import { cn } from '@/lib/utils'type NavItem = {@@ -261,14 +262,16 @@ function HaltBanner() {})const halted = data?.isHalted ?? falseif (!halted || location.pathname.startsWith('/billing')) return null- // Sticky + error-toned so the halt stays in view while scrolling and reads as a hard- // block, not a muted notice (out-of-credits doc, Part A1). Sits just below the top bar.return (- <div className="border-destructive/40 bg-status-error-bg text-destructive sticky top-14 z-20 flex items-center justify-center gap-2 border-b px-4 py-2.5 text-center text-sm font-medium md:top-16 sm:px-8">+ <div className="border-destructive/40 bg-status-error-bg text-destructive flex items-center justify-center gap-2 border-b px-4 py-2.5 text-center text-sm font-medium sm:px-8"><CircleAlert className="size-4 shrink-0" /><span>- Your agent sessions and sandboxes are paused — you're out of prepaid credits.{' '}- <Link to="/billing" className="font-semibold underline underline-offset-2">+ Your agent sessions and sandboxes are paused — you're out of+ prepaid credits.{' '}+ <Link+ to="/billing"+ className="font-semibold underline underline-offset-2"+ >Top up & turn on auto-recharge</Link>{' '}to resume.@@ -321,7 +324,10 @@ export default function AppShell() {{/* Main content */}<div className="md:pt-16 md:pl-60">- <HaltBanner />+ <div className="sticky top-14 z-20 md:top-16">+ <HaltBanner />+ <AgentSecurityAlertBanner />+ </div><main className="mx-auto max-w-7xl px-4 py-6 sm:px-8">{/* Keyed by org + route: clears a page error on navigation ANDremounts org-scoped pages on org switch so local draft/filter