Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | // Internal Import Agent Routes (GST-4 / GST-2 plan §5).
//
// Accepts events from the container's scoped JWT — or, on the alarm path,
// from the Durable Object via the shared `IMPORT_AGENT_SECRET`. M1 ships
// the single `POST /imports/:id/events` endpoint that the container hits
// with its heartbeat; the rest of the agent tool surface (profile/project/
// photo writes, cost reporting) lands in M2.
//
// Trust boundary: the JWT is the capability. Every mutation is filtered by
// `proId = claims.proId` so a compromised prompt or container cannot reach
// into another pro's data (plan §5).
import { Hono } from "hono";
import { and, eq } from "drizzle-orm";
import type { Dal } from "../../dal";
import type { Services } from "../../services";
import type { getDb } from "../../db";
import * as schema from "../../db/schema";
import {
PRO_IMPORT_EVENT_KINDS,
type ProImportEventKind,
} from "../../db/schema/imports";
import { success, handleError } from "../../lib/response";
import { ForbiddenError, NotFoundError, ValidationError } from "../../lib/errors";
import { verifyImportAgentJwt } from "../../import-agent/jwt";
type Env = {
Bindings: CloudflareBindings;
Variables: {
dal: Dal;
services: Services;
db: ReturnType<typeof getDb>;
importId: string;
proId: string;
};
};
const importRoutes = new Hono<Env>();
function secureCompare(a: string, b: string): boolean {
if (a.length !== b.length) return false;
let result = 0;
for (let i = 0; i < a.length; i++) {
result |= a.charCodeAt(i) ^ b.charCodeAt(i);
}
return result === 0;
}
// POST /internal/imports/:importId/events
// Agent calls this with `Authorization: Bearer <jwt>`; the DO's own alarm
// handler posts with `X-Import-Agent-Secret: <secret>` instead.
importRoutes.post("/imports/:importId/events", async (c) => {
try {
const importId = c.req.param("importId");
const secret = c.env.IMPORT_AGENT_SECRET;
if (!secret) {
return c.json(
{
success: false,
error: {
code: "SERVER_MISCONFIGURED",
message: "IMPORT_AGENT_SECRET is not configured",
},
},
500,
);
}
const authHeader = c.req.header("authorization");
const directSecret = c.req.header("x-import-agent-secret");
let authorizedProId: string | null = null;
if (authHeader?.startsWith("Bearer ")) {
const token = authHeader.slice("Bearer ".length);
try {
const claims = await verifyImportAgentJwt(token, secret);
if (claims.importId !== importId) {
throw new ForbiddenError(
"JWT importId does not match request path",
);
}
authorizedProId = claims.proId;
} catch (err) {
const message = err instanceof Error ? err.message : "Invalid token";
return c.json(
{ success: false, error: { code: "UNAUTHORIZED", message } },
401,
);
}
} else if (directSecret && secureCompare(directSecret, secret)) {
// Trusted DO-internal path; no proId from claims, so we resolve it
// from the import row below.
authorizedProId = null;
} else {
return c.json(
{
success: false,
error: { code: "UNAUTHORIZED", message: "Missing credentials" },
},
401,
);
}
const db = c.get("db");
const [importRow] = await db
.select({
id: schema.proImports.id,
proId: schema.proImports.proId,
status: schema.proImports.status,
})
.from(schema.proImports)
.where(eq(schema.proImports.id, importId))
.limit(1);
if (!importRow) {
throw new NotFoundError("Import not found");
}
if (authorizedProId && authorizedProId !== importRow.proId) {
throw new ForbiddenError("JWT proId does not match import owner");
}
const body = await c.req.json<{
kind: string;
payload?: Record<string, unknown>;
}>();
if (!body.kind) {
throw new ValidationError("Missing event kind");
}
if (
!(PRO_IMPORT_EVENT_KINDS as readonly string[]).includes(body.kind)
) {
throw new ValidationError(`Unsupported event kind: ${body.kind}`);
}
const kind = body.kind as ProImportEventKind;
const eventId = crypto.randomUUID();
await db.insert(schema.proImportEvents).values({
id: eventId,
importId,
kind,
payloadJson: body.payload ?? null,
});
// Terminal transitions — keep the row status in sync with the event log.
if (kind === "complete" && importRow.status === "running") {
await db
.update(schema.proImports)
.set({ status: "completed", completedAt: Date.now() })
.where(
and(
eq(schema.proImports.id, importId),
eq(schema.proImports.status, "running"),
),
);
} else if (kind === "error" && importRow.status === "running") {
const payload = body.payload ?? {};
await db
.update(schema.proImports)
.set({
status: "failed",
completedAt: Date.now(),
errorCode: stringOrNull(payload.code),
errorMessage: stringOrNull(payload.message),
})
.where(
and(
eq(schema.proImports.id, importId),
eq(schema.proImports.status, "running"),
),
);
}
return success(c, { eventId, kind });
} catch (err) {
return handleError(c, err);
}
});
function stringOrNull(v: unknown): string | null {
return typeof v === "string" ? v : null;
}
export default importRoutes;
|