Add backend jobs system with built-in tasks and TOML-based configuration parsing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9647ac8c50
commit
1f6d41ab06
27 files changed
+1590
-25
No files matched your search
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "@homepage/indexer",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": "./src/index.ts",
|
||||
"dependencies": {
|
||||
"marked": "^18.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from './walk.ts';
|
||||
export * from './render.ts';
|
||||
export * from './site.ts';
|
||||
@@ -0,0 +1,164 @@
|
||||
import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { renderMarkdown, renderText } from './render.ts';
|
||||
import { buildSite, reservedNames, type Site } from './site.ts';
|
||||
import { buildIndex, type WalkOptions } from './walk.ts';
|
||||
|
||||
const LEGAL = new Map([['impressum', 'impressum.txt']]);
|
||||
|
||||
function options(overrides: Partial<WalkOptions> = {}): WalkOptions {
|
||||
return { maxFileBytes: 1024, maxTotalBytes: 4096, maxEntries: 100, reserved: reservedNames(LEGAL), ...overrides };
|
||||
}
|
||||
|
||||
function write(root: string, files: Record<string, string>): void
|
||||
{
|
||||
for (const [path, content] of Object.entries(files))
|
||||
{
|
||||
mkdirSync(join(root, path, '..'), { recursive: true });
|
||||
writeFileSync(join(root, path), content);
|
||||
}
|
||||
}
|
||||
|
||||
const text = (site: Site, path: string) => site.pages.get(path)?.body.toString();
|
||||
|
||||
describe('buildIndex', () => {
|
||||
let root: string;
|
||||
let outside: string;
|
||||
|
||||
beforeEach(() =>
|
||||
{
|
||||
root = mkdtempSync(join(tmpdir(), 'content-'));
|
||||
outside = mkdtempSync(join(tmpdir(), 'outside-'));
|
||||
write(outside, { 'secret.txt': 'host secret' });
|
||||
write(root, {
|
||||
'about.txt': 'about me',
|
||||
'subdomains/git.example.org/README': 'gitea',
|
||||
'.env': 'TOKEN=1',
|
||||
'.git/config': 'repo',
|
||||
'subdomains/.hidden': 'hidden',
|
||||
});
|
||||
});
|
||||
|
||||
it('lists files and directories in order', async () => {
|
||||
const index = await buildIndex(root, options());
|
||||
|
||||
expect([...index.entries.keys()]).toEqual(['', 'about.txt', 'subdomains', 'subdomains/git.example.org', 'subdomains/git.example.org/README']);
|
||||
expect(index.entries.get('about.txt')?.content?.toString()).toBe('about me');
|
||||
});
|
||||
|
||||
it('never follows symlinks, inside or outside the root', async () => {
|
||||
symlinkSync(join(outside, 'secret.txt'), join(root, 'leak.txt'));
|
||||
symlinkSync(outside, join(root, 'leakdir'));
|
||||
symlinkSync(join(root, 'about.txt'), join(root, 'alias.txt'));
|
||||
|
||||
const index = await buildIndex(root, options());
|
||||
expect([...index.entries.keys()].filter((path) => /leak|alias/.test(path))).toEqual([]);
|
||||
});
|
||||
|
||||
it('skips dotfiles and dot directories everywhere', async () => {
|
||||
const index = await buildIndex(root, options());
|
||||
expect([...index.entries.keys()].some((path) => path.split('/').some((part) => part.startsWith('.')))).toBe(false);
|
||||
});
|
||||
|
||||
it('skips top level names reserved for the site', async () => {
|
||||
write(root, { 'raw/x': 'x', 'impressum': 'collides', 'sitemap.xml': 'x', 'deep/raw': 'fine' });
|
||||
const index = await buildIndex(root, options());
|
||||
|
||||
expect(index.entries.has('raw')).toBe(false);
|
||||
expect(index.entries.has('impressum')).toBe(false);
|
||||
expect(index.entries.has('deep/raw')).toBe(true);
|
||||
expect(index.warnings).toContain('"impressum" is skipped because the name is reserved for the site itself');
|
||||
});
|
||||
|
||||
it('lists but does not load files above the limits', async () => {
|
||||
write(root, { 'big.bin': 'x'.repeat(2000) });
|
||||
const index = await buildIndex(root, options());
|
||||
|
||||
expect(index.entries.get('big.bin')?.content).toBeUndefined();
|
||||
expect(index.warnings.join('\n')).toContain('big.bin is listed but not served');
|
||||
});
|
||||
|
||||
it('changes its hash when content changes', async () => {
|
||||
const before = (await buildIndex(root, options())).hash;
|
||||
write(root, { 'about.txt': 'about someone else' });
|
||||
expect((await buildIndex(root, options())).hash).not.toBe(before);
|
||||
});
|
||||
|
||||
it('survives a missing content directory', async () => {
|
||||
const index = await buildIndex(join(root, 'missing'), options());
|
||||
|
||||
expect([...index.entries.keys()]).toEqual(['']);
|
||||
expect(index.warnings[0]).toContain('cannot be read');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildSite', () => {
|
||||
let site: Site;
|
||||
|
||||
beforeEach(async () =>
|
||||
{
|
||||
const root = mkdtempSync(join(tmpdir(), 'site-'));
|
||||
write(root, {
|
||||
'about.md': '# About\n\n<script>alert(1)</script>\n\n[bad](javascript:alert(1)) [good](https://example.org)',
|
||||
'page.html': '<script>alert(1)</script>',
|
||||
'logo.svg': '<svg onload="alert(1)"></svg>',
|
||||
'links/github.txt': 'https://github.com/example',
|
||||
'spaced name.txt': 'x',
|
||||
'impressum.txt': 'Max Mustermann',
|
||||
});
|
||||
site = buildSite(await buildIndex(root, options()), { siteUrl: 'https://security-command.org/', legal: LEGAL });
|
||||
});
|
||||
|
||||
it('serves listings, file pages and the root listing at /ls', () => {
|
||||
expect(text(site, '/ls')).toContain('<a href="/links">links/</a>');
|
||||
expect(text(site, '/links')).toContain('<a href="/links/github.txt">github.txt</a>');
|
||||
expect(text(site, '/links/github.txt')).toContain('<a href="https://github.com/example">');
|
||||
expect(text(site, '/ls')).toContain('href="/spaced%20name.txt"');
|
||||
expect(site.pages.has('/spaced name.txt')).toBe(true);
|
||||
});
|
||||
|
||||
it('escapes raw HTML and neutralizes script links in markdown', () => {
|
||||
const page = text(site, '/about.md')!;
|
||||
|
||||
expect(page).toContain('<h1>About</h1>');
|
||||
expect(page).not.toContain('<script>');
|
||||
expect(page).toContain('<script>');
|
||||
expect(page).toContain('<a href="#">bad</a>');
|
||||
expect(page).toContain('<a href="https://example.org">good</a>');
|
||||
});
|
||||
|
||||
it('serves raw HTML and SVG as sandboxed plain text', () => {
|
||||
for (const path of ['/raw/page.html', '/raw/logo.svg'])
|
||||
{
|
||||
const page = site.pages.get(path)!;
|
||||
expect(page.type).toBe('text/plain; charset=utf-8');
|
||||
expect(page.headers['Content-Security-Policy']).toContain('sandbox');
|
||||
}
|
||||
});
|
||||
|
||||
it('renders legal pages from their content files', () => {
|
||||
expect(text(site, '/impressum')).toContain('Max Mustermann');
|
||||
});
|
||||
|
||||
it('lists every page in the sitemap and points robots.txt at it', () => {
|
||||
const sitemap = text(site, '/sitemap.xml')!;
|
||||
|
||||
expect(sitemap).toContain('<loc>https://security-command.org/</loc>');
|
||||
expect(sitemap).toContain('<loc>https://security-command.org/ls</loc>');
|
||||
expect(sitemap).toContain('<loc>https://security-command.org/spaced%20name.txt</loc>');
|
||||
expect(sitemap).toContain('<loc>https://security-command.org/impressum</loc>');
|
||||
expect(text(site, '/robots.txt')).toContain('Sitemap: https://security-command.org/sitemap.xml');
|
||||
});
|
||||
});
|
||||
|
||||
describe('render helpers', () => {
|
||||
it('links only web addresses in plain text', () => {
|
||||
expect(renderText('see https://a.example/x. and <b>')).toBe('see <a href="https://a.example/x">https://a.example/x</a>. and <b>');
|
||||
});
|
||||
|
||||
it('keeps mail links in markdown', () => {
|
||||
expect(renderMarkdown('[mail](mailto:a@b.c)')).toContain('href="mailto:a@b.c"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { Marked, type Tokens } from 'marked';
|
||||
import type { Entry } from './walk.ts';
|
||||
|
||||
export type Link = { label: string; href: string };
|
||||
|
||||
const SAFE_SCHEME = /^(https?|mailto):/i;
|
||||
const ANY_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
|
||||
|
||||
export function escapeHtml(text: string): string
|
||||
{
|
||||
return text
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
/** Encodes every segment of a content path for use in a URL. */
|
||||
export function urlPath(path: string): string {
|
||||
return path.split('/').map(encodeURIComponent).join('/');
|
||||
}
|
||||
|
||||
function safeHref(href: string): string {
|
||||
return ANY_SCHEME.test(href) && !SAFE_SCHEME.test(href) ? '#' : href;
|
||||
}
|
||||
|
||||
/**
|
||||
* Markdown with raw HTML shown as text and only web and mail links, because
|
||||
* jobs may write content from outside sources into the directory.
|
||||
*/
|
||||
const markdown = new Marked({
|
||||
gfm: true,
|
||||
renderer: { html: ({ text }: Tokens.HTML | Tokens.Tag) => escapeHtml(text) },
|
||||
walkTokens: (token) =>
|
||||
{
|
||||
if (token.type === 'link' || token.type === 'image') token.href = safeHref(token.href);
|
||||
},
|
||||
});
|
||||
|
||||
export function renderMarkdown(text: string): string {
|
||||
return markdown.parse(text, { async: false });
|
||||
}
|
||||
|
||||
/** Escapes text and turns plain web addresses into links, like the terminal does. */
|
||||
export function renderText(text: string): string {
|
||||
return escapeHtml(text).replace(/https?:\/\/[^\s<>"']+[^\s<>"'.,;:!?)\]]/g, (url) => `<a href="${url}">${url}</a>`);
|
||||
}
|
||||
|
||||
function formatSize(bytes: number): string
|
||||
{
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} K`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} M`;
|
||||
}
|
||||
|
||||
export function renderListing(entry: Entry, children: Entry[]): string
|
||||
{
|
||||
const rows = children.map((child) =>
|
||||
{
|
||||
const name = escapeHtml(child.name) + (child.kind === 'dir' ? '/' : '');
|
||||
const size = child.kind === 'dir' ? '' : formatSize(child.size);
|
||||
return `<tr><td><a href="/${urlPath(child.path)}">${name}</a></td><td class="size">${size}</td><td>${child.modified.toISOString().slice(0, 10)}</td></tr>`;
|
||||
});
|
||||
|
||||
if (rows.length === 0) return '<p class="muted">This directory is empty.</p>';
|
||||
return `<table><tbody>\n${rows.join('\n')}\n</tbody></table>`;
|
||||
}
|
||||
|
||||
const IMAGE = /\.(png|jpe?g|gif|webp|avif)$/i;
|
||||
|
||||
export function renderFile(entry: Entry): string
|
||||
{
|
||||
const raw = `/raw/${urlPath(entry.path)}`;
|
||||
|
||||
if (!entry.content) return `<p class="muted">This file is too large to show. <a href="${raw}">Download it</a>.</p>`;
|
||||
if (IMAGE.test(entry.name)) return `<p><img src="${raw}" alt="${escapeHtml(entry.name)}"></p>`;
|
||||
if (!isText(entry.content)) return `<p class="muted">Binary file. <a href="${raw}">Download it</a>.</p>`;
|
||||
|
||||
const text = entry.content.toString('utf8');
|
||||
if (/\.md$/i.test(entry.name)) return `<article class="markdown">${renderMarkdown(text)}</article>`;
|
||||
return `<pre>${renderText(text)}</pre>`;
|
||||
}
|
||||
|
||||
/** Treats content without NUL bytes that decodes as UTF-8 as text. The sample may end inside a character. */
|
||||
export function isText(content: Buffer): boolean
|
||||
{
|
||||
const sample = content.subarray(0, 8192);
|
||||
if (sample.includes(0)) return false;
|
||||
|
||||
try { new TextDecoder('utf-8', { fatal: true }).decode(sample, { stream: true }); }
|
||||
catch { return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
const STYLE = `
|
||||
:root { color-scheme: dark; --bg: #0b0d10; --text: #d6dde6; --muted: #7d8794; --accent: #7ee787; --border: #1f262e; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; background: var(--bg); color: var(--text); font: 15px/1.6 "JetBrains Mono", ui-monospace, monospace; }
|
||||
header, main, footer { max-width: 60rem; margin: 0 auto; padding: 0.75rem 1rem; }
|
||||
header { display: flex; flex-wrap: wrap; gap: 0.5rem 1rem; justify-content: space-between; border-bottom: 1px solid var(--border); font-size: 0.85rem; }
|
||||
header .site { color: var(--accent); }
|
||||
nav a { margin-left: 0.75rem; }
|
||||
a { color: var(--accent); }
|
||||
.crumbs { color: var(--muted); }
|
||||
.muted, .size { color: var(--muted); }
|
||||
pre { white-space: pre-wrap; word-break: break-word; }
|
||||
table { border-collapse: collapse; width: 100%; }
|
||||
td { padding: 0.15rem 1.5rem 0.15rem 0; white-space: nowrap; }
|
||||
td:first-child { width: 100%; white-space: normal; }
|
||||
img { max-width: 100%; }
|
||||
.markdown code, .markdown pre { background: #12161b; }
|
||||
`;
|
||||
|
||||
export type PageOptions = {
|
||||
title: string;
|
||||
description: string;
|
||||
crumbs: Link[];
|
||||
body: string;
|
||||
nav: Link[];
|
||||
};
|
||||
|
||||
export function renderPage(options: PageOptions): string
|
||||
{
|
||||
const crumbs = options.crumbs.map((crumb) => `<a href="${crumb.href}">${escapeHtml(crumb.label)}</a>`).join(' / ');
|
||||
const nav = options.nav.map((link) => `<a href="${link.href}">${escapeHtml(link.label)}</a>`).join('');
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="dark">
|
||||
<title>${escapeHtml(options.title)}</title>
|
||||
<meta name="description" content="${escapeHtml(options.description)}">
|
||||
<meta property="og:title" content="${escapeHtml(options.title)}">
|
||||
<meta property="og:description" content="${escapeHtml(options.description)}">
|
||||
<style>${STYLE}</style>
|
||||
</head>
|
||||
<body>
|
||||
<header><a class="site" href="/">security-command.org</a><nav>${nav}</nav></header>
|
||||
<main>
|
||||
<p class="crumbs">${crumbs}</p>
|
||||
${options.body}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { escapeHtml, isText, renderFile, renderListing, renderPage, urlPath, type Link } from './render.ts';
|
||||
import type { ContentIndex, Entry } from './walk.ts';
|
||||
|
||||
export type SitePage = {
|
||||
body: Buffer;
|
||||
type: string;
|
||||
headers: Record<string, string>;
|
||||
};
|
||||
|
||||
export type Site = {
|
||||
pages: Map<string, SitePage>;
|
||||
hash: string;
|
||||
};
|
||||
|
||||
export type SiteOptions = {
|
||||
/** Absolute URL of the site, used by the sitemap. */
|
||||
siteUrl: string;
|
||||
/** Route name to content file, for example impressum to impressum.txt. */
|
||||
legal: Map<string, string>;
|
||||
};
|
||||
|
||||
const RESERVED = ['ws', 'raw', 'ls', 'healthz', 'assets', 'index.html', 'sitemap.xml', 'robots.txt'];
|
||||
|
||||
/** Route names the content cannot use at its top level, including the legal pages. */
|
||||
export function reservedNames(legal: Map<string, string>): Set<string> {
|
||||
return new Set([...RESERVED, ...legal.keys()]);
|
||||
}
|
||||
|
||||
const RAW_TYPES: [RegExp, string][] = [
|
||||
[/\.png$/i, 'image/png'],
|
||||
[/\.jpe?g$/i, 'image/jpeg'],
|
||||
[/\.gif$/i, 'image/gif'],
|
||||
[/\.webp$/i, 'image/webp'],
|
||||
[/\.avif$/i, 'image/avif'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Raw files never run in the site's origin: text is served as plain text,
|
||||
* also for HTML and SVG, and a sandbox policy disables scripts entirely.
|
||||
*/
|
||||
const RAW_HEADERS = { 'Content-Security-Policy': "sandbox; default-src 'none'; img-src 'self'" };
|
||||
|
||||
function rawPage(entry: Entry & { content: Buffer }): SitePage
|
||||
{
|
||||
const image = RAW_TYPES.find(([pattern]) => pattern.test(entry.name))?.[1];
|
||||
if (image) return { body: entry.content, type: image, headers: RAW_HEADERS };
|
||||
|
||||
if (isText(entry.content)) return { body: entry.content, type: 'text/plain; charset=utf-8', headers: RAW_HEADERS };
|
||||
|
||||
return {
|
||||
body: entry.content,
|
||||
type: 'application/octet-stream',
|
||||
headers: { ...RAW_HEADERS, 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(entry.name)}` },
|
||||
};
|
||||
}
|
||||
|
||||
function describe(entry: Entry): string
|
||||
{
|
||||
if (entry.kind === 'dir') return `Contents of /${entry.path || ''} on security-command.org.`;
|
||||
if (!entry.content || !isText(entry.content)) return `${entry.name} on security-command.org.`;
|
||||
|
||||
const text = entry.content.toString('utf8').replace(/[#*_`>\[\]()]/g, '').replace(/\s+/g, ' ').trim();
|
||||
return text.length > 160 ? `${text.slice(0, 157)}...` : text;
|
||||
}
|
||||
|
||||
function crumbs(entry: Entry): Link[]
|
||||
{
|
||||
const parts = entry.path ? entry.path.split('/') : [];
|
||||
return [
|
||||
{ label: '~', href: '/ls' },
|
||||
...parts.map((label, index) => ({ label, href: `/${urlPath(parts.slice(0, index + 1).join('/'))}` })),
|
||||
];
|
||||
}
|
||||
|
||||
/** Builds every static route from the index. Paths are decoded, with a leading slash and no trailing one. */
|
||||
export function buildSite(index: ContentIndex, options: SiteOptions): Site
|
||||
{
|
||||
const pages = new Map<string, SitePage>();
|
||||
const nav: Link[] = [
|
||||
{ label: 'terminal', href: '/' },
|
||||
{ label: 'ls', href: '/ls' },
|
||||
...[...options.legal.keys()].map((route) => ({ label: route, href: `/${route}` })),
|
||||
];
|
||||
|
||||
const html = (title: string, description: string, entryCrumbs: Link[], body: string): SitePage => ({
|
||||
body: Buffer.from(renderPage({ title, description, crumbs: entryCrumbs, body, nav })),
|
||||
type: 'text/html; charset=utf-8',
|
||||
headers: {},
|
||||
});
|
||||
|
||||
for (const entry of index.entries.values())
|
||||
{
|
||||
const title = `${entry.path ? `/${entry.path}` : '~'} · security-command.org`;
|
||||
const route = entry.path ? `/${entry.path}` : '/ls';
|
||||
|
||||
if (entry.kind === 'dir')
|
||||
{
|
||||
const children = (entry.children ?? []).map((path) => index.entries.get(path)!);
|
||||
pages.set(route, html(title, describe(entry), crumbs(entry), renderListing(entry, children)));
|
||||
continue;
|
||||
}
|
||||
|
||||
pages.set(route, html(title, describe(entry), crumbs(entry), renderFile(entry)));
|
||||
if (entry.content) pages.set(`/raw/${entry.path}`, rawPage(entry as Entry & { content: Buffer }));
|
||||
}
|
||||
|
||||
for (const [routeName, file] of options.legal)
|
||||
{
|
||||
const entry = index.entries.get(file);
|
||||
const body = entry?.kind === 'file'
|
||||
? renderFile(entry)
|
||||
: `<p class="muted">${escapeHtml(file)} is missing from the content directory.</p>`;
|
||||
pages.set(`/${routeName}`, html(`${routeName} · security-command.org`, `${routeName} of security-command.org.`, [], body));
|
||||
}
|
||||
|
||||
const base = options.siteUrl.replace(/\/$/, '');
|
||||
const urls: [string, Date | undefined][] = [
|
||||
['/', undefined],
|
||||
...[...index.entries.values()].map((entry): [string, Date] => [entry.path ? `/${urlPath(entry.path)}` : '/ls', entry.modified]),
|
||||
...[...options.legal].map(([route, file]): [string, Date | undefined] => [`/${route}`, index.entries.get(file)?.modified]),
|
||||
];
|
||||
|
||||
const sitemap = [
|
||||
'<?xml version="1.0" encoding="UTF-8"?>',
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
|
||||
...urls.map(([url, modified]) =>
|
||||
`<url><loc>${escapeHtml(base + url)}</loc>${modified ? `<lastmod>${modified.toISOString().slice(0, 10)}</lastmod>` : ''}</url>`),
|
||||
'</urlset>',
|
||||
'',
|
||||
].join('\n');
|
||||
pages.set('/sitemap.xml', { body: Buffer.from(sitemap), type: 'application/xml; charset=utf-8', headers: {} });
|
||||
|
||||
const robots = ['User-agent: *', 'Disallow: /ws', 'Disallow: /raw/', `Sitemap: ${base}/sitemap.xml`, ''].join('\n');
|
||||
pages.set('/robots.txt', { body: Buffer.from(robots), type: 'text/plain; charset=utf-8', headers: {} });
|
||||
|
||||
return { pages, hash: index.hash };
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { lstat, readdir, readFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
|
||||
export type Entry = {
|
||||
/** Path relative to the content root with forward slashes; the root itself is "". */
|
||||
path: string;
|
||||
name: string;
|
||||
kind: 'file' | 'dir';
|
||||
size: number;
|
||||
modified: Date;
|
||||
/** Missing for directories and for files above the size limit. */
|
||||
content?: Buffer;
|
||||
children?: string[];
|
||||
};
|
||||
|
||||
export type ContentIndex = {
|
||||
entries: Map<string, Entry>;
|
||||
hash: string;
|
||||
warnings: string[];
|
||||
};
|
||||
|
||||
export type WalkOptions = {
|
||||
maxFileBytes: number;
|
||||
maxTotalBytes: number;
|
||||
maxEntries: number;
|
||||
/** Top level names that would collide with the app's own routes. */
|
||||
reserved: Set<string>;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
/**
|
||||
* Indexes the content directory. Symlinks are never followed, because the
|
||||
* walk runs on the host side and a link could point anywhere; dotfiles are
|
||||
* skipped so that things like .git or .env never become public.
|
||||
*/
|
||||
export async function buildIndex(root: string, options: WalkOptions): Promise<ContentIndex>
|
||||
{
|
||||
const entries = new Map<string, Entry>();
|
||||
const warnings: string[] = [];
|
||||
const hash = createHash('sha256');
|
||||
let total = 0;
|
||||
|
||||
async function visit(path: string, absolute: string): Promise<Entry | undefined>
|
||||
{
|
||||
options.signal?.throwIfAborted();
|
||||
|
||||
const stats = await lstat(absolute);
|
||||
const name = path.split('/').at(-1) ?? '';
|
||||
|
||||
if (stats.isSymbolicLink()) return undefined;
|
||||
if (entries.size >= options.maxEntries)
|
||||
{
|
||||
warnings.push(`stopped at ${options.maxEntries} entries, ${path} and later ones are missing`);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (stats.isDirectory())
|
||||
{
|
||||
const entry: Entry = { path, name, kind: 'dir', size: 0, modified: stats.mtime, children: [] };
|
||||
entries.set(path, entry);
|
||||
hash.update(`d\0${path}\0`);
|
||||
|
||||
const names = (await readdir(absolute)).filter((child) => !child.startsWith('.')).sort((a, b) => a.localeCompare(b, 'en'));
|
||||
for (const child of names)
|
||||
{
|
||||
if (path === '' && options.reserved.has(child))
|
||||
{
|
||||
warnings.push(`"${child}" is skipped because the name is reserved for the site itself`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const visited = await visit(path ? `${path}/${child}` : child, join(absolute, child));
|
||||
if (visited) entry.children!.push(visited.path);
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
if (!stats.isFile()) return undefined;
|
||||
|
||||
const entry: Entry = { path, name, kind: 'file', size: stats.size, modified: stats.mtime };
|
||||
if (stats.size > options.maxFileBytes)
|
||||
{
|
||||
warnings.push(`${path} is listed but not served, it is larger than ${options.maxFileBytes} bytes`);
|
||||
}
|
||||
else if (total + stats.size > options.maxTotalBytes)
|
||||
{
|
||||
warnings.push(`${path} is listed but not served, the content exceeds ${options.maxTotalBytes} bytes in total`);
|
||||
}
|
||||
else
|
||||
{
|
||||
entry.content = await readFile(absolute);
|
||||
total += entry.content.length;
|
||||
}
|
||||
|
||||
entries.set(path, entry);
|
||||
hash.update(`f\0${path}\0`);
|
||||
hash.update(entry.content ?? `${stats.size}:${stats.mtimeMs}`);
|
||||
return entry;
|
||||
}
|
||||
|
||||
try { await visit('', root); }
|
||||
catch (error)
|
||||
{
|
||||
if (options.signal?.aborted) throw error;
|
||||
warnings.push(`the content directory cannot be read: ${(error as Error).message}`);
|
||||
}
|
||||
|
||||
if (!entries.has('')) entries.set('', { path: '', name: '', kind: 'dir', size: 0, modified: new Date(0), children: [] });
|
||||
return { entries, hash: hash.digest('hex').slice(0, 16), warnings };
|
||||
}
|
||||
Reference in new issue
Block a user