projects

showcase

A public git mirror

feat: rename to showcase, prep for /projects hosting

daniel daum committed parent 0fb1449 commit 8ca468c

Showing 21 changed files with 490 additions and 57 deletions.

Dockerfile +6 −4
@@ -1,7 +1,9 @@11# syntax=docker/dockerfile:12233# Base images are pinned by digest. To bump: crane digest <image>:<tag>4FROM golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 AS build4# The build stage runs natively and cross-compiles, so multi-arch builds only5# emulate the small runtime stage.6FROM --platform=$BUILDPLATFORM golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 AS build57WORKDIR /src68COPY go.mod go.sum ./79RUN go mod download@@ -10,7 +12,7 @@ COPY internal ./internal1012COPY web ./web1113ARG TARGETOS TARGETARCH1214RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \13    go build -trimpath -ldflags="-s -w" -o /out/daumdev ./cmd/daumdev15    go build -trimpath -ldflags="-s -w" -o /out/showcase ./cmd/showcase14161517# git is needed at runtime for the mirrors, which is why this isn't distroless.1618FROM alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf@@ -18,7 +20,7 @@ FROM alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c01820RUN apk add --no-cache git ca-certificates \1921    && mkdir /data \2022    && chown 10001:10001 /data21COPY --from=build /out/daumdev /usr/local/bin/daumdev23COPY --from=build /out/showcase /usr/local/bin/showcase2224# the mirrors are owned by this user, so no safe.directory is needed2325USER 10001:100012426ENV HOME=/data@@ -27,5 +29,5 @@ VOLUME /data2729# /healthz is 503 until the first build is published2830HEALTHCHECK --interval=30s --timeout=5s --start-period=5m \2931    CMD ["wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/healthz"]30ENTRYPOINT ["/usr/local/bin/daumdev"]32ENTRYPOINT ["/usr/local/bin/showcase"]3133CMD ["-config", "/config.json", "-data", "/data", "-listen", ":8080"]
README.md +20 −15
@@ -1,6 +1,8 @@1# daum.dev1# showcase223A small, read-only public view of selected Gitea repos. One Go binary3A small, read-only public view of selected Gitea repos, served at4[code.danieldaum.net](https://code.danieldaum.net) and styled as part of5danieldaum.net. One Go binary46rebuilds static HTML from Gitea on a timer, serves it, and passes `git clone`57and `docker pull` through to Gitea. The public side can't write, log in, or68reach Gitea's UI or API.@@ -29,10 +31,10 @@ just run         # build from real Gitea every 10 min and serve on localhost:80029313032```json3133{32    "gitea_url": "http://gitea.tailnet.example:3000",34    "gitea_url": "https://git.danieldaum.net",3335    "user": "daniel",34    "site_url": "https://daum.dev",35    "links": { "website": "https://danieldaum.net" },36    "site_url": "https://code.danieldaum.net",37    "base_path": "",3638    "repos": ["repo-a", "repo-b"],3739    "images": ["repo-a"],3840    "featured": ["repo-a"],@@ -44,27 +46,30 @@ just run         # build from real Gitea every 10 min and serve on localhost:80044464547`featured` (optional) picks up to six repos for the profile, in order.4648Without it, the six most recently updated are shown. Every repo is listed47at `/repos/`.49at `/repos/`. `base_path` (optional, like `/projects`) serves the pages50under one path, for danieldaum.net/projects; clone, `go get` and51`docker pull` stay at the root of `site_url`.48524953## Deploy505455See [deploy/README.md](deploy/README.md): releasing an image, running it at56code.danieldaum.net, moving Gitea to the tailnet, and serving it at57danieldaum.net/projects.585159```sh52just image                       # docker build -t daumdev:latest . (needs Docker)53docker compose up -d             # uses compose.yaml and ./config.json60just image                       # build for this machine (needs Docker)61just release 0.1.0               # push git.danieldaum.net/daniel/showcase:0.1.05462```55635664The container runs as uid 10001 with a read-only root filesystem, no5765capabilities and `no-new-privileges`. Only `/data` is writable: git mirrors58and site builds. It listens on plain HTTP `:8080`. Pangolin terminates TLS.5960Gitea must allow anonymous reads (`REQUIRE_SIGNIN_VIEW = false`, HTTP git61not disabled) and has to be reachable from the container at `gitea_url`.62Put Pangolin's address in `trusted_proxies` so logs show client IPs.66and site builds. It listens on plain HTTP `:8080` behind a reverse proxy67that terminates TLS.63686469## Layout65706671```67cmd/daumdev/       entrypoint72cmd/showcase/      entrypoint6873internal/config/   config.json loading and validation6974internal/gitea/    anonymous Gitea API client7075internal/gitx/     git CLI wrappers@@ -75,7 +80,7 @@ web/               embedded templates and static assets7580testdata/          sample Gitea JSON and golden output7681docs/              spec and design decisions7782Dockerfile         golang build stage, alpine + git runtime, pinned by digest78compose.yaml       example deployment83deploy/            compose, production config, saturn patch and runbook7984```80858186## Docs
cmd/daumdev/main.go → cmd/showcase/main.gorenamed +1 −1
@@ -1,4 +1,4 @@1// Command daumdev builds and serves the read-only daum.dev code site.1// Command showcase builds and serves the read-only code site at site_url.22package main3344import (
compose.yamldeleted +0 −16
@@ -1,16 +0,0 @@1# Example deployment. Pangolin proxies daum.dev to 127.0.0.1:8080, and the2# container reaches Gitea over the host's Tailscale connection.3services:4    daumdev:5        image: daumdev:latest6        build: .7        read_only: true8        cap_drop: [ALL]9        security_opt: ["no-new-privileges:true"]10        volumes:11            - daumdev-data:/data12            - ./config.json:/config.json:ro13        ports: ["127.0.0.1:8080:8080"]14        restart: unless-stopped15volumes:16    daumdev-data:
deploy/README.mdadded +93 −0
@@ -0,0 +1,93 @@1# Deploying showcase23Three stages. Each one works on its own.451. **code.danieldaum.net**: the container on the server, behind your6   reverse proxy. Gitea is still public at git.danieldaum.net.72. **Gitea on the tailnet**: only `gitea_url` changes.83. **danieldaum.net/projects**: saturn's Pages Function serves showcase's9   pages. Clone, `go get` and `docker pull` stay on code.danieldaum.net.1011## Release an image1213On a machine with Docker (the Mac):1415```sh16git tag -s v0.1.0 -m v0.1.0         # signed, on a clean, committed tree17git push origin v0.1.018docker login git.danieldaum.net     # a Gitea token with write:package19just release 0.1.0                  # linux/amd64 + linux/arm64, tags 0.1.0 and latest20```2122The image is `git.danieldaum.net/daniel/showcase:0.1.0`.2324## 1. code.danieldaum.net2526On the server, in a folder holding `compose.yaml` and `config.json` from27here:2829```sh30docker compose up -d31docker compose logs -f              # the first build mirrors every repo32curl -s 127.0.0.1:8080/healthz      # "ok" once the first build is live (503 until then)33```3435- Point your reverse proxy for `code.danieldaum.net` at `127.0.0.1:8080`36  (plain HTTP; the proxy does TLS).37- Optional: put the proxy's address in `trusted_proxies`, so logs show38  visitors' IPs. Behind Cloudflare, `CF-Connecting-IP` is used.39- Gitea must allow anonymous reads (`REQUIRE_SIGNIN_VIEW = false`, HTTP git40  on), or the site is empty and clones fail.41- `images: ["showcase"]` lists the image on the packages page and lets42  `docker pull code.danieldaum.net/daniel/showcase:0.1.0` through.4344Saturn: apply `saturn/saturn.patch` (`git apply` in the saturn repo). It:4546- shares the palette with code.danieldaum.net through a `theme` cookie47  (`theme.js`), so both sites show the same one;48- adds `social/functions/projects/`, which redirects `/projects/…` to49  code.danieldaum.net (so `/projects/saturn/` lands on the saturn repo);50- takes `/projects/` out of likes and comments (`isLikeable`). The email51  worker uses it too, so run `mise run social-email` after deploying.5253The old pages in saturn's `projects/` are never served after this. Delete54them when you like.5556## 2. Gitea on the tailnet5758Set `gitea_url` to the tailnet address (for example59`https://git.aardvark-halibut.ts.net`) and restart the container. Mirrors60follow the new address on the next build. Nothing else changes: Gitea's61address never reaches a page.6263The container has to reach that address, and `*.ts.net` names often don't64resolve inside Docker. In order of preference:6566- Gitea on the same host: put both on one Docker network and use67  `http://gitea:3000`. No tailnet hop.68- A Tailscale sidecar container, sharing its network69  (`network_mode: service:tailscale`).70- The Gitea machine's 100.x tailnet IP. Only plain HTTP works this way,71  since the HTTPS certificate is for the name.7273Check from the server:74`docker compose exec showcase wget -qO- <gitea_url>/api/v1/version`.7576Once Gitea is internal, the server pulls the image from the tailnet name77(`git.aardvark-halibut.ts.net/daniel/showcase`), or from showcase itself78(`code.danieldaum.net/daniel/showcase`).7980## 3. danieldaum.net/projects81821. In `config.json`, add `"base_path": "/projects"` and restart. Pages83   move to `code.danieldaum.net/projects/…`, and old addresses redirect84   there. Clone, `go get`, `docker pull` and `/healthz` stay at the root.852. In saturn's `social/functions/projects/[[path]].js`, set86   `MODE = "proxy"` and deploy. danieldaum.net/projects now serves87   showcase.8889Check: `curl -sI https://danieldaum.net/projects/` (200, showcase's90`Content-Security-Policy`), and `git clone https://code.danieldaum.net/<repo>.git`.9192Each page view is a Functions request (100k a day on the free plan).93Waiting on code.danieldaum.net doesn't count toward the CPU limit.
deploy/compose.yamladded +15 −0
@@ -0,0 +1,15 @@1# code.danieldaum.net: your reverse proxy terminates TLS and forwards to2# 127.0.0.1:8080. Run from this folder, next to config.json.3services:4    showcase:5        image: git.danieldaum.net/daniel/showcase:0.1.06        read_only: true7        cap_drop: [ALL]8        security_opt: ["no-new-privileges:true"]9        volumes:10            - showcase-data:/data11            - ./config.json:/config.json:ro12        ports: ["127.0.0.1:8080:8080"]13        restart: unless-stopped14volumes:15    showcase-data:
deploy/config.jsonadded +9 −0
@@ -0,0 +1,9 @@1{2    "gitea_url": "https://git.danieldaum.net",3    "user": "daniel",4    "site_url": "https://code.danieldaum.net",5    "repos": ["showcase", "saturn", "holonet", "rhea", "minerva", "homelab", "dotfiles"],6    "images": ["showcase"],7    "max_commits": 50,8    "theme": "moss"9}
deploy/saturn/saturn.patchadded +134 −0
@@ -0,0 +1,134 @@1diff --git a/_routes.json b/_routes.json2index f37e407..708a79a 1006443--- a/_routes.json4+++ b/_routes.json5@@ -1,5 +1,5 @@6 {7     "version": 1,8-    "include": ["/about/*", "/now/*", "/blog/*", "/projects/*", "/api/*"],9+    "include": ["/about/*", "/now/*", "/blog/*", "/projects", "/projects/*", "/api/*"],10     "exclude": []11 }12diff --git a/social/README.md b/social/README.md13index 28f5a85..730f46a 10064414--- a/social/README.md15+++ b/social/README.md16@@ -10,6 +10,7 @@ likes and comments. everything for them lives in this folder, and none of it is17 | `functions/_middleware.js` | runs before a page is served and fills its `data-social` section from d1 |18 | `functions/api/like.js` | the like button posts here |19 | `functions/api/moderate.js` | the approve/delete page linked from new-comment emails |20+| `functions/projects/` | not social: `/projects/` is showcase at code.danieldaum.net, redirected or proxied |21 | `email.js` | email worker: turns mail sent to `reply@replies.danieldaum.net` into comments |22 | `schema.sql` | the d1 tables: `Likes`, `LikeVoters`, `Comments` |23 | `wrangler.toml` | pages config (d1 binding) |24@@ -44,13 +45,13 @@ put this at the end of the post, inside `<article>` if it has one. the template25 </section>26 ```27 28-this works on `/about/`, `/now/<slug>/`, `/blog/<slug>/` and `/projects/<slug>/`. take the section out and the page has none.29+this works on `/about/`, `/now/<slug>/` and `/blog/<slug>/`. `/projects/` is showcase (`functions/projects/`), so it has none. take the section out and the page has none.30 31 `/now/` is a copy of the newest edition, so it points at that edition: `data-social="/now/<slug>/"`. update it with each new now post. comments always go on the edition, never on `/now/`.32 33 ### a new kind of page (e.g. `/books/<slug>/`)34 35-1. add it to `isLikeable()` in `lib.js`: `(blog|now|projects)` → `(blog|now|projects|books)`36+1. add it to `isLikeable()` in `lib.js`: `(blog|now)` → `(blog|now|books)`37 2. add `"/books/*"` to `/_routes.json`. every path in there runs a function and isn't cached, so keep it narrow38 3. add the section to the pages39 4. `mise run social-email`: the worker uses `isLikeable()` too, so it rejects comments for the new pages until it's redeployed40diff --git a/social/functions/projects/[[path]].js b/social/functions/projects/[[path]].js41new file mode 10064442index 0000000..5db842e43--- /dev/null44+++ b/social/functions/projects/[[path]].js45@@ -0,0 +1,24 @@46+// /projects/ is showcase, the code site at code.danieldaum.net, not files in47+// this repo (the old pages under projects/ are never served).48+//49+// MODE "redirect": send visitors to code.danieldaum.net.50+// MODE "proxy": serve showcase here at /projects/. Run showcase with51+//   "base_path": "/projects" first, so its links stay under /projects/.52+//   Clone, go get and docker pull stay on code.danieldaum.net.53+const ORIGIN = "https://code.danieldaum.net";54+const MODE = "redirect";55+56+export async function onRequest({ request }) {57+    const url = new URL(request.url);58+    if (MODE === "redirect") {59+        const rest = url.pathname.replace(/^\/projects/, "") || "/";60+        return Response.redirect(ORIGIN + rest + url.search, 302);61+    }62+    if (request.method !== "GET" && request.method !== "HEAD") {63+        return new Response("not found", { status: 404 });64+    }65+    // the origin is fixed: only showcase's own pages can come back66+    const upstream = new Request(ORIGIN + url.pathname + url.search, request);67+    upstream.headers.delete("Cookie");68+    return fetch(upstream, { redirect: "manual" });69+}70diff --git a/social/functions/projects/index.js b/social/functions/projects/index.js71new file mode 10064472index 0000000..6ff911a73--- /dev/null74+++ b/social/functions/projects/index.js75@@ -0,0 +1,2 @@76+// /projects and /projects/ themselves77+export { onRequest } from "./[[path]].js";78diff --git a/social/lib.js b/social/lib.js79index 3022e7b..e312360 10064480--- a/social/lib.js81+++ b/social/lib.js82@@ -3,9 +3,9 @@83 export const SITE = "https://danieldaum.net";84 export const REPLY_TO = "reply@replies.danieldaum.net";85 86-// /about/, /now/, /now/<slug>/, /blog/<slug>/, /projects/<slug>/87+// /about/, /now/, /now/<slug>/, /blog/<slug>/ (/projects/ is showcase, see functions/projects/)88 export function isLikeable(path) {89-    return /^\/(about|now)\/$|^\/(blog|now|projects)\/[a-z0-9-]+\/$/.test(path);90+    return /^\/(about|now)\/$|^\/(blog|now)\/[a-z0-9-]+\/$/.test(path);91 }92 93 // ===== hmac =====94diff --git a/theme.js b/theme.js95index a4832d7..3ad787a 10064496--- a/theme.js97+++ b/theme.js98@@ -1,6 +1,11 @@99 // one palette per visit: it holds while the tab is open, and the next visit gets the100 // next one. without js the css stays moss and the theme button stays hidden.101+// a `theme` cookie on danieldaum.net carries the palette to code.danieldaum.net102+// and back, so both sites show the same one.103 const themes = ["moss", "ink", "wine", "plum", "teal"]; // "flexoki"104+const shared = location.hostname.endsWith("danieldaum.net")105+    ? "; domain=danieldaum.net; secure"106+    : "";107 108 function after(theme) {109     return themes[(themes.indexOf(theme) + 1) % themes.length];110@@ -8,6 +13,7 @@ function after(theme) {111 112 function use(theme) {113     document.documentElement.dataset.theme = theme;114+    document.cookie = `theme=${theme}; path=/; samesite=lax${shared}`;115     try {116         sessionStorage.setItem("theme", theme);117         localStorage.setItem("theme", theme);118@@ -16,10 +22,13 @@ function use(theme) {119 120 let current = "moss";121 try {122+    const cookie = /(?:^|;\s*)theme=([a-z]+)/.exec(document.cookie)?.[1];123     const visit = sessionStorage.getItem("theme");124-    current = themes.includes(visit)125-        ? visit126-        : after(localStorage.getItem("theme"));127+    current = themes.includes(cookie)128+        ? cookie129+        : themes.includes(visit)130+          ? visit131+          : after(localStorage.getItem("theme"));132 } catch {}133 use(current);134 
docs/decisions.md +47 −0
@@ -739,3 +739,50 @@ allowlist of it.739739  elements, and whatever is still open is closed at the end.740740- No new dependency: the tags are read with two regular expressions, which741741  is enough because the output is built from scratch, never copied.742743## Release 0.1.0: name, deploy folder, base path744745- **Name:** the project is "showcase". The binary, `cmd/showcase`, the746  compose service and the image (`git.danieldaum.net/daniel/showcase`) use747  it. The Go module path stays `daum.dev/showcase`, since nothing imports748  it from outside.749- **Deploy folder:** `deploy/` holds the production `config.json` (no750  secrets: the builder is anonymous), `compose.yaml`, the saturn patch and751  the runbook. The root `config.json` stays gitignored, for `just run`.752- **Images:** `just release <version>` builds linux/amd64 and linux/arm64753  with buildx and pushes `<version>` and `latest`. It refuses a dirty tree754  or a HEAD not tagged `v<version>`. The Dockerfile's build stage runs on755  `$BUILDPLATFORM` and cross-compiles, so only the small runtime stage is756  emulated. Both base digests are multi-arch indexes.757- **Mirrors follow `gitea_url`:** `gitx.Mirror` resets `origin` to the758  configured URL before each fetch. Before, a mirror kept fetching the759  address it was cloned from, so moving Gitea to the tailnet would have760  broken every repo until the volume was wiped.761- **`base_path`** (`/projects`, or empty for the root) serves the pages under762  one path segment, for danieldaum.net/projects through saturn's Pages763  Function.764  - Links: templates and the builder still write root-relative links. One765    pass in `render.Write` prefixes every root-relative `href` and `src`766    (`/repo-a/` → `/projects/repo-a/`), README links included, so no link767    can be missed. html/template always quotes attributes with `"` and768    escapes quotes in text and values, so only real attributes match.769    `//host` links are left alone. `TestBasePathLinks` fails if any page770    links outside the base.771  - Server: paths under the base are served with it stripped. Anything772    else redirects into the base (`/repo-a/` → `/projects/repo-a/`), so773    old links keep working. Clone, `docker pull`, release downloads, `go get`774    (`?go-get=1`) and `/healthz` stay at the root: module paths and image775    refs can't move, and Pages Functions only forward GET and HEAD.776  - Release downloads link to `site_url` when a base is set, since777    danieldaum.net doesn't forward them.778  - The webmanifest's paths are relative, so they work under either.779  - Validation: one lowercase segment, not a reserved name or a repo name.780- **Saturn side** (`deploy/saturn/saturn.patch`): `theme.js` shares the781  palette through the `theme` cookie, `social/functions/projects/` redirects782  `/projects/*` to code.danieldaum.net (`MODE = "redirect"`) or proxies it783  (`"proxy"`), `_routes.json` adds `/projects`, and `isLikeable` drops784  `/projects/`. The proxy forwards GET and HEAD only, to a fixed origin,785  without cookies, and returns upstream redirects as they are. Showcase's786  security headers pass through; saturn's `_headers` don't apply to787  Function responses. Tested with Node in front of a `base_path` build:788  all 66 pages and their links work through it.
docs/security.md +1 −1
@@ -13,7 +13,7 @@ enforces it and the test that proves it. Run them all with `just test`.1313| 4 | Realm rewrite, strip `Set-Cookie` and Gitea headers, no client `Authorization`/`Cookie` on git | `newProxy` Rewrite and ModifyResponse. Non-Bearer challenges are dropped too, so git never prompts. | `TestProxyRoutes`, `TestProxyResponses` |1414| 5 | Safe rendering | goldmark; raw HTML is never passed through, only rebuilt from an allowlist of tags and attributes (`htmlRenderer`), with links and images resolved like Markdown's and only http(s)/mailto hrefs; dangerous URLs blanked, `html/template` everywhere, highlighter escapes every token, 512 KB / binary limits, README images relative or https only | `TestSiteGolden` (forbidden strings), `TestOutputIsSafe` (no `<script`, inline `style=` or `on*=` in any page), `TestReadmeHTML` (script, handlers, styles, `javascript:`, stray closes) |1515| 6 | Security headers; raw never rendered as HTML | `route` sets the CSP, `nosniff` and `no-referrer` on every response. `raw` serves allowed images, `text/plain` or an attachment. Release assets are always attachments. | `TestRoutes` (headers on every case, raw SVG and HTML are `text/plain`), `TestProxyResponses` |16| 7 | Container: non-root, read-only, no caps, no-new-privileges, only `/data` writable | `Dockerfile` (`USER 10001`, `HOME=/data`), `compose.yaml` | `hadolint`; container not yet run (see open items) |16| 7 | Container: non-root, read-only, no caps, no-new-privileges, only `/data` writable | `Dockerfile` (`USER 10001`, `HOME=/data`), `deploy/compose.yaml` | `hadolint`; container not yet run (see open items) |1717| 8 | Trust `X-Forwarded-*` only from Pangolin | `clientIP` uses `trusted_proxies`. The proxy strips `X-Forwarded-*` and `Forwarded` toward Gitea. | `TestClientIP`, `TestProxyRoutes` |1818| 9 | Cap `git-upload-pack` bodies, reject other bodies | 10 MB `MaxBytesReader`. A GET or HEAD with a body gets a 400. Proxy GET routes require no body. | `TestProxyResponses`, `TestBodyRejected` |1919
internal/build/build.go +1 −1
@@ -65,7 +65,7 @@ func (b *Builder) Render(ctx context.Context, dir string) error {6565		return err6666	}676768	rd.Theme = b.Cfg.Theme68	rd.Theme, rd.Base = b.Cfg.Theme, b.Cfg.BasePath6969	p := Profile{User: user}7070	if img, ct, err := b.Gitea.Avatar(ctx, user.AvatarURL); err != nil {7171		b.Log.Warn("avatar", "err", err)
internal/build/extra.go +7 −1
@@ -40,6 +40,12 @@ type ExtraPage struct {4040// registry data.4141func (b *Builder) renderExtras(ctx context.Context, rd *render.Renderer, dir string, r *repo) error {4242	base := "/" + r.Name43	// Downloads go through the proxy at the root of site_url. Under a44	// base_path the pages may be served elsewhere, so link there directly.45	dl := base46	if b.Cfg.BasePath != "" {47		dl = b.Cfg.SiteURL + base48	}4349	rel := ExtraPage{Repo: r, Tab: "releases"}4450	for _, x := range r.Releases {4551		v := ReleaseView{Release: x}@@ -48,7 +54,7 @@ func (b *Builder) renderExtras(ctx context.Context, rd *render.Renderer, dir str4854			return err4955		}5056		for _, a := range x.Assets {51			v.Assets = append(v.Assets, Crumb{a.Name, base + "/releases/download/" + url.PathEscape(x.TagName) + "/" + url.PathEscape(a.Name)})57			v.Assets = append(v.Assets, Crumb{a.Name, dl + "/releases/download/" + url.PathEscape(x.TagName) + "/" + url.PathEscape(a.Name)})5258		}5359		rel.Releases = append(rel.Releases, v)5460	}
internal/build/safety_test.go +30 −0
@@ -65,3 +65,33 @@ func TestOutputIsSafe(t *testing.T) {6565		t.Error("private repo directory exists")6666	}6767}6869// Under a base_path every page link stays inside it: anything root-relative70// outside /projects/ would 404 on danieldaum.net. Downloads go to site_url.71func TestBasePathLinks(t *testing.T) {72	dir := t.TempDir()73	b := testBuilder(t)74	b.Cfg.BasePath = "/projects"75	if err := b.Render(context.Background(), dir); err != nil {76		t.Fatal(err)77	}78	link := regexp.MustCompile(`\s(?:href|src)="(/[^"]*)"`)79	pages, downloads := 0, 080	filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {81		if err != nil || d.IsDir() || !strings.HasSuffix(p, ".html") || strings.Contains(p, "/raw/") {82			return err83		}84		pages++85		s, _ := os.ReadFile(p)86		for _, m := range link.FindAllStringSubmatch(string(s), -1) {87			if !strings.HasPrefix(m[1], "/projects/") {88				t.Errorf("%s links outside the base: %s", p, m[1])89			}90		}91		downloads += strings.Count(string(s), `href="https://code.danieldaum.net/repo-a/releases/download/`)92		return nil93	})94	if pages < 50 || downloads == 0 {95		t.Errorf("checked %d pages and %d download links", pages, downloads)96	}97}
internal/config/config.go +11 −3
@@ -14,9 +14,13 @@ import (1414)15151616type Config struct {17	GiteaURL string   `json:"gitea_url"`18	User     string   `json:"user"`19	SiteURL  string   `json:"site_url"`17	GiteaURL string `json:"gitea_url"`18	User     string `json:"user"`19	SiteURL  string `json:"site_url"`20	// BasePath ("/projects") puts the pages under one path segment, so a21	// proxy can serve them at danieldaum.net/projects. Clone, go get, docker22	// pull and /healthz stay at the root of site_url. Empty means the root.23	BasePath string   `json:"base_path"`2024	Repos    []string `json:"repos"`2125	Images   []string `json:"images"`2226	// Featured repos for the profile, in order (up to 6). Empty means the@@ -30,6 +34,7 @@ type Config struct {30343135var (3236	nameRe  = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)37	baseRe  = regexp.MustCompile(`^(/[a-z0-9][a-z0-9-]*)?$`)3338	imageRe = regexp.MustCompile(`^[a-z0-9]+([._-][a-z0-9]+)*(/[a-z0-9]+([._-][a-z0-9]+)*)*$`)3439	// Top-level names the site or router uses for itself.3540	reserved = []string{"static", "v2", "healthz", "api", "user", "repos", "index.html", "404.html"}@@ -92,6 +97,9 @@ func (c *Config) validate() error {9297			}9398		}9499	}100	if b := strings.TrimPrefix(c.BasePath, "/"); !baseRe.MatchString(c.BasePath) || slices.Contains(reserved, b) || seen[b] {101		return fmt.Errorf("base_path %q must be empty or one lowercase segment like /projects, not a reserved or repo name", c.BasePath)102	}95103	if c.Theme == "" {96104		c.Theme = "moss"97105	}
internal/gitx/gitx.go +6 −1
@@ -39,9 +39,14 @@ func git(ctx context.Context, dir string, args ...string) ([]byte, error) {3939	return out, nil4040}414142// Mirror clones url into dir as a bare mirror, or fetches if it exists.42// Mirror clones url into dir as a bare mirror, or fetches if it exists. The43// remote is reset to url first, so changing gitea_url (say, to a tailnet44// address) moves existing mirrors along instead of fetching the old host.4345func Mirror(ctx context.Context, url, dir string) (Repo, error) {4446	if _, err := os.Stat(dir); err == nil {47		if _, err := git(ctx, dir, "remote", "set-url", "origin", url); err != nil {48			return Repo{dir}, err49		}4550		_, err := git(ctx, dir, "fetch", "--prune", "--quiet", "origin")4651		return Repo{dir}, err4752	}
internal/render/render.go +17 −1
@@ -25,6 +25,7 @@ type Renderer struct {2525	Now   time.Time // fixed per build so output is deterministic2626	css   string    // short hash of style.css, so caches never serve a stale one2727	Theme string    // saturn palette name, the default without JS28	Base  string    // base_path ("/projects"), put in front of every root-relative link2829	pages map[string]*template.Template2930	syms  map[string][]byte // sprite symbols by id: f-<glyph> file icons, i-<name> UI icons3031}@@ -108,7 +109,22 @@ func (r *Renderer) Write(dir, rel, name string, p Page) error {108109	if err := t.ExecuteTemplate(&buf, "base", p); err != nil {109110		return fmt.Errorf("render %s: %w", rel, err)110111	}111	return WriteFile(filepath.Join(dir, filepath.FromSlash(rel)), r.fillSprite(buf.Bytes()))112	return WriteFile(filepath.Join(dir, filepath.FromSlash(rel)), r.rebase(r.fillSprite(buf.Bytes())))113}114115// rootLink matches a root-relative href or src: html/template always quotes116// attributes with ", and quotes inside text and values are escaped, so this117// only finds real attributes. "//host" links are left alone.118var rootLink = regexp.MustCompile(`(\s(?:href|src)=")/([^/])`)119120// rebase moves every root-relative link under r.Base. Templates and the121// builder write links from the site root; this one pass keeps them all,122// README links included, right when the pages live under a path.123func (r *Renderer) rebase(b []byte) []byte {124	if r.Base == "" {125		return b126	}127	return rootLink.ReplaceAll(b, []byte("${1}"+r.Base+"/${2}"))112128}113129114130// WriteFile writes b to name, creating parent directories.
internal/server/proxy_test.go +18 −0
@@ -238,3 +238,21 @@ func TestCloneAndPush(t *testing.T) {238238		t.Fatal("cloned a repo that is not allowlisted")239239	}240240}241242// Clones, pulls and downloads stay at the root under a base_path.243func TestProxyRoutesIgnoreBasePath(t *testing.T) {244	u := &upstream{}245	s := proxyServer(t, u, true)246	s.Cfg.BasePath = "/projects"247	for path, want := range map[string]string{248		"/repo-a.git/info/refs?service=git-upload-pack": "/daniel/repo-a.git/info/refs?service=git-upload-pack",249		"/v2/": "/v2/",250		"/repo-a/releases/download/v1.0/app.tar.gz": "/daniel/repo-a/releases/download/v1.0/app.tar.gz",251	} {252		u.got = nil253		w := do(s, "GET", path, nil)254		if w.Code != 200 || len(u.got) != 1 || u.got[0].RequestURI != want {255			t.Errorf("GET %s: %d, upstream %v, want %q", path, w.Code, u.got, want)256		}257	}258}
internal/server/server.go +18 −2
@@ -101,6 +101,22 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request) {101101		s.notFound(w, r)102102		return103103	}104	// Under a base_path the pages live at base/…; old root URLs redirect105	// there. `go get` keeps asking at the root (the module path doesn't move).106	base := s.Cfg.BasePath107	if base != "" {108		switch {109		case strings.HasPrefix(p, base+"/"):110			p = strings.TrimPrefix(p, base)111		case r.URL.Query().Has("go-get"):112		case p == base:113			http.Redirect(w, r, base+"/", http.StatusMovedPermanently)114			return115		default:116			http.Redirect(w, r, base+p, http.StatusMovedPermanently)117			return118		}119	}104120	if !s.Ready() {105121		http.Error(w, "the site is being built, try again in a minute", http.StatusServiceUnavailable)106122		return@@ -113,7 +129,7 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request) {113129	case p == "/repos/": // every repo; the profile shows the featured ones114130		s.file(w, r, "repos/index.html", "text/html; charset=utf-8")115131	case p == "/repos":116		http.Redirect(w, r, "/repos/", http.StatusMovedPermanently)132		http.Redirect(w, r, base+"/repos/", http.StatusMovedPermanently)117133	case first == "static" && rest != "":118134		s.file(w, r, p, staticType(p))119135	case !s.Cfg.HasRepo(first):@@ -125,7 +141,7 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request) {125141	case strings.HasPrefix(rest, "blob/"):126142		s.file(w, r, p+".html", "text/html; charset=utf-8")127143	case rest == "" && !strings.HasSuffix(p, "/"), !strings.HasSuffix(p, "/") && s.isDir(p):128		http.Redirect(w, r, p+"/", http.StatusMovedPermanently)144		http.Redirect(w, r, base+p+"/", http.StatusMovedPermanently)129145	case strings.HasSuffix(p, "/"):130146		s.file(w, r, p+"index.html", "text/html; charset=utf-8")131147	default:
internal/server/server_test.go +37 −0
@@ -139,3 +139,40 @@ func TestClientIP(t *testing.T) {139139		t.Errorf("trusted peer: got %s", ip)140140	}141141}142143func TestBasePath(t *testing.T) {144	s := testServer(t, true)145	s.Cfg.BasePath = "/projects"146	cases := []struct {147		path     string148		status   int149		body     string // or the Location of a redirect150		location string151	}{152		{"/projects/", 200, "home", ""},153		{"/projects/repos/", 200, "all repos", ""},154		{"/projects/repo-a/", 200, "repo page", ""},155		{"/projects/repo-a/blob/main.go", 200, "main.go page", ""},156		{"/projects/repo-a/raw/main.go", 200, "package main", ""},157		{"/projects/static/style.css", 200, "body{}", ""},158		{"/healthz", 200, "ok", ""},159		{"/repo-a/sub/pkg?go-get=1", 200, "repo page", ""}, // module paths stay at the root160		// redirects into the base, so old links keep working161		{"/projects", 301, "", "/projects/"},162		{"/", 301, "", "/projects/"},163		{"/repo-a/log/", 301, "", "/projects/repo-a/log/"},164		{"/projects/repos", 301, "", "/projects/repos/"},165		{"/projects/repo-a", 301, "", "/projects/repo-a/"},166		{"/projects/repo-a/tree/docs", 301, "", "/projects/repo-a/tree/docs/"},167		// still 404 inside the base168		{"/projects/secret/", 404, "not found", ""},169		{"/projects/index.html", 404, "not found", ""},170		{"/projects/../secret/", 404, "not found", ""},171	}172	for _, c := range cases {173		w := do(s, "GET", c.path, nil)174		if w.Code != c.status || !strings.Contains(w.Body.String(), c.body) || w.Header().Get("Location") != c.location {175			t.Errorf("GET %s: %d %q location %q, want %d %q %q", c.path, w.Code, w.Body.String(), w.Header().Get("Location"), c.status, c.body, c.location)176		}177	}178}
justfile +15 −7
@@ -25,9 +25,17 @@ digests:2525    @echo "golang:1.27.4-alpine3.24 $(crane digest golang:1.27.4-alpine3.24)"2626    @echo "alpine:3.24.4            $(crane digest alpine:3.24.4)"272728# Build the image (needs Docker, e.g. on the host)29image:30    docker build -t daumdev:latest .28image_name := "git.danieldaum.net/daniel/showcase"2930# Build the image for this machine (needs Docker, e.g. on the host)31image tag="dev":32    docker build -t {{image_name}}:{{tag}} .3334# Push a tagged release: needs Docker, `docker login git.danieldaum.net`, a clean tree and HEAD tagged v<version>35release version:36    git diff --quiet HEAD || { echo "commit first"; exit 1; }37    test "$(git describe --exact-match --tags HEAD 2>/dev/null)" = "v{{version}}" || { echo "tag HEAD as v{{version}} first"; exit 1; }38    docker buildx build --platform linux/amd64,linux/arm64 -t {{image_name}}:{{version}} -t {{image_name}}:latest --push .31393240# Regenerate the icons from extracted npm packages: material-icon-theme@5.40.0 and @primer/octicons@19.15.03341icons material octicons:@@ -36,20 +44,20 @@ icons material octicons:36443745# Build the binary into ./bin3846build:39    CGO_ENABLED=0 go build -trimpath -o bin/daumdev ./cmd/daumdev47    CGO_ENABLED=0 go build -trimpath -o bin/showcase ./cmd/showcase40484149# Render the site once into ./out (needs a config.json and access to Gitea)4250render config="config.json":4351    rm -rf out44    go run ./cmd/daumdev -config {{config}} -data .data -once -out out52    go run ./cmd/showcase -config {{config}} -data .data -once -out out45534654# Serve the finished build in ./out on localhost:8000 with the real server4755serve config="testdata/demo.json":48    go run ./cmd/daumdev -config {{config}} -serve-dir out -listen 127.0.0.1:800056    go run ./cmd/showcase -config {{config}} -serve-dir out -listen 127.0.0.1:800049575058# Build from real Gitea every 10 minutes and serve on localhost:8000 (needs ./config.json)5159run config="config.json":52    go run ./cmd/daumdev -config {{config}} -data .data -listen 127.0.0.1:800060    go run ./cmd/showcase -config {{config}} -data .data -listen 127.0.0.1:800053615462# Render from real Gitea (needs ./config.json) and serve it5563preview config="config.json": (render config)
web/static/favicon/site.webmanifest +4 −4
@@ -4,12 +4,12 @@44    "description": "Software engineer based in Oakland",55    "icons": [66        {7            "src": "/static/favicon/android-chrome-192x192.png",7            "src": "android-chrome-192x192.png",88            "sizes": "192x192",99            "type": "image/png"1010        },1111        {12            "src": "/static/favicon/android-chrome-512x512.png",12            "src": "android-chrome-512x512.png",1313            "sizes": "512x512",1414            "type": "image/png"1515        }@@ -17,7 +17,7 @@1717    "theme_color": "#1a1e0c",1818    "background_color": "#1a1e0c",1919    "display": "standalone",20    "start_url": "/",21    "scope": "/",20    "start_url": "../../",21    "scope": "../../",2222    "orientation": "portrait-primary"2323}