Skip to content
10 changes: 5 additions & 5 deletions docs/ui.md

Large diffs are not rendered by default.

60 changes: 56 additions & 4 deletions internal/credential/credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
Expand Down Expand Up @@ -57,12 +58,17 @@ var (
)

// AllowedCookieKeys defines the strict whitelist of Bilibili cookie keys stored by TRACE.
// SESSDATA is mandatory; buvid3, buvid4, and b_nut are optional browser fingerprint/device
// cookies preserved when pasted alongside SESSDATA.
var AllowedCookieKeys = []string{
"SESSDATA",
"bili_jct",
"DedeUserID",
"DedeUserID__ckMd5",
"sid",
"buvid3",
"buvid4",
"b_nut",
}

var allowedKeyLookup = map[string]string{
Expand All @@ -71,8 +77,23 @@ var allowedKeyLookup = map[string]string{
"dedeuserid": "DedeUserID",
"dedeuserid__ckmd5": "DedeUserID__ckMd5",
"sid": "sid",
"buvid3": "buvid3",
"buvid4": "buvid4",
"b_nut": "b_nut",
}

var (
reBiliNamedKV = regexp.MustCompile(
`(?i)(^|[?&;,:=\s"'(\[{])(SESSDATA|bili_jct|buvid3|buvid4|b_nut)=(\[REDACTED\]|"[^"\r\n]*"|'[^'\r\n]*'|[^&\s;'",)\]}<>]+)`,
)
reBiliNamedEncPrefix = regexp.MustCompile(
`(?i)(^|%3f|%26|%3b|%20|%3d|%3a|%22|%27|[?&;,:=\+\s"'(\[{])(SESSDATA|bili_jct|buvid3|buvid4|b_nut)(%3d)`,
)
reBiliNamedJSON = regexp.MustCompile(
`(?i)("(?:SESSDATA|bili_jct|buvid3|buvid4|b_nut)"\s*:\s*")([^"]+)(")`,
)
)

// Record is the internal encrypted credential structure persisted in <site>.bin.
// It must NEVER be serialized directly to UI responses or logs.
type Record struct {
Expand All @@ -96,6 +117,7 @@ type Record struct {
State string `json:"state,omitempty"`
Message string `json:"message,omitempty"`
DouyinGuard *DouyinGuardState `json:"douyin_guard,omitempty"`
DouyinWebID string `json:"douyinWebId,omitempty"`
}

// Read older encrypted records, while all new writes use the documented keys.
Expand Down Expand Up @@ -148,8 +170,9 @@ type Status struct {
}

// ParseManualCookieInput parses a manual Bilibili Cookie string and optional refresh_token.
// It enforces the 64 KiB raw input limit, filters by the 5-key whitelist, requires SESSDATA,
// enforces the 32 KiB cleaned outbound header limit, and never echoes input values in error messages.
// It enforces the 64 KiB raw input limit, filters by AllowedCookieKeys (preserving optional
// buvid3, buvid4, b_nut), requires SESSDATA, enforces the 32 KiB cleaned outbound header limit,
// and never echoes input values in error messages.
func ParseManualCookieInput(rawCookie string, rawRefreshToken string) (map[string]string, string, error) {
if len(rawCookie) > MaxCookieInputBytes || len(rawRefreshToken) > MaxCookieInputBytes {
return nil, "", ErrInputTooLarge
Expand Down Expand Up @@ -220,7 +243,7 @@ func isSafeCookieValue(v string) bool {
return v != "" && !strings.ContainsAny(v, "\r\n;")
}

// FilterCookieMap filters a map of cookies down to the 5 whitelisted Bilibili keys,
// FilterCookieMap filters a map of cookies down to the whitelisted Bilibili keys,
// rejecting empty values and values containing CR/LF/semicolon header delimiters.
func FilterCookieMap(in map[string]string) map[string]string {
out := make(map[string]string)
Expand Down Expand Up @@ -851,18 +874,47 @@ func isNonSecretCookieValue(key, val string) bool {
}

// RedactString replaces any stored cookie values or refresh tokens present in in with [REDACTED].
// It also scrubs Weibo sensitive fields (for Weibo stores) and X auth/CSRF/Bearer fields across all sites.
// It also scrubs Bilibili, Weibo, and X sensitive cookie/auth fields so pasted or transient values never leak.
func (s *Store) RedactString(in string) string {
if in == "" {
return ""
}
out := redactWithSecrets(in, s.collectSecrets())
if s == nil || s.site == SiteBilibili {
out = redactBilibiliSensitiveFields(out)
}
if s != nil && s.site == SiteWeibo {
out = redactWeiboSensitiveFields(out)
}
return redactXSensitiveFields(out)
}

func redactBilibiliSensitiveFields(in string) string {
if in == "" {
return ""
}
out := reBiliNamedKV.ReplaceAllStringFunc(in, func(m string) string {
sub := reBiliNamedKV.FindStringSubmatch(m)
if len(sub) != 4 {
return m
}
masked, changed := redactQuotedOrRawValue(sub[3])
if !changed {
return m
}
return sub[1] + sub[2] + "=" + masked
})
out = redactEncodedKVByPrefix(out, reBiliNamedEncPrefix, nil)
out = reBiliNamedJSON.ReplaceAllStringFunc(out, func(m string) string {
sub := reBiliNamedJSON.FindStringSubmatch(m)
if len(sub) != 4 || sub[2] == "[REDACTED]" {
return m
}
return sub[1] + "[REDACTED]" + sub[3]
})
return out
}

func redactWithSecrets(in string, secrets []string) string {
if in == "" || len(secrets) == 0 {
return in
Expand Down
141 changes: 135 additions & 6 deletions internal/credential/credential_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,34 @@ func TestManualCookieParserWhitelistAndBounds(t *testing.T) {
t.Fatalf("error echoed secret bili_jct: %v", err)
}

// 3. Valid Cookie header with extra non-whitelisted fields filters strictly to the 5 allowed keys.
raw := "Cookie: SESSDATA=sess_val_1; bili_jct=csrf_val_2; DedeUserID=12345; DedeUserID__ckMd5=md5_val; sid=sid_val; buvid3=ignore_me; _uuid=ignore_uuid"
// 2b. Optional device cookies (buvid3/buvid4/b_nut) alone without SESSDATA must still be rejected.
buvidOnly := "buvid3=SYNTH_BUVID3_ONLY; buvid4=SYNTH_BUVID4_ONLY; b_nut=1700000001"
if _, _, err := ParseManualCookieInput(buvidOnly, ""); !errors.Is(err, ErrMissingRequiredKeys) {
t.Fatalf("expected ErrMissingRequiredKeys for buvid-only input, got %v", err)
} else if strings.Contains(err.Error(), "SYNTH_BUVID3_ONLY") {
t.Fatalf("error echoed buvid3 secret: %v", err)
}

// 3. Valid Cookie header preserves the 8 allowed keys (including optional buvid3/buvid4/b_nut)
// and strips non-whitelisted keys (_uuid, b_lsid, CURRENT_FNVAL).
raw := "Cookie: SESSDATA=sess_val_1; bili_jct=csrf_val_2; DedeUserID=12345; DedeUserID__ckMd5=md5_val; sid=sid_val; buvid3=SYNTH_BUVID3_OK; buvid4=SYNTH_BUVID4_OK; b_nut=1700000000; _uuid=ignore_uuid; b_lsid=ignore_lsid; CURRENT_FNVAL=4048"
cookies, rt, err := ParseManualCookieInput(raw, " refresh_tok_abc ")
if err != nil {
t.Fatalf("ParseManualCookieInput failed: %v", err)
}
if rt != "refresh_tok_abc" {
t.Fatalf("refreshToken = %q, want refresh_tok_abc", rt)
}
if len(cookies) != 5 {
t.Fatalf("len(cookies) = %d, want 5: %+v", len(cookies), cookies)
if len(cookies) != 8 {
t.Fatalf("len(cookies) = %d, want 8: %+v", len(cookies), cookies)
}
if cookies["buvid3"] != "SYNTH_BUVID3_OK" || cookies["buvid4"] != "SYNTH_BUVID4_OK" || cookies["b_nut"] != "1700000000" {
t.Fatalf("expected buvid3/buvid4/b_nut preserved, got %+v", cookies)
}
if _, exists := cookies["buvid3"]; exists {
t.Fatalf("unexpected non-whitelisted key buvid3 in cookies")
for _, stripped := range []string{"_uuid", "b_lsid", "CURRENT_FNVAL"} {
if _, exists := cookies[stripped]; exists {
t.Fatalf("unexpected non-whitelisted key %s in cookies", stripped)
}
}
}

Expand Down Expand Up @@ -276,3 +290,118 @@ func TestRedactEncodedSecretsAndCookieInjectionGuard(t *testing.T) {
t.Fatal("expected Douyin store to reject SaveVerifiedManual")
}
}

func TestBilibiliBuvidAndBNutSentinelRedaction(t *testing.T) {
dir := t.TempDir()
mgr, _, err := OpenManager(dir)
if err != nil {
t.Fatalf("OpenManager: %v", err)
}
biliStore := mgr.Store(SiteBilibili)

buvid3Sentinel := "SYNTH-BUVID3-SENTINEL-8888infoc"
buvid4Sentinel := "SYNTH-BUVID4-SENTINEL-9999-token"
bnutSentinel := "1799887766"
raw := "SESSDATA=SYNTH_SESS_99; bili_jct=SYNTH_CSRF_99; buvid3=" + buvid3Sentinel + "; buvid4=" + buvid4Sentinel + "; b_nut=" + bnutSentinel
if _, err := biliStore.SaveManual(raw, ""); err != nil {
t.Fatalf("SaveManual: %v", err)
}

// On-disk ciphertext must not contain any buvid3/buvid4/b_nut sentinel.
rawBin, err := os.ReadFile(filepath.Join(dir, BilibiliFileName))
if err != nil {
t.Fatalf("read bilibili.bin: %v", err)
}
for _, sec := range []string{buvid3Sentinel, buvid4Sentinel, bnutSentinel} {
if bytes.Contains(rawBin, []byte(sec)) {
t.Fatalf("bilibili.bin leaked plaintext %q", sec)
}
}

// Both Store.RedactString and Manager.RedactString must scrub stored and transient buvid3/buvid4/b_nut values.
sample := "Cookie: buvid3=" + buvid3Sentinel + "; buvid4=" + buvid4Sentinel + "; b_nut=" + bnutSentinel +
" transient buvid3=TRANSIENT_B3_VALUE&buvid4%3DTRANSIENT_B4_ENC%26b_nut%3D1700999888" +
` {"buvid3":"JSON_B3_VAL","buvid4":"JSON_B4_VAL","b_nut":"1700111222"}`
for label, redacted := range map[string]string{
"store": biliStore.RedactString(sample),
"manager": mgr.RedactString(sample),
} {
for _, leak := range []string{
buvid3Sentinel, buvid4Sentinel, bnutSentinel,
"TRANSIENT_B3_VALUE", "TRANSIENT_B4_ENC", "1700999888",
"JSON_B3_VAL", "JSON_B4_VAL", "1700111222",
} {
if strings.Contains(redacted, leak) {
t.Fatalf("%s RedactString leaked %q in %q", label, leak, redacted)
}
}
}
}

func TestDouyinWebIDPersistenceAndBackwardsCompat(t *testing.T) {
dir := t.TempDir()
dyPath := filepath.Join(dir, DouyinFileName)

// 1. Backwards-compatibility: a legacy encrypted Douyin record without douyinWebId loads cleanly.
store, _, err := OpenDouyin(dyPath)
if err != nil {
t.Fatalf("OpenDouyin: %v", err)
}
if _, err := store.SaveVerifiedDouyinManual(
map[string]string{"sessionid": "SYNTH_DY_WEBID_SESS_1"},
DouyinProfile{SecUID: "MS4wLjABAAAA_WEBID_01", Uname: "测试用户"},
); err != nil {
t.Fatalf("SaveVerifiedDouyinManual: %v", err)
}
if got := store.DouyinWebID(); got != "" {
t.Fatalf("initial DouyinWebID = %q, want empty", got)
}

// 2. EnsureDouyinWebID generates once, persists, and returns the same ID on subsequent calls and restarts.
genCalls := 0
id1, err := store.EnsureDouyinWebID(func() (string, error) {
genCalls++
return "7412345678901234567", nil
})
if err != nil {
t.Fatalf("EnsureDouyinWebID: %v", err)
}
if id1 != "7412345678901234567" || genCalls != 1 {
t.Fatalf("id1=%q genCalls=%d", id1, genCalls)
}
id2, err := store.EnsureDouyinWebID(func() (string, error) {
genCalls++
return "7499999999999999999", nil
})
if err != nil || id2 != id1 || genCalls != 1 {
t.Fatalf("second EnsureDouyinWebID regenerated: id2=%q genCalls=%d err=%v", id2, genCalls, err)
}

// Re-pasting expired/new cookie preserves persisted DouyinWebID.
if _, err := store.SaveVerifiedDouyinManual(
map[string]string{"sessionid": "SYNTH_DY_WEBID_SESS_2"},
DouyinProfile{SecUID: "MS4wLjABAAAA_WEBID_01", Uname: "测试用户"},
); err != nil {
t.Fatalf("re-save cookie: %v", err)
}
if got := store.DouyinWebID(); got != id1 {
t.Fatalf("DouyinWebID lost after cookie re-paste: got %q want %q", got, id1)
}

// Re-open from disk (simulated restart) recovers the exact same webid.
reopened, _, err := OpenDouyin(dyPath)
if err != nil {
t.Fatalf("re-open douyin.bin: %v", err)
}
if got := reopened.DouyinWebID(); got != id1 {
t.Fatalf("reopened DouyinWebID = %q, want %q", got, id1)
}
// Cross-site guard rejects SaveDouyinWebID on Bilibili store.
biliStore, _, err := Open(filepath.Join(dir, BilibiliFileName))
if err != nil {
t.Fatal(err)
}
if err := biliStore.SaveDouyinWebID("7412345678901234567"); err == nil {
t.Fatal("expected SaveDouyinWebID rejected on Bilibili store")
}
}
84 changes: 82 additions & 2 deletions internal/credential/douyin.go
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,12 @@ func (s *Store) SaveVerifiedDouyinManualWithGuard(cookies map[string]string, pro
return Status{}, ErrMissingDouyinSession
}
now := time.Now().UTC().Format(time.RFC3339)
s.mu.Lock()
defer s.mu.Unlock()
prevWebID := ""
if s.rec != nil {
prevWebID = strings.TrimSpace(s.rec.DouyinWebID)
}
rec := &Record{
Version: 1,
Site: SiteDouyin,
Expand All @@ -340,11 +346,85 @@ func (s *Store) SaveVerifiedDouyinManualWithGuard(cookies map[string]string, pro
Face: strings.TrimSpace(profile.Face),
State: "logged_in",
DouyinGuard: cloneDouyinGuardState(guardState),
DouyinWebID: prevWebID,
}
if err := s.saveRecord(rec); err != nil {
if err := s.persistRecordLocked(rec); err != nil {
return Status{}, err
}
return s.Status(), nil
return s.buildStatus(s.rec), nil
}

// DouyinWebID returns the persisted Douyin webid for an active Douyin store, or empty string.
func (s *Store) DouyinWebID() string {
if s == nil {
return ""
}
s.mu.RLock()
defer s.mu.RUnlock()
if s.site != SiteDouyin || !s.isActiveRecordLocked() {
return ""
}
return strings.TrimSpace(s.rec.DouyinWebID)
}

// SaveDouyinWebID persists webID on an active Douyin credential store without changing schema version.
func (s *Store) SaveDouyinWebID(webID string) error {
if err := s.requireSite(SiteDouyin); err != nil {
return err
}
webID = strings.TrimSpace(webID)
if webID == "" {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
if !s.isActiveRecordLocked() {
return ErrNotLoggedIn
}
if strings.TrimSpace(s.rec.DouyinWebID) == webID {
return nil
}
next := s.cloneRecord(s.rec)
next.DouyinWebID = webID
next.UpdatedAt = time.Now().UTC().Format(time.RFC3339)
return s.persistRecordLocked(next)
}

// EnsureDouyinWebID returns the persisted Douyin webid when an active Douyin credential exists,
// or generates and persists one via generate on first use. Returns ("", nil) when logged out.
func (s *Store) EnsureDouyinWebID(generate func() (string, error)) (string, error) {
if s == nil {
return "", nil
}
if err := s.requireSite(SiteDouyin); err != nil {
return "", err
}
s.mu.Lock()
defer s.mu.Unlock()
if !s.isActiveRecordLocked() {
return "", nil
}
if existing := strings.TrimSpace(s.rec.DouyinWebID); existing != "" {
return existing, nil
}
if generate == nil {
return "", nil
}
gen, err := generate()
if err != nil {
return "", err
}
gen = strings.TrimSpace(gen)
if gen == "" {
return "", nil
}
next := s.cloneRecord(s.rec)
next.DouyinWebID = gen
next.UpdatedAt = time.Now().UTC().Format(time.RFC3339)
if err := s.persistRecordLocked(next); err != nil {
return "", err
}
return gen, nil
}

// DouyinGuard returns a copy of the stored bd-ticket-guard state for an active Douyin store, or nil.
Expand Down
1 change: 1 addition & 0 deletions internal/credential/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ func (m *Manager) RedactString(in string) string {
}
out = redactWithSecrets(out, allSecrets)
}
out = redactBilibiliSensitiveFields(out)
out = redactWeiboSensitiveFields(out)
return redactXSensitiveFields(out)
}
Loading