7 Commits
Author SHA1 Message Date
Anya Tokugawa a7ef59f8c0 release: bump version to 0.6.0
Test and release pages-cli / linux (push) Successful in 4s
Test and release pages-cli / macos (push) Skipped
2026-11-30 21:31:25 +09:00
Anya Tokugawa 9b685b72da feat: opt-in OIDC browser open, atomic page creation, and conflict recovery
- Default pages login --oidc to not auto-open a browser and replace --no-browser with --with-open-browser
- Add atomic new Path/Page creation (PUT /_/api/v1/pages/path:... with If-None-Match: *) in pages edit with confirmation and und warning
- Add interactive 409/412 conflict resolution and pages recover (--list, --edit, --discard)
- Update tests, docs (README.md, DISTRIBUTION.md, docs/client-contract.md, docs/neomutt.md), and macOS CI unittest list
2026-11-30 21:26:57 +09:00
Anya Tokugawa bee03094f3 feat(auth): support explicit trusted login and expired session recovery
Test and release pages-cli / linux (push) Successful in 9s
Test and release pages-cli / macos (push) Skipped
2026-11-08 20:29:10 +09:00
Anya Tokugawa e27c023d66 fix: explicitly recreate deleted task captures
Test and release pages-cli / linux (push) Successful in 19s
Test and release pages-cli / macos (push) Skipped
2026-11-08 19:26:51 +09:00
Anya Tokugawa bd54b5f06a fix: replace retained task drafts with current input
Test and release pages-cli / linux (push) Successful in 10s
Test and release pages-cli / macos (push) Skipped
2026-11-08 18:48:44 +09:00
Anya Tokugawa e22af6a0ec feat: route mail by mailing-list sequence or year and month
Test and release pages-cli / linux (push) Successful in 22s
Test and release pages-cli / macos (push) Skipped
2026-11-06 09:50:09 +09:00
Anya Tokugawa 541c2bd069 fix: normalize mailing-list subjects and preserve long Japanese titles
Test and release pages-cli / linux (push) Successful in 31s
Test and release pages-cli / macos (push) Skipped
2026-11-06 09:01:46 +09:00
14 changed files with 1344 additions and 95 deletions

No files matched your search

+1 -1
View File
@@ -45,7 +45,7 @@ jobs:
python3 -m venv .venv python3 -m venv .venv
. .venv/bin/activate . .venv/bin/activate
python -m pip install -r requirements-build.txt python -m pip install -r requirements-build.txt
python -m unittest test_pages test_productivity test_distribution test_tls python -m unittest test_pages test_productivity test_distribution test_tls test_remember
python tools/build.py python tools/build.py
python tools/smoke_binary.py dist/pages python tools/smoke_binary.py dist/pages
PAGES_CLI_TEST_BINARY="$PWD/dist/pages" python -m unittest test_tls PAGES_CLI_TEST_BINARY="$PWD/dist/pages" python -m unittest test_tls
+2 -2
View File
@@ -18,8 +18,8 @@ rpm/debは初期配布の必須条件にせず、LinuxはELFを提供する。Py
```sh ```sh
# ダウンロード先で実行。手元にあるファイルをチェックする。 # ダウンロード先で実行。手元にあるファイルをチェックする。
sha256sum --ignore-missing -c pages-cli-v0.3.0-linux-amd64-SHA256SUMS sha256sum --ignore-missing -c pages-cli-v0.6.0-linux-amd64-SHA256SUMS
tar -xzf pages-cli-v0.3.0-linux-amd64.tar.gz tar -xzf pages-cli-v0.6.0-linux-amd64.tar.gz
mkdir -p ~/.local/bin mkdir -p ~/.local/bin
install -m 755 pages ~/.local/bin/pages install -m 755 pages ~/.local/bin/pages
pages --version pages --version
+1 -1
View File
@@ -6,6 +6,6 @@ ENV SOURCE_REVISION=$SOURCE_REVISION
COPY requirements-build.txt . COPY requirements-build.txt .
RUN pip install --no-cache-dir -r requirements-build.txt RUN pip install --no-cache-dir -r requirements-build.txt
COPY . . COPY . .
RUN python -m unittest test_pages test_productivity test_distribution test_tls && python tools/build.py && python tools/smoke_binary.py dist/pages && PAGES_CLI_TEST_BINARY=/src/dist/pages python -m unittest test_tls RUN python -m unittest test_pages test_productivity test_distribution test_tls test_remember && python tools/build.py && python tools/smoke_binary.py dist/pages && PAGES_CLI_TEST_BINARY=/src/dist/pages python -m unittest test_tls
FROM scratch AS artifacts FROM scratch AS artifacts
COPY --from=build /src/release/ / COPY --from=build /src/release/ /
+29 -12
View File
@@ -53,9 +53,23 @@ pages -k logout
**自己署名証明書だけでなく、期限切れやホスト名不一致も許容します。通信は暗号化されますが、相手の真正性を確認できず、中間者攻撃でパスワード・Bearer・文書等を盗み見られる危険があります。** 信頼できる検証環境でのみ明示指定し、常用する環境では信頼するCAをOSへ登録して通常の検証を使ってください。遠隔HTTP、リダイレクト追従、TLS失敗時の自動再送は引き続き許可しません。 **自己署名証明書だけでなく、期限切れやホスト名不一致も許容します。通信は暗号化されますが、相手の真正性を確認できず、中間者攻撃でパスワード・Bearer・文書等を盗み見られる危険があります。** 信頼できる検証環境でのみ明示指定し、常用する環境では信頼するCAをOSへ登録して通常の検証を使ってください。遠隔HTTP、リダイレクト追従、TLS失敗時の自動再送は引き続き許可しません。
OIDCでは `pages -k login --oidc --no-browser` のように指定できます。ただし、スキップするのはCLIのHTTPS要求のみです。開いたブラウザやOIDCプロバイダーの証明書検証は変更しません。 OIDCでは `pages -k login --oidc`(または `pages -k login --oidc --with-open-browser`)のように指定できます。ただし、スキップするのはCLIのHTTPS要求のみです。開いたブラウザやOIDCプロバイダーの証明書検証は変更しません。
### OIDCでログインする ### 信頼できる端末でログインを維持する
v0.5.0以降では、対応サーバーと組み合わせて最長30日のログインを選択できます。
```sh
pages login --remember
pages login --oidc --remember
```
実際の期限はサーバー管理者の設定に従います。旧サーバーでは通常の期限になる場合があります。
パスワード認証のTOTP、ログアウト、管理者による失効、アカウント停止は従来どおり有効です。
共有端末では使用しないでください。アクセスによる期限の自動延長は行いません。
期限切れ後はlogoutなしで再ログインでき、同じアカウントの作業パスと未送信タスク下書きを保持します。
### OIDC認証の手順
OIDC連携を有効にしたDomainで利用します。サーバーは **v0.3.0以降** が必要です。独立版CLI v0.1.0は対応済みです(分離前のCLIではサーバー同梱版v0.3.0以降)。 OIDC連携を有効にしたDomainで利用します。サーバーは **v0.3.0以降** が必要です。独立版CLI v0.1.0は対応済みです(分離前のCLIではサーバー同梱版v0.3.0以降)。
CLIのファイルだけを更新しても、v0.2.xのサーバーでは利用できません。 CLIのファイルだけを更新しても、v0.2.xのサーバーでは利用できません。
@@ -63,8 +77,8 @@ CLIのファイルだけを更新しても、v0.2.xのサーバーでは利用
```sh ```sh
pages configure --origin https://pages.example.test pages configure --origin https://pages.example.test
pages login --oidc pages login --oidc
# SSH先など、ブラウザを自動で開かない場合 # ブラウザを自動で開く場合
pages login --oidc --no-browser pages login --oidc --with-open-browser
``` ```
CLIに表示されたURLを手元のPC/スマホで開き、OIDCでログインします。 CLIに表示されたURLを手元のPC/スマホで開き、OIDCでログインします。
@@ -83,7 +97,7 @@ OIDCプロバイダーのパスワードやトークンをターミナルに入
`CLI OIDC login is unavailable on this server` は開始APIが利用できない場合の表示です。 `CLI OIDC login is unavailable on this server` は開始APIが利用できない場合の表示です。
configureの接続先URLを確認し、サーバーも対応版へ更新してください。 configureの接続先URLを確認し、サーバーも対応版へ更新してください。
`OIDC login is not enabled for this domain` の場合は、対象DomainのOIDC設定を確認してください。 `OIDC login is not enabled for this domain` の場合は、対象DomainのOIDC設定を確認してください。
`--no-browser` はブラウザーの自動起動だけを抑止し、承認待ちとセッション取得は通常どおり行います。 既定では `pages login --oidc` はURLを表示するだけでブラウザを自動起動しません。`--with-open-browser` を指定するとブラウザの自動起動を試み、失敗した場合も表示されたURLからそのまま承認できます。
## 設定する ## 設定する
@@ -138,8 +152,9 @@ OSの言語からは推測しません。最初に名前付きプロファイル
| `ls` / `cd` / `pwd` | Semantic Pathをたどる。仮想フォルダにも移動可能 | | `ls` / `cd` / `pwd` | Semantic Pathをたどる。仮想フォルダにも移動可能 |
| `cat` / `view` | 正本の出力/`$PAGER`で閲覧 | | `cat` / `view` | 正本の出力/`$PAGER`で閲覧 |
| `get ADDRESS LOCAL` | 正本をダウンロード。既存のローカルファイルは上書きしない | | `get ADDRESS LOCAL` | 正本をダウンロード。既存のローカルファイルは上書きしない |
| `edit ADDRESS` | `$EDITOR`で編集。Wikiはauthoring Markdown、他のテキストは原文 | | `edit ADDRESS` | `$EDITOR`で編集。未存在Pathは確認後に新規作成。Wikiはauthoring Markdown、他のテキストは原文 |
| `put LOCAL ADDRESS --base REVISION_UUID` | 明示した基点RevisionとのCASで更新 | | `put LOCAL ADDRESS --base REVISION_UUID` | 明示した基点RevisionとのCASで更新 |
| `recover [PATH]` | 退避された原稿の一覧表示・再開・破棄(`--list` / `--edit` / `--discard`) |
| `search QUERY` | 権限付きの検索候補 | | `search QUERY` | 権限付きの検索候補 |
| `open ADDRESS` | ブラウザで閲覧。ブラウザ側ログインを使用 | | `open ADDRESS` | ブラウザで閲覧。ブラウザ側ログインを使用 |
| `status` / `logout` | 接続状態表示/セッション失効 | | `status` / `logout` | 接続状態表示/セッション失効 |
@@ -152,9 +167,9 @@ Tab補完、上下キーのプロセス内履歴に対応。複雑な引用位
`auto` 言語選択と未作成言語版の編集は、独立版CLI v0.1.0で利用できます(分離前はサーバー同梱版v0.4.0以降)。 `auto` 言語選択と未作成言語版の編集は、独立版CLI v0.1.0で利用できます(分離前はサーバー同梱版v0.4.0以降)。
```sh ```sh
pages edit /guide --lang auto # 表示される言語の最新版を編集 pages edit /guide --lang auto # 表示される言語の最新版を編集(未存在時は確認後にundで新規作成)
pages edit /guide --lang ja # 日本語版。未作成なら既存内容から開始 pages edit /guide --lang ja # 日本語版。既存Pageなら既存内容から開始、未存在なら新規作成
pages edit /guide --lang en # 英語版。未作成なら既存内容から開始 pages edit /guide --lang en # 英語版。既存Pageなら既存内容から開始、未存在なら新規作成
``` ```
編集開始時に対象言語を表示します。指定言語のRevisionがない場合は、表示中の版の内容を 編集開始時に対象言語を表示します。指定言語のRevisionがない場合は、表示中の版の内容を
@@ -162,19 +177,21 @@ pages edit /guide --lang en # 英語版。未作成なら既存内容から
自動翻訳ではありません。元の言語版は変更せず、編集せずに閉じた場合は何も作成しません。 自動翻訳ではありません。元の言語版は変更せず、編集せずに閉じた場合は何も作成しません。
同じ言語版が先に作成された場合も、競合として保存を止めます。 同じ言語版が先に作成された場合も、競合として保存を止めます。
対応範囲は既存Pageの更新と新規言語版の作成です。新規Path/Page作成、バイナリ更新は未実装です。 指定したPathが存在しない場合(または `create`-only 権限で読取不可の場合)は、新規Pageとして作成するか確認プロンプトを表示してから `$EDITOR` を開きます(`--lang auto` のまま作成する場合は `und` になる旨の警告を表示します)。空のまま閉じた場合は作成しません。新規Path/Page作成には `PUT /_/api/v1/pages/path:...` に対応したサーバーが必要です。バイナリ更新は未実装です。
競合や通信断で自動上書きせず、ローカル原稿を保持します。HTTPS必須(開発用loopbackのみHTTP可)。 保存時に競合(更新時 `409`、新規作成時 `412`)が起きた場合は差分を表示し、対話環境ではマージ編集・最新headへの保存・別Path選択・ローカル保持を選択できます(非対話時は保持して停止)。通信断等で保持された原稿は `pages recover --list` で確認し、`pages recover PATH` で再開または `--discard` で破棄できます。HTTPS必須(開発用loopbackのみHTTP可)。
詳しいURI・保存・安全性の契約は[クライアント契約](docs/client-contract.md)を参照してください。 詳しいURI・保存・安全性の契約は[クライアント契約](docs/client-contract.md)を参照してください。
## テスト ## テスト
```sh ```sh
python3 -m unittest test_pages test_productivity test_distribution test_tls python3 -m unittest test_pages test_productivity test_distribution test_tls test_remember
``` ```
合成サーバーと一時ディレクトリのみを使用します。TLS試験には一時証明書を生成するOpenSSLコマンドが必要です。本番資格情報や外部カレンダーは不要です。Goサーバーとの結合テストはサーバーリポジトリ側で実行します。 合成サーバーと一時ディレクトリのみを使用します。TLS試験には一時証明書を生成するOpenSSLコマンドが必要です。本番資格情報や外部カレンダーは不要です。Goサーバーとの結合テストはサーバーリポジトリ側で実行します。
## タスクと連絡先 ## タスクと連絡先
v0.4.0のメール保存先はML連番があれば `親Path/リスト名/連番`、なければ `親Path/YYYY/MM/識別子` です。この方式にはサーバーv0.9.0以降が必要です。年月・衝突・旧版からの再送の規則は下記NeoMuttガイドを参照してください。
v0.3.0の `pages task from-mail` は本文を関連Wikiへ保存します(サーバーv0.8.0以降)。先に `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` で閲覧制限済みの親Pathを指定してください。タスクの公開範囲とは独立して、本文はWikiの権限に従います。本文を送信しない場合は `--metadata-only` を指定します。 v0.3.0の `pages task from-mail` は本文を関連Wikiへ保存します(サーバーv0.8.0以降)。先に `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` で閲覧制限済みの親Pathを指定してください。タスクの公開範囲とは独立して、本文はWikiの権限に従います。本文を送信しない場合は `--metadata-only` を指定します。
`pages task --help` で作成・計画・開始/終了・レポートを操作できる。 `pages task --help` で作成・計画・開始/終了・レポートを操作できる。
+1 -1
View File
@@ -1 +1 @@
0.3.0 0.6.0
+25 -5
View File
@@ -8,7 +8,7 @@ pages-cliはPagesWikiのHTTPクライアントであり、DBやDocument Storeを
`-k` 使用時もHTTPはloopbackでの開発専用。originにuserinfo、Path、query、fragmentを含めず、リダイレクトには追従しない。ログイン画面のHTMLや302/303をAPIの成功として扱わない。 `-k` 使用時もHTTPはloopbackでの開発専用。originにuserinfo、Path、query、fragmentを含めず、リダイレクトには追従しない。ログイン画面のHTMLや302/303をAPIの成功として扱わない。
パスワードログインでは必要に応じてTOTPを入力する。`login --oidc [--no-browser]` ではブラウザのOIDCログイン後に、ターミナルの確認コードを入力して承認する。S256でCLIのverifierに束縛し、短期リクエストを一度だけBearerセッションへ交換する。SSH先から開始し、別端末で承認できる。ブラウザCookie、外部OIDC token、Campus用PSKをCLIのBearerとして流用しない。 パスワードログインでは必要に応じてTOTPを入力する。`login --oidc [--with-open-browser]` ではブラウザのOIDCログイン後に、ターミナルの確認コードを入力して承認する(既定ではブラウザを自動起動せず、`--with-open-browser` 指定時のみ開く)。S256でCLIのverifierに束縛し、短期リクエストを一度だけBearerセッションへ交換する。SSH先から開始し、別端末で承認できる。ブラウザCookie、外部OIDC token、Campus用PSKをCLIのBearerとして流用しない。
OIDC入口はサーバーv0.3.0以降。OIDCで認証した利用者への追加ローカルTOTP省略と新規言語版の編集はサーバーv0.4.0以降。タスク・連絡先を含む独立CLIの利用基準はサーバーv0.6.0以降。独立CLIとサーバーのバージョン番号は連動しない。 OIDC入口はサーバーv0.3.0以降。OIDCで認証した利用者への追加ローカルTOTP省略と新規言語版の編集はサーバーv0.4.0以降。タスク・連絡先を含む独立CLIの利用基準はサーバーv0.6.0以降。独立CLIとサーバーのバージョン番号は連動しない。
@@ -24,9 +24,13 @@ Pathは到達経路、UUIDはPageの識別子、Revisionは履歴。正本は `/
編集開始時にObject UUIDと保存先言語、基点Revisionを確定する。`auto` は表示されたRevisionの言語を採用する。明示した言語のheadがなければ既存言語の内容を下書きとして開き、空の基点で新規言語版をCAS保存する。自動翻訳はしない。無変更なら作成しない。編集途中でPathが変わっても別Pageへ保存しない。 編集開始時にObject UUIDと保存先言語、基点Revisionを確定する。`auto` は表示されたRevisionの言語を採用する。明示した言語のheadがなければ既存言語の内容を下書きとして開き、空の基点で新規言語版をCAS保存する。自動翻訳はしない。無変更なら作成しない。編集途中でPathが変わっても別Pageへ保存しない。
`$EDITOR` はshellを介さず起動する。作業ファイルは0700の一時ディレクトリ内へ0600で保存し、成功・無変更時は削除する。通信断や競合時は原稿と復旧メタデータを保持して場所を表示する。復旧メタデータにBearerを入れない。競合時は差分を示して停止し、自動マージ・強制上書き・保存要求の自動再送は行わない。 `path:/...`(ルート `/` を除く)を `edit` で開いた際、対象Pathが未存在(`404`)または読取不可(`403`:create-only権限の可能性)の場合は、新規Pageとして作成するか確認プロンプトを出してから `$EDITOR` を開く(非対話標準入力では安全のため中止する)。プロファイル言語が `auto` のまま新規作成する場合は `WARNING` を標準エラーへ出して `und` で作成する。`--lang TAG` を指定した場合はその言語で作成する。空のまま編集を終えた場合は送信しない。
`put` は既存言語の基点を `--base` で指定する。新規Path/Page、バイナリ編集、Asset更新は未対応。Revisionアドレスは取得専用。ブラウザで `open` する際はブラウザ自身のログインを使い、共有リンクを自動発行しない。 `$EDITOR` はshellを介さず起動する。作業ファイルは0700の一時ディレクトリ内へ0600で保存し、成功・無変更時は削除する。通信断や競合(更新時 `409`、新規作成時 `412`)時は原稿と復旧メタデータを保持して場所を表示する。復旧メタデータにBearerを入れない。競合時は差分を示し、対話端末では `[e]` 競合マーカー付き編集(マーカー残存時は保存を拒否)・`[f]` 最新headへの明示保存(更新時)・`[p]` 別Path選択(`412` 時)・`[k]` ローカル保持のいずれかを選べる(非対話時は常にローカル保持で停止)。自動マージ・無断強制上書き・保存要求の自動再送は行わない。
保持された原稿は `pages recover` で一覧(`--list`)・再編集(`--edit`)・再開・破棄(`--discard`)できる。`recover` はディレクトリ0700/ファイル0600・所有者・シンボリックリンク非使用・`origin` 一致・CAS基点(`base_revision_uuid`)の再照合を検査する。
`put` は既存言語の基点を `--base` で指定する。`uuid:`・`rev:`・`/` からの新規作成、バイナリ編集、Asset更新は未対応。Revisionアドレスは取得専用。ブラウザで `open` する際はブラウザ自身のログインを使い、共有リンクを自動発行しない。
## HTTP API ## HTTP API
@@ -40,14 +44,30 @@ Pathは到達経路、UUIDはPageの識別子、Revisionは履歴。正本は `/
| 正本・識別子 | GET/HEAD `/v/raw/{explicit-address}` | | 正本・識別子 | GET/HEAD `/v/raw/{explicit-address}` |
| 編集状態 | GET `/_/api/v1/editor/state` | | 編集状態 | GET `/_/api/v1/editor/state` |
| HTMLへの復帰 | POST `/_/api/v1/render/markdown`、authoring=true、projection=false | | HTMLへの復帰 | POST `/_/api/v1/render/markdown`、authoring=true、projection=false |
| CAS保存 | POST `/_/api/v1/revisions/save` | | CAS保存(既存Page) | POST `/_/api/v1/revisions/save` |
| 原子的作成(新規Path+Page) | PUT `/_/api/v1/pages/path:{semantic-path}` |
| タスク | `/_/api/v1/extension/organizer.tasks/`配下のcapture・items・preferences・work・report | | タスク | `/_/api/v1/extension/organizer.tasks/`配下のcapture・items・preferences・work・report |
| 個人アドレス帳 | `/_/api/v1/extension/organizer.contacts/`配下のitems・import | | 個人アドレス帳 | `/_/api/v1/extension/organizer.contacts/`配下のitems・import |
### 新規Path/Page作成API契約(`PUT /_/api/v1/pages/path:...`)
Viewer面(`/...`)や非正規Projection面(`/v/raw/...`)と分離されたAPI面で、正式なHTTP `PUT` により住所(Path)・Page UUID・初回Revision・不変Documentを原子的に作成する。
- **URI**: `PUT /_/api/v1/pages/path:<UTF-8 percent-encoded semantic path>`(ルート `/`、予約プレフィックス、`..`、`uuid:`/`rev:` は不可)
- **リクエストヘッダ**:
- `Authorization: Bearer <token>`
- `If-None-Match: *`(必須。未指定時は `428 Precondition Required`、既存在/並行作成競合時は `412 Precondition Failed`)
- `Content-Type`: 保存する正本のMIME型(Markdown編集時は先に `POST /_/api/v1/render/markdown` でHTML正本化し `text/html; charset=utf-8` を送信、`--format raw` 時は `text/plain; charset=utf-8`)
- `Content-Language`: BCP 47言語タグ(`auto` 時は `und`)
- `X-PagesWiki-Commit-Message` / `X-PagesWiki-Filename`: 任意(UTF-8 RFC 3986 percent-encoding、空白は `%20`)
- **リクエストボディ**: 正本バイト列そのもの(JSONで包まない。テキスト上限1 MiB)
- **成功応答(`201 Created`)**: `X-PagesWiki-Object-UUID`、`X-PagesWiki-Revision-UUID`、`X-PagesWiki-Document-SHA256`(64桁小文字hex)、`Content-Language`、`ETag`、`Location`、`Cache-Control: private, no-store`
- **エラー応答**: `400`(不正Path・不正言語・非対応MIME)、`401`(未認証)、`403`(存在チェックより先に評価する `create` 権限不足)、`404`/`405`/`501`(未対応サーバー)、`412`(Path既存・並行衝突)、`413`(サイズ上限超過)、`428`(`If-None-Match: *` 欠落)
## 上限と検証 ## 上限と検証
ネットワークには20秒のsocket timeoutと応答サイズ上限がある。総転送時間の厳密なdeadlineや巨大転送のstreamingは未対応。`get` は最大64 MiB、SHA-256を照合し、新規0600ファイルへ出力する。既存ファイルは上書きしない。編集テキストは1 MiB、JSON送信は2 MiBまで。 ネットワークには20秒のsocket timeoutと応答サイズ上限がある。総転送時間の厳密なdeadlineや巨大転送のstreamingは未対応。`get` は最大64 MiB、SHA-256を照合し、新規0600ファイルへ出力する。既存ファイルは上書きしない。編集テキストは1 MiB、JSON送信は2 MiBまで。
メール取り込みは1通2 MiB、本文は明示指定時のみ、保持するメモは16 KiBまで。再送用要求は最大20件。連絡先importは1枚のUTF-8 vCard、64 KiBまで。NeoMutt検索は本人・Domain内の個人アドレス帳を対象とし、最大100件を返す。 メール取り込みは1通2 MiB、本文は明示指定時のみ、保持するメモは16 KiBまで。再送用要求は最大20件。連絡先importは1枚のUTF-8 vCard、64 KiBまで。NeoMutt検索は本人・Domain内の個人アドレス帳を対象とし、最大100件を返す。
CLIの単体・実バイナリ試験は合成データのみを使用する。サーバー側の権限・CAS・OIDC署名検証とGoのHTTP結合テストはPagesWikiリポジトリで管理する。Windowsの資格情報保護とロック移植、新規Page作成、競合の対話的復旧、巨大ファイル転送は後続タスク。 CLIの単体・実バイナリ試験は合成データのみを使用する。サーバー側の権限・CAS・OIDC署名検証とGoのHTTP結合テストはPagesWikiリポジトリで管理する。新規Page作成には `PUT /_/api/v1/pages/path:...` に対応したサーバーが必要。Windowsの資格情報保護とロック移植、巨大ファイル転送は後続タスク。
+46 -4
View File
@@ -4,7 +4,7 @@
```sh ```sh
pages configure --origin https://pages.example.test --username YOUR_USERNAME pages configure --origin https://pages.example.test --username YOUR_USERNAME
pages login --oidc --no-browser pages login --oidc
pages task preferences --wiki-prefix /private/mail pages task preferences --wiki-prefix /private/mail
pages task --help pages task --help
``` ```
@@ -26,9 +26,23 @@ v0.3.0からは件名をタスク名、From・Date・Message-IDをメモにし
本文の公開範囲は保存先Wikiの権限に従う。タスクが個人用でも、公開Pathに保存した本文は公開され得るため、メール用には閲覧者を制限したPathを指定する。設定例の `/private/mail` という名前自体が非公開を保証するものではない。 本文の公開範囲は保存先Wikiの権限に従う。タスクが個人用でも、公開Pathに保存した本文は公開され得るため、メール用には閲覧者を制限したPathを指定する。設定例の `/private/mail` という名前自体が非公開を保証するものではない。
作成Pathは `親Path/安全化した件名--request_id`。同名件名を区別し、既存ページを上書きしない。タスクのメモ閲覧・編集ボタンから本文ページを開ける。タスク・Wiki・再送receiptは同一トランザクションで保存し、途中失敗で片方だけを残さない。UUIDで紐づくので、その後Wikiを移動しても追従する。 CLI v0.4.0のメール取り込みにはPagesWiki v0.9.0以降が必要。保存先は次の優先順で決める。
plain textを優先し、HTMLしかない場合はテキストを抽出する。添付・外部画像・CSS・JS・外部URLは取得せず、本文中のHTMLやWikiマクロも実行しない。原文EMLやHTMLレイアウトの保存機能ではない。入力1通2 MiB、Wiki本文(メタデータ込み)256 KiB、タスクメモ16 KiBまで。上限超過は切り捨てず拒否する。件名300 UTF-8 bytes超は `--title '短い件名'` を指定する。旧 `--include-body` は既定動作の別名として残す。以前の本文非送信動作には `--metadata-only` を使う。 | メール | 保存先 |
| --- | --- |
| 先頭にML連番がある | `親Path/リスト名/連番`(例:`/mail/hogehoge/123`) |
| ML連番なし、Message-IDあり | `親Path/YYYY/MM/UUID` |
| 両方なし | `親Path/YYYY/MM/原文SHA-256` |
リスト名はASCII英数字で始まり、英数字・ピリオド・ハイフン・アンダースコアの100文字以内。連番は最大20桁で、先頭ゼロを除去する。Re:/Fw:/Fwd:の直後も認識し、先頭のML表記を使う。安全なリスト名・連番として解釈できない場合は年月方式へフォールバックする。表示件名の `--title` は保存先の判定を変えない。
年月はDateヘッダに記載されたタイムゾーンの年月。Dateが欠落・不正なら最初の取り込み時点のUTC年月を使い、未送信outboxに確定値を保持する。UUIDは接続先・本人・Message-IDから生成し、Message-ID自体をURLへ露出しない。同じML名・連番に異なるメールが来た場合は409で停止し、既存本文を上書きしない。
既存ページは移動・上書きせず、従来形式で保存済みの要求をretryしても元のページを返す。タスクのメモ閲覧・編集ボタンから本文ページを開ける。タスク・Wiki・再送receiptは同一トランザクションで保存し、途中失敗で片方だけを残さない。UUIDで紐づくので、その後Wikiを移動しても追従する。
CLI v0.3.1ではMIMEヘッダを復号した件名の先頭から `[list 123]`・`[list:123]`・`[list#123]` のような連番を除去する。Re:/Fwd:は維持し、その後の連番も除去する。`[重要]`、件名の途中の括弧、`--title` で明示した件名は変更しない。自動件名が300 UTF-8 bytesを超える場合は文字境界で省略して末尾に「…」を付ける。除去・省略・手動指定で変わった元のSubjectはWiki本文に残す。手動件名の上限超過は拒否する。
plain textを優先し、HTMLしかない場合はテキストを抽出する。添付・外部画像・CSS・JS・外部URLは取得せず、本文中のHTMLやWikiマクロも実行しない。原文EMLやHTMLレイアウトの保存機能ではない。入力1通2 MiB、Wiki本文(メタデータ込み)256 KiB、タスクメモ16 KiBまで。本文・メモの上限超過は切り捨てず拒否する。旧 `--include-body` は既定動作の別名として残す。以前の本文非送信動作には `--metadata-only` を使う。
同じ接続・本人・Message-IDから同じrequest_idを作るため、同じメールの再取り込みで重複しない。Message-IDなしはメール全体のSHA-256を使う。同じIDで本文・指定Path・オプションを変えると412となり、以前のページを上書きしない。旧版でメタデータのみ取り込み済みのメールに本文を追加する場合は、既存の関連Wikiを編集する。同じメールを別の独立タスクにもしたい場合は `task add` を使う。 同じ接続・本人・Message-IDから同じrequest_idを作るため、同じメールの再取り込みで重複しない。Message-IDなしはメール全体のSHA-256を使う。同じIDで本文・指定Path・オプションを変えると412となり、以前のページを上書きしない。旧版でメタデータのみ取り込み済みのメールに本文を追加する場合は、既存の関連Wikiを編集する。同じメールを別の独立タスクにもしたい場合は `task add` を使う。
@@ -52,7 +66,35 @@ pages task retry REQUEST_UUID
最大20件を保留でき、成功した要求はローカルから削除する。同じ本人への再ログインで保留分を維持する。別アカウントへ切り替える場合は別プロファイルを使う。認証済みセッションがない状態からの完全オフライン入力受付ではない。 最大20件を保留でき、成功した要求はローカルから削除する。同じ本人への再ログインで保留分を維持する。別アカウントへ切り替える場合は別プロファイルを使う。認証済みセッションがない状態からの完全オフライン入力受付ではない。
サーバーで保存された直後に応答が失われても、同じrequest_idで再送すれば既存タスクが返る。保留要求を書き換えて再送すると412になる。セッションファイルにはトークンと保留中のメール本文があるため、デバッグ目的で内容を貼り付けない。保存先未設定で失敗した場合は `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` で設定してからretryする。 CLI v0.4.1以降では、同一内容の保留メールを再入力した場合は、確定済みの保存先を維持する。同じrequest_idで本文・件名・オプションを変更して再入力した場合は、ローカルの保留下書きを新しい内容で上書きしてから1回送信する。送信失敗時も新しい内容を保持する。`task add --request-id` も同じ動作。新しいrequest_idを発行して重複タスクを作る処理ではない。
`task retry` は、その時点で保持されている下書きを変更せずに送信する。下書きを上書きするには、NeoMuttから同じメールを改めて取り込むか、同じrequest_idを指定した `task add` を実行する。旧版で保留していた下書きも対象となる。
サーバーにすでに保存済みの同じ要求に対して本文・保存先・オプションが異なる場合は、従来どおり412で停止する。ローカル下書きの上書きは、保存済みタスクやWikiの強制上書きではない。保存済みの内容を変更する場合は通常のタスク/Wiki編集を使う。
サーバーで保存された直後に応答が失われても、同じrequest_id・同じ内容で再送すれば既存タスクが返る。サーバー保存済みの要求と異なる内容で再送すると412になる。セッションファイルにはトークンと保留中のメール本文があるため、デバッグ目的で内容を貼り付けない。保存先未設定で失敗した場合は `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` で設定してからretryする。
### 削除済みタスクを再取り込みする
CLI v0.4.2/PagesWiki v0.14.1以降の機能です。サーバーとCLIの両方の更新が必要で、CLI v0.4.1/PagesWiki v0.14.0では利用できません。
削除後も重複防止の受付記録は残ります。対応サーバーでは、内容の違いにかかわらず削除済み要求を410 `deleted` で拒否します。通常のretryで復活させず、保留下書きを使った再取り込みは次のように明示します。
```sh
pages task retry REQUEST_UUID --recreate-deleted
```
新しいUUIDのタスクを作成し、旧UUIDの削除記録とCalDAVの識別子予約は残します。同じ操作から生成されるUUIDは一定なので、応答が失われても重複作成しません。旧タスクの完了状態・作業記録・サブタスクを復元する操作ではありません。存続中のタスクをこのオプションで上書きすることもできません。
Wiki保存先にページが残っている場合は、本文・リビジョンを上書きせず新しいタスクに再リンクします。ページがなければ保留本文から作ります。本文の変更は通常のWiki編集で行ってください。保存先の現在権限が必要です。保存先は保持したsuffix/指定prefixと現在の既定値で決まり、移動された元ページを自動追跡する機能ではありません。
CLIは送信前に保留下書きを新IDへ移して保存し、`Retry ID:` に新IDを表示します。通信失敗後は新IDを使い、`--recreate-deleted` を付けずに再送します。
```sh
pages task retry NEW_REQUEST_UUID
```
元のメールを再入力するだけでは削除済みの状態を解除しません。受付記録はあるのにタスクと削除記録が両方ない場合は409 `capture_missing` となり、サーバー側の整合性調査が必要です。受付記録・削除記録を手動削除して回避しないでください。
## 計画と実績 ## 計画と実績
+455 -51
View File
@@ -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.6.0'
class Failure(Exception): class Failure(Exception):
def __init__(self, message, status=0, payload=None): def __init__(self, message, status=0, payload=None):
@@ -90,26 +92,30 @@ class Client:
handlers.append(http.HTTPSHandler(context=context)) handlers.append(http.HTTPSHandler(context=context))
self.opener = http.build_opener(*handlers) self.opener = http.build_opener(*handlers)
def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None): def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None, headers=None, expect_status=None):
if not route.startswith('/') or route.startswith('//'): if not route.startswith('/') or route.startswith('//'):
raise Failure('Invalid API route.') raise Failure('Invalid API route.')
headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/' + VERSION} req_headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/' + VERSION}
if headers:
req_headers.update(headers)
if etag is not None: if etag is not None:
headers['If-Match'] = etag req_headers['If-Match'] = etag
if self.token: if self.token:
headers['Authorization'] = 'Bearer ' + self.token req_headers['Authorization'] = 'Bearer ' + self.token
body = None body = None
if data is not None: if data is not None:
body = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode() body = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode()
headers['Content-Type'] = content_type or 'application/json' req_headers['Content-Type'] = content_type or 'application/json'
if form is not None: if form is not None:
body = url.urlencode(form).encode() body = url.urlencode(form).encode()
headers['Content-Type'] = 'application/x-www-form-urlencoded' req_headers['Content-Type'] = 'application/x-www-form-urlencoded'
if body is not None and len(body) > 2 << 20: if body is not None and len(body) > 2 << 20:
raise Failure('Request exceeds the 2 MiB client limit.') raise Failure('Request exceeds the 2 MiB client limit.')
req = http.Request(self.base + route, body, headers, method=method) req = http.Request(self.base + route, body, req_headers, method=method)
try: try:
with self.opener.open(req, timeout=20) as response: with self.opener.open(req, timeout=20) as response:
if expect_status is not None and response.status != expect_status:
raise Failure('Unexpected HTTP status (%d).' % response.status, response.status)
raw = response.read(limit + 1) raw = response.read(limit + 1)
if len(raw) > limit: if len(raw) > limit:
raise Failure('Response exceeds client limit; use the browser for large files.') raise Failure('Response exceeds client limit; use the browser for large files.')
@@ -125,7 +131,8 @@ class Client:
payload = {} payload = {}
messages = {303: 'Login redirect refused; log in again.', 401: 'Session expired or authentication required.', 403: 'Access denied.', messages = {303: 'Login redirect refused; log in again.', 401: 'Session expired or authentication required.', 403: 'Access denied.',
404: 'Not found or not readable.', 409: 'Conflict: remote revision changed.', 404: 'Not found or not readable.', 409: 'Conflict: remote revision changed.',
412: 'Conflict: remote item changed; reload before saving.', 422: 'Invalid fields; check dates, project and required settings.'} 412: 'Conflict: remote item changed; reload before saving.', 422: 'Invalid fields; check dates, project and required settings.',
428: 'Precondition required by server.'}
raise Failure(messages.get(e.code, 'HTTP request failed (%d); redirects are not followed.' % e.code), e.code, payload) from None raise Failure(messages.get(e.code, 'HTTP request failed (%d); redirects are not followed.' % e.code), e.code, payload) from None
except (urllib.error.URLError, TimeoutError, OSError): except (urllib.error.URLError, TimeoutError, OSError):
raise Failure('Connection/TLS failure; no automatic write retry was attempted.') from None raise Failure('Connection/TLS failure; no automatic write retry was attempted.') from None
@@ -142,9 +149,11 @@ class Client:
except (ValueError, UnicodeError): except (ValueError, UnicodeError):
raise Failure('Invalid JSON response.') from None raise Failure('Invalid JSON response.') from None
def login(self, username, password, otp=getpass.getpass): def login(self, username, password, otp=getpass.getpass, *, remember=False):
form={'username':username,'password':password}
if remember:form['remember']='1'
try: try:
result = self.json('/_/auth/login', method='POST', form={'username': username, 'password': password}) result = self.json('/_/auth/login', method='POST', form=form)
except Failure as e: except Failure as e:
if e.status != 401 or not e.payload.get('mfa_required') or not e.payload.get('challenge_token'): if e.status != 401 or not e.payload.get('mfa_required') or not e.payload.get('challenge_token'):
raise raise
@@ -162,12 +171,13 @@ class Client:
self.token = token self.token = token
return time.time() + duration return time.time() + duration
def login_oidc(self, no_browser=False, expected_username='', *, sleep=time.sleep, clock=time.monotonic): def login_oidc(self, open_browser=False, expected_username='', *, remember=False, sleep=time.sleep, clock=time.monotonic):
verifier = secrets.token_urlsafe(32) verifier = secrets.token_urlsafe(32)
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=') challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
try: try:
started = self.json('/_/auth/cli/start', method='POST', form={ form={'code_challenge':challenge,'code_challenge_method':'S256'}
'code_challenge': challenge, 'code_challenge_method': 'S256'}) if remember:form['remember']='1'
started = self.json('/_/auth/cli/start', method='POST', form=form)
except Failure as e: except Failure as e:
if e.status in (404, 405, 501): if e.status in (404, 405, 501):
raise Failure('CLI OIDC login is unavailable on this server. Check the configured server URL and deploy a server version supporting /_/auth/cli/start.', e.status) from None raise Failure('CLI OIDC login is unavailable on this server. Check the configured server URL and deploy a server version supporting /_/auth/cli/start.', e.status) from None
@@ -187,7 +197,7 @@ class Client:
print(self.base + route) print(self.base + route)
print('Confirmation code:', code) print('Confirmation code:', code)
print('Waiting for approval (up to 5 minutes). Ctrl+C cancels locally.', flush=True) print('Waiting for approval (up to 5 minutes). Ctrl+C cancels locally.', flush=True)
if not no_browser: if open_browser:
try: webbrowser.open(self.base + route, new=2) try: webbrowser.open(self.base + route, new=2)
except (webbrowser.Error, OSError): pass # URL remains usable on another device. except (webbrowser.Error, OSError): pass # URL remains usable on another device.
while clock() + interval < deadline: while clock() + interval < deadline:
@@ -276,6 +286,45 @@ class Client:
'base_revision_uuid': state['head_revision_uuid'], 'base_revision_uuid': state['head_revision_uuid'],
'editor_principal_uuid': state['principal_uuid'], 'message': 'Remote CLI edit'}) 'editor_principal_uuid': state['principal_uuid'], 'message': 'Remote CLI edit'})
def create_page(self, addr, text, markdown=False, *, lang=None, content_type=None, filename='', message='Remote CLI create'):
if not addr.startswith('path:') or addr == 'path:/':
raise Failure('New page creation requires a non-root Path.')
if len(text.encode('utf-8')) > 1 << 20:
raise Failure('Text edit exceeds the 1 MiB client limit.')
chosen = self.lang if lang is None else language(lang)
target_lang = 'und' if chosen == 'auto' else chosen
if markdown:
ctype = 'text/html; charset=utf-8'
body_text = self.json('/_/api/v1/render/markdown', method='POST', data={
'markdown': text, 'authoring': True, 'projection': False})['html']
else:
ctype = content_type or 'text/plain; charset=utf-8'
body_text = text
payload = body_text.encode('utf-8')
extra = {'If-None-Match': '*', 'Content-Language': target_lang}
if message:
extra['X-PagesWiki-Commit-Message'] = url.quote(message, safe='-_.,~')
if filename:
extra['X-PagesWiki-Filename'] = url.quote(filename, safe='-_.,~')
route = '/_/api/v1/pages/' + url.quote(addr, safe='/:')
try:
_, resp_headers = self.request(route, method='PUT', data=payload, content_type=ctype, headers=extra, expect_status=201)
except Failure as e:
if e.status in (404, 405, 501):
raise Failure('Atomic page creation (PUT /_/api/v1/pages/path:...) is unavailable on this server. Update the server to a version supporting this endpoint.', e.status, e.payload) from None
if e.status == 412:
raise Failure('Conflict: a page already exists at this Path; reload with pages edit.', 412, e.payload) from None
if e.status == 428:
raise Failure('Server requires a create precondition (If-None-Match: *).', 428, e.payload) from None
raise
object_uuid = resp_headers.get('X-PagesWiki-Object-UUID', '').strip()
revision_uuid = resp_headers.get('X-PagesWiki-Revision-UUID', '').strip()
doc_hash = resp_headers.get('X-PagesWiki-Document-SHA256', '').strip()
saved_lang = resp_headers.get('Content-Language', target_lang).strip() or target_lang
if not object_uuid or not revision_uuid or not re.fullmatch(r'[0-9a-f]{64}', doc_hash):
raise Failure('Invalid page creation response; missing document identity headers.')
return {'status': 'created', 'path': addr[5:], 'object_uuid': object_uuid, 'revision_uuid': revision_uuid, 'document_hash': doc_hash, 'lang': saved_lang}
def private_file(path): def private_file(path):
info = path.lstat() info = path.lstat()
@@ -415,47 +464,336 @@ def configure(words, root=None):
print('Default profile:', data['default_profile']) print('Default profile:', data['default_profile'])
def private_dir(path):
info = path.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
raise Failure('Recovery directory must be owned by you with mode 0700; symlinks are not accepted.')
def run_editor(file):
command = shlex.split(os.environ.get('EDITOR', 'vi'))
if not command or subprocess.run(command + [str(file)], check=False).returncode:
raise Failure('Editor exited unsuccessfully.')
def conflict_buffer(local, remote, head_rev=''):
l = local if (not local or local.endswith('\n')) else local + '\n'
r = remote if (not remote or remote.endswith('\n')) else remote + '\n'
label = 'remote (rev: ' + head_rev + ')' if head_rev else 'remote'
return '<<<<<<< local\n' + l + '=======\n' + r + '>>>>>>> ' + label + '\n'
def has_conflict_markers(text):
return any(line.startswith('<<<<<<< ') or line == '=======' or line.startswith('>>>>>>> ') for line in text.splitlines())
def choose_conflict_action(kind, has_remote=True):
if not sys.stdin.isatty():
return 'k'
if kind == 'update':
prompt = 'Conflict detected. [e]dit with markers, [f]orce-save local on new head, [k]eep local draft and exit [e/f/K]: '
allowed = ('e', 'f', 'k')
elif has_remote:
prompt = 'Path already exists. [e]dit with existing page, [p]ick another path, [k]eep local draft and exit [e/p/K]: '
allowed = ('e', 'p', 'k')
else:
prompt = 'Path already exists (not readable). [p]ick another path, [k]eep local draft and exit [p/K]: '
allowed = ('p', 'k')
try:
choice = input(prompt).strip().lower()
except EOFError:
return 'k'
return choice if choice in allowed else 'k'
def prompt_new_path(cwd='/'):
if not sys.stdin.isatty():
return None
try:
raw = input('New Path (blank to keep draft and exit): ').strip()
except EOFError:
return None
if not raw:
return None
try:
addr = address(raw, cwd)
except Failure as e:
print(safe_text(str(e)), file=sys.stderr)
return None
if not addr.startswith('path:') or addr == 'path:/':
print('Enter a non-root Path.', file=sys.stderr)
return None
return addr
def write_recovery(directory, client, ctx):
metadata = directory / 'recovery.json'
metadata.touch(mode=0o600)
if ctx['creating']:
recovery = {'origin': client.base, 'mode': 'create', 'address': ctx['addr'],
'lang': ctx['lang'], 'format': 'markdown' if ctx['markdown'] else 'raw'}
else:
recovery = {'origin': client.base, 'address': 'uuid:' + ctx['state']['object_uuid'],
'base_revision_uuid': ctx['state']['head_revision_uuid'],
'source_revision_uuid': ctx['state'].get('source_revision_uuid', ''),
'lang': ctx['state']['lang'], 'format': 'markdown' if ctx['markdown'] else 'raw'}
metadata.write_text(json.dumps(recovery))
def commit_edit(client, file, text, ctx, cwd='/'):
while True:
if ctx['creating']:
try:
result = client.create_page(ctx['addr'], text, ctx['markdown'], lang=ctx['lang'])
except Failure as error:
if error.status != 412:
raise
try:
latest = client.snapshot(ctx['addr'], lang=ctx['lang'])
except Failure:
latest = None
remote = ''
if latest is not None:
remote = latest['markdown'] if ctx['markdown'] else latest['body']
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
action = choose_conflict_action('create', has_remote=latest is not None)
if action == 'p':
new_addr = prompt_new_path(cwd)
if not new_addr:
raise
ctx['addr'] = new_addr
continue
if action == 'e' and latest is not None:
ctx['creating'] = False
ctx['state'] = latest
ctx['lang'] = latest['lang']
file.write_text(conflict_buffer(text, remote, latest.get('head_revision_uuid', '')), encoding='utf-8')
run_editor(file)
text = file.read_text(encoding='utf-8')
if has_conflict_markers(text):
print('Conflict markers remain; remove them before saving.', file=sys.stderr)
raise Failure('Conflict markers remain in edited document.', 409) from None
continue
raise
print('Created page:', safe_text(result['path']))
print('Object UUID:', safe_text(result['object_uuid']))
print('Saved revision:', safe_text(result['revision_uuid']))
return result
try:
result = client.save(ctx['state'], text, ctx['markdown'])
except Failure as error:
if error.status != 409:
raise
latest = client.snapshot('uuid:' + ctx['state']['object_uuid'], lang=ctx['state']['lang'])
remote = latest['markdown'] if ctx['markdown'] else latest['body']
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
action = choose_conflict_action('update', has_remote=True)
if action == 'k':
raise
ctx['state'] = latest
if action == 'f':
continue
if action == 'e':
file.write_text(conflict_buffer(text, remote, latest.get('head_revision_uuid', '')), encoding='utf-8')
run_editor(file)
text = file.read_text(encoding='utf-8')
if has_conflict_markers(text):
print('Conflict markers remain; remove them before saving.', file=sys.stderr)
raise Failure('Conflict markers remain in edited document.', 409) from None
continue
raise
print('Saved revision:', safe_text(result['revision_uuid']))
return result
def confirm_create(addr, status):
if not sys.stdin.isatty():
if status == 404:
raise Failure('Not found or not readable (interactive confirmation is required to create a new page).', 404)
raise Failure('Access denied.', 403)
path = safe_text(addr[5:])
if status == 404:
prompt = f'Path {path} does not exist. Create a new page? [y/N]: '
else:
prompt = f'Cannot read {path} (access denied). If you have create-only permission, attempt to create a new page? [y/N]: '
try:
answer = input(prompt)
except EOFError:
return False
return answer.strip().lower() in ('y', 'yes')
def editor(client, addr, mode): def editor(client, addr, mode):
state = client.snapshot(addr) creating = False
print('Editing language:', safe_text(state['lang'])) state = None
if state.get('new_language'): try:
print('Creating a new language revision; source remains unchanged:', safe_text(state.get('source_language', '(empty)'))) state = client.snapshot(addr)
markdown = mode == 'markdown' or (mode == 'auto' and state['content_type'].startswith('text/html')) except Failure as error:
initial = state['markdown'] if markdown else state['body'] if error.status in (404, 403) and addr.startswith('path:') and addr != 'path:/':
if not confirm_create(addr, error.status):
print('Aborted.')
return
creating = True
if client.lang == 'auto':
lang = 'und'
print("WARNING: Creating a new page with language 'und' (profile language is 'auto'). Use --lang TAG to specify an explicit language.", file=sys.stderr)
else:
lang = client.lang
print('Creating new page:', safe_text(addr[5:]))
print('Editing language:', safe_text(lang))
markdown = mode in ('auto', 'markdown')
initial = ''
else:
raise
if not creating:
lang = state['lang']
print('Editing language:', safe_text(lang))
if state.get('new_language'):
print('Creating a new language revision; source remains unchanged:', safe_text(state.get('source_language', '(empty)')))
markdown = mode == 'markdown' or (mode == 'auto' and state['content_type'].startswith('text/html'))
initial = state['markdown'] if markdown else state['body']
directory = Path(tempfile.mkdtemp(prefix='pageswiki-edit-')) directory = Path(tempfile.mkdtemp(prefix='pageswiki-edit-'))
file = directory / ('document.md' if markdown else 'document.txt') file = directory / ('document.md' if markdown else 'document.txt')
file.touch(mode=0o600) file.touch(mode=0o600)
file.write_text(initial, encoding='utf-8') file.write_text(initial, encoding='utf-8')
ctx = {'creating': creating, 'addr': addr, 'state': state, 'lang': lang, 'markdown': markdown}
success = False success = False
try: try:
command = shlex.split(os.environ.get('EDITOR', 'vi')) run_editor(file)
if not command or subprocess.run(command + [str(file)], check=False).returncode:
raise Failure('Editor exited unsuccessfully.')
text = file.read_text(encoding='utf-8') text = file.read_text(encoding='utf-8')
if text == initial: if text == initial:
print('Unchanged.') print('Unchanged; page was not created.' if creating else 'Unchanged.')
else: else:
try: commit_edit(client, file, text, ctx)
result = client.save(state, text, markdown)
except Failure as error:
if error.status == 409:
latest = client.snapshot('uuid:' + state['object_uuid'], lang=state['lang'])
remote = latest['markdown'] if markdown else latest['body']
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
raise
print('Saved revision:', safe_text(result['revision_uuid']))
success = True success = True
finally: finally:
if success: if success:
file.unlink() file.unlink()
directory.rmdir() directory.rmdir()
else: else:
metadata = directory / 'recovery.json' write_recovery(directory, client, ctx)
metadata.touch(mode=0o600)
metadata.write_text(json.dumps({'origin': client.base, 'address': 'uuid:' + state['object_uuid'],
'base_revision_uuid': state['head_revision_uuid'], 'source_revision_uuid': state.get('source_revision_uuid', ''),
'lang': state['lang'], 'format': 'markdown' if markdown else 'raw'}))
print('Local edit retained:', safe_text(file), file=sys.stderr) print('Local edit retained:', safe_text(file), file=sys.stderr)
print('Recover later with: pages recover', safe_text(file), file=sys.stderr)
def resolve_recovery(target):
p = Path(target)
if p.is_symlink():
raise Failure('Recovery path must not be a symlink.')
if p.is_dir():
directory = p
elif p.name in ('recovery.json', 'document.md', 'document.txt'):
directory = p.parent
else:
raise Failure('Specify a pageswiki-edit recovery directory, recovery.json, or retained document file.')
if not directory.exists() or directory.is_symlink():
raise Failure('Recovery directory not found or invalid.')
private_dir(directory)
meta_path = directory / 'recovery.json'
if not meta_path.exists() and not meta_path.is_symlink():
raise Failure('Missing recovery.json metadata.')
private_file(meta_path)
try:
data = json.loads(meta_path.read_text(encoding='utf-8'))
except (ValueError, UnicodeError) as e:
raise Failure('Corrupt recovery.json metadata.') from e
if not isinstance(data, dict):
raise Failure('Corrupt recovery.json metadata.')
req_origin = data.get('origin')
addr = data.get('address')
lang = data.get('lang')
fmt = data.get('format')
rec_mode = data.get('mode', 'update')
if (not isinstance(req_origin, str) or not req_origin
or not isinstance(addr, str) or not addr
or not isinstance(lang, str) or not lang
or fmt not in ('markdown', 'raw')
or rec_mode not in ('update', 'create')):
raise Failure('Invalid recovery.json metadata.')
doc_path = directory / ('document.md' if fmt == 'markdown' else 'document.txt')
if not doc_path.exists() and not doc_path.is_symlink():
raise Failure('Missing retained document file.')
private_file(doc_path)
return directory, meta_path, doc_path, data
def list_recoveries(temp_root=None):
root = Path(temp_root or tempfile.gettempdir())
found = []
for entry in sorted(root.glob('pageswiki-edit-*')):
try:
directory, _, doc_path, data = resolve_recovery(entry)
found.append((directory, doc_path, data, doc_path.stat().st_mtime))
except (Failure, OSError, ValueError):
continue
return found
def cleanup_recovery(directory, meta_path, doc_path):
for p in (doc_path, meta_path):
if p.exists():
p.unlink()
if directory.exists() and not any(directory.iterdir()):
directory.rmdir()
def recover(client, profile, target=None, *, edit_first=False, discard=False, list_only=False, temp_root=None):
if list_only or (target is None and not discard):
items = list_recoveries(temp_root)
if not items:
print('No local recovery drafts found.')
return
for directory, _, data, mtime in items:
stamp = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(mtime))
print(safe_text('\t'.join((str(directory), data.get('mode', 'update'), data['address'], data['lang'], data['origin'], stamp))))
return
if target is None:
raise Failure('Specify a recovery path or use --list.')
directory, meta_path, doc_path, meta = resolve_recovery(target)
if discard:
if not directory.name.startswith('pageswiki-edit-'):
raise Failure('Refusing to discard outside a pageswiki-edit-* directory.')
cleanup_recovery(directory, meta_path, doc_path)
print('Discarded recovery draft:', safe_text(directory))
return
if meta['origin'] != client.base:
raise Failure('Recovery draft belongs to a different server origin (%s); switch profile before recovering.' % safe_text(meta['origin']))
rec_mode = meta.get('mode', 'update')
markdown = meta['format'] == 'markdown'
lang = language(meta['lang'])
addr = meta['address']
if edit_first:
run_editor(doc_path)
text = doc_path.read_text(encoding='utf-8')
if has_conflict_markers(text):
raise Failure('Conflict markers remain in draft; run with --edit to resolve them.', 409)
if rec_mode == 'create':
if not text:
raise Failure('Recovery draft is empty; edit with --edit or remove with --discard.')
ctx = {'creating': True, 'addr': addr, 'state': None, 'lang': lang, 'markdown': markdown}
else:
state = client.snapshot(addr, lang=lang)
expected_base = meta.get('base_revision_uuid', '')
if state['head_revision_uuid'] != expected_base:
remote = state['markdown'] if markdown else state['body']
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
action = choose_conflict_action('update', has_remote=True)
if action == 'k':
raise Failure('Conflict: remote revision changed since draft was saved.', 409)
if action == 'e':
doc_path.write_text(conflict_buffer(text, remote, state.get('head_revision_uuid', '')), encoding='utf-8')
run_editor(doc_path)
text = doc_path.read_text(encoding='utf-8')
if has_conflict_markers(text):
raise Failure('Conflict markers remain in edited document.', 409)
ctx = {'creating': False, 'addr': addr, 'state': state, 'lang': state['lang'], 'markdown': markdown}
cwd = profile.data.get('cwd', '/') if profile else '/'
try:
commit_edit(client, doc_path, text, ctx, cwd=cwd)
except BaseException:
write_recovery(directory, client, ctx)
raise
cleanup_recovery(directory, meta_path, doc_path)
TASK_API = '/_/api/v1/extension/organizer.tasks/' TASK_API = '/_/api/v1/extension/organizer.tasks/'
@@ -496,11 +834,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 +877,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
@@ -540,7 +905,7 @@ def tasks(client, profile, words):
for name in ('done','reopen','archive','start'): for name in ('done','reopen','archive','start'):
p=sub.add_parser(name);p.add_argument('uuid',type=task_uuid) p=sub.add_parser(name);p.add_argument('uuid',type=task_uuid)
sub.add_parser('stop');sub.add_parser('status') sub.add_parser('stop');sub.add_parser('status')
p=sub.add_parser('retry');p.add_argument('request_id',type=task_uuid) p=sub.add_parser('retry');p.add_argument('request_id',type=task_uuid);p.add_argument('--recreate-deleted',action='store_true',help='Explicitly recreate a deleted capture with a new UUID; preserve and relink any existing Wiki page')
p=sub.add_parser('report');p.add_argument('--from',dest='start');p.add_argument('--to',dest='end') p=sub.add_parser('report');p.add_argument('--from',dest='start');p.add_argument('--to',dest='end')
p=sub.add_parser('preferences');p.add_argument('--wiki-prefix');p.add_argument('--project');p.add_argument('--assignee');p.add_argument('--due-days',type=int);p.add_argument('--start-days',type=int);p.add_argument('--planned-days',type=int);p.add_argument('--review-days',type=int);p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int);p.add_argument('--digest',choices=['on','off']);p.add_argument('--at');p.add_argument('--timezone') p=sub.add_parser('preferences');p.add_argument('--wiki-prefix');p.add_argument('--project');p.add_argument('--assignee');p.add_argument('--due-days',type=int);p.add_argument('--start-days',type=int);p.add_argument('--planned-days',type=int);p.add_argument('--review-days',type=int);p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int);p.add_argument('--digest',choices=['on','off']);p.add_argument('--at');p.add_argument('--timezone')
for child in sub.choices.values():child.add_argument('--json',action='store_true') for child in sub.choices.values():child.add_argument('--json',action='store_true')
@@ -549,9 +914,19 @@ 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.')
replaced=payload['request_id'] in pending and pending[payload['request_id']] != payload
pending[payload['request_id']]=payload;profile.save() pending[payload['request_id']]=payload;profile.save()
if replaced:print('Replaced the retained draft with the current input.',file=sys.stderr)
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:
if e.status==410 and e.payload.get('error')=='deleted':
raise Failure('Draft retained. This task was deleted; normal retry will not restore it. To explicitly create a new task (preserving any existing Wiki body), use: pages task retry '+payload['request_id']+' --recreate-deleted',e.status,e.payload) from e
if e.status==409 and e.payload.get('error')=='capture_missing':
raise Failure('Draft retained. The server has a capture receipt but no task or deletion record. Server-side consistency repair is required; retry will not fix it.',e.status,e.payload) from e
if e.status==412:
raise Failure('Draft retained. This request ID conflicts with a server capture or task. An unchanged retry will not resolve it; inspect with: pages task show '+payload['request_id'],e.status,e.payload) from e
if e.status==409 and e.payload.get('error')=='note_exists':
raise Failure('Draft retained. A Wiki page already occupies the destination; it was not overwritten.',e.status,e.payload) from e
print('Draft retained; retry with: pages task retry '+payload['request_id'],file=sys.stderr) print('Draft retained; retry with: pages task retry '+payload['request_id'],file=sys.stderr)
if e.payload.get('error') == 'wiki_prefix_required': raise Failure('Set a private Wiki destination first: pages task preferences --wiki-prefix /YOUR/MAIL/PATH',e.status) from e if e.payload.get('error') == 'wiki_prefix_required': raise Failure('Set a private Wiki destination first: pages task preferences --wiki-prefix /YOUR/MAIL/PATH',e.status) from e
raise raise
@@ -576,18 +951,39 @@ def tasks(client, profile, words):
if action=='retry': if action=='retry':
payload=profile.data.get('task_outbox',{}).get(a.request_id) payload=profile.data.get('task_outbox',{}).get(a.request_id)
if not payload:raise Failure('No retained task capture with this request ID.') if not payload:raise Failure('No retained task capture with this request ID.')
if a.recreate_deleted:
pending=profile.data['task_outbox']
replacement=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+a.request_id))
payload=dict(payload,request_id=replacement,replaces_deleted=a.request_id)
if replacement in pending and pending[replacement]!=payload:
raise Failure('A different recreation draft already exists; inspect or retry it first: '+replacement)
previous=pending.copy()
pending[replacement]=payload;del pending[a.request_id]
try:profile.save()
except Exception:
profile.data['task_outbox']=previous
raise
print('Recreation draft saved. Existing Wiki content will be preserved. Retry ID: '+replacement,file=sys.stderr)
emit(capture(payload));return emit(capture(payload));return
if action in ('add','from-mail'): if action in ('add','from-mail'):
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. Changed input replaces the pending draft below.
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
@@ -670,15 +1066,22 @@ def execute(client, profile, words):
p.add_argument('path', nargs='?', default='.') p.add_argument('path', nargs='?', default='.')
if command == 'edit': if command == 'edit':
p.add_argument('--format', choices=['auto', 'raw', 'markdown'], default='auto') p.add_argument('--format', choices=['auto', 'raw', 'markdown'], default='auto')
p.add_argument('--lang', help='auto edits the visible language; an explicit tag can create a language revision') p.add_argument('--lang', help='auto edits the visible language (or creates as und with warning); an explicit tag selects or creates a language revision')
p = sub.add_parser('get'); p.add_argument('path'); p.add_argument('local') p = sub.add_parser('get'); p.add_argument('path'); p.add_argument('local')
p = sub.add_parser('put'); p.add_argument('local'); p.add_argument('path'); p.add_argument('--base', required=True) p = sub.add_parser('put'); p.add_argument('local'); p.add_argument('path'); p.add_argument('--base', required=True)
p.add_argument('--format', choices=['raw', 'markdown'], default='raw') p.add_argument('--format', choices=['raw', 'markdown'], default='raw')
p = sub.add_parser('recover', help='List, resume, or discard retained local edit drafts')
p.add_argument('target', nargs='?', help='Recovery directory, recovery.json, or retained document file')
p.add_argument('--list', action='store_true', dest='list_only', help='List retained local drafts')
p.add_argument('--edit', action='store_true', dest='edit_first', help='Open the draft in $EDITOR before saving')
p.add_argument('--discard', action='store_true', help='Delete the retained draft without saving')
p = sub.add_parser('search'); p.add_argument('query') p = sub.add_parser('search'); p.add_argument('query')
sub.add_parser('pwd'); sub.add_parser('logout'); sub.add_parser('status') sub.add_parser('pwd'); sub.add_parser('logout'); sub.add_parser('status')
args = parser.parse_args(words) args = parser.parse_args(words)
cwd = profile.data.get('cwd', '/') cwd = profile.data.get('cwd', '/')
cmd = args.command cmd = args.command
if cmd == 'recover':
recover(client, profile, args.target, edit_first=args.edit_first, discard=args.discard, list_only=args.list_only); return
if cmd == 'logout': if cmd == 'logout':
client.json('/_/auth/logout', method='POST') client.json('/_/auth/logout', method='POST')
profile.data.pop('token', None); profile.data.pop('expires', None); profile.save() profile.data.pop('token', None); profile.data.pop('expires', None); profile.save()
@@ -778,7 +1181,7 @@ def shell(client, profile):
def main(argv=None): def main(argv=None):
parser = argparse.ArgumentParser(prog='pages', description=__doc__, epilog='Commands: configure, login, logout, status, shell, ls, cd, pwd, cat, view, get, put, edit, search, open, task, contacts. Use pages COMMAND --help.') parser = argparse.ArgumentParser(prog='pages', description=__doc__, epilog='Commands: configure, login, logout, status, shell, ls, cd, pwd, cat, view, get, put, edit, recover, search, open, task, contacts. Use pages COMMAND --help.')
parser.add_argument('--version', action='version', version='pages-cli ' + VERSION) parser.add_argument('--version', action='version', version='pages-cli ' + VERSION)
parser.add_argument('--profile', help='Use another configured connection for this invocation') parser.add_argument('--profile', help='Use another configured connection for this invocation')
parser.add_argument('--lang', help='auto or an exact language tag for this invocation') parser.add_argument('--lang', help='auto or an exact language tag for this invocation')
@@ -795,9 +1198,10 @@ def main(argv=None):
if args.command == 'login': if args.command == 'login':
login = argparse.ArgumentParser(prog='pages login', description='Log into the configured connection. Password and TOTP are prompted privately.') login = argparse.ArgumentParser(prog='pages login', description='Log into the configured connection. Password and TOTP are prompted privately.')
login.add_argument('--oidc', action='store_true', help='Authenticate and approve in a browser; no local password required') login.add_argument('--oidc', action='store_true', help='Authenticate and approve in a browser; no local password required')
login.add_argument('--no-browser', action='store_true', help='Print the browser login URL without opening it (requires --oidc)') login.add_argument('--with-open-browser', action='store_true', help='Open the browser login URL automatically (requires --oidc)')
login.add_argument('--remember', action='store_true', help='Keep this trusted device signed in for up to 30 days, subject to server policy')
login_args = login.parse_args(args.args) login_args = login.parse_args(args.args)
if login_args.no_browser and not login_args.oidc: login.error('--no-browser requires --oidc') if login_args.with_open_browser and not login_args.oidc: login.error('--with-open-browser requires --oidc')
elif '--help' in args.args: elif '--help' in args.args:
execute(None, None, [args.command] + args.args); return execute(None, None, [args.command] + args.args); return
with contextlib.ExitStack() as stack: with contextlib.ExitStack() as stack:
@@ -814,13 +1218,13 @@ def main(argv=None):
print('WARNING: --insecure disables TLS certificate and hostname verification for this invocation. Credentials and data can be intercepted; this option is not saved.', file=sys.stderr) print('WARNING: --insecure disables TLS certificate and hostname verification for this invocation. Credentials and data can be intercepted; this option is not saved.', file=sys.stderr)
if args.command == 'login': if args.command == 'login':
if not login_args.oidc and not spec.get('username'): raise Failure('Set your account with pages configure --username NAME, or use pages login --oidc.') if not login_args.oidc and not spec.get('username'): raise Failure('Set your account with pages configure --username NAME, or use pages login --oidc.')
if profile.data.get('token'): raise Failure('Log out this profile before replacing its session.') if profile.data.get('token') and profile.data.get('expires',0)>time.time(): raise Failure('Log out this profile before replacing its active session.')
client = Client(spec['origin'], lang=lang, insecure=args.insecure) client = Client(spec['origin'], lang=lang, insecure=args.insecure)
if login_args.oidc: if login_args.oidc:
expires, username = client.login_oidc(login_args.no_browser, spec.get('username', '')) expires, username = client.login_oidc(login_args.with_open_browser, spec.get('username', ''), remember=login_args.remember)
else: else:
username = spec['username'] username = spec['username']
expires = client.login(username, getpass.getpass('Password: ')) expires = client.login(username, getpass.getpass('Password: '), remember=login_args.remember)
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == username same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == username
pending = profile.data.get('task_outbox', {}) pending = profile.data.get('task_outbox', {})
if pending and not same_identity: if pending and not same_identity:
+483 -12
View File
@@ -25,6 +25,7 @@ def server(callback):
class Handler(BaseHTTPRequestHandler): class Handler(BaseHTTPRequestHandler):
def do_GET(self): callback(self) def do_GET(self): callback(self)
def do_POST(self): callback(self) def do_POST(self): callback(self)
def do_PUT(self): callback(self)
def log_message(self, *args): pass def log_message(self, *args): pass
instance = ThreadingHTTPServer(('127.0.0.1', 0), Handler) instance = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
thread = threading.Thread(target=instance.serve_forever, daemon=True) thread = threading.Thread(target=instance.serve_forever, daemon=True)
@@ -54,7 +55,7 @@ class RemoteTests(unittest.TestCase):
if polls == 2: raise Failure('slow',400,{'error':'slow_down'}) if polls == 2: raise Failure('slow',400,{'error':'slow_down'})
return {'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'anya'} return {'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'anya'}
with patch.object(client,'json',side_effect=request), patch.object(m['webbrowser'],'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out: with patch.object(client,'json',side_effect=request), patch.object(m['webbrowser'],'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out:
expires, name = client.login_oidc(True,sleep=sleep,clock=lambda:now[0]) expires, name = client.login_oidc(sleep=sleep,clock=lambda:now[0])
self.assertEqual(name,'anya'); self.assertGreater(expires,time.time()) self.assertEqual(name,'anya'); self.assertGreater(expires,time.time())
self.assertEqual(waits,[5,5,10]); browser.assert_not_called() self.assertEqual(waits,[5,5,10]); browser.assert_not_called()
proof = calls[1][1]['form']['code_verifier'] proof = calls[1][1]['form']['code_verifier']
@@ -69,7 +70,7 @@ class RemoteTests(unittest.TestCase):
client = Client('https://wiki.example') client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=Failure('Not found or not readable.', status)) as api, patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out: with patch.object(client, 'json', side_effect=Failure('Not found or not readable.', status)) as api, patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out:
with self.assertRaisesRegex(Failure, 'CLI OIDC login is unavailable') as caught: with self.assertRaisesRegex(Failure, 'CLI OIDC login is unavailable') as caught:
client.login_oidc(True) client.login_oidc(open_browser=True)
self.assertEqual(caught.exception.status, status) self.assertEqual(caught.exception.status, status)
api.assert_called_once() api.assert_called_once()
browser.assert_not_called() browser.assert_not_called()
@@ -80,11 +81,11 @@ class RemoteTests(unittest.TestCase):
client = Client('https://wiki.example') client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=Failure('Access denied.', 403, {'error': 'oidc_disabled'})): with patch.object(client, 'json', side_effect=Failure('Access denied.', 403, {'error': 'oidc_disabled'})):
with self.assertRaisesRegex(Failure, 'not enabled for this domain'): with self.assertRaisesRegex(Failure, 'not enabled for this domain'):
client.login_oidc(True) client.login_oidc()
for error in (Failure('Connection/TLS failure.'), Failure('Access denied.', 403), Failure('Unavailable.', 503)): for error in (Failure('Connection/TLS failure.'), Failure('Access denied.', 403), Failure('Unavailable.', 503)):
with patch.object(client, 'json', side_effect=error) as api: with patch.object(client, 'json', side_effect=error) as api:
with self.assertRaises(Failure) as caught: with self.assertRaises(Failure) as caught:
client.login_oidc(True) client.login_oidc()
self.assertIs(caught.exception, error) self.assertIs(caught.exception, error)
api.assert_called_once() api.assert_called_once()
@@ -92,12 +93,12 @@ class RemoteTests(unittest.TestCase):
client=Client('https://wiki.example') client=Client('https://wiki.example')
started={'device_code':'D'*43,'verification_uri':'https://evil.example/','user_code':'ABCD-1234','expires_in':300,'interval':5} started={'device_code':'D'*43,'verification_uri':'https://evil.example/','user_code':'ABCD-1234','expires_in':300,'interval':5}
with patch.object(client,'json',return_value=started),patch.object(m['webbrowser'],'open') as browser: with patch.object(client,'json',return_value=started),patch.object(m['webbrowser'],'open') as browser:
with self.assertRaises(Failure): client.login_oidc() with self.assertRaises(Failure): client.login_oidc(open_browser=True)
browser.assert_not_called() browser.assert_not_called()
started['verification_uri']='/_/auth/cli/verify?request='+'R'*43 started['verification_uri']='/_/auth/cli/verify?request='+'R'*43
token={'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'other'} token={'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'other'}
with patch.object(client,'json',side_effect=[started,token,{}]) as api, contextlib.redirect_stdout(io.StringIO()): with patch.object(client,'json',side_effect=[started,token,{}]) as api, contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(Failure): client.login_oidc(True,'anya',sleep=lambda _:None,clock=lambda:0) with self.assertRaises(Failure): client.login_oidc(expected_username='anya',sleep=lambda _:None,clock=lambda:0)
self.assertEqual(api.call_args.args[0],'/_/auth/logout') self.assertEqual(api.call_args.args[0],'/_/auth/logout')
self.assertEqual(client.token,'') self.assertEqual(client.token,'')
@@ -106,27 +107,60 @@ class RemoteTests(unittest.TestCase):
for error in [Failure('denied',403,{'error':'access_denied'}),Failure('expired',400,{'error':'expired_token'}),Failure('network failure')]: for error in [Failure('denied',403,{'error':'access_denied'}),Failure('expired',400,{'error':'expired_token'}),Failure('network failure')]:
client=Client('https://wiki.example') client=Client('https://wiki.example')
with patch.object(client,'json',side_effect=[started,error]) as api,contextlib.redirect_stdout(io.StringIO()): with patch.object(client,'json',side_effect=[started,error]) as api,contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(Failure): client.login_oidc(True,sleep=lambda _:None,clock=lambda:0) with self.assertRaises(Failure): client.login_oidc(sleep=lambda _:None,clock=lambda:0)
self.assertEqual(api.call_count,2) self.assertEqual(api.call_count,2)
client=Client('https://wiki.example') client=Client('https://wiki.example')
with patch.object(client,'json',return_value=started) as api,contextlib.redirect_stdout(io.StringIO()): with patch.object(client,'json',return_value=started) as api,contextlib.redirect_stdout(io.StringIO()):
def interrupt(_): raise KeyboardInterrupt() def interrupt(_): raise KeyboardInterrupt()
with self.assertRaises(KeyboardInterrupt): client.login_oidc(True,sleep=interrupt,clock=lambda:0) with self.assertRaises(KeyboardInterrupt): client.login_oidc(sleep=interrupt,clock=lambda:0)
self.assertEqual(api.call_count,1) self.assertEqual(api.call_count,1)
def test_oidc_main_without_configured_username(self): def test_oidc_main_without_configured_username(self):
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}): with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}):
self.configure(None,'--origin','https://wiki.example') self.configure(None,'--origin','https://wiki.example')
def login(client,*args,**kwargs): client.token='pw_api_'+'s'*43; return time.time()+600,'anya' calls=[]
def login(client,*args,**kwargs):
calls.append((args,kwargs))
client.token='pw_api_'+'s'*43; return time.time()+600,'anya'
with patch.object(Client,'login_oidc',login),contextlib.redirect_stdout(io.StringIO()): with patch.object(Client,'login_oidc',login),contextlib.redirect_stdout(io.StringIO()):
m['main'](['login','--oidc','--no-browser']) m['main'](['login','--oidc'])
m['main'](['status']) m['main'](['status'])
self.configure(None,'--lang','ja') self.configure(None,'--lang','ja')
self.assertIs(calls[-1][0][0],False)
with Profile('default').locked() as profile: with Profile('default').locked() as profile:
self.assertEqual(profile.data['username'],'anya') self.assertEqual(profile.data['username'],'anya')
self.assertEqual(profile.data['configured_username'],'') self.assertEqual(profile.data['configured_username'],'')
with self.assertRaises(Failure): self.configure(None,'--username','other') with self.assertRaises(Failure): self.configure(None,'--username','other')
def test_oidc_browser_opening_is_opt_in(self):
started = {'device_code': 'D'*43, 'verification_uri': '/_/auth/cli/verify?request='+'R'*43,
'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5}
result = {'access_token': 'pw_api_'+'S'*43, 'token_type': 'Bearer', 'expires_in': 3600, 'username': 'anya'}
client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=[started, result]), patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()):
client.login_oidc(sleep=lambda _: None, clock=lambda: 0)
browser.assert_not_called()
client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=[started, result]), patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()):
client.login_oidc(open_browser=True, sleep=lambda _: None, clock=lambda: 0)
browser.assert_called_once_with('https://wiki.example/_/auth/cli/verify?request='+'R'*43, new=2)
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ, {'XDG_CONFIG_HOME': root}):
self.configure(None, '--origin', 'https://wiki.example')
calls = []
def login(client_arg, *args, **kwargs):
calls.append((args, kwargs))
client_arg.token = 'pw_api_'+'s'*43
return time.time()+600, 'anya'
with patch.object(Client, 'login_oidc', login), contextlib.redirect_stdout(io.StringIO()):
m['main'](['login', '--oidc', '--with-open-browser'])
self.assertIs(calls[-1][0][0], True)
with patch.object(Client, 'login_oidc') as login_mock, contextlib.redirect_stderr(io.StringIO()):
for bad_args in (['login', '--with-open-browser'], ['login', '--oidc', '--no-browser']):
with self.assertRaises(SystemExit) as exited:
m['main'](bad_args)
self.assertNotEqual(exited.exception.code, 0)
login_mock.assert_not_called()
def configure(self, root, *args): def configure(self, root, *args):
with contextlib.redirect_stdout(io.StringIO()) as output: with contextlib.redirect_stdout(io.StringIO()) as output:
m['configure'](list(args), root) m['configure'](list(args), root)
@@ -343,7 +377,7 @@ class RemoteTests(unittest.TestCase):
Path(args[-1]).write_text('my edit') Path(args[-1]).write_text('my edit')
class Result: returncode=0 class Result: returncode=0
return Result() return Result()
with patch('tempfile.mkdtemp',return_value=str(directory)), patch('subprocess.run',side_effect=edit), patch.object(client,'snapshot',return_value=state) as snapshot, patch.object(client,'save',side_effect=Failure('conflict',409)), contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): with patch('tempfile.mkdtemp',return_value=str(directory)), patch('subprocess.run',side_effect=edit), patch.object(client,'snapshot',return_value=state) as snapshot, patch.object(client,'save',side_effect=Failure('conflict',409)), patch.object(m['sys'],'stdin',io.StringIO('')), contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(Failure): m['editor'](client,'path:/x','auto') with self.assertRaises(Failure): m['editor'](client,'path:/x','auto')
snapshot.assert_called_with('uuid:object',lang='und') snapshot.assert_called_with('uuid:object',lang='und')
self.assertEqual((directory/'document.txt').read_text(),'my edit') self.assertEqual((directory/'document.txt').read_text(),'my edit')
@@ -352,6 +386,443 @@ class RemoteTests(unittest.TestCase):
self.assertIn('base',recovery) self.assertIn('base',recovery)
self.assertEqual(stat.S_IMODE((directory/'recovery.json').stat().st_mode),0o600) self.assertEqual(stat.S_IMODE((directory/'recovery.json').stat().st_mode),0o600)
def test_create_page_put_contract_and_errors(self):
recorded = []
mode = {'status': 201, 'headers': None}
def handle(h):
length = int(h.headers.get('Content-Length', 0))
body = h.rfile.read(length)
recorded.append((h.command, h.path, h.headers, body))
if h.path == '/_/api/v1/render/markdown':
req = json.loads(body)
self.assertTrue(req['authoring'])
self.assertFalse(req['projection'])
reply(h, 200, {'html': '<p>' + req['markdown'].strip() + '</p>'})
return
if mode['status'] != 201:
reply(h, mode['status'], {'error': 'rejected'})
return
digest = hashlib.sha256(body).hexdigest()
headers = {
'Content-Type': 'application/json; charset=utf-8',
'Location': '/o/uuid:00000000-0000-4000-8000-000000000001',
'ETag': '"' + digest + '"',
'Content-Language': h.headers.get('Content-Language', 'und'),
'X-PagesWiki-Object-UUID': '00000000-0000-4000-8000-000000000001',
'X-PagesWiki-Revision-UUID': '00000000-0000-4000-8000-000000000002',
'X-PagesWiki-Document-SHA256': digest,
}
if mode['headers'] is not None:
headers = mode['headers'](digest)
h.send_response(201)
for k, v in headers.items():
h.send_header(k, v)
h.end_headers()
with server(handle) as base:
client = Client(base, 'secret-token', 'auto')
created = client.create_page('path:/docs/新規 ガイド', '# Title\n', markdown=True)
self.assertEqual(created['path'], '/docs/新規 ガイド')
self.assertEqual(created['lang'], 'und')
self.assertEqual(created['object_uuid'], '00000000-0000-4000-8000-000000000001')
self.assertEqual(created['revision_uuid'], '00000000-0000-4000-8000-000000000002')
self.assertEqual(recorded[0][0], 'POST')
self.assertEqual(recorded[0][1], '/_/api/v1/render/markdown')
method, path, hdrs, raw = recorded[1]
self.assertEqual(method, 'PUT')
self.assertEqual(path, '/_/api/v1/pages/path:/docs/%E6%96%B0%E8%A6%8F%20%E3%82%AC%E3%82%A4%E3%83%89')
self.assertEqual(hdrs.get('Authorization'), 'Bearer secret-token')
self.assertEqual(hdrs.get('If-None-Match'), '*')
self.assertEqual(hdrs.get('Content-Language'), 'und')
self.assertEqual(hdrs.get('Content-Type'), 'text/html; charset=utf-8')
self.assertEqual(hdrs.get('X-PagesWiki-Commit-Message'), 'Remote%20CLI%20create')
self.assertEqual(raw, b'<p># Title</p>')
recorded.clear()
raw_created = client.create_page('path:/notes/memo.txt', 'hello', markdown=False, lang='ja', filename='メモ.txt')
self.assertEqual(raw_created['lang'], 'ja')
self.assertEqual(len(recorded), 1)
self.assertEqual(recorded[0][0], 'PUT')
self.assertEqual(recorded[0][2].get('Content-Type'), 'text/plain; charset=utf-8')
self.assertEqual(recorded[0][2].get('Content-Language'), 'ja')
self.assertEqual(recorded[0][2].get('X-PagesWiki-Filename'), '%E3%83%A1%E3%83%A2.txt')
self.assertEqual(recorded[0][3], b'hello')
before = len(recorded)
for bad in ('path:/', 'uuid:00000000-0000-0000-0000-000000000000', 'rev:00000000-0000-0000-0000-000000000000'):
with self.assertRaises(Failure):
client.create_page(bad, 'x')
with self.assertRaises(Failure):
client.create_page('path:/too-big', 'a' * ((1 << 20) + 1))
self.assertEqual(len(recorded), before)
mode['headers'] = lambda d: {'X-PagesWiki-Object-UUID': '00000000-0000-4000-8000-000000000001'}
with self.assertRaisesRegex(Failure, 'missing document identity'):
client.create_page('path:/bad-headers', 'x')
mode['headers'] = None
for status, pattern in ((200, 'Unexpected HTTP status'), (412, 'already exists'), (428, 'If-None-Match'), (404, 'unavailable'), (405, 'unavailable'), (501, 'unavailable'), (403, 'Access denied')):
recorded.clear()
mode['status'] = status
with self.assertRaisesRegex(Failure, pattern) as caught:
client.create_page('path:/err', 'x')
self.assertEqual(caught.exception.status, status)
self.assertEqual(len(recorded), 1)
def test_editor_creates_new_page_with_confirmation_and_und_warning(self):
client = Client('https://example.test', 'token', 'auto')
with patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: False}), \
patch.object(client, 'create_page') as create_mock, \
patch('subprocess.run') as run_mock, \
contextlib.redirect_stdout(io.StringIO()) as out:
m['editor'](client, 'path:/docs/new', 'auto')
self.assertIn('Aborted.', out.getvalue())
run_mock.assert_not_called()
create_mock.assert_not_called()
def edit_ok(args, **kwargs):
Path(args[-1]).write_text('# Hello\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \
patch.object(client, 'create_page', return_value={'path': '/docs/new', 'object_uuid': 'obj-1', 'revision_uuid': 'rev-1'}) as create_mock, \
patch('subprocess.run', side_effect=edit_ok) as run_mock, \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()) as err:
m['editor'](client, 'path:/docs/new', 'auto')
self.assertIn("WARNING: Creating a new page with language 'und'", err.getvalue())
self.assertIn('Created page: /docs/new', out.getvalue())
self.assertTrue(run_mock.call_args.args[0][-1].endswith('document.md'))
self.assertFalse(Path(run_mock.call_args.args[0][-1]).exists())
create_mock.assert_called_once_with('path:/docs/new', '# Hello\n', True, lang='und')
client_ja = Client('https://example.test', 'token', 'ja')
with patch.object(client_ja, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \
patch.object(client_ja, 'create_page', return_value={'path': '/docs/new', 'object_uuid': 'obj-1', 'revision_uuid': 'rev-1'}) as create_mock, \
patch('subprocess.run', side_effect=edit_ok), \
contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()) as err:
m['editor'](client_ja, 'path:/docs/new', 'raw')
self.assertEqual(err.getvalue(), '')
create_mock.assert_called_once_with('path:/docs/new', '# Hello\n', False, lang='ja')
confirm_calls = []
def record_confirm(addr, status):
confirm_calls.append((addr, status))
return True
with patch.object(client_ja, 'snapshot', side_effect=Failure('Access denied', 403)), \
patch.dict(m['editor'].__globals__, {'confirm_create': record_confirm}), \
patch.object(client_ja, 'create_page', return_value={'path': '/docs/create-only', 'object_uuid': 'obj-2', 'revision_uuid': 'rev-2'}), \
patch('subprocess.run', side_effect=edit_ok), \
contextlib.redirect_stdout(io.StringIO()):
m['editor'](client_ja, 'path:/docs/create-only', 'auto')
self.assertEqual(confirm_calls, [('path:/docs/create-only', 403)])
for non_creatable in ('uuid:00000000-0000-0000-0000-000000000000', 'rev:00000000-0000-0000-0000-000000000000', 'path:/'):
with patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda *_: self.fail('should not prompt')}):
with self.assertRaises(Failure):
m['editor'](client, non_creatable, 'auto')
non_tty = io.StringIO('y\n')
with patch.object(m['sys'], 'stdin', non_tty), \
patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)):
with self.assertRaises(Failure) as caught:
m['editor'](client, 'path:/docs/new', 'auto')
self.assertEqual(caught.exception.status, 404)
def test_editor_new_page_empty_aborts_and_failure_retains_private_recovery(self):
client = Client('https://example.test', 'secret-token', 'auto')
with tempfile.TemporaryDirectory() as root:
directory = Path(root) / 'empty'; directory.mkdir(mode=0o700)
with patch('tempfile.mkdtemp', return_value=str(directory)), \
patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \
patch.object(client, 'create_page') as create_mock, \
patch('subprocess.run', return_value=type('R', (), {'returncode': 0})()), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()):
m['editor'](client, 'path:/docs/empty', 'auto')
create_mock.assert_not_called()
self.assertIn('was not created', out.getvalue())
self.assertFalse(directory.exists())
working = Path(root) / 'race'; working.mkdir(mode=0o700)
def edit_write(args, **kwargs):
Path(args[-1]).write_text('draft body', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(working)), \
patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \
patch.object(client, 'create_page', side_effect=Failure('Conflict', 412)), \
patch('subprocess.run', side_effect=edit_write), \
patch.object(m['sys'], 'stdin', io.StringIO('')), \
contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()) as err:
with self.assertRaises(Failure) as caught:
m['editor'](client, 'path:/docs/race', 'auto')
self.assertEqual(caught.exception.status, 412)
self.assertNotIn('secret-token', err.getvalue())
self.assertEqual((working / 'document.md').read_text(encoding='utf-8'), 'draft body')
self.assertEqual(stat.S_IMODE((working / 'document.md').stat().st_mode), 0o600)
recovery_text = (working / 'recovery.json').read_text(encoding='utf-8')
self.assertNotIn('secret-token', recovery_text)
recovery = json.loads(recovery_text)
self.assertEqual(recovery['mode'], 'create')
self.assertEqual(recovery['address'], 'path:/docs/race')
self.assertEqual(recovery['lang'], 'und')
self.assertEqual(recovery['format'], 'markdown')
self.assertEqual(stat.S_IMODE((working / 'recovery.json').stat().st_mode), 0o600)
def test_editor_409_interactive_edit_and_force_save(self):
state = {'object_uuid': 'object', 'head_revision_uuid': 'base-rev', 'principal_uuid': 'person', 'lang': 'und',
'content_type': 'text/plain', 'filename': 'x.txt', 'body': 'base\n', 'markdown': 'base\n'}
latest = {'object_uuid': 'object', 'head_revision_uuid': 'latest-rev', 'principal_uuid': 'person', 'lang': 'und',
'content_type': 'text/plain', 'filename': 'x.txt', 'body': 'remote line\n', 'markdown': 'remote line\n'}
client = Client('https://example.test', 'token')
with tempfile.TemporaryDirectory() as root:
working = Path(root) / 'merge'; working.mkdir(mode=0o700)
seen_buffers = []
call_count = [0]
def run_ed(args, **kwargs):
call_count[0] += 1
p = Path(args[-1])
if call_count[0] == 1:
p.write_text('local line\n', encoding='utf-8')
else:
seen_buffers.append(p.read_text(encoding='utf-8'))
p.write_text('merged line\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(working)), \
patch('subprocess.run', side_effect=run_ed), \
patch.object(client, 'snapshot', side_effect=[state, latest]), \
patch.object(client, 'save', side_effect=[Failure('conflict', 409), {'revision_uuid': 'merged-rev'}]) as save_mock, \
patch.dict(m['editor'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'e'}), \
contextlib.redirect_stdout(io.StringIO()) as out:
m['editor'](client, 'path:/x', 'auto')
self.assertIn('<<<<<<< local\nlocal line\n=======\nremote line\n>>>>>>> remote (rev: latest-rev)\n', seen_buffers[0])
self.assertEqual(save_mock.call_args_list[1].args, (latest, 'merged line\n', False))
self.assertIn('Saved revision: merged-rev', out.getvalue())
self.assertFalse(working.exists())
markers = Path(root) / 'markers'; markers.mkdir(mode=0o700)
call_count[0] = 0
def leave_markers(args, **kwargs):
call_count[0] += 1
if call_count[0] == 1:
Path(args[-1]).write_text('local line\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(markers)), \
patch('subprocess.run', side_effect=leave_markers), \
patch.object(client, 'snapshot', side_effect=[state, latest]), \
patch.object(client, 'save', side_effect=Failure('conflict', 409)) as save_mock, \
patch.dict(m['editor'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'e'}), \
contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()) as err:
with self.assertRaises(Failure) as caught:
m['editor'](client, 'path:/x', 'auto')
self.assertEqual(caught.exception.status, 409)
self.assertEqual(save_mock.call_count, 1)
self.assertIn('Conflict markers remain', err.getvalue())
self.assertTrue((markers / 'recovery.json').exists())
force_dir = Path(root) / 'force'; force_dir.mkdir(mode=0o700)
def edit_local(args, **kwargs):
Path(args[-1]).write_text('forced body\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(force_dir)), \
patch('subprocess.run', side_effect=edit_local) as run_mock, \
patch.object(client, 'snapshot', side_effect=[state, latest]), \
patch.object(client, 'save', side_effect=[Failure('conflict', 409), {'revision_uuid': 'forced-rev'}]) as save_mock, \
patch.dict(m['editor'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'f'}), \
contextlib.redirect_stdout(io.StringIO()) as out:
m['editor'](client, 'path:/x', 'auto')
self.assertEqual(run_mock.call_count, 1)
self.assertEqual(save_mock.call_args_list[1].args, (latest, 'forced body\n', False))
self.assertIn('Saved revision: forced-rev', out.getvalue())
self.assertFalse(force_dir.exists())
def test_editor_412_interactive_pick_path_and_merge(self):
client = Client('https://example.test', 'token', 'auto')
with tempfile.TemporaryDirectory() as root:
pick_dir = Path(root) / 'pick'; pick_dir.mkdir(mode=0o700)
def edit_new(args, **kwargs):
Path(args[-1]).write_text('# New Draft\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(pick_dir)), \
patch('subprocess.run', side_effect=edit_new), \
patch.object(client, 'snapshot', side_effect=[Failure('Not found', 404), Failure('Forbidden', 403)]), \
patch.object(client, 'create_page', side_effect=[Failure('Exists', 412), {'path': '/docs/alt', 'object_uuid': 'obj-2', 'revision_uuid': 'rev-2'}]) as create_mock, \
patch.dict(m['editor'].__globals__, {
'confirm_create': lambda addr, st: True,
'choose_conflict_action': lambda kind, has_remote=True: 'p',
'prompt_new_path': lambda cwd='/': 'path:/docs/alt',
}), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()):
m['editor'](client, 'path:/docs/orig', 'auto')
self.assertEqual(create_mock.call_args_list[1].args[0], 'path:/docs/alt')
self.assertIn('Created page: /docs/alt', out.getvalue())
self.assertFalse(pick_dir.exists())
merge_dir = Path(root) / 'merge-create'; merge_dir.mkdir(mode=0o700)
existing = {'object_uuid': 'obj-existing', 'head_revision_uuid': 'rev-existing', 'principal_uuid': 'person',
'lang': 'ja', 'content_type': 'text/html', 'filename': '', 'body': '<p>Existing</p>', 'markdown': 'Existing\n'}
call_count = [0]
seen_buffers = []
def edit_merge(args, **kwargs):
call_count[0] += 1
p = Path(args[-1])
if call_count[0] == 1:
p.write_text('My new page\n', encoding='utf-8')
else:
seen_buffers.append(p.read_text(encoding='utf-8'))
p.write_text('Combined page\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(merge_dir)), \
patch('subprocess.run', side_effect=edit_merge), \
patch.object(client, 'snapshot', side_effect=[Failure('Not found', 404), existing]), \
patch.object(client, 'create_page', side_effect=Failure('Exists', 412)), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-combined'}) as save_mock, \
patch.dict(m['editor'].__globals__, {
'confirm_create': lambda addr, st: True,
'choose_conflict_action': lambda kind, has_remote=True: 'e',
}), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()):
m['editor'](client, 'path:/docs/race', 'auto')
self.assertIn('<<<<<<< local\nMy new page\n=======\nExisting\n>>>>>>> remote (rev: rev-existing)\n', seen_buffers[0])
save_mock.assert_called_once_with(existing, 'Combined page\n', True)
self.assertIn('Saved revision: rev-combined', out.getvalue())
self.assertFalse(merge_dir.exists())
def test_recover_list_resume_conflict_discard_and_security(self):
client = Client('https://example.test', 'token', 'auto')
profile = type('P', (), {'data': {'cwd': '/notes'}})()
def make_draft(base_dir, name, meta, doc_text, *, dir_mode=0o700, file_mode=0o600):
d = Path(base_dir) / name
d.mkdir(mode=0o700)
doc_name = 'document.md' if meta['format'] == 'markdown' else 'document.txt'
doc = d / doc_name
doc.touch(mode=0o600); doc.write_text(doc_text, encoding='utf-8'); doc.chmod(file_mode)
meta_file = d / 'recovery.json'
meta_file.touch(mode=0o600); meta_file.write_text(json.dumps(meta), encoding='utf-8'); meta_file.chmod(file_mode)
d.chmod(dir_mode)
return d, doc, meta_file
with tempfile.TemporaryDirectory() as root:
good_dir, good_doc, _ = make_draft(root, 'pageswiki-edit-good', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'ja', 'format': 'raw',
}, 'recovered text\n')
make_draft(root, 'pageswiki-edit-badperm', {
'origin': 'https://example.test', 'address': 'uuid:obj-2',
'base_revision_uuid': 'rev-2', 'lang': 'ja', 'format': 'raw',
}, 'ignored\n', dir_mode=0o755)
bad_link = Path(root) / 'pageswiki-edit-symlink'
bad_link.symlink_to(good_dir)
out = io.StringIO()
with contextlib.redirect_stdout(out):
m['recover'](client, profile, list_only=True, temp_root=root)
lines = out.getvalue().strip().splitlines()
self.assertEqual(len(lines), 1)
self.assertIn(str(good_dir), lines[0])
self.assertNotIn('badperm', out.getvalue())
self.assertNotIn('symlink', out.getvalue())
bad_link.unlink()
# Resume update when head still matches.
state = {'object_uuid': 'obj-1', 'head_revision_uuid': 'rev-1', 'principal_uuid': 'person',
'lang': 'ja', 'content_type': 'text/plain', 'filename': 'a.txt', 'body': 'old', 'markdown': 'old'}
with patch.object(client, 'snapshot', return_value=state), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-2'}) as save_mock, \
contextlib.redirect_stdout(io.StringIO()) as out:
m['recover'](client, profile, str(good_doc))
save_mock.assert_called_once_with(state, 'recovered text\n', False)
self.assertIn('Saved revision: rev-2', out.getvalue())
self.assertFalse(good_dir.exists())
# Resume update when remote head changed: non-interactive keeps draft; interactive 'e' merges.
moved_dir, moved_doc, _ = make_draft(root, 'pageswiki-edit-moved', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'ja', 'format': 'raw',
}, 'draft edit\n')
newer = {'object_uuid': 'obj-1', 'head_revision_uuid': 'rev-9', 'principal_uuid': 'person',
'lang': 'ja', 'content_type': 'text/plain', 'filename': 'a.txt', 'body': 'newer remote\n', 'markdown': 'newer remote\n'}
with patch.object(client, 'snapshot', return_value=newer), \
patch.object(client, 'save') as save_mock, \
patch.object(m['sys'], 'stdin', io.StringIO('')), \
contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(Failure) as caught:
m['recover'](client, profile, str(moved_dir))
self.assertEqual(caught.exception.status, 409)
save_mock.assert_not_called()
self.assertTrue(moved_doc.exists())
def resolve_in_ed(args, **kwargs):
p = Path(args[-1])
self.assertIn('<<<<<<< local\ndraft edit\n=======\nnewer remote\n>>>>>>> remote (rev: rev-9)\n', p.read_text(encoding='utf-8'))
p.write_text('resolved draft\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch.object(client, 'snapshot', return_value=newer), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-10'}) as save_mock, \
patch('subprocess.run', side_effect=resolve_in_ed), \
patch.dict(m['recover'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'e'}), \
contextlib.redirect_stdout(io.StringIO()):
m['recover'](client, profile, str(moved_dir))
save_mock.assert_called_once_with(newer, 'resolved draft\n', False)
self.assertFalse(moved_dir.exists())
# Resume create draft.
create_dir, _, _ = make_draft(root, 'pageswiki-edit-create', {
'origin': 'https://example.test', 'mode': 'create', 'address': 'path:/docs/new',
'lang': 'und', 'format': 'markdown',
}, '# Created from recovery\n')
with patch.object(client, 'create_page', return_value={'path': '/docs/new', 'object_uuid': 'obj-new', 'revision_uuid': 'rev-new'}) as create_mock, \
contextlib.redirect_stdout(io.StringIO()) as out:
m['recover'](client, profile, str(create_dir))
create_mock.assert_called_once_with('path:/docs/new', '# Created from recovery\n', True, lang='und')
self.assertIn('Created page: /docs/new', out.getvalue())
self.assertFalse(create_dir.exists())
# Reject wrong origin with zero network calls.
other_dir, _, _ = make_draft(root, 'pageswiki-edit-other', {
'origin': 'https://other.example', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw',
}, 'other\n')
with patch.object(client, 'snapshot') as snap_mock, patch.object(client, 'save') as save_mock:
with self.assertRaisesRegex(Failure, 'different server origin'):
m['recover'](client, profile, str(other_dir))
snap_mock.assert_not_called(); save_mock.assert_not_called()
# Reject insecure permissions and discard safety check.
_, insecure_doc, _ = make_draft(root, 'pageswiki-edit-insecure', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw',
}, 'x\n', file_mode=0o644)
with self.assertRaisesRegex(Failure, '0600'):
m['recover'](client, profile, str(insecure_doc))
outside_dir, _, _ = make_draft(root, 'custom-dir', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw',
}, 'x\n')
with self.assertRaisesRegex(Failure, 'Refusing to discard'):
m['recover'](client, profile, str(outside_dir), discard=True)
self.assertTrue(outside_dir.exists())
discard_dir, _, _ = make_draft(root, 'pageswiki-edit-discard', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw',
}, 'x\n')
with contextlib.redirect_stdout(io.StringIO()) as out:
m['recover'](client, profile, str(discard_dir), discard=True)
self.assertIn('Discarded recovery draft', out.getvalue())
self.assertFalse(discard_dir.exists())
def oidc_integration(): def oidc_integration():
fixture=json.load(sys.stdin) fixture=json.load(sys.stdin)
@@ -367,7 +838,7 @@ def oidc_integration():
return True return True
with tempfile.TemporaryDirectory() as root,patch.dict(os.environ,{'XDG_CONFIG_HOME':root}),contextlib.redirect_stdout(io.StringIO()) as output: with tempfile.TemporaryDirectory() as root,patch.dict(os.environ,{'XDG_CONFIG_HOME':root}),contextlib.redirect_stdout(io.StringIO()) as output:
m['main'](['configure','--origin',fixture['origin']]) m['main'](['configure','--origin',fixture['origin']])
with patch.object(Client,'json',capture),patch.object(m['webbrowser'],'open',browser): m['main'](['login','--oidc']) with patch.object(Client,'json',capture),patch.object(m['webbrowser'],'open',browser): m['main'](['login','--oidc','--with-open-browser'])
with Profile('default',root).locked() as session: with Profile('default',root).locked() as session:
token=session.data['token']; assert session.data['username']=='admin' token=session.data['token']; assert session.data['username']=='admin'
m['main'](['ls']); m['main'](['status']) m['main'](['ls']); m['main'](['status'])
+196 -1
View File
@@ -9,6 +9,183 @@ 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_deleted_capture_message_retains_draft_without_retry_loop(self):
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
original={'request_id':ident,'title':'Private title','notes':'Private notes'}
for status,code,message in [(410,'deleted','--recreate-deleted'),(409,'capture_missing','consistency repair'),(412,'conflict','unchanged retry'),(409,'note_exists','not overwritten')]:
profile=SimpleNamespace(data={'task_outbox':{ident:original.copy()}},save=lambda:None)
calls=[]
def send(*args,**kw):
calls.append(kw)
raise m['Failure']('old generic message',status,{'error':code})
output=io.StringIO()
with contextlib.redirect_stderr(output),self.assertRaises(m['Failure']) as error:
m['tasks'](SimpleNamespace(json=send),profile,['retry',ident])
self.assertIn(message,str(error.exception))
self.assertNotIn('Private',str(error.exception)+output.getvalue())
self.assertNotIn('retry with:',output.getvalue())
self.assertEqual(profile.data['task_outbox'][ident],original)
self.assertEqual(len(calls),1)
def test_recreate_deleted_persists_successor_and_retries_same_id(self):
import uuid
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
replacement=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+ident))
payload={'request_id':ident,'title':'Private title','wiki_body':'Private body','wiki_suffix':'2030/01/'+ident}
saved,calls=[],[]
profile=SimpleNamespace(data={'task_outbox':{ident:payload.copy()}})
profile.save=lambda:saved.append(json.loads(json.dumps(profile.data)))
def send(route,**kw):
calls.append(kw['data'].copy())
self.assertEqual(saved[-1]['task_outbox'][replacement],kw['data'])
self.assertNotIn(ident,saved[-1]['task_outbox'])
if len(calls)==1:raise m['Failure']('Connection lost')
return {'item':{'uuid':replacement}}
output,error=io.StringIO(),io.StringIO()
with contextlib.redirect_stdout(output),contextlib.redirect_stderr(error):
with self.assertRaises(m['Failure']):m['tasks'](SimpleNamespace(json=send),profile,['retry',ident,'--recreate-deleted'])
self.assertEqual(len(profile.data['task_outbox']),1)
m['tasks'](SimpleNamespace(json=send),profile,['retry',replacement])
self.assertEqual(calls[0],calls[1])
self.assertEqual(calls[0]['request_id'],replacement)
self.assertEqual(calls[0]['replaces_deleted'],ident)
self.assertEqual(calls[0]['wiki_suffix'],payload['wiki_suffix'])
self.assertEqual(calls[0]['wiki_body'],payload['wiki_body'])
self.assertEqual(profile.data['task_outbox'],{})
self.assertIn(replacement,error.getvalue())
self.assertNotIn('Private',error.getvalue())
def test_recreate_deleted_save_failure_keeps_original_and_sends_nothing(self):
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
payload={'request_id':ident,'title':'Draft'}
def fail():raise m['Failure']('disk full')
profile=SimpleNamespace(data={'task_outbox':{ident:payload.copy()}},save=fail)
calls=[]
with self.assertRaises(m['Failure']):m['tasks'](SimpleNamespace(json=lambda *a,**kw:calls.append(kw)),profile,['retry',ident,'--recreate-deleted'])
self.assertEqual(calls,[])
self.assertEqual(profile.data['task_outbox'],{ident:payload})
def test_recreate_deleted_never_clobbers_different_successor_draft(self):
import uuid
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
replacement=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+ident))
pending={ident:{'request_id':ident,'title':'Original'},replacement:{'request_id':replacement,'title':'Different'}}
before=json.loads(json.dumps(pending))
calls=[]
profile=SimpleNamespace(data={'task_outbox':pending},save=lambda:calls.append('save'))
with self.assertRaises(m['Failure']):m['tasks'](SimpleNamespace(json=lambda *a,**kw:calls.append('send')),profile,['retry',ident,'--recreate-deleted'])
self.assertEqual(calls,[])
self.assertEqual(pending,before)
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_keeps_month_but_replaces_changed_options(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))),contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
m['tasks'](client,profile,['from-mail','--wiki-prefix','/changed'])
self.assertEqual(len(calls),3)
self.assertEqual(calls[2]['request_id'],calls[0]['request_id'])
self.assertEqual(calls[2]['wiki_prefix'],'/changed')
self.assertEqual(next(iter(profile.data['task_outbox'].values())),calls[2])
def test_changed_capture_is_saved_before_send_and_retained_on_conflict(self):
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
saved,calls=[],[]
old={'request_id':ident,'title':'Old draft','notes':'Old private notes'}
profile=SimpleNamespace(data={'task_outbox':{ident:old}})
profile.save=lambda:saved.append(json.loads(json.dumps(profile.data)))
def send(route,**kw):
payload=kw['data'].copy();calls.append(payload)
self.assertEqual(saved[-1]['task_outbox'][ident],payload)
if len(calls)==1:raise m['Failure']('conflict',412,{'error':'conflict'})
return {'item':{'uuid':ident}}
client=SimpleNamespace(json=send)
out,err=io.StringIO(),io.StringIO()
with contextlib.redirect_stdout(out),contextlib.redirect_stderr(err):
with self.assertRaises(m['Failure']) as failure:
m['tasks'](client,profile,['add','New draft','--request-id',ident,'--notes','New private notes'])
self.assertEqual(failure.exception.status,412)
self.assertEqual(profile.data['task_outbox'][ident],calls[0])
self.assertEqual(len(calls),1) # No automatic server overwrite/retry.
m['tasks'](client,profile,['retry',ident])
self.assertEqual(calls[0],calls[1])
self.assertEqual(calls[0]['title'],'New draft')
self.assertEqual(profile.data['task_outbox'],{})
self.assertIn('Replaced the retained draft',err.getvalue())
self.assertNotIn('private notes',err.getvalue())
self.assertEqual(json.loads(out.getvalue())['item']['uuid'],ident)
def test_replacing_draft_does_not_send_when_local_save_fails(self):
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
def fail_save():raise m['Failure']('local write failed')
profile=SimpleNamespace(data={'task_outbox':{ident:{'request_id':ident,'title':'Old','notes':''}}},save=fail_save)
calls=[]
client=SimpleNamespace(json=lambda *a,**kw:calls.append(kw))
with self.assertRaises(m['Failure']):m['tasks'](client,profile,['add','New','--request-id',ident])
self.assertEqual(calls,[])
def test_full_outbox_allows_replacement_but_not_new_id(self):
import uuid
pending={str(uuid.uuid4()):{'title':'Old'} for _ in range(20)}
ident=next(iter(pending))
profile=SimpleNamespace(data={'task_outbox':pending},save=lambda:None)
calls=[]
def send(route,**kw):
calls.append(kw['data'].copy())
raise m['Failure']('offline')
client=SimpleNamespace(json=send)
with contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
m['tasks'](client,profile,['add','Replacement','--request-id',ident])
self.assertEqual(len(calls),1)
self.assertEqual(pending[ident]['title'],'Replacement')
with self.assertRaises(m['Failure']):m['tasks'](client,profile,['add','Another'])
self.assertEqual(len(calls),1)
self.assertEqual(len(pending),20)
def test_reimported_mail_replaces_body_and_removes_obsolete_options(self):
from unittest.mock import patch
raw=b'Subject: Old\r\nMessage-ID: <same@example.invalid>\r\n\r\nOLD BODY'
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)
changed=raw.replace(b'Subject: Old',b'Subject: New').replace(b'OLD BODY',b'NEW BODY')
for mail,args in [(raw,['--wiki-prefix','/old']),(changed,['--wiki-prefix','/new']),(changed,['--metadata-only'])]:
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(mail))),contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
m['tasks'](client,profile,['from-mail',*args])
self.assertEqual(len({c['request_id'] for c in calls}),1)
self.assertEqual(calls[1]['title'],'New')
self.assertIn('NEW BODY',calls[1]['wiki_body'])
self.assertNotIn('OLD BODY',calls[1]['wiki_body'])
for key in ('wiki_body','wiki_prefix','wiki_suffix'):self.assertNotIn(key,calls[2])
self.assertEqual(next(iter(profile.data['task_outbox'].values())),calls[2])
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 +193,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 &amp; 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 &amp; friends</p>'
body=m['task_mail'](raw)[3] body=m['task_mail'](raw)[3]
+55
View File
@@ -0,0 +1,55 @@
import contextlib
import io
import os
from pathlib import Path
import runpy
import time
import tempfile
import unittest
from unittest.mock import patch
m = runpy.run_path(str(Path(__file__).with_name('pages')))
class RememberTests(unittest.TestCase):
def test_expired_login_retains_same_account_drafts_and_path(self):
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ, {'XDG_CONFIG_HOME': root}), contextlib.redirect_stdout(io.StringIO()):
with m['Configuration']().locked() as config:
config.data = {'version': 1, 'default_profile': 'default', 'profiles': {'default': {'origin': 'https://wiki.example', 'username': 'anya', 'lang': 'auto'}}}
config.save()
with m['Profile']('default').locked() as profile:
profile.data = {'origin': 'https://wiki.example', 'username': 'anya', 'token': 'expired', 'expires': 1,
'cwd': '/projects/demo', 'task_outbox': {'request': {'title': 'synthetic draft'}}}
profile.save()
def login(client, username, password, *, remember=False):
self.assertTrue(remember)
client.token = 'pw_api_'+'x'*43
return time.time()+2592000
with patch.object(m['Client'], 'login', login), patch.object(m['getpass'], 'getpass', return_value='synthetic'):
m['main'](['login', '--remember'])
with m['Profile']('default').locked() as profile:
self.assertEqual(profile.data['cwd'], '/projects/demo')
self.assertEqual(profile.data['task_outbox']['request']['title'], 'synthetic draft')
self.assertTrue(profile.data['token'].startswith('pw_api_'))
def test_password_choice_is_explicit_and_bound_before_totp(self):
for remember in (False, True):
client = m['Client']('https://wiki.example')
challenge = m['Failure']('MFA', 401, {'mfa_required': True, 'challenge_token': 'challenge'})
result = {'access_token': 'pw_api_' + 'x'*43, 'token_type': 'Bearer', 'expires_in': 2592000}
with patch.object(client, 'json', side_effect=[challenge, result]) as api:
expiry = client.login('anya', 'synthetic-password', lambda _: '123456', remember=remember)
self.assertEqual(api.call_args_list[0].kwargs['form'].get('remember'), '1' if remember else None)
self.assertNotIn('remember', api.call_args_list[1].kwargs['form'])
self.assertAlmostEqual(expiry - time.time(), 2592000, delta=2)
def test_oidc_choice_is_bound_at_start(self):
for remember in (False, True):
client = m['Client']('https://wiki.example')
start = {'device_code': 'd'*43, 'verification_uri': '/_/auth/cli/verify?request='+'r'*43,
'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5}
result = {'access_token': 'pw_api_'+'x'*43, 'token_type': 'Bearer', 'expires_in': 2592000, 'username': 'anya'}
with patch.object(client, 'json', side_effect=[start, result]) as api, contextlib.redirect_stdout(io.StringIO()):
client.login_oidc(remember=remember, sleep=lambda _: None, clock=lambda: 0)
self.assertEqual(api.call_args_list[0].kwargs['form'].get('remember'), '1' if remember else None)
self.assertNotIn('remember', api.call_args_list[1].kwargs['form'])
+32
View File
@@ -5,6 +5,7 @@ import json
from pathlib import Path from pathlib import Path
import runpy import runpy
import sys import sys
import uuid
def run(): def run():
m=runpy.run_path(str(Path(__file__).with_name('pages'))) m=runpy.run_path(str(Path(__file__).with_name('pages')))
@@ -36,5 +37,36 @@ def run():
output=io.StringIO() output=io.StringIO()
with contextlib.redirect_stdout(output):m['contacts'](client,['export',contact['uuid']]) with contextlib.redirect_stdout(output):m['contacts'](client,['export',contact['uuid']])
assert 'UID:urn:test:cli' in output.getvalue() assert 'UID:urn:test:cli' in output.getvalue()
# A rejected capture can be corrected under the same request ID.
# A committed capture is still protected by the server receipt.
request_id=str(uuid.uuid4())
with contextlib.redirect_stderr(io.StringIO()):
try:task('add','Rejected draft','--request-id',request_id,'--estimate','-1')
except m['Failure'] as error:assert error.status==422
else:raise AssertionError('Invalid estimate accepted')
assert profile.data['task_outbox'][request_id]['estimate_minutes']==-1
corrected=task('add','Corrected draft','--request-id',request_id,'--estimate','15')['item']
assert corrected['uuid']==request_id and corrected['title']=='Corrected draft'
assert request_id not in profile.data['task_outbox']
try:task('add','Changed after commit','--request-id',request_id,'--estimate','30')
except m['Failure'] as error:assert error.status==412
else:raise AssertionError('Committed capture silently overwritten')
assert profile.data['task_outbox'][request_id]['title']=='Changed after commit'
stored=task('show',request_id)['item']
assert stored['title']=='Corrected draft' and stored['estimate_minutes']==15
# Recreate explicitly after deletion; never revive the old DAV identity.
client.request(m['TASK_API']+'items/'+request_id,method='DELETE',etag='"'+str(stored['version'])+'"')
with contextlib.redirect_stderr(io.StringIO()):
try:task('retry',request_id)
except m['Failure'] as error:
assert error.status==410 and '--recreate-deleted' in str(error)
else:raise AssertionError('Deleted task implicitly recreated')
recreated=task('retry',request_id,'--recreate-deleted')['item']
replacement=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+request_id))
assert recreated['uuid']==replacement and recreated['title']=='Changed after commit'
assert recreated['estimate_minutes']==30 and not profile.data.get('task_outbox')
try:task('show',request_id)
except m['Failure'] as error:assert error.status==404
else:raise AssertionError('Deleted UUID resurrected')
if __name__=='__main__':run() if __name__=='__main__':run()
+1 -1
View File
@@ -142,7 +142,7 @@ class TLSTests(unittest.TestCase):
def test_oidc_client_uses_explicit_tls_context(self): def test_oidc_client_uses_explicit_tls_context(self):
client=Client(self.base,insecure=True) client=Client(self.base,insecure=True)
with patch.object(m['webbrowser'],'open') as browser,contextlib.redirect_stdout(io.StringIO()) as out: with patch.object(m['webbrowser'],'open') as browser,contextlib.redirect_stdout(io.StringIO()) as out:
_,username=client.login_oidc(no_browser=True,sleep=lambda _:None) _,username=client.login_oidc(sleep=lambda _:None)
browser.assert_not_called() browser.assert_not_called()
self.assertEqual(username,'synthetic') self.assertEqual(username,'synthetic')
self.assertEqual(client.token,self.token) self.assertEqual(client.token,self.token)
+17 -4
View File
@@ -6,11 +6,13 @@ import subprocess
import sys import sys
import tempfile import tempfile
import threading import threading
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
binary=str(Path(sys.argv[1]).resolve()) binary=str(Path(sys.argv[1]).resolve())
token='synthetic_session_'+('x'*40) token='synthetic_session_'+('x'*40)
seen=[] seen=[]
captures=[]
class Handler(BaseHTTPRequestHandler): class Handler(BaseHTTPRequestHandler):
def log_message(self,*args):pass def log_message(self,*args):pass
def do_POST(self): def do_POST(self):
@@ -20,6 +22,10 @@ class Handler(BaseHTTPRequestHandler):
elif self.path=='/_/api/v1/extension/organizer.tasks/capture': elif self.path=='/_/api/v1/extension/organizer.tasks/capture':
if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return
item=json.loads(body) item=json.loads(body)
captures.append(item.copy())
if item.get('wiki_prefix')=='/rejected':self.reply({'error':'invalid'},422);return
if item.get('wiki_prefix')=='/deleted' and not item.get('replaces_deleted'):self.reply({'error':'deleted'},410);return
if item.get('replaces_deleted') and item['request_id']!=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+item['replaces_deleted'])):self.send_error(422);return
if item.get('wiki_body') != 'Message-ID: <smoke@example.invalid>\n\nPRIVATE BODY':self.send_error(422);return if item.get('wiki_body') != 'Message-ID: <smoke@example.invalid>\n\nPRIVATE BODY':self.send_error(422);return
item.pop('wiki_body');self.reply({'item':item,'page_path':'/private/mail/synthetic'}) item.pop('wiki_body');self.reply({'item':item,'page_path':'/private/mail/synthetic'})
else:self.send_error(404) else:self.send_error(404)
@@ -29,8 +35,8 @@ class Handler(BaseHTTPRequestHandler):
if self.path.startswith('/_/api/v1/extension/organizer.contacts/items?'): if self.path.startswith('/_/api/v1/extension/organizer.contacts/items?'):
self.reply({'items':[{'name':'Synthetic Person','emails':['person@example.invalid'],'organization':'Test'}]}) self.reply({'items':[{'name':'Synthetic Person','emails':['person@example.invalid'],'organization':'Test'}]})
else:self.reply({'items':[{'uuid':'synthetic-task','title':'Packaged CLI task','status':'todo'}]}) else:self.reply({'items':[{'uuid':'synthetic-task','title':'Packaged CLI task','status':'todo'}]})
def reply(self,value): def reply(self,value,status=200):
self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps(value).encode()) self.send_response(status);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps(value).encode())
server=ThreadingHTTPServer(('127.0.0.1',0),Handler) server=ThreadingHTTPServer(('127.0.0.1',0),Handler)
thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start() thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
@@ -46,15 +52,22 @@ try:
run('login',stdin='synthetic-password\n') run('login',stdin='synthetic-password\n')
if 'Packaged CLI task' not in run('task','list'):raise AssertionError('Task missing') if 'Packaged CLI task' not in run('task','list'):raise AssertionError('Task missing')
mail='Subject: Mail task\r\nMessage-ID: <smoke@example.invalid>\r\nContent-Type: text/plain\r\n\r\nPRIVATE BODY' mail='Subject: Mail task\r\nMessage-ID: <smoke@example.invalid>\r\nContent-Type: text/plain\r\n\r\nPRIVATE BODY'
captured=run('task','from-mail',stdin=mail) run('task','from-mail','--wiki-prefix','/rejected',stdin=mail,success=False)
captured=run('task','from-mail','--wiki-prefix','/private/mail',stdin=mail)
if len(captures)!=2 or captures[0]['request_id']!=captures[1]['request_id'] or captures[1]['wiki_prefix']!='/private/mail':raise AssertionError('Retained draft was not overwritten under the same request ID')
if 'Mail task' not in captured or 'PRIVATE BODY' in captured:raise AssertionError('Mail privacy') if 'Mail task' not in captured or 'PRIVATE BODY' in captured:raise AssertionError('Mail privacy')
run('task','from-mail','--wiki-prefix','/deleted',stdin=mail,success=False)
deleted_id=captures[-1]['request_id']
restored=json.loads(run('task','retry',deleted_id,'--recreate-deleted'))['item']
if restored['request_id']!=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+deleted_id)) or restored['replaces_deleted']!=deleted_id:raise AssertionError('Recreation identity')
contact=run('contacts','query','--neomutt','--','--name') contact=run('contacts','query','--neomutt','--','--name')
if 'person@example.invalid\tSynthetic Person\tTest' not in contact:raise AssertionError('NeoMutt query') if 'person@example.invalid\tSynthetic Person\tTest' not in contact:raise AssertionError('NeoMutt query')
run('shell',stdin='pwd\nexit\n') run('shell',stdin='pwd\nexit\n')
profile=Path(root)/'pages-cli/sessions/default.json' profile=Path(root)/'pages-cli/sessions/default.json'
if json.loads(profile.read_text()).get('task_outbox'):raise AssertionError('Successful replacement remains pending')
if profile.stat().st_mode&0o077:raise AssertionError('Credential permissions') if profile.stat().st_mode&0o077:raise AssertionError('Credential permissions')
profile.chmod(0o644);run('task','list',success=False);profile.chmod(0o600) profile.chmod(0o644);run('task','list',success=False);profile.chmod(0o600)
run('logout') run('logout')
if not seen:raise AssertionError('No HTTP request') if not seen:raise AssertionError('No HTTP request')
print('Packaged CLI: configure/login/task-list/mail-capture/neomutt-query/shell/permissions/logout passed') print('Packaged CLI: configure/login/task-list/mail-capture/draft-overwrite/deleted-recreation/neomutt-query/shell/permissions/logout passed')
finally:server.shutdown();server.server_close();thread.join() finally:server.shutdown();server.server_close();thread.join()