1
0
forked from um/cli
cli/algo/qmc/key_mmkv.go

168 lines
4.3 KiB
Go
Raw Normal View History

2022-12-04 16:06:38 +00:00
package qmc
import (
2024-02-05 00:41:40 +00:00
"bytes"
"encoding/base64"
2022-12-04 16:06:38 +00:00
"errors"
"fmt"
2024-02-05 00:41:40 +00:00
"io"
2022-12-04 16:06:38 +00:00
"os"
"path/filepath"
"runtime"
2024-02-05 00:41:40 +00:00
"git.unlock-music.dev/awalol/go-mmkv"
"github.com/samber/lo"
2022-12-05 00:54:40 +00:00
"go.uber.org/zap"
"golang.org/x/exp/slices"
"golang.org/x/text/unicode/norm"
2022-12-04 16:06:38 +00:00
)
2022-12-04 23:24:03 +00:00
var streamKeyVault mmkv.Vault
2022-12-04 16:06:38 +00:00
2022-12-05 00:54:40 +00:00
// TODO: move to factory
func readKeyFromMMKV(file string, logger *zap.Logger) ([]byte, error) {
2022-12-04 16:06:38 +00:00
if file == "" {
return nil, errors.New("file path is required while reading key from mmkv")
}
//goland:noinspection GoBoolExpressions
if runtime.GOOS != "darwin" {
return nil, errors.New("mmkv vault not supported on this platform")
}
if streamKeyVault == nil {
mmkvDir, err := getRelativeMMKVDir(file)
if err != nil {
mmkvDir, err = getDefaultMMKVDir()
if err != nil {
return nil, fmt.Errorf("mmkv key valut not found: %w", err)
}
}
2022-12-05 00:54:40 +00:00
2022-12-04 23:24:03 +00:00
mgr, err := mmkv.NewManager(mmkvDir)
if err != nil {
return nil, fmt.Errorf("init mmkv manager: %w", err)
}
streamKeyVault, err = mgr.OpenVault("MMKVStreamEncryptId")
if err != nil {
return nil, fmt.Errorf("open mmkv vault: %w", err)
}
2022-12-05 00:54:40 +00:00
logger.Debug("mmkv vault opened", zap.Strings("keys", streamKeyVault.Keys()))
2022-12-04 16:06:38 +00:00
}
_, partName := filepath.Split(file)
partName = normalizeUnicode(partName)
buf, err := streamKeyVault.GetBytes(file)
if buf == nil {
filePaths := streamKeyVault.Keys()
fileNames := lo.Map(filePaths, func(filePath string, _ int) string {
_, name := filepath.Split(filePath)
return normalizeUnicode(name)
})
for _, key := range fileNames { // fallback: match filename only
if key != partName {
2022-12-04 23:24:03 +00:00
continue
}
idx := slices.Index(fileNames, key)
buf, err = streamKeyVault.GetBytes(filePaths[idx])
2022-12-04 23:24:03 +00:00
if err != nil {
logger.Warn("read key from mmkv", zap.String("key", filePaths[idx]), zap.Error(err))
2022-12-04 16:06:38 +00:00
}
}
2022-12-04 16:06:38 +00:00
}
if len(buf) == 0 {
return nil, errors.New("key not found in mmkv vault")
}
return deriveKey(buf)
}
2024-02-05 00:41:40 +00:00
func readKeyFromMMKVCustom(d *Decoder) ([]byte, error) {
logger := d.logger
filePath, fileName := filepath.Split(VaultPath)
if streamKeyVault == nil {
mgr, err := mmkv.NewManager(filepath.Dir(filePath))
if err != nil {
return nil, fmt.Errorf("init mmkv manager: %w", err)
}
streamKeyVault, err = mgr.OpenVaultCrypto(fileName, VaultKey)
if err != nil {
return nil, fmt.Errorf("open mmkv vault: %w", err)
}
logger.Debug("mmkv vault opened", zap.Strings("keys", streamKeyVault.Keys()))
}
// 获取mid即数据库键值
_, err := d.raw.Seek(-128, io.SeekEnd)
if err != nil {
return nil, fmt.Errorf("get mid error: %w", err)
}
mid, err := io.ReadAll(io.LimitReader(d.raw, 64)) // 取64字节确保完全取完
mid = bytes.ReplaceAll(mid, []byte{0x00}, []byte{}) // clean NUL
mid = bytes.Trim(mid, "\0000") // maybe a little stupid
// 从数据库获取eKey
eKey, err := streamKeyVault.GetBytes(string(mid))
if err != nil {
return nil, fmt.Errorf("get eKey error: %w", err)
}
n, err := base64.StdEncoding.Decode(eKey, eKey)
if err != nil {
return nil, fmt.Errorf("base64 error: %w", err)
}
return deriveKeyV1(eKey[:n])
}
2022-12-04 16:06:38 +00:00
func getRelativeMMKVDir(file string) (string, error) {
mmkvDir := filepath.Join(filepath.Dir(file), "../mmkv")
if _, err := os.Stat(mmkvDir); err != nil {
return "", fmt.Errorf("stat default mmkv dir: %w", err)
}
keyFile := filepath.Join(mmkvDir, "MMKVStreamEncryptId")
if _, err := os.Stat(keyFile); err != nil {
return "", fmt.Errorf("stat default mmkv file: %w", err)
}
return mmkvDir, nil
}
func getDefaultMMKVDir() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("get user home dir: %w", err)
}
mmkvDir := filepath.Join(
homeDir,
"Library/Containers/com.tencent.QQMusicMac/Data", // todo: make configurable
"Library/Application Support/QQMusicMac/mmkv",
)
if _, err := os.Stat(mmkvDir); err != nil {
return "", fmt.Errorf("stat default mmkv dir: %w", err)
}
keyFile := filepath.Join(mmkvDir, "MMKVStreamEncryptId")
if _, err := os.Stat(keyFile); err != nil {
return "", fmt.Errorf("stat default mmkv file: %w", err)
}
return mmkvDir, nil
}
2022-12-05 03:10:40 +00:00
// normalizeUnicode normalizes unicode string to NFC.
// since macOS may change some characters in the file name.
// e.g. "ぜ"(e3 81 9c) -> "ぜ"(e3 81 9b e3 82 99)
func normalizeUnicode(str string) string {
return norm.NFC.String(str)
}