Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b90aef79d0 | ||
|
|
84d52390f9 | ||
|
|
4049acf76e | ||
|
|
43a2d8c5a1 | ||
|
|
38a4fcf530 | ||
|
|
dc978231e2 | ||
|
|
5321d613b4 | ||
|
|
b23e63d4c6 | ||
|
|
f4869c7c8b | ||
|
|
ea1ca432c5 | ||
|
|
c2bc637704 | ||
|
|
a5f90f933d | ||
|
|
78da33d549 | ||
|
|
50a90bcc14 | ||
|
|
bf9a9c2847 | ||
|
|
1057be6d2b | ||
|
|
e4c184d71c | ||
|
|
4711a0efbf | ||
|
|
61ecd1ffbd | ||
|
|
131a7ca01f |
No files matched your search
@@ -91,13 +91,25 @@ jobs:
|
||||
org.opencontainers.image.revision=${{ github.sha }}
|
||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||
|
||||
- name: Build Gecko relay
|
||||
uses: https://github.com/docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile.gecko-relay
|
||||
platforms: linux/amd64
|
||||
load: true
|
||||
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_OWNER }}/pageswiki-gecko-relay:${{ env.IMAGE_TAG }}
|
||||
labels: |
|
||||
org.opencontainers.image.revision=${{ github.sha }}
|
||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||
|
||||
# Publish only after all builds succeed. Use the host daemon for registry
|
||||
# access; BuildKit does not inherit the runner's /etc/hosts entries.
|
||||
- name: Push images
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for image in pageswiki-app pageswiki-adaptor-gateway pageswiki-excalidraw-viewer; do
|
||||
for image in pageswiki-app pageswiki-adaptor-gateway pageswiki-excalidraw-viewer pageswiki-gecko-relay; do
|
||||
docker push "$REGISTRY/$IMAGE_OWNER/$image:$IMAGE_TAG"
|
||||
done
|
||||
|
||||
@@ -105,7 +117,7 @@ jobs:
|
||||
if: always()
|
||||
shell: bash
|
||||
run: |
|
||||
for image in pageswiki-app pageswiki-adaptor-gateway pageswiki-excalidraw-viewer; do
|
||||
for image in pageswiki-app pageswiki-adaptor-gateway pageswiki-excalidraw-viewer pageswiki-gecko-relay; do
|
||||
ref="$REGISTRY/$IMAGE_OWNER/$image:$IMAGE_TAG"
|
||||
if docker image inspect "$ref" >/dev/null 2>&1; then
|
||||
docker image rm "$ref" || echo "Could not remove local CI tag: $ref" >&2
|
||||
|
||||
+4
-1
@@ -14,7 +14,10 @@ FROM source AS test
|
||||
# Test packages create independent SQLite stores. Serialize packages to avoid
|
||||
# concurrent server/store initialization exhausting the shared runner's I/O.
|
||||
# Keep production database deadlines and the complete test suite unchanged.
|
||||
RUN go test -p 1 ./...
|
||||
# Temporary test databases use bounded RAM-backed storage rather than the
|
||||
# runner's overlay filesystem. Compiler temporary files remain on disk.
|
||||
RUN --mount=type=tmpfs,target=/test-tmp,size=2147483648 \
|
||||
TMPDIR=/test-tmp GOTMPDIR=/tmp go test -p 1 ./...
|
||||
|
||||
FROM source AS runtime
|
||||
RUN go build -o /pageswiki ./cmd/pageswiki
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# The relay image contains no browser engine. Mount the independently verified
|
||||
# fixed Gecko distribution read-only at /gecko (see docs/operations/gecko-relay.md).
|
||||
FROM golang:1.25-alpine AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY internal/geckorelay ./internal/geckorelay
|
||||
COPY cmd/gecko-relay ./cmd/gecko-relay
|
||||
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /gecko-relay ./cmd/gecko-relay
|
||||
|
||||
FROM scratch
|
||||
COPY --from=build /gecko-relay /usr/local/bin/gecko-relay
|
||||
COPY --from=build /usr/local/go/LICENSE /licenses/Go.txt
|
||||
COPY --from=build /go/pkg/mod/golang.org/x/net@v0.35.0/LICENSE /licenses/golang-x-net.txt
|
||||
COPY internal/geckorelay/NOTICE.txt /licenses/NOTICE.txt
|
||||
USER 10001:10001
|
||||
EXPOSE 3012
|
||||
ENTRYPOINT ["/usr/local/bin/gecko-relay"]
|
||||
@@ -0,0 +1,81 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"flag"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/geckorelay"
|
||||
)
|
||||
|
||||
func main() {
|
||||
status := flag.Bool("status", false, "print bounded relay resource counters")
|
||||
flag.Parse()
|
||||
// File mount avoids placing the shared secret in image layers or process args.
|
||||
key, err := os.ReadFile(os.Getenv("PAGESWIKI_GECKO_KEY_FILE"))
|
||||
if err != nil {
|
||||
log.Fatal("Gecko relay key file unavailable")
|
||||
}
|
||||
secret := strings.TrimSpace(string(key))
|
||||
addr := os.Getenv("PAGESWIKI_GECKO_LISTEN")
|
||||
if addr == "" {
|
||||
addr = ":3012"
|
||||
}
|
||||
if *status {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
log.Fatal("invalid listen address")
|
||||
}
|
||||
if host == "" || host == "0.0.0.0" {
|
||||
host = "127.0.0.1"
|
||||
}
|
||||
if host == "::" {
|
||||
host = "::1"
|
||||
}
|
||||
nonce := make([]byte, 24)
|
||||
if _, err = rand.Read(nonce); err != nil {
|
||||
log.Fatal("random source unavailable")
|
||||
}
|
||||
req, _ := http.NewRequest("GET", "http://"+net.JoinHostPort(host, port)+"/status", nil)
|
||||
req.Header.Set(geckorelay.GrantHeader, geckorelay.Sign(secret, geckorelay.Grant{Subject: "operator:status", Nonce: hex.EncodeToString(nonce), Expires: time.Now().Add(30 * time.Second).Unix()}))
|
||||
client := http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{Proxy: nil}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Fatal("relay status unavailable")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
log.Fatal("relay status denied")
|
||||
}
|
||||
if _, err = io.Copy(os.Stdout, io.LimitReader(resp.Body, 4096)); err != nil {
|
||||
log.Fatal("relay status read failed")
|
||||
}
|
||||
return
|
||||
}
|
||||
assets := os.Getenv("PAGESWIKI_GECKO_ASSETS")
|
||||
if assets == "" {
|
||||
assets = "/gecko"
|
||||
}
|
||||
if err := geckorelay.VerifyAssets(assets); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
distribution, err := geckorelay.VerifyDistribution(assets)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
relay, err := geckorelay.New(secret, assets)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
relay.Distribution = distribution
|
||||
s := &http.Server{Addr: addr, Handler: relay, ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16 << 10}
|
||||
log.Printf("Gecko relay listening; authenticated TCP 80/443 only")
|
||||
log.Fatal(s.ListenAndServe())
|
||||
}
|
||||
+2
-2
@@ -1398,13 +1398,13 @@ class PagesWikiCLI:
|
||||
if not args:
|
||||
for extension_id, enabled in sorted(states.items()):
|
||||
print(f"{extension_id}\t{'enabled' if enabled else 'disabled'}")
|
||||
print("(extensions not listed here use the default: enabled)")
|
||||
print("(unlisted extensions use their manifest default; viewer.gecko: disabled, others: enabled)")
|
||||
return
|
||||
extension_id = args[0].strip()
|
||||
if not re.fullmatch(r"[a-z][a-z0-9._-]{1,63}", extension_id):
|
||||
raise CLIError("invalid extension ID")
|
||||
if len(args) == 1:
|
||||
print(f"{extension_id}\t{'enabled' if states.get(extension_id, True) else 'disabled'}")
|
||||
print(f"{extension_id}\t{'enabled' if states.get(extension_id, extension_id != 'viewer.gecko') else 'disabled'}")
|
||||
return
|
||||
value = args[1].lower()
|
||||
if value not in {"on", "off"}:
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
import sqlite3
|
||||
import io
|
||||
from contextlib import redirect_stdout
|
||||
from types import SimpleNamespace
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).with_name("pageswiki-cli")
|
||||
@@ -43,5 +47,23 @@ class ContentTypeDetectionTest(unittest.TestCase):
|
||||
self.assertEqual(content_type, "text/plain; charset=shift_jis")
|
||||
|
||||
|
||||
class ExtensionDefaultTest(unittest.TestCase):
|
||||
def test_gecko_is_opt_in(self) -> None:
|
||||
db = sqlite3.connect(":memory:")
|
||||
self.addCleanup(db.close)
|
||||
db.execute("CREATE TABLE config(domain_uuid TEXT,key TEXT,value TEXT,updated_at INTEGER,UNIQUE(domain_uuid,key))")
|
||||
# Exercise the CLI command without reading any deployment database.
|
||||
owner = next(value for value in vars(pageswiki_cli).values() if isinstance(value, type) and hasattr(value, "command_extension"))
|
||||
fixture = SimpleNamespace(db=db, domain_uuid="synthetic")
|
||||
output = io.StringIO()
|
||||
with redirect_stdout(output):
|
||||
owner.command_extension(fixture, ["viewer.gecko"])
|
||||
owner.command_extension(fixture, ["viewer.gecko", "on"])
|
||||
owner.command_extension(fixture, ["viewer.gecko"])
|
||||
owner.command_extension(fixture, ["viewer.gecko", "off"])
|
||||
owner.command_extension(fixture, ["viewer.gecko"])
|
||||
self.assertEqual(output.getvalue().splitlines(), ["viewer.gecko\tdisabled", "viewer.gecko\ton", "viewer.gecko\tenabled", "viewer.gecko\toff", "viewer.gecko\tdisabled"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,47 @@
|
||||
# Optional development/pilot overlay, never selected by the production recipe.
|
||||
# Requires host egress rules; an isolated bridge alone is not an egress firewall.
|
||||
services:
|
||||
app:
|
||||
environment:
|
||||
PAGESWIKI_GECKO_RELAY: http://gecko-relay:3012
|
||||
PAGESWIKI_GECKO_KEY_FILE: /run/secrets/gecko-key
|
||||
volumes:
|
||||
- ${PAGESWIKI_GECKO_KEY_PATH:?Set absolute relay key path}:/run/secrets/gecko-key:ro
|
||||
networks:
|
||||
default: {}
|
||||
gecko-front: {}
|
||||
gecko-relay:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.gecko-relay
|
||||
image: ${PAGESWIKI_GECKO_IMAGE:-pageswiki-gecko-relay:dev}
|
||||
environment:
|
||||
PAGESWIKI_GECKO_KEY_FILE: /run/secrets/gecko-key
|
||||
volumes:
|
||||
- ${PAGESWIKI_GECKO_KEY_PATH:?Set absolute relay key path}:/run/secrets/gecko-key:ro
|
||||
- ${PAGESWIKI_GECKO_ASSETS_DIR:?Set verified complete Gecko bundle directory}:/gecko:ro
|
||||
networks:
|
||||
gecko-front: {}
|
||||
gecko-egress: {}
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
mem_limit: 256m
|
||||
cpus: 0.5
|
||||
pids_limit: 64
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: [CMD, /usr/local/bin/gecko-relay, --status]
|
||||
interval: 30s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
networks:
|
||||
gecko-front:
|
||||
internal: true
|
||||
ipam:
|
||||
config:
|
||||
- subnet: ${PAGESWIKI_GECKO_FRONT_SUBNET:-172.24.0.0/27}
|
||||
gecko-egress:
|
||||
ipam:
|
||||
config:
|
||||
- subnet: ${PAGESWIKI_GECKO_EGRESS_SUBNET:-172.24.0.32/27}
|
||||
@@ -48,6 +48,8 @@ IPアドレス管理(IPAM)、DNSゾーン/レコード管理、機器・
|
||||
|
||||
## CSV/表・スライド拡張(設計TODO)
|
||||
|
||||
初期CSV macroは実装済みです。`{{csv:/data/items.csv range=A1:H200 header=true}}` を認証済みProjectionで展開し、`rev=` で同じObjectのRevisionへ固定できます。現在のPath閲覧権限を毎回検査し、外部URL、匿名公開、asset指定、共有キャッシュ、CSV編集はこの段階に含めません。入力256 KiB・UTF-8、表示200行×32列、走査2,000行・100列、セル16 KiB、Projection当たり4種類のCSVまでに制限します。引用符・改行・BOMに対応し、セルはHTML escapeしてmacroや数式を実行しません。処理不能時は内容を漏らさない警告に置き換えます。Authoringでは元のmacroを保持します。
|
||||
|
||||
CSVをPage本文へ複製せず、認可済みの別Documentをテーブルとして投影するmacroを用意します。候補構文は `{{csv:/data/items.csv range=A1:H200 header=true}}` とし、Path、Revision(またはasset hash)、列・行上限、表示モードを正規化してキャッシュキーに含めます。macroは表示時にboundedなProjectionを作るだけで、結果HTMLを正本へ逆流させません。CSV Editorは元Revisionを編集し、表投影とは別の操作・競合・権限として扱います。
|
||||
|
||||
交換形式はRFC 4180互換CSV(UTF-8、CRLF、引用符・改行を含むfield、BOMの扱いを明示)を第一正本とします。複数シート、型、数式、結合セル、書式が必要な場合はODSを別アダプタ/Assetとして扱い、CSVへの不可逆変換を黙って行いません。行数、列数、セル長、総バイト、ネストmacroを制限し、malformed inputは安全なテキスト表示へfallbackします。
|
||||
|
||||
+193
-18
@@ -1,7 +1,7 @@
|
||||
# 15. RSSビューア・FreshRSS・newsboat
|
||||
|
||||
状態:内蔵簡易reader、FreshRSS読取connector、共通viewer、Wiki保存・タスク化、ダッシュボードを実装。
|
||||
OPMLの確認付き追加取り込み・書出し、FreshRSS購読・カテゴリのnavigationも実装済み。FreshRSSへの書戻しは残件。本番反映と実FreshRSSへの接続は未実施。
|
||||
OPMLの確認付き追加取り込み・書出し、FreshRSS購読・カテゴリのnavigation、opt-inの既読・star書戻しを実装済み。本番反映と実FreshRSSへの接続は未実施。
|
||||
既存のブログRSS「配信」と、本章の外部RSS「購読」は別機能。
|
||||
|
||||
2026-11-08:利用者指定のサブプロジェクト順で最初に実施する。内蔵readerは簡易利用の
|
||||
@@ -33,7 +33,7 @@ FreshRSS停止時は取得済みcacheと鮮度・接続状態を示し、内蔵
|
||||
## 実装済みの読取機能
|
||||
|
||||
`/v/feeds` に購読一覧、フォルダ、記事一覧、外部原文へのリンク、Wiki保存を提供します。
|
||||
FreshRSSの記事・既読・starは取得しますが、状態の変更は送信しません。UIにも読取専用と明示し、
|
||||
FreshRSSの記事・既読・starを取得します。既定は読取専用で、source設定で明示的に許可した場合だけ状態の変更を送信します。
|
||||
FreshRSS passwordを設定時以外にブラウザへ返さず、login tokenはbackend内でのみ利用します。
|
||||
資格情報は既存の暗号化機構を使い、Domain・所有者・source UUID・用途に束縛します。
|
||||
|
||||
@@ -50,9 +50,9 @@ newsboat/neomuttを参考に、デスクトップは左から購読元・一
|
||||
tooltipに残します。タブ名は「RSS」、原文リンクはアイコンです。件数・保持上限・操作の説明は常設せず、
|
||||
キー案内は`?`で表示します。設定と保存フォームは本文ペイン内に置き、モーダルを増やしません。
|
||||
|
||||
`j/k`・上下矢印で移動、`Enter/l`で本文、`Esc/h`で一覧、`/`で件名・配信元検索、`n`で次の未読、
|
||||
`j/k`・上下矢印で記事移動、`Shift+j/k`で次/前のFreshRSSフォルダ、`Enter/l`で本文、`Esc/h`で一覧、`/`で件名・配信元検索、`n`で次の未読、
|
||||
`m`で既読切替、`*`でstar、`r`で背景更新予約、`?`でキー案内です。フォーム入力・IME変換中は
|
||||
一覧ショートカットを抑止します。FreshRSSでは`m`と`*`も外部変更を行いません。
|
||||
一覧ショートカットを抑止します。FreshRSSでは書戻し許可時だけ`m`と`*`で操作を予約します。
|
||||
|
||||
HTML本文は見出し・表・箇条書き・強調・リンクを保持して描画し、plain textは文字情報として表示します。
|
||||
server側の許可リストでscript・イベント属性・任意CSS・form・iframe・画像等を除去し、表示時にも再検査します。
|
||||
@@ -72,10 +72,16 @@ API prefixは `/_/api/v1/extension/organizer.feeds/`。Domain内の本人専用
|
||||
| `POST sources/{uuid}/refresh` | 次回背景取得を予約。画面から外部通信しない |
|
||||
| `POST sources/{uuid}/delete` | versionを照合してsource・cache・内蔵read/starを削除 |
|
||||
| `GET items` | source/unread/starred/件名・配信元で絞り込み、100件単位のkeysetページング |
|
||||
| `GET catalog?source=…` | 本人のFreshRSS購読・カテゴリの取得済み一覧。外部通信なし |
|
||||
| `GET catalog?source=…` | 本人のFreshRSS購読・カテゴリの取得済み一覧。`subscriptions`と空フォルダも含む`folders`。外部通信なし |
|
||||
| `GET item?source=…&id=…` | 本人の記事本文 |
|
||||
| `POST state` | 内蔵read/starの条件付き変更。FreshRSSは拒否 |
|
||||
| `POST remote-state` | FreshRSSの一記事・一項目の変更を予約。request_id、source、id、field、desired、source_versionを指定 |
|
||||
| `GET action?source=…&id=…` | 本人の記事の最新操作記録。外部通信なし |
|
||||
| `GET actions` | 本人の操作履歴。status/sourceで絞り込み、50件単位のkeysetページング |
|
||||
| `GET action/export?request_id=…` | 本人の操作記録1件をJSON attachmentで保存。資格情報・本文・worker claimは含めない |
|
||||
| `POST action/check` | request_idで結果不明操作の読取専用再確認を予約 |
|
||||
| `POST note` | 公開範囲確認付きのWiki単独保存。request_idと入力hashで再送を識別 |
|
||||
| `POST capture-preview` | Wiki親Pathのプレースホルダを展開。保存・外部通信なし |
|
||||
| `GET opml/export` | 本人の内蔵購読をOPML 2.0としてダウンロード |
|
||||
| `POST opml/preview` | ファイルを解析し、追加可能・登録済み・重複・未対応等を返す。保存・外部通信なし |
|
||||
| `POST opml/import` | 選択行を再解析・検査し、確認時の購読設定と一致する場合だけ原子的に追加 |
|
||||
@@ -86,6 +92,12 @@ v2で`feed_items.body_html`を追加します。既存のテキスト本文・
|
||||
v3で`feed_import_receipts`を追加し、購読の一括追加と再送記録を同時保存します。
|
||||
v4でsourceに購読一覧、記事にremote feed ID・カテゴリIDを追加します。FreshRSSの旧workerを
|
||||
versionで無効化し、次の背景取得を予約します。内蔵sourceのversion・取得予約は変更しません。
|
||||
v5でsourceの`write_enabled`(既定OFF)と`feed_actions`を追加します。操作記録はsourceを削除しても保持し、
|
||||
送信済みの可能性があるものはunknown、未送信はcancelledにします。
|
||||
v6でsourceに`remote_folders`を追加します。既存の購読・記事・設定version・取得予約・worker claim・
|
||||
書戻しreceiptは変更しません。初回の背景取得までは既存の購読情報から分類を組み立て、
|
||||
空フォルダは次の取得成功時に追加します。DB更新前にバックアップを取得し、
|
||||
旧バイナリへの切戻しだけで追加schemaが巻き戻るとは扱いません。
|
||||
既存テーブルを破壊・再構成しません。SQLiteのforeign_keys設定に依存せず削除を完遂するtriggerを
|
||||
持ちます。内蔵read/starを本文cacheから分離し、記事を保持窓から落としても状態は黙って消しません。
|
||||
DBは内蔵購読・状態・保存receiptの正本であり、全体を捨てられるcacheとは扱いません。
|
||||
@@ -100,13 +112,14 @@ sourceのprovider・URL・資格情報の変更は別sourceを作る契約です
|
||||
| --- | --- |
|
||||
| 個人のsource数 | Domain・本人ごとに32 |
|
||||
| 定期event | `feed.source.sync`、既定60秒周期、低優先度、1回最大4 sourceを直列取得 |
|
||||
| 書戻しworker | 同じevent内で最大2操作を先に処理。各8秒、取得と合計35秒の予算を共有し、残り9秒未満なら次の操作・取得を開始しない |
|
||||
| source更新間隔 | 5〜1440分、既定30分。取得候補になる間隔であり、混雑時の完了時刻保証ではない |
|
||||
| 通信予算 | 1 source 8秒、batch 35秒、応答/展開後本文4 MiB |
|
||||
| 外部接続 | 公開HTTPS/443のみ。DNS検査・接続先固定、内部アドレス・redirect・proxyを拒否 |
|
||||
| 内蔵記事cache | 1 source最大500件、text本文32 KiB・HTML本文128 KiB。HTML上限超過はtextへフォールバックし、text切詰めを明示 |
|
||||
| 内蔵read/star | 1 source最大10,000件。上限では新規状態保存を拒否し、既存状態を捨てない |
|
||||
| FreshRSS | reading-list最新200件の窓を取得。更新成功時はその窓で置換し、全履歴同期とはしない |
|
||||
| FreshRSS購読一覧 | 最大1,000購読、1購読64カテゴリ、保存JSON 1 MiB。記事と同じ取得予算で収集 |
|
||||
| FreshRSS購読・分類一覧 | 最大1,000購読・1,000フォルダ、1購読64カテゴリ、保存JSON合計1 MiB。記事と同じ取得予算で収集 |
|
||||
| 再試行 | 次の設定間隔まで待機。手動予約にも最終成功から60秒の制限、取得中の重複claim拒否 |
|
||||
|
||||
内蔵は条件付きGET、304ではcacheを保持します。どちらのproviderも通信・認証・構文失敗で
|
||||
@@ -116,33 +129,123 @@ extension無効化は画面・API・取得・完了保存に適用します。
|
||||
|
||||
### FreshRSSの購読とカテゴリ
|
||||
|
||||
背景取得ではlogin後にreading-listと`subscription/list`を読み、両方に成功した場合だけ
|
||||
記事・購読一覧を同じtransactionで置換します。一方の取得失敗、上限超過、不正なsnapshotでは
|
||||
前回の両cacheを保持します。記事が取得窓内にない購読も一覧には残します。
|
||||
背景取得ではlogin後にreading-list・`subscription/list`・`tag/list`を読み、すべてに成功した場合だけ
|
||||
記事・購読一覧・分類一覧を同じtransactionで置換します。一部の取得失敗、上限超過、不正なsnapshotでは
|
||||
前回のcache全体を保持します。記事が取得窓内にない購読も一覧には残します。
|
||||
`tag/list`は`type=folder`だけを分類として取り込み、記事タグとシステムの状態タグは除外します。
|
||||
購読一覧のカテゴリとIDで統合し、購読元のない空フォルダも保持します。
|
||||
|
||||
左ペインでFreshRSS sourceを選ぶと、接続先→分類フォルダ→購読元のツリーを表示します。
|
||||
フォルダ名は記事の絞り込み、隣の矢印は開閉と役割を分けます。開閉状態は接続先UUID単位で
|
||||
ブラウザのlocalStorageに保存し、利用できない場合もその画面内では保持します。
|
||||
閉じたフォルダは購読元のDOMを作らず、展開時は50件ずつ描画します。購読名・分類名で検索すると
|
||||
該当購読を重複なしで一覧化します。名前に含まれる`/`は文字として扱い、独自の階層には分割しません。
|
||||
|
||||
左ペインでFreshRSS sourceを選ぶとカテゴリ選択・購読名の検索・購読一覧を表示します。
|
||||
カテゴリは表示名でなくremote category ID、購読は`origin.streamId`とsubscription IDを対応させます。
|
||||
同名でも混同せず、複数カテゴリに属する購読も扱います。`GET items`の`feed`/`category`は
|
||||
同名でも混同せず、複数カテゴリに属する購読は各フォルダに表示します。記事の分類絞り込みは
|
||||
記事タグではなく同期した購読元の所属を使い、FreshRSSでの分類移動に追従します。
|
||||
分類のない購読は「未分類」に表示し、購読一覧にない記事を未分類へ混在させません。
|
||||
`GET items`の`feed`/`category`/`category_mode=uncategorized`は
|
||||
source指定と組み合わせ、既存の未読・star・検索・keysetページングと併用できます。
|
||||
`category`と`category_mode`の同時指定は拒否します。
|
||||
絞り込み対象は最新200記事のcache内に限られ、購読を選んでも履歴全件を外部取得しません。
|
||||
購読の追加・削除やカテゴリの編集はFreshRSS側で行います。
|
||||
|
||||
## 既読・star同期を追加する条件
|
||||
`Shift+j`/`Shift+k`は、選択中のFreshRSS接続内のフォルダを表示順に選び直します。
|
||||
空フォルダと未分類も含め、先頭・末尾では停止します。「すべての購読」からは、下方向なら先頭、
|
||||
上方向なら末尾を選びます。購読元を選択中なら、その所属フォルダを起点とします。
|
||||
記事検索・未読/starフィルタ・フォルダ開閉状態は維持し、個別購読元の絞り込みは解除します。
|
||||
購読・フォルダの検索でツリーが隠れている場合は、そのナビゲータ検索だけを解除します。
|
||||
前の本文と本文リクエストは破棄して一覧へ戻し、連打では最後の選択だけを反映します。
|
||||
フォーム・編集可能領域・モーダル・IME入力中、およびCtrl/Alt/Commandとの併用では実行しません。
|
||||
source自体の切替、分類の移動・書換え、外部再取得、未読/既読変更は行いません。
|
||||
|
||||
ショートカットヘルプは`?`で開閉し、`Esc`または閉じるボタンでも閉じます。
|
||||
ヘルプだけを閉じる操作では閲覧中の記事や入力フォームを変更せず、エラー等のstatus表示も保持します。
|
||||
|
||||
`sharing.x`が有効なDomainでは、本文の操作列にX共有アイコンを表示します。
|
||||
共有するのは記事の件名と原文URLで、RSS画面や非公開WikiのURLではありません。
|
||||
URLはintentの`url`にだけ渡し、`text`へ重複させません。原文URLのない記事では表示しません。
|
||||
通常の`target=_blank`リンクを一つだけ使い、JavaScriptによる二重openや自動投稿は行いません。
|
||||
|
||||
個人設定の「RSSの記事リンクの開き方」は`rss_link_mode`として保存します。既定は`tab`、
|
||||
`embedded`を選ぶと原文リンクとHTML本文中の外部HTTP(S)リンクを同一タブ内の大きなdialogで開きます。
|
||||
外部ページはクリック時だけiframeへ読み込み、閉じる際に破棄します。元の記事・一覧の状態は維持します。
|
||||
Ctrl/Command/Shift付きのクリック等はブラウザ標準の別タブ操作を維持し、X共有アイコンも対象外です。
|
||||
設定はRSS画面の再読込後に反映します。個人設定はタスク拡張のpreferencesに保存し、無効時は別タブを使います。
|
||||
|
||||
iframeは`allow-scripts`だけのsandboxと`no-referrer`を使い、親画面への操作・同一origin権限・
|
||||
フォーム送信・popup等は許可しません。PagesWiki自身のoriginはiframe化しません。
|
||||
リンク先のCSP/X-Frame-Options、ブラウザのmixed-content制限を回避するproxyは用意しません。
|
||||
表示できないページやログイン・フォーム操作が必要な場合は、dialog内の別タブアイコンを使います。
|
||||
表示可否をcross-origin DOMの読取で判定したり、失敗を装って自動で別タブへ遷移したりはしません。
|
||||
|
||||
### Geckoと自前Wispによる原文閲覧
|
||||
|
||||
通信中継方式を採用する。実装は独立した実験的ビューアとして段階導入し、現行の`tab`/`embedded`を
|
||||
自動置換しない。Geckoビューア・中継・個人設定の接続を実装した。`viewer.gecko`は既定無効で、
|
||||
管理者による有効化と中継の構成が揃った場合だけ選択できる。本番への配備は別途行う。
|
||||
|
||||
端末上の`gecko.js`で1ページを描画し、外部HTTP(S)通信だけを管理者が配置したWispサービスへ中継する。
|
||||
サーバー上でFirefoxを起動したり画面をストリーミングしたりはしない。Firefox全体の操作画面は含めず、
|
||||
既存の記事上dialogにcanvas、戻る・進む・再読込・閉じる・別タブの操作を置く。
|
||||
自前中継を必須とし、Puter等の公開中継への自動fallbackは設けない。
|
||||
|
||||
現行upstreamはGeckoのソケット通信をWispへ接続する。通常のWebページの`fetch`へ単純に置き換えて
|
||||
任意のサイトを直接取得することは前提にしない。GeckoとWisp実装は検証したrevision・プロトコルで固定し、
|
||||
更新時にサイト互換性とセキュリティ修正を再評価する。
|
||||
[gecko.js v0.0.1](https://github.com/HeyPuter/firefox-wasm/releases/tag/v0.0.1)、
|
||||
[Wisp仕様](https://github.com/MercuryWorkshop/wisp-protocol/blob/main/protocol.md)。
|
||||
|
||||
中継はPagesWiki本体とは別コンテナ・別ネットワーク境界とする。外部から無認証で利用できる公開proxyにしない。
|
||||
既存の認証・Domain・本人に束縛した短命セッションを発行し、WebSocketのOriginを検証する。
|
||||
失効・ログアウト・拡張無効化は既存の接続にも反映する。Cookie・WikiのBearer token・FreshRSS資格情報を
|
||||
外部ページへ渡さず、中継用の秘密をURLやログに残さない。
|
||||
|
||||
接続先は公開HTTP(S)用のTCPポートに限定し、UDPや任意の管理用ポートは許可しない。
|
||||
DNS解決後の実接続先でloopback・private・link-local・metadata等を拒否し、IPv4/IPv6・DNS rebindingを
|
||||
含めて検査する。接続検査だけでなくコンテナの外向き通信制限を併用し、Wiki・DB・管理ネットワークへ到達させない。
|
||||
同時セッション・ソケット・帯域・idle/接続timeoutの上限を設ける。ログは通信量・失敗分類・処理時間に限り、
|
||||
記事本文や資格情報を記録しない。HTTPSの証明書検証を無効化せず、HTML改変やTLS終端による閲覧制限回避は行わない。
|
||||
|
||||
原文クリック時だけエンジンを遅延ロードする。静的WASM資産はversion付きでキャッシュするが、
|
||||
記事本文・Cookieの永続化は初期対象外とし、上限付きのメモリプロファイルを渡す。
|
||||
固定版の`destroy()`はWASMの完全終了を保証しないため、初期実装では短時間保持を行わず、
|
||||
閉じるとiframeごと破棄する。タブ非表示が60秒続いた場合も閉じる。
|
||||
戻る/進むは最大64件のビューア内URL履歴から再読み込みし、フォームやスクロール位置は復元しない。
|
||||
上流の最小GREではSessionStoreFunctionsがなく、標準history.back()は失敗する。
|
||||
中継の接続数・転送量・拒否数は認証付きstatus/CLIで取得できる。設定UIへの監視統合と端末側計測は残件とする。
|
||||
|
||||
pthread/SharedArrayBufferのcross-origin isolationはRSSの親documentまで含めて検証する。
|
||||
COOP/COEPをWiki全体へ一律追加せず、対象ビューだけで既存の壁紙・外部リソース・共有操作への影響を確認する。
|
||||
isolation不可・端末のメモリ不足・未対応サイトではエラーと別タブ操作を示し、黙って外部中継や別タブへ切り替えない。
|
||||
|
||||
受入条件は、合成ページでのnavigation・日本語入力・検索・コピー、私有アドレス拒否・認証失効・中継停止・
|
||||
資源上限・無効化、デスクトップとiPhone SEのSafariでの初回/再表示時間・スクロール・メモリ確認とする。
|
||||
実記事での測定は明示した対象で行い、実FreshRSSの全原文や外部カレンダー・メール内容を自動巡回しない。
|
||||
|
||||
現時点ではChromiumで合成Wisp記事の描画・クリック遷移・ビューア内の戻る・接続破棄、
|
||||
接続先制限・資格情報分離・ログアウト/拡張無効化時のWebSocket終了を自動テストした。
|
||||
導入方法、資産hash、資源上限、外向きfirewallと本番前の残件は[Gecko中継の試験導入](../../operations/gecko-relay.md)にまとめる。
|
||||
|
||||
## 既読とstarの書戻し
|
||||
|
||||
server-authoritative stateと未送信の操作を分けます。操作ごとのrequest_idで重複を防ぎ、成功応答前に確定済みと表示しません。newsboat等で同時変更された場合、古いローカルcacheをまとめて送り返しません。接続解除・認可失効時は未送信変更を勝手に再送しません。
|
||||
|
||||
FreshRSS APIに条件付き更新がない操作もあり得るため、対応版の実機fixtureで競合動作を確認するまで完全な双方向同期を約束しません。
|
||||
FreshRSSへの変更は一項目のtag追加・削除です。更新直前の状態と不可分に照合するCASではないため、
|
||||
他clientとの同時操作を完全に直列化する双方向同期ではありません。
|
||||
|
||||
### 書戻しの次段階設計
|
||||
### 操作記録と送信状態
|
||||
|
||||
以下は未実装のRSS-3です。購読navigationの追加だけでは書戻しを有効にしません。
|
||||
sourceごとに既定OFFの書戻し設定を設け、操作は`read`または`starred`の一項目と希望値に限定します。
|
||||
RSS-3は合成環境で実装・検証済みです。sourceごとに既定OFFの「FreshRSSの既読・star変更を許可」を設け、操作は`read`または`starred`の一項目と希望値に限定します。
|
||||
cache内の他項目を同時に送らず、全件既読・購読編集も初期対象に含めません。
|
||||
|
||||
操作記録は記事cacheから分離し、Domain・本人・request_id、source・記事ID、対象項目、希望値、
|
||||
source version、状態、claim期限を保持します。同一request_idの同じ入力は同じ記録を返し、
|
||||
違う入力は拒否します。同じ記事に未解決の操作がある間は次の操作を受け付けません。
|
||||
受付APIは外部通信せず、低優先度workerが送信します。記録数とworkerの時間予算は必ず有限にします。
|
||||
受付APIは外部通信せず、低優先度workerが送信します。Domain・本人ごとに未解決20件、全記録10,000件を上限とし、
|
||||
上限で新規受付を拒否します。receiptを自動削除して古い要求を再送可能にすることはしません。
|
||||
queuedは受付から5分で失効します。claimは60秒で、期限切れsending/checkingはunknownにし、変更を再送しません。
|
||||
|
||||
| 状態 | 次の処理 |
|
||||
| --- | --- |
|
||||
@@ -160,6 +263,48 @@ source version、状態、claim期限を保持します。同一request_idの同
|
||||
外部clientとの同時変更を原子的に防げないAPIでは、確認直後に状態が再変更される可能性もあります。
|
||||
readbackは観測結果であり、exactly-onceやリモートCASの保証とは区別します。
|
||||
|
||||
結果不明時は操作欄の`↻`からclaim期限後に再確認できます。書戻し設定をOFFにしても、sourceが有効なら
|
||||
この読取専用再確認は可能です。画面は未解決操作の間だけ2秒間隔で自サーバーの記録を確認し、
|
||||
背景タブでは停止します。記事の既読・star表示は遠隔の状態を確認するまで切り替えません。
|
||||
再確認で希望値と異なる場合はconflictを表示し、新しい変更は利用者が明示的に操作します。
|
||||
|
||||
### 操作履歴の一覧と保全
|
||||
|
||||
ツールバーの時計アイコンから、リーダー内に操作履歴を開きます。モーダルは増やしません。
|
||||
日時、記事・購読元、変更対象と希望値、状態をまとめ、記事がcache内なら本文へ戻れます。
|
||||
スマホ幅では日時・件名・状態を縦にまとめ、再確認・保存のアイコンをタッチできる大きさにします。
|
||||
|
||||
既定の「未解決」はconfirmed/cancelled以外を表示し、処理中、結果不明、すべて、確認済み、
|
||||
未送信、不一致、中止で絞り込めます。一覧はローカルDBだけを読み、外部通信や自動再試行を行いません。
|
||||
履歴の更新は再読込アイコンと絞り込み操作で行い、記事画面の2秒pollは履歴画面では停止します。
|
||||
`GET actions`のstatusは`unresolved`(省略時も同じ)、`pending`、`unknown`、`all`、
|
||||
`confirmed`、`failed`、`conflict`、`cancelled`です。sourceは削除済みUUIDも指定できます。
|
||||
続きは末尾のcreated_msとrequest_idを`before`/`key`として渡します。同時刻の操作も重複・欠落なく辿ります。
|
||||
1回50件+続き判定の1件を読み、所有者の10,000件上限でソート量を制限します。
|
||||
|
||||
sourceや記事へのinner joinは使わず、削除済み購読元やcache窓から外れた記事の記録も残します。
|
||||
記事名・購読元名は現在の取得済み情報であり、操作時点の監査snapshotではありません。
|
||||
取得できない場合は元のsource UUID/記事IDと「削除済み」「キャッシュ外」を表示します。
|
||||
結果不明の記録は、同じDomain・本人の有効なFreshRSS sourceが残り、claim期限を過ぎた場合だけ
|
||||
読取専用再確認を予約できます。書戻しOFFでも再確認でき、readonlyアカウントは閲覧・保存のみです。
|
||||
削除済みsourceは自動再接続しません。本人の記録に残るsource UUID、および全体の未解決操作に
|
||||
残るsource UUIDの新規登録を拒否し、別接続先への誤った結び付けを防ぎます。
|
||||
|
||||
各行からJSON形式(`pageswiki.feed-action`、version 1)の記録を書き出せます。
|
||||
Domain/本人/request ID、操作内容、状態、日時、現在の表示用メタデータを含み、
|
||||
外部URL・資格情報・本文・内部claimは出力しません。ただし元の記事ID自体がURLの場合はそのIDを保持します。
|
||||
一覧・保存ともDomain・本人で制限し、private/no-storeで返します。schemaはv5のままです。
|
||||
|
||||
保存操作はDBからの削除を意味しません。receiptを削除すると同じrequest_idの再送を防げなくなるため、
|
||||
自動削除・一括削除は未実装です。後段の整理機能では、保全manifest・hash・対象件数を照合した上で、
|
||||
成功/中止/失敗等の終端記録だけをarchiveへ移し、重複防止に必要なrequest_idと入力識別子を
|
||||
tombstoneとして保持します。unknownや実行中の記録は移動・削除対象にしません。
|
||||
tombstoneの保持期間・容量上限・旧クライアントからの再送時応答を決めるまで、現在の10,000件上限を維持します。
|
||||
|
||||
外部APIはlogin、記事参照、変更token、edit-tag、記事再参照の順です。記事の個別参照は
|
||||
`POST stream/items/contents`(読取操作)、変更は`POST edit-tag`に`i`・`T`・`a`または`r`一項目を送ります。
|
||||
URLや本文、資格情報を操作記録・ログへ保存しません。[FreshRSS API実装](https://github.com/FreshRSS/FreshRSS/blob/edge/p/api/greader.php)。
|
||||
|
||||
受入テストは、opt-inなしの拒否、同じ操作の再送、別項目の保持、送信前の権限失効、
|
||||
送信直後の応答喪失、worker停止・再起動、unknownの読取専用再確認、source削除・設定変更、
|
||||
通常取得との排他、他clientによる同時変更を含めます。実サービスを使わない合成fixtureで
|
||||
@@ -207,6 +352,23 @@ previewはsource UUID・設定versionのsnapshotを返し、適用時に一致
|
||||
|
||||
既定はURL、出典、短いメモの保存です。全文保存は取得可能性・利用条件・個人用途等を確認する独立操作とし、feedが短いからといって有料記事を自動取得しません。保存先が自動公開範囲なら内容と添付の公開を明示確認します。
|
||||
|
||||
タスク拡張が有効な場合、Wiki親Pathの初期値はDomain・本人単位の個人設定`wiki_prefix`を使います。
|
||||
「個人設定 → メール・RSS取り込みの既定Wiki親Path」で設定し、メール取り込みと共通です。
|
||||
RSS画面を読み込んだ時点の値を初期表示し、取り込みごとの上書き・空欄への変更を許します。
|
||||
空欄でタスク作成を選んだ場合はWikiを作らず、個人設定の値を再適用しません。
|
||||
未設定またはタスク拡張が無効な場合は空欄です。プロジェクトのWiki配下への暗黙の補完はRSSでは行いません。
|
||||
保存時の公開範囲確認とACL検査は省略しません。既存preferencesを利用するため追加のschema変更はありません。
|
||||
|
||||
親Pathでは`{YYYY}`・`{MM}`・`{DD}`・`{Subject}`を使用できます。日付は取り込み時のドメインの
|
||||
タイムゾーン、Subjectは編集可能な取り込み件名です。件名中の区切り文字・URI演算子・制御文字・
|
||||
空白はハイフンに変換し、180バイト以内の単一Path要素へ整形します。空になる場合は`untitled`です。
|
||||
未対応トークンや不正なPathは拒否します。メールcaptureでも同じ展開規則を適用します。
|
||||
|
||||
RSS取り込みは本文上のdialogで行い、本文を置き換えません。トークン挿入ボタンと実際の保存先を
|
||||
表示し、件名・親Path・保存種別を変更した場合はプレビューを更新して公開範囲の確認をやり直します。
|
||||
展開済みPathを確認後の要求へ固定し、UUIDの末尾(Wiki単独は`rss-`、タスク併設は`mail-`)で
|
||||
同名記事の衝突を避けます。表示された親Path自体を記事ファイルとして上書きする仕様ではありません。
|
||||
|
||||
Wiki単独は親Path配下の `rss-{request UUID}` に新規作成します。既存Pathを上書きせず、Page・Path・
|
||||
初回Revision・活動outbox・再送receiptを同じDB transactionで保存します。権限はtransaction内でも
|
||||
再確認します。初期版の単独保存は通常Wiki空間のみで、独自所有契約を持つ`/u`・`/g`は対象外です。
|
||||
@@ -222,12 +384,25 @@ Wiki単独は親Path配下の `rss-{request UUID}` に新規作成します。
|
||||
|
||||
- [x] RSS-1:read-only FreshRSS connectorと合成fixture。実接続の受入は別。
|
||||
- [x] RSS-2:安全な共通一覧、出典付きWiki保存、任意のタスク化、ダッシュボード。
|
||||
- [ ] RSS-3:FreshRSSへの明示的な既読/star操作と送信状態・競合・再送の契約。
|
||||
- [x] RSS-3:opt-inの既読/star書戻し、操作receipt、背景処理、readback、結果不明の再確認、失効・競合・排他の合成試験。
|
||||
- [x] RSS-3b1:未解決操作の総覧、cache窓外・削除sourceの記録、再送しない再確認、個別JSON保存。50件ページング、本人分離、readonly、1440px/390pxの合成試験。
|
||||
- [ ] RSS-3b2:保全manifestの照合、終端receiptのarchive、重複防止tombstoneと保持期間・容量上限。未知結果の記録を捨てない。
|
||||
- [x] RSS-4a:内蔵簡易reader、購読設定、既読・star、背景取得。
|
||||
- [x] RSS-4b:OPML export/importのpreview、選択追加、重複確認、原子的な保存と再送防止。置換・状態移行は範囲外。
|
||||
- [ ] RSS-5:FreshRSS実環境の接続先・版・API資格情報を指定してread-only受入。
|
||||
- [ ] RSS-6:大規模利用時の公平性、host別並列上限、Retry-After/backoff、資格情報rotation UI。
|
||||
- [x] RSS-7:FreshRSSの購読一覧・カテゴリを使うnavigation。同名ID分離、複数カテゴリ、cache内絞り込み、背景での原子的更新、失敗時保持。
|
||||
- [x] RSS-7b:分類フォルダの継承、空フォルダ・未分類、開閉状態保存、50件ずつの購読描画、分類移動への追従。schema v6の再実行・失敗rollbackと1440px/390pxの合成試験。
|
||||
- [x] RSS-7c:Shift+j/kによるフォルダ選択。空・未分類・端・購読選択中・検索維持・入力/モーダル抑止・連打を合成試験。
|
||||
- [x] RSS-8a:Gecko端末描画+自前Wisp中継の方式決定。公開中継を使わず、独立・既定無効で導入する。
|
||||
- [x] RSS-8b1:upstream v0.0.1/hash固定、最小埋め込みと親documentのisolation、Chromiumで合成記事の描画・遷移確認。
|
||||
- [ ] RSS-8b2:Safari/iPhone SE実機、IME・コピー・実サイト互換性。固定配布物のlicense/notice整備、HTTPSと証明書エラー、日本語findの合成試験は実施済み。
|
||||
- [x] RSS-8c1:認証付きWisp TCP profile、公開IP/port制限、失効・資源上限・管理者/CLI無効化・内部status。
|
||||
- [ ] RSS-8c2:運用ホストの外向きfirewall、設定UIへの中継監視統合、負荷時の長時間受入。
|
||||
- [x] RSS-8d1:個人設定の選択、1ページのpopup閲覧、戻る/進む/再読込/別タブ/終了。
|
||||
- [ ] RSS-8d2:初回/再表示・低メモリ端末の性能評価、実行中の切断・複数タブのUX、本番配備。起動上限と起動失敗時のiframe破棄・原文リンクへの退避は実装済み。
|
||||
|
||||
一覧には配信日と配信時刻(HH:mm)を分けて表示します。Domainの設定タイムゾーンを使い、tooltipには年・秒・タイムゾーンを含めます。配信日時不明は「—」とし、取得日時で補いません。モバイルでも時刻欄を残します。
|
||||
|
||||
隔離試験はRSS/Atom・FreshRSS login/read、欠落ID・巨大/不正feed、条件付きGET、失敗時cache保持、
|
||||
本人分離・失効・readonly、二重送信・版競合・旧worker拒否、migration再実行/失敗rollback、
|
||||
|
||||
@@ -103,7 +103,7 @@ P0は認可・整合性・復旧の安全条件、P1は日常利用の回復性
|
||||
| SHARE-01 / P2 | 未実装:委譲share URL、期限/失効/監査、説明可能な権限総覧 | AUTH-01、PUB-01。login/adapter/federation資格情報と別目的、単一Page投影、caveat・依存物の失効を検証 | [公開](publication.md)、[Schutzaria](schutzaria.md) |
|
||||
| COLLAB-01 / P2 | 一部実装:Page等の変更購読、最近閲覧/編集、集約通知。コメント/反応/評価は未実装 | OUT-01。現在権限で再投影、private履歴のopt-in/保持。inline commentはRevision変更時の孤立・再接続を扱う | [拡張](extensions.md) |
|
||||
| BLOG-01 / P2 | 一部実装:安全なtDiary import、最近コメント、遠隔ブログ射影 | COLLAB-01、遠隔はFED-01。importは再開/重複抑止/dry-run。同一instance射影を再実装しない | [ブログ・日記](blog-diary.md) |
|
||||
| CSV-01 / P2 | viewerのみ実装:別Documentを投影するCSV macro/editor、ODS境界 | 行列・セル・総量上限、Revision固定、権限、CSV引用/改行fixture。表示HTMLをCSV正本へ逆流させない | [表設計](extensions.md) |
|
||||
| CSV-01 / P2 | viewerと有界CSV macroを実装。残件:CSV editor、匿名投影、asset指定、ODS境界 | 行列・セル・総量上限、Revision固定、権限、CSV引用/改行fixture。表示HTMLをCSV正本へ逆流させない | [表設計](extensions.md) |
|
||||
| DIAGRAM-01 / P2 | 一部実装:nwdiag/Draw.io provider、slide preview/editor | RENDER-01。安全なSVG・include拒否・renderer版固定、ticket/CAS保存、print。既存Excalidraw/Krokiとは分ける | [Kunstzeal](kunstzeal.md) |
|
||||
| RECIPE-01 / P2 | 未実装:構造化レシピmetadataとPage投影の初期slice | 材料・数量・未知単位を保持、人数変更は派生値、Asset認可、版競合、出典・公開確認 | [料理レシピ](recipe-management.md) |
|
||||
|
||||
@@ -111,7 +111,7 @@ P0は認可・整合性・復旧の安全条件、P1は日常利用の回復性
|
||||
|
||||
| ID / 優先 | 状態・次の作業 | 着手ゲート・最初の検証 | 詳細 |
|
||||
| --- | --- | --- | --- |
|
||||
| RSS-01 / P2 | 一部実装:内蔵簡易正本、FreshRSS読取connector、3ペインUI・HTML本文、Wiki保存・タスク化・dashboard、OPML確認付き入出力 | 残件はFreshRSS既読/star書戻し、購読/カテゴリnavigation、実接続受入、公平性/backoff。managed schema feeds v3・隔離fixture。本番未反映。二重正本・停止時の自動切替なし | [RSS](feeds.md) |
|
||||
| RSS-01 / P2 | 一部実装:内蔵簡易正本、FreshRSS読取・既読/star書戻し、購読/カテゴリnavigation、3ペインUI・HTML本文、Wiki保存・タスク化・dashboard、OPML、配信時刻 | 残件は実接続受入、公平性/backoff、Gecko実機・運用受入。個別の実装/受入状況はRSS設計を参照。二重正本・停止時の自動切替なし | [RSS](feeds.md) |
|
||||
| IMAP-01 / P3 | 未実装・選定待ち:IMAP読取同期 | provider/認証/保持を決める。UIDVALIDITY/UID、添付量、外部画像、失効をfixture化。neomutt captureは実装済みで別 | [メール](mail.md) |
|
||||
| TICKET-01 / P3 | 未実装:queue/番号/workflow/外部依頼者 | 共有範囲と状態遷移を定義、同時採番・失効・監査。既存個人タスクをticketと呼び替えない | [タスクとticket](tasks-tickets.md) |
|
||||
| EXT-01 / P3 | built-inのみ:第三者manifest/署名/隔離runtime、停止・rollback・観測 | capability・secret・host・予算・export契約。任意コードをGoプロセス内へ直接ロードしない | [拡張](extensions.md) |
|
||||
|
||||
@@ -14,6 +14,14 @@ childrenは現在Pathを既定にし、表示形式は本文macroの `view` 引
|
||||
|
||||
`/v/tree/{path}` は範囲を限定します。展開・全展開・全折りたたみ状態の保持、複数選択、rename・移動・削除はPath操作と一致させます。一般の子一覧から予約ユーザー領域を混入させません。再帰操作は事前の全対象確認と競合検出が必要です。
|
||||
|
||||
## Browserのアップロード
|
||||
|
||||
`/v/browser/{path}` の一覧へファイルをドロップすると、現在のPath配下へアップロードします。フォルダ行へのドロップではそのフォルダが宛先になります。既存の内部Path移動・選択操作とは区別します。
|
||||
|
||||
右下のフローティングカードに待機・送信中・完了・失敗・取消と進捗を表示します。追加ドロップは同じキューへ積み、送信は1件ずつ、最大100件・各256 MiBまで。待機中の取消、折りたたみ、終了分のクリアに対応します。終了後は一覧だけを再取得し、キューは残します。
|
||||
|
||||
既存の認可付き `/v/upload` を使用し、`If-None-Match: *` で同名Pathの上書きを防ぎます。通信断は保存結果不明として扱い、自動再送しません。キューはページ内のみで、ページ離脱・再起動後の再開やフォルダの再帰アップロードには未対応です。新規オブジェクト・Path・初回Revisionの一体的なトランザクション化は残課題です。
|
||||
|
||||
## ホームとブックマーク
|
||||
|
||||
通常トップバー型、中央検索型、検索+セクションカード型を選びます。セクションは手動URL/Path、または指定親の子リンクを表示します。設定は歯車のポップアップで、閲覧画面を編集フォームで埋めません。カード列はviewportに適応します。
|
||||
|
||||
@@ -23,6 +23,12 @@
|
||||
|
||||
### 3. テーマ・アカウント・連絡先
|
||||
|
||||
- [x] 信頼できる端末の長期ログイン(2026-11-08ローカル実装、本番未反映):ログイン画面の明示選択で最大30日。Domain管理者は設定→セッションで0〜30日(0で無効)を指定する。通常ログインは既存の絶対期限を維持。パスワード/TOTP、LDAP、OIDC、SMTPマジックリンクに適用し、選択は認証challengeに固定する。CookieとBearerの期限はDBの発行期限と一致し、ログアウト・管理者失効・アカウント停止で無効になる。既存セッションの延長、TOTPの省略、アクセスによる期限延長は行わない。
|
||||
- [x] 独立CLIの `pages login --remember` / `pages login --oidc --no-browser --remember`。S256 grantに選択を保存し、ブラウザ側のクエリで上書きできない。APIセッションは承認元ブラウザの残存期限を超えない。期限切れ後はlogoutなしで再認証でき、同一アカウントのcwdと未送信タスク下書きを保持する。別アカウントへの下書き移動は拒否する。旧サーバーは選択を無視する場合があるため、実際の期限は応答のexpires_inを正とする。
|
||||
- [x] タスク編集フッターの関連ページ導線(2026-11-08ローカル実装、本番未反映):アーカイブ・削除・保存と同じ並びに関連ページリンクを表示。新規タブで開き、編集中の内容を保持する。保存済みの関連Pageがない場合、解除した場合、Path変更が未保存の場合は非表示。デスクトップ/モバイル4幅のブラウザテストを追加。
|
||||
|
||||
長期ログインのDB変更はmanaged component `cli-auth` v2の `remember` 列追加のみ。既存行はfalse、既存セッションと文書・タスクデータは変更しない。端末名・一覧・個別端末の信頼登録、refresh token rotationは別設計とし、今回は既存セッション管理から失効する。
|
||||
|
||||
- [x] 共通ナビの◐からプリセットを選択、リロードせず切替。host限定Cookieに保持し、Domain既定に戻せる。登録済みテーマのみ許可。Domain設定/アカウントの全端末設定ではなくブラウザ上書き。失敗時は現在テーマを保持する。
|
||||
- [x] 絶対セッション期限:設定→セッション、5〜43200分、既定1440分。Domain単位で新規ブラウザ/APIログイン(OIDC/LDAPを含む)に適用。発行時にDBの期限を固定し、Cookie/APIのexpires_inにも反映。既存セッションの期限とCalDAVアプリパスワードは変更しない。管理者認可とサーバ側失効をfixture検証。
|
||||
- [ ] 無操作タイムアウトとアカウント別の短縮上書き:background pollingを人間の操作とみなさないactivity契約、再認証、既存セッションへの即時適用を別途設計する。
|
||||
|
||||
@@ -26,6 +26,14 @@ v0.3.0のOIDCログインは利用者の動作確認済み。v0.4.0ではOIDC承
|
||||
|
||||
## 利用方法
|
||||
|
||||
### 信頼できる端末でのログイン継続
|
||||
|
||||
2026-11-08ローカル実装、未リリース。独立CLIと対応サーバーを更新すると、`pages login --remember` または `pages login --oidc --no-browser --remember` で最長30日のセッションを要求できる。管理者の `auth_trusted_session_days`(既定30、0で無効)に従い、応答の `expires_in` を期限として保存する。旧サーバーでは通常の期限になる場合がある。
|
||||
|
||||
パスワードログインは必要なTOTPを維持する。選択はTOTP challenge/OIDC grantへ固定し、認証完了時の追加パラメーターで変更できない。CLI grantはmanaged component `cli-auth` v2で `remember` 列を追加し、既存行をfalseとして保持する。承認済みgrantの交換とセッション発行は従来どおり単一トランザクションで処理し、期限は承認元ブラウザの期限を超えない。
|
||||
|
||||
ローカル期限切れ後は `logout` を挟まず再ログインできる。同一アカウントならcwdと未送信タスク下書きを保持し、認証失敗時は従来のローカル状態を変更しない。ログアウト・管理者による失効・アカウント停止は長期セッションにも適用する。共有端末では使用しない。
|
||||
|
||||
```sh
|
||||
# 初回設定。パスワードはlogin時の非表示プロンプト、必要ならTOTPを続けて入力。
|
||||
pages configure --origin https://pages.example.test --username anya
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
- 見直し:見直す日を迎えたもの、または30日間変更されていない未完了タスク。
|
||||
- プロジェクト:名前とメモ、関連Wiki、所属タスクの一覧。タスクは一つのプロジェクトへ所属、または未所属。
|
||||
- タスク:件名、プレーンテキストのメモ、状態、優先度、分単位の見積もり、期限、取り組む日、見直す日、関連Wiki。
|
||||
- 完了/再開、アーカイブ/復元。完了取消でも過去の版は残る。初版は物理削除を提供しない。
|
||||
- 完了/再開、アーカイブ/復元。完了取消でも過去の版は残る。タスクの削除はアーカイブとは別の操作(下記)。
|
||||
- タイトル絞り込みとカーソルページング、変更履歴の版番号・日時表示。
|
||||
- 日本語/英語、既存テーマ、デスクトップの左ナビとモバイルの横ナビ・全画面編集モーダル。
|
||||
|
||||
@@ -34,6 +34,39 @@
|
||||
|
||||
一覧GETは `kind=task|project`、`view`、`project`、`q`、`limit`、`before` を受け付けます。既定60件、上限100件。作成はPOST、更新はPUT、`If-Match: "{version}"` 必須。ヘッダーなしは428、古い版は412。UUIDをクライアントで生成し、同内容の作成再送は同じ版を返します。異内容の再送は競合です。成功時は `item` と現在読める `page_path`、ETagを返します。一覧はメモ本文を省略するため、編集やクイック完了前に必ず詳細を取得します。
|
||||
|
||||
## タスクの削除
|
||||
|
||||
2026-11-08、v0.14.0で本番反映済み。[配備記録](../../operations/releases/2026-11-08-task-deletion.md)。
|
||||
|
||||
UUID検索は追加せず、既存のタスク編集画面で「アーカイブ/復元」の隣に「削除」を置きます。未保存の新規タスク、readonly、プロジェクト編集には表示しません。件名と削除範囲を確認してから実行し、削除失敗時は編集内容を保持します。アーカイブ済みタスクも同じ操作で削除できます。
|
||||
|
||||
- `DELETE /_/api/v1/extension/organizer.tasks/items/{uuid}`。PUTと同じ厳密な `If-Match: "{version}"` を要求し、成功204、未指定428、古い版412。成功応答を失った場合、同じ所有者・同じ削除前の版で再送できます。
|
||||
- 所有者・Domain・active状態・システム拡張の有効状態を同一writer transactionで再検査。他人の対象/削除記録は404。プロジェクトの削除は提供しません。
|
||||
- サブタスクがあれば409 `has_children`(アーカイブ済みも対象)。先に移動または削除します。実行中/一時停止中の集中セッション、実行中の作業記録があれば409 `working`。再帰削除・自動停止はしません。
|
||||
- head・版参照・期限通知予約・達成度メトリクスを削除し、カレンダー時間枠との関連は解除します。Wiki本文、カレンダーの予定、記録済みの作業時間は独立した記録として残します。削除タスクは通常/アーカイブ一覧・詳細・変更履歴から取得できず、復元操作もありません。
|
||||
- `organizer_task_deletions` にDomain、所有者、UUID、collectionで修飾したDAV名/UID、削除版、削除時刻だけを保持します。件名・本文は複写しません。DBとDocument Storeを一緒に保全する既存方針は変わりません。CASファイルや既存バックアップの安全消去を意味せず、保持期間・GCは別課題です。
|
||||
- 削除記録・head除去・関連索引の更新・変更ジャーナル/共通outboxは原子的にコミット。履歴移行ジョブは削除記録から種類を解決し、head欠落で停止しません。
|
||||
- DAVの一覧/REPORTから対象を除き、GETは404、multigetは対象ごとに404。旧ETagでのPUTは412。同じcollectionの同じUIDまたはhrefを使う新規/無条件PUTは既存の `no-uid-conflict` で拒否し、古い端末からの復活を防ぎます。削除済みUUIDへのJSON再作成は410。同名の件名を持つ**新しいUUID/DAV UID・href**のタスクは作成できます。DAV識別子の予約は索引再構築後も保持します。
|
||||
- 従来の「DAV DELETEをアーカイブへ変換する」互換動作は変更しません。今回追加した不可逆操作はWeb/APIからの明示的な削除です。クライアント固有の同期/競合UIの挙動まで保証するものではありません。
|
||||
|
||||
`internal/server/task_delete_test.go` で条件付き削除・権限・再送・DBロールバック・通知取消・作業履歴保全・DAV索引再構築/再送拒否を検証します。既存のChromiumテストに、削除ボタンの位置、確認キャンセル、版競合、成功後の一覧更新を追加しています。本番データの削除は実施しません。
|
||||
|
||||
### 削除済みメール取り込みの再作成
|
||||
|
||||
PagesWiki v0.14.1/pages-cli v0.4.2で実装、2026-11-08 19:42 JSTに本番反映済み。[配備記録](../../operations/releases/2026-11-08-task-capture-recovery.md)。サーバーとCLIの両方の更新が必要です。DBスキーマ変更や既存データの削除はありません。
|
||||
|
||||
`POST /_/api/v1/extension/organizer.tasks/capture` は、受付記録に対応するタスクの状態を本文ハッシュより先に確認します。削除済みなら同じ内容・異なる内容とも410 `deleted`。タスクと削除記録が両方欠落していれば409 `capture_missing` とし、自動修復・再作成はしません。存続中のタスクへの異内容再送は従来どおり412です。
|
||||
|
||||
削除済み要求の保留下書きは `pages task retry REQUEST_UUID --recreate-deleted` で明示的に再取り込みできます。CLIは新しい要求を送る前に保存し、以降の再送用IDを表示します。通信失敗後は表示された新IDで通常の `task retry NEW_REQUEST_UUID` を使います。メール本文・Wiki suffixは保持し、以前のタスクの状態・作業時間・子タスクを復元する操作ではありません。
|
||||
|
||||
- APIには `replaces_deleted` に元のrequest UUIDを渡します。新しい `request_id` はURL名前空間のUUIDv5で、名前は `pages:task-recreate:` と元のrequest UUIDを連結したもの。任意の後継IDを拒否し、同じ再取り込みの二重作成を防ぎます。
|
||||
- 同じDomain・所有者の受付記録と削除記録を要求し、元タスクが存続中なら412、他人の受付記録や不存在の要求は404。writer transaction内でも検査します。受付記録のない直接作成タスクには使えません。
|
||||
- 新しいタスク・受付記録・変更履歴・通知予約を原子的に保存します。旧受付記録、削除記録、DAV識別子の予約は残し、旧端末の再送による復活を防ぎます。
|
||||
- Wiki保存先にページが残っていれば、そのUUIDを新しいタスクに関連付けます。本文・リビジョンは上書きしません。存在しなければ保留本文から作成します。read/create/writeの現在権限と入力上限を検査し、ファイルなどページ以外との衝突は409です。保存先は保留要求と現在の既定値から解決するため、移動済みのWikiや既定Path変更を追跡して復元する機能ではありません。
|
||||
- 再作成済み要求の再送は同じ新タスクを返します。そのタスクも削除済みなら410で停止し、さらに復活させません。元のメールを再入力しただけでは削除済み状態を解除しません。
|
||||
|
||||
`internal/server/task_capture_recreate_test.go` でライフサイクル・並行再送・所有者境界・ロールバック・Wiki保持を検証し、CLIの単体テストとHTTP結合テストでも再送IDの保持を検証します。
|
||||
|
||||
## 保存と復旧の境界
|
||||
|
||||
`organizer_items` はDomain・所有者・UUID・種類・検索用メタデータ・現在版を保持します。本文を含む型付きJSONは既存Document StoreへSHA-256で保存し、同じJSONをDBにも保持します。`organizer_revisions` は版からDocumentへの参照、`organizer_changes` は後続処理用の小さな変更ジャーナルです。head更新・履歴・変更ジャーナルは同じSQLiteトランザクションです。
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# Gecko連携の再配布条件
|
||||
|
||||
PagesWiki v0.13.0ではGeckoエンジンの配布を保留しました。
|
||||
現在は固定版のエンジン、対応ソース、第三者NOTICE、日本語フォントを含む配布bundleを生成できます。
|
||||
実験機能`viewer.gecko`は既定無効のままです。relayイメージとbundleは別物で、
|
||||
起動時にbundle全体を検証してから資産を配信します。
|
||||
本書は今回追加した部品の配布判断と残件を整理するもので、プロジェクト全体の法務監査ではありません。
|
||||
|
||||
## 部品と適用条件
|
||||
|
||||
| 部品 | 固定する出典・版 | ライセンスと配布時の扱い |
|
||||
| --- | --- | --- |
|
||||
| PagesWiki連携・Go relay | このリポジトリのリリースcommit | 自作コード。上流の実装をコピーせずWispフレーム仕様に対応。GeckoのライセンスをWiki全体へ一律適用しない |
|
||||
| Go runtime / 標準ライブラリ | relayのビルドに使うGo 1.25系 | BSD-3-Clause。実ビルド環境のLICENSEを専用イメージ内`/licenses/Go.txt`へ収録 |
|
||||
| golang.org/x/net | v0.35.0、WebSocket実装 | BSD-3-Clause。モジュールのLICENSEを`/licenses/golang-x-net.txt`へ収録 |
|
||||
| Gecko / Mozillaの第三者コード | Firefox fork `2e1e835a5da5907e5ceef19aade58a7493f1e34d` | 主にMPL-2.0。ただし多数の個別licenseがあり、MPLだけの表示では不足。固定commitの総合noticeと該当sourceを扱う |
|
||||
| gecko.js wrapper / WASM追加コード | v0.0.1 `eadcb5fa828d7e8b54ae2df13b6b3208f6553944` | 後述のMPL追加commitを確認。固定配布物にはLICENSE一式がないため、tarをそのまま再公開しない |
|
||||
| Emscripten runtime / WasmFS | 6.0.1と上流のpatch | Emscripten本体はMITまたはUIUC/NCSA。libc等のruntime依存には別noticeがあるため、ツールチェーンの最上位LICENSEだけでは棚卸し完了としない |
|
||||
| zstddec | 0.2.0 | npm metadataは`MIT AND BSD-3-Clause`。JS wrapperと組み込まれたdecoderの両noticeを保持 |
|
||||
| Liberation fonts | 上記Firefox commit内のPDF.js standard_fonts | SIL OFL 1.1。著作権表示・OFL本文・Reserved Font Namesを保持 |
|
||||
| Rust standard libraryと依存crate | 1.95.0と`library/Cargo.lock` | RustのMIT/Apache-2.0と各crateの個別条件。lockに記載された全registry crateのsource・noticeを保持 |
|
||||
| Noto Sans CJK JP | Sans2.004、`523d033d6cb47f4a80c58a35753646f5c3608a78` | SIL OFL 1.1。未改変OTF、Adobeの埋込著作権表示、OFL本文を保持 |
|
||||
|
||||
relayのruntimeイメージは`FROM scratch`とし、Goバイナリとlicenseだけを含めます。
|
||||
Alpine/BusyBoxを新たに再配布する構成にはしません。`go list -deps`でrelayにリンクされる外部Go moduleは
|
||||
`golang.org/x/net v0.35.0`のみと確認しています。ビルド用イメージと配布用runtimeイメージは区別します。
|
||||
|
||||
## 固定版とMPL宣言の関係
|
||||
|
||||
上流v0.0.1のcommitにはルートLICENSEがなく、翌日の
|
||||
[`ac40f56c85060bd49dfc36ca60490f97dd270c50`](https://github.com/HeyPuter/firefox-wasm/commit/ac40f56c85060bd49dfc36ca60490f97dd270c50)
|
||||
でMPL-2.0のLICENSEが追加されています。
|
||||
[固定版からの比較](https://github.com/HeyPuter/firefox-wasm/compare/eadcb5fa828d7e8b54ae2df13b6b3208f6553944...ac40f56c85060bd49dfc36ca60490f97dd270c50)
|
||||
の変更はLICENSE、Makefile、README、chrome demoの2ファイルです。
|
||||
`gecko.js/js`、`gecko.js/src`、`gecko.js/lib`、`gecko.js/emsdk-patches`はこの間に変更されていません。
|
||||
この事実を追加コードのMPL宣言の根拠として記録しますが、生成された全バイナリの第三者noticeを代替するものではありません。
|
||||
|
||||
v0.0.1の[Makefile](https://github.com/HeyPuter/firefox-wasm/blob/eadcb5fa828d7e8b54ae2df13b6b3208f6553944/Makefile)
|
||||
はFirefox forkのcommit `2e1e835a5da5907e5ceef19aade58a7493f1e34d`とEmscripten 6.0.1を指定しています。
|
||||
後続Makefileの参照先変更を混ぜず、再現には固定版側を使います。
|
||||
|
||||
固定版の[GRE縮小スクリプト](https://github.com/HeyPuter/firefox-wasm/blob/eadcb5fa828d7e8b54ae2df13b6b3208f6553944/gecko.js/stage-gre-min.sh)
|
||||
は`chrome/toolkit/content/global/license.html`を明示的に除外し、LiberationのTTFをコピーします。
|
||||
そのため、配布tarの存在やSHA-256一致だけでnoticeの充足を判断しません。
|
||||
|
||||
Wispのwire protocolは独立実装しています。固定版エンジンは独自の`gecko.js/lib/wisp-net.js`を使います。
|
||||
pnpm-lockにある`@mercuryworkshop/wisp-js`はdemo側依存で、lockfileに記載があることだけを根拠に
|
||||
PagesWiki relayの依存物・ライセンスとは扱いません。
|
||||
|
||||
## エンジンを配布する場合に必要な作業
|
||||
|
||||
MPLはファイル単位の義務であり、別実装のWiki全体をMPLへ変更するという意味ではありません。
|
||||
一方、WASMやJavaScriptを閲覧者のブラウザへ送信することも配布として扱う必要があります。
|
||||
**「イメージへ入れず、外部mountから配信すれば再配布ではない」という整理はしません。**
|
||||
[Mozilla MPL FAQ Q8・Q10・Q11・Q16・Q17](https://www.mozilla.org/en-US/MPL/2.0/FAQ/)、
|
||||
[MPL 2.0本文の3章](https://www.mozilla.org/en-US/MPL/2.0/)。
|
||||
|
||||
エンジンの本番有効化・再公開前に次を完了します。
|
||||
|
||||
1. 実際の配布WASM/JS/埋め込みGREと、対応するsource・patch・依存版を照合する。
|
||||
2. Mozillaの固定commitの総合notice、MPL本文、Emscripten/runtime、zstddec、fontの各著作権・licenseを収録する。
|
||||
Mozillaの総合noticeはbuild条件による表示があるため、未処理のHTMLを置くだけで完了としない。
|
||||
3. 受領者がnoticeと対応sourceの取得先を閲覧できる画面/ファイルを用意する。
|
||||
ソースは固定commitで指し、PagesWiki側でエンジンを変更した場合は変更も含める。
|
||||
4. 提供するsourceとnoticeの可用性・保全、配布物とのhash対応を検査する。
|
||||
5. Mozillaの商標はコードlicenseとは別に扱い、Firefoxの公式配布であるとの表現やロゴの流用をしない。
|
||||
|
||||
### 配布bundle
|
||||
|
||||
`tools/gecko/sources.lock.json`に取得元とSHA-256を固定し、`tools/gecko/bundle.py`で組み立てます。
|
||||
生成物は98ファイル、合計1,196,102,561 bytes(manifest自身を除く)です。
|
||||
manifestのSHA-256は`84953114f5e393dd97d9f948a5bc51c95b9355b58461dd3355e068a96cb2e381`。
|
||||
同じ値をrelay側で固定し、列挙された全ファイルのサイズ・hash・通常ファイルであることを起動時に検査します。
|
||||
不足、改変、symlink、別版混入を許可しません。
|
||||
|
||||
元のsource archiveを変更せず保存し、license/copying/copyright/notice/authorsファイルを別の閲覧用テキストにも集約します。
|
||||
Mozillaの条件付きnoticeは**全分岐を含む保守的な上位集合**としてテキスト化し、元のHTMLはsource archiveに保持します。
|
||||
Rustの追加依存はCargo.lockのチェックサムで検証します。crateから欠けていたFortanixのMPLヘッダと
|
||||
vex-sdkのMIT本文も、元ソース・固定commitから補完しています。
|
||||
Notoの未改変フォントには`© 2014-2021 Adobe (http://www.adobe.com/).`が埋め込まれ、READMEにも保持します。
|
||||
|
||||
閲覧画面のⓘは`/_/api/v1/extension/organizer.feeds/browser/distribution/v0.0.1/index.html`を開きます。
|
||||
同じ入口からNOTICE、manifest、ソース一式を取得できます。認証は必要ですが、RSS・Geckoを無効化した後も、
|
||||
認証済みの受領者はソースを取得できます。readonly利用者も取得可能です。
|
||||
relay自体を撤去する場合は、先にbundleと取得先を保全・移設してください。無効化はソース提供の撤回を意味しません。
|
||||
|
||||
CIは中継バイナリの4番目のイメージを配布しますが、約1.2GBのbundleを通常イメージへ重複同梱しません。
|
||||
検証済みbundleをread-onlyでmountする運用です。再配布条件の充足はこの固定版・未改変バイナリ・
|
||||
保持したsource/noticeを前提とします。依存更新時はlockとnoticeを再確認し、公開済みbundleを上書きしません。
|
||||
|
||||
## 一次資料
|
||||
|
||||
- [Gecko forkのLICENSEと商標注意](https://github.com/MercuryWorkshop/firefox/blob/2e1e835a5da5907e5ceef19aade58a7493f1e34d/LICENSE)
|
||||
- [同commitのMozilla総合notice](https://github.com/MercuryWorkshop/firefox/blob/2e1e835a5da5907e5ceef19aade58a7493f1e34d/toolkit/content/license.html)
|
||||
- [Liberationの著作権とOFL](https://github.com/MercuryWorkshop/firefox/blob/2e1e835a5da5907e5ceef19aade58a7493f1e34d/toolkit/components/pdfjs/content/web/standard_fonts/LICENSE_LIBERATION)
|
||||
- [Emscripten 6.0.1 LICENSE](https://github.com/emscripten-core/emscripten/blob/6.0.1/LICENSE)
|
||||
- [zstddec 0.2.0 metadata](https://registry.npmjs.org/zstddec/0.2.0)
|
||||
- [Go LICENSE](https://go.dev/LICENSE)
|
||||
- [golang.org/x/net v0.35.0 LICENSE](https://go.googlesource.com/net/+/refs/tags/v0.35.0/LICENSE)
|
||||
- [Noto CJK固定版OFL](https://github.com/notofonts/noto-cjk/blob/523d033d6cb47f4a80c58a35753646f5c3608a78/LICENSE)
|
||||
- [vex-sdk固定版MIT](https://github.com/vexide/vex-sdk/blob/6c0b83d35b6fc31a7607efe456e387df45476314/LICENSE.md)
|
||||
@@ -0,0 +1,175 @@
|
||||
# RSS Gecko中継の試験導入
|
||||
|
||||
RSS本文上で原文を読むための、端末側Gecko WASMと自前Wisp中継の実験機能です。
|
||||
通常の新規タブ・iframe表示は変更しません。DBスキーマ変更はありません。
|
||||
本番への自動導入・自動有効化は行いません。
|
||||
|
||||
## 構成と有効化条件
|
||||
|
||||
PagesWikiのログイン済み・activeな利用者だけが、
|
||||
`/_/api/v1/extension/organizer.feeds/browser/`以下を使います。
|
||||
同じDomainで`organizer.feeds`と`viewer.gecko`の両方が有効で、
|
||||
本体に中継URLと共有鍵ファイルが設定されていることが必要です。
|
||||
`viewer.gecko`はmanifestで既定無効です。個人設定の「RSSの記事リンクの開き方」で
|
||||
Geckoを選ぶと、RSS画面だけにCOOP/COEPを追加します。選択済みでも管理者が無効化した場合は新規タブへ戻ります。
|
||||
|
||||
ブラウザには中継の鍵を渡しません。本体が認証後に30秒の署名付きgrantを発行して内部HTTP要求へ追加します。
|
||||
WebSocketではOriginも検査し、grantは一回限りです。既存接続の認証・利用者状態・拡張の有効状態は5秒間隔で再検査します。
|
||||
中継はCookie、WikiのBearer token、FreshRSSの資格情報を受け取りません。
|
||||
|
||||
## 固定するエンジン
|
||||
|
||||
[HeyPuter/firefox-wasm v0.0.1](https://github.com/HeyPuter/firefox-wasm/releases/tag/v0.0.1)を使います。
|
||||
対応commitは`eadcb5fa828d7e8b54ae2df13b6b3208f6553944`です。
|
||||
|
||||
配布物`gecko.js-v0.0.1.tar.gz`のSHA-256:
|
||||
|
||||
```text
|
||||
bac28056a00ef6e5fb4345117e73d3629e75aca00dac71389fabbce39c018a73
|
||||
```
|
||||
|
||||
エンジン単体の`dist/`ではなく、後述するsource/notice付きbundleをread-onlyで`/gecko`へmountします。
|
||||
起動時に次の両ファイルに加え、manifestに列挙された全ソース・NOTICE・フォントをhash検査し、
|
||||
欠損・改変・異なる版の混在があれば中継は起動しません。
|
||||
|
||||
| ファイル | SHA-256 |
|
||||
| --- | --- |
|
||||
| gecko.js | e5aeebffd21106eccf23b1219316221add5e95085bc5a1bfb941117cfcd75ef7 |
|
||||
| gecko.wasm.zst | ebd6c75179152624d9644865e11792ed25cadc714d9e0985f412baf9c637a086 |
|
||||
|
||||
資産URLにも`assets/v0.0.1/`を含め、版をまたいだJS/WASMのcache混在を避けます。
|
||||
初回にはJS・圧縮WASM・日本語フォントの合計54,643,095 bytes(約52.1MiB)の転送とWASMの展開・compileが必要です。
|
||||
約1.2GBの対応ソースは閲覧の起動時には取得せず、ⓘから明示的にダウンロードするときだけ配信します。
|
||||
本体のDocker buildにFirefoxのソースビルドを加えません。
|
||||
|
||||
`Dockerfile.gecko-relay`は自前の中継バイナリだけを含みます。エンジンは同梱・再配布しません。
|
||||
**エンジンをイメージへ同梱する場合だけでなく、mountした資産を利用者へ配信する前にもnoticeと対応sourceの提供が必要です。**
|
||||
固定版のMPL宣言、第三者依存物、今回の配布範囲は[再配布条件](gecko-redistribution.md)を参照してください。
|
||||
v0.13.0の本番配備ではエンジンを配信していません。新しいrelayは完成したbundleを必須とします。
|
||||
|
||||
### bundle生成
|
||||
|
||||
Python 3.11以降を使い、十分な空き容量のあるディスク上で実行します。ソースarchiveは展開せず保持します。
|
||||
|
||||
```sh
|
||||
python tools/gecko/bundle.py --cache /srv/gecko-cache --output /srv/gecko/v0.0.1-bundle1
|
||||
# 同一入力からの再生成。出力先はまだ存在しない新しいディレクトリを指定する。
|
||||
python tools/gecko/bundle.py --cache /srv/gecko-cache --output /srv/gecko/rebuilt --offline
|
||||
```
|
||||
|
||||
出力manifestのSHA-256が`84953114f5e393dd97d9f948a5bc51c95b9355b58461dd3355e068a96cb2e381`と一致することを確認します。
|
||||
稼働中のmount先を上書きせず、source/noticeの提供を含めて不変の単位で保全します。
|
||||
|
||||
## 配置
|
||||
|
||||
任意の追加ファイル`docker-compose.gecko.yml`を通常のCompose定義に重ねます。
|
||||
このoverlayは`app`だけへ接続設定を追加し、`app2`は自動変更しません。
|
||||
|
||||
必要な環境変数:
|
||||
|
||||
| 変数 | 内容 |
|
||||
| --- | --- |
|
||||
| PAGESWIKI_GECKO_KEY_PATH | 32文字以上の十分ランダムな共有鍵のファイル絶対Path。appとrelayへ同じread-only mount |
|
||||
| PAGESWIKI_GECKO_ASSETS_DIR | 全ファイルを検証したbundleの絶対Path。engineだけのdistは禁止 |
|
||||
| PAGESWIKI_GECKO_IMAGE | Giteaで配布した`pageswiki-gecko-relay:sha-...`またはrelease tag。省略時は開発用image |
|
||||
| PAGESWIKI_GECKO_FRONT_SUBNET | 内部接続網。既定`172.24.0.0/27`。既存LANとの重複を避ける |
|
||||
| PAGESWIKI_GECKO_EGRESS_SUBNET | 中継の外向き網。既定`172.24.0.32/27` |
|
||||
|
||||
鍵はイメージ、Git、コマンド引数、ログへ含めません。relayはUID/GID `10001:10001`で動きます。
|
||||
mount元ファイルをこのUIDまたはGIDで読み取り可能にし、他の利用者から読めない権限にしてください。
|
||||
本体の`PAGESWIKI_GECKO_RELAY`は内部の固定URL、`PAGESWIKI_GECKO_KEY_FILE`はmount先です。
|
||||
これらは初回参照時に読み込むため、変更・鍵ローテーション時は本体とrelayを再起動します。
|
||||
|
||||
設定確認・試験起動の例:
|
||||
|
||||
```sh
|
||||
docker compose -f docker-compose.yml -f docker-compose.gecko.yml config --quiet
|
||||
docker compose -f docker-compose.yml -f docker-compose.gecko.yml build gecko-relay
|
||||
docker compose -f docker-compose.yml -f docker-compose.gecko.yml up -d gecko-relay app
|
||||
```
|
||||
|
||||
本体も今回の実装を含むイメージに更新する必要があります。既存のregistry/deploy用overrideがある場合は
|
||||
それも指定し、意図せず旧イメージや開発ビルドを本番へ適用しないでください。
|
||||
|
||||
### 外向き通信の制限
|
||||
|
||||
relayは公開ポートを持たず、通常のWikiネットワークやDBデータをmountしません。
|
||||
ただしDocker bridgeの分離だけでは外向き通信を制限できません。試験導入前にホストまたは外部firewallで、
|
||||
relayのegressから管理網・社内網・metadata・Wiki/DBホストへの到達を拒否し、公開TCP 80/443と管理されたDNSだけを許可します。
|
||||
rootless Dockerとrootful Dockerでは適用点が異なるため、ホスト固有のiptablesをこのoverlayから自動変更しません。
|
||||
|
||||
アプリケーション側でもIPv4/IPv6のprivate、loopback、link-local、特殊用途アドレスを拒否します。
|
||||
名前解決で返された全アドレスを検証してから、そのIPを直接dialします。検証後の再名前解決はしません。
|
||||
UDP、80/443以外のTCP、単一ラベルのホスト名は拒否します。
|
||||
これはWisp v1フレームを用いた**制限付きTCP profile**であり、Wispの全機能互換サーバーではありません。
|
||||
|
||||
## 上限と監視
|
||||
|
||||
| 対象 | 上限 |
|
||||
| --- | --- |
|
||||
| 同時セッション | Domain+本人ごとに1、サービス全体4 |
|
||||
| 同時TCP stream | セッションごと16 |
|
||||
| 接続試行 | セッションごと256 |
|
||||
| 合計転送量 | セッションごと送受信合計256MiB |
|
||||
| 帯域 | セッションごと送受信合計2MiB/s、初期burst 2MiB |
|
||||
| セッション期限 | 15分 |
|
||||
| WebSocket受信idle | 90秒 |
|
||||
| 宛先接続 | 名前解決込み8秒、個別dial 2秒 |
|
||||
| relayコンテナ | 256MiB、0.5 CPU、64 PIDs、read-only、capabilitiesなし |
|
||||
| 閲覧プロファイル | 日本語フォントを含むvolatileな32MiB・2,048 entries、端末のOPFSへ永続化しない |
|
||||
| source/noticeダウンロード | 全体2接続まで。ETag・Range対応。閲覧streamの枠とは分離 |
|
||||
|
||||
relayの稼働状態・接続数・送受信bytes・拒否数は、コンテナ内の次の操作でJSON取得できます。
|
||||
鍵はファイルから読み、標準出力には含めません。counterは再起動でリセットします。
|
||||
|
||||
```sh
|
||||
docker compose -f docker-compose.yml -f docker-compose.gecko.yml exec gecko-relay gecko-relay --status
|
||||
```
|
||||
|
||||
`/health`は内容なしの死活確認、`/status`は署名付き内部要求だけに応答します。
|
||||
CPU・メモリはコンテナ監視を使います。設定画面の資源グラフへの統合は未完了です。
|
||||
記事URL、本文、プロファイル内容、資格情報はrelayログに記録しません。
|
||||
|
||||
## 無効化と切り戻し
|
||||
|
||||
管理画面の拡張一覧で`viewer.gecko`を無効化できます。UIが使えない場合は、対象Domainを選択した
|
||||
ローカル`data/pageswiki-cli`で次を実行します。
|
||||
|
||||
```text
|
||||
extension viewer.gecko off
|
||||
```
|
||||
|
||||
既存WebSocketは次の認証再検査時に終了します。新たな閲覧も拒否し、RSSの原文リンクは新規タブへ戻ります。
|
||||
緊急時はrelayコンテナを停止します。DB移行の巻き戻しは不要です。
|
||||
|
||||
## 受入と制約
|
||||
|
||||
自動テストでは外部アクセスしない合成Wisp応答を使い、実際のGecko WASMで描画、canvasクリックによる遷移、
|
||||
ビューア内の「戻る」、iframe削除後の接続終了を確認します。実FreshRSS、外部カレンダー、メール本文は使いません。
|
||||
専用イメージのbuildと、`--network none`・非root・read-only・資源制限付きの一時コンテナで、
|
||||
固定資産の起動時検査と`--status`も確認済みです。本番の中継・ネットワーク設定は変更していません。
|
||||
|
||||
```sh
|
||||
go test -race ./internal/geckorelay ./internal/server -run 'TestGrant|TestDestinations|TestRelay|TestAssets|TestFeedGeckoAuthorization|TestFeedGeckoWebsocket'
|
||||
PAGESWIKI_BROWSER_TEST=1 PAGESWIKI_GECKO_TEST_ASSETS=/verified/bundle go test ./internal/server -run '^TestFeedGeckoChromium$' -count=1
|
||||
PAGESWIKI_GECKO_TEST_BUNDLE=/verified/bundle go test ./internal/geckorelay -run TestDistribution
|
||||
# 公開テストサイトへの実通信。実RSS・外部カレンダー・メールは使用しない。
|
||||
PAGESWIKI_BROWSER_TEST=1 PAGESWIKI_GECKO_TEST_ASSETS=/verified/bundle PAGESWIKI_GECKO_PUBLIC_HTTPS_TEST=1 go test ./internal/server -run '^TestFeedGeckoChromium$' -count=1
|
||||
node internal/server/testdata/feed-gecko-profile.mjs
|
||||
```
|
||||
|
||||
原文クリック時にだけ起動し、閉じるとiframe・worker・接続を破棄します。タブを60秒非表示にした場合も閉じます。
|
||||
再表示では静的資産のHTTP cacheを使えますが、エンジンは再起動します。
|
||||
戻る/進むは最大64件のURLを再読み込みする方式です。上流の最小GREにはSessionStoreFunctionsがなく、
|
||||
標準のhistory.back()が失敗するため、フォーム内容やスクロール位置を復元する履歴ではありません。
|
||||
画面のcanvasは最大1920×1080、experimental WASM JITとGPUは無効です。
|
||||
|
||||
HTTPSの実描画と期限切れ証明書の拒否を確認しました。上流最小GREはエラーページの部品が不足するため、
|
||||
`about:neterror`/`about:certerror`を検知してcanvasを隠し、PagesWiki側で説明します。証明書の無視・例外追加は提供しません。
|
||||
Noto CJKをメモリプロファイルのfontsに置き、エンジンを改変せず日本語描画も確認しています。
|
||||
|
||||
検索アイコンまたはCtrl/Cmd+Fからページ内検索できます。検索語は256文字まで、前後検索と一致なしの表示に対応し、合成記事で日本語検索を確認しています。起動失敗または120秒の起動上限到達時はiframeを破棄し、元記事を別タブで開く導線を残します。上流のdestroy呼出しだけではWASM資源の解放にならないため、親側のiframe破棄まで行います。`TestFeedGeckoStartupFailureChromium` はフォント取得失敗時の破棄と代替導線を検証します。
|
||||
|
||||
本番の標準機能に昇格する前に、Safari/iPhone SE、IME、コピー、実サイト互換性、
|
||||
複数タブ・低メモリ端末の測定、コンテナ外向きfirewallを検証します。
|
||||
外部ページのiframe拒否とは別の仕組みですが、すべてのサイトでの動作や軽さを保証するものではありません。
|
||||
@@ -11,6 +11,9 @@ runner の環境構築や Gitea の事前疎通診断は行わず、本番へ自
|
||||
| `pageswiki-app`(app / app2 共通) | `Dockerfile` |
|
||||
| `pageswiki-adaptor-gateway` | `Dockerfile.adapter-gateway` |
|
||||
| `pageswiki-excalidraw-viewer` | `Dockerfile.excalidraw-viewer` |
|
||||
| `pageswiki-gecko-relay`(任意) | `Dockerfile.gecko-relay` |
|
||||
|
||||
v0.15.0以降はGecko relayを含む4イメージをビルド・昇格します。以下の「3イメージ」は通常配備するapp・gateway・Excalidrawの組を指します。Gecko relayは別overlayで明示的に配備するもので、通常の本番更新では起動しません。
|
||||
|
||||
Kroki、Mermaid、code-server は upstream の配布イメージを使用する。
|
||||
`main` / `mk_district` への push、手動実行でビルド・公開する。
|
||||
@@ -121,6 +124,19 @@ Gitea 1.24 の自動ジョブトークンによるパッケージ公開は前提
|
||||
|
||||
アプリイメージにはソースコードが含まれるため、パッケージの公開範囲にも注意する。
|
||||
|
||||
## テスト用一時領域
|
||||
|
||||
Dockerfileのtest段階では、全Goテストを`-p 1`でパッケージ単位に直列化する。
|
||||
テスト用`TMPDIR`は最大2GiBのtmpfsとし、SQLiteの一時DBをrunnerのoverlay filesystemから分離する。
|
||||
コンパイラ用`GOTMPDIR`はディスク側の`/tmp`に残す。tmpfsは当該RUNの間だけ存在し、
|
||||
runtime段階や本番の保存先・WAL・接続タイムアウトには影響しない。
|
||||
|
||||
CI run 54では、直列化後も既存の壁紙・Ordoschnellic・Seheweitのテストが
|
||||
SQLite接続初期化の5秒タイムアウトで失敗した。ストレージ競合を避ける措置であり、
|
||||
テスト除外・再試行による成功扱い・本番の期限緩和は行わない。
|
||||
tmpfsは最大2GiBのメモリを消費し得るため、runnerにはコンパイラ等と合わせた余裕が必要。
|
||||
実ファイル保存の移行確認は、CIとは別に本番DBの隔離コピーで行う。
|
||||
|
||||
## タグ・容量・本番利用
|
||||
|
||||
3 イメージ共通で `sha-<40桁のコミットID>` を使用し、自動 latest は付けない。
|
||||
@@ -161,3 +177,4 @@ prefix の変更は `PAGESWIKI_IMAGE_PREFIX`(既定 git.anya.jp/anya)。
|
||||
- [Gitea 1.24 Actions の互換性・制限](https://docs.gitea.com/1.24/usage/actions/comparison/)
|
||||
- [Gitea Container Registry](https://docs.gitea.com/usage/packages/container/)
|
||||
- [Docker コンテナの DNS と hosts](https://docs.docker.com/engine/network/#dns-services)
|
||||
- [Dockerfileの一時tmpfsマウント](https://docs.docker.com/reference/dockerfile/#run---mounttype-tmpfs)
|
||||
@@ -0,0 +1,76 @@
|
||||
# RSSフォルダと取り込み操作のリリース
|
||||
|
||||
## 対象
|
||||
|
||||
v0.12.0は`f4869c7c8bd2fd48523eec2e1868d3d0750bbdf7`。
|
||||
2026-11-08 14:55 JSTに本番検証を完了し、注釈付きGitタグとイメージを公開した。
|
||||
既存v0.11.0タグは移動していない。
|
||||
独立pages-cliと未コミットのメール保存先調査は含めない。
|
||||
|
||||
- [ビルドCI run 64](https://git.anya.jp/anya/pages/actions/runs/64): success。
|
||||
- [リリースCI run 65](https://git.anya.jp/anya/pages/actions/runs/65): success。
|
||||
- [Gitea Release v0.12.0](https://git.anya.jp/anya/pages/releases/tag/v0.12.0)。
|
||||
|
||||
本番`.env.release`は同コミットの`sha-`タグに固定している。
|
||||
`v0.12.0`は再ビルドせず同一manifestを昇格し、3イメージすべてのdigestとrevisionを照合済み。
|
||||
|
||||
## 変更
|
||||
|
||||
- FreshRSSの分類フォルダ・購読元をツリー表示し、空フォルダ・未分類・開閉状態保存に対応。
|
||||
- 記事・購読元・分類を背景で原子的に更新し、一部失敗時は前回cacheを保持。
|
||||
- 既読・star書戻しの操作履歴、結果不明の再確認、JSON記録保存。
|
||||
- ショートカットヘルプを`?`・`Esc`・閉じるボタンで閉じ、元の記事とstatus表示を保持。
|
||||
- Wiki・タスク追加を本文上のdialogへ整理し、個人設定のWiki親Pathを初期表示。
|
||||
- `{YYYY}`・`{MM}`・`{DD}`・`{Subject}`を親Pathで使用可能。日付はドメインのタイムゾーン。
|
||||
- 件名を安全な単一Path要素へ整形し、保存先プレビューと公開範囲確認を表示。
|
||||
- `sharing.x`の有効・無効に従うRSS記事のX共有。件名と原文URLを別タブのintentへ渡す。
|
||||
- 個人設定からRSS原文・本文リンクを別タブまたは大きなiframeプレビューで開く方式を選択。
|
||||
|
||||
個人設定は`/-/sys/config?panel=organizer`。Wiki親Pathはメール取り込みと共通。
|
||||
リンクの開き方は既定で別タブとし、設定変更はRSS画面の再読込後に反映する。
|
||||
iframeはsandbox付きで、外部サイトの埋め込み禁止は回避しない。表示できない場合は別タブへ開く。
|
||||
本番利用者の既定値やFreshRSS書戻し許可を自動変更しない。
|
||||
詳細は[RSS設計](../../design/ja/feeds.md)を参照。
|
||||
|
||||
## 移行と保全
|
||||
|
||||
今回の本番schema差分はfeeds v5→v6。`feed_sources.remote_folders`の列追加であり、
|
||||
既存記事・購読設定・送信待ちreceipt・source versionを変更しない。
|
||||
Wiki親Pathとリンク表示モードは既存preferences JSONを使うため追加DDLはない。
|
||||
旧版がv6を理解するとは仮定せず、単なる旧イメージへの切戻しを自動実行しない。
|
||||
|
||||
保全先は`.deployment-backups/release-rss-folders-20261108/`。
|
||||
旧構成を`config/`、停止時点のデータを`cutover/data`・`cutover/data2`に保存した。
|
||||
14:53:29 JSTに停止を開始し、14:54:38 JSTにchecksum付き同期・差分ゼロ・DBの一致を確認した。
|
||||
事前コピーだけでは整合バックアップと扱っていない。
|
||||
稼働元とはinodeを共有せず、既存の不変バックアップとのみ変更のないファイルを共有する。
|
||||
旧イメージは`rollback-before-rss-folders-20261108`タグで保全した。
|
||||
|
||||
## 検証
|
||||
|
||||
手元のGo全体テスト・go vet、RSS関連のrace検査、1440px/390pxのChromium試験を実施。
|
||||
分類の空・未分類・移動・同名ID、失敗時cache保持、schema v6のrollback・再実行を検査した。
|
||||
親Pathの日付境界・日本語件名・階層逸脱防止・不正トークン拒否を検査した。
|
||||
リンクプレビューは別originのローカルfixtureを実際に読み込み、sandboxと復帰を検査した。
|
||||
実FreshRSS・Xへの投稿・外部カレンダー・実メール本文を検証のために取得・操作していない。
|
||||
|
||||
停止済みの前回バックアップから独立コピーを作り、両DBの移行前integrity_checkはok。
|
||||
配備イメージをネットワーク遮断・workers無効で実際に起動し、両DBでfeeds v6への移行、
|
||||
ヘルス、管理対象13コンポーネントのschema check、移行後integrity_checkのokを確認した。
|
||||
schema check単体ではlegacy領域を網羅しないため、起動・SQLite検査と組み合わせた。
|
||||
|
||||
本番切替後は以下を確認した。
|
||||
|
||||
- app・app2・adaptor-gateway・excalidraw-viewerが対象revisionで稼働、restart countは0。
|
||||
- 両アプリの`/health`、schema checkが正常。feeds v6、task-productivity v4。
|
||||
- HTTPSの`/health`とログインは200、匿名のRSS・タスク・設定画面は303、RSS APIは401。
|
||||
- 配信中の`feeds.js`・`feeds.css`・`task-productivity.js`のSHA-256がリポジトリと一致。
|
||||
- 起動後ログのpanic・fatal・DB locked・event job failed・schema errorは各0件。
|
||||
|
||||
## 配布イメージのdigest
|
||||
|
||||
| イメージ(`git.anya.jp/anya/`、タグ`v0.12.0`) | manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:46251f9b869e47d456def4d285c3f076e0d375f2a11d69121885fca08997e6a7` |
|
||||
| pageswiki-adaptor-gateway | `sha256:ee98889018f8389a655126c6a5d1046640be22cae169d97c4b27a7efa08f86c6` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:e7a577a8f178f625f6b13da93b046afda57c5c4c67e5e3b86cab0daf5c5f14ee` |
|
||||
@@ -0,0 +1,92 @@
|
||||
# PagesWiki v0.13.0
|
||||
|
||||
RSSフォルダのキーボード移動と、既定無効のGecko原文ビューア基盤を追加するminor releaseです。
|
||||
エンジン配布を含まない範囲でリリースします。通常のRSS表示・新規タブ・sandbox iframeは維持します。
|
||||
|
||||
## 変更
|
||||
|
||||
- Shift+j/kでFreshRSSの前後の分類フォルダを選択。検索条件、未読/star絞り込みを維持。
|
||||
- 認証付きの独立Wisp TCP relayと、Gecko用の本文上popup、個人設定を実装。
|
||||
- relayは公開TCP 80/443限定、DNS解決後の全IP検査、固定IPへの接続、接続数・帯域・通信量・期限の制限。
|
||||
- ログアウト・利用者状態・拡張無効化を既存WebSocketにも反映。
|
||||
- upstream v0.0.1をhash固定。閲覧プロファイルはメモリのみ、終了時はiframeを破棄。
|
||||
- 戻る/進むは最大64件のビューア内URL履歴を再読み込み。通常ブラウザのフォーム状態復元ではない。
|
||||
- 拡張manifestの既定無効をサーバーとローカルCLIへ反映。
|
||||
- 専用relayはscratch runtimeとし、実ビルドのGo・x/netのBSD licenseを収録。
|
||||
|
||||
## 再配布と本番の範囲
|
||||
|
||||
[再配布条件](../gecko-redistribution.md)にGecko、WASM用追加コード、Emscripten、zstddec、フォントを整理しました。
|
||||
GeckoのJS/WASM/フォントをGit、通常3イメージ、release assetへ同梱しません。
|
||||
relay Dockerfileと試験用Compose overlayは提供しますが、CIの配布イメージは従来の3種類です。
|
||||
|
||||
固定版生成物にはMozillaの総合noticeが含まれないため、エンジン配布用notice/source bundleは残件です。
|
||||
外部mountからのブラウザ配信も再配布として扱い、今回の本番では鍵・asset mount・relay起動・
|
||||
`viewer.gecko`の有効化を追加しません。
|
||||
通常のRSSフォルダショートカットは利用できます。
|
||||
|
||||
## 互換性と検証
|
||||
|
||||
DBスキーマ変更はありません。RSSリンクモード`gecko`は既存preferences JSONの追加値です。
|
||||
未構成・無効時は新規タブ表示に戻り、既存利用者の設定を自動変更しません。
|
||||
旧版でpreferencesを保存する際、新しい値が残っていれば`tab`または`embedded`へ戻す必要があります。
|
||||
|
||||
Go全体テスト、関連race検査、CLI、配布ツール、Chromiumでの1440/390px RSS回帰と実Geckoによる
|
||||
合成Wisp記事の描画・クリック遷移・戻る・終了を検証対象とします。実FreshRSS・外部カレンダー・メール本文は検証に使いません。
|
||||
Safari、IME/copy/find、実HTTPSの互換性と証明書エラー、低メモリ・長時間負荷、監視UI統合、
|
||||
本番の外向きfirewallは実験機能の昇格前の残件です。
|
||||
|
||||
構成・上限・切り戻しは[Gecko中継の試験導入](../gecko-relay.md)、機能の進捗は[RSS設計](../../design/ja/feeds.md)を参照してください。
|
||||
|
||||
## リリース・本番反映記録
|
||||
|
||||
対象commitは`5321d613b40db36238235ff68e256caa6d4e4cf1`。
|
||||
2026-11-08 16:31:51 JSTに本番の外部HTTPS検証を完了しました。
|
||||
|
||||
- [ビルドCI run 66](https://git.anya.jp/anya/pages/actions/runs/66): success。
|
||||
- [リリースCI run 67](https://git.anya.jp/anya/pages/actions/runs/67): success。
|
||||
- [Gitea Release v0.13.0](https://git.anya.jp/anya/pages/releases/tag/v0.13.0)。
|
||||
|
||||
注釈付きGitタグ`v0.13.0`と同名の3イメージを公開しました。
|
||||
SHAタグから再ビルドせず昇格し、両タグのmanifest digest一致を確認しています。
|
||||
本番`.env.release`は`PAGESWIKI_IMAGE_TAG=v0.13.0`です。
|
||||
app・app2・adaptor-gateway・excalidraw-viewerだけを切り替え、他サービスは変更していません。
|
||||
|
||||
### DBと復旧点
|
||||
|
||||
現在の両DBをSQLiteのオンラインバックアップで独立コピーし、`integrity_check`のokと、
|
||||
新イメージをネットワーク遮断・読み取り専用で実行した`schema check`の成功を確認しました。
|
||||
13管理コンポーネントはすべてcurrentで、feeds v6・task-productivity v4のままです。
|
||||
この検査はlegacy領域の全移行を網羅するものではありません。今回のschema追加はありません。
|
||||
|
||||
最初に選んだ前回切替前バックアップにはfeeds v5が残っていたため、現在のDBのコピーへ検査対象を変更しました。
|
||||
`/tmp`上の検査コピー作成はI/Oエラーで中断し、その一時コピーだけを除去して、
|
||||
空き容量のあるディスク上でコピー・整合性検査を完了しています。本番DBへの検査用書き込みはしていません。
|
||||
|
||||
復旧点は`.deployment-backups/release-v0.13.0-20261108/`です。
|
||||
`config/`に旧構成、`cutover/data`・`cutover/data2`に停止時点の全データを保存しました。
|
||||
16:29:32 JSTに停止を開始し、16:31:01 JSTにchecksum同期・再走査の差分ゼロ・DB一致を確認しました。
|
||||
稼働元とはinodeを共有せず、不変の旧バックアップとのみ未変更ファイルを共有しています。
|
||||
旧3イメージは`rollback-before-v0.13.0-20261108`タグで保持しています。
|
||||
旧版へ戻す場合も更新後の書き込みを失わないよう、データの自動巻き戻しは行いません。
|
||||
|
||||
### 配備後検証
|
||||
|
||||
- 4サービスのrevisionが対象commitと一致、再起動回数0。
|
||||
- app・app2の`/health`と管理スキーマ検査が正常。
|
||||
- 外部HTTPSでhealth・ログイン・カレンダーHTML枠は200、匿名のRSS・設定は303、RSS APIとGecko proxyは401。
|
||||
カレンダーHTML枠の200は既存の仕様で、実予定データの取得・閲覧は検証していません。
|
||||
- `feeds.js`・`task-productivity.js`・`feed-gecko.js`・`feed-gecko-profile.mjs`・`feed-gecko.css`の配信SHA-256がソースと一致。
|
||||
- 起動直後のpanic/fatal・database locked・event job failed・schema errorは各0件。
|
||||
- 本番へのGecko環境変数・asset mount追加なし、Gecko relayの起動なし。
|
||||
|
||||
手元ではGo全体テスト、go vet、関連race検査、CLI、配布ツール、ChromiumによるRSSと合成Gecko記事の試験を通しています。
|
||||
ライセンス同梱を含め専用scratch relayのビルド・起動・statusも確認しましたが、配布イメージへの追加や本番起動はしていません。
|
||||
|
||||
### 配布イメージ
|
||||
|
||||
| イメージ(`git.anya.jp/anya/`、タグ`v0.13.0`) | manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:87e9a2761c136aff734761f296c9dbe34fc391ad5687eaf332d3c9ba15b03ab5` |
|
||||
| pageswiki-adaptor-gateway | `sha256:b82bb2184d21ea692b63fa2f9a70f15392474719e444e8d2b7618723cc80c7f1` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:2fff1ac0191e2fc7d8ad21aba365c82e0500f81d78da3672c030e77cb6a418af` |
|
||||
@@ -0,0 +1,100 @@
|
||||
# RSSリリースとFreshRSS書き戻しの本番反映
|
||||
|
||||
## リリース境界
|
||||
|
||||
注釈付きタグ`v0.11.0`は`16e572397b2b1abf096bd6bca26e2af832768b8d`を指す。
|
||||
RSSの内蔵reader、OPML、FreshRSSの読み取り・購読カタログまでの区切りであり、タグは移動しない。
|
||||
その後の既読・star書き戻しを含む本番反映は`61ecd1ffbdf46897d50c2f7eb7a2e1415f1bb456`。
|
||||
`131a7ca`で機能を実装し、`61ecd1f`でCIのテスト一時領域だけを改善した。
|
||||
2026-11-08 JSTに本番反映済み。独立pages-cliや未コミットのメール保存先調査は対象外。
|
||||
|
||||
## 機能と安全条件
|
||||
|
||||
FreshRSSを正本とし、source単位で明示的に許可した場合だけ既読・starの変更を送る。
|
||||
許可は既定OFF。UI操作は永続キューへ入り、外部での確認後に表示へ反映する。
|
||||
送信結果が不明になった場合は自動再送せず、利用者の再確認操作で外部状態を読む。
|
||||
操作IDによる重複防止、source更新との競合、権限失効、source削除、共有leaseを扱う。
|
||||
詳細と残件は[RSS設計](../../design/ja/feeds.md)を参照。
|
||||
|
||||
今回の本番移行には、前段のタスク作業記録訂正監査・日次ダイジェストの送信試行記録も含む。
|
||||
管理対象スキーマの差分は、feedsの未導入状態からv5、task-productivityのv2からv4。
|
||||
ファイル正本の一括書換えは行わない。後続版のスキーマを旧版へ自動downgradeしない。
|
||||
|
||||
## 検証記録
|
||||
|
||||
- 手元で`go test -p 1 ./...`、`go vet ./...`が成功。
|
||||
- feeds関連のrace検査、1440px・390pxのChromium試験、JavaScript構文検査が成功。
|
||||
- 合成FreshRSSでread/starの追加・解除、応答喪失、再確認、競合、設定変更・失効を検査。
|
||||
- v5の移行失敗時rollback、再実行、既定OFF、source削除後の操作記録保持を検査。
|
||||
- [CI run 53](https://git.anya.jp/anya/pages/actions/runs/53)はv0.11.0候補の全テスト・3イメージの公開に成功。
|
||||
[release run 55](https://git.anya.jp/anya/pages/actions/runs/55)で既存イメージを再ビルドせずv0.11.0へ昇格した。
|
||||
- CI run 54は既存3テストのSQLite接続初期化が5秒でtimeout。追加したFreshRSS試験の失敗ではない。
|
||||
該当3テストを手元で各3回成功。テスト専用tmpfsを導入し、
|
||||
[run 56](https://git.anya.jp/anya/pages/actions/runs/56)で全テスト・3イメージ公開が成功。
|
||||
server 97.912秒、store 27.685秒。テスト省略や本番のdeadline変更は行っていない。
|
||||
詳しくは[CI運用](../gitea-images.md#テスト用一時領域)を参照。
|
||||
- 前回停止時バックアップを独立コピーし、ネットワーク遮断・workers無効で主/外部DBを起動。
|
||||
v0.11.0候補でfeeds v4・task-productivity v4への移行、health、schema check、integrity_checkが成功。
|
||||
外部インスタンスのリハーサルでは再登録を実行せず、既存DBを通常起動した。
|
||||
最終イメージではコピーを旧版の状態に戻して起動し、両DBともfeeds v5・task-productivity v4まで
|
||||
移行した後のhealth・schema check・SQLite integrity_checkが成功した。
|
||||
|
||||
外部取り込みカレンダーと実メール本文は取得・表示していない。実FreshRSSへの操作も行っていない。
|
||||
DB・正本の保全はファイルコピーとバイト照合だけを用いる。実サービスへの書き戻し受入確認は残る。
|
||||
|
||||
## 保全・切替手順
|
||||
|
||||
保全先は`.deployment-backups/release-rss-20261108/`。親0700、構成コピー0600。
|
||||
旧構成と停止時点の`cutover/data`・`cutover/data2`を保持する。
|
||||
変更のないファイルは前回の不変バックアップとのみhardlinkを共有し、稼働元とは共有しない。
|
||||
ディスク空きがDBより小さいため、今回新しく独立コピーしたpages.db(link数1を検証)だけは
|
||||
停止後にchecksum付きin-place同期する。他のファイルにin-place更新を使わない。
|
||||
最終checksum差分ゼロとDBのバイト一致を確認してから新しいイメージを起動する。
|
||||
旧バックアップ・旧イメージは削除しない。
|
||||
|
||||
対象はapp・app2・adaptor-gateway・excalidraw-viewerの4サービス。
|
||||
CI成功後の同一SHAの3イメージをpullし、registry overlayで`up --no-build --no-deps`する。
|
||||
code-server・Kroki・独立CLI・ネットワーク構成は変更しない。
|
||||
切戻しが必要な場合は書込みを停止し、切替後データも保全した上で互換性を判断する。
|
||||
稼働中DBへ旧バックアップを自動復元しない。
|
||||
|
||||
## 本番反映結果
|
||||
|
||||
2026-11-08 06:20:55 JSTに停止開始、06:22:12にバックアップ最終照合・sync完了、
|
||||
06:22:37に4サービスの起動確認完了。停止開始から起動確認まで102秒。
|
||||
`.env.release`は`sha-61ecd1ffbdf46897d50c2f7eb7a2e1415f1bb456`を指定する。
|
||||
本番のバージョン指定はv0.11.0タグそのものではなく、追加実装を含むこの固定SHAである。
|
||||
|
||||
| イメージ | manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:e452a7dbadf13c89909c5ee6a685fa39342926675dec2253747534ef6ffabfb0` |
|
||||
| pageswiki-adaptor-gateway | `sha256:77efae4ef3651e12ebac6a15474448dd93bfa89a7072b8db8e296322a68a7956` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:45b6399438fa1b40d54c0b6dfbcc15ca1464abb03b454e8b281d94d58c80b250` |
|
||||
|
||||
4コンテナのsource revision一致・running・再起動0回を確認。主/外部インスタンスのhealth正常、
|
||||
両DBの管理対象13コンポーネントのschema checkはcurrent。
|
||||
このschema checkだけで全データや全legacy schemaの完全性を保証するものではない。
|
||||
公開HTTPSのhealth・ログインは200、匿名RSS・タスク・拡張設定画面は303、RSSのsources・action APIは401。
|
||||
配信feeds.jsとfeeds.cssのSHA256は配備コミットと一致する。
|
||||
起動後ログのpanic・fatal・database is locked・event job failed・schema失敗の検索パターンは0件。
|
||||
|
||||
最終バックアップの両ルートともchecksum付きdry-runの差分はゼロ。
|
||||
旧v0.10.0イメージは`rollback-before-rss-20261108`タグで保持し、ローカルlatestは新イメージに揃えた。
|
||||
今回作成した隔離リハーサル用の一時コピーとコンテナは片付けたが、旧バックアップは削除していない。
|
||||
完了時のディスク空きは約4GiB。その後の容量整理は次節のとおり。
|
||||
|
||||
FreshRSSの書き戻し許可は自動有効化していない。本番ユーザーの設定・記事状態を試験のために変更せず、
|
||||
外部取り込みカレンダー・実メール・実FreshRSSへ検証用アクセスを行っていない。
|
||||
|
||||
## 容量整理
|
||||
|
||||
2026-11-08、ユーザーの削除指示を受け、旧リリースのバックアップ8世代を削除した。
|
||||
対象はrelease-v0.4.0、v0.5.0、v0.6.0、v0.7.0、v0.7.1、v0.8.0、v0.8.1、v0.9.0の各ディレクトリ。
|
||||
現在の切替直前を保全した`release-rss-20261108`と、その前の`release-v0.10.0-20261107`を残した。
|
||||
hardlink共有ファイルも、残したバックアップの参照は維持される。開発時の小さなソース保全やrsyncログは変更していない。
|
||||
9月のrsyncログを11月のバックアップの外部転送証明とは扱わず、今回の保持世代整理として削除した。
|
||||
|
||||
DockerはPagesWikiの指定repositoryだけを対象に、全コンテナの使用中image ID、v0.10.0の切戻し用、
|
||||
v0.11.0の手元イメージを保護した。旧43 image IDに属する102タグと関連参照をforceなしで削除。
|
||||
daemon全体のprune、レジストリの削除、他サービスのイメージ/volume削除は行っていない。
|
||||
本番停止は不要で、空き容量は約4GiBから約61GiBへ増えた。
|
||||
@@ -0,0 +1,77 @@
|
||||
# PagesWiki v0.14.1とpages-cli v0.4.2
|
||||
|
||||
削除済みタスクの受付記録が残り、変更した下書きの再送で412になっていた問題を修正します。
|
||||
削除済みなら410、受付記録に対応するタスクと削除記録が両方欠落していれば409 `capture_missing` で停止します。
|
||||
存続中のタスクを異内容のcaptureで上書きすることは許可しません。
|
||||
|
||||
2026-11-08 19:42:51 JSTに本番配備後の確認を完了しました。
|
||||
DBスキーマ変更・既存データの削除・実タスクの再取り込みは行っていません。
|
||||
Gecko等の未コミット変更は含みません。
|
||||
|
||||
## 再取り込み
|
||||
|
||||
サーバーをv0.14.1、利用するCLIをv0.4.2に更新してから実行します。
|
||||
別インスタンスへ接続している場合は、その接続先サーバーの更新も必要です。
|
||||
|
||||
```sh
|
||||
pages --version
|
||||
pages task retry REQUEST_UUID --recreate-deleted
|
||||
```
|
||||
|
||||
保持した下書きから、新UUIDのタスクを作成します。旧UUIDの削除記録とDAV識別子予約を残し、
|
||||
通常の再送で古いタスクが復活するのを防ぎます。再取り込み用IDは決定的で、応答消失や並行再送でも重複作成しません。
|
||||
既存Wikiが保存先にあれば本文・リビジョンは変更せず、新タスクから関連付けます。
|
||||
ページがなければ保留本文から作ります。移動済みページの自動探索や旧作業記録の復元ではありません。
|
||||
|
||||
通信失敗時はCLIが表示する新IDで `pages task retry NEW_REQUEST_UUID` を実行します。
|
||||
セッションファイルや受付記録を手動で消さないでください。
|
||||
詳細は[実装契約](../../design/ja/tasks-implementation.md#削除済みメール取り込みの再作成)と
|
||||
[CLIのNeoMutt手順](https://git.anya.jp/anya/pages-cli/src/tag/v0.4.2/docs/neomutt.md)を参照してください。
|
||||
|
||||
## リリースと検証
|
||||
|
||||
| 対象 | タグ | commit | CI |
|
||||
| --- | --- | --- | --- |
|
||||
| PagesWiki | [v0.14.1](https://git.anya.jp/anya/pages/releases/tag/v0.14.1) | `4049acf76e36c12b8f3c506de5eaf1e920ac7e86` | [build 72](https://git.anya.jp/anya/pages/actions/runs/72)、[release 75](https://git.anya.jp/anya/pages/actions/runs/75) success |
|
||||
| pages-cli | [v0.4.2](https://git.anya.jp/anya/pages-cli/releases/tag/v0.4.2) | `e27c023d66a61b73d3fe47e982daa6f34213c41f` | [build 73](https://git.anya.jp/anya/pages-cli/actions/runs/73)、[release 74](https://git.anya.jp/anya/pages-cli/actions/runs/74) success |
|
||||
|
||||
- 正確なリリースソースで `go test ./...`。server/storeのgo vet、削除・再取り込み・並行再送のrace検査が成功。
|
||||
- CLIの52単体テスト、サーバーとCLIのHTTP結合テストが成功。Wiki本文・版の保全、他所有者拒否、readonly、kill switch、入力上限、保存途中のロールバックを検証。
|
||||
- 公開されたCLIの4配布ファイルをSHA256SUMSで照合し、Pythonソースとcommitを照合。
|
||||
- 配布Linux ELFでバージョン、メール取り込み、下書き差し替え、削除済み再取り込み、認証・ファイル権限のスモークテストとTLS関連6テストが成功。
|
||||
- Linux ELFはglibc 2.36以降。macOS/Windowsの未検証バイナリは配布していません。
|
||||
|
||||
## 本番切り替えと復旧点
|
||||
|
||||
app・app2・adaptor-gateway・excalidraw-viewerを同じv0.14.1へ更新しました。
|
||||
`.env.release` の選択は `PAGESWIKI_IMAGE_TAG=v0.14.1` です。
|
||||
|
||||
- 19:40:36 JSTに停止開始。
|
||||
- 19:42:17 JSTに、停止時点のdata/data2についてchecksum同期、再走査の差分ゼロ、DBファイル一致を確認。
|
||||
- 19:42:23 JSTに新版の起動と両アプリのhealth応答を確認。
|
||||
- 設定と停止時データは `.deployment-backups/release-v0.14.1-20261108/` の `config/` と `cutover/data`、`cutover/data2` に保存。DBのinodeは稼働元と独立しています。
|
||||
- 旧3イメージを `rollback-before-v0.14.1-20261108` タグで保持。旧バックアップも残しています。
|
||||
|
||||
v0.14.0への切り戻しはイメージ選択のみで行い、DBを過去へ戻しません。
|
||||
その場合は再取り込みAPIが利用できなくなるため、CLIの再取り込み操作を止めてください。
|
||||
v0.14.0より前への切り戻しは削除記録の扱いが異なり、[v0.14.0の注意点](2026-11-08-task-deletion.md#dbと切り戻し)が引き続き適用されます。
|
||||
|
||||
## 配備後確認
|
||||
|
||||
- 4サービスのrevisionが対象commitと一致、running、再起動回数0。
|
||||
- app/app2のhealth正常。管理対象13スキーマはcurrent。これはlegacy領域を含む全移行検証ではありませんが、今回の変更にスキーマ移行はありません。
|
||||
- 両DBの `quick_check` はok。
|
||||
- 外部HTTPSのhealth・ログイン画面200。匿名のタスク/ダッシュボード/RSS画面303、タスクAPI401。匿名DELETEとcapture POSTも401。
|
||||
- tasks.js、tasks.css、organizer-dashboard.js、feeds.js、feed-gecko.jsのSHA-256がリリースcommitと一致。
|
||||
- 起動直後のfatal/panic、DB lock、schema/migration failure、event job failureは両アプリとも0件。
|
||||
- 実際のメール本文・利用者の保留下書きを使った再取り込みは実施していません。
|
||||
|
||||
## 配布イメージ
|
||||
|
||||
SHAタグから再ビルドせず昇格。本番で取得したdigestとCI結果は一致しています。
|
||||
|
||||
| イメージ(`git.anya.jp/anya/`、タグ`v0.14.1`) | manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:11488fb958db12ec5a25aa265fc8179a31ab5728800f47605759822a44eb81e6` |
|
||||
| pageswiki-adaptor-gateway | `sha256:ca17704eb5e88a4e73827ff2a5fafda7c4bb7d9be3987b5a83a3a5ae0c780098` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:a2b692c3864b8c4f13412e746fcea7cd9a2c03d49e0d5ead252432f37930c4c4` |
|
||||
@@ -0,0 +1,70 @@
|
||||
# PagesWiki v0.14.0
|
||||
|
||||
タスク編集画面に、アーカイブと独立した削除操作を追加するminor releaseです。
|
||||
本日の達成率ウィジェットは説明文を除き、グラフと完了数/総数を表示します。
|
||||
Geckoの追加整備やRSSの追加ショートカットなど、並行作業中の変更は含めません。
|
||||
|
||||
## 変更と削除範囲
|
||||
|
||||
- タスク編集画面の「アーカイブ/復元」の隣に「削除」。確認後に実行し、アーカイブ済みタスクにも対応。
|
||||
- DELETE APIは所有者・Domain・active状態を検査し、If-Matchを要求。更新競合時は入力を保持。
|
||||
- サブタスクが残る場合や作業/集中セッションが実行中の場合は削除を拒否。
|
||||
- タスクhead、版参照、通知予約、達成度メトリクスを削除。カレンダー時間枠との関連は解除。
|
||||
- Wikiメモ、カレンダー予定、記録済みの作業時間は保持。CASファイル・既存バックアップの安全消去ではありません。
|
||||
- CalDAV一覧/REPORTから削除対象を除外。削除済みのUUIDとcollection内のDAV UID/hrefを予約し、古い端末からの再作成を拒否。
|
||||
- 従来のDAV DELETEをアーカイブへ変換する動作は維持。
|
||||
|
||||
詳細は[タスクの実装契約](../../design/ja/tasks-implementation.md#タスクの削除)を参照してください。
|
||||
|
||||
## DBと切り戻し
|
||||
|
||||
`organizer_task_deletions` を追加します。起動時の移行は既存タスクを削除せず、
|
||||
既存のタスクデータや版参照を変更しません。DAV索引再構築は削除記録の識別子予約にも対応します。
|
||||
|
||||
旧版は削除記録を認識しません。削除機能を使用した後の旧版への切り戻しでは、
|
||||
クライアントの再送で同じDAVタスクが作成されるおそれがあります。
|
||||
切り戻す場合は書き込み・DAV同期を停止してから判断し、DBを無断で過去へ戻さないでください。
|
||||
|
||||
## 検証と配備
|
||||
|
||||
対象commitは `38a4fcf5301e0c7c6cad12070e040dc62a03d41b`。
|
||||
2026-11-08 18:20:25 JSTに配備後の検証を完了しました。
|
||||
|
||||
- [ビルドCI run 68](https://git.anya.jp/anya/pages/actions/runs/68)、[リリースCI run 69](https://git.anya.jp/anya/pages/actions/runs/69)はともにsuccess。
|
||||
- [Gitea Release v0.14.0](https://git.anya.jp/anya/pages/releases/tag/v0.14.0)と注釈付きGitタグを公開。
|
||||
- リリース対象だけの独立ソースで `go test -p 1 ./...`、server/storeのgo vet、配布ツール等15テスト、PC・モバイル幅のChromium回帰試験が成功。
|
||||
- 両本番DBのオンラインバックアップを隔離し、`EnsureTasksSchema`を各2回実行。task head・版参照・DAV resource/collection識別子のdigestが移行前後で一致し、削除記録は0件、`integrity_check`はok。
|
||||
- app・app2・adaptor-gateway・excalidraw-viewerを同じv0.14.0へ更新。他サービス・Gecko設定・利用者設定は変更なし。
|
||||
|
||||
本番のタスク削除や外部カレンダー本文を用いた検証は行っていません。
|
||||
|
||||
### 復旧点
|
||||
|
||||
`.deployment-backups/release-v0.14.0-20261108/` の `config/` に旧構成、
|
||||
`cutover/data`・`cutover/data2`に停止時点のデータを保存しています。
|
||||
18:18:53 JSTに停止を開始、18:19:57 JSTにchecksum同期・再走査の差分ゼロ・DB一致を確認しました。
|
||||
稼働元とinodeを共有しません。旧バックアップは削除していません。
|
||||
旧3イメージは `rollback-before-v0.14.0-20261108` タグで保持しています。
|
||||
|
||||
`.env.release` は `PAGESWIKI_IMAGE_TAG=v0.14.0`。
|
||||
新版の4サービスは18:20:12〜18:20:18 JSTに起動しました。
|
||||
|
||||
### 配備後検証
|
||||
|
||||
- 4サービスのrevisionが対象commitと一致、running、再起動回数0。
|
||||
- app・app2のhealthと管理スキーマ検査が正常。legacy task領域は上記の隔離コピー移行試験で別途確認。
|
||||
- 両DBの `quick_check` がok、削除記録0件。
|
||||
- 外部HTTPSのhealth・ログイン画面200。匿名のタスク/ダッシュボード/RSS画面は303、タスクAPIは401。
|
||||
- 実在しないUUIDへの匿名DELETEを401で拒否。
|
||||
- tasks.js、tasks.css、organizer-dashboard.js、feeds.js、feed-gecko.jsの配信SHA-256がリリースcommitと一致。未完了Gecko変更の混入なし。
|
||||
- 起動直後のfatal/panic、DB lock、event job failed、schema/migration errorは両アプリとも各0件。
|
||||
|
||||
### 配布イメージ
|
||||
|
||||
SHAタグから再ビルドせず昇格し、本番ホストで取得したdigestとCIの昇格結果が一致しています。
|
||||
|
||||
| イメージ(`git.anya.jp/anya/`、タグ`v0.14.0`) | manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:46edb2640bfda3be73d8bed354bb1e014b050d68b6c17af8036d65d7732378af` |
|
||||
| pageswiki-adaptor-gateway | `sha256:696f2d0bcdf1a3dce8821c061a78ad9f3d6fcaadda32cc1cb4e5d5a117028fc0` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:4d72abb4c1964553458af2b95e19722e18ae05fcfa2b02ff086407ad962ca62c` |
|
||||
@@ -12,6 +12,14 @@ require (
|
||||
modernc.org/sqlite v1.32.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/google/go-cmp v0.6.0 // indirect
|
||||
github.com/google/nftables v0.3.0 // indirect
|
||||
github.com/mdlayher/netlink v1.7.3-0.20250113171957-fbb4dce95f42 // indirect
|
||||
github.com/mdlayher/socket v0.5.0 // indirect
|
||||
golang.org/x/sync v0.11.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||
github.com/SherClockHolmes/webpush-go v1.4.0
|
||||
|
||||
@@ -27,7 +27,10 @@ github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17w
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/gomarkdown/markdown v0.0.0-20260417124207-7d523f7318df h1:Mwihr/o+v4L5h56rwHLOE20+hh7Okhwno5BHz3zDuao=
|
||||
github.com/gomarkdown/markdown v0.0.0-20260417124207-7d523f7318df/go.mod h1:JDGcbDT52eL4fju3sZ4TeHGsQwhG9nbDV21aMyhwPoA=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/nftables v0.3.0 h1:bkyZ0cbpVeMHXOrtlFc8ISmfVqq5gPJukoYieyVmITg=
|
||||
github.com/google/nftables v0.3.0/go.mod h1:BCp9FsrbF1Fn/Yu6CLUc9GGZFw/+hsxfluNXXmxBfRM=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
@@ -55,6 +58,10 @@ github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZ
|
||||
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/mdlayher/netlink v1.7.3-0.20250113171957-fbb4dce95f42 h1:A1Cq6Ysb0GM0tpKMbdCXCIfBclan4oHk1Jb+Hrejirg=
|
||||
github.com/mdlayher/netlink v1.7.3-0.20250113171957-fbb4dce95f42/go.mod h1:BB4YCPDOzfy7FniQ/lxuYQ3dgmM2cZumHbK8RpTjN2o=
|
||||
github.com/mdlayher/socket v0.5.0 h1:ilICZmJcQz70vrWVes1MFera4jGiWNocSkykwwoy3XI=
|
||||
github.com/mdlayher/socket v0.5.0/go.mod h1:WkcBFfvyG8QENs5+hfQPl1X6Jpd2yeLIYgrGFmJiJxI=
|
||||
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
|
||||
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
|
||||
@@ -21,6 +21,7 @@ type Manifest struct {
|
||||
|
||||
func Catalog() []Manifest {
|
||||
return []Manifest{
|
||||
{ID: "viewer.gecko", APIVersion: 1, Version: "0.1.0", Kind: "viewer", Scope: "domain", NameKey: "feeds.gecko", DescriptionKey: "feeds.gecko_help", Capabilities: []string{"feeds.own.read"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: false, ResourceClass: "client-compute+relay-network"},
|
||||
{ID: "organizer.feeds", APIVersion: 1, Version: "0.1.0", Kind: "feeds", Scope: "domain", NameKey: "feeds.title", DescriptionKey: "feeds.help", Capabilities: []string{"feeds.own.read", "feeds.own.write"}, Events: []string{"feed.source.sync"}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "background+network+index"},
|
||||
{ID: "organizer.contacts", APIVersion: 1, Version: "0.2.0", Kind: "contacts", Scope: "domain", NameKey: "contacts.title", DescriptionKey: "contacts.help", Capabilities: []string{"contacts.own.read", "contacts.own.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||
{ID: "organizer.tasks", APIVersion: 1, Version: "0.14.0", Kind: "tasks", Scope: "domain", NameKey: "tasks.title", DescriptionKey: "tasks.help", Capabilities: []string{"tasks.own.read", "tasks.own.write"}, Events: []string{"organizer.task.changed", "organizer.project.changed", "task.digest.deliver"}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+background+index"},
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
PagesWiki Gecko relay
|
||||
|
||||
This image contains the PagesWiki TCP relay, not Firefox/Gecko, gecko.js,
|
||||
gecko.wasm.zst, Mozilla runtime assets or browser fonts.
|
||||
|
||||
Third-party code linked into the relay binary:
|
||||
- Go standard library and runtime, Copyright The Go Authors.
|
||||
BSD-3-Clause; full license: /licenses/Go.txt
|
||||
Source and release archives: https://go.dev/dl/
|
||||
- golang.org/x/net v0.35.0 (WebSocket transport), Copyright The Go Authors.
|
||||
BSD-3-Clause; full license: /licenses/golang-x-net.txt
|
||||
Source: https://go.googlesource.com/net/+/refs/tags/v0.35.0/
|
||||
|
||||
The licenses are copied from the exact toolchain/module used at build time.
|
||||
The scratch runtime image does not contain Alpine, BusyBox or apk.
|
||||
The PagesWiki integration source and engine redistribution assessment are in:
|
||||
https://git.anya.jp/anya/pages
|
||||
docs/operations/gecko-redistribution.md
|
||||
|
||||
Mounting and serving an independently obtained browser engine requires a
|
||||
separate assessment and delivery of its applicable notices and source offer.
|
||||
This relay notice is not a license grant for that engine.
|
||||
@@ -0,0 +1,137 @@
|
||||
// Package geckorelay provides a bounded TCP-only Wisp transport for Gecko.
|
||||
// It is not a public general-purpose proxy: the PagesWiki frontend authenticates
|
||||
// the user and signs each backend request, and every destination is checked here.
|
||||
package geckorelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const GrantHeader = "X-PagesWiki-Gecko-Grant"
|
||||
|
||||
type Grant struct {
|
||||
Subject string `json:"subject"`
|
||||
Nonce string `json:"nonce"`
|
||||
Expires int64 `json:"expires"`
|
||||
}
|
||||
|
||||
func Sign(key string, grant Grant) string {
|
||||
data, _ := json.Marshal(grant)
|
||||
body := base64.RawURLEncoding.EncodeToString(data)
|
||||
h := hmac.New(sha256.New, []byte(key))
|
||||
h.Write([]byte(body))
|
||||
return body + "." + base64.RawURLEncoding.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
func Verify(key, token string, now time.Time) (Grant, error) {
|
||||
var grant Grant
|
||||
parts := strings.Split(token, ".")
|
||||
if len(key) < 32 || len(token) > 2048 || len(parts) != 2 {
|
||||
return grant, errors.New("invalid grant")
|
||||
}
|
||||
sig, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return grant, errors.New("invalid grant")
|
||||
}
|
||||
h := hmac.New(sha256.New, []byte(key))
|
||||
h.Write([]byte(parts[0]))
|
||||
if !hmac.Equal(sig, h.Sum(nil)) {
|
||||
return grant, errors.New("invalid grant")
|
||||
}
|
||||
data, err := base64.RawURLEncoding.DecodeString(parts[0])
|
||||
if err != nil {
|
||||
return grant, errors.New("invalid grant")
|
||||
}
|
||||
if json.Unmarshal(data, &grant) != nil || grant.Subject == "" || len(grant.Subject) > 160 || len(grant.Nonce) < 16 || len(grant.Nonce) > 80 || grant.Expires <= now.Unix() || grant.Expires > now.Add(time.Minute).Unix() {
|
||||
return Grant{}, errors.New("invalid grant")
|
||||
}
|
||||
return grant, nil
|
||||
}
|
||||
|
||||
var denied = func() []netip.Prefix {
|
||||
var result []netip.Prefix
|
||||
for _, p := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "192.88.99.0/24", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "2001::/23", "2001:db8::/32", "2002::/16", "3fff::/20"} {
|
||||
result = append(result, netip.MustParsePrefix(p))
|
||||
}
|
||||
return result
|
||||
}()
|
||||
|
||||
func PublicIP(ip netip.Addr) bool {
|
||||
ip = ip.Unmap()
|
||||
if !ip.IsValid() || ip.Zone() != "" || !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
|
||||
return false
|
||||
}
|
||||
// Only globally allocated IPv6 unicast; excludes NAT64, mapped/private and
|
||||
// future address classes rather than treating unknown ranges as public.
|
||||
if ip.Is6() && !netip.MustParsePrefix("2000::/3").Contains(ip) {
|
||||
return false
|
||||
}
|
||||
for _, p := range denied {
|
||||
if p.Contains(ip) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func ValidDestination(host string, port uint16) bool {
|
||||
if port != 80 && port != 443 {
|
||||
return false
|
||||
}
|
||||
if ip, err := netip.ParseAddr(host); err == nil {
|
||||
return PublicIP(ip)
|
||||
}
|
||||
host = strings.TrimSuffix(strings.ToLower(host), ".")
|
||||
if len(host) == 0 || len(host) > 253 || host == "localhost" || strings.HasSuffix(host, ".localhost") || !strings.Contains(host, ".") {
|
||||
return false
|
||||
}
|
||||
for _, label := range strings.Split(host, ".") {
|
||||
if len(label) == 0 || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
|
||||
return false
|
||||
}
|
||||
for _, c := range label {
|
||||
if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type lookupFunc func(context.Context, string, string) ([]netip.Addr, error)
|
||||
type dialFunc func(context.Context, string, string) (net.Conn, error)
|
||||
|
||||
func dialPublic(ctx context.Context, host string, port uint16, lookup lookupFunc, dial dialFunc) (net.Conn, error) {
|
||||
if !ValidDestination(host, port) {
|
||||
return nil, errors.New("blocked destination")
|
||||
}
|
||||
ips, err := lookup(ctx, "ip", host)
|
||||
if err != nil || len(ips) == 0 || len(ips) > 16 {
|
||||
return nil, errors.New("destination lookup failed")
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if !PublicIP(ip) {
|
||||
return nil, errors.New("blocked destination")
|
||||
}
|
||||
}
|
||||
for _, ip := range ips {
|
||||
conn, e := dial(ctx, "tcp", net.JoinHostPort(ip.Unmap().String(), strconv.Itoa(int(port))))
|
||||
if e == nil {
|
||||
return conn, nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil, errors.New("destination unavailable")
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package geckorelay
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const AssetsPrefix = "/assets/v0.0.1/"
|
||||
|
||||
// Hashes of the two unmodified files in upstream v0.0.1. The release archive
|
||||
// itself is pinned in docs/operations/gecko-relay.md. Refuse mixed engine/glue.
|
||||
func VerifyAssets(dir string) error {
|
||||
for name, want := range map[string]string{
|
||||
"gecko.js": "e5aeebffd21106eccf23b1219316221add5e95085bc5a1bfb941117cfcd75ef7",
|
||||
"gecko.wasm.zst": "ebd6c75179152624d9644865e11792ed25cadc714d9e0985f412baf9c637a086",
|
||||
} {
|
||||
f, err := os.Open(filepath.Join(dir, name))
|
||||
if err != nil {
|
||||
return fmt.Errorf("required Gecko asset unavailable: %s", name)
|
||||
}
|
||||
h := sha256.New()
|
||||
_, err = io.Copy(h, io.LimitReader(f, 64<<20))
|
||||
f.Close()
|
||||
if err != nil || hex.EncodeToString(h.Sum(nil)) != want {
|
||||
return fmt.Errorf("Gecko asset checksum mismatch: %s", name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package geckorelay
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
const DistributionPrefix = "/distribution/v0.0.1/"
|
||||
|
||||
// Updated only after the reproducible source/notice bundle has been reviewed.
|
||||
const DistributionManifestSHA256 = "84953114f5e393dd97d9f948a5bc51c95b9355b58461dd3355e068a96cb2e381"
|
||||
|
||||
type DistributionFile struct {
|
||||
File string `json:"file"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Size int64 `json:"size"`
|
||||
Kind string `json:"kind"`
|
||||
}
|
||||
|
||||
var distributionName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._+-]{0,150}$`)
|
||||
|
||||
func VerifyDistribution(dir string) (map[string]DistributionFile, error) {
|
||||
return verifyDistribution(dir, DistributionManifestSHA256)
|
||||
}
|
||||
|
||||
func verifyDistribution(dir, expected string) (map[string]DistributionFile, error) {
|
||||
path := filepath.Join(dir, "manifest.json")
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Size() > 1<<20 {
|
||||
return nil, fmt.Errorf("Gecko distribution manifest missing or invalid")
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
if hex.EncodeToString(sum[:]) != expected {
|
||||
return nil, fmt.Errorf("Gecko distribution manifest checksum mismatch")
|
||||
}
|
||||
var manifest struct {
|
||||
Format string `json:"format"`
|
||||
Version string `json:"version"`
|
||||
Files []DistributionFile `json:"files"`
|
||||
}
|
||||
if json.Unmarshal(raw, &manifest) != nil || manifest.Format != "pageswiki.gecko-distribution.v1" || manifest.Version != "v0.0.1" || len(manifest.Files) > 512 {
|
||||
return nil, fmt.Errorf("invalid Gecko distribution format")
|
||||
}
|
||||
files := map[string]DistributionFile{}
|
||||
for _, entry := range manifest.Files {
|
||||
if !distributionName.MatchString(entry.File) || entry.File == "manifest.json" || entry.Size < 1 || entry.Size > 2<<30 || len(entry.SHA256) != 64 {
|
||||
return nil, fmt.Errorf("invalid distribution entry")
|
||||
}
|
||||
if _, exists := files[entry.File]; exists {
|
||||
return nil, fmt.Errorf("duplicate distribution entry")
|
||||
}
|
||||
info, err := os.Lstat(filepath.Join(dir, entry.File))
|
||||
if err != nil || !info.Mode().IsRegular() || info.Size() != entry.Size {
|
||||
return nil, fmt.Errorf("distribution file missing or invalid: %s", entry.File)
|
||||
}
|
||||
file, err := os.Open(filepath.Join(dir, entry.File))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hash := sha256.New()
|
||||
_, err = io.Copy(hash, io.LimitReader(file, entry.Size+1))
|
||||
file.Close()
|
||||
if err != nil || hex.EncodeToString(hash.Sum(nil)) != entry.SHA256 {
|
||||
return nil, fmt.Errorf("distribution file checksum mismatch: %s", entry.File)
|
||||
}
|
||||
files[entry.File] = entry
|
||||
}
|
||||
for _, name := range []string{"index.html", "README.txt", "gecko.js", "gecko.wasm.zst", "firefox.tar.gz", "firefox.tar.gz.notices.txt", "wrapper.tar.gz", "wrapper-MPL.txt", "emscripten.tar.gz", "emscripten.tar.gz.notices.txt", "rust-src.tar.xz", "rust-src.tar.xz.notices.txt", "zstddec.tgz", "zstddec.tgz.notices.txt", "NotoSansCJKjp-Regular.otf", "NotoSansCJK-LICENSE.txt"} {
|
||||
if _, ok := files[name]; !ok {
|
||||
return nil, fmt.Errorf("distribution incomplete: %s", name)
|
||||
}
|
||||
}
|
||||
files["manifest.json"] = DistributionFile{File: "manifest.json", SHA256: expected, Size: int64(len(raw)), Kind: "manifest"}
|
||||
return files, nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package geckorelay
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDistribution(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if _, err := VerifyDistribution(dir); err == nil {
|
||||
t.Fatal("missing distribution accepted")
|
||||
}
|
||||
names := []string{"index.html", "README.txt", "gecko.js", "gecko.wasm.zst", "firefox.tar.gz", "firefox.tar.gz.notices.txt", "wrapper.tar.gz", "wrapper-MPL.txt", "emscripten.tar.gz", "emscripten.tar.gz.notices.txt", "rust-src.tar.xz", "rust-src.tar.xz.notices.txt", "zstddec.tgz", "zstddec.tgz.notices.txt", "NotoSansCJKjp-Regular.otf", "NotoSansCJK-LICENSE.txt"}
|
||||
content := []byte("synthetic source and notice")
|
||||
hash := sha256.Sum256(content)
|
||||
var entries []DistributionFile
|
||||
for _, name := range names {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), content, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries = append(entries, DistributionFile{File: name, Size: int64(len(content)), SHA256: hex.EncodeToString(hash[:])})
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"format": "pageswiki.gecko-distribution.v1", "version": "v0.0.1", "files": entries})
|
||||
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), raw, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
want := hex.EncodeToString(sum[:])
|
||||
files, err := verifyDistribution(dir, want)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
relay, _ := New(testKey, dir)
|
||||
relay.Distribution = files
|
||||
for _, name := range []string{"index.html", "firefox.tar.gz", "manifest.json", "unknown", "../manifest.json"} {
|
||||
req := httptest.NewRequest("GET", DistributionPrefix+name, nil)
|
||||
req.Header.Set(GrantHeader, Sign(testKey, Grant{Subject: "test:user", Nonce: "download-test-0123456789", Expires: time.Now().Add(30 * time.Second).Unix()}))
|
||||
rec := httptest.NewRecorder()
|
||||
relay.ServeHTTP(rec, req)
|
||||
expected := 200
|
||||
if strings.Contains(name, "unknown") || strings.Contains(name, "../") {
|
||||
expected = 404
|
||||
}
|
||||
if rec.Code != expected {
|
||||
t.Fatalf("%s: %d", name, rec.Code)
|
||||
}
|
||||
if expected == 200 && rec.Header().Get("ETag") == "" {
|
||||
t.Fatal("no ETag")
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "README.txt"), []byte("tampered"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := verifyDistribution(dir, want); err == nil {
|
||||
t.Fatal("tampered notice accepted")
|
||||
}
|
||||
if err := os.Remove(filepath.Join(dir, "README.txt")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(dir, "gecko.js"), filepath.Join(dir, "README.txt")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := verifyDistribution(dir, want); err == nil {
|
||||
t.Fatal("symlink accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributionRealBundle(t *testing.T) {
|
||||
dir := os.Getenv("PAGESWIKI_GECKO_TEST_BUNDLE")
|
||||
if dir == "" {
|
||||
t.Skip("opt-in complete distribution")
|
||||
}
|
||||
if _, err := VerifyDistribution(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
package geckorelay
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/websocket"
|
||||
)
|
||||
|
||||
const (
|
||||
window = 8
|
||||
maxFrame = 256 << 10
|
||||
maxStreams = 16
|
||||
maxBytes = 256 << 20
|
||||
bytesPerSecond = 2 << 20
|
||||
)
|
||||
|
||||
type Relay struct {
|
||||
Key, Assets string
|
||||
Distribution map[string]DistributionFile
|
||||
downloads chan struct{}
|
||||
mu sync.Mutex
|
||||
active map[string]bool
|
||||
used map[string]int64
|
||||
rx, tx, rejected atomic.Int64
|
||||
// Overridden only by package tests; deployment always resolves and pins public IPs.
|
||||
dial func(context.Context, string, uint16) (net.Conn, error)
|
||||
}
|
||||
|
||||
func New(key, assets string) (*Relay, error) {
|
||||
if len(key) < 32 {
|
||||
return nil, errors.New("relay key must contain at least 32 bytes")
|
||||
}
|
||||
r := &Relay{Key: key, Assets: assets, active: map[string]bool{}, used: map[string]int64{}, downloads: make(chan struct{}, 2)}
|
||||
r.dial = func(ctx context.Context, host string, port uint16) (net.Conn, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||
defer cancel()
|
||||
return dialPublic(ctx, host, port, net.DefaultResolver.LookupNetIP, (&net.Dialer{Timeout: 2 * time.Second}).DialContext)
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (r *Relay) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if req.URL.Path == "/health" && req.Method == "GET" {
|
||||
io.WriteString(w, "ok")
|
||||
return
|
||||
}
|
||||
grant, err := Verify(r.Key, req.Header.Get(GrantHeader), time.Now())
|
||||
if err != nil {
|
||||
http.Error(w, "forbidden", 403)
|
||||
return
|
||||
}
|
||||
if req.Method != "GET" || req.URL.RawQuery != "" {
|
||||
http.Error(w, "invalid request", 400)
|
||||
return
|
||||
}
|
||||
if req.URL.Path == "/status" {
|
||||
r.mu.Lock()
|
||||
active := len(r.active)
|
||||
r.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{"active_sessions": active, "received_bytes": r.rx.Load(), "sent_bytes": r.tx.Load(), "rejected": r.rejected.Load(), "profile": "tcp-80-443", "max_sessions": 4, "max_streams": maxStreams, "bytes_per_second": bytesPerSecond, "max_session_bytes": maxBytes})
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(req.URL.Path, DistributionPrefix) {
|
||||
name := strings.TrimPrefix(req.URL.Path, DistributionPrefix)
|
||||
entry, ok := r.Distribution[name]
|
||||
if !ok {
|
||||
http.NotFound(w, req)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case r.downloads <- struct{}{}:
|
||||
defer func() { <-r.downloads }()
|
||||
default:
|
||||
http.Error(w, "download limit", 429)
|
||||
return
|
||||
}
|
||||
w.Header().Set("ETag", `"`+entry.SHA256+`"`)
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400, immutable")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'none'; base-uri 'none'; frame-ancestors 'self'")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
switch {
|
||||
case name == "index.html":
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
case strings.HasSuffix(name, ".txt"):
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
case name == "manifest.json":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
default:
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="`+name+`"`)
|
||||
}
|
||||
// ServeContent avoids ServeFile's /index.html -> ./ redirect, which
|
||||
// would escape the explicit file allowlist at the proxy boundary.
|
||||
file, err := os.Open(filepath.Join(r.Assets, name))
|
||||
if err != nil {
|
||||
http.NotFound(w, req)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
http.ServeContent(w, req, name, time.Time{}, file)
|
||||
return
|
||||
}
|
||||
if req.URL.Path == AssetsPrefix+"gecko.js" || req.URL.Path == AssetsPrefix+"gecko.wasm.zst" {
|
||||
w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400, immutable")
|
||||
if strings.HasSuffix(req.URL.Path, ".js") {
|
||||
w.Header().Set("Content-Type", "text/javascript")
|
||||
} else {
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
}
|
||||
http.ServeFile(w, req, filepath.Join(r.Assets, filepath.Base(req.URL.Path)))
|
||||
return
|
||||
}
|
||||
if req.URL.Path != "/wisp/" {
|
||||
http.NotFound(w, req)
|
||||
return
|
||||
}
|
||||
r.mu.Lock()
|
||||
now := time.Now().Unix()
|
||||
for nonce, expires := range r.used {
|
||||
if expires <= now {
|
||||
delete(r.used, nonce)
|
||||
}
|
||||
}
|
||||
if r.active[grant.Subject] || len(r.active) >= 4 || r.used[grant.Nonce] > now || len(r.used) >= 256 {
|
||||
r.mu.Unlock()
|
||||
r.rejected.Add(1)
|
||||
http.Error(w, "session limit", 429)
|
||||
return
|
||||
}
|
||||
r.active[grant.Subject] = true
|
||||
r.used[grant.Nonce] = grant.Expires
|
||||
r.mu.Unlock()
|
||||
defer func() { r.mu.Lock(); delete(r.active, grant.Subject); r.mu.Unlock() }()
|
||||
wsServer := websocket.Server{Handshake: func(c *websocket.Config, req *http.Request) error {
|
||||
// Only the authenticated PagesWiki proxy can sign a grant. It validates
|
||||
// the browser Origin before forwarding, not the untrusted client header.
|
||||
if req.Header.Get("Origin") == "" {
|
||||
return errors.New("origin required")
|
||||
}
|
||||
return nil
|
||||
}, Handler: func(ws *websocket.Conn) { r.serve(ws) }}
|
||||
wsServer.ServeHTTP(w, req)
|
||||
}
|
||||
|
||||
type stream struct {
|
||||
data chan []byte
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
mu sync.Mutex
|
||||
conn net.Conn
|
||||
}
|
||||
|
||||
func (s *stream) close() {
|
||||
s.once.Do(func() {
|
||||
close(s.done)
|
||||
s.mu.Lock()
|
||||
if s.conn != nil {
|
||||
s.conn.Close()
|
||||
}
|
||||
s.mu.Unlock()
|
||||
})
|
||||
}
|
||||
func packet(kind byte, id uint32, data []byte) []byte {
|
||||
b := make([]byte, 5+len(data))
|
||||
b[0] = kind
|
||||
binary.LittleEndian.PutUint32(b[1:], id)
|
||||
copy(b[5:], data)
|
||||
return b
|
||||
}
|
||||
func credit() []byte { b := make([]byte, 4); binary.LittleEndian.PutUint32(b, window); return b }
|
||||
|
||||
func (r *Relay) serve(ws *websocket.Conn) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
|
||||
defer cancel()
|
||||
defer ws.Close()
|
||||
ws.MaxPayloadBytes = maxFrame + 5
|
||||
var mu, sendMu, budgetMu sync.Mutex
|
||||
streams := map[uint32]*stream{}
|
||||
var workers sync.WaitGroup
|
||||
var spent int64
|
||||
tokens := float64(bytesPerSecond)
|
||||
last := time.Now()
|
||||
account := func(n int) bool {
|
||||
budgetMu.Lock()
|
||||
defer budgetMu.Unlock()
|
||||
spent += int64(n)
|
||||
if spent > maxBytes {
|
||||
return false
|
||||
}
|
||||
now := time.Now()
|
||||
tokens += now.Sub(last).Seconds() * bytesPerSecond
|
||||
if tokens > bytesPerSecond {
|
||||
tokens = bytesPerSecond
|
||||
}
|
||||
last = now
|
||||
tokens -= float64(n)
|
||||
if tokens < 0 {
|
||||
timer := time.NewTimer(time.Duration(-tokens / bytesPerSecond * float64(time.Second)))
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
tokens = 0
|
||||
last = time.Now()
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
send := func(kind byte, id uint32, data []byte) error {
|
||||
sendMu.Lock()
|
||||
defer sendMu.Unlock()
|
||||
ws.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
return websocket.Message.Send(ws, packet(kind, id, data))
|
||||
}
|
||||
defer func() {
|
||||
cancel()
|
||||
mu.Lock()
|
||||
for _, s := range streams {
|
||||
s.close()
|
||||
}
|
||||
mu.Unlock()
|
||||
workers.Wait()
|
||||
}()
|
||||
go func() { <-ctx.Done(); ws.Close() }()
|
||||
if send(3, 0, credit()) != nil {
|
||||
return
|
||||
}
|
||||
connections := 0
|
||||
for {
|
||||
ws.SetReadDeadline(time.Now().Add(90 * time.Second))
|
||||
var b []byte
|
||||
if websocket.Message.Receive(ws, &b) != nil {
|
||||
return
|
||||
}
|
||||
if len(b) < 5 || !account(len(b)) {
|
||||
return
|
||||
}
|
||||
r.rx.Add(int64(len(b)))
|
||||
kind, id := b[0], binary.LittleEndian.Uint32(b[1:])
|
||||
if id == 0 {
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
s := streams[id]
|
||||
mu.Unlock()
|
||||
switch kind {
|
||||
case 1:
|
||||
connections++
|
||||
if s != nil || len(b) < 9 || len(b) > 261 || connections > 256 {
|
||||
return
|
||||
}
|
||||
port := binary.LittleEndian.Uint16(b[6:8])
|
||||
host := string(b[8:])
|
||||
if b[5] != 1 || !ValidDestination(host, port) {
|
||||
r.rejected.Add(1)
|
||||
if send(4, id, []byte{0x48}) != nil {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
mu.Lock()
|
||||
full := len(streams) >= maxStreams
|
||||
mu.Unlock()
|
||||
if full {
|
||||
r.rejected.Add(1)
|
||||
if send(4, id, []byte{0x49}) != nil {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
s = &stream{data: make(chan []byte, window), done: make(chan struct{})}
|
||||
mu.Lock()
|
||||
streams[id] = s
|
||||
mu.Unlock()
|
||||
workers.Add(1)
|
||||
go func(id uint32, s *stream, host string, port uint16) {
|
||||
defer workers.Done()
|
||||
defer func() { s.close(); mu.Lock(); delete(streams, id); mu.Unlock() }()
|
||||
dialCtx, stop := context.WithCancel(ctx)
|
||||
defer stop()
|
||||
go func() {
|
||||
select {
|
||||
case <-s.done:
|
||||
stop()
|
||||
case <-dialCtx.Done():
|
||||
}
|
||||
}()
|
||||
conn, e := r.dial(dialCtx, host, port)
|
||||
if e != nil {
|
||||
r.rejected.Add(1)
|
||||
send(4, id, []byte{0x48})
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.conn = conn
|
||||
s.mu.Unlock()
|
||||
select {
|
||||
case <-s.done:
|
||||
conn.Close()
|
||||
return
|
||||
default:
|
||||
}
|
||||
readerDone := make(chan struct{})
|
||||
defer func() { conn.Close(); <-readerDone }()
|
||||
go func() {
|
||||
defer close(readerDone)
|
||||
defer s.close()
|
||||
buffer := make([]byte, 64<<10)
|
||||
for {
|
||||
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
|
||||
n, e := conn.Read(buffer)
|
||||
if n > 0 {
|
||||
if !account(n) {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
r.tx.Add(int64(n))
|
||||
if send(2, id, buffer[:n]) != nil {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
if e != nil {
|
||||
send(4, id, []byte{2})
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
count := 0
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-s.done:
|
||||
return
|
||||
case data := <-s.data:
|
||||
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
if _, e = io.Copy(conn, bytes.NewReader(data)); e != nil {
|
||||
send(4, id, []byte{3})
|
||||
return
|
||||
}
|
||||
count++
|
||||
if count == window {
|
||||
count = 0
|
||||
if send(3, id, credit()) != nil {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}(id, s, host, port)
|
||||
case 2:
|
||||
if s == nil {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case <-s.done:
|
||||
case s.data <- b[5:]:
|
||||
default:
|
||||
r.rejected.Add(1)
|
||||
s.close()
|
||||
if send(4, id, []byte{0x49}) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
case 4:
|
||||
if len(b) != 6 {
|
||||
return
|
||||
}
|
||||
if s != nil {
|
||||
s.close()
|
||||
}
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package geckorelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/websocket"
|
||||
)
|
||||
|
||||
const testKey = "synthetic-relay-key-at-least-32-bytes-long"
|
||||
|
||||
func TestAssetsPin(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if VerifyAssets(dir) == nil {
|
||||
t.Fatal("missing assets accepted")
|
||||
}
|
||||
for _, name := range []string{"gecko.js", "gecko.wasm.zst"} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte("untrusted"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if VerifyAssets(dir) == nil {
|
||||
t.Fatal("unverified assets accepted")
|
||||
}
|
||||
if assets := os.Getenv("PAGESWIKI_GECKO_TEST_ASSETS"); assets != "" {
|
||||
if err := VerifyAssets(assets); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrant(t *testing.T) {
|
||||
now := time.Now()
|
||||
g := Grant{"domain:actor", "0123456789abcdef", now.Add(30 * time.Second).Unix()}
|
||||
token := Sign(testKey, g)
|
||||
if got, e := Verify(testKey, token, now); e != nil || got != g {
|
||||
t.Fatal(got, e)
|
||||
}
|
||||
for _, bad := range []string{token + "x", "", strings.Repeat("x", 2049), Sign(testKey, Grant{g.Subject, g.Nonce, now.Add(2 * time.Minute).Unix()}), Sign(testKey, Grant{g.Subject, g.Nonce, now.Unix()})} {
|
||||
if _, e := Verify(testKey, bad, now); e == nil {
|
||||
t.Fatal("accepted invalid grant")
|
||||
}
|
||||
}
|
||||
if _, e := Verify("other-key-at-least-32-bytes-long!!", token, now); e == nil {
|
||||
t.Fatal("wrong key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDestinations(t *testing.T) {
|
||||
for _, host := range []string{"127.0.0.1", "localhost", "host.localhost", "10.0.0.1", "169.254.169.254", "100.64.0.1", "192.0.2.2", "198.19.0.1", "::1", "::ffff:127.0.0.1", "64:ff9b::808:808", "2002:808:808::1", "2001:db8::1", "3fff::1", "fd00::1", "fe80::1%eth0", "bad/host", "example.org\x00.evil", "singlelabel"} {
|
||||
if ValidDestination(host, 443) {
|
||||
t.Fatalf("allowed %q", host)
|
||||
}
|
||||
}
|
||||
for _, host := range []string{"example.org", "EXAMPLE.org.", "8.8.8.8", "2606:4700:4700::1111"} {
|
||||
if !ValidDestination(host, 443) {
|
||||
t.Fatal("blocked", host)
|
||||
}
|
||||
}
|
||||
if ValidDestination("example.org", 22) {
|
||||
t.Fatal("port allowed")
|
||||
}
|
||||
called := false
|
||||
dial := func(_ context.Context, _, addr string) (net.Conn, error) {
|
||||
called = true
|
||||
if addr != "8.8.8.8:443" {
|
||||
t.Fatal("unvalidated DNS re-resolution", addr)
|
||||
}
|
||||
a, b := net.Pipe()
|
||||
b.Close()
|
||||
return a, nil
|
||||
}
|
||||
lookup := func(_ context.Context, _, _ string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("127.0.0.1")}, nil
|
||||
}
|
||||
if _, err := dialPublic(context.Background(), "example.org", 443, lookup, dial); err == nil || called {
|
||||
t.Fatal("mixed DNS allowed")
|
||||
}
|
||||
lookup = func(_ context.Context, _, _ string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
|
||||
}
|
||||
c, err := dialPublic(context.Background(), "example.org", 443, lookup, dial)
|
||||
if err != nil || !called {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
|
||||
func TestRelayFramesAndLimits(t *testing.T) {
|
||||
r, _ := New(testKey, t.TempDir())
|
||||
r.dial = func(ctx context.Context, host string, port uint16) (net.Conn, error) {
|
||||
a, b := net.Pipe()
|
||||
go func() { defer b.Close(); io.Copy(b, b) }()
|
||||
return a, nil
|
||||
}
|
||||
s := httptest.NewServer(r)
|
||||
defer s.Close()
|
||||
grant := Sign(testKey, Grant{"domain:actor", "nonce-first-connection", time.Now().Add(30 * time.Second).Unix()})
|
||||
dial := func(token string) (*websocket.Conn, error) {
|
||||
cfg, _ := websocket.NewConfig("ws"+strings.TrimPrefix(s.URL, "http")+"/wisp/", "https://pages.example")
|
||||
cfg.Header.Set(GrantHeader, token)
|
||||
return websocket.DialConfig(cfg)
|
||||
}
|
||||
if c, e := dial(""); e == nil {
|
||||
c.Close()
|
||||
t.Fatal("anonymous websocket")
|
||||
}
|
||||
c, err := dial(grant)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
receive := func() []byte {
|
||||
var p []byte
|
||||
if e := websocket.Message.Receive(c, &p); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return p
|
||||
}
|
||||
p := receive()
|
||||
if p[0] != 3 || binary.LittleEndian.Uint32(p[1:]) != 0 || binary.LittleEndian.Uint32(p[5:]) != window {
|
||||
t.Fatal(p)
|
||||
}
|
||||
if second, e := dial(grant); e == nil {
|
||||
second.Close()
|
||||
t.Fatal("duplicate actor/replayed grant")
|
||||
}
|
||||
connect := func(id uint32, host string, port uint16, kind byte) {
|
||||
body := []byte{kind, byte(port), byte(port >> 8)}
|
||||
body = append(body, host...)
|
||||
if e := websocket.Message.Send(c, packet(1, id, body)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
connect(1, "127.0.0.1", 80, 1)
|
||||
if p = receive(); p[0] != 4 || p[5] != 0x48 {
|
||||
t.Fatal(p)
|
||||
}
|
||||
connect(2, "example.org", 443, 2)
|
||||
if p = receive(); p[0] != 4 {
|
||||
t.Fatal("UDP accepted")
|
||||
}
|
||||
connect(3, "example.org", 443, 1)
|
||||
for n := 0; n < window; n++ {
|
||||
if e := websocket.Message.Send(c, packet(2, 3, []byte("hello"))); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
got := 0
|
||||
creditSeen := false
|
||||
for got < window*5 || !creditSeen {
|
||||
p = receive()
|
||||
switch p[0] {
|
||||
case 2:
|
||||
got += len(p) - 5
|
||||
case 3:
|
||||
creditSeen = true
|
||||
default:
|
||||
t.Fatal(p)
|
||||
}
|
||||
}
|
||||
// Wisp credits count DATA frames, including empty payloads.
|
||||
for n := 0; n < window; n++ {
|
||||
if e := websocket.Message.Send(c, packet(2, 3, nil)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if p = receive(); p[0] != 3 || binary.LittleEndian.Uint32(p[1:]) != 3 {
|
||||
t.Fatal("empty frame credit", p)
|
||||
}
|
||||
websocket.Message.Send(c, packet(4, 3, []byte{2}))
|
||||
websocket.Message.Send(c, packet(9, 4, nil))
|
||||
var b []byte
|
||||
if websocket.Message.Receive(c, &b) == nil && b[0] != 4 {
|
||||
t.Fatal("invalid packet accepted")
|
||||
}
|
||||
resp, e := http.Get(s.URL + "/status")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != 403 {
|
||||
t.Fatal("unprotected metrics")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayStreamBoundAndCancellation(t *testing.T) {
|
||||
r, _ := New(testKey, t.TempDir())
|
||||
var dialing atomic.Int64
|
||||
r.dial = func(ctx context.Context, host string, port uint16) (net.Conn, error) {
|
||||
dialing.Add(1)
|
||||
defer dialing.Add(-1)
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
server := httptest.NewServer(r)
|
||||
defer server.Close()
|
||||
cfg, _ := websocket.NewConfig("ws"+strings.TrimPrefix(server.URL, "http")+"/wisp/", "https://pages.example")
|
||||
cfg.Header.Set(GrantHeader, Sign(testKey, Grant{"domain:actor", "stream-bound-nonce", time.Now().Add(30 * time.Second).Unix()}))
|
||||
c, err := websocket.DialConfig(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
var frame []byte
|
||||
if err = websocket.Message.Receive(c, &frame); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for id := 1; id <= maxStreams+1; id++ {
|
||||
if err = websocket.Message.Send(c, packet(1, uint32(id), append([]byte{1, 80, 0}, []byte("example.org")...))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err = websocket.Message.Receive(c, &frame); err != nil || len(frame) != 6 || frame[0] != 4 || binary.LittleEndian.Uint32(frame[1:]) != maxStreams+1 || frame[5] != 0x49 {
|
||||
t.Fatal("stream cap", frame, err)
|
||||
}
|
||||
c.Close()
|
||||
for n := 0; n < 100; n++ {
|
||||
r.mu.Lock()
|
||||
active := len(r.active)
|
||||
r.mu.Unlock()
|
||||
if active == 0 && dialing.Load() == 0 {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("closing session did not cancel pending dials")
|
||||
}
|
||||
|
||||
func TestRelaySessionBoundAndReplay(t *testing.T) {
|
||||
r, _ := New(testKey, t.TempDir())
|
||||
server := httptest.NewServer(r)
|
||||
defer server.Close()
|
||||
dial := func(subject, nonce string) (*websocket.Conn, error) {
|
||||
cfg, _ := websocket.NewConfig("ws"+strings.TrimPrefix(server.URL, "http")+"/wisp/", "https://pages.example")
|
||||
cfg.Header.Set(GrantHeader, Sign(testKey, Grant{subject, nonce, time.Now().Add(30 * time.Second).Unix()}))
|
||||
return websocket.DialConfig(cfg)
|
||||
}
|
||||
var conns []*websocket.Conn
|
||||
for _, subject := range []string{"one", "two", "three", "four"} {
|
||||
c, e := dial(subject, "unique-session-nonce-"+subject)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
conns = append(conns, c)
|
||||
defer c.Close()
|
||||
}
|
||||
if c, e := dial("five", "unique-session-nonce-five"); e == nil {
|
||||
c.Close()
|
||||
t.Fatal("global cap exceeded")
|
||||
}
|
||||
conns[0].Close()
|
||||
for n := 0; n < 100; n++ {
|
||||
r.mu.Lock()
|
||||
active := len(r.active)
|
||||
r.mu.Unlock()
|
||||
if active == 3 {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if c, e := dial("one", "unique-session-nonce-one"); e == nil {
|
||||
c.Close()
|
||||
t.Fatal("replayed after close")
|
||||
}
|
||||
c, e := dial("five", "unique-session-nonce-retry")
|
||||
if e != nil {
|
||||
t.Fatal("slot not released", e)
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
@@ -35,6 +35,17 @@ func (s *Server) handleAuthAdmin(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
panel := "auth"
|
||||
switch r.FormValue("action") {
|
||||
case "save_trusted_session_policy":
|
||||
panel = "auth-sessions"
|
||||
days, err := strconv.Atoi(r.PostForm.Get("trusted_session_days"))
|
||||
if err != nil || days < 0 || days > 30 {
|
||||
http.Error(w, "trusted session lifetime must be between 0 and 30 days", 400)
|
||||
return
|
||||
}
|
||||
if err := s.store.SetConfigInDomain(domainUUID, "auth_trusted_session_days", strconv.Itoa(days)); err != nil {
|
||||
http.Error(w, "could not save session policy", 500)
|
||||
return
|
||||
}
|
||||
case "save_session_policy":
|
||||
panel = "auth-sessions"
|
||||
minutes, err := strconv.Atoi(r.FormValue("session_minutes"))
|
||||
|
||||
@@ -51,4 +51,8 @@ func TestBrowserCookieLoginLogoutChromium(t *testing.T) {
|
||||
if err := s.store.DB.QueryRow(`SELECT count(*) FROM auth_sessions WHERE revoked_at_ms>0`).Scan(&revoked); err != nil || revoked != 1 {
|
||||
t.Fatalf("browser revocations=%d %v", revoked, err)
|
||||
}
|
||||
var lifetime int64
|
||||
if err := s.store.DB.QueryRow(`SELECT expires_at_ms-auth_time_ms FROM auth_sessions WHERE revoked_at_ms>0`).Scan(&lifetime); err != nil || lifetime != (30*24*time.Hour).Milliseconds() {
|
||||
t.Fatalf("trusted browser lifetime=%d %v", lifetime, err)
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,7 @@ func (s *Server) handleCLIAuth(w http.ResponseWriter, r *http.Request, action st
|
||||
writeEventJSON(w, 400, map[string]string{"error": "invalid_request"})
|
||||
return
|
||||
}
|
||||
id, device, code, err := s.store.StartCLIAuth(ctx, domain, cliOrigin(r), challenge)
|
||||
id, device, code, err := s.store.StartCLIAuthForLogin(ctx, domain, cliOrigin(r), challenge, r.PostForm.Get("remember") == "1")
|
||||
if err != nil {
|
||||
cliAuthError(w, err)
|
||||
return
|
||||
@@ -140,6 +140,9 @@ func (s *Server) verifyCLIAuth(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
data := map[string]any{"CLIAuth": true, "CLIOrigin": grant.Origin, "CLIRequest": id}
|
||||
if grant.Remember {
|
||||
data["CLIRememberDays"] = s.store.TrustedSessionDays(domain)
|
||||
}
|
||||
if grant.State != "pending" {
|
||||
data["CLIDone"] = true
|
||||
s.renderAuthPage(w, r, data)
|
||||
|
||||
@@ -28,6 +28,14 @@ func cliForm(s *Server, path string, form url.Values, cookie, origin string) *ht
|
||||
}
|
||||
|
||||
func TestCLIAuthOIDCFlow(t *testing.T) {
|
||||
for _, remember := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "normal", true: "trusted"}[remember], func(t *testing.T) {
|
||||
testCLIAuthOIDCFlow(t, remember)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testCLIAuthOIDCFlow(t *testing.T, remember bool) {
|
||||
s, api, domain := configFixture(t)
|
||||
principal := s.mustCLIPrincipal(t, domain, api)
|
||||
// An enrolled local factor must not add a second challenge to OIDC consent.
|
||||
@@ -43,7 +51,13 @@ func TestCLIAuthOIDCFlow(t *testing.T) {
|
||||
}
|
||||
verifier := strings.Repeat("x", 43)
|
||||
sum := sha256.Sum256([]byte(verifier))
|
||||
start := cliForm(s, "/_/auth/cli/start", url.Values{"code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])}, "code_challenge_method": {"S256"}}, "", "")
|
||||
startForm := url.Values{"code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])}, "code_challenge_method": {"S256"}}
|
||||
expectedSeconds := 24 * 60 * 60
|
||||
if remember {
|
||||
startForm.Set("remember", "1")
|
||||
expectedSeconds *= 30
|
||||
}
|
||||
start := cliForm(s, "/_/auth/cli/start", startForm, "", "")
|
||||
if start.Code != 200 {
|
||||
t.Fatalf("start %d %s", start.Code, start.Body.String())
|
||||
}
|
||||
@@ -63,7 +77,12 @@ func TestCLIAuthOIDCFlow(t *testing.T) {
|
||||
t.Fatalf("verify landing: %d %s", verify.Code, verify.Body.String())
|
||||
}
|
||||
begin := httptest.NewRecorder()
|
||||
s.beginOIDC(begin, httptest.NewRequest("GET", "https://localhost/_/auth/oidc?cli="+id, nil))
|
||||
// The browser query must not override the CLI's persisted choice.
|
||||
tamperedRemember := "1"
|
||||
if remember {
|
||||
tamperedRemember = "0"
|
||||
}
|
||||
s.beginOIDC(begin, httptest.NewRequest("GET", "https://localhost/_/auth/oidc?cli="+id+"&remember="+tamperedRemember, nil))
|
||||
if begin.Code != 302 {
|
||||
t.Fatalf("oidc begin %d %s", begin.Code, begin.Body.String())
|
||||
}
|
||||
@@ -86,6 +105,9 @@ func TestCLIAuthOIDCFlow(t *testing.T) {
|
||||
for _, cookie := range complete.Result().Cookies() {
|
||||
if cookie.Name == authCookieName {
|
||||
browser = cookie.Value
|
||||
if cookie.MaxAge != expectedSeconds {
|
||||
t.Fatalf("cookie lifetime %d, want %d", cookie.MaxAge, expectedSeconds)
|
||||
}
|
||||
}
|
||||
}
|
||||
if browser == "" {
|
||||
@@ -128,6 +150,7 @@ func TestCLIAuthOIDCFlow(t *testing.T) {
|
||||
var result struct {
|
||||
Token string `json:"access_token"`
|
||||
Username string `json:"username"`
|
||||
Expires int `json:"expires_in"`
|
||||
}
|
||||
if err := json.Unmarshal(exchange.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -135,6 +158,9 @@ func TestCLIAuthOIDCFlow(t *testing.T) {
|
||||
if !strings.HasPrefix(result.Token, "pw_api_") || result.Username != "admin" || result.Token == browser {
|
||||
t.Fatal("invalid delegated credential")
|
||||
}
|
||||
if result.Expires > expectedSeconds || result.Expires < expectedSeconds-10 {
|
||||
t.Fatalf("CLI lifetime %d, want approximately %d", result.Expires, expectedSeconds)
|
||||
}
|
||||
if _, err := s.store.PrincipalForSession(domain, result.Token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,10 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type oidcChallenge struct{ Verifier, Nonce, Return, Issuer, ClientID, BrowserHash, CLIRequest string }
|
||||
type oidcChallenge struct {
|
||||
Verifier, Nonce, Return, Issuer, ClientID, BrowserHash, CLIRequest string
|
||||
Remember bool
|
||||
}
|
||||
|
||||
func logOIDCFailure(stage, domainUUID, issuer string, err error) {
|
||||
host := "invalid"
|
||||
@@ -57,6 +60,7 @@ func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
|
||||
defer cancel()
|
||||
cliRequest := r.URL.Query().Get("cli")
|
||||
remember := r.URL.Query().Get("remember") == "1"
|
||||
returnPath := safeReturnPath(r.URL.Query().Get("return"))
|
||||
if cliRequest != "" {
|
||||
if !cliSecureTransport(r) || !cliProofPattern.MatchString(cliRequest) {
|
||||
@@ -68,6 +72,12 @@ func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
returnPath = cliVerifyPath(cliRequest)
|
||||
grant, err := s.store.CLIAuthRequest(ctx, domainUUID, cliOrigin(r), cliRequest)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid CLI request", 400)
|
||||
return
|
||||
}
|
||||
remember = grant.Remember
|
||||
}
|
||||
metadata, err := fetchOIDCMetadata(ctx, config.Issuer)
|
||||
if err != nil {
|
||||
@@ -77,7 +87,7 @@ func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
verifier, nonce, browser := randomURLToken(32), randomURLToken(24), randomURLToken(32)
|
||||
browserDigest := sha256.Sum256([]byte(browser))
|
||||
state, err := s.store.CreateAuthChallenge(domainUUID, "", "oidc", oidcChallenge{Verifier: verifier, Nonce: nonce, Return: returnPath, Issuer: config.Issuer, ClientID: config.ClientID, BrowserHash: base64.RawURLEncoding.EncodeToString(browserDigest[:]), CLIRequest: cliRequest}, 5*time.Minute)
|
||||
state, err := s.store.CreateAuthChallenge(domainUUID, "", "oidc", oidcChallenge{Verifier: verifier, Nonce: nonce, Return: returnPath, Issuer: config.Issuer, ClientID: config.ClientID, BrowserHash: base64.RawURLEncoding.EncodeToString(browserDigest[:]), CLIRequest: cliRequest, Remember: remember}, 5*time.Minute)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
@@ -205,7 +215,7 @@ func (s *Server) completeOIDC(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "No local account matches the configured OIDC identity field", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
token, err := s.store.CreateBrowserAuthSession(domainUUID, principal.UUID, 0)
|
||||
token, lifetime, err := s.store.CreateLoginSession(domainUUID, principal.UUID, 0, true, challenge.Remember)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
@@ -217,7 +227,7 @@ func (s *Server) completeOIDC(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
s.setAuthCookie(w, r, token)
|
||||
s.setAuthCookieForSeconds(w, r, token, int(lifetime.Seconds()))
|
||||
http.Redirect(w, r, challenge.Return, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -244,7 +254,7 @@ func (s *Server) requestMagicLink(w http.ResponseWriter, r *http.Request) {
|
||||
if principalErr == nil {
|
||||
select {
|
||||
case s.smtpSlots <- struct{}{}:
|
||||
token, err := s.store.CreateAuthChallenge(domainUUID, principal.UUID, "magic-link", magicLinkChallenge{Return: safeReturnPath(r.FormValue("return")), Email: principal.Email}, 15*time.Minute)
|
||||
token, err := s.store.CreateAuthChallenge(domainUUID, principal.UUID, "magic-link", magicLinkChallenge{Return: safeReturnPath(r.FormValue("return")), Email: principal.Email, Remember: r.PostForm.Get("remember") == "1"}, 15*time.Minute)
|
||||
if err != nil {
|
||||
<-s.smtpSlots
|
||||
break
|
||||
@@ -282,12 +292,12 @@ func (s *Server) verifyMagicLink(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "This sign-in link is invalid or expired", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
token, err := s.store.CreateBrowserAuthSession(domainUUID, principalUUID, 0)
|
||||
token, lifetime, err := s.store.CreateLoginSession(domainUUID, principalUUID, 0, true, payload.Remember)
|
||||
if err != nil {
|
||||
http.Error(w, "This sign-in link is invalid or expired", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
s.setAuthCookie(w, r, token)
|
||||
s.setAuthCookieForSeconds(w, r, token, int(lifetime.Seconds()))
|
||||
http.Redirect(w, r, safeReturnPath(payload.Return), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -306,6 +316,8 @@ func (s *Server) renderAuthPage(w http.ResponseWriter, r *http.Request, data map
|
||||
data["LDAPEnabled"] = config.Enabled
|
||||
}
|
||||
data["Locale"] = s.getLocale(domainUUID)
|
||||
data["TrustedSessionDays"] = s.store.TrustedSessionDays(domainUUID)
|
||||
data["RememberRequested"] = r.PostForm.Get("remember") == "1"
|
||||
transparency := s.homeGlassTransparency(domainUUID)
|
||||
data["HomeGlassTransparency"] = transparency
|
||||
data["HomeGlassOpacity"] = 100 - transparency
|
||||
|
||||
@@ -62,7 +62,11 @@ func requestIsHTTPS(r *http.Request) bool {
|
||||
}
|
||||
|
||||
func (s *Server) setAuthCookie(w http.ResponseWriter, r *http.Request, token string) {
|
||||
http.SetCookie(w, &http.Cookie{Name: authCookieName, Value: token, Path: "/", HttpOnly: true, Secure: requestIsHTTPS(r), SameSite: http.SameSiteLaxMode, MaxAge: s.store.AuthSessionLifetimeMinutes(s.domainUUIDForRequest(r)) * 60})
|
||||
s.setAuthCookieForSeconds(w, r, token, s.store.AuthSessionLifetimeMinutes(s.domainUUIDForRequest(r))*60)
|
||||
}
|
||||
|
||||
func (s *Server) setAuthCookieForSeconds(w http.ResponseWriter, r *http.Request, token string, seconds int) {
|
||||
http.SetCookie(w, &http.Cookie{Name: authCookieName, Value: token, Path: "/", HttpOnly: true, Secure: requestIsHTTPS(r), SameSite: http.SameSiteLaxMode, MaxAge: seconds})
|
||||
}
|
||||
|
||||
func (s *Server) authTokenFromRequest(r *http.Request) string {
|
||||
@@ -160,6 +164,7 @@ func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
var principal *store.Principal
|
||||
mfaLevel := 0
|
||||
remember := r.PostForm.Get("remember") == "1"
|
||||
if action == "setup" && setup && s.validBootstrapToken(domainUUID, r.FormValue("bootstrap_token")) {
|
||||
principal, err = s.store.BootstrapOwner(domainUUID, r.FormValue("username"), r.FormValue("password"), r.FormValue("display_name"), r.FormValue("email"))
|
||||
if err == nil {
|
||||
@@ -171,7 +176,7 @@ func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
||||
} else if action == "login" && !setup {
|
||||
principal, err = s.store.AuthenticatePassword(r.FormValue("username"), r.FormValue("password"))
|
||||
if err == nil && s.store.HasTOTP(principal.UUID) {
|
||||
challenge, challengeErr := s.store.CreateTOTPLoginChallenge(domainUUID, principal.UUID)
|
||||
challenge, challengeErr := s.store.CreateTOTPLoginChallengeForLogin(domainUUID, principal.UUID, remember)
|
||||
if challengeErr != nil {
|
||||
err = challengeErr
|
||||
} else if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
||||
@@ -191,7 +196,7 @@ func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
var principalUUID string
|
||||
principalUUID, err = s.store.CompleteTOTPLoginChallenge(domainUUID, challenge, r.FormValue("code"))
|
||||
principalUUID, remember, err = s.store.CompleteTOTPLoginChallengeForLogin(domainUUID, challenge, r.FormValue("code"))
|
||||
if err == nil {
|
||||
principal = &store.Principal{UUID: principalUUID}
|
||||
mfaLevel = 1
|
||||
@@ -201,18 +206,14 @@ func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
||||
err = store.ErrAccessDenied
|
||||
}
|
||||
if err == nil {
|
||||
var token string
|
||||
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
||||
token, err = s.store.CreateAuthSessionWithMFA(domainUUID, principal.UUID, mfaLevel)
|
||||
} else {
|
||||
token, err = s.store.CreateBrowserAuthSession(domainUUID, principal.UUID, mfaLevel)
|
||||
}
|
||||
token, lifetime, issueErr := s.store.CreateLoginSession(domainUUID, principal.UUID, mfaLevel, !strings.Contains(r.Header.Get("Accept"), "application/json"), remember)
|
||||
err = issueErr
|
||||
if err == nil {
|
||||
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
||||
writeEventJSON(w, http.StatusOK, map[string]any{"access_token": token, "token_type": "Bearer", "expires_in": s.store.AuthSessionLifetimeMinutes(domainUUID) * 60})
|
||||
writeEventJSON(w, http.StatusOK, map[string]any{"access_token": token, "token_type": "Bearer", "expires_in": int(lifetime.Seconds())})
|
||||
return
|
||||
}
|
||||
s.setAuthCookie(w, r, token)
|
||||
s.setAuthCookieForSeconds(w, r, token, int(lifetime.Seconds()))
|
||||
http.Redirect(w, r, safeReturnPath(r.FormValue("return")), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -221,7 +221,7 @@ func (s *Server) handleLDAPLogin(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if s.store.HasTOTP(principal.UUID) {
|
||||
challenge, challengeErr := s.store.CreateTOTPLoginChallenge(domainUUID, principal.UUID)
|
||||
challenge, challengeErr := s.store.CreateTOTPLoginChallengeForLogin(domainUUID, principal.UUID, r.PostForm.Get("remember") == "1")
|
||||
if challengeErr != nil {
|
||||
http.Error(w, "authentication unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
@@ -234,20 +234,15 @@ func (s *Server) handleLDAPLogin(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderAuthPage(w, r, map[string]any{"MFA": true, "Return": returnPath})
|
||||
return
|
||||
}
|
||||
var token string
|
||||
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
||||
token, err = s.store.CreateAuthSession(domainUUID, principal.UUID)
|
||||
} else {
|
||||
token, err = s.store.CreateBrowserAuthSession(domainUUID, principal.UUID, 0)
|
||||
}
|
||||
token, lifetime, err := s.store.CreateLoginSession(domainUUID, principal.UUID, 0, !strings.Contains(r.Header.Get("Accept"), "application/json"), r.PostForm.Get("remember") == "1")
|
||||
if err != nil {
|
||||
http.Error(w, "authentication unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
||||
writeEventJSON(w, http.StatusOK, map[string]any{"access_token": token, "token_type": "Bearer", "expires_in": s.store.AuthSessionLifetimeMinutes(domainUUID) * 60})
|
||||
writeEventJSON(w, http.StatusOK, map[string]any{"access_token": token, "token_type": "Bearer", "expires_in": int(lifetime.Seconds())})
|
||||
return
|
||||
}
|
||||
s.setAuthCookie(w, r, token)
|
||||
s.setAuthCookieForSeconds(w, r, token, int(lifetime.Seconds()))
|
||||
http.Redirect(w, r, returnPath, http.StatusSeeOther)
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSessionPolicyAdminUIAndCookie(t *testing.T) {
|
||||
@@ -48,3 +49,99 @@ func TestSessionPolicyAdminUIAndCookie(t *testing.T) {
|
||||
t.Fatalf("cookie policy %#v", cookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrustedSessionPolicyAndRevocation(t *testing.T) {
|
||||
s, admin, domain := configFixture(t)
|
||||
p := s.mustCLIPrincipal(t, domain, admin)
|
||||
for _, days := range []string{"30", "7", "0"} {
|
||||
form := url.Values{"action": {"save_trusted_session_policy"}, "trusted_session_days": {days}}
|
||||
w := configRequest(s, admin, "POST", "/-/sys/config/auth", form)
|
||||
if w.Code != 303 {
|
||||
t.Fatalf("policy %s: %d %s", days, w.Code, w.Body.String())
|
||||
}
|
||||
want := 24 * time.Hour
|
||||
if days == "30" {
|
||||
want *= 30
|
||||
}
|
||||
if days == "7" {
|
||||
want *= 7
|
||||
}
|
||||
for _, browser := range []bool{false, true} {
|
||||
token, lifetime, err := s.store.CreateLoginSession(domain, p, 0, browser, true)
|
||||
if err != nil || lifetime != want {
|
||||
t.Fatalf("duration %v %v", lifetime, err)
|
||||
}
|
||||
if _, err = s.store.PrincipalForSession(domain, token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.store.RevokeAuthSession(token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.store.PrincipalForSession(domain, token); err == nil {
|
||||
t.Fatal("revoked trusted session accepted")
|
||||
}
|
||||
}
|
||||
w = httptest.NewRecorder()
|
||||
s.handleAuth(w, httptest.NewRequest("GET", "https://localhost/_/auth/login", nil))
|
||||
if strings.Contains(w.Body.String(), `id="auth-remember"`) != (days != "0") {
|
||||
t.Fatal("login choice does not reflect policy")
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"", "-1", "31", "abc"} {
|
||||
w := configRequest(s, admin, "POST", "/-/sys/config/auth", url.Values{"action": {"save_trusted_session_policy"}, "trusted_session_days": {bad}})
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("invalid policy %q accepted: %d", bad, w.Code)
|
||||
}
|
||||
}
|
||||
user, err := s.store.CreatePasswordAccount(domain, "trusted-reader", "a long test password", "Reader", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.store.SetConfigInDomain(domain, "auth_trusted_session_days", "30"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, _, err := s.store.CreateLoginSession(domain, user.UUID, 0, false, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := configRequest(s, token, "POST", "/-/sys/config/auth", url.Values{"action": {"save_trusted_session_policy"}, "trusted_session_days": {"7"}})
|
||||
if w.Code != 403 {
|
||||
t.Fatalf("reader changed trusted policy: %d", w.Code)
|
||||
}
|
||||
if err = s.store.SetPrincipalState(domain, user.UUID, "suspended"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.store.PrincipalForSession(domain, token); err == nil {
|
||||
t.Fatal("suspended trusted session accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrustedSessionExpiryIsFixed(t *testing.T) {
|
||||
s, admin, domain := configFixture(t)
|
||||
p := s.mustCLIPrincipal(t, domain, admin)
|
||||
token, lifetime, err := s.store.CreateLoginSession(domain, p, 0, false, true)
|
||||
if err != nil || lifetime != 30*24*time.Hour {
|
||||
t.Fatalf("trusted default: %v %v", lifetime, err)
|
||||
}
|
||||
var id string
|
||||
var expiry int64
|
||||
if err = s.store.DB.QueryRow(`SELECT uuid,expires_at_ms FROM auth_sessions ORDER BY rowid DESC LIMIT 1`).Scan(&id, &expiry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.store.SetConfigInDomain(domain, "auth_trusted_session_days", "0"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.store.PrincipalForSession(domain, token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var after int64
|
||||
if err = s.store.DB.QueryRow(`SELECT expires_at_ms FROM auth_sessions WHERE uuid=?`, id).Scan(&after); err != nil || after != expiry {
|
||||
t.Fatalf("policy/read changed expiry: %d %d %v", expiry, after, err)
|
||||
}
|
||||
if _, err = s.store.DB.Exec(`UPDATE auth_sessions SET expires_at_ms=? WHERE uuid=?`, time.Now().Add(-time.Second).UnixMilli(), id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.store.PrincipalForSession(domain, token); err == nil {
|
||||
t.Fatal("expired trusted session accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package server
|
||||
|
||||
func init() {
|
||||
for lang, entries := range map[string]map[string]string{
|
||||
"en": {"auth.remember": "Keep me signed in on this trusted device", "auth.days": "days", "auth.remember_cli": "Keep this CLI signed in for up to", "auth.trusted_days": "Trusted device session (days; 0 disables)"},
|
||||
"ja": {"auth.remember": "信頼できる端末でログインを維持する", "auth.days": "日間", "auth.remember_cli": "CLIのログイン継続期間(最大)", "auth.trusted_days": "信頼できる端末の有効期間(日・0で無効)"},
|
||||
} {
|
||||
for key, value := range entries {
|
||||
translations[lang][key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestBrowserUploadQueueChromium(t *testing.T) {
|
||||
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
|
||||
t.Skip("opt-in Chromium")
|
||||
}
|
||||
for _, width := range []string{"1280", "390"} {
|
||||
t.Run(width, func(t *testing.T) { testBrowserUploadQueueChromium(t, width) })
|
||||
}
|
||||
}
|
||||
|
||||
func testBrowserUploadQueueChromium(t *testing.T, width string) {
|
||||
s, token, domain := configFixture(t)
|
||||
s.mux.HandleFunc("/v/browser/", s.handleBrowser)
|
||||
s.mux.HandleFunc("/v/upload", s.handleUpload)
|
||||
object, err := s.store.CreatePageAtPathInDomain(domain, "/drop/existing.txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.store.SaveRevisionContent(object, []byte("original"), "", "und", "text/plain", "existing.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.store.CreatePageAtPathInDomain(domain, "/drop/sub/seed"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script, err := os.ReadFile("internal/server/testdata/browser-upload.js")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var active, peak atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Host = "localhost"
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
if r.Method == "POST" && r.URL.Path == "/v/upload" {
|
||||
n := active.Add(1)
|
||||
defer active.Add(-1)
|
||||
if n > peak.Load() {
|
||||
peak.Store(n)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
if r.URL.Path == "/v/browser/drop" && r.URL.Query().Has("fixture") {
|
||||
rec := httptest.NewRecorder()
|
||||
s.withAuthorization(s.mux).ServeHTTP(rec, r)
|
||||
for key, values := range rec.Header() {
|
||||
w.Header()[key] = values
|
||||
}
|
||||
w.WriteHeader(rec.Code)
|
||||
w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", "<script>"+string(script)+"</script></body>", 1)))
|
||||
return
|
||||
}
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", server.URL+"/v/browser/drop?fixture=1", t.TempDir(), "/tmp/pageswiki-browser-upload-"+width+".png", width, "850").CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("browser: %v %s", err, out)
|
||||
}
|
||||
if peak.Load() != 1 {
|
||||
t.Fatalf("parallel uploads: %d", peak.Load())
|
||||
}
|
||||
for _, path := range []string{"/drop/日本語 #1.txt", "/drop/sub/nested.txt"} {
|
||||
if _, err = s.store.ResolvePathInDomain(domain, path); err != nil {
|
||||
t.Fatal(path, err)
|
||||
}
|
||||
}
|
||||
if _, err = s.store.ResolvePathInDomain(domain, "/drop/cancel.txt"); err == nil {
|
||||
t.Fatal("cancelled file uploaded")
|
||||
}
|
||||
revs, err := s.store.ListRevisions(object)
|
||||
if err != nil || len(revs) != 1 {
|
||||
t.Fatal("existing file overwritten")
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ func (s *Server) transpileMarkdownFromPath(r *http.Request, path string, mode ma
|
||||
|
||||
html := latest.Body
|
||||
if mode == markdownProjection {
|
||||
html = s.expandMacrosForRequest(r, html, path, s.domainUUIDForRequest(r))
|
||||
html = s.safeHTMLProjection(r, html, path, true)
|
||||
} else {
|
||||
return grammaratur.HTMLToMarkdownAuthoring(html)
|
||||
}
|
||||
|
||||
@@ -1078,49 +1078,50 @@ func (s *Server) handleConfig(
|
||||
s.getSystemNavItems(s.domainUUIDForRequest(r)),
|
||||
NavContext{},
|
||||
),
|
||||
"HomePath": homePath,
|
||||
"HomeWallpaperPath": homeWallpaperPath,
|
||||
"HomeWallpaperOpacity": homeWallpaperOpacity,
|
||||
"HomeGlassTransparency": s.homeGlassTransparency(domainUUID),
|
||||
"HomePalette": s.homePalette(domainUUID),
|
||||
"HomeLayout": s.homeLayout(s.domainUUIDForRequest(r)),
|
||||
"HomeBookmarks": s.homeBookmarksText(s.domainUUIDForRequest(r)),
|
||||
"VirtualFolderPages": s.getVirtualFolderPages(s.domainUUIDForRequest(r)),
|
||||
"WikiName": wikiName,
|
||||
"Locale": s.getLocale(s.domainUUIDForRequest(r)),
|
||||
"Timezone": s.getTimezoneName(s.domainUUIDForRequest(r)),
|
||||
"Theme": s.getTheme(s.domainUUIDForRequest(r)),
|
||||
"ThemeOptions": themeOptions(),
|
||||
"EditorKeymap": s.getEditorKeymap(s.domainUUIDForRequest(r)),
|
||||
"EditorFormat": s.getEditorFormat(s.domainUUIDForRequest(r)),
|
||||
"EditorPreviewDefault": s.getEditorPreviewDefault(s.domainUUIDForRequest(r)),
|
||||
"EditorSyntax": s.getEditorSyntaxHighlight(s.domainUUIDForRequest(r)),
|
||||
"EditorAutocomplete": s.getEditorAutocomplete(s.domainUUIDForRequest(r)),
|
||||
"ZombieGraceHours": zombieGraceHours,
|
||||
"Objects": recent,
|
||||
"ZombieObjects": zombies,
|
||||
"Domains": domains,
|
||||
"DomainEntries": domainEntries,
|
||||
"PeriodicalProjections": projections,
|
||||
"PeriodicalKinds": []string{"diary", "blog"},
|
||||
"CampusLegacyPeers": legacyPeers,
|
||||
"Campuses": campuses,
|
||||
"CampusManaged": campusManaged,
|
||||
"CampusOnline": campusOnline,
|
||||
"FederationInstances": federationInstances,
|
||||
"CampusTokens": campusTokens,
|
||||
"AuthPrincipals": authPrincipals,
|
||||
"AuthSessions": authSessions,
|
||||
"AuthSessionMinutes": s.store.AuthSessionLifetimeMinutes(s.domainUUIDForRequest(r)),
|
||||
"OIDCConfig": oidcConfig,
|
||||
"SMTPConfig": smtpConfig,
|
||||
"LDAPConfig": ldapConfig,
|
||||
"LDAPTest": r.URL.Query().Get("ldap_test"),
|
||||
"ObjectsCampusUUID": selectedCampusUUID,
|
||||
"ObjectsDomainUUID": selectedDomain.UUID,
|
||||
"ObjectsDomainHost": objectsDomainHost,
|
||||
"HomeNavItemsConfig": s.getHomeNavItems(s.domainUUIDForRequest(r)),
|
||||
"SystemNavItemsConfig": s.getSystemNavItems(s.domainUUIDForRequest(r)),
|
||||
"HomePath": homePath,
|
||||
"HomeWallpaperPath": homeWallpaperPath,
|
||||
"HomeWallpaperOpacity": homeWallpaperOpacity,
|
||||
"HomeGlassTransparency": s.homeGlassTransparency(domainUUID),
|
||||
"HomePalette": s.homePalette(domainUUID),
|
||||
"HomeLayout": s.homeLayout(s.domainUUIDForRequest(r)),
|
||||
"HomeBookmarks": s.homeBookmarksText(s.domainUUIDForRequest(r)),
|
||||
"VirtualFolderPages": s.getVirtualFolderPages(s.domainUUIDForRequest(r)),
|
||||
"WikiName": wikiName,
|
||||
"Locale": s.getLocale(s.domainUUIDForRequest(r)),
|
||||
"Timezone": s.getTimezoneName(s.domainUUIDForRequest(r)),
|
||||
"Theme": s.getTheme(s.domainUUIDForRequest(r)),
|
||||
"ThemeOptions": themeOptions(),
|
||||
"EditorKeymap": s.getEditorKeymap(s.domainUUIDForRequest(r)),
|
||||
"EditorFormat": s.getEditorFormat(s.domainUUIDForRequest(r)),
|
||||
"EditorPreviewDefault": s.getEditorPreviewDefault(s.domainUUIDForRequest(r)),
|
||||
"EditorSyntax": s.getEditorSyntaxHighlight(s.domainUUIDForRequest(r)),
|
||||
"EditorAutocomplete": s.getEditorAutocomplete(s.domainUUIDForRequest(r)),
|
||||
"ZombieGraceHours": zombieGraceHours,
|
||||
"Objects": recent,
|
||||
"ZombieObjects": zombies,
|
||||
"Domains": domains,
|
||||
"DomainEntries": domainEntries,
|
||||
"PeriodicalProjections": projections,
|
||||
"PeriodicalKinds": []string{"diary", "blog"},
|
||||
"CampusLegacyPeers": legacyPeers,
|
||||
"Campuses": campuses,
|
||||
"CampusManaged": campusManaged,
|
||||
"CampusOnline": campusOnline,
|
||||
"FederationInstances": federationInstances,
|
||||
"CampusTokens": campusTokens,
|
||||
"AuthPrincipals": authPrincipals,
|
||||
"AuthSessions": authSessions,
|
||||
"AuthSessionMinutes": s.store.AuthSessionLifetimeMinutes(s.domainUUIDForRequest(r)),
|
||||
"AuthTrustedSessionDays": s.store.TrustedSessionDays(s.domainUUIDForRequest(r)),
|
||||
"OIDCConfig": oidcConfig,
|
||||
"SMTPConfig": smtpConfig,
|
||||
"LDAPConfig": ldapConfig,
|
||||
"LDAPTest": r.URL.Query().Get("ldap_test"),
|
||||
"ObjectsCampusUUID": selectedCampusUUID,
|
||||
"ObjectsDomainUUID": selectedDomain.UUID,
|
||||
"ObjectsDomainHost": objectsDomainHost,
|
||||
"HomeNavItemsConfig": s.getHomeNavItems(s.domainUUIDForRequest(r)),
|
||||
"SystemNavItemsConfig": s.getSystemNavItems(s.domainUUIDForRequest(r)),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"errors"
|
||||
"html"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Projection only: no network fetch, shared rendered cache or write-back.
|
||||
const maxCSVMacroBytes = 256 << 10
|
||||
|
||||
var csvMacroRE = regexp.MustCompile(`^\{\{csv:(?:"([^"]+)"|([^\s}]+))(.*?)\}\}$`)
|
||||
var csvRangeRE = regexp.MustCompile(`^([A-Z]{1,2})([1-9][0-9]{0,3}):([A-Z]{1,2})([1-9][0-9]{0,3})$`)
|
||||
|
||||
type csvMacroOptions struct {
|
||||
Path, Revision string
|
||||
Row, EndRow, Column, EndColumn int
|
||||
Header bool
|
||||
}
|
||||
|
||||
func parseCSVMacro(raw string) (csvMacroOptions, error) {
|
||||
o := csvMacroOptions{Row: 1, EndRow: 200, Column: 1, EndColumn: 32, Header: true}
|
||||
m := csvMacroRE.FindStringSubmatch(raw)
|
||||
bad := errors.New("invalid CSV macro")
|
||||
if m == nil {
|
||||
return o, bad
|
||||
}
|
||||
o.Path = m[1]
|
||||
if o.Path == "" {
|
||||
o.Path = m[2]
|
||||
}
|
||||
if !strings.HasPrefix(o.Path, "/") || strings.HasPrefix(o.Path, "//") || path.Clean(o.Path) != o.Path || strings.ContainsAny(o.Path, "\\\x00\r\n") || len(o.Path) > 2048 {
|
||||
return o, bad
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, field := range strings.Fields(m[3]) {
|
||||
key, value, ok := strings.Cut(field, "=")
|
||||
if !ok || seen[key] {
|
||||
return o, bad
|
||||
}
|
||||
seen[key] = true
|
||||
switch key {
|
||||
case "header":
|
||||
if value != "true" && value != "false" {
|
||||
return o, bad
|
||||
}
|
||||
o.Header = value == "true"
|
||||
case "rev":
|
||||
if _, err := uuid.Parse(value); len(value) != 36 || err != nil {
|
||||
return o, bad
|
||||
}
|
||||
o.Revision = value
|
||||
case "range":
|
||||
parts := csvRangeRE.FindStringSubmatch(strings.ToUpper(value))
|
||||
if parts == nil {
|
||||
return o, bad
|
||||
}
|
||||
col := func(s string) int {
|
||||
n := 0
|
||||
for _, c := range s {
|
||||
n = n*26 + int(c-'A') + 1
|
||||
}
|
||||
return n
|
||||
}
|
||||
o.Column, o.EndColumn = col(parts[1]), col(parts[3])
|
||||
o.Row, _ = strconv.Atoi(parts[2])
|
||||
o.EndRow, _ = strconv.Atoi(parts[4])
|
||||
if o.Column > o.EndColumn || o.EndColumn > 100 || o.EndColumn-o.Column >= 32 || o.Row > o.EndRow || o.EndRow > 2000 || o.EndRow-o.Row >= 200 {
|
||||
return o, bad
|
||||
}
|
||||
default:
|
||||
return o, bad
|
||||
}
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
func csvMacroTable(body []byte, o csvMacroOptions) (string, error) {
|
||||
if len(body) > maxCSVMacroBytes || !utf8.Valid(body) || strings.IndexByte(string(body), 0) >= 0 {
|
||||
return "", errors.New("invalid CSV input")
|
||||
}
|
||||
reader := csv.NewReader(strings.NewReader(strings.TrimPrefix(string(body), "\ufeff")))
|
||||
reader.FieldsPerRecord = -1
|
||||
var out strings.Builder
|
||||
out.WriteString(`<div class="csv-projection table-scroll"><table><caption><a href="` + html.EscapeString((&url.URL{Path: o.Path}).EscapedPath()) + `" title="Revision ` + html.EscapeString(o.Revision) + `">` + html.EscapeString(path.Base(o.Path)) + `</a></caption><tbody>`)
|
||||
for row := 1; row <= o.EndRow; row++ {
|
||||
record, err := reader.Read()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(record) > 100 {
|
||||
return "", errors.New("too many CSV columns")
|
||||
}
|
||||
if row < o.Row {
|
||||
continue
|
||||
}
|
||||
out.WriteString("<tr>")
|
||||
cell := "td"
|
||||
if o.Header && row == o.Row {
|
||||
cell = "th"
|
||||
}
|
||||
for col := o.Column; col <= o.EndColumn && col <= len(record); col++ {
|
||||
if len(record[col-1]) > 16<<10 {
|
||||
return "", errors.New("CSV cell too large")
|
||||
}
|
||||
// Never expand macros, formulas or markup from CSV cells.
|
||||
out.WriteString("<" + cell + ">" + html.EscapeString(record[col-1]) + "</" + cell + ">")
|
||||
}
|
||||
out.WriteString("</tr>")
|
||||
}
|
||||
out.WriteString("</tbody></table></div>")
|
||||
return out.String(), nil
|
||||
}
|
||||
|
||||
func (s *Server) expandCSVMacro(r *http.Request, macro string) string {
|
||||
fallback := `<span class="projection-warning">` + html.EscapeString(translate(s.getLocale(s.domainUUIDForRequest(r)), "viewer.csv_unavailable")) + `</span>`
|
||||
o, err := parseCSVMacro(macro)
|
||||
if err != nil || r.Context().Err() != nil || s.store == nil || isAnonymousProjection(r) || !s.pathReadFilter(r)(o.Path) {
|
||||
return fallback
|
||||
}
|
||||
domain := s.domainUUIDForRequest(r)
|
||||
object, err := s.store.ResolvePathInDomainContext(r.Context(), domain, o.Path)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
rev, err := s.store.GetLatestRevisionMetadataForLanguagesContext(r.Context(), object, s.revisionLanguageCandidates(r))
|
||||
if o.Revision != "" {
|
||||
rev, err = s.store.GetRevisionMetadataContext(r.Context(), o.Revision)
|
||||
}
|
||||
if err != nil || rev == nil || rev.UUID == "" || rev.ObjectUUID != object {
|
||||
return fallback
|
||||
}
|
||||
media := strings.ToLower(strings.TrimSpace(strings.Split(rev.ContentType, ";")[0]))
|
||||
if media != "text/csv" && media != "application/csv" {
|
||||
return fallback
|
||||
}
|
||||
size, err := s.store.DocumentSizeContext(r.Context(), rev.DocumentHash)
|
||||
if err != nil || size > maxCSVMacroBytes {
|
||||
return fallback
|
||||
}
|
||||
window, err := s.store.ReadDocumentWindowContext(r.Context(), rev.DocumentHash, 0, maxCSVMacroBytes)
|
||||
if err != nil || window.Truncated {
|
||||
return fallback
|
||||
}
|
||||
o.Revision = rev.UUID
|
||||
table, err := csvMacroTable(window.Data, o)
|
||||
if err != nil || r.Context().Err() != nil {
|
||||
return fallback
|
||||
}
|
||||
return table
|
||||
}
|
||||
|
||||
func init() {
|
||||
translations["en"]["viewer.csv_unavailable"] = "CSV unavailable (access, format or size limit)."
|
||||
translations["ja"]["viewer.csv_unavailable"] = "CSVを表示できません(権限・形式・サイズ制限)。"
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"pageswiki/internal/grammaratur"
|
||||
)
|
||||
|
||||
func TestCSVMacroParsingAndBounds(t *testing.T) {
|
||||
for _, raw := range []string{`{{csv:/data/a.csv}}`, `{{csv:"/data/日本語 table.csv" range=B2:D4 header=false}}`} {
|
||||
if _, err := parseCSVMacro(raw); err != nil {
|
||||
t.Fatal(raw, err)
|
||||
}
|
||||
}
|
||||
for _, raw := range []string{`{{csv:https://example.org/a.csv}}`, `{{csv://evil/a.csv}}`, `{{csv:/a/../secret}}`, `{{csv:/a range=A1:C201}}`, `{{csv:/a range=A1:AG2}}`, `{{csv:/a range=A2001:B2002}}`, `{{csv:/a range=D2:A1}}`, `{{csv:/a header=yes}}`, `{{csv:/a header=true header=false}}`, `{{csv:/a unsupported=1}}`, `{{csv:/a rev=bad}}`} {
|
||||
if _, err := parseCSVMacro(raw); err == nil {
|
||||
t.Fatal("accepted", raw)
|
||||
}
|
||||
}
|
||||
o, _ := parseCSVMacro(`{{csv:/data/a.csv range=A1:C3}}`)
|
||||
body := "\ufeffname,description,formula\r\n日本語,\"a,b\r\nnext\",=1+1\r\n<script>,{{children:/private}},end\r\n"
|
||||
got, err := csvMacroTable([]byte(body), o)
|
||||
if err != nil || !strings.Contains(got, "<th>name</th>") || !strings.Contains(got, "a,b\nnext") || !strings.Contains(got, "<script>") || !strings.Contains(got, "{{children:/private}}") {
|
||||
t.Fatalf("CSV: %s %v", got, err)
|
||||
}
|
||||
checkInertProjection(t, got)
|
||||
for _, bad := range [][]byte{[]byte("a,\"unterminated"), {0xff}, []byte("a,\x00"), []byte(strings.Repeat("x", maxCSVMacroBytes+1)), []byte(strings.Repeat("x", (16<<10)+1)), []byte(strings.Repeat("a,", 101))} {
|
||||
if _, err := csvMacroTable(bad, o); err == nil {
|
||||
t.Fatal("invalid/large CSV accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCSVMacroProjectionAuthorizationAndRevision(t *testing.T) {
|
||||
s, token, domain := configFixture(t)
|
||||
object, err := s.store.CreatePageAtPathInDomain(domain, "/data/report.csv")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := s.store.SaveRevisionContent(object, []byte("name,value\r\noriginal,1\r\n"), "", "und", "text/csv", "report.csv")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := httptest.NewRequest("GET", "http://localhost/guide", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
macro := `{{csv:/data/report.csv range=A1:B2}}`
|
||||
got := s.safeHTMLProjection(r, "<p>"+macro+"</p><code>"+macro+"</code>", "/guide", true)
|
||||
if strings.Count(got, `class="csv-projection table-scroll"`) != 1 || !strings.Contains(got, "original") || !strings.Contains(got, "<code>"+macro+"</code>") || !strings.Contains(got, first.UUID) {
|
||||
t.Fatal(got)
|
||||
}
|
||||
second, err := s.store.SaveRevisionContent(object, []byte("name,value\nupdated,2\n"), "", "und", "text/csv", "report.csv")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = s.safeHTMLProjection(r, macro, "/guide", true)
|
||||
if !strings.Contains(got, "updated") || !strings.Contains(got, second.UUID) || strings.Contains(got, "original") {
|
||||
t.Fatal("stale projection", got)
|
||||
}
|
||||
got = s.safeHTMLProjection(r, `{{csv:/data/report.csv rev=`+first.UUID+`}}`, "/guide", true)
|
||||
if !strings.Contains(got, "original") || strings.Contains(got, "updated") {
|
||||
t.Fatal("pinned revision", got)
|
||||
}
|
||||
other, err := s.store.CreatePageAtPathInDomain(domain, "/data/other.csv")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
foreign, err := s.store.SaveRevisionContent(other, []byte("SECRET_DIFFERENT_OBJECT"), "", "und", "text/csv", "other.csv")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = s.safeHTMLProjection(r, `{{csv:/data/report.csv rev=`+foreign.UUID+`}}`, "/guide", true)
|
||||
if strings.Contains(got, "SECRET") || strings.Contains(got, "<table") {
|
||||
t.Fatal("foreign revision leaked", got)
|
||||
}
|
||||
// A fresh request with no credentials must not reuse another reader's table.
|
||||
denied := httptest.NewRequest("GET", "http://localhost/guide", nil)
|
||||
got = s.safeHTMLProjection(denied, macro, "/guide", true)
|
||||
if strings.Contains(got, "updated") || strings.Contains(got, "<table") {
|
||||
t.Fatal("unauthorized table", got)
|
||||
}
|
||||
public := r.WithContext(context.WithValue(r.Context(), anonymousProjectionKey{}, true))
|
||||
if got = s.safeHTMLProjection(public, macro, "/guide", true); strings.Contains(got, "<table") {
|
||||
t.Fatal("anonymous CSV expanded", got)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(r.Context())
|
||||
cancel()
|
||||
if got = s.expandCSVMacro(r.WithContext(ctx), macro); strings.Contains(got, "<table") {
|
||||
t.Fatal("cancelled projection ran")
|
||||
}
|
||||
// Authoring must preserve the macro, never bake projected rows into HTML.
|
||||
source := "<p>" + macro + "</p>"
|
||||
md, err := grammaratur.HTMLToMarkdownAuthoring(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(grammaratur.MarkdownAuthoringHTML(md), macro) || strings.Contains(md, "updated") {
|
||||
t.Fatal("authoring expanded CSV", md)
|
||||
}
|
||||
// Four distinct CSV reads per projection, then leave authored syntax literal.
|
||||
input := strings.Repeat(macro, 2)
|
||||
for _, col := range []string{"A1:A2", "B1:B2", "A1:B1", "A2:B2"} {
|
||||
input += `{{csv:/data/report.csv range=` + col + `}}`
|
||||
}
|
||||
got = s.safeHTMLProjection(r, input, "/guide", true)
|
||||
if strings.Count(got, "<table>") != 5 || !strings.Contains(got, "{{csv:") {
|
||||
t.Fatal("CSV budget not enforced", got)
|
||||
}
|
||||
}
|
||||
@@ -10,16 +10,26 @@ import (
|
||||
const systemExtensionStateKey = "system_extension_states"
|
||||
|
||||
func (s *Server) systemExtensionEnabled(domainUUID, id string) bool {
|
||||
defaultEnabled := true
|
||||
for _, manifest := range systemext.Catalog() {
|
||||
if manifest.ID == id {
|
||||
defaultEnabled = manifest.Enabled
|
||||
break
|
||||
}
|
||||
}
|
||||
raw, err := s.store.GetConfigInDomain(domainUUID, systemExtensionStateKey)
|
||||
if err != nil || strings.TrimSpace(raw) == "" {
|
||||
return true
|
||||
return defaultEnabled
|
||||
}
|
||||
var states map[string]bool
|
||||
if json.Unmarshal([]byte(raw), &states) != nil {
|
||||
return true
|
||||
return defaultEnabled
|
||||
}
|
||||
enabled, ok := states[id]
|
||||
return !ok || enabled
|
||||
if !ok {
|
||||
return defaultEnabled
|
||||
}
|
||||
return enabled
|
||||
}
|
||||
|
||||
func (s *Server) setSystemExtensionEnabled(domainUUID, id string, enabled bool) error {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
@@ -16,7 +17,8 @@ func feedRoute(p string) bool { return p == "/v/feeds" || strings.HasPrefix(p, f
|
||||
func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
domain := s.domainUUIDForRequest(r)
|
||||
if !s.systemExtensionEnabled(domain, "organizer.feeds") {
|
||||
licenseDownload := strings.HasPrefix(r.URL.Path, geckoAPI+"distribution/v0.0.1/")
|
||||
if !licenseDownload && !s.systemExtensionEnabled(domain, "organizer.feeds") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
@@ -29,6 +31,10 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
|
||||
taskError(w, store.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, geckoAPI) {
|
||||
s.handleFeedBrowser(w, r, domain, actor, active)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/v/feeds" {
|
||||
if r.Method != "GET" && r.Method != "HEAD" {
|
||||
w.WriteHeader(405)
|
||||
@@ -38,22 +44,58 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
s.renderWithContext(w, r, "feeds.gohtml", map[string]any{"Title": "RSS", "FeedWritable": active})
|
||||
prefix := ""
|
||||
linkMode := "tab"
|
||||
if s.systemExtensionEnabled(domain, "organizer.tasks") {
|
||||
preferences, e := s.store.TaskPreferences(r.Context(), domain, actor)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
prefix = preferences.WikiPrefix
|
||||
linkMode = preferences.RSSLinkMode
|
||||
}
|
||||
if linkMode == "gecko" {
|
||||
if active && s.geckoAvailable(domain) {
|
||||
geckoIsolation(w)
|
||||
} else {
|
||||
linkMode = "tab"
|
||||
}
|
||||
}
|
||||
s.renderWithContext(w, r, "feeds.gohtml", map[string]any{"Title": "RSS", "FeedTimezone": s.getTimezoneName(domain), "FeedWritable": active, "FeedWikiPrefix": prefix, "FeedLinkMode": linkMode, "FeedShareX": s.systemExtensionEnabled(domain, "sharing.x")})
|
||||
return
|
||||
}
|
||||
key := strings.TrimPrefix(r.URL.Path, feedsAPI)
|
||||
if s.handleFeedAction(w, r, domain, actor, key) {
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(key, "opml/") {
|
||||
s.handleFeedOPML(w, r, domain, actor, key)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case key == "catalog" && r.Method == "GET":
|
||||
catalog, e := s.store.FeedCatalog(r.Context(), domain, actor, r.URL.Query().Get("source"))
|
||||
case key == "capture-preview" && r.Method == "POST":
|
||||
var input struct {
|
||||
Prefix string `json:"prefix"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
if !taskJSON(w, r, &input) {
|
||||
return
|
||||
}
|
||||
prefix, e := store.ExpandWikiPrefix(input.Prefix, input.Title, time.Now().In(s.getLocation(domain)))
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"subscriptions": catalog})
|
||||
writeEventJSON(w, 200, map[string]string{"prefix": prefix})
|
||||
return
|
||||
case key == "catalog" && r.Method == "GET":
|
||||
catalog, e := s.store.FeedCatalogSnapshot(r.Context(), domain, actor, r.URL.Query().Get("source"))
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, catalog)
|
||||
return
|
||||
case key == "note" && r.Method == "POST":
|
||||
var input struct {
|
||||
@@ -167,7 +209,7 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
items, e := s.store.FeedItems(r.Context(), domain, actor, q.Get("source"), q.Get("filter"), q.Get("q"), before, q.Get("key"), q.Get("feed"), q.Get("category"))
|
||||
items, e := s.store.FeedItems(r.Context(), domain, actor, q.Get("source"), q.Get("filter"), q.Get("q"), before, q.Get("key"), q.Get("feed"), q.Get("category"), q.Get("category_mode"))
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
@@ -211,6 +253,6 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
|
||||
func init() {
|
||||
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読取連携"
|
||||
translations["en"]["feeds.help"] = "Private local feeds and FreshRSS integration with optional read/star updates"
|
||||
translations["ja"]["feeds.help"] = "個人用の簡易RSSとFreshRSS連携(既読・star変更は任意)"
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func freshRSSItem(ctx context.Context, client *http.Client, base, auth, id string) (*store.FeedItem, error) {
|
||||
// FreshRSS uses POST for this read-only item lookup (not GET ?i=...).
|
||||
raw, _, _, e := feedRequest(ctx, client, "POST", base+"/reader/api/0/stream/items/contents", auth, url.Values{"i": {id}}, nil)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
items, e := parseFreshRSSItems(raw, base)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if len(items) != 1 || items[0].ID != id {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
return &items[0], nil
|
||||
}
|
||||
func feedActionMatches(a store.FeedAction, i *store.FeedItem) bool {
|
||||
if a.Field == "read" {
|
||||
return i.Read == a.Desired
|
||||
}
|
||||
return i.Starred == a.Desired
|
||||
}
|
||||
|
||||
func (s *Server) runFeedAction(ctx context.Context, client *http.Client, a store.FeedAction, source store.FeedSource) (status, code string, observed *store.FeedItem) {
|
||||
status = "failed"
|
||||
if a.Status == "checking" {
|
||||
status = "unknown"
|
||||
}
|
||||
fail := func(e error) (string, string, *store.FeedItem) {
|
||||
c := e.Error()
|
||||
switch c {
|
||||
case "network", "credentials", "remote_error", "limit", "invalid_feed":
|
||||
default:
|
||||
c = "invalid_feed"
|
||||
}
|
||||
return status, c, nil
|
||||
}
|
||||
if !validCalendarSourceURL(source.URL) {
|
||||
return fail(errFeedInvalid)
|
||||
}
|
||||
user, password, e := s.store.OpenFeedCredential(source)
|
||||
if e != nil {
|
||||
return fail(errors.New("credentials"))
|
||||
}
|
||||
auth, e := freshRSSLogin(ctx, client, source, user, password)
|
||||
if e != nil {
|
||||
return fail(e)
|
||||
}
|
||||
base := strings.TrimRight(source.URL, "/")
|
||||
item, e := freshRSSItem(ctx, client, base, auth, a.ID)
|
||||
if e != nil {
|
||||
return fail(e)
|
||||
}
|
||||
if feedActionMatches(a, item) {
|
||||
return "confirmed", "", item
|
||||
}
|
||||
if a.Status == "checking" {
|
||||
return "conflict", "conflict", item
|
||||
}
|
||||
raw, _, _, e := feedRequest(ctx, client, "GET", base+"/reader/api/0/token", auth, nil, nil)
|
||||
if e != nil {
|
||||
return fail(e)
|
||||
}
|
||||
token := strings.TrimSpace(string(raw))
|
||||
if token == "" || len(token) > 4096 || strings.ContainsAny(token, "\r\n") {
|
||||
return fail(errFeedInvalid)
|
||||
}
|
||||
if e = s.store.MarkFeedActionSending(ctx, a, source); e != nil {
|
||||
return fail(e)
|
||||
}
|
||||
// From this point every uncertain result is terminal until an explicit
|
||||
// read-only recheck. Neither the worker nor a repeated HTTP request resends.
|
||||
status = "unknown"
|
||||
field := "r"
|
||||
if a.Desired {
|
||||
field = "a"
|
||||
}
|
||||
form := url.Values{"i": {a.ID}, "T": {token}, field: {"user/-/state/com.google/" + a.Field}}
|
||||
raw, _, _, e = feedRequest(ctx, client, "POST", base+"/reader/api/0/edit-tag", auth, form, nil)
|
||||
if e != nil {
|
||||
return fail(e)
|
||||
}
|
||||
if strings.TrimSpace(string(raw)) != "OK" {
|
||||
return fail(errFeedInvalid)
|
||||
}
|
||||
item, e = freshRSSItem(ctx, client, base, auth, a.ID)
|
||||
if e != nil {
|
||||
return fail(e)
|
||||
}
|
||||
if !feedActionMatches(a, item) {
|
||||
return "conflict", "conflict", item
|
||||
}
|
||||
return "confirmed", "", item
|
||||
}
|
||||
func (s *Server) syncFeedActions(ctx context.Context, client *http.Client) error {
|
||||
actions, e := s.store.DueFeedActions(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
for _, a := range actions {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
if deadline, ok := ctx.Deadline(); ok && time.Until(deadline) < 9*time.Second {
|
||||
break
|
||||
}
|
||||
a, source, e := s.store.ClaimFeedAction(ctx, a)
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
child, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||
status, code, item := s.runFeedAction(child, client, a, source)
|
||||
cancel()
|
||||
e = s.store.CompleteFeedAction(ctx, a, source, status, code, item)
|
||||
if e != nil && !errors.Is(e, store.ErrAccessDenied) && !errors.Is(e, store.ErrTaskConflict) {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) handleFeedAction(w http.ResponseWriter, r *http.Request, domain, actor, key string) bool {
|
||||
if s.handleFeedHistory(w, r, domain, actor, key) {
|
||||
return true
|
||||
}
|
||||
switch {
|
||||
case key == "action" && r.Method == "GET":
|
||||
a, e := s.store.FeedAction(r.Context(), domain, actor, r.URL.Query().Get("source"), r.URL.Query().Get("id"))
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return true
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"action": a})
|
||||
return true
|
||||
case key == "remote-state" && r.Method == "POST":
|
||||
var input store.FeedAction
|
||||
if !taskJSON(w, r, &input) {
|
||||
return true
|
||||
}
|
||||
a, e := s.store.QueueFeedAction(r.Context(), domain, actor, input)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return true
|
||||
}
|
||||
writeEventJSON(w, 202, map[string]any{"action": a})
|
||||
return true
|
||||
case key == "action/check" && r.Method == "POST":
|
||||
var input struct {
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
if !taskJSON(w, r, &input) {
|
||||
return true
|
||||
}
|
||||
if e := s.store.RecheckFeedAction(r.Context(), domain, actor, input.RequestID); e != nil {
|
||||
taskError(w, e)
|
||||
return true
|
||||
}
|
||||
writeEventJSON(w, 202, map[string]bool{"ok": true})
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func feedActionFixture(t *testing.T) (*Server, string, string, string, store.FeedSource) {
|
||||
t.Helper()
|
||||
s, token, domain, actor, _ := feedFixture(t)
|
||||
ctx := context.Background()
|
||||
v := store.FeedSource{UUID: uuid.NewString(), Provider: "freshrss", Title: "Remote", URL: "https://example.org/api/greader.php", Enabled: true, WriteEnabled: true, Interval: 300}
|
||||
v.Credential, _ = s.store.SealFeedCredential(domain, actor, v.UUID, "reader", "secret")
|
||||
if _, e := s.store.SaveFeedSource(ctx, domain, actor, v); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
all, e := s.store.FeedSources(ctx, domain, actor)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, x := range all {
|
||||
if x.UUID == v.UUID {
|
||||
v = x
|
||||
}
|
||||
}
|
||||
c, e := s.store.ClaimFeed(ctx, v)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.store.CompleteFeed(ctx, c, []store.FeedItem{{ID: "one", Title: "Article", Starred: true}}, "", "", "", false); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return s, token, domain, actor, v
|
||||
}
|
||||
func newFeedAction(v store.FeedSource) store.FeedAction {
|
||||
return store.FeedAction{RequestID: uuid.NewString(), Source: v.UUID, ID: "one", Field: "read", Desired: true, SourceVersion: v.Version}
|
||||
}
|
||||
|
||||
type feedRemoteFake struct {
|
||||
id string
|
||||
read, star, timeout bool
|
||||
edits, lookups, requests int
|
||||
beforeEdit func()
|
||||
afterEdit func()
|
||||
}
|
||||
|
||||
func (f *feedRemoteFake) client(t *testing.T) *http.Client {
|
||||
return &http.Client{Transport: feedTransportFunc(func(r *http.Request) (*http.Response, error) {
|
||||
id := f.id
|
||||
if id == "" {
|
||||
id = "one"
|
||||
}
|
||||
f.requests++
|
||||
body := ""
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/ClientLogin"):
|
||||
body = "Auth=test-auth"
|
||||
case strings.HasSuffix(r.URL.Path, "/stream/items/contents"):
|
||||
if r.Method != "POST" {
|
||||
t.Fatal("read lookup requires POST")
|
||||
}
|
||||
r.ParseForm()
|
||||
if r.Form.Get("i") != id {
|
||||
t.Fatal("wrong item")
|
||||
}
|
||||
f.lookups++
|
||||
cats := []string{}
|
||||
if f.read {
|
||||
cats = append(cats, "user/reader/state/com.google/read")
|
||||
}
|
||||
if f.star {
|
||||
cats = append(cats, "user/reader/state/com.google/starred")
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"items": []map[string]any{{"id": id, "title": "Article", "categories": cats}}})
|
||||
body = string(raw)
|
||||
case strings.HasSuffix(r.URL.Path, "/token"):
|
||||
body = "write-token"
|
||||
if f.beforeEdit != nil {
|
||||
f.beforeEdit()
|
||||
}
|
||||
case strings.HasSuffix(r.URL.Path, "/edit-tag"):
|
||||
if r.Method != "POST" {
|
||||
t.Fatal("mutation method")
|
||||
}
|
||||
r.ParseForm()
|
||||
if len(r.Form) != 3 || r.Form.Get("T") != "write-token" || r.Form.Get("i") != id {
|
||||
t.Fatal("unexpected mutation fields", r.Form)
|
||||
}
|
||||
if tag := r.Form.Get("a"); tag != "" {
|
||||
switch tag {
|
||||
case "user/-/state/com.google/read":
|
||||
f.read = true
|
||||
case "user/-/state/com.google/starred":
|
||||
f.star = true
|
||||
default:
|
||||
t.Fatal("wrong tag", tag)
|
||||
}
|
||||
} else {
|
||||
switch r.Form.Get("r") {
|
||||
case "user/-/state/com.google/read":
|
||||
f.read = false
|
||||
case "user/-/state/com.google/starred":
|
||||
f.star = false
|
||||
default:
|
||||
t.Fatal("wrong tag")
|
||||
}
|
||||
}
|
||||
f.edits++
|
||||
if f.afterEdit != nil {
|
||||
f.afterEdit()
|
||||
}
|
||||
if f.timeout {
|
||||
return nil, errors.New("synthetic response lost after apply")
|
||||
}
|
||||
body = "OK"
|
||||
default:
|
||||
t.Fatal("unexpected path", r.URL.Path)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
}
|
||||
func TestFeedActionWritebackReceiptAndIsolation(t *testing.T) {
|
||||
s, token, domain, actor, v := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a := newFeedAction(v)
|
||||
w := feedRequestTest(s, token, "POST", "remote-state", a)
|
||||
if w.Code != 202 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if w = feedRequestTest(s, token, "POST", "remote-state", a); w.Code != 202 {
|
||||
t.Fatal("replay", w.Code, w.Body)
|
||||
}
|
||||
changed := a
|
||||
changed.Desired = false
|
||||
if w = feedRequestTest(s, token, "POST", "remote-state", changed); w.Code != 412 {
|
||||
t.Fatal("changed replay", w.Code)
|
||||
}
|
||||
changed.RequestID = uuid.NewString()
|
||||
if w = feedRequestTest(s, token, "POST", "remote-state", changed); w.Code != 412 {
|
||||
t.Fatal("parallel intent", w.Code)
|
||||
}
|
||||
item, _ := s.store.FeedItem(ctx, domain, actor, v.UUID, "one")
|
||||
if item.Read {
|
||||
t.Fatal("optimistic cache mutation")
|
||||
}
|
||||
f := &feedRemoteFake{star: true}
|
||||
if e := s.syncFeedActions(ctx, f.client(t)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got, e := s.store.FeedAction(ctx, domain, actor, v.UUID, "one")
|
||||
if e != nil || got.Status != "confirmed" || f.edits != 1 {
|
||||
t.Fatal(got, e, f.edits)
|
||||
}
|
||||
item, _ = s.store.FeedItem(ctx, domain, actor, v.UUID, "one")
|
||||
if !item.Read || !item.Starred {
|
||||
t.Fatal("unrelated star overwritten", item)
|
||||
}
|
||||
if w = feedRequestTest(s, token, "POST", "remote-state", a); w.Code != 202 {
|
||||
t.Fatal("receipt replay", w.Code)
|
||||
}
|
||||
if e = s.syncFeedActions(ctx, f.client(t)); e != nil || f.edits != 1 {
|
||||
t.Fatal("replayed write", e, f.edits)
|
||||
}
|
||||
// A second explicit intent already satisfied remotely causes no edit-tag.
|
||||
a.RequestID = uuid.NewString()
|
||||
if _, e = s.store.QueueFeedAction(ctx, domain, actor, a); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.syncFeedActions(ctx, f.client(t)); e != nil || f.edits != 1 {
|
||||
t.Fatal("redundant write", e)
|
||||
}
|
||||
other, e := s.store.CreatePasswordAccount(domain, "actionother", "long test password", "Other", "")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if got, e = s.store.FeedAction(ctx, domain, other.UUID, v.UUID, "one"); e != nil || got != nil {
|
||||
t.Fatal("other owner receipt", got, e)
|
||||
}
|
||||
a.RequestID = uuid.NewString()
|
||||
if _, e = s.store.QueueFeedAction(ctx, domain, other.UUID, a); e == nil {
|
||||
t.Fatal("other owner mutation")
|
||||
}
|
||||
v.Credential = ""
|
||||
v.WriteEnabled = false
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, actor, v); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
a.SourceVersion++
|
||||
if _, e = s.store.QueueFeedAction(ctx, domain, actor, a); e == nil {
|
||||
t.Fatal("opt-out ignored")
|
||||
}
|
||||
}
|
||||
func TestFeedActionUnknownNeverResendsAndReadOnlyRecheck(t *testing.T) {
|
||||
s, _, domain, actor, v := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a := newFeedAction(v)
|
||||
if _, e := s.store.QueueFeedAction(ctx, domain, actor, a); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
f := &feedRemoteFake{star: true, timeout: true}
|
||||
client := f.client(t)
|
||||
if e := s.syncFeedActions(ctx, client); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got, e := s.store.FeedAction(ctx, domain, actor, v.UUID, "one")
|
||||
if e != nil || got.Status != "unknown" {
|
||||
t.Fatal(got, e)
|
||||
}
|
||||
item, _ := s.store.FeedItem(ctx, domain, actor, v.UUID, "one")
|
||||
if item.Read {
|
||||
t.Fatal("unconfirmed cache")
|
||||
}
|
||||
requests := f.requests
|
||||
if e = s.syncFeedActions(ctx, client); e != nil || f.requests != requests {
|
||||
t.Fatal("automatic retry", e)
|
||||
}
|
||||
if e = s.store.RecheckFeedAction(ctx, domain, actor, a.RequestID); e == nil {
|
||||
t.Fatal("must wait for claim expiry")
|
||||
}
|
||||
// Simulate the uncertainty cooldown without sleeping.
|
||||
v.Credential = ""
|
||||
v.WriteEnabled = false
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, actor, v); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
s.store.DB.Exec(`UPDATE feed_actions SET until_ms=0 WHERE request_id=?`, a.RequestID)
|
||||
if e = s.store.RecheckFeedAction(ctx, domain, actor, a.RequestID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.syncFeedActions(ctx, client); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got, e = s.store.FeedAction(ctx, domain, actor, v.UUID, "one")
|
||||
if e != nil || got.Status != "confirmed" || f.edits != 1 {
|
||||
t.Fatal("recheck sent a write", got, e, f.edits)
|
||||
}
|
||||
}
|
||||
func TestFeedActionConflictAndPostSendFence(t *testing.T) {
|
||||
for _, changed := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "remote_conflict", true: "source_changed"}[changed], func(t *testing.T) {
|
||||
s, _, domain, actor, v := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a := newFeedAction(v)
|
||||
if _, e := s.store.QueueFeedAction(ctx, domain, actor, a); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
f := &feedRemoteFake{star: true}
|
||||
f.afterEdit = func() {
|
||||
if changed {
|
||||
v.Credential = ""
|
||||
v.WriteEnabled = false
|
||||
if _, e := s.store.SaveFeedSource(ctx, domain, actor, v); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
} else {
|
||||
f.read = false
|
||||
}
|
||||
}
|
||||
if e := s.syncFeedActions(ctx, f.client(t)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got, e := s.store.FeedAction(ctx, domain, actor, v.UUID, "one")
|
||||
want := "conflict"
|
||||
if changed {
|
||||
want = "unknown"
|
||||
}
|
||||
if e != nil || got.Status != want || f.edits != 1 {
|
||||
t.Fatal(got, e)
|
||||
}
|
||||
item, e := s.store.FeedItem(ctx, domain, actor, v.UUID, "one")
|
||||
if e != nil || item.Read {
|
||||
t.Fatal("unconfirmed/fenced value stored", item, e)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedActionFencesAndRecovery(t *testing.T) {
|
||||
for _, scenario := range []string{"config", "delete", "readonly", "extension", "crash"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
s, _, domain, actor, v := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a := newFeedAction(v)
|
||||
if _, e := s.store.QueueFeedAction(ctx, domain, actor, a); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if scenario == "crash" {
|
||||
due, e := s.store.DueFeedActions(ctx)
|
||||
if e != nil || len(due) != 1 {
|
||||
t.Fatal(e)
|
||||
}
|
||||
a, source, e := s.store.ClaimFeedAction(ctx, due[0])
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.ClaimFeed(ctx, v); !errors.Is(e, store.ErrTaskConflict) {
|
||||
t.Fatal("fetch overlapped mutation", e)
|
||||
}
|
||||
if e = s.store.MarkFeedActionSending(ctx, a, source); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
s.store.DB.Exec(`UPDATE feed_actions SET until_ms=0 WHERE request_id=?`, a.RequestID)
|
||||
due, e = s.store.DueFeedActions(ctx)
|
||||
if e != nil || len(due) != 0 {
|
||||
t.Fatal("crash requeued", due, e)
|
||||
}
|
||||
got, _ := s.store.FeedAction(ctx, domain, actor, v.UUID, "one")
|
||||
if got.Status != "unknown" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
return
|
||||
}
|
||||
f := &feedRemoteFake{star: true}
|
||||
f.beforeEdit = func() {
|
||||
var e error
|
||||
switch scenario {
|
||||
case "config":
|
||||
v.Credential = ""
|
||||
v.WriteEnabled = false
|
||||
_, e = s.store.SaveFeedSource(ctx, domain, actor, v)
|
||||
case "delete":
|
||||
e = s.store.FeedSourceAction(ctx, domain, actor, v.UUID, "delete", v.Version)
|
||||
case "readonly":
|
||||
e = s.store.SetPrincipalState(domain, actor, "readonly")
|
||||
case "extension":
|
||||
e = s.setSystemExtensionEnabled(domain, "organizer.feeds", false)
|
||||
}
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if e := s.syncFeedActions(ctx, f.client(t)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if f.edits != 0 {
|
||||
t.Fatal("sent after revocation")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedActionSingleFieldAndConcurrentIntent(t *testing.T) {
|
||||
for _, field := range []string{"read", "starred"} {
|
||||
for _, desired := range []bool{false, true} {
|
||||
t.Run(field+map[bool]string{false: "_remove", true: "_add"}[desired], func(t *testing.T) {
|
||||
s, _, domain, actor, v := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a := newFeedAction(v)
|
||||
a.Field = field
|
||||
a.Desired = desired
|
||||
results := make(chan error, 2)
|
||||
for range 2 {
|
||||
go func() {
|
||||
copy := a
|
||||
copy.RequestID = uuid.NewString()
|
||||
_, e := s.store.QueueFeedAction(ctx, domain, actor, copy)
|
||||
results <- e
|
||||
}()
|
||||
}
|
||||
success := 0
|
||||
for range 2 {
|
||||
e := <-results
|
||||
if e == nil {
|
||||
success++
|
||||
} else if !errors.Is(e, store.ErrTaskConflict) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if success != 1 {
|
||||
t.Fatal("concurrent intents accepted", success)
|
||||
}
|
||||
f := &feedRemoteFake{read: true, star: true}
|
||||
if field == "read" {
|
||||
f.read = !desired
|
||||
} else {
|
||||
f.star = !desired
|
||||
}
|
||||
if e := s.syncFeedActions(ctx, f.client(t)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if f.edits != 1 {
|
||||
t.Fatal("wrong edit count", f.edits)
|
||||
}
|
||||
if field == "read" {
|
||||
if f.read != desired || !f.star {
|
||||
t.Fatal("wrong field changed")
|
||||
}
|
||||
} else {
|
||||
if f.star != desired || !f.read {
|
||||
t.Fatal("wrong field changed")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRSSLinkPreference(t *testing.T) {
|
||||
s, token, domain, actor, _ := feedFixture(t)
|
||||
p, err := s.store.TaskPreferences(context.Background(), domain, actor)
|
||||
if err != nil || p.RSSLinkMode != "tab" {
|
||||
t.Fatal(p.RSSLinkMode, err)
|
||||
}
|
||||
p.RSSLinkMode = "embedded"
|
||||
if w := taskRequest(s, token, "PUT", "preferences", p, ""); w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
p, err = s.store.TaskPreferences(context.Background(), domain, actor)
|
||||
if err != nil || p.RSSLinkMode != "embedded" {
|
||||
t.Fatal(p.RSSLinkMode, err)
|
||||
}
|
||||
p.RSSLinkMode = "gecko"
|
||||
if w := taskRequest(s, token, "PUT", "preferences", p, ""); w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
p.RSSLinkMode = "unsafe"
|
||||
if w := taskRequest(s, token, "PUT", "preferences", p, ""); w.Code != 422 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedCapturePreview(t *testing.T) {
|
||||
s, token, _, _, _ := feedFixture(t)
|
||||
for _, tt := range []struct {
|
||||
prefix string
|
||||
status int
|
||||
}{{"/notes/{YYYY}/{MM}/{DD}/{Subject}", 200}, {"/notes/{unknown}", 422}, {"/a/../b", 422}} {
|
||||
w := feedRequestTest(s, token, "POST", "capture-preview", map[string]string{"prefix": tt.prefix, "title": "日本語 / test"})
|
||||
if w.Code != tt.status {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if w.Code == 200 {
|
||||
var data map[string]string
|
||||
if e := json.Unmarshal(w.Body.Bytes(), &data); e != nil || strings.ContainsAny(data["prefix"], "{}") || !strings.HasSuffix(data["prefix"], "/日本語---test") {
|
||||
t.Fatal(data, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
if w := feedRequestTest(s, "", "POST", "capture-preview", map[string]string{"prefix": "/notes"}); w.Code != 401 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,7 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
|
||||
}
|
||||
calls := 0
|
||||
failCatalog := false
|
||||
failFolders := false
|
||||
client := &http.Client{Transport: feedTransportFunc(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
body := ""
|
||||
@@ -63,7 +64,7 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
|
||||
t.Error("article request")
|
||||
}
|
||||
body = `{"items":[{"id":"a","title":"First","origin":{"title":"Same title","streamId":"feed/1"},"categories":["user/alice/label/Tech"]},{"id":"b","title":"Second","origin":{"title":"Same title","streamId":"feed/2"},"categories":["user/alice/label/Other"]}]}`
|
||||
if failCatalog {
|
||||
if failCatalog || failFolders {
|
||||
body = `{"items":[]}`
|
||||
}
|
||||
case strings.HasSuffix(r.URL.Path, "/subscription/list"):
|
||||
@@ -74,6 +75,11 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
|
||||
return nil, errors.New("synthetic timeout")
|
||||
}
|
||||
body = testFeedCatalog
|
||||
case strings.HasSuffix(r.URL.Path, "/tag/list"):
|
||||
if failFolders {
|
||||
return nil, errors.New("synthetic folder failure")
|
||||
}
|
||||
body = `{"tags":[{"id":"user/-/label/Empty/Folder","type":"folder"},{"id":"user/-/label/Not a folder","type":"tag"}]}`
|
||||
default:
|
||||
t.Fatalf("unexpected external request %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
@@ -89,7 +95,7 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
run()
|
||||
if calls != 3 {
|
||||
if calls != 4 {
|
||||
t.Fatal("fetch count", calls)
|
||||
}
|
||||
w := feedRequestTest(s, token, "GET", "catalog?source="+v.UUID, nil)
|
||||
@@ -127,9 +133,16 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
|
||||
if _, e := s.store.FeedCatalog(ctx, uuid.NewString(), actor, v.UUID); e == nil {
|
||||
t.Fatal("cross-domain catalog leak")
|
||||
}
|
||||
if calls != 3 {
|
||||
if calls != 4 {
|
||||
t.Fatal("foreground external request")
|
||||
}
|
||||
failFolders = true
|
||||
run()
|
||||
kept, e := s.store.FeedCatalogSnapshot(ctx, domain, actor, v.UUID)
|
||||
if e != nil || len(kept.Folders) != 3 || len(kept.Subscriptions) != 3 {
|
||||
t.Fatal("folder failure erased snapshot", kept, e)
|
||||
}
|
||||
failFolders = false
|
||||
failCatalog = true
|
||||
run()
|
||||
catalog, e := s.store.FeedCatalog(ctx, domain, actor, v.UUID)
|
||||
|
||||
@@ -328,11 +328,11 @@ func feedRequest(ctx context.Context, client *http.Client, method, target, auth
|
||||
}
|
||||
return raw, res.Header, res.StatusCode, nil
|
||||
}
|
||||
func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource, user, password string, catalogs ...*[]store.FeedRemoteSubscription) ([]store.FeedItem, error) {
|
||||
func freshRSSLogin(ctx context.Context, client *http.Client, v store.FeedSource, user, password string) (string, error) {
|
||||
base := strings.TrimRight(v.URL, "/")
|
||||
raw, _, _, e := feedRequest(ctx, client, "POST", base+"/accounts/ClientLogin", "", url.Values{"Email": {user}, "Passwd": {password}}, nil)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
return "", e
|
||||
}
|
||||
auth := ""
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
@@ -341,12 +341,54 @@ func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource,
|
||||
}
|
||||
}
|
||||
if auth == "" || len(auth) > 4096 || strings.ContainsAny(auth, "\r\n") {
|
||||
return nil, errors.New("credentials")
|
||||
return "", errors.New("credentials")
|
||||
}
|
||||
raw, _, _, e = feedRequest(ctx, client, "GET", base+"/reader/api/0/stream/contents/reading-list?output=json&n=200", auth, nil, nil)
|
||||
return auth, nil
|
||||
}
|
||||
func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource, user, password string, catalogs ...*store.FeedCatalogSnapshot) ([]store.FeedItem, error) {
|
||||
base := strings.TrimRight(v.URL, "/")
|
||||
auth, e := freshRSSLogin(ctx, client, v, user, password)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
raw, _, _, e := feedRequest(ctx, client, "GET", base+"/reader/api/0/stream/contents/reading-list?output=json&n=200", auth, nil, nil)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
items, e := parseFreshRSSItems(raw, base)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if len(catalogs) > 0 {
|
||||
raw, _, _, e = feedRequest(ctx, client, "GET", base+"/reader/api/0/subscription/list?output=json", auth, nil, nil)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
catalog, e := parseFreshRSSCatalog(raw)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
raw, _, _, e = feedRequest(ctx, client, "GET", base+"/reader/api/0/tag/list?output=json", auth, nil, nil)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
folders, e := parseFreshRSSFolders(raw)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
folders, e = store.FeedFolders(catalog, folders)
|
||||
if e != nil {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
snapshot := store.FeedCatalogSnapshot{Subscriptions: catalog, Folders: folders}
|
||||
if _, _, e = snapshot.Encode(); e != nil {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
*catalogs[0] = snapshot
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
func parseFreshRSSItems(raw []byte, base string) ([]store.FeedItem, error) {
|
||||
var response struct {
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
@@ -411,17 +453,6 @@ func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource,
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
if len(catalogs) > 0 {
|
||||
raw, _, _, e = feedRequest(ctx, client, "GET", base+"/reader/api/0/subscription/list?output=json", auth, nil, nil)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
catalog, e := parseFreshRSSCatalog(raw)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
*catalogs[0] = catalog
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -465,6 +496,9 @@ func (s *Server) syncFeedSources(ctx context.Context, job *store.EventJob) error
|
||||
func (s *Server) syncFeedSourcesWithClient(ctx context.Context, job *store.EventJob, client *http.Client) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 35*time.Second)
|
||||
defer cancel()
|
||||
if e := s.syncFeedActions(ctx, client); e != nil {
|
||||
return e
|
||||
}
|
||||
sources, e := s.store.DueFeedSources(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
@@ -474,6 +508,9 @@ func (s *Server) syncFeedSourcesWithClient(ctx context.Context, job *store.Event
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
if deadline, ok := ctx.Deadline(); ok && time.Until(deadline) < 9*time.Second {
|
||||
break
|
||||
}
|
||||
if !s.systemExtensionEnabled(v.Domain, "organizer.feeds") {
|
||||
continue
|
||||
}
|
||||
@@ -483,7 +520,7 @@ func (s *Server) syncFeedSourcesWithClient(ctx context.Context, job *store.Event
|
||||
}
|
||||
child, stop := context.WithTimeout(ctx, 8*time.Second)
|
||||
var items []store.FeedItem
|
||||
var catalog []store.FeedRemoteSubscription
|
||||
var catalog store.FeedCatalogSnapshot
|
||||
etag, modified := v.ETag, v.Modified
|
||||
unchanged := false
|
||||
if !validCalendarSourceURL(v.URL) {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func parseFreshRSSFolders(raw []byte) ([]store.FeedCategory, error) {
|
||||
if len(raw) > 4<<20 || !utf8.Valid(raw) {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
var response struct {
|
||||
Tags []struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
} `json:"tags"`
|
||||
}
|
||||
if json.Unmarshal(raw, &response) != nil || response.Tags == nil || len(response.Tags) > 10000 {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
folders := []store.FeedCategory{}
|
||||
seen := map[string]bool{}
|
||||
for _, tag := range response.Tags {
|
||||
// Article tags and system state tags are not subscription folders.
|
||||
if tag.Type != "folder" {
|
||||
continue
|
||||
}
|
||||
prefix, label, ok := strings.Cut(tag.ID, "/label/")
|
||||
if !ok || !strings.HasPrefix(prefix, "user/") || len(prefix) <= 5 || label == "" || !store.ValidFeedRemoteID(tag.ID) || seen[tag.ID] {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
seen[tag.ID] = true
|
||||
folders = append(folders, store.FeedCategory{ID: tag.ID, Label: feedText(label, 512)})
|
||||
}
|
||||
if _, e := store.FeedFolders(nil, folders); e != nil {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
return folders, nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestFreshRSSFoldersParsing(t *testing.T) {
|
||||
folders, e := parseFreshRSSFolders([]byte(`{"tags":[{"id":"user/-/state/com.google/starred"},{"id":"user/-/label/ArticleTag","type":"tag"},{"id":"user/-/label/技術/Linux","type":"folder"}]}`))
|
||||
if e != nil || len(folders) != 1 || folders[0].Label != "技術/Linux" {
|
||||
t.Fatal(folders, e)
|
||||
}
|
||||
for _, raw := range []string{`{}`, `{"tags":null}`, `{"tags":[{"id":"invalid","type":"folder"}]}`, `{"tags":[{"id":"user/-/label/","type":"folder"}]}`, `{"tags":[{"id":"user/-/label/A","type":"folder"},{"id":"user/-/label/A","type":"folder"}]}`} {
|
||||
if _, e = parseFreshRSSFolders([]byte(raw)); e == nil {
|
||||
t.Fatal("invalid folder accepted", raw)
|
||||
}
|
||||
}
|
||||
tags := []map[string]string{}
|
||||
for i := 0; i < 1001; i++ {
|
||||
tags = append(tags, map[string]string{"id": fmt.Sprintf("user/-/label/%d", i), "type": "folder"})
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"tags": tags})
|
||||
if _, e = parseFreshRSSFolders(raw); e == nil {
|
||||
t.Fatal("unbounded folders")
|
||||
}
|
||||
if _, e = store.FeedFolders([]store.FeedRemoteSubscription{{ID: "feed/1", Categories: []store.FeedCategory{{ID: "cat", Label: "A"}}}}, []store.FeedCategory{{ID: "cat", Label: "B"}}); e == nil {
|
||||
t.Fatal("conflicting labels")
|
||||
}
|
||||
large := store.FeedCatalogSnapshot{}
|
||||
for i := 0; i < 1000; i++ {
|
||||
large.Subscriptions = append(large.Subscriptions, store.FeedRemoteSubscription{ID: fmt.Sprintf("feed/%d", i), Title: strings.Repeat("s", 512)})
|
||||
large.Folders = append(large.Folders, store.FeedCategory{ID: fmt.Sprintf("user/-/label/%d", i), Label: strings.Repeat("f", 512)})
|
||||
}
|
||||
if _, e := store.FeedCatalogJSON(large.Subscriptions); e != nil {
|
||||
t.Fatal("catalog alone should fit", e)
|
||||
}
|
||||
if _, _, e := large.Encode(); e != store.ErrTaskDAVLimit {
|
||||
t.Fatal("combined snapshot limit", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedFolderMembershipAndUncategorized(t *testing.T) {
|
||||
s, token, domain, actor, source := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, e := s.store.DB.Exec(`UPDATE feed_sources SET next_ms=0 WHERE uuid=?`, source.UUID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
sources, e := s.store.FeedSources(ctx, domain, actor)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, v := range sources {
|
||||
if v.UUID == source.UUID {
|
||||
source = v
|
||||
}
|
||||
}
|
||||
claim, e := s.store.ClaimFeed(ctx, source)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
cat := store.FeedCategory{ID: "user/-/label/New/Folder", Label: "New/Folder"}
|
||||
snapshot := store.FeedCatalogSnapshot{Subscriptions: []store.FeedRemoteSubscription{{ID: "feed/1", Title: "Moved", Categories: []store.FeedCategory{cat}}, {ID: "feed/2", Title: "Unclassified", Categories: []store.FeedCategory{}}}, Folders: []store.FeedCategory{{ID: "user/-/label/Empty", Label: "Empty"}}}
|
||||
items := []store.FeedItem{{ID: "a", Title: "Moved", RemoteFeed: "feed/1", RemoteCategories: []string{"user/-/label/Old"}}, {ID: "b", Title: "Unclassified", RemoteFeed: "feed/2", RemoteCategories: []string{"user/-/label/ArticleTag"}}, {ID: "c", Title: "Unknown subscription", RemoteFeed: "feed/unknown"}}
|
||||
if e = s.store.CompleteFeed(ctx, claim, items, "", "", "", false, snapshot); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
query string
|
||||
want string
|
||||
}{{"category=" + url.QueryEscape(cat.ID), "a"}, {"category_mode=uncategorized", "b"}, {"category=user%2F-%2Flabel%2FOld", ""}, {"category=user%2F-%2Flabel%2FEmpty", ""}} {
|
||||
w := feedRequestTest(s, token, "GET", "items?source="+source.UUID+"&"+test.query, nil)
|
||||
var data struct {
|
||||
Items []store.FeedItem `json:"items"`
|
||||
}
|
||||
json.Unmarshal(w.Body.Bytes(), &data)
|
||||
if w.Code != 200 || (test.want == "" && len(data.Items) != 0) || (test.want != "" && (len(data.Items) != 1 || data.Items[0].ID != test.want)) {
|
||||
t.Fatal(test.query, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
for _, query := range []string{"category_mode=uncategorized", "source=" + source.UUID + "&category_mode=bad", "source=" + source.UUID + "&category_mode=uncategorized&category=" + url.QueryEscape(cat.ID)} {
|
||||
if w := feedRequestTest(s, token, "GET", "items?"+query, nil); w.Code != 422 {
|
||||
t.Fatal(query, w.Code)
|
||||
}
|
||||
}
|
||||
got, e := s.store.FeedCatalogSnapshot(ctx, domain, actor, source.UUID)
|
||||
if e != nil || len(got.Folders) != 2 {
|
||||
t.Fatal(got, e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/geckorelay"
|
||||
)
|
||||
|
||||
const geckoAPI = feedsAPI + "browser/"
|
||||
|
||||
type geckoProxy struct {
|
||||
origin *url.URL
|
||||
key string
|
||||
transport *http.Transport
|
||||
}
|
||||
|
||||
func (s *Server) geckoConfig() *geckoProxy {
|
||||
s.geckoOnce.Do(func() {
|
||||
u, err := url.Parse(os.Getenv("PAGESWIKI_GECKO_RELAY"))
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
|
||||
return
|
||||
}
|
||||
key, err := os.ReadFile(os.Getenv("PAGESWIKI_GECKO_KEY_FILE"))
|
||||
if err != nil || len(strings.TrimSpace(string(key))) < 32 {
|
||||
return
|
||||
}
|
||||
s.gecko = &geckoProxy{origin: u, key: strings.TrimSpace(string(key)), transport: &http.Transport{Proxy: nil, DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext, ResponseHeaderTimeout: 10 * time.Second, TLSHandshakeTimeout: 5 * time.Second, IdleConnTimeout: 30 * time.Second, MaxIdleConnsPerHost: 4}}
|
||||
})
|
||||
return s.gecko
|
||||
}
|
||||
|
||||
func (s *Server) geckoAvailable(domain string) bool {
|
||||
return s.systemExtensionEnabled(domain, "viewer.gecko") && s.geckoConfig() != nil
|
||||
}
|
||||
|
||||
func geckoIsolation(w http.ResponseWriter) {
|
||||
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
|
||||
w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp")
|
||||
w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
|
||||
}
|
||||
|
||||
func (s *Server) handleFeedBrowser(w http.ResponseWriter, r *http.Request, domain, actor string, active bool) {
|
||||
path := strings.TrimPrefix(r.URL.Path, geckoAPI)
|
||||
// Recipients can still obtain sources after the viewer is disabled.
|
||||
distribution := strings.HasPrefix(path, strings.TrimPrefix(geckorelay.DistributionPrefix, "/"))
|
||||
if s.geckoConfig() == nil || (!distribution && (!active || !s.geckoAvailable(domain))) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if r.Method != "GET" || r.URL.RawQuery != "" {
|
||||
http.Error(w, "invalid request", 400)
|
||||
return
|
||||
}
|
||||
switch path {
|
||||
case "":
|
||||
geckoIsolation(w)
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self' blob: 'wasm-unsafe-eval'; worker-src 'self' blob:; connect-src 'self' data:; style-src 'self'; img-src 'self' data:; frame-ancestors 'self'; base-uri 'none'; form-action 'none'")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
io.WriteString(w, geckoShell)
|
||||
return
|
||||
case "assets/v0.0.1/gecko.js", "assets/v0.0.1/gecko.wasm.zst":
|
||||
case "wisp/":
|
||||
// WebSocket cookies alone are not CSRF protection.
|
||||
if r.Header.Get("Origin") != externalURL(r, "") || !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
|
||||
http.Error(w, "forbidden", 403)
|
||||
return
|
||||
}
|
||||
default:
|
||||
if !distribution {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
cfg := s.geckoConfig()
|
||||
ctx, cancel := context.WithCancel(r.Context())
|
||||
defer cancel()
|
||||
if path == "wisp/" {
|
||||
token := s.authTokenFromRequest(r)
|
||||
go func() {
|
||||
ticker := time.NewTicker(5 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
p, err := s.store.PrincipalForSession(domain, token)
|
||||
if err != nil || p.UUID != actor || p.State != "active" || !s.systemExtensionEnabled(domain, "organizer.feeds") || !s.geckoAvailable(domain) {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
proxy := &httputil.ReverseProxy{Transport: cfg.transport, Rewrite: func(p *httputil.ProxyRequest) {
|
||||
p.SetURL(cfg.origin)
|
||||
p.Out.URL.Path = "/" + path
|
||||
p.Out.URL.RawPath = ""
|
||||
// No ambient credentials, forwarding headers, target URL or user-supplied
|
||||
// grant crosses this boundary. The relay origin is operator-configured.
|
||||
keep := http.Header{}
|
||||
for _, h := range []string{"Upgrade", "Connection", "Sec-WebSocket-Key", "Sec-WebSocket-Version", "Origin", "Range", "If-None-Match", "If-Modified-Since"} {
|
||||
if value := p.Out.Header.Get(h); value != "" {
|
||||
keep.Set(h, value)
|
||||
}
|
||||
}
|
||||
keep.Set(geckorelay.GrantHeader, geckorelay.Sign(cfg.key, geckorelay.Grant{Subject: domain + ":" + actor, Nonce: randomURLToken(24), Expires: time.Now().Add(30 * time.Second).Unix()}))
|
||||
p.Out.Header = keep
|
||||
}, ModifyResponse: func(resp *http.Response) error {
|
||||
resp.Header.Del("Set-Cookie")
|
||||
resp.Header.Set("Cross-Origin-Resource-Policy", "same-origin")
|
||||
if resp.Header.Get("Cache-Control") == "" {
|
||||
resp.Header.Set("Cache-Control", "private, no-store")
|
||||
}
|
||||
return nil
|
||||
}, ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
http.Error(w, "browser relay unavailable", http.StatusBadGateway)
|
||||
}}
|
||||
// ReverseProxy adds upstream headers rather than replacing existing values.
|
||||
// Do not accidentally append the RSS API's no-store to versioned assets.
|
||||
w.Header().Del("Cache-Control")
|
||||
proxy.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
|
||||
const geckoShell = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="/static/css/feed-gecko.css?v=1"><title>Gecko</title></head><body><p id="status" role="status"></p><canvas id="screen" tabindex="0" aria-label="Original article"></canvas><script type="module" src="/static/js/feed-gecko.js?v=2"></script></body></html>`
|
||||
|
||||
func init() {
|
||||
translations["en"]["feeds.gecko"] = "Gecko RSS browser (experimental)"
|
||||
translations["ja"]["feeds.gecko"] = "Gecko RSSブラウザ(実験的)"
|
||||
translations["en"]["feeds.gecko_help"] = "Requires a separately deployed authenticated relay. Public HTTP/HTTPS only; browsing uses the relay's IP address."
|
||||
translations["ja"]["feeds.gecko_help"] = "認証付き中継サービスの別途配置が必要です。公開HTTP/HTTPSのみ。閲覧先には中継サーバーのIPが使われます。"
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/websocket"
|
||||
"pageswiki/internal/geckorelay"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
// The real engine runs against a synthetic Wisp HTTP responder. This test never
|
||||
// dials an article server, production source, DNS name or external calendar.
|
||||
func TestFeedGeckoChromium(t *testing.T) {
|
||||
testFeedGeckoChromium(t, false)
|
||||
}
|
||||
|
||||
func TestFeedGeckoStartupFailureChromium(t *testing.T) {
|
||||
testFeedGeckoChromium(t, true)
|
||||
}
|
||||
|
||||
func testFeedGeckoChromium(t *testing.T, failure bool) {
|
||||
assets := os.Getenv("PAGESWIKI_GECKO_TEST_ASSETS")
|
||||
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" || assets == "" {
|
||||
t.Skip("opt-in real Gecko assets")
|
||||
}
|
||||
var connections atomic.Int64
|
||||
publicHTTPS := !failure && os.Getenv("PAGESWIKI_GECKO_PUBLIC_HTTPS_TEST") == "1"
|
||||
realRelay, err := geckorelay.New(geckoTestKey, assets)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if publicHTTPS {
|
||||
realRelay.Distribution, err = geckorelay.VerifyDistribution(assets)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if failure && strings.HasSuffix(r.URL.Path, "/NotoSansCJKjp-Regular.otf") {
|
||||
http.Error(w, "synthetic startup failure", 503)
|
||||
return
|
||||
}
|
||||
if publicHTTPS {
|
||||
realRelay.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if _, err := geckorelay.Verify(geckoTestKey, r.Header.Get(geckorelay.GrantHeader), time.Now()); err != nil {
|
||||
http.Error(w, "bad grant", 403)
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/assets/") || strings.HasPrefix(r.URL.Path, geckorelay.DistributionPrefix) {
|
||||
http.ServeFile(w, r, filepath.Join(assets, filepath.Base(r.URL.Path)))
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/wisp/" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
websocket.Handler(func(ws *websocket.Conn) {
|
||||
connections.Add(1)
|
||||
defer connections.Add(-1)
|
||||
packet := func(kind byte, id uint32, data []byte) []byte {
|
||||
out := make([]byte, 5+len(data))
|
||||
out[0] = kind
|
||||
binary.LittleEndian.PutUint32(out[1:], id)
|
||||
copy(out[5:], data)
|
||||
return out
|
||||
}
|
||||
websocket.Message.Send(ws, packet(3, 0, []byte{8, 0, 0, 0}))
|
||||
requests := map[uint32]string{}
|
||||
for {
|
||||
var p []byte
|
||||
if websocket.Message.Receive(ws, &p) != nil || len(p) < 5 {
|
||||
return
|
||||
}
|
||||
id := binary.LittleEndian.Uint32(p[1:])
|
||||
switch p[0] {
|
||||
case 1:
|
||||
requests[id] = ""
|
||||
case 2:
|
||||
requests[id] += string(p[5:])
|
||||
if !strings.Contains(requests[id], "\r\n\r\n") {
|
||||
continue
|
||||
}
|
||||
body := `<!doctype html><meta charset="utf-8"><body style="margin:0;background:rgb(255,0,0)"><a style="display:block;width:300px;height:100px;background:blue;color:white" href="http://fixture.invalid/next">Synthetic next page</a><h1>日本語の記事:学舎の園</h1>`
|
||||
if strings.HasPrefix(requests[id], "GET /next ") {
|
||||
body = `<!doctype html><body style="margin:0;background:rgb(0,255,0)"><h1>Second synthetic page</h1>`
|
||||
}
|
||||
response := fmt.Sprintf("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", len(body), body)
|
||||
websocket.Message.Send(ws, packet(2, id, []byte(response)))
|
||||
websocket.Message.Send(ws, packet(4, id, []byte{2}))
|
||||
delete(requests, id)
|
||||
case 4:
|
||||
delete(requests, id)
|
||||
}
|
||||
}
|
||||
}).ServeHTTP(w, r)
|
||||
}))
|
||||
defer backend.Close()
|
||||
s, token, domain, actor, source := feedFixture(t)
|
||||
configureTestGecko(t, s, domain, backend.URL)
|
||||
p, e := s.store.TaskPreferences(context.Background(), domain, actor)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
p.RSSLinkMode = "gecko"
|
||||
if _, e = s.store.SaveTaskPreferences(context.Background(), domain, actor, p, time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
claim, e := s.store.ClaimFeed(context.Background(), source)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
articleURL := "http://fixture.invalid/first"
|
||||
if publicHTTPS {
|
||||
articleURL = "https://example.com/"
|
||||
}
|
||||
if e = s.store.CompleteFeed(context.Background(), claim, []store.FeedItem{{ID: "synthetic", Title: "Gecko synthetic fixture", URL: articleURL, Body: "Synthetic test fixture."}}, "", "", "", false); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
handler := s.handler()
|
||||
web := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if publicHTTPS && r.URL.Path == "/static/js/feed-gecko.js" {
|
||||
js, err := os.ReadFile("static/js/feed-gecko.js")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
http.Error(w, "fixture missing", 500)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/javascript")
|
||||
io.WriteString(w, strings.Replace(string(js), "engine=new Gecko(", "globalThis.fixtureEngine=engine=new Gecko(", 1))
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Origin") == "http://"+r.Host {
|
||||
r.Header.Set("Origin", "http://localhost")
|
||||
}
|
||||
r.Host = "localhost"
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
handler.ServeHTTP(w, r)
|
||||
}))
|
||||
defer web.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)
|
||||
defer cancel()
|
||||
mode := "synthetic"
|
||||
if failure {
|
||||
mode = "startup-failure"
|
||||
}
|
||||
if publicHTTPS {
|
||||
mode = "public-https"
|
||||
}
|
||||
out, e := exec.CommandContext(ctx, "node", "internal/server/testdata/feed-gecko-browser.mjs", web.URL+"/v/feeds", t.TempDir(), "/tmp/pageswiki-feed-gecko.png", mode).CombinedOutput()
|
||||
if e != nil {
|
||||
t.Fatalf("browser: %v\n%s", e, out)
|
||||
}
|
||||
io.WriteString(os.Stdout, string(out))
|
||||
for i := 0; i < 30 && connections.Load() != 0; i++ {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
if connections.Load() != 0 {
|
||||
t.Fatal("viewer close left relay session alive")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/websocket"
|
||||
"pageswiki/internal/geckorelay"
|
||||
)
|
||||
|
||||
const geckoTestKey = "synthetic-server-relay-key-at-least-32-bytes"
|
||||
|
||||
func configureTestGecko(t *testing.T, s *Server, domain, origin string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "key")
|
||||
if err := os.WriteFile(path, []byte(geckoTestKey), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PAGESWIKI_GECKO_RELAY", origin)
|
||||
t.Setenv("PAGESWIKI_GECKO_KEY_FILE", path)
|
||||
if err := s.setSystemExtensionEnabled(domain, "viewer.gecko", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedGeckoAuthorizationAndHeaders(t *testing.T) {
|
||||
s, token, domain, actor, _ := feedFixture(t)
|
||||
if s.systemExtensionEnabled(domain, "viewer.gecko") {
|
||||
t.Fatal("experimental relay enabled by default")
|
||||
}
|
||||
for _, raw := range []string{"bad json", `{"organizer.feeds":true}`} {
|
||||
if err := s.store.SetConfigInDomain(domain, systemExtensionStateKey, raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.systemExtensionEnabled(domain, "viewer.gecko") {
|
||||
t.Fatal("invalid/absent config enabled relay")
|
||||
}
|
||||
}
|
||||
var requests atomic.Int64
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
g, err := geckorelay.Verify(geckoTestKey, r.Header.Get(geckorelay.GrantHeader), time.Now())
|
||||
if err != nil || g.Subject != domain+":"+actor {
|
||||
t.Error("missing bound grant")
|
||||
}
|
||||
for _, h := range []string{"Cookie", "Authorization", "X-Forwarded-For", "Forwarded", "Referer"} {
|
||||
if r.Header.Get(h) != "" {
|
||||
t.Error("credential/header leaked", h)
|
||||
}
|
||||
}
|
||||
if r.URL.Path != "/assets/v0.0.1/gecko.js" && r.URL.Path != "/distribution/v0.0.1/manifest.json" {
|
||||
t.Error("path", r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Set-Cookie", "forbidden=1")
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400, immutable")
|
||||
io.WriteString(w, "export const fixture=true;")
|
||||
}))
|
||||
defer upstream.Close()
|
||||
configureTestGecko(t, s, domain, upstream.URL)
|
||||
r := httptest.NewRequest("GET", "http://localhost"+geckoAPI+"assets/v0.0.1/gecko.js", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
r.Header.Set("Cookie", "private=secret")
|
||||
r.Header.Set("X-Forwarded-For", "secret")
|
||||
w := httptest.NewRecorder()
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
if w.Code != 200 || requests.Load() != 1 || w.Header().Get("Set-Cookie") != "" {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if len(w.Header().Values("Cache-Control")) != 1 || strings.Contains(w.Header().Get("Cache-Control"), "no-store") {
|
||||
t.Fatal("asset cache disabled", w.Header())
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
path, method string
|
||||
code int
|
||||
}{{"", "GET", 200}, {"wisp/", "GET", 403}, {"assets/v0.0.1/gecko.js?target=https://example.org", "GET", 400}, {"unknown", "GET", 404}, {"assets/v0.0.1/gecko.js", "POST", 400}} {
|
||||
w = feedRequestTest(s, token, tc.method, "browser/"+tc.path, nil)
|
||||
if w.Code != tc.code {
|
||||
t.Fatalf("%s %s: %d %s", tc.method, tc.path, w.Code, w.Body)
|
||||
}
|
||||
if tc.path == "" && w.Header().Get("Cross-Origin-Embedder-Policy") != "require-corp" {
|
||||
t.Fatal("not isolated")
|
||||
}
|
||||
}
|
||||
if w = feedRequestTest(s, "", "GET", "browser/assets/v0.0.1/gecko.js", nil); w.Code == 200 {
|
||||
t.Fatal("anonymous")
|
||||
}
|
||||
for _, origin := range []string{"https://evil.example", "null", "http://localhost.evil.example"} {
|
||||
r := httptest.NewRequest("GET", "http://localhost"+geckoAPI+"wisp/", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
r.Header.Set("Origin", origin)
|
||||
r.Header.Set("Upgrade", "websocket")
|
||||
w := httptest.NewRecorder()
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
if w.Code != 403 {
|
||||
t.Fatal("cross-site websocket", origin, w.Code)
|
||||
}
|
||||
}
|
||||
prefs, err := s.store.TaskPreferences(context.Background(), domain, actor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prefs.RSSLinkMode = "gecko"
|
||||
if _, err = s.store.SaveTaskPreferences(context.Background(), domain, actor, prefs, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page := func() *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("GET", "http://localhost/v/feeds", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
w := httptest.NewRecorder()
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
w = page()
|
||||
if w.Code != 200 || w.Header().Get("Cross-Origin-Opener-Policy") != "same-origin" || !strings.Contains(w.Body.String(), `data-link-mode="gecko"`) {
|
||||
t.Fatal("isolated page", w.Code)
|
||||
}
|
||||
if err = s.setSystemExtensionEnabled(domain, "viewer.gecko", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w = page()
|
||||
if w.Header().Get("Cross-Origin-Opener-Policy") != "" || !strings.Contains(w.Body.String(), `data-link-mode="tab"`) {
|
||||
t.Fatal("disabled fallback")
|
||||
}
|
||||
if w = feedRequestTest(s, token, "GET", "browser/", nil); w.Code != 404 {
|
||||
t.Fatal("disabled shell", w.Code)
|
||||
}
|
||||
if err = s.setSystemExtensionEnabled(domain, "organizer.feeds", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w = feedRequestTest(s, token, "GET", "browser/distribution/v0.0.1/manifest.json", nil); w.Code != 200 {
|
||||
t.Fatal("sources lost after disabling extensions", w.Code)
|
||||
}
|
||||
if w = feedRequestTest(s, "", "GET", "browser/distribution/v0.0.1/manifest.json", nil); w.Code == 200 {
|
||||
t.Fatal("anonymous source download")
|
||||
}
|
||||
if err = s.setSystemExtensionEnabled(domain, "organizer.feeds", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.setSystemExtensionEnabled(domain, "viewer.gecko", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.store.DB.Exec(`UPDATE principals SET state='readonly' WHERE uuid=?`, actor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w = feedRequestTest(s, token, "GET", "browser/", nil); w.Code != 404 {
|
||||
t.Fatal("readonly browser", w.Code)
|
||||
}
|
||||
if w = feedRequestTest(s, token, "GET", "browser/distribution/v0.0.1/manifest.json", nil); w.Code != 200 {
|
||||
t.Fatal("readonly recipient lost source access", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedGeckoWebsocketRevocation(t *testing.T) {
|
||||
for _, disable := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "logout", true: "disable"}[disable], func(t *testing.T) {
|
||||
s, token, domain, _, _ := feedFixture(t)
|
||||
relay, err := geckorelay.New(geckoTestKey, t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
upstream := httptest.NewServer(relay)
|
||||
defer upstream.Close()
|
||||
configureTestGecko(t, s, domain, upstream.URL)
|
||||
web := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Host = "localhost"
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
}))
|
||||
defer web.Close()
|
||||
cfg, _ := websocket.NewConfig("ws"+strings.TrimPrefix(web.URL, "http")+geckoAPI+"wisp/", "http://localhost")
|
||||
cfg.Header.Set("Authorization", "Bearer "+token)
|
||||
conn, err := websocket.DialConfig(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(12 * time.Second))
|
||||
var frame []byte
|
||||
if err = websocket.Message.Receive(conn, &frame); err != nil || len(frame) != 9 || frame[0] != 3 || binary.LittleEndian.Uint32(frame[1:]) != 0 {
|
||||
t.Fatal(frame, err)
|
||||
}
|
||||
if disable {
|
||||
err = s.setSystemExtensionEnabled(domain, "viewer.gecko", false)
|
||||
} else {
|
||||
err = s.store.RevokeAuthSession(token)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start := time.Now()
|
||||
err = websocket.Message.Receive(conn, &frame)
|
||||
if err == nil || time.Since(start) > 10*time.Second {
|
||||
t.Fatal("session not promptly closed", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func writeFeedHistoryJSON(w http.ResponseWriter, value any) {
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func (s *Server) handleFeedHistory(w http.ResponseWriter, r *http.Request, domain, actor, key string) bool {
|
||||
if r.Method != "GET" || (key != "actions" && key != "action/export") {
|
||||
return false
|
||||
}
|
||||
if key == "action/export" {
|
||||
a, e := s.store.FeedActionRecord(r.Context(), domain, actor, r.URL.Query().Get("request_id"))
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return true
|
||||
}
|
||||
id, _ := uuid.Parse(a.RequestID)
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="pageswiki-feed-action-`+id.String()+`.json"`)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
writeFeedHistoryJSON(w, map[string]any{"format": "pageswiki.feed-action", "version": 1, "exported_ms": time.Now().UnixMilli(), "domain_uuid": domain, "owner_uuid": actor, "action": a})
|
||||
return true
|
||||
}
|
||||
q := r.URL.Query()
|
||||
query := store.FeedActionQuery{Source: q.Get("source"), Status: q.Get("status"), Before: -1, Key: q.Get("key")}
|
||||
if q.Has("before") {
|
||||
var e error
|
||||
query.Before, e = strconv.ParseInt(q.Get("before"), 10, 64)
|
||||
if e != nil || query.Before < 0 {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return true
|
||||
}
|
||||
}
|
||||
items, e := s.store.FeedActionHistory(r.Context(), domain, actor, query)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return true
|
||||
}
|
||||
more := len(items) > 50
|
||||
if more {
|
||||
items = items[:50]
|
||||
}
|
||||
writeFeedHistoryJSON(w, map[string]any{"actions": items, "more": more})
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func feedHistoryResponse(t *testing.T, s *Server, token, query string) ([]store.FeedActionRecord, bool) {
|
||||
t.Helper()
|
||||
w := feedRequestTest(s, token, "GET", "actions"+query, nil)
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if w.Header().Get("Cache-Control") != "private, no-store" {
|
||||
t.Fatal("private response cache policy")
|
||||
}
|
||||
var data struct {
|
||||
Actions []store.FeedActionRecord `json:"actions"`
|
||||
More bool `json:"more"`
|
||||
}
|
||||
if e := json.Unmarshal(w.Body.Bytes(), &data); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return data.Actions, data.More
|
||||
}
|
||||
|
||||
func TestFeedHistoryOrphansExportAndRecheck(t *testing.T) {
|
||||
s, token, domain, actor, source := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a, e := s.store.QueueFeedAction(ctx, domain, actor, newFeedAction(source))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
queued, _ := feedHistoryResponse(t, s, token, "?status=pending")
|
||||
if len(queued) != 1 || queued[0].Status != "queued" || queued[0].CanCheck {
|
||||
t.Fatal("queued history", queued)
|
||||
}
|
||||
fake := &feedRemoteFake{timeout: true}
|
||||
if e = s.syncFeedActions(ctx, fake.client(t)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
list, _ := feedHistoryResponse(t, s, token, "")
|
||||
if len(list) != 1 || list[0].Status != "unknown" || list[0].CanCheck || list[0].CheckAfterMS <= time.Now().UnixMilli() || !list[0].ItemPresent || !list[0].SourcePresent {
|
||||
t.Fatal("unknown cooldown", list)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`DELETE FROM feed_items WHERE source_uuid=?`, source.UUID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`UPDATE feed_actions SET until_ms=0 WHERE request_id=?`, a.RequestID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Read-only connector opt-out does not disable read-only result checks.
|
||||
source.Credential, source.WriteEnabled = "", false
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, actor, source); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
list, _ = feedHistoryResponse(t, s, token, "?status=unknown")
|
||||
if len(list) != 1 || list[0].ItemPresent || !list[0].CanCheck || list[0].ItemTitle != "" || list[0].SourceTitle != "Remote" {
|
||||
t.Fatal("evicted item lost", list)
|
||||
}
|
||||
w := feedRequestTest(s, token, "GET", "action/export?request_id="+a.RequestID, nil)
|
||||
if w.Code != 200 || !strings.Contains(w.Header().Get("Content-Disposition"), a.RequestID+".json") || w.Header().Get("X-Content-Type-Options") != "nosniff" {
|
||||
t.Fatal("export", w.Code, w.Header())
|
||||
}
|
||||
var exported struct {
|
||||
Format string `json:"format"`
|
||||
Action store.FeedActionRecord `json:"action"`
|
||||
}
|
||||
if e = json.Unmarshal(w.Body.Bytes(), &exported); e != nil || exported.Format != "pageswiki.feed-action" || exported.Action.RequestID != a.RequestID || exported.Action.Status != "unknown" {
|
||||
t.Fatal("export data", exported, e)
|
||||
}
|
||||
for _, secret := range []string{"credential", "secret", source.URL, `"claim"`, `"until_ms"`} {
|
||||
if strings.Contains(w.Body.String(), secret) {
|
||||
t.Fatal("export leaked internal credentials or worker metadata", secret)
|
||||
}
|
||||
}
|
||||
if w = feedRequestTest(s, token, "POST", "action/check", map[string]string{"request_id": a.RequestID}); w.Code != 202 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if e = s.syncFeedActions(ctx, fake.client(t)); e != nil || fake.edits != 1 {
|
||||
t.Fatal("recheck sent a second mutation", fake.edits, e)
|
||||
}
|
||||
list, _ = feedHistoryResponse(t, s, token, "")
|
||||
if len(list) != 0 {
|
||||
t.Fatal("confirmed action unresolved", list)
|
||||
}
|
||||
list, _ = feedHistoryResponse(t, s, token, "?status=confirmed")
|
||||
if len(list) != 1 || list[0].Status != "confirmed" || list[0].ItemPresent {
|
||||
t.Fatal("evicted receipt missing", list)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`UPDATE feed_actions SET status='unknown' WHERE request_id=?`, a.RequestID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`DELETE FROM feed_sources WHERE uuid=?`, source.UUID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
list, _ = feedHistoryResponse(t, s, token, "?source="+source.UUID)
|
||||
if len(list) != 1 || list[0].SourcePresent || list[0].ItemPresent || list[0].CanCheck || list[0].Error != "source_deleted" {
|
||||
t.Fatal("deleted source receipt lost", list)
|
||||
}
|
||||
if w = feedRequestTest(s, token, "POST", "action/check", map[string]string{"request_id": a.RequestID}); w.Code != 412 {
|
||||
t.Fatal("deleted source recheck accepted", w.Code)
|
||||
}
|
||||
if w = feedRequestTest(s, token, "GET", "action/export?request_id="+a.RequestID, nil); w.Code != 200 {
|
||||
t.Fatal("deleted source export", w.Code)
|
||||
}
|
||||
source.Version, source.Credential = 0, ""
|
||||
source.URL = "https://different.example.org/api/greader.php"
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, actor, source); !errors.Is(e, store.ErrTaskConflict) {
|
||||
t.Fatal("rebound orphan receipt", e)
|
||||
}
|
||||
other, e := s.store.CreatePasswordAccount(domain, "historyreuse", "long test password", "Other", "")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, other.UUID, source); !errors.Is(e, store.ErrTaskConflict) {
|
||||
t.Fatal("rebound unresolved receipt across owners", e)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`UPDATE feed_actions SET status='confirmed' WHERE request_id=?`, a.RequestID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, actor, source); !errors.Is(e, store.ErrTaskConflict) {
|
||||
t.Fatal("rebound terminal receipt", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedHistoryPaginationValidationAndIsolation(t *testing.T) {
|
||||
s, token, domain, actor, source := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
// Same millisecond, stable unique tie-breaker; well above a page boundary.
|
||||
for i := 0; i < 107; i++ {
|
||||
if _, e := s.store.DB.Exec(`INSERT INTO feed_actions(domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,created_ms) VALUES(?,?,?,?,?,'read',1,1,'confirmed',1234)`, domain, actor, uuid.NewString(), source.UUID, fmt.Sprint(i)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
query, seen := "?status=all", map[string]bool{}
|
||||
for {
|
||||
list, more := feedHistoryResponse(t, s, token, query)
|
||||
if len(list) > 50 {
|
||||
t.Fatal("unbounded list")
|
||||
}
|
||||
for _, a := range list {
|
||||
if seen[a.RequestID] {
|
||||
t.Fatal("duplicate cursor record")
|
||||
}
|
||||
seen[a.RequestID] = true
|
||||
}
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
last := list[len(list)-1]
|
||||
query = fmt.Sprintf("?status=all&before=%d&key=%s", last.CreatedMS, last.RequestID)
|
||||
}
|
||||
if len(seen) != 107 {
|
||||
t.Fatal("cursor omissions", len(seen))
|
||||
}
|
||||
for _, query := range []string{"?status=bogus", "?source=bad", "?before=bad", "?before=-1", "?before=1", "?key=" + uuid.NewString(), "?before=1&key=bad"} {
|
||||
if w := feedRequestTest(s, token, "GET", "actions"+query, nil); w.Code != 422 {
|
||||
t.Fatal("invalid query", query, w.Code)
|
||||
}
|
||||
}
|
||||
other, e := s.store.CreatePasswordAccount(domain, "historyother", "long test password", "Other", "")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
otherToken, e := s.store.CreateAuthSession(domain, other.UUID)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
otherList, _ := feedHistoryResponse(t, s, otherToken, "?status=all&source="+source.UUID)
|
||||
if len(otherList) != 0 {
|
||||
t.Fatal("other owner's HTTP history leaked")
|
||||
}
|
||||
list, e := s.store.FeedActionHistory(ctx, domain, other.UUID, store.FeedActionQuery{Source: source.UUID, Status: "all", Before: -1})
|
||||
if e != nil || len(list) != 0 {
|
||||
t.Fatal("other owner's actions leaked", list, e)
|
||||
}
|
||||
for request := range seen {
|
||||
if w := feedRequestTest(s, otherToken, "GET", "action/export?request_id="+request, nil); w.Code != 404 {
|
||||
t.Fatal("other owner's HTTP export", w.Code)
|
||||
}
|
||||
if _, e = s.store.FeedActionRecord(ctx, domain, other.UUID, request); !errors.Is(e, sql.ErrNoRows) {
|
||||
t.Fatal("other owner's receipt leaked", e)
|
||||
}
|
||||
break
|
||||
}
|
||||
if _, e = s.store.FeedActionHistory(ctx, uuid.NewString(), actor, store.FeedActionQuery{Status: "all", Before: -1}); !errors.Is(e, store.ErrAccessDenied) {
|
||||
t.Fatal("other domain", e)
|
||||
}
|
||||
for _, key := range []string{"actions", "action/export?request_id=" + uuid.NewString()} {
|
||||
if w := feedRequestTest(s, "", "GET", key, nil); w.Code != 401 {
|
||||
t.Fatal("anonymous access", w.Code)
|
||||
}
|
||||
}
|
||||
if w := feedRequestTest(s, token, "GET", "action/export?request_id=invalid", nil); w.Code != 422 {
|
||||
t.Fatal("invalid receipt identifier", w.Code)
|
||||
}
|
||||
if e = s.setSystemExtensionEnabled(domain, "organizer.feeds", false); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if w := feedRequestTest(s, token, "GET", "actions", nil); w.Code != 404 {
|
||||
t.Fatal("extension disabled", w.Code)
|
||||
}
|
||||
if _, e = s.store.FeedActionRecord(ctx, domain, actor, uuid.NewString()); !errors.Is(e, store.ErrAccessDenied) {
|
||||
t.Fatal("store disabled", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedHistoryReadonlyAndSourceDisabled(t *testing.T) {
|
||||
s, token, domain, actor, source := feedActionFixture(t)
|
||||
ctx := context.Background()
|
||||
a, e := s.store.QueueFeedAction(ctx, domain, actor, newFeedAction(source))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`UPDATE feed_actions SET status='unknown',until_ms=0 WHERE request_id=?`, a.RequestID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.store.SetPrincipalState(domain, actor, "readonly"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
token, e = s.store.CreateAuthSession(domain, actor)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
list, _ := feedHistoryResponse(t, s, token, "")
|
||||
if len(list) != 1 || list[0].CanCheck {
|
||||
t.Fatal("readonly check permission", list)
|
||||
}
|
||||
if w := feedRequestTest(s, token, "POST", "action/check", map[string]string{"request_id": a.RequestID}); w.Code != 403 {
|
||||
t.Fatal("readonly mutation", w.Code)
|
||||
}
|
||||
if w := feedRequestTest(s, token, "GET", "action/export?request_id="+a.RequestID, nil); w.Code != 200 {
|
||||
t.Fatal("readonly export", w.Code)
|
||||
}
|
||||
if e = s.store.SetPrincipalState(domain, actor, "active"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
token, e = s.store.CreateAuthSession(domain, actor)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
source.Credential, source.Enabled = "", false
|
||||
if _, e = s.store.SaveFeedSource(ctx, domain, actor, source); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
list, _ = feedHistoryResponse(t, s, token, "")
|
||||
if len(list) != 1 || list[0].CanCheck || !list[0].SourcePresent {
|
||||
t.Fatal("disabled source recheck", list)
|
||||
}
|
||||
}
|
||||
@@ -531,6 +531,18 @@ func TestFeedsChromium(t *testing.T) {
|
||||
t.Skip("opt-in Chromium")
|
||||
}
|
||||
s, token, domain, actor, source := feedFixture(t)
|
||||
if err := s.store.SetConfigInDomain(domain, "timezone", "Asia/Tokyo"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prefs, err := s.store.TaskPreferences(context.Background(), domain, actor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prefs.WikiPrefix = "/notes/{YYYY}/{MM}/{DD}/{Subject}"
|
||||
prefs.RSSLinkMode = "embedded"
|
||||
if _, err = s.store.SaveTaskPreferences(context.Background(), domain, actor, prefs, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claim, e := s.store.ClaimFeed(context.Background(), source)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
@@ -543,7 +555,12 @@ func TestFeedsChromium(t *testing.T) {
|
||||
if e = s.store.CompleteFeed(context.Background(), claim, items, "", "", "", false); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
fresh, e := s.store.SaveFeedSource(context.Background(), domain, actor, store.FeedSource{UUID: uuid.NewString(), Provider: "freshrss", Title: "FreshRSS fixture", URL: "https://example.org/api/greader.php", Enabled: true, Interval: 300})
|
||||
fresh := store.FeedSource{UUID: uuid.NewString(), Provider: "freshrss", Title: "FreshRSS fixture", URL: "https://example.org/api/greader.php", Enabled: true, Interval: 300}
|
||||
fresh.Credential, e = s.store.SealFeedCredential(domain, actor, fresh.UUID, "fixture", "synthetic")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
fresh, e = s.store.SaveFeedSource(context.Background(), domain, actor, fresh)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
@@ -564,7 +581,7 @@ func TestFeedsChromium(t *testing.T) {
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.store.CompleteFeed(context.Background(), claim, []store.FeedItem{{ID: "catalog-a", Title: "Catalog first", RemoteFeed: "feed/1", RemoteCategories: []string{"user/alice/label/Tech"}}, {ID: "catalog-b", Title: "Catalog second", RemoteFeed: "feed/2", RemoteCategories: []string{"user/alice/label/Other"}}}, "", "", "", false, catalog); e != nil {
|
||||
if e = s.store.CompleteFeed(context.Background(), claim, []store.FeedItem{{ID: "catalog-a", Title: "Catalog first", RemoteFeed: "feed/1", RemoteCategories: []string{"user/alice/label/Tech"}}, {ID: "catalog-b", Title: "Catalog second", RemoteFeed: "feed/2", RemoteCategories: []string{"user/alice/label/Other"}}}, "", "", "", false, store.FeedCatalogSnapshot{Subscriptions: catalog, Folders: []store.FeedCategory{{ID: "user/-/label/Empty/Folder", Label: "Empty/Folder"}}}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
s.store.BackgroundJobsDisabled = true
|
||||
@@ -577,6 +594,42 @@ func TestFeedsChromium(t *testing.T) {
|
||||
web := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Host = "localhost"
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
if r.URL.Path == "/fixture/embedded" {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
io.WriteString(w, `<h1>Isolated external article fixture</h1><script>parent.postMessage('rss-external-fixture-loaded','*')</script>`)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/fixture/run-feed-actions" && r.Method == "POST" {
|
||||
fake := &feedRemoteFake{id: "catalog-b"}
|
||||
if e := s.syncFeedActions(r.Context(), fake.client(t)); e != nil {
|
||||
http.Error(w, "test worker failed", 500)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/fixture/feed-history" && r.Method == "POST" {
|
||||
missing, orphan := uuid.NewString(), uuid.NewString()
|
||||
for _, entry := range []struct{ request, source, item string }{{missing, fresh.UUID, "history-evicted"}, {orphan, uuid.NewString(), `<img src=x onerror=alert(1)>`}} {
|
||||
if _, e := s.store.DB.Exec(`INSERT INTO feed_actions(domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,created_ms) VALUES(?,?,?,?,?,'read',1,1,'unknown',?)`, domain, actor, entry.request, entry.source, entry.item, time.Now().UnixMilli()); e != nil {
|
||||
t.Error(e)
|
||||
http.Error(w, "fixture insert failed", 500)
|
||||
return
|
||||
}
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]string{"missing": missing, "orphan": orphan})
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/fixture/check-feed-history" && r.Method == "POST" {
|
||||
fake := &feedRemoteFake{id: "history-evicted", read: true}
|
||||
if e := s.syncFeedActions(r.Context(), fake.client(t)); e != nil || fake.edits != 0 {
|
||||
t.Errorf("history read-only check: %v edits=%d", e, fake.edits)
|
||||
http.Error(w, "test recheck failed", 500)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/fixture" {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
fmt.Fprint(w, "<!doctype html><body style='margin:0'><script>"+string(script)+"</script></body>")
|
||||
@@ -586,6 +639,12 @@ func TestFeedsChromium(t *testing.T) {
|
||||
}))
|
||||
defer web.Close()
|
||||
for _, width := range []string{"1440", "390"} {
|
||||
if _, e = s.store.DB.Exec(`DELETE FROM feed_actions`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.DB.Exec(`UPDATE feed_items SET is_read=0 WHERE source_uuid=?`, fresh.UUID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
args := []string{"internal/server/testdata/vim-browser-smoke.mjs", web.URL + "/fixture?width=" + url.QueryEscape(width), t.TempDir(), "/tmp/pageswiki-feeds-" + width + ".png", width, "850"}
|
||||
out, e := exec.CommandContext(ctx, "node", args...).CombinedOutput()
|
||||
|
||||
@@ -20,11 +20,11 @@ import (
|
||||
"golang.org/x/net/html/atom"
|
||||
)
|
||||
|
||||
const htmlProjectionVersion = "controlled-v2"
|
||||
const htmlProjectionVersion = "controlled-v3"
|
||||
const maxProjectionInput = 1 << 20
|
||||
const maxProjectionOutput = 4 << 20
|
||||
|
||||
var projectionMacroRE = regexp.MustCompile(`\{\{(?:children[^}]*|(?:city-breadcrumbs|spot-pages|quartier|street|spot|nearby|city)(?:\s+[^}]*)?)\}\}`)
|
||||
var projectionMacroRE = regexp.MustCompile(`\{\{(?:csv:[^}]*|children[^}]*|(?:city-breadcrumbs|spot-pages|quartier|street|spot|nearby|city)(?:\s+[^}]*)?)\}\}`)
|
||||
var languageClassRE = regexp.MustCompile(`^language-[a-zA-Z0-9_+-]{1,40}$`)
|
||||
|
||||
func projectionPolicy(generated bool) *bluemonday.Policy {
|
||||
@@ -199,6 +199,8 @@ func (s *Server) safeHTMLProjection(r *http.Request, body, path string, expand b
|
||||
}
|
||||
var output strings.Builder
|
||||
macros, count := 0, 0
|
||||
csvCount := 0
|
||||
csvResults := map[string]string{}
|
||||
var emit func(*html.Node, int, bool) bool
|
||||
emit = func(n *html.Node, depth int, literal bool) bool {
|
||||
count++
|
||||
@@ -226,6 +228,14 @@ func (s *Server) safeHTMLProjection(r *http.Request, body, path string, expand b
|
||||
// be reparsed as a nested children request on its raw text.
|
||||
if isAnonymousProjection(r) {
|
||||
expanded = s.expandPublicMacro(r, macro, path)
|
||||
} else if strings.HasPrefix(macro, "{{csv:") {
|
||||
if cached, ok := csvResults[macro]; ok {
|
||||
expanded = cached
|
||||
} else if csvCount < 4 {
|
||||
csvCount++
|
||||
expanded = s.expandCSVMacro(r, macro)
|
||||
csvResults[macro] = expanded
|
||||
}
|
||||
} else if strings.HasPrefix(macro, "{{children") {
|
||||
expanded = s.expandChildrenMacros(macro, path)
|
||||
} else {
|
||||
@@ -236,6 +246,9 @@ func (s *Server) safeHTMLProjection(r *http.Request, body, path string, expand b
|
||||
// promote decoded entities into trusted generated elements.
|
||||
output.WriteString(stdhtml.EscapeString(macro))
|
||||
} else {
|
||||
if output.Len()+len(expanded) > maxProjectionOutput {
|
||||
return false
|
||||
}
|
||||
output.WriteString(expanded)
|
||||
}
|
||||
at = loc[1]
|
||||
|
||||
@@ -19,7 +19,7 @@ func NormalizePath(
|
||||
// Hosted adapter assets use directory-relative module and worker URLs.
|
||||
// DAV collections also require the slash: removing it conflicts with
|
||||
// ServeMux's collection redirect and causes an infinite redirect loop.
|
||||
if strings.HasPrefix(p, "/_/adaptor/") || strings.HasPrefix(p, "/_/api/v1/caldav/") || strings.HasPrefix(p, "/_/api/v1/carddav/") {
|
||||
if strings.HasPrefix(p, "/_/adaptor/") || strings.HasPrefix(p, "/_/api/v1/caldav/") || strings.HasPrefix(p, "/_/api/v1/carddav/") || strings.HasPrefix(p, "/_/api/v1/extension/organizer.feeds/browser/") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -24,3 +24,18 @@ func TestNormalizePathDAVCollections(t *testing.T) {
|
||||
t.Fatal("Wiki canonicalization changed", w.Code, w.Header())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizePathGeckoWebsocket(t *testing.T) {
|
||||
for _, path := range []string{"/_/api/v1/extension/organizer.feeds/browser/", "/_/api/v1/extension/organizer.feeds/browser/wisp/"} {
|
||||
w := httptest.NewRecorder()
|
||||
NormalizePath(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != path {
|
||||
t.Fatal(r.URL.Path)
|
||||
}
|
||||
w.WriteHeader(401)
|
||||
})).ServeHTTP(w, httptest.NewRequest("GET", path, nil))
|
||||
if w.Code != 401 || w.Header().Get("Location") != "" {
|
||||
t.Fatal("redirected browser endpoint", w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,8 @@ import (
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
geckoOnce sync.Once
|
||||
gecko *geckoProxy
|
||||
calendarOnce sync.Once
|
||||
calendarRepo *calendar.Repository
|
||||
calendarErr error
|
||||
@@ -351,7 +353,7 @@ func (s *Server) handler() http.Handler {
|
||||
domainHandler = h
|
||||
h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
background := r.URL.Query().Get("preview") == "1" ||
|
||||
strings.HasPrefix(r.URL.Path, "/v/preview-cache/")
|
||||
strings.HasPrefix(r.URL.Path, "/v/preview-cache/") || r.URL.Path == feedsAPI+"browser/wisp/"
|
||||
if !background {
|
||||
s.foregroundRequests.Add(1)
|
||||
defer s.foregroundRequests.Add(-1)
|
||||
|
||||
@@ -36,8 +36,9 @@ func (c *smtpLimitedConn) Read(buffer []byte) (int, error) {
|
||||
}
|
||||
|
||||
type magicLinkChallenge struct {
|
||||
Return string `json:"return"`
|
||||
Email string `json:"email"`
|
||||
Return string `json:"return"`
|
||||
Email string `json:"email"`
|
||||
Remember bool `json:"remember,omitempty"`
|
||||
}
|
||||
|
||||
func smtpMailbox(value string) (*mail.Address, error) {
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestTaskCaptureDeletedRecreation(t *testing.T) {
|
||||
for _, wiki := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(wiki), func(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
ctx := context.Background()
|
||||
id := uuid.NewString()
|
||||
input := map[string]any{"request_id": id, "title": "Original"}
|
||||
if wiki {
|
||||
input["wiki_body"], input["wiki_prefix"] = "Original private body", "/mail"
|
||||
}
|
||||
w := taskRequest(s, token, "POST", "capture", input, "")
|
||||
if w.Code != 201 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
var result struct {
|
||||
Item store.TaskRecord `json:"item"`
|
||||
Path string `json:"page_path"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, path := result.Item.PageUUID, result.Path
|
||||
var revision string
|
||||
if wiki {
|
||||
r, err := s.store.GetLatestRevision(page)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
revision = r.UUID
|
||||
}
|
||||
if w = taskRequest(s, token, "DELETE", "items/"+id, nil, `"1"`); w.Code != 204 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if w = taskRequest(s, token, "GET", "items/"+id, nil, ""); w.Code != 404 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
for _, title := range []string{"Original", "Changed"} {
|
||||
input["title"] = title
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 410 || !strings.Contains(w.Body.String(), `"deleted"`) {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
input["replaces_deleted"], input["request_id"] = id, store.TaskRecreationID(id)
|
||||
if wiki {
|
||||
input["wiki_body"] = "Must not overwrite the retained page"
|
||||
for _, invalidBody := range []string{"bad\x00body", strings.Repeat("x", 256<<10+1)} {
|
||||
input["wiki_body"] = invalidBody
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 422 {
|
||||
t.Fatal("reused page bypassed body validation", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
input["wiki_body"] = "Must not overwrite the retained page"
|
||||
}
|
||||
// A lost successful response, including concurrent retries, creates one
|
||||
// successor. It neither revives the original nor revises the Wiki.
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 4; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
v := taskRequest(s, token, "POST", "capture", input, "")
|
||||
if v.Code != 201 {
|
||||
t.Errorf("concurrent recreation: %d %s", v.Code, v.Body)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
w = taskRequest(s, token, "POST", "capture", input, "")
|
||||
if w.Code != 201 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Item.UUID != store.TaskRecreationID(id) || result.Item.UUID == id || result.Item.Title != "Changed" || result.Item.Version != 1 || result.Item.PageUUID != page || result.Path != path {
|
||||
t.Fatal(result)
|
||||
}
|
||||
if wiki {
|
||||
r, err := s.store.GetLatestRevision(page)
|
||||
if err != nil || r.UUID != revision || !strings.Contains(r.Body, "Original private body") {
|
||||
t.Fatal("Wiki changed", r, err)
|
||||
}
|
||||
}
|
||||
for table, expected := range map[string]int{"organizer_items": 1, "organizer_capture_receipts": 2, "organizer_task_deletions": 1, "organizer_revisions": 1} {
|
||||
var count int
|
||||
if err := s.store.DB.QueryRow("SELECT count(*) FROM " + table).Scan(&count); err != nil || count != expected {
|
||||
t.Fatal(table, count, err)
|
||||
}
|
||||
}
|
||||
if _, err := s.store.SaveTask(ctx, domain, actor, store.TaskRecord{UUID: id, Kind: "task", Title: "Offline resurrection", Status: "todo", Bucket: "inbox", Priority: 1}, 0); err != store.ErrTaskDeleted {
|
||||
t.Fatal("old UUID revived", err)
|
||||
}
|
||||
input["title"] = "Different committed recovery"
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 412 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
// Deleting the successor cannot be undone by replaying the recovery.
|
||||
if w = taskRequest(s, token, "DELETE", "items/"+result.Item.UUID, nil, `"1"`); w.Code != 204 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 410 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskCaptureRecreationGuards(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
id := uuid.NewString()
|
||||
input := map[string]any{"request_id": id, "title": "Original"}
|
||||
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
recreate := map[string]any{"request_id": store.TaskRecreationID(id), "replaces_deleted": id, "title": "New"}
|
||||
if w := taskRequest(s, token, "POST", "capture", recreate, ""); w.Code != 412 {
|
||||
t.Fatal("live capture replaced", w.Code, w.Body)
|
||||
}
|
||||
if w := taskRequest(s, token, "DELETE", "items/"+id, nil, `"1"`); w.Code != 204 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
other, err := s.store.CreatePasswordAccount(domain, "recreateother", "long fixture password", "Other", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
otherToken, err := s.store.CreateAuthSession(domain, other.UUID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := taskRequest(s, otherToken, "POST", "capture", recreate, ""); w.Code != 404 {
|
||||
t.Fatal("other owner", w.Code, w.Body)
|
||||
}
|
||||
if _, err := s.store.RecreateCapturedTask(context.Background(), "other-domain", actor, store.TaskRecreationID(id), "hash", newTaskRecord("task", "Wrong domain"), "", "", id); err != store.ErrAccessDenied {
|
||||
t.Fatal("wrong domain", err)
|
||||
}
|
||||
if err := s.store.SetPrincipalState(domain, actor, "readonly"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.store.RecreateCapturedTask(context.Background(), domain, actor, store.TaskRecreationID(id), "hash", newTaskRecord("task", "Readonly"), "", "", id); err != store.ErrAccessDenied {
|
||||
t.Fatal("readonly", err)
|
||||
}
|
||||
if err := s.store.SetPrincipalState(domain, actor, "active"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err = s.store.CreateAuthSession(domain, actor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.store.SetConfigInDomain(domain, "system_extension_states", `{"organizer.tasks":false}`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.store.RecreateCapturedTask(context.Background(), domain, actor, store.TaskRecreationID(id), "hash", newTaskRecord("task", "Disabled"), "", "", id); err != store.ErrAccessDenied {
|
||||
t.Fatal("extension disabled", err)
|
||||
}
|
||||
if err := s.store.SetConfigInDomain(domain, "system_extension_states", `{"organizer.tasks":true}`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, invalid := range []string{uuid.NewString(), id, "not-an-id"} {
|
||||
recreate["request_id"] = invalid
|
||||
if w := taskRequest(s, token, "POST", "capture", recreate, ""); w.Code != 422 {
|
||||
t.Fatal("arbitrary recovery ID", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
recreate["request_id"] = store.TaskRecreationID(id)
|
||||
// Failure during receipt insertion rolls back the task, page and journals.
|
||||
if _, err := s.store.DB.Exec(`CREATE TRIGGER reject_recreation BEFORE INSERT ON organizer_capture_receipts BEGIN SELECT RAISE(ABORT,'fixture rejection'); END`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recreate["wiki_body"], recreate["wiki_prefix"] = "New body", "/recreated"
|
||||
if w := taskRequest(s, token, "POST", "capture", recreate, ""); w.Code != 500 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
var count int
|
||||
if err := s.store.DB.QueryRow(`SELECT count(*) FROM organizer_items`).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatal("orphan task", count, err)
|
||||
}
|
||||
if err := s.store.DB.QueryRow(`SELECT count(*) FROM paths WHERE path LIKE '/recreated/%'`).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatal("orphan page", count, err)
|
||||
}
|
||||
if _, err := s.store.DB.Exec(`DROP TRIGGER reject_recreation`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := taskRequest(s, token, "POST", "capture", recreate, ""); w.Code != 201 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if _, err := s.store.GetTask(context.Background(), domain, actor, store.TaskRecreationID(id)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskCaptureOrphanReceipt(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
id := uuid.NewString()
|
||||
input := map[string]any{"request_id": id, "title": "Original"}
|
||||
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
// Simulate preexisting corruption, not a supported user deletion operation.
|
||||
if _, err := s.store.DB.Exec(`DELETE FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND uuid=?`, domain, actor, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, title := range []string{"Original", "Changed"} {
|
||||
input["title"] = title
|
||||
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 409 || !strings.Contains(w.Body.String(), "capture_missing") {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
input["request_id"], input["replaces_deleted"] = store.TaskRecreationID(id), id
|
||||
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 409 || !strings.Contains(w.Body.String(), "capture_missing") {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestTaskDeleteAPIAndDAVTombstone(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
ctx := context.Background()
|
||||
page, err := s.store.CreatePageAtPathInDomain(domain, "/delete-fixture-note")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task := newTaskRecord("task", "Delete fixture")
|
||||
task.PageUUID = page
|
||||
task.NotifyDue, task.DueOn = true, "2099-01-01"
|
||||
task, err = s.store.SaveTask(ctx, domain, actor, task, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
url := "items/" + task.UUID
|
||||
for _, test := range []struct {
|
||||
tag string
|
||||
status int
|
||||
}{{"", 428}, {`W/"1"`, 422}, {`"2"`, 412}} {
|
||||
w := taskRequest(s, token, "DELETE", url, nil, test.tag)
|
||||
if w.Code != test.status {
|
||||
t.Fatalf("precondition %s: %d %s", test.tag, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
w := taskRequest(s, token, "DELETE", url, nil, `"1"`)
|
||||
if w.Code != 204 {
|
||||
t.Fatalf("delete/retry: %d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
for _, suffix := range []string{url, url + "/history"} {
|
||||
if w := taskRequest(s, token, "GET", suffix, nil, ""); w.Code != 404 {
|
||||
t.Fatalf("deleted read: %d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
for _, view := range []string{"all", "archived", "done", "today"} {
|
||||
w := taskRequest(s, token, "GET", "items?view="+view, nil, "")
|
||||
if w.Code != 200 || strings.Contains(w.Body.String(), task.UUID) {
|
||||
t.Fatalf("deleted list %s: %d %s", view, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
for _, table := range []string{"organizer_items", "organizer_revisions", "organizer_reminders", "organizer_task_metrics"} {
|
||||
var count int
|
||||
if err := s.store.DB.QueryRow(`SELECT count(*) FROM ` + table).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("cleanup %s: %d %v", table, count, err)
|
||||
}
|
||||
}
|
||||
if id, err := s.store.ResolvePathInDomain(domain, "/delete-fixture-note"); err != nil || id != page {
|
||||
t.Fatal("Wiki note removed", id, err)
|
||||
}
|
||||
if _, err := s.store.SaveTask(ctx, domain, actor, task, 0); !errors.Is(err, store.ErrTaskDeleted) {
|
||||
t.Fatal("UUID recreated", err)
|
||||
}
|
||||
if _, _, err := s.store.PublishTaskActivity(ctx, 100); err != nil {
|
||||
t.Fatal("deleted head stalled outbox bridge", err)
|
||||
}
|
||||
for _, project := range []string{"", uuid.NewString()} {
|
||||
if project != "" {
|
||||
p := newTaskRecord("project", "Delete project fixture")
|
||||
p.UUID = project
|
||||
if _, err := s.store.SaveTask(ctx, domain, actor, p, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
davTask := newTaskRecord("task", "DAV fixture")
|
||||
davTask.ProjectUUID = project
|
||||
data := &store.TaskDAVData{Name: "client-fixture.ics", UID: "client-fixture-uid", Data: "fixture"}
|
||||
davTask, err = s.store.SaveTaskDAV(ctx, domain, actor, davTask, 0, data, "", project)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.store.DeleteTask(ctx, domain, actor, davTask.UUID, davTask.Version); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Simulate reopening/rebuilding the derived DAV indexes.
|
||||
if err = s.store.EnsureTasksSchema(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.store.TaskDAVByName(ctx, domain, actor, data.Name, project); !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatal("DAV deleted resource exposed", err)
|
||||
}
|
||||
items, err := s.store.TaskDAVList(ctx, domain, actor, project)
|
||||
if err != nil || len(items) != 0 {
|
||||
t.Fatal("DAV deleted resource listed", items, err)
|
||||
}
|
||||
for _, altered := range []string{"neither", "name", "uid"} {
|
||||
candidate := newTaskRecord("task", "Stale client PUT")
|
||||
candidate.ProjectUUID = project
|
||||
d := *data
|
||||
if altered == "name" {
|
||||
d.Name = "other.ics"
|
||||
}
|
||||
if altered == "uid" {
|
||||
d.UID = "other-uid"
|
||||
}
|
||||
if _, err := s.store.SaveTaskDAV(ctx, domain, actor, candidate, 0, &d, "", project); !errors.Is(err, store.ErrTaskDAVIdentity) {
|
||||
t.Fatalf("resurrection %s: %v", altered, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskDeleteGuardsAndAtomicity(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
ctx := context.Background()
|
||||
task, err := s.store.SaveTask(ctx, domain, actor, newTaskRecord("task", "Guarded fixture"), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other, err := s.store.CreatePasswordAccount(domain, "deleteother", "long fixture password", "Other", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.store.DeleteTask(ctx, domain, other.UUID, task.UUID, 1); !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatal("ownership", err)
|
||||
}
|
||||
if err := s.store.DeleteTask(ctx, "other-domain", actor, task.UUID, 1); !errors.Is(err, store.ErrAccessDenied) {
|
||||
t.Fatal("domain", err)
|
||||
}
|
||||
if err := s.store.SetPrincipalState(domain, actor, "readonly"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := taskRequest(s, token, "DELETE", "items/"+task.UUID, nil, `"1"`); w.Code != 401 {
|
||||
t.Fatal("readonly", w.Code, w.Body)
|
||||
}
|
||||
if err := s.store.DeleteTask(ctx, domain, actor, task.UUID, 1); !errors.Is(err, store.ErrAccessDenied) {
|
||||
t.Fatal("readonly store", err)
|
||||
}
|
||||
if err := s.store.SetPrincipalState(domain, actor, "active"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err = s.store.CreateAuthSession(domain, actor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.store.SetConfigInDomain(domain, "system_extension_states", `{"organizer.tasks":false}`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.store.DeleteTask(ctx, domain, actor, task.UUID, 1); !errors.Is(err, store.ErrAccessDenied) {
|
||||
t.Fatal("disabled", err)
|
||||
}
|
||||
if _, err := s.store.DB.Exec(`DELETE FROM config WHERE domain_uuid=? AND key='system_extension_states'`, domain); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
child := newTaskRecord("task", "Archived child")
|
||||
child.ParentUUID = task.UUID
|
||||
child.Archived = true
|
||||
child, err = s.store.SaveTask(ctx, domain, actor, child, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := taskRequest(s, token, "DELETE", "items/"+task.UUID, nil, `"1"`); w.Code != 409 || !strings.Contains(w.Body.String(), "has_children") {
|
||||
t.Fatal("children", w.Code, w.Body)
|
||||
}
|
||||
if err = s.store.DeleteTask(ctx, domain, actor, child.UUID, child.Version); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
focus, err := s.store.ChangeTaskFocus(ctx, domain, actor, "start", store.TaskFocus{UUID: uuid.NewString(), TaskUUID: task.UUID, Phase: "focus", DurationMS: 25 * 60 * 1000}, 0, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.store.DeleteTask(ctx, domain, actor, task.UUID, 1); !errors.Is(err, store.ErrTaskWorking) {
|
||||
t.Fatal("focus", err)
|
||||
}
|
||||
if _, err = s.store.ChangeTaskFocus(ctx, domain, actor, "cancel", focus, focus.Version, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
work, err := s.store.ChangeTaskWork(ctx, domain, actor, "start", store.TaskWork{UUID: uuid.NewString(), TaskUUID: task.UUID}, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.store.DeleteTask(ctx, domain, actor, task.UUID, 1); !errors.Is(err, store.ErrTaskWorking) {
|
||||
t.Fatal("running work", err)
|
||||
}
|
||||
if _, err = s.store.ChangeTaskWork(ctx, domain, actor, "stop", work, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Abort at the last delete step: neither a tombstone nor partial cleanup may remain.
|
||||
if _, err = s.store.DB.Exec(`CREATE TRIGGER fail_fixture_delete BEFORE DELETE ON organizer_items BEGIN SELECT RAISE(ABORT,'fixture failure'); END`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.store.DeleteTask(ctx, domain, actor, task.UUID, 1); err == nil {
|
||||
t.Fatal("injected failure ignored")
|
||||
}
|
||||
if _, err = s.store.GetTask(ctx, domain, actor, task.UUID); err != nil {
|
||||
t.Fatal("head not rolled back", err)
|
||||
}
|
||||
var n int
|
||||
if err = s.store.DB.QueryRow(`SELECT count(*) FROM organizer_task_deletions WHERE item_uuid=?`, task.UUID).Scan(&n); err != nil || n != 0 {
|
||||
t.Fatal("partial tombstone", n, err)
|
||||
}
|
||||
if _, err = s.store.DB.Exec(`DROP TRIGGER fail_fixture_delete`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task.Archived = true
|
||||
task, err = s.store.SaveTask(ctx, domain, actor, task, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := taskRequest(s, token, "DELETE", "items/"+task.UUID, nil, `"`+strconv.FormatInt(task.Version, 10)+`"`); w.Code != 204 {
|
||||
t.Fatal("archived deletion", w.Code, w.Body)
|
||||
}
|
||||
if err := s.store.DeleteTask(ctx, domain, other.UUID, task.UUID, task.Version); !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatal("tombstone ownership", err)
|
||||
}
|
||||
if _, err := s.store.SaveTask(ctx, domain, other.UUID, task, 0); !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatal("tombstone creation privacy", err)
|
||||
}
|
||||
if err := s.store.DB.QueryRow(`SELECT count(*) FROM organizer_work_sessions WHERE uuid=? AND end_ms>0`, work.UUID).Scan(&n); err != nil || n != 1 {
|
||||
t.Fatal("work history removed", n, err)
|
||||
}
|
||||
project, err := s.store.SaveTask(ctx, domain, actor, newTaskRecord("project", "Keep project"), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.store.DeleteTask(ctx, domain, actor, project.UUID, 1); !errors.Is(err, store.ErrTaskInvalid) {
|
||||
t.Fatal("project unexpectedly deleted", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskDeleteDAVHTTP(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
ctx := context.Background()
|
||||
auth, name := "Bearer "+token, "delete-client.ics"
|
||||
url := taskDAVCollection + name
|
||||
if w := davTaskRequest(s, auth, "PUT", url, taskICALFixture, nil); w.Code != 201 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
item, err := s.store.TaskDAVByName(ctx, domain, actor, name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := davTaskRequest(s, auth, "GET", url, "", nil)
|
||||
if before.Code != 200 {
|
||||
t.Fatal(before.Code, before.Body)
|
||||
}
|
||||
if err = s.store.DeleteTask(ctx, domain, actor, item.UUID, item.Version); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := davTaskRequest(s, auth, "GET", url, "", nil); w.Code != 404 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
query := `<c:calendar-query xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:d="DAV:"><d:prop><d:getetag/><c:calendar-data/></d:prop><c:filter><c:comp-filter name="VCALENDAR"><c:comp-filter name="VTODO"/></c:comp-filter></c:filter></c:calendar-query>`
|
||||
if w := davTaskRequest(s, auth, "REPORT", taskDAVCollection, query, nil); w.Code != 207 || strings.Contains(w.Body.String(), name) {
|
||||
t.Fatal("query", w.Code, w.Body)
|
||||
}
|
||||
multi := `<c:calendar-multiget xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:d="DAV:"><d:prop><d:getetag/><c:calendar-data/></d:prop><d:href>` + url + `</d:href></c:calendar-multiget>`
|
||||
if w := davTaskRequest(s, auth, "REPORT", taskDAVCollection, multi, nil); w.Code != 207 || !strings.Contains(w.Body.String(), "404 Not Found") {
|
||||
t.Fatal("multiget", w.Code, w.Body)
|
||||
}
|
||||
if w := davTaskRequest(s, auth, "PUT", url, taskICALFixture, map[string]string{"If-Match": before.Header().Get("ETag")}); w.Code != 412 {
|
||||
t.Fatal("stale conditional PUT", w.Code, w.Body)
|
||||
}
|
||||
if w := davTaskRequest(s, auth, "PUT", url, taskICALFixture, nil); w.Code != 403 || !strings.Contains(w.Body.String(), "no-uid-conflict") {
|
||||
t.Fatal("stale unconditional PUT", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
@@ -56,20 +56,21 @@ func applyTaskReminderDefaults(item *store.TaskRecord, p store.TaskPreferences)
|
||||
}
|
||||
|
||||
type taskCaptureInput struct {
|
||||
RequestID string `json:"request_id"`
|
||||
Title string `json:"title"`
|
||||
Notes string `json:"notes"`
|
||||
ProjectUUID *string `json:"project_uuid"`
|
||||
AssigneeUUID *string `json:"assignee_uuid"`
|
||||
DueOn *string `json:"due_on"`
|
||||
StartOn *string `json:"start_on"`
|
||||
PlannedOn *string `json:"planned_on"`
|
||||
ReviewOn *string `json:"review_on"`
|
||||
Estimate *int `json:"estimate_minutes"`
|
||||
Complexity *int `json:"complexity"`
|
||||
WikiBody *string `json:"wiki_body,omitempty"`
|
||||
WikiPrefix *string `json:"wiki_prefix,omitempty"`
|
||||
WikiSuffix *string `json:"wiki_suffix,omitempty"`
|
||||
ReplacesDeleted string `json:"replaces_deleted,omitempty"`
|
||||
RequestID string `json:"request_id"`
|
||||
Title string `json:"title"`
|
||||
Notes string `json:"notes"`
|
||||
ProjectUUID *string `json:"project_uuid"`
|
||||
AssigneeUUID *string `json:"assignee_uuid"`
|
||||
DueOn *string `json:"due_on"`
|
||||
StartOn *string `json:"start_on"`
|
||||
PlannedOn *string `json:"planned_on"`
|
||||
ReviewOn *string `json:"review_on"`
|
||||
Estimate *int `json:"estimate_minutes"`
|
||||
Complexity *int `json:"complexity"`
|
||||
WikiBody *string `json:"wiki_body,omitempty"`
|
||||
WikiPrefix *string `json:"wiki_prefix,omitempty"`
|
||||
WikiSuffix *string `json:"wiki_suffix,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request, actor string, active bool, kind string) {
|
||||
@@ -155,7 +156,7 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
|
||||
taskError(w, err)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"preferences": p, "defaults": defaultTask(p, time.Now().In(s.getLocation(domain))), "timezone": s.getTimezoneName(domain), "last_digest": last})
|
||||
writeEventJSON(w, 200, map[string]any{"preferences": p, "defaults": defaultTask(p, time.Now().In(s.getLocation(domain))), "timezone": s.getTimezoneName(domain), "last_digest": last, "gecko_available": s.geckoAvailable(domain)})
|
||||
return
|
||||
}
|
||||
if r.Method == "PUT" {
|
||||
@@ -197,6 +198,13 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
if input.ReplacesDeleted != "" {
|
||||
id, err := uuid.Parse(input.ReplacesDeleted)
|
||||
if err != nil || id.String() != input.ReplacesDeleted || input.RequestID != store.TaskRecreationID(input.ReplacesDeleted) {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(input)
|
||||
hash := sha256.Sum256(raw)
|
||||
requestHash := hex.EncodeToString(hash[:])
|
||||
@@ -256,11 +264,16 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
|
||||
writeEventJSON(w, 422, map[string]string{"error": "wiki_prefix_required"})
|
||||
return
|
||||
}
|
||||
if !store.ValidTaskWikiPrefix(prefix) {
|
||||
prefix, err = store.ExpandWikiPrefix(prefix, item.Title, time.Now().In(s.getLocation(domain)))
|
||||
if err != nil {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
target = store.TaskCaptureWikiPath(prefix, item.Title, input.RequestID)
|
||||
pathID := input.RequestID
|
||||
if input.ReplacesDeleted != "" {
|
||||
pathID = input.ReplacesDeleted
|
||||
}
|
||||
target = store.TaskCaptureWikiPath(prefix, item.Title, pathID)
|
||||
if input.WikiSuffix != nil {
|
||||
if !store.ValidTaskMailSuffix(*input.WikiSuffix) {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
@@ -279,7 +292,11 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
item, err = s.store.CaptureTaskWithWiki(r.Context(), domain, actor, input.RequestID, requestHash, item, target, body)
|
||||
if input.ReplacesDeleted != "" {
|
||||
item, err = s.store.RecreateCapturedTask(r.Context(), domain, actor, input.RequestID, requestHash, item, target, body, input.ReplacesDeleted)
|
||||
} else {
|
||||
item, err = s.store.CaptureTaskWithWiki(r.Context(), domain, actor, input.RequestID, requestHash, item, target, body)
|
||||
}
|
||||
if err != nil {
|
||||
taskError(w, err)
|
||||
return
|
||||
|
||||
@@ -62,6 +62,14 @@ func taskError(w http.ResponseWriter, err error) {
|
||||
status, code = 422, "invalid"
|
||||
case errors.Is(err, store.ErrTaskConflict):
|
||||
status, code = 412, "conflict"
|
||||
case errors.Is(err, store.ErrTaskCaptureMissing):
|
||||
status, code = 409, "capture_missing"
|
||||
case errors.Is(err, store.ErrTaskDeleted):
|
||||
status, code = 410, "deleted"
|
||||
case errors.Is(err, store.ErrTaskHasChildren):
|
||||
status, code = 409, "has_children"
|
||||
case errors.Is(err, store.ErrTaskWorking):
|
||||
status, code = 409, "working"
|
||||
case errors.Is(err, store.ErrTaskDAVIdentity):
|
||||
status, code = 409, "uid_conflict"
|
||||
case errors.Is(err, store.ErrTaskDAVRelocated):
|
||||
@@ -323,8 +331,30 @@ func (s *Server) handleTasksAPI(w http.ResponseWriter, r *http.Request) {
|
||||
writeEventJSON(w, 200, map[string]any{"items": items, "parents": parents, "next": next, "today": today})
|
||||
return
|
||||
}
|
||||
if r.Method == "DELETE" && id != "" {
|
||||
if !active {
|
||||
taskError(w, store.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
tag := r.Header.Get("If-Match")
|
||||
if tag == "" {
|
||||
writeEventJSON(w, 428, map[string]string{"error": "precondition"})
|
||||
return
|
||||
}
|
||||
expected, _ := strconv.ParseInt(strings.Trim(tag, `"`), 10, 64)
|
||||
if expected < 1 || tag != `"`+strconv.FormatInt(expected, 10)+`"` {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
if err := s.store.DeleteTask(ctx, domain, actor, id, expected); err != nil {
|
||||
taskError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
if (r.Method != "POST" || id != "") && (r.Method != "PUT" || id == "") {
|
||||
w.Header().Set("Allow", "GET, POST, PUT")
|
||||
w.Header().Set("Allow", "GET, POST, PUT, DELETE")
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
|
||||
+4
@@ -4,6 +4,10 @@
|
||||
if (phase === 'login') {
|
||||
const form = document.querySelector('form[action="/_/auth/login"]')
|
||||
assert(form, 'Login form missing')
|
||||
const remember = form.elements.remember
|
||||
assert(remember && !remember.checked, 'Trusted login must be opt-in')
|
||||
remember.checked = true
|
||||
remember.dispatchEvent(new Event('change', { bubbles: true }))
|
||||
form.elements.username.value = 'admin'
|
||||
form.elements.password.value = 'a long test password'
|
||||
sessionStorage.setItem('auth-flow-phase', 'authenticated')
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
(async()=>{
|
||||
const wait=async fn=>{for(let i=0;i<200;i++){if(fn())return;await new Promise(r=>setTimeout(r,30));}throw Error('Timeout '+fn);};
|
||||
const assert=(ok,msg)=>{if(!ok)throw Error(msg);};
|
||||
await wait(()=>document.querySelector('.browser-upload-queue'));
|
||||
const drop=(target,files)=>{const transfer=new DataTransfer();for(const [name,body]of files)transfer.items.add(new File([body],name,{type:'text/plain'}));const event=new DragEvent('drop',{bubbles:true,cancelable:true,dataTransfer:transfer});target.dispatchEvent(event);assert(event.defaultPrevented,'File drop did not prevent navigation');};
|
||||
const main=document.querySelector('.browser-main');
|
||||
drop(main,[['日本語 #1.txt','new file'],['existing.txt','must not replace'],['cancel.txt','not sent']]);
|
||||
const queued=[...document.querySelectorAll('.browser-upload-queue li')];queued[2].querySelector('button').click();
|
||||
drop(document.querySelector('.browser-row[data-path="/drop/sub"]'),[['nested.txt','nested']]);
|
||||
await wait(()=>document.querySelectorAll('.browser-upload-queue [data-state=done]').length===2&&document.querySelectorAll('.browser-upload-queue [data-state=failed]').length===1);
|
||||
await wait(()=>document.querySelector('.browser-row[data-path="/drop/日本語 #1.txt"]'));
|
||||
assert(document.querySelectorAll('.browser-upload-queue [data-state=cancelled]').length===1,'Cancellation missing');
|
||||
const card=document.querySelector('.browser-upload-queue'),rect=card.getBoundingClientRect();assert(getComputedStyle(card).position==='fixed'&&rect.right<=innerWidth&&rect.bottom<=innerHeight,'Queue not floating within viewport');
|
||||
const toggle=card.querySelector('[aria-controls]');toggle.click();assert(getComputedStyle(card.querySelector('ol')).display==='none','Queue collapse failed');toggle.click();
|
||||
assert(document.querySelectorAll('.browser-upload-queue progress[value="100"]').length===2,'Completion progress missing');
|
||||
document.body.dataset.vimReady='true';
|
||||
})().catch(e=>{const p=document.createElement('pre');p.id='error';p.textContent=e.stack;document.body.append(p);});
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import {spawn} from 'node:child_process';
|
||||
import {writeFile} from 'node:fs/promises';
|
||||
import {setTimeout as delay} from 'node:timers/promises';
|
||||
const [url,profile,screenshot,mode]=process.argv.slice(2);
|
||||
const browser=spawn('chromium',['--headless','--no-sandbox','--disable-gpu','--disable-background-networking','--no-proxy-server','--remote-debugging-port=0',`--user-data-dir=${profile}`,'about:blank']);
|
||||
process.on('SIGTERM',()=>{browser.kill();process.exit(1);});
|
||||
let socket,logs=[];
|
||||
try {
|
||||
const endpoint=await new Promise((resolve,reject)=>{let text='';browser.stderr.on('data',c=>{text+=c;const match=text.match(/DevTools listening on (ws:\/\/[^\s]+)/);if(match)resolve(match[1]);});browser.on('error',reject);browser.on('exit',code=>reject(Error('Browser exited '+code)));});
|
||||
socket=new WebSocket(endpoint);await new Promise((resolve,reject)=>{socket.onopen=resolve;socket.onerror=reject;});
|
||||
let id=0;const pending=new Map();
|
||||
socket.onmessage=e=>{const m=JSON.parse(e.data),p=pending.get(m.id);if(p){pending.delete(m.id);m.error?p.reject(Error(JSON.stringify(m.error))):p.resolve(m.result);}else if(['Runtime.exceptionThrown','Log.entryAdded','Runtime.consoleAPICalled'].includes(m.method))logs.push(JSON.stringify(m.params));};
|
||||
const send=(method,params={},sessionId)=>new Promise((resolve,reject)=>{pending.set(++id,{resolve,reject});socket.send(JSON.stringify({id,method,params,sessionId}));});
|
||||
const {targetId}=await send('Target.createTarget',{url:'about:blank'}),{sessionId}=await send('Target.attachToTarget',{targetId,flatten:true});
|
||||
const call=(method,params)=>send(method,params,sessionId);
|
||||
const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(JSON.stringify(r.exceptionDetails));return r.result.value;};
|
||||
const wait=async(expression,seconds=15)=>{for(let n=0;n<seconds*5;n++){if(await evaluate(expression))return;await delay(200);}if(screenshot){const {data}=await call('Page.captureScreenshot',{format:'png'});await writeFile(screenshot,Buffer.from(data,'base64'));}throw Error('Timeout: '+expression+'\n'+logs.slice(-30).join('\n'));};
|
||||
await call('Runtime.enable');await call('Log.enable');await call('Page.enable');
|
||||
// Only synthetic fixture diagnostics; production does not log article URLs.
|
||||
await call('Page.addScriptToEvaluateOnNewDocument',{source:`if(location.pathname.endsWith('/browser/'))import('/_/api/v1/extension/organizer.feeds/browser/assets/v0.0.1/gecko.js').then(({Gecko})=>{const init=Gecko.prototype.init;Gecko.prototype.init=function(){window.fixtureEngine=this;this.opts.printErr=console.warn;this.opts.print=console.log;return init.call(this);};});`});
|
||||
await call('Emulation.setDeviceMetricsOverride',{width:1280,height:850,deviceScaleFactor:1,mobile:false});await call('Page.navigate',{url});
|
||||
await wait(`document.querySelector('.feed-row')`);
|
||||
if(!await evaluate('crossOriginIsolated'))throw Error('Parent not isolated');
|
||||
await evaluate(`window.geckoReady=false;addEventListener('message',e=>{if(e.data?.type==='pageswiki-gecko'&&e.data.ready)geckoReady=true;});document.querySelector('.feed-row').click()`);
|
||||
await wait(`document.querySelector('.feed-original')`);await evaluate(`document.querySelector('.feed-original').click()`);
|
||||
await wait(`document.querySelector('.feed-external iframe')?.contentWindow.crossOriginIsolated`);
|
||||
if(mode==='startup-failure'){
|
||||
await wait(`document.querySelector('.feed-external [role=alert]')&&!document.querySelector('.feed-external iframe')`);
|
||||
if(!await evaluate(`document.querySelector('.feed-external a[target=_blank]').href==='http://fixture.invalid/first'`))throw Error('Failure lost original fallback');
|
||||
await evaluate(`document.querySelector('.feed-external').close()`);
|
||||
console.log('Gecko startup failure discarded iframe and retained original fallback');
|
||||
}else{
|
||||
await wait(`geckoReady || document.querySelector('.feed-external iframe')?.contentDocument?.querySelector('#status')?.textContent.includes('Viewer failed')`,100);
|
||||
if(!await evaluate('geckoReady'))throw Error('Gecko startup failed\n'+logs.slice(-8).join('\n'));
|
||||
if(mode==='public-https'){
|
||||
const engine=`document.querySelector('.feed-external iframe').contentWindow.fixtureEngine`;
|
||||
await wait(`(async()=>/documentation examples/i.test(String(await ${engine}.evalChrome('document.body.textContent'))))()`,30);
|
||||
await evaluate(`${engine}.load('https://expired.badssl.com/')`);
|
||||
await wait(`(async()=>/^about:(neterror|certerror)/.test(String(await ${engine}.evalChrome('String(document.documentURI)'))))()`,30);
|
||||
const location=await evaluate(`${engine}.evalChrome('String(document.documentURI)')`);
|
||||
if(!String(location).startsWith('about:neterror')&&!String(location).startsWith('about:certerror'))throw Error('Expired certificate was not rejected: '+location);
|
||||
await wait(`document.querySelector('.feed-external iframe').contentDocument.querySelector('canvas').hidden && document.querySelector('.feed-external iframe').contentDocument.querySelector('#status').textContent.length>20`);
|
||||
await evaluate(`document.querySelector('.feed-external').close()`);
|
||||
console.log('Public HTTPS example.com rendered; expired.badssl.com certificate rejected; closed');
|
||||
}else{
|
||||
const pixel=`(()=>{const c=document.querySelector('.feed-external iframe').contentDocument.querySelector('canvas');return Array.from(c.getContext('2d').getImageData(400,200,1,1).data)})()`;
|
||||
await wait(`${pixel}[0]===255 && ${pixel}[1]===0`);
|
||||
await evaluate(`document.querySelector('.feed-external button[title*="Ctrl+F"]').click();document.querySelector('.feed-gecko-find input').value='学舎の園';document.querySelector('.feed-gecko-find').requestSubmit()`);
|
||||
await wait(`(async()=>String(await document.querySelector('.feed-external iframe').contentWindow.fixtureEngine.evalChrome('String(window.getSelection())'))==='学舎の園')()`);
|
||||
await wait(`getComputedStyle(document.querySelector('.feed-gecko-find')).display==='flex'`);
|
||||
await evaluate(`document.querySelector('.feed-gecko-find input').value='missing-synthetic-word';document.querySelector('.feed-gecko-find').requestSubmit()`);
|
||||
await wait(`document.querySelector('.feed-gecko-find output').textContent.length>0`);
|
||||
await evaluate(`document.querySelector('.feed-gecko-find button:last-child').click()`);
|
||||
await wait(`getComputedStyle(document.querySelector('.feed-gecko-find')).display==='none'`);
|
||||
const rect=await evaluate(`(()=>{const r=document.querySelector('.feed-external iframe').getBoundingClientRect();return {x:r.x+100,y:r.y+50}})()`);
|
||||
await call('Input.dispatchMouseEvent',{type:'mousePressed',...rect,button:'left',buttons:1,clickCount:1});await call('Input.dispatchMouseEvent',{type:'mouseReleased',...rect,button:'left',buttons:0,clickCount:1});
|
||||
await wait(`${pixel}[0]===0 && ${pixel}[1]===255`);
|
||||
await wait(`document.querySelector('.feed-external a').href==='http://fixture.invalid/next'`);
|
||||
await evaluate(`[...document.querySelectorAll('.feed-external-bar button')].find(b=>b.textContent==='←').click()`);
|
||||
await wait(`${pixel}[0]===255 && ${pixel}[1]===0`);
|
||||
if(screenshot){const {data}=await call('Page.captureScreenshot',{format:'png'});await writeFile(screenshot,Buffer.from(data,'base64'));}
|
||||
await evaluate(`document.querySelector('.feed-external').close()`);await wait(`!document.querySelector('.feed-external')`);
|
||||
console.log('Real Gecko: isolation, Japanese find/missing match, Wisp article render, click navigation, viewer-local back and teardown passed');
|
||||
}
|
||||
}
|
||||
}finally{socket?.close();browser.kill();await new Promise(resolve=>browser.once('exit',resolve));await delay(300);}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import {memoryProfile} from '../../../static/js/feed-gecko-profile.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
const p=memoryProfile(10);
|
||||
await p.mkdir('cache');await p.writeFile('cache/a',new Uint8Array([1,2,3]));
|
||||
const copy=await p.readFile('cache/a');copy[0]=99;
|
||||
assert.equal((await p.readFile('cache/a'))[0],1);
|
||||
assert.deepEqual(await p.readdir(''),['cache/']);
|
||||
assert.deepEqual(await p.readdir('cache'),['a']);
|
||||
await p.rename('cache','new');assert.equal(await p.stat('cache'),null);
|
||||
assert.equal((await p.readFile('new/a')).length,3);
|
||||
await p.writeFile('b',new Uint8Array(5));await p.rename('new/a','b');
|
||||
await p.writeFile('c',new Uint8Array(7));
|
||||
await assert.rejects(p.writeFile('d',new Uint8Array(1)));
|
||||
for(const path of ['../secret','/absolute','new/../x','a\\b','a\0b'])await assert.rejects(p.stat(path));
|
||||
await p.unlink('b');await p.writeFile('d',new Uint8Array(3));
|
||||
assert.equal(await memoryProfile().stat('d'),null);
|
||||
console.log('Ephemeral profile bounds, isolation and rename passed');
|
||||
Vendored
+95
-7
@@ -4,12 +4,21 @@
|
||||
const frame=document.createElement('iframe');frame.style='display:block;width:100%;height:100vh;border:0';document.body.append(frame);
|
||||
try{
|
||||
await new Promise(resolve=>{frame.onload=resolve;frame.src='/v/feeds';});const d=frame.contentDocument,w=frame.contentWindow;
|
||||
// Let fixture requests finish before destroying a viewport's browser context.
|
||||
const fetch=w.fetch.bind(w);let pendingRequests=0;
|
||||
w.fetch=async(...args)=>{pendingRequests++;try{const response=await fetch(...args);await response.clone().arrayBuffer();return response;}finally{pendingRequests--;}};
|
||||
for(const key of Object.keys(w.localStorage))if(key.startsWith('pageswiki.feed-folders.v1:'))w.localStorage.removeItem(key);
|
||||
await wait(()=>d.querySelectorAll('.feed-row').length===100);
|
||||
const published=d.querySelector('.feed-published-time');assert(/^\d{2}:\d{2}$/.test(published.textContent),'Publication time missing');assert(published.title.includes('2026')&&published.title.includes('JST'),'Publication timezone/full tooltip missing');assert(w.getComputedStyle(published).display!=='none','Publication time hidden on mobile');assert(d.querySelector('.feed-row').children.length===5,'Publication time column missing');
|
||||
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'));const html=d.querySelector('#feed-reader .feed-body').shadowRoot;assert(html?.querySelector('h2')&&html.querySelector('table')&&html.querySelector('strong'),'HTML not rendered');assert(!html.querySelector('script,img,iframe,form'),'Active article HTML');assert(!w.rssAttack,'Script executed');assert(html.querySelector('a').target==='_blank','Article link target');assert(d.querySelector('.feed-original svg')&&!d.querySelector('.feed-original').textContent,'Original link not icon');
|
||||
const share=d.querySelector('.feed-share-x'),intent=new URL(share.href);assert(share.target==='_blank'&&share.rel.includes('noopener')&&intent.searchParams.get('url')==='https://example.org/article'&&intent.searchParams.get('text').includes('日本語のRSS記事')&&!intent.searchParams.get('text').includes('https://'),'RSS share URL or duplicate URL in text');
|
||||
assert(d.getElementById('feeds-app').dataset.linkMode==='embedded','Link preference missing');assert(!d.querySelector('.feed-external iframe'),'External page fetched before click');const externalURL=new URL('/fixture/embedded',w.location.href);externalURL.hostname='localhost';let externalLoaded=0;w.addEventListener('message',e=>{if(e.data==='rss-external-fixture-loaded'&&e.origin==='null')externalLoaded++;});const original=d.querySelector('.feed-original');original.href=externalURL.href;original.click();await wait(()=>d.querySelector('.feed-external[open] iframe'));await wait(()=>externalLoaded===1);let previewFrame=d.querySelector('.feed-external iframe');assert(previewFrame.src===externalURL.href&&previewFrame.getAttribute('sandbox')==='allow-scripts'&&previewFrame.referrerPolicy==='no-referrer','Unsafe external frame');assert(d.querySelector('.feed-external a').target==='_blank','Missing fallback');d.querySelector('.feed-external button').click();await wait(()=>!d.querySelector('.feed-external'));assert(d.querySelector('#feed-reader .feed-body'),'External preview lost article');const articleLink=html.querySelector('a');articleLink.href=externalURL.href;articleLink.click();await wait(()=>externalLoaded===2);d.querySelector('.feed-external').close();await wait(()=>!d.querySelector('.feed-external'));
|
||||
const help=d.getElementById('feed-help'),helpButton=d.querySelector('[aria-controls="feed-help"]'),key=k=>d.dispatchEvent(new w.KeyboardEvent('keydown',{key:k,bubbles:true}));
|
||||
d.getElementById('feed-status').textContent='Synthetic status';key('?');await wait(()=>!help.hidden);assert(helpButton.getAttribute('aria-expanded')==='true','Help toggle state');key('Escape');assert(help.hidden&&d.querySelector('.feed-layout').classList.contains('reading'),'Closing help changed reader');assert(d.getElementById('feed-status').textContent==='Synthetic status','Help erased status');key('?');await wait(()=>!help.hidden);key('?');await wait(()=>help.hidden);helpButton.click();await wait(()=>!help.hidden);help.querySelector('button').click();await wait(()=>help.hidden);assert(helpButton.getAttribute('aria-expanded')==='false','Help state not reset');d.getElementById('feed-status').textContent='';
|
||||
d.querySelectorAll('.feed-row')[1].click();await wait(()=>d.querySelector('#feed-reader .feed-body')&&!d.querySelector('#feed-reader .feed-body').shadowRoot);assert(d.querySelector('#feed-reader .feed-body').textContent.includes('<script>'),'Literal text not preserved');d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body')?.shadowRoot);
|
||||
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'*',bubbles:true}));await wait(()=>d.querySelector('.feed-row[aria-selected=true]').textContent.includes('★'));
|
||||
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'Escape',bubbles:true}));await wait(()=>!d.querySelector('.feed-layout').classList.contains('reading'));
|
||||
@@ -17,7 +26,8 @@
|
||||
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'/',bubbles:true}));await wait(()=>d.activeElement.type==='search');d.activeElement.value='119';d.activeElement.dispatchEvent(new w.Event('input',{bubbles:true}));await wait(()=>d.querySelectorAll('.feed-row').length===1);
|
||||
d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body'));
|
||||
d.querySelector('#feed-reader .feed-actions button:last-child').click();await wait(()=>d.querySelector('#feed-reader form'));
|
||||
const form=d.querySelector('#feed-reader form'),inputs=form.querySelectorAll('input');inputs[2].value='/notes/feed-ui';inputs[2].dispatchEvent(new w.Event('input'));inputs[5].checked=true;form.requestSubmit();await wait(()=>d.querySelector('#feed-reader a[href^="/v/uuid:"]'));
|
||||
assert(!['rgba(0, 0, 0, 0)','transparent'].includes(w.getComputedStyle(d.querySelector('.feed-capture')).backgroundColor),'Capture dialog background transparent');
|
||||
const form=d.querySelector('#feed-reader form'),inputs=form.querySelectorAll('input');assert(inputs[2].value==='/notes/{YYYY}/{MM}/{DD}/{Subject}','Wiki default not filled');assert(form.closest('dialog').open&&d.querySelector('#feed-reader .feed-body'),'Capture replaced article');assert(form.querySelector('a[href="/-/sys/config?panel=organizer"]'),'Default settings link missing');await wait(()=>form.querySelector('output').textContent.includes('/rss-'));assert(!form.querySelector('output').textContent.includes('{'),'Template not expanded');inputs[2].value='/notes/feed-ui';inputs[2].dispatchEvent(new w.Event('input'));await wait(()=>form.querySelector('output').textContent.startsWith('/notes/feed-ui/rss-'));inputs[5].checked=true;form.requestSubmit();await wait(()=>d.querySelector('#feed-reader a[href^="/v/uuid:"]'));d.querySelector('.feed-capture button').click();await wait(()=>!d.querySelector('.feed-capture'));assert(d.querySelector('#feed-reader .feed-body'),'Closing capture lost article');
|
||||
const search=d.querySelector('#feed-toolbar input');search.value='';search.dispatchEvent(new w.Event('input',{bubbles:true}));await wait(()=>d.querySelectorAll('.feed-row').length===100);d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body'));
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'Reader overflow');
|
||||
d.getElementById('feed-opml').click();await wait(()=>d.getElementById('feed-opml-file'));
|
||||
@@ -27,13 +37,91 @@
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'OPML overflow');d.querySelector('.feed-import-options input[type=checkbox]').checked=false;d.getElementById('feed-opml-preview').requestSubmit();await wait(()=>!d.getElementById('feed-opml-preview'));
|
||||
assert(d.getElementById('feed-sources').textContent.includes('Import '+w.innerWidth),'Imported source missing');d.getElementById('feed-opml').click();await wait(()=>d.getElementById('feed-opml-file'));choose();await wait(()=>d.querySelectorAll('#feed-opml-preview tbody tr').length===3);assert(d.querySelector('#feed-opml-preview tbody input').disabled,'Duplicate after import');
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'OPML preview overflow');
|
||||
[...d.querySelectorAll('.feed-source>button:first-child')].find(b=>b.textContent==='FreshRSS fixture').click();await wait(()=>d.querySelectorAll('.feed-subscriptions button').length===4&&d.querySelectorAll('.feed-row').length===2);
|
||||
const category=d.getElementById('feed-category');category.value='user/alice/label/Tech';category.dispatchEvent(new w.Event('change'));await wait(()=>d.querySelectorAll('.feed-row').length===1&&d.querySelector('.feed-row').textContent.includes('Catalog first'));
|
||||
assert(d.querySelectorAll('.feed-subscriptions button').length===2,'Category navigation');
|
||||
d.getElementById('feed-category').value='';d.getElementById('feed-category').dispatchEvent(new w.Event('change'));await wait(()=>d.querySelectorAll('.feed-row').length===2);
|
||||
const freshButton=()=>[...d.querySelectorAll('.feed-source>button:first-child')].find(b=>b.textContent==='FreshRSS fixture');freshButton().click();await wait(()=>d.querySelectorAll('.feed-folder').length===4&&d.querySelectorAll('.feed-row').length===2);
|
||||
const folder=id=>[...d.querySelectorAll('.feed-folder')].find(n=>n.dataset.category===id),tech=()=>folder('user/alice/label/Tech');
|
||||
const folderKey=(key,target=d,extra={})=>target.dispatchEvent(new w.KeyboardEvent('keydown',{key,shiftKey:true,bubbles:true,cancelable:true,...extra}));
|
||||
const activeFolder=()=>d.querySelector('.feed-folder-name[aria-current="true"]');
|
||||
const folderNames=()=>[...d.querySelectorAll('.feed-folder-name')];
|
||||
assert(help.textContent.includes('Shift+j/k'),'Folder shortcuts missing from help');
|
||||
// All subscriptions has no folder: start at either end, including empty/uncategorized.
|
||||
folderKey('K');await wait(()=>activeFolder()===folderNames().at(-1)&&d.querySelectorAll('.feed-row').length===0);
|
||||
folderKey('J');await delay(80);assert(activeFolder()===folderNames().at(-1),'Folder navigation wrapped past end');
|
||||
folderKey('K');await wait(()=>activeFolder()===tech().querySelector('.feed-folder-name')&&d.querySelector('.feed-row')?.textContent.includes('Catalog first'));
|
||||
assert(tech().querySelector('.feed-folder-toggle').getAttribute('aria-expanded')==='false','Keyboard navigation expanded folder');
|
||||
folderKey('k');await wait(()=>activeFolder()===folderNames()[1]&&d.querySelector('.feed-row')?.textContent.includes('Catalog second'));
|
||||
folderKey('K');await wait(()=>activeFolder()===folderNames()[0]&&d.querySelectorAll('.feed-row').length===0);
|
||||
folderKey('K');await delay(80);assert(activeFolder()===folderNames()[0],'Folder navigation wrapped before start');
|
||||
const articleFilter=d.querySelector('#feed-toolbar select');articleFilter.value='starred';articleFilter.dispatchEvent(new w.Event('change'));await delay(80);
|
||||
folderKey('J');await wait(()=>activeFolder()===folderNames()[1]);await delay(80);assert(articleFilter.value==='starred'&&d.querySelectorAll('.feed-row').length===0,'Folder navigation lost starred filter');
|
||||
articleFilter.value='';articleFilter.dispatchEvent(new w.Event('change'));await wait(()=>d.querySelector('.feed-row')?.textContent.includes('Catalog second'));
|
||||
folderKey('K');await wait(()=>activeFolder()===folderNames()[0]&&d.querySelectorAll('.feed-row').length===0);
|
||||
const keep=activeFolder();for(const extra of [{ctrlKey:true},{metaKey:true},{altKey:true},{isComposing:true}])folderKey('J',d,extra);
|
||||
const catalogFind=d.querySelector('.feed-catalog input');folderKey('J',catalogFind);
|
||||
const editable=d.createElement('div');editable.setAttribute('contenteditable','');editable.innerHTML='<span>editing</span>';d.body.append(editable);folderKey('J',editable.firstChild);editable.remove();
|
||||
await delay(80);assert(activeFolder()===keep,'Modifier or editable input triggered folder shortcut');
|
||||
// Preserve article filters while moving from a selected subscription to the next folder.
|
||||
tech().querySelector('.feed-folder-toggle').click();await wait(()=>tech().querySelector('[data-feed="feed/1"]'));
|
||||
tech().querySelector('[data-feed="feed/1"]').click();await wait(()=>d.querySelector('.feed-row')?.textContent.includes('Catalog first'));
|
||||
const globalSearch=d.querySelector('#feed-toolbar input');globalSearch.value='Catalog';globalSearch.dispatchEvent(new w.Event('input',{bubbles:true}));await delay(220);
|
||||
folderKey('H');await wait(()=>activeFolder()===tech().querySelector('.feed-folder-name'));
|
||||
folderKey('K');await wait(()=>activeFolder()===folderNames()[1]&&d.querySelector('.feed-row')?.textContent.includes('Catalog second'));
|
||||
assert(globalSearch.value==='Catalog'&&!d.querySelector('button[data-feed][aria-current="true"]'),'Folder navigation lost search or kept subscription filter');
|
||||
d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body'));
|
||||
const selectedTitle=d.querySelector('#feed-reader h1').textContent;
|
||||
d.querySelector('#feed-reader .feed-actions button:last-child').click();await wait(()=>d.querySelector('.feed-capture[open]'));
|
||||
folderKey('J');await delay(80);assert(activeFolder()===folderNames()[1]&&d.querySelector('#feed-reader h1').textContent===selectedTitle,'Shortcut escaped capture modal');
|
||||
d.querySelector('.feed-capture').close();await wait(()=>!d.querySelector('.feed-capture'));
|
||||
folderKey('J');await wait(()=>activeFolder()===tech().querySelector('.feed-folder-name')&&d.querySelector('.feed-row')?.textContent.includes('Catalog first'));
|
||||
assert(!d.querySelector('.feed-layout').classList.contains('reading')&&!d.querySelector('#feed-reader .feed-body'),'Folder navigation left old article open');
|
||||
const currentCatalogFind=d.querySelector('.feed-catalog input');currentCatalogFind.value='Other';currentCatalogFind.dispatchEvent(new w.Event('input',{bubbles:true}));assert(!activeFolder(),'Catalog filter setup');
|
||||
folderKey('K');await wait(()=>activeFolder()===folderNames()[1]&&d.querySelector('.feed-row')?.textContent.includes('Catalog second'));
|
||||
assert(d.querySelector('.feed-catalog input').value==='','Folder navigation left selected folder hidden by catalog filter');
|
||||
globalSearch.value='';globalSearch.dispatchEvent(new w.Event('input',{bubbles:true}));await delay(220);
|
||||
// Rapid repeats must settle on the latest folder rather than an older request.
|
||||
folderKey('J');folderKey('J');folderKey('K');await wait(()=>activeFolder()===tech().querySelector('.feed-folder-name')&&d.querySelector('.feed-row')?.textContent.includes('Catalog first'));await delay(100);
|
||||
assert(d.querySelectorAll('.feed-row').length===1&&d.querySelector('.feed-row').textContent.includes('Catalog first'),'Stale folder request won');
|
||||
// Horizontal hierarchy navigation, with unchanged article filters and bounded siblings.
|
||||
folderKey('L');await wait(()=>tech().querySelector('button[data-feed="feed/1"][aria-current="true"]'));
|
||||
assert(tech().querySelector('.feed-folder-toggle').getAttribute('aria-expanded')==='true','L did not expand folder');
|
||||
folderKey('L');folderKey('J');folderKey('K');await delay(80);
|
||||
assert(tech().querySelector('button[data-feed="feed/1"][aria-current="true"]'),'Leaf keys escaped the current folder');
|
||||
folderKey('H');await wait(()=>activeFolder()===tech().querySelector('.feed-folder-name'));
|
||||
folderKey('H');await wait(()=>d.querySelector('.feed-tree-all[aria-current="true"]'));
|
||||
assert(tech().querySelector('.feed-folder-toggle').getAttribute('aria-expanded')==='false','H did not collapse folder');
|
||||
folderKey('H');await delay(80);assert(d.querySelector('.feed-tree-all[aria-current="true"]'),'H escaped catalog root');
|
||||
folderKey('L');await wait(()=>activeFolder()===folderNames()[0]);
|
||||
folderKey('L');await delay(80);assert(activeFolder()===folderNames()[0]&&!folderNames()[0].closest('.feed-folder').querySelector('button[data-feed]'),'L fabricated an empty-folder child');
|
||||
tech().querySelector('.feed-folder-name').click();await wait(()=>activeFolder()===tech().querySelector('.feed-folder-name'));
|
||||
tech().querySelector('.feed-folder-name').click();await wait(()=>d.querySelectorAll('.feed-row').length===1&&d.querySelector('.feed-row').textContent.includes('Catalog first'));
|
||||
assert(tech().querySelector('.feed-folder-toggle').getAttribute('aria-expanded')==='false','Selecting folder expands it unexpectedly');tech().querySelector('.feed-folder-toggle').click();await wait(()=>tech().querySelector('button[data-feed="feed/1"]'));
|
||||
const empty=folder('user/-/label/Empty/Folder');assert(empty.querySelector('.feed-folder-name span').textContent==='Empty/Folder','Slash label split');empty.querySelector('.feed-folder-toggle').click();assert(!empty.querySelector('button[data-feed]'),'Empty folder fabricated a feed');empty.querySelector('.feed-folder-name').click();await wait(()=>d.querySelectorAll('.feed-row').length===0);
|
||||
d.querySelector('.feed-folder[data-mode="uncategorized"] .feed-folder-name').click();await wait(()=>d.querySelectorAll('.feed-row').length===0);
|
||||
d.querySelector('.feed-catalog .feed-tree-all').click();await wait(()=>d.querySelectorAll('.feed-row').length===2);
|
||||
[...d.querySelectorAll('.feed-source>button:first-child')].find(b=>b.textContent==='Synthetic news').click();await wait(()=>!d.querySelector('.feed-catalog'));freshButton().click();await wait(()=>tech()?.querySelector('button[data-feed="feed/1"]'));assert(tech().querySelector('.feed-folder-toggle').getAttribute('aria-expanded')==='true','Folder expansion not retained');
|
||||
folder('user/alice/label/Other').querySelector('.feed-folder-toggle').click();await wait(()=>d.querySelector('.feed-subscriptions button[data-feed="feed/2"]'));
|
||||
d.querySelector('.feed-subscriptions button[data-feed="feed/2"]').click();await wait(()=>d.querySelectorAll('.feed-row').length===1&&d.querySelector('.feed-row').textContent.includes('Catalog second'));
|
||||
d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body'));assert(d.querySelectorAll('#feed-reader .feed-actions button:disabled').length===2,'FreshRSS not read-only');
|
||||
if(w.innerWidth<=600)d.querySelector('#feed-toolbar button').click();
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'Catalog overflow');document.body.dataset.vimReady='1';
|
||||
[...d.querySelectorAll('.feed-source')].find(n=>n.textContent.includes('FreshRSS fixture')).querySelector('button:last-child').click();await wait(()=>d.querySelector('#feed-reader form'));
|
||||
const setting=d.querySelector('#feed-reader form');setting.querySelectorAll('input[type=checkbox]')[1].checked=true;setting.requestSubmit();await wait(()=>!d.querySelector('#feed-reader form')&&d.querySelectorAll('.feed-row').length===1);
|
||||
d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body')&&!d.querySelectorAll('#feed-reader .feed-actions button')[1].disabled);
|
||||
d.querySelectorAll('#feed-reader .feed-actions button')[1].click();await wait(()=>d.querySelector('.feed-action-status')?.textContent==='◷');assert(d.querySelector('.feed-row').classList.contains('unread'),'Queued state shown as confirmed');
|
||||
const run=await w.fetch('/fixture/run-feed-actions',{method:'POST'});assert(run.status===204,'Background worker failed');await wait(()=>d.querySelector('.feed-action-status')?.textContent==='✓');assert(!d.querySelector('.feed-row').classList.contains('unread'),'Confirmed state not reflected');
|
||||
// Restore the synthetic source to read-only for the second viewport run.
|
||||
const api='/_/api/v1/extension/organizer.feeds/',source=(await (await w.fetch(api+'sources')).json()).sources.find(s=>s.title==='FreshRSS fixture');
|
||||
await w.fetch(api+'sources',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({uuid:source.uuid,version:source.version,provider:source.provider,title:source.title,folder:source.folder,url:source.url,interval_seconds:source.interval_seconds,enabled:true,write_enabled:false})});
|
||||
const seed=await (await w.fetch('/fixture/feed-history',{method:'POST'})).json();
|
||||
d.getElementById('feed-history').click();await wait(()=>d.querySelectorAll('#feed-history-panel tbody tr').length===2);
|
||||
const receipt=id=>d.querySelector('#feed-history-panel tr[data-request-id="'+id+'"]');
|
||||
assert(d.querySelector('.feed-layout').classList.contains('action-history'),'History full panel');assert(!receipt(seed.missing).querySelector('.feed-history-check').disabled,'Evicted item check unavailable');assert(receipt(seed.orphan).querySelector('.feed-history-check').disabled,'Deleted source check available');assert(!receipt(seed.orphan).querySelector('img'),'Untrusted ID rendered as HTML');
|
||||
const exported=await (await w.fetch(receipt(seed.orphan).querySelector('.feed-history-export').href)).json();assert(exported.format==='pageswiki.feed-action'&&exported.action.request_id===seed.orphan&&!exported.action.source_present,'Orphan receipt export');
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'History overflow');
|
||||
receipt(seed.missing).querySelector('.feed-history-check').click();await wait(()=>receipt(seed.missing)?.querySelector('[data-state=check_queued]'));
|
||||
assert((await w.fetch('/fixture/check-feed-history',{method:'POST'})).status===204,'Recheck worker failed');d.getElementById('feed-history-reload').click();await wait(()=>!receipt(seed.missing)&&receipt(seed.orphan));
|
||||
const hs=d.getElementById('feed-history-state');hs.value='all';hs.dispatchEvent(new w.Event('change'));await wait(()=>receipt(seed.missing)?.querySelector('[data-state=confirmed]'));
|
||||
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'Escape',bubbles:true}));assert(!d.querySelector('.feed-layout').classList.contains('action-history'),'History escape');
|
||||
const previousHistory=d.getElementById('feed-history-panel');d.getElementById('feed-history').click();await wait(()=>d.getElementById('feed-history-panel')!==previousHistory&&receipt(seed.orphan));d.getElementById('feed-history-state').value='all';d.getElementById('feed-history-state').dispatchEvent(new w.Event('change'));await wait(()=>receipt(seed.missing)?.querySelector('[data-state=confirmed]'));
|
||||
assert(d.documentElement.scrollWidth<=w.innerWidth,'History final overflow');
|
||||
const probe=document.createElement('iframe');probe.hidden=true;document.body.append(probe);await new Promise(resolve=>{probe.onload=resolve;probe.src='/v/feeds?source='+encodeURIComponent(source.uuid);});await wait(()=>probe.contentDocument.querySelector('.feed-folder[data-category="user/alice/label/Tech"] .feed-folder-toggle')?.getAttribute('aria-expanded')==='true'&&probe.contentDocument.querySelectorAll('.feed-row').length===2);probe.remove();
|
||||
const previousCatalog=d.querySelector('.feed-catalog');freshButton().click();await wait(()=>d.querySelector('.feed-catalog')!==previousCatalog&&tech()?.querySelector('button[data-feed="feed/1"]')&&d.querySelectorAll('.feed-row').length===2);if(w.innerWidth<=700){d.querySelector('#feed-toolbar button').click();await wait(()=>d.querySelector('.feed-layout').classList.contains('sources-open'));assert(w.getComputedStyle(d.getElementById('feed-sources')).display!=='none','Mobile folders hidden');}assert(d.documentElement.scrollWidth<=w.innerWidth,'Folder tree overflow');await wait(()=>pendingRequests===0);await delay(100);document.body.dataset.vimReady='1';
|
||||
}catch(e){const out=document.createElement('pre');out.id='error';out.textContent=e.stack;document.body.append(out);}
|
||||
})();
|
||||
@@ -40,6 +40,8 @@ window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<12
|
||||
}else if(path==='/v/plan/dashboard'){
|
||||
await wait(()=>document.querySelectorAll('.productivity-day').length>300);if(!document.querySelector('.productivity-day[data-level="2"]'))throw Error('Seven-point completion missing');
|
||||
if(document.querySelectorAll('[data-widget]').length!==6)throw Error('Widget registry missing');
|
||||
await wait(()=>document.querySelector('[data-widget=progress] .dashboard-progress'));
|
||||
if(document.querySelector('[data-widget=progress] .widget-body small'))throw Error('Completion widget explanation should not be displayed');
|
||||
const tab=document.querySelector('[data-tab=done]');tab.click();await wait(()=>document.querySelector('#widget-panel-tasks').textContent.includes('Browser work task'));if(location.pathname!=='/v/plan/dashboard'||document.querySelector('#organizer-dashboard iframe'))throw Error('Tab navigation escaped widget');
|
||||
document.querySelector('#dashboard-controls button[aria-pressed]').click();const width=document.querySelector('[data-widget=tasks] [data-size=width]');width.value='6';width.dispatchEvent(new Event('change'));const height=document.querySelector('[data-widget=tasks] [data-size=height]');height.value='5';height.dispatchEvent(new Event('change'));
|
||||
document.querySelector('[data-widget=tasks] .widget-arrange button').click();document.querySelector('#dashboard-controls button:last-child').click();await wait(()=>document.querySelector('#dashboard-status').textContent.includes('保存しました'));const layout=await fetch('/_/api/v1/extension/organizer.tasks/dashboard').then(r=>r.json());if(layout.widgets[2].id!=='tasks'||layout.widgets[2].width!==6||layout.widgets[2].height!==5||layout.widgets[2].tab!=='done')throw Error('Layout did not persist');
|
||||
|
||||
+32
@@ -130,6 +130,38 @@ window.addEventListener('load', async () => {
|
||||
document.body.dataset.vimReady='true';return;
|
||||
}
|
||||
await wait(()=>$('status').textContent.includes('ありません'));
|
||||
// Deletion shares the archive footer, not a UUID-search workflow.
|
||||
$('new').click();await wait(()=>document.querySelector('#tasks-form [name=title]'));
|
||||
if(!$('delete').hidden)throw Error('Unsaved task must not offer deletion');if(!$('page-open').hidden||$('page-open').hasAttribute('href'))throw Error('New task leaked a related page');$('close').click();
|
||||
$('quick-title').value='Disposable deletion fixture';$('capture').requestSubmit();
|
||||
await wait(()=>$('list').querySelector('[data-action=detail]'));$('list').querySelector('[data-action=detail]').click();
|
||||
await wait(()=>!$('delete').hidden);
|
||||
if($('delete').parentElement!==$('archive').parentElement||$('delete').textContent!=='削除')throw Error('Delete action is not beside archive');
|
||||
const deletionID=$('list').querySelector('[data-task-id]').dataset.taskId;
|
||||
window.confirm=()=>false;$('delete').click();
|
||||
if(!$('dialog').open)throw Error('Cancelled deletion closed the editor');
|
||||
const deletionAPI='/_/api/v1/extension/organizer.tasks/items/'+deletionID;
|
||||
const deletionItem=(await fetch(deletionAPI).then(r=>r.json())).item;
|
||||
if(!$('page-open').hidden)throw Error('Unlinked task offered related page');
|
||||
// The footer link uses the saved, authorized path, never unsaved input.
|
||||
value('page_path','/projects/browser');$('form').requestSubmit();await wait(()=>!$('dialog').open);
|
||||
$('list').querySelector('[data-action=detail]').click();await wait(()=>!$('page-open').hidden);
|
||||
const link=$('page-open');if(link.parentElement!==$('save').parentElement||link.pathname!=='/projects/browser'||link.target!=='_blank'||!link.rel.includes('noopener'))throw Error('Unsafe or misplaced related page navigation');
|
||||
value('title','Unsaved title kept');if(link.hidden||!$('dialog').open)throw Error('Editing task hid the saved page navigation');
|
||||
if(innerWidth<761&&link.getBoundingClientRect().height<44)throw Error('Related page touch target too small');
|
||||
document.querySelector('.task-editor-advanced').open=true;
|
||||
value('page_path','//external.invalid/unsaved');if(!link.hidden||link.hasAttribute('href'))throw Error('Unsaved path exposed a link');
|
||||
value('page_path','/projects/browser');if(link.hidden)throw Error('Restored path did not restore related link');
|
||||
window.confirm=()=>true;$('close').click();$('list').querySelector('[data-action=detail]').click();await wait(()=>!$('page-open').hidden);
|
||||
const freshDeletionItem=(await fetch(deletionAPI).then(r=>r.json())).item;
|
||||
const changed=await fetch(deletionAPI,{method:'PUT',headers:{'Content-Type':'application/json','If-Match':'"'+freshDeletionItem.version+'"'},body:JSON.stringify({...freshDeletionItem,title:'Updated deletion fixture'})});
|
||||
if(!changed.ok)throw Error('Deletion conflict fixture failed');
|
||||
window.confirm=()=>true;$('delete').click();await wait(()=>$('error').textContent.includes('別の画面'));
|
||||
if(!$('dialog').open||$('delete').disabled)throw Error('Deletion failure did not keep a usable editor');
|
||||
$('close').click();$('refresh').click();await wait(()=>$('list').querySelector('input[name=title]')?.value==='Updated deletion fixture');
|
||||
$('list').querySelector('[data-action=detail]').click();await wait(()=>!$('delete').hidden);$('delete').click();
|
||||
await wait(()=>!$('dialog').open&&!$('list').querySelector('[data-task-id]'));
|
||||
if((await fetch(deletionAPI)).status!==404)throw Error('Deleted task remains readable');
|
||||
$('quick-title').value='Write the first task';$('capture').requestSubmit();
|
||||
await wait(()=>$('list').querySelector('[data-action=detail]'));
|
||||
$('list').querySelector('[data-action=detail]').click();
|
||||
|
||||
@@ -39,6 +39,7 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusRequestEntityTooLarge)
|
||||
return
|
||||
}
|
||||
defer r.MultipartForm.RemoveAll()
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
http.Error(w, "file is required", http.StatusBadRequest)
|
||||
@@ -83,6 +84,11 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
objectUUID, err := s.store.ResolvePathInDomain(domainUUID, targetPath)
|
||||
createOnly := r.Header.Get("If-None-Match") == "*"
|
||||
if err == nil && createOnly {
|
||||
http.Error(w, "file already exists", http.StatusPreconditionFailed)
|
||||
return
|
||||
}
|
||||
if err == nil && mode == "enforcing" {
|
||||
// upload and write-once grants never overwrite an existing object.
|
||||
if s.store.Authorize(store.AuthorizationRequest{DomainUUID: domainUUID, PrincipalUUID: principal.UUID, Capability: "write", TargetType: "path", TargetID: targetPath}) != nil {
|
||||
@@ -92,6 +98,13 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
objectUUID, err = s.store.CreatePageAtPathInDomain(domainUUID, targetPath)
|
||||
if err != nil && createOnly {
|
||||
// A concurrent creator wins; never turn this into an overwrite.
|
||||
if _, resolveErr := s.store.ResolvePathInDomain(domainUUID, targetPath); resolveErr == nil {
|
||||
http.Error(w, "file already exists", http.StatusPreconditionFailed)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
@@ -113,17 +126,23 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.TrimSpace(language) == "" {
|
||||
language = "und"
|
||||
}
|
||||
if _, err := s.store.SaveRevisionContent(
|
||||
revision, err := s.store.SaveRevisionContent(
|
||||
objectUUID,
|
||||
payload,
|
||||
"web upload: "+originalName,
|
||||
language,
|
||||
contentType,
|
||||
originalName,
|
||||
); err != nil {
|
||||
)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
writeEventJSON(w, http.StatusCreated, map[string]string{"path": targetPath, "object_uuid": objectUUID, "revision_uuid": revision.UUID})
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, targetPath, http.StatusSeeOther)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -85,6 +86,51 @@ func TestWebUploadCreatesAndRevisesSpecifiedPath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebUploadCreateOnlyJSON(t *testing.T) {
|
||||
s, token, domain := configFixture(t)
|
||||
upload := func(payload string, authenticated bool) *httptest.ResponseRecorder {
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
writer.WriteField("path", "/uploads/日本語 #1.txt")
|
||||
file, _ := writer.CreateFormFile("file", "日本語 #1.txt")
|
||||
file.Write([]byte(payload))
|
||||
writer.Close()
|
||||
r := httptest.NewRequest("POST", "http://localhost/v/upload", &body)
|
||||
r.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
r.Header.Set("Accept", "application/json")
|
||||
r.Header.Set("If-None-Match", "*")
|
||||
if authenticated {
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
s.handleUpload(w, r)
|
||||
return w
|
||||
}
|
||||
if w := upload("denied", false); w.Code != 403 {
|
||||
t.Fatalf("unauthorized: %d", w.Code)
|
||||
}
|
||||
w := upload("original", true)
|
||||
var result map[string]string
|
||||
if w.Code != 201 || json.Unmarshal(w.Body.Bytes(), &result) != nil || result["path"] != "/uploads/日本語 #1.txt" || result["revision_uuid"] == "" {
|
||||
t.Fatalf("JSON upload %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
if w = upload("overwrite", true); w.Code != 412 {
|
||||
t.Fatalf("duplicate: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
object, err := s.store.ResolvePathInDomain(domain, result["path"])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
revisions, err := s.store.ListRevisions(object)
|
||||
if err != nil || len(revisions) != 1 {
|
||||
t.Fatalf("unexpected revisions %d %v", len(revisions), err)
|
||||
}
|
||||
rev, err := s.store.GetRevision(revisions[0].UUID)
|
||||
if err != nil || rev.Body != "original" {
|
||||
t.Fatal("overwritten", err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustServerDomainUUID(t *testing.T, st *store.Store) string {
|
||||
t.Helper()
|
||||
domain, err := st.GetDefaultDomain()
|
||||
|
||||
@@ -164,6 +164,10 @@ func (s *Store) CreateBrowserAuthSession(domainUUID, principalUUID string, mfaLe
|
||||
}
|
||||
|
||||
func (s *Store) createTypedAuthSession(domainUUID, principalUUID string, mfaLevel int, prefix string) (string, error) {
|
||||
return s.createTypedAuthSessionForLifetime(domainUUID, principalUUID, mfaLevel, prefix, s.AuthSessionLifetime(domainUUID))
|
||||
}
|
||||
|
||||
func (s *Store) createTypedAuthSessionForLifetime(domainUUID, principalUUID string, mfaLevel int, prefix string, lifetime time.Duration) (string, error) {
|
||||
raw, _, err := authToken()
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -177,7 +181,7 @@ func (s *Store) createTypedAuthSession(domainUUID, principalUUID string, mfaLeve
|
||||
result, err := s.DB.Exec(`INSERT INTO auth_sessions(uuid,token_hash,principal_uuid,domain_uuid,auth_time_ms,expires_at_ms,last_seen_at_ms,mfa_level)
|
||||
SELECT ?,?,p.uuid,m.domain_uuid,?,?,?,? FROM principals p JOIN domain_memberships m ON m.principal_uuid=p.uuid
|
||||
WHERE p.uuid=? AND p.state IN ('active','readonly') AND m.domain_uuid=? AND m.state='active'`,
|
||||
uuid.NewString(), hash, now, now+s.AuthSessionLifetime(domainUUID).Milliseconds(), now, mfaLevel, principalUUID, domainUUID)
|
||||
uuid.NewString(), hash, now, now+lifetime.Milliseconds(), now, mfaLevel, principalUUID, domainUUID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -27,7 +27,9 @@ var cliAuthMigrations = []db.SQLMigration{{Version: 1, Name: "cli_oidc_handoff",
|
||||
schemaUnique("auth_cli_requests", "id"), schemaUnique("auth_cli_requests", "device_hash"),
|
||||
schemaIndex("auth_cli_requests", "auth_cli_domain_created", "domain_uuid,created_ms"),
|
||||
schemaIndex("auth_cli_requests", "auth_cli_expiry", "expires_ms"),
|
||||
}}}
|
||||
}}, {Version: 2, Name: "cli_trusted_session_choice", Statements: []string{
|
||||
`ALTER TABLE auth_cli_requests ADD COLUMN remember INTEGER NOT NULL DEFAULT 0 CHECK(remember IN (0,1))`,
|
||||
}, Assertions: []string{schemaColumns("auth_cli_requests", "remember")}}}
|
||||
|
||||
var (
|
||||
ErrCLIPending = errors.New("authorization_pending")
|
||||
@@ -39,11 +41,16 @@ var (
|
||||
type CLIAuthRequest struct {
|
||||
ID, Origin, State, BrowserHash, PrincipalUUID string
|
||||
ExpiresMS int64
|
||||
Remember bool
|
||||
}
|
||||
|
||||
// Admission is one write statement; concurrent unauthenticated requests cannot
|
||||
// race the caps. Requests are retained for ten minutes for issuance accounting.
|
||||
func (s *Store) StartCLIAuth(ctx context.Context, domain, origin, challenge string) (id, device, code string, err error) {
|
||||
return s.StartCLIAuthForLogin(ctx, domain, origin, challenge, false)
|
||||
}
|
||||
|
||||
func (s *Store) StartCLIAuthForLogin(ctx context.Context, domain, origin, challenge string, remember bool) (id, device, code string, err error) {
|
||||
if s.ReadOnly {
|
||||
return "", "", "", ErrReadOnly
|
||||
}
|
||||
@@ -66,10 +73,10 @@ func (s *Store) StartCLIAuth(ctx context.Context, domain, origin, challenge stri
|
||||
return
|
||||
}
|
||||
var result sql.Result
|
||||
result, err = s.DB.ExecContext(ctx, `INSERT INTO auth_cli_requests(id,domain_uuid,origin,device_hash,challenge,code_hash,created_ms,expires_ms)
|
||||
SELECT ?,?,?,?,?,?,?,? WHERE (SELECT count(*) FROM auth_cli_requests)<4096
|
||||
result, err = s.DB.ExecContext(ctx, `INSERT INTO auth_cli_requests(id,domain_uuid,origin,device_hash,challenge,code_hash,created_ms,expires_ms,remember)
|
||||
SELECT ?,?,?,?,?,?,?,?,? WHERE (SELECT count(*) FROM auth_cli_requests)<4096
|
||||
AND (SELECT count(*) FROM auth_cli_requests WHERE domain_uuid=? AND created_ms>?)<64`,
|
||||
id, domain, origin, hashAuthToken(device), challenge, hashAuthToken(code), now, now+300000, domain, now-300000)
|
||||
id, domain, origin, hashAuthToken(device), challenge, hashAuthToken(code), now, now+300000, remember, domain, now-300000)
|
||||
if err == nil {
|
||||
if n, e := result.RowsAffected(); e != nil {
|
||||
err = e
|
||||
@@ -82,7 +89,7 @@ func (s *Store) StartCLIAuth(ctx context.Context, domain, origin, challenge stri
|
||||
|
||||
func (s *Store) CLIAuthRequest(ctx context.Context, domain, origin, id string) (*CLIAuthRequest, error) {
|
||||
var grant CLIAuthRequest
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT id,origin,state,browser_hash,principal_uuid,expires_ms FROM auth_cli_requests WHERE id=? AND domain_uuid=? AND origin=? AND expires_ms>?`, id, domain, origin, time.Now().UnixMilli()).Scan(&grant.ID, &grant.Origin, &grant.State, &grant.BrowserHash, &grant.PrincipalUUID, &grant.ExpiresMS)
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT id,origin,state,browser_hash,principal_uuid,expires_ms,remember FROM auth_cli_requests WHERE id=? AND domain_uuid=? AND origin=? AND expires_ms>?`, id, domain, origin, time.Now().UnixMilli()).Scan(&grant.ID, &grant.Origin, &grant.State, &grant.BrowserHash, &grant.PrincipalUUID, &grant.ExpiresMS, &grant.Remember)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrCLIExpired
|
||||
}
|
||||
@@ -168,15 +175,17 @@ func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, ver
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
lifetime := s.AuthSessionLifetime(domain).Milliseconds()
|
||||
trustedLifetime := s.LoginSessionLifetime(domain, true).Milliseconds()
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var id, state, browser string
|
||||
var remember bool
|
||||
err = tx.QueryRowContext(ctx, `UPDATE auth_cli_requests SET next_poll_ms=?,state=CASE WHEN state='approved' THEN 'consumed' ELSE state END
|
||||
WHERE device_hash=? AND challenge=? AND domain_uuid=? AND origin=? AND expires_ms>? AND next_poll_ms<=? AND state IN ('pending','approved','denied')
|
||||
RETURNING id,state,browser_hash`, now+5000, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now, now).Scan(&id, &state, &browser)
|
||||
RETURNING id,state,browser_hash,remember`, now+5000, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now, now).Scan(&id, &state, &browser, &remember)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
var exists int
|
||||
e := tx.QueryRowContext(ctx, `SELECT count(*) FROM auth_cli_requests WHERE device_hash=? AND challenge=? AND domain_uuid=? AND origin=? AND expires_ms>? AND state IN ('pending','approved','denied')`, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now).Scan(&exists)
|
||||
@@ -204,6 +213,9 @@ func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, ver
|
||||
return
|
||||
}
|
||||
var raw string
|
||||
if remember {
|
||||
lifetime = trustedLifetime
|
||||
}
|
||||
raw, _, err = authToken()
|
||||
if err != nil {
|
||||
return
|
||||
|
||||
@@ -8,10 +8,68 @@ import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
)
|
||||
|
||||
const cliTestOrigin = "https://wiki.example"
|
||||
|
||||
func TestCLIAuthTrustedMigrationPreservesExistingRequests(t *testing.T) {
|
||||
s := newSchemaTestStore(t)
|
||||
ctx := context.Background()
|
||||
if err := db.ApplySQLiteMigrations(ctx, s.DB, "cli-auth", cliAuthMigrations[:1]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.DB.Exec(`INSERT INTO auth_cli_requests(id,domain_uuid,origin,device_hash,challenge,code_hash,created_ms,expires_ms) VALUES('old','domain','https://wiki.example','device','challenge','code',1,2)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := db.ApplySQLiteMigrations(ctx, s.DB, "cli-auth", cliAuthMigrations); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var remember int
|
||||
var challenge string
|
||||
if err := s.DB.QueryRow(`SELECT remember,challenge FROM auth_cli_requests WHERE id='old'`).Scan(&remember, &challenge); err != nil || remember != 0 || challenge != "challenge" {
|
||||
t.Fatalf("old grant changed: %d %q %v", remember, challenge, err)
|
||||
}
|
||||
if _, err := s.DB.Exec(`UPDATE auth_cli_requests SET remember=2`); err == nil {
|
||||
t.Fatal("invalid remember flag accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOTPLoginBindsTrustedChoice(t *testing.T) {
|
||||
for _, remember := range []bool{false, true} {
|
||||
s, p, _ := cliAuthFixture(t)
|
||||
secret, err := s.BeginTOTPEnrollment(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, err := totpCode(secret, time.Now().Unix()/30)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.ConfirmTOTPEnrollment(p, code); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Synthetic fixture: permit this time step once for login after enrollment.
|
||||
if _, err = s.DB.Exec(`UPDATE auth_credentials SET parameters_json='{"last_counter":0}' WHERE principal_uuid=? AND kind='totp'`, p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
challenge, err := s.CreateTOTPLoginChallengeForLogin("domain", p, remember)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, choice, err := s.CompleteTOTPLoginChallengeForLogin("domain", challenge, code)
|
||||
if err != nil || got != p || choice != remember {
|
||||
t.Fatalf("bound choice: %q %v %v", got, choice, err)
|
||||
}
|
||||
if _, _, err = s.CompleteTOTPLoginChallengeForLogin("domain", challenge, code); err == nil {
|
||||
t.Fatal("challenge replay accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cliAuthFixture(t *testing.T) (*Store, string, string) {
|
||||
t.Helper()
|
||||
s := newSchemaTestStore(t)
|
||||
|
||||
@@ -30,3 +30,37 @@ func (s *Store) SetAuthSessionLifetimeMinutes(domain string, minutes int) error
|
||||
func (s *Store) AuthSessionLifetime(domain string) time.Duration {
|
||||
return time.Duration(s.AuthSessionLifetimeMinutes(domain)) * time.Minute
|
||||
}
|
||||
|
||||
// Opt-in persistent sessions have a separate, administrator-controlled ceiling.
|
||||
// Zero disables the option. Existing sessions retain their original expiry.
|
||||
func (s *Store) TrustedSessionDays(domain string) int {
|
||||
raw, err := s.GetConfigInDomain(domain, "auth_trusted_session_days")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
if raw == "" {
|
||||
return 30
|
||||
}
|
||||
days, err := strconv.Atoi(raw)
|
||||
if err != nil || days < 0 || days > 30 {
|
||||
return 0
|
||||
}
|
||||
return days
|
||||
}
|
||||
|
||||
func (s *Store) LoginSessionLifetime(domain string, remember bool) time.Duration {
|
||||
if days := s.TrustedSessionDays(domain); remember && days > 0 {
|
||||
return time.Duration(days) * 24 * time.Hour
|
||||
}
|
||||
return s.AuthSessionLifetime(domain)
|
||||
}
|
||||
|
||||
func (s *Store) CreateLoginSession(domain, principal string, mfa int, browser, remember bool) (string, time.Duration, error) {
|
||||
lifetime := s.LoginSessionLifetime(domain, remember)
|
||||
prefix := "pw_api_"
|
||||
if browser {
|
||||
prefix = "pw_browser_"
|
||||
}
|
||||
token, err := s.createTypedAuthSessionForLifetime(domain, principal, mfa, prefix, lifetime)
|
||||
return token, lifetime, err
|
||||
}
|
||||
@@ -176,36 +176,51 @@ func TOTPURI(secret, account, issuer string) string {
|
||||
}
|
||||
|
||||
func (s *Store) CreateTOTPLoginChallenge(domainUUID, principalUUID string) (string, error) {
|
||||
return s.CreateTOTPLoginChallengeForLogin(domainUUID, principalUUID, false)
|
||||
}
|
||||
|
||||
func (s *Store) CreateTOTPLoginChallengeForLogin(domainUUID, principalUUID string, remember bool) (string, error) {
|
||||
token, hash, err := authToken()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
payload, _ := json.Marshal(map[string]string{"principal_uuid": principalUUID})
|
||||
payload, _ := json.Marshal(map[string]any{"principal_uuid": principalUUID, "remember": remember})
|
||||
_, err = s.DB.Exec(`INSERT INTO auth_challenges(uuid,domain_uuid,principal_uuid,kind,token_hash,payload_json,expires_at_ms,created_at_ms) VALUES(?,?,?,?,?,?,?,?)`, uuid.NewString(), domainUUID, principalUUID, "totp-login", hash, string(payload), now+5*60*1000, now)
|
||||
return token, err
|
||||
}
|
||||
func (s *Store) CompleteTOTPLoginChallenge(domainUUID, token, code string) (string, error) {
|
||||
id, _, err := s.CompleteTOTPLoginChallengeForLogin(domainUUID, token, code)
|
||||
return id, err
|
||||
}
|
||||
|
||||
func (s *Store) CompleteTOTPLoginChallengeForLogin(domainUUID, token, code string) (string, bool, error) {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
hash := base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
var challengeUUID, principalUUID string
|
||||
var challengeUUID, principalUUID, payload string
|
||||
var expires int64
|
||||
var attempts int
|
||||
err := s.DB.QueryRow(`SELECT uuid,principal_uuid,expires_at_ms,attempt_count FROM auth_challenges WHERE domain_uuid=? AND kind='totp-login' AND token_hash=? AND consumed_at_ms=0`, domainUUID, hash).Scan(&challengeUUID, &principalUUID, &expires, &attempts)
|
||||
err := s.DB.QueryRow(`SELECT uuid,principal_uuid,expires_at_ms,attempt_count,payload_json FROM auth_challenges WHERE domain_uuid=? AND kind='totp-login' AND token_hash=? AND consumed_at_ms=0`, domainUUID, hash).Scan(&challengeUUID, &principalUUID, &expires, &attempts, &payload)
|
||||
if err != nil || expires < time.Now().UnixMilli() || attempts >= 5 {
|
||||
return "", ErrAccessDenied
|
||||
return "", false, ErrAccessDenied
|
||||
}
|
||||
var options struct {
|
||||
Remember bool `json:"remember"`
|
||||
}
|
||||
if json.Unmarshal([]byte(payload), &options) != nil {
|
||||
return "", false, ErrAccessDenied
|
||||
}
|
||||
if err = s.VerifyTOTP(principalUUID, code); err != nil {
|
||||
_, _ = s.DB.Exec(`UPDATE auth_challenges SET attempt_count=attempt_count+1,consumed_at_ms=CASE WHEN attempt_count+1>=5 THEN ? ELSE consumed_at_ms END WHERE uuid=? AND consumed_at_ms=0`, time.Now().UnixMilli(), challengeUUID)
|
||||
return "", err
|
||||
return "", false, err
|
||||
}
|
||||
result, err := s.DB.Exec(`UPDATE auth_challenges SET consumed_at_ms=? WHERE uuid=? AND consumed_at_ms=0`, time.Now().UnixMilli(), challengeUUID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", false, err
|
||||
}
|
||||
changed, _ := result.RowsAffected()
|
||||
if changed != 1 {
|
||||
return "", ErrAccessDenied
|
||||
return "", false, ErrAccessDenied
|
||||
}
|
||||
return principalUUID, nil
|
||||
return principalUUID, options.Remember, nil
|
||||
}
|
||||
@@ -81,7 +81,11 @@ func minInt64(a, b int64) int64 {
|
||||
}
|
||||
|
||||
func (s *Store) GetRevisionMetadata(revisionUUID string) (*Revision, error) {
|
||||
row := s.DB.QueryRow(`SELECT uuid,object_uuid,COALESCE(document_hash,''),COALESCE(NULLIF(lang,''),'und'),COALESCE(NULLIF(content_type,''),'text/html; charset=utf-8'),COALESCE(filename,''),'',COALESCE(message,''),COALESCE(created_at,0),COALESCE(created_at_ms,COALESCE(created_at,0)*1000) FROM revisions WHERE uuid=?`, revisionUUID)
|
||||
return s.GetRevisionMetadataContext(context.Background(), revisionUUID)
|
||||
}
|
||||
|
||||
func (s *Store) GetRevisionMetadataContext(ctx context.Context, revisionUUID string) (*Revision, error) {
|
||||
row := s.DB.QueryRowContext(ctx, `SELECT uuid,object_uuid,COALESCE(document_hash,''),COALESCE(NULLIF(lang,''),'und'),COALESCE(NULLIF(content_type,''),'text/html; charset=utf-8'),COALESCE(filename,''),'',COALESCE(message,''),COALESCE(created_at,0),COALESCE(created_at_ms,COALESCE(created_at,0)*1000) FROM revisions WHERE uuid=?`, revisionUUID)
|
||||
return scanRevision(row)
|
||||
}
|
||||
|
||||
|
||||
+84
-29
@@ -44,6 +44,20 @@ var feedMigrations = []db.SQLMigration{{Version: 1, Name: "private_feed_reader",
|
||||
`ALTER TABLE feed_items ADD COLUMN remote_categories TEXT NOT NULL DEFAULT '[]'`,
|
||||
`UPDATE feed_sources SET next_ms=0,lease='',lease_until=0,version=version+1 WHERE provider='freshrss'`,
|
||||
}, Assertions: []string{schemaColumns("feed_sources", "remote_catalog"), schemaColumns("feed_items", "remote_feed,remote_categories")},
|
||||
}, {
|
||||
Version: 5, Name: "feed_explicit_remote_actions", Statements: []string{
|
||||
`ALTER TABLE feed_sources ADD COLUMN write_enabled INTEGER NOT NULL DEFAULT 0`,
|
||||
`CREATE TABLE feed_actions(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,request_id TEXT NOT NULL,source_uuid TEXT NOT NULL,item_id TEXT NOT NULL,field TEXT NOT NULL,desired INTEGER NOT NULL,source_version INTEGER NOT NULL,status TEXT NOT NULL,claim TEXT NOT NULL DEFAULT '',until_ms INTEGER NOT NULL DEFAULT 0,created_ms INTEGER NOT NULL,error TEXT NOT NULL DEFAULT '',PRIMARY KEY(domain_uuid,owner_uuid,request_id))`,
|
||||
`CREATE INDEX feed_actions_due ON feed_actions(status,created_ms)`,
|
||||
`CREATE INDEX feed_actions_item ON feed_actions(domain_uuid,owner_uuid,source_uuid,item_id,created_ms DESC)`,
|
||||
`CREATE UNIQUE INDEX feed_actions_active ON feed_actions(source_uuid,item_id) WHERE status IN ('queued','preparing','sending','unknown','check_queued','checking')`,
|
||||
`CREATE TRIGGER feed_actions_source_change AFTER UPDATE OF version ON feed_sources BEGIN UPDATE feed_actions SET status=CASE WHEN status IN ('sending','unknown','check_queued','checking') THEN 'unknown' ELSE 'cancelled' END,error='source_changed' WHERE source_uuid=old.uuid AND status IN ('queued','preparing','sending','unknown','check_queued','checking'); END`,
|
||||
`CREATE TRIGGER feed_actions_source_delete AFTER DELETE ON feed_sources BEGIN UPDATE feed_actions SET status=CASE WHEN status IN ('sending','unknown','check_queued','checking') THEN 'unknown' ELSE 'cancelled' END,error='source_deleted' WHERE source_uuid=old.uuid AND status IN ('queued','preparing','sending','unknown','check_queued','checking'); END`,
|
||||
}, Assertions: []string{schemaColumns("feed_sources", "write_enabled"), schemaUnique("feed_actions", "domain_uuid,owner_uuid,request_id")},
|
||||
}, {
|
||||
Version: 6, Name: "freshrss_empty_folders", Statements: []string{
|
||||
`ALTER TABLE feed_sources ADD COLUMN remote_folders TEXT NOT NULL DEFAULT '[]'`,
|
||||
}, Assertions: []string{schemaColumns("feed_sources", "remote_folders")},
|
||||
}}
|
||||
|
||||
// CaptureFeedNote creates an inert Wiki note and receipt atomically. It does not
|
||||
@@ -111,24 +125,25 @@ func (s *Store) CaptureFeedNote(ctx context.Context, domain, owner, request, sou
|
||||
}
|
||||
|
||||
type FeedSource struct {
|
||||
UUID string `json:"uuid"`
|
||||
Domain string `json:"-"`
|
||||
Owner string `json:"-"`
|
||||
Provider string `json:"provider"`
|
||||
Title string `json:"title"`
|
||||
Folder string `json:"folder"`
|
||||
URL string `json:"url"`
|
||||
Credential string `json:"-"`
|
||||
Version int64 `json:"version"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Interval int `json:"interval_seconds"`
|
||||
NextMS int64 `json:"next_ms"`
|
||||
Lease string `json:"-"`
|
||||
LeaseUntil int64 `json:"-"`
|
||||
LastMS int64 `json:"last_ms"`
|
||||
Error string `json:"error"`
|
||||
ETag string `json:"-"`
|
||||
Modified string `json:"-"`
|
||||
UUID string `json:"uuid"`
|
||||
Domain string `json:"-"`
|
||||
Owner string `json:"-"`
|
||||
Provider string `json:"provider"`
|
||||
Title string `json:"title"`
|
||||
Folder string `json:"folder"`
|
||||
URL string `json:"url"`
|
||||
Credential string `json:"-"`
|
||||
Version int64 `json:"version"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Interval int `json:"interval_seconds"`
|
||||
NextMS int64 `json:"next_ms"`
|
||||
Lease string `json:"-"`
|
||||
LeaseUntil int64 `json:"-"`
|
||||
LastMS int64 `json:"last_ms"`
|
||||
Error string `json:"error"`
|
||||
ETag string `json:"-"`
|
||||
Modified string `json:"-"`
|
||||
WriteEnabled bool `json:"write_enabled"`
|
||||
}
|
||||
type FeedItem struct {
|
||||
Source string `json:"source"`
|
||||
@@ -148,10 +163,10 @@ type FeedItem struct {
|
||||
RemoteCategories []string `json:"remote_categories,omitempty"`
|
||||
}
|
||||
|
||||
const feedSourceColumns = `uuid,domain_uuid,owner_uuid,provider,title,folder,url,credential,version,enabled,interval_seconds,next_ms,lease,lease_until,last_ms,error,etag,modified`
|
||||
const feedSourceColumns = `uuid,domain_uuid,owner_uuid,provider,title,folder,url,credential,version,enabled,interval_seconds,next_ms,lease,lease_until,last_ms,error,etag,modified,write_enabled`
|
||||
|
||||
func scanFeedSource(row interface{ Scan(...any) error }) (v FeedSource, e error) {
|
||||
e = row.Scan(&v.UUID, &v.Domain, &v.Owner, &v.Provider, &v.Title, &v.Folder, &v.URL, &v.Credential, &v.Version, &v.Enabled, &v.Interval, &v.NextMS, &v.Lease, &v.LeaseUntil, &v.LastMS, &v.Error, &v.ETag, &v.Modified)
|
||||
e = row.Scan(&v.UUID, &v.Domain, &v.Owner, &v.Provider, &v.Title, &v.Folder, &v.URL, &v.Credential, &v.Version, &v.Enabled, &v.Interval, &v.NextMS, &v.Lease, &v.LeaseUntil, &v.LastMS, &v.Error, &v.ETag, &v.Modified, &v.WriteEnabled)
|
||||
return
|
||||
}
|
||||
func feedActor(ctx context.Context, q interface {
|
||||
@@ -216,6 +231,9 @@ func (s *Store) FeedSources(ctx context.Context, domain, owner string) ([]FeedSo
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) SaveFeedSource(ctx context.Context, domain, owner string, v FeedSource) (FeedSource, error) {
|
||||
if v.WriteEnabled && v.Provider != "freshrss" {
|
||||
return v, ErrTaskInvalid
|
||||
}
|
||||
if _, e := uuid.Parse(v.UUID); e != nil {
|
||||
return v, ErrTaskInvalid
|
||||
}
|
||||
@@ -228,7 +246,7 @@ func (s *Store) SaveFeedSource(ctx context.Context, domain, owner string, v Feed
|
||||
if v.Version == 0 {
|
||||
old, lookup := scanFeedSource(tx.QueryRowContext(ctx, `SELECT `+feedSourceColumns+` FROM feed_sources WHERE uuid=?`, v.UUID))
|
||||
if lookup == nil {
|
||||
if old.Domain != domain || old.Owner != owner || old.Version != 1 || old.Provider != v.Provider || old.Title != v.Title || old.Folder != v.Folder || old.URL != v.URL || old.Interval != v.Interval || old.Enabled != v.Enabled {
|
||||
if old.Domain != domain || old.Owner != owner || old.Version != 1 || old.Provider != v.Provider || old.Title != v.Title || old.Folder != v.Folder || old.URL != v.URL || old.Interval != v.Interval || old.Enabled != v.Enabled || old.WriteEnabled != v.WriteEnabled {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
if old.Credential != v.Credential {
|
||||
@@ -249,6 +267,17 @@ func (s *Store) SaveFeedSource(ctx context.Context, domain, owner string, v Feed
|
||||
if !errors.Is(lookup, sql.ErrNoRows) {
|
||||
return lookup
|
||||
}
|
||||
// Do not rebind retained receipts to a different remote identity.
|
||||
// Both predicates use existing indexes: owner history and the global
|
||||
// partial index of unresolved operations. Other owners' terminal
|
||||
// receipts remain isolated by domain/owner in metadata lookups.
|
||||
var retired bool
|
||||
if e := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM feed_actions WHERE domain_uuid=? AND owner_uuid=? AND source_uuid=?) OR EXISTS(SELECT 1 FROM feed_actions WHERE source_uuid=? AND status IN ('queued','preparing','sending','unknown','check_queued','checking'))`, domain, owner, v.UUID, v.UUID).Scan(&retired); e != nil {
|
||||
return e
|
||||
}
|
||||
if retired {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
var n int
|
||||
if e := tx.QueryRowContext(ctx, `SELECT count(*) FROM feed_sources WHERE domain_uuid=? AND owner_uuid=?`, domain, owner).Scan(&n); e != nil {
|
||||
return e
|
||||
@@ -256,7 +285,7 @@ func (s *Store) SaveFeedSource(ctx context.Context, domain, owner string, v Feed
|
||||
if n >= 32 {
|
||||
return ErrTaskDAVLimit
|
||||
}
|
||||
_, e := tx.ExecContext(ctx, `INSERT INTO feed_sources(uuid,domain_uuid,owner_uuid,provider,title,folder,url,credential,version,enabled,interval_seconds) VALUES(?,?,?,?,?,?,?,?,1,?,?)`, v.UUID, domain, owner, v.Provider, v.Title, v.Folder, v.URL, v.Credential, v.Enabled, v.Interval)
|
||||
_, e := tx.ExecContext(ctx, `INSERT INTO feed_sources(uuid,domain_uuid,owner_uuid,provider,title,folder,url,credential,version,enabled,interval_seconds,write_enabled) VALUES(?,?,?,?,?,?,?,?,1,?,?,?)`, v.UUID, domain, owner, v.Provider, v.Title, v.Folder, v.URL, v.Credential, v.Enabled, v.Interval, v.WriteEnabled)
|
||||
return e
|
||||
}
|
||||
old, e := scanFeedSource(tx.QueryRowContext(ctx, `SELECT `+feedSourceColumns+` FROM feed_sources WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, v.UUID, domain, owner))
|
||||
@@ -267,7 +296,7 @@ func (s *Store) SaveFeedSource(ctx context.Context, domain, owner string, v Feed
|
||||
if old.Provider != v.Provider || old.URL != v.URL || v.Credential != "" {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
result, e := tx.ExecContext(ctx, `UPDATE feed_sources SET title=?,folder=?,enabled=?,interval_seconds=?,version=version+1,next_ms=0,lease='',lease_until=0 WHERE uuid=? AND version=?`, v.Title, v.Folder, v.Enabled, v.Interval, v.UUID, v.Version)
|
||||
result, e := tx.ExecContext(ctx, `UPDATE feed_sources SET title=?,folder=?,enabled=?,interval_seconds=?,write_enabled=?,version=version+1,next_ms=0,lease='',lease_until=0 WHERE uuid=? AND version=?`, v.Title, v.Folder, v.Enabled, v.Interval, v.WriteEnabled, v.UUID, v.Version)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
@@ -305,7 +334,7 @@ func (s *Store) FeedSourceAction(ctx context.Context, domain, owner, id, action
|
||||
}
|
||||
func (s *Store) FeedItems(ctx context.Context, domain, owner, source, filter, query string, before int64, beforeID string, scope ...string) ([]FeedItem, error) {
|
||||
remoteFeed, category := "", ""
|
||||
if len(scope) > 2 {
|
||||
if len(scope) > 3 {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
if len(scope) > 0 {
|
||||
@@ -314,6 +343,13 @@ func (s *Store) FeedItems(ctx context.Context, domain, owner, source, filter, qu
|
||||
if len(scope) > 1 {
|
||||
category = scope[1]
|
||||
}
|
||||
mode := ""
|
||||
if len(scope) > 2 {
|
||||
mode = scope[2]
|
||||
}
|
||||
if mode != "" && (mode != "uncategorized" || source == "" || category != "") {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
if (remoteFeed != "" && !ValidFeedRemoteID(remoteFeed)) || (category != "" && !ValidFeedRemoteID(category)) || ((remoteFeed != "" || category != "") && source == "") {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
@@ -323,7 +359,14 @@ func (s *Store) FeedItems(ctx context.Context, domain, owner, source, filter, qu
|
||||
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
rows, e := s.DB.QueryContext(ctx, `SELECT i.source_uuid,i.id,i.title,i.url,i.published_ms,i.feed,CASE WHEN s.folder<>'' THEN s.folder ELSE i.folder END,CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END,CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END,COALESCE(t.version,0),s.provider FROM feed_items i JOIN feed_sources s ON s.uuid=i.source_uuid LEFT JOIN feed_states t ON t.source_uuid=i.source_uuid AND t.id=i.id WHERE s.domain_uuid=? AND s.owner_uuid=? AND (?='' OR s.uuid=?) AND (?='' OR instr(lower(i.title),lower(?))>0 OR instr(lower(i.feed),lower(?))>0) AND (?<0 OR i.published_ms<? OR (i.published_ms=? AND (i.source_uuid||':'||i.id)<?)) AND (?<>'unread' OR (CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END)=0) AND (?<>'starred' OR (CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END)=1) AND (?='' OR i.remote_feed=?) AND (?='' OR EXISTS(SELECT 1 FROM json_each(i.remote_categories) WHERE value=?)) ORDER BY i.published_ms DESC,i.source_uuid||':'||i.id DESC LIMIT 101`, domain, owner, source, source, query, query, query, before, before, before, beforeID, filter, filter, remoteFeed, remoteFeed, category, category)
|
||||
args := []any{domain, owner, source, source, query, query, query, before, before, before, beforeID, filter, filter, remoteFeed, remoteFeed, category, category}
|
||||
extra := ""
|
||||
if mode == "uncategorized" {
|
||||
// The uncorrelated list is built once, not a catalog scan per article.
|
||||
extra = ` AND i.remote_feed IN (SELECT json_extract(c.value,'$.id') FROM feed_sources cs,json_each(cs.remote_catalog) c WHERE cs.uuid=? AND cs.domain_uuid=? AND cs.owner_uuid=? AND json_array_length(c.value,'$.categories')=0)`
|
||||
args = append(args, source, domain, owner)
|
||||
}
|
||||
rows, e := s.DB.QueryContext(ctx, `SELECT i.source_uuid,i.id,i.title,i.url,i.published_ms,i.feed,CASE WHEN s.folder<>'' THEN s.folder ELSE i.folder END,CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END,CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END,COALESCE(t.version,0),s.provider FROM feed_items i JOIN feed_sources s ON s.uuid=i.source_uuid LEFT JOIN feed_states t ON t.source_uuid=i.source_uuid AND t.id=i.id WHERE s.domain_uuid=? AND s.owner_uuid=? AND (?='' OR s.uuid=?) AND (?='' OR instr(lower(i.title),lower(?))>0 OR instr(lower(i.feed),lower(?))>0) AND (?<0 OR i.published_ms<? OR (i.published_ms=? AND (i.source_uuid||':'||i.id)<?)) AND (?<>'unread' OR (CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END)=0) AND (?<>'starred' OR (CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END)=1) AND (?='' OR i.remote_feed=?) AND (?='' OR EXISTS(SELECT 1 FROM json_each(i.remote_categories) WHERE value=?))`+extra+` ORDER BY i.published_ms DESC,i.source_uuid||':'||i.id DESC LIMIT 101`, args...)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
@@ -440,17 +483,29 @@ func (s *Store) ClaimFeed(ctx context.Context, v FeedSource) (FeedSource, error)
|
||||
}
|
||||
|
||||
// Failed fetches preserve the previous cache. Version and claim token fence stale workers.
|
||||
func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem, etag, modified, code string, unchanged bool, catalogs ...[]FeedRemoteSubscription) error {
|
||||
func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem, etag, modified, code string, unchanged bool, catalogs ...FeedCatalogSnapshot) error {
|
||||
if len(catalogs) > 1 {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
var catalog string
|
||||
var catalog, folders string
|
||||
if len(catalogs) == 1 {
|
||||
var e error
|
||||
catalog, e = FeedCatalogJSON(catalogs[0])
|
||||
catalog, folders, e = catalogs[0].Encode()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if v.Provider == "freshrss" {
|
||||
membership := map[string][]string{}
|
||||
for _, sub := range catalogs[0].Subscriptions {
|
||||
for _, c := range sub.Categories {
|
||||
membership[sub.ID] = append(membership[sub.ID], c.ID)
|
||||
}
|
||||
}
|
||||
items = append([]FeedItem(nil), items...)
|
||||
for n := range items {
|
||||
items[n].RemoteCategories = membership[items[n].RemoteFeed]
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(items) > 500 || len(etag) > 1024 || len(modified) > 1024 {
|
||||
return ErrTaskInvalid
|
||||
@@ -486,7 +541,7 @@ func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem
|
||||
return nil
|
||||
}
|
||||
if catalog != "" {
|
||||
if _, e = tx.ExecContext(ctx, `UPDATE feed_sources SET remote_catalog=? WHERE uuid=?`, catalog, v.UUID); e != nil {
|
||||
if _, e = tx.ExecContext(ctx, `UPDATE feed_sources SET remote_catalog=?,remote_folders=? WHERE uuid=?`, catalog, folders, v.UUID); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type FeedAction struct {
|
||||
Domain string `json:"-"`
|
||||
Owner string `json:"-"`
|
||||
RequestID string `json:"request_id"`
|
||||
Source string `json:"source"`
|
||||
ID string `json:"id"`
|
||||
Field string `json:"field"`
|
||||
Desired bool `json:"desired"`
|
||||
SourceVersion int64 `json:"source_version"`
|
||||
Status string `json:"status"`
|
||||
Claim string `json:"-"`
|
||||
UntilMS int64 `json:"-"`
|
||||
CreatedMS int64 `json:"created_ms"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
const feedActionColumns = `domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,claim,until_ms,created_ms,error`
|
||||
|
||||
func scanFeedAction(row interface{ Scan(...any) error }) (a FeedAction, e error) {
|
||||
e = row.Scan(&a.Domain, &a.Owner, &a.RequestID, &a.Source, &a.ID, &a.Field, &a.Desired, &a.SourceVersion, &a.Status, &a.Claim, &a.UntilMS, &a.CreatedMS, &a.Error)
|
||||
return
|
||||
}
|
||||
func (s *Store) FeedAction(ctx context.Context, domain, owner, source, id string) (*FeedAction, error) {
|
||||
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
a, e := scanFeedAction(s.DB.QueryRowContext(ctx, `SELECT `+feedActionColumns+` FROM feed_actions WHERE domain_uuid=? AND owner_uuid=? AND source_uuid=? AND item_id=? ORDER BY created_ms DESC,rowid DESC LIMIT 1`, domain, owner, source, id))
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return &a, e
|
||||
}
|
||||
func (s *Store) QueueFeedAction(ctx context.Context, domain, owner string, a FeedAction) (FeedAction, error) {
|
||||
if _, e := uuid.Parse(a.RequestID); e != nil {
|
||||
return a, ErrTaskInvalid
|
||||
}
|
||||
if (a.Field != "read" && a.Field != "starred") || a.ID == "" || len(a.ID) > 1024 {
|
||||
return a, ErrTaskInvalid
|
||||
}
|
||||
a.Domain, a.Owner = domain, owner
|
||||
a.Error, a.Claim, a.UntilMS = "", "", 0
|
||||
e := s.feedWrite(ctx, domain, owner, func(tx *sql.Tx) error {
|
||||
old, e := scanFeedAction(tx.QueryRowContext(ctx, `SELECT `+feedActionColumns+` FROM feed_actions WHERE domain_uuid=? AND owner_uuid=? AND request_id=?`, domain, owner, a.RequestID))
|
||||
if e == nil {
|
||||
if old.Source != a.Source || old.ID != a.ID || old.Field != a.Field || old.Desired != a.Desired || old.SourceVersion != a.SourceVersion {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
a = old
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(e, sql.ErrNoRows) {
|
||||
return e
|
||||
}
|
||||
var allowed bool
|
||||
if e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM feed_sources s JOIN feed_items i ON i.source_uuid=s.uuid WHERE s.domain_uuid=? AND s.owner_uuid=? AND s.uuid=? AND i.id=? AND s.provider='freshrss' AND s.enabled=1 AND s.write_enabled=1 AND s.version=?)`, domain, owner, a.Source, a.ID, a.SourceVersion).Scan(&allowed); e != nil {
|
||||
return e
|
||||
}
|
||||
if !allowed {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
var total, pending int
|
||||
if e = tx.QueryRowContext(ctx, `SELECT count(*),COALESCE(sum(status IN ('queued','preparing','sending','unknown','check_queued','checking')),0) FROM feed_actions WHERE domain_uuid=? AND owner_uuid=?`, domain, owner).Scan(&total, &pending); e != nil {
|
||||
return e
|
||||
}
|
||||
if total >= 10000 || pending >= 20 {
|
||||
return ErrTaskDAVLimit
|
||||
}
|
||||
if e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM feed_actions WHERE source_uuid=? AND item_id=? AND status IN ('queued','preparing','sending','unknown','check_queued','checking'))`, a.Source, a.ID).Scan(&allowed); e != nil {
|
||||
return e
|
||||
}
|
||||
if allowed {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
a.Status, a.CreatedMS = "queued", time.Now().UnixMilli()
|
||||
_, e = tx.ExecContext(ctx, `INSERT INTO feed_actions(domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,created_ms) VALUES(?,?,?,?,?,?,?,?,?,?)`, domain, owner, a.RequestID, a.Source, a.ID, a.Field, a.Desired, a.SourceVersion, a.Status, a.CreatedMS)
|
||||
return e
|
||||
})
|
||||
return a, e
|
||||
}
|
||||
|
||||
// Recheck is deliberately read-only at the remote side, even with writeback OFF.
|
||||
func (s *Store) RecheckFeedAction(ctx context.Context, domain, owner, request string) error {
|
||||
return s.feedWrite(ctx, domain, owner, func(tx *sql.Tx) error {
|
||||
r, e := tx.ExecContext(ctx, `UPDATE feed_actions SET status='check_queued',error='' WHERE domain_uuid=? AND owner_uuid=? AND request_id=? AND status='unknown' AND until_ms<? AND EXISTS(SELECT 1 FROM feed_sources s WHERE s.uuid=feed_actions.source_uuid AND s.domain_uuid=feed_actions.domain_uuid AND s.owner_uuid=feed_actions.owner_uuid AND s.provider='freshrss' AND s.enabled=1)`, domain, owner, request, time.Now().UnixMilli())
|
||||
return feedActionAffected(r, e)
|
||||
})
|
||||
}
|
||||
func feedActionAffected(r sql.Result, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
n, e := r.RowsAffected()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if n != 1 {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) DueFeedActions(ctx context.Context) ([]FeedAction, error) {
|
||||
if s.ReadOnly {
|
||||
return nil, ErrReadOnly
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
// Recovery changes only our receipts, never retries an uncertain remote write.
|
||||
if _, e := s.DB.ExecContext(ctx, `UPDATE feed_actions SET status=CASE WHEN status IN ('sending','checking') THEN 'unknown' ELSE 'failed' END,error='expired' WHERE (status IN ('preparing','sending','checking') AND until_ms<?) OR (status='queued' AND created_ms<?)`, now, now-300000); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
rows, e := s.DB.QueryContext(ctx, `SELECT `+feedActionColumns+` FROM feed_actions WHERE status IN ('queued','check_queued') AND EXISTS(SELECT 1 FROM feed_sources s JOIN principals p ON p.uuid=s.owner_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=s.domain_uuid JOIN domains d ON d.uuid=s.domain_uuid WHERE s.uuid=feed_actions.source_uuid AND s.enabled=1 AND s.lease_until<? AND p.state='active' AND m.state='active' AND d.enabled=1 AND COALESCE(d.placement,'local')='local' AND NOT EXISTS(SELECT 1 FROM config c WHERE c.domain_uuid=s.domain_uuid AND c.key='system_extension_states' AND COALESCE(json_extract(CASE WHEN json_valid(c.value) THEN c.value ELSE '{"organizer.feeds":false}' END,'$."organizer.feeds"'),1)=0)) ORDER BY created_ms LIMIT 2`, now)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []FeedAction{}
|
||||
for rows.Next() {
|
||||
a, e := scanFeedAction(rows)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) ClaimFeedAction(ctx context.Context, a FeedAction) (FeedAction, FeedSource, error) {
|
||||
var source FeedSource
|
||||
e := s.feedWrite(ctx, a.Domain, a.Owner, func(tx *sql.Tx) error {
|
||||
var e error
|
||||
source, e = scanFeedSource(tx.QueryRowContext(ctx, `SELECT `+feedSourceColumns+` FROM feed_sources WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, a.Source, a.Domain, a.Owner))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
check := a.Status == "check_queued"
|
||||
if !source.Enabled || source.Provider != "freshrss" || (!check && (!source.WriteEnabled || source.Version != a.SourceVersion)) {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
a.Claim = uuid.NewString()
|
||||
a.UntilMS = now + 60000
|
||||
state := "preparing"
|
||||
if check {
|
||||
state = "checking"
|
||||
}
|
||||
r, e := tx.ExecContext(ctx, `UPDATE feed_sources SET lease=?,lease_until=? WHERE uuid=? AND lease_until<?`, a.Claim, a.UntilMS, a.Source, now)
|
||||
if e = feedActionAffected(r, e); e != nil {
|
||||
return e
|
||||
}
|
||||
r, e = tx.ExecContext(ctx, `UPDATE feed_actions SET status=?,claim=?,until_ms=? WHERE domain_uuid=? AND owner_uuid=? AND request_id=? AND status=? AND (status='check_queued' OR created_ms>?)`, state, a.Claim, a.UntilMS, a.Domain, a.Owner, a.RequestID, a.Status, now-300000)
|
||||
if e = feedActionAffected(r, e); e != nil {
|
||||
return e
|
||||
}
|
||||
a.Status = state
|
||||
source.Lease = a.Claim
|
||||
source.LeaseUntil = a.UntilMS
|
||||
return nil
|
||||
})
|
||||
return a, source, e
|
||||
}
|
||||
func (s *Store) MarkFeedActionSending(ctx context.Context, a FeedAction, source FeedSource) error {
|
||||
return s.feedWrite(ctx, a.Domain, a.Owner, func(tx *sql.Tx) error {
|
||||
r, e := tx.ExecContext(ctx, `UPDATE feed_actions SET status='sending' WHERE domain_uuid=? AND owner_uuid=? AND request_id=? AND claim=? AND status='preparing' AND until_ms>? AND EXISTS(SELECT 1 FROM feed_sources WHERE uuid=? AND enabled=1 AND write_enabled=1 AND version=? AND lease=?)`, a.Domain, a.Owner, a.RequestID, a.Claim, time.Now().UnixMilli(), a.Source, source.Version, a.Claim)
|
||||
return feedActionAffected(r, e)
|
||||
})
|
||||
}
|
||||
func (s *Store) CompleteFeedAction(ctx context.Context, a FeedAction, source FeedSource, status, code string, observed *FeedItem) error {
|
||||
if (observed != nil && observed.ID != a.ID) || ((status == "confirmed" || status == "conflict") && observed == nil) {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
if status != "confirmed" && status != "unknown" && status != "failed" && status != "conflict" {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
switch code {
|
||||
case "", "network", "credentials", "invalid_feed", "remote_error", "conflict", "limit":
|
||||
default:
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
return s.feedWrite(ctx, a.Domain, a.Owner, func(tx *sql.Tx) error {
|
||||
r, e := tx.ExecContext(ctx, `UPDATE feed_sources SET lease='',lease_until=0 WHERE uuid=? AND version=? AND lease=? AND lease_until>? AND enabled=1`, a.Source, source.Version, a.Claim, time.Now().UnixMilli())
|
||||
if e = feedActionAffected(r, e); e != nil {
|
||||
return e
|
||||
}
|
||||
r, e = tx.ExecContext(ctx, `UPDATE feed_actions SET status=?,error=?,until_ms=CASE WHEN ?='unknown' THEN until_ms ELSE 0 END WHERE domain_uuid=? AND owner_uuid=? AND request_id=? AND claim=? AND status IN ('preparing','sending','checking')`, status, code, status, a.Domain, a.Owner, a.RequestID, a.Claim)
|
||||
if e = feedActionAffected(r, e); e != nil {
|
||||
return e
|
||||
}
|
||||
if observed != nil {
|
||||
_, e = tx.ExecContext(ctx, `UPDATE feed_items SET is_read=?,starred=? WHERE source_uuid=? AND id=?`, observed.Read, observed.Starred, a.Source, a.ID)
|
||||
}
|
||||
return e
|
||||
})
|
||||
}
|
||||
@@ -18,6 +18,51 @@ type FeedRemoteSubscription struct {
|
||||
Categories []FeedCategory `json:"categories"`
|
||||
}
|
||||
|
||||
type FeedCatalogSnapshot struct {
|
||||
Subscriptions []FeedRemoteSubscription `json:"subscriptions"`
|
||||
Folders []FeedCategory `json:"folders"`
|
||||
}
|
||||
|
||||
// Merge membership-derived folders with explicit folders, including empty
|
||||
// ones. IDs, not labels or slash-delimited paths, are the identity boundary.
|
||||
func FeedFolders(catalog []FeedRemoteSubscription, folders []FeedCategory) ([]FeedCategory, error) {
|
||||
out := []FeedCategory{}
|
||||
seen := map[string]string{}
|
||||
add := func(c FeedCategory) error {
|
||||
if !ValidFeedRemoteID(c.ID) || len(c.Label) > 512 || !utf8.ValidString(c.Label) {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
if label, ok := seen[c.ID]; ok {
|
||||
if label != c.Label {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
seen[c.ID] = c.Label
|
||||
out = append(out, c)
|
||||
if len(out) > 1000 {
|
||||
return ErrTaskDAVLimit
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(folders) > 1000 {
|
||||
return nil, ErrTaskDAVLimit
|
||||
}
|
||||
for _, c := range folders {
|
||||
if e := add(c); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
for _, sub := range catalog {
|
||||
for _, c := range sub.Categories {
|
||||
if e := add(c); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func ValidFeedRemoteID(id string) bool {
|
||||
return id != "" && len(id) <= 2048 && utf8.ValidString(id) && !strings.ContainsAny(id, "\x00\r\n")
|
||||
}
|
||||
@@ -59,17 +104,47 @@ func FeedCatalogJSON(catalog []FeedRemoteSubscription) (string, error) {
|
||||
return string(raw), nil
|
||||
}
|
||||
|
||||
func (s *Store) FeedCatalog(ctx context.Context, domain, owner, source string) ([]FeedRemoteSubscription, error) {
|
||||
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
|
||||
return nil, e
|
||||
// Validate the complete snapshot before persisting or reporting fetch success.
|
||||
func (v FeedCatalogSnapshot) Encode() (string, string, error) {
|
||||
catalog, e := FeedCatalogJSON(v.Subscriptions)
|
||||
if e != nil {
|
||||
return "", "", e
|
||||
}
|
||||
var raw string
|
||||
if e := s.DB.QueryRowContext(ctx, `SELECT remote_catalog FROM feed_sources WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, source, domain, owner).Scan(&raw); e != nil {
|
||||
return nil, e
|
||||
folders, e := FeedFolders(v.Subscriptions, v.Folders)
|
||||
if e != nil {
|
||||
return "", "", e
|
||||
}
|
||||
var catalog []FeedRemoteSubscription
|
||||
if e := json.Unmarshal([]byte(raw), &catalog); e != nil {
|
||||
return nil, e
|
||||
raw, e := json.Marshal(folders)
|
||||
if e != nil {
|
||||
return "", "", e
|
||||
}
|
||||
return catalog, nil
|
||||
if len(raw)+len(catalog) > 1<<20 {
|
||||
return "", "", ErrTaskDAVLimit
|
||||
}
|
||||
return catalog, string(raw), nil
|
||||
}
|
||||
|
||||
func (s *Store) FeedCatalog(ctx context.Context, domain, owner, source string) ([]FeedRemoteSubscription, error) {
|
||||
v, e := s.FeedCatalogSnapshot(ctx, domain, owner, source)
|
||||
return v.Subscriptions, e
|
||||
}
|
||||
|
||||
func (s *Store) FeedCatalogSnapshot(ctx context.Context, domain, owner, source string) (FeedCatalogSnapshot, error) {
|
||||
v := FeedCatalogSnapshot{}
|
||||
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
|
||||
return v, e
|
||||
}
|
||||
var raw, folders string
|
||||
if e := s.DB.QueryRowContext(ctx, `SELECT remote_catalog,remote_folders FROM feed_sources WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, source, domain, owner).Scan(&raw, &folders); e != nil {
|
||||
return v, e
|
||||
}
|
||||
if e := json.Unmarshal([]byte(raw), &v.Subscriptions); e != nil {
|
||||
return v, e
|
||||
}
|
||||
if e := json.Unmarshal([]byte(folders), &v.Folders); e != nil {
|
||||
return v, e
|
||||
}
|
||||
var e error
|
||||
v.Folders, e = FeedFolders(v.Subscriptions, v.Folders)
|
||||
return v, e
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// FeedActionRecord is a receipt plus currently available local metadata. A
|
||||
// deleted source or evicted article must not hide an unresolved remote write.
|
||||
type FeedActionRecord struct {
|
||||
FeedAction
|
||||
SourceTitle string `json:"source_title"`
|
||||
ItemTitle string `json:"item_title"`
|
||||
SourcePresent bool `json:"source_present"`
|
||||
ItemPresent bool `json:"item_present"`
|
||||
CanCheck bool `json:"can_check"`
|
||||
CheckAfterMS int64 `json:"check_after_ms"`
|
||||
}
|
||||
|
||||
type FeedActionQuery struct {
|
||||
Source string
|
||||
Status string
|
||||
Before int64
|
||||
Key string
|
||||
}
|
||||
|
||||
const feedActionMetadata = `,COALESCE(s.title,''),COALESCE(i.title,''),s.uuid IS NOT NULL,i.id IS NOT NULL,COALESCE(s.enabled=1 AND s.provider='freshrss',0)`
|
||||
const feedActionJoins = ` FROM feed_actions a LEFT JOIN feed_sources s ON s.uuid=a.source_uuid AND s.domain_uuid=a.domain_uuid AND s.owner_uuid=a.owner_uuid LEFT JOIN feed_items i ON i.source_uuid=s.uuid AND i.id=a.item_id WHERE a.domain_uuid=? AND a.owner_uuid=?`
|
||||
|
||||
func feedActionRecordColumns() string {
|
||||
return "a." + strings.ReplaceAll(feedActionColumns, ",", ",a.") + feedActionMetadata
|
||||
}
|
||||
|
||||
func scanFeedActionRecord(row interface{ Scan(...any) error }, writable bool) (a FeedActionRecord, e error) {
|
||||
var enabled bool
|
||||
e = row.Scan(&a.Domain, &a.Owner, &a.RequestID, &a.Source, &a.ID, &a.Field, &a.Desired, &a.SourceVersion, &a.Status, &a.Claim, &a.UntilMS, &a.CreatedMS, &a.Error, &a.SourceTitle, &a.ItemTitle, &a.SourcePresent, &a.ItemPresent, &enabled)
|
||||
if a.Status == "unknown" {
|
||||
a.CheckAfterMS = a.UntilMS
|
||||
a.CanCheck = writable && enabled && a.UntilMS < time.Now().UnixMilli()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// FeedActionHistory returns at most 51 local receipts (50 plus a next-page
|
||||
// sentinel). The owner cap of 10,000 receipts bounds the sorting work even
|
||||
// without a new schema/index. No fetch, retry, expiry or deletion runs here.
|
||||
func (s *Store) FeedActionHistory(ctx context.Context, domain, owner string, q FeedActionQuery) ([]FeedActionRecord, error) {
|
||||
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
where := ""
|
||||
switch q.Status {
|
||||
case "", "unresolved":
|
||||
where = ` AND a.status NOT IN ('confirmed','cancelled')`
|
||||
case "all":
|
||||
case "pending":
|
||||
where = ` AND a.status IN ('queued','preparing','sending','check_queued','checking')`
|
||||
case "unknown", "confirmed", "failed", "conflict", "cancelled":
|
||||
where = ` AND a.status='` + q.Status + `'`
|
||||
default:
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
args := []any{domain, owner}
|
||||
if q.Source != "" {
|
||||
if _, e := uuid.Parse(q.Source); e != nil {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
where += ` AND a.source_uuid=?`
|
||||
args = append(args, q.Source)
|
||||
}
|
||||
if q.Before >= 0 {
|
||||
if _, e := uuid.Parse(q.Key); e != nil {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
where += ` AND (a.created_ms<? OR (a.created_ms=? AND a.request_id<?))`
|
||||
args = append(args, q.Before, q.Before, q.Key)
|
||||
} else if q.Before != -1 || q.Key != "" {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
writable := !s.ReadOnly && feedActor(ctx, s.DB, domain, owner, true) == nil
|
||||
rows, e := s.DB.QueryContext(ctx, `SELECT `+feedActionRecordColumns()+feedActionJoins+where+` ORDER BY a.created_ms DESC,a.request_id DESC LIMIT 51`, args...)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []FeedActionRecord{}
|
||||
for rows.Next() {
|
||||
a, e := scanFeedActionRecord(rows, writable)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) FeedActionRecord(ctx context.Context, domain, owner, request string) (FeedActionRecord, error) {
|
||||
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
|
||||
return FeedActionRecord{}, e
|
||||
}
|
||||
if _, e := uuid.Parse(request); e != nil {
|
||||
return FeedActionRecord{}, ErrTaskInvalid
|
||||
}
|
||||
writable := !s.ReadOnly && feedActor(ctx, s.DB, domain, owner, true) == nil
|
||||
return scanFeedActionRecord(s.DB.QueryRowContext(ctx, `SELECT `+feedActionRecordColumns()+feedActionJoins+` AND a.request_id=?`, domain, owner, request), writable)
|
||||
}
|
||||
@@ -150,3 +150,79 @@ func TestFeedCatalogMigrationRollbackAndRepeat(t *testing.T) {
|
||||
t.Fatal(integrity, e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedActionsMigrationRollbackAndRepeat(t *testing.T) {
|
||||
st := newSchemaTestStore(t)
|
||||
ctx := context.Background()
|
||||
if e := db.ApplySQLiteMigrations(ctx, st.DB, "feeds", feedMigrations[:4]); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := st.DB.Exec(`INSERT INTO feed_sources(uuid,domain_uuid,owner_uuid,provider,title,folder,url,version,enabled,interval_seconds) VALUES('s','d','u','freshrss','Title','','https://example.org',7,1,300)`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
broken := append([]db.SQLMigration(nil), feedMigrations...)
|
||||
broken[4].Statements = append(append([]string(nil), feedMigrations[4].Statements...), `INSERT INTO no_such_feed_table VALUES(1)`)
|
||||
if e := db.ApplySQLiteMigrations(ctx, st.DB, "feeds", broken); e == nil {
|
||||
t.Fatal("expected failure")
|
||||
}
|
||||
var count int
|
||||
if e := st.DB.QueryRow(`SELECT count(*) FROM pragma_table_info('feed_sources') WHERE name='write_enabled'`).Scan(&count); e != nil || count != 0 {
|
||||
t.Fatal("partial schema", count, e)
|
||||
}
|
||||
for range 2 {
|
||||
if e := st.ensureSchemaComponent("feeds"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if e := st.DB.QueryRow(`SELECT write_enabled FROM feed_sources WHERE uuid='s'`).Scan(&count); e != nil || count != 0 {
|
||||
t.Fatal("write enabled during upgrade", count, e)
|
||||
}
|
||||
if _, e := st.DB.Exec(`INSERT INTO feed_actions(domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,created_ms) VALUES('d','u','r','s','i','read',1,7,'sending',1); DELETE FROM feed_sources WHERE uuid='s'`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var status string
|
||||
if e := st.DB.QueryRow(`SELECT status FROM feed_actions WHERE request_id='r'`).Scan(&status); e != nil || status != "unknown" {
|
||||
t.Fatal("lost uncertain receipt", status, e)
|
||||
}
|
||||
if e := st.DB.QueryRow(`PRAGMA integrity_check`).Scan(&status); e != nil || status != "ok" {
|
||||
t.Fatal(status, e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedFoldersMigrationRollbackAndRepeat(t *testing.T) {
|
||||
st := newSchemaTestStore(t)
|
||||
ctx := context.Background()
|
||||
if e := db.ApplySQLiteMigrations(ctx, st.DB, "feeds", feedMigrations[:5]); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
const catalog = `[{"id":"feed/1","title":"Title","categories":[{"id":"category","label":"Folder"}]}]`
|
||||
if _, e := st.DB.Exec(`INSERT INTO feed_sources(uuid,domain_uuid,owner_uuid,provider,title,folder,url,version,enabled,interval_seconds,lease,next_ms,remote_catalog) VALUES('s','d','u','freshrss','Title','','https://example.org',7,1,300,'worker',999,?);
|
||||
INSERT INTO feed_actions(domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,created_ms) VALUES('d','u','r','s','i','read',1,7,'queued',1)`, catalog); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
broken := append([]db.SQLMigration(nil), feedMigrations...)
|
||||
broken[5].Statements = append(append([]string(nil), feedMigrations[5].Statements...), `INSERT INTO no_such_feed_table VALUES(1)`)
|
||||
if e := db.ApplySQLiteMigrations(ctx, st.DB, "feeds", broken); e == nil {
|
||||
t.Fatal("expected failure")
|
||||
}
|
||||
var count int
|
||||
if e := st.DB.QueryRow(`SELECT count(*) FROM pragma_table_info('feed_sources') WHERE name='remote_folders'`).Scan(&count); e != nil || count != 0 {
|
||||
t.Fatal("partial schema", count, e)
|
||||
}
|
||||
for range 2 {
|
||||
if e := st.ensureSchemaComponent("feeds"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
var version, next int
|
||||
var got, folders, lease, status string
|
||||
if e := st.DB.QueryRow(`SELECT version,next_ms,lease,remote_catalog,remote_folders FROM feed_sources WHERE uuid='s'`).Scan(&version, &next, &lease, &got, &folders); e != nil || version != 7 || next != 999 || lease != "worker" || got != catalog || folders != "[]" {
|
||||
t.Fatal("existing state changed", version, next, lease, got, folders, e)
|
||||
}
|
||||
if e := st.DB.QueryRow(`SELECT status FROM feed_actions WHERE request_id='r'`).Scan(&status); e != nil || status != "queued" {
|
||||
t.Fatal("pending action changed", status, e)
|
||||
}
|
||||
if e := st.DB.QueryRow(`PRAGMA integrity_check`).Scan(&status); e != nil || status != "ok" {
|
||||
t.Fatal(status, e)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
@@ -69,6 +70,10 @@ func (s *Store) ResolvePathInDomain(
|
||||
domainUUID string,
|
||||
path string,
|
||||
) (string, error) {
|
||||
return s.ResolvePathInDomainContext(context.Background(), domainUUID, path)
|
||||
}
|
||||
|
||||
func (s *Store) ResolvePathInDomainContext(ctx context.Context, domainUUID, path string) (string, error) {
|
||||
path = normalizePath(path)
|
||||
if err := s.ensureLocalDomain(domainUUID); err != nil {
|
||||
return "", err
|
||||
@@ -76,7 +81,7 @@ func (s *Store) ResolvePathInDomain(
|
||||
|
||||
var objectUUID string
|
||||
|
||||
err := s.DB.QueryRow(`
|
||||
err := s.DB.QueryRowContext(ctx, `
|
||||
SELECT object_uuid
|
||||
FROM paths
|
||||
WHERE domain_uuid = ?
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
@@ -324,6 +325,10 @@ func (s *Store) GetRevision(
|
||||
}
|
||||
|
||||
func (s *Store) GetLatestRevisionMetadataForLanguages(objectUUID string, rawLanguages []string) (*Revision, error) {
|
||||
return s.GetLatestRevisionMetadataForLanguagesContext(context.Background(), objectUUID, rawLanguages)
|
||||
}
|
||||
|
||||
func (s *Store) GetLatestRevisionMetadataForLanguagesContext(ctx context.Context, objectUUID string, rawLanguages []string) (*Revision, error) {
|
||||
candidates := make([]string, 0, len(rawLanguages)+1)
|
||||
seen := map[string]bool{}
|
||||
for _, rawLanguage := range rawLanguages {
|
||||
@@ -336,7 +341,7 @@ func (s *Store) GetLatestRevisionMetadataForLanguages(objectUUID string, rawLang
|
||||
candidates = append(candidates, "und")
|
||||
}
|
||||
for _, lang := range candidates {
|
||||
row := s.DB.QueryRow(`SELECT uuid,object_uuid,COALESCE(document_hash,''),COALESCE(NULLIF(lang,''),'und'),COALESCE(NULLIF(content_type,''),'text/html; charset=utf-8'),COALESCE(filename,''),'',COALESCE(message,''),COALESCE(created_at,0),COALESCE(created_at_ms,COALESCE(created_at,0)*1000) FROM revisions WHERE object_uuid=? AND COALESCE(NULLIF(lang,''),'und')=? ORDER BY COALESCE(created_at_ms,created_at*1000) DESC,rowid DESC LIMIT 1`, objectUUID, lang)
|
||||
row := s.DB.QueryRowContext(ctx, `SELECT uuid,object_uuid,COALESCE(document_hash,''),COALESCE(NULLIF(lang,''),'und'),COALESCE(NULLIF(content_type,''),'text/html; charset=utf-8'),COALESCE(filename,''),'',COALESCE(message,''),COALESCE(created_at,0),COALESCE(created_at_ms,COALESCE(created_at,0)*1000) FROM revisions WHERE object_uuid=? AND COALESCE(NULLIF(lang,''),'und')=? ORDER BY COALESCE(created_at_ms,created_at*1000) DESC,rowid DESC LIMIT 1`, objectUUID, lang)
|
||||
revision, err := scanRevision(row)
|
||||
if err == nil {
|
||||
return revision, nil
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// A receipt without a live task or a deletion marker needs repair, not an
|
||||
// implicit create that could silently revive an inconsistent record.
|
||||
var ErrTaskCaptureMissing = errors.New("captured task is missing without a deletion record")
|
||||
|
||||
func TaskRecreationID(request string) string {
|
||||
return uuid.NewSHA1(uuid.NameSpaceURL, []byte("pages:task-recreate:"+request)).String()
|
||||
}
|
||||
|
||||
func deletedCapture(ctx context.Context, q interface {
|
||||
QueryRowContext(context.Context, string, ...any) *sql.Row
|
||||
}, domain, actor, request string) error {
|
||||
var id string
|
||||
if err := q.QueryRowContext(ctx, `SELECT item_uuid FROM organizer_capture_receipts WHERE domain_uuid=? AND owner_uuid=? AND request_uuid=?`, domain, actor, request).Scan(&id); err != nil {
|
||||
return err
|
||||
}
|
||||
var live, deleted bool
|
||||
if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_items WHERE domain_uuid=? AND uuid=?), EXISTS(SELECT 1 FROM organizer_task_deletions WHERE domain_uuid=? AND owner_uuid=? AND item_uuid=?)`, domain, id, domain, actor, id).Scan(&live, &deleted); err != nil {
|
||||
return err
|
||||
}
|
||||
if live {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
if !deleted {
|
||||
return ErrTaskCaptureMissing
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecreateCapturedTask never removes old receipts, tombstones or DAV identity
|
||||
// reservations. A deterministic successor ID makes a lost response retry safe.
|
||||
// The caller authorizes read/create/write for target, including retained pages.
|
||||
func (s *Store) RecreateCapturedTask(ctx context.Context, domain, actor, request, hash string, item TaskRecord, target, body, replaces string) (TaskRecord, error) {
|
||||
id, err := uuid.Parse(replaces)
|
||||
if err != nil || id.String() != replaces || request != TaskRecreationID(replaces) {
|
||||
return TaskRecord{}, ErrTaskInvalid
|
||||
}
|
||||
if err = taskActor(ctx, s.DB, domain, actor, true); err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
if err = deletedCapture(ctx, s.DB, domain, actor, replaces); err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
return s.captureTaskWithWiki(ctx, domain, actor, request, hash, item, target, body, replaces)
|
||||
}
|
||||
@@ -35,6 +35,34 @@ func ValidTaskWikiPrefix(p string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Expand only the documented placeholders. Subject is one safe path component,
|
||||
// never a source of separators or URI operators. Callers choose the timezone.
|
||||
func ExpandWikiPrefix(template, subject string, now time.Time) (string, error) {
|
||||
if len(template) > 500 || !utf8.ValidString(template) || !utf8.ValidString(subject) {
|
||||
return "", ErrTaskInvalid
|
||||
}
|
||||
name := strings.Map(func(r rune) rune {
|
||||
if unicode.IsControl(r) || unicode.IsSpace(r) || strings.ContainsRune(`/\?#%:{}<>"|`, r) {
|
||||
return '-'
|
||||
}
|
||||
return r
|
||||
}, subject)
|
||||
name = strings.Trim(name, " .-_")
|
||||
for len(name) > 180 {
|
||||
_, n := utf8.DecodeLastRuneInString(name)
|
||||
name = name[:len(name)-n]
|
||||
}
|
||||
name = strings.Trim(name, " .-_")
|
||||
if name == "" {
|
||||
name = "untitled"
|
||||
}
|
||||
result := strings.NewReplacer("{YYYY}", now.Format("2006"), "{MM}", now.Format("01"), "{DD}", now.Format("02"), "{Subject}", name).Replace(template)
|
||||
if strings.ContainsAny(result, "{}") || !ValidTaskWikiPrefix(result) {
|
||||
return "", ErrTaskInvalid
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// The CLI derives the request UUID from origin, user and Message-ID (or a raw
|
||||
// mail hash). Keep subjects in the title, never in the URL's identity segment.
|
||||
func TaskCaptureWikiPath(prefix, title, request string) string {
|
||||
@@ -49,8 +77,12 @@ func ValidTaskMailSuffix(s string) bool {
|
||||
return mailListSuffix.MatchString(s) || (mailMonthSuffix.MatchString(s) && !strings.HasPrefix(s, "0000/"))
|
||||
}
|
||||
|
||||
func validCapturedTaskWiki(target, body string) bool {
|
||||
return target != "" && ValidTaskWikiPrefix(path.Dir(target)) && path.Clean(target) == target && len(body) <= 256<<10 && utf8.ValidString(body) && strings.IndexByte(body, 0) < 0
|
||||
}
|
||||
|
||||
func (s *Store) createCapturedTaskWiki(ctx context.Context, tx *sql.Tx, domain, actor string, item *TaskRecord, target, body string) error {
|
||||
if target == "" || !ValidTaskWikiPrefix(path.Dir(target)) || path.Clean(target) != target || item.PageUUID != "" || len(body) > 256<<10 || !utf8.ValidString(body) || strings.IndexByte(body, 0) >= 0 {
|
||||
if !validCapturedTaskWiki(target, body) || item.PageUUID != "" {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
var exists bool
|
||||
|
||||
@@ -54,6 +54,9 @@ func (s *Store) ensureTaskDAVSchema() error {
|
||||
`DELETE FROM organizer_dav_collections`,
|
||||
`INSERT INTO organizer_dav_collections(domain_uuid,path,owner_uuid,project_uuid) SELECT domain_uuid,COALESCE(NULLIF(json_extract(data,'$.dav_collection'),''),'tasks/projects/'||uuid),owner_uuid,uuid FROM organizer_items WHERE kind='project'`,
|
||||
`INSERT INTO organizer_dav_resources(domain_uuid,owner_uuid,item_uuid,name,uid) SELECT domain_uuid,owner_uuid,uuid,CASE WHEN project_uuid='' THEN '' ELSE char(0)||project_uuid||char(0) END||COALESCE(json_extract(data,'$.caldav.name'),uuid||'.ics'),CASE WHEN project_uuid='' THEN '' ELSE char(0)||project_uuid||char(0) END||COALESCE(json_extract(data,'$.caldav.uid'),uuid) FROM organizer_items WHERE kind='task'`,
|
||||
// Deleted identities remain reserved after an index rebuild. A stale
|
||||
// client PUT must not silently resurrect a deliberately removed task.
|
||||
`INSERT INTO organizer_dav_resources(domain_uuid,owner_uuid,item_uuid,name,uid) SELECT domain_uuid,owner_uuid,item_uuid,dav_name,dav_uid FROM organizer_task_deletions`,
|
||||
} {
|
||||
if _, err = tx.Exec(q); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var ErrTaskDeleted = errors.New("task has been deleted")
|
||||
var ErrTaskHasChildren = errors.New("move or delete subtasks first")
|
||||
var ErrTaskWorking = errors.New("stop task work and focus sessions first")
|
||||
|
||||
// DeleteTask is deliberately separate from reversible archiving. The head and
|
||||
// revision references are removed; minimal identity tombstones prevent offline
|
||||
// clients from resurrecting the same task. Wiki documents, calendar events and
|
||||
// completed work records are independent resources and are not deleted here.
|
||||
// CAS blobs/backups are not securely erased by this operation.
|
||||
func (s *Store) DeleteTask(ctx context.Context, domain, actor, id string, expected int64) error {
|
||||
if s.ReadOnly {
|
||||
return ErrReadOnly
|
||||
}
|
||||
u, err := uuid.Parse(id)
|
||||
if err != nil || u.String() != id || expected < 1 {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE domain_memberships SET state=state WHERE domain_uuid=? AND principal_uuid=?`, domain, actor); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = taskActor(ctx, tx, domain, actor, true); err != nil {
|
||||
return err
|
||||
}
|
||||
enabled, err := taskReminderExtensionEnabled(ctx, tx, domain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !enabled {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
var raw string
|
||||
err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND uuid=?`, domain, actor, id).Scan(&raw)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
// A lost successful DELETE response can be retried with its original
|
||||
// precondition, without disclosing another owner's tombstone.
|
||||
var version int64
|
||||
if e := tx.QueryRowContext(ctx, `SELECT version FROM organizer_task_deletions WHERE domain_uuid=? AND owner_uuid=? AND item_uuid=?`, domain, actor, id).Scan(&version); e != nil {
|
||||
return e
|
||||
}
|
||||
if version-1 != expected {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var item TaskRecord
|
||||
if err = json.Unmarshal([]byte(raw), &item); err != nil {
|
||||
return err
|
||||
}
|
||||
if item.Kind != "task" {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
if item.Version != expected {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
var children, working bool
|
||||
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND parent_uuid=?)`, domain, actor, id).Scan(&children); err != nil {
|
||||
return err
|
||||
}
|
||||
if children {
|
||||
return ErrTaskHasChildren
|
||||
}
|
||||
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_focus WHERE domain_uuid=? AND owner_uuid=? AND task_uuid=? AND state IN ('running','paused')) OR EXISTS(SELECT 1 FROM organizer_work_sessions WHERE domain_uuid=? AND owner_uuid=? AND task_uuid=? AND end_ms=0 AND cancelled_ms=0)`, domain, actor, id, domain, actor, id).Scan(&working); err != nil {
|
||||
return err
|
||||
}
|
||||
if working {
|
||||
return ErrTaskWorking
|
||||
}
|
||||
name, uid := id+".ics", id
|
||||
if item.CalDAV != nil {
|
||||
name, uid = item.CalDAV.Name, item.CalDAV.UID
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_task_deletions(domain_uuid,owner_uuid,item_uuid,dav_name,dav_uid,version,deleted_at_ms) VALUES(?,?,?,?,?,?,?)`, domain, actor, id, taskDAVIndexKey(item.ProjectUUID, name), taskDAVIndexKey(item.ProjectUUID, uid), item.Version+1, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, q := range []string{
|
||||
`DELETE FROM organizer_reminders WHERE domain_uuid=? AND item_uuid=?`,
|
||||
`DELETE FROM organizer_task_metrics WHERE domain_uuid=? AND task_uuid=?`,
|
||||
`UPDATE organizer_time_blocks SET state='unlinked' WHERE domain_uuid=? AND task_uuid=?`,
|
||||
`DELETE FROM organizer_revisions WHERE domain_uuid=? AND item_uuid=?`,
|
||||
`DELETE FROM organizer_items WHERE domain_uuid=? AND uuid=?`,
|
||||
} {
|
||||
if _, err = tx.ExecContext(ctx, q, domain, id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO organizer_changes(domain_uuid,item_uuid,version,actor_uuid,created_at_ms) VALUES(?,?,?,?,?)`, domain, id, item.Version+1, actor, now); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = s.appendTaskActivityTx(tx, domain, actor, id, "task", item.Version+1, now); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -64,6 +64,7 @@ type TaskPreferences struct {
|
||||
Version int64 `json:"version"`
|
||||
ProjectUUID string `json:"project_uuid"`
|
||||
WikiPrefix string `json:"wiki_prefix"`
|
||||
RSSLinkMode string `json:"rss_link_mode"`
|
||||
AssigneeUUID string `json:"assignee_uuid"`
|
||||
DueDays *int `json:"due_days"`
|
||||
StartDays *int `json:"start_days"`
|
||||
@@ -80,7 +81,7 @@ type TaskPreferences struct {
|
||||
}
|
||||
|
||||
func (s *Store) TaskPreferences(ctx context.Context, domain, actor string) (TaskPreferences, error) {
|
||||
p := TaskPreferences{AssigneeUUID: actor, Complexity: 1, ReminderTime: "09:00", DigestTime: "09:00", Timezone: "UTC"}
|
||||
p := TaskPreferences{AssigneeUUID: actor, Complexity: 1, ReminderTime: "09:00", DigestTime: "09:00", Timezone: "UTC", RSSLinkMode: "tab"}
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return p, err
|
||||
}
|
||||
@@ -120,7 +121,13 @@ func (s *Store) SaveTaskPreferences(ctx context.Context, domain, actor string, p
|
||||
if s.ReadOnly {
|
||||
return p, ErrReadOnly
|
||||
}
|
||||
if !ValidTaskWikiPrefix(p.WikiPrefix) {
|
||||
if _, err := ExpandWikiPrefix(p.WikiPrefix, "subject", now); err != nil {
|
||||
return p, ErrTaskInvalid
|
||||
}
|
||||
if p.RSSLinkMode == "" {
|
||||
p.RSSLinkMode = "tab"
|
||||
}
|
||||
if p.RSSLinkMode != "tab" && p.RSSLinkMode != "embedded" && p.RSSLinkMode != "gecko" {
|
||||
return p, ErrTaskInvalid
|
||||
}
|
||||
// Older clients do not send this field. Preserve their default clock.
|
||||
@@ -220,10 +227,22 @@ func (s *Store) CapturedTask(ctx context.Context, domain, actor, request, hash s
|
||||
if err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
// Check lifecycle before payload equality. A retained receipt must not
|
||||
// disguise a deleted task as an editable version conflict.
|
||||
item, err := s.GetTask(ctx, domain, actor, id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
if err = deletedCapture(ctx, s.DB, domain, actor, request); err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
return TaskRecord{}, ErrTaskDeleted
|
||||
}
|
||||
if err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
if stored != hash {
|
||||
return TaskRecord{}, ErrTaskConflict
|
||||
}
|
||||
return s.GetTask(ctx, domain, actor, id)
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (s *Store) CaptureTask(ctx context.Context, domain, actor, request, hash string, item TaskRecord) (TaskRecord, error) {
|
||||
@@ -233,6 +252,10 @@ func (s *Store) CaptureTask(ctx context.Context, domain, actor, request, hash st
|
||||
// CaptureTaskWithWiki commits the task, receipt and optional Wiki page together.
|
||||
// The HTTP caller must authorize read/create/write for the exact target path.
|
||||
func (s *Store) CaptureTaskWithWiki(ctx context.Context, domain, actor, request, hash string, item TaskRecord, target, body string) (TaskRecord, error) {
|
||||
return s.captureTaskWithWiki(ctx, domain, actor, request, hash, item, target, body, "")
|
||||
}
|
||||
|
||||
func (s *Store) captureTaskWithWiki(ctx context.Context, domain, actor, request, hash string, item TaskRecord, target, body, replaces string) (TaskRecord, error) {
|
||||
if _, err := uuid.Parse(request); err != nil {
|
||||
return TaskRecord{}, ErrTaskInvalid
|
||||
}
|
||||
@@ -245,11 +268,31 @@ func (s *Store) CaptureTaskWithWiki(ctx context.Context, domain, actor, request,
|
||||
}
|
||||
item.UUID = request
|
||||
out, err := s.saveTask(ctx, domain, actor, item, 0, func(tx *sql.Tx, current *TaskRecord, _ TaskRecord) error {
|
||||
if target != "" {
|
||||
if e := s.createCapturedTaskWiki(ctx, tx, domain, actor, current, target, body); e != nil {
|
||||
if replaces != "" {
|
||||
if e := deletedCapture(ctx, tx, domain, actor, replaces); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if target != "" {
|
||||
if !validCapturedTaskWiki(target, body) || current.PageUUID != "" {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
// Explicit recreation may reuse a surviving Wiki page. Its content
|
||||
// and revisions are independent of task deletion and never replaced.
|
||||
reused := false
|
||||
if replaces != "" {
|
||||
e := tx.QueryRowContext(ctx, `SELECT p.object_uuid FROM paths p JOIN objects o ON o.uuid=p.object_uuid WHERE p.domain_uuid=? AND p.path=? AND o.kind='page'`, domain, target).Scan(¤t.PageUUID)
|
||||
if e != nil && !errors.Is(e, sql.ErrNoRows) {
|
||||
return e
|
||||
}
|
||||
reused = e == nil
|
||||
}
|
||||
if !reused {
|
||||
if e := s.createCapturedTaskWiki(ctx, tx, domain, actor, current, target, body); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
_, e := tx.ExecContext(ctx, `INSERT INTO organizer_capture_receipts VALUES(?,?,?,?,?)`, domain, actor, request, hash, item.UUID)
|
||||
return e
|
||||
})
|
||||
|
||||
@@ -81,6 +81,10 @@ func (s *Store) EnsureTasksSchema() error {
|
||||
UNIQUE(domain_uuid,item_uuid,version))`,
|
||||
`CREATE TABLE IF NOT EXISTS organizer_activity_bridge(id INTEGER PRIMARY KEY CHECK(id=1),last_sequence INTEGER NOT NULL DEFAULT 0)`,
|
||||
`INSERT OR IGNORE INTO organizer_activity_bridge(id,last_sequence) VALUES(1,0)`,
|
||||
`CREATE TABLE IF NOT EXISTS organizer_task_deletions (
|
||||
domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,item_uuid TEXT NOT NULL,
|
||||
dav_name TEXT NOT NULL,dav_uid TEXT NOT NULL,version INTEGER NOT NULL,deleted_at_ms INTEGER NOT NULL,
|
||||
PRIMARY KEY(domain_uuid,item_uuid))`,
|
||||
} {
|
||||
if _, err := s.DB.Exec(q); err != nil {
|
||||
return err
|
||||
@@ -227,6 +231,17 @@ func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRec
|
||||
if enabled, exists := states["organizer.tasks"]; exists && !enabled {
|
||||
return TaskRecord{}, ErrAccessDenied
|
||||
}
|
||||
var deletedOwner string
|
||||
err = tx.QueryRowContext(ctx, `SELECT owner_uuid FROM organizer_task_deletions WHERE domain_uuid=? AND item_uuid=?`, domain, item.UUID).Scan(&deletedOwner)
|
||||
if err == nil {
|
||||
if deletedOwner != actor {
|
||||
return TaskRecord{}, sql.ErrNoRows
|
||||
}
|
||||
return TaskRecord{}, ErrTaskDeleted
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
if item.NotifyDue || item.NotifyPlanned {
|
||||
item.ReminderTimezone = "UTC"
|
||||
err = tx.QueryRowContext(ctx, `SELECT value FROM config WHERE domain_uuid=? AND key='timezone'`, domain).Scan(&item.ReminderTimezone)
|
||||
|
||||
@@ -44,7 +44,7 @@ func (s *Store) PublishTaskActivity(ctx context.Context, limit int) (int, int, e
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE organizer_activity_bridge SET last_sequence=last_sequence WHERE id=1`); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, `SELECT c.sequence,c.domain_uuid,c.item_uuid,c.version,c.actor_uuid,c.created_at_ms,COALESCE(i.kind,'') FROM organizer_changes c LEFT JOIN organizer_items i ON i.domain_uuid=c.domain_uuid AND i.uuid=c.item_uuid WHERE c.sequence>(SELECT last_sequence FROM organizer_activity_bridge WHERE id=1) ORDER BY c.sequence LIMIT ?`, limit)
|
||||
rows, err := tx.QueryContext(ctx, `SELECT c.sequence,c.domain_uuid,c.item_uuid,c.version,c.actor_uuid,c.created_at_ms,COALESCE(i.kind,CASE WHEN d.item_uuid IS NOT NULL THEN 'task' ELSE '' END) FROM organizer_changes c LEFT JOIN organizer_items i ON i.domain_uuid=c.domain_uuid AND i.uuid=c.item_uuid LEFT JOIN organizer_task_deletions d ON d.domain_uuid=c.domain_uuid AND d.item_uuid=c.item_uuid WHERE c.sequence>(SELECT last_sequence FROM organizer_activity_bridge WHERE id=1) ORDER BY c.sequence LIMIT ?`, limit)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestExpandWikiPrefix(t *testing.T) {
|
||||
now := time.Date(2026, 12, 31, 18, 0, 0, 0, time.UTC).In(time.FixedZone("JST", 9*3600))
|
||||
for _, tt := range []struct{ template, subject, want string }{
|
||||
{"/notes/{YYYY}/{MM}/{DD}/{Subject}", "日本語 / ../ x?y#z", "/notes/2027/01/01/日本語---..--x-y-z"},
|
||||
{"/notes/{Subject}", "../", "/notes/untitled"},
|
||||
{"/notes/{Subject}", "{YYYY}", "/notes/YYYY"},
|
||||
{"/notes", "unused", "/notes"},
|
||||
{"", "", ""},
|
||||
} {
|
||||
got, err := ExpandWikiPrefix(tt.template, tt.subject, now)
|
||||
if err != nil || got != tt.want {
|
||||
t.Fatalf("%q: %q, %v; want %q", tt.template, got, err, tt.want)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"/notes/{YY}", "/notes/{{Subject}}", "/notes/{Subject", "/a/../b/{YYYY}", "/_/api/{Subject}", "relative/{YYYY}"} {
|
||||
if _, err := ExpandWikiPrefix(bad, "subject", now); err == nil {
|
||||
t.Fatal("accepted", bad)
|
||||
}
|
||||
}
|
||||
got, err := ExpandWikiPrefix("/notes/{Subject}", strings.Repeat("日本語", 200), now)
|
||||
if err != nil || len(got) > len("/notes/")+180 || !ValidTaskWikiPrefix(got) {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user