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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | 1x 2x 1x 1x 30x 1x 1x 17x 17x 17x 17x 1x 16x 16x 16x 16x 13x 13x 13x 13x 1x 12x 1x 1x 3x 1x 2x 13x 13x 13x 1x 12x 1x 11x 1x 11x 2x 9x 1x 8x 8x 8x 8x 17x 6x 6x 8x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 8x 5x 6x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x | // 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 { logger } from "../../lib/logger";
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>;
}>()
.catch(() => null);
if (!body || !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,
});
// Notify on terminal events. Fire-and-forget so the agent's POST is
// not blocked on email/WhatsApp providers. `executionCtx` is absent in
// unit-test app.request() calls — best-effort wrap.
const isTerminal = kind === "complete" || kind === "error";
if (isTerminal && importRow.status === "running") {
try {
c.executionCtx.waitUntil(
notifyImportResult(c, importId, importRow.proId, kind, body.payload),
);
} catch {
// No executionCtx (e.g. tests) — skip notify silently.
}
}
// Terminal transitions — keep the row status in sync with the event log.
if (kind === "complete" && importRow.status === "running") {
const completePayload = body.payload ?? {};
const stats: {
manifestKey?: string;
projectsFound?: number;
photosDownloaded?: number;
costCents?: number;
} = {};
const mk = completePayload.manifestKey;
if (typeof mk === "string") stats.manifestKey = mk;
const pf = completePayload.projectsFound;
if (typeof pf === "number") stats.projectsFound = pf;
const pd = completePayload.photosDownloaded;
if (typeof pd === "number") stats.photosDownloaded = pd;
const cc = completePayload.costCents;
if (typeof cc === "number") stats.costCents = cc;
await db
.update(schema.proImports)
.set({
status: "completed",
completedAt: Date.now(),
statsJson: stats,
})
.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;
}
/**
* Best-effort admin notify. Loads pro name + manifest stats, then delegates
* to ImportResultHandler via the existing CommunicationGateway. Never throws.
*/
type NotifyContext = {
env: CloudflareBindings;
get: (key: "db") => ReturnType<typeof getDb>;
} & {
get: (key: "dal") => Dal;
} & {
get: (key: "services") => Services;
};
async function notifyImportResult(
c: NotifyContext,
importId: string,
proId: string,
kind: "complete" | "error",
payload: Record<string, unknown> | undefined,
): Promise<void> {
try {
const { ImportResultHandler } = await import(
"../../lib/communication/handlers/import-result.handler"
);
const services = c.get("services") as unknown as {
communicationGateway?: ConstructorParameters<typeof ImportResultHandler>[0];
};
const dal = c.get("dal");
if (!services?.communicationGateway || !dal) {
logger.warn(
"[ImportNotify] gateway/dal missing on context — skipping notify",
);
return;
}
const handler = new ImportResultHandler(
services.communicationGateway,
dal,
);
const db = c.get("db");
const [row] = await db
.select({
sourceUrl: schema.proImports.sourceUrl,
submittedBy: schema.proImports.submittedBy,
})
.from(schema.proImports)
.where(eq(schema.proImports.id, importId))
.limit(1);
const pro = await dal.pros.findById(proId).catch(() => null);
const status =
kind === "complete"
? ("completed" as const)
: ("failed" as const);
await handler.handle(
{
importId,
proId,
proName: pro?.businessName ?? "(unknown pro)",
sourceUrl: row?.sourceUrl ?? "",
status,
submittedByUserId: row?.submittedBy ?? null,
projectsFound: numberOrUndefined(payload?.projectsFound),
photosDownloaded: numberOrUndefined(payload?.photosDownloaded),
errorCode: stringOrNull(payload?.code) ?? undefined,
errorMessage: stringOrNull(payload?.message) ?? undefined,
},
{
PORTAL_URL: c.env.PORTAL_URL,
IMPORT_NOTIFY_EMAIL: c.env.IMPORT_NOTIFY_EMAIL,
IMPORT_NOTIFY_WHATSAPP: c.env.IMPORT_NOTIFY_WHATSAPP,
},
);
} catch (err) {
logger.error(
"[ImportNotify] handler failed:",
err instanceof Error ? err.message : String(err),
);
}
}
function numberOrUndefined(v: unknown): number | undefined {
return typeof v === "number" ? v : undefined;
}
export default importRoutes;
|