feat(help): serve the in-app wiki from disk instead of fetching GitHub

The /help pages fetched their markdown from raw.githubusercontent.com at
runtime, so a self-hosted install was served docs from main rather than the
version it was actually running, and help was unusable without network access.
The wiki/ directory was in the repo the whole time; the bundled-snapshot
fallback the code reached for was gitignored and never populated by any build
step, so it was dead code.

Read wiki/ straight from disk instead. server/{src,dist}/services both sit
three levels under the repo root, so a single __dirname anchor resolves in dev,
a built source install, vitest and Docker with no copy or build step. GitHub is
kept strictly as a fallback for when the directory cannot be resolved, decided
once at load by probing for _Sidebar.md: a page missing from a present wiki is
a genuine 404, since falling back per-file would reintroduce the version skew
this removes.

Ship wiki/ in the image: .dockerignore excluded it outright, so the COPY alone
would have produced an image with no wiki, and the GitHub fallback would have
masked that at runtime. Add a real path-containment check on assets now that
the path becomes a filesystem read rather than a URL, and document
TREK_WIKI_DIR as an off-by-default escape hatch across the deployment configs.
This commit is contained in:
jubnl
2026-07-13 23:11:59 +02:00
parent 59c2624fa9
commit 6c87bf2f7a
22 changed files with 359 additions and 39 deletions
+8 -5
View File
@@ -4,16 +4,17 @@ import {
getWikiIndex,
getWikiPage,
getWikiAsset,
isLocalWiki,
WikiNotFound,
type WikiPage,
type WikiNavSection,
} from '../../services/wikiService';
/**
* /api/help — embedded TREK wiki. Content is public docs (the wiki is public on
* GitHub), so these endpoints are unauthenticated; that also lets <img> tags load
* the proxied assets without sending credentials. All upstream calls go to the
* fixed TREK wiki path and are cached server-side.
* /api/help — embedded TREK wiki, served from the `wiki/` directory that ships
* with the app (see wikiService for the GitHub fallback). Content is public docs,
* so these endpoints are unauthenticated; that also lets <img> tags load the
* proxied assets without sending credentials.
*/
@Controller('api/help')
export class HelpController {
@@ -41,7 +42,9 @@ export class HelpController {
try {
const { buf, type } = await getWikiAsset(assetPath);
res.setHeader('Content-Type', type);
res.setHeader('Cache-Control', 'public, max-age=3600');
// Bundled assets are pinned to this build, so they can be cached hard; the
// GitHub fallback refreshes hourly, so match that TTL instead.
res.setHeader('Cache-Control', isLocalWiki() ? 'public, max-age=86400' : 'public, max-age=3600');
res.end(buf);
} catch {
res.status(404).end();
+1 -1
View File
@@ -1,7 +1,7 @@
import { Module } from '@nestjs/common';
import { HelpController } from './help.controller';
/** /api/help — embedded GitHub wiki (fetched + cached in wikiService). */
/** /api/help — the bundled `wiki/` directory, read via wikiService. */
@Module({
controllers: [HelpController],
})
+64 -29
View File
@@ -1,21 +1,41 @@
import path from 'path';
import { promises as fs } from 'fs';
import { existsSync, promises as fs } from 'fs';
/**
* In-app Help/Wiki content, sourced from the TREK GitHub wiki (kept in the repo
* under `wiki/**` and mirrored to the GitHub wiki on push to main). The server
* fetches the markdown from GitHub and caches it, so the embedded help stays in
* sync with wiki edits without a redeploy — and the client never talks to GitHub
* directly (images are proxied too). A bundled snapshot under server/assets/wiki
* is the cold-start / offline fallback.
* In-app Help/Wiki content, sourced from the `wiki/**` directory that ships with
* the app — the same content that CI mirrors to the public GitHub wiki. Reading
* from disk keeps the help pages pinned to the running version (a v1.2 install
* shows v1.2 docs, not whatever `main` says) and works offline.
*
* If that directory can't be resolved — an unusual layout, an image built without
* it — we fall back to fetching from the GitHub wiki over the network and caching
* hourly, so help degrades instead of disappearing. The client never talks to
* GitHub directly either way; images are proxied through /api/help/asset.
*/
const REPO = 'mauriceboe/TREK';
const RAW_BASE = `https://raw.githubusercontent.com/${REPO}/main/wiki`;
const TTL_MS = 60 * 60 * 1000; // refresh from GitHub at most hourly
const SNAPSHOT_DIR = path.join(__dirname, '..', '..', 'assets', 'wiki');
const TTL_MS = 60 * 60 * 1000; // remote fallback only: refresh from GitHub at most hourly
const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
/**
* `server/{src,dist}/services` both sit three levels under the repo root, so this
* one anchor resolves in dev, a built source install, vitest, and Docker (where
* the Dockerfile copies `wiki/` to /app/wiki). `process.cwd()` would not — Docker
* runs the server from /app/server.
*/
const WIKI_DIR = process.env.TREK_WIKI_DIR ?? path.join(__dirname, '..', '..', '..', 'wiki');
/**
* Probe for the sidebar rather than the bare directory: an empty or half-copied
* `wiki/` should fall back to GitHub, not serve an empty table of contents.
*/
const useLocalWiki = existsSync(path.join(WIKI_DIR, '_Sidebar.md'));
if (!useLocalWiki) {
console.warn(`[help] wiki not found at ${WIKI_DIR} — falling back to the GitHub wiki (help may not match this version)`);
}
export class WikiNotFound extends Error {
status = 404;
}
@@ -29,16 +49,26 @@ const assetCache = new Map<string, { buf: Buffer; type: string; ts: number }>();
const fresh = (ts: number): boolean => Date.now() - ts < TTL_MS;
async function readSnapshot(file: string): Promise<string | null> {
try {
return await fs.readFile(path.join(SNAPSHOT_DIR, file), 'utf8');
} catch {
return null;
}
/** Resolve a path inside the wiki dir, refusing anything that escapes it. */
function resolveInWiki(rel: string): string {
const root = path.resolve(WIKI_DIR);
const full = path.resolve(root, rel);
if (full !== root && !full.startsWith(root + path.sep)) throw new WikiNotFound(rel);
return full;
}
/** Fetch a wiki text file with cache → stale-cache → bundled-snapshot fallback. */
/** Fetch a wiki text file: local disk, or GitHub with cache → stale-cache fallback. */
async function fetchText(file: string): Promise<string> {
if (useLocalWiki) {
try {
return await fs.readFile(resolveInWiki(file), 'utf8');
} catch (err) {
if (err instanceof WikiNotFound) throw err;
if ((err as NodeJS.ErrnoException).code === 'ENOENT') throw new WikiNotFound(file);
throw err;
}
}
const cached = textCache.get(file);
if (cached && fresh(cached.ts)) return cached.data;
try {
@@ -53,14 +83,9 @@ async function fetchText(file: string): Promise<string> {
if (res.status === 404) throw new WikiNotFound(file);
} catch (err) {
if (err instanceof WikiNotFound) throw err;
// network/parse error — fall through to stale cache or snapshot
// network/parse error — fall through to stale cache
}
if (cached) return cached.data; // serve stale rather than fail
const snap = await readSnapshot(file);
if (snap != null) {
textCache.set(file, { data: snap, ts: Date.now() });
return snap;
}
throw new WikiNotFound(file);
}
@@ -128,6 +153,9 @@ export interface WikiPage {
markdown: string;
}
/** True when help is served from the bundled wiki rather than fetched from GitHub. */
export const isLocalWiki = (): boolean => useLocalWiki;
export async function getWikiIndex(): Promise<{ sections: WikiNavSection[] }> {
const md = await fetchText('_Sidebar.md');
return { sections: parseSidebar(md) };
@@ -148,7 +176,7 @@ const ASSET_TYPES: Record<string, string> = {
'.svg': 'image/svg+xml',
};
/** Proxy a wiki image so the browser never calls GitHub directly. */
/** Read a wiki image from disk, or proxy it from GitHub so the browser never calls it directly. */
export async function getWikiAsset(assetPath: string): Promise<{ buf: Buffer; type: string }> {
// Defend against traversal; allow nested image folders.
if (assetPath.includes('..') || !/^[A-Za-z0-9/._-]+$/.test(assetPath)) throw new WikiNotFound(assetPath);
@@ -156,6 +184,18 @@ export async function getWikiAsset(assetPath: string): Promise<{ buf: Buffer; ty
const type = ASSET_TYPES[ext];
if (!type) throw new WikiNotFound(assetPath);
if (useLocalWiki) {
try {
// resolveInWiki re-checks containment: the regex above is a filter, this is the boundary.
const buf = await fs.readFile(resolveInWiki(assetPath));
return { buf, type };
} catch (err) {
if (err instanceof WikiNotFound) throw err;
if ((err as NodeJS.ErrnoException).code === 'ENOENT') throw new WikiNotFound(assetPath);
throw err;
}
}
const cached = assetCache.get(assetPath);
if (cached && fresh(cached.ts)) return { buf: cached.buf, type: cached.type };
try {
@@ -171,10 +211,5 @@ export async function getWikiAsset(assetPath: string): Promise<{ buf: Buffer; ty
/* fall through */
}
if (cached) return { buf: cached.buf, type: cached.type };
try {
const buf = await fs.readFile(path.join(SNAPSHOT_DIR, assetPath));
return { buf, type };
} catch {
throw new WikiNotFound(assetPath);
}
throw new WikiNotFound(assetPath);
}