feat: 增加在线语音 SDK 和音色管理后台,完善引擎适配

This commit is contained in:
tongtong committed 2026-11-23 19:02:44 +08:00
1 parent 1856de97bc
commit a532ba4e0f
71 files changed
+3189 -472

No files matched your search

+55 -4
View File
@@ -7,23 +7,31 @@ import (
"math"
"os"
"path/filepath"
"sort"
"sync"
)
type Cache struct {
dir string
dir string
mu sync.Mutex
maxBytes int64
}
func NewCache(dir string) (*Cache, error) {
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, fmt.Errorf("create cache dir: %w", err)
}
return &Cache{dir: dir}, nil
c := &Cache{dir: dir, maxBytes: 256 << 20}
if err := c.prune(0); err != nil {
return nil, err
}
return c, nil
}
// Key covers everything that changes the rendered audio, including the voice
// pack version, so upgrades invalidate old files on their own.
func (c *Cache) Key(version, voice string, speed, pitch float32, text string) string {
sum := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%08x\x00%08x\x00%s",
sum := sha256.Sum256([]byte(fmt.Sprintf("dsp-v2\x00%s\x00%s\x00%08x\x00%08x\x00%s",
version, voice, math.Float32bits(speed), math.Float32bits(pitch), text)))
return hex.EncodeToString(sum[:])
}
@@ -37,11 +45,20 @@ func (c *Cache) Get(key string) ([]byte, bool) {
}
func (c *Cache) Put(key string, data []byte) error {
c.mu.Lock()
defer c.mu.Unlock()
if int64(len(data)) > c.maxBytes {
return fmt.Errorf("audio exceeds cache budget")
}
if err := c.prune(int64(len(data))); err != nil {
return err
}
tmp, err := os.CreateTemp(c.dir, key[:8]+"-*.tmp")
if err != nil {
return err
}
name := tmp.Name()
defer os.Remove(name)
if _, err := tmp.Write(data); err != nil {
tmp.Close()
os.Remove(name)
@@ -52,4 +69,38 @@ func (c *Cache) Put(key string, data []byte) error {
return err
}
return os.Rename(name, filepath.Join(c.dir, key+".wav"))
}
}
func (c *Cache) Open(key string) (*os.File, error) {
return os.Open(filepath.Join(c.dir, key+".wav"))
}
func (c *Cache) prune(incoming int64) error {
entries, err := os.ReadDir(c.dir)
if err != nil {
return err
}
var files []os.FileInfo
var total int64
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".wav" {
continue
}
info, err := entry.Info()
if err != nil {
return err
}
total += info.Size()
files = append(files, info)
}
sort.Slice(files, func(i, j int) bool { return files[i].ModTime().Before(files[j].ModTime()) })
for _, file := range files {
if total+incoming <= c.maxBytes {
break
}
if err := os.Remove(filepath.Join(c.dir, file.Name())); err != nil {
return err
}
total -= file.Size()
}
return nil
}
+25 -1
View File
@@ -24,4 +24,28 @@ func TestCacheRoundTrip(t *testing.T) {
if !ok || string(got) != "wav" {
t.Fatalf("cache get: %q %v", got, ok)
}
}
}
func TestCacheEvictsWithinBudget(t *testing.T) {
c, err := NewCache(t.TempDir())
if err != nil {
t.Fatal(err)
}
c.maxBytes = 6
first, second := c.Key("v", "a", 1, 1, "first"), c.Key("v", "a", 1, 1, "second")
if err := c.Put(first, []byte("1234")); err != nil {
t.Fatal(err)
}
if err := c.Put(second, []byte("5678")); err != nil {
t.Fatal(err)
}
if _, ok := c.Get(first); ok {
t.Fatal("old cache retained beyond budget")
}
if data, ok := c.Get(second); !ok || string(data) != "5678" {
t.Fatal("new cache missing")
}
if err := c.Put(first, make([]byte, 7)); err == nil {
t.Fatal("oversized cache accepted")
}
}
+30 -4
View File
@@ -26,6 +26,23 @@ func ShiftPitch(samples []float32, factor float32) []float32 {
}
func timeStretch(in []float32, factor float32) []float32 {
originalLength := len(in)
padded := make([]float32, len(in)+2*grain)
// Reflect boundaries so even sub-window sounds retain their energy.
for i := range padded {
at := i - grain
if len(in) == 1 {
padded[i] = in[0]
continue
}
period := 2 * (len(in) - 1)
at = ((at % period) + period) % period
if at >= len(in) {
at = period - at
}
padded[i] = in[at]
}
in = padded
hopA := roundInt(float32(hops) / factor)
if hopA < 1 {
hopA = 1
@@ -36,6 +53,7 @@ func timeStretch(in []float32, factor float32) []float32 {
expected = grain
}
out := make([]float32, expected+grain)
weights := make([]float32, len(out))
inPos, outPos := 0, 0
for inPos+grain <= len(in) {
@@ -49,7 +67,7 @@ func timeStretch(in []float32, factor float32) []float32 {
if to > len(in)-grain {
to = len(in) - grain
}
bestCorr := -1.0
bestCorr := 0.0
for cand := from; cand <= to; cand += 4 {
var corr float64
for i := 0; i < overlap; i++ {
@@ -63,13 +81,21 @@ func timeStretch(in []float32, factor float32) []float32 {
}
for i := 0; i < grain; i++ {
out[outPos+i] += in[best+i] * window[i]
weights[outPos+i] += window[i]
}
inPos += hopA
outPos += hops
}
result := make([]float32, expected)
copy(result, out[:min(expected, len(out))])
length := max(1, roundInt(float32(originalLength)*factor))
offset := roundInt(float32(grain) * factor)
result := make([]float32, length)
for i := range result {
at := offset + i
if at < len(out) && weights[at] > 0.00001 {
result[i] = out[at] / weights[at]
}
}
return result
}
@@ -106,4 +132,4 @@ func hann(size int) []float32 {
// roundInt matches Java Math.round(float): floor(x + 0.5).
func roundInt(x float32) int {
return int(math.Floor(float64(x) + 0.5))
}
}
+53 -1
View File
@@ -53,4 +53,56 @@ func TestShiftPitchSilence(t *testing.T) {
t.Fatalf("sample %d: got %v, want 0", i, v)
}
}
}
}
func TestPitchShortAndTail(t *testing.T) {
for _, length := range []int{100, 511, 1023, 1025, 2601} {
for _, factor := range []float32{0.5, 1.2, 2} {
in := make([]float32, length)
for i := range in {
in[i] = 0.5
}
out := ShiftPitch(in, factor)
if math.Abs(float64(len(out)-length)) > 1 {
t.Fatalf("length %d factor %v: %d", length, factor, len(out))
}
var energy float64
for _, v := range out {
energy += float64(v * v)
}
if energy < float64(length)*0.01 {
t.Fatalf("short audio lost: length=%d factor=%v energy=%v", length, factor, energy)
}
var tail float64
for _, v := range out[max(0, len(out)-100):] {
tail += float64(v * v)
}
if tail < 0.01 {
t.Fatalf("tail lost: length=%d factor=%v", length, factor)
}
}
}
}
func TestPitchChangesFrequency(t *testing.T) {
const rate = 22050
input := make([]float32, rate)
for i := range input {
input[i] = float32(0.5 * math.Sin(2*math.Pi*220*float64(i)/rate))
}
for _, factor := range []float32{0.5, 1.2, 2} {
output := ShiftPitch(input, factor)
from, to := rate/5, 4*rate/5
crossings := 0
for i := from + 1; i < to; i++ {
if output[i-1] <= 0 && output[i] > 0 {
crossings++
}
}
frequency := float64(crossings) * rate / float64(to-from)
want := 220 * float64(factor)
if math.Abs(frequency/want-1) > 0.15 {
t.Fatalf("pitch=%v frequency=%.1f want=%.1f", factor, frequency, want)
}
}
}
+105 -21
View File
@@ -1,8 +1,11 @@
package tts
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
@@ -17,17 +20,19 @@ type Manifest struct {
}
type VoiceEntry struct {
Name string `json:"name"`
Locale string `json:"locale"`
Label string `json:"label"`
SpeakerID int `json:"speakerId"`
Quality int `json:"quality"`
Dir string `json:"dir"`
Model string `json:"model"`
Lexicon string `json:"lexicon"`
Tokens string `json:"tokens"`
DataDir string `json:"dataDir"`
RuleFsts []string `json:"ruleFsts"`
SHA256 string `json:"sha256"`
Files map[string]string `json:"files"`
Name string `json:"name"`
Locale string `json:"locale"`
Label string `json:"label"`
SpeakerID int `json:"speakerId"`
Quality int `json:"quality"`
Dir string `json:"dir"`
Model string `json:"model"`
Lexicon string `json:"lexicon"`
Tokens string `json:"tokens"`
DataDir string `json:"dataDir"`
RuleFsts []string `json:"ruleFsts"`
}
type VoicePack struct {
@@ -55,10 +60,17 @@ func LoadRepo(root string) (*Repo, error) {
if err != nil {
return nil, fmt.Errorf("read manifest: %w", err)
}
return LoadRepoManifest(root, raw)
}
func LoadRepoManifest(root string, raw []byte) (*Repo, error) {
var m Manifest
if err := json.Unmarshal(raw, &m); err != nil {
return nil, fmt.Errorf("parse manifest: %w", err)
}
if strings.TrimSpace(m.Version) == "" {
return nil, fmt.Errorf("manifest version is required")
}
if len(m.Voices) == 0 {
return nil, fmt.Errorf("manifest has no voices")
}
@@ -84,14 +96,14 @@ func LoadRepo(root string) (*Repo, error) {
rules = append(rules, filepath.Join(base, f))
}
pack := &VoicePack{
Name: e.Name,
Locale: e.Locale,
Label: e.Label,
SpeakerID: e.SpeakerID,
Quality: e.Quality,
ModelPath: filepath.Join(base, e.Model),
TokensPath: filepath.Join(base, tokens),
RuleFsts: strings.Join(rules, ","),
Name: e.Name,
Locale: e.Locale,
Label: e.Label,
SpeakerID: e.SpeakerID,
Quality: e.Quality,
ModelPath: filepath.Join(base, e.Model),
TokensPath: filepath.Join(base, tokens),
RuleFsts: strings.Join(rules, ","),
}
if e.Lexicon != "" {
pack.LexiconPath = filepath.Join(base, e.Lexicon)
@@ -102,6 +114,31 @@ func LoadRepo(root string) (*Repo, error) {
if pack.Label == "" {
pack.Label = pack.Name
}
paths := []string{pack.ModelPath, pack.TokensPath}
if pack.LexiconPath != "" {
paths = append(paths, pack.LexiconPath)
}
if pack.DataDir != "" {
paths = append(paths, pack.DataDir)
}
paths = append(paths, rules...)
for _, path := range paths {
if err := contained(root, path); err != nil {
return nil, err
}
}
if err := verifyHash(pack.ModelPath, e.SHA256); err != nil {
return nil, err
}
for relative, hash := range e.Files {
path := filepath.Join(base, relative)
if err := contained(root, path); err != nil {
return nil, err
}
if err := verifyHash(path, hash); err != nil {
return nil, err
}
}
if err := pack.validate(); err != nil {
return nil, err
}
@@ -127,9 +164,17 @@ func (p *VoicePack) validate() error {
required = append(required, strings.Split(p.RuleFsts, ",")...)
}
for _, path := range required {
if _, err := os.Stat(path); err != nil {
info, err := os.Stat(path)
if err != nil {
return fmt.Errorf("voice %q: %w", p.Name, err)
}
if path == p.DataDir {
if !info.IsDir() {
return fmt.Errorf("voice %q: dataDir must be a directory", p.Name)
}
} else if !info.Mode().IsRegular() {
return fmt.Errorf("voice %q: resource must be a regular file", p.Name)
}
}
return nil
}
@@ -148,6 +193,11 @@ func (r *Repo) Resolve(requested string) *VoicePack {
if p, ok := r.byName[requested]; ok {
return p
}
for _, p := range r.Packs {
if strings.EqualFold(strings.ReplaceAll(requested, "_", "-"), p.Locale) {
return p
}
}
want := normalizeLanguage(requested)
if want != "" {
for _, p := range r.Packs {
@@ -178,4 +228,38 @@ func normalizeLanguage(tag string) string {
default:
return tag
}
}
}
func contained(root, path string) error {
base, err := filepath.EvalSymlinks(root)
if err != nil {
return err
}
target, err := filepath.EvalSymlinks(path)
if err != nil {
return err
}
rel, err := filepath.Rel(base, target)
if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) {
return fmt.Errorf("voice path outside root: %s", path)
}
return nil
}
func verifyHash(path, expected string) error {
decoded, err := hex.DecodeString(expected)
if err != nil || len(decoded) != sha256.Size {
return fmt.Errorf("missing/invalid SHA256: %s", path)
}
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
hash := sha256.New()
if _, err := io.Copy(hash, f); err != nil {
return err
}
if !strings.EqualFold(hex.EncodeToString(hash.Sum(nil)), expected) {
return fmt.Errorf("SHA256 mismatch: %s", path)
}
return nil
}
+198
View File
@@ -0,0 +1,198 @@
package tts
import (
"archive/zip"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
)
// VoiceStore publishes validated immutable pack directories. Old files remain
// available for in-flight synthesis and rollback; manifests change atomically.
type VoiceStore struct {
Root string
mu sync.Mutex
}
func (s *VoiceStore) manifest() (Manifest, error) {
var m Manifest
raw, err := os.ReadFile(filepath.Join(s.Root, "manifest.json"))
if err != nil {
return m, err
}
err = json.Unmarshal(raw, &m)
return m, err
}
func (s *VoiceStore) commit(m Manifest) (*Repo, error) {
raw, err := json.MarshalIndent(m, "", " ")
if err != nil {
return nil, err
}
// Validate against the real root before replacing the live manifest.
repo, err := LoadRepoManifest(s.Root, raw)
if err != nil {
return nil, err
}
temp, err := os.CreateTemp(s.Root, ".manifest-*.tmp")
if err != nil {
return nil, err
}
name := temp.Name()
defer os.Remove(name)
if _, err = temp.Write(raw); err != nil {
temp.Close()
return nil, err
}
if err = temp.Sync(); err != nil {
temp.Close()
return nil, err
}
if err = temp.Close(); err != nil {
return nil, err
}
if err = os.Rename(name, filepath.Join(s.Root, "manifest.json")); err != nil {
return nil, err
}
return repo, nil
}
func (s *VoiceStore) SetDefault(name string) (*Repo, error) {
s.mu.Lock()
defer s.mu.Unlock()
m, err := s.manifest()
if err != nil {
return nil, err
}
found := false
for _, v := range m.Voices {
if v.Name == name {
found = true
}
}
if !found {
return nil, fmt.Errorf("音色不存在")
}
m.Default = name
return s.commit(m)
}
func (s *VoiceStore) Import(archive string) (*Repo, error) {
s.mu.Lock()
defer s.mu.Unlock()
m, err := s.manifest()
if err != nil {
return nil, err
}
stage, err := os.MkdirTemp(s.Root, ".upload-")
if err != nil {
return nil, err
}
defer os.RemoveAll(stage)
if err = extractVoices(archive, stage); err != nil {
return nil, err
}
raw, err := os.ReadFile(filepath.Join(stage, "manifest.json"))
if err != nil {
return nil, fmt.Errorf("ZIP 根目录需要 manifest.json")
}
if len(raw) > 1024*1024 {
return nil, fmt.Errorf("清单过大")
}
var incoming Manifest
if err = json.Unmarshal(raw, &incoming); err != nil {
return nil, fmt.Errorf("语音包清单无效")
}
if len(incoming.Voices) > 32 {
return nil, fmt.Errorf("单次最多导入 32 个音色")
}
if _, err = LoadRepo(stage); err != nil {
return nil, fmt.Errorf("语音包资源或 SHA256 校验失败: %w", err)
}
existing := map[string]bool{}
for _, v := range m.Voices {
existing[v.Name] = true
}
folder := "pack-" + strings.TrimPrefix(filepath.Base(stage), ".upload-")
for _, v := range incoming.Voices {
if existing[v.Name] {
return nil, fmt.Errorf("音色 %q 已存在,请为新音色使用不同名称", v.Name)
}
if filepath.IsAbs(v.Dir) || strings.Contains(v.Dir, "..") {
return nil, fmt.Errorf("语音包目录无效")
}
v.Dir = filepath.Join(folder, v.Dir)
m.Voices = append(m.Voices, v)
}
destination := filepath.Join(s.Root, folder)
if err = os.Rename(stage, destination); err != nil {
return nil, err
}
m.Version = incoming.Version
repo, err := s.commit(m)
if err != nil {
os.RemoveAll(destination)
return nil, err
}
return repo, nil
}
func extractVoices(archive, root string) error {
z, err := zip.OpenReader(archive)
if err != nil {
return fmt.Errorf("无法读取 ZIP 语音包")
}
defer z.Close()
if len(z.File) > 2048 {
return fmt.Errorf("语音包文件数量超过 2048")
}
var total uint64
for _, entry := range z.File {
name := entry.Name
if name == "" || strings.Contains(name, "\\") || strings.Contains(name, ":") || strings.HasPrefix(name, "/") {
return fmt.Errorf("ZIP 路径无效")
}
for _, part := range strings.Split(name, "/") {
if part == ".." {
return fmt.Errorf("ZIP 路径越界")
}
}
if entry.Mode()&os.ModeSymlink != 0 || (!entry.FileInfo().IsDir() && !entry.Mode().IsRegular()) {
return fmt.Errorf("ZIP 仅允许普通文件和目录")
}
total += entry.UncompressedSize64
if total > 512<<20 {
return fmt.Errorf("解压后语音包超过 512 MiB")
}
target := filepath.Join(root, filepath.FromSlash(name))
rel, err := filepath.Rel(root, target)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return fmt.Errorf("ZIP 路径越界")
}
if entry.FileInfo().IsDir() {
if err = os.MkdirAll(target, 0755); err != nil {
return err
}
continue
}
if err = os.MkdirAll(filepath.Dir(target), 0755); err != nil {
return err
}
src, err := entry.Open()
if err != nil {
return err
}
dst, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
if err != nil {
src.Close()
return err
}
n, copyErr := io.Copy(dst, io.LimitReader(src, int64(entry.UncompressedSize64)+1))
src.Close()
closeErr := dst.Close()
if copyErr != nil || closeErr != nil || uint64(n) != entry.UncompressedSize64 {
return fmt.Errorf("ZIP 文件不完整")
}
}
return nil
}
+98
View File
@@ -0,0 +1,98 @@
package tts
import (
"archive/zip"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func testVoiceStore(t *testing.T) *VoiceStore {
root := t.TempDir()
writeVoiceFiles(t, root, "pack-a")
writeVoiceFiles(t, root, "pack-b")
writeManifest(t, root, testManifest)
return &VoiceStore{Root: root}
}
func TestVoiceStoreDefaultPersists(t *testing.T) {
store := testVoiceStore(t)
repo, err := store.SetDefault("b")
if err != nil {
t.Fatal(err)
}
if repo.Default != "b" {
t.Fatal(repo.Default)
}
fresh, err := LoadRepo(store.Root)
if err != nil || fresh.Default != "b" {
t.Fatal("default not persisted", err)
}
if _, err = store.SetDefault("missing"); err == nil {
t.Fatal("unknown voice accepted")
}
}
func voiceZip(t *testing.T, entries map[string][]byte) string {
t.Helper()
name := filepath.Join(t.TempDir(), "pack.zip")
f, err := os.Create(name)
if err != nil {
t.Fatal(err)
}
w := zip.NewWriter(f)
for path, data := range entries {
entry, err := w.Create(path)
if err != nil {
t.Fatal(err)
}
if _, err = entry.Write(data); err != nil {
t.Fatal(err)
}
}
if err = w.Close(); err != nil {
t.Fatal(err)
}
if err = f.Close(); err != nil {
t.Fatal(err)
}
return name
}
func TestVoiceStoreImportAndDuplicate(t *testing.T) {
store := testVoiceStore(t)
var incoming Manifest
if err := json.Unmarshal([]byte(testManifest), &incoming); err != nil {
t.Fatal(err)
}
incoming.Version = "test-2"
incoming.Default = "c"
incoming.Voices = incoming.Voices[:1]
incoming.Voices[0].Name = "c"
raw, _ := json.Marshal(incoming)
archive := voiceZip(t, map[string][]byte{"manifest.json": raw, "pack-a/model.onnx": []byte("model"), "pack-a/tokens.txt": []byte("tokens"), "pack-a/lexicon.txt": []byte("lexicon"), "pack-a/phone.fst": []byte("fst")})
repo, err := store.Import(archive)
if err != nil {
t.Fatal(err)
}
if len(repo.Packs) != 3 || repo.Default != "a" || repo.Version != "test-2" {
t.Fatal("import changed defaults or lost voices")
}
if _, err = store.Import(archive); err == nil {
t.Fatal("duplicate accepted")
}
}
func TestVoiceStoreRejectsTraversalAndBadHash(t *testing.T) {
store := testVoiceStore(t)
archive := voiceZip(t, map[string][]byte{"../escape": []byte("bad")})
if _, err := store.Import(archive); err == nil {
t.Fatal("traversal accepted")
}
archive = voiceZip(t, map[string][]byte{"manifest.json": []byte(strings.ReplaceAll(testManifest, "9372c470", "00000000")), "pack-a/model.onnx": []byte("tampered")})
if _, err := store.Import(archive); err == nil {
t.Fatal("invalid package accepted")
}
repo, err := LoadRepo(store.Root)
if err != nil || len(repo.Packs) != 2 {
t.Fatal("rejected upload changed live manifest")
}
}
+52 -6
View File
@@ -1,8 +1,10 @@
package tts
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
@@ -37,9 +39,9 @@ const testManifest = `{
"default": "a",
"voices": [
{"name": "a", "locale": "zh-CN", "label": "甲", "speakerId": 0, "quality": 300,
"dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]},
"dir": "pack-a", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]},
{"name": "b", "locale": "yue-HK", "label": "乙", "speakerId": 1, "quality": 300,
"dir": "pack-b", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]}
"dir": "pack-b", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]}
]
}`
@@ -91,8 +93,8 @@ func TestLoadRepoDuplicateName(t *testing.T) {
writeManifest(t, root, `{
"version": "t", "default": "a",
"voices": [
{"name": "a", "locale": "zh-CN", "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt"},
{"name": "a", "locale": "yue-HK", "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt"}
{"name": "a", "locale": "zh-CN", "dir": "pack-a", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt"},
{"name": "a", "locale": "yue-HK", "dir": "pack-a", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt"}
]
}`)
if _, err := LoadRepo(root); err == nil {
@@ -105,7 +107,7 @@ func TestLoadRepoDefaultFallsBackToFirst(t *testing.T) {
writeVoiceFiles(t, root, "pack-a")
writeManifest(t, root, `{
"version": "t", "default": "missing",
"voices": [{"name": "a", "locale": "zh-CN", "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt"}]
"voices": [{"name": "a", "locale": "zh-CN", "dir": "pack-a", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt"}]
}`)
repo, err := LoadRepo(root)
if err != nil {
@@ -114,4 +116,48 @@ func TestLoadRepoDefaultFallsBackToFirst(t *testing.T) {
if repo.Default != "a" {
t.Fatalf("default %q, want a", repo.Default)
}
}
}
func TestLoadRepoRejectsTampering(t *testing.T) {
root := t.TempDir()
writeVoiceFiles(t, root, "pack-a")
writeVoiceFiles(t, root, "pack-b")
writeManifest(t, root, testManifest)
if err := os.WriteFile(filepath.Join(root, "pack-a", "model.onnx"), []byte("tampered"), 0600); err != nil {
t.Fatal(err)
}
if _, err := LoadRepo(root); err == nil {
t.Fatal("tampered model accepted")
}
}
func TestLoadRepoRejectsEscape(t *testing.T) {
root := t.TempDir()
outside := t.TempDir()
writeVoiceFiles(t, outside, "pack-a")
rel, err := filepath.Rel(root, filepath.Join(outside, "pack-a"))
if err != nil {
t.Fatal(err)
}
// Marshal keeps Windows backslashes valid JSON.
raw, _ := json.Marshal(Manifest{Version: "test", Voices: []VoiceEntry{{Name: "a", Dir: rel, Model: "model.onnx", SHA256: "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4"}}})
writeManifest(t, root, string(raw))
if _, err := LoadRepo(root); err == nil {
t.Fatal("escaped model accepted")
}
}
func TestLoadRepoRejectsFrontendHashMismatch(t *testing.T) {
root := t.TempDir()
writeVoiceFiles(t, root, "pack-a")
writeVoiceFiles(t, root, "pack-b")
var manifest Manifest
if err := json.Unmarshal([]byte(testManifest), &manifest); err != nil {
t.Fatal(err)
}
manifest.Voices[0].Files = map[string]string{"tokens.txt": strings.Repeat("0", 64)}
raw, _ := json.Marshal(manifest)
writeManifest(t, root, string(raw))
if _, err := LoadRepo(root); err == nil {
t.Fatal("tampered frontend accepted")
}
}