mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-17 08:18:51 +00:00
feat: publish opt-in hosted static assets from pinned releases while retaining Pages rollback artifacts
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
import { appendFileSync, cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { resolve, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { deploymentMatrix } from "./pages-projects.mjs";
|
||||
|
||||
export function staticAssetsMatrix(projects, targets) {
|
||||
const pages = deploymentMatrix(projects).include;
|
||||
const configured = JSON.parse(targets || "[]");
|
||||
if (!Array.isArray(configured) || configured.length > pages.length) throw new Error("Invalid static asset targets");
|
||||
const seenProjects = new Set();
|
||||
const seenWorkers = new Set();
|
||||
const seenDomains = new Set();
|
||||
return { include: configured.map((target) => {
|
||||
if (!target || Object.keys(target).some((key) => !["project", "worker", "domains"].includes(key))) throw new Error("Invalid static asset target");
|
||||
const page = pages.find((entry) => entry.project === target.project);
|
||||
if (!page || typeof target.worker !== "string" || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(target.worker)) throw new Error("Unknown project or invalid Worker name");
|
||||
if (!Array.isArray(target.domains) || target.domains.length > 10) throw new Error("Explicit domains required");
|
||||
for (const domain of target.domains) {
|
||||
if (typeof domain !== "string" || domain.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(domain) || seenDomains.has(domain)) throw new Error("Invalid or duplicate custom domain");
|
||||
seenDomains.add(domain);
|
||||
}
|
||||
if (seenProjects.has(target.project) || seenWorkers.has(target.worker)) throw new Error("Duplicate static asset target");
|
||||
seenProjects.add(target.project);
|
||||
seenWorkers.add(target.worker);
|
||||
return { ...page, worker: target.worker, domains: target.domains };
|
||||
}) };
|
||||
}
|
||||
|
||||
export function prepareStaticAssets({ target, sourceRoot, destination, sourceSha, release }) {
|
||||
if (!/^[a-f0-9]{40}$/.test(sourceSha) || !/^v\d+\.\d+\.\d+$/.test(release)) throw new Error("Exact release identity required");
|
||||
const output = resolve(sourceRoot, target.output_dir);
|
||||
const dest = resolve(destination);
|
||||
if (existsSync(dest)) throw new Error("Use a new artifact directory");
|
||||
let files = 0;
|
||||
function check(path) {
|
||||
const stat = lstatSync(path);
|
||||
if (stat.isSymbolicLink()) throw new Error("Static artifacts must not contain symlinks");
|
||||
if (stat.isDirectory()) {
|
||||
for (const entry of readdirSync(path)) check(join(path, entry));
|
||||
} else if (!stat.isFile() || stat.size > 25 * 1024 * 1024 || ++files > 19999) {
|
||||
throw new Error("Artifact exceeds Workers Free asset limits");
|
||||
}
|
||||
}
|
||||
check(output);
|
||||
if (!existsSync(join(output, "index.html")) || !existsSync(join(output, "_headers"))) throw new Error("Frontend index and response headers required");
|
||||
if (existsSync(join(output, "_worker.js")) || existsSync(join(output, "_routes.json"))) throw new Error("Only static artifacts are supported");
|
||||
mkdirSync(dest, { recursive: true });
|
||||
cpSync(output, join(dest, "assets"), { recursive: true });
|
||||
if (target.app === "admin") {
|
||||
const redirects = join(dest, "assets", "_redirects");
|
||||
if (existsSync(redirects)) {
|
||||
const rules = readFileSync(redirects, "utf8").split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
|
||||
if (rules.length !== 1 || !/^\/\*\s+\/index\.html\s+200$/.test(rules[0])) throw new Error("Review changed admin redirect rules before publishing static assets");
|
||||
// The asset platform's SPA mode replaces the Pages-only catch-all rewrite.
|
||||
rmSync(redirects);
|
||||
}
|
||||
}
|
||||
mkdirSync(join(dest, "assets", ".well-known"), { recursive: true });
|
||||
writeFileSync(join(dest, "assets", ".well-known", "warmbly-release.json"), JSON.stringify({ release, sourceSha, app: target.app, project: target.project }) + "\n");
|
||||
const config = {
|
||||
name: target.worker,
|
||||
compatibility_date: "2025-10-11",
|
||||
workers_dev: false,
|
||||
preview_urls: false,
|
||||
assets: { directory: "./assets", html_handling: "auto-trailing-slash", not_found_handling: target.app === "admin" ? "single-page-application" : "404-page" },
|
||||
routes: target.domains.map((pattern) => ({ pattern, custom_domain: true })),
|
||||
};
|
||||
writeFileSync(join(dest, "wrangler.json"), JSON.stringify(config, null, 2) + "\n");
|
||||
return config;
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
try {
|
||||
const matrix = staticAssetsMatrix(process.env.CLOUDFLARE_PAGES_PROJECTS, process.env.CLOUDFLARE_STATIC_ASSETS_TARGETS);
|
||||
if (["prepare", "prepare-if-configured"].includes(process.argv[2])) {
|
||||
const target = matrix.include.find((entry) => entry.project === process.env.CLOUDFLARE_PAGES_PROJECT_NAME);
|
||||
if (!target && process.argv[2] === "prepare") throw new Error("Project is not configured for static assets");
|
||||
if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `enabled=${Boolean(target)}\n`);
|
||||
if (target) prepareStaticAssets({ target, sourceRoot: process.cwd(), destination: process.env.STATIC_ASSETS_ARTIFACT_DIR, sourceSha: process.env.SOURCE_SHA, release: process.env.RELEASE_TAG });
|
||||
} else {
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `matrix=${JSON.stringify(matrix)}\nenabled=${matrix.include.length > 0}\n`);
|
||||
}
|
||||
} catch {
|
||||
console.error("::error::Invalid static asset configuration or artifact. Require unique configured Pages projects, Worker names, explicit domains and an exact release identity.");
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { cpSync, existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { staticAssetsMatrix, prepareStaticAssets } from "./pages-static-assets.mjs";
|
||||
|
||||
const projects = JSON.stringify([{ app: "web", project: "dashboard" }, { app: "admin", project: "admin" }, { app: "docs", project: "docs" }]);
|
||||
const configured = [{ project: "dashboard", worker: "warmbly-dashboard", domains: ["stage.warmbly.com"] }];
|
||||
const sha = "a".repeat(40);
|
||||
|
||||
test("static assets are disabled unless exact Pages projects are configured", () => {
|
||||
assert.deepEqual(staticAssetsMatrix(projects), { include: [] });
|
||||
const target = staticAssetsMatrix(projects, JSON.stringify(configured)).include[0];
|
||||
assert.equal(target.output_dir, "web/dist");
|
||||
assert.equal(target.environment, "dashboard-production");
|
||||
assert.equal(target.worker, "warmbly-dashboard");
|
||||
assert.deepEqual(target.domains, ["stage.warmbly.com"]);
|
||||
});
|
||||
|
||||
test("rejects unknown projects, paths, domains, duplicate mappings and overrides", () => {
|
||||
for (const value of [null, {}, [null], [{ ...configured[0], project: "unknown" }], [{ ...configured[0], output_dir: "/tmp" }], [{ ...configured[0], worker: "../worker" }], [{ ...configured[0], domains: ["*.warmbly.com"] }], [{ ...configured[0], domains: ["stage.warmbly.com/path"] }], [{ ...configured[0], domains: ["stage.warmbly.com", "stage.warmbly.com"] }], [configured[0], configured[0]], [configured[0], { project: "admin", worker: "admin", domains: ["stage.warmbly.com"] }]]) {
|
||||
assert.throws(() => staticAssetsMatrix(projects, JSON.stringify(value)));
|
||||
}
|
||||
});
|
||||
|
||||
function fixture(app, fn) {
|
||||
const root = mkdtempSync(join(tmpdir(), "static-assets-"));
|
||||
try {
|
||||
const target = staticAssetsMatrix(projects, JSON.stringify([{ project: app === "web" ? "dashboard" : app, worker: "fixture", domains: [] }])).include[0];
|
||||
const output = join(root, target.output_dir);
|
||||
mkdirSync(output, { recursive: true });
|
||||
writeFileSync(join(output, "index.html"), "<h1>Warmbly fixture</h1>");
|
||||
for (const name of ["_headers", "_redirects", "404.html"]) {
|
||||
try { cpSync(new URL(`../../${app}/public/${name}`, import.meta.url), join(output, name)); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
||||
}
|
||||
fn({ root, target, output, destination: join(root, "artifact") });
|
||||
} finally { rmSync(root, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
test("publishes only assets and preserves exact route/header/404 files and release identity", () => {
|
||||
fixture("web", ({ root, target, output, destination }) => {
|
||||
const config = prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" });
|
||||
assert.equal(config.main, undefined);
|
||||
assert.equal(config.workers_dev, false);
|
||||
assert.equal(config.preview_urls, false);
|
||||
assert.equal(config.assets.not_found_handling, "404-page");
|
||||
assert.deepEqual(config.routes, []);
|
||||
for (const name of ["index.html", "_headers", "_redirects", "404.html"]) assert.deepEqual(readFileSync(join(output, name)), readFileSync(join(destination, "assets", name)));
|
||||
assert.deepEqual(JSON.parse(readFileSync(join(destination, "assets/.well-known/warmbly-release.json"))), { release: "v0.6.74", sourceSha: sha, app: "web", project: "dashboard" });
|
||||
assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" }));
|
||||
});
|
||||
});
|
||||
|
||||
test("admin preserves its SPA fallback and domains are explicit custom-domain bindings", () => {
|
||||
fixture("admin", ({ root, target, destination }) => {
|
||||
const config = prepareStaticAssets({ target: { ...target, domains: ["admin-stage.warmbly.com"] }, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" });
|
||||
assert.equal(config.assets.not_found_handling, "single-page-application");
|
||||
assert.equal(existsSync(join(destination, "assets", "_redirects")), false);
|
||||
assert.deepEqual(config.routes, [{ pattern: "admin-stage.warmbly.com", custom_domain: true }]);
|
||||
});
|
||||
});
|
||||
|
||||
test("refuses unpinned releases, executable Pages functions and symlink artifacts", () => {
|
||||
for (const kind of ["sha", "tag", "function", "symlink"]) fixture("web", ({ root, target, output, destination }) => {
|
||||
if (kind === "function") writeFileSync(join(output, "_worker.js"), "export default {}");
|
||||
if (kind === "symlink") symlinkSync("/etc/hosts", join(output, "outside"));
|
||||
assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: kind === "sha" ? "main" : sha, release: kind === "tag" ? "latest" : "v0.6.74" }));
|
||||
});
|
||||
});
|
||||
|
||||
test("changed admin redirect behavior requires explicit review", () => {
|
||||
fixture("admin", ({ root, target, output, destination }) => {
|
||||
writeFileSync(join(output, "_redirects"), "/old /new 301\n");
|
||||
assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" }));
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user