From 38daea737d262d24dd746281d9c72d92079c7720 Mon Sep 17 00:00:00 2001 From: Anya Tokugawa Date: Sun, 8 Nov 2026 04:00:27 +0900 Subject: [PATCH] feat: render RSS HTML bodies and simplify reader navigation --- docs/design/ja/feeds.md | 19 +++-- internal/server/feeds.go | 6 +- internal/server/feeds_fetch.go | 101 ++++++++++++++++++++---- internal/server/feeds_test.go | 42 +++++++++- internal/server/testdata/feeds.js | 5 +- internal/store/feeds.go | 16 +++- internal/store/feeds_test.go | 26 +++++- static/css/feeds.css | 1 + static/css/organizer.css | 1 + static/js/feeds.js | 24 +++--- templates/pages/feeds.gohtml | 4 +- templates/partials/organizer_nav.gohtml | 12 +-- 12 files changed, 208 insertions(+), 49 deletions(-) diff --git a/docs/design/ja/feeds.md b/docs/design/ja/feeds.md index 83d895d..0bd137a 100644 --- a/docs/design/ja/feeds.md +++ b/docs/design/ja/feeds.md @@ -37,7 +37,7 @@ FreshRSSの記事・既読・starは取得しますが、状態の変更は送 FreshRSS passwordを設定時以外にブラウザへ返さず、login tokenはbackend内でのみ利用します。 資格情報は既存の暗号化機構を使い、Domain・所有者・source UUID・用途に束縛します。 -cacheはsource UUID、remote item ID、title、安全なテキスト本文、記事URL、公開日時、配信元、 +cacheはsource UUID、remote item ID、title、安全化したHTML本文とテキスト本文、記事URL、公開日時、配信元、 フォルダ、read/starを保持します。取得時刻・ETag・Last-Modified・失敗分類はsource側に持ちます。 IDなしRSSは記事URL、URLもなければ題名・日時・本文の組合せから代替キーを作り、題名だけで 重複排除しません。Atomはentry IDを使います。[Atom仕様](https://www.rfc-editor.org/rfc/rfc4287)。 @@ -46,14 +46,19 @@ IDなしRSSは記事URL、URLもなければ題名・日時・本文の組合せ newsboat/neomuttを参考に、デスクトップは左から購読元・一行記事一覧・本文の3ペインとします。 一覧には未読/star、日付、配信元、件名を並べます。狭幅は一覧と本文を切り替え、スマホでは -行とボタンのタッチ領域を広げます。設定と保存フォームは本文ペイン内に置き、モーダルを増やしません。 +行とボタンのタッチ領域を広げます。モバイルの共通ナビはアイコンのみとし、名称はアクセシブル名と +tooltipに残します。タブ名は「RSS」、原文リンクはアイコンです。件数・保持上限・操作の説明は常設せず、 +キー案内は`?`で表示します。設定と保存フォームは本文ペイン内に置き、モーダルを増やしません。 `j/k`・上下矢印で移動、`Enter/l`で本文、`Esc/h`で一覧、`/`で件名・配信元検索、`n`で次の未読、 `m`で既読切替、`*`でstar、`r`で背景更新予約、`?`でキー案内です。フォーム入力・IME変換中は 一覧ショートカットを抑止します。FreshRSSでは`m`と`*`も外部変更を行いません。 -本文は常にtext表示です。script・画像・CSS・Wiki macroを実行せず、記事表示のための外部画像や -原文サイトのfetchも行いません。検索とページングは保存済みcacheだけを対象にし、画面表示で +HTML本文は見出し・表・箇条書き・強調・リンクを保持して描画し、plain textは文字情報として表示します。 +server側の許可リストでscript・イベント属性・任意CSS・form・iframe・画像等を除去し、表示時にも再検査します。 +Shadow DOMでWiki UIと表示スタイルを分離し、本文リンクは安全なHTTP(S) URLに解決して別タブで開きます。 +Wiki macroは展開せず、記事表示のための外部画像や原文サイトのfetchも行いません。 +検索とページングは保存済みcacheだけを対象にし、画面表示で feed取得の完了を待ちません。ダッシュボードには任意追加のRSS widgetを用意します。 ### APIと保存層 @@ -71,7 +76,9 @@ API prefixは `/_/api/v1/extension/organizer.feeds/`。Domain内の本人専用 | `POST state` | 内蔵read/starの条件付き変更。FreshRSSは拒否 | | `POST note` | 公開範囲確認付きのWiki単独保存。request_idと入力hashで再送を識別 | -managed schema `feeds` v1に `feed_sources`、`feed_items`、`feed_states`、`feed_note_receipts`を追加します。 +managed schema `feeds` v1に `feed_sources`、`feed_items`、`feed_states`、`feed_note_receipts`を追加し、 +v2で`feed_items.body_html`を追加します。既存のテキスト本文・既読・starは保持し、条件付きGETのvalidatorを +一度クリアして次回背景取得でHTMLを取り直します。migration前のworkerは設定versionで無効化します。 既存テーブルを破壊・再構成しません。SQLiteのforeign_keys設定に依存せず削除を完遂するtriggerを 持ちます。内蔵read/starを本文cacheから分離し、記事を保持窓から落としても状態は黙って消しません。 DBは内蔵購読・状態・保存receiptの正本であり、全体を捨てられるcacheとは扱いません。 @@ -89,7 +96,7 @@ sourceのprovider・URL・資格情報の変更は別sourceを作る契約です | source更新間隔 | 5〜1440分、既定30分。取得候補になる間隔であり、混雑時の完了時刻保証ではない | | 通信予算 | 1 source 8秒、batch 35秒、応答/展開後本文4 MiB | | 外部接続 | 公開HTTPS/443のみ。DNS検査・接続先固定、内部アドレス・redirect・proxyを拒否 | -| 内蔵記事cache | 1 source最大500件、本文32 KiB。超過本文は切詰めを明示 | +| 内蔵記事cache | 1 source最大500件、text本文32 KiB・HTML本文128 KiB。HTML上限超過はtextへフォールバックし、text切詰めを明示 | | 内蔵read/star | 1 source最大10,000件。上限では新規状態保存を拒否し、既存状態を捨てない | | FreshRSS | reading-list最新200件の窓を取得。更新成功時はその窓で置換し、全履歴同期とはしない | | 再試行 | 次の設定間隔まで待機。手動予約にも最終成功から60秒の制限、取得中の重複claim拒否 | diff --git a/internal/server/feeds.go b/internal/server/feeds.go index 2173ca9..bdab51d 100644 --- a/internal/server/feeds.go +++ b/internal/server/feeds.go @@ -172,6 +172,8 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) { taskError(w, e) return } + // Defense in depth for restored/older caches, not just freshly fetched data. + v.BodyHTML = feedHTML(v.BodyHTML, v.URL) writeEventJSON(w, 200, map[string]any{"item": v}) return case key == "state" && r.Method == "POST": @@ -195,8 +197,8 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) } func init() { - translations["en"]["feeds.title"] = "RSS reader" - translations["ja"]["feeds.title"] = "RSSリーダー" + translations["en"]["feeds.title"] = "RSS" + translations["ja"]["feeds.title"] = "RSS" translations["en"]["feeds.help"] = "Private local feeds and read-only FreshRSS integration" translations["ja"]["feeds.help"] = "個人用の簡易RSSとFreshRSS読取連携" } diff --git a/internal/server/feeds_fetch.go b/internal/server/feeds_fetch.go index cfca5a6..4390e6d 100644 --- a/internal/server/feeds_fetch.go +++ b/internal/server/feeds_fetch.go @@ -19,15 +19,71 @@ import ( "unicode/utf8" "github.com/microcosm-cc/bluemonday" + xhtml "golang.org/x/net/html" "golang.org/x/net/html/charset" "pageswiki/internal/store" ) var errFeedInvalid = errors.New("invalid_feed") var feedTextPolicy = bluemonday.StrictPolicy() +var feedHTMLPolicy = func() *bluemonday.Policy { + p := bluemonday.NewPolicy() + p.AllowElements("p", "div", "span", "br", "hr", "h1", "h2", "h3", "h4", "h5", "h6", "strong", "b", "em", "i", "u", "s", "del", "ins", "sub", "sup", "mark", "small", "blockquote", "pre", "code", "kbd", "samp", "ul", "ol", "li", "dl", "dt", "dd", "table", "caption", "thead", "tbody", "tfoot", "tr", "th", "td", "a") + p.AllowAttrs("href", "target", "rel").OnElements("a") + p.AllowAttrs("colspan", "rowspan", "scope").OnElements("th", "td") + p.AllowStandardURLs() + p.AllowRelativeURLs(false) + return p +}() + +// Keep article structure without granting fetched HTML script, style, form, +// embedding or automatic network capabilities. Wiki capture still uses Body. +func feedHTML(raw, base string) string { + if raw == "" || len(raw) > 128<<10 { + return "" + } + z := xhtml.NewTokenizer(strings.NewReader(raw)) + var out strings.Builder + markup := false + for { + typeOf := z.Next() + if typeOf == xhtml.ErrorToken { + if z.Err() != io.EOF { + return "" + } + break + } + if typeOf == xhtml.StartTagToken || typeOf == xhtml.SelfClosingTagToken { + markup = true + tok := z.Token() + if tok.Data == "a" { + attrs := []xhtml.Attribute{} + for _, attr := range tok.Attr { + if attr.Key == "href" { + if link := feedLink(base, attr.Val); link != "" { + attrs = append(attrs, xhtml.Attribute{Key: "href", Val: link}) + } + } + } + tok.Attr = append(attrs, xhtml.Attribute{Key: "target", Val: "_blank"}, xhtml.Attribute{Key: "rel", Val: "noopener noreferrer"}) + } + out.WriteString(tok.String()) + } else { + out.Write(z.Raw()) + } + } + if !markup { + return "" + } + clean := feedHTMLPolicy.Sanitize(out.String()) + if len(clean) > 128<<10 { + return "" + } + return clean +} func feedText(raw string, limit int) string { - // Text-only reader: no remote images, CSS, script, macros or active HTML. + // Plain text for fallback and inert Wiki/task capture. for _, tag := range []string{"

", "", "
", "
", "
", ""} { raw = strings.ReplaceAll(raw, tag, tag+"\n") } @@ -81,6 +137,19 @@ type rssEntry struct { Date string `xml:"pubDate"` Category string `xml:"category"` } +type atomText struct { + Type string `xml:"type,attr"` + Text string `xml:",chardata"` + Inner string `xml:",innerxml"` +} + +func (v atomText) body() (string, bool) { + if v.Type == "xhtml" { + return v.Inner, true + } + return v.Text, v.Type == "html" +} + type atomEntry struct { ID string `xml:"id"` Title string `xml:"title"` @@ -88,13 +157,10 @@ type atomEntry struct { Href string `xml:"href,attr"` Rel string `xml:"rel,attr"` } `xml:"link"` - Summary string `xml:"summary"` - Content struct { - Text string `xml:",chardata"` - Inner string `xml:",innerxml"` - } `xml:"content"` - Published string `xml:"published"` - Updated string `xml:"updated"` + Summary atomText `xml:"summary"` + Content atomText `xml:"content"` + Published string `xml:"published"` + Updated string `xml:"updated"` Category struct { Term string `xml:"term,attr"` } `xml:"category"` @@ -138,6 +204,7 @@ func parseFeed(raw []byte, base string) ([]store.FeedItem, error) { } var item store.FeedItem isItem := false + htmlBody := false if root == "rss" && t.Name.Local == "item" && depth == 3 { var v rssEntry if d.DecodeElement(&v, &t) != nil { @@ -150,19 +217,18 @@ func parseFeed(raw []byte, base string) ([]store.FeedItem, error) { } item = store.FeedItem{ID: v.ID, Title: v.Title, URL: feedLink(base, v.Link), Body: body, PublishedMS: feedDate(v.Date), Folder: v.Category} isItem = true + htmlBody = true } else if root == "feed" && t.Name.Local == "entry" && depth == 2 { var v atomEntry if d.DecodeElement(&v, &t) != nil { return nil, errFeedInvalid } depth-- - body := v.Content.Text + body, isHTML := v.Content.body() if body == "" { - body = v.Content.Inner - } - if body == "" { - body = v.Summary + body, isHTML = v.Summary.body() } + htmlBody = isHTML link := "" for _, l := range v.Links { if l.Rel == "" || l.Rel == "alternate" { @@ -187,7 +253,13 @@ func parseFeed(raw []byte, base string) ([]store.FeedItem, error) { return nil, errors.New("limit") } item.Title = feedText(item.Title, 2048) - item.Body = feedText(item.Body, 32768) + if htmlBody { + item.BodyHTML = feedHTML(item.Body, base) + item.Body = feedText(item.Body, 32768) + } else { + // Atom type=text is literal, even when it contains HTML-looking text. + item.Body = feedText(html.EscapeString(item.Body), 32768) + } item.Feed = feedText(title, 512) item.Folder = feedText(item.Folder, 512) if item.ID == "" { @@ -314,6 +386,7 @@ func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource, body = i.Content.Content } item.Body = feedText(body, 32768) + item.BodyHTML = feedHTML(body, base) if len(i.Alternate) > 0 { item.URL = feedLink(base, i.Alternate[0].Href) } diff --git a/internal/server/feeds_test.go b/internal/server/feeds_test.go index 1a9d822..870dbda 100644 --- a/internal/server/feeds_test.go +++ b/internal/server/feeds_test.go @@ -176,7 +176,7 @@ func TestFreshRSSReadOnlyContract(t *testing.T) { })) defer remote.Close() items, e := fetchFreshRSS(context.Background(), remote.Client(), store.FeedSource{URL: remote.URL + "/api/greader.php"}, "reader", "api-secret") - if e != nil || len(items) != 1 || !items[0].Read || !items[0].Starred || items[0].Folder != "Tech" || items[0].Body != "Text" || len(requests) != 2 { + if e != nil || len(items) != 1 || !items[0].Read || !items[0].Starred || items[0].Folder != "Tech" || items[0].Body != "Text" || items[0].BodyHTML != "

Text

" || len(requests) != 2 { t.Fatal(items, e, requests) } for _, bad := range []string{"http://example.org/feed", "https://127.0.0.1/feed", "https://10.0.0.1/feed", "https://example.org:8443/feed", "https://user:pass@example.org/feed"} { @@ -185,6 +185,45 @@ func TestFreshRSSReadOnlyContract(t *testing.T) { } } } + +func TestFeedHTMLFormattingAndIsolation(t *testing.T) { + raw := `

Title

Bold

Cell
Storybad
` + clean := feedHTML(raw, "https://example.org/news/feed.xml") + for _, want := range []string{`

Title

`, `Bold`, ``, `colspan="2"`, `href="https://example.org/story"`, `target="_blank"`, `noopener`} { + if !strings.Contains(clean, want) { + t.Fatal("format lost", want, clean) + } + } + for _, bad := range []string{"x

", 17000), "https://example.org") != "" { + t.Fatal("HTML cap") + } + for _, kind := range []string{"text", "html", "xhtml"} { + content := `<b>bold</b>` + if kind == "xhtml" { + content = `
bold
` + } + items, e := parseFeed([]byte(`x`+content+``), "https://example.org") + if e != nil || len(items) != 1 { + t.Fatal(e) + } + if kind == "text" { + if items[0].BodyHTML != "" || items[0].Body != "bold" { + t.Fatal("literal Atom text", items) + } + } else if !strings.Contains(items[0].BodyHTML, "bold") { + t.Fatal("Atom markup", kind, items) + } + } +} + func TestFeedPaginationFailureAndDelete(t *testing.T) { s, token, domain, actor, source := feedFixture(t) ctx := context.Background() @@ -500,6 +539,7 @@ func TestFeedsChromium(t *testing.T) { for i := 0; i < 120; i++ { items = append(items, store.FeedItem{ID: fmt.Sprint(i), Title: fmt.Sprintf("%03d 日本語のRSS記事 — リーダーの密度とキーボード操作", i), Body: "安全な本文です。\n\n {{children}}\n\nSource content stays inert.", Feed: "技術ニュース", URL: "https://example.org/article", PublishedMS: int64(1793500000000 + i)}) } + items[119].BodyHTML = `

HTMLの記事本文

強調やリンクをそのまま読めます。

項目内容
本文HTML表示
` if e = s.store.CompleteFeed(context.Background(), claim, items, "", "", "", false); e != nil { t.Fatal(e) } diff --git a/internal/server/testdata/feeds.js b/internal/server/testdata/feeds.js index c2fd10c..9f3d11c 100644 --- a/internal/server/testdata/feeds.js +++ b/internal/server/testdata/feeds.js @@ -6,8 +6,11 @@ await new Promise(resolve=>{frame.onload=resolve;frame.src='/v/feeds';});const d=frame.contentDocument,w=frame.contentWindow; await wait(()=>d.querySelectorAll('.feed-row').length===100); assert(d.documentElement.scrollWidth<=w.innerWidth,'Viewport overflow'); + assert(d.title.startsWith('RSS ·'),'RSS title');assert(d.getElementById('feed-status').textContent==='','Unrequested status copy');assert(w.getComputedStyle(d.getElementById('feed-status')).display==='none','Empty status takes space'); + for(const a of d.querySelectorAll('.organizer-nav a')){assert(a.getAttribute('aria-label'),'Unnamed navigation');if(w.innerWidth<=700)assert(w.getComputedStyle(a.querySelector('span')).display==='none','Mobile tab label visible');} d.getElementById('feed-rows').focus();d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'j',bubbles:true})); - await wait(()=>d.querySelector('#feed-reader .feed-body'));assert(d.querySelector('#feed-reader .feed-body').textContent.includes('{{ end }} +{{ end }} diff --git a/templates/partials/organizer_nav.gohtml b/templates/partials/organizer_nav.gohtml index 26d8765..982c05c 100644 --- a/templates/partials/organizer_nav.gohtml +++ b/templates/partials/organizer_nav.gohtml @@ -1,11 +1,11 @@ {{ define "organizer-nav" }} - + {{ end }} {{ define "organizer-shortcuts" }} {{ if .FeedsEnabled }}{{ end }}