feat(cms): implement Git publishing for content changes and add entrypoint script

- Added a Docker entrypoint script to manage content repository cloning and updates.
- Updated server configuration to include public URL and proxy settings.
- Enhanced content file utilities to return file paths for written entries.
- Introduced GitPublisher class for handling Git operations and deployments.
- Added tests for Git publishing functionality.
- Updated Dockerfile and docker-compose for production setup.
- Added new public PGP key and security.txt for contact information.
- Created new About and Archive pages in the site.
- Updated site configuration to include new navigation links.
This commit is contained in:
2026-09-01 16:50:26 +03:00
parent ce65be8852
commit d958a298f7
24 changed files with 960 additions and 59 deletions
+13
View File
@@ -6,3 +6,16 @@ ADMIN_JWT_SECRET=tobemodified
TRANSFER_TOKEN_SALT=tobemodified
JWT_SECRET=tobemodified
ENCRYPTION_KEY=tobemodified
# Production reverse-proxy and Git publishing settings. Git publishing stays
# disabled during local development unless explicitly enabled.
PUBLIC_URL=http://localhost:1337
IS_PROXIED=false
GIT_PUBLISH_ENABLED=false
CONTENT_REPOSITORY_ROOT=
CONTENT_GIT_REPOSITORY=andwati/andwati.com
CONTENT_GIT_BRANCH=main
CONTENT_GIT_COMMIT_NAME="andwati.com CMS"
CONTENT_GIT_COMMIT_EMAIL=[email protected]
GITHUB_TOKEN=
DOKPLOY_DEPLOY_WEBHOOK_URL=
+5 -1
View File
@@ -26,8 +26,12 @@ RUN pnpm --filter cms build
FROM base AS runtime
ENV NODE_ENV=production
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates git \
&& rm -rf /var/lib/apt/lists/*
COPY --from=build /app/node_modules /app/node_modules
COPY --from=build /app/apps/cms /app/apps/cms
COPY --chmod=755 apps/cms/docker-entrypoint.sh /usr/local/bin/andwati-cms-entrypoint
WORKDIR /app/apps/cms
EXPOSE 1337
CMD ["pnpm", "start"]
ENTRYPOINT ["andwati-cms-entrypoint"]
+2
View File
@@ -5,6 +5,8 @@ const config = ({
}: Core.Config.Shared.ConfigParams): Core.Config.Server => ({
host: env("HOST", "0.0.0.0"),
port: env.int("PORT", 1337),
url: env("PUBLIC_URL", "http://localhost:1337"),
proxy: env.bool("IS_PROXIED", false),
app: {
keys: env.array("APP_KEYS")!,
},
+40
View File
@@ -0,0 +1,40 @@
#!/bin/sh
set -eu
repository_root="${CONTENT_REPOSITORY_ROOT:-/content-repository}"
repository="${CONTENT_GIT_REPOSITORY:-andwati/andwati.com}"
branch="${CONTENT_GIT_BRANCH:-main}"
case "$repository" in
*[!A-Za-z0-9._/-]* | /* | */ | *..*)
echo "Invalid CONTENT_GIT_REPOSITORY: $repository" >&2
exit 1
;;
esac
mkdir -p "$repository_root"
if [ ! -d "$repository_root/.git" ]; then
if [ -n "$(find "$repository_root" -mindepth 1 -maxdepth 1 -print -quit)" ]; then
echo "$repository_root is not empty and is not a Git checkout" >&2
exit 1
fi
git clone \
--branch "$branch" \
--single-branch \
"https://github.com/$repository.git" \
"$repository_root"
else
git -C "$repository_root" fetch origin "$branch"
git -C "$repository_root" checkout "$branch"
if [ -z "$(git -C "$repository_root" status --porcelain)" ]; then
git -C "$repository_root" merge --ff-only "origin/$branch"
else
echo "Content checkout has unpublished changes; preserving them without pulling." >&2
fi
fi
export CONTENT_REPOSITORY_ROOT="$repository_root"
exec node node_modules/@strapi/strapi/bin/strapi.js start
+2
View File
@@ -13,6 +13,7 @@
"develop": "strapi develop",
"start": "strapi start",
"strapi": "strapi",
"test:publisher": "tsx --test tests/git-publisher.test.ts",
"upgrade": "npx @strapi/upgrade latest",
"upgrade:dry": "npx @strapi/upgrade latest --dry"
},
@@ -32,6 +33,7 @@
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"tsx": "^4.23.13",
"typescript": "^5"
},
"engines": {
+2 -1
View File
@@ -1,12 +1,13 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { coversRoot } from "./content-paths";
/**
* Covers are cached into the Astro app's public/ dir directly, so the built
* site serves them from /covers/<slug>.jpg with no runtime dependency on the
* source (Open Library, Semantic Scholar, ...).
*/
const COVERS_DIR = join(process.cwd(), "..", "site", "public", "covers");
const COVERS_DIR = coversRoot();
async function download(url: string): Promise<Buffer | undefined> {
const res = await fetch(url);
+4 -2
View File
@@ -107,11 +107,12 @@ export function writeEntry(
layout: "nested" | "flat",
frontmatter: Record<string, unknown>,
body: string,
): void {
): string {
const file = entryPath(dir, slug, layout);
mkdirSync(dirname(file), { recursive: true });
const toml = stringifyToml(compact(frontmatter)).trimEnd();
writeFileSync(file, `+++\n${toml}\n+++\n\n${(body ?? "").trim()}\n`);
return file;
}
/** Deletes the file (and, for nested layout, its now-empty directory) for `slug`. */
@@ -119,9 +120,10 @@ export function deleteEntry(
dir: string,
slug: string,
layout: "nested" | "flat",
): void {
): string {
const file = entryPath(dir, slug, layout);
rmSync(file, { force: true });
if (layout === "nested")
rmSync(join(dir, slug), { recursive: true, force: true });
return file;
}
+22
View File
@@ -0,0 +1,22 @@
import { isAbsolute, join, resolve } from "node:path";
/**
* Root of the Git checkout that owns content/ and apps/site/public/covers/.
* Production points this at the persistent checkout prepared by the
* container entrypoint; local development falls back to the workspace root.
*/
export function repositoryRoot(): string {
const configured = process.env.CONTENT_REPOSITORY_ROOT;
if (!configured) return resolve(process.cwd(), "..", "..");
return isAbsolute(configured)
? configured
: resolve(process.cwd(), configured);
}
export function contentRoot(): string {
return join(repositoryRoot(), "content");
}
export function coversRoot(): string {
return join(repositoryRoot(), "apps", "site", "public", "covers");
}
+51 -15
View File
@@ -1,4 +1,5 @@
import { join } from "node:path";
import { rmSync } from "node:fs";
import { join, relative, resolve } from "node:path";
import {
cacheRemoteImage,
fetchBookCover,
@@ -10,6 +11,8 @@ import {
toTomlDate,
writeEntry,
} from "./content-file";
import { contentRoot, coversRoot } from "./content-paths";
import { publishContentChanges } from "./git-publisher";
const BOOKSHELF_UID = "api::bookshelf-entry.bookshelf-entry";
@@ -39,11 +42,6 @@ const isoDate = (value: unknown): string | undefined =>
? value
: undefined;
function contentRoot(): string {
// apps/cms -> repo root/content (also the mount point in the dev container)
return join(process.cwd(), "..", "..", "content");
}
function buildConfigs(): Record<string, SyncConfig> {
const root = contentRoot();
@@ -209,11 +207,28 @@ let importing = false;
function writeEntryForConfig(
config: SyncConfig,
entry: Record<string, unknown>,
): void {
): string | undefined {
const slug = entry.slug as string | undefined;
if (!slug) return;
if (!slug) return undefined;
const { frontmatter, body } = config.toFile(entry);
writeEntry(config.dir, slug, config.layout, frontmatter, body);
return writeEntry(config.dir, slug, config.layout, frontmatter, body);
}
function coverFileForEntry(
entry: Record<string, unknown> | null,
): string | undefined {
const coverImage = entry?.cover_image;
if (typeof coverImage !== "string" || !coverImage.startsWith("/covers/")) {
return undefined;
}
const root = resolve(coversRoot());
const file = resolve(root, coverImage.slice("/covers/".length));
const fromRoot = relative(root, file);
if (fromRoot === ".." || fromRoot.startsWith("../")) {
throw new Error(`Refusing unsafe local cover path: ${coverImage}`);
}
return file;
}
/**
@@ -325,6 +340,9 @@ async function enrichBookshelfEntry(
}
if (Object.keys(patch).length === 0) return entry;
// Keep the nested update outside the network-failure guard. Its middleware
// persists and publishes the enriched entry; publication errors must reach
// the caller instead of being mistaken for a cover-provider outage.
return documents(BOOKSHELF_UID).update({
documentId: entry.documentId as string,
data: patch,
@@ -348,14 +366,13 @@ export function registerContentSync(strapi: {
const config = SYNC_CONFIGS[ctx.uid];
if (!config || importing) return next();
let preDeleteSlug: string | undefined;
let preDeleteEntry: Record<string, unknown> | null = null;
if (ctx.action === "delete") {
const documentId = (ctx.params as { documentId?: string }).documentId;
if (documentId) {
const existing = await strapi
preDeleteEntry = await strapi
.documents(ctx.uid)
.findOne({ documentId });
preDeleteSlug = existing?.slug as string | undefined;
}
}
@@ -374,14 +391,33 @@ export function registerContentSync(strapi: {
result as Record<string, unknown>,
)
: (result as Record<string, unknown>);
writeEntryForConfig(config, entry);
} else if (ctx.action === "delete" && preDeleteSlug) {
deleteEntry(config.dir, preDeleteSlug, config.layout);
const entryFile = writeEntryForConfig(config, entry);
if (entryFile) {
const paths = [entryFile];
const coverFile = coverFileForEntry(entry);
if (coverFile) paths.push(coverFile);
await publishContentChanges(
paths,
`content: ${ctx.action} ${entry.slug as string}`,
);
}
} else if (ctx.action === "delete" && preDeleteEntry) {
const slug = preDeleteEntry.slug as string | undefined;
if (!slug) return result;
const paths = [deleteEntry(config.dir, slug, config.layout)];
const coverFile = coverFileForEntry(preDeleteEntry);
if (coverFile) {
rmSync(coverFile, { force: true });
paths.push(coverFile);
}
await publishContentChanges(paths, `content: delete ${slug}`);
}
} catch (err) {
strapi.log.error(
`content-sync: failed to write ${ctx.uid} to disk: ${(err as Error).message}`,
);
throw err;
}
return result;
+186
View File
@@ -0,0 +1,186 @@
import { execFile } from "node:child_process";
import { relative, resolve } from "node:path";
import { promisify } from "node:util";
import { repositoryRoot } from "./content-paths";
const execFileAsync = promisify(execFile);
interface GitPublisherConfig {
worktree: string;
remote?: string;
branch?: string;
token?: string;
commitName?: string;
commitEmail?: string;
deployWebhookUrl?: string;
fetchImpl?: typeof fetch;
}
function gitAuthenticationEnv(token?: string): NodeJS.ProcessEnv {
if (!token) return process.env;
const credentials = Buffer.from(`x-access-token:${token}`).toString("base64");
return {
...process.env,
GIT_CONFIG_COUNT: "1",
GIT_CONFIG_KEY_0: "http.https://github.com/.extraheader",
GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${credentials}`,
};
}
export class GitPublisher {
private readonly worktree: string;
private readonly remote: string;
private readonly branch: string;
private readonly token?: string;
private readonly commitName: string;
private readonly commitEmail: string;
private readonly deployWebhookUrl?: string;
private readonly fetchImpl: typeof fetch;
private queue: Promise<void> = Promise.resolve();
private deployPending = false;
constructor(config: GitPublisherConfig) {
this.worktree = resolve(config.worktree);
this.remote = config.remote ?? "origin";
this.branch = config.branch ?? "main";
this.token = config.token;
this.commitName = config.commitName ?? "andwati.com CMS";
this.commitEmail =
config.commitEmail ?? "[email protected]";
this.deployWebhookUrl = config.deployWebhookUrl;
this.fetchImpl = config.fetchImpl ?? fetch;
}
publish(paths: string[], message: string): Promise<void> {
const operation = this.queue.then(() => this.publishNow(paths, message));
this.queue = operation.catch(() => undefined);
return operation;
}
private async git(args: string[]): Promise<string> {
const { stdout } = await execFileAsync("git", args, {
cwd: this.worktree,
env: gitAuthenticationEnv(this.token),
timeout: 30_000,
});
return stdout.trim();
}
private repositoryPaths(paths: string[]): string[] {
return [...new Set(paths)].map((path) => {
const absolute = resolve(path);
const repositoryPath = relative(this.worktree, absolute);
if (
repositoryPath === "" ||
repositoryPath === ".." ||
repositoryPath.startsWith("../")
) {
throw new Error(
`Refusing to publish path outside Git checkout: ${path}`,
);
}
return repositoryPath;
});
}
private async hasStagedChanges(): Promise<boolean> {
try {
await this.git(["diff", "--cached", "--quiet"]);
return false;
} catch (error) {
if ((error as { code?: number }).code === 1) return true;
throw error;
}
}
private async publishNow(paths: string[], message: string): Promise<void> {
const repositoryPaths = this.repositoryPaths(paths);
await this.git(["add", "--all", "--", ...repositoryPaths]);
if (await this.hasStagedChanges()) {
await this.git([
"-c",
`user.name=${this.commitName}`,
"-c",
`user.email=${this.commitEmail}`,
"-c",
"commit.gpgsign=false",
"commit",
"-m",
message,
]);
}
await this.git(["fetch", this.remote, this.branch]);
try {
await this.git([
"rebase",
"--autostash",
`${this.remote}/${this.branch}`,
]);
} catch (error) {
await this.git(["rebase", "--abort"]).catch(() => undefined);
throw error;
}
const ahead = Number(
await this.git([
"rev-list",
"--count",
`${this.remote}/${this.branch}..HEAD`,
]),
);
if (ahead > 0) {
await this.git(["push", this.remote, `HEAD:${this.branch}`]);
this.deployPending = true;
}
if (this.deployPending && this.deployWebhookUrl) {
const response = await this.fetchImpl(this.deployWebhookUrl, {
method: "POST",
signal: AbortSignal.timeout(15_000),
});
if (!response.ok) {
throw new Error(
`Dokploy deploy webhook returned ${response.status} ${response.statusText}`,
);
}
this.deployPending = false;
}
}
}
let publisher: GitPublisher | undefined;
function publisherFromEnvironment(): GitPublisher | undefined {
if (process.env.GIT_PUBLISH_ENABLED !== "true") return undefined;
const token = process.env.GITHUB_TOKEN;
const deployWebhookUrl = process.env.DOKPLOY_DEPLOY_WEBHOOK_URL;
if (!token) throw new Error("GITHUB_TOKEN is required for Git publishing");
if (!deployWebhookUrl) {
throw new Error(
"DOKPLOY_DEPLOY_WEBHOOK_URL is required for Git publishing",
);
}
return new GitPublisher({
worktree: repositoryRoot(),
remote: process.env.CONTENT_GIT_REMOTE ?? "origin",
branch: process.env.CONTENT_GIT_BRANCH ?? "main",
token,
commitName: process.env.CONTENT_GIT_COMMIT_NAME,
commitEmail: process.env.CONTENT_GIT_COMMIT_EMAIL,
deployWebhookUrl,
});
}
/** Publishes changed source files when production Git publishing is enabled. */
export async function publishContentChanges(
paths: string[],
message: string,
): Promise<void> {
publisher ??= publisherFromEnvironment();
await publisher?.publish(paths, message);
}
+125
View File
@@ -0,0 +1,125 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import {
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { GitPublisher } from "../src/utils/git-publisher.ts";
function git(cwd: string, ...args: string[]): string {
return execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
}
function repositoryFixture(): {
root: string;
worktree: string;
cleanup: () => void;
} {
const root = mkdtempSync(join(tmpdir(), "andwati-git-publisher-"));
const remote = join(root, "remote.git");
const worktree = join(root, "worktree");
git(root, "init", "--bare", remote);
git(root, "clone", remote, worktree);
writeFileSync(join(worktree, "README.md"), "seed\n");
git(worktree, "add", "README.md");
git(
worktree,
"-c",
"user.name=Test",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"seed",
);
git(worktree, "branch", "-M", "main");
git(worktree, "push", "-u", "origin", "main");
return {
root,
worktree,
cleanup: () => rmSync(root, { recursive: true, force: true }),
};
}
test("commits, pushes, and deploys a changed source file", async () => {
const fixture = repositoryFixture();
let deploys = 0;
const publisher = new GitPublisher({
worktree: fixture.worktree,
branch: "main",
deployWebhookUrl: "https://deploy.invalid/hook",
fetchImpl: async () => {
deploys += 1;
return new Response(null, { status: 200 });
},
});
try {
const contentFile = join(fixture.worktree, "content", "post.md");
mkdirSync(join(fixture.worktree, "content"));
writeFileSync(contentFile, "published\n", { flag: "w" });
const concurrentFile = join(fixture.worktree, "content", "next.md");
writeFileSync(concurrentFile, "still being edited\n");
await publisher.publish([contentFile], "content: update post");
assert.equal(
git(fixture.worktree, "show", "origin/main:content/post.md"),
"published",
);
assert.equal(deploys, 1);
assert.equal(readFileSync(concurrentFile, "utf8"), "still being edited\n");
assert.match(git(fixture.worktree, "status", "--short"), /next\.md/);
await publisher.publish([contentFile], "content: update post");
assert.equal(deploys, 1, "unchanged content must not trigger a deploy");
} finally {
fixture.cleanup();
}
});
test("retries a pending deploy without creating another commit", async () => {
const fixture = repositoryFixture();
let deploys = 0;
const publisher = new GitPublisher({
worktree: fixture.worktree,
branch: "main",
deployWebhookUrl: "https://deploy.invalid/hook",
fetchImpl: async () => {
deploys += 1;
return new Response(null, {
status: deploys === 1 ? 503 : 200,
statusText: deploys === 1 ? "Unavailable" : "OK",
});
},
});
try {
const contentFile = join(fixture.worktree, "entry.md");
writeFileSync(contentFile, "durable\n");
await assert.rejects(
publisher.publish([contentFile], "content: create entry"),
/Dokploy deploy webhook returned 503/,
);
await publisher.publish([contentFile], "content: create entry");
assert.equal(deploys, 2);
assert.equal(
git(fixture.worktree, "rev-list", "--count", "origin/main"),
"2",
"the webhook retry must not create a duplicate commit",
);
} finally {
fixture.cleanup();
}
});