release: v0.18.0 (#725)
Release v0.18.0 — merges `dev` into `main`. ## Thanks - [@lancetm714](https://github.com/lancetm714) for the accent-contrast fix (#680 → #724). - [@RichKidsDev](https://github.com/RichKidsDev) for reporting the outdated Impressum (#697). ### Security - **Journal drafts and password-protected entries no longer render publicly as a subpage essay** ([#684](https://github.com/ralksta/immich-folio/pull/684), [GHSA-987w-cpwm-c9g9](https://github.com/ralksta/immich-folio/security/advisories/GHSA-987w-cpwm-c9g9), medium). A subpage's `essayFile` read the journal entry straight from disk, skipping the draft and password rules `/journal/<slug>` applies. It now resolves through the same rules: a draft reads as missing for visitors, and a protected entry shows its password gate, sharing the `lb_auth_journal_<slug>` cookie. - **Immich descriptions are escaped in generated subpage essays** ([#684](https://github.com/ralksta/immich-folio/pull/684), [GHSA-8ppx-39jv-q5xm](https://github.com/ralksta/immich-folio/security/advisories/GHSA-8ppx-39jv-q5xm), low). The essay built from a subpage's albums (`layout: essay` without markdown) put each asset's Immich description into the page as raw HTML. Captions are now HTML-escaped, and they go through `assetCaption()`, so `exif.caption: false` is respected there as well. Tracked in [#689](https://github.com/ralksta/immich-folio/issues/689). - **Admin drafts no longer keep a typed password, and the contact form's email check runs in linear time** ([#727](https://github.com/ralksta/immich-folio/pull/727)). The admin's session drafts wrote a password as typed to `sessionStorage`; a draft holding a plaintext password is now not kept (the unsaved-changes guard still warns). The email pattern could backtrack polynomially on a crafted domain; its labels now exclude the dot and the length is checked first. Both found by CodeQL before release. ### Added - **A built-in contact form with an inbox in the admin** ([#703](https://github.com/ralksta/immich-folio/pull/703), closes [#702](https://github.com/ralksta/immich-folio/issues/702)). `/contact` needs neither SMTP nor a form service: each message is one file in `content/messages/` (mode `0600`), read under the new _Messages_ tab, where _Reply by email_ opens the owner's mail client with the message quoted. Messages older than `contact.retentionDays` (default 90) are deleted. An optional ntfy push goes to `contact.notifyUrl` or `CONTACT_NOTIFY_URL`, and since [#709](https://github.com/ralksta/immich-folio/pull/709) it carries a fixed "new message" line and nothing about the sender — no name, no address, no text. Spam is kept out without a captcha: an off-screen honeypot, a minimum fill time, three submissions a minute per IP and a cap of 500 stored messages. With the Impressum on and no `legal.contactUrl`, the Impressum links the form as its second contact channel. A new doctor check warns when the form is on but nobody is notified. - **A privacy policy page, next to a list of what the site processes** ([#708](https://github.com/ralksta/immich-folio/pull/708)). `/privacy` renders `content/privacy.md`, edited under Settings → Legal, and the footer links it once the file has text; `privacy.enabled: false` hides it. Folio writes no legal text. Beside the editor it lists what _this_ installation does, read off the configuration — the map, statistics, contact form, password cookies, CDN — and marks every entry that involves a third party. _Insert headings_ adds the matching section headings and nothing else. The doctor warns while the Impressum is on and there is no policy. - **French, Spanish, Italian and Dutch interface translations** ([#681](https://github.com/ralksta/immich-folio/pull/681)), selected with `settings.yaml: lang` as before. The admin panel stays English. - **CDN mode for photos and videos** ([#681](https://github.com/ralksta/immich-folio/pull/681)). With `CDN_URL` set, image and video URLs point at a pull CDN whose origin is this server, so repeat views reach neither the server nor Immich. A site password switches the mode off, since a CDN would hand out cached photos without checking the unlock cookie. The CDN origin is added to the CSP, and a doctor check covers the password and `TRUSTED_PROXY_HOPS` cases. See `docs/deployment.md#cdn-mode`. - **A reworked admin panel** ([#712](https://github.com/ralksta/immich-folio/pull/712), [#713](https://github.com/ralksta/immich-folio/pull/713), [#714](https://github.com/ralksta/immich-folio/pull/714), [#716](https://github.com/ralksta/immich-folio/pull/716), [#717](https://github.com/ralksta/immich-folio/pull/717), [#718](https://github.com/ralksta/immich-folio/pull/718), [#719](https://github.com/ralksta/immich-folio/pull/719), [#721](https://github.com/ralksta/immich-folio/pull/721)): - **A sidebar instead of the header row**, grouped by task, with an unread count on Messages and a dot on Diagnostics while Immich is down. It collapses to an icon rail, with names shown on hover and focus, and remembers that per browser. - **`/admin` is an overview**: what needs attention (unread messages, doctor warnings), published pages, journal entries and recent views. - **The site's own visual language** — the preset's fonts, hairline borders, the square marker — and one page header on every screen. The accent is kept for the current place and the primary action; switches are now pills reading ON or OFF, in green rather than the accent, so Studio Modern's red no longer makes an enabled setting look like an error. - **The page builder is a structure list and a panel.** Hero, subpages and standalone albums sit in one list on the left, subpages drag-sorted in place; the selected entry is edited on the right instead of in an overlay. - **Dialogs only where a change is permanent.** Deleting a message or a journal entry, and resetting the favicon (which used to delete the file without asking), go through one confirm dialog in the admin's own look. Removals in the page builder, which only touch unsaved state, happen at once and offer _Undo_. No `window.confirm()` is left. - **Feature switches are grouped by meaning** as one-line rows under Settings → General; page transitions and scroll-to-top moved to Theme → Look & motion. No setting keys changed. ### Changed - **Fonts and the Leaflet stylesheet are served from the site itself** ([#700](https://github.com/ralksta/immich-folio/pull/700)). Every page used to link `fonts.googleapis.com`, which sends each visitor's IP address to Google. The server now fetches a theme's Google fonts once, rewrites the stylesheet and caches the files in `content/.fonts/`; custom fonts in `theme.fonts` keep working. If Google cannot be reached before a font is cached, the page falls back to the theme's system fonts. `leaflet.css` comes from the npm package instead of unpkg. The CSP drops `fonts.googleapis.com`, `fonts.gstatic.com` and `unpkg.com`. - **Email addresses are kept out of the served HTML** ([#705](https://github.com/ralksta/immich-folio/pull/705)). The Impressum and footer render the address only after hydration, from an encoded form, so harvesters reading raw HTML find nothing. Without JavaScript the Impressum shows `name [at] example [dot] de`. This defeats bulk harvesting, not a person with a browser. - **The Impressum cites § 5 DDG and links its contacts** ([#698](https://github.com/ralksta/immich-folio/pull/698), reported in [#697](https://github.com/ralksta/immich-folio/issues/697) by [@RichKidsDev](https://github.com/RichKidsDev)). The TMG was replaced by the DDG in May 2024; `legal.heading` replaces the line for other laws (e.g. § 5 ECG in Austria). `legal.contactUrl` and `legal.contactLabel` add a contact form as the second channel, so a phone number stays optional. Email, phone and contact URL are now links, and the "Created with the Impressum generator by eRecht24" line, shown on every site whether true or not, is gone. Settings → Legal gains fields for heading, contact URL, VAT ID and tax number, and a doctor check flags missing details. - **Missing pages answer `404`** ([#704](https://github.com/ralksta/immich-folio/pull/704)). Every missing page used to answer `200`, because streaming had started before `notFound()` ran. `/contact`, `/impressum`, `/map` and `/privacy` while switched off, and `/journal/<slug>` without an entry, now return a real 404 with the same not-found page. Album and subpage slugs still depend on Immich and stay soft 404s. - **Passwords set in the admin are stored as scrypt hashes** ([#706](https://github.com/ralksta/immich-folio/pull/706), closes [#690](https://github.com/ralksta/immich-folio/issues/690)). Subpage, album, journal-entry and site passwords were written as typed. The save routes now hash them; a stored hash reads _Protected_ with _Change_ and _Remove_ and is never put into an input. Visitors who unlocked a page stay signed in across unrelated saves. Existing plaintext passwords are hashed the next time their file is saved in the admin. - **One notification surface in the admin** ([#707](https://github.com/ralksta/immich-folio/pull/707)) replaces every `alert()`: errors stay until dismissed, successes clear themselves, and screen readers announce both. ### Fixed - **Map tiles load again** ([#701](https://github.com/ralksta/immich-folio/pull/701)). CARTO started answering every tile with an "API KEY REQUIRED" image, leaving `/map` and journal map blocks as a grey grid. Tiles now come from OpenStreetMap; the dark look is a CSS filter, so the map now follows the colour mode. - **The page builder no longer drops a subpage's `proofing:` flag on save** ([#711](https://github.com/ralksta/immich-folio/pull/711)). A page switched off for proofing by hand reverted after any unrelated edit. - **Unsaved edits in Settings and About survive switching admin tabs, and a backup restore is no longer overwritten by the next save** ([#687](https://github.com/ralksta/immich-folio/pull/687)). Editors that were open during a restore now reload and offer unsaved edits back as a conflict. Also: "Restore my changes" after a conflict found nothing, removing an album left its drawer showing the next album, and the journal saved (rotating a backup) without changes. - **Accent-backed buttons stay readable with a light or malformed accent** ([#724](https://github.com/ralksta/immich-folio/pull/724), supersedes [#680](https://github.com/ralksta/immich-folio/pull/680)) — contributed by [@lancetm714](https://github.com/lancetm714). A white accent made the proofing dialog's _Download selected (.zip)_ button white on white. `theme.accent` is now accepted as hex only and normalised to `#rrggbb`, anything else falls back to the preset, and the proofing dialog and filter pills use the mode-aware `--on-accent` text colour from #688. - **Every preset's accent is visible in both colour modes** ([#688](https://github.com/ralksta/immich-folio/pull/688)). Presets had one accent for both modes; minimal's dark mode drew black buttons on black. Presets now carry a light and a dark accent, and text on accent-filled buttons picks black or white for contrast. A custom accent stays the owner's choice in both modes. - **Visitor-side inconsistencies** ([#685](https://github.com/ralksta/immich-folio/pull/685)): after visiting `/impressum`, every subpage header turned centred and uppercase; back links announced "Back to Back to …"; the hero EXIF chip ignored `exif.location`/`camera`/`settings`; videos in journal entries opened as stills; the setup screen named a non-existent `.env.example`. - **An essay's lightbox walks only the photos the story shows** ([#686](https://github.com/ralksta/immich-folio/pull/686)), not every photo of the subpage's albums, and the proofing bar in essays shows the selection count instead of a filter button that did nothing. - **The page panel scrolls with the mouse wheel** ([#720](https://github.com/ralksta/immich-folio/pull/720)). - **The journal editor's top bar wraps on phones** ([#723](https://github.com/ralksta/immich-folio/pull/723), closes [#675](https://github.com/ralksta/immich-folio/issues/675)), so the title stays editable and Save stays on screen. - **Every admin form field has a name for assistive technology** ([#715](https://github.com/ralksta/immich-folio/pull/715)). Only two inputs had a linked label; 47 are linked now, and clicking a label focuses its field. ### Internal - **`SettingsEditor` and `PageBuilder` are split up** ([#710](https://github.com/ralksta/immich-folio/pull/710), [#711](https://github.com/ralksta/immich-folio/pull/711)). The 2,200-line settings editor is a shell with one file per section; the page builder's YAML handling and edits are pure functions under test. Both were checked side by side against `dev` for identical output. - **`useAdminFetch()`** ([#707](https://github.com/ralksta/immich-folio/pull/707)) gives Analytics, Messages, Backups and the journal list one loading and error pattern. - README brought up to v0.17.0 ([#678](https://github.com/ralksta/immich-folio/pull/678), [#679](https://github.com/ralksta/immich-folio/pull/679)). ### Upgrade notes **`content/` gains two directories the app writes to:** `content/.fonts/` for the cached fonts and `content/messages/` for contact-form messages. Both are created on demand, so a writable `content/` is enough, as before. **The server needs outbound HTTPS to Google once per font** to fill the font cache. Until then pages fall back to the theme's system fonts. Visitors' browsers no longer contact Google. **A custom CSP or reverse-proxy allowlist** must now allow `tile.openstreetmap.org` for images instead of `*.basemaps.cartocdn.com`, and no longer needs `fonts.googleapis.com`, `fonts.gstatic.com` or `unpkg.com`. The built-in CSP is updated. **`theme.accent` must be hex** (`#rgb`, `#rrggbb` or `#rrggbbaa`). Anything else, including a value without `#`, falls back to the preset's accent. **Plaintext passwords in `gallery.yaml`, `settings.yaml` or journal entries** are hashed the next time that file is saved in the admin; one save clears the doctor's warning. **New, optional settings:** `contact.*` (the form is off by default), `privacy.enabled`, `legal.heading`, `legal.contactUrl`, `legal.contactLabel`, and the `CDN_URL` and `CONTACT_NOTIFY_URL` environment variables. See `content/settings.yaml.example` and `.env.local.example`. In the example file, `vatId` and `taxId` had swapped sample values; check yours if you copied them. No `IMAGE_CACHE_VERSION` bump is needed this time. --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: ralksta <ralksta@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Ralf <rohlenbo79@gmail.com> Co-authored-by: Paul Thies <110185070+ImScheinox@users.noreply.github.com> Co-authored-by: lancetm714 <108419425+lancetm714@users.noreply.github.com> Co-authored-by: Lance Martin <lancetaylor95@gmail.com>
This commit is contained in:
110
lib/__tests__/cdn.test.ts
Normal file
110
lib/__tests__/cdn.test.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const config = { authSecret: 'test-auth-secret-32-chars-long-min', sitePassword: '' };
|
||||
|
||||
vi.mock('@/lib/config', () => ({
|
||||
getConfig: () => config,
|
||||
getConfigOrNull: () => config,
|
||||
}));
|
||||
|
||||
const ASSET = '11111111-1111-1111-1111-111111111111';
|
||||
|
||||
describe('normalizeCdnUrl', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
async function normalize(raw: string | undefined) {
|
||||
const { normalizeCdnUrl } = await import('@/lib/env');
|
||||
return normalizeCdnUrl(raw);
|
||||
}
|
||||
|
||||
it('keeps an https origin and drops the trailing slash', async () => {
|
||||
expect(await normalize('https://cdn.example.net/')).toBe('https://cdn.example.net');
|
||||
});
|
||||
|
||||
it('keeps a path prefix', async () => {
|
||||
expect(await normalize(' https://cdn.example.net/folio// ')).toBe(
|
||||
'https://cdn.example.net/folio',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects what cannot prefix a path', async () => {
|
||||
expect(await normalize('')).toBe('');
|
||||
expect(await normalize(undefined)).toBe('');
|
||||
expect(await normalize('cdn.example.net')).toBe('');
|
||||
expect(await normalize('ftp://cdn.example.net')).toBe('');
|
||||
expect(await normalize('https://cdn.example.net/?x=1')).toBe('');
|
||||
expect(await normalize('https://cdn.example.net/#top')).toBe('');
|
||||
expect(await normalize('https://user:pw@cdn.example.net')).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CDN mode', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.unstubAllEnvs();
|
||||
config.sitePassword = '';
|
||||
});
|
||||
|
||||
async function load() {
|
||||
const urls = await import('@/lib/urls');
|
||||
const cdn = await import('@/lib/cdn');
|
||||
return { ...urls, ...cdn };
|
||||
}
|
||||
|
||||
it('keeps URLs relative without CDN_URL', async () => {
|
||||
const { imageUrl, videoUrl, cdnOrigin } = await load();
|
||||
expect(imageUrl(ASSET)).toMatch(/^\/api\/image\/[^?]+\?size=preview$/);
|
||||
expect(videoUrl(ASSET)).toMatch(/^\/api\/video\/[^?]+$/);
|
||||
expect(cdnOrigin()).toBeNull();
|
||||
});
|
||||
|
||||
it('puts images and videos on the CDN', async () => {
|
||||
vi.stubEnv('CDN_URL', 'https://cdn.example.net/folio/');
|
||||
const { imageUrl, videoUrl, exifUrl, downloadUrl, cdnOrigin } = await load();
|
||||
|
||||
expect(imageUrl(ASSET, 'thumbnail')).toMatch(
|
||||
/^https:\/\/cdn\.example\.net\/folio\/api\/image\/[^?]+\?size=thumbnail$/,
|
||||
);
|
||||
expect(videoUrl(ASSET)).toMatch(/^https:\/\/cdn\.example\.net\/folio\/api\/video\//);
|
||||
expect(cdnOrigin()).toBe('https://cdn.example.net');
|
||||
|
||||
// Routes that check cookies or are not cacheable stay on this host.
|
||||
expect(exifUrl(ASSET)).toMatch(/^\/api\/exif\//);
|
||||
expect(downloadUrl('album', ASSET)).toMatch(/^\/api\/download\//);
|
||||
});
|
||||
|
||||
it('keeps the cache buster on CDN URLs', async () => {
|
||||
vi.stubEnv('CDN_URL', 'https://cdn.example.net');
|
||||
vi.stubEnv('IMAGE_CACHE_VERSION', '7');
|
||||
const { imageUrl } = await load();
|
||||
expect(imageUrl(ASSET)).toMatch(/^https:\/\/cdn\.example\.net\/api\/image\/.+&v=7$/);
|
||||
});
|
||||
|
||||
it('stays off while a site password is set, and follows it at runtime', async () => {
|
||||
vi.stubEnv('CDN_URL', 'https://cdn.example.net');
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const { imageUrl, cdnOrigin } = await load();
|
||||
|
||||
config.sitePassword = 'secret';
|
||||
expect(imageUrl(ASSET)).toMatch(/^\/api\/image\//);
|
||||
// The policy still allows the origin; it just goes unused.
|
||||
expect(cdnOrigin()).toBe('https://cdn.example.net');
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
|
||||
config.sitePassword = '';
|
||||
expect(imageUrl(ASSET)).toMatch(/^https:\/\/cdn\.example\.net\/api\/image\//);
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it('ignores an invalid CDN_URL', async () => {
|
||||
vi.stubEnv('CDN_URL', 'not a url');
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const { imageUrl, cdnOrigin } = await load();
|
||||
expect(imageUrl(ASSET)).toMatch(/^\/api\/image\//);
|
||||
expect(cdnOrigin()).toBeNull();
|
||||
warn.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
normalizeSlug,
|
||||
buildSubpageGrid,
|
||||
sanitizeNavLinks,
|
||||
resolveLegal,
|
||||
resolveContact,
|
||||
} from '@/lib/config';
|
||||
|
||||
// EXPERIMENTAL: external navigation links — rendered as <a href> in the
|
||||
@@ -52,6 +54,71 @@ describe('sanitizeNavLinks', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// legal.contactUrl lands in an <a href> on /impressum, so it gets the
|
||||
// navLinks rule: http(s) or nothing.
|
||||
describe('resolveLegal', () => {
|
||||
it('keeps an http(s) contact URL and its label', () => {
|
||||
const legal = resolveLegal({
|
||||
enabled: true,
|
||||
contactUrl: ' https://example.com/contact ',
|
||||
contactLabel: 'Write to me',
|
||||
});
|
||||
expect(legal.contactUrl).toBe('https://example.com/contact');
|
||||
expect(legal.contactLabel).toBe('Write to me');
|
||||
});
|
||||
|
||||
it('drops a contact URL with any other scheme', () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
for (const contactUrl of ['javascript:alert(1)', 'data:text/html,x', 'example.com/contact']) {
|
||||
expect(resolveLegal({ contactUrl }).contactUrl).toBeUndefined();
|
||||
}
|
||||
expect(warn).toHaveBeenCalledTimes(3);
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it('turns blank optional fields into undefined so the page can skip them', () => {
|
||||
const legal = resolveLegal({ heading: ' ', email: '', phone: ' ', vatId: '' });
|
||||
expect(legal.heading).toBeUndefined();
|
||||
expect(legal.email).toBeUndefined();
|
||||
expect(legal.phone).toBeUndefined();
|
||||
expect(legal.vatId).toBeUndefined();
|
||||
});
|
||||
|
||||
it('is disabled unless enabled is literally true', () => {
|
||||
expect(resolveLegal(undefined).enabled).toBe(false);
|
||||
expect(resolveLegal({ name: 'Ralf' }).enabled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveContact', () => {
|
||||
it('is off with a 90-day retention by default', () => {
|
||||
expect(resolveContact(undefined)).toEqual({
|
||||
enabled: false,
|
||||
notifyUrl: undefined,
|
||||
retentionDays: 90,
|
||||
});
|
||||
});
|
||||
|
||||
it('lets CONTACT_NOTIFY_URL override the settings value', () => {
|
||||
expect(
|
||||
resolveContact({ enabled: true, notifyUrl: 'https://a.example/x' }, 'https://b.example/y')
|
||||
.notifyUrl,
|
||||
).toBe('https://b.example/y');
|
||||
});
|
||||
|
||||
it('drops a notify URL that is not http(s)', () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
expect(resolveContact({ notifyUrl: 'javascript:alert(1)' }).notifyUrl).toBeUndefined();
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it('clamps the retention period', () => {
|
||||
expect(resolveContact({ retentionDays: 0 }).retentionDays).toBe(1);
|
||||
expect(resolveContact({ retentionDays: 10_000 }).retentionDays).toBe(365);
|
||||
expect(resolveContact({ retentionDays: 'soon' as unknown as number }).retentionDays).toBe(90);
|
||||
});
|
||||
});
|
||||
|
||||
describe('slugify', () => {
|
||||
it('converts a simple name to lowercase with hyphens', () => {
|
||||
expect(slugify('Kloster Chorin')).toBe('kloster-chorin');
|
||||
|
||||
175
lib/__tests__/contact.test.ts
Normal file
175
lib/__tests__/contact.test.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
MAX_MESSAGES,
|
||||
MIN_FILL_MS,
|
||||
deleteMessage,
|
||||
listMessages,
|
||||
notifyNewMessage,
|
||||
saveMessage,
|
||||
setRead,
|
||||
validateContact,
|
||||
} from '../contact';
|
||||
|
||||
const NOW = 1_800_000_000_000;
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const valid = {
|
||||
name: 'Ada',
|
||||
email: 'ada@example.com',
|
||||
message: 'Hello there',
|
||||
website: '',
|
||||
startedAt: NOW - 10_000,
|
||||
};
|
||||
|
||||
describe('validateContact', () => {
|
||||
it('accepts a normal submission and trims it', () => {
|
||||
expect(validateContact({ ...valid, name: ' Ada\nLovelace ' }, NOW)).toEqual({
|
||||
ok: true,
|
||||
name: 'Ada Lovelace',
|
||||
email: 'ada@example.com',
|
||||
message: 'Hello there',
|
||||
});
|
||||
});
|
||||
|
||||
it('treats a filled honeypot as spam', () => {
|
||||
expect(validateContact({ ...valid, website: 'http://spam' }, NOW)).toEqual({
|
||||
ok: false,
|
||||
reason: 'spam',
|
||||
});
|
||||
});
|
||||
|
||||
it('treats a form sent faster than a person types as spam', () => {
|
||||
expect(validateContact({ ...valid, startedAt: NOW - MIN_FILL_MS + 1 }, NOW).ok).toBe(false);
|
||||
expect(validateContact({ ...valid, startedAt: undefined }, NOW)).toEqual({
|
||||
ok: false,
|
||||
reason: 'spam',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a missing field or a malformed email as invalid', () => {
|
||||
expect(validateContact({ ...valid, name: ' ' }, NOW)).toEqual({ ok: false, reason: 'invalid' });
|
||||
expect(validateContact({ ...valid, email: 'not-an-email' }, NOW).ok).toBe(false);
|
||||
expect(validateContact({ ...valid, email: 'a@b.c\r\nBcc: x@y.z' }, NOW).ok).toBe(false);
|
||||
expect(validateContact({ ...valid, message: 'x'.repeat(5001) }, NOW).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('message storage', () => {
|
||||
let cwd: string;
|
||||
|
||||
beforeEach(() => {
|
||||
cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'folio-contact-'));
|
||||
vi.spyOn(process, 'cwd').mockReturnValue(cwd);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
fs.rmSync(cwd, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const fields = { name: 'Ada', email: 'ada@example.com', message: 'Hi' };
|
||||
|
||||
it('stores a message unread and lists newest first', async () => {
|
||||
await saveMessage(fields, 90, NOW - 1000);
|
||||
const second = await saveMessage({ ...fields, name: 'Grace' }, 90, NOW);
|
||||
const list = await listMessages(90, NOW);
|
||||
expect(list.map((m) => m.name)).toEqual(['Grace', 'Ada']);
|
||||
expect(list[0]).toMatchObject({ read: false, id: (second as { id: string }).id });
|
||||
});
|
||||
|
||||
it('writes the file readable by the owner only', async () => {
|
||||
const msg = (await saveMessage(fields, 90, NOW)) as { id: string };
|
||||
const mode = fs.statSync(path.join(cwd, 'content', 'messages', `${msg.id}.json`)).mode;
|
||||
expect(mode & 0o077).toBe(0);
|
||||
});
|
||||
|
||||
it('deletes messages past the retention period when listing', async () => {
|
||||
await saveMessage(fields, 90, NOW - 31 * DAY);
|
||||
await saveMessage(fields, 90, NOW - DAY);
|
||||
expect(await listMessages(30, NOW)).toHaveLength(1);
|
||||
expect(fs.readdirSync(path.join(cwd, 'content', 'messages'))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('refuses new messages at the cap instead of evicting old ones', async () => {
|
||||
const dir = path.join(cwd, 'content', 'messages');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
for (let i = 0; i < MAX_MESSAGES; i++) {
|
||||
const id = `${NOW - i}-${i.toString(16).padStart(8, '0')}`;
|
||||
fs.writeFileSync(
|
||||
path.join(dir, `${id}.json`),
|
||||
JSON.stringify({
|
||||
id,
|
||||
receivedAt: '',
|
||||
name: 'x',
|
||||
email: 'x@y.z',
|
||||
message: 'm',
|
||||
read: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect(await saveMessage(fields, 90, NOW)).toBe('full');
|
||||
expect(fs.readdirSync(dir)).toHaveLength(MAX_MESSAGES);
|
||||
});
|
||||
|
||||
it('marks read and deletes by id, and ignores ids that could escape the directory', async () => {
|
||||
const msg = (await saveMessage(fields, 90, NOW)) as { id: string };
|
||||
expect(await setRead(msg.id, true)).toBe(true);
|
||||
expect((await listMessages(90, NOW))[0].read).toBe(true);
|
||||
expect(await deleteMessage('../settings')).toBe(false);
|
||||
expect(await deleteMessage(msg.id)).toBe(true);
|
||||
expect(await listMessages(90, NOW)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('notifyNewMessage', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('posts nothing about the sender, so the push service gets no personal data', async () => {
|
||||
const fetchMock = vi.fn(async () => new Response('ok'));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await notifyNewMessage('https://ntfy.sh/topic', 'https://site.example/admin/messages');
|
||||
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect(url).toBe('https://ntfy.sh/topic');
|
||||
expect(init.body).toBe('A new message arrived through the contact form.');
|
||||
expect((init.headers as Record<string, string>).Click).toBe(
|
||||
'https://site.example/admin/messages',
|
||||
);
|
||||
});
|
||||
|
||||
it('does nothing without a URL and never throws on failure', async () => {
|
||||
const fetchMock = vi.fn(async () => {
|
||||
throw new Error('down');
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
await notifyNewMessage(undefined, null);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
await expect(notifyNewMessage('https://ntfy.sh/t', null)).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateContact: email pattern', () => {
|
||||
it('accepts ordinary addresses and rejects malformed ones', () => {
|
||||
for (const email of ['a@b.de', 'first.last@mail.example.co.uk']) {
|
||||
expect(validateContact({ ...valid, email }, NOW).ok).toBe(true);
|
||||
}
|
||||
for (const email of ['a@b', 'a@.de', 'a@b.', 'a@b..de', 'a b@c.de', 'a@@b.de']) {
|
||||
expect(validateContact({ ...valid, email }, NOW).ok).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
// CodeQL js/polynomial-redos: the old pattern backtracked polynomially on a
|
||||
// domain of many dots. The limit keeps input short, and the pattern no
|
||||
// longer has more than one way to match.
|
||||
it('answers crafted input at once', () => {
|
||||
const crafted = '!@!.' + '!.'.repeat(50_000);
|
||||
const start = performance.now();
|
||||
expect(validateContact({ ...valid, email: crafted }, NOW).ok).toBe(false);
|
||||
expect(performance.now() - start).toBeLessThan(50);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
checkCdn,
|
||||
checkAuthSecret,
|
||||
checkProxyHops,
|
||||
countForwardedHops,
|
||||
@@ -9,6 +10,9 @@ import {
|
||||
checkPasswords,
|
||||
checkWritable,
|
||||
checkImmichCalls,
|
||||
checkContact,
|
||||
checkLegal,
|
||||
checkPrivacy,
|
||||
worstLevel,
|
||||
} from '../admin/doctor';
|
||||
|
||||
@@ -305,3 +309,138 @@ describe('worstLevel', () => {
|
||||
).toBe('error');
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkCdn', () => {
|
||||
it('stays silent without CDN_URL', () => {
|
||||
expect(checkCdn(undefined, false, 1)).toBeNull();
|
||||
});
|
||||
|
||||
it('warns that a site password keeps photos off the CDN', () => {
|
||||
const finding = checkCdn('https://cdn.example.net', true, 1)!;
|
||||
expect(finding.level).toBe('warn');
|
||||
expect(finding.detail).toMatch(/password/);
|
||||
});
|
||||
|
||||
it('warns when the rate limiter would count CDN edges', () => {
|
||||
const finding = checkCdn('https://cdn.example.net', false, 0)!;
|
||||
expect(finding.level).toBe('warn');
|
||||
expect(finding.title).toMatch(/TRUSTED_PROXY_HOPS/);
|
||||
});
|
||||
|
||||
it('reports ok with a proxy chain configured', () => {
|
||||
const finding = checkCdn('https://cdn.example.net', false, 2)!;
|
||||
expect(finding.level).toBe('ok');
|
||||
expect(finding.detail).toContain('https://cdn.example.net');
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkLegal', () => {
|
||||
const complete = {
|
||||
enabled: true,
|
||||
name: 'Ralf',
|
||||
address: 'Street 1',
|
||||
zipCity: '10247 Berlin',
|
||||
email: 'mail@example.com',
|
||||
contactUrl: 'https://example.com/contact',
|
||||
};
|
||||
|
||||
it('returns nothing while the Impressum is switched off or absent', () => {
|
||||
expect(checkLegal({ ...complete, enabled: false })).toBeNull();
|
||||
expect(checkLegal(undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it('passes with name, address, email and a second channel', () => {
|
||||
expect(checkLegal(complete)?.level).toBe('ok');
|
||||
expect(checkLegal({ ...complete, contactUrl: undefined, phone: '+49 30 1' })?.level).toBe('ok');
|
||||
});
|
||||
|
||||
it('names the missing address fields', () => {
|
||||
const f = checkLegal({ ...complete, address: '', zipCity: ' ' })!;
|
||||
expect(f.level).toBe('warn');
|
||||
expect(f.detail).toContain('street address, ZIP and city');
|
||||
});
|
||||
|
||||
it('asks for an email address', () => {
|
||||
expect(checkLegal({ ...complete, email: undefined })!.detail).toContain('No email address');
|
||||
});
|
||||
|
||||
it('flags email as the only contact channel', () => {
|
||||
const f = checkLegal({ ...complete, contactUrl: undefined })!;
|
||||
expect(f.level).toBe('warn');
|
||||
expect(f.detail).toContain('only contact channel');
|
||||
});
|
||||
|
||||
it('reports a contact URL the page drops, and does not count it as a channel', () => {
|
||||
const f = checkLegal({ ...complete, contactUrl: 'javascript:alert(1)' })!;
|
||||
expect(f.level).toBe('warn');
|
||||
expect(f.title).toContain('2 gaps');
|
||||
expect(f.detail).toContain('ignored');
|
||||
expect(f.detail).toContain('only contact channel');
|
||||
});
|
||||
|
||||
it('tolerates hand-edited YAML with the wrong types', () => {
|
||||
const f = checkLegal({ ...complete, name: 42, email: ['a'] })!;
|
||||
expect(f.level).toBe('warn');
|
||||
expect(f.detail).toContain('Missing: name');
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkLegal with the built-in contact form', () => {
|
||||
const emailOnly = {
|
||||
enabled: true,
|
||||
name: 'Ralf',
|
||||
address: 'Street 1',
|
||||
zipCity: '10247 Berlin',
|
||||
email: 'mail@example.com',
|
||||
};
|
||||
|
||||
it('counts the form as the second contact channel', () => {
|
||||
expect(checkLegal(emailOnly)?.level).toBe('warn');
|
||||
expect(checkLegal(emailOnly, true)?.level).toBe('ok');
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkContact', () => {
|
||||
it('returns nothing while the form is off', () => {
|
||||
expect(checkContact({ enabled: false })).toBeNull();
|
||||
expect(checkContact(undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it('warns when nobody hears about new messages', () => {
|
||||
expect(checkContact({ enabled: true })?.level).toBe('warn');
|
||||
});
|
||||
|
||||
it('warns about a URL that is not http(s)', () => {
|
||||
const f = checkContact({ enabled: true, notifyUrl: 'ntfy.sh/topic' })!;
|
||||
expect(f.level).toBe('warn');
|
||||
expect(f.title).toContain('ignored');
|
||||
});
|
||||
|
||||
it('is satisfied by the settings value or by CONTACT_NOTIFY_URL', () => {
|
||||
expect(checkContact({ enabled: true, notifyUrl: 'https://ntfy.sh/t' })?.level).toBe('ok');
|
||||
expect(checkContact({ enabled: true }, 'https://ntfy.sh/t')?.level).toBe('ok');
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkPrivacy', () => {
|
||||
it('stays quiet on a site with no legal pages at all', () => {
|
||||
expect(checkPrivacy({ legalEnabled: false, privacyEnabled: true, hasText: false })).toBeNull();
|
||||
});
|
||||
|
||||
it('warns when the Impressum is on and there is no policy', () => {
|
||||
const f = checkPrivacy({ legalEnabled: true, privacyEnabled: true, hasText: false })!;
|
||||
expect(f.level).toBe('warn');
|
||||
expect(f.detail).toContain('no text');
|
||||
});
|
||||
|
||||
it('warns when the text exists but the page is switched off', () => {
|
||||
const f = checkPrivacy({ legalEnabled: true, privacyEnabled: false, hasText: true })!;
|
||||
expect(f.detail).toContain('switched off');
|
||||
});
|
||||
|
||||
it('is satisfied by a published policy', () => {
|
||||
expect(checkPrivacy({ legalEnabled: true, privacyEnabled: true, hasText: true })?.level).toBe(
|
||||
'ok',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
39
lib/__tests__/emailObfuscation.test.ts
Normal file
39
lib/__tests__/emailObfuscation.test.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createElement } from 'react';
|
||||
import { renderToString } from 'react-dom/server';
|
||||
import { decodeEmail, encodeEmail, spelledOutEmail } from '../emailObfuscation';
|
||||
import EmailLink from '@/components/EmailLink';
|
||||
|
||||
const ADDRESS = 'ralf.test+impressum@example.de';
|
||||
|
||||
describe('email obfuscation', () => {
|
||||
it('round-trips, including non-ASCII addresses', () => {
|
||||
expect(decodeEmail(encodeEmail(ADDRESS))).toBe(ADDRESS);
|
||||
expect(decodeEmail(encodeEmail('jürgen@müller.de'))).toBe('jürgen@müller.de');
|
||||
});
|
||||
|
||||
it('leaves nothing a harvester would match in the encoded form', () => {
|
||||
const encoded = encodeEmail(ADDRESS);
|
||||
expect(encoded).not.toContain('@');
|
||||
expect(encoded).not.toContain('example');
|
||||
});
|
||||
|
||||
it('decodes garbage to an empty string instead of throwing', () => {
|
||||
expect(decodeEmail('%%%')).toBe('');
|
||||
});
|
||||
|
||||
it('spells the address out for the no-script fallback', () => {
|
||||
expect(spelledOutEmail('a.b@example.de')).toBe('a [dot] b [at] example [dot] de');
|
||||
});
|
||||
|
||||
/*
|
||||
* The point of the exercise: the server HTML carries neither the address
|
||||
* nor a mailto: link. It appears only once the browser has hydrated.
|
||||
*/
|
||||
it('renders no address and no mailto: on the server', () => {
|
||||
const html = renderToString(createElement(EmailLink, { encoded: encodeEmail(ADDRESS) }));
|
||||
expect(html).not.toContain(ADDRESS);
|
||||
expect(html).not.toContain('mailto:');
|
||||
expect(html).not.toContain('[at]');
|
||||
});
|
||||
});
|
||||
46
lib/__tests__/essay-sequence.test.ts
Normal file
46
lib/__tests__/essay-sequence.test.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { essayPhotoSequence } from '../essaySequence';
|
||||
import type { JournalBlock } from '../journal';
|
||||
|
||||
// Six photos in the subpage's albums; the essay shows only some of them.
|
||||
const photos = ['a', 'b', 'c', 'd', 'e', 'f'].map((id) => ({ id }));
|
||||
const resolve = (key: string) => {
|
||||
const byIndex = Number(key);
|
||||
if (Number.isInteger(byIndex) && byIndex >= 1) return photos[byIndex - 1];
|
||||
return photos.find((p) => p.id === key);
|
||||
};
|
||||
const ids = (list: { id: string }[]) => list.map((p) => p.id);
|
||||
|
||||
describe('essayPhotoSequence', () => {
|
||||
it('lists only the photos the blocks show, in reading order', () => {
|
||||
const blocks: JournalBlock[] = [
|
||||
{ type: 'photo', assetId: 'c', layout: 'wide' },
|
||||
{ type: 'paragraph', html: 'text' },
|
||||
{ type: 'photo-pair', assetIds: ['a', 'e'] },
|
||||
];
|
||||
expect(ids(essayPhotoSequence(blocks, undefined, resolve))).toEqual(['c', 'a', 'e']);
|
||||
});
|
||||
|
||||
it('puts the cover first and does not repeat it', () => {
|
||||
const blocks: JournalBlock[] = [{ type: 'photo', assetId: 'b', layout: 'wide' }];
|
||||
expect(ids(essayPhotoSequence(blocks, 'b', resolve))).toEqual(['b']);
|
||||
expect(ids(essayPhotoSequence(blocks, 'd', resolve))).toEqual(['d', 'b']);
|
||||
});
|
||||
|
||||
it('resolves 1-based index references', () => {
|
||||
const blocks: JournalBlock[] = [{ type: 'photo', assetId: '6', layout: 'contained' }];
|
||||
expect(ids(essayPhotoSequence(blocks, undefined, resolve))).toEqual(['f']);
|
||||
});
|
||||
|
||||
it('skips a pair with a missing half, like the renderer', () => {
|
||||
const blocks: JournalBlock[] = [{ type: 'photo-pair', assetIds: ['a', 'missing'] }];
|
||||
expect(essayPhotoSequence(blocks, undefined, resolve)).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps a grid only while two photos resolve', () => {
|
||||
const one: JournalBlock[] = [{ type: 'photo-grid', assetIds: ['a', 'x', 'y'] }];
|
||||
const two: JournalBlock[] = [{ type: 'photo-grid', assetIds: ['a', 'x', 'b'] }];
|
||||
expect(essayPhotoSequence(one, undefined, resolve)).toEqual([]);
|
||||
expect(ids(essayPhotoSequence(two, undefined, resolve))).toEqual(['a', 'b']);
|
||||
});
|
||||
});
|
||||
102
lib/__tests__/essay-source.test.ts
Normal file
102
lib/__tests__/essay-source.test.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'essay-source-'));
|
||||
|
||||
vi.mock('@/lib/config', () => ({
|
||||
getConfig: () => ({
|
||||
authSecret: 'test-auth-secret-32-chars-long-min',
|
||||
subpages: [],
|
||||
albumPasswords: {},
|
||||
}),
|
||||
}));
|
||||
|
||||
// Journal files come from a temp dir instead of content/journal/. Both the
|
||||
// loader and lib/auth's password lookup go through this module, so the gate
|
||||
// under test reads the same file the essay does.
|
||||
vi.mock('@/lib/admin/journal-service', async () => {
|
||||
const { parseJournalMarkdown } = await import('@/lib/journal');
|
||||
const file = (slug: string) => path.join(dir, `${slug}.md`);
|
||||
return {
|
||||
resolveJournalFilePath: (slug: string) => file(slug),
|
||||
loadEssayFromFile: (slug: string) =>
|
||||
fs.existsSync(file(slug)) ? parseJournalMarkdown(fs.readFileSync(file(slug), 'utf8')) : null,
|
||||
};
|
||||
});
|
||||
|
||||
import { resolveEssayFile, generatedEssayCaption } from '@/lib/essaySource';
|
||||
import { authenticate } from '@/lib/auth';
|
||||
import type { ImmichAsset } from '@/lib/immich';
|
||||
|
||||
const write = (slug: string, frontmatter: string) =>
|
||||
fs.writeFileSync(path.join(dir, `${slug}.md`), `---\n${frontmatter}\n---\n\nBody text.\n`);
|
||||
|
||||
const anonymous = { isAdmin: false, getCookie: () => undefined };
|
||||
|
||||
beforeAll(() => {
|
||||
write('open', 'title: "Open"');
|
||||
write('draft', 'title: "Draft"\ndraft: true');
|
||||
write('locked', 'title: "Locked"\npassword: "letmein"');
|
||||
});
|
||||
|
||||
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
describe('resolveEssayFile', () => {
|
||||
it('returns a public entry', () => {
|
||||
const result = resolveEssayFile('open', anonymous);
|
||||
expect(result.status).toBe('open');
|
||||
});
|
||||
|
||||
it('treats a missing entry as missing', () => {
|
||||
expect(resolveEssayFile('nope', anonymous)).toEqual({ status: 'missing' });
|
||||
});
|
||||
|
||||
it('hides a draft from visitors', () => {
|
||||
expect(resolveEssayFile('draft', anonymous)).toEqual({ status: 'missing' });
|
||||
});
|
||||
|
||||
it('shows a draft to the admin', () => {
|
||||
expect(resolveEssayFile('draft', { ...anonymous, isAdmin: true }).status).toBe('open');
|
||||
});
|
||||
|
||||
it('locks a password-protected entry without a cookie', () => {
|
||||
expect(resolveEssayFile('locked', anonymous)).toEqual({ status: 'locked', title: 'Locked' });
|
||||
});
|
||||
|
||||
it('keeps the entry locked for the admin, like /journal/<slug> does', () => {
|
||||
expect(resolveEssayFile('locked', { ...anonymous, isAdmin: true }).status).toBe('locked');
|
||||
});
|
||||
|
||||
it('opens a protected entry with the journal cookie', async () => {
|
||||
const setCookie = await authenticate('locked', 'letmein', 'journal');
|
||||
expect(setCookie).not.toBeNull();
|
||||
const [pair] = setCookie!.split(';');
|
||||
const [name, value] = pair.split('=');
|
||||
const result = resolveEssayFile('locked', {
|
||||
isAdmin: false,
|
||||
getCookie: (n) => (n === name ? value : undefined),
|
||||
});
|
||||
expect(result.status).toBe('open');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generatedEssayCaption', () => {
|
||||
const asset = (description?: string) =>
|
||||
({ exifInfo: { description } }) as Pick<ImmichAsset, 'exifInfo'>;
|
||||
|
||||
it('escapes markup in an Immich description', () => {
|
||||
expect(generatedEssayCaption(asset('<b>hi</b> & "you"'), true)).toBe(
|
||||
'<b>hi</b> & "you"',
|
||||
);
|
||||
});
|
||||
|
||||
it('follows the exif.caption toggle', () => {
|
||||
expect(generatedEssayCaption(asset('A caption'), false)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('leaves no caption for an empty description', () => {
|
||||
expect(generatedEssayCaption(asset(' '), true)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
124
lib/__tests__/fonts.test.ts
Normal file
124
lib/__tests__/fonts.test.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
__resetFontsForTests,
|
||||
getFontFile,
|
||||
getGoogleCss,
|
||||
parseFamilies,
|
||||
rewriteCss,
|
||||
} from '../fonts';
|
||||
import { getFontsCssUrl } from '../config/theme';
|
||||
|
||||
const GSTATIC_URL = 'https://fonts.gstatic.com/s/archivo/v19/abc.woff2';
|
||||
const GOOGLE_CSS = `@font-face {
|
||||
font-family: 'Archivo';
|
||||
font-weight: 400;
|
||||
src: url(${GSTATIC_URL}) format('woff2');
|
||||
}`;
|
||||
|
||||
let cwd: string;
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
// lib/fonts.ts caches under <cwd>/content/.fonts.
|
||||
cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'folio-fonts-'));
|
||||
vi.spyOn(process, 'cwd').mockReturnValue(cwd);
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
fetchMock = vi.fn(async (url: string) => {
|
||||
if (url.startsWith('https://fonts.googleapis.com/')) return new Response(GOOGLE_CSS);
|
||||
if (url === GSTATIC_URL) return new Response(new Uint8Array([1, 2, 3]));
|
||||
return new Response(null, { status: 404 });
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
__resetFontsForTests();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
fs.rmSync(cwd, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const fileName = () =>
|
||||
rewriteCss(GOOGLE_CSS).match(/\/api\/fonts\/file\/([a-f0-9]{32}\.woff2)/)![1];
|
||||
|
||||
describe('getFontsCssUrl', () => {
|
||||
it('points at this origin, one family parameter per distinct family', () => {
|
||||
expect(getFontsCssUrl(['Archivo', 'Archivo', 'IBM Plex Mono'])).toBe(
|
||||
'/api/fonts/css?family=Archivo&family=IBM%20Plex%20Mono',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseFamilies', () => {
|
||||
it('accepts Google Fonts names with spaces and digits', () => {
|
||||
expect(parseFamilies(['Source Sans 3', 'IBM Plex Mono'])).toEqual([
|
||||
'Source Sans 3',
|
||||
'IBM Plex Mono',
|
||||
]);
|
||||
});
|
||||
|
||||
it('rejects anything that could change the upstream query', () => {
|
||||
expect(parseFamilies(['Inter:wght@100'])).toBeNull();
|
||||
expect(parseFamilies(['Inter&family=Roboto'])).toBeNull();
|
||||
expect(parseFamilies(['../etc'])).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects an empty list and more families than a theme has slots', () => {
|
||||
expect(parseFamilies([])).toBeNull();
|
||||
expect(parseFamilies(['A', 'B', 'C', 'D'])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('rewriteCss', () => {
|
||||
it('replaces every gstatic URL with a same-origin one', () => {
|
||||
const css = rewriteCss(GOOGLE_CSS);
|
||||
expect(css).not.toContain('gstatic');
|
||||
expect(css).toMatch(/url\(\/api\/fonts\/file\/[a-f0-9]{32}\.woff2\)/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getGoogleCss', () => {
|
||||
it('fetches once and serves the cached copy afterwards', async () => {
|
||||
expect(await getGoogleCss(['Archivo'])).toBe(GOOGLE_CSS);
|
||||
__resetFontsForTests();
|
||||
expect(await getGoogleCss(['Archivo'])).toBe(GOOGLE_CSS);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('asks Google with a browser User-Agent, so the answer is WOFF2', async () => {
|
||||
await getGoogleCss(['IBM Plex Mono']);
|
||||
const [url, init] = fetchMock.mock.calls[0];
|
||||
expect(url).toContain('family=IBM+Plex+Mono:wght@');
|
||||
expect(init.headers['User-Agent']).toMatch(/Chrome/);
|
||||
});
|
||||
|
||||
it('does not retry a failed fetch on every request', async () => {
|
||||
fetchMock.mockRejectedValue(new Error('offline'));
|
||||
expect(await getGoogleCss(['Archivo'])).toBeNull();
|
||||
expect(await getGoogleCss(['Archivo'])).toBeNull();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFontFile', () => {
|
||||
it('serves a file that a fetched stylesheet named, and caches it', async () => {
|
||||
await getGoogleCss(['Archivo']);
|
||||
expect(await getFontFile(fileName())).toEqual(new Uint8Array([1, 2, 3]));
|
||||
expect(fs.existsSync(path.join(cwd, 'content', '.fonts', fileName()))).toBe(true);
|
||||
});
|
||||
|
||||
it('finds the file after a restart from the stylesheet on disk', async () => {
|
||||
await getGoogleCss(['Archivo']);
|
||||
__resetFontsForTests();
|
||||
expect(await getFontFile(fileName())).toEqual(new Uint8Array([1, 2, 3]));
|
||||
});
|
||||
|
||||
it('refuses a name no stylesheet produced, without fetching anything', async () => {
|
||||
expect(await getFontFile('0'.repeat(32) + '.woff2')).toBeNull();
|
||||
expect(await getFontFile('../../settings.yaml')).toBeNull();
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -11,17 +11,27 @@ import { describe, it, expect } from 'vitest';
|
||||
import { resolveLocale, getDictionary, dictionaryFor, SUPPORTED_LOCALES } from '../i18n';
|
||||
import { en } from '../i18n/locales/en';
|
||||
import { de } from '../i18n/locales/de';
|
||||
import { fr } from '../i18n/locales/fr';
|
||||
import { es } from '../i18n/locales/es';
|
||||
import { it as itIT } from '../i18n/locales/it';
|
||||
import { nl } from '../i18n/locales/nl';
|
||||
import type { Dictionary } from '../i18n';
|
||||
|
||||
describe('resolveLocale', () => {
|
||||
it('accepts the supported locales', () => {
|
||||
expect(resolveLocale('en')).toBe('en');
|
||||
expect(resolveLocale('de')).toBe('de');
|
||||
for (const locale of SUPPORTED_LOCALES) {
|
||||
expect(resolveLocale(locale)).toBe(locale);
|
||||
}
|
||||
});
|
||||
|
||||
it('drops the region subtag', () => {
|
||||
expect(resolveLocale('de-DE')).toBe('de');
|
||||
expect(resolveLocale('de-AT')).toBe('de');
|
||||
expect(resolveLocale('en_GB')).toBe('en');
|
||||
expect(resolveLocale('fr-CA')).toBe('fr');
|
||||
expect(resolveLocale('es-MX')).toBe('es');
|
||||
expect(resolveLocale('it-CH')).toBe('it');
|
||||
expect(resolveLocale('nl-BE')).toBe('nl');
|
||||
});
|
||||
|
||||
it('is case- and whitespace-insensitive', () => {
|
||||
@@ -30,8 +40,8 @@ describe('resolveLocale', () => {
|
||||
});
|
||||
|
||||
it('falls back to English for languages without a dictionary', () => {
|
||||
expect(resolveLocale('fr')).toBe('en');
|
||||
expect(resolveLocale('ja-JP')).toBe('en');
|
||||
expect(resolveLocale('pt')).toBe('en');
|
||||
expect(resolveLocale('')).toBe('en');
|
||||
expect(resolveLocale(undefined)).toBe('en');
|
||||
expect(resolveLocale(null)).toBe('en');
|
||||
@@ -47,7 +57,8 @@ describe('getDictionary', () => {
|
||||
|
||||
it('dictionaryFor resolves and looks up in one step', () => {
|
||||
expect(dictionaryFor('de-DE')).toBe(de);
|
||||
expect(dictionaryFor('fr')).toBe(en);
|
||||
expect(dictionaryFor('fr-FR')).toBe(fr);
|
||||
expect(dictionaryFor('ja')).toBe(en);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -67,37 +78,110 @@ function invoke(fn: (...args: never[]) => string): string {
|
||||
return (fn as (...a: unknown[]) => string)(...args);
|
||||
}
|
||||
|
||||
describe('dictionary parity', () => {
|
||||
const enLeaves = leaves(en);
|
||||
const deLeaves = new Map(leaves(de));
|
||||
/**
|
||||
* Keys a locale legitimately shares with English — proper nouns, loanwords,
|
||||
* units and cognates that read the same in both languages. Anything not listed
|
||||
* here and still identical to English is an untranslated string.
|
||||
*/
|
||||
const SHARED_EVERYWHERE = [
|
||||
'lightbox.iso',
|
||||
// Pure interpolation with no words of its own.
|
||||
'subpage.coverAria',
|
||||
];
|
||||
|
||||
it('German covers every English key', () => {
|
||||
expect([...deLeaves.keys()].sort()).toEqual(enLeaves.map(([k]) => k).sort());
|
||||
const TRANSLATIONS: [string, Dictionary, string[]][] = [
|
||||
[
|
||||
'de',
|
||||
de,
|
||||
[
|
||||
'nav.journal',
|
||||
'journal.title',
|
||||
'lightbox.copyLinkShort',
|
||||
'lightbox.downloadShort',
|
||||
'common.website',
|
||||
'contact.name',
|
||||
],
|
||||
],
|
||||
[
|
||||
'fr',
|
||||
fr,
|
||||
[
|
||||
'nav.journal',
|
||||
'journal.title',
|
||||
'about.portraitAlt',
|
||||
'legal.contact',
|
||||
'lightbox.downloadShort',
|
||||
'subpage.sectionsNav',
|
||||
'subpage.collectionKicker',
|
||||
// French shares the words "photo(s)", "album(s)" and "collection(s)".
|
||||
'common.photos',
|
||||
'common.albums',
|
||||
'common.collections',
|
||||
'contact.navLabel',
|
||||
'contact.title',
|
||||
'contact.message',
|
||||
],
|
||||
],
|
||||
['es', es, ['lightbox.downloadShort', 'lightbox.info']],
|
||||
[
|
||||
'it',
|
||||
itIT,
|
||||
['nav.home', 'common.home', 'lightbox.info', 'lightbox.copyLinkShort', 'privacy.navLabel'],
|
||||
],
|
||||
[
|
||||
'nl',
|
||||
nl,
|
||||
[
|
||||
'nav.journal',
|
||||
'journal.title',
|
||||
'common.website',
|
||||
'common.albums',
|
||||
'lightbox.camera',
|
||||
'lightbox.info',
|
||||
'lightbox.copyLinkShort',
|
||||
'legal.contact',
|
||||
'contact.navLabel',
|
||||
'contact.title',
|
||||
'privacy.navLabel',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
describe('supported locales', () => {
|
||||
it('have a parity check below for every non-English dictionary', () => {
|
||||
expect(TRANSLATIONS.map(([code]) => code).sort()).toEqual(
|
||||
SUPPORTED_LOCALES.filter((l) => l !== 'en').sort(),
|
||||
);
|
||||
});
|
||||
|
||||
it('each dictionary is the one getDictionary serves', () => {
|
||||
for (const [code, dict] of TRANSLATIONS) {
|
||||
expect(getDictionary(code as (typeof SUPPORTED_LOCALES)[number])).toBe(dict);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe.each(TRANSLATIONS)('dictionary parity: %s', (code, dict, sharedKeys) => {
|
||||
const enLeaves = leaves(en);
|
||||
const otherLeaves = new Map(leaves(dict));
|
||||
|
||||
it('covers every English key', () => {
|
||||
expect([...otherLeaves.keys()].sort()).toEqual(enLeaves.map(([k]) => k).sort());
|
||||
});
|
||||
|
||||
it('matches value kinds — a string never stands in for an interpolator', () => {
|
||||
for (const [path, value] of enLeaves) {
|
||||
expect(typeof deLeaves.get(path), path).toBe(typeof value);
|
||||
expect(typeof otherLeaves.get(path), path).toBe(typeof value);
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves no English string untranslated', () => {
|
||||
// Proper nouns, loanwords and units read the same in both languages;
|
||||
// `coverAria` is pure interpolation with no words of its own.
|
||||
const shared = new Set([
|
||||
'nav.journal',
|
||||
'journal.title',
|
||||
'lightbox.iso',
|
||||
'lightbox.copyLinkShort',
|
||||
'lightbox.downloadShort',
|
||||
'common.website',
|
||||
'subpage.coverAria',
|
||||
]);
|
||||
const shared = new Set([...SHARED_EVERYWHERE, ...sharedKeys]);
|
||||
|
||||
const identical = enLeaves
|
||||
.filter(([path]) => !shared.has(path))
|
||||
.filter(([path, value]) => {
|
||||
const other = deLeaves.get(path);
|
||||
const other = otherLeaves.get(path);
|
||||
if (typeof value === 'function') {
|
||||
return invoke(other as (...a: never[]) => string) === invoke(value as never);
|
||||
}
|
||||
@@ -108,11 +192,30 @@ describe('dictionary parity', () => {
|
||||
expect(identical).toEqual([]);
|
||||
});
|
||||
|
||||
it('plural helpers actually vary on their count', () => {
|
||||
for (const dict of [en, de]) {
|
||||
it('lists only keys that really are identical, so the allowance cannot go stale', () => {
|
||||
const english = new Map(enLeaves);
|
||||
const stale = sharedKeys.filter((path) => {
|
||||
const value = english.get(path);
|
||||
const other = otherLeaves.get(path);
|
||||
return typeof value === 'function'
|
||||
? invoke(other as (...a: never[]) => string) !== invoke(value as never)
|
||||
: other !== value;
|
||||
});
|
||||
expect(stale).toEqual([]);
|
||||
});
|
||||
|
||||
it('formats dates for its own language', () => {
|
||||
expect(dict.dateLocale.split('-')[0]).toBe(code);
|
||||
});
|
||||
});
|
||||
|
||||
describe('plural helpers', () => {
|
||||
it.each([['en', en] as const, ...TRANSLATIONS.map(([c, d]) => [c, d] as const)])(
|
||||
'vary on their count in %s',
|
||||
(_code, dict) => {
|
||||
expect(dict.common.photos(1)).not.toBe(dict.common.photos(2));
|
||||
expect(dict.common.albums(1)).not.toBe(dict.common.albums(2));
|
||||
expect(dict.common.collections(1)).not.toBe(dict.common.collections(2));
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
86
lib/__tests__/password-hashing.test.ts
Normal file
86
lib/__tests__/password-hashing.test.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { hashFrontmatterPassword, hashPassword, hashPasswordKeys } from '../admin/passwordHashing';
|
||||
import { generateScryptHash, verifyScrypt } from '../password';
|
||||
|
||||
const KEY = new Set(['password']);
|
||||
|
||||
describe('hashPassword', () => {
|
||||
it('hashes plaintext, and leaves empty, scrypt and bcrypt values alone', async () => {
|
||||
const hashed = await hashPassword('secret', []);
|
||||
expect(hashed).toMatch(/^scrypt:/);
|
||||
expect(await verifyScrypt('secret', hashed)).toBe(true);
|
||||
expect(await hashPassword('', [])).toBe('');
|
||||
expect(await hashPassword(hashed, [])).toBe(hashed);
|
||||
expect(await hashPassword('$2b$10$abcdefghijklmno', [])).toBe('$2b$10$abcdefghijklmno');
|
||||
});
|
||||
|
||||
/*
|
||||
* The visitor's unlock cookie signs the stored value. The admin form re-sends
|
||||
* the plaintext after a save; a fresh salt each time would sign everyone out.
|
||||
*/
|
||||
it('keeps an existing hash when the plaintext still matches it', async () => {
|
||||
const existing = await generateScryptHash('secret');
|
||||
expect(await hashPassword('secret', [existing])).toBe(existing);
|
||||
expect(await hashPassword('other', [existing])).not.toBe(existing);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hashPasswordKeys', () => {
|
||||
it('hashes every password in a gallery, however deep, and nothing else', async () => {
|
||||
const gallery = {
|
||||
albums: [{ 'album-1': { title: 'Kyoto', password: 'a' } }],
|
||||
subpages: [
|
||||
{
|
||||
name: 'Clients',
|
||||
password: 'b',
|
||||
sections: [{ title: 'S', albums: [{ 'album-2': { password: 'c' } }] }],
|
||||
},
|
||||
],
|
||||
};
|
||||
const out = await hashPasswordKeys(gallery, KEY, null);
|
||||
const albums = out.albums as Array<Record<string, { title: string; password: string }>>;
|
||||
const section = (
|
||||
out.subpages[0].sections![0].albums as Array<Record<string, { password: string }>>
|
||||
)[0];
|
||||
expect(albums[0]['album-1'].password).toMatch(/^scrypt:/);
|
||||
expect(albums[0]['album-1'].title).toBe('Kyoto');
|
||||
expect(out.subpages[0].password).toMatch(/^scrypt:/);
|
||||
expect(section['album-2'].password).toMatch(/^scrypt:/);
|
||||
// The input is not mutated.
|
||||
expect(gallery.subpages[0].password).toBe('b');
|
||||
});
|
||||
|
||||
it('reuses a hash from the file on disk, wherever the entry moved to', async () => {
|
||||
const onDisk = { subpages: [{ name: 'A', password: await generateScryptHash('b') }] };
|
||||
const out = await hashPasswordKeys(
|
||||
{ subpages: [{ name: 'Renamed', password: 'b' }] },
|
||||
KEY,
|
||||
onDisk,
|
||||
);
|
||||
expect(out.subpages[0].password).toBe(onDisk.subpages[0].password);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hashFrontmatterPassword', () => {
|
||||
const entry = (pw: string) =>
|
||||
`---\ntitle: "Price: $5 & more"\npassword: ${pw}\ndraft: true\n---\n\nBody with password: not-this\n`;
|
||||
|
||||
it('hashes only the frontmatter line and leaves the rest byte for byte', async () => {
|
||||
const out = await hashFrontmatterPassword(entry('secret'), null);
|
||||
const line = out.match(/^password: "(scrypt:[^"]+)"$/m)!;
|
||||
expect(await verifyScrypt('secret', line[1])).toBe(true);
|
||||
expect(out).toContain('title: "Price: $5 & more"');
|
||||
expect(out).toContain('Body with password: not-this');
|
||||
});
|
||||
|
||||
it('understands quoted values and keeps the previous hash when unchanged', async () => {
|
||||
const previous = await hashFrontmatterPassword(entry('secret'), null);
|
||||
const again = await hashFrontmatterPassword(entry('"secret"'), previous);
|
||||
expect(again).toBe(previous);
|
||||
});
|
||||
|
||||
it('leaves an entry without a password untouched', async () => {
|
||||
const md = '---\ntitle: Open\n---\n\nText\n';
|
||||
expect(await hashFrontmatterPassword(md, null)).toBe(md);
|
||||
});
|
||||
});
|
||||
97
lib/__tests__/preset-contrast.test.ts
Normal file
97
lib/__tests__/preset-contrast.test.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import {
|
||||
THEME_PRESETS,
|
||||
resolveTheme,
|
||||
accentForMode,
|
||||
onAccent,
|
||||
contrastRatio,
|
||||
} from '../config/theme';
|
||||
|
||||
/**
|
||||
* Every preset's accent must stay visible on its own page background in both
|
||||
* colour modes, and text on an accent-filled button must stay readable. Minimal
|
||||
* shipped a black accent on its black dark mode: the password gate's button and
|
||||
* the error page's "Try again" were invisible.
|
||||
*
|
||||
* The backgrounds are read from app/tokens.css, so a palette change that breaks
|
||||
* an accent fails here too.
|
||||
*/
|
||||
const css = fs.readFileSync(path.join(process.cwd(), 'app', 'tokens.css'), 'utf8');
|
||||
|
||||
function bgPrimary(selector: string): string | undefined {
|
||||
const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const block = new RegExp(`${escaped}\\s*\\{([^}]*)\\}`).exec(css)?.[1];
|
||||
return block ? /--bg-primary:\s*(#[0-9a-fA-F]{3,6})/.exec(block)?.[1] : undefined;
|
||||
}
|
||||
|
||||
const defaults = { dark: bgPrimary(':root')!, light: bgPrimary("[data-theme='light']")! };
|
||||
|
||||
function background(preset: string, mode: 'dark' | 'light'): string {
|
||||
const own =
|
||||
mode === 'dark'
|
||||
? bgPrimary(`[data-preset='${preset}']`)
|
||||
: bgPrimary(`[data-preset='${preset}'][data-theme='light']`);
|
||||
return own ?? defaults[mode];
|
||||
}
|
||||
|
||||
// 3:1 is WCAG's floor for UI components and large text (non-text contrast,
|
||||
// 1.4.11); the accent draws dots, rules, active states and button fills.
|
||||
const ACCENT_MIN = 3;
|
||||
const BUTTON_TEXT_MIN = 4.5;
|
||||
|
||||
describe('preset accent contrast', () => {
|
||||
it('finds a background for every preset and mode', () => {
|
||||
expect(defaults.dark).toBeDefined();
|
||||
expect(defaults.light).toBeDefined();
|
||||
});
|
||||
|
||||
for (const name of Object.keys(THEME_PRESETS)) {
|
||||
for (const mode of ['dark', 'light'] as const) {
|
||||
it(`${name} (${mode}): accent is visible on the page`, () => {
|
||||
const accent = accentForMode(resolveTheme(name), mode);
|
||||
const ratio = contrastRatio(accent, background(name, mode))!;
|
||||
expect(ratio).toBeGreaterThanOrEqual(ACCENT_MIN);
|
||||
});
|
||||
|
||||
it(`${name} (${mode}): button text is readable on the accent`, () => {
|
||||
const accent = accentForMode(resolveTheme(name), mode);
|
||||
expect(contrastRatio(onAccent(accent), accent)!).toBeGreaterThanOrEqual(BUTTON_TEXT_MIN);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('per-mode accents', () => {
|
||||
it('apply while the owner keeps the preset accent', () => {
|
||||
const theme = resolveTheme({ preset: 'minimal', accent: '#000000' });
|
||||
expect(accentForMode(theme, 'dark')).toBe('#ffffff');
|
||||
expect(accentForMode(theme, 'light')).toBe('#000000');
|
||||
});
|
||||
|
||||
it('give way to an accent of the owner’s own, in both modes', () => {
|
||||
const theme = resolveTheme({ preset: 'minimal', accent: '#0055ff' });
|
||||
expect(accentForMode(theme, 'dark')).toBe('#0055ff');
|
||||
expect(accentForMode(theme, 'light')).toBe('#0055ff');
|
||||
});
|
||||
|
||||
it('fall back to the single accent where a preset has none', () => {
|
||||
const theme = resolveTheme('studio-modern');
|
||||
expect(accentForMode(theme, 'dark')).toBe(theme.accent);
|
||||
expect(accentForMode(theme, 'light')).toBe(theme.accent);
|
||||
});
|
||||
});
|
||||
|
||||
describe('onAccent', () => {
|
||||
it('picks the stronger of black and white', () => {
|
||||
expect(onAccent('#000000')).toBe('#ffffff');
|
||||
expect(onAccent('#ffffff')).toBe('#000000');
|
||||
expect(onAccent('#c49a3c')).toBe('#000000');
|
||||
expect(onAccent('#e60012')).toBe('#ffffff');
|
||||
});
|
||||
|
||||
it('keeps white for a colour it cannot parse', () => {
|
||||
expect(onAccent('rebeccapurple')).toBe('#ffffff');
|
||||
});
|
||||
});
|
||||
89
lib/__tests__/privacy.test.ts
Normal file
89
lib/__tests__/privacy.test.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { parseMarkdownBlocks } from '../markdownBlocks';
|
||||
import { privacyAvailable, processingFacts, starterHeadings } from '../privacy';
|
||||
import type { AppConfig } from '../config/schema';
|
||||
|
||||
describe('parseMarkdownBlocks', () => {
|
||||
it('reads headings, lists and paragraphs', () => {
|
||||
const blocks = parseMarkdownBlocks(
|
||||
'# Datenschutz\n\nErster Satz\nzweiter Satz.\n\n### Detail\n- eins\n- **zwei**\n\n1. a\n2. b',
|
||||
);
|
||||
expect(blocks).toEqual([
|
||||
{ type: 'heading', level: 2, html: 'Datenschutz' },
|
||||
{ type: 'paragraph', html: 'Erster Satz zweiter Satz.' },
|
||||
{ type: 'heading', level: 3, html: 'Detail' },
|
||||
{ type: 'list', ordered: false, items: ['eins', '<strong>zwei</strong>'] },
|
||||
{ type: 'list', ordered: true, items: ['a', 'b'] },
|
||||
]);
|
||||
});
|
||||
|
||||
it('escapes the author text before adding its own tags', () => {
|
||||
const [p] = parseMarkdownBlocks('<script>alert(1)</script> [x](javascript:alert(1))');
|
||||
const html = p.type === 'paragraph' ? p.html : '';
|
||||
expect(html).toContain('<script>');
|
||||
expect(html).not.toContain('<script');
|
||||
expect(html).not.toContain('<a ');
|
||||
});
|
||||
});
|
||||
|
||||
const config = (over: Partial<AppConfig> = {}) =>
|
||||
({
|
||||
map: false,
|
||||
analytics: false,
|
||||
contact: { enabled: false, retentionDays: 90 },
|
||||
proofing: { enabled: false },
|
||||
privacy: { enabled: true },
|
||||
...over,
|
||||
}) as unknown as AppConfig;
|
||||
|
||||
describe('processingFacts', () => {
|
||||
it('lists only what this installation actually does', () => {
|
||||
const topics = processingFacts(config(), { hasPasswords: false }).map((f) => f.topic);
|
||||
expect(topics).toEqual(['Photos', 'Server log', 'Fonts', 'Browser storage']);
|
||||
});
|
||||
|
||||
it('names third parties for the map, the notification host and a CDN', () => {
|
||||
const facts = processingFacts(
|
||||
config({
|
||||
map: true,
|
||||
contact: { enabled: true, retentionDays: 30, notifyUrl: 'https://ntfy.sh/secret' },
|
||||
}),
|
||||
{ hasPasswords: true, CDN_URL: 'https://cdn.example.net' },
|
||||
);
|
||||
const third = facts.filter((f) => f.thirdParty).map((f) => f.topic);
|
||||
// The notification carries nothing about the sender (#702), so the
|
||||
// contact form is not a third-party transfer.
|
||||
expect(third).toEqual(['Map', 'CDN']);
|
||||
const contact = facts.find((f) => f.topic === 'Contact form')!;
|
||||
expect(contact.detail).toContain('30 days');
|
||||
// The host, never the topic path: the topic name is the secret.
|
||||
expect(contact.detail).toContain('ntfy.sh');
|
||||
expect(contact.detail).not.toContain('secret');
|
||||
expect(facts.some((f) => f.topic === 'Cookies')).toBe(true);
|
||||
});
|
||||
|
||||
it('turns the facts into headings in the site language, and nothing else', () => {
|
||||
const facts = processingFacts(config({ map: true }), { hasPasswords: false });
|
||||
const de = starterHeadings('de', facts);
|
||||
expect(de).toContain('## Kartendienst');
|
||||
expect(de).not.toContain('Kontaktformular');
|
||||
expect(de.split('\n').filter((l) => l && !l.startsWith('## '))).toEqual([]);
|
||||
expect(starterHeadings('en', facts)).toContain('## Your rights');
|
||||
});
|
||||
});
|
||||
|
||||
describe('privacyAvailable', () => {
|
||||
it('needs the switch on and text in the file', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'folio-privacy-'));
|
||||
expect(privacyAvailable(config(), dir)).toBe(false);
|
||||
fs.writeFileSync(path.join(dir, 'privacy.md'), ' \n');
|
||||
expect(privacyAvailable(config(), dir)).toBe(false);
|
||||
fs.writeFileSync(path.join(dir, 'privacy.md'), '## Text\n');
|
||||
expect(privacyAvailable(config(), dir)).toBe(true);
|
||||
expect(privacyAvailable(config({ privacy: { enabled: false } }), dir)).toBe(false);
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
});
|
||||
@@ -12,11 +12,27 @@ vi.mock('@/lib/auth', () => ({
|
||||
isSiteUnlocked: vi.fn(() => true),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/cdn', () => ({
|
||||
cdnOrigin: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
// Null by default: isKnownMissing() then leaves every path to the page.
|
||||
vi.mock('@/lib/config', () => ({
|
||||
getConfigOrNull: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
import { isSiteUnlocked } from '@/lib/auth';
|
||||
import { cdnOrigin } from '@/lib/cdn';
|
||||
import { tryToParsePath } from 'next/dist/lib/try-to-parse-path';
|
||||
import { proxy, config } from '@/proxy';
|
||||
import { proxy, config, isKnownMissing } from '@/proxy';
|
||||
import { getConfigOrNull } from '@/lib/config';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const mockUnlocked = isSiteUnlocked as unknown as ReturnType<typeof vi.fn>;
|
||||
const mockCdnOrigin = cdnOrigin as unknown as ReturnType<typeof vi.fn>;
|
||||
const mockConfig = getConfigOrNull as unknown as ReturnType<typeof vi.fn>;
|
||||
|
||||
// Next.js 16 renamed the "middleware" file convention to "proxy": the file must
|
||||
// be proxy.ts and must export proxy(), not middleware(). A silent regression here
|
||||
@@ -27,6 +43,28 @@ describe('proxy', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
mockUnlocked.mockReturnValue(true);
|
||||
mockCdnOrigin.mockReturnValue(null);
|
||||
});
|
||||
|
||||
describe('CDN mode', () => {
|
||||
it('leaves the policy untouched without a CDN', () => {
|
||||
const csp = run().headers.get('Content-Security-Policy')!;
|
||||
expect(csp).not.toContain('media-src');
|
||||
});
|
||||
|
||||
it('allows the CDN origin for images and video', () => {
|
||||
mockCdnOrigin.mockReturnValue('https://cdn.example.net');
|
||||
const csp = run().headers.get('Content-Security-Policy')!;
|
||||
const directive = (name: string) =>
|
||||
csp
|
||||
.split(';')
|
||||
.map((d) => d.trim())
|
||||
.find((d) => d.startsWith(`${name} `));
|
||||
expect(directive('img-src')).toContain('https://cdn.example.net');
|
||||
expect(directive('media-src')).toBe("media-src 'self' https://cdn.example.net");
|
||||
// Scripts never come from the CDN.
|
||||
expect(directive('script-src')).not.toContain('cdn.example.net');
|
||||
});
|
||||
});
|
||||
|
||||
it('is exported under the name Next.js 16 expects', () => {
|
||||
@@ -229,3 +267,61 @@ describe('proxy', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/*
|
||||
* app/loading.tsx makes every page stream, so notFound() in a page can no
|
||||
* longer change the 200 that was already sent. Routes whose existence the
|
||||
* proxy can decide on its own get the 404 before streaming starts.
|
||||
*/
|
||||
describe('isKnownMissing', () => {
|
||||
let contentDir: string;
|
||||
const settings = {
|
||||
contact: { enabled: false },
|
||||
legal: { enabled: true },
|
||||
map: false,
|
||||
privacy: { enabled: true },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
contentDir = fs.mkdtempSync(path.join(os.tmpdir(), 'folio-proxy-'));
|
||||
fs.mkdirSync(path.join(contentDir, 'journal'));
|
||||
fs.writeFileSync(path.join(contentDir, 'journal', 'kyoto.md'), '---\ntitle: Kyoto\n---\n');
|
||||
mockConfig.mockReturnValue(settings);
|
||||
});
|
||||
|
||||
it('knows the pages that are switched off in settings', () => {
|
||||
expect(isKnownMissing('/contact', contentDir)).toBe(true);
|
||||
expect(isKnownMissing('/map', contentDir)).toBe(true);
|
||||
expect(isKnownMissing('/impressum', contentDir)).toBe(false);
|
||||
});
|
||||
|
||||
it('knows /privacy by its switch and its file', () => {
|
||||
expect(isKnownMissing('/privacy', contentDir)).toBe(true);
|
||||
fs.writeFileSync(path.join(contentDir, 'privacy.md'), '## Datenschutz\n');
|
||||
expect(isKnownMissing('/privacy', contentDir)).toBe(false);
|
||||
});
|
||||
|
||||
it('knows a journal entry by its file, and rejects slugs that are not slugs', () => {
|
||||
expect(isKnownMissing('/journal/kyoto', contentDir)).toBe(false);
|
||||
expect(isKnownMissing('/journal/osaka', contentDir)).toBe(true);
|
||||
expect(isKnownMissing('/journal/..%2Fsettings', contentDir)).toBe(true);
|
||||
});
|
||||
|
||||
it('leaves album and subpage slugs to the page, which needs Immich to decide', () => {
|
||||
expect(isKnownMissing('/japan', contentDir)).toBe(false);
|
||||
expect(isKnownMissing('/japan/tokyo', contentDir)).toBe(false);
|
||||
});
|
||||
|
||||
it('decides nothing when the config cannot be read', () => {
|
||||
mockConfig.mockReturnValue(null);
|
||||
expect(isKnownMissing('/contact', contentDir)).toBe(false);
|
||||
});
|
||||
|
||||
it('makes proxy() answer 404 with the policy still set', () => {
|
||||
const res = proxy(new NextRequest('https://example.com/contact'));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.headers.get('Content-Security-Policy')).toBeTruthy();
|
||||
mockConfig.mockReturnValue(null);
|
||||
expect(proxy(new NextRequest('https://example.com/contact')).status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -82,6 +82,12 @@ describe('resolveSiteUrl', () => {
|
||||
});
|
||||
|
||||
describe('absoluteUrl', () => {
|
||||
it('passes an already absolute URL through — a photo on the CDN', () => {
|
||||
const cdn = 'https://cdn.example.net/api/image/v2:abc?size=preview';
|
||||
expect(absoluteUrl('https://folio.example', cdn)).toBe(cdn);
|
||||
expect(absoluteUrl(null, cdn)).toBe(cdn);
|
||||
});
|
||||
|
||||
it('joins a path', () => {
|
||||
expect(absoluteUrl('https://folio.example', '/travel')).toBe('https://folio.example/travel');
|
||||
});
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { resolveTheme, THEME_PRESETS, DEFAULT_PRESET } from '@/lib/config/theme';
|
||||
import {
|
||||
resolveTheme,
|
||||
accentForMode,
|
||||
onAccent,
|
||||
THEME_PRESETS,
|
||||
DEFAULT_PRESET,
|
||||
} from '@/lib/config/theme';
|
||||
|
||||
/**
|
||||
* `radius` reaches CSS as `${radius}px` and `${radius * 1.5}px` (app/layout.tsx),
|
||||
@@ -45,6 +51,41 @@ describe('resolveTheme scalar coercion (#633)', () => {
|
||||
expect(resolveTheme({ accent: '#123456' }).accent).toBe('#123456');
|
||||
});
|
||||
|
||||
it('normalises a 3-digit accent to the #rrggbb every consumer survives', () => {
|
||||
expect(resolveTheme({ accent: '#f00' }).accent).toBe('#ff0000');
|
||||
expect(resolveTheme({ accent: '#FFF' }).accent).toBe('#ffffff');
|
||||
});
|
||||
|
||||
it('normalises an 8-digit accent by dropping the alpha', () => {
|
||||
expect(resolveTheme({ accent: '#e6001280' }).accent).toBe('#e60012');
|
||||
});
|
||||
|
||||
it('trims surrounding whitespace from an accent', () => {
|
||||
expect(resolveTheme({ accent: ' #e60012 ' }).accent).toBe('#e60012');
|
||||
});
|
||||
|
||||
it('falls back to the preset accent for a hex literal without the #', () => {
|
||||
// The nastiest input: defined, so var() substitutes it and any accent-
|
||||
// backed background becomes transparent instead of taking its fallback.
|
||||
expect(resolveTheme({ accent: 'e60012' }).accent).toBe(base.accent);
|
||||
});
|
||||
|
||||
it('falls back to the preset accent for a 5-digit hex', () => {
|
||||
expect(resolveTheme({ accent: '#12345' }).accent).toBe(base.accent);
|
||||
});
|
||||
|
||||
it('falls back to the preset accent for named and functional colours', () => {
|
||||
// They would render, but onAccent() reads only hex and would answer white.
|
||||
expect(resolveTheme({ accent: 'red' }).accent).toBe(base.accent);
|
||||
expect(resolveTheme({ accent: 'rgb(230 0 18)' }).accent).toBe(base.accent);
|
||||
});
|
||||
|
||||
it('gives a white accent dark button text, the proofing ZIP button included', () => {
|
||||
// #ffffff on the light theme rendered Download selected white-on-white.
|
||||
const theme = resolveTheme({ accent: '#FFF' });
|
||||
expect(onAccent(accentForMode(theme, 'light'))).toBe('#000000');
|
||||
});
|
||||
|
||||
it('falls back to the preset grain/headerDot when not a boolean', () => {
|
||||
const theme = resolveTheme({
|
||||
grain: 'yes' as unknown as boolean,
|
||||
|
||||
Reference in New Issue
Block a user