Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2192d067ce
|
||
|
|
77c65ec299 | ||
|
|
8c1f580a20 | ||
|
|
34797dfe0d | ||
|
|
bd0b0da309
|
||
|
|
93176c0eb1
|
||
|
|
c26420303e | ||
|
|
ba869c3e11 |
@@ -0,0 +1,3 @@
|
|||||||
|
[
|
||||||
|
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
|
||||||
|
]
|
||||||
@@ -8,6 +8,7 @@ erl_crash.dump
|
|||||||
*.ez
|
*.ez
|
||||||
bear-*.tar
|
bear-*.tar
|
||||||
bear_cli-*.tar
|
bear_cli-*.tar
|
||||||
|
/bear
|
||||||
/tmp/
|
/tmp/
|
||||||
|
|
||||||
# 憑證與本機狀態(嚴禁進入版本庫)
|
# 憑證與本機狀態(嚴禁進入版本庫)
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
**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 帳號登入(Device Flow 或個人存取權杖)、查詢身分、取得 Token,作為 SSO 的終端入口。
|
||||||
|
|
||||||
> **狀態:規劃階段**。本倉庫目前只規劃指令介面(command spec),**尚未實作任何程式碼**。
|
> **狀態:已實作 PAT 模式 MVP(Elixir + Req,issue #6)**。`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 規劃以其作為完全免瀏覽器的替代登入方式(見下文)。
|
> Bear 已支援**個人存取權杖(Personal Access Token,PAT)**;CLI 規劃以其作為完全免瀏覽器的替代登入方式(見下文)。
|
||||||
|
|
||||||
@@ -23,12 +23,46 @@ Bear 目前所有流程都依賴「瀏覽器」:登入 `/login`、儀表板 La
|
|||||||
| `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` | 列出公開應用(需新增公開應用清單 API) | P3 |
|
| `bear apps list/show/create/update/rotate-secret/toggle` | App 管理(需 bear App 管理 JSON API,PAT 登入、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 |
|
||||||
|
|
||||||
完整指令規格(選項、行為、輸出、退出碼)見 [`docs/commands.md`](docs/commands.md)。
|
完整指令規格(選項、行為、輸出、退出碼)見 [`docs/commands.md`](docs/commands.md)。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 實作狀態(PAT 模式 MVP)
|
||||||
|
|
||||||
|
目前已實作**個人存取權杖(PAT)模式**的最小可用版本(issue #6 骨架部分):
|
||||||
|
|
||||||
|
| 指令 | 狀態 |
|
||||||
|
|------|------|
|
||||||
|
| `bear login --token <PAT>` | ✅ 已實作(PAT 模式;Device Flow 待伺服器端 P1) |
|
||||||
|
| `bear whoami` | ✅ 已實作(`GET /userinfo`,Bearer PAT;支援 `BEAR_TOKEN` 環境變數) |
|
||||||
|
| `bear token` | ✅ 已實作(印出 PAT;`--refresh` 為用法錯誤) |
|
||||||
|
| `bear logout` | ✅ 已實作(清除本機憑證;PAT 需至網頁撤銷) |
|
||||||
|
| `bear status` | ✅ 已實作(純本機判定,顯示 PAT/環境變數模式) |
|
||||||
|
| `bear apps` | ✅ 已實作(`list`/`show`/`create`/`update`/`rotate-secret`/`toggle`;issue #10,對接 alterminal/bear#28 的 `/api/v1/apps` JSON API,admin PAT 限定) |
|
||||||
|
| `bear profile`/`password`/`email`/`sessions`/`tokens`/`mfa` | ⏳ 規格已納入 `docs/commands.md` §3.7(#11);待 alterminal/bear#35 API 就緒後實作 |
|
||||||
|
|
||||||
|
### 建置與執行
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mix deps.get # 安裝依賴(Req、Jason)
|
||||||
|
mix test # 跑單元測試
|
||||||
|
mix escript.build # 產生單檔可執行 `bear`
|
||||||
|
./bear --help
|
||||||
|
./bear login --token <PAT> --issuer https://alterminal.com
|
||||||
|
```
|
||||||
|
|
||||||
|
> 發行格式目前採 `mix escript`(目標機需 Erlang);self-contained release(bakeware/burrito)仍為待定方向(見 `docs/commands.md` §7)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 全域選項
|
## 全域選項
|
||||||
|
|
||||||
| 選項 | 說明 | 預設 |
|
| 選項 | 說明 | 預設 |
|
||||||
@@ -84,7 +118,7 @@ $ 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`(Device Flow 或 `--token <PAT>`)/`whoami`/`token`/`logout`/`status`、憑證儲存 0600 |
|
||||||
| **P3 進階** | `bear apps`(公開應用清單 API)、QR 顯示、系統 keyring、發行二進位 |
|
| **P3 進階** | `bear apps` 管理指令群(依賴 bear App 管理 JSON API)、個人自助指令群 `profile`/`password`/`email`/`sessions`/`tokens`/`mfa`(依賴 bear 個人自助 JSON API,#11)、QR 顯示、系統 keyring、發行二進位 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -92,4 +126,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(PAT 僅在建立當下顯示一次,CLI 只「使用」不「管理」)。
|
- **安全**:device_code 只存 SHA-256 雜湊、user_code 限流、憑證檔 0600、token 與 PAT 一律不入 log/commit;一次性明文(`apps` 的 client_secret、`tokens create` 的 PAT、`mfa` 的 recovery codes)僅在成功當下顯示一次;密碼與驗證碼一律互動輸入、不回顧。
|
||||||
|
|||||||
+383
-10
@@ -1,7 +1,7 @@
|
|||||||
# Bear CLI 指令規劃(Command Spec)
|
# Bear CLI 指令規劃(Command Spec)
|
||||||
|
|
||||||
> 狀態:規劃草案(對應 issue #19「創建 bear cli 倉庫」)
|
> 狀態:P2 PAT 模式 MVP 已實作(見第 9 節);Device Flow 待伺服器端 P1。
|
||||||
> 範圍:**本文件只規劃指令介面,不實作程式碼**。
|
> 範圍:本文件為指令介面規格;App 管理指令(`bear apps` CRUD)另見 #5 規劃、個人自助指令(`bear profile` 等)另見 #11 規劃。
|
||||||
> 登入採用的 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)。
|
> 另支援以**個人存取權杖(PAT)**登入(bear 已於 profile 頁提供 PAT 建立/列表/撤銷,`/userinfo` 接受 PAT 作為 Bearer)。
|
||||||
|
|
||||||
@@ -183,17 +183,333 @@ issuer:https://alterminal.com
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 3.6 `bear apps`(P3,暫緩)
|
### 3.6 `bear apps`:App 管理指令群(P3,已實作)
|
||||||
|
|
||||||
列出「公開應用」清單,供 Launch/跳轉參考。
|
> 依賴:bear 伺服器端 **App 管理 JSON API**(alterminal/bear#28,資源前綴 `/api/v1/apps`,PAT Bearer 認證、管理操作限 admin)。API 已上線(PR alterminal/bear#29),本節指令群已實作(issue #10);`--visibility`/`--status` 過濾目前由 CLI 全量列舉後本地套用(伺服器 list 端點尚無對應查詢參數)。
|
||||||
|
|
||||||
|
`bear apps` 是「資源群組」指令:`bear apps <動詞>`。這是第 1 節「扁平結構」原則的首個例外——App 的管理操作(列表、檢視、建立、更新、輪轉 secret、啟停用)若攤平命名會造成指令名爆炸(`bear apps-create`…),故收斂為單一群組;未來同類資源管理指令比照。
|
||||||
|
|
||||||
```
|
```
|
||||||
bear apps
|
bear apps list [選項]
|
||||||
|
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,待確認)。
|
**認證與授權(群組共通)**:
|
||||||
|
|
||||||
**退出碼**:`0` 成功;`3` 未登入;`6` API 尚未提供。
|
- 一律使用既有 PAT 憑證(`bear login --token` 登入,或 `BEAR_TOKEN` 環境變數)作為 Bearer 呼叫 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 落地前本節僅為規格;端點細節以 #35 定案為準。
|
||||||
|
|
||||||
|
比照 `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`)。
|
||||||
|
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. 終端印出 `驗證碼已寄至 alice@example.com 與 new@example.com`,互動提示(不回顯)讀取:`現有信箱驗證碼`、`新信箱驗證碼`。
|
||||||
|
3. `POST /api/v1/profile/email`(`current_code`/`new_code`)。
|
||||||
|
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 EXPIRES
|
||||||
|
0192a1b0-… 203.0.113.10 Mozilla/5.0 (X11; Linux…) 2026-09-07 10:00:00Z 2026-09-08 09:00:00Z 2026-09-21 10:00:00Z
|
||||||
|
```
|
||||||
|
|
||||||
|
(`user_agent` 截斷至欄寬;`--json` 輸出完整值。)
|
||||||
|
- **`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 (無到期) (未使用) revoked
|
||||||
|
```
|
||||||
|
|
||||||
|
`STATUS`:`active`/`expired`/`revoked`(CLI 依 `expires_at`/`revoked_at` 本地判定)。
|
||||||
|
- **`bear tokens create --name NAME [--expires-in DAYS|never] [--scope SCOPES]`**:`POST /api/v1/profile/tokens`(Bearer PAT)。成功後一次性顯示:
|
||||||
|
|
||||||
|
```
|
||||||
|
PAT 已建立:ci-token(30 天後到期)
|
||||||
|
token(只顯示這一次,請立即保存):
|
||||||
|
9f3a…(Base64url,43 字元,無前綴)
|
||||||
|
```
|
||||||
|
|
||||||
|
| 選項 | 預設 | 說明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `--name` | (必填) | 顯示名稱;空白或重複名稱依伺服器規則 `422` → 退出碼 `1` |
|
||||||
|
| `--expires-in` | `30` | 天數(正整數)或 `never`(永不過期) |
|
||||||
|
| `--scope` | `openid profile email` | 空白分隔的 scope 清單(同伺服器預設) |
|
||||||
|
|
||||||
|
`--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 已撤銷:<name>`;若撤銷的是**目前憑證用的 PAT**,後續指令會得到 `401`(退出碼 `3`),屆時重新 `bear login`;CLI 在撤銷成功後偵測到 `id` 對應本機憑證時,主動提示執行 `bear logout` 清除本機憑證。
|
||||||
|
|
||||||
|
#### 3.7.7 `bear mfa`
|
||||||
|
|
||||||
|
TOTP 兩因子管理(WebAuthn/passkey 不在範圍)。
|
||||||
|
|
||||||
|
- **`bear mfa status`**:讀 `GET /api/v1/profile` 的 MFA 欄位,印出 `MFA(TOTP):已啟用/未啟用`。
|
||||||
|
- **`bear mfa setup`**:兩步互動流程——
|
||||||
|
1. `POST /api/v1/profile/mfa/setup`(無 code,Bearer PAT)→ 回傳 Base32 `secret` 與 `otpauth://` URI。終端印出 URI、secret,並在本機產生 ASCII QR(掃碼加入驗證器;QR 由 CLI 本地生成,不經伺服器)。
|
||||||
|
2. 互動提示(不回顯)讀取 6 位碼 → `POST /api/v1/profile/mfa/setup`(帶 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": ["…", "…"]}`(只出現這一次)。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -209,6 +525,7 @@ bear apps
|
|||||||
| `5` | 授權被拒絕(access_denied) |
|
| `5` | 授權被拒絕(access_denied) |
|
||||||
| `6` | 網路/伺服器錯誤 |
|
| `6` | 網路/伺服器錯誤 |
|
||||||
| `7` | 設定檔/憑證檔格式損毀 |
|
| `7` | 設定檔/憑證檔格式損毀 |
|
||||||
|
| `8` | 權限不足(HTTP 403;App 管理操作僅限 admin) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -231,6 +548,8 @@ bear apps
|
|||||||
- `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 客戶端慣例。
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -239,9 +558,12 @@ bear apps
|
|||||||
|
|
||||||
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` 所需的「公開應用清單」API 是否納入 P3?
|
3. `bear apps list --visibility public` 未來是否開放非 admin(僅公開/active 清單,同網頁 Launch)?目前規劃為 admin 限定。
|
||||||
4. 是否支援 `offline_access` scope,或沿用現行 refresh 輪轉即可?
|
4. 是否支援 `offline_access` scope,或沿用現行 refresh 輪轉即可?
|
||||||
5. 是否在 CLI 提供「建立/撤銷 PAT」?目前 PAT 管理僅限網頁(需 session),傾向 CLI 只「使用」不「管理」。
|
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 是否接受該欄位;不開放則 CLI 移除此選項。
|
||||||
|
8. `mfa setup` 的 `secret`/`otpauth://` 屬敏感資料,#35 的 API 回應是否應限制僅 setup 流程期間回傳(未確認前不重送)?
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -254,4 +576,55 @@ bear apps
|
|||||||
| `whoami` | `GET /userinfo`(接受 OIDC access token 或 PAT) |
|
| `whoami` | `GET /userinfo`(接受 OIDC access token 或 PAT) |
|
||||||
| `token --refresh` | `POST /token`(refresh_token,僅 Device Flow) |
|
| `token --refresh` | `POST /token`(refresh_token,僅 Device Flow) |
|
||||||
| `logout` | `POST /revoke`(僅 Device Flow;PAT 僅本機刪除,撤銷走網頁 `/profile/tokens`) |
|
| `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`(先無 code 取 secret,再帶 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)
|
||||||
|
|
||||||
|
目前實作為 **PAT 模式 MVP**(Elixir + Req、mix escript),與上方 Device Flow 規格的差異:
|
||||||
|
|
||||||
|
| 指令 | 原規格(Device Flow) | 現行實作(PAT 模式) |
|
||||||
|
|------|----------------------|----------------------|
|
||||||
|
| `login` | 裝置碼流程 | `--token <PAT>` 驗證 `GET /userinfo` 後保存(`-` 可從 stdin 讀);未給 `--token` 時提示 Device Flow 尚未開放(退出碼 2) |
|
||||||
|
| `whoami` | `GET /userinfo`(refresh 輪轉) | `GET /userinfo`(Bearer PAT,無輪轉);`BEAR_TOKEN` 提供時優先使用 |
|
||||||
|
| `token` | refresh token 輪轉換新 | 直接印出 PAT;`--refresh` 為用法錯誤(退出碼 2);`BEAR_TOKEN` 提供時優先印出 |
|
||||||
|
| `logout` | `POST /revoke`(撤銷 refresh token) | 僅清除本機憑證;PAT 需至網頁 `/profile/tokens` 撤銷 |
|
||||||
|
| `status` | 顯示 access token 剩餘秒數 | 純本機判定:顯示模式(PAT/BEAR_TOKEN 環境變數)與 issuer |
|
||||||
|
| `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 暫緩 | 未實作;個人自助指令規格見 #11(§3.7),伺服器端 API 見 alterminal/bear#35 |
|
||||||
|
|
||||||
|
退出碼差異:`login`/`whoami` 的 token 無效(401)依 §3.1 為 `3`(本節實作一致)。
|
||||||
|
|
||||||
|
憑證檔結構(PAT 模式,0600、原子寫入、O_EXCL):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"issuer": "https://alterminal.com", "access_token": "<PAT>", "email": "..."}
|
||||||
|
```
|
||||||
|
|
||||||
|
建置:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mix deps.get && mix test && mix escript.build # 產生單檔可執行 bear
|
||||||
|
```
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
defmodule BearCli do
|
||||||
|
@moduledoc """
|
||||||
|
Bear CLI — Bear SSO 的終端機客戶端。
|
||||||
|
|
||||||
|
以 Bear 個人存取權杖(Personal Access Token, PAT)在終端機登入,查詢身分
|
||||||
|
(`whoami`)、取得 Token(`token`),作為 SSO 的終端入口。Device
|
||||||
|
Authorization Grant(RFC 8628)登入待伺服器端 P1(bear 倉庫)完成後再接上。
|
||||||
|
"""
|
||||||
|
|
||||||
|
@version "0.1.0"
|
||||||
|
|
||||||
|
@doc "回傳 CLI 版本字串(與 mix.exs 的 version 同步)。"
|
||||||
|
def version, do: @version
|
||||||
|
end
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
defmodule BearCli.Api do
|
||||||
|
@moduledoc """
|
||||||
|
Bear 伺服器 HTTP 介面(一律使用 `Req`)。
|
||||||
|
|
||||||
|
目前僅實作 PAT 模式所需的 `GET /userinfo`。
|
||||||
|
"""
|
||||||
|
|
||||||
|
@finch BearCli.Finch
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
呼叫 `GET {issuer}/userinfo`(Bearer token)。
|
||||||
|
|
||||||
|
回傳:
|
||||||
|
- `{:ok, claims}` — 200,claims 為 JSON map
|
||||||
|
- `{:error, :unauthorized, description}` — 401
|
||||||
|
- `{:error, :server_error, status}` — 其他非 2xx
|
||||||
|
- `{:error, :network, reason}` — 傳輸層錯誤
|
||||||
|
"""
|
||||||
|
def userinfo(issuer, token) do
|
||||||
|
url = String.trim_trailing(issuer, "/") <> "/userinfo"
|
||||||
|
|
||||||
|
case Req.get(url,
|
||||||
|
headers: [authorization: "Bearer " <> token, accept: "application/json"],
|
||||||
|
retry: false,
|
||||||
|
finch: [name: @finch]
|
||||||
|
) do
|
||||||
|
{:ok, %Req.Response{status: 200, body: body}} ->
|
||||||
|
{:ok, decode_body(body)}
|
||||||
|
|
||||||
|
{:ok, %Req.Response{status: 401, body: body}} ->
|
||||||
|
{:error, :unauthorized, error_description(body)}
|
||||||
|
|
||||||
|
{:ok, %Req.Response{status: status}} ->
|
||||||
|
{:error, :server_error, status}
|
||||||
|
|
||||||
|
{:error, exception} ->
|
||||||
|
{:error, :network, Exception.message(exception)}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp decode_body(%{} = body), do: body
|
||||||
|
defp decode_body(body) when is_binary(body), do: Jason.decode!(body)
|
||||||
|
defp decode_body(_), do: %{}
|
||||||
|
|
||||||
|
defp error_description(body) when is_binary(body) do
|
||||||
|
case Jason.decode(body) do
|
||||||
|
{:ok, %{"error_description" => desc}} when is_binary(desc) -> desc
|
||||||
|
{:ok, %{"error" => err}} when is_binary(err) -> err
|
||||||
|
_ -> "invalid_token"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
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
|
||||||
|
apps_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
|
||||||
|
apps_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
|
||||||
|
apps_request(issuer, token, :post, "/api/v1/apps", json: attrs)
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc "`PUT /api/v1/apps/{id}`:部分更新(只送有給的欄位)。"
|
||||||
|
def apps_update(issuer, token, id, attrs) do
|
||||||
|
apps_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
|
||||||
|
apps_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
|
||||||
|
apps_request(issuer, token, :post, "/api/v1/apps/" <> URI.encode(id) <> "/toggle", json: %{})
|
||||||
|
end
|
||||||
|
|
||||||
|
# App 管理 API 共用請求。回傳:
|
||||||
|
# {:ok, body} | {:error, :unauthorized, desc} | {:error, :forbidden, desc}
|
||||||
|
# | {:error, :not_found, desc} | {:error, :unprocessable_entity, body}
|
||||||
|
# | {:error, :server_error, status} | {:error, :network, reason}
|
||||||
|
defp apps_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: status}} ->
|
||||||
|
{:error, :server_error, status}
|
||||||
|
|
||||||
|
{:error, exception} ->
|
||||||
|
{:error, :network, Exception.message(exception)}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,446 @@
|
|||||||
|
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
|
||||||
@@ -0,0 +1,682 @@
|
|||||||
|
defmodule BearCli.CLI do
|
||||||
|
@moduledoc """
|
||||||
|
`bear` 指令的命令列入口與指令分派。
|
||||||
|
|
||||||
|
指令:`login`(PAT 模式)、`whoami`、`token`、`logout`、`status`。
|
||||||
|
|
||||||
|
`BEAR_TOKEN` 環境變數(一次性/CI 用的 PAT)提供時,`whoami`/`token`/`status`
|
||||||
|
優先使用該值,不讀寫本機憑證檔。
|
||||||
|
"""
|
||||||
|
|
||||||
|
alias BearCli.{Api, Apps, Config, Credentials}
|
||||||
|
|
||||||
|
@global_switches [
|
||||||
|
issuer: :string,
|
||||||
|
config: :string,
|
||||||
|
json: :boolean,
|
||||||
|
verbose: :boolean,
|
||||||
|
help: :boolean,
|
||||||
|
version: :boolean
|
||||||
|
]
|
||||||
|
@global_aliases [v: :verbose, h: :help]
|
||||||
|
|
||||||
|
@login_switches [token: :string, scope: :string, "client-id": :string]
|
||||||
|
@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)
|
||||||
|
|
||||||
|
# -- escript 入口 --
|
||||||
|
|
||||||
|
@doc "escript 主函式。執行後以 `System.halt/1` 設定退出碼。"
|
||||||
|
def main(argv) do
|
||||||
|
start_apps()
|
||||||
|
code = argv |> parse() |> dispatch()
|
||||||
|
System.halt(code)
|
||||||
|
end
|
||||||
|
|
||||||
|
# Req 預設用 Finch 作為 HTTP adapter,escript 需自行啟動一個 pool。
|
||||||
|
defp start_apps do
|
||||||
|
_ = Application.ensure_all_started(:req)
|
||||||
|
_ = Application.ensure_all_started(:finch)
|
||||||
|
|
||||||
|
case Finch.start_link(name: BearCli.Finch) do
|
||||||
|
{:ok, _} -> :ok
|
||||||
|
{:error, _} -> :ok
|
||||||
|
end
|
||||||
|
|
||||||
|
:ok
|
||||||
|
end
|
||||||
|
|
||||||
|
# -- 解析 --
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
解析 argv,回傳:
|
||||||
|
|
||||||
|
- `{:version, opts}`
|
||||||
|
- `{:help, opts}`
|
||||||
|
- `{:ok, command, opts}`(opts 為 atom key 的 map)
|
||||||
|
- `{:error, message, exit_code}`
|
||||||
|
"""
|
||||||
|
def parse(argv) do
|
||||||
|
argv = Enum.map(argv, &to_string/1)
|
||||||
|
|
||||||
|
case OptionParser.parse_head(argv, strict: @global_switches, aliases: @global_aliases) do
|
||||||
|
{global, rest, []} ->
|
||||||
|
do_parse(global, rest)
|
||||||
|
|
||||||
|
{_global, _rest, [{opt, _} | _]} ->
|
||||||
|
{:error, "未知選項:#{opt}", 2}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp do_parse(global, rest) do
|
||||||
|
cond do
|
||||||
|
global[:version] ->
|
||||||
|
{:version, %{}}
|
||||||
|
|
||||||
|
global[:help] == true and rest == [] ->
|
||||||
|
{:help, %{}}
|
||||||
|
|
||||||
|
rest == [] ->
|
||||||
|
{:help, %{}}
|
||||||
|
|
||||||
|
true ->
|
||||||
|
[command | args] = rest
|
||||||
|
parse_command(command, args, global)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp parse_command("login", args, global) do
|
||||||
|
with {:ok, opts} <- parse_opts(args, @global_switches ++ @login_switches) do
|
||||||
|
{:ok, :login, merge_opts(global, opts)}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp parse_command("whoami", args, global) do
|
||||||
|
with {:ok, opts} <- parse_opts(args, @global_switches) do
|
||||||
|
{:ok, :whoami, merge_opts(global, opts)}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp parse_command("token", args, global) do
|
||||||
|
with {:ok, opts} <- parse_opts(args, @global_switches ++ @token_switches) do
|
||||||
|
{:ok, :token, merge_opts(global, opts)}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp parse_command("logout", args, global) do
|
||||||
|
with {:ok, opts} <- parse_opts(args, @global_switches) do
|
||||||
|
{:ok, :logout, merge_opts(global, opts)}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp parse_command("status", args, global) do
|
||||||
|
with {:ok, opts} <- parse_opts(args, @global_switches) do
|
||||||
|
{:ok, :status, merge_opts(global, opts)}
|
||||||
|
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(unknown, _args, _global) do
|
||||||
|
{:error, "未知指令:#{unknown}(可用 bear --help 查看說明)", 2}
|
||||||
|
end
|
||||||
|
|
||||||
|
defp parse_opts(args, switches) do
|
||||||
|
case OptionParser.parse(args, strict: switches) do
|
||||||
|
{opts, [], []} ->
|
||||||
|
{:ok, opts}
|
||||||
|
|
||||||
|
{_opts, extra, []} ->
|
||||||
|
{:error, "不接受的參數:#{Enum.join(extra, " ")}", 2}
|
||||||
|
|
||||||
|
{_opts, _extra, [{opt, _} | _]} ->
|
||||||
|
{:error, "無法解析選項:#{opt}", 2}
|
||||||
|
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
|
||||||
|
|
||||||
|
defp merge_opts(global, opts) do
|
||||||
|
Map.merge(Map.new(global), Map.new(opts))
|
||||||
|
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 """
|
||||||
|
執行已解析的指令,回傳退出碼。`opts[:api]` 可注入假的 userinfo 函式供測試。
|
||||||
|
"""
|
||||||
|
def dispatch(parsed, opts \\ []) do
|
||||||
|
api = opts[:api] || (&Api.userinfo/2)
|
||||||
|
|
||||||
|
case parsed do
|
||||||
|
{:version, _} ->
|
||||||
|
IO.puts(BearCli.version())
|
||||||
|
0
|
||||||
|
|
||||||
|
{:help, _} ->
|
||||||
|
print_help()
|
||||||
|
0
|
||||||
|
|
||||||
|
{:error, message, code} ->
|
||||||
|
IO.puts(:stderr, "錯誤:#{message}")
|
||||||
|
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, command, cmd_opts} ->
|
||||||
|
cond do
|
||||||
|
cmd_opts[:version] ->
|
||||||
|
IO.puts(BearCli.version())
|
||||||
|
0
|
||||||
|
|
||||||
|
cmd_opts[:help] ->
|
||||||
|
print_help()
|
||||||
|
0
|
||||||
|
|
||||||
|
true ->
|
||||||
|
run(command, cmd_opts, api)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# -- 指令實作 --
|
||||||
|
|
||||||
|
defp run(:login, opts, api) do
|
||||||
|
case opts[:token] do
|
||||||
|
nil ->
|
||||||
|
IO.puts(:stderr, "Device Flow 登入尚未開放(伺服器端 P1 未實作)。")
|
||||||
|
IO.puts(:stderr, "請改用個人存取權杖登入:bear login --token <PAT>")
|
||||||
|
2
|
||||||
|
|
||||||
|
"" ->
|
||||||
|
fail(opts, "token 不可為空", 2)
|
||||||
|
|
||||||
|
token ->
|
||||||
|
token = if token == "-", do: read_token_from_stdin(), else: token
|
||||||
|
do_login(opts, token, api)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp run(:whoami, opts, api) do
|
||||||
|
case Config.env_token() do
|
||||||
|
# BEAR_TOKEN 優先於憑證檔(不讀檔、不寫檔)。
|
||||||
|
nil ->
|
||||||
|
whoami_from_credentials(opts, api)
|
||||||
|
|
||||||
|
token ->
|
||||||
|
call_userinfo(resolve_issuer(opts), token, opts, api)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp run(:token, opts, _api) do
|
||||||
|
cond do
|
||||||
|
# BEAR_TOKEN 優先於憑證檔(一次性/CI 用,不寫入)。
|
||||||
|
token = Config.env_token() ->
|
||||||
|
IO.puts(token)
|
||||||
|
0
|
||||||
|
|
||||||
|
true ->
|
||||||
|
token_from_credentials(opts)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp run(:logout, opts, _api) do
|
||||||
|
case Credentials.delete() do
|
||||||
|
:ok ->
|
||||||
|
if opts[:json] do
|
||||||
|
IO.puts(Jason.encode!(%{ok: true}))
|
||||||
|
else
|
||||||
|
IO.puts("已登出(本機憑證已清除)。")
|
||||||
|
IO.puts("注意:PAT 本身仍在伺服器端有效,如需撤銷請至 Bear 網頁「個人存取權杖」頁面。")
|
||||||
|
end
|
||||||
|
|
||||||
|
0
|
||||||
|
|
||||||
|
{:error, reason} ->
|
||||||
|
fail(opts, "清除憑證失敗:#{inspect(reason)}", 1)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
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
|
||||||
|
{:ok, creds} ->
|
||||||
|
if opts[:json] do
|
||||||
|
IO.puts(
|
||||||
|
Jason.encode!(%{
|
||||||
|
ok: true,
|
||||||
|
logged_in: true,
|
||||||
|
email: creds["email"],
|
||||||
|
issuer: creds["issuer"],
|
||||||
|
mode: "pat"
|
||||||
|
})
|
||||||
|
)
|
||||||
|
else
|
||||||
|
IO.puts("已登入:#{creds["email"] || "(未知)"}")
|
||||||
|
IO.puts("模式:個人存取權杖(PAT)")
|
||||||
|
IO.puts("issuer:#{creds["issuer"]}")
|
||||||
|
end
|
||||||
|
|
||||||
|
0
|
||||||
|
|
||||||
|
:error ->
|
||||||
|
if opts[:json] do
|
||||||
|
IO.puts(Jason.encode!(%{ok: false, logged_in: false, error: "未登入", code: 3}))
|
||||||
|
else
|
||||||
|
IO.puts("未登入")
|
||||||
|
end
|
||||||
|
|
||||||
|
3
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# -- 指令實作輔助 --
|
||||||
|
|
||||||
|
defp do_login(opts, token, api) do
|
||||||
|
issuer = resolve_issuer(opts)
|
||||||
|
|
||||||
|
if opts[:verbose], do: IO.puts(:stderr, "issuer: #{issuer}")
|
||||||
|
|
||||||
|
case api.(issuer, token) do
|
||||||
|
{:ok, claims} ->
|
||||||
|
email = claims["email"]
|
||||||
|
creds = %{"issuer" => issuer, "access_token" => token, "email" => email}
|
||||||
|
|
||||||
|
case Credentials.save(creds) do
|
||||||
|
:ok ->
|
||||||
|
if opts[:json] do
|
||||||
|
IO.puts(Jason.encode!(%{ok: true, email: email}))
|
||||||
|
else
|
||||||
|
IO.puts("已登入:#{email || "(無 email claim)"}")
|
||||||
|
end
|
||||||
|
|
||||||
|
0
|
||||||
|
|
||||||
|
{:error, reason} ->
|
||||||
|
fail(opts, "憑證檔寫入失敗:#{inspect(reason)}", 1)
|
||||||
|
end
|
||||||
|
|
||||||
|
{:error, :unauthorized, desc} ->
|
||||||
|
# 規格 §3.1:PAT 無效或已撤銷 → 退出碼 3。
|
||||||
|
fail(opts, "PAT 無效或已撤銷(#{desc}),不寫入任何資料", 3)
|
||||||
|
|
||||||
|
{:error, :network, reason} ->
|
||||||
|
fail(opts, "無法連線到 #{issuer}:#{reason}", 6)
|
||||||
|
|
||||||
|
{:error, :server_error, status} ->
|
||||||
|
fail(opts, "伺服器回應 #{status}", 6)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# -- 輔助 --
|
||||||
|
|
||||||
|
# 優先取 --issuer flag;否則取憑證內記錄的 issuer;最後才回落 config/env/預設。
|
||||||
|
defp resolve_issuer(opts, stored_issuer \\ nil) do
|
||||||
|
opts[:issuer] || stored_issuer || Config.resolve_issuer(nil, opts[:config])
|
||||||
|
end
|
||||||
|
|
||||||
|
defp read_token_from_stdin do
|
||||||
|
IO.read(:stdio, :line) |> to_string() |> String.trim()
|
||||||
|
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
|
||||||
|
|
||||||
|
# token 指令的錯誤一律走 stderr,避免污染 stdout(pipe 的對象)。
|
||||||
|
defp fail_token(message, code) do
|
||||||
|
IO.puts(:stderr, "錯誤:#{message}")
|
||||||
|
code
|
||||||
|
end
|
||||||
|
|
||||||
|
@preferred_claims ~w(sub email name preferred_username nickname picture)
|
||||||
|
|
||||||
|
defp print_claims(claims) do
|
||||||
|
preferred =
|
||||||
|
Enum.filter(@preferred_claims, &Map.has_key?(claims, &1))
|
||||||
|
|
||||||
|
rest =
|
||||||
|
claims
|
||||||
|
|> Map.drop(@preferred_claims)
|
||||||
|
|> Enum.sort_by(fn {k, _} -> to_string(k) end)
|
||||||
|
|
||||||
|
Enum.each(preferred, fn k ->
|
||||||
|
IO.puts("#{String.pad_trailing(k, 20)}: #{format_value(claims[k])}")
|
||||||
|
end)
|
||||||
|
|
||||||
|
Enum.each(rest, fn {k, v} ->
|
||||||
|
IO.puts("#{String.pad_trailing(to_string(k), 20)}: #{format_value(v)}")
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
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) when is_boolean(v), do: to_string(v)
|
||||||
|
defp format_value(v) when is_nil(v), do: ""
|
||||||
|
defp format_value(v), do: Jason.encode!(v)
|
||||||
|
|
||||||
|
defp blank?(nil), do: true
|
||||||
|
defp blank?(""), do: true
|
||||||
|
defp blank?(_), do: false
|
||||||
|
|
||||||
|
defp print_help do
|
||||||
|
IO.puts("""
|
||||||
|
Bear CLI — Bear SSO 終端機客戶端
|
||||||
|
|
||||||
|
用法:bear <指令> [選項]
|
||||||
|
|
||||||
|
指令:
|
||||||
|
login --token <PAT> 以個人存取權杖登入(PAT 模式;Device Flow 尚未開放)
|
||||||
|
whoami 顯示目前登入身分
|
||||||
|
token [--refresh] 印出 access token(PAT 模式下 --refresh 為用法錯誤)
|
||||||
|
logout 登出(清除本機憑證)
|
||||||
|
status 顯示登入狀態
|
||||||
|
apps <動詞> App 管理(admin;bear apps --help 查看)
|
||||||
|
|
||||||
|
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>
|
||||||
|
|
||||||
|
全域選項:
|
||||||
|
--issuer URL Bear(OIDC Provider)位址(預設 https://alterminal.com)
|
||||||
|
--config PATH 設定檔路徑(預設 ~/.config/bear/config.json)
|
||||||
|
--json 機器可讀輸出(JSON)
|
||||||
|
-v, --verbose 顯示詳細日誌
|
||||||
|
-h, --help 顯示說明
|
||||||
|
--version 顯示版本
|
||||||
|
|
||||||
|
環境變數:
|
||||||
|
BEAR_TOKEN 一次性/CI 用的 PAT;提供後 whoami/token/status 優先
|
||||||
|
使用,不寫入憑證檔
|
||||||
|
""")
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
defmodule BearCli.Config do
|
||||||
|
@moduledoc """
|
||||||
|
設定檔與憑證檔的路徑及讀取。
|
||||||
|
|
||||||
|
設定優先序:CLI flag > 環境變數(`BEAR_ISSUER`)> 設定檔 > 內建預設。
|
||||||
|
"""
|
||||||
|
|
||||||
|
@default_issuer "https://alterminal.com"
|
||||||
|
|
||||||
|
@doc "內建預設 issuer。"
|
||||||
|
def default_issuer, do: @default_issuer
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
設定檔路徑:`~/.config/bear/config.json`(可用 `BEAR_CONFIG` 覆寫)。
|
||||||
|
"""
|
||||||
|
def config_path do
|
||||||
|
System.get_env("BEAR_CONFIG") || Path.join(config_home(), "config.json")
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
憑證檔路徑:`~/.local/state/bear/credentials.json`(可用 `BEAR_CREDENTIALS` 覆寫)。
|
||||||
|
"""
|
||||||
|
def credentials_path do
|
||||||
|
System.get_env("BEAR_CREDENTIALS") || Path.join(state_home(), "credentials.json")
|
||||||
|
end
|
||||||
|
|
||||||
|
defp config_home do
|
||||||
|
base =
|
||||||
|
System.get_env("XDG_CONFIG_HOME") ||
|
||||||
|
Path.join(System.user_home!(), ".config")
|
||||||
|
|
||||||
|
Path.join(base, "bear")
|
||||||
|
end
|
||||||
|
|
||||||
|
defp state_home do
|
||||||
|
base =
|
||||||
|
System.get_env("XDG_STATE_HOME") ||
|
||||||
|
Path.join(System.user_home!(), ".local/state")
|
||||||
|
|
||||||
|
Path.join(base, "bear")
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
讀取設定檔,回傳 `{:ok, map}` 或 `:error`(檔案不存在/JSON 損毀)。
|
||||||
|
"""
|
||||||
|
def read_config(path \\ config_path()) do
|
||||||
|
case File.read(path) do
|
||||||
|
{:ok, content} -> Jason.decode(content)
|
||||||
|
{:error, _} -> :error
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
解析最終 issuer,依序取第一個非空白值:
|
||||||
|
|
||||||
|
1. `cli_issuer`(`--issuer` flag)
|
||||||
|
2. `BEAR_ISSUER` 環境變數
|
||||||
|
3. 設定檔的 `issuer` 欄位(讀自 `config_path_override` 或預設路徑)
|
||||||
|
4. 內建預設 `https://alterminal.com`
|
||||||
|
"""
|
||||||
|
def resolve_issuer(cli_issuer, config_path_override \\ nil) do
|
||||||
|
path = config_path_override || config_path()
|
||||||
|
|
||||||
|
config =
|
||||||
|
case read_config(path) do
|
||||||
|
{:ok, map} when is_map(map) -> map
|
||||||
|
_ -> %{}
|
||||||
|
end
|
||||||
|
|
||||||
|
Enum.find(
|
||||||
|
[
|
||||||
|
cli_issuer,
|
||||||
|
System.get_env("BEAR_ISSUER"),
|
||||||
|
config["issuer"],
|
||||||
|
@default_issuer
|
||||||
|
],
|
||||||
|
&(not blank?(&1))
|
||||||
|
)
|
||||||
|
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?(""), do: true
|
||||||
|
defp blank?(_), do: false
|
||||||
|
end
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
defmodule BearCli.Credentials do
|
||||||
|
@moduledoc """
|
||||||
|
本機憑證檔的讀寫(0600,原子寫入、防 symlink 攻擊)。
|
||||||
|
|
||||||
|
憑證檔結構(JSON):
|
||||||
|
|
||||||
|
{"issuer": "https://alterminal.com", "access_token": "<PAT>", "email": "..."}
|
||||||
|
|
||||||
|
PAT 模式沒有 refresh token,`access_token` 即個人存取權杖本身。
|
||||||
|
"""
|
||||||
|
|
||||||
|
alias BearCli.Config
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
載入憑證,回傳 `{:ok, map}` 或 `:error`(不存在/JSON 損毀)。
|
||||||
|
"""
|
||||||
|
def load(path \\ Config.credentials_path()) do
|
||||||
|
case File.read(path) do
|
||||||
|
{:ok, content} ->
|
||||||
|
case Jason.decode(content) do
|
||||||
|
{:ok, map} when is_map(map) -> {:ok, map}
|
||||||
|
_ -> :error
|
||||||
|
end
|
||||||
|
|
||||||
|
{:error, _} ->
|
||||||
|
:error
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
寫入憑證(原子、0600)。建立父目錄(0700)。回傳 `:ok` 或 `{:error, reason}`。
|
||||||
|
"""
|
||||||
|
def save(map, path \\ Config.credentials_path()) do
|
||||||
|
json = Jason.encode!(map)
|
||||||
|
|
||||||
|
with :ok <- ensure_parent_dir(path),
|
||||||
|
{:ok, tmp} <- write_temp(path, json) do
|
||||||
|
# rename(2) 會原子地取代目標(包含取代 symlink 本身,而非其指向的檔案)。
|
||||||
|
File.rename(tmp, path)
|
||||||
|
else
|
||||||
|
{:error, _} = error -> error
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
刪除憑證檔;檔案不存在也算成功。
|
||||||
|
"""
|
||||||
|
def delete(path \\ Config.credentials_path()) do
|
||||||
|
case File.rm(path) do
|
||||||
|
:ok -> :ok
|
||||||
|
{:error, :enoent} -> :ok
|
||||||
|
{:error, reason} -> {:error, reason}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp ensure_parent_dir(path) do
|
||||||
|
dir = Path.dirname(path)
|
||||||
|
File.mkdir_p(dir)
|
||||||
|
|
||||||
|
# 目錄權限 0700 為 best-effort(例如憑證路徑落在 /tmp 等共享目錄時無法 chmod,
|
||||||
|
# 忽略即可;真正的保護是憑證檔本身的 0600)。
|
||||||
|
_ = File.chmod(dir, 0o700)
|
||||||
|
:ok
|
||||||
|
end
|
||||||
|
|
||||||
|
defp write_temp(path, json) do
|
||||||
|
dir = Path.dirname(path)
|
||||||
|
tmp = Path.join(dir, ".credentials.#{System.unique_integer([:positive])}.tmp")
|
||||||
|
|
||||||
|
result =
|
||||||
|
with {:ok, io} <- File.open(tmp, [:write, :exclusive, :binary]),
|
||||||
|
:ok <- IO.binwrite(io, json),
|
||||||
|
:ok <- File.close(io),
|
||||||
|
:ok <- File.chmod(tmp, 0o600) do
|
||||||
|
{:ok, tmp}
|
||||||
|
end
|
||||||
|
|
||||||
|
case result do
|
||||||
|
{:ok, _} = ok ->
|
||||||
|
ok
|
||||||
|
|
||||||
|
{:error, _} = error ->
|
||||||
|
_ = File.rm(tmp)
|
||||||
|
error
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
defmodule BearCli.MixProject do
|
||||||
|
use Mix.Project
|
||||||
|
|
||||||
|
def project do
|
||||||
|
[
|
||||||
|
app: :bear_cli,
|
||||||
|
version: "0.1.0",
|
||||||
|
elixir: "~> 1.17",
|
||||||
|
start_permanent: Mix.env() == :prod,
|
||||||
|
deps: deps(),
|
||||||
|
escript: escript(),
|
||||||
|
aliases: aliases()
|
||||||
|
]
|
||||||
|
end
|
||||||
|
|
||||||
|
def application do
|
||||||
|
[
|
||||||
|
extra_applications: [:logger]
|
||||||
|
]
|
||||||
|
end
|
||||||
|
|
||||||
|
def cli do
|
||||||
|
[
|
||||||
|
preferred_envs: [precommit: :test]
|
||||||
|
]
|
||||||
|
end
|
||||||
|
|
||||||
|
# escript 打包:單檔可執行,主模組為 BearCli.CLI。
|
||||||
|
defp escript do
|
||||||
|
[
|
||||||
|
main_module: BearCli.CLI,
|
||||||
|
name: "bear"
|
||||||
|
]
|
||||||
|
end
|
||||||
|
|
||||||
|
defp deps do
|
||||||
|
[
|
||||||
|
# HTTP 一律使用 Req(與 bear 主專案一致)。
|
||||||
|
{:req, "~> 0.5"},
|
||||||
|
{:jason, "~> 1.2"}
|
||||||
|
]
|
||||||
|
end
|
||||||
|
|
||||||
|
defp aliases do
|
||||||
|
[
|
||||||
|
precommit: ["compile --warnings-as-errors", "format", "test"]
|
||||||
|
]
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
%{
|
||||||
|
"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"},
|
||||||
|
"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"},
|
||||||
|
"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"},
|
||||||
|
"nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"},
|
||||||
|
"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"},
|
||||||
|
"telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"},
|
||||||
|
}
|
||||||
@@ -0,0 +1,517 @@
|
|||||||
|
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
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
defmodule BearCli.CLITest do
|
||||||
|
use ExUnit.Case, async: false
|
||||||
|
|
||||||
|
alias BearCli.CLI
|
||||||
|
|
||||||
|
setup do
|
||||||
|
old_creds = System.get_env("BEAR_CREDENTIALS")
|
||||||
|
|
||||||
|
on_exit(fn ->
|
||||||
|
restore_env("BEAR_CREDENTIALS", old_creds)
|
||||||
|
end)
|
||||||
|
|
||||||
|
:ok
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "parse/1" do
|
||||||
|
test "no args -> help" do
|
||||||
|
assert {:help, %{}} = CLI.parse([])
|
||||||
|
end
|
||||||
|
|
||||||
|
test "--version" do
|
||||||
|
assert {:version, %{}} = CLI.parse(["--version"])
|
||||||
|
end
|
||||||
|
|
||||||
|
test "-h alias -> help" do
|
||||||
|
assert {:help, %{}} = CLI.parse(["-h"])
|
||||||
|
end
|
||||||
|
|
||||||
|
test "login --token X" do
|
||||||
|
assert {:ok, :login, %{token: "X"}} = CLI.parse(["login", "--token", "X"])
|
||||||
|
end
|
||||||
|
|
||||||
|
test "global option before command" do
|
||||||
|
assert {:ok, :whoami, %{json: true}} = CLI.parse(["--json", "whoami"])
|
||||||
|
end
|
||||||
|
|
||||||
|
test "global option after command" do
|
||||||
|
assert {:ok, :status, %{json: true}} = CLI.parse(["status", "--json"])
|
||||||
|
end
|
||||||
|
|
||||||
|
test "token --refresh" do
|
||||||
|
assert {:ok, :token, %{refresh: true}} = CLI.parse(["token", "--refresh"])
|
||||||
|
end
|
||||||
|
|
||||||
|
test "issuer flag is captured" do
|
||||||
|
assert {:ok, :whoami, %{issuer: "https://x"}} =
|
||||||
|
CLI.parse(["whoami", "--issuer", "https://x"])
|
||||||
|
end
|
||||||
|
|
||||||
|
test "unknown command -> usage error" do
|
||||||
|
assert {:error, _, 2} = CLI.parse(["frobnicate"])
|
||||||
|
end
|
||||||
|
|
||||||
|
test "unknown option -> usage error" do
|
||||||
|
assert {:error, _, 2} = CLI.parse(["--bogus"])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "dispatch/2 (injected api)" do
|
||||||
|
test "login --token writes credentials and prints email" do
|
||||||
|
path = tmp_path()
|
||||||
|
on_exit(fn -> File.rm(path) end)
|
||||||
|
System.put_env("BEAR_CREDENTIALS", path)
|
||||||
|
|
||||||
|
{code, out} =
|
||||||
|
ExUnit.CaptureIO.with_io(fn ->
|
||||||
|
CLI.dispatch(CLI.parse(["login", "--token", "good"]), api: fake_api())
|
||||||
|
end)
|
||||||
|
|
||||||
|
assert code == 0
|
||||||
|
assert out =~ "已登入:alice@example.com"
|
||||||
|
assert {:ok, %{"access_token" => "good"}} = BearCli.Credentials.load(path)
|
||||||
|
end
|
||||||
|
|
||||||
|
test "login with invalid token exits 3" do
|
||||||
|
System.put_env("BEAR_CREDENTIALS", tmp_path())
|
||||||
|
|
||||||
|
{code, err} =
|
||||||
|
ExUnit.CaptureIO.with_io(
|
||||||
|
:stderr,
|
||||||
|
"",
|
||||||
|
fn -> CLI.dispatch(CLI.parse(["login", "--token", "bad"]), api: fake_api()) end
|
||||||
|
)
|
||||||
|
|
||||||
|
assert code == 3
|
||||||
|
assert err =~ "PAT 無效"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "login without --token points to Device Flow being unavailable" do
|
||||||
|
System.put_env("BEAR_CREDENTIALS", tmp_path())
|
||||||
|
|
||||||
|
{code, err} =
|
||||||
|
ExUnit.CaptureIO.with_io(
|
||||||
|
:stderr,
|
||||||
|
"",
|
||||||
|
fn -> CLI.dispatch(CLI.parse(["login"]), api: fake_api()) end
|
||||||
|
)
|
||||||
|
|
||||||
|
assert code == 2
|
||||||
|
assert err =~ "Device Flow"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "whoami when not logged in exits 3" do
|
||||||
|
System.put_env("BEAR_CREDENTIALS", "/nonexistent/credentials.json")
|
||||||
|
|
||||||
|
{code, err} =
|
||||||
|
ExUnit.CaptureIO.with_io(
|
||||||
|
:stderr,
|
||||||
|
"",
|
||||||
|
fn -> CLI.dispatch(CLI.parse(["whoami"]), api: fake_api()) end
|
||||||
|
)
|
||||||
|
|
||||||
|
assert code == 3
|
||||||
|
assert err =~ "未登入"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "whoami prints claims" 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"}, path)
|
||||||
|
|
||||||
|
{code, out} =
|
||||||
|
ExUnit.CaptureIO.with_io(fn ->
|
||||||
|
CLI.dispatch(CLI.parse(["whoami"]), api: fake_api())
|
||||||
|
end)
|
||||||
|
|
||||||
|
assert code == 0
|
||||||
|
assert out =~ "email"
|
||||||
|
assert out =~ "alice@example.com"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "token prints only the token" 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, out} =
|
||||||
|
ExUnit.CaptureIO.with_io(fn ->
|
||||||
|
CLI.dispatch(CLI.parse(["token"]), api: fake_api())
|
||||||
|
end)
|
||||||
|
|
||||||
|
assert code == 0
|
||||||
|
assert String.trim(out) == "good-token"
|
||||||
|
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
|
||||||
|
path = tmp_path()
|
||||||
|
on_exit(fn -> File.rm(path) end)
|
||||||
|
System.put_env("BEAR_CREDENTIALS", path)
|
||||||
|
|
||||||
|
BearCli.Credentials.save(
|
||||||
|
%{"issuer" => "https://x", "email" => "a@b.c", "access_token" => "t"},
|
||||||
|
path
|
||||||
|
)
|
||||||
|
|
||||||
|
{code, out} =
|
||||||
|
ExUnit.CaptureIO.with_io(fn ->
|
||||||
|
CLI.dispatch(CLI.parse(["status"]), api: fake_api())
|
||||||
|
end)
|
||||||
|
|
||||||
|
assert code == 0
|
||||||
|
assert out =~ "已登入:a@b.c"
|
||||||
|
assert out =~ "PAT"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "logout clears credentials" 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" => "t"}, path)
|
||||||
|
|
||||||
|
{code, _out} =
|
||||||
|
ExUnit.CaptureIO.with_io(fn ->
|
||||||
|
CLI.dispatch(CLI.parse(["logout"]), api: fake_api())
|
||||||
|
end)
|
||||||
|
|
||||||
|
assert code == 0
|
||||||
|
assert :error == BearCli.Credentials.load(path)
|
||||||
|
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
|
||||||
|
fn _issuer, token ->
|
||||||
|
case token do
|
||||||
|
"good" -> {:ok, %{"sub" => "u1", "email" => "alice@example.com", "name" => "Alice"}}
|
||||||
|
"bad" -> {:error, :unauthorized, "invalid_token"}
|
||||||
|
_ -> {:error, :server_error, 500}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp tmp_path do
|
||||||
|
Path.join(System.tmp_dir!(), "bear_cli_cli_#{System.unique_integer([:positive])}.json")
|
||||||
|
end
|
||||||
|
|
||||||
|
defp restore_env(key, nil), do: System.delete_env(key)
|
||||||
|
defp restore_env(key, value), do: System.put_env(key, value)
|
||||||
|
end
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
defmodule BearCli.ConfigTest do
|
||||||
|
use ExUnit.Case, async: false
|
||||||
|
|
||||||
|
alias BearCli.Config
|
||||||
|
|
||||||
|
@nonexistent "/nonexistent/bear_cli_config.json"
|
||||||
|
|
||||||
|
setup do
|
||||||
|
old_issuer = System.get_env("BEAR_ISSUER")
|
||||||
|
old_config = System.get_env("BEAR_CONFIG")
|
||||||
|
|
||||||
|
on_exit(fn ->
|
||||||
|
restore_env("BEAR_ISSUER", old_issuer)
|
||||||
|
restore_env("BEAR_CONFIG", old_config)
|
||||||
|
end)
|
||||||
|
|
||||||
|
System.delete_env("BEAR_ISSUER")
|
||||||
|
System.put_env("BEAR_CONFIG", @nonexistent)
|
||||||
|
|
||||||
|
:ok
|
||||||
|
end
|
||||||
|
|
||||||
|
test "defaults to the built-in issuer when nothing else is set" do
|
||||||
|
assert Config.resolve_issuer(nil) == "https://alterminal.com"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "CLI flag takes precedence over everything" do
|
||||||
|
System.put_env("BEAR_ISSUER", "https://env.example.com")
|
||||||
|
assert Config.resolve_issuer("https://flag.example.com") == "https://flag.example.com"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "BEAR_ISSUER env wins over config and default" do
|
||||||
|
System.put_env("BEAR_ISSUER", "https://env.example.com")
|
||||||
|
assert Config.resolve_issuer(nil) == "https://env.example.com"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "config file issuer wins over default" do
|
||||||
|
path = write_config(%{"issuer" => "https://config.example.com"})
|
||||||
|
|
||||||
|
on_exit(fn -> File.rm(path) end)
|
||||||
|
|
||||||
|
assert Config.resolve_issuer(nil, path) == "https://config.example.com"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "config path override is honored" do
|
||||||
|
path = write_config(%{"issuer" => "https://override.example.com"})
|
||||||
|
|
||||||
|
on_exit(fn -> File.rm(path) end)
|
||||||
|
|
||||||
|
assert Config.resolve_issuer(nil, path) == "https://override.example.com"
|
||||||
|
end
|
||||||
|
|
||||||
|
defp write_config(map) do
|
||||||
|
path =
|
||||||
|
Path.join(System.tmp_dir!(), "bear_cli_config_#{System.unique_integer([:positive])}.json")
|
||||||
|
|
||||||
|
File.write!(path, Jason.encode!(map))
|
||||||
|
path
|
||||||
|
end
|
||||||
|
|
||||||
|
defp restore_env(key, nil), do: System.delete_env(key)
|
||||||
|
defp restore_env(key, value), do: System.put_env(key, value)
|
||||||
|
end
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
defmodule BearCli.CredentialsTest do
|
||||||
|
use ExUnit.Case, async: true
|
||||||
|
|
||||||
|
alias BearCli.Credentials
|
||||||
|
|
||||||
|
test "save/load round-trips JSON" do
|
||||||
|
path = tmp_path()
|
||||||
|
on_exit(fn -> File.rm(path) end)
|
||||||
|
|
||||||
|
assert :ok ==
|
||||||
|
Credentials.save(
|
||||||
|
%{"issuer" => "x", "access_token" => "tok", "email" => "a@b.c"},
|
||||||
|
path
|
||||||
|
)
|
||||||
|
|
||||||
|
assert {:ok, %{"access_token" => "tok", "email" => "a@b.c"}} = Credentials.load(path)
|
||||||
|
end
|
||||||
|
|
||||||
|
test "save creates the file with 0600 permissions" do
|
||||||
|
path = tmp_path()
|
||||||
|
on_exit(fn -> File.rm(path) end)
|
||||||
|
:ok = Credentials.save(%{"access_token" => "tok"}, path)
|
||||||
|
|
||||||
|
mode = File.stat!(path).mode
|
||||||
|
assert Bitwise.band(mode, 0o777) == 0o600
|
||||||
|
end
|
||||||
|
|
||||||
|
test "save creates the parent directory" do
|
||||||
|
base = Path.join(System.tmp_dir!(), "bear_cli_nested_#{System.unique_integer([:positive])}")
|
||||||
|
path = Path.join([base, "sub", "credentials.json"])
|
||||||
|
on_exit(fn -> File.rm_rf(base) end)
|
||||||
|
|
||||||
|
:ok = Credentials.save(%{"a" => "b"}, path)
|
||||||
|
assert File.regular?(path)
|
||||||
|
end
|
||||||
|
|
||||||
|
test "load returns :error for a missing file" do
|
||||||
|
assert :error == Credentials.load("/nonexistent/credentials.json")
|
||||||
|
end
|
||||||
|
|
||||||
|
test "load returns :error for corrupt JSON" do
|
||||||
|
path = tmp_path()
|
||||||
|
on_exit(fn -> File.rm(path) end)
|
||||||
|
File.write!(path, "{not json")
|
||||||
|
|
||||||
|
assert :error == Credentials.load(path)
|
||||||
|
end
|
||||||
|
|
||||||
|
test "delete removes the file and is idempotent" do
|
||||||
|
path = tmp_path()
|
||||||
|
on_exit(fn -> File.rm(path) end)
|
||||||
|
:ok = Credentials.save(%{"a" => "b"}, path)
|
||||||
|
|
||||||
|
assert :ok == Credentials.delete(path)
|
||||||
|
assert :error == Credentials.load(path)
|
||||||
|
assert :ok == Credentials.delete(path)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp tmp_path do
|
||||||
|
Path.join(System.tmp_dir!(), "bear_cli_creds_#{System.unique_integer([:positive])}.json")
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ExUnit.start()
|
||||||
Reference in New Issue
Block a user