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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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` |
Expand Down Expand Up @@ -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:

Expand Down
24 changes: 23 additions & 1 deletion docs/ADDING_A_SITE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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

Expand Down
7 changes: 7 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions docs/AUTOMATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,17 @@ 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
strict JSON: unknown, duplicate, or missing fields are rejected.
- 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.
Expand All @@ -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
Expand Down
5 changes: 5 additions & 0 deletions docs/FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions docs/THREAT_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
62 changes: 55 additions & 7 deletions docs/TJUPT_ADAPTER.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
48 changes: 48 additions & 0 deletions docs/guide/sites.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 12 additions & 2 deletions internal/cli/reconcile_credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -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('{') {
Expand Down Expand Up @@ -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
}
Expand Down
Loading
Loading