Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a451023f0 | ||
|
|
543814cbd6 | ||
|
|
3262f88005 | ||
|
|
0b6343aff0 |
No files matched your search
@@ -24,9 +24,15 @@ Webの新規作成・クイック追加・サブタスク追加でも既定値
|
|||||||
|
|
||||||
### メール本文のWiki保存
|
### メール本文の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は不要。
|
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以降の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を使う。サーバーAPIの入力フィールド・receipt hash形式は変更しない。
|
||||||
|
|
||||||
保存前に対象Pathへのread/create/write権限を検証する。個人タスクの所有権はWikiへの権限を付与しない。Wiki本文の公開範囲は保存先のACLに従うため、個人設定UIに注意を表示する。再送は既定値の再解決より前にreceiptを確認し、既定Pathの変更で重複作成しない。成功応答はitemとpage_pathを返し、タスクの既存メモ操作から関連Wikiへ移動できる。
|
保存前に対象Pathへのread/create/write権限を検証する。個人タスクの所有権はWikiへの権限を付与しない。Wiki本文の公開範囲は保存先のACLに従うため、個人設定UIに注意を表示する。再送は既定値の再解決より前にreceiptを確認し、既定Pathの変更で重複作成しない。成功応答はitemとpage_pathを返し、タスクの既存メモ操作から関連Wikiへ移動できる。
|
||||||
|
|
||||||
|
|||||||
@@ -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,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保存
|
# メール本文の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経由のログイン・メール取り込み・連絡先・ログアウト。
|
- CLI単体テスト41件、合成HTTP経由のログイン・メール取り込み・連絡先・ログアウト。
|
||||||
- GoのメールWiki作成、既定Path・明示Path・プロジェクト配下、再送、権限拒否、衝突、本文上限、トランザクションのロールバック。
|
- GoのメールWiki作成、既定Path・明示Path・プロジェクト配下、再送、権限拒否、衝突、本文上限、トランザクションのロールバック。
|
||||||
- 独立CLIスナップショットとGo APIの結合テスト。作成したページがタスクのメモ操作から開けることを確認。
|
- 独立CLIスナップショットとGo APIの結合テスト。作成したページがタスクのメモ操作から開けることを確認。
|
||||||
- Chromiumのデスクトップ・スマホ幅で、現在のプロジェクト選択・フォームリセット・Wiki Path保存を確認。デスクトップでは候補の先頭ページにないプロジェクトも検証。
|
- 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)を参照。外部取り込みカレンダーや実メール本文は検証のために読んでいない。
|
||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
"database/sql"
|
"database/sql"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -15,6 +17,7 @@ import (
|
|||||||
|
|
||||||
func TestTaskMailWikiCapture(t *testing.T) {
|
func TestTaskMailWikiCapture(t *testing.T) {
|
||||||
s, token, domain, actor := taskFixture(t)
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
s.mux.HandleFunc("/v/raw/", s.handleRawView)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
p, err := s.store.TaskPreferences(ctx, domain, actor)
|
p, err := s.store.TaskPreferences(ctx, domain, actor)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -51,6 +54,29 @@ func TestTaskMailWikiCapture(t *testing.T) {
|
|||||||
if err != nil || !strings.Contains(rev.Body, "<script>bad()</script>") || strings.Contains(rev.Body, "{{children}}") {
|
if err != nil || !strings.Contains(rev.Body, "<script>bad()</script>") || strings.Contains(rev.Body, "{{children}}") {
|
||||||
t.Fatal(rev, err)
|
t.Fatal(rev, err)
|
||||||
}
|
}
|
||||||
|
// Existing Japanese paths are not renamed or broken by receipt replay.
|
||||||
|
legacy := "/private/mail/日本語の件名 [list 123]--" + id
|
||||||
|
if _, err = s.store.DB.Exec(`UPDATE paths SET path=? WHERE domain_uuid=? AND object_uuid=?`, legacy, domain, response.Item.PageUUID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
note := taskRequest(s, token, "GET", "items/"+id+"/note", nil, "")
|
||||||
|
var links struct {
|
||||||
|
URL string `json:"url"`
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(note.Body.Bytes(), &links); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
u, err := url.Parse(links.URL)
|
||||||
|
if err != nil || u.Path != legacy || u.RawQuery != "" || u.Fragment != "" {
|
||||||
|
t.Fatal("Japanese note URL", links.URL, err)
|
||||||
|
}
|
||||||
|
request := httptest.NewRequest("GET", "http://localhost/v/raw/path:"+links.URL, nil)
|
||||||
|
request.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
rawResult := httptest.NewRecorder()
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(rawResult, request)
|
||||||
|
if rawResult.Code != 200 || rawResult.Body.String() != rev.Body {
|
||||||
|
t.Fatal("Japanese path fetch", rawResult.Code)
|
||||||
|
}
|
||||||
// A committed retry remains stable even if the preference changes.
|
// A committed retry remains stable even if the preference changes.
|
||||||
p, err = s.store.TaskPreferences(ctx, domain, actor)
|
p, err = s.store.TaskPreferences(ctx, domain, actor)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -63,6 +89,9 @@ func TestTaskMailWikiCapture(t *testing.T) {
|
|||||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 || !strings.Contains(w.Body.String(), response.Item.PageUUID) {
|
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 || !strings.Contains(w.Body.String(), response.Item.PageUUID) {
|
||||||
t.Fatal(w.Code, w.Body)
|
t.Fatal(w.Code, w.Body)
|
||||||
}
|
}
|
||||||
|
if !strings.Contains(w.Body.String(), legacy) {
|
||||||
|
t.Fatal("retry changed existing path", w.Body)
|
||||||
|
}
|
||||||
input["wiki_body"] = "different"
|
input["wiki_body"] = "different"
|
||||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 412 {
|
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 412 {
|
||||||
t.Fatal(w.Code, w.Body)
|
t.Fatal(w.Code, w.Body)
|
||||||
@@ -74,6 +103,18 @@ func TestTaskMailWikiCapture(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestMailWikiPathDoesNotContainSubject(t *testing.T) {
|
||||||
|
id := uuid.NewString()
|
||||||
|
for _, title := range []string{"日本語", "[hogehoge 123] 件名", strings.Repeat("長い", 100), "?#/\\% []"} {
|
||||||
|
if got := store.TaskCaptureWikiPath("/mail", title, id); got != "/mail/mail-"+id {
|
||||||
|
t.Fatal(got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if store.TaskCaptureWikiPath("/mail", "日本語", uuid.NewString()) == store.TaskCaptureWikiPath("/mail", "日本語", id) {
|
||||||
|
t.Fatal("different mails collided")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestTaskMailWikiRollbackAndAccess(t *testing.T) {
|
func TestTaskMailWikiRollbackAndAccess(t *testing.T) {
|
||||||
s, token, domain, actor := taskFixture(t)
|
s, token, domain, actor := taskFixture(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ func TestTaskCLIHTTPIntegration(t *testing.T) {
|
|||||||
t.Skip("python3 not installed")
|
t.Skip("python3 not installed")
|
||||||
}
|
}
|
||||||
s, token, _, _ := taskFixture(t)
|
s, token, _, _ := taskFixture(t)
|
||||||
|
s.mux.HandleFunc("/v/raw/", s.handleRawView)
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
r.Host = "localhost"
|
r.Host = "localhost"
|
||||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTaskMailLayouts(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
for _, suffix := range []string{"hogehoge/123", "v/0", "2026/01/" + uuid.NewString(), "2026/12/" + strings.Repeat("a", 64)} {
|
||||||
|
id := uuid.NewString()
|
||||||
|
input := map[string]any{"request_id": id, "title": "日本語の件名", "wiki_body": "Body", "wiki_prefix": "/mail", "wiki_suffix": suffix}
|
||||||
|
w := taskRequest(s, token, "POST", "capture", input, "")
|
||||||
|
if w.Code != 201 {
|
||||||
|
t.Fatal(suffix, w.Code, w.Body)
|
||||||
|
}
|
||||||
|
var response struct {
|
||||||
|
Path string `json:"page_path"`
|
||||||
|
Item store.TaskRecord `json:"item"`
|
||||||
|
}
|
||||||
|
if e := json.Unmarshal(w.Body.Bytes(), &response); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if response.Path != "/mail/"+suffix {
|
||||||
|
t.Fatal(response.Path)
|
||||||
|
}
|
||||||
|
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 {
|
||||||
|
t.Fatal("replay", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
// A different Message-ID produces a different request UUID, never an overwrite.
|
||||||
|
other := uuid.NewString()
|
||||||
|
input["request_id"] = other
|
||||||
|
input["wiki_body"] = "Different mail"
|
||||||
|
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 409 {
|
||||||
|
t.Fatal("collision", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
if _, e := s.store.GetTask(context.Background(), domain, actor, other); !errors.Is(e, sql.ErrNoRows) {
|
||||||
|
t.Fatal("partial task", e)
|
||||||
|
}
|
||||||
|
rev, e := s.store.GetLatestRevision(response.Item.PageUUID)
|
||||||
|
if e != nil || strings.Contains(rev.Body, "Different") {
|
||||||
|
t.Fatal("page overwritten", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, suffix := range []string{"", "../123", "/list/123", "a/../../123", "list/001", "list/-1", "list/1?x", "list%2f/1", "list/1/2", "_/123", "2026/13/" + uuid.NewString(), "0000/01/" + uuid.NewString(), "2026/01/not-an-id"} {
|
||||||
|
input := map[string]any{"request_id": uuid.NewString(), "title": "Bad", "wiki_body": "Body", "wiki_prefix": "/mail", "wiki_suffix": suffix}
|
||||||
|
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 422 {
|
||||||
|
t.Fatal(suffix, w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
input := map[string]any{"request_id": uuid.NewString(), "title": "No body", "wiki_suffix": "list/123"}
|
||||||
|
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 422 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
other, e := s.store.CreatePasswordAccount(domain, "mail-layout-other", "fixture password long", "Other", "")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
otherToken, e := s.store.CreateAuthSession(domain, other.UUID)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
input = map[string]any{"request_id": uuid.NewString(), "title": "No Wiki permission", "wiki_body": "Body", "wiki_prefix": "/mail", "wiki_suffix": "private/123"}
|
||||||
|
if w := taskRequest(s, otherToken, "POST", "capture", input, ""); w.Code != 403 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -69,6 +69,7 @@ type taskCaptureInput struct {
|
|||||||
Complexity *int `json:"complexity"`
|
Complexity *int `json:"complexity"`
|
||||||
WikiBody *string `json:"wiki_body,omitempty"`
|
WikiBody *string `json:"wiki_body,omitempty"`
|
||||||
WikiPrefix *string `json:"wiki_prefix,omitempty"`
|
WikiPrefix *string `json:"wiki_prefix,omitempty"`
|
||||||
|
WikiSuffix *string `json:"wiki_suffix,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request, actor string, active bool, kind string) {
|
func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request, actor string, active bool, kind string) {
|
||||||
@@ -260,6 +261,13 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
target = store.TaskCaptureWikiPath(prefix, item.Title, input.RequestID)
|
target = store.TaskCaptureWikiPath(prefix, item.Title, input.RequestID)
|
||||||
|
if input.WikiSuffix != nil {
|
||||||
|
if !store.ValidTaskMailSuffix(*input.WikiSuffix) {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
target = strings.TrimRight(prefix, "/") + "/" + *input.WikiSuffix
|
||||||
|
}
|
||||||
for _, capability := range []string{"read", "create", "write"} {
|
for _, capability := range []string{"read", "create", "write"} {
|
||||||
if s.authorizePathRequest(r, capability, target) != nil {
|
if s.authorizePathRequest(r, capability, target) != nil {
|
||||||
taskError(w, store.ErrAccessDenied)
|
taskError(w, store.ErrAccessDenied)
|
||||||
@@ -267,7 +275,7 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
body = *input.WikiBody
|
body = *input.WikiBody
|
||||||
} else if input.WikiPrefix != nil {
|
} else if input.WikiPrefix != nil || input.WikiSuffix != nil {
|
||||||
taskError(w, store.ErrTaskInvalid)
|
taskError(w, store.ErrTaskInvalid)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"html"
|
"html"
|
||||||
"path"
|
"path"
|
||||||
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
@@ -34,11 +35,18 @@ func ValidTaskWikiPrefix(p string) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// A request UUID suffix separates equal subjects and makes the target stable.
|
// The CLI derives the request UUID from origin, user and Message-ID (or a raw
|
||||||
|
// mail hash). Keep subjects in the title, never in the URL's identity segment.
|
||||||
func TaskCaptureWikiPath(prefix, title, request string) string {
|
func TaskCaptureWikiPath(prefix, title, request string) string {
|
||||||
item := TaskRecord{Title: title, UUID: request}
|
return strings.TrimRight(prefix, "/") + "/mail-" + request
|
||||||
name := path.Base(TaskNotePath("", TaskRecord{}, item))
|
}
|
||||||
return strings.TrimRight(prefix, "/") + "/" + name + "--" + request
|
|
||||||
|
var mailListSuffix = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,99}/(0|[1-9][0-9]{0,19})$`)
|
||||||
|
var mailMonthSuffix = regexp.MustCompile(`^[0-9]{4}/(0[1-9]|1[0-2])/([0-9a-f]{64}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$`)
|
||||||
|
|
||||||
|
// Only the two mail layouts are accepted; no arbitrary relative path traversal.
|
||||||
|
func ValidTaskMailSuffix(s string) bool {
|
||||||
|
return mailListSuffix.MatchString(s) || (mailMonthSuffix.MatchString(s) && !strings.HasPrefix(s, "0000/"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) createCapturedTaskWiki(ctx context.Context, tx *sql.Tx, domain, actor string, item *TaskRecord, target, body string) error {
|
func (s *Store) createCapturedTaskWiki(ctx context.Context, tx *sql.Tx, domain, actor string, item *TaskRecord, target, body string) error {
|
||||||
|
|||||||
+43
-5
@@ -3,6 +3,8 @@
|
|||||||
import argparse
|
import argparse
|
||||||
import email.policy
|
import email.policy
|
||||||
import email.parser
|
import email.parser
|
||||||
|
import email.utils
|
||||||
|
import datetime
|
||||||
import uuid
|
import uuid
|
||||||
import base64
|
import base64
|
||||||
import contextlib
|
import contextlib
|
||||||
@@ -30,7 +32,7 @@ import urllib.parse as url
|
|||||||
import urllib.request as http
|
import urllib.request as http
|
||||||
import webbrowser
|
import webbrowser
|
||||||
|
|
||||||
VERSION = '0.3.0'
|
VERSION = '0.4.0'
|
||||||
|
|
||||||
class Failure(Exception):
|
class Failure(Exception):
|
||||||
def __init__(self, message, status=0, payload=None):
|
def __init__(self, message, status=0, payload=None):
|
||||||
@@ -496,11 +498,37 @@ class MailText(HTMLParser):
|
|||||||
if not self.hidden: self.parts.append(data)
|
if not self.hidden: self.parts.append(data)
|
||||||
|
|
||||||
|
|
||||||
|
def mail_subject(value):
|
||||||
|
# Remove only leading mailing-list sequence markers, preserving meaningful
|
||||||
|
# tags such as [Important], and any Re:/Fwd: prefix before the marker.
|
||||||
|
marker = re.compile(r'^(?P<reply>(?:(?:re|fw|fwd)\s*:\s*)*)\[[^\[\]\r\n]+[\s:#]\s*[0-9]+\]\s*', re.IGNORECASE)
|
||||||
|
while True:
|
||||||
|
match = marker.match(value)
|
||||||
|
if not match: return value.strip()
|
||||||
|
value = match.group('reply') + value[match.end():]
|
||||||
|
|
||||||
|
|
||||||
|
def task_mail_suffix(raw, request_id, now=None):
|
||||||
|
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
||||||
|
subject = ' '.join(safe_text(str(message.get('Subject') or '')).split())
|
||||||
|
marker = re.match(r'^(?:(?:re|fw|fwd)\s*:\s*)*\[([A-Za-z0-9][A-Za-z0-9._-]{0,99})[\s:#]+([0-9]{1,20})\]',subject,re.IGNORECASE)
|
||||||
|
if marker:
|
||||||
|
return marker[1]+'/'+str(int(marker[2]))
|
||||||
|
try: date = email.utils.parsedate_to_datetime(str(message.get('Date') or ''))
|
||||||
|
except (ValueError, TypeError, OverflowError): date = now or datetime.datetime.now(datetime.timezone.utc)
|
||||||
|
# Preserve the month in the sender's Date timezone, not the receiving host's.
|
||||||
|
ident = request_id if ' '.join(safe_text(str(message.get('Message-ID') or '')).split()) else hashlib.sha256(raw).hexdigest()
|
||||||
|
return f'{date.year:04d}/{date.month:02d}/{ident}'
|
||||||
|
|
||||||
|
|
||||||
def task_mail(raw, include_body=True, override_title=None):
|
def task_mail(raw, include_body=True, override_title=None):
|
||||||
if len(raw) > 2 << 20: raise Failure('Mail input exceeds 2 MiB; pipe one message at a time.')
|
if len(raw) > 2 << 20: raise Failure('Mail input exceeds 2 MiB; pipe one message at a time.')
|
||||||
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
||||||
clean = lambda value: ' '.join(safe_text(str(value or '')).split())
|
clean = lambda value: ' '.join(safe_text(str(value or '')).split())
|
||||||
title = override_title or clean(message.get('Subject')) or '(No subject)'
|
subject = clean(message.get('Subject'))
|
||||||
|
title = override_title or mail_subject(subject) or '(No subject)'
|
||||||
|
if not override_title and len(title.encode()) > 300:
|
||||||
|
title = title.encode()[:297].decode('utf-8',errors='ignore').rstrip() + '…'
|
||||||
if len(title.encode()) > 300: raise Failure('Mail subject exceeds 300 UTF-8 bytes; use --title.')
|
if len(title.encode()) > 300: raise Failure('Mail subject exceeds 300 UTF-8 bytes; use --title.')
|
||||||
notes = '\n'.join(key+': '+clean(message.get(key)) for key in ('From','Date','Message-ID') if message.get(key))
|
notes = '\n'.join(key+': '+clean(message.get(key)) for key in ('From','Date','Message-ID') if message.get(key))
|
||||||
wiki_body = None
|
wiki_body = None
|
||||||
@@ -513,7 +541,8 @@ def task_mail(raw, include_body=True, override_title=None):
|
|||||||
if not isinstance(content,str): raise Failure('Mail body is not readable text.')
|
if not isinstance(content,str): raise Failure('Mail body is not readable text.')
|
||||||
if part.get_content_type() == 'text/html':
|
if part.get_content_type() == 'text/html':
|
||||||
parser = MailText();parser.feed(content);parser.close();content = ''.join(parser.parts).strip()
|
parser = MailText();parser.feed(content);parser.close();content = ''.join(parser.parts).strip()
|
||||||
wiki_body = notes + '\n\n' + content
|
# Retain the original subject when its mailing-list marker was removed.
|
||||||
|
wiki_body = (('Subject: '+subject+'\n') if title != subject else '') + notes + '\n\n' + content
|
||||||
if '\0' in wiki_body or len(wiki_body.encode()) > 256 << 10: raise Failure('Mail Wiki body must be valid text of at most 256 KiB; nothing was uploaded.')
|
if '\0' in wiki_body or len(wiki_body.encode()) > 256 << 10: raise Failure('Mail Wiki body must be valid text of at most 256 KiB; nothing was uploaded.')
|
||||||
if len(notes.encode()) > 16384: raise Failure('Mail metadata exceeds 16 KiB.')
|
if len(notes.encode()) > 16384: raise Failure('Mail metadata exceeds 16 KiB.')
|
||||||
return title, notes, clean(message.get('Message-ID')) or hashlib.sha256(raw).hexdigest(), wiki_body
|
return title, notes, clean(message.get('Message-ID')) or hashlib.sha256(raw).hexdigest(), wiki_body
|
||||||
@@ -549,6 +578,7 @@ def tasks(client, profile, words):
|
|||||||
def capture(payload):
|
def capture(payload):
|
||||||
pending=profile.data.setdefault('task_outbox',{})
|
pending=profile.data.setdefault('task_outbox',{})
|
||||||
if len(pending)>=20 and payload['request_id'] not in pending:raise Failure('20 pending captures retained. Retry them before adding more.')
|
if len(pending)>=20 and payload['request_id'] not in pending:raise Failure('20 pending captures retained. Retry them before adding more.')
|
||||||
|
if payload['request_id'] in pending and pending[payload['request_id']] != payload:raise Failure('A different draft with this request ID is retained. Use pages task retry '+payload['request_id'])
|
||||||
pending[payload['request_id']]=payload;profile.save()
|
pending[payload['request_id']]=payload;profile.save()
|
||||||
try: result=client.json(TASK_API+'capture',method='POST',data=payload)
|
try: result=client.json(TASK_API+'capture',method='POST',data=payload)
|
||||||
except Failure as e:
|
except Failure as e:
|
||||||
@@ -581,13 +611,21 @@ def tasks(client, profile, words):
|
|||||||
payload={'request_id':getattr(a,'request_id',None) or str(uuid.uuid4()),'title':a.title,'notes':a.notes or ''}
|
payload={'request_id':getattr(a,'request_id',None) or str(uuid.uuid4()),'title':a.title,'notes':a.notes or ''}
|
||||||
if action=='from-mail':
|
if action=='from-mail':
|
||||||
if a.metadata_only and a.wiki_prefix is not None: raise Failure('--wiki-prefix cannot be combined with --metadata-only.')
|
if a.metadata_only and a.wiki_prefix is not None: raise Failure('--wiki-prefix cannot be combined with --metadata-only.')
|
||||||
title,notes,message_id,wiki_body=task_mail(sys.stdin.buffer.read((2<<20)+1),not a.metadata_only,a.title)
|
raw=sys.stdin.buffer.read((2<<20)+1)
|
||||||
|
title,notes,message_id,wiki_body=task_mail(raw,not a.metadata_only,a.title)
|
||||||
payload.update(title=a.title or title,notes=a.notes if a.notes is not None else notes,request_id=str(uuid.uuid5(uuid.NAMESPACE_URL,client.base+'\n'+profile.data.get('username','')+'\n'+message_id)))
|
payload.update(title=a.title or title,notes=a.notes if a.notes is not None else notes,request_id=str(uuid.uuid5(uuid.NAMESPACE_URL,client.base+'\n'+profile.data.get('username','')+'\n'+message_id)))
|
||||||
if wiki_body is not None: payload['wiki_body']=wiki_body
|
if wiki_body is not None:
|
||||||
|
payload['wiki_body']=wiki_body
|
||||||
|
payload['wiki_suffix']=task_mail_suffix(raw,payload['request_id'])
|
||||||
if a.wiki_prefix is not None: payload['wiki_prefix']=a.wiki_prefix
|
if a.wiki_prefix is not None: payload['wiki_prefix']=a.wiki_prefix
|
||||||
for attr,key in [('project','project_uuid'),('assignee','assignee_uuid'),('due','due_on'),('start_on','start_on'),('planned','planned_on'),('review','review_on'),('estimate','estimate_minutes'),('complexity','complexity')]:
|
for attr,key in [('project','project_uuid'),('assignee','assignee_uuid'),('due','due_on'),('start_on','start_on'),('planned','planned_on'),('review','review_on'),('estimate','estimate_minutes'),('complexity','complexity')]:
|
||||||
value=getattr(a,attr)
|
value=getattr(a,attr)
|
||||||
if value is not None:payload[key]=task_project(client,value) if attr=='project' else value
|
if value is not None:payload[key]=task_project(client,value) if attr=='project' else value
|
||||||
|
# A retry of the same pending mail must not drift across a month boundary
|
||||||
|
# when Date was missing. Other changed options still fail closed.
|
||||||
|
old=profile.data.get('task_outbox',{}).get(payload['request_id'])
|
||||||
|
if action=='from-mail' and old and {k:v for k,v in old.items() if k!='wiki_suffix'}=={k:v for k,v in payload.items() if k!='wiki_suffix'}:
|
||||||
|
payload=old.copy()
|
||||||
emit(capture(payload));return
|
emit(capture(payload));return
|
||||||
if action=='project-add':
|
if action=='project-add':
|
||||||
emit(client.json(TASK_API+'items',method='POST',data={'uuid':str(uuid.uuid4()),'kind':'project','title':a.title,'notes':a.notes,'status':'todo','bucket':'inbox','priority':1}));return
|
emit(client.json(TASK_API+'items',method='POST',data={'uuid':str(uuid.uuid4()),'kind':'project','title':a.title,'notes':a.notes,'status':'todo','bucket':'inbox','priority':1}));return
|
||||||
|
|||||||
@@ -9,6 +9,39 @@ import unittest
|
|||||||
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||||
|
|
||||||
class ProductivityTests(unittest.TestCase):
|
class ProductivityTests(unittest.TestCase):
|
||||||
|
def test_mail_path_priority_and_dates(self):
|
||||||
|
import datetime,hashlib
|
||||||
|
ident='06cb3a24-61f8-4a9f-a0bf-89eea9632f25'
|
||||||
|
suffix=m['task_mail_suffix'];now=datetime.datetime(2030,2,1,tzinfo=datetime.timezone.utc)
|
||||||
|
for marker in ('[hogehoge 00123]','Re: [hogehoge:123]','Fwd: [hogehoge#123]'):
|
||||||
|
raw=('Subject: '+marker+' Title\r\n\r\nbody').encode()
|
||||||
|
self.assertEqual(suffix(raw,ident,now),'hogehoge/123')
|
||||||
|
raw=b'Subject: Plain\r\nDate: Sat, 31 Jan 2026 23:30:00 -0800\r\nMessage-ID: <id@example.invalid>\r\n\r\nbody'
|
||||||
|
self.assertEqual(suffix(raw,ident,now),'2026/01/'+ident)
|
||||||
|
noid=raw.replace(b'Message-ID: <id@example.invalid>\r\n',b'')
|
||||||
|
self.assertEqual(suffix(noid,ident,now),'2026/01/'+hashlib.sha256(noid).hexdigest())
|
||||||
|
for date in (b'',b'Date: broken\r\n'):
|
||||||
|
raw=b'Subject: [../unsafe 123] Title\r\n'+date+b'\r\nbody'
|
||||||
|
self.assertEqual(suffix(raw,ident,now),'2030/02/'+hashlib.sha256(raw).hexdigest())
|
||||||
|
|
||||||
|
def test_pending_mail_month_and_options_are_preserved(self):
|
||||||
|
from unittest.mock import patch
|
||||||
|
raw=b'Subject: Test\r\nMessage-ID: <same@example.invalid>\r\n\r\nbody'
|
||||||
|
calls=[]
|
||||||
|
def send(route,**kw):
|
||||||
|
calls.append(kw['data'].copy())
|
||||||
|
raise m['Failure']('offline')
|
||||||
|
client=SimpleNamespace(base='https://example.invalid',json=send)
|
||||||
|
profile=SimpleNamespace(data={'username':'test'},save=lambda:None)
|
||||||
|
for month in ('2030/01','2030/02'):
|
||||||
|
with patch.dict(m['tasks'].__globals__,task_mail_suffix=lambda raw,ident:month+'/'+ident),patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw))),contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
|
||||||
|
m['tasks'](client,profile,['from-mail'])
|
||||||
|
self.assertEqual(calls[0],calls[1])
|
||||||
|
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw))),self.assertRaises(m['Failure']):
|
||||||
|
m['tasks'](client,profile,['from-mail','--wiki-prefix','/changed'])
|
||||||
|
self.assertEqual(len(calls),2)
|
||||||
|
self.assertEqual(next(iter(profile.data['task_outbox'].values())),calls[0])
|
||||||
|
|
||||||
def test_mail_privacy_and_long_subject_override(self):
|
def test_mail_privacy_and_long_subject_override(self):
|
||||||
raw=b'Subject: Test\r\nFrom: Person <person@example.invalid>\r\nMessage-ID: <id@example.invalid>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPRIVATE BODY'
|
raw=b'Subject: Test\r\nFrom: Person <person@example.invalid>\r\nMessage-ID: <id@example.invalid>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPRIVATE BODY'
|
||||||
title,notes,ident,body=m['task_mail'](raw)
|
title,notes,ident,body=m['task_mail'](raw)
|
||||||
@@ -16,9 +49,27 @@ class ProductivityTests(unittest.TestCase):
|
|||||||
self.assertIn('PRIVATE BODY',body)
|
self.assertIn('PRIVATE BODY',body)
|
||||||
self.assertIsNone(m['task_mail'](raw,False)[3])
|
self.assertIsNone(m['task_mail'](raw,False)[3])
|
||||||
raw=raw.replace(b'Subject: Test',b'Subject: '+b'a'*301)
|
raw=raw.replace(b'Subject: Test',b'Subject: '+b'a'*301)
|
||||||
with self.assertRaises(m['Failure']):m['task_mail'](raw)
|
self.assertLessEqual(len(m['task_mail'](raw)[0].encode()),300)
|
||||||
|
with self.assertRaises(m['Failure']):m['task_mail'](raw,True,'x'*301)
|
||||||
self.assertEqual(m['task_mail'](raw,False,'Override')[0],'Override')
|
self.assertEqual(m['task_mail'](raw,False,'Override')[0],'Override')
|
||||||
|
|
||||||
|
def test_japanese_subject_and_mailing_list_markers(self):
|
||||||
|
from email.message import EmailMessage
|
||||||
|
from email.header import Header
|
||||||
|
for encoding in ('utf-8','iso-2022-jp'):
|
||||||
|
subject='Re: [hogehoge 00123] [team:456] 日本語の依頼 [重要]'
|
||||||
|
raw=('Subject: '+Header(subject,encoding).encode()+'\r\nMessage-ID: <same@example.invalid>\r\n\r\nbody').encode('ascii')
|
||||||
|
title,notes,ident,body=m['task_mail'](raw)
|
||||||
|
self.assertEqual(title,'Re: 日本語の依頼 [重要]')
|
||||||
|
self.assertEqual(ident,'<same@example.invalid>');self.assertIn('Subject: '+subject,body)
|
||||||
|
for subject in ('[重要] 日本語','報告 [list 123]','[release 1.2] 更新'):
|
||||||
|
self.assertEqual(m['mail_subject'](subject),subject)
|
||||||
|
msg=EmailMessage();msg['Subject']='[list 123] '+('日本語'*100);msg.set_content('Body')
|
||||||
|
title,_,_,body=m['task_mail'](msg.as_bytes())
|
||||||
|
self.assertLessEqual(len(title.encode()),300);self.assertTrue(title.endswith('…'))
|
||||||
|
self.assertIn('日本語'*100,body)
|
||||||
|
self.assertEqual(m['task_mail'](msg.as_bytes(),True,'[list 123] 手動指定')[0],'[list 123] 手動指定')
|
||||||
|
|
||||||
def test_html_mail_and_limits(self):
|
def test_html_mail_and_limits(self):
|
||||||
raw=b'Subject: HTML\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<head><style>secret</style></head><p>Hello</p><script>evil()</script><img src="https://example.invalid/image"><p>World & friends</p>'
|
raw=b'Subject: HTML\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<head><style>secret</style></head><p>Hello</p><script>evil()</script><img src="https://example.invalid/image"><p>World & friends</p>'
|
||||||
body=m['task_mail'](raw)[3]
|
body=m['task_mail'](raw)[3]
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import runpy
|
|||||||
import sys
|
import sys
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
from email.message import EmailMessage
|
||||||
|
|
||||||
def run():
|
def run():
|
||||||
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||||
@@ -29,15 +30,27 @@ def run():
|
|||||||
report=task('report','--json');assert sum(d['points'] for d in report['days'])==7
|
report=task('report','--json');assert sum(d['points'] for d in report['days'])==7
|
||||||
assert any(i['uuid']==ident for i in report['tasks'])
|
assert any(i['uuid']==ident for i in report['tasks'])
|
||||||
task('preferences','--wiki-prefix','/private/mail')
|
task('preferences','--wiki-prefix','/private/mail')
|
||||||
mail=b'Subject: CLI mail\r\nMessage-ID: <integration@example.invalid>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPrivate mail body {{children}}'
|
message=EmailMessage();message['Subject']='[hogehoge 123] 日本語の件名と依頼';message['Message-ID']='<integration@example.invalid>';message.set_content('Private mail body {{children}}')
|
||||||
|
mail=message.as_bytes()
|
||||||
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(mail))):
|
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(mail))):
|
||||||
captured=task('from-mail')
|
captured=task('from-mail')
|
||||||
assert captured['item']['page_uuid'] and captured['page_path'].startswith('/private/mail/CLI mail--')
|
assert captured['item']['page_uuid'] and captured['page_path']=='/private/mail/hogehoge/123'
|
||||||
|
assert captured['item']['title']=='日本語の件名と依頼'
|
||||||
assert 'Private mail body' not in captured['item']['notes']
|
assert 'Private mail body' not in captured['item']['notes']
|
||||||
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(mail))):
|
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(mail))):
|
||||||
assert task('from-mail')['item']['page_uuid']==captured['item']['page_uuid']
|
assert task('from-mail')['item']['page_uuid']==captured['item']['page_uuid']
|
||||||
note=client.json(m['TASK_API']+'items/'+captured['item']['uuid']+'/note')
|
note=client.json(m['TASK_API']+'items/'+captured['item']['uuid']+'/note')
|
||||||
assert note['linked'] and note['path']==captured['page_path']
|
assert note['linked'] and note['path']==captured['page_path']
|
||||||
|
raw,_=client.raw('path:'+captured['page_path'])
|
||||||
|
assert '日本語の件名と依頼' in raw.decode() and 'Private mail body' in raw.decode()
|
||||||
|
message.replace_header('Subject','連番なしの日本語');message.replace_header('Message-ID','<other@example.invalid>');message['Date']='Sat, 31 Jan 2026 23:30:00 -0800'
|
||||||
|
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(message.as_bytes()))):dated=task('from-mail')
|
||||||
|
assert dated['page_path']=='/private/mail/2026/01/'+dated['item']['uuid']
|
||||||
|
del message['Message-ID']
|
||||||
|
import hashlib
|
||||||
|
raw_mail=message.as_bytes()
|
||||||
|
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw_mail))):hashed=task('from-mail')
|
||||||
|
assert hashed['page_path']=='/private/mail/2026/01/'+hashlib.sha256(raw_mail).hexdigest()
|
||||||
path=Path(fixture['root'])/'person.vcf'
|
path=Path(fixture['root'])/'person.vcf'
|
||||||
path.write_text('BEGIN:VCARD\r\nVERSION:4.0\r\nUID:urn:test:cli\r\nFN:CLI Person\r\nEMAIL:cli@example.invalid\r\nEND:VCARD\r\n')
|
path.write_text('BEGIN:VCARD\r\nVERSION:4.0\r\nUID:urn:test:cli\r\nFN:CLI Person\r\nEMAIL:cli@example.invalid\r\nEND:VCARD\r\n')
|
||||||
output=io.StringIO()
|
output=io.StringIO()
|
||||||
|
|||||||
Reference in new issue
Block a user