Skip to content

An open-source, faster Devin alternative

TypeScript

api-edge: redact the session snapshot by position, keep application JSON opaque

Igor Zalutskifce82d06e3a1
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index cbc49271..3ce0a25c 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -2270,6 +2270,182 @@ describe("managed agents proxy", () => {
});
});
+ // Review finding 8 (2026-09-15): the detail route used to strip
+ // reserved-looking keys from every nested object, so an application result
+ // that happened to contain userId, a nested runtimeId or artifact came back
+ // intact from the list row and corrupted from the same session's detail.
+ it("returns the application result identical from the list row and the detail, with the platform envelope stripped", async () => {
+ const result = {
+ turnId: "turn-1",
+ callId: "call-1",
+ reportedAt: "2026-09-15T00:01:00.000Z",
+ data: {
+ userId: "u-42",
+ pr: { url: "https://github.com/acme/web/pull/12", runtimeId: "r-9" },
+ artifact: "build-12",
+ checks: [{ name: "lint", userId: "x" }],
+ },
+ };
+ const row = {
+ id: "session-1",
+ projectId: "prj_test",
+ agentId: "worker",
+ deploymentId: "worker:digest",
+ environment: "development",
+ source: "api",
+ status: "idle",
+ labels: { user_id: "u-42", topic: "t" },
+ createdAt: "2026-09-15T00:00:00.000Z",
+ updatedAt: "2026-09-15T00:01:00.000Z",
+ revision: 3,
+ activity: { activeTurnId: null, queued: 0, lastSettledTurn: null },
+ result,
+ accountId: "org_test",
+ userId: "user_private",
+ runtimeId: "internal-runtime",
+ };
+ const snapshot = {
+ id: "session-1",
+ accountId: "org_test",
+ userId: "user_private",
+ agentId: "worker",
+ deploymentId: "worker:digest",
+ projectId: "prj_test",
+ executionMode: "workerd",
+ source: "api",
+ status: "idle",
+ labels: { user_id: "u-42", topic: "t" },
+ revision: 3,
+ result,
+ runtimeId: "internal-runtime",
+ runtimeEpoch: 4,
+ runtimeToken: "internal-runtime-token",
+ microvmId: "internal-vm",
+ microvmState: "suspended",
+ createdAt: "2026-09-15T00:00:00.000Z",
+ updatedAt: "2026-09-15T00:01:00.000Z",
+ environment: "development",
+ turns: [
+ {
+ id: "turn-1",
+ input: "Fix the login page",
+ mode: "queue",
+ status: "completed",
+ payload: { userId: "u-42", repo: "acme/web" },
+ createdAt: "2026-09-15T00:00:00.000Z",
+ updatedAt: "2026-09-15T00:01:00.000Z",
+ },
+ ],
+ };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: URL | string) =>
+ String(input).endsWith("/v1/sessions")
+ ? Response.json({ sessions: [row], nextCursor: null })
+ : Response.json(snapshot),
+ ),
+ );
+ const env = {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ };
+ const caller = { orgID: "org_test", userID: "user_test" };
+
+ const list = await proxyManagedAgents(
+ new Request("https://app.opencomputer.dev/api/managed-agents/sessions"),
+ env,
+ caller,
+ "/api/managed-agents",
+ );
+ const detail = await proxyManagedAgents(
+ new Request("https://app.opencomputer.dev/api/managed-agents/sessions/session-1"),
+ env,
+ caller,
+ "/api/managed-agents",
+ );
+ expect(list.status).toBe(200);
+ expect(detail.status).toBe(200);
+ const listBody = (await list.json()) as { sessions: Array<Record<string, unknown>> };
+ const detailBody = (await detail.json()) as Record<string, unknown>;
+
+ // Application data is opaque: the same value from both routes.
+ expect(listBody.sessions[0].result).toEqual(result);
+ expect(detailBody.result).toEqual(result);
+ expect(detailBody.result).toEqual(listBody.sessions[0].result);
+ expect(detailBody.labels).toEqual({ user_id: "u-42", topic: "t" });
+ expect((detailBody.turns as Array<Record<string, unknown>>)[0].payload).toEqual({
+ userId: "u-42",
+ repo: "acme/web",
+ });
+ // The platform envelope is gone from the top level, and the fields the
+ // dashboard and CLI read are still there.
+ expect(detailBody).not.toHaveProperty("accountId");
+ expect(detailBody).not.toHaveProperty("userId");
+ expect(detailBody).not.toHaveProperty("runtimeId");
+ expect(detailBody).not.toHaveProperty("runtimeEpoch");
+ expect(detailBody).not.toHaveProperty("runtimeToken");
+ expect(detailBody).not.toHaveProperty("microvmId");
+ expect(detailBody.executionMode).toBe("workerd");
+ expect(detailBody.microvmState).toBe("suspended");
+ expect(JSON.stringify(detailBody)).not.toMatch(
+ /org_test|user_private|internal-runtime|internal-vm|runtimeEpoch/,
+ );
+ });
+
+ it("keeps application JSON inside tool outputs on public events", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Response.json({
+ events: [
+ {
+ id: "event-2",
+ seq: 2,
+ timestamp: "2026-09-15T00:00:01.000Z",
+ sessionId: "session-1",
+ turnId: "turn-1",
+ type: "tool.completed",
+ data: {
+ tool: "report",
+ callId: "call-1",
+ title: "report",
+ output: { userId: "u-42", pr: { runtimeId: "r-9" }, artifact: "build-12" },
+ result: true,
+ runtimeId: "internal-runtime",
+ },
+ },
+ ],
+ }),
+ ),
+ );
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/sessions/session-1/events?after=0",
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({
+ events: [
+ expect.objectContaining({
+ type: "tool.completed",
+ data: {
+ tool: "report",
+ callId: "call-1",
+ title: "report",
+ output: { userId: "u-42", pr: { runtimeId: "r-9" }, artifact: "build-12" },
+ result: true,
+ },
+ }),
+ ],
+ });
+ });
+
it("interrupts a session's running turn and returns the sanitized snapshot", async () => {
const fetchSpy = vi.fn(async () =>
Response.json({
diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.ts
index cf61fda4..e1265b23 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -750,8 +750,8 @@ function publicDelivery(value: unknown): Record<string, unknown> {
/**
* Session labels are the owner's own strings under the owner's own keys.
- * They are reattached after the private-key strip, which would otherwise
- * drop a label the owner happened to call `user_id` or `runtime_id`.
+ * They are read from the source, never from a stripped copy, so a label the
+ * owner happened to call `user_id` or `runtime_id` is kept.
*/
function ownerLabels(source: Record<string, unknown>): Record<string, string> {
const labels = record(source.labels) ?? {};
@@ -762,23 +762,77 @@ function ownerLabels(source: Record<string, unknown>): Record<string, string> {
);
}
+/**
+ * The session's result as documented: the call that reported it and its
+ * `data` verbatim. `data` is the application's own JSON, so nothing inside
+ * it is inspected or renamed; `null` when no turn has reported one.
+ */
+function publicSessionResult(value: unknown): unknown {
+ const result = record(value);
+ if (!result) return null;
+ return {
+ turnId: result.turnId,
+ callId: result.callId,
+ reportedAt: result.reportedAt,
+ data: result.data,
+ };
+}
+
+/**
+ * Platform-internal fields of the session envelope that no public route
+ * documents: the runtime generation counter and the name of the memory
+ * object the bindings were admitted against. Dropped by position, since the
+ * name filter is for the fields it lists.
+ */
+const PRIVATE_SESSION_FIELDS = new Set(["runtimeEpoch", "memoryObject"]);
+
+/**
+ * One turn of the snapshot. `payload` is the caller's own JSON and passes
+ * through untouched; `deliveries` are platform records with their own public
+ * shape; the rest of the turn is platform envelope and keeps the name strip.
+ */
+function publicTurn(entry: unknown): unknown {
+ const turn = record(entry);
+ if (!turn) return entry;
+ return Object.fromEntries(
+ Object.entries(turn).flatMap(([key, child]): Array<[string, unknown]> => {
+ if (key === "payload") return [[key, child]];
+ if (key === "deliveries") {
+ return [[key, Array.isArray(child) ? child.map(publicDelivery) : child]];
+ }
+ if (PRIVATE_EVENT_KEYS.has(key)) return [];
+ return [[key, stripPrivateValues(child)]];
+ }),
+ );
+}
+
+/**
+ * The public session. Redaction is by position: the platform envelope (the
+ * session's own fields, memory bindings, turn records, deliveries) is
+ * stripped of private fields, while the positions that hold application
+ * data, `labels`, `result.data` and each turn's `payload`, are copied
+ * verbatim. A recursive strip over the whole object used to remove keys
+ * such as `userId` or `runtimeId` from inside an application's result,
+ * which the list row (assembled separately) kept, so the same session
+ * answered two routes with two different results.
+ */
function publicSessionSnapshot(value: unknown): unknown {
const source = record(value);
- const session = record(stripPrivateValues(value));
- if (!session || !source) return session ?? value;
- const labelled = "labels" in source ? { ...session, labels: ownerLabels(source) } : session;
- if (!Array.isArray(labelled.turns)) return labelled;
- return {
- ...labelled,
- turns: labelled.turns.map((entry) => {
- const turn = record(entry);
- if (!turn || !Array.isArray(turn.deliveries)) return entry;
- return { ...turn, deliveries: turn.deliveries.map(publicDelivery) };
+ if (!source) return value;
+ return Object.fromEntries(
+ Object.entries(source).flatMap(([key, child]): Array<[string, unknown]> => {
+ if (key === "labels") return [[key, ownerLabels(source)]];
+ if (key === "result") return [[key, publicSessionResult(child)]];
+ if (key === "turns") {
+ return [[key, Array.isArray(child) ? child.map(publicTurn) : stripPrivateValues(child)]];
+ }
+ if (PRIVATE_EVENT_KEYS.has(key) || PRIVATE_SESSION_FIELDS.has(key)) return [];
+ return [[key, stripPrivateValues(child)]];
}),
- };
+ );
}
-/** One list row as documented: nothing private is in it, and the labels are the owner's. */
+/** One list row as documented: nothing private is in it, and the labels and result are the owner's. */
function publicSessionSummary(value: unknown): unknown {
const source = record(value);
const row = record(stripPrivateValues(value));
@@ -796,7 +850,7 @@ function publicSessionSummary(value: unknown): unknown {
updatedAt: row.updatedAt,
revision: row.revision,
activity: row.activity,
- result: source.result ?? null,
+ result: publicSessionResult(source.result),
};
}