Полный продакшен-рефактор fix25: split peer/admin, удаление legacy, шифрование secret, auth_id, новые API/роуты и зачистка subscription
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"hy2xs-admin/dao"
|
||||
"hy2xs-admin/model/constant"
|
||||
"hy2xs-admin/model/entity"
|
||||
"hy2xs-admin/util"
|
||||
)
|
||||
|
||||
func getOrCreateConfigKey(key string, size int) (string, error) {
|
||||
cfg, err := dao.GetConfig("key = ?", key)
|
||||
if err == nil && cfg.Value != nil && strings.TrimSpace(*cfg.Value) != "" {
|
||||
return strings.TrimSpace(*cfg.Value), nil
|
||||
}
|
||||
raw, genErr := util.RandomString(size)
|
||||
if genErr != nil {
|
||||
return "", genErr
|
||||
}
|
||||
value := raw
|
||||
remark := key
|
||||
if _, saveErr := dao.SaveConfig(entity.Config{Key: &key, Value: &value, Remark: &remark}); saveErr != nil {
|
||||
if updErr := dao.UpdateConfig([]string{key}, map[string]interface{}{"value": value}); updErr != nil {
|
||||
return "", updErr
|
||||
}
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func GetPeerSecretKey() (string, error) {
|
||||
return getOrCreateConfigKey(constant.PeerSecretKey, 48)
|
||||
}
|
||||
|
||||
func getPeerSecretEncryptionKey() ([]byte, error) {
|
||||
raw, err := getOrCreateConfigKey(constant.PeerSecretEncryptionKey, 32)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
decoded, decErr := util.DecodeBase64Key(raw, 32)
|
||||
if decErr == nil {
|
||||
return decoded, nil
|
||||
}
|
||||
// legacy/plain bootstrap path: convert to stable base64 once
|
||||
plain := []byte(strings.TrimSpace(raw))
|
||||
if len(plain) < 32 {
|
||||
return nil, errors.New("invalid peer secret encryption key")
|
||||
}
|
||||
plain = plain[:32]
|
||||
encoded := base64.StdEncoding.EncodeToString(plain)
|
||||
if updErr := dao.UpdateConfig([]string{constant.PeerSecretEncryptionKey}, map[string]interface{}{"value": encoded}); updErr != nil {
|
||||
return nil, updErr
|
||||
}
|
||||
return plain, nil
|
||||
}
|
||||
|
||||
func PeerSecretDigest(rawSecret string) (string, error) {
|
||||
secretKey, err := GetPeerSecretKey()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return util.HmacSHA256Hex(rawSecret, secretKey), nil
|
||||
}
|
||||
|
||||
func EncryptPeerSecret(rawSecret string) (string, error) {
|
||||
key, err := getPeerSecretEncryptionKey()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return util.EncryptAESGCM(rawSecret, key)
|
||||
}
|
||||
|
||||
func DecryptPeerSecret(stored string) (string, error) {
|
||||
if !strings.HasPrefix(stored, "v1:") {
|
||||
return stored, nil
|
||||
}
|
||||
key, err := getPeerSecretEncryptionKey()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return util.DecryptAESGCM(stored, key)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user