All files / routes/pro/website publish.routes.ts

100% Statements 131/131
100% Branches 78/78
100% Functions 6/6
100% Lines 131/131

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                                                  4x 4x                                 1x     1x     1x       21x 21x 21x 1x     20x 20x 20x     20x         19x 1x         18x 1x     17x 1x         16x 1x           15x     15x   2x 2x 2x 1x     1x             14x     14x 14x 14x   14x 14x 14x 14x 21x         21x 13x 13x         13x     13x 2x         11x 6x     6x           6x       1x       5x     5x     11x 2x     2x           2x 1x       1x           1x           12x 11x           12x     12x               12x 1x       11x               11x 11x 10x             10x       10x 10x     10x             1x     11x         9x           1x       5x 5x 5x 1x     4x 4x   4x 4x 1x     3x       3x 2x     2x 1x               3x               1x           1x       3x 3x 3x   3x 3x 1x     2x       2x           1x           1x       4x 4x 4x   4x 4x 1x     3x 4x   4x           3x   1x           1x       8x 8x 8x 8x   8x         7x 1x     6x 1x           5x 5x 1x     4x               4x   4x       8x           4x            
// Pro Website Publish Routes - Publishing, unpublishing, build trigger routes
 
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import { BadRequestError, NotFoundError } from "../../../lib/errors";
import { error, handleError, success } from "../../../lib/response";
import { requireUser } from "../../../lib/utils";
import { requireProAccess } from "../../../middleware";
import type { Services } from "../../../services";
import { createPreviewToken } from "../../../lib/preview-token";
import { logger } from "../../../lib/logger";
import {
	resolveEnvironment,
	getProjectName,
	getPublishedDomain,
	getProSiteUrls,
} from "../../../lib/domain-utils";
import {
	ensurePagesProject,
	ensureCustomDomain,
	attachDomainToPages,
} from "../../../lib/cloudflare";
 
// Adapter: convert CloudflareBindings to domain-utils parameters
function getUrls(slug: string | null, env: CloudflareBindings) {
	const resolvedEnv = resolveEnvironment(env.ENVIRONMENT);
	return getProSiteUrls(slug, resolvedEnv, {
		localBaseUrl: env.PRO_SITES_URL,
	});
}
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		proId: string;
		proRole: string;
	};
};
 
const publishRoutes = new Hono<Env>();
 
// Minimum time between publish attempts (in minutes)
const PUBLISH_COOLDOWN_MINUTES = 2;
 
// Trigger website publish (create build job)
publishRoutes.post(
	"/:proId/website/publish",
	requireProAccess,
	async (c) => {
		try {
			const proRole = c.get("proRole");
			if (proRole !== "owner" && proRole !== "admin") {
				return error(c, "FORBIDDEN", "Only owners can manage website settings", 403);
			}
 
			const dal = c.get("dal");
			const user = requireUser(c.get("user"));
			const proId = c.get("proId");
 
			// OPTIMIZATION: Fetch website and pro in parallel
			const [website, pro] = await Promise.all([
				dal.proWebsites.findByProId(proId),
				dal.pros.findById(proId),
			]);
 
			if (!website) {
				throw new NotFoundError(
					"Website not configured. Please select a template first.",
				);
			}
 
			if (!pro) {
				throw new NotFoundError("Pro not found");
			}
 
			if (pro.status !== "published") {
				throw new BadRequestError(
					"Pro profile must be published before publishing website",
				);
			}
 
			if (!pro.slug) {
				throw new BadRequestError(
					"Pro must have a slug before publishing website",
				);
			}
 
			// Rate limiting: Check if enough time has passed since last publish attempt
			const latestBuild = await dal.websiteBuildJobs.findLatestBuildJob(
				website.id,
			);
			if (latestBuild) {
				const timeSinceLastBuild =
					Date.now() - new Date(latestBuild.dateCreated).getTime();
				const cooldownMs = PUBLISH_COOLDOWN_MINUTES * 60 * 1000;
				if (timeSinceLastBuild < cooldownMs) {
					const remainingSeconds = Math.ceil(
						(cooldownMs - timeSinceLastBuild) / 1000,
					);
					throw new BadRequestError(
						`Please wait ${remainingSeconds} seconds before publishing again`,
					);
				}
			}
 
			// Cancel any existing pending jobs
			await dal.websiteBuildJobs.cancelPendingJobs(website.id);
 
			// Compute domain names using centralized utility
			const env = resolveEnvironment(c.env.ENVIRONMENT);
			const projectName = getProjectName(pro.slug, env);
			const customDomain = getPublishedDomain(pro.slug, env);
 
			logger.info(`[Publish] Environment: ${env}`);
			logger.info(`[Publish] Pro slug: ${pro.slug}`);
			logger.info(`[Publish] Project name: ${projectName}`);
			logger.info(`[Publish] Custom domain: ${customDomain ?? "none"}`);
			logger.info(
				`[Publish] CF credentials: token=${c.env.CLOUDFLARE_API_TOKEN ? "set" : "NOT SET"}, accountId=${c.env.CLOUDFLARE_ACCOUNT_ID ? "set" : "NOT SET"}`,
			);
 
			// Ensure Pages project + custom domain exist before building
			if (c.env.CLOUDFLARE_API_TOKEN && c.env.CLOUDFLARE_ACCOUNT_ID) {
				logger.info(`[Publish] Ensuring Pages project exists: ${projectName}`);
				const projectCreated = await ensurePagesProject(
					projectName,
					c.env.CLOUDFLARE_API_TOKEN,
					c.env.CLOUDFLARE_ACCOUNT_ID,
				);
				logger.info(
					`[Publish] Pages project result: ${projectCreated ? "OK" : "FAILED"}`,
				);
				if (!projectCreated) {
					throw new BadRequestError(
						"Failed to prepare deployment infrastructure. Please try again.",
					);
				}
 
				if (customDomain) {
					logger.info(
						`[Publish] Ensuring custom domain + DNS: ${customDomain} → ${projectName}.pages.dev`,
					);
					const domainResult = await ensureCustomDomain(
						projectName,
						customDomain,
						c.env.CLOUDFLARE_API_TOKEN,
						c.env.CLOUDFLARE_ACCOUNT_ID,
					);
					if (!domainResult) {
						// Domain/DNS setup is non-blocking: the site is still accessible via
						// {project}.pages.dev, and domains can be retried on the next publish.
						// We log a warning but allow the build to proceed.
						logger.warn(
							`[Publish] Custom domain setup failed for ${customDomain} — site will be accessible via ${projectName}.pages.dev`,
						);
					} else {
						logger.info(`[Publish] Custom domain result: OK`);
					}
				} else {
					logger.info("[Publish] No custom domain to attach (null)");
				}
				// Attach pro-owned custom domain if verified
				if (website.customDomain && website.customDomainVerified) {
					logger.info(
						`[Publish] Attaching pro custom domain: ${website.customDomain}`,
					);
					const externalDomainResult = await attachDomainToPages(
						projectName,
						website.customDomain,
						c.env.CLOUDFLARE_API_TOKEN,
						c.env.CLOUDFLARE_ACCOUNT_ID,
					);
					if (!externalDomainResult) {
						logger.warn(
							`[Publish] Pro custom domain attachment failed for ${website.customDomain} — platform subdomain still works`,
						);
					} else {
						logger.info(
							`[Publish] Pro custom domain attached: ${website.customDomain}`,
						);
					}
				}
			} else {
				logger.warn(
					"[Publish] Skipping Pages/DNS setup — CF credentials not configured",
				);
			}
 
			// Store the project name on the website record
			if (website.pagesProjectName !== projectName) {
				await dal.proWebsites.update(website.id, {
					pagesProjectName: projectName,
				});
			}
 
			// Get next version number
			const version = await dal.websiteBuildJobs.getNextVersion(website.id);
 
			// Create new build job (use "queued" directly since we send to queue next)
			const buildJob = await dal.websiteBuildJobs.createBuildJob({
				proWebsiteId: website.id,
				version,
				triggeredBy: user.id,
				triggerType: "manual",
				status: c.env.BUILD_QUEUE ? "queued" : "pending",
			});
 
			if (!buildJob) {
				throw new Error("Failed to create build job");
			}
 
			// Log "created" event
			await dal.websiteBuildJobs.logBuildEvent(
				buildJob.id,
				"created",
				`Build v${version} created by ${user.email}`,
				{ projectName, customDomain, proSlug: pro.slug },
			);
 
			// Enqueue message to trigger build worker (if queue is available)
			logger.info("[Publish] BUILD_QUEUE available:", !!c.env.BUILD_QUEUE);
			if (c.env.BUILD_QUEUE) {
				const queueMessage = {
					jobId: buildJob.id,
					proId,
					proWebsiteId: website.id,
					projectName,
					timestamp: Date.now(),
				};
				logger.info(
					"[Publish] Sending to queue:",
					JSON.stringify(queueMessage),
				);
				await c.env.BUILD_QUEUE.send(queueMessage);
				logger.info("[Publish] Queue message sent successfully");
 
				// Log "queued" event
				await dal.websiteBuildJobs.logBuildEvent(
					buildJob.id,
					"queued",
					"Build job sent to queue",
				);
			} else {
				// BUILD_QUEUE not configured (e.g. local/preview env) — job stays "pending"
				logger.warn("[Publish] BUILD_QUEUE not available, build job created but not queued");
			}
 
			return success(c, {
				buildJob,
				message: "Build queued successfully",
			});
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
// Cancel active build
publishRoutes.post(
	"/:proId/website/cancel-build",
	requireProAccess,
	async (c) => {
		try {
			const proRole = c.get("proRole");
			if (proRole !== "owner" && proRole !== "admin") {
				return error(c, "FORBIDDEN", "Only owners can manage website settings", 403);
			}
 
			const dal = c.get("dal");
			const proId = c.get("proId");
 
			const website = await dal.proWebsites.findByProId(proId);
			if (!website) {
				throw new NotFoundError("Website not found");
			}
 
			const cancelledCount = await dal.websiteBuildJobs.cancelActiveBuild(
				website.id,
			);
 
			if (cancelledCount > 0) {
				const latestBuild = await dal.websiteBuildJobs.findLatestBuildJob(
					website.id,
				);
				if (latestBuild) {
					await dal.websiteBuildJobs.logBuildEvent(
						latestBuild.id,
						"cancelled",
						"Build cancelled by user",
					);
				}
			}
 
			return success(c, {
				cancelled: cancelledCount,
				message:
					cancelledCount > 0
						? `Cancelled ${cancelledCount} active build(s)`
						: "No active builds to cancel",
			});
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
// Get build status (for polling)
publishRoutes.get(
	"/:proId/website/build-status",
	requireProAccess,
	async (c) => {
		try {
			const dal = c.get("dal");
			const proId = c.get("proId");
 
			const website = await dal.proWebsites.findByProId(proId);
			if (!website) {
				throw new NotFoundError("Website not found");
			}
 
			const latestBuild = await dal.websiteBuildJobs.findLatestBuildJob(
				website.id,
			);
 
			return success(c, {
				latestBuild,
				websiteStatus: website.status,
				hasUnpublishedChanges: website.hasUnpublishedChanges,
			});
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
// Get build history
publishRoutes.get(
	"/:proId/website/builds",
	requireProAccess,
	async (c) => {
		try {
			const dal = c.get("dal");
			const proId = c.get("proId");
 
			const website = await dal.proWebsites.findByProId(proId);
			if (!website) {
				throw new NotFoundError("Website not found");
			}
 
			const offset = parseInt(c.req.query("offset") ?? "0", 10);
			const limit = Math.min(parseInt(c.req.query("limit") ?? "10", 10), 50);
 
			const builds = await dal.websiteBuildJobs.findBuildJobs(
				{ proWebsiteId: website.id },
				offset,
				limit,
			);
 
			return success(c, builds);
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
// Generate preview token (for authenticated preview access)
publishRoutes.get(
	"/:proId/website/preview-token",
	requireProAccess,
	async (c) => {
		try {
			const dal = c.get("dal");
			const user = requireUser(c.get("user"));
			const proId = c.get("proId");
 
			const [website, pro] = await Promise.all([
				dal.proWebsites.findByProId(proId),
				dal.pros.findById(proId),
			]);
 
			if (!website) {
				throw new NotFoundError("Website not found");
			}
 
			if (!pro?.slug) {
				throw new BadRequestError("Pro must have a slug for preview");
			}
 
			// Generate a cryptographically signed preview token
			// Uses HMAC-SHA256 for stateless validation (no DB storage needed)
			// Reuses BETTER_AUTH_SECRET for signing (already configured for auth)
			const secret = c.env.BETTER_AUTH_SECRET;
			if (!secret) {
				throw new Error("BETTER_AUTH_SECRET not configured for token signing");
			}
 
			const { token, expiresAt } = await createPreviewToken(
				pro.slug,
				proId,
				user.id,
				secret,
				30, // 30 minutes expiry
			);
 
			const urls = getUrls(pro.slug, c.env);
			// URL-encode the token for safe transmission
			const previewUrl = urls.previewUrl
				? `${urls.previewUrl}${urls.previewUrl.includes("?") ? "&" : "?"}token=${encodeURIComponent(token)}`
				: null;
 
			return success(c, {
				token,
				expiresAt: expiresAt.toISOString(),
				previewUrl,
			});
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
export default publishRoutes;