From c9789e3e134d070670ef6bebb9f89ca541cf99a6 Mon Sep 17 00:00:00 2001 From: guyu233 Date: Sat, 21 Nov 2026 18:04:38 +0800 Subject: [PATCH] feat(minimaxcode): add daily check-in - registry: advertise check-in for the CN and global regions, with an Asia/Shanghai rollover. - minimaxcode: implement status/claim against the signed /minimax-cloud/api/v1/signin endpoints, map already/skipped/error, and refresh the token once on 401. - resolve realUserID from /v1/api/user/info when login did not persist it, so the panel is scoped to the right account. - tests: status, claim, skip, identity, token refresh, URI encoding, adapter exposure, registry advertising. Live-account claim acceptance is still pending. --- README.md | 2 +- README_EN.md | 2 +- .../unreleased/minimaxcode-daily-checkin.md | 7 + internal/providers/minimaxcode/checkin.go | 445 ++++++++++++++++++ internal/providers/minimaxcode/client.go | 1 + .../providers/minimaxcode/minimaxcode_test.go | 241 +++++++++- internal/providers/registry.go | 2 + internal/providers/registry_test.go | 16 + 8 files changed, 710 insertions(+), 6 deletions(-) create mode 100644 changelog/unreleased/minimaxcode-daily-checkin.md create mode 100644 internal/providers/minimaxcode/checkin.go diff --git a/README.md b/README.md index c9713d31..cea083f1 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ Qoder 国内版、WorkBuddy、Trae 已实现,真账号验收未完成。Kimi C CLI2API 控制台 Accounts 页:每个账号显示登录方式、就绪状态与额度,右侧 Access 面板提供 Base URL 与快速验证

-就绪状态和额度在账号卡片上。Access 页可以复制 Base URL,并做一次快速验证。WorkBuddy、QwenWork、Qoder 可以在卡片上签到;自动签到默认关闭,时间在「系统 → 自动签到」。真实账号签到验收仍待完成。 +就绪状态和额度在账号卡片上。Access 页可以复制 Base URL,并做一次快速验证。WorkBuddy、QwenWork、Qoder、MiniMax Code 可以在卡片上签到;自动签到默认关闭,时间在「系统 → 自动签到」。真实账号签到验收仍待完成。 ## 最早到期优先 diff --git a/README_EN.md b/README_EN.md index 2a2c7fa2..621ed557 100644 --- a/README_EN.md +++ b/README_EN.md @@ -77,7 +77,7 @@ Qoder CN, WorkBuddy, and Trae are implemented; live-account acceptance is still CLI2API console Accounts page: each account shows its login method, ready state, and quota, with an Access panel offering the Base URL and a quick check

-Readiness and quota sit on the account card. Access copies the Base URL and runs a quick check. WorkBuddy, QwenWork, and Qoder can check in from the card; automatic check-in is off by default, and its schedule lives under System → Automatic check-in. Live-account check-in acceptance is still pending. +Readiness and quota sit on the account card. Access copies the Base URL and runs a quick check. WorkBuddy, QwenWork, Qoder, and MiniMax Code can check in from the card; automatic check-in is off by default, and its schedule lives under System → Automatic check-in. Live-account check-in acceptance is still pending. ## Earliest expiry first diff --git a/changelog/unreleased/minimaxcode-daily-checkin.md b/changelog/unreleased/minimaxcode-daily-checkin.md new file mode 100644 index 00000000..b029ad77 --- /dev/null +++ b/changelog/unreleased/minimaxcode-daily-checkin.md @@ -0,0 +1,7 @@ +### English + +- MiniMax Code accounts now support daily check-in across the console: card status, manual and bulk check-in, check-in history, and scheduled auto check-in. + +### 中文 + +- MiniMax Code 账号现已支持每日签到:账号卡片状态、手动/一键签到、签到记录以及定时自动签到均已接入。 diff --git a/internal/providers/minimaxcode/checkin.go b/internal/providers/minimaxcode/checkin.go new file mode 100644 index 00000000..c5f50fbf --- /dev/null +++ b/internal/providers/minimaxcode/checkin.go @@ -0,0 +1,445 @@ +package minimaxcode + +import ( + "bytes" + "context" + "crypto/md5" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "runtime" + "sort" + "strconv" + "strings" + "time" + + "github.com/caigee-cmd/cli2api/internal/providers" +) + +// Daily check-in endpoints used by the MiniMax Code TUI (/checkin). They live on +// the same agent gateway as chat but under the first-party "minimax-cloud" +// prefix, and every request carries the signed query/headers the desktop client +// builds. Status is a read; claim is a POST of "{}". +const ( + signinStatusPath = "/minimax-cloud/api/v1/signin/status" + signinClaimPath = "/minimax-cloud/api/v1/signin/claim" + userInfoPath = "/v1/api/user/info" + + // Public-gateway attribution fields. The route validates the signature built + // from these fixed values; desktop_version only tags the caller. + gatewayAppVersion = "0.7.2" + gatewayVersionCode = "22201" + gatewaySignature = "I*7Cf%WZ#S&%1RlZJ&C2" + // The daily panel rolls over at 00:00 Asia/Shanghai for both regions, so the + // query carries that offset instead of the host's local zone. + gatewayTimezoneOffset = 8 * 3600 + checkinTimeout = 30 * time.Second +) + +// Panel day statuses and claim results, mirrored from the desktop client. +const ( + signinDayUpcoming = 1 + signinDayClaimable = 2 + signinDayClaimed = 3 + signinDayDisabled = 4 + + signinSceneCompleted = 3 + signinSceneBroken = 4 + + signinClaimed = 1 + signinAlreadyClaimed = 2 +) + +type signinDay struct { + DayNo int `json:"day_no"` + Points float64 `json:"points"` + BonusPoints float64 `json:"bonus_points,omitempty"` + Status int `json:"status"` + IsToday bool `json:"is_today"` +} + +type signinPanel struct { + Scene int `json:"scene"` + Days []signinDay `json:"days"` +} + +type signinClaim struct { + ClaimResult int `json:"claim_result"` + DayNo int `json:"day_no"` + Points float64 `json:"points"` + ExpireAtMs int64 `json:"expire_at_ms"` +} + +// Checkin implements providers.AccountCheckiner for the MiniMax Code daily +// sign-in. It reads the seven-day panel, claims today when the panel offers it, +// and reports "already"/"skipped" otherwise so the console card and records stay +// accurate. +func (c *Client) Checkin(ctx context.Context, accountID string) (providers.CheckinResult, error) { + ctx, cancel := context.WithTimeout(ctx, checkinTimeout) + defer cancel() + + credential, err := c.credential(ctx, accountID) + if err != nil { + return providers.CheckinResult{}, err + } + userID, err := c.checkinUserID(ctx, accountID, credential) + if err != nil { + return providers.CheckinResult{}, err + } + + data, err := c.signedGatewayCall(ctx, accountID, http.MethodGet, signinStatusPath, "", userID, "status") + if err != nil { + return providers.CheckinResult{}, err + } + var panel signinPanel + if err := json.Unmarshal(data, &panel); err != nil { + return providers.CheckinResult{}, fmt.Errorf("minimaxcode check-in: invalid status payload") + } + + today := todaySigninDay(panel) + switch { + case today != nil && today.Status == signinDayClaimed: + return alreadyCheckedInResult(panel), nil + case today != nil && today.Status == signinDayClaimable: + return c.claimSignin(ctx, accountID, userID) + default: + return providers.CheckinResult{Status: "skipped", Message: skippedCheckinMessage(panel)}, nil + } +} + +// claimSignin POSTs the claim for a panel that reported today as CLAIMABLE. +func (c *Client) claimSignin(ctx context.Context, accountID, userID string) (providers.CheckinResult, error) { + data, err := c.signedGatewayCall(ctx, accountID, http.MethodPost, signinClaimPath, "{}", userID, "claim") + if err != nil { + return providers.CheckinResult{}, err + } + var claim signinClaim + if err := json.Unmarshal(data, &claim); err != nil { + return providers.CheckinResult{}, fmt.Errorf("minimaxcode check-in: invalid claim payload") + } + switch claim.ClaimResult { + case signinClaimed: + message := "签到成功" + if claim.Points > 0 { + message = fmt.Sprintf("签到成功 +%g 积分", claim.Points) + } + return providers.CheckinResult{Status: "success", Message: message, RewardCredits: claim.Points}, nil + case signinAlreadyClaimed: + return providers.CheckinResult{Status: "already", Message: "今天已签到"}, nil + default: + return providers.CheckinResult{}, fmt.Errorf("minimaxcode check-in: unexpected claim result %d", claim.ClaimResult) + } +} + +// checkinUserID resolves the real MiniMax user id the gateway scopes the panel +// to. Login does not persist it, so the account's observed remote id is used +// when present and otherwise fetched once from the account identity endpoint. +func (c *Client) checkinUserID(ctx context.Context, accountID string, credential Credential) (string, error) { + if id := strings.TrimSpace(credential.UserID); id != "" { + return id, nil + } + if account, err := c.store.Get(ctx, accountID); err == nil { + if id := strings.TrimSpace(account.RemoteUID); id != "" { + return id, nil + } + } + data, err := c.signedGatewayCall(ctx, accountID, http.MethodGet, userInfoPath, "", "0", "account identity") + if err != nil { + return "", err + } + var document struct { + Data struct { + UserInfo userInfoPerson `json:"userInfo"` + UserInfoSnake userInfoPerson `json:"user_info"` + } `json:"data"` + UserInfo userInfoPerson `json:"userInfo"` + UserInfoSnake userInfoPerson `json:"user_info"` + } + if err := json.Unmarshal(data, &document); err != nil { + return "", fmt.Errorf("minimaxcode check-in: invalid account identity payload") + } + id := first( + document.Data.UserInfo.RealUserID, + document.Data.UserInfo.RealUserIDSnake, + document.Data.UserInfoSnake.RealUserID, + document.Data.UserInfoSnake.RealUserIDSnake, + document.UserInfo.RealUserID, + document.UserInfo.RealUserIDSnake, + document.UserInfoSnake.RealUserID, + document.UserInfoSnake.RealUserIDSnake, + ) + if id == "" { + return "", fmt.Errorf("minimaxcode check-in: account identity returned no user id") + } + _ = c.store.Observe(ctx, accountID, id, "ready", "", "") + return id, nil +} + +type userInfoPerson struct { + RealUserID string `json:"realUserID"` + RealUserIDSnake string `json:"real_user_id"` +} + +// signedGatewayCall performs one signed public-gateway request and unwraps the +// response envelope. A 401/403 refreshes the single-use token once and retries; +// the identity and status calls are reads, and status must pass before any +// claim is attempted, so the retry cannot double-claim. +func (c *Client) signedGatewayCall(ctx context.Context, accountID string, method, path, body, userID, operation string) (json.RawMessage, error) { + raw, status, err := c.signedGatewayCallOnce(ctx, accountID, method, path, body, userID) + if err != nil { + return nil, err + } + if status == http.StatusUnauthorized || status == http.StatusForbidden { + if _, refreshErr := c.forceRefresh(ctx, accountID); refreshErr != nil { + return nil, fmt.Errorf("minimaxcode check-in: %s authentication failed (HTTP %d): %w", operation, status, refreshErr) + } + raw, status, err = c.signedGatewayCallOnce(ctx, accountID, method, path, body, userID) + if err != nil { + return nil, err + } + } + if status >= 300 { + return nil, fmt.Errorf("minimaxcode check-in: %s HTTP %d: %s", operation, status, truncate(string(raw), 300)) + } + return gatewayEnvelopeData(raw) +} + +func (c *Client) signedGatewayCallOnce(ctx context.Context, accountID string, method, path, body, userID string) ([]byte, int, error) { + credential, err := c.credential(ctx, accountID) + if err != nil { + return nil, 0, err + } + client, err := c.httpClient(ctx, accountID) + if err != nil { + return nil, 0, err + } + request, err := c.newSignedGatewayRequest(ctx, credential, method, path, body, userID) + if err != nil { + return nil, 0, err + } + response, err := client.Do(request) + if err != nil { + return nil, 0, fmt.Errorf("minimaxcode check-in: %w", err) + } + defer response.Body.Close() + raw, _ := io.ReadAll(io.LimitReader(response.Body, 1<<20)) + return raw, response.StatusCode, nil +} + +// newSignedGatewayRequest mirrors the desktop client's URL query and +// yy/x-timestamp/x-signature attribution headers. The signature is an md5 over +// the exact path+query sent, so both sides must build the same string. +func (c *Client) newSignedGatewayRequest(ctx context.Context, credential Credential, method, path, body, userID string) (*http.Request, error) { + now := c.now() + query := url.Values{} + if path == signinStatusPath || path == signinClaimPath { + query.Set("device_platform", "web") + query.Set("is_desktop", "1") + query.Set("desktop_version", gatewayAppVersion) + } else { + query.Set("device_platform", "mcode") + } + query.Set("biz_id", "3") + query.Set("app_id", "3001") + query.Set("version_code", gatewayVersionCode) + query.Set("unix", strconv.FormatInt(now.UnixMilli(), 10)) + query.Set("timezone_offset", strconv.Itoa(gatewayTimezoneOffset)) + language := "zh" + if credential.Site == "global" { + language = "en" + } + query.Set("sys_language", language) + query.Set("lang", language) + query.Set("device_id", "0") + query.Set("os_name", gatewayOSName()) + query.Set("browser_name", "mcode") + query.Set("user_id", strings.TrimSpace(userID)) + query.Set("client", "mcode") + encodedQuery := query.Encode() + pathWithSearch := path + "?" + encodedQuery + endpoint := strings.TrimRight(credential.agentBase(), "/") + pathWithSearch + + second := now.Unix() + signatureBody := body + yyBody := body + if method == http.MethodGet { + signatureBody = "" + yyBody = "{}" + } + if yyBody == "" { + yyBody = "{}" + } + yy := md5Hex(encodeURIComponent(pathWithSearch) + "_" + yyBody + md5Hex(strconv.FormatInt(now.UnixMilli(), 10)) + "ooui") + signature := md5Hex(strconv.FormatInt(second, 10) + gatewaySignature + signatureBody) + + var reader io.Reader + if method == http.MethodPost { + reader = bytes.NewReader([]byte(body)) + } + request, err := http.NewRequestWithContext(ctx, method, endpoint, reader) + if err != nil { + return nil, err + } + request.Header.Set("Accept", "application/json") + request.Header.Set("Content-Type", "application/json") + request.Header.Set("User-Agent", "MiniMaxCode") + request.Header.Set("Authorization", "Bearer "+credential.AccessToken) + request.Header.Set("yy", yy) + request.Header.Set("x-timestamp", strconv.FormatInt(second, 10)) + request.Header.Set("x-signature", signature) + return request, nil +} + +// gatewayEnvelopeData returns the data member of a MiniMax gateway envelope, +// rejecting a non-zero base_resp/statusInfo code. +func gatewayEnvelopeData(raw []byte) (json.RawMessage, error) { + var envelope struct { + BaseResp struct { + StatusCode int `json:"status_code"` + StatusMsg string `json:"status_msg"` + } `json:"base_resp"` + StatusInfo struct { + Code int `json:"code"` + Message string `json:"message"` + Msg string `json:"msg"` + } `json:"statusInfo"` + Data json.RawMessage `json:"data"` + } + if err := json.Unmarshal(raw, &envelope); err != nil { + return nil, fmt.Errorf("minimaxcode check-in: invalid gateway response") + } + if envelope.BaseResp.StatusCode != 0 { + message := first(envelope.BaseResp.StatusMsg, "request failed") + return nil, fmt.Errorf("minimaxcode check-in: upstream status %d: %s", envelope.BaseResp.StatusCode, message) + } + if envelope.StatusInfo.Code != 0 { + message := first(envelope.StatusInfo.Message, envelope.StatusInfo.Msg, "request failed") + if envelope.StatusInfo.Code == 1_000_048 { + return nil, fmt.Errorf("minimaxcode check-in: authentication failed: %s", message) + } + return nil, fmt.Errorf("minimaxcode check-in: upstream status %d: %s", envelope.StatusInfo.Code, message) + } + if len(envelope.Data) == 0 || string(envelope.Data) == "null" { + return nil, fmt.Errorf("minimaxcode check-in: gateway response has no data") + } + return envelope.Data, nil +} + +func todaySigninDay(panel signinPanel) *signinDay { + for index := range panel.Days { + if panel.Days[index].IsToday { + return &panel.Days[index] + } + } + return nil +} + +// signinStreak counts consecutive claimed days up to and including today (or up +// to yesterday when today is still claimable), matching the TUI panel. +func signinStreak(panel signinPanel) int { + days := append([]signinDay(nil), panel.Days...) + sort.Slice(days, func(left, right int) bool { return days[left].DayNo < days[right].DayNo }) + todayIndex := -1 + for index := range days { + if days[index].IsToday { + todayIndex = index + break + } + } + if todayIndex < 0 { + return 0 + } + index := -1 + switch days[todayIndex].Status { + case signinDayClaimed: + index = todayIndex + case signinDayClaimable: + index = todayIndex - 1 + } + streak := 0 + for ; index >= 0; index-- { + if days[index].Status != signinDayClaimed { + break + } + streak++ + } + return streak +} + +func alreadyCheckedInResult(panel signinPanel) providers.CheckinResult { + today := todaySigninDay(panel) + points := 0.0 + if today != nil { + points = today.Points + } + message := "今天已签到" + if points > 0 { + message = fmt.Sprintf("今天已签到 +%g 积分", points) + } + if streak := signinStreak(panel); streak > 1 { + message += fmt.Sprintf("(连签 %d 天)", streak) + } + return providers.CheckinResult{Status: "already", Message: message, RewardCredits: points} +} + +func skippedCheckinMessage(panel signinPanel) string { + switch panel.Scene { + case signinSceneCompleted: + return "本周签到已完成" + case signinSceneBroken: + return "签到活动暂时不可用" + } + today := todaySigninDay(panel) + if today == nil { + return "签到活动未开始" + } + switch today.Status { + case signinDayDisabled: + return "签到活动未开放" + case signinDayUpcoming: + return "今日签到尚未开始" + default: + return "今日暂不可签到" + } +} + +// encodeURIComponent mirrors JavaScript's encodeURIComponent, which the desktop +// client applies to the signed path+query before hashing. +func encodeURIComponent(value string) string { + var builder strings.Builder + for index := 0; index < len(value); index++ { + char := value[index] + switch { + case char >= 'A' && char <= 'Z', char >= 'a' && char <= 'z', char >= '0' && char <= '9': + builder.WriteByte(char) + case strings.ContainsRune("-_.!~*'()", rune(char)): + builder.WriteByte(char) + default: + builder.WriteByte('%') + builder.WriteByte("0123456789ABCDEF"[char>>4]) + builder.WriteByte("0123456789ABCDEF"[char&15]) + } + } + return builder.String() +} + +func md5Hex(value string) string { + sum := md5.Sum([]byte(value)) + return hex.EncodeToString(sum[:]) +} + +func gatewayOSName() string { + switch runtime.GOOS { + case "windows": + return "win32" + case "darwin": + return "darwin" + default: + return "linux" + } +} + +var _ providers.AccountCheckiner = (*Client)(nil) diff --git a/internal/providers/minimaxcode/client.go b/internal/providers/minimaxcode/client.go index 1c97dacb..9f11859a 100644 --- a/internal/providers/minimaxcode/client.go +++ b/internal/providers/minimaxcode/client.go @@ -254,6 +254,7 @@ func (c *Client) Adapter() providers.Adapter { Classifier: classifier{}, ImportExport: importer{}, Prober: c, + Checkin: c, } } diff --git a/internal/providers/minimaxcode/minimaxcode_test.go b/internal/providers/minimaxcode/minimaxcode_test.go index 30af4f28..cf972c75 100644 --- a/internal/providers/minimaxcode/minimaxcode_test.go +++ b/internal/providers/minimaxcode/minimaxcode_test.go @@ -17,9 +17,10 @@ import ( ) type memoryStore struct { - mu sync.Mutex - payload []byte - account accounts.Account + mu sync.Mutex + payload []byte + account accounts.Account + observedID string } func (s *memoryStore) Get(context.Context, string) (accounts.Account, error) { return s.account, nil } @@ -34,7 +35,10 @@ func (s *memoryStore) SaveCredentialPayload(_ context.Context, _, _ string, payl s.payload = append([]byte(nil), payload...) return nil } -func (s *memoryStore) Observe(context.Context, string, string, string, string, string) error { +func (s *memoryStore) Observe(_ context.Context, _ string, remoteID, _, _, _ string) error { + s.mu.Lock() + defer s.mu.Unlock() + s.observedID = remoteID return nil } @@ -202,3 +206,232 @@ func TestModelsFallback(t *testing.T) { } var _ = fmt.Sprintf + +func newCheckinTestClient(t *testing.T, agentBase, userID string) (*Client, *memoryStore) { + t.Helper() + store := &memoryStore{account: accounts.Account{Enabled: true, RemoteUID: userID}} + credential := Credential{ + Format: CredentialFormat, + AccessToken: "tok", + Site: "cn", + AccountBase: agentBase, + AgentBase: agentBase, + Region: "cn", + UserID: userID, + ExpiresAt: time.Now().Add(time.Hour).Unix(), + } + payload, err := credential.Encode() + if err != nil { + t.Fatal(err) + } + store.payload = payload + client := NewClient(store) + client.http = &http.Client{} + acceptTestEndpoint = true + return client, store +} + +func TestCheckinAlreadyToday(t *testing.T) { + claimCalled := false + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == signinClaimPath { + claimCalled = true + http.Error(w, "claim must not run when today is already signed", http.StatusTeapot) + return + } + if r.URL.Path != signinStatusPath { + http.NotFound(w, r) + return + } + if r.Header.Get("Authorization") != "Bearer tok" { + t.Error("missing bearer token") + } + if r.Header.Get("yy") == "" || len(r.Header.Get("x-signature")) != 32 || r.Header.Get("x-timestamp") == "" { + t.Error("missing gateway signature headers") + } + if r.URL.Query().Get("user_id") != "u-1" || r.URL.Query().Get("device_platform") != "web" || r.URL.Query().Get("is_desktop") != "1" { + t.Errorf("unexpected query: %s", r.URL.RawQuery) + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"base_resp":{"status_code":0},"data":{"scene":2,"days":[ + {"day_no":1,"points":100,"status":3,"is_today":false}, + {"day_no":2,"points":200,"status":3,"is_today":false}, + {"day_no":3,"points":400,"status":3,"is_today":true}, + {"day_no":4,"points":500,"status":1,"is_today":false}, + {"day_no":5,"points":500,"status":1,"is_today":false}, + {"day_no":6,"points":500,"status":1,"is_today":false}, + {"day_no":7,"points":500,"status":1,"is_today":false}]}}`) + })) + defer server.Close() + client, _ := newCheckinTestClient(t, server.URL, "u-1") + result, err := client.Checkin(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if result.Status != "already" || result.RewardCredits != 400 { + t.Fatalf("result = %+v", result) + } + if !strings.Contains(result.Message, "连签 3 天") { + t.Fatalf("message = %q", result.Message) + } + if claimCalled { + t.Fatal("claim endpoint must not run for an already signed day") + } +} + +func TestCheckinClaimsToday(t *testing.T) { + claimBody := "" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case signinStatusPath: + _, _ = io.WriteString(w, `{"base_resp":{"status_code":0},"data":{"scene":2,"days":[ + {"day_no":1,"points":100,"status":3,"is_today":false}, + {"day_no":2,"points":200,"status":3,"is_today":false}, + {"day_no":3,"points":400,"status":2,"is_today":true}, + {"day_no":4,"points":500,"status":1,"is_today":false}, + {"day_no":5,"points":500,"status":1,"is_today":false}, + {"day_no":6,"points":500,"status":1,"is_today":false}, + {"day_no":7,"points":500,"status":1,"is_today":false}]}}`) + case signinClaimPath: + if r.Method != http.MethodPost { + t.Errorf("claim method = %s", r.Method) + } + raw, _ := io.ReadAll(r.Body) + claimBody = string(raw) + if len(r.Header.Get("x-signature")) != 32 { + t.Error("claim missing signature") + } + _, _ = io.WriteString(w, `{"base_resp":{"status_code":0},"data":{"claim_id":"c-1","claim_result":1,"day_no":3,"points":400,"expire_at_ms":1795858082691}}`) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client, _ := newCheckinTestClient(t, server.URL, "u-1") + result, err := client.Checkin(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if result.Status != "success" || result.RewardCredits != 400 { + t.Fatalf("result = %+v", result) + } + if claimBody != "{}" { + t.Fatalf("claim body = %q", claimBody) + } +} + +func TestCheckinSkipsWhenDisabled(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != signinStatusPath { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"base_resp":{"status_code":0},"data":{"scene":2,"days":[ + {"day_no":1,"points":100,"status":3,"is_today":false}, + {"day_no":2,"points":200,"status":3,"is_today":false}, + {"day_no":3,"points":400,"status":4,"is_today":true}, + {"day_no":4,"points":500,"status":1,"is_today":false}, + {"day_no":5,"points":500,"status":1,"is_today":false}, + {"day_no":6,"points":500,"status":1,"is_today":false}, + {"day_no":7,"points":500,"status":1,"is_today":false}]}}`) + })) + defer server.Close() + client, _ := newCheckinTestClient(t, server.URL, "u-1") + result, err := client.Checkin(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if result.Status != "skipped" || !strings.Contains(result.Message, "未开放") { + t.Fatalf("result = %+v", result) + } +} + +func TestCheckinResolvesUserIDFromIdentity(t *testing.T) { + statusUserID := "" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case userInfoPath: + if r.URL.Query().Get("user_id") != "0" { + t.Errorf("identity user_id = %q", r.URL.Query().Get("user_id")) + } + _, _ = io.WriteString(w, `{"base_resp":{"status_code":0},"data":{"userInfo":{"realUserID":"u-9"}}}`) + case signinStatusPath: + statusUserID = r.URL.Query().Get("user_id") + _, _ = io.WriteString(w, `{"base_resp":{"status_code":0},"data":{"scene":2,"days":[ + {"day_no":3,"points":400,"status":3,"is_today":true}]}}`) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client, store := newCheckinTestClient(t, server.URL, "") + result, err := client.Checkin(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if result.Status != "already" { + t.Fatalf("result = %+v", result) + } + if statusUserID != "u-9" { + t.Fatalf("status user_id = %q", statusUserID) + } + if store.observedID != "u-9" { + t.Fatalf("observed id = %q", store.observedID) + } +} + +func TestCheckinRefreshesUnauthorizedToken(t *testing.T) { + statusCalls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case signinStatusPath: + statusCalls++ + if statusCalls == 1 { + w.WriteHeader(http.StatusUnauthorized) + return + } + if r.Header.Get("Authorization") != "Bearer new-token" { + t.Errorf("retry authorization = %q", r.Header.Get("Authorization")) + } + _, _ = io.WriteString(w, `{"base_resp":{"status_code":0},"data":{"scene":2,"days":[ + {"day_no":3,"points":400,"status":3,"is_today":true}]}}`) + case tokenPath: + _, _ = io.WriteString(w, `{"access_token":"new-token","refresh_token":"new-refresh","expires_in":3600}`) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client, _ := newCheckinTestClient(t, server.URL, "u-1") + result, err := client.Checkin(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if result.Status != "already" || statusCalls != 2 { + t.Fatalf("result = %+v, status calls = %d", result, statusCalls) + } +} + +func TestEncodeURIComponentMatchesJavaScript(t *testing.T) { + cases := map[string]string{ + "/minimax-cloud/api/v1/signin/status?device_platform=web&user_id=u-1&lang=zh": "%2Fminimax-cloud%2Fapi%2Fv1%2Fsignin%2Fstatus%3Fdevice_platform%3Dweb%26user_id%3Du-1%26lang%3Dzh", + "a b!~*'()": "a%20b!~*'()", + "timezone=+8": "timezone%3D%2B8", + } + for input, want := range cases { + if got := encodeURIComponent(input); got != want { + t.Errorf("encodeURIComponent(%q) = %q, want %q", input, got, want) + } + } +} + +func TestAdapterExposesCheckin(t *testing.T) { + client, _ := newCheckinTestClient(t, "https://agent.minimax.cn", "u-1") + if client.Adapter().Checkin == nil { + t.Fatal("minimaxcode adapter must expose Checkin") + } +} diff --git a/internal/providers/registry.go b/internal/providers/registry.go index 3fd3ea70..5c160f29 100644 --- a/internal/providers/registry.go +++ b/internal/providers/registry.go @@ -452,11 +452,13 @@ var MiniMaxCode = ProviderDescriptor{ ID: "cn", Label: "CN", ChatBase: "https://agent.minimax.cn", BillingBase: "https://agent.minimax.cn", AuthBase: "https://account.minimax.cn", DefaultDomain: "minimax.cn", + Checkin: &CheckinPolicy{Timezone: "Asia/Shanghai"}, }, { ID: "global", Label: "Global", ChatBase: "https://agent.minimax.io", BillingBase: "https://agent.minimax.io", AuthBase: "https://account.minimax.io", DefaultDomain: "minimax.io", + Checkin: &CheckinPolicy{Timezone: "Asia/Shanghai"}, }, }, DefaultRegion: "cn", diff --git a/internal/providers/registry_test.go b/internal/providers/registry_test.go index 45ff702e..c5ea2695 100644 --- a/internal/providers/registry_test.go +++ b/internal/providers/registry_test.go @@ -66,3 +66,19 @@ func TestQwenWorkAdvertisesDailyCheckin(t *testing.T) { t.Fatal("qwenwork descriptor must support check-in") } } + +func TestMiniMaxCodeAdvertisesDailyCheckin(t *testing.T) { + for _, region := range []string{"cn", "global"} { + policy, ok := CheckinFor("minimaxcode", region) + if !ok || policy == nil { + t.Fatalf("region %s: minimaxcode check-in not advertised", region) + } + if policy.Timezone != "Asia/Shanghai" { + t.Fatalf("region %s: timezone=%q", region, policy.Timezone) + } + } + descriptor, ok := Get("minimaxcode") + if !ok || !descriptor.SupportsCheckin() { + t.Fatal("minimaxcode descriptor must support check-in") + } +}