diff --git a/README.md b/README.md index da4665b..3c57618 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,10 @@ capabilities at the edge, not assumptions in the core domain model. - **Content proof:** v1 piece and v2 Merkle verification, bounded discovery of renamed or scattered bytes, and copy-only, journaled materialization. - **Sites:** an experimental TJUPT adapter with session, account, search, - detail, and bonus reads, plus acknowledged metafile fetch and at-most-once - bonus exchange (confirmed with the account password from a stdin bundle); + detail, and bonus reads, plus acknowledged metafile fetch, at-most-once + 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, and search reads through the official API and a site-issued API key. - **Downloaders:** qBittorrent and Transmission reads, plus reviewed stopped @@ -70,7 +72,7 @@ The complete inventory, including what is deliberately not implemented, is in |---|---|---| | Zero-write | `torrent inspect/verify`, `storage probe/map`, `seed discover/plan`, `client status/list`, ordinary `site` reads and `site bonus review`, `reconcile report`, and every `plan`, `status`, `list`, and `inspect` subcommand | None. Reads can still update atime, hydrate offline placeholders, or be recorded by the remote side. | | Private store | `metafile store init/import`, `storage profile create`, `storage index refresh/refresh-discover`, `reconcile refresh-report`, `site bonus exchange prepare` | The explicit command itself. Owner-only and no-clobber; not encrypted. | -| Tracker-visible | `site metafile fetch` (one GET), `site bonus exchange submit` (at most one POST) | `--acknowledge-site-effect`, `--acknowledge-bonus-exchange` | +| Tracker-visible | `site metafile fetch` (one GET), `site bonus exchange submit` (at most one POST), `site login` (one POST and one verifying GET) | `--acknowledge-site-effect`, `--acknowledge-bonus-exchange`; `site login` is the command itself, with the cookie written only to a pipe or owner-only file | | Target filesystem | `seed materialize run/resume/abandon` | `--acknowledge-filesystem-write`, `--acknowledge-abandon` | | Downloader | `client adopt/activate/stop/remove run/resume` | `--acknowledge-client-add`, `--acknowledge-client-recheck`, `--acknowledge-client-stop`, `--acknowledge-client-removal`; repeats, re-adds, and observation-only adoption have their own flags | | Source deletion | `seed retire run/resume`, `seed retire parent-cleanup run/resume` | `--acknowledge-source-deletion`, `--acknowledge-empty-parent-removal` | @@ -128,6 +130,10 @@ stdin; interactive TTY input is refused, and the cookie is never persisted: printf '%s' "$TJUPT_COOKIE" | ptctl site status --cookie-stdin tjupt ``` +For TJUPT, `site login --credential-bundle-stdin tjupt` can issue that cookie +from the account password and two-step code instead; see +[Site reads and bonus exchange](docs/guide/sites.md). + M-Team uses an API key from 控制台 → 实验室 → 建立存取令牌 instead of a cookie, with the same stdin-only rules: diff --git a/docs/ADDING_A_SITE.md b/docs/ADDING_A_SITE.md index 434ee4c..0a1c6d4 100644 --- a/docs/ADDING_A_SITE.md +++ b/docs/ADDING_A_SITE.md @@ -103,6 +103,7 @@ constant, a port interface, and one entry there. | `torrent.metafile.read_effectful` | `MetafileFetcher` | config and session | `site metafile fetch` | | `bonus.offer.review` | `BonusReviewReader` | config and session | `site bonus review` | | `bonus.exchange.submit_effectful` | `BonusExchangeWriter` | config and session | `site bonus exchange prepare`, `submit` | +| `auth.login_effectful` | `SessionLoginer` | login | `site login` | ### Direct ports @@ -157,6 +158,25 @@ If the site confirms each exchange with the account password, also implement cookie-only open is refused. Keep the `AccountPassword` value out of every error, receipt, and formatted struct; TJUPT is the reference. +### Login port + +`SessionLoginer` signs in and returns a new session `Credential`. Declare +`auth.login_effectful` only when the site's login form is understood well +enough to recognize every refusal page. `LoginConfig` lists the session +lengths the site offers and its default; the CLI rejects any other length +before reading stdin. `Login` must: + +- return an error wrapping `context.Canceled` with zero requests when the + context is already done (`sitetest` checks this); +- send one login request with no retry, and accept a session only after one + verifying read with it names the same account; +- report recognized outcomes with a `*site.LoginError` and one of the + `site.Login*` stop reasons, including the site's remaining-attempts count + when its page states one; +- clear any response body that may echo the password, and keep + `LoginCredentials` and the issued cookie out of every error and formatted + value. TJUPT is the reference. + ## Stop reasons Receipts carry a stop reason, and the CLI publishes only values it already @@ -168,6 +188,7 @@ knows. Any other value collapses into a generic code: | Bonus review | `safeBonusReviewStopReason` in `site_bonus.go` | `site.bonus_review_failed` | | Metafile fetch | `publicMetafileStopReason` in `site_metafile.go` | `site.fetch_failed` | | Bonus exchange submit | `safeBonusExchangeSubmitStop` in `site_bonus_exchange.go` | `site.exchange_failed` | +| Login | `knownLoginStopReason` in `site_login.go` | `site login failed` | Reuse an existing stop reason whenever one fits. A new one is a public-contract change: add it to the allowlist and to the CLI tests in the same commit. @@ -187,7 +208,8 @@ reaches the user. An adapter may wrap one of the sentinels in | `site.ErrAddressBlocked` | `httpguard.ErrBlockedAddress`: DNS returned only private or reserved addresses, as with fake-IP proxies. | Wrapping a sentinel changes that adapter's public error text, so add it -deliberately and pin it in tests. TJUPT wraps none of them. +deliberately and pin it in tests. TJUPT's reads wrap none of them; its login +wraps `site.ErrAddressBlocked`, which `site login` names the same way. ## Persisted identity diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d4570d1..455555e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -353,6 +353,13 @@ Capabilities are small and explicit: - `bonus.catalog.read` - `bonus.offer.review` - `bonus.exchange.submit_effectful` +- `auth.login_effectful` + +`auth.login_effectful` (`site.SessionLoginer`) signs in with an account +password and optional one-time code, read from one stdin bundle, and returns a +verified cookie credential that ptctl writes only to a non-terminal stdout and +never stores. It sends one login request and at most one verifying read, never +retries, and reports a refusal only by a fixed stop reason. Site-specific form or action writes live under narrow namespaced typed ports and durable action schemas. They are not forced into universal fields. The effectful diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 2122986..b80652f 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -102,6 +102,7 @@ Per-command details are in | `--site-cookie-stdin` | `reconcile report` with a live site observation and no downloader | The complete `Cookie` header value | | `--credential-bundle-stdin` | `reconcile report` with both a live site observation and a downloader | `{"schema":"ptctl.credentials/v1","site_cookie":"...","downloader_password":"..."}` | | `--credential-bundle-stdin` | `site bonus exchange submit` for sites that confirm with the account password (TJUPT) | `{"schema":"ptctl.credentials/v1","site_cookie":"...","site_password":"..."}` | +| `--credential-bundle-stdin` | `site login` | `{"schema":"ptctl.credentials/v1","site_username":"...","site_password":"...","site_totp":"123456"}`; `site_totp` is optional | - An interactive terminal on stdin is refused; the secret must be piped. - Single secrets are limited to 64 KiB and the bundle to 128 KiB. The bundle is @@ -109,7 +110,9 @@ Per-command details are in - Site reads, metafile fetch, and reconciliation validate usage, capabilities, and local inputs before reading stdin. - Credentials stay in memory. They are never persisted, printed, or forwarded - in error text. + in error text. The one exception is the session cookie `site login` issues: + it is written to stdout, which must be a pipe or an owner-only file, so the + caller decides where it is kept. - `ptctl site capabilities SITE` lists the authentication methods a site accepts: `cookie_header` takes `--cookie-stdin`, `api_key_header` takes `--api-key-stdin`. Omitting the flag names the one the site needs. @@ -122,7 +125,7 @@ Per-command details are in ## Effects and acknowledgements Every write and every tracker-visible or downloader effect requires its own -flag. Each effectful run also takes the ID printed by its zero-write review +flag, except `site login`, whose only effect is the sign-in the command names. Each effectful run also takes the ID printed by its zero-write review (`--expect-plan-id`, `--expect-adoption-plan-id`, `--expect-activation-plan-id`, `--expect-stop-plan-id`, `--expect-removal-plan-id`, `--expect-cleanup-plan-id`, or diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 1dfae97..934004c 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -96,6 +96,11 @@ deliberately does not. For step-by-step usage, see the - an explicitly acknowledged TJUPT metafile fetch for one remote ID, using one bounded GET with no redirect or retry and publishing the strictly validated exact response only into an initialized private metafile store; +- TJUPT password login with an optional six-digit two-step code from one strict + stdin bundle: one non-retried login POST, recognized refusal pages reported + as fixed stop reasons with the site's remaining-attempts count, and one + verifying read that must name the same account before the new session cookie + is written to a pipe or owner-only stdout; - an experimental M-Team session check, account snapshot (username, uploaded and downloaded bytes, ratio, and bonus), and first-page torrent search with seeders, leechers, and promotion factors, through one read-only POST per diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 26e496f..ee9500b 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -124,6 +124,13 @@ for an explicit numeric loopback address. ### Retry storms and account bans The TJUPT adapter sends at most one bounded GET per command and never retries. +`site login` is the exception: one login POST, then one verifying GET only if +the site issued a session cookie. Because TJUPT blocks the client IP after ten +failed logins, a failed or ambiguous login is never retried, the site's own +remaining-attempts count is surfaced when its page states one, and the +two-step page, which echoes the password in a hidden field, is cleared after +classification. The issued cookie is written only to a pipe or an owner-only +stdout file and is kept only after the verifying read names the same account. The M-Team adapter sends at most one bounded POST per command to one of two read-only JSON API endpoints (`member/profile` and `torrent/search`), with a non-replayable body of at most 16 KiB, and never retries. HTTP 429 is terminal. There is no cross-process limiter in the alpha, so diff --git a/docs/TJUPT_ADAPTER.md b/docs/TJUPT_ADAPTER.md index ada863b..bdc78a4 100644 --- a/docs/TJUPT_ADAPTER.md +++ b/docs/TJUPT_ADAPTER.md @@ -5,7 +5,7 @@ TJUPT is the first experimental site implementation, not a special case embedded in the content core. Its read commands were run against the live site with a real session in October 2026. The adapter declares six ordinary read -capabilities plus two separately acknowledged effectful capabilities: +capabilities plus three effectful capabilities: - session check; - account snapshot read; @@ -15,10 +15,13 @@ capabilities plus two separately acknowledged effectful capabilities: - exact-option, zero-write bonus-offer review; - acknowledged metafile fetch into the private store; - acknowledged, at-most-once bonus exchange, confirmed with the account - password (see [Bonus exchange](#bonus-exchange)). + password (see [Bonus exchange](#bonus-exchange)); +- password login with an optional two-step code, issuing a new session cookie + (see [Login](#login)). -Every TJUPT read sends at most one bounded GET. Only `site bonus exchange -submit` submits a form: one fresh review GET, then at most one POST. +Every TJUPT read sends at most one bounded GET. Only two commands submit a +form: `site bonus exchange submit` sends one fresh review GET, then at most one +POST, and `site login` sends one login POST, then at most one verifying GET. All site transports use the configured TJUPT HTTPS origin, do not retry, and refuse to follow redirects. Each effectful acknowledgement is therefore scoped to a fixed request count. @@ -237,9 +240,10 @@ The generic workflow is described in ## Authentication -The adapter does not automate login, bypass CAPTCHA/Cloudflare, or read browser -cookie stores. A caller may provide the complete Cookie header value through -stdin for one process: +The adapter does not bypass CAPTCHA/Cloudflare or read browser cookie stores. +A caller provides the complete Cookie header value through stdin for one +process, either copied from a browser session or issued by `site login` +([below](#login)): ```bash printf '%s' "$TJUPT_COOKIE" | ptctl site status --cookie-stdin tjupt @@ -258,6 +262,50 @@ Adapter runtime errors are exposed only as fixed safe diagnostics, with typed context cancellation or deadline causes preserved; raw cookie, request, and response details do not cross the CLI boundary. +### Login + +`site login --credential-bundle-stdin tjupt` implements +`auth.login_effectful`, declared only on the default origin. Usage, the +session length, and stdout safety are checked before stdin is read; the bundle +then carries `site_username`, `site_password`, and an optional `site_totp`, +which TJUPT requires to be exactly six digits. Command usage, output, and stop +reasons are in the [sites guide](guide/sites.md). + +TJUPT's `login.php` posts `username`, `password`, and `logout` (the session +length in days: 1, 7, 14, 30, or 90) to `takelogin.php`. An account with +two-step verification gets a `verifyform` page back that re-posts the same +fields plus `verify_code`, so one POST that already carries `verify_code` +completes the login. The adapter sends exactly that one form POST over fresh +HTTP/1.1 with no cookie, no connection reuse, no redirect following, and no +retry, within a 1 MiB body and 32 KiB header budget. Only an `access_token` +`Set-Cookie` is captured; deleted or expired values are ignored, and two +different values fail closed. The response is classified in this order: + +- a `text/html` page with the `verifyform` form and its `verify_code` input: + `login_two_factor_required`, or `login_two_factor_rejected` when a code was + sent; +- a `text/html` 200 page with no session cookie and a `登录失败` / `登錄失敗` / + `login failed` marker: `login_credentials_rejected`; +- exactly one live `access_token` with status 200–399: a candidate session; +- anything else: `login_response_unrecognized`. + +When a refusal page states `你还有 N 次尝试机会`, N is reported with the stop +reason. The two-step page echoes the password in a hidden field, so the +response body is cleared right after classification and never logged. A +candidate session is kept only after a two-second pause and one +`mybonus.php` read with it that is authenticated and names the same username +(case-insensitively); otherwise the stop reason is `login_session_unverified` +and the cookie is dropped. The reported expiry is the cookie's own `Expires`. +A request that fails in transport, or whose response the shared guard rejects, +stops with `login_request_failed`; a host that resolves only to blocked +addresses keeps the `site.ErrAddressBlocked` cause. + +TJUPT blocks the client IP after ten failed logins, so a failed login is never +retried. In October 2026 a login without a code returned the two-step page +with all ten attempts still offered, and a login with a code from a password +manager issued a seven-day `access_token` in two requests that `site status` +and `site account` then accepted. + ## Fixtures Parser tests use synthetic HTML with fictitious users and values, including diff --git a/docs/guide/sites.md b/docs/guide/sites.md index ff0ed17..32b5245 100644 --- a/docs/guide/sites.md +++ b/docs/guide/sites.md @@ -34,6 +34,54 @@ TJUPT search results also carry the category ID, publish time (in UTC), seeders, leechers, snatches, and promotion when the results table has its usual shape; otherwise a result keeps only its name and size. +Instead of copying the cookie out of a browser, `site login` can sign in with +the account password and write a new session cookie for the commands above. +It takes one strict `ptctl.credentials/v1` bundle on stdin with +`site_username`, `site_password`, and, for an account with two-step +verification, the current one-time code in `site_totp`. Stdout must be a pipe +or an owner-only file: the command refuses a terminal, a device, or a file +other users can read. One way to build the bundle without putting a secret in +argv, here with the 1Password CLI supplying the code: + +```bash +(umask 077 + jq -n --arg user "$TJUPT_USER" \ + --rawfile password "$PASSWORD_FILE" \ + --rawfile totp <(op item get "$TJUPT_ITEM" --otp) \ + '{schema: "ptctl.credentials/v1", + site_username: $user, + site_password: ($password | rtrimstr("\n")), + site_totp: ($totp | rtrimstr("\n"))}' | \ + ptctl site login --credential-bundle-stdin tjupt > "$COOKIE_FILE") + +ptctl site status --cookie-stdin tjupt < "$COOKIE_FILE" +``` + +Leave out `site_totp` when the account has no two-step verification. +`--session-days` picks the session length the site offers (TJUPT: 1, 7, 14, 30, +or 90; default 7). On success, stdout holds only the cookie line and stderr +reports `site login succeeded: site=tjupt username=... session_expires=... +requests=2`. + +Login sends one POST and never retries. If the site issues a session cookie, +ptctl waits two seconds and makes one read with it, and keeps the cookie only +if that read shows the same signed-in account. Otherwise it exits `1` with +`site login stopped: REASON`: + +| Reason | Meaning | +|---|---| +| `login_credentials_rejected` | The site refused the username or password. | +| `login_two_factor_required` | The account needs a one-time code and the bundle had none. | +| `login_two_factor_rejected` | The one-time code was wrong or expired. | +| `login_response_unrecognized` | The site answered with a page ptctl does not recognize. | +| `login_session_unverified` | A cookie was issued, but the verifying read did not show the same signed-in account. The cookie is discarded. | +| `login_request_failed` | The request failed or its response was rejected before classification. The site may still have counted the attempt. | + +TJUPT blocks the client IP after ten failed logins. When the page states how +many attempts are left, the error line ends with `(the site reports N login +attempts left before it blocks this IP)`. Fix the input before trying again, +and never loop `site login`. Usage errors exit `2` before stdin is read. + M-Team reads use a site-issued API key instead of a cookie, passed with `--api-key-stdin` under the same stdin-only rules. `status`, `account`, and `search` each send one read-only POST to M-Team's JSON API and never retry; diff --git a/internal/cli/reconcile_credentials.go b/internal/cli/reconcile_credentials.go index 5ce4fac..c8495ea 100644 --- a/internal/cli/reconcile_credentials.go +++ b/internal/cli/reconcile_credentials.go @@ -84,6 +84,14 @@ func decodeReconciliationCredentialBundle(raw []byte) (map[string]string, error) // decodeCredentialBundle strictly decodes one JSON object whose keys are // exactly fields, each once, with string values and no trailing data. func decodeCredentialBundle(raw []byte, fields ...string) (map[string]string, error) { + return decodeCredentialBundleOptional(raw, fields, nil) +} + +// decodeCredentialBundleOptional is decodeCredentialBundle with optional keys: +// every required key must appear, each optional key may appear, and any other +// key is rejected. +func decodeCredentialBundleOptional(raw []byte, required, optional []string) (map[string]string, error) { + fields := append(append([]string(nil), required...), optional...) decoder := json.NewDecoder(bytes.NewReader(raw)) first, err := decoder.Token() if err != nil || first != json.Delim('{') { @@ -119,8 +127,10 @@ func decodeCredentialBundle(raw []byte, fields ...string) (map[string]string, er if token, err := decoder.Token(); err != io.EOF || token != nil { return nil, fmt.Errorf("credential bundle has trailing data") } - if len(values) != len(fields) { - return nil, fmt.Errorf("credential bundle field is missing") + for _, field := range required { + if _, present := values[field]; !present { + return nil, fmt.Errorf("credential bundle field is missing") + } } return values, nil } diff --git a/internal/cli/run.go b/internal/cli/run.go index 1eed8c1..348d7f2 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -131,6 +131,7 @@ are supplied. See docs/READ_ONLY_QUICKSTART.md for the short read-only guide. Usage: ptctl site list [--output table|json] ptctl site capabilities [--output table|json] [SITE] + ptctl site login --credential-bundle-stdin [--session-days N] SITE ptctl site status (--cookie-stdin | --api-key-stdin) [--output table|json] SITE ptctl site account (--cookie-stdin | --api-key-stdin) [--output table|json] SITE ptctl site search (--cookie-stdin | --api-key-stdin) [--output table|json] SITE QUERY... @@ -218,6 +219,7 @@ Usage: Safety defaults: * Ordinary site reads are one bounded request per invocation: a GET, or a read-only POST for JSON API sites such as M-Team. Bonus exchange is one fresh GET plus at most one acknowledged POST after a durable marker. Site requests are never automatically retried. * Session cookies and site API keys are accepted only through stdin and are never persisted. + * Site login reads the account password and optional one-time code only from stdin, sends one login request plus one verifying read, never retries, and writes the new session cookie only to a non-terminal stdout. * .torrent tracker URLs are reduced to origins; passkeys are never printed. * The metafile store preserves exact private bytes with owner-only access and atomic no-clobber commits. * v1, v2, and hybrid verification use exact content proofs; names and sizes are not proof. diff --git a/internal/cli/site.go b/internal/cli/site.go index 9be440b..a9b9f0d 100644 --- a/internal/cli/site.go +++ b/internal/cli/site.go @@ -26,6 +26,8 @@ func (a *app) site(args []string) error { return a.siteRead(args[0], args[1:]) case "detail": return a.siteDetail(args[1:]) + case "login": + return a.siteLogin(args[1:]) case "bonus": if len(args) >= 2 { switch args[1] { diff --git a/internal/cli/site_contract_test.go b/internal/cli/site_contract_test.go index 3b027f2..051e053 100644 --- a/internal/cli/site_contract_test.go +++ b/internal/cli/site_contract_test.go @@ -29,7 +29,8 @@ const tjuptDescriptorJSON = ` { "torrent.detail", "torrent.metafile.read_effectful", "bonus.offer.review", - "bonus.exchange.submit_effectful" + "bonus.exchange.submit_effectful", + "auth.login_effectful" ] }` @@ -64,7 +65,7 @@ func TestBuiltinSiteDiscoveryOutputIsStable(t *testing.T) { {args: []string{"site", "list"}, want: "" + "ID NAME STABILITY BASE URL CAPABILITIES\n" + "mteam M-Team / 馒头PT experimental https://api2.m-team.cc/ 3\n" + - "tjupt TJUPT / 北洋园PT experimental https://www.tjupt.org/ 8\n"}, + "tjupt TJUPT / 北洋园PT experimental https://www.tjupt.org/ 9\n"}, {args: []string{"site", "capabilities", "tjupt"}, want: "" + "SITE KIND VALUE\n" + "tjupt auth cookie_header\n" + @@ -75,7 +76,8 @@ func TestBuiltinSiteDiscoveryOutputIsStable(t *testing.T) { "tjupt capability torrent.detail\n" + "tjupt capability torrent.metafile.read_effectful\n" + "tjupt capability bonus.offer.review\n" + - "tjupt capability bonus.exchange.submit_effectful\n"}, + "tjupt capability bonus.exchange.submit_effectful\n" + + "tjupt capability auth.login_effectful\n"}, {args: []string{"site", "capabilities", "mteam"}, want: "" + "SITE KIND VALUE\n" + "mteam auth api_key_header\n" + diff --git a/internal/cli/site_login.go b/internal/cli/site_login.go new file mode 100644 index 0000000..bddf559 --- /dev/null +++ b/internal/cli/site_login.go @@ -0,0 +1,184 @@ +package cli + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "runtime" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" +) + +const siteLoginTimeout = 45 * time.Second + +// siteLogin signs in with an account password from stdin and writes the new +// session cookie, and nothing else, to stdout, so it can be redirected into a +// private file that later --cookie-stdin commands read. Everything a person +// needs to see goes to stderr. +func (a *app) siteLogin(args []string) error { + fs := newFlagSet("site login") + bundleStdin := fs.Bool("credential-bundle-stdin", false, "read a ptctl.credentials/v1 bundle with site_username, site_password, and optional site_totp from stdin") + sessionDays := fs.Int("session-days", 0, "session length in days; must be one the site offers (default: the site's default)") + if err := fs.Parse(args); err != nil { + return usageError("site login: %v", err) + } + if fs.NArg() != 1 { + return usageError("site login requires exactly one SITE") + } + if !*bundleStdin { + return usageError("--credential-bundle-stdin is required; credentials are never accepted in argv") + } + adapter, ok := a.registry.Get(fs.Arg(0)) + if !ok { + return usageError("unknown site %q", fs.Arg(0)) + } + descriptor := adapter.Descriptor() + if !descriptor.Supports(domain.CapabilityLogin) { + return usageError("site %q does not declare capability %q", descriptor.ID, domain.CapabilityLogin) + } + loginer, ok := adapter.(site.SessionLoginer) + if !ok { + return fmt.Errorf("site %q declares %q but does not implement its typed port", descriptor.ID, domain.CapabilityLogin) + } + config := loginer.LoginConfig() + days := *sessionDays + if days == 0 { + days = config.DefaultSessionDays + } + if !config.Allows(days) { + return usageError("--session-days must be one of %s for site %q", joinDays(config.SessionDays), descriptor.ID) + } + if err := rejectUnsafeCookieOutput(a.stdout); err != nil { + return usageError("%v", err) + } + credentials, err := readLoginCredentialBundle(a.stdin) + if err != nil { + return err + } + + ctx, cancel := context.WithTimeout(context.Background(), siteLoginTimeout) + defer cancel() + result, err := loginer.Login(ctx, credentials, days) + if err != nil { + return siteLoginPublicError(ctx, err) + } + if _, err := io.WriteString(a.stdout, result.Session.SecretValue()+"\n"); err != nil { + return fmt.Errorf("write site session cookie to stdout failed") + } + expires := "unknown" + if result.ExpiresAt != nil { + expires = result.ExpiresAt.UTC().Format(time.RFC3339) + } + fmt.Fprintf(a.stderr, "site login succeeded: site=%s username=%s session_expires=%s requests=%d\n", + terminalSafe(descriptor.ID), terminalSafe(result.Username), expires, result.RequestsAttempted) + return nil +} + +func joinDays(days []int) string { + parts := make([]string, len(days)) + for i, day := range days { + parts[i] = strconv.Itoa(day) + } + return strings.Join(parts, ", ") +} + +// rejectUnsafeCookieOutput refuses to print a session cookie to a terminal or +// another device, or into a regular file that group or other users can read. +// Pipes are allowed. Windows file modes do not express ownership, so the file +// check only runs elsewhere. +func rejectUnsafeCookieOutput(writer io.Writer) error { + file, ok := writer.(*os.File) + if !ok { + return nil + } + info, err := file.Stat() + if err != nil { + return fmt.Errorf("inspect session cookie output failed") + } + if info.Mode()&(os.ModeDevice|os.ModeCharDevice) != 0 { + return fmt.Errorf("refusing to write a session cookie to a terminal or device; redirect stdout to a private file or a pipe") + } + if runtime.GOOS != "windows" && info.Mode().IsRegular() && info.Mode().Perm()&0o077 != 0 { + return fmt.Errorf("refusing to write a session cookie to a file other users can access; create it with umask 077") + } + return nil +} + +// readLoginCredentialBundle reads the account username, password, and +// optional one-time code for one login, as one ptctl.credentials/v1 bundle on +// stdin. +func readLoginCredentialBundle(reader io.Reader) (site.LoginCredentials, error) { + if err := rejectTTYSecret(reader); err != nil { + return site.LoginCredentials{}, err + } + raw, err := io.ReadAll(io.LimitReader(reader, maxCredentialBundleBytes+1)) + if err != nil { + return site.LoginCredentials{}, fmt.Errorf("read site login credential bundle from stdin failed") + } + if len(raw) == 0 || len(raw) > maxCredentialBundleBytes || !utf8.Valid(raw) { + return site.LoginCredentials{}, fmt.Errorf("site login credential bundle is invalid") + } + values, err := decodeCredentialBundleOptional(raw, []string{"schema", "site_username", "site_password"}, []string{"site_totp"}) + if err != nil { + return site.LoginCredentials{}, fmt.Errorf("site login credential bundle is invalid") + } + if values["schema"] != reconciliationCredentialSchema { + return site.LoginCredentials{}, fmt.Errorf("site login credential bundle schema is unsupported") + } + password, err := site.NewAccountPassword(values["site_password"]) + if err != nil { + return site.LoginCredentials{}, fmt.Errorf("site login account password is invalid") + } + code, hasCode := values["site_totp"] + if hasCode { + // Command substitution and password managers can leave surrounding + // whitespace; an empty code is still invalid rather than "none". + code = strings.TrimSpace(code) + if code == "" { + return site.LoginCredentials{}, fmt.Errorf("site login one-time code is invalid") + } + } + credentials, err := site.NewLoginCredentials(values["site_username"], password, code) + if err != nil { + // NewLoginCredentials errors are fixed texts that name the field only. + return site.LoginCredentials{}, fmt.Errorf("site %v", err) + } + return credentials, nil +} + +func siteLoginPublicError(ctx context.Context, err error) error { + if errors.Is(err, context.Canceled) || errors.Is(ctx.Err(), context.Canceled) { + return fmt.Errorf("site login canceled: %w", context.Canceled) + } + if errors.Is(err, context.DeadlineExceeded) || errors.Is(ctx.Err(), context.DeadlineExceeded) { + return fmt.Errorf("site login timed out: %w", context.DeadlineExceeded) + } + var stopped *site.LoginError + if errors.As(err, &stopped) && knownLoginStopReason(stopped.Reason) { + if stopped.AttemptsRemaining != nil { + return fmt.Errorf("site login stopped: %s (the site reports %d login attempts left before it blocks this IP)", stopped.Reason, *stopped.AttemptsRemaining) + } + return fmt.Errorf("site login stopped: %s", stopped.Reason) + } + for _, cause := range []error{site.ErrRateLimited, site.ErrAddressBlocked} { + if errors.Is(err, cause) { + return fmt.Errorf("site login failed: %v", cause) + } + } + return fmt.Errorf("site login failed") +} + +func knownLoginStopReason(reason string) bool { + switch reason { + case site.LoginCredentialsRejected, site.LoginTwoFactorRequired, site.LoginTwoFactorRejected, site.LoginResponseUnrecognized, site.LoginSessionUnverified, site.LoginRequestFailed: + return true + } + return false +} diff --git a/internal/cli/site_login_test.go b/internal/cli/site_login_test.go new file mode 100644 index 0000000..87c6280 --- /dev/null +++ b/internal/cli/site_login_test.go @@ -0,0 +1,246 @@ +package cli + +import ( + "bytes" + "context" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" +) + +const loginSessionCanary = "access_token=SESSION-CANARY" + +type fakeLoginAdapter struct { + result site.LoginResult + err error + calls int + username string + password string + code string + hasCode bool + sessionDays int +} + +func (*fakeLoginAdapter) Descriptor() domain.SiteDescriptor { + return domain.SiteDescriptor{ + ID: "fakept", Name: "Fake PT", BaseURL: "https://fake.invalid/", Stability: "test", + AuthMethods: []domain.AuthMethod{domain.AuthMethodCookieHeader}, + Capabilities: []domain.Capability{domain.CapabilityLogin}, + } +} + +func (*fakeLoginAdapter) LoginConfig() site.LoginConfig { + return site.LoginConfig{SessionDays: []int{1, 7, 30}, DefaultSessionDays: 7} +} + +func (adapter *fakeLoginAdapter) Login(_ context.Context, credentials site.LoginCredentials, sessionDays int) (site.LoginResult, error) { + adapter.calls++ + adapter.username = credentials.Username() + adapter.password = credentials.Password().SecretValue() + adapter.code, adapter.hasCode = credentials.OneTimeCode() + adapter.sessionDays = sessionDays + return adapter.result, adapter.err +} + +type readOnlyFakeSite struct{} + +func (readOnlyFakeSite) Descriptor() domain.SiteDescriptor { + return domain.SiteDescriptor{ + ID: "readonly", Name: "Read Only", BaseURL: "https://readonly.invalid/", Stability: "test", + AuthMethods: []domain.AuthMethod{domain.AuthMethodCookieHeader}, + } +} + +func successfulLoginAdapter(t *testing.T) *fakeLoginAdapter { + t.Helper() + session, err := site.NewCookieCredential(loginSessionCanary) + if err != nil { + t.Fatal(err) + } + expires := time.Date(2026, 10, 22, 15, 4, 33, 0, time.UTC) + return &fakeLoginAdapter{result: site.LoginResult{Session: session, Username: "CanaryUser", ExpiresAt: &expires, RequestsAttempted: 2}} +} + +func loginBundle(fields ...string) string { + return `{"schema":"ptctl.credentials/v1","site_username":"CanaryUser","site_password":"PASSWORD-CANARY"` + strings.Join(fields, "") + `}` +} + +func runSiteLogin(adapter site.Adapter, stdin io.Reader, stdout io.Writer, args ...string) (int, string) { + var errOut bytes.Buffer + a := &app{stdin: stdin, stdout: stdout, stderr: &errOut, registry: site.NewRegistry(adapter, readOnlyFakeSite{})} + code := runWithApp(append([]string{"site", "login"}, args...), a) + return code, errOut.String() +} + +func assertNoLoginLeak(t *testing.T, outputs ...string) { + t.Helper() + for _, output := range outputs { + for _, secret := range []string{"PASSWORD-CANARY", "SESSION-CANARY", "123456", "654321"} { + if strings.Contains(output, secret) { + t.Fatalf("secret %q leaked: %q", secret, output) + } + } + } +} + +func TestSiteLoginWritesOnlyTheSessionCookieToStdout(t *testing.T) { + adapter := successfulLoginAdapter(t) + var out bytes.Buffer + code, stderr := runSiteLogin(adapter, strings.NewReader(loginBundle(`,"site_totp":" 123456\n"`)), &out, "--credential-bundle-stdin", "fakept") + if code != 0 || out.String() != loginSessionCanary+"\n" { + t.Fatalf("code=%d stdout=%q stderr=%q", code, out.String(), stderr) + } + if stderr != "site login succeeded: site=fakept username=CanaryUser session_expires=2026-10-22T15:04:33Z requests=2\n" { + t.Fatalf("stderr=%q", stderr) + } + if adapter.calls != 1 || adapter.username != "CanaryUser" || adapter.password != "PASSWORD-CANARY" || !adapter.hasCode || adapter.code != "123456" || adapter.sessionDays != 7 { + t.Fatalf("login calls=%d username=%q days=%d hasCode=%v", adapter.calls, adapter.username, adapter.sessionDays, adapter.hasCode) + } + + adapter = successfulLoginAdapter(t) + adapter.result.ExpiresAt = nil + out.Reset() + code, stderr = runSiteLogin(adapter, strings.NewReader(loginBundle()), &out, "--credential-bundle-stdin", "--session-days", "30", "fakept") + if code != 0 || adapter.hasCode || adapter.sessionDays != 30 || !strings.Contains(stderr, "session_expires=unknown") { + t.Fatalf("code=%d hasCode=%v days=%d stderr=%q", code, adapter.hasCode, adapter.sessionDays, stderr) + } +} + +func TestSiteLoginUsageErrorsNeverReadStdin(t *testing.T) { + for _, args := range [][]string{ + {}, + {"fakept"}, + {"--credential-bundle-stdin"}, + {"--credential-bundle-stdin", "fakept", "extra"}, + {"--credential-bundle-stdin", "--password", "PASSWORD-CANARY", "fakept"}, + {"--credential-bundle-stdin", "unknown"}, + {"--credential-bundle-stdin", "readonly"}, + {"--credential-bundle-stdin", "--session-days", "2", "fakept"}, + {"--credential-bundle-stdin", "--session-days", "-7", "fakept"}, + } { + adapter := successfulLoginAdapter(t) + reader := &trackingReader{} + var out bytes.Buffer + code, stderr := runSiteLogin(adapter, reader, &out, args...) + if code != 2 || reader.read || adapter.calls != 0 || out.Len() != 0 { + t.Fatalf("args=%q code=%d read=%v calls=%d stderr=%q", args, code, reader.read, adapter.calls, stderr) + } + assertNoLoginLeak(t, stderr) + } + reader := &trackingReader{} + var out, errOut bytes.Buffer + if code := Run([]string{"site", "login", "--credential-bundle-stdin", "mteam"}, reader, &out, &errOut); code != 2 || reader.read || + !strings.Contains(errOut.String(), `site "mteam" does not declare capability "auth.login_effectful"`) { + t.Fatalf("mteam code=%d read=%v stderr=%q", code, reader.read, errOut.String()) + } +} + +func TestSiteLoginRejectsInvalidBundlesWithoutContactingTheSite(t *testing.T) { + tests := []struct { + bundle string + want string + }{ + {bundle: "", want: "site login credential bundle is invalid"}, + {bundle: `{"schema":"ptctl.credentials/v1","site_username":"CanaryUser"}`, want: "site login credential bundle is invalid"}, + {bundle: loginBundle(`,"site_cookie":"SESSION-CANARY"`), want: "site login credential bundle is invalid"}, + {bundle: loginBundle(`,"site_totp":"123456","site_totp":"654321"`), want: "site login credential bundle is invalid"}, + {bundle: strings.Replace(loginBundle(), "ptctl.credentials/v1", "ptctl.credentials/v2", 1), want: "site login credential bundle schema is unsupported"}, + {bundle: loginBundle(`,"site_totp":" "`), want: "site login one-time code is invalid"}, + {bundle: loginBundle(`,"site_totp":"12a456"`), want: "site login one-time code is invalid"}, + {bundle: strings.Replace(loginBundle(), `"CanaryUser"`, `" CanaryUser"`, 1), want: "site login username is invalid"}, + {bundle: strings.Replace(loginBundle(), `"PASSWORD-CANARY"`, `""`, 1), want: "site login account password is invalid"}, + } + for _, test := range tests { + adapter := successfulLoginAdapter(t) + var out bytes.Buffer + code, stderr := runSiteLogin(adapter, strings.NewReader(test.bundle), &out, "--credential-bundle-stdin", "fakept") + if code != 1 || adapter.calls != 0 || out.Len() != 0 || stderr != "error: "+test.want+"\n" { + t.Fatalf("bundle=%q code=%d calls=%d stderr=%q", test.bundle, code, adapter.calls, stderr) + } + } +} + +func TestSiteLoginFailuresUseFixedPublicText(t *testing.T) { + nine := 9 + tests := []struct { + err error + want string + }{ + {err: &site.LoginError{Reason: site.LoginTwoFactorRejected, AttemptsRemaining: &nine}, want: "site login stopped: login_two_factor_rejected (the site reports 9 login attempts left before it blocks this IP)"}, + {err: &site.LoginError{Reason: site.LoginTwoFactorRequired}, want: "site login stopped: login_two_factor_required"}, + {err: &site.LoginError{Reason: site.LoginCredentialsRejected}, want: "site login stopped: login_credentials_rejected"}, + {err: &site.LoginError{Reason: site.LoginSessionUnverified}, want: "site login stopped: login_session_unverified"}, + {err: &site.LoginError{Reason: site.LoginRequestFailed}, want: "site login stopped: login_request_failed"}, + {err: fmt.Errorf("TJUPT login request failed: %w", site.ErrAddressBlocked), want: "site login failed: " + site.ErrAddressBlocked.Error()}, + {err: &site.LoginError{Reason: "PASSWORD-CANARY"}, want: "site login failed"}, + {err: fmt.Errorf("post password=PASSWORD-CANARY cookie=SESSION-CANARY"), want: "site login failed"}, + {err: fmt.Errorf("wrapped: %w", site.ErrRateLimited), want: "site login failed: " + site.ErrRateLimited.Error()}, + {err: fmt.Errorf("site request canceled: %w", context.DeadlineExceeded), want: "site login timed out: context deadline exceeded"}, + } + for _, test := range tests { + adapter := successfulLoginAdapter(t) + adapter.err = test.err + var out bytes.Buffer + code, stderr := runSiteLogin(adapter, strings.NewReader(loginBundle(`,"site_totp":"123456"`)), &out, "--credential-bundle-stdin", "fakept") + if code != 1 || out.Len() != 0 || stderr != "error: "+test.want+"\n" { + t.Fatalf("err=%v code=%d stdout=%q stderr=%q", test.err, code, out.String(), stderr) + } + assertNoLoginLeak(t, stderr) + } +} + +func TestSiteLoginRefusesUnsafeStdout(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows file modes do not express group or other access") + } + dir := t.TempDir() + shared, err := os.OpenFile(filepath.Join(dir, "shared-cookie"), os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + t.Fatal(err) + } + defer shared.Close() + if err := shared.Chmod(0o644); err != nil { + t.Fatal(err) + } + device, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + defer device.Close() + for _, stdout := range []*os.File{shared, device} { + adapter := successfulLoginAdapter(t) + reader := &trackingReader{} + code, stderr := runSiteLogin(adapter, reader, stdout, "--credential-bundle-stdin", "fakept") + if code != 2 || reader.read || adapter.calls != 0 || !strings.Contains(stderr, "refusing to write a session cookie") { + t.Fatalf("stdout=%s code=%d read=%v stderr=%q", stdout.Name(), code, reader.read, stderr) + } + } + + private, err := os.OpenFile(filepath.Join(dir, "private-cookie"), os.O_CREATE|os.O_WRONLY, 0o600) + if err != nil { + t.Fatal(err) + } + if err := private.Chmod(0o600); err != nil { + t.Fatal(err) + } + adapter := successfulLoginAdapter(t) + code, stderr := runSiteLogin(adapter, strings.NewReader(loginBundle()), private, "--credential-bundle-stdin", "fakept") + if closeErr := private.Close(); code != 0 || closeErr != nil { + t.Fatalf("private file code=%d stderr=%q close=%v", code, stderr, closeErr) + } + written, err := os.ReadFile(filepath.Join(dir, "private-cookie")) + if err != nil || string(written) != loginSessionCanary+"\n" { + t.Fatalf("private file content mismatch err=%v", err) + } + if session, err := readCredential(bytes.NewReader(written)); err != nil || session.SecretValue() != loginSessionCanary { + t.Fatalf("written cookie is not readable by --cookie-stdin: err=%v", err) + } +} diff --git a/internal/domain/site.go b/internal/domain/site.go index 43e88d4..5508047 100644 --- a/internal/domain/site.go +++ b/internal/domain/site.go @@ -17,6 +17,7 @@ const ( const ( CapabilityAuthCheck Capability = "auth.check" + CapabilityLogin Capability = "auth.login_effectful" CapabilityAccountRead Capability = "account.read" CapabilitySearch Capability = "torrent.search" CapabilityDetail Capability = "torrent.detail" diff --git a/internal/site/descriptor.go b/internal/site/descriptor.go index 2d10766..abb2682 100644 --- a/internal/site/descriptor.go +++ b/internal/site/descriptor.go @@ -84,6 +84,7 @@ var capabilityPorts = map[domain.Capability]func(Adapter) bool{ domain.CapabilityMetafile: func(a Adapter) bool { _, ok := a.(MetafileFetcher); return ok }, domain.CapabilityBonusReview: func(a Adapter) bool { _, ok := a.(BonusReviewReader); return ok }, domain.CapabilityBonusExchange: func(a Adapter) bool { _, ok := a.(BonusExchangeWriter); return ok }, + domain.CapabilityLogin: func(a Adapter) bool { _, ok := a.(SessionLoginer); return ok }, } // KnownCapabilities returns every capability that has a typed port, in a @@ -98,6 +99,7 @@ func KnownCapabilities() []domain.Capability { domain.CapabilityMetafile, domain.CapabilityBonusReview, domain.CapabilityBonusExchange, + domain.CapabilityLogin, } } diff --git a/internal/site/descriptor_test.go b/internal/site/descriptor_test.go index 8e8ed8d..c8e9158 100644 --- a/internal/site/descriptor_test.go +++ b/internal/site/descriptor_test.go @@ -128,6 +128,7 @@ func TestKnownCapabilitiesCoverEveryDomainCapabilityOnce(t *testing.T) { for _, capability := range []domain.Capability{ domain.CapabilityAuthCheck, domain.CapabilityAccountRead, domain.CapabilitySearch, domain.CapabilityDetail, domain.CapabilityMetafile, domain.CapabilityBonusRead, domain.CapabilityBonusReview, domain.CapabilityBonusExchange, + domain.CapabilityLogin, } { if !seen[capability] { t.Fatalf("missing %q", capability) diff --git a/internal/site/httpguard/client.go b/internal/site/httpguard/client.go index af745ca..5dd7098 100644 --- a/internal/site/httpguard/client.go +++ b/internal/site/httpguard/client.go @@ -268,6 +268,108 @@ func (c *Client) GetOnceClassified(ctx context.Context, relativePath string, que // body is intentionally non-replayable, the dedicated transport is fresh and // H1-only, and the only redirect data retained is an allowlisted classifier ID. func (c *Client) PostFormOnce(ctx context.Context, relativePath string, query url.Values, fields []FormField, accept string, maxFields int, maxFormBytes, maxBody, maxHeaderBytes int64, classify RedirectClassifier) (StrictResponse, error) { + return c.postFormOnce(ctx, relativePath, query, fields, accept, maxFields, maxFormBytes, maxBody, maxHeaderBytes, classify, nil) +} + +// SessionCookie is one Set-Cookie value a caller explicitly asked +// PostLoginFormOnce to keep. The value is a secret: it formats as redacted and +// sits behind a pointer, so formatting a struct that holds a SessionCookie +// prints an address rather than the value. +type SessionCookie struct { + Name string + // Expires is zero for a cookie that lasts only for the browser session. + Expires time.Time + value *string +} + +// NewSessionCookie builds a captured cookie, for adapter test doubles. +func NewSessionCookie(name, value string, expires time.Time) SessionCookie { + return SessionCookie{Name: name, Expires: expires, value: &value} +} + +func (cookie SessionCookie) Value() string { + if cookie.value == nil { + return "" + } + return *cookie.value +} + +func (cookie SessionCookie) String() string { return "[REDACTED]" } +func (cookie SessionCookie) GoString() string { return "httpguard.SessionCookie{[REDACTED]}" } + +const ( + maxCapturedCookieNames = 8 + maxCapturedCookieBytes = 8 << 10 +) + +// PostLoginFormOnce is PostFormOnce for a login form. It also returns the +// Set-Cookie values named in cookieNames, and no others. A cookie the response +// deletes or expires is not returned, and two live values for one name fail +// the request rather than picking one. Nothing else from the response headers +// crosses this boundary. +func (c *Client) PostLoginFormOnce(ctx context.Context, relativePath string, fields []FormField, accept string, maxFields int, maxFormBytes, maxBody, maxHeaderBytes int64, classify RedirectClassifier, cookieNames []string) (StrictResponse, []SessionCookie, error) { + if len(cookieNames) == 0 || len(cookieNames) > maxCapturedCookieNames { + return StrictResponse{}, nil, fmt.Errorf("site session cookie names are invalid") + } + wanted := make(map[string]bool, len(cookieNames)) + for _, name := range cookieNames { + if !cookieToken(name) || wanted[name] { + return StrictResponse{}, nil, fmt.Errorf("site session cookie names are invalid") + } + wanted[name] = true + } + var captured []SessionCookie + capture := func(resp *http.Response) error { + now := time.Now() + byName := make(map[string]SessionCookie, len(wanted)) + for _, cookie := range resp.Cookies() { + if !wanted[cookie.Name] { + continue + } + expires := cookie.Expires + if cookie.MaxAge > 0 { + expires = now.Add(time.Duration(cookie.MaxAge) * time.Second) + } + if cookie.MaxAge < 0 || (!expires.IsZero() && !expires.After(now)) || cookie.Value == "" || cookie.Value == "deleted" { + continue + } + if len(cookie.Value) > maxCapturedCookieBytes || !asciiHeaderValue(cookie.Value) || strings.ContainsAny(cookie.Value, " ;,") { + return fmt.Errorf("site session cookie was invalid") + } + if previous, seen := byName[cookie.Name]; seen && previous.Value() != cookie.Value { + return fmt.Errorf("site session cookie was ambiguous") + } + value := cookie.Value + byName[cookie.Name] = SessionCookie{Name: cookie.Name, Expires: expires.UTC(), value: &value} + } + for _, name := range cookieNames { + if cookie, ok := byName[name]; ok { + captured = append(captured, cookie) + } + } + return nil + } + response, err := c.postFormOnce(ctx, relativePath, nil, fields, accept, maxFields, maxFormBytes, maxBody, maxHeaderBytes, classify, capture) + if err != nil { + return response, nil, err + } + return response, captured, nil +} + +func cookieToken(name string) bool { + if name == "" || len(name) > 64 { + return false + } + for i := 0; i < len(name); i++ { + c := name[i] + if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '-') { + return false + } + } + return true +} + +func (c *Client) postFormOnce(ctx context.Context, relativePath string, query url.Values, fields []FormField, accept string, maxFields int, maxFormBytes, maxBody, maxHeaderBytes int64, classify RedirectClassifier, capture func(*http.Response) error) (StrictResponse, error) { var result StrictResponse if maxBody <= 0 || maxBody > 32<<20 || maxHeaderBytes <= 0 || maxHeaderBytes > hardMaxResponseHeaders { return result, fmt.Errorf("site response budget is invalid") @@ -307,7 +409,7 @@ func (c *Client) PostFormOnce(ctx context.Context, relativePath string, query ur req.Header.Set("User-Agent", "ptctl/0.1 (+https://github.com/tonycoder-hub/ptctl; explicit-effect-client)") c.applyCredential(req) req.Close = true - return c.roundTrip(ctx, req, result, maxBody, maxHeaderBytes, classify) + return c.roundTripCapturing(ctx, req, result, maxBody, maxHeaderBytes, classify, capture) } // PostReadOnce performs one non-following, non-retrying POST for APIs that @@ -367,6 +469,13 @@ func (c *Client) applyCredential(req *http.Request) { // roundTrip sends req exactly once and applies the shared response checks in // a fixed order. Only callers that accept redirects pass a classifier. func (c *Client) roundTrip(ctx context.Context, req *http.Request, result StrictResponse, maxBody, maxHeaderBytes int64, classify RedirectClassifier) (StrictResponse, error) { + return c.roundTripCapturing(ctx, req, result, maxBody, maxHeaderBytes, classify, nil) +} + +// roundTripCapturing is roundTrip with an optional hook that sees the response +// headers after they pass the shared checks and before the body is read. Only +// PostLoginFormOnce passes one. +func (c *Client) roundTripCapturing(ctx context.Context, req *http.Request, result StrictResponse, maxBody, maxHeaderBytes int64, classify RedirectClassifier, capture func(*http.Response) error) (StrictResponse, error) { if c.strictHTTP == nil { return result, fmt.Errorf("strict site transport is unavailable") } @@ -419,6 +528,12 @@ func (c *Client) roundTrip(ctx context.Context, req *http.Request, result Strict } } } + if capture != nil { + if err := capture(resp); err != nil { + result.ObservedAtEnd = time.Now().UTC() + return result, err + } + } if resp.ContentLength > maxBody { result.ObservedAtEnd = time.Now().UTC() return result, fmt.Errorf("site response exceeded the configured budget") diff --git a/internal/site/httpguard/login_test.go b/internal/site/httpguard/login_test.go new file mode 100644 index 0000000..5c0c268 --- /dev/null +++ b/internal/site/httpguard/login_test.go @@ -0,0 +1,114 @@ +package httpguard + +import ( + "context" + "fmt" + "io" + "net/http" + "strings" + "testing" + "time" +) + +func loginResponse(cookies ...string) *http.Response { + return &http.Response{ + StatusCode: http.StatusFound, + Header: http.Header{"Location": {"/index.php"}, "Content-Type": {"text/html; charset=utf-8"}, "Set-Cookie": cookies}, + Body: io.NopCloser(strings.NewReader("")), + ContentLength: 0, + } +} + +func TestPostLoginFormOnceCapturesOnlyRequestedLiveCookies(t *testing.T) { + future := time.Now().Add(7 * 24 * time.Hour).UTC().Format(http.TimeFormat) + calls := 0 + client := strictTestClient(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 != "/takelogin.php" || request.URL.RawQuery != "" || + request.Header.Get("Cookie") != "" || string(body) != "username=CANARY-USER&password=PASSWORD-CANARY" { + t.Fatalf("unexpected login POST: %#v body=%q", request, body) + } + return loginResponse( + "tracker=OTHER-COOKIE-CANARY; Path=/", + "access_token=SESSION-CANARY.part-2_x; Domain=.example.test; Path=/; Expires="+future, + ), nil + }), "") + response, cookies, err := client.PostLoginFormOnce(context.Background(), "takelogin.php", + []FormField{{Name: "username", Value: "CANARY-USER"}, {Name: "password", Value: "PASSWORD-CANARY"}}, + "text/html", 4, 1024, 1024, 1024, nil, []string{"access_token"}) + if err != nil || calls != 1 || response.StatusCode != http.StatusFound || len(cookies) != 1 { + t.Fatalf("response=%#v cookies=%d err=%v calls=%d", response, len(cookies), err, calls) + } + cookie := cookies[0] + if cookie.Name != "access_token" || cookie.Value() != "SESSION-CANARY.part-2_x" || cookie.Expires.IsZero() || cookie.Expires.Location() != time.UTC { + t.Fatalf("cookie name=%q expires=%v", cookie.Name, cookie.Expires) + } + for _, rendered := range []string{fmt.Sprint(cookie), fmt.Sprintf("%v %+v %#v %s", cookie, cookie, cookie, cookie), fmt.Sprintf("%v %+v", cookies, struct{ C SessionCookie }{cookie})} { + if strings.Contains(rendered, "SESSION-CANARY") { + t.Fatalf("session cookie leaked through formatting: %q", rendered) + } + } +} + +func TestPostLoginFormOnceIgnoresDeletedAndExpiredCookies(t *testing.T) { + past := time.Now().Add(-time.Hour).UTC().Format(http.TimeFormat) + for _, header := range []string{ + "access_token=deleted; Path=/", + "access_token=; Path=/", + "access_token=STALE-CANARY; Max-Age=0", + "access_token=STALE-CANARY; Expires=" + past, + } { + client := strictTestClient(t, roundTripFunc(func(*http.Request) (*http.Response, error) { + return loginResponse(header), nil + }), "") + _, cookies, err := client.PostLoginFormOnce(context.Background(), "takelogin.php", []FormField{{Name: "username", Value: "u"}}, + "text/html", 4, 1024, 1024, 1024, nil, []string{"access_token"}) + if err != nil || len(cookies) != 0 { + t.Fatalf("%q: cookies=%d err=%v", header, len(cookies), err) + } + } +} + +func TestPostLoginFormOnceFailsClosedOnAmbiguousOrInvalidCookies(t *testing.T) { + for _, headers := range [][]string{ + {"access_token=FIRST-CANARY", "access_token=SECOND-CANARY"}, + {"access_token=" + strings.Repeat("A", maxCapturedCookieBytes+1)}, + {`access_token="QUOTED CANARY"`}, + } { + client := strictTestClient(t, roundTripFunc(func(*http.Request) (*http.Response, error) { + return loginResponse(headers...), nil + }), "") + _, cookies, err := client.PostLoginFormOnce(context.Background(), "takelogin.php", []FormField{{Name: "username", Value: "u"}}, + "text/html", 4, 1024, 1024, 1024, nil, []string{"access_token"}) + if err == nil || cookies != nil || client.RequestsMade() != 1 || strings.Contains(err.Error(), "CANARY") { + t.Fatalf("%q: cookies=%d err=%v", headers, len(cookies), err) + } + } + client := strictTestClient(t, roundTripFunc(func(*http.Request) (*http.Response, error) { + return loginResponse("access_token=SAME-CANARY; Path=/", "access_token=SAME-CANARY; Path=/"), nil + }), "") + if _, cookies, err := client.PostLoginFormOnce(context.Background(), "takelogin.php", []FormField{{Name: "username", Value: "u"}}, + "text/html", 4, 1024, 1024, 1024, nil, []string{"access_token"}); err != nil || len(cookies) != 1 { + t.Fatalf("repeated identical cookie: cookies=%d err=%v", len(cookies), err) + } +} + +func TestPostLoginFormOnceRejectsInvalidCookieNamesBeforeSending(t *testing.T) { + client := strictTestClient(t, roundTripFunc(func(*http.Request) (*http.Response, error) { + t.Fatal("request sent with invalid cookie names") + return nil, nil + }), "") + for _, names := range [][]string{nil, {""}, {"a b"}, {"a;b"}, {"dup", "dup"}, {"1", "2", "3", "4", "5", "6", "7", "8", "9"}} { + if _, _, err := client.PostLoginFormOnce(context.Background(), "takelogin.php", []FormField{{Name: "username", Value: "u"}}, + "text/html", 4, 1024, 1024, 1024, nil, names); err == nil { + t.Fatalf("names %q accepted", names) + } + } + if client.RequestsMade() != 0 { + t.Fatalf("requests=%d", client.RequestsMade()) + } +} diff --git a/internal/site/login.go b/internal/site/login.go new file mode 100644 index 0000000..60e16dc --- /dev/null +++ b/internal/site/login.go @@ -0,0 +1,119 @@ +package site + +import ( + "context" + "fmt" + "strings" + "time" + "unicode/utf8" +) + +// Login stop reasons are public, secret-free codes. An adapter reports one of +// them through a *LoginError when the site answered with a page it recognizes, +// or when the login request itself did not complete; every other failure +// keeps the generic login failure line. +const ( + LoginCredentialsRejected = "login_credentials_rejected" + LoginTwoFactorRequired = "login_two_factor_required" + LoginTwoFactorRejected = "login_two_factor_rejected" + LoginResponseUnrecognized = "login_response_unrecognized" + LoginSessionUnverified = "login_session_unverified" + // LoginRequestFailed means the login request failed in transport or its + // response was rejected before classification. The site may still have + // counted the attempt. + LoginRequestFailed = "login_request_failed" +) + +// LoginError reports a recognized login refusal by its public stop reason. +// AttemptsRemaining is the site's own count of failed logins left before it +// blocks the client, when the response stated one. +type LoginError struct { + Reason string + AttemptsRemaining *int +} + +func (err *LoginError) Error() string { return "site login stopped: " + err.Reason } + +// LoginCredentials are the account username, password, and optional one-time +// second-factor code for one login. They are held only in process memory and +// format as redacted. +type LoginCredentials struct { + username string + password AccountPassword + oneTimeCode *string +} + +// NewLoginCredentials validates the shape of one login. An empty oneTimeCode +// means none was supplied; a supplied code is 4 to 10 ASCII digits. +func NewLoginCredentials(username string, password AccountPassword, oneTimeCode string) (LoginCredentials, error) { + if username == "" || username != strings.TrimSpace(username) || len(username) > 256 || !utf8.ValidString(username) { + return LoginCredentials{}, fmt.Errorf("login username is invalid") + } + for _, r := range username { + if r < 0x20 || r == 0x7f { + return LoginCredentials{}, fmt.Errorf("login username is invalid") + } + } + if password.SecretValue() == "" { + return LoginCredentials{}, fmt.Errorf("login password is invalid") + } + credentials := LoginCredentials{username: username, password: password} + if oneTimeCode != "" { + if len(oneTimeCode) < 4 || len(oneTimeCode) > 10 || strings.Trim(oneTimeCode, "0123456789") != "" { + return LoginCredentials{}, fmt.Errorf("login one-time code is invalid") + } + credentials.oneTimeCode = &oneTimeCode + } + return credentials, nil +} + +func (credentials LoginCredentials) Username() string { return credentials.username } +func (credentials LoginCredentials) Password() AccountPassword { return credentials.password } + +// OneTimeCode returns the second-factor code and whether one was supplied. +func (credentials LoginCredentials) OneTimeCode() (string, bool) { + if credentials.oneTimeCode == nil { + return "", false + } + return *credentials.oneTimeCode, true +} + +func (credentials LoginCredentials) String() string { return "[REDACTED]" } +func (credentials LoginCredentials) GoString() string { + return "site.LoginCredentials{[REDACTED]}" +} + +// LoginConfig lists the session lengths, in days, a site's login form offers. +// The CLI validates --session-days against it before reading stdin. +type LoginConfig struct { + SessionDays []int + DefaultSessionDays int +} + +// Allows reports whether days is one of the offered session lengths. +func (config LoginConfig) Allows(days int) bool { + for _, offered := range config.SessionDays { + if offered == days { + return true + } + } + return false +} + +// LoginResult is a verified login. Session is the new cookie credential and is +// never serialized; the remaining fields are safe to report. +type LoginResult struct { + Session Credential + Username string + ExpiresAt *time.Time + RequestsAttempted int +} + +// SessionLoginer signs in with an account password and returns a new session +// credential that the site has confirmed with an authenticated read. It sends +// a fixed, small number of requests and never retries, because failed logins +// count toward the site's lockout. +type SessionLoginer interface { + LoginConfig() LoginConfig + Login(context.Context, LoginCredentials, int) (LoginResult, error) +} diff --git a/internal/site/login_test.go b/internal/site/login_test.go new file mode 100644 index 0000000..250dbe7 --- /dev/null +++ b/internal/site/login_test.go @@ -0,0 +1,74 @@ +package site_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/tonycoder-hub/ptctl/internal/site" +) + +func TestNewLoginCredentialsValidatesShapeAndRedacts(t *testing.T) { + password, err := site.NewAccountPassword("PASSWORD-CANARY") + if err != nil { + t.Fatal(err) + } + credentials, err := site.NewLoginCredentials("CanaryUser", password, "987654") + if err != nil { + t.Fatal(err) + } + code, ok := credentials.OneTimeCode() + if credentials.Username() != "CanaryUser" || credentials.Password().SecretValue() != "PASSWORD-CANARY" || !ok || code != "987654" { + t.Fatal("login credential accessors drifted") + } + wrapped := struct{ Credentials site.LoginCredentials }{credentials} + for _, rendered := range []string{ + fmt.Sprintf("%v %+v %#v %s", credentials, credentials, credentials, credentials), + fmt.Sprintf("%v %+v %#v", wrapped, wrapped, wrapped), + } { + if strings.Contains(rendered, "PASSWORD-CANARY") || strings.Contains(rendered, "987654") { + t.Fatalf("login credentials leaked: %s", rendered) + } + } + + without, err := site.NewLoginCredentials("CanaryUser", password, "") + if err != nil { + t.Fatal(err) + } + if code, ok := without.OneTimeCode(); ok || code != "" { + t.Fatalf("absent code reported as %q", code) + } + + for _, test := range []struct { + username string + password site.AccountPassword + code string + }{ + {username: "", password: password}, + {username: " CanaryUser", password: password}, + {username: "Canary\tUser", password: password}, + {username: strings.Repeat("u", 257), password: password}, + {username: "\xff", password: password}, + {username: "CanaryUser"}, + {username: "CanaryUser", password: password, code: "123"}, + {username: "CanaryUser", password: password, code: "12345678901"}, + {username: "CanaryUser", password: password, code: "12 456"}, + {username: "CanaryUser", password: password, code: "123456"}, + } { + if _, err := site.NewLoginCredentials(test.username, test.password, test.code); err == nil { + t.Fatalf("username=%q code=%q accepted", test.username, test.code) + } else if strings.Contains(err.Error(), test.code) && test.code != "" { + t.Fatalf("error echoed the code: %v", err) + } + } +} + +func TestLoginConfigAllowsOnlyOfferedDays(t *testing.T) { + config := site.LoginConfig{SessionDays: []int{1, 7}, DefaultSessionDays: 7} + if !config.Allows(1) || !config.Allows(7) || config.Allows(0) || config.Allows(14) || (site.LoginConfig{}).Allows(0) { + t.Fatal("LoginConfig.Allows drifted") + } + if got := (&site.LoginError{Reason: site.LoginTwoFactorRequired}).Error(); got != "site login stopped: login_two_factor_required" { + t.Fatalf("LoginError text=%q", got) + } +} diff --git a/internal/site/sitetest/sitetest.go b/internal/site/sitetest/sitetest.go index 9b39175..149f25a 100644 --- a/internal/site/sitetest/sitetest.go +++ b/internal/site/sitetest/sitetest.go @@ -62,6 +62,9 @@ func TestAdapter(t *testing.T, adapter site.Adapter, samples Samples) { } }) } + if loginer, ok := adapter.(site.SessionLoginer); ok && descriptor.Supports(domain.CapabilityLogin) { + t.Run(string(domain.CapabilityLogin), func(t *testing.T) { testLogin(t, loginer) }) + } for _, port := range configuredPorts(adapter, descriptor, samples) { t.Run(string(port.capability), func(t *testing.T) { if descriptor.Supports(port.capability) { @@ -73,6 +76,38 @@ func TestAdapter(t *testing.T, adapter site.Adapter, samples Samples) { } } +// testLogin checks the login config and that a done context stops a login +// before its first request. The credentials are synthetic. +func testLogin(t *testing.T, loginer site.SessionLoginer) { + config := loginer.LoginConfig() + seen := map[int]bool{} + for _, days := range config.SessionDays { + if days <= 0 || seen[days] { + t.Fatalf("login session days %v must be positive and unique", config.SessionDays) + } + seen[days] = true + } + if !config.Allows(config.DefaultSessionDays) { + t.Fatalf("default login session days %d is not offered in %v", config.DefaultSessionDays, config.SessionDays) + } + config.SessionDays[0] = -1 + if loginer.LoginConfig().Allows(-1) { + t.Fatal("LoginConfig shares its session days with callers") + } + password, err := site.NewAccountPassword("sitetest-PASSWORD-CANARY") + if err != nil { + t.Fatal(err) + } + credentials, err := site.NewLoginCredentials("sitetest-user", password, "") + if err != nil { + t.Fatal(err) + } + result, err := loginer.Login(canceledContext(), credentials, loginer.LoginConfig().DefaultSessionDays) + if !errors.Is(err, context.Canceled) || result.Session != (site.Credential{}) || result.RequestsAttempted != 0 { + t.Fatalf("canceled login err=%v requests=%d, want context.Canceled before any request", err, result.RequestsAttempted) + } +} + func testDescriptor(t *testing.T, adapter site.Adapter) { first := cloneDescriptor(adapter.Descriptor()) if err := site.ValidateDescriptor(first); err != nil { diff --git a/internal/site/tjupt/adapter.go b/internal/site/tjupt/adapter.go index 0e9d367..d8bf5f0 100644 --- a/internal/site/tjupt/adapter.go +++ b/internal/site/tjupt/adapter.go @@ -28,6 +28,8 @@ const ( type Adapter struct { baseURL string newClient guardedClientFactory + // sleep replaces the real wait between dependent requests in tests. + sleep func(context.Context, time.Duration) error } type guardedClient interface { @@ -106,7 +108,7 @@ func (a *Adapter) Descriptor() domain.SiteDescriptor { domain.CapabilityBonusRead, } if a.productionOrigin() { - capabilities = append(capabilities, domain.CapabilityDetail, domain.CapabilityMetafile, domain.CapabilityBonusReview, domain.CapabilityBonusExchange) + capabilities = append(capabilities, domain.CapabilityDetail, domain.CapabilityMetafile, domain.CapabilityBonusReview, domain.CapabilityBonusExchange, domain.CapabilityLogin) } return domain.SiteDescriptor{ ID: SiteID, diff --git a/internal/site/tjupt/login.go b/internal/site/tjupt/login.go new file mode 100644 index 0000000..1b44394 --- /dev/null +++ b/internal/site/tjupt/login.go @@ -0,0 +1,202 @@ +package tjupt + +import ( + "bytes" + "context" + "errors" + "fmt" + "regexp" + "strconv" + "strings" + "time" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" + "github.com/tonycoder-hub/ptctl/internal/site/httpguard" +) + +// TJUPT's login.php posts username, password, and a session length ("logout", +// in days) to takelogin.php. An account with two-step verification gets a +// verifyform page back that re-posts the same fields plus verify_code, so one +// POST that already carries verify_code completes the login. A successful +// login sets a single access_token cookie that lasts the chosen number of days. +const ( + loginPath = "takelogin.php" + loginSessionCookie = "access_token" + loginAccept = "text/html" + loginDefaultSessionDays = 7 + loginMaxFormFields = 4 + loginMaxFormBytes = 4 << 10 + loginMaxResponseBytes = 1 << 20 + loginMaxResponseHeaderBytes = 32 << 10 + // loginVerifyDelay spaces the verification read after the login POST. + loginVerifyDelay = 2 * time.Second +) + +var loginSessionDays = []int{1, 7, 14, 30, 90} + +var ( + twoFactorForm = regexp.MustCompile(`(?is)]*name\s*=\s*["']?verifyform["']?`) + twoFactorField = regexp.MustCompile(`(?is)]*name\s*=\s*["']?verify_code["']?`) + loginFailedMarker = regexp.MustCompile(`(?i)(登录失败|登錄失敗|login failed)`) + attemptsRemaining = regexp.MustCompile(`你还有\s*\[?\s*([0-9]{1,3})\s*\]?\s*次尝试机会`) +) + +type guardedLoginClient interface { + guardedClient + PostLoginFormOnce(context.Context, string, []httpguard.FormField, string, int, int64, int64, int64, httpguard.RedirectClassifier, []string) (httpguard.StrictResponse, []httpguard.SessionCookie, error) +} + +// The production client must keep the login port, or Login fails closed. +var _ guardedLoginClient = loginRedirectClient{} + +func (a *Adapter) LoginConfig() site.LoginConfig { + return site.LoginConfig{SessionDays: append([]int(nil), loginSessionDays...), DefaultSessionDays: loginDefaultSessionDays} +} + +// Login sends exactly one login POST and, only when TJUPT issues a session +// cookie, one authenticated read that must name the same account. It never +// retries: TJUPT blocks the client IP after ten failed attempts. The login +// response body is discarded after classification because TJUPT's two-step +// page echoes the password back in a hidden field. +func (a *Adapter) Login(ctx context.Context, credentials site.LoginCredentials, sessionDays int) (site.LoginResult, error) { + var result site.LoginResult + if !a.productionOrigin() { + return result, fmt.Errorf("TJUPT login requires the default origin") + } + if !a.LoginConfig().Allows(sessionDays) { + return result, fmt.Errorf("TJUPT login session length is not offered") + } + username, password := credentials.Username(), credentials.Password().SecretValue() + if username == "" || password == "" { + return result, fmt.Errorf("TJUPT login credentials are incomplete") + } + code, hasCode := credentials.OneTimeCode() + if hasCode && (len(code) != 6 || strings.Trim(code, "0123456789") != "") { + return result, fmt.Errorf("TJUPT two-step code must be 6 digits") + } + if err := ctx.Err(); err != nil { + return result, err + } + + rawClient, err := a.clientFactory()(a.baseURL, "", 2*time.Second) + if err != nil { + return result, err + } + client, ok := rawClient.(guardedLoginClient) + if !ok { + _ = rawClient.Close() + return result, fmt.Errorf("open TJUPT login client failed") + } + fields := []httpguard.FormField{ + {Name: "username", Value: username}, + {Name: "password", Value: password}, + {Name: "logout", Value: strconv.Itoa(sessionDays)}, + } + if hasCode { + fields = append(fields, httpguard.FormField{Name: "verify_code", Value: code}) + } + // The redirect after a successful login is neither followed nor needed: + // the cookie and the verification read decide the outcome. + response, cookies, postErr := client.PostLoginFormOnce(ctx, loginPath, fields, loginAccept, loginMaxFormFields, loginMaxFormBytes, loginMaxResponseBytes, loginMaxResponseHeaderBytes, nil, []string{loginSessionCookie}) + result.RequestsAttempted = client.RequestsMade() + _ = client.Close() + outcome := classifyLoginResponse(response, len(cookies) == 1) + clear(response.Body) + if postErr != nil { + switch { + case errors.Is(postErr, context.Canceled) || errors.Is(postErr, context.DeadlineExceeded): + return result, postErr + case errors.Is(postErr, httpguard.ErrBlockedAddress): + return result, fmt.Errorf("TJUPT login request failed: %w", site.ErrAddressBlocked) + } + return result, &site.LoginError{Reason: site.LoginRequestFailed} + } + switch outcome.reason { + case "": + case site.LoginTwoFactorRequired: + if hasCode { + outcome.reason = site.LoginTwoFactorRejected + } + return result, &site.LoginError{Reason: outcome.reason, AttemptsRemaining: outcome.attemptsRemaining} + default: + return result, &site.LoginError{Reason: outcome.reason, AttemptsRemaining: outcome.attemptsRemaining} + } + + cookie := cookies[0] + session, err := site.NewCookieCredential(loginSessionCookie + "=" + cookie.Value()) + if err != nil { + return result, &site.LoginError{Reason: site.LoginResponseUnrecognized} + } + if err := a.pause(ctx, loginVerifyDelay); err != nil { + return result, err + } + result.RequestsAttempted++ + status, err := a.CheckSession(ctx, session) + if err != nil || status.State != domain.AuthenticationAuthenticated || !strings.EqualFold(status.Username, username) { + return result, &site.LoginError{Reason: site.LoginSessionUnverified} + } + result.Session = session + result.Username = status.Username + if !cookie.Expires.IsZero() { + expires := cookie.Expires.UTC() + result.ExpiresAt = &expires + } + return result, nil +} + +type loginOutcome struct { + // reason is empty when TJUPT issued a session cookie worth verifying. + reason string + attemptsRemaining *int +} + +// classifyLoginResponse recognizes the two-step page and the failure page +// before trusting an issued cookie, so a page that both sets a cookie and +// refuses the login is never treated as a login. +func classifyLoginResponse(response httpguard.StrictResponse, cookieIssued bool) loginOutcome { + body := response.Body + outcome := loginOutcome{attemptsRemaining: parseAttemptsRemaining(body)} + switch { + case response.MediaType == "text/html" && twoFactorForm.Match(body) && twoFactorField.Match(body): + outcome.reason = site.LoginTwoFactorRequired + case response.MediaType == "text/html" && response.StatusCode == 200 && !cookieIssued && loginFailedMarker.Match(body): + outcome.reason = site.LoginCredentialsRejected + case cookieIssued && response.StatusCode >= 200 && response.StatusCode <= 399: + outcome.attemptsRemaining = nil + default: + outcome.reason = site.LoginResponseUnrecognized + outcome.attemptsRemaining = nil + } + return outcome +} + +func parseAttemptsRemaining(body []byte) *int { + if len(body) == 0 || !bytes.Contains(body, []byte("次尝试机会")) { + return nil + } + text := spacePattern.ReplaceAllString(tagPattern.ReplaceAllString(string(body), " "), " ") + match := attemptsRemaining.FindStringSubmatch(text) + if match == nil { + return nil + } + remaining, err := strconv.Atoi(match[1]) + if err != nil { + return nil + } + return &remaining +} + +func (a *Adapter) pause(ctx context.Context, delay time.Duration) error { + if a.sleep != nil { + return a.sleep(ctx, delay) + } + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return nil + } +} diff --git a/internal/site/tjupt/login_test.go b/internal/site/tjupt/login_test.go new file mode 100644 index 0000000..72d68f2 --- /dev/null +++ b/internal/site/tjupt/login_test.go @@ -0,0 +1,361 @@ +package tjupt + +import ( + "context" + "errors" + "fmt" + "net/url" + "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" +) + +const ( + loginTestUser = "CanaryUser" + loginTestPassword = "PASSWORD-CANARY" + loginTestSession = "SESSION-CANARY.payload.sig" +) + +type loginFakeClient struct { + response httpguard.StrictResponse + cookies []httpguard.SessionCookie + err error + calls int + closeCalls int + path string + fields []httpguard.FormField + accept string + cookieNames []string +} + +func (*loginFakeClient) Get(context.Context, string, url.Values) ([]byte, *url.URL, error) { + panic("unexpected GET on the login client") +} + +func (*loginFakeClient) GetOnce(context.Context, string, url.Values, string, int64, int64) (httpguard.StrictResponse, error) { + panic("unexpected strict GET on the login client") +} + +func (client *loginFakeClient) PostLoginFormOnce(_ context.Context, path string, fields []httpguard.FormField, accept string, _ int, _, _, _ int64, _ httpguard.RedirectClassifier, cookieNames []string) (httpguard.StrictResponse, []httpguard.SessionCookie, error) { + client.calls++ + client.path = path + client.fields = append([]httpguard.FormField(nil), fields...) + client.accept = accept + client.cookieNames = append([]string(nil), cookieNames...) + return client.response, client.cookies, client.err +} + +func (client *loginFakeClient) RequestsMade() int { return client.calls } +func (client *loginFakeClient) Close() error { + client.closeCalls++ + return nil +} + +func twoFactorPage() []byte { + return []byte(`北洋园PT :: 两步验证 - Powered by NexusPHP +

登录两步验证

+
+ + + +请输入6位数字验证码 +
+

连续 10 次错误尝试会导致你的IP地址被禁用,你还有 [9] 次尝试机会

`) +} + +func loginFailedPage() []byte { + return []byte(`北洋园PT :: 登录失败

登录失败!

+

用户名或密码不正确。你还有 [8] 次尝试机会

`) +} + +func htmlLoginResponse(status int, body []byte) httpguard.StrictResponse { + return httpguard.StrictResponse{StatusCode: status, MediaType: "text/html", Body: body, ResponseBytesKnown: true, ResponseBytesRead: int64(len(body))} +} + +func issuedLoginClient(expires time.Time) *loginFakeClient { + return &loginFakeClient{ + response: htmlLoginResponse(302, nil), + cookies: []httpguard.SessionCookie{httpguard.NewSessionCookie(loginSessionCookie, loginTestSession, expires)}, + } +} + +type loginHarness struct { + adapter *Adapter + login *loginFakeClient + verify *accountFakeClient + cookies []string + sleeps []time.Duration + factoryErr error +} + +func newLoginHarness(t *testing.T, login *loginFakeClient, verifyPage []byte) *loginHarness { + t.Helper() + pageURL, err := url.Parse("https://www.tjupt.org/mybonus.php") + if err != nil { + t.Fatal(err) + } + harness := &loginHarness{adapter: New(""), login: login, verify: &accountFakeClient{body: verifyPage, finalURL: pageURL}} + harness.adapter.newClient = func(baseURL, cookie string, interval time.Duration) (guardedClient, error) { + if baseURL != DefaultBaseURL || interval != 2*time.Second { + t.Fatalf("client base=%q interval=%v", baseURL, interval) + } + harness.cookies = append(harness.cookies, cookie) + if harness.factoryErr != nil { + return nil, harness.factoryErr + } + if cookie == "" { + return harness.login, nil + } + return harness.verify, nil + } + harness.adapter.sleep = func(_ context.Context, delay time.Duration) error { + harness.sleeps = append(harness.sleeps, delay) + return nil + } + return harness +} + +func loginCredentials(t *testing.T, code string) site.LoginCredentials { + t.Helper() + password, err := site.NewAccountPassword(loginTestPassword) + if err != nil { + t.Fatal(err) + } + credentials, err := site.NewLoginCredentials(loginTestUser, password, code) + if err != nil { + t.Fatal(err) + } + return credentials +} + +func assertNoLoginSecrets(t *testing.T, values ...any) { + t.Helper() + for _, value := range values { + rendered := fmt.Sprintf("%v %+v %#v", value, value, value) + for _, secret := range []string{loginTestPassword, "SESSION-CANARY", "123456"} { + if strings.Contains(rendered, secret) { + t.Fatalf("secret %q leaked: %s", secret, rendered) + } + } + } +} + +func TestLoginCapabilityOnlyForTrustedDefaultOrigin(t *testing.T) { + adapter := New("") + if !adapter.Descriptor().Supports(domain.CapabilityLogin) || !site.ImplementsCapability(adapter, domain.CapabilityLogin) { + t.Fatal("default TJUPT adapter did not declare and implement auth.login_effectful") + } + config := adapter.LoginConfig() + if fmt.Sprint(config.SessionDays) != "[1 7 14 30 90]" || config.DefaultSessionDays != 7 || !config.Allows(7) || config.Allows(0) || config.Allows(365) { + t.Fatalf("config=%#v", config) + } + config.SessionDays[0] = 365 + if adapter.LoginConfig().Allows(365) { + t.Fatal("LoginConfig returned shared session days") + } + custom := New("https://www.tjupt.org") + if custom.Descriptor().Supports(domain.CapabilityLogin) { + t.Fatal("non-exact origin declared login") + } + custom.newClient = func(string, string, time.Duration) (guardedClient, error) { + t.Fatal("custom origin opened a login client") + return nil, nil + } + if _, err := custom.Login(context.Background(), loginCredentials(t, ""), 7); err == nil { + t.Fatal("custom origin attempted a login") + } +} + +func TestLoginWithTwoStepCodeVerifiesTheIssuedSession(t *testing.T) { + expires := time.Date(2026, 10, 22, 15, 4, 33, 0, time.UTC) + harness := newLoginHarness(t, issuedLoginClient(expires), accountPage(loginTestUser, "1,234.5")) + result, err := harness.adapter.Login(context.Background(), loginCredentials(t, "123456"), 30) + if err != nil { + t.Fatal(err) + } + login := harness.login + if login.calls != 1 || login.closeCalls != 1 || login.path != loginPath || login.accept != "text/html" || fmt.Sprint(login.cookieNames) != "[access_token]" { + t.Fatalf("login client calls=%d closes=%d path=%q accept=%q names=%q", login.calls, login.closeCalls, login.path, login.accept, login.cookieNames) + } + wantFields := []httpguard.FormField{{Name: "username", Value: loginTestUser}, {Name: "password", Value: loginTestPassword}, {Name: "logout", Value: "30"}, {Name: "verify_code", Value: "123456"}} + if fmt.Sprint(login.fields) != fmt.Sprint(wantFields) { + t.Fatal("login form fields drifted") + } + if fmt.Sprint(harness.cookies) != fmt.Sprint([]string{"", "access_token=" + loginTestSession}) || harness.verify.requests != 1 || harness.verify.path != bonusPagePath { + t.Fatalf("verification clients=%d verify requests=%d path=%q", len(harness.cookies), harness.verify.requests, harness.verify.path) + } + if fmt.Sprint(harness.sleeps) != "[2s]" { + t.Fatalf("sleeps=%v", harness.sleeps) + } + if result.Session.Method() != domain.AuthMethodCookieHeader || result.Session.SecretValue() != "access_token="+loginTestSession || + result.Username != loginTestUser || result.ExpiresAt == nil || !result.ExpiresAt.Equal(expires) || result.RequestsAttempted != 2 { + t.Fatalf("result username=%q expires=%v requests=%d", result.Username, result.ExpiresAt, result.RequestsAttempted) + } + assertNoLoginSecrets(t, result) +} + +func TestLoginWithoutTwoStepFieldSendsThreeFields(t *testing.T) { + harness := newLoginHarness(t, issuedLoginClient(time.Time{}), accountPage(loginTestUser, "1")) + result, err := harness.adapter.Login(context.Background(), loginCredentials(t, ""), 7) + if err != nil || len(harness.login.fields) != 3 || harness.login.fields[2] != (httpguard.FormField{Name: "logout", Value: "7"}) || result.ExpiresAt != nil { + t.Fatalf("fields=%d expires=%v err=%v", len(harness.login.fields), result.ExpiresAt, err) + } +} + +func TestLoginStopsOnRecognizedRefusalsWithoutVerifying(t *testing.T) { + nine, eight := 9, 8 + tests := []struct { + name string + code string + response httpguard.StrictResponse + cookies []httpguard.SessionCookie + reason string + remaining *int + }{ + {name: "two-step required", response: htmlLoginResponse(200, twoFactorPage()), reason: site.LoginTwoFactorRequired, remaining: &nine}, + {name: "two-step code rejected", code: "123456", response: htmlLoginResponse(200, twoFactorPage()), reason: site.LoginTwoFactorRejected, remaining: &nine}, + {name: "two-step page with a cookie", code: "123456", response: htmlLoginResponse(200, twoFactorPage()), + cookies: []httpguard.SessionCookie{httpguard.NewSessionCookie(loginSessionCookie, loginTestSession, time.Time{})}, reason: site.LoginTwoFactorRejected, remaining: &nine}, + {name: "password rejected", response: htmlLoginResponse(200, loginFailedPage()), reason: site.LoginCredentialsRejected, remaining: &eight}, + {name: "unknown page", response: htmlLoginResponse(200, []byte(`北洋园PT

你还有 [3] 次尝试机会

`)), reason: site.LoginResponseUnrecognized}, + {name: "redirect without cookie", response: htmlLoginResponse(302, nil), reason: site.LoginResponseUnrecognized}, + {name: "failure text on a redirect", response: htmlLoginResponse(302, loginFailedPage()), reason: site.LoginResponseUnrecognized}, + {name: "server error with cookie", response: htmlLoginResponse(500, nil), + cookies: []httpguard.SessionCookie{httpguard.NewSessionCookie(loginSessionCookie, loginTestSession, time.Time{})}, reason: site.LoginResponseUnrecognized}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + body := append([]byte(nil), test.response.Body...) + test.response.Body = body + harness := newLoginHarness(t, &loginFakeClient{response: test.response, cookies: test.cookies}, nil) + result, err := harness.adapter.Login(context.Background(), loginCredentials(t, test.code), 7) + var stopped *site.LoginError + if !errors.As(err, &stopped) || stopped.Reason != test.reason { + t.Fatalf("err=%v", err) + } + if (stopped.AttemptsRemaining == nil) != (test.remaining == nil) || (test.remaining != nil && *stopped.AttemptsRemaining != *test.remaining) { + t.Fatalf("attempts remaining=%v want %v", stopped.AttemptsRemaining, test.remaining) + } + if harness.login.calls != 1 || len(harness.cookies) != 1 || harness.verify.requests != 0 || len(harness.sleeps) != 0 { + t.Fatalf("login calls=%d clients=%d verify=%d sleeps=%d", harness.login.calls, len(harness.cookies), harness.verify.requests, len(harness.sleeps)) + } + if result.Session != (site.Credential{}) || result.RequestsAttempted != 1 { + t.Fatalf("result requests=%d", result.RequestsAttempted) + } + if strings.Trim(string(body), "\x00") != "" { + t.Fatal("login response body was retained instead of cleared") + } + assertNoLoginSecrets(t, err, result) + }) + } +} + +func TestLoginRequiresTheVerificationReadToNameTheSameAccount(t *testing.T) { + tests := []struct { + name string + page []byte + err error + }{ + {name: "other account", page: accountPage("OtherUser", "1")}, + {name: "unrecognized page", page: []byte(`maintenance`)}, + {name: "read failed", err: fmt.Errorf("site request failed")}, + {name: "login redirect", err: &httpguard.RedirectError{ID: loginRedirectID}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + harness := newLoginHarness(t, issuedLoginClient(time.Time{}), test.page) + harness.verify.err = test.err + result, err := harness.adapter.Login(context.Background(), loginCredentials(t, ""), 7) + var stopped *site.LoginError + if !errors.As(err, &stopped) || stopped.Reason != site.LoginSessionUnverified || stopped.AttemptsRemaining != nil { + t.Fatalf("err=%v", err) + } + if result.Session != (site.Credential{}) || result.Username != "" || result.RequestsAttempted != 2 || harness.verify.requests != 1 { + t.Fatalf("result username=%q requests=%d verify=%d", result.Username, result.RequestsAttempted, harness.verify.requests) + } + assertNoLoginSecrets(t, err, result) + }) + } + harness := newLoginHarness(t, issuedLoginClient(time.Time{}), accountPage(strings.ToLower(loginTestUser), "1")) + if result, err := harness.adapter.Login(context.Background(), loginCredentials(t, ""), 7); err != nil || result.Username != strings.ToLower(loginTestUser) { + t.Fatalf("case-insensitive username: username=%q err=%v", result.Username, err) + } +} + +func TestLoginRejectsInvalidInputsBeforeAnyRequest(t *testing.T) { + harness := newLoginHarness(t, issuedLoginClient(time.Time{}), nil) + for _, test := range []struct { + code string + days int + }{ + {days: 0}, {days: 2}, {days: 365}, {code: "12345", days: 7}, {code: "1234567", days: 7}, + } { + if _, err := harness.adapter.Login(context.Background(), loginCredentials(t, test.code), test.days); err == nil { + t.Fatalf("code=%q days=%d accepted", test.code, test.days) + } + } + if _, err := harness.adapter.Login(context.Background(), site.LoginCredentials{}, 7); err == nil { + t.Fatal("empty credentials accepted") + } + canceled, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := harness.adapter.Login(canceled, loginCredentials(t, ""), 7); !errors.Is(err, context.Canceled) { + t.Fatalf("canceled err=%v", err) + } + if len(harness.cookies) != 0 || harness.login.calls != 0 { + t.Fatalf("clients=%d calls=%d", len(harness.cookies), harness.login.calls) + } +} + +func TestLoginTransportFailureIsNotRetried(t *testing.T) { + harness := newLoginHarness(t, &loginFakeClient{err: fmt.Errorf("site request failed"), response: httpguard.StrictResponse{Body: twoFactorPage()}}, nil) + result, err := harness.adapter.Login(context.Background(), loginCredentials(t, "123456"), 7) + var stopped *site.LoginError + if !errors.As(err, &stopped) || stopped.Reason != site.LoginRequestFailed || stopped.AttemptsRemaining != nil || + harness.login.calls != 1 || harness.login.closeCalls != 1 || result.RequestsAttempted != 1 || harness.verify.requests != 0 { + t.Fatalf("err=%v calls=%d requests=%d", err, harness.login.calls, result.RequestsAttempted) + } + assertNoLoginSecrets(t, err, result) + + for _, test := range []struct { + postErr error + want error + }{ + {postErr: fmt.Errorf("site request canceled: %w", context.DeadlineExceeded), want: context.DeadlineExceeded}, + {postErr: fmt.Errorf("site request canceled: %w", context.Canceled), want: context.Canceled}, + {postErr: fmt.Errorf("site request failed: %w", httpguard.ErrBlockedAddress), want: site.ErrAddressBlocked}, + } { + harness = newLoginHarness(t, &loginFakeClient{err: test.postErr}, nil) + if _, err := harness.adapter.Login(context.Background(), loginCredentials(t, ""), 7); !errors.Is(err, test.want) || errors.As(err, &stopped) || harness.login.calls != 1 { + t.Fatalf("post err %v became %v", test.postErr, err) + } + } + + harness = newLoginHarness(t, issuedLoginClient(time.Time{}), nil) + harness.factoryErr = fmt.Errorf("site URL must be an HTTPS location") + if _, err := harness.adapter.Login(context.Background(), loginCredentials(t, ""), 7); err == nil || harness.login.calls != 0 { + t.Fatalf("factory err=%v calls=%d", err, harness.login.calls) + } + + readOnly := New("") + readOnly.newClient = func(string, string, time.Duration) (guardedClient, error) { return &accountFakeClient{}, nil } + if _, err := readOnly.Login(context.Background(), loginCredentials(t, ""), 7); err == nil || !strings.Contains(err.Error(), "login client") { + t.Fatalf("client without login port err=%v", err) + } +} + +func TestLoginPauseHonorsCancellation(t *testing.T) { + adapter := New("") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := adapter.pause(ctx, time.Hour); !errors.Is(err, context.Canceled) { + t.Fatalf("pause err=%v", err) + } + if err := adapter.pause(context.Background(), time.Millisecond); err != nil { + t.Fatalf("pause err=%v", err) + } +}