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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 | 1x 1x 36x 36x 36x 36x 31x 31x 5x 1x 1x 4x 1x 3x 3x 3x 36x 3x 2x 2x 2x 1x 1x 12x 12x 12x 12x 12x 12x 12x 1x 11x 11x 1x 10x 10x 1x 9x 9x 1x 1x 2x 1x 1x 1x 8x 8x 9x 9x 1x 9x 9x 1x 1x 9x 9x 1x 1x 1x 9x 9x 8x 9x 3x 1x 7x 7x 7x 7x 7x 7x 1x 6x 6x 7x 7x 1x 5x 1x 4x 4x 1x 3x 3x 3x 3x 1x 3x 1x 3x 1x 3x 1x 3x 1x 3x 3x 3x 3x 1x 1x 8x 8x 8x 8x 8x 8x 1x 7x 7x 1x 1x 6x 6x 5x 4x 4x 5x 1x 1x 6x 1x 1x 5x 5x 5x 5x 5x 5x 1x 4x 4x 4x 1x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 1x | // Internal Social Studio Routes - Called by social studio container/worker
import { verifyS2SRequest } from "@interioring/internal-auth";
import { and, asc, eq, inArray, isNull } from "drizzle-orm";
import { Hono } from "hono";
import type { Dal } from "../../dal";
import type { getDb } from "../../db";
import * as schema from "../../db/schema";
import { NotFoundError } from "../../lib/errors";
import { logger } from "../../lib/logger";
import { handleError, success } from "../../lib/response";
import type { Services } from "../../services";
type Env = {
Bindings: CloudflareBindings;
Variables: {
dal: Dal;
services: Services;
db: ReturnType<typeof getDb>;
};
};
const socialStudioRoutes = new Hono<Env>();
// Middleware to validate internal auth token (HMAC-signed, bound to draftId)
// Scoped to this router's OWN paths, never "*".
//
// This sub-app is mounted at `internal.route("/", …)`, so a `use("*")` here
// matches EVERY path under /api/internal — including sibling routers mounted
// after it (`/imports/*`, `/rrm/*`). Those callers send a valid
// X-Internal-API-Key but not a social-studio HMAC token bound to a draftId,
// so they were rejected with "Invalid or expired internal auth token" on
// every deployed environment. It was invisible locally because the bypass
// below fires when ENVIRONMENT=local and no secret is set.
socialStudioRoutes.use("/social-drafts/*", async (c, next) => {
const token = c.req.header("X-Internal-API-Key");
const secret = c.env.INTERNAL_API_KEY;
const isExplicitlyLocal = c.env.ENVIRONMENT === "local";
// Allow bypass when ENVIRONMENT is explicitly "local" and no secret is configured.
if (!secret && isExplicitlyLocal) {
logger.warn("[Security] Internal auth bypassed for local development");
return next();
}
if (!secret) {
logger.error("[Security] INTERNAL_API_KEY not configured!");
return c.json(
{
success: false,
error: {
code: "UNAUTHORIZED",
message: "Internal API key not configured",
},
},
401,
);
}
if (!token) {
return c.json(
{
success: false,
error: { code: "UNAUTHORIZED", message: "Missing internal auth token" },
},
401,
);
}
// Extract draftId from path for resource-bound verification
// Paths: /social-drafts/:draftId/*
const pathParts = c.req.path.split("/");
const draftsIdx = pathParts.indexOf("social-drafts");
const draftId = draftsIdx >= 0 ? (pathParts[draftsIdx + 1] ?? "") : "";
const valid = await verifyS2SRequest(secret, "social-studio", draftId, token);
if (!valid) {
const tokenPrefix = `${token.slice(0, 8)}...`;
logger.error(
`[InternalAPI] HMAC verify failed — token=${tokenPrefix} path=${c.req.path} draftId=${draftId}`,
);
return c.json(
{
success: false,
error: {
code: "UNAUTHORIZED",
message: "Invalid or expired internal auth token",
},
},
401,
);
}
return next();
});
// GET /internal/social-drafts/:draftId/job-data
// Returns full job payload needed by the social studio container to generate a reel
socialStudioRoutes.get("/social-drafts/:draftId/job-data", async (c) => {
try {
const dal = c.get("dal");
const db = c.get("db");
const draftId = c.req.param("draftId");
logger.info(`[InternalAPI] GET /social-drafts/${draftId}/job-data`);
const draft = await dal.socialDrafts.getById(draftId);
if (!draft) {
throw new NotFoundError("Draft not found");
}
// Fetch project
const project = await dal.projects.findById(draft.projectId);
if (!project) {
throw new NotFoundError("Project not found");
}
// Fetch pro
const pro = await dal.pros.findById(draft.proId);
if (!pro) {
throw new NotFoundError("Pro not found");
}
// Check if this draft has a manual photo selection in the join table
const selectedDraftPhotos = await db
.select({
mediaId: schema.socialDraftPhotos.mediaId,
sortOrder: schema.socialDraftPhotos.sortOrder,
})
.from(schema.socialDraftPhotos)
.where(eq(schema.socialDraftPhotos.draftId, draftId))
.orderBy(asc(schema.socialDraftPhotos.sortOrder));
let photos: Array<{
mediaId: number;
storageKey: string;
caption: string | null;
altText: string | null;
photoType: string | null;
isCover: boolean | null;
}>;
if (selectedDraftPhotos.length > 0) {
// Manual selection: fetch media directly by IDs (supports multi-project drafts)
const selectedMediaIds = selectedDraftPhotos.map((sp) => sp.mediaId);
const mediaRows = await db
.select({
mediaId: schema.media.id,
storageKey: schema.media.storageKey,
caption: schema.media.caption,
altText: schema.media.altText,
photoType: schema.media.photoType,
isCover: schema.media.isCover,
})
.from(schema.media)
.where(
and(
inArray(schema.media.id, selectedMediaIds),
eq(schema.media.mediaType, "image"),
),
);
// Preserve the user-specified sort order from the join table
const mediaById = new Map(mediaRows.map((m) => [m.mediaId, m]));
photos = selectedDraftPhotos
.map((sp) => mediaById.get(sp.mediaId))
.filter((m): m is NonNullable<typeof m> => m !== undefined);
} else {
// Auto selection: fetch all eligible photos from the primary project
const mediaRows = await db
.select({
mediaId: schema.media.id,
storageKey: schema.media.storageKey,
caption: schema.media.caption,
altText: schema.media.altText,
photoType: schema.media.photoType,
isCover: schema.media.isCover,
})
.from(schema.media)
.innerJoin(schema.rooms, eq(schema.media.roomId, schema.rooms.id))
.where(
and(
eq(schema.rooms.projectId, draft.projectId),
eq(schema.media.mediaType, "image"),
),
);
// Post-filter: photoType in ('after', null) OR isCover
photos = mediaRows.filter(
(m) => m.isCover || m.photoType === "after" || m.photoType === null,
);
}
logger.info(
`[job-data] draftId=${draftId} projectId=${draft.projectId} selectedDraftPhotos=${selectedDraftPhotos.length} finalPhotos=${photos.length}`,
);
logger.info(
`[job-data] photos: ${JSON.stringify(photos.map((p) => ({ mediaId: p.mediaId, storageKey: p.storageKey, photoType: p.photoType, isCover: p.isCover })))}`,
);
// Fetch music track if referenced
let musicTrack: {
id: string;
name: string;
r2Key: string;
durationS: number;
category: string;
} | null = null;
if (draft.musicTrackId) {
const [track] = await db
.select({
id: schema.socialStudioMusicTracks.id,
name: schema.socialStudioMusicTracks.name,
r2Key: schema.socialStudioMusicTracks.r2Key,
durationS: schema.socialStudioMusicTracks.durationS,
category: schema.socialStudioMusicTracks.category,
})
.from(schema.socialStudioMusicTracks)
.where(eq(schema.socialStudioMusicTracks.id, draft.musicTrackId))
.limit(1);
musicTrack = track ?? null;
}
// Fetch template if referenced
let template: {
id: string;
name: string;
slots: unknown;
defaultMusicId: string | null;
defaultOverlay: unknown;
brandingRequired: boolean;
} | null = null;
if (draft.templateId) {
const [tmpl] = await db
.select({
id: schema.socialStudioTemplates.id,
name: schema.socialStudioTemplates.name,
slots: schema.socialStudioTemplates.slots,
defaultMusicId: schema.socialStudioTemplates.defaultMusicId,
defaultOverlay: schema.socialStudioTemplates.defaultOverlay,
brandingRequired: schema.socialStudioTemplates.brandingRequired,
})
.from(schema.socialStudioTemplates)
.where(eq(schema.socialStudioTemplates.id, draft.templateId))
.limit(1);
Eif (tmpl) {
template = {
...tmpl,
slots: tmpl.slots ? JSON.parse(tmpl.slots) : null,
defaultOverlay: tmpl.defaultOverlay
? JSON.parse(tmpl.defaultOverlay)
: null,
};
}
}
// Build branding object from pro record when brandingEnabled
let branding: {
businessName: string;
logoUrl: string | null;
brandColorPrimary: string | null;
brandColorSecondary: string | null;
} | null = null;
if (draft.brandingEnabled) {
branding = {
businessName: pro.businessName,
logoUrl: pro.logoUrl ?? null,
brandColorPrimary: pro.brandColorPrimary ?? null,
brandColorSecondary: pro.brandColorSecondary ?? null,
};
}
return success(c, {
draft,
jobDataVersion: draft.jobDataVersion,
project: {
id: project.id,
name: project.title,
workedAreaIds: project.workedAreaIds ?? [],
materials: project.materialTagIds ?? [],
styles: project.styleTagIds ?? [],
locality: project.localityId,
propertyType: project.propertyType,
budgetRange: project.budgetRange,
proId: project.proId,
},
pro: {
id: pro.id,
name: pro.businessName,
logoUrl: pro.logoUrl ?? null,
},
photos,
musicTrack,
branding,
overlayConfig: draft.overlayConfig
? JSON.parse(draft.overlayConfig)
: null,
voiceoverConfig: draft.voiceoverConfig
? JSON.parse(draft.voiceoverConfig)
: null,
template,
slotAssignments: draft.slotAssignments
? JSON.parse(draft.slotAssignments)
: null,
});
} catch (err) {
return handleError(c, err);
}
});
// PATCH /internal/social-drafts/:draftId
// Update draft status/fields after container completes work
socialStudioRoutes.patch("/social-drafts/:draftId", async (c) => {
try {
const dal = c.get("dal");
const draftId = c.req.param("draftId");
logger.info(`[InternalAPI] PATCH /social-drafts/${draftId}`);
const draft = await dal.socialDrafts.getById(draftId);
if (!draft) {
throw new NotFoundError("Draft not found");
}
const body = await c.req.json<{
status?: string;
reelR2Key?: string;
expiresAt?: number; // unix timestamp
captionEn?: string;
template?: string;
jobNonce?: string;
voiceoverR2Key?: string;
voiceoverConfig?: string; // JSON string — Worker sends this with `failed: true` on partial success
}>();
logger.info(
`[InternalAPI] PATCH /social-drafts/${draftId} body: status=${body.status} reelR2Key=${body.reelR2Key || "(none)"} jobNonce=${body.jobNonce || "(none)"} template=${body.template || "(none)"}`,
);
logger.info(
`[InternalAPI] PATCH /social-drafts/${draftId} draft state: status=${draft.status} jobNonce=${draft.jobNonce}`,
);
// Guard: if jobNonce provided, verify it matches
if (body.jobNonce !== undefined && draft.jobNonce !== body.jobNonce) {
return c.json(
{
success: false,
error: { code: "CONFLICT", message: "Job nonce mismatch" },
},
409,
);
}
// Guard: skip status update if current status is 'cancelled'
if (draft.status === "cancelled") {
return success(c, { ok: true });
}
const VALID_STATUSES = [
"pending",
"processing",
"cancelled",
"ready",
"failed",
] as const;
if (
body.status !== undefined &&
!VALID_STATUSES.includes(body.status as (typeof VALID_STATUSES)[number])
) {
return c.json(
{
success: false,
error: {
code: "BAD_REQUEST",
message: `Invalid status: ${body.status}`,
},
},
400,
);
}
const updateData: Partial<typeof schema.socialDrafts.$inferInsert> = {};
Eif (body.status !== undefined) {
updateData.status =
body.status as (typeof schema.socialDrafts.$inferSelect)["status"];
}
if (body.reelR2Key !== undefined) {
updateData.reelR2Key = body.reelR2Key;
}
if (body.expiresAt !== undefined) {
updateData.expiresAt = new Date(body.expiresAt * 1000);
}
if (body.captionEn !== undefined) {
updateData.captionEn = body.captionEn;
}
if (body.template !== undefined) {
updateData.template =
body.template as (typeof schema.socialDrafts.$inferSelect)["template"];
}
if (body.voiceoverR2Key !== undefined) {
updateData.voiceoverR2Key = body.voiceoverR2Key;
}
// voiceoverConfig is a JSON string set by the Worker on partial success
// (e.g. `{"enabled":true,"voice":"nova","failed":true}`). We trust the
// Worker here — the field is only writable via the internal API key.
Iif (body.voiceoverConfig !== undefined) {
updateData.voiceoverConfig = body.voiceoverConfig;
}
await dal.socialDrafts.update(draftId, updateData);
logger.info(
`[InternalAPI] PATCH /social-drafts/${draftId} updated: ${JSON.stringify(Object.keys(updateData))}`,
);
return success(c, { ok: true });
} catch (err) {
return handleError(c, err);
}
});
// PATCH /internal/social-drafts/:draftId/media-enrichment
// Update caption/altText on media records — only if currently null
socialStudioRoutes.patch(
"/social-drafts/:draftId/media-enrichment",
async (c) => {
try {
const dal = c.get("dal");
const db = c.get("db");
const draftId = c.req.param("draftId");
const draft = await dal.socialDrafts.getById(draftId);
if (!draft) {
throw new NotFoundError("Draft not found");
}
const body = await c.req.json<{
jobNonce?: string;
updates: Array<{
mediaId: number;
caption?: string;
altText?: string;
}>;
}>();
// D3 (Codex F3): nonce check — reject the request if the C3 reaper has
// bumped the draft's jobNonce. Without this guard, a slow-but-still-
// running container could mutate media records (caption/altText) for a
// draft that's been declared failed, leaving the user with stale AI
// annotations on their photos. The main PATCH at /social-drafts/:draftId
// has had this check since day one; F3 closed the gap on the side
// channels.
if (body.jobNonce !== undefined && draft.jobNonce !== body.jobNonce) {
logger.warn(
`[InternalAPI] media-enrichment rejected: nonce mismatch on draft=${draftId} (request=${body.jobNonce} vs current=${draft.jobNonce})`,
);
return c.json(
{
success: false,
error: { code: "CONFLICT", message: "Job nonce mismatch" },
},
409,
);
}
let updated = 0;
for (const item of body.updates) {
if (item.caption !== undefined) {
const result = await db
.update(schema.media)
.set({ caption: item.caption, dateUpdated: new Date() })
.where(
and(
eq(schema.media.id, item.mediaId),
isNull(schema.media.caption),
),
)
.returning({ id: schema.media.id });
if (result.length > 0) updated++;
}
if (item.altText !== undefined) {
const result = await db
.update(schema.media)
.set({ altText: item.altText, dateUpdated: new Date() })
.where(
and(
eq(schema.media.id, item.mediaId),
isNull(schema.media.altText),
),
)
.returning({ id: schema.media.id });
Eif (result.length > 0) updated++;
}
}
return success(c, { updated });
} catch (err) {
return handleError(c, err);
}
},
);
// POST /internal/social-drafts/:draftId/upload-reel
// Upload the generated reel video to R2
socialStudioRoutes.post("/social-drafts/:draftId/upload-reel", async (c) => {
try {
const dal = c.get("dal");
const draftId = c.req.param("draftId");
logger.info(`[InternalAPI] POST /social-drafts/${draftId}/upload-reel`);
const draft = await dal.socialDrafts.getById(draftId);
if (!draft) {
throw new NotFoundError("Draft not found");
}
const formData = await c.req.formData();
const reelFile = formData.get("reel") as File | null;
if (!reelFile) {
return c.json(
{
success: false,
error: { code: "BAD_REQUEST", message: "No reel file provided" },
},
400,
);
}
// D3 (Codex F3): nonce check via the multipart formData. The container
// includes its jobNonce alongside the reel blob. If the C3 reaper has
// bumped the nonce on this draft, we reject the upload — otherwise a
// late container could write a stale MP4 to R2, creating an orphan
// pointing nowhere from the DB perspective and showing the wrong reel
// if a future regen happens to land on the same r2Key.
const submittedNonce = formData.get("jobNonce");
if (
submittedNonce !== null &&
typeof submittedNonce === "string" &&
submittedNonce.length > 0 &&
draft.jobNonce !== submittedNonce
) {
logger.warn(
`[InternalAPI] upload-reel rejected: nonce mismatch on draft=${draftId} (request=${submittedNonce} vs current=${draft.jobNonce})`,
);
return c.json(
{
success: false,
error: { code: "CONFLICT", message: "Job nonce mismatch" },
},
409,
);
}
const r2Key = `social-studio/${draft.proId}/${draftId}.mp4`;
const arrayBuffer = await reelFile.arrayBuffer();
logger.info(
`[InternalAPI] upload-reel: draftId=${draftId} size=${arrayBuffer.byteLength} bytes (${(arrayBuffer.byteLength / 1024).toFixed(1)} KB) → r2Key=${r2Key}`,
);
await c.env.R2.put(r2Key, arrayBuffer, {
httpMetadata: {
contentType: "video/mp4",
},
});
logger.info(
`[InternalAPI] upload-reel: draftId=${draftId} R2 put complete`,
);
return success(c, { reelR2Key: r2Key });
} catch (err) {
return handleError(c, err);
}
});
export default socialStudioRoutes;
|