fix: repair Linux installation flows (#221)

## What changed

- Resolve the Flatpak OCI index digest from each real GHCR manifest
instead of manufacturing a digest. Use the actual launcher package path
(`storytold/craft-launcher`) and architecture-specific release tags.
- Vary Netlify's cache key by query string on both OCI index routes;
preserve architecture, repository, ref, and tag filtering.
- Return an explicit `503` if a referenced image is missing or
inaccessible. Document GHCR requirements and remove the distro test's
fallback that treated failed installs as success.
- Fix the `.flatpakref` download route, make all Linux distro tabs
reachable on mobile, make the Arch repo setup enable its config, and
change the advertised minimum to RHEL 10+.

## External release setup required

The current launcher OCI tags were pushed to
`ghcr.io/storytold/craft-launcher`, but anonymous token requests for
that package and the Craft app packages currently return `401`. Flatpak
clients cannot install private images. Set every package included in the
OCI index to **Public** in GHCR package settings before marking this PR
ready to merge. If the website needs authenticated index resolution
during that setup, configure the server-only `FLATPAK_OCI_READ_USERNAME`
and `FLATPAK_OCI_READ_TOKEN` variables; this does not replace public
package visibility for users.

## Validation

- `npm run typecheck` — passed.
- `npx playwright test tests/flatpak-oci.spec.ts` — 9 passed.
- Linux repository Playwright suite — 21 passed locally; the mobile
browser case could not launch locally because Chromium is unavailable.
The PR CI download suite passed all 35 browser tests, including the
mobile case.
- Live GHCR probe — current launcher and PdfCraft package token requests
return `401`; this is the release configuration blocker above.

The deploy preview confirms this: `/index/static?...` responds with
`503` and GHCR's `401` message. The existing `Flatpak OCI Remote` check
therefore fails until those packages are made public. The PR is
intentionally a draft while that external release setting is unresolved.

The initial Flatpak CI crash (`getFlatpakOciIndex().Results` on a
Promise) is fixed in the latest commit. The test helper now gets its
expected app IDs from the catalog without making registry requests. CI
should now reach and report the actual GHCR access failure described
above.
This commit is contained in:
Dylan M. Taylor authored and GitHub committed 2026-11-01 16:32:34 -05:00
1 parent 3a46c65d7f
commit 8f2b99aae7
11 files changed
+422 -86

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
# Linux Flatpak OCI registry
The website's Flatpak OCI index resolves each listed image tag against GHCR and returns the
registry's real OCI manifest digest. The digest is required by Flatpak to pull the image and must
never be generated from release metadata.
## GHCR package setup
Every image referenced by the index must exist and be public so visitors can install it without
credentials:
- `ghcr.io/storytold/craft-launcher` (the shared release workflow uses the GitHub repository name)
- `ghcr.io/storytold/<app-slug>` for each Craft app included in the website's OCI catalog
The release workflow publishes `<version>-<architecture>` and `stable-<architecture>` tags (for
example, `0.12.0-x86_64` and `stable-x86_64`). After the first push for a package, set its GHCR
package visibility to **Public** in the package settings. A private package can sometimes be read
by the website with a server token, but Flatpak clients still cannot install it anonymously.
## Optional website read token
Public GHCR packages normally allow anonymous index resolution. If the deployment needs an
authenticated read, configure these server-only environment variables on the website deployment:
- `FLATPAK_OCI_READ_USERNAME`: GitHub account that owns the token.
- `FLATPAK_OCI_READ_TOKEN`: a token with `read:packages` access to the images.
Do not use `NEXT_PUBLIC_` names or expose this token to browser code. This token only lets the
website resolve manifest digests; it does not replace public package visibility for end-user
installs. A missing tag or inaccessible image now causes the index request to return an error
instead of publishing a fabricated digest.
@@ -1,5 +1,5 @@
import { getLinuxRepoApps } from "../src/lib/linux-repos.ts";
import { getFlatpakOciIndex } from "../src/lib/flatpak-oci.ts";
import { getFlatpakOciAppIds } from "../src/lib/flatpak-oci.ts";
const mode = process.argv[2] || "";
const targetArch = process.argv[3];
@@ -91,13 +91,7 @@ switch (mode) {
case "flatpak-apps": {
const apps = Array.from(
new Set(
getFlatpakOciIndex().Results.flatMap((r) =>
r.Images.map((img) => {
const ref = img.Labels?.["org.flatpak.ref"] ?? "";
const appId = ref.split("/")[1] ?? "";
return appId.replace("ai.storyteller.", "");
})
)
getFlatpakOciAppIds().map((appId) => appId.replace("ai.storyteller.", ""))
)
)
.filter(Boolean)
@@ -380,9 +380,7 @@ test_flatpak() {
done
echo "--- Testing app installation from repository ---"
dbus-run-session -- flatpak install --user --noninteractive --no-deps test-artcraft ai.storyteller.artcraft-launcher || {
echo "Note: Container image not yet published to GHCR (404); Flatpak OCI remote index catalog and token negotiation verified successfully."
}
dbus-run-session -- flatpak install --user --noninteractive --no-deps test-artcraft ai.storyteller.artcraft-launcher
echo "=== Flatpak (OCI Remote) verification passed! All apps verified. ==="
'
@@ -1,11 +1,15 @@
import { getCraftApp, craftAppName } from "@/lib/crafting-apps";
type RouteProps = {
params: Promise<{ slug: string }>;
params: Promise<{ slug: string; filename: string }>;
};
export async function GET(request: Request, props: RouteProps) {
const { slug } = await props.params;
const { slug, filename } = await props.params;
if (filename !== `${slug}-oci.flatpakref`) {
return new Response("Not found", { status: 404 });
}
const app = getCraftApp(slug);
if (!app) {
@@ -1,13 +1,5 @@
import { getFlatpakOciIndex } from "@/lib/flatpak-oci";
import { flatpakOciIndexResponse } from "@/lib/flatpak-oci-route";
export function GET(request: Request) {
const url = new URL(request.url);
const catalog = getFlatpakOciIndex(url.searchParams);
return Response.json(catalog, {
headers: {
"Cache-Control": "no-cache",
"Content-Type": "application/json",
},
});
return flatpakOciIndexResponse(request, "no-cache");
}
@@ -1,13 +1,5 @@
import { getFlatpakOciIndex } from "@/lib/flatpak-oci";
import { flatpakOciIndexResponse } from "@/lib/flatpak-oci-route";
export function GET(request: Request) {
const url = new URL(request.url);
const catalog = getFlatpakOciIndex(url.searchParams);
return Response.json(catalog, {
headers: {
"Cache-Control": "public, max-age=300, s-maxage=300, stale-while-revalidate=86400",
"Content-Type": "application/json",
},
});
return flatpakOciIndexResponse(request, "public, max-age=300, s-maxage=300, stale-while-revalidate=86400");
}
@@ -81,7 +81,7 @@ sudo apt install artcraft-launcher pdfcraft`,
dnf: {
id: "dnf",
name: "DNF & RPM (Fedora, RHEL & Derivatives)",
distros: "Fedora 40+, RHEL 9+, CentOS Stream, Rocky Linux, AlmaLinux",
distros: "Fedora 40+, RHEL 10+, CentOS Stream, Rocky Linux, AlmaLinux",
architectures: STANDARD_ARCHITECTURES,
setupDescription: "Add the ArtCraft RPM repository and install:",
setupCommand: `# Add the ArtCraft RPM repository
@@ -93,7 +93,7 @@ sudo dnf install artcraft-launcher pdfcraft`,
altSetupCommand: `# Fedora 41+ (DNF5):
sudo dnf config-manager addrepo --from-repofile=https://getartcraft.com/rpm/artcraft.repo
# Fedora 40 / RHEL 9 (DNF4):
# Fedora 40 (DNF4):
sudo dnf config-manager --add-repo https://getartcraft.com/rpm/artcraft.repo`,
rawFiles: [
{ name: "artcraft.repo", href: "/rpm/artcraft.repo", description: "YUM/DNF repository configuration" },
@@ -121,14 +121,17 @@ sudo zypper install artcraft-launcher pdfcraft`,
name: "Pacman (Arch Linux & Derivatives)",
distros: "Arch Linux, Manjaro, EndeavourOS, CachyOS",
architectures: STANDARD_ARCHITECTURES.slice(0, 2),
setupDescription: "Add the ArtCraft repository configuration:",
setupCommand: `# Add the ArtCraft repository configuration
setupDescription: "Add and enable the ArtCraft repository configuration:",
setupCommand: `# Download the ArtCraft repository configuration
sudo curl -fsSL https://getartcraft.com/arch/artcraft.conf -o /etc/pacman.d/artcraft.conf
# Enable it in pacman.conf (safe to run more than once)
if ! grep -Fxq 'Include = /etc/pacman.d/artcraft.conf' /etc/pacman.conf; then
echo 'Include = /etc/pacman.d/artcraft.conf' | sudo tee -a /etc/pacman.conf
fi
# Synchronize repositories and install apps
sudo pacman -Syu artcraft-launcher pdfcraft`,
altSetupDescription: "If your /etc/pacman.conf does not include /etc/pacman.d/*.conf, add it with:",
altSetupCommand: `echo "Include = /etc/pacman.d/artcraft.conf" | sudo tee -a /etc/pacman.conf`,
rawFiles: [
{ name: "artcraft.conf", href: "/arch/artcraft.conf", description: "Pacman repository configuration" },
{ name: "artcraft.db", href: "/arch/x86_64/artcraft.db", description: "Sync repository database (x86_64)" },
@@ -149,6 +152,7 @@ export function LinuxRepoGuide() {
activeTab={activeTab}
onTabChange={setActiveTab}
className="w-full sm:w-auto"
listClassName="min-w-0 max-w-full"
/>
<p className="hud-label hidden text-faint sm:block">
Continuous updates via native packages
@@ -0,0 +1,21 @@
import { getFlatpakOciIndex } from "./flatpak-oci";
export async function flatpakOciIndexResponse(request: Request, cacheControl: string): Promise<Response> {
const url = new URL(request.url);
try {
const catalog = await getFlatpakOciIndex(url.searchParams);
return Response.json(catalog, {
headers: {
"Cache-Control": cacheControl,
"Content-Type": "application/json",
"Netlify-Vary": "query",
},
});
} catch (error) {
const message = error instanceof Error ? error.message : "Flatpak OCI index is unavailable";
return Response.json({ error: message }, {
status: 503,
headers: { "Cache-Control": "no-store", "Netlify-Vary": "query" },
});
}
}
@@ -39,6 +39,20 @@ export type FlatpakOciIndexResponse = {
export const DEFAULT_OCI_REGISTRY = "https://ghcr.io";
export const ARCHITECTURES: Array<"x86_64" | "aarch64"> = ["x86_64", "aarch64"];
const MANIFEST_ACCEPT = [
"application/vnd.oci.image.manifest.v1+json",
"application/vnd.oci.image.index.v1+json",
"application/vnd.docker.distribution.manifest.v2+json",
"application/vnd.docker.distribution.manifest.list.v2+json",
].join(", ");
const digestCache = new Map<string, { digest: string; expiresAt: number }>();
const digestRequests = new Map<string, Promise<string>>();
const tokenCache = new Map<string, { token: string; expiresAt: number }>();
const tokenRequests = new Map<string, Promise<string>>();
const DIGEST_CACHE_MS = 5 * 60 * 1000;
const TOKEN_CACHE_MS = 5 * 60 * 1000;
/** Normalize container architecture names to Flatpak conventions. */
function normalizeArch(arch: string | null): string | null {
if (!arch) return null;
@@ -49,24 +63,23 @@ function normalizeArch(arch: string | null): string | null {
}
function buildImagesForTarget(
repoName: string,
appId: string,
appName: string,
release: CraftRelease,
): FlatpakOciImage[] {
const version = release.version;
const tags = ["stable", "latest", version];
const binaryName = appId.replace("ai.storyteller.", "");
return ARCHITECTURES.map((arch) => {
const ref = `app/${appId}/${arch}/stable`;
const digestHash = createHash("sha256")
.update(`${repoName}:${ref}:${version}`)
.digest("hex");
const versionTag = `${version}-${arch}`;
const stableTag = `stable-${arch}`;
return {
Tags: tags,
Digest: `sha256:${digestHash}`,
// flatpak-oci.sh publishes a version-architecture tag and stable-architecture tag.
// These names must match the actual registry tags, and Digest is filled from GHCR below.
Tags: [versionTag, stableTag],
Digest: "",
MediaType: "application/vnd.oci.image.manifest.v1+json",
Architecture: arch,
OS: "linux",
@@ -81,6 +94,153 @@ function buildImagesForTarget(
});
}
function registryUrl(): URL {
const configured = process.env.FLATPAK_OCI_REGISTRY_URL ?? DEFAULT_OCI_REGISTRY;
const url = new URL(configured);
url.pathname = "";
url.search = "";
url.hash = "";
return url;
}
/**
* Resolve a real OCI manifest digest from the target registry. Never synthesize a digest: Flatpak
* asks the registry for this exact content-addressed manifest before it can install the app.
*
* GHCR packages must be public for end-user Flatpak installs. FLATPAK_OCI_READ_TOKEN and the
* optional FLATPAK_OCI_READ_USERNAME are server-side fallbacks for
* resolving the index while package visibility is being configured; they do not grant visitors
* access to private images.
*/
async function fetchManifestDigest(repoName: string, tag: string): Promise<string> {
const registry = registryUrl();
const key = `${registry.origin}/${repoName}:${tag}`;
const cached = digestCache.get(key);
if (cached && cached.expiresAt > Date.now()) return cached.digest;
const existingRequest = digestRequests.get(key);
if (existingRequest) return existingRequest;
const request = resolveManifestDigest(repoName, tag, registry, key);
digestRequests.set(key, request);
try {
return await request;
} finally {
digestRequests.delete(key);
}
}
async function getRegistryPullToken(registry: URL, repoName: string, tag: string): Promise<string> {
const key = `${registry.origin}/${repoName}`;
const cached = tokenCache.get(key);
if (cached && cached.expiresAt > Date.now()) return cached.token;
const existingRequest = tokenRequests.get(key);
if (existingRequest) return existingRequest;
const request = (async () => {
const tokenUrl = new URL("/token", registry);
tokenUrl.searchParams.set("service", registry.host);
tokenUrl.searchParams.set("scope", `repository:${repoName}:pull`);
const tokenHeaders = new Headers();
const readToken = process.env.FLATPAK_OCI_READ_TOKEN;
if (readToken) {
const username = process.env.FLATPAK_OCI_READ_USERNAME;
if (!username) {
throw new Error("FLATPAK_OCI_READ_USERNAME must be set when FLATPAK_OCI_READ_TOKEN is configured");
}
const credentials = `${username}:${readToken}`;
const encodedCredentials = Buffer.from(credentials).toString("base64");
tokenHeaders.set("Authorization", `Basic ${encodedCredentials}`);
}
let tokenResponse: Response;
try {
tokenResponse = await fetch(tokenUrl, { headers: tokenHeaders, cache: "no-store" });
} catch (error) {
throw new Error(`Could not request a pull token from ${registry.host}: ${String(error)}`);
}
if (!tokenResponse.ok) {
throw new Error(
`Could not obtain a pull token for ${repoName}:${tag} from ${registry.host} ` +
`(HTTP ${tokenResponse.status}). Make the GHCR package public or configure ` +
"FLATPAK_OCI_READ_TOKEN with packages:read access.",
);
}
const tokenPayload: unknown = await tokenResponse.json();
if (!tokenPayload || typeof tokenPayload !== "object") {
throw new Error(`Registry returned an invalid pull token response for ${repoName}:${tag}`);
}
let tokenValue: string | null = null;
if ("token" in tokenPayload && typeof tokenPayload.token === "string") {
tokenValue = tokenPayload.token;
} else if ("access_token" in tokenPayload && typeof tokenPayload.access_token === "string") {
tokenValue = tokenPayload.access_token;
}
if (!tokenValue) {
throw new Error(`Registry pull token response did not include a token for ${repoName}:${tag}`);
}
tokenCache.set(key, { token: tokenValue, expiresAt: Date.now() + TOKEN_CACHE_MS });
return tokenValue;
})();
tokenRequests.set(key, request);
try {
return await request;
} finally {
tokenRequests.delete(key);
}
}
async function resolveManifestDigest(repoName: string, tag: string, registry: URL, key: string): Promise<string> {
const token = await getRegistryPullToken(registry, repoName, tag);
const manifestUrl = new URL(`/v2/${repoName}/manifests/${encodeURIComponent(tag)}`, registry);
let manifestResponse: Response;
try {
manifestResponse = await fetch(manifestUrl, {
method: "HEAD",
headers: { Accept: MANIFEST_ACCEPT, Authorization: `Bearer ${token}` },
cache: "no-store",
});
} catch (error) {
throw new Error(`Could not resolve ${repoName}:${tag} from ${registry.host}: ${String(error)}`);
}
if (!manifestResponse.ok) {
const message = manifestResponse.status === 404
? "The OCI image tag is missing. Confirm the release workflow pushed it."
: "The registry denied access. Make the GHCR package public for end-user Flatpak installs.";
throw new Error(
`Could not resolve OCI manifest ${repoName}:${tag} from ${registry.host} ` +
`(HTTP ${manifestResponse.status}). ${message}`,
);
}
let digest = manifestResponse.headers.get("docker-content-digest");
if (!digest && manifestResponse.status === 200) {
// Some registries omit Docker-Content-Digest on HEAD. Fetch the small manifest document and
// calculate its OCI content digest from the exact response bytes.
const getResponse = await fetch(manifestUrl, {
headers: { Accept: MANIFEST_ACCEPT, Authorization: `Bearer ${token}` },
cache: "no-store",
});
if (!getResponse.ok) {
throw new Error(`Could not read OCI manifest ${repoName}:${tag} (HTTP ${getResponse.status})`);
}
const body = await getResponse.arrayBuffer();
if (body.byteLength > 2 * 1024 * 1024) {
throw new Error(`OCI manifest ${repoName}:${tag} exceeded the 2 MiB safety limit`);
}
digest = `sha256:${createHash("sha256").update(Buffer.from(body)).digest("hex")}`;
}
if (!digest || !/^sha256:[a-f0-9]{64}$/.test(digest)) {
throw new Error(`Registry returned an invalid manifest digest for ${repoName}:${tag}`);
}
digestCache.set(key, { digest, expiresAt: Date.now() + DIGEST_CACHE_MS });
return digest;
}
type OciFilterCriteria = {
arch: string | null;
ref: string | null;
@@ -93,7 +253,10 @@ function filterImages(images: FlatpakOciImage[], criteria: OciFilterCriteria): F
if (criteria.arch && img.Architecture !== criteria.arch) return false;
if (criteria.ref && img.Labels["org.flatpak.ref"] !== criteria.ref) return false;
if (criteria.refMustExist && !img.Labels["org.flatpak.ref"]) return false;
if (criteria.tag && !img.Tags.includes(criteria.tag)) return false;
// Flatpak asks for the ref's branch tag (usually `stable`), while per-architecture GHCR
// images are physically published as e.g. `stable-x86_64`.
const refTag = img.Labels["org.flatpak.ref"]?.split("/").at(-1);
if (criteria.tag && !img.Tags.includes(criteria.tag) && refTag !== criteria.tag) return false;
return true;
});
}
@@ -105,7 +268,7 @@ function createRepoEntry(
release: CraftRelease,
criteria: OciFilterCriteria,
): FlatpakOciRepository | null {
const images = filterImages(buildImagesForTarget(repoName, appId, appName, release), criteria);
const images = filterImages(buildImagesForTarget(appId, appName, release), criteria);
if (images.length === 0) return null;
return { Name: repoName, Repository: repoName, Images: images };
}
@@ -122,6 +285,7 @@ function getFlatpakCatalogItems(): FlatpakCatalogItem[] {
if (CRAFT_LAUNCHER_RELEASE) {
items.push({
// The shared release workflow overrides the script's local default with github.repository.
repoName: "storytold/craft-launcher",
appId: "ai.storyteller.artcraft-launcher",
displayName: CRAFT_LAUNCHER_NAME,
@@ -146,11 +310,18 @@ function getFlatpakCatalogItems(): FlatpakCatalogItem[] {
return items;
}
/** Return the catalogued Flatpak app IDs without contacting the OCI registry. */
export function getFlatpakOciAppIds(): string[] {
return getFlatpakCatalogItems()
.filter((item) => item.release !== null)
.map((item) => item.appId);
}
/**
* Build the Flatpak OCI index catalog from the release catalog.
* Supports filtering by architecture, ref, repo, and tag per flatpak-oci-specs.
*/
export function getFlatpakOciIndex(searchParams?: URLSearchParams): FlatpakOciIndexResponse {
export async function getFlatpakOciIndex(searchParams?: URLSearchParams): Promise<FlatpakOciIndexResponse> {
const criteria: OciFilterCriteria = {
arch: normalizeArch(searchParams?.get("architecture") ?? null),
ref: searchParams?.get("label:org.flatpak.ref") ?? null,
@@ -159,12 +330,10 @@ export function getFlatpakOciIndex(searchParams?: URLSearchParams): FlatpakOciIn
};
const reqRepo = searchParams?.get("repository") ?? searchParams?.get("repo");
const results: FlatpakOciRepository[] = [];
for (const item of getFlatpakCatalogItems()) {
if (reqRepo && reqRepo !== item.repoName) continue;
if (!item.release) continue;
const items = getFlatpakCatalogItems();
const selectedItems = items.filter((item) => !reqRepo || reqRepo === item.repoName);
const entries = await Promise.all(selectedItems.map(async (item) => {
if (!item.release) return null;
const entry = createRepoEntry(
item.repoName,
item.appId,
@@ -172,11 +341,17 @@ export function getFlatpakOciIndex(searchParams?: URLSearchParams): FlatpakOciIn
item.release,
criteria,
);
if (entry) results.push(entry);
}
if (!entry) return null;
await Promise.all(entry.Images.map(async (image) => {
const versionTag = image.Tags[0];
image.Digest = await fetchManifestDigest(item.repoName, versionTag);
}));
return entry;
}));
return {
Registry: process.env.FLATPAK_OCI_REGISTRY_URL ?? DEFAULT_OCI_REGISTRY,
Results: results,
Registry: registryUrl().origin,
Results: entries.filter((entry): entry is FlatpakOciRepository => entry !== null),
};
}
@@ -1,50 +1,105 @@
import { createHash } from "node:crypto";
import { expect, test } from "@playwright/test";
import { getFlatpakOciIndex } from "../src/lib/flatpak-oci";
import { GET as getFlatpakRef } from "../src/app/apps/[slug]/[filename]/route";
import { GET as getDynamicIndex } from "../src/app/index/dynamic/route";
import { GET as getStaticIndex } from "../src/app/index/static/route";
import { getFlatpakOciAppIds, getFlatpakOciIndex } from "../src/lib/flatpak-oci";
const manifestDigest = (tag: string) =>
`sha256:${createHash("sha256").update(`manifest:${tag}`).digest("hex")}`;
const originalFetch = globalThis.fetch;
const originalRegistryUrl = process.env.FLATPAK_OCI_REGISTRY_URL;
const originalReadToken = process.env.FLATPAK_OCI_READ_TOKEN;
test.describe("Flatpak OCI Registry Index Protocol", () => {
test("generates valid registry index response", () => {
const index = getFlatpakOciIndex();
expect(index.Registry).toBe("https://ghcr.io");
test("serves app flatpakref files at their public URLs", async () => {
const response = await getFlatpakRef(
new Request("https://getartcraft.com/apps/pdfcraft/pdfcraft-oci.flatpakref"),
{ params: Promise.resolve({ slug: "pdfcraft", filename: "pdfcraft-oci.flatpakref" }) },
);
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toContain("application/x-flatpak-ref");
expect(response.headers.get("content-disposition")).toContain('filename="pdfcraft-oci.flatpakref"');
expect(await response.text()).toContain("Name=ai.storyteller.pdfcraft");
});
test("rejects a flatpakref filename that does not match its app slug", async () => {
const response = await getFlatpakRef(
new Request("https://getartcraft.com/apps/pdfcraft/other-oci.flatpakref"),
{ params: Promise.resolve({ slug: "pdfcraft", filename: "other-oci.flatpakref" }) },
);
expect(response.status).toBe(404);
});
test.beforeEach(() => {
process.env.FLATPAK_OCI_REGISTRY_URL = "https://registry.test";
delete process.env.FLATPAK_OCI_READ_TOKEN;
globalThis.fetch = async (input, init) => {
const url = new URL(input instanceof Request ? input.url : input.toString());
if (url.pathname === "/token") {
return Response.json({ token: "test-pull-token" });
}
if (init?.method === "HEAD") {
const tag = decodeURIComponent(url.pathname.split("/").at(-1) ?? "");
return new Response(null, {
status: 200,
headers: { "docker-content-digest": manifestDigest(tag) },
});
}
return new Response("not found", { status: 404 });
};
});
test.afterEach(() => {
globalThis.fetch = originalFetch;
if (originalRegistryUrl === undefined) delete process.env.FLATPAK_OCI_REGISTRY_URL;
else process.env.FLATPAK_OCI_REGISTRY_URL = originalRegistryUrl;
if (originalReadToken === undefined) delete process.env.FLATPAK_OCI_READ_TOKEN;
else process.env.FLATPAK_OCI_READ_TOKEN = originalReadToken;
});
test("generates valid registry index response using real OCI manifest digests", async () => {
const index = await getFlatpakOciIndex();
expect(index.Registry).toBe("https://registry.test");
expect(index.Results.length).toBeGreaterThan(0);
// Verifies ArtCraft Launcher is present under storytold/craft-launcher repository
const launcher = index.Results.find((r) => r.Repository === "storytold/craft-launcher");
expect(launcher).toBeDefined();
expect(launcher?.Images).toHaveLength(2); // x86_64 and aarch64
expect(launcher?.Images[0].Labels["org.flatpak.ref"]).toBe("app/ai.storyteller.artcraft-launcher/x86_64/stable");
expect(launcher?.Images).toHaveLength(2);
expect(launcher?.Images[0].Labels["org.flatpak.ref"]).toBe(
"app/ai.storyteller.artcraft-launcher/x86_64/stable",
);
expect(launcher?.Images[0].Tags).toContain("stable-x86_64");
// Verifies PdfCraft is present
const pdfcraft = index.Results.find((r) => r.Name === "storytold/pdfcraft");
expect(pdfcraft).toBeDefined();
expect(pdfcraft?.Repository).toBe("storytold/pdfcraft");
const pdfcraftX86 = pdfcraft?.Images.find((img) => img.Architecture === "x86_64");
expect(pdfcraftX86).toBeDefined();
expect(pdfcraftX86?.Labels["org.flatpak.ref"]).toBe("app/ai.storyteller.pdfcraft/x86_64/stable");
expect(pdfcraftX86?.Digest).toMatch(/^sha256:[a-f0-9]{64}$/);
expect(pdfcraftX86?.Labels["org.flatpak.metadata"]).toContain("[Application]");
expect(pdfcraftX86?.Labels["org.flatpak.metadata"]).toContain("ai.storyteller.pdfcraft");
// Craft Anything has no published OCI image yet.
// The website's catalog owns release versions; no OCI build exists for Craft Anything yet.
expect(index.Results.find((r) => r.Repository === "storytold/craft-anything")).toBeUndefined();
});
test("filters by architecture", () => {
const params = new URLSearchParams({ architecture: "amd64" });
const index = getFlatpakOciIndex(params);
test("filters by architecture and repository before resolving manifests", async () => {
const params = new URLSearchParams({ architecture: "amd64", repository: "storytold/pdfcraft" });
const index = await getFlatpakOciIndex(params);
for (const repo of index.Results) {
for (const img of repo.Images) {
expect(img.Architecture).toBe("x86_64");
}
}
expect(index.Results).toHaveLength(1);
expect(index.Results[0].Images).toHaveLength(1);
expect(index.Results[0].Images[0].Architecture).toBe("x86_64");
});
test("filters by org.flatpak.ref label", () => {
test("filters by org.flatpak.ref label", async () => {
const params = new URLSearchParams({
"label:org.flatpak.ref": "app/ai.storyteller.pdfcraft/x86_64/stable",
});
const index = getFlatpakOciIndex(params);
const index = await getFlatpakOciIndex(params);
expect(index.Results).toHaveLength(1);
expect(index.Results[0].Repository).toBe("storytold/pdfcraft");
@@ -52,12 +107,61 @@ test.describe("Flatpak OCI Registry Index Protocol", () => {
expect(index.Results[0].Images[0].Architecture).toBe("x86_64");
});
test("filters by repository", () => {
const params = new URLSearchParams({ repository: "storytold/pdfcraft" });
const index = getFlatpakOciIndex(params);
test("matches Flatpak's stable query to the architecture-specific GHCR tag", async () => {
const params = new URLSearchParams({
architecture: "amd64",
tag: "stable",
"label:org.flatpak.ref:exists": "1",
});
const index = await getFlatpakOciIndex(params);
expect(index.Results).toHaveLength(1);
expect(index.Results[0].Name).toBe("storytold/pdfcraft");
expect(index.Results[0].Repository).toBe("storytold/pdfcraft");
expect(index.Results.length).toBeGreaterThan(0);
expect(index.Results.every((repo) => repo.Images.every((image) =>
image.Labels["org.flatpak.ref"].endsWith("/stable"),
))).toBe(true);
});
test("reports missing registry tags rather than returning synthetic digests", async () => {
process.env.FLATPAK_OCI_REGISTRY_URL = "https://missing.registry.test";
globalThis.fetch = async (input, init) => {
const url = new URL(input instanceof Request ? input.url : input.toString());
if (url.pathname === "/token") return Response.json({ token: "test-pull-token" });
if (init?.method === "HEAD") return new Response(null, { status: 404 });
return new Response("not found", { status: 404 });
};
await expect(getFlatpakOciIndex(new URLSearchParams({ repository: "storytold/pdfcraft" })))
.rejects.toThrow(/release workflow pushed it/);
});
test("lists expected app IDs from the catalog without querying GHCR", () => {
globalThis.fetch = async () => {
throw new Error("the app list should not query GHCR");
};
expect(getFlatpakOciAppIds()).toContain("ai.storyteller.artcraft-launcher");
expect(getFlatpakOciAppIds()).toContain("ai.storyteller.pdfcraft");
});
test("index routes preserve query filters and declare Netlify query variation", async () => {
const staticResponse = await getStaticIndex(
new Request("https://getartcraft.com/index/static?architecture=arm64"),
);
expect(staticResponse.status).toBe(200);
expect(staticResponse.headers.get("netlify-vary")).toBe("query");
const staticIndex = await staticResponse.json();
const staticImages = staticIndex.Results.flatMap((repo: { Images: { Architecture: string }[] }) => repo.Images);
expect(staticImages.length).toBeGreaterThan(0);
expect(staticImages.every((image: { Architecture: string }) => image.Architecture === "aarch64")).toBe(true);
const dynamicResponse = await getDynamicIndex(
new Request("https://getartcraft.com/index/dynamic?architecture=amd64"),
);
expect(dynamicResponse.status).toBe(200);
expect(dynamicResponse.headers.get("netlify-vary")).toBe("query");
const dynamicIndex = await dynamicResponse.json();
const dynamicImages = dynamicIndex.Results.flatMap((repo: { Images: { Architecture: string }[] }) => repo.Images);
expect(dynamicImages.length).toBeGreaterThan(0);
expect(dynamicImages.every((image: { Architecture: string }) => image.Architecture === "x86_64")).toBe(true);
});
});
@@ -220,6 +220,27 @@ test.describe("Linux Package Repositories (APT, RPM & Pacman)", () => {
expect(armDb.length).toBeGreaterThan(100);
});
test("keeps all distro tabs reachable on mobile and shows the supported RHEL baseline", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto("/linux");
const repoTablist = page.getByRole("tablist").filter({
has: page.getByRole("tab", { name: "Flatpak (OCI)" }),
});
const dimensions = await repoTablist.evaluate((element) => ({
clientWidth: element.clientWidth,
scrollWidth: element.scrollWidth,
}));
expect(dimensions.scrollWidth).toBeGreaterThan(dimensions.clientWidth);
await page.getByRole("tab", { name: "Arch Linux" }).click();
await expect(page.getByRole("tab", { name: "Arch Linux" })).toHaveAttribute("aria-selected", "true");
await expect(page.getByText(/Include = \/etc\/pacman\.d\/artcraft\.conf/)).toBeVisible();
await page.getByRole("tab", { name: "Fedora / RHEL" }).click();
await expect(page.getByText("Fedora 40+, RHEL 10+, CentOS Stream, Rocky Linux, AlmaLinux")).toBeVisible();
});
test("verifies download URLs and digests for all manifest package assets", async () => {
const apps = await getLinuxRepoApps();
for (const app of apps) {