Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96065d1e89 | ||
|
|
2cbaa9342d | ||
|
|
38b0fe2a94 | ||
|
|
667776e43f | ||
|
|
02edb51b8a | ||
|
|
b61fbc38a4 | ||
|
|
02fb77f72b | ||
|
|
09afb438c9 | ||
|
|
2d6ceac0d7 | ||
|
|
bd80ff6a0c | ||
|
|
b90aef79d0 | ||
|
|
84d52390f9 | ||
|
|
4049acf76e | ||
|
|
43a2d8c5a1 | ||
|
|
38a4fcf530 | ||
|
|
dc978231e2 | ||
|
|
5321d613b4 | ||
|
|
b23e63d4c6 | ||
|
|
f4869c7c8b | ||
|
|
ea1ca432c5 | ||
|
|
c2bc637704 | ||
|
|
a5f90f933d | ||
|
|
78da33d549 | ||
|
|
50a90bcc14 | ||
|
|
bf9a9c2847 | ||
|
|
1057be6d2b | ||
|
|
e4c184d71c | ||
|
|
4711a0efbf | ||
|
|
61ecd1ffbd | ||
|
|
131a7ca01f | ||
|
|
16e572397b | ||
|
|
bfed3d20f5 | ||
|
|
7fe64113c7 | ||
|
|
38daea737d | ||
|
|
0d8997972c | ||
|
|
0c2cf263b6 | ||
|
|
269f835c3a | ||
|
|
b9e775de13 | ||
|
|
e65ca56f92 | ||
|
|
6e0aecdfb3 | ||
|
|
0964fdc5b7 | ||
|
|
c7aa4fd7dd | ||
|
|
1a451023f0 | ||
|
|
543814cbd6 | ||
|
|
3262f88005 | ||
|
|
0b6343aff0 |
No files matched your search
@@ -35,8 +35,8 @@ jobs:
|
||||
[worker.oci]
|
||||
max-parallelism = 2
|
||||
|
||||
- name: Test release tooling
|
||||
run: node --test tools/ci/release-images.test.mjs
|
||||
- name: Test release tooling and browser logic
|
||||
run: node --test tools/ci/release-images.test.mjs static/js/home-palette-core.test.cjs static/js/csv-core.test.cjs
|
||||
|
||||
- name: Test
|
||||
uses: https://github.com/docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
@@ -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
|
||||
|
||||
@@ -5,6 +5,7 @@ data/*
|
||||
!data/test_cli_dr.py
|
||||
!data/pageswiki-remote
|
||||
/data2/
|
||||
/docs/local/
|
||||
/.codex/
|
||||
/.agents/
|
||||
/.env
|
||||
|
||||
+7
-1
@@ -11,7 +11,13 @@ RUN go mod download
|
||||
COPY . .
|
||||
|
||||
FROM source AS test
|
||||
RUN go 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.
|
||||
# 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"]
|
||||
@@ -342,6 +342,12 @@ window.PagesWikiEditor = {
|
||||
}),
|
||||
];
|
||||
|
||||
if (options.preserveLineEndings) {
|
||||
// Split only at LF, keeping any CR bytes in the document. This
|
||||
// preserves mixed LF/CRLF CSV sources instead of rewriting them.
|
||||
extensions.push(EditorState.lineSeparator.of("\n"));
|
||||
}
|
||||
|
||||
if (keymapName === "vim") {
|
||||
installVimCommands();
|
||||
extensions.push(vim());
|
||||
|
||||
@@ -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}
|
||||
@@ -0,0 +1,5 @@
|
||||
services:
|
||||
app:
|
||||
image: pageswiki-app:task-index-20261109
|
||||
app2:
|
||||
image: pageswiki-app:task-index-20261109
|
||||
@@ -1,5 +1,35 @@
|
||||
# Architecture Implementation Roadmap
|
||||
|
||||
## Current backlog reconciliation (2026-11-08)
|
||||
|
||||
Use the [Japanese implementation backlog](ja/implementation-backlog.md) for the current
|
||||
execution order, stable task IDs, acceptance criteria and explicit holds. Baseline: `e65ca56`.
|
||||
Broad historical checkboxes below may contain implemented slices; they are not a count of
|
||||
unimplemented features. Source completion, physical-client acceptance and production rollout
|
||||
remain separate gates. The 2026-10-31 UX priorities below are historical context.
|
||||
|
||||
## Daily email history and controlled retries (2026-11-08)
|
||||
|
||||
- [x] Private, paginated delivery history and explicit same-day retry from personal settings.
|
||||
- [x] Durable request receipts, attempt-generation fencing, opt-out/version/revocation rechecks and duplicate-delivery acknowledgment.
|
||||
- [x] Bounded 90-day detail cleanup; preserve daily reservations and retry receipts permanently.
|
||||
- [x] Additive schema v4 with old-state preservation, interrupted-migration rollback and integrity tests.
|
||||
- [ ] Production rollout; backup restoration must reconcile external SMTP effects before resuming delivery.
|
||||
- [ ] Retention controls, safe receipt compaction, queued-request cancellation and Inbox outcomes.
|
||||
|
||||
See [delivery contracts and recovery](ja/task-digest-delivery.md).
|
||||
|
||||
## Work history and project reporting (2026-11-08)
|
||||
|
||||
- [x] Owner-scoped paginated work history with inline correction/cancellation and lazy revision display.
|
||||
- [x] Atomic immutable audit snapshots, optimistic concurrency, current authorization and cross-Domain overlap checks.
|
||||
- [x] Exclude cancelled time from reports; aggregate by current project without per-project queries.
|
||||
- [x] Task/dashboard navigation, Japanese/English UI and desktop/mobile browser coverage.
|
||||
- [ ] Production rollout with an aligned DB backup; old binaries must not read the upgraded DB.
|
||||
- [ ] Revoked-Domain recording recovery, cancellation restoration and audit retention policy.
|
||||
|
||||
See [work history contracts and migration](ja/task-productivity-contacts.md).
|
||||
|
||||
## Organizer dashboard (2026-11-02)
|
||||
|
||||
- [x] Common navigation for tasks, calendars, contacts and dashboard; home/navbar contacts entry.
|
||||
@@ -17,7 +47,7 @@ See [dashboard contracts](ja/organizer-dashboard.md). Production rollout is a se
|
||||
- [x] Add home search commands with project/calendar suggestions and explicit creation confirmation.
|
||||
- [x] Add private contacts CRUD, trash/restore, vCard import/export and unknown-property preservation.
|
||||
- [x] Add private CardDAV serving with isolated credentials, conditional writes, bounded reports and sync tokens; revision preview/restore and whole-book export (2026-11-02).
|
||||
- [ ] Shared address books, external CardDAV connectors, physical-device compatibility, work-record corrections and manual digest retry.
|
||||
- [ ] Shared address books, external CardDAV connectors and physical-device compatibility.
|
||||
|
||||
See [CardDAV operation and limits](../operations/carddav-contacts.md). The private profile is not full CardDAV compliance; production rollout is tracked separately.
|
||||
|
||||
@@ -78,9 +108,11 @@ See [component names, boundaries and acceptance criteria](ja/component-names.md)
|
||||
All eight initial component extractions are implemented; unchecked items describe remaining capabilities.
|
||||
Released and deployed as [v0.2.0](../operations/deployments/2026-11-01-v0.2.0.md) on 2026-11-01.
|
||||
|
||||
- [ ] Priority follow-up: eliminate AddEventLog deferred read-to-write transaction contention;
|
||||
preserve atomic raw-log/bucket writes and test independent concurrent writers. Production
|
||||
start-log failures are now observable; job execution succeeded, but log completeness is not guaranteed.
|
||||
- [x] Eliminate AddEventLog deferred read-to-write transaction contention with writer-first
|
||||
acquisition, atomic raw-log/bucket writes and independent concurrent-writer tests.
|
||||
Completion-log failure does not replay successful business work; see [Dregarnuhr](ja/dregarnuhr.md).
|
||||
- [ ] Recover missing logs, improve event-only fallback/retention and define completion/log
|
||||
atomicity. Writer-first acquisition does not guarantee all logs survive prolonged contention.
|
||||
|
||||
### Storage portability and operations (2026-09-27)
|
||||
|
||||
@@ -141,7 +173,10 @@ See [active notification contract](ja/active-notifications.md) and
|
||||
- [x] Private local calendar time-block links, durable retry intents, current event time/ETag lookup, unlink tombstones; imported/shared/public calendars excluded.
|
||||
- [x] Persistent Pomodoro: start/pause/resume/finish/cancel, one active session per principal, conditional transitions, bounded scheduler completion and Inbox notification.
|
||||
- [x] Today bounded estimates/current local time blocks/recorded focus intervals, overlap and incomplete-total indicators. Calendar event summaries include an explicitly approved task-title snapshot, never notes.
|
||||
- [ ] Personal capacity, carry-over and period/project reports; historical focus-span backfill; calendar reminders, notification defaults/quiet hours/digests; Pomodoro personal defaults/cycles and routines.
|
||||
- [x] Daily carry-over, work-period/current-project reports, personal notification defaults and
|
||||
opt-in daily task digest with delivery history and manual retry (source through 2026-11-08).
|
||||
- [ ] Personal capacity, historical focus-span backfill, general calendar reminders, quiet hours,
|
||||
Pomodoro personal defaults/cycles and routines; see TASK-01 / ORG-01 in the current backlog.
|
||||
|
||||
See [time-block and Pomodoro contracts](ja/task-planning-focus.md) for API, privacy,
|
||||
two-store recovery, polling limits and remaining work. Canonical calendars and task
|
||||
@@ -190,14 +225,16 @@ System-service plugins are distinct from document adapters. See
|
||||
- [x] Separate system-extension catalog and settings area for trusted built-ins.
|
||||
- [x] Unified execution/resource monitor (running jobs only), paginated job history with lazy logs.
|
||||
- [x] Protect group owners from ordinary member downgrades and atomically retain an owner during concurrent removal.
|
||||
- [ ] Transactional activity outbox and Domain/principal recent-edit projections.
|
||||
- [x] Transactional Domain-sequenced activity outbox and independent typed consumer checkpoints;
|
||||
task/project source mutations append atomically. See [delivery contract](ja/outbox-delivery.md).
|
||||
- [ ] General Domain/principal recent-edit projections, consumer operations and safe outbox retention.
|
||||
- [x] Diary/blog initial built-ins: Page UUID metadata, calendar/recent entries,
|
||||
categories, read-filtered indices, per-Domain enable/disable and registration UI.
|
||||
See [initial scope](diary-blog-plugins.md); this is authenticated, existing-Page registration only.
|
||||
- [x] Diary/blog atomic Markdown new-post composition, transactional metadata/Revision,
|
||||
embedded-asset freezing, idempotent retry and create/write enforcement.
|
||||
- [ ] Diary/blog: anonymous metadata approval/feeds,
|
||||
recent comments and safe resumable tDiary import; declarative time/OS/sunset theme rules.
|
||||
- [x] Diary/blog approved anonymous metadata and full-body RSS feeds; see [current scope](ja/blog-diary.md).
|
||||
- [ ] Recent comments and safe resumable tDiary import; declarative time/OS/sunset theme rules.
|
||||
- [x] Diary/blog per-Domain prefixes, optional keyword URL planner, multiple articles
|
||||
per day, and authenticated Domain-root diary/blog entry view (2026-09-17).
|
||||
Legacy Page registration remains available.
|
||||
@@ -211,8 +248,8 @@ System-service plugins are distinct from document adapters. See
|
||||
filter, legacy-query redirects, and canonical calendar/filter/pagination navigation.
|
||||
- [x] Local same-Campus diary/blog index/calendar projection without copying articles;
|
||||
source and destination read-policy filtering, source body/edit links, target write guard.
|
||||
- [ ] Project article bodies on destination host, approved anonymous projection,
|
||||
cross-instance source transport/revocation and source-setting federation.
|
||||
- [x] Same-instance destination-host article bodies, approved anonymous projection and RSS.
|
||||
- [ ] Cross-instance source transport/revocation and source-setting federation.
|
||||
- [ ] Rankings, reactions and moderated Page/inline comment services.
|
||||
- [ ] Linkding-compatible bookmark-source injection with scoped credentials.
|
||||
- [ ] Explicit external-search fallback and PagesWiki/GROWI/PukiWiki connectors.
|
||||
@@ -456,7 +493,8 @@ See [Home layouts and sidebar design](navigation-home-sidebar.md).
|
||||
manifests, inert HTML, mutation invalidation and denial/revocation tests.
|
||||
- [ ] Extend those gates to anonymous discovery/dependencies and delegated
|
||||
shares with full impact-aware mutation/alias handling.
|
||||
- [ ] Add Domain groups, group Role bindings, and `/g/` management surfaces.
|
||||
- [x] Add Domain groups, group Role bindings, and `/g/` management surfaces.
|
||||
Full authorization auditing and external group mapping remain separate gates.
|
||||
- [ ] Add explicit OIDC/LDAP group mappings and policy-version invalidation;
|
||||
LDAP authentication must remain usable without enabling group synchronization.
|
||||
- [ ] Add auditable policy decisions.
|
||||
@@ -473,11 +511,12 @@ These items must land before the later feature that depends on them. They are
|
||||
listed separately because they replace concrete single-feature assumptions
|
||||
without changing user-visible Page identity.
|
||||
|
||||
- [ ] Put filesystem `DocumentRoot` access behind the seekable, content-addressed
|
||||
Document Store interface before adding S3 or multi-node payload placement.
|
||||
- [ ] Generalize topology/event-job records into a versioned transactional
|
||||
Domain event outbox before notifications, feeds, metrics, comments, or DR
|
||||
consume mutation events.
|
||||
- [x] Introduce the seekable, content-addressed Document Store interface and Geduldh
|
||||
local payload/materialization adapter. External backends, legacy context propagation
|
||||
and placement contracts remain open; see [Geduldh](ja/geduldh.md).
|
||||
- [x] Introduce a transactional Domain event outbox with typed subscriptions and checkpoints.
|
||||
- [ ] Extend producer coverage and replay/retention contracts before new consumers depend on it;
|
||||
see [remaining delivery work](ja/outbox-delivery.md).
|
||||
- [ ] Add a typed extension manifest and provider registry before adding third-
|
||||
party transpilers, widgets, scanners, storage backends, or themes.
|
||||
- [ ] Inventory process-local sessions, caches, preview slots, scheduler state,
|
||||
@@ -550,10 +589,11 @@ without changing user-visible Page identity.
|
||||
- [ ] Formalize a Domain-sequenced event outbox for Page, Revision, Path,
|
||||
topology, policy, share, comment, reaction, quality, and federation events.
|
||||
- [ ] Add Page/Spot/Street/Quartier subscription and change-notification rules.
|
||||
- [ ] Add a per-Principal notification inbox with unread state, grouping,
|
||||
filtering, retention, cursor pagination, and authorization-safe deep links.
|
||||
- [ ] Add delivery channels for Web inbox, email digest, webhook, and future
|
||||
push adapters, with retry/dead-letter state in the event scheduler.
|
||||
- [x] Per-Principal Inbox, unread state, cursor pagination, topbar/modal/detail UI,
|
||||
task/broadcast producers and current-authorization checks for supported types.
|
||||
- [ ] General notification grouping/filtering/retention and new-producer authorization coverage.
|
||||
- [x] Web Inbox, opt-in Web Push and daily task email; their delivery contracts are distinct.
|
||||
- [ ] General channel subscriptions, webhook delivery, quiet hours and retry/dead-letter operations.
|
||||
- [ ] Add recently edited and recently viewed Page projections; keep private
|
||||
activity private and provide retention/opt-out controls.
|
||||
- [ ] Add privacy-aware Page view counters with bot filtering, idempotent event
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# Implementation status and hardening backlog
|
||||
|
||||
2026-11-08 reconciliation: use the [current Japanese implementation backlog](ja/implementation-backlog.md)
|
||||
for actionable IDs, priorities, dependencies and acceptance gates, based on `e65ca56`.
|
||||
This is a source/document audit, not a production audit or a new deployment.
|
||||
|
||||
For the consolidated current reading order, use the [Japanese handbook](ja/index.md)
|
||||
and [decision register](ja/decisions.md). Dated entries below preserve history;
|
||||
older statements about missing anonymous navigation, blog publication or RSS are
|
||||
@@ -13,6 +17,28 @@ security.
|
||||
|
||||
## Current state
|
||||
|
||||
2026-11-08 digest follow-up: private delivery history and explicit same-day retry
|
||||
are implemented in source. Manual requests are queued for the existing scheduler;
|
||||
attempt IDs fence stale completions, and consent/version/authorization are checked
|
||||
again before SMTP. Detailed terminal attempts expire after 90 days, while daily
|
||||
reservations and request receipts remain. Additive schema v4 and recovery rules
|
||||
preserve duplicate prevention; production rollout remains deferred. See
|
||||
[delivery history and migration](ja/task-digest-delivery.md).
|
||||
|
||||
2026-11-08 work history: owner-only bounded history, inline correction/cancellation,
|
||||
immutable audit snapshots and project-level reports are implemented in source.
|
||||
Cancelled spans leave the report but not the audit. Task/dashboard navigation and
|
||||
Japanese/English desktop/mobile UI are connected. Schema migration v3 requires an
|
||||
aligned DB backup before production rollout; do not hot-swap older binaries onto
|
||||
the upgraded DB. See [contracts and remaining scope](ja/task-productivity-contacts.md).
|
||||
|
||||
The dated task/inbox paragraphs below describe earlier slices. VTODO, time blocks,
|
||||
Pomodoro, active notifications, daily task email, private CardDAV and the organizer
|
||||
dashboard have since been implemented. Their remaining work is shared access,
|
||||
external connectors, conflict resolution and retention, not reimplementation of
|
||||
the existing private interfaces. The [Japanese roadmap](ja/roadmap.md) tracks the
|
||||
current order.
|
||||
|
||||
2026-09-25 task reminders: explicit per-task due/planned-date switches and a local
|
||||
notification time now schedule owner-only Inbox reminders. Reservations are updated
|
||||
in the source transaction; the bounded scheduler rechecks current state/authority,
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
| --- | --- | --- |
|
||||
| Wiki URL | 人が開く説明・知識への入口 | rename可能なPage Path |
|
||||
| iCalendar | 予定・タスク等の交換形式 | export/import、UIDと元データを保持 |
|
||||
| CalDAV | カレンダー資源を扱うWebDAV拡張 | remote connector、将来の提供面 |
|
||||
| CardDAV / vCard | 連絡先の通信 / データ形式 | 個人・共有address book |
|
||||
| CalDAV | カレンダー資源を扱うWebDAV拡張 | 読取remote connectorと限定VEVENT/VTODO提供面は実装済み |
|
||||
| CardDAV / vCard | 連絡先の通信 / データ形式 | 個人address book提供は実装済み、共有・外部connectorは後続 |
|
||||
|
||||
iCalendarとCalDAVは同義ではなく、`.ics`を配信するだけでCalDAVサーバーにはなりません。vCardとCardDAVも区別します。[RFC 5545](https://www.rfc-editor.org/rfc/rfc5545)、[RFC 4791](https://www.rfc-editor.org/rfc/rfc4791)、[RFC 6350](https://www.rfc-editor.org/rfc/rfc6350)、[RFC 6352](https://www.rfc-editor.org/rfc/rfc6352)。
|
||||
|
||||
@@ -29,7 +29,7 @@ local item UUID、calendar UID、remote href、Wiki Page UUIDを対応表に持
|
||||
|
||||
connectorはremote ETagとlocal versionを別々に持ち、更新前の値で条件付き操作します。ETagをDocument SHA-256と仮定しません。対応サーバーではcollection sync-tokenを利用する案ですが、無効なtokenからの再同期と未対応時のboundedな全量照合も必要です。[WebDAV同期仕様](https://www.rfc-editor.org/rfc/rfc6578)。
|
||||
|
||||
通信失敗では外部削除と見なさず、tombstoneは確認できた削除だけです。両側で変更された場合はbase/local/remoteを比較し、内容を保存した競合状態へ移します。勝手な最新版上書きはしません。
|
||||
外部connectorの設計では、通信失敗を外部削除と見なさず、tombstoneは確認できた削除だけにします。双方向書込を追加する際はbase/local/remoteを保存して競合選択へ進めます。これを現在の全DAV入口の挙動とは扱いません。タスク提供面では利用者指定により無条件PUT/DELETEを上書き受理し履歴を保持します。競合候補・通知・採否選択は[所属統一の後続](task-dav-project-unification.md)で、読取外部カレンダーconnectorとは別契約です。
|
||||
|
||||
## 連絡先
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
| ADR-O1 | organizerはtyped metadataと任意Page参照 | タスク初版は専用表+既存CAS Document Store(2026-09-24)。通常のObject閲覧・リンク・削除の権限境界を拡大せず、個人所有を確実に分離する。DBは捨てられる索引ではない。[実装契約](tasks-implementation.md) |
|
||||
| ADR-O2 | task共通部+ticket workflow | 提案。番号・外部依頼者・遷移権限の要件確認 |
|
||||
| ADR-O3 | ICS/vCard入出力→read-only DAV→双方向 | 推奨順。対象サーバー/clientを選んで互換表を作る |
|
||||
| ADR-O4 | FreshRSS正本+PagesWiki connector+newsboat | 第一候補。利用環境・追加運用負荷を確認。内蔵readerは代案 |
|
||||
| ADR-O4 | 簡易利用は内蔵正本、本格運用はFreshRSS正本+PagesWiki connector+newsboat | 2026-11-08利用者指定で採用。内蔵・FreshRSS読取・共通UI・OPML入出力まで実装。source単位で正本を分離し、自動fallbackや二重管理はしない。外部書戻しは残件。実環境の接続先・版・資格情報は別途指定 |
|
||||
| ADR-O5 | IMAP read-only、Wikiコピーは明示操作 | 初期設計方針。providerとsampleが実装前提 |
|
||||
| ADR-O6 | HTMLパーツを先行し全面WYSIWYGは保留 | 提案。round-tripと操作改善の評価でgo/no-go |
|
||||
| ADR-O7 | Wiki Pathと外部UID/hrefを分離 | 共通の設計制約。rename fixtureを全connectorで実施 |
|
||||
@@ -35,7 +35,7 @@
|
||||
|
||||
## 未決事項
|
||||
|
||||
利用するFreshRSSの有無と版、対象CalDAV/CardDAV client、IMAP provider、taskの共有単位、ticketの依頼者公開範囲、保持期限、外部接続を許可するhost、RPO/RTO、WYSIWYG採用基準です。これらが未決でもlocal fixtureと設計は進められますが、外部サービスを勝手に立ち上げたり資格情報を流用したりしません。
|
||||
利用するFreshRSSの接続先・版・資格情報、対象CalDAV/CardDAV client、IMAP provider、taskの共有単位、ticketの依頼者公開範囲、保持期限、外部接続を許可するhost、RPO/RTO、WYSIWYG採用基準です。これらが未決でもlocal fixtureと設計は進められますが、外部サービスを勝手に立ち上げたり資格情報を流用したりしません。
|
||||
|
||||
## 文書運用
|
||||
|
||||
|
||||
@@ -55,7 +55,12 @@
|
||||
- `POST /_/api/v1/editor/convert`:作業中 HTML を安全な authoring Markdown に変換。
|
||||
`POST /_/api/v1/render/markdown` の `authoring:true` で保護フェンスを元の HTML に戻す。
|
||||
`projection:true` と併用したプレビューでは従来の sanitizer・macro 展開を適用する。
|
||||
- 変換できない HTML は文書全体を保護する保守的な実装。フェンスは
|
||||
- 2026-11-09から、全体変換が構造を保てない場合はbody直下のブロック単位に変換する。
|
||||
往復で構造が一致する見出し・段落・リスト等はMarkdownへ戻し、不一致のブロックだけを保護する。
|
||||
再結合後も文書全体を比較し、head内要素等を失う場合は全文保護へ戻す。
|
||||
保護ブロックはDOM再シリアライズを避け、原文の引用符・タグ表記をそのまま保持する。
|
||||
分割は最大1024区間。省略終了タグ等で境界を確定できない場合も全文保護へ戻す。
|
||||
リスト・表の構造要素間の空白は比較時に正規化し、インラインの単語境界やコード内空白は保持する。フェンスは
|
||||
`` ```{=html} `` 形式(本文にバッククォートがある場合はそれより長い区切り)。
|
||||
任意の属性、コメント、未知要素、表の結合、画像キャプション、コード内空白を保持。
|
||||
フェンス内を編集でき、外側に Markdown を追記できる。通常のコードフェンス内にある
|
||||
@@ -70,7 +75,7 @@
|
||||
- `+` は挿入・下書き、`文` は言語の編集・分岐、`↶` は旧リビジョンを作業バッファへ
|
||||
読み込む。復元は明示保存で新 Revision を追加し、旧 Revision を書き換えない。
|
||||
履歴は50件ずつ追加取得し、現在言語で絞り込む。分岐は翻訳生成ではなく本文のコピー。
|
||||
- 挿入は子ページ・表・画像キャプション・補足・コード・引用の6種の初期パレット。
|
||||
- 挿入は子ページ・表・画像キャプション・補足・コード・引用・CSV macroの初期パレット。
|
||||
画像 URL 等のプレースホルダーは編集が必要。ファイルピッカー、図形・外部 widget の
|
||||
パラメータ編集、プラグインによる挿入パーツ登録は既存の HTML editor 設計に残る。
|
||||
- touch/coarse pointer + hover 不可の端末ではデスクトップの Vim 設定を上書きせず、
|
||||
@@ -78,11 +83,13 @@
|
||||
|
||||
## 次段階の実装順序
|
||||
|
||||
CSVの表編集は既存保存・下書き・履歴の契約へ接続済みです。CSVはHTML変換と文字列自動マージを行わず、競合時は比較して採否を決めます。BOMと混在改行を保持するため、CSV初期値はHTMLのtextarea解析を通さず安全なJS文字列として渡し、CodeMirrorはLFのみで分割します。初期フォーカスの遅延処理も、表セルなどへ移ったフォーカスを奪いません。詳細な上限と残件は[表設計](extensions.md)を参照してください。
|
||||
|
||||
1. **E6a presence**:編集中リースの共有ストアと認可付き API、別端末を含む表示。
|
||||
管理者にだけ見える監視ではなく、同じ Page/language を編集できる参加者に限定する。
|
||||
2. **E6b realtime**:下記 CRDT 詳細設計・採用ライブラリ・同時変換ルールを確定した後に
|
||||
feature flag 付きで実装。現時点の CAS を最終コミット時の保護として残す。
|
||||
3. **E5b / E3b**:HTML ブロック単位の保護、hosted editor/CLI への保護フェンス対応、
|
||||
3. **E5b / E3b**:入れ子コンポーネント内のより細粒度なMarkdown復元、hosted editor/CLI への保護フェンス対応、
|
||||
アセットピッカーと拡張挿入パーツ。通常の Markdown だけを扱う外部エディタへ
|
||||
このフェンスを無断で渡さない。既存の外部エディタ変換経路は本変更の対象外。
|
||||
4. 保存 API の旧クライアント移行と base 必須化、下書き大容量化・明示破棄 UX、
|
||||
|
||||
@@ -48,11 +48,25 @@ IPアドレス管理(IPAM)、DNSゾーン/レコード管理、機器・
|
||||
|
||||
## CSV/表・スライド拡張(設計TODO)
|
||||
|
||||
CSVをPage本文へ複製せず、認可済みの別Documentをテーブルとして投影するmacroを用意します。候補構文は `{{csv:/data/items.csv range=A1:H200 header=true}}` とし、Path、Revision(またはasset hash)、列・行上限、表示モードを正規化してキャッシュキーに含めます。macroは表示時にboundedなProjectionを作るだけで、結果HTMLを正本へ逆流させません。CSV Editorは元Revisionを編集し、表投影とは別の操作・競合・権限として扱います。
|
||||
初期CSV macroは実装済みです。`{{csv:/data/items.csv range=A1:H200 header=true}}` を認証済みProjectionで展開し、`rev=` で同じObjectのRevisionへ固定できます。現在のPath閲覧権限を毎回検査し、外部URL、匿名公開、asset指定、共有キャッシュはこの段階に含めません。入力256 KiB・UTF-8、表示200行×32列、走査2,000行・100列、セル16 KiB、Projection当たり4種類のCSVまでに制限します。引用符・改行・BOMに対応し、セルはHTML escapeしてmacroや数式を実行しません。処理不能時は内容を漏らさない警告に置き換えます。Authoringでは元のmacroを保持します。
|
||||
|
||||
既存CSVの編集は `/e/-/{path}` の組み込みエディタで行います。デスクトップはソースと表を並べ、700px以下では表を全幅表示してソースへ切り替えます。セル編集、行・列追加/削除、20操作までの表のUndo/Redoに対応。表は200行・32列・セル16 KiB以内を25行ずつ描画し、先頭行を自動でヘッダ扱いしません。矩形でない行の欠落セルは表示だけでは補わず、列追加・貼り付けで必要になった部分だけ空セルを補います。全体256 KiB・UTF-8以内を対象とし、超過・不正形式の表を部分編集可能にして保存することはありません。表上限を超えても全体上限内ならソースで編集できます。
|
||||
|
||||
表計算ソフトからの複数セル貼り付けは、フォーカス中のセルを左上として反映します。クリップボードの `text/plain` にタブまたは改行があればタブ区切り表として解析し、引用符内の改行・タブ・二重引用符を保持します。カンマは列区切りにせずセル値として扱い、単一行の通常テキストはセル内への貼り付けです。複数行を一つのセルへ貼る場合は引用符で囲むかソースを編集します。HTML形式のクリップボードは使いません。必要な行・セルの拡張を含めて1操作でUndo/Redoでき、構文・行列・セル・変換後CSV全体の上限を検査してから一括反映します。失敗時は部分反映せず、既存のUndo履歴も変更しません。貼り付け範囲外のセルと改行形式は維持します。
|
||||
|
||||
CSV正本をHTMLへ変換せず、未変更fieldの引用符、BOM、混在LF/CRLFを保持します。セル内のHTML、macro、数式は実行しません。表編集も既存の下書き・認証切れ検出・言語別Revision CAS・履歴復元を使用し、他の保存と競合したCSVは文字列の自動マージをせず比較画面へ送ります。原文と編集済み表の両方を別正本として保存しません。DBスキーマ変更はありません。CSV新規作成ウィザード、TSVファイル/文字コード変換、大容量表のwindow編集、矩形選択/範囲コピー、列型/数式、ODSは残件です。
|
||||
|
||||
CSVをPage本文へ複製せず、認可済みの別Documentをテーブルとして投影します。共有キャッシュを将来追加する際は、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します。
|
||||
|
||||
スライドは、Markdown/HTMLの正本からReveal.js互換のProjectionを生成する連携アダプタを設けます。HedgeDoc、Slidevは外部originのホスト型アダプタとして、保存・公開・ユーザー情報をPages Wikiの権限へ自動昇格させず、read-only preview→明示的なimport/saveの順にします。JSを使用できない環境向けには、CSS scroll-snap/`:target`/print CSSだけでページ送りできるCSS-only Slide Editorを別実装します。外部ランタイム停止時は静的HTML/Markdownへ安全にfallbackし、任意script、remote import、iframe権限を本文から許可しません。
|
||||
スライドはローカル同梱のReveal.js 6.0.2で表示します。`/v/slides/{path}` は通常のPath閲覧権限でHTML/Markdownの最新Revisionを取得し、HTMLページのスライドアイコンや「連携アダプタで開く」から移動できます。組み込みHTML/Markdownエディタのスライドアイコンは、未保存の本文を通常プレビューと同じ変換経路で投影します。表示DOMを保存せず、保存・下書き・競合処理は既存エディタに任せます。Markdownの空行で囲んだ `---`、HTMLの直下の `<hr>` が横方向の区切りで、直下の `<section>` も1枚として扱います。コードブロック内の区切りは分割しません。
|
||||
|
||||
Reveal実行は `allow-scripts allow-popups` のsandbox iframeに隔離し、`allow-same-origin` は付けません。本文のscript・CSS・iframe・フォーム・任意data属性を渡さず、独自プラグインや外部Markdownを読み込みません。画像は同一originだけ、リンクはHTTP(S)だけです。矢印キー・タッチ・画面内コントロールで移動し、履歴やURL hashを変更しません。ビューアは全画面に対応し、背景・文字色はテーマから引き継ぎます。ライブラリ読込失敗時は静的なサニタイズ済み本文へfallbackします。本文256 KiB・100枚・DOM 10,000ノード/深さ64を上限とし、常時バックグラウンド生成や共有キャッシュは持ちません。`viewer.slides` は拡張設定でドメイン単位に停止でき、停止後のページではビューア・編集切替・アダプタ候補を表示しません。MITライセンス・固定版・配布元・hashは `static/vendor/reveal/` に同梱します。DBスキーマ変更はありません。
|
||||
|
||||
700px以下の編集画面ではスライドプレビューを全幅表示し、既存のプレビュー非表示ボタンでソースへ戻ります。小画面で自動スクロール形式に変わらないよう `scrollActivationWidth: null` を指定します([Reveal.js公式仕様](https://revealjs.com/scroll-view/))。
|
||||
|
||||
縦方向のスライド、fragments、発表者ノート、macroの非同期展開、スライド専用印刷、外部画像の承認連携は残件です。HedgeDoc、Slidevは外部originのホスト型アダプタとして、保存・公開・ユーザー情報をPages Wikiの権限へ自動昇格させず、read-only preview→明示的なimport/saveの順にします。JSを使用できない環境向けには、CSS scroll-snap/`:target`/print CSSだけでページ送りできるCSS-only Slide Editorを別実装します。
|
||||
|
||||
ネットワーク図ではnwdiagを追加候補とします。ソースをbounded parserで検証し、renderer version/theme/document hashをキーに静的SVGをキュー生成します。include、外部画像・font、未知directive、危険なSVG属性は拒否し、renderer停止時はescaped sourceまたは最後に検証済みの静的画像へfallbackします。編集アダプタの保存はone-use ticketと楽観的Revision競合を使い、Kroki経由の場合もorigin、timeout、quotaを明示します。
|
||||
|
||||
|
||||
+404
-16
@@ -1,41 +1,429 @@
|
||||
# 15. RSSビューア・FreshRSS・newsboat
|
||||
|
||||
状態:設計案。既存のブログRSS「配信」と、本章の外部RSS「購読」は別機能。
|
||||
状態:内蔵簡易reader、FreshRSS読取connector、共通viewer、Wiki保存・タスク化、ダッシュボードを実装。
|
||||
OPMLの確認付き追加取り込み・書出し、FreshRSS購読・カテゴリのnavigation、opt-inの既読・star書戻しを実装済み。本番反映と実FreshRSSへの接続は未実施。
|
||||
既存のブログRSS「配信」と、本章の外部RSS「購読」は別機能。
|
||||
|
||||
## 選択肢と推奨する試作順
|
||||
2026-11-08:利用者指定のサブプロジェクト順で最初に実施する。内蔵readerは簡易利用の
|
||||
正本、本格運用はFreshRSSを正本とする。実環境の接続先・版・資格情報は別途指定する。
|
||||
|
||||
| 案 | 正本 | 利点 | 追加する責任 |
|
||||
## 正本と責務
|
||||
|
||||
| モード | 正本 | PagesWikiの役割 | 範囲 |
|
||||
| --- | --- | --- | --- |
|
||||
| PagesWiki内蔵reader | ローカルの購読と状態 | Wiki保存と一体のUI | 取得・既読・同期・client対応を全て持つ |
|
||||
| FreshRSS connector | FreshRSSの購読・既読 | 既存reader資産を利用 | API互換性、権限、cacheと失効 |
|
||||
| newsboat単独の橋渡し | newsboat側の購読・状態 | CLI利用に合わせやすい | ローカル連携経路・export/importの設計 |
|
||||
| 内蔵簡易reader | PagesWikiの購読・フォルダ・既読・star | feed取得、保持上限内の記事保存、閲覧とWiki保存 | 個人の簡易利用。外部reader向け同期サーバーや高度なルール機能は初期範囲外 |
|
||||
| FreshRSS連携 | FreshRSSの購読・フォルダ・記事・既読・star | 表示用cache、連携UI、Wiki保存・タスク化 | 本格運用。PagesWikiは独立した購読・既読の正本を重ねない |
|
||||
| newsboat等のclient | 接続先FreshRSS | PagesWikiと同じ正本を使う別clientとして扱う | PagesWiki経由の代理同期やnewsboatのDB共有は行わない |
|
||||
|
||||
FreshRSSにはGoogle Reader互換APIがあり、APIの有効化と専用passwordを使います。newsboatにはFreshRSS連携が用意され、カテゴリのtag化やstar操作を扱えます。[FreshRSS公式API](https://freshrss.github.io/FreshRSS/en/developers/06_GoogleReader_API.html)、[newsboat公式マニュアル](https://newsboat.org/releases/2.42/docs/newsboat.html#_freshrss)。
|
||||
|
||||
このため最初の候補は **FreshRSSを正本、PagesWikiを読取connector、newsboatを同じFreshRSSのclient** とする構成です。これは設計上の提案で、ユーザー環境のFreshRSS導入・採用決定ではありません。PagesWikiがnewsboatをサーバー上で起動したり、そのSQLiteを共有したりする必要はありません。
|
||||
本格運用は **FreshRSSを正本、PagesWikiとnewsboatをそのclient** とする構成を採用します。
|
||||
内蔵簡易readerも別providerとして提供し、共通の一覧・保存UIを使用します。FreshRSSを
|
||||
PagesWiki全体の必須依存にはせず、外部サービスの新設・接続は設定時の明示操作とします。
|
||||
|
||||
## 読取MVP
|
||||
sourceは一つのproviderに束縛し、記事キーはDomain/所有者/source UUID/remote IDで
|
||||
区別します。同じURLの記事でも別sourceの既読を自動統合しません。FreshRSSのcacheは
|
||||
再取得可能な派生データですが、内蔵の購読・状態は正本として保全対象にします。
|
||||
|
||||
購読一覧、フォルダ、記事一覧、外部原文、Wiki保存を提供します。初期段階では表示しただけでFreshRSSへ既読を送りません。UIには「読取専用・既読は同期していない」と明示します。ブラウザへFreshRSS password/tokenを渡さず、backend connectorがsecret参照を使います。
|
||||
FreshRSS停止時は取得済みcacheと鮮度・接続状態を示し、内蔵正本へ自動切替しません。
|
||||
外部操作の未送信状態は正本と区別し、成功していない既読・starを同期済みと表示しません。
|
||||
内蔵からFreshRSSへの移行はOPML等による明示的なexport/importとし、初期版では既読・star・
|
||||
記事IDの完全移行を保証しません。移行完了の確認前に内蔵データを削除しません。
|
||||
|
||||
最小cache案はsource UUID、remote feed/item ID、title、safe excerpt/body hash、canonical URL、published/updated/fetched時刻、remote state/versionです。IDなしRSSにはfeed単位の保守的な代替キーを使い、題名だけで重複排除しません。Atomはentry IDと更新情報を持つ形式です。[Atom仕様](https://www.rfc-editor.org/rfc/rfc4287)。
|
||||
## 実装済みの読取機能
|
||||
|
||||
## 既読・star同期を追加する条件
|
||||
`/v/feeds` に購読一覧、フォルダ、記事一覧、外部原文へのリンク、Wiki保存を提供します。
|
||||
FreshRSSの記事・既読・starを取得します。既定は読取専用で、source設定で明示的に許可した場合だけ状態の変更を送信します。
|
||||
FreshRSS passwordを設定時以外にブラウザへ返さず、login tokenはbackend内でのみ利用します。
|
||||
資格情報は既存の暗号化機構を使い、Domain・所有者・source UUID・用途に束縛します。
|
||||
|
||||
cacheはsource UUID、remote item ID、title、安全化したHTML本文とテキスト本文、記事URL、公開日時、配信元、
|
||||
フォルダ、read/starを保持します。取得時刻・ETag・Last-Modified・失敗分類はsource側に持ちます。
|
||||
IDなしRSSは記事URL、URLもなければ題名・日時・本文の組合せから代替キーを作り、題名だけで
|
||||
重複排除しません。Atomはentry IDを使います。[Atom仕様](https://www.rfc-editor.org/rfc/rfc4287)。
|
||||
|
||||
### 高密度ビューア
|
||||
|
||||
newsboat/neomuttを参考に、デスクトップは左から購読元・一行記事一覧・本文の3ペインとします。
|
||||
一覧には未読/star、日付、配信元、件名を並べます。狭幅は一覧と本文を切り替え、スマホでは
|
||||
行とボタンのタッチ領域を広げます。モバイルの共通ナビはアイコンのみとし、名称はアクセシブル名と
|
||||
tooltipに残します。タブ名は「RSS」、原文リンクはアイコンです。件数・保持上限・操作の説明は常設せず、
|
||||
キー案内は`?`で表示します。設定と保存フォームは本文ペイン内に置き、モーダルを増やしません。
|
||||
|
||||
`j/k`・上下矢印で記事移動、`Shift+j/k`で次/前のFreshRSSフォルダ、`Enter/l`で本文、`Esc/h`で一覧、`/`で件名・配信元検索、`n`で次の未読、
|
||||
`m`で既読切替、`*`でstar、`r`で背景更新予約、`?`でキー案内です。フォーム入力・IME変換中は
|
||||
一覧ショートカットを抑止します。FreshRSSでは書戻し許可時だけ`m`と`*`で操作を予約します。
|
||||
|
||||
HTML本文は見出し・表・箇条書き・強調・リンクを保持して描画し、plain textは文字情報として表示します。
|
||||
server側の許可リストでscript・イベント属性・任意CSS・form・iframe・画像等を除去し、表示時にも再検査します。
|
||||
Shadow DOMでWiki UIと表示スタイルを分離し、本文リンクは安全なHTTP(S) URLに解決して別タブで開きます。
|
||||
Wiki macroは展開せず、記事表示のための外部画像や原文サイトのfetchも行いません。
|
||||
検索とページングは保存済みcacheだけを対象にし、画面表示で
|
||||
feed取得の完了を待ちません。ダッシュボードには任意追加のRSS widgetを用意します。
|
||||
|
||||
### APIと保存層
|
||||
|
||||
API prefixは `/_/api/v1/extension/organizer.feeds/`。Domain内の本人専用で、匿名・他人のsourceには
|
||||
アクセスできません。readonlyアカウントは読取のみです。すべての応答はprivate/no-storeとします。
|
||||
|
||||
| endpoint | 操作 |
|
||||
| --- | --- |
|
||||
| `GET sources` / `POST sources` | source一覧/追加・設定更新。新規はUUIDで再送を識別、更新はversion CAS |
|
||||
| `POST sources/{uuid}/refresh` | 次回背景取得を予約。画面から外部通信しない |
|
||||
| `POST sources/{uuid}/delete` | versionを照合してsource・cache・内蔵read/starを削除 |
|
||||
| `GET items` | source/unread/starred/件名・配信元で絞り込み、100件単位のkeysetページング |
|
||||
| `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` | 選択行を再解析・検査し、確認時の購読設定と一致する場合だけ原子的に追加 |
|
||||
|
||||
managed schema `feeds` v1に `feed_sources`、`feed_items`、`feed_states`、`feed_note_receipts`を追加し、
|
||||
v2で`feed_items.body_html`を追加します。既存のテキスト本文・既読・starは保持し、条件付きGETのvalidatorを
|
||||
一度クリアして次回背景取得でHTMLを取り直します。migration前のworkerは設定versionで無効化します。
|
||||
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とは扱いません。
|
||||
|
||||
sourceのprovider・URL・資格情報の変更は別sourceを作る契約です。設定versionとworker claimの
|
||||
両方を照合し、停止/削除/設定更新後に古い取得結果を書き戻しません。完了保存時にも本人の
|
||||
所属・状態・extension有効状態をwriter transaction内で確認します。
|
||||
|
||||
### 背景取得の上限
|
||||
|
||||
| 項目 | 初期実装の値・挙動 |
|
||||
| --- | --- |
|
||||
| 個人の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,000フォルダ、1購読64カテゴリ、保存JSON合計1 MiB。記事と同じ取得予算で収集 |
|
||||
| 再試行 | 次の設定間隔まで待機。手動予約にも最終成功から60秒の制限、取得中の重複claim拒否 |
|
||||
|
||||
内蔵は条件付きGET、304ではcacheを保持します。どちらのproviderも通信・認証・構文失敗で
|
||||
前回cacheを消しません。sourceには安全な失敗分類と最終成功日時を表示し、イベントログには
|
||||
成功/失敗件数だけを記録します。資格情報・生本文・秘密を含み得るURLをログへ出しません。
|
||||
extension無効化は画面・API・取得・完了保存に適用します。購読を登録するまで外部通信は発生しません。
|
||||
|
||||
### FreshRSSの購読とカテゴリ
|
||||
|
||||
背景取得ではlogin後にreading-list・`subscription/list`・`tag/list`を読み、すべてに成功した場合だけ
|
||||
記事・購読一覧・分類一覧を同じtransactionで置換します。一部の取得失敗、上限超過、不正なsnapshotでは
|
||||
前回のcache全体を保持します。記事が取得窓内にない購読も一覧には残します。
|
||||
`tag/list`は`type=folder`だけを分類として取り込み、記事タグとシステムの状態タグは除外します。
|
||||
購読一覧のカテゴリとIDで統合し、購読元のない空フォルダも保持します。
|
||||
|
||||
左ペインでFreshRSS sourceを選ぶと、接続先→分類フォルダ→購読元のツリーを表示します。
|
||||
フォルダ名は記事の絞り込み、隣の矢印は開閉と役割を分けます。開閉状態は接続先UUID単位で
|
||||
ブラウザのlocalStorageに保存し、利用できない場合もその画面内では保持します。
|
||||
閉じたフォルダは購読元のDOMを作らず、展開時は50件ずつ描画します。購読名・分類名で検索すると
|
||||
該当購読を重複なしで一覧化します。名前に含まれる`/`は文字として扱い、独自の階層には分割しません。
|
||||
|
||||
カテゴリは表示名でなくremote category ID、購読は`origin.streamId`とsubscription IDを対応させます。
|
||||
同名でも混同せず、複数カテゴリに属する購読は各フォルダに表示します。記事の分類絞り込みは
|
||||
記事タグではなく同期した購読元の所属を使い、FreshRSSでの分類移動に追従します。
|
||||
分類のない購読は「未分類」に表示し、購読一覧にない記事を未分類へ混在させません。
|
||||
`GET items`の`feed`/`category`/`category_mode=uncategorized`は
|
||||
source指定と組み合わせ、既存の未読・star・検索・keysetページングと併用できます。
|
||||
`category`と`category_mode`の同時指定は拒否します。
|
||||
絞り込み対象は最新200記事のcache内に限られ、購読を選んでも履歴全件を外部取得しません。
|
||||
購読の追加・削除やカテゴリの編集はFreshRSS側で行います。
|
||||
|
||||
`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との同時操作を完全に直列化する双方向同期ではありません。
|
||||
|
||||
## 内蔵fetcherを選ぶ場合
|
||||
### 操作記録と送信状態
|
||||
|
||||
定期event、条件付きGET、host別同時数、timeout、応答サイズ、展開サイズ、backoffを設けます。XML外部entityを無効にし、feed HTMLを安全化します。redirect/DNSを含むSSRF対策、外部画像の同意、個人購読URLや認証情報の秘匿が必要です。
|
||||
RSS-3は合成環境で実装・検証済みです。sourceごとに既定OFFの「FreshRSSの既読・star変更を許可」を設け、操作は`read`または`starred`の一項目と希望値に限定します。
|
||||
cache内の他項目を同時に送らず、全件既読・購読編集も初期対象に含めません。
|
||||
|
||||
OPMLは購読の入出力として扱い、既読・star・全本文のバックアップと同一視しません。importはpreview・追加/置換選択・重複確認を行い、既存購読を黙って削除しません。
|
||||
操作記録は記事cacheから分離し、Domain・本人・request_id、source・記事ID、対象項目、希望値、
|
||||
source version、状態、claim期限を保持します。同一request_idの同じ入力は同じ記録を返し、
|
||||
違う入力は拒否します。同じ記事に未解決の操作がある間は次の操作を受け付けません。
|
||||
受付APIは外部通信せず、低優先度workerが送信します。Domain・本人ごとに未解決20件、全記録10,000件を上限とし、
|
||||
上限で新規受付を拒否します。receiptを自動削除して古い要求を再送可能にすることはしません。
|
||||
queuedは受付から5分で失効します。claimは60秒で、期限切れsending/checkingはunknownにし、変更を再送しません。
|
||||
|
||||
| 状態 | 次の処理 |
|
||||
| --- | --- |
|
||||
| queued | sourceの有効状態・書戻し設定・version・本人の権限を再検査してclaim。古すぎる未送信操作は中止 |
|
||||
| preparing | FreshRSSの現在値を取得。すでに希望値なら書き込まず確認済み。異なる場合だけ変更tokenを取得 |
|
||||
| sending | この状態をDBに確定してから変更を送る。再起動やtimeoutでも自動再送しない |
|
||||
| confirmed | 送信後の読取で希望値を確認。確認できた値だけcacheへ反映 |
|
||||
| unknown | 送信済みか適用済みか判断できない。成功扱いにせず、利用者の再確認操作を待つ |
|
||||
| checking | unknownの再確認。読取のみで、希望値ならconfirmed、異なれば競合として提示 |
|
||||
| failed / cancelled / conflict | 原因を示して終了。新たに送る場合は利用者の明示操作を必要とする |
|
||||
|
||||
通常取得と書戻しはsourceのleaseを共有し、古い取得結果が書戻し後の値を上書きしないようにします。
|
||||
設定変更・無効化・削除は未送信操作を止めますが、すでに外へ送った要求は取り消せません。
|
||||
その場合はunknownを保持し、設定変更後のcacheへ旧workerが反映することを拒否します。
|
||||
外部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で
|
||||
これらを通した後、指定版FreshRSSでの受入を別途行います。
|
||||
|
||||
## 内蔵簡易reader
|
||||
|
||||
購読追加/削除、フォルダ、記事一覧、既読/未読、star、更新間隔と保持上限を初期範囲に
|
||||
します。取得は背景ジョブで行い、更新失敗で購読や状態を消しません。記事本文cacheと
|
||||
既読・starの保持期間を分離し、古い記事を再取得しただけで未読へ戻る挙動を防ぎます。
|
||||
高度な自動分類、全文収集、reader向け互換APIはFreshRSSとの機能競争として追加しません。
|
||||
|
||||
初期版では全体を直列化し、上記の予算内で取得します。将来の並列化時にhost別同時数・公平性・
|
||||
指数backoff/Retry-Afterを追加します。RSS 2.0とAtomを対象とし、XML外部entityは展開しません。
|
||||
外部画像の同意付き表示は未実装で、現在は一律に取得・表示しません。
|
||||
|
||||
### OPML入出力
|
||||
|
||||
RSSツールバーの`⇄`から、本文ペイン内でファイル選択・確認・追加を行います。書出しは本人の内蔵購読の
|
||||
名前・URL・フォルダをOPML 2.0に保存し、停止中の購読も含みます。FreshRSS接続・資格情報は含めません。
|
||||
購読URLのqueryに秘密がある場合はそのURLも書き出されるため、ファイルは本人用として扱います。
|
||||
既読・star・記事本文・有効状態・更新間隔のバックアップではありません。
|
||||
|
||||
取込はUTF-8のOPML 1.0/1.1/2.0を対象とします。OPMLは購読と階層outlineを交換する形式であり、
|
||||
この実装はfeed購読部分のみ扱います。[OPML公式仕様](https://2005.opml.org/spec2.html)。
|
||||
ネストしたフォルダは`親 / 子`という一つのフォルダ名へ投影します。名前のmarkupは文字情報にし、
|
||||
`include`・外部outline・HTMLページの参照は取得しません。コメント扱いのoutline配下も追加対象外です。
|
||||
|
||||
確認表では、追加・登録済み・ファイル内重複・未対応URL/形式・名前不正を区別し、追加可能な行を選択します。
|
||||
HTTPS/443と内部アドレス拒否の既存契約は維持し、ファイル取り込みを検証の迂回経路にはしません。
|
||||
初期版は**追加のみ**で、置換/既存購読の削除は提供しません。有効状態と更新間隔は追加時に指定します。
|
||||
保存後のfeed取得は既存の背景eventが行い、previewやimportのHTTP request中には通信しません。
|
||||
|
||||
上限はファイル512 KiB、記事購読候補500行、outline 1,000個、XML階層16段です。既存sourceと合わせた
|
||||
32件上限を確認画面とwriter transactionの両方で検査します。既存・ファイル内重複は、hostの大小文字・
|
||||
既定443 port・空pathを正規化して判定します。queryの順序、pathの大小文字、redirect先を同一視しません。
|
||||
|
||||
previewはsource UUID・設定versionのsnapshotを返し、適用時に一致しなければ412で再確認を求めます。
|
||||
選択行の再解析、本人・Domain・有効状態の確認、source追加とreceipt保存を一つのtransactionで実行します。
|
||||
同じrequest_id・同じ入力は保存結果を返し、入力が異なれば拒否します。後でsourceを削除してもreceiptを
|
||||
保持するため、古い要求を再送して購読が復活することはありません。receiptはDomain・本人ごとに1,000件まで
|
||||
保持し、上限時は新しいimportを拒否します。既存のWiki/タスク・既読/starは変更しません。
|
||||
|
||||
## Wiki保存と権利・公開
|
||||
|
||||
既定は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`は対象外です。
|
||||
タスクも作成する場合は既存capture APIの原子的なWiki+タスク保存を使います。この経路のPathは
|
||||
既存契約の`mail-{request UUID}`です。途中失敗時は部分的なPage/タスクを残さず、同じ要求で再試行できます。
|
||||
保存先の公開範囲確認を必須にし、取得済み本文のコピーは別チェックとします。
|
||||
|
||||
購読削除で明示保存したWikiやタスクは消しません。内蔵cacheを削除しても既存Wikiへの参照と
|
||||
再送receiptは残します。文書payloadの不変ファイルは既存Document Storeに保存するため、DB失敗時に
|
||||
未参照payloadが残る可能性は既存GC契約に従い、参照のないPage/Pathとは区別します。
|
||||
|
||||
## TODOと受け入れ
|
||||
|
||||
RSS-1:read-only FreshRSS fixture。RSS-2:安全な一覧と出典付きWiki保存。RSS-3:必要なら既読/star送信。RSS-4:内蔵reader採用判断とOPML。オフライン、欠落ID、巨大feed、未知HTML、同期再送、他user情報、feed削除後の保存Page維持を試験します。
|
||||
- [x] RSS-1:read-only FreshRSS connectorと合成fixture。実接続の受入は別。
|
||||
- [x] RSS-2:安全な共通一覧、出典付きWiki保存、任意のタスク化、ダッシュボード。
|
||||
- [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、
|
||||
Wiki保存失敗の原子性を含みます。Chromiumの1440px/390pxで一覧・本文・検索・キー操作・
|
||||
Wiki保存を試験します。実FreshRSS、newsboat、実機Safariの受入はこの合成試験に含めません。
|
||||
|
||||
## 実施段階
|
||||
|
||||
1. **共通契約とfixture**:Domain/本人のsource所有、provider ID、remote ID、cursor、取得予算、
|
||||
最終成功/失敗と無効化を定義する。FreshRSS読取connectorを合成fixtureで先に検証し、
|
||||
内蔵providerも同じ表示契約へ接続する。sourceの資格情報をブラウザ・ログへ出さない。
|
||||
2. **読取UIと背景取得**:購読/フォルダ、記事の一行一覧、本文表示、出典リンクを用意する。
|
||||
デスクトップでは一覧を見渡せる配置、スマホでは一覧と本文を切り替える。画面表示で外部fetchを
|
||||
待たず、schedulerで有界に更新し、取得済みcacheと鮮度を表示する。source停止・失効も検証する。
|
||||
3. **Wiki保存とタスク化**:タイトル・URL・出典・短いメモをpreviewし、保存先Pathを選ぶ。
|
||||
既存captureと権限確認を再利用し、二重送信・保存先競合・自動公開範囲を検査する。全文保存は
|
||||
独立した明示操作。Wiki単独保存とWiki+タスクの原子保存を分け、要求内の失敗では部分成功を
|
||||
残さない。過去に保存済みのWikiは別のタスク作成失敗で削除しない。
|
||||
4. **ダッシュボードとprovider完成**:読める記事だけのwidget、内蔵簡易readerとOPML、
|
||||
FreshRSSの明示的な既読/star操作を段階的に追加する。接続先・対象版の指定後に実環境で
|
||||
read-only→書込の順に受入し、read-only連携を有効化しただけで外部状態を変更しない。
|
||||
|
||||
各段階で無効化、件数・時間・容量上限、移行の再実行、ユーザー/Domain間の分離を試験する。
|
||||
source解除時のcache清掃と、利用者が明示保存したWiki/タスクの保持は別操作とする。
|
||||
@@ -0,0 +1,148 @@
|
||||
# 実装残件台帳
|
||||
|
||||
更新日:2026-11-08。全体照合基準は `e65ca56`(作業履歴・日次メールの後続実装まで)。
|
||||
RSS-01はその後の内蔵reader・FreshRSS読取・共通UI実装まで個別更新。
|
||||
設計書の大項目をそのまま未実装機能と数えず、既存機能の続きとして着手できる単位に整理する。
|
||||
実装順は本書、個別契約はリンク先、過去の経緯は[原ロードマップ](../implementation-roadmap.md)と
|
||||
[実装記録](../implementation-status.md)を参照する。将来の更新でも以下のIDを再利用する。
|
||||
|
||||
## 調査範囲と状態の読み方
|
||||
|
||||
日本語設計書、原ロードマップ、実装記録と、対応するstore/HTTP handler/テストを静的照合した。
|
||||
全エンドポイントの再監査や本番の再試験ではない。実データ、外部カレンダー、メールボックスには
|
||||
アクセスしていない。独立した `anya/pages-cli` の現行HEAD・配布バイナリも今回の照合対象外。
|
||||
|
||||
- **実装済み**:記載した範囲のコードと試験がある。全機能完成・本番適用を意味しない。
|
||||
- **一部実装**:基盤や初期機能はあるが、記載した後続が必要。
|
||||
- **未実装**:設計・TODOの段階。API例や予約URIだけでは利用可能としない。
|
||||
- **確認待ち**:実装の追加ではなく、指定端末・環境・運用での受入が必要。
|
||||
- **保留**:利用者の保留指定、外部環境の選定、保存契約の合意が必要。
|
||||
|
||||
P0は認可・整合性・復旧の安全条件、P1は日常利用の回復性と負荷、P2は機能拡張、P3は
|
||||
別サブプロジェクト。P0の記載は全項目で現に障害や脆弱性を再現したという意味ではない。
|
||||
本番反映は別作業とし、今はソースと隔離fixtureを進められる。
|
||||
|
||||
## 未実装として数え直さないもの
|
||||
|
||||
| 範囲 | 確認できる実装 | 残す境界・根拠 |
|
||||
| --- | --- | --- |
|
||||
| 8つの命名部品 | GrammaraturからSeheweitまでの初期分離 | 分離はHA・全provider対応の完成ではない。[部品一覧](component-names.md) |
|
||||
| イベントログ競合 | writer lockを先に取得、raw/bucket原子保存、完了ログ失敗で業務を再実行しない | `event_log_write.go`、`event_log_write_test.go`、`event_log_reporting_test.go`。[Dregarnuhr](dregarnuhr.md)。ログ欠落の自動回収は別件 |
|
||||
| 共通outbox | Domain sequence、型別購読、checkpoint、タスクと正本の同時保存 | `activity_outbox.go`。[配送契約](outbox-delivery.md)。全producer・保持・分散配送は未完成 |
|
||||
| タスク | 日別計画・持ち越し、親子、Wikiメモ、時間枠、Pomodoro、既定値、達成度・プロジェクト集計 | [生産性と連絡先](task-productivity-contacts.md)、[日別計画](task-daily-notes.md)。共有・日課・競合採否は別件 |
|
||||
| 作業記録・日次メール | 作業訂正/取消/監査、配信履歴、同日手動再送、世代fence | `task_work_history*.go`、`task_digest_history*.go`。managed schema v3/v4。本番未反映 |
|
||||
| オーガナイザー | 共通ナビ、個人設定、配置/サイズを保存するダッシュボード | [ダッシュボード](organizer-dashboard.md)。共有・任意widget runtimeとは別 |
|
||||
| 連絡先 | 個人帳、vCard、履歴復元、trash、個人CardDAVとsync-token | [運用契約](../../operations/carddav-contacts.md)。外部CardDAV connector・共有帳・全端末互換ではない |
|
||||
| DAV | 共通principal/資格情報、限定VEVENT/VTODO、プロジェクト対応、既定リスト名変更 | [所属統一](task-dav-project-unification.md)。CardDAVのsync-tokenを全CalDAV対応と読み替えない |
|
||||
| グループ・公開 | `/g/` 管理、built-in管理グループ、匿名children/tree/City、明示/自動公開 | `groups_handler.go`、`groups_inheritance.go`、[公開契約](publication.md)。委譲shareと完全な権限配信は別 |
|
||||
| 承認・通知 | 要求/決裁APIの限定slice、共通Inbox、アナウンス、タスク通知、Web Push | `publication_approval_api.go`。[Schutzaria](schutzaria.md)。継承reviewer・定足数・現行Revision再検査・決裁UIは残件 |
|
||||
| ブログ・日記 | 作成、公開、同一Campus・同一instanceの射影、本文RSS、記事ナビ | [ブログ・日記](blog-diary.md)。遠隔射影、コメント、tDiary importは別 |
|
||||
| エディタ | E1–E5、下書き、条件付き保存、競合確認、復元、言語分岐、保護HTML | [編集契約](editor-resilience.md)。全入口の同一契約・E6共同編集は未完成 |
|
||||
| ストレージ・DR | Geduldhローカル不変payload、migration台帳、offline snapshot/verify/restore/手動promote | `internal/dr/snapshot.go`、`node.go`。[DR計画](dr-delivery-plan.md)。オンライン同期・自動切替ではない |
|
||||
|
||||
## 次の実施順
|
||||
|
||||
2026-11-08、利用者指定により、大きな機能を提供するサブプロジェクトを以下の順で進める。
|
||||
前案の小規模な回復・基盤改善を先に一巡する順序は、この順序へ置き換える。
|
||||
|
||||
| 順番 | サブプロジェクト | 主な残件ID | 利用できる機能のまとまり |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | RSS・情報収集オーガナイザー | RSS-01 | 購読・フォルダ・記事一覧、出典付きWiki保存、タスク化、ダッシュボード連携 |
|
||||
| 2 | 構造化ドキュメントと編集部品 | CSV-01、DIAGRAM-01、EDIT-01の関連部分 | CSV埋め込み/編集、図表部品挿入、nwdiag/Draw.io等のpreviewと安全な保存 |
|
||||
| 3 | 料理レシピ管理 | RECIPE-01 | 材料・手順・分量変更・材料検索・買い物リスト |
|
||||
| 4 | タスク・プロジェクト管理の第2段階 | TASK-01、DAV-01、REC-01/02、ORG-01の関連部分 | 日課・週次計画・capacity・依存関係・進捗・同期競合の採否 |
|
||||
| 5 | 共同作業・公開承認・共有 | PUB-01、SHARE-01、COLLAB-01の関連部分 | 承認者Inbox/決裁、公開影響確認、期限付き共有、権限総覧 |
|
||||
|
||||
各表のP0〜P3は安全性・負荷等の性質を示す分類として残し、このサブプロジェクト順を覆す
|
||||
一律の実行順にはしない。AUTH-01、OUT-01、QUEUE-01、STORE-01等は、対象機能に必要な
|
||||
範囲を各段階へ組み込む。必須の認可・DB整合性・再送防止は省略せず、無関係な基盤改修を
|
||||
すべて完了させるまで機能開発を止める構成にも戻さない。
|
||||
|
||||
最初のRSSは[着手単位](feeds.md#実施段階)に従う。内蔵は簡易正本、本格運用はFreshRSS正本と
|
||||
する方針を採用。接続先・版・資格情報は別途指定し、まずprovider契約と合成fixtureで一覧・
|
||||
保存フローを検証する。各サブプロジェクトはUI・API・
|
||||
保存・試験が揃った単位でコミットし、本番反映は別ゲートとする。
|
||||
別セッションとの保存層の競合がある場合は、該当ファイルの作業境界を合意してから進める。
|
||||
|
||||
## A. 整合性・回復・認可
|
||||
|
||||
| ID / 優先 | 状態・次の作業 | 依存・完了条件 | 詳細 |
|
||||
| --- | --- | --- | --- |
|
||||
| REC-01 / P1 | 一部実装:失効Domainの取り残された作業記録を終了・回復 | 現在の文書閲覧権限を再付与せず、本人の停止に必要な最小情報だけ扱う。他Domainタイトル非露出、同時停止・新規開始・失効競合を検証 | [作業記録](task-productivity-contacts.md) |
|
||||
| REC-02 / P1 | 一部実装:取消からの復元、監査保持/export | REC-01と既存CAS。復元も新監査版、重複時間再検査、履歴の削除と正本の保持を分離。保持期間を決めるまで削除しない | 同上 |
|
||||
| AUTH-01 / P0 | 一部実装:policy snapshot・ユーザー領域事前読込、更新時の認可fence | 入口一覧を作り、revokeと更新、alias、owner移管、公開境界移動をfixture化。接続1本でも認可callbackが別接続待ちにならない | [Schutzaria](schutzaria.md)、[認証](auth-permissions.md) |
|
||||
| AUTH-02 / P0 | 一部実装:identity連結解除・メール所有・最後の管理者保護、外部group mapping | OIDC/LDAP認証自体は維持。由来付きgrant、解除・同期失効・最後の管理者の並行操作を検証 | [認証](auth-permissions.md) |
|
||||
| PUB-01 / P0 | 一部実装:承認者継承/定足数/対象再検証/決裁UI、広域公開影響のページング | AUTH-01。現行source/policy/generation一致、権限失効後の決裁拒否、alias・依存Asset・移動で公開を広げない | [公開](publication.md) |
|
||||
| PUSH-01 / P0 | 一部実装:claim世代をattemptから分離、購読version付き削除、Retry-After | 古いworker結果と新購読の競合、送信成功後DB失敗、lease超過を注入。配送はexactly-onceと表現しない | [Ordoschnellic](ordoschnellic.md) |
|
||||
| QUEUE-01 / P0 | 一部実装:終了context/drain、汎用lease・heartbeat・fencing | 所有世代を比較して完了、旧worker遅延完了を拒否。全worker/CLIを含むwriter契約が揃うまで多重運転しない | [Dregarnuhr](dregarnuhr.md) |
|
||||
| OUT-01 / P1 | 一部実装:未接続producer、consumer別再生/backoff/公平性、保持 | consumer変更時のbootstrap、一意キーtombstone、最遅必須consumerを含む安全な清掃。heads/checkpointだけ残して履歴を安易に削除しない | [outbox](outbox-delivery.md) |
|
||||
| MAIL-01 / P1 | 一部実装:キュー中再送の取消、Inbox結果、保持設定/receipt整理 | attempt世代、同意、設定versionを再検査。詳細90日整理と重複防止記録の寿命を区別。SMTP結果不明を自動再送しない | [日次メール](task-digest-delivery.md) |
|
||||
| STORE-01 / P0 | 一部実装:legacy schema/context整理、整合snapshot・restore契約、GC pin | migrationの再実行・途中失敗・旧データ保持・参照整合性。DB、CAS、可変正本、暗号鍵、外部副作用を一体で復旧判断 | [保存移植性](../storage-portability-and-operations.md)、[Geduldh](geduldh.md) |
|
||||
|
||||
## B. スケーリングと日常UX
|
||||
|
||||
| ID / 優先 | 状態・次の作業 | 依存・完了条件 | 詳細 |
|
||||
| --- | --- | --- | --- |
|
||||
| SEARCH-01 / P1 | 一部実装:現行head/Domain/言語別索引、H1 metadata、再開可能backfill | AUTH-01。候補上限を網羅性と混同せず、watermark・continuation・日本語検索・起動時間を測定。失効した結果をcacheから戻さない | [Mestionora](mestionora.md) |
|
||||
| CITY-01 / P1 | 一部実装:生成由来/手動上書き/除外tombstone、局所reconcile | OUT-01の既存基盤を再利用。同入力で無変更、rename/merge後も手動名を保持、URL更新と所属の整合性 | [City](knowledge-city.md)、原ロードマップCITY-A〜D |
|
||||
| NAV-01 / P1 | 一部実装:directory索引、有界children/Cityページング、共通sidebar | AUTH-01、CITY-01。隠れた件数・ラベルを出さず、Domain全件読込に依存しない。巨大階層の時間・行数・heapを測定 | [ナビ](navigation-search.md) |
|
||||
| RENDER-01 / P1 | 一部実装:provider版付きcache、同一描画の集約/同時数/清掃、隔離 | 描画をforegroundより低優先にする。停止・更新・認可失効・cache破損・容量不足・外部参照を検証 | [Kunstzeal](kunstzeal.md) |
|
||||
| OBS-01 / P1 | 一部実装:情報源別availability、収集共有、rollup/清掃予算、component metrics | 欠測を0としない。返却点数だけでなく走査量を制限。CPU/RAMを根拠なくproviderへ按分しない。SNMPは別選定 | [Seheweit](seheweit.md) |
|
||||
| EDIT-01 / P1 | 一部実装:新規GET時のPage作成を保存まで延期、全入口CAS、block単位保護HTML/挿入palette | 既存E1–E5を回帰。Page+Path+初回Revisionを原子的に作り、閉じるだけでは空Pageを残さない。PlainText変換は欠落を明示 | [編集](editor-resilience.md)、[日常UX](priority-ux-20261031.md) |
|
||||
| UX-01 / P1 | 一部実装:idle session timeout/個人短縮設定、独立CLIとの契約整理 | 絶対期限とは区別。読み取りpollだけで無期限延長しない。CLI本体の検索・転送等は独立repoを確認して別issue化 | [日常UX](priority-ux-20261031.md)、[CLI契約](remote-cli.md) |
|
||||
|
||||
## C. オーガナイザーと利用機能
|
||||
|
||||
| ID / 優先 | 状態・次の作業 | 依存・完了条件 | 詳細 |
|
||||
| --- | --- | --- | --- |
|
||||
| DAV-01 / P1 | 一部実装:上書き競合の候補保存、Inbox、比較/採否 | task履歴と通知を原子的に対応付け、再同期で候補を重複させない。別人・別Domainへ候補本文を漏らさない | [所属統一](task-dav-project-unification.md) |
|
||||
| DAV-02 / P2 | 一部実装:VTODO時刻期限/繰返し/alarm、VEVENT temporal拡張、差分同期 | 対応profileを分離。未知propertyの保持・拒否、削除tombstone、期限切れtokenからの復旧。選定clientで認定するまで完全準拠としない | [共通DAV](caldav-common.md)、[calendar](calendar-implementation.md) |
|
||||
| TASK-01 / P2 | 一部実装:日別capacity、一括計画、focus backfill、Pomodoro周期/日課 | 見積・実績・予定を混同せず、次回生成を冪等化。親子2階層と一般依存DAGを別に扱う | [時間枠](task-planning-focus.md)、[タスク](tasks-tickets.md) |
|
||||
| ORG-01 / P2 | 一部実装:一般予定通知、共有タスク/アドレス帳、owner回復 | AUTH-01、OUT-01。共有相手失効、担当だけでは本文権限を増やさない、通知の重複抑止。外部CardDAV書込は別ゲート | [予定・連絡先](calendar-contacts.md) |
|
||||
| DASH-01 / P2 | 一部実装:同種widget複数、共有layout、plugin widget | 個人layoutとの分離、配置版競合、widgetごとの認可/取得上限。第三者実行はEXT-01後 | [dashboard](organizer-dashboard.md) |
|
||||
| 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・有界CSV macro・既存CSVの表編集/複数セル貼り付けを実装。残件:新規作成UI、大容量編集、矩形選択/範囲コピー、匿名投影、asset指定、ODS境界 | BOM/改行保持、25行描画、行列・セル・総量上限、貼り付けの一括検証/Undo、Revision CAS、権限、競合確認/履歴復元fixture。表示HTMLをCSV正本へ逆流させない | [表設計](extensions.md) |
|
||||
| DIAGRAM-01 / P2 | Reveal.jsビューア/編集プレビューを実装。残件:nwdiag/Draw.io provider、縦スライド・notes・専用print | RENDER-01。有界入力、sandbox、固定版ローカル同梱、ドメイン単位停止、Path認可。SVG・include拒否・ticket/CAS保存はprovider別に検証 | [Kunstzeal](kunstzeal.md)、[スライド](extensions.md) |
|
||||
| RECIPE-01 / P2 | 未実装:構造化レシピmetadataとPage投影の初期slice | 材料・数量・未知単位を保持、人数変更は派生値、Asset認可、版競合、出典・公開確認 | [料理レシピ](recipe-management.md) |
|
||||
|
||||
## D. 選定・別サブプロジェクト
|
||||
|
||||
| ID / 優先 | 状態・次の作業 | 着手ゲート・最初の検証 | 詳細 |
|
||||
| --- | --- | --- | --- |
|
||||
| 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) |
|
||||
| FED-01 / P3 | 一部実装:管理設定ACK/鮮度、選択権限情報の署名付きDomain配信 | 既存group継承を保持。origin/sequence/競合/revoke/再参加を定義し、独立ローカルgrantを消さない | [Campus](campus-federation.md) |
|
||||
| BACKEND-01 / P3 | 未実装:S3/SFTP、読取WebDAV/SSH、外部SQL、設定/復旧UI | STORE-01。conditional create、Range、破損・切断・遅延・mount喪失の共通試験。単なるmountを正式対応としない | [Geduldh](geduldh.md)、[運用](operations.md) |
|
||||
| DR-01 / P3 | D1未実装:DR01〜13、LB/HA、controller/data authority分離 | 最初は型・pure state machine・mock probe。writer境界合意、fence設備、RPO/RTO、復旧訓練なしで自動昇格しない | [DR実施計画](dr-delivery-plan.md) |
|
||||
| NETWORK-01 / P3 | 未実装:IPAM/DNS/資産管理、検疫scanner | 型付き正本、権限、dry-run→承認→apply、冪等性。スキャン/外部DNS更新を閲覧リクエスト内で行わない | [拡張](extensions.md)、[原ロードマップ](../implementation-roadmap.md) |
|
||||
| CONTENT-01 / P3 | 未実装部分:他Wiki記法、widget、外部検索/Linkding、時刻・日没theme | provider単位の送信同意・上限・失効・変換欠落試験。既存壁紙色themeと時刻条件themeを区別 | [拡張](extensions.md)、[viewer/editor](viewer-editor.md) |
|
||||
|
||||
### 明示的に保留するもの
|
||||
|
||||
- **HOLD-01**:`/tasks/` 配下のメールWikiルーティング調査。利用者の棚上げ指定を維持。関連未コミットファイルを今回の実装・文書コミットへ混ぜない。
|
||||
- **HOLD-02**:vim.wasm runtime改善とnativeアプリ起動。既存設定UIは残すが、自動的に再開しない。
|
||||
- **HOLD-03**:全面WYSIWYG、E6 CRDT/OT共同編集。まずEDIT-01と認可/presence契約、保存量・オフライン・競合モデルを確定する。
|
||||
- **HOLD-04**:本番反映は実装と別ゲート。[v0.15.0までの配備](../../operations/releases/2026-11-08-v0.15.0.md)は完了。追加変更には同世代保全と隔離復元試験、容量確認、外部副作用照合が必要。古いbinaryを新schemaへ向ける切戻しは禁止。
|
||||
|
||||
## 実装と分けて管理する受入
|
||||
|
||||
| ID | 確認待ち | 今回確認していない範囲 |
|
||||
| --- | --- | --- |
|
||||
| ACCEPT-01 | iPhone SE/Safariのカレンダー、IME、電話handoff | Chromiumの狭幅fixtureだけでは実機受入としない |
|
||||
| ACCEPT-02 | Pushの背景受信・再訪・logout・VAPID rotation | 同意済みテスト端末を使う。実通知先へ勝手に送信しない |
|
||||
| ACCEPT-03 | CardDAV/CalDAV clientごとの操作matrix | 過去のTasks.org動作確認は保持するが、全版・全操作の保証に広げない |
|
||||
| ACCEPT-04 | 独立pages-cliの現行契約・配布物 | このrepoの旧Python版でWindows/TLS設定/配布状態を判定しない |
|
||||
|
||||
## 完了・コミット・文書更新の規則
|
||||
|
||||
変更単位ごとに契約、実装、拒否/競合/再送/上限試験を揃えてコミットする。DB変更では
|
||||
旧schema fixture、migration再実行、途中失敗rollback、参照整合性、復旧方式を必要条件にする。
|
||||
破壊的変更・GC・外部副作用は、単に全Goテストが通ることだけで実施可能と判定しない。
|
||||
|
||||
完了時は本書の該当IDと詳細書の状態を同時更新し、ソースcommit、試験、release、本番適用を
|
||||
別々に記録する。旧Phaseの大項目は後続が残る限り丸ごとチェックせず、完了sliceを分ける。
|
||||
残件の総数を完了率には使わない。各行は規模が異なり、着手時に実装・受入単位へ分割する。
|
||||
@@ -1,9 +1,13 @@
|
||||
# PagesWiki 開発設計書
|
||||
|
||||
更新日:2026-09-19。日本語の統合設計版。実装の変更履歴ではなく、現在の境界と次の設計判断を確認するための入口です。
|
||||
更新日:2026-11-08(統合版の初版は2026-09-19)。実装の変更履歴ではなく、現在の境界と次の設計判断を確認するための入口です。
|
||||
|
||||
## この設計書の読み方
|
||||
|
||||
**次に実装する作業は[実装残件台帳](implementation-backlog.md)を入口にする。** `e65ca56`を基準に、実装済みsliceと後続、優先順、依存・完了条件、実機確認待ちと保留を整理した。古い大項目の未チェックを、そのまま全機能未実装と解釈しない。
|
||||
|
||||
2026-11-08追加:[日次タスクメールの配信履歴と手動再送](task-digest-delivery.md)。予約・要求receipt・詳細履歴の保持境界と、DB移行・復旧時の二重送信防止。
|
||||
|
||||
2026-11-02追加:[オーガナイザーの共通ナビゲーションと個人ダッシュボード](organizer-dashboard.md)。配置可能なウィジェット、個人設定への統合、保存・認可・読込負荷の契約。
|
||||
|
||||
2026-11-01追加:[タスク作成・作業記録・達成度レポート・日次メール・個人アドレス帳](task-productivity-contacts.md)。[neomuttとCLIの操作リファレンス](../../operations/neomutt-tasks.md)も参照。
|
||||
@@ -52,6 +56,6 @@
|
||||
21. [決定事項・矛盾の整理・未決事項](/lab/pageswiki-dev/decisions)
|
||||
22. [原資料との対応と外部仕様](/lab/pageswiki-dev/sources)
|
||||
|
||||
## 今回の範囲
|
||||
## 初版の範囲とその後の更新
|
||||
|
||||
今回行うのは設計の再整理と日本語設計書の配置です。オーガナイザー、外部サービス、DAVサーバー、メールアカウント、公開権限の新設は行いません。設計書の配置も匿名公開の許可とは別です。
|
||||
2026-09-19の初版は設計整理と日本語設計書の配置を対象にした。その後の実装は各章の日付付き記録と残件台帳に反映する。2026-11-08の再照合は文書とソースの静的確認であり、本番データの監査・外部サービスへの接続・本番適用は行っていない。設計書の配置も匿名公開の許可とは別です。
|
||||
@@ -111,7 +111,8 @@ Cache-Control: private, no-store
|
||||
- [ ] ディスクcacheの容量・TTL・清掃、renderer更新時の不整合、障害後の一時ファイル残留を管理する。
|
||||
- [ ] provider宛通信と描画サービス内の外部参照を分け、送信許可・接続先・ネットワーク隔離・バージョン固定を契約化する。
|
||||
- [ ] nwdiagの有界parser・安全なSVG出力・編集preview、Draw.io等のproviderを追加する。現在のregistryにnwdiagは実装されていない。
|
||||
- [ ] Reveal互換・HedgeDoc・Slidev・CSS-onlyスライドのimport/save/printを独立providerとして設計する。
|
||||
- [x] Reveal.jsの有界ビューア・既存HTML/Markdownエディタ内previewをローカル固定版で接続する。Path認可・sandbox・ドメイン停止を持ち、正本への保存は既存エディタを利用する([スライド設計](extensions.md))。
|
||||
- [ ] Revealの縦スライド・発表者notes・専用print、HedgeDoc・Slidev・CSS-onlyスライドのimport/save/printを独立providerとして設計する。
|
||||
- [ ] Excalidrawのhosted/browser実行とPDF/動画サムネイル・metadata subprocessを、各々の安全境界を維持したまま段階的に接続する。
|
||||
|
||||
## 検証と反映
|
||||
|
||||
@@ -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に適応します。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# オーガナイザーのナビゲーションと個人ダッシュボード
|
||||
|
||||
タスク・カレンダー・連絡先の入口を共通化し、個人設定と日々の振り返りを分離する。ダッシュボードは本人の作業を見る画面であり、サーバーの実行状態・リソース監視画面とは別に扱う。以下は2026-11-02のソース実装範囲で、2026-11-04にv0.7.0として本番へ反映した。移行・検証・復旧点は[本番反映記録](../../operations/deployments/2026-11-04-v0.7.0.md)を参照する。
|
||||
タスク・カレンダー・連絡先の入口を共通化し、個人設定と日々の振り返りを分離する。ダッシュボードは本人の作業を見る画面であり、サーバーの実行状態・リソース監視画面とは別に扱う。初期実装は2026-11-04にv0.7.0として本番へ反映した。2026-11-09の追加実装は、明日の予定・コマンドウィジェット、件名Markdown、参照欄、個人の外観設定。これらの追加分は本番未反映。
|
||||
|
||||
## 入口と設定の配置
|
||||
|
||||
@@ -10,13 +10,14 @@
|
||||
| --- | --- |
|
||||
| `/v/plan/dashboard` | ウィジェット形式の個人ダッシュボード |
|
||||
| `/v/plan/tasks` | 既存のインライン編集可能なタスク一覧 |
|
||||
| `/v/plan/tasks/index` | neomutt風のキーボード操作によるタスク一覧 |
|
||||
| `/v/plan` | 既存のカレンダー表示。保存されたビューを尊重 |
|
||||
| `/v/plan/contacts` | 個人アドレス帳・履歴・CardDAV接続 |
|
||||
| `/-/sys/config?panel=organizer` | タスクの既定値、日次メール、既定のカレンダー |
|
||||
| `/-/sys/config?panel=organizer` | タスクの既定値、日次メール、既定のカレンダー、個人の外観 |
|
||||
|
||||
旧 `/v/plan/tasks/report` はダッシュボードの達成度ウィジェットへ、旧 `/v/plan/tasks/settings` は個人設定へ303リダイレクトする。カレンダーの表示選択ダイアログはその場の表示変更に使い、既定値の永続化は個人設定へ移す。
|
||||
|
||||
個人設定は通常の設定画面と同じURI体系・テーマを使うが、専用の軽量な画面として返す。GET/HEADかつ正確な `panel=organizer` の場合だけ個人向けハンドラーに振り分け、管理用設定やアカウント一覧は取得・描画しない。POSTの管理者チェックは緩和しない。保存先は既存の本人用APIであり、一般利用者に管理権限を付与しない。
|
||||
個人設定は通常の設定画面と同じURI体系・テーマを使うが、専用の軽量な画面として返す。GET/HEADかつ正確な `panel=organizer`、またはPOSTで `panel=organizer§ion=appearance` の場合だけ個人向けハンドラーに振り分ける。管理用設定のPOSTは従来どおり管理者を要求する。個人設定の保存は本人のactiveアカウントに限定し、管理権限を付与しない。
|
||||
|
||||
## タスク編集画面と通知既定値
|
||||
|
||||
@@ -26,6 +27,43 @@
|
||||
|
||||
760px以下では1カラムにし、主な入力と選択ボタンは44px以上のタッチ領域を確保する。個人設定には新規タスクの期限日・取り組む日のInbox通知と通知時刻を設ける。適用条件と既存データの扱いは[タスク通知](task-reminders.md)を参照する。
|
||||
|
||||
## キーボード操作のタスク一覧
|
||||
|
||||
`/v/plan/tasks/index` を既存のインライン編集とは別の表示として提供する。タスク画面の「キーボード一覧」から開く。左側はプロジェクト、右側は状態・件名・期限・取り組む日・優先度・関連Wikiの表。件名Markdownと選択行のテーマ色を使い、サブタスクは矢印で区別する。順序は指定ソートを優先し、親子の隣接は保証しない。
|
||||
|
||||
| キー | 操作 |
|
||||
| --- | --- |
|
||||
| `j` / `k`、上下矢印 | 次/前のタスクを選択 |
|
||||
| `Ctrl+j` / `Ctrl+k` | 次/前のプロジェクトへ表示を切り替え(所属変更ではない) |
|
||||
| `o` / `O` | ソート選択欄へ/昇順・降順を反転 |
|
||||
| `l` / `Esc` | 絞り込み欄へ/一覧へ戻る。絞り込みはEnterで適用 |
|
||||
| `d` | 選択タスクを完了。削除やアーカイブではない |
|
||||
| `s` | 選択タスクで25分Pomodoroを開始。実行中セッションは上書きしない |
|
||||
| `c` / `m` | 作成/既存の編集ダイアログを開く |
|
||||
| `w` | 関連Wikiへ移動。リンクがなければ案内し、暗黙に新規作成しない |
|
||||
| `?` | キーと絞り込み式のヘルプ |
|
||||
|
||||
入力欄、IME変換中、ダイアログ表示中にはショートカットを実行しない。更新系キーはキーリピートを無視する。作成時は選択中のプロジェクトを引き継ぎ、「すべて」では個人の既定値、「プロジェクトなし」では明示的な未所属とする。ブラウザやOSが予約しているキーをページ側へ渡さない環境では、同じ操作を画面のボタンから行う。
|
||||
|
||||
初期絞り込みは `~active`。複数条件はAND、`!` を条件の前に付けると否定する。OR・括弧・正規表現は扱わない。空欄はアーカイブ以外の全状態を表示する。
|
||||
|
||||
| 書式 | 意味 |
|
||||
| --- | --- |
|
||||
| `~s "リリース準備"` | 件名の部分一致。空白を含む値は引用符で囲む |
|
||||
| `~active` / `~todo` / `~doing` / `~done` / `~cancelled` | 未完了/未着手/着手中/完了/取りやめ |
|
||||
| `~overdue` | ドメインの今日より前に期限を迎えた未完了タスク |
|
||||
| `~due <=today` / `~planned tomorrow` / `~start >=2026-11-01` / `~review <today` | 期限・取り組む日・着手日・見直す日。日付はYYYY-MM-DD、today、tomorrow。比較は `= < <= > >=` |
|
||||
| `~due none` | 日付なし。planned、start、reviewにも使用可能 |
|
||||
| `~bucket inbox` / `~bucket backlog` / `~bucket someday` | 整理先 |
|
||||
| `~priority 3` | 優先度0〜3の一致 |
|
||||
| `~wiki` / `~attachment` / `~archived` | 関連Wikiあり/URL・Path参照あり/アーカイブ済み |
|
||||
|
||||
例:`~s "リリース" ~doing !~overdue`。プロジェクト・条件・ソートはURLクエリへreplaceStateで保持し、操作ごとに履歴エントリを増やさない。
|
||||
|
||||
取得は既存 `items` APIの `view=index`。`filter`、`sort`(due/planned/title/status/priority/created/updated)、`order`(asc/desc)、`project`、`before`を使う。未所属は `project=none`。サーバーで対象全体を絞り込み・ソートして100件ずつ取得し、末尾での下移動または追加読込で次を取得する。ソート値とUUIDによる順序を使い、他ユーザーのカーソルから内容を返さない。日付未設定は昇順の末尾、完全な逆順では先頭になる。並行更新時の固定スナップショットではないため、再読込で最新状態を確認する。
|
||||
|
||||
条件は1000バイト・最大64トークン。SQLは値をバインドし、ソート列は許可リストから選ぶ。不正条件は422で、旧表示を残して操作ボタンを無効化する。プロジェクトも検索・50件単位の追加読込とし、一括取得しない。完了は表示時のversionをIf-Matchで送る。別更新があれば412で止め、メモ等を最新取得しても古い選択行からの更新を無条件に通さない。本人の権限・読み取り専用制限は既存APIに従う。この一覧追加にDBスキーマ変更はない。
|
||||
|
||||
## ウィジェット
|
||||
|
||||
初期構成は次の6種類。任意のHTML・iframe・外部URL・スクリプトを登録する機能ではなく、サーバーが許可する組み込みIDを使う。
|
||||
@@ -39,13 +77,15 @@
|
||||
| `schedule` | 既定カレンダーにある今日の予定 |
|
||||
| `activity` | 完了数・ポイント・作業時間・集中時間、日別ヒートマップ |
|
||||
|
||||
追加メニューには `feeds`(RSS)、`tomorrow-schedule`(明日の予定)、`commands`(タスクコマンド)も用意する。既存の保存済み配置に自動追加せず、追加後に「配置を保存」で確定する。予定は時刻範囲・件名・カレンダー名をカード状に配置し、開催中の予定を強調する。終日予定は時刻の代わりに「終日」を表示する。
|
||||
|
||||
タブはウィジェットの枠内で内容を切り替える。iframeを使わず、ページやブラウザ履歴を移動しない。タスク件名や右上の矢印は既存の詳細・一覧へ移動する。タスクの編集操作は従来の一覧・詳細画面を利用する。
|
||||
|
||||
達成率の分母は `planned_on=今日`、分子はそのうち `status=done` の件数。取りやめ・アーカイブ・プロジェクトを除く。日付はドメインのタイムゾーンで判定する。対象0件は100%でなく「—」を表示する。期限超過を含む「本日のタスク」の件数とは意図的に異なり、画面に定義を明記する。ヒートマップのポイント計算は[タスクの集計契約](task-productivity-contacts.md)に従う。
|
||||
|
||||
## 配置と保存
|
||||
|
||||
デスクトップは12列グリッド。幅は3〜12列、高さは2〜10単位、1単位の表示基準は72pxと12pxの間隔。順序に従ってグリッドへ配置するため、幅の組み合わせによって空白が生じる。任意の絶対座標を保持するレイアウトではない。
|
||||
デスクトップは画面幅いっぱいの12列グリッド。幅は3〜12列、高さは2〜10単位、1単位の表示基準は72pxと12pxの間隔。順序に従ってグリッドへ配置するため、幅の組み合わせによって空白が生じる。任意の絶対座標を保持するレイアウトではない。
|
||||
|
||||
歯車で配置モードを開き、ハンドルのドラッグで並べ替え、右下のハンドルでサイズを変える。矢印ボタンと幅・高さの選択欄でも同じ操作が可能。追加・除去・初期配置への復帰に対応し、「配置を保存」で確定する。タブの選択も配置の一部として保存できる。未保存の離脱を警告し、保存失敗・競合時には編集中の配置を残す。ブラウザ再起動をまたぐ未保存レイアウトの下書きは持たない。
|
||||
|
||||
@@ -69,6 +109,28 @@ APIは `/_/api/v1/extension/organizer.tasks/` 配下。
|
||||
|
||||
## 検証と後続範囲
|
||||
|
||||
### タスク表示と参照
|
||||
|
||||
件名の保存形式は文字列のまま。Web一覧では太字、斜体、取り消し線、インラインコード、リンクのラベルをDOMで描画する。HTML・画像・マクロを実行しない。インライン編集のフォーカス中はMarkdownソースをそのまま入力できる。関連Wikiがある行は塗りつぶした文書アイコンとテーマ色で区別する。
|
||||
|
||||
`TaskRecord.references` はURLまたはWiki Pathの配列(最大20件、1件4096バイト)で、タスクの編集画面の詳細設定から変更する。http/httpsと同一サイトの絶対Pathだけを認め、認証情報入りURL・プロトコル相対URL・制御文字は拒否する。リンク先の取得や公開範囲の変更は行わない。Path参照は文字列のためrenameには追従しない。rename追従が必要な主たる関連Wikiには従来の `page_uuid` を使う。
|
||||
|
||||
正本JSONと変更履歴に参照を保存し、タスクの列追加は不要。旧CLI等がこのフィールドを省略した更新では既存値を維持し、明示的な空配列で解除する。CalDAV更新でも維持するが、VTODOのATTACHへの投影は後続範囲。
|
||||
|
||||
### タスクコマンド
|
||||
|
||||
`add task 件名`、`today UUID`、`tomorrow UUID`、`due UUID YYYY-MM-DD`、`due UUID clear`、`done UUID`、`delete UUID` を提供する。対象は件名検索のサジェストから選ぶとUUIDが入る(250ms debounce、最大10件)。シェルコマンドではない。追加は個人の既定値を読み、通信失敗時は同じUUIDで再試行できる。既存タスクへの操作は取得時のversionをIf-Matchで送信し、競合時は上書きしない。削除は件名を確認してから実行する。今日・明日はダッシュボード読込時のドメイン日付を基準とする。
|
||||
|
||||
### 個人の外観とログイン画面
|
||||
|
||||
壁紙Path・不透明度・グラス透明度・壁紙からの色抽出を個人設定へ追加する。トップ画面の歯車も同じ本人用保存先を使う。初回は既存のドメイン設定を初期値として引き継ぎ、保存後は個人値を優先する。空の壁紙Pathは「壁紙なし」。フォルダ選択時は従来どおり閲覧可能な直下の画像から選ぶ。
|
||||
|
||||
`personal_appearance` はDomain UUIDと本人UUIDを複合キーにしたJSON+versionのテーブル。起動時の設定テーブル初期化で追加する。既存テーブル・正本を破壊せず、保存はversion比較で競合409を返す。タスク既定値・メール同意のversionを変更しない。ドメイン設定画面の外観項目は初期値用として区別する。
|
||||
|
||||
ログイン画面は壁紙なしとし、旧 `/_/auth/wallpaper` は404を返す。個人・ドメインのトップ壁紙をログイン前に公開しない。別のログイン専用背景Pathは今回追加しない。
|
||||
|
||||
### 回帰検証
|
||||
|
||||
合成データで、所有者分離、CAS、読み取り専用、匿名拒否、管理設定への権限拡大がないこと、空配置、禁止ウィジェット、メール設定の不変、今日の集計・予定範囲を検証する。ブラウザではデスクトップとスマホの導線、タブ、設定保存、配置保存、横はみ出しを確認し、デスクトップのドラッグ・リサイズには実ポインター入力を使う。本番の外部取り込みカレンダーは検証に使わない。
|
||||
|
||||
次段階は以下を別途設計する。
|
||||
|
||||
@@ -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契約、再認証、既存セッションへの即時適用を別途設計する。
|
||||
@@ -38,7 +44,8 @@
|
||||
|
||||
- [x] HTTPクライアント初期版 `pages-cli`/コマンド `pages`(2026-11-01ホストのユーザーPATHへ配置済み。実ユーザログインは未実施):configureによる接続先・既定プロファイル・言語管理、パスワード/TOTP、Bearer保持・失効、ls/cd/cat/view/get、既存Page edit/put、Path補完、メモリ内履歴、検索候補、ブラウザ引き継ぎ。詳細と原設計整合は [遠隔CLI](remote-cli.md)。既存DB直アクセスCLIは変更しない。
|
||||
- [x] 専用起動コマンドとセッション保持は独立HTTPクライアント `pages` として実装。既存 `data/pageswiki-cli` のDB直接操作とは分離し、資格情報に0600の保護と失効/ログアウトを設ける。
|
||||
- [ ] `Ctrl+P` のfuzzy検索と、ローカル `$EDITOR` 編集。現在版/ETagを保持してアップロード時の競合を検出し、上書き・差分・キャンセルを選べるようにする。
|
||||
- [x] ローカル `$EDITOR` 編集、現在Revisionを指定した保存、409時の原稿保全(分離前のHTTPクライアント)。
|
||||
- [ ] `Ctrl+P` のfuzzy検索と競合の対話選択。独立CLI側の現状を確認して追跡する。サーバーの新規作成契約とは分ける。
|
||||
- [x] ターミナルにURLを表示するブラウザ認証(OIDC)。`pages login --oidc [--no-browser]`、S256、5分の単回grant、確認コード/CSRF/TOTP、失効再確認、poll・発行上限を実装。2026-11-01 v0.3.0でサーバー・ホストCLIへ本番反映済み。実providerでの本人承認は利用者確認が残る。契約は[遠隔CLI](remote-cli.md)を参照。
|
||||
- [ ] ターミナル表示が難しい内容はブラウザに引き継ぐ。short linkは認証を迂回しない内部リンクとし、公開share link発行とは分離する。自動公開しない。
|
||||
|
||||
@@ -123,7 +130,7 @@
|
||||
|
||||
現行 `data/pageswiki-cli` はSQLite/Document Storeへ直接アクセスする運用CLI。shell、補完、履歴、`$PAGER`/`$EDITOR` は既にあるが、Web認証を受けるリモートクライアントではない。Webユーザの認可をSQLite直アクセスへ継ぎ足さず、HTTP transportを持つ別コマンド(仮称 `pageswiki remote`)として段階導入する。
|
||||
|
||||
2026-11-01:試作名 `data/pageswiki-remote` から、ユーザ指定によりサブプロジェクト `pages-cli`/実行名 `pages` へ整理。`pages configure` と既定値により通常操作のprofile/lang引数を不要とした。OIDCハンドオフはv0.3.0で本番反映済み。実providerでの本人承認、Ctrl+P、新規作成、強制上書きの対話選択、short linkは残件。[範囲・制限・検証](remote-cli.md)を参照。
|
||||
2026-11-01:試作名 `data/pageswiki-remote` から、ユーザ指定によりサブプロジェクト `pages-cli`/実行名 `pages` へ整理。`pages configure` と既定値により通常操作のprofile/lang引数を不要とした。OIDCハンドオフはv0.3.0で本番反映・利用者確認済み。既存Pageの言語分岐と編集はv0.4.0で対応済み。新規Pageの原子的な作成は別件。2026-11-06以降のCLI本体は独立repoを正とし、Ctrl+P・転送・配布対応等の現状を旧同梱版だけで判定しない。[範囲・制限・検証](remote-cli.md)を参照。以下の番号付き項目は初期実装時の契約で、すべて未着手という意味ではない。
|
||||
|
||||
1. パスワード+TOTPの既存JSONログイン、失効/logout、接続先・Principal・Domain別セッション保存。秘密情報はコマンド引数/履歴/ログへ出さず、保存先0700・資格情報0600相当、TLS検証必須。
|
||||
2. `ls/cd/view/get/edit` と現在Pathの保持。検索は認可付き・件数制限・キャンセル可能なAPIを使用し、`Ctrl+P` のfuzzy選択へ接続。端末の制御シーケンスは本文/タイトルから除去する。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 6. 公開・承認・共有・匿名ナビゲーション
|
||||
|
||||
状態:明示的なRevision公開、Street/Spotの自動公開、匿名ナビゲーションは実装済み。承認者Inboxは受信者単位の保存・既読APIまで実装済みで、承認要求の生成・決裁UI・配送ワーカーはTODO。共有URL管理もTODO。
|
||||
状態:明示的なRevision公開、Street/Spotの自動公開、匿名ナビゲーションは実装済み。承認要求の登録・限定決裁APIと受信者別Inboxは実装済み。上位方針・reviewer継承、定足数、現行Revisionの再検証、決裁UIを含む公開運用フローは未完成。共有URL管理もTODO。2026-11-08、`publication_approval_api.go`と照合。
|
||||
|
||||
## 三つの異なるもの
|
||||
|
||||
@@ -42,9 +42,9 @@ Domain・Quartierもrequiredの上限制約を設定できます。automaticは
|
||||
|
||||
状態はdraft → requested → approved / rejected / expired / supersededを案とします。取り消し・公開撤回は別監査イベントです。上位の承認必須設定を下位が解除できないこと、自動公開との優先順位、本人承認の可否を実装前に確定します。
|
||||
|
||||
共通通知Inboxの第一段階として、`notification_inbox`にDomain・受信者・イベント・種別を保存し、同じ組合せを重複排除します。`GET /_/api/v1/notifications` は現在のPrincipalに限定して `unread`、`limit`、`before` のkeyset取得を行い、`POST/PATCH /_/api/v1/notifications/read` は同じDomain・受信者の通知だけを既読化します。通知は権限や承認を付与せず、本文や秘密を保存しません。承認要求からの生成と再表示時の権限再検査は次段階です。
|
||||
共通通知Inboxの第一段階として、`notification_inbox`にDomain・受信者・イベント・種別を保存し、同じ組合せを重複排除します。`GET /_/api/v1/notifications` は現在のPrincipalに限定して `unread`、`limit`、`before` のkeyset取得を行い、`POST/PATCH /_/api/v1/notifications/read` は同じDomain・受信者の通知だけを既読化します。通知は権限や承認を付与せず、承認対象の本文や秘密を保存しません。要求登録からの限定的なInbox生成は下記のAPIに接続済み。現行対象の再検査を含む完全な決裁フローは次段階です。
|
||||
|
||||
承認要求の対象(Path/Object/RevisionのハッシュとJSON)、policy version、generation、期限、要求者を`publication_requests`に固定保存し、決裁履歴を`publication_decisions`へ追記します。期限付きpending要求はスケジューラが小さなbatchでexpiredへ遷移させます。レビュアーの現在権限を再検査する決裁APIとInbox UIは、まだ公開していません。
|
||||
承認要求の対象(Path/Object/RevisionのハッシュとJSON)、policy version、generation、期限、要求者を`publication_requests`に固定保存し、決裁履歴を`publication_decisions`へ追記します。期限付きpending要求はスケジューラが小さなbatchでexpiredへ遷移させます。Domain管理者向けの限定決裁APIは存在しますが、委譲レビュアーの決裁UI・完全な公開承認フローを提供した状態ではありません。
|
||||
|
||||
認証済みのDomain管理者向けに、`POST /_/api/v1/publication/requests`でboundedな対象manifestを登録できます。idempotency keyで再送をまとめ、指定されたレビュアーがDomain管理権限を持つ場合だけInbox通知を作成します。`POST /_/api/v1/publication/requests/{uuid}/decisions`はDomainとgenerationを再検査し、承認・拒否をCASで一度だけ適用します。上位方針の継承、定足数、対象Revisionの現在性検査は、公開運用へ進む前の残タスクです。
|
||||
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
2026-11-06:利用者向けの[クライアント契約](https://git.anya.jp/anya/pages-cli/src/branch/main/docs/client-contract.md)と[NeoMutt連携](https://git.anya.jp/anya/pages-cli/src/branch/main/docs/neomutt.md)は独立した公開pages-cliリポジトリへ移転した。本書はサーバー側のHTTP・OIDC認証契約、結合テストと導入履歴を保持する。下記のv0.3.0/v0.4.0は分離前のサーバー同梱版の番号であり、独立CLIはv0.1.0から採番する。
|
||||
|
||||
2026-11-08整理:以下のPython実装・Windows未対応・TLSバイパスなし等の記述と末尾の
|
||||
「次段階」は分離前の同梱版の記録であり、独立CLIの現行制約ではない。独立版の実装・配布・
|
||||
残件は上記repoを正とする。今回の文書照合では独立版HEADを取得していない。
|
||||
サーバー側の新規作成/CAS等の後続は[残件台帳 EDIT-01 / UX-01](implementation-backlog.md)で追跡する。
|
||||
|
||||
2026-11-01。合成データで検証済み。同日、本番サーバのCity更新と合わせてクライアントをホストの `/home/anya/.local/bin/pages` に配置した。実ユーザの資格情報取得・ログイン・本番Page編集は未実施。接続設定とログインは利用者が行う。[反映記録](../../operations/deployments/2026-11-01-city-pages-cli.md)。
|
||||
|
||||
v0.3.0のOIDCログインは利用者の動作確認済み。v0.4.0ではOIDC承認時の追加ローカルTOTPを廃止し、CLIの `auto` 言語選択と既存Pageの新規言語版編集を実装した。2026-11-01 21:48 JSTに本番サーバー/PATH上のCLIへ反映済み。[v0.4.0反映記録](../../operations/deployments/2026-11-01-v0.4.0.md)。
|
||||
@@ -21,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
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
# 20. 実装順序と受け入れ条件
|
||||
|
||||
状態:2026-09-19再整理。旧Phase番号は原ロードマップとの対応用に残し、実装は依存関係とリスク順に進めます。
|
||||
状態:2026-11-08再照合。旧Phase番号は原ロードマップとの対応用に残し、実装は依存関係とリスク順に進めます。
|
||||
|
||||
現在の作業単位・優先順・受入条件は[実装残件台帳](implementation-backlog.md)に集約しました。
|
||||
以下の日付付き追記と旧優先表は経緯を残すものです。共通outbox、限定DAV、個人連絡先、
|
||||
HTML保護、Inboxなどの初期sliceは実装済みで、旧表の項目全体が新規開発という意味ではありません。
|
||||
2026-11-08の利用者指定により、**RSS・情報収集 → 構造化ドキュメント/編集部品 →
|
||||
料理レシピ → タスク・プロジェクト管理の第2段階 → 共同作業・公開承認・共有**の順で進めます。
|
||||
必要な認可・整合性・性能対策は各機能の受入条件へ組み込みます。以前の回復・基盤改善を
|
||||
先に一巡する推奨順は置き換え、下記の日付付き「次は」は当時の記録として扱います。
|
||||
|
||||
## 優先順
|
||||
|
||||
2026-11-08:[日次メールの配信履歴・手動再送・保持境界](task-digest-delivery.md)をソース実装。migration v4は旧予約を保持し、詳細整理後も日別予約と要求receiptを残す。本番反映は保留して整合性検証を優先する。次は失効Domainに取り残された作業記録の回復、取消済み作業記録の復元と監査保持。共有・外部書き込みは別段階。
|
||||
|
||||
2026-11-08:[作業記録の訂正・取消と監査履歴、プロジェクト別集計](task-productivity-contacts.md#作業記録の訂正と取消)をソース実装。タスク一覧・ダッシュボードから履歴画面へ接続。DBのmanaged migration v3を伴うため、本番反映はバックアップと別工程にする。日次メールの配信結果・手動再送・保持契約は同日の後続実装へ進んだ。失効Domainに取り残された作業記録の回復、共有、外部書き込みは残件。
|
||||
|
||||
2026-11-02:[共通ナビゲーション・個人設定・ウィジェットダッシュボード](organizer-dashboard.md)を実装。タスク/カレンダー/連絡先の導線統一、トップ・ナビバーの連絡先、個人別の配置・サイズ保存。ソース実装と本番反映は区別し、共有・外部ウィジェットは後続。
|
||||
|
||||
2026-11-02:[個人CardDAV提供と履歴復元・一括export](../../operations/carddav-contacts.md)を実装。専用資格情報、条件付き更新、変更tokenと削除tombstone、bounded REPORTを追加。09:04:17 JSTに[v0.6.0として本番2系統へ反映](../../operations/deployments/2026-11-02-v0.6.0.md)。共有アドレス帳・外部CardDAV connector・実機互換確認は同資料の後続範囲。
|
||||
|
||||
2026-11-01:[タスク作成・作業記録・達成度・日次メール・個人アドレス帳](task-productivity-contacts.md)を追加。Web/CLI/neomuttの共通capture、時間記録、既定値、検索コマンドを接続。作業記録の事後訂正、日次メールの再送・保持期間は同設計の後続範囲へ集約する。
|
||||
2026-11-01:[タスク作成・作業記録・達成度・日次メール・個人アドレス帳](task-productivity-contacts.md)を追加。Web/CLI/neomuttの共通capture、時間記録、既定値、検索コマンドを接続。作業記録の事後訂正と日次メールの再送・保持境界は2026-11-08の実装へ進んだ。
|
||||
|
||||
2026-10-31:ユーザ指定により[日常操作・ブラウザ・エディタ・CLI](priority-ux-20261031.md)を次期開発の最優先とする。下記の従来機能追加より優先するが、認可・データ保全の安全条件は省略しない。TODO、受け入れ条件、復元用チェックポイントを同文書に集約する。
|
||||
|
||||
@@ -34,7 +46,7 @@
|
||||
| P1-3 | 検索・decode・大容量 | 現行上限と測定 | current-only検索、隔離、stream、cancel |
|
||||
| P2-1 | 通知と承認Inbox | P0、outbox | 現在権限で再表示・決裁・失効 |
|
||||
| P2-2 | HTMLパーツ | round-trip fixture | macro/asset/未知HTMLを壊さない |
|
||||
| P2-3 | local task | extension契約、原子的ジャーナル | 個人タスク/プロジェクト・Inbox通知・個人local時間枠・永続化Pomodoro・Todayの見積/時間枠/集中集約を実装済み。次は計画持ち越し、日課、共有 |
|
||||
| P2-3 | local task | extension契約、原子的ジャーナル | 個人タスク/プロジェクト・Inbox通知・個人local時間枠・永続化Pomodoro・日別計画と持ち越し・作業記録訂正と集計・日次メール再送を実装済み。次は失効Domainの作業記録回復、日課、共有 |
|
||||
| P2-4 | RSS読取・Wiki保存 | connector共通部 | FreshRSS fixtureと安全なcopy |
|
||||
| P2-6 | 料理レシピ管理 | Document/Asset、検索、権限 | 材料・分量・手順・調理時間・人数・タグを構造化し、単位変換と安全な共有を検証 |
|
||||
| P3 | calendar/contact/mail | import/secret/競合契約 | read-only同期、明示copy、障害復旧 |
|
||||
@@ -57,7 +69,7 @@ P2以降の順序は利用価値で入れ替え可能ですが、P0の該当安
|
||||
- 認証・グループ:実装あり。全endpoint監査・identity lifecycleが残り。
|
||||
- 匿名公開・children/tree/City:実装あり。大規模影響確認、share、承認Inboxが残り。
|
||||
- ブログ・日記・公開射影・本文RSS:実装あり。遠隔射影、コメント、tDiary等が残り。
|
||||
- オーガナイザー:カレンダーと限定CalDAV、個人タスク/プロジェクト・個別ONのInbox通知、個人local時間枠と永続化Pomodoroあり。[タスク実装契約](tasks-implementation.md)、[時間枠とPomodoro](task-planning-focus.md)参照。一般のカレンダー予定通知・共有・VTODO、RSS購読・IMAPは未実装。
|
||||
- オーガナイザー:カレンダーと限定CalDAV、個人タスク/プロジェクト・VTODO同期・個別ONのInbox通知・個人local時間枠・永続化Pomodoro・日次メール・個人CardDAV・ウィジェットダッシュボードあり。[タスク実装契約](tasks-implementation.md)、[時間枠とPomodoro](task-planning-focus.md)、[タスク所属とDAV同期](task-dav-project-unification.md)参照。一般のカレンダー予定通知・共有、DAV競合候補の通知と採否選択、RSS購読・IMAPは残件。
|
||||
- 全面WYSIWYG、native app起動、第三者runtime、vim.wasm改善:判断待ちまたは保留。
|
||||
|
||||
## 共通のDone
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# 日次タスクメールの配信履歴と手動再送
|
||||
|
||||
2026-11-08、`organizer.tasks 0.14.0` のソース実装。個人設定で配信試行を確認し、当日分を明示的に再送できる。送信は既存の `task.digest.deliver` イベントが行い、Webリクエスト内ではSMTPに接続しない。本番反映は別工程とする。
|
||||
|
||||
## 利用者の操作と公開範囲
|
||||
|
||||
入口は `/-/sys/config?panel=organizer` の「メール配信履歴・再送」。初期は閉じておき、開いたときだけ履歴を取得する。自動ポーリングは行わず、更新ボタンとページ送りを用意する。PCは表、スマホは表の領域内だけ横スクロールする。
|
||||
|
||||
本人・現在のDomainの履歴だけを返す。管理者権限は他人の履歴を読む根拠にならない。readonlyは閲覧だけ可能。無効化したタスク拡張へのAPIアクセスは拒否する。履歴には対象日、定期/手動/移行前の区分、状態、更新時刻、理由コードだけを表示する。本文・宛先・SMTP認証情報・生のエラーを保存しない。
|
||||
|
||||
再送は保存済みの配信設定が有効で、当日の配信試行が既に存在する場合だけ可能とする。初回配信の前倒しや過去日のまとめ送りは含めない。現在のタスクから本文を再構成し、現在の本人のアカウントメールアドレスへ送る。元のメールの完全な再現ではない。設定画面の未保存値は使わない。
|
||||
|
||||
送信済みまたは結果不明の場合は、受信状況を確認し、重複配信の可能性を了承するチェックを必須にする。送信中・待機中には次の再送を受け付けない。同じDomain・本人・日付につき、手動要求は最大5件。処理前に中止された要求も回数に含める。
|
||||
|
||||
## API
|
||||
|
||||
基点は `/_/api/v1/extension/organizer.tasks/`。既存の個人タスクAPIと同じ認証を用いる。CalDAV専用資格情報を一般APIの資格情報へ拡張しない。
|
||||
|
||||
| 操作 | URI | 内容 |
|
||||
| --- | --- | --- |
|
||||
| GET | `digest-history?limit=25&after=...` | 新しい順のitems、次のcursor、設定timezoneのtoday、当日のcurrent、手動要求数retries、配信設定enabled、retention_days |
|
||||
| POST | `digest-history/retry` | request_id、day、expected_attempt、duplicate_acknowledgedを受け取り、受付成功は202とrequest_id |
|
||||
|
||||
一覧は1〜100件、既定50件、Webは25件。`created_ms, uuid` のkeysetを使う。cursorは256 bytes以内。expected_attemptは一覧で取得した当日のcurrent.uuidをそのまま送る。
|
||||
|
||||
要求IDはクライアント生成のcanonical UUID。同じ要求IDと同じ内容の再送は新たな予約を作らない。異なる内容での再利用、古いexpected_attempt、実行中、上限到達は412。対象日が現在の配信timezoneの今日でない場合や、必要な重複確認がない場合は422。配信設定OFF、readonly、権限不足は拒否する。APIはSMTP有効設定とアカウントのメール形式も確認する。
|
||||
|
||||
Webはネットワーク失敗時に同じ要求IDを保持して再試行する。受付済みの要求をGETで観測した場合は、再送を重ねず状態表示へ切り替える。古い要求のreceiptがある場合は、日付が過ぎたり詳細履歴が整理された後の同内容再送にも既存の受付IDを返す。新しいSMTP処理は起こさない。受付応答はメールの到達を意味しない。
|
||||
|
||||
## 状態とワーカー
|
||||
|
||||
| 状態 | 意味 | 次の扱い |
|
||||
| --- | --- | --- |
|
||||
| queued | 手動要求をDBで受付済み | スケジューラがclaimする |
|
||||
| sending | 1つの試行が送信処理を担当 | 通常はsent、uncertain、cancelledへ遷移 |
|
||||
| sent | SMTP処理が正常終了 | 受信箱への到達保証ではない。手動再送には確認が必要 |
|
||||
| uncertain | SMTP結果が不明、またはワーカー中断の可能性 | 自動再送しない。手動再送には確認が必要 |
|
||||
| cancelled | SMTPに渡す前に処理中止 | 原因を確認し、当日なら手動で再予約できる |
|
||||
|
||||
イベントは60秒周期。定期配信の候補は最大20件、手動キューは最大10件を取得し、両者を交互に処理する。全体の時間予算は30秒で、残りは次回へ持ち越す。手動キューは受付時の設定versionを固定する。claim時に権限・拡張機能・配信同意・設定version・対象日を確認し、変更されていれば送信中止にする。
|
||||
|
||||
SMTP直前にも、現在の権限・メールアドレス・同意version・拡張状態・対象日・試行IDを読み取りtransactionで再確認する。2分以上古いclaimでは送信を開始しない。処理の終了は現在の試行IDと状態が一致するときだけ保存し、古いワーカーが新しい試行を完了扱いにできないようにする。
|
||||
|
||||
10分以上sendingのままの試行は、イベントの保守処理で最大100件ずつuncertainへ移す。これは「未送信」との断定ではない。プロセス停止・長い休止・SMTPの応答喪失では送信済みの可能性がある。SMTPとDBを一つのtransactionにできないため、exactly-onceや、休止した古いプロセスからのネットワーク送信を完全に取り消す保証はしない。明示確認付きの再送でこの不確実性を扱う。
|
||||
|
||||
理由コードはSMTP未設定、タスク取得失敗、設定・権限変更、拡張無効化、対象日経過、SMTP結果不明、ワーカー中断に限定する。イベントログには件数だけを残す。
|
||||
|
||||
## DBの正本と保持境界
|
||||
|
||||
正本はSQLite。配信に関する以下の3つを分離する。
|
||||
|
||||
| テーブル | 役割 | 保持 |
|
||||
| --- | --- | --- |
|
||||
| organizer_digest_deliveries | Domain・本人・日付の予約と現在の試行ID/状態 | 恒久。日別の自動二重配信を防ぐ |
|
||||
| organizer_digest_requests | 手動要求IDと要求内容・重複確認・受付時刻 | 恒久。同じ要求の再受付を防ぐ |
|
||||
| organizer_digest_attempts | 個々の試行状態・理由・日時 | 終端状態のupdated_msから90日。queued/sendingは削除対象外 |
|
||||
|
||||
詳細の削除はイベント1回につき最大500件で、日時と状態のindexから選ぶ。設定や再送受付は別のwriter transactionで行い、削除と同じSQLite書き込みロックに従う。日別予約と手動receiptを削除・再作成しない。詳細が期限切れになると古い予約が指す試行の詳細行は存在しなくなるが、予約の状態と重複防止機能は残る。現時点では恒久記録の圧縮・失効は実装しない。
|
||||
|
||||
## 移行と復旧
|
||||
|
||||
task-productivityのmanaged migration v4で、既存の日別予約へattempt_uuidを追加し、試行・受付receiptのテーブルとindexを作る。既存の日別予約を削除せず、元のstateとupdated_msを保ってlegacy試行へ対応付ける。旧試行の設定version・timezoneは不明として扱い、現在の設定から過去の同意を推測しない。
|
||||
|
||||
DDL、旧データの対応付け、migration台帳の更新は同じtransactionで完了する。途中失敗なら旧スキーマと予約へ戻る。再実行でIDや予約を再生成しない。前段のv3を含め、旧migration定義の書き換えは行わない。
|
||||
|
||||
本番反映前には、書き込みを停止した整合DBバックアップと、対応するイメージを確保する。反映後にschema version、予約数、legacy試行との対応、`PRAGMA integrity_check` を確認する。旧イメージは更新DBに接続しない。forward-fixを基本とし、旧DBへ戻す場合は更新後の書き込みを保全して照合する。
|
||||
|
||||
特にメールはDB外で送信されるため、送信開始後のバックアップ復元だけでは重複防止を復元できない。復旧時はイベントの自動送信を止め、更新後の予約・receiptを保全して照合し、送信済みか不明な分を自動再送しないこと。移行・反映・復旧の成功と、実際の受信箱への到達は別の確認である。
|
||||
|
||||
## 受け入れ条件と後続
|
||||
|
||||
- 旧予約の全状態を保つ移行、反復、途中失敗のrollback、DB integrity check。
|
||||
- 二重クリック・応答喪失後の同一要求、異内容再利用、当日制約、5回上限。
|
||||
- readonly・別本人・未認証・配信OFF・権限失効・設定変更・日付経過の拒否または送信中止。
|
||||
- 古い試行の送信前チェックと完了通知の拒否、SMTP結果不明の扱い。
|
||||
- 詳細を削除した後も、手動receipt再送や日別自動claimで配信が復活しないこと。
|
||||
- fake SMTPを用いた予約から送信・結果保存までの試験。ブラウザはPCと390px幅。
|
||||
|
||||
検証結果:`go test ./...`、`go vet ./...`、追加の受付競合・権限・保持境界テストの `-race`、JavaScript構文検査が成功。Chromiumの1440px・390pxで、履歴の遅延読込、重複確認、受付応答の喪失後の同一ID再試行、キュー処理後の状態表示を確認した。DB移行の反復・途中失敗のrollbackと `PRAGMA integrity_check` は隔離DBで確認。本番DBは変更していない。
|
||||
|
||||
後続は保持期間の管理UI、恒久receiptの安全な圧縮、当日予約の明示取消、配信結果のInbox連携、複数ワーカーの運用メトリクス。共有送信先・任意宛先・過去日の送信はこの機能へ暗黙に追加しない。
|
||||
@@ -13,6 +13,9 @@
|
||||
| 実行中の記録 | GET `work` | itemがnullなら停止中 |
|
||||
| 開始 | POST `work` | action=start、uuid、task_uuid。開始時刻はサーバーで記録 |
|
||||
| 終了 | POST `work` | action=stopとGETで得たitem。versionで条件付き更新 |
|
||||
| 作業一覧 | GET `work-history?from=YYYY-MM-DD&to=YYYY-MM-DD&limit=50&after=...` | fromを含みtoを含まない期間と重なる本人の記録。最大367日、1ページ最大100件、取消済みを含む |
|
||||
| 作業の履歴 | GET `work-history/{uuid}?before=VERSION` | 新しい版から最大100件。nextが0なら終了。それ以外は次のbeforeへ渡す |
|
||||
| 作業の訂正・取消 | POST `work` | action=correctまたはcancel、uuid、version、reasonが必須。終了済み・未取消の記録のみ |
|
||||
| レポート | GET `report?from=YYYY-MM-DD&to=YYYY-MM-DD` | fromを含み、toを含まない。ドメインのtimezone、最大367日 |
|
||||
| 予定を作る | POST `calendar-capture` | request_id、calendar_uuid、title、from、to。本人所有・非公開・非共有・外部sourceなしのカレンダー限定 |
|
||||
|
||||
@@ -24,9 +27,15 @@ Webの新規作成・クイック追加・サブタスク追加でも既定値
|
||||
|
||||
### メール本文のWiki保存
|
||||
|
||||
v0.9.0は任意の `wiki_suffix` をcaptureに追加する。CLI v0.4.0はML連番なら `リスト名/連番`、それ以外は `YYYY/MM/UUID`(Message-IDあり)または `YYYY/MM/原文SHA-256`(なし)を送る。Dateの記載タイムゾーンの年月を採用し、不正・欠落時のみ初回取り込みUTC年月を用いる。判定はCLIで確定してoutboxに保持する。リスト名はASCII英数字で始まる100文字以内の英数字・`._-`、連番は先頭ゼロ除去後最大20桁。複数表記は先頭を採用する。不正な表記は年月方式へフォールバックする。
|
||||
|
||||
サーバーはMLの2階層または年月の3階層だけを受理し、絶対Path・`.`・`..`・予約セグメント・query/fragment・不正年月・不正識別子を拒否する。解決した親Pathの下へ結合し、その完全Pathのread/create/write権限を検証する。衝突は409で、別Message-IDのタスクも部分作成しない。wiki_suffixはwiki_body指定時のみ許可する。省略時は従来の `mail-request_id` とし、旧receiptのhash・保存先を維持する。新CLIは旧サーバーに暗黙フォールバックしない。既存ページの自動移動、同じ件名・同じ連番の上書きは行わない。設定変更や月替わりで保留要求を書き換えず、異なるオプションでの上書きを拒否する。
|
||||
|
||||
v0.8.0ではcaptureに省略可能な `wiki_body` と `wiki_prefix` を追加する。wiki_bodyを省略した従来クライアントの契約・receipt hashは変えない。本文を指定した場合、親Pathは要求のwiki_prefix、個人preferencesのwiki_prefix、選択プロジェクトの関連WikiとNotesSubpath(未設定はtasks)の順に解決する。いずれもなければ422 `wiki_prefix_required`。空の明示指定も拒否する。個人設定はDomain・本人単位で、既存preferences JSONに保存するため新規schema migrationは不要。
|
||||
|
||||
本文は256 KiBまでのUTF-8テキスト。H1に件名、preに本文をHTMLエスケープして格納し、波括弧も実体参照にしてマクロを実行しない。Pathは `親Path/安全化した件名--request_id`。既存Pathとの競合は409で、既存ページへ追記・上書きしない。新規Wikiのobject/path/revisionとactivity outbox、タスクのPageUUID、capture receiptは同一DBトランザクションで保存する。rollback時に未参照のcontent-addressed Documentファイルが残る可能性は既存DocumentStoreと同様だが、公開可能なページや片方だけのタスクは残さない。
|
||||
本文は256 KiBまでのUTF-8テキスト。H1に件名、preに本文をHTMLエスケープして格納し、波括弧も実体参照にしてマクロを実行しない。v0.8.1、およびv0.9.0以降でwiki_suffixを省略した場合のPathは `親Path/mail-request_id`。CLIは接続先・本人・Message-ID(なければ原文SHA-256)からrequest_idを生成するため、Path末尾は件名・日本語の文字数・ML連番に依存しないASCIIになる。Message-ID自体はURLへ露出しない。既存Pathとの競合は409で、既存ページへ追記・上書きしない。新規Wikiのobject/path/revisionとactivity outbox、タスクのPageUUID、capture receiptは同一DBトランザクションで保存する。rollback時に未参照のcontent-addressed Documentファイルが残る可能性は既存DocumentStoreと同様だが、公開可能なページや片方だけのタスクは残さない。
|
||||
|
||||
v0.8.0の件名入りPathは自動移動しない。既存receiptの同一要求再送は元のページを返す。CLI v0.3.1は先頭のML連番を除去し、長い自動件名は300 UTF-8 bytes以内に文字境界で省略、変更前のSubjectをWiki本文へ保持する。旧版で保存済みの要求を新しい件名・本文で再作成すると412となるため、通信失敗した要求は保存済みoutboxのretryを使う。v0.8.1ではサーバーAPIの入力フィールド・receipt hash形式を変更していない。v0.9.0ではwiki_suffix未指定時のhashを維持し、指定時はsuffixもhashの対象に含める。
|
||||
|
||||
保存前に対象Pathへのread/create/write権限を検証する。個人タスクの所有権はWikiへの権限を付与しない。Wiki本文の公開範囲は保存先のACLに従うため、個人設定UIに注意を表示する。再送は既定値の再解決より前にreceiptを確認し、既定Pathの変更で重複作成しない。成功応答はitemとpage_pathを返し、タスクの既存メモ操作から関連Wikiへ移動できる。
|
||||
|
||||
@@ -42,13 +51,35 @@ Webのタスク行の▶から開始し、上部の作業記録欄で終了す
|
||||
|
||||
深夜をまたぐ作業はローカル日付境界で分割し、夏時間の日も24時間固定にしない。Pomodoroと手動記録は別集計で、両者を合算しない。各系列は最大10,000件で、上限到達時はpartialを返して期間の絞り込みを促す。
|
||||
|
||||
### 作業記録の訂正と取消
|
||||
|
||||
2026-11-08に `organizer.tasks 0.13.0` としてソース実装。`/v/plan/tasks/work` で一覧と変更履歴を確認し、開始・終了をインラインで訂正する。タスク一覧とダッシュボードの達成度ウィジェットから移動できる。初期期間はドメイン時刻の今日を含む30日。ページ送りは開始時刻・UUIDのkeysetで行い、一度に全履歴を描画しない。変更履歴も開いた記録だけ取得する。スマホはラベル付き縦配置にし、操作部を44px以上とする。
|
||||
|
||||
訂正には `start_ms`・`end_ms`、または `start`・`end` の日時ペアを渡す。日時文字列はオフセット付きRFC 3339、あるいはドメインのタイムゾーンでの `YYYY-MM-DDTHH:mm[:ss]`。夏時間移行で存在しない・二通りに解釈できるローカル時刻は422。繰り返される時刻はAPIから明示オフセットを指定する。Webで未変更の時刻は元の瞬間をRFC 3339で送るため、ミリ秒やオフセットを失わない。
|
||||
|
||||
開始はUNIX epochより後、終了は開始より後かつ現在以前、訂正後の長さは31日以内。同じ本人の他の未取消記録と重なる区間は、別Domainも含めて412で拒否する。隣接区間は許可し、他Domainの記録内容は返さない。実行中は従来の終了操作を先に行う。`reason` は前後空白除去後1〜500 UTF-8 bytes、改行・NUL不可。Web入力は160文字まで。
|
||||
|
||||
取消は物理削除ではなく `cancelled_ms` を記録し、作業時間レポートから除外する。タスクの状態・完了ポイントは変更しない。元の時刻と全変更履歴は残る。訂正・取消後の自動復元、過去の記録の新規挿入はこの段階では扱わない。
|
||||
|
||||
現在値と監査snapshotは同じwriter transactionで保存する。認可・拡張機能の有効状態をロック内で再検査し、versionが一致しない更新は412。理由・変更前後の時刻・版・変更時刻を記録し、他人の記録を管理者権限だけで操作する経路は設けない。通信結果が不明な訂正・取消の再送もversionを検証し、古ければ412にする。最新値と履歴を再取得して判断する。Webは失敗時に入力を保持し、自動上書きしない。従来の開始・終了の再送契約は維持する。
|
||||
|
||||
移行前の記録には過去の編集履歴を捏造しない。初回の変更時に直前の値をbaselineとして捕捉する。baselineのchanged_msは捕捉時刻であり、過去の編集時刻ではない。未変更の旧記録を開いた際は現在値だけをbaselineとして表示する。
|
||||
|
||||
### プロジェクト別の集計
|
||||
|
||||
`report` の `projects` 配列にUUID・タイトル・完了数・ポイント・作業時間を返す。ダッシュボードの達成度ウィジェットに表を追加し、日付セルで選んだ日の内訳にも反映する。プロジェクトなしは独立した行とする。所属は現在のタスクから取得するため、過去時点の所属スナップショットではない。Pomodoroはプロジェクト表に合算しない。
|
||||
|
||||
集計は既存の上限付き取得結果を再利用し、プロジェクトごとに追加クエリを発行しない。10,000件上限でpartialとなる場合はプロジェクト表も部分集計であり、全件合計とは表示しない。
|
||||
|
||||
## 毎日のメール
|
||||
|
||||
`/-/sys/config?panel=organizer` の個人設定で本人が有効化する。旧 `/v/plan/tasks/settings` もここへ移動する。送信先は現在の本人のアカウントメールアドレスのみ。管理者のSMTP設定が必要。時刻はHH:mmとIANA timezoneを保存する。`task.digest.deliver` イベントが60秒周期で期限到来設定を最大20件ずつ処理する。キュー停止・負荷・SMTP遅延で配信時刻が遅れる場合がある。
|
||||
|
||||
当日の計画・期限到来タスクを最大100件送る。件名、期限、取り組む日、見積、タスクURLを含め、メモは送らない。送信直前にアカウント状態・同意のversion・送信先を再確認する。メールによる保存・転送の可能性があるため、既定は無効。
|
||||
|
||||
SMTPとSQLiteをまたぐexactly-onceは保証できない。送信前にDomain・本人・日付で予約し、配送結果はsent、uncertain、cancelled。予約後のクラッシュはsendingとして残す。結果不明の場合は自動再送せず、二重送信を避ける。翌日は通常通り処理し、過去日の取りこぼしをまとめて送らない。設定画面に直近結果を表示する。
|
||||
SMTPとSQLiteをまたぐexactly-onceは保証できない。送信前にDomain・本人・日付で予約し、結果不明の場合は自動再送しない。翌日は通常通り処理し、過去日の取りこぼしをまとめて送らない。
|
||||
|
||||
2026-11-08に `organizer.tasks 0.14.0` として[配信履歴・当日分の手動再送・詳細90日保持](task-digest-delivery.md)をソース実装。個人設定の折り畳み履歴から操作する。送信済み/結果不明の再送には重複の了承が必要。詳細の保持期限後も日別予約・再送receiptを残し、重複防止を維持する。migration v4とDB外のメール送信を考慮した復旧条件は同設計を参照。
|
||||
|
||||
## トップ検索コマンド
|
||||
|
||||
@@ -81,8 +112,18 @@ vCardの内容はDocumentStore snapshot、現在値と所有者・version・検
|
||||
managed schemaにtask-productivityとcontactsを追加。task-productivityは既存organizer_items作成後に実行し、旧完了タスクを1回だけ集計projectionへ移す。既存スキーマ定義の改変ではない。切戻しでは旧版のschema checkが新コンポーネントを未知とするため、単に旧イメージを起動できるとは扱わない。データを消して戻さない。
|
||||
|
||||
- 連絡先の共有アドレス帳、外部CardDAV connector、重複候補mergeは別段階。個人CardDAV提供面と外部サービスの取り込みは区別する。
|
||||
- 作業記録の事後修正・取消、失効Domainで取り残された記録の管理用終了手順、プロジェクト別集計、担当者への共有・通知は後続。
|
||||
- 日次メールの手動再送・配信ログの保管期間、receiptの失効設計は後続。安易な削除で重複作成・配信を復活させない。
|
||||
- 失効Domainで取り残された記録の管理用終了手順、取消済み記録の復元、作業監査履歴の保持期間、担当者への共有・通知は後続。
|
||||
- 日次メールの保持期間UI、恒久receiptの圧縮・失効、配信結果のInbox連携は後続。現在は詳細90日、重複防止記録は恒久保持とする。
|
||||
- vCard legacy変換・version間変換と履歴保持期間は後続。
|
||||
|
||||
利用手順は [neomuttとタスクCLI](../../operations/neomutt-tasks.md) を参照。
|
||||
|
||||
### 作業履歴の移行と検証
|
||||
|
||||
task-productivityのmanaged migration v3は、作業記録へのcancelled_ms追加、organizer_work_revisionsの作成、本人別の区間検索index追加を行う。既存の作業時刻・versionは保ち、既存記録は未取消とする。新しい監査データの正本はSQLiteで、アプリのDBバックアップに含める。
|
||||
|
||||
反映前に整合したDBバックアップを取得する。旧版は取消済み記録を正しく集計できず、schemaのversionも一致しないため、更新DBに旧イメージを向ける切戻しは禁止する。通常はforward-fixを選ぶ。復旧が必要ならアプリを停止し、移行前のDBと対応するイメージへ一緒に戻す。更新後の書き込みは別途保全・照合してから復旧する。本番反映は別工程。
|
||||
|
||||
受け入れ試験は、旧スキーマ移行の反復、本人・Domain分離、readonly・失効・無効化、版競合、重複時間、夏時間の欠落・重複、監査失敗時のrollback、並行訂正、取消による集計除外を対象とする。ブラウザはデスクトップと390px幅で訂正・取消・履歴・412時の入力保持を確認する。既存CLIの開始/終了とCalDAVの契約は変更しない。
|
||||
|
||||
2026-11-08の検証結果:`go test ./...`、`go vet ./...`、追加した競合・監査試験の `-race`、変更JSの構文検査が成功。Chromiumの1440px・390pxで、ダッシュボードのプロジェクト別表から履歴へ移動し、訂正・取消・監査表示・競合時の入力保持と横幅の収まりを確認した。すべて隔離fixtureによる試験で、本番移行は未実施。
|
||||
@@ -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トランザクションです。
|
||||
|
||||
@@ -33,14 +33,14 @@ create/read/update/assign/transition/comment/manageは概念上分離します
|
||||
|
||||
iCalendarにはVTODOがあり、CalDAVはカレンダー資源を扱います。ただしクライアントごとのタスク・繰り返し対応を試験する必要があります。これは「CalDAVだけでチケット管理が完成する」という意味ではありません。[iCalendar](https://www.rfc-editor.org/rfc/rfc5545)、[CalDAV](https://www.rfc-editor.org/rfc/rfc4791)。
|
||||
|
||||
最初はlocal task一覧と期限表示、次にVTODOの明示export/import、最後に選定クライアントとの同期を検討します。workflow、コメント、細かな権限をVTODOへ無理に押し込みません。失われる情報を変換警告に残します。
|
||||
local task一覧と期限表示、限定VTODO/CalDAV同期は実装済みです。次は上書き競合の候補保存と採否、時刻期限・繰り返し・アラーム・差分同期を個別に扱います。workflow、コメント、細かな権限をVTODOへ無理に押し込みません。失われる情報を変換警告に残します。
|
||||
|
||||
## 実装TODO
|
||||
|
||||
- TASK-1:個人local作成/取得/更新、version競合、Page参照、所有者限定一覧は実装済み。削除は復元可能なアーカイブ、物理削除は未提供。
|
||||
- TASK-2:日付の期限/計画/見直し、タイトルフィルタ、archive、個別ONのInbox通知は実装済み。担当共有、通知集約、exportは未実装。
|
||||
- TASK-3:checklist/依存とboundedな一覧・calendar射影。
|
||||
- TASK-3:2階層サブタスク、boundedな一覧、日割り工程表・個人時間枠は実装済み。一般依存グラフ、共有、一括計画・日別capacityは後続。
|
||||
- TICKET-1:queue・番号予約・workflow版・権限付き遷移。
|
||||
- TASK-4:VTODO fixture、未対応property保持、繰り返し・同期の判断。
|
||||
- TASK-4:限定VTODO fixtureと同期、プロジェクト対応・既定リスト名変更は実装済み。繰り返し・時刻期限・差分同期と競合候補の通知/採否は後続。[所属統一](task-dav-project-unification.md)と[残件台帳](implementation-backlog.md)を参照。
|
||||
|
||||
同時採番、二重POST、完了取消、夏時間・終日、assignee失効、本文削除を受け入れ試験にします。
|
||||
@@ -43,6 +43,42 @@ Principalで直下の子だけを認可し、最大250件、`private, no-store`
|
||||
modeをdata属性で指定する。これにより今後のストレージ、アダプタ、City設定でも
|
||||
任意HTMLや専用ファイルブラウザを増やさず同じPickerを再利用できる。
|
||||
|
||||
## 実装済みの壁紙連動配色
|
||||
|
||||
壁紙の色調からアクセントとグラス面の配色を生成し、トップ画面 `/` とその上で開く
|
||||
ダイアログにだけ適用する。通常のViewer、Editor、設定画面、ログイン画面の配色は
|
||||
変更しない。iframe内に独立して表示されるビューにも配色は継承しない。
|
||||
|
||||
設定は `/-/sys/config?panel=home` またはトップ画面右下の歯車から行う。既存のトップ
|
||||
画面設定と同じ管理権限を必要とし、ドメイン共通で保存する。歯車のダイアログでは
|
||||
その場でプレビューし、キャンセル・ESCで保存前の状態に戻す。
|
||||
|
||||
| 項目 | 値と既定値 |
|
||||
| --- | --- |
|
||||
| 壁紙との色連動 | `off`、`accent`、`surface`。既定は `surface`(背景も連動) |
|
||||
| 色の反映量 | 0–100。既定は35。0では元のテーマを維持 |
|
||||
| 明暗 | `preserve`(既定、現在のテーマを維持)、`auto`(表示時の壁紙の明るさから判定) |
|
||||
|
||||
`home_wallpaper_palette` に `{"mode":"surface","strength":35,"brightness":"preserve"}`
|
||||
の形式で保存する。明暗の自動判定は背景も連動する場合だけ有効。グラスの透明度は
|
||||
既存の `home_glass_transparency` で独立して調整する。警告・エラー等の意味を持つ色は
|
||||
上書きしない。壁紙がない場合、画像が壊れている場合、Canvasから色を読めない場合、
|
||||
強制カラーモードの場合は元のテーマを維持する。
|
||||
|
||||
表示済みの画像を64×64へ縮小し、初回描画後のアイドル時間に平均色と彩度を重み付け
|
||||
したアクセント候補を抽出する。追加の画像取得、サーバでの画像解析、定期ジョブは不要。
|
||||
画像表示URLは選択したリビジョンに固定し、抽出結果をDomain UUIDと画像SHA256の組で
|
||||
sessionStorageに最大24件保存する。キャッシュにはRGB値と透明部分の割合だけを保存し、
|
||||
画像本体は保存しない。ストレージが使えない場合は表示中の画像から抽出する。
|
||||
|
||||
文字・リンクは推定したグラス背景とのコントラストを補正する。ただし画像の局所的な
|
||||
明暗までは保証しないため、細かい柄で読みにくい場合は透明度を下げるか色連動をオフにする。
|
||||
既存テーマを切り替えた際は新しいテーマを基準に再計算し、オフにするとそのテーマに戻る。
|
||||
|
||||
回帰テストは `node --test static/js/home-palette-core.test.cjs` と `TestHomePalette*`。
|
||||
`PAGESWIKI_BROWSER_TEST=1` でブラウザテストを有効化すると、一時DBと合成画像を使い、
|
||||
保存・キャンセル・再読み込み時のキャッシュ利用・テーマ切替・画面幅を通して検証する。
|
||||
|
||||
## サイドバー詳細設計(実装待ち)
|
||||
|
||||
管理画面のグループ化されたサイドバーは
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# PagesWiki v0.8.0 本番反映
|
||||
|
||||
2026-11-06 08:48:35 JST、本番のapp・app2・adaptor-gateway・excalidraw-viewerをv0.8.0へ更新した。このホストの `/home/anya/.local/bin/pages` も公開ELFのpages-cli v0.3.0へ更新した。機能・配布物は[リリース記録](../releases/2026-11-06-mail-wiki.md)を参照する。
|
||||
|
||||
## 保全と切替
|
||||
|
||||
`.deployment-backups/release-v0.8.0-20261106/` に構成とデータを保全した。configには旧 `.env`、`.env.release`、Compose、旧CLIの `pages-before-v0.3.0` がある。親ディレクトリ0700、構成コピー0600。data・data2は内容を解釈しないファイルコピーで、外部取り込みカレンダー要素にはアクセスしていない。
|
||||
|
||||
最終 `cutover/data`・`cutover/data2` は対象サービス停止後にchecksum付きrsyncで確定し、差分ゼロ、DB・WAL・SHMのバイト一致と稼働元と異なるinodeを確認した。未変更ファイルは前回の不変バックアップとのみlink-destで共有する。稼働元へのハードリンクは作らない。既存バックアップは削除していない。
|
||||
|
||||
| 時刻 JST | 操作 |
|
||||
| --- | --- |
|
||||
| 08:47:23 | 対象4サービス停止開始 |
|
||||
| 08:48:29 | 最終バックアップ検証完了 |
|
||||
| 08:48:35 | v0.8.0起動完了 |
|
||||
|
||||
停止開始から起動完了まで72秒。リリースイメージとSHAイメージのID・source revision一致を確認してから、`.env.release` をv0.8.0へ変更し、registry overlayの `up --no-build --no-deps` で対象4サービスだけ更新した。旧v0.7.1イメージは `rollback-before-v0.8.0-20261106` を付けて保持し、ローカルlatestを新リリースへ揃えた。registry latest、code-server、Kroki等は変更しない。
|
||||
|
||||
DBスキーマ変更はない。新イメージをネットワークなし・読み取り専用で起動するschema checkを切替前に両データ系統へ実施した。切戻し時は書込みを停止して現状も保全し、新CLIのWiki保存を停止する。旧版で個人設定を保存するとwiki_prefixが失われ得る。バックアップの自動復元は行っていない。
|
||||
|
||||
## 検証
|
||||
|
||||
- 対象4コンテナのsource revisionは `80d297dab40871b42ff2afb2ab6212661c465248` と一致。起動正常、再起動0回。appとExcalidrawはhealthy、app2の内部healthも成功。
|
||||
- 両系統の管理対象12コンポーネントはcurrent。legacy領域を含む全データ完全性の検査ではない。
|
||||
- 公開HTTPSでhealth・ログインは200。匿名のタスク・個人設定は303、preferences API・CardDAVは401。
|
||||
- 公開tasks.js・task-productivity.js・tasks.cssのSHA-256がv0.8.0と一致。
|
||||
- 初期ログのpanic、fatal、DB lock、job failed、scheduler claim failed、errorレベルの一致件数は0。
|
||||
- ホストCLIは公開ELFとバイト一致し、versionは0.3.0、from-mailの新オプションも確認した。既存資格情報・セッション・NeoMutt設定は変更していない。
|
||||
|
||||
認証済みのメール取り込み・個人設定操作は一時DBと合成データで検証し、本番にテストメールやタスクを追加していない。利用者の既定Pathは自動設定せず、保存先のACLを確認したうえで本人が選択する。反映後の空き容量は約33 GiB。
|
||||
@@ -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,45 @@
|
||||
# メールWikiのPath依存404の調査
|
||||
|
||||
## 状態と回避策
|
||||
|
||||
2026年11月6日、別インスタンスでNeoMuttから作成したWikiが一覧には見える一方、`/tasks` とその配下への直接アクセスで `{"detail":"Not Found"}` になる報告があった。同じオブジェクトに `/prj/awesome` 側のリンクを追加すると表示できた。原因は未確定で、修正済みとは扱わない。
|
||||
|
||||
回避策は表示できるWiki親prefixを既定値にし、既存オブジェクトには別Pathのリンクを使うこと。メールの再取り込み、オブジェクトの削除、既存Pathの一括移動は不要。Pathごとに権限が異なりうるため、新しいリンク先の公開範囲も確認する。
|
||||
|
||||
## アプリ内で確認した境界
|
||||
|
||||
タスク画面は `/v/plan/tasks`、APIは `/_/api/v1/extension/organizer.tasks/`。`/tasks` は予約ルートではなく、通常のWiki Pathとして解決する。末尾スラッシュは301で取り除く。
|
||||
|
||||
NeoMuttの `pipe_decode=no`・`pipe_split=yes` 相当の標準入力を使い、CLIプロセスから一時DBのフルHTTPハンドラへ取り込む試験を追加した。42パターンは、親prefix7種類、UTF-8/ISO-2022-JPの件名、ML連番/Message-ID/原文hashの組合せ。公開CLI v0.4.0でも一覧のdata-path、直接表示、末尾スラッシュ、言語指定を確認し、代表3パターンをChromiumで表示した。実メール・実アカウント設定は使用しない。
|
||||
|
||||
Python・Chromiumに依存しないGoテストでは、実際のAPIへ既定prefix `/tasks` を設定して取り込み、同一オブジェクトの `/tasks/...` と `/prj/awesome` の両方がHTMLの200を返すことを検証する。未認証閲覧のログイン誘導、一覧表示、旧CLI形式も対象。CIでPythonがない場合もこのテストは実行される。
|
||||
|
||||
親に文書がない場合は、仮想フォルダページ無効ならHTMLの404、有効ならchildren一覧の200となる。これは作成済み子ページまでJSONの404になる報告とは区別する。設定箇所は `/-/sys/config?panel=home` の「仮想フォルダページ」。設定は対象ドメイン単位で、調査のために自動変更しない。
|
||||
|
||||
## 機密情報を共有しない切り分け
|
||||
|
||||
以下は問題のインスタンス内で行う。実URL・メール本文・Cookie・Bearer token・ログ全文を外部へ共有しない。
|
||||
|
||||
1. 問題のPathへのGET時刻を控え、PagesWikiプロセスのアクセスログに同じ要求が到達するか確認する。到達しない場合はプロキシ、ブラウザ、キャッシュなどアプリより手前を調べる。ログ出力先の取り違えにも注意する。
|
||||
2. 公開HTTPSとPagesWikiの直接待受で応答を比較する。Domainの振り分けが変わらないよう、同じHostとPathを使う。まず資格情報なし・リダイレクトを追わないGETのstatusとContent-Typeを比較すれば、メール本文を取得せずに判断できる。認証後の比較が必要ならローカル環境内の安全な手順を使い、コマンド履歴に資格情報を残さない。
|
||||
3. 直接待受は正常でプロキシ経由だけ失敗する場合、`/tasks` に一致するlocation、正規表現location、rewrite、別upstream、Custom Locationsを確認する。実際の設定で確認できるまではプロキシが原因と断定しない。
|
||||
4. PagesWikiへの直接要求も失敗する場合は、稼働イメージrevision、HostによるDomain選択、Path別ACL、既存リンクの対象UUIDをローカルで確認する。同一オブジェクトの別名が読めても、元Pathの権限が同じとは限らない。
|
||||
|
||||
X-Request-IDやServerヘッダーだけで応答元を断定しない。プロキシによる付加・上書きがありうる。原因が判明するまで、推測による `/tasks` 専用ルート追加や権限の緩和はしない。
|
||||
|
||||
## 回帰テストと残件
|
||||
|
||||
```sh
|
||||
go test ./internal/server -run 'TestTaskWikiPrefixRouting|TestNeoMuttMailViewerFlow' -count=1
|
||||
# Chromiumがある開発環境のみ
|
||||
PAGESWIKI_BROWSER_TEST=1 go test ./internal/server -run '^TestNeoMuttMailViewerFlow$' -count=1
|
||||
# 配布ELFでも同じ一時プロファイルを用いて確認する場合
|
||||
PAGES_CLI_TEST_BINARY=/absolute/path/to/pages PAGESWIKI_BROWSER_TEST=1 go test ./internal/server -run '^TestNeoMuttMailViewerFlow$' -count=1
|
||||
```
|
||||
|
||||
- [x] `/tasks` 配下のメール作成から通常ビューアまでの合成HTTP試験。
|
||||
- [x] 同一オブジェクトの別名、親の仮想フォルダ設定、認証境界のGo回帰テスト。
|
||||
- [ ] 問題インスタンスで、直接待受とプロキシ経由の差分を確定する。
|
||||
- [ ] 特定された原因に修正を適用し、元の `/tasks` でも表示できることを確認する。
|
||||
|
||||
テストと調査記録の追加は障害修正リリースではない。既存の回避策とデータを維持する。
|
||||
@@ -0,0 +1,45 @@
|
||||
# ML連番・年月別メール保存先
|
||||
|
||||
PagesWiki v0.9.0とpages-cli v0.4.0は、メール本文を関連Wikiへ保存するとき、ML連番を優先してPathを決める。ML連番がないメールは年月で分割する。件名は表示に使い、日本語件名を識別用Pathには使わない。
|
||||
|
||||
| 優先順 | 判定 | 保存先 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 先頭のML連番あり(例: `[hogehoge 00123]`) | `親Path/hogehoge/123` |
|
||||
| 2 | ML連番なし、Message-IDあり | `親Path/YYYY/MM/UUID` |
|
||||
| 3 | どちらもなし | `親Path/YYYY/MM/原文SHA-256` |
|
||||
|
||||
UUIDは接続先・本人・Message-IDから従来どおり生成する。Message-ID自体はURLへ露出しない。年月はメールのDateヘッダーに記載されたタイムゾーンを尊重する。Date欠落・不正時は初回取り込み時のUTC年月を採用し、再送用outboxへ保存する。月をまたいで同一の保留メールを再入力しても保存先は変えない。
|
||||
|
||||
MLリスト名はASCII英数字で始まる100文字以内の英数字・ピリオド・ハイフン・アンダースコア。連番は最大20桁で先頭ゼロを除く。安全なML表記として認識できないものは年月方式にする。同じML連番の別メールは409で拒否し、タスクの部分作成や既存Wikiの上書きを行わない。
|
||||
|
||||
APIの追加フィールドは省略可能なwiki_suffixのみ。省略時の旧Path・receipt hashは維持する。新CLIの本文取り込みには新サーバーが必要。既存メールの一括移動は行わず、旧版で保持済みの再送要求はそのまま扱う。DBスキーマ変更はない。
|
||||
|
||||
## ソースと検証
|
||||
|
||||
- サーバー: `1a451023f09f483f5efff450dc2c951c925eb999`
|
||||
- CLI: `e22af6a0ecc2b001d6cc0d41901470f535fd8126`
|
||||
- 手元のGo全体テスト・go vet、CLI単体44件が成功。
|
||||
- サーバーCI run 43の全体テストが成功。合成メールを使うHTTP結合試験は手元で実行し、Wiki Pathと本文取得を検証した。
|
||||
- CLI main CI run 42、タグCI run 44が成功。公開添付5ファイルを匿名取得し、4生成物のSHA-256を検証した。
|
||||
- 公開ELFでUTF-8/ISO-2022-JP件名、ML連番Path、Dateのローカル年月、Message-ID由来UUID、Message-IDなし原文hashの各保存先を確認した。同梱ELF・ガイドと検証済みソースの一致も確認した。
|
||||
- [CLI v0.4.0](https://git.anya.jp/anya/pages-cli/releases/tag/v0.4.0)と[NeoMuttガイド](https://git.anya.jp/anya/pages-cli/src/tag/v0.4.0/docs/neomutt.md)を公開。
|
||||
|
||||
## リリースと本番反映
|
||||
|
||||
[サーバーCI run 43](https://git.anya.jp/anya/wikipages/actions/runs/43)の全工程成功後、[run 45](https://git.anya.jp/anya/wikipages/actions/runs/45)で同じSHAイメージをv0.9.0へ昇格した。公開タグの付け替え・リリース時の再ビルドは行っていない。本番取得時にイメージIDとソースrevisionの一致を検証した。
|
||||
|
||||
| イメージ | v0.9.0 manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:4a9b0b85330dac915e73e1aa5155f4691e46b2de945c76f1e14ae9735533a99b` |
|
||||
| pageswiki-adaptor-gateway | `sha256:4ff0dc5565537ae9d157df9515ac3b9df67090f1a69d8cc26f2bea5943885017` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:32a643778dff894f0ba679864e401d5605f80ad28bc4bd85bbcde453f2bc4127` |
|
||||
|
||||
2026-11-06 10:05:28 JSTに対象4サービスを停止開始、10:06:31に最終バックアップ照合完了、10:06:37に起動完了。停止から起動まで69秒。app・app2・adaptor gateway・Excalidraw viewerをregistry overlayでv0.9.0に更新し、他のサービスは変更していない。`.env.release`を更新し、ローカルlatestタグも稼働イメージへ揃えた。
|
||||
|
||||
保全先は `.deployment-backups/release-v0.9.0-20261106/`。旧構成と `cutover/data`・`cutover/data2` を保存し、停止後のchecksum付き同期・差分ゼロ・DB/WAL/SHMのバイト一致・稼働元と異なるinodeを確認した。変更のないファイルは前回の不変バックアップとだけlink-destで共有する。旧イメージは `rollback-before-v0.9.0-20261106` で保持し、既存バックアップは削除していない。
|
||||
|
||||
このホストの `/home/anya/.local/bin/pages` は公開ELF v0.4.0へ原子的に置換し、バイト一致とversionを検証した。旧CLIは保全先configの `pages-before-v0.4.0` に保持する。独立CLIの作業用リポジトリも公開コミット・タグへ同期した。資格情報・セッション・個人設定は変更していない。
|
||||
|
||||
対象4コンテナのrevision一致・起動・再起動0回、appとExcalidrawのhealthy、app2内部health、初期ログのエラーパターン0件を確認した。公開HTTPSのhealth・ログインは200、匿名のタスク画面・個人設定画面は303、preferences API・CardDAVは401。配信されたtasks.js・task-productivity.js・tasks.cssはリリースとSHA-256一致。両系統の管理対象12コンポーネントのschema checkは前後ともcurrent。ただしlegacy領域を含めた全データ完全性検査ではない。
|
||||
|
||||
実メール本文・外部取り込みカレンダーは検証に使用していない。本番には合成メールやタスクを追加せず、認証済み操作は一時DBで試験した。保全は内容を解釈しないファイルコピー。完了時の空き容量は約19 GiB。切戻し時もまず書込み停止と現状保全を行い、バックアップを自動復元しない。
|
||||
@@ -0,0 +1,40 @@
|
||||
# 日本語メール件名とWiki Pathの修正
|
||||
|
||||
PagesWiki v0.8.1とpages-cli v0.3.1はメールの表示名とPathの識別子を分離する。v0.8.0は件名全体をURLへ含め、CLIは300 UTF-8 bytesを超える件名を取り込み前に拒否していた。短い日本語Pathそのものは合成HTTP試験で取得可能だが、実メールの失敗入力は取得していないため、報告されたすべての失敗が同じ原因とは断定しない。
|
||||
|
||||
## 動作
|
||||
|
||||
- Wiki Pathの末尾は `mail-request_id`。接続先・本人・Message-IDから生成済みのUUIDを利用し、件名の文字コード・記号・長さに依存しない。Message-IDそのものをURLへ露出しない。Message-IDなしは原文SHA-256から識別する。
|
||||
- MIME Subjectを復号後、先頭の `[list 123]`・`[list:123]`・`[list#123]` を除去する。Re:/Fw:/Fwd:は維持し、その後の連番も除去する。連番を含まない `[重要]` や途中の括弧はそのまま。
|
||||
- 自動件名は300 UTF-8 bytes以内に文字境界で省略し「…」を付ける。元のSubjectはWiki本文へ保持する。明示的な `--title` は連番除去・省略をせず、上限を超えたら拒否する。
|
||||
- 既存ページのPath・タスク名を一括更新しない。既存receiptを使った同一要求の再送は元のページを返す。旧版で保存済みのメールを新しい本文・件名で再作成すると412となるため、通信失敗分は保持済み要求の `task retry` を使う。
|
||||
|
||||
個人設定の既定Wiki親Pathと保存先ACLは従来通り。APIフィールド・receipt hash形式・DBスキーマは変更しない。
|
||||
|
||||
## ソースと確認
|
||||
|
||||
サーバーの対象コミットは `3262f8800547e8ea343fe290153d4abc84ebd0d0`、CLIは `541c2bd069b5507281b0dde2810243447c098e71`。サーバーのCLI結合テスト用コピーも同じソースへ更新した。
|
||||
|
||||
CLI単体42件、全Goテスト、go vetを実施した。合成メールの日本語SubjectからWikiを作成し、関連メモAPIからPathを取得して本文をHTTP取得する結合テストが成功した。既存の日本語PathのHTTP取得・URLエンコードと再送時の非移動も検証した。
|
||||
|
||||
[CLI v0.3.1](https://git.anya.jp/anya/pages-cli/releases/tag/v0.3.1)はmain CI run 38、タグCI run 40で成功。公開添付5ファイルを匿名ダウンロードし、4生成物のSHA-256を照合した。公開ELFでUTF-8/ISO-2022-JPのSubject、ML連番除去、元件名保持、Message-IDによる同一識別子、通常のログイン・メール取り込み・連絡先スモークを確認した。
|
||||
|
||||
## リリースと本番反映
|
||||
|
||||
[サーバーCI run 39](https://git.anya.jp/anya/wikipages/actions/runs/39)の全工程が成功し、[run 41](https://git.anya.jp/anya/wikipages/actions/runs/41)で検証済みSHAイメージをv0.8.1へ昇格した。ソースrevisionとリリースイメージの一致を確認した。公開タグの付け替えは行っていない。
|
||||
|
||||
| イメージ | v0.8.1 manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:44aa267d010568e6dd83354839d976429dc979ed283888009457bffcc2d37119` |
|
||||
| pageswiki-adaptor-gateway | `sha256:5ccf30103cf4f01a49de0d80289736cbca9cde6f0e34661a39652b3468843533` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:33b44cc2c061c3b66ce8e1124b9e25c43584aec508669564c9f4a260e1c53454` |
|
||||
|
||||
2026-11-06 09:15:57 JSTに対象4サービスの停止を開始、09:17:03に最終バックアップ照合完了、09:17:09にv0.8.1起動完了。停止から起動まで72秒。`.env.release` を更新し、registry overlayの対象4サービスだけを `up --no-build --no-deps` した。code-serverやKroki等は変更していない。
|
||||
|
||||
`.deployment-backups/release-v0.8.1-20261106/` に構成と `cutover/data`・`cutover/data2` を保持する。停止後のchecksum付き同期と差分ゼロ、DB・WAL・SHMのバイト一致と稼働元と異なるinodeを確認した。変更のないファイルは前回の不変バックアップとのみlink-destで共有する。旧イメージは `rollback-before-v0.8.1-20261106` を付けて保持した。既存バックアップは削除しない。
|
||||
|
||||
このホストの `/home/anya/.local/bin/pages` を公開ELFのv0.3.1へ原子的に置換し、バイト一致・versionを確認した。旧CLIは保全先configの `pages-before-v0.3.1` に保持する。利用者の資格情報・セッション・個人設定は変更していない。独立CLIリポジトリも対象コミットとタグへ同期した。
|
||||
|
||||
両系統の管理対象12コンポーネントは切替前後ともcurrent。全コンテナのrevision一致、起動正常・再起動0回、appとExcalidrawのhealthy、app2内部health、初期ログのエラーパターン0件を確認した。公開HTTPSのhealth・ログインは200、匿名のタスク・個人設定は303、preferences API・CardDAVは401。配信されたtasks.js・task-productivity.js・tasks.cssはリリースとSHA-256一致。これはlegacy領域を含む全データ完全性検査ではない。
|
||||
|
||||
実メール本文・外部取り込みカレンダーは検証に使用していない。本番には合成メールやタスクを追加せず、認証済み操作は一時DBで確認した。保全は内容を解釈しないファイルコピー。完了時の空き容量は約26 GiB。切戻しは書込みを停止し現状も保全して実施し、バックアップを自動復元しない。
|
||||
@@ -1,6 +1,6 @@
|
||||
# メール本文のWiki保存
|
||||
|
||||
PagesWiki v0.8.0とpages-cli v0.3.0で、NeoMuttからのメール取り込みを関連Wikiページ付きタスク作成へ拡張する。サーバーを先に更新し、その後CLIを更新する。
|
||||
PagesWiki v0.8.0とpages-cli v0.3.0で、NeoMuttからのメール取り込みを関連Wikiページ付きタスク作成へ拡張した。2026-11-06に本番サーバーと、このホストのCLIへの反映を完了した。別の端末ではサーバーv0.8.0以降への接続を確認してからCLIを更新する。
|
||||
|
||||
## 利用方法と互換性
|
||||
|
||||
@@ -19,11 +19,24 @@ CLIの本文非送信は `--metadata-only`。旧 `--include-body` は既定動
|
||||
|
||||
## ソースと検証
|
||||
|
||||
独立CLIの対象コミットは `cde94ed`。サーバー内の `pages-cli/pages` と `test_productivity.py` はこのソースに明示更新した結合テスト用スナップショットで、配布元ではない。
|
||||
独立CLIの対象コミットは `cde94ed936ddfa1911809f3d1a824bd48a815223`、サーバーは `80d297dab40871b42ff2afb2ab6212661c465248`。サーバー内の `pages-cli/pages` と `test_productivity.py` はこのCLIソースに明示更新した結合テスト用スナップショットで、配布元ではない。
|
||||
|
||||
- CLI単体テスト41件、合成HTTP経由のログイン・メール取り込み・連絡先・ログアウト。
|
||||
- GoのメールWiki作成、既定Path・明示Path・プロジェクト配下、再送、権限拒否、衝突、本文上限、トランザクションのロールバック。
|
||||
- 独立CLIスナップショットとGo APIの結合テスト。作成したページがタスクのメモ操作から開けることを確認。
|
||||
- Chromiumのデスクトップ・スマホ幅で、現在のプロジェクト選択・フォームリセット・Wiki Path保存を確認。デスクトップでは候補の先頭ページにないプロジェクトも検証。
|
||||
- 全Goテスト、go vet、JS構文検査、リリースツール8件も成功。オーガナイザーの全ブラウザ回帰15ケース(小型スマホ・英語を含む)も成功。
|
||||
|
||||
配布・本番切替結果は確認後に追記する。外部取り込みカレンダーや実メール本文を検証のために読まない。
|
||||
## 公開結果
|
||||
|
||||
[CLIのmain CI run 34](https://git.anya.jp/anya/pages-cli/actions/runs/34)と[タグCI run 36](https://git.anya.jp/anya/pages-cli/actions/runs/36)が成功し、[pages-cli v0.3.0](https://git.anya.jp/anya/pages-cli/releases/tag/v0.3.0)を公開した。Linux/amd64 ELF、tar.gz、ソース、メタデータ、SHA256SUMSの5添付を匿名取得した。4生成物のチェックサムとsource_revision、同梱ガイド・設定例を照合し、配布ELFで合成HTTPスモークとTLS回帰6件を実施した。macOS/Windowsの配布状態は変更しない。
|
||||
|
||||
[サーバービルド run 35](https://git.anya.jp/anya/wikipages/actions/runs/35)は全工程成功。[リリース run 37](https://git.anya.jp/anya/wikipages/actions/runs/37)でSHAイメージを再ビルドせずv0.8.0へ昇格した。Gitタグは注釈付きで、公開済みタグを付け替えていない。
|
||||
|
||||
| イメージ | v0.8.0 manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:1817474559818898bd75c0bcc3e9ef7d0d02879604b46bd082668be557922482` |
|
||||
| pageswiki-adaptor-gateway | `sha256:264d545d8b8c8f9d1e48f79153f3a91d1d446f9e7cd3b067d8f3f7338d04053f` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:dbfcac6071db55f34ea52b7c00bdeb624ff2d71a9c8cdab5b5e522e8b745d38b` |
|
||||
|
||||
本番反映と切戻し用保全は[本番切替記録](../deployments/2026-11-06-v0.8.0.md)を参照。外部取り込みカレンダーや実メール本文は検証のために読んでいない。
|
||||
@@ -0,0 +1,39 @@
|
||||
# 壁紙連動配色のリリース
|
||||
|
||||
PagesWiki v0.10.0は、トップ画面の壁紙からアクセントとグラス面の配色を生成する機能を追加した。2026-11-07に本番反映済み。対象ソースは `0964fdc5b72a1ec24709d87172aaccb985e41c78`。公開APIの非互換変更とDBスキーマ変更はない。保留中のメール保存先 `/tasks` の調査変更は含めない。
|
||||
|
||||
## 操作と適用範囲
|
||||
|
||||
トップ画面右下の歯車、または `/-/sys/config?panel=home` から、色連動のオフ・アクセントのみ・背景も連動、反映量、明暗判定を選ぶ。既定は背景も連動・35%・現在の明暗を維持。グラス透明度は独立した設定を維持する。管理権限が必要なドメイン共通設定であり、ダイアログでの変更は保存前にプレビューできる。
|
||||
|
||||
通常Viewer・Editor・設定画面・ログイン画面には動的配色を適用しない。警告色などの意味を持つ色は変更しない。画像の追加取得はせず、表示済みの画像を64×64に縮小して描画後に解析する。色の抽出結果だけをDomain UUIDと画像SHA256単位でsessionStorageへ保存する。詳しくは[壁紙連動配色の設計](../../design/navigation-home-sidebar.md#実装済みの壁紙連動配色)を参照。
|
||||
|
||||
## 検証
|
||||
|
||||
- 手元のGo全体テスト、go vet、配色計算とリリースツールのJavaScriptテストが成功。
|
||||
- 一時DBと合成画像を用いたChromiumテストで、デスクトップ・390px幅の保存、キャンセル、テーマ切替、追加取得なし、キャッシュ再利用・破損時再生成、画像エラー時の復元を確認。
|
||||
- 非管理者からの設定変更は403。トップ画面以外に配色用スクリプトが混入しないことを検証。
|
||||
- スマホ幅で検索+ブックマーク画面の横はみ出しを修正。
|
||||
- [CI run 46](https://git.anya.jp/anya/wikipages/actions/runs/46)の初回job 60は既存の `TestAssetReferencesAreDomainScopedAndIncludeHistoricalHeads` の一時SQLite接続初期化で5秒タイムアウト。検査本体に入る前の失敗で、今回その処理の変更はない。手元で該当テストを10回連続成功後、同一コミットのjob 61を再実行し、全体テストが成功(server 170.870秒、store 84.240秒)。テスト省略やタイムアウト変更は行っていない。
|
||||
|
||||
CIでSQLite初期化のタイムアウトが再発する場合は、runnerのI/O負荷とパッケージ間の並列実行を調査する。本番の接続タイムアウトをこの事象だけで緩和しない。
|
||||
|
||||
## リリースと本番反映
|
||||
|
||||
[CI run 46](https://git.anya.jp/anya/wikipages/actions/runs/46)の再実行でテスト・3イメージのビルド・公開・後処理が成功。そのコミットに注釈付きタグ `v0.10.0` を付けてpushし、[release run 47](https://git.anya.jp/anya/wikipages/actions/runs/47)で再ビルドせずに昇格した。本番で取得したイメージのsource revisionとmanifest digestはリリース結果と一致する。
|
||||
|
||||
| イメージ | v0.10.0 manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:d43c5827e92ab8eef28290edd5d405f84d2c3480315d552cf5afe535bcf8a02d` |
|
||||
| pageswiki-adaptor-gateway | `sha256:6882e44ec667fd4fcaecf7a21a25dfb3432a1aa8c6e54c1d0e9fabe3dd448e50` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:638e02520ce06c2d8267dc8514a4d6544ea8bf70f2d24a368193dad5e6aaa38d` |
|
||||
|
||||
23:12:21 JSTに対象4サービスを停止開始、23:13:31に最終バックアップ照合完了、23:13:37に起動完了。停止から起動まで76秒。`.env.release` をv0.10.0へ変更し、registry overlayの `up --no-build --no-deps` でapp・app2・adaptor gateway・Excalidraw viewerを更新した。ローカルlatestタグも同じイメージに揃えた。レジストリlatest、独立CLI、code-server、Kroki等は変更していない。
|
||||
|
||||
保全先は `.deployment-backups/release-v0.10.0-20261107/`。親ディレクトリ0700、構成コピー0600。旧 `.env`・`.env.release`・Composeと停止時点の `cutover/data`・`cutover/data2` を保持する。前回の不変バックアップとのみlink-destで共有し、checksum付き同期後の差分ゼロ、DB・WAL・SHM等のバイト一致と稼働元とのinode相違を確認した。旧v0.9.0イメージは `rollback-before-v0.10.0-20261107` タグで保持。旧バックアップや旧イメージは削除していない。完了時の空き容量は約12GiB。
|
||||
|
||||
切替後、4コンテナのsource revision一致・running・再起動0回、appとExcalidrawのhealthy、app2内部healthを確認した。起動直後のログでpanic・fatal・database locked・job failed等の検索パターンは0件。公開HTTPSのhealth・ログインは200、匿名のタスク画面・ホーム設定画面は303、preferences API・CardDAVは401。配信されたhome-palette.js、home-palette-core.js、home-appearance.js、home.css、config.cssはリリースソースとSHA256一致。両DBの管理対象12コンポーネントのschema checkは前後ともcurrentで、全データ完全性検査ではない。
|
||||
|
||||
認証後の設定操作は一時DBで試験し、本番の設定値やユーザデータを検証目的で変更していない。外部取り込みカレンダーと実メール本文を取得・表示していない。バックアップは内容を解釈しないファイルコピーとバイト照合のみ。
|
||||
|
||||
切戻しでは最初に書込みを停止し、切替後のデータも別途保全する。今回の新設定は旧版では利用されず、DBスキーマの差分はないが、稼働中データへバックアップを自動で上書きしない。旧構成は保全先configにある。
|
||||
@@ -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` |
|
||||
@@ -0,0 +1,48 @@
|
||||
# PagesWiki v0.15.0とpages-cli v0.5.0
|
||||
|
||||
ブラウザアップロード、信頼端末ログイン、RSSの配信時刻、CSV投影とタスクの関連ページ導線を追加します。Geckoの整備コードと配布イメージも含みますが、専用relayの本番有効化は行いません。
|
||||
|
||||
## 変更内容
|
||||
|
||||
- `/v/browser` のファイルドロップと右下のキュー。逐次送信、待機取消、折りたたみ、同名保護、一覧だけの更新。ページを閉じた後の再開とフォルダ再帰アップロードは未対応。
|
||||
- ログイン時の信頼端末選択。管理者指定の最大30日・絶対期限で、既存セッションは延長しません。パスワード/TOTP、OIDC、LDAP、マジックリンクに選択を引き継ぎます。
|
||||
- CLIの `login --remember` と期限切れ再ログイン時の作業パス/保留下書き保持。
|
||||
- RSS一覧の配信時刻とDomainタイムゾーン。本文の日付表示も同じタイムゾーンへ統一。
|
||||
- 保存済みタスクの関連Wikiページを開くボタン。
|
||||
- 認証済み閲覧者の権限を確認する有界CSV macro。`{{csv:/data/items.csv range=A1:H200 header=true}}` と同じObjectのRevision固定に対応。CSV編集・匿名投影・外部URL取得は含みません。
|
||||
- Geckoの日本語ページ内検索、起動上限・失敗時のiframe破棄、固定ソース/notice付き配布物検査。Safari実機、IME・コピー、運用firewallと低メモリ受入は残件。
|
||||
|
||||
## リリースと検証
|
||||
|
||||
本体commitは `b90aef79d03c21332cd49a47aba015a30f6de1a0`。Gitea [build 76](https://git.anya.jp/anya/pages/actions/runs/76)、[release 79](https://git.anya.jp/anya/pages/actions/runs/79) が成功し、SHAイメージを再ビルドせず `v0.15.0` へ昇格しました。
|
||||
|
||||
CLI commitは `bee03094f3bf2fa0c2dab80313d2f4bd15452c3d`。[v0.5.0](https://git.anya.jp/anya/pages-cli/releases/tag/v0.5.0) のCIと55単体テストが成功。公開した4ファイルのSHA256SUMS照合、Pythonソース一致、取得したLinux ELFのバージョン・ログイン・タスク/メール取り込み・下書き回復等の合成スモークテストを確認しました。未検証のmacOS/Windowsバイナリは追加していません。
|
||||
|
||||
本体は `go test ./...`、`go vet ./...`、リリースツールと壁紙テスト、Gecko配布ツールのテストが成功。Chromiumで認証・タスク・RSS・Gecko・アップロードの合成試験を実施しました。アップロードキューは1280px/390px幅、逐次送信、同名保護、取消、一覧更新を検証しています。
|
||||
|
||||
## DBと復旧
|
||||
|
||||
`cli-auth` v1→v2で `auth_cli_requests.remember` を既定0・0/1制約付きで追加します。他の管理対象componentのversionは変わりません。両インスタンスの独立コピーで、ネットワークを遮断しworkerを停止して新イメージを起動し、schema checkとSQLite integrity_checkが成功しました。実外部カレンダーやメール内容は検証に使用していません。
|
||||
|
||||
保全先は `.deployment-backups/release-v0.15.0-20261108/`。`config/` に旧設定、`cutover/data` と `cutover/data2` に停止時点のデータを保存します。旧3イメージの `rollback-before-v0.15.0-20261108` タグと既存バックアップを保持します。
|
||||
|
||||
新しいmigration履歴を旧版が受け付けるとは限らないため、旧イメージだけのダウングレードは行いません。切戻しが必要ならwriterを止め、切替後データも保全し、停止時バックアップとの変更差分を扱ってからDB・ファイル・設定・イメージを同じ復旧点へ戻します。運用開始後の書き込みを黙って破棄しません。
|
||||
|
||||
## 本番反映
|
||||
|
||||
2026-11-08 20:41:33 JSTに配備後確認を完了しました。20:40:05に停止し、20:41:10に停止時バックアップを検証、20:41:16に新版の起動とhealthを確認しています。
|
||||
|
||||
- app・app2・adaptor-gateway・excalidraw-viewerはすべて対象commitと一致し、running・再起動回数0。
|
||||
- 両DBのquick_checkはok、管理対象13componentはcurrent。legacy領域全体の検証を意味するものではありません。
|
||||
- 外部HTTPSのhealth・ログイン画面200。匿名タスク/dashboard/RSS画面303、タスクAPI・DELETE・captureは401。
|
||||
- tasks、RSS、Gecko、アップロードキュー、信頼端末UIの配信JS/CSSはリリースcommitとSHA-256一致。公開ログイン画面の信頼端末選択も確認。
|
||||
- 起動直後のfatal/panic、DB/schema failure、event job failureは両アプリとも0件。
|
||||
- `.env.release` は `PAGESWIKI_IMAGE_TAG=v0.15.0`。Gecko relayコンテナは起動せず、通常3イメージ・4サービスだけを更新。
|
||||
|
||||
配備イメージのmanifest digest:
|
||||
|
||||
| イメージ(`git.anya.jp/anya/`) | digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:43c398f2c294c7802987aaae1bfdf27b3d0c7ea24fa73df912ac03ea312366b0` |
|
||||
| pageswiki-adaptor-gateway | `sha256:aebc515c3b3e36b58b03ecab1646e6d95b0dd21074a1a863ca5806cb7fde4df1` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:4a80354aa4567abe52ff17e32a6f224e85d8cd2e0f1a466e5690b4b353d901cc` |
|
||||
@@ -0,0 +1,39 @@
|
||||
# PagesWiki v0.16.0
|
||||
|
||||
2026-11-09 05:58:14 JSTに本番の配備後確認を完了しました。CSVの表編集・複数セル貼り付けと、Reveal.jsのビューア・編集プレビューを追加します。
|
||||
|
||||
## 変更と利用方法
|
||||
|
||||
- 既存CSVを `/e/-/{path}` で表編集。行列操作、Undo/Redo、タブ区切りの複数セル貼り付け、既存の下書き・履歴・競合確認に対応します。未変更セルの引用符・BOM・改行を保持し、上限超過時は部分反映しません。
|
||||
- HTMLページのスライドアイコン、または `/v/slides/{path}` でReveal.js表示。エディタのスライドアイコンで未保存HTML/Markdownをプレビューします。Markdownの空行で囲んだ `---`、HTML直下の `<hr>` で区切ります。
|
||||
- Reveal.js 6.0.2をMITライセンスとともにローカル同梱。sandbox、Path認可、入力上限、テーマ追従、スマホの全幅プレビューに対応。拡張設定の `viewer.slides` でドメイン単位に停止できます。
|
||||
|
||||
CSVは全体256 KiB、表200行・32列・セル16 KiB以内。スライドは256 KiB・100枚以内です。縦スライド・発表者ノート・専用印刷・外部画像承認連携は含みません。通常HTMLの自動表示をスライドへ置き換えません。
|
||||
|
||||
## リリースと検証
|
||||
|
||||
対象commitは `02fb77f72b45c342c6b458d733f840b38cc3ae56`。[build 80](https://git.anya.jp/anya/pages/actions/runs/80)と[release 81](https://git.anya.jp/anya/pages/actions/runs/81)が成功し、同じSHAのイメージを再ビルドせずv0.16.0へ昇格しました。
|
||||
|
||||
開発環境で全Goテスト・go vet・JS単体テスト、1280px/390pxのChromium試験を実施しました。CSV保存・競合・履歴・貼り付け拒否、スライドのライブ更新・通常プレビュー復帰・左右キー・履歴非変更・隔離を確認しています。
|
||||
|
||||
本番ではapp・app2・adaptor-gateway・excalidraw-viewerのrevision一致、running、再起動0を確認。両アプリのhealth、外部HTTPSのhealth/login 200、匿名タスク・スライドの303、タスクAPIの401を確認しました。CSV/Reveal.js関連の11配信ファイルはリリースcommitとSHA-256一致。両DBのquick_checkはok、管理対象13componentはcurrentで版変更なしです。legacy領域全体の移行検証を意味しません。起動直後のpanic・fatal・DB/schema失敗・event job失敗に該当するログはありませんでした。
|
||||
|
||||
本番の実コンテンツを編集する試験、外部カレンダー・メール内容の取得は行っていません。pages-cliは変更せず、Gecko relayも起動していません。
|
||||
|
||||
## 保全と切替
|
||||
|
||||
DBスキーマ・ストレージ形式の変更はありません。保全先は `.deployment-backups/release-v0.16.0-20261109/`。`config/` に旧設定、`cutover/data` と `cutover/data2` に停止時点のファイルを保持しています。DBだけは容量を考慮して `pages.db.gz` とし、gzip検査と展開内容のバイト一致を確認しました。他のファイルは停止時checksum比較で一致しています。復旧用に展開する場合は、稼働DBを上書きせず別の停止済み復旧領域に `pages.db` として展開します。
|
||||
|
||||
初回は圧縮で変わったバックアップ先フォルダmtimeを厳密差分検査が検出し、新版起動前にv0.15.0へ自動復帰しました。圧縮後にフォルダmtimeを元に合わせる修正を行い、内容の検証は省略せず再実行しています。再試行は05:54:59 JSTに停止、05:57:28にバックアップ検証完了、05:57:34に新版health確認完了です。
|
||||
|
||||
旧イメージは `rollback-before-v0.16.0-20261109` タグで保持し、過去のバックアップも削除していません。今回のUI機能を切り戻す場合はwriterを止め、現データを保持してv0.15.0のイメージへ戻せます。バックアップ時点へのデータ復旧を選ぶ場合は、切替後の書き込みを別途保全して差分を扱い、黙って破棄しません。
|
||||
|
||||
`.env.release` は `PAGESWIKI_IMAGE_TAG=v0.16.0`。配備後の空き容量は約8.1 GiBのため、次の大きなビルド・バックアップの前に保持世代と不要キャッシュの整理が必要です。
|
||||
|
||||
## 配備イメージ
|
||||
|
||||
- `pageswiki-app`: `sha256:428f4c38297e7d2b529af13b32d45e6a9b40f58915fbd170148a0ad07958a034`
|
||||
- `pageswiki-adaptor-gateway`: `sha256:cdf99b4f02a9abade8862caea1c23cfe775f229118c5c1aabf2584d84a02be50`
|
||||
- `pageswiki-excalidraw-viewer`: `sha256:854fa1d0bb931642e81af394ab4631b47397a94264eb1b34d4f8ff0ca5435e25`
|
||||
|
||||
レジストリのprefixは `git.anya.jp/anya/`、共通タグは `v0.16.0` です。
|
||||
@@ -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,8 +21,11 @@ type Manifest struct {
|
||||
|
||||
func Catalog() []Manifest {
|
||||
return []Manifest{
|
||||
{ID: "viewer.slides", APIVersion: 1, Version: "0.1.0", Kind: "viewer", Scope: "domain", NameKey: "slides.title", DescriptionKey: "slides.help", Capabilities: []string{"path.read"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "client-compute+bounded-read"},
|
||||
{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.12.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"},
|
||||
{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"},
|
||||
{ID: "organizer.calendar", APIVersion: 1, Version: "0.2.0", Kind: "calendar", Scope: "domain", NameKey: "calendar.title", DescriptionKey: "calendar.help", Capabilities: []string{"calendar.read", "calendar.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||
{ID: "content.diary", APIVersion: 1, Version: "0.1.0", Kind: "diary", Scope: "domain", NameKey: "periodical.diary", DescriptionKey: "periodical.diary_help", Capabilities: []string{"path.read", "path.write", "domain.extensions.manage"}, Events: []string{"periodical.registered", "periodical.removed"}, SettingsPanel: "diary", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||
{ID: "content.blog", APIVersion: 1, Version: "0.1.0", Kind: "blog", Scope: "domain", NameKey: "periodical.blog", DescriptionKey: "periodical.blog_help", Capabilities: []string{"path.read", "path.write", "domain.extensions.manage"}, Events: []string{"periodical.registered", "periodical.removed"}, SettingsPanel: "blog", Builtin: true, Enabled: true, ResourceClass: "foreground+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()
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package grammaratur
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
@@ -12,17 +14,93 @@ import (
|
||||
|
||||
// HTMLToMarkdownAuthoring keeps source HTML when conversion loses structure,
|
||||
// attributes, comments or text. This is not a sanitization boundary.
|
||||
var nestedListGap = regexp.MustCompile(`\n[\t ]*\n([\t ]+(?:[-+*]|[0-9]+\.) )`)
|
||||
|
||||
func authoringMarkdown(source string) (string, error) {
|
||||
md, err := HTMLToMarkdown(source)
|
||||
if err != nil {
|
||||
return md, err
|
||||
}
|
||||
// The converter inserts a loose-list gap before nested lists. Only accept
|
||||
// tightening when the resulting DOM matches; code and real paragraphs stay protected.
|
||||
tight := nestedListGap.ReplaceAllString(md, "\n$1")
|
||||
if tight != md && htmlStructure(source) == htmlStructure(MarkdownToHTML(tight)) {
|
||||
return tight, nil
|
||||
}
|
||||
return md, nil
|
||||
}
|
||||
|
||||
func HTMLToMarkdownAuthoring(source string) (string, error) {
|
||||
converted, err := HTMLToMarkdown(source)
|
||||
converted, err := authoringMarkdown(source)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if htmlStructure(source) != htmlStructure(MarkdownToHTML(converted)) {
|
||||
return rawHTMLBlock(source), nil
|
||||
// Protect only the blocks which cannot round-trip. One custom component
|
||||
// must not turn the headings, lists and paragraphs around it into HTML.
|
||||
blocks, ok := authoringBlocks(source)
|
||||
if !ok {
|
||||
return rawHTMLBlock(source), nil
|
||||
}
|
||||
var parts []string
|
||||
for _, raw := range blocks {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
continue
|
||||
}
|
||||
md, e := authoringMarkdown(raw)
|
||||
if e != nil || htmlStructure(raw) != htmlStructure(MarkdownToHTML(md)) {
|
||||
md = rawHTMLBlock(raw)
|
||||
}
|
||||
parts = append(parts, md)
|
||||
}
|
||||
mixed := strings.Join(parts, "\n\n")
|
||||
// Includes head content, comments outside body and fragment edge cases.
|
||||
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(mixed)) {
|
||||
return rawHTMLBlock(source), nil
|
||||
}
|
||||
return mixed, nil
|
||||
}
|
||||
return converted, nil
|
||||
}
|
||||
|
||||
// Token boundaries retain the exact source of protected components (including
|
||||
// attribute quoting and void-element syntax). Never serialize the parsed DOM
|
||||
// back over their source. Malformed/implicit nesting uses whole-document fallback.
|
||||
func authoringBlocks(source string) ([]string, bool) {
|
||||
z := html.NewTokenizer(strings.NewReader(source))
|
||||
var stack, blocks []string
|
||||
start, offset := 0, 0
|
||||
for {
|
||||
kind := z.Next()
|
||||
if kind == html.ErrorToken {
|
||||
return blocks, z.Err() == io.EOF && len(stack) == 0 && offset == len(source)
|
||||
}
|
||||
offset += len(z.Raw())
|
||||
switch kind {
|
||||
case html.StartTagToken:
|
||||
name, _ := z.TagName()
|
||||
switch string(name) {
|
||||
case "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr":
|
||||
default:
|
||||
stack = append(stack, string(name))
|
||||
}
|
||||
case html.EndTagToken:
|
||||
name, _ := z.TagName()
|
||||
if len(stack) == 0 || stack[len(stack)-1] != string(name) {
|
||||
return nil, false
|
||||
}
|
||||
stack = stack[:len(stack)-1]
|
||||
}
|
||||
if len(stack) == 0 {
|
||||
blocks = append(blocks, source[start:offset])
|
||||
start = offset
|
||||
if len(blocks) > 1024 {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// {=html} is an explicit authoring fence, not an ordinary code sample. The
|
||||
// closing delimiter is longer than any run in the source, so arbitrary HTML
|
||||
// (including Markdown examples) cannot accidentally terminate it.
|
||||
@@ -110,6 +188,28 @@ func htmlStructure(source string) string {
|
||||
literal = literal || n.Data == "pre" || n.Data == "code" || n.Data == "script" || n.Data == "style"
|
||||
data := n.Data
|
||||
if n.Type == html.TextNode && !literal {
|
||||
// Formatting whitespace beside a nested block is not an inline word
|
||||
// separator. Keep all whitespace between inline siblings significant.
|
||||
if n.Parent != nil && n.Parent.Data == "li" {
|
||||
isList := func(x *html.Node) bool {
|
||||
return x != nil && x.Type == html.ElementNode && (x.Data == "ul" || x.Data == "ol")
|
||||
}
|
||||
if isList(n.NextSibling) {
|
||||
data = strings.TrimRight(data, " \t\r\n")
|
||||
}
|
||||
if isList(n.PrevSibling) {
|
||||
data = strings.TrimLeft(data, " \t\r\n")
|
||||
}
|
||||
if data == "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(data) == "" && n.Parent != nil {
|
||||
switch n.Parent.Data {
|
||||
case "ul", "ol", "table", "thead", "tbody", "tfoot", "tr":
|
||||
return
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(data) == "" && (n.Parent == nil || n.Parent.Data == "body" || n.Parent.Data == "html") {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -65,3 +65,19 @@ func TestAuthoringWhitespaceComparisonIsConservative(t *testing.T) {
|
||||
t.Fatal("word boundaries ignored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthoringPartialMarkdownRecovery(t *testing.T) {
|
||||
source := `<h1>Title</h1><p>Some <strong>bold</strong> text.</p><figure data-x="keep"><img src="/image"><figcaption>Caption</figcaption></figure><ul><li>First</li><li>Second</li></ul>`
|
||||
md, err := HTMLToMarkdownAuthoring(source)
|
||||
if err != nil || !strings.HasPrefix(md, "# Title") || !strings.Contains(md, "**bold**") || strings.Count(md, "{=html}") != 1 || !strings.Contains(md, "- First") {
|
||||
t.Fatalf("markdown not recovered: %q %v", md, err)
|
||||
}
|
||||
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(md)) {
|
||||
t.Fatal("HTML lost during partial conversion")
|
||||
}
|
||||
protected := `<figure data-x='original'><img src=/image><figcaption>Caption</figcaption></figure>`
|
||||
md, err = HTMLToMarkdownAuthoring("<h1>Title</h1>" + protected + "<p>Tail</p>")
|
||||
if err != nil || !strings.Contains(MarkdownAuthoringHTML(md), protected) || !strings.HasPrefix(md, "# Title") {
|
||||
t.Fatalf("protected bytes changed: %q %v", md, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package grammaratur
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAuthoringNestedLists(t *testing.T) {
|
||||
for _, source := range []string{
|
||||
"<ul><li>Parent<ul><li>Child</li></ul></li></ul>",
|
||||
"<ul>\n<li>Parent\n<ul>\n<li>Child</li>\n</ul>\n</li>\n</ul>",
|
||||
"<ul><li>Parent<ul><li>Child<ul><li>Grandchild</li></ul></li></ul></li><li>Sibling</li></ul>",
|
||||
"<ol><li>Parent<ul><li>Child</li></ul></li></ol>",
|
||||
"<ul><li><strong>Parent</strong><ul><li>Child</li></ul></li></ul>",
|
||||
} {
|
||||
md, err := HTMLToMarkdownAuthoring(source)
|
||||
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(md)) {
|
||||
t.Errorf("list structure changed: %q", md)
|
||||
}
|
||||
if err != nil || strings.Contains(md, "{=html}") {
|
||||
plain, _ := HTMLToMarkdown(source)
|
||||
t.Errorf("source=%q md=%q plain=%q rendered=%q err=%v", source, md, plain, MarkdownToHTML(plain), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthoringNestedListPreservesAttributes(t *testing.T) {
|
||||
source := `<ul><li data-custom="keep">Parent<ul><li>Child</li></ul></li></ul>`
|
||||
md, err := HTMLToMarkdownAuthoring(source)
|
||||
if err != nil || MarkdownAuthoringHTML(md) != source {
|
||||
t.Fatalf("protected list changed: %q %v", md, err)
|
||||
}
|
||||
}
|
||||
@@ -227,4 +227,9 @@ func textMediaType(descriptor Descriptor) bool {
|
||||
}
|
||||
|
||||
// Catalog returns a copy; callers cannot reorder or disable the shared registry.
|
||||
func Catalog() []Adapter { return append([]Adapter(nil), projectionAdapters...) }
|
||||
func Catalog() []Adapter {
|
||||
items := append([]Adapter(nil), projectionAdapters...)
|
||||
// Explicitly selected projection. It must not replace normal HTML/text
|
||||
// viewing in the automatic MIME classifier.
|
||||
return append(items, Adapter{ID: "reveal", Kind: "slides", Delivery: DeliveryRawFrame, Match: func(Descriptor) bool { return false }})
|
||||
}
|
||||
@@ -47,7 +47,7 @@ func TestAdapterCatalogIsCopyAndConcurrent(t *testing.T) {
|
||||
for _, a := range catalog {
|
||||
ids = append(ids, a.ID)
|
||||
}
|
||||
if strings.Join(ids, ",") != "html,excalidraw,csv,archive,debian-package,eml,pe,json,text,image,audio,video,pdf,download" {
|
||||
if strings.Join(ids, ",") != "html,excalidraw,csv,archive,debian-package,eml,pe,json,text,image,audio,video,pdf,download,reveal" {
|
||||
t.Fatal("catalog order changed", ids)
|
||||
}
|
||||
catalog[0].ID = "corrupt"
|
||||
|
||||
@@ -185,6 +185,9 @@ func (s *Server) adapterActionsForPath(r *http.Request, semanticPath string) ([]
|
||||
{ID: "download", Name: "download", Mode: "viewer", Builtin: true,
|
||||
OpenURL: rawProjectionURL("rev:" + revision.UUID)},
|
||||
}
|
||||
if (mediaType == "text/html" || mediaType == "text/markdown" || mediaType == "text/x-markdown") && s.systemExtensionEnabled(domainUUID, "viewer.slides") {
|
||||
actions = append(actions, adapterAction{ID: "reveal", Name: "Reveal.js", Mode: "viewer", Builtin: true, OpenURL: "/v/slides" + semanticPath})
|
||||
}
|
||||
if selected.NeedsText || selected.ID == "html" || selected.ID == "excalidraw" {
|
||||
actions = append(actions, adapterAction{
|
||||
ID: "editor", Name: "Pages Wiki Editor", Mode: "editor",
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -9,12 +9,14 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"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 +59,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 +71,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 +86,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 +214,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 +226,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 +253,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 +291,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,16 +315,11 @@ 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
|
||||
configured, opacity := s.homeWallpaperConfig(domainUUID)
|
||||
data["HomeWallpaperOpacity"] = strconv.FormatFloat(float64(opacity)/100, 'f', 2, 64)
|
||||
if configured != "" {
|
||||
// Only the administrator-selected login wallpaper is exposed; the
|
||||
// request cannot choose an arbitrary document address.
|
||||
data["HomeWallpaperURL"] = "/_/auth/wallpaper"
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
}
|
||||
// Login has no wallpaper: private home images must not become public.
|
||||
s.renderWithContext(w, r, "auth.gohtml", data)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,15 @@ func TestCalendarUpcomingDefaultsAndBounds(t *testing.T) {
|
||||
t.Fatal("tomorrow event in today's widget", event.Start)
|
||||
}
|
||||
}
|
||||
w = calendarRequest(s, token, "GET", calendarAPI+"upcoming?period=day&date="+end.Format("2006-01-02"), "", "")
|
||||
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
for _, event := range result.Events {
|
||||
if !event.Start.Before(end.AddDate(0, 0, 1)) || !event.End.After(end) {
|
||||
t.Fatal("event outside tomorrow", event.Start, event.End)
|
||||
}
|
||||
}
|
||||
if w = calendarRequest(s, "", "GET", calendarAPI+"upcoming", "", ""); w.Code != 403 {
|
||||
t.Fatal("anonymous access", w.Code)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -290,6 +290,11 @@ func (s *Server) handleConfig(
|
||||
}
|
||||
|
||||
case "home":
|
||||
palette, paletteErr := s.parseHomePalette(domainUUID, r.Form)
|
||||
if paletteErr != nil {
|
||||
http.Error(w, paletteErr.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if controlled, e := s.store.DomainEntryControlled(domainUUID); e != nil || controlled {
|
||||
http.Error(w, translate(s.getLocale(domainUUID), "periodical.controlled"), http.StatusConflict)
|
||||
return
|
||||
@@ -344,6 +349,10 @@ func (s *Server) handleConfig(
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if err = s.saveHomePalette(domainUUID, palette); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if err = s.store.SetConfigInDomain(domainUUID, "home_wallpaper_opacity", strconv.Itoa(wallpaperOpacity)); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -463,6 +472,11 @@ func (s *Server) handleConfig(
|
||||
}
|
||||
|
||||
case "home-appearance":
|
||||
palette, paletteErr := s.parseHomePalette(domainUUID, r.Form)
|
||||
if paletteErr != nil {
|
||||
http.Error(w, paletteErr.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if controlled, e := s.store.DomainEntryControlled(domainUUID); e != nil || controlled {
|
||||
http.Error(w, translate(s.getLocale(domainUUID), "periodical.controlled"), http.StatusConflict)
|
||||
return
|
||||
@@ -472,6 +486,10 @@ func (s *Server) handleConfig(
|
||||
http.Error(w, parseErr.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err = s.saveHomePalette(domainUUID, palette); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if err = s.store.SetConfigInDomain(domainUUID, "home_glass_transparency", strconv.Itoa(glassTransparency)); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -1060,48 +1078,50 @@ func (s *Server) handleConfig(
|
||||
s.getSystemNavItems(s.domainUUIDForRequest(r)),
|
||||
NavContext{},
|
||||
),
|
||||
"HomePath": homePath,
|
||||
"HomeWallpaperPath": homeWallpaperPath,
|
||||
"HomeWallpaperOpacity": homeWallpaperOpacity,
|
||||
"HomeGlassTransparency": s.homeGlassTransparency(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,150 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"html"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const csvEditorFixtureBody = "\ufeff\"name\",description\r\n日本語,\"a,b\r\nnext\"\r\n"
|
||||
|
||||
func TestCSVEditorRevisionAndBounds(t *testing.T) {
|
||||
s, token, domain, _ := editorFixture(t)
|
||||
object, err := s.store.CreatePageAtPathInDomain(domain, "/table.csv")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := s.store.SaveRevisionContent(object, []byte(csvEditorFixtureBody), "", "und", "text/csv; charset=utf-8", "table.csv")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, query := range []string{"", "?edittype=markdown", "?lang=und"} {
|
||||
w := configRequest(s, token, "GET", "/e/-/table.csv"+query, nil)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `data-csv="true"`) || !strings.Contains(w.Body.String(), `value="code"`) || strings.Contains(w.Body.String(), `data-editor-action="markdown"`) {
|
||||
t.Fatalf("editor %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
head, _ := s.store.GetRevisionForExactLanguage(object, "und")
|
||||
if head.UUID != first.UUID {
|
||||
t.Fatal("GET changed revision")
|
||||
}
|
||||
save := func(auth, base, body string) int {
|
||||
data, _ := json.Marshal(map[string]any{"object_uuid": object, "body": body, "lang": "und", "content_type": "text/csv; charset=utf-8", "filename": "table.csv", "base_revision_uuid": base})
|
||||
r := httptest.NewRequest("POST", "http://localhost/_/api/v1/revisions/save", bytes.NewReader(data))
|
||||
r.Header.Set("Authorization", "Bearer "+auth)
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
return w.Code
|
||||
}
|
||||
changed := strings.Replace(csvEditorFixtureBody, "日本語", "更新", 1)
|
||||
if code := save(token, first.UUID, changed); code != 200 {
|
||||
t.Fatal("save", code)
|
||||
}
|
||||
if code := save(token, first.UUID, "stale"); code != 409 {
|
||||
t.Fatal("stale save", code)
|
||||
}
|
||||
head, _ = s.store.GetRevisionForExactLanguage(object, "und")
|
||||
if head.Body != changed || head.ContentType != "text/csv; charset=utf-8" || head.Filename != "table.csv" {
|
||||
t.Fatal("CSV altered")
|
||||
}
|
||||
state := configRequest(s, token, "GET", "/_/api/v1/editor/state?uuid="+object+"&lang=und&revision="+first.UUID, nil)
|
||||
var content struct {
|
||||
Body string
|
||||
Editable bool
|
||||
}
|
||||
if err = json.Unmarshal(state.Body.Bytes(), &content); err != nil || state.Code != 200 || !content.Editable || content.Body != csvEditorFixtureBody {
|
||||
t.Fatal("restore", state.Code, err)
|
||||
}
|
||||
reader, err := s.store.CreatePasswordAccount(domain, "csvreader", "a long test password", "Reader", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.store.SetPrincipalState(domain, reader.UUID, "readonly"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
denied, _ := s.store.CreateAuthSession(domain, reader.UUID)
|
||||
if code := save(denied, head.UUID, "forbidden"); code != 403 {
|
||||
t.Fatal("readonly save", code)
|
||||
}
|
||||
// Initial CSV is embedded as an escaped JS string to preserve CRLF. A
|
||||
// field must not terminate that script or become executable markup.
|
||||
if _, err = s.store.SaveRevisionContent(object, []byte("\"</script><script>alert(1)</script>\",value\r\n"), "", "und", "text/csv", "table.csv"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
escaped := configRequest(s, token, "GET", "/e/-/table.csv", nil)
|
||||
if escaped.Code != 200 || strings.Contains(escaped.Body.String(), "<script>alert(1)</script>") || !strings.Contains(escaped.Body.String(), `\u003c/script\u003e`) {
|
||||
t.Fatal("CSV script string was not escaped")
|
||||
}
|
||||
for _, input := range []struct {
|
||||
body []byte
|
||||
code int
|
||||
}{{[]byte(strings.Repeat("x", maxCSVMacroBytes+1)), 413}, {[]byte{0xff, 0xfe}, 415}, {[]byte("a,\x00"), 415}} {
|
||||
rev, e := s.store.SaveRevisionContent(object, input.body, "", "und", "text/csv", "table.csv")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
w := configRequest(s, token, "GET", "/e/-/table.csv", nil)
|
||||
if w.Code != input.code {
|
||||
t.Fatalf("editor bounds %d wanted %d", w.Code, input.code)
|
||||
}
|
||||
w = configRequest(s, token, "GET", "/_/api/v1/editor/state?uuid="+object+"&lang=und&revision="+rev.UUID, nil)
|
||||
if w.Code != input.code {
|
||||
t.Fatalf("state bounds %d wanted %d", w.Code, input.code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCSVEditorChromium(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) {
|
||||
s, token, domain, _ := editorFixture(t)
|
||||
object, err := s.store.CreatePageAtPathInDomain(domain, "/table.csv")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.store.SaveRevisionContent(object, []byte(csvEditorFixtureBody), "", "und", "text/csv; charset=utf-8", "table.csv"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script, err := os.ReadFile("internal/server/testdata/csv-editor.js")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Host = "localhost"
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
if r.URL.Path == "/e/-/table.csv" {
|
||||
rec := httptest.NewRecorder()
|
||||
s.withAuthorization(s.mux).ServeHTTP(rec, r)
|
||||
for k, v := range rec.Header() {
|
||||
w.Header()[k] = v
|
||||
}
|
||||
w.WriteHeader(rec.Code)
|
||||
_, policy, _ := strings.Cut(rec.Header().Get("Content-Security-Policy"), "'nonce-")
|
||||
nonce, _, _ := strings.Cut(policy, "'")
|
||||
w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", `<script nonce="`+html.EscapeString(nonce)+`">`+string(script)+"</script></body>", 1)))
|
||||
return
|
||||
}
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", server.URL+"/e/-/table.csv", t.TempDir(), "/tmp/pageswiki-csv-editor-"+width+".png", width, "850").CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("browser: %v %s", err, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@ package server
|
||||
|
||||
func init() {
|
||||
for lang, entries := range map[string]map[string]string{
|
||||
"en": {"editor.tools": "Insert component / drafts", "editor.language": "Edit / fork language", "editor.restore": "Restore a revision into the editor"},
|
||||
"ja": {"editor.tools": "コンポーネント挿入・下書き", "editor.language": "言語の編集・分岐", "editor.restore": "過去のリビジョンをエディタに復元"},
|
||||
"en": {"editor.tools": "Insert component / drafts", "editor.language": "Edit / fork language", "editor.restore": "Restore a revision into the editor", "editor.csv_source": "CSV source", "editor.csv_table": "CSV table"},
|
||||
"ja": {"editor.tools": "コンポーネント挿入・下書き", "editor.language": "言語の編集・分岐", "editor.restore": "過去のリビジョンをエディタに復元", "editor.csv_source": "CSVソースを表示", "editor.csv_table": "CSVの表を表示"},
|
||||
} {
|
||||
for key, value := range entries {
|
||||
translations[lang][key] = value
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"pageswiki/internal/grammaratur"
|
||||
)
|
||||
@@ -73,7 +74,20 @@ func (s *Server) handleEditorState(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
out := map[string]any{"revision_uuid": rev.UUID, "head_revision_uuid": head, "lang": rev.Language, "content_type": rev.ContentType, "filename": rev.Filename, "principal_uuid": owner}
|
||||
if r.URL.Query().Get("metadata") != "1" {
|
||||
if rev.UUID != "" {
|
||||
csv := selectProjectionAdapter(contentDescriptor{MediaType: strings.ToLower(strings.TrimSpace(strings.Split(rev.ContentType, ";")[0])), Filename: rev.Filename}).Kind == "csv"
|
||||
if csv {
|
||||
size, e := s.store.DocumentSizeContext(r.Context(), rev.DocumentHash)
|
||||
if e != nil || size > maxCSVMacroBytes {
|
||||
http.Error(w, "CSV editor size limit exceeded", 413)
|
||||
return
|
||||
}
|
||||
window, e := s.store.ReadDocumentWindowContext(r.Context(), rev.DocumentHash, 0, maxCSVMacroBytes)
|
||||
if e != nil || window.Truncated || !utf8.Valid(window.Data) || strings.ContainsRune(string(window.Data), 0) {
|
||||
http.Error(w, "CSV source unavailable or not UTF-8", 415)
|
||||
return
|
||||
}
|
||||
rev.Body = string(window.Data)
|
||||
} else if rev.UUID != "" {
|
||||
rev, err = s.store.GetRevision(rev.UUID)
|
||||
}
|
||||
if err != nil {
|
||||
@@ -90,7 +104,7 @@ func (s *Server) handleEditorState(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
out["body"], out["markdown"] = rev.Body, markdown
|
||||
kind := revisionContentView(rev, "").Kind
|
||||
out["editable"] = rev.UUID == "" || kind == "html" || kind == "code"
|
||||
out["editable"] = rev.UUID == "" || kind == "html" || kind == "code" || (csv && utf8.ValidString(rev.Body) && !strings.ContainsRune(rev.Body, 0))
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(out)
|
||||
}
|
||||
@@ -189,7 +189,7 @@ func readEndpointResolver(path string) (endpointTargetResolver, string) {
|
||||
return resolveHandler, "read"
|
||||
case strings.HasPrefix(path, "/_/view/print/"):
|
||||
return resolvePrint, "read"
|
||||
case strings.HasPrefix(path, "/v/preview"), strings.HasPrefix(path, "/v/plain"), strings.HasPrefix(path, "/v/markdown"):
|
||||
case strings.HasPrefix(path, "/v/preview"), strings.HasPrefix(path, "/v/plain"), strings.HasPrefix(path, "/v/markdown"), path == "/v/slides", strings.HasPrefix(path, "/v/slides/"):
|
||||
return resolveViewPath, "read"
|
||||
case strings.HasPrefix(path, "/o/e/"):
|
||||
return resolveObjectURL, "write"
|
||||
|
||||
@@ -268,7 +268,7 @@ func objectIDFromRoute(path string) string {
|
||||
}
|
||||
|
||||
func semanticViewPath(route string) string {
|
||||
for _, prefix := range []string{"/v/preview", "/v/plain", "/v/markdown", "/v/browser"} {
|
||||
for _, prefix := range []string{"/v/preview", "/v/plain", "/v/markdown", "/v/browser", "/v/slides"} {
|
||||
if strings.HasPrefix(route, prefix) {
|
||||
path := strings.TrimPrefix(route, prefix)
|
||||
if path == "" {
|
||||
|
||||
@@ -16,6 +16,7 @@ func (s *Server) registeredEventHandlers() *dregarnuhr.Registry {
|
||||
s.eventHandlersOnce.Do(func() {
|
||||
registry := &dregarnuhr.Registry{}
|
||||
handlers := map[string]dregarnuhr.Handler{
|
||||
store.FeedSyncEventType: s.syncFeedSources,
|
||||
store.TaskDigestEventType: s.deliverTaskDigests,
|
||||
store.NotificationPushEventType: func(ctx context.Context, job *store.EventJob) error {
|
||||
return s.deliverNotificationPushContext(ctx, job)
|
||||
|
||||
@@ -58,6 +58,9 @@ func (s *Server) startEventScheduler() {
|
||||
if s.store == nil {
|
||||
return
|
||||
}
|
||||
if err := s.store.EnsureFeedEvent(); err != nil {
|
||||
log.Printf("feed scheduler initialization failed")
|
||||
}
|
||||
if err := s.store.EnsureBuiltinResourceEvent(); err != nil {
|
||||
log.Printf("resource monitor initialization failed: %v", err)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
const feedsAPI = "/_/api/v1/extension/organizer.feeds/"
|
||||
|
||||
func feedRoute(p string) bool { return p == "/v/feeds" || strings.HasPrefix(p, feedsAPI) }
|
||||
func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
domain := s.domainUUIDForRequest(r)
|
||||
licenseDownload := strings.HasPrefix(r.URL.Path, geckoAPI+"distribution/v0.0.1/")
|
||||
if !licenseDownload && !s.systemExtensionEnabled(domain, "organizer.feeds") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
actor, active := s.calendarActor(r)
|
||||
if actor == "" {
|
||||
s.authRequired(w, r)
|
||||
return
|
||||
}
|
||||
if r.Method != "GET" && r.Method != "HEAD" && !active {
|
||||
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)
|
||||
return
|
||||
}
|
||||
if _, e := s.store.FeedSources(r.Context(), domain, actor); e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
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 == "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]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 {
|
||||
RequestID string `json:"request_id"`
|
||||
Source string `json:"source"`
|
||||
ID string `json:"id"`
|
||||
Path string `json:"path"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
Confirm bool `json:"confirm_publication"`
|
||||
}
|
||||
if !taskJSONLimit(w, r, &input, 128<<10) {
|
||||
return
|
||||
}
|
||||
if !input.Confirm {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
for _, capability := range []string{"read", "create", "write"} {
|
||||
if s.authorizePathRequest(r, capability, input.Path) != nil {
|
||||
taskError(w, store.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
}
|
||||
page, e := s.store.CaptureFeedNote(r.Context(), domain, actor, input.RequestID, input.Source, input.ID, input.Path, input.Title, input.Body)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 201, map[string]string{"page_uuid": page})
|
||||
return
|
||||
case key == "sources" && r.Method == "GET":
|
||||
sources, e := s.store.FeedSources(r.Context(), domain, actor)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"sources": sources})
|
||||
return
|
||||
case key == "sources" && r.Method == "POST":
|
||||
var input struct {
|
||||
store.FeedSource
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if !taskJSON(w, r, &input) {
|
||||
return
|
||||
}
|
||||
if !validCalendarSourceURL(input.URL) || len(input.Username) > 256 || len(input.Password) > 4096 {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
if input.Provider == "freshrss" {
|
||||
u, _ := url.Parse(input.URL)
|
||||
if u.RawQuery != "" || !strings.HasSuffix(strings.TrimRight(u.Path, "/"), "/greader.php") {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
}
|
||||
if input.UUID == "" {
|
||||
input.UUID = uuid.NewString()
|
||||
}
|
||||
if input.Version == 0 && input.Provider == "freshrss" {
|
||||
if input.Username == "" || input.Password == "" {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
cipher, e := s.store.SealFeedCredential(domain, actor, input.UUID, input.Username, input.Password)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
input.Credential = cipher
|
||||
} else if input.Username != "" || input.Password != "" {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
v, e := s.store.SaveFeedSource(r.Context(), domain, actor, input.FeedSource)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"source": v})
|
||||
return
|
||||
case strings.HasPrefix(key, "sources/") && r.Method == "POST":
|
||||
parts := strings.Split(key, "/")
|
||||
if len(parts) != 3 {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
Version int64 `json:"version"`
|
||||
}
|
||||
if !taskJSON(w, r, &input) {
|
||||
return
|
||||
}
|
||||
if e := s.store.FeedSourceAction(r.Context(), domain, actor, parts[1], parts[2], input.Version); e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]bool{"ok": true})
|
||||
return
|
||||
case key == "items" && r.Method == "GET":
|
||||
q := r.URL.Query()
|
||||
before := int64(-1)
|
||||
if q.Has("before") {
|
||||
var e error
|
||||
before, e = strconv.ParseInt(q.Get("before"), 10, 64)
|
||||
if e != nil || before < 0 {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
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"), q.Get("category_mode"))
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
more := len(items) > 100
|
||||
if more {
|
||||
items = items[:100]
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"items": items, "more": more})
|
||||
return
|
||||
case key == "item" && r.Method == "GET":
|
||||
v, e := s.store.FeedItem(r.Context(), domain, actor, r.URL.Query().Get("source"), r.URL.Query().Get("id"))
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
// Defense in depth for restored/older caches, not just freshly fetched data.
|
||||
v.BodyHTML = feedHTML(v.BodyHTML, v.URL)
|
||||
writeEventJSON(w, 200, map[string]any{"item": v})
|
||||
return
|
||||
case key == "state" && r.Method == "POST":
|
||||
var input struct {
|
||||
Source string `json:"source"`
|
||||
ID string `json:"id"`
|
||||
Read bool `json:"read"`
|
||||
Starred bool `json:"starred"`
|
||||
Version int64 `json:"version"`
|
||||
}
|
||||
if !taskJSON(w, r, &input) {
|
||||
return
|
||||
}
|
||||
if e := s.store.SetFeedState(r.Context(), domain, actor, input.Source, input.ID, input.Read, input.Starred, input.Version); e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"version": input.Version + 1})
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
func init() {
|
||||
translations["en"]["feeds.title"] = "RSS"
|
||||
translations["ja"]["feeds.title"] = "RSS"
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
const testFeedCatalog = `{"subscriptions":[{"id":"feed/1","title":"Same title","categories":[{"id":"user/alice/label/Tech","label":"技術"}]},{"id":"feed/2","title":"Same title","categories":[{"id":"user/alice/label/Other","label":"技術"}]},{"id":"feed/3","title":"Empty feed","categories":[]}]}`
|
||||
|
||||
func TestFreshRSSCatalogValidation(t *testing.T) {
|
||||
catalog, e := parseFreshRSSCatalog([]byte(testFeedCatalog))
|
||||
if e != nil || len(catalog) != 3 || catalog[0].Categories[0].ID == catalog[1].Categories[0].ID {
|
||||
t.Fatal(catalog, e)
|
||||
}
|
||||
for _, raw := range []string{`{}`, `{"subscriptions":null}`, `{"subscriptions":[{"id":""}]}`, `{"subscriptions":[{"id":"feed/1"},{"id":"feed/1"}]}`, `{"subscriptions":[{"id":"feed/1","categories":[{"id":"cat","label":"A"},{"id":"cat","label":"A"}]}]}`, `{"subscriptions":[{"id":"feed/1","categories":[{"id":"cat","label":"A"}]},{"id":"feed/2","categories":[{"id":"cat","label":"B"}]}]}`} {
|
||||
if _, e := parseFreshRSSCatalog([]byte(raw)); e == nil {
|
||||
t.Fatal("accepted", raw)
|
||||
}
|
||||
}
|
||||
if c, e := parseFreshRSSCatalog([]byte(`{"subscriptions":[]}`)); e != nil || len(c) != 0 {
|
||||
t.Fatal(c, e)
|
||||
}
|
||||
big := make([]store.FeedRemoteSubscription, 1001)
|
||||
raw, _ := json.Marshal(map[string]any{"subscriptions": big})
|
||||
if _, e := parseFreshRSSCatalog(raw); e == nil {
|
||||
t.Fatal("unbounded catalog")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
|
||||
s, token, domain, actor, local := feedFixture(t)
|
||||
ctx := context.Background()
|
||||
if e := s.store.FeedSourceAction(ctx, domain, actor, local.UUID, "delete", local.Version); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
v := store.FeedSource{UUID: uuid.NewString(), Provider: "freshrss", Title: "FreshRSS", URL: "https://example.org/api/greader.php", Enabled: 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)
|
||||
}
|
||||
calls := 0
|
||||
failCatalog := false
|
||||
failFolders := false
|
||||
client := &http.Client{Transport: feedTransportFunc(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
body := ""
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/accounts/ClientLogin"):
|
||||
if r.Method != "POST" {
|
||||
t.Error("login method")
|
||||
}
|
||||
body = "Auth=synthetic"
|
||||
case strings.HasSuffix(r.URL.Path, "/stream/contents/reading-list"):
|
||||
if r.Method != "GET" || r.URL.Query().Get("n") != "200" {
|
||||
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 || failFolders {
|
||||
body = `{"items":[]}`
|
||||
}
|
||||
case strings.HasSuffix(r.URL.Path, "/subscription/list"):
|
||||
if r.Method != "GET" || r.Header.Get("Authorization") != "GoogleLogin auth=synthetic" {
|
||||
t.Error("catalog request")
|
||||
}
|
||||
if failCatalog {
|
||||
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)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
run := func() {
|
||||
t.Helper()
|
||||
if _, e := s.store.DB.Exec(`UPDATE feed_sources SET next_ms=0 WHERE uuid=?`, v.UUID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := s.syncFeedSourcesWithClient(ctx, &store.EventJob{}, client); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
run()
|
||||
if calls != 4 {
|
||||
t.Fatal("fetch count", calls)
|
||||
}
|
||||
w := feedRequestTest(s, token, "GET", "catalog?source="+v.UUID, nil)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), "Empty feed") || strings.Contains(w.Body.String(), "secret") {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
for _, scope := range []string{"feed=feed%2F1", "category=" + url.QueryEscape("user/alice/label/Tech")} {
|
||||
w = feedRequestTest(s, token, "GET", "items?source="+v.UUID+"&"+scope, nil)
|
||||
var data struct {
|
||||
Items []store.FeedItem `json:"items"`
|
||||
}
|
||||
json.Unmarshal(w.Body.Bytes(), &data)
|
||||
if w.Code != 200 || len(data.Items) != 1 || data.Items[0].ID != "a" {
|
||||
t.Fatal(scope, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
w = feedRequestTest(s, token, "GET", "items?feed=feed%2F1", nil)
|
||||
if w.Code != 422 {
|
||||
t.Fatal("unscoped remote ID", w.Code, w.Body)
|
||||
}
|
||||
other, e := s.store.CreatePasswordAccount(domain, "catalogother", "long test password", "Other", "")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
otherToken, e := s.store.CreateAuthSession(domain, other.UUID)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if w = feedRequestTest(s, otherToken, "GET", "catalog?source="+v.UUID, nil); w.Code == 200 {
|
||||
t.Fatal("cross-owner catalog leak")
|
||||
}
|
||||
if w = feedRequestTest(s, "", "GET", "catalog?source="+v.UUID, nil); w.Code == 200 {
|
||||
t.Fatal("anonymous catalog leak")
|
||||
}
|
||||
if _, e := s.store.FeedCatalog(ctx, uuid.NewString(), actor, v.UUID); e == nil {
|
||||
t.Fatal("cross-domain catalog leak")
|
||||
}
|
||||
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)
|
||||
if e != nil || len(catalog) != 3 {
|
||||
t.Fatal("lost catalog", catalog, e)
|
||||
}
|
||||
items, e := s.store.FeedItems(ctx, domain, actor, v.UUID, "", "", -1, "")
|
||||
if e != nil || len(items) != 2 {
|
||||
t.Fatal("lost articles", items, e)
|
||||
}
|
||||
if e := s.setSystemExtensionEnabled(domain, "organizer.feeds", false); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := s.store.FeedCatalog(ctx, domain, actor, v.UUID); !errors.Is(e, store.ErrAccessDenied) {
|
||||
t.Fatal("disabled read", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/microcosm-cc/bluemonday"
|
||||
xhtml "golang.org/x/net/html"
|
||||
"golang.org/x/net/html/charset"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
var errFeedInvalid = errors.New("invalid_feed")
|
||||
var feedTextPolicy = bluemonday.StrictPolicy()
|
||||
var feedHTMLPolicy = func() *bluemonday.Policy {
|
||||
p := bluemonday.NewPolicy()
|
||||
p.AllowElements("p", "div", "span", "br", "hr", "h1", "h2", "h3", "h4", "h5", "h6", "strong", "b", "em", "i", "u", "s", "del", "ins", "sub", "sup", "mark", "small", "blockquote", "pre", "code", "kbd", "samp", "ul", "ol", "li", "dl", "dt", "dd", "table", "caption", "thead", "tbody", "tfoot", "tr", "th", "td", "a")
|
||||
p.AllowAttrs("href", "target", "rel").OnElements("a")
|
||||
p.AllowAttrs("colspan", "rowspan", "scope").OnElements("th", "td")
|
||||
p.AllowStandardURLs()
|
||||
p.AllowRelativeURLs(false)
|
||||
return p
|
||||
}()
|
||||
|
||||
// Keep article structure without granting fetched HTML script, style, form,
|
||||
// embedding or automatic network capabilities. Wiki capture still uses Body.
|
||||
func feedHTML(raw, base string) string {
|
||||
if raw == "" || len(raw) > 128<<10 {
|
||||
return ""
|
||||
}
|
||||
z := xhtml.NewTokenizer(strings.NewReader(raw))
|
||||
var out strings.Builder
|
||||
markup := false
|
||||
for {
|
||||
typeOf := z.Next()
|
||||
if typeOf == xhtml.ErrorToken {
|
||||
if z.Err() != io.EOF {
|
||||
return ""
|
||||
}
|
||||
break
|
||||
}
|
||||
if typeOf == xhtml.StartTagToken || typeOf == xhtml.SelfClosingTagToken {
|
||||
markup = true
|
||||
tok := z.Token()
|
||||
if tok.Data == "a" {
|
||||
attrs := []xhtml.Attribute{}
|
||||
for _, attr := range tok.Attr {
|
||||
if attr.Key == "href" {
|
||||
if link := feedLink(base, attr.Val); link != "" {
|
||||
attrs = append(attrs, xhtml.Attribute{Key: "href", Val: link})
|
||||
}
|
||||
}
|
||||
}
|
||||
tok.Attr = append(attrs, xhtml.Attribute{Key: "target", Val: "_blank"}, xhtml.Attribute{Key: "rel", Val: "noopener noreferrer"})
|
||||
}
|
||||
out.WriteString(tok.String())
|
||||
} else {
|
||||
out.Write(z.Raw())
|
||||
}
|
||||
}
|
||||
if !markup {
|
||||
return ""
|
||||
}
|
||||
clean := feedHTMLPolicy.Sanitize(out.String())
|
||||
if len(clean) > 128<<10 {
|
||||
return ""
|
||||
}
|
||||
return clean
|
||||
}
|
||||
|
||||
func feedText(raw string, limit int) string {
|
||||
// Plain text for fallback and inert Wiki/task capture.
|
||||
for _, tag := range []string{"</p>", "</div>", "<br>", "<br/>", "<br />", "</li>"} {
|
||||
raw = strings.ReplaceAll(raw, tag, tag+"\n")
|
||||
}
|
||||
text := strings.TrimSpace(html.UnescapeString(feedTextPolicy.Sanitize(raw)))
|
||||
if len(text) > limit {
|
||||
text = text[:limit-16]
|
||||
for !utf8.ValidString(text) {
|
||||
text = text[:len(text)-1]
|
||||
}
|
||||
text += "\n[… truncated]"
|
||||
}
|
||||
return text
|
||||
}
|
||||
func feedLink(base, raw string) string {
|
||||
if strings.TrimSpace(raw) == "" || len(raw) > 4096 {
|
||||
return ""
|
||||
}
|
||||
u, e := url.Parse(strings.TrimSpace(raw))
|
||||
if e != nil {
|
||||
return ""
|
||||
}
|
||||
b, e := url.Parse(base)
|
||||
if e != nil {
|
||||
return ""
|
||||
}
|
||||
u = b.ResolveReference(u)
|
||||
if (u.Scheme != "https" && u.Scheme != "http") || u.Hostname() == "" || u.User != nil {
|
||||
return ""
|
||||
}
|
||||
result := u.String()
|
||||
if len(result) > 4096 {
|
||||
return ""
|
||||
}
|
||||
return result
|
||||
}
|
||||
func feedDate(v string) int64 {
|
||||
for _, layout := range []string{time.RFC3339Nano, time.RFC1123Z, time.RFC1123, time.RFC822Z, time.RFC822, "2006-01-02T15:04:05-0700"} {
|
||||
if t, e := time.Parse(layout, v); e == nil && t.UnixMilli() > 0 && t.Before(time.Now().AddDate(1, 0, 0)) {
|
||||
return t.UnixMilli()
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type rssEntry struct {
|
||||
ID string `xml:"guid"`
|
||||
Title string `xml:"title"`
|
||||
Link string `xml:"link"`
|
||||
Description string `xml:"description"`
|
||||
Content string `xml:"encoded"`
|
||||
Date string `xml:"pubDate"`
|
||||
Category string `xml:"category"`
|
||||
}
|
||||
type atomText struct {
|
||||
Type string `xml:"type,attr"`
|
||||
Text string `xml:",chardata"`
|
||||
Inner string `xml:",innerxml"`
|
||||
}
|
||||
|
||||
func (v atomText) body() (string, bool) {
|
||||
if v.Type == "xhtml" {
|
||||
return v.Inner, true
|
||||
}
|
||||
return v.Text, v.Type == "html"
|
||||
}
|
||||
|
||||
type atomEntry struct {
|
||||
ID string `xml:"id"`
|
||||
Title string `xml:"title"`
|
||||
Links []struct {
|
||||
Href string `xml:"href,attr"`
|
||||
Rel string `xml:"rel,attr"`
|
||||
} `xml:"link"`
|
||||
Summary atomText `xml:"summary"`
|
||||
Content atomText `xml:"content"`
|
||||
Published string `xml:"published"`
|
||||
Updated string `xml:"updated"`
|
||||
Category struct {
|
||||
Term string `xml:"term,attr"`
|
||||
} `xml:"category"`
|
||||
}
|
||||
|
||||
func parseFeed(raw []byte, base string) ([]store.FeedItem, error) {
|
||||
if len(raw) > 4<<20 {
|
||||
return nil, errors.New("limit")
|
||||
}
|
||||
d := xml.NewDecoder(bytes.NewReader(raw))
|
||||
d.CharsetReader = charset.NewReaderLabel
|
||||
root := ""
|
||||
title := ""
|
||||
depth := 0
|
||||
out := []store.FeedItem{}
|
||||
seen := map[string]bool{}
|
||||
for {
|
||||
tok, e := d.Token()
|
||||
if e == io.EOF {
|
||||
break
|
||||
}
|
||||
if e != nil {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
switch t := tok.(type) {
|
||||
case xml.Directive:
|
||||
return nil, errFeedInvalid // DTD/entities have no role in a feed.
|
||||
case xml.StartElement:
|
||||
depth++
|
||||
if depth == 1 && root != "" {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
if depth > 64 {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
if root == "" {
|
||||
root = t.Name.Local
|
||||
if root != "rss" && root != "feed" {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
}
|
||||
var item store.FeedItem
|
||||
isItem := false
|
||||
htmlBody := false
|
||||
if root == "rss" && t.Name.Local == "item" && depth == 3 {
|
||||
var v rssEntry
|
||||
if d.DecodeElement(&v, &t) != nil {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
depth--
|
||||
body := v.Content
|
||||
if body == "" {
|
||||
body = v.Description
|
||||
}
|
||||
item = store.FeedItem{ID: v.ID, Title: v.Title, URL: feedLink(base, v.Link), Body: body, PublishedMS: feedDate(v.Date), Folder: v.Category}
|
||||
isItem = true
|
||||
htmlBody = true
|
||||
} else if root == "feed" && t.Name.Local == "entry" && depth == 2 {
|
||||
var v atomEntry
|
||||
if d.DecodeElement(&v, &t) != nil {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
depth--
|
||||
body, isHTML := v.Content.body()
|
||||
if body == "" {
|
||||
body, isHTML = v.Summary.body()
|
||||
}
|
||||
htmlBody = isHTML
|
||||
link := ""
|
||||
for _, l := range v.Links {
|
||||
if l.Rel == "" || l.Rel == "alternate" {
|
||||
link = feedLink(base, l.Href)
|
||||
break
|
||||
}
|
||||
}
|
||||
date := v.Published
|
||||
if date == "" {
|
||||
date = v.Updated
|
||||
}
|
||||
item = store.FeedItem{ID: v.ID, Title: v.Title, URL: link, Body: body, PublishedMS: feedDate(date), Folder: v.Category.Term}
|
||||
isItem = true
|
||||
} else if t.Name.Local == "title" && ((root == "rss" && depth == 3) || (root == "feed" && depth == 2)) {
|
||||
if d.DecodeElement(&title, &t) != nil {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
depth--
|
||||
}
|
||||
if isItem {
|
||||
if len(out) >= 500 {
|
||||
return nil, errors.New("limit")
|
||||
}
|
||||
item.Title = feedText(item.Title, 2048)
|
||||
if htmlBody {
|
||||
item.BodyHTML = feedHTML(item.Body, base)
|
||||
item.Body = feedText(item.Body, 32768)
|
||||
} else {
|
||||
// Atom type=text is literal, even when it contains HTML-looking text.
|
||||
item.Body = feedText(html.EscapeString(item.Body), 32768)
|
||||
}
|
||||
item.Feed = feedText(title, 512)
|
||||
item.Folder = feedText(item.Folder, 512)
|
||||
if item.ID == "" {
|
||||
key := item.URL
|
||||
if key == "" {
|
||||
key = item.Title + "\x00" + strconv.FormatInt(item.PublishedMS, 10) + "\x00" + item.Body
|
||||
}
|
||||
h := sha256.Sum256([]byte(key))
|
||||
item.ID = "sha256:" + hex.EncodeToString(h[:])
|
||||
}
|
||||
if len(item.ID) > 1024 || seen[item.ID] {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
seen[item.ID] = true
|
||||
out = append(out, item)
|
||||
}
|
||||
case xml.EndElement:
|
||||
depth--
|
||||
}
|
||||
}
|
||||
if root == "" || depth != 0 {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func feedRequest(ctx context.Context, client *http.Client, method, target, auth string, form url.Values, headers map[string]string) ([]byte, http.Header, int, error) {
|
||||
var body io.Reader
|
||||
if form != nil {
|
||||
body = strings.NewReader(form.Encode())
|
||||
}
|
||||
r, e := http.NewRequestWithContext(ctx, method, target, body)
|
||||
if e != nil {
|
||||
return nil, nil, 0, errFeedInvalid
|
||||
}
|
||||
if auth != "" {
|
||||
r.Header.Set("Authorization", "GoogleLogin auth="+auth)
|
||||
}
|
||||
if form != nil {
|
||||
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
r.Header.Set("User-Agent", "PagesWiki-Feeds/0.1")
|
||||
for k, v := range headers {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
res, e := client.Do(r)
|
||||
if e != nil {
|
||||
return nil, nil, 0, errors.New("network")
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode == 401 || res.StatusCode == 403 {
|
||||
return nil, nil, res.StatusCode, errors.New("credentials")
|
||||
}
|
||||
if res.StatusCode == 304 {
|
||||
return nil, res.Header, 304, nil
|
||||
}
|
||||
if res.StatusCode != 200 {
|
||||
return nil, nil, res.StatusCode, errors.New("remote_error")
|
||||
}
|
||||
raw, e := io.ReadAll(io.LimitReader(res.Body, (4<<20)+1))
|
||||
if e != nil {
|
||||
return nil, nil, 0, errors.New("network")
|
||||
}
|
||||
if len(raw) > 4<<20 {
|
||||
return nil, nil, 0, errors.New("limit")
|
||||
}
|
||||
return raw, res.Header, res.StatusCode, nil
|
||||
}
|
||||
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 "", e
|
||||
}
|
||||
auth := ""
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
if strings.HasPrefix(line, "Auth=") {
|
||||
auth = strings.TrimSpace(strings.TrimPrefix(line, "Auth="))
|
||||
}
|
||||
}
|
||||
if auth == "" || len(auth) > 4096 || strings.ContainsAny(auth, "\r\n") {
|
||||
return "", errors.New("credentials")
|
||||
}
|
||||
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"`
|
||||
Title string `json:"title"`
|
||||
Published int64 `json:"published"`
|
||||
Categories []string `json:"categories"`
|
||||
Origin struct {
|
||||
Title string `json:"title"`
|
||||
StreamID string `json:"streamId"`
|
||||
} `json:"origin"`
|
||||
Alternate []struct {
|
||||
Href string `json:"href"`
|
||||
} `json:"alternate"`
|
||||
Summary struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"summary"`
|
||||
Content struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"content"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if json.Unmarshal(raw, &response) != nil || response.Items == nil || len(response.Items) > 200 {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
out := []store.FeedItem{}
|
||||
seen := map[string]bool{}
|
||||
for _, i := range response.Items {
|
||||
if i.ID == "" || len(i.ID) > 1024 || seen[i.ID] {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
seen[i.ID] = true
|
||||
if (i.Origin.StreamID != "" && !store.ValidFeedRemoteID(i.Origin.StreamID)) || len(i.Categories) > 64 {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
item := store.FeedItem{ID: i.ID, Title: feedText(i.Title, 2048), Feed: feedText(i.Origin.Title, 512), RemoteFeed: i.Origin.StreamID, RemoteCategories: []string{}}
|
||||
if i.Published > 0 && i.Published < time.Now().AddDate(1, 0, 0).Unix() {
|
||||
item.PublishedMS = i.Published * 1000
|
||||
}
|
||||
body := i.Summary.Content
|
||||
if body == "" {
|
||||
body = i.Content.Content
|
||||
}
|
||||
item.Body = feedText(body, 32768)
|
||||
item.BodyHTML = feedHTML(body, base)
|
||||
if len(i.Alternate) > 0 {
|
||||
item.URL = feedLink(base, i.Alternate[0].Href)
|
||||
}
|
||||
for _, c := range i.Categories {
|
||||
if !store.ValidFeedRemoteID(c) {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
if strings.HasSuffix(c, "/state/com.google/read") {
|
||||
item.Read = true
|
||||
}
|
||||
if strings.HasSuffix(c, "/state/com.google/starred") {
|
||||
item.Starred = true
|
||||
}
|
||||
if pos := strings.Index(c, "/label/"); pos >= 0 {
|
||||
item.Folder = feedText(c[pos+7:], 512)
|
||||
item.RemoteCategories = append(item.RemoteCategories, c)
|
||||
}
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func parseFreshRSSCatalog(raw []byte) ([]store.FeedRemoteSubscription, error) {
|
||||
if len(raw) > 4<<20 || !utf8.Valid(raw) {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
var response struct {
|
||||
Subscriptions []store.FeedRemoteSubscription `json:"subscriptions"`
|
||||
}
|
||||
if json.Unmarshal(raw, &response) != nil || response.Subscriptions == nil {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
if len(response.Subscriptions) > 1000 {
|
||||
return nil, errors.New("limit")
|
||||
}
|
||||
for i := range response.Subscriptions {
|
||||
sub := &response.Subscriptions[i]
|
||||
sub.Title = feedText(sub.Title, 512)
|
||||
if sub.Categories == nil {
|
||||
sub.Categories = []store.FeedCategory{}
|
||||
}
|
||||
for j := range sub.Categories {
|
||||
sub.Categories[j].Label = feedText(sub.Categories[j].Label, 512)
|
||||
}
|
||||
}
|
||||
if _, e := store.FeedCatalogJSON(response.Subscriptions); e != nil {
|
||||
return nil, errFeedInvalid
|
||||
}
|
||||
return response.Subscriptions, nil
|
||||
}
|
||||
func (s *Server) syncFeedSources(ctx context.Context, job *store.EventJob) error {
|
||||
client := calendarSourceClient()
|
||||
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
defer client.CloseIdleConnections()
|
||||
return s.syncFeedSourcesWithClient(ctx, job, client)
|
||||
}
|
||||
|
||||
// Tests inject a synthetic transport; production always uses the DNS-pinned,
|
||||
// public HTTPS-only transport above, never a user-configurable HTTP client.
|
||||
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
|
||||
}
|
||||
done, failed := 0, 0
|
||||
for _, v := range sources {
|
||||
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
|
||||
}
|
||||
v, e = s.store.ClaimFeed(ctx, v)
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
child, stop := context.WithTimeout(ctx, 8*time.Second)
|
||||
var items []store.FeedItem
|
||||
var catalog store.FeedCatalogSnapshot
|
||||
etag, modified := v.ETag, v.Modified
|
||||
unchanged := false
|
||||
if !validCalendarSourceURL(v.URL) {
|
||||
e = errFeedInvalid
|
||||
} else if v.Provider == "freshrss" {
|
||||
var user, password string
|
||||
user, password, e = s.store.OpenFeedCredential(v)
|
||||
if e == nil {
|
||||
items, e = fetchFreshRSS(child, client, v, user, password, &catalog)
|
||||
} else {
|
||||
e = errors.New("credentials")
|
||||
}
|
||||
} else {
|
||||
var raw []byte
|
||||
var h http.Header
|
||||
var status int
|
||||
raw, h, status, e = feedRequest(child, client, "GET", v.URL, "", nil, map[string]string{"If-None-Match": v.ETag, "If-Modified-Since": v.Modified})
|
||||
if e == nil {
|
||||
unchanged = status == 304
|
||||
if !unchanged {
|
||||
items, e = parseFeed(raw, v.URL)
|
||||
etag, modified = h.Get("ETag"), h.Get("Last-Modified")
|
||||
}
|
||||
}
|
||||
}
|
||||
stop()
|
||||
if e == nil && (len(etag) > 1024 || len(modified) > 1024) {
|
||||
e = errors.New("limit")
|
||||
etag, modified = v.ETag, v.Modified
|
||||
items = nil
|
||||
}
|
||||
code := ""
|
||||
if e != nil {
|
||||
code = e.Error()
|
||||
switch code {
|
||||
case "network", "invalid_feed", "credentials", "remote_error", "limit":
|
||||
default:
|
||||
code = "invalid_feed"
|
||||
}
|
||||
failed++
|
||||
} else {
|
||||
done++
|
||||
}
|
||||
if e = s.store.CompleteFeed(ctx, v, items, etag, modified, code, unchanged, catalog); e != nil && !errors.Is(e, store.ErrAccessDenied) && !errors.Is(e, store.ErrTaskConflict) {
|
||||
return e
|
||||
}
|
||||
}
|
||||
s.addEventProgressLog(ctx, job, fmt.Sprintf("feed sources updated=%d failed=%d", done, failed))
|
||||
return nil
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
const feedOPMLMaxBytes = 512 << 10
|
||||
|
||||
type feedOPMLRow struct {
|
||||
store.FeedSubscription
|
||||
Index int `json:"index"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// Parse only the uploaded document. OPML includes and HTML links are never
|
||||
// fetched. Every token participates in the depth/outline/DTD checks.
|
||||
func parseFeedOPML(raw string) ([]feedOPMLRow, error) {
|
||||
if len(raw) > feedOPMLMaxBytes {
|
||||
return nil, store.ErrTaskDAVLimit
|
||||
}
|
||||
d := xml.NewDecoder(strings.NewReader(strings.TrimPrefix(raw, "\ufeff")))
|
||||
// JSON and the browser's File.text() carry UTF-8, not the original legacy
|
||||
// bytes. Reject other XML encodings instead of silently corrupting names.
|
||||
type frame struct {
|
||||
name xml.Name
|
||||
folder string
|
||||
commented bool
|
||||
}
|
||||
stack := []frame{}
|
||||
rows := []feedOPMLRow{}
|
||||
root, head, body, outlines := 0, 0, 0, 0
|
||||
for {
|
||||
token, err := d.Token()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, store.ErrTaskInvalid
|
||||
}
|
||||
switch t := token.(type) {
|
||||
case xml.Directive:
|
||||
return nil, store.ErrTaskInvalid
|
||||
case xml.CharData:
|
||||
if len(stack) == 0 && strings.TrimSpace(string(t)) != "" {
|
||||
return nil, store.ErrTaskInvalid
|
||||
}
|
||||
case xml.StartElement:
|
||||
if len(stack) >= 16 {
|
||||
return nil, store.ErrTaskDAVLimit
|
||||
}
|
||||
attrs := map[string]string{}
|
||||
seen := map[xml.Name]bool{}
|
||||
for _, a := range t.Attr {
|
||||
if seen[a.Name] {
|
||||
return nil, store.ErrTaskInvalid
|
||||
}
|
||||
seen[a.Name] = true
|
||||
if a.Name.Space == "" {
|
||||
attrs[a.Name.Local] = a.Value
|
||||
}
|
||||
}
|
||||
f := frame{name: t.Name}
|
||||
if len(stack) == 0 {
|
||||
root++
|
||||
if root != 1 || t.Name.Space != "" || t.Name.Local != "opml" || (attrs["version"] != "1.0" && attrs["version"] != "1.1" && attrs["version"] != "2.0") {
|
||||
return nil, store.ErrTaskInvalid
|
||||
}
|
||||
} else {
|
||||
parent := stack[len(stack)-1]
|
||||
f.folder = parent.folder
|
||||
f.commented = parent.commented
|
||||
if len(stack) == 1 && t.Name.Space == "" {
|
||||
switch t.Name.Local {
|
||||
case "head":
|
||||
head++
|
||||
if head != 1 || body != 0 {
|
||||
return nil, store.ErrTaskInvalid
|
||||
}
|
||||
case "body":
|
||||
body++
|
||||
if head != 1 || body != 1 {
|
||||
return nil, store.ErrTaskInvalid
|
||||
}
|
||||
default:
|
||||
return nil, store.ErrTaskInvalid
|
||||
}
|
||||
}
|
||||
inBody := len(stack) >= 2 && stack[1].name == (xml.Name{Local: "body"})
|
||||
if inBody && t.Name.Space == "" && parent.name.Space == "" && (parent.name.Local == "body" || parent.name.Local == "outline") && t.Name.Local != "outline" {
|
||||
return nil, store.ErrTaskInvalid
|
||||
}
|
||||
if inBody && t.Name.Space == "" && t.Name.Local == "outline" && parent.name.Space == "" && (parent.name.Local == "body" || parent.name.Local == "outline") {
|
||||
outlines++
|
||||
if outlines > 1000 {
|
||||
return nil, store.ErrTaskDAVLimit
|
||||
}
|
||||
f.commented = f.commented || strings.EqualFold(attrs["isComment"], "true")
|
||||
label := attrs["text"]
|
||||
if label == "" {
|
||||
label = attrs["title"]
|
||||
}
|
||||
label = feedText(label, 1024)
|
||||
kind := strings.ToLower(attrs["type"])
|
||||
if attrs["xmlUrl"] != "" || kind != "" {
|
||||
if len(rows) >= 500 {
|
||||
return nil, store.ErrTaskDAVLimit
|
||||
}
|
||||
row := feedOPMLRow{FeedSubscription: store.FeedSubscription{Title: label, Folder: f.folder, URL: strings.TrimSpace(attrs["xmlUrl"])}, Index: len(rows), Status: "add"}
|
||||
switch {
|
||||
case f.commented:
|
||||
row.Status = "commented"
|
||||
case kind != "" && kind != "rss" && kind != "atom":
|
||||
row.Status = "unsupported_type"
|
||||
case !validCalendarSourceURL(row.URL):
|
||||
row.Status = "unsupported_url"
|
||||
case label == "" || len(label) > 200 || len(f.folder) > 200:
|
||||
row.Status = "invalid_fields"
|
||||
}
|
||||
rows = append(rows, row)
|
||||
} else if label != "" {
|
||||
if f.folder != "" {
|
||||
f.folder += " / "
|
||||
}
|
||||
f.folder += label
|
||||
}
|
||||
}
|
||||
}
|
||||
stack = append(stack, f)
|
||||
case xml.EndElement:
|
||||
if len(stack) == 0 {
|
||||
return nil, store.ErrTaskInvalid
|
||||
}
|
||||
stack = stack[:len(stack)-1]
|
||||
}
|
||||
}
|
||||
if root != 1 || head != 1 || body != 1 || len(stack) != 0 {
|
||||
return nil, store.ErrTaskInvalid
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func classifyFeedOPML(rows []feedOPMLRow, sources []store.FeedSource) {
|
||||
existing := map[string]bool{}
|
||||
seen := map[string]bool{}
|
||||
for _, s := range sources {
|
||||
if s.Provider == "local" {
|
||||
existing[store.FeedURLKey(s.URL)] = true
|
||||
}
|
||||
}
|
||||
for i := range rows {
|
||||
row := &rows[i]
|
||||
if row.Status != "add" {
|
||||
continue
|
||||
}
|
||||
key := store.FeedURLKey(row.URL)
|
||||
if existing[key] {
|
||||
row.Status = "existing"
|
||||
} else if seen[key] {
|
||||
row.Status = "duplicate"
|
||||
}
|
||||
seen[key] = true
|
||||
}
|
||||
}
|
||||
|
||||
type feedOPMLOutline struct {
|
||||
Text string `xml:"text,attr"`
|
||||
Title string `xml:"title,attr,omitempty"`
|
||||
Type string `xml:"type,attr,omitempty"`
|
||||
URL string `xml:"xmlUrl,attr,omitempty"`
|
||||
Children []feedOPMLOutline `xml:"outline"`
|
||||
}
|
||||
|
||||
func encodeFeedOPML(sources []store.FeedSource) ([]byte, error) {
|
||||
var doc struct {
|
||||
XMLName xml.Name `xml:"opml"`
|
||||
Version string `xml:"version,attr"`
|
||||
Title string `xml:"head>title"`
|
||||
Outlines []feedOPMLOutline `xml:"body>outline"`
|
||||
}
|
||||
doc.Version = "2.0"
|
||||
doc.Title = "PagesWiki RSS"
|
||||
groups := map[string]int{}
|
||||
for _, source := range sources {
|
||||
if source.Provider != "local" {
|
||||
continue
|
||||
}
|
||||
entry := feedOPMLOutline{Text: source.Title, Title: source.Title, Type: "rss", URL: source.URL}
|
||||
if source.Folder == "" {
|
||||
doc.Outlines = append(doc.Outlines, entry)
|
||||
continue
|
||||
}
|
||||
i, ok := groups[source.Folder]
|
||||
if !ok {
|
||||
i = len(doc.Outlines)
|
||||
groups[source.Folder] = i
|
||||
doc.Outlines = append(doc.Outlines, feedOPMLOutline{Text: source.Folder})
|
||||
}
|
||||
doc.Outlines[i].Children = append(doc.Outlines[i].Children, entry)
|
||||
}
|
||||
raw, err := xml.MarshalIndent(doc, "", " ")
|
||||
return append([]byte(xml.Header), raw...), err
|
||||
}
|
||||
|
||||
func (s *Server) handleFeedOPML(w http.ResponseWriter, r *http.Request, domain, actor, key string) {
|
||||
if key == "opml/export" && r.Method == http.MethodGet {
|
||||
sources, err := s.store.FeedSources(r.Context(), domain, actor)
|
||||
if err != nil {
|
||||
taskError(w, err)
|
||||
return
|
||||
}
|
||||
raw, err := encodeFeedOPML(sources)
|
||||
if err != nil {
|
||||
taskError(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/x-opml; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="pageswiki-feeds.opml"`)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Write(raw)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost || (key != "opml/preview" && key != "opml/import") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
OPML string `json:"opml"`
|
||||
Selected []int `json:"selected"`
|
||||
RequestID string `json:"request_id"`
|
||||
Expected string `json:"expected"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Interval int `json:"interval_seconds"`
|
||||
}
|
||||
if !taskJSONLimit(w, r, &input, 2<<20) {
|
||||
return
|
||||
}
|
||||
rows, err := parseFeedOPML(input.OPML)
|
||||
if err != nil {
|
||||
taskError(w, err)
|
||||
return
|
||||
}
|
||||
if key == "opml/preview" {
|
||||
sources, err := s.store.FeedSources(r.Context(), domain, actor)
|
||||
if err != nil {
|
||||
taskError(w, err)
|
||||
return
|
||||
}
|
||||
classifyFeedOPML(rows, sources)
|
||||
writeEventJSON(w, 200, map[string]any{"rows": rows, "expected": store.FeedSourcesSnapshot(sources), "available": 32 - len(sources)})
|
||||
return
|
||||
}
|
||||
// Reparse on apply; client-supplied titles, URLs or row eligibility are not trusted.
|
||||
classifyFeedOPML(rows, nil)
|
||||
seen := map[int]bool{}
|
||||
plan := store.FeedImport{RequestID: input.RequestID, Expected: input.Expected, Enabled: input.Enabled, Interval: input.Interval}
|
||||
for _, index := range input.Selected {
|
||||
if index < 0 || index >= len(rows) || seen[index] || rows[index].Status != "add" {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
seen[index] = true
|
||||
plan.Entries = append(plan.Entries, rows[index].FeedSubscription)
|
||||
}
|
||||
ids, err := s.store.ImportFeedSubscriptions(r.Context(), domain, actor, plan)
|
||||
if err != nil {
|
||||
taskError(w, err)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 201, map[string]any{"source_ids": ids})
|
||||
}
|
||||
Loaded 100 of 272 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user