Add support for multilingual legal pages with English aliases, dynamic link replacement in headers, and redirections for alias routes. Update tests, configs, and frontend assets accordingly.
This commit is contained in:
1 parent
5f3ff481b4
commit
5305687f98
16 files changed
+151
-39
No files matched your search
@@ -2,7 +2,7 @@ import { mkdtempSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { readTheme } from './assets.ts';
|
||||
import { readTheme, setLegalLinks, type Asset } from './assets.ts';
|
||||
|
||||
describe('readTheme', () => {
|
||||
const base = Buffer.from(':root { --text: white; }');
|
||||
@@ -19,3 +19,26 @@ describe('readTheme', () => {
|
||||
expect(await readTheme(undefined, '/nonexistent/theme.css')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('setLegalLinks', () => {
|
||||
const page = (): Map<string, Asset> =>
|
||||
{
|
||||
const index = { body: Buffer.from('<header><nav><a href="/impressum">impressum</a></nav></header>'), type: 'text/html', immutable: false };
|
||||
return new Map([['/index.html', index], ['/', index]]);
|
||||
};
|
||||
|
||||
it('links only the configured legal pages, with their English names', () => {
|
||||
const assets = page();
|
||||
setLegalLinks(assets, [{ route: 'datenschutz', aliases: ['privacy'], file: 'datenschutz.md' }]);
|
||||
|
||||
expect(assets.get('/')?.body.toString()).toBe('<header><nav><a href="/datenschutz" data-en="privacy">datenschutz</a></nav></header>');
|
||||
expect(assets.get('/index.html')).toBe(assets.get('/'));
|
||||
});
|
||||
|
||||
it('leaves the header empty without legal pages', () => {
|
||||
const assets = page();
|
||||
setLegalLinks(assets, []);
|
||||
|
||||
expect(assets.get('/')?.body.toString()).toBe('<header><nav></nav></header>');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { extname, join, relative, sep } from 'node:path';
|
||||
import type { Font } from '@homepage/indexer';
|
||||
import { escapeHtml, type Font, type LegalPage } from '@homepage/indexer';
|
||||
|
||||
export type Asset = {
|
||||
body: Buffer;
|
||||
@@ -53,6 +53,27 @@ export function loadAssets(directory: string): Map<string, Asset>
|
||||
return assets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the configured legal pages into the header of the terminal page,
|
||||
* which the frontend build cannot know. Without legal pages the header has no links.
|
||||
*/
|
||||
export function setLegalLinks(assets: Map<string, Asset>, legal: LegalPage[]): void
|
||||
{
|
||||
const index = assets.get('/index.html');
|
||||
if (!index) return;
|
||||
|
||||
const links = legal.map((page) =>
|
||||
{
|
||||
const english = page.aliases[0] ? ` data-en="${escapeHtml(page.aliases[0])}"` : '';
|
||||
return `<a href="/${escapeHtml(page.route)}"${english}>${escapeHtml(page.route)}</a>`;
|
||||
});
|
||||
|
||||
const html = index.body.toString('utf8').replace(/<nav>[\s\S]*?<\/nav>/, `<nav>${links.join('<span aria-hidden="true">·</span>')}</nav>`);
|
||||
const asset = { ...index, body: Buffer.from(html) };
|
||||
assets.set('/index.html', asset);
|
||||
assets.set('/', asset);
|
||||
}
|
||||
|
||||
const FONT = /^\/assets\/jetbrains-mono-latin-(400|700)-normal-[^/]+\.woff2$/;
|
||||
|
||||
/** The Latin JetBrains Mono files of the frontend, so the static pages use the same font. */
|
||||
|
||||
@@ -27,7 +27,7 @@ function setup()
|
||||
contentDir: content,
|
||||
statusDir: status,
|
||||
siteUrl: 'https://security-command.org',
|
||||
legalPages: new Map([['impressum', 'impressum.txt']]),
|
||||
legalPages: [{ route: 'impressum', aliases: ['imprint'], file: 'impressum.txt' }],
|
||||
build: 'abc1234',
|
||||
} as BackendConfig;
|
||||
|
||||
|
||||
+15
-11
@@ -1,3 +1,5 @@
|
||||
import type { LegalPage } from '@homepage/indexer';
|
||||
|
||||
export type BackendConfig = {
|
||||
host: string;
|
||||
port: number;
|
||||
@@ -13,8 +15,8 @@ export type BackendConfig = {
|
||||
themeFile: string;
|
||||
/** Absolute URL of the site, for the sitemap. */
|
||||
siteUrl: string;
|
||||
/** Route name to content file, from LEGAL_PAGES like "impressum:impressum.txt". */
|
||||
legalPages: Map<string, string>;
|
||||
/** From LEGAL_PAGES like "impressum/imprint:impressum.md": the German route, English aliases and the content file. */
|
||||
legalPages: LegalPage[];
|
||||
/** Directory for the status file shown in sandboxes; empty disables it. */
|
||||
statusDir: string;
|
||||
build: string;
|
||||
@@ -41,16 +43,18 @@ function list(value: string | undefined): string[] {
|
||||
return (value ?? '').split(',').map((entry) => entry.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
function legalPages(value: string): Map<string, string>
|
||||
function legalPages(value: string): LegalPage[]
|
||||
{
|
||||
const pages = new Map<string, string>();
|
||||
for (const pair of list(value))
|
||||
return list(value).map((entry) =>
|
||||
{
|
||||
const [route = '', file = ''] = pair.split(':');
|
||||
if (!/^[a-z0-9-]+$/.test(route) || !file) throw new Error(`LEGAL_PAGES entry "${pair}" must look like route:file`);
|
||||
pages.set(route, file);
|
||||
}
|
||||
return pages;
|
||||
const [routes = '', file = ''] = entry.split(':');
|
||||
const [route = '', ...aliases] = routes.split('/');
|
||||
if (![route, ...aliases].every((name) => /^[a-z0-9-]+$/.test(name)) || !file)
|
||||
{
|
||||
throw new Error(`LEGAL_PAGES entry "${entry}" must look like route/alias:file`);
|
||||
}
|
||||
return { route, aliases, file };
|
||||
});
|
||||
}
|
||||
|
||||
export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
|
||||
@@ -66,7 +70,7 @@ export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
|
||||
triggerDir: env.TRIGGER_DIR ?? '',
|
||||
themeFile: env.THEME_FILE ?? '/config/theme.css',
|
||||
siteUrl: env.SITE_URL ?? 'https://security-command.org',
|
||||
legalPages: legalPages(env.LEGAL_PAGES ?? 'impressum:impressum.txt,datenschutz:datenschutz.txt'),
|
||||
legalPages: legalPages(env.LEGAL_PAGES ?? 'impressum/imprint:impressum.md,datenschutz/privacy:datenschutz.md'),
|
||||
statusDir: env.STATUS_DIR ?? '',
|
||||
build: env.BUILD_SHA ?? 'dev',
|
||||
allowedOrigins: list(env.ALLOWED_ORIGINS),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Site } from '@homepage/indexer';
|
||||
import { watchTree, watchTriggers } from '@homepage/jobs';
|
||||
import { SpawnerClient } from '@homepage/protocol';
|
||||
import { loadAssets, readTheme, siteFonts } from './assets.ts';
|
||||
import { loadAssets, readTheme, setLegalLinks, siteFonts } from './assets.ts';
|
||||
import { createBuiltins } from './builtins.ts';
|
||||
import { loadConfig } from './config.ts';
|
||||
import { SessionHub } from './hub.ts';
|
||||
@@ -18,6 +18,7 @@ const spawner = new SpawnerClient(config.spawnerSocket);
|
||||
|
||||
const assets = loadAssets(config.frontendDir);
|
||||
if (assets.size === 0) log(`no frontend found in ${config.frontendDir}`);
|
||||
setLegalLinks(assets, config.legalPages);
|
||||
|
||||
let site: Site | undefined;
|
||||
let jobs: BackendJobs | undefined;
|
||||
|
||||
@@ -21,6 +21,7 @@ const SITE: Site = {
|
||||
['/ls', { body: Buffer.from('<p>listing</p>'), type: 'text/html; charset=utf-8', headers: {} }],
|
||||
['/spaced name.txt', { body: Buffer.from('<p>page</p>'), type: 'text/html; charset=utf-8', headers: {} }],
|
||||
['/raw/page.html', { body: Buffer.from('<script>'), type: 'text/plain; charset=utf-8', headers: { 'Content-Security-Policy': 'sandbox' } }],
|
||||
['/imprint', { body: Buffer.alloc(0), type: 'text/plain; charset=utf-8', headers: { Location: '/impressum' }, status: 301 }],
|
||||
]),
|
||||
};
|
||||
|
||||
@@ -93,7 +94,7 @@ describe('backend', () => {
|
||||
triggerDir: '',
|
||||
themeFile: '',
|
||||
siteUrl: 'https://security-command.org',
|
||||
legalPages: new Map(),
|
||||
legalPages: [],
|
||||
statusDir: '',
|
||||
build: 'test',
|
||||
allowedOrigins: ['https://security-command.org'],
|
||||
@@ -422,6 +423,12 @@ describe('backend', () => {
|
||||
expect((await http('/%E0%A4%A')).status).toBe(404);
|
||||
});
|
||||
|
||||
it('redirects aliases of legal pages', async () => {
|
||||
const response = await fetch(url.replace('ws://', 'http://').replace('/ws', '/imprint'), { redirect: 'manual' });
|
||||
expect(response.status).toBe(301);
|
||||
expect(response.headers.get('location')).toBe('/impressum');
|
||||
});
|
||||
|
||||
it('serves the theme without caching it', async () => {
|
||||
const response = await http('/theme.css');
|
||||
expect(await response.text()).toBe(':root { --text: red; }');
|
||||
|
||||
@@ -95,6 +95,7 @@ export function createBackend(config: BackendConfig, hub: SessionHub, options: B
|
||||
|
||||
const current = site();
|
||||
const page = current && current.pages.get(sitePath(path) ?? '');
|
||||
if (page?.status) return send(response, page.status, page.type, page.body, page.headers, head);
|
||||
if (current && page)
|
||||
{
|
||||
// Every page changes together with the content, so the content hash is a valid ETag for all of them.
|
||||
|
||||
@@ -10,14 +10,15 @@
|
||||
<link rel="icon" href="/icon-192.png" sizes="192x192" type="image/png" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<link rel="stylesheet" href="/theme.css" />
|
||||
<script src="/labels.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<header class="bar">
|
||||
<span class="site">security-command.org</span>
|
||||
<nav>
|
||||
<a href="/impressum">impressum</a>
|
||||
<a href="/impressum" data-en="imprint">impressum</a>
|
||||
<span aria-hidden="true">·</span>
|
||||
<a href="/datenschutz">datenschutz</a>
|
||||
<a href="/datenschutz" data-en="privacy">datenschutz</a>
|
||||
</nav>
|
||||
</header>
|
||||
<div id="notice" class="notice" role="status" aria-live="polite" hidden></div>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
// The legal pages keep their German names for German visitors. Everyone else
|
||||
// sees the English names that data-en holds; the links stay the same.
|
||||
const language = (navigator.languages && navigator.languages[0]) || navigator.language || 'en';
|
||||
|
||||
if (!/^de\b/i.test(language))
|
||||
{
|
||||
for (const link of document.querySelectorAll('a[data-en]')) link.textContent = link.dataset.en;
|
||||
}
|
||||
Reference in new issue
Block a user