mirror of
https://github.com/storytold/artcraft-services.git
synced 2026-11-19 08:53:03 +01:00
Port the entire website to CloudFlare Pages + Workers (#354)
<!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added support for serving the website and shared-media pages through Cloudflare, including video and audio previews and media embeds. * Added Linux package repository downloads and metadata for APT, RPM, Pacman, and Flatpak. * Added redirects for legacy tutorial links. * Pricing pages can display a campaign-specific header when opened with the matching referral link. * **Chores** * Added automated deployment for development-branch pushes and manual runs. Deployment reports an error if the required hook is missing or the request fails. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
1 parent
c2d03a1ee8
commit
8f0bae1719
21 files changed
+1349
-75
No files matched your search
@@ -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
|
||||
@@ -1,5 +1,9 @@
|
||||
node_modules/
|
||||
.next/
|
||||
out/
|
||||
.wrangler/
|
||||
.build-route-stash/
|
||||
worker/generated-catalog.mjs
|
||||
next-env.d.ts
|
||||
*.tsbuildinfo
|
||||
playwright-report/
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
22
|
||||
@@ -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 <head>, 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=<token>`) from the Vite site;
|
||||
// the canonical route is /media/<token>. Mirrored in netlify.toml so
|
||||
// the edge answers it before the Next runtime.
|
||||
{
|
||||
source: "/media",
|
||||
has: [{ type: "query", key: "media", value: "(?<token>.+)" }],
|
||||
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=<token>`) from the Vite site;
|
||||
// the canonical route is /media/<token>. Mirrored in the Worker so
|
||||
// the edge answers it in static exports.
|
||||
{
|
||||
source: "/media",
|
||||
has: [{ type: "query", key: "media", value: "(?<token>.+)" }],
|
||||
destination: "/media/:token",
|
||||
permanent: true,
|
||||
},
|
||||
];
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
@@ -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}).`,
|
||||
);
|
||||
@@ -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<Metadata> {
|
||||
const { token } = await params;
|
||||
const url = `/media/${encodeURIComponent(token)}`;
|
||||
@@ -29,6 +39,7 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
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<Metadata> {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -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<Record<string, string | string[] | undefined>>;
|
||||
|
||||
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 (
|
||||
<>
|
||||
<RevealManager />
|
||||
|
||||
{isSeedanceRef ? <SeedanceHeader /> : <DefaultHeader />}
|
||||
<Suspense fallback={<DefaultHeader />}>
|
||||
<PricingHeader
|
||||
defaultHeader={<DefaultHeader />}
|
||||
seedanceHeader={<SeedanceHeader />}
|
||||
/>
|
||||
</Suspense>
|
||||
|
||||
<SectionShell id="plans">
|
||||
<SectionEyebrow
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
|
||||
export const dynamic = "force-static";
|
||||
|
||||
/**
|
||||
* Generates the static `/robots.txt` metadata route configuration.
|
||||
*/
|
||||
export default function robots(): MetadataRoute.Robots {
|
||||
return {
|
||||
rules: { userAgent: "*", allow: "/" },
|
||||
|
||||
@@ -3,6 +3,8 @@ import { CRAFTING_APPS, craftAppPath } from "@/lib/crafting-apps";
|
||||
import { getFaqItems, getNewsPosts, getTutorialItems } from "@/lib/content";
|
||||
import { SITE_URL } from "@/lib/links";
|
||||
|
||||
export const dynamic = "force-static";
|
||||
|
||||
type Entry = MetadataRoute.Sitemap[number];
|
||||
|
||||
const STATIC_ROUTES: { path: string; priority: number; changeFrequency: Entry["changeFrequency"] }[] = [
|
||||
@@ -29,6 +31,9 @@ const STATIC_ROUTES: { path: string; priority: number; changeFrequency: Entry["c
|
||||
})),
|
||||
];
|
||||
|
||||
/**
|
||||
* Generates the static `/sitemap.xml` metadata route entries for all public pages and articles.
|
||||
*/
|
||||
export default function sitemap(): MetadataRoute.Sitemap {
|
||||
const staticEntries: Entry[] = STATIC_ROUTES.map((route) => ({
|
||||
url: `${SITE_URL}${route.path}`,
|
||||
|
||||
@@ -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,
|
||||
}: {
|
||||
|
||||
@@ -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<MediaState>({ status: "loading" });
|
||||
const [prompt, setPrompt] = useState<MediaPrompt | null>(null);
|
||||
const [promptLoading, setPromptLoading] = useState(false);
|
||||
|
||||
@@ -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}</>;
|
||||
}
|
||||
@@ -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:") {
|
||||
|
||||
@@ -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<string, string> = { mp4: "video/mp4", webm: "video/webm" };
|
||||
const AUDIO_TYPES: Record<string, string> = {
|
||||
@@ -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)
|
||||
|
||||
@@ -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: `<iframe src="${playerUrl}" width="${width}" height="${height}" title="ArtCraft media player" frameborder="0" allow="fullscreen" allowfullscreen></iframe>`,
|
||||
},
|
||||
{ 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 = `<source src="${escapeHtml(embed.url)}" type="${embed.contentType}">`;
|
||||
const player =
|
||||
embed.kind === "video"
|
||||
? `<video controls playsinline preload="metadata" poster="${poster}" aria-label="${title}">${source}</video>`
|
||||
: `<div class="audio"><img src="${poster}" alt=""><div><p>${title}</p><audio controls preload="metadata" aria-label="${title}">${source}</audio></div></div>`;
|
||||
return new Response(
|
||||
`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title} — ArtCraft</title><style>
|
||||
:root{color-scheme:light dark}*{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;font:14px system-ui;background:light-dark(#f2f1ee,#121316);color:light-dark(#222,#eee)}
|
||||
video{display:block;width:100%;height:100%;object-fit:contain;background:#000}.audio{display:flex;align-items:center;gap:16px;padding:16px;height:100%}.audio img{width:80px;height:80px;object-fit:cover}.audio div{min-width:0;flex:1}p{margin:0 0 12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}audio{width:100%}@media(max-width:360px){.audio img{display:none}}
|
||||
</style></head><body>${player}</body></html>`,
|
||||
{ headers },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the `<head>` 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 = [
|
||||
`<title>${escapeHtml(title)}</title>`,
|
||||
`<meta name="description" content="${escapeHtml(description)}"/>`,
|
||||
`<link rel="canonical" href="${escapeHtml(canonicalUrl)}"/>`,
|
||||
embed
|
||||
? `<link rel="alternate" type="application/json+oembed" href="${escapeHtml(`${canonicalUrl}/oembed?url=${encodeURIComponent(canonicalUrl)}&format=json`)}"/>`
|
||||
: "",
|
||||
`<meta name="robots" content="noindex, follow"/>`,
|
||||
`<meta property="og:title" content="${escapeHtml(title)}"/>`,
|
||||
`<meta property="og:description" content="${escapeHtml(description)}"/>`,
|
||||
`<meta property="og:url" content="${escapeHtml(canonicalUrl)}"/>`,
|
||||
`<meta property="og:site_name" content="ArtCraft"/>`,
|
||||
`<meta property="og:image" content="${escapeHtml(shareImage)}"/>`,
|
||||
!media || shareImage === fallbackImage
|
||||
? `<meta property="og:image:width" content="1200"/><meta property="og:image:height" content="630"/>`
|
||||
: "",
|
||||
`<meta property="og:image:alt" content="${escapeHtml(imageAlt)}"/>`,
|
||||
`<meta property="og:type" content="${ogType}"/>`,
|
||||
embed?.kind === "video"
|
||||
? `<meta property="og:video" content="${escapeHtml(embed.url)}"/><meta property="og:video:secure_url" content="${escapeHtml(embed.url)}"/><meta property="og:video:type" content="${escapeHtml(embed.contentType)}"/>`
|
||||
: "",
|
||||
embed?.kind === "audio"
|
||||
? `<meta property="og:audio" content="${escapeHtml(embed.url)}"/><meta property="og:audio:secure_url" content="${escapeHtml(embed.url)}"/><meta property="og:audio:type" content="${escapeHtml(embed.contentType)}"/>`
|
||||
: "",
|
||||
`<meta name="twitter:card" content="${twitterCard}"/>`,
|
||||
`<meta name="twitter:title" content="${escapeHtml(title)}"/>`,
|
||||
`<meta name="twitter:description" content="${escapeHtml(description)}"/>`,
|
||||
`<meta name="twitter:image" content="${escapeHtml(shareImage)}"/>`,
|
||||
!media || shareImage === fallbackImage
|
||||
? `<meta name="twitter:image:width" content="1200"/><meta name="twitter:image:height" content="630"/>`
|
||||
: "",
|
||||
`<meta name="twitter:image:alt" content="${escapeHtml(imageAlt)}"/>`,
|
||||
embed
|
||||
? [
|
||||
`<meta name="twitter:player" content="${escapeHtml(`${canonicalUrl}/player`)}"/>`,
|
||||
`<meta name="twitter:player:width" content="${embed.width}"/>`,
|
||||
`<meta name="twitter:player:height" content="${embed.height}"/>`,
|
||||
embed.contentType === "video/mp4"
|
||||
? `<meta name="twitter:player:stream" content="${escapeHtml(embed.url)}"/><meta name="twitter:player:stream:content_type" content="${escapeHtml(embed.contentType)}"/>`
|
||||
: "",
|
||||
].join("")
|
||||
: "",
|
||||
];
|
||||
|
||||
return tags.filter(Boolean).join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves the static `/media/__MEDIA_TOKEN__` shell with resolved `<head>` 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 <head> and inject the resolved social tags.
|
||||
html = html.replace(/<head([^>]*)>([\s\S]*?)<\/head>/i, (_match, attrs, headContent) => {
|
||||
const cleaned = headContent
|
||||
.replace(/<title>[\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);
|
||||
},
|
||||
};
|
||||
@@ -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": {}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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": {}
|
||||
}
|
||||
Reference in new issue
Block a user