feat: Phase 1 WinAuth Go 移植完整实现
将原 C#/.NET WinAuth 移植为 Go + Gio GUI,覆盖 Phase 1 全部功能。 核心模块: - internal/authenticator: TOTP (Google/Microsoft/Okta) + HOTP + BattleNet + Steam,含 enroll/sync/code 生成、Steam 交易确认轮询 - internal/config: YAML 配置 + 老版 WinAuth XML 导入(DPAPI + Password + Blowfish/PBKDF2 解密链) - internal/crypto: 现代加密 (WAGO1) + DPAPI 跨平台封装 + 老版 Blowfish ECB - internal/win32: 单实例 Mutex 锁 + 全局热键管理器 (RegisterHotKey + PeekMessage 泵) + SendInput Unicode 注入 + 剪贴板文本/CF_DIB 图像读写 + AttachThreadInput 焦点切换 - internal/hotkey: "Ctrl+Alt+G" 风格快捷键字符串解析/格式化 - internal/qr: gozxing 二维码解码 + otpauth:// URI 解析 - internal/i18n: en/zh-CN/de 三语 TOML UI 模块 (Gio): - 主窗口:圆环倒计时进度条、复制按钮 + Toast 反馈、空列表占位、行分隔线 - 添加流程:vendor 菜单 + 各 vendor 独立对话框 + 二维码扫描入口(文件 / 剪贴板) - 设置:密码加密、老版 XML 导入、每条目热键配置 - Steam:注册向导(含 captcha/email/SMS 多步)+ 交易确认窗 构建:Windows 主目标,非 Windows 平台所有 Win32 功能走 build-tag 桩实现。
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// normalizeLegacySecretData hands the decrypted WinAuth SecretData string
|
||||
// off to the modern Entry.SecretRaw slot. The modern authenticator
|
||||
// SetSecretData methods already accept the exact C# WinAuth on-disk form
|
||||
// (tab-separated head with pipe-separated trailers), so the conversion
|
||||
// is mostly a sanity check.
|
||||
//
|
||||
// vendor is the value detectLegacyVendor produced and is used only to
|
||||
// catch obviously empty/malformed payloads early; the per-vendor parse
|
||||
// happens later in authenticator.SetSecretData.
|
||||
func normalizeLegacySecretData(vendor, secret string) (string, error) {
|
||||
secret = strings.TrimSpace(secret)
|
||||
if secret == "" {
|
||||
return "", errors.New("legacy entry: empty secret payload")
|
||||
}
|
||||
switch vendor {
|
||||
case "battlenet":
|
||||
// Either "<hex>\t...|<serialhex>" (modern C# form) or the
|
||||
// legacy WinAuth2 short form "<40 hex secret><utf8-hex serial>".
|
||||
// Both are accepted by BattleNetAuthenticator.SetSecretData.
|
||||
return secret, nil
|
||||
case "steam":
|
||||
// "<hex>\t...|serial|device|steamdata|session" — SetSecretData
|
||||
// also tolerates fewer fields.
|
||||
return secret, nil
|
||||
default:
|
||||
return secret, nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"git.wxccs.org/iceking2nd/winauth-go/internal/crypto"
|
||||
"git.wxccs.org/iceking2nd/winauth-go/internal/global"
|
||||
)
|
||||
|
||||
// LegacyAuthenticator is the partial WinAuth XML element we care about.
|
||||
// Fields not relevant to migration are ignored.
|
||||
type LegacyAuthenticator struct {
|
||||
XMLName xml.Name `xml:"WinAuthAuthenticator"`
|
||||
Type string `xml:"type,attr"`
|
||||
Name string `xml:"name"`
|
||||
AuthData struct {
|
||||
Encrypted string `xml:"encrypted,attr"`
|
||||
SecretData string `xml:"secretdata"`
|
||||
ServerTimeDiff string `xml:"servertimediff"`
|
||||
} `xml:"authenticatordata"`
|
||||
}
|
||||
|
||||
// legacyRoot matches the outer <WinAuth ...><authenticator>...</authenticator>
|
||||
// container the original WinAuthHelper.SaveAuthenticator writes.
|
||||
type legacyRoot struct {
|
||||
XMLName xml.Name `xml:"WinAuth"`
|
||||
Authenticators []LegacyAuthenticator `xml:"authenticator>WinAuthAuthenticator"`
|
||||
}
|
||||
|
||||
// LegacyPasswordType encodes the per-entry encryption layering of an old
|
||||
// WinAuth config. Multiple bits may be set: the original app supported
|
||||
// chained encryption like "yum" (password → user-DPAPI → machine-DPAPI).
|
||||
type LegacyPasswordType int
|
||||
|
||||
const (
|
||||
LegacyPasswordNone LegacyPasswordType = 0
|
||||
LegacyPasswordExplicit LegacyPasswordType = 1 << iota // 'y' — PBKDF2-SHA1 + Blowfish
|
||||
LegacyPasswordUser // 'u' — User-scope DPAPI
|
||||
LegacyPasswordMachine // 'm' — Machine-scope DPAPI
|
||||
)
|
||||
|
||||
// ErrLegacyPasswordRequired is returned by LoadLegacyXML when at least
|
||||
// one entry has the 'y' bit set but the caller did not supply a
|
||||
// passphrase. The caller is expected to prompt the user and retry.
|
||||
var ErrLegacyPasswordRequired = errors.New("legacy XML: password required")
|
||||
|
||||
// ErrLegacyPasswordWrong is returned when the supplied passphrase
|
||||
// successfully unprotects DPAPI layers but the resulting Blowfish output
|
||||
// fails to look like sensible UTF-8 secret data — almost always a wrong
|
||||
// password since the legacy format has no MAC.
|
||||
var ErrLegacyPasswordWrong = errors.New("legacy XML: wrong password")
|
||||
|
||||
// parseLegacyEncryptionFlags maps the encrypted-attribute string ("y",
|
||||
// "ymu", "um", ...) to a flag bitmask. Unknown letters are ignored.
|
||||
func parseLegacyEncryptionFlags(s string) LegacyPasswordType {
|
||||
var f LegacyPasswordType
|
||||
for _, c := range strings.ToLower(strings.TrimSpace(s)) {
|
||||
switch c {
|
||||
case 'y':
|
||||
f |= LegacyPasswordExplicit
|
||||
case 'u':
|
||||
f |= LegacyPasswordUser
|
||||
case 'm':
|
||||
f |= LegacyPasswordMachine
|
||||
}
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// LegacyXMLNeedsPassword reports whether any entry in the file uses the
|
||||
// 'y' password layer, so the UI knows to prompt before calling
|
||||
// LoadLegacyXML with the user-supplied password.
|
||||
func LegacyXMLNeedsPassword(path string) (bool, error) {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var root legacyRoot
|
||||
if err := xml.Unmarshal(raw, &root); err != nil {
|
||||
return false, fmt.Errorf("legacy XML: %w", err)
|
||||
}
|
||||
for _, a := range root.Authenticators {
|
||||
if parseLegacyEncryptionFlags(a.AuthData.Encrypted)&LegacyPasswordExplicit != 0 {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// LoadLegacyXML reads an old WinAuth XML config (the one stored at
|
||||
// %APPDATA%\WinAuth\winauth.xml). password may be nil if the file is
|
||||
// fully unencrypted, but it must be supplied if any entry carries the
|
||||
// 'y' password bit, otherwise ErrLegacyPasswordRequired is returned.
|
||||
//
|
||||
// Entries that cannot be decrypted (e.g. DPAPI blob produced by a
|
||||
// different Windows user / on a different machine) are logged and
|
||||
// skipped — partial migration is better than aborting.
|
||||
func LoadLegacyXML(path string, password []byte) (*Config, error) {
|
||||
const fn = "internal.config.LoadLegacyXML"
|
||||
logger := global.Log.WithField("func", fn).WithField("path", path)
|
||||
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var root legacyRoot
|
||||
if err := xml.Unmarshal(raw, &root); err != nil {
|
||||
return nil, fmt.Errorf("legacy XML: %w", err)
|
||||
}
|
||||
|
||||
// Pre-flight: refuse early so the UI can switch to password prompt
|
||||
// without us having partially decrypted some unprotected entries.
|
||||
for _, a := range root.Authenticators {
|
||||
flags := parseLegacyEncryptionFlags(a.AuthData.Encrypted)
|
||||
if flags&LegacyPasswordExplicit != 0 && len(password) == 0 {
|
||||
return nil, ErrLegacyPasswordRequired
|
||||
}
|
||||
}
|
||||
|
||||
cfg := &Config{Version: 1}
|
||||
for _, a := range root.Authenticators {
|
||||
entryLogger := logger.WithField("name", a.Name)
|
||||
flags := parseLegacyEncryptionFlags(a.AuthData.Encrypted)
|
||||
|
||||
plaintext, err := decryptLegacySecretData(a.AuthData.SecretData, flags, password)
|
||||
if err != nil {
|
||||
entryLogger.WithError(err).Warn("skip entry: decrypt failed")
|
||||
continue
|
||||
}
|
||||
|
||||
entry, err := convertLegacyEntry(a, plaintext)
|
||||
if err != nil {
|
||||
entryLogger.WithError(err).Warn("skip entry: conversion failed")
|
||||
continue
|
||||
}
|
||||
cfg.Entries = append(cfg.Entries, entry)
|
||||
}
|
||||
logger.WithField("entries", len(cfg.Entries)).Debug("legacy config imported")
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// decryptLegacySecretData reverses the layered encryption WinAuth wrote.
|
||||
// Each layer expects a hex string and produces a hex string (the final
|
||||
// layer's hex decodes to UTF-8 secret data). Order of removal is the
|
||||
// reverse of the original encryption order: User-DPAPI, then
|
||||
// Machine-DPAPI, then explicit Password.
|
||||
func decryptLegacySecretData(data string, flags LegacyPasswordType, password []byte) (string, error) {
|
||||
data = strings.TrimSpace(data)
|
||||
if data == "" || flags == LegacyPasswordNone {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
if flags&LegacyPasswordUser != 0 {
|
||||
blob, err := hex.DecodeString(data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("user-DPAPI: hex decode: %w", err)
|
||||
}
|
||||
out, err := crypto.Unprotect(blob, nil, crypto.DPAPIScopeCurrentUser)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("user-DPAPI: %w", err)
|
||||
}
|
||||
data = hex.EncodeToString(out)
|
||||
}
|
||||
|
||||
if flags&LegacyPasswordMachine != 0 {
|
||||
blob, err := hex.DecodeString(data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("machine-DPAPI: hex decode: %w", err)
|
||||
}
|
||||
out, err := crypto.Unprotect(blob, nil, crypto.DPAPIScopeLocalMachine)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("machine-DPAPI: %w", err)
|
||||
}
|
||||
data = hex.EncodeToString(out)
|
||||
}
|
||||
|
||||
if flags&LegacyPasswordExplicit != 0 {
|
||||
// First 16 hex chars = 8-byte salt; rest is Blowfish ciphertext.
|
||||
const saltHexLen = 16
|
||||
if len(data) < saltHexLen {
|
||||
return "", errors.New("explicit: payload shorter than salt")
|
||||
}
|
||||
saltHex, bodyHex := data[:saltHexLen], data[saltHexLen:]
|
||||
salt, err := hex.DecodeString(saltHex)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("explicit: salt hex decode: %w", err)
|
||||
}
|
||||
key := crypto.DerivePBKDF2SHA1(password, salt)
|
||||
defer func() {
|
||||
for i := range key {
|
||||
key[i] = 0
|
||||
}
|
||||
}()
|
||||
plain, err := crypto.LegacyDecryptBlowfish(bodyHex, key)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("explicit: %w", err)
|
||||
}
|
||||
// The Blowfish output should itself be a hex string representing
|
||||
// the next inner layer (or the UTF-8 secret data). A wrong
|
||||
// password almost always lands here producing garbage bytes;
|
||||
// check that the result is printable ASCII to reject it.
|
||||
if !looksLikeLegacyPlaintext(plain) {
|
||||
return "", ErrLegacyPasswordWrong
|
||||
}
|
||||
data = string(plain)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// looksLikeLegacyPlaintext returns true if buf reads as a printable
|
||||
// ASCII string of the kind WinAuth writes for SecretData (tab-separated
|
||||
// hex, pipe-separated serial, or JSON). Non-printable bytes nearly
|
||||
// always indicate a bad password since legacy Blowfish has no MAC.
|
||||
func looksLikeLegacyPlaintext(buf []byte) bool {
|
||||
if len(buf) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, b := range buf {
|
||||
if b == '\t' || b == '\n' || b == '\r' || (b >= 0x20 && b < 0x7f) {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// convertLegacyEntry takes one parsed authenticator block and its
|
||||
// decrypted secret-data payload and turns it into a modern Entry.
|
||||
// Vendor-specific quirks (Battle.Net serial trailer, Steam JSON, ...)
|
||||
// live in the per-vendor helpers in legacy_secretdata.go.
|
||||
func convertLegacyEntry(a LegacyAuthenticator, secret string) (Entry, error) {
|
||||
vendor := detectLegacyVendor(a.Type)
|
||||
raw, err := normalizeLegacySecretData(vendor, secret)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
return Entry{
|
||||
Name: a.Name,
|
||||
Vendor: vendor,
|
||||
SecretRaw: raw,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func detectLegacyVendor(typeAttr string) string {
|
||||
t := strings.ToLower(typeAttr)
|
||||
switch {
|
||||
case strings.Contains(t, "battlenet"):
|
||||
return "battlenet"
|
||||
case strings.Contains(t, "steam"):
|
||||
return "steam"
|
||||
case strings.Contains(t, "microsoft"):
|
||||
return "microsoft"
|
||||
case strings.Contains(t, "oktaverify"):
|
||||
return "okta"
|
||||
case strings.Contains(t, "hotp"):
|
||||
return "hotp"
|
||||
default:
|
||||
return "google"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.wxccs.org/iceking2nd/winauth-go/internal/crypto"
|
||||
)
|
||||
|
||||
// TestParseLegacyEncryptionFlags covers the encrypted-attribute parsing
|
||||
// for the three letters WinAuth actually wrote, in every legal order
|
||||
// plus the empty / unknown-letter cases.
|
||||
func TestParseLegacyEncryptionFlags(t *testing.T) {
|
||||
cases := map[string]LegacyPasswordType{
|
||||
"": LegacyPasswordNone,
|
||||
"y": LegacyPasswordExplicit,
|
||||
"u": LegacyPasswordUser,
|
||||
"m": LegacyPasswordMachine,
|
||||
"yum": LegacyPasswordExplicit | LegacyPasswordUser | LegacyPasswordMachine,
|
||||
"YMU": LegacyPasswordExplicit | LegacyPasswordUser | LegacyPasswordMachine,
|
||||
" yu ": LegacyPasswordExplicit | LegacyPasswordUser,
|
||||
"abc": LegacyPasswordNone,
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := parseLegacyEncryptionFlags(in); got != want {
|
||||
t.Errorf("parseLegacyEncryptionFlags(%q) = %v, want %v", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestDecryptLegacyExplicitRoundTrip encrypts a known plaintext using
|
||||
// the helpers and round-trips it through decryptLegacySecretData to
|
||||
// catch any salt-layout / PBKDF2 / Blowfish drift.
|
||||
func TestDecryptLegacyExplicitRoundTrip(t *testing.T) {
|
||||
plaintext := "ABCDEF1234\t6\tSHA1\t30"
|
||||
password := []byte("hunter2")
|
||||
salt := []byte{1, 2, 3, 4, 5, 6, 7, 8}
|
||||
|
||||
key := crypto.DerivePBKDF2SHA1(password, salt)
|
||||
body, err := crypto.LegacyEncryptBlowfish([]byte(plaintext), key)
|
||||
if err != nil {
|
||||
t.Fatalf("encrypt: %v", err)
|
||||
}
|
||||
payload := hex.EncodeToString(salt) + body
|
||||
|
||||
got, err := decryptLegacySecretData(payload, LegacyPasswordExplicit, password)
|
||||
if err != nil {
|
||||
t.Fatalf("decrypt: %v", err)
|
||||
}
|
||||
if got != plaintext {
|
||||
t.Errorf("round trip mismatch: got %q want %q", got, plaintext)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDecryptLegacyExplicitWrongPassword verifies the printable-ASCII
|
||||
// heuristic flags a bad passphrase rather than returning garbage to the
|
||||
// caller. Two random passwords almost certainly produce non-printable
|
||||
// Blowfish output of length 8 or more.
|
||||
func TestDecryptLegacyExplicitWrongPassword(t *testing.T) {
|
||||
plaintext := "ABCDEF1234\t6\tSHA1\t30"
|
||||
salt := []byte{9, 9, 9, 9, 9, 9, 9, 9}
|
||||
|
||||
key := crypto.DerivePBKDF2SHA1([]byte("correct"), salt)
|
||||
body, err := crypto.LegacyEncryptBlowfish([]byte(plaintext), key)
|
||||
if err != nil {
|
||||
t.Fatalf("encrypt: %v", err)
|
||||
}
|
||||
payload := hex.EncodeToString(salt) + body
|
||||
|
||||
_, err = decryptLegacySecretData(payload, LegacyPasswordExplicit, []byte("wrong"))
|
||||
if err == nil {
|
||||
t.Fatal("expected wrong-password rejection, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLooksLikeLegacyPlaintext covers the ASCII-printable heuristic.
|
||||
func TestLooksLikeLegacyPlaintext(t *testing.T) {
|
||||
if !looksLikeLegacyPlaintext([]byte("ABC\t123|x")) {
|
||||
t.Error("printable string should pass")
|
||||
}
|
||||
if looksLikeLegacyPlaintext([]byte{0x00, 0x01, 0x02}) {
|
||||
t.Error("control bytes should fail")
|
||||
}
|
||||
if looksLikeLegacyPlaintext(nil) {
|
||||
t.Error("empty buffer should fail")
|
||||
}
|
||||
// High bit / extended ASCII should also fail — WinAuth never wrote
|
||||
// non-ASCII into <secretdata>.
|
||||
if looksLikeLegacyPlaintext([]byte{0xff, 'A'}) {
|
||||
t.Error("high bit should fail")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadLegacyXMLPlaintext walks the full XML → Entry path with an
|
||||
// unencrypted Google entry and an encrypted entry the caller skipped
|
||||
// the password for; the encrypted one should be skipped and the
|
||||
// plaintext one returned.
|
||||
func TestLoadLegacyXMLPlaintext(t *testing.T) {
|
||||
const sample = `<?xml version="1.0"?>
|
||||
<WinAuth version="3.5">
|
||||
<authenticator>
|
||||
<WinAuthAuthenticator type="GoogleAuthenticator">
|
||||
<name>plain</name>
|
||||
<authenticatordata encrypted="">
|
||||
<secretdata>ABCDEF1234 6 SHA1 30</secretdata>
|
||||
<servertimediff>0</servertimediff>
|
||||
</authenticatordata>
|
||||
</WinAuthAuthenticator>
|
||||
</authenticator>
|
||||
</WinAuth>`
|
||||
|
||||
path := writeTempXML(t, sample)
|
||||
cfg, err := LoadLegacyXML(path, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("load: %v", err)
|
||||
}
|
||||
if len(cfg.Entries) != 1 {
|
||||
t.Fatalf("entries=%d, want 1", len(cfg.Entries))
|
||||
}
|
||||
if cfg.Entries[0].Vendor != "google" || cfg.Entries[0].Name != "plain" {
|
||||
t.Errorf("entry mismatch: %+v", cfg.Entries[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadLegacyXMLPasswordRequired(t *testing.T) {
|
||||
const sample = `<?xml version="1.0"?>
|
||||
<WinAuth>
|
||||
<authenticator>
|
||||
<WinAuthAuthenticator type="GoogleAuthenticator">
|
||||
<name>locked</name>
|
||||
<authenticatordata encrypted="y">
|
||||
<secretdata>0102030405060708abcdef</secretdata>
|
||||
</authenticatordata>
|
||||
</WinAuthAuthenticator>
|
||||
</authenticator>
|
||||
</WinAuth>`
|
||||
path := writeTempXML(t, sample)
|
||||
if _, err := LoadLegacyXML(path, nil); err == nil ||
|
||||
!strings.Contains(err.Error(), "password required") {
|
||||
t.Fatalf("want password-required error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func writeTempXML(t *testing.T, body string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "winauth.xml")
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// Package config defines the persistent shape of a winauth-go config and
|
||||
// provides loaders for both the new YAML format and the legacy WinAuth
|
||||
// XML format produced by the original C# application.
|
||||
package config
|
||||
|
||||
// Entry is a serialized authenticator inside the config file. Vendor
|
||||
// determines how Data is interpreted by the authenticator package's
|
||||
// SetSecretData method.
|
||||
type Entry struct {
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Vendor string `yaml:"vendor" json:"vendor"` // google|microsoft|okta|hotp|battlenet|steam
|
||||
IconName string `yaml:"icon" json:"icon,omitempty"`
|
||||
SecretRaw string `yaml:"secret" json:"secret"` // value returned by Authenticator.SecretData()
|
||||
// Hotkey is a human-readable global hotkey like "Ctrl+Alt+G". Empty
|
||||
// means no hotkey. Parsed by internal/hotkey.Parse — invalid strings
|
||||
// log a warning at registration time and are otherwise ignored.
|
||||
Hotkey string `yaml:"hotkey,omitempty" json:"hotkey,omitempty"`
|
||||
}
|
||||
|
||||
// Config is the top-level file shape. Entries are stored unencrypted by
|
||||
// default; if Encrypted is true, EncryptedBlob holds a WAGO1 base64 ciphertext
|
||||
// produced by internal/crypto.EncryptModern and Entries is empty on disk.
|
||||
type Config struct {
|
||||
Version int `yaml:"version" json:"version"`
|
||||
Language string `yaml:"language,omitempty" json:"language,omitempty"`
|
||||
Encrypted bool `yaml:"encrypted" json:"encrypted"`
|
||||
EncryptedBlob string `yaml:"encrypted_blob,omitempty" json:"encrypted_blob,omitempty"`
|
||||
Entries []Entry `yaml:"entries,omitempty" json:"entries,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// DefaultPath returns the default location for the YAML config file. On
|
||||
// Windows we follow the same convention as the legacy WinAuth and use
|
||||
// %APPDATA%\winauth-go\config.yaml. On other platforms we honor
|
||||
// $XDG_CONFIG_HOME (falling back to ~/.config) and use the standard
|
||||
// winauth-go subdirectory.
|
||||
func DefaultPath() string {
|
||||
if p := envConfigPath(); p != "" {
|
||||
return p
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
if dir := os.Getenv("APPDATA"); dir != "" {
|
||||
return filepath.Join(dir, "winauth-go", "config.yaml")
|
||||
}
|
||||
}
|
||||
if dir := os.Getenv("XDG_CONFIG_HOME"); dir != "" {
|
||||
return filepath.Join(dir, "winauth-go", "config.yaml")
|
||||
}
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
return filepath.Join(home, ".config", "winauth-go", "config.yaml")
|
||||
}
|
||||
return "winauth.yaml"
|
||||
}
|
||||
|
||||
func envConfigPath() string {
|
||||
return os.Getenv("WINAUTH_GO_CONFIG")
|
||||
}
|
||||
|
||||
// EnsureDir creates the parent directory of path with 0o700 permissions
|
||||
// (best effort). Returns nil if creation succeeds or the directory already
|
||||
// exists.
|
||||
func EnsureDir(path string) error {
|
||||
return os.MkdirAll(filepath.Dir(path), 0o700)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"git.wxccs.org/iceking2nd/winauth-go/internal/crypto"
|
||||
"git.wxccs.org/iceking2nd/winauth-go/internal/global"
|
||||
)
|
||||
|
||||
// Sentinel errors returned by LoadYAML for the encrypted-config password
|
||||
// path. Callers use errors.Is to distinguish them from generic I/O / parse
|
||||
// failures.
|
||||
var (
|
||||
ErrPasswordRequired = errors.New("config: passphrase required")
|
||||
ErrPasswordWrong = errors.New("config: wrong passphrase")
|
||||
)
|
||||
|
||||
// SaveYAML writes the receiver as YAML to path. If passphrase is non-empty
|
||||
// and cfg.Encrypted is true, the entries slice is serialized to JSON,
|
||||
// encrypted, and stored as EncryptedBlob — entries are NOT written in
|
||||
// plaintext in that case.
|
||||
func SaveYAML(cfg *Config, path string, passphrase []byte) error {
|
||||
const fn = "internal.config.SaveYAML"
|
||||
logger := global.Log.WithField("func", fn).WithField("path", path)
|
||||
|
||||
out := *cfg
|
||||
if cfg.Encrypted && len(passphrase) > 0 {
|
||||
raw, err := json.Marshal(cfg.Entries)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
blob, err := crypto.EncryptModern(raw, passphrase)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out.EncryptedBlob = blob
|
||||
out.Entries = nil
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(&out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := EnsureDir(path); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
logger.Debug("config saved")
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadYAML reads the YAML config at path. If the file is encrypted,
|
||||
// passphrase is required and the EncryptedBlob is decrypted into Entries.
|
||||
func LoadYAML(path string, passphrase []byte) (*Config, error) {
|
||||
const fn = "internal.config.LoadYAML"
|
||||
logger := global.Log.WithField("func", fn).WithField("path", path)
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var cfg Config
|
||||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("config: parse YAML: %w", err)
|
||||
}
|
||||
|
||||
if cfg.Encrypted && cfg.EncryptedBlob != "" {
|
||||
if len(passphrase) == 0 {
|
||||
return &cfg, ErrPasswordRequired
|
||||
}
|
||||
raw, err := crypto.DecryptModern(cfg.EncryptedBlob, passphrase)
|
||||
if err != nil {
|
||||
return &cfg, ErrPasswordWrong
|
||||
}
|
||||
if err := json.Unmarshal(raw, &cfg.Entries); err != nil {
|
||||
return nil, fmt.Errorf("config: decode entries: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
logger.WithField("entries", len(cfg.Entries)).Debug("config loaded")
|
||||
return &cfg, nil
|
||||
}
|
||||
Reference in New Issue
Block a user