diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000000..ca4a787b93 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,50 @@ +name: Trigger Cloudflare deploy + +on: + push: + branches: [cloudflare-dev] + workflow_dispatch: + +permissions: {} + +jobs: + deploy: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Verify target branch + if: github.event_name == 'workflow_dispatch' + run: | + if [ "${GITHUB_REF}" != "refs/heads/cloudflare-dev" ]; then + echo "Manual deploy hook runs must target refs/heads/cloudflare-dev (got ${GITHUB_REF})" >&2 + exit 1 + fi + + - name: Trigger Cloudflare build + env: + DEPLOY_HOOK: ${{ secrets.CLOUDFLARE_DEPLOY_HOOK }} + run: | + if [ -z "$DEPLOY_HOOK" ]; then + echo "CLOUDFLARE_DEPLOY_HOOK is not configured" >&2 + exit 1 + fi + + max_attempts=4 + delay=2 + for attempt in $(seq 1 "$max_attempts"); do + status=$(curl --silent --show-error --output /tmp/cf-deploy-hook.out --write-out "%{http_code}" \ + --connect-timeout 10 --max-time 30 --request POST "$DEPLOY_HOOK") || status="000" + if [ "$status" -ge 200 ] && [ "$status" -lt 300 ]; then + cat /tmp/cf-deploy-hook.out + exit 0 + fi + if [ "$status" = "503" ] && [ "$attempt" -lt "$max_attempts" ]; then + echo "Cloudflare deploy hook returned HTTP 503 (attempt ${attempt}/${max_attempts}); retrying in ${delay}s..." >&2 + sleep "$delay" + delay=$((delay * 2)) + continue + fi + cat /tmp/cf-deploy-hook.out >&2 || true + echo "Cloudflare deploy hook request failed with HTTP ${status}" >&2 + exit 1 + done diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000000..2bd5a0a98a --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +22 diff --git a/frontend/apps/artcraft-website-next/.gitignore b/frontend/apps/artcraft-website-next/.gitignore index a42ea1a436..ee01063202 100644 --- a/frontend/apps/artcraft-website-next/.gitignore +++ b/frontend/apps/artcraft-website-next/.gitignore @@ -1,5 +1,9 @@ node_modules/ .next/ +out/ +.wrangler/ +.build-route-stash/ +worker/generated-catalog.mjs next-env.d.ts *.tsbuildinfo playwright-report/ diff --git a/frontend/apps/artcraft-website-next/.nvmrc b/frontend/apps/artcraft-website-next/.nvmrc new file mode 100644 index 0000000000..2bd5a0a98a --- /dev/null +++ b/frontend/apps/artcraft-website-next/.nvmrc @@ -0,0 +1 @@ +22 diff --git a/frontend/apps/artcraft-website-next/next.config.ts b/frontend/apps/artcraft-website-next/next.config.ts index c70794e965..7060a19789 100644 --- a/frontend/apps/artcraft-website-next/next.config.ts +++ b/frontend/apps/artcraft-website-next/next.config.ts @@ -1,6 +1,9 @@ import type { NextConfig } from "next"; +const isStaticExport = process.env.NEXT_STATIC_EXPORT === "1"; + const nextConfig: NextConfig = { + ...(isStaticExport && { output: "export" }), reactStrictMode: true, // Share previews must work from the raw , even for an unknown crawler // or curl. Wait for generateMetadata instead of streaming it into the body. @@ -12,61 +15,63 @@ const nextConfig: NextConfig = { // output file tracing on serverless deploys). turbopack: { root: __dirname }, outputFileTracingRoot: __dirname, - async redirects() { - return [ - // Legacy Stripe return paths from the Vite site; checkout now lives in - // the webapp, which serves the canonical slash forms. - ...["checkout_success", "checkout_cancel", "portal_closed"].map( - (route) => ({ - source: `/${route}`, - destination: `https://app.getartcraft.com/checkout/${ - route === "checkout_success" ? "success" : "cancel" - }`, - permanent: false, - }), - ), - // LoopCraft is no longer offered: its old page and share images go to - // the Crafting Apps index. - { - source: "/apps/loopcraft", - destination: "/apps", - permanent: true, - }, - { - source: "/images/apps/loopcraft/:file", - destination: "/apps", - permanent: true, - }, - // DrawCraft was renamed VectorCraft; the Crafting Apps READMEs still - // link the old page. - { - source: "/apps/drawcraft", - destination: "/apps/vectorcraft", - permanent: true, - }, - // PrintCraft was renamed PdfCraft. Old page links and share images - // (cached by social sites) follow it. - { - source: "/apps/printcraft", - destination: "/apps/pdfcraft", - permanent: true, - }, - { - source: "/images/apps/printcraft/:file", - destination: "/images/apps/pdfcraft/:file", - permanent: true, - }, - // Legacy share-link form (`/media?media=`) from the Vite site; - // the canonical route is /media/. Mirrored in netlify.toml so - // the edge answers it before the Next runtime. - { - source: "/media", - has: [{ type: "query", key: "media", value: "(?.+)" }], - destination: "/media/:token", - permanent: true, - }, - ]; - }, + ...(!isStaticExport && { + async redirects() { + return [ + // Legacy Stripe return paths from the Vite site; checkout now lives in + // the webapp, which serves the canonical slash forms. + ...["checkout_success", "checkout_cancel", "portal_closed"].map( + (route) => ({ + source: `/${route}`, + destination: `https://app.getartcraft.com/checkout/${ + route === "checkout_success" ? "success" : "cancel" + }`, + permanent: false, + }), + ), + // LoopCraft is no longer offered: its old page and share images go to + // the Crafting Apps index. + { + source: "/apps/loopcraft", + destination: "/apps", + permanent: true, + }, + { + source: "/images/apps/loopcraft/:file", + destination: "/apps", + permanent: true, + }, + // DrawCraft was renamed VectorCraft; the Crafting Apps READMEs still + // link the old page. + { + source: "/apps/drawcraft", + destination: "/apps/vectorcraft", + permanent: true, + }, + // PrintCraft was renamed PdfCraft. Old page links and share images + // (cached by social sites) follow it. + { + source: "/apps/printcraft", + destination: "/apps/pdfcraft", + permanent: true, + }, + { + source: "/images/apps/printcraft/:file", + destination: "/images/apps/pdfcraft/:file", + permanent: true, + }, + // Legacy share-link form (`/media?media=`) from the Vite site; + // the canonical route is /media/. Mirrored in the Worker so + // the edge answers it in static exports. + { + source: "/media", + has: [{ type: "query", key: "media", value: "(?.+)" }], + destination: "/media/:token", + permanent: true, + }, + ]; + }, + }), }; export default nextConfig; diff --git a/frontend/apps/artcraft-website-next/package.json b/frontend/apps/artcraft-website-next/package.json index 0a42ca1922..b2a7ec8e7b 100644 --- a/frontend/apps/artcraft-website-next/package.json +++ b/frontend/apps/artcraft-website-next/package.json @@ -8,6 +8,7 @@ "scripts": { "dev": "next dev --turbopack", "build": "next build", + "build:cloudflare": "node scripts/build-cloudflare.mjs", "start": "next start", "typecheck": "tsc --noEmit", "test:media": "playwright test tests/media.spec.ts tests/media-metadata.spec.ts", diff --git a/frontend/apps/artcraft-website-next/scripts/build-cloudflare.mjs b/frontend/apps/artcraft-website-next/scripts/build-cloudflare.mjs new file mode 100644 index 0000000000..ef615102f4 --- /dev/null +++ b/frontend/apps/artcraft-website-next/scripts/build-cloudflare.mjs @@ -0,0 +1,77 @@ +import { execFileSync } from "node:child_process"; +import { existsSync, mkdirSync, renameSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; + +const ROOT = process.cwd(); +const APP_DIR = join(ROOT, "src", "app"); +const STASH_DIR = join(ROOT, ".build-route-stash"); + +// Dynamic route handlers that Next.js dev/Playwright tests use directly, +// but that are replaced in production by build-time static files + the Cloudflare Worker. +const DYNAMIC_ROUTE_PATHS = [ + "apt", + "rpm", + "arch", + "keys", + "index", + "oci-signatures", + "artcraft-oci.flatpakrepo", + "apps/[slug]/[filename]", + "media/[token]/oembed", + "media/[token]/player", +]; + +/** + * Temporarily moves dynamic Next.js route handlers out of `src/app` before running + * a static export build, recovering any routes left behind by an interrupted build first. + */ +function stashRoutes() { + restoreRoutes(); + rmSync(STASH_DIR, { recursive: true, force: true }); + for (const rel of DYNAMIC_ROUTE_PATHS) { + const src = join(APP_DIR, rel); + if (!existsSync(src)) continue; + const dest = join(STASH_DIR, rel); + mkdirSync(dirname(dest), { recursive: true }); + renameSync(src, dest); + } +} + +/** + * Restores stashed dynamic Next.js route handlers back into `src/app` and removes the stash directory. + */ +function restoreRoutes() { + if (!existsSync(STASH_DIR)) return; + for (const rel of DYNAMIC_ROUTE_PATHS) { + const stashed = join(STASH_DIR, rel); + if (!existsSync(stashed)) continue; + const target = join(APP_DIR, rel); + mkdirSync(dirname(target), { recursive: true }); + renameSync(stashed, target); + } + rmSync(STASH_DIR, { recursive: true, force: true }); +} + +for (const sig of ["SIGINT", "SIGTERM"]) { + process.on(sig, () => { + restoreRoutes(); + process.exit(1); + }); +} + +try { + stashRoutes(); + const nextBin = join(ROOT, "node_modules", ".bin", "next"); + execFileSync(nextBin, ["build"], { + stdio: "inherit", + env: { ...process.env, NEXT_STATIC_EXPORT: "1" }, + }); +} finally { + restoreRoutes(); +} + +const jitiBin = join(ROOT, "node_modules", ".bin", "jiti"); +execFileSync(process.execPath, ["--no-warnings", jitiBin, join(ROOT, "scripts", "generate-static-repos.mjs")], { + stdio: "inherit", + env: process.env, +}); diff --git a/frontend/apps/artcraft-website-next/scripts/generate-static-repos.mjs b/frontend/apps/artcraft-website-next/scripts/generate-static-repos.mjs new file mode 100644 index 0000000000..588ab6b670 --- /dev/null +++ b/frontend/apps/artcraft-website-next/scripts/generate-static-repos.mjs @@ -0,0 +1,246 @@ +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { gzipSync } from "node:zlib"; +import { artcraftStudioDownloads } from "../src/lib/artcraft-studio.ts"; +import { getTutorialItems } from "../src/lib/content.ts"; +import { craftLauncherDownloads } from "../src/lib/craft-launcher.ts"; +import { + CRAFTING_APPS, + craftAppName, + craftAppRelease, + craftReleaseDownloads, +} from "../src/lib/crafting-apps.ts"; +import { getFlatpakOciIndex } from "../src/lib/flatpak-oci.ts"; +import { buildOciSignaturePayload } from "../src/lib/flatpak-signatures.ts"; +import { + RPM_REPO_TIMESTAMP, + VALID_APT_ARCHES, + VALID_PACMAN_ARCHES, + VALID_RPM_ARCHES, + generateAptPackages, + generateAptRelease, + generatePacmanDb, + generateRpmRepomdXml, + getLinuxRepoApps, + getRpmPrimaryXml, + resolvePackageDownloadUrl, +} from "../src/lib/linux-repos.ts"; +import { + getSigningPublicKey, + isRepoSigningConfigured, + signCleartext, + signDetachedArmored, + signDetachedBinary, + signInlineBinary, +} from "../src/lib/repo-signing.ts"; + +const ROOT = process.cwd(); +const OUT_DIR = join(ROOT, "out"); +const WORKER_DIR = join(ROOT, "worker"); + +/** + * Writes a generated repository artifact under the static `out/` directory. + */ +function writeOut(relPath, content) { + const fullPath = join(OUT_DIR, relPath); + mkdirSync(dirname(fullPath), { recursive: true }); + writeFileSync(fullPath, content); +} + +console.info("Generating static Linux repositories and Flatpak OCI catalog..."); + +const [signingConfigured, publicKey, , flatpakIndex] = await Promise.all([ + isRepoSigningConfigured(), + getSigningPublicKey(), + getLinuxRepoApps({ deb: true, rpm: true, arch: true }), + getFlatpakOciIndex(), +]); + +if (signingConfigured && !publicKey) { + throw new Error("Repo signing is configured but the public key could not be loaded"); +} +if (signingConfigured && publicKey) { + writeOut("keys/artcraft.asc", publicKey.armored); + writeOut("keys/artcraft.gpg", Buffer.from(publicKey.binary)); +} + +/** + * Generates APT `Packages`, `Packages.gz`, `Release`, and optional `Release.gpg`/`InRelease` signatures. + */ +async function buildAptRepo() { + await Promise.all( + [...VALID_APT_ARCHES].map(async (arch) => { + const packages = await generateAptPackages(arch); + const base = `apt/dists/stable/main/binary-${arch}`; + writeOut(`${base}/Packages`, packages); + writeOut(`${base}/Packages.gz`, gzipSync(Buffer.from(packages, "utf-8"))); + }), + ); + + const aptRelease = await generateAptRelease(); + writeOut("apt/dists/stable/Release", aptRelease); + if (signingConfigured) { + const [releaseGpg, inRelease] = await Promise.all([ + signDetachedArmored(aptRelease), + signCleartext(aptRelease), + ]); + if (!releaseGpg || !inRelease) { + throw new Error("Failed to sign the apt Release file"); + } + writeOut("apt/dists/stable/Release.gpg", releaseGpg); + writeOut("apt/dists/stable/InRelease", inRelease); + } +} + +/** + * Generates RPM `primary.xml.gz`, `repomd.xml`, and optional `repomd.xml.asc` for a repository prefix. + */ +async function buildRpmTarget(prefix, archFilter) { + const primaryXml = await getRpmPrimaryXml(archFilter); + const primaryBuffer = Buffer.from(primaryXml, "utf-8"); + const primaryGzBuffer = gzipSync(primaryBuffer); + const repomd = generateRpmRepomdXml(primaryBuffer, primaryGzBuffer, RPM_REPO_TIMESTAMP); + + writeOut(`${prefix}/repodata/primary.xml.gz`, primaryGzBuffer); + writeOut(`${prefix}/repodata/repomd.xml`, repomd); + if (signingConfigured) { + const repomdAsc = await signDetachedArmored(repomd); + if (!repomdAsc) { + throw new Error(`Failed to sign ${prefix}/repodata/repomd.xml`); + } + writeOut(`${prefix}/repodata/repomd.xml.asc`, repomdAsc); + } +} + +/** + * Generates top-level and architecture-specific RPM repositories and public key files. + */ +async function buildRpmRepos() { + if (signingConfigured && publicKey) { + writeOut("rpm/repodata/repomd.xml.key", publicKey.armored); + } + await Promise.all([ + buildRpmTarget("rpm", undefined), + ...[...VALID_RPM_ARCHES].map((arch) => buildRpmTarget(`rpm/${arch}`, arch)), + ]); +} + +/** + * Generates Arch Linux Pacman `artcraft.db`, `artcraft.db.tar.gz`, and optional `artcraft.db.sig` files. + */ +async function buildPacmanRepos() { + await Promise.all( + [...VALID_PACMAN_ARCHES].map(async (arch) => { + const db = await generatePacmanDb(arch); + writeOut(`arch/${arch}/artcraft.db`, db); + writeOut(`arch/${arch}/artcraft.db.tar.gz`, db); + if (signingConfigured) { + const sig = await signDetachedBinary(new Uint8Array(db)); + if (!sig) { + throw new Error(`Failed to sign arch/${arch}/artcraft.db`); + } + writeOut(`arch/${arch}/artcraft.db.sig`, Buffer.from(sig)); + } + }), + ); +} + +/** + * Generates Flatpak OCI lookaside OpenPGP signature packets (`signature-1`) for every indexed image digest. + */ +async function buildFlatpakSignatures() { + if (!signingConfigured) return; + const tasks = []; + for (const repo of flatpakIndex.Results) { + const seenDigests = new Set(); + for (const image of repo.Images) { + if (!image.Digest.startsWith("sha256:") || seenDigests.has(image.Digest)) continue; + seenDigests.add(image.Digest); + tasks.push( + (async () => { + const payload = buildOciSignaturePayload(image.Digest, repo.Repository); + const sig = await signInlineBinary(Buffer.from(payload, "utf-8")); + if (!sig) { + throw new Error(`Failed to sign Flatpak OCI digest ${image.Digest} for ${repo.Repository}`); + } + const hex = image.Digest.slice("sha256:".length); + writeOut(`oci-signatures/${repo.Repository}@sha256=${hex}/signature-1`, Buffer.from(sig)); + })(), + ); + } + } + await Promise.all(tasks); +} + +await Promise.all([ + buildAptRepo(), + buildRpmRepos(), + buildPacmanRepos(), + buildFlatpakSignatures(), +]); + +// Build static lookup tables for the Cloudflare Worker +const packageRedirects = {}; +const allDownloads = [ + ...artcraftStudioDownloads(), + ...craftLauncherDownloads(), + ...CRAFTING_APPS.flatMap((app) => { + const release = craftAppRelease(app); + return release ? craftReleaseDownloads(app, release) : []; + }), +]; + +for (const item of allDownloads) { + const resolved = resolvePackageDownloadUrl(item.fileName); + if (resolved) { + packageRedirects[item.fileName] = resolved; + } + if (item.fileName.endsWith(".rpm")) { + const ascName = `${item.fileName}.asc`; + const ascUrl = resolvePackageDownloadUrl(ascName); + if (ascUrl) packageRedirects[ascName] = ascUrl; + } + if (item.fileName.endsWith(".pkg.tar.zst")) { + const sigName = `${item.fileName}.sig`; + const sigUrl = resolvePackageDownloadUrl(sigName); + if (sigUrl) packageRedirects[sigName] = sigUrl; + } +} + +const flatpakApps = Object.fromEntries( + CRAFTING_APPS.map((app) => [ + app.slug, + { + title: craftAppName(app), + appId: `ai.storyteller.${app.slug}`, + }, + ]), +); + +const tutorialRedirects = {}; +for (const item of getTutorialItems()) { + for (const alias of item.aliases) { + if (alias !== item.slug) { + tutorialRedirects[alias] = item.slug; + } + } +} + +mkdirSync(WORKER_DIR, { recursive: true }); +writeFileSync( + join(WORKER_DIR, "generated-catalog.mjs"), + `// Generated at build time by scripts/generate-static-repos.mjs — do not edit by hand. +export const SIGNING_CONFIGURED = ${JSON.stringify(signingConfigured)}; +export const PUBLIC_KEY_BASE64 = ${JSON.stringify( + publicKey ? Buffer.from(publicKey.binary).toString("base64") : null, + )}; +export const FLATPAK_APPS = ${JSON.stringify(flatpakApps)}; +export const FLATPAK_INDEX = ${JSON.stringify(flatpakIndex)}; +export const PACKAGE_REDIRECTS = ${JSON.stringify(packageRedirects)}; +export const TUTORIAL_REDIRECTS = ${JSON.stringify(tutorialRedirects)}; +`, +); + +console.info( + `Static repository generation complete (signed: ${signingConfigured}, OCI repos: ${flatpakIndex.Results.length}, package redirects: ${Object.keys(packageRedirects).length}).`, +); diff --git a/frontend/apps/artcraft-website-next/src/app/media/[token]/page.tsx b/frontend/apps/artcraft-website-next/src/app/media/[token]/page.tsx index bd7b7d25aa..96efc9e468 100644 --- a/frontend/apps/artcraft-website-next/src/app/media/[token]/page.tsx +++ b/frontend/apps/artcraft-website-next/src/app/media/[token]/page.tsx @@ -1,13 +1,23 @@ import type { Metadata } from "next"; import MediaPage from "@/components/media/media-page"; import { fetchPublicMediaFile } from "@/lib/fetch-public-media"; -import { mediaEmbed, mediaShareImage, MEDIA_SHARE_ORIGIN } from "@/lib/media-sharing"; +import { mediaEmbed, mediaShareImage, MEDIA_SHARE_ORIGIN, MEDIA_SHELL_TOKEN } from "@/lib/media-sharing"; import { mediaTitle } from "@/lib/media"; const FALLBACK_IMAGE = { url: "/images/og-image.png", width: 1200, height: 630, alt: "ArtCraft" }; type Props = { params: Promise<{ token: string }> }; +/** + * Generates static placeholder route parameters when exporting the site for Cloudflare. + */ +export function generateStaticParams() { + return process.env.NEXT_STATIC_EXPORT === "1" ? [{ token: MEDIA_SHELL_TOKEN }] : []; +} + +/** + * Generates Open Graph, Twitter Card, and oEmbed metadata for a shared media route. + */ export async function generateMetadata({ params }: Props): Promise { const { token } = await params; const url = `/media/${encodeURIComponent(token)}`; @@ -29,6 +39,7 @@ export async function generateMetadata({ params }: Props): Promise { description: fallbackDescription, images: [FALLBACK_IMAGE], }, }; + if (token === MEDIA_SHELL_TOKEN) return metadata; const media = await fetchPublicMediaFile(token); if (!media) return metadata; const title = mediaTitle(media); @@ -76,6 +87,9 @@ export async function generateMetadata({ params }: Props): Promise { }; } +/** + * Renders the shared media viewer page for a given media token. + */ export default async function Media({ params }: Props) { const { token } = await params; // Resolve in the browser, using the same session credentials as the Vite diff --git a/frontend/apps/artcraft-website-next/src/app/pricing/page.tsx b/frontend/apps/artcraft-website-next/src/app/pricing/page.tsx index 88ddb9b836..8ab401ef57 100644 --- a/frontend/apps/artcraft-website-next/src/app/pricing/page.tsx +++ b/frontend/apps/artcraft-website-next/src/app/pricing/page.tsx @@ -1,9 +1,11 @@ import type { Metadata } from "next"; +import { Suspense } from "react"; import { TagIcon } from "lucide-react"; import RevealManager from "@/components/reveal-manager"; import { SectionShell, SectionEyebrow } from "@/components/landing/section-shell"; import { Accent, PageHeader } from "@/components/page/page-header"; import CreditsCta from "@/components/pricing/credits-cta"; +import PricingHeader from "@/components/pricing/pricing-header"; import PricingTable from "@/components/pricing/pricing-table"; import { PROMO_PCT } from "@/lib/pricing-data"; @@ -14,27 +16,23 @@ export const metadata: Metadata = { alternates: { canonical: "/pricing" }, }; -// Referral code that swaps the header for the Seedance early-access pitch -// (kept from the Vite site's ?ref=sd2fakeyou campaign links). -const SEEDANCE_REF = "sd2fakeyou"; const SEEDANCE_VIMEO_URL = "https://player.vimeo.com/video/1169289718?autoplay=1&muted=1&loop=1&background=0&byline=0&portrait=0&title=0"; -type SearchParams = Promise>; - -export default async function PricingPage({ - searchParams, -}: { - searchParams: SearchParams; -}) { - const params = await searchParams; - const isSeedanceRef = params.ref === SEEDANCE_REF; - +/** + * Renders the ArtCraft pricing page with plan comparison and credit information. + */ +export default function PricingPage() { return ( <> - {isSeedanceRef ? : } + }> + } + seedanceHeader={} + /> + ({ url: `${SITE_URL}${route.path}`, diff --git a/frontend/apps/artcraft-website-next/src/app/tutorials/[slug]/page.tsx b/frontend/apps/artcraft-website-next/src/app/tutorials/[slug]/page.tsx index 5e7773838d..86fe1054e9 100644 --- a/frontend/apps/artcraft-website-next/src/app/tutorials/[slug]/page.tsx +++ b/frontend/apps/artcraft-website-next/src/app/tutorials/[slug]/page.tsx @@ -16,12 +16,21 @@ type Params = Promise<{ slug: string }>; export const dynamicParams = false; // Aliases are served too, then redirected to the canonical slug below. +/** + * Generates static route parameters for canonical tutorial slugs (and aliases in non-export builds). + */ export function generateStaticParams() { - return getTutorialItems().flatMap((item) => - [item.slug, ...item.aliases].map((slug) => ({ slug })), + const slugs = new Set( + getTutorialItems().flatMap((item) => + process.env.NEXT_STATIC_EXPORT === "1" ? [item.slug] : [item.slug, ...item.aliases], + ), ); + return [...slugs].map((slug) => ({ slug })); } +/** + * Generates page metadata for a tutorial article by slug. + */ export async function generateMetadata({ params, }: { @@ -37,6 +46,9 @@ export async function generateMetadata({ }; } +/** + * Renders a tutorial article page, redirecting alias slugs to the canonical slug when needed. + */ export default async function TutorialArticlePage({ params, }: { diff --git a/frontend/apps/artcraft-website-next/src/components/media/media-page.tsx b/frontend/apps/artcraft-website-next/src/components/media/media-page.tsx index bbafdf7a6c..b83d0a4efe 100644 --- a/frontend/apps/artcraft-website-next/src/components/media/media-page.tsx +++ b/frontend/apps/artcraft-website-next/src/components/media/media-page.tsx @@ -6,6 +6,7 @@ import { SectionShell, SectionEyebrow } from "@/components/landing/section-shell import { Accent } from "@/components/page/page-header"; import { Button } from "@/components/ui"; import { getMediaPrompt, getSharedMedia } from "@/lib/media-api"; +import { MEDIA_SHELL_TOKEN } from "@/lib/media-sharing"; import { MEDIA_LABELS, mediaKind, mediaTitle, type MediaDimensions, type MediaPrompt, type SharedMedia } from "@/lib/media"; import { webappUrl } from "@/lib/links"; import MediaPreview from "./media-preview"; @@ -16,7 +17,25 @@ type MediaState = | { status: "ready"; media: SharedMedia } | { status: "error"; code?: number }; -export default function MediaPage({ token }: { token: string }) { +/** + * Safely decodes a URL path segment, returning the raw segment if percent-encoding is malformed. + */ +function safeDecodeSegment(segment: string): string { + try { + return decodeURIComponent(segment); + } catch { + return segment; + } +} + +/** + * Client-side shared media viewer that resolves the media token from props or `window.location.pathname`. + */ +export default function MediaPage({ token: propToken }: { token: string }) { + const token = + propToken === MEDIA_SHELL_TOKEN && typeof window !== "undefined" + ? safeDecodeSegment(window.location.pathname.replace(/^\/media\/([^/?#]+).*$/, "$1")) + : propToken; const [state, setState] = useState({ status: "loading" }); const [prompt, setPrompt] = useState(null); const [promptLoading, setPromptLoading] = useState(false); diff --git a/frontend/apps/artcraft-website-next/src/components/pricing/pricing-header.tsx b/frontend/apps/artcraft-website-next/src/components/pricing/pricing-header.tsx new file mode 100644 index 0000000000..f821e9a7ad --- /dev/null +++ b/frontend/apps/artcraft-website-next/src/components/pricing/pricing-header.tsx @@ -0,0 +1,20 @@ +"use client"; + +import { useSearchParams } from "next/navigation"; +import type { ReactNode } from "react"; + +const SEEDANCE_REF = "sd2fakeyou"; + +/** + * Selects between the Seedance promotional header and the default pricing header based on `?ref=`. + */ +export default function PricingHeader({ + defaultHeader, + seedanceHeader, +}: { + defaultHeader: ReactNode; + seedanceHeader: ReactNode; +}) { + const searchParams = useSearchParams(); + return <>{searchParams.get("ref") === SEEDANCE_REF ? seedanceHeader : defaultHeader}; +} diff --git a/frontend/apps/artcraft-website-next/src/lib/linux-repos.ts b/frontend/apps/artcraft-website-next/src/lib/linux-repos.ts index f45a6d1d9a..69932f9d75 100644 --- a/frontend/apps/artcraft-website-next/src/lib/linux-repos.ts +++ b/frontend/apps/artcraft-website-next/src/lib/linux-repos.ts @@ -119,8 +119,13 @@ export function getRequestBaseUrl(request: Request): string { return `${proto}://${fwdHost}`; } - // Check the request URL hostname (direct requests or Netlify edge URL) - if (url.protocol === "https:" && /^deploy-preview-\d+--artcraft-website-next\.netlify\.app$/.test(url.hostname)) { + // Check the request URL hostname (direct requests or Netlify/Cloudflare edge URL) + if ( + url.protocol === "https:" && + (url.hostname === "getartcraft.com" || + url.hostname === "getartcraft.dev" || + /^deploy-preview-\d+--artcraft-website-next\.netlify\.app$/.test(url.hostname)) + ) { return url.origin; } if ((url.hostname === "localhost" || url.hostname === "127.0.0.1") && url.protocol === "http:") { diff --git a/frontend/apps/artcraft-website-next/src/lib/media-sharing.ts b/frontend/apps/artcraft-website-next/src/lib/media-sharing.ts index 3e7aedc5ad..fe1f568508 100644 --- a/frontend/apps/artcraft-website-next/src/lib/media-sharing.ts +++ b/frontend/apps/artcraft-website-next/src/lib/media-sharing.ts @@ -1,6 +1,7 @@ import { mediaFormat, mediaKind, mediaThumbnail, safeMediaUrl, type SharedMedia } from "./media"; export const MEDIA_SHARE_ORIGIN = "https://getartcraft.com"; +export const MEDIA_SHELL_TOKEN = "__MEDIA_TOKEN__"; const PREVIEW_WIDTH = 1200; const VIDEO_TYPES: Record = { mp4: "video/mp4", webm: "video/webm" }; const AUDIO_TYPES: Record = { @@ -17,6 +18,9 @@ type MediaEmbed = { height: number; }; +/** + * Returns iframe player embed metadata for supported video and audio files, or null otherwise. + */ export function mediaEmbed(media: SharedMedia): MediaEmbed | null { const kind = mediaKind(media); if (kind !== "video" && kind !== "audio") return null; @@ -26,6 +30,9 @@ export function mediaEmbed(media: SharedMedia): MediaEmbed | null { return { kind, contentType, url, width: 640, height: kind === "video" ? 360 : 180 }; } +/** + * Resolves the primary social preview image URL for a shared media item. + */ export function mediaShareImage(media: SharedMedia): string | undefined { const cover = media.cover_image?.maybe_links; return mediaThumbnail(media.media_links, PREVIEW_WIDTH) diff --git a/frontend/apps/artcraft-website-next/worker/index.mjs b/frontend/apps/artcraft-website-next/worker/index.mjs new file mode 100644 index 0000000000..e18f3fe71f --- /dev/null +++ b/frontend/apps/artcraft-website-next/worker/index.mjs @@ -0,0 +1,729 @@ +import { + FLATPAK_APPS, + FLATPAK_INDEX, + PACKAGE_REDIRECTS, + PUBLIC_KEY_BASE64, + SIGNING_CONFIGURED, + TUTORIAL_REDIRECTS, +} from "./generated-catalog.mjs"; + +const MEDIA_SHARE_ORIGIN = "https://getartcraft.com"; +const MEDIA_SHELL_TOKEN = "__MEDIA_TOKEN__"; +const DEFAULT_API_HOST = "https://api.storyteller.ai"; +const PREVIEW_WIDTH = 1200; +const APT_KEYRING_PATH = "/etc/apt/keyrings/artcraft.gpg"; +const OCI_SIGNATURE_LOOKASIDE_PATH = "/oci-signatures"; + +const VIDEO_TYPES = { mp4: "video/mp4", webm: "video/webm" }; +const AUDIO_TYPES = { + mp3: "audio/mpeg", + wav: "audio/wav", + m4a: "audio/mp4", + aac: "audio/aac", + ogg: "audio/ogg", + opus: "audio/ogg", + flac: "audio/flac", +}; + +const MEDIA_LABELS = { + image: "Image", + video: "Video", + audio: "Audio", + mesh: "3D mesh", + splat: "3D splat", + unsupported: "Media file", +}; + +const VALID_RPM_ARCHES = new Set(["x86_64", "aarch64", "riscv64", "noarch"]); +const VALID_PACMAN_ARCHES = new Set(["x86_64", "aarch64"]); + +const REPO_CACHE_CONTROL = "public, max-age=300, s-maxage=3600, stale-while-revalidate=86400"; + +/** + * Escapes HTML special characters for safe interpolation into attributes and text nodes. + */ +function escapeHtml(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll('"', """) + .replaceAll("'", "'") + .replaceAll("<", "<") + .replaceAll(">", ">"); +} + +/** + * Decodes a URL path segment, returning null when percent-encoding is malformed. + */ +function safeDecode(segment) { + try { + return decodeURIComponent(segment); + } catch { + return null; + } +} + +/** + * Resolves the trusted base origin for generated Linux repository and Flatpak descriptors. + */ +function getRequestBaseUrl(request) { + const url = new URL(request.url); + const fwdHost = request.headers.get("x-forwarded-host"); + if (fwdHost && /^deploy-preview-\d+--artcraft-website-next\.netlify\.app(?::\d+)?$/.test(fwdHost)) { + return `https://${fwdHost}`; + } + if (fwdHost && /^(?:localhost|127\.0\.0\.1)(?::\d+)?$/.test(fwdHost)) { + const proto = + request.headers.get("x-forwarded-proto") || (url.protocol ? url.protocol.replace(":", "") : "http"); + return `${proto}://${fwdHost}`; + } + if ( + url.protocol === "https:" && + (url.hostname === "getartcraft.com" || + url.hostname === "getartcraft.dev" || + /^deploy-preview-\d+--artcraft-website-next\.netlify\.app$/.test(url.hostname)) + ) { + return url.origin; + } + if ((url.hostname === "localhost" || url.hostname === "127.0.0.1") && url.protocol === "http:") { + return url.origin; + } + return "https://getartcraft.com"; +} + +/** + * Returns Flatpak INI `GPGKey` and `SignatureLookaside` lines when repository signing is active. + */ +function flatpakSignatureLines(baseUrl) { + if (!SIGNING_CONFIGURED || !PUBLIC_KEY_BASE64) return []; + return [ + `GPGKey=${PUBLIC_KEY_BASE64}`, + `SignatureLookaside=${baseUrl}${OCI_SIGNATURE_LOOKASIDE_PATH}`, + ]; +} + +/** + * Normalizes Flatpak/OCI architecture query values to `amd64` or `arm64`. + */ +function normalizeArch(arch) { + if (!arch) return null; + const lower = arch.toLowerCase(); + if (lower === "amd64" || lower === "x86_64" || lower === "x64") return "amd64"; + if (lower === "arm64" || lower === "aarch64") return "arm64"; + return lower; +} + +/** + * Filters the precomputed Flatpak OCI index according to query parameters. + */ +function filterFlatpakIndex(searchParams) { + const arch = normalizeArch(searchParams.get("architecture")); + const ref = searchParams.get("label:org.flatpak.ref"); + const refMustExist = searchParams.get("label:org.flatpak.ref:exists") === "1"; + const tag = searchParams.get("tag"); + const reqRepo = searchParams.get("repository") ?? searchParams.get("repo"); + + const results = []; + for (const repo of FLATPAK_INDEX.Results) { + if (reqRepo && repo.Repository !== reqRepo) continue; + const images = repo.Images.filter((img) => { + if (arch && img.Architecture !== arch) return false; + if (ref && img.Labels["org.flatpak.ref"] !== ref) return false; + if (refMustExist && !img.Labels["org.flatpak.ref"]) return false; + const refTag = img.Labels["org.flatpak.ref"]?.split("/").at(-1); + if (tag && tag !== "latest" && !img.Tags.includes(tag) && refTag !== tag) { + return false; + } + return true; + }); + if (images.length > 0) { + results.push({ ...repo, Images: images }); + } + } + return { + Registry: FLATPAK_INDEX.Registry, + Results: results, + }; +} + +/** + * Redirects a catalogued Linux package or signature filename to its GitHub Release asset URL. + */ +function handlePackageRedirect(filename) { + if (!filename) return new Response("Not found", { status: 404 }); + const targetUrl = PACKAGE_REDIRECTS[filename]; + if (!targetUrl) return new Response("Package not found", { status: 404 }); + return new Response(null, { + status: 302, + headers: { + Location: targetUrl, + "Cache-Control": "public, max-age=300, s-maxage=3600", + }, + }); +} + +/** + * Serves a pre-generated static repository asset from the Worker `ASSETS` binding with explicit headers. + */ +async function serveStaticAssetWithHeaders(request, env, pathname, contentType, extraHeaders = {}) { + const assetUrl = new URL(pathname, request.url); + const response = await env.ASSETS.fetch(new Request(assetUrl, { method: request.method })); + if (!response.ok) { + return new Response("Not found", { status: 404 }); + } + return new Response(response.body, { + status: 200, + headers: { + "Content-Type": contentType, + "Cache-Control": REPO_CACHE_CONTROL, + ...extraHeaders, + }, + }); +} + +/** + * Validates that a candidate URL uses HTTP(S) and returns its normalized `href`. + */ +function safeMediaUrl(value) { + if (!value) return undefined; + try { + const url = new URL(value); + return ["https:", "http:"].includes(url.protocol) ? url.href : undefined; + } catch { + return undefined; + } +} + +/** + * Extracts the normalized lowercase media file extension or format identifier. + */ +function mediaFormat(media) { + const type = media.media_type?.toLowerCase(); + if (type && !["unknown", "image", "video", "audio", "dimensional"].includes(type)) return type; + try { + return new URL(media.media_links.cdn_url).pathname.match(/\.([a-z0-9]+)$/i)?.[1].toLowerCase() ?? type ?? ""; + } catch { + return type ?? ""; + } +} + +/** + * Determines the high-level media kind (`image`, `video`, `audio`, `mesh`, `splat`, or `unsupported`). + */ +function mediaKind(media) { + switch (media.media_class) { + case "image": + case "video": + case "audio": + case "mesh": + case "splat": + return media.media_class; + case "project": + return "unsupported"; + } + if (media.maybe_engine_category === "splat") return "splat"; + const format = mediaFormat(media); + if (["spz", "splat", "ksplat", "ply"].includes(format)) return "splat"; + if (["glb", "gltf", "fbx", "obj", "stl", "pmx", "pmd"].includes(format)) return "mesh"; + if (["image", "png", "jpg", "jpeg", "webp", "gif", "avif"].includes(format)) return "image"; + if (["video", "mp4", "webm", "mov", "m4v"].includes(format)) return "video"; + if (["audio", "wav", "mp3", "m4a", "aac", "ogg", "opus", "flac"].includes(format)) return "audio"; + return "unsupported"; +} + +/** + * Computes a human-readable display title for a shared media item. + */ +function mediaTitle(media) { + const kind = mediaKind(media); + const label = kind === "mesh" || kind === "splat" ? MEDIA_LABELS[kind] : MEDIA_LABELS[kind].toLowerCase(); + return media.maybe_title?.trim() || media.maybe_original_filename?.trim() || `Untitled ${label}`; +} + +/** + * Resolves a thumbnail URL at the requested width from media link templates. + */ +function mediaThumbnail(links, width) { + const previews = links.maybe_video_previews; + const template = links.maybe_thumbnail_template ?? previews?.still_thumbnail_template; + return safeMediaUrl(template?.replace("{WIDTH}", String(width))) ?? safeMediaUrl(previews?.still); +} + +/** + * Resolves the best social preview image URL for a shared media item. + */ +function mediaShareImage(media) { + const cover = media.cover_image?.maybe_links; + return ( + mediaThumbnail(media.media_links, PREVIEW_WIDTH) ?? + (mediaKind(media) === "image" ? safeMediaUrl(media.media_links.cdn_url) : undefined) ?? + safeMediaUrl(cover?.thumbnail_template?.replace("{WIDTH}", String(PREVIEW_WIDTH))) ?? + safeMediaUrl(cover?.cdn_url) + ); +} + +/** + * Returns embed player metadata for supported video and audio files, or null otherwise. + */ +function mediaEmbed(media) { + const kind = mediaKind(media); + if (kind !== "video" && kind !== "audio") return null; + const contentType = (kind === "video" ? VIDEO_TYPES : AUDIO_TYPES)[mediaFormat(media)]; + const url = safeMediaUrl(media.media_links.cdn_url); + if (!contentType || !url?.startsWith("https://")) return null; + return { kind, contentType, url, width: 640, height: kind === "video" ? 360 : 180 }; +} + +/** + * Fetches public or unlisted shared media metadata from the upstream API by token. + */ +async function fetchPublicMediaFile(token, env) { + const apiHost = env?.NEXT_PUBLIC_API_HOST || DEFAULT_API_HOST; + try { + const response = await fetch(`${apiHost}/v1/media_files/file/${encodeURIComponent(token)}`, { + headers: { Accept: "application/json" }, + signal: AbortSignal.timeout(5000), + }); + if (!response.ok) return null; + const payload = await response.json(); + const media = payload?.media_file; + if (!payload?.success || media?.token !== token || !safeMediaUrl(media.media_links?.cdn_url)) { + return null; + } + return media.creator_set_visibility === "public" || media.creator_set_visibility === "hidden" + ? media + : null; + } catch { + return null; + } +} + +/** + * Parses a positive safe integer query bound or returns `Infinity`. + */ +function maximum(value) { + const parsed = Number(value); + return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : Infinity; +} + +/** + * Handles `/media/:token/oembed` requests and returns an oEmbed 1.0 JSON response. + */ +async function handleMediaOembed(request, token, env) { + const headers = { "Cache-Control": "private, no-store", "X-Robots-Tag": "noindex, nofollow" }; + const query = new URL(request.url).searchParams; + if (query.has("format") && query.get("format") !== "json") { + return Response.json({ error: "Only JSON is supported" }, { status: 501, headers }); + } + if (query.get("url") !== `${MEDIA_SHARE_ORIGIN}/media/${encodeURIComponent(token)}`) { + return Response.json({ error: "Media unavailable" }, { status: 404, headers }); + } + const media = await fetchPublicMediaFile(token, env); + const embed = media && mediaEmbed(media); + if (!media || !embed) { + return Response.json({ error: "Media unavailable" }, { status: 404, headers }); + } + const playerUrl = `${MEDIA_SHARE_ORIGIN}/media/${encodeURIComponent(token)}/player`; + const scale = Math.min( + 1, + maximum(query.get("maxwidth")) / embed.width, + maximum(query.get("maxheight")) / embed.height, + ); + const width = Math.max(1, Math.floor(embed.width * scale)); + const height = Math.max(1, Math.floor(embed.height * scale)); + return Response.json( + { + version: "1.0", + type: embed.kind === "video" ? "video" : "rich", + provider_name: "ArtCraft", + provider_url: MEDIA_SHARE_ORIGIN, + title: mediaTitle(media), + author_name: media.maybe_creator_user?.display_name || media.maybe_creator_user?.username, + width, + height, + html: ``, + }, + { headers }, + ); +} + +/** + * Handles `/media/:token/player` requests and returns a standalone HTML5 player document. + */ +async function handleMediaPlayer(token, env) { + const headers = { + "Content-Type": "text/html; charset=utf-8", + "Cache-Control": "private, no-store", + "X-Content-Type-Options": "nosniff", + "X-Robots-Tag": "noindex, nofollow", + "Referrer-Policy": "no-referrer", + "Content-Security-Policy": + "default-src 'none'; style-src 'unsafe-inline'; img-src https:; media-src https:; base-uri 'none'; form-action 'none'", + }; + const media = await fetchPublicMediaFile(token, env); + const embed = media && mediaEmbed(media); + if (!media || !embed) { + return new Response("Media unavailable", { status: 404, headers }); + } + const title = escapeHtml(mediaTitle(media)); + const poster = escapeHtml(mediaShareImage(media) ?? `${MEDIA_SHARE_ORIGIN}/images/og-image.png`); + const source = ``; + const player = + embed.kind === "video" + ? `` + : `

${title}

`; + return new Response( + `${title} — ArtCraft${player}`, + { headers }, + ); +} + +/** + * Builds the `` social metadata tags (Open Graph, Twitter Card, canonical, and oEmbed) for `/media/:token`. + */ +function buildMediaHeadTags(token, media) { + const encodedToken = encodeURIComponent(token); + const canonicalUrl = `${MEDIA_SHARE_ORIGIN}/media/${encodedToken}`; + const fallbackImage = `${MEDIA_SHARE_ORIGIN}/images/og-image.png`; + const title = media ? `${mediaTitle(media)} — ArtCraft` : "Shared media — ArtCraft"; + const description = media + ? media.maybe_creator_user + ? `Made with ArtCraft by ${media.maybe_creator_user.display_name || media.maybe_creator_user.username}.` + : "Made with ArtCraft." + : "View images, video, music, and interactive 3D creations shared with ArtCraft."; + const shareImage = (media && mediaShareImage(media)) || fallbackImage; + const imageAlt = media ? mediaTitle(media) : "ArtCraft"; + const embed = media ? mediaEmbed(media) : null; + const ogType = embed?.kind === "video" ? "video.other" : "website"; + const twitterCard = embed ? "player" : "summary_large_image"; + + const tags = [ + `${escapeHtml(title)}`, + ``, + ``, + embed + ? `` + : "", + ``, + ``, + ``, + ``, + ``, + ``, + !media || shareImage === fallbackImage + ? `` + : "", + ``, + ``, + embed?.kind === "video" + ? `` + : "", + embed?.kind === "audio" + ? `` + : "", + ``, + ``, + ``, + ``, + !media || shareImage === fallbackImage + ? `` + : "", + ``, + embed + ? [ + ``, + ``, + ``, + embed.contentType === "video/mp4" + ? `` + : "", + ].join("") + : "", + ]; + + return tags.filter(Boolean).join(""); +} + +/** + * Serves the static `/media/__MEDIA_TOKEN__` shell with resolved `` social metadata for `token`. + */ +async function handleMediaPage(request, token, env) { + const shellUrl = new URL(`/media/${MEDIA_SHELL_TOKEN}`, request.url); + const [shellResponse, media] = await Promise.all([ + env.ASSETS.fetch(new Request(shellUrl)), + fetchPublicMediaFile(token, env), + ]); + if (!shellResponse.ok) { + return new Response("Not found", { status: 404 }); + } + let html = await shellResponse.text(); + // Strip placeholder page metadata inside and inject the resolved social tags. + html = html.replace(/]*)>([\s\S]*?)<\/head>/i, (_match, attrs, headContent) => { + const cleaned = headContent + .replace(/[\s\S]*?<\/title>/gi, "") + .replace(/<meta\s+(?:name|property)="(?:description|robots|og:[^"]+|twitter:[^"]+)"[^>]*>/gi, "") + .replace(/<link\s+rel="(?:canonical|alternate)"[^>]*>/gi, ""); + return `<head${attrs}>${buildMediaHeadTags(token, media)}${cleaned}</head>`; + }); + html = html.replaceAll(MEDIA_SHELL_TOKEN, encodeURIComponent(token)); + + return new Response(html, { + status: 200, + headers: { + "Content-Type": "text/html; charset=utf-8", + "Cache-Control": "private, no-store", + }, + }); +} + +export default { + /** + * Main Cloudflare Worker fetch entrypoint handling redirects, Linux repos, Flatpak OCI, and shared media. + */ + async fetch(request, env) { + const url = new URL(request.url); + const { pathname } = url; + + // 1. Legacy & route redirects + if (pathname === "/checkout_success") { + return Response.redirect("https://app.getartcraft.com/checkout/success", 307); + } + if (pathname === "/checkout_cancel" || pathname === "/portal_closed") { + return Response.redirect("https://app.getartcraft.com/checkout/cancel", 307); + } + if (pathname === "/apps/loopcraft" || pathname.startsWith("/images/apps/loopcraft/")) { + return Response.redirect(new URL("/apps", url.origin).href, 308); + } + if (pathname === "/apps/drawcraft") { + return Response.redirect(new URL("/apps/vectorcraft", url.origin).href, 308); + } + if (pathname === "/apps/printcraft") { + return Response.redirect(new URL("/apps/pdfcraft", url.origin).href, 308); + } + if (pathname.startsWith("/images/apps/printcraft/")) { + const file = pathname.slice("/images/apps/printcraft/".length); + return Response.redirect(new URL(`/images/apps/pdfcraft/${file}`, url.origin).href, 308); + } + if (pathname === "/media" && url.searchParams.has("media")) { + const token = url.searchParams.get("media"); + if (token) { + return Response.redirect(new URL(`/media/${encodeURIComponent(token)}`, url.origin).href, 308); + } + } + if (pathname.startsWith("/tutorials/")) { + const slug = pathname.slice("/tutorials/".length).replace(/\/$/, "").toLowerCase(); + const canonical = TUTORIAL_REDIRECTS[slug]; + if (canonical) { + return Response.redirect(new URL(`/tutorials/${canonical}`, url.origin).href, 308); + } + } + + // 2. Host-aware Linux repository & Flatpak descriptors + if (pathname === "/apt/artcraft.list") { + const baseUrl = getRequestBaseUrl(request); + const body = SIGNING_CONFIGURED + ? `deb [signed-by=${APT_KEYRING_PATH}] ${baseUrl}/apt stable main\n` + : `deb [trusted=yes] ${baseUrl}/apt stable main\n`; + return new Response(body, { + headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "public, max-age=3600" }, + }); + } + if (pathname === "/apt/artcraft.sources") { + const baseUrl = getRequestBaseUrl(request); + const body = [ + "Types: deb", + `URIs: ${baseUrl}/apt`, + "Suites: stable", + "Components: main", + "Architectures: amd64 arm64 riscv64", + SIGNING_CONFIGURED ? `Signed-By: ${APT_KEYRING_PATH}` : "Trusted: yes", + "", + ].join("\n"); + return new Response(body, { + headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "public, max-age=3600" }, + }); + } + if (pathname === "/rpm/artcraft.repo") { + const baseUrl = getRequestBaseUrl(request); + const body = SIGNING_CONFIGURED + ? `[artcraft]\n# Signed metadata and signed packages: dnf verifies repomd.xml against its signature, imports the\n# key below, and verifies the OpenPGP header signature inside every package it downloads.\nname=ArtCraft Linux Packages\nbaseurl=${baseUrl}/rpm\nenabled=1\ngpgcheck=1\nrepo_gpgcheck=1\ngpgkey=${baseUrl}/keys/artcraft.asc\n` + : `[artcraft]\nname=ArtCraft Linux Packages\nbaseurl=${baseUrl}/rpm\nenabled=1\ngpgcheck=0\nrepo_gpgcheck=0\n`; + return new Response(body, { + headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "public, max-age=3600" }, + }); + } + if (pathname === "/arch/artcraft.conf") { + const baseUrl = getRequestBaseUrl(request); + const body = SIGNING_CONFIGURED + ? `[artcraft]\n# Import the key before syncing, otherwise pacman rejects the repository:\n# sudo pacman-key --add /tmp/artcraft.asc && sudo pacman-key --lsign-key <fingerprint>\nSigLevel = Required DatabaseRequired\nServer = ${baseUrl}/arch/$arch\n` + : `[artcraft]\nSigLevel = Optional TrustAll\nServer = ${baseUrl}/arch/$arch\n`; + return new Response(body, { + headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "public, max-age=3600" }, + }); + } + if (pathname === "/artcraft-oci.flatpakrepo") { + const baseUrl = getRequestBaseUrl(request); + const sigLines = flatpakSignatureLines(baseUrl); + const ini = `[Flatpak Repo]\nTitle=ArtCraft OCI\nUrl=oci+${baseUrl}\nHomepage=https://getartcraft.com/\nComment=Official ArtCraft OCI Flatpak repository\nDescription=Open-source creative apps for Linux distributed via GitHub Container Registry\n${ + sigLines.length > 0 ? `${sigLines.join("\n")}\n` : "GPGVerify=false\n" + }`; + return new Response(ini, { + headers: { + "Content-Type": "application/x-flatpak-repo; charset=utf-8", + "Cache-Control": "public, max-age=86400", + "Content-Disposition": 'attachment; filename="artcraft-oci.flatpakrepo"', + }, + }); + } + + const flatpakRefMatch = pathname.match(/^\/apps\/([^/]+)\/([^/]+)$/); + if (flatpakRefMatch) { + const [, slug, filename] = flatpakRefMatch; + const app = FLATPAK_APPS[slug]; + if (!app || filename !== `${slug}-oci.flatpakref`) { + return new Response("Not found", { status: 404 }); + } + const baseUrl = `${url.protocol}//${url.host}`; + const sigLines = flatpakSignatureLines(baseUrl); + const ini = `[Flatpak Ref]\nName=${app.appId}\nBranch=stable\nTitle=${app.title}\nUrl=oci+${baseUrl}\nRuntimeRepo=https://dl.flathub.org/repo/flathub.flatpakrepo\nIsRuntime=false\n${sigLines + .map((line) => `${line}\n`) + .join("")}`; + return new Response(ini, { + headers: { + "Content-Type": "application/x-flatpak-ref; charset=utf-8", + "Cache-Control": "public, max-age=86400", + "Content-Disposition": `attachment; filename="${slug}-oci.flatpakref"`, + }, + }); + } + + // 3. Flatpak OCI Index endpoints + if (pathname === "/index/static" || pathname === "/index/dynamic") { + const cacheControl = + pathname === "/index/static" ? "public, max-age=300, s-maxage=300" : "no-cache"; + return Response.json(filterFlatpakIndex(url.searchParams), { + headers: { + "Cache-Control": cacheControl, + "Netlify-Vary": "query", + }, + }); + } + + // 4. Pre-generated keys, OCI signatures & Linux repository files + binary redirects + if (pathname === "/keys/artcraft.asc") { + return serveStaticAssetWithHeaders(request, env, pathname, "application/pgp-keys; charset=utf-8", { + "Content-Disposition": 'inline; filename="artcraft.asc"', + }); + } + if (pathname === "/keys/artcraft.gpg") { + return serveStaticAssetWithHeaders(request, env, pathname, "application/pgp-keys"); + } + if (pathname.startsWith("/oci-signatures/")) { + return serveStaticAssetWithHeaders(request, env, pathname, "application/pgp-signature"); + } + if (pathname.startsWith("/apt/pool/")) { + const filename = pathname.split("/").at(-1); + if (!filename?.endsWith(".deb")) return new Response("Not found", { status: 404 }); + return handlePackageRedirect(filename); + } + if (pathname.startsWith("/apt/dists/")) { + if (pathname.endsWith("/Packages.gz")) { + return serveStaticAssetWithHeaders(request, env, pathname, "application/gzip"); + } + if (pathname.endsWith("/Release.gpg")) { + return serveStaticAssetWithHeaders( + request, + env, + pathname, + "application/pgp-signature; charset=utf-8", + ); + } + if (pathname.endsWith("/Packages") || pathname.endsWith("/Release") || pathname.endsWith("/InRelease")) { + return serveStaticAssetWithHeaders(request, env, pathname, "text/plain; charset=utf-8"); + } + return new Response("Not found", { status: 404 }); + } + if (pathname.startsWith("/rpm/")) { + const rpmPkgMatch = pathname.match(/^\/rpm\/(?:([^/]+)\/)?packages\/(.+)$/); + if (rpmPkgMatch) { + const [, arch, rest] = rpmPkgMatch; + if (arch && !VALID_RPM_ARCHES.has(arch)) return new Response("Not found", { status: 404 }); + const filename = rest.split("/").at(-1); + if (!filename || (!filename.endsWith(".rpm") && !filename.endsWith(".rpm.asc"))) { + return new Response("Not found", { status: 404 }); + } + return handlePackageRedirect(filename); + } + if (pathname.endsWith("/primary.xml.gz")) { + return serveStaticAssetWithHeaders(request, env, pathname, "application/gzip"); + } + if (pathname.endsWith("/repomd.xml")) { + return serveStaticAssetWithHeaders(request, env, pathname, "application/xml; charset=utf-8"); + } + if (pathname.endsWith("/repomd.xml.asc")) { + return serveStaticAssetWithHeaders( + request, + env, + pathname, + "application/pgp-signature; charset=utf-8", + ); + } + if (pathname === "/rpm/repodata/repomd.xml.key") { + return serveStaticAssetWithHeaders(request, env, pathname, "application/pgp-keys; charset=utf-8"); + } + return new Response("Not found", { status: 404 }); + } + if (pathname.startsWith("/arch/")) { + const archMatch = pathname.match(/^\/arch\/([^/]+)\/([^/]+)$/); + if (!archMatch) return new Response("Not found", { status: 404 }); + const [, arch, filename] = archMatch; + if (!VALID_PACMAN_ARCHES.has(arch)) return new Response("Not found", { status: 404 }); + if (filename === "artcraft.db" || filename === "artcraft.db.tar.gz") { + return serveStaticAssetWithHeaders(request, env, pathname, "application/gzip"); + } + if (filename === "artcraft.db.sig") { + return serveStaticAssetWithHeaders(request, env, pathname, "application/pgp-signature"); + } + if (filename.endsWith(".sig") && !SIGNING_CONFIGURED) { + return new Response("Not found", { status: 404 }); + } + if (filename.endsWith(".pkg.tar.zst") || filename.endsWith(".pkg.tar.zst.sig")) { + return handlePackageRedirect(filename); + } + return new Response("Not found", { status: 404 }); + } + + // 5. Shared media routes (/media/:token, /media/:token/oembed, /media/:token/player) + const mediaSubMatch = pathname.match(/^\/media\/([^/]+)\/(oembed|player)$/); + if (mediaSubMatch) { + const token = safeDecode(mediaSubMatch[1]); + if (token === null) return new Response("Not found", { status: 404 }); + const subroute = mediaSubMatch[2]; + return subroute === "oembed" + ? handleMediaOembed(request, token, env) + : handleMediaPlayer(token, env); + } + const mediaPageMatch = pathname.match(/^\/media\/([^/]+)\/?$/); + if (mediaPageMatch) { + const rawSegment = mediaPageMatch[1]; + if (rawSegment.endsWith(".txt")) { + const token = safeDecode(rawSegment.slice(0, -4)); + if (token === null) return new Response("Not found", { status: 404 }); + const rscUrl = new URL(`/media/${MEDIA_SHELL_TOKEN}.txt`, request.url); + const rscResp = await env.ASSETS.fetch(new Request(rscUrl)); + if (!rscResp.ok) return new Response("Not found", { status: 404 }); + const body = (await rscResp.text()).replaceAll(MEDIA_SHELL_TOKEN, encodeURIComponent(token)); + return new Response(body, { + headers: { "Content-Type": "text/x-component; charset=utf-8", "Cache-Control": "private, no-store" }, + }); + } + const token = safeDecode(rawSegment); + if (token === null) return new Response("Not found", { status: 404 }); + return handleMediaPage(request, token, env); + } + + return env.ASSETS.fetch(request); + }, +}; diff --git a/frontend/apps/artcraft-website-next/wrangler.jsonc b/frontend/apps/artcraft-website-next/wrangler.jsonc new file mode 100644 index 0000000000..7be91587b2 --- /dev/null +++ b/frontend/apps/artcraft-website-next/wrangler.jsonc @@ -0,0 +1,34 @@ +{ + "name": "artcraft-services", + "compatibility_date": "2026-11-06", + "main": "worker/index.mjs", + "build": { + "command": "npm ci --ignore-scripts && npm run build:cloudflare" + }, + "assets": { + "directory": "./out", + "binding": "ASSETS", + "run_worker_first": [ + "/checkout_success", + "/checkout_cancel", + "/portal_closed", + "/apps/loopcraft", + "/apps/drawcraft", + "/apps/printcraft", + "/images/apps/loopcraft/*", + "/images/apps/printcraft/*", + "/tutorials/*", + "/apps/*/*-oci.flatpakref", + "/artcraft-oci.flatpakrepo", + "/index/*", + "/keys/*", + "/oci-signatures/*", + "/apt/*", + "/rpm/*", + "/arch/*", + "/media", + "/media/*" + ] + }, + "previews": {} +} diff --git a/package.json b/package.json new file mode 100644 index 0000000000..080760e3d7 --- /dev/null +++ b/package.json @@ -0,0 +1,7 @@ +{ + "name": "artcraft-services", + "private": true, + "scripts": { + "build": "npm --prefix frontend/apps/artcraft-website-next ci --ignore-scripts && npm --prefix frontend/apps/artcraft-website-next run build:cloudflare" + } +} diff --git a/wrangler.jsonc b/wrangler.jsonc new file mode 100644 index 0000000000..f9da5b33c8 --- /dev/null +++ b/wrangler.jsonc @@ -0,0 +1,34 @@ +{ + "name": "artcraft-services", + "compatibility_date": "2026-11-06", + "main": "frontend/apps/artcraft-website-next/worker/index.mjs", + "build": { + "command": "npm run build" + }, + "assets": { + "directory": "./frontend/apps/artcraft-website-next/out", + "binding": "ASSETS", + "run_worker_first": [ + "/checkout_success", + "/checkout_cancel", + "/portal_closed", + "/apps/loopcraft", + "/apps/drawcraft", + "/apps/printcraft", + "/images/apps/loopcraft/*", + "/images/apps/printcraft/*", + "/tutorials/*", + "/apps/*/*-oci.flatpakref", + "/artcraft-oci.flatpakrepo", + "/index/*", + "/keys/*", + "/oci-signatures/*", + "/apt/*", + "/rpm/*", + "/arch/*", + "/media", + "/media/*" + ] + }, + "previews": {} +}