feat: 實作 bear CLI 骨架與 PAT 模式共用基礎(issue #6)
- 專案骨架:Elixir + Mix escript(單檔可執行 bear),HTTP 一律 Req - 設定/憑證檔讀寫:0600、原子寫入(rename)、O_CREAT|O_EXCL 防 symlink - PAT Bearer 呼叫 /userinfo;--json 輸出;規格化退出碼 - 補齊 main 規格承諾的 BEAR_TOKEN 環境變數(優先於憑證檔、不寫入) - login 無效 PAT 退出碼 3(依 docs/commands.md §3.1);token --refresh 用法錯誤 2(§3.3) - 35 個單元測試;mix precommit(compile --warnings-as-errors + format + test)全綠 - 沿用已關閉 PR #3 的實作(feat/pat-mode-mvp 分支),文件改依 main 現行版本更新 apps 管理指令待 #5 規格與 alterminal/bear#28 API 就緒後實作。
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user