Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
870011f8a7
|
@@ -1,16 +1,15 @@
|
|||||||
# 🐻 Bear CLI
|
# 🐻 Bear CLI
|
||||||
|
|
||||||
**Bear CLI** 是 [澳特科技](https://alterminal.com)(Alter Technology)單點登入系統 [Bear](https://gitea.alterminal.com/alterminal/bear) 的**終端機(CLI)客戶端**:讓使用者在 Linux 終端機以 Bear 帳號登入(Device Flow 或個人存取權杖)、查詢身分、取得 Token,作為 SSO 的終端入口。
|
**Bear CLI** 是 [澳特科技](https://alterminal.com)(Alter Technology)單點登入系統 [Bear](https://gitea.alterminal.com/alterminal/bear) 的**終端機(CLI)客戶端**:讓使用者在 Linux 終端機直接以 Bear 帳號登入、查詢身分、取得並續期 Token,作為 SSO 的終端入口。
|
||||||
|
|
||||||
> **狀態:已實作 PAT 模式 MVP(Elixir + Req,issue #6)+ App 管理(#10)+ 個人自助指令群(#11)+ 管理端指令群(#12)+ Vault 密碼管理(#17)**。`login --token <PAT>`、`whoami`、`token`、`logout`、`status`、`apps`、`profile`/`password`/`email`/`sessions`/`tokens`/`mfa`、`jwks`/`accounts`/`audit-logs`、`vault` 已可用;Device Authorization Grant(RFC 8628)登入待伺服器端 P1(bear 倉庫)完成後再接。
|
> **狀態:已實作 PAT 模式 MVP(Elixir + Req)**。`login --token <PAT>`、`whoami`、`token`、`logout`、`status` 已可用;Device Authorization Grant(RFC 8628)登入待伺服器端 P1(bear 倉庫)完成後再接。
|
||||||
> 伺服器端採用的 OIDC **Device Authorization Grant(RFC 8628)** 方向,詳見 bear 倉庫的設計文件 `docs/cli-feature-plan.md`(issue #17)。
|
> 伺服器端採用的 OIDC **Device Authorization Grant(RFC 8628)** 方向,詳見 bear 倉庫的設計文件 `docs/cli-feature-plan.md`(issue #17)。
|
||||||
> Bear 已支援**個人存取權杖(Personal Access Token,PAT)**;CLI 規劃以其作為完全免瀏覽器的替代登入方式(見下文)。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 為什麼需要 CLI
|
## 為什麼需要 CLI
|
||||||
|
|
||||||
Bear 目前所有流程都依賴「瀏覽器」:登入 `/login`、儀表板 Launch、Relying Party 走 Authorization Code Flow + PKCE。但**終端機沒有瀏覽器可互動**,無法完成 `redirect_uri` 回跳,因此需要一個為「無瀏覽器/輸入受限裝置」設計的登入流程,讓 `bear` 指令也能以 OIDC 身分登入並取用 Token。此外,Bear 現已支援**個人存取權杖(PAT)**,CLI 亦可直接以 PAT 登入,完全免瀏覽器,適合 CI/腳本/一次性使用。
|
Bear 目前所有流程都依賴「瀏覽器」:登入 `/login`、儀表板 Launch、Relying Party 走 Authorization Code Flow + PKCE。但**終端機沒有瀏覽器可互動**,無法完成 `redirect_uri` 回跳,因此需要一個為「無瀏覽器/輸入受限裝置」設計的登入流程,讓 `bear` 指令也能以 OIDC 身分登入並取用 Token。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -18,50 +17,29 @@ Bear 目前所有流程都依賴「瀏覽器」:登入 `/login`、儀表板 La
|
|||||||
|
|
||||||
| 指令 | 說明 | 階段 |
|
| 指令 | 說明 | 階段 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| `bear login` | 啟動 Device Flow 登入;或 `--token <PAT>` 以個人存取權杖登入 | P2 |
|
| `bear login` | 啟動 Device Flow 登入(取得授權碼 → 兌換 Token) | P2 |
|
||||||
| `bear whoami` | 顯示目前登入身分(`GET /userinfo`) | P2 |
|
| `bear whoami` | 顯示目前登入身分(`GET /userinfo`) | P2 |
|
||||||
| `bear token [--refresh]` | 印出 access token(過期自動 refresh),供 pipe 給其他工具 | P2 |
|
| `bear token [--refresh]` | 印出 access token(過期自動 refresh),供 pipe 給其他工具 | P2 |
|
||||||
| `bear logout` | 撤銷 refresh token(`POST /revoke`) | P2 |
|
| `bear logout` | 撤銷 refresh token(`POST /revoke`) | P2 |
|
||||||
| `bear status` | 顯示登入狀態與 token 剩餘效期 | P2 |
|
| `bear status` | 顯示登入狀態與 token 剩餘效期 | P2 |
|
||||||
| `bear apps list/show/create/update/rotate-secret/toggle` | App 管理(需 bear App 管理 JSON API,PAT 登入、admin 限定) | P3(✅ 已實作) |
|
| `bear apps` | 列出公開應用(需新增公開應用清單 API) | P3 |
|
||||||
| `bear jwks list/show/create/toggle` | 簽章金鑰管理(admin 限定) | P3(✅ 已實作) |
|
|
||||||
| `bear accounts list/show/create/update/set-password/delete` | 帳號管理(admin 限定) | P3(✅ 已實作) |
|
|
||||||
| `bear audit-logs list` | 稽核日誌查詢(admin 限定) | P3(✅ 已實作) |
|
|
||||||
| `bear profile show/set` | 個人資料檢視/更新(需 bear 個人自助 JSON API) | P3(✅ 已實作) |
|
|
||||||
| `bear password change` | 變更密碼(互動輸入,不進 shell history) | P3(✅ 已實作) |
|
|
||||||
| `bear email change --new EMAIL` | 變更 email(雙向驗證碼流程) | P3(✅ 已實作) |
|
|
||||||
| `bear sessions list/revoke/revoke-others` | 管理網頁 session | P3(✅ 已實作) |
|
|
||||||
| `bear tokens list/create/revoke` | 管理 PAT(create 一次性顯示明文) | P3(✅ 已實作) |
|
|
||||||
| `bear mfa status/setup/disable/recovery-codes` | TOTP 兩因子管理 | P3(✅ 已實作) |
|
|
||||||
| `bear vault status/unlock/lock` | Vault 解鎖狀態與 K_user session(僅記憶體) | P3(✅ 已實作) |
|
|
||||||
| `bear vault list/get/create/edit` | 項目 CRUD(客戶端端到端加密,與 Web Vault 互操作) | P3(✅ 已實作) |
|
|
||||||
| `bear vault delete/restore/purge` | 回收桶(soft delete/還原/永久刪除) | P3(✅ 已實作) |
|
|
||||||
| `bear vault folders list/create/rename/delete` | 資料夾管理(名稱客戶端加密) | P3(✅ 已實作) |
|
|
||||||
| `bear vault sync` | 完整同步(伺服器為準) | P3(✅ 已實作) |
|
|
||||||
| `bear vault password change` | 變更 vault 主密碼(重新包裝 K_user,不動 cipher) | P3(✅ 已實作) |
|
|
||||||
| `bear vault rescue` | 助記詞救援(BIP39,重設主密碼) | P3(✅ 已實作) |
|
|
||||||
|
|
||||||
完整指令規格(選項、行為、輸出、退出碼)見 [`docs/commands.md`](docs/commands.md)。
|
完整指令規格(選項、行為、輸出、退出碼)見 [`docs/commands.md`](docs/commands.md)。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 實作狀態(PAT 模式 MVP)
|
## 實作狀態(MVP)
|
||||||
|
|
||||||
目前已實作**個人存取權杖(PAT)模式**的最小可用版本(issue #6 骨架部分):
|
目前已實作**個人存取權杖(PAT)模式**的最小可用版本,涵蓋 P2 指令:
|
||||||
|
|
||||||
| 指令 | 狀態 |
|
| 指令 | 狀態 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| `bear login --token <PAT>` | ✅ 已實作(PAT 模式;Device Flow 待伺服器端 P1) |
|
| `bear login --token <PAT>` | ✅ 已實作(PAT 模式;Device Flow 待伺服器端 P1) |
|
||||||
| `bear whoami` | ✅ 已實作(`GET /userinfo`,Bearer PAT;支援 `BEAR_TOKEN` 環境變數) |
|
| `bear whoami` | ✅ 已實作(`GET /userinfo`,Bearer PAT) |
|
||||||
| `bear token` | ✅ 已實作(印出 PAT;`--refresh` 為用法錯誤) |
|
| `bear token` | ✅ 已實作(印出 PAT;`--refresh` 在 PAT 模式下無作用) |
|
||||||
| `bear logout` | ✅ 已實作(清除本機憑證;PAT 需至網頁撤銷) |
|
| `bear logout` | ✅ 已實作(清除本機憑證;PAT 需至網頁撤銷) |
|
||||||
| `bear status` | ✅ 已實作(純本機判定,顯示 PAT/環境變數模式) |
|
| `bear status` | ✅ 已實作(純本機判定) |
|
||||||
| `bear apps` | ✅ 已實作(`list`/`show`/`create`/`update`/`rotate-secret`/`toggle`;issue #10,對接 alterminal/bear#28 的 `/api/v1/apps` JSON API,admin PAT 限定) |
|
| `bear apps` | ⏳ P3 暫緩 |
|
||||||
| `bear jwks` | ✅ 已實作(`list`/`show`/`create`/`toggle`;issue #12,對接 alterminal/bear#46 的 `/api/v1/jwks` JSON API,admin PAT 限定) |
|
|
||||||
| `bear accounts` | ✅ 已實作(`list`/`show`/`create`/`update`/`set-password`/`delete`;issue #12,對接 alterminal/bear#46 的 `/api/v1/accounts` JSON API;密碼不進命令列,初始/新密碼一次性輸出) |
|
|
||||||
| `bear audit-logs` | ✅ 已實作(`list` 含 `--category` 過濾與 emails 對照;issue #12,對接 alterminal/bear#46 的 `/api/v1/audit-logs` JSON API) |
|
|
||||||
| `bear profile`/`password`/`email`/`sessions`/`tokens`/`mfa` | ✅ 已實作(issue #11,對接 alterminal/bear#38 的 `/api/v1/profile*` JSON API,任何有效 PAT 皆可):`profile show/set`、`password change`、`email change --new`、`sessions list/revoke/revoke-others`、`tokens list/create/revoke`、`mfa status/setup/disable/recovery-codes`。規格見 `docs/commands.md` §3.7 |
|
|
||||||
| `bear vault` | ✅ 已實作(issue #17,對接 alterminal/bear#41 的 `/api/v1/vault` JSON API,任何有效 PAT 皆可):`status`/`unlock`/`lock`/`list`/`get`/`create`/`edit`/`delete`/`restore`/`purge`/`folders`/`sync`/`password change`/`rescue`。端到端加密全在客戶端(AES-256-CBC+HMAC-SHA-256 加密字串、PBKDF2-SHA512、BIP39 助記詞),格式與 Web Vault(P2)完全一致;K_user 僅存 shell 環境變數記憶體(`BEAR_VAULT_SESSION`),不落盤。規格見 `docs/commands.md` §3.11 |
|
|
||||||
|
|
||||||
### 建置與執行
|
### 建置與執行
|
||||||
|
|
||||||
@@ -90,9 +68,18 @@ mix escript.build # 產生單檔可執行 `bear`
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 登入流程(`bear login`,示意)
|
## 登入流程(`bear login`)
|
||||||
|
|
||||||
### Device Flow(預設)
|
### PAT 模式(現行)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ bear login --token <PAT>
|
||||||
|
已登入:alice@example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
以個人存取權杖(PAT)直接驗證 `GET /userinfo`,成功後將 token 寫入本機憑證檔(0600)。全程免瀏覽器。
|
||||||
|
|
||||||
|
### Device Flow(待伺服器端 P1,示意)
|
||||||
|
|
||||||
```
|
```
|
||||||
$ bear login
|
$ bear login
|
||||||
@@ -106,15 +93,6 @@ $ bear login
|
|||||||
|
|
||||||
登入後,CLI 將 refresh token 寫入本機憑證檔(0600),access token 僅做短命快取。
|
登入後,CLI 將 refresh token 寫入本機憑證檔(0600),access token 僅做短命快取。
|
||||||
|
|
||||||
### 個人存取權杖(PAT,免瀏覽器)
|
|
||||||
|
|
||||||
```
|
|
||||||
$ bear login --token <PAT>
|
|
||||||
已登入:alice@example.com
|
|
||||||
```
|
|
||||||
|
|
||||||
以 PAT 登入不產生 refresh token;CLI 直接將該 PAT 寫入憑證檔(0600)作為憑證,適合 CI/腳本等無瀏覽器情境。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 憑證與設定檔
|
## 憑證與設定檔
|
||||||
@@ -122,7 +100,7 @@ $ bear login --token <PAT>
|
|||||||
| 檔 | 路徑 | 內容 | 權限 |
|
| 檔 | 路徑 | 內容 | 權限 |
|
||||||
|----|------|------|------|
|
|----|------|------|------|
|
||||||
| 設定 | `~/.config/bear/config.json` | `issuer`、`client_id`、`scope` | 0644 |
|
| 設定 | `~/.config/bear/config.json` | `issuer`、`client_id`、`scope` | 0644 |
|
||||||
| 憑證 | `~/.local/state/bear/credentials.json` | Device Flow:`refresh_token`+快取 `access_token`/`expires_at`;PAT:直接存 `access_token`(無 refresh) | **0600** |
|
| 憑證 | `~/.local/state/bear/credentials.json` | `refresh_token`(優先)+快取的 `access_token`/`expires_at` | **0600** |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -131,8 +109,8 @@ $ bear login --token <PAT>
|
|||||||
| 階段 | 內容 |
|
| 階段 | 內容 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| **P1 伺服器:Device Flow** | `device_codes` 資料表、`POST /device_authorization`、`GET/POST /device` 授權頁、token 端點 `device_code` grant、Discovery 更新(於 bear 倉庫) |
|
| **P1 伺服器:Device Flow** | `device_codes` 資料表、`POST /device_authorization`、`GET/POST /device` 授權頁、token 端點 `device_code` grant、Discovery 更新(於 bear 倉庫) |
|
||||||
| **P2 CLI 登入** | 本倉庫實作 `login`(Device Flow 或 `--token <PAT>`)/`whoami`/`token`/`logout`/`status`、憑證儲存 0600 |
|
| **P2 CLI 登入** | 本倉庫實作 `login`/`whoami`/`token`/`logout`/`status`、憑證儲存 0600 |
|
||||||
| **P3 進階** | `bear apps` 管理指令群(依賴 bear App 管理 JSON API)、個人自助指令群 `profile`/`password`/`email`/`sessions`/`tokens`/`mfa`(依賴 bear 個人自助 JSON API,#11)、QR 顯示、系統 keyring、發行二進位 |
|
| **P3 進階** | `bear apps`(公開應用清單 API)、QR 顯示、系統 keyring、發行二進位 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -140,4 +118,4 @@ $ bear login --token <PAT>
|
|||||||
|
|
||||||
- **語言**:Elixir(與 Bear 主專案一致),HTTP 一律使用 `Req`。
|
- **語言**:Elixir(與 Bear 主專案一致),HTTP 一律使用 `Req`。
|
||||||
- **發行**:`mix escript`(單檔可執行)或 `mix release` 自包含二進位(待定)。
|
- **發行**:`mix escript`(單檔可執行)或 `mix release` 自包含二進位(待定)。
|
||||||
- **安全**:device_code 只存 SHA-256 雜湊、user_code 限流、憑證檔 0600、token 與 PAT 一律不入 log/commit;一次性明文(`apps` 的 client_secret、`tokens create` 的 PAT、`mfa` 的 recovery codes)僅在成功當下顯示一次;密碼與驗證碼一律互動輸入、不回顧。
|
- **安全**:device_code 只存 SHA-256 雜湊、user_code 限流、憑證檔 0600、token 一律不入 log/commit。
|
||||||
|
|||||||
+44
-672
@@ -1,9 +1,8 @@
|
|||||||
# Bear CLI 指令規劃(Command Spec)
|
# Bear CLI 指令規劃(Command Spec)
|
||||||
|
|
||||||
> 狀態:P2 PAT 模式 MVP 已實作(見第 9 節);Device Flow 待伺服器端 P1。
|
> 狀態:規劃草案(對應 issue #19「創建 bear cli 倉庫」)
|
||||||
> 範圍:本文件為指令介面規格;App 管理指令(`bear apps` CRUD)另見 #5 規劃、個人自助指令(`bear profile` 等)另見 #11 規劃。
|
> 實作:PAT 模式 MVP 已落地(issue #2),本文件為指令介面規格;Device Flow 待伺服器端 P1。
|
||||||
> 登入採用的 OIDC Device Authorization Grant(RFC 8628)細節,見 bear 倉庫 `docs/cli-feature-plan.md`(issue #17)。
|
> 登入採用的 OIDC Device Authorization Grant(RFC 8628)細節,見 bear 倉庫 `docs/cli-feature-plan.md`(issue #17)。
|
||||||
> 另支援以**個人存取權杖(PAT)**登入(bear 已於 profile 頁提供 PAT 建立/列表/撤銷,`/userinfo` 接受 PAT 作為 Bearer)。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -27,9 +26,7 @@
|
|||||||
| `-h, --help` | bool | — | 顯示說明 |
|
| `-h, --help` | bool | — | 顯示說明 |
|
||||||
| `--version` | bool | — | 顯示版本後離開 |
|
| `--version` | bool | — | 顯示版本後離開 |
|
||||||
|
|
||||||
優先序:CLI flag > 環境變數(`BEAR_ISSUER`、`BEAR_TOKEN`)> 設定檔 > 內建預設。
|
優先序:CLI flag > 環境變數(`BEAR_ISSUER`)> 設定檔 > 內建預設。
|
||||||
|
|
||||||
> `BEAR_TOKEN` 為一次性/CI 用的個人存取權杖(PAT);提供後優先於本機憑證檔,但不寫入憑證檔。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -37,20 +34,27 @@
|
|||||||
|
|
||||||
### 3.1 `bear login`
|
### 3.1 `bear login`
|
||||||
|
|
||||||
登入 Bear,取得並保存憑證。預設走 **Device Flow**;亦可用 `--token` 直接以**個人存取權杖(PAT)**登入。
|
登入並保存 Token。目前有兩種模式:
|
||||||
|
|
||||||
|
- **PAT 模式(現行)**:`bear login --token <PAT>`,以個人存取權杖驗證 `GET /userinfo` 後保存 token,全程免瀏覽器。
|
||||||
|
- **Device Flow(待 P1)**:`bear login`,啟動 Device Authorization Grant(RFC 8628),需伺服器端 P1 完成。
|
||||||
|
|
||||||
```
|
```
|
||||||
bear login [--scope "openid profile email"] [--client-id ID]
|
bear login [--token <PAT>] [--scope "openid profile email"] [--client-id ID]
|
||||||
bear login --token <PAT>
|
|
||||||
```
|
```
|
||||||
|
|
||||||
| 選項 | 預設 | 說明 |
|
| 選項 | 預設 | 說明 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| `--scope` | `openid profile email` | Device Flow 請求的 scope(空白分隔) |
|
| `--token` | — | PAT 模式:直接提供個人存取權杖(`-` 表示從 stdin 讀取) |
|
||||||
| `--client-id` | 設定檔內值 | OIDC client id |
|
| `--scope` | `openid profile email` | Device Flow:請求的 scope(空白分隔) |
|
||||||
| `--token <PAT>` | — | 直接以個人存取權杖登入(跳過 Device Flow) |
|
| `--client-id` | 設定檔內值 | Device Flow:OIDC client id |
|
||||||
|
|
||||||
**行為(Device Flow,未給 `--token`)**:
|
**PAT 模式行為**:
|
||||||
|
|
||||||
|
1. 向 `{issuer}/userinfo` 送 `Authorization: Bearer <PAT>` 驗證 token。
|
||||||
|
2. 成功 → 寫入憑證檔(0600),印出 `已登入:<email>`;失敗(401)→ 印出錯誤,退出碼 `1`;網路錯誤 → 退出碼 `6`。
|
||||||
|
|
||||||
|
**Device Flow 行為**:
|
||||||
|
|
||||||
1. 讀取設定 → 向 `{issuer}/.well-known/openid-configuration` 取 `device_authorization_endpoint`(**動態發現,不寫死網址**)。
|
1. 讀取設定 → 向 `{issuer}/.well-known/openid-configuration` 取 `device_authorization_endpoint`(**動態發現,不寫死網址**)。
|
||||||
2. `POST /device_authorization`(`client_id` + `scope`)。
|
2. `POST /device_authorization`(`client_id` + `scope`)。
|
||||||
@@ -69,13 +73,7 @@ bear login --token <PAT>
|
|||||||
- `access_denied` → 中止並提示;
|
- `access_denied` → 中止並提示;
|
||||||
- 成功 → 寫入憑證檔(0600),印出 `已登入:<email>`。
|
- 成功 → 寫入憑證檔(0600),印出 `已登入:<email>`。
|
||||||
|
|
||||||
**行為(PAT,給 `--token <PAT>`)**:
|
**退出碼**:`0` 成功;`4` 等待逾時(`expires_in`);`5` 使用者拒絕;`6` 網路/伺服器錯誤。
|
||||||
|
|
||||||
1. 以該 PAT 作為 Bearer 呼叫 `GET /userinfo` 驗證可用性並取得身分。
|
|
||||||
2. 成功 → 將 PAT 直接寫入憑證檔(0600),印出 `已登入:<email>`(無 refresh token)。
|
|
||||||
3. 失敗(401/無效或已撤銷)→ 提示 PAT 無效,不寫入任何資料。
|
|
||||||
|
|
||||||
**退出碼**:`0` 成功;`3` PAT 無效或已撤銷;`4` 等待逾時(`expires_in`);`5` 使用者拒絕;`6` 網路/伺服器錯誤。
|
|
||||||
|
|
||||||
**`--json` 輸出範例(成功)**:
|
**`--json` 輸出範例(成功)**:
|
||||||
|
|
||||||
@@ -83,8 +81,6 @@ bear login --token <PAT>
|
|||||||
{"ok": true, "email": "alice@example.com", "expires_in": 3600}
|
{"ok": true, "email": "alice@example.com", "expires_in": 3600}
|
||||||
```
|
```
|
||||||
|
|
||||||
PAT 模式下 `expires_in` 依權杖到期日回傳;無到期日則省略該欄位。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 3.2 `bear whoami`
|
### 3.2 `bear whoami`
|
||||||
@@ -95,7 +91,7 @@ PAT 模式下 `expires_in` 依權杖到期日回傳;無到期日則省略該
|
|||||||
bear whoami
|
bear whoami
|
||||||
```
|
```
|
||||||
|
|
||||||
**行為**:讀取憑證——Device Flow 讀取快取的 access token(過期則先用 refresh token 輪轉換新);PAT 直接使用該 token——呼叫 `/userinfo`,印出 claims(name、email、picture 等)。`/userinfo` 同時接受 OIDC access token 與 PAT 作為 Bearer。
|
**行為**:讀取快取的 access token(過期則先用 refresh token 輪轉換新),呼叫 `/userinfo`,印出 claims(name、email、picture 等)。
|
||||||
|
|
||||||
**退出碼**:`0` 成功;`3` 未登入。
|
**退出碼**:`0` 成功;`3` 未登入。
|
||||||
|
|
||||||
@@ -126,7 +122,6 @@ bear token [--refresh]
|
|||||||
|
|
||||||
- 若無 `--refresh` 且快取的 access token 未過期 → 直接印出。
|
- 若無 `--refresh` 且快取的 access token 未過期 → 直接印出。
|
||||||
- 若過期(或指定 `--refresh`)→ 以 refresh token 向 `/token` 換新,更新快取後印出。
|
- 若過期(或指定 `--refresh`)→ 以 refresh token 向 `/token` 換新,更新快取後印出。
|
||||||
- **PAT 模式**:直接印出該 PAT(無 refresh token;`--refresh` 為無效選項,報用法錯誤 `2`)。
|
|
||||||
- 輸出**只含 token 本體**(單行、無前綴),方便 pipe;診斷訊息一律走 stderr。
|
- 輸出**只含 token 本體**(單行、無前綴),方便 pipe;診斷訊息一律走 stderr。
|
||||||
|
|
||||||
**退出碼**:`0` 成功;`3` 未登入;`1` refresh 失敗(token 已撤銷或過期,需重新 login)。
|
**退出碼**:`0` 成功;`3` 未登入;`1` refresh 失敗(token 已撤銷或過期,需重新 login)。
|
||||||
@@ -141,9 +136,7 @@ bear token [--refresh]
|
|||||||
bear logout
|
bear logout
|
||||||
```
|
```
|
||||||
|
|
||||||
**行為**:
|
**行為**:呼叫 `POST /revoke`(撤銷 refresh token),無論伺服器回應如何,皆刪除本機憑證檔。
|
||||||
- Device Flow:呼叫 `POST /revoke`(撤銷 refresh token),無論伺服器回應如何,皆刪除本機憑證檔。
|
|
||||||
- PAT:僅刪除本機憑證檔(PAT 的撤銷需於網頁 `/profile/tokens` 進行,CLI 不提供撤銷)。
|
|
||||||
|
|
||||||
**退出碼**:`0` 成功;`6` 伺服器呼叫失敗(但本機憑證已清除)。
|
**退出碼**:`0` 成功;`6` 伺服器呼叫失敗(但本機憑證已清除)。
|
||||||
|
|
||||||
@@ -157,612 +150,32 @@ bear logout
|
|||||||
bear status
|
bear status
|
||||||
```
|
```
|
||||||
|
|
||||||
**行為**:讀取本機憑證,印出登入與否、憑證類型(Device Flow/PAT)、access token 剩餘秒數、refresh token 是否存在。
|
**行為**:讀取本機憑證,印出登入與否、access token 剩餘秒數、refresh token 是否存在。
|
||||||
|
|
||||||
**退出碼**:`0` 已登入;`3` 未登入。
|
**退出碼**:`0` 已登入;`3` 未登入。
|
||||||
|
|
||||||
**輸出範例(Device Flow)**:
|
**輸出範例**:
|
||||||
|
|
||||||
```
|
```
|
||||||
已登入:alice@example.com
|
已登入:alice@example.com
|
||||||
憑證類型:Device Flow
|
|
||||||
access token 剩餘:3210 秒
|
access token 剩餘:3210 秒
|
||||||
refresh token:有
|
refresh token:有
|
||||||
issuer:https://alterminal.com
|
issuer:https://alterminal.com
|
||||||
```
|
```
|
||||||
|
|
||||||
**輸出範例(PAT,無到期日)**:
|
|
||||||
|
|
||||||
```
|
|
||||||
已登入:alice@example.com
|
|
||||||
憑證類型:Personal Access Token
|
|
||||||
access token 剩餘:無到期
|
|
||||||
refresh token:無
|
|
||||||
issuer:https://alterminal.com
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 3.6 `bear apps`:App 管理指令群(P3,已實作)
|
### 3.6 `bear apps`(P3,暫緩)
|
||||||
|
|
||||||
> 依賴:bear 伺服器端 **App 管理 JSON API**(alterminal/bear#28,資源前綴 `/api/v1/apps`,PAT Bearer 認證、管理操作限 admin)。API 已上線(PR alterminal/bear#29),本節指令群已實作(issue #10);`--visibility`/`--status` 過濾目前由 CLI 全量列舉後本地套用(伺服器 list 端點尚無對應查詢參數)。
|
列出「公開應用」清單,供 Launch/跳轉參考。
|
||||||
|
|
||||||
`bear apps` 是「資源群組」指令:`bear apps <動詞>`。這是第 1 節「扁平結構」原則的首個例外——App 的管理操作(列表、檢視、建立、更新、輪轉 secret、啟停用)若攤平命名會造成指令名爆炸(`bear apps-create`…),故收斂為單一群組;未來同類資源管理指令比照。
|
|
||||||
|
|
||||||
```
|
```
|
||||||
bear apps list [選項]
|
bear apps
|
||||||
bear apps show <client-id>
|
|
||||||
bear apps create [選項]
|
|
||||||
bear apps update <client-id> [選項]
|
|
||||||
bear apps rotate-secret <client-id>
|
|
||||||
bear apps toggle <client-id>
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**認證與授權(群組共通)**:
|
**前置**:bear 伺服器端需新增「公開應用清單」API(列為 P3,待確認)。
|
||||||
|
|
||||||
- 一律使用既有 PAT 憑證(`bear login --token` 登入,或 `BEAR_TOKEN` 環境變數)作為 Bearer 呼叫 API;不提供其他登入方式。
|
**退出碼**:`0` 成功;`3` 未登入;`6` API 尚未提供。
|
||||||
- 管理操作僅限 admin 角色帳號。`401`(token 無效/已撤銷)→ 退出碼 `3`,提示重新 `bear login`;`403`(非 admin)→ 退出碼 `8`,明確提示「此操作需 admin 權限」,不重試。
|
|
||||||
- **`client_secret` 只在 `create`/`rotate-secret` 成功當下一次性顯示**於 stdout,不寫入憑證檔、log、`--verbose` 輸出或版本庫;`list`/`show`/`update`/`toggle` 的回應永遠不含 secret(API 端保證)。
|
|
||||||
- App 識別一律以 `client_id`(人類可讀、唯一),不暴露資料庫 UUID。若 API 路徑參數僅接受 UUID,由 CLI 先以 list 比對解析(見第 7 節開放問題 6)。
|
|
||||||
|
|
||||||
**群組共通退出碼**:
|
|
||||||
|
|
||||||
| 碼 | 語意 |
|
|
||||||
|----|------|
|
|
||||||
| `0` | 成功 |
|
|
||||||
| `1` | 目標不存在或驗證失敗(HTTP 404/422;含欄位格式錯誤、`client_id` 重複) |
|
|
||||||
| `2` | 用法錯誤(缺必選參數、列舉值非法、PKCE 未綁 `--jwk-id` 等,由 CLI 本地檢查) |
|
|
||||||
| `3` | 未登入或憑證無效(HTTP 401) |
|
|
||||||
| `6` | 網路/伺服器錯誤 |
|
|
||||||
| `8` | 權限不足(HTTP 403,管理操作僅限 admin) |
|
|
||||||
|
|
||||||
#### 3.6.1 `bear apps list`
|
|
||||||
|
|
||||||
列出 App 清單。
|
|
||||||
|
|
||||||
```
|
|
||||||
bear apps list [--visibility public|internal] [--status active|inactive]
|
|
||||||
[--page N] [--per-page N] [--json]
|
|
||||||
```
|
|
||||||
|
|
||||||
| 選項 | 預設 | 說明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `--visibility` | 全部 | 過濾 `public` 或 `internal` |
|
|
||||||
| `--status` | 全部 | 過濾 `active` 或 `inactive` |
|
|
||||||
| `--page` | `1` | 分頁頁碼(對應 API `page`) |
|
|
||||||
| `--per-page` | `20` | 每頁筆數(對應 API `per_page`,上限同伺服器) |
|
|
||||||
|
|
||||||
**行為**:`GET /api/v1/apps`(Bearer PAT),套用過濾與分頁;人類可讀輸出為表格,依 `client_id` 排序。
|
|
||||||
|
|
||||||
```
|
|
||||||
CLIENT ID TITLE VISIBILITY STATUS METHOD SCOPES
|
|
||||||
my-app My App public active client_secret openid, profile
|
|
||||||
internal-tool Internal Tool internal inactive PKCE openid
|
|
||||||
```
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{"ok": true, "page": 1, "per_page": 20, "apps": [{"client_id": "my-app", "title": "My App", "url": "https://example.com", "method": "client_secret", "status": "active", "visibility": "public", "scopes": ["openid", "profile"], "redirect_urls": ["https://example.com/callback"], "post_logout_redirect_uris": [], "sub": "id", "jwk_id": null, "created_at": "2026-09-07T00:00:00Z", "updated_at": "2026-09-07T00:00:00Z"}]}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 3.6.2 `bear apps show <client-id>`
|
|
||||||
|
|
||||||
顯示單一 App 完整資訊。
|
|
||||||
|
|
||||||
**行為**:`GET /api/v1/apps/{id}`(以 client-id 解析);印出全部欄位(同 create 選項集合,另含 `status`、`created_at`/`updated_at`、`jwk_id`);`client_secret` 永不回傳。
|
|
||||||
|
|
||||||
**輸出範例**:
|
|
||||||
|
|
||||||
```
|
|
||||||
client_id : my-app
|
|
||||||
title : My App
|
|
||||||
url : https://example.com
|
|
||||||
method : client_secret
|
|
||||||
visibility : public
|
|
||||||
status : active
|
|
||||||
scopes : openid, profile
|
|
||||||
redirect_urls : https://example.com/callback
|
|
||||||
post_logout_redirect_uris : (無)
|
|
||||||
sub : id
|
|
||||||
jwk_id : (無)
|
|
||||||
created_at : 2026-09-07T00:00:00Z
|
|
||||||
updated_at : 2026-09-07T00:00:00Z
|
|
||||||
```
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "app": {…同 list 之單一物件…}}`
|
|
||||||
|
|
||||||
#### 3.6.3 `bear apps create`
|
|
||||||
|
|
||||||
建立 App。`method=client_secret` 且未給 `--secret` 時,由伺服器自動產生並**一次性**回傳明文。
|
|
||||||
|
|
||||||
```
|
|
||||||
bear apps create --client-id ID --url URL --title TITLE
|
|
||||||
[--method client_secret|PKCE] [--visibility public|internal]
|
|
||||||
[--redirect-url URL]… [--post-logout-redirect-uri URI]…
|
|
||||||
[--scope SCOPE]… [--sub FIELD] [--jwk-id ID] [--secret SECRET] [--json]
|
|
||||||
```
|
|
||||||
|
|
||||||
| 選項 | 預設 | 說明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `--client-id` | (必填) | 唯一識別碼;英數字與連字號/底線 |
|
|
||||||
| `--url` | (必填) | 絕對 URI(http/https 或自訂 scheme 如 `myapp://`) |
|
|
||||||
| `--title` | (必填) | 顯示名稱 |
|
|
||||||
| `--method` | `client_secret` | `client_secret` 或 `PKCE`;`PKCE` 必須給 `--jwk-id` |
|
|
||||||
| `--visibility` | `internal` | `public` 或 `internal` |
|
|
||||||
| `--redirect-url` | `[]` | 可重複給予,附加為允許的 redirect URL 清單 |
|
|
||||||
| `--post-logout-redirect-uri` | `[]` | 可重複給予,登出後跳轉 URI 清單 |
|
|
||||||
| `--scope` | `["openid"]` | 可重複給予,允許的 scope 清單 |
|
|
||||||
| `--sub` | `id` | 作為 `sub` claim 的欄位名 |
|
|
||||||
| `--jwk-id` | — | 綁定的 JWK id(`method=PKCE` 時必填) |
|
|
||||||
| `--secret` | 自動產生 | 自備 client secret;省略則由伺服器產生並一次性回傳 |
|
|
||||||
|
|
||||||
**行為**:`POST /api/v1/apps`(Bearer PAT)。成功後印出 App 摘要與一次性 secret 區塊:
|
|
||||||
|
|
||||||
```
|
|
||||||
App 已建立:my-app(public/active)
|
|
||||||
client_secret(只顯示這一次,請立即保存):
|
|
||||||
4f9c1d2e-…
|
|
||||||
```
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "app": {…}, "client_secret": "4f9c1d2e-…"}`(secret 同樣只出現這一次。)
|
|
||||||
|
|
||||||
#### 3.6.4 `bear apps update <client-id>`
|
|
||||||
|
|
||||||
更新既有 App。**只更新有給的欄位**(部分更新);未給的欄位保持不變。`client_id` 不可變更(伺服器 update 不允許);`status` 不在此改(用 `toggle`)。
|
|
||||||
|
|
||||||
```
|
|
||||||
bear apps update <client-id> [--url URL] [--title TITLE]
|
|
||||||
[--method client_secret|PKCE] [--visibility public|internal]
|
|
||||||
[--redirect-url URL]… [--post-logout-redirect-uri URI]…
|
|
||||||
[--scope SCOPE]… [--sub FIELD] [--jwk-id ID] [--json]
|
|
||||||
```
|
|
||||||
|
|
||||||
**行為**:`PUT /api/v1/apps/{id}`(Bearer PAT),只送有給的欄位。清單類欄位(`--redirect-url`、`--post-logout-redirect-uri`、`--scope`)為**整組覆寫**語意:有給即取代整份清單。成功後印出更新後的 App 摘要(同 `show` 的精簡版)。422 驗證失敗時逐欄位列出錯誤。
|
|
||||||
|
|
||||||
#### 3.6.5 `bear apps rotate-secret <client-id>`
|
|
||||||
|
|
||||||
輪轉 client secret。舊 secret 立即失效。
|
|
||||||
|
|
||||||
**行為**:`POST /api/v1/apps/{id}/rotate-secret`(Bearer PAT)。成功後一次性顯示新 secret(提示同 create)。`method=PKCE` 的 App 不使用 client secret → 退出碼 `1`,提示該 App 無 secret 可輪轉。
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "client_secret": "9a7b3c…"}`(secret 只出現這一次)
|
|
||||||
|
|
||||||
#### 3.6.6 `bear apps toggle <client-id>`
|
|
||||||
|
|
||||||
切換 App 狀態:`active ↔ inactive`。
|
|
||||||
|
|
||||||
**行為**:`POST /api/v1/apps/{id}/toggle`(Bearer PAT)。成功後印出新狀態,如 `my-app:active → inactive`。
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "app": {"client_id": "my-app", "status": "inactive"}}`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 3.7 `bear profile`:個人自助指令群(P3,已實作)
|
|
||||||
|
|
||||||
> 依賴:bear 伺服器端**個人自助 JSON API**(alterminal/bear#35,資源前綴 `/api/v1/profile`,PAT Bearer 認證、**任何有效 PAT 帳號**可用,不限 admin)。API 已上線(PR alterminal/bear#38),本節指令群已實作(issue #11);端點細節以 #38 實作為準。
|
|
||||||
|
|
||||||
比照 `bear apps` 的「資源群組」例外:個人自助操作若攤平命名同樣會造成指令名爆炸(`bear password-change`…),收斂為 `bear <資源> <動詞>` 的六個子群組。頭像(picture)檔案上傳需要 multipart 與本機圖片,終端體驗差,**不在本期範圍**(#35 有對應端點,未來有需要再評估);如需更換頭像,可自行上傳圖片後以 `profile set --picture URL` 設定。
|
|
||||||
|
|
||||||
```
|
|
||||||
bear profile show [--json]
|
|
||||||
bear profile set [選項] [--json]
|
|
||||||
bear password change
|
|
||||||
bear email change --new EMAIL [--json]
|
|
||||||
bear sessions list|revoke <id>|revoke-others [--json]
|
|
||||||
bear tokens list|create|revoke <id> [選項] [--json]
|
|
||||||
bear mfa status|setup|disable|recovery-codes [--json]
|
|
||||||
```
|
|
||||||
|
|
||||||
**認證與授權(群組共通)**:
|
|
||||||
|
|
||||||
- 一律使用既有 PAT 憑證(`bear login --token` 登入,或 `BEAR_TOKEN` 環境變數)作為 Bearer 呼叫 API;不提供其他登入方式。
|
|
||||||
- 與 `apps` 群組不同,個人自助操作**任何有效 PAT 帳號皆可**(非 admin 限定)。`401`(token 無效/已撤銷)→ 退出碼 `3`,提示重新 `bear login`;`403` → 退出碼 `8`(正常情況不應出現,保留對應);`404`/`422` → 退出碼 `1`;網路/伺服器錯誤 → `6`。退出碼沿用 §4 總表,群組共通部分同 §3.6 表。
|
|
||||||
- **敏感輸入一律互動提示讀取且不回顯**:目前密碼、新密碼、email 驗證碼、MFA 驗證碼。不接受命令列明文參數(不進 shell history、不出現在 `ps`)。非 TTY 環境執行需要互動輸入的指令 → 退出碼 `2`,提示需在終端機執行。
|
|
||||||
- **一次性明文**(`tokens create` 的 PAT、`mfa setup`/`recovery-codes` 產生的 recovery codes)只於成功當下輸出於 stdout,不寫入憑證檔、log、`--verbose` 輸出或版本庫(同 `apps create` 的 `client_secret` 處理)。
|
|
||||||
- 密碼與 email 變更不因 CLI 放寬:沿用伺服器端現行密碼驗證與 email 雙向驗證碼流程,CLI 只是通道。
|
|
||||||
|
|
||||||
#### 3.7.1 `bear profile show`
|
|
||||||
|
|
||||||
顯示完整個人資料。
|
|
||||||
|
|
||||||
**行為**:`GET /api/v1/profile`(Bearer PAT),印出全部 OIDC profile 欄位(name、given_name、family_name、nickname、preferred_username、picture、profile、website、gender、birthdate、zoneinfo、locale、phone_number、address_*、email、email_verified、totp_enabled 等),格式同 `whoami` 的 `key : value`。
|
|
||||||
|
|
||||||
**輸出範例**:
|
|
||||||
|
|
||||||
```
|
|
||||||
sub : 0190...uuid
|
|
||||||
email : alice@example.com
|
|
||||||
email_verified: true
|
|
||||||
name : Alice Chen
|
|
||||||
given_name : Alice
|
|
||||||
family_name : Chen
|
|
||||||
nickname : ali
|
|
||||||
locale : zh_TW
|
|
||||||
zoneinfo : Asia/Taipei
|
|
||||||
mfa_enabled : true
|
|
||||||
```
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "profile": {…同上欄位…}}`
|
|
||||||
|
|
||||||
#### 3.7.2 `bear profile set [選項]`
|
|
||||||
|
|
||||||
更新個人資料。**只更新有給的欄位**(部分更新,同 `apps update` 語意);`email` 不可由此改(走 `bear email change`),`sub`、`email_verified`、`totp_enabled` 唯讀。
|
|
||||||
|
|
||||||
```
|
|
||||||
bear profile set [--name NAME] [--given-name NAME] [--family-name NAME]
|
|
||||||
[--nickname NAME] [--preferred-username NAME]
|
|
||||||
[--profile URL] [--picture URL] [--website URL]
|
|
||||||
[--gender male|female|other] [--birthdate YYYY-MM-DD]
|
|
||||||
[--zoneinfo TZ] [--locale LOC] [--phone-number E164]
|
|
||||||
[--phone-verified] [--address-formatted TEXT]
|
|
||||||
[--address-street-address TEXT] [--address-locality TEXT]
|
|
||||||
[--address-region TEXT] [--address-postal-code TEXT]
|
|
||||||
[--address-country TEXT] [--json]
|
|
||||||
```
|
|
||||||
|
|
||||||
| 選項 | 說明 |
|
|
||||||
|------|------|
|
|
||||||
| `--name` 等 20 個欄位選項 | 對應網頁 `/profile/edit` 表單的同一欄位集合(`profile_changeset` 的 `profile_fields`) |
|
|
||||||
| `--gender` | 列舉 `male`/`female`/`other`(非法值 → 退出碼 `2`) |
|
|
||||||
| `--birthdate` | `YYYY-MM-DD` |
|
|
||||||
| `--phone-verified` | 布林旗標(設定 `phone_number_verified`;清除不在本期,避免自我標記已驗證的濫用——**待 #35 確認是否開放**) |
|
|
||||||
| URL 類(`--profile`/`--picture`/`--website`) | 需 `http(s)://` 開頭,否則 `422` → 退出碼 `1` |
|
|
||||||
|
|
||||||
**行為**:`PUT /api/v1/profile`(Bearer PAT),只送有給的欄位。成功後印出更新後摘要;`422` 驗證失敗時逐欄位列出錯誤(退出碼 `1`)。`preferred_username` 與他人重複 → `422`,退出碼 `1`。
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "profile": {…更新後完整物件…}}`
|
|
||||||
|
|
||||||
#### 3.7.3 `bear password change`
|
|
||||||
|
|
||||||
變更密碼。**無任何命令列參數**(密碼一律互動輸入)。
|
|
||||||
|
|
||||||
**行為**:
|
|
||||||
|
|
||||||
1. 互動提示(不回顯)依序讀取:`目前密碼`、`新密碼`、`確認新密碼`。
|
|
||||||
2. 兩次新密碼不一致 → 退出碼 `2`(本地檢查),不發請求。
|
|
||||||
3. `POST /api/v1/profile/password`(Bearer PAT,body 帶 `current_password`/`new_password`/`password_confirmation`;CLI 以兩次輸入一致的新密碼填 `password_confirmation`)。
|
|
||||||
4. 成功 → 印出 `密碼已變更`;現行密碼錯誤 → 退出碼 `1`;新密碼不符伺服器強度規則 → `422`,退出碼 `1`。
|
|
||||||
|
|
||||||
比照網頁流程,變更密碼**不**自動撤銷其他 session;需要時另用 `bear sessions revoke-others`。
|
|
||||||
|
|
||||||
#### 3.7.4 `bear email change --new EMAIL`
|
|
||||||
|
|
||||||
變更 email(雙向驗證碼流程)。驗證碼一律互動輸入,不接受命令列參數。
|
|
||||||
|
|
||||||
| 選項 | 說明 |
|
|
||||||
|------|------|
|
|
||||||
| `--new EMAIL` | (必填)新 email 位址 |
|
|
||||||
|
|
||||||
**行為**:
|
|
||||||
|
|
||||||
1. `POST /api/v1/profile/email/request-codes`(Bearer PAT,`new_email`)→ 伺服器向**現有與新**信箱各寄一組驗證碼。
|
|
||||||
2. 終端印出 `驗證碼已寄至現有信箱與 <new>`,互動提示(不回顧)讀取:`現有信箱驗證碼`、`新信箱驗證碼`。
|
|
||||||
3. `POST /api/v1/profile/email`(`new_email`/`current_code`/`new_code`;API 版需再帶一次 `new_email`,CLI 自動帶入)。
|
|
||||||
4. 成功 → 印出 `email 已更新:new@example.com`,並提醒 `bear login` 用的 PAT 不受影響(PAT 不綁 email)。
|
|
||||||
|
|
||||||
錯誤:`same_email`/`email_taken`/`invalid_email` → 退出碼 `1`;驗證碼錯誤或逾期 → 退出碼 `1`,提示重新執行(會重寄驗證碼);伺服器限流(`429`)→ 退出碼 `1`,提示稍後再試。
|
|
||||||
|
|
||||||
**`--json` 輸出範例(成功)**:`{"ok": true, "email": "new@example.com"}`
|
|
||||||
|
|
||||||
#### 3.7.5 `bear sessions`
|
|
||||||
|
|
||||||
管理**網頁 session**(裝置登入狀態);與 PAT 無關——撤銷 session 不影響 PAT,PAT 的撤銷用 `bear tokens revoke`。CLI 以 PAT 呼叫 API,本身沒有「目前 session」,清單不標記目前項。
|
|
||||||
|
|
||||||
- **`bear sessions list`**:`GET /api/v1/profile/sessions`(Bearer PAT),表格輸出,新到舊排序:
|
|
||||||
|
|
||||||
```
|
|
||||||
ID IP USER AGENT CREATED LAST SEEN
|
|
||||||
0192a1b0-… 203.0.113.10 Mozilla/5.0 (X11; Linux…) 2026-09-07 10:00:00Z 2026-09-08 09:00:00Z
|
|
||||||
```
|
|
||||||
|
|
||||||
(`user_agent` 截斷至欄寬;`--json` 輸出完整值。API 回應欄位為 `id`/`ip`/`user_agent`/`created_at`/`last_seen_at`,不含 `expires_at`。)
|
|
||||||
- **`bear sessions revoke <id>`**:`POST /api/v1/profile/sessions/{id}/revoke`。成功印出 `session 已撤銷`;不存在或非本人 → `404`,退出碼 `1`。
|
|
||||||
- **`bear sessions revoke-others`**:`POST /api/v1/profile/sessions/revoke-others`。成功印出 `已撤銷 N 個其他 session`。
|
|
||||||
|
|
||||||
`<id>` 為 session UUID(取自 `list` 輸出;不接受前綴比對)。
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "sessions": […]}`/`{"ok": true, "revoked": 3}`
|
|
||||||
|
|
||||||
#### 3.7.6 `bear tokens`
|
|
||||||
|
|
||||||
管理 PAT。**token 明文絕不出現在 `list`**(伺服器只存 SHA-256 雜湊)。
|
|
||||||
|
|
||||||
- **`bear tokens list`**:`GET /api/v1/profile/tokens`(Bearer PAT),新到舊排序:
|
|
||||||
|
|
||||||
```
|
|
||||||
ID NAME SCOPE CREATED EXPIRES LAST USED STATUS
|
|
||||||
0192a1c0-… ci-token openid, profile 2026-09-01 00:00:00Z 2026-10-01 00:00:00Z 2026-09-08 08:00:00Z active
|
|
||||||
0192a1b0-… old-laptop openid, profile 2026-08-01 00:00:00Z (無到期) (未使用) expired
|
|
||||||
```
|
|
||||||
|
|
||||||
`STATUS`:`active`/`expired`(CLI 依 `expires_at` 本地判定)。API 的 list 端點只回**未撤銷**的 token,故 `revoked` 不會出現在清單。
|
|
||||||
- **`bear tokens create --name NAME [--expires-in DAYS|never]`**:`POST /api/v1/profile/tokens`(Bearer PAT,body `name`/`expires_in`;scope 由伺服器給預設 `openid profile email`,API 不接受指定)。成功後一次性顯示:
|
|
||||||
|
|
||||||
```
|
|
||||||
PAT 已建立:ci-token(30 天後到期)
|
|
||||||
token(只顯示這一次,請立即保存):
|
|
||||||
9f3a…(Base64url,43 字元,無前綴)
|
|
||||||
```
|
|
||||||
|
|
||||||
| 選項 | 預設 | 說明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `--name` | (必填) | 顯示名稱;空白或重複名稱依伺服器規則 `422` → 退出碼 `1` |
|
|
||||||
| `--expires-in` | `30` | 天數(正整數)或 `never`(永不過期) |
|
|
||||||
|
|
||||||
`--json` 輸出範例:`{"ok": true, "token": {…list 之單一物件…}, "raw": "9f3a…"}`(`raw` 只出現這一次。)
|
|
||||||
提醒:新 PAT 要使用須另以 `bear login --token` 登入(或設 `BEAR_TOKEN`)。
|
|
||||||
- **`bear tokens revoke <id>`**:`POST /api/v1/profile/tokens/{id}/revoke`(`<id>` 為 UUID)。成功印出 `PAT 已撤銷`;若撤銷的是**目前憑證用的 PAT**,後續指令會得到 `401`(退出碼 `3`),屆時重新 `bear login`(本機憑證檔未存 token id,CLI 無法預先比對,僅能提示此退路)。
|
|
||||||
|
|
||||||
#### 3.7.7 `bear mfa`
|
|
||||||
|
|
||||||
TOTP 兩因子管理(WebAuthn/passkey 不在範圍)。
|
|
||||||
|
|
||||||
- **`bear mfa status`**:讀 `GET /api/v1/profile` 的 `mfa_enabled` 欄位,印出 `MFA(TOTP):已啟用/未啟用`。
|
|
||||||
- **`bear mfa setup`**:兩步互動流程——
|
|
||||||
1. `POST /api/v1/profile/mfa/setup`(無 body,Bearer PAT)→ 回傳 Base32 `secret` 與 `otpauth://` URI。終端印出 URI、secret,並在本機產生 ASCII QR(掃碼加入驗證器;QR 由 CLI 本地生成,不經伺服器;`--json` 模式此步資訊走 stderr,stdout 留給最終結果)。
|
|
||||||
2. 互動提示(不回顧)讀取 6 位碼 → `POST /api/v1/profile/mfa/setup/confirm`(`code`)確認。
|
|
||||||
3. 成功 → **一次性**顯示 recovery codes(提示同 PAT:只顯示這一次)。
|
|
||||||
|
|
||||||
已啟用 MFA 再執行 → 退出碼 `1`,提示已啟用。驗證碼錯誤 → 退出碼 `1`,可重試(不重產 secret)。
|
|
||||||
- **`bear mfa disable`**:互動提示(不回顯)讀取目前的 TOTP 碼或 recovery code → `POST /api/v1/profile/mfa/disable`。成功印出 `MFA 已停用`;碼錯誤 → 退出碼 `1`,未停用。
|
|
||||||
- **`bear mfa recovery-codes`**:互動提示(不回顯)讀取目前的 TOTP 碼或 recovery code → `POST /api/v1/profile/mfa/recovery-codes`。成功後**一次性**顯示整組新的 recovery codes(舊組全部失效)。
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "totp_enabled": true}`;setup 確認成功:`{"ok": true, "recovery_codes": ["…", "…"]}`(只出現這一次)。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 3.8 `bear jwks`:簽章金鑰管理指令群(admin,已實作)
|
|
||||||
|
|
||||||
> 依賴:bear 伺服器端 **JWK 管理 JSON API**(alterminal/bear#36/PR #46,資源前綴 `/api/v1/jwks`,PAT Bearer 認證、admin 限定)。API 已上線,本節指令群已實作(issue #12)。
|
|
||||||
|
|
||||||
|
|
||||||
比照 `apps` 的「資源群組」結構。金鑰材質(`key_data`)**永不經 CLI 顯示**(API 端即不序列化;公開 JWK 走 `/.well-known/jwks.json`),本群組僅管理公開中繼資料。
|
|
||||||
|
|
||||||
|
|
||||||
```
|
|
||||||
bear jwks list [--json]
|
|
||||||
bear jwks show <kid> [--json]
|
|
||||||
bear jwks create --kid KID [--alg ALG] [--json]
|
|
||||||
bear jwks toggle <kid> [--json]
|
|
||||||
```
|
|
||||||
|
|
||||||
**認證與授權(群組共通)**:一律使用既有 PAT 憑證(`bear login --token` 或 `BEAR_TOKEN` 環境變數)作為 Bearer,僅限 admin 角色。
|
|
||||||
`401`(token 無效)→ 退出碼 `3`,提示重新 `bear login`;`403`(非 admin)→ 退出碼 `8`,提示此操作需 admin 權限,不重試。
|
|
||||||
|
|
||||||
|
|
||||||
**識別與退出碼**:金鑰一律以 `kid`(人類可讀)識別;API 路徑參數為 UUID,由 CLI 先以 list 比對解析。退出碼同 §3.6 群組共通表(0/1/2/3/6/8)。
|
|
||||||
|
|
||||||
|
|
||||||
#### 3.8.1 `bear jwks list`
|
|
||||||
|
|
||||||
**行為**:`GET /api/v1/jwks`(Bearer PAT),列出所有金鑰(active 與 inactive),最新在前;人類可讀輸出為表格(ID 前 8 碼、KID、KTY、ALG、ACTIVE、CREATED AT)。
|
|
||||||
|
|
||||||
```
|
|
||||||
ID KID KTY ALG ACTIVE CREATED AT
|
|
||||||
0192cccc sig-2026-01 RSA RS256 active 2026-09-09T00:00:00Z
|
|
||||||
0192cccc sig-2025-12 EC ES256 inactive 2025-12-01T00:00:00Z
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "jwks": [{…}]}`(僅公開欄位,無 `key_data`)。
|
|
||||||
|
|
||||||
|
|
||||||
#### 3.8.2 `bear jwks show <kid>`
|
|
||||||
|
|
||||||
**行為**:`GET /api/v1/jwks/{id}`(以 kid 解析),印出公開欄位(id、kid、kty、alg、use、active、created_at);找不到 kid → 退出碼 `1`。
|
|
||||||
|
|
||||||
#### 3.8.3 `bear jwks create --kid KID [--alg ALG]`
|
|
||||||
|
|
||||||
| 選項 | 預設 | 說明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `--kid` | (必填) | 金鑰識別碼 |
|
|
||||||
| `--alg` | `RS256` | `RS256`/`RS384`/`RS512`/`ES256`/`ES384`/`ES512` |
|
|
||||||
|
|
||||||
**行為**:`POST /api/v1/jwks`(body 為 kid 與 alg;金鑰由伺服器產生)。成功印出 `JWK 已建立:<kid>(<alg>/active)`。`alg` 非法 → 退出碼 `2`(本地檢查);kid 重複等 422 → 退出碼 `1` 逐欄位列錯。
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "jwk": {…}}`
|
|
||||||
|
|
||||||
#### 3.8.4 `bear jwks toggle <kid>`
|
|
||||||
|
|
||||||
**行為**:`POST /api/v1/jwks/{id}/toggle`(以 kid 解析),切換 `active ⇄ inactive`;成功印出如 `sig-2026-01:active → inactive`。
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "jwk": {"id": "…", "kid": "…", "active": false}}`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 3.9 `bear accounts`:帳號管理指令群(admin,已實作)
|
|
||||||
|
|
||||||
> 依賵:bear 伺服器端 **帳號管理 JSON API**(alterminal/bear#36/PR #46,資源前綴 `/api/v1/accounts`,PAT Bearer 認證、admin 限定)。API 已上線,本節指令群已實作(issue #12)。
|
|
||||||
|
|
||||||
帳號 JSON 不含機密欄位(hash_password、totp_secret、recovery codes;API 端保證),CLI 亦不顯示。敏感規則與伺服器端一致:不可移除自己的 admin 角色(403)、不可刪除自己(403)。
|
|
||||||
|
|
||||||
```
|
|
||||||
bear accounts list [--page N] [--per-page N] [--json]
|
|
||||||
bear accounts show <email> [--json]
|
|
||||||
bear accounts create --email EMAIL [--role user|admin] [--generate-password] [--json]
|
|
||||||
bear accounts update <email> --role user|admin [--json]
|
|
||||||
bear accounts set-password <email> [--generate-password] [--json]
|
|
||||||
bear accounts delete <email> [--json]
|
|
||||||
```
|
|
||||||
|
|
||||||
**認證與授權(群組共通)**:同 §3.8(PAT Bearer、僅限 admin;401 → 3;403 → 8)。退出碼同 §3.6 群組共通表。
|
|
||||||
|
|
||||||
**識別與密碼**:帳號一律以 `email` 識別;API 路徑參數為 UUID,由 CLI 先以 list 分頁比對解析。密碼不進命令列(避免 shell history 與 ps):交互提示輸入(不回顧)或 `--generate-password` 由 CLI 產生。初始/新密碼只在成功當下一次性輸出。
|
|
||||||
|
|
||||||
#### 3.9.1 `bear accounts list`
|
|
||||||
|
|
||||||
**行為**:`GET /api/v1/accounts`(Bearer PAT,分頁,最新在前);人類可讀輸出為表格。
|
|
||||||
|
|
||||||
```
|
|
||||||
EMAIL ROLE TOTP CREATED AT
|
|
||||||
admin@example.com admin on 2026-01-01T00:00:00Z
|
|
||||||
alice@example.com user off 2026-02-01T00:00:00Z
|
|
||||||
```
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "page": 1, "per_page": 20, "total": 2, "accounts": […]}`
|
|
||||||
|
|
||||||
#### 3.9.2 `bear accounts show <email>`
|
|
||||||
|
|
||||||
**行為**:`GET /api/v1/accounts/{id}`(以 email 解析),印出公開欄位(id、email、role、totp_enabled、created_at、updated_at);找不到 → 退出碼 `1`。
|
|
||||||
|
|
||||||
#### 3.9.3 `bear accounts create`
|
|
||||||
|
|
||||||
| 選項 | 預設 | 說明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `--email` | (必填) | 帳號 email(唯一) |
|
|
||||||
| `--role` | `user` | `user` 或 `admin` |
|
|
||||||
| `--generate-password` | 互動輸入 | 由 CLI 產生 16 字元隨機密碼(含字母與數字) |
|
|
||||||
|
|
||||||
**行為**:`POST /api/v1/accounts`(免信箱驗證;密碼以明文放入 `hash_password`,伺服器端驗強度後雜湏)。成功印出帳號摘要與一次性密碼區塊:
|
|
||||||
|
|
||||||
```
|
|
||||||
帳號已建立:new@example.com(user)
|
|
||||||
初始密碼(只顯示這一次,請立即保存並轉交當事人):
|
|
||||||
xK7mP9qR2sL4wY6z
|
|
||||||
```
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "account": {…}, "initial_password": "…"}`(密碼只出現這一次)。
|
|
||||||
|
|
||||||
#### 3.9.4 `bear accounts update <email> --role user|admin`
|
|
||||||
|
|
||||||
**行為**:`PUT /api/v1/accounts/{id}`(body 為 role)。成功印出 `alice@example.com:角色 → admin`。伺服器拒絕自降 admin(403)→ 退出碼 `8`。`--role` 罪給或非法 → 退出碼 `2`。
|
|
||||||
|
|
||||||
#### 3.9.5 `bear accounts set-password <email>`
|
|
||||||
|
|
||||||
**行為**:`PUT /api/v1/accounts/{id}/password`(管理員設新密碼,免舊密碼)。密碼來源同 create;非 TTY 且未給 `--generate-password` → 退出碼 `2`,提示加 `--generate-password`。成功後一次性顯示新密碼(同 create 提示)。
|
|
||||||
|
|
||||||
#### 3.9.6 `bear accounts delete <email>`
|
|
||||||
|
|
||||||
**行為**:`DELETE /api/v1/accounts/{id}`(管理端硬刪除,免驗證碼)。成功印出 `已刪除帳號:<email>`;伺服器拒絕自刪(403)→ 退出碼 `8`。
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "email": "alice@example.com", "deleted": true}`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 3.10 `bear audit-logs`:稽核日誌指令群(admin,已實作)
|
|
||||||
|
|
||||||
> 依賵:bear 伺服器端 **稽核日誌 JSON API**(alterminal/bear#36/PR #46,`/api/v1/audit-logs`,PAT Bearer 認證、admin 限定)。API 已上線,本節指令群已實作(issue #12)。
|
|
||||||
|
|
||||||
```
|
|
||||||
bear audit-logs list [--page N] [--per-page N] [--category CATEGORY] [--json]
|
|
||||||
```
|
|
||||||
|
|
||||||
**認證與授權**:同 §3.8(PAT Bearer、僅限 admin;401 → 3;403 → 8)。
|
|
||||||
|
|
||||||
#### 3.10.1 `bear audit-logs list`
|
|
||||||
|
|
||||||
| 選項 | 預設 | 說明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `--page` | `1` | 分頁頁碼 |
|
|
||||||
| `--per-page` | `50` | 每頁筆數(伺服器上限 200) |
|
|
||||||
| `--category` | 全部 | 過濾類別(伺服器端支援;如 `account`、`jwk`) |
|
|
||||||
|
|
||||||
**行為**:`GET /api/v1/audit-logs`(Bearer PAT,最新在前);回應附 `emails` 對照(account/actor id → email),人類可讀輸出以 email 呈現、無對照時顯示 id 前 8 碼:
|
|
||||||
|
|
||||||
```
|
|
||||||
TIME CATEGORY EVENT ACTOR ACCOUNT
|
|
||||||
2026-09-09T01:00:00Z account account_created_by_admin admin@example.com alice@example.com
|
|
||||||
```
|
|
||||||
|
|
||||||
**`--json` 輸出範例**:`{"ok": true, "page": 1, "per_page": 50, "total": 1, "total_pages": 1, "emails": {…}, "entries": […]}`
|
|
||||||
|
|
||||||
### 3.11 `bear vault`:密碼管理指令群(P3,已實作)
|
|
||||||
|
|
||||||
> 依賴:bear 伺服器端 **vault JSON API**(alterminal/bear#41,`/api/v1/vault`、PAT Bearer、任何有效 PAT 帳號)與 Web Vault(P2,alterminal/bear#48/#49)。兩者皆已上線,本節指令群已實作(issue #17)。
|
|
||||||
|
|
||||||
**端到端加密(與 Web Vault 完全一致,同一 vault 兩端互相可解)**:
|
|
||||||
|
|
||||||
- 加密字串 `"2.<iv_b64>.<ct_b64>.<mac_b64>"`:AES-256-CBC+PKCS#7、encrypt-then-MAC(HMAC-SHA-256 over `iv <> ct`)、先驗 MAC 再解密。
|
|
||||||
- K_user 為隨機 64 byte(前 32 enc_key/後 32 mac_key);K_user 的包裝(wrapped key)加密的是 **K_user 的 base64**。
|
|
||||||
- 主金鑰:PBKDF2-SHA512(salt=帳號 email 小寫;迭代數以 `GET /api/v1/vault/config` 公告與 profile 記錄為準,**不寫死**)。
|
|
||||||
- 助記詞:BIP39(12 字、128-bit 熵、英文詞表);救援金鑰=種子 hex → PBKDF2-SHA512(salt=email 小寫)。
|
|
||||||
- 所有加解密全在客戶端(本 CLI)完成;伺服器零解密。
|
|
||||||
|
|
||||||
**K_user 僅存記憶體(不落盤)**:`vault unlock` 解開 K_user 後輸出 session 環境變數設定指令,使用者 `export BEAR_VAULT_SESSION=<base64>` 匯入後,同一 shell 的後續 vault 指令即可解密(同 Bitwarden CLI 的 `BW_SESSION` 慣例;環境變數只存在 shell 記憶體,不寫入任何檔案)。`vault lock` 提示 `unset BEAR_VAULT_SESSION` 即丟棄。
|
|
||||||
|
|
||||||
```
|
|
||||||
bear vault status [--json]
|
|
||||||
bear vault unlock [--json]
|
|
||||||
bear vault lock
|
|
||||||
bear vault list [--folder UUID] [--json]
|
|
||||||
bear vault get <uuid> [--json]
|
|
||||||
bear vault create --type login|secure_note|card|identity [--folder UUID] [--json]
|
|
||||||
bear vault edit <uuid> [--json]
|
|
||||||
bear vault delete <uuid> [--json]
|
|
||||||
bear vault restore <uuid> [--json]
|
|
||||||
bear vault purge <uuid> [--json]
|
|
||||||
bear vault folders list|create|rename <uuid>|delete <uuid> [--json]
|
|
||||||
bear vault sync [--json]
|
|
||||||
bear vault password change [--json]
|
|
||||||
bear vault rescue [--json]
|
|
||||||
```
|
|
||||||
|
|
||||||
**認證與授權(群組共通)**:
|
|
||||||
|
|
||||||
- 使用既有 PAT 憑證(`bear login --token` 或 `BEAR_TOKEN`)作為 Bearer;任何有效 PAT 帳號皆可。
|
|
||||||
- **KDF salt 需要帳號 email**:來源優先序為 `--email EMAIL` 選項>憑證檔記錄的 email>(無法得知 → 用法錯誤 `2`,提示以 `--email` 提供)。一般 `bear login` 後憑證檔即有 email,無需手動給。
|
|
||||||
- `401` → `3`;`403` → `8`;`404`/`422` → `1`;網路/伺服器錯誤 → `6`(沿用 §4 總表)。
|
|
||||||
- **主密碼、助記詞、項目密碼等敏感輸入一律互動提示讀取且不回顧**,不接受命令列明文參數;非 TTY → `2`。名稱、URI、備註等非敏感欄位互動提示可回顯(直接 Enter=保留現值/略過)。
|
|
||||||
- vault 尚未初始化(`GET /profile` 404)→ `vault status` 顯示「尚未初始化」並提示至 Web Vault 設定(初始化產生助記詞的流程在 Web Vault P2,CLI 不重作);其餘需要 profile 的指令 → 退出碼 `1`。
|
|
||||||
|
|
||||||
#### 3.11.1 `bear vault status`
|
|
||||||
|
|
||||||
顯示初始化狀態、KDF 參數、上次同步與本 shell 解鎖狀態(`BEAR_VAULT_SESSION` 是否設定)。`GET /api/v1/vault/config`+`GET /api/v1/vault/profile`。
|
|
||||||
|
|
||||||
**`--json`**:`{"ok": true, "initialized": true, "kdf": {…}, "unlocked": false, …}`;未初始化 → `{"ok": true, "initialized": false, "unlocked": false}`。
|
|
||||||
|
|
||||||
#### 3.11.2 `bear vault unlock`
|
|
||||||
|
|
||||||
互動輸入主密碼(不回顧)→ PBKDF2 推導 K_master → 解開 `wrapped_user_password` 得 K_user → 輸出 `export BEAR_VAULT_SESSION=…`。主密碼錯誤(MAC 驗證失敗)→ 退出碼 `1`(訊息「主密碼不正確」)。
|
|
||||||
|
|
||||||
**`--json`**:`{"ok": true, "session": "<base64>", "env": "BEAR_VAULT_SESSION"}`。
|
|
||||||
|
|
||||||
#### 3.11.3 `bear vault lock`
|
|
||||||
|
|
||||||
K_user 只存在環境變數,本指令提示 `unset BEAR_VAULT_SESSION`(無法代跨 shell unset)。
|
|
||||||
|
|
||||||
#### 3.11.4 `bear vault list [--folder UUID]`
|
|
||||||
|
|
||||||
`GET /api/v1/vault/ciphers`。未解鎖 → 只顯示 UUID/類型(名稱為密文狀態提示);已解鎖 → 一併解密名稱與所屬資料夾名。`--folder` 以 `data.folder_uuid` 過濾(資料夾關聯存在 cipher 的 `data` 欄位,與 Web Vault 一致)。
|
|
||||||
|
|
||||||
```
|
|
||||||
UUID NAME TYPE FOLDER UPDATED STATE
|
|
||||||
c9J2… GitHub login 工作 2026-09-10T05:00:00Z 有效
|
|
||||||
```
|
|
||||||
|
|
||||||
**`--json`**:`{"ok": true, "decrypted": true, "ciphers": […含 "plain" 明文欄位(已解鎖時)…]}`。
|
|
||||||
|
|
||||||
#### 3.11.5 `bear vault get <uuid>`
|
|
||||||
|
|
||||||
`GET /api/v1/vault/ciphers/{uuid}`。已解鎖 → 解密全部欄位(名稱/帳號/密碼/URI/備註/額外資訊);未解鎖 → 顯示密文與提示。密碼欄位只在 stdout 呈現(供腳本擷取),不提供 `--clip`(本版)。
|
|
||||||
|
|
||||||
#### 3.11.6 `bear vault create --type login|secure_note|card|identity [--folder UUID]`
|
|
||||||
|
|
||||||
互動輸入欄位(名稱必填;`login`:帳號/密碼(不回顧)/URI(逗號分隔可多個)/備註;`secure_note`:筆記內容;`card`/`identity`:額外資訊,加密存於 `data.extra`——與 Web Vault 相同的欄位配置)。客戶端加密後 `POST /api/v1/vault/ciphers`(客戶端產生 UUID)。需要解鎖。
|
|
||||||
|
|
||||||
#### 3.11.7 `bear vault edit <uuid>`
|
|
||||||
|
|
||||||
`GET` 現值 → 解密 → 逐欄提示(**直接 Enter=保留現值**;密碼欄不回顧)→ 僅重加密有變更的欄位 → `PUT /api/v1/vault/ciphers/{uuid}`。需要解鎖。
|
|
||||||
|
|
||||||
#### 3.11.8 `bear vault delete/restore/purge <uuid>`
|
|
||||||
|
|
||||||
`delete` → `POST …/{uuid}/delete`(回收桶);`restore` → `POST …/{uuid}/restore`;`purge` → `DELETE …/{uuid}/purge`(**永久刪除,互動確認 `y` 才執行**,其他輸入取消 → 退出碼 `1`)。已回收桶再 delete → `409` → `1`。
|
|
||||||
|
|
||||||
#### 3.11.9 `bear vault folders list|create|rename <uuid>|delete <uuid>`
|
|
||||||
|
|
||||||
資料夾 CRUD(name 客戶端加密):`GET`/`POST`(互動輸入名稱,需解鎖)/`PUT …/{uuid}`(互動輸入新名稱,需解鎖)/`DELETE …/{uuid}`。刪除資料夾不影響所屬項目(僅失去分類)。
|
|
||||||
|
|
||||||
#### 3.11.10 `bear vault sync`
|
|
||||||
|
|
||||||
`GET /api/v1/vault/sync`(伺服器回 profile+folders+ciphers 並標記 `last_synced_at`)。**離線衝突以伺服器為準**(CLI 為無狀態客戶端,不做雙向合併;本機無快取可衝突)。顯示數量統計;`--json` 回完整 sync payload。
|
|
||||||
|
|
||||||
#### 3.11.11 `bear vault password change`
|
|
||||||
|
|
||||||
互動輸入:目前主密碼 → 驗證(解開 wrapped_user_password)→ 新主密碼+確認(≥8 字元,兩次一致)→ 以新 K_master 重新包裝 K_user → `PUT /api/v1/vault/profile`(只動 `wrapped_user_password`,**ciphers 不需重新加密**)。
|
|
||||||
|
|
||||||
#### 3.11.12 `bear vault rescue`
|
|
||||||
|
|
||||||
忘記主密碼的救援路徑:互動輸入助記詞(12 字,會做 BIP39 完整驗證:字數/詞表/校驗和)→ 解開 `wrapped_user_mnemonic` 得 K_user → 設新主密碼(≥8 字元,兩次一致)→ 重新包裝上傳。助記詞錯誤 → 退出碼 `1`。CLI 不提供助記詞顯示(僅 Web Vault 設定時顯示一次)。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -778,7 +191,6 @@ c9J2… GitHub login 工作 2026-09-10T05:0
|
|||||||
| `5` | 授權被拒絕(access_denied) |
|
| `5` | 授權被拒絕(access_denied) |
|
||||||
| `6` | 網路/伺服器錯誤 |
|
| `6` | 網路/伺服器錯誤 |
|
||||||
| `7` | 設定檔/憑證檔格式損毀 |
|
| `7` | 設定檔/憑證檔格式損毀 |
|
||||||
| `8` | 權限不足(HTTP 403;管理端操作僅限 admin:apps/jwks/accounts/audit-logs) |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -787,10 +199,9 @@ c9J2… GitHub login 工作 2026-09-10T05:0
|
|||||||
| 檔 | 路徑 | 內容 | 權限 |
|
| 檔 | 路徑 | 內容 | 權限 |
|
||||||
|----|------|------|------|
|
|----|------|------|------|
|
||||||
| 設定 | `~/.config/bear/config.json` | `issuer`、`client_id`、`scope` | 0644 |
|
| 設定 | `~/.config/bear/config.json` | `issuer`、`client_id`、`scope` | 0644 |
|
||||||
| 憑證 | `~/.local/state/bear/credentials.json` | Device Flow:`refresh_token`+快取 `access_token`/`expires_at`;PAT:`access_token`(無 refresh) | **0600** |
|
| 憑證 | `~/.local/state/bear/credentials.json` | `refresh_token`(優先)+快取 `access_token`/`expires_at` | **0600** |
|
||||||
|
|
||||||
- **Device Flow 只以 refresh token 為主**:access token 短命快取,過期以 refresh token 輪轉換新(沿用 Bear 既有 refresh rotation + 重用偵測)。
|
- **只以 refresh token 為主**:access token 短命快取,過期以 refresh token 輪轉換新(沿用 Bear 既有 refresh rotation + 重用偵測)。
|
||||||
- **PAT 直接存 access token**:無 refresh token、無輪轉;效期由權杖本身的 `expires_at` 決定(可無到期日)。
|
|
||||||
- 寫入憑證檔務必 0600,且以 `O_CREAT|O_EXCL` 防止 symlink 攻擊。
|
- 寫入憑證檔務必 0600,且以 `O_CREAT|O_EXCL` 防止 symlink 攻擊。
|
||||||
- 未來可擴充系統 keyring(libsecret / Keychain),避免明文檔。
|
- 未來可擴充系統 keyring(libsecret / Keychain),避免明文檔。
|
||||||
|
|
||||||
@@ -801,8 +212,6 @@ c9J2… GitHub login 工作 2026-09-10T05:0
|
|||||||
- `authorization_pending`、`slow_down`、`access_denied`、`invalid_grant` 依 RFC 8628 §3.5 顯示對應中文提示。
|
- `authorization_pending`、`slow_down`、`access_denied`、`invalid_grant` 依 RFC 8628 §3.5 顯示對應中文提示。
|
||||||
- 所有診斷訊息走 stderr;`--json` 模式將錯誤以 `{"ok": false, "error": "...", "code": N}` 輸出。
|
- 所有診斷訊息走 stderr;`--json` 模式將錯誤以 `{"ok": false, "error": "...", "code": N}` 輸出。
|
||||||
- token、user_code、device_code 一律不入 log、不入 stdout(除 `bear token` 之目的外)、不入版本庫。
|
- token、user_code、device_code 一律不入 log、不入 stdout(除 `bear token` 之目的外)、不入版本庫。
|
||||||
- `client_secret`(App 管理)僅於 `apps create`/`apps rotate-secret` 成功當下一次性輸出;`403` 顯示「此操作需 admin 權限」並以退出碼 `8` 結束,不重試。
|
|
||||||
- 個人自助的敏感輸入(密碼、email/MFA 驗證碼)一律互動提示、不回顧、不接受命令列參數;一次性明文(`tokens create` 的 PAT、`mfa` 的 recovery codes)僅於成功當下輸出(見 §3.7)。
|
|
||||||
- 網路層一律使用 `Req`,遵循 bear 倉庫 HTTP 客戶端慣例。
|
- 網路層一律使用 `Req`,遵循 bear 倉庫 HTTP 客戶端慣例。
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -811,12 +220,8 @@ c9J2… GitHub login 工作 2026-09-10T05:0
|
|||||||
|
|
||||||
1. CLI 的 OIDC client 採新 `method: "device"`(client auth 為 `none`)或沿用 `PKCE`+JWK?傾向前者(見 bear `cli-feature-plan.md` §5.5)。
|
1. CLI 的 OIDC client 採新 `method: "device"`(client auth 為 `none`)或沿用 `PKCE`+JWK?傾向前者(見 bear `cli-feature-plan.md` §5.5)。
|
||||||
2. 發行格式:escript(目標機需 Erlang)或 self-contained release(bakeware/burrito)?
|
2. 發行格式:escript(目標機需 Erlang)或 self-contained release(bakeware/burrito)?
|
||||||
3. `bear apps list --visibility public` 未來是否開放非 admin(僅公開/active 清單,同網頁 Launch)?目前規劃為 admin 限定。
|
3. `bear apps` 所需的「公開應用清單」API 是否納入 P3?
|
||||||
4. 是否支援 `offline_access` scope,或沿用現行 refresh 輪轉即可?
|
4. 是否支援 `offline_access` scope,或沿用現行 refresh 輪轉即可?
|
||||||
5. 是否在 CLI 提供「建立/撤銷 PAT」?原規劃傾向 CLI 只「使用」不「管理」;#35 的 PAT 端點落地後,`bear tokens` 已納入 §3.7.6 規格(管理自己帳號的 PAT),此題視為已解。
|
|
||||||
6. App 管理 API 的路徑參數最終採 UUID 或 `client_id`(alterminal/bear#28 規格為 `{id}`)?若為 UUID,CLI 需先以 list 解析 `client_id` → UUID,或伺服器提供以 `client_id` 直取的端點。
|
|
||||||
7. `bear profile set --phone-verified`(自我標記電話已驗證)是否開放?#35 已定案:API 接受該欄位(`profile_changeset` 的 `profile_fields` 含 `phone_number_verified`),CLI 保留 `--phone-verified` 旗標(僅設定,清除不在本期)。
|
|
||||||
8. `mfa setup` 的 `secret`/`otpauth://` 屬敏感資料,#35 的 API 回應是否應限制僅 setup 流程期間回傳(未確認前不重送)?#38 實作為 setup 回應一次性回傳,未確認前重呼 setup 會重產 secret;CLI 依此實作(第二步走 `/mfa/setup/confirm`)。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -825,60 +230,27 @@ c9J2… GitHub login 工作 2026-09-10T05:0
|
|||||||
| 本指令 | 對應 OIDC/Bear 端點 |
|
| 本指令 | 對應 OIDC/Bear 端點 |
|
||||||
|--------|----------------------|
|
|--------|----------------------|
|
||||||
| `login` | `/.well-known/openid-configuration` → `POST /device_authorization` → `POST /token`(device_code) |
|
| `login` | `/.well-known/openid-configuration` → `POST /device_authorization` → `POST /token`(device_code) |
|
||||||
| `login --token <PAT>` | `GET /userinfo`(Bearer PAT 驗證身分,無 OIDC 端點) |
|
| `whoami` | `GET /userinfo` |
|
||||||
| `whoami` | `GET /userinfo`(接受 OIDC access token 或 PAT) |
|
| `token --refresh` | `POST /token`(refresh_token) |
|
||||||
| `token --refresh` | `POST /token`(refresh_token,僅 Device Flow) |
|
| `logout` | `POST /revoke` |
|
||||||
| `logout` | `POST /revoke`(僅 Device Flow;PAT 僅本機刪除,撤銷走網頁 `/profile/tokens`) |
|
| `apps`(P3) | 待新增「公開應用清單」API |
|
||||||
| `apps list` | `GET /api/v1/apps`(Bearer PAT;分頁 `page`/`per_page`) |
|
|
||||||
| `apps show` | `GET /api/v1/apps/{id}` |
|
|
||||||
| `apps create` | `POST /api/v1/apps` |
|
|
||||||
| `apps update` | `PUT /api/v1/apps/{id}` |
|
|
||||||
| `apps rotate-secret` | `POST /api/v1/apps/{id}/rotate-secret` |
|
|
||||||
| `apps toggle` | `POST /api/v1/apps/{id}/toggle` |
|
|
||||||
| `profile show` | `GET /api/v1/profile` |
|
|
||||||
| `profile set` | `PUT /api/v1/profile` |
|
|
||||||
| `password change` | `POST /api/v1/profile/password` |
|
|
||||||
| `email change` | `POST /api/v1/profile/email/request-codes` → `POST /api/v1/profile/email` |
|
|
||||||
| `sessions list` | `GET /api/v1/profile/sessions` |
|
|
||||||
| `sessions revoke <id>` | `POST /api/v1/profile/sessions/{id}/revoke` |
|
|
||||||
| `sessions revoke-others` | `POST /api/v1/profile/sessions/revoke-others` |
|
|
||||||
| `tokens list` | `GET /api/v1/profile/tokens` |
|
|
||||||
| `tokens create` | `POST /api/v1/profile/tokens` |
|
|
||||||
| `tokens revoke <id>` | `POST /api/v1/profile/tokens/{id}/revoke` |
|
|
||||||
| `mfa status` | `GET /api/v1/profile`(讀 MFA 欄位) |
|
|
||||||
| `mfa setup` | `POST /api/v1/profile/mfa/setup`(取 secret)→ `POST /api/v1/profile/mfa/setup/confirm`(帶 code 確認) |
|
|
||||||
| `mfa disable` | `POST /api/v1/profile/mfa/disable` |
|
|
||||||
| `mfa recovery-codes` | `POST /api/v1/profile/mfa/recovery-codes` |
|
|
||||||
|
|
||||||
> `apps` 群組依賴 alterminal/bear#28 的 App 管理 JSON API(PAT Bearer、admin 限定);`profile` 系列依賴 alterminal/bear#35 的個人自助 JSON API(PAT Bearer、任何有效帳號)。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 9. 現行實作狀態(PAT 模式 MVP,issue #6)
|
## 9. PAT 模式與原規格差異(現行實作)
|
||||||
|
|
||||||
目前實作為 **PAT 模式 MVP**(Elixir + Req、mix escript),與上方 Device Flow 規格的差異:
|
目前實作為 PAT 模式 MVP,與上方 Device Flow 規格有以下差異:
|
||||||
|
|
||||||
| 指令 | 原規格(Device Flow) | 現行實作(PAT 模式) |
|
| 指令 | 原規格(Device Flow) | PAT 模式現行行為 |
|
||||||
|------|----------------------|----------------------|
|
|------|----------------------|------------------|
|
||||||
| `login` | 裝置碼流程 | `--token <PAT>` 驗證 `GET /userinfo` 後保存(`-` 可從 stdin 讀);未給 `--token` 時提示 Device Flow 尚未開放(退出碼 2) |
|
| `login` | 裝置碼流程 | `--token <PAT>` 驗證 `/userinfo` 後保存 |
|
||||||
| `whoami` | `GET /userinfo`(refresh 輪轉) | `GET /userinfo`(Bearer PAT,無輪轉);`BEAR_TOKEN` 提供時優先使用 |
|
| `whoami` | `GET /userinfo`(refresh 輪轉) | `GET /userinfo`(Bearer PAT,無輪轉) |
|
||||||
| `token` | refresh token 輪轉換新 | 直接印出 PAT;`--refresh` 為用法錯誤(退出碼 2);`BEAR_TOKEN` 提供時優先印出 |
|
| `token --refresh` | refresh token 輪轉換新 | 無 refresh token,`--refresh` 忽略並警告 |
|
||||||
| `logout` | `POST /revoke`(撤銷 refresh token) | 僅清除本機憑證;PAT 需至網頁 `/profile/tokens` 撤銷 |
|
| `logout` | `POST /revoke`(撤銷 refresh token) | 僅清除本機憑證;PAT 需至網頁撤銷 |
|
||||||
| `status` | 顯示 access token 剩餘秒數 | 純本機判定:顯示模式(PAT/BEAR_TOKEN 環境變數)與 issuer |
|
| `status` | 顯示 access token 剩餘秒數 | 顯示 PAT 模式與 issuer(PAT 無效期資訊) |
|
||||||
| `apps` | P3 暫緩 | ✅ 已實作(issue #10):`list`/`show`/`create`/`update`/`rotate-secret`/`toggle`,對接 alterminal/bear#28 的 `/api/v1/apps` JSON API(PAT Bearer、admin 限定)。`client_id` → UUID 由 CLI 以 list 解析;一次性 `client_secret` 僅於 create/rotate-secret 成功當下輸出 |
|
|
||||||
| `profile`/`password`/`email`/`sessions`/`tokens`/`mfa` | P3 暫緩 | ✅ 已實作(issue #11):`profile show/set`、`password change`、`email change`、`sessions list/revoke/revoke-others`、`tokens list/create/revoke`、`mfa status/setup/disable/recovery-codes`,對接 alterminal/bear#38 的 `/api/v1/profile*` JSON API(PAT Bearer、任何有效帳號)。敏感輸入互動提示;一次性明文(PAT 明文、recovery codes)僅於成功當下輸出;mfa setup 的 ASCII QR 由本機 eqrcode 生成 |
|
|
||||||
| `jwks`/`accounts`/`audit-logs` | P3 暫緩 | ✅ 已實作(issue #12):對接 alterminal/bear#46 的管理端 JSON API(PAT Bearer、admin 限定);規格見 §3.8–§3.10 |
|
|
||||||
|
|
||||||
退出碼差異:`login`/`whoami` 的 token 無效(401)依 §3.1 為 `3`(本節實作一致)。
|
憑證檔結構(PAT 模式):
|
||||||
|
|
||||||
憑證檔結構(PAT 模式,0600、原子寫入、O_EXCL):
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{"issuer": "https://alterminal.com", "access_token": "<PAT>", "email": "..."}
|
{"issuer": "https://alterminal.com", "access_token": "<PAT>", "email": "..."}
|
||||||
```
|
```
|
||||||
|
|
||||||
建置:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
mix deps.get && mix test && mix escript.build # 產生單檔可執行 bear
|
|
||||||
```
|
|
||||||
|
|||||||
@@ -1,351 +0,0 @@
|
|||||||
defmodule BearCli.Accounts do
|
|
||||||
@moduledoc """
|
|
||||||
`bear accounts` 指令群(帳號管理;docs/commands.md §3.9、issue #12)。
|
|
||||||
|
|
||||||
對應伺服器端帳號管理 JSON API(alterminal/bear#46,`/api/v1/accounts`、
|
|
||||||
PAT Bearer、admin 限定)。認證沿用既有 PAT 憑證(`BEAR_TOKEN` 或憑證檔)。
|
|
||||||
|
|
||||||
CLI 對外介面一律以 `email` 識別帳號(人類可讀、唯一);API 路徑參數為
|
|
||||||
UUID,由本模組先以 list 分頁比對解析。帳號 JSON 不含 `hash_password`、
|
|
||||||
`totp_secret` 等機密欄位(API 端保證),CLI 亦不顯示。
|
|
||||||
|
|
||||||
`create`/`set-password` 未給 `--password` 時由 CLI 產生隨機密碼,並只在
|
|
||||||
成功當下一次性輸出(不寫入憑證檔/log/`--verbose`);密碼一律不進命令列
|
|
||||||
(避免 shell history/`ps`),改以互動輸入(不回顧)或 `--generate-password`。
|
|
||||||
|
|
||||||
敏感規則與伺服器端一致:不可移除自己的 admin 角色(403)、不可刪除自己(403)。
|
|
||||||
|
|
||||||
退出碼:0 成功;1 404/422;2 用法錯誤;3 未登入或 401;6 網路/伺服器
|
|
||||||
錯誤;8 權限不足(403,僅限 admin)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import BearCli.Admin, only: [context: 1, fail: 3, format_api_error: 2]
|
|
||||||
alias BearCli.Api
|
|
||||||
alias BearCli.TTY
|
|
||||||
|
|
||||||
@list_per_page_fetch 100
|
|
||||||
@max_fetch_pages 50
|
|
||||||
|
|
||||||
# -- 入口 --
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
執行 `bear accounts <動詞>`,回傳退出碼。`opts[:accounts_api]` 可注入假
|
|
||||||
API 模組供測試(需實作 `accounts_list/3`、`accounts_create/3`、
|
|
||||||
`accounts_get/3`、`accounts_update_role/4`、`accounts_set_password/4`、
|
|
||||||
`accounts_delete/3`)。
|
|
||||||
"""
|
|
||||||
def run(verb, opts) do
|
|
||||||
api = opts[:accounts_api] || Api
|
|
||||||
|
|
||||||
with {:ok, ctx} <- context(opts) do
|
|
||||||
execute(verb, ctx, opts, api)
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 各動詞 --
|
|
||||||
|
|
||||||
defp execute(:list, ctx, opts, api) do
|
|
||||||
params = [page: opts[:page] || 1, per_page: opts[:per_page] || 20]
|
|
||||||
|
|
||||||
case api.accounts_list(ctx.issuer, ctx.token, params) do
|
|
||||||
{:ok, body} ->
|
|
||||||
accounts = body["data"] || []
|
|
||||||
page = body["page"] || params[:page]
|
|
||||||
per_page = body["per_page"] || params[:per_page]
|
|
||||||
total = body["total"] || length(accounts)
|
|
||||||
render_list(opts, accounts, page, per_page, total)
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:show, ctx, opts, api) do
|
|
||||||
with {:ok, account} <- resolve_account(ctx, opts[:email_arg], api) do
|
|
||||||
case api.accounts_get(ctx.issuer, ctx.token, account["id"]) do
|
|
||||||
{:ok, body} ->
|
|
||||||
show_account(body["data"] || %{}, opts)
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:create, ctx, opts, api) do
|
|
||||||
with {:ok, password} <- read_password(opts) do
|
|
||||||
attrs = %{"email" => opts[:email], "hash_password" => password}
|
|
||||||
attrs = if opts[:role], do: Map.put(attrs, "role", opts[:role]), else: attrs
|
|
||||||
|
|
||||||
case api.accounts_create(ctx.issuer, ctx.token, attrs) do
|
|
||||||
{:ok, body} ->
|
|
||||||
account = body["data"] || %{}
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, account: account, initial_password: password}))
|
|
||||||
else
|
|
||||||
IO.puts("帳號已建立:#{account["email"]}(#{account["role"]})")
|
|
||||||
print_password_block(password)
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:update, ctx, opts, api) do
|
|
||||||
with {:ok, account} <- resolve_account(ctx, opts[:email_arg], api) do
|
|
||||||
case api.accounts_update_role(ctx.issuer, ctx.token, account["id"], %{"role" => opts[:role]}) do
|
|
||||||
{:ok, body} ->
|
|
||||||
updated = body["data"] || %{}
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, account: updated}))
|
|
||||||
else
|
|
||||||
IO.puts("#{updated["email"]}:角色 → #{updated["role"]}")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:"set-password", ctx, opts, api) do
|
|
||||||
with {:ok, account} <- resolve_account(ctx, opts[:email_arg], api),
|
|
||||||
{:ok, password} <- read_password(opts) do
|
|
||||||
case api.accounts_set_password(ctx.issuer, ctx.token, account["id"], %{
|
|
||||||
"hash_password" => password
|
|
||||||
}) do
|
|
||||||
{:ok, _body} ->
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, email: account["email"], new_password: password}))
|
|
||||||
else
|
|
||||||
IO.puts("已為 #{account["email"]} 設定新密碼。")
|
|
||||||
print_password_block(password)
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:delete, ctx, opts, api) do
|
|
||||||
with {:ok, account} <- resolve_account(ctx, opts[:email_arg], api) do
|
|
||||||
case api.accounts_delete(ctx.issuer, ctx.token, account["id"]) do
|
|
||||||
{:ok, _body} ->
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, email: account["email"], deleted: true}))
|
|
||||||
else
|
|
||||||
IO.puts("已刪除帳號:#{account["email"]}")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- email → UUID 解析(分頁全量列舉比對;設頁數上限避免無限迴圈)--
|
|
||||||
|
|
||||||
defp resolve_account(_ctx, nil, _api), do: {:error, "缺少 <email> 參數", 2}
|
|
||||||
|
|
||||||
defp resolve_account(ctx, email, api) do
|
|
||||||
with {:ok, all} <- fetch_all(ctx, api) do
|
|
||||||
case Enum.find(all, &(&1["email"] == email)) do
|
|
||||||
nil -> {:error, "找不到 email 為 #{email} 的帳號", 1}
|
|
||||||
account -> {:ok, account}
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> {:error, message, code}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp fetch_all(ctx, api) do
|
|
||||||
do_fetch_all(ctx, api, 1, [])
|
|
||||||
end
|
|
||||||
|
|
||||||
defp do_fetch_all(_ctx, _api, page, acc) when page > @max_fetch_pages, do: {:ok, acc}
|
|
||||||
|
|
||||||
defp do_fetch_all(ctx, api, page, acc) do
|
|
||||||
case api.accounts_list(ctx.issuer, ctx.token, page: page, per_page: @list_per_page_fetch) do
|
|
||||||
{:ok, body} ->
|
|
||||||
entries = body["data"] || []
|
|
||||||
acc = acc ++ entries
|
|
||||||
total = body["total"]
|
|
||||||
|
|
||||||
if entries == [] or length(entries) < @list_per_page_fetch or
|
|
||||||
(is_integer(total) and length(acc) >= total) do
|
|
||||||
{:ok, acc}
|
|
||||||
else
|
|
||||||
do_fetch_all(ctx, api, page + 1, acc)
|
|
||||||
end
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
{message, code} = format_api_error(ctx, error)
|
|
||||||
{:error, message, code}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 密碼輸入(不進命令列;非 TTY 且未 --generate-password → 用法錯誤)--
|
|
||||||
|
|
||||||
defp read_password(%{generate_password: true}), do: {:ok, generate_password()}
|
|
||||||
|
|
||||||
defp read_password(_opts) do
|
|
||||||
if tty?() do
|
|
||||||
password = prompt_password("新密碼(至少 8 字元,含字母與數字):")
|
|
||||||
confirm = prompt_password("再次輸入新密碼:")
|
|
||||||
|
|
||||||
cond do
|
|
||||||
password != confirm ->
|
|
||||||
{:error, "兩次輸入的密碼不一致", 2}
|
|
||||||
|
|
||||||
weak_password?(password) ->
|
|
||||||
{:error, "密碼至少 8 字元且須包含字母與數字", 2}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, password}
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, "非 TTY 環境無法互動輸入密碼;請加 --generate-password 由 CLI 產生", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
@password_chars "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789"
|
|
||||||
@password_length 16
|
|
||||||
|
|
||||||
defp generate_password do
|
|
||||||
@password_chars
|
|
||||||
|> String.codepoints()
|
|
||||||
|> Enum.take_random(@password_length)
|
|
||||||
|> Enum.join()
|
|
||||||
end
|
|
||||||
|
|
||||||
defp weak_password?(password) when is_binary(password) do
|
|
||||||
String.length(password) >= 8 and Regex.match?(~r/[a-zA-Z]/, password) and
|
|
||||||
Regex.match?(~r/[0-9]/, password)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp weak_password?(_), do: true
|
|
||||||
|
|
||||||
# stdin 是否為 TTY:優先以 fd 0 實際裝置判定(escript 環境 :io.columns/0
|
|
||||||
# 一律 enotsup,真終端機會被誤判;見 BearCli.TTY,issue #19)。
|
|
||||||
defp tty? do
|
|
||||||
TTY.stdin_tty?()
|
|
||||||
end
|
|
||||||
|
|
||||||
defp prompt_password(prompt) do
|
|
||||||
IO.puts(:stderr, prompt)
|
|
||||||
IO.gets("") |> String.trim_trailing("\n")
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 輸出 --
|
|
||||||
|
|
||||||
defp render_list(opts, accounts, page, per_page, total) do
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(
|
|
||||||
Jason.encode!(%{
|
|
||||||
ok: true,
|
|
||||||
page: page,
|
|
||||||
per_page: per_page,
|
|
||||||
total: total,
|
|
||||||
accounts: accounts
|
|
||||||
})
|
|
||||||
)
|
|
||||||
else
|
|
||||||
print_table(accounts)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
@table_headers ["EMAIL", "ROLE", "TOTP", "CREATED AT"]
|
|
||||||
|
|
||||||
defp print_table(accounts) do
|
|
||||||
rows =
|
|
||||||
Enum.map(accounts, fn account ->
|
|
||||||
[
|
|
||||||
account["email"] || "",
|
|
||||||
account["role"] || "",
|
|
||||||
totp_label(account["totp_enabled"]),
|
|
||||||
account["created_at"] || ""
|
|
||||||
]
|
|
||||||
end)
|
|
||||||
|
|
||||||
widths =
|
|
||||||
Enum.with_index(@table_headers, fn _header, i ->
|
|
||||||
Enum.max([
|
|
||||||
String.length(Enum.at(@table_headers, i))
|
|
||||||
| Enum.map(rows, &String.length(Enum.at(&1, i)))
|
|
||||||
])
|
|
||||||
end)
|
|
||||||
|
|
||||||
render_row = fn cells ->
|
|
||||||
cells
|
|
||||||
|> Enum.with_index()
|
|
||||||
|> Enum.map(fn {cell, i} -> String.pad_trailing(cell, Enum.at(widths, i)) end)
|
|
||||||
|> Enum.join(" ")
|
|
||||||
|> String.trim_trailing()
|
|
||||||
end
|
|
||||||
|
|
||||||
IO.puts(render_row.(@table_headers))
|
|
||||||
Enum.each(rows, fn cells -> IO.puts(render_row.(cells)) end)
|
|
||||||
end
|
|
||||||
|
|
||||||
@account_fields ~w(id email role totp_enabled created_at updated_at)
|
|
||||||
|
|
||||||
defp show_account(account, opts) do
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, account: account}))
|
|
||||||
else
|
|
||||||
Enum.each(@account_fields, fn field ->
|
|
||||||
IO.puts("#{String.pad_trailing(field, 16)}: #{format_account_value(account[field])}")
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_account_value(nil), do: "(無)"
|
|
||||||
defp format_account_value(true), do: "已啟用"
|
|
||||||
defp format_account_value(false), do: "未啟用"
|
|
||||||
defp format_account_value(value) when is_binary(value), do: value
|
|
||||||
defp format_account_value(value), do: Jason.encode!(value)
|
|
||||||
|
|
||||||
defp totp_label(true), do: "on"
|
|
||||||
defp totp_label(false), do: "off"
|
|
||||||
defp totp_label(_), do: "(未知)"
|
|
||||||
|
|
||||||
# 初始/新密碼只在成功當下一次性輸出(不寫入憑證檔/log/--verbose)。
|
|
||||||
defp print_password_block(password) do
|
|
||||||
IO.puts("初始密碼(只顯示這一次,請立即保存並轉交當事人):")
|
|
||||||
IO.puts(" #{password}")
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 錯誤處理 --
|
|
||||||
|
|
||||||
defp fail_api(opts, ctx, error) do
|
|
||||||
{message, code} = format_api_error(ctx, error)
|
|
||||||
fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,273 +0,0 @@
|
|||||||
defmodule BearCli.Admin do
|
|
||||||
@moduledoc """
|
|
||||||
`bear jwks`/`bear accounts`/`bear audit-logs` 管理端指令群的共用層
|
|
||||||
(docs/commands.md §3.8–§3.10、issue #12)。
|
|
||||||
|
|
||||||
`parse/3` 由 `BearCli.CLI` 的 fallback 分派呼叫,負責解析三個資源群組的
|
|
||||||
子指令與選項並做本地用法驗證;`context/1`/`fail/3`/`format_api_error/3`
|
|
||||||
為各群組模組共用的背景與錯誤處理。
|
|
||||||
"""
|
|
||||||
|
|
||||||
alias BearCli.{Accounts, AuditLogs, Config, Credentials, Jwks}
|
|
||||||
|
|
||||||
@jwks_verbs ~w(list show create toggle)
|
|
||||||
@accounts_verbs ~w(list show create update set-password delete)
|
|
||||||
@audit_logs_verbs ~w(list)
|
|
||||||
|
|
||||||
@jwks_create_switches [kid: :string, alg: :string]
|
|
||||||
|
|
||||||
@accounts_list_switches [page: :integer, per_page: :integer]
|
|
||||||
@accounts_create_switches [email: :string, role: :string, generate_password: :boolean]
|
|
||||||
@accounts_update_switches [role: :string]
|
|
||||||
@accounts_set_password_switches [generate_password: :boolean]
|
|
||||||
|
|
||||||
@audit_logs_list_switches [page: :integer, per_page: :integer, category: :string]
|
|
||||||
|
|
||||||
@algs ~w(RS256 RS384 RS512 ES256 ES384 ES512)
|
|
||||||
@roles ~w(user admin)
|
|
||||||
|
|
||||||
@global_switches [
|
|
||||||
issuer: :string,
|
|
||||||
config: :string,
|
|
||||||
json: :boolean,
|
|
||||||
verbose: :boolean,
|
|
||||||
help: :boolean,
|
|
||||||
version: :boolean
|
|
||||||
]
|
|
||||||
|
|
||||||
# -- 解析(非管理端指令回 :error,交回 CLI 報未知指令)--
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
解析 `jwks`/`accounts`/`audit-logs` 群組的 argv,回傳 `{:ok, {module, verb}, opts}`
|
|
||||||
或 `{:error, message, code}`;非本層負責的指令回 `:error`。
|
|
||||||
"""
|
|
||||||
def parse(["jwks" | rest], global), do: parse_group("jwks", @jwks_verbs, rest, global)
|
|
||||||
|
|
||||||
def parse(["accounts" | rest], global),
|
|
||||||
do: parse_group("accounts", @accounts_verbs, rest, global)
|
|
||||||
|
|
||||||
def parse(["audit-logs" | rest], global),
|
|
||||||
do: parse_group("audit-logs", @audit_logs_verbs, rest, global)
|
|
||||||
|
|
||||||
def parse(_, _), do: :error
|
|
||||||
|
|
||||||
defp parse_group(group, verbs, rest, global) do
|
|
||||||
case rest do
|
|
||||||
[verb | args] ->
|
|
||||||
if verb in verbs do
|
|
||||||
switches = group_switches(group, verb)
|
|
||||||
|
|
||||||
case OptionParser.parse(args, strict: @global_switches ++ switches) do
|
|
||||||
{opts, positionals, []} ->
|
|
||||||
validate(group, verb, positionals, merge_opts(global, opts_to_map(opts)))
|
|
||||||
|
|
||||||
{_opts, _extra, [{opt, _} | _]} ->
|
|
||||||
{:error, "無法解析選項:#{opt}", 2}
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, "未知的 #{group} 子指令:#{verb}(可用:#{Enum.join(verbs, " ")})", 2}
|
|
||||||
end
|
|
||||||
|
|
||||||
[] ->
|
|
||||||
{:error, "#{group} 缺少子指令(可用:#{Enum.join(verbs, " ")})", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp group_switches("jwks", "list"), do: []
|
|
||||||
defp group_switches("jwks", "show"), do: []
|
|
||||||
defp group_switches("jwks", "create"), do: @jwks_create_switches
|
|
||||||
defp group_switches("jwks", "toggle"), do: []
|
|
||||||
defp group_switches("accounts", "list"), do: @accounts_list_switches
|
|
||||||
defp group_switches("accounts", "show"), do: []
|
|
||||||
defp group_switches("accounts", "create"), do: @accounts_create_switches
|
|
||||||
defp group_switches("accounts", "update"), do: @accounts_update_switches
|
|
||||||
defp group_switches("accounts", "set-password"), do: @accounts_set_password_switches
|
|
||||||
defp group_switches("accounts", "delete"), do: []
|
|
||||||
defp group_switches("audit-logs", "list"), do: @audit_logs_list_switches
|
|
||||||
|
|
||||||
# keyword 轉 map(本層無 :keep 選項,直接 Map.new)。
|
|
||||||
defp opts_to_map(opts), do: Map.new(opts)
|
|
||||||
|
|
||||||
defp merge_opts(global, opts), do: Map.merge(Map.new(global), opts)
|
|
||||||
|
|
||||||
# -- 本地用法驗證(用法錯誤 → 退出碼 2)--
|
|
||||||
|
|
||||||
# jwks
|
|
||||||
defp validate("jwks", "list", [], opts), do: {:ok, {Jwks, :list}, opts}
|
|
||||||
defp validate("jwks", "list", extra, _opts), do: positional_error("jwks list", extra, 0)
|
|
||||||
|
|
||||||
defp validate("jwks", "show", [kid], opts),
|
|
||||||
do: {:ok, {Jwks, :show}, Map.put(opts, :kid_arg, kid)}
|
|
||||||
|
|
||||||
defp validate("jwks", "show", [], _opts), do: {:error, "jwks show 缺少 <kid>", 2}
|
|
||||||
defp validate("jwks", "show", extra, _opts), do: positional_error("jwks show", extra, 1)
|
|
||||||
|
|
||||||
defp validate("jwks", "create", [], opts) do
|
|
||||||
cond do
|
|
||||||
blank?(opts[:kid]) ->
|
|
||||||
{:error, "jwks create 缺少必選參數:--kid", 2}
|
|
||||||
|
|
||||||
opts[:alg] && opts[:alg] not in @algs ->
|
|
||||||
{:error, "--alg 不接受的值:#{opts[:alg]}(可用:#{Enum.join(@algs, "、")})", 2}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, {Jwks, :create}, opts}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp validate("jwks", "create", extra, _opts), do: positional_error("jwks create", extra, 0)
|
|
||||||
|
|
||||||
defp validate("jwks", "toggle", [kid], opts),
|
|
||||||
do: {:ok, {Jwks, :toggle}, Map.put(opts, :kid_arg, kid)}
|
|
||||||
|
|
||||||
defp validate("jwks", "toggle", [], _opts), do: {:error, "jwks toggle 缺少 <kid>", 2}
|
|
||||||
defp validate("jwks", "toggle", extra, _opts), do: positional_error("jwks toggle", extra, 1)
|
|
||||||
|
|
||||||
# accounts
|
|
||||||
defp validate("accounts", "list", [], opts), do: {:ok, {Accounts, :list}, opts}
|
|
||||||
defp validate("accounts", "list", extra, _opts), do: positional_error("accounts list", extra, 0)
|
|
||||||
|
|
||||||
defp validate("accounts", "show", [email], opts),
|
|
||||||
do: {:ok, {Accounts, :show}, Map.put(opts, :email_arg, email)}
|
|
||||||
|
|
||||||
defp validate("accounts", "show", [], _opts), do: {:error, "accounts show 缺少 <email>", 2}
|
|
||||||
defp validate("accounts", "show", extra, _opts), do: positional_error("accounts show", extra, 1)
|
|
||||||
|
|
||||||
defp validate("accounts", "create", [], opts) do
|
|
||||||
cond do
|
|
||||||
blank?(opts[:email]) ->
|
|
||||||
{:error, "accounts create 缺少必選參數:--email", 2}
|
|
||||||
|
|
||||||
opts[:role] && opts[:role] not in @roles ->
|
|
||||||
{:error, "--role 不接受的值:#{opts[:role]}(可用:#{Enum.join(@roles, "、")})", 2}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, {Accounts, :create}, opts}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp validate("accounts", "create", extra, _opts),
|
|
||||||
do: positional_error("accounts create", extra, 0)
|
|
||||||
|
|
||||||
defp validate("accounts", "update", [email], opts) do
|
|
||||||
if blank?(opts[:role]) or opts[:role] not in @roles do
|
|
||||||
{:error, "accounts update 必須給 --role user|admin", 2}
|
|
||||||
else
|
|
||||||
{:ok, {Accounts, :update}, Map.put(opts, :email_arg, email)}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp validate("accounts", "update", [], _opts), do: {:error, "accounts update 缺少 <email>", 2}
|
|
||||||
|
|
||||||
defp validate("accounts", "update", extra, _opts),
|
|
||||||
do: positional_error("accounts update", extra, 1)
|
|
||||||
|
|
||||||
defp validate("accounts", "set-password", [email], opts),
|
|
||||||
do: {:ok, {Accounts, :"set-password"}, Map.put(opts, :email_arg, email)}
|
|
||||||
|
|
||||||
defp validate("accounts", "set-password", [], _opts),
|
|
||||||
do: {:error, "accounts set-password 缺少 <email>", 2}
|
|
||||||
|
|
||||||
defp validate("accounts", "set-password", extra, _opts),
|
|
||||||
do: positional_error("accounts set-password", extra, 1)
|
|
||||||
|
|
||||||
defp validate("accounts", "delete", [email], opts),
|
|
||||||
do: {:ok, {Accounts, :delete}, Map.put(opts, :email_arg, email)}
|
|
||||||
|
|
||||||
defp validate("accounts", "delete", [], _opts), do: {:error, "accounts delete 缺少 <email>", 2}
|
|
||||||
|
|
||||||
defp validate("accounts", "delete", extra, _opts),
|
|
||||||
do: positional_error("accounts delete", extra, 1)
|
|
||||||
|
|
||||||
# audit-logs
|
|
||||||
defp validate("audit-logs", "list", [], opts), do: {:ok, {AuditLogs, :list}, opts}
|
|
||||||
|
|
||||||
defp validate("audit-logs", "list", extra, _opts),
|
|
||||||
do: positional_error("audit-logs list", extra, 0)
|
|
||||||
|
|
||||||
defp positional_error(command, extra, _max) do
|
|
||||||
{:error, "#{command} 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 共用背景(token/issuer;三個群組模組共用)--
|
|
||||||
|
|
||||||
@doc "解析 token/issuer 背景,回傳 {:ok, ctx} 或 {:error, message, code}。"
|
|
||||||
def context(opts) do
|
|
||||||
if token = Config.env_token() do
|
|
||||||
# BEAR_TOKEN 優先於憑證檔(不讀檔、不寫檔)。
|
|
||||||
{:ok, %{token: token, issuer: resolve_issuer(opts, nil)}}
|
|
||||||
else
|
|
||||||
case Credentials.load() do
|
|
||||||
{:ok, creds} ->
|
|
||||||
token = creds["access_token"]
|
|
||||||
|
|
||||||
if blank?(token) do
|
|
||||||
{:error, "憑證檔缺少 access_token,請重新 bear login", 7}
|
|
||||||
else
|
|
||||||
{:ok, %{token: token, issuer: resolve_issuer(opts, creds["issuer"])}}
|
|
||||||
end
|
|
||||||
|
|
||||||
:error ->
|
|
||||||
{:error, "未登入(請先執行 bear login)", 3}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp resolve_issuer(opts, stored_issuer) do
|
|
||||||
opts[:issuer] || stored_issuer || Config.resolve_issuer(nil, opts[:config])
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 共用錯誤處理 --
|
|
||||||
|
|
||||||
@doc "輸出錯誤(--json 走 stdout JSON、人類模式走 stderr),回傳退出碼。"
|
|
||||||
def fail(opts, message, code) do
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: false, error: message, code: code}))
|
|
||||||
else
|
|
||||||
IO.puts(:stderr, "錯誤:#{message}")
|
|
||||||
end
|
|
||||||
|
|
||||||
code
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "API 錯誤 → 訊息與退出碼(管理端共通對應)。"
|
|
||||||
def format_api_error(_ctx, {:error, :unauthorized, desc}) do
|
|
||||||
{"token 無效或已過期(#{desc}),請重新 bear login", 3}
|
|
||||||
end
|
|
||||||
|
|
||||||
def format_api_error(_ctx, {:error, :forbidden, _desc}) do
|
|
||||||
{"此操作需 admin 權限(HTTP 403)", 8}
|
|
||||||
end
|
|
||||||
|
|
||||||
def format_api_error(_ctx, {:error, :not_found, _desc}) do
|
|
||||||
{"找不到目標資源(HTTP 404)", 1}
|
|
||||||
end
|
|
||||||
|
|
||||||
def format_api_error(_ctx, {:error, :unprocessable_entity, body}) do
|
|
||||||
details =
|
|
||||||
body
|
|
||||||
|> Map.get("errors", %{})
|
|
||||||
|> Enum.map(fn {field, messages} ->
|
|
||||||
"#{field}: #{Enum.join(List.wrap(messages), "、")}"
|
|
||||||
end)
|
|
||||||
|> Enum.join(";")
|
|
||||||
|
|
||||||
if details == "" do
|
|
||||||
{"驗證失敗(HTTP 422)", 1}
|
|
||||||
else
|
|
||||||
{"驗證失敗(HTTP 422):#{details}", 1}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def format_api_error(_ctx, {:error, :server_error, status}) do
|
|
||||||
{"伺服器回應 #{status}", 6}
|
|
||||||
end
|
|
||||||
|
|
||||||
def format_api_error(ctx, {:error, :network, reason}) do
|
|
||||||
{"無法連線到 #{ctx.issuer}:#{reason}", 6}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp blank?(nil), do: true
|
|
||||||
defp blank?(""), do: true
|
|
||||||
defp blank?(_), do: false
|
|
||||||
end
|
|
||||||
+1
-379
@@ -2,12 +2,7 @@ defmodule BearCli.Api do
|
|||||||
@moduledoc """
|
@moduledoc """
|
||||||
Bear 伺服器 HTTP 介面(一律使用 `Req`)。
|
Bear 伺服器 HTTP 介面(一律使用 `Req`)。
|
||||||
|
|
||||||
- `GET /userinfo`:PAT 模式身分驗證(issue #6)。
|
目前僅實作 PAT 模式所需的 `GET /userinfo`。
|
||||||
- App 管理 API `/api/v1/apps`(alterminal/bear#28;PAT Bearer、admin 限定)。
|
|
||||||
- 個人自助 API `/api/v1/profile*`(alterminal/bear#35;PAT Bearer、
|
|
||||||
任何有效帳號):profile/密碼/email/sessions/PAT/MFA。
|
|
||||||
- 管理端 API `/api/v1/jwks`/`/api/v1/accounts`/`/api/v1/audit-logs`
|
|
||||||
(alterminal/bear#36; PAT Bearer, admin only).
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@finch BearCli.Finch
|
@finch BearCli.Finch
|
||||||
@@ -56,377 +51,4 @@ defmodule BearCli.Api do
|
|||||||
end
|
end
|
||||||
|
|
||||||
defp error_description(_), do: "invalid_token"
|
defp error_description(_), do: "invalid_token"
|
||||||
|
|
||||||
# -- App 管理 API(alterminal/bear#28;PAT Bearer、admin 限定)--
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`GET /api/v1/apps`:列出 App(分頁)。
|
|
||||||
|
|
||||||
`params` 為 keyword(`page:`/`per_page:`,可加 `visibility:`/`status:` 過濾)。
|
|
||||||
成功回 `{:ok, %{"data" => [apps], "page" => n, "per_page" => n, "total" => n}}`。
|
|
||||||
"""
|
|
||||||
def apps_list(issuer, token, params \\ []) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/apps", params: params)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/apps/{id}`:單一 App(`client_secret` 永不回傳)。"
|
|
||||||
def apps_get(issuer, token, id) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/apps/" <> URI.encode(id))
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`POST /api/v1/apps`:建立 App。`method=client_secret` 且未給
|
|
||||||
`client_secret` 時由伺服器產生,成功回應內含一次性明文
|
|
||||||
(`%{"data" => app, "client_secret" => secret}`)。
|
|
||||||
"""
|
|
||||||
def apps_create(issuer, token, attrs) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/apps", json: attrs)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`PUT /api/v1/apps/{id}`:部分更新(只送有給的欄位)。"
|
|
||||||
def apps_update(issuer, token, id, attrs) do
|
|
||||||
api_request(issuer, token, :put, "/api/v1/apps/" <> URI.encode(id), json: attrs)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`POST /api/v1/apps/{id}/rotate-secret`:輪轉 client secret,回應內含
|
|
||||||
一次性明文。PKCE App 回 422 `%{"error" => "pkce_app"}`。
|
|
||||||
"""
|
|
||||||
def apps_rotate_secret(issuer, token, id) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/apps/" <> URI.encode(id) <> "/rotate-secret",
|
|
||||||
json: %{}
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`POST /api/v1/apps/{id}/toggle`:切換 active ↔ inactive。"
|
|
||||||
def apps_toggle(issuer, token, id) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/apps/" <> URI.encode(id) <> "/toggle", json: %{})
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 個人自助 API(alterminal/bear#35;PAT Bearer、任何有效帳號)--
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/profile`:完整個人資料(含 MFA 狀態)。"
|
|
||||||
def profile_get(issuer, token) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/profile")
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`PUT /api/v1/profile`:更新個人資料欄位(只送有給的欄位)。"
|
|
||||||
def profile_update(issuer, token, attrs) do
|
|
||||||
api_request(issuer, token, :put, "/api/v1/profile", json: attrs)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`POST /api/v1/profile/password`:變更密碼(body:`current_password`、
|
|
||||||
`new_password`、`password_confirmation`;伺服器驗舊密碼,不因 CLI 放寬)。
|
|
||||||
"""
|
|
||||||
def profile_change_password(issuer, token, current_password, new_password) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/profile/password",
|
|
||||||
json: %{
|
|
||||||
current_password: current_password,
|
|
||||||
new_password: new_password,
|
|
||||||
password_confirmation: new_password
|
|
||||||
}
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`POST /api/v1/profile/email/request-codes`:寄發 email 變更雙向驗證碼。"
|
|
||||||
def profile_email_request_codes(issuer, token, new_email) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/profile/email/request-codes",
|
|
||||||
json: %{new_email: new_email}
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`POST /api/v1/profile/email`:確認變更 email(body:`new_email`、
|
|
||||||
`current_code`、`new_code`)。
|
|
||||||
"""
|
|
||||||
def profile_email_change(issuer, token, new_email, current_code, new_code) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/profile/email",
|
|
||||||
json: %{new_email: new_email, current_code: current_code, new_code: new_code}
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/profile/sessions`:列出作用中 session(新到舊)。"
|
|
||||||
def sessions_list(issuer, token) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/profile/sessions")
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`POST /api/v1/profile/sessions/{id}/revoke`:撤銷單一 session。"
|
|
||||||
def sessions_revoke(issuer, token, id) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/profile/sessions/" <> URI.encode(id) <> "/revoke",
|
|
||||||
json: %{}
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`POST /api/v1/profile/sessions/revoke-others`:撤銷其他 session
|
|
||||||
(body `keep` 可省略=全部撤銷)。
|
|
||||||
"""
|
|
||||||
def sessions_revoke_others(issuer, token, keep \\ nil) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/profile/sessions/revoke-others",
|
|
||||||
json: %{keep: keep} |> Map.reject(fn {_k, v} -> is_nil(v) end)
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/profile/tokens`:列出未撤銷的 PAT(新到舊)。"
|
|
||||||
def tokens_list(issuer, token) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/profile/tokens")
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`POST /api/v1/profile/tokens`:建立 PAT;明文 `token` 只在成功回應
|
|
||||||
出現一次(body:`name`、`expires_in`=天數或 `never`)。
|
|
||||||
"""
|
|
||||||
def tokens_create(issuer, token, name, expires_in) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/profile/tokens",
|
|
||||||
json: %{name: name, expires_in: expires_in}
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`POST /api/v1/profile/tokens/{id}/revoke`:撤銷單一 PAT。"
|
|
||||||
def tokens_revoke(issuer, token, id) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/profile/tokens/" <> URI.encode(id) <> "/revoke",
|
|
||||||
json: %{}
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`POST /api/v1/profile/mfa/setup`(無 body):開始 TOTP 設定,回
|
|
||||||
`%{"data" => %{"secret" => ..., "otpauth_uri" => ...}}`。已啟用 MFA 回
|
|
||||||
422 `already_enabled`。
|
|
||||||
"""
|
|
||||||
def mfa_setup(issuer, token) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/profile/mfa/setup", json: %{})
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`POST /api/v1/profile/mfa/setup/confirm`(body:`code`):確認設定並
|
|
||||||
啟用 MFA,回一次性 recovery codes。
|
|
||||||
"""
|
|
||||||
def mfa_setup_confirm(issuer, token, code) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/profile/mfa/setup/confirm", json: %{code: code})
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`POST /api/v1/profile/mfa/disable`(body:`code`=目前 TOTP 或
|
|
||||||
recovery code):停用 MFA。
|
|
||||||
"""
|
|
||||||
def mfa_disable(issuer, token, code) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/profile/mfa/disable", json: %{code: code})
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`POST /api/v1/profile/mfa/recovery-codes`(body:`code`):重產一組
|
|
||||||
一次性 recovery codes(舊組全部失效)。
|
|
||||||
"""
|
|
||||||
def mfa_recovery_codes(issuer, token, code) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/profile/mfa/recovery-codes", json: %{code: code})
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- Vault API(alterminal/bear#41;PAT Bearer、任何有效帳號)--
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/vault/config`:公告的 KDF 參數與支援的加密字串型別。"
|
|
||||||
def vault_config(issuer, token) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/vault/config")
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/vault/profile`:vault profile(404=尚未初始化)。"
|
|
||||||
def vault_profile_get(issuer, token) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/vault/profile")
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`PUT /api/v1/vault/profile`:建立或更新 profile(上傳重新包裝的金鑰)。"
|
|
||||||
def vault_profile_put(issuer, token, attrs) do
|
|
||||||
api_request(issuer, token, :put, "/api/v1/vault/profile", json: attrs)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/vault/sync`:完整同步(profile+folders+ciphers)。"
|
|
||||||
def vault_sync(issuer, token) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/vault/sync")
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/vault/ciphers`:列出 ciphers(含回收桶)。"
|
|
||||||
def vault_ciphers_list(issuer, token) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/vault/ciphers")
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`POST /api/v1/vault/ciphers`:以客戶端 UUID upsert(衝突時整列覆蓋)。"
|
|
||||||
def vault_ciphers_upsert(issuer, token, attrs) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/vault/ciphers", json: attrs)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/vault/ciphers/{uuid}`:單一 cipher。"
|
|
||||||
def vault_ciphers_get(issuer, token, uuid) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/vault/ciphers/" <> URI.encode(uuid))
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`PUT /api/v1/vault/ciphers/{uuid}`:部分更新(遞增 revision_date)。"
|
|
||||||
def vault_ciphers_update(issuer, token, uuid, attrs) do
|
|
||||||
api_request(issuer, token, :put, "/api/v1/vault/ciphers/" <> URI.encode(uuid), json: attrs)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`POST /api/v1/vault/ciphers/{uuid}/delete`:丟進回收桶(soft delete)。"
|
|
||||||
def vault_ciphers_delete(issuer, token, uuid) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/vault/ciphers/" <> URI.encode(uuid) <> "/delete",
|
|
||||||
json: %{}
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`POST /api/v1/vault/ciphers/{uuid}/restore`:從回收桶還原。"
|
|
||||||
def vault_ciphers_restore(issuer, token, uuid) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/vault/ciphers/" <> URI.encode(uuid) <> "/restore",
|
|
||||||
json: %{}
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`DELETE /api/v1/vault/ciphers/{uuid}/purge`:永久刪除(hard delete)。"
|
|
||||||
def vault_ciphers_purge(issuer, token, uuid) do
|
|
||||||
api_request(issuer, token, :delete, "/api/v1/vault/ciphers/" <> URI.encode(uuid) <> "/purge")
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/vault/folders`:列出資料夾。"
|
|
||||||
def vault_folders_list(issuer, token) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/vault/folders")
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`POST /api/v1/vault/folders`:以客戶端 UUID upsert 資料夾。"
|
|
||||||
def vault_folders_upsert(issuer, token, attrs) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/vault/folders", json: attrs)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`PUT /api/v1/vault/folders/{uuid}`:重新命名(新的加密名稱)。"
|
|
||||||
def vault_folders_rename(issuer, token, uuid, attrs) do
|
|
||||||
api_request(issuer, token, :put, "/api/v1/vault/folders/" <> URI.encode(uuid), json: attrs)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`DELETE /api/v1/vault/folders/{uuid}`:刪除資料夾。"
|
|
||||||
def vault_folders_delete(issuer, token, uuid) do
|
|
||||||
api_request(issuer, token, :delete, "/api/v1/vault/folders/" <> URI.encode(uuid))
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 共用請求輔助 --
|
|
||||||
|
|
||||||
# 回傳:
|
|
||||||
# {:ok, body} | {:error, :unauthorized, desc} | {:error, :forbidden, desc}
|
|
||||||
# | {:error, :not_found, desc} | {:error, :unprocessable_entity, body}
|
|
||||||
# | {:error, :too_many_requests, body}
|
|
||||||
# | {:error, :server_error, status} | {:error, :network, reason}
|
|
||||||
defp api_request(issuer, token, method, path, extra \\ []) do
|
|
||||||
url = String.trim_trailing(issuer, "/") <> path
|
|
||||||
|
|
||||||
opts =
|
|
||||||
[
|
|
||||||
headers: [authorization: "Bearer " <> token, accept: "application/json"],
|
|
||||||
retry: false,
|
|
||||||
finch: [name: @finch]
|
|
||||||
]
|
|
||||||
|> Keyword.merge(extra)
|
|
||||||
|
|
||||||
case apply(Req, method, [url, opts]) do
|
|
||||||
{:ok, %Req.Response{status: status, body: body}} when status in 200..299 ->
|
|
||||||
{:ok, decode_body(body)}
|
|
||||||
|
|
||||||
{:ok, %Req.Response{status: 401, body: body}} ->
|
|
||||||
{:error, :unauthorized, error_description(decode_body(body))}
|
|
||||||
|
|
||||||
{:ok, %Req.Response{status: 403, body: body}} ->
|
|
||||||
{:error, :forbidden, error_description(decode_body(body))}
|
|
||||||
|
|
||||||
{:ok, %Req.Response{status: 404, body: body}} ->
|
|
||||||
{:error, :not_found, error_description(decode_body(body))}
|
|
||||||
|
|
||||||
{:ok, %Req.Response{status: 422, body: body}} ->
|
|
||||||
{:error, :unprocessable_entity, decode_body(body)}
|
|
||||||
|
|
||||||
{:ok, %Req.Response{status: 429, body: body}} ->
|
|
||||||
{:error, :too_many_requests, decode_body(body)}
|
|
||||||
|
|
||||||
{:ok, %Req.Response{status: status}} ->
|
|
||||||
{:error, :server_error, status}
|
|
||||||
|
|
||||||
{:error, exception} ->
|
|
||||||
{:error, :network, Exception.message(exception)}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/jwks`: list all keys (active and inactive), newest first (no pagination)."
|
|
||||||
def jwks_list(issuer, token) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/jwks")
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`POST /api/v1/jwks`: create a new signing key. attrs: `%{"kid" => "...", "alg" => "RS256"}`
|
|
||||||
(`alg` optional; RS256/384/512, ES256/384/512). Key material is never serialized.
|
|
||||||
"""
|
|
||||||
def jwks_create(issuer, token, attrs) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/jwks", json: attrs)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/jwks/{id}`: single key (public metadata only)."
|
|
||||||
def jwks_get(issuer, token, id) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/jwks/" <> URI.encode(id))
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`POST /api/v1/jwks/{id}/toggle`: switch key between active and inactive."
|
|
||||||
def jwks_toggle(issuer, token, id) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/jwks/" <> URI.encode(id) <> "/toggle", json: %{})
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- Accounts API (alterminal/bear#46; PAT Bearer, admin only) --
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`GET /api/v1/accounts`: paginated list (newest first; per_page max 100).
|
|
||||||
Returns `{:ok, %{"data" => [accounts], "page" => n, "per_page" => n, "total" => n}}`.
|
|
||||||
"""
|
|
||||||
def accounts_list(issuer, token, params \\ []) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/accounts", params: params)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`POST /api/v1/accounts`: create an account directly (no email verification).
|
|
||||||
attrs: `%{"email" => "...", "hash_password" => "<plaintext>", "role" => "user|admin"}`
|
|
||||||
(`role` optional, default `user`).
|
|
||||||
"""
|
|
||||||
def accounts_create(issuer, token, attrs) do
|
|
||||||
api_request(issuer, token, :post, "/api/v1/accounts", json: attrs)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`GET /api/v1/accounts/{id}`: single account (no credential fields)."
|
|
||||||
def accounts_get(issuer, token, id) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/accounts/" <> URI.encode(id))
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`PUT /api/v1/accounts/{id}`: update role; attrs: `%{"role" => "user|admin"}`.
|
|
||||||
"""
|
|
||||||
def accounts_update_role(issuer, token, id, attrs) do
|
|
||||||
api_request(issuer, token, :put, "/api/v1/accounts/" <> URI.encode(id), json: attrs)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`PUT /api/v1/accounts/{id}/password`: admin sets a new password (no old password
|
|
||||||
needed); attrs: `%{"hash_password" => "<plaintext>"}`.
|
|
||||||
"""
|
|
||||||
def accounts_set_password(issuer, token, id, attrs) do
|
|
||||||
api_request(issuer, token, :put, "/api/v1/accounts/" <> URI.encode(id) <> "/password",
|
|
||||||
json: attrs
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "`DELETE /api/v1/accounts/{id}`: hard-delete an account (admin path). Returns `{:ok, %{}}` (204 empty)."
|
|
||||||
def accounts_delete(issuer, token, id) do
|
|
||||||
api_request(issuer, token, :delete, "/api/v1/accounts/" <> URI.encode(id))
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- Audit logs API (alterminal/bear#46; PAT Bearer, admin only) --
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
`GET /api/v1/audit-logs`: paginated list (newest first). params: `page:` /
|
|
||||||
`per_page:` (max 200) / `category:` filter. Returns `{:ok, %{"data" => [entries],
|
|
||||||
"page" => n, "per_page" => n, "total" => n, "total_pages" => n,
|
|
||||||
"emails" => %{id => email}}}`.
|
|
||||||
"""
|
|
||||||
def audit_logs_list(issuer, token, params \\ []) do
|
|
||||||
api_request(issuer, token, :get, "/api/v1/audit-logs", params: params)
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,446 +0,0 @@
|
|||||||
defmodule BearCli.Apps do
|
|
||||||
@moduledoc """
|
|
||||||
`bear apps` 指令群(App 管理;docs/commands.md §3.6、issue #10)。
|
|
||||||
|
|
||||||
對應伺服器端 App 管理 JSON API(alterminal/bear#28,`/api/v1/apps`、
|
|
||||||
PAT Bearer、admin 限定)。認證沿用既有 PAT 憑證(`BEAR_TOKEN` 或憑證檔)。
|
|
||||||
|
|
||||||
API 路徑參數為資料庫 UUID,CLI 對外介面一律使用 `client_id`;show/
|
|
||||||
update/rotate-secret/toggle 先以 list 比對解析(§7 開放問題 6 的結論)。
|
|
||||||
|
|
||||||
`client_secret` 僅於 create/rotate-secret 成功當下一次性輸出,不寫入
|
|
||||||
憑證檔/log/`--verbose`。
|
|
||||||
|
|
||||||
退出碼:0 成功;1 404/422;2 用法錯誤;3 未登入或 401;6 網路/伺服器
|
|
||||||
錯誤;8 權限不足(403,僅限 admin)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
alias BearCli.{Api, Config, Credentials}
|
|
||||||
|
|
||||||
@list_per_page_fetch 100
|
|
||||||
@max_fetch_pages 50
|
|
||||||
|
|
||||||
# -- 入口 --
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
執行 `bear apps <動詞>`,回傳退出碼。
|
|
||||||
|
|
||||||
`opts[:apps_api]` 可注入假 API 模組供測試(需實作 `apps_list/3`、
|
|
||||||
`apps_get/3`、`apps_create/3`、`apps_update/4`、`apps_rotate_secret/3`、
|
|
||||||
`apps_toggle/3`)。
|
|
||||||
"""
|
|
||||||
def run(verb, opts) do
|
|
||||||
api = opts[:apps_api] || Api
|
|
||||||
|
|
||||||
with {:ok, ctx} <- context(opts) do
|
|
||||||
execute(verb, ctx, opts, api)
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 共用背景(token/issuer)--
|
|
||||||
|
|
||||||
defp context(opts) do
|
|
||||||
if token = Config.env_token() do
|
|
||||||
# BEAR_TOKEN 優先於憑證檔(不讀檔、不寫檔)。
|
|
||||||
{:ok, %{token: token, issuer: resolve_issuer(opts, nil)}}
|
|
||||||
else
|
|
||||||
case Credentials.load() do
|
|
||||||
{:ok, creds} ->
|
|
||||||
token = creds["access_token"]
|
|
||||||
|
|
||||||
if blank?(token) do
|
|
||||||
{:error, "憑證檔缺少 access_token,請重新 bear login", 7}
|
|
||||||
else
|
|
||||||
{:ok, %{token: token, issuer: resolve_issuer(opts, creds["issuer"])}}
|
|
||||||
end
|
|
||||||
|
|
||||||
:error ->
|
|
||||||
{:error, "未登入(請先執行 bear login)", 3}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp resolve_issuer(opts, stored_issuer) do
|
|
||||||
opts[:issuer] || stored_issuer || Config.resolve_issuer(nil, opts[:config])
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 各動詞 --
|
|
||||||
|
|
||||||
defp execute(:list, ctx, opts, api) do
|
|
||||||
filters =
|
|
||||||
opts
|
|
||||||
|> Map.take([:visibility, :status])
|
|
||||||
|> Enum.reject(fn {_k, v} -> blank?(v) end)
|
|
||||||
|> Map.new()
|
|
||||||
|
|
||||||
if filters == %{} do
|
|
||||||
params = [page: opts[:page] || 1, per_page: opts[:per_page] || 20]
|
|
||||||
|
|
||||||
case api.apps_list(ctx.issuer, ctx.token, params) do
|
|
||||||
{:ok, body} ->
|
|
||||||
apps = body["data"] || []
|
|
||||||
page = body["page"] || params[:page]
|
|
||||||
per_page = body["per_page"] || params[:per_page]
|
|
||||||
total = body["total"] || length(apps)
|
|
||||||
render_list(opts, sort_apps(apps), page, per_page, total)
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
# 伺服器 list 端點目前僅支援分頁(bear#28),無 visibility/status
|
|
||||||
# 過濾參數;有過濾時以全量列舉後在本地過濾、排序與分頁。
|
|
||||||
with {:ok, all} <- fetch_all(ctx, api) do
|
|
||||||
filtered =
|
|
||||||
all
|
|
||||||
|> Enum.filter(&matches_filters?(&1, filters))
|
|
||||||
|> sort_apps()
|
|
||||||
|
|
||||||
page = opts[:page] || 1
|
|
||||||
per_page = opts[:per_page] || 20
|
|
||||||
page_apps = filtered |> Enum.drop((page - 1) * per_page) |> Enum.take(per_page)
|
|
||||||
render_list(opts, page_apps, page, per_page, length(filtered))
|
|
||||||
0
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:show, ctx, opts, api) do
|
|
||||||
with {:ok, app} <- resolve_app(ctx, opts[:client_id_arg], api) do
|
|
||||||
case api.apps_get(ctx.issuer, ctx.token, app["id"]) do
|
|
||||||
{:ok, body} ->
|
|
||||||
show_app(body["data"] || %{}, opts)
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:create, ctx, opts, api) do
|
|
||||||
attrs = build_attrs(opts, :create)
|
|
||||||
|
|
||||||
case api.apps_create(ctx.issuer, ctx.token, attrs) do
|
|
||||||
{:ok, body} ->
|
|
||||||
app = body["data"] || %{}
|
|
||||||
secret = body["client_secret"]
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
output = %{ok: true, app: app} |> maybe_put(:client_secret, secret)
|
|
||||||
IO.puts(Jason.encode!(output))
|
|
||||||
else
|
|
||||||
IO.puts("App 已建立:#{app["client_id"]}(#{app["visibility"]}/#{app["status"]})")
|
|
||||||
print_secret_block(secret, rotated?: false)
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:update, ctx, opts, api) do
|
|
||||||
attrs = build_attrs(opts, :update)
|
|
||||||
|
|
||||||
with {:ok, app} <- resolve_app(ctx, opts[:client_id_arg], api) do
|
|
||||||
case api.apps_update(ctx.issuer, ctx.token, app["id"], attrs) do
|
|
||||||
{:ok, body} ->
|
|
||||||
show_app(body["data"] || %{}, opts, summary?: true)
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:"rotate-secret", ctx, opts, api) do
|
|
||||||
with {:ok, app} <- resolve_app(ctx, opts[:client_id_arg], api) do
|
|
||||||
case api.apps_rotate_secret(ctx.issuer, ctx.token, app["id"]) do
|
|
||||||
{:ok, body} ->
|
|
||||||
secret = body["client_secret"]
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, client_secret: secret}))
|
|
||||||
else
|
|
||||||
print_secret_block(secret, rotated?: true)
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:toggle, ctx, opts, api) do
|
|
||||||
with {:ok, app} <- resolve_app(ctx, opts[:client_id_arg], api) do
|
|
||||||
case api.apps_toggle(ctx.issuer, ctx.token, app["id"]) do
|
|
||||||
{:ok, body} ->
|
|
||||||
updated = body["data"] || %{}
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(
|
|
||||||
Jason.encode!(%{
|
|
||||||
ok: true,
|
|
||||||
app: %{client_id: updated["client_id"], status: updated["status"]}
|
|
||||||
})
|
|
||||||
)
|
|
||||||
else
|
|
||||||
IO.puts("#{app["client_id"]}:#{app["status"]} → #{updated["status"]}")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- client_id → UUID 解析 --
|
|
||||||
|
|
||||||
defp resolve_app(_ctx, nil, _api), do: {:error, "缺少 <client-id> 參數", 2}
|
|
||||||
|
|
||||||
defp resolve_app(ctx, client_id, api) do
|
|
||||||
with {:ok, all} <- fetch_all(ctx, api) do
|
|
||||||
case Enum.find(all, &(&1["client_id"] == client_id)) do
|
|
||||||
nil -> {:error, "找不到 client_id 為 #{client_id} 的 App", 1}
|
|
||||||
app -> {:ok, app}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# 全量列舉(分頁逐步拉取直到取完;設頁數上限避免無限迴圈)。
|
|
||||||
defp fetch_all(ctx, api) do
|
|
||||||
do_fetch_all(ctx, api, 1, [])
|
|
||||||
end
|
|
||||||
|
|
||||||
defp do_fetch_all(_ctx, _api, page, acc) when page > @max_fetch_pages, do: {:ok, acc}
|
|
||||||
|
|
||||||
defp do_fetch_all(ctx, api, page, acc) do
|
|
||||||
case api.apps_list(ctx.issuer, ctx.token, page: page, per_page: @list_per_page_fetch) do
|
|
||||||
{:ok, body} ->
|
|
||||||
entries = body["data"] || []
|
|
||||||
acc = acc ++ entries
|
|
||||||
total = body["total"]
|
|
||||||
|
|
||||||
if entries == [] or length(entries) < @list_per_page_fetch or
|
|
||||||
(is_integer(total) and length(acc) >= total) do
|
|
||||||
{:ok, acc}
|
|
||||||
else
|
|
||||||
do_fetch_all(ctx, api, page + 1, acc)
|
|
||||||
end
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
{message, code} = format_api_error(ctx, error)
|
|
||||||
{:error, message, code}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 請求屬性組裝 --
|
|
||||||
|
|
||||||
# create:必填欄位已在解析層驗證(缺 → 用法錯誤 2),這裡只組裝。
|
|
||||||
defp build_attrs(opts, :create) do
|
|
||||||
%{}
|
|
||||||
|> put_value("client_id", opts[:client_id])
|
|
||||||
|> put_value("url", opts[:url])
|
|
||||||
|> put_value("title", opts[:title])
|
|
||||||
|> put_value("method", opts[:method])
|
|
||||||
|> put_value("visibility", opts[:visibility])
|
|
||||||
|> put_list("redirect_urls", opts[:redirect_url])
|
|
||||||
|> put_list("post_logout_redirect_uris", opts[:post_logout_redirect_uri])
|
|
||||||
|> put_list("scopes", opts[:scope])
|
|
||||||
|> put_value("sub", opts[:sub])
|
|
||||||
|> put_value("jwk_id", opts[:jwk_id])
|
|
||||||
|> put_value("client_secret", opts[:secret])
|
|
||||||
end
|
|
||||||
|
|
||||||
# update:只送有給的欄位(部分更新);清單類整組覆寫。
|
|
||||||
defp build_attrs(opts, :update) do
|
|
||||||
%{}
|
|
||||||
|> put_value("url", opts[:url])
|
|
||||||
|> put_value("title", opts[:title])
|
|
||||||
|> put_value("method", opts[:method])
|
|
||||||
|> put_value("visibility", opts[:visibility])
|
|
||||||
|> put_list("redirect_urls", opts[:redirect_url])
|
|
||||||
|> put_list("post_logout_redirect_uris", opts[:post_logout_redirect_uri])
|
|
||||||
|> put_list("scopes", opts[:scope])
|
|
||||||
|> put_value("sub", opts[:sub])
|
|
||||||
|> put_value("jwk_id", opts[:jwk_id])
|
|
||||||
end
|
|
||||||
|
|
||||||
defp put_value(map, _key, nil), do: map
|
|
||||||
defp put_value(map, _key, ""), do: map
|
|
||||||
defp put_value(map, key, value), do: Map.put(map, key, value)
|
|
||||||
|
|
||||||
defp put_list(map, _key, nil), do: map
|
|
||||||
defp put_list(map, _key, []), do: map
|
|
||||||
defp put_list(map, key, values), do: Map.put(map, key, values)
|
|
||||||
|
|
||||||
# -- 過濾與排序 --
|
|
||||||
|
|
||||||
defp matches_filters?(app, filters) do
|
|
||||||
Enum.all?(filters, fn {k, v} -> app[to_string(k)] == v end)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp sort_apps(apps), do: Enum.sort_by(apps, &{&1["client_id"] || "", &1["id"] || ""})
|
|
||||||
|
|
||||||
# -- 輸出 --
|
|
||||||
|
|
||||||
defp render_list(opts, apps, page, per_page, total) do
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(
|
|
||||||
Jason.encode!(%{ok: true, page: page, per_page: per_page, total: total, apps: apps})
|
|
||||||
)
|
|
||||||
else
|
|
||||||
print_table(apps)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
@table_headers ["CLIENT ID", "TITLE", "VISIBILITY", "STATUS", "METHOD", "SCOPES"]
|
|
||||||
|
|
||||||
defp print_table(apps) do
|
|
||||||
rows =
|
|
||||||
Enum.map(apps, fn app ->
|
|
||||||
[
|
|
||||||
app["client_id"] || "",
|
|
||||||
app["title"] || "",
|
|
||||||
app["visibility"] || "",
|
|
||||||
app["status"] || "",
|
|
||||||
app["method"] || "",
|
|
||||||
Enum.join(app["scopes"] || [], ", ")
|
|
||||||
]
|
|
||||||
end)
|
|
||||||
|
|
||||||
widths =
|
|
||||||
Enum.with_index(@table_headers, fn _header, i ->
|
|
||||||
Enum.max([
|
|
||||||
String.length(Enum.at(@table_headers, i))
|
|
||||||
| Enum.map(rows, &String.length(Enum.at(&1, i)))
|
|
||||||
])
|
|
||||||
end)
|
|
||||||
|
|
||||||
render_row = fn cells ->
|
|
||||||
cells
|
|
||||||
|> Enum.with_index()
|
|
||||||
|> Enum.map(fn {cell, i} -> String.pad_trailing(cell, Enum.at(widths, i)) end)
|
|
||||||
|> Enum.join(" ")
|
|
||||||
|> String.trim_trailing()
|
|
||||||
end
|
|
||||||
|
|
||||||
IO.puts(render_row.(@table_headers))
|
|
||||||
Enum.each(rows, fn cells -> IO.puts(render_row.(cells)) end)
|
|
||||||
end
|
|
||||||
|
|
||||||
@app_fields ~w(client_id title url method visibility status scopes redirect_urls post_logout_redirect_uris sub jwk_id created_at updated_at)
|
|
||||||
|
|
||||||
defp show_app(app, opts, summary? \\ false)
|
|
||||||
|
|
||||||
defp show_app(app, opts, _summary?) do
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, app: app}))
|
|
||||||
else
|
|
||||||
Enum.each(@app_fields, fn key ->
|
|
||||||
IO.puts("#{String.pad_trailing(key, 26)}: #{format_app_value(app[key])}")
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_app_value(nil), do: "(無)"
|
|
||||||
defp format_app_value([]), do: "(無)"
|
|
||||||
defp format_app_value(values) when is_list(values), do: Enum.join(values, ", ")
|
|
||||||
defp format_app_value(value) when is_binary(value), do: value
|
|
||||||
defp format_app_value(value), do: to_string(value)
|
|
||||||
|
|
||||||
# secret 只在成功當下一次性輸出(不寫入憑證檔/log/--verbose)。
|
|
||||||
defp print_secret_block(nil, _opts), do: :ok
|
|
||||||
|
|
||||||
defp print_secret_block(secret, rotated?: rotated?) do
|
|
||||||
lead = if rotated?, do: "client_secret 已輪轉", else: "client_secret"
|
|
||||||
IO.puts("#{lead}(只顯示這一次,請立即保存):")
|
|
||||||
IO.puts(" #{secret}")
|
|
||||||
end
|
|
||||||
|
|
||||||
defp maybe_put(map, _key, nil), do: map
|
|
||||||
defp maybe_put(map, key, value), do: Map.put(map, key, value)
|
|
||||||
|
|
||||||
# -- 錯誤處理 --
|
|
||||||
|
|
||||||
# API 錯誤 → 依 §3.6 群組共通退出碼輸出,回傳退出碼。
|
|
||||||
defp fail_api(opts, ctx, error) do
|
|
||||||
{message, code} = format_api_error(ctx, error)
|
|
||||||
fail(opts, message, code)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_api_error(_ctx, {:error, :unauthorized, desc}) do
|
|
||||||
{"token 無效或已過期(#{desc}),請重新 bear login", 3}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_api_error(_ctx, {:error, :forbidden, _desc}) do
|
|
||||||
{"此操作需 admin 權限(HTTP 403)", 8}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_api_error(_ctx, {:error, :not_found, _desc}) do
|
|
||||||
{"找不到目標 App(HTTP 404)", 1}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_api_error(_ctx, {:error, :unprocessable_entity, %{"error" => "pkce_app"}}) do
|
|
||||||
{"此 App 為 PKCE,無 client secret 可輪轉", 1}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_api_error(_ctx, {:error, :unprocessable_entity, body}) do
|
|
||||||
details =
|
|
||||||
body
|
|
||||||
|> Map.get("errors", %{})
|
|
||||||
|> Enum.map(fn {field, messages} ->
|
|
||||||
"#{field}: #{Enum.join(List.wrap(messages), "、")}"
|
|
||||||
end)
|
|
||||||
|> Enum.join(";")
|
|
||||||
|
|
||||||
if details == "" do
|
|
||||||
{"驗證失敗(HTTP 422)", 1}
|
|
||||||
else
|
|
||||||
{"驗證失敗(HTTP 422):#{details}", 1}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_api_error(_ctx, {:error, :server_error, status}) do
|
|
||||||
{"伺服器回應 #{status}", 6}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_api_error(ctx, {:error, :network, reason}) do
|
|
||||||
{"無法連線到 #{ctx.issuer}:#{reason}", 6}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp fail(opts, message, code) do
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: false, error: message, code: code}))
|
|
||||||
else
|
|
||||||
IO.puts(:stderr, "錯誤:#{message}")
|
|
||||||
end
|
|
||||||
|
|
||||||
code
|
|
||||||
end
|
|
||||||
|
|
||||||
defp blank?(nil), do: true
|
|
||||||
|
|
||||||
defp blank?(""), do: true
|
|
||||||
defp blank?(_), do: false
|
|
||||||
end
|
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
defmodule BearCli.AuditLogs do
|
|
||||||
@moduledoc """
|
|
||||||
`bear audit-logs` 指令群(稽核日誌;docs/commands.md §3.10、issue #12)。
|
|
||||||
|
|
||||||
對應伺服器端稽核日誌 JSON API(alterminal/bear#46,`/api/v1/audit-logs`、
|
|
||||||
PAT Bearer、admin 限定)。認證沿用既有 PAT 憑證(`BEAR_TOKEN` 或憑證檔)。
|
|
||||||
|
|
||||||
退出碼:0 成功;2 用法錯誤;3 未登入或 401;6 網路/伺服器錯誤;
|
|
||||||
8 權限不足(403,僅限 admin)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import BearCli.Admin, only: [context: 1, fail: 3, format_api_error: 2]
|
|
||||||
alias BearCli.Api
|
|
||||||
|
|
||||||
# -- 入口 --
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
執行 `bear audit-logs <動詞>`,回傳退出碼。`opts[:audit_logs_api]` 可注入
|
|
||||||
假 API 模組供測試(需實作 `audit_logs_list/3`)。
|
|
||||||
"""
|
|
||||||
def run(:list, opts) do
|
|
||||||
api = opts[:audit_logs_api] || Api
|
|
||||||
|
|
||||||
with {:ok, ctx} <- context(opts) do
|
|
||||||
params =
|
|
||||||
[page: opts[:page] || 1, per_page: opts[:per_page] || 50]
|
|
||||||
|> maybe_put(:category, opts[:category])
|
|
||||||
|
|
||||||
case api.audit_logs_list(ctx.issuer, ctx.token, params) do
|
|
||||||
{:ok, body} ->
|
|
||||||
entries = body["data"] || []
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(
|
|
||||||
Jason.encode!(
|
|
||||||
Map.take(body, ["page", "per_page", "total", "total_pages", "emails"])
|
|
||||||
|> Map.merge(%{ok: true, entries: entries})
|
|
||||||
)
|
|
||||||
)
|
|
||||||
else
|
|
||||||
print_table(entries, body["emails"] || %{})
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
{message, code} = format_api_error(ctx, error)
|
|
||||||
fail(opts, message, code)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp maybe_put(params, _key, nil), do: params
|
|
||||||
defp maybe_put(params, _key, ""), do: params
|
|
||||||
defp maybe_put(params, key, value), do: Keyword.put(params, key, value)
|
|
||||||
|
|
||||||
# -- 輸出 --
|
|
||||||
|
|
||||||
@table_headers ["TIME", "CATEGORY", "EVENT", "ACTOR", "ACCOUNT"]
|
|
||||||
|
|
||||||
defp print_table(entries, emails) do
|
|
||||||
rows =
|
|
||||||
Enum.map(entries, fn entry ->
|
|
||||||
[
|
|
||||||
entry["created_at"] || "",
|
|
||||||
entry["category"] || "",
|
|
||||||
entry["event"] || "",
|
|
||||||
email_of(emails, entry["actor_id"]),
|
|
||||||
email_of(emails, entry["account_id"])
|
|
||||||
]
|
|
||||||
end)
|
|
||||||
|
|
||||||
widths =
|
|
||||||
Enum.with_index(@table_headers, fn _header, i ->
|
|
||||||
Enum.max([
|
|
||||||
String.length(Enum.at(@table_headers, i))
|
|
||||||
| Enum.map(rows, &String.length(Enum.at(&1, i)))
|
|
||||||
])
|
|
||||||
end)
|
|
||||||
|
|
||||||
render_row = fn cells ->
|
|
||||||
cells
|
|
||||||
|> Enum.with_index()
|
|
||||||
|> Enum.map(fn {cell, i} -> String.pad_trailing(cell, Enum.at(widths, i)) end)
|
|
||||||
|> Enum.join(" ")
|
|
||||||
|> String.trim_trailing()
|
|
||||||
end
|
|
||||||
|
|
||||||
IO.puts(render_row.(@table_headers))
|
|
||||||
Enum.each(rows, fn cells -> IO.puts(render_row.(cells)) end)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp email_of(_emails, nil), do: "-"
|
|
||||||
|
|
||||||
defp email_of(emails, id) do
|
|
||||||
case Map.get(emails, id) do
|
|
||||||
nil -> String.slice(id || "", 0, 8)
|
|
||||||
email -> email
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
+53
-666
@@ -2,24 +2,10 @@ defmodule BearCli.CLI do
|
|||||||
@moduledoc """
|
@moduledoc """
|
||||||
`bear` 指令的命令列入口與指令分派。
|
`bear` 指令的命令列入口與指令分派。
|
||||||
|
|
||||||
指令:`login`(PAT 模式)、`whoami`、`token`、`logout`、`status`。
|
支援指令:`login`(PAT 模式)、`whoami`、`token`、`logout`、`status`。
|
||||||
|
|
||||||
`BEAR_TOKEN` 環境變數(一次性/CI 用的 PAT)提供時,`whoami`/`token`/`status`
|
|
||||||
優先使用該值,不讀寫本機憑證檔。
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
alias BearCli.{
|
alias BearCli.{Api, Config, Credentials}
|
||||||
Accounts,
|
|
||||||
Admin,
|
|
||||||
Api,
|
|
||||||
Apps,
|
|
||||||
AuditLogs,
|
|
||||||
Config,
|
|
||||||
Credentials,
|
|
||||||
Jwks,
|
|
||||||
SelfService,
|
|
||||||
Vault
|
|
||||||
}
|
|
||||||
|
|
||||||
@global_switches [
|
@global_switches [
|
||||||
issuer: :string,
|
issuer: :string,
|
||||||
@@ -34,81 +20,6 @@ defmodule BearCli.CLI do
|
|||||||
@login_switches [token: :string, scope: :string, "client-id": :string]
|
@login_switches [token: :string, scope: :string, "client-id": :string]
|
||||||
@token_switches [refresh: :boolean]
|
@token_switches [refresh: :boolean]
|
||||||
|
|
||||||
# -- apps 指令群(docs/commands.md §3.6)--
|
|
||||||
# 注意:OptionParser 會把選項名的連字號正規化為底線
|
|
||||||
# (--client-id → :client_id),switch 定義需用底線 atom。
|
|
||||||
@apps_verbs ~w(list show create update rotate-secret toggle)
|
|
||||||
|
|
||||||
@apps_list_switches [
|
|
||||||
visibility: :string,
|
|
||||||
status: :string,
|
|
||||||
page: :integer,
|
|
||||||
per_page: :integer
|
|
||||||
]
|
|
||||||
|
|
||||||
@apps_create_switches [
|
|
||||||
client_id: :string,
|
|
||||||
url: :string,
|
|
||||||
title: :string,
|
|
||||||
method: :string,
|
|
||||||
visibility: :string,
|
|
||||||
redirect_url: :keep,
|
|
||||||
post_logout_redirect_uri: :keep,
|
|
||||||
scope: :keep,
|
|
||||||
sub: :string,
|
|
||||||
jwk_id: :string,
|
|
||||||
secret: :string
|
|
||||||
]
|
|
||||||
|
|
||||||
@apps_update_switches [
|
|
||||||
url: :string,
|
|
||||||
title: :string,
|
|
||||||
method: :string,
|
|
||||||
visibility: :string,
|
|
||||||
redirect_url: :keep,
|
|
||||||
post_logout_redirect_uri: :keep,
|
|
||||||
scope: :keep,
|
|
||||||
sub: :string,
|
|
||||||
jwk_id: :string
|
|
||||||
]
|
|
||||||
|
|
||||||
@visibilities ~w(public internal)
|
|
||||||
@statuses ~w(active inactive)
|
|
||||||
@methods ~w(client_secret PKCE)
|
|
||||||
|
|
||||||
# -- 個人自助指令群(docs/commands.md §3.7)--
|
|
||||||
|
|
||||||
@profile_verbs ~w(show set)
|
|
||||||
@sessions_verbs ~w(list revoke revoke-others)
|
|
||||||
@tokens_verbs ~w(list create revoke)
|
|
||||||
@mfa_verbs ~w(status setup disable recovery-codes)
|
|
||||||
|
|
||||||
@profile_set_switches [
|
|
||||||
name: :string,
|
|
||||||
given_name: :string,
|
|
||||||
family_name: :string,
|
|
||||||
nickname: :string,
|
|
||||||
preferred_username: :string,
|
|
||||||
profile: :string,
|
|
||||||
picture: :string,
|
|
||||||
website: :string,
|
|
||||||
gender: :string,
|
|
||||||
birthdate: :string,
|
|
||||||
zoneinfo: :string,
|
|
||||||
locale: :string,
|
|
||||||
phone_number: :string,
|
|
||||||
phone_verified: :boolean,
|
|
||||||
address_formatted: :string,
|
|
||||||
address_street_address: :string,
|
|
||||||
address_locality: :string,
|
|
||||||
address_region: :string,
|
|
||||||
address_postal_code: :string,
|
|
||||||
address_country: :string
|
|
||||||
]
|
|
||||||
|
|
||||||
@email_switches [new: :string]
|
|
||||||
@tokens_create_switches [name: :string, expires_in: :string]
|
|
||||||
|
|
||||||
# -- escript 入口 --
|
# -- escript 入口 --
|
||||||
|
|
||||||
@doc "escript 主函式。執行後以 `System.halt/1` 設定退出碼。"
|
@doc "escript 主函式。執行後以 `System.halt/1` 設定退出碼。"
|
||||||
@@ -200,169 +111,10 @@ defmodule BearCli.CLI do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
defp parse_command("apps", args, global) do
|
|
||||||
case args do
|
|
||||||
[verb | rest] when verb in @apps_verbs ->
|
|
||||||
switches = apps_switches(verb)
|
|
||||||
|
|
||||||
case OptionParser.parse(rest, strict: @global_switches ++ switches) do
|
|
||||||
{opts, positionals, []} ->
|
|
||||||
validate_apps(verb, positionals, merge_opts(global, opts_to_map(opts)))
|
|
||||||
|
|
||||||
{_opts, _extra, [{opt, _} | _]} ->
|
|
||||||
{:error, "無法解析選項:#{opt}", 2}
|
|
||||||
end
|
|
||||||
|
|
||||||
[] ->
|
|
||||||
{:error, "apps 缺少子指令(可用:#{Enum.join(@apps_verbs, " ")})", 2}
|
|
||||||
|
|
||||||
[unknown | _] ->
|
|
||||||
{:error, "未知的 apps 子指令:#{unknown}(可用:#{Enum.join(@apps_verbs, " ")})", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp parse_command("profile", args, global) do
|
|
||||||
case args do
|
|
||||||
[verb | rest] when verb in @profile_verbs ->
|
|
||||||
switches = if verb == "set", do: @profile_set_switches, else: []
|
|
||||||
|
|
||||||
case OptionParser.parse(rest, strict: @global_switches ++ switches) do
|
|
||||||
{opts, positionals, []} ->
|
|
||||||
validate_self_service(
|
|
||||||
:profile,
|
|
||||||
verb,
|
|
||||||
positionals,
|
|
||||||
merge_opts(global, opts_to_map(opts))
|
|
||||||
)
|
|
||||||
|
|
||||||
{_opts, _extra, [{opt, _} | _]} ->
|
|
||||||
{:error, "無法解析選項:#{opt}", 2}
|
|
||||||
end
|
|
||||||
|
|
||||||
[] ->
|
|
||||||
{:error, "profile 缺少子指令(可用:#{Enum.join(@profile_verbs, " ")})", 2}
|
|
||||||
|
|
||||||
[unknown | _] ->
|
|
||||||
{:error, "未知的 profile 子指令:#{unknown}(可用:#{Enum.join(@profile_verbs, " ")})", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp parse_command("password", args, global) do
|
|
||||||
case args do
|
|
||||||
["change" | rest] ->
|
|
||||||
case OptionParser.parse(rest, strict: @global_switches) do
|
|
||||||
{opts, [], []} ->
|
|
||||||
{:ok, {:self_service, :password, :change}, merge_opts(global, opts_to_map(opts))}
|
|
||||||
|
|
||||||
{_opts, extra, []} ->
|
|
||||||
{:error, "password change 不接受參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
{_opts, _extra, [{opt, _} | _]} ->
|
|
||||||
{:error, "無法解析選項:#{opt}", 2}
|
|
||||||
end
|
|
||||||
|
|
||||||
[] ->
|
|
||||||
{:error, "password 缺少子指令(可用:change)", 2}
|
|
||||||
|
|
||||||
[unknown | _] ->
|
|
||||||
{:error, "未知的 password 子指令:#{unknown}(可用:change)", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp parse_command("email", args, global) do
|
|
||||||
case args do
|
|
||||||
["change" | rest] ->
|
|
||||||
case OptionParser.parse(rest, strict: @global_switches ++ @email_switches) do
|
|
||||||
{opts, [], []} ->
|
|
||||||
{:ok, {:self_service, :email, :change}, merge_opts(global, opts_to_map(opts))}
|
|
||||||
|
|
||||||
{_opts, extra, []} ->
|
|
||||||
{:error, "email change 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
{_opts, _extra, [{opt, _} | _]} ->
|
|
||||||
{:error, "無法解析選項:#{opt}", 2}
|
|
||||||
end
|
|
||||||
|
|
||||||
[] ->
|
|
||||||
{:error, "email 缺少子指令(可用:change)", 2}
|
|
||||||
|
|
||||||
[unknown | _] ->
|
|
||||||
{:error, "未知的 email 子指令:#{unknown}(可用:change)", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp parse_command("sessions", args, global) do
|
|
||||||
case args do
|
|
||||||
[verb | rest] when verb in @sessions_verbs ->
|
|
||||||
parse_group_verb("sessions", verb, rest, [], global)
|
|
||||||
|
|
||||||
[] ->
|
|
||||||
{:error, "sessions 缺少子指令(可用:#{Enum.join(@sessions_verbs, " ")})", 2}
|
|
||||||
|
|
||||||
[unknown | _] ->
|
|
||||||
{:error, "未知的 sessions 子指令:#{unknown}(可用:#{Enum.join(@sessions_verbs, " ")})", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp parse_command("tokens", args, global) do
|
|
||||||
case args do
|
|
||||||
[verb | rest] when verb in @tokens_verbs ->
|
|
||||||
parse_group_verb("tokens", verb, rest, [], global)
|
|
||||||
|
|
||||||
[] ->
|
|
||||||
{:error, "tokens 缺少子指令(可用:#{Enum.join(@tokens_verbs, " ")})", 2}
|
|
||||||
|
|
||||||
[unknown | _] ->
|
|
||||||
{:error, "未知的 tokens 子指令:#{unknown}(可用:#{Enum.join(@tokens_verbs, " ")})", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp parse_command("mfa", args, global) do
|
|
||||||
case args do
|
|
||||||
[verb | rest] when verb in @mfa_verbs ->
|
|
||||||
parse_group_verb("mfa", verb, rest, [], global)
|
|
||||||
|
|
||||||
[] ->
|
|
||||||
{:error, "mfa 缺少子指令(可用:#{Enum.join(@mfa_verbs, " ")})", 2}
|
|
||||||
|
|
||||||
[unknown | _] ->
|
|
||||||
{:error, "未知的 mfa 子指令:#{unknown}(可用:#{Enum.join(@mfa_verbs, " ")})", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# 管理端指令群(jwks/accounts/audit-logs;解析委由 BearCli.Admin)
|
|
||||||
defp parse_command(group, args, global) when group in ~w(jwks accounts audit-logs) do
|
|
||||||
case Admin.parse([group | args], global) do
|
|
||||||
:error -> {:error, "未知指令:#{group}(可用 bear --help 查看說明)", 2}
|
|
||||||
parsed -> parsed
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# vault 指令群(issue #17;解析委由 BearCli.Vault)
|
|
||||||
defp parse_command("vault", args, global) do
|
|
||||||
Vault.parse(["vault" | args], global)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp parse_command(unknown, _args, _global) do
|
defp parse_command(unknown, _args, _global) do
|
||||||
{:error, "未知指令:#{unknown}(可用 bear --help 查看說明)", 2}
|
{:error, "未知指令:#{unknown}(可用 bear --help 查看說明)", 2}
|
||||||
end
|
end
|
||||||
|
|
||||||
# sessions/tokens/mfa 共用:verb 已驗證合法後解析選項與位置參數。
|
|
||||||
defp parse_group_verb(group, verb, rest, extra_switches, global) do
|
|
||||||
switches = group_switches(group, verb) ++ extra_switches
|
|
||||||
|
|
||||||
case OptionParser.parse(rest, strict: @global_switches ++ switches) do
|
|
||||||
{opts, positionals, []} ->
|
|
||||||
validate_self_service(group, verb, positionals, merge_opts(global, opts_to_map(opts)))
|
|
||||||
|
|
||||||
{_opts, _extra, [{opt, _} | _]} ->
|
|
||||||
{:error, "無法解析選項:#{opt}", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp group_switches("tokens", "create"), do: @tokens_create_switches
|
|
||||||
defp group_switches(_group, _verb), do: []
|
|
||||||
|
|
||||||
defp parse_opts(args, switches) do
|
defp parse_opts(args, switches) do
|
||||||
case OptionParser.parse(args, strict: switches) do
|
case OptionParser.parse(args, strict: switches) do
|
||||||
{opts, [], []} ->
|
{opts, [], []} ->
|
||||||
@@ -376,217 +128,10 @@ defmodule BearCli.CLI do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
# -- apps 解析輔助 --
|
|
||||||
|
|
||||||
defp apps_switches("list"), do: @apps_list_switches
|
|
||||||
defp apps_switches("show"), do: []
|
|
||||||
defp apps_switches("create"), do: @apps_create_switches
|
|
||||||
defp apps_switches("update"), do: @apps_update_switches
|
|
||||||
defp apps_switches("rotate-secret"), do: []
|
|
||||||
defp apps_switches("toggle"), do: []
|
|
||||||
|
|
||||||
# apps 子指令的本地用法驗證(§3.6:用法錯誤 → 退出碼 2)。
|
|
||||||
defp validate_apps("list", [], opts) do
|
|
||||||
cond do
|
|
||||||
invalid_enum?(opts[:visibility], @visibilities, "--visibility") ->
|
|
||||||
usage_error(opts[:visibility], "--visibility", @visibilities)
|
|
||||||
|
|
||||||
invalid_enum?(opts[:status], @statuses, "--status") ->
|
|
||||||
usage_error(opts[:status], "--status", @statuses)
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, {Apps, :list}, opts}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp validate_apps("list", extra, _opts),
|
|
||||||
do: {:error, "apps list 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
defp validate_apps("show", [client_id], opts),
|
|
||||||
do: {:ok, {Apps, :show}, Map.put(opts, :client_id_arg, client_id)}
|
|
||||||
|
|
||||||
defp validate_apps("show", [], _opts), do: {:error, "apps show 缺少 <client-id>", 2}
|
|
||||||
|
|
||||||
defp validate_apps("show", extra, _opts),
|
|
||||||
do: {:error, "apps show 只接受一個 <client-id>(多餘:#{Enum.join(Enum.drop(extra, 1), " ")})", 2}
|
|
||||||
|
|
||||||
defp validate_apps("create", [], opts) do
|
|
||||||
missing =
|
|
||||||
[{"client-id", opts[:client_id]}, {"url", opts[:url]}, {"title", opts[:title]}]
|
|
||||||
|> Enum.filter(fn {_name, v} -> blank?(v) end)
|
|
||||||
|> Enum.map(&elem(&1, 0))
|
|
||||||
|
|
||||||
cond do
|
|
||||||
missing != [] ->
|
|
||||||
{:error, "apps create 缺少必選參數:#{Enum.join(missing, "、")}", 2}
|
|
||||||
|
|
||||||
invalid_enum?(opts[:method], @methods, "--method") ->
|
|
||||||
usage_error(opts[:method], "--method", @methods)
|
|
||||||
|
|
||||||
invalid_enum?(opts[:visibility], @visibilities, "--visibility") ->
|
|
||||||
usage_error(opts[:visibility], "--visibility", @visibilities)
|
|
||||||
|
|
||||||
opts[:method] == "PKCE" and blank?(opts[:jwk_id]) ->
|
|
||||||
{:error, "method=PKCE 必須給 --jwk-id", 2}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, {Apps, :create}, opts}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp validate_apps("create", extra, _opts),
|
|
||||||
do: {:error, "apps create 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
defp validate_apps("update", [client_id], opts) do
|
|
||||||
cond do
|
|
||||||
invalid_enum?(opts[:method], @methods, "--method") ->
|
|
||||||
usage_error(opts[:method], "--method", @methods)
|
|
||||||
|
|
||||||
invalid_enum?(opts[:visibility], @visibilities, "--visibility") ->
|
|
||||||
usage_error(opts[:visibility], "--visibility", @visibilities)
|
|
||||||
|
|
||||||
opts[:method] == "PKCE" and blank?(opts[:jwk_id]) ->
|
|
||||||
{:error, "method=PKCE 必須給 --jwk-id", 2}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, {Apps, :update}, Map.put(opts, :client_id_arg, client_id)}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp validate_apps("update", [], _opts), do: {:error, "apps update 缺少 <client-id>", 2}
|
|
||||||
|
|
||||||
defp validate_apps("update", extra, _opts),
|
|
||||||
do: {:error, "apps update 只接受一個 <client-id>(多餘:#{Enum.join(Enum.drop(extra, 1), " ")})", 2}
|
|
||||||
|
|
||||||
defp validate_apps("rotate-secret", [client_id], opts),
|
|
||||||
do: {:ok, {Apps, :"rotate-secret"}, Map.put(opts, :client_id_arg, client_id)}
|
|
||||||
|
|
||||||
defp validate_apps("rotate-secret", [], _opts),
|
|
||||||
do: {:error, "apps rotate-secret 缺少 <client-id>", 2}
|
|
||||||
|
|
||||||
defp validate_apps("rotate-secret", extra, _opts),
|
|
||||||
do:
|
|
||||||
{:error, "apps rotate-secret 只接受一個 <client-id>(多餘:#{Enum.join(Enum.drop(extra, 1), " ")})",
|
|
||||||
2}
|
|
||||||
|
|
||||||
defp validate_apps("toggle", [client_id], opts),
|
|
||||||
do: {:ok, {Apps, :toggle}, Map.put(opts, :client_id_arg, client_id)}
|
|
||||||
|
|
||||||
defp validate_apps("toggle", [], _opts), do: {:error, "apps toggle 缺少 <client-id>", 2}
|
|
||||||
|
|
||||||
defp validate_apps("toggle", extra, _opts),
|
|
||||||
do: {:error, "apps toggle 只接受一個 <client-id>(多餘:#{Enum.join(Enum.drop(extra, 1), " ")})", 2}
|
|
||||||
|
|
||||||
defp invalid_enum?(nil, _allowed, _flag), do: false
|
|
||||||
defp invalid_enum?(value, allowed, _flag), do: value not in allowed
|
|
||||||
|
|
||||||
defp usage_error(value, flag, allowed) do
|
|
||||||
{:error, "#{flag} 不接受的值:#{value}(可用:#{Enum.join(allowed, "、")})", 2}
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 個人自助指令群解析輔助(§3.7)--
|
|
||||||
|
|
||||||
# 各群組的位置參數驗證;通過後回 {:ok, {:self_service, group, verb}, opts}。
|
|
||||||
defp validate_self_service(:profile, "show", [], opts),
|
|
||||||
do: {:ok, {:self_service, :profile, :show}, opts}
|
|
||||||
|
|
||||||
defp validate_self_service(:profile, "show", extra, _opts),
|
|
||||||
do: {:error, "profile show 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
defp validate_self_service(:profile, "set", [], opts),
|
|
||||||
do: {:ok, {:self_service, :profile, :set}, opts}
|
|
||||||
|
|
||||||
defp validate_self_service(:profile, "set", extra, _opts),
|
|
||||||
do: {:error, "profile set 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
defp validate_self_service("sessions", "list", [], opts),
|
|
||||||
do: {:ok, {:self_service, :sessions, :list}, opts}
|
|
||||||
|
|
||||||
defp validate_self_service("sessions", "list", extra, _opts),
|
|
||||||
do: {:error, "sessions list 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
defp validate_self_service("sessions", "revoke", [id], opts),
|
|
||||||
do: {:ok, {:self_service, :sessions, :revoke}, Map.put(opts, :id_arg, id)}
|
|
||||||
|
|
||||||
defp validate_self_service("sessions", "revoke", [], _opts),
|
|
||||||
do: {:error, "sessions revoke 缺少 <id>", 2}
|
|
||||||
|
|
||||||
defp validate_self_service("sessions", "revoke", extra, _opts),
|
|
||||||
do: {:error, "sessions revoke 只接受一個 <id>(多餘:#{Enum.join(Enum.drop(extra, 1), " ")})", 2}
|
|
||||||
|
|
||||||
defp validate_self_service("sessions", "revoke-others", [], opts),
|
|
||||||
do: {:ok, {:self_service, :sessions, :"revoke-others"}, opts}
|
|
||||||
|
|
||||||
defp validate_self_service("sessions", "revoke-others", extra, _opts),
|
|
||||||
do: {:error, "sessions revoke-others 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
defp validate_self_service("tokens", "list", [], opts),
|
|
||||||
do: {:ok, {:self_service, :tokens, :list}, opts}
|
|
||||||
|
|
||||||
defp validate_self_service("tokens", "list", extra, _opts),
|
|
||||||
do: {:error, "tokens list 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
defp validate_self_service("tokens", "create", [], opts) do
|
|
||||||
if blank?(opts[:name]) do
|
|
||||||
{:error, "tokens create 缺少 --name NAME", 2}
|
|
||||||
else
|
|
||||||
{:ok, {:self_service, :tokens, :create}, opts}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp validate_self_service("tokens", "create", extra, _opts),
|
|
||||||
do: {:error, "tokens create 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
defp validate_self_service("tokens", "revoke", [id], opts),
|
|
||||||
do: {:ok, {:self_service, :tokens, :revoke}, Map.put(opts, :id_arg, id)}
|
|
||||||
|
|
||||||
defp validate_self_service("tokens", "revoke", [], _opts),
|
|
||||||
do: {:error, "tokens revoke 缺少 <id>", 2}
|
|
||||||
|
|
||||||
defp validate_self_service("tokens", "revoke", extra, _opts),
|
|
||||||
do: {:error, "tokens revoke 只接受一個 <id>(多餘:#{Enum.join(Enum.drop(extra, 1), " ")})", 2}
|
|
||||||
|
|
||||||
defp validate_self_service("mfa", "status", [], opts),
|
|
||||||
do: {:ok, {:self_service, :mfa, :status}, opts}
|
|
||||||
|
|
||||||
defp validate_self_service("mfa", "status", extra, _opts),
|
|
||||||
do: {:error, "mfa status 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
defp validate_self_service("mfa", "setup", [], opts),
|
|
||||||
do: {:ok, {:self_service, :mfa, :setup}, opts}
|
|
||||||
|
|
||||||
defp validate_self_service("mfa", "setup", extra, _opts),
|
|
||||||
do: {:error, "mfa setup 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
defp validate_self_service("mfa", "disable", [], opts),
|
|
||||||
do: {:ok, {:self_service, :mfa, :disable}, opts}
|
|
||||||
|
|
||||||
defp validate_self_service("mfa", "disable", extra, _opts),
|
|
||||||
do: {:error, "mfa disable 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
defp validate_self_service("mfa", "recovery-codes", [], opts),
|
|
||||||
do: {:ok, {:self_service, :mfa, :"recovery-codes"}, opts}
|
|
||||||
|
|
||||||
defp validate_self_service("mfa", "recovery-codes", extra, _opts),
|
|
||||||
do: {:error, "mfa recovery-codes 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
|
||||||
|
|
||||||
defp merge_opts(global, opts) do
|
defp merge_opts(global, opts) do
|
||||||
Map.merge(Map.new(global), Map.new(opts))
|
Map.merge(Map.new(global), Map.new(opts))
|
||||||
end
|
end
|
||||||
|
|
||||||
# keyword 轉 map:`:keep` 選項(@keep_keys)重複出現時收集為清單,其餘取最後值。
|
|
||||||
@keep_keys ~w(redirect_url post_logout_redirect_uri scope)a
|
|
||||||
|
|
||||||
defp opts_to_map(opts) do
|
|
||||||
Enum.reduce(opts, %{}, fn
|
|
||||||
{k, v}, acc when k in @keep_keys ->
|
|
||||||
Map.update(acc, k, [v], fn existing -> existing ++ [v] end)
|
|
||||||
|
|
||||||
{k, v}, acc ->
|
|
||||||
Map.put(acc, k, v)
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 分派 --
|
# -- 分派 --
|
||||||
|
|
||||||
@doc """
|
@doc """
|
||||||
@@ -600,11 +145,6 @@ defmodule BearCli.CLI do
|
|||||||
IO.puts(BearCli.version())
|
IO.puts(BearCli.version())
|
||||||
0
|
0
|
||||||
|
|
||||||
{:help, :vault} ->
|
|
||||||
# vault 群組專屬說明
|
|
||||||
_ = Vault.run(:help, %{})
|
|
||||||
0
|
|
||||||
|
|
||||||
{:help, _} ->
|
{:help, _} ->
|
||||||
print_help()
|
print_help()
|
||||||
0
|
0
|
||||||
@@ -613,35 +153,6 @@ defmodule BearCli.CLI do
|
|||||||
IO.puts(:stderr, "錯誤:#{message}")
|
IO.puts(:stderr, "錯誤:#{message}")
|
||||||
code
|
code
|
||||||
|
|
||||||
# apps 指令群({:ok, {module, verb}, opts} 形狀;注入的 api 模組同時作為 apps_api)
|
|
||||||
{:ok, {Apps, verb}, cmd_opts} when is_atom(verb) ->
|
|
||||||
apps_api = cmd_opts[:apps_api] || opts[:apps_api] || Api
|
|
||||||
Apps.run(verb, Map.put(cmd_opts, :apps_api, apps_api))
|
|
||||||
|
|
||||||
# 個人自助指令群({:ok, {:self_service, group, verb}, opts} 形狀)
|
|
||||||
{:ok, {:self_service, group, verb}, cmd_opts} when is_atom(group) and is_atom(verb) ->
|
|
||||||
inject_opts = opts |> Map.new() |> Map.take([:ss_api, :io, :tty?])
|
|
||||||
ss_opts = Map.merge(inject_opts, Map.take(cmd_opts, [:ss_api, :io, :tty?]))
|
|
||||||
SelfService.run(group, verb, Map.merge(cmd_opts, ss_opts))
|
|
||||||
|
|
||||||
# 管理端指令群(jwks/accounts/audit-logs;各自注入對應的 api 模組)
|
|
||||||
{:ok, {Jwks, verb}, cmd_opts} when is_atom(verb) ->
|
|
||||||
jwks_api = cmd_opts[:jwks_api] || opts[:jwks_api] || Api
|
|
||||||
Jwks.run(verb, Map.put(cmd_opts, :jwks_api, jwks_api))
|
|
||||||
|
|
||||||
{:ok, {Accounts, verb}, cmd_opts} when is_atom(verb) ->
|
|
||||||
accounts_api = cmd_opts[:accounts_api] || opts[:accounts_api] || Api
|
|
||||||
Accounts.run(verb, Map.put(cmd_opts, :accounts_api, accounts_api))
|
|
||||||
|
|
||||||
{:ok, {AuditLogs, verb}, cmd_opts} when is_atom(verb) ->
|
|
||||||
audit_logs_api = cmd_opts[:audit_logs_api] || opts[:audit_logs_api] || Api
|
|
||||||
AuditLogs.run(verb, Map.put(cmd_opts, :audit_logs_api, audit_logs_api))
|
|
||||||
|
|
||||||
# vault 指令群({:ok, {BearCli.Vault, verb}, opts} 形狀)
|
|
||||||
{:ok, {BearCli.Vault, verb}, cmd_opts} when is_atom(verb) ->
|
|
||||||
vault_opts = opts |> Map.new() |> Map.take([:vault_api, :io, :tty?, :session, :email])
|
|
||||||
Vault.run(verb, Map.merge(cmd_opts, vault_opts))
|
|
||||||
|
|
||||||
{:ok, command, cmd_opts} ->
|
{:ok, command, cmd_opts} ->
|
||||||
cond do
|
cond do
|
||||||
cmd_opts[:version] ->
|
cmd_opts[:version] ->
|
||||||
@@ -677,25 +188,61 @@ defmodule BearCli.CLI do
|
|||||||
end
|
end
|
||||||
|
|
||||||
defp run(:whoami, opts, api) do
|
defp run(:whoami, opts, api) do
|
||||||
case Config.env_token() do
|
case Credentials.load() do
|
||||||
# BEAR_TOKEN 優先於憑證檔(不讀檔、不寫檔)。
|
{:ok, creds} ->
|
||||||
nil ->
|
issuer = resolve_issuer(opts, creds["issuer"])
|
||||||
whoami_from_credentials(opts, api)
|
token = creds["access_token"]
|
||||||
|
|
||||||
token ->
|
if blank?(token) do
|
||||||
call_userinfo(resolve_issuer(opts), token, opts, api)
|
fail(opts, "憑證檔缺少 access_token,請重新 bear login", 7)
|
||||||
|
else
|
||||||
|
if opts[:verbose], do: IO.puts(:stderr, "issuer: #{issuer}")
|
||||||
|
|
||||||
|
case api.(issuer, token) do
|
||||||
|
{:ok, claims} ->
|
||||||
|
if opts[:json] do
|
||||||
|
IO.puts(Jason.encode!(%{ok: true, claims: claims}))
|
||||||
|
else
|
||||||
|
print_claims(claims)
|
||||||
|
end
|
||||||
|
|
||||||
|
0
|
||||||
|
|
||||||
|
{:error, :unauthorized, desc} ->
|
||||||
|
fail(opts, "token 無效或已過期(#{desc}),請重新 bear login", 1)
|
||||||
|
|
||||||
|
{:error, :network, reason} ->
|
||||||
|
fail(opts, "無法連線到 #{issuer}:#{reason}", 6)
|
||||||
|
|
||||||
|
{:error, :server_error, status} ->
|
||||||
|
fail(opts, "伺服器回應 #{status}", 6)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
:error ->
|
||||||
|
fail(opts, "未登入(請先執行 bear login)", 3)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
defp run(:token, opts, _api) do
|
defp run(:token, opts, _api) do
|
||||||
cond do
|
case Credentials.load() do
|
||||||
# BEAR_TOKEN 優先於憑證檔(一次性/CI 用,不寫入)。
|
{:ok, creds} ->
|
||||||
token = Config.env_token() ->
|
if opts[:refresh] do
|
||||||
IO.puts(token)
|
IO.puts(:stderr, "警告:PAT 模式無 refresh token,--refresh 已忽略。")
|
||||||
0
|
end
|
||||||
|
|
||||||
true ->
|
case creds["access_token"] do
|
||||||
token_from_credentials(opts)
|
token when is_binary(token) and token != "" ->
|
||||||
|
# token 指令只輸出 token 本體(單行、無前綴),供 pipe 使用。
|
||||||
|
IO.puts(token)
|
||||||
|
0
|
||||||
|
|
||||||
|
_ ->
|
||||||
|
fail_token("憑證檔缺少 access_token,請重新 bear login", 7)
|
||||||
|
end
|
||||||
|
|
||||||
|
:error ->
|
||||||
|
fail_token("未登入(請先執行 bear login)", 3)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -717,100 +264,6 @@ defmodule BearCli.CLI do
|
|||||||
end
|
end
|
||||||
|
|
||||||
defp run(:status, opts, _api) do
|
defp run(:status, opts, _api) do
|
||||||
env_token = Config.env_token()
|
|
||||||
|
|
||||||
cond do
|
|
||||||
env_token ->
|
|
||||||
issuer = resolve_issuer(opts)
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(
|
|
||||||
Jason.encode!(%{
|
|
||||||
ok: true,
|
|
||||||
logged_in: true,
|
|
||||||
mode: "env_token",
|
|
||||||
issuer: issuer
|
|
||||||
})
|
|
||||||
)
|
|
||||||
else
|
|
||||||
IO.puts("已登入(BEAR_TOKEN 環境變數)")
|
|
||||||
IO.puts("模式:個人存取權杖(環境變數,不寫入憑證檔)")
|
|
||||||
IO.puts("issuer:#{issuer}")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
true ->
|
|
||||||
status_from_credentials(opts)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 指令實作輔助 --
|
|
||||||
|
|
||||||
defp whoami_from_credentials(opts, api) do
|
|
||||||
case Credentials.load() do
|
|
||||||
{:ok, creds} ->
|
|
||||||
token = creds["access_token"]
|
|
||||||
|
|
||||||
if blank?(token) do
|
|
||||||
fail(opts, "憑證檔缺少 access_token,請重新 bear login", 7)
|
|
||||||
else
|
|
||||||
call_userinfo(resolve_issuer(opts, creds["issuer"]), token, opts, api)
|
|
||||||
end
|
|
||||||
|
|
||||||
:error ->
|
|
||||||
fail(opts, "未登入(請先執行 bear login)", 3)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp call_userinfo(issuer, token, opts, api) do
|
|
||||||
if opts[:verbose], do: IO.puts(:stderr, "issuer: #{issuer}")
|
|
||||||
|
|
||||||
case api.(issuer, token) do
|
|
||||||
{:ok, claims} ->
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, claims: claims}))
|
|
||||||
else
|
|
||||||
print_claims(claims)
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, :unauthorized, desc} ->
|
|
||||||
fail(opts, "token 無效或已過期(#{desc}),請重新 bear login", 3)
|
|
||||||
|
|
||||||
{:error, :network, reason} ->
|
|
||||||
fail(opts, "無法連線到 #{issuer}:#{reason}", 6)
|
|
||||||
|
|
||||||
{:error, :server_error, status} ->
|
|
||||||
fail(opts, "伺服器回應 #{status}", 6)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp token_from_credentials(opts) do
|
|
||||||
case Credentials.load() do
|
|
||||||
{:ok, creds} ->
|
|
||||||
if opts[:refresh] do
|
|
||||||
# 規格 §3.3:PAT 模式下 --refresh 為無效選項,報用法錯誤。
|
|
||||||
fail_token("PAT 模式無 refresh token,--refresh 為無效選項", 2)
|
|
||||||
else
|
|
||||||
case creds["access_token"] do
|
|
||||||
token when is_binary(token) and token != "" ->
|
|
||||||
# token 指令只輸出 token 本體(單行、無前綴),供 pipe 使用。
|
|
||||||
IO.puts(token)
|
|
||||||
0
|
|
||||||
|
|
||||||
_ ->
|
|
||||||
fail_token("憑證檔缺少 access_token,請重新 bear login", 7)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
:error ->
|
|
||||||
fail_token("未登入(請先執行 bear login)", 3)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp status_from_credentials(opts) do
|
|
||||||
case Credentials.load() do
|
case Credentials.load() do
|
||||||
{:ok, creds} ->
|
{:ok, creds} ->
|
||||||
if opts[:json] do
|
if opts[:json] do
|
||||||
@@ -869,8 +322,7 @@ defmodule BearCli.CLI do
|
|||||||
end
|
end
|
||||||
|
|
||||||
{:error, :unauthorized, desc} ->
|
{:error, :unauthorized, desc} ->
|
||||||
# 規格 §3.1:PAT 無效或已撤銷 → 退出碼 3。
|
fail(opts, "token 無效或已過期(#{desc})", 1)
|
||||||
fail(opts, "PAT 無效或已撤銷(#{desc}),不寫入任何資料", 3)
|
|
||||||
|
|
||||||
{:error, :network, reason} ->
|
{:error, :network, reason} ->
|
||||||
fail(opts, "無法連線到 #{issuer}:#{reason}", 6)
|
fail(opts, "無法連線到 #{issuer}:#{reason}", 6)
|
||||||
@@ -946,70 +398,9 @@ defmodule BearCli.CLI do
|
|||||||
指令:
|
指令:
|
||||||
login --token <PAT> 以個人存取權杖登入(PAT 模式;Device Flow 尚未開放)
|
login --token <PAT> 以個人存取權杖登入(PAT 模式;Device Flow 尚未開放)
|
||||||
whoami 顯示目前登入身分
|
whoami 顯示目前登入身分
|
||||||
token [--refresh] 印出 access token(PAT 模式下 --refresh 為用法錯誤)
|
token [--refresh] 印出 access token(PAT 模式下 --refresh 為無作用)
|
||||||
logout 登出(清除本機憑證)
|
logout 登出(清除本機憑證)
|
||||||
status 顯示登入狀態
|
status 顯示登入狀態
|
||||||
apps <動詞> App 管理(admin;bear apps --help 查看)
|
|
||||||
jwks <動詞> 簽章金鑰管理(admin)
|
|
||||||
accounts <動詞> 帳號管理(admin)
|
|
||||||
audit-logs list 稽核日誌(admin)
|
|
||||||
profile <動詞> 個人資料(show/set)
|
|
||||||
password change 變更密碼(互動輸入,不進 shell history)
|
|
||||||
email change --new E 變更 email(雙向驗證碼流程)
|
|
||||||
sessions <動詞> 管理網頁 session(list/revoke/revoke-others)
|
|
||||||
tokens <動詞> 管理 PAT(list/create/revoke)
|
|
||||||
mfa <動詞> TOTP 兩因子(status/setup/disable/recovery-codes)
|
|
||||||
|
|
||||||
apps 指令群(需 admin 權限的 PAT):
|
|
||||||
apps list [--visibility public|internal] [--status active|inactive]
|
|
||||||
[--page N] [--per-page N]
|
|
||||||
apps show <client-id>
|
|
||||||
apps create --client-id ID --url URL --title TITLE
|
|
||||||
[--method client_secret|PKCE] [--visibility public|internal]
|
|
||||||
[--redirect-url URL]... [--post-logout-redirect-uri URI]...
|
|
||||||
[--scope SCOPE]... [--sub FIELD] [--jwk-id ID] [--secret SECRET]
|
|
||||||
apps update <client-id> [同 create 的選項;只更新有給的欄位]
|
|
||||||
apps rotate-secret <client-id>
|
|
||||||
apps toggle <client-id>
|
|
||||||
|
|
||||||
個人自助指令群(任何有效 PAT 皆可):
|
|
||||||
profile show
|
|
||||||
profile set [--name NAME] [--given-name NAME] [--family-name NAME]
|
|
||||||
[--nickname NAME] [--preferred-username NAME]
|
|
||||||
[--profile URL] [--picture URL] [--website URL]
|
|
||||||
[--gender male|female|other] [--birthdate YYYY-MM-DD]
|
|
||||||
[--zoneinfo TZ] [--locale LOC] [--phone-number E164]
|
|
||||||
[--phone-verified] [--address-formatted TEXT]
|
|
||||||
[--address-street-address TEXT] [--address-locality TEXT]
|
|
||||||
[--address-region TEXT] [--address-postal-code TEXT]
|
|
||||||
[--address-country TEXT]
|
|
||||||
password change
|
|
||||||
email change --new EMAIL
|
|
||||||
sessions list
|
|
||||||
sessions revoke <id>
|
|
||||||
sessions revoke-others
|
|
||||||
tokens list
|
|
||||||
tokens create --name NAME [--expires-in DAYS|never]
|
|
||||||
tokens revoke <id>
|
|
||||||
mfa status
|
|
||||||
mfa setup
|
|
||||||
mfa disable
|
|
||||||
mfa recovery-codes
|
|
||||||
vault 指令群(任何有效 PAT 皆可;詳見 bear vault --help 與 docs/commands.md §3.11):
|
|
||||||
vault status 初始化狀態、KDF 參數、解鎖狀態
|
|
||||||
vault unlock 主密碼解鎖 → 匯出 BEAR_VAULT_SESSION
|
|
||||||
vault lock 丟棄 session(unset 環境變數)
|
|
||||||
vault list [--folder UUID] 列出項目(解鎖後顯示明文名稱)
|
|
||||||
vault get <uuid> 顯示單一項目(解鎖後解密欄位)
|
|
||||||
vault create --type login|secure_note|card|identity [--folder UUID]
|
|
||||||
vault edit <uuid> 互動編輯(Enter 保留現值)
|
|
||||||
vault delete <uuid> 丟入回收桶
|
|
||||||
vault restore <uuid> 從回收桶還原
|
|
||||||
vault purge <uuid> 永久刪除(需確認)
|
|
||||||
vault folders list|create|rename <uuid>|delete <uuid>
|
|
||||||
vault sync 完整同步(伺服器為準)
|
|
||||||
vault password change 變更 vault 主密碼
|
|
||||||
vault rescue 助記詞救援(重設主密碼)
|
|
||||||
|
|
||||||
全域選項:
|
全域選項:
|
||||||
--issuer URL Bear(OIDC Provider)位址(預設 https://alterminal.com)
|
--issuer URL Bear(OIDC Provider)位址(預設 https://alterminal.com)
|
||||||
@@ -1018,10 +409,6 @@ defmodule BearCli.CLI do
|
|||||||
-v, --verbose 顯示詳細日誌
|
-v, --verbose 顯示詳細日誌
|
||||||
-h, --help 顯示說明
|
-h, --help 顯示說明
|
||||||
--version 顯示版本
|
--version 顯示版本
|
||||||
|
|
||||||
環境變數:
|
|
||||||
BEAR_TOKEN 一次性/CI 用的 PAT;提供後 whoami/token/status 優先
|
|
||||||
使用,不寫入憑證檔
|
|
||||||
""")
|
""")
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -78,18 +78,6 @@ defmodule BearCli.Config do
|
|||||||
)
|
)
|
||||||
end
|
end
|
||||||
|
|
||||||
@doc """
|
|
||||||
`BEAR_TOKEN` 環境變數(一次性/CI 用的 PAT)。
|
|
||||||
|
|
||||||
提供後優先於本機憑證檔,但不寫入憑證檔。空值或純空白視為未提供。
|
|
||||||
"""
|
|
||||||
def env_token do
|
|
||||||
case System.get_env("BEAR_TOKEN") do
|
|
||||||
nil -> nil
|
|
||||||
token -> if blank?(String.trim(token)), do: nil, else: String.trim(token)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp blank?(nil), do: true
|
defp blank?(nil), do: true
|
||||||
defp blank?(""), do: true
|
defp blank?(""), do: true
|
||||||
defp blank?(_), do: false
|
defp blank?(_), do: false
|
||||||
|
|||||||
@@ -1,198 +0,0 @@
|
|||||||
defmodule BearCli.Jwks do
|
|
||||||
@moduledoc """
|
|
||||||
`bear jwks` 指令群(簽章金鑰管理;docs/commands.md §3.8、issue #12)。
|
|
||||||
|
|
||||||
對應伺服器端 JWK 管理 JSON API(alterminal/bear#46,`/api/v1/jwks`、
|
|
||||||
PAT Bearer、admin 限定)。認證沿用既有 PAT 憑證(`BEAR_TOKEN` 或憑證檔)。
|
|
||||||
|
|
||||||
金鑰材質(`key_data`)永不經 CLI 顯示(API 端即不序列化);本群組只管理
|
|
||||||
公開中繼資料(kid/kty/alg/active 等)。
|
|
||||||
|
|
||||||
退出碼:0 成功;1 404/422;2 用法錯誤;3 未登入或 401;6 網路/伺服器
|
|
||||||
錯誤;8 權限不足(403,僅限 admin)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import BearCli.Admin, only: [context: 1, fail: 3, format_api_error: 2]
|
|
||||||
alias BearCli.Api
|
|
||||||
|
|
||||||
# -- 入口 --
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
執行 `bear jwks <動詞>`,回傳退出碼。`opts[:jwks_api]` 可注入假 API 模組
|
|
||||||
供測試(需實作 `jwks_list/2`、`jwks_create/3`、`jwks_get/3`、`jwks_toggle/3`)。
|
|
||||||
"""
|
|
||||||
def run(verb, opts) do
|
|
||||||
api = opts[:jwks_api] || Api
|
|
||||||
|
|
||||||
with {:ok, ctx} <- context(opts) do
|
|
||||||
execute(verb, ctx, opts, api)
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 各動詞 --
|
|
||||||
|
|
||||||
defp execute(:list, ctx, opts, api) do
|
|
||||||
case api.jwks_list(ctx.issuer, ctx.token) do
|
|
||||||
{:ok, body} ->
|
|
||||||
render_list(opts, body["data"] || [])
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:show, ctx, opts, api) do
|
|
||||||
with {:ok, key} <- resolve_key(ctx, opts[:kid_arg], api) do
|
|
||||||
case api.jwks_get(ctx.issuer, ctx.token, key["id"]) do
|
|
||||||
{:ok, body} ->
|
|
||||||
show_key(body["data"] || %{}, opts)
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:create, ctx, opts, api) do
|
|
||||||
attrs = %{"kid" => opts[:kid], "alg" => opts[:alg] || "RS256"}
|
|
||||||
|
|
||||||
case api.jwks_create(ctx.issuer, ctx.token, attrs) do
|
|
||||||
{:ok, body} ->
|
|
||||||
key = body["data"] || %{}
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, jwk: key}))
|
|
||||||
else
|
|
||||||
IO.puts("JWK 已建立:#{key["kid"]}(#{key["alg"]}/#{status_label(key)})")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:toggle, ctx, opts, api) do
|
|
||||||
with {:ok, key} <- resolve_key(ctx, opts[:kid_arg], api) do
|
|
||||||
case api.jwks_toggle(ctx.issuer, ctx.token, key["id"]) do
|
|
||||||
{:ok, body} ->
|
|
||||||
updated = body["data"] || %{}
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(
|
|
||||||
Jason.encode!(%{
|
|
||||||
ok: true,
|
|
||||||
jwk: %{id: updated["id"], kid: updated["kid"], active: updated["active"]}
|
|
||||||
})
|
|
||||||
)
|
|
||||||
else
|
|
||||||
IO.puts("#{key["kid"]}:#{status_label(key)} → #{status_label(updated)}")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- kid → UUID 解析(API 路徑參數為 UUID,CLI 對外介面用 kid)--
|
|
||||||
|
|
||||||
defp resolve_key(_ctx, nil, _api), do: {:error, "缺少 <kid> 參數", 2}
|
|
||||||
|
|
||||||
defp resolve_key(ctx, kid, api) do
|
|
||||||
case api.jwks_list(ctx.issuer, ctx.token) do
|
|
||||||
{:ok, body} ->
|
|
||||||
case Enum.find(body["data"] || [], &(&1["kid"] == kid)) do
|
|
||||||
nil -> {:error, "找不到 kid 為 #{kid} 的金鑰", 1}
|
|
||||||
key -> {:ok, key}
|
|
||||||
end
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
{message, code} = format_api_error(ctx, error)
|
|
||||||
{:error, message, code}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 輸出 --
|
|
||||||
|
|
||||||
defp render_list(opts, keys) do
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, jwks: keys}))
|
|
||||||
else
|
|
||||||
print_table(keys)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
@table_headers ["ID", "KID", "KTY", "ALG", "ACTIVE", "CREATED AT"]
|
|
||||||
|
|
||||||
defp print_table(keys) do
|
|
||||||
rows =
|
|
||||||
Enum.map(keys, fn key ->
|
|
||||||
[
|
|
||||||
String.slice(key["id"] || "", 0, 8),
|
|
||||||
key["kid"] || "",
|
|
||||||
key["kty"] || "",
|
|
||||||
key["alg"] || "",
|
|
||||||
status_label(key),
|
|
||||||
key["created_at"] || ""
|
|
||||||
]
|
|
||||||
end)
|
|
||||||
|
|
||||||
widths =
|
|
||||||
Enum.with_index(@table_headers, fn _header, i ->
|
|
||||||
Enum.max([
|
|
||||||
String.length(Enum.at(@table_headers, i))
|
|
||||||
| Enum.map(rows, &String.length(Enum.at(&1, i)))
|
|
||||||
])
|
|
||||||
end)
|
|
||||||
|
|
||||||
render_row = fn cells ->
|
|
||||||
cells
|
|
||||||
|> Enum.with_index()
|
|
||||||
|> Enum.map(fn {cell, i} -> String.pad_trailing(cell, Enum.at(widths, i)) end)
|
|
||||||
|> Enum.join(" ")
|
|
||||||
|> String.trim_trailing()
|
|
||||||
end
|
|
||||||
|
|
||||||
IO.puts(render_row.(@table_headers))
|
|
||||||
Enum.each(rows, fn cells -> IO.puts(render_row.(cells)) end)
|
|
||||||
end
|
|
||||||
|
|
||||||
@key_fields ~w(id kid kty alg use active created_at)
|
|
||||||
|
|
||||||
defp show_key(key, opts) do
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, jwk: key}))
|
|
||||||
else
|
|
||||||
Enum.each(@key_fields, fn field ->
|
|
||||||
IO.puts("#{String.pad_trailing(field, 14)}: #{format_key_value(key[field])}")
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_key_value(nil), do: "(無)"
|
|
||||||
defp format_key_value(value) when is_binary(value), do: value
|
|
||||||
defp format_key_value(value), do: Jason.encode!(value)
|
|
||||||
|
|
||||||
defp status_label(%{"active" => true}), do: "active"
|
|
||||||
defp status_label(%{"active" => false}), do: "inactive"
|
|
||||||
defp status_label(_), do: "(未知)"
|
|
||||||
|
|
||||||
# -- 錯誤處理 --
|
|
||||||
|
|
||||||
defp fail_api(opts, ctx, error) do
|
|
||||||
{message, code} = format_api_error(ctx, error)
|
|
||||||
fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,776 +0,0 @@
|
|||||||
defmodule BearCli.SelfService do
|
|
||||||
@moduledoc """
|
|
||||||
`bear` 個人自助指令群(docs/commands.md §3.7、issue #11)。
|
|
||||||
|
|
||||||
對應伺服器端個人自助 JSON API(alterminal/bear#35,`/api/v1/profile*`、
|
|
||||||
PAT Bearer、任何有效帳號):profile/password/email/sessions/
|
|
||||||
tokens/mfa。
|
|
||||||
|
|
||||||
- 敏感輸入(密碼、email/MFA 驗證碼)一律互動提示讀取且不回顧,
|
|
||||||
不接受命令列明文參數;非 TTY 環境 → 退出碼 2。
|
|
||||||
- 一次性明文(`tokens create` 的 PAT、`mfa` 的 recovery codes)只於
|
|
||||||
成功當下輸出於 stdout,不寫入憑證檔/log/`--verbose` 輸出。
|
|
||||||
|
|
||||||
退出碼:0 成功;1 404/422/429;2 用法錯誤(含非 TTY 的互動輸入);
|
|
||||||
3 未登入或 401;6 網路/伺服器錯誤;8 權限不足(403)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
alias BearCli.{Api, Config, Credentials, TTY}
|
|
||||||
|
|
||||||
@genders ~w(male female other)
|
|
||||||
|
|
||||||
# profile set 的可更新欄位:CLI 選項名(atom)→ API 欄位名。
|
|
||||||
@profile_set_fields [
|
|
||||||
name: "name",
|
|
||||||
given_name: "given_name",
|
|
||||||
family_name: "family_name",
|
|
||||||
nickname: "nickname",
|
|
||||||
preferred_username: "preferred_username",
|
|
||||||
profile: "profile",
|
|
||||||
picture: "picture",
|
|
||||||
website: "website",
|
|
||||||
gender: "gender",
|
|
||||||
birthdate: "birthdate",
|
|
||||||
zoneinfo: "zoneinfo",
|
|
||||||
locale: "locale",
|
|
||||||
phone_number: "phone_number",
|
|
||||||
phone_verified: "phone_number_verified",
|
|
||||||
address_formatted: "address_formatted",
|
|
||||||
address_street_address: "address_street_address",
|
|
||||||
address_locality: "address_locality",
|
|
||||||
address_region: "address_region",
|
|
||||||
address_postal_code: "address_postal_code",
|
|
||||||
address_country: "address_country"
|
|
||||||
]
|
|
||||||
|
|
||||||
@url_fields ~w(profile picture website)
|
|
||||||
|
|
||||||
# -- 入口 --
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
執行個人自助指令,回傳退出碼。`group` 為 :profile/:password/:email/
|
|
||||||
:sessions/:tokens/:mfa,`verb` 為子指令 atom,`opts` 為解析後選項。
|
|
||||||
|
|
||||||
`opts[:ss_api]` 可注入假 API 模組供測試;`opts[:io]` 可注入互動輸入
|
|
||||||
模組(實作 `prompt_secret/1`),`opts[:tty?]` 可覆寫 TTY 判定。
|
|
||||||
"""
|
|
||||||
def run(group, verb, opts) do
|
|
||||||
api = opts[:ss_api] || Api
|
|
||||||
|
|
||||||
with {:ok, ctx} <- context(opts) do
|
|
||||||
execute(group, verb, ctx, opts, api)
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 各指令實作(execute/5 子句群)--
|
|
||||||
|
|
||||||
defp execute(:profile, :show, ctx, opts, api) do
|
|
||||||
case api.profile_get(ctx.issuer, ctx.token) do
|
|
||||||
{:ok, body} ->
|
|
||||||
show_profile(body["data"] || %{}, opts)
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:profile, :set, ctx, opts, api) do
|
|
||||||
case build_profile_attrs(opts) do
|
|
||||||
{:ok, attrs} ->
|
|
||||||
case api.profile_update(ctx.issuer, ctx.token, attrs) do
|
|
||||||
{:ok, body} ->
|
|
||||||
show_profile(body["data"] || %{}, opts)
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
|
|
||||||
{:error, message, code} ->
|
|
||||||
fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:password, :change, ctx, opts, api) do
|
|
||||||
with {:ok, {current, new}} <- read_password_prompts(opts) do
|
|
||||||
case api.profile_change_password(ctx.issuer, ctx.token, current, new) do
|
|
||||||
{:ok, _body} ->
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true}))
|
|
||||||
else
|
|
||||||
IO.puts("密碼已變更")
|
|
||||||
IO.puts("提醒:變更密碼不自動撤銷其他 session;需要時另用 bear sessions revoke-others。")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:email, :change, ctx, opts, api) do
|
|
||||||
# OptionParser 把 --new EMAIL 正規化為 :new(底線)。
|
|
||||||
new_email = opts[:new] || opts[:new_email]
|
|
||||||
|
|
||||||
with :ok <- require_new_email(new_email),
|
|
||||||
{:ok, {current_code, new_code}} <- request_and_read_codes(ctx, opts, api, new_email) do
|
|
||||||
case api.profile_email_change(ctx.issuer, ctx.token, new_email, current_code, new_code) do
|
|
||||||
{:ok, body} ->
|
|
||||||
updated = (body["data"] || %{})["email"] || new_email
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, email: updated}))
|
|
||||||
else
|
|
||||||
IO.puts("email 已更新:#{updated}")
|
|
||||||
IO.puts("提醒:bear login 用的 PAT 不綁 email,不受影響。")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:sessions, :list, ctx, opts, api) do
|
|
||||||
case api.sessions_list(ctx.issuer, ctx.token) do
|
|
||||||
{:ok, body} ->
|
|
||||||
sessions = body["data"] || []
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, sessions: sessions}))
|
|
||||||
else
|
|
||||||
print_sessions_table(sessions)
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:sessions, :revoke, ctx, opts, api) do
|
|
||||||
id = opts[:id_arg]
|
|
||||||
|
|
||||||
with :ok <- require_id(id, "sessions revoke") do
|
|
||||||
case api.sessions_revoke(ctx.issuer, ctx.token, id) do
|
|
||||||
{:ok, _body} ->
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, revoked: id}))
|
|
||||||
else
|
|
||||||
IO.puts("session 已撤銷")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:sessions, :"revoke-others", ctx, opts, api) do
|
|
||||||
case api.sessions_revoke_others(ctx.issuer, ctx.token) do
|
|
||||||
{:ok, body} ->
|
|
||||||
count = (body["data"] || %{})["revoked_count"]
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, revoked: count}))
|
|
||||||
else
|
|
||||||
IO.puts("已撤銷 #{count} 個其他 session")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:tokens, :list, ctx, opts, api) do
|
|
||||||
case api.tokens_list(ctx.issuer, ctx.token) do
|
|
||||||
{:ok, body} ->
|
|
||||||
tokens = body["data"] || []
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, tokens: tokens}))
|
|
||||||
else
|
|
||||||
print_tokens_table(tokens)
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:tokens, :create, ctx, opts, api) do
|
|
||||||
name = opts[:name]
|
|
||||||
|
|
||||||
with {:ok, expires_in} <- parse_expires_in(opts[:expires_in]) do
|
|
||||||
case api.tokens_create(ctx.issuer, ctx.token, name, expires_in) do
|
|
||||||
{:ok, body} ->
|
|
||||||
token = body["data"] || %{}
|
|
||||||
raw = body["token"]
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, token: token, raw: raw}))
|
|
||||||
else
|
|
||||||
expires_at = token["expires_at"]
|
|
||||||
expiry_note = if expires_at, do: "(#{expires_at} 到期)", else: "(無到期日)"
|
|
||||||
|
|
||||||
IO.puts("PAT 已建立:#{token["name"]}#{expiry_note}")
|
|
||||||
IO.puts("token(只顯示這一次,請立即保存):")
|
|
||||||
IO.puts(" #{raw}")
|
|
||||||
IO.puts("提醒:新 PAT 要使用須另以 bear login --token 登入(或設 BEAR_TOKEN)。")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:tokens, :revoke, ctx, opts, api) do
|
|
||||||
id = opts[:id_arg]
|
|
||||||
|
|
||||||
with :ok <- require_id(id, "tokens revoke") do
|
|
||||||
case api.tokens_revoke(ctx.issuer, ctx.token, id) do
|
|
||||||
{:ok, body} ->
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, revoked: (body["data"] || %{})["revoked"] || id}))
|
|
||||||
else
|
|
||||||
IO.puts("PAT 已撤銷")
|
|
||||||
end
|
|
||||||
|
|
||||||
# 撤銷目前憑證用的 PAT 時,後續指令會得 401;本機憑證檔只存 PAT
|
|
||||||
# 明文、未存 token id,CLI 無法可靠比對,一律提示重新登入的退路。
|
|
||||||
IO.puts(
|
|
||||||
:stderr,
|
|
||||||
"提醒:若撤銷的是本機憑證所用的 PAT,後續指令會得到 401;屆時重新 bear login。"
|
|
||||||
)
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:mfa, :status, ctx, opts, api) do
|
|
||||||
case api.profile_get(ctx.issuer, ctx.token) do
|
|
||||||
{:ok, body} ->
|
|
||||||
data = body["data"] || %{}
|
|
||||||
enabled = data["mfa_enabled"] || data["totp_enabled"] || false
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, totp_enabled: enabled}))
|
|
||||||
else
|
|
||||||
IO.puts("MFA(TOTP):#{if enabled, do: "已啟用", else: "未啟用"}")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:mfa, :setup, ctx, opts, api) do
|
|
||||||
with {:ok, _data} <- mfa_begin(ctx, opts, api),
|
|
||||||
{:ok, code} <- prompt_secret(opts, "6 位驗證碼(掃描 QR 後由驗證器產生)") do
|
|
||||||
case api.mfa_setup_confirm(ctx.issuer, ctx.token, code) do
|
|
||||||
{:ok, body} ->
|
|
||||||
codes = (body["data"] || %{})["recovery_codes"] || []
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, recovery_codes: codes}))
|
|
||||||
else
|
|
||||||
IO.puts("MFA 已啟用。")
|
|
||||||
print_recovery_codes(codes)
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:mfa, :disable, ctx, opts, api) do
|
|
||||||
with {:ok, code} <- prompt_secret(opts, "目前的 TOTP 碼或 recovery code") do
|
|
||||||
case api.mfa_disable(ctx.issuer, ctx.token, code) do
|
|
||||||
{:ok, _body} ->
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true}))
|
|
||||||
else
|
|
||||||
IO.puts("MFA 已停用")
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp execute(:mfa, :"recovery-codes", ctx, opts, api) do
|
|
||||||
with {:ok, code} <- prompt_secret(opts, "目前的 TOTP 碼或 recovery code") do
|
|
||||||
case api.mfa_recovery_codes(ctx.issuer, ctx.token, code) do
|
|
||||||
{:ok, body} ->
|
|
||||||
codes = (body["data"] || %{})["recovery_codes"] || []
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, recovery_codes: codes}))
|
|
||||||
else
|
|
||||||
print_recovery_codes(codes)
|
|
||||||
end
|
|
||||||
|
|
||||||
0
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
fail_api(opts, ctx, error)
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, message, code} -> fail(opts, message, code)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 共用背景(token/issuer)--
|
|
||||||
|
|
||||||
defp context(opts) do
|
|
||||||
if token = Config.env_token() do
|
|
||||||
# BEAR_TOKEN 優先於憑證檔(不讀檔、不寫檔)。
|
|
||||||
{:ok, %{token: token, issuer: resolve_issuer(opts, nil)}}
|
|
||||||
else
|
|
||||||
case Credentials.load() do
|
|
||||||
{:ok, creds} ->
|
|
||||||
token = creds["access_token"]
|
|
||||||
|
|
||||||
if blank?(token) do
|
|
||||||
{:error, "憑證檔缺少 access_token,請重新 bear login", 7}
|
|
||||||
else
|
|
||||||
{:ok, %{token: token, issuer: resolve_issuer(opts, creds["issuer"])}}
|
|
||||||
end
|
|
||||||
|
|
||||||
:error ->
|
|
||||||
{:error, "未登入(請先執行 bear login)", 3}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp resolve_issuer(opts, stored_issuer) do
|
|
||||||
opts[:issuer] || stored_issuer || Config.resolve_issuer(nil, opts[:config])
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- profile set 屬性組裝與本地驗證 --
|
|
||||||
|
|
||||||
# 只送有給的欄位(§3.7.2);非法值本地檢查 → 用法錯誤 2,不發請求。
|
|
||||||
defp build_profile_attrs(opts) do
|
|
||||||
given =
|
|
||||||
@profile_set_fields
|
|
||||||
|> Enum.flat_map(fn {opt_key, api_key} ->
|
|
||||||
case Map.get(opts, opt_key) do
|
|
||||||
v when is_binary(v) and v != "" -> [{api_key, v}]
|
|
||||||
true -> [{api_key, true}]
|
|
||||||
_other -> []
|
|
||||||
end
|
|
||||||
end)
|
|
||||||
|> Map.new()
|
|
||||||
|
|
||||||
cond do
|
|
||||||
given == %{} ->
|
|
||||||
{:error, "profile set 未給任何欄位(可用選項見 bear --help)", 2}
|
|
||||||
|
|
||||||
invalid_gender?(given) ->
|
|
||||||
{:error, "--gender 不接受的值:#{given["gender"]}(可用:#{Enum.join(@genders, "、")})", 2}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
check_url_fields(given)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp invalid_gender?(%{"gender" => g}), do: g not in @genders
|
|
||||||
defp invalid_gender?(_), do: false
|
|
||||||
|
|
||||||
# URL 類欄位本地檢查 http(s)://(§3.7.2)。
|
|
||||||
defp check_url_fields(given) do
|
|
||||||
bad =
|
|
||||||
Enum.find(@url_fields, fn field ->
|
|
||||||
case given[field] do
|
|
||||||
v when is_binary(v) ->
|
|
||||||
not (String.starts_with?(v, "http://") or String.starts_with?(v, "https://"))
|
|
||||||
|
|
||||||
_ ->
|
|
||||||
false
|
|
||||||
end
|
|
||||||
end)
|
|
||||||
|
|
||||||
case bad do
|
|
||||||
nil -> {:ok, given}
|
|
||||||
field -> {:error, "--#{String.replace(field, "_", "-")} 需為 http(s):// 開頭的 URL", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- password 互動輸入 --
|
|
||||||
|
|
||||||
defp read_password_prompts(opts) do
|
|
||||||
with {:ok, current} <- prompt_secret(opts, "目前密碼"),
|
|
||||||
{:ok, new} <- prompt_secret(opts, "新密碼"),
|
|
||||||
{:ok, confirm} <- prompt_secret(opts, "確認新密碼") do
|
|
||||||
if new == confirm do
|
|
||||||
{:ok, {current, new}}
|
|
||||||
else
|
|
||||||
# 兩次新密碼不一致 → 本地檢查,不發請求(§3.7.3)。
|
|
||||||
{:error, "兩次輸入的新密碼不一致", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- email 流程輔助 --
|
|
||||||
|
|
||||||
defp require_new_email(nil), do: {:error, "email change 缺少 --new EMAIL", 2}
|
|
||||||
defp require_new_email(""), do: {:error, "email change 缺少 --new EMAIL", 2}
|
|
||||||
defp require_new_email(_), do: :ok
|
|
||||||
|
|
||||||
defp request_and_read_codes(ctx, opts, api, new_email) do
|
|
||||||
case api.profile_email_request_codes(ctx.issuer, ctx.token, new_email) do
|
|
||||||
{:ok, _body} ->
|
|
||||||
IO.puts(:stderr, "驗證碼已寄至現有信箱與 #{new_email},請查收。")
|
|
||||||
|
|
||||||
with {:ok, current_code} <- prompt_secret(opts, "現有信箱驗證碼"),
|
|
||||||
{:ok, new_code} <- prompt_secret(opts, "新信箱驗證碼") do
|
|
||||||
{:ok, {current_code, new_code}}
|
|
||||||
end
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
{message, code} = format_api_error(ctx, error)
|
|
||||||
{:error, message, code}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- tokens create 選項 --
|
|
||||||
|
|
||||||
# --expires-in:正整數天數或 never;預設 30(§3.7.6)。
|
|
||||||
defp parse_expires_in(nil), do: {:ok, "30"}
|
|
||||||
defp parse_expires_in("never"), do: {:ok, "never"}
|
|
||||||
|
|
||||||
defp parse_expires_in(value) when is_binary(value) do
|
|
||||||
case Integer.parse(value) do
|
|
||||||
{n, ""} when n > 0 -> {:ok, value}
|
|
||||||
_ -> {:error, "--expires-in 需為正整數天數或 never", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- mfa setup 第一步 --
|
|
||||||
|
|
||||||
defp mfa_begin(ctx, opts, api) do
|
|
||||||
case api.mfa_setup(ctx.issuer, ctx.token) do
|
|
||||||
{:ok, body} ->
|
|
||||||
data = body["data"] || %{}
|
|
||||||
secret = data["secret"]
|
|
||||||
uri = data["otpauth_uri"]
|
|
||||||
|
|
||||||
if opts[:json] do
|
|
||||||
# 兩步互動流程:第一步資訊走 stderr(stdout 保留給最終結果 JSON,
|
|
||||||
# 維持單一 JSON 物件的機器可讀輸出)。
|
|
||||||
IO.puts(
|
|
||||||
:stderr,
|
|
||||||
Jason.encode!(%{step: "setup", secret: secret, otpauth_uri: uri})
|
|
||||||
)
|
|
||||||
else
|
|
||||||
IO.puts("請用驗證器(Google Authenticator 等)掃描 QR,或手動輸入:")
|
|
||||||
IO.puts(" otpauth URI:#{uri}")
|
|
||||||
IO.puts(" secret(Base32):#{secret}")
|
|
||||||
print_qr(uri)
|
|
||||||
end
|
|
||||||
|
|
||||||
{:ok, data}
|
|
||||||
|
|
||||||
{:error, _kind, _detail} = error ->
|
|
||||||
{message, code} = format_api_error(ctx, error)
|
|
||||||
{:error, message, code}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 互動輸入 --
|
|
||||||
|
|
||||||
# 敏感輸入一律互動提示讀取且不回顯;非 TTY → 退出碼 2(§3.7 群組共通)。
|
|
||||||
# 測試可注入 opts[:io](實作 prompt_secret/1)與 opts[:tty?]。
|
|
||||||
defp prompt_secret(opts, label) do
|
|
||||||
tty? = Map.get(opts, :tty?, true)
|
|
||||||
io = opts[:io]
|
|
||||||
|
|
||||||
cond do
|
|
||||||
not tty? ->
|
|
||||||
{:error, "此指令需要互動輸入(#{label}),請在終端機執行", 2}
|
|
||||||
|
|
||||||
io ->
|
|
||||||
case io.prompt_secret(label) do
|
|
||||||
:eof -> {:error, "未讀到輸入(#{label})", 2}
|
|
||||||
{:ok, value} -> {:ok, value}
|
|
||||||
end
|
|
||||||
|
|
||||||
true ->
|
|
||||||
# 非 TTY(pipe/redirect)讀不到互動輸入 → 退出碼 2(§3.7 群組共通)。
|
|
||||||
if tty_stdin?() do
|
|
||||||
case IO.gets("#{label}:") do
|
|
||||||
:eof -> {:error, "未讀到輸入(#{label})", 2}
|
|
||||||
line -> {:ok, String.trim(line)}
|
|
||||||
end
|
|
||||||
else
|
|
||||||
{:error, "此指令需要互動輸入(#{label}),請在終端機執行", 2}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# stdin 是否為 TTY:優先以 fd 0 實際裝置判定(escript 環境 :io.rows/0 一律
|
|
||||||
# enotsup,真終端機會被誤判;見 BearCli.TTY,issue #19)。
|
|
||||||
defp tty_stdin? do
|
|
||||||
TTY.stdin_tty?()
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 輸出 --
|
|
||||||
|
|
||||||
@profile_fields ~w(id email role name given_name family_name nickname preferred_username profile picture website gender birthdate zoneinfo locale phone_number phone_number_verified address mfa_enabled created_at updated_at)
|
|
||||||
|
|
||||||
defp show_profile(profile, opts) do
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: true, profile: profile}))
|
|
||||||
else
|
|
||||||
Enum.each(@profile_fields, fn key ->
|
|
||||||
if Map.has_key?(profile, key) do
|
|
||||||
IO.puts("#{String.pad_trailing(key, 22)}: #{format_value(profile[key])}")
|
|
||||||
end
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_value(nil), do: "(無)"
|
|
||||||
defp format_value(true), do: "true"
|
|
||||||
defp format_value(false), do: "false"
|
|
||||||
defp format_value(v) when is_binary(v), do: v
|
|
||||||
defp format_value(v) when is_number(v), do: to_string(v)
|
|
||||||
defp format_value(v), do: Jason.encode!(v)
|
|
||||||
|
|
||||||
@sessions_headers ["ID", "IP", "USER AGENT", "CREATED", "LAST SEEN"]
|
|
||||||
|
|
||||||
defp print_sessions_table(sessions) do
|
|
||||||
rows =
|
|
||||||
Enum.map(sessions, fn s ->
|
|
||||||
[
|
|
||||||
s["id"] || "",
|
|
||||||
s["ip"] || "",
|
|
||||||
truncate(s["user_agent"] || "", 28),
|
|
||||||
s["created_at"] || "",
|
|
||||||
s["last_seen_at"] || ""
|
|
||||||
]
|
|
||||||
end)
|
|
||||||
|
|
||||||
print_table(@sessions_headers, rows)
|
|
||||||
end
|
|
||||||
|
|
||||||
@tokens_headers ["ID", "NAME", "SCOPE", "CREATED", "EXPIRES", "LAST USED", "STATUS"]
|
|
||||||
|
|
||||||
defp print_tokens_table(tokens) do
|
|
||||||
rows =
|
|
||||||
Enum.map(tokens, fn t ->
|
|
||||||
[
|
|
||||||
t["id"] || "",
|
|
||||||
t["name"] || "",
|
|
||||||
t["scope"] || "",
|
|
||||||
t["created_at"] || "",
|
|
||||||
t["expires_at"] || "(無到期)",
|
|
||||||
t["last_used_at"] || "(未使用)",
|
|
||||||
token_status(t)
|
|
||||||
]
|
|
||||||
end)
|
|
||||||
|
|
||||||
print_table(@tokens_headers, rows)
|
|
||||||
end
|
|
||||||
|
|
||||||
# list 僅回未撤銷 token;STATUS 依 expires_at 本地判定(§3.7.6)。
|
|
||||||
defp token_status(%{"expires_at" => nil}), do: "active"
|
|
||||||
|
|
||||||
defp token_status(%{"expires_at" => expires_at}) when is_binary(expires_at) do
|
|
||||||
case DateTime.from_iso8601(expires_at) do
|
|
||||||
{:ok, dt, _} ->
|
|
||||||
if DateTime.compare(dt, DateTime.utc_now()) == :gt, do: "active", else: "expired"
|
|
||||||
|
|
||||||
_ ->
|
|
||||||
"active"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp token_status(_), do: "active"
|
|
||||||
|
|
||||||
defp print_table(headers, rows) do
|
|
||||||
widths =
|
|
||||||
Enum.with_index(headers, fn _h, i ->
|
|
||||||
Enum.max([
|
|
||||||
String.length(Enum.at(headers, i))
|
|
||||||
| Enum.map(rows, &String.length(Enum.at(&1, i)))
|
|
||||||
])
|
|
||||||
end)
|
|
||||||
|
|
||||||
render_row = fn cells ->
|
|
||||||
cells
|
|
||||||
|> Enum.with_index()
|
|
||||||
|> Enum.map(fn {cell, i} -> String.pad_trailing(to_string(cell), Enum.at(widths, i)) end)
|
|
||||||
|> Enum.join(" ")
|
|
||||||
|> String.trim_trailing()
|
|
||||||
end
|
|
||||||
|
|
||||||
IO.puts(render_row.(headers))
|
|
||||||
|
|
||||||
case rows do
|
|
||||||
[] -> IO.puts("(無資料)")
|
|
||||||
_ -> Enum.each(rows, fn cells -> IO.puts(render_row.(cells)) end)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp truncate(text, max) do
|
|
||||||
if String.length(text) > max do
|
|
||||||
String.slice(text, 0, max - 1) <> "…"
|
|
||||||
else
|
|
||||||
text
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# recovery codes 只顯示一次(同 PAT 明文處理)。
|
|
||||||
defp print_recovery_codes([]), do: IO.puts("(伺服器未回傳 recovery codes)")
|
|
||||||
|
|
||||||
defp print_recovery_codes(codes) do
|
|
||||||
IO.puts("recovery codes(只顯示這一次,請立即保存;舊組全部失效):")
|
|
||||||
|
|
||||||
Enum.each(codes, fn code ->
|
|
||||||
IO.puts(" #{code}")
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
# QR 由 CLI 本地生成(eqrcode),不經伺服器(§3.7.7)。產生失敗不阻斷流程,
|
|
||||||
# 只印 URI 與 secret 供手動輸入。
|
|
||||||
defp print_qr(uri) do
|
|
||||||
qr = EQRCode.encode(uri)
|
|
||||||
m = qr.matrix
|
|
||||||
|
|
||||||
IO.puts("QR(掃碼加入驗證器):")
|
|
||||||
|
|
||||||
for i <- 0..(tuple_size(m) - 1) do
|
|
||||||
row =
|
|
||||||
for j <- 0..(tuple_size(m) - 1) do
|
|
||||||
if elem(elem(m, i), j) == 1, do: "██", else: " "
|
|
||||||
end
|
|
||||||
|
|
||||||
IO.puts(Enum.join(row))
|
|
||||||
end
|
|
||||||
rescue
|
|
||||||
_ -> IO.puts(:stderr, "(QR 產生失敗,請手動輸入上列 otpauth URI/secret)")
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 錯誤處理 --
|
|
||||||
|
|
||||||
defp fail_api(opts, ctx, error) do
|
|
||||||
{message, code} = format_api_error(ctx, error)
|
|
||||||
fail(opts, message, code)
|
|
||||||
end
|
|
||||||
|
|
||||||
# API 錯誤 → 依 §3.7 群組共通退出碼輸出,回傳退出碼。
|
|
||||||
defp format_api_error(_ctx, {:error, :unauthorized, desc}) do
|
|
||||||
{"token 無效或已過期(#{desc}),請重新 bear login", 3}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_api_error(_ctx, {:error, :forbidden, desc}) do
|
|
||||||
{"權限不足(HTTP 403:#{desc})", 8}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_api_error(_ctx, {:error, :not_found, _desc}) do
|
|
||||||
{"找不到目標(HTTP 404)", 1}
|
|
||||||
end
|
|
||||||
|
|
||||||
# 語意錯誤(same_email/email_taken/invalid_code/already_enabled 等)。
|
|
||||||
defp format_api_error(
|
|
||||||
_ctx,
|
|
||||||
{:error, :unprocessable_entity, %{"error" => error, "error_description" => desc}}
|
|
||||||
) do
|
|
||||||
{"#{error}:#{desc}", 1}
|
|
||||||
end
|
|
||||||
|
|
||||||
# 422 逐欄位驗證錯誤(changeset errors)。
|
|
||||||
defp format_api_error(_ctx, {:error, :unprocessable_entity, %{"errors" => errors}}) do
|
|
||||||
details =
|
|
||||||
errors
|
|
||||||
|> Enum.map(fn {field, messages} ->
|
|
||||||
"#{field}: #{Enum.join(List.wrap(messages), "、")}"
|
|
||||||
end)
|
|
||||||
|> Enum.join(";")
|
|
||||||
|
|
||||||
if details == "" do
|
|
||||||
{"驗證失敗(HTTP 422)", 1}
|
|
||||||
else
|
|
||||||
{"驗證失敗(HTTP 422):#{details}", 1}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_api_error(_ctx, {:error, :unprocessable_entity, _body}) do
|
|
||||||
{"驗證失敗(HTTP 422)", 1}
|
|
||||||
end
|
|
||||||
|
|
||||||
# 伺服器限流(email 驗證碼)→ 退出碼 1,提示稍後再試(§3.7.4)。
|
|
||||||
defp format_api_error(_ctx, {:error, :too_many_requests, _body}) do
|
|
||||||
{"請求過於頻繁(HTTP 429),請稍後再試", 1}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_api_error(_ctx, {:error, :server_error, status}) do
|
|
||||||
{"伺服器回應 #{status}", 6}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp format_api_error(ctx, {:error, :network, reason}) do
|
|
||||||
{"無法連線到 #{ctx.issuer}:#{reason}", 6}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp fail(opts, message, code) do
|
|
||||||
if opts[:json] do
|
|
||||||
IO.puts(Jason.encode!(%{ok: false, error: message, code: code}))
|
|
||||||
else
|
|
||||||
IO.puts(:stderr, "錯誤:#{message}")
|
|
||||||
end
|
|
||||||
|
|
||||||
code
|
|
||||||
end
|
|
||||||
|
|
||||||
defp require_id(nil, command), do: {:error, "#{command} 缺少 <id>", 2}
|
|
||||||
defp require_id("", command), do: {:error, "#{command} 缺少 <id>", 2}
|
|
||||||
defp require_id(_, _command), do: :ok
|
|
||||||
|
|
||||||
defp blank?(nil), do: true
|
|
||||||
defp blank?(""), do: true
|
|
||||||
defp blank?(_), do: false
|
|
||||||
end
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
defmodule BearCli.TTY do
|
|
||||||
@moduledoc """
|
|
||||||
stdin 是否為終端機(TTY)的偵測(issue #19;來源 bear #52 驗收建議 2)。
|
|
||||||
|
|
||||||
不再只依賴 `:io.rows/0`/`:io.columns/0`:兩者走 io 協定詢問 group
|
|
||||||
leader,escript(`erl -noshell` 的 `standard_io`)不支援行列查詢,
|
|
||||||
即使 fd 0 是真終端機也回 `{:error, :enotsup}`,互動環境會被誤判成
|
|
||||||
非 TTY(無法讀 stdin 密碼,只能靠測試注入介面繞過)。
|
|
||||||
|
|
||||||
本模組改為直接判定 fd 0 指向的裝置:
|
|
||||||
|
|
||||||
- Linux:readlink `/proc/self/fd/0`,指向 `/dev/pts/*`、`/dev/tty*`、
|
|
||||||
`/dev/console`、`/dev/ptmx` 視為 TTY;pipe/socket/一般檔案(含
|
|
||||||
`/dev/null`)視為非 TTY。
|
|
||||||
- 無 `/proc` 的平台(如 macOS、Windows):退回 `:io.rows/0`(僅在
|
|
||||||
終端機裝置成功)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
@tty_prefixes ["/dev/pts/", "/dev/tty", "/dev/console", "/dev/ptmx"]
|
|
||||||
|
|
||||||
@doc "stdin(fd 0)是否為終端機。"
|
|
||||||
@spec stdin_tty?() :: boolean()
|
|
||||||
def stdin_tty? do
|
|
||||||
case fd0_path() do
|
|
||||||
{:ok, path} -> tty_path?(path)
|
|
||||||
:error -> rows_tty?()
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
裝置路徑是否為終端機(公開供測試與診斷)。
|
|
||||||
|
|
||||||
iex> BearCli.TTY.tty_path?("/dev/pts/0")
|
|
||||||
true
|
|
||||||
iex> BearCli.TTY.tty_path?("pipe:[42]")
|
|
||||||
false
|
|
||||||
"""
|
|
||||||
@spec tty_path?(String.t()) :: boolean()
|
|
||||||
def tty_path?(path) when is_binary(path) do
|
|
||||||
String.starts_with?(path, @tty_prefixes)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
舊式偵測(`:io.rows/0`):終端機 io 裝置回 `{:ok, rows}`;escript 的
|
|
||||||
`standard_io` 一律回 `{:error, :enotsup}`。僅作為無 `/proc` 平台的退路。
|
|
||||||
"""
|
|
||||||
@spec rows_tty?() :: boolean()
|
|
||||||
def rows_tty? do
|
|
||||||
match?({:ok, _}, :io.rows())
|
|
||||||
end
|
|
||||||
|
|
||||||
# fd 0 實際指向的路徑(readlink /proc/self/fd/0);無 /proc 或讀取失敗 → :error
|
|
||||||
defp fd0_path do
|
|
||||||
case :file.read_link(~c"/proc/self/fd/0") do
|
|
||||||
{:ok, path} -> {:ok, to_string(path)}
|
|
||||||
{:error, _} -> :error
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,139 +0,0 @@
|
|||||||
defmodule BearCli.Vault.BIP39 do
|
|
||||||
@moduledoc """
|
|
||||||
BIP39 助記詞(12 字、128-bit 熵、英文詞表),與 Web Vault 的
|
|
||||||
assets/js/vault/bip39.js 完全一致:
|
|
||||||
|
|
||||||
- 產生:16 bytes 熵 → 熵+SHA-256 前 4 bit 校驗 → 12 × 11-bit 索引
|
|
||||||
- 種子:PBKDF2-HMAC-SHA512(password=正規化助記詞、salt=
|
|
||||||
`"mnemonic"`(Bear 不用 BIP39 passphrase)、2048 迭代、64 bytes)
|
|
||||||
- 救援金鑰:種子 hex 字串 → PBKDF2-SHA512(salt=帳號 email 小寫、
|
|
||||||
迭代數同主金鑰),與主金鑰同形
|
|
||||||
|
|
||||||
正規化:小寫、去首尾空白、內部連續空白收斂為單一空格。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import BearCli.Vault.BIP39.Wordlist, only: [words: 0, index: 1]
|
|
||||||
import Bitwise
|
|
||||||
|
|
||||||
@strength_bits 128
|
|
||||||
@word_count 12
|
|
||||||
@seed_iterations 2048
|
|
||||||
@seed_keylen 64
|
|
||||||
|
|
||||||
# -- 正規化 --
|
|
||||||
|
|
||||||
@doc "正規化助記詞(小寫、trim、內部空白收斂);回傳單字清單。"
|
|
||||||
def normalize(mnemonic) do
|
|
||||||
mnemonic
|
|
||||||
|> to_string()
|
|
||||||
|> String.downcase()
|
|
||||||
|> String.trim()
|
|
||||||
|> String.split(~r/\s+/, trim: true)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "正規化後以單一空格連接的助記詞字串。"
|
|
||||||
def normalize_joined(mnemonic) do
|
|
||||||
normalize(mnemonic) |> Enum.join(" ")
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 產生 --
|
|
||||||
|
|
||||||
@doc "以 CSPRNG 產生 12 字助記詞(128-bit 熵)。"
|
|
||||||
def generate do
|
|
||||||
mnemonic_from_entropy(:crypto.strong_rand_bytes(div(@strength_bits, 8)))
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "16 bytes 熵 → 12 字助記詞(熵+SHA-256 前 4 bit 校驗)。"
|
|
||||||
def mnemonic_from_entropy(entropy) when byte_size(entropy) == 16 do
|
|
||||||
checksum = :crypto.hash(:sha256, entropy)
|
|
||||||
|
|
||||||
bits =
|
|
||||||
(entropy <> checksum)
|
|
||||||
|> bytes_to_bits()
|
|
||||||
|> Enum.take(12 * 11)
|
|
||||||
|
|
||||||
bits
|
|
||||||
|> Enum.chunk_every(11)
|
|
||||||
|> Enum.map(fn eleven ->
|
|
||||||
Enum.reduce(eleven, 0, fn bit, acc -> acc * 2 + bit end)
|
|
||||||
|> then(&Enum.at(words(), &1))
|
|
||||||
end)
|
|
||||||
|> Enum.join(" ")
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 驗證 --
|
|
||||||
|
|
||||||
@doc "驗證助記詞:12 字、全部在詞表、校驗和正確。回 true/false。"
|
|
||||||
def valid?(mnemonic) do
|
|
||||||
list = normalize(mnemonic)
|
|
||||||
|
|
||||||
if length(list) != @word_count do
|
|
||||||
false
|
|
||||||
else
|
|
||||||
indices = Enum.map(list, &index/1)
|
|
||||||
|
|
||||||
if Enum.any?(indices, &is_nil/1) do
|
|
||||||
false
|
|
||||||
else
|
|
||||||
bits = Enum.flat_map(indices, &int_to_bits(&1, 11))
|
|
||||||
entropy_bits = Enum.take(bits, 128)
|
|
||||||
checksum_bits = Enum.drop(bits, 128)
|
|
||||||
|
|
||||||
entropy = bits_to_bytes(entropy_bits)
|
|
||||||
checksum = :crypto.hash(:sha256, entropy)
|
|
||||||
|
|
||||||
expected =
|
|
||||||
checksum
|
|
||||||
|> bytes_to_bits()
|
|
||||||
|> Enum.take(4)
|
|
||||||
|
|
||||||
checksum_bits == expected
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 種子與救援金鑰 --
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
BIP39 種子:PBKDF2-HMAC-SHA512(2048 迭代、64 bytes、salt=`"mnemonic"`)。
|
|
||||||
password=正規化助記詞(與 bip39.js `mnemonicToSeed` 相同)。
|
|
||||||
"""
|
|
||||||
def mnemonic_to_seed(mnemonic) do
|
|
||||||
:crypto.pbkdf2_hmac(
|
|
||||||
:sha512,
|
|
||||||
normalize_joined(mnemonic),
|
|
||||||
"mnemonic",
|
|
||||||
@seed_iterations,
|
|
||||||
@seed_keylen
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
救援金鑰:種子 hex 字串 → PBKDF2-SHA512(salt=帳號 email 小寫、迭代數
|
|
||||||
同主金鑰)。與 bip39.js `rescueKeyFromSeed` 相同構造。
|
|
||||||
"""
|
|
||||||
def rescue_key_from_seed(seed, email, iterations) do
|
|
||||||
seed_hex = Base.encode16(seed, case: :lower)
|
|
||||||
:crypto.pbkdf2_hmac(:sha512, seed_hex, String.downcase(email), iterations, 64)
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- Private --
|
|
||||||
|
|
||||||
defp bytes_to_bits(binary) do
|
|
||||||
for(<<byte <- binary>>, do: for(i <- 7..0//-1, do: Bitwise.bsr(byte, i) &&& 1))
|
|
||||||
|> List.flatten()
|
|
||||||
end
|
|
||||||
|
|
||||||
defp int_to_bits(value, n) do
|
|
||||||
for(i <- (n - 1)..0//-1, do: Bitwise.bsr(value, i) &&& 1)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp bits_to_bytes(bits) do
|
|
||||||
bits
|
|
||||||
|> Enum.chunk_every(8)
|
|
||||||
|> Enum.map(fn eight ->
|
|
||||||
Enum.reduce(eight, 0, fn bit, acc -> acc * 2 + bit end)
|
|
||||||
end)
|
|
||||||
|> :binary.list_to_bin()
|
|
||||||
end
|
|
||||||
end
|
|
||||||
File diff suppressed because one or more lines are too long
@@ -1,118 +0,0 @@
|
|||||||
defmodule BearCli.Vault.Crypto do
|
|
||||||
@moduledoc """
|
|
||||||
客戶端 vault 加密原語(issue #17,對應 bear 倉庫 Bear.Vault.Crypto 與
|
|
||||||
Web Vault 的 assets/js/vault/crypto.js)。
|
|
||||||
|
|
||||||
格式必須與 Web Vault **完全一致**(同一 vault 兩端互相可解):
|
|
||||||
|
|
||||||
- 加密字串 `"2.<iv_b64>.<ct_b64>.<mac_b64>"`(AES-256-CBC+HMAC-SHA-256、
|
|
||||||
PKCS#7、encrypt-then-MAC、先驗 MAC 再解密)
|
|
||||||
- K_user 為隨機 64 byte(前 32 enc_key/後 32 mac_key)
|
|
||||||
- 主金鑰:PBKDF2-SHA512(迭代數以 `GET /api/v1/vault/config` 公告為準,
|
|
||||||
不寫死),salt=帳號 email 小寫
|
|
||||||
- K_user 的包裝(wrap):加密 **K_user 的 base64**(隨機 bytes 非 UTF-8,
|
|
||||||
與 Web Vault `wrapUserKey` 相同構造)
|
|
||||||
- 助記詞救援:BIP39 種子 → hex 字串 → PBKDF2-SHA512(salt=email 小寫)
|
|
||||||
|
|
||||||
全部在客戶端完成,K_user 僅存記憶體(不落盤、不進 log/commit)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
@type_prefix "2"
|
|
||||||
@block_size 16
|
|
||||||
|
|
||||||
# -- 金鑰推導 --
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
以主密碼推導 64-byte 主金鑰(PBKDF2-SHA512;salt=帳號 email 小寫)。
|
|
||||||
`iterations` 以 `/api/v1/vault/config` 公告值為準,不寫死。
|
|
||||||
"""
|
|
||||||
def derive_master_key(password, email, iterations)
|
|
||||||
when is_binary(password) and is_binary(email) and is_integer(iterations) do
|
|
||||||
:crypto.pbkdf2_hmac(:sha512, password, String.downcase(email), iterations, 64)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc "產生隨機 64-byte 使用者金鑰(`<<enc_key::32, mac_key::32>>`)。"
|
|
||||||
def generate_user_key do
|
|
||||||
:crypto.strong_rand_bytes(64)
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 加密字串(type 2)--
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
以 64-byte `user_key` 加密明文,回傳加密字串 `"2.<iv>.<ct>.<mac>"`
|
|
||||||
(AES-256-CBC+PKCS#7;encrypt-then-MAC,HMAC-SHA-256 over `iv <> ct`)。
|
|
||||||
"""
|
|
||||||
def encrypt(plaintext, user_key)
|
|
||||||
when is_binary(plaintext) and byte_size(user_key) == 64 do
|
|
||||||
<<enc_key::binary-size(32), mac_key::binary-size(32)>> = user_key
|
|
||||||
iv = :crypto.strong_rand_bytes(@block_size)
|
|
||||||
|
|
||||||
ciphertext =
|
|
||||||
:crypto.crypto_one_time(:aes_256_cbc, enc_key, iv, pkcs7_pad(plaintext), true)
|
|
||||||
|
|
||||||
mac = :crypto.mac(:hmac, :sha256, mac_key, iv <> ciphertext)
|
|
||||||
|
|
||||||
[@type_prefix, Base.encode64(iv), Base.encode64(ciphertext), Base.encode64(mac)]
|
|
||||||
|> Enum.join(".")
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
先驗 MAC(encrypt-then-MAC)再解密加密字串。回 `{:ok, plaintext}` 或
|
|
||||||
`{:error, :invalid}`(失敗形態一致,不洩漏原因)。
|
|
||||||
"""
|
|
||||||
def decrypt(encrypted_string, user_key)
|
|
||||||
when is_binary(encrypted_string) and byte_size(user_key) == 64 do
|
|
||||||
<<enc_key::binary-size(32), mac_key::binary-size(32)>> = user_key
|
|
||||||
|
|
||||||
with [@type_prefix, iv_b64, ct_b64, mac_b64] <- String.split(encrypted_string, "."),
|
|
||||||
{:ok, iv} <- Base.decode64(iv_b64),
|
|
||||||
{:ok, ct} <- Base.decode64(ct_b64),
|
|
||||||
{:ok, mac} <- Base.decode64(mac_b64),
|
|
||||||
true <- byte_size(iv) == @block_size,
|
|
||||||
true <- mac == :crypto.mac(:hmac, :sha256, mac_key, iv <> ct),
|
|
||||||
plaintext <- :crypto.crypto_one_time(:aes_256_cbc, enc_key, iv, ct, false),
|
|
||||||
plaintext <- pkcs7_unpad(plaintext) do
|
|
||||||
{:ok, plaintext}
|
|
||||||
else
|
|
||||||
_ -> {:error, :invalid}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 包裝金鑰(wrap/unwrap;與 Web Vault wrapUserKey 相同構造)--
|
|
||||||
|
|
||||||
@doc "包裝 K_user:加密 K_user 的 base64 字串,回傳加密字串。"
|
|
||||||
def wrap_user_key(user_key, wrapping_key) do
|
|
||||||
encrypt(Base.encode64(user_key), wrapping_key)
|
|
||||||
end
|
|
||||||
|
|
||||||
@doc """
|
|
||||||
解開包裝的 K_user。回 `{:ok, 64-byte key}` 或 `{:error, :invalid}`。
|
|
||||||
"""
|
|
||||||
def unwrap_user_key(wrapped, wrapping_key) do
|
|
||||||
with {:ok, inner} <- decrypt(wrapped, wrapping_key),
|
|
||||||
{:ok, key} <- Base.decode64(inner),
|
|
||||||
true <- byte_size(key) == 64 do
|
|
||||||
{:ok, key}
|
|
||||||
else
|
|
||||||
_ -> {:error, :invalid}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- Private --
|
|
||||||
|
|
||||||
defp pkcs7_pad(data) do
|
|
||||||
pad_len = @block_size - rem(byte_size(data), @block_size)
|
|
||||||
data <> :binary.copy(<<pad_len>>, pad_len)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp pkcs7_unpad(data) do
|
|
||||||
pad_len = :binary.last(data)
|
|
||||||
|
|
||||||
if pad_len in 1..@block_size//1 and byte_size(data) >= pad_len and
|
|
||||||
binary_part(data, byte_size(data), -pad_len) == :binary.copy(<<pad_len>>, pad_len) do
|
|
||||||
binary_part(data, 0, byte_size(data) - pad_len)
|
|
||||||
else
|
|
||||||
:error
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -37,9 +37,7 @@ defmodule BearCli.MixProject do
|
|||||||
[
|
[
|
||||||
# HTTP 一律使用 Req(與 bear 主專案一致)。
|
# HTTP 一律使用 Req(與 bear 主專案一致)。
|
||||||
{:req, "~> 0.5"},
|
{:req, "~> 0.5"},
|
||||||
{:jason, "~> 1.2"},
|
{:jason, "~> 1.2"}
|
||||||
# MFA setup 的 otpauth URI 本地 ASCII QR(§3.7.7)。
|
|
||||||
{:eqrcode, "~> 0.2"}
|
|
||||||
]
|
]
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
%{
|
%{
|
||||||
"eqrcode": {:hex, :eqrcode, "0.2.1", "d12838813e8fc87b8940cc05f9baadb189031f6009facdc56ff074375ec73b6e", [:mix], [], "hexpm", "d5828a222b904c68360e7dc2a40c3ef33a1328b7c074583898040f389f928025"},
|
|
||||||
"finch": {:hex, :finch, "0.23.0", "e3f9287ac25a8832f848b144c2b57346aac65b205e2e0629a52adfe6507fd837", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "80e58d3f936f57e3fdf404f83a3642897ae6d9fb642934e46da4d8fe761b99d5"},
|
"finch": {:hex, :finch, "0.23.0", "e3f9287ac25a8832f848b144c2b57346aac65b205e2e0629a52adfe6507fd837", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "80e58d3f936f57e3fdf404f83a3642897ae6d9fb642934e46da4d8fe761b99d5"},
|
||||||
"hpax": {:hex, :hpax, "1.0.4", "777de5d433b0fbdc7c418159c8055910faa8047ffdb3d6b31098d2a46cd7685c", [:mix], [], "hexpm", "afc7cb142ebcc2d01ce7816190b98ce5dd49e799111b24249f3443d730f377ca"},
|
"hpax": {:hex, :hpax, "1.0.4", "777de5d433b0fbdc7c418159c8055910faa8047ffdb3d6b31098d2a46cd7685c", [:mix], [], "hexpm", "afc7cb142ebcc2d01ce7816190b98ce5dd49e799111b24249f3443d730f377ca"},
|
||||||
"jason": {:hex, :jason, "1.4.5", "2e3a008590b0b8d7388c20293e9dcc9cf3e5d642fd2a114e4cbbb52e595d940a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "b0c823996102bcd0239b3c2444eb00409b72f6a140c1950bc8b457d836b30684"},
|
"jason": {:hex, :jason, "1.4.5", "2e3a008590b0b8d7388c20293e9dcc9cf3e5d642fd2a114e4cbbb52e595d940a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "b0c823996102bcd0239b3c2444eb00409b72f6a140c1950bc8b457d836b30684"},
|
||||||
"mime": {:hex, :mime, "2.0.7", "b8d739037be7cd402aee1ba0306edfdef982687ee7e9859bee6198c1e7e2f128", [:mix], [], "hexpm", "6171188e399ee16023ffc5b76ce445eb6d9672e2e241d2df6050f3c771e80ccd"},
|
"mime": {:hex, :mime, "2.0.7", "b8d739037be7cd402aee1ba0306edfdef982687ee7e9859bee6198c1e7e2f128", [:mix], [], "hexpm", "6171188e399ee16023ffc5b76ce445eb6d9672e2e241d2df6050f3c771e80ccd"},
|
||||||
"mint": {:hex, :mint, "1.10.0", "85af3353bfc504f5bdfe494bd92b8490f87a306dc659ee1ad0af435107e898dc", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 0.1.1 or ~> 0.2.0 or ~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "8b16fb72aaa7531d206a1f05e4cc85509ba531ccec7a17a22736c9c95cbb24d1"},
|
"mint": {:hex, :mint, "1.9.3", "3337184d69179695c7a9f1714d92c11e629d36c8c037a21cf490131d3d150554", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 0.1.1 or ~> 0.2.0 or ~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "5f7c9342480c069dbbc4eeac3490303c9e01870ff01a7f1d29b6107054fc1e74"},
|
||||||
"nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"},
|
"nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"},
|
||||||
"nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"},
|
"nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"},
|
||||||
"req": {:hex, :req, "0.7.4", "23e9ffec17de032a46a4b15ed65c09793893bf4a7c680f4bbf6227fce6bdf74d", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "4b192d63253e8dcc6221ef992ea9ebef7d3555166e8423aa5b553e86bc3c69a2"},
|
"req": {:hex, :req, "0.7.4", "23e9ffec17de032a46a4b15ed65c09793893bf4a7c680f4bbf6227fce6bdf74d", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "4b192d63253e8dcc6221ef992ea9ebef7d3555166e8423aa5b553e86bc3c69a2"},
|
||||||
|
|||||||
@@ -1,526 +0,0 @@
|
|||||||
defmodule BearCli.AdminCommandsTest do
|
|
||||||
@moduledoc """
|
|
||||||
`bear jwks`/`bear accounts`/`bear audit-logs` 管理端指令群單元測試(issue #12):
|
|
||||||
注入 fake API,涵蓋解析、輸出、退出碼與 401/403/404/422 分流。
|
|
||||||
"""
|
|
||||||
use ExUnit.Case, async: false
|
|
||||||
|
|
||||||
alias BearCli.{Accounts, AuditLogs, CLI, Jwks}
|
|
||||||
|
|
||||||
# -- fake API --
|
|
||||||
|
|
||||||
defmodule FakeApi do
|
|
||||||
@jwks [
|
|
||||||
%{
|
|
||||||
"id" => "0192cccc-0000-7000-8000-000000000001",
|
|
||||||
"kid" => "sig-2026-01",
|
|
||||||
"kty" => "RSA",
|
|
||||||
"alg" => "RS256",
|
|
||||||
"use" => "sig",
|
|
||||||
"active" => true,
|
|
||||||
"created_at" => "2026-09-09T00:00:00Z"
|
|
||||||
},
|
|
||||||
%{
|
|
||||||
"id" => "0192cccc-0000-7000-8000-000000000002",
|
|
||||||
"kid" => "sig-2025-12",
|
|
||||||
"kty" => "EC",
|
|
||||||
"alg" => "ES256",
|
|
||||||
"use" => "sig",
|
|
||||||
"active" => false,
|
|
||||||
"created_at" => "2025-12-01T00:00:00Z"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
@accounts [
|
|
||||||
%{
|
|
||||||
"id" => "0192bbbb-0000-7000-8000-000000000001",
|
|
||||||
"email" => "admin@example.com",
|
|
||||||
"role" => "admin",
|
|
||||||
"totp_enabled" => true,
|
|
||||||
"created_at" => "2026-01-01T00:00:00Z",
|
|
||||||
"updated_at" => "2026-01-01T00:00:00Z"
|
|
||||||
},
|
|
||||||
%{
|
|
||||||
"id" => "0192bbbb-0000-7000-8000-000000000002",
|
|
||||||
"email" => "alice@example.com",
|
|
||||||
"role" => "user",
|
|
||||||
"totp_enabled" => false,
|
|
||||||
"created_at" => "2026-02-01T00:00:00Z",
|
|
||||||
"updated_at" => "2026-02-01T00:00:00Z"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
@audit_entries [
|
|
||||||
%{
|
|
||||||
"id" => "0192dddd-0000-7000-8000-000000000001",
|
|
||||||
"event" => "account_created_by_admin",
|
|
||||||
"category" => "account",
|
|
||||||
"account_id" => "0192bbbb-0000-7000-8000-000000000002",
|
|
||||||
"actor_id" => "0192bbbb-0000-7000-8000-000000000001",
|
|
||||||
"ip" => "127.0.0.1",
|
|
||||||
"metadata" => %{"via" => "api"},
|
|
||||||
"created_at" => "2026-09-09T01:00:00Z"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
@emails %{
|
|
||||||
"0192bbbb-0000-7000-8000-000000000001" => "admin@example.com",
|
|
||||||
"0192bbbb-0000-7000-8000-000000000002" => "alice@example.com"
|
|
||||||
}
|
|
||||||
|
|
||||||
def jwks_list(_issuer, _token), do: ok_or_error(%{"data" => @jwks})
|
|
||||||
|
|
||||||
def jwks_create(_issuer, _token, attrs) do
|
|
||||||
key = %{
|
|
||||||
"id" => "0192cccc-0000-7000-8000-000000000003",
|
|
||||||
"kid" => attrs["kid"],
|
|
||||||
"kty" => "RSA",
|
|
||||||
"alg" => attrs["alg"],
|
|
||||||
"use" => "sig",
|
|
||||||
"active" => true,
|
|
||||||
"created_at" => "2026-09-09T02:00:00Z"
|
|
||||||
}
|
|
||||||
|
|
||||||
ok_or_error(%{"data" => key})
|
|
||||||
end
|
|
||||||
|
|
||||||
def jwks_get(_issuer, _token, id) do
|
|
||||||
case Enum.find(@jwks, &(&1["id"] == id)) do
|
|
||||||
nil -> {:error, :not_found, "not_found"}
|
|
||||||
key -> ok_or_error(%{"data" => key})
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def jwks_toggle(_issuer, _token, id) do
|
|
||||||
case Enum.find(@jwks, &(&1["id"] == id)) do
|
|
||||||
nil ->
|
|
||||||
{:error, :not_found, "not_found"}
|
|
||||||
|
|
||||||
key ->
|
|
||||||
new_active = !key["active"]
|
|
||||||
ok_or_error(%{"data" => %{key | "active" => new_active}})
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def accounts_list(_issuer, _token, params) do
|
|
||||||
page = params[:page] || 1
|
|
||||||
per_page = params[:per_page] || 20
|
|
||||||
|
|
||||||
ok_or_error(%{
|
|
||||||
"data" => Enum.slice(@accounts, (page - 1) * per_page, per_page),
|
|
||||||
"page" => page,
|
|
||||||
"per_page" => per_page,
|
|
||||||
"total" => length(@accounts)
|
|
||||||
})
|
|
||||||
end
|
|
||||||
|
|
||||||
def accounts_create(_issuer, _token, attrs) do
|
|
||||||
account = %{
|
|
||||||
"id" => "0192bbbb-0000-7000-8000-000000000003",
|
|
||||||
"email" => attrs["email"],
|
|
||||||
"role" => attrs["role"] || "user",
|
|
||||||
"totp_enabled" => false,
|
|
||||||
"created_at" => "2026-09-09T00:00:00Z",
|
|
||||||
"updated_at" => "2026-09-09T00:00:00Z"
|
|
||||||
}
|
|
||||||
|
|
||||||
ok_or_error(%{"data" => account})
|
|
||||||
end
|
|
||||||
|
|
||||||
def accounts_get(_issuer, _token, id) do
|
|
||||||
case Enum.find(@accounts, &(&1["id"] == id)) do
|
|
||||||
nil -> {:error, :not_found, "not_found"}
|
|
||||||
account -> ok_or_error(%{"data" => account})
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def accounts_update_role(_issuer, _token, id, attrs) do
|
|
||||||
case Enum.find(@accounts, &(&1["id"] == id)) do
|
|
||||||
nil ->
|
|
||||||
{:error, :not_found, "not_found"}
|
|
||||||
|
|
||||||
account ->
|
|
||||||
ok_or_error(%{"data" => %{account | "role" => attrs["role"]}})
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def accounts_set_password(_issuer, _token, id, _attrs) do
|
|
||||||
case Enum.find(@accounts, &(&1["id"] == id)) do
|
|
||||||
nil -> {:error, :not_found, "not_found"}
|
|
||||||
_account -> ok_or_error(%{})
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def accounts_delete(_issuer, _token, id) do
|
|
||||||
case Enum.find(@accounts, &(&1["id"] == id)) do
|
|
||||||
nil -> {:error, :not_found, "not_found"}
|
|
||||||
_account -> ok_or_error(%{})
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def audit_logs_list(_issuer, _token, params) do
|
|
||||||
category = params[:category]
|
|
||||||
|
|
||||||
entries =
|
|
||||||
if category,
|
|
||||||
do: Enum.filter(@audit_entries, &(&1["category"] == category)),
|
|
||||||
else: @audit_entries
|
|
||||||
|
|
||||||
ok_or_error(%{
|
|
||||||
"data" => entries,
|
|
||||||
"page" => params[:page] || 1,
|
|
||||||
"per_page" => params[:per_page] || 50,
|
|
||||||
"total" => length(entries),
|
|
||||||
"total_pages" => 1,
|
|
||||||
"emails" => @emails
|
|
||||||
})
|
|
||||||
end
|
|
||||||
|
|
||||||
defp ok_or_error(body) do
|
|
||||||
if error = Process.get(:fake_api_error) do
|
|
||||||
error
|
|
||||||
else
|
|
||||||
{:ok, body}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 測試輔助 --
|
|
||||||
|
|
||||||
setup do
|
|
||||||
old_token = System.get_env("BEAR_TOKEN")
|
|
||||||
old_creds = System.get_env("BEAR_CREDENTIALS")
|
|
||||||
|
|
||||||
on_exit(fn ->
|
|
||||||
restore(old_token, "BEAR_TOKEN")
|
|
||||||
restore(old_creds, "BEAR_CREDENTIALS")
|
|
||||||
end)
|
|
||||||
|
|
||||||
System.put_env("BEAR_TOKEN", "admin-pat")
|
|
||||||
System.put_env("BEAR_CREDENTIALS", "/nonexistent/credentials.json")
|
|
||||||
:ok
|
|
||||||
end
|
|
||||||
|
|
||||||
defp run_out(argv) do
|
|
||||||
ExUnit.CaptureIO.with_io(fn ->
|
|
||||||
CLI.dispatch(CLI.parse(argv), admin_apis())
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp run_err(argv) do
|
|
||||||
ExUnit.CaptureIO.with_io(:stderr, "", fn ->
|
|
||||||
CLI.dispatch(CLI.parse(argv), admin_apis())
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp admin_apis do
|
|
||||||
[jwks_api: FakeApi, accounts_api: FakeApi, audit_logs_api: FakeApi]
|
|
||||||
end
|
|
||||||
|
|
||||||
defp with_api_error(error) do
|
|
||||||
Process.put(:fake_api_error, error)
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- jwks --
|
|
||||||
|
|
||||||
test "jwks list renders table" do
|
|
||||||
{code, out} = run_out(["jwks", "list"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "KID"
|
|
||||||
assert out =~ "sig-2026-01"
|
|
||||||
assert out =~ "sig-2025-12"
|
|
||||||
assert out =~ "active"
|
|
||||||
assert out =~ "inactive"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "jwks list --json outputs spec shape" do
|
|
||||||
{code, out} = run_out(["jwks", "list", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["ok"] == true
|
|
||||||
assert Enum.any?(decoded["jwks"], &(&1["kid"] == "sig-2026-01"))
|
|
||||||
# key_data 永不出現
|
|
||||||
refute out =~ "key_data"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "jwks show resolves kid and prints public metadata" do
|
|
||||||
{code, out} = run_out(["jwks", "show", "sig-2026-01"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "kid"
|
|
||||||
assert out =~ "sig-2026-01"
|
|
||||||
assert out =~ "RS256"
|
|
||||||
refute out =~ "key_data"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "jwks show unknown kid exits 1" do
|
|
||||||
{code, err} = run_err(["jwks", "show", "no-such-key"])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "找不到"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "jwks create sends kid/alg and prints summary" do
|
|
||||||
{code, out} = run_out(["jwks", "create", "--kid", "sig-2026-09", "--alg", "ES256"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "JWK 已建立:sig-2026-09"
|
|
||||||
assert out =~ "ES256"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "jwks create without --kid exits 2" do
|
|
||||||
{code, err} = run_err(["jwks", "create"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "--kid"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "jwks create invalid alg exits 2" do
|
|
||||||
{code, err} = run_err(["jwks", "create", "--kid", "k", "--alg", "HS256"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "--alg"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "jwks toggle prints transition" do
|
|
||||||
{code, out} = run_out(["jwks", "toggle", "sig-2026-01"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "sig-2026-01:active → inactive"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "jwks toggle --json returns new state" do
|
|
||||||
{code, out} = run_out(["jwks", "toggle", "sig-2026-01", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["ok"] == true
|
|
||||||
assert decoded["jwk"]["kid"] == "sig-2026-01"
|
|
||||||
assert decoded["jwk"]["active"] == false
|
|
||||||
end
|
|
||||||
|
|
||||||
test "jwks list 403 exits 8 with admin hint" do
|
|
||||||
with_api_error({:error, :forbidden, "Admin role required."})
|
|
||||||
{code, err} = run_err(["jwks", "list"])
|
|
||||||
assert code == 8
|
|
||||||
assert err =~ "admin"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "jwks list 401 exits 3" do
|
|
||||||
with_api_error({:error, :unauthorized, "invalid_token"})
|
|
||||||
{code, err} = run_err(["jwks", "list"])
|
|
||||||
assert code == 3
|
|
||||||
assert err =~ "bear login"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "jwks unknown verb exits 2" do
|
|
||||||
{code, err} = run_err(["jwks", "rotate"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "未知的 jwks 子指令"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- accounts --
|
|
||||||
|
|
||||||
test "accounts list renders table" do
|
|
||||||
{code, out} = run_out(["accounts", "list"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "EMAIL"
|
|
||||||
assert out =~ "admin@example.com"
|
|
||||||
assert out =~ "alice@example.com"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts list --json outputs spec shape" do
|
|
||||||
{code, out} = run_out(["accounts", "list", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["ok"] == true
|
|
||||||
assert decoded["page"] == 1
|
|
||||||
assert decoded["total"] == 2
|
|
||||||
assert Enum.any?(decoded["accounts"], &(&1["email"] == "alice@example.com"))
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts list pagination params pass through" do
|
|
||||||
{code, out} = run_out(["accounts", "list", "--per-page", "1", "--page", "2"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "alice@example.com"
|
|
||||||
refute out =~ "admin@example.com"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts show resolves email and prints fields" do
|
|
||||||
{code, out} = run_out(["accounts", "show", "alice@example.com"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "email"
|
|
||||||
assert out =~ "alice@example.com"
|
|
||||||
refute out =~ "hash_password"
|
|
||||||
refute out =~ "totp_secret"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts show unknown email exits 1" do
|
|
||||||
{code, err} = run_err(["accounts", "show", "nobody@example.com"])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "找不到"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts create --generate-password sends plaintext once" do
|
|
||||||
{code, out} =
|
|
||||||
run_out([
|
|
||||||
"accounts",
|
|
||||||
"create",
|
|
||||||
"--email",
|
|
||||||
"new@example.com",
|
|
||||||
"--generate-password",
|
|
||||||
"--role",
|
|
||||||
"admin"
|
|
||||||
])
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "帳號已建立:new@example.com"
|
|
||||||
assert out =~ "初始密碼(只顯示這一次"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts create without email exits 2" do
|
|
||||||
{code, err} = run_err(["accounts", "create", "--generate-password"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "--email"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts create invalid role exits 2" do
|
|
||||||
{code, err} =
|
|
||||||
run_err([
|
|
||||||
"accounts",
|
|
||||||
"create",
|
|
||||||
"--email",
|
|
||||||
"x@example.com",
|
|
||||||
"--role",
|
|
||||||
"root",
|
|
||||||
"--generate-password"
|
|
||||||
])
|
|
||||||
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "--role"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts update requires --role" do
|
|
||||||
{code, err} = run_err(["accounts", "update", "alice@example.com"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "--role"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts update sends role and prints transition" do
|
|
||||||
{code, out} = run_out(["accounts", "update", "alice@example.com", "--role", "admin"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "alice@example.com:角色 → admin"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts set-password non-tty without generate exits 2" do
|
|
||||||
{code, err} = run_err(["accounts", "set-password", "alice@example.com"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "--generate-password"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts set-password --generate-password prints one-time password" do
|
|
||||||
{code, out} =
|
|
||||||
run_out(["accounts", "set-password", "alice@example.com", "--generate-password"])
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "只顯示這一次"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts delete prints confirmation" do
|
|
||||||
{code, out} = run_out(["accounts", "delete", "alice@example.com"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "已刪除帳號:alice@example.com"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts delete 403 self-delete exits 8" do
|
|
||||||
with_api_error({:error, :forbidden, "cannot delete yourself"})
|
|
||||||
{code, err} = run_err(["accounts", "delete", "admin@example.com"])
|
|
||||||
assert code == 8
|
|
||||||
assert err =~ "admin"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts list 403 exits 8" do
|
|
||||||
with_api_error({:error, :forbidden, "Admin role required."})
|
|
||||||
{code, _err} = run_err(["accounts", "list"])
|
|
||||||
assert code == 8
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- audit-logs --
|
|
||||||
|
|
||||||
test "audit-logs list renders table with emails" do
|
|
||||||
{code, out} = run_out(["audit-logs", "list"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "EVENT"
|
|
||||||
assert out =~ "account_created_by_admin"
|
|
||||||
assert out =~ "admin@example.com"
|
|
||||||
assert out =~ "alice@example.com"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "audit-logs list --json outputs spec shape" do
|
|
||||||
{code, out} = run_out(["audit-logs", "list", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["ok"] == true
|
|
||||||
assert decoded["total"] == 1
|
|
||||||
assert decoded["total_pages"] == 1
|
|
||||||
assert decoded["emails"]["0192bbbb-0000-7000-8000-000000000002"] == "alice@example.com"
|
|
||||||
assert Enum.any?(decoded["entries"], &(&1["event"] == "account_created_by_admin"))
|
|
||||||
end
|
|
||||||
|
|
||||||
test "audit-logs list --category filters server-side" do
|
|
||||||
{code, out} = run_out(["audit-logs", "list", "--category", "account"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "account_created_by_admin"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "audit-logs list --category jwk filters to empty" do
|
|
||||||
{code, out} = run_out(["audit-logs", "list", "--category", "jwk"])
|
|
||||||
assert code == 0
|
|
||||||
refute out =~ "account_created_by_admin"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "audit-logs list 403 exits 8" do
|
|
||||||
with_api_error({:error, :forbidden, "Admin role required."})
|
|
||||||
{code, err} = run_err(["audit-logs", "list"])
|
|
||||||
assert code == 8
|
|
||||||
assert err =~ "admin"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "audit-logs list network error exits 6" do
|
|
||||||
with_api_error({:error, :network, "econnrefused"})
|
|
||||||
{code, err} = run_err(["audit-logs", "list"])
|
|
||||||
assert code == 6
|
|
||||||
assert err =~ "econnrefused"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 解析 --
|
|
||||||
|
|
||||||
test "parse returns group module and verb" do
|
|
||||||
assert {:ok, {Jwks, :list}, opts} = CLI.parse(["jwks", "list", "--json"])
|
|
||||||
assert opts[:json] == true
|
|
||||||
|
|
||||||
assert {:ok, {Accounts, :create}, opts2} =
|
|
||||||
CLI.parse(["accounts", "create", "--email", "x@example.com", "--generate-password"])
|
|
||||||
|
|
||||||
assert opts2[:email] == "x@example.com"
|
|
||||||
assert opts2[:generate_password] == true
|
|
||||||
|
|
||||||
assert {:ok, {AuditLogs, :list}, opts3} = CLI.parse(["audit-logs", "list", "--page", "2"])
|
|
||||||
assert opts3[:page] == 2
|
|
||||||
end
|
|
||||||
|
|
||||||
test "unknown group verb reports in group error" do
|
|
||||||
assert {:error, msg, 2} = CLI.parse(["accounts", "purge"])
|
|
||||||
assert msg =~ "未知的 accounts 子指令"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "accounts update keeps positional email" do
|
|
||||||
assert {:ok, {Accounts, :update}, opts} =
|
|
||||||
CLI.parse(["accounts", "update", "a@example.com", "--role", "admin"])
|
|
||||||
|
|
||||||
assert opts[:email_arg] == "a@example.com"
|
|
||||||
assert opts[:role] == "admin"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 輔助 --
|
|
||||||
|
|
||||||
defp restore(nil, key), do: System.delete_env(key)
|
|
||||||
defp restore(value, key), do: System.put_env(key, value)
|
|
||||||
end
|
|
||||||
@@ -1,517 +0,0 @@
|
|||||||
defmodule BearCli.AppsTest do
|
|
||||||
@moduledoc """
|
|
||||||
`bear apps` 指令群單元測試(issue #10):注入 fake API,涵蓋解析、
|
|
||||||
輸出、退出碼、client_id → UUID 解析與 401/403/404/422 分流。
|
|
||||||
"""
|
|
||||||
use ExUnit.Case, async: false
|
|
||||||
|
|
||||||
alias BearCli.{Apps, CLI}
|
|
||||||
|
|
||||||
# -- fake API --
|
|
||||||
|
|
||||||
defmodule FakeApi do
|
|
||||||
@apps [
|
|
||||||
%{
|
|
||||||
"id" => "0192aaaa-0000-7000-8000-000000000001",
|
|
||||||
"client_id" => "my-app",
|
|
||||||
"title" => "My App",
|
|
||||||
"url" => "https://example.com",
|
|
||||||
"method" => "client_secret",
|
|
||||||
"status" => "active",
|
|
||||||
"visibility" => "public",
|
|
||||||
"scopes" => ["openid", "profile"],
|
|
||||||
"redirect_urls" => ["https://example.com/callback"],
|
|
||||||
"post_logout_redirect_uris" => [],
|
|
||||||
"sub" => "id",
|
|
||||||
"jwk_id" => nil,
|
|
||||||
"created_at" => "2026-09-07T00:00:00Z",
|
|
||||||
"updated_at" => "2026-09-07T00:00:00Z"
|
|
||||||
},
|
|
||||||
%{
|
|
||||||
"id" => "0192aaaa-0000-7000-8000-000000000002",
|
|
||||||
"client_id" => "internal-tool",
|
|
||||||
"title" => "Internal Tool",
|
|
||||||
"url" => "https://internal.example.com",
|
|
||||||
"method" => "PKCE",
|
|
||||||
"status" => "inactive",
|
|
||||||
"visibility" => "internal",
|
|
||||||
"scopes" => ["openid"],
|
|
||||||
"redirect_urls" => [],
|
|
||||||
"post_logout_redirect_uris" => [],
|
|
||||||
"sub" => "id",
|
|
||||||
"jwk_id" => "jwk-1",
|
|
||||||
"created_at" => "2026-09-06T00:00:00Z",
|
|
||||||
"updated_at" => "2026-09-06T00:00:00Z"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
def apps, do: @apps
|
|
||||||
|
|
||||||
def apps_list(_issuer, _token, params) do
|
|
||||||
if error = Process.get(:fake_api_error) do
|
|
||||||
error
|
|
||||||
else
|
|
||||||
page = params[:page] || 1
|
|
||||||
per_page = params[:per_page] || 20
|
|
||||||
|
|
||||||
{:ok,
|
|
||||||
%{
|
|
||||||
"data" => Enum.slice(@apps, (page - 1) * per_page, per_page),
|
|
||||||
"page" => page,
|
|
||||||
"per_page" => per_page,
|
|
||||||
"total" => length(@apps)
|
|
||||||
}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def apps_get(_issuer, _token, id) do
|
|
||||||
if error = Process.get(:fake_api_error) do
|
|
||||||
error
|
|
||||||
else
|
|
||||||
case Enum.find(@apps, &(&1["id"] == id)) do
|
|
||||||
nil -> {:error, :not_found, "not_found"}
|
|
||||||
app -> {:ok, %{"data" => app}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def apps_create(_issuer, _token, attrs) do
|
|
||||||
if error = Process.get(:fake_api_error) do
|
|
||||||
error
|
|
||||||
else
|
|
||||||
app =
|
|
||||||
%{
|
|
||||||
"id" => "0192aaaa-0000-7000-8000-000000000003",
|
|
||||||
"client_id" => attrs["client_id"],
|
|
||||||
"title" => attrs["title"],
|
|
||||||
"url" => attrs["url"],
|
|
||||||
"method" => attrs["method"] || "client_secret",
|
|
||||||
"status" => "active",
|
|
||||||
"visibility" => attrs["visibility"] || "internal",
|
|
||||||
"scopes" => attrs["scopes"] || ["openid"],
|
|
||||||
"redirect_urls" => attrs["redirect_urls"] || [],
|
|
||||||
"post_logout_redirect_uris" => attrs["post_logout_redirect_uris"] || [],
|
|
||||||
"sub" => attrs["sub"] || "id",
|
|
||||||
"jwk_id" => attrs["jwk_id"],
|
|
||||||
"created_at" => "2026-09-08T00:00:00Z",
|
|
||||||
"updated_at" => "2026-09-08T00:00:00Z"
|
|
||||||
}
|
|
||||||
|
|
||||||
{:ok, %{"data" => app, "client_secret" => "4f9c1d2e-new-secret"}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def apps_update(_issuer, _token, id, _attrs) do
|
|
||||||
if error = Process.get(:fake_api_error) do
|
|
||||||
error
|
|
||||||
else
|
|
||||||
case Enum.find(@apps, &(&1["id"] == id)) do
|
|
||||||
nil -> {:error, :not_found, "not_found"}
|
|
||||||
app -> {:ok, %{"data" => app}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def apps_rotate_secret(_issuer, _token, id) do
|
|
||||||
if error = Process.get(:fake_api_error) do
|
|
||||||
error
|
|
||||||
else
|
|
||||||
case Enum.find(@apps, &(&1["id"] == id)) do
|
|
||||||
%{"method" => "PKCE"} -> {:error, :unprocessable_entity, %{"error" => "pkce_app"}}
|
|
||||||
%{} -> {:ok, %{"client_secret" => "9a7b3c-rotated"}}
|
|
||||||
nil -> {:error, :not_found, "not_found"}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def apps_toggle(_issuer, _token, id) do
|
|
||||||
if error = Process.get(:fake_api_error) do
|
|
||||||
error
|
|
||||||
else
|
|
||||||
case Enum.find(@apps, &(&1["id"] == id)) do
|
|
||||||
nil ->
|
|
||||||
{:error, :not_found, "not_found"}
|
|
||||||
|
|
||||||
app ->
|
|
||||||
new_status = if app["status"] == "active", do: "inactive", else: "active"
|
|
||||||
{:ok, %{"data" => %{app | "status" => new_status}}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 測試輔助 --
|
|
||||||
|
|
||||||
setup do
|
|
||||||
old_token = System.get_env("BEAR_TOKEN")
|
|
||||||
old_creds = System.get_env("BEAR_CREDENTIALS")
|
|
||||||
|
|
||||||
on_exit(fn ->
|
|
||||||
restore(old_token, "BEAR_TOKEN")
|
|
||||||
restore(old_creds, "BEAR_CREDENTIALS")
|
|
||||||
end)
|
|
||||||
|
|
||||||
System.put_env("BEAR_TOKEN", "admin-pat")
|
|
||||||
System.put_env("BEAR_CREDENTIALS", "/nonexistent/credentials.json")
|
|
||||||
:ok
|
|
||||||
end
|
|
||||||
|
|
||||||
# 成功路徑:捕獲 stdout,回傳 {退出碼, stdout}
|
|
||||||
defp run_out(argv) do
|
|
||||||
ExUnit.CaptureIO.with_io(fn ->
|
|
||||||
CLI.dispatch(CLI.parse(argv), apps_api: FakeApi)
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
# 錯誤路徑:捕獲 stderr,回傳 {退出碼, stderr}
|
|
||||||
defp run_err(argv) do
|
|
||||||
ExUnit.CaptureIO.with_io(:stderr, "", fn ->
|
|
||||||
CLI.dispatch(CLI.parse(argv), apps_api: FakeApi)
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp with_api_error(error) do
|
|
||||||
Process.put(:fake_api_error, error)
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- list --
|
|
||||||
|
|
||||||
test "apps list renders table sorted by client_id" do
|
|
||||||
{code, out} = run_out(["apps", "list"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "CLIENT ID"
|
|
||||||
assert out =~ "internal-tool"
|
|
||||||
assert out =~ "my-app"
|
|
||||||
# 依 client_id 排序:internal-tool 在 my-app 之前
|
|
||||||
assert String.contains?(out, "internal-tool")
|
|
||||||
assert :binary.match(out, "internal-tool") < :binary.match(out, "my-app")
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps list --json outputs spec shape" do
|
|
||||||
{code, out} = run_out(["apps", "list", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["ok"] == true
|
|
||||||
assert decoded["page"] == 1
|
|
||||||
assert decoded["per_page"] == 20
|
|
||||||
assert decoded["total"] == 2
|
|
||||||
assert Enum.any?(decoded["apps"], &(&1["client_id"] == "my-app"))
|
|
||||||
assert Enum.any?(decoded["apps"], &(&1["client_id"] == "internal-tool"))
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps list --visibility/--status filters locally" do
|
|
||||||
{code, out} = run_out(["apps", "list", "--visibility", "public", "--status", "active"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "my-app"
|
|
||||||
refute out =~ "internal-tool"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps list server-side pagination (per-page 1, page 2)" do
|
|
||||||
# 無過濾 → 直接交給 API 分頁;fake API 第 2 頁(per_page=1)回傳第二筆
|
|
||||||
{code, out} = run_out(["apps", "list", "--per-page", "1", "--page", "2"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "internal-tool"
|
|
||||||
refute out =~ "my-app"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps list 403 exits 8 with admin hint" do
|
|
||||||
with_api_error({:error, :forbidden, "Admin role required."})
|
|
||||||
{code, err} = run_err(["apps", "list"])
|
|
||||||
assert code == 8
|
|
||||||
assert err =~ "admin"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- show --
|
|
||||||
|
|
||||||
test "apps show <client-id> resolves UUID and prints fields" do
|
|
||||||
{code, out} = run_out(["apps", "show", "my-app"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "client_id"
|
|
||||||
assert out =~ "my-app"
|
|
||||||
assert out =~ "https://example.com"
|
|
||||||
# secret 值不會出現(method 欄位的 "client_secret" 是合法輸出)
|
|
||||||
refute out =~ "4f9c1d2e"
|
|
||||||
refute out =~ "9a7b3c"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps show --json" do
|
|
||||||
{code, out} = run_out(["apps", "show", "my-app", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["ok"] == true
|
|
||||||
assert decoded["app"]["client_id"] == "my-app"
|
|
||||||
assert decoded["app"]["id"] == "0192aaaa-0000-7000-8000-000000000001"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps show unknown client_id exits 1" do
|
|
||||||
{code, err} = run_err(["apps", "show", "no-such-app"])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "找不到"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps show without client-id exits 2" do
|
|
||||||
{code, err} = run_err(["apps", "show"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "缺少"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- create --
|
|
||||||
|
|
||||||
test "apps create sends required attrs and prints one-time secret" do
|
|
||||||
{code, out} =
|
|
||||||
run_out([
|
|
||||||
"apps",
|
|
||||||
"create",
|
|
||||||
"--client-id",
|
|
||||||
"new-app",
|
|
||||||
"--url",
|
|
||||||
"https://new.example.com",
|
|
||||||
"--title",
|
|
||||||
"New App",
|
|
||||||
"--visibility",
|
|
||||||
"public",
|
|
||||||
"--scope",
|
|
||||||
"openid",
|
|
||||||
"--scope",
|
|
||||||
"profile"
|
|
||||||
])
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "App 已建立:new-app"
|
|
||||||
assert out =~ "只顯示這一次"
|
|
||||||
assert out =~ "4f9c1d2e-new-secret"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps create --json includes client_secret once" do
|
|
||||||
{code, out} =
|
|
||||||
run_out([
|
|
||||||
"apps",
|
|
||||||
"create",
|
|
||||||
"--client-id",
|
|
||||||
"new-app",
|
|
||||||
"--url",
|
|
||||||
"https://new.example.com",
|
|
||||||
"--title",
|
|
||||||
"New App",
|
|
||||||
"--json"
|
|
||||||
])
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["ok"] == true
|
|
||||||
assert decoded["client_secret"] == "4f9c1d2e-new-secret"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps create missing required exits 2" do
|
|
||||||
{code, err} = run_err(["apps", "create", "--client-id", "x"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "缺少必選參數"
|
|
||||||
assert err =~ "url"
|
|
||||||
assert err =~ "title"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps create invalid visibility exits 2" do
|
|
||||||
{code, err} =
|
|
||||||
run_err([
|
|
||||||
"apps",
|
|
||||||
"create",
|
|
||||||
"--client-id",
|
|
||||||
"x",
|
|
||||||
"--url",
|
|
||||||
"https://x",
|
|
||||||
"--title",
|
|
||||||
"X",
|
|
||||||
"--visibility",
|
|
||||||
"bogus"
|
|
||||||
])
|
|
||||||
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "--visibility"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps create PKCE without jwk-id exits 2" do
|
|
||||||
{code, err} =
|
|
||||||
run_err([
|
|
||||||
"apps",
|
|
||||||
"create",
|
|
||||||
"--client-id",
|
|
||||||
"x",
|
|
||||||
"--url",
|
|
||||||
"https://x",
|
|
||||||
"--title",
|
|
||||||
"X",
|
|
||||||
"--method",
|
|
||||||
"PKCE"
|
|
||||||
])
|
|
||||||
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "--jwk-id"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps create 422 renders field errors and exits 1" do
|
|
||||||
with_api_error(
|
|
||||||
{:error, :unprocessable_entity, %{"errors" => %{"client_id" => ["has already been taken"]}}}
|
|
||||||
)
|
|
||||||
|
|
||||||
{code, err} =
|
|
||||||
run_err([
|
|
||||||
"apps",
|
|
||||||
"create",
|
|
||||||
"--client-id",
|
|
||||||
"my-app",
|
|
||||||
"--url",
|
|
||||||
"https://x",
|
|
||||||
"--title",
|
|
||||||
"X"
|
|
||||||
])
|
|
||||||
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "422"
|
|
||||||
assert err =~ "client_id"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- update --
|
|
||||||
|
|
||||||
test "apps update sends only given fields" do
|
|
||||||
{code, out} = run_out(["apps", "update", "my-app", "--title", "Renamed"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "client_id"
|
|
||||||
assert out =~ "my-app"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps update --json" do
|
|
||||||
{code, out} = run_out(["apps", "update", "my-app", "--title", "Renamed", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["ok"] == true
|
|
||||||
assert decoded["app"]["client_id"] == "my-app"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- rotate-secret --
|
|
||||||
|
|
||||||
test "apps rotate-secret prints one-time new secret" do
|
|
||||||
{code, out} = run_out(["apps", "rotate-secret", "my-app"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "已輪轉"
|
|
||||||
assert out =~ "9a7b3c-rotated"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps rotate-secret on PKCE app exits 1" do
|
|
||||||
{code, err} = run_err(["apps", "rotate-secret", "internal-tool"])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "PKCE"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- toggle --
|
|
||||||
|
|
||||||
test "apps toggle prints transition" do
|
|
||||||
{code, out} = run_out(["apps", "toggle", "my-app"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "my-app:active → inactive"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps toggle --json returns new status" do
|
|
||||||
{code, out} = run_out(["apps", "toggle", "my-app", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["ok"] == true
|
|
||||||
assert decoded["app"]["status"] == "inactive"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 認證分流 --
|
|
||||||
|
|
||||||
test "apps list 401 exits 3" do
|
|
||||||
with_api_error({:error, :unauthorized, "Invalid or expired token"})
|
|
||||||
{code, err} = run_err(["apps", "list"])
|
|
||||||
assert code == 3
|
|
||||||
assert err =~ "bear login"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps list network error exits 6" do
|
|
||||||
with_api_error({:error, :network, "connection refused"})
|
|
||||||
{code, err} = run_err(["apps", "list"])
|
|
||||||
assert code == 6
|
|
||||||
assert err =~ "無法連線"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "not logged in exits 3 without credentials" do
|
|
||||||
System.delete_env("BEAR_TOKEN")
|
|
||||||
{code, err} = run_err(["apps", "list"])
|
|
||||||
assert code == 3
|
|
||||||
assert err =~ "未登入"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 解析 --
|
|
||||||
|
|
||||||
test "apps without verb exits 2" do
|
|
||||||
assert {:error, msg, 2} = CLI.parse(["apps"])
|
|
||||||
assert msg =~ "子指令"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps unknown verb exits 2" do
|
|
||||||
assert {:error, msg, 2} = CLI.parse(["apps", "frobnicate"])
|
|
||||||
assert msg =~ "未知的 apps 子指令"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps list parses spec options" do
|
|
||||||
assert {:ok, {Apps, :list}, opts} =
|
|
||||||
CLI.parse([
|
|
||||||
"apps",
|
|
||||||
"list",
|
|
||||||
"--visibility",
|
|
||||||
"public",
|
|
||||||
"--page",
|
|
||||||
"2",
|
|
||||||
"--per-page",
|
|
||||||
"5"
|
|
||||||
])
|
|
||||||
|
|
||||||
assert opts[:visibility] == "public"
|
|
||||||
assert opts[:page] == 2
|
|
||||||
assert opts[:per_page] == 5
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps create parses repeatable list options" do
|
|
||||||
assert {:ok, {Apps, :create}, opts} =
|
|
||||||
CLI.parse([
|
|
||||||
"apps",
|
|
||||||
"create",
|
|
||||||
"--client-id",
|
|
||||||
"x",
|
|
||||||
"--url",
|
|
||||||
"https://x",
|
|
||||||
"--title",
|
|
||||||
"X",
|
|
||||||
"--redirect-url",
|
|
||||||
"https://a/cb",
|
|
||||||
"--redirect-url",
|
|
||||||
"https://b/cb",
|
|
||||||
"--scope",
|
|
||||||
"openid",
|
|
||||||
"--scope",
|
|
||||||
"email",
|
|
||||||
"--post-logout-redirect-uri",
|
|
||||||
"https://a/logout"
|
|
||||||
])
|
|
||||||
|
|
||||||
assert opts[:redirect_url] == ["https://a/cb", "https://b/cb"]
|
|
||||||
assert opts[:scope] == ["openid", "email"]
|
|
||||||
assert opts[:post_logout_redirect_uri] == ["https://a/logout"]
|
|
||||||
end
|
|
||||||
|
|
||||||
test "apps show keeps positional client-id" do
|
|
||||||
assert {:ok, {Apps, :show}, opts} = CLI.parse(["apps", "show", "my-app", "--json"])
|
|
||||||
assert opts[:client_id_arg] == "my-app"
|
|
||||||
assert opts[:json] == true
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 輔助 --
|
|
||||||
|
|
||||||
defp restore(nil, key), do: System.delete_env(key)
|
|
||||||
defp restore(value, key), do: System.put_env(key, value)
|
|
||||||
end
|
|
||||||
+3
-102
@@ -72,7 +72,7 @@ defmodule BearCli.CLITest do
|
|||||||
assert {:ok, %{"access_token" => "good"}} = BearCli.Credentials.load(path)
|
assert {:ok, %{"access_token" => "good"}} = BearCli.Credentials.load(path)
|
||||||
end
|
end
|
||||||
|
|
||||||
test "login with invalid token exits 3" do
|
test "login with invalid token exits 1" do
|
||||||
System.put_env("BEAR_CREDENTIALS", tmp_path())
|
System.put_env("BEAR_CREDENTIALS", tmp_path())
|
||||||
|
|
||||||
{code, err} =
|
{code, err} =
|
||||||
@@ -82,8 +82,8 @@ defmodule BearCli.CLITest do
|
|||||||
fn -> CLI.dispatch(CLI.parse(["login", "--token", "bad"]), api: fake_api()) end
|
fn -> CLI.dispatch(CLI.parse(["login", "--token", "bad"]), api: fake_api()) end
|
||||||
)
|
)
|
||||||
|
|
||||||
assert code == 3
|
assert code == 1
|
||||||
assert err =~ "PAT 無效"
|
assert err =~ "token 無效"
|
||||||
end
|
end
|
||||||
|
|
||||||
test "login without --token points to Device Flow being unavailable" do
|
test "login without --token points to Device Flow being unavailable" do
|
||||||
@@ -145,23 +145,6 @@ defmodule BearCli.CLITest do
|
|||||||
assert String.trim(out) == "good-token"
|
assert String.trim(out) == "good-token"
|
||||||
end
|
end
|
||||||
|
|
||||||
test "token --refresh is a usage error in PAT mode" do
|
|
||||||
path = tmp_path()
|
|
||||||
on_exit(fn -> File.rm(path) end)
|
|
||||||
System.put_env("BEAR_CREDENTIALS", path)
|
|
||||||
BearCli.Credentials.save(%{"issuer" => "https://x", "access_token" => "good-token"}, path)
|
|
||||||
|
|
||||||
{code, err} =
|
|
||||||
ExUnit.CaptureIO.with_io(
|
|
||||||
:stderr,
|
|
||||||
"",
|
|
||||||
fn -> CLI.dispatch(CLI.parse(["token", "--refresh"]), api: fake_api()) end
|
|
||||||
)
|
|
||||||
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "--refresh"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "status when logged in exits 0 and reports PAT mode" do
|
test "status when logged in exits 0 and reports PAT mode" do
|
||||||
path = tmp_path()
|
path = tmp_path()
|
||||||
on_exit(fn -> File.rm(path) end)
|
on_exit(fn -> File.rm(path) end)
|
||||||
@@ -198,88 +181,6 @@ defmodule BearCli.CLITest do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "BEAR_TOKEN environment variable" do
|
|
||||||
setup do
|
|
||||||
old_creds = System.get_env("BEAR_CREDENTIALS")
|
|
||||||
old_token = System.get_env("BEAR_TOKEN")
|
|
||||||
|
|
||||||
on_exit(fn ->
|
|
||||||
restore_env("BEAR_CREDENTIALS", old_creds)
|
|
||||||
restore_env("BEAR_TOKEN", old_token)
|
|
||||||
end)
|
|
||||||
|
|
||||||
:ok
|
|
||||||
end
|
|
||||||
|
|
||||||
test "whoami uses BEAR_TOKEN without credentials file" do
|
|
||||||
System.put_env("BEAR_CREDENTIALS", "/nonexistent/credentials.json")
|
|
||||||
System.put_env("BEAR_TOKEN", "good")
|
|
||||||
|
|
||||||
{code, out} =
|
|
||||||
ExUnit.CaptureIO.with_io(fn ->
|
|
||||||
CLI.dispatch(CLI.parse(["whoami"]), api: fake_api())
|
|
||||||
end)
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "alice@example.com"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "whoami with invalid BEAR_TOKEN exits 3" do
|
|
||||||
System.put_env("BEAR_CREDENTIALS", "/nonexistent/credentials.json")
|
|
||||||
System.put_env("BEAR_TOKEN", "bad")
|
|
||||||
|
|
||||||
{code, err} =
|
|
||||||
ExUnit.CaptureIO.with_io(
|
|
||||||
:stderr,
|
|
||||||
"",
|
|
||||||
fn -> CLI.dispatch(CLI.parse(["whoami"]), api: fake_api()) end
|
|
||||||
)
|
|
||||||
|
|
||||||
assert code == 3
|
|
||||||
assert err =~ "token 無效"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "token prints BEAR_TOKEN" do
|
|
||||||
System.put_env("BEAR_CREDENTIALS", "/nonexistent/credentials.json")
|
|
||||||
System.put_env("BEAR_TOKEN", "env-pat")
|
|
||||||
|
|
||||||
{code, out} =
|
|
||||||
ExUnit.CaptureIO.with_io(fn ->
|
|
||||||
CLI.dispatch(CLI.parse(["token"]), api: fake_api())
|
|
||||||
end)
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert String.trim(out) == "env-pat"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "status reports env token mode" do
|
|
||||||
System.put_env("BEAR_CREDENTIALS", "/nonexistent/credentials.json")
|
|
||||||
System.put_env("BEAR_TOKEN", "env-pat")
|
|
||||||
|
|
||||||
{code, out} =
|
|
||||||
ExUnit.CaptureIO.with_io(fn ->
|
|
||||||
CLI.dispatch(CLI.parse(["status"]), api: fake_api())
|
|
||||||
end)
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "BEAR_TOKEN"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "blank BEAR_TOKEN is ignored" do
|
|
||||||
System.put_env("BEAR_CREDENTIALS", "/nonexistent/credentials.json")
|
|
||||||
System.put_env("BEAR_TOKEN", " ")
|
|
||||||
|
|
||||||
{code, _err} =
|
|
||||||
ExUnit.CaptureIO.with_io(
|
|
||||||
:stderr,
|
|
||||||
"",
|
|
||||||
fn -> CLI.dispatch(CLI.parse(["whoami"]), api: fake_api()) end
|
|
||||||
)
|
|
||||||
|
|
||||||
assert code == 3
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp fake_api do
|
defp fake_api do
|
||||||
fn _issuer, token ->
|
fn _issuer, token ->
|
||||||
case token do
|
case token do
|
||||||
|
|||||||
@@ -1,662 +0,0 @@
|
|||||||
defmodule BearCli.SelfServiceTest do
|
|
||||||
@moduledoc """
|
|
||||||
`bear` 個人自助指令群單元測試(issue #11):注入 fake API,涵蓋
|
|
||||||
解析、輸出、退出碼、互動輸入注入與 401/403/404/422/429 分流。
|
|
||||||
"""
|
|
||||||
|
|
||||||
use ExUnit.Case, async: false
|
|
||||||
|
|
||||||
alias BearCli.{CLI, SelfService}
|
|
||||||
|
|
||||||
# -- fake API --
|
|
||||||
|
|
||||||
defmodule FakeApi do
|
|
||||||
@profile %{
|
|
||||||
"id" => "0190aaaa-0000-7000-8000-000000000001",
|
|
||||||
"email" => "alice@example.com",
|
|
||||||
"role" => "user",
|
|
||||||
"name" => "Alice Chen",
|
|
||||||
"given_name" => "Alice",
|
|
||||||
"family_name" => "Chen",
|
|
||||||
"nickname" => "ali",
|
|
||||||
"preferred_username" => "alice",
|
|
||||||
"locale" => "zh_TW",
|
|
||||||
"zoneinfo" => "Asia/Taipei",
|
|
||||||
"phone_number" => nil,
|
|
||||||
"phone_number_verified" => false,
|
|
||||||
"address" => nil,
|
|
||||||
"mfa_enabled" => false,
|
|
||||||
"created_at" => "2026-09-01T00:00:00Z",
|
|
||||||
"updated_at" => "2026-09-01T00:00:00Z"
|
|
||||||
}
|
|
||||||
|
|
||||||
@sessions [
|
|
||||||
%{
|
|
||||||
"id" => "0192a1b0-0000-7000-8000-0000000000aa",
|
|
||||||
"ip" => "203.0.113.10",
|
|
||||||
"user_agent" => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36",
|
|
||||||
"created_at" => "2026-09-07T10:00:00Z",
|
|
||||||
"last_seen_at" => "2026-09-08T09:00:00Z"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
@tokens [
|
|
||||||
%{
|
|
||||||
"id" => "0192a1c0-0000-7000-8000-0000000000bb",
|
|
||||||
"name" => "ci-token",
|
|
||||||
"scope" => "openid profile email",
|
|
||||||
"expires_at" => "2999-01-01T00:00:00Z",
|
|
||||||
"revoked_at" => nil,
|
|
||||||
"last_used_at" => "2026-09-08T08:00:00Z",
|
|
||||||
"created_at" => "2026-09-01T00:00:00Z"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
def error do
|
|
||||||
Process.get(:fake_ss_error)
|
|
||||||
end
|
|
||||||
|
|
||||||
def profile_get(_issuer, _token) do
|
|
||||||
error() || {:ok, %{"data" => profile()}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def profile do
|
|
||||||
Map.merge(@profile, Process.get(:fake_profile_overrides) || %{})
|
|
||||||
end
|
|
||||||
|
|
||||||
def profile_update(_issuer, _token, attrs) do
|
|
||||||
error() || {:ok, %{"data" => Map.merge(profile(), attrs)}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def profile_change_password(_issuer, _token, current, new) do
|
|
||||||
cond do
|
|
||||||
error() ->
|
|
||||||
error()
|
|
||||||
|
|
||||||
current == "wrong-pass" ->
|
|
||||||
{:error, :unprocessable_entity,
|
|
||||||
%{"errors" => %{"current_password" => ["is incorrect"]}}}
|
|
||||||
|
|
||||||
byte_size(new) < 8 ->
|
|
||||||
{:error, :unprocessable_entity,
|
|
||||||
%{"errors" => %{"new_password" => ["must be at least 8 characters"]}}}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, %{"data" => %{"updated" => true}}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def profile_email_request_codes(_issuer, _token, new_email) do
|
|
||||||
cond do
|
|
||||||
error() ->
|
|
||||||
error()
|
|
||||||
|
|
||||||
new_email == "alice@example.com" ->
|
|
||||||
{:error, :unprocessable_entity,
|
|
||||||
%{"error" => "same_email", "error_description" => "The new email must be different."}}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, %{"data" => %{"sent" => true}}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def profile_email_change(_issuer, _token, _new_email, current_code, _new_code) do
|
|
||||||
cond do
|
|
||||||
error() ->
|
|
||||||
error()
|
|
||||||
|
|
||||||
current_code == "000000" ->
|
|
||||||
{:error, :unprocessable_entity,
|
|
||||||
%{"error" => "invalid_current_code", "error_description" => "incorrect"}}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, %{"data" => %{"email" => "new@example.com"}}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def sessions_list(_issuer, _token) do
|
|
||||||
error() || {:ok, %{"data" => @sessions}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def sessions_revoke(_issuer, _token, id) do
|
|
||||||
cond do
|
|
||||||
error() ->
|
|
||||||
error()
|
|
||||||
|
|
||||||
id == "missing" ->
|
|
||||||
{:error, :not_found, "not_found"}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, %{"data" => %{"revoked" => id}}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def sessions_revoke_others(_issuer, _token) do
|
|
||||||
error() || {:ok, %{"data" => %{"revoked_count" => 3}}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def tokens_list(_issuer, _token) do
|
|
||||||
error() || {:ok, %{"data" => @tokens}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def tokens_create(_issuer, _token, name, expires_in) do
|
|
||||||
cond do
|
|
||||||
error() ->
|
|
||||||
error()
|
|
||||||
|
|
||||||
name == " " ->
|
|
||||||
{:error, :unprocessable_entity, %{"errors" => %{"name" => ["can't be blank"]}}}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
expires_at = if expires_in == "never", do: nil, else: "2999-01-01T00:00:00Z"
|
|
||||||
|
|
||||||
{:ok,
|
|
||||||
%{
|
|
||||||
"data" => %{
|
|
||||||
"id" => "0192a1c0-0000-7000-8000-0000000000cc",
|
|
||||||
"name" => name,
|
|
||||||
"scope" => "openid profile email",
|
|
||||||
"expires_at" => expires_at,
|
|
||||||
"revoked_at" => nil,
|
|
||||||
"last_used_at" => nil,
|
|
||||||
"created_at" => "2026-09-09T00:00:00Z"
|
|
||||||
},
|
|
||||||
"token" => "9f3a-raw-token-once"
|
|
||||||
}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def tokens_revoke(_issuer, _token, id) do
|
|
||||||
cond do
|
|
||||||
error() ->
|
|
||||||
error()
|
|
||||||
|
|
||||||
id == "missing" ->
|
|
||||||
{:error, :not_found, "not_found"}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, %{"data" => %{"revoked" => id}}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def mfa_setup(_issuer, _token) do
|
|
||||||
error() ||
|
|
||||||
{:ok,
|
|
||||||
%{"data" => %{"secret" => "JBSWY3DPEHPK3PXP", "otpauth_uri" => "otpauth://totp/Bear:x"}}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def mfa_setup_confirm(_issuer, _token, code) do
|
|
||||||
cond do
|
|
||||||
error() ->
|
|
||||||
error()
|
|
||||||
|
|
||||||
code == "000000" ->
|
|
||||||
{:error, :unprocessable_entity,
|
|
||||||
%{"error" => "invalid_code", "error_description" => "Invalid verification code."}}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, %{"data" => %{"enabled" => true, "recovery_codes" => ["rc-1", "rc-2"]}}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def mfa_disable(_issuer, _token, code) do
|
|
||||||
cond do
|
|
||||||
error() ->
|
|
||||||
error()
|
|
||||||
|
|
||||||
code == "000000" ->
|
|
||||||
{:error, :unprocessable_entity,
|
|
||||||
%{
|
|
||||||
"error" => "invalid_code",
|
|
||||||
"error_description" => "Invalid code. MFA was not disabled."
|
|
||||||
}}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, %{"data" => %{"enabled" => false}}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def mfa_recovery_codes(_issuer, _token, code) do
|
|
||||||
cond do
|
|
||||||
error() ->
|
|
||||||
error()
|
|
||||||
|
|
||||||
code == "000000" ->
|
|
||||||
{:error, :unprocessable_entity,
|
|
||||||
%{"error" => "invalid_code", "error_description" => "Invalid code."}}
|
|
||||||
|
|
||||||
true ->
|
|
||||||
{:ok, %{"data" => %{"recovery_codes" => ["new-rc-1", "new-rc-2"]}}}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# 互動輸入注入:依序回應佇列中的值;prompt 前綴不影響。
|
|
||||||
defmodule FakeIO do
|
|
||||||
def prompt_secret(_label) do
|
|
||||||
case Process.get(:fake_io_inputs) do
|
|
||||||
[] ->
|
|
||||||
:eof
|
|
||||||
|
|
||||||
[next | rest] ->
|
|
||||||
Process.put(:fake_io_inputs, rest)
|
|
||||||
{:ok, next}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 測試輔助 --
|
|
||||||
|
|
||||||
setup do
|
|
||||||
old_token = System.get_env("BEAR_TOKEN")
|
|
||||||
old_creds = System.get_env("BEAR_CREDENTIALS")
|
|
||||||
|
|
||||||
on_exit(fn ->
|
|
||||||
restore(old_token, "BEAR_TOKEN")
|
|
||||||
restore(old_creds, "BEAR_CREDENTIALS")
|
|
||||||
end)
|
|
||||||
|
|
||||||
System.put_env("BEAR_TOKEN", "user-pat")
|
|
||||||
System.put_env("BEAR_CREDENTIALS", "/nonexistent/credentials.json")
|
|
||||||
:ok
|
|
||||||
end
|
|
||||||
|
|
||||||
defp run_out(argv, io_inputs \\ nil) do
|
|
||||||
if io_inputs, do: Process.put(:fake_io_inputs, io_inputs)
|
|
||||||
|
|
||||||
opts = [ss_api: FakeApi, io: FakeIO, tty?: true]
|
|
||||||
|
|
||||||
ExUnit.CaptureIO.with_io(fn ->
|
|
||||||
CLI.dispatch(CLI.parse(argv), opts)
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp run_err(argv, io_inputs \\ nil) do
|
|
||||||
if io_inputs, do: Process.put(:fake_io_inputs, io_inputs)
|
|
||||||
|
|
||||||
opts = [ss_api: FakeApi, io: FakeIO, tty?: true]
|
|
||||||
|
|
||||||
ExUnit.CaptureIO.with_io(:stderr, "", fn ->
|
|
||||||
CLI.dispatch(CLI.parse(argv), opts)
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp with_api_error(error) do
|
|
||||||
Process.put(:fake_ss_error, error)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp restore(nil, key), do: System.delete_env(key)
|
|
||||||
defp restore(value, key), do: System.put_env(key, value)
|
|
||||||
|
|
||||||
# -- 解析:用法錯誤(退出碼 2)--
|
|
||||||
|
|
||||||
test "unknown self-service command exits 2" do
|
|
||||||
assert {:error, _msg, 2} = CLI.parse(["frobnicate"])
|
|
||||||
end
|
|
||||||
|
|
||||||
test "profile without verb exits 2" do
|
|
||||||
assert {:error, msg, 2} = CLI.parse(["profile"])
|
|
||||||
assert msg =~ "profile 缺少子指令"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "profile unknown verb exits 2" do
|
|
||||||
assert {:error, msg, 2} = CLI.parse(["profile", "delete"])
|
|
||||||
assert msg =~ "未知的 profile 子指令"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "profile show with positional exits 2" do
|
|
||||||
assert {:error, msg, 2} = CLI.parse(["profile", "show", "extra"])
|
|
||||||
assert msg =~ "不接受位置參數"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "password unknown verb exits 2" do
|
|
||||||
assert {:error, msg, 2} = CLI.parse(["password", "reset"])
|
|
||||||
assert msg =~ "未知的 password 子指令"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "password change rejects positional args" do
|
|
||||||
assert {:error, msg, 2} = CLI.parse(["password", "change", "secret"])
|
|
||||||
assert msg =~ "不接受參數"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "email change missing --new exits 2 at runtime" do
|
|
||||||
{code, err} = run_err(["email", "change"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "缺少 --new"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "sessions revoke missing id exits 2" do
|
|
||||||
assert {:error, msg, 2} = CLI.parse(["sessions", "revoke"])
|
|
||||||
assert msg =~ "缺少 <id>"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "tokens create missing --name exits 2" do
|
|
||||||
assert {:error, msg, 2} = CLI.parse(["tokens", "create"])
|
|
||||||
assert msg =~ "缺少 --name"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "tokens create invalid --expires-in exits 2" do
|
|
||||||
{code, err} = run_err(["tokens", "create", "--name", "x", "--expires-in", "-5"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "--expires-in"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "mfa unknown verb exits 2" do
|
|
||||||
assert {:error, msg, 2} = CLI.parse(["mfa", "enable"])
|
|
||||||
assert msg =~ "未知的 mfa 子指令"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- profile --
|
|
||||||
|
|
||||||
test "profile show prints fields" do
|
|
||||||
{code, out} = run_out(["profile", "show"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "email"
|
|
||||||
assert out =~ "alice@example.com"
|
|
||||||
assert out =~ "mfa_enabled"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "profile show --json outputs spec shape" do
|
|
||||||
{code, out} = run_out(["profile", "show", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["ok"] == true
|
|
||||||
assert decoded["profile"]["email"] == "alice@example.com"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "profile set sends only given fields" do
|
|
||||||
{code, out} = run_out(["profile", "set", "--name", "New Name", "--locale", "zh_TW"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "New Name"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "profile set without fields exits 2" do
|
|
||||||
{code, err} = run_err(["profile", "set"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "未給任何欄位"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "profile set invalid gender exits 2 without request" do
|
|
||||||
{code, err} = run_err(["profile", "set", "--gender", "robot"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "--gender"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "profile set invalid url exits 2" do
|
|
||||||
{code, err} = run_err(["profile", "set", "--picture", "ftp://x"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "http(s)://"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- password --
|
|
||||||
|
|
||||||
test "password change happy path" do
|
|
||||||
{code, out} = run_out(["password", "change"], ["old-pass", "new-pass-9", "new-pass-9"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "密碼已變更"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "password change mismatched confirmation exits 2 locally" do
|
|
||||||
{code, err} = run_err(["password", "change"], ["old", "new-pass-9", "different-9"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "不一致"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "password change wrong current password maps to 422 exit 1" do
|
|
||||||
{code, err} = run_err(["password", "change"], ["wrong-pass", "new-pass-9", "new-pass-9"])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "current_password"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "password change in non-TTY exits 2" do
|
|
||||||
{code, _out} =
|
|
||||||
ExUnit.CaptureIO.with_io(fn ->
|
|
||||||
CLI.dispatch(
|
|
||||||
CLI.parse(["password", "change"]),
|
|
||||||
ss_api: FakeApi,
|
|
||||||
tty?: false
|
|
||||||
)
|
|
||||||
end)
|
|
||||||
|
|
||||||
assert code == 2
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- email --
|
|
||||||
|
|
||||||
test "email change full flow" do
|
|
||||||
{code, out} =
|
|
||||||
run_out(["email", "change", "--new", "new@example.com"], ["111111", "222222"])
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "email 已更新:new@example.com"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "email change same email maps 422 error to exit 1" do
|
|
||||||
{code, err} =
|
|
||||||
run_err(["email", "change", "--new", "alice@example.com"], ["111111", "222222"])
|
|
||||||
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "same_email"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "email change invalid code maps to exit 1" do
|
|
||||||
{code, err} =
|
|
||||||
run_err(["email", "change", "--new", "new@example.com"], ["000000", "222222"])
|
|
||||||
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "invalid_current_code"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "email change rate limited maps 429 to exit 1" do
|
|
||||||
with_api_error({:error, :too_many_requests, %{"error" => "rate_limited"}})
|
|
||||||
|
|
||||||
{code, err} = run_err(["email", "change", "--new", "new@example.com"], [])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "429"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- sessions --
|
|
||||||
|
|
||||||
test "sessions list renders table" do
|
|
||||||
{code, out} = run_out(["sessions", "list"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "ID"
|
|
||||||
assert out =~ "203.0.113.10"
|
|
||||||
assert out =~ "Mozilla/5.0"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "sessions list --json outputs spec shape" do
|
|
||||||
{code, out} = run_out(["sessions", "list", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["ok"] == true
|
|
||||||
assert length(decoded["sessions"]) == 1
|
|
||||||
assert hd(decoded["sessions"])["user_agent"] =~ "Mozilla"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "sessions revoke prints confirmation" do
|
|
||||||
{code, out} = run_out(["sessions", "revoke", "0192a1b0-0000"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "session 已撤銷"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "sessions revoke missing id maps 404 to exit 1" do
|
|
||||||
{code, err} = run_err(["sessions", "revoke", "missing"])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "404"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "sessions revoke-others prints count" do
|
|
||||||
{code, out} = run_out(["sessions", "revoke-others"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "已撤銷 3 個其他 session"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- tokens --
|
|
||||||
|
|
||||||
test "tokens list renders table with status" do
|
|
||||||
{code, out} = run_out(["tokens", "list"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "ci-token"
|
|
||||||
assert out =~ "active"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "tokens list --json outputs spec shape" do
|
|
||||||
{code, out} = run_out(["tokens", "list", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["ok"] == true
|
|
||||||
assert hd(decoded["tokens"])["name"] == "ci-token"
|
|
||||||
# 明文絕不出現在 list
|
|
||||||
refute out =~ "9f3a-raw-token-once"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "tokens create shows raw token exactly once" do
|
|
||||||
{code, out} = run_out(["tokens", "create", "--name", "ci-token"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "PAT 已建立:ci-token"
|
|
||||||
assert out =~ "9f3a-raw-token-once"
|
|
||||||
assert out =~ "只顯示這一次"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "tokens create --json includes raw once" do
|
|
||||||
{code, out} = run_out(["tokens", "create", "--name", "ci", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["raw"] == "9f3a-raw-token-once"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "tokens create never expiry" do
|
|
||||||
{code, out} = run_out(["tokens", "create", "--name", "ci", "--expires-in", "never"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "無到期日"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "tokens revoke prints confirmation" do
|
|
||||||
{code, out} = run_out(["tokens", "revoke", "0192a1c0-0000"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "PAT 已撤銷"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- mfa --
|
|
||||||
|
|
||||||
test "mfa status shows disabled" do
|
|
||||||
{code, out} = run_out(["mfa", "status"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "未啟用"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "mfa status shows enabled when totp on" do
|
|
||||||
Process.put(:fake_profile_overrides, %{"mfa_enabled" => true})
|
|
||||||
{code, out} = run_out(["mfa", "status"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "已啟用"
|
|
||||||
after
|
|
||||||
Process.delete(:fake_profile_overrides)
|
|
||||||
end
|
|
||||||
|
|
||||||
test "mfa setup prints QR + secret then recovery codes" do
|
|
||||||
{code, out} = run_out(["mfa", "setup"], ["123456"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "otpauth://totp/Bear:x"
|
|
||||||
assert out =~ "JBSWY3DPEHPK3PXP"
|
|
||||||
# QR 為 ASCII 區塊字元
|
|
||||||
assert out =~ "█"
|
|
||||||
assert out =~ "recovery codes"
|
|
||||||
assert out =~ "rc-1"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "mfa setup --json does not print QR block" do
|
|
||||||
{code, out} = run_out(["mfa", "setup", "--json"], ["123456"])
|
|
||||||
assert code == 0
|
|
||||||
assert {:ok, decoded} = Jason.decode(out)
|
|
||||||
assert decoded["recovery_codes"] == ["rc-1", "rc-2"]
|
|
||||||
end
|
|
||||||
|
|
||||||
test "mfa setup invalid code maps to exit 1" do
|
|
||||||
{code, err} = run_err(["mfa", "setup"], ["000000"])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "invalid_code"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "mfa setup already enabled maps 422 to exit 1" do
|
|
||||||
with_api_error(
|
|
||||||
{:error, :unprocessable_entity,
|
|
||||||
%{"error" => "already_enabled", "error_description" => "MFA is already enabled."}}
|
|
||||||
)
|
|
||||||
|
|
||||||
{code, err} = run_err(["mfa", "setup"], ["123456"])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "already_enabled"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "mfa disable happy path" do
|
|
||||||
{code, out} = run_out(["mfa", "disable"], ["123456"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "MFA 已停用"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "mfa recovery-codes regenerates" do
|
|
||||||
{code, out} = run_out(["mfa", "recovery-codes"], ["123456"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "new-rc-1"
|
|
||||||
assert out =~ "只顯示這一次"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 共通錯誤分流 --
|
|
||||||
|
|
||||||
test "401 maps to exit 3 with re-login hint" do
|
|
||||||
with_api_error({:error, :unauthorized, "invalid_token"})
|
|
||||||
|
|
||||||
{code, err} = run_err(["profile", "show"])
|
|
||||||
assert code == 3
|
|
||||||
assert err =~ "bear login"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "403 maps to exit 8" do
|
|
||||||
with_api_error({:error, :forbidden, "forbidden"})
|
|
||||||
|
|
||||||
{code, err} = run_err(["profile", "show"])
|
|
||||||
assert code == 8
|
|
||||||
assert err =~ "403"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "network error maps to exit 6" do
|
|
||||||
with_api_error({:error, :network, "econnrefused"})
|
|
||||||
|
|
||||||
{code, err} = run_err(["profile", "show"])
|
|
||||||
assert code == 6
|
|
||||||
assert err =~ "econnrefused"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "server error maps to exit 6" do
|
|
||||||
with_api_error({:error, :server_error, 500})
|
|
||||||
|
|
||||||
{code, err} = run_err(["profile", "show"])
|
|
||||||
assert code == 6
|
|
||||||
assert err =~ "500"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "not logged in exits 3" do
|
|
||||||
System.delete_env("BEAR_TOKEN")
|
|
||||||
|
|
||||||
{code, err} = run_err(["profile", "show"])
|
|
||||||
assert code == 3
|
|
||||||
assert err =~ "未登入"
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 直接模組層測試 --
|
|
||||||
|
|
||||||
test "SelfService.run/3 with injected api" do
|
|
||||||
{code, out} =
|
|
||||||
ExUnit.CaptureIO.with_io(fn ->
|
|
||||||
SelfService.run(:profile, :show,
|
|
||||||
ss_api: FakeApi,
|
|
||||||
issuer: "https://alterminal.com"
|
|
||||||
)
|
|
||||||
end)
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "alice@example.com"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
defmodule BearCli.TTYTest do
|
|
||||||
@moduledoc """
|
|
||||||
`BearCli.TTY` 單元測試(issue #19):
|
|
||||||
|
|
||||||
- `tty_path?/1`:裝置路徑分類(pts/tty/console=TTY;pipe/檔案/
|
|
||||||
socket//dev/null=非 TTY)。
|
|
||||||
- `stdin_tty?/0`:在本測試環境(ExUnit 捕獲 IO,stdin 非 TTY)應為
|
|
||||||
`false`;`rows_tty?/0` 在 escript/noshell 環境回 `enotsup` → `false`。
|
|
||||||
- fd 0 偵測走 `/proc/self/fd/0`,Linux 上必可用。
|
|
||||||
"""
|
|
||||||
use ExUnit.Case, async: true
|
|
||||||
|
|
||||||
alias BearCli.TTY
|
|
||||||
|
|
||||||
describe "tty_path?/1" do
|
|
||||||
test "終端機裝置路徑 → true" do
|
|
||||||
assert TTY.tty_path?("/dev/pts/0")
|
|
||||||
assert TTY.tty_path?("/dev/pts/17")
|
|
||||||
assert TTY.tty_path?("/dev/tty1")
|
|
||||||
assert TTY.tty_path?("/dev/tty")
|
|
||||||
assert TTY.tty_path?("/dev/ttyS0")
|
|
||||||
assert TTY.tty_path?("/dev/console")
|
|
||||||
assert TTY.tty_path?("/dev/ptmx")
|
|
||||||
end
|
|
||||||
|
|
||||||
test "pipe/檔案/socket/null → false" do
|
|
||||||
refute TTY.tty_path?("pipe:[12345]")
|
|
||||||
refute TTY.tty_path?("socket:[12345]")
|
|
||||||
refute TTY.tty_path?("/dev/null")
|
|
||||||
refute TTY.tty_path?("/home/user/secret.txt")
|
|
||||||
refute TTY.tty_path?("/proc/self/fd/0")
|
|
||||||
refute TTY.tty_path?("")
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe "stdin_tty?/0" do
|
|
||||||
test "測試環境(stdin 非 TTY)→ false" do
|
|
||||||
# ExUnit 的 group leader 為擷取裝置、測試程序的 stdin 非終端機。
|
|
||||||
refute TTY.stdin_tty?()
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe "fd0 實體判定(Linux /proc)" do
|
|
||||||
test "/proc/self/fd/0 可解析且與路徑分類一致" do
|
|
||||||
# 本測試在 Linux 跑:readlink 一定有結果;stdin 非 TTY → 分類為非 TTY。
|
|
||||||
assert {:ok, path} = call_fd0_path()
|
|
||||||
assert TTY.stdin_tty?() == TTY.tty_path?(path)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
defp call_fd0_path do
|
|
||||||
case :file.read_link('/proc/self/fd/0') do
|
|
||||||
{:ok, p} -> {:ok, to_string(p)}
|
|
||||||
{:error, e} -> {:error, e}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,712 +0,0 @@
|
|||||||
defmodule BearCli.VaultTest do
|
|
||||||
@moduledoc """
|
|
||||||
`bear vault` 指令群單元測試(issue #17):注入 fake API 與 fake IO,
|
|
||||||
涵蓋解析、退出碼、session 傳遞、輸出,以及以 bear 倉庫
|
|
||||||
Bear.Vault.Crypto 產生的密文樣本做交叉驗證(解密方向)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
use ExUnit.Case, async: false
|
|
||||||
|
|
||||||
alias BearCli.{CLI, Vault}
|
|
||||||
alias BearCli.Vault.{BIP39, Crypto}
|
|
||||||
|
|
||||||
# -- 測試向量(bear 倉庫 Bear.Vault.Crypto 產生;低迭代數 1000)--
|
|
||||||
|
|
||||||
@email "alice@example.com"
|
|
||||||
@master_password "hunter2-master"
|
|
||||||
@iterations 1000
|
|
||||||
|
|
||||||
@mnemonic "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
|
|
||||||
|
|
||||||
@k_user_b64 "K/O8bAn/PY6dn/eDgrk+nygzsJqefb8X6dXJbsObc52vgwE59gJneAoisgLUVH27ZJzo0ZmZ9YHINm77GDBhvQ=="
|
|
||||||
|
|
||||||
# Bear.Vault.Crypto 產生的密文樣本(Bear 加密 → CLI 必須能解)
|
|
||||||
@bear_fields %{
|
|
||||||
"name" =>
|
|
||||||
"2.d6+BTOM7a9cfjkwHuVwMiQ==.HjD0PvHOAvF3paiwPVYhEw==.PP1LIagMuk+K1abbVsacUuZ75D6encFDxqoPlpYdxX0=",
|
|
||||||
"username" =>
|
|
||||||
"2.vC7LtEADotrjHGCsjW5Uig==.IaNd0TABb1ho8A4G0pqA/2n0Na6cxQ0ZwoN4bKt2R6A=.x8QsmI0yJCcLEZV4gsCKAFHQeG1knlr/djc18oAGBJA=",
|
|
||||||
"password" =>
|
|
||||||
"2.nxg73aQIDN4xvpEMBk3dSQ==.Y3+Tb5FwJkG/MmdtcTu1K82yiyQHFFqZeqR/IhJaOq0=.8jixeUyAfq+pw/wHuywg63VCIOCqGx3MJDnPV33NozU=",
|
|
||||||
"notes" =>
|
|
||||||
"2.v5pif7yQpe2u3XAgH06Srw==.oDT6EqIuzuVcZca2oI4j2AJWQk70XmLWn0C9GY/NkMs=.ntfUvhrh8W879tdRM/VVBaRKJ9fwTvZBOKybZXK+1Ww=",
|
|
||||||
"uri" =>
|
|
||||||
"2.Dip98+nZdQa73RVoYxRXmg==.9IVFM9cxG6qLfdcvpPNNPnukpasXXVC3qnYaPQeBp+U=.5AdqSZcYL3vIxAOOkQPCszIwtgGbmTwMuk5rraJuCD4="
|
|
||||||
}
|
|
||||||
|
|
||||||
@wrapped_password "2.7QpF/MDK1QxjxvHuW+InIw==.Ner6k/lJdta6eBfFICfBXpSeUTuOoABGKUp8dG9joah1dWrjazOJqW/9YPGgiAgYS25wif2WgtnQ5grXHY2xrjSvRclb0rdH1mSA/ublaVfVxKMFGZPnkeoQgB+FmjcP.iRDkb7+J67pVh/ywWiWP+bkZut2k4o7JrJfJG6izZzg="
|
|
||||||
@wrapped_mnemonic "2.i73ZfZChxC+x8qIWtXRQ5w==.5gOWELJjoYm78kP6cXvUG1yR4X6T44c7sTHMp0om8RhljFa9dfGLCXaxTULLBHlJ/9EbrRj3Q3kUaG3/e6grAm37L4zEJZsXcETQS9J4tvHSh87lqGH+3lvMAsBlRpVp.ePbxk+weahIIaZdQlCRqHQ0KTnSinUOleuoUIMghlqE="
|
|
||||||
|
|
||||||
@folder_name_ct "2.uREiwRhNrOwjocwcGJrSXA==.vc5kZtTN/SfDJB0/3Qe5yg==.fVSBlhTtmpP0Lm8rbHT+n1ftomf3chV8pWwpK0Rwgig="
|
|
||||||
@extra_ct "2.W1q2N0MclfjZvF0puu+g0A==.K3s0aX2La3XwsUu9cIwluQ==./ZrMME1LJoHjtev/xWXRwcPmIEiyN/Nq4QcauPiRWSw="
|
|
||||||
|
|
||||||
@profile %{
|
|
||||||
"id" => "0193aaaa-0000-7000-8000-0000000000aa",
|
|
||||||
"security_stamp" => "stamp-1",
|
|
||||||
"kdf" => %{
|
|
||||||
"iterations" => @iterations,
|
|
||||||
"hash" => "SHA-512",
|
|
||||||
"salt" => "account_email_lowercase"
|
|
||||||
},
|
|
||||||
"wrapped_user_password" => @wrapped_password,
|
|
||||||
"wrapped_user_mnemonic" => @wrapped_mnemonic,
|
|
||||||
"enabled" => true,
|
|
||||||
"last_synced_at" => "2026-09-10T00:00:00Z"
|
|
||||||
}
|
|
||||||
|
|
||||||
@folder %{
|
|
||||||
"id" => "0193bbbb-0000-7000-8000-0000000000bb",
|
|
||||||
"folder_uuid" => "folder-uuid-1",
|
|
||||||
"name" => @folder_name_ct,
|
|
||||||
"revision_date" => "2026-09-10T01:00:00Z"
|
|
||||||
}
|
|
||||||
|
|
||||||
@cipher %{
|
|
||||||
"id" => "0193cccc-0000-7000-8000-0000000000cc",
|
|
||||||
"cipher_uuid" => "cipher-uuid-1",
|
|
||||||
"cipher_type" => "login",
|
|
||||||
"name" => @bear_fields["name"],
|
|
||||||
"username" => @bear_fields["username"],
|
|
||||||
"password" => @bear_fields["password"],
|
|
||||||
"uris" => [@bear_fields["uri"]],
|
|
||||||
"notes" => @bear_fields["notes"],
|
|
||||||
"data" => %{"folder_uuid" => "folder-uuid-1", "extra" => @extra_ct},
|
|
||||||
"favorite" => false,
|
|
||||||
"reprompt" => 0,
|
|
||||||
"deleted_at" => nil,
|
|
||||||
"revision_date" => "2026-09-10T05:00:00Z"
|
|
||||||
}
|
|
||||||
|
|
||||||
# -- fake API --
|
|
||||||
|
|
||||||
defmodule FakeApi do
|
|
||||||
def error, do: Process.get(:fake_vault_error)
|
|
||||||
def error(result), do: Process.put(:fake_vault_error, result)
|
|
||||||
|
|
||||||
def uploads, do: Process.get(:fake_vault_uploads, [])
|
|
||||||
def push_upload(u), do: Process.put(:fake_vault_uploads, [u | uploads()])
|
|
||||||
|
|
||||||
def vault_config(_issuer, _token) do
|
|
||||||
error() ||
|
|
||||||
{:ok,
|
|
||||||
%{
|
|
||||||
"data" => %{
|
|
||||||
"kdf" => %{
|
|
||||||
"iterations" => 1000,
|
|
||||||
"hash" => "SHA-512",
|
|
||||||
"salt" => "account_email_lowercase"
|
|
||||||
},
|
|
||||||
"encryption_types" => ["2"]
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_profile_get(_issuer, _token) do
|
|
||||||
error() || {:ok, %{"data" => profile()}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_profile_put(_issuer, _token, attrs) do
|
|
||||||
push_upload({:profile, attrs})
|
|
||||||
{:ok, %{"data" => Map.merge(profile(), attrs)}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_sync(_issuer, _token) do
|
|
||||||
error() ||
|
|
||||||
{:ok,
|
|
||||||
%{
|
|
||||||
"data" => %{
|
|
||||||
"profile" => profile(),
|
|
||||||
"folders" => [folder()],
|
|
||||||
"ciphers" => [cipher()],
|
|
||||||
"domains" => nil
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_ciphers_list(_issuer, _token) do
|
|
||||||
error() || {:ok, %{"data" => [cipher()]}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_ciphers_upsert(_issuer, _token, attrs) do
|
|
||||||
push_upload({:cipher_upsert, attrs})
|
|
||||||
{:ok, %{"data" => Map.merge(cipher(), attrs)}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_ciphers_get(_issuer, _token, "cipher-uuid-1") do
|
|
||||||
error() || {:ok, %{"data" => cipher()}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_ciphers_get(_issuer, _token, _other) do
|
|
||||||
error() || {:error, :not_found, "not_found"}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_ciphers_update(_issuer, _token, uuid, attrs) do
|
|
||||||
push_upload({:cipher_update, uuid, attrs})
|
|
||||||
{:ok, %{"data" => Map.merge(cipher(), attrs)}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_ciphers_delete(_issuer, _token, uuid) do
|
|
||||||
push_upload({:cipher_delete, uuid})
|
|
||||||
{:ok, %{"data" => cipher()}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_ciphers_restore(_issuer, _token, uuid) do
|
|
||||||
push_upload({:cipher_restore, uuid})
|
|
||||||
{:ok, %{"data" => cipher()}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_ciphers_purge(_issuer, _token, uuid) do
|
|
||||||
push_upload({:cipher_purge, uuid})
|
|
||||||
{:ok, %{"data" => %{"deleted" => uuid}}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_folders_list(_issuer, _token) do
|
|
||||||
error() || {:ok, %{"data" => [folder()]}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_folders_upsert(_issuer, _token, attrs) do
|
|
||||||
push_upload({:folder_upsert, attrs})
|
|
||||||
{:ok, %{"data" => Map.merge(folder(), attrs)}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_folders_rename(_issuer, _token, uuid, attrs) do
|
|
||||||
push_upload({:folder_rename, uuid, attrs})
|
|
||||||
{:ok, %{"data" => Map.merge(folder(), attrs)}}
|
|
||||||
end
|
|
||||||
|
|
||||||
def vault_folders_delete(_issuer, _token, uuid) do
|
|
||||||
push_upload({:folder_delete, uuid})
|
|
||||||
{:ok, %{"data" => %{"deleted" => uuid}}}
|
|
||||||
end
|
|
||||||
|
|
||||||
defp profile, do: BearCli.VaultTest.profile_fixture()
|
|
||||||
defp folder, do: BearCli.VaultTest.folder_fixture()
|
|
||||||
defp cipher, do: BearCli.VaultTest.cipher_fixture()
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- fake IO(prompt_secret/1 不回顯;prompt/1 一般輸入)--
|
|
||||||
|
|
||||||
defmodule FakeIO do
|
|
||||||
defp take(queue_key) do
|
|
||||||
case Process.get(queue_key) do
|
|
||||||
[] ->
|
|
||||||
:eof
|
|
||||||
|
|
||||||
[next | rest] ->
|
|
||||||
Process.put(queue_key, rest)
|
|
||||||
{:ok, next}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def prompt_secret(_label), do: take(:fake_io_inputs)
|
|
||||||
def prompt(_label), do: take(:fake_io_inputs)
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 測試輔助 --
|
|
||||||
|
|
||||||
setup do
|
|
||||||
old = System.get_env("BEAR_TOKEN")
|
|
||||||
old_session = System.get_env("BEAR_VAULT_SESSION")
|
|
||||||
old_creds = System.get_env("BEAR_CREDENTIALS")
|
|
||||||
|
|
||||||
on_exit(fn ->
|
|
||||||
restore(old, "BEAR_TOKEN")
|
|
||||||
restore(old_session, "BEAR_VAULT_SESSION")
|
|
||||||
restore(old_creds, "BEAR_CREDENTIALS")
|
|
||||||
end)
|
|
||||||
|
|
||||||
System.put_env("BEAR_TOKEN", "user-pat")
|
|
||||||
System.put_env("BEAR_CREDENTIALS", "/nonexistent/credentials.json")
|
|
||||||
System.delete_env("BEAR_VAULT_SESSION")
|
|
||||||
:ok
|
|
||||||
end
|
|
||||||
|
|
||||||
def profile_fixture, do: @profile
|
|
||||||
def folder_fixture, do: @folder
|
|
||||||
def cipher_fixture, do: @cipher
|
|
||||||
|
|
||||||
defp run_out(argv, inputs \\ [], session \\ nil) do
|
|
||||||
Process.put(:fake_io_inputs, inputs)
|
|
||||||
Process.put(:fake_vault_uploads, [])
|
|
||||||
FakeApi.error(nil)
|
|
||||||
|
|
||||||
opts = [vault_api: FakeApi, io: FakeIO, tty?: true, email: @email] |> maybe_session(session)
|
|
||||||
|
|
||||||
ExUnit.CaptureIO.with_io(fn ->
|
|
||||||
CLI.dispatch(CLI.parse(argv), opts)
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
# 錯誤輸出在 stderr;以 with_io(:stderr) 捕捉。不重設 FakeApi.error
|
|
||||||
# (呼叫者可先設定錯誤情境)。
|
|
||||||
defp run_err(argv, inputs \\ [], session \\ nil) do
|
|
||||||
Process.put(:fake_io_inputs, inputs)
|
|
||||||
Process.put(:fake_vault_uploads, [])
|
|
||||||
|
|
||||||
opts = [vault_api: FakeApi, io: FakeIO, tty?: true, email: @email] |> maybe_session(session)
|
|
||||||
|
|
||||||
ExUnit.CaptureIO.with_io(:stderr, "", fn ->
|
|
||||||
CLI.dispatch(CLI.parse(argv), opts)
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
defp maybe_session(opts, nil), do: opts
|
|
||||||
defp maybe_session(opts, session), do: Keyword.put(opts, :session, session)
|
|
||||||
|
|
||||||
defp uploads, do: Process.get(:fake_vault_uploads, []) |> Enum.reverse()
|
|
||||||
|
|
||||||
defp restore(nil, key), do: System.delete_env(key)
|
|
||||||
defp restore(value, key), do: System.put_env(key, value)
|
|
||||||
|
|
||||||
# -- 加密原語:與 bear(Bear.Vault.Crypto)交叉驗證 --
|
|
||||||
|
|
||||||
describe "crypto interop (Bear.Vault.Crypto samples)" do
|
|
||||||
test "decrypts fields encrypted by Bear.Vault.Crypto" do
|
|
||||||
k_user = Base.decode64!(@k_user_b64)
|
|
||||||
|
|
||||||
assert {:ok, "GitHub"} = Crypto.decrypt(@bear_fields["name"], k_user)
|
|
||||||
assert {:ok, "s3cret-帕米拉"} = Crypto.decrypt(@bear_fields["password"], k_user)
|
|
||||||
end
|
|
||||||
|
|
||||||
test "unwraps K_user encrypted by Bear.Vault.Crypto (password path)" do
|
|
||||||
master = Crypto.derive_master_key(@master_password, @email, @iterations)
|
|
||||||
assert {:ok, key} = Crypto.unwrap_user_key(@wrapped_password, master)
|
|
||||||
assert Base.encode64(key) == @k_user_b64
|
|
||||||
end
|
|
||||||
|
|
||||||
test "rejects wrong master password (MAC failure)" do
|
|
||||||
master = Crypto.derive_master_key("wrong-password", @email, @iterations)
|
|
||||||
assert {:error, :invalid} = Crypto.unwrap_user_key(@wrapped_password, master)
|
|
||||||
end
|
|
||||||
|
|
||||||
test "rejects tampered MAC" do
|
|
||||||
k_user = Base.decode64!(@k_user_b64)
|
|
||||||
ct = Crypto.encrypt("hello", k_user)
|
|
||||||
[pre, iv, c, _mac] = String.split(ct, ".")
|
|
||||||
tampered = Enum.join([pre, iv, c, Base.encode64(:crypto.strong_rand_bytes(32))], ".")
|
|
||||||
assert {:error, :invalid} = Crypto.decrypt(tampered, k_user)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- BIP39 --
|
|
||||||
|
|
||||||
describe "BIP39" do
|
|
||||||
test "official vector: zero entropy → abandon…about" do
|
|
||||||
assert BIP39.mnemonic_from_entropy(<<0::128>>) == @mnemonic
|
|
||||||
end
|
|
||||||
|
|
||||||
test "official vector: mnemonic → seed" do
|
|
||||||
seed = BIP39.mnemonic_to_seed(@mnemonic)
|
|
||||||
|
|
||||||
assert Base.encode16(seed, case: :lower) ==
|
|
||||||
"5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "valid?/1 accepts official vector and rejects bad checksum" do
|
|
||||||
assert BIP39.valid?(@mnemonic)
|
|
||||||
assert BIP39.valid?(String.upcase(" #{@mnemonic} "))
|
|
||||||
# 改一個字 → 校驗和不符
|
|
||||||
refute BIP39.valid?(String.replace(@mnemonic, "about", "abandon"))
|
|
||||||
refute BIP39.valid?("not twelve words")
|
|
||||||
end
|
|
||||||
|
|
||||||
test "rescue key path unwraps wrapped_mnemonic (Bear-produced)" do
|
|
||||||
seed = BIP39.mnemonic_to_seed(@mnemonic)
|
|
||||||
rescue_key = BIP39.rescue_key_from_seed(seed, @email, @iterations)
|
|
||||||
assert {:ok, key} = Crypto.unwrap_user_key(@wrapped_mnemonic, rescue_key)
|
|
||||||
assert Base.encode64(key) == @k_user_b64
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 解析與用法錯誤 --
|
|
||||||
|
|
||||||
describe "parsing" do
|
|
||||||
test "unknown verb → 2" do
|
|
||||||
{code, err} = run_err(["vault", "nope"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "未知的 vault 子指令"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "missing uuid → 2" do
|
|
||||||
{code, err} = run_err(["vault", "get"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "缺少 <uuid>"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "create rejects bad --type → 2" do
|
|
||||||
{code, err} = run_err(["vault", "create", "--type", "photo"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "--type"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "vault with no verb → 2" do
|
|
||||||
{code, err} = run_err(["vault"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "缺少子指令"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- status / unlock / lock --
|
|
||||||
|
|
||||||
describe "status" do
|
|
||||||
test "shows initialized + KDF + lock state" do
|
|
||||||
{code, out} = run_out(["vault", "status"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "已初始化"
|
|
||||||
assert out =~ "SHA-512"
|
|
||||||
assert out =~ "未解鎖"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "--json reports initialized false on 404" do
|
|
||||||
FakeApi.error({:error, :not_found, "not_found"})
|
|
||||||
|
|
||||||
{code, out} =
|
|
||||||
ExUnit.CaptureIO.with_io(fn ->
|
|
||||||
CLI.dispatch(CLI.parse(["vault", "status", "--json"]),
|
|
||||||
vault_api: FakeApi,
|
|
||||||
io: FakeIO,
|
|
||||||
tty?: true,
|
|
||||||
email: @email
|
|
||||||
)
|
|
||||||
end)
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "\"initialized\":false"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe "unlock" do
|
|
||||||
test "correct master password → session env output" do
|
|
||||||
{code, out} = run_out(["vault", "unlock"], [@master_password])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "BEAR_VAULT_SESSION="
|
|
||||||
assert out =~ @k_user_b64
|
|
||||||
end
|
|
||||||
|
|
||||||
test "wrong master password → 1" do
|
|
||||||
{code, err} = run_err(["vault", "unlock"], ["wrong-password"])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "主密碼不正確"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe "lock" do
|
|
||||||
test "suggests unset when session present" do
|
|
||||||
{code, out} = run_out(["vault", "lock"], [], @k_user_b64)
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "unset BEAR_VAULT_SESSION"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- list / get(解密顯示)--
|
|
||||||
|
|
||||||
describe "list" do
|
|
||||||
test "locked: shows uuid/type without decrypting" do
|
|
||||||
{code, out} = run_out(["vault", "list"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "cipher-uuid-1"
|
|
||||||
refute out =~ "GitHub"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "unlocked: decrypts names and folder (Bear-encrypted samples)" do
|
|
||||||
{code, out} = run_out(["vault", "list"], [], @k_user_b64)
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "GitHub"
|
|
||||||
assert out =~ "工作"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "--folder filters by data.folder_uuid" do
|
|
||||||
{code, out} = run_out(["vault", "list", "--folder", "folder-uuid-1"], [], @k_user_b64)
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "GitHub"
|
|
||||||
|
|
||||||
{code, out} = run_out(["vault", "list", "--folder", "no-such"], [], @k_user_b64)
|
|
||||||
assert code == 0
|
|
||||||
refute out =~ "GitHub"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe "get" do
|
|
||||||
test "unlocked: decrypts all fields (Bear-encrypted samples)" do
|
|
||||||
{code, out} = run_out(["vault", "get", "cipher-uuid-1"], [], @k_user_b64)
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "GitHub"
|
|
||||||
assert out =~ "alice@example.com"
|
|
||||||
assert out =~ "s3cret-帕米拉"
|
|
||||||
assert out =~ "https://github.com"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "locked: shows ciphertext state hint" do
|
|
||||||
{code, out} = run_out(["vault", "get", "cipher-uuid-1"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "未解密"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "404 → 1" do
|
|
||||||
{code, err} = run_err(["vault", "get", "missing-uuid"])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "404"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- create(加密上傳)--
|
|
||||||
|
|
||||||
describe "create" do
|
|
||||||
test "requires session → 2" do
|
|
||||||
{code, err} = run_err(["vault", "create", "--type", "login"], [])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "BEAR_VAULT_SESSION"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "login: encrypts fields client-side and uploads" do
|
|
||||||
inputs = [
|
|
||||||
"GitHub",
|
|
||||||
"alice@example.com",
|
|
||||||
"new-secret",
|
|
||||||
"https://github.com,https://api.github.com",
|
|
||||||
"備註"
|
|
||||||
]
|
|
||||||
|
|
||||||
{code, out} =
|
|
||||||
run_out(
|
|
||||||
["vault", "create", "--type", "login", "--folder", "folder-uuid-1"],
|
|
||||||
inputs,
|
|
||||||
@k_user_b64
|
|
||||||
)
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "已建立"
|
|
||||||
|
|
||||||
assert [{:cipher_upsert, attrs}] = uploads()
|
|
||||||
|
|
||||||
# 欄位是加密字串(type 2),非明文
|
|
||||||
assert attrs["name"] =~ ~r/^2\./
|
|
||||||
assert attrs["username"] =~ ~r/^2\./
|
|
||||||
assert attrs["password"] =~ ~r/^2\./
|
|
||||||
assert length(attrs["uris"]) == 2
|
|
||||||
assert attrs["data"]["folder_uuid"] == "folder-uuid-1"
|
|
||||||
|
|
||||||
# CLI 加密 → Bear/CLI 可解回(round-trip)
|
|
||||||
assert {:ok, "GitHub"} = Crypto.decrypt(attrs["name"], Base.decode64!(@k_user_b64))
|
|
||||||
assert {:ok, "new-secret"} = Crypto.decrypt(attrs["password"], Base.decode64!(@k_user_b64))
|
|
||||||
end
|
|
||||||
|
|
||||||
test "secure_note: notes encrypted" do
|
|
||||||
inputs = ["筆記標題", "內容一二三"]
|
|
||||||
|
|
||||||
{code, _out} = run_out(["vault", "create", "--type", "secure_note"], inputs, @k_user_b64)
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert [{:cipher_upsert, attrs}] = uploads()
|
|
||||||
assert {:ok, "筆記標題"} = Crypto.decrypt(attrs["name"], Base.decode64!(@k_user_b64))
|
|
||||||
assert {:ok, "內容一二三"} = Crypto.decrypt(attrs["notes"], Base.decode64!(@k_user_b64))
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- edit --
|
|
||||||
|
|
||||||
describe "edit" do
|
|
||||||
test "Enter keeps current values; changes re-encrypted" do
|
|
||||||
# 依次:名稱(新值)、帳號(Enter 保留)、密碼(Enter 保留)、URI、備註
|
|
||||||
inputs = ["新名字", "", "", "https://github.com", ""]
|
|
||||||
|
|
||||||
{code, out} = run_out(["vault", "edit", "cipher-uuid-1"], inputs, @k_user_b64)
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "已更新"
|
|
||||||
|
|
||||||
assert [{:cipher_update, "cipher-uuid-1", attrs}] = uploads()
|
|
||||||
assert {:ok, "新名字"} = Crypto.decrypt(attrs["name"], Base.decode64!(@k_user_b64))
|
|
||||||
# 密碼 Enter 保留 → 重加密後解密仍為原明文
|
|
||||||
assert {:ok, "s3cret-帕米拉"} = Crypto.decrypt(attrs["password"], Base.decode64!(@k_user_b64))
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- delete / restore / purge --
|
|
||||||
|
|
||||||
describe "delete / restore / purge" do
|
|
||||||
test "delete → trash endpoint" do
|
|
||||||
{code, _out} = run_out(["vault", "delete", "cipher-uuid-1"])
|
|
||||||
assert code == 0
|
|
||||||
assert [{:cipher_delete, "cipher-uuid-1"}] = uploads()
|
|
||||||
end
|
|
||||||
|
|
||||||
test "restore → restore endpoint" do
|
|
||||||
{code, _out} = run_out(["vault", "restore", "cipher-uuid-1"])
|
|
||||||
assert code == 0
|
|
||||||
assert [{:cipher_restore, "cipher-uuid-1"}] = uploads()
|
|
||||||
end
|
|
||||||
|
|
||||||
test "purge requires y confirmation" do
|
|
||||||
{code, _out} = run_out(["vault", "purge", "cipher-uuid-1"], ["n"])
|
|
||||||
assert code == 1
|
|
||||||
assert uploads() == []
|
|
||||||
|
|
||||||
{code, _out} = run_out(["vault", "purge", "cipher-uuid-1"], ["y"])
|
|
||||||
assert code == 0
|
|
||||||
assert [{:cipher_purge, "cipher-uuid-1"}] = uploads()
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- folders --
|
|
||||||
|
|
||||||
describe "folders" do
|
|
||||||
test "list unlocked decrypts names (Bear-encrypted sample)" do
|
|
||||||
{code, out} = run_out(["vault", "folders", "list"], [], @k_user_b64)
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "folder-uuid-1"
|
|
||||||
assert out =~ "工作"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "create encrypts name" do
|
|
||||||
{code, _out} = run_out(["vault", "folders", "create"], ["新資料夾"], @k_user_b64)
|
|
||||||
assert code == 0
|
|
||||||
assert [{:folder_upsert, attrs}] = uploads()
|
|
||||||
assert {:ok, "新資料夾"} = Crypto.decrypt(attrs["name"], Base.decode64!(@k_user_b64))
|
|
||||||
end
|
|
||||||
|
|
||||||
test "rename encrypts new name" do
|
|
||||||
{code, _out} = run_out(["vault", "folders", "rename", "folder-uuid-1"], ["改名"], @k_user_b64)
|
|
||||||
assert code == 0
|
|
||||||
assert [{:folder_rename, "folder-uuid-1", %{"name" => ct}}] = uploads()
|
|
||||||
assert {:ok, "改名"} = Crypto.decrypt(ct, Base.decode64!(@k_user_b64))
|
|
||||||
end
|
|
||||||
|
|
||||||
test "delete folder" do
|
|
||||||
{code, _out} = run_out(["vault", "folders", "delete", "folder-uuid-1"])
|
|
||||||
assert code == 0
|
|
||||||
assert [{:folder_delete, "folder-uuid-1"}] = uploads()
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- sync --
|
|
||||||
|
|
||||||
describe "sync" do
|
|
||||||
test "reports counts from server payload" do
|
|
||||||
{code, out} = run_out(["vault", "sync"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "資料夾:1 個"
|
|
||||||
assert out =~ "項目:1 個"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "--json echoes payload" do
|
|
||||||
{code, out} = run_out(["vault", "sync", "--json"])
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "\"ciphers\""
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- password change / rescue --
|
|
||||||
|
|
||||||
describe "password change" do
|
|
||||||
test "re-wraps K_user under new master password (ciphers untouched)" do
|
|
||||||
inputs = [@master_password, "new-master-88", "new-master-88"]
|
|
||||||
|
|
||||||
{code, out} = run_out(["vault", "password", "change"], inputs)
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "主密碼已更新"
|
|
||||||
|
|
||||||
assert [{:profile, %{"wrapped_user_password" => wrapped}}] = uploads()
|
|
||||||
|
|
||||||
# 新包裝可用新主密碼解開,且解出同一把 K_user
|
|
||||||
new_master = Crypto.derive_master_key("new-master-88", @email, @iterations)
|
|
||||||
assert {:ok, key} = Crypto.unwrap_user_key(wrapped, new_master)
|
|
||||||
assert Base.encode64(key) == @k_user_b64
|
|
||||||
|
|
||||||
# 只動 wrapped_user_password
|
|
||||||
assert map_size(Process.get(:fake_vault_uploads) |> hd() |> elem(1)) == 1
|
|
||||||
end
|
|
||||||
|
|
||||||
test "mismatched new passwords → 2" do
|
|
||||||
{code, err} =
|
|
||||||
run_err(["vault", "password", "change"], [@master_password, "aaaabbbb", "ccccdddd"])
|
|
||||||
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "不一致"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "short new password → 2" do
|
|
||||||
{code, err} = run_err(["vault", "password", "change"], [@master_password, "short", "short"])
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "至少需要"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
describe "rescue" do
|
|
||||||
test "unwraps via mnemonic and sets new master password" do
|
|
||||||
inputs = [@mnemonic, "brand-new-99", "brand-new-99"]
|
|
||||||
|
|
||||||
{code, out} = run_out(["vault", "rescue"], inputs)
|
|
||||||
|
|
||||||
assert code == 0
|
|
||||||
assert out =~ "重設主密碼"
|
|
||||||
|
|
||||||
assert [{:profile, %{"wrapped_user_password" => wrapped}}] = uploads()
|
|
||||||
|
|
||||||
new_master = Crypto.derive_master_key("brand-new-99", @email, @iterations)
|
|
||||||
assert {:ok, key} = Crypto.unwrap_user_key(wrapped, new_master)
|
|
||||||
assert Base.encode64(key) == @k_user_b64
|
|
||||||
end
|
|
||||||
|
|
||||||
test "invalid mnemonic checksum → 1" do
|
|
||||||
bad = String.replace(@mnemonic, "about", "abandon")
|
|
||||||
{code, err} = run_err(["vault", "rescue"], [bad])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "助記詞"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "wrong-but-valid mnemonic → 1 (unwrap fails)" do
|
|
||||||
# 另一組合法助記詞,但解不開 wrapped_user_mnemonic
|
|
||||||
other = BIP39.generate()
|
|
||||||
{code, err} = run_err(["vault", "rescue"], [other, "brand-new-99", "brand-new-99"])
|
|
||||||
assert code == 1
|
|
||||||
assert err =~ "助記詞"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- API 錯誤分流 --
|
|
||||||
|
|
||||||
describe "api errors" do
|
|
||||||
test "401 → 3" do
|
|
||||||
FakeApi.error({:error, :unauthorized, "invalid_token"})
|
|
||||||
{code, err} = run_err(["vault", "list"])
|
|
||||||
assert code == 3
|
|
||||||
assert err =~ "重新 bear login"
|
|
||||||
end
|
|
||||||
|
|
||||||
test "403 → 8" do
|
|
||||||
FakeApi.error({:error, :forbidden, "forbidden"})
|
|
||||||
{code, err} = run_err(["vault", "list"])
|
|
||||||
assert code == 8
|
|
||||||
end
|
|
||||||
|
|
||||||
test "network → 6" do
|
|
||||||
FakeApi.error({:error, :network, "econnrefused"})
|
|
||||||
{code, err} = run_err(["vault", "list"])
|
|
||||||
assert code == 6
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# -- 非 TTY --
|
|
||||||
|
|
||||||
describe "non-tty interactive" do
|
|
||||||
test "unlock without tty → 2" do
|
|
||||||
Process.put(:fake_io_inputs, [@master_password])
|
|
||||||
FakeApi.error(nil)
|
|
||||||
|
|
||||||
{code, err} =
|
|
||||||
ExUnit.CaptureIO.with_io(:stderr, "", fn ->
|
|
||||||
CLI.dispatch(CLI.parse(["vault", "unlock"]),
|
|
||||||
vault_api: FakeApi,
|
|
||||||
io: FakeIO,
|
|
||||||
tty?: false,
|
|
||||||
email: @email
|
|
||||||
)
|
|
||||||
end)
|
|
||||||
|
|
||||||
assert code == 2
|
|
||||||
assert err =~ "互動輸入"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
Reference in New Issue
Block a user