Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changelog/unreleased/qoder-checkin-activity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### English

- Qoder check-in sends the activity page `Origin` / `Referer` headers alongside the desktop identity. The in-process PAT path had dropped them, which could make upstream return no daily credit campaign even when the activity was open.
- Global check-in retries the campaign list with the desktop COSY token when the OpenAPI bearer authenticates but exposes no claimable campaign.

### 中文

- Qoder 签到重新发送活动页需要的 `Origin` / `Referer` 头。进程内 PAT 路径之前漏掉这两个头,可能导致上游在活动开放时也不返回每日积分活动。
- 国际版在 OpenAPI token 能鉴权但拿不到可领活动时,会再用桌面 COSY token 重试活动列表。
50 changes: 43 additions & 7 deletions internal/providers/qoder/checkin.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,12 @@ import (
// on CN, OpenAPI token on Global; rotated via EnsureFreshSession before the
// call and force-refreshed on a 401).
//
// Campaign requests send the desktop identity headers the activity endpoint
// requires (User-Agent, Cosy-ClientType, Cosy-Version) and omit the derived
// cosy-machine* set. A full derived set is treated as a non-official client
// and the daily credit campaign is filtered out of an otherwise successful
// list, which is what made a later check-in look like "no campaign".
// Campaign requests send the desktop identity and activity-page headers the
// endpoint expects (User-Agent, Cosy-ClientType, Cosy-Version, Origin, Referer)
// and omit the derived cosy-machine* set. A full derived set is treated as a
// non-official client and the daily credit campaign is filtered out of an
// otherwise successful list, which is what made a later check-in look like
// "no campaign". Origin/Referer mirror the official activity iframe.
//
// Wire shape:
// - GET {openapi}/sash/api/v1/me/campaigns → list of campaigns
Expand Down Expand Up @@ -138,8 +139,11 @@ func (b *Bridge) Checkin(ctx context.Context) (providers.CheckinResult, error) {
req.Header.Set("User-Agent", "Qoder")
req.Header.Set("Cosy-ClientType", "10")
req.Header.Set("Cosy-Version", qauth.DesktopCosyVersion)
// Derived machine headers are deliberately absent. See the comment
// on Client.Checkin: a full derived set hides the daily campaign.
// The campaign endpoint serves the desktop activity iframe. Keep its
// browser origin/referer, while omitting derived machine headers that
// make upstream classify the request as non-official.
req.Header.Set("Origin", endpoint.origin)
req.Header.Set("Referer", endpoint.base+"/growth-page/activity-iframe")
// redirect: manual — the campaigns endpoint 302s to a login page when
// the token is rejected, and we want to see the 302 rather than follow it.
resp, err := checkinHTTPClient.Do(req)
Expand Down Expand Up @@ -181,9 +185,32 @@ func (b *Bridge) Checkin(ctx context.Context) (providers.CheckinResult, error) {
// 1) List campaigns. A successful response with nothing claimable is
// retried: the endpoint intermittently omits the daily campaign, and
// treating that single snapshot as final dropped the day's check-in.
// Global quota calls need a separate OpenAPI bearer, but the activity
// endpoint has also accepted the desktop COSY token. If the OpenAPI token
// authenticates yet returns no claimable credit campaign, retry the list
// once with the COSY token before declaring the activity closed.
cosyFallback := ""
if b.Region != nil && b.Region.NeedsOpenAPIToken {
cosyFallback = b.CurrentSecurityOauth()
}
campaignListFrom := func(raw map[string]any, err error) []campaign {
if err != nil {
return nil
}
return campaignsFrom(raw)
}

var items []campaign
for attempt, wait := range checkinListRetryWaits {
listRaw, _, err := doRequest(checkinCampaignsPath, http.MethodGet, false)
items = campaignListFrom(listRaw, err)
if err == nil && cosyFallback != "" && bearer != cosyFallback &&
!hasClaimableCreditCampaign(items) && attempt == 0 {
bearer = cosyFallback
cosyFallback = ""
listRaw, _, err = doRequest(checkinCampaignsPath, http.MethodGet, false)
items = campaignListFrom(listRaw, err)
}
if err != nil {
// 404 means the credit campaign is not open today; surface as skipped
// rather than an error so the scheduler logs a clean "already/none".
Expand Down Expand Up @@ -454,6 +481,15 @@ func creditCampaigns(items []campaign) []campaign {
return out
}

func hasClaimableCreditCampaign(items []campaign) bool {
for _, c := range creditCampaigns(items) {
if c.ClaimStatus == "CLAIMABLE" {
return true
}
}
return false
}

// campaignListNeedsRetry reports whether a successful listing should be
// fetched again. An empty list, or a list with no CLAIMABLE credit campaign,
// is the intermittent shape that used to end the day's check-in.
Expand Down
93 changes: 87 additions & 6 deletions internal/providers/qoder/checkin_inprocess_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ func TestBridgeCheckinHappyPath(t *testing.T) {
t.Fatalf("claim POST hits = %d want 2 (all CLAIMABLE CLAIM_BENEFIT)", claimHits.Load())
}

// Desktop identity only. A derived cosy-machine* set hides the daily
// credit campaign, so none of those headers may be sent.
// Desktop identity + activity-page headers. A derived cosy-machine* set
// hides the daily credit campaign, so none of those headers may be sent.
if got := gotHeaders.Get("Authorization"); !strings.HasPrefix(got, "Bearer ") {
t.Fatalf("Authorization = %q want Bearer <token>", got)
}
Expand All @@ -116,12 +116,18 @@ func TestBridgeCheckinHappyPath(t *testing.T) {
if got := gotHeaders.Get("Cosy-Version"); got != "0.4.8" {
t.Fatalf("Cosy-Version = %q want 0.4.8", got)
}
if got := gotHeaders.Get("Origin"); got != "https://stub.test" {
t.Fatalf("Origin = %q want activity page origin", got)
}
if got := gotHeaders.Get("Referer"); got != openapi.URL+"/growth-page/activity-iframe" {
t.Fatalf("Referer = %q want activity iframe referer", got)
}
for _, key := range []string{
"Cosy-Machineid", "Cosy-Machinetoken", "Cosy-Machinetype", "Cosy-Machinecode",
"Cosy-Machineos", "Cosy-Machinehostname", "Origin", "Referer",
"Cosy-Machineos", "Cosy-Machinehostname",
} {
if got := gotHeaders.Get(key); got != "" {
t.Fatalf("%s = %q, derived machine/browser headers must be omitted", key, got)
t.Fatalf("%s = %q, derived machine headers must be omitted", key, got)
}
}
}
Expand Down Expand Up @@ -490,7 +496,7 @@ func TestBridgeCheckinGlobalUsesOpenAPIBearer(t *testing.T) {
checkinHTTPClient = origClient
})

var campaignsAuth string
var campaignsAuth, campaignsOrigin, campaignsReferer string
openapi := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/jobToken/exchange":
Expand All @@ -500,6 +506,8 @@ func TestBridgeCheckinGlobalUsesOpenAPIBearer(t *testing.T) {
})
case r.URL.Path == "/sash/api/v1/me/campaigns":
campaignsAuth = r.Header.Get("Authorization")
campaignsOrigin = r.Header.Get("Origin")
campaignsReferer = r.Header.Get("Referer")
_ = json.NewEncoder(w).Encode(map[string]any{
"campaigns": []map[string]any{{
"campaignId": "c1", "actionType": "CLAIM_BENEFIT", "claimStatus": "LOCKED",
Expand All @@ -521,7 +529,7 @@ func TestBridgeCheckinGlobalUsesOpenAPIBearer(t *testing.T) {
b := NewBridge("fake-pat-secret-0123456789abcdef", region, mid, mtok, mtyp)
fakeJT := map[string]any{
"id": "test-uid-12345", "name": "tester",
"securityOauthToken": "cosy-sot", "refreshToken": "rt",
"securityOauthToken": "", "refreshToken": "rt",
"expireTime": float64(time.Now().Add(24 * time.Hour).UnixMilli()),
}
b.applyJobToken(fakeJT, "personal_standard")
Expand All @@ -533,4 +541,77 @@ func TestBridgeCheckinGlobalUsesOpenAPIBearer(t *testing.T) {
if campaignsAuth != "Bearer openapi-token-xyz" {
t.Fatalf("campaign Authorization = %q want the OpenAPI bearer", campaignsAuth)
}
if campaignsOrigin != "https://stub.test" {
t.Fatalf("campaign Origin = %q want activity page origin", campaignsOrigin)
}
if campaignsReferer != openapi.URL+"/growth-page/activity-iframe" {
t.Fatalf("campaign Referer = %q want activity iframe referer", campaignsReferer)
}
}

// TestBridgeCheckinGlobalFallsBackToCOSYForCampaigns covers the compatibility
// case where the OpenAPI bearer authenticates but does not expose the daily
// credit campaign, while the desktop COSY token still does.
func TestBridgeCheckinGlobalFallsBackToCOSYForCampaigns(t *testing.T) {
origHook := CheckinEndpointHook
origClient := checkinHTTPClient
t.Cleanup(func() {
CheckinEndpointHook = origHook
checkinHTTPClient = origClient
})

var campaignAuth []string
openapi := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/jobToken/exchange":
_ = json.NewEncoder(w).Encode(map[string]any{
"token": "openapi-token-xyz", "refresh_token": "openapi-rt",
"expires_at": "2099-01-01T00:00:00Z",
})
case r.Method == http.MethodGet && r.URL.Path == "/sash/api/v1/me/campaigns":
campaignAuth = append(campaignAuth, r.Header.Get("Authorization"))
if len(campaignAuth) == 1 {
_ = json.NewEncoder(w).Encode(map[string]any{"campaigns": []map[string]any{{
"campaignId": "c1", "actionType": "CLAIM_BENEFIT", "claimStatus": "LOCKED",
}}})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"campaigns": []map[string]any{{
"campaignId": "c1", "actionType": "CLAIM_BENEFIT", "claimStatus": "CLAIMABLE",
"benefit": map[string]any{"kind": "CREDITS", "amount": 100.0},
}}})
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/claim"):
_ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"status": "CLAIMED"}})
default:
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
http.NotFound(w, r)
}
}))
defer openapi.Close()
CheckinEndpointHook = func(*qauth.RegionConfig) *checkinRegion {
return &checkinRegion{base: openapi.URL, origin: "https://stub.test"}
}
checkinHTTPClient = openapi.Client()

mid, mtok, mtyp := mustDeriveMachineIdentity("fake-pat-secret-0123456789abcdef")
region := &qauth.RegionConfig{Name: "global", OpenAPIBase: openapi.URL, NeedsOpenAPIToken: true}
b := NewBridge("fake-pat-secret-0123456789abcdef", region, mid, mtok, mtyp)
fakeJT := map[string]any{
"id": "test-uid-12345", "name": "tester",
"securityOauthToken": "cosy-sot", "refreshToken": "rt",
"expireTime": float64(time.Now().Add(24 * time.Hour).UnixMilli()),
}
b.applyJobToken(fakeJT, "personal_standard")
b.bootstrapped.Store(true)

result, err := b.Checkin(context.Background())
if err != nil {
t.Fatalf("Checkin err = %v", err)
}
if result.Status != "success" || result.RewardCredits != 100 {
t.Fatalf("result = %+v want success +100", result)
}
if len(campaignAuth) < 2 || campaignAuth[0] != "Bearer openapi-token-xyz" || campaignAuth[1] != "Bearer cosy-sot" {
t.Fatalf("campaign auth sequence = %v", campaignAuth)
}
}
Loading