feat: 實作個人自助指令群(issue #11) #15
@@ -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 的終端入口。
|
||||
|
||||
> **狀態:已實作 PAT 模式 MVP(Elixir + Req,issue #6)**。`login --token <PAT>`、`whoami`、`token`、`logout`、`status` 已可用;Device Authorization Grant(RFC 8628)登入待伺服器端 P1(bear 倉庫)完成後再接。
|
||||
> **狀態:已實作 PAT 模式 MVP(Elixir + Req,issue #6)+ App 管理(#10)+ 個人自助指令群(#11)**。`login --token <PAT>`、`whoami`、`token`、`logout`、`status`、`apps`、`profile`/`password`/`email`/`sessions`/`tokens`/`mfa` 已可用;Device Authorization Grant(RFC 8628)登入待伺服器端 P1(bear 倉庫)完成後再接。
|
||||
> 伺服器端採用的 OIDC **Device Authorization Grant(RFC 8628)** 方向,詳見 bear 倉庫的設計文件 `docs/cli-feature-plan.md`(issue #17)。
|
||||
> Bear 已支援**個人存取權杖(Personal Access Token,PAT)**;CLI 規劃以其作為完全免瀏覽器的替代登入方式(見下文)。
|
||||
|
||||
@@ -23,13 +23,13 @@ Bear 目前所有流程都依賴「瀏覽器」:登入 `/login`、儀表板 La
|
||||
| `bear token [--refresh]` | 印出 access token(過期自動 refresh),供 pipe 給其他工具 | P2 |
|
||||
| `bear logout` | 撤銷 refresh token(`POST /revoke`) | P2 |
|
||||
| `bear status` | 顯示登入狀態與 token 剩餘效期 | P2 |
|
||||
| `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 |
|
||||
| `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)。
|
||||
|
||||
@@ -47,7 +47,7 @@ Bear 目前所有流程都依賴「瀏覽器」:登入 `/login`、儀表板 La
|
||||
| `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 就緒後實作 |
|
||||
| `bear profile`/`password`/`email`/`sessions`/`tokens`/`mfa` | ✅ 已實作(issue #11,對接 alterminal/bear#38 的 `/api/v1/profile*` JSON API,任何有效 PAT 皆可):`profile show/set`、`password change`、`email change --new`、`sessions list/revoke/revoke-others`、`tokens list/create/revoke`、`mfa status/setup/disable/recovery-codes`。規格見 `docs/commands.md` §3.7 |
|
||||
|
||||
### 建置與執行
|
||||
|
||||
|
||||
+19
-20
@@ -338,9 +338,9 @@ bear apps update <client-id> [--url URL] [--title TITLE]
|
||||
|
||||
---
|
||||
|
||||
### 3.7 `bear profile`:個人自助指令群(P3,規劃中)
|
||||
### 3.7 `bear profile`:個人自助指令群(P3,已實作)
|
||||
|
||||
> 依賴:bear 伺服器端**個人自助 JSON API**(alterminal/bear#35,資源前綴 `/api/v1/profile`,PAT Bearer 認證、**任何有效 PAT 帳號**可用,不限 admin)。API 落地前本節僅為規格;端點細節以 #35 定案為準。
|
||||
> 依賴:bear 伺服器端**個人自助 JSON API**(alterminal/bear#35,資源前綴 `/api/v1/profile`,PAT Bearer 認證、**任何有效 PAT 帳號**可用,不限 admin)。API 已上線(PR alterminal/bear#38),本節指令群已實作(issue #11);端點細節以 #38 實作為準。
|
||||
|
||||
比照 `bear apps` 的「資源群組」例外:個人自助操作若攤平命名同樣會造成指令名爆炸(`bear password-change`…),收斂為 `bear <資源> <動詞>` 的六個子群組。頭像(picture)檔案上傳需要 multipart 與本機圖片,終端體驗差,**不在本期範圍**(#35 有對應端點,未來有需要再評估);如需更換頭像,可自行上傳圖片後以 `profile set --picture URL` 設定。
|
||||
|
||||
@@ -421,7 +421,7 @@ bear profile set [--name NAME] [--given-name NAME] [--family-name NAME]
|
||||
|
||||
1. 互動提示(不回顯)依序讀取:`目前密碼`、`新密碼`、`確認新密碼`。
|
||||
2. 兩次新密碼不一致 → 退出碼 `2`(本地檢查),不發請求。
|
||||
3. `POST /api/v1/profile/password`(Bearer PAT,body 帶 `current_password`/`new_password`)。
|
||||
3. `POST /api/v1/profile/password`(Bearer PAT,body 帶 `current_password`/`new_password`/`password_confirmation`;CLI 以兩次輸入一致的新密碼填 `password_confirmation`)。
|
||||
4. 成功 → 印出 `密碼已變更`;現行密碼錯誤 → 退出碼 `1`;新密碼不符伺服器強度規則 → `422`,退出碼 `1`。
|
||||
|
||||
比照網頁流程,變更密碼**不**自動撤銷其他 session;需要時另用 `bear sessions revoke-others`。
|
||||
@@ -437,8 +437,8 @@ bear profile set [--name NAME] [--given-name NAME] [--family-name NAME]
|
||||
**行為**:
|
||||
|
||||
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`)。
|
||||
2. 終端印出 `驗證碼已寄至現有信箱與 <new>`,互動提示(不回顧)讀取:`現有信箱驗證碼`、`新信箱驗證碼`。
|
||||
3. `POST /api/v1/profile/email`(`new_email`/`current_code`/`new_code`;API 版需再帶一次 `new_email`,CLI 自動帶入)。
|
||||
4. 成功 → 印出 `email 已更新:new@example.com`,並提醒 `bear login` 用的 PAT 不受影響(PAT 不綁 email)。
|
||||
|
||||
錯誤:`same_email`/`email_taken`/`invalid_email` → 退出碼 `1`;驗證碼錯誤或逾期 → 退出碼 `1`,提示重新執行(會重寄驗證碼);伺服器限流(`429`)→ 退出碼 `1`,提示稍後再試。
|
||||
@@ -452,11 +452,11 @@ bear profile set [--name NAME] [--given-name NAME] [--family-name NAME]
|
||||
- **`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
|
||||
ID IP USER AGENT CREATED LAST SEEN
|
||||
0192a1b0-… 203.0.113.10 Mozilla/5.0 (X11; Linux…) 2026-09-07 10:00:00Z 2026-09-08 09:00:00Z
|
||||
```
|
||||
|
||||
(`user_agent` 截斷至欄寬;`--json` 輸出完整值。)
|
||||
(`user_agent` 截斷至欄寬;`--json` 輸出完整值。API 回應欄位為 `id`/`ip`/`user_agent`/`created_at`/`last_seen_at`,不含 `expires_at`。)
|
||||
- **`bear sessions revoke <id>`**:`POST /api/v1/profile/sessions/{id}/revoke`。成功印出 `session 已撤銷`;不存在或非本人 → `404`,退出碼 `1`。
|
||||
- **`bear sessions revoke-others`**:`POST /api/v1/profile/sessions/revoke-others`。成功印出 `已撤銷 N 個其他 session`。
|
||||
|
||||
@@ -473,11 +473,11 @@ ID IP USER AGENT
|
||||
```
|
||||
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
|
||||
0192a1b0-… old-laptop openid, profile 2026-08-01 00:00:00Z (無到期) (未使用) expired
|
||||
```
|
||||
|
||||
`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)。成功後一次性顯示:
|
||||
`STATUS`:`active`/`expired`(CLI 依 `expires_at` 本地判定)。API 的 list 端點只回**未撤銷**的 token,故 `revoked` 不會出現在清單。
|
||||
- **`bear tokens create --name NAME [--expires-in DAYS|never]`**:`POST /api/v1/profile/tokens`(Bearer PAT,body `name`/`expires_in`;scope 由伺服器給預設 `openid profile email`,API 不接受指定)。成功後一次性顯示:
|
||||
|
||||
```
|
||||
PAT 已建立:ci-token(30 天後到期)
|
||||
@@ -489,20 +489,19 @@ token(只顯示這一次,請立即保存):
|
||||
|------|------|------|
|
||||
| `--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` 清除本機憑證。
|
||||
- **`bear tokens revoke <id>`**:`POST /api/v1/profile/tokens/{id}/revoke`(`<id>` 為 UUID)。成功印出 `PAT 已撤銷`;若撤銷的是**目前憑證用的 PAT**,後續指令會得到 `401`(退出碼 `3`),屆時重新 `bear login`(本機憑證檔未存 token id,CLI 無法預先比對,僅能提示此退路)。
|
||||
|
||||
#### 3.7.7 `bear mfa`
|
||||
|
||||
TOTP 兩因子管理(WebAuthn/passkey 不在範圍)。
|
||||
|
||||
- **`bear mfa status`**:讀 `GET /api/v1/profile` 的 MFA 欄位,印出 `MFA(TOTP):已啟用/未啟用`。
|
||||
- **`bear mfa status`**:讀 `GET /api/v1/profile` 的 `mfa_enabled` 欄位,印出 `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)確認。
|
||||
1. `POST /api/v1/profile/mfa/setup`(無 body,Bearer PAT)→ 回傳 Base32 `secret` 與 `otpauth://` URI。終端印出 URI、secret,並在本機產生 ASCII QR(掃碼加入驗證器;QR 由 CLI 本地生成,不經伺服器;`--json` 模式此步資訊走 stderr,stdout 留給最終結果)。
|
||||
2. 互動提示(不回顧)讀取 6 位碼 → `POST /api/v1/profile/mfa/setup/confirm`(`code`)確認。
|
||||
3. 成功 → **一次性**顯示 recovery codes(提示同 PAT:只顯示這一次)。
|
||||
|
||||
已啟用 MFA 再執行 → 退出碼 `1`,提示已啟用。驗證碼錯誤 → 退出碼 `1`,可重試(不重產 secret)。
|
||||
@@ -562,8 +561,8 @@ TOTP 兩因子管理(WebAuthn/passkey 不在範圍)。
|
||||
4. 是否支援 `offline_access` scope,或沿用現行 refresh 輪轉即可?
|
||||
5. 是否在 CLI 提供「建立/撤銷 PAT」?原規劃傾向 CLI 只「使用」不「管理」;#35 的 PAT 端點落地後,`bear tokens` 已納入 §3.7.6 規格(管理自己帳號的 PAT),此題視為已解。
|
||||
6. App 管理 API 的路徑參數最終採 UUID 或 `client_id`(alterminal/bear#28 規格為 `{id}`)?若為 UUID,CLI 需先以 list 解析 `client_id` → UUID,或伺服器提供以 `client_id` 直取的端點。
|
||||
7. `bear profile set --phone-verified`(自我標記電話已驗證)是否開放?#35 需決定 API 是否接受該欄位;不開放則 CLI 移除此選項。
|
||||
8. `mfa setup` 的 `secret`/`otpauth://` 屬敏感資料,#35 的 API 回應是否應限制僅 setup 流程期間回傳(未確認前不重送)?
|
||||
7. `bear profile set --phone-verified`(自我標記電話已驗證)是否開放?#35 已定案:API 接受該欄位(`profile_changeset` 的 `profile_fields` 含 `phone_number_verified`),CLI 保留 `--phone-verified` 旗標(僅設定,清除不在本期)。
|
||||
8. `mfa setup` 的 `secret`/`otpauth://` 屬敏感資料,#35 的 API 回應是否應限制僅 setup 流程期間回傳(未確認前不重送)?#38 實作為 setup 回應一次性回傳,未確認前重呼 setup 會重產 secret;CLI 依此實作(第二步走 `/mfa/setup/confirm`)。
|
||||
|
||||
---
|
||||
|
||||
@@ -593,7 +592,7 @@ TOTP 兩因子管理(WebAuthn/passkey 不在範圍)。
|
||||
| `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 setup` | `POST /api/v1/profile/mfa/setup`(取 secret)→ `POST /api/v1/profile/mfa/setup/confirm`(帶 code 確認) |
|
||||
| `mfa disable` | `POST /api/v1/profile/mfa/disable` |
|
||||
| `mfa recovery-codes` | `POST /api/v1/profile/mfa/recovery-codes` |
|
||||
|
||||
@@ -613,7 +612,7 @@ TOTP 兩因子管理(WebAuthn/passkey 不在範圍)。
|
||||
| `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 |
|
||||
| `profile`/`password`/`email`/`sessions`/`tokens`/`mfa` | P3 暫緩 | ✅ 已實作(issue #11):`profile show/set`、`password change`、`email change`、`sessions list/revoke/revoke-others`、`tokens list/create/revoke`、`mfa status/setup/disable/recovery-codes`,對接 alterminal/bear#38 的 `/api/v1/profile*` JSON API(PAT Bearer、任何有效帳號)。敏感輸入互動提示;一次性明文(PAT 明文、recovery codes)僅於成功當下輸出;mfa setup 的 ASCII QR 由本機 eqrcode 生成 |
|
||||
|
||||
退出碼差異:`login`/`whoami` 的 token 無效(401)依 §3.1 為 `3`(本節實作一致)。
|
||||
|
||||
|
||||
+138
-9
@@ -2,7 +2,10 @@ defmodule BearCli.Api do
|
||||
@moduledoc """
|
||||
Bear 伺服器 HTTP 介面(一律使用 `Req`)。
|
||||
|
||||
目前僅實作 PAT 模式所需的 `GET /userinfo`。
|
||||
- `GET /userinfo`:PAT 模式身分驗證(issue #6)。
|
||||
- App 管理 API `/api/v1/apps`(alterminal/bear#28;PAT Bearer、admin 限定)。
|
||||
- 個人自助 API `/api/v1/profile*`(alterminal/bear#35;PAT Bearer、
|
||||
任何有效帳號):profile/密碼/email/sessions/PAT/MFA。
|
||||
"""
|
||||
|
||||
@finch BearCli.Finch
|
||||
@@ -61,12 +64,12 @@ defmodule BearCli.Api do
|
||||
成功回 `{: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)
|
||||
api_request(issuer, token, :get, "/api/v1/apps", params: params)
|
||||
end
|
||||
|
||||
@doc "`GET /api/v1/apps/{id}`:單一 App(`client_secret` 永不回傳)。"
|
||||
def apps_get(issuer, token, id) do
|
||||
apps_request(issuer, token, :get, "/api/v1/apps/" <> URI.encode(id))
|
||||
api_request(issuer, token, :get, "/api/v1/apps/" <> URI.encode(id))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -75,12 +78,12 @@ defmodule BearCli.Api do
|
||||
(`%{"data" => app, "client_secret" => secret}`)。
|
||||
"""
|
||||
def apps_create(issuer, token, attrs) do
|
||||
apps_request(issuer, token, :post, "/api/v1/apps", json: attrs)
|
||||
api_request(issuer, token, :post, "/api/v1/apps", json: attrs)
|
||||
end
|
||||
|
||||
@doc "`PUT /api/v1/apps/{id}`:部分更新(只送有給的欄位)。"
|
||||
def apps_update(issuer, token, id, attrs) do
|
||||
apps_request(issuer, token, :put, "/api/v1/apps/" <> URI.encode(id), json: attrs)
|
||||
api_request(issuer, token, :put, "/api/v1/apps/" <> URI.encode(id), json: attrs)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -88,21 +91,144 @@ defmodule BearCli.Api do
|
||||
一次性明文。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",
|
||||
api_request(issuer, token, :post, "/api/v1/apps/" <> URI.encode(id) <> "/rotate-secret",
|
||||
json: %{}
|
||||
)
|
||||
end
|
||||
|
||||
@doc "`POST /api/v1/apps/{id}/toggle`:切換 active ↔ inactive。"
|
||||
def apps_toggle(issuer, token, id) do
|
||||
apps_request(issuer, token, :post, "/api/v1/apps/" <> URI.encode(id) <> "/toggle", json: %{})
|
||||
api_request(issuer, token, :post, "/api/v1/apps/" <> URI.encode(id) <> "/toggle", json: %{})
|
||||
end
|
||||
|
||||
# App 管理 API 共用請求。回傳:
|
||||
# -- 個人自助 API(alterminal/bear#35;PAT Bearer、任何有效帳號)--
|
||||
|
||||
@doc "`GET /api/v1/profile`:完整個人資料(含 MFA 狀態)。"
|
||||
def profile_get(issuer, token) do
|
||||
api_request(issuer, token, :get, "/api/v1/profile")
|
||||
end
|
||||
|
||||
@doc "`PUT /api/v1/profile`:更新個人資料欄位(只送有給的欄位)。"
|
||||
def profile_update(issuer, token, attrs) do
|
||||
api_request(issuer, token, :put, "/api/v1/profile", json: attrs)
|
||||
end
|
||||
|
||||
@doc """
|
||||
`POST /api/v1/profile/password`:變更密碼(body:`current_password`、
|
||||
`new_password`、`password_confirmation`;伺服器驗舊密碼,不因 CLI 放寬)。
|
||||
"""
|
||||
def profile_change_password(issuer, token, current_password, new_password) do
|
||||
api_request(issuer, token, :post, "/api/v1/profile/password",
|
||||
json: %{
|
||||
current_password: current_password,
|
||||
new_password: new_password,
|
||||
password_confirmation: new_password
|
||||
}
|
||||
)
|
||||
end
|
||||
|
||||
@doc "`POST /api/v1/profile/email/request-codes`:寄發 email 變更雙向驗證碼。"
|
||||
def profile_email_request_codes(issuer, token, new_email) do
|
||||
api_request(issuer, token, :post, "/api/v1/profile/email/request-codes",
|
||||
json: %{new_email: new_email}
|
||||
)
|
||||
end
|
||||
|
||||
@doc """
|
||||
`POST /api/v1/profile/email`:確認變更 email(body:`new_email`、
|
||||
`current_code`、`new_code`)。
|
||||
"""
|
||||
def profile_email_change(issuer, token, new_email, current_code, new_code) do
|
||||
api_request(issuer, token, :post, "/api/v1/profile/email",
|
||||
json: %{new_email: new_email, current_code: current_code, new_code: new_code}
|
||||
)
|
||||
end
|
||||
|
||||
@doc "`GET /api/v1/profile/sessions`:列出作用中 session(新到舊)。"
|
||||
def sessions_list(issuer, token) do
|
||||
api_request(issuer, token, :get, "/api/v1/profile/sessions")
|
||||
end
|
||||
|
||||
@doc "`POST /api/v1/profile/sessions/{id}/revoke`:撤銷單一 session。"
|
||||
def sessions_revoke(issuer, token, id) do
|
||||
api_request(issuer, token, :post, "/api/v1/profile/sessions/" <> URI.encode(id) <> "/revoke",
|
||||
json: %{}
|
||||
)
|
||||
end
|
||||
|
||||
@doc """
|
||||
`POST /api/v1/profile/sessions/revoke-others`:撤銷其他 session
|
||||
(body `keep` 可省略=全部撤銷)。
|
||||
"""
|
||||
def sessions_revoke_others(issuer, token, keep \\ nil) do
|
||||
api_request(issuer, token, :post, "/api/v1/profile/sessions/revoke-others",
|
||||
json: %{keep: keep} |> Map.reject(fn {_k, v} -> is_nil(v) end)
|
||||
)
|
||||
end
|
||||
|
||||
@doc "`GET /api/v1/profile/tokens`:列出未撤銷的 PAT(新到舊)。"
|
||||
def tokens_list(issuer, token) do
|
||||
api_request(issuer, token, :get, "/api/v1/profile/tokens")
|
||||
end
|
||||
|
||||
@doc """
|
||||
`POST /api/v1/profile/tokens`:建立 PAT;明文 `token` 只在成功回應
|
||||
出現一次(body:`name`、`expires_in`=天數或 `never`)。
|
||||
"""
|
||||
def tokens_create(issuer, token, name, expires_in) do
|
||||
api_request(issuer, token, :post, "/api/v1/profile/tokens",
|
||||
json: %{name: name, expires_in: expires_in}
|
||||
)
|
||||
end
|
||||
|
||||
@doc "`POST /api/v1/profile/tokens/{id}/revoke`:撤銷單一 PAT。"
|
||||
def tokens_revoke(issuer, token, id) do
|
||||
api_request(issuer, token, :post, "/api/v1/profile/tokens/" <> URI.encode(id) <> "/revoke",
|
||||
json: %{}
|
||||
)
|
||||
end
|
||||
|
||||
@doc """
|
||||
`POST /api/v1/profile/mfa/setup`(無 body):開始 TOTP 設定,回
|
||||
`%{"data" => %{"secret" => ..., "otpauth_uri" => ...}}`。已啟用 MFA 回
|
||||
422 `already_enabled`。
|
||||
"""
|
||||
def mfa_setup(issuer, token) do
|
||||
api_request(issuer, token, :post, "/api/v1/profile/mfa/setup", json: %{})
|
||||
end
|
||||
|
||||
@doc """
|
||||
`POST /api/v1/profile/mfa/setup/confirm`(body:`code`):確認設定並
|
||||
啟用 MFA,回一次性 recovery codes。
|
||||
"""
|
||||
def mfa_setup_confirm(issuer, token, code) do
|
||||
api_request(issuer, token, :post, "/api/v1/profile/mfa/setup/confirm", json: %{code: code})
|
||||
end
|
||||
|
||||
@doc """
|
||||
`POST /api/v1/profile/mfa/disable`(body:`code`=目前 TOTP 或
|
||||
recovery code):停用 MFA。
|
||||
"""
|
||||
def mfa_disable(issuer, token, code) do
|
||||
api_request(issuer, token, :post, "/api/v1/profile/mfa/disable", json: %{code: code})
|
||||
end
|
||||
|
||||
@doc """
|
||||
`POST /api/v1/profile/mfa/recovery-codes`(body:`code`):重產一組
|
||||
一次性 recovery codes(舊組全部失效)。
|
||||
"""
|
||||
def mfa_recovery_codes(issuer, token, code) do
|
||||
api_request(issuer, token, :post, "/api/v1/profile/mfa/recovery-codes", json: %{code: code})
|
||||
end
|
||||
|
||||
# -- 共用請求輔助 --
|
||||
|
||||
# 回傳:
|
||||
# {:ok, body} | {:error, :unauthorized, desc} | {:error, :forbidden, desc}
|
||||
# | {:error, :not_found, desc} | {:error, :unprocessable_entity, body}
|
||||
# | {:error, :too_many_requests, body}
|
||||
# | {:error, :server_error, status} | {:error, :network, reason}
|
||||
defp apps_request(issuer, token, method, path, extra \\ []) do
|
||||
defp api_request(issuer, token, method, path, extra \\ []) do
|
||||
url = String.trim_trailing(issuer, "/") <> path
|
||||
|
||||
opts =
|
||||
@@ -129,6 +255,9 @@ defmodule BearCli.Api do
|
||||
{:ok, %Req.Response{status: 422, body: body}} ->
|
||||
{:error, :unprocessable_entity, decode_body(body)}
|
||||
|
||||
{:ok, %Req.Response{status: 429, body: body}} ->
|
||||
{:error, :too_many_requests, decode_body(body)}
|
||||
|
||||
{:ok, %Req.Response{status: status}} ->
|
||||
{:error, :server_error, status}
|
||||
|
||||
|
||||
+281
-1
@@ -8,7 +8,7 @@ defmodule BearCli.CLI do
|
||||
優先使用該值,不讀寫本機憑證檔。
|
||||
"""
|
||||
|
||||
alias BearCli.{Api, Apps, Config, Credentials}
|
||||
alias BearCli.{Api, Apps, Config, Credentials, SelfService}
|
||||
|
||||
@global_switches [
|
||||
issuer: :string,
|
||||
@@ -65,6 +65,39 @@ defmodule BearCli.CLI do
|
||||
@statuses ~w(active inactive)
|
||||
@methods ~w(client_secret PKCE)
|
||||
|
||||
# -- 個人自助指令群(docs/commands.md §3.7)--
|
||||
|
||||
@profile_verbs ~w(show set)
|
||||
@sessions_verbs ~w(list revoke revoke-others)
|
||||
@tokens_verbs ~w(list create revoke)
|
||||
@mfa_verbs ~w(status setup disable recovery-codes)
|
||||
|
||||
@profile_set_switches [
|
||||
name: :string,
|
||||
given_name: :string,
|
||||
family_name: :string,
|
||||
nickname: :string,
|
||||
preferred_username: :string,
|
||||
profile: :string,
|
||||
picture: :string,
|
||||
website: :string,
|
||||
gender: :string,
|
||||
birthdate: :string,
|
||||
zoneinfo: :string,
|
||||
locale: :string,
|
||||
phone_number: :string,
|
||||
phone_verified: :boolean,
|
||||
address_formatted: :string,
|
||||
address_street_address: :string,
|
||||
address_locality: :string,
|
||||
address_region: :string,
|
||||
address_postal_code: :string,
|
||||
address_country: :string
|
||||
]
|
||||
|
||||
@email_switches [new: :string]
|
||||
@tokens_create_switches [name: :string, expires_in: :string]
|
||||
|
||||
# -- escript 入口 --
|
||||
|
||||
@doc "escript 主函式。執行後以 `System.halt/1` 設定退出碼。"
|
||||
@@ -177,10 +210,135 @@ defmodule BearCli.CLI do
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_command("profile", args, global) do
|
||||
case args do
|
||||
[verb | rest] when verb in @profile_verbs ->
|
||||
switches = if verb == "set", do: @profile_set_switches, else: []
|
||||
|
||||
case OptionParser.parse(rest, strict: @global_switches ++ switches) do
|
||||
{opts, positionals, []} ->
|
||||
validate_self_service(
|
||||
:profile,
|
||||
verb,
|
||||
positionals,
|
||||
merge_opts(global, opts_to_map(opts))
|
||||
)
|
||||
|
||||
{_opts, _extra, [{opt, _} | _]} ->
|
||||
{:error, "無法解析選項:#{opt}", 2}
|
||||
end
|
||||
|
||||
[] ->
|
||||
{:error, "profile 缺少子指令(可用:#{Enum.join(@profile_verbs, " ")})", 2}
|
||||
|
||||
[unknown | _] ->
|
||||
{:error, "未知的 profile 子指令:#{unknown}(可用:#{Enum.join(@profile_verbs, " ")})", 2}
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_command("password", args, global) do
|
||||
case args do
|
||||
["change" | rest] ->
|
||||
case OptionParser.parse(rest, strict: @global_switches) do
|
||||
{opts, [], []} ->
|
||||
{:ok, {:self_service, :password, :change}, merge_opts(global, opts_to_map(opts))}
|
||||
|
||||
{_opts, extra, []} ->
|
||||
{:error, "password change 不接受參數:#{Enum.join(extra, " ")}", 2}
|
||||
|
||||
{_opts, _extra, [{opt, _} | _]} ->
|
||||
{:error, "無法解析選項:#{opt}", 2}
|
||||
end
|
||||
|
||||
[] ->
|
||||
{:error, "password 缺少子指令(可用:change)", 2}
|
||||
|
||||
[unknown | _] ->
|
||||
{:error, "未知的 password 子指令:#{unknown}(可用:change)", 2}
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_command("email", args, global) do
|
||||
case args do
|
||||
["change" | rest] ->
|
||||
case OptionParser.parse(rest, strict: @global_switches ++ @email_switches) do
|
||||
{opts, [], []} ->
|
||||
{:ok, {:self_service, :email, :change}, merge_opts(global, opts_to_map(opts))}
|
||||
|
||||
{_opts, extra, []} ->
|
||||
{:error, "email change 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
||||
|
||||
{_opts, _extra, [{opt, _} | _]} ->
|
||||
{:error, "無法解析選項:#{opt}", 2}
|
||||
end
|
||||
|
||||
[] ->
|
||||
{:error, "email 缺少子指令(可用:change)", 2}
|
||||
|
||||
[unknown | _] ->
|
||||
{:error, "未知的 email 子指令:#{unknown}(可用:change)", 2}
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_command("sessions", args, global) do
|
||||
case args do
|
||||
[verb | rest] when verb in @sessions_verbs ->
|
||||
parse_group_verb("sessions", verb, rest, [], global)
|
||||
|
||||
[] ->
|
||||
{:error, "sessions 缺少子指令(可用:#{Enum.join(@sessions_verbs, " ")})", 2}
|
||||
|
||||
[unknown | _] ->
|
||||
{:error, "未知的 sessions 子指令:#{unknown}(可用:#{Enum.join(@sessions_verbs, " ")})", 2}
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_command("tokens", args, global) do
|
||||
case args do
|
||||
[verb | rest] when verb in @tokens_verbs ->
|
||||
parse_group_verb("tokens", verb, rest, [], global)
|
||||
|
||||
[] ->
|
||||
{:error, "tokens 缺少子指令(可用:#{Enum.join(@tokens_verbs, " ")})", 2}
|
||||
|
||||
[unknown | _] ->
|
||||
{:error, "未知的 tokens 子指令:#{unknown}(可用:#{Enum.join(@tokens_verbs, " ")})", 2}
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_command("mfa", args, global) do
|
||||
case args do
|
||||
[verb | rest] when verb in @mfa_verbs ->
|
||||
parse_group_verb("mfa", verb, rest, [], global)
|
||||
|
||||
[] ->
|
||||
{:error, "mfa 缺少子指令(可用:#{Enum.join(@mfa_verbs, " ")})", 2}
|
||||
|
||||
[unknown | _] ->
|
||||
{:error, "未知的 mfa 子指令:#{unknown}(可用:#{Enum.join(@mfa_verbs, " ")})", 2}
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_command(unknown, _args, _global) do
|
||||
{:error, "未知指令:#{unknown}(可用 bear --help 查看說明)", 2}
|
||||
end
|
||||
|
||||
# sessions/tokens/mfa 共用:verb 已驗證合法後解析選項與位置參數。
|
||||
defp parse_group_verb(group, verb, rest, extra_switches, global) do
|
||||
switches = group_switches(group, verb) ++ extra_switches
|
||||
|
||||
case OptionParser.parse(rest, strict: @global_switches ++ switches) do
|
||||
{opts, positionals, []} ->
|
||||
validate_self_service(group, verb, positionals, merge_opts(global, opts_to_map(opts)))
|
||||
|
||||
{_opts, _extra, [{opt, _} | _]} ->
|
||||
{:error, "無法解析選項:#{opt}", 2}
|
||||
end
|
||||
end
|
||||
|
||||
defp group_switches("tokens", "create"), do: @tokens_create_switches
|
||||
defp group_switches(_group, _verb), do: []
|
||||
|
||||
defp parse_opts(args, switches) do
|
||||
case OptionParser.parse(args, strict: switches) do
|
||||
{opts, [], []} ->
|
||||
@@ -302,6 +460,92 @@ defmodule BearCli.CLI do
|
||||
{:error, "#{flag} 不接受的值:#{value}(可用:#{Enum.join(allowed, "、")})", 2}
|
||||
end
|
||||
|
||||
# -- 個人自助指令群解析輔助(§3.7)--
|
||||
|
||||
# 各群組的位置參數驗證;通過後回 {:ok, {:self_service, group, verb}, opts}。
|
||||
defp validate_self_service(:profile, "show", [], opts),
|
||||
do: {:ok, {:self_service, :profile, :show}, opts}
|
||||
|
||||
defp validate_self_service(:profile, "show", extra, _opts),
|
||||
do: {:error, "profile show 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
||||
|
||||
defp validate_self_service(:profile, "set", [], opts),
|
||||
do: {:ok, {:self_service, :profile, :set}, opts}
|
||||
|
||||
defp validate_self_service(:profile, "set", extra, _opts),
|
||||
do: {:error, "profile set 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
||||
|
||||
defp validate_self_service("sessions", "list", [], opts),
|
||||
do: {:ok, {:self_service, :sessions, :list}, opts}
|
||||
|
||||
defp validate_self_service("sessions", "list", extra, _opts),
|
||||
do: {:error, "sessions list 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
||||
|
||||
defp validate_self_service("sessions", "revoke", [id], opts),
|
||||
do: {:ok, {:self_service, :sessions, :revoke}, Map.put(opts, :id_arg, id)}
|
||||
|
||||
defp validate_self_service("sessions", "revoke", [], _opts),
|
||||
do: {:error, "sessions revoke 缺少 <id>", 2}
|
||||
|
||||
defp validate_self_service("sessions", "revoke", extra, _opts),
|
||||
do: {:error, "sessions revoke 只接受一個 <id>(多餘:#{Enum.join(Enum.drop(extra, 1), " ")})", 2}
|
||||
|
||||
defp validate_self_service("sessions", "revoke-others", [], opts),
|
||||
do: {:ok, {:self_service, :sessions, :"revoke-others"}, opts}
|
||||
|
||||
defp validate_self_service("sessions", "revoke-others", extra, _opts),
|
||||
do: {:error, "sessions revoke-others 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
||||
|
||||
defp validate_self_service("tokens", "list", [], opts),
|
||||
do: {:ok, {:self_service, :tokens, :list}, opts}
|
||||
|
||||
defp validate_self_service("tokens", "list", extra, _opts),
|
||||
do: {:error, "tokens list 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
||||
|
||||
defp validate_self_service("tokens", "create", [], opts) do
|
||||
if blank?(opts[:name]) do
|
||||
{:error, "tokens create 缺少 --name NAME", 2}
|
||||
else
|
||||
{:ok, {:self_service, :tokens, :create}, opts}
|
||||
end
|
||||
end
|
||||
|
||||
defp validate_self_service("tokens", "create", extra, _opts),
|
||||
do: {:error, "tokens create 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
||||
|
||||
defp validate_self_service("tokens", "revoke", [id], opts),
|
||||
do: {:ok, {:self_service, :tokens, :revoke}, Map.put(opts, :id_arg, id)}
|
||||
|
||||
defp validate_self_service("tokens", "revoke", [], _opts),
|
||||
do: {:error, "tokens revoke 缺少 <id>", 2}
|
||||
|
||||
defp validate_self_service("tokens", "revoke", extra, _opts),
|
||||
do: {:error, "tokens revoke 只接受一個 <id>(多餘:#{Enum.join(Enum.drop(extra, 1), " ")})", 2}
|
||||
|
||||
defp validate_self_service("mfa", "status", [], opts),
|
||||
do: {:ok, {:self_service, :mfa, :status}, opts}
|
||||
|
||||
defp validate_self_service("mfa", "status", extra, _opts),
|
||||
do: {:error, "mfa status 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
||||
|
||||
defp validate_self_service("mfa", "setup", [], opts),
|
||||
do: {:ok, {:self_service, :mfa, :setup}, opts}
|
||||
|
||||
defp validate_self_service("mfa", "setup", extra, _opts),
|
||||
do: {:error, "mfa setup 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
||||
|
||||
defp validate_self_service("mfa", "disable", [], opts),
|
||||
do: {:ok, {:self_service, :mfa, :disable}, opts}
|
||||
|
||||
defp validate_self_service("mfa", "disable", extra, _opts),
|
||||
do: {:error, "mfa disable 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
||||
|
||||
defp validate_self_service("mfa", "recovery-codes", [], opts),
|
||||
do: {:ok, {:self_service, :mfa, :"recovery-codes"}, opts}
|
||||
|
||||
defp validate_self_service("mfa", "recovery-codes", extra, _opts),
|
||||
do: {:error, "mfa recovery-codes 不接受位置參數:#{Enum.join(extra, " ")}", 2}
|
||||
|
||||
defp merge_opts(global, opts) do
|
||||
Map.merge(Map.new(global), Map.new(opts))
|
||||
end
|
||||
@@ -345,6 +589,12 @@ defmodule BearCli.CLI do
|
||||
apps_api = cmd_opts[:apps_api] || opts[:apps_api] || Api
|
||||
Apps.run(verb, Map.put(cmd_opts, :apps_api, apps_api))
|
||||
|
||||
# 個人自助指令群({:ok, {:self_service, group, verb}, opts} 形狀)
|
||||
{:ok, {:self_service, group, verb}, cmd_opts} when is_atom(group) and is_atom(verb) ->
|
||||
inject_opts = opts |> Map.new() |> Map.take([:ss_api, :io, :tty?])
|
||||
ss_opts = Map.merge(inject_opts, Map.take(cmd_opts, [:ss_api, :io, :tty?]))
|
||||
SelfService.run(group, verb, Map.merge(cmd_opts, ss_opts))
|
||||
|
||||
{:ok, command, cmd_opts} ->
|
||||
cond do
|
||||
cmd_opts[:version] ->
|
||||
@@ -653,6 +903,12 @@ defmodule BearCli.CLI do
|
||||
logout 登出(清除本機憑證)
|
||||
status 顯示登入狀態
|
||||
apps <動詞> App 管理(admin;bear apps --help 查看)
|
||||
profile <動詞> 個人資料(show/set)
|
||||
password change 變更密碼(互動輸入,不進 shell history)
|
||||
email change --new E 變更 email(雙向驗證碼流程)
|
||||
sessions <動詞> 管理網頁 session(list/revoke/revoke-others)
|
||||
tokens <動詞> 管理 PAT(list/create/revoke)
|
||||
mfa <動詞> TOTP 兩因子(status/setup/disable/recovery-codes)
|
||||
|
||||
apps 指令群(需 admin 權限的 PAT):
|
||||
apps list [--visibility public|internal] [--status active|inactive]
|
||||
@@ -666,6 +922,30 @@ defmodule BearCli.CLI do
|
||||
apps rotate-secret <client-id>
|
||||
apps toggle <client-id>
|
||||
|
||||
個人自助指令群(任何有效 PAT 皆可):
|
||||
profile show
|
||||
profile set [--name NAME] [--given-name NAME] [--family-name NAME]
|
||||
[--nickname NAME] [--preferred-username NAME]
|
||||
[--profile URL] [--picture URL] [--website URL]
|
||||
[--gender male|female|other] [--birthdate YYYY-MM-DD]
|
||||
[--zoneinfo TZ] [--locale LOC] [--phone-number E164]
|
||||
[--phone-verified] [--address-formatted TEXT]
|
||||
[--address-street-address TEXT] [--address-locality TEXT]
|
||||
[--address-region TEXT] [--address-postal-code TEXT]
|
||||
[--address-country TEXT]
|
||||
password change
|
||||
email change --new EMAIL
|
||||
sessions list
|
||||
sessions revoke <id>
|
||||
sessions revoke-others
|
||||
tokens list
|
||||
tokens create --name NAME [--expires-in DAYS|never]
|
||||
tokens revoke <id>
|
||||
mfa status
|
||||
mfa setup
|
||||
mfa disable
|
||||
mfa recovery-codes
|
||||
|
||||
全域選項:
|
||||
--issuer URL Bear(OIDC Provider)位址(預設 https://alterminal.com)
|
||||
--config PATH 設定檔路徑(預設 ~/.config/bear/config.json)
|
||||
|
||||
@@ -0,0 +1,775 @@
|
||||
defmodule BearCli.SelfService do
|
||||
@moduledoc """
|
||||
`bear` 個人自助指令群(docs/commands.md §3.7、issue #11)。
|
||||
|
||||
對應伺服器端個人自助 JSON API(alterminal/bear#35,`/api/v1/profile*`、
|
||||
PAT Bearer、任何有效帳號):profile/password/email/sessions/
|
||||
tokens/mfa。
|
||||
|
||||
- 敏感輸入(密碼、email/MFA 驗證碼)一律互動提示讀取且不回顧,
|
||||
不接受命令列明文參數;非 TTY 環境 → 退出碼 2。
|
||||
- 一次性明文(`tokens create` 的 PAT、`mfa` 的 recovery codes)只於
|
||||
成功當下輸出於 stdout,不寫入憑證檔/log/`--verbose` 輸出。
|
||||
|
||||
退出碼:0 成功;1 404/422/429;2 用法錯誤(含非 TTY 的互動輸入);
|
||||
3 未登入或 401;6 網路/伺服器錯誤;8 權限不足(403)。
|
||||
"""
|
||||
|
||||
alias BearCli.{Api, Config, Credentials}
|
||||
|
||||
@genders ~w(male female other)
|
||||
|
||||
# profile set 的可更新欄位:CLI 選項名(atom)→ API 欄位名。
|
||||
@profile_set_fields [
|
||||
name: "name",
|
||||
given_name: "given_name",
|
||||
family_name: "family_name",
|
||||
nickname: "nickname",
|
||||
preferred_username: "preferred_username",
|
||||
profile: "profile",
|
||||
picture: "picture",
|
||||
website: "website",
|
||||
gender: "gender",
|
||||
birthdate: "birthdate",
|
||||
zoneinfo: "zoneinfo",
|
||||
locale: "locale",
|
||||
phone_number: "phone_number",
|
||||
phone_verified: "phone_number_verified",
|
||||
address_formatted: "address_formatted",
|
||||
address_street_address: "address_street_address",
|
||||
address_locality: "address_locality",
|
||||
address_region: "address_region",
|
||||
address_postal_code: "address_postal_code",
|
||||
address_country: "address_country"
|
||||
]
|
||||
|
||||
@url_fields ~w(profile picture website)
|
||||
|
||||
# -- 入口 --
|
||||
|
||||
@doc """
|
||||
執行個人自助指令,回傳退出碼。`group` 為 :profile/:password/:email/
|
||||
:sessions/:tokens/:mfa,`verb` 為子指令 atom,`opts` 為解析後選項。
|
||||
|
||||
`opts[:ss_api]` 可注入假 API 模組供測試;`opts[:io]` 可注入互動輸入
|
||||
模組(實作 `prompt_secret/1`),`opts[:tty?]` 可覆寫 TTY 判定。
|
||||
"""
|
||||
def run(group, verb, opts) do
|
||||
api = opts[:ss_api] || Api
|
||||
|
||||
with {:ok, ctx} <- context(opts) do
|
||||
execute(group, verb, ctx, opts, api)
|
||||
else
|
||||
{:error, message, code} -> fail(opts, message, code)
|
||||
end
|
||||
end
|
||||
|
||||
# -- 各指令實作(execute/5 子句群)--
|
||||
|
||||
defp execute(:profile, :show, ctx, opts, api) do
|
||||
case api.profile_get(ctx.issuer, ctx.token) do
|
||||
{:ok, body} ->
|
||||
show_profile(body["data"] || %{}, opts)
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:profile, :set, ctx, opts, api) do
|
||||
case build_profile_attrs(opts) do
|
||||
{:ok, attrs} ->
|
||||
case api.profile_update(ctx.issuer, ctx.token, attrs) do
|
||||
{:ok, body} ->
|
||||
show_profile(body["data"] || %{}, opts)
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
|
||||
{:error, message, code} ->
|
||||
fail(opts, message, code)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:password, :change, ctx, opts, api) do
|
||||
with {:ok, {current, new}} <- read_password_prompts(opts) do
|
||||
case api.profile_change_password(ctx.issuer, ctx.token, current, new) do
|
||||
{:ok, _body} ->
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true}))
|
||||
else
|
||||
IO.puts("密碼已變更")
|
||||
IO.puts("提醒:變更密碼不自動撤銷其他 session;需要時另用 bear sessions revoke-others。")
|
||||
end
|
||||
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
else
|
||||
{:error, message, code} -> fail(opts, message, code)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:email, :change, ctx, opts, api) do
|
||||
# OptionParser 把 --new EMAIL 正規化為 :new(底線)。
|
||||
new_email = opts[:new] || opts[:new_email]
|
||||
|
||||
with :ok <- require_new_email(new_email),
|
||||
{:ok, {current_code, new_code}} <- request_and_read_codes(ctx, opts, api, new_email) do
|
||||
case api.profile_email_change(ctx.issuer, ctx.token, new_email, current_code, new_code) do
|
||||
{:ok, body} ->
|
||||
updated = (body["data"] || %{})["email"] || new_email
|
||||
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true, email: updated}))
|
||||
else
|
||||
IO.puts("email 已更新:#{updated}")
|
||||
IO.puts("提醒:bear login 用的 PAT 不綁 email,不受影響。")
|
||||
end
|
||||
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
else
|
||||
{:error, message, code} -> fail(opts, message, code)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:sessions, :list, ctx, opts, api) do
|
||||
case api.sessions_list(ctx.issuer, ctx.token) do
|
||||
{:ok, body} ->
|
||||
sessions = body["data"] || []
|
||||
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true, sessions: sessions}))
|
||||
else
|
||||
print_sessions_table(sessions)
|
||||
end
|
||||
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:sessions, :revoke, ctx, opts, api) do
|
||||
id = opts[:id_arg]
|
||||
|
||||
with :ok <- require_id(id, "sessions revoke") do
|
||||
case api.sessions_revoke(ctx.issuer, ctx.token, id) do
|
||||
{:ok, _body} ->
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true, revoked: id}))
|
||||
else
|
||||
IO.puts("session 已撤銷")
|
||||
end
|
||||
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
else
|
||||
{:error, message, code} -> fail(opts, message, code)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:sessions, :"revoke-others", ctx, opts, api) do
|
||||
case api.sessions_revoke_others(ctx.issuer, ctx.token) do
|
||||
{:ok, body} ->
|
||||
count = (body["data"] || %{})["revoked_count"]
|
||||
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true, revoked: count}))
|
||||
else
|
||||
IO.puts("已撤銷 #{count} 個其他 session")
|
||||
end
|
||||
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:tokens, :list, ctx, opts, api) do
|
||||
case api.tokens_list(ctx.issuer, ctx.token) do
|
||||
{:ok, body} ->
|
||||
tokens = body["data"] || []
|
||||
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true, tokens: tokens}))
|
||||
else
|
||||
print_tokens_table(tokens)
|
||||
end
|
||||
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:tokens, :create, ctx, opts, api) do
|
||||
name = opts[:name]
|
||||
|
||||
with {:ok, expires_in} <- parse_expires_in(opts[:expires_in]) do
|
||||
case api.tokens_create(ctx.issuer, ctx.token, name, expires_in) do
|
||||
{:ok, body} ->
|
||||
token = body["data"] || %{}
|
||||
raw = body["token"]
|
||||
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true, token: token, raw: raw}))
|
||||
else
|
||||
expires_at = token["expires_at"]
|
||||
expiry_note = if expires_at, do: "(#{expires_at} 到期)", else: "(無到期日)"
|
||||
|
||||
IO.puts("PAT 已建立:#{token["name"]}#{expiry_note}")
|
||||
IO.puts("token(只顯示這一次,請立即保存):")
|
||||
IO.puts(" #{raw}")
|
||||
IO.puts("提醒:新 PAT 要使用須另以 bear login --token 登入(或設 BEAR_TOKEN)。")
|
||||
end
|
||||
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
else
|
||||
{:error, message, code} -> fail(opts, message, code)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:tokens, :revoke, ctx, opts, api) do
|
||||
id = opts[:id_arg]
|
||||
|
||||
with :ok <- require_id(id, "tokens revoke") do
|
||||
case api.tokens_revoke(ctx.issuer, ctx.token, id) do
|
||||
{:ok, body} ->
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true, revoked: (body["data"] || %{})["revoked"] || id}))
|
||||
else
|
||||
IO.puts("PAT 已撤銷")
|
||||
end
|
||||
|
||||
# 撤銷目前憑證用的 PAT 時,後續指令會得 401;本機憑證檔只存 PAT
|
||||
# 明文、未存 token id,CLI 無法可靠比對,一律提示重新登入的退路。
|
||||
IO.puts(
|
||||
:stderr,
|
||||
"提醒:若撤銷的是本機憑證所用的 PAT,後續指令會得到 401;屆時重新 bear login。"
|
||||
)
|
||||
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
else
|
||||
{:error, message, code} -> fail(opts, message, code)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:mfa, :status, ctx, opts, api) do
|
||||
case api.profile_get(ctx.issuer, ctx.token) do
|
||||
{:ok, body} ->
|
||||
data = body["data"] || %{}
|
||||
enabled = data["mfa_enabled"] || data["totp_enabled"] || false
|
||||
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true, totp_enabled: enabled}))
|
||||
else
|
||||
IO.puts("MFA(TOTP):#{if enabled, do: "已啟用", else: "未啟用"}")
|
||||
end
|
||||
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:mfa, :setup, ctx, opts, api) do
|
||||
with {:ok, _data} <- mfa_begin(ctx, opts, api),
|
||||
{:ok, code} <- prompt_secret(opts, "6 位驗證碼(掃描 QR 後由驗證器產生)") do
|
||||
case api.mfa_setup_confirm(ctx.issuer, ctx.token, code) do
|
||||
{:ok, body} ->
|
||||
codes = (body["data"] || %{})["recovery_codes"] || []
|
||||
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true, recovery_codes: codes}))
|
||||
else
|
||||
IO.puts("MFA 已啟用。")
|
||||
print_recovery_codes(codes)
|
||||
end
|
||||
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
else
|
||||
{:error, message, code} -> fail(opts, message, code)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:mfa, :disable, ctx, opts, api) do
|
||||
with {:ok, code} <- prompt_secret(opts, "目前的 TOTP 碼或 recovery code") do
|
||||
case api.mfa_disable(ctx.issuer, ctx.token, code) do
|
||||
{:ok, _body} ->
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true}))
|
||||
else
|
||||
IO.puts("MFA 已停用")
|
||||
end
|
||||
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
else
|
||||
{:error, message, code} -> fail(opts, message, code)
|
||||
end
|
||||
end
|
||||
|
||||
defp execute(:mfa, :"recovery-codes", ctx, opts, api) do
|
||||
with {:ok, code} <- prompt_secret(opts, "目前的 TOTP 碼或 recovery code") do
|
||||
case api.mfa_recovery_codes(ctx.issuer, ctx.token, code) do
|
||||
{:ok, body} ->
|
||||
codes = (body["data"] || %{})["recovery_codes"] || []
|
||||
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true, recovery_codes: codes}))
|
||||
else
|
||||
print_recovery_codes(codes)
|
||||
end
|
||||
|
||||
0
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
fail_api(opts, ctx, error)
|
||||
end
|
||||
else
|
||||
{:error, message, code} -> fail(opts, message, code)
|
||||
end
|
||||
end
|
||||
|
||||
# -- 共用背景(token/issuer)--
|
||||
|
||||
defp context(opts) do
|
||||
if token = Config.env_token() do
|
||||
# BEAR_TOKEN 優先於憑證檔(不讀檔、不寫檔)。
|
||||
{:ok, %{token: token, issuer: resolve_issuer(opts, nil)}}
|
||||
else
|
||||
case Credentials.load() do
|
||||
{:ok, creds} ->
|
||||
token = creds["access_token"]
|
||||
|
||||
if blank?(token) do
|
||||
{:error, "憑證檔缺少 access_token,請重新 bear login", 7}
|
||||
else
|
||||
{:ok, %{token: token, issuer: resolve_issuer(opts, creds["issuer"])}}
|
||||
end
|
||||
|
||||
:error ->
|
||||
{:error, "未登入(請先執行 bear login)", 3}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp resolve_issuer(opts, stored_issuer) do
|
||||
opts[:issuer] || stored_issuer || Config.resolve_issuer(nil, opts[:config])
|
||||
end
|
||||
|
||||
# -- profile set 屬性組裝與本地驗證 --
|
||||
|
||||
# 只送有給的欄位(§3.7.2);非法值本地檢查 → 用法錯誤 2,不發請求。
|
||||
defp build_profile_attrs(opts) do
|
||||
given =
|
||||
@profile_set_fields
|
||||
|> Enum.flat_map(fn {opt_key, api_key} ->
|
||||
case Map.get(opts, opt_key) do
|
||||
v when is_binary(v) and v != "" -> [{api_key, v}]
|
||||
true -> [{api_key, true}]
|
||||
_other -> []
|
||||
end
|
||||
end)
|
||||
|> Map.new()
|
||||
|
||||
cond do
|
||||
given == %{} ->
|
||||
{:error, "profile set 未給任何欄位(可用選項見 bear --help)", 2}
|
||||
|
||||
invalid_gender?(given) ->
|
||||
{:error, "--gender 不接受的值:#{given["gender"]}(可用:#{Enum.join(@genders, "、")})", 2}
|
||||
|
||||
true ->
|
||||
check_url_fields(given)
|
||||
end
|
||||
end
|
||||
|
||||
defp invalid_gender?(%{"gender" => g}), do: g not in @genders
|
||||
defp invalid_gender?(_), do: false
|
||||
|
||||
# URL 類欄位本地檢查 http(s)://(§3.7.2)。
|
||||
defp check_url_fields(given) do
|
||||
bad =
|
||||
Enum.find(@url_fields, fn field ->
|
||||
case given[field] do
|
||||
v when is_binary(v) ->
|
||||
not (String.starts_with?(v, "http://") or String.starts_with?(v, "https://"))
|
||||
|
||||
_ ->
|
||||
false
|
||||
end
|
||||
end)
|
||||
|
||||
case bad do
|
||||
nil -> {:ok, given}
|
||||
field -> {:error, "--#{String.replace(field, "_", "-")} 需為 http(s):// 開頭的 URL", 2}
|
||||
end
|
||||
end
|
||||
|
||||
# -- password 互動輸入 --
|
||||
|
||||
defp read_password_prompts(opts) do
|
||||
with {:ok, current} <- prompt_secret(opts, "目前密碼"),
|
||||
{:ok, new} <- prompt_secret(opts, "新密碼"),
|
||||
{:ok, confirm} <- prompt_secret(opts, "確認新密碼") do
|
||||
if new == confirm do
|
||||
{:ok, {current, new}}
|
||||
else
|
||||
# 兩次新密碼不一致 → 本地檢查,不發請求(§3.7.3)。
|
||||
{:error, "兩次輸入的新密碼不一致", 2}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# -- email 流程輔助 --
|
||||
|
||||
defp require_new_email(nil), do: {:error, "email change 缺少 --new EMAIL", 2}
|
||||
defp require_new_email(""), do: {:error, "email change 缺少 --new EMAIL", 2}
|
||||
defp require_new_email(_), do: :ok
|
||||
|
||||
defp request_and_read_codes(ctx, opts, api, new_email) do
|
||||
case api.profile_email_request_codes(ctx.issuer, ctx.token, new_email) do
|
||||
{:ok, _body} ->
|
||||
IO.puts(:stderr, "驗證碼已寄至現有信箱與 #{new_email},請查收。")
|
||||
|
||||
with {:ok, current_code} <- prompt_secret(opts, "現有信箱驗證碼"),
|
||||
{:ok, new_code} <- prompt_secret(opts, "新信箱驗證碼") do
|
||||
{:ok, {current_code, new_code}}
|
||||
end
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
{message, code} = format_api_error(ctx, error)
|
||||
{:error, message, code}
|
||||
end
|
||||
end
|
||||
|
||||
# -- tokens create 選項 --
|
||||
|
||||
# --expires-in:正整數天數或 never;預設 30(§3.7.6)。
|
||||
defp parse_expires_in(nil), do: {:ok, "30"}
|
||||
defp parse_expires_in("never"), do: {:ok, "never"}
|
||||
|
||||
defp parse_expires_in(value) when is_binary(value) do
|
||||
case Integer.parse(value) do
|
||||
{n, ""} when n > 0 -> {:ok, value}
|
||||
_ -> {:error, "--expires-in 需為正整數天數或 never", 2}
|
||||
end
|
||||
end
|
||||
|
||||
# -- mfa setup 第一步 --
|
||||
|
||||
defp mfa_begin(ctx, opts, api) do
|
||||
case api.mfa_setup(ctx.issuer, ctx.token) do
|
||||
{:ok, body} ->
|
||||
data = body["data"] || %{}
|
||||
secret = data["secret"]
|
||||
uri = data["otpauth_uri"]
|
||||
|
||||
if opts[:json] do
|
||||
# 兩步互動流程:第一步資訊走 stderr(stdout 保留給最終結果 JSON,
|
||||
# 維持單一 JSON 物件的機器可讀輸出)。
|
||||
IO.puts(
|
||||
:stderr,
|
||||
Jason.encode!(%{step: "setup", secret: secret, otpauth_uri: uri})
|
||||
)
|
||||
else
|
||||
IO.puts("請用驗證器(Google Authenticator 等)掃描 QR,或手動輸入:")
|
||||
IO.puts(" otpauth URI:#{uri}")
|
||||
IO.puts(" secret(Base32):#{secret}")
|
||||
print_qr(uri)
|
||||
end
|
||||
|
||||
{:ok, data}
|
||||
|
||||
{:error, _kind, _detail} = error ->
|
||||
{message, code} = format_api_error(ctx, error)
|
||||
{:error, message, code}
|
||||
end
|
||||
end
|
||||
|
||||
# -- 互動輸入 --
|
||||
|
||||
# 敏感輸入一律互動提示讀取且不回顯;非 TTY → 退出碼 2(§3.7 群組共通)。
|
||||
# 測試可注入 opts[:io](實作 prompt_secret/1)與 opts[:tty?]。
|
||||
defp prompt_secret(opts, label) do
|
||||
tty? = Map.get(opts, :tty?, true)
|
||||
io = opts[:io]
|
||||
|
||||
cond do
|
||||
not tty? ->
|
||||
{:error, "此指令需要互動輸入(#{label}),請在終端機執行", 2}
|
||||
|
||||
io ->
|
||||
case io.prompt_secret(label) do
|
||||
:eof -> {:error, "未讀到輸入(#{label})", 2}
|
||||
{:ok, value} -> {:ok, value}
|
||||
end
|
||||
|
||||
true ->
|
||||
# 非 TTY(pipe/redirect)讀不到互動輸入 → 退出碼 2(§3.7 群組共通)。
|
||||
if tty_stdin?() do
|
||||
case IO.gets("#{label}:") do
|
||||
:eof -> {:error, "未讀到輸入(#{label})", 2}
|
||||
line -> {:ok, String.trim(line)}
|
||||
end
|
||||
else
|
||||
{:error, "此指令需要互動輸入(#{label}),請在終端機執行", 2}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# :io.rows/0 僅在終端機裝置成功;pipe/檔案重導回 {:error, :enotsup}。
|
||||
defp tty_stdin? do
|
||||
match?({:ok, _}, :io.rows())
|
||||
end
|
||||
|
||||
# -- 輸出 --
|
||||
|
||||
@profile_fields ~w(id email role name given_name family_name nickname preferred_username profile picture website gender birthdate zoneinfo locale phone_number phone_number_verified address mfa_enabled created_at updated_at)
|
||||
|
||||
defp show_profile(profile, opts) do
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: true, profile: profile}))
|
||||
else
|
||||
Enum.each(@profile_fields, fn key ->
|
||||
if Map.has_key?(profile, key) do
|
||||
IO.puts("#{String.pad_trailing(key, 22)}: #{format_value(profile[key])}")
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
defp format_value(nil), do: "(無)"
|
||||
defp format_value(true), do: "true"
|
||||
defp format_value(false), do: "false"
|
||||
defp format_value(v) when is_binary(v), do: v
|
||||
defp format_value(v) when is_number(v), do: to_string(v)
|
||||
defp format_value(v), do: Jason.encode!(v)
|
||||
|
||||
@sessions_headers ["ID", "IP", "USER AGENT", "CREATED", "LAST SEEN"]
|
||||
|
||||
defp print_sessions_table(sessions) do
|
||||
rows =
|
||||
Enum.map(sessions, fn s ->
|
||||
[
|
||||
s["id"] || "",
|
||||
s["ip"] || "",
|
||||
truncate(s["user_agent"] || "", 28),
|
||||
s["created_at"] || "",
|
||||
s["last_seen_at"] || ""
|
||||
]
|
||||
end)
|
||||
|
||||
print_table(@sessions_headers, rows)
|
||||
end
|
||||
|
||||
@tokens_headers ["ID", "NAME", "SCOPE", "CREATED", "EXPIRES", "LAST USED", "STATUS"]
|
||||
|
||||
defp print_tokens_table(tokens) do
|
||||
rows =
|
||||
Enum.map(tokens, fn t ->
|
||||
[
|
||||
t["id"] || "",
|
||||
t["name"] || "",
|
||||
t["scope"] || "",
|
||||
t["created_at"] || "",
|
||||
t["expires_at"] || "(無到期)",
|
||||
t["last_used_at"] || "(未使用)",
|
||||
token_status(t)
|
||||
]
|
||||
end)
|
||||
|
||||
print_table(@tokens_headers, rows)
|
||||
end
|
||||
|
||||
# list 僅回未撤銷 token;STATUS 依 expires_at 本地判定(§3.7.6)。
|
||||
defp token_status(%{"expires_at" => nil}), do: "active"
|
||||
|
||||
defp token_status(%{"expires_at" => expires_at}) when is_binary(expires_at) do
|
||||
case DateTime.from_iso8601(expires_at) do
|
||||
{:ok, dt, _} ->
|
||||
if DateTime.compare(dt, DateTime.utc_now()) == :gt, do: "active", else: "expired"
|
||||
|
||||
_ ->
|
||||
"active"
|
||||
end
|
||||
end
|
||||
|
||||
defp token_status(_), do: "active"
|
||||
|
||||
defp print_table(headers, rows) do
|
||||
widths =
|
||||
Enum.with_index(headers, fn _h, i ->
|
||||
Enum.max([
|
||||
String.length(Enum.at(headers, i))
|
||||
| Enum.map(rows, &String.length(Enum.at(&1, i)))
|
||||
])
|
||||
end)
|
||||
|
||||
render_row = fn cells ->
|
||||
cells
|
||||
|> Enum.with_index()
|
||||
|> Enum.map(fn {cell, i} -> String.pad_trailing(to_string(cell), Enum.at(widths, i)) end)
|
||||
|> Enum.join(" ")
|
||||
|> String.trim_trailing()
|
||||
end
|
||||
|
||||
IO.puts(render_row.(headers))
|
||||
|
||||
case rows do
|
||||
[] -> IO.puts("(無資料)")
|
||||
_ -> Enum.each(rows, fn cells -> IO.puts(render_row.(cells)) end)
|
||||
end
|
||||
end
|
||||
|
||||
defp truncate(text, max) do
|
||||
if String.length(text) > max do
|
||||
String.slice(text, 0, max - 1) <> "…"
|
||||
else
|
||||
text
|
||||
end
|
||||
end
|
||||
|
||||
# recovery codes 只顯示一次(同 PAT 明文處理)。
|
||||
defp print_recovery_codes([]), do: IO.puts("(伺服器未回傳 recovery codes)")
|
||||
|
||||
defp print_recovery_codes(codes) do
|
||||
IO.puts("recovery codes(只顯示這一次,請立即保存;舊組全部失效):")
|
||||
|
||||
Enum.each(codes, fn code ->
|
||||
IO.puts(" #{code}")
|
||||
end)
|
||||
end
|
||||
|
||||
# QR 由 CLI 本地生成(eqrcode),不經伺服器(§3.7.7)。產生失敗不阻斷流程,
|
||||
# 只印 URI 與 secret 供手動輸入。
|
||||
defp print_qr(uri) do
|
||||
qr = EQRCode.encode(uri)
|
||||
m = qr.matrix
|
||||
|
||||
IO.puts("QR(掃碼加入驗證器):")
|
||||
|
||||
for i <- 0..(tuple_size(m) - 1) do
|
||||
row =
|
||||
for j <- 0..(tuple_size(m) - 1) do
|
||||
if elem(elem(m, i), j) == 1, do: "██", else: " "
|
||||
end
|
||||
|
||||
IO.puts(Enum.join(row))
|
||||
end
|
||||
rescue
|
||||
_ -> IO.puts(:stderr, "(QR 產生失敗,請手動輸入上列 otpauth URI/secret)")
|
||||
end
|
||||
|
||||
# -- 錯誤處理 --
|
||||
|
||||
defp fail_api(opts, ctx, error) do
|
||||
{message, code} = format_api_error(ctx, error)
|
||||
fail(opts, message, code)
|
||||
end
|
||||
|
||||
# API 錯誤 → 依 §3.7 群組共通退出碼輸出,回傳退出碼。
|
||||
defp format_api_error(_ctx, {:error, :unauthorized, desc}) do
|
||||
{"token 無效或已過期(#{desc}),請重新 bear login", 3}
|
||||
end
|
||||
|
||||
defp format_api_error(_ctx, {:error, :forbidden, desc}) do
|
||||
{"權限不足(HTTP 403:#{desc})", 8}
|
||||
end
|
||||
|
||||
defp format_api_error(_ctx, {:error, :not_found, _desc}) do
|
||||
{"找不到目標(HTTP 404)", 1}
|
||||
end
|
||||
|
||||
# 語意錯誤(same_email/email_taken/invalid_code/already_enabled 等)。
|
||||
defp format_api_error(
|
||||
_ctx,
|
||||
{:error, :unprocessable_entity, %{"error" => error, "error_description" => desc}}
|
||||
) do
|
||||
{"#{error}:#{desc}", 1}
|
||||
end
|
||||
|
||||
# 422 逐欄位驗證錯誤(changeset errors)。
|
||||
defp format_api_error(_ctx, {:error, :unprocessable_entity, %{"errors" => errors}}) do
|
||||
details =
|
||||
errors
|
||||
|> Enum.map(fn {field, messages} ->
|
||||
"#{field}: #{Enum.join(List.wrap(messages), "、")}"
|
||||
end)
|
||||
|> Enum.join(";")
|
||||
|
||||
if details == "" do
|
||||
{"驗證失敗(HTTP 422)", 1}
|
||||
else
|
||||
{"驗證失敗(HTTP 422):#{details}", 1}
|
||||
end
|
||||
end
|
||||
|
||||
defp format_api_error(_ctx, {:error, :unprocessable_entity, _body}) do
|
||||
{"驗證失敗(HTTP 422)", 1}
|
||||
end
|
||||
|
||||
# 伺服器限流(email 驗證碼)→ 退出碼 1,提示稍後再試(§3.7.4)。
|
||||
defp format_api_error(_ctx, {:error, :too_many_requests, _body}) do
|
||||
{"請求過於頻繁(HTTP 429),請稍後再試", 1}
|
||||
end
|
||||
|
||||
defp format_api_error(_ctx, {:error, :server_error, status}) do
|
||||
{"伺服器回應 #{status}", 6}
|
||||
end
|
||||
|
||||
defp format_api_error(ctx, {:error, :network, reason}) do
|
||||
{"無法連線到 #{ctx.issuer}:#{reason}", 6}
|
||||
end
|
||||
|
||||
defp fail(opts, message, code) do
|
||||
if opts[:json] do
|
||||
IO.puts(Jason.encode!(%{ok: false, error: message, code: code}))
|
||||
else
|
||||
IO.puts(:stderr, "錯誤:#{message}")
|
||||
end
|
||||
|
||||
code
|
||||
end
|
||||
|
||||
defp require_id(nil, command), do: {:error, "#{command} 缺少 <id>", 2}
|
||||
defp require_id("", command), do: {:error, "#{command} 缺少 <id>", 2}
|
||||
defp require_id(_, _command), do: :ok
|
||||
|
||||
defp blank?(nil), do: true
|
||||
defp blank?(""), do: true
|
||||
defp blank?(_), do: false
|
||||
end
|
||||
@@ -37,7 +37,9 @@ defmodule BearCli.MixProject do
|
||||
[
|
||||
# HTTP 一律使用 Req(與 bear 主專案一致)。
|
||||
{:req, "~> 0.5"},
|
||||
{:jason, "~> 1.2"}
|
||||
{:jason, "~> 1.2"},
|
||||
# MFA setup 的 otpauth URI 本地 ASCII QR(§3.7.7)。
|
||||
{:eqrcode, "~> 0.2"}
|
||||
]
|
||||
end
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
%{
|
||||
"eqrcode": {:hex, :eqrcode, "0.2.1", "d12838813e8fc87b8940cc05f9baadb189031f6009facdc56ff074375ec73b6e", [:mix], [], "hexpm", "d5828a222b904c68360e7dc2a40c3ef33a1328b7c074583898040f389f928025"},
|
||||
"finch": {:hex, :finch, "0.23.0", "e3f9287ac25a8832f848b144c2b57346aac65b205e2e0629a52adfe6507fd837", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "80e58d3f936f57e3fdf404f83a3642897ae6d9fb642934e46da4d8fe761b99d5"},
|
||||
"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"},
|
||||
|
||||
@@ -0,0 +1,662 @@
|
||||
defmodule BearCli.SelfServiceTest do
|
||||
@moduledoc """
|
||||
`bear` 個人自助指令群單元測試(issue #11):注入 fake API,涵蓋
|
||||
解析、輸出、退出碼、互動輸入注入與 401/403/404/422/429 分流。
|
||||
"""
|
||||
|
||||
use ExUnit.Case, async: false
|
||||
|
||||
alias BearCli.{CLI, SelfService}
|
||||
|
||||
# -- fake API --
|
||||
|
||||
defmodule FakeApi do
|
||||
@profile %{
|
||||
"id" => "0190aaaa-0000-7000-8000-000000000001",
|
||||
"email" => "alice@example.com",
|
||||
"role" => "user",
|
||||
"name" => "Alice Chen",
|
||||
"given_name" => "Alice",
|
||||
"family_name" => "Chen",
|
||||
"nickname" => "ali",
|
||||
"preferred_username" => "alice",
|
||||
"locale" => "zh_TW",
|
||||
"zoneinfo" => "Asia/Taipei",
|
||||
"phone_number" => nil,
|
||||
"phone_number_verified" => false,
|
||||
"address" => nil,
|
||||
"mfa_enabled" => false,
|
||||
"created_at" => "2026-09-01T00:00:00Z",
|
||||
"updated_at" => "2026-09-01T00:00:00Z"
|
||||
}
|
||||
|
||||
@sessions [
|
||||
%{
|
||||
"id" => "0192a1b0-0000-7000-8000-0000000000aa",
|
||||
"ip" => "203.0.113.10",
|
||||
"user_agent" => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36",
|
||||
"created_at" => "2026-09-07T10:00:00Z",
|
||||
"last_seen_at" => "2026-09-08T09:00:00Z"
|
||||
}
|
||||
]
|
||||
|
||||
@tokens [
|
||||
%{
|
||||
"id" => "0192a1c0-0000-7000-8000-0000000000bb",
|
||||
"name" => "ci-token",
|
||||
"scope" => "openid profile email",
|
||||
"expires_at" => "2999-01-01T00:00:00Z",
|
||||
"revoked_at" => nil,
|
||||
"last_used_at" => "2026-09-08T08:00:00Z",
|
||||
"created_at" => "2026-09-01T00:00:00Z"
|
||||
}
|
||||
]
|
||||
|
||||
def error do
|
||||
Process.get(:fake_ss_error)
|
||||
end
|
||||
|
||||
def profile_get(_issuer, _token) do
|
||||
error() || {:ok, %{"data" => profile()}}
|
||||
end
|
||||
|
||||
def profile do
|
||||
Map.merge(@profile, Process.get(:fake_profile_overrides) || %{})
|
||||
end
|
||||
|
||||
def profile_update(_issuer, _token, attrs) do
|
||||
error() || {:ok, %{"data" => Map.merge(profile(), attrs)}}
|
||||
end
|
||||
|
||||
def profile_change_password(_issuer, _token, current, new) do
|
||||
cond do
|
||||
error() ->
|
||||
error()
|
||||
|
||||
current == "wrong-pass" ->
|
||||
{:error, :unprocessable_entity,
|
||||
%{"errors" => %{"current_password" => ["is incorrect"]}}}
|
||||
|
||||
byte_size(new) < 8 ->
|
||||
{:error, :unprocessable_entity,
|
||||
%{"errors" => %{"new_password" => ["must be at least 8 characters"]}}}
|
||||
|
||||
true ->
|
||||
{:ok, %{"data" => %{"updated" => true}}}
|
||||
end
|
||||
end
|
||||
|
||||
def profile_email_request_codes(_issuer, _token, new_email) do
|
||||
cond do
|
||||
error() ->
|
||||
error()
|
||||
|
||||
new_email == "alice@example.com" ->
|
||||
{:error, :unprocessable_entity,
|
||||
%{"error" => "same_email", "error_description" => "The new email must be different."}}
|
||||
|
||||
true ->
|
||||
{:ok, %{"data" => %{"sent" => true}}}
|
||||
end
|
||||
end
|
||||
|
||||
def profile_email_change(_issuer, _token, _new_email, current_code, _new_code) do
|
||||
cond do
|
||||
error() ->
|
||||
error()
|
||||
|
||||
current_code == "000000" ->
|
||||
{:error, :unprocessable_entity,
|
||||
%{"error" => "invalid_current_code", "error_description" => "incorrect"}}
|
||||
|
||||
true ->
|
||||
{:ok, %{"data" => %{"email" => "new@example.com"}}}
|
||||
end
|
||||
end
|
||||
|
||||
def sessions_list(_issuer, _token) do
|
||||
error() || {:ok, %{"data" => @sessions}}
|
||||
end
|
||||
|
||||
def sessions_revoke(_issuer, _token, id) do
|
||||
cond do
|
||||
error() ->
|
||||
error()
|
||||
|
||||
id == "missing" ->
|
||||
{:error, :not_found, "not_found"}
|
||||
|
||||
true ->
|
||||
{:ok, %{"data" => %{"revoked" => id}}}
|
||||
end
|
||||
end
|
||||
|
||||
def sessions_revoke_others(_issuer, _token) do
|
||||
error() || {:ok, %{"data" => %{"revoked_count" => 3}}}
|
||||
end
|
||||
|
||||
def tokens_list(_issuer, _token) do
|
||||
error() || {:ok, %{"data" => @tokens}}
|
||||
end
|
||||
|
||||
def tokens_create(_issuer, _token, name, expires_in) do
|
||||
cond do
|
||||
error() ->
|
||||
error()
|
||||
|
||||
name == " " ->
|
||||
{:error, :unprocessable_entity, %{"errors" => %{"name" => ["can't be blank"]}}}
|
||||
|
||||
true ->
|
||||
expires_at = if expires_in == "never", do: nil, else: "2999-01-01T00:00:00Z"
|
||||
|
||||
{:ok,
|
||||
%{
|
||||
"data" => %{
|
||||
"id" => "0192a1c0-0000-7000-8000-0000000000cc",
|
||||
"name" => name,
|
||||
"scope" => "openid profile email",
|
||||
"expires_at" => expires_at,
|
||||
"revoked_at" => nil,
|
||||
"last_used_at" => nil,
|
||||
"created_at" => "2026-09-09T00:00:00Z"
|
||||
},
|
||||
"token" => "9f3a-raw-token-once"
|
||||
}}
|
||||
end
|
||||
end
|
||||
|
||||
def tokens_revoke(_issuer, _token, id) do
|
||||
cond do
|
||||
error() ->
|
||||
error()
|
||||
|
||||
id == "missing" ->
|
||||
{:error, :not_found, "not_found"}
|
||||
|
||||
true ->
|
||||
{:ok, %{"data" => %{"revoked" => id}}}
|
||||
end
|
||||
end
|
||||
|
||||
def mfa_setup(_issuer, _token) do
|
||||
error() ||
|
||||
{:ok,
|
||||
%{"data" => %{"secret" => "JBSWY3DPEHPK3PXP", "otpauth_uri" => "otpauth://totp/Bear:x"}}}
|
||||
end
|
||||
|
||||
def mfa_setup_confirm(_issuer, _token, code) do
|
||||
cond do
|
||||
error() ->
|
||||
error()
|
||||
|
||||
code == "000000" ->
|
||||
{:error, :unprocessable_entity,
|
||||
%{"error" => "invalid_code", "error_description" => "Invalid verification code."}}
|
||||
|
||||
true ->
|
||||
{:ok, %{"data" => %{"enabled" => true, "recovery_codes" => ["rc-1", "rc-2"]}}}
|
||||
end
|
||||
end
|
||||
|
||||
def mfa_disable(_issuer, _token, code) do
|
||||
cond do
|
||||
error() ->
|
||||
error()
|
||||
|
||||
code == "000000" ->
|
||||
{:error, :unprocessable_entity,
|
||||
%{
|
||||
"error" => "invalid_code",
|
||||
"error_description" => "Invalid code. MFA was not disabled."
|
||||
}}
|
||||
|
||||
true ->
|
||||
{:ok, %{"data" => %{"enabled" => false}}}
|
||||
end
|
||||
end
|
||||
|
||||
def mfa_recovery_codes(_issuer, _token, code) do
|
||||
cond do
|
||||
error() ->
|
||||
error()
|
||||
|
||||
code == "000000" ->
|
||||
{:error, :unprocessable_entity,
|
||||
%{"error" => "invalid_code", "error_description" => "Invalid code."}}
|
||||
|
||||
true ->
|
||||
{:ok, %{"data" => %{"recovery_codes" => ["new-rc-1", "new-rc-2"]}}}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# 互動輸入注入:依序回應佇列中的值;prompt 前綴不影響。
|
||||
defmodule FakeIO do
|
||||
def prompt_secret(_label) do
|
||||
case Process.get(:fake_io_inputs) do
|
||||
[] ->
|
||||
:eof
|
||||
|
||||
[next | rest] ->
|
||||
Process.put(:fake_io_inputs, rest)
|
||||
{:ok, next}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# -- 測試輔助 --
|
||||
|
||||
setup do
|
||||
old_token = System.get_env("BEAR_TOKEN")
|
||||
old_creds = System.get_env("BEAR_CREDENTIALS")
|
||||
|
||||
on_exit(fn ->
|
||||
restore(old_token, "BEAR_TOKEN")
|
||||
restore(old_creds, "BEAR_CREDENTIALS")
|
||||
end)
|
||||
|
||||
System.put_env("BEAR_TOKEN", "user-pat")
|
||||
System.put_env("BEAR_CREDENTIALS", "/nonexistent/credentials.json")
|
||||
:ok
|
||||
end
|
||||
|
||||
defp run_out(argv, io_inputs \\ nil) do
|
||||
if io_inputs, do: Process.put(:fake_io_inputs, io_inputs)
|
||||
|
||||
opts = [ss_api: FakeApi, io: FakeIO, tty?: true]
|
||||
|
||||
ExUnit.CaptureIO.with_io(fn ->
|
||||
CLI.dispatch(CLI.parse(argv), opts)
|
||||
end)
|
||||
end
|
||||
|
||||
defp run_err(argv, io_inputs \\ nil) do
|
||||
if io_inputs, do: Process.put(:fake_io_inputs, io_inputs)
|
||||
|
||||
opts = [ss_api: FakeApi, io: FakeIO, tty?: true]
|
||||
|
||||
ExUnit.CaptureIO.with_io(:stderr, "", fn ->
|
||||
CLI.dispatch(CLI.parse(argv), opts)
|
||||
end)
|
||||
end
|
||||
|
||||
defp with_api_error(error) do
|
||||
Process.put(:fake_ss_error, error)
|
||||
end
|
||||
|
||||
defp restore(nil, key), do: System.delete_env(key)
|
||||
defp restore(value, key), do: System.put_env(key, value)
|
||||
|
||||
# -- 解析:用法錯誤(退出碼 2)--
|
||||
|
||||
test "unknown self-service command exits 2" do
|
||||
assert {:error, _msg, 2} = CLI.parse(["frobnicate"])
|
||||
end
|
||||
|
||||
test "profile without verb exits 2" do
|
||||
assert {:error, msg, 2} = CLI.parse(["profile"])
|
||||
assert msg =~ "profile 缺少子指令"
|
||||
end
|
||||
|
||||
test "profile unknown verb exits 2" do
|
||||
assert {:error, msg, 2} = CLI.parse(["profile", "delete"])
|
||||
assert msg =~ "未知的 profile 子指令"
|
||||
end
|
||||
|
||||
test "profile show with positional exits 2" do
|
||||
assert {:error, msg, 2} = CLI.parse(["profile", "show", "extra"])
|
||||
assert msg =~ "不接受位置參數"
|
||||
end
|
||||
|
||||
test "password unknown verb exits 2" do
|
||||
assert {:error, msg, 2} = CLI.parse(["password", "reset"])
|
||||
assert msg =~ "未知的 password 子指令"
|
||||
end
|
||||
|
||||
test "password change rejects positional args" do
|
||||
assert {:error, msg, 2} = CLI.parse(["password", "change", "secret"])
|
||||
assert msg =~ "不接受參數"
|
||||
end
|
||||
|
||||
test "email change missing --new exits 2 at runtime" do
|
||||
{code, err} = run_err(["email", "change"])
|
||||
assert code == 2
|
||||
assert err =~ "缺少 --new"
|
||||
end
|
||||
|
||||
test "sessions revoke missing id exits 2" do
|
||||
assert {:error, msg, 2} = CLI.parse(["sessions", "revoke"])
|
||||
assert msg =~ "缺少 <id>"
|
||||
end
|
||||
|
||||
test "tokens create missing --name exits 2" do
|
||||
assert {:error, msg, 2} = CLI.parse(["tokens", "create"])
|
||||
assert msg =~ "缺少 --name"
|
||||
end
|
||||
|
||||
test "tokens create invalid --expires-in exits 2" do
|
||||
{code, err} = run_err(["tokens", "create", "--name", "x", "--expires-in", "-5"])
|
||||
assert code == 2
|
||||
assert err =~ "--expires-in"
|
||||
end
|
||||
|
||||
test "mfa unknown verb exits 2" do
|
||||
assert {:error, msg, 2} = CLI.parse(["mfa", "enable"])
|
||||
assert msg =~ "未知的 mfa 子指令"
|
||||
end
|
||||
|
||||
# -- profile --
|
||||
|
||||
test "profile show prints fields" do
|
||||
{code, out} = run_out(["profile", "show"])
|
||||
assert code == 0
|
||||
assert out =~ "email"
|
||||
assert out =~ "alice@example.com"
|
||||
assert out =~ "mfa_enabled"
|
||||
end
|
||||
|
||||
test "profile show --json outputs spec shape" do
|
||||
{code, out} = run_out(["profile", "show", "--json"])
|
||||
assert code == 0
|
||||
assert {:ok, decoded} = Jason.decode(out)
|
||||
assert decoded["ok"] == true
|
||||
assert decoded["profile"]["email"] == "alice@example.com"
|
||||
end
|
||||
|
||||
test "profile set sends only given fields" do
|
||||
{code, out} = run_out(["profile", "set", "--name", "New Name", "--locale", "zh_TW"])
|
||||
assert code == 0
|
||||
assert out =~ "New Name"
|
||||
end
|
||||
|
||||
test "profile set without fields exits 2" do
|
||||
{code, err} = run_err(["profile", "set"])
|
||||
assert code == 2
|
||||
assert err =~ "未給任何欄位"
|
||||
end
|
||||
|
||||
test "profile set invalid gender exits 2 without request" do
|
||||
{code, err} = run_err(["profile", "set", "--gender", "robot"])
|
||||
assert code == 2
|
||||
assert err =~ "--gender"
|
||||
end
|
||||
|
||||
test "profile set invalid url exits 2" do
|
||||
{code, err} = run_err(["profile", "set", "--picture", "ftp://x"])
|
||||
assert code == 2
|
||||
assert err =~ "http(s)://"
|
||||
end
|
||||
|
||||
# -- password --
|
||||
|
||||
test "password change happy path" do
|
||||
{code, out} = run_out(["password", "change"], ["old-pass", "new-pass-9", "new-pass-9"])
|
||||
assert code == 0
|
||||
assert out =~ "密碼已變更"
|
||||
end
|
||||
|
||||
test "password change mismatched confirmation exits 2 locally" do
|
||||
{code, err} = run_err(["password", "change"], ["old", "new-pass-9", "different-9"])
|
||||
assert code == 2
|
||||
assert err =~ "不一致"
|
||||
end
|
||||
|
||||
test "password change wrong current password maps to 422 exit 1" do
|
||||
{code, err} = run_err(["password", "change"], ["wrong-pass", "new-pass-9", "new-pass-9"])
|
||||
assert code == 1
|
||||
assert err =~ "current_password"
|
||||
end
|
||||
|
||||
test "password change in non-TTY exits 2" do
|
||||
{code, _out} =
|
||||
ExUnit.CaptureIO.with_io(fn ->
|
||||
CLI.dispatch(
|
||||
CLI.parse(["password", "change"]),
|
||||
ss_api: FakeApi,
|
||||
tty?: false
|
||||
)
|
||||
end)
|
||||
|
||||
assert code == 2
|
||||
end
|
||||
|
||||
# -- email --
|
||||
|
||||
test "email change full flow" do
|
||||
{code, out} =
|
||||
run_out(["email", "change", "--new", "new@example.com"], ["111111", "222222"])
|
||||
|
||||
assert code == 0
|
||||
assert out =~ "email 已更新:new@example.com"
|
||||
end
|
||||
|
||||
test "email change same email maps 422 error to exit 1" do
|
||||
{code, err} =
|
||||
run_err(["email", "change", "--new", "alice@example.com"], ["111111", "222222"])
|
||||
|
||||
assert code == 1
|
||||
assert err =~ "same_email"
|
||||
end
|
||||
|
||||
test "email change invalid code maps to exit 1" do
|
||||
{code, err} =
|
||||
run_err(["email", "change", "--new", "new@example.com"], ["000000", "222222"])
|
||||
|
||||
assert code == 1
|
||||
assert err =~ "invalid_current_code"
|
||||
end
|
||||
|
||||
test "email change rate limited maps 429 to exit 1" do
|
||||
with_api_error({:error, :too_many_requests, %{"error" => "rate_limited"}})
|
||||
|
||||
{code, err} = run_err(["email", "change", "--new", "new@example.com"], [])
|
||||
assert code == 1
|
||||
assert err =~ "429"
|
||||
end
|
||||
|
||||
# -- sessions --
|
||||
|
||||
test "sessions list renders table" do
|
||||
{code, out} = run_out(["sessions", "list"])
|
||||
assert code == 0
|
||||
assert out =~ "ID"
|
||||
assert out =~ "203.0.113.10"
|
||||
assert out =~ "Mozilla/5.0"
|
||||
end
|
||||
|
||||
test "sessions list --json outputs spec shape" do
|
||||
{code, out} = run_out(["sessions", "list", "--json"])
|
||||
assert code == 0
|
||||
assert {:ok, decoded} = Jason.decode(out)
|
||||
assert decoded["ok"] == true
|
||||
assert length(decoded["sessions"]) == 1
|
||||
assert hd(decoded["sessions"])["user_agent"] =~ "Mozilla"
|
||||
end
|
||||
|
||||
test "sessions revoke prints confirmation" do
|
||||
{code, out} = run_out(["sessions", "revoke", "0192a1b0-0000"])
|
||||
assert code == 0
|
||||
assert out =~ "session 已撤銷"
|
||||
end
|
||||
|
||||
test "sessions revoke missing id maps 404 to exit 1" do
|
||||
{code, err} = run_err(["sessions", "revoke", "missing"])
|
||||
assert code == 1
|
||||
assert err =~ "404"
|
||||
end
|
||||
|
||||
test "sessions revoke-others prints count" do
|
||||
{code, out} = run_out(["sessions", "revoke-others"])
|
||||
assert code == 0
|
||||
assert out =~ "已撤銷 3 個其他 session"
|
||||
end
|
||||
|
||||
# -- tokens --
|
||||
|
||||
test "tokens list renders table with status" do
|
||||
{code, out} = run_out(["tokens", "list"])
|
||||
assert code == 0
|
||||
assert out =~ "ci-token"
|
||||
assert out =~ "active"
|
||||
end
|
||||
|
||||
test "tokens list --json outputs spec shape" do
|
||||
{code, out} = run_out(["tokens", "list", "--json"])
|
||||
assert code == 0
|
||||
assert {:ok, decoded} = Jason.decode(out)
|
||||
assert decoded["ok"] == true
|
||||
assert hd(decoded["tokens"])["name"] == "ci-token"
|
||||
# 明文絕不出現在 list
|
||||
refute out =~ "9f3a-raw-token-once"
|
||||
end
|
||||
|
||||
test "tokens create shows raw token exactly once" do
|
||||
{code, out} = run_out(["tokens", "create", "--name", "ci-token"])
|
||||
assert code == 0
|
||||
assert out =~ "PAT 已建立:ci-token"
|
||||
assert out =~ "9f3a-raw-token-once"
|
||||
assert out =~ "只顯示這一次"
|
||||
end
|
||||
|
||||
test "tokens create --json includes raw once" do
|
||||
{code, out} = run_out(["tokens", "create", "--name", "ci", "--json"])
|
||||
assert code == 0
|
||||
assert {:ok, decoded} = Jason.decode(out)
|
||||
assert decoded["raw"] == "9f3a-raw-token-once"
|
||||
end
|
||||
|
||||
test "tokens create never expiry" do
|
||||
{code, out} = run_out(["tokens", "create", "--name", "ci", "--expires-in", "never"])
|
||||
assert code == 0
|
||||
assert out =~ "無到期日"
|
||||
end
|
||||
|
||||
test "tokens revoke prints confirmation" do
|
||||
{code, out} = run_out(["tokens", "revoke", "0192a1c0-0000"])
|
||||
assert code == 0
|
||||
assert out =~ "PAT 已撤銷"
|
||||
end
|
||||
|
||||
# -- mfa --
|
||||
|
||||
test "mfa status shows disabled" do
|
||||
{code, out} = run_out(["mfa", "status"])
|
||||
assert code == 0
|
||||
assert out =~ "未啟用"
|
||||
end
|
||||
|
||||
test "mfa status shows enabled when totp on" do
|
||||
Process.put(:fake_profile_overrides, %{"mfa_enabled" => true})
|
||||
{code, out} = run_out(["mfa", "status"])
|
||||
assert code == 0
|
||||
assert out =~ "已啟用"
|
||||
after
|
||||
Process.delete(:fake_profile_overrides)
|
||||
end
|
||||
|
||||
test "mfa setup prints QR + secret then recovery codes" do
|
||||
{code, out} = run_out(["mfa", "setup"], ["123456"])
|
||||
assert code == 0
|
||||
assert out =~ "otpauth://totp/Bear:x"
|
||||
assert out =~ "JBSWY3DPEHPK3PXP"
|
||||
# QR 為 ASCII 區塊字元
|
||||
assert out =~ "█"
|
||||
assert out =~ "recovery codes"
|
||||
assert out =~ "rc-1"
|
||||
end
|
||||
|
||||
test "mfa setup --json does not print QR block" do
|
||||
{code, out} = run_out(["mfa", "setup", "--json"], ["123456"])
|
||||
assert code == 0
|
||||
assert {:ok, decoded} = Jason.decode(out)
|
||||
assert decoded["recovery_codes"] == ["rc-1", "rc-2"]
|
||||
end
|
||||
|
||||
test "mfa setup invalid code maps to exit 1" do
|
||||
{code, err} = run_err(["mfa", "setup"], ["000000"])
|
||||
assert code == 1
|
||||
assert err =~ "invalid_code"
|
||||
end
|
||||
|
||||
test "mfa setup already enabled maps 422 to exit 1" do
|
||||
with_api_error(
|
||||
{:error, :unprocessable_entity,
|
||||
%{"error" => "already_enabled", "error_description" => "MFA is already enabled."}}
|
||||
)
|
||||
|
||||
{code, err} = run_err(["mfa", "setup"], ["123456"])
|
||||
assert code == 1
|
||||
assert err =~ "already_enabled"
|
||||
end
|
||||
|
||||
test "mfa disable happy path" do
|
||||
{code, out} = run_out(["mfa", "disable"], ["123456"])
|
||||
assert code == 0
|
||||
assert out =~ "MFA 已停用"
|
||||
end
|
||||
|
||||
test "mfa recovery-codes regenerates" do
|
||||
{code, out} = run_out(["mfa", "recovery-codes"], ["123456"])
|
||||
assert code == 0
|
||||
assert out =~ "new-rc-1"
|
||||
assert out =~ "只顯示這一次"
|
||||
end
|
||||
|
||||
# -- 共通錯誤分流 --
|
||||
|
||||
test "401 maps to exit 3 with re-login hint" do
|
||||
with_api_error({:error, :unauthorized, "invalid_token"})
|
||||
|
||||
{code, err} = run_err(["profile", "show"])
|
||||
assert code == 3
|
||||
assert err =~ "bear login"
|
||||
end
|
||||
|
||||
test "403 maps to exit 8" do
|
||||
with_api_error({:error, :forbidden, "forbidden"})
|
||||
|
||||
{code, err} = run_err(["profile", "show"])
|
||||
assert code == 8
|
||||
assert err =~ "403"
|
||||
end
|
||||
|
||||
test "network error maps to exit 6" do
|
||||
with_api_error({:error, :network, "econnrefused"})
|
||||
|
||||
{code, err} = run_err(["profile", "show"])
|
||||
assert code == 6
|
||||
assert err =~ "econnrefused"
|
||||
end
|
||||
|
||||
test "server error maps to exit 6" do
|
||||
with_api_error({:error, :server_error, 500})
|
||||
|
||||
{code, err} = run_err(["profile", "show"])
|
||||
assert code == 6
|
||||
assert err =~ "500"
|
||||
end
|
||||
|
||||
test "not logged in exits 3" do
|
||||
System.delete_env("BEAR_TOKEN")
|
||||
|
||||
{code, err} = run_err(["profile", "show"])
|
||||
assert code == 3
|
||||
assert err =~ "未登入"
|
||||
end
|
||||
|
||||
# -- 直接模組層測試 --
|
||||
|
||||
test "SelfService.run/3 with injected api" do
|
||||
{code, out} =
|
||||
ExUnit.CaptureIO.with_io(fn ->
|
||||
SelfService.run(:profile, :show,
|
||||
ss_api: FakeApi,
|
||||
issuer: "https://alterminal.com"
|
||||
)
|
||||
end)
|
||||
|
||||
assert code == 0
|
||||
assert out =~ "alice@example.com"
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user