Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6bf3dfe41 | ||
|
|
8fd0b6ec8b | ||
|
|
6ba30bc9f4 | ||
|
|
a9249009f0 | ||
|
|
19e12f96a8 | ||
|
|
433169c7e7 | ||
|
|
8988e5a2f8 | ||
|
|
b4792bb175 | ||
|
|
50b8b0323f | ||
|
|
93f4ecb8f4 | ||
|
|
5821254535 | ||
|
|
60f5fb1881 | ||
|
|
2af87b4f58 |
No files matched your search
@@ -9,6 +9,10 @@ language-neutral; existing English source documents remain here for traceability
|
|||||||
and future aligned translations, not as automatically current English editions.
|
and future aligned translations, not as automatically current English editions.
|
||||||
|
|
||||||
- Concepts and boundaries: chapters 1–6.
|
- Concepts and boundaries: chapters 1–6.
|
||||||
|
- [Organizer navigation and personal dashboard](ja/organizer-dashboard.md): shared navigation,
|
||||||
|
personal settings, resizable widgets, owner-scoped layout storage and extension boundaries.
|
||||||
|
- [Task capture, work reporting and private address book](ja/task-productivity-contacts.md):
|
||||||
|
shared Web/CLI API, neomutt, defaults, daily digest and home search commands.
|
||||||
- Existing product and runtime: chapters 7–11.
|
- Existing product and runtime: chapters 7–11.
|
||||||
- Organizer / task / calendar / RSS / mail / HTML editing proposals: chapters 12–17.
|
- Organizer / task / calendar / RSS / mail / HTML editing proposals: chapters 12–17.
|
||||||
- Operations, i18n, ordered work, decisions and sources: chapters 18–22.
|
- Operations, i18n, ordered work, decisions and sources: chapters 18–22.
|
||||||
|
|||||||
@@ -1,5 +1,29 @@
|
|||||||
# Architecture Implementation Roadmap
|
# Architecture Implementation Roadmap
|
||||||
|
|
||||||
|
## Organizer dashboard (2026-11-02)
|
||||||
|
|
||||||
|
- [x] Common navigation for tasks, calendars, contacts and dashboard; home/navbar contacts entry.
|
||||||
|
- [x] Owner-only personal settings at `/-/sys/config?panel=organizer`, without expanding admin permissions.
|
||||||
|
- [x] Task tabs, today/tomorrow tasks, daily completion, calendar and activity widgets; reorder/resize and versioned layout persistence.
|
||||||
|
- [ ] Shared dashboards, multiple widget instances and sandboxed third-party widgets.
|
||||||
|
|
||||||
|
See [dashboard contracts](ja/organizer-dashboard.md). Production rollout is a separate gate.
|
||||||
|
|
||||||
|
## Task productivity and private contacts (2026-11-01)
|
||||||
|
|
||||||
|
- [x] Add idempotent task capture API and neomutt configuration reference.
|
||||||
|
- [x] Extend pages-cli with task planning, start/stop records, reports and private contact lookup.
|
||||||
|
- [x] Add per-user defaults, accomplishment heatmap and opt-in daily SMTP task digest.
|
||||||
|
- [x] Add home search commands with project/calendar suggestions and explicit creation confirmation.
|
||||||
|
- [x] Add private contacts CRUD, trash/restore, vCard import/export and unknown-property preservation.
|
||||||
|
- [x] Add private CardDAV serving with isolated credentials, conditional writes, bounded reports and sync tokens; revision preview/restore and whole-book export (2026-11-02).
|
||||||
|
- [ ] Shared address books, external CardDAV connectors, physical-device compatibility, work-record corrections and manual digest retry.
|
||||||
|
|
||||||
|
See [CardDAV operation and limits](../operations/carddav-contacts.md). The private profile is not full CardDAV compliance; production rollout is tracked separately.
|
||||||
|
|
||||||
|
See [contracts and remaining scope](ja/task-productivity-contacts.md). These checks describe
|
||||||
|
the implemented slice; production rollout and test evidence are recorded separately.
|
||||||
|
|
||||||
## Current highest priority (2026-10-31)
|
## Current highest priority (2026-10-31)
|
||||||
|
|
||||||
The user-prioritized [daily UX / browser / editor / CLI backlog](ja/priority-ux-20261031.md)
|
The user-prioritized [daily UX / browser / editor / CLI backlog](ja/priority-ux-20261031.md)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 14. 予定・iCalendar・CalDAV・連絡先
|
# 14. 予定・iCalendar・CalDAV・連絡先
|
||||||
|
|
||||||
状態:カレンダー部分は2026-09-22にローカル正本・Plan UI・限定CalDAVを実装開始。最新の契約・実装範囲・残作業は [カレンダー詳細設計](calendar-implementation.md) を参照。以下の旧順序/URI案より同設計を優先する。連絡先と外部同期は引き続き設計案。
|
状態:カレンダー部分は2026-09-22にローカル正本・Plan UI・限定CalDAVを実装開始。最新の契約・実装範囲・残作業は [カレンダー詳細設計](calendar-implementation.md) を参照。2026-11-01に個人アドレス帳のCRUD・vCard入出力・neomutt検索、2026-11-02に個人CardDAV提供・履歴復元・一括exportを実装した。[個人アドレス帳の実装契約](task-productivity-contacts.md)と[CardDAV運用](../../operations/carddav-contacts.md)を以下の旧URI案より優先する。共有アドレス帳と外部CardDAV connectorは引き続き設計案。
|
||||||
|
|
||||||
## 四つのレイヤー
|
## 四つのレイヤー
|
||||||
|
|
||||||
@@ -37,7 +37,7 @@ address bookの所有者・共有範囲、contact UUID、remote UID、複数メ
|
|||||||
|
|
||||||
## URL/API案と実装順
|
## URL/API案と実装順
|
||||||
|
|
||||||
人向けは `/v/organizer`、APIは `/_/api/v1/extension/organizer.{calendar|contacts}/…` を候補とします。**未実装・未予約**です。DAV提供面はroot discovery、認証、標準メソッドとルーターの衝突を調査してから決めます。Wiki PathをそのままDAV collectionにしません。
|
旧案の `/v/organizer` ではなく、連絡先の実装は `/v/plan/contacts`、APIは `/_/api/v1/extension/organizer.contacts/`、CardDAV提供面は `/_/api/v1/carddav/` を使います。Wiki PathをそのままDAV collectionにしません。以下の順序案のうち、個人アドレス帳と限定DAV提供は実装済み、共有と外部connectorは後続です。
|
||||||
|
|
||||||
1. ICS/vCard fixture、入出力preview、警告、重複防止。
|
1. ICS/vCard fixture、入出力preview、警告、重複防止。
|
||||||
2. local calendar/agenda・連絡先一覧、権限・version試験。
|
2. local calendar/agenda・連絡先一覧、権限・version試験。
|
||||||
|
|||||||
@@ -76,7 +76,8 @@ SQLiteの単一 `UPDATE ... RETURNING` で選択とclaimを行い、同じジョ
|
|||||||
|
|
||||||
## v0.2.0後の優先修正:ログ保存競合
|
## v0.2.0後の優先修正:ログ保存競合
|
||||||
|
|
||||||
2026-11-01、ソース実装・合成データ検証。本番未反映。基点は `0f686aa`。
|
2026-11-01、ソース実装・合成データ検証。基点は `0f686aa`。
|
||||||
|
同日20:00 JST、[v0.2.1として本番反映](../../operations/deployments/2026-11-01-v0.2.1.md)した。
|
||||||
v0.2.0本番観察で開始ログ保存のSQLITE_BUSY_SNAPSHOT(517)が発生したため、
|
v0.2.0本番観察で開始ログ保存のSQLITE_BUSY_SNAPSHOT(517)が発生したため、
|
||||||
読取transactionをwriterへ昇格させる `AddEventLog` を修正した。
|
読取transactionをwriterへ昇格させる `AddEventLog` を修正した。
|
||||||
|
|
||||||
@@ -110,7 +111,7 @@ readonly、空ID誤分類、policy読取失敗、主キー利用、完了/retr
|
|||||||
|
|
||||||
長時間ロックで保存できなかったログの自動回収、完了状態とログ自体の一体commit、
|
長時間ロックで保存できなかったログの自動回収、完了状態とログ自体の一体commit、
|
||||||
event-only fallback検索や保持処理の最適化は後続。v0.2.0タグは変更せず、
|
event-only fallback検索や保持処理の最適化は後続。v0.2.0タグは変更せず、
|
||||||
本番反映時は新しいPATCH版として別途検証・公開する。
|
新しいPATCH版v0.2.1として別途検証・公開した。
|
||||||
|
|
||||||
## 未実装:リース・HA・終了処理
|
## 未実装:リース・HA・終了処理
|
||||||
|
|
||||||
@@ -126,7 +127,7 @@ exactly-onceの配送・実行は保証しない。外部副作用の冪等性
|
|||||||
- [ ] 成功後・完了保存前の障害、lease更新停止、旧workerの遅延完了を障害注入試験する。
|
- [ ] 成功後・完了保存前の障害、lease更新停止、旧workerの遅延完了を障害注入試験する。
|
||||||
- [ ] アプリケーションの停止contextをschedulerに接続し、受付停止・実行中処理のdrain・期限付き終了を実装する。
|
- [ ] アプリケーションの停止contextをschedulerに接続し、受付停止・実行中処理のdrain・期限付き終了を実装する。
|
||||||
- [ ] 各業務ハンドラーへcontextを伝播する。現状は独自のBackground/timeoutを使う処理も残る。
|
- [ ] 各業務ハンドラーへcontextを伝播する。現状は独自のBackground/timeoutを使う処理も残る。
|
||||||
- [x] 開始/進捗/完了ログのcontext伝播、有界writer取得、ログ保存失敗の診断(ソース実装。本番未反映)。
|
- [x] 開始/進捗/完了ログのcontext伝播、有界writer取得、ログ保存失敗の診断(v0.2.1で本番反映)。
|
||||||
- [ ] 古い設定DB呼出しをcontext対応にする。完了保存失敗・欠落ログの回収方針も定義する。
|
- [ ] 古い設定DB呼出しをcontext対応にする。完了保存失敗・欠落ログの回収方針も定義する。
|
||||||
|
|
||||||
コアのLoop/Runnerはキャンセルを受け付けるが、現行アプリケーションは従来どおり
|
コアのLoop/Runnerはキャンセルを受け付けるが、現行アプリケーションは従来どおり
|
||||||
|
|||||||
@@ -4,6 +4,10 @@
|
|||||||
|
|
||||||
## この設計書の読み方
|
## この設計書の読み方
|
||||||
|
|
||||||
|
2026-11-02追加:[オーガナイザーの共通ナビゲーションと個人ダッシュボード](organizer-dashboard.md)。配置可能なウィジェット、個人設定への統合、保存・認可・読込負荷の契約。
|
||||||
|
|
||||||
|
2026-11-01追加:[タスク作成・作業記録・達成度レポート・日次メール・個人アドレス帳](task-productivity-contacts.md)。[neomuttとCLIの操作リファレンス](../../operations/neomutt-tasks.md)も参照。
|
||||||
|
|
||||||
- **実装済み**:利用できる機能の範囲。関連する制約や未監査部分も併記します。
|
- **実装済み**:利用できる機能の範囲。関連する制約や未監査部分も併記します。
|
||||||
- **設計案**:今回具体化した方針。API・テーブル・既定値は、実装や互換性試験で確定させます。
|
- **設計案**:今回具体化した方針。API・テーブル・既定値は、実装や互換性試験で確定させます。
|
||||||
- **TODO**:未実装の作業。記述やURL例が存在しても利用可能とは限りません。
|
- **TODO**:未実装の作業。記述やURL例が存在しても利用可能とは限りません。
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# オーガナイザーのナビゲーションと個人ダッシュボード
|
||||||
|
|
||||||
|
タスク・カレンダー・連絡先の入口を共通化し、個人設定と日々の振り返りを分離する。ダッシュボードは本人の作業を見る画面であり、サーバーの実行状態・リソース監視画面とは別に扱う。以下は2026-11-02のソース実装範囲で、2026-11-04にv0.7.0として本番へ反映した。移行・検証・復旧点は[本番反映記録](../../operations/deployments/2026-11-04-v0.7.0.md)を参照する。
|
||||||
|
|
||||||
|
## 入口と設定の配置
|
||||||
|
|
||||||
|
各オーガナイザー画面に、ダッシュボード・タスク・カレンダー・連絡先・個人設定の共通ナビゲーションを置く。有効な拡張機能だけを表示し、現在の画面を強調する。トップ画面とログイン中のナビバーに、ダッシュボードと連絡先を直接開くアイコンを追加する。
|
||||||
|
|
||||||
|
| 入口 | 役割 |
|
||||||
|
| --- | --- |
|
||||||
|
| `/v/plan/dashboard` | ウィジェット形式の個人ダッシュボード |
|
||||||
|
| `/v/plan/tasks` | 既存のインライン編集可能なタスク一覧 |
|
||||||
|
| `/v/plan` | 既存のカレンダー表示。保存されたビューを尊重 |
|
||||||
|
| `/v/plan/contacts` | 個人アドレス帳・履歴・CardDAV接続 |
|
||||||
|
| `/-/sys/config?panel=organizer` | タスクの既定値、日次メール、既定のカレンダー |
|
||||||
|
|
||||||
|
旧 `/v/plan/tasks/report` はダッシュボードの達成度ウィジェットへ、旧 `/v/plan/tasks/settings` は個人設定へ303リダイレクトする。カレンダーの表示選択ダイアログはその場の表示変更に使い、既定値の永続化は個人設定へ移す。
|
||||||
|
|
||||||
|
個人設定は通常の設定画面と同じURI体系・テーマを使うが、専用の軽量な画面として返す。GET/HEADかつ正確な `panel=organizer` の場合だけ個人向けハンドラーに振り分け、管理用設定やアカウント一覧は取得・描画しない。POSTの管理者チェックは緩和しない。保存先は既存の本人用APIであり、一般利用者に管理権限を付与しない。
|
||||||
|
|
||||||
|
## タスク編集画面と通知既定値
|
||||||
|
|
||||||
|
2026-11-04の追加実装(v0.7.0の本番反映には含まない)では、デスクトップの編集画面を最大1180px幅の2カラムへ整理した。左側は件名・状態・整理先・プロジェクト・メモと作業アクション、右側は取り組む日・期限・見直す日・工程日付・優先度・工数・複雑度・Inbox通知とする。主要項目は1024×768でもスクロールなしで表示でき、低いウィンドウや詳細設定展開時には入力部分だけをスクロールする。保存操作はフッターに残す。
|
||||||
|
|
||||||
|
状態・整理先・複雑度はnative radioの単一選択を使い、選択中の項目をテーマ色と下線で示す。状態・整理先には記号を添え、複雑度は1〜5の数値と段階表示を併用する。ラベル、キーボード操作、読み取り専用制限は維持する。担当者UUID、プロジェクト検索、Wiki連携は詳細設定に折りたたみ、入力検証エラー時には展開する。
|
||||||
|
|
||||||
|
760px以下では1カラムにし、主な入力と選択ボタンは44px以上のタッチ領域を確保する。個人設定には新規タスクの期限日・取り組む日のInbox通知と通知時刻を設ける。適用条件と既存データの扱いは[タスク通知](task-reminders.md)を参照する。
|
||||||
|
|
||||||
|
## ウィジェット
|
||||||
|
|
||||||
|
初期構成は次の6種類。任意のHTML・iframe・外部URL・スクリプトを登録する機能ではなく、サーバーが許可する組み込みIDを使う。
|
||||||
|
|
||||||
|
| ID | 内容 |
|
||||||
|
| --- | --- |
|
||||||
|
| `progress` | 今日に計画したタスクの完了数と達成率 |
|
||||||
|
| `today` | 今日の計画と今日までの期限超過を含む未完了タスク |
|
||||||
|
| `tomorrow` | 明日の計画または期限の未完了タスク |
|
||||||
|
| `tasks` | Inbox / Backlog / Someday / Review / Incomplete / Done タブ付き一覧 |
|
||||||
|
| `schedule` | 既定カレンダーにある今日の予定 |
|
||||||
|
| `activity` | 完了数・ポイント・作業時間・集中時間、日別ヒートマップ |
|
||||||
|
|
||||||
|
タブはウィジェットの枠内で内容を切り替える。iframeを使わず、ページやブラウザ履歴を移動しない。タスク件名や右上の矢印は既存の詳細・一覧へ移動する。タスクの編集操作は従来の一覧・詳細画面を利用する。
|
||||||
|
|
||||||
|
達成率の分母は `planned_on=今日`、分子はそのうち `status=done` の件数。取りやめ・アーカイブ・プロジェクトを除く。日付はドメインのタイムゾーンで判定する。対象0件は100%でなく「—」を表示する。期限超過を含む「本日のタスク」の件数とは意図的に異なり、画面に定義を明記する。ヒートマップのポイント計算は[タスクの集計契約](task-productivity-contacts.md)に従う。
|
||||||
|
|
||||||
|
## 配置と保存
|
||||||
|
|
||||||
|
デスクトップは12列グリッド。幅は3〜12列、高さは2〜10単位、1単位の表示基準は72pxと12pxの間隔。順序に従ってグリッドへ配置するため、幅の組み合わせによって空白が生じる。任意の絶対座標を保持するレイアウトではない。
|
||||||
|
|
||||||
|
歯車で配置モードを開き、ハンドルのドラッグで並べ替え、右下のハンドルでサイズを変える。矢印ボタンと幅・高さの選択欄でも同じ操作が可能。追加・除去・初期配置への復帰に対応し、「配置を保存」で確定する。タブの選択も配置の一部として保存できる。未保存の離脱を警告し、保存失敗・競合時には編集中の配置を残す。ブラウザ再起動をまたぐ未保存レイアウトの下書きは持たない。
|
||||||
|
|
||||||
|
スマホは1列とタッチ向け操作へ切り替え、デスクトップ用の幅を上書きしない。カード内の長い一覧はスクロールする。並べ替えは矢印でも行える。幅指定とドラッグリサイズはスマホでは非表示。
|
||||||
|
|
||||||
|
保存は `organizer_dashboard_layouts` のDomain・本人を複合キーにし、JSONにウィジェットID・幅・高さ・選択タブだけを持つ。`task-productivity` managed migration v2でテーブルを追加する。既存v1の定義を変更しない。タスク既定値・メール同意とは別のversionを使い、配置保存が配信時刻や送信直前の同意チェックに影響しないようにする。
|
||||||
|
|
||||||
|
APIは `/_/api/v1/extension/organizer.tasks/` 配下。
|
||||||
|
|
||||||
|
| 操作 | 契約 |
|
||||||
|
| --- | --- |
|
||||||
|
| GET `dashboard` | `{version, widgets}`。未保存なら初期配置 |
|
||||||
|
| PUT `dashboard` | GETしたversionとwidgetsを送る。競合412、不正422、読み取り専用403 |
|
||||||
|
| GET `progress` | `{date, total, done}`。一覧の表示上限とは無関係にSQL集計 |
|
||||||
|
|
||||||
|
空配列は空のダッシュボードとして保持する。同じウィジェットの重複、未知ID、不正なタブやサイズは拒否する。新規APIは通常のセッション認証を使い、CalDAV資格情報を受け付けない。匿名には返さず、レスポンスは `private, no-store`。ダッシュボードは `organizer.tasks` の有効化に従い、カレンダー無効時は予定を取得しない。
|
||||||
|
|
||||||
|
## 読み込み負荷
|
||||||
|
|
||||||
|
ウィジェットの初期読込・全更新は最大2ジョブを並行実行し、定期ポーリングしない。タブ切替では旧リクエストを中断し、後から到着した古い応答を採用しない。タスクは1回20件のカーソルページング。予定は既存upcoming APIに `period=day` を追加し、ドメインの当日0時から翌日0時までだけを問い合わせ、最大20件を表示する。続きはカレンダー本体へ移動する。達成度は既存report APIの期間・件数上限を引き継ぐ。
|
||||||
|
|
||||||
|
## 検証と後続範囲
|
||||||
|
|
||||||
|
合成データで、所有者分離、CAS、読み取り専用、匿名拒否、管理設定への権限拡大がないこと、空配置、禁止ウィジェット、メール設定の不変、今日の集計・予定範囲を検証する。ブラウザではデスクトップとスマホの導線、タブ、設定保存、配置保存、横はみ出しを確認し、デスクトップのドラッグ・リサイズには実ポインター入力を使う。本番の外部取り込みカレンダーは検証に使わない。
|
||||||
|
|
||||||
|
次段階は以下を別途設計する。
|
||||||
|
|
||||||
|
- ウィジェットの複数インスタンス、プロジェクト等の個別フィルターと保存スキーマversion。
|
||||||
|
- 共有ダッシュボード。個人の配置やタスク権限を暗黙に共有しない。
|
||||||
|
- 外部プラグインウィジェットの権限宣言・実行制限・障害隔離・リソース観測。
|
||||||
|
- 画面外ウィジェットの遅延読込と、必要時だけの変更通知による更新。
|
||||||
|
- データ移行後の切戻し手順。旧イメージのschema checkに新しいversionを無視させず、バックアップ保全と移行検証を伴ってリリースする。
|
||||||
@@ -26,7 +26,7 @@
|
|||||||
- [x] 共通ナビの◐からプリセットを選択、リロードせず切替。host限定Cookieに保持し、Domain既定に戻せる。登録済みテーマのみ許可。Domain設定/アカウントの全端末設定ではなくブラウザ上書き。失敗時は現在テーマを保持する。
|
- [x] 共通ナビの◐からプリセットを選択、リロードせず切替。host限定Cookieに保持し、Domain既定に戻せる。登録済みテーマのみ許可。Domain設定/アカウントの全端末設定ではなくブラウザ上書き。失敗時は現在テーマを保持する。
|
||||||
- [x] 絶対セッション期限:設定→セッション、5〜43200分、既定1440分。Domain単位で新規ブラウザ/APIログイン(OIDC/LDAPを含む)に適用。発行時にDBの期限を固定し、Cookie/APIのexpires_inにも反映。既存セッションの期限とCalDAVアプリパスワードは変更しない。管理者認可とサーバ側失効をfixture検証。
|
- [x] 絶対セッション期限:設定→セッション、5〜43200分、既定1440分。Domain単位で新規ブラウザ/APIログイン(OIDC/LDAPを含む)に適用。発行時にDBの期限を固定し、Cookie/APIのexpires_inにも反映。既存セッションの期限とCalDAVアプリパスワードは変更しない。管理者認可とサーバ側失効をfixture検証。
|
||||||
- [ ] 無操作タイムアウトとアカウント別の短縮上書き:background pollingを人間の操作とみなさないactivity契約、再認証、既存セッションへの即時適用を別途設計する。
|
- [ ] 無操作タイムアウトとアカウント別の短縮上書き:background pollingを人間の操作とみなさないactivity契約、再認証、既存セッションへの即時適用を別途設計する。
|
||||||
- [x] 電話連絡先の初期実装(2026-11-01ローカル検証済み、本番未反映):本人編集、独立した公開範囲、表示用文字列と正規化した `tel:` リンク。公開は明示確認とプロフィール/ドメイン上限に従う。クリックなしで発信しない。
|
- [x] 電話連絡先の初期実装(2026-11-01 v0.2.0本番反映済み):本人編集、独立した公開範囲、表示用文字列と正規化した `tel:` リンク。公開は明示確認とプロフィール/ドメイン上限に従う。クリックなしで発信しない。
|
||||||
|
|
||||||
### 4. Cityの表示名
|
### 4. Cityの表示名
|
||||||
|
|
||||||
@@ -37,9 +37,9 @@
|
|||||||
### 5. セッション付きCLI/TUI
|
### 5. セッション付きCLI/TUI
|
||||||
|
|
||||||
- [x] HTTPクライアント初期版 `pages-cli`/コマンド `pages`(2026-11-01ホストのユーザーPATHへ配置済み。実ユーザログインは未実施):configureによる接続先・既定プロファイル・言語管理、パスワード/TOTP、Bearer保持・失効、ls/cd/cat/view/get、既存Page edit/put、Path補完、メモリ内履歴、検索候補、ブラウザ引き継ぎ。詳細と原設計整合は [遠隔CLI](remote-cli.md)。既存DB直アクセスCLIは変更しない。
|
- [x] HTTPクライアント初期版 `pages-cli`/コマンド `pages`(2026-11-01ホストのユーザーPATHへ配置済み。実ユーザログインは未実施):configureによる接続先・既定プロファイル・言語管理、パスワード/TOTP、Bearer保持・失効、ls/cd/cat/view/get、既存Page edit/put、Path補完、メモリ内履歴、検索候補、ブラウザ引き継ぎ。詳細と原設計整合は [遠隔CLI](remote-cli.md)。既存DB直アクセスCLIは変更しない。
|
||||||
- [ ] 既存 `data/pageswiki-cli` を拡張する専用起動コマンドとセッション保持。履歴や資格情報に0600相当の保護と失効/ログアウトを設ける。
|
- [x] 専用起動コマンドとセッション保持は独立HTTPクライアント `pages` として実装。既存 `data/pageswiki-cli` のDB直接操作とは分離し、資格情報に0600の保護と失効/ログアウトを設ける。
|
||||||
- [ ] `Ctrl+P` のfuzzy検索と、ローカル `$EDITOR` 編集。現在版/ETagを保持してアップロード時の競合を検出し、上書き・差分・キャンセルを選べるようにする。
|
- [ ] `Ctrl+P` のfuzzy検索と、ローカル `$EDITOR` 編集。現在版/ETagを保持してアップロード時の競合を検出し、上書き・差分・キャンセルを選べるようにする。
|
||||||
- [ ] パスワード認証に加え、ターミナルにURLを表示するブラウザ認証(OIDC)。既存Web認証と同じ本人性/MFA制約を適用し、短命・単回の認可コード+PKCEやdevice-flow相当の仕様を検討する。URLや履歴に長期トークンを含めない。
|
- [x] ターミナルにURLを表示するブラウザ認証(OIDC)。`pages login --oidc [--no-browser]`、S256、5分の単回grant、確認コード/CSRF/TOTP、失効再確認、poll・発行上限を実装。2026-11-01 v0.3.0でサーバー・ホストCLIへ本番反映済み。実providerでの本人承認は利用者確認が残る。契約は[遠隔CLI](remote-cli.md)を参照。
|
||||||
- [ ] ターミナル表示が難しい内容はブラウザに引き継ぐ。short linkは認証を迂回しない内部リンクとし、公開share link発行とは分離する。自動公開しない。
|
- [ ] ターミナル表示が難しい内容はブラウザに引き継ぐ。short linkは認証を迂回しない内部リンクとし、公開share link発行とは分離する。自動公開しない。
|
||||||
|
|
||||||
## チェックポイントと進捗
|
## チェックポイントと進捗
|
||||||
@@ -93,9 +93,9 @@
|
|||||||
- 電話番号は3〜15桁、先頭の+、表示用の空白・ハイフン・括弧に限定。内線、URIパラメータ、サービスコード、制御文字、任意スキームを拒否。空欄保存は番号を消去してprivateに戻す。
|
- 電話番号は3〜15桁、先頭の+、表示用の空白・ハイフン・括弧に限定。内線、URIパラメータ、サービスコード、制御文字、任意スキームを拒否。空欄保存は番号を消去してprivateに戻す。
|
||||||
- JA/ENの説明・フォーム・保存後アンカーを追加。デスクトップ1440px/375pxで実ブラウザの入力・保存・telリンク・フォーム幅を検証。iPhoneの電話アプリ起動そのものは未検証。
|
- JA/ENの説明・フォーム・保存後アンカーを追加。デスクトップ1440px/375pxで実ブラウザの入力・保存・telリンク・フォーム幅を検証。iPhoneの電話アプリ起動そのものは未検証。
|
||||||
- store/HTTPで本人・匿名・他メンバー・管理者・越境・公開確認・公開撤回・競合・不正番号を検証。個人情報の本文を監査ログへ追加しない。CardDAV、住所録、複数番号、内線は後続。
|
- store/HTTPで本人・匿名・他メンバー・管理者・越境・公開確認・公開撤回・競合・不正番号を検証。個人情報の本文を監査ログへ追加しない。CardDAV、住所録、複数番号、内線は後続。
|
||||||
- **本番反映済みfix2にはこの機能を含めない。** 次回リリースでは追加componentの適用と、旧版への切り戻し条件を別途検証する。
|
- fix2時点では未反映だったが、v0.2.0で追加componentの適用と切り戻し条件を検証し本番反映した。[リリース記録](../../operations/deployments/2026-11-01-v0.2.0.md)を参照。
|
||||||
|
|
||||||
### 新規DBの初期接続競合(後続修正、本番未反映)
|
### 新規DBの初期接続競合(v0.2.0本番反映済み)
|
||||||
|
|
||||||
全体回帰で `TestSQLMigrationLedgerConcurrencyAndChecksum` がまれにSQLITE_BUSYとなることを確認。診断メッセージをmigration connection取得/BEGINに分け、2,000回の反復で接続取得段階の失敗を再現した。`sql.Open` がlazyのため、最初の並行接続でWALへの切替が競合していた。
|
全体回帰で `TestSQLMigrationLedgerConcurrencyAndChecksum` がまれにSQLITE_BUSYとなることを確認。診断メッセージをmigration connection取得/BEGINに分け、2,000回の反復で接続取得段階の失敗を再現した。`sql.Open` がlazyのため、最初の並行接続でWALへの切替が競合していた。
|
||||||
|
|
||||||
@@ -123,7 +123,7 @@
|
|||||||
|
|
||||||
現行 `data/pageswiki-cli` はSQLite/Document Storeへ直接アクセスする運用CLI。shell、補完、履歴、`$PAGER`/`$EDITOR` は既にあるが、Web認証を受けるリモートクライアントではない。Webユーザの認可をSQLite直アクセスへ継ぎ足さず、HTTP transportを持つ別コマンド(仮称 `pageswiki remote`)として段階導入する。
|
現行 `data/pageswiki-cli` はSQLite/Document Storeへ直接アクセスする運用CLI。shell、補完、履歴、`$PAGER`/`$EDITOR` は既にあるが、Web認証を受けるリモートクライアントではない。Webユーザの認可をSQLite直アクセスへ継ぎ足さず、HTTP transportを持つ別コマンド(仮称 `pageswiki remote`)として段階導入する。
|
||||||
|
|
||||||
2026-11-01:試作名 `data/pageswiki-remote` から、ユーザ指定によりサブプロジェクト `pages-cli`/実行名 `pages` へ整理。`pages configure` と既定値により通常操作のprofile/lang引数を不要とした。以下は全体計画であり、Ctrl+P、OIDCハンドオフ、新規作成、強制上書きの対話選択、short linkは未実装。[初期版の範囲・制限・検証](remote-cli.md)を参照。
|
2026-11-01:試作名 `data/pageswiki-remote` から、ユーザ指定によりサブプロジェクト `pages-cli`/実行名 `pages` へ整理。`pages configure` と既定値により通常操作のprofile/lang引数を不要とした。OIDCハンドオフはv0.3.0で本番反映済み。実providerでの本人承認、Ctrl+P、新規作成、強制上書きの対話選択、short linkは残件。[範囲・制限・検証](remote-cli.md)を参照。
|
||||||
|
|
||||||
1. パスワード+TOTPの既存JSONログイン、失効/logout、接続先・Principal・Domain別セッション保存。秘密情報はコマンド引数/履歴/ログへ出さず、保存先0700・資格情報0600相当、TLS検証必須。
|
1. パスワード+TOTPの既存JSONログイン、失効/logout、接続先・Principal・Domain別セッション保存。秘密情報はコマンド引数/履歴/ログへ出さず、保存先0700・資格情報0600相当、TLS検証必須。
|
||||||
2. `ls/cd/view/get/edit` と現在Pathの保持。検索は認可付き・件数制限・キャンセル可能なAPIを使用し、`Ctrl+P` のfuzzy選択へ接続。端末の制御シーケンスは本文/タイトルから除去する。
|
2. `ls/cd/view/get/edit` と現在Pathの保持。検索は認可付き・件数制限・キャンセル可能なAPIを使用し、`Ctrl+P` のfuzzy選択へ接続。端末の制御シーケンスは本文/タイトルから除去する。
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
2026-11-01。合成データで検証済み。同日、本番サーバのCity更新と合わせてクライアントをホストの `/home/anya/.local/bin/pages` に配置した。実ユーザの資格情報取得・ログイン・本番Page編集は未実施。接続設定とログインは利用者が行う。[反映記録](../../operations/deployments/2026-11-01-city-pages-cli.md)。
|
2026-11-01。合成データで検証済み。同日、本番サーバのCity更新と合わせてクライアントをホストの `/home/anya/.local/bin/pages` に配置した。実ユーザの資格情報取得・ログイン・本番Page編集は未実施。接続設定とログインは利用者が行う。[反映記録](../../operations/deployments/2026-11-01-city-pages-cli.md)。
|
||||||
|
|
||||||
|
v0.3.0のOIDCログインは利用者の動作確認済み。v0.4.0ではOIDC承認時の追加ローカルTOTPを廃止し、CLIの `auto` 言語選択と既存Pageの新規言語版編集を実装した。2026-11-01 21:48 JSTに本番サーバー/PATH上のCLIへ反映済み。[v0.4.0反映記録](../../operations/deployments/2026-11-01-v0.4.0.md)。
|
||||||
|
|
||||||
## 原設計との整合
|
## 原設計との整合
|
||||||
|
|
||||||
原設計の [Address Model](../address-model.md)、[URI](../uri.md)、[認証バックエンド](../auth-backend.md)、[エディタの保存契約](editor-resilience.md)を使用する。
|
原設計の [Address Model](../address-model.md)、[URI](../uri.md)、[認証バックエンド](../auth-backend.md)、[エディタの保存契約](editor-resilience.md)を使用する。
|
||||||
@@ -13,7 +15,7 @@
|
|||||||
- 旧認証設計にはCookie中心の記載が残るが、実装済みのJSONログインはBearerセッションを発行する。CLIはこのフローを使用し、Web Cookieを抽出しない。
|
- 旧認証設計にはCookie中心の記載が残るが、実装済みのJSONログインはBearerセッションを発行する。CLIはこのフローを使用し、Web Cookieを抽出しない。
|
||||||
- `data/pageswiki-cli` は信頼されたローカル運用ツールとして維持。遠隔版はサブプロジェクト `pages-cli`、実行名 `pages`(`pages-cli/pages`)とし、DB・Document Storeを直接開かない。
|
- `data/pageswiki-cli` は信頼されたローカル運用ツールとして維持。遠隔版はサブプロジェクト `pages-cli`、実行名 `pages`(`pages-cli/pages`)とし、DB・Document Storeを直接開かない。
|
||||||
|
|
||||||
サーバAPI/DBスキーマの追加・変更はない。初期実装はPython 3.9以降の標準ライブラリで動作するUnix系クライアント(fcntl、readline使用)。Windowsネイティブ版は未対応。
|
初期のパスワード版にはサーバAPI/DBスキーマの追加・変更はない。後続のOIDC引き継ぎでは下記のauthエンドポイントとmanaged component `cli-auth` v1を追加する。Python 3.9以降の標準ライブラリで動作するUnix系クライアント(fcntl、readline使用)。Windowsネイティブ版は未対応。
|
||||||
|
|
||||||
## 利用方法
|
## 利用方法
|
||||||
|
|
||||||
@@ -24,7 +26,7 @@ pages login
|
|||||||
pages status
|
pages status
|
||||||
pages
|
pages
|
||||||
|
|
||||||
# ワンショット。--lang はコマンドより前に指定する。
|
# ワンショット。editでは --lang をコマンドの後にも指定可能。
|
||||||
pages ls /manual
|
pages ls /manual
|
||||||
pages edit /manual/start
|
pages edit /manual/start
|
||||||
pages get /manual/start ./start.html
|
pages get /manual/start ./start.html
|
||||||
@@ -32,7 +34,7 @@ pages put ./start.html /manual/start --base REVISION_UUID
|
|||||||
pages logout
|
pages logout
|
||||||
```
|
```
|
||||||
|
|
||||||
配置方法と詳しい設定例は [pages-cli README](../../../pages-cli/README.md)。既定プロファイル名は `default`、編集言語は `und`。`pages configure --lang ja` で変更し、`configure set --profile work --origin ... --username ... --lang en` で接続先を追加する。`configure use work` で既定を切り替え、通常操作ではprofile/langの引数を省略する。一時的な `--profile`/`--lang` 上書きも残す。
|
配置方法と詳しい設定例は [pages-cli README](../../../pages-cli/README.md)。既定プロファイル名は `default`、新規プロファイルの編集言語は `auto`。既存の明示設定は保持する。`pages configure --lang auto` で表示対象の言語に追従し、`--lang ja` なら日本語版を指定する。`configure set --profile work --origin ... --username ... --lang en` で接続先を追加し、`configure use work` で既定を切り替える。一時的な `--profile`/`--lang` 上書きも残す。
|
||||||
|
|
||||||
設定は `config.json` の version/default_profile/profiles と、各接続のorigin/username/langに限定。パスワード・Bearerは設定表示へ含めない。configureはネットワーク通信をせず、ログイン中のorigin/username変更を拒否する。mainは設定ロック→セッションロックの順で取得し、起動時の接続先すり替えを防ぐ。手編集時も保存したセッションの接続先・アカウントとの一致を確認してから使用する。logoutは設定を手編集した場合でも、保存済みの元接続先に対して失効する。
|
設定は `config.json` の version/default_profile/profiles と、各接続のorigin/username/langに限定。パスワード・Bearerは設定表示へ含めない。configureはネットワーク通信をせず、ログイン中のorigin/username変更を拒否する。mainは設定ロック→セッションロックの順で取得し、起動時の接続先すり替えを防ぐ。手編集時も保存したセッションの接続先・アカウントとの一致を確認してから使用する。logoutは設定を手編集した場合でも、保存済みの元接続先に対して失効する。
|
||||||
|
|
||||||
@@ -47,11 +49,13 @@ TabはPath候補を取得し、上下キーは当該プロセス内の履歴を
|
|||||||
- `get ADDRESS LOCAL` は最大64 MiBの正本を取得し、SHA-256を照合する。ローカル出力は0600で新規作成し、既存ファイルを上書きしない。Revision UUIDを表示する。
|
- `get ADDRESS LOCAL` は最大64 MiBの正本を取得し、SHA-256を照合する。ローカル出力は0600で新規作成し、既存ファイルを上書きしない。Revision UUIDを表示する。
|
||||||
- `cat` はpipe時に正本バイト列を出力。TTY時には制御文字を除去する。`view` はテキストを `$PAGER`(既定less)に渡し、HTMLを端末上で実行しない。
|
- `cat` はpipe時に正本バイト列を出力。TTY時には制御文字を除去する。`view` はテキストを `$PAGER`(既定less)に渡し、HTMLを端末上で実行しない。
|
||||||
- `edit` は `$EDITOR`(既定vi)をshellを介さず起動。HTMLはauthoring Markdownが既定、その他の対応テキストは原文。`--format raw` でHTMLを直接編集できる。`--format markdown` はHTML文書専用。
|
- `edit` は `$EDITOR`(既定vi)をshellを介さず起動。HTMLはauthoring Markdownが既定、その他の対応テキストは原文。`--format raw` でHTMLを直接編集できる。`--format markdown` はHTML文書専用。
|
||||||
|
- `auto` はRaw HEADのRevision UUIDから言語を確認し、その言語の現在headを再取得する。以降の保存・競合比較はその言語に固定し、途中で通常表示の言語が変わっても追従しない。
|
||||||
|
- 明示言語のheadがなければ表示対象のRevisionを下書きとして読み込む。保存先言語と空の `base_revision_uuid` を保持し、保存時点でもheadがないことをCASで確認する。元の言語版は変更しない。これは内容の分岐であり自動翻訳ではない。無変更で閉じれば新規Revisionは作らない。
|
||||||
- ローカル作業ファイルは0700の一時ディレクトリ内に0600で保存。成功・無変更時は削除、失敗/409/通信断時は原稿とrecovery.jsonを保持して場所を表示する。recovery.jsonにはorigin、UUID、基点Revision、言語、形式を記録し、Bearerは含めない。
|
- ローカル作業ファイルは0700の一時ディレクトリ内に0600で保存。成功・無変更時は削除、失敗/409/通信断時は原稿とrecovery.jsonを保持して場所を表示する。recovery.jsonにはorigin、UUID、基点Revision、言語、形式を記録し、Bearerは含めない。
|
||||||
- 409では最新内容とローカル原稿の差分を表示し、保存は停止する。自動マージ、強制上書き、自動再送はしない。応答喪失時は取得してサーバの状態を確認してから再試行する。
|
- 409では最新内容とローカル原稿の差分を表示し、保存は停止する。自動マージ、強制上書き、自動再送はしない。応答喪失時は取得してサーバの状態を確認してから再試行する。
|
||||||
- `put` は既存Pageの既存言語のみ。`--base` が必須で、現在headと不一致なら送信しない。サーバ保存も同じbaseでCASを行う。編集を保持したい場合は最新を取得して差分を確認し、調整済み原稿とその最新Revisionを明示して保存する。
|
- `put` は既存Pageの既存言語のみ。`--base` が必須で、現在headと不一致なら送信しない。サーバ保存も同じbaseでCASを行う。編集を保持したい場合は最新を取得して差分を確認し、調整済み原稿とその最新Revisionを明示して保存する。
|
||||||
- `put --format markdown` はauthoring変換を使用。rawは正本形式を保持する。ローカル拡張子で保存MIMEを勝手に変更しない。テキスト編集は1 MiB、JSON送信は2 MiBまで。
|
- `put --format markdown` はauthoring変換を使用。rawは正本形式を保持する。ローカル拡張子で保存MIMEを勝手に変更しない。テキスト編集は1 MiB、JSON送信は2 MiBまで。
|
||||||
- `rev:` は取得専用。新規Page、未作成の言語head、バイナリ編集、Asset更新は拒否する。新規作成のためにエディタGETの副作用を利用しない。
|
- `rev:` は取得専用。新規Path/Page、バイナリ編集、Asset更新は拒否する。新規作成のためにエディタGETの副作用を利用しない。新規言語版も保存APIで既存Pageの書込権限を検査する。
|
||||||
- `open` は同一originのPath/UUID/Revisionビューアをブラウザで開く。BearerはURLに含めず、ブラウザ側のログインが必要。共有リンクは自動発行しない。
|
- `open` は同一originのPath/UUID/Revisionビューアをブラウザで開く。BearerはURLに含めず、ブラウザ側のログインが必要。共有リンクは自動発行しない。
|
||||||
|
|
||||||
## HTTP契約
|
## HTTP契約
|
||||||
@@ -67,7 +71,67 @@ TabはPath候補を取得し、上下キーは当該プロセス内の履歴を
|
|||||||
| 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保存 | POST `/_/api/v1/revisions/save` |
|
||||||
|
|
||||||
一覧は既存の件数制限を維持し、truncatedを表示する。巨大な全階層を再帰取得しない。読み取りのRaw言語選択は既存サーバの候補選択に従うが、編集は指定言語のheadを必須とし、存在しない場合は拒否する。
|
一覧は既存の件数制限を維持し、truncatedを表示する。巨大な全階層を再帰取得しない。読み取りのRaw言語選択は既存サーバの候補選択に従う。`auto` はRawのlang指定を省略し、実際に選択されたRevisionの言語をeditor/stateのmetadataで確認する。明示言語のheadがない場合だけ、同APIのrevision指定で元の内容を読み込む。元のRevision UUIDを保存の基点に流用せず、空の基点で新規言語版を作る。
|
||||||
|
|
||||||
|
## OIDCブラウザ引き継ぎ
|
||||||
|
|
||||||
|
`pages login --oidc` はブラウザを開き、`--no-browser` はURLだけを表示する。
|
||||||
|
CLI側に受信ポートは不要で、SSH先から開始して別のPC/スマホで承認できる。
|
||||||
|
接続先のOIDC設定・既存アカウントとの対応を再利用し、新たなprovider登録は不要。
|
||||||
|
ユーザー名未指定なら認証結果をセッションに保存する。指定済みなら一致を検査し、
|
||||||
|
不一致時は新セッションを失効させるリクエストを送って保存を止める。
|
||||||
|
設定上のusernameと認証結果のusernameは別々に保持し、接続先・アカウントの手編集対策を維持する。
|
||||||
|
|
||||||
|
### プロトコル
|
||||||
|
|
||||||
|
[RFC 8628](https://datatracker.ietf.org/doc/html/rfc8628)の別端末承認・ポーリングの考え方と、
|
||||||
|
[RFC 7636](https://www.rfc-editor.org/rfc/rfc7636)のS256照合を参照する。
|
||||||
|
これはPagesWiki専用のsession handoffであり、汎用OAuth Device Authorization Serverの
|
||||||
|
discovery/grant_type/client registrationへの完全準拠を標榜しない。
|
||||||
|
|
||||||
|
| 入口 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| POST `/_/auth/cli/start` | formの`code_challenge`、`code_challenge_method=S256`で開始 |
|
||||||
|
| GET `/_/auth/cli/verify?request=...` | OIDCへの入口と、認証後の本人・接続先確認/承認フォーム |
|
||||||
|
| GET `/_/auth/oidc?cli=...` | 既存のnonce・state・PKCE・署名検証を使うOIDCフロー |
|
||||||
|
| POST `/_/auth/cli/verify` | browser session、CSRF、request、確認コードで承認/拒否 |
|
||||||
|
| POST `/_/auth/cli/token` | formの`device_code`、`code_verifier`を照合して単回交換 |
|
||||||
|
|
||||||
|
1. CLIは暗号学的乱数のverifierを生成し、そのSHA-256を送る。サーバは独立した256bitの
|
||||||
|
public request ID/device codeと32bit確認コードを生成する。
|
||||||
|
返却するverification URIは同一origin内の固定Path。CLIもPath形式を厳密に検査する。
|
||||||
|
2. ブラウザは既存CookieがあってもOIDCフローを通る。新しいOIDC callbackで作られた
|
||||||
|
browser sessionにリクエストを一度だけ束縛する。他ブラウザによる再束縛を拒否。
|
||||||
|
3. callbackだけではCLIへ認証情報を渡さない。承認画面はterminalの確認コード入力を要求し、
|
||||||
|
フォーム内にコードを埋め込まない。本人が開始した操作だけ承認するよう警告する。
|
||||||
|
同一origin検査+browser tokenとrequestに束縛したCSRFを使用する。
|
||||||
|
4. OIDC認証後の承認で追加のローカルTOTPは要求しない。プロバイダーの認証ポリシーを使用する。
|
||||||
|
OIDC成功だけをMFA成功とは扱わず、未検証のMFA levelを加算しない。
|
||||||
|
ローカルパスワードログイン時のTOTP要件は変更しない。
|
||||||
|
5. CLIは5秒間隔でpoll。pendingのみ継続し、slow_downで間隔を5秒ずつ最大30秒へ増やす。
|
||||||
|
拒否・失効・ネットワーク障害・交換応答の喪失では自動再送しない。
|
||||||
|
6. grantの消費と専用`pw_api_`セッション発行を同じtransactionで確定する。
|
||||||
|
Principal/Domain membership/承認元browser sessionの失効・期限を再検査する。
|
||||||
|
セッションは既存の権限評価に従い、期限はDomain設定と承認元session期限の短い方。
|
||||||
|
MFA levelを保持する。ブラウザCookieや外部provider tokenをCLIへ流用しない。
|
||||||
|
|
||||||
|
### 永続化・上限
|
||||||
|
|
||||||
|
- managed component `cli-auth` v1に短期状態を保存。既存authテーブルやURIは改名しない。
|
||||||
|
- grantは5分で失効。確認失敗は最大5回、OIDC開始は1grantあたり3回まで。
|
||||||
|
- 同一Domainで5分間に64件まで、全体の保持件数は4096件まで。発行前に作成10分超の行を削除する。
|
||||||
|
上限判定は単一INSERT内で行い、並行発行で超過しない。長期履歴にはしない。
|
||||||
|
- device code/確認コード/browser tokenはハッシュだけを保存。verifierはCLIのメモリだけ。
|
||||||
|
新しいAPI Bearerの平文は既存0600セッションファイルだけに保存する。
|
||||||
|
- 外向け応答はno-store、承認ページはno-referrer・frame禁止。Bearer・verifier・確認コードを
|
||||||
|
URLに含めない。リクエスト本文をアクセスログへ記録しない運用を前提とする。
|
||||||
|
- read-onlyインスタンスは発行・承認・交換しない。初期化は通常のmanaged schema手順に従う。
|
||||||
|
v0.2.0へ戻す前には追加componentを含む互換性を確認し、schema履歴を削除して回避しない。
|
||||||
|
|
||||||
|
HTTP応答が失われた場合にセッションが発行済みの可能性は残る。平文BearerをDBへ保持して
|
||||||
|
再配布する方式は採らず、利用者が設定画面で不要なセッションを失効する。
|
||||||
|
Ctrl+C時は未交換grantを即時サーバ削除せず、5分の期限で失効させる。
|
||||||
|
この上限は入口全体のDDoS対策ではない。reverse proxyでの一般的なリクエスト制限は別途必要。
|
||||||
|
|
||||||
## セキュリティと運用上の制限
|
## セキュリティと運用上の制限
|
||||||
|
|
||||||
@@ -82,14 +146,40 @@ TabはPath候補を取得し、上下キーは当該プロセス内の履歴を
|
|||||||
|
|
||||||
Python unittest:origin制限、端末制御文字、別origin redirect遮断、非JSON/403/サイズ上限、TOTP、資格情報権限・symlink・並行実行拒否、authoring/CAS payload、ダウンロード上書き拒否、409時の原稿保全。
|
Python unittest:origin制限、端末制御文字、別origin redirect遮断、非JSON/403/サイズ上限、TOTP、資格情報権限・symlink・並行実行拒否、authoring/CAS payload、ダウンロード上書き拒否、409時の原稿保全。
|
||||||
|
|
||||||
設定追加後は12件:既定値/複数接続切替/言語保存、一時上書き、設定表示からのトークン除外、セッション保持中の再接続先変更拒否、手編集での接続先不一致拒否も検査。HTTP統合試験では公開エントリーポイントのconfigure→login→引数省略のls/status/edit→logoutを通す。
|
Python単体試験22件:既定値/複数接続切替/言語保存、一時上書き、設定表示からのトークン除外、接続先変更拒否、PKCE、poll間隔、URL検査、アカウント不一致、取消、通信断、username未指定でのsession保持、開始API未対応/OIDC無効時の診断、autoの言語とhead固定、新規言語版の空CAS、無変更終了、競合時の言語固定を検査する。
|
||||||
|
|
||||||
Goの `TestRemoteCLIHTTPIntegration`:一時DBと本物のHTTPハンドラでログイン、一覧、編集状態、authoring変換、保存、古いRevision拒否、Rawハッシュ、immutable拒否、存在しない言語拒否、put、ログアウト後の拒否を検査。Pythonがないビルド環境ではこの統合試験をskipする。外部カレンダーや本番資格情報は使わない。
|
Goの `TestRemoteCLIHTTPIntegration`:一時DBと本物のHTTPハンドラでログイン、一覧、編集状態、authoring変換、保存、古いRevision拒否、Rawハッシュ、immutable拒否、新規言語版作成と並行作成の409、元言語の保持、日本語版のみ存在するPageのauto編集、put、ログアウト後の拒否を検査。Pythonがないビルド環境ではこの統合試験をskipする。外部カレンダーや本番資格情報は使わない。
|
||||||
|
|
||||||
|
OIDCは署名付き模擬providerによるcallback→承認→交換のHTTP試験、12並行交換で1sessionのみ、
|
||||||
|
越境・別origin・期限・失効・MFA・不正コード・発行上限・途中失敗rollbackを検査する。
|
||||||
|
`TestRemoteCLIOIDCIntegration`ではPython CLIから実際のHTTP経由でconfigure→OIDC待機/交換→一覧→authoring保存→logoutを実行する。
|
||||||
|
この試験のブラウザ操作だけはfixtureの承認ブリッジを使い、実OIDC callbackは別のHTTP試験で検証する。
|
||||||
|
承認画面のChromium試験は1440px/390pxで実フォームとCookieによる承認を確認する。
|
||||||
|
v0.3.0の本番OIDCログインは利用者確認済み。追加TOTP省略はローカルTOTP有効の合成アカウントでも検証し、MFA levelを不当に上げないことと既存の検証済みlevelの継承を確認する。
|
||||||
|
|
||||||
|
2026-11-01のv0.3.0公開時の実行結果:全Goテスト(キャッシュなし)、全Go vet、関連store/serverのrace検査、
|
||||||
|
Python 18件、OIDCとパスワードのCLI HTTP統合試験、承認画面と既存CookieログインのChromium試験が成功。
|
||||||
|
CLI承認画面のモバイルスクリーンショットも確認した。実機Safariは未確認。
|
||||||
|
前段のイベントログ修正を保持し、OIDCは機能追加としてv0.3.0で公開した。
|
||||||
|
同日20:52 JSTに本番サーバーとユーザーPATH上のCLIへ反映済み。
|
||||||
|
[本番反映記録](../../operations/deployments/2026-11-01-v0.3.0.md)にCI再実行、schema移行、公開API確認と復旧条件を記載した。
|
||||||
|
サーバーとCLIの両方が必要。開始APIの404/405/501は未対応または接続先の誤りとして明示し、
|
||||||
|
OIDC無効の403と区別する。エラー時のログイン要求は自動再送せず、資格情報も保存しない。
|
||||||
|
|
||||||
|
同日の後続変更でも全Goテスト(キャッシュなし)、全Go vet、CLI関連store/serverのrace検査、
|
||||||
|
Python 22件、承認画面と既存CookieログインのChromium試験が成功した。
|
||||||
|
`TestRemoteCLILanguageForkRequiresWritePermission`で、有効なreadonlyセッションからの言語版作成が403になり、Revisionが残らないことも確認した。
|
||||||
|
この後続変更はv0.4.0で配布し、同日21:48 JSTに本番へ反映した。実ユーザーの文書編集は行わず、利用者による操作確認に委ねる。
|
||||||
|
|
||||||
|
ソースのチェックポイント:`.deployment-backups/dev-cli-oidc-20261101/source-after.tar.gz`
|
||||||
|
(SHA-256 `3e4228cd53b4220dffe43a80b4ed02c0bd757a8b3845829b7d3a77a64b0e9c4b`)。
|
||||||
|
OIDC関連18ファイルのみで、本番DB・鍵・セッション・前段のログ保存修正は含まない。
|
||||||
|
変更前はGitの`0f686aa`と比較し、対象ファイル単位で復元する。作業ツリー全体をresetしない。
|
||||||
|
|
||||||
次段階の順序:
|
次段階の順序:
|
||||||
|
|
||||||
1. Ctrl+Pによる検索選択、補完の引用文字/途中カーソル対応、永続履歴の明示opt-in。
|
1. Ctrl+Pによる検索選択、補完の引用文字/途中カーソル対応、永続履歴の明示opt-in。
|
||||||
2. 新規Page+Path+初回Revisionの原子的な作成API、create/upload-only権限、並行作成の衝突、言語分岐。
|
2. 新規Page+Path+初回Revisionの原子的な作成API、create/upload-only権限、並行作成の衝突。既存Pageの言語分岐は実装済み。
|
||||||
3. 競合の対話選択・復旧コマンド、巨大転送のstreamingとキャンセル、mget/mput(globのlocal/remoteを明示)。
|
3. 競合の対話選択・復旧コマンド、巨大転送のstreamingとキャンセル、mget/mput(globのlocal/remoteを明示)。
|
||||||
4. OIDCブラウザ認証の短命・単回・PKCE相当ハンドオフ。既存device approvalをそのまま転用せず、本人確認・Domain・CLIリクエストを束縛する。
|
4. OIDC引き継ぎの本番schema適用・サーバ/CLI配布と利用者確認はv0.3.0で完了。追加TOTP省略と言語編集改善はv0.4.0で配布済み。schema v1の定義は変更しない。
|
||||||
5. OS keyring、Windows対応、非公開の短縮リンク引き継ぎ。自動的な公開shareは行わない。
|
5. OS keyring、Windows対応、非公開の短縮リンク引き継ぎ。自動的な公開shareは行わない。
|
||||||
@@ -4,6 +4,12 @@
|
|||||||
|
|
||||||
## 優先順
|
## 優先順
|
||||||
|
|
||||||
|
2026-11-02:[共通ナビゲーション・個人設定・ウィジェットダッシュボード](organizer-dashboard.md)を実装。タスク/カレンダー/連絡先の導線統一、トップ・ナビバーの連絡先、個人別の配置・サイズ保存。ソース実装と本番反映は区別し、共有・外部ウィジェットは後続。
|
||||||
|
|
||||||
|
2026-11-02:[個人CardDAV提供と履歴復元・一括export](../../operations/carddav-contacts.md)を実装。専用資格情報、条件付き更新、変更tokenと削除tombstone、bounded REPORTを追加。09:04:17 JSTに[v0.6.0として本番2系統へ反映](../../operations/deployments/2026-11-02-v0.6.0.md)。共有アドレス帳・外部CardDAV connector・実機互換確認は同資料の後続範囲。
|
||||||
|
|
||||||
|
2026-11-01:[タスク作成・作業記録・達成度・日次メール・個人アドレス帳](task-productivity-contacts.md)を追加。Web/CLI/neomuttの共通capture、時間記録、既定値、検索コマンドを接続。作業記録の事後訂正、日次メールの再送・保持期間は同設計の後続範囲へ集約する。
|
||||||
|
|
||||||
2026-10-31:ユーザ指定により[日常操作・ブラウザ・エディタ・CLI](priority-ux-20261031.md)を次期開発の最優先とする。下記の従来機能追加より優先するが、認可・データ保全の安全条件は省略しない。TODO、受け入れ条件、復元用チェックポイントを同文書に集約する。
|
2026-10-31:ユーザ指定により[日常操作・ブラウザ・エディタ・CLI](priority-ux-20261031.md)を次期開発の最優先とする。下記の従来機能追加より優先するが、認可・データ保全の安全条件は省略しない。TODO、受け入れ条件、復元用チェックポイントを同文書に集約する。
|
||||||
|
|
||||||
2026-09-27追記:`organizer.tasks 0.11.1`で[既定タスクリスト名の変更](task-dav-default-list-name.md)を実装し、12:51 JSTに[本番両インスタンスへ反映](../../operations/deployments/2026-09-27-default-task-list-name.md)。PROPPATCH 405を解消し、利用者・domain別の表示名を保存、全探索結果へ反映する。実機再試行は確認待ち。色・アイコン・通常プロジェクトのPROPPATCHは別件。
|
2026-09-27追記:`organizer.tasks 0.11.1`で[既定タスクリスト名の変更](task-dav-default-list-name.md)を実装し、12:51 JSTに[本番両インスタンスへ反映](../../operations/deployments/2026-09-27-default-task-list-name.md)。PROPPATCH 405を解消し、利用者・domain別の表示名を保存、全探索結果へ反映する。実機再試行は確認待ち。色・アイコン・通常プロジェクトのPROPPATCHは別件。
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# タスク作成と作業記録と個人アドレス帳
|
||||||
|
|
||||||
|
タスクの入口をWeb・CLI・メールで共通化する。タスク、作業記録、既定値、配信設定、連絡先はDomainと本人に属する。既存のタスクAPI・CalDAVを変更せず、個人向けAPIを追加する。管理者であることだけでは他人のデータを読めない。
|
||||||
|
|
||||||
|
## 作成API
|
||||||
|
|
||||||
|
基点は `/_/api/v1/extension/organizer.tasks/`。通常のログインセッションのBearer認証を使う。CalDAV専用資格情報はこのAPIの資格情報ではない。
|
||||||
|
|
||||||
|
| 操作 | Methodと相対URI | 契約 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| タスクを作る | POST `capture` | UUIDのrequest_id、titleが必須。notes、project_uuid、assignee_uuid、due_on、start_on、planned_on、review_on、estimate_minutes、complexityを指定可能 |
|
||||||
|
| 既定値 | GET / PUT `preferences` | PUTはGETしたversionを含める。競合は412 |
|
||||||
|
| 実行中の記録 | GET `work` | itemがnullなら停止中 |
|
||||||
|
| 開始 | POST `work` | action=start、uuid、task_uuid。開始時刻はサーバーで記録 |
|
||||||
|
| 終了 | POST `work` | action=stopとGETで得たitem。versionで条件付き更新 |
|
||||||
|
| レポート | GET `report?from=YYYY-MM-DD&to=YYYY-MM-DD` | fromを含み、toを含まない。ドメインのtimezone、最大367日 |
|
||||||
|
| 予定を作る | POST `calendar-capture` | request_id、calendar_uuid、title、from、to。本人所有・非公開・非共有・外部sourceなしのカレンダー限定 |
|
||||||
|
|
||||||
|
captureは省略した項目に本人の既定値を適用する。日付の空文字は既定値を使わず明示的に解除する。日数は作成日のドメインtimezoneにおける暦日で、0は当日、空欄は未設定。担当者UUIDは計画上の注記であり、所有権の移転や閲覧権限の付与ではない。
|
||||||
|
|
||||||
|
Webの新規作成・クイック追加・サブタスク追加でも既定値を読む。サブタスクのプロジェクト・優先度・bucketは親の所属を優先する。既存汎用items APIとCalDAVではクライアント指定を尊重し、新しいcaptureの既定値を暗黙適用しない。
|
||||||
|
|
||||||
|
同じrequest_id・同じ要求内容の再送は既存タスクを返す。最初の保存後に既定値やタスクが更新されても作り直さない。同じrequest_idで別内容を送ると412。要求のreceiptとタスクRevisionは同一トランザクションで保存する。API入力は32 KiBまで、件名300 UTF-8 bytes、メモ16 KiBまで。
|
||||||
|
|
||||||
|
calendar-captureも同じUIDを再利用し、再送で既存予定を上書きしない。時刻は `2026-11-02T09:00` のドメイン時刻、またはオフセット付きRFC 3339。終了は開始後、最大31日。予定内容を取得する前にPersonalLocal制約をロック内で検査する。外部取り込みカレンダーの内容を読まない。
|
||||||
|
|
||||||
|
## 作業時間と達成度
|
||||||
|
|
||||||
|
Webのタスク行の▶から開始し、上部の作業記録欄で終了する。CLIは `task start UUID` / `task stop`。タイマーはサーバーで継続するので、ブラウザや端末を閉じても止まらない。停止はタスク完了とは別操作。忘れずに終了すること。同一人物で同時に開始できる記録は1件。
|
||||||
|
|
||||||
|
`/v/plan/dashboard` の達成度ウィジェットは完了数、ポイント、作業時間、Pomodoro集中時間を表示する。旧 `/v/plan/tasks/report` はここへ移動する。[配置・保存の契約](organizer-dashboard.md)を参照。ポイントは `1 + ceil(見積分数 / 30) × 複雑度`。複雑度は1〜5、未設定の旧タスクは1。見積なしは1ポイント。完了の取消は集計から除外し、再完了するとその日の実績になる。完了済みタスクの見積変更も現在のポイントへ反映される。これは個人の振り返り指標であり、人事評価や客観的生産性の尺度ではない。
|
||||||
|
|
||||||
|
深夜をまたぐ作業はローカル日付境界で分割し、夏時間の日も24時間固定にしない。Pomodoroと手動記録は別集計で、両者を合算しない。各系列は最大10,000件で、上限到達時はpartialを返して期間の絞り込みを促す。
|
||||||
|
|
||||||
|
## 毎日のメール
|
||||||
|
|
||||||
|
`/-/sys/config?panel=organizer` の個人設定で本人が有効化する。旧 `/v/plan/tasks/settings` もここへ移動する。送信先は現在の本人のアカウントメールアドレスのみ。管理者のSMTP設定が必要。時刻はHH:mmとIANA timezoneを保存する。`task.digest.deliver` イベントが60秒周期で期限到来設定を最大20件ずつ処理する。キュー停止・負荷・SMTP遅延で配信時刻が遅れる場合がある。
|
||||||
|
|
||||||
|
当日の計画・期限到来タスクを最大100件送る。件名、期限、取り組む日、見積、タスクURLを含め、メモは送らない。送信直前にアカウント状態・同意のversion・送信先を再確認する。メールによる保存・転送の可能性があるため、既定は無効。
|
||||||
|
|
||||||
|
SMTPとSQLiteをまたぐexactly-onceは保証できない。送信前にDomain・本人・日付で予約し、配送結果はsent、uncertain、cancelled。予約後のクラッシュはsendingとして残す。結果不明の場合は自動再送せず、二重送信を避ける。翌日は通常通り処理し、過去日の取りこぼしをまとめて送らない。設定画面に直近結果を表示する。
|
||||||
|
|
||||||
|
## トップ検索コマンド
|
||||||
|
|
||||||
|
```text
|
||||||
|
add task 見積を確認 project:"開発 計画" cost:2h due:2026-11-03 review:2026-11-02 complexity:3
|
||||||
|
add task 文書を書く start:2026-11-02 planned:2026-11-02
|
||||||
|
add cal 打ち合わせ calendar:personal from:2026-11-02T09:00 to:2026-11-02T10:00
|
||||||
|
```
|
||||||
|
|
||||||
|
`project:` は名前またはUUID、候補を表示する。`calendar:` は名前・pretty_name・UUID、対象が1つだけなら省略可能。スペースを含む名前は引用符で囲む。工数は2h、30m、1.5hなど整数分に換算できる値。日付はYYYY-MM-DD。
|
||||||
|
|
||||||
|
Enterでは確認欄を表示し、「作成」で保存する。通常の検索候補への移動とは分離する。未知のオプション・重複指定・曖昧な名前は拒否。通信失敗時は同じ画面の再試行で同じrequest_idを使用する。トップ検索の入力は再読込をまたぐ永続下書きではない。
|
||||||
|
|
||||||
|
## 個人アドレス帳
|
||||||
|
|
||||||
|
画面は `/v/plan/contacts`、APIは `/_/api/v1/extension/organizer.contacts/`。拡張機能organizer.contactsを無効化すると読み書きとも停止する。Principal・プロフィール連絡先とは独立し、メール一致による自動アカウント紐付けはしない。
|
||||||
|
|
||||||
|
名前、複数メール・電話、所属、メモを編集できる。GET itemsはqとafterで最大100件ずつ検索・取得。POST itemsでUUID付き新規作成、GET items/UUIDで詳細、PUT items/UUIDでversionとIf-Matchを伴う条件付き更新。削除はdeleted=trueの同じPUTで行い、一覧から除外する。「削除済み」へ切り替えて復元できる(一覧APIのdeleted=1、更新時deleted=false)。削除したデータとvCard snapshotは保全される。
|
||||||
|
|
||||||
|
POST importは1件のUTF-8 vCard、GET items/UUID.vcfは書き出し。Webは最大2 MiB・200件のファイルを確認後に1件ずつ取り込み、失敗したカード番号を報告する。原子的な一括処理ではなく、成功分は保持する。同じUID・同じ内容は重複登録せず、同じUIDの異なる内容は412。UIDなしは入力バイト列のSHA-256から安定したUIDを補う。
|
||||||
|
|
||||||
|
vCard 3.0/4.0のUTF-8を対象とし、fold/unfold、テキストescape、複数のEMAIL/TEL、未知propertyを扱う。未対応propertyは保存・再出力し、PHOTO等の外部URLを取得しない。変更していない編集項目のparameterや繰り返しも保持する。変更した項目は画面の値で置換するため、その項目のTYPE等は外れる。vCard 2.1、ENCODING/CHARSET指定、壊れた行は欠落を起こす前に拒否する。1件64 KiBまで。
|
||||||
|
|
||||||
|
vCardの内容はDocumentStore snapshot、現在値と所有者・version・検索用projectionはSQLite、履歴はorganizer_contact_revisionsに保存する。DR snapshotのDocument参照抽出にも連絡先の現在・履歴を含める。一般のWiki/アセットURLに公開するための登録はしない。
|
||||||
|
|
||||||
|
2026-11-02に `organizer.contacts 0.2.0` として、個人CardDAV提供、変更履歴の確認・復元、全アドレス帳exportを追加した。履歴はGET `items/UUID/history` と `items/UUID/history/VERSION`、復元はPOST `items/UUID/restore` にrevision・version・If-Matchを渡し、新しい版を保存する。GET `export.vcf` は有効な連絡先のみ、最大5,000件・16 MiBを一括出力する。CardDAVのrootは `/_/api/v1/carddav/`。専用scope `contacts` を使い、既存CalDAVのallを拡張しない。[接続・同期・移行契約](../../operations/carddav-contacts.md)を参照。
|
||||||
|
|
||||||
|
## 移行と後続範囲
|
||||||
|
|
||||||
|
managed schemaにtask-productivityとcontactsを追加。task-productivityは既存organizer_items作成後に実行し、旧完了タスクを1回だけ集計projectionへ移す。既存スキーマ定義の改変ではない。切戻しでは旧版のschema checkが新コンポーネントを未知とするため、単に旧イメージを起動できるとは扱わない。データを消して戻さない。
|
||||||
|
|
||||||
|
- 連絡先の共有アドレス帳、外部CardDAV connector、重複候補mergeは別段階。個人CardDAV提供面と外部サービスの取り込みは区別する。
|
||||||
|
- 作業記録の事後修正・取消、失効Domainで取り残された記録の管理用終了手順、プロジェクト別集計、担当者への共有・通知は後続。
|
||||||
|
- 日次メールの手動再送・配信ログの保管期間、receiptの失効設計は後続。安易な削除で重複作成・配信を復活させない。
|
||||||
|
- vCard legacy変換・version間変換と履歴保持期間は後続。
|
||||||
|
|
||||||
|
利用手順は [neomuttとタスクCLI](../../operations/neomutt-tasks.md) を参照。
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
# タスク通知:予約・配信・取消
|
# タスク通知:予約・配信・取消
|
||||||
|
|
||||||
更新日:2026-09-25。個人タスクの期限日/計画日のInbox通知を実装。カレンダー通知、メール、OS push、集中タイマー、quiet hours、通知の集約は未実装。
|
更新日:2026-11-04。本書は個人タスクの期限日/取り組む日のInbox通知と、その個人既定値を扱う。日次メールやOS通知、集中タイマーは別機能として扱い、Inbox予約の配信条件と混同しない。
|
||||||
|
|
||||||
## 操作と既定値
|
## 操作と既定値
|
||||||
|
|
||||||
タスク編集に「期限日にInboxへ通知」「取り組む日にInboxへ通知」と時刻入力を追加する。両方とも既定OFF。通知を選択した日付が必須で、未指定の時刻は09:00。期限は引き続き日付型であり、通知時刻によって時刻付きの締切へ変換しない。プロジェクトには通知を設定しない。
|
タスク編集に「期限日にInboxへ通知」「取り組む日にInboxへ通知」と時刻入力を置く。未設定の個人では両方ともOFF、未指定の時刻は09:00。通知を選択した日付は必須。期限は引き続き日付型であり、通知時刻によって時刻付きの締切へ変換しない。プロジェクトには通知を設定しない。
|
||||||
|
|
||||||
|
2026-11-04のソース更新では、個人設定 `/-/sys/config?panel=organizer` に期限日・取り組む日の通知既定値と通知時刻を追加した。Domain・本人ごとの既存preferences JSONに `notify_due`、`notify_planned`、`reminder_time` を保存する。DBスキーマ変更は不要。メールの日次配信とは独立した設定であり、古い設定の通知はOFFのまま、時刻は09:00として読む。
|
||||||
|
|
||||||
|
既定値は新規タスクだけに使い、既存タスクの設定や予約を一括変更しない。対応する日付がある場合だけ通知ONとし、日付のない簡易追加は許可する。新規編集画面で日付を入力した場合にも既定値を適用するが、利用者が通知を明示的に選び直した後はその選択を優先する。簡易追加・サブタスクはpreferencesの `defaults` を使用し、capture APIはリクエストの日付上書き後に通知の既定値を適用する。既存のitems APIの更新、CalDAV更新に個人既定値を強制しない。
|
||||||
|
|
||||||
保存時のドメイン設定のタイムゾーンをサーバー側で取得し、`reminder_timezone` に記録する。APIが指定した別のzoneを信用しない。設定画面のzone変更だけでは保存済み予約を動かさず、タスクの再保存で新しいzoneを適用する。編集画面には保存時に適用するzoneを表示する。
|
保存時のドメイン設定のタイムゾーンをサーバー側で取得し、`reminder_timezone` に記録する。APIが指定した別のzoneを信用しない。設定画面のzone変更だけでは保存済み予約を動かさず、タスクの再保存で新しいzoneを適用する。編集画面には保存時に適用するzoneを表示する。
|
||||||
|
|
||||||
@@ -42,4 +46,4 @@ Inboxには一般的な通知文と対象UUIDだけを保存し、個人タス
|
|||||||
|
|
||||||
テスト対象:初期OFF、指定日とzoneでの予約、夏時間、存在しない時刻、日付変更・完了・取消・アーカイブ・OFF、権限失効、拡張停止、期限切れ予約、同一機会の重複防止、並列配信、予約/Inbox挿入失敗時のrollback、現時点での件名表示、別所有者への漏えい防止。ブラウザでは通知設定の保存、バックグラウンド配信後の赤丸、Inbox表示まで隔離環境で確認する。
|
テスト対象:初期OFF、指定日とzoneでの予約、夏時間、存在しない時刻、日付変更・完了・取消・アーカイブ・OFF、権限失効、拡張停止、期限切れ予約、同一機会の重複防止、並列配信、予約/Inbox挿入失敗時のrollback、現時点での件名表示、別所有者への漏えい防止。ブラウザでは通知設定の保存、バックグラウンド配信後の赤丸、Inbox表示まで隔離環境で確認する。
|
||||||
|
|
||||||
次段階:個人/ドメインの通知既定値、quiet hours、集約、予約状態の詳細表示、ローカルカレンダーの時間枠との関連付け・予定通知。外部から取り込んだカレンダー内容へのアクセスは、別途許可があるまで行わない。
|
次段階:ドメインの通知既定値、quiet hours、集約、予約状態の詳細表示、ローカルカレンダーの時間枠との関連付け・予定通知。外部から取り込んだカレンダー内容へのアクセスは、別途許可があるまで行わない。
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
# 個人アドレス帳の操作とCardDAV接続
|
||||||
|
|
||||||
|
`organizer.contacts 0.2.0` は、Webの個人アドレス帳と外部クライアントが同じ連絡先を編集するための限定CardDAV提供面を持つ。連絡先はDomainと所有者で分離し、管理者であることだけでは他人の連絡先を取得できない。共有アドレス帳や、PagesWikiから外部サービスを定期取得するconnectorは別の後続機能である。
|
||||||
|
|
||||||
|
2026-11-02、v0.6.0で本番2系統へ反映した。[展開とバックアップ整理の記録](deployments/2026-11-02-v0.6.0.md)を参照する。
|
||||||
|
|
||||||
|
## Webでの操作
|
||||||
|
|
||||||
|
入口は `/v/plan/contacts`。
|
||||||
|
|
||||||
|
- 名前、複数メールアドレス・電話番号、所属、メモを編集する。
|
||||||
|
- 「削除済み」の一覧から連絡先を復元する。削除は履歴を残す論理削除である。
|
||||||
|
- 個別の「変更履歴」で過去のvCardを確認し、選んだ版を新しい版として復元する。復元確認で未保存フォームの破棄を明示する。他の端末で変更されていた場合は412で止まり、再読み込みが必要になる。
|
||||||
|
- 「アドレス帳を書き出す」で有効な連絡先を1つの `.vcf` にまとめる。削除済みは含まない。上限は5,000件または16 MiBで、超過した場合は途中までのファイルを正常応答として返さない。
|
||||||
|
- ⇄ の「CardDAV連携」で、端末別の資格情報を発行・失効する。
|
||||||
|
|
||||||
|
vCardの未対応項目は保存・再出力するが、Webで変更した項目についてはその項目のTYPEなどのparameterを再現しない。PHOTO等の外部URLにはアクセスしない。vCard 2.1、ENCODING/CHARSET指定、1件64 KiBを超える画像入りカードなどは拒否する。詳細は[個人アドレス帳の実装契約](../design/ja/task-productivity-contacts.md)を参照。
|
||||||
|
|
||||||
|
## クライアントを接続する
|
||||||
|
|
||||||
|
1. Webに通常ログインし、連絡先画面の ⇄ を開く。
|
||||||
|
2. 端末名、読み取り専用または読み書き、有効期間を選び、パスワードを発行する。
|
||||||
|
3. 表示された認証情報IDとパスワードをクライアントに保存する。パスワードは再表示できない。
|
||||||
|
|
||||||
|
| 項目 | 値 |
|
||||||
|
| --- | --- |
|
||||||
|
| サーバーURL | `https://pages.anya.jp/_/api/v1/carddav/`。別DomainではそのDomainのHTTPS originを使う |
|
||||||
|
| ユーザー名 | 発行画面の認証情報ID。Wikiのユーザー名・メールアドレスではない |
|
||||||
|
| パスワード | 発行した連絡先専用パスワード |
|
||||||
|
| アドレス帳 | 自動検出される `PagesWiki Contacts` |
|
||||||
|
| discovery | `/.well-known/carddav` からAPI rootへ307転送 |
|
||||||
|
|
||||||
|
専用資格情報のscopeは `contacts`。既存の `tasks`、`calendar`、`all` は連絡先への権限を持たず、`all` の意味は予定とタスクのままである。連絡先の資格情報からWiki API、予定、タスクへアクセスできない。通常セッションのBearerでも本人のCardDAVを操作できるが、端末設定には用途を限定した資格情報を使う。
|
||||||
|
|
||||||
|
資格情報の管理は既存の `/_/api/v1/caldav-credentials` APIを共用する。作成時に `scope: "contacts"` を明示する。この管理API自体には通常のログインセッションが必要で、CardDAV資格情報による再発行はできない。HTTPSを必須とし、AuthorizationやvCard本文をログ・問い合わせに貼り付けない。
|
||||||
|
|
||||||
|
vdirsyncer 0.21.0では、合成データによる検出、取得、双方からの更新、新規作成、双方からの削除を検証した。設定例は以下の通り。実際の資格情報を含むファイルは所有者のみ読み取り可能にする。
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[general]
|
||||||
|
status_path = "~/.local/state/vdirsyncer"
|
||||||
|
|
||||||
|
[pair contacts]
|
||||||
|
a = "contacts_local"
|
||||||
|
b = "contacts_remote"
|
||||||
|
collections = ["contacts"]
|
||||||
|
|
||||||
|
[storage contacts_local]
|
||||||
|
type = "filesystem"
|
||||||
|
path = "~/.local/share/contacts"
|
||||||
|
fileext = ".vcf"
|
||||||
|
|
||||||
|
[storage contacts_remote]
|
||||||
|
type = "carddav"
|
||||||
|
url = "https://pages.anya.jp/_/api/v1/carddav/"
|
||||||
|
username = "発行された認証情報ID"
|
||||||
|
password = "発行されたパスワード"
|
||||||
|
```
|
||||||
|
|
||||||
|
`contacts_local` のpath配下に `contacts` ディレクトリを作り、`vdirsyncer discover`、`vdirsyncer sync` を実行する。アドレス帳名の書き換えは未対応なので、`metadata = ["displayname"]` によるmetasyncは設定しない。全件削除はクライアントの安全機構が止める場合があり、意図した削除か確認するまで強制オプションを使わない。DAVx⁵・iOSの端末実機での検証は別途必要である。
|
||||||
|
|
||||||
|
## URIと通信契約
|
||||||
|
|
||||||
|
| URI | 役割と操作 |
|
||||||
|
| --- | --- |
|
||||||
|
| `/_/api/v1/carddav/` | OPTIONS、PROPFIND。current-user-principalとaddressbook-home-set |
|
||||||
|
| `/_/api/v1/carddav/{principal_uuid}/` | 本人のhome。OPTIONS、PROPFIND |
|
||||||
|
| `/_/api/v1/carddav/{principal_uuid}/contacts/` | 固定の個人アドレス帳。OPTIONS、PROPFIND、REPORT |
|
||||||
|
| 同上の `{resource_name}.vcf` | OPTIONS、PROPFIND、GET、HEAD、PUT、DELETE |
|
||||||
|
|
||||||
|
resource名は `.vcf` を含め5〜128 ASCII bytes、英数字・ハイフン・アンダースコア・ピリオドのみ、先頭ピリオドは禁止。Web作成分はUUID.vcf、クライアント作成分は受信した名前を固定対応表に保存する。UIDは同じ所有者・Domain内で一意かつ作成後は変更不可。名前とUIDが同じという仮定はしない。
|
||||||
|
|
||||||
|
取得時のETagはリソースのversionを表す。作成は `If-None-Match: *`、更新・削除は取得済みの `If-Match` が必要で、条件がない場合は428、競合時は412を返す。内容の正規化でPUTの入力バイト列と保存値が変わった場合は、PUT応答にETagを付けず再取得を要求する。vCardのUID欠落・変更・重複を黙って別人として保存しない。
|
||||||
|
|
||||||
|
PROPFINDはDepth 0または1。アドレス帳一覧は同じDB snapshotからtokenとメタデータを取得し、本文をロードせず最大5,000件を返す。上限超過は507で、欠落した一覧からクライアントが削除を誤推定することを避ける。
|
||||||
|
|
||||||
|
REPORTは以下の限定範囲を実装する。
|
||||||
|
|
||||||
|
- `addressbook-multiget`:同じアドレス帳の最大100 href。外部URLは取得しない。
|
||||||
|
- `addressbook-query`:最大200件のアドレス帳を対象とするbounded scan。propertyの存在・不在、text-match、anyof/allofを扱う。未知propertyも原文から検索する。parameter filterは未対応で、無視せずエラーにする。
|
||||||
|
- `sync-collection`:sync-level 1。最大200件ずつの差分、追加・更新・削除tombstoneを返す。続きがある場合はアドレス帳の507応答と次のtokenを207内に含める。クライアントはそのtokenで続行する。
|
||||||
|
|
||||||
|
不正なsync-tokenは403の `valid-sync-token`。クライアントはローカルデータを捨てず、再照合する。XMLは64 KiB、深さ12、要素1,000まででDTDを拒否する。全体の処理期限は20秒。取得・更新は `private, no-store` とする。
|
||||||
|
|
||||||
|
対応するvCardは既存のUTF-8 3.0/4.0保存profileで、通信では保存されたversionをそのまま返す。3.0↔4.0変換やaddress-dataの部分抽出はしない。別versionを明示要求された場合は拒否する。MKCOL、PROPPATCH、DAV ACL、共有・複数アドレス帳、MOVE/COPYは未対応。`DAV: 1, addressbook-access` はクライアント検出用に返すが、CardDAV全機能への準拠を意味しない。応答には `X-PagesWiki-CardDAV-Profile: private-addressbook` を付ける。
|
||||||
|
|
||||||
|
基本プロトコルは[RFC 6352](https://www.rfc-editor.org/rfc/rfc6352.html)、差分同期は[RFC 6578](https://www.rfc-editor.org/rfc/rfc6578.html)を参照する。text-matchは `i;octet` と、titlecase後の互換分解を使う `i;unicode-casemap` を扱う。[RFC 5051](https://www.rfc-editor.org/rfc/rfc5051.html)
|
||||||
|
|
||||||
|
## 保存と移行
|
||||||
|
|
||||||
|
contactsのmanaged schema v2を追加し、リリース済みv1の定義は変更しない。既存の連絡先と履歴を残したままresource名、変更sequence、DB epochを補う。変更sequenceは連絡先ごとの最新1行だけを保持し、論理削除も差分に残す。vCard snapshotと履歴の保管は従来通りであり、履歴自体の保持期間・GCは後続設計となる。
|
||||||
|
|
||||||
|
sync-tokenはDB epoch、Domain、所有者、sequenceに結び付く。DBバックアップを復元するとsequenceが過去へ戻り得るため、復元先を公開する前に停止状態で `organizer_contact_epoch` のvalueを新しい32-byte乱数のhexへ更新し、既存クライアントを再照合させる。tombstoneを物理削除する保守もtoken失効とセットで設計する。通常稼働中の自動purgeは実装しない。
|
||||||
|
|
||||||
|
切戻しには旧バイナリが新schema versionを拒否する場合がある。旧イメージへの交換だけを安全なrollbackとは扱わず、整合したDB・DocumentStoreのバックアップと復元手順を用意する。新しい連絡先秘密値は `pw_contactdav_` prefixを使い、旧版がタスク権限として誤解釈しない。
|
||||||
|
|
||||||
|
## 検証
|
||||||
|
|
||||||
|
2026-11-02に以下を合成データで実施した。本番連絡先や外部取り込みカレンダーの内容は検証に使用していない。
|
||||||
|
|
||||||
|
- `go test ./... -count=1`、`go vet ./...`。
|
||||||
|
- 連絡先・managed schemaのrace detector付きテスト。同時PUTは一方だけ204、他方は412となる。
|
||||||
|
- v1からv2への既存行保全・繰り返し起動、変更sequence更新、資格情報削除のmarker清掃。
|
||||||
|
- 読み取り専用・失効・別scope・extension無効化、カレンダーとタスクを無効にした場合の独立稼働。
|
||||||
|
- 201件の一覧と差分ページング、上限超過の明示、XML・UID・文字コード・Unicode検索の境界条件。
|
||||||
|
- vdirsyncer 0.21.0での往復同期、Chromiumのデスクトップとスマートフォン幅での保存・履歴確認・復元・一括export・資格情報発行と失効。
|
||||||
|
|
||||||
|
実クライアント試験は `PAGESWIKI_VDIRSYNCER` に実行ファイルを指定し、`go test ./internal/server -run '^TestContactDAVVdirsyncer$' -count=1` で再実行できる。ブラウザ試験は `PAGESWIKI_BROWSER_TEST=1` で `TestProductivityChromium` の `contacts-` サブテストを実行する。通常のテストでは外部クライアントとブラウザの試験をskipする。
|
||||||
|
|
||||||
|
## 次段階
|
||||||
|
|
||||||
|
- [ ] 複数・共有アドレス帳、read/write collaboratorと共有解除、管理者の代理操作境界。
|
||||||
|
- [ ] 外部CardDAV connector。ETagと同期receipt、競合保全、URLのSSRF対策、イベントキュー・停止スイッチ。
|
||||||
|
- [ ] 200件を超えるaddressbook-queryの索引化、parameter filter、vCard version変換の情報保持試験。
|
||||||
|
- [ ] 端末実機の互換試験、連絡先mergeの確認UI、履歴保持・削除ポリシー。
|
||||||
|
|
||||||
|
後続機能は現在の個人アドレス帳を暗黙に公開・共有しない。外部connectorの追加は資格情報の保存・外向き通信を新たに伴うため、現在のCardDAV提供面とは別の設定とする。
|
||||||
@@ -122,4 +122,5 @@ panic・fatal・ジョブ失敗・再起動は検出していない。
|
|||||||
|
|
||||||
`0f686aa` を基点に、上記ログ競合の修正をソースへ実装した。
|
`0f686aa` を基点に、上記ログ競合の修正をソースへ実装した。
|
||||||
契約と検証範囲は [Dregarnuhrのログ保存競合修正](../../design/ja/dregarnuhr.md#v020後の優先修正ログ保存競合) を参照。
|
契約と検証範囲は [Dregarnuhrのログ保存競合修正](../../design/ja/dregarnuhr.md#v020後の優先修正ログ保存競合) を参照。
|
||||||
この追記は本番修正済みを意味しない。v0.2.0のイメージ・タグは変更していない。
|
修正は同日20:00 JSTに [v0.2.1として本番反映](2026-11-01-v0.2.1.md)した。
|
||||||
|
上記の継続課題・観察結果はv0.2.0切替時点の記録である。v0.2.0のイメージ・タグは変更していない。
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
# PagesWiki v0.2.1 のログ保存修正と本番反映
|
||||||
|
|
||||||
|
2026-11-01 20:00:00 JST、イベントログのSQLite書込競合を修正した `v0.2.1` を本番へ反映した。
|
||||||
|
対象は `app`、`app2`、`adaptor-gateway`、`excalidraw-viewer`。code-server、Kroki、Mermaidは再作成していない。
|
||||||
|
別作業で進行中のCLI認証変更は含めず、イベントログ関連の9ファイルだけをリリースした。
|
||||||
|
|
||||||
|
## リリース対象
|
||||||
|
|
||||||
|
- ソースcommit:`a36934e72cd68e4ce6ea27b944d00378ef316e8d`。
|
||||||
|
- 注釈付きGitタグ:`v0.2.1`。タグobject:`1ab0aca388cb24fc52edf4d6ac8dfadec526f6a7`。
|
||||||
|
- [ビルド run 14](https://git.anya.jp/anya/wikipages/actions/runs/14):全工程成功。
|
||||||
|
- [リリース昇格 run 15](https://git.anya.jp/anya/wikipages/actions/runs/15):全工程成功。
|
||||||
|
- SemVerのPATCH更新。v0.2.0のタグ・配布物は変更していない。
|
||||||
|
|
||||||
|
`AddEventLogContext` が読み取り前に `BEGIN IMMEDIATE` で書込権を取得し、
|
||||||
|
rawログと集約bucketを同じtransactionで保存する。書込権取得の待機と再試行を有界にし、
|
||||||
|
取消後はrollbackと接続設定の復元を行う。開始・進捗・完了ログの保存失敗は秘密を含まない分類で診断する。
|
||||||
|
完了ログだけの失敗で、成功済みの業務処理を再実行しない。
|
||||||
|
契約と残件は [Dregarnuhr](../../design/ja/dregarnuhr.md#v020後の優先修正ログ保存競合) を参照。
|
||||||
|
|
||||||
|
registry prefixは `git.anya.jp/anya/`。3種類ともSHAタグとリリースタグのmanifest digestが一致し、
|
||||||
|
OCI revisionラベルはソースcommitと一致した。タグ昇格時の再ビルドは行っていない。
|
||||||
|
|
||||||
|
| イメージ | v0.2.1 manifest digest |
|
||||||
|
| --- | --- |
|
||||||
|
| pageswiki-app | `sha256:8b789f8f28a987bcb6f5ba2828fb00222716cce251a5b159a5e0bf7adba2cf46` |
|
||||||
|
| pageswiki-adaptor-gateway | `sha256:c7a288c6c01e1509d7e3dbbd22ded464747fc05d56ccb45410bed0ce8c1cd5b7` |
|
||||||
|
| pageswiki-excalidraw-viewer | `sha256:c08569a0a8a170067952e0e427154882da0e076454deb130143ef57b821071c7` |
|
||||||
|
|
||||||
|
## 検証
|
||||||
|
|
||||||
|
未コミットのCLI認証変更を含まない独立ソースコピーで、次を確認した。
|
||||||
|
|
||||||
|
- `go test ./... -count=1`:全件成功。
|
||||||
|
- `go test -race ./internal/store ./internal/server -run 'TestEvent(Log|Completion|Logging)' -count=3`:成功。
|
||||||
|
- `go vet ./...`:成功。
|
||||||
|
- Gitea CIの全Goテストとリリースツール試験:成功。
|
||||||
|
|
||||||
|
整合バックアップの独立コピー2系統をCIイメージで起動した。
|
||||||
|
network none、CPU 2、メモリ2GiB、コピーだけのDR設定でworkersを無効化し、外部enroll引数を省略した。
|
||||||
|
両方とも設定済みポート3000でhealthが成功し、起動ログのerror・failed・panic・fatalは0件だった。
|
||||||
|
管理対象9コンポーネントのschema checkはすべてcurrent。DBスキーマ追加・データ変換はない。
|
||||||
|
検証コピーと検証コンテナは削除し、整合バックアップは保持した。
|
||||||
|
|
||||||
|
本番切替後も、4サービスのrevision一致・再起動0回、アプリ2台のhealth、
|
||||||
|
公開HTTPSのhealth・ログインの200、gateway・Excalidrawのhealth、
|
||||||
|
アプリ2台の管理対象9コンポーネントcurrentを確認した。
|
||||||
|
外部から取り込んだカレンダーの内容は開いていない。
|
||||||
|
|
||||||
|
## ログ競合の観察
|
||||||
|
|
||||||
|
切替準備前のv0.2.0では、直近2分にappの開始ログ保存競合が7件発生し、ジョブ本体の失敗は0件だった。
|
||||||
|
切替後の確認は19:59:53 JSTを起点とし、composeログの失敗件数と、
|
||||||
|
読み取り専用DB接続によるジョブ状態・定型の開始/完了ログの件数だけを取得する。
|
||||||
|
payloadやイベント本文は出力しない。
|
||||||
|
|
||||||
|
19:59:53〜20:03:21 JSTの約3分28秒で、4サービスとも開始/進捗/完了ログ保存失敗、
|
||||||
|
SQLiteロック、ジョブ失敗、panic・fatalは0件だった。4サービスとも再起動0回を維持した。
|
||||||
|
この間に作成され完了したジョブはappで30件、app2で27件、すべてsucceededであり、
|
||||||
|
57件すべてに開始ログと完了ログが存在した。観察範囲では、修正前に発生していた開始ログの欠落は再現していない。
|
||||||
|
|
||||||
|
## 保全と起動設定
|
||||||
|
|
||||||
|
保全先は `.deployment-backups/release-v0.2.1-20261101/`。親ディレクトリは0700。
|
||||||
|
|
||||||
|
- `cutover/data`・`cutover/data2`:19:59:53 JSTに確定した切替直前の整合コピー。
|
||||||
|
- `config/`:切替前のCompose、`.env.release`、秘密値を含む `.env`。秘密設定は0600で保持し、Gitへ入れない。
|
||||||
|
- アプリ2台とgatewayを停止し、最終差分約6.22GBを同期。DBバイト一致とfilesystem sync後に新版を起動した。
|
||||||
|
- 未変更ファイルのhardlink共有はバックアップ間のみ。本番とのhardlink共有はない。既存バックアップは削除していない。
|
||||||
|
- 検証コピー削除後・本番切替後のホスト空き容量は約28GB。バックアップ世代の整理は別途判断する。
|
||||||
|
|
||||||
|
Git無視対象 `.env.release` の `PAGESWIKI_IMAGE_TAG` を `v0.2.1` に更新した。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose --env-file .env --env-file .env.release \
|
||||||
|
-f docker-compose.yml -f docker-compose.registry.yml \
|
||||||
|
up -d --no-build --no-deps app app2 adaptor-gateway excalidraw-viewer
|
||||||
|
```
|
||||||
|
|
||||||
|
ローカル互換タグ `pageswiki-app:latest`、`pageswiki-adaptor-gateway:latest`、
|
||||||
|
`pageswiki-excalidraw-viewer:latest` もv0.2.1へ合わせた。registryのlatestは更新していない。
|
||||||
|
|
||||||
|
## 復旧点と後続監視
|
||||||
|
|
||||||
|
旧版v0.2.0は、上記3種類のローカルrepositoryの `rollback-before-v0.2.1-20261101` タグで保持した。
|
||||||
|
v0.2.0のregistryタグも利用できる。このPATCH版にschema変更はないが、復旧前には切替後の状態と互換性を確認する。
|
||||||
|
イメージ切替とデータ復元は別操作であり、バックアップへデータを戻すと切替後の書込みが失われる。
|
||||||
|
データ復元は別途承認・保全の上で行う。schema履歴を削除してcheckを通す回避はしない。
|
||||||
|
|
||||||
|
長時間ロックやI/O障害で保存できなかったログの自動回収、業務完了状態とログの一体commit、
|
||||||
|
リース・HA・終了処理は後続課題として残る。短時間の本番観察は長期負荷試験の代替ではない。
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
# PagesWiki v0.3.0 のCLI OIDC認証と本番反映
|
||||||
|
|
||||||
|
2026-11-01 20:52:08 JST、CLIのブラウザー経由OIDC認証を含むv0.3.0を本番へ反映した。
|
||||||
|
サーバーだけでなく、ホストの `/home/anya/.local/bin/pages` も同じリリースのCLIへ更新した。
|
||||||
|
以前の `Not found or not readable.` は、新CLIが要求する `POST /_/auth/cli/start` を
|
||||||
|
本番v0.2.1が持たず404を返していたためである。
|
||||||
|
|
||||||
|
## 配布物
|
||||||
|
|
||||||
|
- ソースcommit:`60f5fb18817d115a56b424dce2602198ac2c89f3`。
|
||||||
|
- 注釈付きGitタグ:`v0.3.0`。タグobject:`d02116577a79a1396b96c88fbadd7139dd158bd8`。
|
||||||
|
- [ビルド run 16](https://git.anya.jp/anya/wikipages/actions/runs/16):再実行で全工程成功。
|
||||||
|
- [リリース昇格 run 17](https://git.anya.jp/anya/wikipages/actions/runs/17):全工程成功。
|
||||||
|
- 後方互換な認証機能追加なので、SemVerのMINORを更新した。v0.2.1の配布物は変更していない。
|
||||||
|
|
||||||
|
対象はapp、app2、adaptor-gateway、excalidraw-viewer。code-server、Kroki、Mermaidは再作成していない。
|
||||||
|
registry prefixは `git.anya.jp/anya/`。3種類ともSHAタグとリリースタグのmanifest digestが一致し、
|
||||||
|
OCI revisionはソースcommitと一致する。昇格時の再ビルドは行っていない。
|
||||||
|
|
||||||
|
| イメージ | v0.3.0 manifest digest |
|
||||||
|
| --- | --- |
|
||||||
|
| pageswiki-app | `sha256:49e7e5f0fffcefc3ac272a1e2a29308884065d1384f2e5df6d24717b1a4a65f5` |
|
||||||
|
| pageswiki-adaptor-gateway | `sha256:246e2f1150c814679ca01d0f8f8636e006fa70a280cb1ab4e934e2d84fa5aa46` |
|
||||||
|
| pageswiki-excalidraw-viewer | `sha256:a9d992e521dfc2e942dedc2ed0296dc30fd8d0b24d8591bf057cd9f7fe4c612f` |
|
||||||
|
|
||||||
|
## 認証の範囲
|
||||||
|
|
||||||
|
`pages login --oidc` はブラウザー承認を開始し、`--no-browser` は自動起動せずURLを表示する。
|
||||||
|
確認コードを入力し、必要なTOTPを確認した後、CLI専用のBearerセッションを取得する。
|
||||||
|
S256 PKCE、5分の有効期限、単回交換、Domain/origin/ブラウザーへの束縛、CSRF、
|
||||||
|
発行・poll・承認試行の上限を設ける。ブラウザーCookieやOIDC providerのトークンをCLIへ転送しない。
|
||||||
|
通信断で交換結果が不明な場合は自動再送しない。詳細は [遠隔CLI設計](../../design/ja/remote-cli.md) を参照。
|
||||||
|
|
||||||
|
開始APIの404/405/501は、CLI認証未対応または接続先の誤りを示す専用メッセージにした。
|
||||||
|
OIDC無効の403と区別し、未対応サーバーで権限不足と誤解されないようにした。
|
||||||
|
|
||||||
|
## 検証とCI再実行
|
||||||
|
|
||||||
|
- 全Goテストをキャッシュなしで実行し成功。
|
||||||
|
- `go test -race ./internal/store ./internal/server -run 'Test(CLI|RemoteCLI)' -count=3` と全Go vetが成功。
|
||||||
|
- Python CLIの18試験が成功。未対応サーバー・OIDC無効の診断、秘密を出力しないこと、自動再送しないことを含む。
|
||||||
|
- 署名付き模擬OIDC providerでcallbackから承認・単回交換・失効まで検証。
|
||||||
|
- Python CLIのHTTP統合試験で認証後のAPI利用を検証。
|
||||||
|
- 承認画面はChromiumの1440px/390pxで入力・承認・保存を確認し、モバイル画像も目視確認した。
|
||||||
|
|
||||||
|
最初のCIは、既存のカレンダー、検索、匿名公開、outboxテストでDB初期化/処理の
|
||||||
|
`context deadline exceeded` により失敗した。大容量コピーと時間帯が重なっておりI/O競合が疑われるが、原因を断定しない。
|
||||||
|
コピー完了後、同じcommitを再実行して全工程が成功した。タイムアウト延長・テスト除外・実装変更で通したものではない。
|
||||||
|
今後は大容量保全とCIを重ねず、runnerの資源分離・負荷計測を継続課題とする。
|
||||||
|
|
||||||
|
## スキーマ移行と本番確認
|
||||||
|
|
||||||
|
追加は `cli-auth` version 1の要求管理テーブル・索引とmigration履歴。
|
||||||
|
既存の文書・カレンダー・タスクの正本変換や既存行の削除はない。
|
||||||
|
v0.2.1切替直前の整合バックアップから独立コピーを2系統作り、CIイメージで起動した。
|
||||||
|
network none、CPU 2、メモリ2GiB、コピーだけのDR設定でworkers無効、外部enroll引数なしとした。
|
||||||
|
移行前はcli-authのみpending、起動後は10コンポーネントすべてcurrentで、health成功・起動エラー0件だった。
|
||||||
|
|
||||||
|
本番切替後も、4サービスのrevision一致・再起動0回、公開HTTPSのhealth/ログイン200、
|
||||||
|
アプリ2台とgateway・Excalidrawのhealth成功、2台とも10コンポーネントcurrentを確認した。
|
||||||
|
更新したホストCLIとリポジトリの実行ファイルはバイト一致した。
|
||||||
|
|
||||||
|
実ユーザーの資格情報を使わず、公開HTTPSで次を確認した。
|
||||||
|
|
||||||
|
- CLI開始APIが200を返し、有効期限300秒・poll間隔5秒の要求を作成する。
|
||||||
|
- 要求の承認入口が200でOIDCログインリンクを表示し、no-storeを返す。
|
||||||
|
- 未承認要求のtoken APIは `authorization_pending` を返し、セッションを発行しない。
|
||||||
|
|
||||||
|
この確認で作成した未承認要求1件は5分で失効する。確認コード・device code・verifierは出力/保存していない。
|
||||||
|
実OIDC providerでの本人ログインと最終承認は利用者による確認が残る。
|
||||||
|
外部から取り込んだカレンダーの内容は開いていない。
|
||||||
|
|
||||||
|
切替後の観察で、20:54:03 JSTに `city.reconcile` のexecute段階でSQLITE_BUSY(5)を1件検出した。
|
||||||
|
当該ジョブは2回目の自動再試行でsucceededとなった。認証処理や開始/進捗/完了ログ保存の失敗ではない。
|
||||||
|
panic・fatal・再起動はなく、イベントログ保存失敗も0件だった。
|
||||||
|
City再構成の書込競合と取消確認を含むexecute経路の切り分けは後続課題として残す。
|
||||||
|
|
||||||
|
## 保全と復旧
|
||||||
|
|
||||||
|
保全先は `.deployment-backups/release-v0.3.0-20261101/`。親ディレクトリは0700。
|
||||||
|
`cutover/data`・`cutover/data2` は20:52:02 JSTに確定した切替前の整合コピー。
|
||||||
|
20:51:28 JSTに停止を開始し、約6.22GBの最終同期・DBバイト一致・filesystem sync後、20:52:08 JSTに切替を完了した。
|
||||||
|
`config/` に旧Compose、`.env.release`、0600の `.env`、旧ホストCLIを保持した。
|
||||||
|
本番とのhardlink共有はない。既存バックアップは保持し、検証専用コピーだけを削除した。
|
||||||
|
切替後のホスト空き容量は約21GB。世代整理・別媒体への退避は自動削除せず別途判断する。
|
||||||
|
|
||||||
|
Git無視対象 `.env.release` は `PAGESWIKI_IMAGE_TAG=v0.3.0`。
|
||||||
|
通常の `.env` とregistry overlayを併用し、`up --no-build` で起動する。
|
||||||
|
ローカル3イメージのlatest互換タグもv0.3.0へ揃えた。registryのlatestは更新していない。
|
||||||
|
|
||||||
|
旧v0.2.1は各ローカルrepositoryの `rollback-before-v0.3.0-20261101` タグで保持した。
|
||||||
|
隔離コピーに対する旧版のschema checkは `cli-auth: unknown` で終了コード1となった。
|
||||||
|
**旧イメージへの差替えだけを検証済みの復旧手順とは扱わない。**
|
||||||
|
復旧前に書込みを止め、切替後データも保全し、追加component・発行済みセッションとの互換性を確認する。
|
||||||
|
schema履歴を消してcheckを通さない。バックアップ復元は切替後の書込みを失うため、別途承認と復旧範囲の確認を必要とする。
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# PagesWiki v0.4.0 のCLI言語編集と本番反映
|
||||||
|
|
||||||
|
2026-11-01 21:48:37 JST、CLIの言語自動選択・新規言語版編集と、OIDC承認時の追加ローカルTOTP省略を本番へ反映した。
|
||||||
|
ホストの `/home/anya/.local/bin/pages` も同じリリースへ更新した。接続設定と保存済みセッションは変更していない。
|
||||||
|
|
||||||
|
## 配布物
|
||||||
|
|
||||||
|
- ソースcommit:`93f4ecb8f4be8a798e22c4816663fc6754cc1951`。
|
||||||
|
- 注釈付きGitタグ:`v0.4.0`。タグobject:`2f7a20f6deeb80f3e998426aaf7d3f2546eba7d8`。
|
||||||
|
- [ビルド run 18](https://git.anya.jp/anya/wikipages/actions/runs/18):初回で全工程成功。
|
||||||
|
- [リリース昇格 run 19](https://git.anya.jp/anya/wikipages/actions/runs/19):全工程成功。
|
||||||
|
- 公開CLIの機能追加を含むため、SemVerのMINORを更新した。公開済みタグは変更していない。
|
||||||
|
|
||||||
|
対象はapp、app2、adaptor-gateway、excalidraw-viewer。code-server、Kroki、Mermaidは再作成していない。
|
||||||
|
registry prefixは `git.anya.jp/anya/`。SHAタグとリリースタグのmanifest digest・image IDが一致し、
|
||||||
|
OCI revisionはソースcommitと一致する。リリース昇格時の再ビルドはない。
|
||||||
|
|
||||||
|
| イメージ | v0.4.0 manifest digest |
|
||||||
|
| --- | --- |
|
||||||
|
| pageswiki-app | `sha256:d3c4fd22e1530bf85c1ec0451b731e57ede616a8f070922d517696957f3368ef` |
|
||||||
|
| pageswiki-adaptor-gateway | `sha256:08f796af86d60b851c80ad88acc1141d1240398f7b83697fe907e9b28b49bca1` |
|
||||||
|
| pageswiki-excalidraw-viewer | `sha256:adfdb46a4c4329366f1a66b918f3d5ba06b767723770b3f6e180566224193552` |
|
||||||
|
|
||||||
|
## 利用方法と互換性
|
||||||
|
|
||||||
|
OIDC経由のCLI承認では、ローカルTOTPが登録済みでも再入力を要求しない。
|
||||||
|
プロバイダー側の認証ポリシー、確認コード、明示承認、CSRF、PKCE、単回交換は維持する。
|
||||||
|
OIDC成功だけでMFA levelを加算せず、パスワードログイン時のローカルTOTP要件も変更しない。
|
||||||
|
|
||||||
|
新規CLIプロファイルの言語は `auto`。既存プロファイルの `und` 等は維持するため、必要に応じて変更する。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages configure --lang auto
|
||||||
|
pages edit /対象のパス
|
||||||
|
# 一時指定、または明示的な言語版の作成
|
||||||
|
pages edit /対象のパス --lang auto
|
||||||
|
pages edit /対象のパス --lang en
|
||||||
|
```
|
||||||
|
|
||||||
|
`auto` は通常表示されるRevisionの言語を確定し、その言語の現在headを編集する。
|
||||||
|
明示言語のheadがない場合は既存内容を下書きとし、空のCAS基点で最初のRevisionを作成する。
|
||||||
|
元の言語版は変更せず、無変更終了では何も作らない。同時作成や更新は409で停止し、ローカル原稿を保持する。
|
||||||
|
新規Path/Page作成・自動翻訳は含まない。[CLI設計](../../design/ja/remote-cli.md)を参照。
|
||||||
|
|
||||||
|
## 検証
|
||||||
|
|
||||||
|
- 全Goテスト(キャッシュなし)、全Go vet、CLI関連store/serverのrace検査、Python単体22件が成功。
|
||||||
|
- 実HTTPハンドラと合成データで、auto編集、新規言語版、元言語保持、競合、失効、readonlyの書込拒否を確認。
|
||||||
|
- 模擬OIDC providerとローカルTOTP有効の合成アカウントで、追加TOTPなしの承認・交換を確認。
|
||||||
|
- Chromiumで1440px/390pxの承認画面と既存Cookieログインを確認。
|
||||||
|
- CIのテスト・3イメージのビルド・push・リリース昇格がすべて成功。
|
||||||
|
- 本番4サービスのrevision一致・再起動0回・health成功。公開HTTPSのhealth/ログインも200。
|
||||||
|
- 更新前後とも両インスタンスのmanaged schema 10コンポーネントがcurrent。今回のschema変更はない。
|
||||||
|
- イメージ内、リポジトリ、ホストPATH上のCLIが同じSHA-256。承認テンプレートに追加TOTP欄がないことも確認。
|
||||||
|
- 起動後の初期観察では、4サービスにpanic/fatal・DB lock・ジョブ失敗・errorログはなかった。
|
||||||
|
|
||||||
|
公開HTTPSでCLI開始→承認入口→未承認token交換の `authorization_pending` を確認した。
|
||||||
|
要求は1件だけ作成し、コード・verifier・device codeは表示/保存せず、セッションは発行していない。要求は5分で失効する。
|
||||||
|
実ユーザーの資格情報による最終承認・文書編集は行っていない。外部取り込みカレンダーの内容も開いていない。
|
||||||
|
|
||||||
|
## 保全と復旧
|
||||||
|
|
||||||
|
保全先は `.deployment-backups/release-v0.4.0-20261101/`、親ディレクトリは0700。
|
||||||
|
`config/` に旧Compose、`.env.release`、0600の `.env`、旧ホストCLIを保持した。
|
||||||
|
`cutover/data`・`cutover/data2` は21:48:21 JSTに最終同期を完了した停止時整合バックアップ。
|
||||||
|
21:47:30 JSTに停止を開始し、チェックサム比較による同期、DB関連ファイルのバイト一致、filesystem sync後に起動した。
|
||||||
|
対象4サービスの停止開始から再起動完了までは約67秒。
|
||||||
|
|
||||||
|
容量を抑えるため、前回バックアップの未変更ファイルだけをrsyncのlink-destで共有した。
|
||||||
|
本番データとのハードリンク共有はない。DBは別inodeであり、最終同期もin-place更新を使用していない。
|
||||||
|
バックアップ世代は不変として扱い、共有ファイルを直接編集しない。既存バックアップは削除していない。
|
||||||
|
切替後の空き容量は約14GB。世代の別媒体への退避・整理は後続の運用課題とする。
|
||||||
|
|
||||||
|
Git無視対象 `.env.release` は `PAGESWIKI_IMAGE_TAG=v0.4.0`。
|
||||||
|
通常の `.env` とregistry overlayを併用し、`up --no-build --no-deps` で対象4サービスだけを更新した。
|
||||||
|
ローカル3イメージのlatest互換タグもv0.4.0へ揃えた。registryのlatestは更新していない。
|
||||||
|
|
||||||
|
旧v0.3.0は各ローカルrepositoryの `rollback-before-v0.4.0-20261101` で保持した。
|
||||||
|
旧イメージの読み取り専用schema checkは、両退避DBで全コンポーネントcurrentとなった。
|
||||||
|
これはmanaged schemaの互換確認であり、復旧起動全体の実地試験ではない。
|
||||||
|
復旧時は進行中の編集・CLI承認を考慮し、書込みを停止して切替後データも保全したうえで、旧タグと旧CLIを使用する。
|
||||||
|
追加TOTP要件は旧版に戻る。DBバックアップの復元は切替後の書込みを失うため、自動で行わず別途承認を必要とする。
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# PagesWiki v0.5.0 のタスク管理と個人アドレス帳の本番反映
|
||||||
|
|
||||||
|
2026-11-01 23:15:44 JST、タスク作成API、作業時間記録、達成度レポート、日次メール設定、個人アドレス帳、トップ検索の作成コマンドを本番へ反映した。ホストの `/home/anya/.local/bin/pages` も更新した。既存CLIの接続設定と保存済みセッションは変更していない。
|
||||||
|
|
||||||
|
## 配布物
|
||||||
|
|
||||||
|
- ソースcommit:`8988e5a2f8436708a5a591ef126261629d662f32`。
|
||||||
|
- 注釈付きGitタグ:`v0.5.0`。タグobject:`008b146b2f4fac75c76ad3e7606552e1ae12bc51`。
|
||||||
|
- [ビルド run 21](https://git.anya.jp/anya/wikipages/actions/runs/21):再実行のjob 23で全工程成功。
|
||||||
|
- [リリース昇格 run 22](https://git.anya.jp/anya/wikipages/actions/runs/22):全工程成功。
|
||||||
|
- 公開API・CLIの追加機能に対し、SemVerのMINORを更新した。既存のリリースタグは変更していない。
|
||||||
|
|
||||||
|
対象はapp、app2、adaptor-gateway、excalidraw-viewer。code-server、Kroki、Mermaidは再作成していない。
|
||||||
|
registry prefixは `git.anya.jp/anya/`。SHAタグとリリースタグのimage ID・manifest digestが一致し、linux/amd64のOCI revisionも上記commitと一致する。リリース昇格時の再ビルドはない。
|
||||||
|
|
||||||
|
| イメージ | v0.5.0 manifest digest |
|
||||||
|
| --- | --- |
|
||||||
|
| pageswiki-app | `sha256:6e326d06244878af1f5eb9a562893136a2c6b5414b53f8edd477334f07f092d6` |
|
||||||
|
| pageswiki-adaptor-gateway | `sha256:097bd78daa97fd5d4de2aff1b58f93397176672421b4b1459a86408ab6f3e3f3` |
|
||||||
|
| pageswiki-excalidraw-viewer | `sha256:d8bbd27d3ef15a5fc41e87786b6074116fbda98375cccce341693e716325fa29` |
|
||||||
|
|
||||||
|
イメージ内、リポジトリ、ホストPATH上のCLIのSHA-256は、いずれも `d423d1a38cb931880e78e419188083592d9163cdd958ace86f58849d141c4f41`。
|
||||||
|
|
||||||
|
## 利用開始と機能範囲
|
||||||
|
|
||||||
|
| 入口 | 内容 |
|
||||||
|
| --- | --- |
|
||||||
|
| `/v/plan/tasks/settings` | プロジェクト・担当者・見積・複雑度・各日付の既定値、日次メールの時刻設定 |
|
||||||
|
| `/v/plan/tasks/report` | 日別の完了数・ポイントのヒートマップ、タスク別作業時間、Pomodoro時間 |
|
||||||
|
| `/v/plan/contacts` | 本人専用アドレス帳、複数メール・電話、検索、削除・復元、vCard入出力 |
|
||||||
|
| `pages task` | 作成・計画・完了、メールからの作成、作業開始・終了、レポート、設定 |
|
||||||
|
| `pages contacts` | 検索、neomuttの宛先補完、vCard入出力 |
|
||||||
|
| トップ検索 | `add task` と `add cal`、プロジェクト・カレンダー候補、明示確認後の作成 |
|
||||||
|
|
||||||
|
日次メールは既定で無効。本人の有効化、本人のメール登録、管理者のSMTP設定が必要。導入作業では実メールを送信していない。担当者UUIDは計画上の注記であり、所有権移転・閲覧権限付与ではない。
|
||||||
|
|
||||||
|
連絡先は個人アドレス帳として実装した。共有アドレス帳、CardDAV提供・外部双方向同期は未実装。作業記録の事後修正、配信結果不明時の手動再送、連絡先の履歴復元UI等も後続範囲とする。詳細と制約は [タスクと連絡先の設計](../../design/ja/task-productivity-contacts.md)、コマンド例は [neomuttとタスクCLI](../neomutt-tasks.md) を参照。
|
||||||
|
|
||||||
|
## 検証
|
||||||
|
|
||||||
|
- ローカルの全Goテスト、全Go vet、CLIのPython単体26件、検索コマンド解析テスト2件が成功。
|
||||||
|
- 最終版でタスク作成・作業記録・日次配信・予定作成・CLI実HTTP・連絡先のrace検査が成功。managed schemaの反復適用・readonly・旧完了タスクの移行も検査した。
|
||||||
|
- 合成データの実HTTPでCLIの作成、開始、終了、更新、完了、集計、連絡先入出力を検証した。SMTPは模擬サーバーで日本語本文・MIMEを検証した。
|
||||||
|
- Chromiumで新規5画面のデスクトップ/スマートフォン計10ケースと、既存タスク画面4サイズを検証した。最終のサブタスク既定値修正も両画面幅で再確認した。
|
||||||
|
- 本番4サービスが同じソースrevisionで稼働し、再起動回数は0。healthcheckを持つapp・Excalidrawはhealthy、appとapp2のローカルhealthは200、公開HTTPSのhealth・ログインは200。
|
||||||
|
- 本番の新規API4種は匿名要求を401・no-storeで拒否。設定・レポート・連絡先ページはログインへ303。新規・更新JS/CSS計8ファイルは公開HTTPSの内容とリリースソースのSHA-256が一致した。
|
||||||
|
- 両インスタンスのmanaged schemaはcontactsとtask-productivityを含む12コンポーネントすべてcurrent。起動後の初期観察では、4サービスにpanic/fatal・DB lock・ジョブ失敗・errorログはなかった。
|
||||||
|
|
||||||
|
本番の実ユーザー資格情報を使った新規タスク・連絡先の作成は行っていない。外部取り込みカレンダーの内容も開いていない。バックアップは内容を解釈しないファイル保全である。
|
||||||
|
|
||||||
|
### CI再実行の経緯
|
||||||
|
|
||||||
|
初回のjob 22では、既存の `TestSaveRevisionFreezesEmbeddedAssetHeads` が `db.Open` の段階で `initialize SQLite connection: context deadline exceeded` となった(8秒)。アセット機能のassertionへ到達する前の失敗で、新機能を含むserverパッケージは成功していた。
|
||||||
|
|
||||||
|
同一テストをローカルで20回連続実行して成功。同一commit・同一テスト条件のまま全CIを再実行し、job 23では全テストとビルド・pushが成功した。テストの削除・スキップ、DB期限の緩和はしていない。
|
||||||
|
|
||||||
|
後続のCI改善では、SQLiteの初期化遅延を計測し、テスト用ストレージとパッケージ並列度、BuildKitの永続キャッシュを見直す。一時的なI/O競合は候補だが、このログだけで原因を断定しない。
|
||||||
|
|
||||||
|
## 保全と復旧
|
||||||
|
|
||||||
|
保全先は `.deployment-backups/release-v0.5.0-20261101/`、親ディレクトリは0700。
|
||||||
|
`config/` に旧Compose、旧 `.env.release`、0600の `.env`、旧ホストCLIを保持した。
|
||||||
|
|
||||||
|
23:15:14 JSTに対象4サービスの停止を開始した。停止確認後に `cutover/data` と `cutover/data2` をチェックサム比較で最終同期し、DB関連ファイルのバイト一致・別inode・filesystem syncを確認して、23:15:37 JSTにバックアップ検証を終えた。23:15:44 JSTに再起動が完了した。停止開始から再起動完了までは約30秒。
|
||||||
|
|
||||||
|
変更されていないファイルは前回の不変バックアップをrsyncのlink-destとして共有した。本番ファイルとのハードリンク共有やin-place更新は行っていない。DBは事前コピーせず、停止後に一度だけコピーして一時的な必要容量を抑えた。共有されたバックアップファイルを直接編集してはいけない。
|
||||||
|
|
||||||
|
旧v0.4.0イメージを、各ローカルrepositoryの `rollback-before-v0.5.0-20261101` タグで保持した。旧版による読み取り専用schema checkでは、保全した両DBのmanaged schema 10コンポーネントがcurrent。これはschemaの検査であり、復旧起動全体の実地試験ではない。
|
||||||
|
|
||||||
|
今回の更新ではDBに新しいコンポーネントを追加している。旧イメージへの交換だけで安全に切り戻せるとは扱わない。復旧が必要な場合は書込みを停止し、切替後データも保全してから旧版との互換性を確認する。バックアップの復元は切替後の書込みを失うため、自動で実行しない。
|
||||||
|
|
||||||
|
Git無視対象 `.env.release` は `PAGESWIKI_IMAGE_TAG=v0.5.0`。通常の `.env` とregistry overlayを併用し、`up --no-build --no-deps` で対象4サービスだけを更新した。ローカルlatest互換タグはv0.5.0へ揃え、registryのlatestは変更していない。
|
||||||
|
|
||||||
|
切替後の空き容量は約7.3GB。既存バックアップ・旧イメージは削除していない。別媒体への保全確認と世代整理を、次の大容量操作より先に実施する。
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# PagesWiki v0.6.0 のCardDAV本番反映とバックアップ整理
|
||||||
|
|
||||||
|
2026-11-02 09:04:17 JST、個人CardDAV、連絡先の履歴確認・復元、アドレス帳一括exportを本番2系統へ反映した。拡張機能は `organizer.contacts 0.2.0`。利用入口は `/v/plan/contacts`、CardDAVは `/_/api/v1/carddav/`。接続手順と限定対応範囲は[CardDAV運用資料](../carddav-contacts.md)を参照する。
|
||||||
|
|
||||||
|
## 配布物
|
||||||
|
|
||||||
|
- ソースcommit:`19e12f96a840bdeba2b378644918e333d2e688fe`。
|
||||||
|
- 注釈付きGitタグ:`v0.6.0`。タグobject:`93816c53d68449c7a604bbfed8c750362ed6a83e`。
|
||||||
|
- [ビルド run 23](https://git.anya.jp/anya/wikipages/actions/runs/23):再実行job 26でテスト・3イメージのビルド・push・後処理がすべて成功。
|
||||||
|
- [リリース昇格 run 24](https://git.anya.jp/anya/wikipages/actions/runs/24):job 27が成功。ビルド済みのSHAタグを再ビルドせず昇格した。
|
||||||
|
- 後方互換なAPI・機能追加に対してSemVerのMINORを更新した。既存タグは変更していない。
|
||||||
|
|
||||||
|
registry prefixは `git.anya.jp/anya/`。本番のapp、app2、adaptor-gateway、excalidraw-viewerは同じソースrevisionで稼働する。code-server、Kroki、Mermaidは再作成していない。CLIソースの変更はなく、ホストCLIの置換もしていない。
|
||||||
|
|
||||||
|
| イメージ | v0.6.0 manifest digest |
|
||||||
|
| --- | --- |
|
||||||
|
| pageswiki-app | `sha256:21eefdbe838433db9b6abb20cd8467861e4e87ca894c8db90cd9292d69d0f868` |
|
||||||
|
| pageswiki-adaptor-gateway | `sha256:61ab1563ed1188ee710924d491670b148f7b9cb100ca74515fd94d270cb7a0af` |
|
||||||
|
| pageswiki-excalidraw-viewer | `sha256:e3a9fa82eee4f4f55a2eb271c142d2e069176b6acb3422899e9b6594d573b33c` |
|
||||||
|
|
||||||
|
Git無視対象 `.env.release` は `PAGESWIKI_IMAGE_TAG=v0.6.0`。通常の `.env` とregistry overlayを併用し、`up --no-build --no-deps` で対象4サービスのみ更新した。ローカルlatest互換タグはv0.6.0へ揃えた。registryのlatestは変更していない。
|
||||||
|
|
||||||
|
## バックアップの整理
|
||||||
|
|
||||||
|
ユーザーの削除指示を受け、次の旧世代だけを削除した。すべて `.deployment-backups/` 直下の通常ディレクトリであることと、対象path・filesystemを確認してから削除した。
|
||||||
|
|
||||||
|
- `prod-ux-20261101/`
|
||||||
|
- `release-v0.2.0-20261101/`
|
||||||
|
- `release-v0.2.1-20261101/`
|
||||||
|
- `release-v0.3.0-20261101/`
|
||||||
|
|
||||||
|
v0.4.0・v0.5.0切替前バックアップ、小規模な開発保全、rsync.log・rsync2.log、稼働データ、旧イメージは保持した。Docker全体のpruneは実行していない。
|
||||||
|
|
||||||
|
空き容量は作業開始時の約7.5 GBから、旧世代削除直後に約65 GBへ増加した。新しい復旧点とイメージを保管し、今回のリハーサル専用コピーを削除した後は約59 GBとなった。過去世代間で共有されるハードリンクがあるため、各ディレクトリの見かけの容量の合計と回収量は一致しない。
|
||||||
|
|
||||||
|
## 移行と保全
|
||||||
|
|
||||||
|
保全先は `.deployment-backups/release-v0.6.0-20261102/`。親ディレクトリは0700、保存した `.env` は0600。`config/` に旧Compose、旧 `.env.release`、`.env`、旧ホストCLIを保持する。`cutover/data` と `cutover/data2` が切替直前の整合バックアップである。
|
||||||
|
|
||||||
|
事前の読み取り専用チェックでは、本番2系統ともcontactsだけがv1からv2への更新待ちで、他の管理対象はcurrentだった。変更前のバックアップから独立したコピー2系統を作り、検証済みSHAイメージを `--network none`、DR設定の `workers_enabled=false` で起動した。両系統のhealthと管理対象12コンポーネントのschema checkが成功した。このコピーは本番に使用せず、検証コンテナ停止・削除後に破棄した。
|
||||||
|
|
||||||
|
本番切替前には、稼働イメージがv0.5.0であること、Composeと `.env` が保全時から変わっていないこと、新イメージのrevision、空き容量を確認した。
|
||||||
|
|
||||||
|
| 時刻 JST | 操作 |
|
||||||
|
| --- | --- |
|
||||||
|
| 09:03:41 | 対象4サービスの停止開始 |
|
||||||
|
| 09:04:11 | 停止確認後の最終バックアップ検証完了 |
|
||||||
|
| 09:04:17 | v0.6.0の再起動完了 |
|
||||||
|
|
||||||
|
停止開始から再起動完了までは約36秒。最終同期はチェックサム比較を使い、DB・WAL・SHM等のバイト一致、稼働ファイルと異なるinode、filesystem syncを確認した。変更のないファイルは過去の不変バックアップをrsyncのlink-destとして共有するが、本番ファイルとはハードリンク共有しない。in-place更新も使用しない。
|
||||||
|
|
||||||
|
旧v0.5.0イメージには各ローカルrepositoryで `rollback-before-v0.6.0-20261102` を付けて保持した。切替直前バックアップ2系統に対する旧版の読み取り専用schema checkでは、contacts v1を含む管理対象12コンポーネントがcurrentだった。これは復旧起動全体の実地試験ではない。
|
||||||
|
|
||||||
|
本番はcontacts v2へ移行済みであり、旧イメージへの交換だけを安全なrollbackとは扱わない。復旧時は書込みを停止して切替後データも保全し、互換性・書込み損失を確認する。バックアップ復元を自動実行しない。CardDAVのDBを過去へ戻す復旧では、公開前のepoch更新とクライアント再照合も必要になる。
|
||||||
|
|
||||||
|
## 検証結果
|
||||||
|
|
||||||
|
- リリース前の全Goテストをローカルで再実行して成功。リリースツールのNodeテストも成功。
|
||||||
|
- Giteaの全テスト、3イメージのビルド・公開、リリース昇格が成功。
|
||||||
|
- 本番4サービスのソースrevision一致、再起動0回。healthcheckを持つappとExcalidrawはhealthy、app2もコンテナ内healthが200。
|
||||||
|
- 両本番DBはcontacts v2を含む管理対象12コンポーネントすべてcurrent。
|
||||||
|
- 公開HTTPSの `/health` とログイン入口は200。連絡先画面の匿名アクセスは303、CardDAVと連絡先の一覧・一括export APIは401、well-known discoveryは307。
|
||||||
|
- 公開HTTPSで配信されたcontacts.js、contact-history.js、task-dav-settings.js、contacts.css、dav-settings.cssのSHA-256がリリースソースと一致。
|
||||||
|
- 初期観察では4サービスのログにpanic、fatal、DB lock、job failed、scheduler claim failed、errorレベルの該当なし。
|
||||||
|
|
||||||
|
認証済みの実ユーザーで本番連絡先を作成・更新する試験は行っていない。CardDAVの往復同期とWeb操作は前段の合成データ試験で確認した。外部取り込みカレンダーの内容は開いておらず、保全は内容を解釈しないファイルコピーである。
|
||||||
|
|
||||||
|
### CI再実行
|
||||||
|
|
||||||
|
初回job 25は既存の `TestCityAutoPlanSameSpotNameInDifferentStreets` で `initialize SQLite connection: context deadline exceeded` となった。configFixtureのDB接続初期化段階であり、Cityのassertionに入る前の失敗だった。
|
||||||
|
|
||||||
|
同じテストをローカルで20回反復して成功。同一commit・同一テスト条件のままCIを1回再実行し、job 26で全工程が成功した。テストの削除・スキップや、DBの期限延長はしていない。
|
||||||
|
|
||||||
|
v0.5.0のCIでも別テストのSQLite初期化時に同種の症状が出ている。後続のCI改善では、テスト一時領域のI/O計測、tmpfs利用の評価、パッケージ並列度、BuildKitキャッシュを検討する。このログだけでストレージを原因と断定しない。
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# PagesWiki v0.7.0 のオーガナイザー本番反映
|
||||||
|
|
||||||
|
2026-11-04 00:23:30 JST、オーガナイザーの共通ナビゲーション、個人設定、ウィジェット形式のダッシュボードを本番2系統へ反映した。ダッシュボードは `/v/plan/dashboard`、個人設定は `/-/sys/config?panel=organizer`、連絡先は `/v/plan/contacts`。仕様と後続範囲は[設計書](../../design/ja/organizer-dashboard.md)を参照する。
|
||||||
|
|
||||||
|
## 配布物
|
||||||
|
|
||||||
|
- ソースcommit:`6ba30bc9f4ae4a8b53b909ebe6597eb8f52fa0ef`。
|
||||||
|
- 注釈付きGitタグ:`v0.7.0`。タグobject:`25f59e33bf90699426e9515fc62efa262268385d`。
|
||||||
|
- [ビルド run 25](https://git.anya.jp/anya/wikipages/actions/runs/25):job 28でテスト、3イメージのビルド・pushが成功。
|
||||||
|
- [リリース run 26](https://git.anya.jp/anya/wikipages/actions/runs/26):job 29で既存SHAイメージの昇格が成功。再ビルドしていない。
|
||||||
|
- 後方互換な機能追加としてSemVerのMINORを更新。既存リリースタグは変更していない。
|
||||||
|
|
||||||
|
registry prefixは `git.anya.jp/anya/`。
|
||||||
|
|
||||||
|
| イメージ | v0.7.0 manifest digest |
|
||||||
|
| --- | --- |
|
||||||
|
| pageswiki-app | `sha256:30ebc4e568087d791f7381313a93b963e18c81b7f51a93923b3d874c8a1b90b8` |
|
||||||
|
| pageswiki-adaptor-gateway | `sha256:0373dd70c0c8097ccccd61302c83b48502e47a8fd256335bb44297afd6ac6eca` |
|
||||||
|
| pageswiki-excalidraw-viewer | `sha256:381f31eb6754743ee8116b11230f522e0c726345cdb12f4f21f050fb13b64105` |
|
||||||
|
|
||||||
|
`.env.release` を `PAGESWIKI_IMAGE_TAG=v0.7.0` に更新し、通常の `.env` とregistry overlayを併用して `up --no-build --no-deps` でapp、app2、adaptor-gateway、excalidraw-viewerのみ再作成した。ローカルlatest互換タグも同版へ揃えた。registryのlatest、code-server、Kroki、Mermaid、ホストCLIは変更していない。
|
||||||
|
|
||||||
|
## 移行とバックアップ
|
||||||
|
|
||||||
|
今回の管理対象スキーマ変更は `task-productivity` v1からv2への更新で、個人別配置を保存する `organizer_dashboard_layouts` を追加する。他の管理対象コンポーネントは変更なし。
|
||||||
|
|
||||||
|
独立した旧バックアップのコピー2系統を、実際のリリースイメージで起動した。ネットワークは `none`、DR設定は `workers_enabled=false` とし、外部連携とバックグラウンド処理を無効化した。両系統のhealthと管理対象12コンポーネントのschema checkが成功した。リハーサル専用コピーとコンテナは検証後に削除した。
|
||||||
|
|
||||||
|
保全先は `.deployment-backups/release-v0.7.0-20261104/`。親ディレクトリは0700、保存した `.env` は0600。`config/` に旧Compose、`.env`、旧 `.env.release` を保存し、`cutover/data` と `cutover/data2` に停止時点の整合バックアップを保持する。
|
||||||
|
|
||||||
|
| 時刻 JST | 操作 |
|
||||||
|
| --- | --- |
|
||||||
|
| 00:22:08 | 対象4サービスの停止開始 |
|
||||||
|
| 00:23:23 | 停止後の最終バックアップ検証完了 |
|
||||||
|
| 00:23:30 | v0.7.0の再起動完了 |
|
||||||
|
|
||||||
|
停止開始から再起動完了まで82秒。停止後にチェックサム付きrsyncで最終同期し、差分ゼロ、DB・WAL・SHM等のバイト一致、本番ファイルとは異なるinode、filesystem syncを確認した。変更のないファイルは過去の不変バックアップをlink-destとして共有するが、本番ファイルとはハードリンク共有しない。
|
||||||
|
|
||||||
|
旧v0.6.0の3イメージをローカルタグ `rollback-before-v0.7.0-20261104` で保持した。切替直前バックアップ2系統に旧v0.6.0を用いた読み取り専用schema checkを実行し、task-productivity v1を含め管理対象12コンポーネントがcurrentだった。旧世代バックアップとイメージは削除していない。今回の一時リハーサルコピー削除後の空き容量は約46 GiB。
|
||||||
|
|
||||||
|
本番はtask-productivity v2に移行済みのため、旧イメージへの交換だけを安全なrollbackとは扱わない。復旧時は書込みを止め、切替後データも別途保全し、互換性と書込み損失を確認する。バックアップ復元は自動実行しない。CardDAVデータも過去へ戻す場合は、公開前のepoch更新とクライアント再照合が必要となる。
|
||||||
|
|
||||||
|
## 検証結果
|
||||||
|
|
||||||
|
- ローカルの `go test ./...`、`go vet ./...`、リリースツールのNodeテスト8件、`git diff --check` が成功。
|
||||||
|
- `TestProductivityChromium` のデスクトップ・スマホの10ケースが成功。合成データによる配置保存、実ポインターによるドラッグ・リサイズ等を確認。
|
||||||
|
- Giteaの全Goテスト、3イメージのビルド・公開、リリース昇格が成功。
|
||||||
|
- 本番4サービスのソースrevision一致、再起動0回。appとExcalidrawはhealthy、app2も内部healthが成功。
|
||||||
|
- 本番2系統の管理対象12コンポーネントはすべてcurrent。schema checkの対象外であるlegacy領域の完全性検査を意味するものではない。
|
||||||
|
- 公開HTTPSのhealthとログイン画面は200。ダッシュボードと個人設定の匿名アクセスは303、dashboard・progress APIとCardDAV入口は401。
|
||||||
|
- 公開HTTPSのorganizer-dashboard.js、organizer-settings.js、task-productivity.js、contacts.js、tasks.js、calendar.js、organizer.css、home.cssのSHA-256がソースと一致。
|
||||||
|
- 切替直後の対象4サービスのログでは、panic、fatal、DB lock、job failed、scheduler claim failed、errorレベルの該当件数は0。
|
||||||
|
|
||||||
|
本番の実ユーザーデータを作成・更新するUI試験は行っていない。認証済み操作は合成データのブラウザ・API試験で検証した。外部から取り込んだカレンダー要素にはアクセスしていない。バックアップは内容を解釈しないファイルコピーとして実施した。
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
# neomuttとpages CLIによるタスク管理
|
||||||
|
|
||||||
|
メールからタスクを作り、作業の開始・終了を記録し、個人アドレス帳をneomuttの宛先補完に使う。先に通常の端末でpages-cliを設定してログインする。neomuttの設定やシェル履歴にトークンを書かない。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages configure --origin https://pages.anya.jp --username YOUR_USERNAME
|
||||||
|
pages login --oidc --no-browser
|
||||||
|
pages task --help
|
||||||
|
```
|
||||||
|
|
||||||
|
別接続を使うときは `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) を参照。
|
||||||
@@ -508,7 +508,7 @@ func publish(stage, target string) error {
|
|||||||
func verifyReferences(ctx context.Context, database *sql.DB, seen map[string]bool) error {
|
func verifyReferences(ctx context.Context, database *sql.DB, seen map[string]bool) error {
|
||||||
// Only authoritative references, not derived projection/preview caches. Some
|
// Only authoritative references, not derived projection/preview caches. Some
|
||||||
// installations predate optional modules, hence the explicit table check.
|
// installations predate optional modules, hence the explicit table check.
|
||||||
for _, ref := range [][2]string{{"revisions", "document_hash"}, {"assets", "head_document_hash"}, {"asset_head_history", "document_hash"}, {"organizer_items", "document_hash"}, {"organizer_revisions", "document_hash"}} {
|
for _, ref := range [][2]string{{"revisions", "document_hash"}, {"assets", "head_document_hash"}, {"asset_head_history", "document_hash"}, {"organizer_items", "document_hash"}, {"organizer_revisions", "document_hash"}, {"organizer_contacts", "hash"}, {"organizer_contact_revisions", "hash"}} {
|
||||||
var exists bool
|
var exists bool
|
||||||
if err := database.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)", ref[0]).Scan(&exists); err != nil {
|
if err := database.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)", ref[0]).Scan(&exists); err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -21,7 +21,8 @@ type Manifest struct {
|
|||||||
|
|
||||||
func Catalog() []Manifest {
|
func Catalog() []Manifest {
|
||||||
return []Manifest{
|
return []Manifest{
|
||||||
{ID: "organizer.tasks", APIVersion: 1, Version: "0.11.1", Kind: "tasks", Scope: "domain", NameKey: "tasks.title", DescriptionKey: "tasks.help", Capabilities: []string{"tasks.own.read", "tasks.own.write"}, Events: []string{"organizer.task.changed", "organizer.project.changed"}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+background+index"},
|
{ID: "organizer.contacts", APIVersion: 1, Version: "0.2.0", Kind: "contacts", Scope: "domain", NameKey: "contacts.title", DescriptionKey: "contacts.help", Capabilities: []string{"contacts.own.read", "contacts.own.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||||
|
{ID: "organizer.tasks", APIVersion: 1, Version: "0.12.0", Kind: "tasks", Scope: "domain", NameKey: "tasks.title", DescriptionKey: "tasks.help", Capabilities: []string{"tasks.own.read", "tasks.own.write"}, Events: []string{"organizer.task.changed", "organizer.project.changed", "task.digest.deliver"}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+background+index"},
|
||||||
{ID: "organizer.calendar", APIVersion: 1, Version: "0.2.0", Kind: "calendar", Scope: "domain", NameKey: "calendar.title", DescriptionKey: "calendar.help", Capabilities: []string{"calendar.read", "calendar.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
{ID: "organizer.calendar", APIVersion: 1, Version: "0.2.0", Kind: "calendar", Scope: "domain", NameKey: "calendar.title", DescriptionKey: "calendar.help", Capabilities: []string{"calendar.read", "calendar.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||||
{ID: "content.diary", APIVersion: 1, Version: "0.1.0", Kind: "diary", Scope: "domain", NameKey: "periodical.diary", DescriptionKey: "periodical.diary_help", Capabilities: []string{"path.read", "path.write", "domain.extensions.manage"}, Events: []string{"periodical.registered", "periodical.removed"}, SettingsPanel: "diary", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
{ID: "content.diary", APIVersion: 1, Version: "0.1.0", Kind: "diary", Scope: "domain", NameKey: "periodical.diary", DescriptionKey: "periodical.diary_help", Capabilities: []string{"path.read", "path.write", "domain.extensions.manage"}, Events: []string{"periodical.registered", "periodical.removed"}, SettingsPanel: "diary", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||||
{ID: "content.blog", APIVersion: 1, Version: "0.1.0", Kind: "blog", Scope: "domain", NameKey: "periodical.blog", DescriptionKey: "periodical.blog_help", Capabilities: []string{"path.read", "path.write", "domain.extensions.manage"}, Events: []string{"periodical.registered", "periodical.removed"}, SettingsPanel: "blog", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
{ID: "content.blog", APIVersion: 1, Version: "0.1.0", Kind: "blog", Scope: "domain", NameKey: "periodical.blog", DescriptionKey: "periodical.blog_help", Capabilities: []string{"path.read", "path.write", "domain.extensions.manage"}, Events: []string{"periodical.registered", "periodical.removed"}, SettingsPanel: "blog", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||||
|
|||||||
@@ -0,0 +1,185 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
var cliProofPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`)
|
||||||
|
var cliVerifierPattern = regexp.MustCompile(`^[A-Za-z0-9._~-]{43,128}$`)
|
||||||
|
|
||||||
|
func cliOrigin(r *http.Request) string { return strings.ToLower(externalURL(r, "")) }
|
||||||
|
func cliSecureTransport(r *http.Request) bool {
|
||||||
|
if requestIsHTTPS(r) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
host := r.Host
|
||||||
|
if h, _, err := net.SplitHostPort(host); err == nil {
|
||||||
|
host = h
|
||||||
|
}
|
||||||
|
return host == "localhost" || host == "127.0.0.1" || host == "::1" || host == "[::1]"
|
||||||
|
}
|
||||||
|
func cliVerifyPath(id string) string { return "/_/auth/cli/verify?request=" + url.QueryEscape(id) }
|
||||||
|
func cliConsentCSRF(token, id string) string {
|
||||||
|
sum := sha256.Sum256([]byte("pages-cli-consent:" + token + ":" + id))
|
||||||
|
return base64.RawURLEncoding.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleCLIAuth(w http.ResponseWriter, r *http.Request, action string) {
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||||
|
w.Header().Set("X-Frame-Options", "DENY")
|
||||||
|
if !cliSecureTransport(r) {
|
||||||
|
writeEventJSON(w, 400, map[string]string{"error": "https_required"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
r = r.WithContext(ctx)
|
||||||
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
config, err := s.store.AuthProviderConfig(domain, "oidc")
|
||||||
|
if err != nil || !config.Enabled {
|
||||||
|
writeEventJSON(w, 403, map[string]string{"error": "oidc_disabled"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if action == "cli/verify" {
|
||||||
|
s.verifyCLIAuth(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
w.Header().Set("Allow", "POST")
|
||||||
|
http.Error(w, "method not allowed", 405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||||
|
if err := r.ParseForm(); err != nil {
|
||||||
|
writeEventJSON(w, 400, map[string]string{"error": "invalid_request"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch action {
|
||||||
|
case "cli/start":
|
||||||
|
challenge := r.PostForm.Get("code_challenge")
|
||||||
|
if !cliProofPattern.MatchString(challenge) || r.PostForm.Get("code_challenge_method") != "S256" {
|
||||||
|
writeEventJSON(w, 400, map[string]string{"error": "invalid_request"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, device, code, err := s.store.StartCLIAuth(ctx, domain, cliOrigin(r), challenge)
|
||||||
|
if err != nil {
|
||||||
|
cliAuthError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"device_code": device, "verification_uri": cliVerifyPath(id), "user_code": code[:4] + "-" + code[4:], "expires_in": 300, "interval": 5})
|
||||||
|
case "cli/token":
|
||||||
|
device, verifier := r.PostForm.Get("device_code"), r.PostForm.Get("code_verifier")
|
||||||
|
if !cliProofPattern.MatchString(device) || !cliVerifierPattern.MatchString(verifier) {
|
||||||
|
writeEventJSON(w, 400, map[string]string{"error": "invalid_request"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token, name, expires, err := s.store.ExchangeCLIAuth(ctx, domain, cliOrigin(r), device, verifier)
|
||||||
|
if err != nil {
|
||||||
|
cliAuthError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"access_token": token, "token_type": "Bearer", "username": name, "expires_in": max(1, (expires-time.Now().UnixMilli())/1000)})
|
||||||
|
default:
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func cliAuthError(w http.ResponseWriter, err error) {
|
||||||
|
code, status := "temporarily_unavailable", 503
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, store.ErrCLIPending):
|
||||||
|
code, status = "authorization_pending", 400
|
||||||
|
case errors.Is(err, store.ErrCLISlowDown):
|
||||||
|
code, status = "slow_down", 400
|
||||||
|
case errors.Is(err, store.ErrCLIExpired):
|
||||||
|
code, status = "expired_token", 400
|
||||||
|
case errors.Is(err, store.ErrAccessDenied):
|
||||||
|
code, status = "access_denied", 403
|
||||||
|
case errors.Is(err, store.ErrCLILimit):
|
||||||
|
code, status = "too_many_requests", 429
|
||||||
|
}
|
||||||
|
writeEventJSON(w, status, map[string]string{"error": code})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) verifyCLIAuth(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet && r.Method != http.MethodPost {
|
||||||
|
w.Header().Set("Allow", "GET, POST")
|
||||||
|
http.Error(w, "method not allowed", 405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||||
|
if err := r.ParseForm(); err != nil {
|
||||||
|
http.Error(w, "invalid request", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id := r.URL.Query().Get("request")
|
||||||
|
if r.Method == http.MethodPost {
|
||||||
|
id = r.PostForm.Get("request")
|
||||||
|
}
|
||||||
|
if !cliProofPattern.MatchString(id) {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
grant, err := s.store.CLIAuthRequest(r.Context(), domain, cliOrigin(r), id)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "CLI request expired; restart pages login --oidc", 410)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data := map[string]any{"CLIAuth": true, "CLIOrigin": grant.Origin, "CLIRequest": id}
|
||||||
|
if grant.State != "pending" {
|
||||||
|
data["CLIDone"] = true
|
||||||
|
s.renderAuthPage(w, r, data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if grant.BrowserHash == "" {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
http.Error(w, "OIDC login required", 403)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data["CLILogin"] = "/_/auth/oidc?cli=" + url.QueryEscape(id)
|
||||||
|
s.renderAuthPage(w, r, data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token := s.authTokenFromRequest(r)
|
||||||
|
sum := sha256.Sum256([]byte(token))
|
||||||
|
hash := base64.RawURLEncoding.EncodeToString(sum[:])
|
||||||
|
principal, err := s.store.PrincipalForSession(domain, token)
|
||||||
|
if !strings.HasPrefix(token, "pw_browser_") || hash != grant.BrowserHash || err != nil {
|
||||||
|
http.Error(w, "This request belongs to another browser. Restart CLI login.", 403)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data["CLIUsername"] = principal.Username
|
||||||
|
data["CLICSRF"] = cliConsentCSRF(token, id)
|
||||||
|
if r.Method == http.MethodPost {
|
||||||
|
if !validBrowserMutationOrigin(r) || subtle.ConstantTimeCompare([]byte(r.PostForm.Get("csrf")), []byte(cliConsentCSRF(token, id))) != 1 {
|
||||||
|
http.Error(w, "invalid approval origin or token", 403)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
decision := r.PostForm.Get("decision")
|
||||||
|
if decision != "approve" && decision != "deny" {
|
||||||
|
http.Error(w, "invalid decision", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = s.store.DecideCLIAuth(r.Context(), domain, cliOrigin(r), id, token, r.PostForm.Get("user_code"), r.PostForm.Get("totp"), decision == "approve")
|
||||||
|
if err != nil {
|
||||||
|
data["Error"] = translate(s.getLocale(domain), "auth.cli_invalid")
|
||||||
|
} else {
|
||||||
|
data["CLIDone"] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.renderAuthPage(w, r, data)
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCLIConsentChromium(t *testing.T) {
|
||||||
|
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
|
||||||
|
t.Skip("opt-in Chromium")
|
||||||
|
}
|
||||||
|
for _, width := range []string{"1440", "390"} {
|
||||||
|
t.Run(width, func(t *testing.T) {
|
||||||
|
s, api, domain := configFixture(t)
|
||||||
|
if err := s.store.SetAuthProviderConfig(domain, store.AuthProviderConfig{Kind: "oidc", Enabled: true, Issuer: "https://id.example", ClientID: "client"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
browser, err := s.store.CreateBrowserAuthSession(domain, s.mustCLIPrincipal(t, domain, api), 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var code string
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method == "GET" && r.URL.Path == "/_/auth/cli/verify" {
|
||||||
|
r.AddCookie(&http.Cookie{Name: authCookieName, Value: browser})
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
s.handleAuth(rec, r)
|
||||||
|
for k, values := range rec.Header() {
|
||||||
|
w.Header()[k] = values
|
||||||
|
}
|
||||||
|
s.setAuthCookie(w, r, browser)
|
||||||
|
encoded, _ := json.Marshal(code)
|
||||||
|
script := `<script>(async()=>{try{
|
||||||
|
const form=document.querySelector('.auth-form'); if(!form)throw Error('missing consent form');
|
||||||
|
if(document.documentElement.scrollWidth>innerWidth+2)throw Error('horizontal overflow');
|
||||||
|
const field=form.elements.user_code; if(getComputedStyle(field).backgroundColor==='rgba(0, 0, 0, 0)')throw Error('input theme missing');
|
||||||
|
field.value=` + string(encoded) + `; const data=new URLSearchParams(new FormData(form)); data.set('decision','approve');
|
||||||
|
const response=await fetch(form.action,{method:'POST',body:data}); const html=await response.text();
|
||||||
|
if(!response.ok||html.includes('name="user_code"'))throw Error('approval failed');
|
||||||
|
document.body.dataset.vimReady='true';
|
||||||
|
}catch(e){const p=document.createElement('pre');p.id='error';p.textContent=e.message;document.body.append(p)}})();</script>`
|
||||||
|
w.WriteHeader(rec.Code)
|
||||||
|
_, _ = w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", script+"</body>", 1)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(r.URL.Path, "/_/auth/") {
|
||||||
|
s.withAuthorization(http.HandlerFunc(s.handleAuth)).ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
origin := strings.Replace(server.URL, "127.0.0.1", "localhost", 1)
|
||||||
|
id, _, c, err := s.store.StartCLIAuth(context.Background(), domain, origin, strings.Repeat("c", 43))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
code = c
|
||||||
|
if err := s.store.BindCLIAuth(context.Background(), domain, origin, id, browser); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
screenshot := ""
|
||||||
|
if dir := os.Getenv("PAGESWIKI_BROWSER_ARTIFACTS"); dir != "" {
|
||||||
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
screenshot = filepath.Join(dir, "cli-consent-"+width+".png")
|
||||||
|
}
|
||||||
|
command := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", origin+cliVerifyPath(id), t.TempDir(), screenshot, width, "900")
|
||||||
|
if out, err := command.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("consent browser: %v %s", err, out)
|
||||||
|
}
|
||||||
|
grant, err := s.store.CLIAuthRequest(context.Background(), domain, origin, id)
|
||||||
|
if err != nil || grant.State != "approved" {
|
||||||
|
t.Fatalf("not persisted: %+v %v", grant, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
for lang, entries := range map[string]map[string]string{
|
||||||
|
"ja": {
|
||||||
|
"auth.cli_title": "ターミナルからのアクセスを承認",
|
||||||
|
"auth.cli_warning": "自分で pages login --oidc を開始した場合のみ続行してください。他人から送られたURLや確認コードを使って承認しないでください。有効期限は開始から5分です。",
|
||||||
|
"auth.cli_account": "ログインするアカウント",
|
||||||
|
"auth.cli_access": "このCLIはあなたの現在の権限で閲覧・編集できます。専用セッションは設定画面から失効できます。",
|
||||||
|
"auth.cli_code": "ターミナルに表示された確認コード",
|
||||||
|
"auth.cli_approve": "このCLIを承認する",
|
||||||
|
"auth.cli_deny": "拒否する",
|
||||||
|
"auth.cli_done": "リクエストは処理済みです。ターミナルに戻って結果を確認してください。この画面は閉じられます。",
|
||||||
|
"auth.cli_invalid": "確認コードが正しくないか、リクエストが失効しました。5回失敗した場合はCLIでログインをやり直してください。",
|
||||||
|
},
|
||||||
|
"en": {
|
||||||
|
"auth.cli_title": "Approve terminal access",
|
||||||
|
"auth.cli_warning": "Continue only if you started pages login --oidc yourself. Never approve a URL or code sent by someone else. This request expires five minutes after creation.",
|
||||||
|
"auth.cli_account": "Account",
|
||||||
|
"auth.cli_access": "This CLI can read and edit using your current permissions. Its separate session can be revoked in Settings.",
|
||||||
|
"auth.cli_code": "Confirmation code shown in your terminal",
|
||||||
|
"auth.cli_approve": "Approve this CLI",
|
||||||
|
"auth.cli_deny": "Deny",
|
||||||
|
"auth.cli_done": "This request has been processed. Return to your terminal to check the result. You may close this page.",
|
||||||
|
"auth.cli_invalid": "Incorrect confirmation code or expired request. After five failed attempts, restart login from the CLI.",
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
for key, value := range entries {
|
||||||
|
translations[lang][key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func cliForm(s *Server, path string, form url.Values, cookie, origin string) *httptest.ResponseRecorder {
|
||||||
|
r := httptest.NewRequest("POST", "https://localhost"+path, strings.NewReader(form.Encode()))
|
||||||
|
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
if origin != "" {
|
||||||
|
r.Header.Set("Origin", origin)
|
||||||
|
}
|
||||||
|
if cookie != "" {
|
||||||
|
r.AddCookie(&http.Cookie{Name: authCookieName, Value: cookie})
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
s.withAuthorization(http.HandlerFunc(s.handleAuth)).ServeHTTP(w, r)
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCLIAuthOIDCFlow(t *testing.T) {
|
||||||
|
s, api, domain := configFixture(t)
|
||||||
|
principal := s.mustCLIPrincipal(t, domain, api)
|
||||||
|
// An enrolled local factor must not add a second challenge to OIDC consent.
|
||||||
|
if _, err := s.store.DB.Exec(`INSERT INTO auth_credentials(uuid,principal_uuid,kind,identifier,secret_hash,created_at_ms,updated_at_ms,enabled) VALUES('cli-test-totp',?,'totp',?,'synthetic-invalid',1,1,1)`, principal, principal); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
p := newOIDCTestProvider(t)
|
||||||
|
previous := oidcVerifier
|
||||||
|
oidcVerifier = p.verifier
|
||||||
|
t.Cleanup(func() { oidcVerifier = previous })
|
||||||
|
if err := s.store.SetAuthProviderConfig(domain, store.AuthProviderConfig{Kind: "oidc", Enabled: true, Issuer: p.server.URL, ClientID: "client", ClientSecret: "secret", OIDCMatchBy: "preferred_username"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
verifier := strings.Repeat("x", 43)
|
||||||
|
sum := sha256.Sum256([]byte(verifier))
|
||||||
|
start := cliForm(s, "/_/auth/cli/start", url.Values{"code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])}, "code_challenge_method": {"S256"}}, "", "")
|
||||||
|
if start.Code != 200 {
|
||||||
|
t.Fatalf("start %d %s", start.Code, start.Body.String())
|
||||||
|
}
|
||||||
|
var grant struct {
|
||||||
|
Device string `json:"device_code"`
|
||||||
|
URI string `json:"verification_uri"`
|
||||||
|
Code string `json:"user_code"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(start.Body.Bytes(), &grant); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
u, _ := url.Parse(grant.URI)
|
||||||
|
id := u.Query().Get("request")
|
||||||
|
verify := httptest.NewRecorder()
|
||||||
|
s.handleAuth(verify, httptest.NewRequest("GET", "https://localhost"+grant.URI, nil))
|
||||||
|
if verify.Code != 200 || !strings.Contains(verify.Body.String(), "/_/auth/oidc?cli=") || strings.Contains(verify.Body.String(), grant.Device) {
|
||||||
|
t.Fatalf("verify landing: %d %s", verify.Code, verify.Body.String())
|
||||||
|
}
|
||||||
|
begin := httptest.NewRecorder()
|
||||||
|
s.beginOIDC(begin, httptest.NewRequest("GET", "https://localhost/_/auth/oidc?cli="+id, nil))
|
||||||
|
if begin.Code != 302 {
|
||||||
|
t.Fatalf("oidc begin %d %s", begin.Code, begin.Body.String())
|
||||||
|
}
|
||||||
|
location, _ := url.Parse(begin.Header().Get("Location"))
|
||||||
|
claims := oidcTestClaims(p.server.URL)
|
||||||
|
claims["nonce"] = location.Query().Get("nonce")
|
||||||
|
p.mu.Lock()
|
||||||
|
p.idToken = oidcTestToken(t, p.key, map[string]string{"alg": "RS256", "kid": "one"}, claims)
|
||||||
|
p.mu.Unlock()
|
||||||
|
callback := httptest.NewRequest("GET", "https://localhost/_/auth/callback/oidc?code=code&state="+url.QueryEscape(location.Query().Get("state")), nil)
|
||||||
|
for _, cookie := range begin.Result().Cookies() {
|
||||||
|
callback.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
complete := httptest.NewRecorder()
|
||||||
|
s.completeOIDC(complete, callback)
|
||||||
|
if complete.Code != 303 || complete.Header().Get("Location") != grant.URI {
|
||||||
|
t.Fatalf("oidc callback %d %s", complete.Code, complete.Body.String())
|
||||||
|
}
|
||||||
|
var browser string
|
||||||
|
for _, cookie := range complete.Result().Cookies() {
|
||||||
|
if cookie.Name == authCookieName {
|
||||||
|
browser = cookie.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if browser == "" {
|
||||||
|
t.Fatal("missing browser session")
|
||||||
|
}
|
||||||
|
consent := httptest.NewRequest("GET", "https://localhost"+grant.URI, nil)
|
||||||
|
consent.AddCookie(&http.Cookie{Name: authCookieName, Value: browser})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
s.handleAuth(w, consent)
|
||||||
|
if w.Code != 200 || !strings.Contains(w.Body.String(), `name="user_code"`) || !strings.Contains(w.Body.String(), cliConsentCSRF(browser, id)) {
|
||||||
|
t.Fatalf("consent %d %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
if strings.Contains(w.Body.String(), `name="totp"`) {
|
||||||
|
t.Fatal("OIDC consent repeated local TOTP")
|
||||||
|
}
|
||||||
|
form := url.Values{"request": {id}, "csrf": {cliConsentCSRF(browser, id)}, "user_code": {grant.Code}, "decision": {"approve"}}
|
||||||
|
if w := cliForm(s, "/_/auth/cli/verify", form, browser, "https://evil.example"); w.Code != 403 {
|
||||||
|
t.Fatal("cross-origin approval accepted")
|
||||||
|
}
|
||||||
|
bad := url.Values{"request": {id}, "csrf": {"bad"}, "user_code": {grant.Code}, "decision": {"approve"}}
|
||||||
|
if w := cliForm(s, "/_/auth/cli/verify", bad, browser, "https://localhost"); w.Code != 403 {
|
||||||
|
t.Fatal("CSRF accepted")
|
||||||
|
}
|
||||||
|
other, err := s.store.CreateBrowserAuthSession(domain, s.mustCLIPrincipal(t, domain, browser), 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if w := cliForm(s, "/_/auth/cli/verify", form, other, "https://localhost"); w.Code != 403 {
|
||||||
|
t.Fatal("other browser accepted")
|
||||||
|
}
|
||||||
|
approved := cliForm(s, "/_/auth/cli/verify", form, browser, "https://localhost")
|
||||||
|
if approved.Code != 200 || strings.Contains(approved.Body.String(), `name="user_code"`) {
|
||||||
|
t.Fatalf("approve: %d %s", approved.Code, approved.Body.String())
|
||||||
|
}
|
||||||
|
poll := url.Values{"device_code": {grant.Device}, "code_verifier": {verifier}}
|
||||||
|
exchange := cliForm(s, "/_/auth/cli/token", poll, "", "")
|
||||||
|
if exchange.Code != 200 {
|
||||||
|
t.Fatalf("exchange %d %s", exchange.Code, exchange.Body.String())
|
||||||
|
}
|
||||||
|
var result struct {
|
||||||
|
Token string `json:"access_token"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(exchange.Body.Bytes(), &result); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(result.Token, "pw_api_") || result.Username != "admin" || result.Token == browser {
|
||||||
|
t.Fatal("invalid delegated credential")
|
||||||
|
}
|
||||||
|
if _, err := s.store.PrincipalForSession(domain, result.Token); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if w := cliForm(s, "/_/auth/cli/token", poll, "", ""); w.Code == 200 {
|
||||||
|
t.Fatal("replay accepted")
|
||||||
|
}
|
||||||
|
if err := s.store.RevokeAuthSession(result.Token); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := s.store.PrincipalForSession(domain, result.Token); err == nil {
|
||||||
|
t.Fatal("CLI session not revocable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) mustCLIPrincipal(t *testing.T, domain, token string) string {
|
||||||
|
t.Helper()
|
||||||
|
p, err := s.store.PrincipalForSession(domain, token)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return p.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCLITransportAndMethods(t *testing.T) {
|
||||||
|
for _, host := range []string{"localhost.attacker.test", "127.0.0.10", "wiki.example"} {
|
||||||
|
if cliSecureTransport(httptest.NewRequest("POST", "http://"+host+"/_/auth/cli/start", nil)) {
|
||||||
|
t.Fatal("insecure remote", host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s, _, domain := configFixture(t)
|
||||||
|
if err := s.store.SetAuthProviderConfig(domain, store.AuthProviderConfig{Kind: "oidc", Enabled: true, Issuer: "https://id.example", ClientID: "client"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, path := range []string{"start", "token"} {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
s.handleAuth(w, httptest.NewRequest("GET", "https://localhost/_/auth/cli/"+path, nil))
|
||||||
|
if w.Code != 405 {
|
||||||
|
t.Fatalf("GET %s %d", path, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w := cliForm(s, "/_/auth/cli/start", url.Values{"code_challenge": {strings.Repeat("x", 43)}, "code_challenge_method": {"plain"}}, "", "")
|
||||||
|
if w.Code != 400 {
|
||||||
|
t.Fatal("plain challenge accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type oidcChallenge struct{ Verifier, Nonce, Return, Issuer, ClientID, BrowserHash string }
|
type oidcChallenge struct{ Verifier, Nonce, Return, Issuer, ClientID, BrowserHash, CLIRequest string }
|
||||||
|
|
||||||
func logOIDCFailure(stage, domainUUID, issuer string, err error) {
|
func logOIDCFailure(stage, domainUUID, issuer string, err error) {
|
||||||
host := "invalid"
|
host := "invalid"
|
||||||
@@ -56,6 +56,19 @@ func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
|
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
cliRequest := r.URL.Query().Get("cli")
|
||||||
|
returnPath := safeReturnPath(r.URL.Query().Get("return"))
|
||||||
|
if cliRequest != "" {
|
||||||
|
if !cliSecureTransport(r) || !cliProofPattern.MatchString(cliRequest) {
|
||||||
|
http.Error(w, "invalid CLI request", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.store.BeginCLIAuth(ctx, domainUUID, cliOrigin(r), cliRequest); err != nil {
|
||||||
|
http.Error(w, "invalid CLI request", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
returnPath = cliVerifyPath(cliRequest)
|
||||||
|
}
|
||||||
metadata, err := fetchOIDCMetadata(ctx, config.Issuer)
|
metadata, err := fetchOIDCMetadata(ctx, config.Issuer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logOIDCFailure("discovery", domainUUID, config.Issuer, err)
|
logOIDCFailure("discovery", domainUUID, config.Issuer, err)
|
||||||
@@ -64,7 +77,7 @@ func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
verifier, nonce, browser := randomURLToken(32), randomURLToken(24), randomURLToken(32)
|
verifier, nonce, browser := randomURLToken(32), randomURLToken(24), randomURLToken(32)
|
||||||
browserDigest := sha256.Sum256([]byte(browser))
|
browserDigest := sha256.Sum256([]byte(browser))
|
||||||
state, err := s.store.CreateAuthChallenge(domainUUID, "", "oidc", oidcChallenge{Verifier: verifier, Nonce: nonce, Return: safeReturnPath(r.URL.Query().Get("return")), Issuer: config.Issuer, ClientID: config.ClientID, BrowserHash: base64.RawURLEncoding.EncodeToString(browserDigest[:])}, 5*time.Minute)
|
state, err := s.store.CreateAuthChallenge(domainUUID, "", "oidc", oidcChallenge{Verifier: verifier, Nonce: nonce, Return: returnPath, Issuer: config.Issuer, ClientID: config.ClientID, BrowserHash: base64.RawURLEncoding.EncodeToString(browserDigest[:]), CLIRequest: cliRequest}, 5*time.Minute)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), 500)
|
http.Error(w, err.Error(), 500)
|
||||||
return
|
return
|
||||||
@@ -197,6 +210,13 @@ func (s *Server) completeOIDC(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Error(w, err.Error(), 500)
|
http.Error(w, err.Error(), 500)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if challenge.CLIRequest != "" {
|
||||||
|
if err := s.store.BindCLIAuth(r.Context(), domainUUID, cliOrigin(r), challenge.CLIRequest, token); err != nil {
|
||||||
|
_ = s.store.RevokeAuthSession(token)
|
||||||
|
http.Error(w, "CLI request expired or already used; restart login", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
s.setAuthCookie(w, r, token)
|
s.setAuthCookie(w, r, token)
|
||||||
http.Redirect(w, r, challenge.Return, http.StatusSeeOther)
|
http.Redirect(w, r, challenge.Return, http.StatusSeeOther)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -101,6 +101,10 @@ func (s *Server) authTokenFromRequest(r *http.Request) string {
|
|||||||
func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
||||||
action := strings.Trim(strings.TrimPrefix(r.URL.Path, "/_/auth"), "/")
|
action := strings.Trim(strings.TrimPrefix(r.URL.Path, "/_/auth"), "/")
|
||||||
domainUUID := s.domainUUIDForRequest(r)
|
domainUUID := s.domainUUIDForRequest(r)
|
||||||
|
if strings.HasPrefix(action, "cli/") {
|
||||||
|
s.handleCLIAuth(w, r, action)
|
||||||
|
return
|
||||||
|
}
|
||||||
switch action {
|
switch action {
|
||||||
case "wallpaper":
|
case "wallpaper":
|
||||||
s.handleAuthWallpaper(w, r)
|
s.handleAuthWallpaper(w, r)
|
||||||
|
|||||||
@@ -79,21 +79,25 @@ func readDAV(w http.ResponseWriter, r *http.Request) (davNode, error) {
|
|||||||
func xmlText(s string) string { var b bytes.Buffer; xml.EscapeText(&b, []byte(s)); return b.String() }
|
func xmlText(s string) string { var b bytes.Buffer; xml.EscapeText(&b, []byte(s)); return b.String() }
|
||||||
|
|
||||||
type davResponse struct {
|
type davResponse struct {
|
||||||
href string
|
href string
|
||||||
props map[xml.Name]string
|
props map[xml.Name]string
|
||||||
status int
|
status int
|
||||||
|
errorXML string
|
||||||
}
|
}
|
||||||
|
|
||||||
func davProperty(ns, key, value string) (xml.Name, string) {
|
func davProperty(ns, key, value string) (xml.Name, string) {
|
||||||
return xml.Name{Space: ns, Local: key}, value
|
return xml.Name{Space: ns, Local: key}, value
|
||||||
}
|
}
|
||||||
func writeDAV(w http.ResponseWriter, rows []davResponse, requested []davNode) {
|
func writeDAV(w http.ResponseWriter, rows []davResponse, requested []davNode, syncToken ...string) {
|
||||||
var b strings.Builder
|
var b strings.Builder
|
||||||
b.WriteString(`<?xml version="1.0" encoding="UTF-8"?><d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">`)
|
b.WriteString(`<?xml version="1.0" encoding="UTF-8"?><d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">`)
|
||||||
for _, row := range rows {
|
for _, row := range rows {
|
||||||
b.WriteString("<d:response><d:href>" + xmlText(row.href) + "</d:href>")
|
b.WriteString("<d:response><d:href>" + xmlText(row.href) + "</d:href>")
|
||||||
if row.status != 0 {
|
if row.status != 0 {
|
||||||
fmt.Fprintf(&b, "<d:status>HTTP/1.1 %d %s</d:status>", row.status, http.StatusText(row.status))
|
fmt.Fprintf(&b, "<d:status>HTTP/1.1 %d %s</d:status>", row.status, http.StatusText(row.status))
|
||||||
|
if row.errorXML != "" {
|
||||||
|
b.WriteString("<d:error>" + row.errorXML + "</d:error>")
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
present, missing := strings.Builder{}, strings.Builder{}
|
present, missing := strings.Builder{}, strings.Builder{}
|
||||||
props := requested
|
props := requested
|
||||||
@@ -122,6 +126,9 @@ func writeDAV(w http.ResponseWriter, rows []davResponse, requested []davNode) {
|
|||||||
}
|
}
|
||||||
b.WriteString("</d:response>")
|
b.WriteString("</d:response>")
|
||||||
}
|
}
|
||||||
|
if len(syncToken) == 1 {
|
||||||
|
b.WriteString("<d:sync-token>" + xmlText(syncToken[0]) + "</d:sync-token>")
|
||||||
|
}
|
||||||
b.WriteString("</d:multistatus>")
|
b.WriteString("</d:multistatus>")
|
||||||
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
|
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
|
||||||
w.WriteHeader(207)
|
w.WriteHeader(207)
|
||||||
|
|||||||
@@ -60,6 +60,9 @@ func (s *Server) handleCalendarUpcoming(w http.ResponseWriter, r *http.Request,
|
|||||||
start = day
|
start = day
|
||||||
}
|
}
|
||||||
end := start.AddDate(0, 0, 31)
|
end := start.AddDate(0, 0, 31)
|
||||||
|
if r.URL.Query().Get("period") == "day" {
|
||||||
|
end = start.AddDate(0, 0, 1)
|
||||||
|
}
|
||||||
for _, c := range cs {
|
for _, c := range cs {
|
||||||
if !selected[c.ID] {
|
if !selected[c.ID] {
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -61,6 +61,17 @@ func TestCalendarUpcomingDefaultsAndBounds(t *testing.T) {
|
|||||||
if !strings.Contains(w.Header().Get("Cache-Control"), "no-store") {
|
if !strings.Contains(w.Header().Get("Cache-Control"), "no-store") {
|
||||||
t.Fatal("private response cached")
|
t.Fatal("private response cached")
|
||||||
}
|
}
|
||||||
|
w = calendarRequest(s, token, "GET", calendarAPI+"upcoming?period=day", "", "")
|
||||||
|
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
now := time.Now().In(s.getLocation(domain))
|
||||||
|
end := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, s.getLocation(domain))
|
||||||
|
for _, event := range result.Events {
|
||||||
|
if !event.Start.Before(end) {
|
||||||
|
t.Fatal("tomorrow event in today's widget", event.Start)
|
||||||
|
}
|
||||||
|
}
|
||||||
if w = calendarRequest(s, "", "GET", calendarAPI+"upcoming", "", ""); w.Code != 403 {
|
if w = calendarRequest(s, "", "GET", calendarAPI+"upcoming", "", ""); w.Code != 403 {
|
||||||
t.Fatal("anonymous access", w.Code)
|
t.Fatal("anonymous access", w.Code)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -98,6 +98,10 @@ func (s *Server) handleConfig(
|
|||||||
w http.ResponseWriter,
|
w http.ResponseWriter,
|
||||||
r *http.Request,
|
r *http.Request,
|
||||||
) {
|
) {
|
||||||
|
if personalOrganizerSettings(r) {
|
||||||
|
s.handleOrganizerSettings(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
domainUUID := s.domainUUIDForRequest(r)
|
domainUUID := s.domainUUIDForRequest(r)
|
||||||
principal := s.requestPrincipal(r)
|
principal := s.requestPrincipal(r)
|
||||||
currentDomain := s.domainForRequest(r)
|
currentDomain := s.domainForRequest(r)
|
||||||
|
|||||||
@@ -22,5 +22,6 @@ func configPanelGroups(locale string, plugins []adapterPlugin) []configPanelGrou
|
|||||||
groups[4].Panels = append(groups[4].Panels, configPanelLink{"adapter-" + plugin.ID, plugin.Name})
|
groups[4].Panels = append(groups[4].Panels, configPanelLink{"adapter-" + plugin.ID, plugin.Name})
|
||||||
}
|
}
|
||||||
groups = append(groups, configPanelGroup{"extensions", translate(locale, "extension.title"), []configPanelLink{link("extensions", "extension.catalog"), link("diary", "periodical.diary"), link("blog", "periodical.blog")}})
|
groups = append(groups, configPanelGroup{"extensions", translate(locale, "extension.title"), []configPanelLink{link("extensions", "extension.catalog"), link("diary", "periodical.diary"), link("blog", "periodical.blog")}})
|
||||||
|
groups = append(groups, configPanelGroup{"organizer", translate(locale, "organizer.title"), []configPanelLink{link("organizer", "organizer.settings")}})
|
||||||
return groups
|
return groups
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,586 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/xml"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"golang.org/x/text/unicode/norm"
|
||||||
|
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
const contactDAV = "/_/api/v1/carddav/"
|
||||||
|
const cardNS = "urn:ietf:params:xml:ns:carddav"
|
||||||
|
|
||||||
|
func contactDAVRoute(p string) bool {
|
||||||
|
return p == strings.TrimSuffix(contactDAV, "/") || strings.HasPrefix(p, contactDAV) || p == "/.well-known/carddav"
|
||||||
|
}
|
||||||
|
func contactDAVError(w http.ResponseWriter, status int, ns, condition string) {
|
||||||
|
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
io.WriteString(w, `<?xml version="1.0"?><d:error xmlns:d="DAV:"><p:`+condition+` xmlns:p="`+xmlText(ns)+`"/></d:error>`)
|
||||||
|
}
|
||||||
|
func contactDAVStoreError(w http.ResponseWriter, err error) {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, sql.ErrNoRows):
|
||||||
|
w.WriteHeader(404)
|
||||||
|
case errors.Is(err, store.ErrTaskConflict):
|
||||||
|
w.WriteHeader(412)
|
||||||
|
case errors.Is(err, store.ErrContactUIDConflict):
|
||||||
|
contactDAVError(w, 403, cardNS, "no-uid-conflict")
|
||||||
|
case errors.Is(err, store.ErrContactSyncToken):
|
||||||
|
contactDAVError(w, 403, davNS, "valid-sync-token")
|
||||||
|
case errors.Is(err, store.ErrAccessDenied):
|
||||||
|
w.WriteHeader(403)
|
||||||
|
case errors.Is(err, store.ErrTaskInvalid):
|
||||||
|
contactDAVError(w, 403, cardNS, "valid-address-data")
|
||||||
|
default:
|
||||||
|
http.Error(w, "address book operation failed", 500)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func contactDAVRow(base string, item store.ContactDAVItem) davResponse {
|
||||||
|
row := davResponse{href: base + item.Name}
|
||||||
|
if item.Deleted {
|
||||||
|
row.status = 404
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
size := len(item.VCard)
|
||||||
|
if item.Size > 0 {
|
||||||
|
size = item.Size
|
||||||
|
}
|
||||||
|
row.props = map[xml.Name]string{
|
||||||
|
{Space: davNS, Local: "getetag"}: xmlText(store.ContactETag(item.Contact)),
|
||||||
|
{Space: davNS, Local: "resourcetype"}: "",
|
||||||
|
{Space: davNS, Local: "getcontenttype"}: "text/vcard; charset=utf-8",
|
||||||
|
{Space: davNS, Local: "getcontentlength"}: strconv.Itoa(size),
|
||||||
|
{Space: cardNS, Local: "address-data"}: xmlText(item.VCard),
|
||||||
|
}
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
func contactBookRow(base, token string, writable bool) davResponse {
|
||||||
|
return davResponse{href: base, props: map[xml.Name]string{
|
||||||
|
{Space: davNS, Local: "displayname"}: "PagesWiki Contacts",
|
||||||
|
{Space: davNS, Local: "resourcetype"}: "<d:collection/><a:addressbook/>",
|
||||||
|
{Space: davNS, Local: "current-user-privilege-set"}: davPrivileges(writable),
|
||||||
|
{Space: davNS, Local: "sync-token"}: xmlText(token),
|
||||||
|
{Space: "http://calendarserver.org/ns/", Local: "getctag"}: xmlText(token),
|
||||||
|
{Space: cardNS, Local: "addressbook-description"}: "Private contacts",
|
||||||
|
{Space: cardNS, Local: "max-resource-size"}: "65536",
|
||||||
|
{Space: cardNS, Local: "supported-address-data"}: `<a:address-data-type content-type="text/vcard" version="3.0"/><a:address-data-type content-type="text/vcard" version="4.0"/>`,
|
||||||
|
{Space: cardNS, Local: "supported-collation-set"}: `<a:supported-collation>i;unicode-casemap</a:supported-collation><a:supported-collation>i;octet</a:supported-collation>`,
|
||||||
|
{Space: davNS, Local: "supported-report-set"}: `<d:supported-report><d:report><a:addressbook-query/></d:report></d:supported-report><d:supported-report><d:report><a:addressbook-multiget/></d:report></d:supported-report><d:supported-report><d:report><d:sync-collection/></d:report></d:supported-report>`,
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleContactDAV(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
r = r.WithContext(ctx)
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
if !s.systemExtensionEnabled(domain, "organizer.contacts") {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Path == "/.well-known/carddav" {
|
||||||
|
w.Header().Set("Location", contactDAV)
|
||||||
|
w.WriteHeader(307)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actor, writable, _, credential, ok := s.davActor(w, r, "contacts", false)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// davActor authenticates the principal; storage rechecks active membership,
|
||||||
|
// ownership and the extension switch even on reads.
|
||||||
|
snapshot, err := s.store.ContactDAVSnapshot(ctx, domain, actor, "", 0)
|
||||||
|
if err != nil {
|
||||||
|
contactDAVStoreError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
principal := contactDAV + actor + "/"
|
||||||
|
book := principal + "contacts/"
|
||||||
|
p := r.URL.Path
|
||||||
|
root := p == contactDAV || p == strings.TrimSuffix(contactDAV, "/")
|
||||||
|
home := p == principal || p == strings.TrimSuffix(principal, "/")
|
||||||
|
collection := p == book || p == strings.TrimSuffix(book, "/")
|
||||||
|
name := ""
|
||||||
|
if !root && !home && !collection {
|
||||||
|
if !strings.HasPrefix(p, book) {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name = strings.TrimPrefix(p, book)
|
||||||
|
if !store.ValidContactDAVName(name) {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.Header().Set("DAV", "1, addressbook-access")
|
||||||
|
w.Header().Set("X-PagesWiki-CardDAV-Profile", "private-addressbook")
|
||||||
|
allow := "OPTIONS, PROPFIND"
|
||||||
|
if collection {
|
||||||
|
allow += ", REPORT"
|
||||||
|
}
|
||||||
|
if name != "" {
|
||||||
|
allow += ", GET, HEAD"
|
||||||
|
if writable {
|
||||||
|
allow += ", PUT, DELETE"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.Header().Set("Allow", allow)
|
||||||
|
if r.Method == "OPTIONS" {
|
||||||
|
w.WriteHeader(204)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "PROPFIND" {
|
||||||
|
depth := r.Header.Get("Depth")
|
||||||
|
if depth != "0" && depth != "1" {
|
||||||
|
contactDAVError(w, 403, davNS, "propfind-finite-depth")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, e := readDAV(w, r)
|
||||||
|
if e != nil || n.XMLName.Local != "" && n.XMLName != (xml.Name{Space: davNS, Local: "propfind"}) {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var requested []davNode
|
||||||
|
if prop := n.child(davNS, "prop"); prop != nil {
|
||||||
|
requested = prop.Children
|
||||||
|
}
|
||||||
|
if name != "" {
|
||||||
|
c, e := s.store.ContactDAVResource(ctx, domain, actor, name)
|
||||||
|
if e != nil {
|
||||||
|
contactDAVStoreError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if c.Deleted {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
row := contactDAVRow(book, store.ContactDAVItem{Contact: c, Name: name})
|
||||||
|
delete(row.props, xml.Name{Space: cardNS, Local: "address-data"})
|
||||||
|
writeDAV(w, []davResponse{row}, requested)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var rows []davResponse
|
||||||
|
if collection {
|
||||||
|
rows = append(rows, contactBookRow(book, snapshot.Token, writable))
|
||||||
|
if depth == "1" {
|
||||||
|
data, e := s.store.ContactDAVInventory(ctx, domain, actor)
|
||||||
|
if e != nil {
|
||||||
|
contactDAVStoreError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if data.More {
|
||||||
|
contactDAVError(w, 507, davNS, "number-of-matches-within-limits")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, c := range data.Items {
|
||||||
|
row := contactDAVRow(book, c)
|
||||||
|
delete(row.props, xml.Name{Space: cardNS, Local: "address-data"})
|
||||||
|
rows = append(rows, row)
|
||||||
|
}
|
||||||
|
rows[0] = contactBookRow(book, data.Token, writable)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
href := principal
|
||||||
|
if root {
|
||||||
|
href = contactDAV
|
||||||
|
}
|
||||||
|
rows = append(rows, davResponse{href: href, props: map[xml.Name]string{
|
||||||
|
{Space: davNS, Local: "resourcetype"}: "<d:collection/><d:principal/>",
|
||||||
|
{Space: davNS, Local: "displayname"}: "PagesWiki Contacts",
|
||||||
|
{Space: davNS, Local: "current-user-principal"}: "<d:href>" + principal + "</d:href>",
|
||||||
|
{Space: davNS, Local: "principal-URL"}: "<d:href>" + principal + "</d:href>",
|
||||||
|
{Space: cardNS, Local: "addressbook-home-set"}: "<d:href>" + principal + "</d:href>",
|
||||||
|
{Space: davNS, Local: "current-user-privilege-set"}: davPrivileges(false),
|
||||||
|
}})
|
||||||
|
if depth == "1" {
|
||||||
|
rows = append(rows, contactBookRow(book, snapshot.Token, writable))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeDAV(w, rows, requested)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "REPORT" && collection {
|
||||||
|
s.contactDAVReport(w, r, domain, actor, book)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if name == "" {
|
||||||
|
w.WriteHeader(405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c, err := s.store.ContactDAVResource(ctx, domain, actor, name)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
contactDAVStoreError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
exists := err == nil && !c.Deleted
|
||||||
|
if r.Method == "GET" || r.Method == "HEAD" {
|
||||||
|
if !exists {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tag := store.ContactETag(c)
|
||||||
|
w.Header().Set("ETag", tag)
|
||||||
|
if contactETagMatch(r.Header.Get("If-None-Match"), tag, true) {
|
||||||
|
w.WriteHeader(304)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/vcard; charset=utf-8")
|
||||||
|
w.Header().Set("Content-Length", strconv.Itoa(len(c.VCard)))
|
||||||
|
if r.Method == "GET" {
|
||||||
|
io.WriteString(w, c.VCard)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method != "PUT" && r.Method != "DELETE" {
|
||||||
|
w.WriteHeader(405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !writable {
|
||||||
|
w.WriteHeader(403)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "DELETE" && !exists {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
match, none := r.Header.Get("If-Match"), r.Header.Get("If-None-Match")
|
||||||
|
if match != "" && none != "" {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if match != "" && (!exists || !contactETagMatch(match, store.ContactETag(c), false)) || none != "" && exists && contactETagMatch(none, store.ContactETag(c), true) {
|
||||||
|
w.WriteHeader(412)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if exists && match == "" {
|
||||||
|
w.WriteHeader(428)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !exists && match == "" && none != "*" {
|
||||||
|
w.WriteHeader(428)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw := ""
|
||||||
|
if r.Method == "PUT" {
|
||||||
|
media, params, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||||
|
if e != nil || media != "text/vcard" && media != "text/x-vcard" || params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8") {
|
||||||
|
contactDAVError(w, 415, cardNS, "supported-address-data")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 65536))
|
||||||
|
if e != nil {
|
||||||
|
w.WriteHeader(413)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw = string(data)
|
||||||
|
if values := store.ContactPropertyValues(store.Contact{VCard: raw}, "UID"); len(values) != 1 || values[0] == "" {
|
||||||
|
contactDAVError(w, 403, cardNS, "valid-address-data")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if v := params["version"]; v != "" {
|
||||||
|
values := store.ContactPropertyValues(store.Contact{VCard: raw}, "VERSION")
|
||||||
|
if len(values) != 1 || values[0] != v {
|
||||||
|
contactDAVError(w, 415, cardNS, "supported-address-data")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
saved, e := s.store.SaveContactDAV(ctx, domain, actor, credential, name, raw, c.Version, r.Method == "DELETE")
|
||||||
|
if e != nil {
|
||||||
|
contactDAVStoreError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "DELETE" {
|
||||||
|
w.WriteHeader(204)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// RFC 6352: a transformed PUT representation must be fetched again by client.
|
||||||
|
if saved.VCard == raw {
|
||||||
|
w.Header().Set("ETag", store.ContactETag(saved))
|
||||||
|
}
|
||||||
|
if exists {
|
||||||
|
w.WriteHeader(204)
|
||||||
|
} else {
|
||||||
|
w.Header().Set("Location", book+name)
|
||||||
|
w.WriteHeader(201)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func contactETagMatch(value, tag string, weak bool) bool {
|
||||||
|
for _, v := range strings.Split(value, ",") {
|
||||||
|
v = strings.TrimSpace(v)
|
||||||
|
if weak {
|
||||||
|
v = strings.TrimPrefix(v, "W/")
|
||||||
|
}
|
||||||
|
if v == "*" || v == tag {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
func (s *Server) contactDAVReport(w http.ResponseWriter, r *http.Request, domain, actor, book string) {
|
||||||
|
if depth := r.Header.Get("Depth"); depth != "" && depth != "0" && depth != "1" {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, err := readDAV(w, r)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
prop := n.child(davNS, "prop")
|
||||||
|
if prop == nil || len(prop.Children) == 0 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, p := range prop.Children {
|
||||||
|
if p.XMLName == (xml.Name{Space: cardNS, Local: "address-data"}) && (len(p.Children) > 0 || p.attr("content-type") != "" && p.attr("content-type") != "text/vcard" || p.attr("version") != "" && p.attr("version") != "3.0" && p.attr("version") != "4.0") {
|
||||||
|
contactDAVError(w, 403, cardNS, "supported-address-data")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
requested := prop.Children
|
||||||
|
rows := []davResponse{}
|
||||||
|
if n.XMLName == (xml.Name{Space: davNS, Local: "sync-collection"}) {
|
||||||
|
level := n.child(davNS, "sync-level")
|
||||||
|
token := n.child(davNS, "sync-token")
|
||||||
|
if level == nil || level.Text != "1" || token == nil {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
limit := 200
|
||||||
|
if l := n.child(davNS, "limit"); l != nil {
|
||||||
|
num := l.child(davNS, "nresults")
|
||||||
|
if num == nil {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
v, e := strconv.Atoi(num.Text)
|
||||||
|
if e != nil || v < 1 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if v < limit {
|
||||||
|
limit = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data, e := s.store.ContactDAVSnapshot(r.Context(), domain, actor, token.Text, limit)
|
||||||
|
if e != nil {
|
||||||
|
contactDAVStoreError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, c := range data.Items {
|
||||||
|
rows = append(rows, contactDAVRow(book, c))
|
||||||
|
}
|
||||||
|
if data.More {
|
||||||
|
rows = append(rows, davResponse{href: book, status: 507, errorXML: "<d:number-of-matches-within-limits/>"})
|
||||||
|
}
|
||||||
|
writeContactDAV(w, rows, requested, data.Token)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if n.XMLName == (xml.Name{Space: cardNS, Local: "addressbook-multiget"}) {
|
||||||
|
count := 0
|
||||||
|
for _, h := range n.Children {
|
||||||
|
if h.XMLName != (xml.Name{Space: davNS, Local: "href"}) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
count++
|
||||||
|
if count > 100 {
|
||||||
|
contactDAVError(w, 507, davNS, "number-of-matches-within-limits")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
u, e := url.Parse(h.Text)
|
||||||
|
if e != nil || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Host != "" && (!strings.EqualFold(u.Host, r.Host) || u.Scheme != "https" && u.Scheme != "http") || !strings.HasPrefix(u.Path, book) || !store.ValidContactDAVName(strings.TrimPrefix(u.Path, book)) {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := strings.TrimPrefix(u.Path, book)
|
||||||
|
c, e := s.store.ContactDAVResource(r.Context(), domain, actor, name)
|
||||||
|
if errors.Is(e, sql.ErrNoRows) {
|
||||||
|
rows = append(rows, davResponse{href: book + name, status: 404})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if e != nil {
|
||||||
|
contactDAVStoreError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rows = append(rows, contactDAVRow(book, store.ContactDAVItem{Contact: c, Name: name}))
|
||||||
|
}
|
||||||
|
if count == 0 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeContactDAV(w, rows, requested)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if n.XMLName != (xml.Name{Space: cardNS, Local: "addressbook-query"}) {
|
||||||
|
contactDAVError(w, 403, davNS, "supported-report")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
filter := n.child(cardNS, "filter")
|
||||||
|
if filter != nil && !validContactFilter(*filter) {
|
||||||
|
contactDAVError(w, 403, cardNS, "supported-filter")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// A bounded full scan is explicit; never return a truncated 207 as a complete
|
||||||
|
// address book, which would make clients infer deletions. Sync is paginated.
|
||||||
|
data, e := s.store.ContactDAVSnapshot(r.Context(), domain, actor, "", 200)
|
||||||
|
if e != nil {
|
||||||
|
contactDAVStoreError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if data.More {
|
||||||
|
contactDAVError(w, 507, davNS, "number-of-matches-within-limits")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
limit := 200
|
||||||
|
if l := n.child(cardNS, "limit"); l != nil {
|
||||||
|
num := l.child(cardNS, "nresults")
|
||||||
|
if num == nil {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
v, e := strconv.Atoi(num.Text)
|
||||||
|
if e != nil || v < 1 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if v < limit {
|
||||||
|
limit = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, c := range data.Items {
|
||||||
|
if filter == nil || matchContactFilter(c.Contact, *filter) {
|
||||||
|
rows = append(rows, contactDAVRow(book, c))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(rows) > limit {
|
||||||
|
contactDAVError(w, 507, davNS, "number-of-matches-within-limits")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeContactDAV(w, rows, requested)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeContactDAV(w http.ResponseWriter, rows []davResponse, requested []davNode, token ...string) {
|
||||||
|
for _, p := range requested {
|
||||||
|
if p.XMLName == (xml.Name{Space: cardNS, Local: "address-data"}) && p.attr("version") != "" {
|
||||||
|
for _, row := range rows {
|
||||||
|
if v, ok := row.props[xml.Name{Space: cardNS, Local: "address-data"}]; ok && !strings.HasPrefix(v, xmlText("BEGIN:VCARD\r\nVERSION:"+p.attr("version")+"\r\n")) {
|
||||||
|
contactDAVError(w, 403, cardNS, "supported-address-data")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeDAV(w, rows, requested, token...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validContactFilter(n davNode) bool {
|
||||||
|
if n.attr("test") != "" && n.attr("test") != "anyof" && n.attr("test") != "allof" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, p := range n.Children {
|
||||||
|
if p.XMLName != (xml.Name{Space: cardNS, Local: "prop-filter"}) || p.attr("name") == "" || p.attr("test") != "" && p.attr("test") != "anyof" && p.attr("test") != "allof" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, c := range p.attr("name") {
|
||||||
|
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, m := range p.Children {
|
||||||
|
switch m.XMLName {
|
||||||
|
case xml.Name{Space: cardNS, Local: "is-not-defined"}:
|
||||||
|
if len(p.Children) != 1 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
case xml.Name{Space: cardNS, Local: "text-match"}:
|
||||||
|
if m.attr("collation") != "" && m.attr("collation") != "i;unicode-casemap" && m.attr("collation") != "i;octet" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if m.attr("match-type") != "" && m.attr("match-type") != "contains" && m.attr("match-type") != "equals" && m.attr("match-type") != "starts-with" && m.attr("match-type") != "ends-with" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if m.attr("negate-condition") != "" && m.attr("negate-condition") != "yes" && m.attr("negate-condition") != "no" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if len(m.Children) > 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
func matchContactFilter(c store.Contact, n davNode) bool {
|
||||||
|
if len(n.Children) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
all := n.attr("test") == "allof"
|
||||||
|
result := all
|
||||||
|
for _, p := range n.Children {
|
||||||
|
values := store.ContactPropertyValues(c, p.attr("name"))
|
||||||
|
match := len(values) > 0
|
||||||
|
if len(p.Children) > 0 {
|
||||||
|
and := p.attr("test") == "allof"
|
||||||
|
match = and
|
||||||
|
for _, m := range p.Children {
|
||||||
|
hit := false
|
||||||
|
if m.XMLName.Local == "is-not-defined" {
|
||||||
|
hit = len(values) == 0
|
||||||
|
} else {
|
||||||
|
for _, v := range values {
|
||||||
|
query := m.Text
|
||||||
|
if m.attr("collation") != "i;octet" {
|
||||||
|
v = norm.NFKD.String(strings.Map(unicode.ToTitle, v))
|
||||||
|
query = norm.NFKD.String(strings.Map(unicode.ToTitle, query))
|
||||||
|
}
|
||||||
|
switch m.attr("match-type") {
|
||||||
|
case "equals":
|
||||||
|
hit = v == query
|
||||||
|
case "starts-with":
|
||||||
|
hit = strings.HasPrefix(v, query)
|
||||||
|
case "ends-with":
|
||||||
|
hit = strings.HasSuffix(v, query)
|
||||||
|
default:
|
||||||
|
hit = strings.Contains(v, query)
|
||||||
|
}
|
||||||
|
if hit {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if m.attr("negate-condition") == "yes" {
|
||||||
|
hit = !hit && len(values) > 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if and {
|
||||||
|
match = match && hit
|
||||||
|
} else {
|
||||||
|
match = match || hit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if all {
|
||||||
|
result = result && match
|
||||||
|
} else {
|
||||||
|
result = result || match
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Real client interoperability uses only disposable, synthetic contacts.
|
||||||
|
func TestContactDAVVdirsyncer(t *testing.T) {
|
||||||
|
bin := os.Getenv("PAGESWIKI_VDIRSYNCER")
|
||||||
|
if bin == "" {
|
||||||
|
t.Skip("opt-in vdirsyncer executable")
|
||||||
|
}
|
||||||
|
s, _, domain, actor := taskFixture(t)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
credential, password, err := s.store.CreateDAVCredential(ctx, domain, actor, "Fixture", true, 1, "contacts")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
native, err := s.store.SaveContact(ctx, domain, actor, store.Contact{UUID: uuid.NewString(), VCard: testCard}, true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
server := httptest.NewServer(s.handler())
|
||||||
|
defer server.Close()
|
||||||
|
dir := t.TempDir()
|
||||||
|
local := filepath.Join(dir, "cards")
|
||||||
|
if err = os.MkdirAll(filepath.Join(local, "contacts"), 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
config := fmt.Sprintf(`[general]
|
||||||
|
status_path = %q
|
||||||
|
[pair contacts]
|
||||||
|
a = "local"
|
||||||
|
b = "remote"
|
||||||
|
collections = ["contacts"]
|
||||||
|
[storage local]
|
||||||
|
type = "filesystem"
|
||||||
|
path = %q
|
||||||
|
fileext = ".vcf"
|
||||||
|
[storage remote]
|
||||||
|
type = "carddav"
|
||||||
|
url = %q
|
||||||
|
username = %q
|
||||||
|
password = %q
|
||||||
|
`, filepath.Join(dir, "status"), local, strings.Replace(server.URL, "127.0.0.1", "localhost", 1)+contactDAV, credential.ID, password)
|
||||||
|
configPath := filepath.Join(dir, "vdirsyncer.conf")
|
||||||
|
if err = os.WriteFile(configPath, []byte(config), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
run := func(action string, extra ...string) {
|
||||||
|
t.Helper()
|
||||||
|
cmd := exec.CommandContext(ctx, bin, append([]string{"-c", configPath, action}, extra...)...)
|
||||||
|
cmd.Stdin = strings.NewReader("y\ny\ny\n")
|
||||||
|
out, e := cmd.CombinedOutput()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatalf("%s: %v\n%s", action, e, strings.ReplaceAll(string(out), password, "[REDACTED]"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
run("discover")
|
||||||
|
run("sync")
|
||||||
|
files, err := filepath.Glob(filepath.Join(local, "contacts", "*.vcf"))
|
||||||
|
if err != nil || len(files) != 1 {
|
||||||
|
t.Fatal(files, err)
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile(files[0])
|
||||||
|
if err != nil || !strings.Contains(string(raw), "FN:田中") {
|
||||||
|
t.Fatal("download", err)
|
||||||
|
}
|
||||||
|
if err = os.WriteFile(files[0], []byte(strings.Replace(string(raw), "FN:田中", "FN:Client edited", 1)), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
run("sync")
|
||||||
|
got, err := s.store.Contact(ctx, domain, actor, native.UUID)
|
||||||
|
if err != nil || got.Name != "Client edited" || !strings.Contains(got.VCard, "X-PRIVATE:keep") {
|
||||||
|
t.Fatal("client edit", got.Name, err)
|
||||||
|
}
|
||||||
|
got.Name = "Web edited"
|
||||||
|
got, err = s.store.SaveContact(ctx, domain, actor, got, false)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
run("sync")
|
||||||
|
raw, err = os.ReadFile(files[0])
|
||||||
|
if err != nil || !strings.Contains(string(raw), "FN:Web edited") {
|
||||||
|
t.Fatal("web edit", err)
|
||||||
|
}
|
||||||
|
newPath := filepath.Join(local, "contacts", "client-new.vcf")
|
||||||
|
newCard := strings.ReplaceAll(testCard, "urn:test:dav-contact", "urn:test:client-new")
|
||||||
|
if err = os.WriteFile(newPath, []byte(newCard), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
run("sync")
|
||||||
|
items, _, err := s.store.Contacts(ctx, domain, actor, "", "")
|
||||||
|
if err != nil || len(items) != 2 {
|
||||||
|
t.Fatal("client create", len(items), err)
|
||||||
|
}
|
||||||
|
if err = os.Remove(newPath); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
run("sync")
|
||||||
|
items, _, err = s.store.Contacts(ctx, domain, actor, "", "")
|
||||||
|
if err != nil || len(items) != 1 {
|
||||||
|
t.Fatal("client delete", len(items), err)
|
||||||
|
}
|
||||||
|
got.Deleted = true
|
||||||
|
if _, err = s.store.SaveContact(ctx, domain, actor, got, false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Emptying a whole book requires vdirsyncer's explicit safety override.
|
||||||
|
run("sync", "--force-delete", "contacts/contacts")
|
||||||
|
files, err = filepath.Glob(filepath.Join(local, "contacts", "*.vcf"))
|
||||||
|
if err != nil || len(files) != 0 {
|
||||||
|
t.Fatal("web delete", files, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,358 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/xml"
|
||||||
|
"fmt"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testCard = "BEGIN:VCARD\r\nVERSION:4.0\r\nUID:urn:test:dav-contact\r\nFN:田中\r\nEMAIL;TYPE=work:tanaka@example.invalid\r\nX-PRIVATE:keep\r\nEND:VCARD\r\n"
|
||||||
|
|
||||||
|
func TestContactDAVConcurrentWritesAndStandaloneExtension(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
for _, id := range []string{"organizer.tasks", "organizer.calendar"} {
|
||||||
|
if e := s.setSystemExtensionEnabled(domain, id, false); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cred, pass, err := s.store.CreateDAVCredential(ctx, domain, actor, "phone", true, 1, "contacts")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(cred.ID+":"+pass))
|
||||||
|
path := contactDAV + actor + "/contacts/one.vcf"
|
||||||
|
if w := cardRequest(s, auth, "PUT", path, testCard, map[string]string{"If-None-Match": "*"}); w.Code != 201 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
if w := cardRequest(s, "Bearer "+token, "GET", "/_/api/v1/caldav-credentials", "", nil); w.Code != 200 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
start := make(chan struct{})
|
||||||
|
results := make(chan int, 2)
|
||||||
|
for _, name := range []string{"First", "Second"} {
|
||||||
|
go func(name string) {
|
||||||
|
<-start
|
||||||
|
w := cardRequest(s, auth, "PUT", path, strings.Replace(testCard, "FN:田中", "FN:"+name, 1), map[string]string{"If-Match": `"1"`})
|
||||||
|
results <- w.Code
|
||||||
|
}(name)
|
||||||
|
}
|
||||||
|
close(start)
|
||||||
|
a, b := <-results, <-results
|
||||||
|
if !(a == 204 && b == 412 || a == 412 && b == 204) {
|
||||||
|
t.Fatal("concurrent overwrite", a, b)
|
||||||
|
}
|
||||||
|
// Removing the contacts marker must never reinterpret this secret as tasks.
|
||||||
|
if _, err = s.store.DB.Exec(`DELETE FROM organizer_contact_credentials WHERE credential_id=?`, cred.ID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, _, _, err = s.store.AuthenticateDAV(ctx, domain, cred.ID, pass, ""); err != store.ErrAccessDenied {
|
||||||
|
t.Fatal("scope downgrade", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContactDAVInventoryAndLimits(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
for i := 0; i < 201; i++ {
|
||||||
|
_, e := s.store.SaveContact(ctx, domain, actor, store.Contact{UUID: uuid.NewString(), Name: fmt.Sprintf("Person %03d", i)}, false)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data, err := s.store.ContactDAVInventory(ctx, domain, actor)
|
||||||
|
if err != nil || data.More || len(data.Items) != 201 {
|
||||||
|
t.Fatal(len(data.Items), err)
|
||||||
|
}
|
||||||
|
for _, c := range data.Items {
|
||||||
|
if c.VCard != "" || c.Size < 1 || c.Version != 1 {
|
||||||
|
t.Fatal("inventory must contain metadata only", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
book := contactDAV + actor + "/contacts/"
|
||||||
|
auth := "Bearer " + token
|
||||||
|
w := cardRequest(s, auth, "PROPFIND", book, "", nil)
|
||||||
|
if w.Code != 207 || strings.Count(w.Body.String(), "<d:response>") != 202 || strings.Contains(w.Body.String(), "BEGIN:VCARD") {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
w = cardRequest(s, auth, "REPORT", book, cardSync("", ""), nil)
|
||||||
|
if w.Code != 207 || !strings.Contains(w.Body.String(), "507") {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
next := cardRequest(s, auth, "REPORT", book, cardSync(responseSync(t, w), ""), nil)
|
||||||
|
if next.Code != 207 || strings.Count(next.Body.String(), "<d:response>") != 1 {
|
||||||
|
t.Fatal(next.Code, next.Body)
|
||||||
|
}
|
||||||
|
query := `<a:addressbook-query xmlns:a="urn:ietf:params:xml:ns:carddav" xmlns:d="DAV:"><d:prop><d:getetag/></d:prop></a:addressbook-query>`
|
||||||
|
w = cardRequest(s, auth, "REPORT", book, query, nil)
|
||||||
|
if w.Code != 507 {
|
||||||
|
t.Fatal("must not silently truncate a full query", w.Code)
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
raw, media string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{strings.Replace(testCard, "UID:urn:test:dav-contact\r\n", "", 1), "text/vcard", 403},
|
||||||
|
{testCard, "text/vcard; version=3.0", 415},
|
||||||
|
{testCard, "text/vcard; charset=shift_jis", 415},
|
||||||
|
} {
|
||||||
|
w = cardRequest(s, auth, "PUT", book+"invalid.vcf", tc.raw, map[string]string{"If-None-Match": "*", "Content-Type": tc.media})
|
||||||
|
if w.Code != tc.want {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContactDAVUnicodeAndUnknownProperties(t *testing.T) {
|
||||||
|
card := store.Contact{VCard: strings.Replace(testCard, "X-PRIVATE:keep", "X-PRIVATE:CAFÉ", 1)}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
collation, query string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"i;unicode-casemap", "cafe\u0301", true},
|
||||||
|
{"i;unicode-casemap", "CAFÉ", true},
|
||||||
|
{"i;octet", "café", false},
|
||||||
|
{"i;octet", "CAFÉ", true},
|
||||||
|
} {
|
||||||
|
var filter davNode
|
||||||
|
raw := `<a:filter xmlns:a="urn:ietf:params:xml:ns:carddav"><a:prop-filter name="X-PRIVATE"><a:text-match collation="` + tc.collation + `" match-type="equals">` + tc.query + `</a:text-match></a:prop-filter></a:filter>`
|
||||||
|
if e := xml.Unmarshal([]byte(raw), &filter); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if !validContactFilter(filter) || matchContactFilter(card, filter) != tc.want {
|
||||||
|
t.Fatal(tc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func cardRequest(s *Server, auth, method, path, body string, headers map[string]string) *httptest.ResponseRecorder {
|
||||||
|
if headers == nil {
|
||||||
|
headers = map[string]string{}
|
||||||
|
}
|
||||||
|
if _, ok := headers["Content-Type"]; !ok {
|
||||||
|
headers["Content-Type"] = "text/vcard"
|
||||||
|
}
|
||||||
|
return davTaskRequest(s, auth, method, path, body, headers)
|
||||||
|
}
|
||||||
|
func cardSync(token string, limit string) string {
|
||||||
|
return `<d:sync-collection xmlns:d="DAV:"><d:sync-token>` + xmlText(token) + `</d:sync-token><d:sync-level>1</d:sync-level><d:prop><d:getetag/></d:prop>` + limit + `</d:sync-collection>`
|
||||||
|
}
|
||||||
|
func responseSync(t *testing.T, w *httptest.ResponseRecorder) string {
|
||||||
|
t.Helper()
|
||||||
|
var value struct {
|
||||||
|
Token string `xml:"sync-token"`
|
||||||
|
}
|
||||||
|
if e := xml.Unmarshal(w.Body.Bytes(), &value); e != nil || value.Token == "" {
|
||||||
|
t.Fatal(e, w.Body)
|
||||||
|
}
|
||||||
|
return value.Token
|
||||||
|
}
|
||||||
|
func TestContactDAVRoundTripAndScopes(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
book := contactDAV + actor + "/contacts/"
|
||||||
|
cred, password, err := s.store.CreateDAVCredential(ctx, domain, actor, "phone", true, 90, "contacts")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(cred.ID+":"+password))
|
||||||
|
request := func(method, path, body string, h map[string]string, want int) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
w := cardRequest(s, auth, method, path, body, h)
|
||||||
|
if w.Code != want {
|
||||||
|
t.Fatalf("%s %s: %d want %d %s", method, path, w.Code, want, w.Body)
|
||||||
|
}
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
options := request("OPTIONS", contactDAV, "", nil, 204)
|
||||||
|
if options.Header().Get("DAV") != "1, addressbook-access" {
|
||||||
|
t.Fatal(options.Header())
|
||||||
|
}
|
||||||
|
home := request("PROPFIND", contactDAV, `<d:propfind xmlns:d="DAV:" xmlns:a="urn:ietf:params:xml:ns:carddav"><d:prop><d:current-user-principal/><a:addressbook-home-set/></d:prop></d:propfind>`, nil, 207)
|
||||||
|
if !strings.Contains(home.Body.String(), contactDAV+actor+"/") {
|
||||||
|
t.Fatal(home.Body)
|
||||||
|
}
|
||||||
|
discovery := request("PROPFIND", contactDAV+actor+"/", "", nil, 207)
|
||||||
|
if !strings.Contains(discovery.Body.String(), book) {
|
||||||
|
t.Fatal(discovery.Body)
|
||||||
|
}
|
||||||
|
empty := request("REPORT", book, cardSync("", ""), nil, 207)
|
||||||
|
emptyToken := responseSync(t, empty)
|
||||||
|
path := book + "client-contact.vcf"
|
||||||
|
request("PUT", path, testCard, map[string]string{"If-None-Match": "*"}, 201)
|
||||||
|
get := request("GET", path, "", nil, 200)
|
||||||
|
tag := get.Header().Get("ETag")
|
||||||
|
request("GET", path, "", map[string]string{"If-None-Match": tag}, 304)
|
||||||
|
request("PUT", path, testCard, map[string]string{"If-None-Match": "*"}, 412)
|
||||||
|
request("PUT", path, testCard, nil, 428)
|
||||||
|
request("PUT", path, testCard, map[string]string{"If-Match": `"999"`}, 412)
|
||||||
|
request("PUT", book+"duplicate.vcf", testCard, map[string]string{"If-None-Match": "*"}, 403)
|
||||||
|
c, err := s.store.ContactDAVResource(ctx, domain, actor, "client-contact.vcf")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c.Name = "Webで変更"
|
||||||
|
c, err = s.store.SaveContact(ctx, domain, actor, c, false)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
delta := request("REPORT", book, cardSync(emptyToken, ""), nil, 207)
|
||||||
|
if !strings.Contains(delta.Body.String(), path) || strings.Contains(delta.Body.String(), "Webで変更") {
|
||||||
|
t.Fatal(delta.Body)
|
||||||
|
}
|
||||||
|
synced := responseSync(t, delta)
|
||||||
|
multi := `<a:addressbook-multiget xmlns:a="urn:ietf:params:xml:ns:carddav" xmlns:d="DAV:"><d:prop><d:getetag/><a:address-data/></d:prop><d:href>` + path + `</d:href><d:href>` + book + `missing.vcf</d:href></a:addressbook-multiget>`
|
||||||
|
got := request("REPORT", book, multi, nil, 207)
|
||||||
|
if !strings.Contains(got.Body.String(), "Webで変更") || !strings.Contains(got.Body.String(), "X-PRIVATE:keep") || !strings.Contains(got.Body.String(), "404 Not Found") {
|
||||||
|
t.Fatal(got.Body)
|
||||||
|
}
|
||||||
|
request("DELETE", path, "", map[string]string{"If-Match": store.ContactETag(c)}, 204)
|
||||||
|
request("GET", path, "", nil, 404)
|
||||||
|
delta = request("REPORT", book, cardSync(synced, ""), nil, 207)
|
||||||
|
if !strings.Contains(delta.Body.String(), path) || !strings.Contains(delta.Body.String(), "404 Not Found") {
|
||||||
|
t.Fatal(delta.Body)
|
||||||
|
}
|
||||||
|
request("REPORT", book, cardSync("urn:foreign:123", ""), nil, 403)
|
||||||
|
request("PUT", path, testCard, map[string]string{"If-None-Match": "*"}, 201)
|
||||||
|
c, err = s.store.ContactDAVResource(ctx, domain, actor, "client-contact.vcf")
|
||||||
|
if err != nil || c.Deleted {
|
||||||
|
t.Fatal(c, err)
|
||||||
|
}
|
||||||
|
if w := cardRequest(s, auth, "GET", contactsAPI+"items", "", nil); w.Code != 401 {
|
||||||
|
t.Fatal("DAV credential leaked to API", w.Code)
|
||||||
|
}
|
||||||
|
if w := cardRequest(s, auth, "PROPFIND", taskDAVRoot, "", nil); w.Code != 401 {
|
||||||
|
t.Fatal("contact credential grants tasks", w.Code)
|
||||||
|
}
|
||||||
|
// The legacy 'all' scope remains calendar+tasks, not newly added contacts.
|
||||||
|
all, pass, e := s.store.CreateDAVCredential(ctx, domain, actor, "old", true, 1, "all")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
otherAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(all.ID+":"+pass))
|
||||||
|
if w := cardRequest(s, otherAuth, "PROPFIND", contactDAV, "", nil); w.Code != 401 {
|
||||||
|
t.Fatal("old authority expanded", w.Code)
|
||||||
|
}
|
||||||
|
request("PROPFIND", contactDAV+uuid.NewString()+"/contacts/", "", nil, 404)
|
||||||
|
if e = s.store.RevokeTaskDAVCredential(ctx, domain, actor, cred.ID); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
request("GET", path, "", nil, 401)
|
||||||
|
if _, e = s.store.SaveContactDAV(ctx, domain, actor, cred.ID, "client-contact.vcf", testCard, c.Version, false); e != store.ErrAccessDenied {
|
||||||
|
t.Fatal("revoked writer", e)
|
||||||
|
}
|
||||||
|
// A normal session can still edit its own address book.
|
||||||
|
if w := cardRequest(s, "Bearer "+token, "GET", path, "", nil); w.Code != 200 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContactDAVPaginationHistoryAndBoundaries(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
auth := "Bearer " + token
|
||||||
|
book := contactDAV + actor + "/contacts/"
|
||||||
|
var ids []string
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
id := uuid.NewString()
|
||||||
|
ids = append(ids, id)
|
||||||
|
_, e := s.store.SaveContact(ctx, domain, actor, store.Contact{UUID: id, Name: "Person"}, false)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
first := cardRequest(s, auth, "REPORT", book, cardSync("", `<d:limit><d:nresults>1</d:nresults></d:limit>`), nil)
|
||||||
|
if first.Code != 207 || !strings.Contains(first.Body.String(), "507 Insufficient Storage") {
|
||||||
|
t.Fatal(first.Code, first.Body)
|
||||||
|
}
|
||||||
|
second := cardRequest(s, auth, "REPORT", book, cardSync(responseSync(t, first), ""), nil)
|
||||||
|
if second.Code != 207 || strings.Contains(second.Body.String(), "507 Insufficient Storage") {
|
||||||
|
t.Fatal(second.Code, second.Body)
|
||||||
|
}
|
||||||
|
var r struct {
|
||||||
|
Responses []struct {
|
||||||
|
Href string `xml:"href"`
|
||||||
|
} `xml:"response"`
|
||||||
|
}
|
||||||
|
if e := xml.Unmarshal(second.Body.Bytes(), &r); e != nil || len(r.Responses) != 2 {
|
||||||
|
t.Fatal(e, second.Body)
|
||||||
|
}
|
||||||
|
c, e := s.store.Contact(ctx, domain, actor, ids[0])
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
c.Name = "Changed"
|
||||||
|
c, e = s.store.SaveContact(ctx, domain, actor, c, false)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
h, e := s.store.ContactHistory(ctx, domain, actor, c.UUID, 0)
|
||||||
|
if e != nil || len(h) != 2 {
|
||||||
|
t.Fatal(h, e)
|
||||||
|
}
|
||||||
|
restored, e := s.store.RestoreContactRevision(ctx, domain, actor, c.UUID, 1, c.Version)
|
||||||
|
if e != nil || restored.Name != "Person" || restored.Version != 3 {
|
||||||
|
t.Fatal(restored, e)
|
||||||
|
}
|
||||||
|
if _, e = s.store.RestoreContactRevision(ctx, domain, actor, c.UUID, 1, c.Version); e != store.ErrTaskConflict {
|
||||||
|
t.Fatal("stale restore", e)
|
||||||
|
}
|
||||||
|
raw, e := s.store.ExportContacts(ctx, domain, actor)
|
||||||
|
if e != nil || strings.Count(raw, "BEGIN:VCARD") != 3 {
|
||||||
|
t.Fatal(e, raw)
|
||||||
|
}
|
||||||
|
history := cardRequest(s, auth, "GET", contactsAPI+"items/"+c.UUID+"/history", "", nil)
|
||||||
|
if history.Code != 200 {
|
||||||
|
t.Fatal(history.Code, history.Body)
|
||||||
|
}
|
||||||
|
preview := cardRequest(s, auth, "GET", contactsAPI+"items/"+c.UUID+"/history/1", "", nil)
|
||||||
|
if preview.Code != 200 || !strings.Contains(preview.Body.String(), "Person") {
|
||||||
|
t.Fatal(preview.Code, preview.Body)
|
||||||
|
}
|
||||||
|
restoreBody, _ := json.Marshal(map[string]int64{"version": restored.Version, "revision": 1})
|
||||||
|
restore := cardRequest(s, auth, "POST", contactsAPI+"items/"+c.UUID+"/restore", string(restoreBody), map[string]string{"If-Match": store.ContactETag(restored)})
|
||||||
|
if restore.Code != 200 {
|
||||||
|
t.Fatal(restore.Code, restore.Body)
|
||||||
|
}
|
||||||
|
query := `<a:addressbook-query xmlns:a="urn:ietf:params:xml:ns:carddav" xmlns:d="DAV:"><d:prop><d:getetag/></d:prop><a:filter><a:prop-filter name="FN"><a:text-match match-type="equals">Person</a:text-match></a:prop-filter></a:filter></a:addressbook-query>`
|
||||||
|
found := cardRequest(s, auth, "REPORT", book, query, nil)
|
||||||
|
if found.Code != 207 {
|
||||||
|
t.Fatal(found.Code, found.Body)
|
||||||
|
}
|
||||||
|
for _, body := range []string{strings.Replace(query, `name="FN"`, `name="BAD NAME"`, 1), strings.Replace(query, `match-type="equals"`, `collation="unsupported"`, 1)} {
|
||||||
|
w := cardRequest(s, auth, "REPORT", book, body, nil)
|
||||||
|
if w.Code != 403 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xmlBomb := `<!DOCTYPE x [<!ENTITY x "bomb">]><d:propfind xmlns:d="DAV:"/>`
|
||||||
|
if w := cardRequest(s, auth, "PROPFIND", book, xmlBomb, nil); w.Code != 400 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
foreign := `<a:addressbook-multiget xmlns:a="urn:ietf:params:xml:ns:carddav" xmlns:d="DAV:"><d:prop><d:getetag/></d:prop><d:href>https://evil.invalid` + book + `a.vcf</d:href></a:addressbook-multiget>`
|
||||||
|
if w := cardRequest(s, auth, "REPORT", book, foreign, nil); w.Code != 400 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
read, pass, e := s.store.CreateDAVCredential(ctx, domain, actor, "readonly", false, 1, "contacts")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
readonly := "Basic " + base64.StdEncoding.EncodeToString([]byte(read.ID+":"+pass))
|
||||||
|
if w := cardRequest(s, readonly, "PUT", book+"new.vcf", testCard, map[string]string{"If-None-Match": "*"}); w.Code != 403 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
if e = s.setSystemExtensionEnabled(domain, "organizer.contacts", false); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if w := cardRequest(s, auth, "PROPFIND", book, "", nil); w.Code != 404 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package server
|
|||||||
func init() {
|
func init() {
|
||||||
for lang, entries := range map[string]map[string]string{
|
for lang, entries := range map[string]map[string]string{
|
||||||
"en": {
|
"en": {
|
||||||
|
"contacts.title": "Private address book", "contacts.help": "Private contacts, vCard import/export and email address lookup.",
|
||||||
"contact.title": "Contact details", "contact.phone": "Phone number",
|
"contact.title": "Contact details", "contact.phone": "Phone number",
|
||||||
"contact.help": "Private by default, independently of your profile. A tap opens the phone app. Leave blank to remove. Use 3–15 digits with an optional leading +, spaces, hyphens or parentheses; extensions and service codes are not supported.",
|
"contact.help": "Private by default, independently of your profile. A tap opens the phone app. Leave blank to remove. Use 3–15 digits with an optional leading +, spaces, hyphens or parentheses; extensions and service codes are not supported.",
|
||||||
"contact.visibility_help": "The profile audience remains the upper limit. Anonymous access also requires the domain to permit public profiles. Administrators do not automatically see private numbers.",
|
"contact.visibility_help": "The profile audience remains the upper limit. Anonymous access also requires the domain to permit public profiles. Administrators do not automatically see private numbers.",
|
||||||
@@ -10,6 +11,7 @@ func init() {
|
|||||||
"contact.invalid_phone": "Enter a phone number with 3–15 digits and optional leading +; only spaces, hyphens and parentheses may separate digits.",
|
"contact.invalid_phone": "Enter a phone number with 3–15 digits and optional leading +; only spaces, hyphens and parentheses may separate digits.",
|
||||||
},
|
},
|
||||||
"ja": {
|
"ja": {
|
||||||
|
"contacts.title": "個人アドレス帳", "contacts.help": "非公開の連絡先、vCard入出力、メールアドレス検索。",
|
||||||
"contact.title": "連絡先", "contact.phone": "電話番号",
|
"contact.title": "連絡先", "contact.phone": "電話番号",
|
||||||
"contact.help": "プロフィールとは別に、既定で非公開です。タップすると電話アプリを開きます。空欄で削除。3〜15桁の数字と先頭の+、空白・ハイフン・括弧を使用できます。内線やサービスコードは未対応です。",
|
"contact.help": "プロフィールとは別に、既定で非公開です。タップすると電話アプリを開きます。空欄で削除。3〜15桁の数字と先頭の+、空白・ハイフン・括弧を使用できます。内線やサービスコードは未対応です。",
|
||||||
"contact.visibility_help": "プロフィールの公開範囲を上限とします。匿名公開にはドメイン側の許可も必要です。管理者でも非公開の番号は表示されません。",
|
"contact.visibility_help": "プロフィールの公開範囲を上限とします。匿名公開にはドメイン側の許可も必要です。管理者でも非公開の番号は表示されません。",
|
||||||
|
|||||||
@@ -0,0 +1,227 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const contactsAPI = "/_/api/v1/extension/organizer.contacts/"
|
||||||
|
|
||||||
|
func contactRoute(p string) bool {
|
||||||
|
return contactDAVRoute(p) || p == "/v/plan/contacts" || strings.HasPrefix(p, contactsAPI)
|
||||||
|
}
|
||||||
|
func (s *Server) handleContacts(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
if !s.systemExtensionEnabled(domain, "organizer.contacts") {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actor, active := s.calendarActor(r)
|
||||||
|
if actor == "" {
|
||||||
|
s.authRequired(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method != "GET" && r.Method != "HEAD" && !active {
|
||||||
|
taskError(w, store.ErrAccessDenied)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Path == "/v/plan/contacts" {
|
||||||
|
if r.Method != "GET" && r.Method != "HEAD" {
|
||||||
|
w.WriteHeader(405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, _, e := s.store.Contacts(r.Context(), domain, actor, "", ""); e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.renderWithContext(w, r, "contacts.gohtml", map[string]any{"Title": "Contacts", "ContactWritable": active, "Path": r.URL.Path})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
key := strings.TrimPrefix(r.URL.Path, contactsAPI)
|
||||||
|
if key == "export.vcf" && (r.Method == "GET" || r.Method == "HEAD") {
|
||||||
|
raw, e := s.store.ExportContacts(r.Context(), domain, actor)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/vcard; charset=utf-8")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="contacts.vcf"`)
|
||||||
|
w.Header().Set("Content-Length", strconv.Itoa(len(raw)))
|
||||||
|
if r.Method == "GET" {
|
||||||
|
io.WriteString(w, raw)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
parts := strings.Split(key, "/")
|
||||||
|
if len(parts) >= 3 && parts[0] == "items" && (parts[2] == "history" || parts[2] == "restore") {
|
||||||
|
id, e := uuid.Parse(parts[1])
|
||||||
|
if e != nil || id.String() != parts[1] {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if parts[2] == "history" && r.Method == "GET" {
|
||||||
|
if len(parts) == 4 {
|
||||||
|
revision, e := strconv.ParseInt(parts[3], 10, 64)
|
||||||
|
if e != nil || revision < 1 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c, e := s.store.ContactAtRevision(r.Context(), domain, actor, parts[1], revision)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"item": c})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(parts) != 3 {
|
||||||
|
w.WriteHeader(404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
before := int64(0)
|
||||||
|
if v := r.URL.Query().Get("before"); v != "" {
|
||||||
|
before, e = strconv.ParseInt(v, 10, 64)
|
||||||
|
if e != nil || before < 1 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
items, e := s.store.ContactHistory(r.Context(), domain, actor, parts[1], before)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next := int64(0)
|
||||||
|
if len(items) == 100 {
|
||||||
|
next = items[99].Version
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"items": items, "next": next})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if parts[2] == "restore" && len(parts) == 3 && r.Method == "POST" {
|
||||||
|
var input struct {
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
Revision int64 `json:"revision"`
|
||||||
|
}
|
||||||
|
if !taskJSON(w, r, &input) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if input.Version < 1 || input.Revision < 1 {
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Header.Get("If-Match") == "" {
|
||||||
|
w.WriteHeader(428)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Header.Get("If-Match") != `"`+strconv.FormatInt(input.Version, 10)+`"` {
|
||||||
|
w.WriteHeader(412)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c, e := s.store.RestoreContactRevision(r.Context(), domain, actor, parts[1], input.Revision, input.Version)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("ETag", store.ContactETag(c))
|
||||||
|
writeEventJSON(w, 200, map[string]any{"item": c})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if key == "items" && r.Method == "GET" {
|
||||||
|
items, next, e := s.store.ListContacts(r.Context(), domain, actor, r.URL.Query().Get("q"), r.URL.Query().Get("after"), r.URL.Query().Get("deleted") == "1")
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"items": items, "next": next})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if key == "import" && r.Method == "POST" {
|
||||||
|
raw, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 65536))
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c, e := s.store.SaveContact(r.Context(), domain, actor, store.Contact{UUID: uuid.NewString(), VCard: string(raw)}, true)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 201, map[string]any{"item": c})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id := strings.TrimPrefix(key, "items/")
|
||||||
|
export := strings.HasSuffix(id, ".vcf")
|
||||||
|
if export {
|
||||||
|
id = strings.TrimSuffix(id, ".vcf")
|
||||||
|
}
|
||||||
|
if key != "items" {
|
||||||
|
if u, e := uuid.Parse(id); e != nil || u.String() != id {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if key != "items" && (r.Method == "GET" || r.Method == "HEAD") {
|
||||||
|
c, e := s.store.Contact(r.Context(), domain, actor, id)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("ETag", `"`+strconv.FormatInt(c.Version, 10)+`"`)
|
||||||
|
if export {
|
||||||
|
w.Header().Set("Content-Type", "text/vcard; charset=utf-8")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="contact.vcf"`)
|
||||||
|
w.Write([]byte(c.VCard))
|
||||||
|
} else {
|
||||||
|
writeEventJSON(w, 200, map[string]any{"item": c})
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !export && (key == "items" && r.Method == "POST" || key != "items" && r.Method == "PUT") {
|
||||||
|
var c store.Contact
|
||||||
|
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 128<<10))
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
if decoder.Decode(&c) != nil || decoder.Decode(&struct{}{}) != io.EOF {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if key == "items" {
|
||||||
|
if c.Version != 0 {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if c.UUID != id {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Header.Get("If-Match") == "" {
|
||||||
|
w.WriteHeader(428)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Header.Get("If-Match") != `"`+strconv.FormatInt(c.Version, 10)+`"` {
|
||||||
|
taskError(w, store.ErrTaskConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c, e := s.store.SaveContact(r.Context(), domain, actor, c, false)
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("ETag", `"`+strconv.FormatInt(c.Version, 10)+`"`)
|
||||||
|
writeEventJSON(w, 200, map[string]any{"item": c})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Allow", "GET, HEAD, POST, PUT")
|
||||||
|
w.WriteHeader(405)
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"net/http/httptest"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestContactsPreserveImportAndIsolation(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
raw := "BEGIN:VCARD\r\nVERSION:4.0\r\nUID:urn:test:person\r\nFN:田中\r\nEMAIL;TYPE=work:tanaka@example.invalid\r\nTEL;TYPE=cell:1234\r\nX-PRIVATE:keep\\,this\r\nPHOTO:https://example.invalid/do-not-fetch\r\nEND:VCARD\r\n"
|
||||||
|
c, e := s.store.SaveContact(ctx, domain, actor, store.Contact{UUID: uuid.NewString(), VCard: raw}, true)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
repeat, e := s.store.SaveContact(ctx, domain, actor, store.Contact{UUID: uuid.NewString(), VCard: raw}, true)
|
||||||
|
if e != nil || repeat.UUID != c.UUID {
|
||||||
|
t.Fatal("not idempotent", e)
|
||||||
|
}
|
||||||
|
c.Name = "変更"
|
||||||
|
c, e = s.store.SaveContact(ctx, domain, actor, c, false)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for _, preserved := range []string{"EMAIL;TYPE=work:", "TEL;TYPE=cell:", "X-PRIVATE:keep\\,this", "PHOTO:https:"} {
|
||||||
|
if !strings.Contains(c.VCard, preserved) {
|
||||||
|
t.Fatal("lost", preserved)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
old := c
|
||||||
|
old.Version--
|
||||||
|
if _, e = s.store.SaveContact(ctx, domain, actor, old, false); e != store.ErrTaskConflict {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e = s.store.Contact(ctx, domain, uuid.NewString(), c.UUID); e == nil {
|
||||||
|
t.Fatal("other user read")
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest("GET", "http://localhost"+contactsAPI+"items?q=tanaka", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
s.handleContacts(w, req)
|
||||||
|
if w.Code != 200 || !strings.Contains(w.Body.String(), "変更") {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
c.Deleted = true
|
||||||
|
if _, e = s.store.SaveContact(ctx, domain, actor, c, false); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
items, _, e := s.store.Contacts(ctx, domain, actor, "", "")
|
||||||
|
if e != nil || len(items) != 0 {
|
||||||
|
t.Fatal(items, e)
|
||||||
|
}
|
||||||
|
if e = s.setSystemExtensionEnabled(domain, "organizer.contacts", false); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e = s.store.Contact(ctx, domain, actor, c.UUID); e != store.ErrAccessDenied {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestContactFormatValidation(t *testing.T) {
|
||||||
|
for _, raw := range []string{"BEGIN:VCARD\nVERSION:2.1\nFN:x\nEND:VCARD\n", "BEGIN:VCARD\nVERSION:4.0\nFN;ENCODING=QUOTED-PRINTABLE:x\nEND:VCARD\n", "BEGIN:VCARD\nVERSION:4.0\nFN:x\nmalformed\nEND:VCARD\n"} {
|
||||||
|
if _, e := store.ParseContact(raw); e == nil {
|
||||||
|
t.Fatal("accepted malformed/legacy")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raw := "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:" + strings.Repeat("名", 90) + "\r\nNOTE:one\\ntwo\r\nEND:VCARD\r\n"
|
||||||
|
c, e := store.ParseContact(raw)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
again, e := store.ParseContact(c.VCard)
|
||||||
|
if e != nil || again.Name != c.Name || again.Notes != "one\ntwo" {
|
||||||
|
t.Fatal(again, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -40,6 +40,9 @@ func (s *Server) davActor(w http.ResponseWriter, r *http.Request, requested stri
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
w.Header().Set("WWW-Authenticate", `Basic realm="PagesWiki CalDAV", charset="UTF-8"`)
|
w.Header().Set("WWW-Authenticate", `Basic realm="PagesWiki CalDAV", charset="UTF-8"`)
|
||||||
|
if requested == "contacts" {
|
||||||
|
w.Header().Set("WWW-Authenticate", `Basic realm="PagesWiki CardDAV", charset="UTF-8"`)
|
||||||
|
}
|
||||||
w.WriteHeader(401)
|
w.WriteHeader(401)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -87,11 +90,11 @@ func (s *Server) handleDAVHome(w http.ResponseWriter, r *http.Request) {
|
|||||||
{Space: calNS, Local: "calendar-home-set"}: "<d:href>" + calendarDAV + "</d:href>",
|
{Space: calNS, Local: "calendar-home-set"}: "<d:href>" + calendarDAV + "</d:href>",
|
||||||
}}}
|
}}}
|
||||||
rows[0].props[xml.Name{Space: davNS, Local: "current-user-privilege-set"}] = davPrivileges(false)
|
rows[0].props[xml.Name{Space: davNS, Local: "current-user-privilege-set"}] = davPrivileges(false)
|
||||||
if writable && tasks && scope != "calendar" {
|
if writable && tasks && (scope == "tasks" || scope == "all") {
|
||||||
rows[0].props[xml.Name{Space: davNS, Local: "current-user-privilege-set"}] += "<d:privilege><d:bind/></d:privilege>"
|
rows[0].props[xml.Name{Space: davNS, Local: "current-user-privilege-set"}] += "<d:privilege><d:bind/></d:privilege>"
|
||||||
}
|
}
|
||||||
if r.Header.Get("Depth") == "1" {
|
if r.Header.Get("Depth") == "1" {
|
||||||
if calendars && scope != "tasks" {
|
if calendars && (scope == "calendar" || scope == "all") {
|
||||||
repo, err := s.calendars()
|
repo, err := s.calendars()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
calendarError(w, err)
|
calendarError(w, err)
|
||||||
@@ -108,7 +111,7 @@ func (s *Server) handleDAVHome(w http.ResponseWriter, r *http.Request) {
|
|||||||
rows = append(rows, row)
|
rows = append(rows, row)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if tasks && scope != "calendar" {
|
if tasks && (scope == "tasks" || scope == "all") {
|
||||||
row := taskDAVCollectionRow()
|
row := taskDAVCollectionRow()
|
||||||
title, err := s.store.TaskDAVDefaultTitle(r.Context(), domain, actor)
|
title, err := s.store.TaskDAVDefaultTitle(r.Context(), domain, actor)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -137,7 +140,7 @@ func davPrivileges(write bool) string {
|
|||||||
func (s *Server) handleDAVCredentials(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleDAVCredentials(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Cache-Control", "private, no-store")
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
domain := s.domainUUIDForRequest(r)
|
domain := s.domainUUIDForRequest(r)
|
||||||
if !s.systemExtensionEnabled(domain, "organizer.tasks") && !s.systemExtensionEnabled(domain, "organizer.calendar") {
|
if !s.systemExtensionEnabled(domain, "organizer.tasks") && !s.systemExtensionEnabled(domain, "organizer.calendar") && !s.systemExtensionEnabled(domain, "organizer.contacts") {
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ func (s *Server) withStandbyReadOnly(next http.Handler) http.Handler {
|
|||||||
// V1 standby does not serve organizer or DAV endpoints: their current
|
// V1 standby does not serve organizer or DAV endpoints: their current
|
||||||
// read paths repair file-backed indexes and update credential metadata.
|
// read paths repair file-backed indexes and update credential metadata.
|
||||||
// They become available after promotion; no false successful sync responses.
|
// They become available after promotion; no false successful sync responses.
|
||||||
for _, prefix := range []string{"/v/plan", "/v/calendar", "/v/event", "/v/tasks", "/_/api/v1/calendar", "/_/api/v1/caldav", "/_/api/v1/task", "/_/api/v1/extension/", "/.well-known/caldav"} {
|
for _, prefix := range []string{"/v/plan", "/v/calendar", "/v/event", "/v/tasks", "/_/api/v1/calendar", "/_/api/v1/caldav", "/_/api/v1/carddav", "/_/api/v1/task", "/_/api/v1/extension/", "/.well-known/caldav", "/.well-known/carddav"} {
|
||||||
if strings.HasPrefix(r.URL.Path, prefix) {
|
if strings.HasPrefix(r.URL.Path, prefix) {
|
||||||
fail("organizer/DAV read service requires DR promotion in this version")
|
fail("organizer/DAV read service requires DR promotion in this version")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -100,6 +100,9 @@ var mutationPrefixPolicies = []struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func policyForRequest(r *http.Request) endpointPolicy {
|
func policyForRequest(r *http.Request) endpointPolicy {
|
||||||
|
if personalOrganizerSettings(r) {
|
||||||
|
return endpointPolicy{Name: "organizer.settings", Capability: "read", Target: targetDomain, Resolver: resolveHandler}
|
||||||
|
}
|
||||||
if taskRoute(r.URL.Path) {
|
if taskRoute(r.URL.Path) {
|
||||||
return endpointPolicy{Name: "tasks.handler", Capability: "read", Target: targetDomain, Resolver: resolveHandler}
|
return endpointPolicy{Name: "tasks.handler", Capability: "read", Target: targetDomain, Resolver: resolveHandler}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ func (s *Server) registeredEventHandlers() *dregarnuhr.Registry {
|
|||||||
s.eventHandlersOnce.Do(func() {
|
s.eventHandlersOnce.Do(func() {
|
||||||
registry := &dregarnuhr.Registry{}
|
registry := &dregarnuhr.Registry{}
|
||||||
handlers := map[string]dregarnuhr.Handler{
|
handlers := map[string]dregarnuhr.Handler{
|
||||||
|
store.TaskDigestEventType: s.deliverTaskDigests,
|
||||||
store.NotificationPushEventType: func(ctx context.Context, job *store.EventJob) error {
|
store.NotificationPushEventType: func(ctx context.Context, job *store.EventJob) error {
|
||||||
return s.deliverNotificationPushContext(ctx, job)
|
return s.deliverNotificationPushContext(ctx, job)
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -73,6 +73,9 @@ func (s *Server) startEventScheduler() {
|
|||||||
if err := s.store.EnsureTaskFocusEvent(); err != nil {
|
if err := s.store.EnsureTaskFocusEvent(); err != nil {
|
||||||
log.Printf("focus timer initialization failed: %v", err)
|
log.Printf("focus timer initialization failed: %v", err)
|
||||||
}
|
}
|
||||||
|
if err := s.store.EnsureTaskDigestEvent(); err != nil {
|
||||||
|
log.Printf("task digest initialization failed: %v", err)
|
||||||
|
}
|
||||||
if err := s.store.EnsureNotificationPushEvent(); err != nil {
|
if err := s.store.EnsureNotificationPushEvent(); err != nil {
|
||||||
log.Printf("notification push initialization failed: %v", err)
|
log.Printf("notification push initialization failed: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,6 +35,12 @@ func SetDAVAuthOutcome(r *http.Request, outcome string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func davLogTarget(path string) string {
|
func davLogTarget(path string) string {
|
||||||
|
if path == "/.well-known/carddav" {
|
||||||
|
return "carddav_discovery"
|
||||||
|
}
|
||||||
|
if path == "/_/api/v1/carddav" || strings.HasPrefix(path, "/_/api/v1/carddav/") {
|
||||||
|
return "carddav"
|
||||||
|
}
|
||||||
const root = "/_/api/v1/caldav"
|
const root = "/_/api/v1/caldav"
|
||||||
p := strings.TrimSuffix(path, "/")
|
p := strings.TrimSuffix(path, "/")
|
||||||
switch p {
|
switch p {
|
||||||
|
|||||||
@@ -77,10 +77,12 @@ func TestDAVLogTarget(t *testing.T) {
|
|||||||
for path, want := range map[string]string{
|
for path, want := range map[string]string{
|
||||||
"/_/api/v1/caldav": "home", "/_/api/v1/caldav/": "home",
|
"/_/api/v1/caldav": "home", "/_/api/v1/caldav/": "home",
|
||||||
"/_/api/v1/caldav/tasks/": "task_home", "/_/api/v1/caldav/tasks/default": "task_collection",
|
"/_/api/v1/caldav/tasks/": "task_home", "/_/api/v1/caldav/tasks/default": "task_collection",
|
||||||
"/_/api/v1/caldav/tasks/default/private.ics": "task_resource",
|
"/_/api/v1/caldav/tasks/default/private.ics": "task_resource",
|
||||||
"/_/api/v1/caldav/private/": "calendar_collection",
|
"/_/api/v1/caldav/private/": "calendar_collection",
|
||||||
"/.well-known/caldav": "well_known",
|
"/.well-known/caldav": "well_known",
|
||||||
"/_/api/v1/caldav-credentials": "", "/health": "",
|
"/.well-known/carddav": "carddav_discovery",
|
||||||
|
"/_/api/v1/carddav/private-owner/private.vcf": "carddav",
|
||||||
|
"/_/api/v1/caldav-credentials": "", "/health": "",
|
||||||
} {
|
} {
|
||||||
if got := davLogTarget(path); got != want {
|
if got := davLogTarget(path); got != want {
|
||||||
t.Errorf("%s: %q != %q", path, got, want)
|
t.Errorf("%s: %q != %q", path, got, want)
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ func NormalizePath(
|
|||||||
// Hosted adapter assets use directory-relative module and worker URLs.
|
// Hosted adapter assets use directory-relative module and worker URLs.
|
||||||
// DAV collections also require the slash: removing it conflicts with
|
// DAV collections also require the slash: removing it conflicts with
|
||||||
// ServeMux's collection redirect and causes an infinite redirect loop.
|
// ServeMux's collection redirect and causes an infinite redirect loop.
|
||||||
if strings.HasPrefix(p, "/_/adaptor/") || strings.HasPrefix(p, "/_/api/v1/caldav/") {
|
if strings.HasPrefix(p, "/_/adaptor/") || strings.HasPrefix(p, "/_/api/v1/caldav/") || strings.HasPrefix(p, "/_/api/v1/carddav/") {
|
||||||
next.ServeHTTP(w, r)
|
next.ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestNormalizePathDAVCollections(t *testing.T) {
|
func TestNormalizePathDAVCollections(t *testing.T) {
|
||||||
for _, path := range []string{"/_/api/v1/caldav/", "/_/api/v1/caldav/tasks/", "/_/api/v1/caldav/tasks/default/", "/_/api/v1/caldav/calendar-id/"} {
|
for _, path := range []string{"/_/api/v1/caldav/", "/_/api/v1/caldav/tasks/", "/_/api/v1/caldav/tasks/default/", "/_/api/v1/caldav/calendar-id/", "/_/api/v1/carddav/", "/_/api/v1/carddav/actor/contacts/"} {
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(401) })
|
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(401) })
|
||||||
for _, method := range []string{"GET", "OPTIONS", "PROPFIND", "REPORT"} {
|
for _, method := range []string{"GET", "OPTIONS", "PROPFIND", "REPORT"} {
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func personalOrganizerSettings(r *http.Request) bool {
|
||||||
|
return r.URL.Path == "/-/sys/config" && r.URL.Query().Get("panel") == "organizer" && (r.Method == "GET" || r.Method == "HEAD")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleOrganizerDashboard(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != "GET" && r.Method != "HEAD" {
|
||||||
|
w.Header().Set("Allow", "GET, HEAD")
|
||||||
|
w.WriteHeader(405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, active, ok := s.taskReady(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
s.renderWithContext(w, r, "organizer_dashboard.gohtml", map[string]any{"TaskWritable": active, "Today": time.Now().In(s.getLocation(domain)).Format("2006-01-02"), "Timezone": s.getTimezoneName(domain)})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleOrganizerSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
actor, active := s.calendarActor(r)
|
||||||
|
if actor == "" {
|
||||||
|
s.authRequired(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.renderWithContext(w, r, "organizer_settings.gohtml", map[string]any{"TaskWritable": active})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleDashboardData(w http.ResponseWriter, r *http.Request, actor string, active bool, kind string) {
|
||||||
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
if kind == "progress" {
|
||||||
|
if r.Method != "GET" {
|
||||||
|
w.Header().Set("Allow", "GET")
|
||||||
|
w.WriteHeader(405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p, err := s.store.DashboardProgress(r.Context(), domain, actor, time.Now().In(s.getLocation(domain)).Format("2006-01-02"))
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, p)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method != "GET" && r.Method != "PUT" {
|
||||||
|
w.Header().Set("Allow", "GET, PUT")
|
||||||
|
w.WriteHeader(405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p, err := s.store.Dashboard(r.Context(), domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "PUT" {
|
||||||
|
if !active {
|
||||||
|
taskError(w, store.ErrAccessDenied)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var input struct {
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
Widgets []store.DashboardWidget `json:"widgets"`
|
||||||
|
}
|
||||||
|
if !taskJSON(w, r, &input) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if input.Version != p.Version {
|
||||||
|
taskError(w, store.ErrTaskConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// An empty dashboard is valid; nil means the initial default layout.
|
||||||
|
if input.Widgets == nil {
|
||||||
|
input.Widgets = []store.DashboardWidget{}
|
||||||
|
}
|
||||||
|
p, err = s.store.SaveDashboard(r.Context(), domain, actor, input.Version, input.Widgets)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func organizerSection(path string) string {
|
||||||
|
switch {
|
||||||
|
case path == "/v/plan/dashboard":
|
||||||
|
return "dashboard"
|
||||||
|
case strings.HasPrefix(path, "/-/sys/config"):
|
||||||
|
return "settings"
|
||||||
|
case path == "/v/plan/contacts":
|
||||||
|
return "contacts"
|
||||||
|
case taskRoute(path):
|
||||||
|
return "tasks"
|
||||||
|
case calendarRoute(path):
|
||||||
|
return "calendar"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
for lang, entries := range map[string]map[string]string{
|
||||||
|
"en": {"organizer.title": "Organizer", "organizer.dashboard": "Dashboard", "organizer.settings": "Personal settings", "organizer.contacts": "Contacts", "organizer.private": "Preferences apply only to you in this Domain. System administration is separate.", "organizer.calendar_defaults": "Default calendars", "organizer.open": "Open"},
|
||||||
|
"ja": {"organizer.title": "オーガナイザー", "organizer.dashboard": "ダッシュボード", "organizer.settings": "個人設定", "organizer.contacts": "連絡先", "organizer.private": "このドメイン内の自分だけに適用する設定です。システムの管理設定とは別です。", "organizer.calendar_defaults": "既定のカレンダー", "organizer.open": "開く"},
|
||||||
|
} {
|
||||||
|
for k, v := range entries {
|
||||||
|
translations[lang][k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/url"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestOrganizerDashboardLayoutIsolationAndCAS(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
w := taskRequest(s, token, "GET", "dashboard", nil, "")
|
||||||
|
if w.Code != 200 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
var layout struct {
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
Widgets []store.DashboardWidget `json:"widgets"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &layout); err != nil || len(layout.Widgets) != 6 {
|
||||||
|
t.Fatal(layout, err)
|
||||||
|
}
|
||||||
|
widgets := []store.DashboardWidget{{ID: "tasks", Width: 7, Height: 4, Tab: "review"}}
|
||||||
|
w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": 0, "widgets": widgets}, "")
|
||||||
|
if w.Code != 200 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
if w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": 0, "widgets": widgets}, ""); w.Code != 412 {
|
||||||
|
t.Fatal("stale layout", w.Code)
|
||||||
|
}
|
||||||
|
p, err := s.store.TaskPreferences(context.Background(), domain, actor)
|
||||||
|
if err != nil || p.Version != 0 {
|
||||||
|
t.Fatal(p, err)
|
||||||
|
}
|
||||||
|
// A legacy CLI preferences write must preserve dashboard metadata.
|
||||||
|
p.Estimate = 90
|
||||||
|
w = taskRequest(s, token, "PUT", "preferences", p, "")
|
||||||
|
if w.Code != 200 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
p, err = s.store.TaskPreferences(context.Background(), domain, actor)
|
||||||
|
if err != nil || p.Estimate != 90 {
|
||||||
|
t.Fatal(p, err)
|
||||||
|
}
|
||||||
|
l, err := s.store.Dashboard(context.Background(), domain, actor)
|
||||||
|
if err != nil || len(l.Widgets) != 1 || l.Version != 1 {
|
||||||
|
t.Fatal(l, err)
|
||||||
|
}
|
||||||
|
// Layout updates cannot postpone the digest scheduler.
|
||||||
|
if _, err = s.store.DB.Exec(`UPDATE organizer_task_preferences SET next_digest_ms=123 WHERE domain_uuid=? AND owner_uuid=?`, domain, actor); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": l.Version, "widgets": []store.DashboardWidget{}}, "")
|
||||||
|
if w.Code != 200 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
var next int64
|
||||||
|
if err = s.store.DB.QueryRow(`SELECT next_digest_ms FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(&next); err != nil || next != 123 {
|
||||||
|
t.Fatal(next, err)
|
||||||
|
}
|
||||||
|
after, err := s.store.TaskPreferences(context.Background(), domain, actor)
|
||||||
|
if err != nil || after.Version != p.Version || after.Estimate != 90 {
|
||||||
|
t.Fatal("layout changed mail consent", after, err)
|
||||||
|
}
|
||||||
|
w = taskRequest(s, token, "GET", "dashboard", nil, "")
|
||||||
|
if err = json.Unmarshal(w.Body.Bytes(), &layout); err != nil || len(layout.Widgets) != 0 {
|
||||||
|
t.Fatal("empty layout reset", layout, err)
|
||||||
|
}
|
||||||
|
for _, invalid := range [][]store.DashboardWidget{{{ID: "iframe", Width: 4, Height: 3}}, {{ID: "tasks", Width: 13, Height: 3, Tab: "inbox"}}, {{ID: "tasks", Width: 4, Height: 3, Tab: "secret"}}, {{ID: "progress", Width: 4, Height: 3}, {ID: "progress", Width: 4, Height: 3}}} {
|
||||||
|
w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": layout.Version, "widgets": invalid}, "")
|
||||||
|
if w.Code != 422 {
|
||||||
|
t.Fatal("invalid accepted", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other, err := s.store.CreatePasswordAccount(domain, "dashboardother", "long test password", "Other", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
otherToken, err := s.store.CreateAuthSession(domain, other.UUID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
w = taskRequest(s, otherToken, "GET", "dashboard", nil, "")
|
||||||
|
if err = json.Unmarshal(w.Body.Bytes(), &layout); err != nil || layout.Version != 0 || len(layout.Widgets) != 6 {
|
||||||
|
t.Fatal("owner leakage", layout, err)
|
||||||
|
}
|
||||||
|
if err = s.store.SetPrincipalState(domain, actor, "readonly"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
token, err = s.store.CreateAuthSession(domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": 3, "widgets": widgets}, ""); w.Code != 403 {
|
||||||
|
t.Fatal("readonly write", w.Code)
|
||||||
|
}
|
||||||
|
if w = taskRequest(s, token, "GET", "dashboard", nil, ""); w.Code != 200 {
|
||||||
|
t.Fatal("readonly read", w.Code)
|
||||||
|
}
|
||||||
|
if w = taskRequest(s, "", "GET", "dashboard", nil, ""); w.Code == 200 {
|
||||||
|
t.Fatal("anonymous dashboard")
|
||||||
|
}
|
||||||
|
if err = s.store.SetConfigInDomain(domain, "system_extension_states", `{"organizer.tasks":false}`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if w = taskRequest(s, token, "GET", "dashboard", nil, ""); w.Code != 404 {
|
||||||
|
t.Fatal("disabled dashboard", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOrganizerPersonalSettingsAreNotAdminAccess(t *testing.T) {
|
||||||
|
s, _, domain, _ := taskFixture(t)
|
||||||
|
u, err := s.store.CreatePasswordAccount(domain, "organizer", "long test password", "Organizer", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
token, err := s.store.CreateAuthSession(domain, u.UUID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
w := configRequest(s, token, "GET", "/-/sys/config?panel=organizer", nil)
|
||||||
|
if w.Code != 200 || !strings.Contains(w.Body.String(), `id="task-productivity"`) {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
if strings.Contains(w.Body.String(), `id="panel-auth"`) || strings.Contains(w.Body.String(), `id="panel-campus`) {
|
||||||
|
t.Fatal("admin data in personal settings")
|
||||||
|
}
|
||||||
|
if w = configRequest(s, token, "GET", "/-/sys/config?panel=auth", nil); w.Code != 403 {
|
||||||
|
t.Fatal("admin access", w.Code)
|
||||||
|
}
|
||||||
|
if w = configRequest(s, token, "POST", "/-/sys/config?panel=organizer", url.Values{"section": {"home"}}); w.Code != 403 {
|
||||||
|
t.Fatal("config mutation", w.Code)
|
||||||
|
}
|
||||||
|
for path, target := range map[string]string{"/v/plan/tasks/settings": "/-/sys/config?panel=organizer", "/v/plan/tasks/report": "/v/plan/dashboard#activity"} {
|
||||||
|
w = configRequest(s, token, "GET", path, nil)
|
||||||
|
if w.Code != 303 || w.Header().Get("Location") != target {
|
||||||
|
t.Fatal(path, w.Code, w.Header())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, path := range []string{"/v/plan/dashboard", "/v/plan/tasks", "/v/plan/contacts", "/v/plan"} {
|
||||||
|
w = configRequest(s, token, "GET", path, nil)
|
||||||
|
if w.Code != 200 || !strings.Contains(w.Body.String(), `class="organizer-nav"`) {
|
||||||
|
t.Fatal(path, w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOrganizerProgressExactAndPrivate(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
today := time.Now().In(s.getLocation(domain)).Format("2006-01-02")
|
||||||
|
for i, status := range []string{"todo", "done", "cancelled", "done"} {
|
||||||
|
item := newTaskRecord("task", "Progress test")
|
||||||
|
item.Status = status
|
||||||
|
item.PlannedOn = today
|
||||||
|
item.Archived = i == 3
|
||||||
|
if _, err := s.store.SaveTask(context.Background(), domain, actor, item, 0); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w := taskRequest(s, token, "GET", "progress", nil, "")
|
||||||
|
var p store.DashboardProgress
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &p); err != nil || w.Code != 200 || p.Total != 2 || p.Done != 1 || p.Date != today {
|
||||||
|
t.Fatal(w.Code, p, err, w.Body)
|
||||||
|
}
|
||||||
|
other, err := s.store.CreatePasswordAccount(domain, "progressother", "long test password", "Other", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
p, err = s.store.DashboardProgress(context.Background(), domain, other.UUID, today)
|
||||||
|
if err != nil || p.Total != 0 {
|
||||||
|
t.Fatal("progress leak", p, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProductivityChromium(t *testing.T) {
|
||||||
|
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
|
||||||
|
t.Skip("opt-in Chromium")
|
||||||
|
}
|
||||||
|
for _, view := range []string{"contacts", "settings", "report", "tasks", "home", "editor"} {
|
||||||
|
sizes := []string{"desktop", "mobile"}
|
||||||
|
if view == "editor" {
|
||||||
|
sizes = append(sizes, "laptop", "mobile-small", "english")
|
||||||
|
}
|
||||||
|
for _, size := range sizes {
|
||||||
|
t.Run(view+"-"+size, func(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
if size == "english" {
|
||||||
|
if err := s.store.SetConfigInDomain(domain, "locale", "en"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { s.renderSearchHome(w, r, "search") })
|
||||||
|
item := newTaskRecord("task", "Browser work task")
|
||||||
|
item.Status = "done"
|
||||||
|
item.Estimate = 60
|
||||||
|
item.Complexity = 3
|
||||||
|
if _, e := s.store.SaveTask(context.Background(), domain, actor, item, 0); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
repo, e := s.calendars()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e = repo.Create(context.Background(), domain, actor, "Command calendar", "local"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
script, e := os.ReadFile("internal/server/testdata/productivity-browser.js")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
if r.Method == "GET" && r.URL.RequestURI() == path {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(rec, r)
|
||||||
|
for k, v := range rec.Header() {
|
||||||
|
w.Header()[k] = v
|
||||||
|
}
|
||||||
|
w.WriteHeader(rec.Code)
|
||||||
|
// The home template uses nonce CSP. Reuse its already generated nonce
|
||||||
|
// only in this synthetic fixture; production HTML is never rewritten.
|
||||||
|
nonce := ""
|
||||||
|
if csp := rec.Header().Get("Content-Security-Policy"); strings.Contains(csp, "'nonce-") {
|
||||||
|
nonce = strings.SplitN(strings.SplitN(csp, "'nonce-", 2)[1], "'", 2)[0]
|
||||||
|
}
|
||||||
|
w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", "<script nonce=\""+nonce+"\">"+string(script)+"</script></body>", 1)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
width, height := "1440", "1000"
|
||||||
|
if size == "mobile" {
|
||||||
|
width, height = "390", "844"
|
||||||
|
}
|
||||||
|
if size == "laptop" {
|
||||||
|
width, height = "1024", "768"
|
||||||
|
}
|
||||||
|
if size == "mobile-small" {
|
||||||
|
width, height = "320", "568"
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
shot := ""
|
||||||
|
if prefix := os.Getenv("PAGESWIKI_PRODUCTIVITY_SCREENSHOT"); prefix != "" {
|
||||||
|
shot = prefix + "-" + view + "-" + size + ".png"
|
||||||
|
}
|
||||||
|
command := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", strings.Replace(server.URL, "127.0.0.1", "localhost", 1)+path, t.TempDir(), shot, width, height)
|
||||||
|
if view == "report" && size == "desktop" {
|
||||||
|
command.Env = append(os.Environ(), "PAGESWIKI_DASHBOARD_DRAG=1")
|
||||||
|
}
|
||||||
|
out, e := command.CombinedOutput()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatalf("%v: %s", e, out)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,13 +9,22 @@ import (
|
|||||||
"os/exec"
|
"os/exec"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestRemoteCLIHTTPIntegration(t *testing.T) {
|
func TestRemoteCLIHTTPIntegration(t *testing.T) {
|
||||||
if _, err := exec.LookPath("python3"); err != nil {
|
if _, err := exec.LookPath("python3"); err != nil {
|
||||||
t.Skip("python3 not installed")
|
t.Skip("python3 not installed")
|
||||||
}
|
}
|
||||||
s, _, _, _ := editorFixture(t)
|
s, _, domain, _ := editorFixture(t)
|
||||||
|
object, err := s.store.CreatePageAtPathInDomain(domain, "/ja-only")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := s.store.SaveRevisionForLanguage(object, "<h1>日本語のページ</h1><p>{{children}}</p>", "", "ja"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
s.mux.HandleFunc("/_/auth/", s.handleAuth)
|
s.mux.HandleFunc("/_/auth/", s.handleAuth)
|
||||||
s.mux.HandleFunc("/v/raw/", s.handleRawView)
|
s.mux.HandleFunc("/v/raw/", s.handleRawView)
|
||||||
s.mux.HandleFunc("/_/api/v1/path-picker", s.handlePathPickerAPI)
|
s.mux.HandleFunc("/_/api/v1/path-picker", s.handlePathPickerAPI)
|
||||||
@@ -33,3 +42,81 @@ func TestRemoteCLIHTTPIntegration(t *testing.T) {
|
|||||||
t.Fatalf("remote CLI: %v\n%s", err, out)
|
t.Fatalf("remote CLI: %v\n%s", err, out)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRemoteCLILanguageForkRequiresWritePermission(t *testing.T) {
|
||||||
|
s, token, domain, object := editorFixture(t)
|
||||||
|
principal := s.mustCLIPrincipal(t, domain, token)
|
||||||
|
if err := s.store.SetPrincipalState(domain, principal, "readonly"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Changing account state revokes old sessions. Use a newly authenticated
|
||||||
|
// readonly session so this exercises write authorization, not expiration.
|
||||||
|
token, err := s.store.CreateAuthSession(domain, principal)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(map[string]any{
|
||||||
|
"object_uuid": object, "body": "<h1>New language</h1>", "lang": "ja",
|
||||||
|
"content_type": "text/html", "base_revision_uuid": "", "editor_principal_uuid": principal,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := httptest.NewRequest("POST", "http://localhost/_/api/v1/revisions/save", bytes.NewReader(body))
|
||||||
|
r.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
if w.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("readonly language fork: %d %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
revision, err := s.store.GetRevisionMetadataForExactLanguage(object, "ja")
|
||||||
|
if err != nil || revision.UUID != "" {
|
||||||
|
t.Fatalf("denied language fork persisted: %s %v", revision.UUID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRemoteCLIOIDCIntegration(t *testing.T) {
|
||||||
|
if _, err := exec.LookPath("python3"); err != nil {
|
||||||
|
t.Skip("python3 not installed")
|
||||||
|
}
|
||||||
|
s, api, domain, _ := editorFixture(t)
|
||||||
|
if err := s.store.SetAuthProviderConfig(domain, store.AuthProviderConfig{Kind: "oidc", Enabled: true, Issuer: "https://id.example", ClientID: "client"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s.mux.HandleFunc("/_/auth/", s.handleAuth)
|
||||||
|
s.mux.HandleFunc("/v/raw/", s.handleRawView)
|
||||||
|
s.mux.HandleFunc("/_/api/v1/path-picker", s.handlePathPickerAPI)
|
||||||
|
principal := s.mustCLIPrincipal(t, domain, api)
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
r.Host = "localhost"
|
||||||
|
// Test-only bridge in this httptest server. The real signed OIDC callback,
|
||||||
|
// browser binding and CSRF flow are covered by TestCLIAuthOIDCFlow.
|
||||||
|
if r.URL.Path == "/__test/cli-approve" {
|
||||||
|
_ = r.ParseForm()
|
||||||
|
browser, err := s.store.CreateBrowserAuthSession(domain, principal, 0)
|
||||||
|
if err == nil {
|
||||||
|
err = s.store.BindCLIAuth(r.Context(), domain, "http://localhost", r.Form.Get("request"), browser)
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
err = s.store.DecideCLIAuth(r.Context(), domain, "http://localhost", r.Form.Get("request"), browser, r.Form.Get("code"), "", true)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "synthetic approval failed", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]bool{"approved": true})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
cmd := exec.CommandContext(ctx, "python3", "pages-cli/test_pages.py", "--oidc-integration")
|
||||||
|
input, _ := json.Marshal(map[string]string{"origin": server.URL})
|
||||||
|
cmd.Stdin = bytes.NewReader(input)
|
||||||
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("CLI OIDC integration: %v %s", err, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -67,6 +67,8 @@ func (s *Server) renderWithContext(
|
|||||||
w.Header().Add("Vary", "Cookie")
|
w.Header().Add("Vary", "Cookie")
|
||||||
data["CalendarEnabled"] = s.systemExtensionEnabled(domainUUID, "organizer.calendar")
|
data["CalendarEnabled"] = s.systemExtensionEnabled(domainUUID, "organizer.calendar")
|
||||||
data["TasksEnabled"] = s.systemExtensionEnabled(domainUUID, "organizer.tasks")
|
data["TasksEnabled"] = s.systemExtensionEnabled(domainUUID, "organizer.tasks")
|
||||||
|
data["ContactsEnabled"] = s.systemExtensionEnabled(domainUUID, "organizer.contacts")
|
||||||
|
data["OrganizerSection"] = organizerSection(r.URL.Path)
|
||||||
if r.URL.Path == "/" {
|
if r.URL.Path == "/" {
|
||||||
data["IsHome"] = true
|
data["IsHome"] = true
|
||||||
data["BookmarkSections"] = s.bookmarkSections(r)
|
data["BookmarkSections"] = s.bookmarkSections(r)
|
||||||
|
|||||||
@@ -84,6 +84,10 @@ func sendMagicLinkSMTPWithTLS(ctx context.Context, config store.AuthProviderConf
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
return deliverSMTPMessage(ctx, config, host, sender, addressee, message, tlsOverride)
|
||||||
|
}
|
||||||
|
|
||||||
|
func deliverSMTPMessage(ctx context.Context, config store.AuthProviderConfig, host, sender, addressee string, message []byte, tlsOverride *tls.Config) error {
|
||||||
ctx, cancel := context.WithTimeout(ctx, smtpDeliveryTimeout)
|
ctx, cancel := context.WithTimeout(ctx, smtpDeliveryTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
connection, err := (&net.Dialer{Timeout: 3 * time.Second}).DialContext(ctx, "tcp", config.SMTPAddress)
|
connection, err := (&net.Dialer{Timeout: 3 * time.Second}).DialContext(ctx, "tcp", config.SMTPAddress)
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTaskCalendarCapture(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
repo, e := s.calendars()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
c, e := repo.Create(context.Background(), domain, actor, "Command calendar", "local")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
input := map[string]any{"request_id": uuid.NewString(), "calendar_uuid": c.ID, "title": "会議", "from": "2026-11-02T09:00", "to": "2026-11-02T10:00"}
|
||||||
|
for range 2 {
|
||||||
|
w := taskRequest(s, token, "POST", "calendar-capture", input, "")
|
||||||
|
if w.Code != 201 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os/exec"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTaskCLIHTTPIntegration(t *testing.T) {
|
||||||
|
if _, e := exec.LookPath("python3"); e != nil {
|
||||||
|
t.Skip("python3 not installed")
|
||||||
|
}
|
||||||
|
s, token, _, _ := taskFixture(t)
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
r.Host = "localhost"
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
cmd := exec.CommandContext(ctx, "python3", "pages-cli/test_task_integration.py")
|
||||||
|
b, _ := json.Marshal(map[string]string{"origin": server.URL, "token": token, "root": t.TempDir()})
|
||||||
|
cmd.Stdin = bytes.NewReader(b)
|
||||||
|
if out, e := cmd.CombinedOutput(); e != nil {
|
||||||
|
t.Fatalf("CLI task integration %v: %s", e, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -64,6 +64,9 @@ func (s *Server) handleTaskDAVCredentials(w http.ResponseWriter, r *http.Request
|
|||||||
if body.Scope != "tasks" {
|
if body.Scope != "tasks" {
|
||||||
endpoint = calendarDAV
|
endpoint = calendarDAV
|
||||||
}
|
}
|
||||||
|
if body.Scope == "contacts" {
|
||||||
|
endpoint = contactDAV
|
||||||
|
}
|
||||||
response := map[string]any{"credential": credential, "username": credential.ID, "password": password, "url": endpoint}
|
response := map[string]any{"credential": credential, "username": credential.ID, "password": password, "url": endpoint}
|
||||||
if body.Scope == "tasks" {
|
if body.Scope == "tasks" {
|
||||||
response["collection"] = taskDAVCollection
|
response["collection"] = taskDAVCollection
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func sendTaskDigestSMTP(ctx context.Context, config store.AuthProviderConfig, recipient, day, body string) error {
|
||||||
|
// Reuse envelope validation and bounded TLS-aware SMTP transport, without
|
||||||
|
// exposing SMTP credentials, recipient or task content to job logs.
|
||||||
|
host, from, to, _, err := smtpMessage(config, recipient, "https://pages.invalid/")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sender, _ := smtpMailbox(config.SMTPFrom)
|
||||||
|
addressee, _ := smtpMailbox(recipient)
|
||||||
|
if len(body) > 128<<10 || len(day) != 10 || strings.ContainsAny(day, "\r\n\x00") {
|
||||||
|
return store.ErrTaskInvalid
|
||||||
|
}
|
||||||
|
encoded := base64.StdEncoding.EncodeToString([]byte(body))
|
||||||
|
var lines strings.Builder
|
||||||
|
for len(encoded) > 76 {
|
||||||
|
lines.WriteString(encoded[:76] + "\r\n")
|
||||||
|
encoded = encoded[76:]
|
||||||
|
}
|
||||||
|
lines.WriteString(encoded + "\r\n")
|
||||||
|
message := []byte(fmt.Sprintf("To: %s\r\nFrom: %s\r\nSubject: PagesWiki tasks %s\r\nDate: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n%s", addressee.String(), sender.String(), day, time.Now().Format(time.RFC1123Z), lines.String()))
|
||||||
|
return deliverSMTPMessage(ctx, config, host, from, to, message, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) deliverTaskDigests(ctx context.Context, job *store.EventJob) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
due, err := s.store.DueTaskDigests(ctx, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sent, uncertain := 0, 0
|
||||||
|
for _, candidate := range due {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
claim, e := s.store.ClaimTaskDigest(ctx, candidate, time.Now())
|
||||||
|
if errors.Is(e, sql.ErrNoRows) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
state := "cancelled"
|
||||||
|
if s.systemExtensionEnabled(claim.Domain, "organizer.tasks") {
|
||||||
|
config, e := s.store.AuthProviderConfig(claim.Domain, "smtp")
|
||||||
|
if e == nil && config.Enabled {
|
||||||
|
items, next, e := s.store.ListTasks(ctx, claim.Domain, claim.Owner, store.TaskQuery{Kind: "task", View: "today", Today: claim.Day, Limit: 100})
|
||||||
|
if e == nil {
|
||||||
|
var body strings.Builder
|
||||||
|
host, _ := s.store.GetDomainEffectiveHost(claim.Domain)
|
||||||
|
base := ""
|
||||||
|
if host != "" && !strings.ContainsAny(host, "/\\\r\n\t @") {
|
||||||
|
base = "https://" + host
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&body, "Tasks / やることリスト — %s (%s)\n\n", claim.Day, claim.Timezone)
|
||||||
|
if len(items) == 0 {
|
||||||
|
body.WriteString("No tasks due or planned today. / 今日の対象タスクはありません。\n")
|
||||||
|
}
|
||||||
|
for _, item := range items {
|
||||||
|
fmt.Fprintf(&body, "- %s\n due/期限: %s | planned/予定: %s | estimate/見積: %d min\n %s/v/plan/task/%s\n", item.Title, item.DueOn, item.PlannedOn, item.Estimate, base, item.UUID)
|
||||||
|
}
|
||||||
|
if next != "" {
|
||||||
|
body.WriteString("\nFirst 100 items only. / 最初の100件です。続きはタスク画面で確認してください。\n")
|
||||||
|
}
|
||||||
|
// Check consent and current account email immediately before send.
|
||||||
|
if recipient, e := s.store.TaskDigestRecipient(ctx, claim); e == nil {
|
||||||
|
state = "uncertain"
|
||||||
|
if e = sendTaskDigestSMTP(ctx, config, recipient, claim.Day, body.String()); e == nil {
|
||||||
|
state = "sent"
|
||||||
|
sent++
|
||||||
|
} else {
|
||||||
|
uncertain++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Persist delivery outcome even if the scheduler context was cancelled.
|
||||||
|
finish, stop := context.WithTimeout(context.Background(), 2*time.Second)
|
||||||
|
e = s.store.FinishTaskDigest(finish, claim, state)
|
||||||
|
stop()
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(due) > 0 {
|
||||||
|
s.addEventProgressLog(ctx, job, fmt.Sprintf("task digest checked=%d sent=%d uncertain=%d", len(due), sent, uncertain))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
cal "pageswiki/internal/calendar"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func taskJSON(w http.ResponseWriter, r *http.Request, output any) bool {
|
||||||
|
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32768))
|
||||||
|
d.DisallowUnknownFields()
|
||||||
|
if d.Decode(output) != nil || d.Decode(&struct{}{}) != io.EOF {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultTask(p store.TaskPreferences, now time.Time) store.TaskRecord {
|
||||||
|
item := store.TaskRecord{Kind: "task", Status: "todo", Bucket: "inbox", Priority: 1, ProjectUUID: p.ProjectUUID, AssigneeUUID: p.AssigneeUUID, Estimate: p.Estimate, Complexity: p.Complexity}
|
||||||
|
for _, date := range []struct {
|
||||||
|
offset *int
|
||||||
|
target *string
|
||||||
|
}{{p.DueDays, &item.DueOn}, {p.StartDays, &item.StartOn}, {p.PlannedDays, &item.PlannedOn}, {p.ReviewDays, &item.ReviewOn}} {
|
||||||
|
if date.offset != nil {
|
||||||
|
*date.target = now.AddDate(0, 0, *date.offset).Format("2006-01-02")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
applyTaskReminderDefaults(&item, p)
|
||||||
|
return item
|
||||||
|
}
|
||||||
|
|
||||||
|
// Undated captures must remain possible, even when reminder defaults are on.
|
||||||
|
// Apply after date overrides, and never apply to updates of existing tasks.
|
||||||
|
func applyTaskReminderDefaults(item *store.TaskRecord, p store.TaskPreferences) {
|
||||||
|
item.NotifyDue = p.NotifyDue && item.DueOn != ""
|
||||||
|
item.NotifyPlanned = p.NotifyPlanned && item.PlannedOn != ""
|
||||||
|
item.ReminderTime = p.ReminderTime
|
||||||
|
if item.ReminderTime == "" {
|
||||||
|
item.ReminderTime = "09:00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type taskCaptureInput struct {
|
||||||
|
RequestID string `json:"request_id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Notes string `json:"notes"`
|
||||||
|
ProjectUUID *string `json:"project_uuid"`
|
||||||
|
AssigneeUUID *string `json:"assignee_uuid"`
|
||||||
|
DueOn *string `json:"due_on"`
|
||||||
|
StartOn *string `json:"start_on"`
|
||||||
|
PlannedOn *string `json:"planned_on"`
|
||||||
|
ReviewOn *string `json:"review_on"`
|
||||||
|
Estimate *int `json:"estimate_minutes"`
|
||||||
|
Complexity *int `json:"complexity"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request, actor string, active bool, kind string) {
|
||||||
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
if r.Method != "GET" && !active {
|
||||||
|
taskError(w, store.ErrAccessDenied)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch kind {
|
||||||
|
case "dashboard", "progress":
|
||||||
|
s.handleDashboardData(w, r, actor, active, kind)
|
||||||
|
return
|
||||||
|
case "calendar-capture":
|
||||||
|
if r.Method == "POST" {
|
||||||
|
if !s.systemExtensionEnabled(domain, "organizer.calendar") {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var input struct {
|
||||||
|
RequestID string `json:"request_id"`
|
||||||
|
CalendarUUID string `json:"calendar_uuid"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Start string `json:"from"`
|
||||||
|
End string `json:"to"`
|
||||||
|
}
|
||||||
|
if !taskJSON(w, r, &input) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if id, e := uuid.Parse(input.RequestID); e != nil || id.String() != input.RequestID || strings.TrimSpace(input.Title) == "" || len(input.Title) > 300 {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, _, e := s.store.ListTasks(r.Context(), domain, actor, store.TaskQuery{Kind: "task", View: "all", Today: time.Now().In(s.getLocation(domain)).Format("2006-01-02"), Limit: 1}); e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
parse := func(value string) (time.Time, error) {
|
||||||
|
if strings.HasSuffix(value, "Z") || len(value) > 19 {
|
||||||
|
return time.Parse(time.RFC3339, value)
|
||||||
|
}
|
||||||
|
v, e := time.ParseInLocation("2006-01-02T15:04", value, s.getLocation(domain))
|
||||||
|
if e == nil && v.Format("2006-01-02T15:04") != value {
|
||||||
|
e = store.ErrTaskInvalid
|
||||||
|
}
|
||||||
|
return v, e
|
||||||
|
}
|
||||||
|
start, e1 := parse(input.Start)
|
||||||
|
end, e2 := parse(input.End)
|
||||||
|
if e1 != nil || e2 != nil || !end.After(start) || end.Sub(start) > 31*24*time.Hour {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
repo, e := s.calendars()
|
||||||
|
if e != nil {
|
||||||
|
taskError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
event, e := cal.Build("", cal.Event{UID: input.RequestID, Summary: input.Title, Start: start, End: end})
|
||||||
|
if e != nil {
|
||||||
|
calendarError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c, event, e := repo.TaskBlock(r.Context(), domain, input.CalendarUUID, actor, input.RequestID, &event)
|
||||||
|
if e != nil {
|
||||||
|
calendarError(w, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 201, map[string]any{"uid": event.UID, "calendar": c.PrettyName})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "preferences":
|
||||||
|
if r.Method == "GET" {
|
||||||
|
p, err := s.store.TaskPreferences(r.Context(), domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if p.Version == 0 {
|
||||||
|
p.Timezone = s.getTimezoneName(domain)
|
||||||
|
}
|
||||||
|
last, err := s.store.LastTaskDigest(r.Context(), domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"preferences": p, "defaults": defaultTask(p, time.Now().In(s.getLocation(domain))), "timezone": s.getTimezoneName(domain), "last_digest": last})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "PUT" {
|
||||||
|
var p store.TaskPreferences
|
||||||
|
if !taskJSON(w, r, &p) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if p.DigestEnabled {
|
||||||
|
principal, err := s.store.PrincipalForSession(domain, s.authTokenFromRequest(r))
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, store.ErrAccessDenied)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err = smtpMailbox(principal.Email); err != nil {
|
||||||
|
writeEventJSON(w, 422, map[string]string{"error": "email_required"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
config, err := s.store.AuthProviderConfig(domain, "smtp")
|
||||||
|
if err != nil || !config.Enabled {
|
||||||
|
writeEventJSON(w, 422, map[string]string{"error": "smtp_unavailable"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p, err := s.store.SaveTaskPreferences(r.Context(), domain, actor, p, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"preferences": p})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "capture":
|
||||||
|
if r.Method == "POST" {
|
||||||
|
var input taskCaptureInput
|
||||||
|
if !taskJSON(w, r, &input) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if id, err := uuid.Parse(input.RequestID); err != nil || id.String() != input.RequestID {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p, err := s.store.TaskPreferences(r.Context(), domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
item := defaultTask(p, time.Now().In(s.getLocation(domain)))
|
||||||
|
item.Title = input.Title
|
||||||
|
item.Notes = input.Notes
|
||||||
|
for _, v := range []struct {
|
||||||
|
from *string
|
||||||
|
to *string
|
||||||
|
}{{input.ProjectUUID, &item.ProjectUUID}, {input.AssigneeUUID, &item.AssigneeUUID}, {input.DueOn, &item.DueOn}, {input.StartOn, &item.StartOn}, {input.PlannedOn, &item.PlannedOn}, {input.ReviewOn, &item.ReviewOn}} {
|
||||||
|
if v.from != nil {
|
||||||
|
*v.to = *v.from
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if input.Estimate != nil {
|
||||||
|
item.Estimate = *input.Estimate
|
||||||
|
}
|
||||||
|
if input.Complexity != nil {
|
||||||
|
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)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.taskResponse(w, r, item, 201)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "work":
|
||||||
|
if r.Method == "GET" {
|
||||||
|
v, err := s.store.ActiveTaskWork(r.Context(), domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"item": v, "server_now_ms": time.Now().UnixMilli()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == "POST" {
|
||||||
|
var input struct {
|
||||||
|
store.TaskWork
|
||||||
|
Action string `json:"action"`
|
||||||
|
}
|
||||||
|
if !taskJSON(w, r, &input) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
v, err := s.store.ChangeTaskWork(r.Context(), domain, actor, input.Action, input.TaskWork, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, map[string]any{"item": v, "server_now_ms": time.Now().UnixMilli()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "report":
|
||||||
|
if r.Method == "GET" {
|
||||||
|
now := time.Now().In(s.getLocation(domain))
|
||||||
|
end := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, now.Location())
|
||||||
|
start := end.AddDate(-1, 0, 0)
|
||||||
|
for _, v := range []struct {
|
||||||
|
key string
|
||||||
|
target *time.Time
|
||||||
|
}{{"from", &start}, {"to", &end}} {
|
||||||
|
if value := r.URL.Query().Get(v.key); value != "" {
|
||||||
|
parsed, err := time.ParseInLocation("2006-01-02", value, now.Location())
|
||||||
|
if err != nil || parsed.Format("2006-01-02") != value {
|
||||||
|
taskError(w, store.ErrTaskInvalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
*v.target = parsed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
report, err := s.store.TaskReport(r.Context(), domain, actor, start, end, now)
|
||||||
|
if err != nil {
|
||||||
|
taskError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, report)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.Header().Set("Allow", map[string]string{"calendar-capture": "POST", "capture": "POST", "work": "GET, POST", "report": "GET", "preferences": "GET, PUT"}[kind])
|
||||||
|
w.WriteHeader(405)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleTaskProductivityPage(w http.ResponseWriter, r *http.Request, active bool) {
|
||||||
|
if strings.HasSuffix(r.URL.Path, "/settings") {
|
||||||
|
http.Redirect(w, r, "/-/sys/config?panel=organizer", http.StatusSeeOther)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.Redirect(w, r, "/v/plan/dashboard#activity", http.StatusSeeOther)
|
||||||
|
}
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTaskDigestSMTPContent(t *testing.T) {
|
||||||
|
address, _, done := fakeSMTP(t, "", false)
|
||||||
|
body := "やること\n- 私用タスク\n"
|
||||||
|
if e := sendTaskDigestSMTP(context.Background(), store.AuthProviderConfig{SMTPAddress: address, SMTPFrom: "wiki@example.test"}, "reader@example.test", "2026-11-01", body); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
result := <-done
|
||||||
|
parts := strings.SplitN(strings.ReplaceAll(result.message, "\r\n", "\n"), "\n\n", 2)
|
||||||
|
if len(parts) != 2 {
|
||||||
|
t.Fatal("missing MIME body")
|
||||||
|
}
|
||||||
|
decoded, e := base64.StdEncoding.DecodeString(strings.Join(strings.Fields(parts[1]), ""))
|
||||||
|
if e != nil || string(decoded) != body {
|
||||||
|
t.Fatal("body encoding", e)
|
||||||
|
}
|
||||||
|
if !strings.Contains(parts[0], "Subject: PagesWiki tasks 2026-11-01") || strings.Contains(parts[0], "私用") {
|
||||||
|
t.Fatal("wrong headers")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTaskReminderPreferencesAndCapture(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
existing, err := s.store.SaveTask(ctx, domain, actor, newTaskRecord("task", "Existing without reminders"), 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
w := taskRequest(s, token, "GET", "preferences", nil, "")
|
||||||
|
var result struct {
|
||||||
|
Preferences store.TaskPreferences `json:"preferences"`
|
||||||
|
Defaults store.TaskRecord `json:"defaults"`
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Preferences.NotifyDue || result.Preferences.NotifyPlanned || result.Preferences.ReminderTime != "09:00" {
|
||||||
|
t.Fatal("unexpected initial reminder preferences", result.Preferences)
|
||||||
|
}
|
||||||
|
p := result.Preferences
|
||||||
|
p.NotifyDue, p.NotifyPlanned, p.ReminderTime = true, true, "10:35"
|
||||||
|
w = taskRequest(s, token, "PUT", "preferences", p, "")
|
||||||
|
if w.Code != 200 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
p = result.Preferences
|
||||||
|
for _, clock := range []string{"9:00", "24:00", "10:35:00", "garbage"} {
|
||||||
|
bad := p
|
||||||
|
bad.ReminderTime = clock
|
||||||
|
if w = taskRequest(s, token, "PUT", "preferences", bad, ""); w.Code != 422 {
|
||||||
|
t.Fatal("invalid clock accepted", clock, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
dates map[string]any
|
||||||
|
due, planned bool
|
||||||
|
}{
|
||||||
|
{"undated", map[string]any{}, false, false},
|
||||||
|
{"dated", map[string]any{"due_on": "2030-01-02", "planned_on": "2030-01-01"}, true, true},
|
||||||
|
{"cleared", map[string]any{"due_on": "", "planned_on": ""}, false, false},
|
||||||
|
} {
|
||||||
|
input := tc.dates
|
||||||
|
input["request_id"] = uuid.NewString()
|
||||||
|
input["title"] = tc.name
|
||||||
|
w = taskRequest(s, token, "POST", "capture", input, "")
|
||||||
|
if w.Code != 201 {
|
||||||
|
t.Fatal(tc.name, w.Code, w.Body)
|
||||||
|
}
|
||||||
|
var response struct {
|
||||||
|
Item store.TaskRecord `json:"item"`
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if response.Item.NotifyDue != tc.due || response.Item.NotifyPlanned != tc.planned || response.Item.ReminderTime != "10:35" {
|
||||||
|
t.Fatal("wrong reminder defaults", response.Item)
|
||||||
|
}
|
||||||
|
if tc.due && response.Item.ReminderTimezone == "" {
|
||||||
|
t.Fatal("missing server timezone")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
zero := 0
|
||||||
|
p.PlannedDays = &zero
|
||||||
|
if w = taskRequest(s, token, "PUT", "preferences", p, ""); w.Code != 200 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
w = taskRequest(s, token, "GET", "preferences", nil, "")
|
||||||
|
if err = json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !result.Defaults.NotifyPlanned || result.Defaults.NotifyDue || result.Defaults.PlannedOn == "" {
|
||||||
|
t.Fatal("dated defaults missing", result.Defaults)
|
||||||
|
}
|
||||||
|
loaded, err := s.store.GetTask(ctx, domain, actor, existing.UUID)
|
||||||
|
if err != nil || loaded.Version != existing.Version || loaded.NotifyDue || loaded.NotifyPlanned {
|
||||||
|
t.Fatal("existing task changed", loaded, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTaskCaptureDefaultsReplayAndPermissions(t *testing.T) {
|
||||||
|
s, token, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
days := 2
|
||||||
|
p := store.TaskPreferences{AssigneeUUID: actor, DueDays: &days, Complexity: 3, Estimate: 60, Timezone: "Asia/Tokyo", DigestTime: "09:00"}
|
||||||
|
p, err := s.store.SaveTaskPreferences(ctx, domain, actor, p, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
id := uuid.NewString()
|
||||||
|
input := map[string]any{"request_id": id, "title": "Mail task", "notes": "Subject only"}
|
||||||
|
w := taskRequest(s, token, "POST", "capture", input, "")
|
||||||
|
if w.Code != 201 {
|
||||||
|
t.Fatalf("capture %d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
var response struct {
|
||||||
|
Item store.TaskRecord `json:"item"`
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if response.Item.Complexity != 3 || response.Item.Estimate != 60 || response.Item.AssigneeUUID != actor || response.Item.DueOn == "" {
|
||||||
|
t.Fatalf("defaults missing %+v", response.Item)
|
||||||
|
}
|
||||||
|
p.Estimate = 120
|
||||||
|
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 {
|
||||||
|
t.Fatalf("retry %d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
loaded, err := s.store.GetTask(ctx, domain, actor, id)
|
||||||
|
if err != nil || loaded.Estimate != 60 || loaded.Version != 1 {
|
||||||
|
t.Fatal(loaded, err)
|
||||||
|
}
|
||||||
|
input["title"] = "Different"
|
||||||
|
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 412 {
|
||||||
|
t.Fatalf("conflicting replay %d", w.Code)
|
||||||
|
}
|
||||||
|
input["request_id"] = uuid.NewString()
|
||||||
|
input["due_on"] = ""
|
||||||
|
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil || response.Item.DueOn != "" {
|
||||||
|
t.Fatal("explicit clear lost", err)
|
||||||
|
}
|
||||||
|
if w = taskRequest(s, "", "POST", "capture", input, ""); w.Code == 201 {
|
||||||
|
t.Fatal("anonymous capture")
|
||||||
|
}
|
||||||
|
if err = s.store.SetPrincipalState(domain, actor, "readonly"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
token, err = s.store.CreateAuthSession(domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 403 {
|
||||||
|
t.Fatal("readonly capture", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTaskWorkReportSplitsMidnightAndCompletion(t *testing.T) {
|
||||||
|
s, _, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
item := newTaskRecord("task", "Tracked task")
|
||||||
|
item.Estimate = 60
|
||||||
|
item.Complexity = 3
|
||||||
|
item, err := s.store.SaveTask(ctx, domain, actor, item, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
loc, _ := time.LoadLocation("Asia/Tokyo")
|
||||||
|
start := time.Date(2026, 11, 1, 23, 30, 0, 0, loc)
|
||||||
|
end := start.Add(90 * time.Minute)
|
||||||
|
v, err := s.store.ChangeTaskWork(ctx, domain, actor, "start", store.TaskWork{UUID: uuid.NewString(), TaskUUID: item.UUID}, start)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.ChangeTaskWork(ctx, domain, actor, "start", store.TaskWork{UUID: uuid.NewString(), TaskUUID: item.UUID}, start); err != store.ErrTaskConflict {
|
||||||
|
t.Fatal("second active timer", err)
|
||||||
|
}
|
||||||
|
v, err = s.store.ChangeTaskWork(ctx, domain, actor, "stop", v, end)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if again, e := s.store.ChangeTaskWork(ctx, domain, actor, "stop", v, end.Add(time.Hour)); e != nil || again.EndMS != v.EndMS {
|
||||||
|
t.Fatal("stop replay changed duration", e)
|
||||||
|
}
|
||||||
|
a := time.Date(2026, 11, 1, 0, 0, 0, 0, loc)
|
||||||
|
report, err := s.store.TaskReport(ctx, domain, actor, a, a.AddDate(0, 0, 2), end)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(report.Tasks) != 1 || report.Tasks[0].WorkMS != 90*60000 || report.Days[0].WorkMS != 30*60000 || report.Days[1].WorkMS != 60*60000 {
|
||||||
|
t.Fatalf("wrong split %+v", report)
|
||||||
|
}
|
||||||
|
item.Status = "done"
|
||||||
|
item, err = s.store.SaveTask(ctx, domain, actor, item, item.Version)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
now := time.Now().In(loc)
|
||||||
|
day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
|
||||||
|
report, err = s.store.TaskReport(ctx, domain, actor, day, day.AddDate(0, 0, 1), now)
|
||||||
|
if err != nil || report.Days[0].Points != 7 || report.Days[0].Completed != 1 {
|
||||||
|
t.Fatal("points", report, err)
|
||||||
|
}
|
||||||
|
item.Status = "todo"
|
||||||
|
if _, err = s.store.SaveTask(ctx, domain, actor, item, item.Version); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
report, err = s.store.TaskReport(ctx, domain, actor, day, day.AddDate(0, 0, 1), now)
|
||||||
|
if err != nil || report.Days[0].Points != 0 {
|
||||||
|
t.Fatal("reopen did not retract", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTaskDigestClaimOnceAndOptOut(t *testing.T) {
|
||||||
|
s, _, domain, actor := taskFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
now := time.Date(2026, 11, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
p := store.TaskPreferences{Complexity: 1, DigestEnabled: true, DigestTime: "09:00", Timezone: "UTC"}
|
||||||
|
p, err := s.store.SaveTaskPreferences(ctx, domain, actor, p, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if rows, e := s.store.DueTaskDigests(ctx, now); e != nil || len(rows) != 0 {
|
||||||
|
t.Fatal(rows, e)
|
||||||
|
}
|
||||||
|
now = now.Add(2 * time.Hour)
|
||||||
|
due, err := s.store.DueTaskDigests(ctx, now)
|
||||||
|
if err != nil || len(due) != 1 {
|
||||||
|
t.Fatal(due, err)
|
||||||
|
}
|
||||||
|
claim, err := s.store.ClaimTaskDigest(ctx, due[0], now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, e := s.store.ClaimTaskDigest(ctx, due[0], now); e == nil {
|
||||||
|
t.Fatal("double claim")
|
||||||
|
}
|
||||||
|
if err = s.store.FinishTaskDigest(ctx, claim, "sent"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
p.DigestEnabled = false
|
||||||
|
if _, err = s.store.SaveTaskPreferences(ctx, domain, actor, p, now); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.TaskDigestRecipient(ctx, claim); err == nil {
|
||||||
|
t.Fatal("opt-out not enforced")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,10 +20,22 @@ import (
|
|||||||
const tasksAPI = "/_/api/v1/extension/organizer.tasks/"
|
const tasksAPI = "/_/api/v1/extension/organizer.tasks/"
|
||||||
|
|
||||||
func taskRoute(p string) bool {
|
func taskRoute(p string) bool {
|
||||||
|
if p == "/v/plan/dashboard" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if contactRoute(p) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
return strings.HasPrefix(p, tasksAPI) || p == strings.TrimSuffix(taskDAVRoot, "/") || strings.HasPrefix(p, taskDAVRoot) || p == "/v/plan/today" || p == "/v/plan/tasks" || strings.HasPrefix(p, "/v/plan/tasks/") || p == "/v/plan/projects" || strings.HasPrefix(p, "/v/plan/project/") || strings.HasPrefix(p, "/v/plan/task/")
|
return strings.HasPrefix(p, tasksAPI) || p == strings.TrimSuffix(taskDAVRoot, "/") || strings.HasPrefix(p, taskDAVRoot) || p == "/v/plan/today" || p == "/v/plan/tasks" || strings.HasPrefix(p, "/v/plan/tasks/") || p == "/v/plan/projects" || strings.HasPrefix(p, "/v/plan/project/") || strings.HasPrefix(p, "/v/plan/task/")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) registerTaskRoutes() {
|
func (s *Server) registerTaskRoutes() {
|
||||||
|
s.mux.HandleFunc("/v/plan/dashboard", s.handleOrganizerDashboard)
|
||||||
|
s.mux.HandleFunc(contactDAV, s.handleContactDAV)
|
||||||
|
s.mux.HandleFunc(strings.TrimSuffix(contactDAV, "/"), s.handleContactDAV)
|
||||||
|
s.mux.HandleFunc("/.well-known/carddav", s.handleContactDAV)
|
||||||
|
s.mux.HandleFunc(contactsAPI, s.handleContacts)
|
||||||
|
s.mux.HandleFunc("/v/plan/contacts", s.handleContacts)
|
||||||
for _, p := range []string{"/v/plan/today", "/v/plan/tasks", "/v/plan/tasks/", "/v/plan/projects", "/v/plan/project/", "/v/plan/task/"} {
|
for _, p := range []string{"/v/plan/today", "/v/plan/tasks", "/v/plan/tasks/", "/v/plan/projects", "/v/plan/project/", "/v/plan/task/"} {
|
||||||
s.mux.HandleFunc(p, s.handleTaskPage)
|
s.mux.HandleFunc(p, s.handleTaskPage)
|
||||||
}
|
}
|
||||||
@@ -86,6 +98,10 @@ func (s *Server) handleTaskPage(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
domain := s.domainUUIDForRequest(r)
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
if r.URL.Path == "/v/plan/tasks/report" || r.URL.Path == "/v/plan/tasks/settings" {
|
||||||
|
s.handleTaskProductivityPage(w, r, active)
|
||||||
|
return
|
||||||
|
}
|
||||||
if strings.HasPrefix(r.URL.Path, "/v/plan/tasks/schedule") {
|
if strings.HasPrefix(r.URL.Path, "/v/plan/tasks/schedule") {
|
||||||
s.handleTaskSchedulePage(w, r, actor)
|
s.handleTaskSchedulePage(w, r, actor)
|
||||||
return
|
return
|
||||||
@@ -196,6 +212,10 @@ func (s *Server) handleTasksAPI(w http.ResponseWriter, r *http.Request) {
|
|||||||
r = r.WithContext(ctx)
|
r = r.WithContext(ctx)
|
||||||
domain := s.domainUUIDForRequest(r)
|
domain := s.domainUUIDForRequest(r)
|
||||||
parts := strings.Split(strings.TrimPrefix(r.URL.Path, tasksAPI), "/")
|
parts := strings.Split(strings.TrimPrefix(r.URL.Path, tasksAPI), "/")
|
||||||
|
if len(parts) == 1 && (parts[0] == "dashboard" || parts[0] == "progress" || parts[0] == "calendar-capture" || parts[0] == "capture" || parts[0] == "preferences" || parts[0] == "work" || parts[0] == "report") {
|
||||||
|
s.handleTaskProductivity(w, r, actor, active, parts[0])
|
||||||
|
return
|
||||||
|
}
|
||||||
if len(parts) == 1 && parts[0] == "schedule" {
|
if len(parts) == 1 && parts[0] == "schedule" {
|
||||||
s.handleTaskScheduleAPI(w, r, actor)
|
s.handleTaskScheduleAPI(w, r, actor)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<120;i++){if(fn())return;await new Promise(r=>setTimeout(r,100));}throw Error('Timed out: '+fn.toString());};const fill=(n,value)=>{n.value=value;n.dispatchEvent(new Event('input',{bubbles:true}));};try{
|
||||||
|
const path=location.pathname;
|
||||||
|
if(path==='/v/plan/task/-/new'){
|
||||||
|
const api='/_/api/v1/extension/organizer.tasks/',dialog=document.querySelector('#tasks-dialog'),form=document.querySelector('#tasks-form');
|
||||||
|
const input=name=>form.querySelector('[name="'+name+'"]');
|
||||||
|
await wait(()=>input('page_path'));if(input('notify_due').checked||input('notify_planned').checked)throw Error('Initial defaults not off');
|
||||||
|
document.querySelector('#tasks-close').click();
|
||||||
|
const prefs=await fetch(api+'preferences').then(r=>r.json());const saved=await fetch(api+'preferences',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({...prefs.preferences,notify_due:true,notify_planned:true,reminder_time:'10:35'})});if(!saved.ok)throw Error('Preferences save failed');
|
||||||
|
document.querySelector('#tasks-new').click();await wait(()=>input('page_path'));
|
||||||
|
if(input('notify_due').checked||input('notify_planned').checked)throw Error('Undated task enabled reminders');
|
||||||
|
fill(input('title'),'タスク編集のレイアウト確認');fill(input('notes'),'主要項目を左右に整理。日付と通知をまとめて設定します。');
|
||||||
|
fill(input('planned_on'),'2030-01-01');fill(input('due_on'),'2030-01-02');
|
||||||
|
if(!input('notify_due').checked||!input('notify_planned').checked||input('reminder_time').value!=='10:35')throw Error('Dated defaults missing');
|
||||||
|
input('notify_due').click();fill(input('due_on'),'2030-01-03');if(input('notify_due').checked)throw Error('Explicit reminder choice overwritten');
|
||||||
|
for(const [key,value] of [['status','doing'],['bucket','backlog'],['complexity','4']]){const radio=form.querySelector('[name="'+key+'"][value="'+value+'"]');if(radio.type!=='radio')throw Error('Not a native radio group');radio.click();if(form.querySelectorAll('[name="'+key+'"]:checked').length!==1)throw Error('Multiple radio choices');}
|
||||||
|
fill(input('estimate_minutes'),'90');form.requestSubmit();await wait(()=>!dialog.open);
|
||||||
|
const items=await fetch(api+'items?q='+encodeURIComponent('レイアウト確認')).then(r=>r.json());const task=items.items[0];
|
||||||
|
if(task.status!=='doing'||task.bucket!=='backlog'||task.complexity!==4||!task.notify_planned||task.notify_due||task.reminder_time!=='10:35')throw Error('Editor fields not persisted');
|
||||||
|
await wait(()=>document.querySelector('[data-task-id="'+task.uuid+'"] [data-action=detail]'));document.querySelector('[data-task-id="'+task.uuid+'"] [data-action=detail]').click();await wait(()=>input('page_path'));
|
||||||
|
if(input('notify_due').checked)throw Error('Defaults changed existing task');
|
||||||
|
if(form.querySelector('.task-editor-advanced').open)throw Error('Advanced section should start collapsed');
|
||||||
|
const fields=document.querySelector('#tasks-fields'),rect=dialog.getBoundingClientRect();
|
||||||
|
if(rect.width>innerWidth+1||rect.height>innerHeight+1||fields.scrollWidth>fields.clientWidth+1)throw Error('Editor overflow');
|
||||||
|
if(innerWidth>=1000){const left=form.querySelector('.task-editor-main').getBoundingClientRect(),right=form.querySelector('.task-editor-plan').getBoundingClientRect();if(right.left<=left.right||Math.abs(right.top-left.top)>2)throw Error('Editor is not two columns');if(fields.scrollHeight>fields.clientHeight+2)throw Error('Desktop editor needs scrolling: '+fields.scrollHeight+'/'+fields.clientHeight);}
|
||||||
|
if(innerWidth<760&&form.querySelector('.task-editor-plan').getBoundingClientRect().top<form.querySelector('.task-editor-main').getBoundingClientRect().bottom)throw Error('Mobile columns overlap');
|
||||||
|
}else if(path==='/v/plan/contacts'){
|
||||||
|
await wait(()=>document.querySelector('#contacts-controls button'));document.querySelector('#contacts-controls button').click();fill(document.querySelector('[name=name]'),'ブラウザ連絡先');fill(document.querySelector('[name=emails]'),'browser@example.invalid');fill(document.querySelector('[name=notes]'),'Non-public notes');document.querySelector('#contact-editor form').requestSubmit();await wait(()=>document.querySelector('#contacts-list button')?.textContent.includes('ブラウザ'));const r=await fetch('/_/api/v1/extension/organizer.contacts/items?q=browser').then(r=>r.json());if(r.items.length!==1)throw Error('Contact save missing');
|
||||||
|
fill(document.querySelector('[name=name]'),'変更後');document.querySelector('#contact-editor form').requestSubmit();await wait(()=>document.querySelector('#contacts-list button')?.textContent.includes('変更後'));
|
||||||
|
await wait(()=>document.querySelector('.contact-history'));document.querySelector('.contact-history').open=true;await wait(()=>document.querySelectorAll('.contact-history-row').length===2);document.querySelectorAll('.contact-history-row')[1].querySelector('button').click();await wait(()=>document.querySelector('.contact-history pre').textContent.includes('ブラウザ連絡先'));
|
||||||
|
window.confirm=()=>true;document.querySelectorAll('.contact-history-row')[1].querySelectorAll('button')[1].click();await wait(()=>document.querySelector('#contacts-list button')?.textContent.includes('ブラウザ'));
|
||||||
|
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=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');
|
||||||
|
}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');
|
||||||
|
const tab=document.querySelector('[data-tab=done]');tab.click();await wait(()=>document.querySelector('#widget-panel-tasks').textContent.includes('Browser work task'));if(location.pathname!=='/v/plan/dashboard'||document.querySelector('#organizer-dashboard iframe'))throw Error('Tab navigation escaped widget');
|
||||||
|
document.querySelector('#dashboard-controls button[aria-pressed]').click();const width=document.querySelector('[data-widget=tasks] [data-size=width]');width.value='6';width.dispatchEvent(new Event('change'));const height=document.querySelector('[data-widget=tasks] [data-size=height]');height.value='5';height.dispatchEvent(new Event('change'));
|
||||||
|
document.querySelector('[data-widget=tasks] .widget-arrange button').click();document.querySelector('#dashboard-controls button:last-child').click();await wait(()=>document.querySelector('#dashboard-status').textContent.includes('保存しました'));const layout=await fetch('/_/api/v1/extension/organizer.tasks/dashboard').then(r=>r.json());if(layout.widgets[2].id!=='tasks'||layout.widgets[2].width!==6||layout.widgets[2].height!==5||layout.widgets[2].tab!=='done')throw Error('Layout did not persist');
|
||||||
|
if(!document.querySelector('.organizer-nav a[href="/v/plan/contacts"]')||!document.querySelector('.organizer-nav a[aria-current="page"]'))throw Error('Shared navigation missing');
|
||||||
|
}else if(path==='/v/plan/tasks'){
|
||||||
|
const prefs=await fetch('/_/api/v1/extension/organizer.tasks/preferences').then(r=>r.json());await fetch('/_/api/v1/extension/organizer.tasks/preferences',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({...prefs.preferences,due_days:2,estimate_minutes:60})});
|
||||||
|
await wait(()=>document.querySelector('#tasks-quick-title'));fill(document.querySelector('#tasks-quick-title'),'Recording task');document.querySelector('#tasks-capture').requestSubmit();await wait(()=>document.querySelector('[data-action=work]'));document.querySelector('[data-action=work]').click();await wait(()=>document.querySelector('.task-work-bar a').textContent.includes('Recording task'));document.querySelector('.task-work-bar button').click();await wait(()=>document.querySelector('.task-work-bar').hidden);
|
||||||
|
document.querySelector('[data-action=add-child]').click();const child=document.querySelector('.task-child-capture');fill(child.querySelector('input'),'Defaulted child');child.requestSubmit();await wait(()=>document.querySelectorAll('.task-inline-row').length===2);const children=await fetch('/_/api/v1/extension/organizer.tasks/items?q=Defaulted').then(r=>r.json());if(children.items[0].estimate_minutes!==60||!children.items[0].due_on)throw Error('Subtask defaults missing');
|
||||||
|
}else{
|
||||||
|
const input=document.querySelector('[data-home-type-search]');fill(input,'add task 検証 cost:2h complexity:3');input.closest('form').requestSubmit();await wait(()=>document.querySelector('.home-command-panel button'));document.querySelector('.home-command-panel button').click();await wait(()=>document.querySelector('.home-command-panel a'));const d=await fetch('/_/api/v1/extension/organizer.tasks/items?q='+encodeURIComponent('検証')).then(r=>r.json());if(d.items[0].estimate_minutes!==120)throw Error('Command cost missing');fill(input,'add cal 会議 from:2026-11-02T09:00 to:2026-11-02T10:00');input.closest('form').requestSubmit();await wait(()=>document.querySelector('.home-command-panel button'));document.querySelector('.home-command-panel button').click();await wait(()=>document.querySelector('.home-command-panel a')?.href.includes('/event/'));
|
||||||
|
}
|
||||||
|
if(document.documentElement.scrollWidth>innerWidth+2)throw Error('Page horizontal overflow: '+[...document.querySelectorAll('body *')].filter(n=>{const r=n.getBoundingClientRect();return r.width&&r.right>innerWidth+2;}).slice(0,15).map(n=>n.tagName+'.'+n.className+':'+Math.round(n.getBoundingClientRect().right)).join(', '));document.body.dataset.vimReady='true';
|
||||||
|
}catch(e){const n=document.createElement('pre');n.id='error';n.textContent=(e.stack||String(e))+'\n'+(document.querySelector('.home-command-panel')?.textContent||'');document.body.append(n);}});
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
window.addEventListener('load', async () => {
|
window.addEventListener('load', async () => {
|
||||||
const $=id=>document.getElementById('tasks-'+id);
|
const $=id=>document.getElementById('tasks-'+id);
|
||||||
const wait=async fn=>{for(let i=0;i<100;i++){if(fn())return;await new Promise(r=>setTimeout(r,50));}throw Error('Timed out: '+fn);};
|
const wait=async fn=>{for(let i=0;i<100;i++){if(fn())return;await new Promise(r=>setTimeout(r,50));}throw Error('Timed out: '+fn);};
|
||||||
const value=(name,text)=>{const n=document.querySelector('#tasks-form [name="'+name+'"]');if(!n)throw Error('Missing field '+name);n.value=text;n.dispatchEvent(new Event('input',{bubbles:true}));};
|
const value=(name,text)=>{let n=document.querySelector('#tasks-form [name="'+name+'"]');if(!n)throw Error('Missing field '+name);if(n.type==='radio'){n=document.querySelector('#tasks-form [name="'+name+'"][value="'+text+'"]');n.click();}else{n.value=text;n.dispatchEvent(new Event('input',{bubbles:true}));}};
|
||||||
try {
|
try {
|
||||||
if (!sessionStorage.getItem('focus-reload')) {
|
if (!sessionStorage.getItem('focus-reload')) {
|
||||||
$('dav-open').click(); await wait(()=>$('dav-dialog').open&&$('dav-dialog').querySelector('thead'));
|
$('dav-open').click(); await wait(()=>$('dav-dialog').open&&$('dav-dialog').querySelector('thead'));
|
||||||
|
|||||||
+14
@@ -44,6 +44,20 @@ try {
|
|||||||
if (state.ready) { ready = true; break; }
|
if (state.ready) { ready = true; break; }
|
||||||
await delay(200);
|
await delay(200);
|
||||||
}
|
}
|
||||||
|
if(ready && process.env.PAGESWIKI_DASHBOARD_DRAG==='1'){
|
||||||
|
const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(JSON.stringify(r.exceptionDetails));return r.result.value;};
|
||||||
|
const rect=async selector=>evaluate(`(()=>{const n=document.querySelector(${JSON.stringify(selector)});n.scrollIntoView({block:'center',behavior:'instant'});const r=n.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};})()`);
|
||||||
|
const drag=async(from,to)=>{await call('Input.dispatchMouseEvent',{type:'mouseMoved',...from});await call('Input.dispatchMouseEvent',{type:'mousePressed',...from,button:'left',buttons:1,clickCount:1});for(let n=1;n<=8;n++)await call('Input.dispatchMouseEvent',{type:'mouseMoved',x:from.x+(to.x-from.x)*n/8,y:from.y+(to.y-from.y)*n/8,buttons:1});await call('Input.dispatchMouseEvent',{type:'mouseReleased',...to,button:'left',buttons:0,clickCount:1});};
|
||||||
|
await evaluate(`scrollTo({top:0,behavior:'instant'})`);
|
||||||
|
const coordinates=await evaluate(`(()=>{const point=s=>{const r=document.querySelector(s).getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};};return {from:point('[data-widget=progress] .widget-drag'),to:point('[data-widget=today] .widget-header')};})()`);await drag(coordinates.from,coordinates.to);
|
||||||
|
if(await evaluate(`document.querySelector('#dashboard-grid').firstElementChild.dataset.widget`)!=='today')throw Error('Pointer reorder failed: '+JSON.stringify(coordinates));
|
||||||
|
const grip=await rect('[data-widget=tasks] .widget-resize');await drag(grip,{x:grip.x,y:grip.y-84});
|
||||||
|
if(await evaluate(`document.querySelector('[data-widget=tasks] [data-size=height]').value`)!=='4')throw Error('Pointer resize failed');
|
||||||
|
await evaluate(`document.querySelector('#dashboard-controls button:last-child').click()`);
|
||||||
|
let saved=false;for(let n=0;n<50;n++){if(await evaluate(`document.querySelector('#dashboard-status').textContent.includes('保存しました')`)){saved=true;break;}await delay(100);}if(!saved)throw Error('Pointer layout save failed');
|
||||||
|
const layout=await evaluate(`fetch('/_/api/v1/extension/organizer.tasks/dashboard').then(r=>r.json())`);if(layout.widgets[0].id!=='today'||layout.widgets.find(w=>w.id==='tasks').height!==4)throw Error('Pointer layout persistence failed');
|
||||||
|
await evaluate(`document.querySelector('#dashboard-controls button[aria-pressed]').click();scrollTo(0,0)`);
|
||||||
|
}
|
||||||
if (screenshot) {
|
if (screenshot) {
|
||||||
const {data} = await call('Page.captureScreenshot', {format: 'png'});
|
const {data} = await call('Page.captureScreenshot', {format: 'png'});
|
||||||
await writeFile(screenshot, Buffer.from(data, 'base64'));
|
await writeFile(screenshot, Buffer.from(data, 'base64'));
|
||||||
|
|||||||
@@ -0,0 +1,238 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
var cliAuthMigrations = []db.SQLMigration{{Version: 1, Name: "cli_oidc_handoff", Statements: []string{
|
||||||
|
`CREATE TABLE auth_cli_requests (
|
||||||
|
id TEXT PRIMARY KEY, domain_uuid TEXT NOT NULL, origin TEXT NOT NULL,
|
||||||
|
device_hash TEXT NOT NULL UNIQUE, challenge TEXT NOT NULL, code_hash TEXT NOT NULL,
|
||||||
|
state TEXT NOT NULL DEFAULT 'pending', browser_hash TEXT NOT NULL DEFAULT '',
|
||||||
|
principal_uuid TEXT NOT NULL DEFAULT '', mfa_level INTEGER NOT NULL DEFAULT 0, attempts INTEGER NOT NULL DEFAULT 0, oidc_attempts INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_ms INTEGER NOT NULL, expires_ms INTEGER NOT NULL, next_poll_ms INTEGER NOT NULL DEFAULT 0)`,
|
||||||
|
`CREATE INDEX auth_cli_domain_created ON auth_cli_requests(domain_uuid,created_ms)`,
|
||||||
|
`CREATE INDEX auth_cli_expiry ON auth_cli_requests(expires_ms)`,
|
||||||
|
}, Assertions: []string{
|
||||||
|
schemaColumns("auth_cli_requests", "id,domain_uuid,origin,device_hash,challenge,code_hash,state,browser_hash,principal_uuid,mfa_level,attempts,oidc_attempts,created_ms,expires_ms,next_poll_ms"),
|
||||||
|
schemaUnique("auth_cli_requests", "id"), schemaUnique("auth_cli_requests", "device_hash"),
|
||||||
|
schemaIndex("auth_cli_requests", "auth_cli_domain_created", "domain_uuid,created_ms"),
|
||||||
|
schemaIndex("auth_cli_requests", "auth_cli_expiry", "expires_ms"),
|
||||||
|
}}}
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrCLIPending = errors.New("authorization_pending")
|
||||||
|
ErrCLISlowDown = errors.New("slow_down")
|
||||||
|
ErrCLIExpired = errors.New("expired_token")
|
||||||
|
ErrCLILimit = errors.New("too_many_requests")
|
||||||
|
)
|
||||||
|
|
||||||
|
type CLIAuthRequest struct {
|
||||||
|
ID, Origin, State, BrowserHash, PrincipalUUID string
|
||||||
|
ExpiresMS int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// Admission is one write statement; concurrent unauthenticated requests cannot
|
||||||
|
// race the caps. Requests are retained for ten minutes for issuance accounting.
|
||||||
|
func (s *Store) StartCLIAuth(ctx context.Context, domain, origin, challenge string) (id, device, code string, err error) {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return "", "", "", ErrReadOnly
|
||||||
|
}
|
||||||
|
id, _, err = authToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
device, _, err = authToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var raw [4]byte
|
||||||
|
if _, err = rand.Read(raw[:]); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
code = strings.ToUpper(hex.EncodeToString(raw[:]))
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
_, err = s.DB.ExecContext(ctx, `DELETE FROM auth_cli_requests WHERE expires_ms<?`, now-5*60*1000)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var result sql.Result
|
||||||
|
result, err = s.DB.ExecContext(ctx, `INSERT INTO auth_cli_requests(id,domain_uuid,origin,device_hash,challenge,code_hash,created_ms,expires_ms)
|
||||||
|
SELECT ?,?,?,?,?,?,?,? WHERE (SELECT count(*) FROM auth_cli_requests)<4096
|
||||||
|
AND (SELECT count(*) FROM auth_cli_requests WHERE domain_uuid=? AND created_ms>?)<64`,
|
||||||
|
id, domain, origin, hashAuthToken(device), challenge, hashAuthToken(code), now, now+300000, domain, now-300000)
|
||||||
|
if err == nil {
|
||||||
|
if n, e := result.RowsAffected(); e != nil {
|
||||||
|
err = e
|
||||||
|
} else if n != 1 {
|
||||||
|
err = ErrCLILimit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) CLIAuthRequest(ctx context.Context, domain, origin, id string) (*CLIAuthRequest, error) {
|
||||||
|
var grant CLIAuthRequest
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT id,origin,state,browser_hash,principal_uuid,expires_ms FROM auth_cli_requests WHERE id=? AND domain_uuid=? AND origin=? AND expires_ms>?`, id, domain, origin, time.Now().UnixMilli()).Scan(&grant.ID, &grant.Origin, &grant.State, &grant.BrowserHash, &grant.PrincipalUUID, &grant.ExpiresMS)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, ErrCLIExpired
|
||||||
|
}
|
||||||
|
return &grant, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) BeginCLIAuth(ctx context.Context, domain, origin, id string) error {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return ErrReadOnly
|
||||||
|
}
|
||||||
|
result, err := s.DB.ExecContext(ctx, `UPDATE auth_cli_requests SET oidc_attempts=oidc_attempts+1 WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash='' AND expires_ms>? AND oidc_attempts<3`, id, domain, origin, time.Now().UnixMilli())
|
||||||
|
return cliChanged(result, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only the verified OIDC callback calls this method. The first successful
|
||||||
|
// browser wins; another browser cannot rebind an in-flight approval.
|
||||||
|
func (s *Store) BindCLIAuth(ctx context.Context, domain, origin, id, browser string) error {
|
||||||
|
if s.ReadOnly || !strings.HasPrefix(browser, "pw_browser_") {
|
||||||
|
return ErrAccessDenied
|
||||||
|
}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
result, err := s.DB.ExecContext(ctx, `UPDATE auth_cli_requests SET browser_hash=?,principal_uuid=(SELECT principal_uuid FROM auth_sessions WHERE token_hash=?)
|
||||||
|
WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash='' AND expires_ms>?
|
||||||
|
AND EXISTS(SELECT 1 FROM auth_sessions WHERE token_hash=? AND domain_uuid=? AND revoked_at_ms=0 AND expires_at_ms>?)`, hashAuthToken(browser), hashAuthToken(browser), id, domain, origin, now, hashAuthToken(browser), domain, now)
|
||||||
|
return cliChanged(result, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func cliChanged(result sql.Result, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
n, err := result.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if n != 1 {
|
||||||
|
return ErrAccessDenied
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// The verified OIDC callback is the only production caller of BindCLIAuth.
|
||||||
|
// Authenticate at the provider, then require explicit local consent, not a
|
||||||
|
// second local TOTP challenge. This does not claim the provider performed MFA.
|
||||||
|
func (s *Store) DecideCLIAuth(ctx context.Context, domain, origin, id, browser, code, _ string, approve bool) error {
|
||||||
|
if s.ReadOnly || !strings.HasPrefix(browser, "pw_browser_") {
|
||||||
|
return ErrAccessDenied
|
||||||
|
}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
var expectedCode string
|
||||||
|
err := s.DB.QueryRowContext(ctx, `UPDATE auth_cli_requests SET attempts=attempts+1
|
||||||
|
WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash=? AND attempts<5 AND expires_ms>?
|
||||||
|
RETURNING code_hash`, id, domain, origin, hashAuthToken(browser), now).Scan(&expectedCode)
|
||||||
|
if err != nil {
|
||||||
|
return ErrAccessDenied
|
||||||
|
}
|
||||||
|
level := 0
|
||||||
|
if approve {
|
||||||
|
if hashAuthToken(strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(code), "-", ""))) != expectedCode {
|
||||||
|
return ErrAccessDenied
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state := "denied"
|
||||||
|
if approve {
|
||||||
|
state = "approved"
|
||||||
|
}
|
||||||
|
result, err := s.DB.ExecContext(ctx, `UPDATE auth_cli_requests SET state=?,mfa_level=? WHERE id=? AND domain_uuid=? AND state='pending' AND browser_hash=? AND expires_ms>?
|
||||||
|
AND EXISTS(SELECT 1 FROM auth_sessions a JOIN principals p ON p.uuid=a.principal_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=a.domain_uuid
|
||||||
|
WHERE a.token_hash=? AND a.domain_uuid=? AND a.revoked_at_ms=0 AND a.expires_at_ms>? AND p.state IN ('active','readonly') AND m.state='active')`, state, level, id, domain, hashAuthToken(browser), now, hashAuthToken(browser), domain, now)
|
||||||
|
if err = cliChanged(result, err); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Poll and exchange start with a write, avoiding a WAL read-to-write upgrade.
|
||||||
|
// Grant consumption and API-session creation commit together. No replay on a
|
||||||
|
// lost HTTP response: a new login is required (no credential stored in grant).
|
||||||
|
func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, verifier string) (token, username string, expires int64, err error) {
|
||||||
|
if s.ReadOnly {
|
||||||
|
err = ErrReadOnly
|
||||||
|
return
|
||||||
|
}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
lifetime := s.AuthSessionLifetime(domain).Milliseconds()
|
||||||
|
tx, err := s.DB.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var id, state, browser string
|
||||||
|
err = tx.QueryRowContext(ctx, `UPDATE auth_cli_requests SET next_poll_ms=?,state=CASE WHEN state='approved' THEN 'consumed' ELSE state END
|
||||||
|
WHERE device_hash=? AND challenge=? AND domain_uuid=? AND origin=? AND expires_ms>? AND next_poll_ms<=? AND state IN ('pending','approved','denied')
|
||||||
|
RETURNING id,state,browser_hash`, now+5000, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now, now).Scan(&id, &state, &browser)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
var exists int
|
||||||
|
e := tx.QueryRowContext(ctx, `SELECT count(*) FROM auth_cli_requests WHERE device_hash=? AND challenge=? AND domain_uuid=? AND origin=? AND expires_ms>? AND state IN ('pending','approved','denied')`, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now).Scan(&exists)
|
||||||
|
if e != nil {
|
||||||
|
err = e
|
||||||
|
} else if exists > 0 {
|
||||||
|
err = ErrCLISlowDown
|
||||||
|
} else {
|
||||||
|
err = ErrCLIExpired
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if state != "consumed" {
|
||||||
|
err = tx.Commit()
|
||||||
|
if err == nil {
|
||||||
|
if state == "denied" {
|
||||||
|
err = ErrAccessDenied
|
||||||
|
} else {
|
||||||
|
err = ErrCLIPending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var raw string
|
||||||
|
raw, _, err = authToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token = "pw_api_" + raw
|
||||||
|
// A disabled user, removed membership or revoked browser cannot delegate.
|
||||||
|
err = tx.QueryRowContext(ctx, `INSERT INTO auth_sessions(uuid,token_hash,principal_uuid,domain_uuid,auth_time_ms,expires_at_ms,last_seen_at_ms,mfa_level)
|
||||||
|
SELECT ?,?,p.uuid,a.domain_uuid,a.auth_time_ms,min(?,a.expires_at_ms),?,max(a.mfa_level,g.mfa_level)
|
||||||
|
FROM auth_cli_requests g JOIN auth_sessions a ON a.token_hash=g.browser_hash JOIN principals p ON p.uuid=a.principal_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=a.domain_uuid
|
||||||
|
WHERE a.token_hash=? AND a.domain_uuid=? AND a.revoked_at_ms=0 AND a.expires_at_ms>? AND p.state IN ('active','readonly') AND m.state='active'
|
||||||
|
AND g.id=?
|
||||||
|
RETURNING principal_uuid,expires_at_ms`, uuid.NewString(), hashAuthToken(token), now+lifetime, now, browser, domain, now, id).Scan(&username, &expires)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
err = ErrAccessDenied
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
token = ""
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var name string
|
||||||
|
err = tx.QueryRowContext(ctx, `SELECT COALESCE((SELECT subject FROM principal_identities WHERE principal_uuid=? AND provider_type='password' LIMIT 1),?)`, username, username).Scan(&name)
|
||||||
|
if err != nil {
|
||||||
|
token = ""
|
||||||
|
return
|
||||||
|
}
|
||||||
|
username = name
|
||||||
|
err = tx.Commit()
|
||||||
|
if err != nil {
|
||||||
|
token = ""
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const cliTestOrigin = "https://wiki.example"
|
||||||
|
|
||||||
|
func cliAuthFixture(t *testing.T) (*Store, string, string) {
|
||||||
|
t.Helper()
|
||||||
|
s := newSchemaTestStore(t)
|
||||||
|
s.authKey = make([]byte, 32) // synthetic key; no on-disk or production secrets
|
||||||
|
if err := s.EnsureAuthSchema(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.ensureSchemaComponent("cli-auth"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
p, err := s.BootstrapOwner("domain", "owner", "correct horse battery staple", "Owner", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
browser, err := s.CreateBrowserAuthSession("domain", p.UUID, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return s, p.UUID, browser
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCLIAuthExchangeIsAtomicAndSingleUse(t *testing.T) {
|
||||||
|
s, _, browser := cliAuthFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
verifier := strings.Repeat("a", 43)
|
||||||
|
id, device, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier); !errors.Is(err, ErrCLIPending) {
|
||||||
|
t.Fatalf("pending: %v", err)
|
||||||
|
}
|
||||||
|
if _, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier); !errors.Is(err, ErrCLISlowDown) {
|
||||||
|
t.Fatalf("poll rate: %v", err)
|
||||||
|
}
|
||||||
|
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err == nil {
|
||||||
|
t.Fatal("request rebound")
|
||||||
|
}
|
||||||
|
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, code, "", true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := s.DB.Exec(`UPDATE auth_cli_requests SET next_poll_ms=0`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
var successes atomic.Int32
|
||||||
|
for range 12 {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
token, name, expires, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier)
|
||||||
|
if err == nil {
|
||||||
|
if !strings.HasPrefix(token, "pw_api_") || name != "owner" || expires <= time.Now().UnixMilli() {
|
||||||
|
t.Errorf("bad issued session")
|
||||||
|
}
|
||||||
|
if _, err := s.PrincipalForSession("domain", token); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
successes.Add(1)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
if successes.Load() != 1 {
|
||||||
|
t.Fatalf("issued %d sessions", successes.Load())
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if err := s.DB.QueryRow(`SELECT count(*) FROM auth_sessions`).Scan(&count); err != nil || count != 2 {
|
||||||
|
t.Fatalf("sessions=%d %v", count, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCLIAuthBoundariesAndRevocation(t *testing.T) {
|
||||||
|
for _, mode := range []string{"domain", "origin", "verifier", "device", "expired", "denied", "suspended", "membership", "browser revoked"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
s, _, browser := cliAuthFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
verifier := strings.Repeat("b", 43)
|
||||||
|
id, device, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, code, "", mode != "denied"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
domain, origin := "domain", cliTestOrigin
|
||||||
|
var query string
|
||||||
|
switch mode {
|
||||||
|
case "domain":
|
||||||
|
domain = "other"
|
||||||
|
case "origin":
|
||||||
|
origin = "https://alias.example"
|
||||||
|
case "verifier":
|
||||||
|
verifier = strings.Repeat("c", 43)
|
||||||
|
case "device":
|
||||||
|
device = strings.Repeat("d", 43)
|
||||||
|
case "expired":
|
||||||
|
query = `UPDATE auth_cli_requests SET expires_ms=1`
|
||||||
|
case "suspended":
|
||||||
|
query = `UPDATE principals SET state='suspended'`
|
||||||
|
case "membership":
|
||||||
|
query = `UPDATE domain_memberships SET state='suspended'`
|
||||||
|
case "browser revoked":
|
||||||
|
query = `UPDATE auth_sessions SET revoked_at_ms=1`
|
||||||
|
}
|
||||||
|
if query != "" {
|
||||||
|
if _, err := s.DB.Exec(query); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if token, _, _, err := s.ExchangeCLIAuth(ctx, domain, origin, device, verifier); err == nil || token != "" {
|
||||||
|
t.Fatalf("bypass %s", mode)
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if err := s.DB.QueryRow(`SELECT count(*) FROM auth_sessions`).Scan(&count); err != nil || count != 1 {
|
||||||
|
t.Fatalf("session leaked %d %v", count, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCLIAuthApprovalAttemptsAndIssuanceCap(t *testing.T) {
|
||||||
|
s, _, browser := cliAuthFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
id, _, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, strings.Repeat("c", 43))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for range 5 {
|
||||||
|
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, "wrong", "", true); err == nil {
|
||||||
|
t.Fatal("wrong code accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, code, "", true); err == nil {
|
||||||
|
t.Fatal("attempt limit bypassed")
|
||||||
|
}
|
||||||
|
for range 63 {
|
||||||
|
if _, _, _, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, strings.Repeat("c", 43)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, _, _, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, strings.Repeat("c", 43)); !errors.Is(err, ErrCLILimit) {
|
||||||
|
t.Fatalf("cap: %v", err)
|
||||||
|
}
|
||||||
|
s.ReadOnly = true
|
||||||
|
if _, _, _, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, strings.Repeat("c", 43)); !errors.Is(err, ErrReadOnly) {
|
||||||
|
t.Fatalf("readonly: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCLIAuthSessionFailureRollsBackConsumption(t *testing.T) {
|
||||||
|
s, _, browser := cliAuthFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
verifier := strings.Repeat("e", 43)
|
||||||
|
id, device, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, code, "", true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := s.DB.Exec(`CREATE TRIGGER reject_cli_session BEFORE INSERT ON auth_sessions BEGIN SELECT RAISE(ABORT,'synthetic failure'); END`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if token, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier); err == nil || token != "" {
|
||||||
|
t.Fatal("failed write accepted")
|
||||||
|
}
|
||||||
|
grant, err := s.CLIAuthRequest(ctx, "domain", cliTestOrigin, id)
|
||||||
|
if err != nil || grant.State != "approved" {
|
||||||
|
t.Fatalf("consumed without session: %+v %v", grant, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCLIAuthOIDCDoesNotRepeatLocalTOTPOrInventMFA(t *testing.T) {
|
||||||
|
s, principal, browser := cliAuthFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
verifier := strings.Repeat("t", 43)
|
||||||
|
secret, err := s.BeginTOTPEnrollment(principal)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
code, err := totpCode(secret, time.Now().Unix()/30)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.ConfirmTOTPEnrollment(principal, code); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
id, device, userCode, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for range 3 {
|
||||||
|
if err := s.BeginCLIAuth(ctx, "domain", cliTestOrigin, id); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := s.BeginCLIAuth(ctx, "domain", cliTestOrigin, id); err == nil {
|
||||||
|
t.Fatal("OIDC challenge amplification allowed")
|
||||||
|
}
|
||||||
|
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, userCode, "", true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
token, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var level int
|
||||||
|
if err := s.DB.QueryRow(`SELECT mfa_level FROM auth_sessions WHERE token_hash=?`, hashAuthToken(token)).Scan(&level); err != nil || level != 0 {
|
||||||
|
t.Fatalf("OIDC must not invent local MFA: %d %v", level, err)
|
||||||
|
}
|
||||||
|
// Preserve an actually verified level from the bound browser session.
|
||||||
|
strongBrowser, err := s.CreateBrowserAuthSession("domain", principal, 1)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
id, device, userCode, err = s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, strongBrowser); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, strongBrowser, userCode, "", true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
token, _, _, err = s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.DB.QueryRow(`SELECT mfa_level FROM auth_sessions WHERE token_hash=?`, hashAuthToken(token)).Scan(&level); err != nil || level != 1 {
|
||||||
|
t.Fatalf("verified MFA level lost: %d %v", level, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrContactUIDConflict = errors.New("contact UID conflict")
|
||||||
|
var ErrContactSyncToken = errors.New("invalid contact sync token")
|
||||||
|
|
||||||
|
func ContactPropertyValues(c Contact, key string) []string {
|
||||||
|
lines, err := cardLines(c.VCard)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
values := []string{}
|
||||||
|
for _, line := range lines[1 : len(lines)-1] {
|
||||||
|
k, v, e := cardKey(line)
|
||||||
|
if e == nil && k == strings.ToUpper(key) {
|
||||||
|
values = append(values, cardText(v))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
func ValidContactDAVName(name string) bool {
|
||||||
|
if len(name) < 5 || len(name) > 128 || !strings.HasSuffix(name, ".vcf") || strings.HasPrefix(name, ".") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, c := range name {
|
||||||
|
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("-_.", c)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
func ContactETag(c Contact) string { return fmt.Sprintf(`"%d"`, c.Version) }
|
||||||
|
|
||||||
|
type ContactDAVItem struct {
|
||||||
|
Contact
|
||||||
|
Name string
|
||||||
|
Sequence int64
|
||||||
|
Size int
|
||||||
|
}
|
||||||
|
type ContactDAVSnapshot struct {
|
||||||
|
Items []ContactDAVItem
|
||||||
|
Token string
|
||||||
|
More bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scope and epoch bind opaque tokens to this database, domain and owner. Each
|
||||||
|
// resource retains only its latest sequence; soft-deleted rows are tombstones.
|
||||||
|
func (s *Store) ContactDAVSnapshot(ctx context.Context, domain, actor, token string, limit int) (ContactDAVSnapshot, error) {
|
||||||
|
if limit < 0 || limit > 200 {
|
||||||
|
return ContactDAVSnapshot{}, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
return s.contactDAVSnapshot(ctx, domain, actor, token, limit, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PROPFIND inventories contain metadata only, never thousands of vCard bodies.
|
||||||
|
// The same read transaction supplies both the inventory and its change token.
|
||||||
|
func (s *Store) ContactDAVInventory(ctx context.Context, domain, actor string) (ContactDAVSnapshot, error) {
|
||||||
|
return s.contactDAVSnapshot(ctx, domain, actor, "", 5000, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) contactDAVSnapshot(ctx context.Context, domain, actor, token string, limit int, metadata bool) (ContactDAVSnapshot, error) {
|
||||||
|
out := ContactDAVSnapshot{Items: []ContactDAVItem{}}
|
||||||
|
tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if err = taskActor(ctx, tx, domain, actor, false); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err = contactEnabled(ctx, tx, domain); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
var epoch string
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT value FROM organizer_contact_epoch WHERE id=1`).Scan(&epoch); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
hash := sha256.Sum256([]byte(epoch + "\x00" + domain + "\x00" + actor))
|
||||||
|
prefix := "urn:pageswiki:contacts:" + hex.EncodeToString(hash[:]) + ":"
|
||||||
|
var high int64
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT COALESCE(MAX(sequence),0) FROM organizer_contact_changes WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(&high); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
since := int64(0)
|
||||||
|
if token != "" {
|
||||||
|
if !strings.HasPrefix(token, prefix) {
|
||||||
|
return out, ErrContactSyncToken
|
||||||
|
}
|
||||||
|
since, err = strconv.ParseInt(strings.TrimPrefix(token, prefix), 10, 64)
|
||||||
|
if err != nil || since < 0 || since > high || prefix+strconv.FormatInt(since, 10) != token {
|
||||||
|
return out, ErrContactSyncToken
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.Token = prefix + strconv.FormatInt(high, 10)
|
||||||
|
if limit == 0 {
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
fields := `c.data,n.name,x.sequence,0`
|
||||||
|
if metadata {
|
||||||
|
fields = `json_object('uuid',c.uuid,'version',c.version),n.name,x.sequence,length(CAST(json_extract(c.data,'$.vcard') AS BLOB))`
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, `SELECT `+fields+` FROM organizer_contact_changes x JOIN organizer_contacts c USING(domain_uuid,owner_uuid,uuid) JOIN organizer_contact_names n USING(domain_uuid,owner_uuid,uuid) WHERE x.domain_uuid=? AND x.owner_uuid=? AND x.sequence>? AND (?<>'' OR c.deleted=0) ORDER BY x.sequence LIMIT ?`, domain, actor, since, token, limit+1)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
if len(out.Items) == limit {
|
||||||
|
out.More = true
|
||||||
|
out.Token = prefix + strconv.FormatInt(out.Items[len(out.Items)-1].Sequence, 10)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
var item ContactDAVItem
|
||||||
|
var raw string
|
||||||
|
if err = rows.Scan(&raw, &item.Name, &item.Sequence, &item.Size); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal([]byte(raw), &item.Contact); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.Items = append(out.Items, item)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ContactDAVResource(ctx context.Context, domain, actor, name string) (Contact, error) {
|
||||||
|
if !ValidContactDAVName(name) {
|
||||||
|
return Contact{}, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return Contact{}, err
|
||||||
|
}
|
||||||
|
if err := contactEnabled(ctx, s.DB, domain); err != nil {
|
||||||
|
return Contact{}, err
|
||||||
|
}
|
||||||
|
var id string
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT uuid FROM organizer_contact_names WHERE domain_uuid=? AND owner_uuid=? AND name=?`, domain, actor, name).Scan(&id)
|
||||||
|
if err != nil {
|
||||||
|
return Contact{}, err
|
||||||
|
}
|
||||||
|
return s.Contact(ctx, domain, actor, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The version is compared under the same write lock as credential revocation,
|
||||||
|
// membership and extension state. No read-modify-write bypass for DAV clients.
|
||||||
|
func (s *Store) SaveContactDAV(ctx context.Context, domain, actor, credential, name, raw string, version int64, remove bool) (Contact, error) {
|
||||||
|
if !ValidContactDAVName(name) {
|
||||||
|
return Contact{}, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
old, err := s.ContactDAVResource(ctx, domain, actor, name)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return old, err
|
||||||
|
}
|
||||||
|
if old.Version != version {
|
||||||
|
return old, ErrTaskConflict
|
||||||
|
}
|
||||||
|
if remove {
|
||||||
|
if old.Version == 0 || old.Deleted {
|
||||||
|
return old, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
old.Deleted = true
|
||||||
|
return s.saveContact(ctx, domain, actor, old, "fields", credential, name)
|
||||||
|
}
|
||||||
|
id := old.UUID
|
||||||
|
if id == "" {
|
||||||
|
id = strings.TrimSuffix(name, ".vcf")
|
||||||
|
if u, e := uuid.Parse(id); e != nil || u.String() != id {
|
||||||
|
id = uuid.NewSHA1(uuid.NameSpaceURL, []byte(domain+"\x00"+actor+"\x00"+name)).String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s.saveContact(ctx, domain, actor, Contact{UUID: id, Version: version, VCard: raw}, "dav", credential, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ContactRevision struct {
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
Deleted bool `json:"deleted"`
|
||||||
|
CreatedMS int64 `json:"created_ms"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ContactHistory(ctx context.Context, domain, actor, id string, before int64) ([]ContactRevision, error) {
|
||||||
|
if _, err := s.Contact(ctx, domain, actor, id); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rows, err := s.DB.QueryContext(ctx, `SELECT version,deleted,created_ms FROM organizer_contact_revisions WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND (?=0 OR version<?) ORDER BY version DESC LIMIT 100`, domain, actor, id, before, before)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []ContactRevision{}
|
||||||
|
for rows.Next() {
|
||||||
|
var r ContactRevision
|
||||||
|
if err = rows.Scan(&r.Version, &r.Deleted, &r.CreatedMS); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
func (s *Store) RestoreContactRevision(ctx context.Context, domain, actor, id string, revision, version int64) (Contact, error) {
|
||||||
|
old, err := s.Contact(ctx, domain, actor, id)
|
||||||
|
if err != nil {
|
||||||
|
return old, err
|
||||||
|
}
|
||||||
|
if old.Version != version {
|
||||||
|
return old, ErrTaskConflict
|
||||||
|
}
|
||||||
|
var hash string
|
||||||
|
if err = s.DB.QueryRowContext(ctx, `SELECT hash FROM organizer_contact_revisions WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND version=?`, domain, actor, id, revision).Scan(&hash); err != nil {
|
||||||
|
return old, err
|
||||||
|
}
|
||||||
|
raw, err := s.readDocument(hash)
|
||||||
|
if err != nil {
|
||||||
|
return old, err
|
||||||
|
}
|
||||||
|
return s.saveContact(ctx, domain, actor, Contact{UUID: id, Version: version, VCard: raw}, "dav", "", "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ContactAtRevision(ctx context.Context, domain, actor, id string, version int64) (Contact, error) {
|
||||||
|
if _, err := s.Contact(ctx, domain, actor, id); err != nil {
|
||||||
|
return Contact{}, err
|
||||||
|
}
|
||||||
|
var hash string
|
||||||
|
var deleted bool
|
||||||
|
if err := s.DB.QueryRowContext(ctx, `SELECT hash,deleted FROM organizer_contact_revisions WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND version=?`, domain, actor, id, version).Scan(&hash, &deleted); err != nil {
|
||||||
|
return Contact{}, err
|
||||||
|
}
|
||||||
|
raw, err := s.readDocument(hash)
|
||||||
|
if err != nil {
|
||||||
|
return Contact{}, err
|
||||||
|
}
|
||||||
|
c, err := ParseContact(raw)
|
||||||
|
c.UUID = id
|
||||||
|
c.Version = version
|
||||||
|
c.Deleted = deleted
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// One SQLite read snapshot, bounded before headers are sent. An export must
|
||||||
|
// never look successful when contacts have been silently truncated.
|
||||||
|
func (s *Store) ExportContacts(ctx context.Context, domain, actor string) (string, error) {
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := contactEnabled(ctx, s.DB, domain); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
rows, err := s.DB.QueryContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND deleted=0 ORDER BY uuid LIMIT 5001`, domain, actor)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out strings.Builder
|
||||||
|
count := 0
|
||||||
|
for rows.Next() {
|
||||||
|
var raw string
|
||||||
|
var c Contact
|
||||||
|
if err = rows.Scan(&raw); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal([]byte(raw), &c); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
count++
|
||||||
|
if count > 5000 || out.Len()+len(c.VCard) > 16<<20 {
|
||||||
|
return "", ErrTaskDAVLimit
|
||||||
|
}
|
||||||
|
out.WriteString(c.VCard)
|
||||||
|
}
|
||||||
|
return out.String(), rows.Err()
|
||||||
|
}
|
||||||
@@ -0,0 +1,497 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/mail"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
var contactMigrations = []db.SQLMigration{{Version: 1, Name: "private_address_book", Statements: []string{
|
||||||
|
`CREATE TABLE organizer_contacts(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,uid TEXT NOT NULL,version INTEGER NOT NULL,name TEXT NOT NULL,search TEXT NOT NULL,data TEXT NOT NULL,hash TEXT NOT NULL,deleted INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(domain_uuid,owner_uuid,uuid),UNIQUE(domain_uuid,owner_uuid,uid))`,
|
||||||
|
`CREATE INDEX organizer_contacts_owner ON organizer_contacts(domain_uuid,owner_uuid,deleted,uuid)`,
|
||||||
|
`CREATE TABLE organizer_contact_revisions(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,version INTEGER NOT NULL,hash TEXT NOT NULL,deleted INTEGER NOT NULL,created_ms INTEGER NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,uuid,version))`,
|
||||||
|
}, Assertions: []string{schemaColumns("organizer_contacts", "domain_uuid,owner_uuid,uuid,uid,version,name,search,data,hash,deleted"), schemaUnique("organizer_contacts", "domain_uuid,owner_uuid,uid")}}, {Version: 2, Name: "contact_dav_sync", Statements: []string{
|
||||||
|
`CREATE TABLE organizer_contact_credentials(credential_id TEXT PRIMARY KEY)`,
|
||||||
|
`CREATE TRIGGER organizer_contact_credential_delete AFTER DELETE ON organizer_dav_credentials BEGIN DELETE FROM organizer_contact_credentials WHERE credential_id=old.id; END`,
|
||||||
|
`CREATE TABLE organizer_contact_names(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,name TEXT NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,uuid),UNIQUE(domain_uuid,owner_uuid,name))`,
|
||||||
|
`INSERT INTO organizer_contact_names SELECT domain_uuid,owner_uuid,uuid,uuid||'.vcf' FROM organizer_contacts`,
|
||||||
|
`CREATE TABLE organizer_contact_epoch(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL)`,
|
||||||
|
`INSERT INTO organizer_contact_epoch VALUES(1,lower(hex(randomblob(32))))`,
|
||||||
|
`CREATE TABLE organizer_contact_changes(sequence INTEGER PRIMARY KEY AUTOINCREMENT,domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,UNIQUE(domain_uuid,owner_uuid,uuid))`,
|
||||||
|
`CREATE INDEX organizer_contact_changes_owner ON organizer_contact_changes(domain_uuid,owner_uuid,sequence,uuid)`,
|
||||||
|
`INSERT INTO organizer_contact_changes(domain_uuid,owner_uuid,uuid) SELECT domain_uuid,owner_uuid,uuid FROM organizer_contacts ORDER BY domain_uuid,owner_uuid,uuid`,
|
||||||
|
`CREATE TRIGGER organizer_contact_insert AFTER INSERT ON organizer_contacts BEGIN INSERT INTO organizer_contact_names SELECT new.domain_uuid,new.owner_uuid,new.uuid,new.uuid||'.vcf' WHERE NOT EXISTS(SELECT 1 FROM organizer_contact_names WHERE domain_uuid=new.domain_uuid AND owner_uuid=new.owner_uuid AND uuid=new.uuid); INSERT INTO organizer_contact_changes(domain_uuid,owner_uuid,uuid) VALUES(new.domain_uuid,new.owner_uuid,new.uuid); END`,
|
||||||
|
`CREATE TRIGGER organizer_contact_update AFTER UPDATE ON organizer_contacts BEGIN DELETE FROM organizer_contact_changes WHERE domain_uuid=new.domain_uuid AND owner_uuid=new.owner_uuid AND uuid=new.uuid; INSERT INTO organizer_contact_changes(domain_uuid,owner_uuid,uuid) VALUES(new.domain_uuid,new.owner_uuid,new.uuid); END`,
|
||||||
|
}, Assertions: []string{
|
||||||
|
schemaColumns("organizer_contact_changes", "sequence,domain_uuid,owner_uuid,uuid"),
|
||||||
|
schemaColumns("organizer_contact_credentials", "credential_id"),
|
||||||
|
schemaColumns("organizer_contact_epoch", "id,value"),
|
||||||
|
schemaColumns("organizer_contact_names", "domain_uuid,owner_uuid,uuid,name"),
|
||||||
|
schemaUnique("organizer_contact_names", "domain_uuid,owner_uuid,name"),
|
||||||
|
schemaUnique("organizer_contact_changes", "domain_uuid,owner_uuid,uuid"),
|
||||||
|
schemaIndex("organizer_contact_changes", "organizer_contact_changes_owner", "domain_uuid,owner_uuid,sequence,uuid"),
|
||||||
|
`SELECT 1 WHERE (SELECT count(*) FROM organizer_contact_epoch WHERE id=1 AND length(value)=64)<>1`,
|
||||||
|
`SELECT 1 WHERE (SELECT count(*) FROM sqlite_master WHERE type='trigger' AND name IN ('organizer_contact_insert','organizer_contact_update','organizer_contact_credential_delete'))<>3`,
|
||||||
|
}}}
|
||||||
|
|
||||||
|
type Contact struct {
|
||||||
|
UUID string `json:"uuid"`
|
||||||
|
UID string `json:"uid"`
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Emails []string `json:"emails"`
|
||||||
|
Phones []string `json:"phones"`
|
||||||
|
Organization string `json:"organization"`
|
||||||
|
Notes string `json:"notes"`
|
||||||
|
VCard string `json:"vcard,omitempty"`
|
||||||
|
Deleted bool `json:"deleted"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Preserve every unfolded property, including unsupported fields/parameters.
|
||||||
|
// Encoded legacy v2.1/QP and malformed data are rejected, never silently lost.
|
||||||
|
func cardLines(raw string) ([]string, error) {
|
||||||
|
if len(raw) > 65536 || !utf8.ValidString(raw) || strings.ContainsRune(raw, 0) {
|
||||||
|
return nil, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
for _, c := range raw {
|
||||||
|
if c < 32 && c != '\r' && c != '\n' && c != '\t' || c == 127 {
|
||||||
|
return nil, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raw = strings.ReplaceAll(raw, "\r\n", "\n")
|
||||||
|
if strings.ContainsRune(raw, '\r') {
|
||||||
|
return nil, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
var lines []string
|
||||||
|
for _, line := range strings.Split(strings.TrimSuffix(raw, "\n"), "\n") {
|
||||||
|
if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") {
|
||||||
|
if len(lines) == 0 {
|
||||||
|
return nil, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
lines[len(lines)-1] += line[1:]
|
||||||
|
} else {
|
||||||
|
lines = append(lines, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(lines) < 4 || lines[0] != "BEGIN:VCARD" || lines[len(lines)-1] != "END:VCARD" {
|
||||||
|
return nil, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
return lines, nil
|
||||||
|
}
|
||||||
|
func cardKey(line string) (string, string, error) {
|
||||||
|
quoted := false
|
||||||
|
colon := -1
|
||||||
|
for i, c := range line {
|
||||||
|
if c == '"' {
|
||||||
|
quoted = !quoted
|
||||||
|
}
|
||||||
|
if c == ':' && !quoted {
|
||||||
|
colon = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if colon < 1 {
|
||||||
|
return "", "", ErrTaskInvalid
|
||||||
|
}
|
||||||
|
head := line[:colon]
|
||||||
|
key := strings.SplitN(head, ";", 2)[0]
|
||||||
|
if i := strings.LastIndex(key, "."); i >= 0 {
|
||||||
|
key = key[i+1:]
|
||||||
|
}
|
||||||
|
for _, c := range key {
|
||||||
|
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') {
|
||||||
|
return "", "", ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
upper := strings.ToUpper(head)
|
||||||
|
if strings.Contains(upper, "ENCODING=") || strings.Contains(upper, "CHARSET=") {
|
||||||
|
return "", "", ErrTaskInvalid
|
||||||
|
}
|
||||||
|
return strings.ToUpper(key), line[colon+1:], nil
|
||||||
|
}
|
||||||
|
func cardText(s string) string {
|
||||||
|
var b strings.Builder
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
if s[i] == '\\' && i+1 < len(s) {
|
||||||
|
i++
|
||||||
|
if s[i] == 'n' || s[i] == 'N' {
|
||||||
|
b.WriteByte('\n')
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.WriteByte(s[i])
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
func escapeCard(s string) string {
|
||||||
|
return strings.NewReplacer("\\", "\\\\", "\r\n", "\\n", "\n", "\\n", ";", "\\;", ",", "\\,").Replace(s)
|
||||||
|
}
|
||||||
|
func foldCard(lines []string) string {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, line := range lines {
|
||||||
|
first := true
|
||||||
|
for len(line) > 0 {
|
||||||
|
n := 75
|
||||||
|
if !first {
|
||||||
|
b.WriteByte(' ')
|
||||||
|
n = 74
|
||||||
|
}
|
||||||
|
if len(line) < n {
|
||||||
|
n = len(line)
|
||||||
|
}
|
||||||
|
for n > 0 && n < len(line) && !utf8.RuneStart(line[n]) {
|
||||||
|
n--
|
||||||
|
}
|
||||||
|
b.WriteString(line[:n])
|
||||||
|
b.WriteString("\r\n")
|
||||||
|
line = line[n:]
|
||||||
|
first = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
func ParseContact(raw string) (Contact, error) {
|
||||||
|
c := Contact{Emails: []string{}, Phones: []string{}}
|
||||||
|
lines, err := cardLines(raw)
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
versions, names, uids := 0, 0, 0
|
||||||
|
for _, line := range lines[1 : len(lines)-1] {
|
||||||
|
key, value, e := cardKey(line)
|
||||||
|
if e != nil {
|
||||||
|
return c, e
|
||||||
|
}
|
||||||
|
value = cardText(value)
|
||||||
|
switch key {
|
||||||
|
case "VERSION":
|
||||||
|
versions++
|
||||||
|
if value != "4.0" && value != "3.0" {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
case "BEGIN", "END":
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
case "UID":
|
||||||
|
uids++
|
||||||
|
c.UID = value
|
||||||
|
case "FN":
|
||||||
|
names++
|
||||||
|
if c.Name == "" {
|
||||||
|
c.Name = value
|
||||||
|
}
|
||||||
|
case "EMAIL":
|
||||||
|
c.Emails = append(c.Emails, value)
|
||||||
|
case "TEL":
|
||||||
|
c.Phones = append(c.Phones, strings.TrimPrefix(value, "tel:"))
|
||||||
|
case "ORG":
|
||||||
|
if c.Organization == "" {
|
||||||
|
c.Organization = value
|
||||||
|
}
|
||||||
|
case "NOTE":
|
||||||
|
if c.Notes == "" {
|
||||||
|
c.Notes = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if versions != 1 || names < 1 || uids > 1 || len(c.Name) > 300 || len(c.UID) > 1024 || strings.TrimSpace(c.Name) == "" || len(c.Emails) > 30 || len(c.Phones) > 30 {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if lines[1] != "VERSION:4.0" && lines[1] != "VERSION:3.0" {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
for _, value := range append([]string{c.Name, c.UID}, c.Emails...) {
|
||||||
|
if strings.ContainsAny(value, "\r\n\x00") {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, value := range c.Emails {
|
||||||
|
a, e := mail.ParseAddress(value)
|
||||||
|
if e != nil || a.Address != value {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c.UID == "" {
|
||||||
|
sum := sha256.Sum256([]byte(raw))
|
||||||
|
c.UID = "urn:pageswiki:import:" + hex.EncodeToString(sum[:])
|
||||||
|
lines = append(lines[:len(lines)-1], "UID:"+c.UID, "END:VCARD")
|
||||||
|
}
|
||||||
|
c.VCard = foldCard(lines)
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Editing the visible fields retains other fields verbatim. Even repeated FN,
|
||||||
|
// ORG/NOTE and typed email/phone fields survive when that field is unchanged.
|
||||||
|
func buildContact(old Contact, c Contact) (Contact, error) {
|
||||||
|
if len(c.Name) > 300 || strings.TrimSpace(c.Name) == "" || len(c.Notes) > 16384 || len(c.Organization) > 1000 || len(c.Emails) > 30 || len(c.Phones) > 30 {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
for _, value := range append(append([]string{c.Name, c.Organization}, c.Emails...), c.Phones...) {
|
||||||
|
if strings.ContainsAny(value, "\r\n\x00") {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, value := range c.Emails {
|
||||||
|
a, e := mail.ParseAddress(value)
|
||||||
|
if e != nil || a.Address != value {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines := []string{"BEGIN:VCARD", "VERSION:4.0", "UID:urn:uuid:" + c.UUID, "END:VCARD"}
|
||||||
|
if old.VCard != "" {
|
||||||
|
var e error
|
||||||
|
lines, e = cardLines(old.VCard)
|
||||||
|
if e != nil {
|
||||||
|
return c, e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
changes := map[string][]string{}
|
||||||
|
if old.VCard == "" || c.Name != old.Name {
|
||||||
|
changes["FN"] = []string{c.Name}
|
||||||
|
}
|
||||||
|
if c.Organization != old.Organization {
|
||||||
|
changes["ORG"] = []string{c.Organization}
|
||||||
|
}
|
||||||
|
if c.Notes != old.Notes {
|
||||||
|
changes["NOTE"] = []string{c.Notes}
|
||||||
|
}
|
||||||
|
if strings.Join(c.Emails, "\x00") != strings.Join(old.Emails, "\x00") {
|
||||||
|
changes["EMAIL"] = c.Emails
|
||||||
|
}
|
||||||
|
if strings.Join(c.Phones, "\x00") != strings.Join(old.Phones, "\x00") {
|
||||||
|
changes["TEL"] = c.Phones
|
||||||
|
}
|
||||||
|
out := []string{}
|
||||||
|
for _, line := range lines[:len(lines)-1] {
|
||||||
|
k, _, _ := cardKey(line)
|
||||||
|
if _, replace := changes[k]; !replace {
|
||||||
|
out = append(out, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, key := range []string{"FN", "ORG", "NOTE", "EMAIL", "TEL"} {
|
||||||
|
for _, value := range changes[key] {
|
||||||
|
if value != "" {
|
||||||
|
out = append(out, key+":"+escapeCard(value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out = append(out, "END:VCARD")
|
||||||
|
parsed, e := ParseContact(foldCard(out))
|
||||||
|
parsed.UUID = c.UUID
|
||||||
|
parsed.Version = c.Version
|
||||||
|
parsed.Deleted = c.Deleted
|
||||||
|
return parsed, e
|
||||||
|
}
|
||||||
|
func contactEnabled(ctx context.Context, q interface {
|
||||||
|
QueryRowContext(context.Context, string, ...any) *sql.Row
|
||||||
|
}, domain string) error {
|
||||||
|
var raw string
|
||||||
|
err := q.QueryRowContext(ctx, `SELECT value FROM config WHERE domain_uuid=? AND key='system_extension_states'`, domain).Scan(&raw)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) || err == nil && raw == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
states := map[string]bool{}
|
||||||
|
if json.Unmarshal([]byte(raw), &states) != nil {
|
||||||
|
return ErrAccessDenied
|
||||||
|
}
|
||||||
|
if on, ok := states["organizer.contacts"]; ok && !on {
|
||||||
|
return ErrAccessDenied
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (s *Store) Contacts(ctx context.Context, domain, actor, query, after string) ([]Contact, string, error) {
|
||||||
|
return s.ListContacts(ctx, domain, actor, query, after, false)
|
||||||
|
}
|
||||||
|
func (s *Store) ListContacts(ctx context.Context, domain, actor, query, after string, deleted bool) ([]Contact, string, error) {
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
if err := contactEnabled(ctx, s.DB, domain); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
if len(query) > 200 {
|
||||||
|
return nil, "", ErrTaskInvalid
|
||||||
|
}
|
||||||
|
rows, err := s.DB.QueryContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND deleted=? AND uuid>? AND instr(search,?)>0 ORDER BY uuid LIMIT 101`, domain, actor, deleted, after, strings.ToLower(query))
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []Contact{}
|
||||||
|
next := ""
|
||||||
|
for rows.Next() {
|
||||||
|
var raw string
|
||||||
|
if err = rows.Scan(&raw); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
var c Contact
|
||||||
|
if err = json.Unmarshal([]byte(raw), &c); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
if len(out) == 100 {
|
||||||
|
next = out[99].UUID
|
||||||
|
break
|
||||||
|
}
|
||||||
|
c.VCard = ""
|
||||||
|
out = append(out, c)
|
||||||
|
}
|
||||||
|
return out, next, rows.Err()
|
||||||
|
}
|
||||||
|
func (s *Store) Contact(ctx context.Context, domain, actor, id string) (Contact, error) {
|
||||||
|
var c Contact
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if err := contactEnabled(ctx, s.DB, domain); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
var raw string
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND uuid=?`, domain, actor, id).Scan(&raw)
|
||||||
|
if err == nil {
|
||||||
|
err = json.Unmarshal([]byte(raw), &c)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
func (s *Store) SaveContact(ctx context.Context, domain, actor string, c Contact, rawImport bool) (Contact, error) {
|
||||||
|
mode := "fields"
|
||||||
|
if rawImport {
|
||||||
|
mode = "import"
|
||||||
|
}
|
||||||
|
return s.saveContact(ctx, domain, actor, c, mode, "", "")
|
||||||
|
}
|
||||||
|
func (s *Store) saveContact(ctx context.Context, domain, actor string, c Contact, mode, credential, name string) (Contact, error) {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return c, ErrReadOnly
|
||||||
|
}
|
||||||
|
if id, e := uuid.Parse(c.UUID); e != nil || id.String() != c.UUID || c.Version < 0 {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
tx, err := s.DB.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if _, err = tx.ExecContext(ctx, `UPDATE domain_memberships SET state=state WHERE domain_uuid=? AND principal_uuid=?`, domain, actor); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if err = taskActor(ctx, tx, domain, actor, true); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if err = contactEnabled(ctx, tx, domain); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if credential != "" {
|
||||||
|
if err = davCredentialAllowed(ctx, tx, domain, actor, credential, true, "contacts"); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var old Contact
|
||||||
|
var data string
|
||||||
|
err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND uuid=?`, domain, actor, c.UUID).Scan(&data)
|
||||||
|
if err == nil {
|
||||||
|
if err = json.Unmarshal([]byte(data), &old); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
} else if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if c.Version != old.Version {
|
||||||
|
return c, ErrTaskConflict
|
||||||
|
}
|
||||||
|
if mode == "import" || mode == "dav" {
|
||||||
|
if mode == "import" && c.Version != 0 {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
parsed, e := ParseContact(c.VCard)
|
||||||
|
if e != nil {
|
||||||
|
return c, e
|
||||||
|
}
|
||||||
|
parsed.UUID = c.UUID
|
||||||
|
parsed.Version = c.Version
|
||||||
|
c = parsed
|
||||||
|
if old.Version != 0 && old.UID != c.UID {
|
||||||
|
return c, ErrContactUIDConflict
|
||||||
|
}
|
||||||
|
var existing string
|
||||||
|
err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND uid=?`, domain, actor, c.UID).Scan(&existing)
|
||||||
|
if err == nil {
|
||||||
|
var previous Contact
|
||||||
|
if json.Unmarshal([]byte(existing), &previous) != nil {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if mode == "import" {
|
||||||
|
if previous.VCard != c.VCard || previous.Deleted {
|
||||||
|
return c, ErrTaskConflict
|
||||||
|
}
|
||||||
|
return previous, nil
|
||||||
|
}
|
||||||
|
if previous.UUID != c.UUID {
|
||||||
|
return c, ErrContactUIDConflict
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
c, err = buildContact(old, c)
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if name != "" {
|
||||||
|
if !ValidContactDAVName(name) {
|
||||||
|
return c, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
var existing string
|
||||||
|
err = tx.QueryRowContext(ctx, `SELECT name FROM organizer_contact_names WHERE domain_uuid=? AND owner_uuid=? AND uuid=?`, domain, actor, c.UUID).Scan(&existing)
|
||||||
|
if err == nil && existing != name {
|
||||||
|
return c, ErrTaskConflict
|
||||||
|
}
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO organizer_contact_names VALUES(?,?,?,?)`, domain, actor, c.UUID, name); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
var mapped string
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT uuid FROM organizer_contact_names WHERE domain_uuid=? AND owner_uuid=? AND name=?`, domain, actor, name).Scan(&mapped); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
if mapped != c.UUID {
|
||||||
|
return c, ErrTaskConflict
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.Version++
|
||||||
|
b, err := json.Marshal(c)
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
hash := sha256.Sum256([]byte(c.VCard))
|
||||||
|
digest := hex.EncodeToString(hash[:])
|
||||||
|
if err = s.persistDocument(digest, c.VCard); err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
search := strings.ToLower(c.Name + "\n" + c.Organization + "\n" + strings.Join(c.Emails, "\n") + "\n" + strings.Join(c.Phones, "\n"))
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_contacts(domain_uuid,owner_uuid,uuid,uid,version,name,search,data,hash,deleted) VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(domain_uuid,owner_uuid,uuid) DO UPDATE SET version=excluded.version,name=excluded.name,search=excluded.search,data=excluded.data,hash=excluded.hash,deleted=excluded.deleted`, domain, actor, c.UUID, c.UID, c.Version, c.Name, search, string(b), digest, c.Deleted)
|
||||||
|
if err != nil {
|
||||||
|
return c, fmt.Errorf("save contact: %w", err)
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_contact_revisions VALUES(?,?,?,?,?,?,?)`, domain, actor, c.UUID, c.Version, digest, c.Deleted, time.Now().UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
return c, tx.Commit()
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Dashboard is owner-scoped presentation metadata. It never contains executable
|
||||||
|
// widgets, URLs or private task content, and is versioned separately from mail.
|
||||||
|
type DashboardWidget struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Width int `json:"width"`
|
||||||
|
Height int `json:"height"`
|
||||||
|
Tab string `json:"tab,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func DefaultDashboard() []DashboardWidget {
|
||||||
|
return []DashboardWidget{{ID: "progress", Width: 4, Height: 3}, {ID: "today", Width: 4, Height: 3}, {ID: "tomorrow", Width: 4, Height: 3}, {ID: "tasks", Width: 8, Height: 4, Tab: "inbox"}, {ID: "schedule", Width: 4, Height: 4}, {ID: "activity", Width: 12, Height: 5}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ValidateDashboard(items []DashboardWidget) error {
|
||||||
|
if len(items) > 6 {
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, item := range items {
|
||||||
|
switch item.ID {
|
||||||
|
case "progress", "today", "tomorrow", "tasks", "schedule", "activity":
|
||||||
|
default:
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if seen[item.ID] || item.Width < 3 || item.Width > 12 || item.Height < 2 || item.Height > 10 {
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
|
seen[item.ID] = true
|
||||||
|
if item.ID == "tasks" {
|
||||||
|
switch item.Tab {
|
||||||
|
case "inbox", "backlog", "someday", "review", "all", "done":
|
||||||
|
default:
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
|
} else if item.Tab != "" {
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type DashboardLayout struct {
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
Widgets []DashboardWidget `json:"widgets"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Dashboard(ctx context.Context, domain, actor string) (DashboardLayout, error) {
|
||||||
|
p := DashboardLayout{Widgets: DefaultDashboard()}
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
var raw string
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT version,data FROM organizer_dashboard_layouts WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(&p.Version, &raw)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
err = json.Unmarshal([]byte(raw), &p.Widgets)
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Layout updates do not invalidate in-flight email delivery consent/version.
|
||||||
|
func (s *Store) SaveDashboard(ctx context.Context, domain, actor string, version int64, widgets []DashboardWidget) (DashboardLayout, error) {
|
||||||
|
p := DashboardLayout{}
|
||||||
|
if s.ReadOnly {
|
||||||
|
return p, ErrReadOnly
|
||||||
|
}
|
||||||
|
if version < 0 {
|
||||||
|
return p, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if err := ValidateDashboard(widgets); err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
tx, err := s.DB.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if err = taskProductivityWriter(ctx, tx, domain, actor); err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
err = tx.QueryRowContext(ctx, `SELECT version FROM organizer_dashboard_layouts WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(&p.Version)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
if p.Version != version {
|
||||||
|
return p, ErrTaskConflict
|
||||||
|
}
|
||||||
|
p.Version++
|
||||||
|
p.Widgets = widgets
|
||||||
|
if p.Widgets == nil {
|
||||||
|
p.Widgets = []DashboardWidget{}
|
||||||
|
}
|
||||||
|
data, err := json.Marshal(p.Widgets)
|
||||||
|
if err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dashboard_layouts(domain_uuid,owner_uuid,version,data) VALUES(?,?,?,?) ON CONFLICT(domain_uuid,owner_uuid) DO UPDATE SET version=excluded.version,data=excluded.data`, domain, actor, p.Version, string(data))
|
||||||
|
if err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
return p, tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
type DashboardProgress struct {
|
||||||
|
Date string `json:"date"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
Done int `json:"done"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deliberately count all rows, not a truncated list response. Cancelled and
|
||||||
|
// archived items are excluded from both numerator and denominator.
|
||||||
|
func (s *Store) DashboardProgress(ctx context.Context, domain, actor, day string) (DashboardProgress, error) {
|
||||||
|
p := DashboardProgress{Date: day}
|
||||||
|
if !validTaskDate(day) || day == "" {
|
||||||
|
return p, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT count(*),COALESCE(sum(status='done'),0) FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND kind='task' AND archived=0 AND status!='cancelled' AND planned_on=?`, domain, actor, day).Scan(&p.Total, &p.Done)
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
@@ -12,8 +12,11 @@ import (
|
|||||||
// Once released, add a new version; never edit an applied definition.
|
// Once released, add a new version; never edit an applied definition.
|
||||||
// Auth, City, tasks and calendars remain in their existing migration paths.
|
// Auth, City, tasks and calendars remain in their existing migration paths.
|
||||||
var managedStoreSchemas = map[string][]db.SQLMigration{
|
var managedStoreSchemas = map[string][]db.SQLMigration{
|
||||||
"profile-contacts": profileContactMigrations,
|
"contacts": contactMigrations,
|
||||||
"event-jobs": eventJobMigrations,
|
"task-productivity": taskProductivityMigrations,
|
||||||
|
"cli-auth": cliAuthMigrations,
|
||||||
|
"profile-contacts": profileContactMigrations,
|
||||||
|
"event-jobs": eventJobMigrations,
|
||||||
"projection-metadata": {{Version: 1, Name: "adopt_projection_metadata", Statements: []string{
|
"projection-metadata": {{Version: 1, Name: "adopt_projection_metadata", Statements: []string{
|
||||||
`CREATE TABLE IF NOT EXISTS projection_metadata (
|
`CREATE TABLE IF NOT EXISTS projection_metadata (
|
||||||
document_hash TEXT NOT NULL,kind TEXT NOT NULL,version INTEGER NOT NULL,
|
document_hash TEXT NOT NULL,kind TEXT NOT NULL,version INTEGER NOT NULL,
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package store
|
package store
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -8,6 +9,48 @@ import (
|
|||||||
"pageswiki/internal/db"
|
"pageswiki/internal/db"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestContactDAVUpgradePreservesRowsAndTracksChanges(t *testing.T) {
|
||||||
|
st := newSchemaTestStore(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
if e := db.ApplySQLiteMigrations(ctx, st.DB, "contacts", contactMigrations[:1]); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e := st.DB.Exec(`INSERT INTO organizer_contacts VALUES('d','u','c','uid',1,'Name','name','{"name":"Name"}','hash',0)`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for range 2 {
|
||||||
|
if e := st.ensureSchemaComponent("contacts"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var name, data string
|
||||||
|
var before, after int64
|
||||||
|
var count int
|
||||||
|
if e := st.DB.QueryRow(`SELECT name FROM organizer_contact_names WHERE uuid='c'`).Scan(&name); e != nil || name != "c.vcf" {
|
||||||
|
t.Fatal(name, e)
|
||||||
|
}
|
||||||
|
if e := st.DB.QueryRow(`SELECT data FROM organizer_contacts WHERE uuid='c'`).Scan(&data); e != nil || data != `{"name":"Name"}` {
|
||||||
|
t.Fatal(data, e)
|
||||||
|
}
|
||||||
|
if e := st.DB.QueryRow(`SELECT sequence FROM organizer_contact_changes WHERE uuid='c'`).Scan(&before); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for range 3 {
|
||||||
|
if _, e := st.DB.Exec(`UPDATE organizer_contacts SET deleted=1 WHERE uuid='c'`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if e := st.DB.QueryRow(`SELECT count(*),max(sequence) FROM organizer_contact_changes WHERE uuid='c'`).Scan(&count, &after); e != nil || count != 1 || after <= before {
|
||||||
|
t.Fatal(count, before, after, e)
|
||||||
|
}
|
||||||
|
if _, e := st.DB.Exec(`INSERT INTO organizer_dav_credentials VALUES('credential'); INSERT INTO organizer_contact_credentials VALUES('credential'); DELETE FROM organizer_dav_credentials WHERE id='credential'`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := st.DB.QueryRow(`SELECT count(*) FROM organizer_contact_credentials`).Scan(&count); e != nil || count != 0 {
|
||||||
|
t.Fatal(count, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func newSchemaTestStore(t *testing.T) *Store {
|
func newSchemaTestStore(t *testing.T) *Store {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
database, err := db.Open(filepath.Join(t.TempDir(), "schema.db"))
|
database, err := db.Open(filepath.Join(t.TempDir(), "schema.db"))
|
||||||
@@ -15,9 +58,58 @@ func newSchemaTestStore(t *testing.T) *Store {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
t.Cleanup(func() { database.Close() })
|
t.Cleanup(func() { database.Close() })
|
||||||
|
// task-productivity follows the legacy task schema at application startup.
|
||||||
|
// Provide its source projection, not the component under test itself.
|
||||||
|
if _, err = database.Exec(`CREATE TABLE organizer_items(domain_uuid TEXT,owner_uuid TEXT,uuid TEXT,kind TEXT,data TEXT)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = database.Exec(`CREATE TABLE organizer_dav_credentials(id TEXT PRIMARY KEY)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
return &Store{DB: database}
|
return &Store{DB: database}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTaskProductivityMigrationBackfillsOnce(t *testing.T) {
|
||||||
|
st := newSchemaTestStore(t)
|
||||||
|
if _, e := st.DB.Exec(`INSERT INTO organizer_items VALUES('d','u','t','task','{"completed_at_ms":123,"estimate_minutes":60}')`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for range 2 {
|
||||||
|
if e := st.ensureSchemaComponent("task-productivity"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var count, complexity int
|
||||||
|
var completed int64
|
||||||
|
if e := st.DB.QueryRow(`SELECT count(*),completed_ms,complexity FROM organizer_task_metrics`).Scan(&count, &completed, &complexity); e != nil || count != 1 || completed != 123 || complexity != 1 {
|
||||||
|
t.Fatal(count, completed, complexity, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDashboardUpgradePreservesTaskPreferences(t *testing.T) {
|
||||||
|
st := newSchemaTestStore(t)
|
||||||
|
if err := db.ApplySQLiteMigrations(context.Background(), st.DB, "task-productivity", taskProductivityMigrations[:1]); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := st.DB.Exec(`INSERT INTO organizer_task_preferences VALUES('domain','owner',7,'{"estimate_minutes":90}',123)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for range 2 {
|
||||||
|
if err := st.ensureSchemaComponent("task-productivity"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var version, next int64
|
||||||
|
var raw string
|
||||||
|
if err := st.DB.QueryRow(`SELECT version,data,next_digest_ms FROM organizer_task_preferences`).Scan(&version, &raw, &next); err != nil || version != 7 || next != 123 || raw != `{"estimate_minutes":90}` {
|
||||||
|
t.Fatal(version, raw, next, err)
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if err := st.DB.QueryRow(`SELECT count(*) FROM organizer_dashboard_layouts`).Scan(&count); err != nil || count != 0 {
|
||||||
|
t.Fatal(count, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestManagedSchemasFreshRepeatAndReadOnly(t *testing.T) {
|
func TestManagedSchemasFreshRepeatAndReadOnly(t *testing.T) {
|
||||||
for component := range managedStoreSchemas {
|
for component := range managedStoreSchemas {
|
||||||
t.Run(component, func(t *testing.T) {
|
t.Run(component, func(t *testing.T) {
|
||||||
|
|||||||
@@ -102,9 +102,15 @@ func NewWithDocumentRoot(
|
|||||||
if err := st.EnsureAuthSchema(); err != nil {
|
if err := st.EnsureAuthSchema(); err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
if err := st.ensureSchemaComponent("cli-auth"); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
if err := st.EnsureTasksSchema(); err != nil {
|
if err := st.EnsureTasksSchema(); err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
if err := st.ensureSchemaComponent("contacts"); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
if err := st.EnsureBrowserNavigationSchema(); err != nil {
|
if err := st.EnsureBrowserNavigationSchema(); err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,10 @@ func (s *Store) CreateTaskDAVCredential(ctx context.Context, domain, actor, labe
|
|||||||
|
|
||||||
func (s *Store) CreateDAVCredential(ctx context.Context, domain, actor, label string, write bool, days int, scope string, compatibility ...bool) (TaskDAVCredential, string, error) {
|
func (s *Store) CreateDAVCredential(ctx context.Context, domain, actor, label string, write bool, days int, scope string, compatibility ...bool) (TaskDAVCredential, string, error) {
|
||||||
compat := len(compatibility) == 1 && compatibility[0]
|
compat := len(compatibility) == 1 && compatibility[0]
|
||||||
if scope != "tasks" && scope != "calendar" && scope != "all" {
|
if scope == "contacts" && compat {
|
||||||
|
return TaskDAVCredential{}, "", ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if scope != "tasks" && scope != "calendar" && scope != "all" && scope != "contacts" {
|
||||||
return TaskDAVCredential{}, "", ErrTaskInvalid
|
return TaskDAVCredential{}, "", ErrTaskInvalid
|
||||||
}
|
}
|
||||||
label = strings.TrimSpace(label)
|
label = strings.TrimSpace(label)
|
||||||
@@ -71,12 +74,19 @@ func (s *Store) CreateDAVCredential(ctx context.Context, domain, actor, label st
|
|||||||
// of accidentally interpreting them as task-only authority.
|
// of accidentally interpreting them as task-only authority.
|
||||||
secret = "pw_dav_" + base64.RawURLEncoding.EncodeToString(raw)
|
secret = "pw_dav_" + base64.RawURLEncoding.EncodeToString(raw)
|
||||||
}
|
}
|
||||||
|
if scope == "contacts" {
|
||||||
|
secret = "pw_contactdav_" + base64.RawURLEncoding.EncodeToString(raw)
|
||||||
|
}
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
c := TaskDAVCredential{ID: uuid.NewString(), Label: label, Write: write, CreatedMS: now.UnixMilli(), ExpiresMS: now.Add(time.Duration(days) * 24 * time.Hour).UnixMilli(), Scope: scope}
|
c := TaskDAVCredential{ID: uuid.NewString(), Label: label, Write: write, CreatedMS: now.UnixMilli(), ExpiresMS: now.Add(time.Duration(days) * 24 * time.Hour).UnixMilli(), Scope: scope}
|
||||||
c.CalendarAccessCompat = compat
|
c.CalendarAccessCompat = compat
|
||||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_credentials(id,domain_uuid,owner_uuid,label,secret_hash,write_access,created_ms,expires_ms) VALUES(?,?,?,?,?,?,?,?)`, c.ID, domain, actor, c.Label, taskDAVSecretHash(secret), write, c.CreatedMS, c.ExpiresMS)
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_credentials(id,domain_uuid,owner_uuid,label,secret_hash,write_access,created_ms,expires_ms) VALUES(?,?,?,?,?,?,?,?)`, c.ID, domain, actor, c.Label, taskDAVSecretHash(secret), write, c.CreatedMS, c.ExpiresMS)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_scopes(credential_id,scope) VALUES(?,?)`, c.ID, scope)
|
if scope == "contacts" {
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_contact_credentials VALUES(?)`, c.ID)
|
||||||
|
} else {
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_scopes(credential_id,scope) VALUES(?,?)`, c.ID, scope)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if err == nil && compat {
|
if err == nil && compat {
|
||||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_compat(credential_id) VALUES(?)`, c.ID)
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_compat(credential_id) VALUES(?)`, c.ID)
|
||||||
@@ -90,7 +100,7 @@ func (s *Store) ListTaskDAVCredentials(ctx context.Context, domain, actor string
|
|||||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
rows, err := s.DB.QueryContext(ctx, `SELECT id,label,write_access,created_ms,expires_ms,COALESCE((SELECT scope FROM organizer_dav_scopes WHERE credential_id=id),'tasks'),EXISTS(SELECT 1 FROM organizer_dav_compat WHERE credential_id=id) FROM organizer_dav_credentials WHERE domain_uuid=? AND owner_uuid=? ORDER BY created_ms DESC LIMIT 100`, domain, actor)
|
rows, err := s.DB.QueryContext(ctx, `SELECT id,label,write_access,created_ms,expires_ms,CASE WHEN EXISTS(SELECT 1 FROM organizer_contact_credentials WHERE credential_id=id) THEN 'contacts' ELSE COALESCE((SELECT scope FROM organizer_dav_scopes WHERE credential_id=id),'tasks') END,EXISTS(SELECT 1 FROM organizer_dav_compat WHERE credential_id=id) FROM organizer_dav_credentials WHERE domain_uuid=? AND owner_uuid=? ORDER BY created_ms DESC LIMIT 100`, domain, actor)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -130,7 +140,7 @@ func davCredentialAllowed(ctx context.Context, q interface {
|
|||||||
QueryRowContext(context.Context, string, ...any) *sql.Row
|
QueryRowContext(context.Context, string, ...any) *sql.Row
|
||||||
}, domain, actor, id string, write bool, scope string) error {
|
}, domain, actor, id string, write bool, scope string) error {
|
||||||
var yes bool
|
var yes bool
|
||||||
if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_dav_credentials WHERE id=? AND domain_uuid=? AND owner_uuid=? AND expires_ms>? AND (?=0 OR write_access=1) AND COALESCE((SELECT scope FROM organizer_dav_scopes WHERE credential_id=id),'tasks') IN (?, 'all'))`, id, domain, actor, time.Now().UnixMilli(), write, scope).Scan(&yes); err != nil {
|
if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_dav_credentials WHERE id=? AND domain_uuid=? AND owner_uuid=? AND expires_ms>? AND (?=0 OR write_access=1) AND ((?='contacts' AND EXISTS(SELECT 1 FROM organizer_contact_credentials WHERE credential_id=id)) OR (? IN ('tasks','calendar') AND NOT EXISTS(SELECT 1 FROM organizer_contact_credentials WHERE credential_id=id) AND COALESCE((SELECT scope FROM organizer_dav_scopes WHERE credential_id=id),'tasks') IN (?, 'all'))))`, id, domain, actor, time.Now().UnixMilli(), write, scope, scope, scope).Scan(&yes); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !yes {
|
if !yes {
|
||||||
@@ -151,16 +161,19 @@ func (s *Store) CheckDAVCredential(ctx context.Context, domain, actor, id string
|
|||||||
|
|
||||||
// An empty requested scope is discovery only; callers must filter collections.
|
// An empty requested scope is discovery only; callers must filter collections.
|
||||||
func (s *Store) AuthenticateDAV(ctx context.Context, domain, id, secret, requested string) (string, bool, string, error) {
|
func (s *Store) AuthenticateDAV(ctx context.Context, domain, id, secret, requested string) (string, bool, string, error) {
|
||||||
if len(secret) > 128 || !(strings.HasPrefix(secret, "pw_taskdav_") || strings.HasPrefix(secret, "pw_dav_")) {
|
if len(secret) > 128 || !(strings.HasPrefix(secret, "pw_taskdav_") || strings.HasPrefix(secret, "pw_dav_") || strings.HasPrefix(secret, "pw_contactdav_")) {
|
||||||
return "", false, "", ErrAccessDenied
|
return "", false, "", ErrAccessDenied
|
||||||
}
|
}
|
||||||
var actor, hash, state, scope string
|
var actor, hash, state, scope string
|
||||||
var write bool
|
var write bool
|
||||||
err := s.DB.QueryRowContext(ctx, `SELECT c.owner_uuid,c.secret_hash,c.write_access,p.state,COALESCE(s.scope,'tasks') FROM organizer_dav_credentials c JOIN principals p ON p.uuid=c.owner_uuid LEFT JOIN organizer_dav_scopes s ON s.credential_id=c.id WHERE c.id=? AND c.domain_uuid=? AND c.expires_ms>?`, id, domain, time.Now().UnixMilli()).Scan(&actor, &hash, &write, &state, &scope)
|
err := s.DB.QueryRowContext(ctx, `SELECT c.owner_uuid,c.secret_hash,c.write_access,p.state,CASE WHEN EXISTS(SELECT 1 FROM organizer_contact_credentials WHERE credential_id=c.id) THEN 'contacts' ELSE COALESCE(s.scope,'tasks') END FROM organizer_dav_credentials c JOIN principals p ON p.uuid=c.owner_uuid LEFT JOIN organizer_dav_scopes s ON s.credential_id=c.id WHERE c.id=? AND c.domain_uuid=? AND c.expires_ms>?`, id, domain, time.Now().UnixMilli()).Scan(&actor, &hash, &write, &state, &scope)
|
||||||
if err != nil || subtle.ConstantTimeCompare([]byte(hash), []byte(taskDAVSecretHash(secret))) != 1 {
|
if err != nil || subtle.ConstantTimeCompare([]byte(hash), []byte(taskDAVSecretHash(secret))) != 1 {
|
||||||
return "", false, "", ErrAccessDenied
|
return "", false, "", ErrAccessDenied
|
||||||
}
|
}
|
||||||
if requested != "" && scope != "all" && scope != requested {
|
if strings.HasPrefix(secret, "pw_contactdav_") && scope != "contacts" {
|
||||||
|
return "", false, "", ErrAccessDenied
|
||||||
|
}
|
||||||
|
if requested != "" && scope != requested && !(scope == "all" && (requested == "tasks" || requested == "calendar")) {
|
||||||
return "", false, "", ErrAccessDenied
|
return "", false, "", ErrAccessDenied
|
||||||
}
|
}
|
||||||
if err = taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
if err = taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const TaskDigestEventType = "task.digest.deliver"
|
||||||
|
|
||||||
|
type TaskDigestDue struct {
|
||||||
|
Domain string
|
||||||
|
Owner string
|
||||||
|
}
|
||||||
|
type TaskDigestClaim struct {
|
||||||
|
TaskDigestDue
|
||||||
|
Day string
|
||||||
|
Version int64
|
||||||
|
Timezone string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) EnsureTaskDigestEvent() error {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return ErrReadOnly
|
||||||
|
}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
_, err := s.DB.Exec(`INSERT OR IGNORE INTO event_definitions(uuid,name,event_type,event_key,payload,schedule_kind,interval_seconds,next_run_at_ms,enabled,priority,max_attempts,created_at_ms,updated_at_ms) VALUES('builtin.task.digest','Daily task email',?,'local','{}','interval',60,?,1,-2,1,?,?)`, TaskDigestEventType, now, now, now)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) DueTaskDigests(ctx context.Context, now time.Time) ([]TaskDigestDue, error) {
|
||||||
|
rows, err := s.DB.QueryContext(ctx, `SELECT domain_uuid,owner_uuid FROM organizer_task_preferences WHERE next_digest_ms>0 AND next_digest_ms<=? ORDER BY next_digest_ms,domain_uuid,owner_uuid LIMIT 20`, now.UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []TaskDigestDue{}
|
||||||
|
for rows.Next() {
|
||||||
|
var v TaskDigestDue
|
||||||
|
if err = rows.Scan(&v.Domain, &v.Owner); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, v)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Claim before SMTP: an ambiguous delivery is never automatically sent twice.
|
||||||
|
// An interrupted claim stays visible as "sending" for operator review.
|
||||||
|
func (s *Store) ClaimTaskDigest(ctx context.Context, due TaskDigestDue, now time.Time) (TaskDigestClaim, error) {
|
||||||
|
out := TaskDigestClaim{TaskDigestDue: due}
|
||||||
|
if s.ReadOnly {
|
||||||
|
return out, ErrReadOnly
|
||||||
|
}
|
||||||
|
tx, err := s.DB.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
res, err := tx.ExecContext(ctx, `UPDATE organizer_task_preferences SET next_digest_ms=next_digest_ms WHERE domain_uuid=? AND owner_uuid=? AND next_digest_ms>0 AND next_digest_ms<=?`, due.Domain, due.Owner, now.UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n, _ := res.RowsAffected()
|
||||||
|
if n != 1 {
|
||||||
|
return out, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
var raw string
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, due.Domain, due.Owner).Scan(&raw); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
var p TaskPreferences
|
||||||
|
if err = json.Unmarshal([]byte(raw), &p); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
loc, err := time.LoadLocation(p.Timezone)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.Day = now.In(loc).Format("2006-01-02")
|
||||||
|
out.Timezone = p.Timezone
|
||||||
|
out.Version = p.Version
|
||||||
|
allowed := taskActor(ctx, tx, due.Domain, due.Owner, true)
|
||||||
|
on, e := taskReminderExtensionEnabled(ctx, tx, due.Domain)
|
||||||
|
if e != nil {
|
||||||
|
return out, e
|
||||||
|
}
|
||||||
|
if allowed != nil && !errors.Is(allowed, ErrAccessDenied) {
|
||||||
|
return out, allowed
|
||||||
|
}
|
||||||
|
if allowed != nil || !on || !p.DigestEnabled {
|
||||||
|
// An opted-in schedule resumes after a domain or extension is restored.
|
||||||
|
next, e := nextTaskDigest(now, p)
|
||||||
|
if e != nil {
|
||||||
|
return out, e
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `UPDATE organizer_task_preferences SET next_digest_ms=? WHERE domain_uuid=? AND owner_uuid=?`, next, due.Domain, due.Owner)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
return out, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
// Missed days are not replayed. Run once for today's due time; if the
|
||||||
|
// configured hour has not arrived, move the cursor there without sending.
|
||||||
|
clock, _ := time.Parse("15:04", p.DigestTime)
|
||||||
|
local := now.In(loc)
|
||||||
|
today := time.Date(local.Year(), local.Month(), local.Day(), clock.Hour(), clock.Minute(), 0, 0, loc)
|
||||||
|
next, err := nextTaskDigest(now, p)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `UPDATE organizer_task_preferences SET next_digest_ms=? WHERE domain_uuid=? AND owner_uuid=?`, next, due.Domain, due.Owner)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if today.After(now) {
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
return out, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
res, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO organizer_digest_deliveries VALUES(?,?,?,'sending',?)`, due.Domain, due.Owner, out.Day, now.UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n, _ = res.RowsAffected()
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if n != 1 {
|
||||||
|
return out, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) TaskDigestRecipient(ctx context.Context, c TaskDigestClaim) (string, error) {
|
||||||
|
if err := taskActor(ctx, s.DB, c.Domain, c.Owner, true); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
var raw, email string
|
||||||
|
var version int64
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT f.data,f.version,p.email FROM organizer_task_preferences f JOIN principals p ON p.uuid=f.owner_uuid WHERE f.domain_uuid=? AND f.owner_uuid=?`, c.Domain, c.Owner).Scan(&raw, &version, &email)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
var p TaskPreferences
|
||||||
|
if json.Unmarshal([]byte(raw), &p) != nil || !p.DigestEnabled || version != c.Version {
|
||||||
|
return "", ErrAccessDenied
|
||||||
|
}
|
||||||
|
return email, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) FinishTaskDigest(ctx context.Context, c TaskDigestClaim, state string) error {
|
||||||
|
if state != "sent" && state != "uncertain" && state != "cancelled" {
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
|
_, err := s.DB.ExecContext(ctx, `UPDATE organizer_digest_deliveries SET state=?,updated_ms=? WHERE domain_uuid=? AND owner_uuid=? AND day=? AND state='sending'`, state, time.Now().UnixMilli(), c.Domain, c.Owner, c.Day)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) LastTaskDigest(ctx context.Context, domain, actor string) (map[string]any, error) {
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var day, state string
|
||||||
|
var ms int64
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT day,state,updated_ms FROM organizer_digest_deliveries WHERE domain_uuid=? AND owner_uuid=? ORDER BY day DESC LIMIT 1`, domain, actor).Scan(&day, &state, &ms)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return map[string]any{"day": day, "state": state, "updated_at_ms": ms}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,471 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
var taskProductivityMigrations = []db.SQLMigration{{Version: 1, Name: "task_capture_work_and_reporting", Statements: []string{
|
||||||
|
`CREATE TABLE organizer_task_preferences(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,version INTEGER NOT NULL,data TEXT NOT NULL,next_digest_ms INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(domain_uuid,owner_uuid))`,
|
||||||
|
`CREATE INDEX organizer_digest_due ON organizer_task_preferences(next_digest_ms) WHERE next_digest_ms>0`,
|
||||||
|
`CREATE TABLE organizer_capture_receipts(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,request_uuid TEXT NOT NULL,request_hash TEXT NOT NULL,item_uuid TEXT NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,request_uuid))`,
|
||||||
|
`CREATE TABLE organizer_work_sessions(uuid TEXT PRIMARY KEY,domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,task_uuid TEXT NOT NULL,start_ms INTEGER NOT NULL,end_ms INTEGER NOT NULL DEFAULT 0,version INTEGER NOT NULL DEFAULT 1)`,
|
||||||
|
`CREATE UNIQUE INDEX organizer_work_active ON organizer_work_sessions(owner_uuid) WHERE end_ms=0`,
|
||||||
|
`CREATE INDEX organizer_work_period ON organizer_work_sessions(domain_uuid,owner_uuid,start_ms,uuid)`,
|
||||||
|
`CREATE TABLE organizer_task_metrics(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,task_uuid TEXT NOT NULL,completed_ms INTEGER NOT NULL,estimate INTEGER NOT NULL,complexity INTEGER NOT NULL,PRIMARY KEY(domain_uuid,task_uuid))`,
|
||||||
|
`CREATE INDEX organizer_task_completed ON organizer_task_metrics(domain_uuid,owner_uuid,completed_ms)`,
|
||||||
|
`INSERT INTO organizer_task_metrics SELECT domain_uuid,owner_uuid,uuid,COALESCE(json_extract(data,'$.completed_at_ms'),0),COALESCE(json_extract(data,'$.estimate_minutes'),0),max(1,COALESCE(json_extract(data,'$.complexity'),1)) FROM organizer_items WHERE kind='task'`,
|
||||||
|
`CREATE TABLE organizer_digest_deliveries(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,day TEXT NOT NULL,state TEXT NOT NULL,updated_ms INTEGER NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,day))`,
|
||||||
|
}, Assertions: []string{
|
||||||
|
schemaColumns("organizer_task_preferences", "domain_uuid,owner_uuid,version,data,next_digest_ms"),
|
||||||
|
schemaUnique("organizer_capture_receipts", "domain_uuid,owner_uuid,request_uuid"),
|
||||||
|
schemaIndex("organizer_work_sessions", "organizer_work_period", "domain_uuid,owner_uuid,start_ms,uuid"),
|
||||||
|
}}, {Version: 2, Name: "personal_dashboard_layout", Statements: []string{
|
||||||
|
`CREATE TABLE organizer_dashboard_layouts(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,version INTEGER NOT NULL,data TEXT NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid))`,
|
||||||
|
}, Assertions: []string{schemaColumns("organizer_dashboard_layouts", "domain_uuid,owner_uuid,version,data"), schemaUnique("organizer_dashboard_layouts", "domain_uuid,owner_uuid")}}}
|
||||||
|
|
||||||
|
type TaskPreferences struct {
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
ProjectUUID string `json:"project_uuid"`
|
||||||
|
AssigneeUUID string `json:"assignee_uuid"`
|
||||||
|
DueDays *int `json:"due_days"`
|
||||||
|
StartDays *int `json:"start_days"`
|
||||||
|
PlannedDays *int `json:"planned_days"`
|
||||||
|
ReviewDays *int `json:"review_days"`
|
||||||
|
Estimate int `json:"estimate_minutes"`
|
||||||
|
Complexity int `json:"complexity"`
|
||||||
|
NotifyDue bool `json:"notify_due"`
|
||||||
|
NotifyPlanned bool `json:"notify_planned"`
|
||||||
|
ReminderTime string `json:"reminder_time"`
|
||||||
|
DigestEnabled bool `json:"digest_enabled"`
|
||||||
|
DigestTime string `json:"digest_time"`
|
||||||
|
Timezone string `json:"timezone"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) TaskPreferences(ctx context.Context, domain, actor string) (TaskPreferences, error) {
|
||||||
|
p := TaskPreferences{AssigneeUUID: actor, Complexity: 1, ReminderTime: "09:00", DigestTime: "09:00", Timezone: "UTC"}
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
var raw string
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT data FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(&raw)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
err = json.Unmarshal([]byte(raw), &p)
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func nextTaskDigest(now time.Time, p TaskPreferences) (int64, error) {
|
||||||
|
loc, err := time.LoadLocation(p.Timezone)
|
||||||
|
if err != nil {
|
||||||
|
return 0, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
clock, err := time.Parse("15:04", p.DigestTime)
|
||||||
|
if err != nil || clock.Format("15:04") != p.DigestTime {
|
||||||
|
return 0, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if !p.DigestEnabled {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
t := now.In(loc)
|
||||||
|
candidate := time.Date(t.Year(), t.Month(), t.Day(), clock.Hour(), clock.Minute(), 0, 0, loc)
|
||||||
|
if !candidate.After(now) {
|
||||||
|
candidate = time.Date(t.Year(), t.Month(), t.Day()+1, clock.Hour(), clock.Minute(), 0, 0, loc)
|
||||||
|
}
|
||||||
|
return candidate.UnixMilli(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) SaveTaskPreferences(ctx context.Context, domain, actor string, p TaskPreferences, now time.Time) (TaskPreferences, error) {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return p, ErrReadOnly
|
||||||
|
}
|
||||||
|
// Older clients do not send this field. Preserve their default clock.
|
||||||
|
if p.ReminderTime == "" {
|
||||||
|
p.ReminderTime = "09:00"
|
||||||
|
}
|
||||||
|
clock, clockErr := time.Parse("15:04", p.ReminderTime)
|
||||||
|
if clockErr != nil || clock.Format("15:04") != p.ReminderTime {
|
||||||
|
return p, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
for _, n := range []*int{p.DueDays, p.StartDays, p.PlannedDays, p.ReviewDays} {
|
||||||
|
if n != nil && (*n < 0 || *n > 3650) {
|
||||||
|
return p, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.Estimate < 0 || p.Estimate > 10080 || p.Complexity < 1 || p.Complexity > 5 || p.Version < 0 {
|
||||||
|
return p, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
next, err := nextTaskDigest(now, p)
|
||||||
|
if err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
tx, err := s.DB.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if err = taskProductivityWriter(ctx, tx, domain, actor); err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
if err = validateTaskAssignee(ctx, tx, domain, p.AssigneeUUID); err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
if p.ProjectUUID != "" {
|
||||||
|
var yes bool
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND kind='project' AND archived=0)`, domain, actor, p.ProjectUUID).Scan(&yes); err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
if !yes {
|
||||||
|
return p, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var current int64
|
||||||
|
err = tx.QueryRowContext(ctx, `SELECT version FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(¤t)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
if current != p.Version {
|
||||||
|
return p, ErrTaskConflict
|
||||||
|
}
|
||||||
|
p.Version++
|
||||||
|
raw, _ := json.Marshal(p)
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_task_preferences VALUES(?,?,?,?,?) ON CONFLICT(domain_uuid,owner_uuid) DO UPDATE SET version=excluded.version,data=excluded.data,next_digest_ms=excluded.next_digest_ms`, domain, actor, p.Version, string(raw), next)
|
||||||
|
if err != nil {
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
return p, tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
func taskProductivityWriter(ctx context.Context, tx *sql.Tx, domain, actor string) error {
|
||||||
|
if _, err := tx.ExecContext(ctx, `UPDATE domain_memberships SET state=state WHERE domain_uuid=? AND principal_uuid=?`, domain, actor); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := taskActor(ctx, tx, domain, actor, true); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
on, err := taskReminderExtensionEnabled(ctx, tx, domain)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !on {
|
||||||
|
return ErrAccessDenied
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assignment is a private planning annotation, NOT a grant to read this task.
|
||||||
|
func validateTaskAssignee(ctx context.Context, tx *sql.Tx, domain, assignee string) error {
|
||||||
|
if assignee == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if _, err := uuid.Parse(assignee); err != nil {
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if err := taskActor(ctx, tx, domain, assignee, false); err != nil {
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) CapturedTask(ctx context.Context, domain, actor, request, hash string) (TaskRecord, error) {
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return TaskRecord{}, err
|
||||||
|
}
|
||||||
|
var stored, id string
|
||||||
|
err := s.DB.QueryRowContext(ctx, `SELECT request_hash,item_uuid FROM organizer_capture_receipts WHERE domain_uuid=? AND owner_uuid=? AND request_uuid=?`, domain, actor, request).Scan(&stored, &id)
|
||||||
|
if err != nil {
|
||||||
|
return TaskRecord{}, err
|
||||||
|
}
|
||||||
|
if stored != hash {
|
||||||
|
return TaskRecord{}, ErrTaskConflict
|
||||||
|
}
|
||||||
|
return s.GetTask(ctx, domain, actor, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) CaptureTask(ctx context.Context, domain, actor, request, hash string, item TaskRecord) (TaskRecord, error) {
|
||||||
|
if _, err := uuid.Parse(request); err != nil {
|
||||||
|
return TaskRecord{}, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
old, err := s.CapturedTask(ctx, domain, actor, request, hash)
|
||||||
|
if err == nil {
|
||||||
|
return old, nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return old, err
|
||||||
|
}
|
||||||
|
item.UUID = request
|
||||||
|
out, err := s.saveTask(ctx, domain, actor, item, 0, func(tx *sql.Tx, _ *TaskRecord, _ TaskRecord) error {
|
||||||
|
_, e := tx.ExecContext(ctx, `INSERT INTO organizer_capture_receipts VALUES(?,?,?,?,?)`, domain, actor, request, hash, item.UUID)
|
||||||
|
return e
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if old, e := s.CapturedTask(ctx, domain, actor, request, hash); e == nil {
|
||||||
|
return old, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type TaskWork struct {
|
||||||
|
UUID string `json:"uuid"`
|
||||||
|
TaskUUID string `json:"task_uuid"`
|
||||||
|
StartMS int64 `json:"start_ms"`
|
||||||
|
EndMS int64 `json:"end_ms"`
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanTaskWork(row interface{ Scan(...any) error }) (TaskWork, error) {
|
||||||
|
var v TaskWork
|
||||||
|
err := row.Scan(&v.UUID, &v.TaskUUID, &v.StartMS, &v.EndMS, &v.Version)
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
|
||||||
|
const taskWorkColumns = `uuid,task_uuid,start_ms,end_ms,version`
|
||||||
|
|
||||||
|
func (s *Store) ActiveTaskWork(ctx context.Context, domain, actor string) (*TaskWork, error) {
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
v, err := scanTaskWork(s.DB.QueryRowContext(ctx, `SELECT `+taskWorkColumns+` FROM organizer_work_sessions WHERE domain_uuid=? AND owner_uuid=? AND end_ms=0`, domain, actor))
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return &v, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ChangeTaskWork(ctx context.Context, domain, actor, action string, v TaskWork, now time.Time) (TaskWork, error) {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return v, ErrReadOnly
|
||||||
|
}
|
||||||
|
if _, err := uuid.Parse(v.UUID); err != nil {
|
||||||
|
return v, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
tx, err := s.DB.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if err = taskProductivityWriter(ctx, tx, domain, actor); err != nil {
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
old, err := scanTaskWork(tx.QueryRowContext(ctx, `SELECT `+taskWorkColumns+` FROM organizer_work_sessions WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, v.UUID, domain, actor))
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
switch action {
|
||||||
|
case "start":
|
||||||
|
if v.Version != 0 {
|
||||||
|
return v, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
if old.TaskUUID != v.TaskUUID {
|
||||||
|
return v, ErrTaskConflict
|
||||||
|
}
|
||||||
|
return old, tx.Commit()
|
||||||
|
}
|
||||||
|
var yes bool
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND kind='task' AND archived=0 AND status NOT IN ('done','cancelled'))`, domain, actor, v.TaskUUID).Scan(&yes); err != nil {
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
if !yes {
|
||||||
|
return v, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
v.StartMS = now.UnixMilli()
|
||||||
|
v.EndMS = 0
|
||||||
|
v.Version = 1
|
||||||
|
res, e := tx.ExecContext(ctx, `INSERT OR IGNORE INTO organizer_work_sessions(uuid,domain_uuid,owner_uuid,task_uuid,start_ms) VALUES(?,?,?,?,?)`, v.UUID, domain, actor, v.TaskUUID, v.StartMS)
|
||||||
|
if e != nil {
|
||||||
|
return v, e
|
||||||
|
}
|
||||||
|
n, _ := res.RowsAffected()
|
||||||
|
if n != 1 {
|
||||||
|
return v, ErrTaskConflict
|
||||||
|
}
|
||||||
|
case "stop":
|
||||||
|
if err != nil {
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
if old.EndMS > 0 {
|
||||||
|
if v.Version == old.Version || v.Version == old.Version-1 {
|
||||||
|
return old, tx.Commit()
|
||||||
|
}
|
||||||
|
return v, ErrTaskConflict
|
||||||
|
}
|
||||||
|
if old.Version != v.Version {
|
||||||
|
return v, ErrTaskConflict
|
||||||
|
}
|
||||||
|
v = old
|
||||||
|
v.EndMS = max(v.StartMS, now.UnixMilli())
|
||||||
|
v.Version++
|
||||||
|
_, err = tx.ExecContext(ctx, `UPDATE organizer_work_sessions SET end_ms=?,version=? WHERE uuid=?`, v.EndMS, v.Version, v.UUID)
|
||||||
|
if err != nil {
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return v, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
return v, tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
type TaskReportDay struct {
|
||||||
|
Date string `json:"date"`
|
||||||
|
Completed int `json:"completed"`
|
||||||
|
Points int `json:"points"`
|
||||||
|
Estimate int `json:"estimate_minutes"`
|
||||||
|
WorkMS int64 `json:"work_ms"`
|
||||||
|
FocusMS int64 `json:"focus_ms"`
|
||||||
|
}
|
||||||
|
type TaskReportItem struct {
|
||||||
|
UUID string `json:"uuid"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
ProjectUUID string `json:"project_uuid"`
|
||||||
|
WorkMS int64 `json:"work_ms"`
|
||||||
|
Points int `json:"points"`
|
||||||
|
Completed bool `json:"completed"`
|
||||||
|
}
|
||||||
|
type TaskReport struct {
|
||||||
|
Days []TaskReportDay `json:"days"`
|
||||||
|
Tasks []TaskReportItem `json:"tasks"`
|
||||||
|
Sessions []TaskWork `json:"sessions"`
|
||||||
|
Partial bool `json:"partial"`
|
||||||
|
Timezone string `json:"timezone"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) TaskReport(ctx context.Context, domain, actor string, start, end, now time.Time) (TaskReport, error) {
|
||||||
|
out := TaskReport{Days: []TaskReportDay{}, Tasks: []TaskReportItem{}, Sessions: []TaskWork{}, Timezone: start.Location().String()}
|
||||||
|
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if !end.After(start) || end.Sub(start) > 367*24*time.Hour {
|
||||||
|
return out, ErrTaskInvalid
|
||||||
|
}
|
||||||
|
days := map[string]int{}
|
||||||
|
for day := start; day.Before(end); day = day.AddDate(0, 0, 1) {
|
||||||
|
days[day.Format("2006-01-02")] = len(out.Days)
|
||||||
|
out.Days = append(out.Days, TaskReportDay{Date: day.Format("2006-01-02")})
|
||||||
|
}
|
||||||
|
byTask := map[string]int{}
|
||||||
|
rows, err := s.DB.QueryContext(ctx, `SELECT m.completed_ms,m.estimate,m.complexity,m.task_uuid,COALESCE(i.title,''),COALESCE(i.project_uuid,'') FROM organizer_task_metrics m LEFT JOIN organizer_items i ON i.domain_uuid=m.domain_uuid AND i.owner_uuid=m.owner_uuid AND i.uuid=m.task_uuid WHERE m.domain_uuid=? AND m.owner_uuid=? AND m.completed_ms>=? AND m.completed_ms<? ORDER BY m.completed_ms,m.task_uuid LIMIT 10001`, domain, actor, start.UnixMilli(), end.UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n := 0
|
||||||
|
for rows.Next() {
|
||||||
|
var ms int64
|
||||||
|
var estimate, complexity int
|
||||||
|
var id, title, project string
|
||||||
|
if err = rows.Scan(&ms, &estimate, &complexity, &id, &title, &project); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
if n > 10000 {
|
||||||
|
out.Partial = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if index, ok := days[time.UnixMilli(ms).In(start.Location()).Format("2006-01-02")]; ok {
|
||||||
|
d := &out.Days[index]
|
||||||
|
d.Completed++
|
||||||
|
d.Estimate += estimate
|
||||||
|
d.Points += 1 + ((estimate+29)/30)*max(1, complexity)
|
||||||
|
byTask[id] = len(out.Tasks)
|
||||||
|
out.Tasks = append(out.Tasks, TaskReportItem{UUID: id, Title: title, ProjectUUID: project, Completed: true, Points: 1 + ((estimate+29)/30)*max(1, complexity)})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err = rows.Err()
|
||||||
|
rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
// Split intervals at local midnight; never assume a day is exactly 24h.
|
||||||
|
addSpan := func(a, b int64, focus bool) int64 {
|
||||||
|
a = max(a, start.UnixMilli())
|
||||||
|
b = min(b, end.UnixMilli(), now.UnixMilli())
|
||||||
|
if b <= a {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
total := b - a
|
||||||
|
for a < b {
|
||||||
|
t := time.UnixMilli(a).In(start.Location())
|
||||||
|
next := time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location()).UnixMilli()
|
||||||
|
stop := min(next, b)
|
||||||
|
if index, ok := days[t.Format("2006-01-02")]; ok {
|
||||||
|
if focus {
|
||||||
|
out.Days[index].FocusMS += stop - a
|
||||||
|
} else {
|
||||||
|
out.Days[index].WorkMS += stop - a
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a = stop
|
||||||
|
}
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
rows, err = s.DB.QueryContext(ctx, `SELECT w.uuid,w.task_uuid,w.start_ms,w.end_ms,w.version,COALESCE(i.title,''),COALESCE(i.project_uuid,'') FROM organizer_work_sessions w LEFT JOIN organizer_items i ON i.domain_uuid=w.domain_uuid AND i.owner_uuid=w.owner_uuid AND i.uuid=w.task_uuid WHERE w.domain_uuid=? AND w.owner_uuid=? AND w.start_ms<? AND (w.end_ms=0 OR w.end_ms>?) ORDER BY w.start_ms DESC,w.uuid LIMIT 10001`, domain, actor, end.UnixMilli(), start.UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n = 0
|
||||||
|
for rows.Next() {
|
||||||
|
var v TaskWork
|
||||||
|
var title, project string
|
||||||
|
if err = rows.Scan(&v.UUID, &v.TaskUUID, &v.StartMS, &v.EndMS, &v.Version, &title, &project); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
if n > 10000 {
|
||||||
|
out.Partial = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
finish := v.EndMS
|
||||||
|
if finish == 0 {
|
||||||
|
finish = now.UnixMilli()
|
||||||
|
}
|
||||||
|
elapsed := addSpan(v.StartMS, finish, false)
|
||||||
|
if elapsed == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out.Sessions = append(out.Sessions, v)
|
||||||
|
index, ok := byTask[v.TaskUUID]
|
||||||
|
if !ok {
|
||||||
|
index = len(out.Tasks)
|
||||||
|
byTask[v.TaskUUID] = index
|
||||||
|
out.Tasks = append(out.Tasks, TaskReportItem{UUID: v.TaskUUID, Title: title, ProjectUUID: project})
|
||||||
|
}
|
||||||
|
out.Tasks[index].WorkMS += elapsed
|
||||||
|
}
|
||||||
|
err = rows.Err()
|
||||||
|
rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
rows, err = s.DB.QueryContext(ctx, `SELECT start_ms,end_ms FROM organizer_focus_spans WHERE domain_uuid=? AND owner_uuid=? AND start_ms>=? AND start_ms<? AND end_ms>? AND phase='focus' ORDER BY start_ms,session_uuid,version LIMIT 10001`, domain, actor, start.Add(-180*time.Minute).UnixMilli(), end.UnixMilli(), start.UnixMilli())
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
n = 0
|
||||||
|
for rows.Next() {
|
||||||
|
var a, b int64
|
||||||
|
if err = rows.Scan(&a, &b); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
if n > 10000 {
|
||||||
|
out.Partial = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
addSpan(a, b, true)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
+22
-1
@@ -36,6 +36,8 @@ type TaskRecord struct {
|
|||||||
DueOn string `json:"due_on"`
|
DueOn string `json:"due_on"`
|
||||||
PlannedOn string `json:"planned_on"`
|
PlannedOn string `json:"planned_on"`
|
||||||
ReviewOn string `json:"review_on"`
|
ReviewOn string `json:"review_on"`
|
||||||
|
AssigneeUUID string `json:"assignee_uuid,omitempty"`
|
||||||
|
Complexity int `json:"complexity,omitempty"`
|
||||||
PageUUID string `json:"page_uuid"`
|
PageUUID string `json:"page_uuid"`
|
||||||
Archived bool `json:"archived"`
|
Archived bool `json:"archived"`
|
||||||
Version int64 `json:"version"`
|
Version int64 `json:"version"`
|
||||||
@@ -96,7 +98,10 @@ func (s *Store) EnsureTasksSchema() error {
|
|||||||
if err := s.ensureTaskBlocksSchema(); err != nil {
|
if err := s.ensureTaskBlocksSchema(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return s.ensureTaskFocusSchema()
|
if err := s.ensureTaskFocusSchema(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return s.ensureSchemaComponent("task-productivity")
|
||||||
}
|
}
|
||||||
|
|
||||||
func validTaskDate(v string) bool {
|
func validTaskDate(v string) bool {
|
||||||
@@ -108,6 +113,9 @@ func validTaskDate(v string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func validateTask(item *TaskRecord) error {
|
func validateTask(item *TaskRecord) error {
|
||||||
|
if item.Complexity < 0 || item.Complexity > 5 {
|
||||||
|
return ErrTaskInvalid
|
||||||
|
}
|
||||||
if !validTaskNotesSubpath(item.NotesSubpath) || (item.Kind != "project" && item.NotesSubpath != "") {
|
if !validTaskNotesSubpath(item.NotesSubpath) || (item.Kind != "project" && item.NotesSubpath != "") {
|
||||||
return ErrTaskInvalid
|
return ErrTaskInvalid
|
||||||
}
|
}
|
||||||
@@ -188,6 +196,9 @@ func (s *Store) SaveTask(ctx context.Context, domain, actor string, item TaskRec
|
|||||||
|
|
||||||
// prepare participates in the same writer transaction as the task head.
|
// prepare participates in the same writer transaction as the task head.
|
||||||
func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRecord, expected int64, prepare func(*sql.Tx, *TaskRecord, TaskRecord) error) (TaskRecord, error) {
|
func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRecord, expected int64, prepare func(*sql.Tx, *TaskRecord, TaskRecord) error) (TaskRecord, error) {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return TaskRecord{}, ErrReadOnly
|
||||||
|
}
|
||||||
if err := validateTask(&item); err != nil {
|
if err := validateTask(&item); err != nil {
|
||||||
return TaskRecord{}, err
|
return TaskRecord{}, err
|
||||||
}
|
}
|
||||||
@@ -266,6 +277,11 @@ func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRec
|
|||||||
if err = s.validateTaskParentTx(ctx, tx, domain, actor, item, old); err != nil {
|
if err = s.validateTaskParentTx(ctx, tx, domain, actor, item, old); err != nil {
|
||||||
return TaskRecord{}, err
|
return TaskRecord{}, err
|
||||||
}
|
}
|
||||||
|
if item.AssigneeUUID != old.AssigneeUUID {
|
||||||
|
if err = validateTaskAssignee(ctx, tx, domain, item.AssigneeUUID); err != nil {
|
||||||
|
return TaskRecord{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
// DAV identity and round-trip metadata are writable only through the DAV
|
// DAV identity and round-trip metadata are writable only through the DAV
|
||||||
// transaction callback, never through a generic JSON/UI update.
|
// transaction callback, never through a generic JSON/UI update.
|
||||||
item.CalDAV = old.CalDAV
|
item.CalDAV = old.CalDAV
|
||||||
@@ -330,6 +346,11 @@ func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRec
|
|||||||
if err = s.syncTaskRemindersTx(ctx, tx, domain, actor, item); err != nil {
|
if err = s.syncTaskRemindersTx(ctx, tx, domain, actor, item); err != nil {
|
||||||
return TaskRecord{}, err
|
return TaskRecord{}, err
|
||||||
}
|
}
|
||||||
|
if item.Kind == "task" {
|
||||||
|
if _, err = tx.ExecContext(ctx, `INSERT INTO organizer_task_metrics VALUES(?,?,?,?,?,?) ON CONFLICT(domain_uuid,task_uuid) DO UPDATE SET completed_ms=excluded.completed_ms,estimate=excluded.estimate,complexity=excluded.complexity`, domain, actor, item.UUID, item.CompletedMS, item.Estimate, max(1, item.Complexity)); err != nil {
|
||||||
|
return TaskRecord{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
if err = tx.Commit(); err != nil {
|
if err = tx.Commit(); err != nil {
|
||||||
return TaskRecord{}, err
|
return TaskRecord{}, err
|
||||||
}
|
}
|
||||||
|
|||||||
+59
-7
@@ -34,11 +34,41 @@ pages[default]:/manual> exit
|
|||||||
|
|
||||||
`exit` はシェルを閉じるだけです。セッションを失効させる場合は `pages logout`。
|
`exit` はシェルを閉じるだけです。セッションを失効させる場合は `pages logout`。
|
||||||
|
|
||||||
|
### OIDCでログインする
|
||||||
|
|
||||||
|
OIDC連携を有効にしたDomainで利用します。サーバーとCLIの両方に **v0.3.0以降** が必要です。
|
||||||
|
CLIのファイルだけを更新しても、v0.2.xのサーバーでは利用できません。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages configure --origin https://pages.example.test
|
||||||
|
pages login --oidc
|
||||||
|
# SSH先など、ブラウザを自動で開かない場合
|
||||||
|
pages login --oidc --no-browser
|
||||||
|
```
|
||||||
|
|
||||||
|
CLIに表示されたURLを手元のPC/スマホで開き、OIDCでログインします。
|
||||||
|
続いてアカウント・接続先を確認し、ターミナルの確認コードを入力して承認します。
|
||||||
|
OIDCで認証した場合は、追加のローカルTOTPを要求しません。承認後はCLIが専用セッションを受け取ります。
|
||||||
|
OIDCプロバイダーのパスワードやトークンをターミナルに入力する必要はありません。
|
||||||
|
プロバイダー側のMFAポリシーはそのまま適用されます。パスワードログイン時のローカルTOTPも変更しません。
|
||||||
|
この追加TOTP省略にはv0.4.0以降のサーバーが必要です。v0.3.0では従来どおりTOTPを要求します。
|
||||||
|
|
||||||
|
ユーザー名の指定は省略できます。指定済みならブラウザで認証したユーザーとの一致を確認し、
|
||||||
|
不一致時は発行セッションの失効を試みて保存しません。`pages logout` 後に設定を変更できます。
|
||||||
|
リクエストは5分で失効します。Ctrl+Cはローカルの待機を終了し、未交換リクエストは期限で失効します。
|
||||||
|
他人から送られたURL・コードでは承認しないでください。通信断で交換結果が不明な場合は自動再送せず、
|
||||||
|
サーバのセッション管理で不要なセッションを確認・失効してからログインし直します。
|
||||||
|
|
||||||
|
`CLI OIDC login is unavailable on this server` は開始APIが利用できない場合の表示です。
|
||||||
|
configureの接続先URLを確認し、サーバーも対応版へ更新してください。
|
||||||
|
`OIDC login is not enabled for this domain` の場合は、対象DomainのOIDC設定を確認してください。
|
||||||
|
`--no-browser` はブラウザーの自動起動だけを抑止し、承認待ちとセッション取得は通常どおり行います。
|
||||||
|
|
||||||
## 設定する
|
## 設定する
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
pages configure # 設定を表示(トークンは表示しない)
|
pages configure # 設定を表示(トークンは表示しない)
|
||||||
pages configure --lang ja # 現在の既定接続の編集言語
|
pages configure --lang auto # 表示対象の言語版を編集
|
||||||
pages configure list # 接続先一覧、★が既定
|
pages configure list # 接続先一覧、★が既定
|
||||||
pages configure set --profile work --origin https://work.example.test --username anya --lang en
|
pages configure set --profile work --origin https://work.example.test --username anya --lang en
|
||||||
pages configure use work # 以後はworkを指定不要
|
pages configure use work # 以後はworkを指定不要
|
||||||
@@ -46,11 +76,13 @@ pages status
|
|||||||
pages edit /guide
|
pages edit /guide
|
||||||
```
|
```
|
||||||
|
|
||||||
既定プロファイル名は `default`、既定言語は `und`(言語未指定)です。OSや表示言語から
|
既定プロファイル名は `default`、新しいプロファイルの既定言語は `auto` です。
|
||||||
書き込み先の言語を推測しません。最初に名前付きプロファイルを作った場合はそれを既定とします。
|
`auto` はサーバーが通常表示するRevisionの言語を取得し、その言語の最新版を編集します。
|
||||||
言語は接続先ごとに保持し、編集時はその言語の既存Revisionを使用します。
|
OSの言語からは推測しません。最初に名前付きプロファイルを作った場合はそれを既定とします。
|
||||||
|
言語は接続先ごとに保持します。既存設定の `und`(言語未指定)や `ja` は自動変更しません。
|
||||||
|
以前のCLIで設定済みの場合は `pages configure --lang auto` で切り替えられます。
|
||||||
|
|
||||||
一度だけ変更したいときは `pages --profile personal --lang ja edit /guide` も使えます。
|
一度だけ変更したいときは `pages edit /guide --lang auto`、`pages --profile personal --lang ja edit /guide` も使えます。
|
||||||
プロファイル自体は先にconfigureで登録します。引数の上書きは設定ファイルを書き換えません。
|
プロファイル自体は先にconfigureで登録します。引数の上書きは設定ファイルを書き換えません。
|
||||||
|
|
||||||
設定ファイルは `~/.config/pages-cli/config.json`(`XDG_CONFIG_HOME`対応)。
|
設定ファイルは `~/.config/pages-cli/config.json`(`XDG_CONFIG_HOME`対応)。
|
||||||
@@ -63,7 +95,7 @@ pages edit /guide
|
|||||||
"default": {
|
"default": {
|
||||||
"origin": "https://pages.example.test",
|
"origin": "https://pages.example.test",
|
||||||
"username": "anya",
|
"username": "anya",
|
||||||
"lang": "und"
|
"lang": "auto"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,7 +126,22 @@ pages edit /guide
|
|||||||
`pages --help`、`pages configure --help`、`pages edit --help` で引数を確認できます。
|
`pages --help`、`pages configure --help`、`pages edit --help` で引数を確認できます。
|
||||||
Tab補完、上下キーのプロセス内履歴に対応。複雑な引用位置の補完、Ctrl+Pのfuzzy UIは後続です。
|
Tab補完、上下キーのプロセス内履歴に対応。複雑な引用位置の補完、Ctrl+Pのfuzzy UIは後続です。
|
||||||
|
|
||||||
初期版は既存Page・既存言語の更新まで。新規作成、OIDC引き継ぎ、バイナリ更新は未実装です。
|
### 言語を指定して編集する
|
||||||
|
|
||||||
|
`auto` 言語選択と未作成言語版の編集は、v0.4.0以降のCLIで利用できます。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages edit /guide --lang auto # 表示される言語の最新版を編集
|
||||||
|
pages edit /guide --lang ja # 日本語版。未作成なら既存内容から開始
|
||||||
|
pages edit /guide --lang en # 英語版。未作成なら既存内容から開始
|
||||||
|
```
|
||||||
|
|
||||||
|
編集開始時に対象言語を表示します。指定言語のRevisionがない場合は、表示中の版の内容を
|
||||||
|
下書きとして `$EDITOR` を開き、変更を保存するとその言語の最初のRevisionを作ります。
|
||||||
|
自動翻訳ではありません。元の言語版は変更せず、編集せずに閉じた場合は何も作成しません。
|
||||||
|
同じ言語版が先に作成された場合も、競合として保存を止めます。
|
||||||
|
|
||||||
|
対応範囲は既存Pageの更新と新規言語版の作成です。新規Path/Page作成、バイナリ更新は未実装です。
|
||||||
競合や通信断で自動上書きせず、ローカル原稿を保持します。HTTPS必須(開発用loopbackのみHTTP可)。
|
競合や通信断で自動上書きせず、ローカル原稿を保持します。HTTPS必須(開発用loopbackのみHTTP可)。
|
||||||
詳しいURI・保存・安全性の契約は[設計書](../docs/design/ja/remote-cli.md)を参照してください。
|
詳しいURI・保存・安全性の契約は[設計書](../docs/design/ja/remote-cli.md)を参照してください。
|
||||||
|
|
||||||
@@ -106,3 +153,8 @@ go test ./internal/server -run TestRemoteCLIHTTPIntegration -count=1
|
|||||||
```
|
```
|
||||||
|
|
||||||
偽サーバと一時DBのみを使用します。本番資格情報や外部カレンダーは不要です。
|
偽サーバと一時DBのみを使用します。本番資格情報や外部カレンダーは不要です。
|
||||||
|
## タスクと連絡先
|
||||||
|
|
||||||
|
`pages task --help` で作成・計画・開始/終了・レポートを操作できる。
|
||||||
|
`pages contacts --help` で個人アドレス帳の検索・vCard入出力を行える。
|
||||||
|
[neomutt設定と操作例](../docs/operations/neomutt-tasks.md)を参照。
|
||||||
+313
-29
@@ -1,6 +1,10 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""pages — navigate and edit PagesWiki from your terminal (pages-cli)."""
|
"""pages — navigate and edit PagesWiki from your terminal (pages-cli)."""
|
||||||
import argparse
|
import argparse
|
||||||
|
import email.policy
|
||||||
|
import email.parser
|
||||||
|
import uuid
|
||||||
|
import base64
|
||||||
import contextlib
|
import contextlib
|
||||||
import difflib
|
import difflib
|
||||||
import fcntl
|
import fcntl
|
||||||
@@ -11,6 +15,7 @@ import os
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import posixpath
|
import posixpath
|
||||||
import re
|
import re
|
||||||
|
import secrets
|
||||||
import shlex
|
import shlex
|
||||||
import stat
|
import stat
|
||||||
import subprocess
|
import subprocess
|
||||||
@@ -69,20 +74,22 @@ class NoRedirect(http.HTTPRedirectHandler):
|
|||||||
|
|
||||||
|
|
||||||
class Client:
|
class Client:
|
||||||
def __init__(self, base, token='', lang='und'):
|
def __init__(self, base, token='', lang='auto'):
|
||||||
self.base, self.token, self.lang = origin(base), token, lang
|
self.base, self.token, self.lang = origin(base), token, lang
|
||||||
self.opener = http.build_opener(NoRedirect())
|
self.opener = http.build_opener(NoRedirect())
|
||||||
|
|
||||||
def request(self, route, method='GET', data=None, form=None, limit=4 << 20):
|
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('//'):
|
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/0.1'}
|
headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/0.1'}
|
||||||
|
if etag is not None:
|
||||||
|
headers['If-Match'] = etag
|
||||||
if self.token:
|
if self.token:
|
||||||
headers['Authorization'] = 'Bearer ' + self.token
|
headers['Authorization'] = 'Bearer ' + self.token
|
||||||
body = None
|
body = None
|
||||||
if data is not None:
|
if data is not None:
|
||||||
body = json.dumps(data, ensure_ascii=False).encode()
|
body = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode()
|
||||||
headers['Content-Type'] = 'application/json'
|
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'
|
headers['Content-Type'] = 'application/x-www-form-urlencoded'
|
||||||
@@ -105,7 +112,8 @@ class Client:
|
|||||||
if not isinstance(payload, dict):
|
if not isinstance(payload, dict):
|
||||||
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.'}
|
||||||
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
|
||||||
@@ -130,34 +138,113 @@ class Client:
|
|||||||
raise
|
raise
|
||||||
result = self.json('/_/auth/totp', method='POST', form={
|
result = self.json('/_/auth/totp', method='POST', form={
|
||||||
'challenge_token': e.payload['challenge_token'], 'code': otp('TOTP: ')})
|
'challenge_token': e.payload['challenge_token'], 'code': otp('TOTP: ')})
|
||||||
|
return self.accept_session(result)
|
||||||
|
|
||||||
|
def accept_session(self, result):
|
||||||
token = result.get('access_token')
|
token = result.get('access_token')
|
||||||
if not isinstance(token, str) or not re.fullmatch(r'[A-Za-z0-9_.~-]{16,1024}', token) or result.get('token_type') != 'Bearer':
|
if not isinstance(token, str) or not re.fullmatch(r'[A-Za-z0-9_.~-]{16,1024}', token) or result.get('token_type') != 'Bearer':
|
||||||
raise Failure('Server did not issue a Bearer session.')
|
raise Failure('Server did not issue a Bearer session.')
|
||||||
|
duration = result.get('expires_in')
|
||||||
|
if not isinstance(duration, int) or isinstance(duration, bool) or not 1 <= duration <= 30*24*60*60:
|
||||||
|
raise Failure('Invalid session lifetime.')
|
||||||
self.token = token
|
self.token = token
|
||||||
return time.time() + int(result['expires_in'])
|
return time.time() + duration
|
||||||
|
|
||||||
|
def login_oidc(self, no_browser=False, expected_username='', *, sleep=time.sleep, clock=time.monotonic):
|
||||||
|
verifier = secrets.token_urlsafe(32)
|
||||||
|
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
|
||||||
|
try:
|
||||||
|
started = self.json('/_/auth/cli/start', method='POST', form={
|
||||||
|
'code_challenge': challenge, 'code_challenge_method': 'S256'})
|
||||||
|
except Failure as e:
|
||||||
|
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
|
||||||
|
if e.status == 403 and e.payload.get('error') == 'oidc_disabled':
|
||||||
|
raise Failure('OIDC login is not enabled for this domain. Ask your administrator to enable it.', e.status) from None
|
||||||
|
raise
|
||||||
|
device, route, code = (started.get(k) for k in ('device_code', 'verification_uri', 'user_code'))
|
||||||
|
if (not isinstance(device, str) or not re.fullmatch(r'[A-Za-z0-9_-]{43}', device)
|
||||||
|
or not isinstance(route, str) or not re.fullmatch(r'/_/auth/cli/verify\?request=[A-Za-z0-9_-]{43}', route)
|
||||||
|
or not isinstance(code, str) or not re.fullmatch(r'[A-F0-9]{4}-[A-F0-9]{4}', code)):
|
||||||
|
raise Failure('Invalid browser login response; no browser was opened.')
|
||||||
|
lifetime, interval = int(started.get('expires_in', 0)), int(started.get('interval', 0))
|
||||||
|
if not 1 <= lifetime <= 300 or not 5 <= interval <= 30:
|
||||||
|
raise Failure('Invalid browser login lifetime or polling interval.')
|
||||||
|
deadline = clock() + lifetime
|
||||||
|
print('Open this URL and approve only the request you started:')
|
||||||
|
print(self.base + route)
|
||||||
|
print('Confirmation code:', code)
|
||||||
|
print('Waiting for approval (up to 5 minutes). Ctrl+C cancels locally.', flush=True)
|
||||||
|
if not no_browser:
|
||||||
|
try: webbrowser.open(self.base + route, new=2)
|
||||||
|
except (webbrowser.Error, OSError): pass # URL remains usable on another device.
|
||||||
|
while clock() + interval < deadline:
|
||||||
|
sleep(interval)
|
||||||
|
try:
|
||||||
|
result = self.json('/_/auth/cli/token', method='POST', form={
|
||||||
|
'device_code': device, 'code_verifier': verifier})
|
||||||
|
except Failure as e:
|
||||||
|
reason = e.payload.get('error')
|
||||||
|
if e.status == 400 and reason == 'authorization_pending': continue
|
||||||
|
if e.status == 400 and reason == 'slow_down':
|
||||||
|
interval = min(30, interval + 5); continue
|
||||||
|
if reason in ('access_denied', 'expired_token', 'oidc_disabled'):
|
||||||
|
raise Failure('Browser login denied, expired or disabled. Restart pages login --oidc.') from None
|
||||||
|
raise # Never retry an ambiguous token exchange or a network failure.
|
||||||
|
name = result.get('username')
|
||||||
|
expires = self.accept_session(result)
|
||||||
|
if (not isinstance(name, str) or not name or any(unicodedata.category(c).startswith('C') for c in name)
|
||||||
|
or (expected_username and name.lower() != expected_username.lower())):
|
||||||
|
try: self.json('/_/auth/logout', method='POST')
|
||||||
|
except Failure: pass
|
||||||
|
self.token = ''
|
||||||
|
raise Failure('The browser account differs from the configured username; attempted to revoke the new session.')
|
||||||
|
return expires, name
|
||||||
|
raise Failure('Browser login expired. Restart pages login --oidc.')
|
||||||
|
|
||||||
def listing(self, path, prefix=''):
|
def listing(self, path, prefix=''):
|
||||||
return self.json('/_/api/v1/path-picker?' + url.urlencode({'path': path, 'mode': 'children', 'prefix': prefix}))
|
return self.json('/_/api/v1/path-picker?' + url.urlencode({'path': path, 'mode': 'children', 'prefix': prefix}))
|
||||||
|
|
||||||
def raw(self, addr, method='GET'):
|
def raw(self, addr, method='GET'):
|
||||||
raw, headers = self.request('/v/raw/' + url.quote(addr, safe='/:') + '?' + url.urlencode({'lang': self.lang}), method=method, limit=64 << 20)
|
query = '' if self.lang == 'auto' else '?' + url.urlencode({'lang': self.lang})
|
||||||
|
raw, headers = self.request('/v/raw/' + url.quote(addr, safe='/:') + query, method=method, limit=64 << 20)
|
||||||
digest = headers.get('X-PagesWiki-Document-SHA256')
|
digest = headers.get('X-PagesWiki-Document-SHA256')
|
||||||
if method == 'GET' and (not digest or hashlib.sha256(raw).hexdigest() != digest):
|
if method == 'GET' and (not digest or hashlib.sha256(raw).hexdigest() != digest):
|
||||||
raise Failure('Document SHA-256 mismatch.')
|
raise Failure('Document SHA-256 mismatch.')
|
||||||
return raw, headers
|
return raw, headers
|
||||||
|
|
||||||
def snapshot(self, addr):
|
def snapshot(self, addr, lang=None):
|
||||||
if addr.startswith('rev:'):
|
if addr.startswith('rev:'):
|
||||||
raise Failure('Revision addresses are immutable; edit a path: or uuid: address.')
|
raise Failure('Revision addresses are immutable; edit a path: or uuid: address.')
|
||||||
_, headers = self.raw(addr, 'HEAD')
|
_, headers = self.raw(addr, 'HEAD')
|
||||||
ident = headers.get('X-PagesWiki-Object-UUID')
|
ident = headers.get('X-PagesWiki-Object-UUID')
|
||||||
if not ident:
|
if not ident:
|
||||||
raise Failure('Missing Object UUID metadata.')
|
raise Failure('Missing Object UUID metadata.')
|
||||||
state = self.json('/_/api/v1/editor/state?' + url.urlencode({'uuid': ident, 'lang': self.lang}))
|
target = self.lang if lang is None else lang
|
||||||
|
visible = headers.get('X-PagesWiki-Revision-UUID', '')
|
||||||
|
def load(language, **extra):
|
||||||
|
return self.json('/_/api/v1/editor/state?' + url.urlencode({'uuid': ident, 'lang': language, **extra}))
|
||||||
|
if target == 'auto':
|
||||||
|
# Resolve the viewer's language, then obtain that exact language's
|
||||||
|
# current head. Never save against a head from a different language.
|
||||||
|
target = load('und', revision=visible, metadata=1)['lang'] if visible else 'und'
|
||||||
|
state = load(target)
|
||||||
if not state.get('editable') or not state.get('principal_uuid'):
|
if not state.get('editable') or not state.get('principal_uuid'):
|
||||||
raise Failure('Not an authenticated editable text document; use the browser.')
|
raise Failure('Not an authenticated editable text document; use the browser.')
|
||||||
if not state.get('head_revision_uuid') or not state.get('content_type'):
|
if not state.get('head_revision_uuid'):
|
||||||
raise Failure('No saved revision in this exact language; creation/translation is not supported yet.')
|
# An empty CAS base asserts absence of this language. Seed from the
|
||||||
|
# visible source without changing it or pretending it is the base.
|
||||||
|
if visible:
|
||||||
|
source = load(state['lang'], revision=visible)
|
||||||
|
if not source.get('editable') or source.get('principal_uuid') != state['principal_uuid']:
|
||||||
|
raise Failure('Cannot fork this document or the editing account changed.')
|
||||||
|
for key in ('body', 'markdown', 'content_type', 'filename'):
|
||||||
|
state[key] = source[key]
|
||||||
|
state['source_revision_uuid'] = visible
|
||||||
|
state['source_language'] = source['lang']
|
||||||
|
state['new_language'] = True
|
||||||
|
if not state.get('content_type'):
|
||||||
|
raise Failure('Missing document format; use the browser.')
|
||||||
state['object_uuid'] = ident
|
state['object_uuid'] = ident
|
||||||
return state
|
return state
|
||||||
|
|
||||||
@@ -169,7 +256,7 @@ class Client:
|
|||||||
raise Failure('Markdown authoring is supported only for HTML Wiki documents.')
|
raise Failure('Markdown authoring is supported only for HTML Wiki documents.')
|
||||||
text = self.json('/_/api/v1/render/markdown', method='POST', data={
|
text = self.json('/_/api/v1/render/markdown', method='POST', data={
|
||||||
'markdown': text, 'authoring': True, 'projection': False})['html']
|
'markdown': text, 'authoring': True, 'projection': False})['html']
|
||||||
if text == state['body']:
|
if state['head_revision_uuid'] and text == state['body']:
|
||||||
return {'status': 'unchanged', 'revision_uuid': state['head_revision_uuid']}
|
return {'status': 'unchanged', 'revision_uuid': state['head_revision_uuid']}
|
||||||
return self.json('/_/api/v1/revisions/save', method='POST', data={
|
return self.json('/_/api/v1/revisions/save', method='POST', data={
|
||||||
'object_uuid': state['object_uuid'], 'body': text, 'lang': state['lang'],
|
'object_uuid': state['object_uuid'], 'body': text, 'lang': state['lang'],
|
||||||
@@ -234,7 +321,7 @@ def profile_name(name):
|
|||||||
|
|
||||||
def language(value):
|
def language(value):
|
||||||
if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*', value):
|
if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*', value):
|
||||||
raise Failure('Use a language tag such as und, ja or en-US; the server validates the exact tag.')
|
raise Failure('Use auto or a language tag such as und, ja or en-US; the server validates the exact tag.')
|
||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
@@ -265,7 +352,7 @@ class Configuration(PrivateJSON):
|
|||||||
raise Failure('Profiles accept only origin, username and lang; never store a password here.')
|
raise Failure('Profiles accept only origin, username and lang; never store a password here.')
|
||||||
if not isinstance(spec.get('username', ''), str) or any(unicodedata.category(c).startswith('C') for c in spec.get('username', '')):
|
if not isinstance(spec.get('username', ''), str) or any(unicodedata.category(c).startswith('C') for c in spec.get('username', '')):
|
||||||
raise Failure('Invalid configured username.')
|
raise Failure('Invalid configured username.')
|
||||||
normalized[name] = dict(spec, origin=origin(spec.get('origin', '')), lang=language(spec.get('lang', 'und')))
|
normalized[name] = dict(spec, origin=origin(spec.get('origin', '')), lang=language(spec.get('lang', 'auto')))
|
||||||
if profiles and default not in profiles: raise Failure('Default profile does not exist.')
|
if profiles and default not in profiles: raise Failure('Default profile does not exist.')
|
||||||
return {'version': 1, 'default_profile': default, 'profiles': normalized}
|
return {'version': 1, 'default_profile': default, 'profiles': normalized}
|
||||||
|
|
||||||
@@ -287,7 +374,7 @@ def configure(words, root=None):
|
|||||||
print(json.dumps(data, ensure_ascii=False, indent=2)); return
|
print(json.dumps(data, ensure_ascii=False, indent=2)); return
|
||||||
if args.action == 'list':
|
if args.action == 'list':
|
||||||
for name, spec in data['profiles'].items():
|
for name, spec in data['profiles'].items():
|
||||||
print(safe_text(('★ ' if name == data['default_profile'] else ' ') + name + ' ' + spec['origin'] + ' ' + spec.get('username', '') + ' [' + spec.get('lang', 'und') + ']'))
|
print(safe_text(('★ ' if name == data['default_profile'] else ' ') + name + ' ' + spec['origin'] + ' ' + spec.get('username', '') + ' [' + spec.get('lang', 'auto') + ']'))
|
||||||
if not data['profiles']: print('No connections. Use: pages configure --origin https://wiki.example --username NAME')
|
if not data['profiles']: print('No connections. Use: pages configure --origin https://wiki.example --username NAME')
|
||||||
return
|
return
|
||||||
if args.action == 'use':
|
if args.action == 'use':
|
||||||
@@ -296,7 +383,7 @@ def configure(words, root=None):
|
|||||||
data['default_profile'] = name
|
data['default_profile'] = name
|
||||||
else:
|
else:
|
||||||
name = profile_name(args.profile or data['default_profile'])
|
name = profile_name(args.profile or data['default_profile'])
|
||||||
spec = dict(data['profiles'].get(name, {'lang': 'und'}))
|
spec = dict(data['profiles'].get(name, {'lang': 'auto'}))
|
||||||
if args.origin is not None: spec['origin'] = origin(args.origin)
|
if args.origin is not None: spec['origin'] = origin(args.origin)
|
||||||
if args.username is not None: spec['username'] = args.username.strip()
|
if args.username is not None: spec['username'] = args.username.strip()
|
||||||
if args.lang is not None: spec['lang'] = language(args.lang)
|
if args.lang is not None: spec['lang'] = language(args.lang)
|
||||||
@@ -304,7 +391,7 @@ def configure(words, root=None):
|
|||||||
# Configuration and session locks use this order. Never retarget an
|
# Configuration and session locks use this order. Never retarget an
|
||||||
# active credential to a different Domain or account.
|
# active credential to a different Domain or account.
|
||||||
with Profile(name, root).locked() as session:
|
with Profile(name, root).locked() as session:
|
||||||
if session.data.get('token') and (spec['origin'] != session.data.get('origin') or spec.get('username', '') != session.data.get('username')):
|
if session.data.get('token') and (spec['origin'] != session.data.get('origin') or spec.get('username', '') != session.data.get('configured_username', session.data.get('username'))):
|
||||||
raise Failure('Log out this profile before changing its origin or username.')
|
raise Failure('Log out this profile before changing its origin or username.')
|
||||||
data['profiles'][name] = spec
|
data['profiles'][name] = spec
|
||||||
if len(data['profiles']) == 1: data['default_profile'] = name
|
if len(data['profiles']) == 1: data['default_profile'] = name
|
||||||
@@ -318,6 +405,9 @@ def configure(words, root=None):
|
|||||||
|
|
||||||
def editor(client, addr, mode):
|
def editor(client, addr, mode):
|
||||||
state = client.snapshot(addr)
|
state = client.snapshot(addr)
|
||||||
|
print('Editing language:', safe_text(state['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'))
|
markdown = mode == 'markdown' or (mode == 'auto' and state['content_type'].startswith('text/html'))
|
||||||
initial = state['markdown'] if markdown else state['body']
|
initial = state['markdown'] if markdown else state['body']
|
||||||
directory = Path(tempfile.mkdtemp(prefix='pageswiki-edit-'))
|
directory = Path(tempfile.mkdtemp(prefix='pageswiki-edit-'))
|
||||||
@@ -337,7 +427,7 @@ def editor(client, addr, mode):
|
|||||||
result = client.save(state, text, markdown)
|
result = client.save(state, text, markdown)
|
||||||
except Failure as error:
|
except Failure as error:
|
||||||
if error.status == 409:
|
if error.status == 409:
|
||||||
latest = client.snapshot('uuid:' + state['object_uuid'])
|
latest = client.snapshot('uuid:' + state['object_uuid'], lang=state['lang'])
|
||||||
remote = latest['markdown'] if markdown else latest['body']
|
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'))))
|
print(safe_text(''.join(difflib.unified_diff(remote.splitlines(True), text.splitlines(True), fromfile='remote', tofile='local'))))
|
||||||
raise
|
raise
|
||||||
@@ -351,11 +441,188 @@ def editor(client, addr, mode):
|
|||||||
metadata = directory / 'recovery.json'
|
metadata = directory / 'recovery.json'
|
||||||
metadata.touch(mode=0o600)
|
metadata.touch(mode=0o600)
|
||||||
metadata.write_text(json.dumps({'origin': client.base, 'address': 'uuid:' + state['object_uuid'],
|
metadata.write_text(json.dumps({'origin': client.base, 'address': 'uuid:' + state['object_uuid'],
|
||||||
'base_revision_uuid': state['head_revision_uuid'], 'lang': state['lang'], 'format': 'markdown' if markdown else 'raw'}))
|
'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)
|
||||||
|
|
||||||
|
|
||||||
|
TASK_API = '/_/api/v1/extension/organizer.tasks/'
|
||||||
|
|
||||||
|
|
||||||
|
def task_uuid(value):
|
||||||
|
try:
|
||||||
|
parsed = str(uuid.UUID(value))
|
||||||
|
if parsed != value: raise ValueError()
|
||||||
|
return parsed
|
||||||
|
except (ValueError, AttributeError):
|
||||||
|
raise Failure('Use a canonical task or project UUID.') from None
|
||||||
|
|
||||||
|
|
||||||
|
def task_project(client, value):
|
||||||
|
if value == '': return ''
|
||||||
|
try: return task_uuid(value)
|
||||||
|
except Failure: pass
|
||||||
|
data = client.json(TASK_API+'items?'+url.urlencode({'kind':'project','view':'all','q':value,'limit':100}))
|
||||||
|
matches = [item['uuid'] for item in data.get('items',[]) if item['title'] == value]
|
||||||
|
if len(matches) != 1 or data.get('next'):
|
||||||
|
raise Failure('Project name is missing or ambiguous; use its UUID.')
|
||||||
|
return matches[0]
|
||||||
|
|
||||||
|
|
||||||
|
def task_mail(raw, include_body=False, 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))
|
||||||
|
if include_body:
|
||||||
|
part = message.get_body(preferencelist=('plain',))
|
||||||
|
if part:
|
||||||
|
content = part.get_content()
|
||||||
|
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()
|
||||||
|
|
||||||
|
|
||||||
|
def tasks(client, profile, words):
|
||||||
|
parser = argparse.ArgumentParser(prog='pages task',description='Private task capture, planning and work-time records. Stops do not complete a task.')
|
||||||
|
sub = parser.add_subparsers(dest='action',required=True)
|
||||||
|
p=sub.add_parser('list');p.add_argument('--view',default='all',choices=['all','today','inbox','backlog','someday','review','done','archived','carryover']);p.add_argument('--project');p.add_argument('--q',default='');p.add_argument('--before',default='')
|
||||||
|
sub.add_parser('projects')
|
||||||
|
p=sub.add_parser('project-add');p.add_argument('title');p.add_argument('--notes',default='')
|
||||||
|
p=sub.add_parser('show');p.add_argument('uuid',type=task_uuid)
|
||||||
|
for name in ('add','from-mail','update'):
|
||||||
|
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')
|
||||||
|
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))
|
||||||
|
if name=='add':p.add_argument('--request-id',type=task_uuid)
|
||||||
|
for name in ('done','reopen','archive','start'):
|
||||||
|
p=sub.add_parser(name);p.add_argument('uuid',type=task_uuid)
|
||||||
|
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')
|
||||||
|
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))
|
||||||
|
def capture(payload):
|
||||||
|
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.')
|
||||||
|
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
|
||||||
|
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','')}
|
||||||
|
if getattr(a,'project',None) is not None:query['project']=task_project(client,a.project)
|
||||||
|
data=client.json(TASK_API+'items?'+url.urlencode(query))
|
||||||
|
if a.json:emit(data)
|
||||||
|
else:
|
||||||
|
for item in data.get('items',[]):print(safe_text('\t'.join([item['uuid'],item['status'],item.get('due_on',''),item['title']])))
|
||||||
|
if data.get('next'):print('Next page: --before '+data['next'],file=sys.stderr)
|
||||||
|
return
|
||||||
|
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')]:
|
||||||
|
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
|
||||||
|
emit(client.json(TASK_API+'preferences',method='PUT',data=p) if changed else data);return
|
||||||
|
if action=='retry':
|
||||||
|
payload=profile.data.get('task_outbox',{}).get(a.request_id)
|
||||||
|
if not payload:raise Failure('No retained task capture with this request ID.')
|
||||||
|
emit(capture(payload));return
|
||||||
|
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)
|
||||||
|
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)))
|
||||||
|
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
|
||||||
|
emit(capture(payload));return
|
||||||
|
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
|
||||||
|
if action in ('update','done','reopen','archive'):
|
||||||
|
item=client.json(TASK_API+'items/'+a.uuid)['item']
|
||||||
|
if item['kind']!='task':raise Failure('This operation requires a task.')
|
||||||
|
for attr,key in [('title','title'),('notes','notes'),('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,None)
|
||||||
|
if value is not None:item[key]=task_project(client,value) if attr=='project' else value
|
||||||
|
if action=='done':item['status']='done'
|
||||||
|
elif action=='reopen':item['status']='todo'
|
||||||
|
elif action=='archive':item['archived']=True
|
||||||
|
emit(client.json(TASK_API+'items/'+a.uuid,method='PUT',data=item,etag='"'+str(item['version'])+'"'));return
|
||||||
|
if action=='start':
|
||||||
|
emit(client.json(TASK_API+'work',method='POST',data={'action':'start','uuid':str(uuid.uuid4()),'task_uuid':a.uuid,'version':0}));return
|
||||||
|
if action in ('stop','status'):
|
||||||
|
data=client.json(TASK_API+'work')
|
||||||
|
if action=='stop':
|
||||||
|
if not data['item']:raise Failure('No running work timer in this Domain.')
|
||||||
|
data=client.json(TASK_API+'work',method='POST',data={**data['item'],'action':'stop'})
|
||||||
|
emit(data);return
|
||||||
|
if action=='report':
|
||||||
|
query={k:v for k,v in [('from',a.start),('to',a.end)] if v}
|
||||||
|
data=client.json(TASK_API+'report?'+url.urlencode(query))
|
||||||
|
if a.json:emit(data);return
|
||||||
|
print('Timezone:',safe_text(data['timezone']))
|
||||||
|
print('Date\tCompleted\tPoints\tWork minutes\tPomodoro minutes')
|
||||||
|
for day in data['days']:
|
||||||
|
if day['completed'] or day['work_ms'] or day['focus_ms']:print('%s\t%d\t%d\t%.1f\t%.1f'%(day['date'],day['completed'],day['points'],day['work_ms']/60000,day['focus_ms']/60000))
|
||||||
|
print('\nTask UUID\tWork minutes\tTitle')
|
||||||
|
for task in data['tasks']:print(safe_text('%s\t%.1f\t%s'%(task['uuid'],task['work_ms']/60000,task['title'])))
|
||||||
|
if data['partial']:print('Partial report: narrow the date range.',file=sys.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
def contacts(client, words):
|
||||||
|
parser=argparse.ArgumentParser(prog='pages contacts',description='Private address book; never links contacts to login accounts.')
|
||||||
|
sub=parser.add_subparsers(dest='action',required=True)
|
||||||
|
p=sub.add_parser('list');p.add_argument('--query',default='');p.add_argument('--after',default='')
|
||||||
|
p=sub.add_parser('query');p.add_argument('query');p.add_argument('--neomutt',action='store_true')
|
||||||
|
p=sub.add_parser('show');p.add_argument('uuid',type=task_uuid)
|
||||||
|
p=sub.add_parser('export');p.add_argument('uuid',type=task_uuid)
|
||||||
|
p=sub.add_parser('import');p.add_argument('file',type=Path)
|
||||||
|
a=parser.parse_args(words);api='/_/api/v1/extension/organizer.contacts/'
|
||||||
|
if a.action=='import':
|
||||||
|
with a.file.open('rb') as f:raw=f.read(65537)
|
||||||
|
if len(raw)>65536:raise Failure('One UTF-8 vCard per import, up to 64 KiB. Use the Web importer for multiple cards.')
|
||||||
|
data=client.json(api+'import',method='POST',data=raw,content_type='text/vcard')
|
||||||
|
elif a.action=='export':
|
||||||
|
data=client.json(api+'items/'+a.uuid);sys.stdout.write(data['item']['vcard']);return
|
||||||
|
elif a.action=='show':data=client.json(api+'items/'+a.uuid)
|
||||||
|
else:
|
||||||
|
try: data=client.json(api+'items?'+url.urlencode({'q':a.query,'after':getattr(a,'after','')}))
|
||||||
|
except Failure:
|
||||||
|
if a.action=='query' and a.neomutt: print('PagesWiki address query failed; check login and permissions.')
|
||||||
|
raise
|
||||||
|
if a.action=='query' and a.neomutt:
|
||||||
|
if not any(item['emails'] for item in data.get('items',[])):
|
||||||
|
print('No matching email addresses.')
|
||||||
|
raise Failure('No matching email addresses.')
|
||||||
|
print('PagesWiki contacts'+(' (first 100; narrow query)' if data.get('next') else ''))
|
||||||
|
for item in data.get('items',[]):
|
||||||
|
clean=lambda v:' '.join(safe_text(v).split())
|
||||||
|
for address in item['emails']:
|
||||||
|
# Do not let imported metadata forge query result columns.
|
||||||
|
if '\t' not in address and '\n' not in address and '\r' not in address:
|
||||||
|
print(clean(address)+'\t'+clean(item['name'])+'\t'+clean(item['organization']))
|
||||||
|
return
|
||||||
|
print(json.dumps(data,ensure_ascii=False,indent=2))
|
||||||
|
|
||||||
|
|
||||||
def execute(client, profile, words):
|
def execute(client, profile, words):
|
||||||
|
if words and words[0] in ('contact','contacts'):
|
||||||
|
return contacts(client,words[1:])
|
||||||
|
if words and words[0] in ('task','tasks'):
|
||||||
|
return tasks(client,profile,words[1:])
|
||||||
parser = argparse.ArgumentParser(prog='pages')
|
parser = argparse.ArgumentParser(prog='pages')
|
||||||
sub = parser.add_subparsers(dest='command', required=True)
|
sub = parser.add_subparsers(dest='command', required=True)
|
||||||
for command in ('ls', 'cd', 'cat', 'view', 'edit', 'open'):
|
for command in ('ls', 'cd', 'cat', 'view', 'edit', 'open'):
|
||||||
@@ -363,6 +630,7 @@ 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 = 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')
|
||||||
@@ -402,9 +670,12 @@ def execute(client, profile, words):
|
|||||||
route = addr[5:] if addr.startswith('path:') else '/o/' + addr if addr.startswith('uuid:') else '/r/view/' + addr[4:]
|
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)
|
webbrowser.open(client.base + url.quote(route, safe='/:'), new=2)
|
||||||
elif cmd == 'edit':
|
elif cmd == 'edit':
|
||||||
editor(client, addr, args.format)
|
editing = Client(client.base, client.token, language(args.lang)) if args.lang else client
|
||||||
|
editor(editing, addr, args.format)
|
||||||
elif cmd == 'put':
|
elif cmd == 'put':
|
||||||
state = client.snapshot(addr)
|
state = client.snapshot(addr)
|
||||||
|
if not state['head_revision_uuid']:
|
||||||
|
raise Failure('No revision in the target language; use edit --lang to create a language revision.')
|
||||||
if state['head_revision_uuid'] != args.base: raise Failure('Conflict: supplied base is not the current language head.', 409)
|
if state['head_revision_uuid'] != args.base: raise Failure('Conflict: supplied base is not the current language head.', 409)
|
||||||
text = Path(args.local).read_text(encoding='utf-8')
|
text = Path(args.local).read_text(encoding='utf-8')
|
||||||
print('Revision:', safe_text(client.save(state, text, args.format == 'markdown')['revision_uuid']))
|
print('Revision:', safe_text(client.save(state, text, args.format == 'markdown')['revision_uuid']))
|
||||||
@@ -467,9 +738,9 @@ 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. 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, search, open, task, contacts. Use pages COMMAND --help.')
|
||||||
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='Override the configured exact language for this invocation')
|
parser.add_argument('--lang', help='auto or an exact language tag for this invocation')
|
||||||
parser.add_argument('command', nargs='?', default='shell')
|
parser.add_argument('command', nargs='?', default='shell')
|
||||||
parser.add_argument('args', nargs=argparse.REMAINDER)
|
parser.add_argument('args', nargs=argparse.REMAINDER)
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
@@ -480,7 +751,10 @@ def main(argv=None):
|
|||||||
parser.print_help(); return
|
parser.print_help(); return
|
||||||
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.parse_args(args.args)
|
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_args = login.parse_args(args.args)
|
||||||
|
if login_args.no_browser and not login_args.oidc: login.error('--no-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:
|
||||||
@@ -490,17 +764,27 @@ def main(argv=None):
|
|||||||
spec = settings['profiles'].get(name)
|
spec = settings['profiles'].get(name)
|
||||||
if spec is None:
|
if spec is None:
|
||||||
raise Failure('No connection configured. Run: pages configure --origin https://HOST --username NAME')
|
raise Failure('No connection configured. Run: pages configure --origin https://HOST --username NAME')
|
||||||
lang = language(args.lang or spec.get('lang', 'und'))
|
lang = language(args.lang or spec.get('lang', 'auto'))
|
||||||
# Hold the profile lock before releasing the configuration lock.
|
# Hold the profile lock before releasing the configuration lock.
|
||||||
profile = stack.enter_context(Profile(name).locked())
|
profile = stack.enter_context(Profile(name).locked())
|
||||||
if args.command == 'login':
|
if args.command == 'login':
|
||||||
if not spec.get('username'): raise Failure('Set your account with pages configure --username NAME.')
|
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'): raise Failure('Log out this profile before replacing its session.')
|
||||||
client = Client(spec['origin'], lang=lang)
|
client = Client(spec['origin'], lang=lang)
|
||||||
expires = client.login(spec['username'], getpass.getpass('Password: '))
|
if login_args.oidc:
|
||||||
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == spec['username']
|
expires, username = client.login_oidc(login_args.no_browser, spec.get('username', ''))
|
||||||
|
else:
|
||||||
|
username = spec['username']
|
||||||
|
expires = client.login(username, getpass.getpass('Password: '))
|
||||||
|
same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == username
|
||||||
|
pending = profile.data.get('task_outbox', {})
|
||||||
|
if pending and not same_identity:
|
||||||
|
try: client.json('/_/auth/logout', method='POST')
|
||||||
|
except Failure: pass
|
||||||
|
raise Failure('Pending task drafts belong to the previous account. Use a separate profile; the drafts were retained.')
|
||||||
cwd = profile.data.get('cwd', '/') if same_identity else '/'
|
cwd = profile.data.get('cwd', '/') if same_identity else '/'
|
||||||
profile.data = {'origin': client.base, 'username': spec['username'], 'token': client.token, 'expires': expires, 'cwd': cwd}
|
profile.data = {'origin': client.base, 'username': username, 'configured_username': spec.get('username', ''), 'token': client.token, 'expires': expires, 'cwd': cwd}
|
||||||
|
if pending: profile.data['task_outbox'] = pending
|
||||||
try:
|
try:
|
||||||
profile.save()
|
profile.save()
|
||||||
except OSError:
|
except OSError:
|
||||||
@@ -512,7 +796,7 @@ def main(argv=None):
|
|||||||
raise Failure('Could not save credentials; attempted to revoke the new session.') from None
|
raise Failure('Could not save credentials; attempted to revoke the new session.') from None
|
||||||
print('Logged in. Session saved privately.'); return
|
print('Logged in. Session saved privately.'); return
|
||||||
if not profile.data.get('token'): raise Failure('Log in first.')
|
if not profile.data.get('token'): raise Failure('Log in first.')
|
||||||
if args.command != 'logout' and (profile.data.get('origin') != spec['origin'] or profile.data.get('username') != spec.get('username')):
|
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.')
|
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.')
|
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)
|
||||||
|
|||||||
+204
-6
@@ -1,4 +1,5 @@
|
|||||||
import contextlib
|
import contextlib
|
||||||
|
import base64
|
||||||
from email.message import Message
|
from email.message import Message
|
||||||
import hashlib
|
import hashlib
|
||||||
import io
|
import io
|
||||||
@@ -38,6 +39,94 @@ def reply(h, status, body, mime='application/json'):
|
|||||||
|
|
||||||
|
|
||||||
class RemoteTests(unittest.TestCase):
|
class RemoteTests(unittest.TestCase):
|
||||||
|
def test_oidc_polling_pkce_and_no_secret_output(self):
|
||||||
|
now = [0]
|
||||||
|
waits, calls = [], []
|
||||||
|
started = {'device_code': 'D'*43, 'verification_uri': '/_/auth/cli/verify?request='+'R'*43,
|
||||||
|
'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5}
|
||||||
|
client = Client('https://wiki.example')
|
||||||
|
def sleep(seconds): waits.append(seconds); now[0] += seconds
|
||||||
|
def request(route, **kwargs):
|
||||||
|
calls.append((route, kwargs))
|
||||||
|
if route.endswith('/start'): return started
|
||||||
|
polls = len(calls)-1
|
||||||
|
if polls == 1: raise Failure('pending',400,{'error':'authorization_pending'})
|
||||||
|
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'}
|
||||||
|
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])
|
||||||
|
self.assertEqual(name,'anya'); self.assertGreater(expires,time.time())
|
||||||
|
self.assertEqual(waits,[5,5,10]); browser.assert_not_called()
|
||||||
|
proof = calls[1][1]['form']['code_verifier']
|
||||||
|
expected=base64.urlsafe_b64encode(hashlib.sha256(proof.encode()).digest()).decode().rstrip('=')
|
||||||
|
self.assertEqual(calls[0][1]['form']['code_challenge'],expected)
|
||||||
|
self.assertNotIn(proof,out.getvalue()); self.assertNotIn(started['device_code'],out.getvalue()); self.assertNotIn(client.token,out.getvalue())
|
||||||
|
self.assertIn('ABCD-1234',out.getvalue())
|
||||||
|
|
||||||
|
def test_oidc_unavailable_server_explained_without_retry(self):
|
||||||
|
for status in (404, 405, 501):
|
||||||
|
with self.subTest(status=status):
|
||||||
|
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 self.assertRaisesRegex(Failure, 'CLI OIDC login is unavailable') as caught:
|
||||||
|
client.login_oidc(True)
|
||||||
|
self.assertEqual(caught.exception.status, status)
|
||||||
|
api.assert_called_once()
|
||||||
|
browser.assert_not_called()
|
||||||
|
self.assertEqual(out.getvalue(), '')
|
||||||
|
self.assertEqual(client.token, '')
|
||||||
|
|
||||||
|
def test_oidc_disabled_and_other_start_errors(self):
|
||||||
|
client = Client('https://wiki.example')
|
||||||
|
with patch.object(client, 'json', side_effect=Failure('Access denied.', 403, {'error': 'oidc_disabled'})):
|
||||||
|
with self.assertRaisesRegex(Failure, 'not enabled for this domain'):
|
||||||
|
client.login_oidc(True)
|
||||||
|
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 self.assertRaises(Failure) as caught:
|
||||||
|
client.login_oidc(True)
|
||||||
|
self.assertIs(caught.exception, error)
|
||||||
|
api.assert_called_once()
|
||||||
|
|
||||||
|
def test_oidc_rejects_external_url_and_wrong_account(self):
|
||||||
|
client=Client('https://wiki.example')
|
||||||
|
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 self.assertRaises(Failure): client.login_oidc()
|
||||||
|
browser.assert_not_called()
|
||||||
|
started['verification_uri']='/_/auth/cli/verify?request='+'R'*43
|
||||||
|
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 self.assertRaises(Failure): client.login_oidc(True,'anya',sleep=lambda _:None,clock=lambda:0)
|
||||||
|
self.assertEqual(api.call_args.args[0],'/_/auth/logout')
|
||||||
|
self.assertEqual(client.token,'')
|
||||||
|
|
||||||
|
def test_oidc_cancellation_denial_and_ambiguous_exchange(self):
|
||||||
|
started={'device_code':'D'*43,'verification_uri':'/_/auth/cli/verify?request='+'R'*43,'user_code':'ABCD-1234','expires_in':300,'interval':5}
|
||||||
|
for error in [Failure('denied',403,{'error':'access_denied'}),Failure('expired',400,{'error':'expired_token'}),Failure('network failure')]:
|
||||||
|
client=Client('https://wiki.example')
|
||||||
|
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)
|
||||||
|
self.assertEqual(api.call_count,2)
|
||||||
|
client=Client('https://wiki.example')
|
||||||
|
with patch.object(client,'json',return_value=started) as api,contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
def interrupt(_): raise KeyboardInterrupt()
|
||||||
|
with self.assertRaises(KeyboardInterrupt): client.login_oidc(True,sleep=interrupt,clock=lambda:0)
|
||||||
|
self.assertEqual(api.call_count,1)
|
||||||
|
|
||||||
|
def test_oidc_main_without_configured_username(self):
|
||||||
|
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}):
|
||||||
|
self.configure(None,'--origin','https://wiki.example')
|
||||||
|
def login(client,*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()):
|
||||||
|
m['main'](['login','--oidc','--no-browser'])
|
||||||
|
m['main'](['status'])
|
||||||
|
self.configure(None,'--lang','ja')
|
||||||
|
with Profile('default').locked() as profile:
|
||||||
|
self.assertEqual(profile.data['username'],'anya')
|
||||||
|
self.assertEqual(profile.data['configured_username'],'')
|
||||||
|
with self.assertRaises(Failure): self.configure(None,'--username','other')
|
||||||
|
|
||||||
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)
|
||||||
@@ -50,11 +139,14 @@ class RemoteTests(unittest.TestCase):
|
|||||||
self.configure(root,'use','work')
|
self.configure(root,'use','work')
|
||||||
settings=json.loads(self.configure(root,'show'))
|
settings=json.loads(self.configure(root,'show'))
|
||||||
self.assertEqual(settings['default_profile'],'work')
|
self.assertEqual(settings['default_profile'],'work')
|
||||||
self.assertEqual(settings['profiles']['default']['lang'],'und')
|
self.assertEqual(settings['profiles']['default']['lang'],'auto')
|
||||||
self.assertEqual(settings['profiles']['work']['lang'],'ja')
|
self.assertEqual(settings['profiles']['work']['lang'],'ja')
|
||||||
self.configure(root,'--lang','en-US')
|
self.configure(root,'--lang','en-US')
|
||||||
settings=json.loads(self.configure(root,'show'))
|
settings=json.loads(self.configure(root,'show'))
|
||||||
self.assertEqual(settings['profiles']['work']['lang'],'en-US')
|
self.assertEqual(settings['profiles']['work']['lang'],'en-US')
|
||||||
|
self.configure(root,'--lang','und')
|
||||||
|
settings=json.loads(self.configure(root,'show'))
|
||||||
|
self.assertEqual(settings['profiles']['work']['lang'],'und')
|
||||||
with m['Configuration'](root).locked() as cfg:
|
with m['Configuration'](root).locked() as cfg:
|
||||||
self.assertEqual(stat.S_IMODE(cfg.path.stat().st_mode),0o600)
|
self.assertEqual(stat.S_IMODE(cfg.path.stat().st_mode),0o600)
|
||||||
with self.assertRaises(Failure): self.configure(root,'use','missing')
|
with self.assertRaises(Failure): self.configure(root,'use','missing')
|
||||||
@@ -185,6 +277,62 @@ class RemoteTests(unittest.TestCase):
|
|||||||
self.assertEqual(stat.S_IMODE(Path(file).stat().st_mode),0o600)
|
self.assertEqual(stat.S_IMODE(Path(file).stat().st_mode),0o600)
|
||||||
with self.assertRaises(FileExistsError): m['execute'](client,profile,['get','/path',file])
|
with self.assertRaises(FileExistsError): m['execute'](client,profile,['get','/path',file])
|
||||||
|
|
||||||
|
def test_auto_snapshot_pins_visible_language_and_head(self):
|
||||||
|
client=Client('https://example.test','token')
|
||||||
|
state={'lang':'ja','head_revision_uuid':'current-ja','content_type':'text/plain','filename':'x.txt','body':'new','markdown':'new','editable':True,'principal_uuid':'owner'}
|
||||||
|
headers={'X-PagesWiki-Object-UUID':'object','X-PagesWiki-Revision-UUID':'visible-ja'}
|
||||||
|
with patch.object(client,'raw',return_value=(b'',headers)),patch.object(client,'json',side_effect=[{'lang':'ja'},state]) as api:
|
||||||
|
result=client.snapshot('path:/x')
|
||||||
|
self.assertEqual(result['lang'],'ja')
|
||||||
|
self.assertEqual(result['head_revision_uuid'],'current-ja')
|
||||||
|
self.assertIn('revision=visible-ja',api.call_args_list[0].args[0])
|
||||||
|
self.assertIn('lang=ja',api.call_args_list[1].args[0])
|
||||||
|
self.assertNotIn('revision=',api.call_args_list[1].args[0])
|
||||||
|
|
||||||
|
def test_fork_uses_empty_base_and_preserves_source(self):
|
||||||
|
client=Client('https://example.test','token','en')
|
||||||
|
target={'lang':'en','head_revision_uuid':'','content_type':'text/html','filename':'','body':'','markdown':'','editable':True,'principal_uuid':'owner'}
|
||||||
|
source=dict(target,lang='ja',body='<h1>Source</h1>',markdown='# Source',revision_uuid='ja-base')
|
||||||
|
headers={'X-PagesWiki-Object-UUID':'object','X-PagesWiki-Revision-UUID':'ja-base'}
|
||||||
|
with patch.object(client,'raw',return_value=(b'',headers)),patch.object(client,'json',side_effect=[target,source]):
|
||||||
|
result=client.snapshot('path:/x')
|
||||||
|
self.assertEqual(result['lang'],'en'); self.assertEqual(result['head_revision_uuid'],'')
|
||||||
|
self.assertEqual(result['source_language'],'ja'); self.assertEqual(result['body'],source['body'])
|
||||||
|
with patch.object(client,'json',return_value={'revision_uuid':'en-new'}) as api:
|
||||||
|
client.save(result,result['body'])
|
||||||
|
self.assertEqual(api.call_args.kwargs['data']['base_revision_uuid'],'')
|
||||||
|
self.assertEqual(api.call_args.kwargs['data']['lang'],'en')
|
||||||
|
for changes in ({'editable':False},{'principal_uuid':'someone-else'}):
|
||||||
|
with patch.object(client,'raw',return_value=(b'',headers)),patch.object(client,'json',side_effect=[dict(target,head_revision_uuid=''),dict(source,**changes)]):
|
||||||
|
with self.assertRaises(Failure): client.snapshot('path:/x')
|
||||||
|
|
||||||
|
def test_editor_unchanged_fork_does_not_save(self):
|
||||||
|
client=Client('https://example.test','token','ja')
|
||||||
|
state={'object_uuid':'object','head_revision_uuid':'','principal_uuid':'owner','lang':'ja',
|
||||||
|
'content_type':'text/plain','filename':'x.txt','body':'source','markdown':'source','new_language':True,'source_language':'und'}
|
||||||
|
with patch.object(client,'snapshot',return_value=state),patch.object(client,'save') as save,patch('subprocess.run') as command,contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
command.return_value.returncode=0
|
||||||
|
m['editor'](client,'path:/x','auto')
|
||||||
|
save.assert_not_called()
|
||||||
|
self.assertFalse(Path(command.call_args.args[0][-1]).exists())
|
||||||
|
|
||||||
|
def test_edit_language_override_does_not_change_profile(self):
|
||||||
|
client=Client('https://example.test','token','und')
|
||||||
|
with tempfile.TemporaryDirectory() as root:
|
||||||
|
profile=Profile('test',root)
|
||||||
|
profile.data={'cwd':'/notes'}
|
||||||
|
def editor_override(editing,addr,mode):
|
||||||
|
self.assertEqual((editing.base,editing.token,editing.lang),(client.base,client.token,'auto'))
|
||||||
|
self.assertEqual((addr,mode),('path:/notes/page','auto'))
|
||||||
|
with patch.dict(m['execute'].__globals__,{'editor':editor_override}):
|
||||||
|
m['execute'](client,profile,['edit','page','--lang','auto'])
|
||||||
|
self.assertEqual(client.lang,'und')
|
||||||
|
self.assertEqual(profile.data,{'cwd':'/notes'})
|
||||||
|
with patch.object(client,'snapshot',return_value={'head_revision_uuid':''}),patch.object(client,'save') as save:
|
||||||
|
with self.assertRaisesRegex(Failure,'use edit --lang'):
|
||||||
|
m['execute'](client,profile,['put','unused','page','--base',''])
|
||||||
|
save.assert_not_called()
|
||||||
|
|
||||||
def test_editor_conflict_retains_private_recovery(self):
|
def test_editor_conflict_retains_private_recovery(self):
|
||||||
state={'object_uuid':'object','head_revision_uuid':'base','principal_uuid':'person','lang':'und',
|
state={'object_uuid':'object','head_revision_uuid':'base','principal_uuid':'person','lang':'und',
|
||||||
'content_type':'text/plain','filename':'x.txt','body':'old','markdown':'old'}
|
'content_type':'text/plain','filename':'x.txt','body':'old','markdown':'old'}
|
||||||
@@ -195,8 +343,9 @@ 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), 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)), 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')
|
||||||
self.assertEqual((directory/'document.txt').read_text(),'my edit')
|
self.assertEqual((directory/'document.txt').read_text(),'my edit')
|
||||||
recovery=(directory/'recovery.json').read_text()
|
recovery=(directory/'recovery.json').read_text()
|
||||||
self.assertNotIn('secret-token',recovery)
|
self.assertNotIn('secret-token',recovery)
|
||||||
@@ -204,6 +353,36 @@ class RemoteTests(unittest.TestCase):
|
|||||||
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 oidc_integration():
|
||||||
|
fixture=json.load(sys.stdin)
|
||||||
|
original=Client.json
|
||||||
|
grant={}
|
||||||
|
def capture(client,route,**kwargs):
|
||||||
|
result=original(client,route,**kwargs)
|
||||||
|
if route=='/_/auth/cli/start': grant.update(result)
|
||||||
|
return result
|
||||||
|
def browser(target,**kwargs):
|
||||||
|
ident=m['url'].parse_qs(m['url'].urlsplit(target).query)['request'][0]
|
||||||
|
original(Client(fixture['origin']),'/__test/cli-approve',method='POST',form={'request':ident,'code':grant['user_code']})
|
||||||
|
return True
|
||||||
|
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']])
|
||||||
|
with patch.object(Client,'json',capture),patch.object(m['webbrowser'],'open',browser): m['main'](['login','--oidc'])
|
||||||
|
with Profile('default',root).locked() as session:
|
||||||
|
token=session.data['token']; assert session.data['username']=='admin'
|
||||||
|
m['main'](['ls']); m['main'](['status'])
|
||||||
|
client=Client(fixture['origin'],token)
|
||||||
|
state=client.snapshot('path:/editor-fixture')
|
||||||
|
client.save(state,'# OIDC edit\n\n{{children}}\n',True)
|
||||||
|
assert '{{children}}' in client.snapshot('path:/editor-fixture')['markdown']
|
||||||
|
m['main'](['logout'])
|
||||||
|
assert token not in output.getvalue()
|
||||||
|
try: client.snapshot('path:/editor-fixture')
|
||||||
|
except Failure as e: assert e.status in (401,403,303)
|
||||||
|
else: raise AssertionError('revoked CLI session accepted')
|
||||||
|
print('OIDC CLI configure/login/list/authoring/logout integration passed')
|
||||||
|
|
||||||
|
|
||||||
def integration():
|
def integration():
|
||||||
fixture=json.load(sys.stdin)
|
fixture=json.load(sys.stdin)
|
||||||
# Exercise the public entry point with persisted defaults, not only Client.
|
# Exercise the public entry point with persisted defaults, not only Client.
|
||||||
@@ -223,15 +402,33 @@ def integration():
|
|||||||
m['main'](['logout'])
|
m['main'](['logout'])
|
||||||
assert session_token not in output.getvalue()
|
assert session_token not in output.getvalue()
|
||||||
with Profile('default',root).locked() as session: assert 'token' not in session.data
|
with Profile('default',root).locked() as session: assert 'token' not in session.data
|
||||||
client=Client(fixture['origin'])
|
client=Client(fixture['origin'], lang='und')
|
||||||
client.login('admin','a long test password')
|
client.login('admin','a long test password')
|
||||||
addr='path:/editor-fixture'
|
addr='path:/editor-fixture'
|
||||||
state=client.snapshot(addr)
|
state=client.snapshot(addr)
|
||||||
assert state['lang']=='und' and state['principal_uuid']
|
assert state['lang']=='und' and state['principal_uuid']
|
||||||
missing=Client(fixture['origin'], client.token, 'ja')
|
missing=Client(fixture['origin'], client.token, 'ja')
|
||||||
try: missing.snapshot(addr)
|
fork=missing.snapshot(addr)
|
||||||
except Failure: pass
|
assert fork['lang']=='ja' and fork['head_revision_uuid']=='' and fork['new_language']
|
||||||
else: raise AssertionError('missing language silently fell back')
|
assert fork['body']==state['body'] and fork['source_language']=='und'
|
||||||
|
missing.save(fork,'# Japanese draft\n\n{{children}}\n',True)
|
||||||
|
assert missing.snapshot(addr)['lang']=='ja'
|
||||||
|
assert client.snapshot(addr)['head_revision_uuid']==state['head_revision_uuid']
|
||||||
|
try: missing.save(fork,'competing first revision')
|
||||||
|
except Failure as e: assert e.status==409
|
||||||
|
else: raise AssertionError('concurrent language creation overwrote the head')
|
||||||
|
auto=Client(fixture['origin'],client.token)
|
||||||
|
auto_state=auto.snapshot('path:/ja-only')
|
||||||
|
assert auto_state['lang']=='ja' and auto_state['head_revision_uuid']
|
||||||
|
def edit_japanese(args, **kwargs):
|
||||||
|
path=Path(args[-1]); path.write_text(path.read_text()+'\nJapanese edit\n')
|
||||||
|
class Result: returncode=0
|
||||||
|
return Result()
|
||||||
|
with patch('subprocess.run',side_effect=edit_japanese),contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
m['editor'](auto,'path:/ja-only','auto')
|
||||||
|
assert 'Japanese edit' in auto.snapshot('path:/ja-only')['body']
|
||||||
|
pending=Client(fixture['origin'],client.token,'und').snapshot('path:/ja-only')
|
||||||
|
assert pending['head_revision_uuid']==''
|
||||||
assert client.listing('/')['entries']
|
assert client.listing('/')['entries']
|
||||||
assert client.save(state,'# Remote\n\n{{children}}\n',True)['revision_uuid'] != state['head_revision_uuid']
|
assert client.save(state,'# Remote\n\n{{children}}\n',True)['revision_uuid'] != state['head_revision_uuid']
|
||||||
latest=client.snapshot(addr)
|
latest=client.snapshot(addr)
|
||||||
@@ -261,4 +458,5 @@ def integration():
|
|||||||
|
|
||||||
if __name__=='__main__':
|
if __name__=='__main__':
|
||||||
if sys.argv[1:] == ['--integration']: integration()
|
if sys.argv[1:] == ['--integration']: integration()
|
||||||
|
elif sys.argv[1:] == ['--oidc-integration']: oidc_integration()
|
||||||
else: unittest.main()
|
else: unittest.main()
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import runpy
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
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)
|
||||||
|
self.assertEqual(title,'Test');self.assertNotIn('PRIVATE BODY',notes);self.assertIn('Message-ID:',notes)
|
||||||
|
self.assertIn('PRIVATE BODY',m['task_mail'](raw,True)[1])
|
||||||
|
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_capture_retains_request_until_explicit_retry(self):
|
||||||
|
calls=[]
|
||||||
|
def send(route,**kwargs):
|
||||||
|
calls.append(kwargs['data'].copy())
|
||||||
|
if len(calls)==1:raise m['Failure']('offline')
|
||||||
|
return {'item':{'uuid':kwargs['data']['request_id']}}
|
||||||
|
profile=SimpleNamespace(data={},save=lambda:None)
|
||||||
|
client=SimpleNamespace(json=send)
|
||||||
|
with contextlib.redirect_stdout(io.StringIO()),contextlib.redirect_stderr(io.StringIO()):
|
||||||
|
with self.assertRaises(m['Failure']):m['tasks'](client,profile,['add','Offline task'])
|
||||||
|
ident=next(iter(profile.data['task_outbox']))
|
||||||
|
m['tasks'](client,profile,['retry',ident])
|
||||||
|
self.assertEqual(calls[0],calls[1]);self.assertEqual(profile.data['task_outbox'],{})
|
||||||
|
|
||||||
|
def test_neomutt_query_columns_are_not_forgeable(self):
|
||||||
|
client=SimpleNamespace(json=lambda *a,**kw:{'items':[{'name':'A\tB\nC','emails':['a@example.invalid'],'organization':'Org\nInjected'}]})
|
||||||
|
out=io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(out):m['contacts'](client,['query','A','--neomutt'])
|
||||||
|
rows=out.getvalue().splitlines();self.assertEqual(len(rows),2);self.assertEqual(len(rows[1].split('\t')),3)
|
||||||
|
|
||||||
|
def test_command_help_without_credentials(self):
|
||||||
|
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)
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""Called by the Go synthetic HTTP fixture; no production credentials."""
|
||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import runpy
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def run():
|
||||||
|
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||||
|
fixture=json.load(sys.stdin)
|
||||||
|
client=m['Client'](fixture['origin'],fixture['token'])
|
||||||
|
profile=m['Profile']('test',fixture['root'])
|
||||||
|
def task(*words):
|
||||||
|
output=io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(output):m['tasks'](client,profile,list(words))
|
||||||
|
return json.loads(output.getvalue())
|
||||||
|
with profile.locked():
|
||||||
|
prefs=task('preferences','--due-days','2','--estimate','60','--complexity','3')
|
||||||
|
assert prefs['preferences']['due_days']==2
|
||||||
|
item=task('add','CLI task')['item'];ident=item['uuid']
|
||||||
|
assert item['estimate_minutes']==60 and item['due_on']
|
||||||
|
task('start',ident);assert task('status')['item']['task_uuid']==ident
|
||||||
|
task('stop');assert task('status')['item'] is None
|
||||||
|
item=task('update',ident,'--title','Updated CLI task')['item'];assert item['title']=='Updated CLI task'
|
||||||
|
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'])
|
||||||
|
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()
|
||||||
|
with contextlib.redirect_stdout(output):m['contacts'](client,['import',str(path)])
|
||||||
|
contact=json.loads(output.getvalue())['item'];output=io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(output):m['contacts'](client,['query','CLI','--neomutt'])
|
||||||
|
assert 'cli@example.invalid\tCLI Person\t' in output.getvalue()
|
||||||
|
output=io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(output):m['contacts'](client,['export',contact['uuid']])
|
||||||
|
assert 'UID:urn:test:cli' in output.getvalue()
|
||||||
|
|
||||||
|
if __name__=='__main__':run()
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
#contacts-app{max-width:1200px;margin:auto;padding:1rem}#contacts-controls{display:flex;gap:.5rem;flex-wrap:wrap}.contacts-layout{display:grid;grid-template-columns:minmax(200px,1fr) minmax(300px,2fr);gap:1rem;margin-top:1rem}#contacts-list>button{display:block;width:100%;text-align:start;padding:.5rem;border:0;border-bottom:1px solid var(--border-color,#7775);background:transparent;color:inherit}#contact-editor form{display:grid;gap:.6rem}#contact-editor label{display:grid;grid-template-columns:8rem 1fr;gap:.5rem}#contact-editor input,#contact-editor textarea{width:100%;min-width:0}#contact-editor textarea{min-height:5rem}#contact-editor details pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:20rem;overflow:auto}@media(max-width:650px){.contacts-layout{grid-template-columns:1fr}#contacts-list{max-height:30vh;overflow:auto}#contact-editor label{grid-template-columns:1fr}}
|
||||||
|
#contacts-app,#contacts-app *{box-sizing:border-box}.contacts-layout>*{min-width:0}#contacts-list button{overflow-wrap:anywhere}
|
||||||
|
.contact-history-row{display:flex;align-items:center;gap:.4rem;padding:.3rem 0;flex-wrap:wrap}.contact-history-row span{flex:1;min-width:12rem}#contacts-controls>a{align-self:center}
|
||||||
|
@media(max-width:650px){#contacts-app input,#contacts-app select,#contacts-app button{min-height:44px;font-size:16px}}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
#tasks-dav-dialog{box-sizing:border-box;width:min(800px,96vw);max-height:92dvh;overflow:auto;color:var(--fg);background:var(--bg)!important;border:1px solid var(--border,#8885);border-radius:1rem;padding:1rem;box-shadow:0 1rem 4rem #0005}
|
#tasks-dav-dialog{box-sizing:border-box;width:min(800px,96vw);max-height:92dvh;overflow:auto;color:var(--fg);background:var(--bg)!important;border:1px solid var(--border,#8885);border-radius:1rem;padding:1rem;box-shadow:0 1rem 4rem #0005}
|
||||||
#tasks-dav-dialog::backdrop{background:#0007;backdrop-filter:blur(3px)}
|
#tasks-dav-dialog::backdrop{background:#0007;backdrop-filter:blur(3px)}
|
||||||
|
#tasks-dav-dialog [hidden]{display:none!important}
|
||||||
#tasks-dav-dialog header{display:flex;align-items:center;justify-content:space-between;gap:1rem}#tasks-dav-dialog h2{font-size:1.2rem;margin:.25rem 0}#tasks-dav-dialog p{font-size:.9rem}#tasks-dav-dialog form{display:flex;flex-wrap:wrap;gap:.4rem;margin:1rem 0}#tasks-dav-dialog form>input{flex:1;min-width:10rem}#tasks-dav-dialog>input,#tasks-dav-dialog section input{width:100%}#tasks-dav-dialog input,#tasks-dav-dialog select,#tasks-dav-dialog button{box-sizing:border-box;font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--border,#8885);border-radius:.4rem;padding:.5rem;min-width:0}#tasks-dav-dialog button{cursor:pointer}#tasks-dav-dialog :focus-visible{outline:2px solid var(--accent);outline-offset:2px}#tasks-dav-dialog section{padding:.7rem;border:1px solid var(--accent);border-radius:.5rem}#tasks-dav-dialog section label{display:block;font-size:.85rem;margin:.3rem 0}#tasks-dav-dialog .task-dav-table{overflow:auto}#tasks-dav-dialog table{width:100%;border-collapse:collapse;font-size:.85rem}#tasks-dav-dialog th,#tasks-dav-dialog td{padding:.35rem;text-align:left;border-bottom:1px solid var(--border,#8885)}#tasks-dav-dialog td:first-child{overflow-wrap:anywhere}#tasks-dav-dialog [role=status]{color:var(--danger,#d55)}
|
#tasks-dav-dialog header{display:flex;align-items:center;justify-content:space-between;gap:1rem}#tasks-dav-dialog h2{font-size:1.2rem;margin:.25rem 0}#tasks-dav-dialog p{font-size:.9rem}#tasks-dav-dialog form{display:flex;flex-wrap:wrap;gap:.4rem;margin:1rem 0}#tasks-dav-dialog form>input{flex:1;min-width:10rem}#tasks-dav-dialog>input,#tasks-dav-dialog section input{width:100%}#tasks-dav-dialog input,#tasks-dav-dialog select,#tasks-dav-dialog button{box-sizing:border-box;font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--border,#8885);border-radius:.4rem;padding:.5rem;min-width:0}#tasks-dav-dialog button{cursor:pointer}#tasks-dav-dialog :focus-visible{outline:2px solid var(--accent);outline-offset:2px}#tasks-dav-dialog section{padding:.7rem;border:1px solid var(--accent);border-radius:.5rem}#tasks-dav-dialog section label{display:block;font-size:.85rem;margin:.3rem 0}#tasks-dav-dialog .task-dav-table{overflow:auto}#tasks-dav-dialog table{width:100%;border-collapse:collapse;font-size:.85rem}#tasks-dav-dialog th,#tasks-dav-dialog td{padding:.35rem;text-align:left;border-bottom:1px solid var(--border,#8885)}#tasks-dav-dialog td:first-child{overflow-wrap:anywhere}#tasks-dav-dialog [role=status]{color:var(--danger,#d55)}
|
||||||
#tasks-dav-dialog .dav-compat-toggle{display:flex;align-items:center;gap:.5rem;width:100%;font-size:.9rem}#tasks-dav-dialog .dav-compat-toggle input{width:1.2rem;height:1.2rem;min-height:0;flex:none;accent-color:var(--accent)}#tasks-dav-dialog .dav-compat-help{width:100%;margin:.15rem 0;font-size:.85rem;color:var(--muted,var(--fg))}
|
#tasks-dav-dialog .dav-compat-toggle{display:flex;align-items:center;gap:.5rem;width:100%;font-size:.9rem}#tasks-dav-dialog .dav-compat-toggle input{width:1.2rem;height:1.2rem;min-height:0;flex:none;accent-color:var(--accent)}#tasks-dav-dialog .dav-compat-help{width:100%;margin:.15rem 0;font-size:.85rem;color:var(--muted,var(--fg))}
|
||||||
@media(max-width:760px){#tasks-dav-dialog{width:100%;max-width:none;height:100dvh;max-height:100dvh;margin:0;border-radius:0}#tasks-dav-dialog input,#tasks-dav-dialog select,#tasks-dav-dialog button{min-height:44px;font-size:16px}#tasks-dav-dialog .dav-compat-toggle{min-height:44px}}
|
@media(max-width:760px){#tasks-dav-dialog{width:100%;max-width:none;height:100dvh;max-height:100dvh;margin:0;border-radius:0}#tasks-dav-dialog input,#tasks-dav-dialog select,#tasks-dav-dialog button{min-height:44px;font-size:16px}#tasks-dav-dialog .dav-compat-toggle{min-height:44px}}
|
||||||
+2
-2
@@ -56,7 +56,7 @@ body.periodical-top:has(> .home-wallpaper) .periodical-shell dialog header { bac
|
|||||||
body:has(> .home-wallpaper) :is(.notification-dialog,.calendar-upcoming-dialog,.city-map-dialog,dialog.home-bookmark-manager,.auth-menu-popover),
|
body:has(> .home-wallpaper) :is(.notification-dialog,.calendar-upcoming-dialog,.city-map-dialog,dialog.home-bookmark-manager,.auth-menu-popover),
|
||||||
body.periodical-top:has(> .home-wallpaper) .periodical-shell dialog { background:color-mix(in srgb,var(--bg) 92%,transparent); }
|
body.periodical-top:has(> .home-wallpaper) .periodical-shell dialog { background:color-mix(in srgb,var(--bg) 92%,transparent); }
|
||||||
}
|
}
|
||||||
.home-shortcuts { display:flex; width:max-content; max-width:100%; margin:1.35rem auto 0; gap:.25rem; }
|
.home-shortcuts { display:flex; flex-wrap:wrap; justify-content:center; width:max-content; max-width:100%; margin:1.35rem auto 0; gap:.25rem; }
|
||||||
.home-shortcuts a { display:grid; place-items:center; width:2.45rem; height:2.45rem; border-radius:50%; color:var(--fg); }
|
.home-shortcuts a { display:grid; place-items:center; width:2.45rem; height:2.45rem; border-radius:50%; color:var(--fg); }
|
||||||
.home-shortcuts a:hover,.home-shortcuts a:focus-visible { background:color-mix(in srgb,var(--accent) 17%,transparent); color:var(--accent); outline:2px solid color-mix(in srgb,var(--accent) 42%,transparent); outline-offset:-2px; }
|
.home-shortcuts a:hover,.home-shortcuts a:focus-visible { background:color-mix(in srgb,var(--accent) 17%,transparent); color:var(--accent); outline:2px solid color-mix(in srgb,var(--accent) 42%,transparent); outline-offset:-2px; }
|
||||||
.home-shortcuts svg { width:1.35rem; height:1.35rem; fill:none; stroke:currentColor; stroke-width:1.65; stroke-linecap:round; stroke-linejoin:round; }
|
.home-shortcuts svg { width:1.35rem; height:1.35rem; fill:none; stroke:currentColor; stroke-width:1.65; stroke-linecap:round; stroke-linejoin:round; }
|
||||||
@@ -84,7 +84,7 @@ body.periodical-top:has(> .home-wallpaper) .periodical-shell dialog header { bac
|
|||||||
.home-bookmark { display: flex; gap: .8rem; align-items: center; padding: 1.25rem; border: 1px solid var(--border); border-radius: .65rem; overflow-wrap: anywhere; }
|
.home-bookmark { display: flex; gap: .8rem; align-items: center; padding: 1.25rem; border: 1px solid var(--border); border-radius: .65rem; overflow-wrap: anywhere; }
|
||||||
.home-bookmark:hover { background: var(--button-hover-bg); border-color: var(--accent); }
|
.home-bookmark:hover { background: var(--button-hover-bg); border-color: var(--accent); }
|
||||||
.home-empty { color: var(--muted); }
|
.home-empty { color: var(--muted); }
|
||||||
.home-layout-search .home-main { min-height: 100vh; min-height: 100svh; display: grid; align-items: center; padding-block: 5rem; }
|
.home-layout-search .home-main { min-height: 100vh; min-height: 100svh; display: grid; grid-template-columns:minmax(0,1fr); align-items: center; padding-block: 5rem; }
|
||||||
.home-layout-directory .home-main { padding-top: max(7rem, 18vh); }
|
.home-layout-directory .home-main { padding-top: max(7rem, 18vh); }
|
||||||
@media (max-width: 600px) { .home-layout-directory .home-main { padding-top: 7rem; } .home-search ~ .home-bookmarks { margin-top: 2.5rem; } }
|
@media (max-width: 600px) { .home-layout-directory .home-main { padding-top: 7rem; } .home-search ~ .home-bookmarks { margin-top: 2.5rem; } }
|
||||||
.home-paged { height:100vh; height:100dvh; overflow:hidden; overscroll-behavior:none; }
|
.home-paged { height:100vh; height:100dvh; overflow:hidden; overscroll-behavior:none; }
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
.organizer-nav{display:flex;flex-shrink:0;gap:.25rem;align-items:center;flex-wrap:wrap;padding:.45rem 1rem;border-bottom:1px solid var(--border,#8885);color:var(--fg);background:var(--bg)}
|
||||||
|
.organizer-nav a{display:flex;align-items:center;gap:.4rem;padding:.4rem .7rem;border-radius:.4rem;color:var(--link,var(--accent));text-decoration:none;white-space:nowrap;font-size:.9rem}
|
||||||
|
.organizer-nav a[aria-current=page]{background:color-mix(in srgb,var(--accent,#478ddd) 15%,transparent);box-shadow:inset 0 -2px var(--accent,#478ddd);color:var(--fg)}
|
||||||
|
.organizer-nav a:hover{background:var(--row-hover,var(--border-soft,#8882))}
|
||||||
|
.organizer-nav-icons{display:flex;align-items:center;gap:.15rem}.organizer-launch{display:inline-flex;align-items:center;justify-content:center;color:var(--fg);width:2.1rem;height:2.1rem;box-sizing:border-box;padding:.35rem;border-radius:50%}
|
||||||
|
.organizer-launch svg{width:100%;height:100%;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}.organizer-launch:hover{color:var(--accent)}
|
||||||
|
.organizer-page .topbar{flex-wrap:wrap;gap:.2rem}.organizer-settings-content{min-width:0;padding:.75rem 1rem}.organizer-settings-content #task-productivity{margin:0;padding:0}.organizer-calendar-options{display:grid;gap:.4rem}.organizer-calendar-options label{display:flex;align-items:center;gap:.5rem;min-height:2rem}
|
||||||
|
#organizer-dashboard{max-width:1800px;margin:auto;padding:1rem;box-sizing:border-box;color:var(--fg)}
|
||||||
|
.dashboard-toolbar{display:flex;justify-content:space-between;align-items:center;gap:.75rem;flex-wrap:wrap}.dashboard-toolbar h1{margin:0;font-size:1.5rem}#dashboard-controls{display:flex;gap:.35rem;align-items:center;flex-wrap:wrap}
|
||||||
|
#organizer-dashboard button,#organizer-dashboard select,#organizer-calendar-defaults button{font:inherit;color:var(--fg);background:var(--input-bg,var(--bg));border:1px solid var(--border,#8885);border-radius:.35rem;padding:.3rem .5rem;cursor:pointer}
|
||||||
|
#organizer-dashboard button:disabled{opacity:.5;cursor:default}#organizer-dashboard a{color:var(--link,var(--accent))}#dashboard-status{min-height:1.3em;margin:.4rem 0;font-size:.85rem}
|
||||||
|
#dashboard-grid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));grid-auto-rows:72px;gap:12px;align-items:stretch}
|
||||||
|
.dashboard-widget{grid-column:span var(--widget-width,4);grid-row:span var(--widget-height,3);min-width:0;min-height:0;display:flex;flex-direction:column;position:relative;border:1px solid var(--border,#8885);border-radius:.65rem;background:var(--panel-bg,var(--bg));overflow:hidden;box-shadow:0 2px 8px #0001}
|
||||||
|
.widget-header{display:flex;align-items:center;gap:.5rem;min-width:0;padding:.55rem .7rem;border-bottom:1px solid var(--border,#8883)}.widget-header h2{font-size:.95rem;margin:0;flex:1;min-width:0}.widget-header>a{text-decoration:none;padding:.1rem .3rem}
|
||||||
|
.widget-body{flex:1;min-height:0;overflow:auto;overscroll-behavior:contain;padding:.65rem;contain:layout style}.widget-body p{margin:.4rem 0}.widget-body small{font-size:.8rem;opacity:.8}
|
||||||
|
.widget-arrange{display:none;gap:.3rem;align-items:center;flex-wrap:wrap;padding:.35rem;border-bottom:1px dashed var(--border,#8885);font-size:.8rem}.widget-arrange label{display:flex;align-items:center;gap:.2rem}
|
||||||
|
#organizer-dashboard .widget-drag,#organizer-dashboard .widget-resize{display:none;touch-action:none}.is-arranging .widget-arrange{display:flex}#organizer-dashboard.is-arranging .widget-drag,#organizer-dashboard.is-arranging .widget-resize{display:inline-flex}.widget-drag{cursor:grab!important}.widget-resize{position:absolute;right:0;bottom:0;z-index:2;cursor:nwse-resize!important}.widget-moving{outline:2px solid var(--accent);box-shadow:0 5px 20px #0004}
|
||||||
|
.widget-tabs{display:flex;gap:.2rem;overflow-x:auto;white-space:nowrap;margin-bottom:.4rem;padding-bottom:.25rem}#organizer-dashboard .widget-tabs button{border:0;border-radius:0;padding:.4rem .5rem}#organizer-dashboard .widget-tabs button[aria-selected=true]{box-shadow:inset 0 -2px var(--accent);color:var(--accent)}
|
||||||
|
.dashboard-list{list-style:none;margin:0;padding:0}.dashboard-list li{display:flex;align-items:baseline;gap:.45rem;padding:.4rem 0;border-bottom:1px solid var(--border,#8883);font-size:.88rem}.dashboard-list a{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dashboard-list time{font-size:.8rem;white-space:nowrap;opacity:.8}.dashboard-progress{display:grid;place-items:center;width:100px;height:100px;border-radius:50%;margin:.2rem auto;font-size:1.6rem;font-weight:600;background:radial-gradient(closest-side,var(--bg) 80%,transparent 81%),conic-gradient(var(--accent,#478ddd) var(--progress),var(--border,#8883) 0)}[data-widget=progress] .widget-body{text-align:center}
|
||||||
|
.dashboard-widget #task-productivity{margin:0;padding:0;max-width:none}.dashboard-widget .productivity-stats{margin:.5rem 0}.dashboard-widget .productivity-stat strong{font-size:1.25rem}.dashboard-widget .productivity-note{margin:.3rem 0}.visually-hidden{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}
|
||||||
|
[data-widget=progress] .dashboard-progress{width:84px;height:84px;font-size:1.4rem}[data-widget=progress] .widget-body small{display:block;line-height:1.4}
|
||||||
|
@media(max-width:700px){.home-account{top:3rem;max-width:calc(100vw - 1rem);box-sizing:border-box;flex-wrap:wrap;justify-content:flex-end}.home-wiki-title{max-width:calc(100vw - 2rem)}.home-paged .home-bookmarks-page{padding-top:6.5rem}.home-account .organizer-launch{width:1.8rem;height:1.8rem}.organizer-page .config-sidebar{width:auto;min-width:0;padding:.4rem}.organizer-page .config-sidebar .sidebar-nav{display:flex;flex-wrap:wrap;gap:.25rem}.organizer-page .config-sidebar .sidebar-nav a{padding:.5rem}.organizer-page .config-layout{gap:.5rem}}
|
||||||
|
@media(max-width:700px){.organizer-nav{padding:.3rem;gap:.15rem}.organizer-nav a{padding:.5rem .45rem;font-size:.8rem}.organizer-page .topbar>.brand{flex:1}.organizer-page .topbar{padding:.5rem}#organizer-dashboard{padding:.6rem}#dashboard-grid{grid-template-columns:minmax(0,1fr);grid-auto-rows:auto}.dashboard-widget{grid-column:1;grid-row:auto;min-height:180px;max-height:480px}.dashboard-widget[data-widget=activity]{max-height:650px}.widget-body{max-height:440px}#organizer-dashboard button,#organizer-dashboard select{min-height:40px}.widget-arrange [data-size=width]{display:none}.widget-arrange label:has([data-size=width]){display:none}#organizer-dashboard .widget-resize{display:none!important}.dashboard-list li{padding:.65rem 0}.organizer-settings-content{padding:.5rem}.organizer-settings-content .productivity-setting{grid-template-columns:1fr}.organizer-nav-icons{gap:0}.organizer-launch{width:1.9rem;height:1.9rem}}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#task-productivity{max-width:1200px;margin:1rem auto;padding:0 1rem;color:var(--fg,var(--text-color));box-sizing:border-box}
|
||||||
|
body:has(#task-productivity) .topbar,body:has(#contacts-app) .topbar{flex-wrap:wrap;gap:.5rem}
|
||||||
|
#task-productivity,#contacts-app{min-width:0;width:100%;overflow-wrap:anywhere}
|
||||||
|
@media(max-width:600px){body:has(#task-productivity) .topbar,body:has(#contacts-app) .topbar{padding:.5rem;gap:.3rem}body:has(#task-productivity) .topbar>.brand,body:has(#contacts-app) .topbar>.brand{flex:1}body:has(#task-productivity) .topbar>nav{display:none}}
|
||||||
|
.productivity-nav,.productivity-controls{display:flex;flex-wrap:wrap;align-items:center;gap:.65rem;margin:.5rem 0}.productivity-nav a{color:var(--link,var(--accent,#478ddd))}
|
||||||
|
.productivity-stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:.6rem;margin:1rem 0}.productivity-stat{padding:.6rem;border:1px solid var(--border,#8885);border-radius:.4rem}.productivity-stat strong{display:block;font-size:1.5rem}
|
||||||
|
.productivity-heatmap-scroll{overflow:auto;max-width:100%;padding:.4rem 0}.productivity-heatmap{display:grid;grid-template-rows:repeat(7,13px);grid-auto-flow:column;grid-auto-columns:13px;gap:3px;width:max-content}
|
||||||
|
.productivity-day{padding:0;min-width:0;border:0;border-radius:2px;background:var(--border,#8884);cursor:pointer}.productivity-day[data-level="1"]{background:#9be9a8}.productivity-day[data-level="2"]{background:#40c463}.productivity-day[data-level="3"]{background:#30a14e}.productivity-day[data-level="4"]{background:#216e39}.productivity-day:focus-visible{outline:2px solid var(--link,#4af);outline-offset:2px}
|
||||||
|
.productivity-table-wrap{overflow:auto}.productivity-table{border-collapse:collapse;width:100%}.productivity-table th,.productivity-table td{padding:.35rem .5rem;text-align:left;border-bottom:1px solid var(--border,#8884)}.productivity-table a{color:var(--link,#478ddd)}
|
||||||
|
.productivity-settings{max-width:850px}.productivity-setting{display:grid;grid-template-columns:minmax(180px,1fr) minmax(160px,2fr);gap:.5rem;padding:.4rem 0;border-bottom:1px solid var(--border,#8884);align-items:center}.productivity-setting input,.productivity-setting select,.productivity-controls input{box-sizing:border-box;width:100%;min-width:0;color:inherit;background:var(--input-bg,var(--bg,#222));border:1px solid var(--border,#8887);border-radius:.3rem;padding:.4rem}.productivity-setting input[type=checkbox]{width:2.2rem;height:1.2rem;accent-color:var(--link,#40a060)}.productivity-controls input{width:auto}.productivity-settings button,.productivity-controls button{padding:.4rem .8rem;color:inherit;background:var(--button-bg,var(--bg,#555));border:1px solid var(--border,#8887);border-radius:.3rem;cursor:pointer}.productivity-note{font-size:.85rem;opacity:.8}.productivity-running{padding:.5rem;border:1px solid var(--border,#8885);display:flex;gap:.5rem;align-items:center;flex-wrap:wrap}
|
||||||
|
@media(max-width:600px){.productivity-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.productivity-setting{grid-template-columns:1fr}.productivity-setting input,.productivity-setting select,.productivity-settings button{min-height:42px}.productivity-controls{align-items:stretch}.productivity-controls input{max-width:43%}#task-productivity{padding:0 .6rem}.productivity-table th,.productivity-table td{padding:.5rem .3rem}}
|
||||||
@@ -24,6 +24,57 @@ body:has(#tasks-app)>.topbar{min-width:0}#tasks-app{box-sizing:border-box}
|
|||||||
@media(max-width:760px){body:has(#tasks-app)>.topbar{flex-wrap:wrap;padding:.65rem;gap:.5rem}body:has(#tasks-app)>.topbar>.brand{flex:1;min-width:0}body:has(#tasks-app)>.topbar>.brand>a{display:block;overflow:hidden;text-overflow:ellipsis}body:has(#tasks-app)>.topbar>nav{order:2;width:100%}body:has(#tasks-app)>.topbar>.city-map-launch{margin-inline:0;flex-shrink:0}#tasks-fields{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}}
|
@media(max-width:760px){body:has(#tasks-app)>.topbar{flex-wrap:wrap;padding:.65rem;gap:.5rem}body:has(#tasks-app)>.topbar>.brand{flex:1;min-width:0}body:has(#tasks-app)>.topbar>.brand>a{display:block;overflow:hidden;text-overflow:ellipsis}body:has(#tasks-app)>.topbar>nav{order:2;width:100%}body:has(#tasks-app)>.topbar>.city-map-launch{margin-inline:0;flex-shrink:0}#tasks-fields{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}}
|
||||||
@media(max-width:760px){#tasks-dialog{max-width:none}#tasks-form{max-height:calc(100dvh - 2rem);height:100%}#tasks-fields{flex:1}#tasks-form>footer{margin-top:.5rem}}
|
@media(max-width:760px){#tasks-dialog{max-width:none}#tasks-form{max-height:calc(100dvh - 2rem);height:100%}#tasks-fields{flex:1}#tasks-form>footer{margin-top:.5rem}}
|
||||||
|
|
||||||
|
/* Detail editor: content on the left, scheduling on the right. */
|
||||||
|
#tasks-dialog{width:min(1180px,96vw);max-height:96dvh;padding:1rem;overflow:hidden}
|
||||||
|
body:has(#tasks-dialog[open]){overflow:hidden}
|
||||||
|
#tasks-form{max-height:calc(96dvh - 2rem);min-height:0}
|
||||||
|
#tasks-fields{gap:.7rem;margin:.5rem 0;overscroll-behavior:contain;scrollbar-gutter:stable}
|
||||||
|
#tasks-fields.task-editor-grid{grid-template-columns:minmax(0,1fr) minmax(0,1fr);align-items:start}
|
||||||
|
.task-editor-main,.task-editor-plan{min-width:0;display:flex;flex-direction:column;gap:.55rem}
|
||||||
|
.task-editor-plan{border-left:1px solid var(--border,#8885);padding-left:1rem}
|
||||||
|
#tasks-fields label{min-width:0;margin:0;font-size:.82rem;gap:.2rem}
|
||||||
|
#tasks-fields input,#tasks-fields select,#tasks-fields textarea{font-size:.88rem;padding:.4rem .5rem;margin:0}
|
||||||
|
#tasks-fields input[type=date]::-webkit-calendar-picker-indicator,#tasks-fields input[type=time]::-webkit-calendar-picker-indicator{background-color:#e8e8e8;border-radius:2px;opacity:.75}
|
||||||
|
#tasks-fields textarea{min-height:6rem;max-height:14rem}
|
||||||
|
#tasks-fields .task-editor-main>label:has(textarea){flex:1}
|
||||||
|
.task-editor-dates,.task-editor-effort,.task-editor-extra{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.5rem}
|
||||||
|
#tasks-fields fieldset{min-width:0;margin:0;padding:0;border:0}
|
||||||
|
#tasks-fields legend{font-size:.82rem;margin:0 0 .25rem;padding:0;color:var(--fg)}
|
||||||
|
.task-choice-options{display:flex;gap:.3rem}
|
||||||
|
#tasks-fields .task-choice-options label{position:relative;flex:1;display:flex}
|
||||||
|
#tasks-fields .task-choice-options input{position:absolute;width:1px;height:1px;opacity:0;padding:0;clip-path:inset(50%)}
|
||||||
|
.task-choice-options label>span{box-sizing:border-box;display:flex;align-items:center;justify-content:center;gap:.3rem;min-height:2.2rem;padding:.35rem .2rem;border:1px solid var(--border,#8885);border-radius:.4rem;cursor:pointer;text-align:center;line-height:1.25;background:var(--panel,var(--bg))}
|
||||||
|
.task-choice-options input:checked+span{border-color:var(--accent);background:color-mix(in srgb,var(--accent) 20%,var(--bg));box-shadow:inset 0 -2px var(--accent);font-weight:600}
|
||||||
|
.task-choice-options input:focus-visible+span{outline:2px solid var(--accent);outline-offset:2px}
|
||||||
|
.task-choice-options input:disabled+span{opacity:.65;cursor:default}
|
||||||
|
.task-choice-icon{color:var(--accent);font-size:1rem}
|
||||||
|
[data-field=complexity] .task-choice-icon{font-size:.5rem;letter-spacing:-.08em}
|
||||||
|
#tasks-fields .task-editor-reminders{padding:.5rem .65rem;border:1px solid var(--border,#8885);border-radius:.5rem;display:grid;grid-template-columns:minmax(0,1fr) 7rem;gap:.4rem .6rem}
|
||||||
|
#tasks-fields .task-editor-reminders label.task-toggle{grid-column:1;font-size:.8rem}
|
||||||
|
#tasks-fields .task-editor-reminders label:has(input[type=time]){grid-column:2;grid-row:1/3;align-self:center}
|
||||||
|
#tasks-fields .task-editor-reminders small{grid-column:1/-1;font-size:.7rem;color:var(--muted,var(--fg));line-height:1.45}
|
||||||
|
.task-editor-advanced{grid-column:1/-1;border-top:1px solid var(--border,#8885);padding-top:.4rem;font-size:.82rem}
|
||||||
|
.task-editor-advanced summary{cursor:pointer;padding:.2rem 0}
|
||||||
|
.task-editor-extra{margin-top:.5rem}
|
||||||
|
#tasks-fields .task-editor-extra .task-full{grid-column:auto}
|
||||||
|
.task-editor-actions{display:flex;gap:.4rem;flex-wrap:wrap}
|
||||||
|
#tasks-app .task-editor-actions button{font-size:.8rem;padding:.4rem .55rem}
|
||||||
|
#tasks-form>footer{margin-top:.5rem}
|
||||||
|
#tasks-error:empty{display:none}
|
||||||
|
#tasks-history{max-height:8rem;overflow:auto}
|
||||||
|
@media(max-width:760px){
|
||||||
|
#tasks-dialog{width:100%;max-width:none;height:100dvh;max-height:100dvh;padding:.75rem}
|
||||||
|
#tasks-form{max-height:calc(100dvh - 1.5rem)}
|
||||||
|
#tasks-fields.task-editor-grid{grid-template-columns:minmax(0,1fr)}
|
||||||
|
.task-editor-plan{border-left:0;border-top:1px solid var(--border,#8885);padding: .65rem 0 0}
|
||||||
|
#tasks-fields input,#tasks-fields select,#tasks-fields textarea{font-size:16px;min-height:44px;max-width:100%}
|
||||||
|
.task-choice-options label>span{min-height:44px;font-size:.78rem}
|
||||||
|
#tasks-fields .task-choice-options input{min-height:0}
|
||||||
|
#tasks-fields label.task-toggle{min-height:44px}
|
||||||
|
#tasks-fields label.task-toggle input{min-height:0;flex-shrink:0}
|
||||||
|
.task-editor-extra{grid-template-columns:minmax(0,1fr)}
|
||||||
|
}
|
||||||
|
|
||||||
/* Inline tasks: shared columns on desktop, labelled touch controls on mobile. */
|
/* Inline tasks: shared columns on desktop, labelled touch controls on mobile. */
|
||||||
.tasks-list-scroll{min-width:0}
|
.tasks-list-scroll{min-width:0}
|
||||||
.task-inline-header{display:none}
|
.task-inline-header{display:none}
|
||||||
|
|||||||
+6
-14
@@ -1954,13 +1954,11 @@
|
|||||||
"checkbox",
|
"checkbox",
|
||||||
enabled.some((e) => e.id === c.id),
|
enabled.some((e) => e.id === c.id),
|
||||||
);
|
);
|
||||||
if (actor)
|
if (actor) {
|
||||||
field(
|
const settingsLink=node('a',t('既定のカレンダーは個人設定で変更','Change default calendars in personal settings'));
|
||||||
t("自分のデフォルトとして保存", "Save as my defaults"),
|
settingsLink.href='/-/sys/config?panel=organizer#organizer-calendar-defaults';
|
||||||
"save-defaults",
|
$("calendar-fields").append(settingsLink);
|
||||||
"checkbox",
|
}
|
||||||
false,
|
|
||||||
);
|
|
||||||
$("calendar-fields").append(
|
$("calendar-fields").append(
|
||||||
node(
|
node(
|
||||||
"p",
|
"p",
|
||||||
@@ -1980,13 +1978,7 @@
|
|||||||
const base = ["detail", "edit", "new"].includes(route().view)
|
const base = ["detail", "edit", "new"].includes(route().view)
|
||||||
? "/v/plan"
|
? "/v/plan"
|
||||||
: location.pathname;
|
: location.pathname;
|
||||||
if (form.has("save-defaults")) {
|
navigate(
|
||||||
await api("preferences", "PUT", {
|
|
||||||
calendars: selected.map((c) => c.id),
|
|
||||||
});
|
|
||||||
navigate(base);
|
|
||||||
} else
|
|
||||||
navigate(
|
|
||||||
base +
|
base +
|
||||||
"?calendar=" +
|
"?calendar=" +
|
||||||
selected.map((c) => encodeURIComponent(c.pretty_name)).join(","),
|
selected.map((c) => encodeURIComponent(c.pretty_name)).join(","),
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
(() => {
|
||||||
|
'use strict';
|
||||||
|
const app = document.getElementById('contacts-app'); if (!app) return;
|
||||||
|
const ja = document.documentElement.lang.startsWith('ja'), t = (en, jp) => ja ? jp : en;
|
||||||
|
const api = '/_/api/v1/extension/organizer.contacts/', editor = document.getElementById('contact-editor');
|
||||||
|
const el = (tag, text) => { const n = document.createElement(tag); if (text !== undefined) n.textContent = text; return n; };
|
||||||
|
const exportLink = el('a', t('Export address book', 'アドレス帳を書き出す')); exportLink.href = api + 'export.vcf';
|
||||||
|
document.getElementById('contacts-controls').append(exportLink);
|
||||||
|
async function request(path, options = {}) {
|
||||||
|
const r = await fetch(api + path, { credentials: 'same-origin', signal: AbortSignal.timeout(15000), ...options, headers: { 'Content-Type': 'application/json', ...options.headers } });
|
||||||
|
const data = await r.json().catch(() => ({}));
|
||||||
|
if (!r.ok || r.redirected) throw Error(r.status === 412 ? t('Changed elsewhere. Reload before restoring.', '他で変更されています。再読込してから復元してください。') : t('Unable to load/restore. Check login and permissions.', '読込・復元できません。ログインと権限を確認してください。'));
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
function attach() {
|
||||||
|
const form = editor.querySelector('form'), link = form?.querySelector('a[href$=".vcf"]');
|
||||||
|
if (!link || form.dataset.historyAttached) return; form.dataset.historyAttached = 'true';
|
||||||
|
const id = new URL(link.href).pathname.split('/').pop().slice(0, -4);
|
||||||
|
const details = el('details'); details.className = 'contact-history';
|
||||||
|
details.append(el('summary', t('Revision history', '変更履歴')));
|
||||||
|
const status = el('p'); status.role = 'status'; const rows = el('div'), preview = el('pre'); details.append(status, rows, preview); editor.append(details);
|
||||||
|
let opened = false, busy = false, version = 0;
|
||||||
|
async function load(before = '') {
|
||||||
|
if (busy) return; busy = true;
|
||||||
|
try {
|
||||||
|
if (!version) version = (await request('items/' + id)).item.version;
|
||||||
|
const data = await request('items/' + id + '/history' + (before ? '?before=' + before : ''));
|
||||||
|
if (!details.isConnected) return;
|
||||||
|
rows.querySelector('[data-more]')?.remove();
|
||||||
|
for (const revision of data.items) {
|
||||||
|
const row = el('div'); row.className = 'contact-history-row';
|
||||||
|
row.append(el('span', '#' + revision.version + ' · ' + new Date(revision.created_ms).toLocaleString() + (revision.deleted ? t(' · deleted', ' · 削除') : '')));
|
||||||
|
const view = el('button', t('Preview', '確認')); view.type = 'button';
|
||||||
|
view.onclick = async () => { try { const d = await request('items/' + id + '/history/' + revision.version); if (details.isConnected) preview.textContent = d.item.vcard; } catch (e) { status.textContent = e.message; } };
|
||||||
|
row.append(view);
|
||||||
|
if (app.dataset.writable === 'true') {
|
||||||
|
const restore = el('button', t('Restore', '復元')); restore.type = 'button';
|
||||||
|
restore.onclick = async () => {
|
||||||
|
if (busy || !confirm(t('Restore this revision as a new version? Unsaved form edits will be discarded. The contact will be active.', 'この履歴を新しい版として復元しますか?フォームの未保存変更は破棄し、連絡先を有効な状態に戻します。'))) return;
|
||||||
|
busy = true; restore.disabled = true;
|
||||||
|
try { const d = await request('items/' + id + '/restore', { method: 'POST', headers: { 'If-Match': '"' + version + '"' }, body: JSON.stringify({ version, revision: revision.version }) }); if (details.isConnected) app.dispatchEvent(new CustomEvent('contact-restored', { detail: d.item })); }
|
||||||
|
catch (e) { status.textContent = e.message; } finally { busy = false; restore.disabled = false; }
|
||||||
|
};
|
||||||
|
row.append(restore);
|
||||||
|
}
|
||||||
|
rows.append(row);
|
||||||
|
}
|
||||||
|
if (data.next) { const more = el('button', t('Earlier revisions', '以前の履歴')); more.type = 'button'; more.dataset.more = 'true'; more.onclick = () => load(data.next); rows.append(more); }
|
||||||
|
} catch (e) { status.textContent = e.message; opened = false; } finally { busy = false; }
|
||||||
|
}
|
||||||
|
details.ontoggle = () => { if (details.open && !opened) { opened = true; load(); } };
|
||||||
|
}
|
||||||
|
new MutationObserver(attach).observe(editor, { childList: true }); attach();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
(()=>{'use strict';const app=document.getElementById('contacts-app');if(!app)return;const ja=document.documentElement.lang.startsWith('ja'),t=(en,jp)=>ja?jp:en,api='/_/api/v1/extension/organizer.contacts/',writable=app.dataset.writable==='true',status=document.getElementById('contacts-status'),list=document.getElementById('contacts-list'),editor=document.getElementById('contact-editor'),controls=document.getElementById('contacts-controls');
|
||||||
|
const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;},button=(text,fn)=>{const b=el('button',text);b.type='button';b.onclick=fn;return b;};app.querySelector('h1').textContent=t('Private contacts','個人アドレス帳');
|
||||||
|
async function request(path,options={}){const r=await fetch(api+path,{credentials:'same-origin',signal:AbortSignal.timeout(15000),...options,headers:{'Content-Type':'application/json',...options.headers}});const d=await r.json().catch(()=>({}));if(!r.ok||r.redirected)throw Error(r.status===412?t('Changed or duplicate UID. Your input is retained.','競合または同じUIDの連絡先があります。入力は保持しています。'):t('Unable to save/load. Check your login, permissions and input.','保存・読込できません。ログイン、権限、入力を確認してください。'));return d;}
|
||||||
|
let dirty=false,busy=false,ticket=0;const search=el('input');search.type='search';search.placeholder=search.ariaLabel=t('Name, email, phone, organization','名前・メール・電話・所属');controls.append(search);const trash=el('select');trash.ariaLabel=t('Contacts or trash','連絡先・削除済み');for(const [value,label]of [['0',t('Contacts','連絡先')],['1',t('Deleted contacts','削除済み')]]){const o=el('option',label);o.value=value;trash.append(o);}controls.append(trash);trash.onchange=()=>load();const allowLeave=()=>!dirty||confirm(t('Discard unsaved edits?','未保存の変更を破棄しますか?'));
|
||||||
|
function show(c){dirty=false;editor.replaceChildren();const form=el('form'),inputs={};for(const [key,label,multi] of [['name',t('Name','名前'),false],['emails',t('Emails (one per line)','メール(1行1件)'),true],['phones',t('Phones (one per line)','電話(1行1件)'),true],['organization',t('Organization','所属'),false],['notes',t('Notes','メモ'),true]]){const l=el('label',label),n=el(multi?'textarea':'input');n.value=Array.isArray(c[key])?c[key].join('\n'):c[key]||'';n.disabled=!writable;n.name=key;if(key==='name'){n.required=true;n.maxLength=300;}l.append(n);form.append(l);inputs[key]=n;n.oninput=()=>{dirty=true;};}
|
||||||
|
const actions=el('div'),save=el('button',t('Save','保存'));save.type='submit';save.disabled=!writable;actions.append(save);if(c.version){const a=el('a',t('Export vCard','vCardを書き出す'));a.href=api+'items/'+c.uuid+'.vcf';actions.append(' ',a);const remove=button(c.deleted?t('Restore','復元'):t('Delete','削除'),async()=>{if(busy||!confirm(c.deleted?t('Restore this contact?','この連絡先を復元しますか?'):t('Delete this contact?','この連絡先を削除しますか?')))return;busy=true;try{await request('items/'+c.uuid,{method:'PUT',headers:{'If-Match':'"'+c.version+'"'},body:JSON.stringify({...c,deleted:!c.deleted})});dirty=false;editor.replaceChildren();await load();}catch(e){status.textContent=e.message;}finally{busy=false;}});remove.disabled=!writable;actions.append(' ',remove);}
|
||||||
|
form.append(actions);form.onsubmit=async e=>{e.preventDefault();if(busy)return;const draft={...c};for(const key of Object.keys(inputs))draft[key]=['emails','phones'].includes(key)?inputs[key].value.split('\n').map(v=>v.trim()).filter(Boolean):inputs[key].value;busy=true;save.disabled=true;try{const d=await request('items'+(c.version?'/'+c.uuid:''),{method:c.version?'PUT':'POST',headers:c.version?{'If-Match':'"'+c.version+'"'}:{},body:JSON.stringify(draft)});show(d.item);status.textContent=t('Saved','保存しました');await load();}catch(e){status.textContent=e.message;}finally{busy=false;save.disabled=!writable;}};editor.append(form);if(c.vcard){const d=el('details'),summary=el('summary',t('Original vCard (unsupported properties are retained)','vCard(未対応プロパティも保持)'));d.append(summary,el('pre',c.vcard));editor.append(d);}inputs.name.focus();}
|
||||||
|
async function load(after='',append=false){const id=++ticket;try{const d=await request('items?'+new URLSearchParams({q:search.value,after,deleted:trash.value}));if(id!==ticket)return;if(!append)list.replaceChildren();list.querySelector('[data-more]')?.remove();for(const c of d.items){const b=button(c.name+' · '+(c.emails[0]||c.organization||''),async()=>{if(!allowLeave())return;try{const d=await request('items/'+c.uuid);show(d.item);}catch(e){status.textContent=e.message;}});list.append(b);}if(d.next){const b=button(t('More','続き'),()=>load(d.next,true));b.dataset.more='true';list.append(b);}if(!list.children.length)list.append(el('p',t('No contacts','連絡先がありません')));}catch(e){status.textContent=e.message;}}
|
||||||
|
let timer;search.oninput=()=>{clearTimeout(timer);timer=setTimeout(()=>load(),200);};if(writable){controls.append(button(t('New contact','連絡先を追加'),()=>{if(allowLeave())show({uuid:crypto.randomUUID(),version:0,emails:[],phones:[],deleted:false});}));const file=el('input');file.type='file';file.accept='.vcf,text/vcard';file.hidden=true;controls.append(button(t('Import vCard','vCardを取り込む'),()=>file.click()),file);file.onchange=async()=>{const f=file.files[0];if(!f)return;try{if(f.size>2*1024*1024)throw Error(t('Maximum 2 MiB','上限は2 MiBです'));const text=await f.text();const cards=text.match(/BEGIN:VCARD\r?\n[\s\S]*?END:VCARD(?:\r?\n|$)/g)||[];if(!cards.length||cards.length>200||text.replace(/BEGIN:VCARD\r?\n[\s\S]*?END:VCARD(?:\r?\n|$)/g,'').trim())throw Error(t('Expected up to 200 UTF-8 vCards (3.0/4.0).','UTF-8のvCard 3.0/4.0(最大200件)を指定してください。'));if(!confirm(t('Import contacts: ','連絡先を取り込みます:')+cards.length+'\n'+t('Existing identical UID/content is skipped. Conflicts are not overwritten.','同一UID・内容は重複登録しません。競合は上書きせず報告します。')))return;let success=0,failed=[];for(let i=0;i<cards.length;i++){try{await request('import',{method:'POST',headers:{'Content-Type':'text/vcard'},body:cards[i]});success++;}catch(e){failed.push(i+1);}}status.textContent=t('Imported/existing: ','取り込み済み・既存:')+success+(failed.length?t(' / Failed card numbers: ',' / 失敗したカード番号:')+failed.join(', '):'');await load();}catch(e){status.textContent=e.message;}finally{file.value='';}};}
|
||||||
|
app.addEventListener('contact-restored',e=>{show(e.detail);load();status.textContent=t('Revision restored as a new version','履歴を新しい版として復元しました');});window.addEventListener('beforeunload',e=>{if(dirty){e.preventDefault();e.returnValue='';}});load();})();
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
(function(root){'use strict';function parse(input){
|
||||||
|
const tokens=[];let value='',quote='',escaped=false,started=false;
|
||||||
|
for(const ch of input.trim()){if(escaped){value+=ch;escaped=false;started=true;continue;}if(ch==='\\'){escaped=true;continue;}if(quote){if(ch===quote)quote='';else value+=ch;continue;}if(ch==='"'||ch==="'"){quote=ch;started=true;continue;}if(/\s/.test(ch)){if(started){tokens.push(value);value='';started=false;}}else{value+=ch;started=true;}}
|
||||||
|
if(quote||escaped)throw Error('Unclosed quote / 引用符を閉じてください');if(started)tokens.push(value);
|
||||||
|
if(tokens[0]?.toLowerCase()!=='add'||!['task','cal'].includes(tokens[1]?.toLowerCase()))throw Error('add task / add cal');
|
||||||
|
const kind=tokens[1].toLowerCase(),options={},title=[],allowed=kind==='task'?['project','cost','due','start','review','planned','complexity']:['calendar','from','to'];
|
||||||
|
for(const token of tokens.slice(2)){const m=token.match(/^([a-z]+):(.*)$/i);if(!m){title.push(token);continue;}const key=m[1].toLowerCase();if(!allowed.includes(key)||Object.hasOwn(options,key)||!m[2])throw Error('Invalid option / オプションを確認:'+key);options[key]=m[2];}
|
||||||
|
if(!title.join(' ').trim())throw Error('Title required / 件名を入力してください');
|
||||||
|
if(options.cost){const m=options.cost.match(/^(\d+(?:\.\d+)?)(h|m)$/);if(!m)throw Error('cost:2h / cost:30m');options.estimate_minutes=Number(m[1])*(m[2]==='h'?60:1);if(!Number.isInteger(options.estimate_minutes)||options.estimate_minutes>10080)throw Error('Invalid cost / 工数を確認してください');}
|
||||||
|
for(const k of ['due','start','review','planned'])if(options[k]&&!/^\d{4}-\d{2}-\d{2}$/.test(options[k]))throw Error(k+':YYYY-MM-DD');
|
||||||
|
if(options.complexity&&!/^[1-5]$/.test(options.complexity))throw Error('complexity:1–5');
|
||||||
|
if(kind==='cal'&&(!options.from||!options.to))throw Error('from:YYYY-MM-DDTHH:mm to:YYYY-MM-DDTHH:mm');
|
||||||
|
return {kind,title:title.join(' '),options};
|
||||||
|
}root.PagesWikiHomeCommand={parse};if(typeof module!=='undefined')module.exports={parse};})(globalThis);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
const {test}=require('node:test');const assert=require('node:assert/strict');const {parse}=require('./home-command-parser.js');
|
||||||
|
test('commands preserve quoted project and title',()=>{const c=parse('add task "調査を進める" project:"開発 計画" cost:2h due:2026-11-02');assert.equal(c.title,'調査を進める');assert.equal(c.options.project,'開発 計画');assert.equal(c.options.estimate_minutes,120);});
|
||||||
|
test('calendar and malformed input',()=>{assert.equal(parse('add cal 会議 from:2026-11-02T09:00 to:2026-11-02T10:00').kind,'cal');for(const v of ['add task','add task x cost:0.001h','add task x foo:z','add task x project:a project:b','add task "x','add cal x'])assert.throws(()=>parse(v));});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
(()=>{'use strict';const input=document.querySelector('[data-home-type-search]'),parser=window.PagesWikiHomeCommand;if(!input||!parser)return;const form=input.closest('form'),ja=document.documentElement.lang.startsWith('ja'),t=(en,jp)=>ja?jp:en,api='/_/api/v1/extension/organizer.tasks/',box=document.createElement('section');box.className='home-command-panel';box.hidden=true;box.style.cssText='position:relative;z-index:30;padding:.7rem;border-radius:.5rem;background:var(--bg-color,var(--bg,#222));color:var(--text-color,var(--fg,#eee));text-align:start';form.after(box);let busy=false,sequence=0,timer,prepared=null;
|
||||||
|
const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
|
||||||
|
async function request(path,options={}){const r=await fetch(api+path,{credentials:'same-origin',signal:AbortSignal.timeout(15000),...options,headers:{'Content-Type':'application/json'}});const d=await r.json().catch(()=>({}));if(!r.ok||r.redirected)throw Error(t('Check login, permissions, dates and current task settings. Input is retained.','ログイン、権限、日時、タスク設定を確認してください。入力は保持しています。'));return d;}
|
||||||
|
const matches=()=>/^add\s+(task|cal)\b/i.test(input.value.trim());
|
||||||
|
async function resolve(kind,name){const d=await request(kind==='project'?'items?'+new URLSearchParams({kind:'project',view:'all',q:name,limit:100}):'calendars'),items=d.items.filter(c=>kind==='project'?c.title===name||c.uuid===name:c.name===name||c.pretty_name===name||c.id===name||!name);if(items.length!==1||d.next)throw Error(t('Select a unique '+kind+' (name or UUID).',kind==='project'?'プロジェクトを名前またはUUIDで一意に指定してください。':'カレンダーを指定してください(calendar:名前)。'));return kind==='project'?items[0].uuid:items[0].id;}
|
||||||
|
async function suggestions(){const id=++sequence;if(!matches()){box.hidden=true;return;}box.hidden=false;box.replaceChildren(el('small',t('Enter: review → Create. Dates use the Domain timezone.','Enterで確認 → 作成。日時はドメインのタイムゾーンです。')));const m=input.value.match(/\b(project|calendar):([^\s"]*)$/i);if(!m)return;try{const kind=m[1].toLowerCase(),d=await request(kind==='project'?'items?'+new URLSearchParams({kind:'project',view:'all',q:m[2],limit:20}):'calendars');if(id!==sequence||!matches())return;for(const c of d.items.filter(c=>kind==='project'||c.name.toLowerCase().includes(m[2].toLowerCase())).slice(0,8)){const b=el('button',kind==='project'?c.title:c.name);b.type='button';b.style.display='block';b.onclick=()=>{const name=kind==='project'?c.title:c.pretty_name;input.value=input.value.slice(0,m.index)+kind+':'+JSON.stringify(name)+' ';input.focus();prepared=null;sequence++;box.replaceChildren();};box.append(b);}}catch(e){if(id===sequence)box.append(el('p',e.message));}}
|
||||||
|
input.addEventListener('input',()=>{prepared=null;sequence++;clearTimeout(timer);timer=setTimeout(suggestions,180);});input.addEventListener('keydown',e=>{if(matches()&&e.key==='Escape'){box.hidden=true;sequence++;}});
|
||||||
|
form.addEventListener('submit',async e=>{if(!matches())return;e.preventDefault();e.stopImmediatePropagation();if(busy)return;clearTimeout(timer);sequence++;busy=true;const source=input.value;box.hidden=false;box.replaceChildren();try{const cmd=parser.parse(source),o=cmd.options;let path,payload;
|
||||||
|
if(prepared?.source===source){({path,payload}=prepared);}else if(cmd.kind==='task'){path='capture';payload={request_id:crypto.randomUUID(),title:cmd.title};if(o.project)payload.project_uuid=await resolve('project',o.project);for(const [a,b]of [['due','due_on'],['start','start_on'],['planned','planned_on'],['review','review_on'],['estimate_minutes','estimate_minutes']])if(o[a]!==undefined)payload[b]=o[a];if(o.complexity)payload.complexity=Number(o.complexity);}else{path='calendar-capture';payload={request_id:crypto.randomUUID(),title:cmd.title,calendar_uuid:await resolve('calendar',o.calendar||''),from:o.from,to:o.to};}
|
||||||
|
if(source!==input.value)return;prepared={source,path,payload};box.append(el('strong',cmd.title),el('pre',Object.entries(o).map(([k,v])=>k+': '+v).join('\n')));const create=el('button',t('Create','作成')),cancel=el('button',t('Cancel','キャンセル'));create.type=cancel.type='button';cancel.onclick=()=>{box.hidden=true;};create.onclick=async()=>{if(busy)return;busy=true;create.disabled=true;cancel.disabled=true;input.disabled=true;try{const d=await request(path,{method:'POST',body:JSON.stringify(payload)});prepared=null;box.replaceChildren();const link=el('a',t('Created → Open','作成しました → 開く'));link.href=path==='capture'?'/v/plan/task/'+d.item.uuid:'/v/plan/event/'+encodeURIComponent(d.uid)+'?calendar='+encodeURIComponent(d.calendar);box.append(link);input.value='';}catch(err){box.append(el('p',err.message));}finally{busy=false;create.disabled=false;cancel.disabled=false;input.disabled=false;}};box.append(create,cancel);
|
||||||
|
}catch(err){box.append(el('p',err.message));}finally{busy=false;}},true);
|
||||||
|
})();
|
||||||
@@ -105,6 +105,7 @@
|
|||||||
candidates = [];
|
candidates = [];
|
||||||
close();
|
close();
|
||||||
const query = input.value.trim();
|
const query = input.value.trim();
|
||||||
|
if (/^add\s+(task|cal)\b/i.test(query)) return;
|
||||||
if ([...query].length < 2) return;
|
if ([...query].length < 2) return;
|
||||||
timer = setTimeout(() => request(query), 140);
|
timer = setTimeout(() => request(query), 140);
|
||||||
});
|
});
|
||||||
@@ -114,6 +115,7 @@
|
|||||||
else if (event.key === 'Escape') { event.preventDefault(); close(); }
|
else if (event.key === 'Escape') { event.preventDefault(); close(); }
|
||||||
});
|
});
|
||||||
form.addEventListener('submit', event => {
|
form.addEventListener('submit', event => {
|
||||||
|
if (/^add\s+(task|cal)\b/i.test(input.value.trim())) return;
|
||||||
if (event.ctrlKey || event.metaKey) return;
|
if (event.ctrlKey || event.metaKey) return;
|
||||||
const options = rows();
|
const options = rows();
|
||||||
let selected = active >= 0 ? options[active] : null;
|
let selected = active >= 0 ? options[active] : null;
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
(() => {
|
||||||
|
'use strict';
|
||||||
|
const root=document.getElementById('organizer-dashboard');if(!root)return;
|
||||||
|
const ja=document.documentElement.lang.startsWith('ja'),t=(en,jp)=>ja?jp:en;
|
||||||
|
const api='/_/api/v1/extension/organizer.tasks/',calendarAPI='/_/api/v1/extension/organizer.calendar/';
|
||||||
|
const grid=document.getElementById('dashboard-grid'),status=document.getElementById('dashboard-status'),controls=document.getElementById('dashboard-controls');
|
||||||
|
const writable=root.dataset.writable==='true',today=root.dataset.today,zone=root.dataset.timezone;
|
||||||
|
const names={progress:t('Today’s completion','本日の達成率'),today:t('Today’s tasks','本日のタスク'),tomorrow:t('Tomorrow’s tasks','明日のタスク'),tasks:t('Tasks','タスク'),schedule:t('Today’s schedule','本日のスケジュール'),activity:t('Activity report','達成度・作業レポート')};
|
||||||
|
const defaults=[['progress',4,3],['today',4,3],['tomorrow',4,3],['tasks',8,4],['schedule',4,4],['activity',12,5]].map(([id,width,height])=>({id,width,height,...(id==='tasks'?{tab:'inbox'}:{})}));
|
||||||
|
const tabs={inbox:'Inbox',backlog:'Backlog',someday:'Someday',review:'Review',all:'Incomplete',done:'Done'};
|
||||||
|
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
|
||||||
|
function button(text,label,fn){const b=el('button',text);b.type='button';b.title=b.ariaLabel=label;b.onclick=fn;return b;}
|
||||||
|
function link(text,href){const a=el('a',text);a.href=href;return a;}
|
||||||
|
let widgets=[],version=0,dirty=false,saving=false,editing=false,loaded=false;
|
||||||
|
const cards=new Map();let active=0;const queue=[];
|
||||||
|
// No timer polling. At most two widget jobs run concurrently; obsolete tab
|
||||||
|
// requests are aborted. Errors remain confined to the affected widget.
|
||||||
|
function schedule(job){queue.push(job);pump();}
|
||||||
|
function pump(){while(active<2&&queue.length){active++;Promise.resolve().then(queue.shift()).catch(e=>{status.textContent=e.message;}).finally(()=>{active--;pump();});}}
|
||||||
|
async function request(url,options={}){
|
||||||
|
const response=await fetch(url,{credentials:'same-origin',cache:'no-store',...options,headers:{'Content-Type':'application/json',...options.headers}});
|
||||||
|
if(response.status===401||response.redirected)throw Error(t('Sign in again. Unsaved layout is retained.','再度ログインしてください。未保存の配置は保持しています。'));
|
||||||
|
const data=await response.json().catch(()=>({}));
|
||||||
|
if(!response.ok)throw Error(response.status===412?t('Settings changed elsewhere. Reload to review; your layout has not been overwritten.','別の画面で設定が更新されました。再読み込みして確認してください。配置は上書きしていません。'):t('Request failed. Try again.','取得・保存に失敗しました。再度お試しください。'));
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
const save=button(t('Save layout','配置を保存'),t('Save layout','配置を保存'),async()=>{
|
||||||
|
if(saving||!loaded)return;saving=true;updateControls();
|
||||||
|
try{const data=await request(api+'dashboard',{method:'PUT',signal:AbortSignal.timeout(15000),body:JSON.stringify({version,widgets})});version=data.version;dirty=false;status.textContent=t('Layout saved','配置を保存しました');}
|
||||||
|
catch(e){status.textContent=e.message;}finally{saving=false;updateControls();}
|
||||||
|
});
|
||||||
|
const edit=button('⚙',t('Arrange widgets','ウィジェットを配置'),()=>{editing=!editing;root.classList.toggle('is-arranging',editing);edit.setAttribute('aria-pressed',String(editing));});edit.setAttribute('aria-pressed','false');
|
||||||
|
const refresh=button('↻',t('Refresh visible widgets','ウィジェットを更新'),()=>{for(const item of widgets){const card=cards.get(item.id);if(card)loadWidget(item,card);}});
|
||||||
|
const add=el('select');add.ariaLabel=t('Add widget','ウィジェットを追加');add.onchange=()=>{const item=defaults.find(w=>w.id===add.value);if(item){widgets.push({...item});render();changed();}};
|
||||||
|
const reset=button(t('Reset layout','初期配置'),t('Reset layout','初期配置'),()=>{if(confirm(t('Replace this layout with the default layout? Save to apply.','初期配置に戻しますか? 保存するまでは確定しません。'))){widgets=defaults.map(x=>({...x}));render();changed();}});
|
||||||
|
controls.append(refresh);if(writable)controls.append(edit,add,reset,save);
|
||||||
|
function updateControls(){save.disabled=!dirty||saving||!loaded;edit.disabled=add.disabled=reset.disabled=saving||!loaded;refresh.disabled=!loaded;root.classList.toggle('dashboard-saving',saving);for(const card of cards.values())card.querySelectorAll('.widget-arrange button,.widget-arrange select,.widget-drag,.widget-resize').forEach(n=>n.disabled=saving);add.replaceChildren();const option=el('option',t('+ Add widget','+ ウィジェットを追加'));option.value='';add.append(option);for(const [id,name] of Object.entries(names)){if(widgets.some(w=>w.id===id)||id==='schedule'&&root.dataset.calendar!=='true')continue;const o=el('option',name);o.value=id;add.append(o);}}
|
||||||
|
function changed(){dirty=true;status.textContent=t('Unsaved layout changes','配置は未保存です');updateControls();}
|
||||||
|
window.addEventListener('beforeunload',event=>{if(dirty){event.preventDefault();event.returnValue='';}});
|
||||||
|
function applySize(item,card){card.style.setProperty('--widget-width',String(item.width));card.style.setProperty('--widget-height',String(item.height));}
|
||||||
|
function move(item,delta){if(saving)return;const index=widgets.indexOf(item),target=index+delta;if(target<0||target>=widgets.length)return;widgets.splice(index,1);widgets.splice(target,0,item);for(const w of widgets)grid.append(cards.get(w.id));changed();}
|
||||||
|
function render(){
|
||||||
|
for(const card of cards.values()){card._controller?.abort();card._gesture?.abort();}cards.clear();grid.replaceChildren();
|
||||||
|
for(const item of widgets){
|
||||||
|
const card=el('section',undefined,'dashboard-widget');card.id=item.id;card.dataset.widget=item.id;applySize(item,card);
|
||||||
|
const header=el('header',undefined,'widget-header'),heading=el('h2',names[item.id]);heading.id='widget-title-'+item.id;card.setAttribute('aria-labelledby',heading.id);
|
||||||
|
header.append(heading);const destinations={progress:'/v/plan/today',today:'/v/plan/today',tomorrow:'/v/plan/tasks/tomorrow',tasks:'/v/plan/tasks',schedule:'/v/plan',activity:'/v/plan/dashboard#activity'};
|
||||||
|
const open=link('↗',destinations[item.id]);open.title=open.ariaLabel=t('Open ','開く: ')+names[item.id];header.append(open);
|
||||||
|
const arrange=el('div',undefined,'widget-arrange');
|
||||||
|
if(writable){
|
||||||
|
const drag=button('⠿',t('Drag to move; use arrow buttons to reorder','ドラッグで移動。矢印ボタンでも並べ替えできます'),()=>{});drag.className='widget-drag';header.prepend(drag);
|
||||||
|
arrange.append(button('←',t('Move earlier','前に移動'),()=>move(item,-1)),button('→',t('Move later','後ろに移動'),()=>move(item,1)));
|
||||||
|
for(const [key,label,min,max] of [['width',t('Width','幅'),3,12],['height',t('Height','高さ'),2,10]]){
|
||||||
|
const field=el('label',label),select=el('select');select.dataset.size=key;
|
||||||
|
for(let n=min;n<=max;n++){const option=el('option',key==='width'?n+'/12':String(n));option.value=String(n);select.append(option);}select.value=String(item[key]);
|
||||||
|
select.onchange=()=>{item[key]=Number(select.value);applySize(item,card);changed();};field.append(select);arrange.append(field);
|
||||||
|
}
|
||||||
|
arrange.append(button('×',t('Remove widget','ウィジェットを外す'),()=>{widgets=widgets.filter(w=>w!==item);render();changed();}));
|
||||||
|
let action;
|
||||||
|
function start(event,mode){if(!editing||saving||event.button!==0)return;event.preventDefault();event.currentTarget.setPointerCapture(event.pointerId);action={mode,x:event.clientX,y:event.clientY,width:item.width,height:item.height,pointer:event.pointerId};card.classList.add('widget-moving');card._gesture?.abort();card._gesture=new AbortController();const options={signal:card._gesture.signal};document.addEventListener('pointermove',moving,options);document.addEventListener('pointerup',finish,options);document.addEventListener('pointercancel',cancel,options);}
|
||||||
|
function moving(event){if(!action||event.pointerId!==action.pointer||action.mode!=='resize')return;const unit=(grid.clientWidth+12)/12;item.width=Math.max(3,Math.min(12,Math.round(action.width+(event.clientX-action.x)/unit)));item.height=Math.max(2,Math.min(10,Math.round(action.height+(event.clientY-action.y)/84)));applySize(item,card);}
|
||||||
|
function finish(event){if(!action||event.pointerId!==action.pointer)return;const previous=action;action=null;card._gesture?.abort();card.classList.remove('widget-moving');if(previous.mode==='move'){const target=document.elementFromPoint(event.clientX,event.clientY)?.closest('[data-widget]');if(target&&target!==card&&grid.contains(target)){const from=widgets.indexOf(item),to=widgets.findIndex(w=>w.id===target.dataset.widget);widgets.splice(from,1);widgets.splice(to,0,item);for(const w of widgets)grid.append(cards.get(w.id));changed();}}else{arrange.querySelector('[data-size=width]').value=String(item.width);arrange.querySelector('[data-size=height]').value=String(item.height);changed();}}
|
||||||
|
function cancel(event){if(!action||event.pointerId!==action.pointer)return;if(action.mode==='resize'){item.width=action.width;item.height=action.height;applySize(item,card);}action=null;card._gesture?.abort();card.classList.remove('widget-moving');}
|
||||||
|
const resize=button('◢',t('Drag to resize; size controls are also available','ドラッグでサイズ変更。幅・高さの選択欄でも変更できます'),()=>{});resize.className='widget-resize';
|
||||||
|
for(const [handle,mode] of [[drag,'move'],[resize,'resize']])handle.onpointerdown=e=>start(e,mode);
|
||||||
|
card.append(resize);
|
||||||
|
}
|
||||||
|
const body=el('div',undefined,'widget-body');body.setAttribute('role','region');body.setAttribute('aria-labelledby',heading.id);body.tabIndex=0;
|
||||||
|
card.append(header,arrange,body);grid.append(card);cards.set(item.id,card);loadWidget(item,card);
|
||||||
|
}
|
||||||
|
if(!widgets.length)grid.append(el('p',t('Add a widget to get started.','ウィジェットを追加してください。')));
|
||||||
|
updateControls();
|
||||||
|
}
|
||||||
|
function loadWidget(item,card){
|
||||||
|
card._controller?.abort();const controller=new AbortController();card._controller=controller;
|
||||||
|
const body=card.querySelector('.widget-body');body.replaceChildren(el('p',t('Loading…','読み込み中…')));
|
||||||
|
schedule(async()=>{
|
||||||
|
if(controller.signal.aborted||!card.isConnected)return;
|
||||||
|
const signal=AbortSignal.any([controller.signal,AbortSignal.timeout(15000)]);
|
||||||
|
try{
|
||||||
|
if(item.id==='activity'){
|
||||||
|
body.replaceChildren();const report=el('section');report.id='task-productivity';report.dataset.view='report';const h=el('h3');h.className='visually-hidden';const message=el('p');message.id='productivity-status';message.role='status';const content=el('div');content.id='productivity-content';report.append(h,message,content);body.append(report);await window.PagesWikiProductivityMount(report,controller.signal);return;
|
||||||
|
}
|
||||||
|
if(item.id==='progress'){
|
||||||
|
const data=await request(api+'progress',{signal});if(controller.signal.aborted)return;body.replaceChildren();const percentage=data.total?Math.round(data.done*100/data.total):null;
|
||||||
|
const ring=el('div',percentage===null?'—':percentage+'%','dashboard-progress');ring.style.setProperty('--progress',(percentage||0)+'%');
|
||||||
|
body.append(ring,el('p',data.done+' / '+data.total),el('small',t('Completed / tasks planned for today. Cancelled and archived tasks are excluded.','今日に計画したタスクの完了数/総数。取りやめ・アーカイブは除きます。')));return;
|
||||||
|
}
|
||||||
|
if(item.id==='schedule'){
|
||||||
|
if(root.dataset.calendar!=='true'){body.replaceChildren(el('p',t('Calendar extension is disabled.','カレンダー拡張は無効です。')));return;}
|
||||||
|
const data=await request(calendarAPI+'upcoming?period=day',{signal});if(controller.signal.aborted)return;
|
||||||
|
const list=el('ul',undefined,'dashboard-list'),format=new Intl.DateTimeFormat(ja?'ja-JP':'en-GB',{hour:'2-digit',minute:'2-digit',timeZone:zone});
|
||||||
|
for(const event of data.events){const row=el('li'),a=link(event.summary||t('(Untitled)','(無題)'),event.href);row.append(el('time',event.all_day?t('All day','終日'):format.format(new Date(event.start))),a);list.append(row);}
|
||||||
|
body.replaceChildren(list);if(!data.events.length)body.append(el('p',t('No events today.','本日の予定はありません。')));body.append(link(t('Open calendar →','カレンダーで確認 →'),'/v/plan'));return;
|
||||||
|
}
|
||||||
|
const tabbar=el('div',undefined,'widget-tabs');tabbar.setAttribute('role','tablist');tabbar.ariaLabel=names.tasks;
|
||||||
|
const list=el('div');list.id='widget-panel-'+item.id;list.setAttribute('role','tabpanel');list.tabIndex=0;
|
||||||
|
const panel=el('div');panel.append(list);body.replaceChildren();if(item.id==='tasks')body.append(tabbar);body.append(panel);
|
||||||
|
let sequence=0,tabController;
|
||||||
|
async function tasks(tab,append=false,cursor=''){
|
||||||
|
const ticket=++sequence;tabController?.abort();tabController=new AbortController();
|
||||||
|
const q=new URLSearchParams({kind:'task',view:tab,limit:'20'});
|
||||||
|
if(item.id==='tomorrow'){const date=new Date(today+'T12:00:00Z');date.setUTCDate(date.getUTCDate()+1);q.set('date',date.toISOString().slice(0,10));}
|
||||||
|
if(cursor)q.set('before',cursor);
|
||||||
|
list.setAttribute('aria-busy','true');
|
||||||
|
const notice=el('p',t('Loading…','読み込み中…'));if(!append)list.replaceChildren(notice);
|
||||||
|
try{
|
||||||
|
const data=await request(api+'items?'+q,{signal:AbortSignal.any([controller.signal,tabController.signal,AbortSignal.timeout(15000)])});if(ticket!==sequence||controller.signal.aborted)return;
|
||||||
|
if(!append)list.replaceChildren();panel.querySelector('[data-more]')?.remove();
|
||||||
|
const ul=el('ul',undefined,'dashboard-list');
|
||||||
|
for(const task of data.items){const row=el('li');row.dataset.task=task.uuid;
|
||||||
|
const title=link(task.title,'/v/plan/task/'+encodeURIComponent(task.uuid));title.title=task.title;
|
||||||
|
row.append(el('span',task.status==='done'?'✓':task.status==='cancelled'?'−':task.status==='doing'?'◐':'○'),title);
|
||||||
|
if(task.due_on)row.append(el('time',task.due_on));ul.append(row);
|
||||||
|
}
|
||||||
|
list.append(ul);if(!data.items.length&&!append)list.append(el('p',t('No matching tasks.','該当するタスクはありません。')));
|
||||||
|
if(data.next){const more=button(t('Load more','続きを表示'),t('Load more','続きを表示'),()=>{more.disabled=true;tasks(tab,true,data.next).finally(()=>{more.disabled=false;});});more.dataset.more='true';panel.append(more);}
|
||||||
|
}catch(e){if(e.name!=='AbortError'&&ticket===sequence){if(!append)list.replaceChildren();list.append(el('p',e.message));}}finally{if(ticket===sequence)list.setAttribute('aria-busy','false');}
|
||||||
|
}
|
||||||
|
if(item.id==='tasks'){
|
||||||
|
for(const [key,label] of Object.entries(tabs)){const b=button(label,label,()=>{if(saving||item.tab===key)return;item.tab=key;selectTabs();if(writable)changed();tasks(key);});b.dataset.tab=key;b.id='dashboard-tab-'+key;b.setAttribute('role','tab');b.setAttribute('aria-controls',list.id);tabbar.append(b);}
|
||||||
|
function selectTabs(){for(const b of tabbar.children){b.setAttribute('aria-selected',String(b.dataset.tab===item.tab));b.tabIndex=b.dataset.tab===item.tab?0:-1;}list.setAttribute('aria-labelledby','dashboard-tab-'+item.tab);}
|
||||||
|
tabbar.onkeydown=event=>{const keys=Object.keys(tabs),index=keys.indexOf(item.tab);let next;if(event.key==='ArrowRight')next=(index+1)%keys.length;else if(event.key==='ArrowLeft')next=(index+keys.length-1)%keys.length;else if(event.key==='Home')next=0;else if(event.key==='End')next=keys.length-1;else return;event.preventDefault();tabbar.children[next].click();tabbar.children[next].focus();};selectTabs();
|
||||||
|
}
|
||||||
|
await tasks(item.id==='tasks'?item.tab:item.id==='tomorrow'?'day':'today');
|
||||||
|
}catch(e){if(!controller.signal.aborted)body.replaceChildren(el('p',e.message),button('↻',t('Retry','再試行'),()=>loadWidget(item,card)));}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
updateControls();
|
||||||
|
function initialize(){status.textContent=t('Loading…','読み込み中…');request(api+'dashboard',{signal:AbortSignal.timeout(15000)}).then(data=>{version=data.version;widgets=data.widgets;loaded=true;status.textContent='';render();if(location.hash==='#activity')requestAnimationFrame(()=>document.getElementById('activity')?.scrollIntoView({block:'start'}));}).catch(e=>{status.replaceChildren(document.createTextNode(e.message+' '),button('↻',t('Retry','再試行'),initialize));});}
|
||||||
|
initialize();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
(() => {
|
||||||
|
'use strict';
|
||||||
|
const root=document.getElementById('organizer-calendar-defaults');if(!root)return;
|
||||||
|
const ja=document.documentElement.lang.startsWith('ja'),t=(en,jp)=>ja?jp:en,api='/_/api/v1/extension/organizer.calendar/';
|
||||||
|
const status=root.querySelector('[role=status]'),content=root.querySelector('[data-calendar-defaults]');
|
||||||
|
const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
|
||||||
|
async function request(path,options={}){const r=await fetch(api+path,{credentials:'same-origin',cache:'no-store',signal:AbortSignal.timeout(15000),...options,headers:{'Content-Type':'application/json'}});if(!r.ok||r.redirected)throw Error(t('Unable to save or load settings. Check your session and try again.','取得・保存できません。ログイン状態を確認して再度お試しください。'));return r.json();}
|
||||||
|
request('calendars').then(data=>{
|
||||||
|
const form=el('form'),list=el('div');list.className='organizer-calendar-options';
|
||||||
|
for(const calendar of data.calendars){const label=el('label'),input=el('input');input.type='checkbox';input.name='calendar';input.value=calendar.id;input.checked=data.defaults.includes(calendar.id);input.disabled=root.dataset.writable!=='true';label.append(input,document.createTextNode(calendar.name));list.append(label);}
|
||||||
|
const help=el('p',t('Used for calendar navigation and upcoming events, including the dashboard. If none are selected, the first available calendar is used.','カレンダー表示と直近の予定、ダッシュボードに使用します。未選択なら最初の利用可能なカレンダーを使用します。'));
|
||||||
|
const save=el('button',t('Save','保存'));save.type='submit';save.disabled=root.dataset.writable!=='true';form.append(list,help,save);content.append(form);
|
||||||
|
form.onsubmit=async event=>{event.preventDefault();const calendars=[...form.querySelectorAll('input:checked')].map(n=>n.value);if(calendars.length>32){status.textContent=t('Select at most 32 calendars.','32個以内で選択してください。');return;}save.disabled=true;try{await request('preferences',{method:'PUT',body:JSON.stringify({calendars})});status.textContent=t('Saved','保存しました');}catch(e){status.textContent=e.message;}finally{save.disabled=false;}};
|
||||||
|
}).catch(e=>{status.textContent=e.message;});
|
||||||
|
})();
|
||||||
@@ -1,28 +1,31 @@
|
|||||||
(() => {
|
(() => {
|
||||||
'use strict';
|
'use strict';
|
||||||
const app = document.getElementById('tasks-app') || document.getElementById('calendar-app');
|
const app = document.getElementById('tasks-app') || document.getElementById('calendar-app') || document.getElementById('contacts-app');
|
||||||
if (!app) return;
|
if (!app) return;
|
||||||
const calendar = app.id === 'calendar-app';
|
const calendar = app.id === 'calendar-app';
|
||||||
|
const contacts = app.id === 'contacts-app';
|
||||||
if (calendar && !app.dataset.actor) return;
|
if (calendar && !app.dataset.actor) return;
|
||||||
const ja = document.documentElement.lang.startsWith('ja');
|
const ja = document.documentElement.lang.startsWith('ja');
|
||||||
const t = (en, jp) => ja ? jp : en;
|
const t = (en, jp) => ja ? jp : en;
|
||||||
const api = '/_/api/v1/caldav-credentials';
|
const api = '/_/api/v1/caldav-credentials';
|
||||||
const el = (tag, text) => { const n = document.createElement(tag); if (text !== undefined) n.textContent = text; return n; };
|
const el = (tag, text) => { const n = document.createElement(tag); if (text !== undefined) n.textContent = text; return n; };
|
||||||
const button = el('button', '⇄'); button.type = 'button'; button.id = 'tasks-dav-open';
|
const button = el('button', '⇄'); button.type = 'button'; button.id = 'tasks-dav-open';
|
||||||
button.title = button.ariaLabel = t('CalDAV / CLI access', 'CalDAV / CLI連携');
|
button.title = button.ariaLabel = contacts ? t('CardDAV access', 'CardDAV連携') : t('CalDAV / CLI access', 'CalDAV / CLI連携');
|
||||||
app.querySelector(calendar ? '.calendar-toolbar' : '.tasks-toolbar .tasks-actions').append(button);
|
app.querySelector(contacts ? '#contacts-controls' : calendar ? '.calendar-toolbar' : '.tasks-toolbar .tasks-actions').append(button);
|
||||||
const dialog = el('dialog'); dialog.id = 'tasks-dav-dialog'; dialog.setAttribute('aria-labelledby', 'tasks-dav-title');
|
const dialog = el('dialog'); dialog.id = 'tasks-dav-dialog'; dialog.setAttribute('aria-labelledby', 'tasks-dav-title');
|
||||||
const header = el('header'); header.className = 'tasks-toolbar';
|
const header = el('header'); header.className = 'tasks-toolbar';
|
||||||
const title = el('h2', t('CalDAV access', '予定・タスクのCalDAV連携')); title.id = 'tasks-dav-title';
|
const title = el('h2', t('CalDAV access', '予定・タスクのCalDAV連携')); title.id = 'tasks-dav-title';
|
||||||
|
if (contacts) title.textContent = t('CardDAV access', '連絡先のCardDAV連携');
|
||||||
const close = el('button', '×'); close.type = 'button'; close.ariaLabel = t('Close', '閉じる'); header.append(title, close);
|
const close = el('button', '×'); close.type = 'button'; close.ariaLabel = t('Close', '閉じる'); header.append(title, close);
|
||||||
const help = el('p', t('Choose calendars, tasks, or both. Calendar permissions still apply. Existing task passwords remain task-only. Wiki access is not granted. Use HTTPS.', '予定・タスクの対象を選んで発行します。予定には既存のカレンダー権限が適用されます。従来のパスワードはタスク専用のままです。Wikiへのアクセス権は付与されません。HTTPSで接続してください。'));
|
const help = el('p', t('Choose calendars, tasks, or both. Calendar permissions still apply. Existing task passwords remain task-only. Wiki access is not granted. Use HTTPS.', '予定・タスクの対象を選んで発行します。予定には既存のカレンダー権限が適用されます。従来のパスワードはタスク専用のままです。Wikiへのアクセス権は付与されません。HTTPSで接続してください。'));
|
||||||
const url = el('input'); url.readOnly = true; url.value = location.origin + '/_/api/v1/caldav/'; url.ariaLabel = 'CalDAV URL'; url.onclick = () => url.select();
|
const url = el('input'); url.readOnly = true; url.value = location.origin + '/_/api/v1/caldav/'; url.ariaLabel = 'CalDAV URL'; url.onclick = () => url.select();
|
||||||
|
if (contacts) { url.value = location.origin + '/_/api/v1/carddav/'; url.ariaLabel = 'CardDAV URL'; help.textContent = t('Private address book access only. Issue a separate password for each device. Existing CalDAV passwords cannot access contacts. Use HTTPS.', '個人アドレス帳専用です。端末ごとにパスワードを発行してください。既存のCalDAVパスワードでは連絡先へアクセスできません。HTTPSで接続してください。'); }
|
||||||
const form = el('form'); const label = el('input'); label.required = true; label.maxLength = 100; label.placeholder = t('Device / client name', '端末・クライアント名'); label.ariaLabel = label.placeholder;
|
const form = el('form'); const label = el('input'); label.required = true; label.maxLength = 100; label.placeholder = t('Device / client name', '端末・クライアント名'); label.ariaLabel = label.placeholder;
|
||||||
const access = el('select'); access.ariaLabel = t('Access', 'アクセス権限');
|
const access = el('select'); access.ariaLabel = t('Access', 'アクセス権限');
|
||||||
for (const [value, text] of [['read', t('Read only', '読み取り専用')], ['write', t('Read / write', '読み書き')]]) { const option = el('option', text); option.value = value; if (value === 'write' && !calendar && app.dataset.writable !== 'true') option.disabled = true; access.append(option); }
|
for (const [value, text] of [['read', t('Read only', '読み取り専用')], ['write', t('Read / write', '読み書き')]]) { const option = el('option', text); option.value = value; if (value === 'write' && !calendar && app.dataset.writable !== 'true') option.disabled = true; access.append(option); }
|
||||||
const scope = el('select'); scope.ariaLabel = t('Scope', '対象');
|
const scope = el('select'); scope.ariaLabel = t('Scope', '対象');
|
||||||
const scopes = { tasks: t('Tasks only', 'タスクのみ'), calendar: t('Calendars only', '予定のみ'), all: t('Calendars and tasks', '予定とタスク') };
|
const scopes = { tasks: t('Tasks only', 'タスクのみ'), calendar: t('Calendars only', '予定のみ'), all: t('Calendars and tasks', '予定とタスク'), contacts: t('Contacts only', '連絡先のみ') };
|
||||||
for (const [value, text] of Object.entries(scopes)) { const option = el('option', text); option.value = value; option.selected = value === (calendar ? 'calendar' : 'tasks'); scope.append(option); }
|
for (const [value, text] of Object.entries(scopes)) { if (contacts && value !== 'contacts') continue; const option = el('option', text); option.value = value; option.selected = value === (contacts ? 'contacts' : calendar ? 'calendar' : 'tasks'); scope.append(option); }
|
||||||
const days = el('select'); days.ariaLabel = t('Validity', '有効期間');
|
const days = el('select'); days.ariaLabel = t('Validity', '有効期間');
|
||||||
for (const n of [30, 90, 365]) { const option = el('option', n + t(' days', '日間')); option.value = String(n); option.selected = n === 90; days.append(option); }
|
for (const n of [30, 90, 365]) { const option = el('option', n + t(' days', '日間')); option.value = String(n); option.selected = n === 90; days.append(option); }
|
||||||
const issue = el('button', t('Issue password', 'パスワードを発行')); issue.type = 'submit'; form.append(label, scope, access, days, issue);
|
const issue = el('button', t('Issue password', 'パスワードを発行')); issue.type = 'submit'; form.append(label, scope, access, days, issue);
|
||||||
@@ -31,10 +34,13 @@
|
|||||||
compatLabel.append(compat, document.createTextNode(t('OneTask compatibility (calendar-access advertisement)', 'OneTask互換モード(calendar-accessを宣言)')));
|
compatLabel.append(compat, document.createTextNode(t('OneTask compatibility (calendar-access advertisement)', 'OneTask互換モード(calendar-accessを宣言)')));
|
||||||
const compatHelp = el('p', t('Opt in only for clients that require calendar-access. This is a limited implementation, not full RFC compliance. Task dates are date-only; recurrence, timezone definitions and alarms remain unsupported. Enabling this does not grant additional access.', 'calendar-accessを要求するクライアント向けの互換設定です。完全なRFC準拠ではありません。タスクの日付は日単位のみで、繰り返し・タイムゾーン定義・アラームは引き続き未対応です。アクセス権限は増えません。'));
|
const compatHelp = el('p', t('Opt in only for clients that require calendar-access. This is a limited implementation, not full RFC compliance. Task dates are date-only; recurrence, timezone definitions and alarms remain unsupported. Enabling this does not grant additional access.', 'calendar-accessを要求するクライアント向けの互換設定です。完全なRFC準拠ではありません。タスクの日付は日単位のみで、繰り返し・タイムゾーン定義・アラームは引き続き未対応です。アクセス権限は増えません。'));
|
||||||
compatHelp.id = 'tasks-dav-compat-help'; compatHelp.className = 'dav-compat-help'; form.append(compatLabel, compatHelp);
|
compatHelp.id = 'tasks-dav-compat-help'; compatHelp.className = 'dav-compat-help'; form.append(compatLabel, compatHelp);
|
||||||
|
const updateScope = () => { const card = scope.value === 'contacts'; compatLabel.hidden = compatHelp.hidden = card; if (card) compat.checked = false; url.value = location.origin + (card ? '/_/api/v1/carddav/' : '/_/api/v1/caldav/'); };
|
||||||
|
scope.onchange = updateScope; updateScope();
|
||||||
const secret = el('section'); secret.hidden = true;
|
const secret = el('section'); secret.hidden = true;
|
||||||
const status = el('p'); status.role = 'status';
|
const status = el('p'); status.role = 'status';
|
||||||
const tableWrap = el('div'); tableWrap.className = 'task-dav-table'; const table = el('table'); tableWrap.append(table);
|
const tableWrap = el('div'); tableWrap.className = 'task-dav-table'; const table = el('table'); tableWrap.append(table);
|
||||||
const note = el('p', t('Clients: chroncal, vdirsyncer + Todoman. Task start/due accept dates only. Recurring events and alarms cannot be created via DAV. Calendar events are deleted; tasks are archived.', '連携例:chroncal、vdirsyncer + Todoman。タスクの開始・期限は日付のみ対応。DAV経由の繰り返し予定・アラームの新規作成は未対応です。削除操作では予定は削除、タスクはアーカイブされます。'));
|
const note = el('p', t('Clients: chroncal, vdirsyncer + Todoman. Task start/due accept dates only. Recurring events and alarms cannot be created via DAV. Calendar events are deleted; tasks are archived.', '連携例:chroncal、vdirsyncer + Todoman。タスクの開始・期限は日付のみ対応。DAV経由の繰り返し予定・アラームの新規作成は未対応です。削除操作では予定は削除、タスクはアーカイブされます。'));
|
||||||
|
if (contacts) note.textContent = t('Use the credential ID as the username, not your account name. Deletes go to trash. Changes use ETags; stale edits are rejected. Shared books and remote-source connectors are not available.', 'ユーザー名にはアカウント名ではなく認証情報IDを使います。削除した連絡先は削除済み一覧から復元できます。ETagで競合を検知し、古い編集内容は上書きしません。共有アドレス帳・外部サービス取り込みは未対応です。');
|
||||||
dialog.append(header, help, url, form, secret, status, tableWrap, note); app.append(dialog);
|
dialog.append(header, help, url, form, secret, status, tableWrap, note); app.append(dialog);
|
||||||
let busy = false, generation = 0;
|
let busy = false, generation = 0;
|
||||||
async function request(path = '', options = {}) {
|
async function request(path = '', options = {}) {
|
||||||
@@ -48,6 +54,7 @@
|
|||||||
table.replaceChildren(); const head = el('tr');
|
table.replaceChildren(); const head = el('tr');
|
||||||
[t('Name', '名称'), t('Scope', '対象'), t('Access', '権限'), t('Expires', '有効期限'), ''].forEach(v => head.append(el('th', v))); const thead = el('thead'); thead.append(head); table.append(thead); const body = el('tbody'); table.append(body);
|
[t('Name', '名称'), t('Scope', '対象'), t('Access', '権限'), t('Expires', '有効期限'), ''].forEach(v => head.append(el('th', v))); const thead = el('thead'); thead.append(head); table.append(thead); const body = el('tbody'); table.append(body);
|
||||||
for (const c of data.items) {
|
for (const c of data.items) {
|
||||||
|
if (contacts && c.scope !== 'contacts') continue;
|
||||||
const row = el('tr'); row.append(el('td', c.label + (c.calendar_access_compat ? t(' · OneTask compatibility', ' · OneTask互換') : '')), el('td', scopes[c.scope || 'tasks']), el('td', c.write ? t('Read / write', '読み書き') : t('Read only', '読み取り専用')), el('td', new Date(c.expires_ms).toLocaleString()));
|
const row = el('tr'); row.append(el('td', c.label + (c.calendar_access_compat ? t(' · OneTask compatibility', ' · OneTask互換') : '')), el('td', scopes[c.scope || 'tasks']), el('td', c.write ? t('Read / write', '読み書き') : t('Read only', '読み取り専用')), el('td', new Date(c.expires_ms).toLocaleString()));
|
||||||
const cell = el('td'), revoke = el('button', t('Revoke', '失効')); revoke.type = 'button';
|
const cell = el('td'), revoke = el('button', t('Revoke', '失効')); revoke.type = 'button';
|
||||||
revoke.onclick = async () => { if (busy || !confirm(t('Revoke this password?', 'このパスワードを失効させますか?'))) return; busy = true; revoke.disabled = true; status.textContent = ''; try { await request('/' + encodeURIComponent(c.id), { method: 'DELETE' }); await load(); } catch (e) { status.textContent = e.message; } finally { busy = false; revoke.disabled = false; } };
|
revoke.onclick = async () => { if (busy || !confirm(t('Revoke this password?', 'このパスワードを失効させますか?'))) return; busy = true; revoke.disabled = true; status.textContent = ''; try { await request('/' + encodeURIComponent(c.id), { method: 'DELETE' }); await load(); } catch (e) { status.textContent = e.message; } finally { busy = false; revoke.disabled = false; } };
|
||||||
@@ -61,6 +68,7 @@
|
|||||||
e.preventDefault(); if (busy) return; busy = true; issue.disabled = true; status.textContent = '';
|
e.preventDefault(); if (busy) return; busy = true; issue.disabled = true; status.textContent = '';
|
||||||
try {
|
try {
|
||||||
const data = await request('', { method: 'POST', body: JSON.stringify({ label: label.value, scope: scope.value, write: access.value === 'write', days: Number(days.value), calendar_access_compat: compat.checked }) });
|
const data = await request('', { method: 'POST', body: JSON.stringify({ label: label.value, scope: scope.value, write: access.value === 'write', days: Number(days.value), calendar_access_compat: compat.checked }) });
|
||||||
|
url.value = location.origin + data.url;
|
||||||
secret.replaceChildren(el('p', t('Shown only once. Save both values in your password manager before closing.', 'この画面を閉じると再表示できません。両方をパスワードマネージャーなどに保存してください。')));
|
secret.replaceChildren(el('p', t('Shown only once. Save both values in your password manager before closing.', 'この画面を閉じると再表示できません。両方をパスワードマネージャーなどに保存してください。')));
|
||||||
for (const [name, value] of [[t('Username (credential ID)', 'ユーザー名(認証情報ID)'), data.username], [t('Password', 'パスワード'), data.password]]) { const wrapper = el('label', name), field = el('input'); field.readOnly = true; field.value = value; field.autocomplete = 'off'; field.spellcheck = false; field.onclick = () => field.select(); wrapper.append(field); secret.append(wrapper); }
|
for (const [name, value] of [[t('Username (credential ID)', 'ユーザー名(認証情報ID)'), data.username], [t('Password', 'パスワード'), data.password]]) { const wrapper = el('label', name), field = el('input'); field.readOnly = true; field.value = value; field.autocomplete = 'off'; field.spellcheck = false; field.onclick = () => field.select(); wrapper.append(field); secret.append(wrapper); }
|
||||||
secret.hidden = false; label.value = ''; await load();
|
secret.hidden = false; label.value = ''; await load();
|
||||||
|
|||||||
@@ -25,6 +25,7 @@
|
|||||||
function button(label,icon,fn){const b=el('button',icon);b.type='button';b.title=b.ariaLabel=label;b.addEventListener('click',fn);actions.append(b);return b;}
|
function button(label,icon,fn){const b=el('button',icon);b.type='button';b.title=b.ariaLabel=label;b.addEventListener('click',fn);actions.append(b);return b;}
|
||||||
const detail=el('a','⋯');detail.title=detail.ariaLabel=t('Details','詳細');detail.href='/v/plan/task/'+item.uuid;detail.dataset.action='detail';if(options.onDetail)detail.addEventListener('click',e=>{if(e.ctrlKey||e.metaKey||e.shiftKey||e.button)return;e.preventDefault();if(blocked())return;options.onDetail(item.uuid);});actions.append(detail);
|
const detail=el('a','⋯');detail.title=detail.ariaLabel=t('Details','詳細');detail.href='/v/plan/task/'+item.uuid;detail.dataset.action='detail';if(options.onDetail)detail.addEventListener('click',e=>{if(e.ctrlKey||e.metaKey||e.shiftKey||e.button)return;e.preventDefault();if(blocked())return;options.onDetail(item.uuid);});actions.append(detail);
|
||||||
function blocked(){if(saving||dirtyRows.has(row)){message(t('Save or reload this row first.','先にこの行の変更を保存するか再読込してください。'));return true;}return false;}
|
function blocked(){if(saving||dirtyRows.has(row)){message(t('Save or reload this row first.','先にこの行の変更を保存するか再読込してください。'));return true;}return false;}
|
||||||
|
if(writable&&!item.archived)button(t('Start work recording','作業時間を記録開始'),'▶',()=>{if(!blocked())document.getElementById('tasks-app')?.dispatchEvent(new CustomEvent('task-work',{detail:item}));}).dataset.action='work';
|
||||||
button(t('Calendar time blocks','カレンダーへ時間枠を追加'),'▦',async()=>{if(blocked())return;try{const d=await request(api+'/'+item.uuid);document.getElementById('tasks-app')?.dispatchEvent(new CustomEvent('task-plan',{detail:d.item}));}catch(e){message(e.message);}}).dataset.action='plan';
|
button(t('Calendar time blocks','カレンダーへ時間枠を追加'),'▦',async()=>{if(blocked())return;try{const d=await request(api+'/'+item.uuid);document.getElementById('tasks-app')?.dispatchEvent(new CustomEvent('task-plan',{detail:d.item}));}catch(e){message(e.message);}}).dataset.action='plan';
|
||||||
const reset=button(t('Reload row (discard edits)','行を再読込(編集を破棄)'),'↻',async()=>{if(saving)return;if(dirtyRows.has(row)&&!confirm(t('Discard changes in this row?','この行の変更を破棄しますか?')))return;try{const d=await request(api+'/'+item.uuid);item=d.item;draft={};dirtyRows.delete(row);Object.keys(inputs).forEach(k=>inputs[k].value=item[k]||'');paint();message('','idle');}catch(e){message(e.message);}});reset.dataset.action='reload';
|
const reset=button(t('Reload row (discard edits)','行を再読込(編集を破棄)'),'↻',async()=>{if(saving)return;if(dirtyRows.has(row)&&!confirm(t('Discard changes in this row?','この行の変更を破棄しますか?')))return;try{const d=await request(api+'/'+item.uuid);item=d.item;draft={};dirtyRows.delete(row);Object.keys(inputs).forEach(k=>inputs[k].value=item[k]||'');paint();message('','idle');}catch(e){message(e.message);}});reset.dataset.action='reload';
|
||||||
function buttonMore(cursor){const more=el('button',t('More subtasks','続きのサブタスク'));more.type='button';more.className='task-children-more';more.addEventListener('click',async()=>{if(dirtyRows.size)return;more.disabled=true;try{const d=await request(api+'?'+new URLSearchParams({view:'family',parent:item.uuid,limit:100,before:cursor}));if(dirtyRows.size)return;d.items.forEach(c=>more.before(create(c,{...options,initialChildren:[],context:false,nested:true})));if(d.next)more.replaceWith(buttonMore(d.next));else more.remove();}catch(e){message(e.message);}finally{more.disabled=false;}});return more;}
|
function buttonMore(cursor){const more=el('button',t('More subtasks','続きのサブタスク'));more.type='button';more.className='task-children-more';more.addEventListener('click',async()=>{if(dirtyRows.size)return;more.disabled=true;try{const d=await request(api+'?'+new URLSearchParams({view:'family',parent:item.uuid,limit:100,before:cursor}));if(dirtyRows.size)return;d.items.forEach(c=>more.before(create(c,{...options,initialChildren:[],context:false,nested:true})));if(d.next)more.replaceWith(buttonMore(d.next));else more.remove();}catch(e){message(e.message);}finally{more.disabled=false;}});return more;}
|
||||||
@@ -47,7 +48,7 @@
|
|||||||
if(options.initialChildren?.length){loadAll=button(t('Load all subtasks, including other dates','別の日付も含めてすべてのサブタスクを表示'),'⇊',loadChildren);loadAll.dataset.action='children-all';}
|
if(options.initialChildren?.length){loadAll=button(t('Load all subtasks, including other dates','別の日付も含めてすべてのサブタスクを表示'),'⇊',loadChildren);loadAll.dataset.action='children-all';}
|
||||||
if(writable&&!item.archived){const add=el('form',undefined,'task-child-capture'),input=el('input'),submit=el('button','+');input.required=true;input.maxLength=300;input.placeholder=input.ariaLabel=t('New subtask','サブタスクを追加');submit.type='submit';submit.title=t('Add subtask','サブタスクを追加');add.append(input,submit);add.hidden=true;row.append(add);button(t('Add subtask','サブタスクを追加'),'+',()=>{if(blocked())return;add.hidden=!add.hidden;if(!add.hidden)input.focus();}).dataset.action='add-child';
|
if(writable&&!item.archived){const add=el('form',undefined,'task-child-capture'),input=el('input'),submit=el('button','+');input.required=true;input.maxLength=300;input.placeholder=input.ariaLabel=t('New subtask','サブタスクを追加');submit.type='submit';submit.title=t('Add subtask','サブタスクを追加');add.append(input,submit);add.hidden=true;row.append(add);button(t('Add subtask','サブタスクを追加'),'+',()=>{if(blocked())return;add.hidden=!add.hidden;if(!add.hidden)input.focus();}).dataset.action='add-child';
|
||||||
input.addEventListener('input',()=>{if(input.value)dirtyRows.add(add);else dirtyRows.delete(add);});
|
input.addEventListener('input',()=>{if(input.value)dirtyRows.add(add);else dirtyRows.delete(add);});
|
||||||
add.addEventListener('submit',async e=>{e.preventDefault();if(submit.disabled||blocked())return;const title=input.value.trim();if(!title)return;submit.disabled=input.disabled=true;if(!childDraft||childDraft.title!==title)childDraft={uuid:crypto.randomUUID(),kind:'task',title,notes:'',parent_uuid:item.uuid,project_uuid:item.project_uuid,status:'todo',bucket:item.bucket,priority:item.priority,estimate_minutes:0,archived:false,version:0};try{const d=await request(api,{method:'POST',body:JSON.stringify(childDraft)});childDraft=null;childRequest++;input.value='';dirtyRows.delete(add);showChildren(true);children.querySelector('small')?.remove();children.append(create(d.item,{...options,initialChildren:[],context:false,nested:true}));document.getElementById('tasks-app')?.dispatchEvent(new Event('task-today-refresh'));}catch(err){message(err.message);}finally{submit.disabled=input.disabled=false;input.focus();}});
|
add.addEventListener('submit',async e=>{e.preventDefault();if(submit.disabled||blocked())return;const title=input.value.trim();if(!title)return;submit.disabled=input.disabled=true;try{if(!childDraft||childDraft.title!==title){const preferences=await request('/_/api/v1/extension/organizer.tasks/preferences');childDraft={...preferences.defaults,uuid:crypto.randomUUID(),kind:'task',title,notes:'',parent_uuid:item.uuid,project_uuid:item.project_uuid,status:'todo',bucket:item.bucket,priority:item.priority,archived:false,version:0};}const d=await request(api,{method:'POST',body:JSON.stringify(childDraft)});childDraft=null;childRequest++;input.value='';dirtyRows.delete(add);showChildren(true);children.querySelector('small')?.remove();children.append(create(d.item,{...options,initialChildren:[],context:false,nested:true}));document.getElementById('tasks-app')?.dispatchEvent(new Event('task-today-refresh'));}catch(err){message(err.message);}finally{submit.disabled=input.disabled=false;input.focus();}});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(options.context){row.dataset.context='true';const badge=el('small',t('Parent','親'),'task-context-badge');badge.title=t('Context only: this parent is outside the current filter.','親子関係を示すために表示しています。親自体は現在の条件の対象外です。');inputs.title.parentElement.append(badge);}
|
if(options.context){row.dataset.context='true';const badge=el('small',t('Parent','親'),'task-context-badge');badge.title=t('Context only: this parent is outside the current filter.','親子関係を示すために表示しています。親自体は現在の条件の対象外です。');inputs.title.parentElement.append(badge);}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
(() => {
|
||||||
|
'use strict';
|
||||||
|
function mount(root,signal){if(!root||root.dataset.mounted)return;root.dataset.mounted='true';
|
||||||
|
const ja=document.documentElement.lang.startsWith('ja'), api='/_/api/v1/extension/organizer.tasks/';
|
||||||
|
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','通知の既定時刻']});
|
||||||
|
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;}
|
||||||
|
const error=e=>{status.textContent=e.message||t('error');};
|
||||||
|
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(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;
|
||||||
|
if(key==='project_uuid'){const empty=el('option',t('none'));empty.value='';input.append(empty);for(const item of projects.items){const option=el('option',item.title);option.value=item.uuid;input.append(option);}if(p[key]&&!projects.items.some(x=>x.uuid===p[key])){const current=el('option',p[key]);current.value=p[key];input.append(current);}}
|
||||||
|
else if(['digest_enabled','notify_due','notify_planned'].includes(key)){input.type='checkbox';input.checked=!!p[key];input.setAttribute('role','switch');}
|
||||||
|
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==='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);
|
||||||
|
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;}
|
||||||
|
async function report(){
|
||||||
|
const controls=el('form');controls.className='productivity-controls';const from=el('input'),to=el('input');from.type=to.type='date';from.required=to.required=true;from.ariaLabel=ja?'開始日':'From';to.ariaLabel=ja?'終了日(含まない)':'To (exclusive)';const refresh=el('button','↻ '+t('refresh'));controls.append(from,to,refresh);
|
||||||
|
const results=el('section');content.replaceChildren(controls,results);let generation=0;
|
||||||
|
async function load(){const ticket=++generation;refresh.disabled=true;try{const query=new URLSearchParams();if(from.value)query.set('from',from.value);if(to.value)query.set('to',to.value);const d=await request('report?'+query);if(ticket!==generation)return;status.textContent=d.partial?t('partial'):d.timezone;
|
||||||
|
if(!from.value&&d.days.length){from.value=d.days[0].date;const end=new Date(d.days.at(-1).date+'T12:00:00Z');end.setUTCDate(end.getUTCDate()+1);to.value=end.toISOString().slice(0,10);}
|
||||||
|
const stats=el('div');stats.className='productivity-stats';for(const [label,key,divisor] of [['completed','completed',1],['points','points',1],['work','work_ms',3600000],['focus','focus_ms',3600000]]){const card=el('div',t(label));card.className='productivity-stat';const sum=d.days.reduce((total,day)=>total+day[key],0)/divisor;card.append(el('strong',divisor===1?String(sum):sum.toFixed(2)));stats.append(card);}
|
||||||
|
const scroll=el('div');scroll.className='productivity-heatmap-scroll';const grid=el('div');grid.className='productivity-heatmap';grid.ariaLabel=t('report');const detail=el('section');detail.append(taskTable(d));let detailSequence=0;
|
||||||
|
if(d.days.length){const weekday=new Date(d.days[0].date+'T12:00:00Z').getUTCDay();for(let i=0;i<weekday;i++)grid.append(el('span'));}
|
||||||
|
for(const day of d.days){const cell=el('button');cell.type='button';cell.className='productivity-day';cell.dataset.level=String(day.points===0?0:day.points<=3?1:day.points<=8?2:day.points<=20?3:4);cell.title=cell.ariaLabel=`${day.date}: ${day.completed} ${t('completed')}, ${day.points} ${t('points')}, ${(day.work_ms/3600000).toFixed(2)}h`;
|
||||||
|
cell.onclick=async()=>{const sequence=++detailSequence;try{const next=new Date(day.date+'T12:00:00Z');next.setUTCDate(next.getUTCDate()+1);const single=await request('report?'+new URLSearchParams({from:day.date,to:next.toISOString().slice(0,10)}));if(sequence!==detailSequence)return;detail.replaceChildren(el('h2',day.date),taskTable(single));}catch(e){error(e);}};grid.append(cell);}
|
||||||
|
scroll.append(grid);const note=el('p',ja?'1タスクのポイント = 1 + ⌈見積分数 / 30⌉ × 複雑度(1〜5)。完了取消は集計から除外。作業時間とPomodoroは別集計で、重複する場合は加算しません。':'Points per task = 1 + ceil(estimated minutes / 30) × complexity (1–5). Reopened tasks are excluded. Work and Pomodoro are separate; overlapping time is not added together.');note.className='productivity-note';results.replaceChildren(stats,scroll,note,detail);
|
||||||
|
}catch(e){error(e);}finally{refresh.disabled=false;}}
|
||||||
|
controls.onsubmit=e=>{e.preventDefault();load();};await load();
|
||||||
|
}
|
||||||
|
return (root.dataset.view==='settings'?settings():report()).catch(error);
|
||||||
|
}
|
||||||
|
window.PagesWikiProductivityMount=mount;
|
||||||
|
mount(document.getElementById('task-productivity'));
|
||||||
|
})();
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
(()=>{'use strict';const app=document.getElementById('tasks-app');if(!app)return;const ja=document.documentElement.lang.startsWith('ja'),t=(a,b)=>ja?b:a,api='/_/api/v1/extension/organizer.tasks/',bar=document.createElement('section'),label=document.createElement('a'),clock=document.createElement('span'),stop=document.createElement('button'),status=document.createElement('span');bar.className='task-work-bar';bar.hidden=true;bar.style.cssText='display:none;grid-column:1/-1;gap:.6rem;align-items:center;flex-wrap:wrap;padding:.5rem 0';stop.type='button';stop.textContent=t('■ Stop recording','■ 作業記録を終了');status.role='status';bar.append(label,clock,stop,status);app.prepend(bar);let current=null,busy=false;
|
||||||
|
async function request(path,options={}){const r=await fetch(api+path,{credentials:'same-origin',signal:AbortSignal.timeout(15000),...options,headers:{'Content-Type':'application/json'}});const d=await r.json().catch(()=>({}));if(!r.ok||r.redirected)throw Error(t('Recording failed. Check the active timer and reload; no duplicate timer is started.','記録できません。実行中の記録と権限を確認し再読込してください。タイマーは重複開始しません。'));return d;}
|
||||||
|
function tick(){clock.textContent=current?.uuid?Math.floor(Math.max(0,Date.now()-current.start_ms)/60000)+' min':'';}
|
||||||
|
async function load(){if(busy||document.hidden)return;try{const d=await request('work');current=d.item;bar.hidden=!current?.uuid;bar.style.display=bar.hidden?'none':'flex';if(current?.uuid){label.href='/v/plan/task/'+current.task_uuid;const task=await request('items/'+current.task_uuid);label.textContent=t('Recording: ','作業記録:')+task.item.title;}tick();}catch(e){status.textContent=e.message;}}
|
||||||
|
app.addEventListener('task-work',async e=>{if(busy)return;busy=true;try{await request('work',{method:'POST',body:JSON.stringify({action:'start',uuid:crypto.randomUUID(),task_uuid:e.detail.uuid})});status.textContent='';}catch(err){bar.hidden=false;bar.style.display='flex';status.textContent=err.message;const feedback=document.getElementById('tasks-status');if(feedback)feedback.textContent=err.message;}finally{busy=false;await load();}});
|
||||||
|
stop.onclick=async()=>{if(busy||!current?.uuid)return;busy=true;stop.disabled=true;try{await request('work',{method:'POST',body:JSON.stringify({...current,action:'stop'})});status.textContent='';}catch(e){status.textContent=e.message;}finally{busy=false;stop.disabled=false;await load();}};setInterval(()=>{if(!document.hidden)tick();},10000);setInterval(load,60000);document.addEventListener('visibilitychange',load);load();})();
|
||||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user