Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
76a14686c1
|
||
|
|
3f5965bf36 |
@@ -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/
|
||||||
|
|
||||||
# 憑證與本機狀態(嚴禁進入版本庫)
|
# 憑證與本機狀態(嚴禁進入版本庫)
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
# 🐻 Bear CLI
|
# 🐻 Bear CLI
|
||||||
|
|
||||||
**Bear CLI** 是 [澳特科技](https://alterminal.com)(Alter Technology)單點登入系統 [Bear](https://gitea.alterminal.com/alterminal/bear) 的**終端機(CLI)客戶端**:讓使用者在 Linux 終端機直接以 Bear 帳號登入、查詢身分、取得並續期 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 規劃以其作為完全免瀏覽器的替代登入方式(見下文)。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 為什麼需要 CLI
|
## 為什麼需要 CLI
|
||||||
|
|
||||||
Bear 目前所有流程都依賴「瀏覽器」:登入 `/login`、儀表板 Launch、Relying Party 走 Authorization Code Flow + PKCE。但**終端機沒有瀏覽器可互動**,無法完成 `redirect_uri` 回跳,因此需要一個為「無瀏覽器/輸入受限裝置」設計的登入流程,讓 `bear` 指令也能以 OIDC 身分登入並取用 Token。
|
Bear 目前所有流程都依賴「瀏覽器」:登入 `/login`、儀表板 Launch、Relying Party 走 Authorization Code Flow + PKCE。但**終端機沒有瀏覽器可互動**,無法完成 `redirect_uri` 回跳,因此需要一個為「無瀏覽器/輸入受限裝置」設計的登入流程,讓 `bear` 指令也能以 OIDC 身分登入並取用 Token。此外,Bear 現已支援**個人存取權杖(PAT)**,CLI 亦可直接以 PAT 登入,完全免瀏覽器,適合 CI/腳本/一次性使用。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -17,7 +18,7 @@ Bear 目前所有流程都依賴「瀏覽器」:登入 `/login`、儀表板 La
|
|||||||
|
|
||||||
| 指令 | 說明 | 階段 |
|
| 指令 | 說明 | 階段 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| `bear login` | 啟動 Device Flow 登入(取得授權碼 → 兌換 Token) | P2 |
|
| `bear login` | 啟動 Device Flow 登入;或 `--token <PAT>` 以個人存取權杖登入 | P2 |
|
||||||
| `bear whoami` | 顯示目前登入身分(`GET /userinfo`) | P2 |
|
| `bear whoami` | 顯示目前登入身分(`GET /userinfo`) | P2 |
|
||||||
| `bear token [--refresh]` | 印出 access token(過期自動 refresh),供 pipe 給其他工具 | P2 |
|
| `bear token [--refresh]` | 印出 access token(過期自動 refresh),供 pipe 給其他工具 | P2 |
|
||||||
| `bear logout` | 撤銷 refresh token(`POST /revoke`) | P2 |
|
| `bear logout` | 撤銷 refresh token(`POST /revoke`) | P2 |
|
||||||
@@ -28,6 +29,33 @@ Bear 目前所有流程都依賴「瀏覽器」:登入 `/login`、儀表板 La
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 實作狀態(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` | ⏳ 待 #5 規格與 alterminal/bear#28 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)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 全域選項
|
## 全域選項
|
||||||
|
|
||||||
| 選項 | 說明 | 預設 |
|
| 選項 | 說明 | 預設 |
|
||||||
@@ -43,6 +71,8 @@ Bear 目前所有流程都依賴「瀏覽器」:登入 `/login`、儀表板 La
|
|||||||
|
|
||||||
## 登入流程(`bear login`,示意)
|
## 登入流程(`bear login`,示意)
|
||||||
|
|
||||||
|
### Device Flow(預設)
|
||||||
|
|
||||||
```
|
```
|
||||||
$ bear login
|
$ bear login
|
||||||
正在向 https://alterminal.com 註冊裝置...
|
正在向 https://alterminal.com 註冊裝置...
|
||||||
@@ -55,6 +85,15 @@ $ bear login
|
|||||||
|
|
||||||
登入後,CLI 將 refresh token 寫入本機憑證檔(0600),access token 僅做短命快取。
|
登入後,CLI 將 refresh token 寫入本機憑證檔(0600),access token 僅做短命快取。
|
||||||
|
|
||||||
|
### 個人存取權杖(PAT,免瀏覽器)
|
||||||
|
|
||||||
|
```
|
||||||
|
$ bear login --token <PAT>
|
||||||
|
已登入:alice@example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
以 PAT 登入不產生 refresh token;CLI 直接將該 PAT 寫入憑證檔(0600)作為憑證,適合 CI/腳本等無瀏覽器情境。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 憑證與設定檔
|
## 憑證與設定檔
|
||||||
@@ -62,7 +101,7 @@ $ bear login
|
|||||||
| 檔 | 路徑 | 內容 | 權限 |
|
| 檔 | 路徑 | 內容 | 權限 |
|
||||||
|----|------|------|------|
|
|----|------|------|------|
|
||||||
| 設定 | `~/.config/bear/config.json` | `issuer`、`client_id`、`scope` | 0644 |
|
| 設定 | `~/.config/bear/config.json` | `issuer`、`client_id`、`scope` | 0644 |
|
||||||
| 憑證 | `~/.local/state/bear/credentials.json` | `refresh_token`(優先)+快取的 `access_token`/`expires_at` | **0600** |
|
| 憑證 | `~/.local/state/bear/credentials.json` | Device Flow:`refresh_token`+快取 `access_token`/`expires_at`;PAT:直接存 `access_token`(無 refresh) | **0600** |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -71,7 +110,7 @@ $ bear login
|
|||||||
| 階段 | 內容 |
|
| 階段 | 內容 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| **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`/`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`(公開應用清單 API)、QR 顯示、系統 keyring、發行二進位 |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -80,4 +119,4 @@ $ bear login
|
|||||||
|
|
||||||
- **語言**:Elixir(與 Bear 主專案一致),HTTP 一律使用 `Req`。
|
- **語言**:Elixir(與 Bear 主專案一致),HTTP 一律使用 `Req`。
|
||||||
- **發行**:`mix escript`(單檔可執行)或 `mix release` 自包含二進位(待定)。
|
- **發行**:`mix escript`(單檔可執行)或 `mix release` 自包含二進位(待定)。
|
||||||
- **安全**:device_code 只存 SHA-256 雜湊、user_code 限流、憑證檔 0600、token 一律不入 log/commit。
|
- **安全**:device_code 只存 SHA-256 雜湊、user_code 限流、憑證檔 0600、token 與 PAT 一律不入 log/commit(PAT 僅在建立當下顯示一次,CLI 只「使用」不「管理」)。
|
||||||
|
|||||||
+75
-16
@@ -1,8 +1,9 @@
|
|||||||
# Bear CLI 指令規劃(Command Spec)
|
# Bear CLI 指令規劃(Command Spec)
|
||||||
|
|
||||||
> 狀態:規劃草案(對應 issue #19「創建 bear cli 倉庫」)
|
> 狀態:P2 PAT 模式 MVP 已實作(見第 9 節);Device Flow 待伺服器端 P1。
|
||||||
> 範圍:**本文件只規劃指令介面,不實作程式碼**。
|
> 範圍:本文件為指令介面規格;App 管理指令(`bear apps` CRUD)另見 #5 規劃。
|
||||||
> 登入採用的 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)。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -26,7 +27,9 @@
|
|||||||
| `-h, --help` | bool | — | 顯示說明 |
|
| `-h, --help` | bool | — | 顯示說明 |
|
||||||
| `--version` | bool | — | 顯示版本後離開 |
|
| `--version` | bool | — | 顯示版本後離開 |
|
||||||
|
|
||||||
優先序:CLI flag > 環境變數(`BEAR_ISSUER`)> 設定檔 > 內建預設。
|
優先序:CLI flag > 環境變數(`BEAR_ISSUER`、`BEAR_TOKEN`)> 設定檔 > 內建預設。
|
||||||
|
|
||||||
|
> `BEAR_TOKEN` 為一次性/CI 用的個人存取權杖(PAT);提供後優先於本機憑證檔,但不寫入憑證檔。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -34,18 +37,20 @@
|
|||||||
|
|
||||||
### 3.1 `bear login`
|
### 3.1 `bear login`
|
||||||
|
|
||||||
啟動 Device Flow 登入,取得並保存 Token。
|
登入 Bear,取得並保存憑證。預設走 **Device Flow**;亦可用 `--token` 直接以**個人存取權杖(PAT)**登入。
|
||||||
|
|
||||||
```
|
```
|
||||||
bear login [--scope "openid profile email"] [--client-id ID]
|
bear login [--scope "openid profile email"] [--client-id ID]
|
||||||
|
bear login --token <PAT>
|
||||||
```
|
```
|
||||||
|
|
||||||
| 選項 | 預設 | 說明 |
|
| 選項 | 預設 | 說明 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| `--scope` | `openid profile email` | 請求的 scope(空白分隔) |
|
| `--scope` | `openid profile email` | Device Flow 請求的 scope(空白分隔) |
|
||||||
| `--client-id` | 設定檔內值 | OIDC client id |
|
| `--client-id` | 設定檔內值 | OIDC client id |
|
||||||
|
| `--token <PAT>` | — | 直接以個人存取權杖登入(跳過 Device Flow) |
|
||||||
|
|
||||||
**行為**:
|
**行為(Device Flow,未給 `--token`)**:
|
||||||
|
|
||||||
1. 讀取設定 → 向 `{issuer}/.well-known/openid-configuration` 取 `device_authorization_endpoint`(**動態發現,不寫死網址**)。
|
1. 讀取設定 → 向 `{issuer}/.well-known/openid-configuration` 取 `device_authorization_endpoint`(**動態發現,不寫死網址**)。
|
||||||
2. `POST /device_authorization`(`client_id` + `scope`)。
|
2. `POST /device_authorization`(`client_id` + `scope`)。
|
||||||
@@ -64,7 +69,13 @@ bear login [--scope "openid profile email"] [--client-id ID]
|
|||||||
- `access_denied` → 中止並提示;
|
- `access_denied` → 中止並提示;
|
||||||
- 成功 → 寫入憑證檔(0600),印出 `已登入:<email>`。
|
- 成功 → 寫入憑證檔(0600),印出 `已登入:<email>`。
|
||||||
|
|
||||||
**退出碼**:`0` 成功;`4` 等待逾時(`expires_in`);`5` 使用者拒絕;`6` 網路/伺服器錯誤。
|
**行為(PAT,給 `--token <PAT>`)**:
|
||||||
|
|
||||||
|
1. 以該 PAT 作為 Bearer 呼叫 `GET /userinfo` 驗證可用性並取得身分。
|
||||||
|
2. 成功 → 將 PAT 直接寫入憑證檔(0600),印出 `已登入:<email>`(無 refresh token)。
|
||||||
|
3. 失敗(401/無效或已撤銷)→ 提示 PAT 無效,不寫入任何資料。
|
||||||
|
|
||||||
|
**退出碼**:`0` 成功;`3` PAT 無效或已撤銷;`4` 等待逾時(`expires_in`);`5` 使用者拒絕;`6` 網路/伺服器錯誤。
|
||||||
|
|
||||||
**`--json` 輸出範例(成功)**:
|
**`--json` 輸出範例(成功)**:
|
||||||
|
|
||||||
@@ -72,6 +83,8 @@ bear login [--scope "openid profile email"] [--client-id ID]
|
|||||||
{"ok": true, "email": "alice@example.com", "expires_in": 3600}
|
{"ok": true, "email": "alice@example.com", "expires_in": 3600}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
PAT 模式下 `expires_in` 依權杖到期日回傳;無到期日則省略該欄位。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 3.2 `bear whoami`
|
### 3.2 `bear whoami`
|
||||||
@@ -82,7 +95,7 @@ bear login [--scope "openid profile email"] [--client-id ID]
|
|||||||
bear whoami
|
bear whoami
|
||||||
```
|
```
|
||||||
|
|
||||||
**行為**:讀取快取的 access token(過期則先用 refresh token 輪轉換新),呼叫 `/userinfo`,印出 claims(name、email、picture 等)。
|
**行為**:讀取憑證——Device Flow 讀取快取的 access token(過期則先用 refresh token 輪轉換新);PAT 直接使用該 token——呼叫 `/userinfo`,印出 claims(name、email、picture 等)。`/userinfo` 同時接受 OIDC access token 與 PAT 作為 Bearer。
|
||||||
|
|
||||||
**退出碼**:`0` 成功;`3` 未登入。
|
**退出碼**:`0` 成功;`3` 未登入。
|
||||||
|
|
||||||
@@ -113,6 +126,7 @@ bear token [--refresh]
|
|||||||
|
|
||||||
- 若無 `--refresh` 且快取的 access token 未過期 → 直接印出。
|
- 若無 `--refresh` 且快取的 access token 未過期 → 直接印出。
|
||||||
- 若過期(或指定 `--refresh`)→ 以 refresh token 向 `/token` 換新,更新快取後印出。
|
- 若過期(或指定 `--refresh`)→ 以 refresh token 向 `/token` 換新,更新快取後印出。
|
||||||
|
- **PAT 模式**:直接印出該 PAT(無 refresh token;`--refresh` 為無效選項,報用法錯誤 `2`)。
|
||||||
- 輸出**只含 token 本體**(單行、無前綴),方便 pipe;診斷訊息一律走 stderr。
|
- 輸出**只含 token 本體**(單行、無前綴),方便 pipe;診斷訊息一律走 stderr。
|
||||||
|
|
||||||
**退出碼**:`0` 成功;`3` 未登入;`1` refresh 失敗(token 已撤銷或過期,需重新 login)。
|
**退出碼**:`0` 成功;`3` 未登入;`1` refresh 失敗(token 已撤銷或過期,需重新 login)。
|
||||||
@@ -127,7 +141,9 @@ bear token [--refresh]
|
|||||||
bear logout
|
bear logout
|
||||||
```
|
```
|
||||||
|
|
||||||
**行為**:呼叫 `POST /revoke`(撤銷 refresh token),無論伺服器回應如何,皆刪除本機憑證檔。
|
**行為**:
|
||||||
|
- Device Flow:呼叫 `POST /revoke`(撤銷 refresh token),無論伺服器回應如何,皆刪除本機憑證檔。
|
||||||
|
- PAT:僅刪除本機憑證檔(PAT 的撤銷需於網頁 `/profile/tokens` 進行,CLI 不提供撤銷)。
|
||||||
|
|
||||||
**退出碼**:`0` 成功;`6` 伺服器呼叫失敗(但本機憑證已清除)。
|
**退出碼**:`0` 成功;`6` 伺服器呼叫失敗(但本機憑證已清除)。
|
||||||
|
|
||||||
@@ -141,19 +157,30 @@ bear logout
|
|||||||
bear status
|
bear status
|
||||||
```
|
```
|
||||||
|
|
||||||
**行為**:讀取本機憑證,印出登入與否、access token 剩餘秒數、refresh token 是否存在。
|
**行為**:讀取本機憑證,印出登入與否、憑證類型(Device Flow/PAT)、access token 剩餘秒數、refresh token 是否存在。
|
||||||
|
|
||||||
**退出碼**:`0` 已登入;`3` 未登入。
|
**退出碼**:`0` 已登入;`3` 未登入。
|
||||||
|
|
||||||
**輸出範例**:
|
**輸出範例(Device Flow)**:
|
||||||
|
|
||||||
```
|
```
|
||||||
已登入:alice@example.com
|
已登入:alice@example.com
|
||||||
|
憑證類型:Device Flow
|
||||||
access token 剩餘:3210 秒
|
access token 剩餘:3210 秒
|
||||||
refresh token:有
|
refresh token:有
|
||||||
issuer:https://alterminal.com
|
issuer:https://alterminal.com
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**輸出範例(PAT,無到期日)**:
|
||||||
|
|
||||||
|
```
|
||||||
|
已登入:alice@example.com
|
||||||
|
憑證類型:Personal Access Token
|
||||||
|
access token 剩餘:無到期
|
||||||
|
refresh token:無
|
||||||
|
issuer:https://alterminal.com
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 3.6 `bear apps`(P3,暫緩)
|
### 3.6 `bear apps`(P3,暫緩)
|
||||||
@@ -190,9 +217,10 @@ bear apps
|
|||||||
| 檔 | 路徑 | 內容 | 權限 |
|
| 檔 | 路徑 | 內容 | 權限 |
|
||||||
|----|------|------|------|
|
|----|------|------|------|
|
||||||
| 設定 | `~/.config/bear/config.json` | `issuer`、`client_id`、`scope` | 0644 |
|
| 設定 | `~/.config/bear/config.json` | `issuer`、`client_id`、`scope` | 0644 |
|
||||||
| 憑證 | `~/.local/state/bear/credentials.json` | `refresh_token`(優先)+快取 `access_token`/`expires_at` | **0600** |
|
| 憑證 | `~/.local/state/bear/credentials.json` | Device Flow:`refresh_token`+快取 `access_token`/`expires_at`;PAT:`access_token`(無 refresh) | **0600** |
|
||||||
|
|
||||||
- **只以 refresh token 為主**:access token 短命快取,過期以 refresh token 輪轉換新(沿用 Bear 既有 refresh rotation + 重用偵測)。
|
- **Device Flow 只以 refresh token 為主**:access token 短命快取,過期以 refresh token 輪轉換新(沿用 Bear 既有 refresh rotation + 重用偵測)。
|
||||||
|
- **PAT 直接存 access token**:無 refresh token、無輪轉;效期由權杖本身的 `expires_at` 決定(可無到期日)。
|
||||||
- 寫入憑證檔務必 0600,且以 `O_CREAT|O_EXCL` 防止 symlink 攻擊。
|
- 寫入憑證檔務必 0600,且以 `O_CREAT|O_EXCL` 防止 symlink 攻擊。
|
||||||
- 未來可擴充系統 keyring(libsecret / Keychain),避免明文檔。
|
- 未來可擴充系統 keyring(libsecret / Keychain),避免明文檔。
|
||||||
|
|
||||||
@@ -213,6 +241,7 @@ bear apps
|
|||||||
2. 發行格式:escript(目標機需 Erlang)或 self-contained release(bakeware/burrito)?
|
2. 發行格式:escript(目標機需 Erlang)或 self-contained release(bakeware/burrito)?
|
||||||
3. `bear apps` 所需的「公開應用清單」API 是否納入 P3?
|
3. `bear apps` 所需的「公開應用清單」API 是否納入 P3?
|
||||||
4. 是否支援 `offline_access` scope,或沿用現行 refresh 輪轉即可?
|
4. 是否支援 `offline_access` scope,或沿用現行 refresh 輪轉即可?
|
||||||
|
5. 是否在 CLI 提供「建立/撤銷 PAT」?目前 PAT 管理僅限網頁(需 session),傾向 CLI 只「使用」不「管理」。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -221,7 +250,37 @@ bear apps
|
|||||||
| 本指令 | 對應 OIDC/Bear 端點 |
|
| 本指令 | 對應 OIDC/Bear 端點 |
|
||||||
|--------|----------------------|
|
|--------|----------------------|
|
||||||
| `login` | `/.well-known/openid-configuration` → `POST /device_authorization` → `POST /token`(device_code) |
|
| `login` | `/.well-known/openid-configuration` → `POST /device_authorization` → `POST /token`(device_code) |
|
||||||
| `whoami` | `GET /userinfo` |
|
| `login --token <PAT>` | `GET /userinfo`(Bearer PAT 驗證身分,無 OIDC 端點) |
|
||||||
| `token --refresh` | `POST /token`(refresh_token) |
|
| `whoami` | `GET /userinfo`(接受 OIDC access token 或 PAT) |
|
||||||
| `logout` | `POST /revoke` |
|
| `token --refresh` | `POST /token`(refresh_token,僅 Device Flow) |
|
||||||
|
| `logout` | `POST /revoke`(僅 Device Flow;PAT 僅本機刪除,撤銷走網頁 `/profile/tokens`) |
|
||||||
| `apps`(P3) | 待新增「公開應用清單」API |
|
| `apps`(P3) | 待新增「公開應用清單」API |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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 暫緩 | 未實作;App 管理指令規格見 #5,伺服器端 API 見 alterminal/bear#28 |
|
||||||
|
|
||||||
|
退出碼差異:`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,54 @@
|
|||||||
|
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"
|
||||||
|
end
|
||||||
@@ -0,0 +1,480 @@
|
|||||||
|
defmodule BearCli.CLI do
|
||||||
|
@moduledoc """
|
||||||
|
`bear` 指令的命令列入口與指令分派。
|
||||||
|
|
||||||
|
指令:`login`(PAT 模式)、`whoami`、`token`、`logout`、`status`。
|
||||||
|
|
||||||
|
`BEAR_TOKEN` 環境變數(一次性/CI 用的 PAT)提供時,`whoami`/`token`/`status`
|
||||||
|
優先使用該值,不讀寫本機憑證檔。
|
||||||
|
"""
|
||||||
|
|
||||||
|
alias BearCli.{Api, 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]
|
||||||
|
|
||||||
|
# -- 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(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
|
||||||
|
|
||||||
|
defp merge_opts(global, opts) do
|
||||||
|
Map.merge(Map.new(global), Map.new(opts))
|
||||||
|
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
|
||||||
|
|
||||||
|
{: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 顯示登入狀態
|
||||||
|
|
||||||
|
全域選項:
|
||||||
|
--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.9.3", "3337184d69179695c7a9f1714d92c11e629d36c8c037a21cf490131d3d150554", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 0.1.1 or ~> 0.2.0 or ~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "5f7c9342480c069dbbc4eeac3490303c9e01870ff01a7f1d29b6107054fc1e74"},
|
||||||
|
"nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"},
|
||||||
|
"nimble_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,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