From 77c71856132b5c2ff5706dfa2194dded92c4da58 Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:25:22 +0100 Subject: [PATCH 1/3] M29, second part: stories for visitors /stories and /stories/{id} start from VisibleStories and show parts only through VisibleStoryBlocks; a draft, a binned, an all-hidden and an unknown story answer the same 404. Start page section, sitemap entries without lastmod, link preview with title and summary only, covers from visible items in two queries, the item card split out of _ItemCards. Tests for the visibility matrix, the 404, time, deletion, the public accessibility runs; security.md rows, German entries, changelog. The demo story is published. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- CHANGELOG.md | 12 +- docs/development.md | 5 + docs/security.md | 8 +- src/Commonage.Web/Data/VisibleStoryBlocks.cs | 31 ++ src/Commonage.Web/Demo/DemoContent.cs | 7 +- src/Commonage.Web/Pages/Index.cshtml | 12 + src/Commonage.Web/Pages/Index.cshtml.cs | 10 + .../Pages/Shared/_ItemCard.cshtml | 28 ++ .../Pages/Shared/_ItemCards.cshtml | 26 +- .../Pages/Shared/_StoryBody.cshtml | 2 +- .../Pages/Shared/_StoryCards.cshtml | 29 ++ .../Pages/Stories/Details.cshtml | 18 + .../Pages/Stories/Details.cshtml.cs | 35 ++ src/Commonage.Web/Pages/Stories/Index.cshtml | 17 + .../Pages/Stories/Index.cshtml.cs | 18 + .../Resources/SharedResource.de.resx | 2 + .../Resources/SharedResource.resx | 2 + src/Commonage.Web/Search/PublicFeeds.cs | 10 + src/Commonage.Web/Search/StoryCards.cs | 47 ++ src/Commonage.Web/wwwroot/css/site.css | 9 - .../AccessibilityTests.cs | 4 +- .../StoryBrowserTests.cs | 18 + tests/Commonage.Tests/EndpointAccessTests.cs | 2 +- .../StoryVisibilityMatrixTests.cs | 443 ++++++++++++++++++ 24 files changed, 751 insertions(+), 44 deletions(-) create mode 100644 src/Commonage.Web/Pages/Shared/_ItemCard.cshtml create mode 100644 src/Commonage.Web/Pages/Shared/_StoryCards.cshtml create mode 100644 src/Commonage.Web/Pages/Stories/Details.cshtml create mode 100644 src/Commonage.Web/Pages/Stories/Details.cshtml.cs create mode 100644 src/Commonage.Web/Pages/Stories/Index.cshtml create mode 100644 src/Commonage.Web/Pages/Stories/Index.cshtml.cs create mode 100644 src/Commonage.Web/Search/StoryCards.cs create mode 100644 tests/Commonage.Tests/StoryVisibilityMatrixTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 24179b2..d55d9b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,14 +5,22 @@ version may change things that need attention when updating, and these notes say ## Unreleased +### For visitors + +- **Stories, second part.** Published stories are public. `/stories` lists them with a picture and a few words, the start + page shows the first three, and `/stories/{number}` reads one: the curator's texts, and the items of the story as cards with + the curator's captions. An item that visitors may not see (a draft, not yet public, in the bin, withdrawn) is left out + without a trace, and a story with nothing to read answers "not found" like an unknown page. A record-only item has no picture. + The sitemap lists the stories. A link to a story shows its title and its summary, no picture and nothing from an item. + Stories are not in the feed or in search. The demo archive's story is published. + ### For curators - **Stories, first part.** Under "Stories" in the admin area, curators write a story: a title, a few words of summary, and parts in order, each a text or one of the items of the archive with a caption. A story can be moved up and down in the list, and its parts within it, with buttons that work without JavaScript and keep the place on the page. The preview shows it as visitors will see it: a part with an item that is not public is left out. A story with parts that visitors cannot - see says so on the page, only here. Publishing a story changes nothing for visitors yet; the public pages come in a later - part. Helpers do not see stories. + see says so on the page, only here. Helpers do not see stories. - **Export format 9** has `stories` after `items`. An export of published items has only published stories and the parts whose item is in it. An import counts the stories in the dry run and does not import them. The demo archive has a story. diff --git a/docs/development.md b/docs/development.md index 13149dc..de95e11 100644 --- a/docs/development.md +++ b/docs/development.md @@ -142,6 +142,11 @@ the request, so behind Caddy they depend on `ASPNETCORE_FORWARDEDHEADERS_ENABLED tries that setting. Text goes into XML through `XmlText`, because one pasted control character would make a whole feed unreadable. `ArchiveItem.MayTravel` decides what goes along with a link, and it needs the contribution to be loaded. +Stories (`Pages/Stories`, `Search/StoryCards.cs`): public pages start from `db.VisibleStories` and read parts only through +`VisibleStoryBlocks` (`LoadAsync` for the page, `CoversAsync` for the list). `_StoryBody` is shared with the curator preview and +must stay free of ids, anchors and `data-` attributes; `_ItemCard` is the one item card, also used by `_ItemCards`. The link +preview of a story has no image and no item text, and the sitemap has no `lastmod` for stories. + `Search/PublicItemRecord.cs` is what an item says to programs: `/items/{id}.json` and the `DC.*` tags (`Pages/Shared/_DublinCore.cshtml`, written by the layout when the page set `ViewData["Record"]`). `PublicItemRecord` is an allow-list: add a field there on purpose, and never serialise `ArchiveItem` or `MediaFile`. It follows the link-preview rules, so description and files go with `MayTravel`, diff --git a/docs/security.md b/docs/security.md index 7398f9f..ae2403b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -29,7 +29,9 @@ vulnerability, see [SECURITY.md](../SECURITY.md). | Import | Only curators (the `/Admin` policy). The sheet and ZIP are kept in `import-staging` on the media volume, which is never served by path, for a day at most. A sheet is read as strict UTF-8, at most 20 MB and 100,000 rows; a ZIP at most 4 GB and 200,000 entries; every entry is counted as it is unpacked into a temporary file, and a name inside it is never used in a path. A folder to import from is chosen from a listing of `import/`, links and hidden files are skipped. Files go through the same checks as an upload. One import at a time. Everything imported is a draft; the activity log records each item and the import, never the spreadsheet or the contributors' details. `ImportTests`. | | Reading an export | Admins only (`Administer`), the dry run is `private, no-store`. Same staging folder, one-at-a-time lock and file checks as the spreadsheet import; the ZIP is at most 4 GB and 200,000 entries, `archive.json` at most 256 MB counted as it is unpacked (a ZIP entry's declared size is not trusted), parsed with a depth limit and capped lists (20,000 items, 5,000 collections, 50,000 tags, 500 files per item, 100,000 files in all), at most 8 GB of files in all, 50 new collections per run and 10,000 recorded lines in the dry run (the rest is counted). A file is taken only under the exact path `files//-`, unique, never by name and never as a path on disk; its type and size are found from the bytes and its sha256 must match. Unknown values are lines in the dry run, not exceptions. **Decision on consent:** a contributor's name, email address, consent text, rights statement and reference code, visitor notes, internal notes and received-from are never deserialised or stored (`ExportImportTable` decides every property of the export, and `ExportImportTests` fails when the exporter gains one without a decision); only whether the contributor agreed to sharing is read, and an item with a contribution that does not say yes (no, null or no answer at all), or one rejected or withdrawn, is left out. The ZIP is staged in a folder and file only the app's account can read (Linux and macOS), and a file that cannot be stored costs only that file, counted without the error text; the run is not cancelled by closing the tab. Everything arrives as a draft, whatever its status, and the code only inserts (a test reads the source for publishing, removing and unfiltered queries). `ExportImportTests`. | | Earlier texts | `ItemRevisions` keeps what a title, description, date, credit, original location or reference number said before a change, with the account that changed it (its name at the time) and when. The fields are a fixed list (`RevisionField`): never a contributor's name or email, the internal notes or where an item was received from, so removing a contributor's details never has to touch it. Who changed it is forgotten on the activity log's schedule (`ActivityLogKeptYears`); the text itself stays with the item. Shown on the item's admin page only; a curator may restore, a helper only reads. The rows go with their item (cascade, hidden while it is in the bin) and are not exported. `RevisionTests`, `ExportTests`. | -| Stories | Curators and admins only (`ManageArchive`; a helper gets 403 on every page and handler). A story is text and item parts in a chosen order; part 1 has no public page. What visitors will be able to see is decided in one place: `Visibility.Story` and `VisibleStoryBlocks` (a published story, and only the parts whose item passes `Visibility.Item` with the day; a story with no visible part is as hidden as a draft). The curator pages show hidden items to curators only and say why visitors do not see them. Input is limited on the server (title 200, summary 1,000, text 20,000, caption 1,000 characters, 200 parts per story); an item is added by number or by a page address on this site, never by path. Block handlers are scoped to their story and never save the story row. Accepted: a removed part is deleted at once (the bin covers whole stories, from part 3; the confirmation says so). The export lists stories (`stories`, format 9): a copy of what is public holds published stories with only parts whose item is in the copy, a full copy holds drafts, and the bin is never exported. The import only counts stories (`StoryCountConverter` skips them) and creates nothing. `StoryEditTests`, `VisibilityGuardTests`, `ExportTests`, `ExportImportTests`. | +| Stories | Curators and admins only (`ManageArchive`; a helper gets 403 on every page and handler). A story is text and item parts in a chosen order. What visitors see is decided in one place: `Visibility.Story` and `VisibleStoryBlocks` (a published story, and only the parts whose item passes `Visibility.Item` with the day; a story with no visible part is as hidden as a draft). The curator pages show hidden items to curators only and say why visitors do not see them. Input is limited on the server (title 200, summary 1,000, text 20,000, caption 1,000 characters, 200 parts per story); an item is added by number or by a page address on this site, never by path. Block handlers are scoped to their story and never save the story row. Accepted: a removed part is deleted at once (the bin covers whole stories, from part 3; the confirmation says so). The export lists stories (`stories`, format 9): a copy of what is public holds published stories with only parts whose item is in the copy, a full copy holds drafts, and the bin is never exported. The import only counts stories (`StoryCountConverter` skips them) and creates nothing. `StoryEditTests`, `VisibilityGuardTests`, `ExportTests`, `ExportImportTests`. | +| Stories on the website | `/stories` and `/stories/{id}` start from `VisibleStories` (published, not in the bin, at least one visible part) and show parts only through `VisibleStoryBlocks`, which loads items through `VisibleItems`; a story page never follows a part to its item (`VisibilityGuardTests` reads the source). A draft, a story in the bin, one whose parts are all hidden and an unknown number answer the same 404 (same body and headers, `StoryVisibilityMatrixTests`). A part that is left out leaves nothing behind: no id, position, anchor, `data-` attribute, caption, placeholder, count or "n of m" in the public page (`_StoryBody` has none, and the page equals the page without the part, also with a hidden part between two visible ones). The list, its total, its paging (24 a page) and its covers (two queries for all stories of a page) are computed from visible rows only, so a hidden story changes nothing about them. The cover is a visible item's thumbnail, never of a record-only item. Block changes never save the story row, so there is no "updated" date, no `lastmod` in the sitemap and no `ETag` or `Last-Modified` from block or item data. The start page shows the first three, without a count. `StoryVisibilityMatrixTests`, `EndpointAccessTests`, `AccessibilityTests`. | +| Stories beyond the website | The link preview of a story has its title and its summary and nothing else: no picture (a cover never goes into `og:image`; an item's rights and consent may not allow it to travel), no item title, id or caption, and no description when the summary is empty (never the first lines of a part). Stories are not in `/feed.xml`, `/search`, the JSON or Dublin Core. The sitemap lists `/stories` and each visible story, without a date, and follows `AllowSearchEngines`. A contributor who did not agree to sharing beyond the website has their item shown in a story on the website like anywhere else, and nothing of it in the preview or the feed. `StoryVisibilityMatrixTests`. | | Recordings | Only curators can add a recording (MP3, M4A, WAV, FLAC, recognised by their first bytes); contribution links refuse them. Visitors hear only a copy made by the app itself (`AudioTools`, no outside program): the sound is copied byte for byte, and ID3v2/ID3v1/APE tags (MP3), `udta`, `meta`, `uuid` and padding boxes and the dates in the headers (M4A), every chunk except `fmt `, `fact` and `data` (WAV), and every block except stream info and the seek table (FLAC) are left out. A file that is not built as its type says (impossible sizes, missing parts, fragmented M4A) fails and has no copy, so nothing is ever served untouched. The parser is managed code reading sizes against the file's length, with the header of an M4A limited to 64 MB; it runs on the single preview queue and a failure marks only that file. Served for published items only, from `/media/{id}/audio` with range requests, with its own copy (`audio/…` key); the original is only at `/admin/media/{id}/original` for curators. Accepted: the sound itself may contain a voice that identifies someone, which is what an oral history is; curators decide what to publish. `AudioTests`. | | PDF files | Only curators can add a PDF; contribution links refuse it. A PDF is recognised by `%PDF-` and read by poppler (`pdfinfo`, `pdftoppm`), a large C++ parser, so it runs as separate processes, never inside the app: each call has a time limit (`Uploads:PdfTimeoutSeconds`, 60) and is killed with its children when it takes longer, the size of the drawn picture is set by us with `-scale-to` whatever size the page claims, at most 300 pages are drawn, and no part of the file or its name reaches a command line (arguments are passed as a list, the file is copied to a random name in an owner-only temporary folder that is removed afterwards). Pages are served only for published items; the PDF stays private. Accepted: a hostile PDF made by a curator could still exploit poppler, which runs with the app's rights in the container; build with `WITH_PDF=false` to remove it. `poppler-utils` comes from the distribution at build time and is not pinned to a version, so a rebuild of the same commit can ship another poppler (accepted; the base image digest is pinned). The text of a PDF (`pdftotext`, same limits, control characters removed, at most 200,000 characters) is only matched by search, never shown, and it is in the index only while the item is not in the bin and the PDF is not in the bin; a draft is found only by curators, as before. The preview queue is single, so a very long PDF delays other previews (at most 60 s per page); copies of a PDF left by a stopped app are removed at the next start. | | Uploads | Files are recognised by their content (magic bytes), never by name or browser type, and stored under random names outside the web root. Originals are never changed or served to visitors. Previews are made by libvips, rotated upright and stripped of all metadata. Images over 250 megapixels get no preview (decompression bombs), also for GIF and AVIF (`Images_with_more_pixels_than_the_limit_get_no_preview`). GIF and AVIF (libheif with an AV1 decoder, from M23) are further decoders reachable from a contribution link; a GIF is read as its first frame only. There is no time limit on a decode, so a very large AVIF costs memory and time on a small server; the pixel limit and the three-attempt guard are the protection. Size limits per file and per request. A file that the preview maker fails on, in whatever way, costs only its own preview, and one that takes the app down is given up after three attempts instead of at every start (`PreviewFailureTests`). | @@ -71,6 +73,10 @@ server updated and its access limited is what protects against that. the same care as the server. - **The login page reveals whether an account exists** when it has been locked after wrong passwords ("too many failed attempts"). +- **Story texts and captions are the curators' words and are not checked.** A caption or a text can name a hidden item or + person; only the part of a hidden item is left out, never what a curator wrote elsewhere. Story numbers are sequential, + so a gap between two stories can be seen, as for items. The sitemap may list a story that has just been hidden, or lack + one that has just been published, for up to ten minutes. - **Deleted material stays for 30 days.** Items and photos in the bin keep their files and personal data until they are deleted for good, which curators can do at once when someone asks for removal. - **The default privacy text is a template**, describing what Commonage stores. Each group has to adapt it and check its diff --git a/src/Commonage.Web/Data/VisibleStoryBlocks.cs b/src/Commonage.Web/Data/VisibleStoryBlocks.cs index 0c07e96..a912f6d 100644 --- a/src/Commonage.Web/Data/VisibleStoryBlocks.cs +++ b/src/Commonage.Web/Data/VisibleStoryBlocks.cs @@ -53,6 +53,37 @@ public static async Task> LoadAsync(CommonageDbContext db, return result; } + + /// + /// The picture each story shows in a list: that of its first block whose item visitors may see and that has a picture (never + /// one for a record-only item). Two queries for all , whatever their number. A story without such a + /// block is not in the result. + /// + public static async Task> CoversAsync(CommonageDbContext db, IReadOnlyCollection storyIds, CancellationToken ct = default) + { + if (storyIds.Count == 0) + return []; + + var blocks = await db.StoryBlocks.AsNoTracking() + .Where(b => storyIds.Contains(b.StoryId) && b.Kind == StoryBlockKind.Item && b.ArchiveItemId != null) + .Join(db.VisibleItems, b => b.ArchiveItemId!.Value, i => i.Id, (b, i) => new { b.StoryId, b.Position, BlockId = b.Id, ItemId = i.Id }) + .OrderBy(b => b.StoryId).ThenBy(b => b.Position).ThenBy(b => b.BlockId) + .ToListAsync(ct); + var itemIds = blocks.Select(b => b.ItemId).Distinct().ToList(); + if (itemIds.Count == 0) + return []; + + var pictures = await db.VisibleItems + .Where(i => itemIds.Contains(i.Id)) + .Select(ItemSummary.FromItem) + .ToDictionaryAsync(i => i.Id, i => i.ThumbnailMediaFileId, ct); + + var covers = new Dictionary(); + foreach (var block in blocks) + if (!covers.ContainsKey(block.StoryId) && pictures.TryGetValue(block.ItemId, out var picture) && picture is { } file) + covers[block.StoryId] = file; + return covers; + } } /// What the shared story partial shows: the words of a story and the blocks visitors may see. diff --git a/src/Commonage.Web/Demo/DemoContent.cs b/src/Commonage.Web/Demo/DemoContent.cs index 8b8aa67..3aec65b 100644 --- a/src/Commonage.Web/Demo/DemoContent.cs +++ b/src/Commonage.Web/Demo/DemoContent.cs @@ -170,14 +170,15 @@ await AddPhotoAsync(letter, "letter-page-2", DemoLetter.Render(letterPages[1], s } db.ArchiveItems.AddRange(items); - // A story that curators can open under Stories: words between three published items, and one part that names the draft, - // which visitors will not see. + // A published story: words between three published items, and one part that names the draft. Visitors read the story + // without that part, and curators see it under Stories with the reason. var story = new Story { Title = T("Mill Street over thirty years", "Die Mühlenstraße in dreißig Jahren"), Summary = T("From the winter of 1952 to the street party of 1971, told with a few of the photos.", "Vom Winter 1952 bis zum Straßenfest 1971, erzählt mit einigen der Fotos."), - Status = StoryStatus.Draft, + Status = StoryStatus.Published, + PublishedAt = now, CreatedAt = now, UpdatedAt = now, Position = 0, diff --git a/src/Commonage.Web/Pages/Index.cshtml b/src/Commonage.Web/Pages/Index.cshtml index 618e876..b7e7347 100644 --- a/src/Commonage.Web/Pages/Index.cshtml +++ b/src/Commonage.Web/Pages/Index.cshtml @@ -42,6 +42,18 @@ } +@if (Model.Stories.Count > 0) +{ +
+

@T["Stories"]

+ + @if (Model.MoreStories) + { +

@T["All stories"]

+ } +
+} + @* A single decade is no timeline. *@ @if (Model.Decades.Count > 1) { diff --git a/src/Commonage.Web/Pages/Index.cshtml.cs b/src/Commonage.Web/Pages/Index.cshtml.cs index 42b567d..5ac911c 100644 --- a/src/Commonage.Web/Pages/Index.cshtml.cs +++ b/src/Commonage.Web/Pages/Index.cshtml.cs @@ -17,6 +17,12 @@ public class IndexModel(CommonageDbContext db, Commonage.Web.Operations.ArchiveP public IReadOnlyList Recent { get; private set; } = []; + /// The first stories visitors may read, and whether there are more than shown. No count: a count would tell of hidden ones. + public IReadOnlyList Stories { get; private set; } = []; + public bool MoreStories { get; private set; } + + private const int StoryCount = 3; + /// How many published items each decade has. public IReadOnlyList Decades { get; private set; } = []; @@ -41,6 +47,10 @@ public async Task OnGetAsync() .Select(ItemSummary.FromItem) .ToListAsync(); + var stories = await db.LoadFirstAsync(StoryCount + 1, HttpContext.RequestAborted); + MoreStories = stories.Count > StoryCount; + Stories = stories.Take(StoryCount).ToList(); + Decades = await DecadeTimeline.LoadAsync(db.VisibleItems, HttpContext.RequestAborted); var popularTags = await db.VisibleItems diff --git a/src/Commonage.Web/Pages/Shared/_ItemCard.cshtml b/src/Commonage.Web/Pages/Shared/_ItemCard.cshtml new file mode 100644 index 0000000..bd3d863 --- /dev/null +++ b/src/Commonage.Web/Pages/Shared/_ItemCard.cshtml @@ -0,0 +1,28 @@ +@model ItemSummary +@inject Commonage.Web.Operations.ArchiveProfile Profile +@{ + var showCollection = ViewData["ShowCollection"] is true; + var material = (await Profile.GetAsync()).MaterialLanguage; +} + +@* One item card: the picture (never for a record-only item, see ItemSummary), the title, the date. Shared by lists and stories. *@ + + @if (Model.ThumbnailMediaFileId is { } mediaFileId) + { + + } + else + { + + } + @Model.Title + +@if (Model.DateText is not null) +{ + @Model.DateText +} +@if (showCollection) +{ + @Model.CollectionTitle +} diff --git a/src/Commonage.Web/Pages/Shared/_ItemCards.cshtml b/src/Commonage.Web/Pages/Shared/_ItemCards.cshtml index 0eadf00..28affc5 100644 --- a/src/Commonage.Web/Pages/Shared/_ItemCards.cshtml +++ b/src/Commonage.Web/Pages/Shared/_ItemCards.cshtml @@ -1,34 +1,10 @@ @model IEnumerable -@inject Commonage.Web.Operations.ArchiveProfile Profile -@{ - var showCollection = ViewData["ShowCollection"] is true; - var material = (await Profile.GetAsync()).MaterialLanguage; -} diff --git a/src/Commonage.Web/Pages/Shared/_StoryBody.cshtml b/src/Commonage.Web/Pages/Shared/_StoryBody.cshtml index 872ce86..c069e9c 100644 --- a/src/Commonage.Web/Pages/Shared/_StoryBody.cshtml +++ b/src/Commonage.Web/Pages/Shared/_StoryBody.cshtml @@ -21,7 +21,7 @@ break; case Commonage.Web.Data.StoryBlockView.Item item:
- + @if (!string.IsNullOrWhiteSpace(item.Caption)) {
@item.Caption
diff --git a/src/Commonage.Web/Pages/Shared/_StoryCards.cshtml b/src/Commonage.Web/Pages/Shared/_StoryCards.cshtml new file mode 100644 index 0000000..0a052e6 --- /dev/null +++ b/src/Commonage.Web/Pages/Shared/_StoryCards.cshtml @@ -0,0 +1,29 @@ +@model IEnumerable +@inject Commonage.Web.Operations.ArchiveProfile Profile +@{ + var material = (await Profile.GetAsync()).MaterialLanguage; +} + + diff --git a/src/Commonage.Web/Pages/Stories/Details.cshtml b/src/Commonage.Web/Pages/Stories/Details.cshtml new file mode 100644 index 0000000..2b4a9f3 --- /dev/null +++ b/src/Commonage.Web/Pages/Stories/Details.cshtml @@ -0,0 +1,18 @@ +@page "/stories/{id:int}" +@model Commonage.Web.Pages.Stories.DetailsModel +@{ + ViewData["Title"] = Model.Body.Title; + var address = $"{HttpContext.Request.BaseAddress()}/stories/{Model.StoryId}"; + ViewData["Canonical"] = address; + // The words of the story and nothing from an item, and no picture: a preview travels, an item's rights may not. An empty + // summary gives an empty description, never the first lines of a block. + ViewData["LinkPreview"] = new LinkPreview(Model.Body.Title, LinkPreview.Shorten(Model.Body.Summary), address); +} + + + + diff --git a/src/Commonage.Web/Pages/Stories/Details.cshtml.cs b/src/Commonage.Web/Pages/Stories/Details.cshtml.cs new file mode 100644 index 0000000..4a7a8f8 --- /dev/null +++ b/src/Commonage.Web/Pages/Stories/Details.cshtml.cs @@ -0,0 +1,35 @@ +using Commonage.Web.Data; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; + +namespace Commonage.Web.Pages.Stories; + +/// +/// A story as visitors read it. A draft, a story in the bin, one whose blocks are all hidden and an unknown number all give the +/// same NotFound(). No date of change is shown and no ETag or Last-Modified is sent: neither may follow block or item data. +/// +public class DetailsModel(CommonageDbContext db) : PageModel +{ + public int StoryId { get; private set; } + public StoryBody Body { get; private set; } = null!; + + public async Task OnGetAsync(int id, CancellationToken cancellationToken) + { + var story = await db.VisibleStories.AsNoTracking() + .Where(s => s.Id == id) + .Select(s => new { s.Id, s.Title, s.Summary }) + .FirstOrDefaultAsync(cancellationToken); + if (story is null) + return NotFound(); + + var blocks = await VisibleStoryBlocks.LoadAsync(db, story.Id, cancellationToken); + // Blocks that changed between the two queries: the same answer as for every other story nobody may read. + if (blocks.Count == 0) + return NotFound(); + + StoryId = story.Id; + Body = new StoryBody(story.Title, story.Summary, blocks); + return Page(); + } +} diff --git a/src/Commonage.Web/Pages/Stories/Index.cshtml b/src/Commonage.Web/Pages/Stories/Index.cshtml new file mode 100644 index 0000000..a4e14f1 --- /dev/null +++ b/src/Commonage.Web/Pages/Stories/Index.cshtml @@ -0,0 +1,17 @@ +@page "/stories" +@model Commonage.Web.Pages.Stories.IndexModel +@{ + ViewData["Title"] = T["Stories"]; +} + +

@T["Stories"]

+ +@if (Model.Stories.TotalCount == 0) +{ +

@T["No stories yet."]

+} +else +{ + + +} diff --git a/src/Commonage.Web/Pages/Stories/Index.cshtml.cs b/src/Commonage.Web/Pages/Stories/Index.cshtml.cs new file mode 100644 index 0000000..dc9e43c --- /dev/null +++ b/src/Commonage.Web/Pages/Stories/Index.cshtml.cs @@ -0,0 +1,18 @@ +using Commonage.Web.Data; +using Commonage.Web.Search; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace Commonage.Web.Pages.Stories; + +/// The stories visitors may read. Only VisibleStories and its covers feed this page, so a hidden story leaves no trace in it. +public class IndexModel(CommonageDbContext db) : PageModel +{ + public PagedList Stories { get; private set; } = PagedList.Empty; + + [BindProperty(SupportsGet = true, Name = QueryUrls.PageKey)] + public int PageNumber { get; set; } = 1; + + public async Task OnGetAsync(CancellationToken cancellationToken) => + Stories = await db.LoadPageAsync(PageNumber, cancellationToken); +} diff --git a/src/Commonage.Web/Resources/SharedResource.de.resx b/src/Commonage.Web/Resources/SharedResource.de.resx index 8c3e86a..b99ff96 100644 --- a/src/Commonage.Web/Resources/SharedResource.de.resx +++ b/src/Commonage.Web/Resources/SharedResource.de.resx @@ -1145,4 +1145,6 @@ Besucher sehen dieses Objekt ohne seine Fotos. {0, plural, one {# Objekt, das Besuchern nicht gezeigt wird} other {# Objekte, die Besuchern nicht gezeigt werden}} {0, plural, one {# Teil} other {# Teile}} + Noch keine Geschichten. + Alle Geschichten diff --git a/src/Commonage.Web/Resources/SharedResource.resx b/src/Commonage.Web/Resources/SharedResource.resx index aa54c30..eb77f81 100644 --- a/src/Commonage.Web/Resources/SharedResource.resx +++ b/src/Commonage.Web/Resources/SharedResource.resx @@ -71,6 +71,7 @@ All places All right All statuses + All stories Almost done: the archive is saving what you sent. Also add files the archive already has Always @@ -492,6 +493,7 @@ No preview could be created. No previews have failed. No role + No stories yet. No tags match. No: they should ask first None diff --git a/src/Commonage.Web/Search/PublicFeeds.cs b/src/Commonage.Web/Search/PublicFeeds.cs index b9d8d60..9c1c85c 100644 --- a/src/Commonage.Web/Search/PublicFeeds.cs +++ b/src/Commonage.Web/Search/PublicFeeds.cs @@ -42,6 +42,7 @@ public static class PublicFeeds // A sitemap may hold at most 50,000 addresses. private const int MaxSitemapItems = 49_000; + private const int MaxSitemapStories = 500; private const string CacheControl = "public, max-age=600"; private static readonly XNamespace Atom = "http://www.w3.org/2005/Atom"; @@ -133,6 +134,13 @@ private static async Task ServeSitemapAsync(HttpContext context, Common .Select(i => new { i.Id, i.UpdatedAt }) .ToListAsync(cancellationToken); + // No lastmod for a story: it would follow the blocks and so the items, which a story must not tell. + var stories = await db.VisibleStories + .OrderBy(s => s.Id) + .Select(s => s.Id) + .Take(MaxSitemapStories) + .ToListAsync(cancellationToken); + static XElement Page(string url, DateTime? changed = null) => new(Sitemap + "url", new XElement(Sitemap + "loc", url), changed is { } at ? new XElement(Sitemap + "lastmod", at.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)) : null); @@ -141,6 +149,8 @@ private static async Task ServeSitemapAsync(HttpContext context, Common Page($"{address}/"), Page($"{address}/collections"), collections.Select(id => Page($"{address}/collections/{id}")), + stories.Count > 0 ? Page($"{address}/stories") : null, + stories.Select(id => Page($"{address}/stories/{id}")), items.Select(item => Page($"{address}/items/{item.Id}", item.UpdatedAt))); context.Response.Headers.CacheControl = CacheControl; diff --git a/src/Commonage.Web/Search/StoryCards.cs b/src/Commonage.Web/Search/StoryCards.cs new file mode 100644 index 0000000..d63da58 --- /dev/null +++ b/src/Commonage.Web/Search/StoryCards.cs @@ -0,0 +1,47 @@ +using Commonage.Web.Data; +using Microsoft.EntityFrameworkCore; + +namespace Commonage.Web.Search; + +/// A story as visitors find it in a list: its words and a picture of a visible item, if it has one. +public record StoryCard(int Id, string Title, string? Summary, int? CoverMediaFileId); + +public static class StoryCards +{ + /// A page of the list stays small however many stories there are. + public const int PageSize = 24; + + private sealed record Head(int Id, string Title, string? Summary); + + /// + /// One page of the stories visitors may read, in the order curators gave them. The total, the paging and the covers are + /// computed from visible rows only, so a story that is hidden changes nothing about the page. + /// + public static async Task> LoadPageAsync(this CommonageDbContext db, int page, CancellationToken ct) + { + var heads = await db.VisibleStories + .OrderBy(s => s.Position).ThenBy(s => s.Id) + .Select(s => new Head(s.Id, s.Title, s.Summary)) + .ToPagedListAsync(page, PageSize, ct); + return new PagedList(await WithCoversAsync(db, heads.Items, ct), heads.Page, PageSize, heads.TotalCount); + } + + /// The first stories, for the start page. + public static async Task> LoadFirstAsync(this CommonageDbContext db, int count, CancellationToken ct) + { + var heads = await db.VisibleStories + .OrderBy(s => s.Position).ThenBy(s => s.Id) + .Take(count) + .Select(s => new Head(s.Id, s.Title, s.Summary)) + .ToListAsync(ct); + return await WithCoversAsync(db, heads, ct); + } + + private static async Task> WithCoversAsync(CommonageDbContext db, IReadOnlyList heads, CancellationToken ct) + { + // The cover is the picture of an item visitors see, never an original and never a hidden item's. It is shown on the + // website only: a story cover must never go into og:image without a MayTravel check. + var covers = await VisibleStoryBlocks.CoversAsync(db, heads.Select(h => h.Id).ToList(), ct); + return heads.Select(h => new StoryCard(h.Id, h.Title, h.Summary, covers.TryGetValue(h.Id, out var cover) ? cover : null)).ToList(); + } +} diff --git a/src/Commonage.Web/wwwroot/css/site.css b/src/Commonage.Web/wwwroot/css/site.css index de1144b..2673bae 100644 --- a/src/Commonage.Web/wwwroot/css/site.css +++ b/src/Commonage.Web/wwwroot/css/site.css @@ -805,15 +805,6 @@ main:focus { max-inline-size: 16rem; } -.story-figure .row { - margin: 0; -} - -.story-figure .row > * { - inline-size: 100%; - padding: 0; -} - .story-block-thumbnail { inline-size: 6rem; block-size: 6rem; diff --git a/tests/Commonage.BrowserTests/AccessibilityTests.cs b/tests/Commonage.BrowserTests/AccessibilityTests.cs index 6cd3390..6ce61f9 100644 --- a/tests/Commonage.BrowserTests/AccessibilityTests.cs +++ b/tests/Commonage.BrowserTests/AccessibilityTests.cs @@ -9,7 +9,7 @@ namespace Commonage.BrowserTests; public class AccessibilityTests(BrowserFixture app) { public static TheoryData PublicPages() => Widths( - "/", "/collections", "/collections/1", "/items/1", "/items/1/tell", "/help", "/items/2", "/items/6", "/search", "/search?q=flood", "/search?q=1950s", "/search?q=zzzznothing", "/items/99999", "/places", "/people", + "/", "/collections", "/collections/1", "/stories", "/stories/1", "/items/1", "/items/1/tell", "/help", "/items/2", "/items/6", "/search", "/search?q=flood", "/search?q=1950s", "/search?q=zzzznothing", "/items/99999", "/places", "/people", "/Account/Login", "CONTRIBUTE", "/contribute/no-such-link", "/about", "/contact", "/privacy"); public static TheoryData CuratorPages() => Widths( @@ -76,7 +76,7 @@ public async Task A_page_holds_up_with_much_longer_text(string path) Assert.True(overflow <= 0, $"{path} scrolls sideways by {overflow} px: {string.Join(" | ", tooWide)}"); } - public static TheoryData MainPages() => new() { "/", "/collections", "/collections/1", "/items/1", "/search?q=flood", "CONTRIBUTE", "/privacy" }; + public static TheoryData MainPages() => new() { "/", "/collections", "/collections/1", "/stories/1", "/items/1", "/search?q=flood", "CONTRIBUTE", "/privacy" }; /// For states a page only reaches by using it, as well as for each page as it loads. internal static async Task AssertNoViolationsAsync(IPage page, string what) diff --git a/tests/Commonage.BrowserTests/StoryBrowserTests.cs b/tests/Commonage.BrowserTests/StoryBrowserTests.cs index fea0d13..b975f7d 100644 --- a/tests/Commonage.BrowserTests/StoryBrowserTests.cs +++ b/tests/Commonage.BrowserTests/StoryBrowserTests.cs @@ -91,4 +91,22 @@ public async Task Leaving_with_an_edited_text_part_asks_first() Assert.Equal(["beforeunload"], dialogs); Assert.Equal("Changed but not saved", await page.InputValueAsync("textarea[id^=text-] >> nth=0")); } + + [Fact] + public async Task The_demo_story_reads_without_its_draft_item_and_curators_see_the_draft_with_its_reason() + { + const string draft = "Unsorted photos from the club house"; + var visitor = await app.NewPageAsync(); + await visitor.GotoAsync("/stories/1"); + Assert.Contains("Mill Street over thirty years", await visitor.InnerTextAsync("h1")); + Assert.DoesNotContain(draft, await visitor.ContentAsync()); + Assert.DoesNotContain("Still to be sorted", await visitor.ContentAsync()); + await visitor.GotoAsync("/stories"); + Assert.True(await visitor.Locator("main a:has-text('Mill Street over thirty years')").IsVisibleAsync()); + + var curator = await app.LogInAsync(); + await curator.GotoAsync("/Admin/Stories/Edit/1"); + Assert.Contains(draft, await curator.InnerTextAsync("main")); + Assert.Contains("Visitors do not see this item: it is not published.", await curator.InnerTextAsync("main")); + } } diff --git a/tests/Commonage.Tests/EndpointAccessTests.cs b/tests/Commonage.Tests/EndpointAccessTests.cs index 1fc4ada..06d7ab0 100644 --- a/tests/Commonage.Tests/EndpointAccessTests.cs +++ b/tests/Commonage.Tests/EndpointAccessTests.cs @@ -14,7 +14,7 @@ public class EndpointAccessTests(CommonageAppFactory app) { private static readonly string[] MeantForVisitors = [ - "/", "/Index", "/search", "/items/{id:int}", "/items/{id:int}.json", "/items/{id:int}/tell", "/help", "/collections", "/collections/{id:int}", + "/", "/Index", "/search", "/items/{id:int}", "/items/{id:int}.json", "/items/{id:int}/tell", "/help", "/collections", "/collections/{id:int}", "/stories", "/stories/{id:int}", "/{kind:regex(^(places|people)$)}", "/{slug:regex(^(about|contact|privacy|imprint)$)}", "/SetLanguage", "/Error/{code:int?}", // Published pictures only, see MediaTests. diff --git a/tests/Commonage.Tests/StoryVisibilityMatrixTests.cs b/tests/Commonage.Tests/StoryVisibilityMatrixTests.cs new file mode 100644 index 0000000..2fcb2f0 --- /dev/null +++ b/tests/Commonage.Tests/StoryVisibilityMatrixTests.cs @@ -0,0 +1,443 @@ +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using Commonage.Web.Domain; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Commonage.Tests; + +/// +/// What visitors read of a story, address by address. Item B has a word of its own in its title, description, credit, photo and +/// caption, so any part of it that shows where it must not is caught. Every test has an archive of its own, so that what is +/// listed and counted is only what the test made. See docs/plan-m29-stories.md. +/// +[Collection(nameof(AppCollection))] +public partial class StoryVisibilityMatrixTests(CommonageAppFactory app) +{ + private sealed class MutableClock(DateTimeOffset now) : TimeProvider + { + public DateTimeOffset Now { get; set; } = now; + public override DateTimeOffset GetUtcNow() => Now; + } + + private sealed record Seeded(int StoryId, int AId, int BId, int CId, int BFileId, int BlockOfB, string BWord, string StoryWord); + + private static ArchiveItem NewItem(Collection collection, string title, DateTime now, bool withFile, string word) + { + var item = new ArchiveItem + { + Title = title, Description = $"Words {word}", Credit = $"Credit {word}", Collection = collection, CreatedAt = now, UpdatedAt = now, + }; + if (withFile) + item.MediaFiles.Add(new MediaFile + { + ArchiveItem = item, OriginalFileName = "a.jpg", ContentType = "image/jpeg", Sha256 = new string('a', 64), + StorageId = Guid.NewGuid(), Status = ProcessingStatus.Ready, AltText = $"Alt {word}", Caption = $"Photo caption {word}", + }); + return item; + } + + /// A published story: text, A, B, C, text. A and C are visible; B is in the state given. + private static async Task SeedAsync(WebApplicationFactory archive, string kind, Action stateOfB, bool publishStory = true, bool siblingsVisible = true) + { + var bWord = TestData.UniqueWord(kind); + var storyWord = TestData.UniqueWord("story"); + return await archive.WithDbAsync(async db => + { + var now = DateTime.UtcNow; + var collection = new Collection { Title = $"Box {TestData.UniqueWord("box")}", CreatedAt = now }; + var a = NewItem(collection, $"Alpha {TestData.UniqueWord("a")}", now, true, "alpha"); + var b = NewItem(collection, $"Title {bWord}", now, true, bWord); + var c = NewItem(collection, $"Charlie {TestData.UniqueWord("c")}", now, true, "charlie"); + if (siblingsVisible) + { + a.Publish(now); + c.Publish(now); + } + stateOfB(b, now); + var story = new Story { Title = $"Story {storyWord}", Summary = $"Summary {storyWord}", CreatedAt = now, UpdatedAt = now }; + if (publishStory) + story.Publish(now); + void Part(StoryBlockKind kind, string? text = null, ArchiveItem? item = null, string? caption = null) => + story.Blocks.Add(new StoryBlock { Position = story.Blocks.Count, Kind = kind, Text = text, ArchiveItem = item, Caption = caption }); + Part(StoryBlockKind.Text, $"Opening text {storyWord}"); + Part(StoryBlockKind.Item, item: a, caption: "Caption of the first"); + Part(StoryBlockKind.Item, item: b, caption: $"Caption {bWord}"); + Part(StoryBlockKind.Item, item: c, caption: "Caption of the third"); + Part(StoryBlockKind.Text, $"Closing text {storyWord}"); + db.AddRange(collection, a, b, c, story); + await db.SaveChangesAsync(); + var blockOfB = story.Blocks.Single(x => x.ArchiveItem == b).Id; + return new Seeded(story.Id, a.Id, b.Id, c.Id, b.MediaFiles.Single().Id, blockOfB, bWord, storyWord); + }); + } + + private static async Task> NewArchiveAsync(CommonageAppFactory app, MutableClock? clock = null) + { + if (clock is null) + return await app.NewArchiveAsync(); + return await app.NewArchiveAsync(b => b.ConfigureTestServices(s => s.AddSingleton(clock))); + } + + private static async Task TextAsync(HttpClient client, string address) + { + var response = await client.GetAsync(address); + return response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : ""; + } + + /// Every page carries a form token that is new with each response; nothing else is changed. + private static string WithoutToken(string page) => Token().Replace(page, "$1"); + + [GeneratedRegex(@"(__RequestVerificationToken[^>]*?value="")[^""]*")] + private static partial Regex Token(); + + private static string Headers(HttpResponseMessage response) => string.Join('\n', + response.Headers.Concat(response.Content.Headers).Where(h => h.Key is not ("Date" or "Set-Cookie")).OrderBy(h => h.Key, StringComparer.Ordinal) + .Select(h => $"{h.Key}: {string.Join(',', h.Value)}")); + + private static string MetaTags(string page) => string.Concat(Regex.Matches(page, @"]*(og:|name=""description"")[^>]*>").Select(m => m.Value + "\n")); + + private static string[] Addresses(Seeded s) => + ["/stories", $"/stories/{s.StoryId}", "/", "/sitemap.xml", "/feed.xml", $"/items/{s.BId}", $"/media/{s.BFileId}/thumbnail", + $"/media/{s.BFileId}/card"]; + + [Fact] + public async Task An_item_block_in_a_state_visitors_may_not_see_leaves_no_trace_and_the_page_is_the_page_without_the_block() + { + var states = new Dictionary> + { + ["draft"] = (_, _) => { }, + ["waiting"] = (i, _) => i.Status = ItemStatus.Submitted, + ["rejected"] = (i, now) => i.Reject(now), + ["withdrawn"] = (i, now) => i.Withdraw(now), + ["embargoed"] = (i, now) => { i.Publish(now); i.SetPublicFrom(DateOnly.FromDateTime(now).AddDays(3), now); }, + ["binned"] = (i, now) => { i.Publish(now); i.MoveToBin(now); }, + }; + await using var archive = await NewArchiveAsync(app); + using var visitor = archive.CreateClient(); + + foreach (var (kind, state) in states) + { + var seeded = await SeedAsync(archive, kind, state); + var everything = new StringBuilder(); + foreach (var address in Addresses(seeded)) + everything.Append(await TextAsync(visitor, address)); + var text = everything.ToString(); + + Assert.Contains($"Opening text {seeded.StoryWord}", text); + Assert.Contains("Caption of the first", text); + Assert.Contains("Caption of the third", text); + Assert.True(!text.Contains(seeded.BWord), $"{kind}: a word of the hidden item shows."); + Assert.DoesNotContain($"/items/{seeded.BId}\"", text); + Assert.DoesNotContain($"/items/{seeded.BId}<", text); + Assert.DoesNotContain($"/media/{seeded.BFileId}/", text); + // The search page repeats what was typed, so it is checked for what it would show of the item, not for the word. + var search = await TextAsync(visitor, $"/search?q={seeded.BWord}"); + Assert.DoesNotContain($"Title {seeded.BWord}", search); + Assert.DoesNotContain($"/items/{seeded.BId}\"", search); + foreach (var variant in new[] { "preview", "thumbnail", "card", "large" }) + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/media/{seeded.BFileId}/{variant}")).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/items/{seeded.BId}")).StatusCode); + + // The block sits between two visible ones. With it taken out, the page is the same, byte for byte, but for the token. + var withBlock = WithoutToken(await TextAsync(visitor, $"/stories/{seeded.StoryId}")); + await archive.WithDbAsync(db => db.StoryBlocks.Where(b => b.Id == seeded.BlockOfB).ExecuteDeleteAsync()); + var withoutBlock = WithoutToken(await TextAsync(visitor, $"/stories/{seeded.StoryId}")); + Assert.True(withBlock == withoutBlock, $"{kind}: the page tells that a block was left out."); + } + } + + [Fact] + public async Task The_page_of_a_story_carries_no_id_position_anchor_or_data_attribute_of_its_blocks() + { + await using var archive = await NewArchiveAsync(app); + var seeded = await SeedAsync(archive, "plain", (i, now) => i.Publish(now)); + using var visitor = archive.CreateClient(); + + var body = await TextAsync(visitor, $"/stories/{seeded.StoryId}"); + var article = body[body.IndexOf("
", StringComparison.Ordinal)]; + + Assert.DoesNotContain(" id=\"", article); + Assert.DoesNotContain("data-", article); + Assert.DoesNotContain("href=\"#", article); + Assert.DoesNotContain("style=", article); + } + + [Fact] + public async Task A_record_only_item_shows_its_title_and_link_but_no_picture() + { + await using var archive = await NewArchiveAsync(app); + var seeded = await SeedAsync(archive, "recordonly", (i, now) => { i.Publish(now); i.MediaLevel = MediaLevel.RecordOnly; }); + using var visitor = archive.CreateClient(); + + var story = await TextAsync(visitor, $"/stories/{seeded.StoryId}"); + var cards = await TextAsync(visitor, "/stories"); + + Assert.Contains($"Title {seeded.BWord}", story); + Assert.Contains($"/items/{seeded.BId}\"", story); + Assert.Contains($"Caption {seeded.BWord}", story); + foreach (var page in new[] { story, cards }) + { + Assert.DoesNotContain($"/media/{seeded.BFileId}/", page); + Assert.DoesNotContain($"Alt {seeded.BWord}", page); + } + foreach (var variant in new[] { "preview", "thumbnail", "card", "large" }) + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/media/{seeded.BFileId}/{variant}")).StatusCode); + } + + [Fact] + public async Task A_contributor_who_did_not_agree_to_sharing_beyond_the_website_has_nothing_in_a_preview_or_the_feed() + { + await using var archive = await NewArchiveAsync(app); + var seeded = await SeedAsync(archive, "notsharing", (i, now) => + { + i.Publish(now); + i.Contribution = new Contribution + { + ContributorName = "Erika Muster", ShowName = false, Rights = RightsStatement.PermissionFromRightsHolder, + ConsentText = "I agree.", SubmittedAt = now, ConsentCoversSharing = false, + }; + }); + using var visitor = archive.CreateClient(); + + var story = await TextAsync(visitor, $"/stories/{seeded.StoryId}"); + + // On the website the item shows as it does anywhere else. + Assert.Contains($"Title {seeded.BWord}", story); + Assert.DoesNotContain(seeded.BWord, MetaTags(story)); + Assert.DoesNotContain("og:image", story); + Assert.DoesNotContain(seeded.BWord, await TextAsync(visitor, "/feed.xml")); + Assert.DoesNotContain("Erika", story); + } + + [Fact] + public async Task The_preview_of_a_story_has_its_title_and_summary_and_no_picture_and_no_description_without_a_summary() + { + await using var archive = await NewArchiveAsync(app); + var seeded = await SeedAsync(archive, "preview", (i, now) => i.Publish(now)); + var without = await archive.WithDbAsync(async db => + { + var story = await db.Stories.SingleAsync(s => s.Id == seeded.StoryId); + var copy = new Story { Title = "Without summary", Summary = null, CreatedAt = story.CreatedAt, UpdatedAt = story.UpdatedAt, Position = 1 }; + copy.Publish(story.CreatedAt); + copy.Blocks.Add(new StoryBlock { Position = 0, Kind = StoryBlockKind.Text, Text = $"The first words {seeded.StoryWord}" }); + db.Stories.Add(copy); + await db.SaveChangesAsync(); + return copy.Id; + }); + using var visitor = archive.CreateClient(); + + var with = MetaTags(await TextAsync(visitor, $"/stories/{seeded.StoryId}")); + Assert.Contains($"content=\"Story {seeded.StoryWord}\"", with); + Assert.Contains($"og:description\" content=\"Summary {seeded.StoryWord}\"", with); + Assert.DoesNotContain("og:image", with); + Assert.DoesNotContain("twitter:card", await TextAsync(visitor, $"/stories/{seeded.StoryId}")); + Assert.DoesNotContain(seeded.BWord, with); + Assert.DoesNotContain("Alpha", with); + + var empty = MetaTags(await TextAsync(visitor, $"/stories/{without}")); + Assert.Contains("og:title\" content=\"Without summary\"", empty); + Assert.DoesNotContain("description", empty); + Assert.DoesNotContain(seeded.StoryWord, empty); + } + + [Fact] + public async Task The_words_of_a_story_are_not_in_search_or_the_feed_and_the_story_is_in_the_sitemap_without_a_date() + { + await using var archive = await NewArchiveAsync(app); + var seeded = await SeedAsync(archive, "words", (i, now) => i.Publish(now)); + using var visitor = archive.CreateClient(); + + var search = await TextAsync(visitor, $"/search?q={seeded.StoryWord}"); + Assert.DoesNotContain($"Opening text {seeded.StoryWord}", search); + Assert.DoesNotContain($"/stories/{seeded.StoryId}", search); + var feed = await TextAsync(visitor, "/feed.xml"); + Assert.DoesNotContain(seeded.StoryWord, feed); + Assert.DoesNotContain("/stories", feed); + + var sitemap = await TextAsync(visitor, "/sitemap.xml"); + Assert.Matches($"https?://[^<]+/stories/{seeded.StoryId}", sitemap); + Assert.Matches("https?://[^<]+/stories", sitemap); + + var response = await visitor.GetAsync($"/stories/{seeded.StoryId}"); + Assert.False(response.Headers.Contains("ETag") || response.Content.Headers.Contains("Last-Modified")); + } + + [Fact] + public async Task A_story_that_is_a_draft_in_the_bin_all_hidden_or_unknown_answers_the_same_404_and_changes_nothing_else() + { + await using var archive = await NewArchiveAsync(app); + var shown = await SeedAsync(archive, "shown", (i, now) => i.Publish(now)); + using var visitor = archive.CreateClient(); + var pagesBefore = new[] { "/stories", "/", "/sitemap.xml" }; + var before = new List(); + foreach (var address in pagesBefore) + before.Add(WithoutToken(await TextAsync(visitor, address))); + + // Their items are hidden too: a visible item would show on the start page and in the sitemap, whatever the story is. + var draft = await SeedAsync(archive, "draftstory", (_, _) => { }, publishStory: false, siblingsVisible: false); + var binned = await SeedAsync(archive, "binnedstory", (_, _) => { }, siblingsVisible: false); + await archive.WithDbAsync(async db => + { + var story = await db.Stories.SingleAsync(s => s.Id == binned.StoryId); + story.MoveToBin(DateTime.UtcNow); + return await db.SaveChangesAsync(); + }); + var allHidden = await SeedAsync(archive, "allhidden", (_, _) => { }, siblingsVisible: false); + await archive.WithDbAsync(async db => + { + // Only item blocks, and none of them visible: the first and the last are texts in the seed, so those go. + await db.StoryBlocks.Where(b => b.StoryId == allHidden.StoryId && b.Kind == StoryBlockKind.Text).ExecuteDeleteAsync(); + await db.StoryBlocks.Where(b => b.StoryId == allHidden.StoryId && b.ArchiveItemId != allHidden.BId) + .ExecuteDeleteAsync(); + return 0; + }); + var embargoedOnly = await SeedAsync(archive, "embargoedonly", (i, now) => { i.Publish(now); i.SetPublicFrom(DateOnly.FromDateTime(now).AddDays(3), now); }, siblingsVisible: false); + await archive.WithDbAsync(async db => + { + await db.StoryBlocks.Where(b => b.StoryId == embargoedOnly.StoryId && b.ArchiveItemId != embargoedOnly.BId).ExecuteDeleteAsync(); + return 0; + }); + var hidden = new[] { draft, binned, allHidden, embargoedOnly }; + + var reference = await visitor.GetAsync("/stories/99999999"); + Assert.Equal(HttpStatusCode.NotFound, reference.StatusCode); + var referenceBody = WithoutToken(await reference.Content.ReadAsStringAsync()); + foreach (var story in hidden) + { + var response = await visitor.GetAsync($"/stories/{story.StoryId}"); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.Equal(Headers(reference), Headers(response)); + Assert.Equal(referenceBody, WithoutToken(await response.Content.ReadAsStringAsync())); + } + + // The listings are byte for byte what they were before the hidden stories existed. + for (var i = 0; i < pagesBefore.Length; i++) + Assert.Equal(before[i], WithoutToken(await TextAsync(visitor, pagesBefore[i]))); + Assert.Equal(HttpStatusCode.OK, (await visitor.GetAsync($"/stories/{shown.StoryId}")).StatusCode); + } + + [Fact] + public async Task A_story_whose_only_item_is_embargoed_is_not_there_until_the_day_and_then_it_is() + { + var clock = new MutableClock(new DateTimeOffset(2031, 5, 9, 12, 0, 0, TimeSpan.Zero)); + await using var archive = await NewArchiveAsync(app, clock); + var id = await archive.WithDbAsync(async db => + { + var now = DateTime.UtcNow; + var item = NewItem(new Collection { Title = "Box", CreatedAt = now }, "Opening day", now, false, "x"); + item.Publish(now); + item.SetPublicFrom(new DateOnly(2031, 5, 10), now); + var story = new Story { Title = "Waiting story", CreatedAt = now, UpdatedAt = now }; + story.Publish(now); + story.Blocks.Add(new StoryBlock { Position = 0, Kind = StoryBlockKind.Item, ArchiveItem = item, Caption = "Opening caption" }); + db.AddRange(item, story); + await db.SaveChangesAsync(); + return story.Id; + }); + using var visitor = archive.CreateClient(); + + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/stories/{id}")).StatusCode); + Assert.DoesNotContain("Waiting story", await TextAsync(visitor, "/stories")); + Assert.DoesNotContain($"/stories/{id}<", await TextAsync(visitor, "/sitemap.xml")); + + clock.Now = new DateTimeOffset(2031, 5, 10, 12, 0, 0, TimeSpan.Zero); + + Assert.Contains("Opening caption", await TextAsync(visitor, $"/stories/{id}")); + Assert.Contains("Waiting story", await TextAsync(visitor, "/stories")); + Assert.Contains($"/stories/{id}<", await TextAsync(visitor, "/sitemap.xml")); + } + + [Fact] + public async Task A_story_follows_its_story_and_its_items_when_they_are_published_unpublished_binned_restored_and_deleted() + { + await using var archive = await NewArchiveAsync(app); + var seeded = await SeedAsync(archive, "changing", (i, now) => i.Publish(now)); + using var visitor = archive.CreateClient(); + Task StoryAsync() => TextAsync(visitor, $"/stories/{seeded.StoryId}"); + async Task ChangeAsync(Action change) + { + await archive.WithDbAsync(async db => + { + change(new CommonageDbContextAccess(db)); + return await db.SaveChangesAsync(); + }); + } + + Assert.Contains($"Title {seeded.BWord}", await StoryAsync()); + + // The story goes back to a draft, and comes back. + await ChangeAsync(a => a.Story(seeded.StoryId).Unpublish()); + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/stories/{seeded.StoryId}")).StatusCode); + await ChangeAsync(a => a.Story(seeded.StoryId).Publish(DateTime.UtcNow)); + Assert.Contains($"Title {seeded.BWord}", await StoryAsync()); + + // The item goes to the bin: its block is gone; restoring the item brings the block back. + await ChangeAsync(a => a.Item(seeded.BId).MoveToBin(DateTime.UtcNow)); + Assert.DoesNotContain(seeded.BWord, await StoryAsync()); + await ChangeAsync(a => a.Item(seeded.BId).RestoreFromBin(DateTime.UtcNow)); + Assert.Contains($"Caption {seeded.BWord}", await StoryAsync()); + + // The story goes to the bin and is restored. + await ChangeAsync(a => a.Story(seeded.StoryId).MoveToBin(DateTime.UtcNow)); + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/stories/{seeded.StoryId}")).StatusCode); + await ChangeAsync(a => a.Story(seeded.StoryId).RestoreFromBin(DateTime.UtcNow)); + Assert.Equal(HttpStatusCode.OK, (await visitor.GetAsync($"/stories/{seeded.StoryId}")).StatusCode); + } + + [Fact] + public async Task Deleting_an_item_for_good_leaves_the_story_with_its_other_blocks_in_order() + { + await using var archive = await NewArchiveAsync(app); + var seeded = await SeedAsync(archive, "deleted", (i, now) => i.Publish(now)); + using var visitor = archive.CreateClient(); + + await archive.WithDbAsync(async db => + { + await db.MediaFiles.IgnoreQueryFilters().Where(f => f.ArchiveItemId == seeded.BId).ExecuteDeleteAsync(); + return await db.ArchiveItems.IgnoreQueryFilters().Where(i => i.Id == seeded.BId).ExecuteDeleteAsync(); + }); + + var page = await TextAsync(visitor, $"/stories/{seeded.StoryId}"); + Assert.DoesNotContain(seeded.BWord, page); + var order = new[] { $"Opening text {seeded.StoryWord}", "Caption of the first", "Caption of the third", $"Closing text {seeded.StoryWord}" }; + var places = order.Select(o => page.IndexOf(o, StringComparison.Ordinal)).ToArray(); + Assert.All(places, p => Assert.True(p > 0)); + Assert.Equal(places.Order(), places); + var blocks = await archive.WithDbAsync(db => db.StoryBlocks.Where(b => b.StoryId == seeded.StoryId).CountAsync()); + Assert.Equal(4, blocks); + } + + [Fact] + public async Task The_list_pages_the_visible_stories_only_and_takes_each_cover_from_a_visible_item() + { + await using var archive = await NewArchiveAsync(app); + var hiddenFirst = await SeedAsync(archive, "coverhidden", (_, _) => { }); + var visible = await SeedAsync(archive, "covervisible", (i, now) => i.Publish(now)); + using var visitor = archive.CreateClient(); + + var list = await TextAsync(visitor, "/stories"); + var start = await TextAsync(visitor, "/"); + + // The cover of a story is the picture of its first visible item (A), never of the hidden B before it in rank. + foreach (var page in new[] { list, start }) + { + Assert.Contains($"/stories/{visible.StoryId}\"", page); + Assert.DoesNotContain(hiddenFirst.BWord, page); + Assert.DoesNotContain($"/media/{hiddenFirst.BFileId}/", page); + } + Assert.Contains("
Loads a story or an item for a test that changes it. + private sealed class CommonageDbContextAccess(Commonage.Web.Data.CommonageDbContext db) + { + public Story Story(int id) => db.Stories.IgnoreQueryFilters().Single(s => s.Id == id); + public ArchiveItem Item(int id) => db.ArchiveItems.IgnoreQueryFilters().Single(i => i.Id == id); + } +} From 964d74cc2ebce9d389813615b7c7304902521f7b Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:30:07 +0100 Subject: [PATCH 2/3] M29, second part: pin the cover rule and the preview picture, count only texts with words The cover tests put a hidden, embargoed, binned or record-only item first; the preview tests give the archive a logo and allow only it as og:image. A text of white space alone no longer keeps a story visible or shows in it. Paging is tested with hidden stories added. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- CHANGELOG.md | 4 +- docs/plan-m29-stories.md | 4 +- docs/security.md | 2 +- src/Commonage.Web/Data/Visibility.cs | 5 +- src/Commonage.Web/Data/VisibleStoryBlocks.cs | 5 +- .../StoryVisibilityMatrixTests.cs | 221 +++++++++++++++++- 6 files changed, 229 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d55d9b0..0d9bf77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,8 @@ version may change things that need attention when updating, and these notes say - **Stories, second part.** Published stories are public. `/stories` lists them with a picture and a few words, the start page shows the first three, and `/stories/{number}` reads one: the curator's texts, and the items of the story as cards with the curator's captions. An item that visitors may not see (a draft, not yet public, in the bin, withdrawn) is left out - without a trace, and a story with nothing to read answers "not found" like an unknown page. A record-only item has no picture. - The sitemap lists the stories. A link to a story shows its title and its summary, no picture and nothing from an item. + without a trace, and a story with nothing to read (no item visitors may see, no text with words in it) answers "not found" like an unknown page. A record-only item has no picture. + The sitemap lists the stories. A link to a story shows its title and its summary and nothing from an item: no item picture, the archive logo as on every other page. Stories are not in the feed or in search. The demo archive's story is published. ### For curators diff --git a/docs/plan-m29-stories.md b/docs/plan-m29-stories.md index 0c39b43..9fbd56e 100644 --- a/docs/plan-m29-stories.md +++ b/docs/plan-m29-stories.md @@ -24,7 +24,7 @@ A block whose item is hidden is left out without a trace: no placeholder, no cap The rule lives in `Data/` only, as it does for M27: -- `Visibility.Story(DateOnly today)` in `Data/Visibility.cs`: published, and at least one text block or one item block whose item +- `Visibility.Story(DateOnly today)` in `Data/Visibility.cs`: published, and at least one text block with words in it (not only white space; a blank text is also left out of the page) or one item block whose item passes the item rule. The item condition is built from `Visibility.Item`, never a second spelling of `ItemStatus.Published`. The explicit `DeletedAt == null` is belt and braces on top of the query filter. - `CommonageDbContext.VisibleStories` and `BinnedStories` (`IgnoreQueryFilters`, `DeletedAt != null`). @@ -205,7 +205,7 @@ The `privacy-reviewer` found no design-level leak and asked for these, which are its other blocks in order. 5. **`/stories` is computed from visible rows only**: total, paging and covers. Covers come from one query, not one per story, and the page size is capped. Test: `/stories` is byte-identical with and without a hidden story. -6. **Link preview and sitemap.** The preview holds no item text, id or picture; when the summary is empty the description is empty +6. **Link preview and sitemap.** The preview holds no item text, id or picture (the archive logo, as on every other page, may be its image); when the summary is empty the description is empty (never the first text block). A story cover must never go into `og:image` without a `MayTravel` check (comment in the code). Story ids are sequential, so a gap is visible, as for items: listed under known limits. 7. **A published-only export is a public copy**, so captions of visible items travel with it; this is intended (the items do too). diff --git a/docs/security.md b/docs/security.md index ae2403b..ef7bbc5 100644 --- a/docs/security.md +++ b/docs/security.md @@ -31,7 +31,7 @@ vulnerability, see [SECURITY.md](../SECURITY.md). | Earlier texts | `ItemRevisions` keeps what a title, description, date, credit, original location or reference number said before a change, with the account that changed it (its name at the time) and when. The fields are a fixed list (`RevisionField`): never a contributor's name or email, the internal notes or where an item was received from, so removing a contributor's details never has to touch it. Who changed it is forgotten on the activity log's schedule (`ActivityLogKeptYears`); the text itself stays with the item. Shown on the item's admin page only; a curator may restore, a helper only reads. The rows go with their item (cascade, hidden while it is in the bin) and are not exported. `RevisionTests`, `ExportTests`. | | Stories | Curators and admins only (`ManageArchive`; a helper gets 403 on every page and handler). A story is text and item parts in a chosen order. What visitors see is decided in one place: `Visibility.Story` and `VisibleStoryBlocks` (a published story, and only the parts whose item passes `Visibility.Item` with the day; a story with no visible part is as hidden as a draft). The curator pages show hidden items to curators only and say why visitors do not see them. Input is limited on the server (title 200, summary 1,000, text 20,000, caption 1,000 characters, 200 parts per story); an item is added by number or by a page address on this site, never by path. Block handlers are scoped to their story and never save the story row. Accepted: a removed part is deleted at once (the bin covers whole stories, from part 3; the confirmation says so). The export lists stories (`stories`, format 9): a copy of what is public holds published stories with only parts whose item is in the copy, a full copy holds drafts, and the bin is never exported. The import only counts stories (`StoryCountConverter` skips them) and creates nothing. `StoryEditTests`, `VisibilityGuardTests`, `ExportTests`, `ExportImportTests`. | | Stories on the website | `/stories` and `/stories/{id}` start from `VisibleStories` (published, not in the bin, at least one visible part) and show parts only through `VisibleStoryBlocks`, which loads items through `VisibleItems`; a story page never follows a part to its item (`VisibilityGuardTests` reads the source). A draft, a story in the bin, one whose parts are all hidden and an unknown number answer the same 404 (same body and headers, `StoryVisibilityMatrixTests`). A part that is left out leaves nothing behind: no id, position, anchor, `data-` attribute, caption, placeholder, count or "n of m" in the public page (`_StoryBody` has none, and the page equals the page without the part, also with a hidden part between two visible ones). The list, its total, its paging (24 a page) and its covers (two queries for all stories of a page) are computed from visible rows only, so a hidden story changes nothing about them. The cover is a visible item's thumbnail, never of a record-only item. Block changes never save the story row, so there is no "updated" date, no `lastmod` in the sitemap and no `ETag` or `Last-Modified` from block or item data. The start page shows the first three, without a count. `StoryVisibilityMatrixTests`, `EndpointAccessTests`, `AccessibilityTests`. | -| Stories beyond the website | The link preview of a story has its title and its summary and nothing else: no picture (a cover never goes into `og:image`; an item's rights and consent may not allow it to travel), no item title, id or caption, and no description when the summary is empty (never the first lines of a part). Stories are not in `/feed.xml`, `/search`, the JSON or Dublin Core. The sitemap lists `/stories` and each visible story, without a date, and follows `AllowSearchEngines`. A contributor who did not agree to sharing beyond the website has their item shown in a story on the website like anywhere else, and nothing of it in the preview or the feed. `StoryVisibilityMatrixTests`. | +| Stories beyond the website | The link preview of a story has its title and its summary and nothing else: no item picture (a cover never goes into `og:image`; an item's rights and consent may not allow it to travel; the archive logo is the preview picture, as on every other page), no item title, id or caption, and no description when the summary is empty (never the first lines of a part). Stories are not in `/feed.xml`, `/search`, the JSON or Dublin Core. The sitemap lists `/stories` and each visible story, without a date, and follows `AllowSearchEngines`. A contributor who did not agree to sharing beyond the website has their item shown in a story on the website like anywhere else, and nothing of it in the preview or the feed. `StoryVisibilityMatrixTests`. | | Recordings | Only curators can add a recording (MP3, M4A, WAV, FLAC, recognised by their first bytes); contribution links refuse them. Visitors hear only a copy made by the app itself (`AudioTools`, no outside program): the sound is copied byte for byte, and ID3v2/ID3v1/APE tags (MP3), `udta`, `meta`, `uuid` and padding boxes and the dates in the headers (M4A), every chunk except `fmt `, `fact` and `data` (WAV), and every block except stream info and the seek table (FLAC) are left out. A file that is not built as its type says (impossible sizes, missing parts, fragmented M4A) fails and has no copy, so nothing is ever served untouched. The parser is managed code reading sizes against the file's length, with the header of an M4A limited to 64 MB; it runs on the single preview queue and a failure marks only that file. Served for published items only, from `/media/{id}/audio` with range requests, with its own copy (`audio/…` key); the original is only at `/admin/media/{id}/original` for curators. Accepted: the sound itself may contain a voice that identifies someone, which is what an oral history is; curators decide what to publish. `AudioTests`. | | PDF files | Only curators can add a PDF; contribution links refuse it. A PDF is recognised by `%PDF-` and read by poppler (`pdfinfo`, `pdftoppm`), a large C++ parser, so it runs as separate processes, never inside the app: each call has a time limit (`Uploads:PdfTimeoutSeconds`, 60) and is killed with its children when it takes longer, the size of the drawn picture is set by us with `-scale-to` whatever size the page claims, at most 300 pages are drawn, and no part of the file or its name reaches a command line (arguments are passed as a list, the file is copied to a random name in an owner-only temporary folder that is removed afterwards). Pages are served only for published items; the PDF stays private. Accepted: a hostile PDF made by a curator could still exploit poppler, which runs with the app's rights in the container; build with `WITH_PDF=false` to remove it. `poppler-utils` comes from the distribution at build time and is not pinned to a version, so a rebuild of the same commit can ship another poppler (accepted; the base image digest is pinned). The text of a PDF (`pdftotext`, same limits, control characters removed, at most 200,000 characters) is only matched by search, never shown, and it is in the index only while the item is not in the bin and the PDF is not in the bin; a draft is found only by curators, as before. The preview queue is single, so a very long PDF delays other previews (at most 60 s per page); copies of a PDF left by a stopped app are removed at the next start. | | Uploads | Files are recognised by their content (magic bytes), never by name or browser type, and stored under random names outside the web root. Originals are never changed or served to visitors. Previews are made by libvips, rotated upright and stripped of all metadata. Images over 250 megapixels get no preview (decompression bombs), also for GIF and AVIF (`Images_with_more_pixels_than_the_limit_get_no_preview`). GIF and AVIF (libheif with an AV1 decoder, from M23) are further decoders reachable from a contribution link; a GIF is read as its first frame only. There is no time limit on a decode, so a very large AVIF costs memory and time on a small server; the pixel limit and the three-attempt guard are the protection. Size limits per file and per request. A file that the preview maker fails on, in whatever way, costs only its own preview, and one that takes the app down is given up after three attempts instead of at every start (`PreviewFailureTests`). | diff --git a/src/Commonage.Web/Data/Visibility.cs b/src/Commonage.Web/Data/Visibility.cs index f22fbec..2b1f02a 100644 --- a/src/Commonage.Web/Data/Visibility.cs +++ b/src/Commonage.Web/Data/Visibility.cs @@ -1,3 +1,4 @@ +using System.Text.RegularExpressions; using System.Linq.Expressions; using Commonage.Web.Domain; @@ -27,13 +28,13 @@ public static Expression> Media(DateOnly today) => && f.ArchiveItem.MediaLevel == MediaLevel.Everything; /// - /// The stories visitors may read: published, not in the bin, and with at least one text block or one item block whose item + /// The stories visitors may read: published, not in the bin, and with at least one text block that has words in it (not only white space) or one item block whose item /// allows (so embargo and withdrawal come with it). This is the only place that writes /// in a query. The explicit DeletedAt test is belt and braces on the query filter. /// A method on the context rather than an expression: it cannot be applied to a navigation from a block to its item. /// public static IQueryable Story(CommonageDbContext db, DateOnly today) => db.Stories.Where(s => s.Status == StoryStatus.Published && s.DeletedAt == null - && s.Blocks.Any(b => b.Kind == StoryBlockKind.Text + && s.Blocks.Any(b => (b.Kind == StoryBlockKind.Text && b.Text != null && Regex.IsMatch(b.Text, @"\S")) || db.ArchiveItems.Where(Item(today)).Any(i => i.Id == b.ArchiveItemId))); } diff --git a/src/Commonage.Web/Data/VisibleStoryBlocks.cs b/src/Commonage.Web/Data/VisibleStoryBlocks.cs index a912f6d..047e391 100644 --- a/src/Commonage.Web/Data/VisibleStoryBlocks.cs +++ b/src/Commonage.Web/Data/VisibleStoryBlocks.cs @@ -46,7 +46,10 @@ public static async Task> LoadAsync(CommonageDbContext db, foreach (var block in blocks) { if (block.Kind == StoryBlockKind.Text) - result.Add(new StoryBlockView.Text(block.Text ?? "")); + { + if (!string.IsNullOrWhiteSpace(block.Text)) + result.Add(new StoryBlockView.Text(block.Text)); + } else if (block.ArchiveItemId is { } id && items.TryGetValue(id, out var summary)) result.Add(new StoryBlockView.Item(summary, block.Caption)); } diff --git a/tests/Commonage.Tests/StoryVisibilityMatrixTests.cs b/tests/Commonage.Tests/StoryVisibilityMatrixTests.cs index 2fcb2f0..5a3f852 100644 --- a/tests/Commonage.Tests/StoryVisibilityMatrixTests.cs +++ b/tests/Commonage.Tests/StoryVisibilityMatrixTests.cs @@ -101,6 +101,47 @@ private static string Headers(HttpResponseMessage response) => string.Join('\n', private static string MetaTags(string page) => string.Concat(Regex.Matches(page, @"]*(og:|name=""description"")[^>]*>").Select(m => m.Value + "\n")); + /// The archive gets a logo, as most do: a page without a picture of its own then shows the logo, as on every other page. + private static async Task GiveLogoAsync(WebApplicationFactory archive) + { + var logo = Guid.NewGuid(); + await archive.WithDbAsync(async db => + { + var settings = await db.ArchiveSettings.FirstOrDefaultAsync(); + if (settings is null) + db.ArchiveSettings.Add(settings = new ArchiveSettings()); + settings.LogoId = logo; + return await db.SaveChangesAsync(); + }); + archive.Services.GetRequiredService().Forget(); + return logo; + } + + /// + /// A link preview of a story has no picture of an item: its og:image is the archive logo or nothing, never a file under /media, + /// and the large card is announced exactly when there is an image. + /// + private static void AssertNoItemPicture(string page, Guid logo) + { + var images = Regex.Matches(page, @" m.Groups[1].Value).ToList(); + Assert.All(images, image => + { + Assert.DoesNotContain("/media/", image); + Assert.EndsWith($"/branding/{logo}/icon", image); + }); + Assert.Equal(images.Count > 0, page.Contains("twitter:card")); + Assert.DoesNotContain("og:image:alt", page); + } + + /// The card of one story in a list, from its list item to the end of it. + private static string Card(string page, int storyId) + { + var at = page.IndexOf($"/stories/{storyId}\"", StringComparison.Ordinal); + Assert.True(at > 0, $"Story {storyId} is not listed."); + var start = page.LastIndexOf("", at, StringComparison.Ordinal) + 5)]; + } + private static string[] Addresses(Seeded s) => ["/stories", $"/stories/{s.StoryId}", "/", "/sitemap.xml", "/feed.xml", $"/items/{s.BId}", $"/media/{s.BFileId}/thumbnail", $"/media/{s.BFileId}/card"]; @@ -193,6 +234,7 @@ public async Task A_record_only_item_shows_its_title_and_link_but_no_picture() public async Task A_contributor_who_did_not_agree_to_sharing_beyond_the_website_has_nothing_in_a_preview_or_the_feed() { await using var archive = await NewArchiveAsync(app); + var logo = await GiveLogoAsync(archive); var seeded = await SeedAsync(archive, "notsharing", (i, now) => { i.Publish(now); @@ -209,15 +251,16 @@ public async Task A_contributor_who_did_not_agree_to_sharing_beyond_the_website_ // On the website the item shows as it does anywhere else. Assert.Contains($"Title {seeded.BWord}", story); Assert.DoesNotContain(seeded.BWord, MetaTags(story)); - Assert.DoesNotContain("og:image", story); + AssertNoItemPicture(story, logo); Assert.DoesNotContain(seeded.BWord, await TextAsync(visitor, "/feed.xml")); Assert.DoesNotContain("Erika", story); } [Fact] - public async Task The_preview_of_a_story_has_its_title_and_summary_and_no_picture_and_no_description_without_a_summary() + public async Task The_preview_of_a_story_has_its_title_and_summary_and_no_item_picture_and_no_description_without_a_summary() { await using var archive = await NewArchiveAsync(app); + var logo = await GiveLogoAsync(archive); var seeded = await SeedAsync(archive, "preview", (i, now) => i.Publish(now)); var without = await archive.WithDbAsync(async db => { @@ -234,8 +277,8 @@ public async Task The_preview_of_a_story_has_its_title_and_summary_and_no_pictur var with = MetaTags(await TextAsync(visitor, $"/stories/{seeded.StoryId}")); Assert.Contains($"content=\"Story {seeded.StoryWord}\"", with); Assert.Contains($"og:description\" content=\"Summary {seeded.StoryWord}\"", with); - Assert.DoesNotContain("og:image", with); - Assert.DoesNotContain("twitter:card", await TextAsync(visitor, $"/stories/{seeded.StoryId}")); + AssertNoItemPicture(await TextAsync(visitor, $"/stories/{seeded.StoryId}"), logo); + Assert.Contains($"/branding/{logo}/icon", with); Assert.DoesNotContain(seeded.BWord, with); Assert.DoesNotContain("Alpha", with); @@ -243,6 +286,7 @@ public async Task The_preview_of_a_story_has_its_title_and_summary_and_no_pictur Assert.Contains("og:title\" content=\"Without summary\"", empty); Assert.DoesNotContain("description", empty); Assert.DoesNotContain(seeded.StoryWord, empty); + AssertNoItemPicture(await TextAsync(visitor, $"/stories/{without}"), logo); } [Fact] @@ -434,6 +478,175 @@ public async Task The_list_pages_the_visible_stories_only_and_takes_each_cover_f Assert.Equal(HttpStatusCode.OK, (await visitor.GetAsync("/stories?page=999")).StatusCode); } + private sealed record CoverSeed(int StoryId, int BFileId, int? AFileId, string BWord); + + /// A published story whose item blocks come in this order: B (in the state given), then A, a visible item, if asked for. A text only if asked for. + private static async Task SeedCoverAsync(WebApplicationFactory archive, string kind, Action stateOfB, bool withA, bool withText) + { + var bWord = TestData.UniqueWord(kind); + return await archive.WithDbAsync(async db => + { + var now = DateTime.UtcNow; + var collection = new Collection { Title = $"Box {TestData.UniqueWord("box")}", CreatedAt = now }; + var b = NewItem(collection, $"Title {bWord}", now, true, bWord); + stateOfB(b, now); + var a = NewItem(collection, $"Alpha {TestData.UniqueWord("a")}", now, true, "alpha"); + a.Publish(now); + var story = new Story { Title = $"Cover {bWord}", CreatedAt = now, UpdatedAt = now }; + story.Publish(now); + story.Blocks.Add(new StoryBlock { Position = 0, Kind = StoryBlockKind.Item, ArchiveItem = b }); + if (withA) + story.Blocks.Add(new StoryBlock { Position = 1, Kind = StoryBlockKind.Item, ArchiveItem = a }); + if (withText) + story.Blocks.Add(new StoryBlock { Position = 2, Kind = StoryBlockKind.Text, Text = $"Only words {bWord}" }); + db.AddRange(collection, b, a, story); + await db.SaveChangesAsync(); + return new CoverSeed(story.Id, b.MediaFiles.Single().Id, withA ? a.MediaFiles.Single().Id : null, bWord); + }); + } + + private static Dictionary> StatesWithoutPicture() => new() + { + ["draft"] = (_, _) => { }, + ["embargoed"] = (i, now) => { i.Publish(now); i.SetPublicFrom(DateOnly.FromDateTime(now).AddDays(3), now); }, + ["binned"] = (i, now) => { i.Publish(now); i.MoveToBin(now); }, + ["recordonly"] = (i, now) => { i.Publish(now); i.MediaLevel = MediaLevel.RecordOnly; }, + }; + + [Fact] + public async Task The_cover_is_the_picture_of_the_first_item_visitors_may_see_even_when_a_hidden_or_record_only_item_comes_first() + { + await using var archive = await NewArchiveAsync(app); + using var visitor = archive.CreateClient(); + var seeds = new List<(string Kind, CoverSeed Seed)>(); + foreach (var (kind, state) in StatesWithoutPicture()) + seeds.Add((kind, await SeedCoverAsync(archive, kind, state, withA: true, withText: false))); + // Positive case: the first item is visible and has a picture, and it is the cover. + var visible = await SeedCoverAsync(archive, "visiblefirst", (i, now) => i.Publish(now), withA: true, withText: false); + + var list = await TextAsync(visitor, "/stories"); + var start = await TextAsync(visitor, "/"); + foreach (var page in new[] { list, start }) + { + foreach (var (kind, seed) in seeds) + { + Assert.True(!page.Contains($"/media/{seed.BFileId}/"), $"{kind}: the picture of the first item shows."); + Assert.Contains($"/media/{seed.AFileId}/thumbnail", Card(page, seed.StoryId)); + } + Assert.Contains($"/media/{visible.BFileId}/thumbnail", Card(page, visible.StoryId)); + } + } + + [Fact] + public async Task A_story_whose_only_item_is_hidden_or_record_only_is_kept_by_a_text_and_its_cover_is_the_text_tile() + { + await using var archive = await NewArchiveAsync(app); + using var visitor = archive.CreateClient(); + var seeds = new List<(string Kind, CoverSeed Seed)>(); + foreach (var (kind, state) in StatesWithoutPicture()) + seeds.Add((kind, await SeedCoverAsync(archive, kind, state, withA: false, withText: true))); + + var list = await TextAsync(visitor, "/stories"); + var start = await TextAsync(visitor, "/"); + foreach (var page in new[] { list, start }) + foreach (var (kind, seed) in seeds) + { + var card = Card(page, seed.StoryId); + Assert.True(card.Contains("text-tile") && !card.Contains(" + { + var now = DateTime.UtcNow; + for (var n = 0; n < visibleStories; n++) + { + var story = new Story { Title = $"Paged {n:00}", CreatedAt = now, UpdatedAt = now, Position = n }; + story.Publish(now); + story.Blocks.Add(new StoryBlock { Position = 0, Kind = StoryBlockKind.Text, Text = $"Words of {n}" }); + db.Stories.Add(story); + } + return await db.SaveChangesAsync(); + }); + using var visitor = archive.CreateClient(); + async Task PagesAsync() => + [ + WithoutToken(await TextAsync(visitor, "/stories")), WithoutToken(await TextAsync(visitor, "/stories?page=2")), + WithoutToken(await TextAsync(visitor, "/")), WithoutToken(await TextAsync(visitor, "/sitemap.xml")), + ]; + static int Cards(string page) => Regex.Matches(page, "class=\"collection-card\"").Count; + + var before = await PagesAsync(); + Assert.Equal(Commonage.Web.Search.StoryCards.PageSize, Cards(before[0])); + Assert.Equal(2, Cards(before[1])); + + // A draft, a story in the bin and one whose only item is hidden and first in the order. Their items are hidden too, + // because a visible item would show on the start page and in the sitemap whatever the story is. + await SeedAsync(archive, "pagedraft", (_, _) => { }, publishStory: false, siblingsVisible: false); + var binned = await SeedAsync(archive, "pagebinned", (_, _) => { }, siblingsVisible: false); + var onlyHidden = await SeedAsync(archive, "pagehidden", (_, _) => { }, siblingsVisible: false); + await archive.WithDbAsync(async db => + { + await db.StoryBlocks.Where(b => b.StoryId == onlyHidden.StoryId && b.ArchiveItemId != onlyHidden.BId).ExecuteDeleteAsync(); + await db.Stories.Where(s => s.Id == onlyHidden.StoryId).ExecuteUpdateAsync(s => s.SetProperty(x => x.Position, -1)); + var story = await db.Stories.SingleAsync(s => s.Id == binned.StoryId); + story.MoveToBin(DateTime.UtcNow); + return await db.SaveChangesAsync(); + }); + + var after = await PagesAsync(); + for (var i = 0; i < before.Length; i++) + Assert.True(before[i] == after[i], $"Page {i} changed with hidden stories."); + } + + [Fact] + public async Task A_text_of_nothing_but_white_space_does_not_keep_a_story_visible_or_show_up_in_it() + { + await using var archive = await NewArchiveAsync(app); + var ids = await archive.WithDbAsync(async db => + { + var now = DateTime.UtcNow; + Story Make(string title, params string[] texts) + { + var story = new Story { Title = title, CreatedAt = now, UpdatedAt = now }; + story.Publish(now); + foreach (var text in texts) + story.Blocks.Add(new StoryBlock { Position = story.Blocks.Count, Kind = StoryBlockKind.Text, Text = text }); + return story; + } + var onlyBlank = Make("Blank only", " ", "\n\t \r\n"); + var withWords = Make("Blank and words", " ", "Real words here"); + var hiddenItem = NewItem(new Collection { Title = "Box", CreatedAt = now }, "Hidden one", now, false, "hid"); + var blankAndHidden = Make("Blank and hidden item", " "); + blankAndHidden.Blocks.Add(new StoryBlock { Position = 1, Kind = StoryBlockKind.Item, ArchiveItem = hiddenItem }); + db.AddRange(onlyBlank, withWords, hiddenItem, blankAndHidden); + await db.SaveChangesAsync(); + return (OnlyBlank: onlyBlank.Id, WithWords: withWords.Id, BlankAndHidden: blankAndHidden.Id); + }); + using var visitor = archive.CreateClient(); + + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/stories/{ids.OnlyBlank}")).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/stories/{ids.BlankAndHidden}")).StatusCode); + var list = await TextAsync(visitor, "/stories"); + Assert.DoesNotContain("Blank only", list); + Assert.DoesNotContain("Blank and hidden item", list); + Assert.Contains("Blank and words", list); + var sitemap = await TextAsync(visitor, "/sitemap.xml"); + Assert.DoesNotContain($"/stories/{ids.OnlyBlank}<", sitemap); + Assert.DoesNotContain($"/stories/{ids.BlankAndHidden}<", sitemap); + + var page = await TextAsync(visitor, $"/stories/{ids.WithWords}"); + Assert.Contains("Real words here", page); + var article = page[page.IndexOf("
", StringComparison.Ordinal)]; + Assert.DoesNotMatch(@"]*>\s*

", article); + } + /// Loads a story or an item for a test that changes it. private sealed class CommonageDbContextAccess(Commonage.Web.Data.CommonageDbContext db) { From 8c5a937bfd0d9cc91ca9ed091a2b3d2e7d8af37e Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:03:00 +0100 Subject: [PATCH 3/3] M29, second part: fix the tests that were wrong, not the rules The list pages with p, the start page shows three stories, a withdrawn item needs a contribution, and the inline-script test reads a published story. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- tests/Commonage.Tests/SecurityHeaderTests.cs | 5 +++- .../StoryVisibilityMatrixTests.cs | 28 ++++++++++++++----- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/tests/Commonage.Tests/SecurityHeaderTests.cs b/tests/Commonage.Tests/SecurityHeaderTests.cs index 556444a..f496793 100644 --- a/tests/Commonage.Tests/SecurityHeaderTests.cs +++ b/tests/Commonage.Tests/SecurityHeaderTests.cs @@ -57,6 +57,9 @@ public async Task Pages_contain_no_inline_script_or_style() var storyId = await app.WithDbAsync(async db => { var story = new Story { Title = TestData.Unique("A story"), CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + // Published with a text, so that the page visitors read is checked too. + story.Publish(DateTime.UtcNow); + story.Blocks.Add(new StoryBlock { Position = 0, Kind = StoryBlockKind.Text, Text = "Some words." }); db.Stories.Add(story); await db.SaveChangesAsync(); return story.Id; @@ -99,7 +102,7 @@ private static string FillIn(string route, ArchiveItem item, string token, int t var id = route.StartsWith("/Collections", StringComparison.OrdinalIgnoreCase) || route.Contains("Admin/Collections", StringComparison.OrdinalIgnoreCase) ? item.CollectionId.ToString() : route.Contains("Admin/Tags", StringComparison.OrdinalIgnoreCase) ? tagId.ToString() - : route.Contains("Admin/Stories", StringComparison.OrdinalIgnoreCase) ? storyId.ToString() + : route.Contains("Stories", StringComparison.OrdinalIgnoreCase) ? storyId.ToString() : route.Contains("Admin/Contributions", StringComparison.OrdinalIgnoreCase) ? linkId.ToString() : item.Id.ToString(); var url = route .Replace("{token}", token) diff --git a/tests/Commonage.Tests/StoryVisibilityMatrixTests.cs b/tests/Commonage.Tests/StoryVisibilityMatrixTests.cs index 5a3f852..de9a731 100644 --- a/tests/Commonage.Tests/StoryVisibilityMatrixTests.cs +++ b/tests/Commonage.Tests/StoryVisibilityMatrixTests.cs @@ -154,7 +154,15 @@ public async Task An_item_block_in_a_state_visitors_may_not_see_leaves_no_trace_ ["draft"] = (_, _) => { }, ["waiting"] = (i, _) => i.Status = ItemStatus.Submitted, ["rejected"] = (i, now) => i.Reject(now), - ["withdrawn"] = (i, now) => i.Withdraw(now), + ["withdrawn"] = (i, now) => + { + i.Contribution = new Contribution + { + ContributorName = "Someone", ShowName = false, Rights = RightsStatement.PermissionFromRightsHolder, + ConsentText = "I agree.", SubmittedAt = now, + }; + i.Withdraw(now); + }, ["embargoed"] = (i, now) => { i.Publish(now); i.SetPublicFrom(DateOnly.FromDateTime(now).AddDays(3), now); }, ["binned"] = (i, now) => { i.Publish(now); i.MoveToBin(now); }, }; @@ -475,7 +483,7 @@ public async Task The_list_pages_the_visible_stories_only_and_takes_each_cover_f Assert.DoesNotContain($"/media/{hiddenFirst.BFileId}/", page); } Assert.Contains("
using var visitor = archive.CreateClient(); async Task PagesAsync() => [ - WithoutToken(await TextAsync(visitor, "/stories")), WithoutToken(await TextAsync(visitor, "/stories?page=2")), + WithoutToken(await TextAsync(visitor, "/stories")), WithoutToken(await TextAsync(visitor, "/stories?p=2")), WithoutToken(await TextAsync(visitor, "/")), WithoutToken(await TextAsync(visitor, "/sitemap.xml")), ]; static int Cards(string page) => Regex.Matches(page, "class=\"collection-card\"").Count;