Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80d297dab4 | ||
|
|
52b501d1ce | ||
|
|
7187af42ed | ||
|
|
8733645747 | ||
|
|
9861b19f7b | ||
|
|
fdb411a896 |
No files matched your search
@@ -1,5 +1,7 @@
|
||||
# pages-cli:`pages` HTTPクライアント
|
||||
|
||||
2026-11-06:利用者向けの[クライアント契約](https://git.anya.jp/anya/pages-cli/src/branch/main/docs/client-contract.md)と[NeoMutt連携](https://git.anya.jp/anya/pages-cli/src/branch/main/docs/neomutt.md)は独立した公開pages-cliリポジトリへ移転した。本書はサーバー側のHTTP・OIDC認証契約、結合テストと導入履歴を保持する。下記のv0.3.0/v0.4.0は分離前のサーバー同梱版の番号であり、独立CLIはv0.1.0から採番する。
|
||||
|
||||
2026-11-01。合成データで検証済み。同日、本番サーバのCity更新と合わせてクライアントをホストの `/home/anya/.local/bin/pages` に配置した。実ユーザの資格情報取得・ログイン・本番Page編集は未実施。接続設定とログインは利用者が行う。[反映記録](../../operations/deployments/2026-11-01-city-pages-cli.md)。
|
||||
|
||||
v0.3.0のOIDCログインは利用者の動作確認済み。v0.4.0ではOIDC承認時の追加ローカルTOTPを廃止し、CLIの `auto` 言語選択と既存Pageの新規言語版編集を実装した。2026-11-01 21:48 JSTに本番サーバー/PATH上のCLIへ反映済み。[v0.4.0反映記録](../../operations/deployments/2026-11-01-v0.4.0.md)。
|
||||
|
||||
@@ -20,7 +20,17 @@ captureは省略した項目に本人の既定値を適用する。日付の空
|
||||
|
||||
Webの新規作成・クイック追加・サブタスク追加でも既定値を読む。サブタスクのプロジェクト・優先度・bucketは親の所属を優先する。既存汎用items APIとCalDAVではクライアント指定を尊重し、新しいcaptureの既定値を暗黙適用しない。
|
||||
|
||||
同じrequest_id・同じ要求内容の再送は既存タスクを返す。最初の保存後に既定値やタスクが更新されても作り直さない。同じrequest_idで別内容を送ると412。要求のreceiptとタスクRevisionは同一トランザクションで保存する。API入力は32 KiBまで、件名300 UTF-8 bytes、メモ16 KiBまで。
|
||||
同じrequest_id・同じ要求内容の再送は既存タスクを返す。最初の保存後に既定値やタスクが更新されても作り直さない。同じrequest_idで別内容を送ると412。要求のreceiptとタスクRevisionは同一トランザクションで保存する。captureのJSON入力は2 MiBまで、その他の作成・更新は32 KiBまで。件名300 UTF-8 bytes、メモ16 KiBまで。
|
||||
|
||||
### メール本文のWiki保存
|
||||
|
||||
v0.8.0ではcaptureに省略可能な `wiki_body` と `wiki_prefix` を追加する。wiki_bodyを省略した従来クライアントの契約・receipt hashは変えない。本文を指定した場合、親Pathは要求のwiki_prefix、個人preferencesのwiki_prefix、選択プロジェクトの関連WikiとNotesSubpath(未設定はtasks)の順に解決する。いずれもなければ422 `wiki_prefix_required`。空の明示指定も拒否する。個人設定はDomain・本人単位で、既存preferences JSONに保存するため新規schema migrationは不要。
|
||||
|
||||
本文は256 KiBまでのUTF-8テキスト。H1に件名、preに本文をHTMLエスケープして格納し、波括弧も実体参照にしてマクロを実行しない。Pathは `親Path/安全化した件名--request_id`。既存Pathとの競合は409で、既存ページへ追記・上書きしない。新規Wikiのobject/path/revisionとactivity outbox、タスクのPageUUID、capture receiptは同一DBトランザクションで保存する。rollback時に未参照のcontent-addressed Documentファイルが残る可能性は既存DocumentStoreと同様だが、公開可能なページや片方だけのタスクは残さない。
|
||||
|
||||
保存前に対象Pathへのread/create/write権限を検証する。個人タスクの所有権はWikiへの権限を付与しない。Wiki本文の公開範囲は保存先のACLに従うため、個人設定UIに注意を表示する。再送は既定値の再解決より前にreceiptを確認し、既定Pathの変更で重複作成しない。成功応答はitemとpage_pathを返し、タスクの既存メモ操作から関連Wikiへ移動できる。
|
||||
|
||||
個人設定の既定プロジェクトは保存済みUUIDを選択状態・既定選択状態の双方に反映する。最初の100候補にない場合も本人のitemを取得して名前を表示し、取得できない場合はUUIDを保持して別項目の保存で意図せず解除しない。CLIの本文抽出・再送・NeoMutt設定は独立pages-cliリポジトリを正本とする。
|
||||
|
||||
calendar-captureも同じUIDを再利用し、再送で既存予定を上書きしない。時刻は `2026-11-02T09:00` のドメイン時刻、またはオフセット付きRFC 3339。終了は開始後、最大31日。予定内容を取得する前にPersonalLocal制約をロック内で検査する。外部取り込みカレンダーの内容を読まない。
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# PagesWiki v0.7.1 本番反映
|
||||
|
||||
2026-11-06 02:11:04 JST、本番のapp・app2・adaptor-gateway・excalidraw-viewerをv0.7.1へ更新した。タスク編集画面の2カラム化と個人別Inbox通知既定値を反映した。配布物とdigestは[リリース記録](../releases/2026-11-04-v0.7.1.md)を参照する。ソースrevisionは `a6bf3dfe41bec1896acf6a047562f79b6028836b`。
|
||||
|
||||
## 切替と保全
|
||||
|
||||
公開済み3イメージのdigestとrevisionを照合した。旧バックアップの独立コピー2系統で、ネットワークなし・DR workers無効の起動確認と管理対象12コンポーネントのschema checkを実施し、成功した。
|
||||
|
||||
`.deployment-backups/release-v0.7.1-20261106/` に旧Compose、`.env`、旧 `.env.release` と切替直前の `cutover/data`・`cutover/data2` を保持する。親ディレクトリ0700、保存した `.env` は0600。停止後のチェックサム付き最終同期、差分ゼロ、DB・WAL・SHMのバイト一致、稼働ファイルと異なるinodeを確認した。変更のないファイルは過去の不変バックアップとのみlink-destで共有する。
|
||||
|
||||
| 時刻 JST | 操作 |
|
||||
| --- | --- |
|
||||
| 02:09:36 | 対象4サービスの停止開始 |
|
||||
| 02:10:58 | 最終バックアップ検証完了 |
|
||||
| 02:11:04 | v0.7.1の起動完了 |
|
||||
|
||||
停止開始から起動完了まで88秒。`.env.release` をv0.7.1に設定し、registry overlayで対象サービスだけ `up --no-build --no-deps` した。旧v0.7.0イメージには `rollback-before-v0.7.1-20261106` を付けて保持した。ローカルlatestは新バージョンへ揃えた。registry latest、code-server、Kroki等は変更していない。旧バックアップは削除せず、今回のリハーサルコピーだけを停止・検証後に削除した。終了時の空き容量は約40 GiB。
|
||||
|
||||
DBスキーマはv0.7.0と同じ。旧版へ戻して個人設定を再保存すると新しい通知既定値を失う可能性があるため、切戻しは書込みを停止して現行データも保全し、互換性を確認する。バックアップの自動復元は行わない。
|
||||
|
||||
## 本番確認
|
||||
|
||||
- 対象4サービスのrevision一致、起動状態正常、再起動0回。appとExcalidrawのhealthcheckはhealthy。app2の内部healthも成功。
|
||||
- 両系統の管理対象12コンポーネントはcurrent。これはlegacy領域を含む全データの完全性検査ではない。
|
||||
- 公開HTTPSのhealthとログイン入口は200。匿名のタスク画面・個人設定は303、preferences APIとCardDAV入口は401。
|
||||
- 公開されたtasks.js、task-productivity.js、tasks.cssのSHA-256がv0.7.1ソースと一致。
|
||||
- 初期ログのpanic、fatal、DB lock、job failed、scheduler claim failed、errorレベルの該当件数は0。
|
||||
|
||||
本番の実ユーザーデータを作成・更新するUI試験は行っていない。認証済み操作はリリース前の合成データ試験で確認済み。外部取り込みカレンダー要素にはアクセスせず、バックアップは内容を解釈しないファイルコピーとした。ホストのCLIはこの切替では置き換えていない。
|
||||
@@ -1,109 +1,10 @@
|
||||
# neomuttとpages CLIによるタスク管理
|
||||
# NeoMutt連携ドキュメントの移転
|
||||
|
||||
メールからタスクを作り、作業の開始・終了を記録し、個人アドレス帳をneomuttの宛先補完に使う。先に通常の端末でpages-cliを設定してログインする。neomuttの設定やシェル履歴にトークンを書かない。
|
||||
NeoMuttとpages CLIによるメールからのタスク作成、作業時間の記録・レポート、日次メール設定、連絡先の宛先補完の利用手順は、独立した公開リポジトリへ移転した。
|
||||
|
||||
```sh
|
||||
pages configure --origin https://pages.anya.jp --username YOUR_USERNAME
|
||||
pages login --oidc --no-browser
|
||||
pages task --help
|
||||
```
|
||||
- [NeoMuttとタスク・連絡先の操作ガイド](https://git.anya.jp/anya/pages-cli/src/branch/main/docs/neomutt.md)
|
||||
- [NeoMutt設定ファイル例](https://git.anya.jp/anya/pages-cli/src/branch/main/examples/neomuttrc)
|
||||
- [CLIの接続・保存・安全性の契約](https://git.anya.jp/anya/pages-cli/src/branch/main/docs/client-contract.md)
|
||||
- [CLIリポジトリと配布物](https://git.anya.jp/anya/pages-cli)
|
||||
|
||||
別接続を使うときは `pages --profile NAME task ...`。保存セッションはprivateなプロファイルファイルを使い、処理中はプロファイルロックを取得する。
|
||||
|
||||
## メールから作成
|
||||
|
||||
```sh
|
||||
pages task from-mail < message.eml
|
||||
pages task from-mail --project '開発 計画' --due 2026-11-03 < message.eml
|
||||
# 本文を保存してよいメールに限り明示する
|
||||
pages task from-mail --include-body < message.eml
|
||||
```
|
||||
|
||||
既定では件名をタスク名、From・Date・Message-IDをメモにする。本文と添付はアップロードしない。include-bodyはplain text本文だけを追加し、HTML画像・添付・外部URLは取得しない。1通2 MiB、メモ16 KiBが上限。件名が300 UTF-8 bytesを超える場合は `--title '短い件名'` で指定する。
|
||||
|
||||
同じ接続・本人・Message-IDから同じrequest_idを作るため、同じメールの再取り込みで重複しない。Message-IDなしはメール全体のSHA-256を使う。同じメールを別の独立タスクにもしたい場合は `task add` を使う。
|
||||
|
||||
`~/.config/neomutt/neomuttrc` の例。pagesの絶対パスはインストール先に合わせる。件名等をシェルコマンド文字列に展開せず、メールを標準入力で渡す。
|
||||
|
||||
```muttrc
|
||||
set pipe_split = yes
|
||||
set pipe_decode = no
|
||||
macro index,pager ,t "<pipe-message>/home/anya/.local/bin/pages task from-mail<enter>" "Create PagesWiki task"
|
||||
```
|
||||
|
||||
`,` → `t` で選択メールを取り込む。pipe_splitは複数メールを1つのMIME入力へ連結しないため、pipe_decode=noはCLI側でMIMEを解釈するための設定。既存のpipe操作にも影響するので、自分の設定と合わせて確認する。[NeoMutt設定リファレンス](https://neomutt.org/guide/reference.html)を参照。
|
||||
|
||||
## 通信失敗と再送
|
||||
|
||||
CLIは作成要求を送信前にprivateなセッションファイルへ保持する。失敗時に表示するrequest_idで明示的に再送する。
|
||||
|
||||
```sh
|
||||
pages task retry REQUEST_UUID
|
||||
```
|
||||
|
||||
最大20件を保留でき、成功した要求はローカルから削除する。同じ本人への再ログインで保留分を維持する。別アカウントへ切り替える場合は別プロファイルを使う。認証済みセッションがない状態からの完全オフライン入力受付ではない。
|
||||
|
||||
サーバーで保存された直後に応答が失われても、同じrequest_idで再送すれば既存タスクが返る。保留要求を書き換えて再送すると412になる。セッションファイルにはトークンもあるため、デバッグ目的で内容を貼り付けない。
|
||||
|
||||
## 計画と実績
|
||||
|
||||
```sh
|
||||
pages task project-add '開発 計画'
|
||||
pages task projects
|
||||
pages task preferences --project '開発 計画' --due-days 3 --review-days 1 --estimate 60 --complexity 2
|
||||
pages task add '設計をレビュー' --estimate 120 --planned 2026-11-02
|
||||
pages task list --view today
|
||||
pages task update TASK_UUID --due 2026-11-04
|
||||
pages task start TASK_UUID
|
||||
pages task status
|
||||
pages task stop
|
||||
pages task done TASK_UUID
|
||||
pages task report --from 2026-11-01 --to 2026-12-01
|
||||
pages task report --from 2026-11-01 --to 2026-12-01 --json
|
||||
```
|
||||
|
||||
stopは作業記録の終了、doneはタスクの完了。両者は独立している。見積は分単位、complexityは1〜5。期間のtoは含まない。CSV等への後処理にはJSONを使う。APIはドメインのタイムゾーンで日付を集計する。
|
||||
|
||||
日次メールを設定する例。SMTP設定と本人のメール登録が必要で、CLIを実行しただけでは第三者へ送信しない。
|
||||
|
||||
```sh
|
||||
pages task preferences --digest on --at 09:00 --timezone Asia/Tokyo
|
||||
pages task preferences --digest off
|
||||
```
|
||||
|
||||
## neomuttの宛先補完
|
||||
|
||||
```sh
|
||||
pages contacts list --query 田中
|
||||
pages contacts import contact.vcf
|
||||
pages contacts export CONTACT_UUID > contact.vcf
|
||||
pages contacts query 田中 --neomutt
|
||||
```
|
||||
|
||||
```muttrc
|
||||
set query_command = "/home/anya/.local/bin/pages contacts query --neomutt -- %s"
|
||||
bind editor <Tab> complete-query
|
||||
```
|
||||
|
||||
neomuttは%sをシェル用に引用するので、%sをさらに引用符で囲まない。出力は先頭の状態行と、メール・名前・所属のタブ区切り。`--`は検索語をCLIオプションとして解釈させないために付ける。標準のCtrl-Tによる補完を残したい場合はbind行を省略する。[外部アドレス検索](https://neomutt.org/guide/advancedusage.html#query)、[query_command](https://neomutt.org/guide/reference.html#query-command)。
|
||||
|
||||
連絡先は本人のDomain内だけを検索し、最大100件。メールアドレスのない連絡先は候補に出ない。ログイン切れの場合は通常の端末で再ログインする。書き出したvCardには非公開情報が含まれるため、ファイル権限と保存先を確認する。
|
||||
|
||||
## HTTPクライアントから使う
|
||||
|
||||
`POST https://pages.anya.jp/_/api/v1/extension/organizer.tasks/capture`
|
||||
|
||||
Content-Typeはapplication/json、AuthorizationはBearerセッション。例示UUIDは要求ごとに生成し、通信再送時だけ同じものを使う。
|
||||
|
||||
```json
|
||||
{
|
||||
"request_id": "884587b2-6ae5-4aef-86d0-fd21dac39d1c",
|
||||
"title": "メールで依頼された内容を確認",
|
||||
"notes": "Message-ID: <example@example.invalid>",
|
||||
"estimate_minutes": 30,
|
||||
"complexity": 2,
|
||||
"due_on": "2026-11-03"
|
||||
}
|
||||
```
|
||||
|
||||
成功は201とitem。認証切れ401、権限不足403、要求IDの内容競合412、不正入力422。トークンをクエリ文字列に含めず、HTTPSで送る。詳細は [タスクと連絡先の設計](../design/ja/task-productivity-contacts.md) を参照。
|
||||
利用者向け手順と設定例の正本はpages-cli側とし、このページは既存リンクの移転案内として残す。サーバーAPI・権限・DB・通知ジョブの設計は引き続き[タスクと連絡先の設計](../design/ja/task-productivity-contacts.md)で管理する。PagesWiki側の `pages-cli/` はHTTP結合テスト用の固定スナップショットであり、独立CLIの配布元ではない。
|
||||
@@ -0,0 +1,35 @@
|
||||
# pages-cliの公開リポジトリと配布
|
||||
|
||||
2026-11-06、サーバー本番をv0.7.1へ更新した後、pages-cliを[公開リポジトリ anya/pages-cli](https://git.anya.jp/anya/pages-cli)へ切り出し、[v0.1.0](https://git.anya.jp/anya/pages-cli/releases/tag/v0.1.0)をGitea Actionsから公開した。ソースとLinux/amd64成果物はログイン不要で取得できる。
|
||||
|
||||
同日、実行単位の `--insecure` / `-k` を追加したv0.2.0を公開した。最新の変更・TLS試験・配布確認は[v0.2.0リリース記録](releases/2026-11-06-pages-cli-v0.2.0.md)を参照。以下の切り出し・初回検証記録はv0.1.0時点のもの。
|
||||
|
||||
## ソースと互換性
|
||||
|
||||
`git subtree split --prefix=pages-cli` でCLI配下の5コミットを抽出した。抽出先の基点は `d3f4e668c448289f8cf264e4b7286ad772cf2d05`。サーバー側のCLIスナップショットは `pages-cli/pages`、SHA-256は `d423d1a38cb931880e78e419188083592d9163cdd958ace86f58849d141c4f41`。
|
||||
|
||||
独立先はCLIをルートの `pages` として保持し、独立SemVerの初版を0.1.0とする。サーバーのv0.7.1と番号を連動させない。`--version` とHTTP User-AgentをCLIのVERSIONへ合わせる。接続先・言語・セッション保存場所は変更しない。
|
||||
|
||||
独立したローカルリポジトリは `/home/anya/prj/pages/pages-cli` に配置し、originを公開Giteaリポジトリへ接続した。配布準備コミットは `e4fb4f309f9257498af678c3ae37d22039081b15`、公開用の説明修正後のコミットは `e3f1be2f6f99ced3d287cbe2155c3d614b0a133b`。公開前にCLIのみの履歴と追跡対象を確認し、秘密情報候補はテスト用の架空資格情報だった。サーバーの履歴・設定・データは含めない。
|
||||
|
||||
v0.1.0のソースは `7fa71eceb1ecbed84ad3bc904af3f3a473624b92`。NeoMutt連携ガイド、設定例、クライアント契約を独立リポジトリへ移転し、tar.gzにも同梱した。サーバーの旧ドキュメントは移転案内、HTTP/OIDCサーバー内部設計と結合テストはサーバー側に保持する。
|
||||
|
||||
サーバー側の3つのGo結合テストはCLIのスナップショットを参照している。切り出し時点では削除せず、独立リポジトリを正本にした後、レビュー済みリビジョンに固定して明示更新する。サーバーCI中に認証付きgit fetchを増やしたり、最新CLIへ暗黙追従したりしない。DB直接操作CLI `data/pageswiki-cli` は切り出し対象外。
|
||||
|
||||
## 配布方式
|
||||
|
||||
Linux/amd64はPython同梱ELF、tar.gz、ソーススクリプト、ビルドメタデータ、SHA256SUMSを生成する。Python 3.11のDebian 12イメージをdigest固定し、PyInstaller 6.22.0を使用する。最低glibcは2.36、Alpine/muslは対象外。rpm/debは後続で、まずELFを提供する。
|
||||
|
||||
Gitea Actionsのmain pushはテストとビルド、vタグはさらにRelease添付まで行う。draftへ全ファイルを添付後に公開し、公開済み同名ファイルのハッシュが異なれば停止する。API呼出しはジョブtokenを使用し、権限不足時のみCLIリポジトリ限定のrelease tokenを別途設定する。既存のサーバー用PATを自動コピーしない。
|
||||
|
||||
macOS用のnative buildジョブはrunner接続後に有効化する。Windows/amd64はfcntl・readline・所有者/権限検査の移植が必要で、未検証exeを公開しない。詳細TODOは独立作業コピーの `WINDOWS-TODO.md` に保持する。PyInstallerはクロスコンパイラではなく、OSごとの実ビルド・検証が必要。[公式説明](https://www.pyinstaller.org/en/stable/)
|
||||
|
||||
## 検証と残件
|
||||
|
||||
ソース単体テスト32件、実ELFのconfigure・合成HTTPログイン・タスク一覧・メール取り込み時の本文非送信・NeoMutt宛先検索・対話シェル・不正な資格情報ファイル権限の拒否・ログアウトを確認した。テストは一時ディレクトリと合成HTTPサーバーのみを使用し、本番ユーザーの資格情報は使用しない。
|
||||
|
||||
既存cp01dのホストにリポジトリ専用の `cp01d-pages-cli` を追加し、[初回CI run 29](https://git.anya.jp/anya/pages-cli/actions/runs/29)、[移転後CI run 30](https://git.anya.jp/anya/pages-cli/actions/runs/30)、[v0.1.0 Release CI run 31](https://git.anya.jp/anya/pages-cli/actions/runs/31)が成功した。既存runnerは変更していない。配置・停止方法は[runner運用記録](pages-cli-runner.md)を参照。
|
||||
|
||||
Releaseはジョブtokenで公開でき、追加PATは不要だった。添付5ファイルを匿名ダウンロードし、SHA256SUMS記載の4生成物を照合、ダウンロードしたELFの上記スモークテストを実施した。tar.gz内のREADME・NeoMuttガイド・クライアント契約・設定例がソースと一致し、メタデータのsource_revisionがタグ先コミットと一致することも確認した。
|
||||
|
||||
残件はmacOS runnerの設置、Windows移植とrunnerでの検証。実行ファイルのコード署名、macOS公証、rpm/debは後続。リポジトリ公開はオープンソースライセンスの新規付与とは別の操作であり、独自コードへのライセンスは追加していない。
|
||||
@@ -0,0 +1,34 @@
|
||||
# cp01d上のpages-cli専用runner
|
||||
|
||||
2026-11-06、既存のPagesWiki用runnerを維持したまま、同じcp01ホストへpages-cli用runnerを追加した。Giteaの登録名は `cp01d-pages-cli`、登録範囲は公開リポジトリ `anya/pages-cli` のみ。既存の `cp01d` は `anya/wikipages` 専用のまま変更していない。
|
||||
|
||||
## 配置と起動
|
||||
|
||||
- SSH接続先は既存設定の `cp01`。rootful Dockerを使用する。
|
||||
- Composeは `/var/container/gitea/runner-pages-cli/compose.yml`、プロジェクト名は `gitea-pages-cli`。
|
||||
- コンテナ名は `gitea-pages-cli-runner`、登録情報は `runner-pages-cli/data/.runner`(0600)。配置ディレクトリは0700。
|
||||
- runner設定は `runner-pages-cli/config.yaml`。capacity=1、timeout=2h、TLS検証有効、ジョブのprivileged=false。
|
||||
- イメージは既存と同じrunner v3.5.0のdigest `gitea/runner@sha256:66b7da94dc7dcadb2e076bec6928221336a9a637196399281c4b766fe1288242`。
|
||||
- 既存ネットワーク `anya-npm-net` と `git.anya.jp:172.18.0.10` の名前解決を使用。新規ネットワークやサブネットは作成していない。
|
||||
|
||||
```sh
|
||||
# cp01上で実行。既存のGitea・PagesWiki用runnerには影響しない。
|
||||
sudo docker compose -p gitea-pages-cli \
|
||||
-f /var/container/gitea/runner-pages-cli/compose.yml up -d --no-deps runner
|
||||
|
||||
# 新規ジョブの引受けを止める場合。実行中ジョブを確認してから行う。
|
||||
sudo docker compose -p gitea-pages-cli \
|
||||
-f /var/container/gitea/runner-pages-cli/compose.yml stop runner
|
||||
```
|
||||
|
||||
既存Gitea Composeへの依存を避け、追加runnerだけを独立Composeで管理する。restart=unless-stopped。サーバーや既存runnerの再起動・再登録は不要。既存Gitea用のComposeファイルだけを指定した操作では追加runnerは管理されない。
|
||||
|
||||
## 認証と公開ジョブ
|
||||
|
||||
登録トークンはCLIリポジトリ専用APIで取得し、暗号化SSHの標準入力から登録時の一時コンテナ環境へ渡した。Compose、Git、通常起動時の環境変数に登録トークンは保存しない。登録後は `.runner` を使う。`.runner` はコピー・公開せず、バックアップ時も権限を維持する。
|
||||
|
||||
ジョブラベルは `ubuntu-latest`。公開リポジトリのmain・バージョンタグ・手動実行のみを対象とし、外部PR実行は設定していない。Docker socketを使うため、ジョブにはホストに対する強い権限がある。レビューしていない外部コードをこのrunnerで実行しない。既存runnerとDocker daemonを共有するため、両runnerが同時に各1ジョブを実行できる。今後並列数を増やす場合はCPU・メモリ・ディスク負荷を確認する。
|
||||
|
||||
初回の既存待機ジョブrun 29と、NeoMutt移転後のrun 30が成功した。run 30では32件のテストと実ELFによる合成ログイン、メール→タスク、宛先検索、対話シェル、権限検査、ログアウトを確認した。macOS runnerは未接続のため対応ジョブを無効化している。
|
||||
|
||||
v0.1.0タグのrun 31ではRelease添付と公開も成功した。Giteaのジョブtokenを利用し、追加PATやActions secretは作成していない。公開後の匿名ダウンロードとSHA256照合、実バイナリの合成API試験も成功した。
|
||||
@@ -0,0 +1,41 @@
|
||||
# PagesWiki v0.7.1 リリース
|
||||
|
||||
2026-11-04、タスク編集画面の整理と個人別のInbox通知既定値を含むv0.7.1を公開した。Gitタグと3つのコンテナイメージを作成済み。リリース作成と本番切替は分離し、2026-11-06に[本番反映](../deployments/2026-11-06-v0.7.1.md)を完了した。
|
||||
|
||||
## 変更内容
|
||||
|
||||
- タスク編集をデスクトップでは左右2カラムへ整理。左に件名・状態・整理先・プロジェクト・メモ、右に日付・工数・複雑度・通知を配置する。
|
||||
- 状態・整理先・複雑度を、選択中の状態が分かるラジオボタン型UIに変更。担当者UUID、検索、Wiki連携は詳細設定へ折りたたむ。
|
||||
- 小型スマホでは1カラムとタッチ向けの入力領域を維持する。
|
||||
- 個人設定に、新規タスクの期限日・取り組む日のInbox通知ON/OFFと通知時刻を追加する。日付のない簡易追加を許可し、既存タスクの通知設定は変更しない。
|
||||
|
||||
詳細は[オーガナイザー設計](../../design/ja/organizer-dashboard.md)と[タスク通知設計](../../design/ja/task-reminders.md)を参照する。
|
||||
|
||||
## 配布物
|
||||
|
||||
- ソースcommit:`a6bf3dfe41bec1896acf6a047562f79b6028836b`。
|
||||
- 注釈付きGitタグ:`v0.7.1`。タグobject:`d25b4569ef9711a8b42f4085a2d78de3b7b5935f`。
|
||||
- [ビルド run 27](https://git.anya.jp/anya/wikipages/actions/runs/27):job 30のテスト・3イメージのビルド・push・後処理がすべて成功。
|
||||
- [リリース run 28](https://git.anya.jp/anya/wikipages/actions/runs/28):job 31の全工程が成功。SHAタグのイメージを再ビルドせず昇格した。
|
||||
|
||||
registry prefixは `git.anya.jp/anya/`。昇格処理でソースrevisionとlinux/amd64を確認し、昇格元・先のmanifest digestが一致することを検証した。
|
||||
|
||||
| イメージ | v0.7.1 manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:6cd80934ddbd7e8876f2b4c4e02b3a7f31ae1ecc8bcc88ea30637101f099b99e` |
|
||||
| pageswiki-adaptor-gateway | `sha256:fb4b5a488ccc1683ad4032cb61071ce9a433db7bcacde23f484daa8c5bfac7e9` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:b4a146ec43756bded73ceeec08b006f22100b354a957c685e05337d70190ce3c` |
|
||||
|
||||
今回の採番は利用者指定のv0.7.1とした。通知既定値の機能追加を含むため、通常の機能追加でMINORを増やす[運用規則](../versioning.md)の個別例外であり、規則全体は変更していない。公開済みタグの付け替えとlatestの更新は行っていない。
|
||||
|
||||
## 互換性と適用時の注意
|
||||
|
||||
DBスキーマとmanaged migrationのversionは変更しない。既存preferences JSONに `notify_due`、`notify_planned`、`reminder_time` を追加する。古い設定では通知OFF、時刻09:00として読み込む。既存タスクへの一括適用は行わない。
|
||||
|
||||
旧版に戻した後で個人設定を保存すると、新しい通知既定値が失われる可能性がある。スキーマ変更がなくても、切替前の設定・データの保全と切戻し時の書込み確認は必要。今回のリリース作成ではデプロイ用バックアップの作成・削除、本番データ更新、サービス再起動は行っていない。
|
||||
|
||||
## 検証
|
||||
|
||||
実装段階で全Goテスト、go vet、JS構文検査、差分検査、合成データのブラウザテストが成功した。ブラウザではPC・1024×768のノートPC・390px幅と320px幅のスマホ・英語表示、通知既定値の保存と適用、明示的な通知OFFの保持、再編集を検証した。本番のユーザーデータや外部取り込みカレンダーを検証に使用していない。
|
||||
|
||||
今回のリリースCIでも全Goテストとリリースツールのテストが成功した。サーバーパッケージは201.686秒、ストアは104.383秒で成功し、再実行は不要だった。配布物はレジストリへ公開済み。2026-11-06に本番適用と稼働確認を完了した。詳細は[本番反映記録](../deployments/2026-11-06-v0.7.1.md)を参照する。
|
||||
@@ -0,0 +1,29 @@
|
||||
# メール本文のWiki保存
|
||||
|
||||
PagesWiki v0.8.0とpages-cli v0.3.0で、NeoMuttからのメール取り込みを関連Wikiページ付きタスク作成へ拡張する。サーバーを先に更新し、その後CLIを更新する。
|
||||
|
||||
## 利用方法と互換性
|
||||
|
||||
個人設定 `/-/sys/config?panel=organizer` に「メール本文の既定Wiki親Path」を追加した。既定プロジェクトも現在の選択を表示し、候補の先頭100件にない場合は個別取得する。
|
||||
|
||||
```sh
|
||||
pages task preferences --wiki-prefix /YOUR/MAIL/PATH
|
||||
pages task from-mail < message.eml
|
||||
```
|
||||
|
||||
メール本文は保存先Wikiの公開範囲・閲覧権限に従う。非公開を保証する特別なPath名はないため、保存先の権限を先に確認する。タスクのメモ閲覧・編集から本文ページを開ける。タスクとWikiは同一トランザクションで保存する。
|
||||
|
||||
CLIの本文非送信は `--metadata-only`。旧 `--include-body` は既定動作の別名として残す。旧版で取り込み済みのメールに異なる内容を再送すると412となり、本文追加のために既存ページを暗黙上書きしない。
|
||||
|
||||
サーバーの新しいcaptureフィールドは任意で、従来CLIの要求hashを維持する。schema migrationはなく、WikiPrefixは既存preferences JSONに追加する。旧版へ切り戻す場合、新CLIのWiki保存を停止する。旧サーバーで個人設定を再保存すると新フィールドを落とす可能性があるので注意する。
|
||||
|
||||
## ソースと検証
|
||||
|
||||
独立CLIの対象コミットは `cde94ed`。サーバー内の `pages-cli/pages` と `test_productivity.py` はこのソースに明示更新した結合テスト用スナップショットで、配布元ではない。
|
||||
|
||||
- CLI単体テスト41件、合成HTTP経由のログイン・メール取り込み・連絡先・ログアウト。
|
||||
- GoのメールWiki作成、既定Path・明示Path・プロジェクト配下、再送、権限拒否、衝突、本文上限、トランザクションのロールバック。
|
||||
- 独立CLIスナップショットとGo APIの結合テスト。作成したページがタスクのメモ操作から開けることを確認。
|
||||
- Chromiumのデスクトップ・スマホ幅で、現在のプロジェクト選択・フォームリセット・Wiki Path保存を確認。デスクトップでは候補の先頭ページにないプロジェクトも検証。
|
||||
|
||||
配布・本番切替結果は確認後に追記する。外部取り込みカレンダーや実メール本文を検証のために読まない。
|
||||
@@ -0,0 +1,30 @@
|
||||
# pages-cli v0.2.0
|
||||
|
||||
2026-11-06、独立CLIへ実行単位のTLS検証スキップを追加し、[v0.2.0](https://git.anya.jp/anya/pages-cli/releases/tag/v0.2.0)を公開した。機能追加としてSemVerのMINORを増やした。サーバー本番はv0.7.1のままで、サービスの再起動・設定変更は不要。
|
||||
|
||||
## 動作
|
||||
|
||||
グローバルオプション `--insecure` / `-k` をコマンドの前に置く。指定した呼出しのCLI通信のみ証明書・ホスト名の検証をスキップする。設定とセッションには保存せず、既定は検証有効のまま。対話シェルでは終了まで有効。言語指定で編集用Clientを作り直す場合も指定を引き継ぐ。
|
||||
|
||||
```sh
|
||||
pages --insecure login
|
||||
pages -k task list
|
||||
pages -k edit /guide --lang ja
|
||||
pages -k login --oidc --no-browser
|
||||
pages -k logout
|
||||
```
|
||||
|
||||
警告は標準エラーへ出し、JSONやNeoMutt宛先候補へ混ぜない。`configure` は通信せず保存対象でもないため `-k configure` を拒否する。Python全体のTLS既定値は変更せず、OIDCブラウザやプロバイダーの証明書検証も変更しない。
|
||||
|
||||
期限切れ・ホスト名不一致も許容するため、通信相手の真正性を保証できず、資格情報を中間者に盗まれる危険がある。信頼できる検証環境でのみ明示指定する。遠隔HTTP、リダイレクト追従、TLS障害後の自動バイパス・自動再送は引き続き許可しない。利用者向けの正本は[CLI README](https://git.anya.jp/anya/pages-cli/src/tag/v0.2.0/README.md)と[NeoMuttガイド](https://git.anya.jp/anya/pages-cli/src/tag/v0.2.0/docs/neomutt.md)。
|
||||
|
||||
## リリースと検証
|
||||
|
||||
- ソースコミット:`59ab4c5b26e14a43dd372e5d8f7b6ef5df77a501`。
|
||||
- [main CI run 32](https://git.anya.jp/anya/pages-cli/actions/runs/32)と[tag Release CI run 33](https://git.anya.jp/anya/pages-cli/actions/runs/33)が成功。
|
||||
- ソース回帰試験38件、TLS試験スイート6件、既存の合成APIスモークテストが成功。TLS試験のログイン・タスク操作・対話シェル・ログアウトは生成ELFを呼び出して確認した。
|
||||
- TLS試験は一時生成した自己署名証明書とlocalhost HTTPSのみ。既定拒否、明示指定時の成功、ホスト名検証、通常のCA信頼、リダイレクト拒否、非永続化、OIDC開始・交換、言語指定編集への引継ぎを確認。
|
||||
- 公開された5添付を匿名取得し、SHA256SUMS記載の4生成物を照合。ダウンロードしたELFをサブプロセス試験対象に指定し、TLS試験スイート6件と合成APIスモークテストを再実行した。
|
||||
- メタデータのsource_revision、tar.gz内のELF、更新した利用ガイドが対象ソース・公開ELFと一致。
|
||||
|
||||
配布はLinux/amd64、glibc 2.36以上。macOS/Windowsバイナリは今回未配布。v0.1.0のタグ・成果物は維持した。ユーザーのインストール済み `pages` は自動で置き換えていない。証明書検証のスキップはRelease公開やGiteaアクセスには使用していない。
|
||||
@@ -23,6 +23,20 @@ func TestProductivityChromium(t *testing.T) {
|
||||
for _, size := range sizes {
|
||||
t.Run(view+"-"+size, func(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
if view == "settings" {
|
||||
project, err := s.store.SaveTask(context.Background(), domain, actor, newTaskRecord("project", "Saved default project"), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := s.store.TaskPreferences(context.Background(), domain, actor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.ProjectUUID = project.UUID
|
||||
if _, err = s.store.SaveTaskPreferences(context.Background(), domain, actor, p, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if size == "english" {
|
||||
if err := s.store.SetConfigInDomain(domain, "locale", "en"); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -50,6 +64,11 @@ func TestProductivityChromium(t *testing.T) {
|
||||
path := map[string]string{"contacts": "/v/plan/contacts", "settings": "/-/sys/config?panel=organizer", "report": "/v/plan/dashboard", "tasks": "/v/plan/tasks", "home": "/", "editor": "/v/plan/task/-/new"}[view]
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
// Simulate a saved project outside the first project list page.
|
||||
if view == "settings" && size == "desktop" && r.URL.Path == "/_/api/v1/extension/organizer.tasks/items" && r.URL.Query().Get("kind") == "project" {
|
||||
writeEventJSON(w, 200, map[string]any{"items": []any{}, "next": "fixture"})
|
||||
return
|
||||
}
|
||||
if r.Method == "GET" && r.URL.RequestURI() == path {
|
||||
rec := httptest.NewRecorder()
|
||||
s.withAuthorization(s.mux).ServeHTTP(rec, r)
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestTaskMailWikiCapture(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
ctx := context.Background()
|
||||
p, err := s.store.TaskPreferences(ctx, domain, actor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, bad := range []string{"mail", "/a/../b", "/_/api", "/v/blog", "/a?x", "/a//b", "/a\nb"} {
|
||||
p.WikiPrefix = bad
|
||||
if w := taskRequest(s, token, "PUT", "preferences", p, ""); w.Code != 422 {
|
||||
t.Fatal(bad, w.Code)
|
||||
}
|
||||
}
|
||||
p.WikiPrefix = "/private/mail"
|
||||
if _, err = s.store.SaveTaskPreferences(ctx, domain, actor, p, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := uuid.NewString()
|
||||
input := map[string]any{"request_id": id, "title": "Mail / {{children}}", "notes": "From: sender@example.invalid", "wiki_body": "Hello\n<script>bad()</script> {{children}}"}
|
||||
w := taskRequest(s, token, "POST", "capture", input, "")
|
||||
if w.Code != 201 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
var response struct {
|
||||
Item store.TaskRecord `json:"item"`
|
||||
Path string `json:"page_path"`
|
||||
}
|
||||
if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target := store.TaskCaptureWikiPath(p.WikiPrefix, input["title"].(string), id)
|
||||
if response.Item.PageUUID == "" || response.Path != target || strings.Contains(response.Item.Notes, "bad()") {
|
||||
t.Fatal(w.Body)
|
||||
}
|
||||
rev, err := s.store.GetLatestRevision(response.Item.PageUUID)
|
||||
if err != nil || !strings.Contains(rev.Body, "<script>bad()</script>") || strings.Contains(rev.Body, "{{children}}") {
|
||||
t.Fatal(rev, err)
|
||||
}
|
||||
// A committed retry remains stable even if the preference changes.
|
||||
p, err = s.store.TaskPreferences(ctx, domain, actor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.WikiPrefix = "/elsewhere"
|
||||
if _, err = s.store.SaveTaskPreferences(ctx, domain, actor, p, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 || !strings.Contains(w.Body.String(), response.Item.PageUUID) {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
input["wiki_body"] = "different"
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 412 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
input["request_id"] = uuid.NewString()
|
||||
input["wiki_prefix"] = "/explicit"
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 || !strings.Contains(w.Body.String(), "/explicit/") {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskMailWikiRollbackAndAccess(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
ctx := context.Background()
|
||||
id := uuid.NewString()
|
||||
title := "Mail"
|
||||
input := map[string]any{"request_id": id, "title": title, "wiki_body": "Mail body"}
|
||||
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 422 || !strings.Contains(w.Body.String(), "wiki_prefix_required") {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
input["wiki_prefix"] = "/mail"
|
||||
target := store.TaskCaptureWikiPath("/mail", title, id)
|
||||
absent := func() {
|
||||
t.Helper()
|
||||
if _, e := s.store.ResolvePathInDomain(domain, target); !errors.Is(e, sql.ErrNoRows) {
|
||||
t.Fatal("orphan Wiki", e)
|
||||
}
|
||||
if _, e := s.store.GetTask(ctx, domain, actor, id); !errors.Is(e, sql.ErrNoRows) {
|
||||
t.Fatal("orphan task", e)
|
||||
}
|
||||
}
|
||||
// Failure after document insert must roll back the entire capture, including receipt.
|
||||
if _, e := s.store.DB.Exec(`CREATE TRIGGER reject_capture BEFORE INSERT ON organizer_changes BEGIN SELECT RAISE(ABORT,'fixture'); END`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 500 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
absent()
|
||||
if _, e := s.store.DB.Exec(`DROP TRIGGER reject_capture`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, body := range []string{strings.Repeat("x", 256<<10+1), "bad\x00text"} {
|
||||
input["wiki_body"] = body
|
||||
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 422 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
absent()
|
||||
}
|
||||
input["wiki_body"] = "Mail body"
|
||||
other, e := s.store.CreatePasswordAccount(domain, "mailother", "long fixture password", "Other", "")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
otherToken, e := s.store.CreateAuthSession(domain, other.UUID)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if w := taskRequest(s, otherToken, "POST", "capture", input, ""); w.Code != 403 {
|
||||
t.Fatal("Wiki ACL", w.Code, w.Body)
|
||||
}
|
||||
absent()
|
||||
existing, e := s.store.CreatePageAtPathInDomain(domain, target)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 409 {
|
||||
t.Fatal("collision", w.Code, w.Body)
|
||||
}
|
||||
if got, e := s.store.ResolvePathInDomain(domain, target); e != nil || got != existing {
|
||||
t.Fatal("overwrite", e)
|
||||
}
|
||||
if _, e = s.store.GetTask(ctx, domain, actor, id); !errors.Is(e, sql.ErrNoRows) {
|
||||
t.Fatal("orphan collision task", e)
|
||||
}
|
||||
input["request_id"] = uuid.NewString()
|
||||
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskMailWikiProjectFallback(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
ctx := context.Background()
|
||||
root, e := s.store.CreatePageAtPathInDomain(domain, "/projects/app")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
project := newTaskRecord("project", "App")
|
||||
project.PageUUID = root
|
||||
project.NotesSubpath = "mail"
|
||||
project, e = s.store.SaveTask(ctx, domain, actor, project, 0)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
p, e := s.store.TaskPreferences(ctx, domain, actor)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
p.ProjectUUID = project.UUID
|
||||
if _, e = s.store.SaveTaskPreferences(ctx, domain, actor, p, time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
input := map[string]any{"request_id": uuid.NewString(), "title": "Project mail", "wiki_body": "Body"}
|
||||
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 || !strings.Contains(w.Body.String(), "/projects/app/mail/") {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,10 @@ package server
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -15,7 +17,11 @@ import (
|
||||
)
|
||||
|
||||
func taskJSON(w http.ResponseWriter, r *http.Request, output any) bool {
|
||||
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32768))
|
||||
return taskJSONLimit(w, r, output, 32768)
|
||||
}
|
||||
|
||||
func taskJSONLimit(w http.ResponseWriter, r *http.Request, output any, limit int64) bool {
|
||||
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(output) != nil || d.Decode(&struct{}{}) != io.EOF {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
@@ -61,6 +67,8 @@ type taskCaptureInput struct {
|
||||
ReviewOn *string `json:"review_on"`
|
||||
Estimate *int `json:"estimate_minutes"`
|
||||
Complexity *int `json:"complexity"`
|
||||
WikiBody *string `json:"wiki_body,omitempty"`
|
||||
WikiPrefix *string `json:"wiki_prefix,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request, actor string, active bool, kind string) {
|
||||
@@ -181,13 +189,23 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
|
||||
case "capture":
|
||||
if r.Method == "POST" {
|
||||
var input taskCaptureInput
|
||||
if !taskJSON(w, r, &input) {
|
||||
if !taskJSONLimit(w, r, &input, 2<<20) {
|
||||
return
|
||||
}
|
||||
if id, err := uuid.Parse(input.RequestID); err != nil || id.String() != input.RequestID {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
raw, _ := json.Marshal(input)
|
||||
hash := sha256.Sum256(raw)
|
||||
requestHash := hex.EncodeToString(hash[:])
|
||||
if old, e := s.store.CapturedTask(r.Context(), domain, actor, input.RequestID, requestHash); e == nil {
|
||||
s.taskResponse(w, r, old, 201)
|
||||
return
|
||||
} else if !errors.Is(e, sql.ErrNoRows) {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
p, err := s.store.TaskPreferences(r.Context(), domain, actor)
|
||||
if err != nil {
|
||||
taskError(w, err)
|
||||
@@ -211,9 +229,49 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
|
||||
item.Complexity = *input.Complexity
|
||||
}
|
||||
applyTaskReminderDefaults(&item, p)
|
||||
raw, _ := json.Marshal(input)
|
||||
hash := sha256.Sum256(raw)
|
||||
item, err = s.store.CaptureTask(r.Context(), domain, actor, input.RequestID, hex.EncodeToString(hash[:]), item)
|
||||
target, body := "", ""
|
||||
if input.WikiBody != nil {
|
||||
prefix := p.WikiPrefix
|
||||
if input.WikiPrefix != nil {
|
||||
prefix = *input.WikiPrefix
|
||||
}
|
||||
if prefix == "" && input.WikiPrefix == nil && item.ProjectUUID != "" {
|
||||
project, e := s.store.GetTask(r.Context(), domain, actor, item.ProjectUUID)
|
||||
if e != nil && !errors.Is(e, sql.ErrNoRows) {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
if e == nil && project.Kind == "project" && !project.Archived {
|
||||
if base := s.taskPagePath(r, project.PageUUID); base != "" {
|
||||
sub := project.NotesSubpath
|
||||
if sub == "" {
|
||||
sub = "tasks"
|
||||
}
|
||||
prefix = strings.TrimRight(base, "/") + "/" + sub
|
||||
}
|
||||
}
|
||||
}
|
||||
if prefix == "" {
|
||||
writeEventJSON(w, 422, map[string]string{"error": "wiki_prefix_required"})
|
||||
return
|
||||
}
|
||||
if !store.ValidTaskWikiPrefix(prefix) {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
target = store.TaskCaptureWikiPath(prefix, item.Title, input.RequestID)
|
||||
for _, capability := range []string{"read", "create", "write"} {
|
||||
if s.authorizePathRequest(r, capability, target) != nil {
|
||||
taskError(w, store.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
}
|
||||
body = *input.WikiBody
|
||||
} else if input.WikiPrefix != nil {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
item, err = s.store.CaptureTaskWithWiki(r.Context(), domain, actor, input.RequestID, requestHash, item, target, body)
|
||||
if err != nil {
|
||||
taskError(w, err)
|
||||
return
|
||||
|
||||
@@ -31,7 +31,12 @@ window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<12
|
||||
const exported=await fetch('/_/api/v1/extension/organizer.contacts/export.vcf').then(r=>r.text());if(!exported.includes('ブラウザ連絡先'))throw Error('Export missing');
|
||||
document.querySelector('#tasks-dav-open').click();await wait(()=>document.querySelector('#tasks-dav-dialog').open);const dav=document.querySelector('#tasks-dav-dialog');if(getComputedStyle(dav.querySelector('.dav-compat-toggle')).display!=='none')throw Error('CalDAV-only compatibility visible');fill(dav.querySelector('form>input'),'Browser contact client');dav.querySelector('form').requestSubmit();await wait(()=>!dav.querySelector('section').hidden);const credentials=await fetch('/_/api/v1/caldav-credentials').then(r=>r.json());if(credentials.items.length!==1||credentials.items[0].scope!=='contacts')throw Error('Wrong credential scope');dav.querySelector('tbody button').click();await wait(()=>!dav.querySelector('tbody button'));dav.querySelector('header button').click();
|
||||
}else if(path==='/-/sys/config'){
|
||||
await wait(()=>document.querySelector('[name=project_uuid] option:checked')?.textContent==='Saved default project');
|
||||
const savedProject=document.querySelector('[name=project_uuid]').value;
|
||||
document.querySelector('.productivity-settings').reset();if(document.querySelector('[name=project_uuid]').value!==savedProject)throw Error('Default project reset lost selection');
|
||||
fill(document.querySelector('[name=wiki_prefix]'),'/private/mail');
|
||||
await wait(()=>document.querySelector('[name=due_days]'));fill(document.querySelector('[name=due_days]'),'2');document.querySelector('[name=notify_due]').click();document.querySelector('[name=notify_planned]').click();fill(document.querySelector('[name=reminder_time]'),'08:45');document.querySelector('.productivity-settings').requestSubmit();await wait(()=>document.querySelector('#productivity-status').textContent.includes('保存'));const d=await fetch('/_/api/v1/extension/organizer.tasks/preferences').then(r=>r.json());if(d.preferences.due_days!==2||!d.preferences.notify_due||!d.preferences.notify_planned||d.preferences.reminder_time!=='08:45'||!d.defaults.notify_due||d.defaults.notify_planned)throw Error('Preferences missing');
|
||||
if(d.preferences.project_uuid!==savedProject||d.preferences.wiki_prefix!=='/private/mail')throw Error('Wiki destination or existing default project lost');
|
||||
}else if(path==='/v/plan/dashboard'){
|
||||
await wait(()=>document.querySelectorAll('.productivity-day').length>300);if(!document.querySelector('.productivity-day[data-level="2"]'))throw Error('Seven-point completion missing');
|
||||
if(document.querySelectorAll('[data-widget]').length!==6)throw Error('Widget registry missing');
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"html"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func ValidTaskWikiPrefix(p string) bool {
|
||||
if p == "" {
|
||||
return true
|
||||
}
|
||||
if len(p) > 500 || !utf8.ValidString(p) || !strings.HasPrefix(p, "/") || path.Clean(p) != p || strings.ContainsAny(p, "\\?#%:") || strings.IndexFunc(p, unicode.IsControl) >= 0 {
|
||||
return false
|
||||
}
|
||||
for _, part := range strings.Split(p, "/") {
|
||||
if part == "_" || part == ".." || part == "." {
|
||||
return false
|
||||
}
|
||||
}
|
||||
first := strings.Split(strings.TrimPrefix(p, "/"), "/")[0]
|
||||
switch first {
|
||||
case "-", "v", "e", "o", "r", "static", "raw":
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// A request UUID suffix separates equal subjects and makes the target stable.
|
||||
func TaskCaptureWikiPath(prefix, title, request string) string {
|
||||
item := TaskRecord{Title: title, UUID: request}
|
||||
name := path.Base(TaskNotePath("", TaskRecord{}, item))
|
||||
return strings.TrimRight(prefix, "/") + "/" + name + "--" + request
|
||||
}
|
||||
|
||||
func (s *Store) createCapturedTaskWiki(ctx context.Context, tx *sql.Tx, domain, actor string, item *TaskRecord, target, body string) error {
|
||||
if target == "" || !ValidTaskWikiPrefix(path.Dir(target)) || path.Clean(target) != target || item.PageUUID != "" || len(body) > 256<<10 || !utf8.ValidString(body) || strings.IndexByte(body, 0) >= 0 {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
var exists bool
|
||||
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM paths WHERE domain_uuid=? AND path=?)`, domain, target).Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
return ErrTaskNoteExists
|
||||
}
|
||||
item.PageUUID = uuid.NewString()
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO objects(uuid,kind,created_at) VALUES(?,'page',strftime('%s','now'))`, item.PageUUID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO paths(domain_uuid,path,object_uuid,created_at) VALUES(?,?,?,strftime('%s','now'))`, domain, target, item.PageUUID); err != nil {
|
||||
return err
|
||||
}
|
||||
// Mail is data, never HTML or executable wiki macros (including {{...}}).
|
||||
escape := func(v string) string {
|
||||
return strings.NewReplacer("{", "{", "}", "}").Replace(html.EscapeString(v))
|
||||
}
|
||||
content := "<h1>" + escape(item.Title) + "</h1>\n<pre>" + escape(body) + "</pre>\n"
|
||||
now := time.Now()
|
||||
rev := &Revision{UUID: uuid.NewString(), ObjectUUID: item.PageUUID, DocumentHash: revisionHash(content), Language: "und", ContentType: "text/html; charset=utf-8", Body: content, Message: "Capture mail as task Wiki", CreatedAt: now.Unix(), CreatedAtMS: now.UnixMilli()}
|
||||
if err := s.persistDocument(rev.DocumentHash, rev.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := insertRevision(tx, rev, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.appendRevisionActivityOutboxIfAvailable(tx, rev); err != nil {
|
||||
return err
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]string{"path": target, "object_uuid": item.PageUUID})
|
||||
return s.appendActivityOutboxIfAvailable(tx, ActivityOutboxEvent{DomainUUID: domain, ActorUUID: actor, EventType: "page.created", TargetKind: "page", TargetUUID: item.PageUUID, Payload: string(payload), IdempotencyKey: "page.created:" + item.PageUUID})
|
||||
}
|
||||
@@ -33,6 +33,7 @@ var taskProductivityMigrations = []db.SQLMigration{{Version: 1, Name: "task_capt
|
||||
type TaskPreferences struct {
|
||||
Version int64 `json:"version"`
|
||||
ProjectUUID string `json:"project_uuid"`
|
||||
WikiPrefix string `json:"wiki_prefix"`
|
||||
AssigneeUUID string `json:"assignee_uuid"`
|
||||
DueDays *int `json:"due_days"`
|
||||
StartDays *int `json:"start_days"`
|
||||
@@ -89,6 +90,9 @@ func (s *Store) SaveTaskPreferences(ctx context.Context, domain, actor string, p
|
||||
if s.ReadOnly {
|
||||
return p, ErrReadOnly
|
||||
}
|
||||
if !ValidTaskWikiPrefix(p.WikiPrefix) {
|
||||
return p, ErrTaskInvalid
|
||||
}
|
||||
// Older clients do not send this field. Preserve their default clock.
|
||||
if p.ReminderTime == "" {
|
||||
p.ReminderTime = "09:00"
|
||||
@@ -193,6 +197,12 @@ func (s *Store) CapturedTask(ctx context.Context, domain, actor, request, hash s
|
||||
}
|
||||
|
||||
func (s *Store) CaptureTask(ctx context.Context, domain, actor, request, hash string, item TaskRecord) (TaskRecord, error) {
|
||||
return s.CaptureTaskWithWiki(ctx, domain, actor, request, hash, item, "", "")
|
||||
}
|
||||
|
||||
// CaptureTaskWithWiki commits the task, receipt and optional Wiki page together.
|
||||
// The HTTP caller must authorize read/create/write for the exact target path.
|
||||
func (s *Store) CaptureTaskWithWiki(ctx context.Context, domain, actor, request, hash string, item TaskRecord, target, body string) (TaskRecord, error) {
|
||||
if _, err := uuid.Parse(request); err != nil {
|
||||
return TaskRecord{}, ErrTaskInvalid
|
||||
}
|
||||
@@ -204,10 +214,18 @@ func (s *Store) CaptureTask(ctx context.Context, domain, actor, request, hash st
|
||||
return old, err
|
||||
}
|
||||
item.UUID = request
|
||||
out, err := s.saveTask(ctx, domain, actor, item, 0, func(tx *sql.Tx, _ *TaskRecord, _ TaskRecord) error {
|
||||
out, err := s.saveTask(ctx, domain, actor, item, 0, func(tx *sql.Tx, current *TaskRecord, _ TaskRecord) error {
|
||||
if target != "" {
|
||||
if e := s.createCapturedTaskWiki(ctx, tx, domain, actor, current, target, body); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
_, e := tx.ExecContext(ctx, `INSERT INTO organizer_capture_receipts VALUES(?,?,?,?,?)`, domain, actor, request, hash, item.UUID)
|
||||
return e
|
||||
})
|
||||
if err == nil && target != "" {
|
||||
s.InvalidatePathCaches()
|
||||
}
|
||||
if err != nil {
|
||||
if old, e := s.CapturedTask(ctx, domain, actor, request, hash); e == nil {
|
||||
return old, nil
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# pages-cli
|
||||
|
||||
このディレクトリはサーバーのHTTP結合テスト用スナップショットです。CLIの配布・新規開発・利用手順の正本は[公開pages-cliリポジトリ](https://git.anya.jp/anya/pages-cli)へ移転しました。[NeoMutt連携ガイド](https://git.anya.jp/anya/pages-cli/src/branch/main/docs/neomutt.md)と[クライアント契約](https://git.anya.jp/anya/pages-cli/src/branch/main/docs/client-contract.md)も独立側を参照してください。
|
||||
|
||||
**`pages` — PagesWikiをターミナルから読む、たどる、編集する。**
|
||||
|
||||
プロファイルや言語は初回に設定し、普段のコマンドは短く保ちます。
|
||||
|
||||
+63
-18
@@ -10,6 +10,7 @@ import difflib
|
||||
import fcntl
|
||||
import getpass
|
||||
import hashlib
|
||||
from html.parser import HTMLParser
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -17,6 +18,7 @@ import posixpath
|
||||
import re
|
||||
import secrets
|
||||
import shlex
|
||||
import ssl
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -28,6 +30,7 @@ import urllib.parse as url
|
||||
import urllib.request as http
|
||||
import webbrowser
|
||||
|
||||
VERSION = '0.3.0'
|
||||
|
||||
class Failure(Exception):
|
||||
def __init__(self, message, status=0, payload=None):
|
||||
@@ -74,14 +77,23 @@ class NoRedirect(http.HTTPRedirectHandler):
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, base, token='', lang='auto'):
|
||||
def __init__(self, base, token='', lang='auto', *, insecure=False):
|
||||
self.base, self.token, self.lang = origin(base), token, lang
|
||||
self.opener = http.build_opener(NoRedirect())
|
||||
self.insecure = insecure
|
||||
handlers = [NoRedirect()]
|
||||
if insecure:
|
||||
# This client's TLS policy only; never change Python's global defaults.
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(['http/1.1'])
|
||||
handlers.append(http.HTTPSHandler(context=context))
|
||||
self.opener = http.build_opener(*handlers)
|
||||
|
||||
def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None):
|
||||
if not route.startswith('/') or route.startswith('//'):
|
||||
raise Failure('Invalid API route.')
|
||||
headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/0.1'}
|
||||
headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/' + VERSION}
|
||||
if etag is not None:
|
||||
headers['If-Match'] = etag
|
||||
if self.token:
|
||||
@@ -469,21 +481,42 @@ def task_project(client, value):
|
||||
return matches[0]
|
||||
|
||||
|
||||
def task_mail(raw, include_body=False, override_title=None):
|
||||
class MailText(HTMLParser):
|
||||
"""Extract inert text; never load links, images, styles or attachments."""
|
||||
def __init__(self):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.parts, self.hidden = [], []
|
||||
def handle_starttag(self, tag, attrs):
|
||||
if tag in ('script','style','head'): self.hidden.append(tag)
|
||||
if not self.hidden and tag in ('br','p','div','li','tr','h1','h2','h3','pre'): self.parts.append('\n')
|
||||
def handle_endtag(self, tag):
|
||||
if self.hidden and tag == self.hidden[-1]: self.hidden.pop()
|
||||
if not self.hidden and tag in ('p','div','li','tr','h1','h2','h3','pre'): self.parts.append('\n')
|
||||
def handle_data(self, data):
|
||||
if not self.hidden: self.parts.append(data)
|
||||
|
||||
|
||||
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.')
|
||||
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
||||
clean = lambda value: ' '.join(safe_text(str(value or '')).split())
|
||||
title = override_title or clean(message.get('Subject')) or '(No subject)'
|
||||
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))
|
||||
wiki_body = None
|
||||
if include_body:
|
||||
part = message.get_body(preferencelist=('plain',))
|
||||
content = ''
|
||||
part = message.get_body(preferencelist=('plain','html'))
|
||||
if part:
|
||||
content = part.get_content()
|
||||
try: content = part.get_content()
|
||||
except (LookupError, UnicodeError, ValueError) as e: raise Failure('Mail body encoding is not supported; convert to UTF-8 first.') from e
|
||||
if not isinstance(content,str): raise Failure('Mail body is not readable text.')
|
||||
notes += '\n\n' + content
|
||||
if len(notes.encode()) > 16384: raise Failure('Mail notes exceed 16 KiB; omit --include-body.')
|
||||
return title, notes, clean(message.get('Message-ID')) or hashlib.sha256(raw).hexdigest()
|
||||
if part.get_content_type() == 'text/html':
|
||||
parser = MailText();parser.feed(content);parser.close();content = ''.join(parser.parts).strip()
|
||||
wiki_body = 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 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
|
||||
|
||||
|
||||
def tasks(client, profile, words):
|
||||
@@ -497,7 +530,9 @@ def tasks(client, profile, words):
|
||||
p=sub.add_parser(name)
|
||||
if name=='add':p.add_argument('title')
|
||||
elif name=='update':p.add_argument('uuid',type=task_uuid);p.add_argument('--title')
|
||||
else:p.add_argument('--title');p.add_argument('--include-body',action='store_true')
|
||||
else:
|
||||
p.add_argument('--title');p.add_argument('--wiki-prefix',help='Wiki parent Path (otherwise use personal default or project Wiki subtree)')
|
||||
body=p.add_mutually_exclusive_group();body.add_argument('--include-body',action='store_true',help='Save body to Wiki (default; retained for compatibility)');body.add_argument('--metadata-only',action='store_true',help='Do not upload body or create a Wiki document')
|
||||
p.add_argument('--notes');p.add_argument('--project');p.add_argument('--assignee')
|
||||
p.add_argument('--due');p.add_argument('--start-on');p.add_argument('--planned');p.add_argument('--review')
|
||||
p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int,choices=range(1,6))
|
||||
@@ -507,7 +542,7 @@ def tasks(client, profile, words):
|
||||
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('report');p.add_argument('--from',dest='start');p.add_argument('--to',dest='end')
|
||||
p=sub.add_parser('preferences');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')
|
||||
a=parser.parse_args(words);action=a.action
|
||||
def emit(data): print(json.dumps(data,ensure_ascii=False,indent=2))
|
||||
@@ -516,8 +551,10 @@ def tasks(client, profile, words):
|
||||
if len(pending)>=20 and payload['request_id'] not in pending:raise Failure('20 pending captures retained. Retry them before adding more.')
|
||||
pending[payload['request_id']]=payload;profile.save()
|
||||
try: result=client.json(TASK_API+'capture',method='POST',data=payload)
|
||||
except Failure:
|
||||
print('Draft retained; retry with: pages task retry '+payload['request_id'],file=sys.stderr);raise
|
||||
except Failure as e:
|
||||
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
|
||||
raise
|
||||
del pending[payload['request_id']];profile.save();return result
|
||||
if action in ('list','projects'):
|
||||
query={'kind':'project' if action=='projects' else 'task','view':getattr(a,'view','all'),'limit':100,'q':getattr(a,'q',''),'before':getattr(a,'before','')}
|
||||
@@ -531,7 +568,7 @@ def tasks(client, profile, words):
|
||||
if action=='show':emit(client.json(TASK_API+'items/'+a.uuid));return
|
||||
if action=='preferences':
|
||||
data=client.json(TASK_API+'preferences');p=data['preferences'];changed=False
|
||||
for attr,key in [('project','project_uuid'),('assignee','assignee_uuid'),('due_days','due_days'),('start_days','start_days'),('planned_days','planned_days'),('review_days','review_days'),('estimate','estimate_minutes'),('complexity','complexity'),('at','digest_time'),('timezone','timezone')]:
|
||||
for attr,key in [('wiki_prefix','wiki_prefix'),('project','project_uuid'),('assignee','assignee_uuid'),('due_days','due_days'),('start_days','start_days'),('planned_days','planned_days'),('review_days','review_days'),('estimate','estimate_minutes'),('complexity','complexity'),('at','digest_time'),('timezone','timezone')]:
|
||||
value=getattr(a,attr)
|
||||
if value is not None:p[key]=task_project(client,value) if attr=='project' else value;changed=True
|
||||
if a.digest:p['digest_enabled']=a.digest=='on';changed=True
|
||||
@@ -543,8 +580,11 @@ def tasks(client, profile, words):
|
||||
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 ''}
|
||||
if action=='from-mail':
|
||||
title,notes,message_id=task_mail(sys.stdin.buffer.read((2<<20)+1),a.include_body,a.title)
|
||||
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)
|
||||
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 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')]:
|
||||
value=getattr(a,attr)
|
||||
if value is not None:payload[key]=task_project(client,value) if attr=='project' else value
|
||||
@@ -670,7 +710,7 @@ def execute(client, profile, words):
|
||||
route = addr[5:] if addr.startswith('path:') else '/o/' + addr if addr.startswith('uuid:') else '/r/view/' + addr[4:]
|
||||
webbrowser.open(client.base + url.quote(route, safe='/:'), new=2)
|
||||
elif cmd == 'edit':
|
||||
editing = Client(client.base, client.token, language(args.lang)) if args.lang else client
|
||||
editing = Client(client.base, client.token, language(args.lang), insecure=client.insecure) if args.lang else client
|
||||
editor(editing, addr, args.format)
|
||||
elif cmd == 'put':
|
||||
state = client.snapshot(addr)
|
||||
@@ -739,13 +779,16 @@ def shell(client, profile):
|
||||
|
||||
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.add_argument('--version', action='version', version='pages-cli ' + VERSION)
|
||||
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('-k', '--insecure', action='store_true', help='Skip TLS certificate and hostname verification for this invocation only (unsafe; place before COMMAND)')
|
||||
parser.add_argument('command', nargs='?', default='shell')
|
||||
parser.add_argument('args', nargs=argparse.REMAINDER)
|
||||
args = parser.parse_args(argv)
|
||||
if args.command == 'configure':
|
||||
if args.profile or args.lang: parser.error('Use pages configure set --profile NAME --lang TAG.')
|
||||
if args.insecure: parser.error('--insecure is invocation-only; configure does not connect or save a TLS bypass.')
|
||||
configure(args.args); return
|
||||
if args.command == 'help':
|
||||
parser.print_help(); return
|
||||
@@ -767,10 +810,12 @@ def main(argv=None):
|
||||
lang = language(args.lang or spec.get('lang', 'auto'))
|
||||
# Hold the profile lock before releasing the configuration lock.
|
||||
profile = stack.enter_context(Profile(name).locked())
|
||||
if args.insecure:
|
||||
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 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.')
|
||||
client = Client(spec['origin'], lang=lang)
|
||||
client = Client(spec['origin'], lang=lang, insecure=args.insecure)
|
||||
if login_args.oidc:
|
||||
expires, username = client.login_oidc(login_args.no_browser, spec.get('username', ''))
|
||||
else:
|
||||
@@ -799,7 +844,7 @@ def main(argv=None):
|
||||
if args.command != 'logout' and (profile.data.get('origin') != spec['origin'] or profile.data.get('configured_username', profile.data.get('username')) != spec.get('username', '')):
|
||||
raise Failure('Session and configured identity differ. Log out before reconnecting.')
|
||||
if args.command not in ('logout', 'status') and profile.data.get('expires', 0) <= time.time(): raise Failure('Session expired; log out and log in again.')
|
||||
client = Client(profile.data['origin'], profile.data['token'], lang)
|
||||
client = Client(profile.data['origin'], profile.data['token'], lang, insecure=args.insecure)
|
||||
if args.command == 'shell': shell(client, profile)
|
||||
else: execute(client, profile, [args.command] + args.args)
|
||||
|
||||
|
||||
@@ -11,13 +11,43 @@ m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||
class ProductivityTests(unittest.TestCase):
|
||||
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'
|
||||
title,notes,ident=m['task_mail'](raw)
|
||||
title,notes,ident,body=m['task_mail'](raw)
|
||||
self.assertEqual(title,'Test');self.assertNotIn('PRIVATE BODY',notes);self.assertIn('Message-ID:',notes)
|
||||
self.assertIn('PRIVATE BODY',m['task_mail'](raw,True)[1])
|
||||
self.assertIn('PRIVATE BODY',body)
|
||||
self.assertIsNone(m['task_mail'](raw,False)[3])
|
||||
raw=raw.replace(b'Subject: Test',b'Subject: '+b'a'*301)
|
||||
with self.assertRaises(m['Failure']):m['task_mail'](raw)
|
||||
self.assertEqual(m['task_mail'](raw,False,'Override')[0],'Override')
|
||||
|
||||
def test_html_mail_and_limits(self):
|
||||
raw=b'Subject: HTML\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<head><style>secret</style></head><p>Hello</p><script>evil()</script><img src="https://example.invalid/image"><p>World & friends</p>'
|
||||
body=m['task_mail'](raw)[3]
|
||||
self.assertIn('Hello\n',body);self.assertIn('World & friends',body)
|
||||
for value in ('secret','evil','https://'):self.assertNotIn(value,body)
|
||||
for body in (b'a'*(256<<10),b'bad\0text'):
|
||||
with self.assertRaises(m['Failure']):m['task_mail'](b'Subject: Test\r\n\r\n'+body)
|
||||
|
||||
def test_mail_payload_wiki_and_metadata_only(self):
|
||||
from unittest.mock import patch
|
||||
raw=b'Subject: Test\r\nMessage-ID: <same@example.invalid>\r\n\r\nPRIVATE BODY'
|
||||
calls=[]
|
||||
client=SimpleNamespace(base='https://example.invalid',json=lambda route,**kw:calls.append(kw['data'].copy()) or {'item':{'uuid':kw['data']['request_id']}})
|
||||
profile=SimpleNamespace(data={'username':'test'},save=lambda:None)
|
||||
for args in (['--wiki-prefix','/private/mail'],['--metadata-only']):
|
||||
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw))),contextlib.redirect_stdout(io.StringIO()):
|
||||
m['tasks'](client,profile,['from-mail',*args])
|
||||
self.assertIn('PRIVATE BODY',calls[0]['wiki_body']);self.assertNotIn('PRIVATE BODY',calls[0]['notes'])
|
||||
self.assertEqual(calls[0]['wiki_prefix'],'/private/mail')
|
||||
self.assertNotIn('wiki_body',calls[1]);self.assertEqual(calls[0]['request_id'],calls[1]['request_id'])
|
||||
|
||||
def test_multipart_prefers_plain_and_skips_attachment(self):
|
||||
from email.message import EmailMessage
|
||||
msg=EmailMessage();msg['Subject']='Mixed';msg.set_content('Plain body')
|
||||
msg.add_alternative('<p>HTML alternate</p>',subtype='html')
|
||||
msg.add_attachment(b'ATTACHMENT',maintype='application',subtype='octet-stream',filename='secret.bin')
|
||||
body=m['task_mail'](msg.as_bytes())[3]
|
||||
self.assertIn('Plain body',body);self.assertNotIn('alternate',body);self.assertNotIn('ATTACHMENT',body)
|
||||
|
||||
def test_capture_retains_request_until_explicit_retry(self):
|
||||
calls=[]
|
||||
def send(route,**kwargs):
|
||||
@@ -42,3 +72,12 @@ class ProductivityTests(unittest.TestCase):
|
||||
for cmd in [('task','--help'),('contacts','--help'),('task','add','--help')]:
|
||||
with contextlib.redirect_stdout(io.StringIO()),self.assertRaises(SystemExit) as raised:m['main'](list(cmd))
|
||||
self.assertEqual(raised.exception.code,0)
|
||||
|
||||
def test_neomutt_query_leading_dash_is_data(self):
|
||||
calls=[]
|
||||
def query(route):
|
||||
calls.append(route)
|
||||
return {'items':[{'name':'Person','emails':['person@example.invalid'],'organization':''}]}
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
m['contacts'](SimpleNamespace(json=query),['query','--neomutt','--','--unexpected'])
|
||||
self.assertIn('q=--unexpected',calls[0])
|
||||
@@ -5,6 +5,8 @@ import json
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
def run():
|
||||
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||
@@ -26,6 +28,16 @@ def run():
|
||||
task('done',ident)
|
||||
report=task('report','--json');assert sum(d['points'] for d in report['days'])==7
|
||||
assert any(i['uuid']==ident for i in report['tasks'])
|
||||
task('preferences','--wiki-prefix','/private/mail')
|
||||
mail=b'Subject: CLI mail\r\nMessage-ID: <integration@example.invalid>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPrivate mail body {{children}}'
|
||||
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(mail))):
|
||||
captured=task('from-mail')
|
||||
assert captured['item']['page_uuid'] and captured['page_path'].startswith('/private/mail/CLI mail--')
|
||||
assert 'Private mail body' not in captured['item']['notes']
|
||||
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(mail))):
|
||||
assert task('from-mail')['item']['page_uuid']==captured['item']['page_uuid']
|
||||
note=client.json(m['TASK_API']+'items/'+captured['item']['uuid']+'/note')
|
||||
assert note['linked'] and note['path']==captured['page_path']
|
||||
path=Path(fixture['root'])/'person.vcf'
|
||||
path.write_text('BEGIN:VCARD\r\nVERSION:4.0\r\nUID:urn:test:cli\r\nFN:CLI Person\r\nEMAIL:cli@example.invalid\r\nEND:VCARD\r\n')
|
||||
output=io.StringIO()
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
const word={tasks:['Tasks','タスク'],report:['Activity report','達成度・作業レポート'],settings:['Task defaults and email','タスクの既定値・メール'],contacts:['Contacts','連絡先'],completed:['Completed','完了件数'],points:['Points','ポイント'],work:['Work hours','作業時間'],focus:['Pomodoro hours','集中時間'],save:['Save','保存'],saved:['Saved','保存しました'],refresh:['Refresh','更新'],project_uuid:['Default project','既定のプロジェクト'],assignee_uuid:['Assignee UUID (annotation only)','担当者UUID(管理用メモ)'],due_days:['Due in days','期限までの日数'],start_days:['Start in days','着手までの日数'],planned_days:['Plan in days','取り組む日までの日数'],review_days:['Review in days','見直しまでの日数'],estimate_minutes:['Estimated minutes','見込み工数(分)'],complexity:['Complexity (1–5)','複雑度(1〜5)'],digest_enabled:['Email daily task list to my account email','毎日のやることリストを自分のメールに送る'],digest_time:['Delivery time','配信時刻'],timezone:['IANA timezone','タイムゾーン(IANA)'],none:['None','なし'],empty:['No records in this period.','この期間の記録はありません。'],partial:['Partial results: narrow the period.','件数上限に達しました。期間を狭めてください。'],error:['Request failed. Input is retained.','処理に失敗しました。入力は保持しています。'],email_required:['Set your account email first.','先にプロフィールにメールアドレスを設定してください。'],smtp_unavailable:['Ask an administrator to configure SMTP.','管理者によるSMTP設定が必要です。']};
|
||||
const t=k=>(word[k]||[k,k])[ja?1:0],el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
|
||||
Object.assign(word,{notify_due:['Notify on due dates','期限日に通知する'],notify_planned:['Notify on planned dates','取り組む日に通知する'],reminder_time:['Default notification time','通知の既定時刻']});
|
||||
Object.assign(word,{wiki_prefix:['Default Wiki parent path for mail','メール本文の既定Wiki親Path']});
|
||||
const status=root.querySelector('#productivity-status'),content=root.querySelector('#productivity-content');
|
||||
root.querySelectorAll('[data-word]').forEach(n=>n.textContent=t(n.dataset.word));root.querySelector('h1,h2,h3').textContent=t(root.dataset.view==='settings'?'settings':'report');
|
||||
async function request(path,options={}){const timeout=AbortSignal.timeout(15000);const r=await fetch(api+path,{credentials:'same-origin',cache:'no-store',signal:signal?AbortSignal.any([signal,timeout]):timeout,...options,headers:{'Content-Type':'application/json',...options.headers}});const d=await r.json().catch(()=>({}));if(!r.ok||r.redirected)throw Error(t(d.error||'error'));return d;}
|
||||
@@ -12,7 +13,8 @@
|
||||
async function settings(){
|
||||
const data=await request('preferences'),p=data.preferences;const form=el('form');form.className='productivity-settings';const fields={};
|
||||
const projects=await request('items?kind=project&view=all&limit=100');
|
||||
for(const key of ['project_uuid','assignee_uuid','due_days','start_days','planned_days','review_days','estimate_minutes','complexity','notify_due','notify_planned','reminder_time','digest_enabled','digest_time','timezone']){
|
||||
if(p.project_uuid&&!projects.items.some(x=>x.uuid===p.project_uuid)){try{const current=await request('items/'+encodeURIComponent(p.project_uuid));if(current.item.kind==='project')projects.items.unshift(current.item);}catch{ /* Keep the saved reference visible without exposing inaccessible data. */ }}
|
||||
for(const key of ['project_uuid','wiki_prefix','assignee_uuid','due_days','start_days','planned_days','review_days','estimate_minutes','complexity','notify_due','notify_planned','reminder_time','digest_enabled','digest_time','timezone']){
|
||||
if(key==='notify_due')form.append(el('h3',ja?'新規タスクのInbox通知':'Inbox reminders for new tasks'));
|
||||
if(key==='digest_enabled')form.append(el('h3',ja?'日次メール':'Daily email'));
|
||||
const label=el('label',t(key));label.className='productivity-setting';const input=el(key==='project_uuid'?'select':'input');input.name=key;
|
||||
@@ -21,11 +23,16 @@
|
||||
else if(key.endsWith('_days')||['estimate_minutes','complexity'].includes(key)){input.type='number';input.min=key==='complexity'?1:0;input.max=key.endsWith('_days')?3650:key==='complexity'?5:10080;input.step=1;}
|
||||
else input.type=['digest_time','reminder_time'].includes(key)?'time':'text';
|
||||
if(input.type!=='checkbox')input.value=p[key]??'';if(key==='reminder_time'){input.required=true;input.step=60;}input.disabled=root.dataset.writable!=='true';fields[key]=input;label.append(input);form.append(label);
|
||||
if(key==='project_uuid')for(const option of input.options)option.defaultSelected=option.selected=option.value===(p.project_uuid||'');
|
||||
else if(input.type==='checkbox')input.defaultChecked=input.checked;
|
||||
else input.defaultValue=input.value;
|
||||
if(key==='wiki_prefix'){input.placeholder='/private/mail';input.maxLength=500;const help=el('p',ja?'メール本文をWikiに保存する親Pathです。空欄ならプロジェクトのWiki配下を使います。保存した本文はそのPathの公開範囲・閲覧権限に従います。':'Parent path for mail Wiki pages. If blank, use the project Wiki subtree. Saved mail inherits the destination path’s visibility and read permissions.');help.className='productivity-note';form.append(help);}
|
||||
if(key==='reminder_time'){const help=el('p',ja?'新規タスクの対応する日付が設定されている場合だけ通知します。既存タスクは変更しません。通知時刻は保存時のドメインのタイムゾーン('+data.timezone+')を使用します。':'Reminders apply only to new tasks with the corresponding date. Existing tasks are unchanged. Times use the Domain timezone on save ('+data.timezone+').');help.className='productivity-note';form.append(help);}
|
||||
}
|
||||
const note=el('p',ja?'日数は作成日からの暦日です。空欄は未設定、0は当日。担当者の指定では閲覧権限は付与されません。メールは今日の計画・期限到来分を最大100件送ります。SMTPは管理者設定を使用し、配信時刻にはキュー待ちの遅延があります。':'Offsets are calendar days from creation; blank means unset, 0 means today. Assignment does not grant access. Email includes up to 100 tasks planned or due today, using administrator SMTP settings. Queue delays may apply.');note.className='productivity-note';form.append(note);
|
||||
if(data.last_digest){const states={sent:['Sent','送信済み'],sending:['Sending / result pending','送信中・結果未確定'],uncertain:['Delivery uncertain (no automatic retry)','結果不明(自動再送なし)'],cancelled:['Cancelled','送信取消']};form.append(el('p',(ja?'直近の配信: ':'Latest delivery: ')+data.last_digest.day+' · '+(states[data.last_digest.state]||['Unknown','不明'])[ja?1:0]));}
|
||||
const save=el('button',t('save'));save.type='submit';save.disabled=root.dataset.writable!=='true';form.append(save);content.replaceChildren(form);
|
||||
fields.project_uuid.value=p.project_uuid||'';
|
||||
form.onsubmit=async event=>{event.preventDefault();if(!form.reportValidity())return;save.disabled=true;const value={...p};for(const [key,input] of Object.entries(fields)){value[key]=input.type==='checkbox'?input.checked:input.type==='number'?(input.value===''?null:Number(input.value)):input.value;}try{const result=await request('preferences',{method:'PUT',body:JSON.stringify(value)});Object.assign(p,result.preferences);status.textContent=t('saved');}catch(e){error(e);}finally{save.disabled=false;}};
|
||||
}
|
||||
function taskTable(data){const wrap=el('div');wrap.className='productivity-table-wrap';const table=el('table');table.className='productivity-table';const head=el('tr');for(const name of [ja?'タスク':'Task',t('points'),t('work')])head.append(el('th',name));const thead=el('thead');thead.append(head);table.append(thead);const body=el('tbody');for(const task of data.tasks){const row=el('tr'),name=el('td'),link=el('a',(task.completed?'✓ ':'')+(task.title||task.uuid));link.href='/v/plan/task/'+encodeURIComponent(task.uuid);name.append(link);row.append(name,el('td',String(task.points||0)),el('td',(task.work_ms/3600000).toFixed(2)));body.append(row);}table.append(body);wrap.append(table);if(!data.tasks.length)wrap.append(el('p',t('empty')));return wrap;}
|
||||
|
||||
@@ -4,4 +4,4 @@
|
||||
{{ template "organizer-nav" . }}
|
||||
<main id="organizer-dashboard" data-writable="{{ .TaskWritable }}" data-calendar="{{ .CalendarEnabled }}" data-today="{{ .Today }}" data-timezone="{{ .Timezone }}">
|
||||
<header class="dashboard-toolbar"><div><h1>{{ T "organizer.dashboard" }}</h1><small>{{ .Today }} · {{ .Timezone }}</small></div><div id="dashboard-controls"></div></header><p id="dashboard-status" role="status" aria-live="polite"></p><div id="dashboard-grid"></div>
|
||||
</main><script src="/static/js/organizer-dashboard.js?v=1" defer></script><script src="/static/js/task-productivity.js?v=3" defer></script></body></html>{{ end }}
|
||||
</main><script src="/static/js/organizer-dashboard.js?v=1" defer></script><script src="/static/js/task-productivity.js?v=4" defer></script></body></html>{{ end }}
|
||||
@@ -5,4 +5,4 @@
|
||||
<section class="organizer-settings-content"><h1>{{ T "organizer.settings" }}</h1><p>{{ T "organizer.private" }}</p>
|
||||
{{ if .TasksEnabled }}<section id="task-productivity" data-view="settings" data-writable="{{ .TaskWritable }}"><h2></h2><p id="productivity-status" role="status" aria-live="polite"></p><div id="productivity-content"></div></section>{{ end }}
|
||||
{{ if .CalendarEnabled }}<section id="organizer-calendar-defaults" data-writable="{{ .TaskWritable }}"><h2>{{ T "organizer.calendar_defaults" }}</h2><p role="status"></p><div data-calendar-defaults></div></section>{{ end }}
|
||||
</section></div></main><script src="/static/js/task-productivity.js?v=3" defer></script><script src="/static/js/organizer-settings.js?v=1" defer></script></body></html>{{ end }}
|
||||
</section></div></main><script src="/static/js/task-productivity.js?v=4" defer></script><script src="/static/js/organizer-settings.js?v=1" defer></script></body></html>{{ end }}
|
||||
Reference in new issue
Block a user