diff --git a/README.md b/README.md index a8a0425..3fdea89 100644 --- a/README.md +++ b/README.md @@ -54,9 +54,9 @@ capabilities at the edge, not assumptions in the core domain model. bonus exchange (confirmed with the account password from a stdin bundle), and password login with an optional two-step code that issues the session cookie; - and an experimental M-Team adapter with session, account, search, and - detail reads plus acknowledged metafile fetch through the official API and a - site-issued API key. + and an experimental M-Team adapter with session, account, search, detail, + and bonus reads plus acknowledged metafile fetch and at-most-once bonus + exchange through the official API and a site-issued API key. - **Downloaders:** qBittorrent and Transmission reads, plus reviewed stopped adoption, recheck/start, stop, and keep-data removal of one exact job. - **Reconciliation:** one report that keeps site, downloader, metafile, and diff --git a/docs/ADDING_A_SITE.md b/docs/ADDING_A_SITE.md index 6d49f32..7537013 100644 --- a/docs/ADDING_A_SITE.md +++ b/docs/ADDING_A_SITE.md @@ -269,23 +269,24 @@ and do it in a separate behavior-preserving commit. | NexusPHP forks, including TJUPT | Cookie sessions match `cookie_header`, and HTML responses match the existing ports. | Page recognition and parsers for that fork, with synthetic fixtures. Forks differ, so do not assume TJUPT's pages. | | Unit3D | Cookie-session web pages fit. | Using its token-authenticated API instead runs into the gaps below. | | Gazelle-based trackers | Cookie sessions fit; their JSON responses need a JSON parser rather than HTML recognition. | Where an API key replaces the session cookie, the gaps below apply. | -| M-Team | Status, account, search, detail, the signed-link metafile download, and live-site reconciliation are implemented in `internal/site/mteam` over the JSON API with an API key. | Bonus commands: the open gaps below. | +| M-Team | Status, account, search, detail, the bonus shop catalog, review, and exchange, the signed-link metafile download, and live-site reconciliation are implemented in `internal/site/mteam` over the JSON API with an API key. | RSS, seeding lists, and messages are not implemented. | ## Gaps for API-token sites These are the places that assumed a cookie, HTML, or a single origin. The -M-Team adapter closed what its four reads and its download needed; the rest is +M-Team adapter closed what its reads, its download, and its bonus exchange +needed; the rest is design work for whichever pull request first needs it. Each open item changes a public contract or a security control, so it needs its own review. | Gap | Status | Where | What is left | |---|---|---|---| | Only one auth method existed | Done | `domain.AuthMethodAPIKeyHeader` (`api_key_header`); `knownAuthMethod` in `internal/site/descriptor.go` | Nothing. | -| Credential input was cookie-only | Partly done | `--api-key-stdin` and `readAPIKeyCredential` in `internal/cli` serve `site status`, `account`, `search`, and `detail`; `site metafile fetch` reads it with `readEffectfulAPIKeyCredential`; `reconcile` takes `--site-api-key-stdin`, `--site-live`, and the bundle's `site_api_key` | Bonus commands still take cookies only. | -| The CLI gated on cookies | Partly done | `siteRead` in `internal/cli/site.go`, `site detail`, `site metafile fetch`, and `reconcile` check the method the caller chose | Two `SupportsAuth(domain.AuthMethodCookieHeader)` checks remain, in `site_bonus.go` and `site_bonus_exchange.go`. | +| Credential input was cookie-only | Done | `--api-key-stdin` and `readAPIKeyCredential` in `internal/cli` serve `site status`, `account`, `search`, `detail`, `bonus-catalog`, and `bonus review`; `site metafile fetch` and `site bonus exchange submit` read it with `readEffectfulAPIKeyCredential`; `reconcile` takes `--site-api-key-stdin`, `--site-live`, and the bundle's `site_api_key` | Nothing. The `--credential-bundle-stdin` of `site bonus exchange submit` still carries a cookie, because only TJUPT confirms an exchange with the password. | +| The CLI gated on cookies | Done | Every site command picks the method with `siteCredentialSourceFor` and checks that the site supports it | Nothing. | | The transport only sent `Cookie` | Done | `httpguard.NewWithHeaderCredential` binds one validated, non-reserved header | Nothing. | | Redaction did not know the header | Done | `security.Redact` covers `x-api-key` header lines and `apiKey`-style fields | Nothing. | -| No JSON requests | Done | `httpguard.Client.PostReadOnce`: one bounded, non-replayable POST with no redirect and no retry, covered in the threat model | Nothing for reads. Effectful API calls still need their own acknowledged port. | +| No JSON requests | Done | `httpguard.Client.PostReadOnce`: one bounded, non-replayable POST with no redirect and no retry, covered in the threat model; `PostEffectOnce` sends the same POST for an acknowledged write, such as the M-Team bonus exchange, and says so in its `User-Agent` | Nothing. | | One origin per site | Done | The API origin is the descriptor `BaseURL`; a signed link and its one redirect may reach only hosts the adapter allowlists (`siteHost` in `internal/site/mteam/metafile.go`), each on a fresh credential-free client | A new site's allowlist needs the same review before its hosts are contacted. | | The download is two requests | Done | `site.NewLinkedMetafileFetchConfig` declares a linked route; `MetafileFetchLimits.MaxLinkRequests` and `MetafileFetchUsage.LinkRequestsAttempted` count the requests before the one metafile `GET`, and the sealed record checks them; `httpguard.SecretLink` and `GetLinkOnce` keep the signed URL secret | Nothing. Both fields are omitted for direct routes, so TJUPT records are unchanged. See [MTEAM_ADAPTER.md](MTEAM_ADAPTER.md#metafile-download). | | Site-specific CLI text | Done | `detailRouteWarnings` in `internal/cli/site_detail.go` keys the `site detail` warning by route ID; an unlisted route gets only the generic sentence | Add a sentence there when a new detail route has something specific to say. | diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 8940148..dd4df0b 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -83,7 +83,8 @@ deliberately does not. For step-by-step usage, see the remain site claims only; - an explicitly acknowledged, durable bonus-exchange state machine (TJUPT confirms each exchange with the account password, read with the cookie from - one strict stdin bundle and sent in the same single POST): + one strict stdin bundle and sent in the same single POST; M-Team exchanges + one unit of goods that take no input with the API key alone): private reviewed intent, fresh exact-option re-observation, deterministic no-clobber attempt marker, at most one non-retried POST, and a separately sealed confirmed/rejected/unknown outcome; its credential-free bounded @@ -111,11 +112,13 @@ deliberately does not. For step-by-step usage, see the shown, acknowledgement flags are still required, account passwords are never saved, and `site logout SITE` deletes the file; - an experimental M-Team session check, account snapshot (username, uploaded - and downloaded bytes, ratio, and bonus), first-page torrent search with - seeders, leechers, promotion factors, and category names, and torrent detail - for one remote ID, through one read-only POST per invocation to the official - JSON API, authenticated by a site-issued API key saved by `site login` or - piped on stdin, with no redirect, proxy, or retry; + and downloaded bytes, ratio, and bonus), torrent search by page, mode, + category, and free promotion with seeders, leechers, promotion factors, and + category names, torrent detail for one remote ID, and a bonus-shop catalog + and exact-goods review, through read-only POSTs to the official JSON API (one + per invocation; the catalog reads the balance and the shop on one client), + authenticated by a site-issued API key saved by `site login` or piped on + stdin, with no redirect, proxy, or retry; - an explicitly acknowledged M-Team metafile fetch for one remote ID: one token POST for a signed download link, one credential-free GET of that link, and at most one further GET only for a redirect to an M-Team HTTPS host, with diff --git a/docs/MTEAM_ADAPTER.md b/docs/MTEAM_ADAPTER.md index d8061e7..155d997 100644 --- a/docs/MTEAM_ADAPTER.md +++ b/docs/MTEAM_ADAPTER.md @@ -5,15 +5,19 @@ M-Team (馒头PT, TP :: mTorrent) is the second experimental site and the first that uses a site-issued API key instead of a session cookie. The adapter talks only to M-Team's own hosts, starting at the official JSON API at -`https://api2.m-team.cc`, and declares four reads and one acknowledged -download: +`https://api2.m-team.cc`, and declares six reads and two acknowledged +effects: - session check (`site status`); - account snapshot (`site account`); - torrent search (`site search`), with category names; - torrent detail (`site detail`); +- bonus shop catalog (`site bonus-catalog`) and one-offer review (`site bonus + review`); - metafile download (`site metafile fetch`), which is tracker-visible and needs - `--acknowledge-site-effect`; see [Metafile download](#metafile-download). + `--acknowledge-site-effect`; see [Metafile download](#metafile-download); +- bonus exchange (`site bonus exchange submit`), which spends bonus and needs + `--acknowledge-bonus-exchange`; see [Bonus shop](#bonus-shop). The reads were smoke-tested live on 2026-10-16 with a newly created API key: `site status` reported `authenticated`, `site account` read the profile, `site @@ -51,6 +55,8 @@ ptctl site search mteam "Ubuntu" ptctl site search --output json mteam "Ubuntu" ptctl site search --page 2 --category 419,439 --free mteam "Ubuntu" ptctl site detail mteam REMOTE_ID +ptctl site bonus-catalog mteam +ptctl site bonus review mteam OPTION ptctl site metafile fetch --acknowledge-site-effect --metafile-store "$PTCTL_STORE" mteam REMOTE_ID ``` @@ -76,16 +82,19 @@ sent. `--cookie-stdin` is refused because the adapter does not accept cookies. ## Requests -Each read sends exactly one request and never retries (the download takes more; -see [Metafile download](#metafile-download)): +Each read sends exactly one request and never retries, except `bonus-catalog`, +which sends two on one connection (the download takes more; see [Metafile +download](#metafile-download)): | Command | Request | Body | |---|---|---| | `site status`, `site account` | `POST /api/member/profile` | an empty `multipart/form-data` form | | `site search` | `POST /api/torrent/search` | `{"mode":"normal","keyword":QUERY,"pageNumber":1,"pageSize":50}`; the options below add `categories` and `discount` and change `mode` and `pageNumber` | | `site detail` | `POST /api/torrent/detail` | a `multipart/form-data` form with the one field `id` | +| `site bonus-catalog` | `POST /api/member/profile`, then `POST /api/mall/list` | an empty `multipart/form-data` form each | +| `site bonus review` | `POST /api/mall/list` | an empty `multipart/form-data` form | -The API exposes these reads as POST requests. All three endpoints only read; +The API exposes these reads as POST requests. All five endpoints only read; the reads send no other endpoint. In particular, `site detail` never calls `/api/torrent/viewHits`, which the website's own detail page calls to count a view. The request uses the same strict transport as every @@ -273,9 +282,66 @@ with `site_api_key` in place of `site_cookie`. The read is the one `/api/torrent/detail` request above; it never asks for a signed download link. See [Reconciliation](guide/reconcile.md). +## Bonus shop + +M-Team sells goods for bonus (魔力值) in its shop (商城). `site bonus-catalog +mteam` reads the balance from the profile and the goods from `/api/mall/list`, +one row per goods ID. The option is the goods ID; the columns are the name, the +goods type, the price, and a status: + +| Goods type | Example | Status | +|---|---|---| +| `UPLOAD` | 上传量, priced per GB | `available` | +| `INVITE` | an invitation | `available` | +| `TITLE`, `GLOBAL_FREE_SINGLE`, `GLOBAL_FREE_POOL` | a custom title, a site-wide free promotion | `available, requires input` | +| any other type, such as `INVITE_BUY_BONUS` | selling an invitation back | `unknown` | + +Goods the shop marks off the shelf (`shelf` is `NO`) are `disabled`; goods +with any other shelf value, or limited to some roles, are `unknown`. The name is the +simplified-Chinese name the API returns (which the site sometimes writes in +traditional script), else the traditional or English one. A shop answer that is +empty, repeats a goods ID, or holds goods without a canonical ID, type, name, or +price fails the whole catalog instead of returning a partial one. + +`site bonus review mteam OPTION` reads the shop once more and reports one goods +item as an offer review (route `mteam.mall_list_review.v1`). The balance is not +part of the review, so the review ID changes only when the goods item does, +such as when its price changes. The review accounting maps the JSON answer onto +the shared limits: each goods item counts as one form, each of its members as +one field, and each JSON token as one token. + +**Exchange.** `site bonus exchange submit` follows the same prepare, submit, +and status workflow as TJUPT (see [the sites guide](guide/sites.md)), with the +saved API key and no password. After one fresh review it sends one +`POST /api/mall/exchange` (route `mteam.mall_exchange_post.v1`) with the form +fields `goodsId` and `num`, where `num` is always `1`: one unit, so one GB of +upload credit or one invitation. Only goods that are `available` and need no +input can be exchanged; for the rest the fresh review stops as +`submission_form_unavailable` and nothing is sent. The POST identifies itself +as an explicit-effect client in its `User-Agent`. The answer is read as: + +| Answer | Outcome | `SUBMISSION STOP` | +|---|---|---| +| API code `0` | `confirmed` | none | +| HTTP 401, or API code `401` | `rejected` | `server_authentication_rejected` | +| HTTP 429, or API code `4` | `rejected` | `server_rate_limited` | +| Any other API code, such as too little bonus or a shop limit | `rejected` | `server_refused` | +| Any other status, a body that is not JSON, or a cut-off answer | `unknown` | `submission_response_unrecognized` | + +A rejected exchange spends nothing. An `unknown` one may have spent bonus, is +never retried, and is checked on the site's own bonus log. The shop's own +limits, such as the upload-credit cap tied to share ratio, are enforced by the +site, not by ptctl. + +**Live check.** On 2026-10-16 `site bonus-catalog` and `site bonus review mteam +1` were run live: the catalog listed the six goods above with the balance, and +the review completed in one request. `site bonus exchange submit` has not been +run live, because the test account's balance was below the cheapest goods +item; it is covered by synthetic tests only. + ## Not supported yet -Bonus exchange, RSS, seeding lists, and messages are not implemented. +RSS, seeding lists, and messages are not implemented. ## Fixtures diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index bfe6adb..620e890 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -179,10 +179,11 @@ session or revoke the key on the site. Account and downloader passwords are never saved. The file is not encrypted; an OS keyring or credential helper remains future work (see [Known gaps](#known-gaps-before-broader-mutation-support)). -The M-Team adapter's reads send at most one bounded POST per command to one of -three read-only JSON API endpoints (`member/profile`, `torrent/search`, and -`torrent/detail`), with a non-replayable body of at most 16 KiB, and never -retry. Its metafile fetch sends one token POST, waits three seconds, and then +The M-Team adapter's reads send bounded POSTs to four read-only JSON API +endpoints (`member/profile`, `torrent/search`, `torrent/detail`, and +`mall/list`), one per command except `bonus-catalog`, which sends `member/profile` +then `mall/list` on one client spaced three seconds apart. Each body is +non-replayable and at most 16 KiB, and nothing is retried. Its metafile fetch sends one token POST, waits three seconds, and then makes at most two GETs as described above; the site's per-torrent daily download limit and burst refusals stop it as `rate_limited`. HTTP 429 is terminal. There is no cross-process limiter in the alpha, so callers must not loop or parallelize site commands. There is no Cloudflare or @@ -200,7 +201,8 @@ preserved, never arbitrary cookie, key, URL, header, or response text. The detail route sends only the canonical `id`; it deliberately omits NexusPHP's view-counting `hit` parameter and never follows the download reference found in the page. -Bonus review sends only the one GET and has no POST-capable transport surface. +TJUPT's bonus review sends only the one GET and has no POST-capable transport +surface; M-Team's sends the one read-only `mall/list` POST. The account projection accepts only the exact authenticated bonus-page route, valid UTF-8, a bounded username, and a canonical bonus decimal. Optional fields come only from the page's single user-panel table, and only when every @@ -221,6 +223,14 @@ timeout, transport ambiguity, unrecognized response, or local outcome-write failure is recorded as rejected/unknown when possible and is never used to justify another automatic request. +On M-Team the fresh review is the one read-only `mall/list` POST and the +submission is one `mall/exchange` POST sent through `PostEffectOnce`, whose +`User-Agent` names an explicit-effect client. The body holds only `goodsId` and +`num`, fixed at `1`, and goods that need user input or are not plainly +available never get one. The API key is the only credential. API code `0` is +confirmed and any other API code is rejected; a status, media type, or body +that is not recognized, or a cut-off answer, is unknown and is not retried. + A site that confirms exchanges with the account password (TJUPT) widens the secret surface to that password, so its handling is narrower than the cookie's. It is never saved and never read from argv. With `--credential-bundle-stdin` diff --git a/docs/guide/sites.md b/docs/guide/sites.md index 15c8f12..84358fa 100644 --- a/docs/guide/sites.md +++ b/docs/guide/sites.md @@ -163,9 +163,11 @@ API and never retry; search results add seeders, leechers, promotion, and category-name columns, and `search` takes `--page N`, `--mode normal|adult`, `--category ID`, and `--free`. `site metafile fetch` downloads one `.torrent` into the private store through M-Team's signed link, as described in -[metafiles.md](metafiles.md). Bonus commands are not available for M-Team yet, -and `reconcile` reads live site detail with a cookie only. Setup, results, and -error lines are in [MTEAM_ADAPTER.md](../MTEAM_ADAPTER.md): +[metafiles.md](metafiles.md). `bonus-catalog` and `bonus review` read M-Team's +bonus shop, and `bonus exchange submit` buys one unit of goods that need no +input with the API key alone. `reconcile --site-live` reads live detail with the +saved key. Setup, results, and error lines are in +[MTEAM_ADAPTER.md](../MTEAM_ADAPTER.md): ```bash ptctl site login mteam @@ -174,6 +176,8 @@ ptctl site account mteam ptctl site search mteam "Ubuntu" ptctl site search --page 2 --free mteam "Ubuntu" ptctl site detail mteam REMOTE_ID +ptctl site bonus-catalog mteam +ptctl site bonus review mteam GOODS_ID printf '%s' "$MTEAM_API_KEY" | ptctl site status --api-key-stdin mteam ``` @@ -205,9 +209,9 @@ flag, its `submit` uses the saved session cookie and asks for the password on the terminal with echo off; the password is used for that one exchange and never saved. Scripts pass the cookie and password together as one strict JSON bundle on stdin (`--credential-bundle-stdin`), and `--cookie-stdin` is refused; -see the TJUPT example below. A site that needs only the cookie uses the saved -cookie, or takes `--cookie-stdin`. A saved credential never stands in for -`--acknowledge-bonus-exchange`. +see the TJUPT example below. A site that needs only the cookie or API key, such +as M-Team, uses the saved one, or takes `--cookie-stdin` or `--api-key-stdin`. +A saved credential never stands in for `--acknowledge-bonus-exchange`. To cross that boundary, first initialize a private state store (the same versioned owner-only store format used by metafile artifacts), review the exact diff --git a/internal/cli/run.go b/internal/cli/run.go index e874dae..a119d5f 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -141,10 +141,10 @@ Usage: ptctl site account [--cookie-stdin | --api-key-stdin] [--output table|json] SITE ptctl site search [--cookie-stdin | --api-key-stdin] [--page N] [--mode MODE] [--category ID]... [--free] [--output table|json] SITE QUERY... ptctl site detail [--cookie-stdin | --api-key-stdin] [--output table|json] SITE REMOTE_ID - ptctl site bonus-catalog [--cookie-stdin] [--output table|json] SITE - ptctl site bonus review [--cookie-stdin] [--output table|json] SITE OPTION + ptctl site bonus-catalog [--cookie-stdin | --api-key-stdin] [--output table|json] SITE + ptctl site bonus review [--cookie-stdin | --api-key-stdin] [--output table|json] SITE OPTION ptctl site bonus exchange prepare --state-store DIR --expect-review-id ID [--output table|json] SITE OPTION - ptctl site bonus exchange submit --state-store DIR --intent-record RECORD_ID --expect-review-id ID [--cookie-stdin | --credential-bundle-stdin] --acknowledge-bonus-exchange [--output table|json] SITE OPTION + ptctl site bonus exchange submit --state-store DIR --intent-record RECORD_ID --expect-review-id ID [--cookie-stdin | --api-key-stdin | --credential-bundle-stdin] --acknowledge-bonus-exchange [--output table|json] SITE OPTION ptctl site bonus exchange status --state-store DIR --intent-record RECORD_ID [--output table|json] ptctl site bonus exchange list --state-store DIR [--max-operations N] [--output table|json] ptctl site bonus exchange prune --state-store DIR --intent-record RECORD_ID --operation-id ID --acknowledge-state-prune [--output table|json] diff --git a/internal/cli/site_bonus.go b/internal/cli/site_bonus.go index 24d6c3d..e081f10 100644 --- a/internal/cli/site_bonus.go +++ b/internal/cli/site_bonus.go @@ -51,12 +51,16 @@ func (a *app) siteBonusReview(args []string) error { fs := newFlagSet("site bonus review") output := fs.String("output", "table", "table or json") cookieStdin := fs.Bool("cookie-stdin", false, "read session Cookie header value from stdin") + apiKeyStdin := fs.Bool("api-key-stdin", false, "read a site-issued API key from stdin") if err := fs.Parse(args); err != nil { return usageError("site bonus review: %v", err) } if fs.NArg() != 2 { return usageError("site bonus review requires SITE and OPTION") } + if *cookieStdin && *apiKeyStdin { + return usageError("--cookie-stdin and --api-key-stdin are mutually exclusive") + } if err := validateOutput(*output); err != nil { return err } @@ -68,14 +72,15 @@ func (a *app) siteBonusReview(args []string) error { if !descriptor.Supports(domain.CapabilityBonusReview) { return usageError("site %q does not declare capability %q", descriptor.ID, domain.CapabilityBonusReview) } - if !descriptor.SupportsAuth(domain.AuthMethodCookieHeader) { - return usageError("site %q does not support cookie_header authentication", descriptor.ID) - } - // The site takes cookies, so without the flag this picks its saved cookie. - source, err := siteCredentialSourceFor(descriptor, *cookieStdin, false) + // Without a flag this picks the credential the site signs in with. + source, err := siteCredentialSourceFor(descriptor, *cookieStdin, *apiKeyStdin) if err != nil { return err } + readSecret := readCredential + if source.method == domain.AuthMethodAPIKeyHeader { + readSecret = readAPIKeyCredential + } reader, ok := adapter.(site.BonusReviewReader) if !ok { return usageError("site %q declares %q but does not implement its typed port", descriptor.ID, domain.CapabilityBonusReview) @@ -97,7 +102,7 @@ func (a *app) siteBonusReview(args []string) error { } report := newSiteBonusReviewReport(descriptor.ID, selector, config, limits) - credential, err := a.readSiteCredential(source, readCredential) + credential, err := a.readSiteCredential(source, readSecret) if err != nil { report.Blockers = append(report.Blockers, siteDetailFinding{Code: "credential.unavailable", Message: "the site credential could not be read"}) return a.finishSiteBonusReview(*output, report, siteCredentialReadError(source, err)) diff --git a/internal/cli/site_bonus_api_key_test.go b/internal/cli/site_bonus_api_key_test.go new file mode 100644 index 0000000..7d4e7b3 --- /dev/null +++ b/internal/cli/site_bonus_api_key_test.go @@ -0,0 +1,185 @@ +package cli + +import ( + "bytes" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/tonycoder-hub/ptctl/internal/bonusexchange" + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" +) + +// A site that signs in with an API key, as M-Team does, reviews and +// exchanges bonus offers with that key alone. + +func apiKeyBonusReview(t *testing.T) *fakeBonusReviewAdapter { + adapter := successfulFakeBonusReview(t) + adapter.authMethod = domain.AuthMethodAPIKeyHeader + return adapter +} + +func apiKeyBonusExchange(t *testing.T) *fakeBonusExchangeAdapter { + adapter := successfulFakeBonusExchange(t) + adapter.authMethod = domain.AuthMethodAPIKeyHeader + return adapter +} + +func TestSiteBonusReviewReadsAPipedOrSavedAPIKey(t *testing.T) { + useTempConfigDir(t) + adapter := apiKeyBonusReview(t) + var out bytes.Buffer + a := &app{stdin: strings.NewReader(apiKeyCanary + "\n"), stdout: &out, registry: site.NewRegistry(adapter)} + if err := a.siteBonusReview([]string{"--api-key-stdin", "--output", "json", "fakept", "1"}); err != nil || + adapter.opened != 1 || adapter.credential != apiKeyCanary || adapter.credentialMethod != domain.AuthMethodAPIKeyHeader || + strings.Contains(out.String(), "CANARY") { + t.Fatalf("err=%v opened=%d method=%q stdout=%q", err, adapter.opened, adapter.credentialMethod, out.String()) + } + + writeSavedCredential(t, "fakept", domain.AuthMethodAPIKeyHeader, savedAPIKeyCanary+"\n") + adapter = apiKeyBonusReview(t) + stdin := &trackingReader{} + out.Reset() + a = &app{stdin: stdin, stdout: &out, registry: site.NewRegistry(adapter)} + if err := a.siteBonusReview([]string{"--output", "json", "fakept", "1"}); err != nil || stdin.read || + adapter.credential != savedAPIKeyCanary || adapter.credentialMethod != domain.AuthMethodAPIKeyHeader || strings.Contains(out.String(), "CANARY") { + t.Fatalf("err=%v read=%t method=%q stdout=%q", err, stdin.read, adapter.credentialMethod, out.String()) + } +} + +func TestSiteBonusReviewCredentialFlagMisuseNeverReadsStdin(t *testing.T) { + useTempConfigDir(t) + for _, test := range []struct { + name string + adapter *fakeBonusReviewAdapter + args []string + want string + }{ + {name: "both flags", adapter: apiKeyBonusReview(t), args: []string{"--cookie-stdin", "--api-key-stdin", "fakept", "1"}, + want: "--cookie-stdin and --api-key-stdin are mutually exclusive"}, + {name: "cookie for an API key site", adapter: apiKeyBonusReview(t), args: []string{"--cookie-stdin", "fakept", "1"}, + want: `site "fakept" does not support cookie_header authentication`}, + {name: "API key for a cookie site", adapter: successfulFakeBonusReview(t), args: []string{"--api-key-stdin", "fakept", "1"}, + want: `site "fakept" does not support api_key_header authentication`}, + {name: "nothing saved", adapter: apiKeyBonusReview(t), args: []string{"fakept", "1"}, + want: `no saved API key for site "fakept"; run 'ptctl site login fakept' first, or pipe one with --api-key-stdin`}, + } { + t.Run(test.name, func(t *testing.T) { + reader := &trackingReader{} + var out bytes.Buffer + a := &app{stdin: reader, stdout: &out, registry: site.NewRegistry(test.adapter)} + var usage *usageErr + if err := a.siteBonusReview(test.args); !errors.As(err, &usage) || err.Error() != test.want || reader.read || out.Len() != 0 || test.adapter.opened != 0 { + t.Fatalf("err=%v read=%t opened=%d stdout=%q", err, reader.read, test.adapter.opened, out.String()) + } + }) + } +} + +func prepareAPIKeyBonusExchange(t *testing.T, adapter site.Adapter, reviewID string) (string, string) { + t.Helper() + stateRoot := initializedBonusExchangeStore(t) + prepared := runBonusExchangeCLI(t, &app{stdin: &trackingReader{}, registry: site.NewRegistry(adapter)}, []string{ + "prepare", "--state-store", stateRoot, "--expect-review-id", reviewID, "--output", "json", "fakept", "1", + }, false) + return stateRoot, prepared.Operation.IntentRecord.ID.String() +} + +func TestSiteBonusExchangeSubmitUsesAPipedOrSavedAPIKey(t *testing.T) { + useTempConfigDir(t) + adapter := apiKeyBonusExchange(t) + stateRoot, intent := prepareAPIKeyBonusExchange(t, adapter, adapter.review.ReviewID) + submitted := runBonusExchangeCLI(t, &app{stdin: strings.NewReader(apiKeyCanary + "\n"), registry: site.NewRegistry(adapter)}, []string{ + "submit", "--state-store", stateRoot, "--intent-record", intent, "--expect-review-id", adapter.review.ReviewID, + "--api-key-stdin", "--acknowledge-bonus-exchange", "--output", "json", "fakept", "1", + }, false) + if submitted.Outcome != bonusexchange.StateConfirmed || adapter.opened != 1 || adapter.submissions != 1 || + adapter.credential != apiKeyCanary || adapter.credentialMethod != domain.AuthMethodAPIKeyHeader { + t.Fatalf("submitted=%#v adapter=%#v", submitted, adapter) + } + assertDirectoryExcludesText(t, stateRoot, apiKeyCanary) + + writeSavedCredential(t, "fakept", domain.AuthMethodAPIKeyHeader, savedAPIKeyCanary+"\n") + adapter = apiKeyBonusExchange(t) + stateRoot, intent = prepareAPIKeyBonusExchange(t, adapter, adapter.review.ReviewID) + stdin := &trackingReader{} + submitted = runBonusExchangeCLI(t, &app{stdin: stdin, registry: site.NewRegistry(adapter)}, []string{ + "submit", "--state-store", stateRoot, "--intent-record", intent, "--expect-review-id", adapter.review.ReviewID, + "--acknowledge-bonus-exchange", "--output", "json", "fakept", "1", + }, false) + if stdin.read || submitted.Outcome != bonusexchange.StateConfirmed || adapter.submissions != 1 || + adapter.credential != savedAPIKeyCanary || adapter.credentialMethod != domain.AuthMethodAPIKeyHeader { + t.Fatalf("read=%t submitted=%#v adapter=%#v", stdin.read, submitted, adapter) + } + assertDirectoryExcludesText(t, stateRoot, savedAPIKeyCanary) +} + +func TestSiteBonusExchangeAPIKeyRejectionsArePublicStopReasons(t *testing.T) { + useTempConfigDir(t) + for _, stop := range []string{"server_refused", "server_rate_limited", "server_authentication_rejected"} { + adapter := apiKeyBonusExchange(t) + adapter.submissionOutcome = site.BonusExchangeOutcomeRejected + adapter.submissionStop = stop + stateRoot, intent := prepareAPIKeyBonusExchange(t, adapter, adapter.review.ReviewID) + var out bytes.Buffer + a := &app{stdin: strings.NewReader(apiKeyCanary), stdout: &out, registry: site.NewRegistry(adapter)} + err := a.siteBonusExchange([]string{ + "submit", "--state-store", stateRoot, "--intent-record", intent, "--expect-review-id", adapter.review.ReviewID, + "--api-key-stdin", "--acknowledge-bonus-exchange", "--output", "json", "fakept", "1", + }) + var envelope struct { + Data siteBonusExchangeReport `json:"data"` + } + if decodeErr := json.Unmarshal(out.Bytes(), &envelope); decodeErr != nil { + t.Fatal(decodeErr) + } + if err == nil || strings.Contains(out.String(), "CANARY") || envelope.Data.Outcome != bonusexchange.StateRejected || + envelope.Data.Request.Submission.StopReason != stop || adapter.submissions != 1 { + t.Fatalf("stop=%s err=%v report=%#v", stop, err, envelope.Data) + } + } +} + +func TestSiteBonusExchangeSubmitCredentialFlagMisuseNeverReadsStdin(t *testing.T) { + useTempConfigDir(t) + apiKeySite := apiKeyBonusExchange(t) + passwordSite := &fakePasswordBonusExchangeAdapter{fakeBonusExchangeAdapter: successfulFakeBonusExchange(t)} + for _, test := range []struct { + name string + adapter site.Adapter + flags []string + want string + }{ + {name: "API key and cookie", adapter: apiKeySite, flags: []string{"--api-key-stdin", "--cookie-stdin"}, + want: "site bonus exchange submit accepts one of --cookie-stdin, --api-key-stdin, or --credential-bundle-stdin"}, + {name: "API key and bundle", adapter: apiKeySite, flags: []string{"--api-key-stdin", "--credential-bundle-stdin"}, + want: "site bonus exchange submit accepts one of --cookie-stdin, --api-key-stdin, or --credential-bundle-stdin"}, + {name: "bundle for an API key site", adapter: apiKeySite, flags: []string{"--credential-bundle-stdin"}, + want: `site "fakept" bonus exchange takes only --api-key-stdin`}, + {name: "cookie for an API key site", adapter: apiKeySite, flags: []string{"--cookie-stdin"}, + want: `site "fakept" does not support cookie_header authentication`}, + {name: "API key for a password site", adapter: passwordSite, flags: []string{"--api-key-stdin"}, + want: `site "fakept" confirms bonus exchange with the account password; submit requires --credential-bundle-stdin`}, + {name: "nothing saved", adapter: apiKeySite, flags: nil, + want: `no saved API key for site "fakept"; run 'ptctl site login fakept' first, or pipe one with --api-key-stdin`}, + } { + t.Run(test.name, func(t *testing.T) { + reader := &trackingReader{} + var out bytes.Buffer + a := &app{stdin: reader, stdout: &out, registry: site.NewRegistry(test.adapter)} + args := append([]string{ + "submit", "--state-store", "/nonexistent-ptctl-store", "--intent-record", "sha256:" + strings.Repeat("a", 64), + "--expect-review-id", apiKeySite.review.ReviewID, "--acknowledge-bonus-exchange", + }, append(test.flags, "fakept", "1")...) + var usage *usageErr + if err := a.siteBonusExchange(args); !errors.As(err, &usage) || err.Error() != test.want || reader.read || out.Len() != 0 { + t.Fatalf("err=%v read=%t stdout=%q", err, reader.read, out.String()) + } + }) + } + if apiKeySite.opened != 0 || passwordSite.opened != 0 { + t.Fatalf("a session opened: %d %d", apiKeySite.opened, passwordSite.opened) + } +} diff --git a/internal/cli/site_bonus_exchange.go b/internal/cli/site_bonus_exchange.go index 867b883..2e98af8 100644 --- a/internal/cli/site_bonus_exchange.go +++ b/internal/cli/site_bonus_exchange.go @@ -524,6 +524,7 @@ func (a *app) siteBonusExchangeSubmit(args []string) error { intentValue := fs.String("intent-record", "", "sealed intent record ID") expectedReview := fs.String("expect-review-id", "", "exact review ID approved by the user") cookieStdin := fs.Bool("cookie-stdin", false, "read one Cookie header value from stdin") + apiKeyStdin := fs.Bool("api-key-stdin", false, "read a site-issued API key from stdin") bundleStdin := fs.Bool("credential-bundle-stdin", false, "read a ptctl.credentials/v1 bundle with site_cookie and site_password from stdin") acknowledge := fs.Bool("acknowledge-bonus-exchange", false, "acknowledge one bonus exchange form submission") timeout := fs.Duration("timeout", bonusExchangeDefaultTimeout, "fresh review and submission timeout") @@ -536,6 +537,9 @@ func (a *app) siteBonusExchangeSubmit(args []string) error { if *cookieStdin && *bundleStdin { return usageError("site bonus exchange submit accepts --cookie-stdin or --credential-bundle-stdin, not both") } + if *apiKeyStdin && (*cookieStdin || *bundleStdin) { + return usageError("site bonus exchange submit accepts one of --cookie-stdin, --api-key-stdin, or --credential-bundle-stdin") + } if !*acknowledge { return usageError("site bonus exchange submit requires --acknowledge-bonus-exchange") } @@ -557,15 +561,23 @@ func (a *app) siteBonusExchangeSubmit(args []string) error { return err } passwordWriter, needsPassword := writer.(site.PasswordConfirmedBonusExchangeWriter) - if needsPassword && *cookieStdin { + if needsPassword && (*cookieStdin || *apiKeyStdin) { return usageError("site %q confirms bonus exchange with the account password; submit requires --credential-bundle-stdin", descriptor.ID) } if !needsPassword && *bundleStdin { - return usageError("site %q bonus exchange takes only --cookie-stdin", descriptor.ID) + return usageError("site %q bonus exchange takes only %s", descriptor.ID, credentialStdinFlag(defaultSiteAuthMethod(descriptor))) + } + // Without a flag the saved credential is used, and a site that confirms + // with the account password asks for it, hidden, on this terminal. + source := siteCredentialSource{method: domain.AuthMethodCookieHeader, saved: !*bundleStdin} + if !*bundleStdin { + if source, err = siteCredentialSourceFor(descriptor, *cookieStdin, *apiKeyStdin); err != nil { + return err + } + } + if needsPassword && source.method != domain.AuthMethodCookieHeader { + return usageError("site %q bonus exchange is unavailable", descriptor.ID) } - // Without a flag the saved cookie is used, and a site that confirms with - // the account password asks for it, hidden, on this terminal. - source := siteCredentialSource{method: domain.AuthMethodCookieHeader, saved: !*cookieStdin && !*bundleStdin} var terminal promptTerminal if source.saved && needsPassword { var ok bool @@ -655,7 +667,11 @@ func (a *app) siteBonusExchangeSubmit(args []string) error { } siteSession, err = passwordWriter.OpenPasswordConfirmedBonusExchangeSession(ctx, credential, password) } else { - credential, readErr := a.readSiteCredential(source, readEffectfulSiteCredential) + readSecret := readEffectfulSiteCredential + if source.method == domain.AuthMethodAPIKeyHeader { + readSecret = readEffectfulAPIKeyCredential + } + credential, readErr := a.readSiteCredential(source, readSecret) if readErr != nil { _ = stateSession.Close() addBonusExchangeBlocker(&report, "credential.read_failed", "the site credential could not be read") @@ -783,7 +799,7 @@ func (a *app) bonusExchangeWriter(siteID, selector string) (domain.SiteDescripto return domain.SiteDescriptor{}, nil, site.BonusExchangeConfig{}, usageError("unknown site %q", siteID) } descriptor := adapter.Descriptor() - if !descriptor.Supports(domain.CapabilityBonusExchange) || !descriptor.SupportsAuth(domain.AuthMethodCookieHeader) { + if !descriptor.Supports(domain.CapabilityBonusExchange) { return descriptor, nil, site.BonusExchangeConfig{}, usageError("site %q does not support acknowledged bonus exchange", descriptor.ID) } writer, ok := adapter.(site.BonusExchangeWriter) @@ -1096,7 +1112,8 @@ func safeBonusExchangeOutcome(value string) string { func safeBonusExchangeSubmitStop(value string) string { switch value { case "context_before_submission", "submission_not_sent", "submission_transport_uncertain", "submission_response_unrecognized", "server_duplicate_lock", "server_permission_rejected", - "server_password_rejected", "server_password_required", "server_price_changed", "site.exchange_receipt_invalid": + "server_password_rejected", "server_password_required", "server_price_changed", "server_refused", "server_rate_limited", "server_authentication_rejected", + "site.exchange_receipt_invalid": return value case "": return "" @@ -1318,7 +1335,7 @@ func bonusRecordID(ref *metastore.RecordRef) string { func (a *app) siteBonusExchangeHelp() { fmt.Fprint(a.stdout, `Usage: ptctl site bonus exchange prepare --state-store DIR --expect-review-id ID [--output table|json] SITE OPTION - ptctl site bonus exchange submit --state-store DIR --intent-record RECORD_ID --expect-review-id ID [--cookie-stdin | --credential-bundle-stdin] --acknowledge-bonus-exchange [--output table|json] SITE OPTION + ptctl site bonus exchange submit --state-store DIR --intent-record RECORD_ID --expect-review-id ID [--cookie-stdin | --api-key-stdin | --credential-bundle-stdin] --acknowledge-bonus-exchange [--output table|json] SITE OPTION ptctl site bonus exchange status --state-store DIR --intent-record RECORD_ID [--output table|json] ptctl site bonus exchange list --state-store DIR [--max-operations N] [--output table|json] ptctl site bonus exchange prune --state-store DIR --intent-record RECORD_ID --operation-id ID --acknowledge-state-prune [--output table|json] @@ -1329,13 +1346,15 @@ the production adapter before reading stdin, performs one fresh bounded review, durably publishes a deterministic at-most-once attempt marker, and only then may submit the exact opaque form once. There are no redirects or retries. -Without a credential flag, submit uses the session cookie 'ptctl site login -SITE' saved. A site that confirms each exchange with the account password, such -as TJUPT, then asks for the password on this terminal with echo off. Scripts -pipe credentials instead: --cookie-stdin for a cookie alone, or, for a site -that needs the password, --credential-bundle-stdin with strict JSON containing -schema "ptctl.credentials/v1", site_cookie, and site_password. The password is -added to that single POST only; it is never stored or printed. +Without a credential flag, submit uses the session cookie or API key 'ptctl +site login SITE' saved. A site that confirms each exchange with the account +password, such as TJUPT, then asks for the password on this terminal with echo +off. Scripts pipe credentials instead: --cookie-stdin or --api-key-stdin for a +cookie or API key alone, or, for a site that needs the password, +--credential-bundle-stdin with strict JSON containing schema +"ptctl.credentials/v1", site_cookie, and site_password. The password is added +to that single POST only; it is never stored or printed. M-Team needs no +password: an API key alone exchanges goods that take no input, one unit each. After the POST, a bounded local finalization interval may persist the exact adapter observation even if the network context ended. If no durable outcome diff --git a/internal/cli/site_bonus_exchange_test.go b/internal/cli/site_bonus_exchange_test.go index 8532c6d..bc66316 100644 --- a/internal/cli/site_bonus_exchange_test.go +++ b/internal/cli/site_bonus_exchange_test.go @@ -35,12 +35,19 @@ type fakeBonusExchangeAdapter struct { reviews int submissions int credential string + credentialMethod domain.AuthMethod + // authMethod is the one method the fake site accepts; empty means cookies. + authMethod domain.AuthMethod } -func (*fakeBonusExchangeAdapter) Descriptor() domain.SiteDescriptor { +func (adapter *fakeBonusExchangeAdapter) Descriptor() domain.SiteDescriptor { + method := domain.AuthMethodCookieHeader + if adapter.authMethod != "" { + method = adapter.authMethod + } return domain.SiteDescriptor{ ID: "fakept", Name: "Fake PT", BaseURL: "https://fake.invalid/", Stability: "test", - AuthMethods: []domain.AuthMethod{domain.AuthMethodCookieHeader}, + AuthMethods: []domain.AuthMethod{method}, Capabilities: []domain.Capability{domain.CapabilityBonusReview, domain.CapabilityBonusExchange}, } } @@ -64,7 +71,7 @@ func (adapter *fakeBonusExchangeAdapter) BonusExchangeConfig() (site.BonusExchan func (adapter *fakeBonusExchangeAdapter) OpenBonusExchangeSession(ctx context.Context, credential site.Credential) (site.BonusExchangeSession, error) { adapter.opened++ - adapter.credential = credential.SecretValue() + adapter.credential, adapter.credentialMethod = credential.SecretValue(), credential.Method() if err := ctx.Err(); err != nil { return nil, err } @@ -896,7 +903,7 @@ func TestSiteBonusExchangeHelpAndDispatch(t *testing.T) { var out, errOut bytes.Buffer if code := Run([]string{"site", "bonus", "exchange", "help"}, strings.NewReader(""), &out, &errOut); code != 0 || !strings.Contains(out.String(), "deterministic at-most-once attempt marker") || !strings.Contains(out.String(), "never chooses a latest operation") || !strings.Contains(out.String(), "acknowledge-state-prune") || !strings.Contains(out.String(), "acknowledge-history-forget") || !strings.Contains(out.String(), "submission-unknown operations are never pruned") || - !strings.Contains(out.String(), "[--cookie-stdin | --credential-bundle-stdin]") || !strings.Contains(out.String(), "site_password") { + !strings.Contains(out.String(), "[--cookie-stdin | --api-key-stdin | --credential-bundle-stdin]") || !strings.Contains(out.String(), "site_password") { t.Fatalf("code=%d out=%q err=%q", code, out.String(), errOut.String()) } out.Reset() diff --git a/internal/cli/site_bonus_test.go b/internal/cli/site_bonus_test.go index 1e4ade4..6a0df0d 100644 --- a/internal/cli/site_bonus_test.go +++ b/internal/cli/site_bonus_test.go @@ -24,12 +24,19 @@ type fakeBonusReviewAdapter struct { closeErr error opened int credential string + // authMethod is the one method the fake site accepts; empty means cookies. + authMethod domain.AuthMethod + credentialMethod domain.AuthMethod } -func (*fakeBonusReviewAdapter) Descriptor() domain.SiteDescriptor { +func (adapter *fakeBonusReviewAdapter) Descriptor() domain.SiteDescriptor { + method := domain.AuthMethodCookieHeader + if adapter.authMethod != "" { + method = adapter.authMethod + } return domain.SiteDescriptor{ ID: "fakept", Name: "Fake PT", BaseURL: "https://fake.invalid/", Stability: "test", - AuthMethods: []domain.AuthMethod{domain.AuthMethodCookieHeader}, Capabilities: []domain.Capability{domain.CapabilityBonusReview}, + AuthMethods: []domain.AuthMethod{method}, Capabilities: []domain.Capability{domain.CapabilityBonusReview}, } } @@ -55,7 +62,7 @@ func (adapter *fakeBonusReviewAdapter) OpenBonusReviewSession(ctx context.Contex if err := ctx.Err(); err != nil { return nil, err } - adapter.credential = credential.SecretValue() + adapter.credential, adapter.credentialMethod = credential.SecretValue(), credential.Method() if adapter.openErr != nil { return nil, adapter.openErr } diff --git a/internal/cli/site_contract_test.go b/internal/cli/site_contract_test.go index 2831328..ea0b9a9 100644 --- a/internal/cli/site_contract_test.go +++ b/internal/cli/site_contract_test.go @@ -48,8 +48,11 @@ const mteamDescriptorJSON = ` { "auth.check", "account.read", "torrent.search", + "bonus.catalog.read", "torrent.detail", - "torrent.metafile.read_effectful" + "torrent.metafile.read_effectful", + "bonus.offer.review", + "bonus.exchange.submit_effectful" ] }` @@ -68,7 +71,7 @@ func TestBuiltinSiteDiscoveryOutputIsStable(t *testing.T) { {args: []string{"site", "capabilities", "--output", "json", "mteam"}, want: descriptorListJSON(mteamDescriptorJSON)}, {args: []string{"site", "list"}, want: "" + "ID NAME STABILITY BASE URL CAPABILITIES\n" + - "mteam M-Team / 馒头PT experimental https://api2.m-team.cc/ 5\n" + + "mteam M-Team / 馒头PT experimental https://api2.m-team.cc/ 8\n" + "tjupt TJUPT / 北洋园PT experimental https://www.tjupt.org/ 9\n"}, {args: []string{"site", "capabilities", "tjupt"}, want: "" + "SITE KIND VALUE\n" + @@ -88,8 +91,11 @@ func TestBuiltinSiteDiscoveryOutputIsStable(t *testing.T) { "mteam capability auth.check\n" + "mteam capability account.read\n" + "mteam capability torrent.search\n" + + "mteam capability bonus.catalog.read\n" + "mteam capability torrent.detail\n" + - "mteam capability torrent.metafile.read_effectful\n"}, + "mteam capability torrent.metafile.read_effectful\n" + + "mteam capability bonus.offer.review\n" + + "mteam capability bonus.exchange.submit_effectful\n"}, } for _, test := range tests { t.Run(strings.Join(test.args, " "), func(t *testing.T) { diff --git a/internal/site/httpguard/client.go b/internal/site/httpguard/client.go index e10d81d..6da0702 100644 --- a/internal/site/httpguard/client.go +++ b/internal/site/httpguard/client.go @@ -412,7 +412,7 @@ func (c *Client) postFormOnce(ctx context.Context, relativePath string, query ur req.Header.Set("Accept", accept) req.Header.Set("Accept-Encoding", "identity") req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.Header.Set("User-Agent", "ptctl/0.1 (+https://github.com/tonycoder-hub/ptctl; explicit-effect-client)") + req.Header.Set("User-Agent", explicitEffectUserAgent) c.applyCredential(req) req.Close = true return c.roundTripCapturing(ctx, req, result, maxBody, maxHeaderBytes, classify, capture) @@ -422,6 +422,17 @@ func (c *Client) postFormOnce(ctx context.Context, relativePath string, query ur // expose reads only through POST. The caller supplies the encoded body; it is // sent once, never replayed, and never included in a result or diagnostic. func (c *Client) PostReadOnce(ctx context.Context, relativePath, contentType string, body []byte, accept string, maxRequestBytes, maxBody, maxHeaderBytes int64) (StrictResponse, error) { + return c.postBodyOnce(ctx, relativePath, contentType, body, accept, maxRequestBytes, maxBody, maxHeaderBytes, readOnlyUserAgent) +} + +// PostEffectOnce is PostReadOnce for one acknowledged API write, such as a +// bonus exchange. It identifies itself as an explicit-effect client, and like +// every request here it is never retried, replayed, or redirected. +func (c *Client) PostEffectOnce(ctx context.Context, relativePath, contentType string, body []byte, accept string, maxRequestBytes, maxBody, maxHeaderBytes int64) (StrictResponse, error) { + return c.postBodyOnce(ctx, relativePath, contentType, body, accept, maxRequestBytes, maxBody, maxHeaderBytes, explicitEffectUserAgent) +} + +func (c *Client) postBodyOnce(ctx context.Context, relativePath, contentType string, body []byte, accept string, maxRequestBytes, maxBody, maxHeaderBytes int64, userAgent string) (StrictResponse, error) { var result StrictResponse if maxBody <= 0 || maxBody > 32<<20 || maxHeaderBytes <= 0 || maxHeaderBytes > hardMaxResponseHeaders { return result, fmt.Errorf("site response budget is invalid") @@ -458,7 +469,7 @@ func (c *Client) PostReadOnce(ctx context.Context, relativePath, contentType str req.Header.Set("Accept", accept) req.Header.Set("Accept-Encoding", "identity") req.Header.Set("Content-Type", contentType) - req.Header.Set("User-Agent", readOnlyUserAgent) + req.Header.Set("User-Agent", userAgent) c.applyCredential(req) req.Close = true return c.roundTrip(ctx, req, result, maxBody, maxHeaderBytes, nil) @@ -582,6 +593,8 @@ func linkRedirectTarget(from *url.URL, raw string) (*url.URL, bool) { const readOnlyUserAgent = "ptctl/0.1 (+https://github.com/tonycoder-hub/ptctl; conservative-read-only-client)" +const explicitEffectUserAgent = "ptctl/0.1 (+https://github.com/tonycoder-hub/ptctl; explicit-effect-client)" + func (c *Client) applyCredential(req *http.Request) { if c.credentialValue != "" { req.Header.Set(c.credentialHeader, c.credentialValue) diff --git a/internal/site/httpguard/post_read_test.go b/internal/site/httpguard/post_read_test.go index 9bfac5b..50680aa 100644 --- a/internal/site/httpguard/post_read_test.go +++ b/internal/site/httpguard/post_read_test.go @@ -85,6 +85,42 @@ func TestPostReadOnceSendsOneNonReplayableRead(t *testing.T) { } } +func TestPostEffectOnceSendsOneWriteAsAnEffectClient(t *testing.T) { + const key = "KEY-CANARY" + const payload = "--b\r\nContent-Disposition: form-data; name=\"goodsId\"\r\n\r\n1\r\n--b--\r\n" + calls := 0 + client := headerCredentialTestClient(t, roundTripFunc(func(request *http.Request) (*http.Response, error) { + calls++ + body, err := io.ReadAll(request.Body) + if err != nil { + t.Fatal(err) + } + if request.Method != http.MethodPost || request.URL.Path != "/api/mall/exchange" || request.Header.Get("X-Api-Key") != key || + request.Header.Get("Content-Type") != "multipart/form-data; boundary=b" || + request.Header.Get("User-Agent") != explicitEffectUserAgent || !request.Close || request.GetBody != nil || string(body) != payload { + t.Fatalf("unexpected effect POST: request=%#v body=%q", request, body) + } + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"code":"0"}`)), + ContentLength: 12, + }, nil + }), "X-Api-Key", key) + response, err := client.PostEffectOnce(context.Background(), "api/mall/exchange", "multipart/form-data; boundary=b", []byte(payload), "application/json", 1024, 1024, 1024) + if err != nil { + t.Fatal(err) + } + if calls != 1 || client.RequestsMade() != 1 || response.StatusCode != http.StatusOK || string(response.Body) != `{"code":"0"}` || + response.RequestBytes != int64(len(payload)) || !response.ResponseBytesKnown { + t.Fatalf("calls=%d requests=%d response=%#v", calls, client.RequestsMade(), response) + } + // Invalid input is refused before any request, as for PostReadOnce. + if _, err := client.PostEffectOnce(context.Background(), "api/mall/exchange", "", []byte(payload), "application/json", 1024, 1024, 1024); err == nil || client.RequestsMade() != 1 { + t.Fatalf("err=%v requests=%d", err, client.RequestsMade()) + } +} + func TestPostReadOnceRejectsInvalidInputBeforeAnyRequest(t *testing.T) { tests := []struct { name string diff --git a/internal/site/mteam/adapter.go b/internal/site/mteam/adapter.go index c872e50..80aee86 100644 --- a/internal/site/mteam/adapter.go +++ b/internal/site/mteam/adapter.go @@ -87,8 +87,11 @@ func (a *Adapter) Descriptor() domain.SiteDescriptor { domain.CapabilityAuthCheck, domain.CapabilityAccountRead, domain.CapabilitySearch, + domain.CapabilityBonusRead, domain.CapabilityDetail, domain.CapabilityMetafile, + domain.CapabilityBonusReview, + domain.CapabilityBonusExchange, }, } } @@ -130,6 +133,17 @@ func (a *Adapter) call(ctx context.Context, credential site.Credential, path, co if err := ctx.Err(); err != nil { return nil, err } + client, err := a.openClient(credential) + if err != nil { + return nil, err + } + defer client.Close() + return post(ctx, client, path, contentType, body) +} + +// openClient binds one API client to the key. The client spaces its own +// requests, so a command that needs several reads makes them all on one. +func (a *Adapter) openClient(credential site.Credential) (guardedClient, error) { if credential.Method() != domain.AuthMethodAPIKeyHeader { return nil, fmt.Errorf("M-Team requires api_key_header authentication") } @@ -140,7 +154,10 @@ func (a *Adapter) call(ctx context.Context, credential site.Credential, path, co if err != nil || client == nil { return nil, fmt.Errorf("open M-Team API client failed") } - defer client.Close() + return client, nil +} + +func post(ctx context.Context, client guardedClient, path, contentType string, body []byte) (json.RawMessage, error) { response, err := client.PostReadOnce(ctx, path, contentType, body, apiAccept, maxRequestBytes, maxResponseBytes, maxResponseHeaderBytes) if err != nil { return nil, requestError(err) diff --git a/internal/site/mteam/adapter_test.go b/internal/site/mteam/adapter_test.go index 6015f64..07a4ad1 100644 --- a/internal/site/mteam/adapter_test.go +++ b/internal/site/mteam/adapter_test.go @@ -82,8 +82,11 @@ func TestIdentityIsPinned(t *testing.T) { } want := domain.SiteDescriptor{ ID: "mteam", Name: "M-Team / 馒头PT", BaseURL: "https://api2.m-team.cc/", Stability: "experimental", - AuthMethods: []domain.AuthMethod{domain.AuthMethodAPIKeyHeader}, - Capabilities: []domain.Capability{domain.CapabilityAuthCheck, domain.CapabilityAccountRead, domain.CapabilitySearch, domain.CapabilityDetail, domain.CapabilityMetafile}, + AuthMethods: []domain.AuthMethod{domain.AuthMethodAPIKeyHeader}, + Capabilities: []domain.Capability{ + domain.CapabilityAuthCheck, domain.CapabilityAccountRead, domain.CapabilitySearch, domain.CapabilityBonusRead, + domain.CapabilityDetail, domain.CapabilityMetafile, domain.CapabilityBonusReview, domain.CapabilityBonusExchange, + }, } if got := New().Descriptor(); !reflect.DeepEqual(got, want) { t.Fatalf("descriptor=%#v", got) diff --git a/internal/site/mteam/bonus.go b/internal/site/mteam/bonus.go new file mode 100644 index 0000000..fa76060 --- /dev/null +++ b/internal/site/mteam/bonus.go @@ -0,0 +1,909 @@ +package mteam + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "sync" + "time" + "unicode/utf8" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" + "github.com/tonycoder-hub/ptctl/internal/site/httpguard" +) + +const ( + BonusReviewOrigin = Origin + // BonusReviewRouteID names the one POST to api/mall/list. The mall list is + // the site's own catalog of goods; reviewing one item never submits it. + BonusReviewRouteID = "mteam.mall_list_review.v1" + // BonusExchangeRouteID names the one POST to api/mall/exchange. + BonusExchangeRouteID = "mteam.mall_exchange_post.v1" + + bonusConfirmedCode = "mteam.mall_exchange.confirm" + site.BonusExchangeMessageConfirmationSuffix + + mallListPath = "api/mall/list" + mallExchangePath = "api/mall/exchange" + + // exchangeQuantity is the only amount ptctl ever asks for: one unit of + // the reviewed goods, such as 1 GB of upload or one invite. + exchangeQuantity = "1" + maxGoodsIDDigits = 10 + maxGoodsName = 256 + maxGoodsType = 64 +) + +// mallInputModes maps the goods types ptctl has seen to the input the site's +// exchange asks for. UPLOAD and INVITE take only the goods ID and an amount, +// which ptctl fixes at one. Titles and the global-free pools need a value the +// user chooses, so they stay review-only. Any other type is unsupported. +var mallInputModes = map[string]string{ + "UPLOAD": site.BonusReviewInputNone, + "INVITE": site.BonusReviewInputNone, + "TITLE": site.BonusReviewInputRequired, + "GLOBAL_FREE_SINGLE": site.BonusReviewInputRequired, + "GLOBAL_FREE_POOL": site.BonusReviewInputRequired, +} + +var bonusEvidenceBasis = []string{ + site.BonusReviewBasisAuthenticated, + site.BonusReviewBasisExactSelector, + site.BonusReviewBasisExactForm, + site.BonusReviewBasisOneRequest, + site.BonusReviewBasisSiteClaimOnly, + site.BonusReviewBasisNoSubmission, +} + +var ( + _ site.BonusCatalogReader = (*Adapter)(nil) + _ site.BonusReviewReader = (*Adapter)(nil) + _ site.BonusReviewSession = (*bonusReviewSession)(nil) + _ site.BonusExchangeWriter = (*Adapter)(nil) + _ site.BonusExchangeSession = (*bonusExchangeSession)(nil) +) + +// guardedEffectClient is a guardedClient that can also send the one +// state-changing exchange POST. Only the exchange session asks for it. +type guardedEffectClient interface { + guardedClient + PostEffectOnce(context.Context, string, string, []byte, string, int64, int64, int64) (httpguard.StrictResponse, error) +} + +// BonusCatalog reads the balance from the profile and then the mall list, on +// one client so the two reads keep the site's request spacing. +func (a *Adapter) BonusCatalog(ctx context.Context, credential site.Credential) (domain.BonusCatalog, error) { + if err := ctx.Err(); err != nil { + return domain.BonusCatalog{}, err + } + client, err := a.openClient(credential) + if err != nil { + return domain.BonusCatalog{}, err + } + defer client.Close() + data, err := post(ctx, client, profilePath, emptyFormMediaType, []byte(emptyFormBody)) + if err != nil { + return domain.BonusCatalog{}, err + } + profile, err := parseProfile(data) + if err != nil { + return domain.BonusCatalog{}, err + } + data, err = post(ctx, client, mallListPath, emptyFormMediaType, []byte(emptyFormBody)) + if err != nil { + return domain.BonusCatalog{}, err + } + offers, _, err := parseMall(data, site.DefaultBonusReviewLimits()) + if err != nil || len(offers) == 0 { + return domain.BonusCatalog{}, fmt.Errorf("M-Team mall response was not recognized; refusing an empty catalog") + } + rows := make([]domain.BonusCatalogRow, 0, len(offers)) + for _, offer := range offers { + rows = append(rows, domain.BonusCatalogRow{Selector: offer.id, Columns: append(offer.columns(), offer.catalogStatus())}) + } + return domain.BonusCatalog{SiteID: SiteID, Balance: profile.Bonus, Rows: rows, ObservedAt: time.Now().UTC()}, nil +} + +func (a *Adapter) ValidateBonusReviewSelector(selector string) error { + return validateGoodsSelector(selector) +} + +func (a *Adapter) BonusReviewConfig() (site.BonusReviewConfig, error) { + config, err := site.NewBonusReviewConfig(BonusReviewOrigin, BonusReviewRouteID) + if err != nil { + return site.BonusReviewConfig{}, fmt.Errorf("M-Team bonus review configuration is invalid") + } + return config, nil +} + +func (a *Adapter) OpenBonusReviewSession(ctx context.Context, credential site.Credential) (site.BonusReviewSession, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + config, err := a.BonusReviewConfig() + if err != nil { + return nil, err + } + if credential.Method() != domain.AuthMethodAPIKeyHeader { + return nil, fmt.Errorf("M-Team bonus review requires api_key_header authentication") + } + if !validAPIKey(credential.SecretValue()) { + return nil, fmt.Errorf("M-Team API key is malformed: %w", site.ErrCredentialMalformed) + } + client, err := a.clientFactory()(DefaultBaseURL, credential.SecretValue(), minRequestInterval) + if err != nil || client == nil { + return nil, fmt.Errorf("open M-Team bonus review session failed") + } + return &bonusReviewSession{client: client, config: config}, nil +} + +type bonusReviewSession struct { + client guardedClient + config site.BonusReviewConfig + mu sync.Mutex + used bool + closed bool +} + +func (session *bonusReviewSession) ReadBonusReview(ctx context.Context, selector string, limits site.BonusReviewLimits) (*site.ObservedBonusReview, site.BonusReviewReceipt, error) { + now := time.Now().UTC() + receipt := site.BonusReviewReceipt{ + Effect: site.BonusReviewReadEffect, + SiteID: SiteID, + Selector: selector, + Origin: session.config.Origin, + RouteID: session.config.RouteID, + ObservedAtStart: now, + ObservedAtEnd: now, + Limits: limits, + } + if err := limits.Validate(); err != nil { + receipt.StopReason = "invalid_limits" + return nil, receipt, fmt.Errorf("M-Team bonus review limits are invalid") + } + if err := validateGoodsSelector(selector); err != nil { + receipt.StopReason = "invalid_selector" + return nil, receipt, err + } + if err := ctx.Err(); err != nil { + receipt.StopReason = "context_done" + return nil, receipt, err + } + + session.mu.Lock() + if session.closed { + session.mu.Unlock() + receipt.StopReason = "session_closed" + return nil, receipt, fmt.Errorf("M-Team bonus review session is closed") + } + if session.used { + session.mu.Unlock() + receipt.StopReason = "request_budget_exhausted" + receipt.Used.RequestsAttempted = session.RequestsMade() + return nil, receipt, fmt.Errorf("M-Team bonus review request budget is exhausted") + } + session.used = true + client := session.client + session.mu.Unlock() + + response, requestErr := client.PostReadOnce(ctx, mallListPath, emptyFormMediaType, []byte(emptyFormBody), apiAccept, maxRequestBytes, limits.MaxResponseBytes, limits.MaxResponseHeaderBytes) + receipt.Used.RequestsAttempted = client.RequestsMade() + receipt.Used.ResponseBytesRead = response.ResponseBytesRead + receipt.Used.ResponseBytesKnown = response.ResponseBytesKnown + if !response.ObservedAtStart.IsZero() { + receipt.ObservedAtStart = response.ObservedAtStart + } + if !response.ObservedAtEnd.IsZero() { + receipt.ObservedAtEnd = response.ObservedAtEnd + } else { + receipt.ObservedAtEnd = time.Now().UTC() + } + if requestErr != nil { + if errors.Is(requestErr, context.Canceled) || errors.Is(ctx.Err(), context.Canceled) { + receipt.StopReason = "context_done" + return nil, receipt, fmt.Errorf("M-Team bonus review request stopped: %w", context.Canceled) + } + if errors.Is(requestErr, context.DeadlineExceeded) || errors.Is(ctx.Err(), context.DeadlineExceeded) { + receipt.StopReason = "context_done" + return nil, receipt, fmt.Errorf("M-Team bonus review request stopped: %w", context.DeadlineExceeded) + } + if receipt.Used.RequestsAttempted != 1 { + receipt.StopReason = "request_accounting_invalid" + return nil, receipt, fmt.Errorf("M-Team bonus review request accounting is invalid") + } + receipt.StopReason = "site_request_failed" + return nil, receipt, fmt.Errorf("M-Team bonus review request failed") + } + if receipt.Used.RequestsAttempted != 1 { + receipt.StopReason = "request_accounting_invalid" + return nil, receipt, fmt.Errorf("M-Team bonus review request accounting is invalid") + } + if !response.ResponseBytesKnown || response.ResponseBytesRead != int64(len(response.Body)) || + response.ObservedAtStart.IsZero() || response.ObservedAtEnd.IsZero() || response.ObservedAtEnd.Before(response.ObservedAtStart) || + int64(len(response.Body)) > limits.MaxResponseBytes { + receipt.StopReason = "response_accounting_invalid" + return nil, receipt, fmt.Errorf("M-Team bonus review response accounting is invalid") + } + if stopReason, err := classifyMallResponse(response); err != nil { + receipt.StopReason = stopReason + return nil, receipt, err + } + tokens, err := countJSONTokens(response.Body, limits.MaxTokens) + receipt.Used.TokensExamined = tokens + if err != nil { + receipt.StopReason = mallStopReason(err) + return nil, receipt, fmt.Errorf("M-Team mall response was not recognized") + } + data, stopReason, err := decodeMallEnvelope(response.Body) + if err != nil { + receipt.StopReason = stopReason + return nil, receipt, err + } + offers, usage, err := parseMall(data, limits) + receipt.Used.FormsExamined = usage.forms + receipt.Used.FieldsExamined = usage.fields + receipt.Used.VisibleTextBytes = usage.visibleTextBytes + if err != nil { + receipt.StopReason = mallStopReason(err) + return nil, receipt, fmt.Errorf("M-Team mall response was not recognized") + } + offer, ok := findOffer(offers, selector) + if !ok { + receipt.StopReason = "selector_not_found" + return nil, receipt, fmt.Errorf("M-Team mall has no goods %s", selector) + } + review, err := offer.review(selector) + if err != nil { + receipt.StopReason = "unrecognized_offer" + return nil, receipt, fmt.Errorf("M-Team mall goods was not recognized") + } + receipt.Complete = true + observed, err := site.NewObservedBonusReview(review, receipt) + if err != nil { + receipt.Complete = false + receipt.StopReason = "response_accounting_invalid" + return nil, receipt, fmt.Errorf("M-Team bonus review observation is invalid") + } + return observed, receipt, nil +} + +func (session *bonusReviewSession) RequestsMade() int { + if session == nil || session.client == nil { + return 0 + } + return session.client.RequestsMade() +} + +func (session *bonusReviewSession) Close() error { + if session == nil { + return nil + } + session.mu.Lock() + if session.closed { + session.mu.Unlock() + return nil + } + session.closed = true + client := session.client + session.mu.Unlock() + if client == nil { + return nil + } + if err := client.Close(); err != nil { + return fmt.Errorf("close M-Team bonus review session failed") + } + return nil +} + +func (a *Adapter) ValidateBonusExchangeSelector(selector string) error { + return validateGoodsSelector(selector) +} + +func (a *Adapter) BonusExchangeConfig() (site.BonusExchangeConfig, error) { + config, err := site.NewBonusExchangeConfig(BonusReviewOrigin, BonusReviewRouteID, BonusExchangeRouteID) + if err != nil { + return site.BonusExchangeConfig{}, fmt.Errorf("M-Team bonus exchange configuration is invalid") + } + return config, nil +} + +// OpenBonusExchangeSession binds one client for the fresh mall review and the +// one exchange POST. M-Team asks for no password: the API key alone +// authorizes the exchange. +func (a *Adapter) OpenBonusExchangeSession(ctx context.Context, credential site.Credential) (site.BonusExchangeSession, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + config, err := a.BonusExchangeConfig() + if err != nil { + return nil, err + } + if credential.Method() != domain.AuthMethodAPIKeyHeader { + return nil, fmt.Errorf("M-Team bonus exchange requires api_key_header authentication") + } + if !validAPIKey(credential.SecretValue()) { + return nil, fmt.Errorf("M-Team API key is malformed: %w", site.ErrCredentialMalformed) + } + readClient, err := a.clientFactory()(DefaultBaseURL, credential.SecretValue(), minRequestInterval) + if err != nil || readClient == nil { + return nil, fmt.Errorf("open M-Team bonus exchange session failed") + } + client, ok := readClient.(guardedEffectClient) + if !ok { + _ = readClient.Close() + return nil, fmt.Errorf("open M-Team bonus exchange session failed") + } + reviewConfig, err := site.NewBonusReviewConfig(config.Origin, config.ReviewRouteID) + if err != nil { + _ = client.Close() + return nil, fmt.Errorf("open M-Team bonus exchange session failed") + } + reviewer := &bonusReviewSession{client: client, config: reviewConfig} + return &bonusExchangeSession{client: client, config: config, reviewer: reviewer}, nil +} + +type bonusExchangeSession struct { + client guardedEffectClient + config site.BonusExchangeConfig + reviewer *bonusReviewSession + mu sync.Mutex + closed bool + reviewed bool + submitted bool + observed *site.ObservedBonusReview + receipt site.BonusReviewReceipt + body []byte + exchangeLimits site.BonusExchangeLimits +} + +func (session *bonusExchangeSession) ReadFreshBonusReview(ctx context.Context, selector string, limits site.BonusReviewLimits, exchangeLimits site.BonusExchangeLimits) (*site.ObservedBonusReview, site.BonusReviewReceipt, error) { + if session == nil { + return nil, site.BonusReviewReceipt{}, fmt.Errorf("M-Team bonus exchange session is unavailable") + } + if exchangeLimits.Validate() != nil { + return nil, site.BonusReviewReceipt{}, fmt.Errorf("M-Team bonus exchange limits are invalid") + } + session.mu.Lock() + if session.closed || session.reviewed { + session.mu.Unlock() + return nil, site.BonusReviewReceipt{}, fmt.Errorf("M-Team bonus exchange review is unavailable") + } + session.reviewed = true + reviewer := session.reviewer + session.mu.Unlock() + if reviewer == nil { + return nil, site.BonusReviewReceipt{}, fmt.Errorf("M-Team bonus exchange review is unavailable") + } + observed, receipt, err := reviewer.ReadBonusReview(ctx, selector, limits) + if err != nil { + return nil, receipt, err + } + // Only goods that need nothing beyond the ID and the fixed amount have a + // form ptctl can send. + review := observed.PublicCopy() + if review.Availability != site.BonusReviewAvailabilityAvailable || review.InputMode != site.BonusReviewInputNone { + receipt.Complete = false + receipt.StopReason = "submission_form_unavailable" + return nil, receipt, fmt.Errorf("M-Team bonus exchange form is unavailable") + } + body := exchangeBody(selector) + if exchangeLimits.MaxFormFields < 2 || int64(len(body)) > exchangeLimits.MaxFormBytes { + receipt.Complete = false + receipt.StopReason = "submission_form_budget_exceeded" + return nil, receipt, fmt.Errorf("M-Team bonus exchange form exceeds the configured budget") + } + session.mu.Lock() + session.observed = observed + session.receipt = receipt + session.body = body + session.exchangeLimits = exchangeLimits + session.mu.Unlock() + return observed, receipt, nil +} + +func (session *bonusExchangeSession) SubmitFreshBonusExchange(ctx context.Context, observed *site.ObservedBonusReview, expectedReviewID string, limits site.BonusExchangeLimits) (*site.ObservedBonusExchange, site.BonusExchangeReceipt, error) { + now := time.Now().UTC() + receipt := site.BonusExchangeReceipt{ + Effect: site.BonusExchangeSubmitEffect, ExpectedReviewID: expectedReviewID, + FreshReviewID: expectedReviewID, ObservedAtStart: now, ObservedAtEnd: now, + Limits: limits, Outcome: site.BonusExchangeOutcomeNotSubmitted, + } + if session == nil { + receipt.StopReason = "session_unavailable" + return nil, completeBonusExchangeReceipt(receipt), fmt.Errorf("M-Team bonus exchange session is unavailable") + } + receipt.SiteID = SiteID + receipt.Origin = session.config.Origin + receipt.ReviewRouteID = session.config.ReviewRouteID + receipt.ActionRouteID = session.config.ActionRouteID + if limits.Validate() != nil || site.ValidateBonusReviewID(expectedReviewID) != nil { + receipt.StopReason = "invalid_precondition" + return nil, completeBonusExchangeReceipt(receipt), fmt.Errorf("M-Team bonus exchange precondition is invalid") + } + + session.mu.Lock() + if session.closed || session.submitted || !session.reviewed || session.observed == nil || session.body == nil || + observed != session.observed || limits != session.exchangeLimits { + session.mu.Unlock() + receipt.StopReason = "fresh_review_authority_unavailable" + return nil, completeBonusExchangeReceipt(receipt), fmt.Errorf("M-Team bonus exchange fresh review authority is unavailable") + } + freshReceipt := session.receipt + body := session.body + session.submitted = true + client := session.client + session.mu.Unlock() + + review := observed.PublicCopy() + receipt.Selector = review.Selector + receipt.FreshReviewID = review.ReviewID + receipt.Used.ReviewRequestsAttempted = freshReceipt.Used.RequestsAttempted + receipt.Used.TotalRequestsAttempted = boundedBonusRequestCount(client.RequestsMade()) + if !observed.MatchesReceipt(freshReceipt) || !observed.Matches(SiteID, review.Selector, session.config.Origin, session.config.ReviewRouteID) || + review.ReviewID != expectedReviewID || review.Availability != site.BonusReviewAvailabilityAvailable || review.InputMode != site.BonusReviewInputNone || + review.ActionMethod != "post" || review.ActionRouteID != session.config.ActionRouteID { + receipt.StopReason = "fresh_review_mismatch" + return nil, completeBonusExchangeReceipt(receipt), fmt.Errorf("M-Team bonus exchange fresh review did not match the approved intent") + } + if err := ctx.Err(); err != nil { + receipt.StopReason = "context_before_submission" + completed := completeBonusExchangeReceipt(receipt) + authority, authorityErr := site.NewObservedBonusExchange(completed) + if authorityErr != nil { + return nil, completed, fmt.Errorf("M-Team bonus exchange receipt is invalid") + } + return authority, completed, err + } + + response, submitErr := client.PostEffectOnce(ctx, mallExchangePath, emptyFormMediaType, body, apiAccept, limits.MaxFormBytes, limits.MaxResponseBytes, limits.MaxResponseHeaderBytes) + receipt.ObservedAtStart = nonzeroBonusTime(response.ObservedAtStart, receipt.ObservedAtStart) + receipt.ObservedAtEnd = nonzeroBonusTime(response.ObservedAtEnd, time.Now().UTC()) + receipt.Used.TotalRequestsAttempted = boundedBonusRequestCount(client.RequestsMade()) + receipt.Used.SubmissionRequestsAttempted = receipt.Used.TotalRequestsAttempted - receipt.Used.ReviewRequestsAttempted + if receipt.Used.SubmissionRequestsAttempted < 0 { + receipt.Used.SubmissionRequestsAttempted = 0 + } + receipt.RequestAttempted = receipt.Used.SubmissionRequestsAttempted == 1 + if receipt.RequestAttempted { + receipt.Used.FormFieldsSubmitted = 2 + receipt.Used.FormBytesSubmitted = int64(len(body)) + receipt.Used.ResponseBytesRead = response.ResponseBytesRead + receipt.Used.ResponseBytesKnown = response.ResponseBytesKnown + receipt.ResponseComplete = response.ResponseBytesKnown + } + if submitErr != nil { + if !receipt.RequestAttempted { + receipt.Outcome = site.BonusExchangeOutcomeNotSubmitted + receipt.StopReason = "submission_not_sent" + } else { + receipt.Outcome = site.BonusExchangeOutcomeUnknown + receipt.StopReason = "submission_transport_uncertain" + } + receipt = completeBonusExchangeReceipt(receipt) + authority, authorityErr := site.NewObservedBonusExchange(receipt) + if authorityErr != nil { + return nil, receipt, fmt.Errorf("M-Team bonus exchange receipt is invalid") + } + if errors.Is(submitErr, context.Canceled) || errors.Is(ctx.Err(), context.Canceled) { + return authority, receipt, fmt.Errorf("M-Team bonus exchange stopped: %w", context.Canceled) + } + if errors.Is(submitErr, context.DeadlineExceeded) || errors.Is(ctx.Err(), context.DeadlineExceeded) { + return authority, receipt, fmt.Errorf("M-Team bonus exchange stopped: %w", context.DeadlineExceeded) + } + return authority, receipt, fmt.Errorf("M-Team bonus exchange response is uncertain") + } + + receipt.Outcome, receipt.StopReason = classifyExchangeResponse(response) + if receipt.Outcome == site.BonusExchangeOutcomeConfirmed { + receipt.ConfirmationCode = bonusConfirmedCode + } + receipt = completeBonusExchangeReceipt(receipt) + authority, authorityErr := site.NewObservedBonusExchange(receipt) + if authorityErr != nil { + return nil, receipt, fmt.Errorf("M-Team bonus exchange receipt is invalid") + } + if receipt.Outcome != site.BonusExchangeOutcomeConfirmed { + return authority, receipt, fmt.Errorf("M-Team bonus exchange was not confirmed") + } + return authority, receipt, nil +} + +func (session *bonusExchangeSession) RequestsMade() int { + if session == nil || session.client == nil { + return 0 + } + return session.client.RequestsMade() +} + +func (session *bonusExchangeSession) Close() error { + if session == nil { + return nil + } + session.mu.Lock() + if session.closed { + session.mu.Unlock() + return nil + } + session.closed = true + client := session.client + session.mu.Unlock() + if client != nil { + if err := client.Close(); err != nil { + return fmt.Errorf("close M-Team bonus exchange session failed") + } + } + return nil +} + +// classifyExchangeResponse reads only the envelope code of a complete JSON +// answer. Code "0" is the API's success; any other code means the site +// refused the exchange before spending bonus. Anything that is not a complete +// envelope stays unknown, because the exchange may have happened. +func classifyExchangeResponse(response httpguard.StrictResponse) (string, string) { + complete := response.ResponseBytesKnown && response.ResponseBytesRead == int64(len(response.Body)) + switch { + case !complete: + return site.BonusExchangeOutcomeUnknown, "submission_response_unrecognized" + case response.StatusCode == http.StatusUnauthorized: + return site.BonusExchangeOutcomeRejected, "server_authentication_rejected" + case response.StatusCode == http.StatusTooManyRequests: + return site.BonusExchangeOutcomeRejected, "server_rate_limited" + case response.StatusCode != http.StatusOK || !utf8.Valid(response.Body): + return site.BonusExchangeOutcomeUnknown, "submission_response_unrecognized" + } + switch response.MediaType { + case "application/json", "text/plain", "": + default: + return site.BonusExchangeOutcomeUnknown, "submission_response_unrecognized" + } + var envelope struct { + Code flexText `json:"code"` + } + if !isJSONObject(response.Body) || json.Unmarshal(response.Body, &envelope) != nil || !envelope.Code.set { + return site.BonusExchangeOutcomeUnknown, "submission_response_unrecognized" + } + switch envelope.Code.value { + case "0": + return site.BonusExchangeOutcomeConfirmed, "" + case "401": + return site.BonusExchangeOutcomeRejected, "server_authentication_rejected" + case "4": + return site.BonusExchangeOutcomeRejected, "server_rate_limited" + default: + return site.BonusExchangeOutcomeRejected, "server_refused" + } +} + +// classifyMallResponse maps the transport side of one mall answer to a public +// stop reason before any JSON is read. +func classifyMallResponse(response httpguard.StrictResponse) (string, error) { + switch { + case response.StatusCode == http.StatusUnauthorized || response.StatusCode == http.StatusForbidden: + return "authentication_required", fmt.Errorf("M-Team API rejected the request: %w", site.ErrCredentialRejected) + case response.StatusCode == http.StatusNotFound: + return "not_found", fmt.Errorf("M-Team mall was not found") + case response.StatusCode == http.StatusTooManyRequests: + return "rate_limited", fmt.Errorf("M-Team API refused the request: %w", site.ErrRateLimited) + case response.StatusCode >= 300 && response.StatusCode <= 399: + return "redirect_rejected", fmt.Errorf("M-Team API redirect was rejected") + case response.StatusCode != http.StatusOK: + return "http_status_rejected", fmt.Errorf("M-Team bonus review response status was rejected") + case len(response.Body) == 0: + return "empty_response", fmt.Errorf("M-Team bonus review response was empty") + case !utf8.Valid(response.Body): + return "invalid_text_encoding", fmt.Errorf("M-Team bonus review response text was invalid") + } + switch response.MediaType { + case "application/json", "text/plain", "": + return "", nil + default: + return "content_type_rejected", fmt.Errorf("M-Team API response was not JSON") + } +} + +func decodeMallEnvelope(body []byte) (json.RawMessage, string, error) { + var envelope struct { + Code flexText `json:"code"` + Data json.RawMessage `json:"data"` + } + if !isJSONObject(body) || json.Unmarshal(body, &envelope) != nil || !envelope.Code.set { + return nil, "unrecognized_response", fmt.Errorf("M-Team API response was not recognized") + } + switch envelope.Code.value { + case "0": + return envelope.Data, "", nil + case "401": + return nil, "authentication_required", fmt.Errorf("M-Team API rejected the request: %w", site.ErrCredentialRejected) + case "4": + return nil, "rate_limited", fmt.Errorf("M-Team API refused the request: %w", site.ErrRateLimited) + default: + return nil, "unrecognized_response", fmt.Errorf("M-Team API refused the bonus review request") + } +} + +type mallParseError struct{ reason string } + +func (err *mallParseError) Error() string { return err.reason } + +func mallStopReason(err error) string { + var parseErr *mallParseError + if errors.As(err, &parseErr) { + return parseErr.reason + } + return "unrecognized_response" +} + +// countJSONTokens walks the whole answer once so the review's token budget +// covers every value the site sent, not only the members ptctl keeps. +func countJSONTokens(body []byte, maxTokens int) (int, error) { + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.UseNumber() + tokens := 0 + for { + _, err := decoder.Token() + if err == io.EOF { + return tokens, nil + } + if err != nil { + return tokens, &mallParseError{reason: "unrecognized_response"} + } + if tokens == maxTokens { + return tokens, &mallParseError{reason: "token_budget_exceeded"} + } + tokens++ + } +} + +type mallUsage struct { + forms int + fields int + visibleTextBytes int64 +} + +type mallGoods struct { + ID flexText `json:"id"` + NameChs *string `json:"nameChs"` + NameCht *string `json:"nameCht"` + NameEng *string `json:"nameEng"` + Type *string `json:"type"` + Points flexText `json:"points"` + Roles json.RawMessage `json:"roles"` + Shelf *string `json:"shelf"` +} + +type mallOffer struct { + id, name, kind, points string + availability, inputMode string +} + +// parseMall maps api/mall/list data, a list of goods objects. Each goods +// counts as one form and each of its members as one field. Any goods without +// a canonical ID, a name, a type, or a price fails the whole list, and so does +// a repeated ID, rather than reviewing a partial or ambiguous mall. +func parseMall(data json.RawMessage, limits site.BonusReviewLimits) ([]mallOffer, mallUsage, error) { + var usage mallUsage + var items []json.RawMessage + data = bytes.TrimSpace(data) + if len(data) == 0 || data[0] != '[' || json.Unmarshal(data, &items) != nil { + return nil, usage, &mallParseError{reason: "unrecognized_response"} + } + if len(items) == 0 { + return nil, usage, &mallParseError{reason: "selector_not_found"} + } + offers := make([]mallOffer, 0, len(items)) + seen := make(map[string]struct{}, len(items)) + for _, item := range items { + usage.forms++ + if usage.forms > limits.MaxForms { + return nil, usage, &mallParseError{reason: "form_budget_exceeded"} + } + var members map[string]json.RawMessage + var goods mallGoods + if !isJSONObject(item) || json.Unmarshal(item, &members) != nil || json.Unmarshal(item, &goods) != nil { + return nil, usage, &mallParseError{reason: "unrecognized_offer"} + } + usage.fields += len(members) + if usage.fields > limits.MaxFields { + return nil, usage, &mallParseError{reason: "field_budget_exceeded"} + } + offer, ok := goods.offer() + if !ok { + return nil, usage, &mallParseError{reason: "unrecognized_offer"} + } + if _, duplicate := seen[offer.id]; duplicate { + return nil, usage, &mallParseError{reason: "selector_ambiguous"} + } + seen[offer.id] = struct{}{} + for _, column := range offer.columns() { + usage.visibleTextBytes += int64(len(column)) + } + if usage.visibleTextBytes > limits.MaxVisibleTextBytes { + return nil, usage, &mallParseError{reason: "visible_text_budget_exceeded"} + } + offers = append(offers, offer) + } + return offers, usage, nil +} + +func findOffer(offers []mallOffer, id string) (mallOffer, bool) { + for _, offer := range offers { + if offer.id == id { + return offer, true + } + } + return mallOffer{}, false +} + +func (goods mallGoods) offer() (mallOffer, bool) { + if !goods.ID.set || validateGoodsSelector(goods.ID.value) != nil || goods.Type == nil || !mallType(*goods.Type) { + return mallOffer{}, false + } + points := decimalText(goods.Points) + if points == "" { + return mallOffer{}, false + } + name := "" + for _, candidate := range []*string{goods.NameChs, goods.NameCht, goods.NameEng} { + if candidate == nil { + continue + } + text, ok := cleanText(*candidate, maxGoodsName) + if !ok { + return mallOffer{}, false + } + if text != "" { + name = text + break + } + } + if name == "" { + return mallOffer{}, false + } + offer := mallOffer{id: goods.ID.value, name: name, kind: *goods.Type, points: points} + offer.availability, offer.inputMode = goods.state() + return offer, true +} + +// state reports what the list claims about one goods item. Goods off the +// shelf are disabled. A role restriction is not checked against the account, +// so restricted goods stay unknown rather than claimed available. +func (goods mallGoods) state() (string, string) { + inputMode, known := mallInputModes[*goods.Type] + if !known { + return site.BonusReviewAvailabilityUnknown, site.BonusReviewInputUnsupported + } + shelf := "" + if goods.Shelf != nil { + shelf = *goods.Shelf + } + switch { + case shelf == "NO": + return site.BonusReviewAvailabilityDisabled, inputMode + case shelf != "YES" || !unrestrictedRoles(goods.Roles): + return site.BonusReviewAvailabilityUnknown, inputMode + default: + return site.BonusReviewAvailabilityAvailable, inputMode + } +} + +func unrestrictedRoles(raw json.RawMessage) bool { + raw = bytes.TrimSpace(raw) + if len(raw) == 0 || bytes.Equal(raw, []byte("null")) { + return true + } + var roles []json.RawMessage + return raw[0] == '[' && json.Unmarshal(raw, &roles) == nil && len(roles) == 0 +} + +func (offer mallOffer) columns() []string { + price := "points " + offer.points + if offer.kind == "UPLOAD" { + price += " per GB" + } + return []string{offer.name, offer.kind, price} +} + +// catalogStatus uses bonus review's vocabulary, as the TJUPT catalog does. +func (offer mallOffer) catalogStatus() string { + switch { + case offer.inputMode == site.BonusReviewInputUnsupported: + return site.BonusReviewAvailabilityUnknown + case offer.availability == site.BonusReviewAvailabilityAvailable && offer.inputMode == site.BonusReviewInputRequired: + return offer.availability + ", requires input" + default: + return offer.availability + } +} + +func (offer mallOffer) review(selector string) (domain.BonusOfferReview, error) { + review := domain.BonusOfferReview{ + SiteID: SiteID, + Selector: selector, + Columns: offer.columns(), + Availability: offer.availability, + InputMode: offer.inputMode, + ActionMethod: "post", + ActionRouteID: BonusExchangeRouteID, + FormShapeID: mallFormShapeID(offer), + EvidenceBasis: append([]string(nil), bonusEvidenceBasis...), + } + reviewID, err := site.ComputeBonusReviewID(review) + if err != nil { + return domain.BonusOfferReview{}, err + } + review.ReviewID = reviewID + return review, nil +} + +// mallFormShapeID binds the review to the exact exchange ptctl would send and +// to the type and price the list showed, so a changed price changes the +// review ID and stops an approved intent. +func mallFormShapeID(offer mallOffer) string { + hash := sha256.New() + hash.Write([]byte("ptctl-mteam-mall-exchange-v1\x00")) + var length [8]byte + for _, part := range []string{"goodsId", offer.id, "num", exchangeQuantity, offer.kind, offer.points} { + binary.BigEndian.PutUint64(length[:], uint64(len(part))) + hash.Write(length[:]) + hash.Write([]byte(part)) + } + return "sha256:" + hex.EncodeToString(hash.Sum(nil)) +} + +func exchangeBody(goodsID string) []byte { + return formBody("goodsId", goodsID, "num", exchangeQuantity) +} + +func validateGoodsSelector(selector string) error { + if len(selector) > maxGoodsIDDigits || !canonicalID(selector) { + return fmt.Errorf("M-Team bonus selector must be a canonical goods ID") + } + return nil +} + +func mallType(value string) bool { + if value == "" || len(value) > maxGoodsType { + return false + } + for i := 0; i < len(value); i++ { + if c := value[i]; !(c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_') { + return false + } + } + return true +} + +func completeBonusExchangeReceipt(receipt site.BonusExchangeReceipt) site.BonusExchangeReceipt { + if receipt.ObservedAtStart.IsZero() { + receipt.ObservedAtStart = time.Now().UTC() + } + if receipt.ObservedAtEnd.IsZero() || receipt.ObservedAtEnd.Before(receipt.ObservedAtStart) { + receipt.ObservedAtEnd = receipt.ObservedAtStart + } + receipt.Complete = true + return receipt +} + +func nonzeroBonusTime(value, fallback time.Time) time.Time { + if value.IsZero() { + return fallback.UTC() + } + return value.UTC() +} + +func boundedBonusRequestCount(value int) int { + if value < 0 { + return 0 + } + if value > 3 { + return 3 + } + return value +} diff --git a/internal/site/mteam/bonus_test.go b/internal/site/mteam/bonus_test.go new file mode 100644 index 0000000..4a0c1ac --- /dev/null +++ b/internal/site/mteam/bonus_test.go @@ -0,0 +1,519 @@ +package mteam + +import ( + "context" + "errors" + "net/http" + "reflect" + "strings" + "testing" + "time" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" + "github.com/tonycoder-hub/ptctl/internal/site/httpguard" +) + +// mallFixture is synthetic. It mirrors the shape of api/mall/list and covers +// every state a goods item can be in. +const mallFixture = `{"code":"0","message":"SUCCESS","data":[ + {"id":"6","type":"GLOBAL_FREE_SINGLE","points":"0","shelf":"YES","roles":[],"nameChs":"全站免费 CANARY","nameEng":"Global free CANARY", + "description":"{freeDay} CANARY","extra":{"freeDay":"3"},"createdDate":"2026-01-01 00:00:00"}, + {"id":"1","type":"UPLOAD","points":"800","shelf":"YES","roles":[],"nameChs":"上传量 CANARY","nameEng":"Upload CANARY","extra":{"ratioLimitBonus":"4"}}, + {"id":"2","type":"INVITE","points":"80000","shelf":"YES","roles":[],"nameChs":"","nameEng":"Invite CANARY","extra":{}}, + {"id":"3","type":"TITLE","points":"5000","shelf":"YES","roles":[],"nameChs":"头衔 CANARY"}, + {"id":"5","type":"INVITE_BUY_BONUS","points":"80000","shelf":"YES","roles":[],"nameChs":"邀请换魔力 CANARY"}, + {"id":"8","type":"UPLOAD","points":"700","shelf":"NO","roles":[],"nameChs":"下架 CANARY"}, + {"id":"9","type":"INVITE","points":"1","shelf":"YES","roles":["VIP"],"nameChs":"限定 CANARY"} +]}` + +const exchangeConfirmed = `{"code":"0","message":"SUCCESS","data":null}` + +type scriptedStep struct { + response httpguard.StrictResponse + err error + // unsent leaves the request uncounted, as httpguard does when it refuses + // before the request leaves the process. + unsent bool +} + +type scriptedCall struct { + fakeCall + effect bool +} + +// scriptedClient answers each request with the next step and can also send +// the exchange POST. +type scriptedClient struct { + steps []scriptedStep + calls []scriptedCall + closed bool +} + +func (f *scriptedClient) next(call scriptedCall) (httpguard.StrictResponse, error) { + if len(f.steps) == 0 { + return httpguard.StrictResponse{}, errors.New("scripted client has no step left") + } + step := f.steps[0] + f.steps = f.steps[1:] + if !step.unsent { + f.calls = append(f.calls, call) + } + return step.response, step.err +} + +func (f *scriptedClient) PostReadOnce(_ context.Context, path, contentType string, body []byte, accept string, maxRequest, maxBody, maxHeader int64) (httpguard.StrictResponse, error) { + return f.next(scriptedCall{fakeCall: fakeCall{path, contentType, accept, string(body), maxRequest, maxBody, maxHeader}}) +} + +func (f *scriptedClient) PostEffectOnce(_ context.Context, path, contentType string, body []byte, accept string, maxRequest, maxBody, maxHeader int64) (httpguard.StrictResponse, error) { + return f.next(scriptedCall{fakeCall: fakeCall{path, contentType, accept, string(body), maxRequest, maxBody, maxHeader}, effect: true}) +} + +func (f *scriptedClient) RequestsMade() int { return len(f.calls) } + +func (f *scriptedClient) Close() error { + f.closed = true + return nil +} + +func scriptedAdapter(client guardedClient) (*Adapter, *factoryRecord) { + record := &factoryRecord{} + return &Adapter{newClient: func(baseURL, apiKey string, interval time.Duration) (guardedClient, error) { + record.baseURL, record.apiKey, record.interval = baseURL, apiKey, interval + record.opened++ + return client, nil + }}, record +} + +func observedStatus(status int, mediaType, body string) httpguard.StrictResponse { + response := observedJSON(body) + response.StatusCode, response.MediaType = status, mediaType + return response +} + +func steps(responses ...httpguard.StrictResponse) []scriptedStep { + result := make([]scriptedStep, len(responses)) + for i, response := range responses { + result[i] = scriptedStep{response: response} + } + return result +} + +func TestBonusConfigsArePinned(t *testing.T) { + adapter := New() + review, err := adapter.BonusReviewConfig() + if err != nil || review.Origin != "https://api2.m-team.cc" || review.RouteID != "mteam.mall_list_review.v1" { + t.Fatalf("review config=%#v err=%v", review, err) + } + exchange, err := adapter.BonusExchangeConfig() + if err != nil || exchange.Origin != "https://api2.m-team.cc" || exchange.ReviewRouteID != "mteam.mall_list_review.v1" || + exchange.ActionRouteID != "mteam.mall_exchange_post.v1" { + t.Fatalf("exchange config=%#v err=%v", exchange, err) + } + if !site.IsBonusExchangeMessageConfirmation(bonusConfirmedCode) { + t.Fatalf("confirmation code %q is not a message confirmation", bonusConfirmedCode) + } + for _, selector := range []string{"1", "7", "1234567890"} { + if adapter.ValidateBonusReviewSelector(selector) != nil || adapter.ValidateBonusExchangeSelector(selector) != nil { + t.Fatalf("selector %q rejected", selector) + } + } + for _, selector := range []string{"", "0", "01", " 1", "1 ", "1\n", "-1", "1a", "12345678901"} { + if adapter.ValidateBonusReviewSelector(selector) == nil || adapter.ValidateBonusExchangeSelector(selector) == nil { + t.Fatalf("selector %q accepted", selector) + } + } +} + +func TestBonusCatalogReadsBalanceThenMallOnOneClient(t *testing.T) { + client := &scriptedClient{steps: steps(jsonResponse(profileFixture), jsonResponse(mallFixture))} + adapter, record := scriptedAdapter(client) + catalog, err := adapter.BonusCatalog(context.Background(), apiKey(t)) + if err != nil { + t.Fatal(err) + } + if record.opened != 1 || record.interval != minRequestInterval || !client.closed || len(client.calls) != 2 || + client.calls[0].path != profilePath || client.calls[1].path != mallListPath || client.calls[1].body != emptyFormBody || + client.calls[1].contentType != emptyFormMediaType || client.calls[1].effect { + t.Fatalf("record=%#v calls=%#v closed=%t", record, client.calls, client.closed) + } + want := []domain.BonusCatalogRow{ + {Selector: "6", Columns: []string{"全站免费 CANARY", "GLOBAL_FREE_SINGLE", "points 0", "available, requires input"}}, + {Selector: "1", Columns: []string{"上传量 CANARY", "UPLOAD", "points 800 per GB", "available"}}, + {Selector: "2", Columns: []string{"Invite CANARY", "INVITE", "points 80000", "available"}}, + {Selector: "3", Columns: []string{"头衔 CANARY", "TITLE", "points 5000", "available, requires input"}}, + {Selector: "5", Columns: []string{"邀请换魔力 CANARY", "INVITE_BUY_BONUS", "points 80000", "unknown"}}, + {Selector: "8", Columns: []string{"下架 CANARY", "UPLOAD", "points 700 per GB", "disabled"}}, + {Selector: "9", Columns: []string{"限定 CANARY", "INVITE", "points 1", "unknown"}}, + } + if catalog.SiteID != SiteID || catalog.Balance != "12345.6" || !reflect.DeepEqual(catalog.Rows, want) || catalog.ObservedAt.IsZero() { + t.Fatalf("catalog=%#v", catalog) + } +} + +func TestBonusCatalogFailsClosed(t *testing.T) { + for _, test := range []struct { + name string + mall string + calls int + }{ + {name: "empty mall", mall: `{"code":"0","data":[]}`, calls: 2}, + {name: "mall object", mall: `{"code":"0","data":{"id":"1"}}`, calls: 2}, + {name: "goods without a name", mall: `{"code":"0","data":[{"id":"1","type":"UPLOAD","points":"800","shelf":"YES"}]}`, calls: 2}, + {name: "goods without a price", mall: `{"code":"0","data":[{"id":"1","type":"UPLOAD","shelf":"YES","nameChs":"CANARY"}]}`, calls: 2}, + {name: "goods with a bad ID", mall: `{"code":"0","data":[{"id":"01","type":"UPLOAD","points":"800","nameChs":"CANARY"}]}`, calls: 2}, + {name: "goods with a bad type", mall: `{"code":"0","data":[{"id":"1","type":"upload","points":"800","nameChs":"CANARY"}]}`, calls: 2}, + {name: "repeated goods", mall: `{"code":"0","data":[{"id":"1","type":"UPLOAD","points":"800","nameChs":"A"},{"id":"1","type":"UPLOAD","points":"800","nameChs":"B"}]}`, calls: 2}, + {name: "refused", mall: `{"code":"1","message":"CANARY refusal","data":null}`, calls: 2}, + } { + t.Run(test.name, func(t *testing.T) { + client := &scriptedClient{steps: steps(jsonResponse(profileFixture), jsonResponse(test.mall))} + adapter, _ := scriptedAdapter(client) + catalog, err := adapter.BonusCatalog(context.Background(), apiKey(t)) + if err == nil || len(catalog.Rows) != 0 || len(client.calls) != test.calls || strings.Contains(err.Error(), "CANARY") { + t.Fatalf("catalog=%#v err=%v calls=%d", catalog, err, len(client.calls)) + } + }) + } + // A rejected key stops before the mall is read. + client := &scriptedClient{steps: steps(jsonResponse(`{"code":"401","message":"CANARY","data":null}`), jsonResponse(mallFixture))} + adapter, _ := scriptedAdapter(client) + if _, err := adapter.BonusCatalog(context.Background(), apiKey(t)); !errors.Is(err, site.ErrCredentialRejected) || len(client.calls) != 1 { + t.Fatalf("err=%v calls=%d", err, len(client.calls)) + } +} + +func openReview(t *testing.T, client guardedClient) site.BonusReviewSession { + t.Helper() + adapter, record := scriptedAdapter(client) + session, err := adapter.OpenBonusReviewSession(context.Background(), apiKey(t)) + if err != nil { + t.Fatal(err) + } + if record.opened != 1 || record.baseURL != DefaultBaseURL || record.apiKey != testAPIKey || record.interval != minRequestInterval { + t.Fatalf("factory=%#v", record) + } + return session +} + +func TestBonusReviewReadsOneGoodsItemInOneRequest(t *testing.T) { + client := &scriptedClient{steps: steps(observedJSON(mallFixture))} + session := openReview(t, client) + limits := site.DefaultBonusReviewLimits() + observed, receipt, err := session.ReadBonusReview(context.Background(), "1", limits) + if err != nil { + t.Fatal(err) + } + if len(client.calls) != 1 || client.calls[0].path != mallListPath || client.calls[0].body != emptyFormBody || client.calls[0].effect || + client.calls[0].maxBody != limits.MaxResponseBytes || client.calls[0].maxHeader != limits.MaxResponseHeaderBytes { + t.Fatalf("calls=%#v", client.calls) + } + review := observed.PublicCopy() + if review.SiteID != SiteID || review.Selector != "1" || review.Balance != "" || + !reflect.DeepEqual(review.Columns, []string{"上传量 CANARY", "UPLOAD", "points 800 per GB"}) || + review.Availability != site.BonusReviewAvailabilityAvailable || review.InputMode != site.BonusReviewInputNone || + review.ActionMethod != "post" || review.ActionRouteID != BonusExchangeRouteID || site.ValidateBonusReviewID(review.ReviewID) != nil { + t.Fatalf("review=%#v", review) + } + if !receipt.Complete || receipt.StopReason != "" || receipt.RouteID != BonusReviewRouteID || receipt.Origin != BonusReviewOrigin || + receipt.Used.RequestsAttempted != 1 || receipt.Used.FormsExamined != 7 || receipt.Used.FieldsExamined == 0 || receipt.Used.TokensExamined == 0 || + receipt.Used.VisibleTextBytes == 0 || !observed.MatchesReceipt(receipt) { + t.Fatalf("receipt=%#v", receipt) + } + + // A second read on the session is refused without a request. + _, receipt, err = session.ReadBonusReview(context.Background(), "1", limits) + if err == nil || receipt.StopReason != "request_budget_exhausted" || len(client.calls) != 1 { + t.Fatalf("second read err=%v receipt=%#v", err, receipt) + } + if err := session.Close(); err != nil || !client.closed { + t.Fatalf("close err=%v closed=%t", err, client.closed) + } +} + +func TestBonusReviewReportsWhatTheMallClaims(t *testing.T) { + for _, test := range []struct { + selector, availability, inputMode string + }{ + {"2", site.BonusReviewAvailabilityAvailable, site.BonusReviewInputNone}, + {"3", site.BonusReviewAvailabilityAvailable, site.BonusReviewInputRequired}, + {"6", site.BonusReviewAvailabilityAvailable, site.BonusReviewInputRequired}, + {"5", site.BonusReviewAvailabilityUnknown, site.BonusReviewInputUnsupported}, + {"8", site.BonusReviewAvailabilityDisabled, site.BonusReviewInputNone}, + {"9", site.BonusReviewAvailabilityUnknown, site.BonusReviewInputNone}, + } { + session := openReview(t, &scriptedClient{steps: steps(observedJSON(mallFixture))}) + observed, _, err := session.ReadBonusReview(context.Background(), test.selector, site.DefaultBonusReviewLimits()) + if err != nil { + t.Fatalf("%s: %v", test.selector, err) + } + if review := observed.PublicCopy(); review.Availability != test.availability || review.InputMode != test.inputMode { + t.Fatalf("%s: review=%#v", test.selector, review) + } + } + + // The review ID moves with the price, so an approved intent cannot be + // spent at a different one. + first := openReview(t, &scriptedClient{steps: steps(observedJSON(mallFixture))}) + second := openReview(t, &scriptedClient{steps: steps(observedJSON(strings.Replace(mallFixture, `"points":"800"`, `"points":"900"`, 1)))}) + a, _, errA := first.ReadBonusReview(context.Background(), "1", site.DefaultBonusReviewLimits()) + b, _, errB := second.ReadBonusReview(context.Background(), "1", site.DefaultBonusReviewLimits()) + if errA != nil || errB != nil || a.PublicCopy().ReviewID == b.PublicCopy().ReviewID || a.PublicCopy().FormShapeID == b.PublicCopy().FormShapeID { + t.Fatalf("errA=%v errB=%v", errA, errB) + } +} + +func TestBonusReviewStopsWithoutEchoingServerText(t *testing.T) { + small := func(change func(*site.BonusReviewLimits)) site.BonusReviewLimits { + limits := site.DefaultBonusReviewLimits() + change(&limits) + return limits + } + for _, test := range []struct { + name string + response httpguard.StrictResponse + selector string + limits site.BonusReviewLimits + stop string + }{ + {name: "http 401", response: observedStatus(http.StatusUnauthorized, "application/json", `{"code":"401"}`), stop: "authentication_required"}, + {name: "http 404", response: observedStatus(http.StatusNotFound, "text/html", "CANARY"), stop: "not_found"}, + {name: "http 429", response: observedStatus(http.StatusTooManyRequests, "text/html", "CANARY"), stop: "rate_limited"}, + {name: "redirect", response: observedStatus(http.StatusFound, "text/html", "CANARY"), stop: "redirect_rejected"}, + {name: "http 500", response: observedStatus(http.StatusInternalServerError, "text/html", "CANARY"), stop: "http_status_rejected"}, + {name: "html", response: observedStatus(http.StatusOK, "text/html", "CANARY"), stop: "content_type_rejected"}, + {name: "empty", response: observedJSON(""), stop: "empty_response"}, + {name: "not json", response: observedJSON("CANARY"), stop: "unrecognized_response"}, + {name: "code 401", response: observedJSON(`{"code":"401","message":"CANARY","data":null}`), stop: "authentication_required"}, + {name: "code 4", response: observedJSON(`{"code":"4","message":"CANARY","data":null}`), stop: "rate_limited"}, + {name: "code 1", response: observedJSON(`{"code":"1","message":"CANARY","data":null}`), stop: "unrecognized_response"}, + {name: "missing goods", response: observedJSON(mallFixture), selector: "99", stop: "selector_not_found"}, + {name: "repeated goods", response: observedJSON(`{"code":"0","data":[{"id":"1","type":"UPLOAD","points":"8","nameChs":"A"},{"id":"1","type":"UPLOAD","points":"8","nameChs":"B"}]}`), stop: "selector_ambiguous"}, + {name: "malformed goods", response: observedJSON(`{"code":"0","data":[{"id":"1","type":"UPLOAD","points":"8","nameChs":"A"},{"id":"2","type":"UPLOAD","nameChs":"B"}]}`), stop: "unrecognized_offer"}, + {name: "token budget", response: observedJSON(mallFixture), limits: small(func(l *site.BonusReviewLimits) { l.MaxTokens = 20 }), stop: "token_budget_exceeded"}, + {name: "form budget", response: observedJSON(mallFixture), limits: small(func(l *site.BonusReviewLimits) { l.MaxForms = 3 }), stop: "form_budget_exceeded"}, + {name: "field budget", response: observedJSON(mallFixture), limits: small(func(l *site.BonusReviewLimits) { l.MaxFields = 10 }), stop: "field_budget_exceeded"}, + {name: "text budget", response: observedJSON(mallFixture), limits: small(func(l *site.BonusReviewLimits) { l.MaxVisibleTextBytes = 40 }), stop: "visible_text_budget_exceeded"}, + } { + t.Run(test.name, func(t *testing.T) { + selector, limits := test.selector, test.limits + if selector == "" { + selector = "1" + } + if limits == (site.BonusReviewLimits{}) { + limits = site.DefaultBonusReviewLimits() + } + client := &scriptedClient{steps: steps(test.response)} + session := openReview(t, client) + observed, receipt, err := session.ReadBonusReview(context.Background(), selector, limits) + if err == nil || observed != nil || receipt.Complete || receipt.StopReason != test.stop || len(client.calls) != 1 || strings.Contains(err.Error(), "CANARY") { + t.Fatalf("observed=%v receipt=%#v err=%v", observed, receipt, err) + } + }) + } +} + +func TestBonusReviewFailsBeforeAnyRequest(t *testing.T) { + client := &scriptedClient{steps: steps(observedJSON(mallFixture))} + session := openReview(t, client) + if _, receipt, err := session.ReadBonusReview(context.Background(), "01", site.DefaultBonusReviewLimits()); err == nil || receipt.StopReason != "invalid_selector" { + t.Fatalf("receipt=%#v err=%v", receipt, err) + } + invalid := site.DefaultBonusReviewLimits() + invalid.MaxRequests = 2 + if _, receipt, err := session.ReadBonusReview(context.Background(), "1", invalid); err == nil || receipt.StopReason != "invalid_limits" { + t.Fatalf("receipt=%#v err=%v", receipt, err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, receipt, err := session.ReadBonusReview(ctx, "1", site.DefaultBonusReviewLimits()); !errors.Is(err, context.Canceled) || receipt.StopReason != "context_done" { + t.Fatalf("receipt=%#v err=%v", receipt, err) + } + if len(client.calls) != 0 { + t.Fatalf("calls=%#v", client.calls) + } +} + +func openExchange(t *testing.T, client guardedClient) site.BonusExchangeSession { + t.Helper() + adapter, record := scriptedAdapter(client) + session, err := adapter.OpenBonusExchangeSession(context.Background(), apiKey(t)) + if err != nil { + t.Fatal(err) + } + if record.opened != 1 || record.apiKey != testAPIKey || record.interval != minRequestInterval { + t.Fatalf("factory=%#v", record) + } + return session +} + +func reviewForExchange(t *testing.T, session site.BonusExchangeSession, selector string) *site.ObservedBonusReview { + t.Helper() + observed, _, err := session.ReadFreshBonusReview(context.Background(), selector, site.DefaultBonusReviewLimits(), site.DefaultBonusExchangeLimits()) + if err != nil { + t.Fatal(err) + } + return observed +} + +func TestBonusExchangeSendsOneEffectPostAfterTheFreshReview(t *testing.T) { + client := &scriptedClient{steps: steps(observedJSON(mallFixture), observedJSON(exchangeConfirmed))} + session := openExchange(t, client) + observed := reviewForExchange(t, session, "1") + limits := site.DefaultBonusExchangeLimits() + authority, receipt, err := session.SubmitFreshBonusExchange(context.Background(), observed, observed.PublicCopy().ReviewID, limits) + if err != nil { + t.Fatal(err) + } + wantBody := "--" + formBoundary + "\r\nContent-Disposition: form-data; name=\"goodsId\"\r\n\r\n1\r\n" + + "--" + formBoundary + "\r\nContent-Disposition: form-data; name=\"num\"\r\n\r\n1\r\n" + + "--" + formBoundary + "--\r\n" + if len(client.calls) != 2 || client.calls[0].effect || !client.calls[1].effect || client.calls[1].path != mallExchangePath || + client.calls[1].contentType != emptyFormMediaType || client.calls[1].body != wantBody || client.calls[1].accept != apiAccept || + client.calls[1].maxRequest != limits.MaxFormBytes || client.calls[1].maxBody != limits.MaxResponseBytes { + t.Fatalf("calls=%#v", client.calls) + } + if receipt.Outcome != site.BonusExchangeOutcomeConfirmed || receipt.ConfirmationCode != bonusConfirmedCode || receipt.StopReason != "" || + !receipt.RequestAttempted || !receipt.ResponseComplete || receipt.Used.TotalRequestsAttempted != 2 || receipt.Used.ReviewRequestsAttempted != 1 || + receipt.Used.SubmissionRequestsAttempted != 1 || receipt.Used.FormFieldsSubmitted != 2 || receipt.Used.FormBytesSubmitted != int64(len(wantBody)) || + !authority.MatchesReceipt(receipt) { + t.Fatalf("receipt=%#v", receipt) + } + config, _ := New().BonusExchangeConfig() + if !authority.Matches(SiteID, "1", observed.PublicCopy().ReviewID, config) { + t.Fatal("authority does not match the exchange config") + } + + // The session submits once. + if _, receipt, err := session.SubmitFreshBonusExchange(context.Background(), observed, observed.PublicCopy().ReviewID, limits); err == nil || + receipt.StopReason != "fresh_review_authority_unavailable" || len(client.calls) != 2 { + t.Fatalf("second submit receipt=%#v err=%v", receipt, err) + } +} + +func TestBonusExchangeOutcomes(t *testing.T) { + for _, test := range []struct { + name string + step scriptedStep + outcome string + stop string + }{ + {name: "refused", step: scriptedStep{response: observedJSON(`{"code":"1","message":"CANARY","data":null}`)}, outcome: site.BonusExchangeOutcomeRejected, stop: "server_refused"}, + {name: "code 401", step: scriptedStep{response: observedJSON(`{"code":"401","message":"CANARY"}`)}, outcome: site.BonusExchangeOutcomeRejected, stop: "server_authentication_rejected"}, + {name: "http 401", step: scriptedStep{response: observedStatus(http.StatusUnauthorized, "text/html", "CANARY")}, outcome: site.BonusExchangeOutcomeRejected, stop: "server_authentication_rejected"}, + {name: "code 4", step: scriptedStep{response: observedJSON(`{"code":"4","message":"CANARY"}`)}, outcome: site.BonusExchangeOutcomeRejected, stop: "server_rate_limited"}, + {name: "http 429", step: scriptedStep{response: observedStatus(http.StatusTooManyRequests, "text/html", "CANARY")}, outcome: site.BonusExchangeOutcomeRejected, stop: "server_rate_limited"}, + {name: "http 500", step: scriptedStep{response: observedStatus(http.StatusInternalServerError, "text/html", "CANARY")}, outcome: site.BonusExchangeOutcomeUnknown, stop: "submission_response_unrecognized"}, + {name: "redirect", step: scriptedStep{response: observedStatus(http.StatusFound, "text/html", "")}, outcome: site.BonusExchangeOutcomeUnknown, stop: "submission_response_unrecognized"}, + {name: "html", step: scriptedStep{response: observedStatus(http.StatusOK, "text/html", "

CANARY

")}, outcome: site.BonusExchangeOutcomeUnknown, stop: "submission_response_unrecognized"}, + {name: "no code", step: scriptedStep{response: observedJSON(`{"message":"CANARY"}`)}, outcome: site.BonusExchangeOutcomeUnknown, stop: "submission_response_unrecognized"}, + {name: "transport after send", step: scriptedStep{err: errors.New("CANARY reset")}, outcome: site.BonusExchangeOutcomeUnknown, stop: "submission_transport_uncertain"}, + {name: "not sent", step: scriptedStep{err: errors.New("CANARY refused"), unsent: true}, outcome: site.BonusExchangeOutcomeNotSubmitted, stop: "submission_not_sent"}, + } { + t.Run(test.name, func(t *testing.T) { + client := &scriptedClient{steps: []scriptedStep{{response: observedJSON(mallFixture)}, test.step}} + session := openExchange(t, client) + observed := reviewForExchange(t, session, "2") + authority, receipt, err := session.SubmitFreshBonusExchange(context.Background(), observed, observed.PublicCopy().ReviewID, site.DefaultBonusExchangeLimits()) + if err == nil || authority == nil || !authority.MatchesReceipt(receipt) || receipt.Outcome != test.outcome || receipt.StopReason != test.stop || + receipt.ConfirmationCode != "" || strings.Contains(err.Error(), "CANARY") { + t.Fatalf("receipt=%#v err=%v", receipt, err) + } + }) + } +} + +func TestBonusExchangeRefusesBeforeTheEffect(t *testing.T) { + // Goods that need input or are not available never get a form. + for _, selector := range []string{"3", "5", "8", "9"} { + client := &scriptedClient{steps: steps(observedJSON(mallFixture), observedJSON(exchangeConfirmed))} + session := openExchange(t, client) + observed, receipt, err := session.ReadFreshBonusReview(context.Background(), selector, site.DefaultBonusReviewLimits(), site.DefaultBonusExchangeLimits()) + if err == nil || observed != nil || receipt.StopReason != "submission_form_unavailable" || len(client.calls) != 1 { + t.Fatalf("%s: receipt=%#v err=%v", selector, receipt, err) + } + if _, receipt, err := session.SubmitFreshBonusExchange(context.Background(), nil, strings.Repeat("0", 0)+"sha256:"+strings.Repeat("a", 64), site.DefaultBonusExchangeLimits()); err == nil || + receipt.StopReason != "fresh_review_authority_unavailable" || len(client.calls) != 1 { + t.Fatalf("%s: submit receipt=%#v err=%v", selector, receipt, err) + } + } + + t.Run("mismatched review ID", func(t *testing.T) { + client := &scriptedClient{steps: steps(observedJSON(mallFixture), observedJSON(exchangeConfirmed))} + session := openExchange(t, client) + observed := reviewForExchange(t, session, "1") + _, receipt, err := session.SubmitFreshBonusExchange(context.Background(), observed, "sha256:"+strings.Repeat("b", 64), site.DefaultBonusExchangeLimits()) + if err == nil || receipt.StopReason != "fresh_review_mismatch" || len(client.calls) != 1 { + t.Fatalf("receipt=%#v err=%v", receipt, err) + } + }) + t.Run("canceled before submission", func(t *testing.T) { + client := &scriptedClient{steps: steps(observedJSON(mallFixture), observedJSON(exchangeConfirmed))} + session := openExchange(t, client) + observed := reviewForExchange(t, session, "1") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + authority, receipt, err := session.SubmitFreshBonusExchange(ctx, observed, observed.PublicCopy().ReviewID, site.DefaultBonusExchangeLimits()) + if !errors.Is(err, context.Canceled) || authority == nil || receipt.Outcome != site.BonusExchangeOutcomeNotSubmitted || + receipt.StopReason != "context_before_submission" || len(client.calls) != 1 { + t.Fatalf("receipt=%#v err=%v", receipt, err) + } + }) + t.Run("different limits", func(t *testing.T) { + client := &scriptedClient{steps: steps(observedJSON(mallFixture), observedJSON(exchangeConfirmed))} + session := openExchange(t, client) + observed := reviewForExchange(t, session, "1") + limits := site.DefaultBonusExchangeLimits() + limits.MaxFormBytes-- + _, receipt, err := session.SubmitFreshBonusExchange(context.Background(), observed, observed.PublicCopy().ReviewID, limits) + if err == nil || receipt.StopReason != "fresh_review_authority_unavailable" || len(client.calls) != 1 { + t.Fatalf("receipt=%#v err=%v", receipt, err) + } + }) + t.Run("one fresh review per session", func(t *testing.T) { + client := &scriptedClient{steps: steps(observedJSON(mallFixture), observedJSON(mallFixture))} + session := openExchange(t, client) + reviewForExchange(t, session, "1") + if _, _, err := session.ReadFreshBonusReview(context.Background(), "1", site.DefaultBonusReviewLimits(), site.DefaultBonusExchangeLimits()); err == nil || len(client.calls) != 1 { + t.Fatalf("err=%v calls=%d", err, len(client.calls)) + } + }) + t.Run("closed session", func(t *testing.T) { + client := &scriptedClient{steps: steps(observedJSON(mallFixture))} + session := openExchange(t, client) + if err := session.Close(); err != nil || !client.closed { + t.Fatalf("close err=%v", err) + } + if _, _, err := session.ReadFreshBonusReview(context.Background(), "1", site.DefaultBonusReviewLimits(), site.DefaultBonusExchangeLimits()); err == nil || len(client.calls) != 0 { + t.Fatalf("err=%v calls=%d", err, len(client.calls)) + } + }) +} + +func TestBonusSessionsRejectForeignCredentialsAndReadOnlyClients(t *testing.T) { + cookie, err := site.NewCookieCredential("sid=CANARY") + if err != nil { + t.Fatal(err) + } + adapter, record := scriptedAdapter(&scriptedClient{}) + if _, err := adapter.OpenBonusReviewSession(context.Background(), cookie); err == nil { + t.Fatal("review opened with a cookie") + } + if _, err := adapter.OpenBonusExchangeSession(context.Background(), cookie); err == nil { + t.Fatal("exchange opened with a cookie") + } + if _, err := adapter.BonusCatalog(context.Background(), cookie); err == nil { + t.Fatal("catalog read with a cookie") + } + if record.opened != 0 { + t.Fatalf("factory opened %d clients", record.opened) + } + + // A client that cannot send an effect POST never backs an exchange. + readOnly := &fakeClient{} + adapter, _ = scriptedAdapter(readOnly) + if session, err := adapter.OpenBonusExchangeSession(context.Background(), apiKey(t)); err == nil || session != nil || !readOnly.closed { + t.Fatalf("session=%v err=%v closed=%t", session, err, readOnly.closed) + } +} diff --git a/internal/site/mteam/detail.go b/internal/site/mteam/detail.go index 26dbda8..a487f2d 100644 --- a/internal/site/mteam/detail.go +++ b/internal/site/mteam/detail.go @@ -312,11 +312,15 @@ func validateTorrentRef(ref domain.TorrentRef) error { return nil } -// formBody encodes one multipart field. Callers pass only canonical IDs, so -// the value never needs quoting. -func formBody(name, value string) []byte { - return []byte("--" + formBoundary + "\r\n" + - "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + - value + "\r\n" + - "--" + formBoundary + "--\r\n") +// formBody encodes multipart fields given as name, value pairs. Callers pass +// only fixed names and canonical decimal values, so nothing needs quoting. +func formBody(pairs ...string) []byte { + var body strings.Builder + for i := 0; i+1 < len(pairs); i += 2 { + body.WriteString("--" + formBoundary + "\r\n" + + "Content-Disposition: form-data; name=\"" + pairs[i] + "\"\r\n\r\n" + + pairs[i+1] + "\r\n") + } + body.WriteString("--" + formBoundary + "--\r\n") + return []byte(body.String()) } diff --git a/internal/site/sites/sites_test.go b/internal/site/sites/sites_test.go index de91e6a..cd9070e 100644 --- a/internal/site/sites/sites_test.go +++ b/internal/site/sites/sites_test.go @@ -25,7 +25,7 @@ func samples(t *testing.T) map[string]sitetest.Samples { } return map[string]sitetest.Samples{ tjupt.SiteID: {Credential: cookie, RemoteID: "1", BonusSelector: "1"}, - mteam.SiteID: {Credential: apiKey, RemoteID: "1"}, + mteam.SiteID: {Credential: apiKey, RemoteID: "1", BonusSelector: "1"}, } }