An open-source, faster Devin alternative
TypeScript
api-edge: remove Agent Hook exposure alert receiver (sessions-api only)
Mohamed Habib via Computer2dd8f7c4f8c3
diff --git a/cloudflare-workers/api-edge/src/agent_security_notifications.test.ts b/cloudflare-workers/api-edge/src/agent_security_notifications.test.tsdeleted file mode 100644index aaf93439..00000000--- a/cloudflare-workers/api-edge/src/agent_security_notifications.test.ts+++ /dev/null@@ -1,320 +0,0 @@-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.tsdeleted file mode 100644index 08bc9e77..00000000--- a/cloudflare-workers/api-edge/src/agent_security_notifications.ts+++ /dev/null@@ -1,369 +0,0 @@-// 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 e6085e87..73a68785 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -32,10 +32,6 @@ import {import { planSchedule, summarizeWorkMinutePlan, trialEndsAt } from "./billing_summary";import { emitBillingEvent, type BillingEventsEnv } from "./billing_events";import { handleWebhooksAPI, type WebhookEnv } from "./webhooks";-import {- acknowledgeAgentSecurityNotification,- listAgentSecurityNotifications,-} from "./agent_security_notifications";import { createAPIKeyWithHash } from "./api_keys";import { createdKeyForSync, revokeComputerKey, syncComputerKey } from "./computer_keys";import {@@ -1110,17 +1106,6 @@ 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, ctx, caller);diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex fe1962b6..5c94d95c 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -57,10 +57,6 @@ import {} from "./create_context_cache";import { authDashboard, handleDashboard, type DashboardEnv } from "./dashboard";import { handleAgentFeedback, isAgentFeedbackPath, type AgentFeedbackEnv } from "./agent_feedback";-import {- AGENT_SECURITY_NOTIFICATION_PATH,- receiveAgentSecurityNotification,-} from "./agent_security_notifications";import {autumnWebhook,autumnProjectInternal,@@ -149,9 +145,6 @@ export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv, L// edge's own origin is always allowed).WIRE_HTTP_URL?: string;COMPUTER_API_CORS_ORIGINS?: 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;@@ -5492,9 +5485,6 @@ export default {if (req.method !== "POST") return json({ error: "method not allowed" }, 405);return agentRuntimeUsageInternal(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 64e6ead0..e350a734 100644--- a/cloudflare-workers/api-edge/wrangler.igor-dev.toml+++ b/cloudflare-workers/api-edge/wrangler.igor-dev.toml@@ -20,7 +20,6 @@# 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 f6720856..d23433bb 100644--- a/cloudflare-workers/api-edge/wrangler.prod.toml+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -166,8 +166,6 @@ deleted_classes = ["VmSession"]# OC_MANAGED_CRED_HMAC_SECRET — dedicated HMAC for handing a minted OR key to# the managed agents backend (shared only with it; 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# OC_MANAGED_AGENTS_SECRET — dedicated HS256 secret shared only with thediff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex c06a5d2c..06a3d722 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -170,8 +170,6 @@ deleted_classes = ["VmSession"]# until set. See .agents/work/token-billing.md.# OC_MANAGED_CRED_HMAC_SECRET — dedicated HMAC for the minted-OR-key hand-off to# the managed agents backend (shared only with it).-# OC_SECURITY_NOTIFICATION_SECRET — dedicated HMAC for minimal Agent Hook-# exposure alerts from sessions-api.# OC_MANAGED_AGENTS_SECRET — dedicated HS256 secret shared only with the# managed-agents backend.# AGENT_FEEDBACK_TRIAGE_TOKEN — bearer token for the feedback.now triage